ReadByteable

Trait ReadByteable 

Source
pub trait ReadByteable: Read {
    // Provided method
    fn read_byteable<T: Byteable>(&mut self) -> Result<T> { ... }
}
Expand description

Extension trait for Read that adds methods for reading Byteable types.

This trait is automatically implemented for all types that implement std::io::Read, providing convenient methods for reading binary data directly into Rust types.

§Examples

§Reading from a file

use byteable::{Byteable, ReadByteable};
use std::fs::File;

#[derive(byteable::Byteable, Debug)]
struct Header {
    #[byteable(big_endian)]
    magic: u32,
    #[byteable(little_endian)]
    version: u16,
    #[byteable(little_endian)]
    flags: u16,
}

let mut file = File::open("data.bin")?;
let header: Header = file.read_byteable()?;
println!("Header: {:?}", header);

§Reading from a TCP stream

use byteable::ReadByteable;
use std::net::TcpStream;

let mut stream = TcpStream::connect("127.0.0.1:8080")?;

// Read a u32 length prefix
let length: u32 = stream.read_byteable()?;
println!("Message length: {}", length);

§Reading multiple values

use byteable::ReadByteable;
use std::io::Cursor;

let data = vec![1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0];
let mut cursor = Cursor::new(data);

let a: u32 = cursor.read_byteable()?;
let b: u32 = cursor.read_byteable()?;
let c: u32 = cursor.read_byteable()?;

#[cfg(target_endian = "little")]
assert_eq!((a, b, c), (1, 2, 3));

Provided Methods§

Source

fn read_byteable<T: Byteable>(&mut self) -> Result<T>

Reads a Byteable type from this reader.

This method reads exactly T::BYTE_SIZE bytes from the reader and converts them into a value of type T.

§Errors

This method returns an error if:

  • The reader reaches EOF before reading T::BYTE_SIZE bytes
  • Any underlying I/O error occurs
§Examples
use byteable::{Byteable, ReadByteable};
use std::io::Cursor;

let data = vec![0x12, 0x34, 0x56, 0x78];
let mut cursor = Cursor::new(data);

let value: u32 = cursor.read_byteable().unwrap();
#[cfg(target_endian = "little")]
assert_eq!(value, 0x78563412);

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementors§

Source§

impl<T: Read> ReadByteable for T