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