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