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