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//! # #![feature(allocator_api)]
74//! # #[path = "../examples/mutex.rs"] mod mutex; use mutex::*;
75//! # use core::pin::Pin;
76//! use pin_init::{pin_data, pin_init, InPlaceInit};
77//!
78//! #[pin_data]
79//! struct Foo {
80//!     #[pin]
81//!     a: CMutex<usize>,
82//!     b: u32,
83//! }
84//!
85//! let foo = pin_init!(Foo {
86//!     a <- CMutex::new(42),
87//!     b: 24,
88//! });
89//! # let _ = Box::pin_init(foo);
90//! ```
91//!
92//! `foo` now is of the type [`impl PinInit<Foo>`]. We can now use any smart pointer that we like
93//! (or just the stack) to actually initialize a `Foo`:
94//!
95//! ```rust
96//! # #![feature(allocator_api)]
97//! # #[path = "../examples/mutex.rs"] mod mutex; use mutex::*;
98//! # use core::{alloc::AllocError, pin::Pin};
99//! # use pin_init::*;
100//! #
101//! # #[pin_data]
102//! # struct Foo {
103//! #     #[pin]
104//! #     a: CMutex<usize>,
105//! #     b: u32,
106//! # }
107//! #
108//! # let foo = pin_init!(Foo {
109//! #     a <- CMutex::new(42),
110//! #     b: 24,
111//! # });
112//! let foo: Result<Pin<Box<Foo>>, AllocError> = Box::pin_init(foo);
113//! ```
114//!
115//! For more information see the [`pin_init!`] macro.
116//!
117//! ## Using a custom function/macro that returns an initializer
118//!
119//! Many types that use this library supply a function/macro that returns an initializer, because
120//! the above method only works for types where you can access the fields.
121//!
122//! ```rust
123//! # #![feature(allocator_api)]
124//! # #[path = "../examples/mutex.rs"] mod mutex; use mutex::*;
125//! # use pin_init::*;
126//! # use std::sync::Arc;
127//! # use core::pin::Pin;
128//! let mtx: Result<Pin<Arc<CMutex<usize>>>, _> = Arc::pin_init(CMutex::new(42));
129//! ```
130//!
131//! To declare an init macro/function you just return an [`impl PinInit<T, E>`]:
132//!
133//! ```rust
134//! # #![feature(allocator_api)]
135//! # use pin_init::*;
136//! # #[path = "../examples/error.rs"] mod error; use error::Error;
137//! # #[path = "../examples/mutex.rs"] mod mutex; use mutex::*;
138//! #[pin_data]
139//! struct DriverData {
140//!     #[pin]
141//!     status: CMutex<i32>,
142//!     buffer: Box<[u8; 1_000_000]>,
143//! }
144//!
145//! impl DriverData {
146//!     fn new() -> impl PinInit<Self, Error> {
147//!         pin_init!(Self {
148//!             status <- CMutex::new(0),
149//!             buffer: Box::init(pin_init::init_zeroed())?,
150//!         }? Error)
151//!     }
152//! }
153//! ```
154//!
155//! ## Manual creation of an initializer
156//!
157//! Often when working with primitives the previous approaches are not sufficient. That is where
158//! [`pin_init_from_closure()`] comes in. This `unsafe` function allows you to create a
159//! [`impl PinInit<T, E>`] directly from a closure. Of course you have to ensure that the closure
160//! actually does the initialization in the correct way. Here are the things to look out for
161//! (we are calling the parameter to the closure `slot`):
162//! - when the closure returns `Ok(())`, then it has completed the initialization successfully, so
163//!   `slot` now contains a valid bit pattern for the type `T`,
164//! - when the closure returns `Err(e)`, then the caller may deallocate the memory at `slot`, so
165//!   you need to take care to clean up anything if your initialization fails mid-way,
166//! - you may assume that `slot` will stay pinned even after the closure returns until `drop` of
167//!   `slot` gets called.
168//!
169//! ```rust
170//! # #![feature(extern_types)]
171//! use pin_init::{pin_data, pinned_drop, PinInit, PinnedDrop, pin_init_from_closure};
172//! use core::{
173//!     marker::PhantomPinned,
174//!     cell::UnsafeCell,
175//!     pin::Pin,
176//!     mem::MaybeUninit,
177//! };
178//! mod bindings {
179//!     #[repr(C)]
180//!     pub struct foo {
181//!         /* fields from C ... */
182//!     }
183//!     extern "C" {
184//!         pub fn init_foo(ptr: *mut foo);
185//!         pub fn destroy_foo(ptr: *mut foo);
186//!         #[must_use = "you must check the error return code"]
187//!         pub fn enable_foo(ptr: *mut foo, flags: u32) -> i32;
188//!     }
189//! }
190//!
191//! /// # Invariants
192//! ///
193//! /// `foo` is always initialized
194//! #[pin_data(PinnedDrop)]
195//! pub struct RawFoo {
196//!     #[pin]
197//!     _p: PhantomPinned,
198//!     #[pin]
199//!     foo: UnsafeCell<MaybeUninit<bindings::foo>>,
200//! }
201//!
202//! impl RawFoo {
203//!     pub fn new(flags: u32) -> impl PinInit<Self, i32> {
204//!         // SAFETY:
205//!         // - when the closure returns `Ok(())`, then it has successfully initialized and
206//!         //   enabled `foo`,
207//!         // - when it returns `Err(e)`, then it has cleaned up before
208//!         unsafe {
209//!             pin_init_from_closure(move |slot: *mut Self| {
210//!                 // `slot` contains uninit memory, avoid creating a reference.
211//!                 let foo = &raw mut (*slot).foo;
212//!                 let foo = UnsafeCell::raw_get(foo).cast::<bindings::foo>();
213//!
214//!                 // Initialize the `foo`
215//!                 bindings::init_foo(foo);
216//!
217//!                 // Try to enable it.
218//!                 let err = bindings::enable_foo(foo, flags);
219//!                 if err != 0 {
220//!                     // Enabling has failed, first clean up the foo and then return the error.
221//!                     bindings::destroy_foo(foo);
222//!                     Err(err)
223//!                 } else {
224//!                     // All fields of `RawFoo` have been initialized, since `_p` is a ZST.
225//!                     Ok(())
226//!                 }
227//!             })
228//!         }
229//!     }
230//! }
231//!
232//! #[pinned_drop]
233//! impl PinnedDrop for RawFoo {
234//!     fn drop(self: Pin<&mut Self>) {
235//!         // SAFETY: Since `foo` is initialized, destroying is safe.
236//!         unsafe { bindings::destroy_foo(self.foo.get().cast::<bindings::foo>()) };
237//!     }
238//! }
239//! ```
240//!
241//! For more information on how to use [`pin_init_from_closure()`], take a look at the uses inside
242//! the `kernel` crate. The [`sync`] module is a good starting point.
243//!
244//! [`sync`]: https://rust.docs.kernel.org/kernel/sync/index.html
245//! [pinning]: https://doc.rust-lang.org/std/pin/index.html
246//! [structurally pinned fields]:
247//!     https://doc.rust-lang.org/std/pin/index.html#projections-and-structural-pinning
248//! [stack]: crate::stack_pin_init
249#![cfg_attr(
250    kernel,
251    doc = "[`Arc<T>`]: https://rust.docs.kernel.org/kernel/sync/struct.Arc.html"
252)]
253#![cfg_attr(
254    kernel,
255    doc = "[`Box<T>`]: https://rust.docs.kernel.org/kernel/alloc/kbox/struct.Box.html"
256)]
257#![cfg_attr(not(kernel), doc = "[`Arc<T>`]: alloc::alloc::sync::Arc")]
258#![cfg_attr(not(kernel), doc = "[`Box<T>`]: alloc::alloc::boxed::Box")]
259//! [`impl PinInit<Foo>`]: crate::PinInit
260//! [`impl PinInit<T, E>`]: crate::PinInit
261//! [`impl Init<T, E>`]: crate::Init
262//! [Rust-for-Linux]: https://rust-for-linux.com/
263
264#![forbid(missing_docs, unsafe_op_in_unsafe_fn)]
265#![cfg_attr(not(feature = "std"), no_std)]
266#![cfg_attr(feature = "alloc", feature(allocator_api))]
267#![cfg_attr(
268    all(feature = "unsafe-pinned", CONFIG_RUSTC_HAS_UNSAFE_PINNED),
269    feature(unsafe_pinned)
270)]
271#![cfg_attr(all(USE_RUSTC_FEATURES, doc), allow(internal_features))]
272#![cfg_attr(all(USE_RUSTC_FEATURES, doc), feature(rustdoc_internals))]
273
274use core::{
275    cell::UnsafeCell,
276    convert::Infallible,
277    marker::PhantomData,
278    mem::MaybeUninit,
279    num::*,
280    pin::Pin,
281    ptr::{self, NonNull},
282};
283
284// This is used by doc-tests -- the proc-macros expand to `::pin_init::...` and without this the
285// doc-tests wouldn't have an extern crate named `pin_init`.
286#[allow(unused_extern_crates)]
287extern crate self as pin_init;
288
289#[doc(hidden)]
290pub mod __internal;
291
292#[cfg(any(feature = "std", feature = "alloc"))]
293mod alloc;
294#[cfg(any(feature = "std", feature = "alloc"))]
295pub use alloc::InPlaceInit;
296
297/// Used to specify the pinning information of the fields of a struct.
298///
299/// This is somewhat similar in purpose as
300/// [pin-project-lite](https://crates.io/crates/pin-project-lite).
301/// Place this macro on a struct definition and then `#[pin]` in front of the attributes of each
302/// field you want to structurally pin.
303///
304/// This macro enables the use of the [`pin_init!`] macro. When pin-initializing a `struct`,
305/// then `#[pin]` directs the type of initializer that is required.
306///
307/// If your `struct` implements `Drop`, then you need to add `PinnedDrop` as arguments to this
308/// macro, and change your `Drop` implementation to `PinnedDrop` annotated with
309/// `#[`[`macro@pinned_drop`]`]`, since dropping pinned values requires extra care.
310///
311/// # Examples
312///
313/// ```
314/// # #![feature(allocator_api)]
315/// # #[path = "../examples/mutex.rs"] mod mutex; use mutex::*;
316/// use pin_init::pin_data;
317///
318/// enum Command {
319///     /* ... */
320/// }
321///
322/// #[pin_data]
323/// struct DriverData {
324///     #[pin]
325///     queue: CMutex<Vec<Command>>,
326///     buf: Box<[u8; 1024 * 1024]>,
327/// }
328/// ```
329///
330/// ```
331/// # #![feature(allocator_api)]
332/// # #[path = "../examples/mutex.rs"] mod mutex; use mutex::*;
333/// # mod bindings { pub struct info; pub unsafe fn destroy_info(_: *mut info) {} }
334/// use core::pin::Pin;
335/// use pin_init::{pin_data, pinned_drop, PinnedDrop};
336///
337/// enum Command {
338///     /* ... */
339/// }
340///
341/// #[pin_data(PinnedDrop)]
342/// struct DriverData {
343///     #[pin]
344///     queue: CMutex<Vec<Command>>,
345///     buf: Box<[u8; 1024 * 1024]>,
346///     raw_info: *mut bindings::info,
347/// }
348///
349/// #[pinned_drop]
350/// impl PinnedDrop for DriverData {
351///     fn drop(self: Pin<&mut Self>) {
352///         unsafe { bindings::destroy_info(self.raw_info) };
353///     }
354/// }
355/// ```
356pub use ::pin_init_internal::pin_data;
357
358/// Used to implement `PinnedDrop` safely.
359///
360/// Only works on structs that are annotated via `#[`[`macro@pin_data`]`]`.
361///
362/// # Examples
363///
364/// ```
365/// # #![feature(allocator_api)]
366/// # #[path = "../examples/mutex.rs"] mod mutex; use mutex::*;
367/// # mod bindings { pub struct info; pub unsafe fn destroy_info(_: *mut info) {} }
368/// use core::pin::Pin;
369/// use pin_init::{pin_data, pinned_drop, PinnedDrop};
370///
371/// enum Command {
372///     /* ... */
373/// }
374///
375/// #[pin_data(PinnedDrop)]
376/// struct DriverData {
377///     #[pin]
378///     queue: CMutex<Vec<Command>>,
379///     buf: Box<[u8; 1024 * 1024]>,
380///     raw_info: *mut bindings::info,
381/// }
382///
383/// #[pinned_drop]
384/// impl PinnedDrop for DriverData {
385///     fn drop(self: Pin<&mut Self>) {
386///         unsafe { bindings::destroy_info(self.raw_info) };
387///     }
388/// }
389/// ```
390pub use ::pin_init_internal::pinned_drop;
391
392/// Derives the [`Zeroable`] trait for the given `struct` or `union`.
393///
394/// This can only be used for `struct`s/`union`s where every field implements the [`Zeroable`]
395/// trait.
396///
397/// # Examples
398///
399/// ```
400/// use pin_init::Zeroable;
401///
402/// #[derive(Zeroable)]
403/// pub struct DriverData {
404///     pub(crate) id: i64,
405///     buf_ptr: *mut u8,
406///     len: usize,
407/// }
408/// ```
409///
410/// ```
411/// use pin_init::Zeroable;
412///
413/// #[derive(Zeroable)]
414/// pub union SignCast {
415///     signed: i64,
416///     unsigned: u64,
417/// }
418/// ```
419pub use ::pin_init_internal::Zeroable;
420
421/// Derives the [`Zeroable`] trait for the given `struct` or `union` if all fields implement
422/// [`Zeroable`].
423///
424/// Contrary to the derive macro named [`macro@Zeroable`], this one silently fails when a field
425/// doesn't implement [`Zeroable`].
426///
427/// # Examples
428///
429/// ```
430/// use pin_init::MaybeZeroable;
431///
432/// // implements `Zeroable`
433/// #[derive(MaybeZeroable)]
434/// pub struct DriverData {
435///     pub(crate) id: i64,
436///     buf_ptr: *mut u8,
437///     len: usize,
438/// }
439///
440/// // does not implement `Zeroable`
441/// #[derive(MaybeZeroable)]
442/// pub struct DriverData2 {
443///     pub(crate) id: i64,
444///     buf_ptr: *mut u8,
445///     len: usize,
446///     // this field doesn't implement `Zeroable`
447///     other_data: &'static i32,
448/// }
449/// ```
450pub use ::pin_init_internal::MaybeZeroable;
451
452/// Initialize and pin a type directly on the stack.
453///
454/// # Examples
455///
456/// ```rust
457/// # #![feature(allocator_api)]
458/// # #[path = "../examples/mutex.rs"] mod mutex; use mutex::*;
459/// # use pin_init::*;
460/// # use core::pin::Pin;
461/// #[pin_data]
462/// struct Foo {
463///     #[pin]
464///     a: CMutex<usize>,
465///     b: Bar,
466/// }
467///
468/// #[pin_data]
469/// struct Bar {
470///     x: u32,
471/// }
472///
473/// stack_pin_init!(let foo = pin_init!(Foo {
474///     a <- CMutex::new(42),
475///     b: Bar {
476///         x: 64,
477///     },
478/// }));
479/// let foo: Pin<&mut Foo> = foo;
480/// println!("a: {}", &*foo.a.lock());
481/// ```
482///
483/// # Syntax
484///
485/// A normal `let` binding with optional type annotation. The expression is expected to implement
486/// [`PinInit`]/[`Init`] with the error type [`Infallible`]. If you want to use a different error
487/// type, then use [`stack_try_pin_init!`].
488#[macro_export]
489macro_rules! stack_pin_init {
490    (let $var:ident $(: $t:ty)? = $val:expr) => {
491        let val = $val;
492        let mut $var = ::core::pin::pin!($crate::__internal::StackInit$(::<$t>)?::uninit());
493        let mut $var = match $crate::__internal::StackInit::init($var, val) {
494            Ok(res) => res,
495            Err(x) => {
496                let x: ::core::convert::Infallible = x;
497                match x {}
498            }
499        };
500    };
501}
502
503/// Initialize and pin a type directly on the stack.
504///
505/// # Examples
506///
507/// ```rust
508/// # #![feature(allocator_api)]
509/// # #[path = "../examples/error.rs"] mod error; use error::Error;
510/// # #[path = "../examples/mutex.rs"] mod mutex; use mutex::*;
511/// # use pin_init::*;
512/// #[pin_data]
513/// struct Foo {
514///     #[pin]
515///     a: CMutex<usize>,
516///     b: Box<Bar>,
517/// }
518///
519/// struct Bar {
520///     x: u32,
521/// }
522///
523/// stack_try_pin_init!(let foo: Foo = pin_init!(Foo {
524///     a <- CMutex::new(42),
525///     b: Box::try_new(Bar {
526///         x: 64,
527///     })?,
528/// }? Error));
529/// let foo = foo.unwrap();
530/// println!("a: {}", &*foo.a.lock());
531/// ```
532///
533/// ```rust
534/// # #![feature(allocator_api)]
535/// # #[path = "../examples/error.rs"] mod error; use error::Error;
536/// # #[path = "../examples/mutex.rs"] mod mutex; use mutex::*;
537/// # use pin_init::*;
538/// #[pin_data]
539/// struct Foo {
540///     #[pin]
541///     a: CMutex<usize>,
542///     b: Box<Bar>,
543/// }
544///
545/// struct Bar {
546///     x: u32,
547/// }
548///
549/// stack_try_pin_init!(let foo: Foo =? pin_init!(Foo {
550///     a <- CMutex::new(42),
551///     b: Box::try_new(Bar {
552///         x: 64,
553///     })?,
554/// }? Error));
555/// println!("a: {}", &*foo.a.lock());
556/// # Ok::<_, Error>(())
557/// ```
558///
559/// # Syntax
560///
561/// A normal `let` binding with optional type annotation. The expression is expected to implement
562/// [`PinInit`]/[`Init`]. This macro assigns a result to the given variable, adding a `?` after the
563/// `=` will propagate this error.
564#[macro_export]
565macro_rules! stack_try_pin_init {
566    (let $var:ident $(: $t:ty)? = $val:expr) => {
567        let val = $val;
568        let mut $var = ::core::pin::pin!($crate::__internal::StackInit$(::<$t>)?::uninit());
569        let mut $var = $crate::__internal::StackInit::init($var, val);
570    };
571    (let $var:ident $(: $t:ty)? =? $val:expr) => {
572        let val = $val;
573        let mut $var = ::core::pin::pin!($crate::__internal::StackInit$(::<$t>)?::uninit());
574        let mut $var = $crate::__internal::StackInit::init($var, val)?;
575    };
576}
577
578/// Construct an in-place, fallible pinned initializer for `struct`s.
579///
580/// The error type defaults to [`Infallible`]; if you need a different one, write `? Error` at the
581/// end, after the struct initializer.
582///
583/// The syntax is almost identical to that of a normal `struct` initializer:
584///
585/// ```rust
586/// # use pin_init::*;
587/// # use core::pin::Pin;
588/// #[pin_data]
589/// struct Foo {
590///     a: usize,
591///     b: Bar,
592/// }
593///
594/// #[pin_data]
595/// struct Bar {
596///     x: u32,
597/// }
598///
599/// # fn demo() -> impl PinInit<Foo> {
600/// let a = 42;
601///
602/// let initializer = pin_init!(Foo {
603///     a,
604///     b: Bar {
605///         x: 64,
606///     },
607/// });
608/// # initializer }
609/// # Box::pin_init(demo()).unwrap();
610/// ```
611///
612/// Arbitrary Rust expressions can be used to set the value of a variable.
613///
614/// The fields are initialized in the order that they appear in the initializer. So it is possible
615/// to read already initialized fields using raw pointers.
616///
617/// IMPORTANT: You are not allowed to create references to fields of the struct inside of the
618/// initializer.
619///
620/// # Init-functions
621///
622/// When working with this library it is often desired to let others construct your types without
623/// giving access to all fields. This is where you would normally write a plain function `new` that
624/// would return a new instance of your type. With this library that is also possible. However,
625/// there are a few extra things to keep in mind.
626///
627/// To create an initializer function, simply declare it like this:
628///
629/// ```rust
630/// # use pin_init::*;
631/// # use core::pin::Pin;
632/// # #[pin_data]
633/// # struct Foo {
634/// #     a: usize,
635/// #     b: Bar,
636/// # }
637/// # #[pin_data]
638/// # struct Bar {
639/// #     x: u32,
640/// # }
641/// impl Foo {
642///     fn new() -> impl PinInit<Self> {
643///         pin_init!(Self {
644///             a: 42,
645///             b: Bar {
646///                 x: 64,
647///             },
648///         })
649///     }
650/// }
651/// ```
652///
653/// Users of `Foo` can now create it like this:
654///
655/// ```rust
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        let slot = unsafe { __internal::Slot::<__internal::Pinned, _>::new(slot) };
963        let mut guard = slot.init(self.0)?;
964        (self.1)(guard.let_binding())?;
965        core::mem::forget(guard);
966        Ok(())
967    }
968}
969
970/// An initializer for `T`.
971///
972/// To use this initializer, you will need a suitable memory location that can hold a `T`. This can
973/// be [`Box<T>`], [`Arc<T>`] or even the stack (see [`stack_pin_init!`]). Because
974/// [`PinInit<T, E>`] is a super trait, you can use every function that takes it as well.
975///
976/// Also see the [module description](self).
977///
978/// # Safety
979///
980/// When implementing this trait you will need to take great care. Also there are probably very few
981/// cases where a manual implementation is necessary. Use [`init_from_closure`] where possible.
982///
983/// The [`Init::__init`] function:
984/// - returns `Ok(())` if it initialized every field of `slot`,
985/// - returns `Err(err)` if it encountered an error and then cleaned `slot`, this means:
986///     - `slot` can be deallocated without UB occurring,
987///     - `slot` does not need to be dropped,
988///     - `slot` is not partially initialized.
989/// - while constructing the `T` at `slot` it upholds the pinning invariants of `T`.
990///
991/// The `__pinned_init` function from the supertrait [`PinInit`] needs to execute the exact same
992/// code as `__init`.
993///
994/// Contrary to its supertype [`PinInit<T, E>`] the caller is allowed to
995/// move the pointee after initialization.
996///
997#[cfg_attr(
998    kernel,
999    doc = "[`Arc<T>`]: https://rust.docs.kernel.org/kernel/sync/struct.Arc.html"
1000)]
1001#[cfg_attr(
1002    kernel,
1003    doc = "[`Box<T>`]: https://rust.docs.kernel.org/kernel/alloc/kbox/struct.Box.html"
1004)]
1005#[cfg_attr(not(kernel), doc = "[`Arc<T>`]: alloc::alloc::sync::Arc")]
1006#[cfg_attr(not(kernel), doc = "[`Box<T>`]: alloc::alloc::boxed::Box")]
1007#[must_use = "An initializer must be used in order to create its value."]
1008pub unsafe trait Init<T: ?Sized, E = Infallible>: PinInit<T, E> {
1009    /// Initializes `slot`.
1010    ///
1011    /// # Safety
1012    ///
1013    /// - `slot` is a valid pointer to uninitialized memory.
1014    /// - the caller does not touch `slot` when `Err` is returned, they are only permitted to
1015    ///   deallocate.
1016    unsafe fn __init(self, slot: *mut T) -> Result<(), E>;
1017
1018    /// First initializes the value using `self` then calls the function `f` with the initialized
1019    /// value.
1020    ///
1021    /// If `f` returns an error the value is dropped and the initializer will forward the error.
1022    ///
1023    /// # Examples
1024    ///
1025    /// ```rust
1026    /// use pin_init::{init, init_zeroed, Init};
1027    ///
1028    /// struct Foo {
1029    ///     buf: [u8; 1_000_000],
1030    /// }
1031    ///
1032    /// impl Foo {
1033    ///     fn setup(&mut self) {
1034    ///         println!("Setting up foo");
1035    ///     }
1036    /// }
1037    ///
1038    /// let foo = init!(Foo {
1039    ///     buf <- init_zeroed()
1040    /// }).chain(|foo| {
1041    ///     foo.setup();
1042    ///     Ok(())
1043    /// });
1044    /// ```
1045    fn chain<F>(self, f: F) -> ChainInit<Self, F, T, E>
1046    where
1047        F: FnOnce(&mut T) -> Result<(), E>,
1048    {
1049        ChainInit(self, f, __internal::PhantomInvariant::new())
1050    }
1051}
1052
1053/// An initializer returned by [`Init::chain`].
1054pub struct ChainInit<I, F, T: ?Sized, E>(I, F, __internal::PhantomInvariant<(E, T)>);
1055
1056// SAFETY: The `__init` function is implemented such that it
1057// - returns `Ok(())` on successful initialization,
1058// - returns `Err(err)` on error and in this case `slot` will be dropped.
1059unsafe impl<T: ?Sized, E, I, F> Init<T, E> for ChainInit<I, F, T, E>
1060where
1061    I: Init<T, E>,
1062    F: FnOnce(&mut T) -> Result<(), E>,
1063{
1064    unsafe fn __init(self, slot: *mut T) -> Result<(), E> {
1065        // SAFETY: All requirements fulfilled since this function is `__init`.
1066        let slot = unsafe { __internal::Slot::<__internal::Unpinned, _>::new(slot) };
1067        let mut guard = slot.init(self.0)?;
1068        (self.1)(guard.let_binding())?;
1069        core::mem::forget(guard);
1070        Ok(())
1071    }
1072}
1073
1074// SAFETY: `__pinned_init` behaves exactly the same as `__init`.
1075unsafe impl<T: ?Sized, E, I, F> PinInit<T, E> for ChainInit<I, F, T, E>
1076where
1077    I: Init<T, E>,
1078    F: FnOnce(&mut T) -> Result<(), E>,
1079{
1080    unsafe fn __pinned_init(self, slot: *mut T) -> Result<(), E> {
1081        // SAFETY: `__init` has less strict requirements compared to `__pinned_init`.
1082        unsafe { self.__init(slot) }
1083    }
1084}
1085
1086/// Implement `PinInit` and `Init` for closures.
1087///
1088/// It is unsafe to create this type, since the closure needs to fulfill the same safety
1089/// requirement as the `__pinned_init`/`__init` functions.
1090struct InitClosure<F, T: ?Sized>(F, __internal::PhantomInvariant<T>);
1091
1092// SAFETY: While constructing the `InitClosure`, the user promised that it upholds the
1093// `__init` invariants.
1094unsafe impl<T: ?Sized, F, E> Init<T, E> for InitClosure<F, T>
1095where
1096    F: FnOnce(*mut T) -> Result<(), E>,
1097{
1098    #[inline]
1099    unsafe fn __init(self, slot: *mut T) -> Result<(), E> {
1100        (self.0)(slot)
1101    }
1102}
1103
1104// SAFETY: While constructing the `InitClosure`, the user promised that it upholds the
1105// `__pinned_init` invariants.
1106unsafe impl<T: ?Sized, F, E> PinInit<T, E> for InitClosure<F, T>
1107where
1108    F: FnOnce(*mut T) -> Result<(), E>,
1109{
1110    #[inline]
1111    unsafe fn __pinned_init(self, slot: *mut T) -> Result<(), E> {
1112        (self.0)(slot)
1113    }
1114}
1115
1116/// Creates a new [`PinInit<T, E>`] from the given closure.
1117///
1118/// # Safety
1119///
1120/// The closure:
1121/// - returns `Ok(())` if it initialized every field of `slot`,
1122/// - returns `Err(err)` if it encountered an error and then cleaned `slot`, this means:
1123///     - `slot` can be deallocated without UB occurring,
1124///     - `slot` does not need to be dropped,
1125///     - `slot` is not partially initialized.
1126/// - may assume that the `slot` does not move if `T: !Unpin`,
1127/// - while constructing the `T` at `slot` it upholds the pinning invariants of `T`.
1128#[inline]
1129pub const unsafe fn pin_init_from_closure<T: ?Sized, E>(
1130    f: impl FnOnce(*mut T) -> Result<(), E>,
1131) -> impl PinInit<T, E> {
1132    InitClosure(f, __internal::PhantomInvariant::new())
1133}
1134
1135/// Creates a new [`Init<T, E>`] from the given closure.
1136///
1137/// # Safety
1138///
1139/// The closure:
1140/// - returns `Ok(())` if it initialized every field of `slot`,
1141/// - returns `Err(err)` if it encountered an error and then cleaned `slot`, this means:
1142///     - `slot` can be deallocated without UB occurring,
1143///     - `slot` does not need to be dropped,
1144///     - `slot` is not partially initialized.
1145/// - the `slot` may move after initialization.
1146/// - while constructing the `T` at `slot` it upholds the pinning invariants of `T`.
1147#[inline]
1148pub const unsafe fn init_from_closure<T: ?Sized, E>(
1149    f: impl FnOnce(*mut T) -> Result<(), E>,
1150) -> impl Init<T, E> {
1151    InitClosure(f, __internal::PhantomInvariant::new())
1152}
1153
1154/// Changes the to be initialized type.
1155///
1156/// # Safety
1157///
1158/// - `*mut U` must be castable to `*mut T` and any value of type `T` written through such a
1159///   pointer must result in a valid `U`.
1160pub const unsafe fn cast_pin_init<T, U, E>(init: impl PinInit<T, E>) -> impl PinInit<U, E> {
1161    // SAFETY: initialization delegated to a valid initializer. Cast is valid by function safety
1162    // requirements.
1163    unsafe { pin_init_from_closure(|ptr: *mut U| init.__pinned_init(ptr.cast::<T>())) }
1164}
1165
1166/// Changes the to be initialized type.
1167///
1168/// # Safety
1169///
1170/// - `*mut U` must be castable to `*mut T` and any value of type `T` written through such a
1171///   pointer must result in a valid `U`.
1172pub const unsafe fn cast_init<T, U, E>(init: impl Init<T, E>) -> impl Init<U, E> {
1173    // SAFETY: initialization delegated to a valid initializer. Cast is valid by function safety
1174    // requirements.
1175    unsafe { init_from_closure(|ptr: *mut U| init.__init(ptr.cast::<T>())) }
1176}
1177
1178/// An initializer that leaves the memory uninitialized.
1179///
1180/// The initializer is a no-op. The `slot` memory is not changed.
1181#[inline]
1182pub fn uninit<T, E>() -> impl Init<MaybeUninit<T>, E> {
1183    // SAFETY: The memory is allowed to be uninitialized.
1184    unsafe { init_from_closure(|_| Ok(())) }
1185}
1186
1187/// Array initializer from element initializer.
1188struct ArrayInit<T: ?Sized, F>(F, __internal::PhantomInvariant<T>);
1189
1190// SAFETY: On success, all `N` elements of the array have been initialized. On error or panic, the
1191// elements that have been initialized so far are dropped, thus leaving the array uninitialized and
1192// ready to deallocate.
1193unsafe impl<T, F, I, E, const N: usize> PinInit<[T; N], E> for ArrayInit<T, F>
1194where
1195    F: FnMut(usize) -> I,
1196    I: PinInit<T, E>,
1197{
1198    unsafe fn __pinned_init(mut self, slot: *mut [T; N]) -> Result<(), E> {
1199        /// # Invariants
1200        ///
1201        /// - `ptr[..num_init]` contains initialized elements of type `T`
1202        /// - `ptr[num_init..N]` (where N is the size of the array) contains uninitialized memory
1203        struct ArrayInitGuard<T> {
1204            /// A pointer to the first element of the array.
1205            ptr: *mut T,
1206            /// The number of initialized elements in the array.
1207            num_init: usize,
1208        }
1209
1210        impl<T> Drop for ArrayInitGuard<T> {
1211            #[inline]
1212            fn drop(&mut self) {
1213                // SAFETY: Per type invariant, `self.ptr[..self.num_init]` are initialized.
1214                unsafe {
1215                    core::ptr::drop_in_place(core::ptr::slice_from_raw_parts_mut(
1216                        self.ptr,
1217                        self.num_init,
1218                    ))
1219                };
1220            }
1221        }
1222
1223        // INVARIANT: nothing is initialized yet.
1224        let mut guard = ArrayInitGuard {
1225            ptr: slot.cast::<T>(),
1226            num_init: 0,
1227        };
1228
1229        for i in 0..N {
1230            // INVARIANT: Elements `self.ptr[..self.num_init]` have been initialized
1231            // thus far. This holds true for every `self.num_init = i`.
1232            guard.num_init = i;
1233
1234            let init = (self.0)(i);
1235            // SAFETY:
1236            // - The subslot is derived from `slot` with a valid offset.
1237            // - If `Err` is touched, the subslot is not touched further, the guard will drop
1238            //   previously initialized elements only.
1239            // - `slot` is pinned so is the subslot.
1240            unsafe { init.__pinned_init(&raw mut (*slot)[i]) }?;
1241        }
1242
1243        // Dismiss the drop guard now that all elements are initialized.
1244        core::mem::forget(guard);
1245        Ok(())
1246    }
1247}
1248
1249// SAFETY: Follows the `PinInit` impl. `__init` executes the same code as `__pinned_init`.
1250unsafe impl<T, F, I, E, const N: usize> Init<[T; N], E> for ArrayInit<T, F>
1251where
1252    F: FnMut(usize) -> I,
1253    I: Init<T, E>,
1254{
1255    #[inline(always)]
1256    unsafe fn __init(self, slot: *mut [T; N]) -> Result<(), E> {
1257        // SAFETY: `I: Init` cancels out the pinning requirement on subslots. The other safety
1258        // requirements follow that of `__init`.
1259        unsafe { self.__pinned_init(slot) }
1260    }
1261}
1262
1263/// Initializes an array by initializing each element via the provided initializer.
1264///
1265/// # Examples
1266///
1267/// ```rust
1268/// # use pin_init::*;
1269/// use pin_init::init_array_from_fn;
1270/// let array: Box<[usize; 1_000]> = Box::init(init_array_from_fn(|i| i)).unwrap();
1271/// assert_eq!(array.len(), 1_000);
1272/// ```
1273pub fn init_array_from_fn<I, const N: usize, T, E>(
1274    make_init: impl FnMut(usize) -> I,
1275) -> impl Init<[T; N], E>
1276where
1277    I: Init<T, E>,
1278{
1279    ArrayInit(make_init, __internal::PhantomInvariant::new())
1280}
1281
1282/// Initializes an array by initializing each element via the provided initializer.
1283///
1284/// # Examples
1285///
1286/// ```rust
1287/// # #![feature(allocator_api)]
1288/// # #[path = "../examples/mutex.rs"] mod mutex; use mutex::*;
1289/// # use pin_init::*;
1290/// # use core::pin::Pin;
1291/// use pin_init::pin_init_array_from_fn;
1292/// use std::sync::Arc;
1293/// let array: Pin<Arc<[CMutex<usize>; 1_000]>> =
1294///     Arc::pin_init(pin_init_array_from_fn(|i| CMutex::new(i))).unwrap();
1295/// assert_eq!(array.len(), 1_000);
1296/// ```
1297pub fn pin_init_array_from_fn<I, const N: usize, T, E>(
1298    make_init: impl FnMut(usize) -> I,
1299) -> impl PinInit<[T; N], E>
1300where
1301    I: PinInit<T, E>,
1302{
1303    ArrayInit(make_init, __internal::PhantomInvariant::new())
1304}
1305
1306/// Construct an initializer in a closure and run it.
1307///
1308/// Returns an initializer that first runs the closure and then the initializer returned by it.
1309///
1310/// See also [`init_scope`].
1311///
1312/// # Examples
1313///
1314/// ```
1315/// # use pin_init::*;
1316/// # #[pin_data]
1317/// # struct Foo { a: u64, b: isize }
1318/// # struct Bar { a: u32, b: isize }
1319/// # fn lookup_bar() -> Result<Bar, Error> { todo!() }
1320/// # struct Error;
1321/// fn init_foo() -> impl PinInit<Foo, Error> {
1322///     pin_init_scope(|| {
1323///         let bar = lookup_bar()?;
1324///         Ok(pin_init!(Foo { a: bar.a.into(), b: bar.b }? Error))
1325///     })
1326/// }
1327/// ```
1328///
1329/// This initializer will first execute `lookup_bar()`, match on it, if it returned an error, the
1330/// initializer itself will fail with that error. If it returned `Ok`, then it will run the
1331/// initializer returned by the [`pin_init!`] invocation.
1332pub fn pin_init_scope<T, E, F, I>(make_init: F) -> impl PinInit<T, E>
1333where
1334    F: FnOnce() -> Result<I, E>,
1335    I: PinInit<T, E>,
1336{
1337    // SAFETY:
1338    // - If `make_init` returns `Err`, `Err` is returned and `slot` is completely uninitialized,
1339    // - If `make_init` returns `Ok`, safety requirement are fulfilled by `init.__pinned_init`.
1340    // - The safety requirements of `init.__pinned_init` are fulfilled, since it's being called
1341    //   from an initializer.
1342    unsafe {
1343        pin_init_from_closure(move |slot: *mut T| -> Result<(), E> {
1344            let init = make_init()?;
1345            init.__pinned_init(slot)
1346        })
1347    }
1348}
1349
1350/// Construct an initializer in a closure and run it.
1351///
1352/// Returns an initializer that first runs the closure and then the initializer returned by it.
1353///
1354/// See also [`pin_init_scope`].
1355///
1356/// # Examples
1357///
1358/// ```
1359/// # use pin_init::*;
1360/// # struct Foo { a: u64, b: isize }
1361/// # struct Bar { a: u32, b: isize }
1362/// # fn lookup_bar() -> Result<Bar, Error> { todo!() }
1363/// # struct Error;
1364/// fn init_foo() -> impl Init<Foo, Error> {
1365///     init_scope(|| {
1366///         let bar = lookup_bar()?;
1367///         Ok(init!(Foo { a: bar.a.into(), b: bar.b }? Error))
1368///     })
1369/// }
1370/// ```
1371///
1372/// This initializer will first execute `lookup_bar()`, match on it, if it returned an error, the
1373/// initializer itself will fail with that error. If it returned `Ok`, then it will run the
1374/// initializer returned by the [`init!`] invocation.
1375pub fn init_scope<T, E, F, I>(make_init: F) -> impl Init<T, E>
1376where
1377    F: FnOnce() -> Result<I, E>,
1378    I: Init<T, E>,
1379{
1380    // SAFETY:
1381    // - If `make_init` returns `Err`, `Err` is returned and `slot` is completely uninitialized,
1382    // - If `make_init` returns `Ok`, safety requirement are fulfilled by `init.__init`.
1383    // - The safety requirements of `init.__init` are fulfilled, since it's being called from an
1384    //   initializer.
1385    unsafe {
1386        init_from_closure(move |slot: *mut T| -> Result<(), E> {
1387            let init = make_init()?;
1388            init.__init(slot)
1389        })
1390    }
1391}
1392
1393// SAFETY: the `__init` function always returns `Ok(())` and initializes every field of `slot`.
1394unsafe impl<T> Init<T> for T {
1395    unsafe fn __init(self, slot: *mut T) -> Result<(), Infallible> {
1396        // SAFETY: `slot` is valid for writes by the safety requirements of this function.
1397        unsafe { slot.write(self) };
1398        Ok(())
1399    }
1400}
1401
1402// SAFETY: the `__pinned_init` function always returns `Ok(())` and initializes every field of
1403// `slot`. Additionally, all pinning invariants of `T` are upheld.
1404unsafe impl<T> PinInit<T> for T {
1405    unsafe fn __pinned_init(self, slot: *mut T) -> Result<(), Infallible> {
1406        // SAFETY: `slot` is valid for writes by the safety requirements of this function.
1407        unsafe { slot.write(self) };
1408        Ok(())
1409    }
1410}
1411
1412// SAFETY: when the `__init` function returns with
1413// - `Ok(())`, `slot` was initialized and all pinned invariants of `T` are upheld.
1414// - `Err(err)`, slot was not written to.
1415unsafe impl<T, E> Init<T, E> for Result<T, E> {
1416    unsafe fn __init(self, slot: *mut T) -> Result<(), E> {
1417        // SAFETY: `slot` is valid for writes by the safety requirements of this function.
1418        unsafe { slot.write(self?) };
1419        Ok(())
1420    }
1421}
1422
1423// SAFETY: when the `__pinned_init` function returns with
1424// - `Ok(())`, `slot` was initialized and all pinned invariants of `T` are upheld.
1425// - `Err(err)`, slot was not written to.
1426unsafe impl<T, E> PinInit<T, E> for Result<T, E> {
1427    unsafe fn __pinned_init(self, slot: *mut T) -> Result<(), E> {
1428        // SAFETY: `slot` is valid for writes by the safety requirements of this function.
1429        unsafe { slot.write(self?) };
1430        Ok(())
1431    }
1432}
1433
1434/// Smart pointer containing uninitialized memory and that can write a value.
1435pub trait InPlaceWrite<T> {
1436    /// The type `Self` turns into when the contents are initialized.
1437    type Initialized;
1438
1439    /// Use the given initializer to write a value into `self`.
1440    ///
1441    /// Does not drop the current value and considers it as uninitialized memory.
1442    fn write_init<E>(self, init: impl Init<T, E>) -> Result<Self::Initialized, E>;
1443
1444    /// Use the given pin-initializer to write a value into `self`.
1445    ///
1446    /// Does not drop the current value and considers it as uninitialized memory.
1447    fn write_pin_init<E>(self, init: impl PinInit<T, E>) -> Result<Pin<Self::Initialized>, E>;
1448}
1449
1450impl<T> InPlaceWrite<T> for &'static mut MaybeUninit<T> {
1451    type Initialized = &'static mut T;
1452
1453    fn write_init<E>(self, init: impl Init<T, E>) -> Result<Self::Initialized, E> {
1454        let slot = self.as_mut_ptr();
1455
1456        // SAFETY: `slot` is a valid pointer to uninitialized memory.
1457        unsafe { init.__init(slot)? };
1458
1459        // SAFETY: The above call initialized the memory.
1460        unsafe { Ok(self.assume_init_mut()) }
1461    }
1462
1463    fn write_pin_init<E>(self, init: impl PinInit<T, E>) -> Result<Pin<Self::Initialized>, E> {
1464        let slot = self.as_mut_ptr();
1465
1466        // SAFETY: `slot` is a valid pointer to uninitialized memory.
1467        //
1468        // The `'static` borrow guarantees the data will not be
1469        // moved/invalidated until it gets dropped (which is never).
1470        unsafe { init.__pinned_init(slot)? };
1471
1472        // SAFETY: The above call initialized the memory.
1473        Ok(Pin::static_mut(unsafe { self.assume_init_mut() }))
1474    }
1475}
1476
1477/// Trait facilitating pinned destruction.
1478///
1479/// Use [`pinned_drop`] to implement this trait safely:
1480///
1481/// ```rust
1482/// # #![feature(allocator_api)]
1483/// # #[path = "../examples/mutex.rs"] mod mutex; use mutex::*;
1484/// # use pin_init::*;
1485/// use core::pin::Pin;
1486/// #[pin_data(PinnedDrop)]
1487/// struct Foo {
1488///     #[pin]
1489///     mtx: CMutex<usize>,
1490/// }
1491///
1492/// #[pinned_drop]
1493/// impl PinnedDrop for Foo {
1494///     fn drop(self: Pin<&mut Self>) {
1495///         println!("Foo is being dropped!");
1496///     }
1497/// }
1498/// ```
1499///
1500/// # Safety
1501///
1502/// This trait must be implemented via the [`pinned_drop`] proc-macro attribute on the impl.
1503pub unsafe trait PinnedDrop: __internal::HasPinData {
1504    /// Executes the pinned destructor of this type.
1505    ///
1506    /// While this function is marked safe, it is actually unsafe to call it manually. For this
1507    /// reason it takes an additional parameter. This type can only be constructed by `unsafe` code
1508    /// and thus prevents this function from being called where it should not.
1509    ///
1510    /// This extra parameter will be generated by the `#[pinned_drop]` proc-macro attribute
1511    /// automatically.
1512    fn drop(self: Pin<&mut Self>, only_call_from_drop: __internal::OnlyCallFromDrop);
1513}
1514
1515/// Marker trait for types that can be initialized by writing just zeroes.
1516///
1517/// # Safety
1518///
1519/// The bit pattern consisting of only zeroes is a valid bit pattern for this type. In other words,
1520/// this is not UB:
1521///
1522/// ```rust,ignore
1523/// let val: Self = unsafe { core::mem::zeroed() };
1524/// ```
1525pub unsafe trait Zeroable {
1526    /// Create a new zeroed `Self`.
1527    ///
1528    /// The returned initializer will write `0x00` to every byte of the given `slot`.
1529    #[inline]
1530    fn init_zeroed() -> impl Init<Self>
1531    where
1532        Self: Sized,
1533    {
1534        init_zeroed()
1535    }
1536
1537    /// Create a `Self` consisting of all zeroes.
1538    ///
1539    /// Whenever a type implements [`Zeroable`], this function should be preferred over
1540    /// [`core::mem::zeroed()`] or using `MaybeUninit<T>::zeroed().assume_init()`.
1541    ///
1542    /// # Examples
1543    ///
1544    /// ```
1545    /// use pin_init::{Zeroable, zeroed};
1546    ///
1547    /// #[derive(Zeroable)]
1548    /// struct Point {
1549    ///     x: u32,
1550    ///     y: u32,
1551    /// }
1552    ///
1553    /// let point: Point = zeroed();
1554    /// assert_eq!(point.x, 0);
1555    /// assert_eq!(point.y, 0);
1556    /// ```
1557    fn zeroed() -> Self
1558    where
1559        Self: Sized,
1560    {
1561        zeroed()
1562    }
1563}
1564
1565/// Create an initializer for a zeroed `T`.
1566///
1567/// The returned initializer will write `0x00` to every byte of the given `slot`.
1568#[inline]
1569pub fn init_zeroed<T: Zeroable>() -> impl Init<T> {
1570    // SAFETY: Because `T: Zeroable`, all bytes zero is a valid bit pattern for `T`
1571    // and because we write all zeroes, the memory is initialized.
1572    unsafe {
1573        init_from_closure(|slot: *mut T| {
1574            slot.write_bytes(0, 1);
1575            Ok(())
1576        })
1577    }
1578}
1579
1580/// Create a `T` consisting of all zeroes.
1581///
1582/// Whenever a type implements [`Zeroable`], this function should be preferred over
1583/// [`core::mem::zeroed()`] or using `MaybeUninit<T>::zeroed().assume_init()`.
1584///
1585/// # Examples
1586///
1587/// ```
1588/// use pin_init::{Zeroable, zeroed};
1589///
1590/// #[derive(Zeroable)]
1591/// struct Point {
1592///     x: u32,
1593///     y: u32,
1594/// }
1595///
1596/// let point: Point = zeroed();
1597/// assert_eq!(point.x, 0);
1598/// assert_eq!(point.y, 0);
1599/// ```
1600pub const fn zeroed<T: Zeroable>() -> T {
1601    // SAFETY:By the type invariants of `Zeroable`, all zeroes is a valid bit pattern for `T`.
1602    unsafe { core::mem::zeroed() }
1603}
1604
1605macro_rules! impl_zeroable {
1606    ($($({$($generics:tt)*})? $t:ty, )*) => {
1607        // SAFETY: Safety comments written in the macro invocation.
1608        $(unsafe impl$($($generics)*)? Zeroable for $t {})*
1609    };
1610}
1611
1612impl_zeroable! {
1613    // SAFETY: All primitives that are allowed to be zero.
1614    bool,
1615    char,
1616    u8, u16, u32, u64, u128, usize,
1617    i8, i16, i32, i64, i128, isize,
1618    f32, f64,
1619
1620    // Note: do not add uninhabited types (such as `!` or `core::convert::Infallible`) to this list;
1621    // creating an instance of an uninhabited type is immediate undefined behavior. For more on
1622    // uninhabited/empty types, consult The Rustonomicon:
1623    // <https://doc.rust-lang.org/stable/nomicon/exotic-sizes.html#empty-types>. The Rust Reference
1624    // also has information on undefined behavior:
1625    // <https://doc.rust-lang.org/stable/reference/behavior-considered-undefined.html>.
1626    //
1627    // SAFETY: These are inhabited ZSTs; there is nothing to zero and a valid value exists.
1628    {<T: ?Sized>} PhantomData<T>, core::marker::PhantomPinned, (),
1629
1630    // SAFETY: Type is allowed to take any value, including all zeros.
1631    {<T>} MaybeUninit<T>,
1632
1633    // SAFETY: `T: Zeroable` and `UnsafeCell` is `repr(transparent)`.
1634    {<T: ?Sized + Zeroable>} UnsafeCell<T>,
1635
1636    // SAFETY: `null` pointer is valid.
1637    //
1638    // We cannot use `T: ?Sized`, since the VTABLE pointer part of fat pointers is not allowed to be
1639    // null.
1640    //
1641    // When `Pointee` gets stabilized, we could use
1642    // `T: ?Sized where <T as Pointee>::Metadata: Zeroable`
1643    {<T>} *mut T, {<T>} *const T,
1644
1645    // SAFETY: `null` pointer is valid and the metadata part of these fat pointers is allowed to be
1646    // zero.
1647    {<T>} *mut [T], {<T>} *const [T], *mut str, *const str,
1648
1649    // SAFETY: `T` is `Zeroable`.
1650    {<const N: usize, T: Zeroable>} [T; N], {<T: Zeroable>} Wrapping<T>,
1651}
1652
1653macro_rules! impl_tuple_zeroable {
1654    ($first:ident, $(,)?) => {
1655        #[cfg_attr(all(USE_RUSTC_FEATURES, doc), doc(fake_variadic))]
1656        /// Implemented for tuples up to 10 items long.
1657        // SAFETY: All elements are zeroable and padding can be zero.
1658        unsafe impl<$first: Zeroable> Zeroable for ($first,) {}
1659    };
1660    ($first:ident, $($t:ident),* $(,)?) => {
1661        #[cfg_attr(doc, doc(hidden))]
1662        // SAFETY: All elements are zeroable and padding can be zero.
1663        unsafe impl<$first: Zeroable, $($t: Zeroable),*> Zeroable for ($first, $($t),*) {}
1664        impl_tuple_zeroable!($($t),* ,);
1665    }
1666}
1667
1668impl_tuple_zeroable!(A, B, C, D, E, F, G, H, I, J);
1669
1670/// Marker trait for types that allow `Option<Self>` to be set to all zeroes in order to write
1671/// `None` to that location.
1672///
1673/// # Safety
1674///
1675/// The implementer needs to ensure that `unsafe impl Zeroable for Option<Self> {}` is sound.
1676pub unsafe trait ZeroableOption {}
1677
1678// SAFETY: by the safety requirement of `ZeroableOption`, this is valid.
1679unsafe impl<T: ZeroableOption> Zeroable for Option<T> {}
1680
1681macro_rules! impl_fn_zeroable_option {
1682    ([$($abi:literal),* $(,)?] $args:tt) => {
1683        $(impl_fn_zeroable_option!({extern $abi} $args);)*
1684        $(impl_fn_zeroable_option!({unsafe extern $abi} $args);)*
1685    };
1686    ({$($prefix:tt)*} {$(,)?}) => {};
1687    ({$($prefix:tt)*} {$ret:ident, $arg:ident $(,)?}) => {
1688        #[cfg_attr(all(USE_RUSTC_FEATURES, doc), doc(fake_variadic))]
1689        /// Implemented for function pointers with up to 20 arity.
1690        // SAFETY: function pointers are part of the option layout optimization:
1691        // <https://doc.rust-lang.org/stable/std/option/index.html#representation>.
1692        unsafe impl<$ret, $arg> ZeroableOption for $($prefix)* fn($arg) -> $ret {}
1693        impl_fn_zeroable_option!({$($prefix)*} {$arg,});
1694    };
1695    ({$($prefix:tt)*} {$ret:ident, $($rest:ident),* $(,)?}) => {
1696        #[cfg_attr(doc, doc(hidden))]
1697        // SAFETY: function pointers are part of the option layout optimization:
1698        // <https://doc.rust-lang.org/stable/std/option/index.html#representation>.
1699        unsafe impl<$ret, $($rest),*> ZeroableOption for $($prefix)* fn($($rest),*) -> $ret {}
1700        impl_fn_zeroable_option!({$($prefix)*} {$($rest),*,});
1701    };
1702}
1703
1704impl_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 });
1705
1706macro_rules! impl_zeroable_option {
1707    ($($({$($generics:tt)*})? $t:ty, )*) => {
1708        // SAFETY: Safety comments written in the macro invocation.
1709        $(unsafe impl$($($generics)*)? ZeroableOption for $t {})*
1710    };
1711}
1712
1713impl_zeroable_option! {
1714    // SAFETY: `Option<&T>` is part of the option layout optimization guarantee:
1715    // <https://doc.rust-lang.org/stable/std/option/index.html#representation>.
1716    {<T: ?Sized>} &T,
1717    // SAFETY: `Option<&mut T>` is part of the option layout optimization guarantee:
1718    // <https://doc.rust-lang.org/stable/std/option/index.html#representation>.
1719    {<T: ?Sized>} &mut T,
1720    // SAFETY: `Option<NonNull<T>>` is part of the option layout optimization guarantee:
1721    // <https://doc.rust-lang.org/stable/std/option/index.html#representation>.
1722    {<T: ?Sized>} NonNull<T>,
1723    // SAFETY: All zeros is equivalent to `None` (option layout optimization guarantee:
1724    // <https://doc.rust-lang.org/stable/std/option/index.html#representation>).
1725    NonZero<u8>, NonZero<u16>, NonZero<u32>, NonZero<u64>, NonZero<u128>, NonZero<usize>,
1726    NonZero<i8>, NonZero<i16>, NonZero<i32>, NonZero<i64>, NonZero<i128>, NonZero<isize>,
1727}
1728
1729/// This trait allows creating an instance of `Self` which contains exactly one
1730/// [structurally pinned value](https://doc.rust-lang.org/std/pin/index.html#projections-and-structural-pinning).
1731///
1732/// This is useful when using wrapper `struct`s like [`UnsafeCell`] or with new-type `struct`s.
1733///
1734/// # Examples
1735///
1736/// ```
1737/// # use core::cell::UnsafeCell;
1738/// # use pin_init::{pin_data, pin_init, Wrapper};
1739///
1740/// #[pin_data]
1741/// struct Foo {}
1742///
1743/// #[pin_data]
1744/// struct Bar {
1745///     #[pin]
1746///     content: UnsafeCell<Foo>
1747/// };
1748///
1749/// let foo_initializer = pin_init!(Foo{});
1750/// let initializer = pin_init!(Bar {
1751///     content <- UnsafeCell::pin_init(foo_initializer)
1752/// });
1753/// ```
1754pub trait Wrapper<T> {
1755    /// Creates an pin-initializer for a [`Self`] containing `T` from the `value_init` initializer.
1756    fn pin_init<E>(value_init: impl PinInit<T, E>) -> impl PinInit<Self, E>;
1757}
1758
1759impl<T> Wrapper<T> for UnsafeCell<T> {
1760    fn pin_init<E>(value_init: impl PinInit<T, E>) -> impl PinInit<Self, E> {
1761        // SAFETY: `UnsafeCell<T>` has a compatible layout to `T`.
1762        unsafe { cast_pin_init(value_init) }
1763    }
1764}
1765
1766impl<T> Wrapper<T> for MaybeUninit<T> {
1767    fn pin_init<E>(value_init: impl PinInit<T, E>) -> impl PinInit<Self, E> {
1768        // SAFETY: `MaybeUninit<T>` has a compatible layout to `T`.
1769        unsafe { cast_pin_init(value_init) }
1770    }
1771}
1772
1773#[cfg(all(feature = "unsafe-pinned", CONFIG_RUSTC_HAS_UNSAFE_PINNED))]
1774impl<T> Wrapper<T> for core::pin::UnsafePinned<T> {
1775    fn pin_init<E>(init: impl PinInit<T, E>) -> impl PinInit<Self, E> {
1776        // SAFETY: `UnsafePinned<T>` has a compatible layout to `T`.
1777        unsafe { cast_pin_init(init) }
1778    }
1779}