This one isn't mine. I spotted it in the r/rust post The Day const Betrayed Me and the discussion below it. It's on my list because it's interesting.
The surprise
The author embedded a data file with a const:
pub const DATA: &'static [u8] = include_bytes!("data.bin");
DATA is a &'static reference, so the
bytes should be in the binary once. Then an unrelated code change made
the binary noticeably smaller: before, DATA had been
embedded twice.
Why
The Rust Reference says it directly:
Constants are essentially inlined wherever they are used, meaning that they are copied directly into the relevant context when used. [...] References to the same constant are not necessarily guaranteed to refer to the same memory address.
The compiler splits a crate into several codegen units and compiles
them in parallel. Every codegen unit that uses the const
evaluates it and gets its own copy of the bytes, and the units don't
coordinate with each other. Within one unit the copy can be shared,
across units it isn't.
As u/ToTheBatmobileGuy put it in the comments, there's a difference between what the compiler can do and what it is guaranteed to do. Merging the copies is something it can do, not something you can rely on.
The fix
Use a static when the data should exist exactly once. A
static is one place in memory, and every use refers to
it:
pub static DATA: &[u8] = include_bytes!("data.bin");
const |
static |
|
|---|---|---|
| What it is | a value, pasted in at every use | one fixed place in memory |
| Same address everywhere | not guaranteed | yes |
| Good for | small values: numbers, short strings, array sizes | big data, anything whose address matters |