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