Skip to content

Commit b4a89a3

Browse files
authored
fix: Optimize the "short node list" helper used in panic messages (#490)
1 parent 93d0a72 commit b4a89a3

File tree

1 file changed

+23
-21
lines changed

1 file changed

+23
-21
lines changed

consumer/src/tree.rs

Lines changed: 23 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,8 @@
44
// the LICENSE-MIT file), at your option.
55

66
use accesskit::{FrozenNode as NodeData, NodeId, Tree as TreeData, TreeUpdate};
7-
use alloc::{format, string::String, sync::Arc, vec, vec::Vec};
7+
use alloc::{string::String, sync::Arc, vec};
8+
use core::fmt;
89
use hashbrown::{HashMap, HashSet};
910
use immutable_chunkmap::map::MapM as ChunkMap;
1011

@@ -135,10 +136,10 @@ impl State {
135136
}
136137

137138
if !pending_nodes.is_empty() {
138-
panic!("TreeUpdate includes {} nodes which are neither in the current tree nor a child of another node from the update: {}", pending_nodes.len(), short_node_list(pending_nodes.keys()));
139+
panic!("TreeUpdate includes {} nodes which are neither in the current tree nor a child of another node from the update: {}", pending_nodes.len(), ShortNodeList(&pending_nodes));
139140
}
140141
if !pending_children.is_empty() {
141-
panic!("TreeUpdate's nodes include {} children ids which are neither in the current tree nor the id of another node from the update: {}", pending_children.len(), short_node_list(pending_children.keys()));
142+
panic!("TreeUpdate's nodes include {} children ids which are neither in the current tree nor the id of another node from the update: {}", pending_children.len(), ShortNodeList(&pending_children));
142143
}
143144

144145
self.focus = update.focus;
@@ -333,24 +334,25 @@ impl Tree {
333334
}
334335
}
335336

336-
fn short_node_list<'a>(nodes: impl ExactSizeIterator<Item = &'a NodeId>) -> String {
337-
if nodes.len() > 10 {
338-
format!(
339-
"[{} ...]",
340-
nodes
341-
.take(10)
342-
.map(|id| format!("#{}", id.0))
343-
.collect::<Vec<_>>()
344-
.join(", "),
345-
)
346-
} else {
347-
format!(
348-
"[{}]",
349-
nodes
350-
.map(|id| format!("#{}", id.0))
351-
.collect::<Vec<_>>()
352-
.join(", "),
353-
)
337+
struct ShortNodeList<'a, T>(&'a HashMap<NodeId, T>);
338+
339+
impl<T> fmt::Display for ShortNodeList<'_, T> {
340+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
341+
write!(f, "[")?;
342+
let mut iter = self.0.iter();
343+
for i in 0..10 {
344+
let Some((id, _)) = iter.next() else {
345+
break;
346+
};
347+
if i != 0 {
348+
write!(f, ", ")?;
349+
}
350+
write!(f, "#{}", id.0)?;
351+
}
352+
if iter.next().is_some() {
353+
write!(f, " ...")?;
354+
}
355+
write!(f, "]")
354356
}
355357
}
356358

0 commit comments

Comments
 (0)