Crate format_struct

source ·
Expand description

A crate for quick and easy format structure definitions for use in binary file parsing.

§Usage

This crate should be used by invoking the provided format_struct macro like this:

use format_struct::{format_struct, FromByteSlice};

// Here we define a small structure.
format_struct! {
    struct little Test {
        foo: u8,
        bar: u32,
        baz: [u8; 2],
    }
}

// This is the data we want to parse:
let data = &[
    0x42u8, // this goes into foo
    0x39, 0x05, 0x00, 0x00, // this goes into bar
    0xaa, 0x55, // this goes into baz
][..];

// This is completely zero-cost since the implementation is just a transmute.
let s = Test::from_byte_slice(data).unwrap();

// Each integer field access compiles to a single unaligned memory access instruction.
assert_eq!(s.foo(), 0x42);
assert_eq!(s.bar(), 1337);
assert_eq!(s.baz(), &[0xaa, 0x55]);

§Reexports

Due to the way macros currently work in Rust this crate reexports the paste crate since it’s needed to construct identifiers for setters and mutable getters.

Re-exports§

Macros§

  • Defines a structure that can be transmuted from/into a byte slice for parsing/constructing binary formats in a zero-copy way. That works due to the generated structure having alignment of 1 byte and no internal padding. Generated structures will have the FromByteSlice trait implemented on them.

Structs§

Traits§

  • An unsafe trait for types that byte slices may be transmuted into.