rctree-0.3.3/.gitignore010064400017500001750000000000611326024057600132140ustar0000000000000000/target **/*.rs.bk Cargo.lock /.idea /rctree.iml rctree-0.3.3/.travis.yml010064400017500001750000000004501326364114500133370ustar0000000000000000language: rust rust: - 1.17.0 - stable - nightly sudo: required script: - cargo build --verbose --all - cargo test --verbose --all - if [ $TRAVIS_RUST_VERSION == "nightly" ]; then env RUSTFLAGS="-Z sanitizer=leak" cargo +nightly test --target x86_64-unknown-linux-gnu; fi rctree-0.3.3/Cargo.toml.orig010064400017500001750000000006341350437057500141250ustar0000000000000000[package] name = "rctree" # When updating version, also modify html_root_url in the lib.rs version = "0.3.3" authors = [ "Simon Sapin ", "Evgeniy Reizner " ] license = "MIT" description = "A 'DOM-like' tree implemented using reference counting" repository = "https://github.com/RazrFalcon/rctree" documentation = "https://docs.rs/rctree/" readme = "README.md" rctree-0.3.3/Cargo.toml0000644000000015360000000000000103650ustar00# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies # # If you believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] name = "rctree" version = "0.3.3" authors = ["Simon Sapin ", "Evgeniy Reizner "] description = "A 'DOM-like' tree implemented using reference counting" documentation = "https://docs.rs/rctree/" readme = "README.md" license = "MIT" repository = "https://github.com/RazrFalcon/rctree" rctree-0.3.3/LICENSE010064400017500001750000000021311326024045400122240ustar0000000000000000The MIT License (MIT) Copyright (c) 2018 Simon Sapin Copyright (c) 2018 Reizner Evgeniy Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. rctree-0.3.3/README.md010064400017500001750000000061451346600742200125130ustar0000000000000000# rctree [![Build Status](https://travis-ci.org/RazrFalcon/rctree.svg?branch=master)](https://travis-ci.org/RazrFalcon/rctree) [![Crates.io](https://img.shields.io/crates/v/rctree.svg)](https://crates.io/crates/rctree) [![Documentation](https://docs.rs/rctree/badge.svg)](https://docs.rs/rctree) *rctree* is a "DOM-like" tree implemented using reference counting. ### Origin This is a fork of the [rust-forest](https://github.com/SimonSapin/rust-forest) rctree. ### Details "DOM-like" here means that data structures can be used to represent the parsed content of an HTML or XML document, like [*the* DOM](https://dom.spec.whatwg.org/) does, but don't necessarily have the exact same API as the DOM. That is: * A tree is made up of nodes. * Each node has zero or more *child* nodes, which are ordered. * Each node has a no more than one *parent*, the node that it is a *child* of. * A node without a *parent* is called a *root*. * As a consequence, each node may also have *siblings*: its *parent*'s other *children*, if any. * From any given node, access to its parent, previous sibling, next sibling, first child, and last child (if any) can take no more than *O(1)* time. * Each node also has data associated to it, which for the purpose of this project is purely generic. For an HTML document, the data would be either the text of a text node, or the name and attributes of an element node. * The tree is mutable: nodes (with their sub-trees) can be inserted or removed anywhere in the tree. The lifetime of nodes is managed through *reference counting*. To avoid reference cycles which would cause memory leaks, the tree is *asymmetric*: each node holds optional *strong references* to its next sibling and first child, but only optional *weak references* to its parent, previous sibling, and last child. Nodes are destroyed as soon as there is no strong reference left to them. The structure is such that holding a reference to the root is sufficient to keep the entire tree alive. However, if for example the only reference that exists from outside the tree is one that you use to traverse it, you will not be able to go back "up" the tree to ancestors and previous siblings after going "down", as those nodes will have been destroyed. Weak references to destroyed nodes are treated as if they were not set at all. (E.g. a node can become a root when its parent is destroyed.) Since nodes are *aliased* (have multiple references to them), [`RefCell`](http://doc.rust-lang.org/std/cell/index.html) is used for interior mutability. Advantages: * A single `Node` user-visible type to manipulate the tree, with methods. * Memory is freed as soon as it becomes unused (if parts of the tree are removed). Disadvantages: * The tree can only be accessed from the thread is was created in. * Any tree manipulation, including read-only traversals, requires incrementing and decrementing reference counts, which causes run-time overhead. * Nodes are allocated individually, which may cause memory fragmentation and hurt performance. ### Dependency [Rust](https://www.rust-lang.org/) >= 1.17 ### License *rctree* is licensed under the **MIT**. rctree-0.3.3/src/lib.rs010064400017500001750000000656701350437054700131530ustar0000000000000000/*! *rctree* is a "DOM-like" tree implemented using reference counting. "DOM-like" here means that data structures can be used to represent the parsed content of an HTML or XML document, like [*the* DOM](https://dom.spec.whatwg.org/) does, but don't necessarily have the exact same API as the DOM. That is: * A tree is made up of nodes. * Each node has zero or more *child* nodes, which are ordered. * Each node has a no more than one *parent*, the node that it is a *child* of. * A node without a *parent* is called a *root*. * As a consequence, each node may also have *siblings*: its *parent*'s other *children*, if any. * From any given node, access to its parent, previous sibling, next sibling, first child, and last child (if any) can take no more than *O(1)* time. * Each node also has data associated to it, which for the purpose of this project is purely generic. For an HTML document, the data would be either the text of a text node, or the name and attributes of an element node. * The tree is mutable: nodes (with their sub-trees) can be inserted or removed anywhere in the tree. The lifetime of nodes is managed through *reference counting*. To avoid reference cycles which would cause memory leaks, the tree is *asymmetric*: each node holds optional *strong references* to its next sibling and first child, but only optional *weak references* to its parent, previous sibling, and last child. Nodes are destroyed as soon as there is no strong reference left to them. The structure is such that holding a reference to the root is sufficient to keep the entire tree alive. However, if for example the only reference that exists from outside the tree is one that you use to traverse it, you will not be able to go back "up" the tree to ancestors and previous siblings after going "down", as those nodes will have been destroyed. Weak references to destroyed nodes are treated as if they were not set at all. (E.g. a node can become a root when its parent is destroyed.) Since nodes are *aliased* (have multiple references to them), [`RefCell`](http://doc.rust-lang.org/std/cell/index.html) is used for interior mutability. Advantages: * A single `Node` user-visible type to manipulate the tree, with methods. * Memory is freed as soon as it becomes unused (if parts of the tree are removed). Disadvantages: * The tree can only be accessed from the thread is was created in. * Any tree manipulation, including read-only traversals, requires incrementing and decrementing reference counts, which causes run-time overhead. * Nodes are allocated individually, which may cause memory fragmentation and hurt performance. */ #![doc(html_root_url = "https://docs.rs/rctree/0.3.3")] #![forbid(unsafe_code)] #![warn(missing_docs)] use std::fmt; use std::cell::{RefCell, Ref, RefMut}; use std::rc::{Rc, Weak}; type Link = Rc>>; type WeakLink = Weak>>; /// A reference to a node holding a value of type `T`. Nodes form a tree. /// /// Internally, this uses reference counting for lifetime tracking /// and `std::cell::RefCell` for interior mutability. /// /// **Note:** Cloning a `Node` only increments a reference count. It does not copy the data. pub struct Node(Link); /// A weak reference to a node holding a value of type `T`. pub struct WeakNode(WeakLink); struct NodeData { root: Option>, parent: Option>, first_child: Option>, last_child: Option>, previous_sibling: Option>, next_sibling: Option>, data: T, } /// Cloning a `Node` only increments a reference count. It does not copy the data. impl Clone for Node { fn clone(&self) -> Self { Node(Rc::clone(&self.0)) } } impl PartialEq for Node { fn eq(&self, other: &Node) -> bool { Rc::ptr_eq(&self.0, &other.0) } } impl fmt::Debug for Node { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(&*self.borrow(), f) } } impl fmt::Display for Node { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&*self.borrow(), f) } } macro_rules! try_opt { ($expr: expr) => { match $expr { Some(value) => value, None => return None } } } impl Node { /// Creates a new node from its associated data. pub fn new(data: T) -> Node { Node(Rc::new(RefCell::new(NodeData { root: None, parent: None, first_child: None, last_child: None, previous_sibling: None, next_sibling: None, data, }))) } /// Returns a weak referece to a node. pub fn downgrade(&self) -> WeakNode { WeakNode(Rc::downgrade(&self.0)) } /// Returns a root node. /// /// If the current node is the root node - will return itself. /// /// # Panics /// /// Panics if the node is currently mutably borrowed. pub fn root(&self) -> Node { match self.0.borrow().root.as_ref() { Some(v) => Node(v.upgrade().unwrap()), None => self.clone(), } } /// Returns a parent node, unless this node is the root of the tree. /// /// # Panics /// /// Panics if the node is currently mutably borrowed. pub fn parent(&self) -> Option> { Some(Node(try_opt!(try_opt!(self.0.borrow().parent.as_ref()).upgrade()))) } /// Returns a first child of this node, unless it has no child. /// /// # Panics /// /// Panics if the node is currently mutably borrowed. pub fn first_child(&self) -> Option> { Some(Node(try_opt!(self.0.borrow().first_child.as_ref()).clone())) } /// Returns a last child of this node, unless it has no child. /// /// # Panics /// /// Panics if the node is currently mutably borrowed. pub fn last_child(&self) -> Option> { Some(Node(try_opt!(try_opt!(self.0.borrow().last_child.as_ref()).upgrade()))) } /// Returns the previous sibling of this node, unless it is a first child. /// /// # Panics /// /// Panics if the node is currently mutably borrowed. pub fn previous_sibling(&self) -> Option> { Some(Node(try_opt!(try_opt!(self.0.borrow().previous_sibling.as_ref()).upgrade()))) } /// Returns the next sibling of this node, unless it is a last child. /// /// # Panics /// /// Panics if the node is currently mutably borrowed. pub fn next_sibling(&self) -> Option> { Some(Node(try_opt!(self.0.borrow().next_sibling.as_ref()).clone())) } /// Returns a shared reference to this node's data /// /// # Panics /// /// Panics if the node is currently mutably borrowed. pub fn borrow(&self) -> Ref { Ref::map(self.0.borrow(), |v| &v.data) } /// Returns a unique/mutable reference to this node's data /// /// # Panics /// /// Panics if the node is currently borrowed. pub fn borrow_mut(&mut self) -> RefMut { RefMut::map(self.0.borrow_mut(), |v| &mut v.data) } /// Returns an iterator of nodes to this node and its ancestors. /// /// Includes the current node. pub fn ancestors(&self) -> Ancestors { Ancestors(Some(self.clone())) } /// Returns an iterator of nodes to this node and the siblings before it. /// /// Includes the current node. pub fn preceding_siblings(&self) -> PrecedingSiblings { PrecedingSiblings(Some(self.clone())) } /// Returns an iterator of nodes to this node and the siblings after it. /// /// Includes the current node. pub fn following_siblings(&self) -> FollowingSiblings { FollowingSiblings(Some(self.clone())) } /// Returns an iterator of nodes to this node's children. /// /// # Panics /// /// Panics if the node is currently mutably borrowed. pub fn children(&self) -> Children { Children { next: self.first_child(), next_back: self.last_child(), } } /// Returns `true` if this node has children nodes. /// /// # Panics /// /// Panics if the node is currently mutably borrowed. pub fn has_children(&self) -> bool { self.first_child().is_some() } /// Returns an iterator of nodes to this node and its descendants, in tree order. /// /// Includes the current node. pub fn descendants(&self) -> Descendants { Descendants(self.traverse()) } /// Returns an iterator of nodes to this node and its descendants, in tree order. pub fn traverse(&self) -> Traverse { Traverse { root: self.clone(), next: Some(NodeEdge::Start(self.clone())), next_back: Some(NodeEdge::End(self.clone())), } } /// Detaches a node from its parent and siblings. Children are not affected. /// /// # Panics /// /// Panics if the node or one of its adjoining nodes is currently borrowed. pub fn detach(&mut self) { self.0.borrow_mut().detach(); } /// Appends a new child to this node, after existing children. /// /// # Panics /// /// Panics if the node, the new child, or one of their adjoining nodes is currently borrowed. pub fn append(&mut self, new_child: Node) { assert!(*self != new_child, "a node cannot be appended to itself"); let mut self_borrow = self.0.borrow_mut(); let mut last_child_opt = None; { let mut new_child_borrow = new_child.0.borrow_mut(); new_child_borrow.detach(); new_child_borrow.root = Some(self_borrow.root.clone().unwrap_or(Rc::downgrade(&self.0))); new_child_borrow.parent = Some(Rc::downgrade(&self.0)); if let Some(last_child_weak) = self_borrow.last_child.take() { if let Some(last_child_strong) = last_child_weak.upgrade() { new_child_borrow.previous_sibling = Some(last_child_weak); last_child_opt = Some(last_child_strong); } } self_borrow.last_child = Some(Rc::downgrade(&new_child.0)); } if let Some(last_child_strong) = last_child_opt { let mut last_child_borrow = last_child_strong.borrow_mut(); debug_assert!(last_child_borrow.next_sibling.is_none()); last_child_borrow.next_sibling = Some(new_child.0); } else { // No last child debug_assert!(self_borrow.first_child.is_none()); self_borrow.first_child = Some(new_child.0); } } /// Prepends a new child to this node, before existing children. /// /// # Panics /// /// Panics if the node, the new child, or one of their adjoining nodes is currently borrowed. pub fn prepend(&mut self, new_child: Node) { assert!(*self != new_child, "a node cannot be prepended to itself"); let mut self_borrow = self.0.borrow_mut(); { let mut new_child_borrow = new_child.0.borrow_mut(); new_child_borrow.detach(); new_child_borrow.root = Some(self_borrow.root.clone().unwrap_or(Rc::downgrade(&self.0))); new_child_borrow.parent = Some(Rc::downgrade(&self.0)); match self_borrow.first_child.take() { Some(first_child_strong) => { { let mut first_child_borrow = first_child_strong.borrow_mut(); debug_assert!(first_child_borrow.previous_sibling.is_none()); first_child_borrow.previous_sibling = Some(Rc::downgrade(&new_child.0)); } new_child_borrow.next_sibling = Some(first_child_strong); } None => { debug_assert!(self_borrow.first_child.is_none()); self_borrow.last_child = Some(Rc::downgrade(&new_child.0)); } } } self_borrow.first_child = Some(new_child.0); } /// Inserts a new sibling after this node. /// /// # Panics /// /// Panics if the node, the new sibling, or one of their adjoining nodes is currently borrowed. pub fn insert_after(&mut self, new_sibling: Node) { assert!(*self != new_sibling, "a node cannot be inserted after itself"); let mut self_borrow = self.0.borrow_mut(); { let mut new_sibling_borrow = new_sibling.0.borrow_mut(); new_sibling_borrow.detach(); new_sibling_borrow.root = self_borrow.root.clone(); new_sibling_borrow.parent = self_borrow.parent.clone(); new_sibling_borrow.previous_sibling = Some(Rc::downgrade(&self.0)); match self_borrow.next_sibling.take() { Some(next_sibling_strong) => { { let mut next_sibling_borrow = next_sibling_strong.borrow_mut(); debug_assert!({ let weak = next_sibling_borrow.previous_sibling.as_ref().unwrap(); Rc::ptr_eq(&weak.upgrade().unwrap(), &self.0) }); next_sibling_borrow.previous_sibling = Some(Rc::downgrade(&new_sibling.0)); } new_sibling_borrow.next_sibling = Some(next_sibling_strong); } None => { if let Some(parent_ref) = self_borrow.parent.as_ref() { if let Some(parent_strong) = parent_ref.upgrade() { let mut parent_borrow = parent_strong.borrow_mut(); parent_borrow.last_child = Some(Rc::downgrade(&new_sibling.0)); } } } } } self_borrow.next_sibling = Some(new_sibling.0); } /// Inserts a new sibling before this node. /// /// # Panics /// /// Panics if the node, the new sibling, or one of their adjoining nodes is currently borrowed. pub fn insert_before(&mut self, new_sibling: Node) { assert!(*self != new_sibling, "a node cannot be inserted before itself"); let mut self_borrow = self.0.borrow_mut(); let mut previous_sibling_opt = None; { let mut new_sibling_borrow = new_sibling.0.borrow_mut(); new_sibling_borrow.detach(); new_sibling_borrow.root = self_borrow.root.clone(); new_sibling_borrow.parent = self_borrow.parent.clone(); new_sibling_borrow.next_sibling = Some(self.0.clone()); if let Some(previous_sibling_weak) = self_borrow.previous_sibling.take() { if let Some(previous_sibling_strong) = previous_sibling_weak.upgrade() { new_sibling_borrow.previous_sibling = Some(previous_sibling_weak); previous_sibling_opt = Some(previous_sibling_strong); } } self_borrow.previous_sibling = Some(Rc::downgrade(&new_sibling.0)); } if let Some(previous_sibling_strong) = previous_sibling_opt { let mut previous_sibling_borrow = previous_sibling_strong.borrow_mut(); debug_assert!({ let rc = previous_sibling_borrow.next_sibling.as_ref().unwrap(); Rc::ptr_eq(rc, &self.0) }); previous_sibling_borrow.next_sibling = Some(new_sibling.0); } else { // No previous sibling. if let Some(parent_ref) = self_borrow.parent.as_ref() { if let Some(parent_strong) = parent_ref.upgrade() { let mut parent_borrow = parent_strong.borrow_mut(); parent_borrow.first_child = Some(new_sibling.0); } } } } /// Returns a copy of a current node without children. /// /// # Panics /// /// Panics if the node is currently mutably borrowed. pub fn make_copy(&mut self) -> Node where T: Clone { Node::new(self.borrow().clone()) } /// Returns a copy of a current node with children. /// /// # Panics /// /// Panics if any of the descendant nodes are currently mutably borrowed. pub fn make_deep_copy(&mut self) -> Node where T: Clone { let mut root = self.make_copy(); Node::_make_deep_copy(&mut root, self); root } fn _make_deep_copy(parent: &mut Node, node: &Node) where T: Clone { for mut child in node.children() { let mut new_node = child.make_copy(); parent.append(new_node.clone()); if child.has_children() { Node::_make_deep_copy(&mut new_node, &child); } } } } /// Cloning a `WeakNode` only increments a reference count. It does not copy the data. impl Clone for WeakNode { fn clone(&self) -> Self { WeakNode(Weak::clone(&self.0)) } } impl WeakNode { /// Attempts to upgrade the WeakNode to a Node. pub fn upgrade(&self) -> Option> { self.0.upgrade().map(Node) } } impl NodeData { /// Detaches a node from its parent and siblings. Children are not affected. fn detach(&mut self) { let parent_weak = self.parent.take(); let previous_sibling_weak = self.previous_sibling.take(); let next_sibling_strong = self.next_sibling.take(); let previous_sibling_opt = previous_sibling_weak.as_ref().and_then(|weak| weak.upgrade()); if let Some(next_sibling_ref) = next_sibling_strong.as_ref() { let mut next_sibling_borrow = next_sibling_ref.borrow_mut(); next_sibling_borrow.previous_sibling = previous_sibling_weak; } else if let Some(parent_ref) = parent_weak.as_ref() { if let Some(parent_strong) = parent_ref.upgrade() { let mut parent_borrow = parent_strong.borrow_mut(); parent_borrow.last_child = previous_sibling_weak; } } if let Some(previous_sibling_strong) = previous_sibling_opt { let mut previous_sibling_borrow = previous_sibling_strong.borrow_mut(); previous_sibling_borrow.next_sibling = next_sibling_strong; } else if let Some(parent_ref) = parent_weak.as_ref() { if let Some(parent_strong) = parent_ref.upgrade() { let mut parent_borrow = parent_strong.borrow_mut(); parent_borrow.first_child = next_sibling_strong; } } } } impl Drop for NodeData { fn drop(&mut self) { // Collect all descendant nodes and detach them to prevent the stack overflow. let mut stack = Vec::new(); if let Some(first_child) = self.first_child.as_ref() { // Create `Node` from `NodeData`. let first_child = Node(first_child.clone()); // Iterate `self` children, without creating yet another `Node`. for child1 in first_child.following_siblings() { for child2 in child1.descendants() { stack.push(child2); } } } for mut node in stack { node.detach(); } } } /// Iterators prelude. pub mod iterator { pub use super::Ancestors; pub use super::PrecedingSiblings; pub use super::FollowingSiblings; pub use super::Children; pub use super::Descendants; pub use super::Traverse; pub use super::NodeEdge; } macro_rules! impl_node_iterator { ($name: ident, $next: expr) => { impl Iterator for $name { type Item = Node; /// # Panics /// /// Panics if the node about to be yielded is currently mutably borrowed. fn next(&mut self) -> Option { match self.0.take() { Some(node) => { self.0 = $next(&node); Some(node) } None => None } } } } } /// An iterator of nodes to the ancestors a given node. pub struct Ancestors(Option>); impl_node_iterator!(Ancestors, |node: &Node| node.parent()); /// An iterator of nodes to the siblings before a given node. pub struct PrecedingSiblings(Option>); impl_node_iterator!(PrecedingSiblings, |node: &Node| node.previous_sibling()); /// An iterator of nodes to the siblings after a given node. pub struct FollowingSiblings(Option>); impl_node_iterator!(FollowingSiblings, |node: &Node| node.next_sibling()); /// A double ended iterator of nodes to the children of a given node. pub struct Children { next: Option>, next_back: Option>, } impl Children { // true if self.next_back's next sibling is self.next fn finished(&self) -> bool { match self.next_back { Some(ref next_back) => next_back.next_sibling() == self.next, _ => true, } } } impl Iterator for Children { type Item = Node; /// # Panics /// /// Panics if the node about to be yielded is currently mutably borrowed. fn next(&mut self) -> Option { if self.finished() { return None; } match self.next.take() { Some(node) => { self.next = node.next_sibling(); Some(node) } None => None } } } impl DoubleEndedIterator for Children { /// # Panics /// /// Panics if the node about to be yielded is currently mutably borrowed. fn next_back(&mut self) -> Option { if self.finished() { return None; } match self.next_back.take() { Some(node) => { self.next_back = node.previous_sibling(); Some(node) } None => None } } } /// An iterator of nodes to a given node and its descendants, in tree order. pub struct Descendants(Traverse); impl Iterator for Descendants { type Item = Node; /// # Panics /// /// Panics if the node about to be yielded is currently mutably borrowed. fn next(&mut self) -> Option { loop { match self.0.next() { Some(NodeEdge::Start(node)) => return Some(node), Some(NodeEdge::End(_)) => {} None => return None } } } } /// A node type during traverse. #[derive(Clone, Debug)] pub enum NodeEdge { /// Indicates that start of a node that has children. /// Yielded by `Traverse::next` before the node's descendants. /// In HTML or XML, this corresponds to an opening tag like `
` Start(Node), /// Indicates that end of a node that has children. /// Yielded by `Traverse::next` after the node's descendants. /// In HTML or XML, this corresponds to a closing tag like `
` End(Node), } // Implement PartialEq manually, because we do not need to require T: PartialEq impl PartialEq for NodeEdge { fn eq(&self, other: &NodeEdge) -> bool { match (&*self, &*other) { (&NodeEdge::Start(ref n1), &NodeEdge::Start(ref n2)) => *n1 == *n2, (&NodeEdge::End(ref n1), &NodeEdge::End(ref n2)) => *n1 == *n2, _ => false, } } } impl NodeEdge { fn next_item(&self, root: &Node) -> Option> { match *self { NodeEdge::Start(ref node) => match node.first_child() { Some(first_child) => Some(NodeEdge::Start(first_child)), None => Some(NodeEdge::End(node.clone())), }, NodeEdge::End(ref node) => { if *node == *root { None } else { match node.next_sibling() { Some(next_sibling) => Some(NodeEdge::Start(next_sibling)), None => match node.parent() { Some(parent) => Some(NodeEdge::End(parent)), // `node.parent()` here can only be `None` // if the tree has been modified during iteration, // but silently stoping iteration // seems a more sensible behavior than panicking. None => None, }, } } } } } fn previous_item(&self, root: &Node) -> Option> { match *self { NodeEdge::End(ref node) => match node.last_child() { Some(last_child) => Some(NodeEdge::End(last_child)), None => Some(NodeEdge::Start(node.clone())), }, NodeEdge::Start(ref node) => { if *node == *root { None } else { match node.previous_sibling() { Some(previous_sibling) => Some(NodeEdge::End(previous_sibling)), None => match node.parent() { Some(parent) => Some(NodeEdge::Start(parent)), // `node.parent()` here can only be `None` // if the tree has been modified during iteration, // but silently stoping iteration // seems a more sensible behavior than panicking. None => None } } } } } } } /// A double ended iterator of nodes to a given node and its descendants, /// in tree order. pub struct Traverse { root: Node, next: Option>, next_back: Option>, } impl Traverse { // true if self.next_back's next item is self.next fn finished(&self) -> bool { match self.next_back { Some(ref next_back) => next_back.next_item(&self.root) == self.next, _ => true, } } } impl Iterator for Traverse { type Item = NodeEdge; /// # Panics /// /// Panics if the node about to be yielded is currently mutably borrowed. fn next(&mut self) -> Option { if self.finished() { return None; } match self.next.take() { Some(item) => { self.next = item.next_item(&self.root); Some(item) } None => None } } } impl DoubleEndedIterator for Traverse { /// # Panics /// /// Panics if the node about to be yielded is currently mutably borrowed. fn next_back(&mut self) -> Option { if self.finished() { return None; } match self.next_back.take() { Some(item) => { self.next_back = item.previous_item(&self.root); Some(item) } None => None } } } rctree-0.3.3/tests/tests.rs010064400017500001750000000177011350437004600141040ustar0000000000000000extern crate rctree; use rctree::{Node, NodeEdge}; use std::fmt; #[test] fn it_works() { use std::cell; struct DropTracker<'a>(&'a cell::Cell); impl<'a> Drop for DropTracker<'a> { fn drop(&mut self) { self.0.set(self.0.get() + 1); } } let mut new_counter = 0; let drop_counter = cell::Cell::new(0); let mut new = || { new_counter += 1; Node::new((new_counter, DropTracker(&drop_counter))) }; { let mut a = new(); // 1 a.append(new()); // 2 a.append(new()); // 3 a.prepend(new()); // 4 let mut b = new(); // 5 b.append(a.clone()); a.insert_before(new()); // 6 a.insert_before(new()); // 7 a.insert_after(new()); // 8 a.insert_after(new()); // 9 let c = new(); // 10 b.append(c.clone()); assert_eq!(drop_counter.get(), 0); c.previous_sibling().unwrap().detach(); assert_eq!(drop_counter.get(), 1); assert_eq!(b.descendants().map(|node| { let borrow = node.borrow(); borrow.0 }).collect::>(), [ 5, 6, 7, 1, 4, 2, 3, 9, 10 ]); } assert_eq!(drop_counter.get(), 10); } struct TreePrinter(Node); impl fmt::Debug for TreePrinter { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { writeln!(f, "{:?}", self.0.borrow()).unwrap(); iter_children(&self.0, 1, f); Ok(()) } } fn iter_children(parent: &Node, depth: usize, f: &mut fmt::Formatter) { for child in parent.children() { for _ in 0..depth { write!(f, " ").unwrap(); } writeln!(f, "{:?}", child.borrow()).unwrap(); iter_children(&child, depth + 1, f); } } #[test] fn make_copy_1() { let mut node1 = Node::new(1); let node2 = Node::new(2); node1.append(node2); let node1_copy = node1.make_copy(); node1.append(node1_copy); assert_eq!(format!("{:?}", TreePrinter(node1)), "1 2 1 "); } #[test] fn make_deep_copy_1() { let mut node1 = Node::new(1); let mut node2 = Node::new(2); node1.append(node2.clone()); node2.append(node1.make_deep_copy()); assert_eq!(format!("{:?}", TreePrinter(node1)), "1 2 1 2 "); } #[test] #[should_panic] fn append_1() { let mut node1 = Node::new(1); let node1_2 = node1.clone(); node1.append(node1_2); } #[test] #[should_panic] fn prepend_1() { let mut node1 = Node::new(1); let node1_2 = node1.clone(); node1.prepend(node1_2); } #[test] #[should_panic] fn insert_before_1() { let mut node1 = Node::new(1); let node1_2 = node1.clone(); node1.insert_before(node1_2); } #[test] #[should_panic] fn insert_after_1() { let mut node1 = Node::new(1); let node1_2 = node1.clone(); node1.insert_after(node1_2); } #[test] #[should_panic] fn iter_1() { let mut node1 = Node::new(1); let mut node2 = Node::new(2); node1.append(node2.clone()); node2.append(node1.make_deep_copy()); let _n = node2.borrow_mut(); for _ in node1.descendants() {} } #[test] fn stack_overflow() { let mut parent = Node::new(1); for _ in 0..200_000 { let mut node = Node::new(1); node.append(parent.clone()); parent = node; } } #[test] fn root_1() { let node1 = Node::new(1); assert_eq!(node1, node1.root()); } #[test] fn root_2() { let mut node1 = Node::new("node1"); let node2 = Node::new("node2"); node1.append(node2.clone()); assert_eq!(node1.root(), node1); assert_eq!(node2.root(), node1); } #[test] fn root_3() { let mut node1 = Node::new("node1"); let mut node2 = Node::new("node2"); let node3 = Node::new("node3"); node1.append(node2.clone()); node2.append(node3.clone()); assert_eq!(node1.root(), node1); assert_eq!(node2.root(), node1); assert_eq!(node3.root(), node1); } #[test] fn root_4() { let mut node1 = Node::new("node1"); let node2 = Node::new("node2"); let node3 = Node::new("node3"); node1.append(node2.clone()); node1.prepend(node3.clone()); assert_eq!(node1.root(), node1); assert_eq!(node2.root(), node1); assert_eq!(node3.root(), node1); } #[test] fn weak_1() { let node1 = Node::new("node1"); let weak1 = node1.downgrade(); let weak2 = weak1.clone(); let node2 = weak1.upgrade().unwrap(); assert_eq!(node1, node2); let node3 = weak2.upgrade().unwrap(); assert_eq!(node1, node3); } #[test] fn weak_2() { let weak; { let node1 = Node::new("node1"); weak = node1.downgrade(); } assert_eq!(None, weak.upgrade()); } #[test] fn children_1() { let mut node1 = Node::new("node1"); let node2 = Node::new("node2"); let node3 = Node::new("node3"); node1.append(node2.clone()); node1.append(node3.clone()); let mut children = node1.children(); let c = children.next(); assert!(c.is_some()); let c = c.unwrap(); assert_eq!(c, node2); let c = children.next(); assert!(c.is_some()); let c = c.unwrap(); assert_eq!(c, node3); assert!(children.next().is_none()); assert!(children.next_back().is_none()); } #[test] fn children_2() { let mut node1 = Node::new("node1"); let node2 = Node::new("node2"); let node3 = Node::new("node3"); node1.append(node2.clone()); node1.append(node3.clone()); let mut children = node1.children(); let c = children.next_back(); assert!(c.is_some()); let c = c.unwrap(); assert_eq!(c, node3); let c = children.next_back(); assert!(c.is_some()); let c = c.unwrap(); assert_eq!(c, node2); assert!(children.next().is_none()); assert!(children.next_back().is_none()); } #[test] fn traverse_1() { let mut node1 = Node::new("node1"); let node2 = Node::new("node2"); let node3 = Node::new("node3"); node1.append(node2.clone()); node1.append(node3.clone()); let mut traverse = node1.traverse(); let t = traverse.next(); assert!(t.is_some()); let t = t.unwrap(); assert_eq!(t, NodeEdge::Start(node1.clone())); let t = traverse.next(); assert!(t.is_some()); let t = t.unwrap(); assert_eq!(t, NodeEdge::Start(node2.clone())); let t = traverse.next(); assert!(t.is_some()); let t = t.unwrap(); assert_eq!(t, NodeEdge::End(node2.clone())); let t = traverse.next(); assert!(t.is_some()); let t = t.unwrap(); assert_eq!(t, NodeEdge::Start(node3.clone())); let t = traverse.next(); assert!(t.is_some()); let t = t.unwrap(); assert_eq!(t, NodeEdge::End(node3.clone())); let t = traverse.next(); assert!(t.is_some()); let t = t.unwrap(); assert_eq!(t, NodeEdge::End(node1.clone())); assert!(traverse.next().is_none()); assert!(traverse.next_back().is_none()); } #[test] fn traverse_2() { let mut node1 = Node::new("node1"); let node2 = Node::new("node2"); let node3 = Node::new("node3"); node1.append(node2.clone()); node1.append(node3.clone()); let mut traverse = node1.traverse(); let t = traverse.next_back(); assert!(t.is_some()); let t = t.unwrap(); assert_eq!(t, NodeEdge::End(node1.clone())); let t = traverse.next_back(); assert!(t.is_some()); let t = t.unwrap(); assert_eq!(t, NodeEdge::End(node3.clone())); let t = traverse.next_back(); assert!(t.is_some()); let t = t.unwrap(); assert_eq!(t, NodeEdge::Start(node3.clone())); let t = traverse.next_back(); assert!(t.is_some()); let t = t.unwrap(); assert_eq!(t, NodeEdge::End(node2.clone())); let t = traverse.next_back(); assert!(t.is_some()); let t = t.unwrap(); assert_eq!(t, NodeEdge::Start(node2.clone())); let t = traverse.next_back(); assert!(t.is_some()); let t = t.unwrap(); assert_eq!(t, NodeEdge::Start(node1.clone())); assert!(traverse.next().is_none()); assert!(traverse.next_back().is_none()); } rctree-0.3.3/.cargo_vcs_info.json0000644000000001120000000000000123540ustar00{ "git": { "sha1": "7e3506c96d896af1d6f1103591d695222c277681" } }