Add Rc::get_mut_unchecked, Arc::get_mut_unchecked

This commit is contained in:
Simon Sapin 2019-07-06 18:17:24 +02:00
parent 9dd5c19199
commit 1613fdae37
2 changed files with 60 additions and 2 deletions

View File

@ -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

View File

@ -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.
///