Include_bytes
Sometimes it is useful to include byte
data directly inside an executable. The Rust program could read in this data from a file at startup, but this is not always necessary.
Instead, with the include_bytes
macro, we can access a file's data directly in the Rust program at compile-time. We can run const
functions on it to test and process it.
We use the include_bytes
macro in this Rust program. At compile-time the file is included, and we create a modified copy and test the data with const
functions.
include_bytes
. Usually we need to access parent directories, so we use standard path syntax for this.const
functions loop over the data from the included file, and modify it at compile-time or test for the letter "x."main()
we print out some of the data. Note that the constant functions have already run, and the file is already in memory.// Part 1: include this text file directly inside executable. const DATA: &[u8] = include_bytes!("../../example.txt"); // Part 2: use constant functions to process the constant data at compile-time. const DATA_UPPERCASE: &[u8] = &uppercase(DATA); const HAS_LETTER_X: bool = has_letter_x(DATA); const fn uppercase(data: &[u8]) -> [u8; DATA.len()] { let mut result = [0; DATA.len()]; let mut i = 0; while i < data.len() { result[i] = data[i].to_ascii_uppercase(); i += 1; } result } const fn has_letter_x(data: &[u8]) -> bool { let mut i = 0; while i < data.len() { if data[i] == b'x' { return true; } i += 1; } false } fn main() { // Part 3: display the constant data. let value = String::from_utf8_lossy(DATA).to_string(); println!("String: [{}]", value); let value = String::from_utf8_lossy(DATA_UPPERCASE).to_string(); println!("String uppercase: [{}]", value); println!("Has letter x: [{}]", HAS_LETTER_X); }String: [Some example text] String uppercase: [SOME EXAMPLE TEXT] Has letter x: [true]
For small files, include_bytes
is useful. For larger files, the Rust compiler will cause errors and warnings about constant functions that run too long.
Because of this, it is best to only use include_bytes
on smaller files. Code being evaluated in const
functions can sometimes be slower than expected as well.