read_tree/
tree.rs

1//! Types for storing and exploring trees.
2
3#![deny(missing_docs)]
4
5/// An error returned when attempting to build a [`Sapling`]`<T>`.
6///
7/// The error contains the sapling that failed to build in order to return it to
8/// the caller. Otherwise the [`build`] function would drop the sapling without
9/// returning a resulting [`Tree`]`<T>`.
10///
11/// [`build`]: Sapling::build
12pub enum BuildError<T> {
13    /// The sapling is incomplete and not ready to be built.
14    ///
15    /// It is either empty or there are still unclosed nodes. Use [`pop_all`] to
16    /// close any unclosed nodes and use [`is_empty`] to check if th sapling is
17    /// empty.
18    ///
19    /// [`is_empty`]: Sapling::is_empty
20    /// [`pop_all`]: Sapling::pop_all
21    Incomplete(Sapling<T>),
22
23    /// The sapling contains more than one root node.
24    ///
25    /// When creating nodes on a sapling it is possible to [`pop`] the root node
26    /// and [`push`] a second root. Trees however must have a unique root.
27    ///
28    /// To get an iterator over the root nodes build the sapling into a
29    /// [`PolyTree`]`<T>` using [`build_polytree`].
30    ///
31    /// [`build_polytree`]: Sapling::build_polytree
32    /// [`pop`]: Sapling::pop
33    /// [`push`]: Sapling::push
34    MultipleRoots(Sapling<T>),
35}
36
37impl<T> std::fmt::Debug for BuildError<T> {
38    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
39        match self {
40            Self::Incomplete(_) => write!(f, "Incomplete"),
41            Self::MultipleRoots(_) => write!(f, "MultipleRoots"),
42        }
43    }
44}
45
46impl<T> std::fmt::Display for BuildError<T> {
47    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
48        match self {
49            Self::Incomplete(_) => write!(f, "Incomplete tree structure"),
50            Self::MultipleRoots(_) => write!(f, "Multiple roots in tree"),
51        }
52    }
53}
54
55impl<T> std::error::Error for BuildError<T> {}
56
57/// An error returned when validating a vertex slice.
58#[derive(Debug, PartialEq, Copy, Clone)]
59pub enum ValidationError {
60    /// The vertex slice is empty.
61    ///
62    /// Nodes must always have exactly one root. The buffer therefor needs to
63    /// have at least one entry.
64    Empty,
65
66    /// The vertex slice contains more than one root node.
67    ///
68    /// Nodes can only have exactly one root node.
69    MultipleRoots,
70
71    /// Some of the lengths of the vertices do not match up. Ensure a vertex
72    /// does not have more descendants than its ancestors.
73    IllegalStructure,
74}
75
76impl std::fmt::Display for ValidationError {
77    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
78        match self {
79            Self::Empty => write!(f, "Empty vertex slice"),
80            Self::MultipleRoots => write!(f, "Multiple roots in vertex slice"),
81            Self::IllegalStructure => write!(f, "Vertex with invalid length"),
82        }
83    }
84}
85
86impl std::error::Error for ValidationError {}
87
88/// An internal type that stores the payload and relationships of a node in a
89/// [`Tree`]`<T>` or [`PolyTree`]`<T>`.
90///
91/// Every node on the tree is represented by a [`Vertex`]`<T>`. The `len` field
92/// stores the number of descendants the node has; this is the number of nodes
93/// in the subtree below the node. A leaf node has length `0`.
94///
95/// Every [`Tree`]`<T>` contains a [`Vec`]`<`[`Vertex`]`<T>>` representing the
96/// trees nodes in a depth first order; meaning every vertex is followed by its
97/// first child. This makes it very easy to take a slice of the vertex buffer
98/// that represents a subtree. We expose such a slice to the user as a
99/// [`Node`]`<T>`.
100///
101/// The type implements [`Clone`] and [`Copy`] as long as the payload `T`
102/// implements the same. Supporting [`Copy`] is important to ensure
103/// [`Vec::extend_from_slice`] executes as fast as possible. This method is used
104/// by [`Sapling::push_tree`] to copy the nodes of a tree into another sapling.
105#[derive(Debug, Clone, Copy)]
106pub struct Vertex<T> {
107    len: usize,
108    data: T,
109}
110
111impl<T> Vertex<T> {
112    /// Returns a new vertex with payload `data` intending to own `len` many
113    /// descendants.
114    pub fn new(data: T, len: usize) -> Self {
115        Vertex { data, len }
116    }
117}
118
119/// A builder to construct [`Tree`]`<T>`s and [`PolyTree`]`<T>`s.
120///
121/// Saplings are the only way of creating a [`Tree`]`<T>`. New saplings are
122/// initialized empty, containing no nodes. Nodes are then added to the sapling
123/// until the tree is complete. The sapling can then be turned into a tree.
124///
125/// Nodes are added to saplings using [`push`]. Adding a new node also selects
126/// it, meaning later calls of [`push`] will attach the new node as a child to
127/// this one. To close a node once all its child nodes have been added, call
128/// [`pop`].
129///
130/// When the sapling is complete, turn it into a [`Tree`]`<T>` using [`build`].
131/// This method returns a [`Result`]`<`[`Tree`]`<T>, `[`BuildError`]`<T>>` to
132/// indicate if the sapling was built successfully. In case of an error
133/// [`BuildError`]`<T>` will contain the sapling.
134///
135/// # Examples
136///
137/// ```rust
138/// use read_tree::{Sapling, Tree};
139///
140/// fn main() -> Result<(), Box<dyn std::error::Error>> {
141///     let mut sap = Sapling::new();
142///     assert!(sap.is_empty());
143///
144///     sap.push(1); // Add a new node to the tree carrying the payload `1`.
145///     sap.push_leaf(11); // Add a child node to node `1`. This node will have no children.
146///     sap.push(12); // Add another child node to `1`. Select this node.
147///     sap.push_leaf(121); // Add leaf nodes to node `12`.
148///     sap.push_leaf(122);
149///
150///     sap.pop(); // Close node `12`.
151///     sap.pop(); // Close node `1`.
152///
153///     assert!(sap.is_ready());
154///     let _tree = sap.build()?;
155///
156///     Ok(())
157/// }
158/// ```
159///
160/// [`build`]: Sapling::build
161/// [`pop`]: Sapling::pop
162/// [`push`]: Sapling::push
163#[derive(Debug)]
164pub struct Sapling<T> {
165    path: Vec<usize>,
166    verts: Vec<Vertex<T>>,
167}
168
169impl<T> Sapling<T> {
170    /// Creates a new empty sapling.
171    ///
172    /// An empty sapling is not yet ready to be built. Add at least one node
173    /// before building it into a tree.
174    ///
175    /// # Examples
176    ///
177    /// ```rust
178    /// use read_tree::Sapling;
179    ///
180    /// let sap = Sapling::<usize>::new();
181    /// assert!(sap.is_empty());
182    /// assert!(sap.build().is_err());
183    /// ```
184    pub fn new() -> Self {
185        Sapling {
186            path: Vec::new(),
187            verts: Vec::new(),
188        }
189    }
190
191    /// Creates a new empty sapling with enough capacity to store `len` many
192    /// nodes.
193    ///
194    /// The sapling is allowed to receive more than `len` nodes; this may
195    /// however cause further memory allocations. For more information check out
196    /// [`Vec::with_capacity`].
197    ///
198    /// The optional parameter `depth` should predict the maximum depth of the
199    /// tree. If the depth is unknown use `None`. The depth should include the
200    /// root node, can however exclude leaf nodes, if the leaf nodes will be
201    /// added using [`push_leaf`]. The rule is that every call to [`push`]
202    /// increases the depth, and every call to [`pop`] decreases it. Empty
203    /// saplings start with depth `0` and methods like [`push_leaf`] do not
204    /// affect the depth. If omitted `0` will be used by default.
205    ///
206    /// [`pop`]: Sapling::pop
207    /// [`push_leaf`]: Sapling::push_leaf
208    /// [`push`]: Sapling::push
209    pub fn with_capacity(len: usize, depth: Option<usize>) -> Self {
210        Sapling {
211            path: Vec::with_capacity(depth.unwrap_or(0)),
212            verts: Vec::with_capacity(len),
213        }
214    }
215
216    /// Adds a new node with the payload `data` to the sapling.
217    ///
218    /// The new node is positioned as a child node of the currently selected
219    /// node. The selected node will be changed to be the new node until the
220    /// next call of [`pop`]. To avoid changing the selection use [`push_leaf`]
221    /// instead; note that this will make it impossible to attach child nodes to
222    /// the node, forcing it to be a leaf node.
223    ///
224    /// Nodes have to be added to the sapling in the correct oder. Once a node
225    /// has been closed using [`pop`] its subtree is finalized and can no longer
226    /// be changed.
227    ///
228    /// [`pop`]: Sapling::pop
229    /// [`push_leaf`]: Sapling::push_leaf
230    /// [`push`]: Sapling::push
231    pub fn push(&mut self, data: T) {
232        self.path.push(self.verts.len());
233        self.verts.push(Vertex { len: 0, data });
234    }
235
236    /// Adds a new leaf node with the payload `data` to the sapling.
237    ///
238    /// This method is a convenient shortcut that behaves the same as calling
239    /// [`push`] immediately followed by [`pop`].
240    ///
241    /// [`pop`]: Sapling::pop
242    /// [`push`]: Sapling::push
243    pub fn push_leaf(&mut self, data: T) {
244        self.verts.push(Vertex { len: 0, data });
245    }
246
247    /// Adds another tree to the selected node in the sapling. This operation
248    /// does not change the selected node, similar to [`push_leaf`].
249    ///
250    /// Empties `tree` in the process and returns it as an empty sapling. This
251    /// allows the caller to reuse the trees internal buffers.
252    ///
253    /// [`push_leaf`]: Sapling::push_leaf
254    pub fn push_tree(&mut self, tree: Tree<T>) -> Sapling<T> {
255        let mut sap = tree.into_sapling();
256        self.verts.append(&mut sap.verts);
257        sap.clear();
258        sap
259    }
260
261    /// Adds another poly-tree to the selected node in the sapling. This
262    /// operation does not change the selected node, similar to [`push_leaf`].
263    ///
264    /// Empties `tree` in the process and returns it as an empty sapling. This
265    /// allows the caller to reuse the trees internal buffers.
266    ///
267    /// [`push_leaf`]: Sapling::push_leaf
268    pub fn push_polytree(&mut self, tree: PolyTree<T>) -> Sapling<T> {
269        let mut sap = tree.into_sapling();
270        self.verts.append(&mut sap.verts);
271        sap.clear();
272        sap
273    }
274
275    /// Clones the contents of a node and attaches the cloned subtree to the
276    /// sapling. Requires the payload type `T` to be [`Clone`].
277    ///
278    /// If `T` implements [`Copy`], the cloning of the subtree is relatively
279    /// cheap. See [`Vec::extend_from_slice`] for more information.
280    pub fn push_node(&mut self, node: Node<T>)
281    where
282        T: Clone,
283    {
284        self.verts.extend_from_slice(node.verts);
285    }
286
287    /// Returns a reference to the payload of the selected node. Returns `None`
288    /// if no node is currently selected; this happens when the sapling is empty
289    /// or after a root node was closed.
290    ///
291    /// # Examples
292    ///
293    /// ```rust
294    /// use read_tree::Sapling;
295    ///
296    /// let mut sap = Sapling::new();
297    /// sap.push(0);
298    /// sap.push(1);
299    ///
300    /// assert_eq!(sap.peek(), Some(&1));
301    /// assert_eq!(sap.pop(), Some(&1));
302    ///
303    /// assert_eq!(sap.peek(), Some(&0));
304    /// assert_eq!(sap.pop(), Some(&0));
305    ///
306    /// assert_eq!(sap.peek(), None);
307    /// assert_eq!(sap.pop(), None);
308    /// ```
309    pub fn peek(&self) -> Option<&T> {
310        let i = *self.path.last()?;
311        Some(&self.verts[i].data)
312    }
313
314    /// Closes the selected node.
315    ///
316    /// The subtree under the selected node is complete and will be closed. From
317    /// then on new nodes will be attached to the parent of the closed node.
318    ///
319    /// Returns a reference to the payload of the closed node. Returns `None` if
320    /// no node was selected; this happens when the sapling is empty or after a
321    /// root node has been closed.
322    ///
323    /// # Examples
324    ///
325    /// ```rust
326    /// use read_tree::Sapling;
327    ///
328    /// let mut sap = Sapling::new();
329    /// sap.push(0);
330    /// assert_eq!(sap.pop(), Some(&0));
331    ///
332    /// assert!(sap.is_ready());
333    /// ```
334    ///
335    /// ```rust
336    /// use read_tree::Sapling;
337    ///
338    /// let mut sap = Sapling::<usize>::new();
339    /// assert_eq!(sap.pop(), None);
340    /// ```
341    pub fn pop(&mut self) -> Option<&T> {
342        let i = self.path.pop()?;
343        self.verts[i].len = self.verts.len() - i - 1;
344        Some(&self.verts[i].data)
345    }
346
347    /// Closes all open nodes.
348    ///
349    /// # Examples
350    ///
351    /// ```rust
352    /// use read_tree::Sapling;
353    ///
354    /// let mut sap = Sapling::new();
355    /// sap.push(0);
356    /// sap.push(1);
357    /// sap.push(2);
358    /// sap.pop_all();
359    ///
360    /// assert!(sap.is_ready());
361    /// ```
362    pub fn pop_all(&mut self) {
363        while let Some(i) = self.path.pop() {
364            self.verts[i].len = self.verts.len() - i - 1;
365        }
366    }
367
368    /// Closes the current node and makes it a leaf node.
369    ///
370    /// Any nodes that were attached to the node will be attached to its parent
371    /// instead.
372    ///
373    /// # Examples
374    ///
375    /// ```rust
376    /// use read_tree::Sapling;
377    ///
378    /// let mut sap = Sapling::new();
379    /// sap.push(0);
380    /// sap.push(1);
381    /// sap.push_leaf(2);
382    ///
383    /// // make `1` a leaf node; changing `2` to be a child of `0`
384    /// sap.pop_as_leaf();
385    /// sap.pop();
386    ///
387    /// let tree = sap.build().unwrap();
388    /// let mut iter = tree.as_node().children();
389    ///
390    /// assert_eq!(iter.next().unwrap().data(), &1);
391    /// assert_eq!(iter.next().unwrap().data(), &2);
392    /// assert!(iter.next().is_none());
393    /// ```
394    pub fn pop_as_leaf(&mut self) -> Option<&T> {
395        let i = self.path.pop()?;
396        Some(&self.verts[i].data)
397    }
398
399    /// Closes all open nodes and makes them all leaf nodes.
400    ///
401    /// If there are open nodes in the sapling, this will create multiple root
402    /// nodes.
403    ///
404    /// # Examples
405    ///
406    /// ```rust
407    /// use read_tree::{BuildError, Sapling};
408    ///
409    /// let mut sap = Sapling::new();
410    /// sap.push(0);
411    /// sap.push(1);
412    ///
413    /// sap.pop_as_leaf_all();
414    /// match sap.build().unwrap_err() {
415    ///     BuildError::MultipleRoots(_) => (),
416    ///     _ => panic!(),
417    /// }
418    /// ```
419    pub fn pop_as_leaf_all(&mut self) {
420        self.path.clear();
421    }
422
423    /// Removes all nodes from the sapling, making it empty.
424    ///
425    /// # Examples
426    ///
427    /// ```rust
428    /// use read_tree::Sapling;
429    ///
430    /// let mut sap = Sapling::new();
431    /// sap.push_leaf(0);
432    /// assert_eq!(sap.is_empty(), false);
433    ///
434    /// sap.clear();
435    /// assert_eq!(sap.is_empty(), true);
436    /// ```
437    pub fn clear(&mut self) {
438        self.path.clear();
439        self.verts.clear();
440    }
441
442    /// Returns `true` if the sapling contains no nodes. Use [`push`] to add
443    /// nodes.
444    ///
445    /// [`push`]: Sapling::push
446    pub fn is_empty(&self) -> bool {
447        self.verts.is_empty()
448    }
449
450    /// Return `true` if the sapling is ready to be built.
451    ///
452    /// Verifies that the sapling is not empty and has no open nodes. It does
453    /// not verify the number of root nodes of the sapling. Building into a
454    /// [`Tree`]`<T>` may still fail because trees do not allow multiple root
455    /// nodes.
456    pub fn is_ready(&self) -> bool {
457        self.path.is_empty() && !self.verts.is_empty()
458    }
459
460    /// Builds the sapling into a [`Tree`]`<T>`.
461    ///
462    /// Consumes the sapling in the process. Fails when the sapling is
463    /// incomplete or has multiple roots. When failing to build the sapling, the
464    /// sapling is returned unmodified with the [`BuildError`]`<T>`.
465    pub fn build(self) -> Result<Tree<T>, BuildError<T>> {
466        if !self.is_ready() {
467            return Err(BuildError::Incomplete(self));
468        }
469        if self.verts[0].len < self.verts.len() - 1 {
470            return Err(BuildError::MultipleRoots(self));
471        }
472
473        Ok(Tree {
474            path: self.path,
475            verts: self.verts,
476        })
477    }
478
479    /// Builds the sapling into a [`PolyTree`]`<T>`.
480    ///
481    /// Consumes the sapling in the process. Fails when the sapling is
482    /// incomplete. When failing to build the sapling, the sapling is returned
483    /// unmodified with the [`BuildError`]`<T>`.
484    pub fn build_polytree(self) -> Result<PolyTree<T>, BuildError<T>> {
485        if !self.is_ready() {
486            return Err(BuildError::Incomplete(self));
487        }
488
489        Ok(PolyTree {
490            path: self.path,
491            verts: self.verts,
492        })
493    }
494}
495
496impl<T> Default for Sapling<T> {
497    fn default() -> Self {
498        Self::new()
499    }
500}
501
502/// A read-only tree data structure.
503///
504/// Trees are created from [`Sapling`]`<T>`s. Most interactions with trees
505/// happen on slices of them called [`Node`]s. Get a node representing the
506/// entire tree using [`as_node`].
507///
508/// [`as_node`]: Tree::as_node
509#[derive(Debug)]
510pub struct Tree<T> {
511    /// Unused buffer.
512    ///
513    /// The buffer was used by the sapling that was used to construct the tree.
514    /// It is kept in case the tree is turned back into a sapling.
515    path: Vec<usize>,
516    verts: Vec<Vertex<T>>,
517}
518
519#[allow(clippy::len_without_is_empty)]
520impl<T> Tree<T> {
521    /// Returns the unique root node of the tree representing the entire tree.
522    ///
523    /// You can think of this as taking the complete slice of the tree similar
524    /// to `&vec[..]` for a [`Vec`]`<T>`.
525    pub fn as_node(&self) -> Node<T> {
526        Node {
527            rank: 0,
528            verts: &self.verts[..],
529        }
530    }
531
532    /// Returns the node with the specified `rank`.
533    pub fn get(&self, rank: usize) -> Option<Node<T>> {
534        if rank >= self.verts.len() {
535            return None;
536        }
537
538        Some(Node {
539            rank,
540            verts: &self.verts[..],
541        })
542    }
543
544    /// Returns the number of nodes in the tree.
545    ///
546    /// Because trees are required to have exactly one root node, the length
547    /// will always be at least `1`.
548    pub fn len(&self) -> usize {
549        self.verts.len()
550    }
551
552    /// Turns the tree back into a sapling. No nodes are removed from the
553    /// tree; building the returned sapling will result in the original tree.
554    ///
555    /// All internal buffers are reused, making this a cheap operation. The only
556    /// cost of converting [`Sapling`]`<T>`s and [`Tree`]`<T>`s back and forth
557    /// is the validation that occurs during [`build`].
558    ///
559    /// [`build`]: Sapling::build
560    pub fn into_sapling(self) -> Sapling<T> {
561        Sapling {
562            path: self.path,
563            verts: self.verts,
564        }
565    }
566}
567
568/// A read-only poly-tree data structure.
569///
570/// Similar to [`Tree`]`<T>` but allows multiple root nodes.
571#[derive(Debug)]
572pub struct PolyTree<T> {
573    path: Vec<usize>,
574    verts: Vec<Vertex<T>>,
575}
576
577#[allow(clippy::len_without_is_empty)]
578impl<T> PolyTree<T> {
579    /// Returns an iterator over the root nodes of the poly-tree.
580    pub fn roots(&self) -> Children<T> {
581        Children {
582            top: 0,
583            bottom: self.verts.len(),
584            verts: &self.verts[..],
585        }
586    }
587
588    /// Returns the node with the specified `rank`.
589    pub fn get(&self, rank: usize) -> Option<Node<T>> {
590        if rank >= self.verts.len() {
591            return None;
592        }
593
594        Some(Node {
595            rank,
596            verts: &self.verts[..],
597        })
598    }
599
600    /// Returns the number of nodes in the poly-tree.
601    ///
602    /// Because poly-trees are required to not be empty, the length will always
603    /// be at least `1`.
604    pub fn len(&self) -> usize {
605        self.verts.len()
606    }
607
608    /// Turns the poly-tree back into a sapling. No nodes are removed from the
609    /// tree; building the returned sapling will result in the original
610    /// poly-tree.
611    ///
612    /// All internal buffers are reused, making this a cheap operation. The only
613    /// cost of converting [`Sapling`]`<T>`s and [`PolyTree`]`<T>`s back and
614    /// forth is the validation that occurs during [`build_polytree`].
615    ///
616    /// [`build_polytree`]: Sapling::build_polytree
617    pub fn into_sapling(self) -> Sapling<T> {
618        Sapling {
619            path: self.path,
620            verts: self.verts,
621        }
622    }
623}
624
625/// A slice of a [`Tree`]`<T>` or [`PolyTree`]`<T>`.
626///
627/// A node is essentially the same as a tree, except it does not own its data.
628///
629/// Navigating the subtree of a node is done using iterators.
630///
631/// *It is planned to add a query type that allows querying nodes from subtrees
632/// using chains of conditions. Currently only some basic iterators are
633/// available.*
634#[derive(Debug)]
635pub struct Node<'a, T> {
636    rank: usize,
637    verts: &'a [Vertex<T>],
638}
639
640impl<'a, T> Node<'a, T> {
641    /// Turns a slice of vertices into a [`Node`]`<T>`, after performing some
642    /// validations.
643    ///
644    /// Returns an error in case of a failed validation. For the possible errors
645    /// see [`ValidationError`]. For a more detailed description of the
646    /// validation process see the safety section for [`from_unchecked`].
647    ///
648    /// To avoid running the validations; which have a significant cost for
649    /// large trees; use the unsafe alternative [`from_unchecked`].
650    ///
651    /// [`from_unchecked`]: Node::from_unchecked
652    pub fn from(verts: &[Vertex<T>]) -> Result<Node<T>, ValidationError> {
653        if verts.is_empty() {
654            return Err(ValidationError::Empty);
655        }
656        if verts[0].len != verts.len() - 1 {
657            return Err(ValidationError::MultipleRoots);
658        }
659
660        let mut path = Vec::new();
661        for (i, val) in verts.iter().enumerate() {
662            while path.last() == Some(&i) {
663                path.pop();
664            }
665
666            let scope = i + val.len + 1;
667            if path.last().map(|head| *head < scope) == Some(true) {
668                return Err(ValidationError::IllegalStructure);
669            }
670            path.push(scope);
671        }
672
673        Ok(Node { rank: 0, verts })
674    }
675
676    /// Returns a slice of vertices as a [`Node`]`<T>`.
677    ///
678    /// This is the unsafe alternative to [`from`] that skips all validations.
679    ///
680    /// # Safety
681    ///
682    /// The caller must guarantee that all expected qualities of the vertex
683    /// slice are fulfilled.
684    ///
685    /// 1. The vertex slice must not be empty.
686    /// 2. The first vertex must span the entire slice.
687    ///
688    ///    This means that the `len` of the first vertex is equal to
689    ///    `verts.len() - 1`.
690    ///
691    /// 3. The scope of all vertices must be contained within the scope of its
692    ///    parent vertex
693    ///
694    ///    Here `scope` refers to the range starting from a nodes index to the
695    ///    nodes index plus its `len` inclusive.
696    ///
697    /// [`from`]: Node::from
698    pub unsafe fn from_unchecked(verts: &[Vertex<T>]) -> Node<T> {
699        Node { rank: 0, verts }
700    }
701
702    /// Returns a reference to the payload of the node.
703    pub fn data(self) -> &'a T {
704        &self.verts[self.rank].data
705    }
706
707    /// Returns the rank of the node in the tree. The rank can be used to look
708    /// up the node from the tree using [`get`].
709    ///
710    /// The rank also exposes information about the structure of the tree. Any
711    /// node `child` with a rank greater than that of a node `parent` but not
712    /// exceeding `parent.rank() + parent.len()` is a descendant of `parent`.
713    ///
714    /// [`get`]: Tree::get
715    pub fn rank(self) -> usize {
716        self.rank
717    }
718
719    /// Returns the number of descending nodes within the subtree of this node.
720    /// A leaf node returns length `0`.
721    pub fn len(self) -> usize {
722        self.verts[self.rank].len
723    }
724
725    /// Returns `true` if the node has no child nodes.
726    pub fn is_empty(self) -> bool {
727        self.verts[self.rank].len == 0
728    }
729
730    /// Returns the node with the specified `rank`.
731    ///
732    /// The rank must be relative to the trees root, or the most recently pruned
733    /// node. See [`isolated`] for more information.
734    ///
735    /// [`isolated`]: Node::isolated
736    pub fn get(self, rank: usize) -> Option<Node<'a, T>> {
737        if rank >= self.verts.len() {
738            return None;
739        }
740
741        Some(Node {
742            rank,
743            verts: self.verts,
744        })
745    }
746
747    /// Returns the parent of the node or `None` if it does not have one.
748    pub fn parent(self) -> Option<Node<'a, T>> {
749        self.ancestors().next()
750    }
751
752    /// Returns an iterator over the child nodes of the node. See [`Children`]
753    /// for more information about the iterator.
754    pub fn children(self) -> Children<'a, T> {
755        Children::from(self)
756    }
757
758    /// Returns a depth first iterator of nodes. It iterates all nodes in the
759    /// subtree of the node, including the node itself. See [`Descendants`] for
760    /// more information about the iterator.
761    pub fn descendants(self) -> Descendants<'a, T> {
762        Descendants::from(self)
763    }
764
765    /// Returns an iterator over the parent nodes. The parent of the node is
766    /// first. The root of the tree is last. See [`Ancestors`] for more
767    /// information about the iterator.
768    pub fn ancestors(self) -> Ancestors<'a, T> {
769        Ancestors::from(self)
770    }
771
772    /// Returns the nodes internal vertex slice.
773    pub fn as_slice(self) -> &'a [Vertex<T>] {
774        self.verts
775    }
776
777    /// Returns the node isolated from the rest of the tree.
778    ///
779    /// An isolated node will always have rank `0`, and it will be impossible to
780    /// access its ancestors. It is still possible to explore the subtree below
781    /// the node.
782    ///
783    /// When getting nodes by rank you must get them from this or any descending
784    /// node. If you use the rank in a node that is not affected by this
785    /// isolation, it will return some other node. Think of the isolated node as
786    /// an entirely new tree with its own ranking.
787    pub fn isolated(self) -> Node<'a, T> {
788        Node {
789            rank: 0,
790            verts: &self.verts[self.rank..=self.rank + self.verts[self.rank].len],
791        }
792    }
793
794    /// Clones the contents of the node into a new [`Tree`]`<T>`.
795    ///
796    /// Similar to [`push_node`] this operation is cheaper if `T` implements
797    /// [`Copy`]. It is internally based on [`Vec::extend_from_slice`].
798    ///
799    /// [`push_node`]: Sapling::push_node
800    pub fn into_tree(self) -> Tree<T>
801    where
802        T: Clone,
803    {
804        let mut verts = Vec::new();
805        verts.extend_from_slice(self.verts);
806
807        Tree {
808            path: Vec::new(),
809            verts,
810        }
811    }
812}
813
814impl<'a, T> Copy for Node<'a, T> {}
815
816impl<'a, T> Clone for Node<'a, T> {
817    fn clone(&self) -> Self {
818        *self
819    }
820}
821
822/// Iterates the children of a node.
823///
824/// # Examples
825///
826/// ```rust
827/// use read_tree::Sapling;
828///
829/// fn main() -> Result<(), Box<dyn std::error::Error>> {
830///     let mut sap = Sapling::new();
831///     sap.push(1);
832///     sap.push_leaf(11);
833///     sap.push(12);
834///     sap.push_leaf(121);
835///     sap.pop();
836///     sap.pop();
837///     let tree = sap.build()?;
838///     let mut iter = tree.as_node().children();
839///
840///     assert_eq!(iter.next().unwrap().data(), &11);
841///     assert_eq!(iter.next().unwrap().data(), &12);
842///     assert!(iter.next().is_none());
843///
844///     Ok(())
845/// }
846/// ```
847#[derive(Debug)]
848pub struct Children<'a, T> {
849    /// The next child node.
850    top: usize,
851
852    /// One beyond the last child node.
853    bottom: usize,
854    verts: &'a [Vertex<T>],
855}
856
857impl<'a, T> Children<'a, T> {
858    /// Creates a new iterator over the children of a node.
859    pub fn from(node: Node<'a, T>) -> Self {
860        Children {
861            top: node.rank() + 1,
862            bottom: node.rank() + node.len() + 1,
863            verts: node.verts,
864        }
865    }
866}
867
868impl<'a, T> Iterator for Children<'a, T> {
869    type Item = Node<'a, T>;
870
871    fn next(&mut self) -> Option<Self::Item> {
872        if self.top >= self.bottom {
873            return None;
874        }
875
876        let ret = Node {
877            rank: self.top,
878            verts: self.verts,
879        };
880        self.top += self.verts[self.top].len + 1;
881        Some(ret)
882    }
883
884    fn size_hint(&self) -> (usize, Option<usize>) {
885        if self.top >= self.bottom {
886            (0, Some(0))
887        } else {
888            (1, Some(self.bottom - self.top))
889        }
890    }
891}
892
893/// Iterates all descendants of a node depth first.
894///
895/// The iterator implements [`ExactSizeIterator`] and [`DoubleEndedIterator`]
896/// giving access to [`len`] and [`rev`]. It also has fast implementations for
897/// [`nth`] and [`last`].
898///
899///
900/// # Examples
901///
902/// ```rust
903/// use read_tree::Sapling;
904///
905/// fn main() -> Result<(), Box<dyn std::error::Error>> {
906///     let mut sap = Sapling::new();
907///     sap.push(1);
908///     sap.push(11);
909///     sap.push_leaf(111);
910///     sap.pop();
911///     sap.push(12);
912///     sap.push_leaf(121);
913///     sap.pop();
914///     sap.pop();
915///     let tree = sap.build()?;
916///     let mut iter = tree.as_node().descendants();
917///
918///     assert_eq!(iter.len(), 4);
919///     assert_eq!(iter.next().unwrap().data(), &11);
920///     assert_eq!(iter.next().unwrap().data(), &111);
921///     assert_eq!(iter.next().unwrap().data(), &12);
922///     assert_eq!(iter.next().unwrap().data(), &121);
923///     assert!(iter.next().is_none());
924///
925///     Ok(())
926/// }
927/// ```
928///
929/// [`last`]: Iterator::last
930/// [`len`]: ExactSizeIterator::len
931/// [`nth`]: Iterator::nth
932/// [`rev`]: Iterator::rev
933#[derive(Debug)]
934pub struct Descendants<'a, T> {
935    /// The next node to yield from the top.
936    top: usize,
937
938    /// The previously yielded node from the bottom
939    bottom: usize,
940    verts: &'a [Vertex<T>],
941}
942
943impl<'a, T> Descendants<'a, T> {
944    /// Creates a new iterator over the descendants of a node.
945    pub fn from(node: Node<'a, T>) -> Self {
946        Descendants {
947            top: node.rank() + 1,
948            bottom: node.rank() + node.len() + 1,
949            verts: node.verts,
950        }
951    }
952}
953
954impl<'a, T> Iterator for Descendants<'a, T> {
955    type Item = Node<'a, T>;
956
957    fn next(&mut self) -> Option<Self::Item> {
958        if self.top >= self.bottom {
959            return None;
960        }
961
962        let ret = Node {
963            rank: self.top,
964            verts: self.verts,
965        };
966        self.top += 1;
967        Some(ret)
968    }
969
970    fn nth(&mut self, n: usize) -> Option<Self::Item> {
971        self.top += n;
972        self.next()
973    }
974
975    fn last(mut self) -> Option<Self::Item> {
976        self.next_back()
977    }
978
979    fn size_hint(&self) -> (usize, Option<usize>) {
980        (self.len(), Some(self.len()))
981    }
982
983    fn count(self) -> usize {
984        self.len()
985    }
986}
987
988impl<'a, T> DoubleEndedIterator for Descendants<'a, T> {
989    fn next_back(&mut self) -> Option<Self::Item> {
990        if self.top >= self.bottom {
991            return None;
992        }
993
994        self.bottom -= 1;
995        Some(Node {
996            rank: self.bottom,
997            verts: self.verts,
998        })
999    }
1000}
1001
1002impl<'a, T> ExactSizeIterator for Descendants<'a, T> {
1003    fn len(&self) -> usize {
1004        self.bottom - self.top
1005    }
1006}
1007
1008/// Iterates all ancestors of a node starting with the parent of the node.
1009///
1010/// The iterator implements [`DoubleEndedIterator`], allowing it to be reversed
1011/// using [`rev`].
1012///
1013/// [`rev`]: Iterator::rev
1014#[derive(Debug)]
1015pub struct Ancestors<'a, T> {
1016    /// The next potential top most ancestor.
1017    top: usize,
1018
1019    /// The previously found bottom most ancestor.
1020    bottom: usize,
1021    verts: &'a [Vertex<T>],
1022}
1023
1024impl<'a, T> Ancestors<'a, T> {
1025    /// Creates a new iterator over the ancestors of a node.
1026    pub fn from(node: Node<'a, T>) -> Self {
1027        Ancestors {
1028            top: 0,
1029            bottom: node.rank(),
1030            verts: node.verts,
1031        }
1032    }
1033}
1034
1035impl<'a, T> Iterator for Ancestors<'a, T> {
1036    type Item = Node<'a, T>;
1037
1038    fn next(&mut self) -> Option<Self::Item> {
1039        if self.top >= self.bottom {
1040            return None;
1041        }
1042
1043        for i in (self.top..self.bottom).rev() {
1044            if self.bottom <= i + self.verts[i].len {
1045                self.bottom = i;
1046                return Some(Node {
1047                    rank: i,
1048                    verts: self.verts,
1049                });
1050            }
1051        }
1052
1053        None
1054    }
1055
1056    fn size_hint(&self) -> (usize, Option<usize>) {
1057        (0, Some(self.top - self.bottom))
1058    }
1059
1060    fn count(self) -> usize {
1061        // The reverse direction of the iterator can skip subtrees and should therefor
1062        // be faster for most trees.
1063        self.rev().count()
1064    }
1065
1066    fn last(mut self) -> Option<Self::Item> {
1067        self.next_back()
1068    }
1069}
1070
1071impl<'a, T> DoubleEndedIterator for Ancestors<'a, T> {
1072    fn next_back(&mut self) -> Option<Self::Item> {
1073        let mut i = self.top;
1074        while i < self.bottom {
1075            let len = self.verts[i].len;
1076            if i + len < self.bottom {
1077                i += len + 1;
1078            } else {
1079                self.top = i + 1;
1080                return Some(Node {
1081                    rank: i,
1082                    verts: self.verts,
1083                });
1084            }
1085        }
1086
1087        None
1088    }
1089}