Re: [PATCH v3 09/13] rust: init: add `Zeroable` trait and `init::zeroed` function

From: Alice Ryhl
Date: Thu Mar 30 2023 - 18:36:37 EST


On 3/30/23 00:33, y86-dev@xxxxxxxxxxxxxx wrote:
From: Benno Lossin <y86-dev@xxxxxxxxxxxxxx>

Add the `Zeroable` trait which marks types that can be initialized by
writing `0x00` to every byte of the type. Also add the `init::zeroed`
function that creates an initializer for a `Zeroable` type that writes
`0x00` to every byte.

Signed-off-by: Benno Lossin <y86-dev@xxxxxxxxxxxxxx>

Reviewed-by: Alice Ryhl <aliceryhl@xxxxxxxxxx>

+impl_zeroable! {
+ // SAFETY: All primitives that are allowed to be zero.
+ bool,
+ char,
+ u8, u16, u32, u64, u128, usize,
+ i8, i16, i32, i64, i128, isize,
+ f32, f64,
+ // SAFETY: There is nothing to zero.
+ core::marker::PhantomPinned, Infallible, (),
+}

Here are some other types it might make sense to add:

* Option<NonNull<T>>
* Option<Box<T>>
* Option<NonZeroU32>
* PhantomData<T>
* MaybeUninit<T>

+
+// SAFETY: We are allowed to zero padding bytes.
+unsafe impl<const N: usize, T: Zeroable> Zeroable for [T; N] {}

There are no padding bytes in [T; N].