Skip to content

Commit 70cc9c2

Browse files
committed
Implement RcUninit (rust-lang#112566)
RcUninit was discussed in rust-lang/libs-team#90 https://internals.rust-lang.org/t/an-alternative-to-rc-new-cyclic/22849/6 rust-lang#112566 RcUninit allows the user to construct cyclic data structures without using `Rc::new_cyclic`, which allows cyclic constructions across await points. It also allows you to create long linked lists without overflowing the stack. This is an alternative to `UniqueRc`. While `UniqueRc` does allow for cyclic data structures to be created, it must be done by mutating the UniqueRc. Mutation is prone to creating reference cycles. Construction-only assignment of fields, without any mutation to "set" the struct afterwards cannot generate reference cycles. It's also more cumbersome to work with. For instance, if we have objects A, B, and C, and we want these to connect as `A => B => C -> A` (`=>` being strong, `->` being weak), then we must do something along the following lines. let mut a_uniq = UniqueRc::new(A::new()); let a_weak = UniqueRc::downgrade(&a_uniq); let c = Rc::new(C::new(a_weak)); let b = Rc::new(B::new(c)); a_uniq.set_b(b); let a = a_uniq.into_rc(); To implement `A::set_b`, the field `A::b` must either be - `Option<Rc<B>>`: Requiring unwrap/clone for each access. - `MaybeUninit<Rc<B>>`: Requiring unsafe. - `Weak<B>`: Requiring upgrade for every access. The above also makes it easier to make mistakes in more complex programs where we don't have the full picture. It is not hard to change the above into `Rc<RefCell<A>>`, and then provide this pointer to `C`, which would cause a reference cycle to be created once `a.borrow_mut().set_b(b)` gets called. On the other hand RcUninit doesn't have this problem, since initialization is deferred. The equivalent would look like the following. let a_uninit = RcUninit::new(); let b_uninit = RcUninit::new(); let c_uninit = RcUninit::new(); let c = c_uninit.init(C::new(a_uninit.weak())); let b = b_uninit.init(B::new(c)); let a = a_uninit.init(b); This creates the structure (A => B => C -> A)
1 parent d7df5bd commit 70cc9c2

File tree

2 files changed

+127
-1
lines changed

2 files changed

+127
-1
lines changed

library/alloc/src/rc.rs

+103
Original file line numberDiff line numberDiff line change
@@ -4159,3 +4159,106 @@ impl<T: ?Sized, A: Allocator> Drop for UniqueRcUninit<T, A> {
41594159
}
41604160
}
41614161
}
4162+
4163+
/// An uninitialized Rc that allows deferred construction whilst exposing weak pointers before
4164+
/// being constructed.
4165+
///
4166+
/// Weak pointers will return `None` on `upgrade` as long as [RcUninit::init] has not been called.
4167+
#[unstable(feature = "unique_rc_arc", issue = "112566")]
4168+
#[cfg(not(no_global_oom_handling))]
4169+
pub struct RcUninit<
4170+
T,
4171+
#[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
4172+
> {
4173+
ptr: NonNull<RcInner<T>>,
4174+
weak: Weak<T, A>,
4175+
}
4176+
4177+
impl<T> RcUninit<T> {
4178+
/// Creates new RcUninit.
4179+
#[unstable(feature = "unique_rc_arc", issue = "112566")]
4180+
pub fn new() -> Self {
4181+
let ptr = unsafe {
4182+
Rc::allocate_for_layout(
4183+
Layout::new::<T>(),
4184+
|layout| Global.allocate(layout),
4185+
<*mut u8>::cast,
4186+
)
4187+
};
4188+
4189+
let ptr = NonNull::new(ptr).unwrap();
4190+
unsafe { (*ptr.as_ptr()).weak.set(2); };
4191+
4192+
Self {
4193+
ptr,
4194+
weak: Weak {
4195+
ptr,
4196+
alloc: Global,
4197+
},
4198+
}
4199+
}
4200+
}
4201+
4202+
impl<T, A: Allocator + Clone> RcUninit<T, A> {
4203+
/// Creates new RcUninit.
4204+
#[unstable(feature = "unique_rc_arc", issue = "112566")]
4205+
pub fn new_in(alloc: A) -> Self {
4206+
let ptr = unsafe {
4207+
Rc::allocate_for_layout(
4208+
Layout::new::<T>(),
4209+
|layout| alloc.allocate(layout),
4210+
<*mut u8>::cast,
4211+
)
4212+
};
4213+
4214+
let ptr = NonNull::new(ptr).unwrap();
4215+
unsafe { (*ptr.as_ptr()).weak.set(2); };
4216+
4217+
Self {
4218+
ptr,
4219+
weak: Weak {
4220+
ptr,
4221+
alloc,
4222+
},
4223+
}
4224+
}
4225+
4226+
/// Get a weak reference.
4227+
#[unstable(feature = "unique_rc_arc", issue = "112566")]
4228+
pub fn weak(&self) -> &Weak<T, A> {
4229+
&self.weak
4230+
}
4231+
4232+
/// Write a value and return Rc.
4233+
#[unstable(feature = "unique_rc_arc", issue = "112566")]
4234+
pub fn init(self, value: T) -> Rc<T, A> {
4235+
unsafe {
4236+
let ptr = self.weak.ptr.as_ptr();
4237+
ptr::write(&raw mut (*ptr).value, value);
4238+
}
4239+
4240+
let ptr = self.ptr;
4241+
let alloc = self.weak.alloc.clone();
4242+
mem::forget(self);
4243+
4244+
Rc {
4245+
ptr,
4246+
phantom: PhantomData,
4247+
alloc,
4248+
}
4249+
}
4250+
}
4251+
4252+
#[unstable(feature = "unique_rc_arc", issue = "112566")]
4253+
impl<T> fmt::Debug for RcUninit<T> {
4254+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4255+
write!(f, "(RcUninit)")
4256+
}
4257+
}
4258+
4259+
#[unstable(feature = "unique_rc_arc", issue = "112566")]
4260+
impl<T, A: Allocator> Drop for RcUninit<T, A> {
4261+
fn drop(&mut self) {
4262+
unsafe { Rc::from_inner(self.ptr) };
4263+
}
4264+
}

library/alloctests/tests/rc.rs

+24-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ use std::any::Any;
22
use std::cell::{Cell, RefCell};
33
use std::iter::TrustedLen;
44
use std::mem;
5-
use std::rc::{Rc, UniqueRc, Weak};
5+
use std::rc::{Rc, RcUninit, UniqueRc, Weak};
66

77
#[test]
88
fn uninhabited() {
@@ -922,3 +922,26 @@ fn test_unique_rc_unsizing_coercion() {
922922
let rc: Rc<[u8]> = UniqueRc::into_rc(rc);
923923
assert_eq!(*rc, [123, 0, 0]);
924924
}
925+
926+
#[test]
927+
fn test_rc_uninit() {
928+
RcUninit::<()>::new();
929+
RcUninit::<i32>::new();
930+
RcUninit::<String>::new();
931+
}
932+
933+
#[test]
934+
fn test_rc_uninit_init() {
935+
let x: RcUninit<i32> = RcUninit::new();
936+
assert_eq!(Weak::strong_count(x.weak()), 1);
937+
assert_eq!(Weak::weak_count(x.weak()), 1);
938+
let weak = x.weak().clone();
939+
940+
let rc = x.init(123);
941+
assert_eq!(Rc::strong_count(&rc), 1);
942+
assert_eq!(Rc::weak_count(&rc), 2);
943+
944+
assert_eq!(*rc, 123);
945+
assert_eq!(weak.upgrade().map(|x| *x), Some(123));
946+
assert!(Rc::ptr_eq(&weak.upgrade().unwrap(), &rc));
947+
}

0 commit comments

Comments
 (0)