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