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/// // implements `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 implement `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 // SAFETY: This code is unreachable.
871 let _ = move |ptr: *mut $ty| unsafe {
872 let data = <$ty as $crate::__internal::HasPinData>::__pin_data();
873 _ = data
874 .$field(ptr)
875 .init($crate::__internal::AlwaysFail::<$field_ty>::new());
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, __internal::PhantomInvariant::new())
951 }
952}
953
954/// An initializer returned by [`PinInit::pin_chain`].
955pub struct ChainPinInit<I, F, T: ?Sized, E>(I, F, __internal::PhantomInvariant<(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, __internal::PhantomInvariant::new())
1059 }
1060}
1061
1062/// An initializer returned by [`Init::chain`].
1063pub struct ChainInit<I, F, T: ?Sized, E>(I, F, __internal::PhantomInvariant<(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/// Implement `PinInit` and `Init` for closures.
1096///
1097/// It is unsafe to create this type, since the closure needs to fulfill the same safety
1098/// requirement as the `__pinned_init`/`__init` functions.
1099struct InitClosure<F, T: ?Sized>(F, __internal::PhantomInvariant<T>);
1100
1101// SAFETY: While constructing the `InitClosure`, the user promised that it upholds the
1102// `__init` invariants.
1103unsafe impl<T: ?Sized, F, E> Init<T, E> for InitClosure<F, T>
1104where
1105 F: FnOnce(*mut T) -> Result<(), E>,
1106{
1107 #[inline]
1108 unsafe fn __init(self, slot: *mut T) -> Result<(), E> {
1109 (self.0)(slot)
1110 }
1111}
1112
1113// SAFETY: While constructing the `InitClosure`, the user promised that it upholds the
1114// `__pinned_init` invariants.
1115unsafe impl<T: ?Sized, F, E> PinInit<T, E> for InitClosure<F, T>
1116where
1117 F: FnOnce(*mut T) -> Result<(), E>,
1118{
1119 #[inline]
1120 unsafe fn __pinned_init(self, slot: *mut T) -> Result<(), E> {
1121 (self.0)(slot)
1122 }
1123}
1124
1125/// Creates a new [`PinInit<T, E>`] from the given closure.
1126///
1127/// # Safety
1128///
1129/// The closure:
1130/// - returns `Ok(())` if it initialized every field of `slot`,
1131/// - returns `Err(err)` if it encountered an error and then cleaned `slot`, this means:
1132/// - `slot` can be deallocated without UB occurring,
1133/// - `slot` does not need to be dropped,
1134/// - `slot` is not partially initialized.
1135/// - may assume that the `slot` does not move if `T: !Unpin`,
1136/// - while constructing the `T` at `slot` it upholds the pinning invariants of `T`.
1137#[inline]
1138pub const unsafe fn pin_init_from_closure<T: ?Sized, E>(
1139 f: impl FnOnce(*mut T) -> Result<(), E>,
1140) -> impl PinInit<T, E> {
1141 InitClosure(f, __internal::PhantomInvariant::new())
1142}
1143
1144/// Creates a new [`Init<T, E>`] from the given closure.
1145///
1146/// # Safety
1147///
1148/// The closure:
1149/// - returns `Ok(())` if it initialized every field of `slot`,
1150/// - returns `Err(err)` if it encountered an error and then cleaned `slot`, this means:
1151/// - `slot` can be deallocated without UB occurring,
1152/// - `slot` does not need to be dropped,
1153/// - `slot` is not partially initialized.
1154/// - the `slot` may move after initialization.
1155/// - while constructing the `T` at `slot` it upholds the pinning invariants of `T`.
1156#[inline]
1157pub const unsafe fn init_from_closure<T: ?Sized, E>(
1158 f: impl FnOnce(*mut T) -> Result<(), E>,
1159) -> impl Init<T, E> {
1160 InitClosure(f, __internal::PhantomInvariant::new())
1161}
1162
1163/// Changes the to be initialized type.
1164///
1165/// # Safety
1166///
1167/// - `*mut U` must be castable to `*mut T` and any value of type `T` written through such a
1168/// pointer must result in a valid `U`.
1169pub const unsafe fn cast_pin_init<T, U, E>(init: impl PinInit<T, E>) -> impl PinInit<U, E> {
1170 // SAFETY: initialization delegated to a valid initializer. Cast is valid by function safety
1171 // requirements.
1172 unsafe { pin_init_from_closure(|ptr: *mut U| init.__pinned_init(ptr.cast::<T>())) }
1173}
1174
1175/// Changes the to be initialized type.
1176///
1177/// # Safety
1178///
1179/// - `*mut U` must be castable to `*mut T` and any value of type `T` written through such a
1180/// pointer must result in a valid `U`.
1181pub const unsafe fn cast_init<T, U, E>(init: impl Init<T, E>) -> impl Init<U, E> {
1182 // SAFETY: initialization delegated to a valid initializer. Cast is valid by function safety
1183 // requirements.
1184 unsafe { init_from_closure(|ptr: *mut U| init.__init(ptr.cast::<T>())) }
1185}
1186
1187/// An initializer that leaves the memory uninitialized.
1188///
1189/// The initializer is a no-op. The `slot` memory is not changed.
1190#[inline]
1191pub fn uninit<T, E>() -> impl Init<MaybeUninit<T>, E> {
1192 // SAFETY: The memory is allowed to be uninitialized.
1193 unsafe { init_from_closure(|_| Ok(())) }
1194}
1195
1196/// Initializes an array by initializing each element via the provided initializer.
1197///
1198/// # Examples
1199///
1200/// ```rust
1201/// # use pin_init::*;
1202/// use pin_init::init_array_from_fn;
1203/// let array: Box<[usize; 1_000]> = Box::init(init_array_from_fn(|i| i)).unwrap();
1204/// assert_eq!(array.len(), 1_000);
1205/// ```
1206pub fn init_array_from_fn<I, const N: usize, T, E>(
1207 mut make_init: impl FnMut(usize) -> I,
1208) -> impl Init<[T; N], E>
1209where
1210 I: Init<T, E>,
1211{
1212 let init = move |slot: *mut [T; N]| {
1213 let slot = slot.cast::<T>();
1214 for i in 0..N {
1215 let init = make_init(i);
1216 // SAFETY: Since 0 <= `i` < N, it is still in bounds of `[T; N]`.
1217 let ptr = unsafe { slot.add(i) };
1218 // SAFETY: The pointer is derived from `slot` and thus satisfies the `__init`
1219 // requirements.
1220 if let Err(e) = unsafe { init.__init(ptr) } {
1221 // SAFETY: The loop has initialized the elements `slot[0..i]` and since we return
1222 // `Err` below, `slot` will be considered uninitialized memory.
1223 unsafe { ptr::drop_in_place(ptr::slice_from_raw_parts_mut(slot, i)) };
1224 return Err(e);
1225 }
1226 }
1227 Ok(())
1228 };
1229 // SAFETY: The initializer above initializes every element of the array. On failure it drops
1230 // any initialized elements and returns `Err`.
1231 unsafe { init_from_closure(init) }
1232}
1233
1234/// Initializes an array by initializing each element via the provided initializer.
1235///
1236/// # Examples
1237///
1238/// ```rust
1239/// # #![feature(allocator_api)]
1240/// # #[path = "../examples/mutex.rs"] mod mutex; use mutex::*;
1241/// # use pin_init::*;
1242/// # use core::pin::Pin;
1243/// use pin_init::pin_init_array_from_fn;
1244/// use std::sync::Arc;
1245/// let array: Pin<Arc<[CMutex<usize>; 1_000]>> =
1246/// Arc::pin_init(pin_init_array_from_fn(|i| CMutex::new(i))).unwrap();
1247/// assert_eq!(array.len(), 1_000);
1248/// ```
1249pub fn pin_init_array_from_fn<I, const N: usize, T, E>(
1250 mut make_init: impl FnMut(usize) -> I,
1251) -> impl PinInit<[T; N], E>
1252where
1253 I: PinInit<T, E>,
1254{
1255 let init = move |slot: *mut [T; N]| {
1256 let slot = slot.cast::<T>();
1257 for i in 0..N {
1258 let init = make_init(i);
1259 // SAFETY: Since 0 <= `i` < N, it is still in bounds of `[T; N]`.
1260 let ptr = unsafe { slot.add(i) };
1261 // SAFETY: The pointer is derived from `slot` and thus satisfies the `__init`
1262 // requirements.
1263 if let Err(e) = unsafe { init.__pinned_init(ptr) } {
1264 // SAFETY: The loop has initialized the elements `slot[0..i]` and since we return
1265 // `Err` below, `slot` will be considered uninitialized memory.
1266 unsafe { ptr::drop_in_place(ptr::slice_from_raw_parts_mut(slot, i)) };
1267 return Err(e);
1268 }
1269 }
1270 Ok(())
1271 };
1272 // SAFETY: The initializer above initializes every element of the array. On failure it drops
1273 // any initialized elements and returns `Err`.
1274 unsafe { pin_init_from_closure(init) }
1275}
1276
1277/// Construct an initializer in a closure and run it.
1278///
1279/// Returns an initializer that first runs the closure and then the initializer returned by it.
1280///
1281/// See also [`init_scope`].
1282///
1283/// # Examples
1284///
1285/// ```
1286/// # use pin_init::*;
1287/// # #[pin_data]
1288/// # struct Foo { a: u64, b: isize }
1289/// # struct Bar { a: u32, b: isize }
1290/// # fn lookup_bar() -> Result<Bar, Error> { todo!() }
1291/// # struct Error;
1292/// fn init_foo() -> impl PinInit<Foo, Error> {
1293/// pin_init_scope(|| {
1294/// let bar = lookup_bar()?;
1295/// Ok(pin_init!(Foo { a: bar.a.into(), b: bar.b }? Error))
1296/// })
1297/// }
1298/// ```
1299///
1300/// This initializer will first execute `lookup_bar()`, match on it, if it returned an error, the
1301/// initializer itself will fail with that error. If it returned `Ok`, then it will run the
1302/// initializer returned by the [`pin_init!`] invocation.
1303pub fn pin_init_scope<T, E, F, I>(make_init: F) -> impl PinInit<T, E>
1304where
1305 F: FnOnce() -> Result<I, E>,
1306 I: PinInit<T, E>,
1307{
1308 // SAFETY:
1309 // - If `make_init` returns `Err`, `Err` is returned and `slot` is completely uninitialized,
1310 // - If `make_init` returns `Ok`, safety requirement are fulfilled by `init.__pinned_init`.
1311 // - The safety requirements of `init.__pinned_init` are fulfilled, since it's being called
1312 // from an initializer.
1313 unsafe {
1314 pin_init_from_closure(move |slot: *mut T| -> Result<(), E> {
1315 let init = make_init()?;
1316 init.__pinned_init(slot)
1317 })
1318 }
1319}
1320
1321/// Construct an initializer in a closure and run it.
1322///
1323/// Returns an initializer that first runs the closure and then the initializer returned by it.
1324///
1325/// See also [`pin_init_scope`].
1326///
1327/// # Examples
1328///
1329/// ```
1330/// # use pin_init::*;
1331/// # struct Foo { a: u64, b: isize }
1332/// # struct Bar { a: u32, b: isize }
1333/// # fn lookup_bar() -> Result<Bar, Error> { todo!() }
1334/// # struct Error;
1335/// fn init_foo() -> impl Init<Foo, Error> {
1336/// init_scope(|| {
1337/// let bar = lookup_bar()?;
1338/// Ok(init!(Foo { a: bar.a.into(), b: bar.b }? Error))
1339/// })
1340/// }
1341/// ```
1342///
1343/// This initializer will first execute `lookup_bar()`, match on it, if it returned an error, the
1344/// initializer itself will fail with that error. If it returned `Ok`, then it will run the
1345/// initializer returned by the [`init!`] invocation.
1346pub fn init_scope<T, E, F, I>(make_init: F) -> impl Init<T, E>
1347where
1348 F: FnOnce() -> Result<I, E>,
1349 I: Init<T, E>,
1350{
1351 // SAFETY:
1352 // - If `make_init` returns `Err`, `Err` is returned and `slot` is completely uninitialized,
1353 // - If `make_init` returns `Ok`, safety requirement are fulfilled by `init.__init`.
1354 // - The safety requirements of `init.__init` are fulfilled, since it's being called from an
1355 // initializer.
1356 unsafe {
1357 init_from_closure(move |slot: *mut T| -> Result<(), E> {
1358 let init = make_init()?;
1359 init.__init(slot)
1360 })
1361 }
1362}
1363
1364// SAFETY: the `__init` function always returns `Ok(())` and initializes every field of `slot`.
1365unsafe impl<T> Init<T> for T {
1366 unsafe fn __init(self, slot: *mut T) -> Result<(), Infallible> {
1367 // SAFETY: `slot` is valid for writes by the safety requirements of this function.
1368 unsafe { slot.write(self) };
1369 Ok(())
1370 }
1371}
1372
1373// SAFETY: the `__pinned_init` function always returns `Ok(())` and initializes every field of
1374// `slot`. Additionally, all pinning invariants of `T` are upheld.
1375unsafe impl<T> PinInit<T> for T {
1376 unsafe fn __pinned_init(self, slot: *mut T) -> Result<(), Infallible> {
1377 // SAFETY: `slot` is valid for writes by the safety requirements of this function.
1378 unsafe { slot.write(self) };
1379 Ok(())
1380 }
1381}
1382
1383// SAFETY: when the `__init` function returns with
1384// - `Ok(())`, `slot` was initialized and all pinned invariants of `T` are upheld.
1385// - `Err(err)`, slot was not written to.
1386unsafe impl<T, E> Init<T, E> for Result<T, E> {
1387 unsafe fn __init(self, slot: *mut T) -> Result<(), E> {
1388 // SAFETY: `slot` is valid for writes by the safety requirements of this function.
1389 unsafe { slot.write(self?) };
1390 Ok(())
1391 }
1392}
1393
1394// SAFETY: when the `__pinned_init` function returns with
1395// - `Ok(())`, `slot` was initialized and all pinned invariants of `T` are upheld.
1396// - `Err(err)`, slot was not written to.
1397unsafe impl<T, E> PinInit<T, E> for Result<T, E> {
1398 unsafe fn __pinned_init(self, slot: *mut T) -> Result<(), E> {
1399 // SAFETY: `slot` is valid for writes by the safety requirements of this function.
1400 unsafe { slot.write(self?) };
1401 Ok(())
1402 }
1403}
1404
1405/// Smart pointer containing uninitialized memory and that can write a value.
1406pub trait InPlaceWrite<T> {
1407 /// The type `Self` turns into when the contents are initialized.
1408 type Initialized;
1409
1410 /// Use the given initializer to write a value into `self`.
1411 ///
1412 /// Does not drop the current value and considers it as uninitialized memory.
1413 fn write_init<E>(self, init: impl Init<T, E>) -> Result<Self::Initialized, E>;
1414
1415 /// Use the given pin-initializer to write a value into `self`.
1416 ///
1417 /// Does not drop the current value and considers it as uninitialized memory.
1418 fn write_pin_init<E>(self, init: impl PinInit<T, E>) -> Result<Pin<Self::Initialized>, E>;
1419}
1420
1421impl<T> InPlaceWrite<T> for &'static mut MaybeUninit<T> {
1422 type Initialized = &'static mut T;
1423
1424 fn write_init<E>(self, init: impl Init<T, E>) -> Result<Self::Initialized, E> {
1425 let slot = self.as_mut_ptr();
1426
1427 // SAFETY: `slot` is a valid pointer to uninitialized memory.
1428 unsafe { init.__init(slot)? };
1429
1430 // SAFETY: The above call initialized the memory.
1431 unsafe { Ok(self.assume_init_mut()) }
1432 }
1433
1434 fn write_pin_init<E>(self, init: impl PinInit<T, E>) -> Result<Pin<Self::Initialized>, E> {
1435 let slot = self.as_mut_ptr();
1436
1437 // SAFETY: `slot` is a valid pointer to uninitialized memory.
1438 //
1439 // The `'static` borrow guarantees the data will not be
1440 // moved/invalidated until it gets dropped (which is never).
1441 unsafe { init.__pinned_init(slot)? };
1442
1443 // SAFETY: The above call initialized the memory.
1444 Ok(Pin::static_mut(unsafe { self.assume_init_mut() }))
1445 }
1446}
1447
1448/// Trait facilitating pinned destruction.
1449///
1450/// Use [`pinned_drop`] to implement this trait safely:
1451///
1452/// ```rust
1453/// # #![feature(allocator_api)]
1454/// # #[path = "../examples/mutex.rs"] mod mutex; use mutex::*;
1455/// # use pin_init::*;
1456/// use core::pin::Pin;
1457/// #[pin_data(PinnedDrop)]
1458/// struct Foo {
1459/// #[pin]
1460/// mtx: CMutex<usize>,
1461/// }
1462///
1463/// #[pinned_drop]
1464/// impl PinnedDrop for Foo {
1465/// fn drop(self: Pin<&mut Self>) {
1466/// println!("Foo is being dropped!");
1467/// }
1468/// }
1469/// ```
1470///
1471/// # Safety
1472///
1473/// This trait must be implemented via the [`pinned_drop`] proc-macro attribute on the impl.
1474pub unsafe trait PinnedDrop: __internal::HasPinData {
1475 /// Executes the pinned destructor of this type.
1476 ///
1477 /// While this function is marked safe, it is actually unsafe to call it manually. For this
1478 /// reason it takes an additional parameter. This type can only be constructed by `unsafe` code
1479 /// and thus prevents this function from being called where it should not.
1480 ///
1481 /// This extra parameter will be generated by the `#[pinned_drop]` proc-macro attribute
1482 /// automatically.
1483 fn drop(self: Pin<&mut Self>, only_call_from_drop: __internal::OnlyCallFromDrop);
1484}
1485
1486/// Marker trait for types that can be initialized by writing just zeroes.
1487///
1488/// # Safety
1489///
1490/// The bit pattern consisting of only zeroes is a valid bit pattern for this type. In other words,
1491/// this is not UB:
1492///
1493/// ```rust,ignore
1494/// let val: Self = unsafe { core::mem::zeroed() };
1495/// ```
1496pub unsafe trait Zeroable {
1497 /// Create a new zeroed `Self`.
1498 ///
1499 /// The returned initializer will write `0x00` to every byte of the given `slot`.
1500 #[inline]
1501 fn init_zeroed() -> impl Init<Self>
1502 where
1503 Self: Sized,
1504 {
1505 init_zeroed()
1506 }
1507
1508 /// Create a `Self` consisting of all zeroes.
1509 ///
1510 /// Whenever a type implements [`Zeroable`], this function should be preferred over
1511 /// [`core::mem::zeroed()`] or using `MaybeUninit<T>::zeroed().assume_init()`.
1512 ///
1513 /// # Examples
1514 ///
1515 /// ```
1516 /// use pin_init::{Zeroable, zeroed};
1517 ///
1518 /// #[derive(Zeroable)]
1519 /// struct Point {
1520 /// x: u32,
1521 /// y: u32,
1522 /// }
1523 ///
1524 /// let point: Point = zeroed();
1525 /// assert_eq!(point.x, 0);
1526 /// assert_eq!(point.y, 0);
1527 /// ```
1528 fn zeroed() -> Self
1529 where
1530 Self: Sized,
1531 {
1532 zeroed()
1533 }
1534}
1535
1536/// Create an initializer for a zeroed `T`.
1537///
1538/// The returned initializer will write `0x00` to every byte of the given `slot`.
1539#[inline]
1540pub fn init_zeroed<T: Zeroable>() -> impl Init<T> {
1541 // SAFETY: Because `T: Zeroable`, all bytes zero is a valid bit pattern for `T`
1542 // and because we write all zeroes, the memory is initialized.
1543 unsafe {
1544 init_from_closure(|slot: *mut T| {
1545 slot.write_bytes(0, 1);
1546 Ok(())
1547 })
1548 }
1549}
1550
1551/// Create a `T` consisting of all zeroes.
1552///
1553/// Whenever a type implements [`Zeroable`], this function should be preferred over
1554/// [`core::mem::zeroed()`] or using `MaybeUninit<T>::zeroed().assume_init()`.
1555///
1556/// # Examples
1557///
1558/// ```
1559/// use pin_init::{Zeroable, zeroed};
1560///
1561/// #[derive(Zeroable)]
1562/// struct Point {
1563/// x: u32,
1564/// y: u32,
1565/// }
1566///
1567/// let point: Point = zeroed();
1568/// assert_eq!(point.x, 0);
1569/// assert_eq!(point.y, 0);
1570/// ```
1571pub const fn zeroed<T: Zeroable>() -> T {
1572 // SAFETY:By the type invariants of `Zeroable`, all zeroes is a valid bit pattern for `T`.
1573 unsafe { core::mem::zeroed() }
1574}
1575
1576macro_rules! impl_zeroable {
1577 ($($({$($generics:tt)*})? $t:ty, )*) => {
1578 // SAFETY: Safety comments written in the macro invocation.
1579 $(unsafe impl$($($generics)*)? Zeroable for $t {})*
1580 };
1581}
1582
1583impl_zeroable! {
1584 // SAFETY: All primitives that are allowed to be zero.
1585 bool,
1586 char,
1587 u8, u16, u32, u64, u128, usize,
1588 i8, i16, i32, i64, i128, isize,
1589 f32, f64,
1590
1591 // Note: do not add uninhabited types (such as `!` or `core::convert::Infallible`) to this list;
1592 // creating an instance of an uninhabited type is immediate undefined behavior. For more on
1593 // uninhabited/empty types, consult The Rustonomicon:
1594 // <https://doc.rust-lang.org/stable/nomicon/exotic-sizes.html#empty-types>. The Rust Reference
1595 // also has information on undefined behavior:
1596 // <https://doc.rust-lang.org/stable/reference/behavior-considered-undefined.html>.
1597 //
1598 // SAFETY: These are inhabited ZSTs; there is nothing to zero and a valid value exists.
1599 {<T: ?Sized>} PhantomData<T>, core::marker::PhantomPinned, (),
1600
1601 // SAFETY: Type is allowed to take any value, including all zeros.
1602 {<T>} MaybeUninit<T>,
1603
1604 // SAFETY: `T: Zeroable` and `UnsafeCell` is `repr(transparent)`.
1605 {<T: ?Sized + Zeroable>} UnsafeCell<T>,
1606
1607 // SAFETY: `null` pointer is valid.
1608 //
1609 // We cannot use `T: ?Sized`, since the VTABLE pointer part of fat pointers is not allowed to be
1610 // null.
1611 //
1612 // When `Pointee` gets stabilized, we could use
1613 // `T: ?Sized where <T as Pointee>::Metadata: Zeroable`
1614 {<T>} *mut T, {<T>} *const T,
1615
1616 // SAFETY: `null` pointer is valid and the metadata part of these fat pointers is allowed to be
1617 // zero.
1618 {<T>} *mut [T], {<T>} *const [T], *mut str, *const str,
1619
1620 // SAFETY: `T` is `Zeroable`.
1621 {<const N: usize, T: Zeroable>} [T; N], {<T: Zeroable>} Wrapping<T>,
1622}
1623
1624macro_rules! impl_tuple_zeroable {
1625 ($first:ident, $(,)?) => {
1626 #[cfg_attr(all(USE_RUSTC_FEATURES, doc), doc(fake_variadic))]
1627 /// Implemented for tuples up to 10 items long.
1628 // SAFETY: All elements are zeroable and padding can be zero.
1629 unsafe impl<$first: Zeroable> Zeroable for ($first,) {}
1630 };
1631 ($first:ident, $($t:ident),* $(,)?) => {
1632 #[cfg_attr(doc, doc(hidden))]
1633 // SAFETY: All elements are zeroable and padding can be zero.
1634 unsafe impl<$first: Zeroable, $($t: Zeroable),*> Zeroable for ($first, $($t),*) {}
1635 impl_tuple_zeroable!($($t),* ,);
1636 }
1637}
1638
1639impl_tuple_zeroable!(A, B, C, D, E, F, G, H, I, J);
1640
1641/// Marker trait for types that allow `Option<Self>` to be set to all zeroes in order to write
1642/// `None` to that location.
1643///
1644/// # Safety
1645///
1646/// The implementer needs to ensure that `unsafe impl Zeroable for Option<Self> {}` is sound.
1647pub unsafe trait ZeroableOption {}
1648
1649// SAFETY: by the safety requirement of `ZeroableOption`, this is valid.
1650unsafe impl<T: ZeroableOption> Zeroable for Option<T> {}
1651
1652macro_rules! impl_fn_zeroable_option {
1653 ([$($abi:literal),* $(,)?] $args:tt) => {
1654 $(impl_fn_zeroable_option!({extern $abi} $args);)*
1655 $(impl_fn_zeroable_option!({unsafe extern $abi} $args);)*
1656 };
1657 ({$($prefix:tt)*} {$(,)?}) => {};
1658 ({$($prefix:tt)*} {$ret:ident, $arg:ident $(,)?}) => {
1659 #[cfg_attr(all(USE_RUSTC_FEATURES, doc), doc(fake_variadic))]
1660 /// Implemented for function pointers with up to 20 arity.
1661 // SAFETY: function pointers are part of the option layout optimization:
1662 // <https://doc.rust-lang.org/stable/std/option/index.html#representation>.
1663 unsafe impl<$ret, $arg> ZeroableOption for $($prefix)* fn($arg) -> $ret {}
1664 impl_fn_zeroable_option!({$($prefix)*} {$arg,});
1665 };
1666 ({$($prefix:tt)*} {$ret:ident, $($rest:ident),* $(,)?}) => {
1667 #[cfg_attr(doc, doc(hidden))]
1668 // SAFETY: function pointers are part of the option layout optimization:
1669 // <https://doc.rust-lang.org/stable/std/option/index.html#representation>.
1670 unsafe impl<$ret, $($rest),*> ZeroableOption for $($prefix)* fn($($rest),*) -> $ret {}
1671 impl_fn_zeroable_option!({$($prefix)*} {$($rest),*,});
1672 };
1673}
1674
1675impl_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 });
1676
1677macro_rules! impl_zeroable_option {
1678 ($($({$($generics:tt)*})? $t:ty, )*) => {
1679 // SAFETY: Safety comments written in the macro invocation.
1680 $(unsafe impl$($($generics)*)? ZeroableOption for $t {})*
1681 };
1682}
1683
1684impl_zeroable_option! {
1685 // SAFETY: `Option<&T>` is part of the option layout optimization guarantee:
1686 // <https://doc.rust-lang.org/stable/std/option/index.html#representation>.
1687 {<T: ?Sized>} &T,
1688 // SAFETY: `Option<&mut T>` is part of the option layout optimization guarantee:
1689 // <https://doc.rust-lang.org/stable/std/option/index.html#representation>.
1690 {<T: ?Sized>} &mut T,
1691 // SAFETY: `Option<NonNull<T>>` is part of the option layout optimization guarantee:
1692 // <https://doc.rust-lang.org/stable/std/option/index.html#representation>.
1693 {<T: ?Sized>} NonNull<T>,
1694 // SAFETY: All zeros is equivalent to `None` (option layout optimization guarantee:
1695 // <https://doc.rust-lang.org/stable/std/option/index.html#representation>).
1696 NonZero<u8>, NonZero<u16>, NonZero<u32>, NonZero<u64>, NonZero<u128>, NonZero<usize>,
1697 NonZero<i8>, NonZero<i16>, NonZero<i32>, NonZero<i64>, NonZero<i128>, NonZero<isize>,
1698}
1699
1700/// This trait allows creating an instance of `Self` which contains exactly one
1701/// [structurally pinned value](https://doc.rust-lang.org/std/pin/index.html#projections-and-structural-pinning).
1702///
1703/// This is useful when using wrapper `struct`s like [`UnsafeCell`] or with new-type `struct`s.
1704///
1705/// # Examples
1706///
1707/// ```
1708/// # use core::cell::UnsafeCell;
1709/// # use pin_init::{pin_data, pin_init, Wrapper};
1710///
1711/// #[pin_data]
1712/// struct Foo {}
1713///
1714/// #[pin_data]
1715/// struct Bar {
1716/// #[pin]
1717/// content: UnsafeCell<Foo>
1718/// };
1719///
1720/// let foo_initializer = pin_init!(Foo{});
1721/// let initializer = pin_init!(Bar {
1722/// content <- UnsafeCell::pin_init(foo_initializer)
1723/// });
1724/// ```
1725pub trait Wrapper<T> {
1726 /// Creates an pin-initializer for a [`Self`] containing `T` from the `value_init` initializer.
1727 fn pin_init<E>(value_init: impl PinInit<T, E>) -> impl PinInit<Self, E>;
1728}
1729
1730impl<T> Wrapper<T> for UnsafeCell<T> {
1731 fn pin_init<E>(value_init: impl PinInit<T, E>) -> impl PinInit<Self, E> {
1732 // SAFETY: `UnsafeCell<T>` has a compatible layout to `T`.
1733 unsafe { cast_pin_init(value_init) }
1734 }
1735}
1736
1737impl<T> Wrapper<T> for MaybeUninit<T> {
1738 fn pin_init<E>(value_init: impl PinInit<T, E>) -> impl PinInit<Self, E> {
1739 // SAFETY: `MaybeUninit<T>` has a compatible layout to `T`.
1740 unsafe { cast_pin_init(value_init) }
1741 }
1742}
1743
1744#[cfg(all(feature = "unsafe-pinned", CONFIG_RUSTC_HAS_UNSAFE_PINNED))]
1745impl<T> Wrapper<T> for core::pin::UnsafePinned<T> {
1746 fn pin_init<E>(init: impl PinInit<T, E>) -> impl PinInit<Self, E> {
1747 // SAFETY: `UnsafePinned<T>` has a compatible layout to `T`.
1748 unsafe { cast_pin_init(init) }
1749 }
1750}