├── .github └── workflows │ └── ci.yml ├── .gitignore ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── src └── lib.rs └── tests ├── iterators.rs ├── remove.rs └── walkers.rs /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: rose_tree 2 | on: [push, pull_request] 3 | jobs: 4 | rustfmt-check: 5 | runs-on: ubuntu-latest 6 | steps: 7 | - uses: actions/checkout@v2 8 | - name: Install stable 9 | uses: actions-rs/toolchain@v1 10 | with: 11 | profile: minimal 12 | toolchain: stable 13 | override: true 14 | components: rustfmt 15 | - name: Run rustfmt 16 | uses: actions-rs/cargo@v1 17 | with: 18 | command: fmt 19 | args: --all -- --check 20 | 21 | cargo-test: 22 | runs-on: ubuntu-latest 23 | steps: 24 | - uses: actions/checkout@v2 25 | - name: Install stable 26 | uses: actions-rs/toolchain@v1 27 | with: 28 | profile: minimal 29 | toolchain: stable 30 | override: true 31 | - name: Run default features 32 | uses: actions-rs/cargo@v1 33 | with: 34 | command: test 35 | 36 | cargo-doc: 37 | runs-on: ubuntu-latest 38 | steps: 39 | - uses: actions/checkout@v2 40 | - name: Install stable 41 | uses: actions-rs/toolchain@v1 42 | with: 43 | profile: minimal 44 | toolchain: stable 45 | override: true 46 | - name: Run default features 47 | uses: actions-rs/cargo@v1 48 | with: 49 | command: doc 50 | 51 | cargo-publish: 52 | if: github.event_name == 'push' && github.ref == 'refs/heads/master' 53 | env: 54 | CRATESIO_TOKEN: ${{ secrets.CRATESIO_TOKEN }} 55 | runs-on: ubuntu-latest 56 | steps: 57 | - uses: actions/checkout@v2 58 | - name: cargo publish 59 | continue-on-error: true 60 | run: cargo publish --token $CRATESIO_TOKEN 61 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | *~ 3 | *# 4 | *.o 5 | *.so 6 | *.swp 7 | *.dylib 8 | *.dSYM 9 | *.dll 10 | *.rlib 11 | *.dummy 12 | *.exe 13 | *-test 14 | /bin/main 15 | /bin/test-internal 16 | /bin/test-external 17 | /doc/ 18 | /target/ 19 | /build/ 20 | /.rust/ 21 | rusti.sh 22 | watch.sh 23 | /examples/** 24 | !/examples/*.rs 25 | !/examples/assets/ 26 | Cargo.lock 27 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "rose_tree" 3 | version = "0.3.0" 4 | authors = ["mitchmindtree "] 5 | description = "An indexable tree data structure with a variable and unbounded number of branches per node. It is Implemented on top of petgraph's Graph data structure and attempts to follow similar conventions where suitable." 6 | readme = "README.md" 7 | keywords = ["rose", "tree", "data-structure", "graph"] 8 | license = "MIT/Apache-2.0" 9 | repository = "https://github.com/mitchmindtree/rose_tree-rs.git" 10 | homepage = "https://github.com/mitchmindtree/rose_tree-rs" 11 | 12 | 13 | [dependencies] 14 | petgraph = "0.6" 15 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2015 2 | 3 | Permission is hereby granted, free of charge, to any 4 | person obtaining a copy of this software and associated 5 | documentation files (the "Software"), to deal in the 6 | Software without restriction, including without 7 | limitation the rights to use, copy, modify, merge, 8 | publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software 10 | is furnished to do so, subject to the following 11 | conditions: 12 | 13 | The above copyright notice and this permission notice 14 | shall be included in all copies or substantial portions 15 | of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 18 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 19 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 21 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 22 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 23 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 24 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 25 | DEALINGS IN THE SOFTWARE. 26 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # rose_tree [![Actions Status](https://github.com/mitchmindtree/rose_tree/workflows/rose_tree/badge.svg)](https://github.com/mitchmindtree/rose_tree/actions) [![Crates.io](https://img.shields.io/crates/v/rose_tree.svg)](https://crates.io/crates/rose_tree) [![Crates.io](https://img.shields.io/crates/l/rose_tree.svg)](https://github.com/mitchmindtree/rose_tree-rs/blob/master/LICENSE-MIT) [![docs.rs](https://docs.rs/rose_tree/badge.svg)](https://docs.rs/rose_tree/) 2 | 3 | An implementation of the [**rose tree** (aka **multi-way tree**) data structure](https://en.wikipedia.org/wiki/Rose_tree) for Rust. 4 | 5 | An indexable tree data structure with a variable and unbounded number of branches per node. 6 | 7 | It is Implemented on top of [petgraph](https://github.com/bluss/petulant-avenger-graphlibrary)'s [Graph](http://bluss.github.io/petulant-avenger-graphlibrary/doc/petgraph/graph/struct.Graph.html) data structure and attempts to follow similar conventions where suitable. 8 | 9 | 10 | Usage 11 | ----- 12 | 13 | Please see the [tests directory](https://github.com/mitchmindtree/rose_tree-rs/tree/master/tests) for some basic usage examples. 14 | 15 | License 16 | ------- 17 | 18 | Dual-licensed to be compatible with the petgraph and Rust projects. 19 | 20 | Licensed under the Apache License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0 or the MIT license http://opensource.org/licenses/MIT, at your option. This file may not be copied, modified, or distributed except according to those terms. 21 | 22 | 23 | [Beautiful ascii source](http://www.chris.com/ascii/joan/www.geocities.com/SoHo/7373/flowers.html). 24 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! 2 | //! **rose_tree** is a rose tree (aka multi-way tree) data structure library. 3 | //! 4 | //! The most prominent type is [**RoseTree**](./struct.RoseTree.html) - a wrapper around [petgraph] 5 | //! (http://bluss.github.io/petulant-avenger-graphlibrary/doc/petgraph/index.html)'s [**Graph**] 6 | //! (http://bluss.github.io/petulant-avenger-graphlibrary/doc/petgraph/graph/struct.Graph.html) 7 | //! data structure, exposing a refined API targeted towards rose tree related functionality. 8 | //! 9 | 10 | #![forbid(unsafe_code)] 11 | #![warn(missing_docs)] 12 | 13 | pub extern crate petgraph; 14 | use petgraph as pg; 15 | 16 | use petgraph::graph::IndexType; 17 | pub use petgraph::graph::NodeIndex; 18 | 19 | type DefIndex = u32; 20 | 21 | /// The PetGraph to be used internally within the RoseTree for storing/managing nodes and edges. 22 | pub type PetGraph = pg::Graph; 23 | 24 | /// An indexable tree data structure with a variable and unbounded number of branches per node. 25 | /// 26 | /// Also known as a multi-way tree. 27 | /// 28 | /// See the [wikipedia article on the "Rose tree" data 29 | /// structure](https://en.wikipedia.org/wiki/Rose_tree). 30 | /// 31 | /// Note: The following documentation is adapted from petgraph's [**Graph** documentation] 32 | /// (http://bluss.github.io/petulant-avenger-graphlibrary/doc/petgraph/graph/struct.Graph.html). 33 | /// 34 | /// **RoseTree** is parameterized over the node weight **N** and **Ix** which is the index type 35 | /// used. 36 | /// 37 | /// A wrapper around petgraph's **Graph** data structure with a refined API specifically targeted 38 | /// towards use as a **RoseTree**. 39 | /// 40 | /// **NodeIndex** is a type that acts as a reference to nodes, but these are only stable across 41 | /// certain operations. **Removing nodes may shift other indices.** Adding kids to the **RoseTree** 42 | /// keeps all indices stable, but removing a node will force the last node to shift its index to 43 | /// take its place. 44 | /// 45 | /// The fact that the node indices in the **RoseTree** are numbered in a compact interval from 0 to 46 | /// *n*-1 simplifies some graph algorithms. 47 | /// 48 | /// The **Ix** parameter is u32 by default. The goal is that you can ignore this parameter 49 | /// completely unless you need a very large **RoseTree** -- then you can use usize. 50 | /// 51 | /// The **RoseTree** also offers methods for accessing the underlying **Graph**, which can be useful 52 | /// for taking advantage of petgraph's various graph-related algorithms. 53 | #[derive(Clone, Debug)] 54 | pub struct RoseTree { 55 | /// A graph for storing all nodes and edges between them that represent the tree. 56 | graph: PetGraph, 57 | } 58 | 59 | /// An iterator that yeilds an index to the parent of the current child before the setting the 60 | /// parent as the new current child. This occurs recursively until the root index is yeilded. 61 | pub struct ParentRecursion<'a, N: 'a, Ix: IndexType> { 62 | rose_tree: &'a RoseTree, 63 | child: NodeIndex, 64 | } 65 | 66 | /// An iterator yielding indices to the children of some node. 67 | pub type Children<'a, Ix> = pg::graph::Neighbors<'a, (), Ix>; 68 | 69 | /// An iterator yielding indices to the siblings of some child node. 70 | pub struct Siblings<'a, Ix: IndexType> { 71 | child: NodeIndex, 72 | maybe_siblings: Option>, 73 | } 74 | 75 | /// A "walker" object that can be used to step through the children of some parent node. 76 | pub struct WalkChildren { 77 | walk_edges: pg::graph::WalkNeighbors, 78 | } 79 | 80 | /// A "walker" object that can be used to step through the siblings of some child node. 81 | pub struct WalkSiblings { 82 | child: NodeIndex, 83 | maybe_walk_children: Option>, 84 | } 85 | 86 | /// `RoseTree`'s API ensures that it always has a "root" node and that its index is always 0. 87 | pub const ROOT: usize = 0; 88 | 89 | impl RoseTree 90 | where 91 | Ix: IndexType, 92 | { 93 | /// Create a new `RoseTree` along with some root node. 94 | /// Returns both the `RoseTree` and an index into the root node in a tuple. 95 | pub fn new(root: N) -> (Self, NodeIndex) { 96 | Self::with_capacity(1, root) 97 | } 98 | 99 | /// Create a new `RoseTree` with estimated capacity and some root node. 100 | /// Returns both the `RoseTree` and an index into the root node in a tuple. 101 | pub fn with_capacity(nodes: usize, root: N) -> (Self, NodeIndex) { 102 | let mut graph = PetGraph::with_capacity(nodes, nodes); 103 | let root = graph.add_node(root); 104 | (RoseTree { graph }, root) 105 | } 106 | 107 | /// The total number of nodes in the RoseTree. 108 | pub fn node_count(&self) -> usize { 109 | self.graph.node_count() 110 | } 111 | 112 | /// Borrow the `RoseTree`'s underlying `PetGraph`. 113 | /// All existing `NodeIndex`s may be used to index into this graph the same way they may be 114 | /// used to index into the `RoseTree`. 115 | pub fn graph(&self) -> &PetGraph { 116 | &self.graph 117 | } 118 | 119 | /// Take ownership of the RoseTree and return the internal PetGraph. 120 | /// All existing `NodeIndex`s may be used to index into this graph the same way they may be 121 | /// used to index into the `RoseTree`. 122 | pub fn into_graph(self) -> PetGraph { 123 | let RoseTree { graph } = self; 124 | graph 125 | } 126 | 127 | /// Add a child node to the node at the given NodeIndex. 128 | /// Returns an index into the child's position within the tree. 129 | /// 130 | /// Computes in **O(1)** time. 131 | /// 132 | /// **Panics** if the given parent node doesn't exist. 133 | /// 134 | /// **Panics** if the Graph is at the maximum number of edges for its index. 135 | pub fn add_child(&mut self, parent: NodeIndex, kid: N) -> NodeIndex { 136 | let kid = self.graph.add_node(kid); 137 | self.graph.add_edge(parent, kid, ()); 138 | kid 139 | } 140 | 141 | /// Borrow the weight from the node at the given index. 142 | pub fn node_weight(&self, node: NodeIndex) -> Option<&N> { 143 | self.graph.node_weight(node) 144 | } 145 | 146 | /// Mutably borrow the weight from the node at the given index. 147 | pub fn node_weight_mut(&mut self, node: NodeIndex) -> Option<&mut N> { 148 | self.graph.node_weight_mut(node) 149 | } 150 | 151 | /// Index the `RoseTree` by two node indices. 152 | /// 153 | /// **Panics** if the indices are equal or if they are out of bounds. 154 | pub fn index_twice_mut(&mut self, a: NodeIndex, b: NodeIndex) -> (&mut N, &mut N) { 155 | self.graph.index_twice_mut(a, b) 156 | } 157 | 158 | /// Remove all nodes in the `RoseTree` except for the root. 159 | pub fn remove_all_but_root(&mut self) { 160 | // We can assume that the `root`'s index is zero, as it is always the first node to be 161 | // added to the RoseTree. 162 | if let Some(root) = self.graph.remove_node(NodeIndex::new(0)) { 163 | self.graph.clear(); 164 | self.graph.add_node(root); 165 | } 166 | } 167 | 168 | /// Removes and returns the node at the given index. 169 | /// 170 | /// The parent of `node` will become the new parent for all of its children. 171 | /// 172 | /// The root node cannot be removed. If its index is given, `None` will be returned. 173 | /// 174 | /// Note: this method may shift other node indices, invalidating previously returned indices! 175 | pub fn remove_node(&mut self, node: NodeIndex) -> Option { 176 | // Check if an attempt to remove the root node has been made. 177 | if node.index() == ROOT || self.graph.node_weight(node).is_none() { 178 | return None; 179 | } 180 | 181 | // Now that we know we're not the root node, we know that we **must** have some parent. 182 | let parent = self.parent(node).expect("No parent node found"); 183 | 184 | // For each of `node`'s children, set their parent to `node`'s parent. 185 | let mut children = self.graph.neighbors_directed(node, pg::Outgoing).detach(); 186 | while let Some((child_edge, child_node)) = children.next(&self.graph) { 187 | self.graph.remove_edge(child_edge); 188 | self.graph.add_edge(parent, child_node, ()); 189 | } 190 | 191 | // Finally, remove our node and return it. 192 | self.graph.remove_node(node) 193 | } 194 | 195 | /// Removes the node at the given index along with all their children, returning them as a new 196 | /// RoseTree. 197 | /// 198 | /// If there was no node at the given index, `None` will be returned. 199 | pub fn remove_node_with_children(&mut self, _node: NodeIndex) -> Option> { 200 | unimplemented!(); 201 | } 202 | 203 | /// An index to the parent of the node at the given index if there is one. 204 | pub fn parent(&self, child: NodeIndex) -> Option> { 205 | self.graph.neighbors_directed(child, pg::Incoming).next() 206 | } 207 | 208 | /// An iterator over the given child's parent, that parent's parent and so forth. 209 | /// 210 | /// The returned iterator yields `NodeIndex`s. 211 | pub fn parent_recursion(&self, child: NodeIndex) -> ParentRecursion { 212 | ParentRecursion { 213 | rose_tree: self, 214 | child, 215 | } 216 | } 217 | 218 | /// An iterator over all nodes that are children to the node at the given index. 219 | /// 220 | /// The returned iterator yields `NodeIndex`s. 221 | pub fn children(&self, parent: NodeIndex) -> Children { 222 | self.graph.neighbors_directed(parent, pg::Outgoing) 223 | } 224 | 225 | /// A "walker" object that may be used to step through the children of the given parent node. 226 | /// 227 | /// Unlike the `Children` type, `WalkChildren` does not borrow the `RoseTree`. 228 | pub fn walk_children(&self, parent: NodeIndex) -> WalkChildren { 229 | let walk_edges = self.graph.neighbors_directed(parent, pg::Outgoing).detach(); 230 | WalkChildren { walk_edges } 231 | } 232 | 233 | /// An iterator over all nodes that are siblings to the node at the given index. 234 | /// 235 | /// The returned iterator yields `NodeIndex`s. 236 | pub fn siblings(&self, child: NodeIndex) -> Siblings { 237 | let maybe_siblings = self.parent(child).map(|parent| self.children(parent)); 238 | Siblings { 239 | child, 240 | maybe_siblings, 241 | } 242 | } 243 | 244 | /// A "walker" object that may be used to step through the siblings of the given child node. 245 | /// 246 | /// Unlike the `Siblings` type, `WalkSiblings` does not borrow the `RoseTree`. 247 | pub fn walk_siblings(&self, child: NodeIndex) -> WalkSiblings { 248 | let maybe_walk_children = self.parent(child).map(|parent| self.walk_children(parent)); 249 | WalkSiblings { 250 | child, 251 | maybe_walk_children, 252 | } 253 | } 254 | } 255 | 256 | impl ::std::ops::Index> for RoseTree 257 | where 258 | Ix: IndexType, 259 | { 260 | type Output = N; 261 | fn index(&self, index: NodeIndex) -> &N { 262 | &self.graph[index] 263 | } 264 | } 265 | 266 | impl ::std::ops::IndexMut> for RoseTree 267 | where 268 | Ix: IndexType, 269 | { 270 | fn index_mut(&mut self, index: NodeIndex) -> &mut N { 271 | &mut self.graph[index] 272 | } 273 | } 274 | 275 | impl<'a, Ix> Iterator for Siblings<'a, Ix> 276 | where 277 | Ix: IndexType, 278 | { 279 | type Item = NodeIndex; 280 | fn next(&mut self) -> Option> { 281 | let Siblings { 282 | child, 283 | ref mut maybe_siblings, 284 | } = *self; 285 | maybe_siblings.as_mut().and_then(|siblings| { 286 | siblings.next().and_then(|sibling| { 287 | if sibling != child { 288 | Some(sibling) 289 | } else { 290 | siblings.next() 291 | } 292 | }) 293 | }) 294 | } 295 | } 296 | 297 | impl<'a, N, Ix> Iterator for ParentRecursion<'a, N, Ix> 298 | where 299 | Ix: IndexType, 300 | { 301 | type Item = NodeIndex; 302 | fn next(&mut self) -> Option> { 303 | let ParentRecursion { 304 | ref mut child, 305 | ref rose_tree, 306 | } = *self; 307 | rose_tree.parent(*child).map(|parent| { 308 | *child = parent; 309 | parent 310 | }) 311 | } 312 | } 313 | 314 | impl WalkChildren 315 | where 316 | Ix: IndexType, 317 | { 318 | /// Fetch the next child index in the walk for the given `RoseTree`. 319 | pub fn next(&mut self, tree: &RoseTree) -> Option> { 320 | self.walk_edges.next(&tree.graph).map(|(_, n)| n) 321 | } 322 | } 323 | 324 | impl WalkSiblings 325 | where 326 | Ix: IndexType, 327 | { 328 | /// Fetch the next sibling index in the walk for the given `RoseTree`. 329 | pub fn next(&mut self, tree: &RoseTree) -> Option> { 330 | let WalkSiblings { 331 | child, 332 | ref mut maybe_walk_children, 333 | } = *self; 334 | maybe_walk_children.as_mut().and_then(|walk_children| { 335 | walk_children.next(tree).and_then(|sibling| { 336 | if child != sibling { 337 | Some(sibling) 338 | } else { 339 | walk_children.next(tree) 340 | } 341 | }) 342 | }) 343 | } 344 | } 345 | -------------------------------------------------------------------------------- /tests/iterators.rs: -------------------------------------------------------------------------------- 1 | extern crate rose_tree; 2 | 3 | use rose_tree::RoseTree; 4 | 5 | struct Weight; 6 | 7 | #[test] 8 | fn children() { 9 | let (mut tree, root) = RoseTree::::new(Weight); 10 | let a = tree.add_child(root, Weight); 11 | let b = tree.add_child(root, Weight); 12 | let c = tree.add_child(root, Weight); 13 | 14 | { 15 | let mut children = tree.children(root); 16 | assert_eq!(Some(c), children.next()); 17 | assert_eq!(Some(b), children.next()); 18 | assert_eq!(Some(a), children.next()); 19 | assert_eq!(None, children.next()); 20 | } 21 | 22 | { 23 | let d = tree.add_child(b, Weight); 24 | let e = tree.add_child(b, Weight); 25 | let f = tree.add_child(b, Weight); 26 | let mut children = tree.children(b); 27 | assert_eq!(Some(f), children.next()); 28 | assert_eq!(Some(e), children.next()); 29 | assert_eq!(Some(d), children.next()); 30 | assert_eq!(None, children.next()); 31 | } 32 | } 33 | 34 | #[test] 35 | fn parent_recursion() { 36 | let (mut tree, root) = RoseTree::::new(Weight); 37 | let a = tree.add_child(root, Weight); 38 | let a_1 = tree.add_child(root, Weight); 39 | let a_2 = tree.add_child(root, Weight); 40 | let b = tree.add_child(a, Weight); 41 | let c = tree.add_child(b, Weight); 42 | 43 | { 44 | let mut parent_recursion = tree.parent_recursion(c); 45 | assert_eq!(Some(b), parent_recursion.next()); 46 | assert_eq!(Some(a), parent_recursion.next()); 47 | assert_eq!(Some(root), parent_recursion.next()); 48 | assert_eq!(None, parent_recursion.next()); 49 | } 50 | 51 | let b_1 = tree.add_child(a_1, Weight); 52 | let c_1 = tree.add_child(b_1, Weight); 53 | let d_1 = tree.add_child(c_1, Weight); 54 | 55 | { 56 | let mut parent_recursion = tree.parent_recursion(d_1); 57 | assert_eq!(Some(c_1), parent_recursion.next()); 58 | assert_eq!(Some(b_1), parent_recursion.next()); 59 | assert_eq!(Some(a_1), parent_recursion.next()); 60 | assert_eq!(Some(root), parent_recursion.next()); 61 | assert_eq!(None, parent_recursion.next()); 62 | } 63 | 64 | let b_2 = tree.add_child(a_2, Weight); 65 | let c_2 = tree.add_child(b_2, Weight); 66 | 67 | { 68 | let mut parent_recursion = tree.parent_recursion(c_2); 69 | assert_eq!(Some(b_2), parent_recursion.next()); 70 | assert_eq!(Some(a_2), parent_recursion.next()); 71 | assert_eq!(Some(root), parent_recursion.next()); 72 | assert_eq!(None, parent_recursion.next()); 73 | } 74 | } 75 | 76 | #[test] 77 | fn siblings() { 78 | let (mut tree, root) = RoseTree::::new(Weight); 79 | let a = tree.add_child(root, Weight); 80 | let b = tree.add_child(root, Weight); 81 | let c = tree.add_child(root, Weight); 82 | let d = tree.add_child(root, Weight); 83 | 84 | { 85 | let mut siblings = tree.siblings(a); 86 | assert_eq!(Some(d), siblings.next()); 87 | assert_eq!(Some(c), siblings.next()); 88 | assert_eq!(Some(b), siblings.next()); 89 | assert_eq!(None, siblings.next()); 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /tests/remove.rs: -------------------------------------------------------------------------------- 1 | extern crate rose_tree; 2 | 3 | use rose_tree::RoseTree; 4 | 5 | #[test] 6 | fn remove_node() { 7 | let (mut tree, root) = RoseTree::::new(0); 8 | let a = tree.add_child(root, 1); 9 | let _b = tree.add_child(a, 2); 10 | let _c = tree.add_child(a, 3); 11 | let _d = tree.add_child(a, 4); 12 | 13 | assert_eq!(Some(1), tree.remove_node(a)); 14 | 15 | let mut children = tree.children(root); 16 | assert_eq!(Some(2), children.next().map(|idx| tree[idx])); 17 | assert_eq!(Some(3), children.next().map(|idx| tree[idx])); 18 | assert_eq!(Some(4), children.next().map(|idx| tree[idx])); 19 | assert_eq!(None, children.next()); 20 | } 21 | -------------------------------------------------------------------------------- /tests/walkers.rs: -------------------------------------------------------------------------------- 1 | extern crate rose_tree; 2 | 3 | use rose_tree::RoseTree; 4 | 5 | struct Weight; 6 | 7 | #[test] 8 | fn walk_children() { 9 | let (mut tree, root) = RoseTree::::new(Weight); 10 | let a = tree.add_child(root, Weight); 11 | let b = tree.add_child(root, Weight); 12 | let c = tree.add_child(root, Weight); 13 | 14 | let mut child_walker = tree.walk_children(root); 15 | assert_eq!(Some(c), child_walker.next(&tree)); 16 | assert_eq!(Some(b), child_walker.next(&tree)); 17 | assert_eq!(Some(a), child_walker.next(&tree)); 18 | assert_eq!(None, child_walker.next(&tree)); 19 | 20 | let d = tree.add_child(b, Weight); 21 | let e = tree.add_child(b, Weight); 22 | let f = tree.add_child(b, Weight); 23 | 24 | child_walker = tree.walk_children(b); 25 | assert_eq!(Some(f), child_walker.next(&tree)); 26 | assert_eq!(Some(e), child_walker.next(&tree)); 27 | assert_eq!(Some(d), child_walker.next(&tree)); 28 | assert_eq!(None, child_walker.next(&tree)); 29 | } 30 | 31 | #[test] 32 | fn walk_siblings() { 33 | let (mut tree, root) = RoseTree::::new(Weight); 34 | let a = tree.add_child(root, Weight); 35 | let b = tree.add_child(root, Weight); 36 | let c = tree.add_child(root, Weight); 37 | let d = tree.add_child(root, Weight); 38 | 39 | let mut sibling_walker = tree.walk_siblings(a); 40 | assert_eq!(Some(d), sibling_walker.next(&tree)); 41 | assert_eq!(Some(c), sibling_walker.next(&tree)); 42 | assert_eq!(Some(b), sibling_walker.next(&tree)); 43 | assert_eq!(None, sibling_walker.next(&tree)); 44 | } 45 | --------------------------------------------------------------------------------