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

From: Alice Ryhl
Date: Fri Nov 29 2024 - 04:39:58 EST


On Thu, Nov 28, 2024 at 5:43 PM Paolo Bonzini <pbonzini@xxxxxxxxxx> wrote:
>
> On 11/28/24 15:40, Alice Ryhl wrote:
> >> 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@xxxxxxxxxx>
> >
> > Slices are zeroable. I know they don't implement the trait,
>
> Right, I should have used the uppercase "Zeroable" for clarity.
>
> > 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, ...);
> > }
>
> Yeah, that would be I think
>
> pub fn write_zero<T: Zeroable + ?Sized>(value: &mut T) {
> unsafe {
> ptr::write_bytes((value as *mut T).cast::<u8>(), 0,
> std::mem::size_of_val(value))
> }
> }
>
> ? And it works for both sized values and slices. If Zeroable is
> limited to sized types, I guess you could still do:
>
> pub fn write_zero_slice<T: Zeroable>(value: &mut [T]) {
> ptr::write_bytes(value.as_mut_ptr(), 0, value.len())
> }
>
> So the question is whether the ZERO constant is worthwhile enough, to
> justify the limitation of the Sized bound (e.g. having separate
> write_zero and write_zero_slice in the future).

Why not both?

If you change the constant to a const fn, then you don't have to rule
out either use-case.

Alice