From 5c7064dda2a4b9ab44697eb5424d80c6845c3bd8 Mon Sep 17 00:00:00 2001 From: Hamdan-Khan Date: Tue, 3 Mar 2026 20:25:20 +0500 Subject: [PATCH] implement ZeroableOption for NonZero* integer types add a macro for implementing `ZeroableOption` for `NonZero*` types. `Option` now automatically implements `Zeroable` trait by implementing `ZeroableOption` for `NonZero*` types, which serves as a blanket impl. Link: https://github.com/Rust-for-Linux/pin-init/issues/95 Signed-off-by: Hamdan-Khan --- CHANGELOG.md | 1 + src/lib.rs | 21 ++++++++++++++------- 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 56b248b3..556cf880 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - `[pin_]init_scope` functions to run arbitrary code inside of an initializer. - `&'static mut MaybeUninit` now implements `InPlaceWrite`. This enables users to use external allocation mechanisms such as `static_cell`. +- Non-zero integer types (`NonZero*`) now implement `ZeroableOption`. ### Changed diff --git a/src/lib.rs b/src/lib.rs index a513930e..f1d2c95c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1613,13 +1613,6 @@ impl_zeroable! { // SAFETY: `T: Zeroable` and `UnsafeCell` is `repr(transparent)`. {} UnsafeCell, - // SAFETY: All zeros is equivalent to `None` (option layout optimization guarantee: - // ). - Option, Option, Option, Option, - Option, Option, - Option, Option, Option, Option, - Option, Option, - // SAFETY: `null` pointer is valid. // // We cannot use `T: ?Sized`, since the VTABLE pointer part of fat pointers is not allowed to be @@ -1664,6 +1657,20 @@ macro_rules! impl_fn_zeroable_option { 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 }); +macro_rules! impl_non_zero_int_zeroable_option { + ($($int:ty),* $(,)?) => { + // SAFETY: Safety comment written in the macro invocation. + $(unsafe impl ZeroableOption for $int {})* + }; +} + +impl_non_zero_int_zeroable_option! { + // SAFETY: All zeros is equivalent to `None` (option layout optimization guarantee: + // ). + NonZeroU8, NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU128, NonZeroUsize, + NonZeroI8, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI128, NonZeroIsize, +} + /// This trait allows creating an instance of `Self` which contains exactly one /// [structurally pinned value](https://doc.rust-lang.org/std/pin/index.html#projections-and-structural-pinning). ///