Crate structview

Source
Expand description

This crate enables casting references to binary data into references to higher-level data structures, such as structs, unions, and arrays.

The implemented approach is similar to a common pattern used when parsing binary data formats in C, where char *s representing the raw data are directly cast to, for example, struct pointers. This technique has the benefits of being simple and highly efficient. Unfortunately, it is also unsafe, as issues with alignment and integer endianess are usually ignored.

structview avoids these issues by providing a safe and convenient interface to its users: an (automatically derivable) trait View, as well as types for safely viewing integer fields.

§Example

use structview::{u32_le, View};

#[derive(Clone, Copy, View)]
#[repr(C)]
struct Animal {
    name: [u8; 4],
    number_of_heads: u8,
    number_of_legs: u32_le,
}

fn main() -> Result<(), structview::Error> {
    let data = [0x43, 0x61, 0x74, 0x00, 0x01, 0x04, 0x00, 0x00, 0x00];
    let animal = Animal::view(&data)?;

    assert_eq!(animal.name, *b"Cat\x00");
    assert_eq!(animal.number_of_heads, 1);
    assert_eq!(animal.number_of_legs.to_int(), 4);

    Ok(())
}

Structs§

I16
View of an i16 value.
I32
View of an i32 value.
I64
View of an i64 value.
U16
View of an u16 value.
U32
View of an u32 value.
U64
View of an u64 value.

Enums§

Error
Error type returned when creating a view fails.

Traits§

View
Trait for viewing byte data as a higher-level representation.

Type Aliases§

i16_be
View of a big-endian i16 value.
i16_le
View of a little-endian i16 value.
i32_be
View of a big-endian i32 value.
i32_le
View of a little-endian i32 value.
i64_be
View of a big-endian i64 value.
i64_le
View of a little-endian i64 value.
u16_be
View of a big-endian u16 value.
u16_le
View of a little-endian u16 value.
u32_be
View of a big-endian u32 value.
u32_le
View of a little-endian u32 value.
u64_be
View of a big-endian u64 value.
u64_le
View of a little-endian u64 value.

Derive Macros§

View
Derive structview::View on a struct or union.