rctree-0.2.1/.gitignore010064400017500001750000000000611326024057600132110ustar0000000000000000/target **/*.rs.bk Cargo.lock /.idea /rctree.iml rctree-0.2.1/.travis.yml010064400017500001750000000004501326364114500133340ustar0000000000000000language: 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.2.1/Cargo.toml.orig010064400017500001750000000007541326733265200141250ustar0000000000000000[package] name = "rctree" # When updating version, also modify html_root_url in the lib.rs and in the README version = "0.2.1" authors = [ "Simon Sapin ", "Reizner Evgeniy " ] 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" [dev-dependencies] pretty_assertions = "0.5.1" indoc = "0.2" rctree-0.2.1/Cargo.toml0000644000000016760000000000000103670ustar00# 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.2.1" authors = ["Simon Sapin ", "Reizner Evgeniy "] 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" [dev-dependencies.indoc] version = "0.2" [dev-dependencies.pretty_assertions] version = "0.5.1" rctree-0.2.1/LICENSE010064400017500001750000000021311326024045400122210ustar0000000000000000The 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.2.1/README.md010064400017500001750000000076611326733315000125130ustar0000000000000000# 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 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. ### Differences * `NodeRef` -> `Node`. * All nodes has a root node reference that can be accessed at *O(1)*. * Added `make_copy`, `make_deep_copy`, `has_children` and `root` methods. * `Node` implements `PartialEq` now. * Used `std` features like `Rc::ptr_eq`, `Ref` and `RefMut` instead of handwritten one. * `borrow_mut`, `detach`, `append`, `prepend`, `insert_after`, `insert_before`, `make_copy` and `make_deep_copy` are marked as `mut`. * `append`, `prepend`, `insert_after` and `insert_before` methods will panic if the provided child/sibling is the same the same node. ### Usage Dependency: [Rust](https://www.rust-lang.org/) >= 1.17 #### As source The library consists of a single file which you can copy to your project. This is a preferable solution since you can tweak the crate for your needs. #### As crate Add this to your `Cargo.toml`: ```toml [dependencies] rctree = "0.2" ``` ### License *rctree* is licensed under the **MIT**. rctree-0.2.1/src/lib.rs010064400017500001750000000604711326733301200131320ustar0000000000000000/*! *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.2.1")] #![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); 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) } } 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 root node. /// /// If the current node is the root node - will return itself. /// /// # Panics /// /// Panics if the node is currently mutability 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 mutability 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 mutability 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 mutability borrowed. pub fn last_child(&self) -> Option> { Some(Node(try_opt!(try_opt!(self.0.borrow().last_child.as_ref()).upgrade()))) } /// Returns a previous sibling of this node, unless it is a first child. /// /// # Panics /// /// Panics if the node is currently mutability borrowed. pub fn previous_sibling(&self) -> Option> { Some(Node(try_opt!(try_opt!(self.0.borrow().previous_sibling.as_ref()).upgrade()))) } /// Returns a previous sibling of this node, unless it is a first child. /// /// # Panics /// /// Panics if the node is currently mutability 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 mutability 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 mutability borrowed. pub fn children(&self) -> Children { Children(self.first_child()) } /// Returns `true` if this node has children nodes. /// /// # Panics /// /// Panics if the node is currently mutability borrowed. pub fn has_children(&self) -> bool { self.first_child().is_some() } /// Returns an iterator of nodes to this node's children, in reverse order. /// /// # Panics /// /// Panics if the node is currently mutability borrowed. pub fn reverse_children(&self) -> ReverseChildren { ReverseChildren(self.last_child()) } /// 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())), } } /// Returns an iterator of nodes to this node and its descendants, in tree order. pub fn reverse_traverse(&self) -> ReverseTraverse { ReverseTraverse { root: self.clone(), next: 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 mutability 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); } } } } 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; } } } } 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 mutability 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()); /// An iterator of nodes to the children of a given node. pub struct Children(Option>); impl_node_iterator!(Children, |node: &Node| node.next_sibling()); /// An iterator of nodes to the children of a given node, in reverse order. pub struct ReverseChildren(Option>); impl_node_iterator!(ReverseChildren, |node: &Node| node.previous_sibling()); /// 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 mutability 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)] 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), } /// An iterator of nodes to a given node and its descendants, in tree order. pub struct Traverse { root: Node, next: Option>, } impl Iterator for Traverse { type Item = NodeEdge; /// # Panics /// /// Panics if the node about to be yielded is currently mutability borrowed. fn next(&mut self) -> Option { match self.next.take() { Some(item) => { self.next = match item { 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 == self.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 } } } } }; Some(item) } None => None } } } /// An iterator of nodes to a given node and its descendants, in reverse tree order. pub struct ReverseTraverse { root: Node, next: Option>, } impl Iterator for ReverseTraverse { type Item = NodeEdge; /// # Panics /// /// Panics if the node about to be yielded is currently mutability borrowed. fn next(&mut self) -> Option { match self.next.take() { Some(item) => { self.next = match item { 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 == self.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 } } } } }; Some(item) } None => None } } } rctree-0.2.1/tests/tests.rs010064400017500001750000000106111326363243100140730ustar0000000000000000#[macro_use] extern crate indoc; #[macro_use] extern crate pretty_assertions; extern crate rctree; use rctree::Node; 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)), indoc!(" 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)), indoc!(" 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..1000000 { // let node = Node::new(1); // parent.append(node.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); }