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