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

Make (A)Rc/Weak allocator_api APIs more consistent #119761

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
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
131 changes: 82 additions & 49 deletions library/alloc/src/rc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -365,6 +365,12 @@ impl<T: ?Sized, A: Allocator> Rc<T, A> {
unsafe { self.ptr.as_ref() }
}

#[inline]
fn into_inner_with_allocator(this: Self) -> (NonNull<RcBox<T>>, A) {
let this = mem::ManuallyDrop::new(this);
(this.ptr, unsafe { ptr::read(&this.alloc) })
}

#[inline]
unsafe fn from_inner_in(ptr: NonNull<RcBox<T>>, alloc: A) -> Self {
Self { ptr, phantom: PhantomData, alloc }
Expand Down Expand Up @@ -661,16 +667,6 @@ impl<T> Rc<T> {
}

impl<T, A: Allocator> Rc<T, A> {
/// Returns a reference to the underlying allocator.
///
/// Note: this is an associated function, which means that you have
/// to call it as `Rc::allocator(&r)` instead of `r.allocator()`. This
/// is so that there is no conflict with a method on the inner type.
#[inline]
#[unstable(feature = "allocator_api", issue = "32838")]
pub fn allocator(this: &Self) -> &A {
&this.alloc
}
/// Constructs a new `Rc` in the provided allocator.
///
/// # Examples
Expand Down Expand Up @@ -1145,12 +1141,9 @@ impl<T, A: Allocator> Rc<mem::MaybeUninit<T>, A> {
/// ```
#[unstable(feature = "new_uninit", issue = "63291")]
#[inline]
pub unsafe fn assume_init(self) -> Rc<T, A>
where
A: Clone,
{
let md_self = mem::ManuallyDrop::new(self);
unsafe { Rc::from_inner_in(md_self.ptr.cast(), md_self.alloc.clone()) }
pub unsafe fn assume_init(self) -> Rc<T, A> {
let (ptr, alloc) = Self::into_inner_with_allocator(self);
unsafe { Rc::from_inner_in(ptr.cast(), alloc) }
}
}

Expand Down Expand Up @@ -1189,12 +1182,9 @@ impl<T, A: Allocator> Rc<[mem::MaybeUninit<T>], A> {
/// ```
#[unstable(feature = "new_uninit", issue = "63291")]
#[inline]
pub unsafe fn assume_init(self) -> Rc<[T], A>
where
A: Clone,
{
let md_self = mem::ManuallyDrop::new(self);
unsafe { Rc::from_ptr_in(md_self.ptr.as_ptr() as _, md_self.alloc.clone()) }
pub unsafe fn assume_init(self) -> Rc<[T], A> {
let (ptr, alloc) = Self::into_inner_with_allocator(self);
unsafe { Rc::from_ptr_in(ptr.as_ptr() as _, alloc) }
}
}

Expand Down Expand Up @@ -1333,6 +1323,17 @@ impl<T: ?Sized> Rc<T> {
}

impl<T: ?Sized, A: Allocator> Rc<T, A> {
/// Returns a reference to the underlying allocator.
///
/// Note: this is an associated function, which means that you have
/// to call it as `Rc::allocator(&r)` instead of `r.allocator()`. This
/// is so that there is no conflict with a method on the inner type.
#[inline]
#[unstable(feature = "allocator_api", issue = "32838")]
pub fn allocator(this: &Self) -> &A {
&this.alloc
}

/// Consumes the `Rc`, returning the wrapped pointer.
///
/// To avoid a memory leak the pointer must be converted back to an `Rc` using
Expand All @@ -1356,6 +1357,33 @@ impl<T: ?Sized, A: Allocator> Rc<T, A> {
ptr
}

/// Consumes the `Rc`, returning the wrapped pointer and allocator.
///
/// To avoid a memory leak the pointer must be converted back to an `Rc` using
/// [`Rc::from_raw_in`].
///
/// # Examples
///
/// ```
/// #![feature(allocator_api)]
/// use std::rc::Rc;
/// use std::alloc::System;
///
/// let x = Rc::new_in("hello".to_owned(), System);
/// let (ptr, alloc) = Rc::into_raw_with_allocator(x);
/// assert_eq!(unsafe { &*ptr }, "hello");
/// let x = unsafe { Rc::from_raw_in(ptr, alloc) };
/// assert_eq!(&*x, "hello");
/// ```
#[unstable(feature = "allocator_api", issue = "32838")]
pub fn into_raw_with_allocator(this: Self) -> (*const T, A) {
let this = mem::ManuallyDrop::new(this);
let ptr = Self::as_ptr(&this);
// Safety: `this` is ManuallyDrop so the allocator will not be double-dropped
let alloc = unsafe { ptr::read(Self::allocator(&this)) };
(ptr, alloc)
}

/// Provides a raw pointer to the data.
///
/// The counts are not affected in any way and the `Rc` is not consumed. The pointer is valid
Expand Down Expand Up @@ -1809,7 +1837,9 @@ impl<T: Clone, A: Allocator + Clone> Rc<T, A> {
// reference to the allocation.
unsafe { &mut this.ptr.as_mut().value }
}
}

impl<T: Clone, A: Allocator> Rc<T, A> {
/// If we have the only reference to `T` then unwrap it. Otherwise, clone `T` and return the
/// clone.
///
Expand Down Expand Up @@ -1845,7 +1875,7 @@ impl<T: Clone, A: Allocator + Clone> Rc<T, A> {
}
}

impl<A: Allocator + Clone> Rc<dyn Any, A> {
impl<A: Allocator> Rc<dyn Any, A> {
/// Attempt to downcast the `Rc<dyn Any>` to a concrete type.
///
/// # Examples
Expand All @@ -1868,12 +1898,8 @@ impl<A: Allocator + Clone> Rc<dyn Any, A> {
#[stable(feature = "rc_downcast", since = "1.29.0")]
pub fn downcast<T: Any>(self) -> Result<Rc<T, A>, Self> {
if (*self).is::<T>() {
unsafe {
let ptr = self.ptr.cast::<RcBox<T>>();
let alloc = self.alloc.clone();
forget(self);
Ok(Rc::from_inner_in(ptr, alloc))
}
let (ptr, alloc) = Rc::into_inner_with_allocator(self);
unsafe { Ok(Rc::from_inner_in(ptr.cast(), alloc)) }
} else {
Err(self)
}
Expand Down Expand Up @@ -1908,12 +1934,8 @@ impl<A: Allocator + Clone> Rc<dyn Any, A> {
#[inline]
#[unstable(feature = "downcast_unchecked", issue = "90850")]
pub unsafe fn downcast_unchecked<T: Any>(self) -> Rc<T, A> {
unsafe {
let ptr = self.ptr.cast::<RcBox<T>>();
let alloc = self.alloc.clone();
mem::forget(self);
Rc::from_inner_in(ptr, alloc)
}
let (ptr, alloc) = Rc::into_inner_with_allocator(self);
unsafe { Rc::from_inner_in(ptr.cast(), alloc) }
}
}

Expand Down Expand Up @@ -2661,12 +2683,13 @@ impl From<Rc<str>> for Rc<[u8]> {
}

#[stable(feature = "boxed_slice_try_from", since = "1.43.0")]
impl<T, const N: usize> TryFrom<Rc<[T]>> for Rc<[T; N]> {
type Error = Rc<[T]>;
impl<T, A: Allocator, const N: usize> TryFrom<Rc<[T], A>> for Rc<[T; N], A> {
type Error = Rc<[T], A>;

fn try_from(boxed_slice: Rc<[T]>) -> Result<Self, Self::Error> {
fn try_from(boxed_slice: Rc<[T], A>) -> Result<Self, Self::Error> {
if boxed_slice.len() == N {
Ok(unsafe { Rc::from_raw(Rc::into_raw(boxed_slice) as *mut [T; N]) })
let (ptr, alloc) = Rc::into_inner_with_allocator(boxed_slice);
Ok(unsafe { Rc::from_inner_in(ptr.cast(), alloc) })
} else {
Err(boxed_slice)
}
Expand Down Expand Up @@ -2923,6 +2946,13 @@ impl<T: ?Sized> Weak<T> {
}

impl<T: ?Sized, A: Allocator> Weak<T, A> {
/// Returns a reference to the underlying allocator.
#[inline]
#[unstable(feature = "allocator_api", issue = "32838")]
pub fn allocator(&self) -> &A {
&self.alloc
}

/// Returns a raw pointer to the object `T` pointed to by this `Weak<T>`.
///
/// The pointer is valid only if there are some strong references. The pointer may be dangling,
Expand Down Expand Up @@ -3000,39 +3030,42 @@ impl<T: ?Sized, A: Allocator> Weak<T, A> {
result
}

/// Consumes the `Weak<T>` and turns it into a raw pointer.
/// Consumes the `Weak<T>`, returning the wrapped pointer and allocator.
///
/// This converts the weak pointer into a raw pointer, while still preserving the ownership of
/// one weak reference (the weak count is not modified by this operation). It can be turned
/// back into the `Weak<T>` with [`from_raw`].
/// back into the `Weak<T>` with [`from_raw_in`].
///
/// The same restrictions of accessing the target of the pointer as with
/// [`as_ptr`] apply.
///
/// # Examples
///
/// ```
/// #![feature(allocator_api)]
/// use std::rc::{Rc, Weak};
/// use std::alloc::System;
///
/// let strong = Rc::new("hello".to_owned());
/// let strong = Rc::new_in("hello".to_owned(), System);
/// let weak = Rc::downgrade(&strong);
/// let raw = weak.into_raw();
/// let (raw, alloc) = weak.into_raw_with_allocator();
///
/// assert_eq!(1, Rc::weak_count(&strong));
/// assert_eq!("hello", unsafe { &*raw });
///
/// drop(unsafe { Weak::from_raw(raw) });
/// drop(unsafe { Weak::from_raw_in(raw, alloc) });
/// assert_eq!(0, Rc::weak_count(&strong));
/// ```
///
/// [`from_raw`]: Weak::from_raw
/// [`from_raw_in`]: Weak::from_raw_in
/// [`as_ptr`]: Weak::as_ptr
#[inline]
#[unstable(feature = "allocator_api", issue = "32838")]
pub fn into_raw_and_alloc(self) -> (*const T, A) {
let rc = mem::ManuallyDrop::new(self);
let result = rc.as_ptr();
let alloc = unsafe { ptr::read(&rc.alloc) };
pub fn into_raw_with_allocator(self) -> (*const T, A) {
let this = mem::ManuallyDrop::new(self);
let result = this.as_ptr();
// Safety: `this` is ManuallyDrop so the allocator will not be double-dropped
let alloc = unsafe { ptr::read(this.allocator()) };
(result, alloc)
}

Expand Down
Loading
Loading