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