Skip to main content

pin_init/
lib.rs

1// SPDX-License-Identifier: Apache-2.0 OR MIT
2
3//! Library to safely and fallibly initialize pinned `struct`s using in-place constructors.
4//!
5//! [Pinning][pinning] is Rust's way of ensuring data does not move.
6//!
7//! It also allows in-place initialization of big `struct`s that would otherwise produce a stack
8//! overflow.
9//!
10//! This library's main use-case is in [Rust-for-Linux]. Although this version can be used
11//! standalone.
12//!
13//! There are cases when you want to in-place initialize a struct. For example when it is very big
14//! and moving it from the stack is not an option, because it is bigger than the stack itself.
15//! Another reason would be that you need the address of the object to initialize it. This stands
16//! in direct conflict with Rust's normal process of first initializing an object and then moving
17//! it into it's final memory location. For more information, see
18//! <https://rust-for-linux.com/the-safe-pinned-initialization-problem>.
19//!
20//! This library allows you to do in-place initialization safely.
21//!
22//! ## Nightly Needed for `alloc` feature
23//!
24//! This library requires the [`allocator_api` unstable feature] when the `alloc` feature is
25//! enabled and thus this feature can only be used with a nightly compiler. When enabling the
26//! `alloc` feature, the user will be required to activate `allocator_api` as well.
27//!
28//! [`allocator_api` unstable feature]: https://doc.rust-lang.org/nightly/unstable-book/library-features/allocator-api.html
29//!
30//! The feature is enabled by default, thus by default `pin-init` will require a nightly compiler.
31//! However, using the crate on stable compilers is possible by disabling `alloc`. In practice this
32//! will require the `std` feature, because stable compilers have neither `Box` nor `Arc` in no-std
33//! mode.
34//!
35//! ## Nightly needed for `unsafe-pinned` feature
36//!
37//! This feature enables the `Wrapper` implementation on the unstable `core::pin::UnsafePinned` type.
38//! This requires the [`unsafe_pinned` unstable feature](https://github.com/rust-lang/rust/issues/125735)
39//! and therefore a nightly compiler. Note that this feature is not enabled by default.
40//!
41//! # Overview
42//!
43//! To initialize a `struct` with an in-place constructor you will need two things:
44//! - an in-place constructor,
45//! - a memory location that can hold your `struct` (this can be the [stack], an [`Arc<T>`],
46//!   [`Box<T>`] or any other smart pointer that supports this library).
47//!
48//! To get an in-place constructor there are generally three options:
49//! - directly creating an in-place constructor using the [`pin_init!`] macro,
50//! - a custom function/macro returning an in-place constructor provided by someone else,
51//! - using the unsafe function [`pin_init_from_closure()`] to manually create an initializer.
52//!
53//! Aside from pinned initialization, this library also supports in-place construction without
54//! pinning, the macros/types/functions are generally named like the pinned variants without the
55//! `pin_` prefix.
56//!
57//! # Examples
58//!
59//! Throughout the examples we will often make use of the `CMutex` type which can be found in
60//! `../examples/mutex.rs`. It is essentially a userland rebuild of the `struct mutex` type from
61//! the Linux kernel. It also uses a wait list and a basic spinlock. Importantly the wait list
62//! requires it to be pinned to be locked and thus is a prime candidate for using this library.
63//!
64//! ## Using the [`pin_init!`] macro
65//!
66//! If you want to use [`PinInit`], then you will have to annotate your `struct` with
67//! `#[`[`pin_data`]`]`. It is a macro that uses `#[pin]` as a marker for
68//! [structurally pinned fields]. After doing this, you can then create an in-place constructor via
69//! [`pin_init!`]. The syntax is almost the same as normal `struct` initializers. The difference is
70//! that you need to write `<-` instead of `:` for fields that you want to initialize in-place.
71//!
72//! ```rust
73//! # #![expect(clippy::disallowed_names)]
74//! # #![feature(allocator_api)]
75//! # #[path = "../examples/mutex.rs"] mod mutex; use mutex::*;
76//! # use core::pin::Pin;
77//! use pin_init::{pin_data, pin_init, InPlaceInit};
78//!
79//! #[pin_data]
80//! struct Foo {
81//!     #[pin]
82//!     a: CMutex<usize>,
83//!     b: u32,
84//! }
85//!
86//! let foo = pin_init!(Foo {
87//!     a <- CMutex::new(42),
88//!     b: 24,
89//! });
90//! # let _ = Box::pin_init(foo);
91//! ```
92//!
93//! `foo` now is of the type [`impl PinInit<Foo>`]. We can now use any smart pointer that we like
94//! (or just the stack) to actually initialize a `Foo`:
95//!
96//! ```rust
97//! # #![expect(clippy::disallowed_names)]
98//! # #![feature(allocator_api)]
99//! # #[path = "../examples/mutex.rs"] mod mutex; use mutex::*;
100//! # use core::{alloc::AllocError, pin::Pin};
101//! # use pin_init::*;
102//! #
103//! # #[pin_data]
104//! # struct Foo {
105//! #     #[pin]
106//! #     a: CMutex<usize>,
107//! #     b: u32,
108//! # }
109//! #
110//! # let foo = pin_init!(Foo {
111//! #     a <- CMutex::new(42),
112//! #     b: 24,
113//! # });
114//! let foo: Result<Pin<Box<Foo>>, AllocError> = Box::pin_init(foo);
115//! ```
116//!
117//! For more information see the [`pin_init!`] macro.
118//!
119//! ## Using a custom function/macro that returns an initializer
120//!
121//! Many types that use this library supply a function/macro that returns an initializer, because
122//! the above method only works for types where you can access the fields.
123//!
124//! ```rust
125//! # #![feature(allocator_api)]
126//! # #[path = "../examples/mutex.rs"] mod mutex; use mutex::*;
127//! # use pin_init::*;
128//! # use std::sync::Arc;
129//! # use core::pin::Pin;
130//! let mtx: Result<Pin<Arc<CMutex<usize>>>, _> = Arc::pin_init(CMutex::new(42));
131//! ```
132//!
133//! To declare an init macro/function you just return an [`impl PinInit<T, E>`]:
134//!
135//! ```rust
136//! # #![feature(allocator_api)]
137//! # use pin_init::*;
138//! # #[path = "../examples/error.rs"] mod error; use error::Error;
139//! # #[path = "../examples/mutex.rs"] mod mutex; use mutex::*;
140//! #[pin_data]
141//! struct DriverData {
142//!     #[pin]
143//!     status: CMutex<i32>,
144//!     buffer: Box<[u8; 1_000_000]>,
145//! }
146//!
147//! impl DriverData {
148//!     fn new() -> impl PinInit<Self, Error> {
149//!         pin_init!(Self {
150//!             status <- CMutex::new(0),
151//!             buffer: Box::init(pin_init::init_zeroed())?,
152//!         }? Error)
153//!     }
154//! }
155//! ```
156//!
157//! ## Manual creation of an initializer
158//!
159//! Often when working with primitives the previous approaches are not sufficient. That is where
160//! [`pin_init_from_closure()`] comes in. This `unsafe` function allows you to create a
161//! [`impl PinInit<T, E>`] directly from a closure. Of course you have to ensure that the closure
162//! actually does the initialization in the correct way. Here are the things to look out for
163//! (we are calling the parameter to the closure `slot`):
164//! - when the closure returns `Ok(())`, then it has completed the initialization successfully, so
165//!   `slot` now contains a valid bit pattern for the type `T`,
166//! - when the closure returns `Err(e)`, then the caller may deallocate the memory at `slot`, so
167//!   you need to take care to clean up anything if your initialization fails mid-way,
168//! - you may assume that `slot` will stay pinned even after the closure returns until `drop` of
169//!   `slot` gets called.
170//!
171//! ```rust
172//! # #![feature(extern_types)]
173//! use pin_init::{pin_data, pinned_drop, PinInit, PinnedDrop, pin_init_from_closure};
174//! use core::{
175//!     marker::PhantomPinned,
176//!     cell::UnsafeCell,
177//!     pin::Pin,
178//!     mem::MaybeUninit,
179//! };
180//! mod bindings {
181//!     #[repr(C)]
182//!     pub struct foo {
183//!         /* fields from C ... */
184//!     }
185//!     extern "C" {
186//!         pub fn init_foo(ptr: *mut foo);
187//!         pub fn destroy_foo(ptr: *mut foo);
188//!         #[must_use = "you must check the error return code"]
189//!         pub fn enable_foo(ptr: *mut foo, flags: u32) -> i32;
190//!     }
191//! }
192//!
193//! /// # Invariants
194//! ///
195//! /// `foo` is always initialized
196//! #[pin_data(PinnedDrop)]
197//! pub struct RawFoo {
198//!     #[pin]
199//!     _p: PhantomPinned,
200//!     #[pin]
201//!     foo: UnsafeCell<MaybeUninit<bindings::foo>>,
202//! }
203//!
204//! impl RawFoo {
205//!     pub fn new(flags: u32) -> impl PinInit<Self, i32> {
206//!         // SAFETY:
207//!         // - when the closure returns `Ok(())`, then it has successfully initialized and
208//!         //   enabled `foo`,
209//!         // - when it returns `Err(e)`, then it has cleaned up before
210//!         unsafe {
211//!             pin_init_from_closure(move |slot: *mut Self| {
212//!                 // `slot` contains uninit memory, avoid creating a reference.
213//!                 let foo = &raw mut (*slot).foo;
214//!                 let foo = UnsafeCell::raw_get(foo).cast::<bindings::foo>();
215//!
216//!                 // Initialize the `foo`
217//!                 bindings::init_foo(foo);
218//!
219//!                 // Try to enable it.
220//!                 let err = bindings::enable_foo(foo, flags);
221//!                 if err != 0 {
222//!                     // Enabling has failed, first clean up the foo and then return the error.
223//!                     bindings::destroy_foo(foo);
224//!                     Err(err)
225//!                 } else {
226//!                     // All fields of `RawFoo` have been initialized, since `_p` is a ZST.
227//!                     Ok(())
228//!                 }
229//!             })
230//!         }
231//!     }
232//! }
233//!
234//! #[pinned_drop]
235//! impl PinnedDrop for RawFoo {
236//!     fn drop(self: Pin<&mut Self>) {
237//!         // SAFETY: Since `foo` is initialized, destroying is safe.
238//!         unsafe { bindings::destroy_foo(self.foo.get().cast::<bindings::foo>()) };
239//!     }
240//! }
241//! ```
242//!
243//! For more information on how to use [`pin_init_from_closure()`], take a look at the uses inside
244//! the `kernel` crate. The [`sync`] module is a good starting point.
245//!
246//! [`sync`]: https://rust.docs.kernel.org/kernel/sync/index.html
247//! [pinning]: https://doc.rust-lang.org/std/pin/index.html
248//! [structurally pinned fields]:
249//!     https://doc.rust-lang.org/std/pin/index.html#projections-and-structural-pinning
250//! [stack]: crate::stack_pin_init
251#![cfg_attr(
252    kernel,
253    doc = "[`Arc<T>`]: https://rust.docs.kernel.org/kernel/sync/struct.Arc.html"
254)]
255#![cfg_attr(
256    kernel,
257    doc = "[`Box<T>`]: https://rust.docs.kernel.org/kernel/alloc/kbox/struct.Box.html"
258)]
259#![cfg_attr(not(kernel), doc = "[`Arc<T>`]: alloc::alloc::sync::Arc")]
260#![cfg_attr(not(kernel), doc = "[`Box<T>`]: alloc::alloc::boxed::Box")]
261//! [`impl PinInit<Foo>`]: crate::PinInit
262//! [`impl PinInit<T, E>`]: crate::PinInit
263//! [`impl Init<T, E>`]: crate::Init
264//! [Rust-for-Linux]: https://rust-for-linux.com/
265
266#![forbid(missing_docs, unsafe_op_in_unsafe_fn)]
267#![cfg_attr(not(feature = "std"), no_std)]
268#![cfg_attr(feature = "alloc", feature(allocator_api))]
269#![cfg_attr(
270    all(feature = "unsafe-pinned", CONFIG_RUSTC_HAS_UNSAFE_PINNED),
271    feature(unsafe_pinned)
272)]
273#![cfg_attr(all(USE_RUSTC_FEATURES, doc), allow(internal_features))]
274#![cfg_attr(all(USE_RUSTC_FEATURES, doc), feature(rustdoc_internals))]
275
276use core::{
277    cell::UnsafeCell,
278    convert::Infallible,
279    marker::PhantomData,
280    mem::MaybeUninit,
281    num::*,
282    pin::Pin,
283    ptr::{self, NonNull},
284};
285
286// This is used by doc-tests -- the proc-macros expand to `::pin_init::...` and without this the
287// doc-tests wouldn't have an extern crate named `pin_init`.
288#[allow(unused_extern_crates)]
289extern crate self as pin_init;
290
291#[doc(hidden)]
292pub mod __internal;
293
294#[cfg(any(feature = "std", feature = "alloc"))]
295mod alloc;
296#[cfg(any(feature = "std", feature = "alloc"))]
297pub use alloc::InPlaceInit;
298
299/// Used to specify the pinning information of the fields of a struct.
300///
301/// This is somewhat similar in purpose as
302/// [pin-project-lite](https://crates.io/crates/pin-project-lite).
303/// Place this macro on a struct definition and then `#[pin]` in front of the attributes of each
304/// field you want to structurally pin.
305///
306/// This macro enables the use of the [`pin_init!`] macro. When pin-initializing a `struct`,
307/// then `#[pin]` directs the type of initializer that is required.
308///
309/// If your `struct` implements `Drop`, then you need to add `PinnedDrop` as arguments to this
310/// macro, and change your `Drop` implementation to `PinnedDrop` annotated with
311/// `#[`[`macro@pinned_drop`]`]`, since dropping pinned values requires extra care.
312///
313/// # Examples
314///
315/// ```
316/// # #![feature(allocator_api)]
317/// # #[path = "../examples/mutex.rs"] mod mutex; use mutex::*;
318/// use pin_init::pin_data;
319///
320/// enum Command {
321///     /* ... */
322/// }
323///
324/// #[pin_data]
325/// struct DriverData {
326///     #[pin]
327///     queue: CMutex<Vec<Command>>,
328///     buf: Box<[u8; 1024 * 1024]>,
329/// }
330/// ```
331///
332/// ```
333/// # #![feature(allocator_api)]
334/// # #[path = "../examples/mutex.rs"] mod mutex; use mutex::*;
335/// # mod bindings { pub struct info; pub unsafe fn destroy_info(_: *mut info) {} }
336/// use core::pin::Pin;
337/// use pin_init::{pin_data, pinned_drop, PinnedDrop};
338///
339/// enum Command {
340///     /* ... */
341/// }
342///
343/// #[pin_data(PinnedDrop)]
344/// struct DriverData {
345///     #[pin]
346///     queue: CMutex<Vec<Command>>,
347///     buf: Box<[u8; 1024 * 1024]>,
348///     raw_info: *mut bindings::info,
349/// }
350///
351/// #[pinned_drop]
352/// impl PinnedDrop for DriverData {
353///     fn drop(self: Pin<&mut Self>) {
354///         unsafe { bindings::destroy_info(self.raw_info) };
355///     }
356/// }
357/// ```
358pub use ::pin_init_internal::pin_data;
359
360/// Used to implement `PinnedDrop` safely.
361///
362/// Only works on structs that are annotated via `#[`[`macro@pin_data`]`]`.
363///
364/// # Examples
365///
366/// ```
367/// # #![feature(allocator_api)]
368/// # #[path = "../examples/mutex.rs"] mod mutex; use mutex::*;
369/// # mod bindings { pub struct info; pub unsafe fn destroy_info(_: *mut info) {} }
370/// use core::pin::Pin;
371/// use pin_init::{pin_data, pinned_drop, PinnedDrop};
372///
373/// enum Command {
374///     /* ... */
375/// }
376///
377/// #[pin_data(PinnedDrop)]
378/// struct DriverData {
379///     #[pin]
380///     queue: CMutex<Vec<Command>>,
381///     buf: Box<[u8; 1024 * 1024]>,
382///     raw_info: *mut bindings::info,
383/// }
384///
385/// #[pinned_drop]
386/// impl PinnedDrop for DriverData {
387///     fn drop(self: Pin<&mut Self>) {
388///         unsafe { bindings::destroy_info(self.raw_info) };
389///     }
390/// }
391/// ```
392pub use ::pin_init_internal::pinned_drop;
393
394/// Derives the [`Zeroable`] trait for the given `struct` or `union`.
395///
396/// This can only be used for `struct`s/`union`s where every field implements the [`Zeroable`]
397/// trait.
398///
399/// # Examples
400///
401/// ```
402/// use pin_init::Zeroable;
403///
404/// #[derive(Zeroable)]
405/// pub struct DriverData {
406///     pub(crate) id: i64,
407///     buf_ptr: *mut u8,
408///     len: usize,
409/// }
410/// ```
411///
412/// ```
413/// use pin_init::Zeroable;
414///
415/// #[derive(Zeroable)]
416/// pub union SignCast {
417///     signed: i64,
418///     unsigned: u64,
419/// }
420/// ```
421pub use ::pin_init_internal::Zeroable;
422
423/// Derives the [`Zeroable`] trait for the given `struct` or `union` if all fields implement
424/// [`Zeroable`].
425///
426/// Contrary to the derive macro named [`macro@Zeroable`], this one silently fails when a field
427/// doesn't implement [`Zeroable`].
428///
429/// # Examples
430///
431/// ```
432/// use pin_init::MaybeZeroable;
433///
434/// // implements `Zeroable`
435/// #[derive(MaybeZeroable)]
436/// pub struct DriverData {
437///     pub(crate) id: i64,
438///     buf_ptr: *mut u8,
439///     len: usize,
440/// }
441///
442/// // does not implement `Zeroable`
443/// #[derive(MaybeZeroable)]
444/// pub struct DriverData2 {
445///     pub(crate) id: i64,
446///     buf_ptr: *mut u8,
447///     len: usize,
448///     // this field doesn't implement `Zeroable`
449///     other_data: &'static i32,
450/// }
451/// ```
452pub use ::pin_init_internal::MaybeZeroable;
453
454/// Initialize and pin a type directly on the stack.
455///
456/// # Examples
457///
458/// ```rust
459/// # #![expect(clippy::disallowed_names)]
460/// # #![feature(allocator_api)]
461/// # #[path = "../examples/mutex.rs"] mod mutex; use mutex::*;
462/// # use pin_init::*;
463/// # use core::pin::Pin;
464/// #[pin_data]
465/// struct Foo {
466///     #[pin]
467///     a: CMutex<usize>,
468///     b: Bar,
469/// }
470///
471/// #[pin_data]
472/// struct Bar {
473///     x: u32,
474/// }
475///
476/// stack_pin_init!(let foo = pin_init!(Foo {
477///     a <- CMutex::new(42),
478///     b: Bar {
479///         x: 64,
480///     },
481/// }));
482/// let foo: Pin<&mut Foo> = foo;
483/// println!("a: {}", &*foo.a.lock());
484/// ```
485///
486/// # Syntax
487///
488/// A normal `let` binding with optional type annotation. The expression is expected to implement
489/// [`PinInit`]/[`Init`] with the error type [`Infallible`]. If you want to use a different error
490/// type, then use [`stack_try_pin_init!`].
491#[macro_export]
492macro_rules! stack_pin_init {
493    (let $var:ident $(: $t:ty)? = $val:expr) => {
494        let val = $val;
495        let mut $var = ::core::pin::pin!($crate::__internal::StackInit$(::<$t>)?::uninit());
496        let Ok(mut $var) = $crate::__internal::StackInit::init($var, val);
497    };
498}
499
500/// Initialize and pin a type directly on the stack.
501///
502/// # Examples
503///
504/// ```rust
505/// # #![expect(clippy::disallowed_names)]
506/// # #![feature(allocator_api)]
507/// # #[path = "../examples/error.rs"] mod error; use error::Error;
508/// # #[path = "../examples/mutex.rs"] mod mutex; use mutex::*;
509/// # use pin_init::*;
510/// #[pin_data]
511/// struct Foo {
512///     #[pin]
513///     a: CMutex<usize>,
514///     b: Box<Bar>,
515/// }
516///
517/// struct Bar {
518///     x: u32,
519/// }
520///
521/// stack_try_pin_init!(let foo: Foo = pin_init!(Foo {
522///     a <- CMutex::new(42),
523///     b: Box::try_new(Bar {
524///         x: 64,
525///     })?,
526/// }? Error));
527/// let foo = foo.unwrap();
528/// println!("a: {}", &*foo.a.lock());
529/// ```
530///
531/// ```rust
532/// # #![expect(clippy::disallowed_names)]
533/// # #![feature(allocator_api)]
534/// # #[path = "../examples/error.rs"] mod error; use error::Error;
535/// # #[path = "../examples/mutex.rs"] mod mutex; use mutex::*;
536/// # use pin_init::*;
537/// #[pin_data]
538/// struct Foo {
539///     #[pin]
540///     a: CMutex<usize>,
541///     b: Box<Bar>,
542/// }
543///
544/// struct Bar {
545///     x: u32,
546/// }
547///
548/// stack_try_pin_init!(let foo: Foo =? pin_init!(Foo {
549///     a <- CMutex::new(42),
550///     b: Box::try_new(Bar {
551///         x: 64,
552///     })?,
553/// }? Error));
554/// println!("a: {}", &*foo.a.lock());
555/// # Ok::<_, Error>(())
556/// ```
557///
558/// # Syntax
559///
560/// A normal `let` binding with optional type annotation. The expression is expected to implement
561/// [`PinInit`]/[`Init`]. This macro assigns a result to the given variable, adding a `?` after the
562/// `=` will propagate this error.
563#[macro_export]
564macro_rules! stack_try_pin_init {
565    (let $var:ident $(: $t:ty)? = $val:expr) => {
566        let val = $val;
567        let mut $var = ::core::pin::pin!($crate::__internal::StackInit$(::<$t>)?::uninit());
568        let mut $var = $crate::__internal::StackInit::init($var, val);
569    };
570    (let $var:ident $(: $t:ty)? =? $val:expr) => {
571        let val = $val;
572        let mut $var = ::core::pin::pin!($crate::__internal::StackInit$(::<$t>)?::uninit());
573        let mut $var = $crate::__internal::StackInit::init($var, val)?;
574    };
575}
576
577/// Construct an in-place, fallible pinned initializer for `struct`s.
578///
579/// The error type defaults to [`Infallible`]; if you need a different one, write `? Error` at the
580/// end, after the struct initializer.
581///
582/// The syntax is almost identical to that of a normal `struct` initializer:
583///
584/// ```rust
585/// # use pin_init::*;
586/// # use core::pin::Pin;
587/// #[pin_data]
588/// struct Foo {
589///     a: usize,
590///     b: Bar,
591/// }
592///
593/// #[pin_data]
594/// struct Bar {
595///     x: u32,
596/// }
597///
598/// # fn demo() -> impl PinInit<Foo> {
599/// let a = 42;
600///
601/// let initializer = pin_init!(Foo {
602///     a,
603///     b: Bar {
604///         x: 64,
605///     },
606/// });
607/// # initializer }
608/// # Box::pin_init(demo()).unwrap();
609/// ```
610///
611/// Arbitrary Rust expressions can be used to set the value of a variable.
612///
613/// The fields are initialized in the order that they appear in the initializer. So it is possible
614/// to read already initialized fields using raw pointers.
615///
616/// IMPORTANT: You are not allowed to create references to fields of the struct inside of the
617/// initializer.
618///
619/// # Init-functions
620///
621/// When working with this library it is often desired to let others construct your types without
622/// giving access to all fields. This is where you would normally write a plain function `new` that
623/// would return a new instance of your type. With this library that is also possible. However,
624/// there are a few extra things to keep in mind.
625///
626/// To create an initializer function, simply declare it like this:
627///
628/// ```rust
629/// # use pin_init::*;
630/// # use core::pin::Pin;
631/// # #[pin_data]
632/// # struct Foo {
633/// #     a: usize,
634/// #     b: Bar,
635/// # }
636/// # #[pin_data]
637/// # struct Bar {
638/// #     x: u32,
639/// # }
640/// impl Foo {
641///     fn new() -> impl PinInit<Self> {
642///         pin_init!(Self {
643///             a: 42,
644///             b: Bar {
645///                 x: 64,
646///             },
647///         })
648///     }
649/// }
650/// ```
651///
652/// Users of `Foo` can now create it like this:
653///
654/// ```rust
655/// # #![expect(clippy::disallowed_names)]
656/// # use pin_init::*;
657/// # use core::pin::Pin;
658/// # #[pin_data]
659/// # struct Foo {
660/// #     a: usize,
661/// #     b: Bar,
662/// # }
663/// # #[pin_data]
664/// # struct Bar {
665/// #     x: u32,
666/// # }
667/// # impl Foo {
668/// #     fn new() -> impl PinInit<Self> {
669/// #         pin_init!(Self {
670/// #             a: 42,
671/// #             b: Bar {
672/// #                 x: 64,
673/// #             },
674/// #         })
675/// #     }
676/// # }
677/// let foo = Box::pin_init(Foo::new());
678/// ```
679///
680/// They can also easily embed it into their own `struct`s:
681///
682/// ```rust
683/// # use pin_init::*;
684/// # use core::pin::Pin;
685/// # #[pin_data]
686/// # struct Foo {
687/// #     a: usize,
688/// #     b: Bar,
689/// # }
690/// # #[pin_data]
691/// # struct Bar {
692/// #     x: u32,
693/// # }
694/// # impl Foo {
695/// #     fn new() -> impl PinInit<Self> {
696/// #         pin_init!(Self {
697/// #             a: 42,
698/// #             b: Bar {
699/// #                 x: 64,
700/// #             },
701/// #         })
702/// #     }
703/// # }
704/// #[pin_data]
705/// struct FooContainer {
706///     #[pin]
707///     foo1: Foo,
708///     #[pin]
709///     foo2: Foo,
710///     other: u32,
711/// }
712///
713/// impl FooContainer {
714///     fn new(other: u32) -> impl PinInit<Self> {
715///         pin_init!(Self {
716///             foo1 <- Foo::new(),
717///             foo2 <- Foo::new(),
718///             other,
719///         })
720///     }
721/// }
722/// ```
723///
724/// Here we see that when using `pin_init!` with `PinInit`, one needs to write `<-` instead of `:`.
725/// This signifies that the given field is initialized in-place. As with `struct` initializers, just
726/// writing the field (in this case `other`) without `:` or `<-` means `other: other,`.
727///
728/// # Syntax
729///
730/// As already mentioned in the examples above, inside of `pin_init!` a `struct` initializer with
731/// the following modifications is expected:
732/// - Fields that you want to initialize in-place have to use `<-` instead of `:`.
733/// - You can use `_: { /* run any user-code here */ },` anywhere where you can place fields in
734///   order to run arbitrary code.
735/// - In front of the initializer you can write `&this in` to have access to a [`NonNull<Self>`]
736///   pointer named `this` inside of the initializer.
737/// - Using struct update syntax one can place `..Zeroable::init_zeroed()` at the very end of the
738///   struct, this initializes every field with 0 and then runs all initializers specified in the
739///   body. This can only be done if [`Zeroable`] is implemented for the struct.
740///
741/// For instance:
742///
743/// ```rust
744/// # use pin_init::*;
745/// # use core::marker::PhantomPinned;
746/// #[pin_data]
747/// #[derive(Zeroable)]
748/// struct Buf {
749///     // `ptr` points into `buf`.
750///     ptr: *mut u8,
751///     buf: [u8; 64],
752///     #[pin]
753///     pin: PhantomPinned,
754/// }
755///
756/// let init = pin_init!(&this in Buf {
757///     buf: [0; 64],
758///     // SAFETY: TODO.
759///     ptr: unsafe { (&raw mut (*this.as_ptr()).buf).cast() },
760///     pin: PhantomPinned,
761/// });
762/// let init = pin_init!(Buf {
763///     buf: [1; 64],
764///     ..Zeroable::init_zeroed()
765/// });
766/// ```
767///
768/// [`NonNull<Self>`]: core::ptr::NonNull
769pub use pin_init_internal::pin_init;
770
771/// Construct an in-place, fallible initializer for `struct`s.
772///
773/// This macro defaults the error to [`Infallible`]; if you need a different one, write `? Error`
774/// at the end, after the struct initializer.
775///
776/// The syntax is identical to [`pin_init!`] and its safety caveats also apply:
777/// - `unsafe` code must guarantee either full initialization or return an error and allow
778///   deallocation of the memory.
779/// - the fields are initialized in the order given in the initializer.
780/// - no references to fields are allowed to be created inside of the initializer.
781///
782/// This initializer is for initializing data in-place that might later be moved. If you want to
783/// pin-initialize, use [`pin_init!`].
784///
785/// # Examples
786///
787/// ```rust
788/// # #![feature(allocator_api)]
789/// # #[path = "../examples/error.rs"] mod error; use error::Error;
790/// # #[path = "../examples/mutex.rs"] mod mutex; use mutex::*;
791/// # use pin_init::InPlaceInit;
792/// use pin_init::{init, Init, init_zeroed};
793///
794/// struct BigBuf {
795///     small: [u8; 1024 * 1024],
796/// }
797///
798/// impl BigBuf {
799///     fn new() -> impl Init<Self> {
800///         init!(Self {
801///             small <- init_zeroed(),
802///         })
803///     }
804/// }
805/// # let _ = Box::init(BigBuf::new());
806/// ```
807pub use pin_init_internal::init;
808
809/// Asserts that a field on a struct using `#[pin_data]` is marked with `#[pin]` ie. that it is
810/// structurally pinned.
811///
812/// # Examples
813///
814/// This will succeed:
815/// ```
816/// use pin_init::{pin_data, assert_pinned};
817///
818/// #[pin_data]
819/// struct MyStruct {
820///     #[pin]
821///     some_field: u64,
822/// }
823///
824/// assert_pinned!(MyStruct, some_field, u64);
825/// ```
826///
827/// This will fail:
828/// ```compile_fail
829/// use pin_init::{pin_data, assert_pinned};
830///
831/// #[pin_data]
832/// struct MyStruct {
833///     some_field: u64,
834/// }
835///
836/// assert_pinned!(MyStruct, some_field, u64);
837/// ```
838///
839/// Some uses of the macro may trigger the `can't use generic parameters from outer item` error. To
840/// work around this, you may pass the `inline` parameter to the macro. The `inline` parameter can
841/// only be used when the macro is invoked from a function body.
842/// ```
843/// # use core::pin::Pin;
844/// use pin_init::{pin_data, assert_pinned};
845///
846/// #[pin_data]
847/// struct Foo<T> {
848///     #[pin]
849///     elem: T,
850/// }
851///
852/// impl<T> Foo<T> {
853///     fn project_this(self: Pin<&mut Self>) -> Pin<&mut T> {
854///         assert_pinned!(Foo<T>, elem, T, inline);
855///
856///         // SAFETY: The field is structurally pinned.
857///         unsafe { self.map_unchecked_mut(|me| &mut me.elem) }
858///     }
859/// }
860/// ```
861#[macro_export]
862macro_rules! assert_pinned {
863    ($ty:ty, $field:ident, $field_ty:ty, inline) => {
864        // SAFETY: This code is unreachable.
865        let _ = move |ptr: *mut $ty| unsafe {
866            let data = <$ty as $crate::__internal::HasPinData>::__pin_data();
867            _ = data
868                .$field(ptr)
869                .init($crate::__internal::AlwaysFail::<$field_ty>::new());
870        };
871    };
872
873    ($ty:ty, $field:ident, $field_ty:ty) => {
874        const _: () = {
875            $crate::assert_pinned!($ty, $field, $field_ty, inline);
876        };
877    };
878}
879
880/// A pin-initializer for the type `T`.
881///
882/// To use this initializer, you will need a suitable memory location that can hold a `T`. This can
883/// be [`Box<T>`], [`Arc<T>`] or even the stack (see [`stack_pin_init!`]).
884///
885/// Also see the [module description](self).
886///
887/// # Safety
888///
889/// When implementing this trait you will need to take great care. Also there are probably very few
890/// cases where a manual implementation is necessary. Use [`pin_init_from_closure`] where possible.
891///
892/// The [`PinInit::__pinned_init`] function:
893/// - returns `Ok(())` if it initialized every field of `slot`,
894/// - returns `Err(err)` if it encountered an error and then cleaned `slot`, this means:
895///     - `slot` can be deallocated without UB occurring,
896///     - `slot` does not need to be dropped,
897///     - `slot` is not partially initialized.
898/// - while constructing the `T` at `slot` it upholds the pinning invariants of `T`.
899///
900#[cfg_attr(
901    kernel,
902    doc = "[`Arc<T>`]: https://rust.docs.kernel.org/kernel/sync/struct.Arc.html"
903)]
904#[cfg_attr(
905    kernel,
906    doc = "[`Box<T>`]: https://rust.docs.kernel.org/kernel/alloc/kbox/struct.Box.html"
907)]
908#[cfg_attr(not(kernel), doc = "[`Arc<T>`]: alloc::alloc::sync::Arc")]
909#[cfg_attr(not(kernel), doc = "[`Box<T>`]: alloc::alloc::boxed::Box")]
910#[must_use = "An initializer must be used in order to create its value."]
911pub unsafe trait PinInit<T: ?Sized, E = Infallible>: Sized {
912    /// Initializes `slot`.
913    ///
914    /// # Safety
915    ///
916    /// - `slot` is a valid pointer to uninitialized memory.
917    /// - the caller does not touch `slot` when `Err` is returned, they are only permitted to
918    ///   deallocate.
919    /// - `slot` will not move until it is dropped, i.e. it will be pinned.
920    unsafe fn __pinned_init(self, slot: *mut T) -> Result<(), E>;
921
922    /// First initializes the value using `self` then calls the function `f` with the initialized
923    /// value.
924    ///
925    /// If `f` returns an error the value is dropped and the initializer will forward the error.
926    ///
927    /// # Examples
928    ///
929    /// ```rust
930    /// # #![feature(allocator_api)]
931    /// # #[path = "../examples/mutex.rs"] mod mutex; use mutex::*;
932    /// # use pin_init::*;
933    /// let mtx_init = CMutex::new(42);
934    /// // Make the initializer print the value.
935    /// let mtx_init = mtx_init.pin_chain(|mtx| {
936    ///     println!("{:?}", mtx.get_data_mut());
937    ///     Ok(())
938    /// });
939    /// ```
940    fn pin_chain<F>(self, f: F) -> ChainPinInit<Self, F, T, E>
941    where
942        F: FnOnce(Pin<&mut T>) -> Result<(), E>,
943    {
944        ChainPinInit(self, f, __internal::PhantomInvariant::new())
945    }
946}
947
948/// An initializer returned by [`PinInit::pin_chain`].
949pub struct ChainPinInit<I, F, T: ?Sized, E>(I, F, __internal::PhantomInvariant<(E, T)>);
950
951// SAFETY: The `__pinned_init` function is implemented such that it
952// - returns `Ok(())` on successful initialization,
953// - returns `Err(err)` on error and in this case `slot` will be dropped.
954// - considers `slot` pinned.
955unsafe impl<T: ?Sized, E, I, F> PinInit<T, E> for ChainPinInit<I, F, T, E>
956where
957    I: PinInit<T, E>,
958    F: FnOnce(Pin<&mut T>) -> Result<(), E>,
959{
960    unsafe fn __pinned_init(self, slot: *mut T) -> Result<(), E> {
961        // SAFETY: All requirements fulfilled since this function is `__pinned_init`.
962        unsafe { self.0.__pinned_init(slot)? };
963        // SAFETY: The above call initialized `slot` and we still have unique access.
964        let val = unsafe { &mut *slot };
965        // SAFETY: `slot` is considered pinned.
966        let val = unsafe { Pin::new_unchecked(val) };
967        // SAFETY: `slot` was initialized above.
968        (self.1)(val).inspect_err(|_| unsafe { core::ptr::drop_in_place(slot) })
969    }
970}
971
972/// An initializer for `T`.
973///
974/// To use this initializer, you will need a suitable memory location that can hold a `T`. This can
975/// be [`Box<T>`], [`Arc<T>`] or even the stack (see [`stack_pin_init!`]). Because
976/// [`PinInit<T, E>`] is a super trait, you can use every function that takes it as well.
977///
978/// Also see the [module description](self).
979///
980/// # Safety
981///
982/// When implementing this trait you will need to take great care. Also there are probably very few
983/// cases where a manual implementation is necessary. Use [`init_from_closure`] where possible.
984///
985/// The [`Init::__init`] function:
986/// - returns `Ok(())` if it initialized every field of `slot`,
987/// - returns `Err(err)` if it encountered an error and then cleaned `slot`, this means:
988///     - `slot` can be deallocated without UB occurring,
989///     - `slot` does not need to be dropped,
990///     - `slot` is not partially initialized.
991/// - while constructing the `T` at `slot` it upholds the pinning invariants of `T`.
992///
993/// The `__pinned_init` function from the supertrait [`PinInit`] needs to execute the exact same
994/// code as `__init`.
995///
996/// Contrary to its supertype [`PinInit<T, E>`] the caller is allowed to
997/// move the pointee after initialization.
998///
999#[cfg_attr(
1000    kernel,
1001    doc = "[`Arc<T>`]: https://rust.docs.kernel.org/kernel/sync/struct.Arc.html"
1002)]
1003#[cfg_attr(
1004    kernel,
1005    doc = "[`Box<T>`]: https://rust.docs.kernel.org/kernel/alloc/kbox/struct.Box.html"
1006)]
1007#[cfg_attr(not(kernel), doc = "[`Arc<T>`]: alloc::alloc::sync::Arc")]
1008#[cfg_attr(not(kernel), doc = "[`Box<T>`]: alloc::alloc::boxed::Box")]
1009#[must_use = "An initializer must be used in order to create its value."]
1010pub unsafe trait Init<T: ?Sized, E = Infallible>: PinInit<T, E> {
1011    /// Initializes `slot`.
1012    ///
1013    /// # Safety
1014    ///
1015    /// - `slot` is a valid pointer to uninitialized memory.
1016    /// - the caller does not touch `slot` when `Err` is returned, they are only permitted to
1017    ///   deallocate.
1018    unsafe fn __init(self, slot: *mut T) -> Result<(), E>;
1019
1020    /// First initializes the value using `self` then calls the function `f` with the initialized
1021    /// value.
1022    ///
1023    /// If `f` returns an error the value is dropped and the initializer will forward the error.
1024    ///
1025    /// # Examples
1026    ///
1027    /// ```rust
1028    /// # #![expect(clippy::disallowed_names)]
1029    /// use pin_init::{init, init_zeroed, Init};
1030    ///
1031    /// struct Foo {
1032    ///     buf: [u8; 1_000_000],
1033    /// }
1034    ///
1035    /// impl Foo {
1036    ///     fn setup(&mut self) {
1037    ///         println!("Setting up foo");
1038    ///     }
1039    /// }
1040    ///
1041    /// let foo = init!(Foo {
1042    ///     buf <- init_zeroed()
1043    /// }).chain(|foo| {
1044    ///     foo.setup();
1045    ///     Ok(())
1046    /// });
1047    /// ```
1048    fn chain<F>(self, f: F) -> ChainInit<Self, F, T, E>
1049    where
1050        F: FnOnce(&mut T) -> Result<(), E>,
1051    {
1052        ChainInit(self, f, __internal::PhantomInvariant::new())
1053    }
1054}
1055
1056/// An initializer returned by [`Init::chain`].
1057pub struct ChainInit<I, F, T: ?Sized, E>(I, F, __internal::PhantomInvariant<(E, T)>);
1058
1059// SAFETY: The `__init` function is implemented such that it
1060// - returns `Ok(())` on successful initialization,
1061// - returns `Err(err)` on error and in this case `slot` will be dropped.
1062unsafe impl<T: ?Sized, E, I, F> Init<T, E> for ChainInit<I, F, T, E>
1063where
1064    I: Init<T, E>,
1065    F: FnOnce(&mut T) -> Result<(), E>,
1066{
1067    unsafe fn __init(self, slot: *mut T) -> Result<(), E> {
1068        // SAFETY: All requirements fulfilled since this function is `__init`.
1069        unsafe { self.0.__pinned_init(slot)? };
1070        // SAFETY: The above call initialized `slot` and we still have unique access.
1071        (self.1)(unsafe { &mut *slot }).inspect_err(|_|
1072            // SAFETY: `slot` was initialized above.
1073            unsafe { core::ptr::drop_in_place(slot) })
1074    }
1075}
1076
1077// SAFETY: `__pinned_init` behaves exactly the same as `__init`.
1078unsafe impl<T: ?Sized, E, I, F> PinInit<T, E> for ChainInit<I, F, T, E>
1079where
1080    I: Init<T, E>,
1081    F: FnOnce(&mut T) -> Result<(), E>,
1082{
1083    unsafe fn __pinned_init(self, slot: *mut T) -> Result<(), E> {
1084        // SAFETY: `__init` has less strict requirements compared to `__pinned_init`.
1085        unsafe { self.__init(slot) }
1086    }
1087}
1088
1089/// Implement `PinInit` and `Init` for closures.
1090///
1091/// It is unsafe to create this type, since the closure needs to fulfill the same safety
1092/// requirement as the `__pinned_init`/`__init` functions.
1093struct InitClosure<F, T: ?Sized>(F, __internal::PhantomInvariant<T>);
1094
1095// SAFETY: While constructing the `InitClosure`, the user promised that it upholds the
1096// `__init` invariants.
1097unsafe impl<T: ?Sized, F, E> Init<T, E> for InitClosure<F, T>
1098where
1099    F: FnOnce(*mut T) -> Result<(), E>,
1100{
1101    #[inline]
1102    unsafe fn __init(self, slot: *mut T) -> Result<(), E> {
1103        (self.0)(slot)
1104    }
1105}
1106
1107// SAFETY: While constructing the `InitClosure`, the user promised that it upholds the
1108// `__pinned_init` invariants.
1109unsafe impl<T: ?Sized, F, E> PinInit<T, E> for InitClosure<F, T>
1110where
1111    F: FnOnce(*mut T) -> Result<(), E>,
1112{
1113    #[inline]
1114    unsafe fn __pinned_init(self, slot: *mut T) -> Result<(), E> {
1115        (self.0)(slot)
1116    }
1117}
1118
1119/// Creates a new [`PinInit<T, E>`] from the given closure.
1120///
1121/// # Safety
1122///
1123/// The closure:
1124/// - returns `Ok(())` if it initialized every field of `slot`,
1125/// - returns `Err(err)` if it encountered an error and then cleaned `slot`, this means:
1126///     - `slot` can be deallocated without UB occurring,
1127///     - `slot` does not need to be dropped,
1128///     - `slot` is not partially initialized.
1129/// - may assume that the `slot` does not move if `T: !Unpin`,
1130/// - while constructing the `T` at `slot` it upholds the pinning invariants of `T`.
1131#[inline]
1132pub const unsafe fn pin_init_from_closure<T: ?Sized, E>(
1133    f: impl FnOnce(*mut T) -> Result<(), E>,
1134) -> impl PinInit<T, E> {
1135    InitClosure(f, __internal::PhantomInvariant::new())
1136}
1137
1138/// Creates a new [`Init<T, E>`] from the given closure.
1139///
1140/// # Safety
1141///
1142/// The closure:
1143/// - returns `Ok(())` if it initialized every field of `slot`,
1144/// - returns `Err(err)` if it encountered an error and then cleaned `slot`, this means:
1145///     - `slot` can be deallocated without UB occurring,
1146///     - `slot` does not need to be dropped,
1147///     - `slot` is not partially initialized.
1148/// - the `slot` may move after initialization.
1149/// - while constructing the `T` at `slot` it upholds the pinning invariants of `T`.
1150#[inline]
1151pub const unsafe fn init_from_closure<T: ?Sized, E>(
1152    f: impl FnOnce(*mut T) -> Result<(), E>,
1153) -> impl Init<T, E> {
1154    InitClosure(f, __internal::PhantomInvariant::new())
1155}
1156
1157/// Changes the to be initialized type.
1158///
1159/// # Safety
1160///
1161/// - `*mut U` must be castable to `*mut T` and any value of type `T` written through such a
1162///   pointer must result in a valid `U`.
1163pub const unsafe fn cast_pin_init<T, U, E>(init: impl PinInit<T, E>) -> impl PinInit<U, E> {
1164    // SAFETY: initialization delegated to a valid initializer. Cast is valid by function safety
1165    // requirements.
1166    unsafe { pin_init_from_closure(|ptr: *mut U| init.__pinned_init(ptr.cast::<T>())) }
1167}
1168
1169/// Changes the to be initialized type.
1170///
1171/// # Safety
1172///
1173/// - `*mut U` must be castable to `*mut T` and any value of type `T` written through such a
1174///   pointer must result in a valid `U`.
1175pub const unsafe fn cast_init<T, U, E>(init: impl Init<T, E>) -> impl Init<U, E> {
1176    // SAFETY: initialization delegated to a valid initializer. Cast is valid by function safety
1177    // requirements.
1178    unsafe { init_from_closure(|ptr: *mut U| init.__init(ptr.cast::<T>())) }
1179}
1180
1181/// An initializer that leaves the memory uninitialized.
1182///
1183/// The initializer is a no-op. The `slot` memory is not changed.
1184#[inline]
1185pub fn uninit<T, E>() -> impl Init<MaybeUninit<T>, E> {
1186    // SAFETY: The memory is allowed to be uninitialized.
1187    unsafe { init_from_closure(|_| Ok(())) }
1188}
1189
1190/// Initializes an array by initializing each element via the provided initializer.
1191///
1192/// # Examples
1193///
1194/// ```rust
1195/// # use pin_init::*;
1196/// use pin_init::init_array_from_fn;
1197/// let array: Box<[usize; 1_000]> = Box::init(init_array_from_fn(|i| i)).unwrap();
1198/// assert_eq!(array.len(), 1_000);
1199/// ```
1200pub fn init_array_from_fn<I, const N: usize, T, E>(
1201    mut make_init: impl FnMut(usize) -> I,
1202) -> impl Init<[T; N], E>
1203where
1204    I: Init<T, E>,
1205{
1206    let init = move |slot: *mut [T; N]| {
1207        let slot = slot.cast::<T>();
1208        for i in 0..N {
1209            let init = make_init(i);
1210            // SAFETY: Since 0 <= `i` < N, it is still in bounds of `[T; N]`.
1211            let ptr = unsafe { slot.add(i) };
1212            // SAFETY: The pointer is derived from `slot` and thus satisfies the `__init`
1213            // requirements.
1214            if let Err(e) = unsafe { init.__init(ptr) } {
1215                // SAFETY: The loop has initialized the elements `slot[0..i]` and since we return
1216                // `Err` below, `slot` will be considered uninitialized memory.
1217                unsafe { ptr::drop_in_place(ptr::slice_from_raw_parts_mut(slot, i)) };
1218                return Err(e);
1219            }
1220        }
1221        Ok(())
1222    };
1223    // SAFETY: The initializer above initializes every element of the array. On failure it drops
1224    // any initialized elements and returns `Err`.
1225    unsafe { init_from_closure(init) }
1226}
1227
1228/// Initializes an array by initializing each element via the provided initializer.
1229///
1230/// # Examples
1231///
1232/// ```rust
1233/// # #![feature(allocator_api)]
1234/// # #[path = "../examples/mutex.rs"] mod mutex; use mutex::*;
1235/// # use pin_init::*;
1236/// # use core::pin::Pin;
1237/// use pin_init::pin_init_array_from_fn;
1238/// use std::sync::Arc;
1239/// let array: Pin<Arc<[CMutex<usize>; 1_000]>> =
1240///     Arc::pin_init(pin_init_array_from_fn(|i| CMutex::new(i))).unwrap();
1241/// assert_eq!(array.len(), 1_000);
1242/// ```
1243pub fn pin_init_array_from_fn<I, const N: usize, T, E>(
1244    mut make_init: impl FnMut(usize) -> I,
1245) -> impl PinInit<[T; N], E>
1246where
1247    I: PinInit<T, E>,
1248{
1249    let init = move |slot: *mut [T; N]| {
1250        let slot = slot.cast::<T>();
1251        for i in 0..N {
1252            let init = make_init(i);
1253            // SAFETY: Since 0 <= `i` < N, it is still in bounds of `[T; N]`.
1254            let ptr = unsafe { slot.add(i) };
1255            // SAFETY: The pointer is derived from `slot` and thus satisfies the `__init`
1256            // requirements.
1257            if let Err(e) = unsafe { init.__pinned_init(ptr) } {
1258                // SAFETY: The loop has initialized the elements `slot[0..i]` and since we return
1259                // `Err` below, `slot` will be considered uninitialized memory.
1260                unsafe { ptr::drop_in_place(ptr::slice_from_raw_parts_mut(slot, i)) };
1261                return Err(e);
1262            }
1263        }
1264        Ok(())
1265    };
1266    // SAFETY: The initializer above initializes every element of the array. On failure it drops
1267    // any initialized elements and returns `Err`.
1268    unsafe { pin_init_from_closure(init) }
1269}
1270
1271/// Construct an initializer in a closure and run it.
1272///
1273/// Returns an initializer that first runs the closure and then the initializer returned by it.
1274///
1275/// See also [`init_scope`].
1276///
1277/// # Examples
1278///
1279/// ```
1280/// # use pin_init::*;
1281/// # #[pin_data]
1282/// # struct Foo { a: u64, b: isize }
1283/// # struct Bar { a: u32, b: isize }
1284/// # fn lookup_bar() -> Result<Bar, Error> { todo!() }
1285/// # struct Error;
1286/// fn init_foo() -> impl PinInit<Foo, Error> {
1287///     pin_init_scope(|| {
1288///         let bar = lookup_bar()?;
1289///         Ok(pin_init!(Foo { a: bar.a.into(), b: bar.b }? Error))
1290///     })
1291/// }
1292/// ```
1293///
1294/// This initializer will first execute `lookup_bar()`, match on it, if it returned an error, the
1295/// initializer itself will fail with that error. If it returned `Ok`, then it will run the
1296/// initializer returned by the [`pin_init!`] invocation.
1297pub fn pin_init_scope<T, E, F, I>(make_init: F) -> impl PinInit<T, E>
1298where
1299    F: FnOnce() -> Result<I, E>,
1300    I: PinInit<T, E>,
1301{
1302    // SAFETY:
1303    // - If `make_init` returns `Err`, `Err` is returned and `slot` is completely uninitialized,
1304    // - If `make_init` returns `Ok`, safety requirement are fulfilled by `init.__pinned_init`.
1305    // - The safety requirements of `init.__pinned_init` are fulfilled, since it's being called
1306    //   from an initializer.
1307    unsafe {
1308        pin_init_from_closure(move |slot: *mut T| -> Result<(), E> {
1309            let init = make_init()?;
1310            init.__pinned_init(slot)
1311        })
1312    }
1313}
1314
1315/// Construct an initializer in a closure and run it.
1316///
1317/// Returns an initializer that first runs the closure and then the initializer returned by it.
1318///
1319/// See also [`pin_init_scope`].
1320///
1321/// # Examples
1322///
1323/// ```
1324/// # use pin_init::*;
1325/// # struct Foo { a: u64, b: isize }
1326/// # struct Bar { a: u32, b: isize }
1327/// # fn lookup_bar() -> Result<Bar, Error> { todo!() }
1328/// # struct Error;
1329/// fn init_foo() -> impl Init<Foo, Error> {
1330///     init_scope(|| {
1331///         let bar = lookup_bar()?;
1332///         Ok(init!(Foo { a: bar.a.into(), b: bar.b }? Error))
1333///     })
1334/// }
1335/// ```
1336///
1337/// This initializer will first execute `lookup_bar()`, match on it, if it returned an error, the
1338/// initializer itself will fail with that error. If it returned `Ok`, then it will run the
1339/// initializer returned by the [`init!`] invocation.
1340pub fn init_scope<T, E, F, I>(make_init: F) -> impl Init<T, E>
1341where
1342    F: FnOnce() -> Result<I, E>,
1343    I: Init<T, E>,
1344{
1345    // SAFETY:
1346    // - If `make_init` returns `Err`, `Err` is returned and `slot` is completely uninitialized,
1347    // - If `make_init` returns `Ok`, safety requirement are fulfilled by `init.__init`.
1348    // - The safety requirements of `init.__init` are fulfilled, since it's being called from an
1349    //   initializer.
1350    unsafe {
1351        init_from_closure(move |slot: *mut T| -> Result<(), E> {
1352            let init = make_init()?;
1353            init.__init(slot)
1354        })
1355    }
1356}
1357
1358// SAFETY: the `__init` function always returns `Ok(())` and initializes every field of `slot`.
1359unsafe impl<T> Init<T> for T {
1360    unsafe fn __init(self, slot: *mut T) -> Result<(), Infallible> {
1361        // SAFETY: `slot` is valid for writes by the safety requirements of this function.
1362        unsafe { slot.write(self) };
1363        Ok(())
1364    }
1365}
1366
1367// SAFETY: the `__pinned_init` function always returns `Ok(())` and initializes every field of
1368// `slot`. Additionally, all pinning invariants of `T` are upheld.
1369unsafe impl<T> PinInit<T> for T {
1370    unsafe fn __pinned_init(self, slot: *mut T) -> Result<(), Infallible> {
1371        // SAFETY: `slot` is valid for writes by the safety requirements of this function.
1372        unsafe { slot.write(self) };
1373        Ok(())
1374    }
1375}
1376
1377// SAFETY: when the `__init` function returns with
1378// - `Ok(())`, `slot` was initialized and all pinned invariants of `T` are upheld.
1379// - `Err(err)`, slot was not written to.
1380unsafe impl<T, E> Init<T, E> for Result<T, E> {
1381    unsafe fn __init(self, slot: *mut T) -> Result<(), E> {
1382        // SAFETY: `slot` is valid for writes by the safety requirements of this function.
1383        unsafe { slot.write(self?) };
1384        Ok(())
1385    }
1386}
1387
1388// SAFETY: when the `__pinned_init` function returns with
1389// - `Ok(())`, `slot` was initialized and all pinned invariants of `T` are upheld.
1390// - `Err(err)`, slot was not written to.
1391unsafe impl<T, E> PinInit<T, E> for Result<T, E> {
1392    unsafe fn __pinned_init(self, slot: *mut T) -> Result<(), E> {
1393        // SAFETY: `slot` is valid for writes by the safety requirements of this function.
1394        unsafe { slot.write(self?) };
1395        Ok(())
1396    }
1397}
1398
1399/// Smart pointer containing uninitialized memory and that can write a value.
1400pub trait InPlaceWrite<T> {
1401    /// The type `Self` turns into when the contents are initialized.
1402    type Initialized;
1403
1404    /// Use the given initializer to write a value into `self`.
1405    ///
1406    /// Does not drop the current value and considers it as uninitialized memory.
1407    fn write_init<E>(self, init: impl Init<T, E>) -> Result<Self::Initialized, E>;
1408
1409    /// Use the given pin-initializer to write a value into `self`.
1410    ///
1411    /// Does not drop the current value and considers it as uninitialized memory.
1412    fn write_pin_init<E>(self, init: impl PinInit<T, E>) -> Result<Pin<Self::Initialized>, E>;
1413}
1414
1415impl<T> InPlaceWrite<T> for &'static mut MaybeUninit<T> {
1416    type Initialized = &'static mut T;
1417
1418    fn write_init<E>(self, init: impl Init<T, E>) -> Result<Self::Initialized, E> {
1419        let slot = self.as_mut_ptr();
1420
1421        // SAFETY: `slot` is a valid pointer to uninitialized memory.
1422        unsafe { init.__init(slot)? };
1423
1424        // SAFETY: The above call initialized the memory.
1425        unsafe { Ok(self.assume_init_mut()) }
1426    }
1427
1428    fn write_pin_init<E>(self, init: impl PinInit<T, E>) -> Result<Pin<Self::Initialized>, E> {
1429        let slot = self.as_mut_ptr();
1430
1431        // SAFETY: `slot` is a valid pointer to uninitialized memory.
1432        //
1433        // The `'static` borrow guarantees the data will not be
1434        // moved/invalidated until it gets dropped (which is never).
1435        unsafe { init.__pinned_init(slot)? };
1436
1437        // SAFETY: The above call initialized the memory.
1438        Ok(Pin::static_mut(unsafe { self.assume_init_mut() }))
1439    }
1440}
1441
1442/// Trait facilitating pinned destruction.
1443///
1444/// Use [`pinned_drop`] to implement this trait safely:
1445///
1446/// ```rust
1447/// # #![feature(allocator_api)]
1448/// # #[path = "../examples/mutex.rs"] mod mutex; use mutex::*;
1449/// # use pin_init::*;
1450/// use core::pin::Pin;
1451/// #[pin_data(PinnedDrop)]
1452/// struct Foo {
1453///     #[pin]
1454///     mtx: CMutex<usize>,
1455/// }
1456///
1457/// #[pinned_drop]
1458/// impl PinnedDrop for Foo {
1459///     fn drop(self: Pin<&mut Self>) {
1460///         println!("Foo is being dropped!");
1461///     }
1462/// }
1463/// ```
1464///
1465/// # Safety
1466///
1467/// This trait must be implemented via the [`pinned_drop`] proc-macro attribute on the impl.
1468pub unsafe trait PinnedDrop: __internal::HasPinData {
1469    /// Executes the pinned destructor of this type.
1470    ///
1471    /// While this function is marked safe, it is actually unsafe to call it manually. For this
1472    /// reason it takes an additional parameter. This type can only be constructed by `unsafe` code
1473    /// and thus prevents this function from being called where it should not.
1474    ///
1475    /// This extra parameter will be generated by the `#[pinned_drop]` proc-macro attribute
1476    /// automatically.
1477    fn drop(self: Pin<&mut Self>, only_call_from_drop: __internal::OnlyCallFromDrop);
1478}
1479
1480/// Marker trait for types that can be initialized by writing just zeroes.
1481///
1482/// # Safety
1483///
1484/// The bit pattern consisting of only zeroes is a valid bit pattern for this type. In other words,
1485/// this is not UB:
1486///
1487/// ```rust,ignore
1488/// let val: Self = unsafe { core::mem::zeroed() };
1489/// ```
1490pub unsafe trait Zeroable {
1491    /// Create a new zeroed `Self`.
1492    ///
1493    /// The returned initializer will write `0x00` to every byte of the given `slot`.
1494    #[inline]
1495    fn init_zeroed() -> impl Init<Self>
1496    where
1497        Self: Sized,
1498    {
1499        init_zeroed()
1500    }
1501
1502    /// Create a `Self` consisting of all zeroes.
1503    ///
1504    /// Whenever a type implements [`Zeroable`], this function should be preferred over
1505    /// [`core::mem::zeroed()`] or using `MaybeUninit<T>::zeroed().assume_init()`.
1506    ///
1507    /// # Examples
1508    ///
1509    /// ```
1510    /// use pin_init::{Zeroable, zeroed};
1511    ///
1512    /// #[derive(Zeroable)]
1513    /// struct Point {
1514    ///     x: u32,
1515    ///     y: u32,
1516    /// }
1517    ///
1518    /// let point: Point = zeroed();
1519    /// assert_eq!(point.x, 0);
1520    /// assert_eq!(point.y, 0);
1521    /// ```
1522    fn zeroed() -> Self
1523    where
1524        Self: Sized,
1525    {
1526        zeroed()
1527    }
1528}
1529
1530/// Create an initializer for a zeroed `T`.
1531///
1532/// The returned initializer will write `0x00` to every byte of the given `slot`.
1533#[inline]
1534pub fn init_zeroed<T: Zeroable>() -> impl Init<T> {
1535    // SAFETY: Because `T: Zeroable`, all bytes zero is a valid bit pattern for `T`
1536    // and because we write all zeroes, the memory is initialized.
1537    unsafe {
1538        init_from_closure(|slot: *mut T| {
1539            slot.write_bytes(0, 1);
1540            Ok(())
1541        })
1542    }
1543}
1544
1545/// Create a `T` consisting of all zeroes.
1546///
1547/// Whenever a type implements [`Zeroable`], this function should be preferred over
1548/// [`core::mem::zeroed()`] or using `MaybeUninit<T>::zeroed().assume_init()`.
1549///
1550/// # Examples
1551///
1552/// ```
1553/// use pin_init::{Zeroable, zeroed};
1554///
1555/// #[derive(Zeroable)]
1556/// struct Point {
1557///     x: u32,
1558///     y: u32,
1559/// }
1560///
1561/// let point: Point = zeroed();
1562/// assert_eq!(point.x, 0);
1563/// assert_eq!(point.y, 0);
1564/// ```
1565pub const fn zeroed<T: Zeroable>() -> T {
1566    // SAFETY:By the type invariants of `Zeroable`, all zeroes is a valid bit pattern for `T`.
1567    unsafe { core::mem::zeroed() }
1568}
1569
1570macro_rules! impl_zeroable {
1571    ($($({$($generics:tt)*})? $t:ty, )*) => {
1572        // SAFETY: Safety comments written in the macro invocation.
1573        $(unsafe impl$($($generics)*)? Zeroable for $t {})*
1574    };
1575}
1576
1577impl_zeroable! {
1578    // SAFETY: All primitives that are allowed to be zero.
1579    bool,
1580    char,
1581    u8, u16, u32, u64, u128, usize,
1582    i8, i16, i32, i64, i128, isize,
1583    f32, f64,
1584
1585    // Note: do not add uninhabited types (such as `!` or `core::convert::Infallible`) to this list;
1586    // creating an instance of an uninhabited type is immediate undefined behavior. For more on
1587    // uninhabited/empty types, consult The Rustonomicon:
1588    // <https://doc.rust-lang.org/stable/nomicon/exotic-sizes.html#empty-types>. The Rust Reference
1589    // also has information on undefined behavior:
1590    // <https://doc.rust-lang.org/stable/reference/behavior-considered-undefined.html>.
1591    //
1592    // SAFETY: These are inhabited ZSTs; there is nothing to zero and a valid value exists.
1593    {<T: ?Sized>} PhantomData<T>, core::marker::PhantomPinned, (),
1594
1595    // SAFETY: Type is allowed to take any value, including all zeros.
1596    {<T>} MaybeUninit<T>,
1597
1598    // SAFETY: `T: Zeroable` and `UnsafeCell` is `repr(transparent)`.
1599    {<T: ?Sized + Zeroable>} UnsafeCell<T>,
1600
1601    // SAFETY: `null` pointer is valid.
1602    //
1603    // We cannot use `T: ?Sized`, since the VTABLE pointer part of fat pointers is not allowed to be
1604    // null.
1605    //
1606    // When `Pointee` gets stabilized, we could use
1607    // `T: ?Sized where <T as Pointee>::Metadata: Zeroable`
1608    {<T>} *mut T, {<T>} *const T,
1609
1610    // SAFETY: `null` pointer is valid and the metadata part of these fat pointers is allowed to be
1611    // zero.
1612    {<T>} *mut [T], {<T>} *const [T], *mut str, *const str,
1613
1614    // SAFETY: `T` is `Zeroable`.
1615    {<const N: usize, T: Zeroable>} [T; N], {<T: Zeroable>} Wrapping<T>,
1616}
1617
1618macro_rules! impl_tuple_zeroable {
1619    ($first:ident, $(,)?) => {
1620        #[cfg_attr(all(USE_RUSTC_FEATURES, doc), doc(fake_variadic))]
1621        /// Implemented for tuples up to 10 items long.
1622        // SAFETY: All elements are zeroable and padding can be zero.
1623        unsafe impl<$first: Zeroable> Zeroable for ($first,) {}
1624    };
1625    ($first:ident, $($t:ident),* $(,)?) => {
1626        #[cfg_attr(doc, doc(hidden))]
1627        // SAFETY: All elements are zeroable and padding can be zero.
1628        unsafe impl<$first: Zeroable, $($t: Zeroable),*> Zeroable for ($first, $($t),*) {}
1629        impl_tuple_zeroable!($($t),* ,);
1630    }
1631}
1632
1633impl_tuple_zeroable!(A, B, C, D, E, F, G, H, I, J);
1634
1635/// Marker trait for types that allow `Option<Self>` to be set to all zeroes in order to write
1636/// `None` to that location.
1637///
1638/// # Safety
1639///
1640/// The implementer needs to ensure that `unsafe impl Zeroable for Option<Self> {}` is sound.
1641pub unsafe trait ZeroableOption {}
1642
1643// SAFETY: by the safety requirement of `ZeroableOption`, this is valid.
1644unsafe impl<T: ZeroableOption> Zeroable for Option<T> {}
1645
1646macro_rules! impl_fn_zeroable_option {
1647    ([$($abi:literal),* $(,)?] $args:tt) => {
1648        $(impl_fn_zeroable_option!({extern $abi} $args);)*
1649        $(impl_fn_zeroable_option!({unsafe extern $abi} $args);)*
1650    };
1651    ({$($prefix:tt)*} {$(,)?}) => {};
1652    ({$($prefix:tt)*} {$ret:ident, $arg:ident $(,)?}) => {
1653        #[cfg_attr(all(USE_RUSTC_FEATURES, doc), doc(fake_variadic))]
1654        /// Implemented for function pointers with up to 20 arity.
1655        // SAFETY: function pointers are part of the option layout optimization:
1656        // <https://doc.rust-lang.org/stable/std/option/index.html#representation>.
1657        unsafe impl<$ret, $arg> ZeroableOption for $($prefix)* fn($arg) -> $ret {}
1658        impl_fn_zeroable_option!({$($prefix)*} {$arg,});
1659    };
1660    ({$($prefix:tt)*} {$ret:ident, $($rest:ident),* $(,)?}) => {
1661        #[cfg_attr(doc, doc(hidden))]
1662        // SAFETY: function pointers are part of the option layout optimization:
1663        // <https://doc.rust-lang.org/stable/std/option/index.html#representation>.
1664        unsafe impl<$ret, $($rest),*> ZeroableOption for $($prefix)* fn($($rest),*) -> $ret {}
1665        impl_fn_zeroable_option!({$($prefix)*} {$($rest),*,});
1666    };
1667}
1668
1669impl_fn_zeroable_option!(["Rust", "C"] { A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U });
1670
1671macro_rules! impl_zeroable_option {
1672    ($($({$($generics:tt)*})? $t:ty, )*) => {
1673        // SAFETY: Safety comments written in the macro invocation.
1674        $(unsafe impl$($($generics)*)? ZeroableOption for $t {})*
1675    };
1676}
1677
1678impl_zeroable_option! {
1679    // SAFETY: `Option<&T>` is part of the option layout optimization guarantee:
1680    // <https://doc.rust-lang.org/stable/std/option/index.html#representation>.
1681    {<T: ?Sized>} &T,
1682    // SAFETY: `Option<&mut T>` is part of the option layout optimization guarantee:
1683    // <https://doc.rust-lang.org/stable/std/option/index.html#representation>.
1684    {<T: ?Sized>} &mut T,
1685    // SAFETY: `Option<NonNull<T>>` is part of the option layout optimization guarantee:
1686    // <https://doc.rust-lang.org/stable/std/option/index.html#representation>.
1687    {<T: ?Sized>} NonNull<T>,
1688    // SAFETY: All zeros is equivalent to `None` (option layout optimization guarantee:
1689    // <https://doc.rust-lang.org/stable/std/option/index.html#representation>).
1690    NonZero<u8>, NonZero<u16>, NonZero<u32>, NonZero<u64>, NonZero<u128>, NonZero<usize>,
1691    NonZero<i8>, NonZero<i16>, NonZero<i32>, NonZero<i64>, NonZero<i128>, NonZero<isize>,
1692}
1693
1694/// This trait allows creating an instance of `Self` which contains exactly one
1695/// [structurally pinned value](https://doc.rust-lang.org/std/pin/index.html#projections-and-structural-pinning).
1696///
1697/// This is useful when using wrapper `struct`s like [`UnsafeCell`] or with new-type `struct`s.
1698///
1699/// # Examples
1700///
1701/// ```
1702/// # use core::cell::UnsafeCell;
1703/// # use pin_init::{pin_data, pin_init, Wrapper};
1704///
1705/// #[pin_data]
1706/// struct Foo {}
1707///
1708/// #[pin_data]
1709/// struct Bar {
1710///     #[pin]
1711///     content: UnsafeCell<Foo>
1712/// };
1713///
1714/// let foo_initializer = pin_init!(Foo{});
1715/// let initializer = pin_init!(Bar {
1716///     content <- UnsafeCell::pin_init(foo_initializer)
1717/// });
1718/// ```
1719pub trait Wrapper<T> {
1720    /// Creates an pin-initializer for a [`Self`] containing `T` from the `value_init` initializer.
1721    fn pin_init<E>(value_init: impl PinInit<T, E>) -> impl PinInit<Self, E>;
1722}
1723
1724impl<T> Wrapper<T> for UnsafeCell<T> {
1725    fn pin_init<E>(value_init: impl PinInit<T, E>) -> impl PinInit<Self, E> {
1726        // SAFETY: `UnsafeCell<T>` has a compatible layout to `T`.
1727        unsafe { cast_pin_init(value_init) }
1728    }
1729}
1730
1731impl<T> Wrapper<T> for MaybeUninit<T> {
1732    fn pin_init<E>(value_init: impl PinInit<T, E>) -> impl PinInit<Self, E> {
1733        // SAFETY: `MaybeUninit<T>` has a compatible layout to `T`.
1734        unsafe { cast_pin_init(value_init) }
1735    }
1736}
1737
1738#[cfg(all(feature = "unsafe-pinned", CONFIG_RUSTC_HAS_UNSAFE_PINNED))]
1739impl<T> Wrapper<T> for core::pin::UnsafePinned<T> {
1740    fn pin_init<E>(init: impl PinInit<T, E>) -> impl PinInit<Self, E> {
1741        // SAFETY: `UnsafePinned<T>` has a compatible layout to `T`.
1742        unsafe { cast_pin_init(init) }
1743    }
1744}