I've got a file containing raw binary data, that I would like to load to an array of 4 byte long u32
words.
It's possible to do by including the contents of the file at compile time:
let bytes = include_bytes!("audio.raw");
Then, I can convert it to an array of u32
words using transmute
. The length of the new array should be obviously 1/4 of the original byte array.
let audio = unsafe { std::mem::transmute::<[u8; 63504], [u32; 15876]>(*bytes) };
// works
As you can see above, I had to hardcode the lengthes of the input and output arrays. However when trying to avoid hardcoding these numbers, it doesn't work:
let audio = unsafe { std::mem::transmute::<[u8; bytes.len()], [u32; bytes.len()/4]>(*bytes) };
// error: non-constant value
It seems that .len()
is called at runtime, and since dynamic arrays cannot be allocated in Rust, it yields an error. However in theory, there should be a way to calculate the necessary length at compilation stage, as the length of the bytes
array is fixed. So my question is: is there a macro that gives back the length of a static array?
(I'm perfectly aware that dynamic allocation is possible with vectors, my question is explicitly about fixed-sized arrays.)
Sample code (include_bytes
replaced with hard-coded array):
fn main() {
// let bytes = include_bytes!("audio.raw");
let bytes = [1, 0, 0, 0, 2, 0, 0, 0];
// works:
let audio = unsafe { std::mem::transmute::<[u8; 8], [u32; 2]>(bytes) };
// error:
let audio = unsafe { std::mem::transmute::<[u8; bytes.len()], [u32; bytes.len() / 4]>(bytes) };
println!("{}", audio[1]);
}