radiate_extensions/architects/node_collections/
tree.rs

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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
use radiate::Valid;

use crate::{
    node_collections, schema::collection_type::CollectionType, NodeCollection, NodeFactory,
    NodeRepairs,
};
use crate::node::Node;
use super::BreadthFirstIterator;

#[derive(Clone, PartialEq, Default)]
pub struct Tree<T>
where
    T: Clone + PartialEq,
{
    pub nodes: Vec<Node<T>>,
}

impl<T> Tree<T>
where
    T: Clone + PartialEq + Default,
{
    pub fn new(nodes: Vec<Node<T>>) -> Self {
        Tree { nodes }
    }

    pub fn sub_tree(&self, index: usize) -> Self {
        let nodes = BreadthFirstIterator::new(&self.nodes, index)
            .collect::<Vec<&Node<T>>>();

        Tree::new(node_collections::reindex(0, nodes.as_slice()))
    }
}

impl<T> NodeCollection<T> for Tree<T>
where
    T: Clone + PartialEq + Default,
{
    fn from_nodes(nodes: Vec<Node<T>>) -> Self {
        Self { nodes }
    }

    fn get(&self, index: usize) -> &Node<T> {
        self.nodes.get(index).unwrap_or_else(|| {
            panic!(
                "Node index {} out of bounds for tree with {} nodes",
                index,
                self.nodes.len()
            )
        })
    }

    fn get_mut(&mut self, index: usize) -> &mut Node<T> {
        let length = self.nodes.len();
        self.nodes.get_mut(index).unwrap_or_else(|| {
            panic!(
                "Node index {} out of bounds for tree with {} nodes",
                index, length
            )
        })
    }

    fn get_nodes(&self) -> &[Node<T>] {
        &self.nodes
    }

    fn get_nodes_mut(&mut self) -> &mut [Node<T>] {
        &mut self.nodes
    }
}

impl<T> NodeRepairs<T> for Tree<T>
where
    T: Clone + PartialEq + Default,
{
    fn repair(&mut self, _: Option<&NodeFactory<T>>) -> Self {
        let mut collection = self.clone();

        for node in collection.iter_mut() {
            node.collection_type = Some(CollectionType::Tree);
        }

        collection
    }
}

impl<T> Valid for Tree<T>
where
    T: Clone + PartialEq + Default,
{
    fn is_valid(&self) -> bool {
        self.nodes.iter().all(|node| node.is_valid())
    }
}

impl<T> std::fmt::Debug for Tree<T>
where
    T: Clone + PartialEq + Default + std::fmt::Debug,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Tree {{\n")?;
        for node in self.get_nodes() {
            write!(f, "  {:?},\n", node)?;
        }
        write!(f, "}}")
    }
}