google / google/zerocopy

Add `FromBytes`/`IntoBytes` methods which read from/write to an `io::Read`/`io::Write`

Open
#158 11 comments 2 reactions 0 assignees View on GitHub
compatibility-nonbreaking
Dominant language
Rust
Stars
2.6k
Forks
179
Avg merge
1d 19h
Merged PRs (30d)
29

Description

## Progress

- [ ] Add `FromBytes::read_from_io` and `IntoBytes::write_to_io` in 0.8
- [ ] In 0.9, perform the following renames:
- `IntoBytes::write_to` -> `write_to_bytes` (to be consistent with `FromBytes::read_from_bytes`)
- Rename `FromBytes::read_from_io` -> `read_from` and `IntoBytes::write_to_io` -> `write_to`
- Any similar rename for `TryFromBytes` method if [#2619](https://github.com/google/zerocopy/pull/2619) (or an equivalent PR) lands

## Original text

Crosvm has a utility function called [zerocopy_from_reader](https://github.com/google/crosvm/blob/8a7550c/common/data_model/src/lib.rs#L12-L23):

```rust
pub fn zerocopy_from_reader(mut read: R) -> io::Result {
// Allocate on the stack via `MaybeUninit` to ensure proper alignment.
let mut out = MaybeUninit::zeroed();

// Safe because the pointer is valid and points to `size_of::()` bytes of zeroes,
// which is a properly initialized value for `u8`.
let buf = unsafe { from_raw_parts_mut(out.as_mut_ptr() as *mut u8, size_of::()) };
read.read_exact(buf)?;

// Safe because any bit pattern is considered a valid value for `T`.
Ok(unsafe { out.assume_init() })
}
```

Maybe we should add something similar to `FromBytes` (and potentially a write analogue to `AsBytes`)?

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.