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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
//! Traversable node definition

#[cfg(feature = "async")]
mod r#async;
#[cfg(feature = "async")]
pub use r#async::*;

#[cfg(not(feature = "async"))]
mod sync;
#[cfg(not(feature = "async"))]
pub use sync::*;

mod macros {
    #[macro_export]
    macro_rules! node {
        ($value:expr $(,$($children:expr),*)?) => (
            Node {
                value: $value,
                children: vec![ $($($children),*)? ]
            }
        )
    }
}

/// Represents the minimum unit in a tree, containing a value of type T and all
/// those nodes children of the node itself, if any.
#[derive(Debug)]
pub struct Node<T> {
    value: T,
    children: Vec<Node<T>>,
}

impl<T> Node<T> {
    pub fn new(value: T) -> Self {
        Node {
            value,
            children: vec![],
        }
    }

    /// Returns a immutable reference to  node's value.
    pub fn value(&self) -> &T {
        &self.value
    }

    /// Sets the given value as the Node's one.
    pub fn set_value(&mut self, value: T) {
        self.value = value;
    }

    /// Returns a mutable reference to node's value.
    pub fn value_mut(&mut self) -> &mut T {
        &mut self.value
    }

    /// Returns an immutable slice of all node's children.
    pub fn children(&self) -> &[Node<T>] {
        &self.children
    }

    /// Returns a mutable slice of all node's children.
    pub fn children_mut(&mut self) -> &mut [Node<T>] {
        self.children.as_mut()
    }

    /// Adds a new child to the node and returns its total number of children.
    pub fn add_child(&mut self, child: Node<T>) -> usize {
        self.children.push(child);
        self.children.len()
    }

    /// Removes the children located at the given index and returns it, if any.
    pub fn remove_child(&mut self, index: usize) -> Option<Node<T>> {
        (index < self.children.len()).then_some(self.children.remove(index))
    }

    /// Returns the total of direct descendants (children) the node has.
    pub fn children_len(&self) -> usize {
        self.children.len()
    }

    /// Returns the number of descendants the node has. This method return 0 if, and only if,
    /// the node has no children.
    pub fn size(&self) -> usize {
        self.children
            .iter()
            .fold(self.children.len(), |len, node| -> usize {
                len.saturating_add(node.size())
            })
    }

    /// Returns the length of the longest branch in the tree rooted by self. Also known as the
    /// height of the tree. This method returns 1 if, and only if, the node has no children.
    pub fn height(&self) -> usize {
        self.children
            .iter()
            .map(|node| node.height())
            .max()
            .unwrap_or_default()
            .saturating_add(1)
    }
}

impl<T: Clone> Clone for Node<T> {
    fn clone(&self) -> Self {
        Self {
            value: self.value.clone(),
            children: self.children.clone(),
        }
    }
}

impl<T: PartialEq> PartialEq for Node<T> {
    fn eq(&self, other: &Self) -> bool {
        self.value == other.value && self.children == other.children
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_node_new() {
        let root = Node::new(42);
        assert_eq!(root.value(), &42);
        assert_eq!(root.children_len(), 0);
    }

    #[test]
    fn test_node_value_mut() {
        let mut root = Node::new(42);
        assert_eq!(root.value(), &42);

        (*root.value_mut()) = 123;
        assert_eq!(root.value(), &123);
    }

    #[test]
    fn test_node_add_child() {
        let mut root = node!(10);
        root.add_child(node!(20));
        root.add_child(node!(30));

        assert_eq!(root.children_len(), 2);
    }

    #[test]
    fn test_node_children_mut() {
        let mut root = node!(10, node!(20), node!(30));
        root.children_mut().swap(0, 1);
        assert_eq!(root, node!(10, node!(30), node!(20)));
    }

    #[test]
    fn test_node_remove_child() {
        let mut root = node!(10, node!(20), node!(30));
        let removed = root.remove_child(0);
        assert_eq!(removed.unwrap().value(), &20);
        assert_eq!(root.children_len(), 1);
    }

    #[test]
    fn test_node_size() {
        let root = node!(10, node!(20, node!(40)), node!(30, node!(50), node!(60)));
        assert_eq!(root.size(), 5);
    }

    #[test]
    fn test_node_height() {
        let root = node!(10, node!(20, node!(40)), node!(30, node!(50), node!(60)));
        assert_eq!(root.height(), 3);
    }

    #[test]
    fn test_node_copy() {
        let original = node!(10, node!(20), node!(30));
        let mut copy = original.clone();

        assert_eq!(copy, original);

        copy.remove_child(0);
        assert_ne!(copy, original);
    }
}