about summary refs log tree commit diff stats
path: root/pkgs/by-name/lf/lf-make-map/src/mapping/map_tree/iterator.rs
blob: 4364bb2b29396775e019edc8164a57654c08b8ef (plain) (blame)
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
use crate::mapping::MapKey;

use super::{MappingTree, Node, NodeValue};

pub struct MappingTreeIterator {
    children: Vec<(Vec<MapKey>, String)>,
}

impl MappingTreeIterator {
    pub fn new(tree: &MappingTree, ignore_extendable: bool) -> Self {
        let children = extract_child(vec![], &tree.root, ignore_extendable);

        Self { children }
    }
}

fn extract_child(
    current_key: Vec<MapKey>,
    node: &Node,
    ignore_extendable: bool,
) -> Vec<(Vec<MapKey>, String)> {
    match &node.value {
        NodeValue::Parent { children } => children
            .iter()
            .map(|(key, value)| {
                let mut new_key = current_key.clone();
                new_key.push(key.to_owned());

                extract_child(new_key, value, ignore_extendable)
            })
            .flatten()
            .collect(),
        NodeValue::Child { path, extandable } => {
            if ignore_extendable {
                vec![(current_key, path.to_string())]
            } else {
                if *extandable {
                    vec![(current_key, path.to_string())]
                } else {
                    vec![]
                }
            }
        }
    }
}

impl Iterator for MappingTreeIterator {
    type Item = (Vec<MapKey>, String);

    fn next(&mut self) -> Option<Self::Item> {
        self.children.pop()
    }
}