Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add strong_count mutation methods to Rc #83476

Merged
merged 1 commit into from
Apr 7, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 67 additions & 0 deletions library/alloc/src/rc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -910,6 +910,73 @@ impl<T: ?Sized> Rc<T> {
this.inner().strong()
}

/// Increments the strong reference count on the `Rc<T>` associated with the
/// provided pointer by one.
///
/// # Safety
///
/// The pointer must have been obtained through `Rc::into_raw`, and the
/// associated `Rc` instance must be valid (i.e. the strong count must be at
/// least 1) for the duration of this method.
///
/// # Examples
///
/// ```
/// use std::rc::Rc;
///
/// let five = Rc::new(5);
///
/// unsafe {
/// let ptr = Rc::into_raw(five);
/// Rc::increment_strong_count(ptr);
///
/// let five = Rc::from_raw(ptr);
/// assert_eq!(2, Rc::strong_count(&five));
/// }
/// ```
#[inline]
#[stable(feature = "rc_mutate_strong_count", since = "1.53.0")]
pub unsafe fn increment_strong_count(ptr: *const T) {
// Retain Rc, but don't touch refcount by wrapping in ManuallyDrop
let rc = unsafe { mem::ManuallyDrop::new(Rc::<T>::from_raw(ptr)) };
// Now increase refcount, but don't drop new refcount either
let _rc_clone: mem::ManuallyDrop<_> = rc.clone();
}

/// Decrements the strong reference count on the `Rc<T>` associated with the
/// provided pointer by one.
///
/// # Safety
///
/// The pointer must have been obtained through `Rc::into_raw`, and the
/// associated `Rc` instance must be valid (i.e. the strong count must be at
/// least 1) when invoking this method. This method can be used to release
/// the final `Rc` and backing storage, but **should not** be called after
/// the final `Rc` has been released.
///
/// # Examples
///
/// ```
/// use std::rc::Rc;
///
/// let five = Rc::new(5);
///
/// unsafe {
/// let ptr = Rc::into_raw(five);
/// Rc::increment_strong_count(ptr);
///
/// let five = Rc::from_raw(ptr);
/// assert_eq!(2, Rc::strong_count(&five));
/// Rc::decrement_strong_count(ptr);
/// assert_eq!(1, Rc::strong_count(&five));
/// }
/// ```
#[inline]
#[stable(feature = "rc_mutate_strong_count", since = "1.53.0")]
pub unsafe fn decrement_strong_count(ptr: *const T) {
unsafe { mem::drop(Rc::from_raw(ptr)) };
}

/// Returns `true` if there are no other `Rc` or [`Weak`] pointers to
/// this allocation.
#[inline]
Expand Down