1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
use super::*;
use bitstring::BitString;
use std::option::Option;

#[derive(Clone, Copy, PartialEq, Eq)]
enum Direction {
	Left,
	Right,
	Up,
}
use self::Direction::*;

/// Iterate over tree
pub struct Iter<'a, S: BitString + 'a, V: 'a> {
	stack: Vec<(Direction, &'a Node<S, V>)>,
}

impl<'a, S: BitString + Clone, V> Iter<'a, S, V> {
	/// new iterator
	pub fn new(tree: &'a RadixMap<S, V>) -> Self {
		match tree.root() {
			None => Iter { stack: Vec::new() },
			Some(node) => Iter {
				stack: vec![(Left, node)],
			},
		}
	}
}

impl<'a, S: BitString + Clone, V> Iterator for Iter<'a, S, V> {
	type Item = (&'a S, &'a V);

	fn next(&mut self) -> Option<Self::Item> {
		if self.stack.is_empty() {
			return None;
		}

		// go up in tree from last visited node
		while Up == self.stack[self.stack.len() - 1].0 {
			if 1 == self.stack.len() {
				self.stack.clear();
				return None;
			}

			self.stack.pop();
			// stack cannot be empty yet!
			debug_assert!(!self.stack.is_empty());
		}

		loop {
			let top = self.stack.len() - 1;
			let (dir, node) = self.stack[top];

			debug_assert!(!self.stack.is_empty());
			// go down in tree to next node
			match dir {
				Left => match *node {
					Node::InnerNode(ref inner) => {
						self.stack[top].0 = Right;
						self.stack.push((Left, inner.left()));
					},
					Node::Leaf(ref leaf) => {
						self.stack[top].0 = Up;
						return Some((&leaf.key, &leaf.value));
					},
				},
				Right => match *node {
					Node::InnerNode(ref inner) => {
						self.stack[top].0 = Up;
						self.stack.push((Left, inner.right()));
					},
					Node::Leaf(_) => unreachable!(),
				},
				Up => unreachable!(),
			}
		}
	}
}