hff_core/read/
depth_first_iter.rs

1use super::{Hff, TableView};
2use std::fmt::Debug;
3
4/// A depth first iterator over hff content.
5pub struct DepthFirstIter<'a, T: Debug> {
6    /// The hff structure we are following.
7    hff: &'a Hff<T>,
8    /// The current index of iteration.
9    index: usize,
10    /// Stack of expected siblings at each depth.
11    count: Vec<usize>,
12}
13
14impl<'a, T: Debug> DepthFirstIter<'a, T> {
15    /// Create a depth first iterator over tables in the tree.
16    pub fn new(hff: &'a Hff<T>) -> DepthFirstIter<'a, T> {
17        Self {
18            hff,
19            index: 0,
20            count: vec![],
21        }
22    }
23}
24
25impl<'a, T: Debug> Iterator for DepthFirstIter<'a, T> {
26    // Depth and table view.
27    type Item = (usize, TableView<'a, T>);
28
29    fn next(&mut self) -> Option<Self::Item> {
30        let tables = self.hff.tables_array();
31
32        if self.index < tables.len() {
33            // We have more data.
34            let table = &tables[self.index];
35
36            // Remove stack entries which have expired.
37            while let Some(top) = self.count.pop() {
38                if top > 0 {
39                    self.count.push(top - 1);
40                    break;
41                }
42            }
43
44            // Store the current depth before adding children.
45            let depth = self.count.len();
46
47            // If the table has children, add to the stack.
48            if table.child_count() > 0 {
49                self.count.push(table.child_count() as usize);
50            }
51
52            let view = TableView::new(self.hff, self.index);
53            self.index += 1;
54
55            Some((depth, view))
56        } else {
57            // We're done.
58            None
59        }
60    }
61}