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