use crate::tree::RadixNode;
pub struct LeavesIterator<'a, T> {
stack: Vec<(&'a RadixNode<T>, usize, Vec<u8>)>,
}
impl<'a, T> LeavesIterator<'a, T> {
pub(crate) fn new(root: &'a RadixNode<T>) -> Self {
let mut iterator = Self { stack: Vec::new() };
iterator.stack.push((root, 0, Vec::new()));
iterator
}
}
impl<'a, T> Iterator for LeavesIterator<'a, T> {
type Item = (Vec<u8>, &'a T);
fn next(&mut self) -> Option<Self::Item> {
loop {
let (node, child_index, current_key) = self.stack.pop()?;
if child_index == 0 {
if let Some(ref value) = node.value {
if node.children.is_empty() {
return Some((current_key.clone(), value));
}
}
if !node.children.is_empty() {
self.stack.push((node, 1, current_key));
}
continue;
}
let current_child_idx = child_index - 1;
if current_child_idx < node.children.len() {
if current_child_idx + 1 < node.children.len() {
self.stack
.push((node, child_index + 1, current_key.clone()));
}
let (_, child) = &node.children[current_child_idx];
let mut child_key = current_key;
child_key.extend_from_slice(&child.key);
self.stack.push((child, 0, child_key));
}
}
}
}