Alignment issue casting from &[u8] to &[u32] at compile time

⚓ Rust    📅 2025-10-29    👤 surdeus    👁️ 9      

surdeus

Warning

This post was published 33 days ago. The information described in this article may have changed.

I'm trying to read bytes from a binary file and cast the pointer to the slice to &[u32]. It works at runtime using the fs module:

let mut buf = Vec::new();

let file = File::open("slang.spv").unwrap();
let mut reader = BufReader::new(file);
reader.read_to_end(&mut buf).

let code = std::slice::from_raw_parts(buf.as_ptr() as *const u32, buf.len() / 4);

However at compile time:

let buf = include_bytes!("../../slang.spv");
let code = std::slice::from_raw_parts(buf.as_ptr() as *const u32, buf.len() / 4);

It panics with unsafe precondition(s) violated: slice::from_raw_parts requires the pointer to be aligned and non-null, and the total size of the slice not to exceed isize::MAX

2 posts - 2 participants

Read full topic

🏷️ Rust_feed