Advertisement
Guest User

Untitled

a guest
Mar 24th, 2019
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.57 KB | None | 0 0
  1. use std::rc::Rc;
  2. use std::cell::{RefCell, RefMut, Ref};
  3.  
  4.  
  5. #[derive(Debug)]
  6. struct SharedRcOption<T>(Option<Rc<RefCell<T>>>);
  7.  
  8. impl<T> SharedRcOption<T> {
  9. fn empty() -> Self {
  10. Self(None)
  11. }
  12.  
  13. fn new(element: T) -> Self {
  14. Self(Some(Rc::new(RefCell::new(element))))
  15. }
  16.  
  17. fn is_empty(&self) -> bool {
  18. self.0.is_none()
  19. }
  20.  
  21. fn borrow_mut(&mut self) -> RefMut<T> {
  22. self.0.as_mut().expect(
  23. "Empty SharedRCOption cannot be unwrapped"
  24. ).borrow_mut()
  25. }
  26.  
  27. fn borrow(&self) -> Ref<T> {
  28. self.0.as_ref().expect(
  29. "Empty SharedRCOption cannot be unwrapped"
  30. ).borrow()
  31. }
  32.  
  33. fn clear(&mut self) {
  34. self.0 = None;
  35. }
  36. }
  37.  
  38. impl<T> Clone for SharedRcOption<T> {
  39. fn clone(&self) -> Self {
  40. Self(self.0.clone())
  41. }
  42. }
  43.  
  44. #[derive(Debug)]
  45. struct Edge {
  46. next: SharedRcOption<Edge>,
  47. }
  48.  
  49. impl Edge {
  50. fn new() -> Self {
  51. Self {
  52. next: SharedRcOption::empty(),
  53. }
  54. }
  55.  
  56. fn as_shared_rc_option(self) -> SharedRcOption<Self> {
  57. SharedRcOption::new(self)
  58. }
  59. }
  60.  
  61.  
  62. fn main() {
  63. let mut a = Edge::new().as_shared_rc_option();
  64. a.borrow_mut().next = Edge::new().as_shared_rc_option();
  65. a.borrow_mut().next.borrow_mut().next = Edge::new().as_shared_rc_option();
  66. a.borrow_mut().next.borrow_mut().next.borrow_mut().next = Edge::new().as_shared_rc_option();
  67. a.borrow_mut().next.borrow_mut().next.borrow_mut().next.borrow_mut().next =
  68. a.clone();
  69. //a.next.borrow_mut().next.clear();
  70.  
  71. println!("{:?}", a);
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement