Advertisement
Guest User

Untitled

a guest
Sep 15th, 2019
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.70 KB | None | 0 0
  1. use std::ops::{Deref, DerefMut};
  2. use std::rc::{Rc, Weak};
  3. use std::cell::RefCell;
  4. use crate::List::{Cons, Nil};
  5.  
  6. #[derive(Clone,Debug)]
  7. enum List<Link> {
  8. Cons(i32, RefCell<Link>),
  9. Nil,
  10. }
  11.  
  12. impl<Link> List<Link> {
  13. fn tail(&self) -> Option<&RefCell<Link>> {
  14. match self {
  15. Cons(_, item) => Some(item),
  16. Nil => None,
  17. }
  18. }
  19. }
  20.  
  21. #[derive(Clone,Debug)]
  22. struct RcLink(pub Rc<List<RcLink>>);
  23.  
  24. impl Deref for RcLink {
  25. type Target = Rc<List<RcLink>>;
  26. fn deref(&self) -> &Self::Target { &self.0 }
  27. }
  28. impl DerefMut for RcLink {
  29. fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 }
  30. }
  31.  
  32. #[derive(Clone,Debug)]
  33. struct WeakLink(pub Weak<List<WeakLink>>);
  34.  
  35. impl Deref for WeakLink {
  36. type Target = Weak<List<WeakLink>>;
  37. fn deref(&self) -> &Self::Target { &self.0 }
  38. }
  39. impl DerefMut for WeakLink {
  40. fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 }
  41. }
  42.  
  43. fn main() {
  44. let a = RcLink(Rc::new(Cons(5, RefCell::new(RcLink(Rc::new(Nil))))));
  45.  
  46. println!("a initial rc count = {}", Rc::strong_count(&a));
  47. println!("a next item = {:?}", a.tail());
  48.  
  49. let b = RcLink(Rc::new(Cons(10, RefCell::new(a.clone()))));
  50.  
  51. println!("a rc count after b creation = {}", Rc::strong_count(&a));
  52. println!("b initial rc count = {}", Rc::strong_count(&b));
  53. println!("b next item = {:?}", b.tail());
  54.  
  55. if let Some(link) = a.tail() {
  56. *link.borrow_mut() = b.clone();
  57. }
  58.  
  59. println!("b rc count after changing a = {}", Rc::strong_count(&b));
  60. println!("a rc count after changing a = {}", Rc::strong_count(&a));
  61.  
  62. // Uncomment the next line to see that we have a cycle;
  63. // it will overflow the stack
  64. // println!("a next item = {:?}", a.tail());
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement