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
i16value. - I32
- View of an
i32value. - I64
- View of an
i64value. - U16
- View of an
u16value. - U32
- View of an
u32value. - U64
- View of an
u64value.
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
i16value. - i16_le
- View of a little-endian
i16value. - i32_be
- View of a big-endian
i32value. - i32_le
- View of a little-endian
i32value. - i64_be
- View of a big-endian
i64value. - i64_le
- View of a little-endian
i64value. - u16_be
- View of a big-endian
u16value. - u16_le
- View of a little-endian
u16value. - u32_be
- View of a big-endian
u32value. - u32_le
- View of a little-endian
u32value. - u64_be
- View of a big-endian
u64value. - u64_le
- View of a little-endian
u64value.
Derive Macros§
- View
- Derive
structview::Viewon a struct or union.