Load a binary blob as array of struct, at compile time

Hi.

Is there a way to load, at compile time, a binary blob as an array of struct? I'd like to do something like this:

#[repr(C)]
struct CharData {
    image: [u8; 8]
}

/* I wish this would work: */
const MY_COOL_FONT: &'static [CharData; 128] = include_bytes!("../assets/font8x8.bin");

Thanks

this can be done, you just need to transmute() it

// SAFETY: type is repr(C), no padding, file is properly dumped
const MY_COOL_FONT: &'static [CharData; 128] = unsafe {
    &core::mem::transmute(*include_bytes!("../assets/font8x8.bin"))
};

see this blog post:

2 Likes

It's perfect! Thank you!

Note however the SAFETY comment - it's essential here, since for repr(Rust) structs their layout is unspecified, and you can't know whether this blob of bytes does match it. If you just want to include some complex data into binary at compile-time, you might want to look for something like databake, for more convenience.

1 Like