Guest User

Untitled

a guest
Oct 4th, 2025
209
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.78 KB | None | 0 0
  1. #[derive(Debug)]
  2. struct Node<T> where T: Debug, T: Default {
  3. prev: Option<Rc<RefCell<Node<T>>>>,
  4. next: Option<Rc<RefCell<Node<T>>>>,
  5. value: T,
  6. }
  7.  
  8. impl<T> Node<T> where T: Debug, T: Default {
  9. /// Create a self-linked node: prev == this, next == this.
  10. fn new(value: T) -> Rc<RefCell<Self>> {
  11. let node = Rc::new(RefCell::new(Self { prev: None, next: None, value }));
  12. {
  13. let mut n = node.borrow_mut();
  14. n.prev = Some(Rc::clone(&node));
  15. n.next = Some(Rc::clone(&node));
  16. }
  17. node
  18. }
  19.  
  20. /// Splice a new node *after* `this` in the circular ring; returns the new node.
  21. fn add_next(this: &Rc<RefCell<Node<T>>>, value: T) -> Rc<RefCell<Node<T>>> {
  22. let new = Node::new(value); // self-linked; we’ll rewire below
  23.  
  24. // Current successor of `this`
  25. let next = {
  26. let t = this.borrow();
  27. t.next.as_ref().expect("ring invariant").clone()
  28. };
  29.  
  30. // Rewire: this <-> new <-> next
  31. {
  32. let mut nb = new.borrow_mut();
  33. nb.prev = Some(Rc::clone(this));
  34. nb.next = Some(Rc::clone(&next));
  35. }
  36. this.borrow_mut().next = Some(Rc::clone(&new));
  37. next.borrow_mut().prev = Some(Rc::clone(&new));
  38.  
  39. new
  40. }
  41.  
  42. pub fn remove(node: Rc<RefCell<Self>>) -> (Option<Rc<RefCell<Self>>>, Self) {
  43. // Snapshot neighbors
  44. let (prev, next) = {
  45. let n = node.borrow();
  46. (
  47. n.prev.as_ref().expect("prev").clone(),
  48. n.next.as_ref().expect("next").clone(),
  49. )
  50. };
  51.  
  52. let singleton = Rc::ptr_eq(&prev, &node) && Rc::ptr_eq(&next, &node);
  53.  
  54. if !singleton {
  55. // Rewire neighbors
  56. {
  57. let mut pb = prev.borrow_mut();
  58. pb.next = Some(Rc::clone(&next));
  59. }
  60. {
  61. let mut nb = next.borrow_mut();
  62. nb.prev = Some(Rc::clone(&prev));
  63. }
  64. }
  65.  
  66. // Break this node's own links
  67. {
  68. let mut n = node.borrow_mut();
  69. n.prev = None;
  70. n.next = None;
  71. }
  72.  
  73. // Determine return-next *before* any potential drops.
  74. let ret_next = if singleton { None } else { Some(Rc::clone(&next)) };
  75.  
  76. // In the singleton case, our local `prev`/`next` are extra strong refs to `node`.
  77. // Drop them so Rc::try_unwrap sees a strong count of 1.
  78. if singleton {
  79. drop(prev);
  80. drop(next);
  81. }
  82.  
  83. let owned = Rc::try_unwrap(node)
  84. .ok()
  85. .expect("Node::remove: other strong Rc clones exist")
  86. .into_inner();
  87.  
  88. (ret_next, owned)
  89. }
  90. }
Advertisement
Add Comment
Please, Sign In to add comment