Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // A tree structure that stores its nodes in depth-first order for faster
- // iteration.
- struct Tree<T> {
- raw_nodes: Vec<RawNode<T>>,
- node_capacity: usize,
- }
- // The internal node type.
- struct RawNode<T> {
- value: T,
- parent_index: Option<usize>,
- num_children: usize,
- }
- // We want to be able to refer to a node in the tree, and call methods like:
- //
- // let root_node = tree.root();
- // let val = root_node.child(1).value();
- // let child_node = root_node.child(3);
- // let original_node = child_node.parent();
- //
- // But we can't do this. If all we have is a `&RawNode`, we can't access other
- // nodes (except with unsafe shenanigans of course). Also, what about the `Tree`
- // field `node_capacity`? A `&mut RawNode` should have access to this field when
- // it tries to add children.
- // Define an RST proxy `Node` type to solve these issues. This can't be
- // represented with a DST because the wrapped pointer is not directly to the
- // data itself, but to the containing `Tree` instead.
- struct &'a Node<T> {
- tree: &'a Tree<T>,
- index: usize,
- }
- struct &'a mut Node<T> {
- tree: &'a mut Tree<T>,
- index: usize,
- }
- // Now implement the methods we want.
- impl Node<T> {
- fn parent(&self) -> &Node<T> {
- // A bunch of code...
- }
- fn add_child(&mut self) {
- let capacity = self.tree.node_capacity;
- // Code code....
- }
- }
Add Comment
Please, Sign In to add comment