Macro include_data::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.
A compiler error will be thrown if the source file is not the same size as the target type.
Example
#[repr(C)]
struct StructWithPadding {
byte: u8,
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.
static BAR_DATA: StructWithPadding = 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.