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, ViewError};

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

fn main() -> Result<(), ViewError> {
    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

View of an i16 value.
View of an i32 value.
View of an i64 value.
View of an u16 value.
View of an u32 value.
View of an u64 value.

Enums

Error type returned when creating a view fails.

Traits

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

Type Definitions

View of a big-endian i16 value.
View of a little-endian i16 value.
View of a big-endian i32 value.
View of a little-endian i32 value.
View of a big-endian i64 value.
View of a little-endian i64 value.
View of a big-endian u16 value.
View of a little-endian u16 value.
View of a big-endian u32 value.
View of a little-endian u32 value.
View of a big-endian u64 value.
View of a little-endian u64 value.

Derive Macros

Derive structview::View on a struct or union.