├── .github ├── dependabot.yml └── workflows │ └── test.yml ├── .gitignore ├── Cargo.toml ├── LICENSE ├── README.md ├── examples └── simple_tree.rs ├── src ├── display.rs ├── iter.rs ├── lib.rs ├── serde.rs └── sort.rs └── tests ├── iter.rs ├── macro.rs ├── node_mut.rs ├── node_ref.rs ├── serde.rs ├── sort.rs ├── subtree.rs └── tree.rs /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # To get started with Dependabot version updates, you'll need to specify which 2 | # package ecosystems to update and where the package manifests are located. 3 | # Please see the documentation for all configuration options: 4 | # https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates 5 | 6 | version: 2 7 | updates: 8 | - package-ecosystem: "cargo" 9 | directory: "/" 10 | schedule: 11 | interval: "weekly" 12 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Tests 2 | 3 | on: 4 | pull_request: 5 | push: 6 | branches: 7 | - "master" 8 | 9 | jobs: 10 | format: 11 | name: Format code 12 | runs-on: ubuntu-latest 13 | steps: 14 | - uses: actions/checkout@v4 15 | - uses: dtolnay/rust-toolchain@stable 16 | with: 17 | components: rustfmt 18 | - run: cargo fmt -- --check 19 | 20 | clippy: 21 | name: Clippy check 22 | runs-on: ubuntu-latest 23 | steps: 24 | - uses: actions/checkout@v4 25 | - uses: dtolnay/rust-toolchain@stable 26 | with: 27 | components: clippy 28 | - uses: Swatinem/rust-cache@v2 29 | - run: cargo clippy --all-targets --all-features -- --deny warnings 30 | 31 | test: 32 | name: Test code 33 | runs-on: ubuntu-latest 34 | strategy: 35 | matrix: 36 | rust_version: [stable, beta, nightly] 37 | fail-fast: false 38 | steps: 39 | - uses: actions/checkout@v3 40 | - uses: dtolnay/rust-toolchain@master 41 | with: 42 | toolchain: ${{matrix.rust_version}} 43 | - uses: Swatinem/rust-cache@v2 44 | with: 45 | key: ${{matrix.rust_version}} 46 | - run: cargo update 47 | - run: cargo test --all-features 48 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | Cargo.lock 3 | .vscode 4 | .idea -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "ego-tree" 3 | edition = "2021" 4 | version = "0.10.0" 5 | description = "Vec-backed ID-tree" 6 | keywords = ["tree", "vec", "id", "index"] 7 | authors = [ 8 | "June McEnroe ", 9 | "Carlo Federico Vescovo ", 10 | ] 11 | license = "ISC" 12 | repository = "https://github.com/rust-scraper/ego-tree" 13 | readme = "README.md" 14 | 15 | [features] 16 | serde = ["dep:serde"] 17 | 18 | [dependencies] 19 | serde = { version = "1.0.209", optional = true } 20 | 21 | [dev-dependencies] 22 | serde = "1.0.209" 23 | serde_test = "1.0.177" 24 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright © 2016, June McEnroe 2 | Copyright © 2024-2025, rust-scraper Contributors 3 | 4 | Permission to use, copy, modify, and/or distribute this software for any 5 | purpose with or without fee is hereby granted, provided that the above 6 | copyright notice and this permission notice appear in all copies. 7 | 8 | THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 9 | WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 10 | MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 11 | ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 12 | WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 13 | ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 14 | OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 15 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Ego Tree 2 | 3 | [![crates.io](https://img.shields.io/crates/v/ego-tree?color=dark-green)][crate] 4 | [![downloads](https://img.shields.io/crates/d/ego-tree)][crate] 5 | [![test](https://github.com/rust-scraper/ego-tree/actions/workflows/test.yml/badge.svg)][tests] 6 | 7 | `ego-tree` is a Rust crate that provides a Vec-backed ID-tree implementation. It offers a flexible and efficient way to create and manipulate tree structures in Rust, with a focus on performance and ease of use. 8 | 9 | `ego-tree` is on [Crates.io][crate] and [GitHub][github]. 10 | 11 | ## Design Philosophy 12 | 13 | The design of `ego-tree` is centered around the following principles: 14 | 15 | 1. **Efficiency**: The tree structure is backed by a Vec, allowing for fast, cache-friendly operations and efficient memory usage. 16 | 17 | 2. **Flexibility**: Nodes can have any number of children, allowing for the representation of various tree structures. 18 | 19 | 3. **Stability**: Node references remain valid even after modifying the tree structure, thanks to the use of stable NodeId indices. 20 | 21 | 4. **Safety**: The API is designed to prevent common errors, such as creating cycles or detaching the root node. 22 | 23 | 5. **Ergonomics**: The crate provides both low-level operations and high-level conveniences like the `tree!` macro for easy tree construction. 24 | 25 | ## Key Design Choices 26 | 27 | ### Vec-Backed Structure 28 | 29 | Unlike traditional pointer-based trees, `ego-tree` uses a Vec to store all nodes. This design choice offers several advantages: 30 | 31 | - Improved cache locality, potentially leading to better performance 32 | - Simplified memory management 33 | - Easier serialization and deserialization 34 | - Constant-time access to any node by its ID 35 | 36 | ### Node IDs 37 | 38 | Nodes are identified by `NodeId`s, which are wrappers around indices into the underlying Vec. This approach allows for: 39 | 40 | - Stable references to nodes, even as the tree structure changes 41 | - Efficient node lookup (O(1) time complexity) 42 | - Compact representation of relationships between nodes 43 | 44 | ### Immutable and Mutable Node References 45 | 46 | The crate provides both `NodeRef` (immutable) and `NodeMut` (mutable) types for working with nodes. This separation allows for: 47 | 48 | - Clear distinction between read-only and modifying operations 49 | - Prevention of multiple mutable references to the same node, enforcing Rust's borrowing rules 50 | - Efficient implementation of various tree traversal iterators 51 | 52 | ### Orphan Nodes 53 | 54 | Nodes can be detached from the tree but not removed entirely. This design choice: 55 | 56 | - Simplifies certain tree manipulation algorithms 57 | - Allows for temporary detachment and reattachment of subtrees 58 | - Maintains the validity of NodeIds, even for detached nodes 59 | 60 | ### Rich Iterator Support 61 | 62 | The crate provides a variety of iterator types for traversing the tree in different ways. This design: 63 | 64 | - Allows for efficient and idiomatic tree traversal 65 | - Supports various algorithms and use cases without sacrificing performance 66 | - Leverages Rust's powerful iterator ecosystem 67 | 68 | ## Use Cases 69 | 70 | `ego-tree` is well-suited for applications that require: 71 | 72 | - Efficient representation and manipulation of hierarchical data structures 73 | - Frequent traversal and modification of tree structures 74 | - Stable references to tree nodes across operations 75 | - Serialization and deserialization of tree structures 76 | 77 | Some potential use cases include: 78 | 79 | - DOM-like structures for document processing 80 | - File system representations 81 | - Organizational hierarchies 82 | - Game scene graphs 83 | - Abstract syntax trees for compilers or interpreters 84 | 85 | ## Getting Started 86 | 87 | Add this to your `Cargo.toml`: 88 | 89 | ```toml 90 | [dependencies] 91 | ego-tree = "0.6.2" 92 | ``` 93 | 94 | Basic usage: 95 | 96 | ```rust 97 | use ego_tree::Tree; 98 | 99 | let mut tree = Tree::new(1); 100 | let mut root = tree.root_mut(); 101 | root.append(2); 102 | let mut child = root.append(3); 103 | child.append(4); 104 | child.append(5); 105 | ``` 106 | 107 | For more detailed usage examples and API documentation, please refer to the [documentation](https://docs.rs/ego-tree). 108 | 109 | ## License 110 | 111 | This project is licensed under the ISC License. 112 | 113 | ## Contributing 114 | 115 | Contributions are welcome! Please feel free to submit a Pull Request. 116 | 117 | ## Credits 118 | 119 | `ego-tree` is created and maintained by the team of [rust-scraper](https://github.com/rust-scraper). 120 | 121 | [crate]: https://crates.io/crates/ego-tree 122 | [github]: https://github.com/rust-scraper/ego-tree 123 | [tests]: https://github.com/rust-scraper/ego-tree/actions/workflows/test.yml 124 | -------------------------------------------------------------------------------- /examples/simple_tree.rs: -------------------------------------------------------------------------------- 1 | //! Implements this tree 2 | //! ``` 3 | //! 1 4 | //! ├── 2 5 | //! └── 3 6 | //! ├── 4 7 | //! └── 5 8 | //! ``` 9 | 10 | use ego_tree::{tree, NodeMut, Tree}; 11 | 12 | fn main() { 13 | // Manual construction of the tree 14 | let mut tree: Tree = Tree::new(1); 15 | let mut root: NodeMut = tree.root_mut(); 16 | root.append(2); 17 | let mut child: NodeMut = root.append(3); 18 | child.append(4); 19 | child.append(5); 20 | println!("Manual:\n{tree}"); 21 | 22 | // Construction of the tree through the tree! macro 23 | let macro_tree: Tree = tree!(1 => {2, 3 => {4, 5}}); 24 | println!("Automated:\n{macro_tree}"); 25 | 26 | // Prooving equality 27 | assert_eq!(tree, macro_tree); 28 | } 29 | -------------------------------------------------------------------------------- /src/display.rs: -------------------------------------------------------------------------------- 1 | use std::fmt::Display; 2 | 3 | /// Indentation token 4 | #[derive(Debug)] 5 | struct Token { 6 | /// Is followed by a brother 7 | siblings: bool, 8 | /// Is intermediate while printing children 9 | children: bool, 10 | } 11 | 12 | impl Display for Token { 13 | fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { 14 | let Token { siblings, children } = self; 15 | 16 | write!( 17 | f, 18 | "{}", 19 | match (siblings, children) { 20 | (true, true) => "│ ", 21 | (true, false) => "├── ", 22 | (false, true) => " ", 23 | (false, false) => "└── ", 24 | } 25 | ) 26 | } 27 | } 28 | 29 | impl Token { 30 | /// Create a new indentation token 31 | fn new(siblings: bool) -> Self { 32 | Token { 33 | siblings, 34 | children: false, 35 | } 36 | } 37 | 38 | /// Set children flag before starting displaying children 39 | fn set_children(&mut self) { 40 | self.children = true; 41 | } 42 | } 43 | 44 | /// Manages the state during the display operation 45 | #[derive(Debug)] 46 | pub struct Indentation { 47 | tokens: Vec, 48 | ignore_root: bool, 49 | } 50 | 51 | impl Display for Indentation { 52 | fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { 53 | let first: usize = if self.ignore_root { 1 } else { 0 }; 54 | 55 | for token in &self.tokens[first..] { 56 | write!(f, "{token}")?; 57 | } 58 | 59 | Ok(()) 60 | } 61 | } 62 | 63 | impl Indentation { 64 | /// Creates a new indentation handler 65 | pub fn new(ignore_root: bool) -> Self { 66 | Indentation { 67 | tokens: Vec::new(), 68 | ignore_root, 69 | } 70 | } 71 | 72 | /// Adds a new layer of indentation 73 | pub fn indent(&mut self, siblings: bool) -> &mut Self { 74 | // Setup children mode for previous tokens 75 | let len = self.tokens.len(); 76 | if len > 0 { 77 | self.tokens[len - 1].set_children(); 78 | } 79 | 80 | self.tokens.push(Token::new(siblings)); 81 | self 82 | } 83 | 84 | /// Removes the last layer of indentation 85 | pub fn deindent(&mut self) -> &mut Self { 86 | self.tokens.pop(); 87 | self 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /src/iter.rs: -------------------------------------------------------------------------------- 1 | use std::iter::FusedIterator; 2 | use std::ops::Range; 3 | use std::{slice, vec}; 4 | 5 | use crate::{Node, NodeId, NodeRef, Tree}; 6 | 7 | /// Iterator that moves out of a tree in insert order. 8 | #[derive(Debug)] 9 | pub struct IntoIter(vec::IntoIter>); 10 | impl ExactSizeIterator for IntoIter {} 11 | impl FusedIterator for IntoIter {} 12 | impl Iterator for IntoIter { 13 | type Item = T; 14 | fn next(&mut self) -> Option { 15 | self.0.next().map(|node| node.value) 16 | } 17 | fn size_hint(&self) -> (usize, Option) { 18 | self.0.size_hint() 19 | } 20 | } 21 | impl DoubleEndedIterator for IntoIter { 22 | fn next_back(&mut self) -> Option { 23 | self.0.next_back().map(|node| node.value) 24 | } 25 | } 26 | 27 | /// Iterator over values in insert order. 28 | #[derive(Debug)] 29 | pub struct Values<'a, T: 'a>(slice::Iter<'a, Node>); 30 | impl<'a, T: 'a> Clone for Values<'a, T> { 31 | fn clone(&self) -> Self { 32 | Values(self.0.clone()) 33 | } 34 | } 35 | impl<'a, T: 'a> ExactSizeIterator for Values<'a, T> {} 36 | impl<'a, T: 'a> FusedIterator for Values<'a, T> {} 37 | impl<'a, T: 'a> Iterator for Values<'a, T> { 38 | type Item = &'a T; 39 | fn next(&mut self) -> Option { 40 | self.0.next().map(|node| &node.value) 41 | } 42 | fn size_hint(&self) -> (usize, Option) { 43 | self.0.size_hint() 44 | } 45 | } 46 | impl<'a, T: 'a> DoubleEndedIterator for Values<'a, T> { 47 | fn next_back(&mut self) -> Option { 48 | self.0.next_back().map(|node| &node.value) 49 | } 50 | } 51 | 52 | /// Mutable iterator over values in insert order. 53 | #[derive(Debug)] 54 | pub struct ValuesMut<'a, T: 'a>(slice::IterMut<'a, Node>); 55 | impl<'a, T: 'a> ExactSizeIterator for ValuesMut<'a, T> {} 56 | impl<'a, T: 'a> FusedIterator for ValuesMut<'a, T> {} 57 | impl<'a, T: 'a> Iterator for ValuesMut<'a, T> { 58 | type Item = &'a mut T; 59 | fn next(&mut self) -> Option { 60 | self.0.next().map(|node| &mut node.value) 61 | } 62 | fn size_hint(&self) -> (usize, Option) { 63 | self.0.size_hint() 64 | } 65 | } 66 | impl<'a, T: 'a> DoubleEndedIterator for ValuesMut<'a, T> { 67 | fn next_back(&mut self) -> Option { 68 | self.0.next_back().map(|node| &mut node.value) 69 | } 70 | } 71 | 72 | /// Iterator over nodes in insert order. 73 | #[derive(Debug)] 74 | pub struct Nodes<'a, T: 'a> { 75 | tree: &'a Tree, 76 | iter: Range, 77 | } 78 | impl<'a, T: 'a> Clone for Nodes<'a, T> { 79 | fn clone(&self) -> Self { 80 | Self { 81 | tree: self.tree, 82 | iter: self.iter.clone(), 83 | } 84 | } 85 | } 86 | impl<'a, T: 'a> ExactSizeIterator for Nodes<'a, T> {} 87 | impl<'a, T: 'a> FusedIterator for Nodes<'a, T> {} 88 | impl<'a, T: 'a> Iterator for Nodes<'a, T> { 89 | type Item = NodeRef<'a, T>; 90 | fn next(&mut self) -> Option { 91 | self.iter 92 | .next() 93 | .map(|i| unsafe { self.tree.get_unchecked(NodeId::from_index(i)) }) 94 | } 95 | fn size_hint(&self) -> (usize, Option) { 96 | self.iter.size_hint() 97 | } 98 | } 99 | impl<'a, T: 'a> DoubleEndedIterator for Nodes<'a, T> { 100 | fn next_back(&mut self) -> Option { 101 | self.iter 102 | .next_back() 103 | .map(|i| unsafe { self.tree.get_unchecked(NodeId::from_index(i)) }) 104 | } 105 | } 106 | 107 | impl IntoIterator for Tree { 108 | type Item = T; 109 | type IntoIter = IntoIter; 110 | fn into_iter(self) -> Self::IntoIter { 111 | IntoIter(self.vec.into_iter()) 112 | } 113 | } 114 | 115 | impl Tree { 116 | /// Returns an iterator over values in insert order. 117 | pub fn values(&self) -> Values { 118 | Values(self.vec.iter()) 119 | } 120 | 121 | /// Returns a mutable iterator over values in insert order. 122 | pub fn values_mut(&mut self) -> ValuesMut { 123 | ValuesMut(self.vec.iter_mut()) 124 | } 125 | 126 | /// Returns an iterator over nodes in insert order. 127 | pub fn nodes(&self) -> Nodes { 128 | Nodes { 129 | tree: self, 130 | iter: 0..self.vec.len(), 131 | } 132 | } 133 | } 134 | 135 | macro_rules! axis_iterators { 136 | ($(#[$m:meta] $i:ident($f:path);)*) => { 137 | $( 138 | #[$m] 139 | #[derive(Debug)] 140 | pub struct $i<'a, T: 'a>(Option>); 141 | impl<'a, T: 'a> Clone for $i<'a, T> { 142 | fn clone(&self) -> Self { 143 | $i(self.0) 144 | } 145 | } 146 | impl<'a, T: 'a> FusedIterator for $i<'a, T> {} 147 | impl<'a, T: 'a> Iterator for $i<'a, T> { 148 | type Item = NodeRef<'a, T>; 149 | fn next(&mut self) -> Option { 150 | let node = self.0.take(); 151 | self.0 = node.as_ref().and_then($f); 152 | node 153 | } 154 | } 155 | )* 156 | }; 157 | } 158 | 159 | axis_iterators! { 160 | /// Iterator over ancestors. 161 | Ancestors(NodeRef::parent); 162 | 163 | /// Iterator over previous siblings. 164 | PrevSiblings(NodeRef::prev_sibling); 165 | 166 | /// Iterator over next siblings. 167 | NextSiblings(NodeRef::next_sibling); 168 | 169 | /// Iterator over first children. 170 | FirstChildren(NodeRef::first_child); 171 | 172 | /// Iterator over last children. 173 | LastChildren(NodeRef::last_child); 174 | } 175 | 176 | /// Iterator over children. 177 | #[derive(Debug)] 178 | pub struct Children<'a, T: 'a> { 179 | front: Option>, 180 | back: Option>, 181 | } 182 | impl<'a, T: 'a> Clone for Children<'a, T> { 183 | fn clone(&self) -> Self { 184 | Self { 185 | front: self.front, 186 | back: self.back, 187 | } 188 | } 189 | } 190 | impl<'a, T: 'a> FusedIterator for Children<'a, T> {} 191 | impl<'a, T: 'a> Iterator for Children<'a, T> { 192 | type Item = NodeRef<'a, T>; 193 | fn next(&mut self) -> Option { 194 | if self.front == self.back { 195 | let node = self.front.take(); 196 | self.back = None; 197 | node 198 | } else { 199 | let node = self.front.take(); 200 | self.front = node.as_ref().and_then(NodeRef::next_sibling); 201 | node 202 | } 203 | } 204 | } 205 | impl<'a, T: 'a> DoubleEndedIterator for Children<'a, T> { 206 | fn next_back(&mut self) -> Option { 207 | if self.back == self.front { 208 | let node = self.back.take(); 209 | self.front = None; 210 | node 211 | } else { 212 | let node = self.back.take(); 213 | self.back = node.as_ref().and_then(NodeRef::prev_sibling); 214 | node 215 | } 216 | } 217 | } 218 | 219 | /// Open or close edge of a node. 220 | #[derive(Debug)] 221 | pub enum Edge<'a, T: 'a> { 222 | /// Open. 223 | Open(NodeRef<'a, T>), 224 | /// Close. 225 | Close(NodeRef<'a, T>), 226 | } 227 | impl<'a, T: 'a> Copy for Edge<'a, T> {} 228 | impl<'a, T: 'a> Clone for Edge<'a, T> { 229 | fn clone(&self) -> Self { 230 | *self 231 | } 232 | } 233 | impl<'a, T: 'a> Eq for Edge<'a, T> {} 234 | impl<'a, T: 'a> PartialEq for Edge<'a, T> { 235 | fn eq(&self, other: &Self) -> bool { 236 | match (*self, *other) { 237 | (Edge::Open(a), Edge::Open(b)) | (Edge::Close(a), Edge::Close(b)) => a == b, 238 | _ => false, 239 | } 240 | } 241 | } 242 | 243 | /// Iterator which traverses a subtree. 244 | #[derive(Debug)] 245 | pub struct Traverse<'a, T: 'a> { 246 | root: Option>, 247 | edge: Option>, 248 | } 249 | impl<'a, T: 'a> Clone for Traverse<'a, T> { 250 | fn clone(&self) -> Self { 251 | Self { 252 | root: self.root, 253 | edge: self.edge, 254 | } 255 | } 256 | } 257 | impl<'a, T: 'a> FusedIterator for Traverse<'a, T> {} 258 | impl<'a, T: 'a> Iterator for Traverse<'a, T> { 259 | type Item = Edge<'a, T>; 260 | fn next(&mut self) -> Option { 261 | match self.edge { 262 | None => { 263 | if let Some(root) = self.root { 264 | self.edge = Some(Edge::Open(root)); 265 | } 266 | } 267 | Some(Edge::Open(node)) => { 268 | if let Some(first_child) = node.first_child() { 269 | self.edge = Some(Edge::Open(first_child)); 270 | } else { 271 | self.edge = Some(Edge::Close(node)); 272 | } 273 | } 274 | Some(Edge::Close(node)) => { 275 | if node == self.root.unwrap() { 276 | self.root = None; 277 | self.edge = None; 278 | } else if let Some(next_sibling) = node.next_sibling() { 279 | self.edge = Some(Edge::Open(next_sibling)); 280 | } else { 281 | self.edge = node.parent().map(Edge::Close); 282 | } 283 | } 284 | } 285 | self.edge 286 | } 287 | } 288 | 289 | /// Iterator over a node and its descendants. 290 | #[derive(Debug)] 291 | pub struct Descendants<'a, T: 'a>(Traverse<'a, T>); 292 | impl<'a, T: 'a> Clone for Descendants<'a, T> { 293 | fn clone(&self) -> Self { 294 | Descendants(self.0.clone()) 295 | } 296 | } 297 | impl<'a, T: 'a> FusedIterator for Descendants<'a, T> {} 298 | impl<'a, T: 'a> Iterator for Descendants<'a, T> { 299 | type Item = NodeRef<'a, T>; 300 | fn next(&mut self) -> Option { 301 | for edge in &mut self.0 { 302 | if let Edge::Open(node) = edge { 303 | return Some(node); 304 | } 305 | } 306 | None 307 | } 308 | } 309 | 310 | impl<'a, T: 'a> NodeRef<'a, T> { 311 | /// Returns an iterator over ancestors. 312 | pub fn ancestors(&self) -> Ancestors<'a, T> { 313 | Ancestors(self.parent()) 314 | } 315 | 316 | /// Returns an iterator over previous siblings. 317 | pub fn prev_siblings(&self) -> PrevSiblings<'a, T> { 318 | PrevSiblings(self.prev_sibling()) 319 | } 320 | 321 | /// Returns an iterator over next siblings. 322 | pub fn next_siblings(&self) -> NextSiblings<'a, T> { 323 | NextSiblings(self.next_sibling()) 324 | } 325 | 326 | /// Returns an iterator over first children. 327 | pub fn first_children(&self) -> FirstChildren<'a, T> { 328 | FirstChildren(self.first_child()) 329 | } 330 | 331 | /// Returns an iterator over last children. 332 | pub fn last_children(&self) -> LastChildren<'a, T> { 333 | LastChildren(self.last_child()) 334 | } 335 | 336 | /// Returns an iterator over children. 337 | pub fn children(&self) -> Children<'a, T> { 338 | Children { 339 | front: self.first_child(), 340 | back: self.last_child(), 341 | } 342 | } 343 | 344 | /// Returns an iterator which traverses the subtree starting at this node. 345 | pub fn traverse(&self) -> Traverse<'a, T> { 346 | Traverse { 347 | root: Some(*self), 348 | edge: None, 349 | } 350 | } 351 | 352 | /// Returns an iterator over this node and its descendants. 353 | pub fn descendants(&self) -> Descendants<'a, T> { 354 | Descendants(self.traverse()) 355 | } 356 | } 357 | -------------------------------------------------------------------------------- /src/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 | 38 | use std::fmt::{self, Debug, Display, Formatter}; 39 | use std::num::NonZeroUsize; 40 | 41 | #[cfg(feature = "serde")] 42 | pub mod serde; 43 | 44 | /// Vec-backed ID-tree. 45 | /// 46 | /// Always contains at least a root node. 47 | #[derive(Clone, PartialEq, Eq, Hash)] 48 | pub struct Tree { 49 | vec: Vec>, 50 | } 51 | 52 | /// Node ID. 53 | /// 54 | /// Index into a `Tree`-internal `Vec`. 55 | #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] 56 | pub struct NodeId(NonZeroUsize); 57 | 58 | impl 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)] 72 | struct Node { 73 | parent: Option, 74 | prev_sibling: Option, 75 | next_sibling: Option, 76 | children: Option<(NodeId, NodeId)>, 77 | value: T, 78 | } 79 | 80 | fn _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::, [usize; 5]>; 85 | } 86 | 87 | impl Node { 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(self, mut transform: F) -> Node 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(&self, mut transform: F) -> Node 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)] 127 | pub struct NodeRef<'a, T: 'a> { 128 | /// Node ID. 129 | id: NodeId, 130 | 131 | /// Tree containing the node. 132 | tree: &'a Tree, 133 | 134 | node: &'a Node, 135 | } 136 | 137 | /// Node mutator. 138 | #[derive(Debug)] 139 | pub struct NodeMut<'a, T: 'a> { 140 | /// Node ID. 141 | id: NodeId, 142 | 143 | /// Tree containing the node. 144 | tree: &'a mut Tree, 145 | } 146 | 147 | // Trait implementations regardless of T. 148 | 149 | impl<'a, T: 'a> Copy for NodeRef<'a, T> {} 150 | impl<'a, T: 'a> Clone for NodeRef<'a, T> { 151 | fn clone(&self) -> Self { 152 | *self 153 | } 154 | } 155 | 156 | impl<'a, T: 'a> Eq for NodeRef<'a, T> {} 157 | impl<'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 | 165 | impl Tree { 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> { 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> { 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 { 196 | self.vec.get_unchecked(id.to_index()) 197 | } 198 | 199 | unsafe fn node_mut(&mut self, id: NodeId) -> &mut Node { 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 { 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 { 218 | NodeMut { id, tree: self } 219 | } 220 | 221 | /// Returns a reference to the root node. 222 | pub fn root(&self) -> NodeRef { 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 { 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 { 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) -> NodeMut { 242 | let offset = self.vec.len(); 243 | let offset_id = |id: NodeId| -> NodeId { 244 | let old_index = id.to_index(); 245 | let new_index = old_index + offset; 246 | unsafe { NodeId::from_index(new_index) } 247 | }; 248 | let other_tree_root_id = offset_id(other_tree.root().id); 249 | for node in other_tree.vec.iter_mut() { 250 | node.parent.as_mut().map(|id| *id = offset_id(*id)); 251 | node.prev_sibling.as_mut().map(|id| *id = offset_id(*id)); 252 | node.next_sibling.as_mut().map(|id| *id = offset_id(*id)); 253 | node.children.as_mut().map(|(id1, id2)| { 254 | *id1 = offset_id(*id1); 255 | *id2 = offset_id(*id2); 256 | }); 257 | } 258 | self.vec.append(&mut other_tree.vec); 259 | unsafe { self.get_unchecked_mut(other_tree_root_id) } 260 | } 261 | 262 | /// Maps a `Tree` to `Tree` 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(self, mut transform: F) -> Tree 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` to `Tree` by applying a function to all node values, 278 | /// copying over the tree's structure and node ids untouched. 279 | pub fn map_ref(&self, mut transform: F) -> Tree 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 | 293 | impl<'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 { 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(&self, f: F) -> Option 310 | where 311 | F: FnOnce(&Node) -> Option, 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 { 318 | self.axis(|node| node.parent) 319 | } 320 | 321 | /// Returns the previous sibling of this node. 322 | pub fn prev_sibling(&self) -> Option { 323 | self.axis(|node| node.prev_sibling) 324 | } 325 | 326 | /// Returns the next sibling of this node. 327 | pub fn next_sibling(&self) -> Option { 328 | self.axis(|node| node.next_sibling) 329 | } 330 | 331 | /// Returns the first child of this node. 332 | pub fn first_child(&self) -> Option { 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 { 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 | 352 | impl<'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 { 360 | self.tree 361 | } 362 | 363 | fn node(&mut self) -> &mut Node { 364 | unsafe { self.tree.node_mut(self.id) } 365 | } 366 | 367 | /// Returns the value of this node. 368 | pub fn value(&mut self) -> &mut T { 369 | &mut self.node().value 370 | } 371 | 372 | /// Downcast `NodeMut` to `NodeRef`. 373 | pub fn as_ref(&mut self) -> NodeRef<'_, T> { 374 | unsafe { self.tree.get_unchecked(self.id) } 375 | } 376 | 377 | fn axis(&mut self, f: F) -> Option> 378 | where 379 | F: FnOnce(&mut Node) -> Option, 380 | { 381 | let id = f(self.node()); 382 | id.map(move |id| unsafe { self.tree.get_unchecked_mut(id) }) 383 | } 384 | 385 | fn into_axis(mut self, f: F) -> Result 386 | where 387 | F: FnOnce(&mut Node) -> Option, 388 | { 389 | let id = f(self.node()); 390 | match id { 391 | Some(id) => Ok(unsafe { self.tree.get_unchecked_mut(id) }), 392 | None => Err(self), 393 | } 394 | } 395 | 396 | /// Returns the parent of this node. 397 | pub fn parent(&mut self) -> Option> { 398 | self.axis(|node| node.parent) 399 | } 400 | 401 | /// Returns the parent of this node. 402 | /// 403 | /// Returns `Ok(parent)` if possible and `Err(self)` otherwise 404 | /// so the caller can recover the current position. 405 | pub fn into_parent(self) -> Result { 406 | self.into_axis(|node| node.parent) 407 | } 408 | 409 | /// Returns the previous sibling of this node. 410 | pub fn prev_sibling(&mut self) -> Option> { 411 | self.axis(|node| node.prev_sibling) 412 | } 413 | 414 | /// Returns the previous sibling of this node. 415 | /// 416 | /// Returns `Ok(prev_sibling)` if possible and `Err(self)` otherwise 417 | /// so the caller can recover the current position. 418 | pub fn into_prev_sibling(self) -> Result { 419 | self.into_axis(|node| node.prev_sibling) 420 | } 421 | 422 | /// Returns the next sibling of this node. 423 | pub fn next_sibling(&mut self) -> Option> { 424 | self.axis(|node| node.next_sibling) 425 | } 426 | 427 | /// Returns the next sibling of this node. 428 | /// 429 | /// Returns `Ok(next_sibling)` if possible and `Err(self)` otherwise 430 | /// so the caller can recover the current position. 431 | pub fn into_next_sibling(self) -> Result { 432 | self.into_axis(|node| node.next_sibling) 433 | } 434 | 435 | /// Returns the first child of this node. 436 | pub fn first_child(&mut self) -> Option> { 437 | self.axis(|node| node.children.map(|(id, _)| id)) 438 | } 439 | 440 | /// Returns the first child of this node. 441 | /// 442 | /// Returns `Ok(first_child)` if possible and `Err(self)` otherwise 443 | /// so the caller can recover the current position. 444 | pub fn into_first_child(self) -> Result { 445 | self.into_axis(|node| node.children.map(|(id, _)| id)) 446 | } 447 | 448 | /// Returns the last child of this node. 449 | pub fn last_child(&mut self) -> Option> { 450 | self.axis(|node| node.children.map(|(_, id)| id)) 451 | } 452 | 453 | /// Returns the last child of this node. 454 | /// 455 | /// Returns `Ok(last_child)` if possible and `Err(self)` otherwise 456 | /// so the caller can recover the current position. 457 | pub fn into_last_child(self) -> Result { 458 | self.into_axis(|node| node.children.map(|(_, id)| id)) 459 | } 460 | 461 | /// Returns true if this node has siblings. 462 | pub fn has_siblings(&self) -> bool { 463 | unsafe { self.tree.get_unchecked(self.id).has_siblings() } 464 | } 465 | 466 | /// Returns true if this node has children. 467 | pub fn has_children(&self) -> bool { 468 | unsafe { self.tree.get_unchecked(self.id).has_children() } 469 | } 470 | 471 | /// Apply function for each ancestor mutable node reference. 472 | pub fn for_each_ancestor<'b, F>(&'b mut self, mut f: F) 473 | where 474 | F: FnMut(&mut NodeMut<'b, T>), 475 | { 476 | let mut current = self.parent(); 477 | while let Some(mut node) = current { 478 | f(&mut node); 479 | current = node.into_parent().ok(); 480 | } 481 | } 482 | 483 | /// Apply function for each next sibling mutable node reference. 484 | pub fn for_each_next_sibling<'b, F>(&'b mut self, mut f: F) 485 | where 486 | F: FnMut(&mut NodeMut<'b, T>), 487 | { 488 | let mut current = self.next_sibling(); 489 | while let Some(mut node) = current { 490 | f(&mut node); 491 | current = node.into_next_sibling().ok(); 492 | } 493 | } 494 | 495 | /// Apply function for each previout sibling mutable node reference. 496 | pub fn for_each_prev_sibling<'b, F>(&'b mut self, mut f: F) 497 | where 498 | F: FnMut(&mut NodeMut<'b, T>), 499 | { 500 | let mut current = self.prev_sibling(); 501 | while let Some(mut node) = current { 502 | f(&mut node); 503 | current = node.into_prev_sibling().ok(); 504 | } 505 | } 506 | 507 | /// Apply function for this node and each sibling mutable node reference. 508 | pub fn for_each_sibling(&mut self, mut f: F) 509 | where 510 | F: for<'b> FnMut(&mut NodeMut<'b, T>), 511 | { 512 | self.for_each_prev_sibling(&mut f); 513 | f(self); 514 | self.for_each_next_sibling(&mut f); 515 | } 516 | 517 | /// Apply function for each children mutable node reference. 518 | pub fn for_each_child(&mut self, mut f: F) 519 | where 520 | F: for<'b> FnMut(&mut NodeMut<'b, T>), 521 | { 522 | let Some(mut first_child) = self.first_child() else { 523 | return; 524 | }; 525 | f(&mut first_child); 526 | first_child.for_each_next_sibling(f); 527 | } 528 | 529 | /// Apply function for this node and each descendant mutable node reference. 530 | pub fn for_each_descendant(&mut self, mut f: F) 531 | where 532 | F: FnMut(&mut NodeMut<'_, T>), 533 | { 534 | let id = self.id(); 535 | 536 | f(self); 537 | 538 | // Start at our first child, if any. 539 | let Some(mut node) = self.first_child() else { 540 | return; 541 | }; 542 | 543 | loop { 544 | f(&mut node); 545 | 546 | // Try to go deeper into its first child. 547 | match node.into_first_child() { 548 | Ok(child) => { 549 | node = child; 550 | continue; 551 | } 552 | Err(n) => { 553 | node = n; 554 | } 555 | } 556 | 557 | // No deeper child, so climb until we find a next sibling or hit self. 558 | loop { 559 | match node.into_next_sibling() { 560 | Ok(sib) => { 561 | node = sib; 562 | break; 563 | } 564 | Err(n) => { 565 | node = n; 566 | } 567 | } 568 | 569 | // No sibling, so climb up. 570 | let Ok(parent) = node.into_parent() else { 571 | unreachable!(); 572 | }; 573 | if parent.id() == id { 574 | return; 575 | } 576 | node = parent; 577 | } 578 | } 579 | } 580 | 581 | /// Appends a new child to this node. 582 | pub fn append(&mut self, value: T) -> NodeMut { 583 | let id = self.tree.orphan(value).id; 584 | self.append_id(id) 585 | } 586 | 587 | /// Prepends a new child to this node. 588 | pub fn prepend(&mut self, value: T) -> NodeMut { 589 | let id = self.tree.orphan(value).id; 590 | self.prepend_id(id) 591 | } 592 | 593 | /// Appends a subtree, return the root of the merged subtree. 594 | pub fn append_subtree(&mut self, subtree: Tree) -> NodeMut { 595 | let root_id = self.tree.extend_tree(subtree).id; 596 | self.append_id(root_id) 597 | } 598 | 599 | /// Prepends a subtree, return the root of the merged subtree. 600 | pub fn prepend_subtree(&mut self, subtree: Tree) -> NodeMut { 601 | let root_id = self.tree.extend_tree(subtree).id; 602 | self.prepend_id(root_id) 603 | } 604 | 605 | /// Inserts a new sibling before this node. 606 | /// 607 | /// # Panics 608 | /// 609 | /// Panics if this node is an orphan. 610 | pub fn insert_before(&mut self, value: T) -> NodeMut { 611 | let id = self.tree.orphan(value).id; 612 | self.insert_id_before(id) 613 | } 614 | 615 | /// Inserts a new sibling after this node. 616 | /// 617 | /// # Panics 618 | /// 619 | /// Panics if this node is an orphan. 620 | pub fn insert_after(&mut self, value: T) -> NodeMut { 621 | let id = self.tree.orphan(value).id; 622 | self.insert_id_after(id) 623 | } 624 | 625 | /// Detaches this node from its parent. 626 | pub fn detach(&mut self) { 627 | let parent_id = match self.node().parent { 628 | Some(id) => id, 629 | None => return, 630 | }; 631 | let prev_sibling_id = self.node().prev_sibling; 632 | let next_sibling_id = self.node().next_sibling; 633 | 634 | { 635 | self.node().parent = None; 636 | self.node().prev_sibling = None; 637 | self.node().next_sibling = None; 638 | } 639 | 640 | if let Some(id) = prev_sibling_id { 641 | unsafe { 642 | self.tree.node_mut(id).next_sibling = next_sibling_id; 643 | } 644 | } 645 | if let Some(id) = next_sibling_id { 646 | unsafe { 647 | self.tree.node_mut(id).prev_sibling = prev_sibling_id; 648 | } 649 | } 650 | 651 | let parent = unsafe { self.tree.node_mut(parent_id) }; 652 | let (first_child_id, last_child_id) = parent.children.unwrap(); 653 | if first_child_id == last_child_id { 654 | parent.children = None; 655 | } else if first_child_id == self.id { 656 | parent.children = Some((next_sibling_id.unwrap(), last_child_id)); 657 | } else if last_child_id == self.id { 658 | parent.children = Some((first_child_id, prev_sibling_id.unwrap())); 659 | } 660 | } 661 | 662 | /// Appends a child to this node. 663 | /// 664 | /// # Panics 665 | /// 666 | /// Panics if `new_child_id` is not valid. 667 | pub fn append_id(&mut self, new_child_id: NodeId) -> NodeMut { 668 | assert_ne!( 669 | self.id(), 670 | new_child_id, 671 | "Cannot append node as a child to itself" 672 | ); 673 | 674 | let last_child_id = self.node().children.map(|(_, id)| id); 675 | 676 | if last_child_id != Some(new_child_id) { 677 | { 678 | let mut new_child = self.tree.get_mut(new_child_id).unwrap(); 679 | new_child.detach(); 680 | new_child.node().parent = Some(self.id); 681 | new_child.node().prev_sibling = last_child_id; 682 | } 683 | 684 | if let Some(id) = last_child_id { 685 | unsafe { 686 | self.tree.node_mut(id).next_sibling = Some(new_child_id); 687 | } 688 | } 689 | 690 | { 691 | self.node().children = match self.node().children { 692 | Some((first_child_id, _)) => Some((first_child_id, new_child_id)), 693 | None => Some((new_child_id, new_child_id)), 694 | }; 695 | } 696 | } 697 | 698 | unsafe { self.tree.get_unchecked_mut(new_child_id) } 699 | } 700 | 701 | /// Prepends a child to this node. 702 | /// 703 | /// # Panics 704 | /// 705 | /// Panics if `new_child_id` is not valid. 706 | pub fn prepend_id(&mut self, new_child_id: NodeId) -> NodeMut { 707 | assert_ne!( 708 | self.id(), 709 | new_child_id, 710 | "Cannot prepend node as a child to itself" 711 | ); 712 | 713 | let first_child_id = self.node().children.map(|(id, _)| id); 714 | 715 | if first_child_id != Some(new_child_id) { 716 | { 717 | let mut new_child = self.tree.get_mut(new_child_id).unwrap(); 718 | new_child.detach(); 719 | new_child.node().parent = Some(self.id); 720 | new_child.node().next_sibling = first_child_id; 721 | } 722 | 723 | if let Some(id) = first_child_id { 724 | unsafe { 725 | self.tree.node_mut(id).prev_sibling = Some(new_child_id); 726 | } 727 | } 728 | 729 | { 730 | self.node().children = match self.node().children { 731 | Some((_, last_child_id)) => Some((new_child_id, last_child_id)), 732 | None => Some((new_child_id, new_child_id)), 733 | }; 734 | } 735 | } 736 | 737 | unsafe { self.tree.get_unchecked_mut(new_child_id) } 738 | } 739 | 740 | /// Inserts a sibling before this node. 741 | /// 742 | /// # Panics 743 | /// 744 | /// - Panics if `new_sibling_id` is not valid. 745 | /// - Panics if this node is an orphan. 746 | pub fn insert_id_before(&mut self, new_sibling_id: NodeId) -> NodeMut { 747 | assert_ne!( 748 | self.id(), 749 | new_sibling_id, 750 | "Cannot insert node as a sibling of itself" 751 | ); 752 | 753 | let parent_id = self.node().parent.unwrap(); 754 | let prev_sibling_id = self.node().prev_sibling; 755 | 756 | { 757 | let mut new_sibling = self.tree.get_mut(new_sibling_id).unwrap(); 758 | new_sibling.detach(); 759 | new_sibling.node().parent = Some(parent_id); 760 | new_sibling.node().prev_sibling = prev_sibling_id; 761 | new_sibling.node().next_sibling = Some(self.id); 762 | } 763 | 764 | if let Some(id) = prev_sibling_id { 765 | unsafe { 766 | self.tree.node_mut(id).next_sibling = Some(new_sibling_id); 767 | } 768 | } 769 | 770 | self.node().prev_sibling = Some(new_sibling_id); 771 | 772 | { 773 | let parent = unsafe { self.tree.node_mut(parent_id) }; 774 | let (first_child_id, last_child_id) = parent.children.unwrap(); 775 | if first_child_id == self.id { 776 | parent.children = Some((new_sibling_id, last_child_id)); 777 | } 778 | } 779 | 780 | unsafe { self.tree.get_unchecked_mut(new_sibling_id) } 781 | } 782 | 783 | /// Inserts a sibling after this node. 784 | /// 785 | /// # Panics 786 | /// 787 | /// - Panics if `new_sibling_id` is not valid. 788 | /// - Panics if this node is an orphan. 789 | pub fn insert_id_after(&mut self, new_sibling_id: NodeId) -> NodeMut { 790 | assert_ne!( 791 | self.id(), 792 | new_sibling_id, 793 | "Cannot insert node as a sibling of itself" 794 | ); 795 | 796 | let parent_id = self.node().parent.unwrap(); 797 | let next_sibling_id = self.node().next_sibling; 798 | 799 | { 800 | let mut new_sibling = self.tree.get_mut(new_sibling_id).unwrap(); 801 | new_sibling.detach(); 802 | new_sibling.node().parent = Some(parent_id); 803 | new_sibling.node().prev_sibling = Some(self.id); 804 | new_sibling.node().next_sibling = next_sibling_id; 805 | } 806 | 807 | if let Some(id) = next_sibling_id { 808 | unsafe { 809 | self.tree.node_mut(id).prev_sibling = Some(new_sibling_id); 810 | } 811 | } 812 | 813 | self.node().next_sibling = Some(new_sibling_id); 814 | 815 | { 816 | let parent = unsafe { self.tree.node_mut(parent_id) }; 817 | let (first_child_id, last_child_id) = parent.children.unwrap(); 818 | if last_child_id == self.id { 819 | parent.children = Some((first_child_id, new_sibling_id)); 820 | } 821 | } 822 | 823 | unsafe { self.tree.get_unchecked_mut(new_sibling_id) } 824 | } 825 | 826 | /// Reparents the children of a node, appending them to this node. 827 | /// 828 | /// # Panics 829 | /// 830 | /// Panics if `from_id` is not valid. 831 | pub fn reparent_from_id_append(&mut self, from_id: NodeId) { 832 | assert_ne!( 833 | self.id(), 834 | from_id, 835 | "Cannot reparent node's children to itself" 836 | ); 837 | 838 | let new_child_ids = { 839 | let mut from = self.tree.get_mut(from_id).unwrap(); 840 | match from.node().children.take() { 841 | Some(ids) => ids, 842 | None => return, 843 | } 844 | }; 845 | 846 | unsafe { 847 | self.tree.node_mut(new_child_ids.0).parent = Some(self.id); 848 | self.tree.node_mut(new_child_ids.1).parent = Some(self.id); 849 | } 850 | 851 | if self.node().children.is_none() { 852 | self.node().children = Some(new_child_ids); 853 | return; 854 | } 855 | 856 | let old_child_ids = self.node().children.unwrap(); 857 | unsafe { 858 | self.tree.node_mut(old_child_ids.1).next_sibling = Some(new_child_ids.0); 859 | self.tree.node_mut(new_child_ids.0).prev_sibling = Some(old_child_ids.1); 860 | } 861 | 862 | self.node().children = Some((old_child_ids.0, new_child_ids.1)); 863 | } 864 | 865 | /// Reparents the children of a node, prepending them to this node. 866 | /// 867 | /// # Panics 868 | /// 869 | /// Panics if `from_id` is not valid. 870 | pub fn reparent_from_id_prepend(&mut self, from_id: NodeId) { 871 | assert_ne!( 872 | self.id(), 873 | from_id, 874 | "Cannot reparent node's children to itself" 875 | ); 876 | 877 | let new_child_ids = { 878 | let mut from = self.tree.get_mut(from_id).unwrap(); 879 | match from.node().children.take() { 880 | Some(ids) => ids, 881 | None => return, 882 | } 883 | }; 884 | 885 | unsafe { 886 | self.tree.node_mut(new_child_ids.0).parent = Some(self.id); 887 | self.tree.node_mut(new_child_ids.1).parent = Some(self.id); 888 | } 889 | 890 | if self.node().children.is_none() { 891 | self.node().children = Some(new_child_ids); 892 | return; 893 | } 894 | 895 | let old_child_ids = self.node().children.unwrap(); 896 | unsafe { 897 | self.tree.node_mut(old_child_ids.0).prev_sibling = Some(new_child_ids.1); 898 | self.tree.node_mut(new_child_ids.1).next_sibling = Some(old_child_ids.0); 899 | } 900 | 901 | self.node().children = Some((new_child_ids.0, old_child_ids.1)); 902 | } 903 | } 904 | 905 | impl<'a, T: 'a> From> for NodeRef<'a, T> { 906 | fn from(node: NodeMut<'a, T>) -> Self { 907 | unsafe { node.tree.get_unchecked(node.id) } 908 | } 909 | } 910 | 911 | /// Iterators. 912 | pub mod iter; 913 | 914 | /// Creates a tree from expressions. 915 | /// 916 | /// # Examples 917 | /// 918 | /// ``` 919 | /// #[macro_use] extern crate ego_tree; 920 | /// # fn main() { 921 | /// let tree = tree!("root"); 922 | /// # } 923 | /// ``` 924 | /// 925 | /// ``` 926 | /// #[macro_use] extern crate ego_tree; 927 | /// # fn main() { 928 | /// let tree = tree! { 929 | /// "root" => { 930 | /// "child a", 931 | /// "child b" => { 932 | /// "grandchild a", 933 | /// "grandchild b", 934 | /// }, 935 | /// "child c", 936 | /// } 937 | /// }; 938 | /// # } 939 | /// ``` 940 | /// Compose trees using the `@` marker: 941 | /// ``` 942 | /// #[macro_use] extern crate ego_tree; 943 | /// # fn main() { 944 | /// let subtree = tree! { 945 | /// "foo" => { "bar", "baz" } 946 | /// }; 947 | /// let new_tree = tree! { 948 | /// "root" => { 949 | /// "child x", 950 | /// "child y", 951 | /// @ subtree, 952 | /// } 953 | /// }; 954 | /// # } 955 | /// ``` 956 | #[macro_export] 957 | macro_rules! tree { 958 | (@ $n:ident { }) => { }; 959 | 960 | // Last leaf. 961 | (@ $n:ident { $value:expr }) => { 962 | { $n.append($value); } 963 | }; 964 | 965 | // Leaf. 966 | (@ $n:ident { $value:expr, $($tail:tt)* }) => { 967 | { 968 | $n.append($value); 969 | tree!(@ $n { $($tail)* }); 970 | } 971 | }; 972 | 973 | // Last node with children. 974 | (@ $n:ident { $value:expr => $children:tt }) => { 975 | { 976 | let mut node = $n.append($value); 977 | tree!(@ node $children); 978 | } 979 | }; 980 | 981 | // Node with children. 982 | (@ $n:ident { $value:expr => $children:tt, $($tail:tt)* }) => { 983 | { 984 | { 985 | let mut node = $n.append($value); 986 | tree!(@ node $children); 987 | } 988 | tree!(@ $n { $($tail)* }); 989 | } 990 | }; 991 | 992 | // Append subtree from expression. 993 | (@ $n:ident { @ $subtree:expr $(, $($tail:tt)*)? }) => {{ 994 | $n.append_subtree($subtree); 995 | $( tree!(@ $n { $($tail)* }); )? 996 | }}; 997 | 998 | 999 | ($root:expr) => { $crate::Tree::new($root) }; 1000 | 1001 | ($root:expr => $children:tt) => { 1002 | { 1003 | let mut tree = $crate::Tree::new($root); 1004 | { 1005 | let mut node = tree.root_mut(); 1006 | tree!(@ node $children); 1007 | } 1008 | tree 1009 | } 1010 | }; 1011 | } 1012 | 1013 | impl Debug for Tree { 1014 | fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> { 1015 | use crate::iter::Edge; 1016 | if f.alternate() { 1017 | write!(f, "Tree {{")?; 1018 | for edge in self.root().traverse() { 1019 | match edge { 1020 | Edge::Open(node) if node.has_children() => { 1021 | write!(f, " {:?} => {{", node.value())?; 1022 | } 1023 | Edge::Open(node) if node.next_sibling().is_some() => { 1024 | write!(f, " {:?},", node.value())?; 1025 | } 1026 | Edge::Open(node) => { 1027 | write!(f, " {:?}", node.value())?; 1028 | } 1029 | Edge::Close(node) if node.has_children() => { 1030 | if node.next_sibling().is_some() { 1031 | write!(f, " }},")?; 1032 | } else { 1033 | write!(f, " }}")?; 1034 | } 1035 | } 1036 | _ => {} 1037 | } 1038 | } 1039 | write!(f, " }}") 1040 | } else { 1041 | f.debug_struct("Tree").field("vec", &self.vec).finish() 1042 | } 1043 | } 1044 | } 1045 | 1046 | // Handles display 1047 | mod display; 1048 | 1049 | impl Display for Tree { 1050 | fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> { 1051 | use crate::display::Indentation; 1052 | use crate::iter::Edge; 1053 | 1054 | let mut indent: Indentation = Indentation::new(true); 1055 | 1056 | for edge in self.root().traverse() { 1057 | match edge { 1058 | Edge::Open(node) if node.has_children() => { 1059 | indent.indent(node.next_sibling().is_some()); 1060 | writeln!(f, "{indent}{}", node.value())?; 1061 | } 1062 | Edge::Open(node) => { 1063 | indent.indent(node.next_sibling().is_some()); 1064 | writeln!(f, "{indent}{}", node.value())?; 1065 | indent.deindent(); 1066 | } 1067 | Edge::Close(node) if node.has_children() => { 1068 | indent.deindent(); 1069 | } 1070 | _ => {} 1071 | } 1072 | } 1073 | Ok(()) 1074 | } 1075 | } 1076 | 1077 | mod sort; 1078 | -------------------------------------------------------------------------------- /src/serde.rs: -------------------------------------------------------------------------------- 1 | //! Implement `serde::Serialize` and `serde::Deserialize` traits for Tree 2 | //! 3 | //! # Warning 4 | //! Serialize and Deserialize implementations are recursive. They require an amount of stack memory 5 | //! proportional to the depth of the tree. 6 | 7 | use std::{fmt, marker::PhantomData}; 8 | 9 | use serde::{ 10 | de::{self, MapAccess, Visitor}, 11 | ser::{Serialize, SerializeStruct}, 12 | Deserialize, Deserializer, 13 | }; 14 | 15 | use crate::{NodeMut, NodeRef, Tree}; 16 | 17 | #[derive(Debug)] 18 | struct SerNode<'a, T> { 19 | value: &'a T, 20 | children: Vec>, 21 | } 22 | 23 | impl<'a, T> From> for SerNode<'a, T> { 24 | fn from(node: NodeRef<'a, T>) -> Self { 25 | let value = node.value(); 26 | let children = node.children().map(SerNode::from).collect(); 27 | Self { value, children } 28 | } 29 | } 30 | 31 | impl Serialize for SerNode<'_, T> { 32 | fn serialize(&self, serializer: S) -> Result 33 | where 34 | S: serde::Serializer, 35 | { 36 | let mut state = serializer.serialize_struct("Node", 2)?; 37 | state.serialize_field("value", &self.value)?; 38 | state.serialize_field("children", &self.children)?; 39 | state.end() 40 | } 41 | } 42 | 43 | impl Serialize for Tree { 44 | fn serialize(&self, serializer: S) -> Result 45 | where 46 | S: serde::Serializer, 47 | { 48 | SerNode::from(self.root()).serialize(serializer) 49 | } 50 | } 51 | 52 | #[derive(Debug)] 53 | struct DeserNode { 54 | value: T, 55 | children: Vec>, 56 | } 57 | 58 | impl DeserNode { 59 | fn into_tree_node(self, parent: &mut NodeMut) { 60 | let mut node = parent.append(self.value); 61 | 62 | for child in self.children { 63 | child.into_tree_node(&mut node); 64 | } 65 | } 66 | } 67 | 68 | impl From> for Tree { 69 | fn from(root: DeserNode) -> Self { 70 | let mut tree: Tree = Tree::new(root.value); 71 | let mut tree_root = tree.root_mut(); 72 | 73 | for child in root.children { 74 | child.into_tree_node(&mut tree_root); 75 | } 76 | 77 | tree 78 | } 79 | } 80 | 81 | struct DeserNodeVisitor { 82 | marker: PhantomData DeserNode>, 83 | } 84 | 85 | impl DeserNodeVisitor { 86 | fn new() -> Self { 87 | DeserNodeVisitor { 88 | marker: PhantomData, 89 | } 90 | } 91 | } 92 | 93 | impl<'de, T> Visitor<'de> for DeserNodeVisitor 94 | where 95 | T: Deserialize<'de>, 96 | { 97 | type Value = DeserNode; 98 | 99 | fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { 100 | formatter.write_str("struct Node") 101 | } 102 | 103 | fn visit_map(self, mut map: M) -> Result 104 | where 105 | M: MapAccess<'de>, 106 | { 107 | let mut value = None; 108 | let mut children = None; 109 | 110 | while let Some(key) = map.next_key()? { 111 | match key { 112 | "value" => { 113 | if value.is_some() { 114 | return Err(de::Error::duplicate_field("value")); 115 | } 116 | value = Some(map.next_value()?); 117 | } 118 | "children" => { 119 | if children.is_some() { 120 | return Err(de::Error::duplicate_field("children")); 121 | } 122 | children = Some(map.next_value()?); 123 | } 124 | _ => { 125 | return Err(de::Error::unknown_field(key, &["value", "children"])); 126 | } 127 | } 128 | } 129 | 130 | let value = value.ok_or_else(|| de::Error::missing_field("value"))?; 131 | let children = children.ok_or_else(|| de::Error::missing_field("children"))?; 132 | 133 | Ok(DeserNode { value, children }) 134 | } 135 | } 136 | 137 | impl<'de, T> Deserialize<'de> for DeserNode 138 | where 139 | T: Deserialize<'de>, 140 | { 141 | fn deserialize(deserializer: D) -> Result 142 | where 143 | D: Deserializer<'de>, 144 | { 145 | deserializer.deserialize_struct("Node", &["value", "children"], DeserNodeVisitor::new()) 146 | } 147 | } 148 | 149 | impl<'de, T: Deserialize<'de>> Deserialize<'de> for Tree { 150 | fn deserialize(deserializer: D) -> Result 151 | where 152 | D: serde::Deserializer<'de>, 153 | { 154 | let deser = DeserNode::::deserialize(deserializer)?; 155 | Ok(deser.into()) 156 | } 157 | } 158 | -------------------------------------------------------------------------------- /src/sort.rs: -------------------------------------------------------------------------------- 1 | //! Sorting functionality for tree nodes. 2 | //! 3 | //! This module provides methods for sorting children of a node in a tree. 4 | //! The sorting can be done based on the node values or their indices. 5 | 6 | use std::cmp::Ordering; 7 | 8 | use crate::{NodeMut, NodeRef}; 9 | 10 | impl<'a, T: 'a> NodeMut<'a, T> { 11 | /// Sort children by value in ascending order. 12 | /// 13 | /// # Examples 14 | /// 15 | /// ```rust 16 | /// use ego_tree::tree; 17 | /// 18 | /// let mut tree = tree!('a' => { 'd', 'c', 'b' }); 19 | /// tree.root_mut().sort(); 20 | /// assert_eq!( 21 | /// vec![&'b', &'c', &'d'], 22 | /// tree.root() 23 | /// .children() 24 | /// .map(|n| n.value()) 25 | /// .collect::>(), 26 | /// ); 27 | /// ``` 28 | pub fn sort(&mut self) 29 | where 30 | T: Ord, 31 | { 32 | self.sort_by(|a, b| a.value().cmp(b.value())); 33 | } 34 | 35 | /// Sort children by `NodeRef` in ascending order using a comparison function. 36 | /// 37 | /// # Examples 38 | /// 39 | /// ```rust 40 | /// use ego_tree::tree; 41 | /// 42 | /// let mut tree = tree!('a' => { 'c', 'd', 'b' }); 43 | /// tree.root_mut().sort_by(|a, b| b.value().cmp(a.value())); 44 | /// assert_eq!( 45 | /// vec![&'d', &'c', &'b'], 46 | /// tree.root() 47 | /// .children() 48 | /// .map(|n| n.value()) 49 | /// .collect::>(), 50 | /// ); 51 | /// 52 | /// // Example for sort_by_id. 53 | /// tree.root_mut().sort_by(|a, b| a.id().cmp(&b.id())); 54 | /// assert_eq!( 55 | /// vec![&'c', &'d', &'b'], 56 | /// tree.root() 57 | /// .children() 58 | /// .map(|n| n.value()) 59 | /// .collect::>(), 60 | /// ); 61 | /// ``` 62 | pub fn sort_by(&mut self, mut compare: F) 63 | where 64 | F: FnMut(NodeRef, NodeRef) -> Ordering, 65 | { 66 | if !self.has_children() { 67 | return; 68 | } 69 | 70 | let mut children = { 71 | let this = unsafe { self.tree.get_unchecked(self.id) }; 72 | this.children().map(|child| child.id).collect::>() 73 | }; 74 | 75 | children.sort_by(|a, b| { 76 | let a = unsafe { self.tree.get_unchecked(*a) }; 77 | let b = unsafe { self.tree.get_unchecked(*b) }; 78 | compare(a, b) 79 | }); 80 | 81 | for id in children { 82 | self.append_id(id); 83 | } 84 | } 85 | 86 | /// Sort children by `NodeRef`'s key in ascending order using a key extraction function. 87 | /// 88 | /// # Examples 89 | /// 90 | /// ```rust 91 | /// use ego_tree::tree; 92 | /// 93 | /// let mut tree = tree!("1a" => { "2b", "4c", "3d" }); 94 | /// tree.root_mut().sort_by_key(|a| a.value().split_at(1).0.parse::().unwrap()); 95 | /// assert_eq!( 96 | /// vec!["2b", "3d", "4c"], 97 | /// tree.root() 98 | /// .children() 99 | /// .map(|n| *n.value()) 100 | /// .collect::>(), 101 | /// ); 102 | /// 103 | /// // Example for sort_by_id. 104 | /// tree.root_mut().sort_by_key(|n| n.id()); 105 | /// assert_eq!( 106 | /// vec![&"2b", &"4c", &"3d"], 107 | /// tree.root() 108 | /// .children() 109 | /// .map(|n| n.value()) 110 | /// .collect::>(), 111 | /// ); 112 | /// ``` 113 | pub fn sort_by_key(&mut self, mut f: F) 114 | where 115 | F: FnMut(NodeRef) -> K, 116 | K: Ord, 117 | { 118 | self.sort_by(|a, b| f(a).cmp(&f(b))); 119 | } 120 | } 121 | -------------------------------------------------------------------------------- /tests/iter.rs: -------------------------------------------------------------------------------- 1 | use ego_tree::tree; 2 | 3 | #[test] 4 | fn into_iter() { 5 | let tree = tree!('a' => { 'b', 'c', 'd' }); 6 | assert_eq!( 7 | vec!['a', 'b', 'c', 'd'], 8 | tree.into_iter().collect::>() 9 | ); 10 | } 11 | 12 | #[test] 13 | fn values() { 14 | let tree = tree!('a' => { 'b', 'c', 'd' }); 15 | assert_eq!( 16 | vec![&'a', &'b', &'c', &'d'], 17 | tree.values().collect::>() 18 | ); 19 | } 20 | 21 | #[test] 22 | fn values_mut() { 23 | let mut tree = tree!('a' => { 'b', 'c', 'd' }); 24 | 25 | for c in tree.values_mut() { 26 | *c = c.to_ascii_uppercase(); 27 | } 28 | 29 | assert_eq!( 30 | vec![&'A', &'B', &'C', &'D'], 31 | tree.values().collect::>() 32 | ); 33 | } 34 | 35 | #[test] 36 | fn nodes() { 37 | let mut tree = tree!('a' => { 'b' => { 'c' }, 'd' }); 38 | tree.orphan('e').append('f'); 39 | tree.root_mut().append('g'); 40 | assert_eq!( 41 | vec![&'a', &'b', &'c', &'d', &'e', &'f', &'g'], 42 | tree.nodes().map(|n| n.value()).collect::>() 43 | ); 44 | } 45 | 46 | #[test] 47 | fn ancestors() { 48 | let tree = tree!('a' => { 'b' => { 'c' => { 'd' } } }); 49 | let d = tree 50 | .root() 51 | .last_child() 52 | .unwrap() 53 | .last_child() 54 | .unwrap() 55 | .last_child() 56 | .unwrap(); 57 | assert_eq!( 58 | vec![&'c', &'b', &'a'], 59 | d.ancestors().map(|n| n.value()).collect::>() 60 | ); 61 | } 62 | 63 | #[test] 64 | fn ancestors_fused() { 65 | let tree = tree!('a' => { 'b' => { 'c' => { 'd' } } }); 66 | let d = tree 67 | .root() 68 | .last_child() 69 | .unwrap() 70 | .last_child() 71 | .unwrap() 72 | .last_child() 73 | .unwrap(); 74 | 75 | let mut ancestors = d.ancestors(); 76 | assert_eq!(ancestors.by_ref().count(), 3); 77 | assert_eq!(ancestors.next(), None); 78 | } 79 | 80 | #[test] 81 | fn prev_siblings() { 82 | let tree = tree!('a' => { 'b', 'c', 'd' }); 83 | assert_eq!( 84 | vec![&'c', &'b'], 85 | tree.root() 86 | .last_child() 87 | .unwrap() 88 | .prev_siblings() 89 | .map(|n| n.value()) 90 | .collect::>() 91 | ); 92 | } 93 | 94 | #[test] 95 | fn next_siblings() { 96 | let tree = tree!('a' => { 'b', 'c', 'd' }); 97 | assert_eq!( 98 | vec![&'c', &'d'], 99 | tree.root() 100 | .first_child() 101 | .unwrap() 102 | .next_siblings() 103 | .map(|n| n.value()) 104 | .collect::>() 105 | ); 106 | } 107 | 108 | #[test] 109 | fn children() { 110 | let tree = tree!('a' => { 'b', 'c', 'd' }); 111 | assert_eq!( 112 | vec![&'b', &'c', &'d'], 113 | tree.root() 114 | .children() 115 | .map(|n| n.value()) 116 | .collect::>() 117 | ); 118 | } 119 | 120 | #[test] 121 | fn children_fused() { 122 | let tree = tree!('a' => { 'b', 'c', 'd' }); 123 | 124 | let mut children = tree.root().children(); 125 | 126 | assert_eq!(children.by_ref().count(), 3); 127 | assert_eq!(children.next(), None); 128 | } 129 | 130 | #[test] 131 | fn children_rev() { 132 | let tree = tree!('a' => { 'b', 'c', 'd' }); 133 | assert_eq!( 134 | vec![&'d', &'c', &'b'], 135 | tree.root() 136 | .children() 137 | .rev() 138 | .map(|n| n.value()) 139 | .collect::>() 140 | ); 141 | } 142 | 143 | #[test] 144 | fn first_children() { 145 | let tree = tree!('a' => { 'b' => { 'd', 'e' }, 'c' }); 146 | assert_eq!( 147 | vec![&'b', &'d'], 148 | tree.root() 149 | .first_children() 150 | .map(|n| n.value()) 151 | .collect::>() 152 | ); 153 | } 154 | 155 | #[test] 156 | fn last_children() { 157 | let tree = tree!('a' => { 'b', 'c' => { 'd', 'e' } }); 158 | assert_eq!( 159 | vec![&'c', &'e'], 160 | tree.root() 161 | .last_children() 162 | .map(|n| n.value()) 163 | .collect::>() 164 | ); 165 | } 166 | 167 | #[test] 168 | fn traverse() { 169 | use ego_tree::iter::Edge; 170 | 171 | #[derive(Debug, PartialEq, Eq)] 172 | enum Value<'a> { 173 | Open(&'a char), 174 | Close(&'a char), 175 | } 176 | 177 | let tree = tree!('a' => { 'b' => { 'd', 'e' }, 'c' }); 178 | 179 | let traversal = tree 180 | .root() 181 | .traverse() 182 | .map(|edge| match edge { 183 | Edge::Open(node) => Value::Open(node.value()), 184 | Edge::Close(node) => Value::Close(node.value()), 185 | }) 186 | .collect::>(); 187 | 188 | assert_eq!( 189 | &[ 190 | Value::Open(&'a'), 191 | Value::Open(&'b'), 192 | Value::Open(&'d'), 193 | Value::Close(&'d'), 194 | Value::Open(&'e'), 195 | Value::Close(&'e'), 196 | Value::Close(&'b'), 197 | Value::Open(&'c'), 198 | Value::Close(&'c'), 199 | Value::Close(&'a'), 200 | ], 201 | &traversal[..] 202 | ); 203 | } 204 | 205 | #[test] 206 | fn traverse_fused() { 207 | let tree = tree!('a' => { 'b' => { 'd', 'e' }, 'c' }); 208 | 209 | let mut traversal = tree.root().traverse(); 210 | 211 | assert_eq!(traversal.by_ref().count(), 2 * 5); 212 | assert_eq!(traversal.next(), None); 213 | } 214 | 215 | #[test] 216 | fn descendants() { 217 | let tree = tree!('a' => { 'b' => { 'd', 'e' }, 'c' }); 218 | 219 | let descendants = tree 220 | .root() 221 | .descendants() 222 | .map(|n| n.value()) 223 | .collect::>(); 224 | 225 | assert_eq!(&[&'a', &'b', &'d', &'e', &'c',], &descendants[..]); 226 | } 227 | 228 | #[test] 229 | fn descendants_fused() { 230 | let tree = tree!('a' => { 'b' => { 'd', 'e' }, 'c' }); 231 | 232 | let mut descendants = tree.root().descendants(); 233 | 234 | assert_eq!(descendants.by_ref().count(), 5); 235 | assert_eq!(descendants.next(), None); 236 | } 237 | -------------------------------------------------------------------------------- /tests/macro.rs: -------------------------------------------------------------------------------- 1 | use ego_tree::{tree, Tree}; 2 | 3 | #[test] 4 | fn root() { 5 | let macro_tree = tree!('a'); 6 | let manual_tree = Tree::new('a'); 7 | assert_eq!(manual_tree, macro_tree); 8 | } 9 | 10 | #[test] 11 | fn single_child() { 12 | let macro_tree = tree!('a' => { 'b' }); 13 | 14 | let mut manual_tree = Tree::new('a'); 15 | manual_tree.root_mut().append('b'); 16 | 17 | assert_eq!(manual_tree, macro_tree); 18 | } 19 | 20 | #[test] 21 | fn single_child_comma() { 22 | let macro_tree = tree! { 23 | 'a' => { 24 | 'b', 25 | } 26 | }; 27 | 28 | let mut manual_tree = Tree::new('a'); 29 | manual_tree.root_mut().append('b'); 30 | 31 | assert_eq!(manual_tree, macro_tree); 32 | } 33 | 34 | #[test] 35 | fn leaves() { 36 | let macro_tree = tree!('a' => { 'b', 'c', 'd' }); 37 | 38 | let mut manual_tree = Tree::new('a'); 39 | manual_tree.root_mut().append('b'); 40 | manual_tree.root_mut().append('c'); 41 | manual_tree.root_mut().append('d'); 42 | 43 | assert_eq!(manual_tree, macro_tree); 44 | } 45 | 46 | #[test] 47 | fn leaves_comma() { 48 | let macro_tree = tree! { 49 | 'a' => { 50 | 'b', 51 | 'c', 52 | 'd', 53 | } 54 | }; 55 | 56 | let mut manual_tree = Tree::new('a'); 57 | manual_tree.root_mut().append('b'); 58 | manual_tree.root_mut().append('c'); 59 | manual_tree.root_mut().append('d'); 60 | 61 | assert_eq!(manual_tree, macro_tree); 62 | } 63 | 64 | #[test] 65 | fn nested_single_child() { 66 | let macro_tree = tree!('a' => { 'b' => { 'c' } }); 67 | 68 | let mut manual_tree = Tree::new('a'); 69 | manual_tree.root_mut().append('b').append('c'); 70 | 71 | assert_eq!(manual_tree, macro_tree); 72 | } 73 | 74 | #[test] 75 | fn nested_single_child_comma() { 76 | let macro_tree = tree! { 77 | 'a' => { 78 | 'b' => { 79 | 'c', 80 | }, 81 | } 82 | }; 83 | 84 | let mut manual_tree = Tree::new('a'); 85 | manual_tree.root_mut().append('b').append('c'); 86 | 87 | assert_eq!(manual_tree, macro_tree); 88 | } 89 | 90 | #[test] 91 | fn nested_leaves() { 92 | let macro_tree = tree!('a' => { 'b' => { 'c', 'd', 'e' } }); 93 | 94 | let mut manual_tree = Tree::new('a'); 95 | { 96 | let mut root = manual_tree.root_mut(); 97 | let mut node = root.append('b'); 98 | node.append('c'); 99 | node.append('d'); 100 | node.append('e'); 101 | } 102 | 103 | assert_eq!(manual_tree, macro_tree); 104 | } 105 | 106 | #[test] 107 | fn nested_leaves_comma() { 108 | let macro_tree = tree! { 109 | 'a' => { 110 | 'b' => { 111 | 'c', 112 | 'd', 113 | 'e', 114 | }, 115 | } 116 | }; 117 | 118 | let mut manual_tree = Tree::new('a'); 119 | { 120 | let mut root = manual_tree.root_mut(); 121 | let mut node = root.append('b'); 122 | node.append('c'); 123 | node.append('d'); 124 | node.append('e'); 125 | } 126 | 127 | assert_eq!(manual_tree, macro_tree); 128 | } 129 | 130 | #[test] 131 | fn nested_nested() { 132 | let macro_tree = tree!('a' => { 'b' => { 'c' => { 'd' } } }); 133 | 134 | let mut manual_tree = Tree::new('a'); 135 | manual_tree.root_mut().append('b').append('c').append('d'); 136 | 137 | assert_eq!(manual_tree, macro_tree); 138 | } 139 | 140 | #[test] 141 | fn mixed() { 142 | let macro_tree = tree! { 143 | 'a' => { 144 | 'b', 145 | 'd' => { 'e', 'f' }, 146 | 'g' => { 'h' => { 'i' } }, 147 | 'j', 148 | } 149 | }; 150 | 151 | let mut manual_tree = Tree::new('a'); 152 | { 153 | let mut node = manual_tree.root_mut(); 154 | node.append('b'); 155 | { 156 | let mut d = node.append('d'); 157 | d.append('e'); 158 | d.append('f'); 159 | } 160 | node.append('g').append('h').append('i'); 161 | node.append('j'); 162 | } 163 | 164 | assert_eq!(manual_tree, macro_tree); 165 | } 166 | 167 | #[test] 168 | fn subtree() { 169 | let subtree = tree! { 170 | 'x' => { 'y' => {'z'}} 171 | }; 172 | let tree = tree! { 173 | 'a' => { 174 | 'b', 175 | 'c' => {'d', 'e'}, 176 | @ subtree.clone(), 177 | 'f' => { @subtree }, 178 | } 179 | }; 180 | let expected_tree = tree! { 181 | 'a' => { 182 | 'b', 183 | 'c' => {'d', 'e'}, 184 | 'x' => { 'y' => {'z'}}, 185 | 'f' => {'x' => { 'y' => {'z'}} }, 186 | } 187 | }; 188 | assert_eq!(tree, expected_tree); 189 | } 190 | -------------------------------------------------------------------------------- /tests/node_mut.rs: -------------------------------------------------------------------------------- 1 | use ego_tree::{tree, NodeRef}; 2 | 3 | #[test] 4 | fn value() { 5 | let mut tree = tree!('a'); 6 | assert_eq!(&'a', tree.root_mut().value()); 7 | } 8 | 9 | #[test] 10 | fn parent() { 11 | let mut tree = tree!('a' => { 'b' }); 12 | assert_eq!( 13 | &'a', 14 | tree.root_mut() 15 | .first_child() 16 | .unwrap() 17 | .parent() 18 | .unwrap() 19 | .value() 20 | ); 21 | } 22 | 23 | #[test] 24 | fn prev_sibling() { 25 | let mut tree = tree!('a' => { 'b', 'c' }); 26 | assert_eq!( 27 | &'b', 28 | tree.root_mut() 29 | .last_child() 30 | .unwrap() 31 | .prev_sibling() 32 | .unwrap() 33 | .value() 34 | ); 35 | } 36 | 37 | #[test] 38 | fn next_sibling() { 39 | let mut tree = tree!('a' => { 'b', 'c' }); 40 | assert_eq!( 41 | &'c', 42 | tree.root_mut() 43 | .first_child() 44 | .unwrap() 45 | .next_sibling() 46 | .unwrap() 47 | .value() 48 | ); 49 | } 50 | 51 | #[test] 52 | fn first_child() { 53 | let mut tree = tree!('a' => { 'b', 'c' }); 54 | assert_eq!(&'b', tree.root_mut().first_child().unwrap().value()); 55 | } 56 | 57 | #[test] 58 | fn last_child() { 59 | let mut tree = tree!('a' => { 'b', 'c' }); 60 | assert_eq!(&'c', tree.root_mut().last_child().unwrap().value()); 61 | } 62 | 63 | #[test] 64 | fn has_siblings() { 65 | let mut tree = tree!('a' => { 'b', 'c' }); 66 | assert!(tree.root_mut().first_child().unwrap().has_siblings()); 67 | assert!(!tree.root_mut().has_siblings()); 68 | } 69 | 70 | #[test] 71 | fn has_children() { 72 | let mut tree = tree!('a' => { 'b', 'c' }); 73 | assert!(tree.root_mut().has_children()); 74 | assert!(!tree.root_mut().first_child().unwrap().has_children()); 75 | } 76 | 77 | #[test] 78 | fn for_each_next_sibling() { 79 | let mut tree = tree!(1 => { 2, 3, 4, 5, 6 }); 80 | let mut root = tree.root_mut(); 81 | let mut c = root.first_child().unwrap(); 82 | 83 | c.for_each_next_sibling(|n| { 84 | *n.value() += 1; 85 | }); 86 | 87 | let res = tree!(1 => { 2, 4, 5, 6, 7 }); 88 | 89 | assert_eq!(tree, res); 90 | } 91 | 92 | #[test] 93 | fn for_each_prev_sibling() { 94 | let mut tree = tree!(1 => { 2, 3, 4, 5, 6 }); 95 | let mut root = tree.root_mut(); 96 | let mut c = root.last_child().unwrap(); 97 | 98 | c.for_each_prev_sibling(|n| { 99 | *n.value() += 1; 100 | }); 101 | 102 | let res = tree!(1 => { 3, 4, 5, 6, 6 }); 103 | 104 | assert_eq!(tree, res); 105 | } 106 | 107 | #[test] 108 | fn for_each_sibling() { 109 | let rt = 2; 110 | let mut tree = tree!(rt => { 2, 3, 4, 5, 6 }); 111 | let mut root = tree.root_mut(); 112 | let mut c = root.last_child().unwrap(); 113 | 114 | c.for_each_sibling(|n| { 115 | let v = n.parent().map(|mut p| *p.value()).unwrap(); 116 | *n.value() += v; 117 | }); 118 | 119 | let res = tree!(rt => { 4, 5, 6, 7, 8 }); 120 | 121 | assert_eq!(tree, res); 122 | } 123 | 124 | #[test] 125 | fn for_each_child() { 126 | let mut tree = tree!(1 => { 2, 3, 4, 5, 6 }); 127 | let mut root = tree.root_mut(); 128 | root.for_each_child(|n| *n.value() += 1); 129 | 130 | assert_eq!(*root.value(), 1); 131 | 132 | let res = tree!(1 => { 3, 4, 5, 6, 7 }); 133 | 134 | assert_eq!(tree, res); 135 | } 136 | 137 | #[test] 138 | fn for_each_descendant() { 139 | let mut tree = tree!(1 => { 2 => {3, 4, 5, 6}, 3, 4 => {0, 1}, 5, 6 => {1, 2} }); 140 | let mut root = tree.root_mut(); 141 | root.for_each_descendant(|n| *n.value() += 1); 142 | 143 | let tree2 = tree!(2 => { 3 => {4, 5, 6, 7}, 4, 5 => {1, 2}, 6, 7 => {2, 3} }); 144 | 145 | assert_eq!(tree, tree2); 146 | } 147 | 148 | #[test] 149 | fn append_1() { 150 | let mut tree = tree!('a'); 151 | tree.root_mut().append('b'); 152 | 153 | let root = tree.root(); 154 | let child = root.first_child().unwrap(); 155 | 156 | assert_eq!(&'b', child.value()); 157 | assert_eq!(Some(child), root.last_child()); 158 | assert_eq!(Some(root), child.parent()); 159 | assert_eq!(None, child.next_sibling()); 160 | assert_eq!(None, child.next_sibling()); 161 | } 162 | 163 | #[test] 164 | fn append_2() { 165 | let mut tree = tree!('a'); 166 | tree.root_mut().append('b'); 167 | tree.root_mut().append('c'); 168 | 169 | let root = tree.root(); 170 | let b = root.first_child().unwrap(); 171 | let c = root.last_child().unwrap(); 172 | 173 | assert_eq!(&'b', b.value()); 174 | assert_eq!(&'c', c.value()); 175 | assert_eq!(Some(root), b.parent()); 176 | assert_eq!(Some(root), c.parent()); 177 | assert_eq!(None, b.prev_sibling()); 178 | assert_eq!(Some(c), b.next_sibling()); 179 | assert_eq!(Some(b), c.prev_sibling()); 180 | assert_eq!(None, c.next_sibling()); 181 | } 182 | 183 | #[test] 184 | fn append_3() { 185 | let mut tree = tree!('a'); 186 | tree.root_mut().append('b'); 187 | tree.root_mut().append('c'); 188 | tree.root_mut().append('d'); 189 | 190 | let root = tree.root(); 191 | let b = root.first_child().unwrap(); 192 | let c = b.next_sibling().unwrap(); 193 | let d = root.last_child().unwrap(); 194 | 195 | assert_eq!(&'b', b.value()); 196 | assert_eq!(&'c', c.value()); 197 | assert_eq!(&'d', d.value()); 198 | assert_eq!(Some(root), b.parent()); 199 | assert_eq!(Some(root), c.parent()); 200 | assert_eq!(Some(root), d.parent()); 201 | assert_eq!(None, b.prev_sibling()); 202 | assert_eq!(Some(c), b.next_sibling()); 203 | assert_eq!(Some(b), c.prev_sibling()); 204 | assert_eq!(Some(d), c.next_sibling()); 205 | assert_eq!(Some(c), d.prev_sibling()); 206 | assert_eq!(None, d.next_sibling()); 207 | } 208 | 209 | #[test] 210 | fn prepend_1() { 211 | let mut tree = tree!('a'); 212 | tree.root_mut().prepend('b'); 213 | 214 | let root = tree.root(); 215 | let child = root.first_child().unwrap(); 216 | 217 | assert_eq!(&'b', child.value()); 218 | assert_eq!(Some(child), root.last_child()); 219 | assert_eq!(Some(root), child.parent()); 220 | assert_eq!(None, child.next_sibling()); 221 | assert_eq!(None, child.next_sibling()); 222 | } 223 | 224 | #[test] 225 | fn prepend_2() { 226 | let mut tree = tree!('a'); 227 | tree.root_mut().prepend('c'); 228 | tree.root_mut().prepend('b'); 229 | 230 | let root = tree.root(); 231 | let b = root.first_child().unwrap(); 232 | let c = root.last_child().unwrap(); 233 | 234 | assert_eq!(&'b', b.value()); 235 | assert_eq!(&'c', c.value()); 236 | assert_eq!(Some(root), b.parent()); 237 | assert_eq!(Some(root), c.parent()); 238 | assert_eq!(None, b.prev_sibling()); 239 | assert_eq!(Some(c), b.next_sibling()); 240 | assert_eq!(Some(b), c.prev_sibling()); 241 | assert_eq!(None, c.next_sibling()); 242 | } 243 | 244 | #[test] 245 | fn prepend_3() { 246 | let mut tree = tree!('a'); 247 | tree.root_mut().prepend('d'); 248 | tree.root_mut().prepend('c'); 249 | tree.root_mut().prepend('b'); 250 | 251 | let root = tree.root(); 252 | let b = root.first_child().unwrap(); 253 | let c = b.next_sibling().unwrap(); 254 | let d = root.last_child().unwrap(); 255 | 256 | assert_eq!(&'b', b.value()); 257 | assert_eq!(&'c', c.value()); 258 | assert_eq!(&'d', d.value()); 259 | assert_eq!(Some(root), b.parent()); 260 | assert_eq!(Some(root), c.parent()); 261 | assert_eq!(Some(root), d.parent()); 262 | assert_eq!(None, b.prev_sibling()); 263 | assert_eq!(Some(c), b.next_sibling()); 264 | assert_eq!(Some(b), c.prev_sibling()); 265 | assert_eq!(Some(d), c.next_sibling()); 266 | assert_eq!(Some(c), d.prev_sibling()); 267 | assert_eq!(None, d.next_sibling()); 268 | } 269 | 270 | #[test] 271 | fn insert_before_first() { 272 | let mut tree = tree!('a' => { 'c' }); 273 | tree.root_mut().first_child().unwrap().insert_before('b'); 274 | 275 | let root = tree.root(); 276 | let b = root.first_child().unwrap(); 277 | let c = root.last_child().unwrap(); 278 | 279 | assert_eq!(&'b', b.value()); 280 | assert_eq!(Some(root), b.parent()); 281 | assert_eq!(None, b.prev_sibling()); 282 | assert_eq!(Some(c), b.next_sibling()); 283 | assert_eq!(Some(b), c.prev_sibling()); 284 | assert_eq!(None, c.next_sibling()); 285 | } 286 | 287 | #[test] 288 | fn insert_before() { 289 | let mut tree = tree!('a' => { 'b', 'd' }); 290 | tree.root_mut().last_child().unwrap().insert_before('c'); 291 | 292 | let root = tree.root(); 293 | let b = root.first_child().unwrap(); 294 | let c = b.next_sibling().unwrap(); 295 | let d = root.last_child().unwrap(); 296 | 297 | assert_eq!(&'c', c.value()); 298 | assert_eq!(Some(root), b.parent()); 299 | assert_eq!(Some(root), c.parent()); 300 | assert_eq!(Some(root), d.parent()); 301 | assert_eq!(None, b.prev_sibling()); 302 | assert_eq!(Some(c), b.next_sibling()); 303 | assert_eq!(Some(b), c.prev_sibling()); 304 | assert_eq!(Some(d), c.next_sibling()); 305 | assert_eq!(Some(c), d.prev_sibling()); 306 | assert_eq!(None, d.next_sibling()); 307 | } 308 | 309 | #[test] 310 | fn insert_after_first() { 311 | let mut tree = tree!('a' => { 'b' }); 312 | tree.root_mut().first_child().unwrap().insert_after('c'); 313 | 314 | let root = tree.root(); 315 | let b = root.first_child().unwrap(); 316 | let c = root.last_child().unwrap(); 317 | 318 | assert_eq!(&'c', c.value()); 319 | assert_eq!(Some(root), c.parent()); 320 | assert_eq!(None, b.prev_sibling()); 321 | assert_eq!(Some(c), b.next_sibling()); 322 | assert_eq!(Some(b), c.prev_sibling()); 323 | assert_eq!(None, c.next_sibling()); 324 | } 325 | 326 | #[test] 327 | fn insert_after() { 328 | let mut tree = tree!('a' => { 'b', 'd' }); 329 | tree.root_mut().first_child().unwrap().insert_after('c'); 330 | 331 | let root = tree.root(); 332 | let b = root.first_child().unwrap(); 333 | let c = b.next_sibling().unwrap(); 334 | let d = root.last_child().unwrap(); 335 | 336 | assert_eq!(&'c', c.value()); 337 | assert_eq!(Some(root), b.parent()); 338 | assert_eq!(Some(root), c.parent()); 339 | assert_eq!(Some(root), d.parent()); 340 | assert_eq!(None, b.prev_sibling()); 341 | assert_eq!(Some(c), b.next_sibling()); 342 | assert_eq!(Some(b), c.prev_sibling()); 343 | assert_eq!(Some(d), c.next_sibling()); 344 | assert_eq!(Some(c), d.prev_sibling()); 345 | assert_eq!(None, d.next_sibling()); 346 | } 347 | 348 | #[test] 349 | fn insert_at_index() { 350 | let mut tree = tree!('a' => { 'b', 'c', 'e' }); 351 | 352 | { 353 | let mut root = tree.root_mut(); 354 | let mut child = root.first_child().unwrap(); 355 | 356 | for _ in 0..2 { 357 | child = child.into_next_sibling().unwrap(); 358 | } 359 | 360 | child.insert_before('d'); 361 | } 362 | 363 | let descendants = tree 364 | .root() 365 | .descendants() 366 | .map(|n| n.value()) 367 | .collect::>(); 368 | 369 | assert_eq!(&[&'a', &'b', &'c', &'d', &'e',], &descendants[..]); 370 | } 371 | 372 | #[test] 373 | fn detach() { 374 | let mut tree = tree!('a' => { 'b', 'd' }); 375 | let mut root = tree.root_mut(); 376 | let mut b = root.first_child().unwrap(); 377 | let mut c = b.insert_after('c'); 378 | c.detach(); 379 | 380 | assert!(c.parent().is_none()); 381 | assert!(c.prev_sibling().is_none()); 382 | assert!(c.next_sibling().is_none()); 383 | } 384 | 385 | #[test] 386 | #[should_panic(expected = "Cannot append node as a child to itself")] 387 | fn append_id_itself() { 388 | let mut tree = tree! { 389 | 'a' => { 390 | 'b' => { 'c', 'd' }, 391 | 'e' => { 'f', 'g' }, 392 | } 393 | }; 394 | let mut a = tree.root_mut(); 395 | let mut e = a.last_child().unwrap(); 396 | e.append_id(e.id()); 397 | } 398 | 399 | #[test] 400 | fn append_id_noop() { 401 | let mut tree = tree! { 402 | 'a' => { 403 | 'b' => { 'c', 'd' }, 404 | 'e' => { 'f', 'g' }, 405 | } 406 | }; 407 | let mut a = tree.root_mut(); 408 | let e_id = a.last_child().unwrap().id(); 409 | a.append_id(e_id); 410 | assert_eq!(a.first_child().unwrap().next_sibling().unwrap().id(), e_id); 411 | } 412 | 413 | #[test] 414 | #[should_panic(expected = "Cannot prepend node as a child to itself")] 415 | fn prepend_id_itself() { 416 | let mut tree = tree! { 417 | 'a' => { 418 | 'b' => { 'c', 'd' }, 419 | 'e' => { 'f', 'g' }, 420 | } 421 | }; 422 | let mut a = tree.root_mut(); 423 | let mut e = a.last_child().unwrap(); 424 | e.prepend_id(e.id()); 425 | } 426 | 427 | #[test] 428 | fn prepend_id_noop() { 429 | let mut tree = tree! { 430 | 'a' => { 431 | 'b' => { 'c', 'd' }, 432 | 'e' => { 'f', 'g' }, 433 | } 434 | }; 435 | let mut a = tree.root_mut(); 436 | let b_id = a.first_child().unwrap().id(); 437 | a.prepend_id(b_id); 438 | assert_eq!(a.last_child().unwrap().prev_sibling().unwrap().id(), b_id); 439 | } 440 | 441 | #[test] 442 | fn reparent_from_id_append() { 443 | let mut tree = tree! { 444 | 'a' => { 445 | 'b' => { 'c', 'd' }, 446 | 'e' => { 'f', 'g' }, 447 | } 448 | }; 449 | let e_id = tree.root().last_child().unwrap().id(); 450 | tree.root_mut() 451 | .first_child() 452 | .unwrap() 453 | .reparent_from_id_append(e_id); 454 | 455 | let b = tree.root().first_child().unwrap(); 456 | let e = tree.root().last_child().unwrap(); 457 | let d = b.first_child().unwrap().next_sibling().unwrap(); 458 | let g = b.last_child().unwrap(); 459 | let f = g.prev_sibling().unwrap(); 460 | 461 | assert!(!e.has_children()); 462 | assert_eq!(&'f', f.value()); 463 | assert_eq!(&'g', g.value()); 464 | assert_eq!(Some(f), d.next_sibling()); 465 | assert_eq!(Some(d), f.prev_sibling()); 466 | } 467 | 468 | #[test] 469 | fn reparent_from_id_prepend() { 470 | let mut tree = tree! { 471 | 'a' => { 472 | 'b' => { 'f', 'g' }, 473 | 'e' => { 'c', 'd' }, 474 | } 475 | }; 476 | let e_id = tree.root().last_child().unwrap().id(); 477 | tree.root_mut() 478 | .first_child() 479 | .unwrap() 480 | .reparent_from_id_prepend(e_id); 481 | 482 | let b = tree.root().first_child().unwrap(); 483 | let e = tree.root().last_child().unwrap(); 484 | let c = b.first_child().unwrap(); 485 | let d = c.next_sibling().unwrap(); 486 | let f = b.last_child().unwrap().prev_sibling().unwrap(); 487 | 488 | assert!(!e.has_children()); 489 | assert_eq!(&'c', c.value()); 490 | assert_eq!(&'d', d.value()); 491 | assert_eq!(Some(f), d.next_sibling()); 492 | assert_eq!(Some(d), f.prev_sibling()); 493 | } 494 | 495 | #[test] 496 | fn into() { 497 | let mut tree = tree!('a'); 498 | let node_ref: NodeRef<_> = tree.root_mut().into(); 499 | assert_eq!(&'a', node_ref.value()); 500 | } 501 | -------------------------------------------------------------------------------- /tests/node_ref.rs: -------------------------------------------------------------------------------- 1 | use ego_tree::tree; 2 | 3 | #[test] 4 | fn value() { 5 | let tree = tree!('a'); 6 | assert_eq!(&'a', tree.root().value()); 7 | } 8 | 9 | #[test] 10 | fn parent() { 11 | let tree = tree!('a' => { 'b' }); 12 | let b = tree.root().first_child().unwrap(); 13 | assert_eq!(tree.root(), b.parent().unwrap()); 14 | } 15 | 16 | #[test] 17 | fn prev_sibling() { 18 | let tree = tree!('a' => { 'b', 'c' }); 19 | let c = tree.root().last_child().unwrap(); 20 | assert_eq!(tree.root().first_child(), c.prev_sibling()); 21 | } 22 | 23 | #[test] 24 | fn next_sibling() { 25 | let tree = tree!('a' => { 'b', 'c' }); 26 | let b = tree.root().first_child().unwrap(); 27 | assert_eq!(tree.root().last_child(), b.next_sibling()); 28 | } 29 | 30 | #[test] 31 | fn first_child() { 32 | let tree = tree!('a' => { 'b', 'c' }); 33 | assert_eq!(&'b', tree.root().first_child().unwrap().value()); 34 | } 35 | 36 | #[test] 37 | fn last_child() { 38 | let tree = tree!('a' => { 'b', 'c' }); 39 | assert_eq!(&'c', tree.root().last_child().unwrap().value()); 40 | } 41 | 42 | #[test] 43 | fn has_siblings() { 44 | let tree = tree!('a' => { 'b', 'c' }); 45 | assert!(!tree.root().has_siblings()); 46 | assert!(tree.root().first_child().unwrap().has_siblings()); 47 | } 48 | 49 | #[test] 50 | fn has_children() { 51 | let tree = tree!('a' => { 'b', 'c' }); 52 | assert!(tree.root().has_children()); 53 | assert!(!tree.root().first_child().unwrap().has_children()); 54 | } 55 | 56 | #[test] 57 | fn clone() { 58 | let tree = tree!('a'); 59 | let one = tree.root(); 60 | let two = one; 61 | assert_eq!(one, two); 62 | } 63 | 64 | #[test] 65 | fn eq() { 66 | let tree = tree!('a'); 67 | assert_eq!(tree.root(), tree.root()); 68 | } 69 | 70 | #[test] 71 | #[should_panic] 72 | fn neq() { 73 | let tree = tree!('a' => { 'b', 'c' }); 74 | assert_eq!(tree.root(), tree.root().first_child().unwrap()); 75 | } 76 | 77 | #[test] 78 | #[should_panic] 79 | fn neq_tree() { 80 | let one = tree!('a'); 81 | let two = one.clone(); 82 | assert_eq!(one.root(), two.root()); 83 | } 84 | -------------------------------------------------------------------------------- /tests/serde.rs: -------------------------------------------------------------------------------- 1 | #![cfg(feature = "serde")] 2 | 3 | use ego_tree::tree; 4 | use serde_test::{assert_tokens, Token}; 5 | 6 | #[test] 7 | fn test_internal_serde_repr_trivial() { 8 | let tree = tree!("a"); 9 | 10 | assert_tokens( 11 | &tree, 12 | &[ 13 | Token::Struct { 14 | name: "Node", 15 | len: 2, 16 | }, 17 | Token::BorrowedStr("value"), 18 | Token::BorrowedStr("a"), 19 | Token::BorrowedStr("children"), 20 | Token::Seq { len: Some(0) }, 21 | Token::SeqEnd, 22 | Token::StructEnd, 23 | ], 24 | ); 25 | } 26 | 27 | #[test] 28 | fn test_internal_serde_repr() { 29 | let tree = tree!("a" => {"b", "c" => {"d", "e"}, "f"}); 30 | 31 | assert_tokens( 32 | &tree, 33 | &[ 34 | Token::Struct { 35 | name: "Node", 36 | len: 2, 37 | }, 38 | Token::BorrowedStr("value"), 39 | Token::BorrowedStr("a"), 40 | Token::BorrowedStr("children"), 41 | Token::Seq { len: Some(3) }, 42 | Token::Struct { 43 | name: "Node", 44 | len: 2, 45 | }, 46 | Token::BorrowedStr("value"), 47 | Token::BorrowedStr("b"), 48 | Token::BorrowedStr("children"), 49 | Token::Seq { len: Some(0) }, 50 | Token::SeqEnd, 51 | Token::StructEnd, 52 | Token::Struct { 53 | name: "Node", 54 | len: 2, 55 | }, 56 | Token::BorrowedStr("value"), 57 | Token::BorrowedStr("c"), 58 | Token::BorrowedStr("children"), 59 | Token::Seq { len: Some(2) }, 60 | Token::Struct { 61 | name: "Node", 62 | len: 2, 63 | }, 64 | Token::BorrowedStr("value"), 65 | Token::BorrowedStr("d"), 66 | Token::BorrowedStr("children"), 67 | Token::Seq { len: Some(0) }, 68 | Token::SeqEnd, 69 | Token::StructEnd, 70 | Token::Struct { 71 | name: "Node", 72 | len: 2, 73 | }, 74 | Token::BorrowedStr("value"), 75 | Token::BorrowedStr("e"), 76 | Token::BorrowedStr("children"), 77 | Token::Seq { len: Some(0) }, 78 | Token::SeqEnd, 79 | Token::StructEnd, 80 | Token::SeqEnd, 81 | Token::StructEnd, 82 | Token::Struct { 83 | name: "Node", 84 | len: 2, 85 | }, 86 | Token::BorrowedStr("value"), 87 | Token::BorrowedStr("f"), 88 | Token::BorrowedStr("children"), 89 | Token::Seq { len: Some(0) }, 90 | Token::SeqEnd, 91 | Token::StructEnd, 92 | Token::SeqEnd, 93 | Token::StructEnd, 94 | ], 95 | ); 96 | } 97 | -------------------------------------------------------------------------------- /tests/sort.rs: -------------------------------------------------------------------------------- 1 | use std::assert_eq; 2 | 3 | use ego_tree::tree; 4 | 5 | #[test] 6 | fn sort() { 7 | let mut tree = tree!('a' => { 'd' => { 'e', 'f' }, 'c', 'b' }); 8 | tree.root_mut().sort(); 9 | assert_eq!( 10 | vec![&'b', &'c', &'d'], 11 | tree.root() 12 | .children() 13 | .map(|n| n.value()) 14 | .collect::>(), 15 | ); 16 | assert_eq!( 17 | tree.to_string(), 18 | tree!('a' => { 'b', 'c', 'd' => { 'e', 'f' } }).to_string() 19 | ); 20 | } 21 | 22 | #[test] 23 | fn sort_by() { 24 | let mut tree = tree!('a' => { 'c', 'd', 'b' }); 25 | tree.root_mut().sort_by(|a, b| b.value().cmp(a.value())); 26 | assert_eq!( 27 | vec![&'d', &'c', &'b'], 28 | tree.root() 29 | .children() 30 | .map(|n| n.value()) 31 | .collect::>(), 32 | ); 33 | 34 | let mut tree = tree!('a' => { 'c','d', 'e', 'b' }); 35 | tree.root_mut().sort_by(|a, b| b.value().cmp(a.value())); 36 | assert_eq!( 37 | vec![&'e', &'d', &'c', &'b'], 38 | tree.root() 39 | .children() 40 | .map(|n| n.value()) 41 | .collect::>(), 42 | ); 43 | } 44 | 45 | #[test] 46 | fn sort_by_key() { 47 | let mut tree = tree!("1a" => { "2b", "4c", "3d" }); 48 | tree.root_mut() 49 | .sort_by_key(|a| a.value().split_at(1).0.parse::().unwrap()); 50 | assert_eq!( 51 | vec!["2b", "3d", "4c"], 52 | tree.root() 53 | .children() 54 | .map(|n| *n.value()) 55 | .collect::>(), 56 | ); 57 | } 58 | 59 | #[test] 60 | fn sort_id() { 61 | let mut tree = tree!('a' => { 'd', 'c', 'b' }); 62 | tree.root_mut().sort(); 63 | assert_ne!( 64 | vec![&'d', &'c', &'b'], 65 | tree.root() 66 | .children() 67 | .map(|n| n.value()) 68 | .collect::>(), 69 | ); 70 | tree.root_mut().sort_by_key(|n| n.id()); 71 | assert_eq!( 72 | vec![&'d', &'c', &'b'], 73 | tree.root() 74 | .children() 75 | .map(|n| n.value()) 76 | .collect::>(), 77 | ); 78 | } 79 | 80 | #[test] 81 | fn sort_by_id() { 82 | let mut tree = tree!('a' => { 'd', 'b', 'c' }); 83 | tree.root_mut().sort_by(|a, b| b.id().cmp(&a.id())); 84 | assert_eq!( 85 | vec![&'c', &'b', &'d'], 86 | tree.root() 87 | .children() 88 | .map(|n| n.value()) 89 | .collect::>(), 90 | ); 91 | } 92 | -------------------------------------------------------------------------------- /tests/subtree.rs: -------------------------------------------------------------------------------- 1 | use ego_tree::tree; 2 | 3 | #[test] 4 | fn prepend_subtree() { 5 | let mut tree = tree!('a' => { 'b', 'c' => { 'd', 'e' } }); 6 | let node_id = tree.root().first_child().unwrap().id(); 7 | let mut node = tree.get_mut(node_id).unwrap(); 8 | assert_eq!(node.value(), &'b'); 9 | 10 | let subtree = tree!('f' => { 'g', 'h' => { 'i', 'j' } }); 11 | let mut root_subtree = node.prepend_subtree(subtree); 12 | assert_eq!(root_subtree.parent().unwrap().value(), &'b'); 13 | assert_eq!( 14 | root_subtree.parent().unwrap().parent().unwrap().value(), 15 | &'a' 16 | ); 17 | 18 | let new_tree = 19 | tree!('a' => { 'b' => { 'f' => { 'g', 'h' => { 'i', 'j' } } }, 'c' => { 'd', 'e' } }); 20 | assert_eq!(format!("{:#?}", tree), format!("{:#?}", new_tree)); 21 | } 22 | 23 | #[test] 24 | fn append_subtree() { 25 | let mut tree = tree!('a' => { 'b', 'c' }); 26 | let mut node = tree.root_mut(); 27 | assert_eq!(node.value(), &'a'); 28 | 29 | let subtree = tree!('d' => { 'e', 'f' }); 30 | let mut root_subtree = node.append_subtree(subtree); 31 | assert_eq!(root_subtree.parent().unwrap().value(), &'a'); 32 | 33 | let new_tree = tree!('a' => { 'b', 'c', 'd' => { 'e', 'f' } }); 34 | assert_eq!(format!("{:#?}", tree), format!("{:#?}", new_tree)); 35 | } 36 | -------------------------------------------------------------------------------- /tests/tree.rs: -------------------------------------------------------------------------------- 1 | use ego_tree::{tree, Tree}; 2 | 3 | #[test] 4 | fn new() { 5 | let tree = Tree::new('a'); 6 | let root = tree.root(); 7 | assert_eq!(&'a', root.value()); 8 | assert_eq!(None, root.parent()); 9 | assert_eq!(None, root.prev_sibling()); 10 | assert_eq!(None, root.next_sibling()); 11 | assert_eq!(None, root.first_child()); 12 | assert_eq!(None, root.last_child()); 13 | } 14 | 15 | #[test] 16 | fn root() { 17 | let tree = Tree::new('a'); 18 | assert_eq!(&'a', tree.root().value()); 19 | } 20 | 21 | #[test] 22 | fn root_mut() { 23 | let mut tree = Tree::new('a'); 24 | assert_eq!(&'a', tree.root_mut().value()); 25 | } 26 | 27 | #[test] 28 | fn orphan() { 29 | let mut tree = Tree::new('a'); 30 | let mut orphan = tree.orphan('b'); 31 | assert_eq!(&'b', orphan.value()); 32 | assert!(orphan.parent().is_none()); 33 | } 34 | 35 | #[test] 36 | fn get() { 37 | let tree = Tree::new('a'); 38 | let id = tree.root().id(); 39 | assert_eq!(Some(tree.root()), tree.get(id)); 40 | } 41 | 42 | #[test] 43 | fn get_mut() { 44 | let mut tree = Tree::new('a'); 45 | let id = tree.root().id(); 46 | assert_eq!(Some('a'), tree.get_mut(id).map(|mut n| *n.value())); 47 | } 48 | 49 | #[test] 50 | fn clone() { 51 | let one = Tree::new('a'); 52 | let two = one.clone(); 53 | assert_eq!(one, two); 54 | } 55 | 56 | #[test] 57 | fn eq() { 58 | let one = Tree::new('a'); 59 | let two = Tree::new('a'); 60 | assert_eq!(one, two); 61 | } 62 | 63 | #[test] 64 | #[should_panic] 65 | fn neq() { 66 | let one = Tree::new('a'); 67 | let two = Tree::new('b'); 68 | assert_eq!(one, two); 69 | } 70 | 71 | #[test] 72 | fn insert_id_after() { 73 | let mut tree = tree! { 74 | "root" => { 75 | "a" => { 76 | "child 1", 77 | }, 78 | "b" => { 79 | "child 2", 80 | }, 81 | } 82 | }; 83 | 84 | let a = tree.root().first_child().unwrap().id(); 85 | let b = tree.root().last_child().unwrap().id(); 86 | 87 | assert_eq!(2, tree.root().children().count()); 88 | assert_eq!(1, tree.get(a).unwrap().children().count()); 89 | assert_eq!(1, tree.get(b).unwrap().children().count()); 90 | 91 | let child_1 = tree.get(a).unwrap().first_child().unwrap().id(); 92 | tree.get_mut(b).unwrap().insert_id_after(child_1); 93 | 94 | assert_eq!( 95 | 0, 96 | tree.get(a).unwrap().children().count(), 97 | "child 1 should be moved from a" 98 | ); 99 | assert_eq!( 100 | 1, 101 | tree.get(b).unwrap().children().count(), 102 | "b should be unchanged" 103 | ); 104 | assert_eq!( 105 | child_1, 106 | tree.root().last_child().unwrap().id(), 107 | "child 1 should be last child of root" 108 | ); 109 | assert_eq!(3, tree.root().children().count()); 110 | } 111 | 112 | #[test] 113 | fn insert_id_before() { 114 | let mut tree = tree! { 115 | "root" => { 116 | "a" => { 117 | "child 1", 118 | }, 119 | "b" => { 120 | "child 2", 121 | }, 122 | } 123 | }; 124 | 125 | let a = tree.root().first_child().unwrap().id(); 126 | let b = tree.root().last_child().unwrap().id(); 127 | 128 | assert_eq!(2, tree.root().children().count()); 129 | assert_eq!(1, tree.get(a).unwrap().children().count()); 130 | assert_eq!(1, tree.get(b).unwrap().children().count()); 131 | 132 | let child_1 = tree.get(a).unwrap().first_child().unwrap().id(); 133 | tree.get_mut(b).unwrap().insert_id_before(child_1); 134 | 135 | assert_eq!( 136 | 0, 137 | tree.get(a).unwrap().children().count(), 138 | "child 1 should be moved from a" 139 | ); 140 | assert_eq!( 141 | 1, 142 | tree.get(b).unwrap().children().count(), 143 | "b should be unchanged" 144 | ); 145 | assert_eq!( 146 | b, 147 | tree.root().last_child().unwrap().id(), 148 | "b should be last child of root" 149 | ); 150 | assert_eq!( 151 | child_1, 152 | tree.get(b).unwrap().prev_sibling().unwrap().id(), 153 | "child 1 should be between a and b" 154 | ); 155 | assert_eq!(3, tree.root().children().count()); 156 | } 157 | 158 | #[test] 159 | fn test_map_values() { 160 | let str_tree = tree! { 161 | "root" => { 162 | "a" => { 163 | "child 1", 164 | }, 165 | "b" => { 166 | "child 2", 167 | }, 168 | } 169 | }; 170 | 171 | let identity_mapped_tree = str_tree.clone().map(|value| value); 172 | 173 | // If we pass the identity function to `.map_values()`, 174 | // then we expect the tree to effectively remain untouched: 175 | assert_eq!(str_tree, identity_mapped_tree); 176 | 177 | let string_tree = str_tree.clone().map(|value| value.to_owned()); 178 | 179 | // A `&str` will produce the same output for `.to_string()` as its equivalent `String`, 180 | // so the output of `.to_string()` should match for corresponding trees as well: 181 | assert_eq!(str_tree.to_string(), string_tree.to_string()); 182 | } 183 | 184 | #[test] 185 | fn test_map_value_refs() { 186 | let str_tree = tree! { 187 | "root" => { 188 | "a" => { 189 | "child 1", 190 | }, 191 | "b" => { 192 | "child 2", 193 | }, 194 | } 195 | }; 196 | 197 | let identity_mapped_tree = str_tree.map_ref(|&value| value); 198 | 199 | // If we pass the identity function to `.map_values()`, 200 | // then we expect the tree to effectively remain untouched: 201 | assert_eq!(str_tree, identity_mapped_tree); 202 | 203 | let string_tree = str_tree.map_ref(|&value| value.to_owned()); 204 | 205 | // A `&str` will produce the same output for `.to_string()` as its equivalent `String`, 206 | // so the output of `.to_string()` should match for corresponding trees as well: 207 | assert_eq!(str_tree.to_string(), string_tree.to_string()); 208 | } 209 | 210 | #[test] 211 | fn test_display() { 212 | let tree = tree! { 213 | "root" => { 214 | "a" => { 215 | "child 1", 216 | }, 217 | "b" => { 218 | "child 2", 219 | }, 220 | } 221 | }; 222 | 223 | let repr = format!("{tree}"); 224 | let expected = "root\n├── a\n│ └── child 1\n└── b\n └── child 2\n"; 225 | 226 | assert_eq!(repr, expected); 227 | 228 | let tree = tree! { 229 | "root" => { 230 | "a", "b" => { 231 | "x", "y" 232 | }, "c" 233 | } 234 | }; 235 | 236 | let repr = format!("{tree}"); 237 | let expected = "root\n├── a\n├── b\n│ ├── x\n│ └── y\n└── c\n"; 238 | 239 | assert_eq!(repr, expected); 240 | } 241 | --------------------------------------------------------------------------------