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