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