Implement RcUninit (#112566) by kstrafe · Pull Request #140640 · rust-lang/rust (original) (raw)

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

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)

Tracking Issue

#112566

RcUninit was discussed in
rust-lang/libs-team#90
https://internals.rust-lang.org/t/an-alternative-to-rc-new-cyclic/22849/6
#112566