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.extend(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    fn axis<F>(&mut self, f: F) -> Option<NodeMut<T>>
373    where
374        F: FnOnce(&mut Node<T>) -> Option<NodeId>,
375    {
376        let id = f(self.node());
377        id.map(move |id| unsafe { self.tree.get_unchecked_mut(id) })
378    }
379
380    fn into_axis<F>(mut self, f: F) -> Result<Self, Self>
381    where
382        F: FnOnce(&mut Node<T>) -> Option<NodeId>,
383    {
384        let id = f(self.node());
385        match id {
386            Some(id) => Ok(unsafe { self.tree.get_unchecked_mut(id) }),
387            None => Err(self),
388        }
389    }
390
391    /// Returns the parent of this node.
392    pub fn parent(&mut self) -> Option<NodeMut<T>> {
393        self.axis(|node| node.parent)
394    }
395
396    /// Returns the parent of this node.
397    ///
398    /// Returns `Ok(parent)` if possible and `Err(self)` otherwise
399    /// so the caller can recover the current position.
400    pub fn into_parent(self) -> Result<Self, Self> {
401        self.into_axis(|node| node.parent)
402    }
403
404    /// Returns the previous sibling of this node.
405    pub fn prev_sibling(&mut self) -> Option<NodeMut<T>> {
406        self.axis(|node| node.prev_sibling)
407    }
408
409    /// Returns the previous sibling of this node.
410    ///
411    /// Returns `Ok(prev_sibling)` if possible and `Err(self)` otherwise
412    /// so the caller can recover the current position.
413    pub fn into_prev_sibling(self) -> Result<Self, Self> {
414        self.into_axis(|node| node.prev_sibling)
415    }
416
417    /// Returns the next sibling of this node.
418    pub fn next_sibling(&mut self) -> Option<NodeMut<T>> {
419        self.axis(|node| node.next_sibling)
420    }
421
422    /// Returns the next sibling of this node.
423    ///
424    /// Returns `Ok(next_sibling)` if possible and `Err(self)` otherwise
425    /// so the caller can recover the current position.
426    pub fn into_next_sibling(self) -> Result<Self, Self> {
427        self.into_axis(|node| node.next_sibling)
428    }
429
430    /// Returns the first child of this node.
431    pub fn first_child(&mut self) -> Option<NodeMut<T>> {
432        self.axis(|node| node.children.map(|(id, _)| id))
433    }
434
435    /// Returns the first child of this node.
436    ///
437    /// Returns `Ok(first_child)` if possible and `Err(self)` otherwise
438    /// so the caller can recover the current position.
439    pub fn into_first_child(self) -> Result<Self, Self> {
440        self.into_axis(|node| node.children.map(|(id, _)| id))
441    }
442
443    /// Returns the last child of this node.
444    pub fn last_child(&mut self) -> Option<NodeMut<T>> {
445        self.axis(|node| node.children.map(|(_, id)| id))
446    }
447
448    /// Returns the last child of this node.
449    ///
450    /// Returns `Ok(last_child)` if possible and `Err(self)` otherwise
451    /// so the caller can recover the current position.
452    pub fn into_last_child(self) -> Result<Self, Self> {
453        self.into_axis(|node| node.children.map(|(_, id)| id))
454    }
455
456    /// Returns true if this node has siblings.
457    pub fn has_siblings(&self) -> bool {
458        unsafe { self.tree.get_unchecked(self.id).has_siblings() }
459    }
460
461    /// Returns true if this node has children.
462    pub fn has_children(&self) -> bool {
463        unsafe { self.tree.get_unchecked(self.id).has_children() }
464    }
465
466    /// Appends a new child to this node.
467    pub fn append(&mut self, value: T) -> NodeMut<T> {
468        let id = self.tree.orphan(value).id;
469        self.append_id(id)
470    }
471
472    /// Prepends a new child to this node.
473    pub fn prepend(&mut self, value: T) -> NodeMut<T> {
474        let id = self.tree.orphan(value).id;
475        self.prepend_id(id)
476    }
477
478    /// Appends a subtree, return the root of the merged subtree.
479    pub fn append_subtree(&mut self, subtree: Tree<T>) -> NodeMut<T> {
480        let root_id = self.tree.extend_tree(subtree).id;
481        self.append_id(root_id)
482    }
483
484    /// Prepends a subtree, return the root of the merged subtree.
485    pub fn prepend_subtree(&mut self, subtree: Tree<T>) -> NodeMut<T> {
486        let root_id = self.tree.extend_tree(subtree).id;
487        self.prepend_id(root_id)
488    }
489
490    /// Inserts a new sibling before this node.
491    ///
492    /// # Panics
493    ///
494    /// Panics if this node is an orphan.
495    pub fn insert_before(&mut self, value: T) -> NodeMut<T> {
496        let id = self.tree.orphan(value).id;
497        self.insert_id_before(id)
498    }
499
500    /// Inserts a new sibling after this node.
501    ///
502    /// # Panics
503    ///
504    /// Panics if this node is an orphan.
505    pub fn insert_after(&mut self, value: T) -> NodeMut<T> {
506        let id = self.tree.orphan(value).id;
507        self.insert_id_after(id)
508    }
509
510    /// Detaches this node from its parent.
511    pub fn detach(&mut self) {
512        let parent_id = match self.node().parent {
513            Some(id) => id,
514            None => return,
515        };
516        let prev_sibling_id = self.node().prev_sibling;
517        let next_sibling_id = self.node().next_sibling;
518
519        {
520            self.node().parent = None;
521            self.node().prev_sibling = None;
522            self.node().next_sibling = None;
523        }
524
525        if let Some(id) = prev_sibling_id {
526            unsafe {
527                self.tree.node_mut(id).next_sibling = next_sibling_id;
528            }
529        }
530        if let Some(id) = next_sibling_id {
531            unsafe {
532                self.tree.node_mut(id).prev_sibling = prev_sibling_id;
533            }
534        }
535
536        let parent = unsafe { self.tree.node_mut(parent_id) };
537        let (first_child_id, last_child_id) = parent.children.unwrap();
538        if first_child_id == last_child_id {
539            parent.children = None;
540        } else if first_child_id == self.id {
541            parent.children = Some((next_sibling_id.unwrap(), last_child_id));
542        } else if last_child_id == self.id {
543            parent.children = Some((first_child_id, prev_sibling_id.unwrap()));
544        }
545    }
546
547    /// Appends a child to this node.
548    ///
549    /// # Panics
550    ///
551    /// Panics if `new_child_id` is not valid.
552    pub fn append_id(&mut self, new_child_id: NodeId) -> NodeMut<T> {
553        assert_ne!(
554            self.id(),
555            new_child_id,
556            "Cannot append node as a child to itself"
557        );
558
559        let last_child_id = self.node().children.map(|(_, id)| id);
560
561        if last_child_id != Some(new_child_id) {
562            {
563                let mut new_child = self.tree.get_mut(new_child_id).unwrap();
564                new_child.detach();
565                new_child.node().parent = Some(self.id);
566                new_child.node().prev_sibling = last_child_id;
567            }
568
569            if let Some(id) = last_child_id {
570                unsafe {
571                    self.tree.node_mut(id).next_sibling = Some(new_child_id);
572                }
573            }
574
575            {
576                self.node().children = match self.node().children {
577                    Some((first_child_id, _)) => Some((first_child_id, new_child_id)),
578                    None => Some((new_child_id, new_child_id)),
579                };
580            }
581        }
582
583        unsafe { self.tree.get_unchecked_mut(new_child_id) }
584    }
585
586    /// Prepends a child to this node.
587    ///
588    /// # Panics
589    ///
590    /// Panics if `new_child_id` is not valid.
591    pub fn prepend_id(&mut self, new_child_id: NodeId) -> NodeMut<T> {
592        assert_ne!(
593            self.id(),
594            new_child_id,
595            "Cannot prepend node as a child to itself"
596        );
597
598        let first_child_id = self.node().children.map(|(id, _)| id);
599
600        if first_child_id != Some(new_child_id) {
601            {
602                let mut new_child = self.tree.get_mut(new_child_id).unwrap();
603                new_child.detach();
604                new_child.node().parent = Some(self.id);
605                new_child.node().next_sibling = first_child_id;
606            }
607
608            if let Some(id) = first_child_id {
609                unsafe {
610                    self.tree.node_mut(id).prev_sibling = Some(new_child_id);
611                }
612            }
613
614            {
615                self.node().children = match self.node().children {
616                    Some((_, last_child_id)) => Some((new_child_id, last_child_id)),
617                    None => Some((new_child_id, new_child_id)),
618                };
619            }
620        }
621
622        unsafe { self.tree.get_unchecked_mut(new_child_id) }
623    }
624
625    /// Inserts a sibling before this node.
626    ///
627    /// # Panics
628    ///
629    /// - Panics if `new_sibling_id` is not valid.
630    /// - Panics if this node is an orphan.
631    pub fn insert_id_before(&mut self, new_sibling_id: NodeId) -> NodeMut<T> {
632        assert_ne!(
633            self.id(),
634            new_sibling_id,
635            "Cannot insert node as a sibling of itself"
636        );
637
638        let parent_id = self.node().parent.unwrap();
639        let prev_sibling_id = self.node().prev_sibling;
640
641        {
642            let mut new_sibling = self.tree.get_mut(new_sibling_id).unwrap();
643            new_sibling.detach();
644            new_sibling.node().parent = Some(parent_id);
645            new_sibling.node().prev_sibling = prev_sibling_id;
646            new_sibling.node().next_sibling = Some(self.id);
647        }
648
649        if let Some(id) = prev_sibling_id {
650            unsafe {
651                self.tree.node_mut(id).next_sibling = Some(new_sibling_id);
652            }
653        }
654
655        self.node().prev_sibling = Some(new_sibling_id);
656
657        {
658            let parent = unsafe { self.tree.node_mut(parent_id) };
659            let (first_child_id, last_child_id) = parent.children.unwrap();
660            if first_child_id == self.id {
661                parent.children = Some((new_sibling_id, last_child_id));
662            }
663        }
664
665        unsafe { self.tree.get_unchecked_mut(new_sibling_id) }
666    }
667
668    /// Inserts a sibling after this node.
669    ///
670    /// # Panics
671    ///
672    /// - Panics if `new_sibling_id` is not valid.
673    /// - Panics if this node is an orphan.
674    pub fn insert_id_after(&mut self, new_sibling_id: NodeId) -> NodeMut<T> {
675        assert_ne!(
676            self.id(),
677            new_sibling_id,
678            "Cannot insert node as a sibling of itself"
679        );
680
681        let parent_id = self.node().parent.unwrap();
682        let next_sibling_id = self.node().next_sibling;
683
684        {
685            let mut new_sibling = self.tree.get_mut(new_sibling_id).unwrap();
686            new_sibling.detach();
687            new_sibling.node().parent = Some(parent_id);
688            new_sibling.node().prev_sibling = Some(self.id);
689            new_sibling.node().next_sibling = next_sibling_id;
690        }
691
692        if let Some(id) = next_sibling_id {
693            unsafe {
694                self.tree.node_mut(id).prev_sibling = Some(new_sibling_id);
695            }
696        }
697
698        self.node().next_sibling = Some(new_sibling_id);
699
700        {
701            let parent = unsafe { self.tree.node_mut(parent_id) };
702            let (first_child_id, last_child_id) = parent.children.unwrap();
703            if last_child_id == self.id {
704                parent.children = Some((first_child_id, new_sibling_id));
705            }
706        }
707
708        unsafe { self.tree.get_unchecked_mut(new_sibling_id) }
709    }
710
711    /// Reparents the children of a node, appending them to this node.
712    ///
713    /// # Panics
714    ///
715    /// Panics if `from_id` is not valid.
716    pub fn reparent_from_id_append(&mut self, from_id: NodeId) {
717        assert_ne!(
718            self.id(),
719            from_id,
720            "Cannot reparent node's children to itself"
721        );
722
723        let new_child_ids = {
724            let mut from = self.tree.get_mut(from_id).unwrap();
725            match from.node().children.take() {
726                Some(ids) => ids,
727                None => return,
728            }
729        };
730
731        unsafe {
732            self.tree.node_mut(new_child_ids.0).parent = Some(self.id);
733            self.tree.node_mut(new_child_ids.1).parent = Some(self.id);
734        }
735
736        if self.node().children.is_none() {
737            self.node().children = Some(new_child_ids);
738            return;
739        }
740
741        let old_child_ids = self.node().children.unwrap();
742        unsafe {
743            self.tree.node_mut(old_child_ids.1).next_sibling = Some(new_child_ids.0);
744            self.tree.node_mut(new_child_ids.0).prev_sibling = Some(old_child_ids.1);
745        }
746
747        self.node().children = Some((old_child_ids.0, new_child_ids.1));
748    }
749
750    /// Reparents the children of a node, prepending them to this node.
751    ///
752    /// # Panics
753    ///
754    /// Panics if `from_id` is not valid.
755    pub fn reparent_from_id_prepend(&mut self, from_id: NodeId) {
756        assert_ne!(
757            self.id(),
758            from_id,
759            "Cannot reparent node's children to itself"
760        );
761
762        let new_child_ids = {
763            let mut from = self.tree.get_mut(from_id).unwrap();
764            match from.node().children.take() {
765                Some(ids) => ids,
766                None => return,
767            }
768        };
769
770        unsafe {
771            self.tree.node_mut(new_child_ids.0).parent = Some(self.id);
772            self.tree.node_mut(new_child_ids.1).parent = Some(self.id);
773        }
774
775        if self.node().children.is_none() {
776            self.node().children = Some(new_child_ids);
777            return;
778        }
779
780        let old_child_ids = self.node().children.unwrap();
781        unsafe {
782            self.tree.node_mut(old_child_ids.0).prev_sibling = Some(new_child_ids.1);
783            self.tree.node_mut(new_child_ids.1).next_sibling = Some(old_child_ids.0);
784        }
785
786        self.node().children = Some((new_child_ids.0, old_child_ids.1));
787    }
788}
789
790impl<'a, T: 'a> From<NodeMut<'a, T>> for NodeRef<'a, T> {
791    fn from(node: NodeMut<'a, T>) -> Self {
792        unsafe { node.tree.get_unchecked(node.id) }
793    }
794}
795
796/// Iterators.
797pub mod iter;
798
799/// Creates a tree from expressions.
800///
801/// # Examples
802///
803/// ```
804/// #[macro_use] extern crate ego_tree;
805/// # fn main() {
806/// let tree = tree!("root");
807/// # }
808/// ```
809///
810/// ```
811/// #[macro_use] extern crate ego_tree;
812/// # fn main() {
813/// let tree = tree! {
814///     "root" => {
815///         "child a",
816///         "child b" => {
817///             "grandchild a",
818///             "grandchild b",
819///         },
820///         "child c",
821///     }
822/// };
823/// # }
824/// ```
825#[macro_export]
826macro_rules! tree {
827    (@ $n:ident { }) => { };
828
829    // Last leaf.
830    (@ $n:ident { $value:expr }) => {
831        { $n.append($value); }
832    };
833
834    // Leaf.
835    (@ $n:ident { $value:expr, $($tail:tt)* }) => {
836        {
837            $n.append($value);
838            tree!(@ $n { $($tail)* });
839        }
840    };
841
842    // Last node with children.
843    (@ $n:ident { $value:expr => $children:tt }) => {
844        {
845            let mut node = $n.append($value);
846            tree!(@ node $children);
847        }
848    };
849
850    // Node with children.
851    (@ $n:ident { $value:expr => $children:tt, $($tail:tt)* }) => {
852        {
853            {
854                let mut node = $n.append($value);
855                tree!(@ node $children);
856            }
857            tree!(@ $n { $($tail)* });
858        }
859    };
860
861    ($root:expr) => { $crate::Tree::new($root) };
862
863    ($root:expr => $children:tt) => {
864        {
865            let mut tree = $crate::Tree::new($root);
866            {
867                let mut node = tree.root_mut();
868                tree!(@ node $children);
869            }
870            tree
871        }
872    };
873}
874
875impl<T: Debug> Debug for Tree<T> {
876    fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
877        use crate::iter::Edge;
878        if f.alternate() {
879            write!(f, "Tree {{")?;
880            for edge in self.root().traverse() {
881                match edge {
882                    Edge::Open(node) if node.has_children() => {
883                        write!(f, " {:?} => {{", node.value())?;
884                    }
885                    Edge::Open(node) if node.next_sibling().is_some() => {
886                        write!(f, " {:?},", node.value())?;
887                    }
888                    Edge::Open(node) => {
889                        write!(f, " {:?}", node.value())?;
890                    }
891                    Edge::Close(node) if node.has_children() => {
892                        if node.next_sibling().is_some() {
893                            write!(f, " }},")?;
894                        } else {
895                            write!(f, " }}")?;
896                        }
897                    }
898                    _ => {}
899                }
900            }
901            write!(f, " }}")
902        } else {
903            f.debug_struct("Tree").field("vec", &self.vec).finish()
904        }
905    }
906}
907
908// Handles display
909mod display;
910
911impl<T: Display> Display for Tree<T> {
912    fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
913        use crate::display::Indentation;
914        use crate::iter::Edge;
915
916        let mut indent: Indentation = Indentation::new(true);
917
918        for edge in self.root().traverse() {
919            match edge {
920                Edge::Open(node) if node.has_children() => {
921                    indent.indent(node.next_sibling().is_some());
922                    writeln!(f, "{indent}{}", node.value())?;
923                }
924                Edge::Open(node) => {
925                    indent.indent(node.next_sibling().is_some());
926                    writeln!(f, "{indent}{}", node.value())?;
927                    indent.deindent();
928                }
929                Edge::Close(node) if node.has_children() => {
930                    indent.deindent();
931                }
932                _ => {}
933            }
934        }
935        Ok(())
936    }
937}
938
939mod sort;