Guest User

Untitled

a guest
Jun 20th, 2018
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.36 KB | None | 0 0
  1. // A tree structure that stores its nodes in depth-first order for faster
  2. // iteration.
  3. struct Tree<T> {
  4. raw_nodes: Vec<RawNode<T>>,
  5. node_capacity: usize,
  6. }
  7.  
  8. // The internal node type.
  9. struct RawNode<T> {
  10. value: T,
  11. parent_index: Option<usize>,
  12. num_children: usize,
  13. }
  14.  
  15. // We want to be able to refer to a node in the tree, and call methods like:
  16. //
  17. // let root_node = tree.root();
  18. // let val = root_node.child(1).value();
  19. // let child_node = root_node.child(3);
  20. // let original_node = child_node.parent();
  21. //
  22. // But we can't do this. If all we have is a `&RawNode`, we can't access other
  23. // nodes (except with unsafe shenanigans of course). Also, what about the `Tree`
  24. // field `node_capacity`? A `&mut RawNode` should have access to this field when
  25. // it tries to add children.
  26.  
  27. // Define an RST proxy `Node` type to solve these issues. This can't be
  28. // represented with a DST because the wrapped pointer is not directly to the
  29. // data itself, but to the containing `Tree` instead.
  30. struct &'a Node<T> {
  31. tree: &'a Tree<T>,
  32. index: usize,
  33. }
  34.  
  35. struct &'a mut Node<T> {
  36. tree: &'a mut Tree<T>,
  37. index: usize,
  38. }
  39.  
  40. // Now implement the methods we want.
  41. impl Node<T> {
  42. fn parent(&self) -> &Node<T> {
  43. // A bunch of code...
  44. }
  45. fn add_child(&mut self) {
  46. let capacity = self.tree.node_capacity;
  47. // Code code....
  48. }
  49. }
Add Comment
Please, Sign In to add comment