simple_tree/
lib.rs

1use std::collections::{BTreeSet};
2
3
4/// An ID that stores an index and a version
5/// `index` is used to retrieve the data from the internal tree arrays
6/// `version` allows reuse of previous indexes that have been deleted
7#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
8pub struct NodeID {
9    index: usize,
10    version: usize,
11}
12
13/// Stores all data and relationships between nodes
14#[derive(Clone, PartialEq, Eq)]
15pub struct Tree<T: Clone> {
16    roots: Vec<NodeID>,
17    parents: Vec<Option<NodeID>>,
18    children: Vec<Vec<NodeID>>,
19    data: Vec<Option<T>>,
20    versions: Vec<usize>,
21    empty: BTreeSet<usize>,
22}
23
24/// Used internally to keep track of iterator position
25struct IterStack<'a> {
26    group: &'a Vec<NodeID>,
27    next_index: usize,
28}
29
30/// For iterating over the tree, depth-first
31pub struct DepthIter<'a, T: Clone> {
32    tree: &'a Tree<T>,
33    stacks: Vec<IterStack<'a>>,
34}
35
36
37/// For iterating over the tree, depth-first
38pub struct BreadthIter<'a, T: Clone> {
39    tree: &'a Tree<T>,
40    depth: usize,
41    current: Vec<NodeID>,
42    next: Vec<NodeID>,
43    next_index: usize,
44}
45
46
47impl<T: Clone> Tree<T> {
48    /// Returns a new empty tree
49    pub fn new() -> Self {
50        Self {
51            roots: vec![],
52            parents: vec![],
53            children: vec![],
54            data: vec![],
55            versions: vec![],
56            empty: Default::default()
57        }
58    }
59
60    /// Check if a `node id` points to a valid, non-deleted node in the tree.
61    /// Returns true if the node id is valid.
62    /// # Arguments
63    /// * `node` - the NodeID to check
64    pub fn is_valid(&self, node: NodeID) -> bool {
65        node.index < self.data.len() && !self.empty.contains(&node.index) && self.versions[node.index] == node.version
66    }
67
68
69    /// Mark a node in the tree, and all of its children as invalid.
70    /// This allows the reuse of these indexes by other nodes created later.
71    /// Returns the number of total nodes that were deleted.
72    pub fn delete(&mut self, node: NodeID) -> usize {
73        if !self.is_valid(node) {
74            return 0;
75        }
76        let mut total = 1;
77        let ids = self.children_ids_unchecked(node).clone();
78        for child in ids {
79            total += self.delete(child);
80        }
81        if let Some(parent) = self.parents[node.index] {
82            if let Some(index) = self.children[parent.index].iter().position(|&x| x == node) {
83                self.children[parent.index].remove(index);
84            }
85        } else {
86            if let Some(index) = self.roots.iter().position(|&x| x == node) {
87                self.roots.remove(index);
88            }
89        }
90
91        self.data[node.index] = None;
92        self.parents[node.index] = None;
93        self.children[node.index].clear();
94        self.empty.insert(node.index);
95        total
96    }
97
98    /// Add a root node and return its id
99    pub fn add_root(&mut self, val: T) -> NodeID {
100        let i = NodeID{index: self.data.len(), version: 0};
101        self.data.push(Some(val));
102        self.roots.push(i);
103        self.children.push(vec![]);
104        self.parents.push(None);
105        self.versions.push(0);
106        i
107    }
108
109    /// Returns the value for a node (if it exists)
110    pub fn get(&self, node: NodeID) -> Option<&T> {
111        match self.is_valid(node) {
112            true => self.data[node.index].as_ref(),
113            false => None,
114        }
115    }
116
117    /// Returns the mutable value for a node (if it exists)
118    pub fn get_mut(&mut self, node: NodeID) -> Option<&mut T> {
119        match self.is_valid(node) {
120            true => self.data[node.index].as_mut(),
121            false => None,
122        }
123    }
124
125    /// Returns the value for a node, and panic if it doesn't exist
126    pub fn get_unchecked(&self, node: NodeID) -> &T {
127        self.data[node.index].as_ref().unwrap()
128    }
129
130    /// Returns the mutable value for a node, and panic if it doesn't exist
131    pub fn get_unchecked_mut(&mut self, node: NodeID) -> &mut T {
132        self.data[node.index].as_mut().unwrap()
133    }
134
135    /// Set the value for a node (if it already exists)
136    pub fn set(&mut self, node: NodeID, val: T) {
137        if self.is_valid(node) {
138            self.data[node.index] = Some(val);
139        }
140    }
141
142    /// Add a child to the node and return its id (if successful)
143    pub fn add_child(&mut self, node: NodeID, val: T) -> Option<NodeID> {
144        match self.is_valid(node) {
145            true => Some(self.add_child_unchecked(node, val)),
146            false => None
147        }
148    }
149
150    /// Add a child to the node and return its id.
151    /// Panics if node does not exist
152    pub fn add_child_unchecked(&mut self, node: NodeID, val: T) -> NodeID {
153        let x = match self.empty.iter().next().cloned() {
154            Some(x) => {
155                self.data[x] = Some(val);
156                self.parents[x] = Some(node);
157                let version = self.versions.get_mut(x).unwrap();
158                *version += 1;
159                self.empty.remove(&x);
160                NodeID{ index: x, version: *version }
161            },
162            _ => {
163                self.data.push(Some(val));
164                self.parents.push(Some(node));
165                self.children.push(vec![]);
166                self.versions.push(0);
167                NodeID{index: self.data.len() - 1, version: 0 }
168            },
169        };
170        self.children[node.index].push(x);
171        x
172
173    }
174
175    /// Returns the children_ids for a node
176    /// Panics if the node doesn't exist
177    pub fn children_ids_unchecked(&self, node: NodeID) -> &Vec<NodeID> {
178        &self.children[node.index]
179    }
180
181
182    /// Returns the root nodes of the tree
183    pub fn root_ids(&self) -> &Vec<NodeID> {
184        &self.roots
185    }
186
187    /// Returns the parent id for the node
188    pub fn parent_id(&self, node: NodeID) -> Option<NodeID> {
189        match self.is_valid(node) {
190            true => self.parents[node.index],
191            false => None,
192        }
193    }
194
195
196    /// Returns a depth-first iterator
197    /// This iterates a single node until a leaf is reached and then moves onto the next one
198    pub fn iter_depth(&self) -> DepthIter<T> {
199        DepthIter{
200            tree: &self,
201            stacks: vec![IterStack{group: &self.roots, next_index: 0}],
202        }
203    }
204
205    /// Returns a breadth-first iterator
206    /// This iterates an entire depth-level before moving onto the next deepest nodes
207    pub fn iter_breadth(&self) -> BreadthIter<T> {
208        BreadthIter{
209            tree: &self,
210            current: self.roots.clone(),
211            next_index: 0,
212            next: vec![],
213            depth: 0,
214        }
215    }
216
217
218    /// Returns the node sequence from a root node to the given node
219    pub fn path(&self, node: NodeID) -> Vec<NodeID> {
220        let mut path: Vec<NodeID> = vec![node];
221        let mut cur = node;
222        loop {
223            match self.parents[cur.index] {
224                Some(x) => {
225                    path.push(x);
226                    cur = x;
227                },
228                None => break,
229            }
230        }
231        path.reverse();
232        path
233    }
234
235    /// Returns references to values in the node sequence from a root node to the given node
236    pub fn path_values_ref(&self, node: NodeID) -> Vec<&T> {
237        self.path(node).iter().map(|&x| self.get_unchecked(x)).collect::<Vec<_>>()
238    }
239
240    /// Returns cloned values in the node sequence from a root node to the given node
241    pub fn path_values(&self, node: NodeID) -> Vec<T> {
242        self
243            .path(node)
244            .into_iter()
245            .map(|x| self.get_unchecked(x).clone())
246            .collect()
247    }
248}
249
250
251/// A node of the tree
252#[derive(Debug, Eq, PartialEq)]
253pub struct Node<'a, T> {
254    pub id: NodeID,
255    pub value: &'a T,
256    pub depth: usize,
257}
258
259
260/// Implement depth-first iteration
261impl<'a, T: Clone> Iterator for DepthIter<'a, T> {
262    type Item = Node<'a, T>;
263
264    fn next(&mut self) -> Option<Self::Item> {
265        loop {
266            if self.stacks.is_empty(){
267                return None;
268            }
269            if {
270                let stack = self.stacks.last().unwrap();
271                stack.next_index >= stack.group.len()
272            }{
273                // Finished checking this group - pop up a level and go to next one
274                self.stacks.pop();
275                if self.stacks.is_empty() {
276                    return None;
277                }
278                let stack = self.stacks.last_mut().unwrap();
279                stack.next_index += 1;
280            } else {
281                // return value at next_index:
282                // Increment stack to next sibling
283                let depth = self.stacks.len() - 1;
284                let mut stack = self.stacks.last_mut().unwrap();
285                let node = stack.group[stack.next_index];
286                let children = self.tree.children_ids_unchecked(node);
287                if !children.is_empty() {
288                    self.stacks.push(IterStack{
289                        next_index: 0,
290                        group: children,
291                    })
292                } else {
293                    stack.next_index += 1;
294                }
295                return Some(Self::Item {
296                    id: node,
297                    value: self.tree.get_unchecked(node),
298                    depth,
299                });
300            }
301        }
302    }
303}
304
305
306
307/// Implement breadth-first iteration
308impl<'a, T: Clone> Iterator for BreadthIter<'a, T> {
309    type Item = Node<'a, T>;
310    fn next(&mut self) -> Option<Self::Item> {
311        loop {
312            if self.current.is_empty() {
313                return None;
314            }
315            if self.next_index >= self.current.len() {
316                self.next_index = 0;
317                self.current = self.next.clone();
318                self.next.clear();
319                self.depth += 1;
320                continue;
321            }
322
323            let node = self.current[self.next_index];
324            let children = self.tree.children_ids_unchecked(node);
325            self.next.append(&mut children.clone());
326            self.next_index += 1;
327
328            return Some(Self::Item{
329                value: self.tree.get_unchecked(node),
330                depth: self.depth,
331                id: node,
332            });
333        }
334    }
335}
336
337
338#[cfg(test)]
339mod tests {
340    use super::*;
341
342    #[test]
343    fn depth_first_iteration() {
344        let mut tree: Tree<i32> = Tree::new();
345        let root = tree.add_root(0);
346        let child1 = tree.add_child_unchecked(root, 1);
347        let _child2 = tree.add_child_unchecked(root, 2);
348        let _child1_1 = tree.add_child_unchecked(child1, 11);
349
350        let expected: Vec<(i32, usize)> = vec![(0, 0), (1, 1), (11, 2), (2, 1)];
351        let real = tree.iter_depth().map(|x|{
352            (*x.value, x.depth)
353        }).collect::<Vec<_>>();
354        assert_eq!(real, expected);
355    }
356
357    #[test]
358    fn breadth_first_iteration() {
359        let mut tree: Tree<i32> = Tree::new();
360        let root = tree.add_root(0);
361        let child1 = tree.add_child_unchecked(root, 1);
362        let _child2 = tree.add_child_unchecked(root, 2);
363        let _child1_1 = tree.add_child_unchecked(child1, 11);
364
365        let expected: Vec<(i32, usize)> = vec![(0, 0), (1, 1), (2, 1), (11, 2)];
366        let real = tree.iter_breadth().map(|x|{
367            (*x.value, x.depth)
368        }).collect::<Vec<_>>();
369        assert_eq!(real, expected);
370    }
371}