svgdom/
tree.rs

1/*!
2rctree is a "DOM-like" tree implemented using reference counting.
3*/
4
5// This is a copy of the https://github.com/RazrFalcon/rctree
6//
7// Changes:
8// - Node::new marked as private
9// - Node::borrow marked as private
10// - Node::borrow_mut marked as private
11// - Node::make_copy removed
12// - Node::make_deep_copy removed
13
14use std::fmt;
15use std::cell::{RefCell, Ref, RefMut};
16use std::rc::{Rc, Weak};
17
18type Link<T> = Rc<RefCell<NodeData<T>>>;
19type WeakLink<T> = Weak<RefCell<NodeData<T>>>;
20
21/// A reference to a node holding a value of type `T`. Nodes form a tree.
22///
23/// Internally, this uses reference counting for lifetime tracking
24/// and `std::cell::RefCell` for interior mutability.
25///
26/// **Note:** Cloning a `Node` only increments a reference count. It does not copy the data.
27pub struct Node<T>(Link<T>);
28
29struct NodeData<T> {
30    root: Option<WeakLink<T>>,
31    parent: Option<WeakLink<T>>,
32    first_child: Option<Link<T>>,
33    last_child: Option<WeakLink<T>>,
34    previous_sibling: Option<WeakLink<T>>,
35    next_sibling: Option<Link<T>>,
36    data: T,
37}
38
39/// Cloning a `Node` only increments a reference count. It does not copy the data.
40impl<T> Clone for Node<T> {
41    fn clone(&self) -> Self {
42        Node(Rc::clone(&self.0))
43    }
44}
45
46impl<T> PartialEq for Node<T> {
47    fn eq(&self, other: &Node<T>) -> bool {
48        Rc::ptr_eq(&self.0, &other.0)
49    }
50}
51
52impl<T: fmt::Debug> fmt::Debug for Node<T> {
53    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
54        fmt::Debug::fmt(&*self.borrow(), f)
55    }
56}
57
58impl<T: fmt::Display> fmt::Display for Node<T> {
59    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
60        fmt::Display::fmt(&*self.borrow(), f)
61    }
62}
63
64
65macro_rules! try_opt {
66    ($expr: expr) => {
67        match $expr {
68            Some(value) => value,
69            None => return None
70        }
71    }
72}
73
74
75impl<T> Node<T> {
76    /// Creates a new node from its associated data.
77    pub(crate) fn new(data: T) -> Node<T> {
78        Node(Rc::new(RefCell::new(NodeData {
79            root: None,
80            parent: None,
81            first_child: None,
82            last_child: None,
83            previous_sibling: None,
84            next_sibling: None,
85            data,
86        })))
87    }
88
89    /// Returns a root node.
90    ///
91    /// If the current node is the root node - will return itself.
92    ///
93    /// # Panics
94    ///
95    /// Panics if the node is currently mutably borrowed.
96    pub fn root(&self) -> Node<T> {
97        match self.0.borrow().root.as_ref() {
98            Some(v) => Node(v.upgrade().unwrap()),
99            None => self.clone(),
100        }
101    }
102
103    /// Returns a parent node, unless this node is the root of the tree.
104    ///
105    /// # Panics
106    ///
107    /// Panics if the node is currently mutably borrowed.
108    pub fn parent(&self) -> Option<Node<T>> {
109        Some(Node(try_opt!(try_opt!(self.0.borrow().parent.as_ref()).upgrade())))
110    }
111
112    /// Returns a first child of this node, unless it has no child.
113    ///
114    /// # Panics
115    ///
116    /// Panics if the node is currently mutably borrowed.
117    pub fn first_child(&self) -> Option<Node<T>> {
118        Some(Node(try_opt!(self.0.borrow().first_child.as_ref()).clone()))
119    }
120
121    /// Returns a last child of this node, unless it has no child.
122    ///
123    /// # Panics
124    ///
125    /// Panics if the node is currently mutably borrowed.
126    pub fn last_child(&self) -> Option<Node<T>> {
127        Some(Node(try_opt!(try_opt!(self.0.borrow().last_child.as_ref()).upgrade())))
128    }
129
130    /// Returns the previous sibling of this node, unless it is a first child.
131    ///
132    /// # Panics
133    ///
134    /// Panics if the node is currently mutably borrowed.
135    pub fn previous_sibling(&self) -> Option<Node<T>> {
136        Some(Node(try_opt!(try_opt!(self.0.borrow().previous_sibling.as_ref()).upgrade())))
137    }
138
139    /// Returns the next sibling of this node, unless it is a last child.
140    ///
141    /// # Panics
142    ///
143    /// Panics if the node is currently mutably borrowed.
144    pub fn next_sibling(&self) -> Option<Node<T>> {
145        Some(Node(try_opt!(self.0.borrow().next_sibling.as_ref()).clone()))
146    }
147
148    /// Returns a shared reference to this node's data
149    ///
150    /// # Panics
151    ///
152    /// Panics if the node is currently mutably borrowed.
153    pub(crate) fn borrow(&self) -> Ref<T> {
154        Ref::map(self.0.borrow(), |v| &v.data)
155    }
156
157    /// Returns a unique/mutable reference to this node's data
158    ///
159    /// # Panics
160    ///
161    /// Panics if the node is currently borrowed.
162    pub(crate) fn borrow_mut(&mut self) -> RefMut<T> {
163        RefMut::map(self.0.borrow_mut(), |v| &mut v.data)
164    }
165
166    /// Returns an iterator of nodes to this node and its ancestors.
167    ///
168    /// Includes the current node.
169    pub fn ancestors(&self) -> Ancestors<T> {
170        Ancestors(Some(self.clone()))
171    }
172
173    /// Returns an iterator of nodes to this node and the siblings before it.
174    ///
175    /// Includes the current node.
176    pub fn preceding_siblings(&self) -> PrecedingSiblings<T> {
177        PrecedingSiblings(Some(self.clone()))
178    }
179
180    /// Returns an iterator of nodes to this node and the siblings after it.
181    ///
182    /// Includes the current node.
183    pub fn following_siblings(&self) -> FollowingSiblings<T> {
184        FollowingSiblings(Some(self.clone()))
185    }
186
187    /// Returns an iterator of nodes to this node's children.
188    ///
189    /// # Panics
190    ///
191    /// Panics if the node is currently mutably borrowed.
192    pub fn children(&self) -> Children<T> {
193        Children {
194            next: self.first_child(),
195            next_back: self.last_child(),
196        }
197    }
198
199    /// Returns `true` if this node has children nodes.
200    ///
201    /// # Panics
202    ///
203    /// Panics if the node is currently mutably borrowed.
204    pub fn has_children(&self) -> bool {
205        self.first_child().is_some()
206    }
207
208    /// Returns an iterator of nodes to this node and its descendants, in tree order.
209    ///
210    /// Includes the current node.
211    pub fn descendants(&self) -> Descendants<T> {
212        Descendants(self.traverse())
213    }
214
215    /// Returns an iterator of nodes to this node and its descendants, in tree order.
216    pub fn traverse(&self) -> Traverse<T> {
217        Traverse {
218            root: self.clone(),
219            next: Some(NodeEdge::Start(self.clone())),
220            next_back: Some(NodeEdge::End(self.clone())),
221        }
222    }
223
224    /// Detaches a node from its parent and siblings. Children are not affected.
225    ///
226    /// # Panics
227    ///
228    /// Panics if the node or one of its adjoining nodes is currently borrowed.
229    pub fn detach(&mut self) {
230        self.0.borrow_mut().detach();
231    }
232
233    /// Appends a new child to this node, after existing children.
234    ///
235    /// # Panics
236    ///
237    /// Panics if the node, the new child, or one of their adjoining nodes is currently borrowed.
238    pub fn append(&mut self, new_child: Node<T>) {
239        assert!(*self != new_child, "a node cannot be appended to itself");
240
241        let mut self_borrow = self.0.borrow_mut();
242        let mut last_child_opt = None;
243        {
244            let mut new_child_borrow = new_child.0.borrow_mut();
245            new_child_borrow.detach();
246            new_child_borrow.root = Some(self_borrow.root.clone().unwrap_or(Rc::downgrade(&self.0)));
247            new_child_borrow.parent = Some(Rc::downgrade(&self.0));
248            if let Some(last_child_weak) = self_borrow.last_child.take() {
249                if let Some(last_child_strong) = last_child_weak.upgrade() {
250                    new_child_borrow.previous_sibling = Some(last_child_weak);
251                    last_child_opt = Some(last_child_strong);
252                }
253            }
254            self_borrow.last_child = Some(Rc::downgrade(&new_child.0));
255        }
256
257        if let Some(last_child_strong) = last_child_opt {
258            let mut last_child_borrow = last_child_strong.borrow_mut();
259            debug_assert!(last_child_borrow.next_sibling.is_none());
260            last_child_borrow.next_sibling = Some(new_child.0);
261        } else {
262            // No last child
263            debug_assert!(self_borrow.first_child.is_none());
264            self_borrow.first_child = Some(new_child.0);
265        }
266    }
267
268    /// Prepends a new child to this node, before existing children.
269    ///
270    /// # Panics
271    ///
272    /// Panics if the node, the new child, or one of their adjoining nodes is currently borrowed.
273    pub fn prepend(&mut self, new_child: Node<T>) {
274        assert!(*self != new_child, "a node cannot be prepended to itself");
275
276        let mut self_borrow = self.0.borrow_mut();
277        {
278            let mut new_child_borrow = new_child.0.borrow_mut();
279            new_child_borrow.detach();
280            new_child_borrow.root = Some(self_borrow.root.clone().unwrap_or(Rc::downgrade(&self.0)));
281            new_child_borrow.parent = Some(Rc::downgrade(&self.0));
282            match self_borrow.first_child.take() {
283                Some(first_child_strong) => {
284                    {
285                        let mut first_child_borrow = first_child_strong.borrow_mut();
286                        debug_assert!(first_child_borrow.previous_sibling.is_none());
287                        first_child_borrow.previous_sibling = Some(Rc::downgrade(&new_child.0));
288                    }
289                    new_child_borrow.next_sibling = Some(first_child_strong);
290                }
291                None => {
292                    debug_assert!(self_borrow.first_child.is_none());
293                    self_borrow.last_child = Some(Rc::downgrade(&new_child.0));
294                }
295            }
296        }
297        self_borrow.first_child = Some(new_child.0);
298    }
299
300    /// Inserts a new sibling after this node.
301    ///
302    /// # Panics
303    ///
304    /// Panics if the node, the new sibling, or one of their adjoining nodes is currently borrowed.
305    pub fn insert_after(&mut self, new_sibling: Node<T>) {
306        assert!(*self != new_sibling, "a node cannot be inserted after itself");
307
308        let mut self_borrow = self.0.borrow_mut();
309        {
310            let mut new_sibling_borrow = new_sibling.0.borrow_mut();
311            new_sibling_borrow.detach();
312            new_sibling_borrow.root = self_borrow.root.clone();
313            new_sibling_borrow.parent = self_borrow.parent.clone();
314            new_sibling_borrow.previous_sibling = Some(Rc::downgrade(&self.0));
315            match self_borrow.next_sibling.take() {
316                Some(next_sibling_strong) => {
317                    {
318                        let mut next_sibling_borrow = next_sibling_strong.borrow_mut();
319                        debug_assert!({
320                            let weak = next_sibling_borrow.previous_sibling.as_ref().unwrap();
321                            Rc::ptr_eq(&weak.upgrade().unwrap(), &self.0)
322                        });
323                        next_sibling_borrow.previous_sibling = Some(Rc::downgrade(&new_sibling.0));
324                    }
325                    new_sibling_borrow.next_sibling = Some(next_sibling_strong);
326                }
327                None => {
328                    if let Some(parent_ref) = self_borrow.parent.as_ref() {
329                        if let Some(parent_strong) = parent_ref.upgrade() {
330                            let mut parent_borrow = parent_strong.borrow_mut();
331                            parent_borrow.last_child = Some(Rc::downgrade(&new_sibling.0));
332                        }
333                    }
334                }
335            }
336        }
337        self_borrow.next_sibling = Some(new_sibling.0);
338    }
339
340    /// Inserts a new sibling before this node.
341    ///
342    /// # Panics
343    ///
344    /// Panics if the node, the new sibling, or one of their adjoining nodes is currently borrowed.
345    pub fn insert_before(&mut self, new_sibling: Node<T>) {
346        assert!(*self != new_sibling, "a node cannot be inserted before itself");
347
348        let mut self_borrow = self.0.borrow_mut();
349        let mut previous_sibling_opt = None;
350        {
351            let mut new_sibling_borrow = new_sibling.0.borrow_mut();
352            new_sibling_borrow.detach();
353            new_sibling_borrow.root = self_borrow.root.clone();
354            new_sibling_borrow.parent = self_borrow.parent.clone();
355            new_sibling_borrow.next_sibling = Some(self.0.clone());
356            if let Some(previous_sibling_weak) = self_borrow.previous_sibling.take() {
357                if let Some(previous_sibling_strong) = previous_sibling_weak.upgrade() {
358                    new_sibling_borrow.previous_sibling = Some(previous_sibling_weak);
359                    previous_sibling_opt = Some(previous_sibling_strong);
360                }
361            }
362            self_borrow.previous_sibling = Some(Rc::downgrade(&new_sibling.0));
363        }
364
365        if let Some(previous_sibling_strong) = previous_sibling_opt {
366            let mut previous_sibling_borrow = previous_sibling_strong.borrow_mut();
367            debug_assert!({
368                let rc = previous_sibling_borrow.next_sibling.as_ref().unwrap();
369                Rc::ptr_eq(rc, &self.0)
370            });
371            previous_sibling_borrow.next_sibling = Some(new_sibling.0);
372        } else {
373            // No previous sibling.
374            if let Some(parent_ref) = self_borrow.parent.as_ref() {
375                if let Some(parent_strong) = parent_ref.upgrade() {
376                    let mut parent_borrow = parent_strong.borrow_mut();
377                    parent_borrow.first_child = Some(new_sibling.0);
378                }
379            }
380        }
381    }
382}
383
384impl<T> NodeData<T> {
385    /// Detaches a node from its parent and siblings. Children are not affected.
386    fn detach(&mut self) {
387        let parent_weak = self.parent.take();
388        let previous_sibling_weak = self.previous_sibling.take();
389        let next_sibling_strong = self.next_sibling.take();
390
391        let previous_sibling_opt = previous_sibling_weak.as_ref().and_then(|weak| weak.upgrade());
392
393        if let Some(next_sibling_ref) = next_sibling_strong.as_ref() {
394            let mut next_sibling_borrow = next_sibling_ref.borrow_mut();
395            next_sibling_borrow.previous_sibling = previous_sibling_weak;
396        } else if let Some(parent_ref) = parent_weak.as_ref() {
397            if let Some(parent_strong) = parent_ref.upgrade() {
398                let mut parent_borrow = parent_strong.borrow_mut();
399                parent_borrow.last_child = previous_sibling_weak;
400            }
401        }
402
403        if let Some(previous_sibling_strong) = previous_sibling_opt {
404            let mut previous_sibling_borrow = previous_sibling_strong.borrow_mut();
405            previous_sibling_borrow.next_sibling = next_sibling_strong;
406        } else if let Some(parent_ref) = parent_weak.as_ref() {
407            if let Some(parent_strong) = parent_ref.upgrade() {
408                let mut parent_borrow = parent_strong.borrow_mut();
409                parent_borrow.first_child = next_sibling_strong;
410            }
411        }
412    }
413}
414
415
416/// Iterators prelude.
417pub mod iterator {
418    pub use super::Ancestors;
419    pub use super::PrecedingSiblings;
420    pub use super::FollowingSiblings;
421    pub use super::Children;
422    pub use super::Descendants;
423    pub use super::Traverse;
424    pub use super::NodeEdge;
425}
426
427macro_rules! impl_node_iterator {
428    ($name: ident, $next: expr) => {
429        impl<T> Iterator for $name<T> {
430            type Item = Node<T>;
431
432            /// # Panics
433            ///
434            /// Panics if the node about to be yielded is currently mutably borrowed.
435            fn next(&mut self) -> Option<Self::Item> {
436                match self.0.take() {
437                    Some(node) => {
438                        self.0 = $next(&node);
439                        Some(node)
440                    }
441                    None => None
442                }
443            }
444        }
445    }
446}
447
448/// An iterator of nodes to the ancestors a given node.
449pub struct Ancestors<T>(Option<Node<T>>);
450impl_node_iterator!(Ancestors, |node: &Node<T>| node.parent());
451
452/// An iterator of nodes to the siblings before a given node.
453pub struct PrecedingSiblings<T>(Option<Node<T>>);
454impl_node_iterator!(PrecedingSiblings, |node: &Node<T>| node.previous_sibling());
455
456/// An iterator of nodes to the siblings after a given node.
457pub struct FollowingSiblings<T>(Option<Node<T>>);
458impl_node_iterator!(FollowingSiblings, |node: &Node<T>| node.next_sibling());
459
460/// A double ended iterator of nodes to the children of a given node.
461pub struct Children<T> {
462    next: Option<Node<T>>,
463    next_back: Option<Node<T>>,
464}
465
466impl<T> Children<T> {
467    // true if self.next_back's next sibling is self.next
468    fn finished(&self) -> bool {
469        match self.next_back {
470            Some(ref next_back) => next_back.next_sibling() == self.next,
471            _ => true,
472        }
473    }
474}
475
476impl<T> Iterator for Children<T> {
477    type Item = Node<T>;
478
479    /// # Panics
480    ///
481    /// Panics if the node about to be yielded is currently mutably borrowed.
482    fn next(&mut self) -> Option<Self::Item> {
483        if self.finished() {
484            return None;
485        }
486
487        match self.next.take() {
488            Some(node) => {
489                self.next = node.next_sibling();
490                Some(node)
491            }
492            None => None
493        }
494    }
495}
496
497impl<T> DoubleEndedIterator for Children<T> {
498    /// # Panics
499    ///
500    /// Panics if the node about to be yielded is currently mutably borrowed.
501    fn next_back(&mut self) -> Option<Self::Item> {
502        if self.finished() {
503            return None;
504        }
505
506        match self.next_back.take() {
507            Some(node) => {
508                self.next_back = node.previous_sibling();
509                Some(node)
510            }
511            None => None
512        }
513    }
514}
515
516/// An iterator of nodes to a given node and its descendants, in tree order.
517pub struct Descendants<T>(Traverse<T>);
518
519impl<T> Iterator for Descendants<T> {
520    type Item = Node<T>;
521
522    /// # Panics
523    ///
524    /// Panics if the node about to be yielded is currently mutably borrowed.
525    fn next(&mut self) -> Option<Self::Item> {
526        loop {
527            match self.0.next() {
528                Some(NodeEdge::Start(node)) => return Some(node),
529                Some(NodeEdge::End(_)) => {}
530                None => return None
531            }
532        }
533    }
534}
535
536
537/// A node type during traverse.
538#[derive(Clone, Debug)]
539pub enum NodeEdge<T> {
540    /// Indicates that start of a node that has children.
541    /// Yielded by `Traverse::next` before the node's descendants.
542    /// In HTML or XML, this corresponds to an opening tag like `<div>`
543    Start(Node<T>),
544
545    /// Indicates that end of a node that has children.
546    /// Yielded by `Traverse::next` after the node's descendants.
547    /// In HTML or XML, this corresponds to a closing tag like `</div>`
548    End(Node<T>),
549}
550
551// Implement PartialEq manually, because we do not need to require T: PartialEq
552impl<T> PartialEq for NodeEdge<T> {
553    fn eq(&self, other: &NodeEdge<T>) -> bool {
554        match (&*self, &*other) {
555            (&NodeEdge::Start(ref n1), &NodeEdge::Start(ref n2)) => *n1 == *n2,
556            (&NodeEdge::End(ref n1), &NodeEdge::End(ref n2)) => *n1 == *n2,
557            _ => false,
558        }
559    }
560}
561
562impl<T> NodeEdge<T> {
563    fn next_item(&self, root: &Node<T>) -> Option<NodeEdge<T>> {
564        match *self {
565            NodeEdge::Start(ref node) => match node.first_child() {
566                Some(first_child) => Some(NodeEdge::Start(first_child)),
567                None => Some(NodeEdge::End(node.clone())),
568            },
569            NodeEdge::End(ref node) => {
570                if *node == *root {
571                    None
572                } else {
573                    match node.next_sibling() {
574                        Some(next_sibling) => Some(NodeEdge::Start(next_sibling)),
575                        None => match node.parent() {
576                            Some(parent) => Some(NodeEdge::End(parent)),
577
578                            // `node.parent()` here can only be `None`
579                            // if the tree has been modified during iteration,
580                            // but silently stoping iteration
581                            // seems a more sensible behavior than panicking.
582                            None => None,
583                        },
584                    }
585                }
586            }
587        }
588    }
589
590    fn previous_item(&self, root: &Node<T>) -> Option<NodeEdge<T>> {
591        match *self {
592            NodeEdge::End(ref node) => match node.last_child() {
593                Some(last_child) => Some(NodeEdge::End(last_child)),
594                None => Some(NodeEdge::Start(node.clone())),
595            },
596            NodeEdge::Start(ref node) => {
597                if *node == *root {
598                    None
599                } else {
600                    match node.previous_sibling() {
601                        Some(previous_sibling) => Some(NodeEdge::End(previous_sibling)),
602                        None => match node.parent() {
603                            Some(parent) => Some(NodeEdge::Start(parent)),
604
605                            // `node.parent()` here can only be `None`
606                            // if the tree has been modified during iteration,
607                            // but silently stoping iteration
608                            // seems a more sensible behavior than panicking.
609                            None => None
610                        }
611                    }
612                }
613            }
614        }
615    }
616}
617
618/// A double ended iterator of nodes to a given node and its descendants,
619/// in tree order.
620pub struct Traverse<T> {
621    root: Node<T>,
622    next: Option<NodeEdge<T>>,
623    next_back: Option<NodeEdge<T>>,
624}
625
626impl<T> Traverse<T> {
627    // true if self.next_back's next item is self.next
628    fn finished(&self) -> bool {
629        match self.next_back {
630            Some(ref next_back) => next_back.next_item(&self.root) == self.next,
631            _ => true,
632        }
633    }
634}
635
636impl<T> Iterator for Traverse<T> {
637    type Item = NodeEdge<T>;
638
639    /// # Panics
640    ///
641    /// Panics if the node about to be yielded is currently mutably borrowed.
642    fn next(&mut self) -> Option<Self::Item> {
643        if self.finished() {
644            return None;
645        }
646
647        match self.next.take() {
648            Some(item) => {
649                self.next = item.next_item(&self.root);
650                Some(item)
651            }
652            None => None
653        }
654    }
655}
656
657impl<T> DoubleEndedIterator for Traverse<T> {
658    /// # Panics
659    ///
660    /// Panics if the node about to be yielded is currently mutably borrowed.
661    fn next_back(&mut self) -> Option<Self::Item> {
662        if self.finished() {
663            return None;
664        }
665
666        match self.next_back.take() {
667            Some(item) => {
668                self.next_back = item.previous_item(&self.root);
669                Some(item)
670            }
671            None => None
672        }
673    }
674}