1 // SPDX-License-Identifier: Apache-2.0 OR MIT 2 3 //! Library to safely and fallibly initialize pinned `struct`s using in-place constructors. 4 //! 5 //! [Pinning][pinning] is Rust's way of ensuring data does not move. 6 //! 7 //! It also allows in-place initialization of big `struct`s that would otherwise produce a stack 8 //! overflow. 9 //! 10 //! This library's main use-case is in [Rust-for-Linux]. Although this version can be used 11 //! standalone. 12 //! 13 //! There are cases when you want to in-place initialize a struct. For example when it is very big 14 //! and moving it from the stack is not an option, because it is bigger than the stack itself. 15 //! Another reason would be that you need the address of the object to initialize it. This stands 16 //! in direct conflict with Rust's normal process of first initializing an object and then moving 17 //! it into it's final memory location. For more information, see 18 //! <https://rust-for-linux.com/the-safe-pinned-initialization-problem>. 19 //! 20 //! This library allows you to do in-place initialization safely. 21 //! 22 //! ## Nightly Needed for `alloc` feature 23 //! 24 //! This library requires the [`allocator_api` unstable feature] when the `alloc` feature is 25 //! enabled and thus this feature can only be used with a nightly compiler. When enabling the 26 //! `alloc` feature, the user will be required to activate `allocator_api` as well. 27 //! 28 //! [`allocator_api` unstable feature]: https://doc.rust-lang.org/nightly/unstable-book/library-features/allocator-api.html 29 //! 30 //! The feature is enabled by default, thus by default `pin-init` will require a nightly compiler. 31 //! However, using the crate on stable compilers is possible by disabling `alloc`. In practice this 32 //! will require the `std` feature, because stable compilers have neither `Box` nor `Arc` in no-std 33 //! mode. 34 //! 35 //! ## Nightly needed for `unsafe-pinned` feature 36 //! 37 //! This feature enables the `Wrapper` implementation on the unstable `core::pin::UnsafePinned` type. 38 //! This requires the [`unsafe_pinned` unstable feature](https://github.com/rust-lang/rust/issues/125735) 39 //! and therefore a nightly compiler. Note that this feature is not enabled by default. 40 //! 41 //! # Overview 42 //! 43 //! To initialize a `struct` with an in-place constructor you will need two things: 44 //! - an in-place constructor, 45 //! - a memory location that can hold your `struct` (this can be the [stack], an [`Arc<T>`], 46 //! [`Box<T>`] or any other smart pointer that supports this library). 47 //! 48 //! To get an in-place constructor there are generally three options: 49 //! - directly creating an in-place constructor using the [`pin_init!`] macro, 50 //! - a custom function/macro returning an in-place constructor provided by someone else, 51 //! - using the unsafe function [`pin_init_from_closure()`] to manually create an initializer. 52 //! 53 //! Aside from pinned initialization, this library also supports in-place construction without 54 //! pinning, the macros/types/functions are generally named like the pinned variants without the 55 //! `pin_` prefix. 56 //! 57 //! # Examples 58 //! 59 //! Throughout the examples we will often make use of the `CMutex` type which can be found in 60 //! `../examples/mutex.rs`. It is essentially a userland rebuild of the `struct mutex` type from 61 //! the Linux kernel. It also uses a wait list and a basic spinlock. Importantly the wait list 62 //! requires it to be pinned to be locked and thus is a prime candidate for using this library. 63 //! 64 //! ## Using the [`pin_init!`] macro 65 //! 66 //! If you want to use [`PinInit`], then you will have to annotate your `struct` with 67 //! `#[`[`pin_data`]`]`. It is a macro that uses `#[pin]` as a marker for 68 //! [structurally pinned fields]. After doing this, you can then create an in-place constructor via 69 //! [`pin_init!`]. The syntax is almost the same as normal `struct` initializers. The difference is 70 //! that you need to write `<-` instead of `:` for fields that you want to initialize in-place. 71 //! 72 //! ```rust 73 //! # #![expect(clippy::disallowed_names)] 74 //! # #![feature(allocator_api)] 75 //! # #[path = "../examples/mutex.rs"] mod mutex; use mutex::*; 76 //! # use core::pin::Pin; 77 //! use pin_init::{pin_data, pin_init, InPlaceInit}; 78 //! 79 //! #[pin_data] 80 //! struct Foo { 81 //! #[pin] 82 //! a: CMutex<usize>, 83 //! b: u32, 84 //! } 85 //! 86 //! let foo = pin_init!(Foo { 87 //! a <- CMutex::new(42), 88 //! b: 24, 89 //! }); 90 //! # let _ = Box::pin_init(foo); 91 //! ``` 92 //! 93 //! `foo` now is of the type [`impl PinInit<Foo>`]. We can now use any smart pointer that we like 94 //! (or just the stack) to actually initialize a `Foo`: 95 //! 96 //! ```rust 97 //! # #![expect(clippy::disallowed_names)] 98 //! # #![feature(allocator_api)] 99 //! # #[path = "../examples/mutex.rs"] mod mutex; use mutex::*; 100 //! # use core::{alloc::AllocError, pin::Pin}; 101 //! # use pin_init::*; 102 //! # 103 //! # #[pin_data] 104 //! # struct Foo { 105 //! # #[pin] 106 //! # a: CMutex<usize>, 107 //! # b: u32, 108 //! # } 109 //! # 110 //! # let foo = pin_init!(Foo { 111 //! # a <- CMutex::new(42), 112 //! # b: 24, 113 //! # }); 114 //! let foo: Result<Pin<Box<Foo>>, AllocError> = Box::pin_init(foo); 115 //! ``` 116 //! 117 //! For more information see the [`pin_init!`] macro. 118 //! 119 //! ## Using a custom function/macro that returns an initializer 120 //! 121 //! Many types that use this library supply a function/macro that returns an initializer, because 122 //! the above method only works for types where you can access the fields. 123 //! 124 //! ```rust 125 //! # #![feature(allocator_api)] 126 //! # #[path = "../examples/mutex.rs"] mod mutex; use mutex::*; 127 //! # use pin_init::*; 128 //! # use std::sync::Arc; 129 //! # use core::pin::Pin; 130 //! let mtx: Result<Pin<Arc<CMutex<usize>>>, _> = Arc::pin_init(CMutex::new(42)); 131 //! ``` 132 //! 133 //! To declare an init macro/function you just return an [`impl PinInit<T, E>`]: 134 //! 135 //! ```rust 136 //! # #![feature(allocator_api)] 137 //! # use pin_init::*; 138 //! # #[path = "../examples/error.rs"] mod error; use error::Error; 139 //! # #[path = "../examples/mutex.rs"] mod mutex; use mutex::*; 140 //! #[pin_data] 141 //! struct DriverData { 142 //! #[pin] 143 //! status: CMutex<i32>, 144 //! buffer: Box<[u8; 1_000_000]>, 145 //! } 146 //! 147 //! impl DriverData { 148 //! fn new() -> impl PinInit<Self, Error> { 149 //! pin_init!(Self { 150 //! status <- CMutex::new(0), 151 //! buffer: Box::init(pin_init::init_zeroed())?, 152 //! }? Error) 153 //! } 154 //! } 155 //! ``` 156 //! 157 //! ## Manual creation of an initializer 158 //! 159 //! Often when working with primitives the previous approaches are not sufficient. That is where 160 //! [`pin_init_from_closure()`] comes in. This `unsafe` function allows you to create a 161 //! [`impl PinInit<T, E>`] directly from a closure. Of course you have to ensure that the closure 162 //! actually does the initialization in the correct way. Here are the things to look out for 163 //! (we are calling the parameter to the closure `slot`): 164 //! - when the closure returns `Ok(())`, then it has completed the initialization successfully, so 165 //! `slot` now contains a valid bit pattern for the type `T`, 166 //! - when the closure returns `Err(e)`, then the caller may deallocate the memory at `slot`, so 167 //! you need to take care to clean up anything if your initialization fails mid-way, 168 //! - you may assume that `slot` will stay pinned even after the closure returns until `drop` of 169 //! `slot` gets called. 170 //! 171 //! ```rust 172 //! # #![feature(extern_types)] 173 //! use pin_init::{pin_data, pinned_drop, PinInit, PinnedDrop, pin_init_from_closure}; 174 //! use core::{ 175 //! 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(USE_RUSTC_FEATURES, feature(lint_reasons))] 268 #![cfg_attr( 269 all(any(feature = "alloc", feature = "std"), USE_RUSTC_FEATURES), 270 feature(new_uninit) 271 )] 272 #![forbid(missing_docs, unsafe_op_in_unsafe_fn)] 273 #![cfg_attr(not(feature = "std"), no_std)] 274 #![cfg_attr(feature = "alloc", feature(allocator_api))] 275 #![cfg_attr( 276 all(feature = "unsafe-pinned", CONFIG_RUSTC_HAS_UNSAFE_PINNED), 277 feature(unsafe_pinned) 278 )] 279 280 use core::{ 281 cell::UnsafeCell, 282 convert::Infallible, 283 marker::PhantomData, 284 mem::MaybeUninit, 285 num::*, 286 pin::Pin, 287 ptr::{self, NonNull}, 288 }; 289 290 // This is used by doc-tests -- the proc-macros expand to `::pin_init::...` and without this the 291 // doc-tests wouldn't have an extern crate named `pin_init`. 292 #[allow(unused_extern_crates)] 293 extern crate self as pin_init; 294 295 #[doc(hidden)] 296 pub mod __internal; 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 = 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 =? 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, fallible pinned initializer for `struct`s. 588 /// 589 /// The error type defaults to [`Infallible`]; if you need a different one, write `? Error` at the 590 /// end, after the struct initializer. 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 /// - You can use `_: { /* run any user-code here */ },` anywhere where you can place fields in 744 /// order to run arbitrary code. 745 /// - In front of the initializer you can write `&this in` to have access to a [`NonNull<Self>`] 746 /// pointer named `this` inside of the initializer. 747 /// - Using struct update syntax one can place `..Zeroable::init_zeroed()` at the very end of the 748 /// struct, this initializes every field with 0 and then runs all initializers specified in the 749 /// body. This can only be done if [`Zeroable`] is implemented for the struct. 750 /// 751 /// For instance: 752 /// 753 /// ```rust 754 /// # use pin_init::*; 755 /// # use core::{ptr::addr_of_mut, marker::PhantomPinned}; 756 /// #[pin_data] 757 /// #[derive(Zeroable)] 758 /// struct Buf { 759 /// // `ptr` points into `buf`. 760 /// ptr: *mut u8, 761 /// buf: [u8; 64], 762 /// #[pin] 763 /// pin: PhantomPinned, 764 /// } 765 /// 766 /// let init = pin_init!(&this in Buf { 767 /// buf: [0; 64], 768 /// // SAFETY: TODO. 769 /// ptr: unsafe { addr_of_mut!((*this.as_ptr()).buf).cast() }, 770 /// pin: PhantomPinned, 771 /// }); 772 /// let init = pin_init!(Buf { 773 /// buf: [1; 64], 774 /// ..Zeroable::init_zeroed() 775 /// }); 776 /// ``` 777 /// 778 /// [`NonNull<Self>`]: core::ptr::NonNull 779 pub use pin_init_internal::pin_init; 780 781 /// Construct an in-place, fallible initializer for `struct`s. 782 /// 783 /// This macro defaults the error to [`Infallible`]; if you need a different one, write `? Error` 784 /// at the end, after the struct initializer. 785 /// 786 /// The syntax is identical to [`pin_init!`] and its safety caveats also apply: 787 /// - `unsafe` code must guarantee either full initialization or return an error and allow 788 /// deallocation of the memory. 789 /// - the fields are initialized in the order given in the initializer. 790 /// - no references to fields are allowed to be created inside of the initializer. 791 /// 792 /// This initializer is for initializing data in-place that might later be moved. If you want to 793 /// pin-initialize, use [`pin_init!`]. 794 /// 795 /// # Examples 796 /// 797 /// ```rust 798 /// # #![feature(allocator_api)] 799 /// # #[path = "../examples/error.rs"] mod error; use error::Error; 800 /// # #[path = "../examples/mutex.rs"] mod mutex; use mutex::*; 801 /// # use pin_init::InPlaceInit; 802 /// use pin_init::{init, Init, init_zeroed}; 803 /// 804 /// struct BigBuf { 805 /// small: [u8; 1024 * 1024], 806 /// } 807 /// 808 /// impl BigBuf { 809 /// fn new() -> impl Init<Self> { 810 /// init!(Self { 811 /// small <- init_zeroed(), 812 /// }) 813 /// } 814 /// } 815 /// # let _ = Box::init(BigBuf::new()); 816 /// ``` 817 pub use pin_init_internal::init; 818 819 /// Asserts that a field on a struct using `#[pin_data]` is marked with `#[pin]` ie. that it is 820 /// structurally pinned. 821 /// 822 /// # Examples 823 /// 824 /// This will succeed: 825 /// ``` 826 /// use pin_init::{pin_data, assert_pinned}; 827 /// 828 /// #[pin_data] 829 /// struct MyStruct { 830 /// #[pin] 831 /// some_field: u64, 832 /// } 833 /// 834 /// assert_pinned!(MyStruct, some_field, u64); 835 /// ``` 836 /// 837 /// This will fail: 838 /// ```compile_fail 839 /// use pin_init::{pin_data, assert_pinned}; 840 /// 841 /// #[pin_data] 842 /// struct MyStruct { 843 /// some_field: u64, 844 /// } 845 /// 846 /// assert_pinned!(MyStruct, some_field, u64); 847 /// ``` 848 /// 849 /// Some uses of the macro may trigger the `can't use generic parameters from outer item` error. To 850 /// work around this, you may pass the `inline` parameter to the macro. The `inline` parameter can 851 /// only be used when the macro is invoked from a function body. 852 /// ``` 853 /// # use core::pin::Pin; 854 /// use pin_init::{pin_data, assert_pinned}; 855 /// 856 /// #[pin_data] 857 /// struct Foo<T> { 858 /// #[pin] 859 /// elem: T, 860 /// } 861 /// 862 /// impl<T> Foo<T> { 863 /// fn project_this(self: Pin<&mut Self>) -> Pin<&mut T> { 864 /// assert_pinned!(Foo<T>, elem, T, inline); 865 /// 866 /// // SAFETY: The field is structurally pinned. 867 /// unsafe { self.map_unchecked_mut(|me| &mut me.elem) } 868 /// } 869 /// } 870 /// ``` 871 #[macro_export] 872 macro_rules! assert_pinned { 873 ($ty:ty, $field:ident, $field_ty:ty, inline) => { 874 let _ = move |ptr: *mut $field_ty| { 875 // SAFETY: This code is unreachable. 876 let data = unsafe { <$ty as $crate::__internal::HasPinData>::__pin_data() }; 877 let init = $crate::__internal::AlwaysFail::<$field_ty>::new(); 878 // SAFETY: This code is unreachable. 879 unsafe { data.$field(ptr, init) }.ok(); 880 }; 881 }; 882 883 ($ty:ty, $field:ident, $field_ty:ty) => { 884 const _: () = { 885 $crate::assert_pinned!($ty, $field, $field_ty, inline); 886 }; 887 }; 888 } 889 890 /// A pin-initializer for the type `T`. 891 /// 892 /// To use this initializer, you will need a suitable memory location that can hold a `T`. This can 893 /// be [`Box<T>`], [`Arc<T>`] or even the stack (see [`stack_pin_init!`]). 894 /// 895 /// Also see the [module description](self). 896 /// 897 /// # Safety 898 /// 899 /// When implementing this trait you will need to take great care. Also there are probably very few 900 /// cases where a manual implementation is necessary. Use [`pin_init_from_closure`] where possible. 901 /// 902 /// The [`PinInit::__pinned_init`] function: 903 /// - returns `Ok(())` if it initialized every field of `slot`, 904 /// - returns `Err(err)` if it encountered an error and then cleaned `slot`, this means: 905 /// - `slot` can be deallocated without UB occurring, 906 /// - `slot` does not need to be dropped, 907 /// - `slot` is not partially initialized. 908 /// - while constructing the `T` at `slot` it upholds the pinning invariants of `T`. 909 /// 910 #[cfg_attr( 911 kernel, 912 doc = "[`Arc<T>`]: https://rust.docs.kernel.org/kernel/sync/struct.Arc.html" 913 )] 914 #[cfg_attr( 915 kernel, 916 doc = "[`Box<T>`]: https://rust.docs.kernel.org/kernel/alloc/kbox/struct.Box.html" 917 )] 918 #[cfg_attr(not(kernel), doc = "[`Arc<T>`]: alloc::alloc::sync::Arc")] 919 #[cfg_attr(not(kernel), doc = "[`Box<T>`]: alloc::alloc::boxed::Box")] 920 #[must_use = "An initializer must be used in order to create its value."] 921 pub unsafe trait PinInit<T: ?Sized, E = Infallible>: Sized { 922 /// Initializes `slot`. 923 /// 924 /// # Safety 925 /// 926 /// - `slot` is a valid pointer to uninitialized memory. 927 /// - the caller does not touch `slot` when `Err` is returned, they are only permitted to 928 /// deallocate. 929 /// - `slot` will not move until it is dropped, i.e. it will be pinned. 930 unsafe fn __pinned_init(self, slot: *mut T) -> Result<(), E>; 931 932 /// First initializes the value using `self` then calls the function `f` with the initialized 933 /// value. 934 /// 935 /// If `f` returns an error the value is dropped and the initializer will forward the error. 936 /// 937 /// # Examples 938 /// 939 /// ```rust 940 /// # #![feature(allocator_api)] 941 /// # #[path = "../examples/mutex.rs"] mod mutex; use mutex::*; 942 /// # use pin_init::*; 943 /// let mtx_init = CMutex::new(42); 944 /// // Make the initializer print the value. 945 /// let mtx_init = mtx_init.pin_chain(|mtx| { 946 /// println!("{:?}", mtx.get_data_mut()); 947 /// Ok(()) 948 /// }); 949 /// ``` 950 fn pin_chain<F>(self, f: F) -> ChainPinInit<Self, F, T, E> 951 where 952 F: FnOnce(Pin<&mut T>) -> Result<(), E>, 953 { 954 ChainPinInit(self, f, PhantomData) 955 } 956 } 957 958 /// An initializer returned by [`PinInit::pin_chain`]. 959 pub struct ChainPinInit<I, F, T: ?Sized, E>(I, F, __internal::Invariant<(E, T)>); 960 961 // SAFETY: The `__pinned_init` function is implemented such that it 962 // - returns `Ok(())` on successful initialization, 963 // - returns `Err(err)` on error and in this case `slot` will be dropped. 964 // - considers `slot` pinned. 965 unsafe impl<T: ?Sized, E, I, F> PinInit<T, E> for ChainPinInit<I, F, T, E> 966 where 967 I: PinInit<T, E>, 968 F: FnOnce(Pin<&mut T>) -> Result<(), E>, 969 { 970 unsafe fn __pinned_init(self, slot: *mut T) -> Result<(), E> { 971 // SAFETY: All requirements fulfilled since this function is `__pinned_init`. 972 unsafe { self.0.__pinned_init(slot)? }; 973 // SAFETY: The above call initialized `slot` and we still have unique access. 974 let val = unsafe { &mut *slot }; 975 // SAFETY: `slot` is considered pinned. 976 let val = unsafe { Pin::new_unchecked(val) }; 977 // SAFETY: `slot` was initialized above. 978 (self.1)(val).inspect_err(|_| unsafe { core::ptr::drop_in_place(slot) }) 979 } 980 } 981 982 /// An initializer for `T`. 983 /// 984 /// To use this initializer, you will need a suitable memory location that can hold a `T`. This can 985 /// be [`Box<T>`], [`Arc<T>`] or even the stack (see [`stack_pin_init!`]). Because 986 /// [`PinInit<T, E>`] is a super trait, you can use every function that takes it as well. 987 /// 988 /// Also see the [module description](self). 989 /// 990 /// # Safety 991 /// 992 /// When implementing this trait you will need to take great care. Also there are probably very few 993 /// cases where a manual implementation is necessary. Use [`init_from_closure`] where possible. 994 /// 995 /// The [`Init::__init`] function: 996 /// - returns `Ok(())` if it initialized every field of `slot`, 997 /// - returns `Err(err)` if it encountered an error and then cleaned `slot`, this means: 998 /// - `slot` can be deallocated without UB occurring, 999 /// - `slot` does not need to be dropped, 1000 /// - `slot` is not partially initialized. 1001 /// - while constructing the `T` at `slot` it upholds the pinning invariants of `T`. 1002 /// 1003 /// The `__pinned_init` function from the supertrait [`PinInit`] needs to execute the exact same 1004 /// code as `__init`. 1005 /// 1006 /// Contrary to its supertype [`PinInit<T, E>`] the caller is allowed to 1007 /// move the pointee after initialization. 1008 /// 1009 #[cfg_attr( 1010 kernel, 1011 doc = "[`Arc<T>`]: https://rust.docs.kernel.org/kernel/sync/struct.Arc.html" 1012 )] 1013 #[cfg_attr( 1014 kernel, 1015 doc = "[`Box<T>`]: https://rust.docs.kernel.org/kernel/alloc/kbox/struct.Box.html" 1016 )] 1017 #[cfg_attr(not(kernel), doc = "[`Arc<T>`]: alloc::alloc::sync::Arc")] 1018 #[cfg_attr(not(kernel), doc = "[`Box<T>`]: alloc::alloc::boxed::Box")] 1019 #[must_use = "An initializer must be used in order to create its value."] 1020 pub unsafe trait Init<T: ?Sized, E = Infallible>: PinInit<T, E> { 1021 /// Initializes `slot`. 1022 /// 1023 /// # Safety 1024 /// 1025 /// - `slot` is a valid pointer to uninitialized memory. 1026 /// - the caller does not touch `slot` when `Err` is returned, they are only permitted to 1027 /// deallocate. 1028 unsafe fn __init(self, slot: *mut T) -> Result<(), E>; 1029 1030 /// First initializes the value using `self` then calls the function `f` with the initialized 1031 /// value. 1032 /// 1033 /// If `f` returns an error the value is dropped and the initializer will forward the error. 1034 /// 1035 /// # Examples 1036 /// 1037 /// ```rust 1038 /// # #![expect(clippy::disallowed_names)] 1039 /// use pin_init::{init, init_zeroed, Init}; 1040 /// 1041 /// struct Foo { 1042 /// buf: [u8; 1_000_000], 1043 /// } 1044 /// 1045 /// impl Foo { 1046 /// fn setup(&mut self) { 1047 /// println!("Setting up foo"); 1048 /// } 1049 /// } 1050 /// 1051 /// let foo = init!(Foo { 1052 /// buf <- init_zeroed() 1053 /// }).chain(|foo| { 1054 /// foo.setup(); 1055 /// Ok(()) 1056 /// }); 1057 /// ``` 1058 fn chain<F>(self, f: F) -> ChainInit<Self, F, T, E> 1059 where 1060 F: FnOnce(&mut T) -> Result<(), E>, 1061 { 1062 ChainInit(self, f, PhantomData) 1063 } 1064 } 1065 1066 /// An initializer returned by [`Init::chain`]. 1067 pub struct ChainInit<I, F, T: ?Sized, E>(I, F, __internal::Invariant<(E, T)>); 1068 1069 // SAFETY: The `__init` function is implemented such that it 1070 // - returns `Ok(())` on successful initialization, 1071 // - returns `Err(err)` on error and in this case `slot` will be dropped. 1072 unsafe impl<T: ?Sized, E, I, F> Init<T, E> for ChainInit<I, F, T, E> 1073 where 1074 I: Init<T, E>, 1075 F: FnOnce(&mut T) -> Result<(), E>, 1076 { 1077 unsafe fn __init(self, slot: *mut T) -> Result<(), E> { 1078 // SAFETY: All requirements fulfilled since this function is `__init`. 1079 unsafe { self.0.__pinned_init(slot)? }; 1080 // SAFETY: The above call initialized `slot` and we still have unique access. 1081 (self.1)(unsafe { &mut *slot }).inspect_err(|_| 1082 // SAFETY: `slot` was initialized above. 1083 unsafe { core::ptr::drop_in_place(slot) }) 1084 } 1085 } 1086 1087 // SAFETY: `__pinned_init` behaves exactly the same as `__init`. 1088 unsafe impl<T: ?Sized, E, I, F> PinInit<T, E> for ChainInit<I, F, T, E> 1089 where 1090 I: Init<T, E>, 1091 F: FnOnce(&mut T) -> Result<(), E>, 1092 { 1093 unsafe fn __pinned_init(self, slot: *mut T) -> Result<(), E> { 1094 // SAFETY: `__init` has less strict requirements compared to `__pinned_init`. 1095 unsafe { self.__init(slot) } 1096 } 1097 } 1098 1099 /// Creates a new [`PinInit<T, E>`] from the given closure. 1100 /// 1101 /// # Safety 1102 /// 1103 /// The closure: 1104 /// - returns `Ok(())` if it initialized every field of `slot`, 1105 /// - returns `Err(err)` if it encountered an error and then cleaned `slot`, this means: 1106 /// - `slot` can be deallocated without UB occurring, 1107 /// - `slot` does not need to be dropped, 1108 /// - `slot` is not partially initialized. 1109 /// - may assume that the `slot` does not move if `T: !Unpin`, 1110 /// - while constructing the `T` at `slot` it upholds the pinning invariants of `T`. 1111 #[inline] 1112 pub const unsafe fn pin_init_from_closure<T: ?Sized, E>( 1113 f: impl FnOnce(*mut T) -> Result<(), E>, 1114 ) -> impl PinInit<T, E> { 1115 __internal::InitClosure(f, PhantomData) 1116 } 1117 1118 /// Creates a new [`Init<T, E>`] from the given closure. 1119 /// 1120 /// # Safety 1121 /// 1122 /// The closure: 1123 /// - returns `Ok(())` if it initialized every field of `slot`, 1124 /// - returns `Err(err)` if it encountered an error and then cleaned `slot`, this means: 1125 /// - `slot` can be deallocated without UB occurring, 1126 /// - `slot` does not need to be dropped, 1127 /// - `slot` is not partially initialized. 1128 /// - the `slot` may move after initialization. 1129 /// - while constructing the `T` at `slot` it upholds the pinning invariants of `T`. 1130 #[inline] 1131 pub const unsafe fn init_from_closure<T: ?Sized, E>( 1132 f: impl FnOnce(*mut T) -> Result<(), E>, 1133 ) -> impl Init<T, E> { 1134 __internal::InitClosure(f, PhantomData) 1135 } 1136 1137 /// Changes the to be initialized type. 1138 /// 1139 /// # Safety 1140 /// 1141 /// - `*mut U` must be castable to `*mut T` and any value of type `T` written through such a 1142 /// pointer must result in a valid `U`. 1143 pub const unsafe fn cast_pin_init<T, U, E>(init: impl PinInit<T, E>) -> impl PinInit<U, E> { 1144 // SAFETY: initialization delegated to a valid initializer. Cast is valid by function safety 1145 // requirements. 1146 let res = unsafe { pin_init_from_closure(|ptr: *mut U| init.__pinned_init(ptr.cast::<T>())) }; 1147 // FIXME: remove the let statement once the nightly-MSRV allows it (1.78 otherwise encounters a 1148 // cycle when computing the type returned by this function) 1149 #[allow(clippy::let_and_return)] 1150 res 1151 } 1152 1153 /// Changes the to be initialized type. 1154 /// 1155 /// # Safety 1156 /// 1157 /// - `*mut U` must be castable to `*mut T` and any value of type `T` written through such a 1158 /// pointer must result in a valid `U`. 1159 pub const unsafe fn cast_init<T, U, E>(init: impl Init<T, E>) -> impl Init<U, E> { 1160 // SAFETY: initialization delegated to a valid initializer. Cast is valid by function safety 1161 // requirements. 1162 let res = unsafe { init_from_closure(|ptr: *mut U| init.__init(ptr.cast::<T>())) }; 1163 // FIXME: remove the let statement once the nightly-MSRV allows it (1.78 otherwise encounters a 1164 // cycle when computing the type returned by this function) 1165 #[allow(clippy::let_and_return)] 1166 res 1167 } 1168 1169 /// An initializer that leaves the memory uninitialized. 1170 /// 1171 /// The initializer is a no-op. The `slot` memory is not changed. 1172 #[inline] 1173 pub fn uninit<T, E>() -> impl Init<MaybeUninit<T>, E> { 1174 // SAFETY: The memory is allowed to be uninitialized. 1175 unsafe { init_from_closure(|_| Ok(())) } 1176 } 1177 1178 /// Initializes an array by initializing each element via the provided initializer. 1179 /// 1180 /// # Examples 1181 /// 1182 /// ```rust 1183 /// # use pin_init::*; 1184 /// use pin_init::init_array_from_fn; 1185 /// let array: Box<[usize; 1_000]> = Box::init(init_array_from_fn(|i| i)).unwrap(); 1186 /// assert_eq!(array.len(), 1_000); 1187 /// ``` 1188 pub fn init_array_from_fn<I, const N: usize, T, E>( 1189 mut make_init: impl FnMut(usize) -> I, 1190 ) -> impl Init<[T; N], E> 1191 where 1192 I: Init<T, E>, 1193 { 1194 let init = move |slot: *mut [T; N]| { 1195 let slot = slot.cast::<T>(); 1196 for i in 0..N { 1197 let init = make_init(i); 1198 // SAFETY: Since 0 <= `i` < N, it is still in bounds of `[T; N]`. 1199 let ptr = unsafe { slot.add(i) }; 1200 // SAFETY: The pointer is derived from `slot` and thus satisfies the `__init` 1201 // requirements. 1202 if let Err(e) = unsafe { init.__init(ptr) } { 1203 // SAFETY: The loop has initialized the elements `slot[0..i]` and since we return 1204 // `Err` below, `slot` will be considered uninitialized memory. 1205 unsafe { ptr::drop_in_place(ptr::slice_from_raw_parts_mut(slot, i)) }; 1206 return Err(e); 1207 } 1208 } 1209 Ok(()) 1210 }; 1211 // SAFETY: The initializer above initializes every element of the array. On failure it drops 1212 // any initialized elements and returns `Err`. 1213 unsafe { init_from_closure(init) } 1214 } 1215 1216 /// Initializes an array by initializing each element via the provided initializer. 1217 /// 1218 /// # Examples 1219 /// 1220 /// ```rust 1221 /// # #![feature(allocator_api)] 1222 /// # #[path = "../examples/mutex.rs"] mod mutex; use mutex::*; 1223 /// # use pin_init::*; 1224 /// # use core::pin::Pin; 1225 /// use pin_init::pin_init_array_from_fn; 1226 /// use std::sync::Arc; 1227 /// let array: Pin<Arc<[CMutex<usize>; 1_000]>> = 1228 /// Arc::pin_init(pin_init_array_from_fn(|i| CMutex::new(i))).unwrap(); 1229 /// assert_eq!(array.len(), 1_000); 1230 /// ``` 1231 pub fn pin_init_array_from_fn<I, const N: usize, T, E>( 1232 mut make_init: impl FnMut(usize) -> I, 1233 ) -> impl PinInit<[T; N], E> 1234 where 1235 I: PinInit<T, E>, 1236 { 1237 let init = move |slot: *mut [T; N]| { 1238 let slot = slot.cast::<T>(); 1239 for i in 0..N { 1240 let init = make_init(i); 1241 // SAFETY: Since 0 <= `i` < N, it is still in bounds of `[T; N]`. 1242 let ptr = unsafe { slot.add(i) }; 1243 // SAFETY: The pointer is derived from `slot` and thus satisfies the `__init` 1244 // requirements. 1245 if let Err(e) = unsafe { init.__pinned_init(ptr) } { 1246 // SAFETY: The loop has initialized the elements `slot[0..i]` and since we return 1247 // `Err` below, `slot` will be considered uninitialized memory. 1248 unsafe { ptr::drop_in_place(ptr::slice_from_raw_parts_mut(slot, i)) }; 1249 return Err(e); 1250 } 1251 } 1252 Ok(()) 1253 }; 1254 // SAFETY: The initializer above initializes every element of the array. On failure it drops 1255 // any initialized elements and returns `Err`. 1256 unsafe { pin_init_from_closure(init) } 1257 } 1258 1259 /// Construct an initializer in a closure and run it. 1260 /// 1261 /// Returns an initializer that first runs the closure and then the initializer returned by it. 1262 /// 1263 /// See also [`init_scope`]. 1264 /// 1265 /// # Examples 1266 /// 1267 /// ``` 1268 /// # use pin_init::*; 1269 /// # #[pin_data] 1270 /// # struct Foo { a: u64, b: isize } 1271 /// # struct Bar { a: u32, b: isize } 1272 /// # fn lookup_bar() -> Result<Bar, Error> { todo!() } 1273 /// # struct Error; 1274 /// fn init_foo() -> impl PinInit<Foo, Error> { 1275 /// pin_init_scope(|| { 1276 /// let bar = lookup_bar()?; 1277 /// Ok(pin_init!(Foo { a: bar.a.into(), b: bar.b }? Error)) 1278 /// }) 1279 /// } 1280 /// ``` 1281 /// 1282 /// This initializer will first execute `lookup_bar()`, match on it, if it returned an error, the 1283 /// initializer itself will fail with that error. If it returned `Ok`, then it will run the 1284 /// initializer returned by the [`pin_init!`] invocation. 1285 pub fn pin_init_scope<T, E, F, I>(make_init: F) -> impl PinInit<T, E> 1286 where 1287 F: FnOnce() -> Result<I, E>, 1288 I: PinInit<T, E>, 1289 { 1290 // SAFETY: 1291 // - If `make_init` returns `Err`, `Err` is returned and `slot` is completely uninitialized, 1292 // - If `make_init` returns `Ok`, safety requirement are fulfilled by `init.__pinned_init`. 1293 // - The safety requirements of `init.__pinned_init` are fulfilled, since it's being called 1294 // from an initializer. 1295 unsafe { 1296 pin_init_from_closure(move |slot: *mut T| -> Result<(), E> { 1297 let init = make_init()?; 1298 init.__pinned_init(slot) 1299 }) 1300 } 1301 } 1302 1303 /// Construct an initializer in a closure and run it. 1304 /// 1305 /// Returns an initializer that first runs the closure and then the initializer returned by it. 1306 /// 1307 /// See also [`pin_init_scope`]. 1308 /// 1309 /// # Examples 1310 /// 1311 /// ``` 1312 /// # use pin_init::*; 1313 /// # struct Foo { a: u64, b: isize } 1314 /// # struct Bar { a: u32, b: isize } 1315 /// # fn lookup_bar() -> Result<Bar, Error> { todo!() } 1316 /// # struct Error; 1317 /// fn init_foo() -> impl Init<Foo, Error> { 1318 /// init_scope(|| { 1319 /// let bar = lookup_bar()?; 1320 /// Ok(init!(Foo { a: bar.a.into(), b: bar.b }? Error)) 1321 /// }) 1322 /// } 1323 /// ``` 1324 /// 1325 /// This initializer will first execute `lookup_bar()`, match on it, if it returned an error, the 1326 /// initializer itself will fail with that error. If it returned `Ok`, then it will run the 1327 /// initializer returned by the [`init!`] invocation. 1328 pub fn init_scope<T, E, F, I>(make_init: F) -> impl Init<T, E> 1329 where 1330 F: FnOnce() -> Result<I, E>, 1331 I: Init<T, E>, 1332 { 1333 // SAFETY: 1334 // - If `make_init` returns `Err`, `Err` is returned and `slot` is completely uninitialized, 1335 // - If `make_init` returns `Ok`, safety requirement are fulfilled by `init.__init`. 1336 // - The safety requirements of `init.__init` are fulfilled, since it's being called from an 1337 // initializer. 1338 unsafe { 1339 init_from_closure(move |slot: *mut T| -> Result<(), E> { 1340 let init = make_init()?; 1341 init.__init(slot) 1342 }) 1343 } 1344 } 1345 1346 // SAFETY: the `__init` function always returns `Ok(())` and initializes every field of `slot`. 1347 unsafe impl<T> Init<T> for T { 1348 unsafe fn __init(self, slot: *mut T) -> Result<(), Infallible> { 1349 // SAFETY: `slot` is valid for writes by the safety requirements of this function. 1350 unsafe { slot.write(self) }; 1351 Ok(()) 1352 } 1353 } 1354 1355 // SAFETY: the `__pinned_init` function always returns `Ok(())` and initializes every field of 1356 // `slot`. Additionally, all pinning invariants of `T` are upheld. 1357 unsafe impl<T> PinInit<T> for T { 1358 unsafe fn __pinned_init(self, slot: *mut T) -> Result<(), Infallible> { 1359 // SAFETY: `slot` is valid for writes by the safety requirements of this function. 1360 unsafe { slot.write(self) }; 1361 Ok(()) 1362 } 1363 } 1364 1365 // SAFETY: when the `__init` function returns with 1366 // - `Ok(())`, `slot` was initialized and all pinned invariants of `T` are upheld. 1367 // - `Err(err)`, slot was not written to. 1368 unsafe impl<T, E> Init<T, E> for Result<T, E> { 1369 unsafe fn __init(self, slot: *mut T) -> Result<(), E> { 1370 // SAFETY: `slot` is valid for writes by the safety requirements of this function. 1371 unsafe { slot.write(self?) }; 1372 Ok(()) 1373 } 1374 } 1375 1376 // SAFETY: when the `__pinned_init` function returns with 1377 // - `Ok(())`, `slot` was initialized and all pinned invariants of `T` are upheld. 1378 // - `Err(err)`, slot was not written to. 1379 unsafe impl<T, E> PinInit<T, E> for Result<T, E> { 1380 unsafe fn __pinned_init(self, slot: *mut T) -> Result<(), E> { 1381 // SAFETY: `slot` is valid for writes by the safety requirements of this function. 1382 unsafe { slot.write(self?) }; 1383 Ok(()) 1384 } 1385 } 1386 1387 /// Smart pointer containing uninitialized memory and that can write a value. 1388 pub trait InPlaceWrite<T> { 1389 /// The type `Self` turns into when the contents are initialized. 1390 type Initialized; 1391 1392 /// Use the given initializer to write a value into `self`. 1393 /// 1394 /// Does not drop the current value and considers it as uninitialized memory. 1395 fn write_init<E>(self, init: impl Init<T, E>) -> Result<Self::Initialized, E>; 1396 1397 /// Use the given pin-initializer to write a value into `self`. 1398 /// 1399 /// Does not drop the current value and considers it as uninitialized memory. 1400 fn write_pin_init<E>(self, init: impl PinInit<T, E>) -> Result<Pin<Self::Initialized>, E>; 1401 } 1402 1403 impl<T> InPlaceWrite<T> for &'static mut MaybeUninit<T> { 1404 type Initialized = &'static mut T; 1405 1406 fn write_init<E>(self, init: impl Init<T, E>) -> Result<Self::Initialized, E> { 1407 let slot = self.as_mut_ptr(); 1408 1409 // SAFETY: `slot` is a valid pointer to uninitialized memory. 1410 unsafe { init.__init(slot)? }; 1411 1412 // SAFETY: The above call initialized the memory. 1413 unsafe { Ok(self.assume_init_mut()) } 1414 } 1415 1416 fn write_pin_init<E>(self, init: impl PinInit<T, E>) -> Result<Pin<Self::Initialized>, E> { 1417 let slot = self.as_mut_ptr(); 1418 1419 // SAFETY: `slot` is a valid pointer to uninitialized memory. 1420 // 1421 // The `'static` borrow guarantees the data will not be 1422 // moved/invalidated until it gets dropped (which is never). 1423 unsafe { init.__pinned_init(slot)? }; 1424 1425 // SAFETY: The above call initialized the memory. 1426 Ok(Pin::static_mut(unsafe { self.assume_init_mut() })) 1427 } 1428 } 1429 1430 /// Trait facilitating pinned destruction. 1431 /// 1432 /// Use [`pinned_drop`] to implement this trait safely: 1433 /// 1434 /// ```rust 1435 /// # #![feature(allocator_api)] 1436 /// # #[path = "../examples/mutex.rs"] mod mutex; use mutex::*; 1437 /// # use pin_init::*; 1438 /// use core::pin::Pin; 1439 /// #[pin_data(PinnedDrop)] 1440 /// struct Foo { 1441 /// #[pin] 1442 /// mtx: CMutex<usize>, 1443 /// } 1444 /// 1445 /// #[pinned_drop] 1446 /// impl PinnedDrop for Foo { 1447 /// fn drop(self: Pin<&mut Self>) { 1448 /// println!("Foo is being dropped!"); 1449 /// } 1450 /// } 1451 /// ``` 1452 /// 1453 /// # Safety 1454 /// 1455 /// This trait must be implemented via the [`pinned_drop`] proc-macro attribute on the impl. 1456 pub unsafe trait PinnedDrop: __internal::HasPinData { 1457 /// Executes the pinned destructor of this type. 1458 /// 1459 /// While this function is marked safe, it is actually unsafe to call it manually. For this 1460 /// reason it takes an additional parameter. This type can only be constructed by `unsafe` code 1461 /// and thus prevents this function from being called where it should not. 1462 /// 1463 /// This extra parameter will be generated by the `#[pinned_drop]` proc-macro attribute 1464 /// automatically. 1465 fn drop(self: Pin<&mut Self>, only_call_from_drop: __internal::OnlyCallFromDrop); 1466 } 1467 1468 /// Marker trait for types that can be initialized by writing just zeroes. 1469 /// 1470 /// # Safety 1471 /// 1472 /// The bit pattern consisting of only zeroes is a valid bit pattern for this type. In other words, 1473 /// this is not UB: 1474 /// 1475 /// ```rust,ignore 1476 /// let val: Self = unsafe { core::mem::zeroed() }; 1477 /// ``` 1478 pub unsafe trait Zeroable { 1479 /// Create a new zeroed `Self`. 1480 /// 1481 /// The returned initializer will write `0x00` to every byte of the given `slot`. 1482 #[inline] 1483 fn init_zeroed() -> impl Init<Self> 1484 where 1485 Self: Sized, 1486 { 1487 init_zeroed() 1488 } 1489 1490 /// Create a `Self` consisting of all zeroes. 1491 /// 1492 /// Whenever a type implements [`Zeroable`], this function should be preferred over 1493 /// [`core::mem::zeroed()`] or using `MaybeUninit<T>::zeroed().assume_init()`. 1494 /// 1495 /// # Examples 1496 /// 1497 /// ``` 1498 /// use pin_init::{Zeroable, zeroed}; 1499 /// 1500 /// #[derive(Zeroable)] 1501 /// struct Point { 1502 /// x: u32, 1503 /// y: u32, 1504 /// } 1505 /// 1506 /// let point: Point = zeroed(); 1507 /// assert_eq!(point.x, 0); 1508 /// assert_eq!(point.y, 0); 1509 /// ``` 1510 fn zeroed() -> Self 1511 where 1512 Self: Sized, 1513 { 1514 zeroed() 1515 } 1516 } 1517 1518 /// Marker trait for types that allow `Option<Self>` to be set to all zeroes in order to write 1519 /// `None` to that location. 1520 /// 1521 /// # Safety 1522 /// 1523 /// The implementer needs to ensure that `unsafe impl Zeroable for Option<Self> {}` is sound. 1524 pub unsafe trait ZeroableOption {} 1525 1526 // SAFETY: by the safety requirement of `ZeroableOption`, this is valid. 1527 unsafe impl<T: ZeroableOption> Zeroable for Option<T> {} 1528 1529 // SAFETY: `Option<&T>` is part of the option layout optimization guarantee: 1530 // <https://doc.rust-lang.org/stable/std/option/index.html#representation>. 1531 unsafe impl<T> ZeroableOption for &T {} 1532 // SAFETY: `Option<&mut T>` is part of the option layout optimization guarantee: 1533 // <https://doc.rust-lang.org/stable/std/option/index.html#representation>. 1534 unsafe impl<T> ZeroableOption for &mut T {} 1535 // SAFETY: `Option<NonNull<T>>` is part of the option layout optimization guarantee: 1536 // <https://doc.rust-lang.org/stable/std/option/index.html#representation>. 1537 unsafe impl<T> ZeroableOption for NonNull<T> {} 1538 1539 /// Create an initializer for a zeroed `T`. 1540 /// 1541 /// The returned initializer will write `0x00` to every byte of the given `slot`. 1542 #[inline] 1543 pub fn init_zeroed<T: Zeroable>() -> impl Init<T> { 1544 // SAFETY: Because `T: Zeroable`, all bytes zero is a valid bit pattern for `T` 1545 // and because we write all zeroes, the memory is initialized. 1546 unsafe { 1547 init_from_closure(|slot: *mut T| { 1548 slot.write_bytes(0, 1); 1549 Ok(()) 1550 }) 1551 } 1552 } 1553 1554 /// Create a `T` consisting of all zeroes. 1555 /// 1556 /// Whenever a type implements [`Zeroable`], this function should be preferred over 1557 /// [`core::mem::zeroed()`] or using `MaybeUninit<T>::zeroed().assume_init()`. 1558 /// 1559 /// # Examples 1560 /// 1561 /// ``` 1562 /// use pin_init::{Zeroable, zeroed}; 1563 /// 1564 /// #[derive(Zeroable)] 1565 /// struct Point { 1566 /// x: u32, 1567 /// y: u32, 1568 /// } 1569 /// 1570 /// let point: Point = zeroed(); 1571 /// assert_eq!(point.x, 0); 1572 /// assert_eq!(point.y, 0); 1573 /// ``` 1574 pub const fn zeroed<T: Zeroable>() -> T { 1575 // SAFETY:By the type invariants of `Zeroable`, all zeroes is a valid bit pattern for `T`. 1576 unsafe { core::mem::zeroed() } 1577 } 1578 1579 macro_rules! impl_zeroable { 1580 ($($({$($generics:tt)*})? $t:ty, )*) => { 1581 // SAFETY: Safety comments written in the macro invocation. 1582 $(unsafe impl$($($generics)*)? Zeroable for $t {})* 1583 }; 1584 } 1585 1586 impl_zeroable! { 1587 // SAFETY: All primitives that are allowed to be zero. 1588 bool, 1589 char, 1590 u8, u16, u32, u64, u128, usize, 1591 i8, i16, i32, i64, i128, isize, 1592 f32, f64, 1593 1594 // Note: do not add uninhabited types (such as `!` or `core::convert::Infallible`) to this list; 1595 // creating an instance of an uninhabited type is immediate undefined behavior. For more on 1596 // uninhabited/empty types, consult The Rustonomicon: 1597 // <https://doc.rust-lang.org/stable/nomicon/exotic-sizes.html#empty-types>. The Rust Reference 1598 // also has information on undefined behavior: 1599 // <https://doc.rust-lang.org/stable/reference/behavior-considered-undefined.html>. 1600 // 1601 // SAFETY: These are inhabited ZSTs; there is nothing to zero and a valid value exists. 1602 {<T: ?Sized>} PhantomData<T>, core::marker::PhantomPinned, (), 1603 1604 // SAFETY: Type is allowed to take any value, including all zeros. 1605 {<T>} MaybeUninit<T>, 1606 1607 // SAFETY: `T: Zeroable` and `UnsafeCell` is `repr(transparent)`. 1608 {<T: ?Sized + Zeroable>} UnsafeCell<T>, 1609 1610 // SAFETY: All zeros is equivalent to `None` (option layout optimization guarantee: 1611 // <https://doc.rust-lang.org/stable/std/option/index.html#representation>). 1612 Option<NonZeroU8>, Option<NonZeroU16>, Option<NonZeroU32>, Option<NonZeroU64>, 1613 Option<NonZeroU128>, Option<NonZeroUsize>, 1614 Option<NonZeroI8>, Option<NonZeroI16>, Option<NonZeroI32>, Option<NonZeroI64>, 1615 Option<NonZeroI128>, Option<NonZeroIsize>, 1616 1617 // SAFETY: `null` pointer is valid. 1618 // 1619 // We cannot use `T: ?Sized`, since the VTABLE pointer part of fat pointers is not allowed to be 1620 // null. 1621 // 1622 // When `Pointee` gets stabilized, we could use 1623 // `T: ?Sized where <T as Pointee>::Metadata: Zeroable` 1624 {<T>} *mut T, {<T>} *const T, 1625 1626 // SAFETY: `null` pointer is valid and the metadata part of these fat pointers is allowed to be 1627 // zero. 1628 {<T>} *mut [T], {<T>} *const [T], *mut str, *const str, 1629 1630 // SAFETY: `T` is `Zeroable`. 1631 {<const N: usize, T: Zeroable>} [T; N], {<T: Zeroable>} Wrapping<T>, 1632 } 1633 1634 macro_rules! impl_tuple_zeroable { 1635 ($(,)?) => {}; 1636 ($first:ident, $($t:ident),* $(,)?) => { 1637 // SAFETY: All elements are zeroable and padding can be zero. 1638 unsafe impl<$first: Zeroable, $($t: Zeroable),*> Zeroable for ($first, $($t),*) {} 1639 impl_tuple_zeroable!($($t),* ,); 1640 } 1641 } 1642 1643 impl_tuple_zeroable!(A, B, C, D, E, F, G, H, I, J); 1644 1645 macro_rules! impl_fn_zeroable_option { 1646 ([$($abi:literal),* $(,)?] $args:tt) => { 1647 $(impl_fn_zeroable_option!({extern $abi} $args);)* 1648 $(impl_fn_zeroable_option!({unsafe extern $abi} $args);)* 1649 }; 1650 ({$($prefix:tt)*} {$(,)?}) => {}; 1651 ({$($prefix:tt)*} {$ret:ident, $($rest:ident),* $(,)?}) => { 1652 // SAFETY: function pointers are part of the option layout optimization: 1653 // <https://doc.rust-lang.org/stable/std/option/index.html#representation>. 1654 unsafe impl<$ret, $($rest),*> ZeroableOption for $($prefix)* fn($($rest),*) -> $ret {} 1655 impl_fn_zeroable_option!({$($prefix)*} {$($rest),*,}); 1656 }; 1657 } 1658 1659 impl_fn_zeroable_option!(["Rust", "C"] { A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U }); 1660 1661 /// This trait allows creating an instance of `Self` which contains exactly one 1662 /// [structurally pinned value](https://doc.rust-lang.org/std/pin/index.html#projections-and-structural-pinning). 1663 /// 1664 /// This is useful when using wrapper `struct`s like [`UnsafeCell`] or with new-type `struct`s. 1665 /// 1666 /// # Examples 1667 /// 1668 /// ``` 1669 /// # use core::cell::UnsafeCell; 1670 /// # use pin_init::{pin_data, pin_init, Wrapper}; 1671 /// 1672 /// #[pin_data] 1673 /// struct Foo {} 1674 /// 1675 /// #[pin_data] 1676 /// struct Bar { 1677 /// #[pin] 1678 /// content: UnsafeCell<Foo> 1679 /// }; 1680 /// 1681 /// let foo_initializer = pin_init!(Foo{}); 1682 /// let initializer = pin_init!(Bar { 1683 /// content <- UnsafeCell::pin_init(foo_initializer) 1684 /// }); 1685 /// ``` 1686 pub trait Wrapper<T> { 1687 /// Creates an pin-initializer for a [`Self`] containing `T` from the `value_init` initializer. 1688 fn pin_init<E>(value_init: impl PinInit<T, E>) -> impl PinInit<Self, E>; 1689 } 1690 1691 impl<T> Wrapper<T> for UnsafeCell<T> { 1692 fn pin_init<E>(value_init: impl PinInit<T, E>) -> impl PinInit<Self, E> { 1693 // SAFETY: `UnsafeCell<T>` has a compatible layout to `T`. 1694 unsafe { cast_pin_init(value_init) } 1695 } 1696 } 1697 1698 impl<T> Wrapper<T> for MaybeUninit<T> { 1699 fn pin_init<E>(value_init: impl PinInit<T, E>) -> impl PinInit<Self, E> { 1700 // SAFETY: `MaybeUninit<T>` has a compatible layout to `T`. 1701 unsafe { cast_pin_init(value_init) } 1702 } 1703 } 1704 1705 #[cfg(all(feature = "unsafe-pinned", CONFIG_RUSTC_HAS_UNSAFE_PINNED))] 1706 impl<T> Wrapper<T> for core::pin::UnsafePinned<T> { 1707 fn pin_init<E>(init: impl PinInit<T, E>) -> impl PinInit<Self, E> { 1708 // SAFETY: `UnsafePinned<T>` has a compatible layout to `T`. 1709 unsafe { cast_pin_init(init) } 1710 } 1711 } 1712