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