WriteByteable

Trait WriteByteable 

Source
pub trait WriteByteable: Write {
    // Provided method
    fn write_byteable<T: Byteable>(&mut self, data: T) -> Result<()> { ... }
}
Expand description

Extension trait for Write that adds methods for writing Byteable types.

This trait is automatically implemented for all types that implement std::io::Write, providing convenient methods for writing Rust types directly as binary data.

§Examples

§Writing to a file

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

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

let header = Header {
    magic: 0x12345678,
    version: 1,
    flags: 0,
};

let mut file = File::create("output.bin")?;
file.write_byteable(header)?;

§Writing to a TCP stream

use byteable::WriteByteable;
use std::net::TcpStream;

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

// Write a u32 length prefix
stream.write_byteable(42u32)?;

§Writing multiple values

use byteable::WriteByteable;
use std::io::Cursor;

let mut buffer = Cursor::new(Vec::new());

buffer.write_byteable(1u32).unwrap();
buffer.write_byteable(2u32).unwrap();
buffer.write_byteable(3u32).unwrap();

#[cfg(target_endian = "little")]
assert_eq!(
    buffer.into_inner(),
    vec![1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0]
);

Provided Methods§

Source

fn write_byteable<T: Byteable>(&mut self, data: T) -> Result<()>

Writes a Byteable type to this writer.

This method converts the value into its byte array representation and writes all bytes to the writer.

§Errors

This method returns an error if any underlying I/O error occurs while writing.

§Examples
use byteable::{Byteable, WriteByteable};
use std::io::Cursor;

let mut buffer = Cursor::new(Vec::new());
buffer.write_byteable(0x12345678u32).unwrap();

#[cfg(target_endian = "little")]
assert_eq!(buffer.into_inner(), vec![0x78, 0x56, 0x34, 0x12]);

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§