Advertisement
NLinker

Tree graph algorithm without RefCell

Mar 5th, 2024
1,440
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.49 KB | None | 0 0
  1. use std::error::Error;
  2. use refbox::{RefBox, Ref};
  3.  
  4. struct Node<T> {
  5.     id: T,
  6.     left: Option<RefBox<Node<T>>>,
  7.     right: Option<RefBox<Node<T>>>,
  8. }
  9.  
  10. trait MapRefBox<T> {
  11.     fn map_to_ref(&self) -> Option<Ref<T>>;
  12. }
  13.  
  14. impl<T> MapRefBox<T> for Option<RefBox<T>> {
  15.     fn map_to_ref(&self) -> Option<Ref<T>> {
  16.         self.as_ref().map(|rc| rc.create_ref())
  17.     }
  18. }
  19.  
  20. fn node(id: i32, l: RefBox<Node<i32>>, r: RefBox<Node<i32>>) -> RefBox<Node<i32>> {
  21.     RefBox::new(Node { id, left: Some(l), right: Some(r) })
  22. }
  23. fn left(id: i32, l: RefBox<Node<i32>>) -> RefBox<Node<i32>> {
  24.     RefBox::new(Node { id, left: Some(l), right: None })
  25. }
  26. fn right(id: i32, r: RefBox<Node<i32>>) -> RefBox<Node<i32>> {
  27.     RefBox::new(Node { id, left: None, right: Some(r) })
  28. }
  29. fn leaf(id: i32) -> RefBox<Node<i32>> {
  30.     RefBox::new(Node { id, left: None, right: None })
  31. }
  32.  
  33. // immutable access to tree
  34. fn print_tree(node: Option<Ref<Node<i32>>>, depth: usize) -> Result<(), Box<dyn Error>> {
  35.     if let Some(n) = node {
  36.         let n = n.try_borrow_mut()?;
  37.         println!("{}{}", "  ".repeat(depth), n.id);
  38.         print_tree(n.left.map_to_ref(), depth + 1)?;
  39.         print_tree(n.right.map_to_ref(), depth + 1)?;
  40.     }
  41.     Ok(())
  42. }
  43.  
  44.  
  45. fn main() -> Result<(), Box<dyn Error>> {
  46.     let tree = node(1,
  47.                     node(2, leaf(4), leaf(5)),
  48.                     node(3, leaf(6), leaf(7)));
  49.     print_tree(Some(tree).map_to_ref(), 0)?;
  50.  
  51.  
  52.     println!("Hello, world!");
  53.     Ok(())
  54. }
  55.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement