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<N, Ix> = pg::Graph<N, (), pg::Directed, Ix>; 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<N, Ix: IndexType = DefIndex> { 55 /// A graph for storing all nodes and edges between them that represent the tree. 56 graph: PetGraph<N, Ix>, 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<N, Ix>, 63 child: NodeIndex<Ix>, 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<Ix>, 72 maybe_siblings: Option<Children<'a, Ix>>, 73 } 74 75 /// A "walker" object that can be used to step through the children of some parent node. 76 pub struct WalkChildren<Ix: IndexType> { 77 walk_edges: pg::graph::WalkNeighbors<Ix>, 78 } 79 80 /// A "walker" object that can be used to step through the siblings of some child node. 81 pub struct WalkSiblings<Ix: IndexType> { 82 child: NodeIndex<Ix>, 83 maybe_walk_children: Option<WalkChildren<Ix>>, 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<N, Ix> RoseTree<N, Ix> 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. new(root: N) -> (Self, NodeIndex<Ix>)95 pub fn new(root: N) -> (Self, NodeIndex<Ix>) { 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. with_capacity(nodes: usize, root: N) -> (Self, NodeIndex<Ix>)101 pub fn with_capacity(nodes: usize, root: N) -> (Self, NodeIndex<Ix>) { 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. node_count(&self) -> usize108 pub fn node_count(&self) -> usize { 109 self.graph.node_count() 110 } 111 112 /// Borrow the `RoseTree`'s underlying `PetGraph<N, Ix>`. 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`. graph(&self) -> &PetGraph<N, Ix>115 pub fn graph(&self) -> &PetGraph<N, Ix> { 116 &self.graph 117 } 118 119 /// Take ownership of the RoseTree and return the internal PetGraph<N, Ix>. 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`. into_graph(self) -> PetGraph<N, Ix>122 pub fn into_graph(self) -> PetGraph<N, Ix> { 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. add_child(&mut self, parent: NodeIndex<Ix>, kid: N) -> NodeIndex<Ix>135 pub fn add_child(&mut self, parent: NodeIndex<Ix>, kid: N) -> NodeIndex<Ix> { 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. node_weight(&self, node: NodeIndex<Ix>) -> Option<&N>142 pub fn node_weight(&self, node: NodeIndex<Ix>) -> Option<&N> { 143 self.graph.node_weight(node) 144 } 145 146 /// Mutably borrow the weight from the node at the given index. node_weight_mut(&mut self, node: NodeIndex<Ix>) -> Option<&mut N>147 pub fn node_weight_mut(&mut self, node: NodeIndex<Ix>) -> 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. index_twice_mut(&mut self, a: NodeIndex<Ix>, b: NodeIndex<Ix>) -> (&mut N, &mut N)154 pub fn index_twice_mut(&mut self, a: NodeIndex<Ix>, b: NodeIndex<Ix>) -> (&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. remove_all_but_root(&mut self)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! remove_node(&mut self, node: NodeIndex<Ix>) -> Option<N>175 pub fn remove_node(&mut self, node: NodeIndex<Ix>) -> Option<N> { 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. remove_node_with_children(&mut self, _node: NodeIndex<Ix>) -> Option<RoseTree<N, Ix>>199 pub fn remove_node_with_children(&mut self, _node: NodeIndex<Ix>) -> Option<RoseTree<N, Ix>> { 200 unimplemented!(); 201 } 202 203 /// An index to the parent of the node at the given index if there is one. parent(&self, child: NodeIndex<Ix>) -> Option<NodeIndex<Ix>>204 pub fn parent(&self, child: NodeIndex<Ix>) -> Option<NodeIndex<Ix>> { 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<Ix>`s. parent_recursion(&self, child: NodeIndex<Ix>) -> ParentRecursion<N, Ix>211 pub fn parent_recursion(&self, child: NodeIndex<Ix>) -> ParentRecursion<N, Ix> { 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<Ix>`s. children(&self, parent: NodeIndex<Ix>) -> Children<Ix>221 pub fn children(&self, parent: NodeIndex<Ix>) -> Children<Ix> { 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`. walk_children(&self, parent: NodeIndex<Ix>) -> WalkChildren<Ix>228 pub fn walk_children(&self, parent: NodeIndex<Ix>) -> WalkChildren<Ix> { 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<Ix>`s. siblings(&self, child: NodeIndex<Ix>) -> Siblings<Ix>236 pub fn siblings(&self, child: NodeIndex<Ix>) -> Siblings<Ix> { 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`. walk_siblings(&self, child: NodeIndex<Ix>) -> WalkSiblings<Ix>247 pub fn walk_siblings(&self, child: NodeIndex<Ix>) -> WalkSiblings<Ix> { 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<N, Ix> ::std::ops::Index<NodeIndex<Ix>> for RoseTree<N, Ix> 257 where 258 Ix: IndexType, 259 { 260 type Output = N; index(&self, index: NodeIndex<Ix>) -> &N261 fn index(&self, index: NodeIndex<Ix>) -> &N { 262 &self.graph[index] 263 } 264 } 265 266 impl<N, Ix> ::std::ops::IndexMut<NodeIndex<Ix>> for RoseTree<N, Ix> 267 where 268 Ix: IndexType, 269 { index_mut(&mut self, index: NodeIndex<Ix>) -> &mut N270 fn index_mut(&mut self, index: NodeIndex<Ix>) -> &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<Ix>; next(&mut self) -> Option<NodeIndex<Ix>>280 fn next(&mut self) -> Option<NodeIndex<Ix>> { 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<Ix>; next(&mut self) -> Option<NodeIndex<Ix>>302 fn next(&mut self) -> Option<NodeIndex<Ix>> { 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<Ix> WalkChildren<Ix> 315 where 316 Ix: IndexType, 317 { 318 /// Fetch the next child index in the walk for the given `RoseTree`. next<N>(&mut self, tree: &RoseTree<N, Ix>) -> Option<NodeIndex<Ix>>319 pub fn next<N>(&mut self, tree: &RoseTree<N, Ix>) -> Option<NodeIndex<Ix>> { 320 self.walk_edges.next(&tree.graph).map(|(_, n)| n) 321 } 322 } 323 324 impl<Ix> WalkSiblings<Ix> 325 where 326 Ix: IndexType, 327 { 328 /// Fetch the next sibling index in the walk for the given `RoseTree`. next<N>(&mut self, tree: &RoseTree<N, Ix>) -> Option<NodeIndex<Ix>>329 pub fn next<N>(&mut self, tree: &RoseTree<N, Ix>) -> Option<NodeIndex<Ix>> { 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