lib.rs 57 KB

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