#struct #mapped #cargo-toml #raw #mappable

map_struct

A rust library to map raw data to a struct

3 releases (breaking)

0.3.0 Jul 5, 2019
0.2.0 Jun 8, 2019
0.1.0 Jun 1, 2019

#6 in #mapped

Download history 3/week @ 2024-02-15 18/week @ 2024-02-22 9/week @ 2024-02-29 3/week @ 2024-03-07 3/week @ 2024-03-14 36/week @ 2024-03-28 20/week @ 2024-04-04

60 downloads per month

Custom license

3KB

map_struct

A rust library to map raw data to a struct.

Usage

In Cargo.toml,

[dependencies]
map_struct = "0.3"

Implement unsafe Mappable trait to the struct to be mapped to a raw data:

#[repr(C)]
struct Hoge {
    a: u8,
    b: u8,
    c: u16,
}

unsafe impl Mappable for Hoge {}

Call mapped:

// mapped returns Option<(&Self, &[u8])>
Hoge::mapped(&[0x2, 0x3, 0x4, 0x5, 0x6])

mapped returns None if the argument length is not enough for the struct. It otherwise returns the tuple of the reference to the mapped struct and the rest of the data. For &mut [u8], we may also use mapped_mut, which returns Option<(&mut Self, &mut [u8])> instead.

We also provide a inverse method of mapped, as_bytes. The usage is following.

let hoge = Hoge::mapped(&[0x2, 0x3, 0x4, 0x5, 0x6]).unwrap().0;
assert!(hoge.as_bytes() == &[0x2, 0x3, 0x4, 0x5]);

No runtime deps