Skip to content

Instantly share code, notes, and snippets.

@aturon
Created May 29, 2014 17:47
Show Gist options
  • Save aturon/89273f34820a3d99bf5b to your computer and use it in GitHub Desktop.
Save aturon/89273f34820a3d99bf5b to your computer and use it in GitHub Desktop.
clone-on-write for Rc
impl<T: Clone> Rc<T>
#[inline(always)]
fn inner_mut<'a>(&'a mut self) -> &'a mut RcBox<T> {
unsafe { &mut (*self._ptr) }
}
/// Construct a mutable pointer by cloning the referent into a new
/// reference-counted box, unless this is the sole reference.
pub fn to_mut<'a>(&'a mut self) -> &'a mut T {
// We hold a strong reference, which is also implicitly a weak
// reference (so self.weak() >= 1).
if self.weak() > 1 || self.strong() > 1 {
self.dec_strong();
self._ptr = transmute(box RcBox {
value: self.inner().value.clone(),
strong: Cell::new(1),
weak: Cell::new(1)
})
}
&mut self.inner_mut().value
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment