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