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