read_native

Function read_native 

Source
pub fn read_native<R, W, T>(reader: &mut R) -> Result<T>
where R: Read + ?Sized, W: EndianRead, T: From<W>,
Available on crate feature io-std only.
Expand description

Read a value in its wire representation and convert it into a native type.

This is the recommended ergonomic pattern for #[derive(Endianize)] types:

  • the generated *Wire type is the IO/layout type (it implements EndianRead)
  • your “real” type is the native type used throughout your program

Conceptually:

  1. read W from the stream (endian-correct)
  2. convert into T using From<W>

Under the hood, this is equivalent to:

let wire: W = read_specific(reader)?;
let native: T = wire.into();

§Example

use simple_endian::Endianize;
use simple_endian::read_native;

#[derive(Endianize)]
#[endian(le)]
#[repr(C)]
struct Header {
    magic: u32,
    version: u16,
}

// Reads `HeaderWire` and converts to `Header`.
let header: Header = read_native::<_, HeaderWire, Header>(&mut reader)?;

§Notes

  • This composes naturally for nested Endianize types (a PacketWire contains a HeaderWire).
  • For enums, the wire representation is tag + union payload, so you typically want to keep trait derives on the native enum and only convert at the boundary.