From 84822ec6452e2ff7e0389cf99e72c33f29fb3d2d Mon Sep 17 00:00:00 2001 From: Tassilo Horn Date: Wed, 13 Jan 2021 16:33:03 +0100 Subject: [PATCH] Make it compile and work --- src/lib.rs | 57 +++++++++++++++++++++++++++++++++++++++--------------- 1 file changed, 41 insertions(+), 16 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 1569f1a..d9d273b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -108,29 +108,36 @@ pub struct Node { } impl Node { - fn add_children<'a>(&'a self, v: &'a mut Vec<&'a Node>) { - for n in self.nodes.iter() { - v.push(&n); - n.add_children(v); - } - } - - fn iter(&self) -> NodeIter { - let mut v = vec![self]; - self.add_children(&mut v); - NodeIter { stack: v } + fn iter(&self) -> PreOrderNodeIter { + PreOrderNodeIter::new(self) } } -struct NodeIter<'a> { +struct PreOrderNodeIter<'a> { stack: Vec<&'a Node>, } -impl<'a> Iterator for NodeIter<'a> { +impl<'a> PreOrderNodeIter<'a> { + fn new(node: &'a Node) -> PreOrderNodeIter { + PreOrderNodeIter { stack: vec![node] } + } +} + +impl<'a> Iterator for PreOrderNodeIter<'a> { type Item = &'a Node; - fn next(&mut self) -> Option<::Item> { - self.stack.pop() + fn next(&mut self) -> Option { + if let Some(node) = self.stack.pop() { + for n in &node.nodes { + self.stack.push(&n); + } + for n in &node.floating_nodes { + self.stack.push(&n); + } + Some(node) + } else { + None + } } } @@ -163,7 +170,7 @@ pub struct Con<'a> { impl<'a> std::fmt::Display for Con<'a> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> { - write!(f, "{} {}", self.name, self.app_id.unwrap_or("")) + write!(f, "{} — {}", self.app_id.unwrap_or(""), self.name) } } @@ -187,3 +194,21 @@ pub fn get_cons<'a>(tree: &'a Node) -> Vec> { } v } + +#[test] +fn test_get_cons() { + let tree = get_tree(); + + println!("Those IDs are in get_tree():"); + for n in tree.iter() { + println!(" id: {}", n.id); + } + + let cons = get_cons(&tree); + + println!("There are {} cons.", cons.len()); + + for c in cons { + println!("{}", c); + } +}