ego_tree/
lib.rs

1//! Vec-backed ID-tree.
2//!
3//! # Behavior
4//!
5//! - Trees have at least a root node;
6//! - Nodes have zero or more ordered children;
7//! - Nodes have at most one parent;
8//! - Nodes can be detached (orphaned) but not removed;
9//! - Node parent, next sibling, previous sibling, first child and last child
10//!   can be accessed in constant time;
11//! - All methods perform in constant time;
12//! - All iterators perform in linear time.
13//!
14//! # Examples
15//!
16//! ```
17//! let mut tree = ego_tree::Tree::new('a');
18//! let mut root = tree.root_mut();
19//! root.append('b');
20//! let mut c = root.append('c');
21//! c.append('d');
22//! c.append('e');
23//! ```
24//!
25//! ```
26//! #[macro_use] extern crate ego_tree;
27//! # fn main() {
28//! let tree = tree!('a' => { 'b', 'c' => { 'd', 'e' } });
29//! # }
30//! ```
31
32#![warn(
33    missing_docs,
34    missing_debug_implementations,
35    missing_copy_implementations
36)]
37
38use std::fmt::{self, Debug, Display, Formatter};
39use std::num::NonZeroUsize;
40
41#[cfg(feature = "serde")]
42pub mod serde;
43
44/// Vec-backed ID-tree.
45///
46/// Always contains at least a root node.
47#[derive(Clone, PartialEq, Eq, Hash)]
48pub struct Tree<T> {
49    vec: Vec<Node<T>>,
50}
51
52/// Node ID.
53///
54/// Index into a `Tree`-internal `Vec`.
55#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
56pub struct NodeId(NonZeroUsize);
57
58impl NodeId {
59    // Safety: `n` must not equal `usize::MAX`.
60    // (This is never the case for `Vec::len()`, that would mean it owns
61    // the entire address space without leaving space even for its pointer.)
62    unsafe fn from_index(n: usize) -> Self {
63        NodeId(NonZeroUsize::new_unchecked(n + 1))
64    }
65
66    fn to_index(self) -> usize {
67        self.0.get() - 1
68    }
69}
70
71#[derive(Debug, Clone, PartialEq, Eq, Hash)]
72struct Node<T> {
73    parent: Option<NodeId>,
74    prev_sibling: Option<NodeId>,
75    next_sibling: Option<NodeId>,
76    children: Option<(NodeId, NodeId)>,
77    value: T,
78}
79
80fn _static_assert_size_of_node() {
81    // "Instantiating" the generic `transmute` function without calling it
82    // still triggers the magic compile-time check
83    // that input and output types have the same `size_of()`.
84    let _ = std::mem::transmute::<Node<()>, [usize; 5]>;
85}
86
87impl<T> Node<T> {
88    fn new(value: T) -> Self {
89        Node {
90            parent: None,
91            prev_sibling: None,
92            next_sibling: None,
93            children: None,
94            value,
95        }
96    }
97
98    pub fn map<F, U>(self, mut transform: F) -> Node<U>
99    where
100        F: FnMut(T) -> U,
101    {
102        Node {
103            parent: self.parent,
104            prev_sibling: self.prev_sibling,
105            next_sibling: self.next_sibling,
106            children: self.children,
107            value: transform(self.value),
108        }
109    }
110
111    pub fn map_ref<F, U>(&self, mut transform: F) -> Node<U>
112    where
113        F: FnMut(&T) -> U,
114    {
115        Node {
116            parent: self.parent,
117            prev_sibling: self.prev_sibling,
118            next_sibling: self.next_sibling,
119            children: self.children,
120            value: transform(&self.value),
121        }
122    }
123}
124
125/// Node reference.
126#[derive(Debug)]
127pub struct NodeRef<'a, T: 'a> {
128    /// Node ID.
129    id: NodeId,
130
131    /// Tree containing the node.
132    tree: &'a Tree<T>,
133
134    node: &'a Node<T>,
135}
136
137/// Node mutator.
138#[derive(Debug)]
139pub struct NodeMut<'a, T: 'a> {
140    /// Node ID.
141    id: NodeId,
142
143    /// Tree containing the node.
144    tree: &'a mut Tree<T>,
145}
146
147// Trait implementations regardless of T.
148
149impl<'a, T: 'a> Copy for NodeRef<'a, T> {}
150impl<'a, T: 'a> Clone for NodeRef<'a, T> {
151    fn clone(&self) -> Self {
152        *self
153    }
154}
155
156impl<'a, T: 'a> Eq for NodeRef<'a, T> {}
157impl<'a, T: 'a> PartialEq for NodeRef<'a, T> {
158    fn eq(&self, other: &Self) -> bool {
159        self.id == other.id
160            && std::ptr::eq(self.tree, other.tree)
161            && std::ptr::eq(self.node, other.node)
162    }
163}
164
165impl<T> Tree<T> {
166    /// Creates a tree with a root node.
167    pub fn new(root: T) -> Self {
168        Tree {
169            vec: vec![Node::new(root)],
170        }
171    }
172
173    /// Creates a tree with a root node and the specified capacity.
174    pub fn with_capacity(root: T, capacity: usize) -> Self {
175        let mut vec = Vec::with_capacity(capacity);
176        vec.push(Node::new(root));
177        Tree { vec }
178    }
179
180    /// Returns a reference to the specified node.
181    pub fn get(&self, id: NodeId) -> Option<NodeRef<'_, T>> {
182        self.vec.get(id.to_index()).map(|node| NodeRef {
183            id,
184            node,
185            tree: self,
186        })
187    }
188
189    /// Returns a mutator of the specified node.
190    pub fn get_mut(&mut self, id: NodeId) -> Option<NodeMut<'_, T>> {
191        let exists = self.vec.get(id.to_index()).map(|_| ());
192        exists.map(move |_| NodeMut { id, tree: self })
193    }
194
195    unsafe fn node(&self, id: NodeId) -> &Node<T> {
196        self.vec.get_unchecked(id.to_index())
197    }
198
199    unsafe fn node_mut(&mut self, id: NodeId) -> &mut Node<T> {
200        self.vec.get_unchecked_mut(id.to_index())
201    }
202
203    /// Returns a reference to the specified node.
204    /// # Safety
205    /// The caller must ensure that `id` is a valid node ID.
206    pub unsafe fn get_unchecked(&self, id: NodeId) -> NodeRef<'_, T> {
207        NodeRef {
208            id,
209            node: self.node(id),
210            tree: self,
211        }
212    }
213
214    /// Returns a mutator of the specified node.
215    /// # Safety
216    /// The caller must ensure that `id` is a valid node ID.
217    pub unsafe fn get_unchecked_mut(&mut self, id: NodeId) -> NodeMut<'_, T> {
218        NodeMut { id, tree: self }
219    }
220
221    /// Returns a reference to the root node.
222    pub fn root(&self) -> NodeRef<'_, T> {
223        unsafe { self.get_unchecked(NodeId::from_index(0)) }
224    }
225
226    /// Returns a mutator of the root node.
227    pub fn root_mut(&mut self) -> NodeMut<'_, T> {
228        unsafe { self.get_unchecked_mut(NodeId::from_index(0)) }
229    }
230
231    /// Creates an orphan node.
232    pub fn orphan(&mut self, value: T) -> NodeMut<'_, T> {
233        let id = unsafe { NodeId::from_index(self.vec.len()) };
234        self.vec.push(Node::new(value));
235        unsafe { self.get_unchecked_mut(id) }
236    }
237
238    /// Merge with another tree as orphan, returning the new root of tree being merged.
239    // Allowing this for compactness.
240    #[allow(clippy::option_map_unit_fn)]
241    pub fn extend_tree(&mut self, mut other_tree: Tree<T>) -> NodeMut<'_, T> {
242        let offset = self.vec.len();
243        let offset_id = |id: NodeId| -> NodeId {
244            let old_index = id.to_index();
245            let new_index = old_index + offset;
246            unsafe { NodeId::from_index(new_index) }
247        };
248        let other_tree_root_id = offset_id(other_tree.root().id);
249        for node in other_tree.vec.iter_mut() {
250            node.parent.as_mut().map(|id| *id = offset_id(*id));
251            node.prev_sibling.as_mut().map(|id| *id = offset_id(*id));
252            node.next_sibling.as_mut().map(|id| *id = offset_id(*id));
253            node.children.as_mut().map(|(id1, id2)| {
254                *id1 = offset_id(*id1);
255                *id2 = offset_id(*id2);
256            });
257        }
258        self.vec.append(&mut other_tree.vec);
259        unsafe { self.get_unchecked_mut(other_tree_root_id) }
260    }
261
262    /// Maps a `Tree<T>` to `Tree<U>` by applying a function to all node values,
263    /// copying over the tree's structure and node ids untouched, consuming `self`.
264    pub fn map<F, U>(self, mut transform: F) -> Tree<U>
265    where
266        F: FnMut(T) -> U,
267    {
268        Tree {
269            vec: self
270                .vec
271                .into_iter()
272                .map(|node| node.map(&mut transform))
273                .collect(),
274        }
275    }
276
277    /// Maps a `&Tree<T>` to `Tree<U>` by applying a function to all node values,
278    /// copying over the tree's structure and node ids untouched.
279    pub fn map_ref<F, U>(&self, mut transform: F) -> Tree<U>
280    where
281        F: FnMut(&T) -> U,
282    {
283        Tree {
284            vec: self
285                .vec
286                .iter()
287                .map(|node| node.map_ref(&mut transform))
288                .collect(),
289        }
290    }
291}
292
293impl<'a, T: 'a> NodeRef<'a, T> {
294    /// Returns the ID of this node.
295    pub fn id(&self) -> NodeId {
296        self.id
297    }
298
299    /// Returns the tree owning this node.
300    pub fn tree(&self) -> &'a Tree<T> {
301        self.tree
302    }
303
304    /// Returns the value of this node.
305    pub fn value(&self) -> &'a T {
306        &self.node.value
307    }
308
309    fn axis<F>(&self, f: F) -> Option<Self>
310    where
311        F: FnOnce(&Node<T>) -> Option<NodeId>,
312    {
313        f(self.node).map(|id| unsafe { self.tree.get_unchecked(id) })
314    }
315
316    /// Returns the parent of this node.
317    pub fn parent(&self) -> Option<Self> {
318        self.axis(|node| node.parent)
319    }
320
321    /// Returns the previous sibling of this node.
322    pub fn prev_sibling(&self) -> Option<Self> {
323        self.axis(|node| node.prev_sibling)
324    }
325
326    /// Returns the next sibling of this node.
327    pub fn next_sibling(&self) -> Option<Self> {
328        self.axis(|node| node.next_sibling)
329    }
330
331    /// Returns the first child of this node.
332    pub fn first_child(&self) -> Option<Self> {
333        self.axis(|node| node.children.map(|(id, _)| id))
334    }
335
336    /// Returns the last child of this node.
337    pub fn last_child(&self) -> Option<Self> {
338        self.axis(|node| node.children.map(|(_, id)| id))
339    }
340
341    /// Returns true if this node has siblings.
342    pub fn has_siblings(&self) -> bool {
343        self.node.prev_sibling.is_some() || self.node.next_sibling.is_some()
344    }
345
346    /// Returns true if this node has children.
347    pub fn has_children(&self) -> bool {
348        self.node.children.is_some()
349    }
350}
351
352impl<'a, T: 'a> NodeMut<'a, T> {
353    /// Returns the ID of this node.
354    pub fn id(&self) -> NodeId {
355        self.id
356    }
357
358    /// Returns the tree owning this node.
359    pub fn tree(&mut self) -> &mut Tree<T> {
360        self.tree
361    }
362
363    fn node(&mut self) -> &mut Node<T> {
364        unsafe { self.tree.node_mut(self.id) }
365    }
366
367    /// Returns the value of this node.
368    pub fn value(&mut self) -> &mut T {
369        &mut self.node().value
370    }
371
372    /// Downcast `NodeMut` to `NodeRef`.
373    pub fn as_ref(&mut self) -> NodeRef<'_, T> {
374        unsafe { self.tree.get_unchecked(self.id) }
375    }
376
377    fn axis<F>(&mut self, f: F) -> Option<NodeMut<'_, T>>
378    where
379        F: FnOnce(&mut Node<T>) -> Option<NodeId>,
380    {
381        let id = f(self.node());
382        id.map(move |id| unsafe { self.tree.get_unchecked_mut(id) })
383    }
384
385    fn into_axis<F>(mut self, f: F) -> Result<Self, Self>
386    where
387        F: FnOnce(&mut Node<T>) -> Option<NodeId>,
388    {
389        let id = f(self.node());
390        match id {
391            Some(id) => Ok(unsafe { self.tree.get_unchecked_mut(id) }),
392            None => Err(self),
393        }
394    }
395
396    /// Returns the parent of this node.
397    pub fn parent(&mut self) -> Option<NodeMut<'_, T>> {
398        self.axis(|node| node.parent)
399    }
400
401    /// Returns the parent of this node.
402    ///
403    /// Returns `Ok(parent)` if possible and `Err(self)` otherwise
404    /// so the caller can recover the current position.
405    pub fn into_parent(self) -> Result<Self, Self> {
406        self.into_axis(|node| node.parent)
407    }
408
409    /// Returns the previous sibling of this node.
410    pub fn prev_sibling(&mut self) -> Option<NodeMut<'_, T>> {
411        self.axis(|node| node.prev_sibling)
412    }
413
414    /// Returns the previous sibling of this node.
415    ///
416    /// Returns `Ok(prev_sibling)` if possible and `Err(self)` otherwise
417    /// so the caller can recover the current position.
418    pub fn into_prev_sibling(self) -> Result<Self, Self> {
419        self.into_axis(|node| node.prev_sibling)
420    }
421
422    /// Returns the next sibling of this node.
423    pub fn next_sibling(&mut self) -> Option<NodeMut<'_, T>> {
424        self.axis(|node| node.next_sibling)
425    }
426
427    /// Returns the next sibling of this node.
428    ///
429    /// Returns `Ok(next_sibling)` if possible and `Err(self)` otherwise
430    /// so the caller can recover the current position.
431    pub fn into_next_sibling(self) -> Result<Self, Self> {
432        self.into_axis(|node| node.next_sibling)
433    }
434
435    /// Returns the first child of this node.
436    pub fn first_child(&mut self) -> Option<NodeMut<'_, T>> {
437        self.axis(|node| node.children.map(|(id, _)| id))
438    }
439
440    /// Returns the first child of this node.
441    ///
442    /// Returns `Ok(first_child)` if possible and `Err(self)` otherwise
443    /// so the caller can recover the current position.
444    pub fn into_first_child(self) -> Result<Self, Self> {
445        self.into_axis(|node| node.children.map(|(id, _)| id))
446    }
447
448    /// Returns the last child of this node.
449    pub fn last_child(&mut self) -> Option<NodeMut<'_, T>> {
450        self.axis(|node| node.children.map(|(_, id)| id))
451    }
452
453    /// Returns the last child of this node.
454    ///
455    /// Returns `Ok(last_child)` if possible and `Err(self)` otherwise
456    /// so the caller can recover the current position.
457    pub fn into_last_child(self) -> Result<Self, Self> {
458        self.into_axis(|node| node.children.map(|(_, id)| id))
459    }
460
461    /// Returns true if this node has siblings.
462    pub fn has_siblings(&self) -> bool {
463        unsafe { self.tree.get_unchecked(self.id).has_siblings() }
464    }
465
466    /// Returns true if this node has children.
467    pub fn has_children(&self) -> bool {
468        unsafe { self.tree.get_unchecked(self.id).has_children() }
469    }
470
471    /// Apply function for each ancestor mutable node reference.
472    pub fn for_each_ancestor<'b, F>(&'b mut self, mut f: F)
473    where
474        F: FnMut(&mut NodeMut<'b, T>),
475    {
476        let mut current = self.parent();
477        while let Some(mut node) = current {
478            f(&mut node);
479            current = node.into_parent().ok();
480        }
481    }
482
483    /// Apply function for each next sibling mutable node reference.
484    pub fn for_each_next_sibling<'b, F>(&'b mut self, mut f: F)
485    where
486        F: FnMut(&mut NodeMut<'b, T>),
487    {
488        let mut current = self.next_sibling();
489        while let Some(mut node) = current {
490            f(&mut node);
491            current = node.into_next_sibling().ok();
492        }
493    }
494
495    /// Apply function for each previout sibling mutable node reference.
496    pub fn for_each_prev_sibling<'b, F>(&'b mut self, mut f: F)
497    where
498        F: FnMut(&mut NodeMut<'b, T>),
499    {
500        let mut current = self.prev_sibling();
501        while let Some(mut node) = current {
502            f(&mut node);
503            current = node.into_prev_sibling().ok();
504        }
505    }
506
507    /// Apply function for this node and each sibling mutable node reference.
508    pub fn for_each_sibling<F>(&mut self, mut f: F)
509    where
510        F: for<'b> FnMut(&mut NodeMut<'b, T>),
511    {
512        self.for_each_prev_sibling(&mut f);
513        f(self);
514        self.for_each_next_sibling(&mut f);
515    }
516
517    /// Apply function for each children mutable node reference.
518    pub fn for_each_child<F>(&mut self, mut f: F)
519    where
520        F: for<'b> FnMut(&mut NodeMut<'b, T>),
521    {
522        let Some(mut first_child) = self.first_child() else {
523            return;
524        };
525        f(&mut first_child);
526        first_child.for_each_next_sibling(f);
527    }
528
529    /// Apply function for this node and each descendant mutable node reference.
530    pub fn for_each_descendant<F>(&mut self, mut f: F)
531    where
532        F: FnMut(&mut NodeMut<'_, T>),
533    {
534        let id = self.id();
535
536        f(self);
537
538        // Start at our first child, if any.
539        let Some(mut node) = self.first_child() else {
540            return;
541        };
542
543        loop {
544            f(&mut node);
545
546            // Try to go deeper into its first child.
547            match node.into_first_child() {
548                Ok(child) => {
549                    node = child;
550                    continue;
551                }
552                Err(n) => {
553                    node = n;
554                }
555            }
556
557            // No deeper child, so climb until we find a next sibling or hit self.
558            loop {
559                match node.into_next_sibling() {
560                    Ok(sib) => {
561                        node = sib;
562                        break;
563                    }
564                    Err(n) => {
565                        node = n;
566                    }
567                }
568
569                // No sibling, so climb up.
570                let Ok(parent) = node.into_parent() else {
571                    unreachable!();
572                };
573                if parent.id() == id {
574                    return;
575                }
576                node = parent;
577            }
578        }
579    }
580
581    /// Appends a new child to this node.
582    pub fn append(&mut self, value: T) -> NodeMut<'_, T> {
583        let id = self.tree.orphan(value).id;
584        self.append_id(id)
585    }
586
587    /// Prepends a new child to this node.
588    pub fn prepend(&mut self, value: T) -> NodeMut<'_, T> {
589        let id = self.tree.orphan(value).id;
590        self.prepend_id(id)
591    }
592
593    /// Appends a subtree, return the root of the merged subtree.
594    pub fn append_subtree(&mut self, subtree: Tree<T>) -> NodeMut<'_, T> {
595        let root_id = self.tree.extend_tree(subtree).id;
596        self.append_id(root_id)
597    }
598
599    /// Prepends a subtree, return the root of the merged subtree.
600    pub fn prepend_subtree(&mut self, subtree: Tree<T>) -> NodeMut<'_, T> {
601        let root_id = self.tree.extend_tree(subtree).id;
602        self.prepend_id(root_id)
603    }
604
605    /// Inserts a new sibling before this node.
606    ///
607    /// # Panics
608    ///
609    /// Panics if this node is an orphan.
610    pub fn insert_before(&mut self, value: T) -> NodeMut<'_, T> {
611        let id = self.tree.orphan(value).id;
612        self.insert_id_before(id)
613    }
614
615    /// Inserts a new sibling after this node.
616    ///
617    /// # Panics
618    ///
619    /// Panics if this node is an orphan.
620    pub fn insert_after(&mut self, value: T) -> NodeMut<'_, T> {
621        let id = self.tree.orphan(value).id;
622        self.insert_id_after(id)
623    }
624
625    /// Detaches this node from its parent.
626    pub fn detach(&mut self) {
627        let parent_id = match self.node().parent {
628            Some(id) => id,
629            None => return,
630        };
631        let prev_sibling_id = self.node().prev_sibling;
632        let next_sibling_id = self.node().next_sibling;
633
634        {
635            self.node().parent = None;
636            self.node().prev_sibling = None;
637            self.node().next_sibling = None;
638        }
639
640        if let Some(id) = prev_sibling_id {
641            unsafe {
642                self.tree.node_mut(id).next_sibling = next_sibling_id;
643            }
644        }
645        if let Some(id) = next_sibling_id {
646            unsafe {
647                self.tree.node_mut(id).prev_sibling = prev_sibling_id;
648            }
649        }
650
651        let parent = unsafe { self.tree.node_mut(parent_id) };
652        let (first_child_id, last_child_id) = parent.children.unwrap();
653        if first_child_id == last_child_id {
654            parent.children = None;
655        } else if first_child_id == self.id {
656            parent.children = Some((next_sibling_id.unwrap(), last_child_id));
657        } else if last_child_id == self.id {
658            parent.children = Some((first_child_id, prev_sibling_id.unwrap()));
659        }
660    }
661
662    /// Appends a child to this node.
663    ///
664    /// # Panics
665    ///
666    /// Panics if `new_child_id` is not valid.
667    pub fn append_id(&mut self, new_child_id: NodeId) -> NodeMut<'_, T> {
668        assert_ne!(
669            self.id(),
670            new_child_id,
671            "Cannot append node as a child to itself"
672        );
673
674        let last_child_id = self.node().children.map(|(_, id)| id);
675
676        if last_child_id != Some(new_child_id) {
677            {
678                let mut new_child = self.tree.get_mut(new_child_id).unwrap();
679                new_child.detach();
680                new_child.node().parent = Some(self.id);
681                new_child.node().prev_sibling = last_child_id;
682            }
683
684            if let Some(id) = last_child_id {
685                unsafe {
686                    self.tree.node_mut(id).next_sibling = Some(new_child_id);
687                }
688            }
689
690            {
691                self.node().children = match self.node().children {
692                    Some((first_child_id, _)) => Some((first_child_id, new_child_id)),
693                    None => Some((new_child_id, new_child_id)),
694                };
695            }
696        }
697
698        unsafe { self.tree.get_unchecked_mut(new_child_id) }
699    }
700
701    /// Prepends a child to this node.
702    ///
703    /// # Panics
704    ///
705    /// Panics if `new_child_id` is not valid.
706    pub fn prepend_id(&mut self, new_child_id: NodeId) -> NodeMut<'_, T> {
707        assert_ne!(
708            self.id(),
709            new_child_id,
710            "Cannot prepend node as a child to itself"
711        );
712
713        let first_child_id = self.node().children.map(|(id, _)| id);
714
715        if first_child_id != Some(new_child_id) {
716            {
717                let mut new_child = self.tree.get_mut(new_child_id).unwrap();
718                new_child.detach();
719                new_child.node().parent = Some(self.id);
720                new_child.node().next_sibling = first_child_id;
721            }
722
723            if let Some(id) = first_child_id {
724                unsafe {
725                    self.tree.node_mut(id).prev_sibling = Some(new_child_id);
726                }
727            }
728
729            {
730                self.node().children = match self.node().children {
731                    Some((_, last_child_id)) => Some((new_child_id, last_child_id)),
732                    None => Some((new_child_id, new_child_id)),
733                };
734            }
735        }
736
737        unsafe { self.tree.get_unchecked_mut(new_child_id) }
738    }
739
740    /// Inserts a sibling before this node.
741    ///
742    /// # Panics
743    ///
744    /// - Panics if `new_sibling_id` is not valid.
745    /// - Panics if this node is an orphan.
746    pub fn insert_id_before(&mut self, new_sibling_id: NodeId) -> NodeMut<'_, T> {
747        assert_ne!(
748            self.id(),
749            new_sibling_id,
750            "Cannot insert node as a sibling of itself"
751        );
752
753        let parent_id = self.node().parent.unwrap();
754        let prev_sibling_id = self.node().prev_sibling;
755
756        {
757            let mut new_sibling = self.tree.get_mut(new_sibling_id).unwrap();
758            new_sibling.detach();
759            new_sibling.node().parent = Some(parent_id);
760            new_sibling.node().prev_sibling = prev_sibling_id;
761            new_sibling.node().next_sibling = Some(self.id);
762        }
763
764        if let Some(id) = prev_sibling_id {
765            unsafe {
766                self.tree.node_mut(id).next_sibling = Some(new_sibling_id);
767            }
768        }
769
770        self.node().prev_sibling = Some(new_sibling_id);
771
772        {
773            let parent = unsafe { self.tree.node_mut(parent_id) };
774            let (first_child_id, last_child_id) = parent.children.unwrap();
775            if first_child_id == self.id {
776                parent.children = Some((new_sibling_id, last_child_id));
777            }
778        }
779
780        unsafe { self.tree.get_unchecked_mut(new_sibling_id) }
781    }
782
783    /// Inserts a sibling after this node.
784    ///
785    /// # Panics
786    ///
787    /// - Panics if `new_sibling_id` is not valid.
788    /// - Panics if this node is an orphan.
789    pub fn insert_id_after(&mut self, new_sibling_id: NodeId) -> NodeMut<'_, T> {
790        assert_ne!(
791            self.id(),
792            new_sibling_id,
793            "Cannot insert node as a sibling of itself"
794        );
795
796        let parent_id = self.node().parent.unwrap();
797        let next_sibling_id = self.node().next_sibling;
798
799        {
800            let mut new_sibling = self.tree.get_mut(new_sibling_id).unwrap();
801            new_sibling.detach();
802            new_sibling.node().parent = Some(parent_id);
803            new_sibling.node().prev_sibling = Some(self.id);
804            new_sibling.node().next_sibling = next_sibling_id;
805        }
806
807        if let Some(id) = next_sibling_id {
808            unsafe {
809                self.tree.node_mut(id).prev_sibling = Some(new_sibling_id);
810            }
811        }
812
813        self.node().next_sibling = Some(new_sibling_id);
814
815        {
816            let parent = unsafe { self.tree.node_mut(parent_id) };
817            let (first_child_id, last_child_id) = parent.children.unwrap();
818            if last_child_id == self.id {
819                parent.children = Some((first_child_id, new_sibling_id));
820            }
821        }
822
823        unsafe { self.tree.get_unchecked_mut(new_sibling_id) }
824    }
825
826    /// Reparents the children of a node, appending them to this node.
827    ///
828    /// # Panics
829    ///
830    /// Panics if `from_id` is not valid.
831    pub fn reparent_from_id_append(&mut self, from_id: NodeId) {
832        assert_ne!(
833            self.id(),
834            from_id,
835            "Cannot reparent node's children to itself"
836        );
837
838        let new_child_ids = {
839            let mut from = self.tree.get_mut(from_id).unwrap();
840            match from.node().children.take() {
841                Some(ids) => ids,
842                None => return,
843            }
844        };
845
846        let mut child_id = new_child_ids.0;
847        loop {
848            let child = unsafe { self.tree.node_mut(child_id) };
849            child.parent = Some(self.id);
850            child_id = match child.next_sibling {
851                Some(id) => id,
852                None => break,
853            };
854        }
855
856        if self.node().children.is_none() {
857            self.node().children = Some(new_child_ids);
858            return;
859        }
860
861        let old_child_ids = self.node().children.unwrap();
862        unsafe {
863            self.tree.node_mut(old_child_ids.1).next_sibling = Some(new_child_ids.0);
864            self.tree.node_mut(new_child_ids.0).prev_sibling = Some(old_child_ids.1);
865        }
866
867        self.node().children = Some((old_child_ids.0, new_child_ids.1));
868    }
869
870    /// Reparents the children of a node, prepending them to this node.
871    ///
872    /// # Panics
873    ///
874    /// Panics if `from_id` is not valid.
875    pub fn reparent_from_id_prepend(&mut self, from_id: NodeId) {
876        assert_ne!(
877            self.id(),
878            from_id,
879            "Cannot reparent node's children to itself"
880        );
881
882        let new_child_ids = {
883            let mut from = self.tree.get_mut(from_id).unwrap();
884            match from.node().children.take() {
885                Some(ids) => ids,
886                None => return,
887            }
888        };
889
890        let mut child_id = new_child_ids.0;
891        loop {
892            let child = unsafe { self.tree.node_mut(child_id) };
893            child.parent = Some(self.id);
894            child_id = match child.next_sibling {
895                Some(id) => id,
896                None => break,
897            };
898        }
899
900        if self.node().children.is_none() {
901            self.node().children = Some(new_child_ids);
902            return;
903        }
904
905        let old_child_ids = self.node().children.unwrap();
906        unsafe {
907            self.tree.node_mut(old_child_ids.0).prev_sibling = Some(new_child_ids.1);
908            self.tree.node_mut(new_child_ids.1).next_sibling = Some(old_child_ids.0);
909        }
910
911        self.node().children = Some((new_child_ids.0, old_child_ids.1));
912    }
913
914    /// Clone a subtree as orphan, returning the cloned root node.
915    pub fn clone_subtree(&mut self) -> NodeMut<'_, T>
916    where
917        T: Clone,
918    {
919        enum Edge {
920            Open {
921                cur: NodeId,
922                cloned_parent: Option<NodeId>,
923            },
924            Close {
925                cur: NodeId,
926                cloned_cur: NodeId,
927                cloned_parent: Option<NodeId>,
928            },
929        }
930
931        let mut edge = Edge::Open {
932            cur: self.id,
933            cloned_parent: None,
934        };
935
936        loop {
937            match edge {
938                Edge::Open { cur, cloned_parent } => {
939                    let node = unsafe { self.tree.node(cur) };
940                    let first_child = node.children.map(|(id, _)| id);
941
942                    let cloned_value = node.value.clone();
943                    let cloned_node = self.tree.orphan(cloned_value).id;
944
945                    if let Some(cloned_parent) = cloned_parent {
946                        unsafe {
947                            self.tree
948                                .get_unchecked_mut(cloned_parent)
949                                .append_id(cloned_node);
950                        }
951                    }
952
953                    if let Some(first_child) = first_child {
954                        edge = Edge::Open {
955                            cur: first_child,
956                            cloned_parent: Some(cloned_node),
957                        };
958                    } else {
959                        edge = Edge::Close {
960                            cur,
961                            cloned_cur: cloned_node,
962                            cloned_parent,
963                        };
964                    }
965                }
966                Edge::Close {
967                    cur,
968                    cloned_cur,
969                    cloned_parent,
970                } => {
971                    if cur == self.id {
972                        return unsafe { self.tree.get_unchecked_mut(cloned_cur) };
973                    }
974
975                    let node = unsafe { self.tree.node(cur) };
976                    if let Some(next_sibling) = node.next_sibling {
977                        edge = Edge::Open {
978                            cur: next_sibling,
979                            cloned_parent,
980                        };
981                    } else {
982                        // Since the current node is not the root, both its parent and
983                        // cloned node parent are guaranteed to exist.
984                        let parent = node.parent.unwrap();
985                        let cloned_node = unsafe { self.tree.node(cloned_cur) };
986                        let cloned_parent = cloned_node.parent.unwrap();
987                        let cloned_grandparent = unsafe { self.tree.node(cloned_parent).parent };
988
989                        edge = Edge::Close {
990                            cur: parent,
991                            cloned_cur: cloned_parent,
992                            cloned_parent: cloned_grandparent,
993                        };
994                    }
995                }
996            }
997        }
998    }
999}
1000
1001impl<'a, T: 'a> From<NodeMut<'a, T>> for NodeRef<'a, T> {
1002    fn from(node: NodeMut<'a, T>) -> Self {
1003        unsafe { node.tree.get_unchecked(node.id) }
1004    }
1005}
1006
1007/// Iterators.
1008pub mod iter;
1009
1010/// Creates a tree from expressions.
1011///
1012/// # Examples
1013///
1014/// ```
1015/// #[macro_use] extern crate ego_tree;
1016/// # fn main() {
1017/// let tree = tree!("root");
1018/// # }
1019/// ```
1020///
1021/// ```
1022/// #[macro_use] extern crate ego_tree;
1023/// # fn main() {
1024/// let tree = tree! {
1025///     "root" => {
1026///         "child a",
1027///         "child b" => {
1028///             "grandchild a",
1029///             "grandchild b",
1030///         },
1031///         "child c",
1032///     }
1033/// };
1034/// # }
1035/// ```
1036/// Compose trees using the `@` marker:
1037/// ```
1038/// #[macro_use] extern crate ego_tree;
1039/// # fn main() {
1040/// let subtree = tree! {
1041///     "foo" => { "bar", "baz" }
1042/// };
1043/// let new_tree = tree! {
1044///     "root" => {
1045///         "child x",
1046///         "child y",
1047///         @ subtree,
1048///     }
1049/// };
1050/// # }
1051/// ```
1052#[macro_export]
1053macro_rules! tree {
1054    (@ $n:ident { }) => { };
1055
1056    // Last leaf.
1057    (@ $n:ident { $value:expr }) => {
1058        { $n.append($value); }
1059    };
1060
1061    // Leaf.
1062    (@ $n:ident { $value:expr, $($tail:tt)* }) => {
1063        {
1064            $n.append($value);
1065            tree!(@ $n { $($tail)* });
1066        }
1067    };
1068
1069    // Last node with children.
1070    (@ $n:ident { $value:expr => $children:tt }) => {
1071        {
1072            let mut node = $n.append($value);
1073            tree!(@ node $children);
1074        }
1075    };
1076
1077    // Node with children.
1078    (@ $n:ident { $value:expr => $children:tt, $($tail:tt)* }) => {
1079        {
1080            {
1081                let mut node = $n.append($value);
1082                tree!(@ node $children);
1083            }
1084            tree!(@ $n { $($tail)* });
1085        }
1086    };
1087
1088    // Append subtree from expression.
1089    (@ $n:ident { @ $subtree:expr $(, $($tail:tt)*)? }) => {{
1090        $n.append_subtree($subtree);
1091        $( tree!(@ $n { $($tail)* }); )?
1092    }};
1093
1094
1095    ($root:expr) => { $crate::Tree::new($root) };
1096
1097    ($root:expr => $children:tt) => {
1098        {
1099            let mut tree = $crate::Tree::new($root);
1100            {
1101                let mut node = tree.root_mut();
1102                tree!(@ node $children);
1103            }
1104            tree
1105        }
1106    };
1107}
1108
1109impl<T: Debug> Debug for Tree<T> {
1110    fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
1111        use crate::iter::Edge;
1112        if f.alternate() {
1113            write!(f, "Tree {{")?;
1114            for edge in self.root().traverse() {
1115                match edge {
1116                    Edge::Open(node) if node.has_children() => {
1117                        write!(f, " {:?} => {{", node.value())?;
1118                    }
1119                    Edge::Open(node) if node.next_sibling().is_some() => {
1120                        write!(f, " {:?},", node.value())?;
1121                    }
1122                    Edge::Open(node) => {
1123                        write!(f, " {:?}", node.value())?;
1124                    }
1125                    Edge::Close(node) if node.has_children() => {
1126                        if node.next_sibling().is_some() {
1127                            write!(f, " }},")?;
1128                        } else {
1129                            write!(f, " }}")?;
1130                        }
1131                    }
1132                    _ => {}
1133                }
1134            }
1135            write!(f, " }}")
1136        } else {
1137            f.debug_struct("Tree").field("vec", &self.vec).finish()
1138        }
1139    }
1140}
1141
1142// Handles display
1143mod display;
1144
1145impl<T: Display> Display for Tree<T> {
1146    fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
1147        use crate::display::Indentation;
1148        use crate::iter::Edge;
1149
1150        let mut indent: Indentation = Indentation::new(true);
1151
1152        for edge in self.root().traverse() {
1153            match edge {
1154                Edge::Open(node) if node.has_children() => {
1155                    indent.indent(node.next_sibling().is_some());
1156                    writeln!(f, "{indent}{}", node.value())?;
1157                }
1158                Edge::Open(node) => {
1159                    indent.indent(node.next_sibling().is_some());
1160                    writeln!(f, "{indent}{}", node.value())?;
1161                    indent.deindent();
1162                }
1163                Edge::Close(node) if node.has_children() => {
1164                    indent.deindent();
1165                }
1166                _ => {}
1167            }
1168        }
1169        Ok(())
1170    }
1171}
1172
1173mod sort;