Crate bytes_cast[][src]

Utilities for safely re-interpreting &[u8] bytes as custom structs and back without copying, for efficiently reading structured binary data.

Example

Reading bytes:

use bytes_cast::{BytesCast, unaligned};

#[derive(BytesCast)]
#[repr(C)]
struct Foo {
    bar: [u8; 2],
    baz: unaligned::U32Be,
}

let input = &[1_u8, 2, 3, 4, 5, 6, 7, 8];

let (foo, rest) = Foo::from_bytes(input).unwrap();
assert_eq!(foo.bar, [1_u8, 2]);
assert_eq!(foo.baz.get(), 0x0304_0506_u32);
assert_eq!(rest, &[7_u8, 8]);

assert!(<[Foo; 2]>::from_bytes(input).is_err()); // input is too short

let (values, rest) = unaligned::U16Le::slice_from_bytes(input, 2).unwrap();
assert_eq!(values.len(), 2);
assert_eq!(values[0].get(), 0x02_01_u16);
assert_eq!(values[1].get(), 0x04_03_u16);
assert_eq!(rest, &[5_u8, 6, 7, 8]);

assert!(unaligned::U16Le::slice_from_bytes(input, 5).is_err()); // input is too short

Writing bytes:


let foo = Foo { bar: [1, 2], baz: 0x0304_0506.into() };
assert_eq!(foo.as_bytes(), &[1_u8, 2, 3, 4, 5, 6]);

let slice: &[unaligned::U16Le] = &[0x02_01.into(), 0x04_03.into()];
assert_eq!(slice.as_bytes(), &[1_u8, 2, 3, 4]);

Modules

unaligned

Integer and float types without alignment requirement, for each endianness.

Structs

FromBytesError

The error type for BytesCast::from_bytes and BytesCast::slice_from_bytes.

Traits

BytesCast

Marks a type as safe to interpret from and to bytes without copying.

Derive Macros

BytesCast

Derive the BytesCast trait. See trait documentation.