Skip to content

Commit

Permalink
perf: use more iterators
Browse files Browse the repository at this point in the history
  • Loading branch information
EdJoPaTo committed Jan 30, 2022
1 parent 4cf8992 commit 2941d7c
Show file tree
Hide file tree
Showing 3 changed files with 75 additions and 83 deletions.
40 changes: 18 additions & 22 deletions src/interactive/ui/history.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,13 +89,14 @@ struct GraphDataPoints {
}

impl GraphDataPoints {
fn parse_from_datapoints(entries: &[DataPoint]) -> Option<Self> {
let mut data = Vec::new();
for entry in entries {
if let Some(point) = GraphDataPoint::parse_from_datapoint(entry) {
data.push(point);
}
}
fn parse_from_datapoints<'a, I>(entries: I) -> Option<Self>
where
I: IntoIterator<Item = &'a DataPoint>,
{
let data = entries
.into_iter()
.filter_map(GraphDataPoint::parse_from_datapoint)
.collect::<Vec<_>>();

if data.len() < 2 {
None
Expand Down Expand Up @@ -146,18 +147,15 @@ impl GraphDataPoints {
}
}

pub fn draw<B>(
f: &mut Frame<B>,
area: Rect,
topic_history: &[HistoryEntry],
json_selector: &[usize],
) where
pub fn draw<'h, B, H>(f: &mut Frame<B>, area: Rect, topic_history: H, json_selector: &[usize])
where
B: Backend,
H: IntoIterator<Item = &'h HistoryEntry>,
{
let mut data = Vec::new();
for entry in topic_history {
data.push(DataPoint::parse_from_history_entry(entry, json_selector));
}
let data = topic_history
.into_iter()
.map(|entry| DataPoint::parse_from_history_entry(entry, json_selector))
.collect::<Vec<_>>();

let table_area = GraphDataPoints::parse_from_datapoints(&data).map_or(area, |points| {
let chunks = Layout::default()
Expand Down Expand Up @@ -209,17 +207,15 @@ where
}
title += ")";

let mut rows_content: Vec<Vec<String>> = Vec::new();
for entry in topic_history {
let rows = topic_history.iter().map(|entry| {
let time = match entry.time {
PacketTime::Retained => String::from(format::TIMESTAMP_RETAINED),
PacketTime::Local(time) => time.format(format::TIMESTAMP_FORMAT).to_string(),
};
let qos = format::qos(entry.qos);
let value = entry.value.clone().unwrap_or_else(|err| err);
rows_content.push(vec![time, qos, value]);
}
let rows = rows_content.iter().map(|cells| Row::new(cells.clone()));
Row::new(vec![time, qos, value])
});

let t = Table::new(rows)
.block(Block::default().borders(Borders::ALL).title(title))
Expand Down
10 changes: 5 additions & 5 deletions src/mqtt_history.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,14 +105,14 @@ impl MqttHistory {
.history
.lock()
.map_err(|err| anyhow::anyhow!("failed to aquire lock of mqtt history: {}", err))?;
let mut result = Vec::new();
for (topic, history) in history.iter() {
result.push(TopicMessagesLastPayload {
let mut result = history
.iter()
.map(|(topic, history)| TopicMessagesLastPayload {
topic: topic.clone(),
messages: history.len(),
last_payload: history.last().unwrap().packet.payload.to_vec(),
});
}
})
.collect::<Vec<_>>();
result.sort_by_key(|o| o.topic.clone());
Ok(result)
}
Expand Down
108 changes: 52 additions & 56 deletions src/topic_view.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,25 +19,23 @@ impl TopicTreeEntry {
}

pub fn topics_below(&self) -> usize {
let mut counter = 0;
for below in &self.entries_below {
if below.messages > 0 {
counter += 1;
}

counter += below.topics_below();
}

counter
self.entries_below
.iter()
.map(|below| {
let has_messages = if below.messages > 0 { 1 } else { 0 };
let topics_below = below.topics_below();
has_messages + topics_below
})
.sum()
}

pub fn messages_below(&self) -> usize {
let mut counter = self.messages;
for below in &self.entries_below {
counter += below.messages_below();
}

counter
let below = self
.entries_below
.iter()
.map(Self::messages_below)
.sum::<usize>();
self.messages + below
}
}

Expand All @@ -53,26 +51,22 @@ where
let mut keys = map.keys().copied().collect::<Vec<_>>();
keys.sort_unstable();

let roots = topic::get_all_roots(keys.clone());
let topics = topic::get_all_with_parents(keys);

let mut result = Vec::new();
for root in roots {
result.push(build_recursive(&map, &topics, root));
}

result
let topics = topic::get_all_with_parents(keys.clone());
topic::get_all_roots(keys)
.iter()
.map(|root| build_recursive(&map, &topics, root))
.collect()
}

fn build_recursive(
map: &HashMap<&str, &TopicMessagesLastPayload>,
all_topics: &[&str],
topic: &str,
) -> TopicTreeEntry {
let mut entries_below: Vec<TopicTreeEntry> = Vec::new();
for child in topic::get_direct_children(topic, all_topics) {
entries_below.push(build_recursive(map, all_topics, child));
}
let entries_below = topic::get_direct_children(topic, all_topics)
.iter()
.map(|child| build_recursive(map, all_topics, child))
.collect();

let info = map.get(topic);

Expand Down Expand Up @@ -101,33 +95,35 @@ pub fn get_identifier_of_topic(
Some(identifier)
}

pub fn tree_items_from_tmlp_tree(entries: &[TopicTreeEntry]) -> Vec<TreeItem> {
let mut result = Vec::new();

for entry in entries {
let children = tree_items_from_tmlp_tree(&entry.entries_below);

let meta = entry.last_payload.as_ref().map_or_else(
|| {
format!(
"({} topics, {} messages)",
entry.topics_below(),
entry.messages_below()
)
},
|payload| format!("= {}", format::payload_as_utf8(payload.clone())),
);

let text = vec![Spans::from(vec![
Span::styled(entry.leaf(), Style::default().add_modifier(Modifier::BOLD)),
Span::raw(" "),
Span::styled(meta, Style::default().fg(Color::DarkGray)),
])];

result.push(TreeItem::new(text, children));
}

result
pub fn tree_items_from_tmlp_tree<'a, I>(entries: I) -> Vec<TreeItem<'a>>
where
I: IntoIterator<Item = &'a TopicTreeEntry>,
{
entries
.into_iter()
.map(|entry| {
let children = tree_items_from_tmlp_tree(&entry.entries_below);

let meta = entry.last_payload.as_ref().map_or_else(
|| {
format!(
"({} topics, {} messages)",
entry.topics_below(),
entry.messages_below()
)
},
|payload| format!("= {}", format::payload_as_utf8(payload.clone())),
);

let text = vec![Spans::from(vec![
Span::styled(entry.leaf(), Style::default().add_modifier(Modifier::BOLD)),
Span::raw(" "),
Span::styled(meta, Style::default().fg(Color::DarkGray)),
])];

TreeItem::new(text, children)
})
.collect()
}

pub fn is_topic_opened(opened: &HashSet<String>, topic: &str) -> bool {
Expand Down

0 comments on commit 2941d7c

Please sign in to comment.