Skip to content

Accessing &mut MaybeUninit<T> as &mut [u8] by zeroing #2318

Open
@kupiakos

Description

@kupiakos

I have a &mut MaybeUninit<T>. T: FromBytes and is very large. I want to initialize it with data from an io::Read::read method in a closure and output the initialized &mut T.

Today, my options are:

  • FromBytes::read_from_io, unpack the Result, and write that to the &mut MaybeUninit<T>. However, I've already proven that return-value optimization doesn't optimize away the temporary objects and memory copies, which is why I'm using a &mut MaybeUninit<T> in the first place. We're trying to do zero copies after all 😄
  • Use the FromZeros::zero method to zero out all of the bytes, and then assume_init_mut().as_mut_bytes() to pass into read. This requires using unsafe.

There are two improvements to zerocopy I can consider to solve this problem:

  • Provide a zeroing method on FromBytes that outputs a &mut [u8]. This would be valuable for my above situation and for an extra reason: it allows users to get a [u8] out of a non-IntoBytes type by first ensuring all of the padding bytes are zeroed. While the &mut exists, the object cannot be overwritten with a T containing padding.

  • As part of Support MaybeUninit<T: ?Sized> via KnownLayout #1797, add a zero method to the zerocopy MaybeUninit that outputs &mut T just like write does. That'd solve this particular problem.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions