include_unsafe

Macro include_unsafe 

Source
macro_rules! include_unsafe {
    ($file:expr) => { ... };
}
Expand description

Include data from a file as static data in the executable, without checking validity.

Warning: This macro is very unsafe. If at all possible, other macros in this crate should be preferred: even if that makes a runtime conversion necessary, that is often a good tradeoff rather than maintaining the soundness of using this macro. See below for full safety requirements.

Can assign to both static and const variables.

A compiler error will be thrown if the source file is not the same size as the target type. The path is interpreted by core::include_bytes and is host-platform-specific. The interpretation of multi-byte sequences (e.g., a u32 which occupies 4 bytes) is according to the endianness of the target platform.

§Example

// This struct contains a `bool`, which is only valid for bit patterns of
// 0x00 and 0x01, so does not satisfy `bytemuck::AnyBitPattern` and thus
// requires `include_unsafe`.
#[repr(C)]
struct StructWithBool {
    boolean: bool,
    two_bytes: u16,
}

// Safety: we guarantee that the included file contains bytes which are
// a valid bit-pattern for our struct, when compiled on this host.
// This file contains bytes 0x01 0x00 0x02 0x03 in that order. The padding
// byte (second byte) could be any value, but the first byte has to be
// valid for `bool`.
static BAR_DATA: StructWithBool = unsafe { include_unsafe!("../tests/test_data/file_exactly_4_bytes_long") };

§Safety

If at all possible, consider using another macro from this crate, even if doing so means performing runtime conversions.

For a use of this macro to be sound, the bytes of the source file must form a valid bit-pattern for the target type. This macro takes the bytes of the source file in order and then bitwise converts to the target type. It does not handle any endianness issues.

In particular, note that Rust does not have a stable ABI. This means that the compiler is free to lay out non-primitive types however it pleases: fields will not be in any guaranteed order, there may (or may not) be padding between fields, etc. The layout of a type may change between versions of the compiler and between compiler profiles (for example, debug and release builds could result in different layouts). It is therefore strongly recommended that this macro is only used when the repr attribute is used to force a guaranteed layout.

Maintaining soundness when using this macro is delicate. In particular, changing the contents of the source file or the definition of the target type at all will often silently result in undefined behaviour.