Skip to content

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

@joshlf

Description

@joshlf

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 (or an equivalent PR) lands

Original text

Crosvm has a utility function called zerocopy_from_reader:

pub fn zerocopy_from_reader<R: io::Read, T: FromBytes>(mut read: R) -> io::Result<T> {
    // 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::<T>()` 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::<T>()) };
    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)?

Sub-issues

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