Re: [PATCH 1/2] rust: Zeroable: allow struct update syntax outside init macros

Alice Ryhl
2024-11-28T14:41:07Z

On Thu, Nov 28, 2024 at 3:13 PM Paolo Bonzini <pbonzini@redhat.com> wrote:
>
> The Zeroable trait is a marker trait, even though the various init macros
> use a "fake" struct update syntax. Sometimes, such a struct update
> syntax can be useful even outside the init macros. Add an associated
> const that returns an all-zero instance of a Zeroable type.
>
> The exact syntax used by the init macros cannot be reproduced without
> forgoing the ability to use Zeroable::ZERO in const context. However,
> it might not be a good idea to add a fn zeroed() inside the
> Zeroable trait, to avoid confusion with the init::zeroed() function
> and because Zeroable::ZERO is unrelated to the Init and PinInit
> traits. In other words, let's treat this difference as a
> feature rather than a bug.
>
> The definition of the ZERO constant requires adding a Sized boundary, but
> this is not a problem either because neither slices nor trait objects
> are zeroable.
>
> Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>

Slices are zeroable. I know they don't implement the trait, but they
could implement it, and this could be used to implement e.g.:

pub fn write_zero<T: Zeroed + ?Sized>(value: &mut T) {
memset(0, ...);
}

Alice