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