Skip to content

Commit 5142171

Browse files
committed
Implement UniqueArc
1 parent ee612c4 commit 5142171

File tree

3 files changed

+187
-2
lines changed

3 files changed

+187
-2
lines changed

library/alloc/src/sync.rs

+181-1
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ use core::intrinsics::abort;
1818
use core::iter;
1919
use core::marker::{PhantomData, Unsize};
2020
use core::mem::{self, ManuallyDrop, align_of_val_raw};
21-
use core::ops::{CoerceUnsized, Deref, DerefPure, DispatchFromDyn, LegacyReceiver};
21+
use core::ops::{CoerceUnsized, Deref, DerefMut, DerefPure, DispatchFromDyn, LegacyReceiver};
2222
use core::panic::{RefUnwindSafe, UnwindSafe};
2323
use core::pin::{Pin, PinCoerceUnsized};
2424
use core::ptr::{self, NonNull};
@@ -4012,3 +4012,183 @@ impl<T: core::error::Error + ?Sized> core::error::Error for Arc<T> {
40124012
core::error::Error::provide(&**self, req);
40134013
}
40144014
}
4015+
4016+
/// A uniquely owned [`Arc`].
4017+
///
4018+
/// This represents an `Arc` that is known to be uniquely owned -- that is, have exactly one strong
4019+
/// reference. Multiple weak pointers can be created, but attempts to upgrade those to strong
4020+
/// references will fail unless the `UniqueArc` they point to has been converted into a regular `Arc`.
4021+
///
4022+
/// Because they are uniquely owned, the contents of a `UniqueArc` can be freely mutated. A common
4023+
/// use case is to have an object be mutable during its initialization phase but then have it become
4024+
/// immutable and converted to a normal `Arc`.
4025+
///
4026+
/// This can be used as a flexible way to create cyclic data structures, as in the example below.
4027+
///
4028+
/// ```
4029+
/// #![feature(unique_rc_arc)]
4030+
/// use std::sync::{Arc, Weak, UniqueArc};
4031+
///
4032+
/// struct Gadget {
4033+
/// #[allow(dead_code)]
4034+
/// me: Weak<Gadget>,
4035+
/// }
4036+
///
4037+
/// fn create_gadget() -> Option<Arc<Gadget>> {
4038+
/// let mut rc = UniqueArc::new(Gadget {
4039+
/// me: Weak::new(),
4040+
/// });
4041+
/// rc.me = UniqueArc::downgrade(&rc);
4042+
/// Some(UniqueArc::into_arc(rc))
4043+
/// }
4044+
///
4045+
/// create_gadget().unwrap();
4046+
/// ```
4047+
///
4048+
/// An advantage of using `UniqueArc` over [`Arc::new_cyclic`] to build cyclic data structures is that
4049+
/// [`Arc::new_cyclic`]'s `data_fn` parameter cannot be async or return a [`Result`]. As shown in the
4050+
/// previous example, `UniqueArc` allows for more flexibility in the construction of cyclic data,
4051+
/// including fallible or async constructors.
4052+
#[unstable(feature = "unique_rc_arc", issue = "112566")]
4053+
#[derive(Debug)]
4054+
pub struct UniqueArc<
4055+
T: ?Sized,
4056+
#[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
4057+
> {
4058+
ptr: NonNull<ArcInner<T>>,
4059+
phantom: PhantomData<ArcInner<T>>,
4060+
alloc: A,
4061+
}
4062+
4063+
#[unstable(feature = "unique_rc_arc", issue = "112566")]
4064+
impl<T: ?Sized + Unsize<U>, U: ?Sized, A: Allocator> CoerceUnsized<UniqueArc<U, A>>
4065+
for UniqueArc<T, A>
4066+
{
4067+
}
4068+
4069+
// Depends on A = Global
4070+
impl<T> UniqueArc<T> {
4071+
/// Creates a new `UniqueArc`.
4072+
///
4073+
/// Weak references to this `UniqueArc` can be created with [`UniqueArc::downgrade`]. Upgrading
4074+
/// these weak references will fail before the `UniqueArc` has been converted into an [`Arc`].
4075+
/// After converting the `UniqueArc` into an [`Arc`], any weak references created beforehand will
4076+
/// point to the new [`Arc`].
4077+
#[cfg(not(no_global_oom_handling))]
4078+
#[unstable(feature = "unique_rc_arc", issue = "112566")]
4079+
pub fn new(value: T) -> Self {
4080+
Self::new_in(value, Global)
4081+
}
4082+
}
4083+
4084+
impl<T, A: Allocator> UniqueArc<T, A> {
4085+
/// Creates a new `UniqueArc` in the provided allocator.
4086+
///
4087+
/// Weak references to this `UniqueArc` can be created with [`UniqueArc::downgrade`]. Upgrading
4088+
/// these weak references will fail before the `UniqueArc` has been converted into an [`Arc`].
4089+
/// After converting the `UniqueArc` into an [`Arc`], any weak references created beforehand will
4090+
/// point to the new [`Arc`].
4091+
#[cfg(not(no_global_oom_handling))]
4092+
#[unstable(feature = "unique_rc_arc", issue = "112566")]
4093+
pub fn new_in(data: T, alloc: A) -> Self {
4094+
let (ptr, alloc) = Box::into_unique(Box::new_in(
4095+
ArcInner {
4096+
strong: atomic::AtomicUsize::new(0),
4097+
// keep one weak reference so if all the weak pointers that are created are dropped
4098+
// the UniqueArc still stays valid.
4099+
weak: atomic::AtomicUsize::new(1),
4100+
data,
4101+
},
4102+
alloc,
4103+
));
4104+
Self { ptr: ptr.into(), phantom: PhantomData, alloc }
4105+
}
4106+
}
4107+
4108+
impl<T: ?Sized, A: Allocator> UniqueArc<T, A> {
4109+
/// Converts the `UniqueArc` into a regular [`Arc`].
4110+
///
4111+
/// This consumes the `UniqueArc` and returns a regular [`Arc`] that contains the `value` that
4112+
/// is passed to `into_arc`.
4113+
///
4114+
/// Any weak references created before this method is called can now be upgraded to strong
4115+
/// references.
4116+
#[unstable(feature = "unique_rc_arc", issue = "112566")]
4117+
pub fn into_arc(this: Self) -> Arc<T, A> {
4118+
let this = ManuallyDrop::new(this);
4119+
4120+
// Move the allocator out.
4121+
// SAFETY: `this.alloc` will not be accessed again, nor dropped because it is in
4122+
// a `ManuallyDrop`.
4123+
let alloc: A = unsafe { ptr::read(&this.alloc) };
4124+
4125+
// SAFETY: This pointer was allocated at creation time so we know it is valid.
4126+
unsafe {
4127+
// Convert our weak reference into a strong reference
4128+
(*this.ptr.as_ptr()).strong.store(1, Release);
4129+
Arc::from_inner_in(this.ptr, alloc)
4130+
}
4131+
}
4132+
}
4133+
4134+
impl<T: ?Sized, A: Allocator + Clone> UniqueArc<T, A> {
4135+
/// Creates a new weak reference to the `UniqueArc`.
4136+
///
4137+
/// Attempting to upgrade this weak reference will fail before the `UniqueArc` has been converted
4138+
/// to a [`Arc`] using [`UniqueArc::into_arc`].
4139+
#[unstable(feature = "unique_rc_arc", issue = "112566")]
4140+
pub fn downgrade(this: &Self) -> Weak<T, A> {
4141+
// Using a relaxed ordering is alright here, as knowledge of the
4142+
// original reference prevents other threads from erroneously deleting
4143+
// the object or converting the object to a normal `Arc<T, A>`.
4144+
//
4145+
// Note that we don't need to test if the weak counter is locked because there
4146+
// are no such operations like `Arc::get_mut` or `Arc::make_mut` that will lock
4147+
// the weak counter.
4148+
//
4149+
// SAFETY: This pointer was allocated at creation time so we know it is valid.
4150+
let old_size = unsafe { (*this.ptr.as_ptr()).weak.fetch_add(1, Relaxed) };
4151+
4152+
// See comments in Arc::clone() for why we do this (for mem::forget).
4153+
if old_size > MAX_REFCOUNT {
4154+
abort();
4155+
}
4156+
4157+
Weak { ptr: this.ptr, alloc: this.alloc.clone() }
4158+
}
4159+
}
4160+
4161+
#[unstable(feature = "unique_rc_arc", issue = "112566")]
4162+
impl<T: ?Sized, A: Allocator> Deref for UniqueArc<T, A> {
4163+
type Target = T;
4164+
4165+
fn deref(&self) -> &T {
4166+
// SAFETY: This pointer was allocated at creation time so we know it is valid.
4167+
unsafe { &self.ptr.as_ref().data }
4168+
}
4169+
}
4170+
4171+
// #[unstable(feature = "unique_rc_arc", issue = "112566")]
4172+
#[unstable(feature = "pin_coerce_unsized_trait", issue = "123430")]
4173+
unsafe impl<T: ?Sized> PinCoerceUnsized for UniqueArc<T> {}
4174+
4175+
#[unstable(feature = "unique_rc_arc", issue = "112566")]
4176+
impl<T: ?Sized, A: Allocator> DerefMut for UniqueArc<T, A> {
4177+
fn deref_mut(&mut self) -> &mut T {
4178+
// SAFETY: This pointer was allocated at creation time so we know it is valid. We know we
4179+
// have unique ownership and therefore it's safe to make a mutable reference because
4180+
// `UniqueArc` owns the only strong reference to itself.
4181+
unsafe { &mut (*self.ptr.as_ptr()).data }
4182+
}
4183+
}
4184+
4185+
#[unstable(feature = "unique_rc_arc", issue = "112566")]
4186+
unsafe impl<#[may_dangle] T: ?Sized, A: Allocator> Drop for UniqueArc<T, A> {
4187+
fn drop(&mut self) {
4188+
// See `Arc::drop_slow` which drops an `Arc` with a strong count of 0.
4189+
// SAFETY: This pointer was allocated at creation time so we know it is valid.
4190+
let _weak = Weak { ptr: self.ptr, alloc: &self.alloc };
4191+
4192+
unsafe { ptr::drop_in_place(&mut (*self.ptr.as_ptr()).data) };
4193+
}
4194+
}

library/alloc/tests/arc.rs

+4-1
Original file line numberDiff line numberDiff line change
@@ -266,7 +266,7 @@ fn make_mut_unsized() {
266266

267267
#[allow(unused)]
268268
mod pin_coerce_unsized {
269-
use alloc::sync::Arc;
269+
use alloc::sync::{Arc, UniqueArc};
270270
use core::pin::Pin;
271271

272272
pub trait MyTrait {}
@@ -276,4 +276,7 @@ mod pin_coerce_unsized {
276276
pub fn pin_arc(arg: Pin<Arc<String>>) -> Pin<Arc<dyn MyTrait>> {
277277
arg
278278
}
279+
pub fn pin_unique_arc(arg: Pin<UniqueArc<String>>) -> Pin<UniqueArc<dyn MyTrait>> {
280+
arg
281+
}
279282
}

library/std/src/sync/mod.rs

+2
Original file line numberDiff line numberDiff line change
@@ -172,6 +172,8 @@ pub use core::sync::Exclusive;
172172
#[stable(feature = "rust1", since = "1.0.0")]
173173
pub use core::sync::atomic;
174174

175+
#[unstable(feature = "unique_rc_arc", issue = "112566")]
176+
pub use alloc_crate::sync::UniqueArc;
175177
#[stable(feature = "rust1", since = "1.0.0")]
176178
pub use alloc_crate::sync::{Arc, Weak};
177179

0 commit comments

Comments
 (0)