Function abomonation::encode

source ·
pub unsafe fn encode<T: Abomonation, W: Write>(
    typed: &T,
    write: &mut W,
) -> Result<()>
Expand description

Encodes a typed reference into a binary buffer.

§Safety

This method is unsafe because it is unsafe to transmute typed allocations to binary. Furthermore, Rust currently indicates that it is undefined behavior to observe padding bytes, which will happen when we memmcpy structs which contain padding bytes.

§Examples

use abomonation::{encode, decode};

// create some test data out of abomonation-approved types
let vector = (0..256u64).map(|i| (i, format!("{}", i)))
                        .collect::<Vec<_>>();

// encode a Vec<(u64, String)> into a Vec<u8>
let mut bytes = Vec::new();
unsafe { encode(&vector, &mut bytes); }

// decode a &Vec<(u64, String)> from &mut [u8] binary data
if let Some((result, remaining)) = unsafe { decode::<Vec<(u64, String)>>(&mut bytes) } {
    assert!(result == &vector);
    assert!(remaining.len() == 0);
}