On Fri, May 29, 2026 at 01:30:42PM -0400, Lyude Paul wrote:
> SetOnce is nice, but it does have one problem - you can't use it with
> fallible initializers. While we will be adding support for doing that with
> SetOnce, this leads into another problem: There's no way for racing callers
> to actually block on the initialization of SetOnce, which makes it a
> difficult type to use safely for situations where we want to initialize
> data fallibly once, and then provide access to it to multiple users at once
> until drop.
> 
> So to solve this, introduce a new type: LazyInit. LazyInit is like SetOnce
> with a couple of important differences:
> 
> * It can't be used in const context
> * It can handle in-place fallible initializers.
> * It uses a Mutex for synchronization instead of an atomic, allowing
>   callers to block on initialization.
> * It requires its contents already be Send + Sync, since the Mutex protects
>   initializing data and not the data itself.
> 
> Signed-off-by: Lyude Paul <[email protected]>

> +    /// Retrieve the contents of `inner.data` and extend their lifetime.
> +    ///
> +    /// # Safety
> +    ///
> +    /// The caller guarantees that `self.inner.data` has been previously 
> initialized.
> +    #[inline(always)]
> +    unsafe fn data<'a>(&'a self, inner: &MutexGuard<'_, Inner<T>>) -> &'a T {
> +        // SAFETY:
> +        // - Our safety contract guarantees `inner.data` is initialized.
> +        // - `T` is `Send` + `Sync`, and thus does not need the `Mutex` for 
> synchronization, making
> +        //   it safe to hold onto outside of the lock.
> +        // - We're guaranteed via `Inner`'s type invariants that so long as 
> immutable references to
> +        //   self exist, `data` cannot be uninitialized - ensuring it lives 
> throughout the lifetime
> +        //   of A.
> +        // - We're guaranteed the container of `T` will not be written to 
> via `Inner`s type
> +        //   invariants until `Drop`, ensuring it remains populated for the 
> lifetime of 'a.
> +        unsafe { mem::transmute::<&_, &'a _>(inner.data.assume_init_ref()) }

I'm not a big fan of using these kinds of tricks to access the contents
of a mutex after unlocking it. Could we instead use a struct like this:

struct LazyInit<T> {
    data: UnsafeCell<MaybeUninit<T>>,
    set: AtomicBool,
    lock: Mutex<()>,
}

or even:

struct LazyInit<T> {
    data: SetOnce<T>,
    lock: Mutex<()>,
}

I think this logic will be simpler for everyone.

By the way, another option is to use a similar strategy to
https://lore.kernel.org/rust-for-linux/[email protected]/
where you just use SetOnce and protect calls to `populate` by another
mutex in the structure. Then you don't need a separate LazyInit.

Alice

Reply via email to