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