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

Alice Ryhl
2024-11-29T09:39:46Z

On Thu, Nov 28, 2024 at 5:43 PM Paolo Bonzini <pbonzini@redhat.com> 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@redhat.com>
> >
> > 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