Macro load_file::load_bytes [−][src]
macro_rules! load_bytes { ($name:expr) => { ... }; }
Load a file as a reference to a byte array at run-time.
The file is located relative to the current source file, and the binary must be run with the crate root as the working directory.
The resulting value is a &'static [u8]
with the contents of the file.
This macro can often be a drop-in replacement for include_bytes!
,
switching it to be a run-time rather than compile-time operation.
Each time the macro is reached, the file is read into memory in its entirety and the memory is leaked, keeping the memory valid for the remainder of the program execution.
Compatibility with include_bytes!
Apart from the semantic differences between include_bytes!
and
load_bytes!
there are also some technical differences:
- With
include_bytes!
, the length of the array is statically known, and is included in the type:&'static [u8; N]
, vs&'static [u8]
forload_bytes!
include_bytes!
can appear in static contexts in the source code, whileload_bytes!
can not. It is possible to use thelazy_static
crate to work around this.
Example
#[macro_use] extern crate load_file; fn main() { let greeting: &[u8] = load_bytes!("greeting.txt"); println!("{:?}", greeting); }
Panics
To facilitate using load_bytes!
as a drop-in replacement for
include_bytes!
, all error situations cause panics:
- File not found
- Read errors