From nobody Mon Jun 8 11:01:52 2026 Received: from us-smtp-delivery-124.mimecast.com (us-smtp-delivery-124.mimecast.com [170.10.129.124]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id CE82D38D41F for ; Fri, 29 May 2026 17:32:08 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=170.10.129.124 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1780075930; cv=none; b=ZmnJwV2r1dwsOlKsBUADSkkAXYKe8kaSFKwGO4T3kmf6M+0H4N9DBdJ/UbbxnNm7Z8eT8cKvPjsOK11j5CrwOgnHEO4fR7x8InJSqSTg6QAoYj4j/FtY+ZP7fL/4oPZ7vXjPz8LVID8AGBlHRgHhwtQhAJdCPadiuGReomHgWqA= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1780075930; c=relaxed/simple; bh=MrTkfmDf83gaBbKz1p+h1nqg8TL6yUkib+CRXlnBFDU=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version:Content-Type; b=ktk/5trEorjRUa2NOe1+A008P2Ky1GPVW0p8k3oOc5I34eM+OaFPGJYKwrSVQVOt1xpo66GZ4MhXhEIySbAYhlBej87SYhWGVTjRLmBzio5ESsPmvF0EIRhDQg9k8tHXhPBtEnOLck6roq/SqrfYJiq+t55gxCSDYK04CZDaidw= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=quarantine dis=none) header.from=redhat.com; spf=pass smtp.mailfrom=redhat.com; dkim=pass (1024-bit key) header.d=redhat.com header.i=@redhat.com header.b=bG6PKx4g; arc=none smtp.client-ip=170.10.129.124 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=quarantine dis=none) header.from=redhat.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=redhat.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (1024-bit key) header.d=redhat.com header.i=@redhat.com header.b="bG6PKx4g" DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1780075927; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version:content-type:content-type: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references; bh=CTXkVWhfiCkPPMFCSefkBsAtfCVesv2uIIO2EqJJ/8Y=; b=bG6PKx4g0RFXi6Ewe6i8ch1FpzYuMzt8oi1kLG6zio4f0W68s7p6ba2i/lwyAKVm9GIL+D tqBor+9bkq1I9BwcaeP/bNq4F0StSXW+8SGGOK1IXiPRbUMV2m4fgJyvT0tMzxtiew+Ixk MOK+c8hTiva9HQat5ysAwobK/zHPJA8= Received: from mx-prod-mc-05.mail-002.prod.us-west-2.aws.redhat.com (ec2-54-186-198-63.us-west-2.compute.amazonaws.com [54.186.198.63]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.3, cipher=TLS_AES_256_GCM_SHA384) id us-mta-171-E7vl8DQ1NBWSv445wnwexg-1; Fri, 29 May 2026 13:32:06 -0400 X-MC-Unique: E7vl8DQ1NBWSv445wnwexg-1 X-Mimecast-MFC-AGG-ID: E7vl8DQ1NBWSv445wnwexg_1780075922 Received: from mx-prod-int-01.mail-002.prod.us-west-2.aws.redhat.com (mx-prod-int-01.mail-002.prod.us-west-2.aws.redhat.com [10.30.177.4]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (2048 bits) server-digest SHA256) (No client certificate requested) by mx-prod-mc-05.mail-002.prod.us-west-2.aws.redhat.com (Postfix) with ESMTPS id 2F1791955F44; Fri, 29 May 2026 17:32:02 +0000 (UTC) Received: from GoldenWind.redhat.com (unknown [10.22.89.101]) by mx-prod-int-01.mail-002.prod.us-west-2.aws.redhat.com (Postfix) with ESMTP id D395A30001BB; Fri, 29 May 2026 17:31:59 +0000 (UTC) From: Lyude Paul To: dri-devel@lists.freedesktop.org, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org Cc: "Gary Guo" , "Ingo Molnar" , "Miguel Ojeda" , "Alice Ryhl" , "Tamir Duberstein" , "Boqun Feng" , "Peter Zijlstra" , "Benno Lossin" , "Will Deacon" , "Lyude Paul" Subject: [PATCH v2 1/2] rust: sync: lock: Add Lock::get_mut_pinned() Date: Fri, 29 May 2026 13:30:41 -0400 Message-ID: <20260529173137.303717-2-lyude@redhat.com> In-Reply-To: <20260529173137.303717-1-lyude@redhat.com> References: <20260529173137.303717-1-lyude@redhat.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable X-Scanned-By: MIMEDefang 3.4.1 on 10.30.177.4 These two functions are inspired by the Rust stdlib equivalent: https://doc.rust-lang.org/std/sync/struct.Mutex.html#method.get_mut() The idea here is very simple - if the user has access to a Pin<&mut Mutex<=E2=80=A6>>, we can guarantee that no one else can look at the data p= rotected by the lock. Thus in such situations, locking the mutex isn't necessary to access its contents. This can be useful in situations like `Drop` implementations, where we may want to access the contents of a Mutex within a struct before dropping it. So to do this, we add `get_mut_pinned()` to `Lock` - which provides a function to access the inner contents of a Mutex provided a Pin<&mut =E2=80= =A6>. Signed-off-by: Lyude Paul Reviewed-by: Alice Ryhl --- rust/kernel/sync/lock.rs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/rust/kernel/sync/lock.rs b/rust/kernel/sync/lock.rs index 10b6b5e9b024f..5ca36baed34f5 100644 --- a/rust/kernel/sync/lock.rs +++ b/rust/kernel/sync/lock.rs @@ -190,6 +190,17 @@ pub fn try_lock(&self) -> Option> { // that `init` was called. unsafe { B::try_lock(self.state.get()).map(|state| Guard::new(self= , state)) } } + + /// Returns a pinned mutable reference to the underlying data. + /// + /// Because this borrows the lock mutably, no actual locking needs to = take place - as the + /// mutable borrow statically guarantees no new locks can be acquired = while this reference + /// exists. + #[inline(always)] + pub fn get_mut_pinned(self: Pin<&mut Self>) -> Pin<&mut T> { + // SAFETY: We return a pinned T, ensuring we don't move T. + unsafe { self.map_unchecked_mut(|data| data.data.get_mut()) } + } } =20 /// A lock guard. --=20 2.54.0 From nobody Mon Jun 8 11:01:52 2026 Received: from us-smtp-delivery-124.mimecast.com (us-smtp-delivery-124.mimecast.com [170.10.129.124]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 0581438F626 for ; Fri, 29 May 2026 17:32:15 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=170.10.129.124 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1780075937; cv=none; b=ju9mUBnzfdVRzQxLIaVkOPEN6Rax8EbLsgBeQKlOxOW9kitw5AEOAaWR+crZrKqYEGBJuM3LlPqK/zh1O2fbZv8ViulZzAdOIRqcBYzd9fKY9U0DzPkTYxnfpTbV4jlJJPiPieeZdI/CEmwp5a641/EZ9adyvfqmc8hTcxVD+S8= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1780075937; c=relaxed/simple; bh=zPn6nqAu1xl8TVlRNqGn5m/9MbYXv0GxCOMzInCWhv4=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=sHLFmRKd2HPtGMFrhXoKyyyjIw0iXuYhurZHeNSbiEymaNLR2qmgwbTS0fakwxRoObBROGerOvHQNEo2D0Gj3SyhGSoRGBa+o/ZBC9C1zURQwt3EX2OpdPgr7qNHLUPJSj+8LKE6eRkYOOuY5gevd9169LBioZ0E64HYuk0dnQ4= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=quarantine dis=none) header.from=redhat.com; spf=pass smtp.mailfrom=redhat.com; dkim=pass (1024-bit key) header.d=redhat.com header.i=@redhat.com header.b=g9Ef67SJ; arc=none smtp.client-ip=170.10.129.124 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=quarantine dis=none) header.from=redhat.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=redhat.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (1024-bit key) header.d=redhat.com header.i=@redhat.com header.b="g9Ef67SJ" DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1780075935; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references; bh=0OrO3a42S41lJJNYXb6XfMiTxjoSVK/EuCVR7kSM8TA=; b=g9Ef67SJ2dwlCu1XlCK+DEH2Hhmb5JyeF4im9RPPZHRYIvcDAxwqSWLw7Mh7oYysaGTitr EXdEJF7Bam88OMFYZgZHcLdD+P3Y7v0wsS3u96Y0Omaf42M8cj6gO9lpWgvrdYmkB4QPoo NdTlY1ECmxfFBBcgv+3O1Kz49TXmJJw= Received: from mx-prod-mc-08.mail-002.prod.us-west-2.aws.redhat.com (ec2-35-165-154-97.us-west-2.compute.amazonaws.com [35.165.154.97]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.3, cipher=TLS_AES_256_GCM_SHA384) id us-mta-57-sMu1eDT_NbGDOylbKIWmPQ-1; Fri, 29 May 2026 13:32:09 -0400 X-MC-Unique: sMu1eDT_NbGDOylbKIWmPQ-1 X-Mimecast-MFC-AGG-ID: sMu1eDT_NbGDOylbKIWmPQ_1780075927 Received: from mx-prod-int-01.mail-002.prod.us-west-2.aws.redhat.com (mx-prod-int-01.mail-002.prod.us-west-2.aws.redhat.com [10.30.177.4]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (2048 bits) server-digest SHA256) (No client certificate requested) by mx-prod-mc-08.mail-002.prod.us-west-2.aws.redhat.com (Postfix) with ESMTPS id 83104180058F; Fri, 29 May 2026 17:32:07 +0000 (UTC) Received: from GoldenWind.redhat.com (unknown [10.22.89.101]) by mx-prod-int-01.mail-002.prod.us-west-2.aws.redhat.com (Postfix) with ESMTP id 8D6373002D2D; Fri, 29 May 2026 17:32:05 +0000 (UTC) From: Lyude Paul To: dri-devel@lists.freedesktop.org, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org Cc: "Gary Guo" , "Ingo Molnar" , "Miguel Ojeda" , "Alice Ryhl" , "Tamir Duberstein" , "Boqun Feng" , "Peter Zijlstra" , "Viresh Kumar" , "Benno Lossin" , "Will Deacon" , "Lyude Paul" Subject: [PATCH v2 2/2] rust: sync: Introduce LazyInit Date: Fri, 29 May 2026 13:30:42 -0400 Message-ID: <20260529173137.303717-3-lyude@redhat.com> In-Reply-To: <20260529173137.303717-1-lyude@redhat.com> References: <20260529173137.303717-1-lyude@redhat.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable X-Scanned-By: MIMEDefang 3.4.1 on 10.30.177.4 Content-Type: text/plain; charset="utf-8" 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 --- V2: * Get rid of references to populate() in safety comments * Drop unused import in kunit tests * s/r @ _/r/ in unit tests * Fix many safety comments, a few of them did not get updated by me by mistake before submitting the first version of this series. * Pin-project harder, since the last time I looked at this I've got a better understanding of pin projection - so let's take advantage of that to cut down on some unsafe blocks. * Improve root doc comment a little bit * Improve INVARIANT comments rust/kernel/sync.rs | 2 + rust/kernel/sync/lazy_init.rs | 352 ++++++++++++++++++++++++++++++++++ 2 files changed, 354 insertions(+) create mode 100644 rust/kernel/sync/lazy_init.rs diff --git a/rust/kernel/sync.rs b/rust/kernel/sync.rs index 993dbf2caa0e3..d18c26c56c4d2 100644 --- a/rust/kernel/sync.rs +++ b/rust/kernel/sync.rs @@ -15,6 +15,7 @@ pub mod barrier; pub mod completion; mod condvar; +mod lazy_init; pub mod lock; mod locked_by; pub mod poll; @@ -25,6 +26,7 @@ pub use arc::{Arc, ArcBorrow, UniqueArc}; pub use completion::Completion; pub use condvar::{new_condvar, CondVar, CondVarTimeoutResult}; +pub use lazy_init::*; pub use lock::global::{global_lock, GlobalGuard, GlobalLock, GlobalLockBac= kend, GlobalLockedBy}; pub use lock::mutex::{new_mutex, Mutex, MutexGuard}; pub use lock::spinlock::{new_spinlock, SpinLock, SpinLockGuard}; diff --git a/rust/kernel/sync/lazy_init.rs b/rust/kernel/sync/lazy_init.rs new file mode 100644 index 0000000000000..3f3126f4b153b --- /dev/null +++ b/rust/kernel/sync/lazy_init.rs @@ -0,0 +1,352 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Thread-safe lazy-initialization containers for use with [`Init`] and [= `PinInit`]. +use crate::{ + prelude::*, + sync::{ + LockClassKey, + Mutex, + MutexGuard, // + }, +}; +use core::{ + mem::{ + self, + MaybeUninit, // + }, + ptr, +}; +use pin_init::{ + pin_init, + PinInit, // +}; + +/// # Invariants +/// +/// - `data` is guaranteed to be initialized if `is_init` is `true`. +/// - There is only one location where `data` is written to through an imm= utable shared reference, +/// `LazyInit::init()`. All other places where `data` is written to thro= ugh this container require +/// exclusive mutable references. This means `data` cannot be deinitiali= zed so long as shared +/// references to it exist. +#[pin_data(PinnedDrop)] +struct Inner { + #[pin] + data: MaybeUninit, + is_init: bool, +} + +#[pinned_drop] +impl PinnedDrop for Inner { + fn drop(self: Pin<&mut Self>) { + if self.is_init { + let project =3D self.project(); + + // SAFETY: + // - We drop this in place, ensuring we don't violate pinning = invariants. + // - `is_init` is true, ensuring `data` is initialized via our= type invariants. + unsafe { project.data.get_unchecked_mut().assume_init_drop() }; + + *project.is_init =3D false; + } + } +} + +/// Errors that can occur during [`LazyInit::new`]. +#[derive(Debug)] +pub enum LazyInitError<'a, T: Send + Sync, E =3D Error> { + /// The [`LazyInit`] has already been initialized. + /// + /// `self.0` contains a reference to the previously initialized value. + AlreadyInit(&'a T), + /// An error occurred during initialization. + DuringInit(E), +} + +impl<'a, T: Send + Sync, E> From for LazyInitError<'a, T, E> { + fn from(value: E) -> Self { + Self::DuringInit(value) + } +} + +/// Creates a [`LazyInit`] initialiser with the given name and newly-creat= ed lock class. +/// +/// It uses the name if one is given, otherwise it generates one based on = the file name and line +/// number. +#[macro_export] +macro_rules! new_lazy_init { + ($( $name:literal )?) =3D> { + $crate::sync::LazyInit::new($crate::optional_name!($($name)?), $cr= ate::static_lock_class!()) + }; +} +pub use new_lazy_init; + +/// A thread-safe container that allows thread-safe single-time initializa= tion of its contents, +/// which can then have shared references taken to its contents. It is sim= ilar to [`SetOnce`] except +/// that it uses a [`Mutex`], it can be populated using fallible [`PinInit= `] initializers, and +/// multiple callers attempting to initialize at the same time will block = until the conetents of the +/// [`LazyInit`] is finished initializing. +/// +/// This type cannot be used in `const` contexts, however, unlike [`SetOnc= e`] users of this type are +/// able to block if another thread is busy populating the [`SetOnce`]. Th= is also allows the use of +/// fallible initializers for population. +/// +/// This type internally uses a [`Mutex`] for synchronizing creation of `T= `, but allows access to +/// `T` outside of lock post-init. This means that only the initialization= of the value is protected +/// by the lock, and thus `T` must provide it's own synchronization by imp= lementing `Send` + `Sync`. +/// +/// # Examples +/// +/// ``` +/// use kernel::sync::{ +/// LazyInit, +/// LazyInitError, +/// Arc, +/// new_lazy_init, // +/// }; +/// +/// struct Inner { +/// a: u8, +/// } +/// +/// #[pin_data] +/// struct Example { +/// #[pin] +/// lazy: LazyInit>, +/// } +/// +/// impl Example { +/// fn new() -> impl PinInit { +/// pin_init!(Self { +/// lazy <- new_lazy_init!(), +/// }) +/// } +/// } +/// +/// // Allocate a boxed `Example`. +/// let e =3D KBox::pin_init(Example::new(), GFP_KERNEL)?; +/// +/// assert!(e.lazy.init(Arc::init(init!(Inner { a: 42 }), GFP_KERNEL)).is_= ok()); +/// +/// // `as_ref()` can be used to get a reference to the contents of a `Laz= yInit` if its initialized. +/// assert_eq!(e.lazy.as_ref().unwrap().a, 42); +/// +/// // If `LazyInit::init()` fails due to the `LazyInit` already being ini= tialized, a reference to +/// // the initialized data can still be retrieved from the error. +/// match e.lazy.init(Arc::init(init!(Inner { a: 54 }), GFP_KERNEL)) { +/// Err(LazyInitError::AlreadyInit(ret)) =3D> assert_eq!(ret.a, 42), +/// _ =3D> unreachable!(), +/// } +/// # Ok::<(), Error>(()) +/// ``` +/// +/// [`SetOnce`]: super::SetOnce +#[pin_data] +pub struct LazyInit { + #[pin] + inner: Mutex>, +} + +impl LazyInit { + /// Create a new initializer for an empty [`LazyInit`]. + pub fn new(name: &'static CStr, key: Pin<&'static LockClassKey>) -> im= pl PinInit { + pin_init!(Self { + inner <- Mutex::new( + pin_init!(Inner { + data <- MaybeUninit::uninit(), + is_init: false, + }), + name, + key + ) + }) + } + + /// Retrieve the contents of `inner.data` and extend their lifetime. + /// + /// # Safety + /// + /// The caller guarantees that `self.inner.data` has been previously i= nitialized. + #[inline(always)] + unsafe fn data<'a>(&'a self, inner: &MutexGuard<'_, Inner>) -> &'a = T { + // SAFETY: + // - Our safety contract guarantees `inner.data` is initialized. + // - `T` is `Send` + `Sync`, and thus does not need the `Mutex` fo= r synchronization, making + // it safe to hold onto outside of the lock. + // - We're guaranteed via `Inner`'s type invariants that so long a= s immutable references to + // self exist, `data` cannot be uninitialized - ensuring it live= s 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 th= e lifetime of 'a. + unsafe { mem::transmute::<&_, &'a _>(inner.data.assume_init_ref())= } + } + + /// Attempt to init the contents of [`LazyInit`] and return a referenc= e to its contents. + /// + /// If the contents of the [`LazyInit`] were already initialized, they= will not be + /// re-initialized. + /// + /// Returns: + /// + /// - `Ok(&T)` if the container was initialized successfully, or if it= was already initialized + /// by another user. + /// - [`Err(LazyInitError::AlreadyInit)`](LazyInitError::AlreadyInit) = if the container was + /// already initialized. This error contains a reference to the cont= ents of the [`LazyInit`]. + /// - [`Err(LazyInitError::DuringInit)`](LazyInitError::DuringInit) if= an error was encountered + /// while trying to initialize this [`LazyInit`]. + pub fn init<'a, E>( + &'a self, + init: impl PinInit, + ) -> Result<&'a T, LazyInitError<'a, T, E>> { + let mut inner =3D self.inner.lock(); + let do_init =3D !inner.is_init; + + if do_init { + let inner =3D inner.as_mut().project(); + + // INVARIANT: This is the only place we can write to `data` th= rough an immutable shared + // reference, and because we check `do_init` before writing - = it can only be written to + // once. + // + // SAFETY: + // - We drop `inner.data` in place, ensuring we don't violate = pinning invariants. + // - Via Inner's invariants, since we checked `is_init` we're = guaranteed `data` is + // uninitialized. + // - We do not touch `data` at any point after this if we fail. + // - This does not move `data`. + unsafe { init.__pinned_init(inner.data.get_unchecked_mut().as_= mut_ptr()) }?; + + // INVARIANT: Now that we've successfully initialized `inner.d= ata`, we update + // `inner.is_init` to reflect this - fulfilling the relevant I= nner type invariant. + *inner.is_init =3D true; + } + + // SAFETY: We confirmed `data` is initialized above. + let ret =3D unsafe { self.data(&inner) }; + + match do_init { + true =3D> Ok(ret), + false =3D> Err(LazyInitError::AlreadyInit(ret)), + } + } + + /// Get a reference to the contained object. + /// + /// Returns [`None`] if this [`LazyInit`] is empty. + pub fn as_ref<'a>(&'a self) -> Option<&'a T> { + let inner =3D self.inner.lock(); + + inner.is_init.then(|| { + // SAFETY: This closure can only execute if `inner.is_init` is= true, guaranteeing + // `inner.data` is initialized via `Inner`s type invariants. + unsafe { self.data(&inner) } + }) + } + + /// Release the contents of the [`LazyInit`]. + /// + /// Since this call borrows the [`LazyInit`] mutably, no locking actua= lly needs to take place - + /// as parallel lock acquisitions are prevented via the compiler enfor= cing Rust's borrowing + /// rules. + /// + /// Returns [`true`] if `self` was initialized before calling this fun= ction. + pub fn reset(self: Pin<&mut Self>) -> bool { + let inner =3D self.project().inner.get_mut_pinned(); + let was_init =3D inner.is_init; + + // SAFETY: + // - We drop in place, and therefore do not move `inner`. + // - The `PinnedDrop` implementation of `Inner` leaves it in a wel= l-defined + // state, so we do not need to worry about UB from further usage. + unsafe { ptr::drop_in_place(inner.get_unchecked_mut()) }; + + was_init + } +} + +#[kunit_tests(rust_lazy_init)] +mod tests { + use super::*; + use pin_init::{ + init_from_closure, + stack_pin_init, // + }; + + #[derive(Debug)] + #[pin_data] + struct LazyInitTest {} + + impl LazyInitTest { + fn init_ok() -> impl Init { + init!(LazyInitTest {}) + } + + fn init_err(e: Error) -> impl Init { + // SAFETY: + // This initializer is intended to fail for testing purposes, = and does not actually + // initialize any data meaning: + // + // - We don't need to worry about returning Ok(()). + // - We have nothing to actually clean in the slot. + // - Since there is no data in the slot, nothing can meaningfu= lly move and we have no + // pinning invariants. + unsafe { init_from_closure(move |_| Err(e)) } + } + } + + fn try_lazy_init(once: &LazyInit) -> Result { + // It should start as being empty. + assert!((*once).as_ref().is_none()); + + // Try populating it a single time, this should succeed. + let res =3D once.init(LazyInitTest::init_ok()).map_err(|_| EINVAL)= ?; + assert!((*once).as_ref().is_some()); + + // Populating a second time should fail and return the contents. + match once.init(LazyInitTest::init_ok()) { + Err(LazyInitError::AlreadyInit(data)) =3D> assert!(core::ptr::= eq(data, res)), + r =3D> panic!("Calling once.init() twice returned unexpected v= alue: {r:?}"), + } + + // And it should still hold a value + assert!((*once).as_ref().is_some()); + + Ok(()) + } + + #[test] + fn lazy_init() -> Result { + stack_pin_init!(let once: LazyInit =3D new_lazy_init= !()); + + try_lazy_init(&once)?; + Ok(()) + } + + #[test] + fn lazy_init_error() -> Result { + stack_pin_init!(let once: LazyInit =3D new_lazy_init= !()); + + // Make sure it starts as empty. + assert!((*once).as_ref().is_none()); + + // Try populating it with a initializer that fails. + match once.init(LazyInitTest::init_err(EJUKEBOX)) { + Err(LazyInitError::DuringInit(e)) =3D> assert_eq!(e, EJUKEBOX), + r =3D> panic!( + "Calling once.init() with a failing initializer returned a= n unexpected value: {r:?}" + ), + } + + try_lazy_init(&once)?; + Ok(()) + } + + #[test] + fn lazy_init_reset() -> Result { + stack_pin_init!(let once: LazyInit =3D new_lazy_init= !()); + + try_lazy_init(&once)?; + assert_eq!(once.as_mut().reset(), true); + assert_eq!(once.as_mut().reset(), false); + try_lazy_init(&once) + } +} --=20 2.54.0