diff --git a/src/listhead.rs b/src/listhead.rs index a322303..db7fd7a 100644 --- a/src/listhead.rs +++ b/src/listhead.rs @@ -6,6 +6,7 @@ pub struct ListHead { prev: Weak::>>, next: Weak::>>, data: Weak::>, + _self_wp: Weak::>>, } impl ListHead { @@ -14,8 +15,10 @@ impl ListHead { let this = Rc::new(RefCell::new(ListHead{ prev: Weak::>>::new(), next: Weak::>>::new(), - data: Weak::>::new() + data: Weak::>::new(), + _self_wp: Weak::>>::new() })); + this.borrow_mut()._self_wp = Rc::downgrade(&this); this.borrow_mut().init(); return this; } @@ -24,26 +27,20 @@ impl ListHead { let this = Rc::new(RefCell::new(ListHead{ prev: Weak::>>::new(), next: Weak::>>::new(), - data: data + data: data, + _self_wp: Weak::>>::new() })); this.borrow_mut().init(); return this; } - fn get_rc_refcell(&self) -> Rc::>> { - let cell_rc: &Rc>> = &self.next.upgrade().unwrap(); - //let head: &ListHead = &*cell_rc.borrow(); - let cell_start = cell_rc.as_ptr() as *const u8; - //let data_start = head as *const ListHead as *const u8; - //let cell_offset = unsafe { data_start.offset_from(cell_start) }; - unsafe { - return Rc::from_raw(cell_start as *const RefCell::>); - }; + fn shared_from_self(&self) -> Rc::>> { + return self._self_wp.upgrade().unwrap(); } fn init(&mut self) { - self.prev = Rc::downgrade(&self.get_rc_refcell()); - self.next = Rc::downgrade(&self.get_rc_refcell()); + self.prev = Rc::downgrade(&self.shared_from_self()); + self.next = Rc::downgrade(&self.shared_from_self()); } pub fn data(&self) -> Weak::> { @@ -87,8 +84,8 @@ impl ListHead { pub fn for_each(&self, cb: fn (&Weak::>) -> bool) { let mut pos = self.next.clone(); - let self_weak = &Rc::downgrade(&self.get_rc_refcell()); - while !Weak::ptr_eq(&pos, self_weak) { + let self_weak = Rc::downgrade(&self.shared_from_self()); + while !Weak::ptr_eq(&pos, &self_weak) { if !cb(&pos.upgrade().unwrap().borrow().data()) { break; }