Skip to content

Commit

Permalink
Add Rc::get_mut_unchecked, Arc::get_mut_unchecked
Browse files Browse the repository at this point in the history
  • Loading branch information
SimonSapin committed Aug 16, 2019
1 parent 9dd5c19 commit 1613fda
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 2 deletions.
31 changes: 30 additions & 1 deletion src/liballoc/rc.rs
Expand Up @@ -560,13 +560,42 @@ impl<T: ?Sized> Rc<T> {
pub fn get_mut(this: &mut Self) -> Option<&mut T> {
if Rc::is_unique(this) {
unsafe {
Some(&mut this.ptr.as_mut().value)
Some(Rc::get_mut_unchecked(this))
}
} else {
None
}
}

/// Returns a mutable reference to the inner value,
/// without any check.
///
/// See also [`get_mut`], which is safe and does appropriate checks.
///
/// [`get_mut`]: struct.Rc.html#method.get_mut
///
/// # Safety
///
/// There must be no other `Rc` or [`Weak`][weak] pointers to the same value.
/// This is the case for example immediately after `Rc::new`.
///
/// # Examples
///
/// ```
/// use std::rc::Rc;
///
/// let mut x = Rc::new(String::new());
/// unsafe {
/// Rc::get_mut_unchecked(&mut x).push_str("foo")
/// }
/// assert_eq!(*x, "foo");
/// ```
#[inline]
#[unstable(feature = "get_mut_unchecked", issue = "0")]
pub unsafe fn get_mut_unchecked(this: &mut Self) -> &mut T {
&mut this.ptr.as_mut().value
}

#[inline]
#[stable(feature = "ptr_eq", since = "1.17.0")]
/// Returns `true` if the two `Rc`s point to the same value (not
Expand Down
31 changes: 30 additions & 1 deletion src/liballoc/sync.rs
Expand Up @@ -945,13 +945,42 @@ impl<T: ?Sized> Arc<T> {
// the Arc itself to be `mut`, so we're returning the only possible
// reference to the inner data.
unsafe {
Some(&mut this.ptr.as_mut().data)
Some(Arc::get_mut_unchecked(this))
}
} else {
None
}
}

/// Returns a mutable reference to the inner value,
/// without any check.
///
/// See also [`get_mut`], which is safe and does appropriate checks.
///
/// [`get_mut`]: struct.Arc.html#method.get_mut
///
/// # Safety
///
/// There must be no other `Arc` or [`Weak`][weak] pointers to the same value.
/// This is the case for example immediately after `Rc::new`.
///
/// # Examples
///
/// ```
/// use std::sync::Arc;
///
/// let mut x = Arc::new(String::new());
/// unsafe {
/// Arc::get_mut_unchecked(&mut x).push_str("foo")
/// }
/// assert_eq!(*x, "foo");
/// ```
#[inline]
#[unstable(feature = "get_mut_unchecked", issue = "0")]
pub unsafe fn get_mut_unchecked(this: &mut Self) -> &mut T {
&mut this.ptr.as_mut().data
}

/// Determine whether this is the unique reference (including weak refs) to
/// the underlying data.
///
Expand Down

0 comments on commit 1613fda

Please sign in to comment.