google / google/zerocopy

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

Open
#2,318 2 comments 0 reactions 0 assignees View on GitHub
customer-request
Dominant language
Rust
Stars
2.6k
Forks
179
Avg merge
1d 19h
Merged PRs (30d)
29

Description

I have a `&mut MaybeUninit`. `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`. 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` 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 #1797, add a `zero` method to the zerocopy `MaybeUninit` that outputs `&mut T` just like `write` does. That'd solve this particular problem.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.