Skip to content

Commit

Permalink
Add AncestorIterator by jgraham
Browse files Browse the repository at this point in the history
  • Loading branch information
ILyoan committed Sep 10, 2013
1 parent bcd7c0b commit 47c5279
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions src/components/util/tree.rs
Expand Up @@ -42,6 +42,23 @@ impl<Node, Ref: TreeNodeRef<Node>> Iterator<Ref> for ChildIterator<Ref> {
}
}

pub struct AncestorIterator<Ref> {
priv current: Option<Ref>,
}

impl<Node, Ref: TreeNodeRef<Node>> Iterator<Ref> for AncestorIterator<Ref> {
fn next(&mut self) -> Option<Ref> {
if self.current.is_none() {
return None;
}

// FIXME: Do we need two clones here?
let x = self.current.get_ref().clone();
self.current = x.with_base(|n| TreeNodeRef::<Node>::parent_node(n));
Some(x.clone())
}
}

// FIXME: Do this without precomputing a vector of refs.
// Easy for preorder; harder for postorder.
pub struct TreeIterator<Ref> {
Expand Down Expand Up @@ -196,6 +213,13 @@ pub trait TreeNodeRef<Node>: Clone {
}
}

/// Iterates over all ancestors of this node.
fn ancestors(&self) -> AncestorIterator<Self> {
AncestorIterator {
current: self.with_base(|n| get!(n, parent_node)),
}
}

/// Iterates over this node and all its descendants, in preorder.
fn traverse_preorder(&self) -> TreeIterator<Self> {
self.traverse_preorder_prune(|_| false)
Expand Down

0 comments on commit 47c5279

Please sign in to comment.