tree_flat/
tree.rs

1#![allow(dead_code)]
2
3use crate::iter::{IntoIter, TreeIter};
4use crate::node::NodeMut;
5use std::cmp::Ordering;
6use std::fmt::{Debug, Display, Formatter};
7
8use crate::prelude::*;
9
10/// Vec-backed, *flattened in pre-order*, Tree.
11///
12/// Always contains at least a root node.
13#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
14pub struct Tree<T> {
15    pub(crate) data: Vec<T>,
16    pub(crate) level: Vec<usize>,
17    pub(crate) parent: Vec<usize>,
18}
19
20impl<T: Debug> Tree<T> {
21    /// Create a new [Tree] with the specified value
22    pub fn new(root: T) -> Self {
23        Self::with_capacity(root, 1)
24    }
25
26    /// Create a new [Tree] with the specified value & set the capacity of the internal vectors
27    pub fn with_capacity(root: T, capacity: usize) -> Self {
28        let mut t = Tree {
29            data: Vec::with_capacity(capacity),
30            level: Vec::with_capacity(capacity),
31            parent: Vec::with_capacity(capacity),
32        };
33        t.push_with_level(root, 0, 0.into());
34        t
35    }
36
37    /// Returns the total number of elements the tree can hold without reallocating.
38    pub fn capacity(&self) -> usize {
39        self.data.capacity() // Any of the three underlying vectors is good enough.
40    }
41
42    /// Reserves capacity for at least `additional` more elements to be inserted
43    /// in the given `Tree<T>`. The collection may reserve more space to
44    /// speculatively avoid frequent reallocations. After calling `reserve`,
45    /// capacity will be greater than or equal to `self.len() + additional`.
46    /// Does nothing if capacity is already sufficient.
47    ///
48    /// # Panics
49    ///
50    /// Panics if the new capacity exceeds `isize::MAX` bytes.
51    pub fn reserve(&mut self, additional: usize) {
52        self.data.reserve(additional);
53        self.level.reserve(additional);
54        self.parent.reserve(additional);
55    }
56
57    /// Reserves the minimum capacity for at least `additional` more elements to
58    /// be inserted in the given `Tree<T>`. Unlike [`reserve`], this will not
59    /// deliberately over-allocate to speculatively avoid frequent allocations.
60    /// After calling `reserve_exact`, capacity will be greater than or equal to
61    /// `self.len() + additional`. Does nothing if the capacity is already
62    /// sufficient.
63    ///
64    /// Note that the allocator may give the collection more space than it
65    /// requests. Therefore, capacity can not be relied upon to be precisely
66    /// minimal. Prefer [`reserve`] if future insertions are expected.
67    ///
68    /// [`reserve`]: Tree::reserve
69    ///
70    /// # Panics
71    ///
72    /// Panics if the new capacity exceeds `isize::MAX` bytes.
73    pub fn reserve_exact(&mut self, additional: usize) {
74        self.data.reserve_exact(additional);
75        self.level.reserve_exact(additional);
76        self.parent.reserve_exact(additional);
77    }
78
79    /// Tries to reserve capacity for at least `additional` more elements to be inserted
80    /// in the given `Tree<T>`. The collection may reserve more space to speculatively avoid
81    /// frequent reallocations. After calling `try_reserve`, capacity will be
82    /// greater than or equal to `self.len() + additional` if it returns
83    /// `Ok(())`. Does nothing if capacity is already sufficient. This method
84    /// preserves the contents even if an error occurs.
85    ///
86    /// # Errors
87    ///
88    /// If the capacity overflows, or the allocator reports a failure, then an error
89    /// is returned.
90    pub fn try_reserve(
91        &mut self,
92        additional: usize,
93    ) -> Result<(), std::collections::TryReserveError> {
94        self.data.try_reserve(additional)?;
95        self.level.try_reserve(additional)?;
96        self.parent.try_reserve(additional)
97    }
98
99    /// Tries to reserve the minimum capacity for at least `additional`
100    /// elements to be inserted in the given `Tree<T>`. Unlike [`try_reserve`],
101    /// this will not deliberately over-allocate to speculatively avoid frequent
102    /// allocations. After calling `try_reserve_exact`, capacity will be greater
103    /// than or equal to `self.len() + additional` if it returns `Ok(())`.
104    /// Does nothing if the capacity is already sufficient.
105    ///
106    /// Note that the allocator may give the collection more space than it
107    /// requests. Therefore, capacity can not be relied upon to be precisely
108    /// minimal. Prefer [`try_reserve`] if future insertions are expected.
109    ///
110    /// [`try_reserve`]: Tree::try_reserve
111    ///
112    /// # Errors
113    ///
114    /// If the capacity overflows, or the allocator reports a failure, then an error
115    /// is returned.
116    pub fn try_reserve_exact(
117        &mut self,
118        additional: usize,
119    ) -> Result<(), std::collections::TryReserveError> {
120        self.data.try_reserve_exact(additional)?;
121        self.level.try_reserve_exact(additional)?;
122        self.parent.try_reserve_exact(additional)
123    }
124
125    /// Shrinks the capacity of the tree as much as possible.
126    ///
127    /// It will drop down as close as possible to the length but the allocator
128    /// may still inform the tree that there is space for a few more elements.
129    pub fn shrink_to_fit(&mut self) {
130        if self.capacity() > self.len() {
131            self.data.shrink_to_fit();
132            self.level.shrink_to_fit();
133            self.parent.shrink_to_fit();
134        }
135    }
136
137    /// Shrinks the capacity of the tree with a lower bound.
138    ///
139    /// The capacity will remain at least as large as both the length
140    /// and the supplied value.
141    ///
142    /// If the current capacity is less than the lower limit, this is a no-op.
143    pub fn shrink_to(&mut self, min_capacity: usize) {
144        if self.capacity() > min_capacity {
145            self.data.shrink_to(min_capacity);
146            self.level.shrink_to(min_capacity);
147            self.parent.shrink_to(min_capacity);
148        }
149    }
150
151    /// Shortens the tree, keeping the first `len` elements and dropping
152    /// the rest.
153    ///
154    /// If `len` is greater than the tree's current length, this has no
155    /// effect.
156    ///
157    /// The [`drain`] method can emulate `truncate`, but causes the excess
158    /// elements to be returned instead of dropped.
159    ///
160    /// Note that this method has no effect on the allocated capacity
161    /// of the tree.
162    ///
163    /// [`drain`]: Tree::drain
164    pub fn truncate(&mut self, len: usize) {
165        self.data.truncate(len);
166        self.level.truncate(len);
167        self.parent.truncate(len);
168    }
169
170    /// Push a node into the tree
171    ///
172    /// #WARNING
173    ///
174    /// This assumes you are pushing in pre-order!
175    pub fn push_with_level(&mut self, data: T, level: usize, parent: NodeId) -> NodeId {
176        let parent = parent.to_index();
177        //let parent = if parent == 0 { 0 } else { parent - 1 };
178
179        self.data.push(data);
180        self.level.push(level);
181        self.parent.push(parent);
182
183        (self.data.len() - 1).into()
184    }
185
186    pub(crate) fn _make_node(&self, id: NodeId) -> Node<T> {
187        Node {
188            id,
189            data: &self.data[id.to_index()],
190            tree: self,
191        }
192    }
193
194    pub(crate) fn _make_node_mut(&mut self, id: NodeId) -> NodeMut<T> {
195        NodeMut {
196            id,
197            data: &mut self.data[id.to_index()],
198        }
199    }
200
201    pub(crate) fn _make_tree_mut(&mut self, id: NodeId, parent: NodeId) -> TreeMut<T> {
202        TreeMut {
203            id,
204            parent,
205            tree: self,
206        }
207    }
208
209    /// Removes the last element from a tree and returns it as a triple
210    /// `(data: T, level: usize, parent: NodeId)`, or [`None`] if it
211    /// is empty.
212    #[inline]
213    pub fn pop(&mut self) -> Option<(T, usize, NodeId)> {
214        if let Some(data) = self.data.pop() {
215            let level = self.level.pop().unwrap();
216            let parent = self.parent.pop().unwrap().into();
217            Some((data, level, parent))
218        } else {
219            None
220        }
221    }
222
223    /// Removes the specified range from the tree in bulk, returning all
224    /// removed elements as an iterator. If the iterator is dropped before
225    /// being fully consumed, it drops the remaining removed elements.
226    ///
227    /// The returned iterator keeps a mutable borrow on the tree to optimize
228    /// its implementation.
229    ///
230    /// # Panics
231    ///
232    /// Panics if the starting point is greater than the end point or if
233    /// the end point is greater than the length of the vector.
234    ///
235    /// # Leaking
236    ///
237    /// If the returned iterator goes out of scope without being dropped (due to
238    /// [`mem::forget`], for example), the tree may have lost and leaked
239    /// elements arbitrarily, including elements outside the range.
240    //
241    // # Implementation
242    //
243    // The return type may be specialized as in `std::vec::Drain`, implementing more traits.
244    pub fn drain<R>(&mut self, range: R) -> impl Iterator<Item = (T, usize, NodeId)> + '_
245    where
246        R: std::ops::RangeBounds<usize> + Clone,
247    {
248        let mut data_drain = self.data.drain(range.clone());
249        let mut level_drain = self.level.drain(range.clone());
250        let mut parent_drain = self.parent.drain(range);
251        std::iter::from_fn(move || match data_drain.next() {
252            Some(data) => {
253                let level = level_drain.next().unwrap();
254                let parent = parent_drain.next().unwrap().into();
255                Some((data, level, parent))
256            }
257            None => None,
258        })
259    }
260
261    /// Clears the tree, removing all values.
262    ///
263    /// Note that this method has no effect on the allocated capacity
264    /// of the tree.
265    #[inline]
266    pub fn clear(&mut self) {
267        self.data.clear();
268        self.level.clear();
269        self.parent.clear();
270    }
271
272    /// Returns the number of elements in the tree, also referred to as its ‘length’.
273    pub fn len(&self) -> usize {
274        self.data.len()
275    }
276
277    /// Returns `true` if the vector contains no elements.
278    pub fn is_empty(&self) -> bool {
279        self.data.is_empty()
280    }
281
282    /// Get a mutable [TreeMut<T>] handle of the root, so you can push children
283    ///
284    /// This always success
285    pub fn tree_root_mut(&mut self) -> TreeMut<T> {
286        self._make_tree_mut(0.into(), 0.into())
287    }
288
289    /// Get a mutable [TreeMut<T>] from his [NodeId], so you can push children
290    pub fn tree_node_mut(&mut self, id: NodeId) -> Option<TreeMut<T>> {
291        if id.to_index() < self.data.len() {
292            Some(self._make_tree_mut(id, 0.into()))
293        } else {
294            None
295        }
296    }
297
298    /// Get the [Node<T>] from his [NodeId]
299    pub fn node(&self, id: NodeId) -> Option<Node<T>> {
300        if id.to_index() < self.data.len() {
301            Some(self._make_node(id))
302        } else {
303            None
304        }
305    }
306
307    /// Get the root [Node<T>]
308    pub fn root(&self) -> Node<T> {
309        self._make_node(0.into())
310    }
311
312    /// Get a mutable [NodeMut<T>] from his [NodeId].
313    pub fn node_mut(&mut self, id: NodeId) -> Option<NodeMut<T>> {
314        if id.to_index() < self.data.len() {
315            Some(self._make_node_mut(id))
316        } else {
317            None
318        }
319    }
320
321    /// Get a mutable [NodeMut<T>] handle of the root.
322    ///
323    /// This always success
324    pub fn root_mut(&mut self) -> NodeMut<'_, T> {
325        self._make_node_mut(0.into())
326    }
327
328    pub fn iter(&self) -> TreeIter<'_, T> {
329        TreeIter { pos: 0, tree: self }
330    }
331    pub fn into_iter(&self) -> IntoIter<T> {
332        IntoIter { tree: self }
333    }
334
335    /// A slice view of the internal data
336    pub fn as_data(&self) -> &[T] {
337        &self.data
338    }
339    /// A slice view of the internal data
340    pub fn as_data_mut(&mut self) -> &mut [T] {
341        self.data.as_mut_slice()
342    }
343
344    /// A slice view of the internal level
345    pub fn as_level(&self) -> &[usize] {
346        &self.level
347    }
348
349    /// Get the level from a [NodeId]
350    pub fn get_level(&self, of: NodeId) -> usize {
351        if of.to_index() == 0 {
352            0
353        } else {
354            self.level[of.to_index()]
355        }
356    }
357
358    /// A slice view of the internal parents
359    pub fn as_parents(&self) -> &[usize] {
360        &self.parent
361    }
362
363    /// Consume tree and move-out the data
364    pub fn to_data(self) -> Vec<T> {
365        self.data
366    }
367
368    /// Pretty-print the tree
369    pub fn print(&self, f: &mut Formatter<'_>) -> std::fmt::Result
370    where
371        T: Display,
372    {
373        let last = self.data.len() - 1;
374        for (pos, x) in self.data.iter().enumerate() {
375            let mut branch = if pos == 0 {
376                "."
377            } else if pos == last {
378                "└──"
379            } else {
380                "├──"
381            }
382            .to_string();
383
384            let level = self.level[pos];
385            let mut col = String::with_capacity(level * 2);
386            for _i in 1..level {
387                match pos.cmp(&last) {
388                    Ordering::Greater => branch.push_str(&"──".repeat(level)),
389                    Ordering::Less => col.push_str("├   "),
390                    Ordering::Equal => branch.push_str("──"),
391                }
392            }
393            writeln!(f, "{}{} {}", col, branch, x)?;
394        }
395        Ok(())
396    }
397}
398
399impl<T: Debug + Display> Display for Tree<T> {
400    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
401        self.print(f)
402    }
403}