1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
use std::{convert::TryInto, io};
const SPV_MAGIC_NUMBER_LE: u32 = 0x07230203;
const SPV_MAGIC_NUMBER_BE: u32 = SPV_MAGIC_NUMBER_LE.swap_bytes();
pub fn decode_spv(bytes: &[u8]) -> io::Result<Vec<u32>> {
if bytes.len() % 4 != 0 {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"`bytes` is not 4-byte aligned",
));
}
let mut words: Vec<_> = bytes
.chunks(4)
.map(|word| u32::from_le_bytes(word.try_into().unwrap()))
.collect();
match words.get(0) {
Some(&SPV_MAGIC_NUMBER_LE) => (),
Some(&SPV_MAGIC_NUMBER_BE) => {
for word in &mut words {
*word = word.swap_bytes();
}
}
_ => {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"`bytes` is not valid SPIR-V data",
))
}
}
Ok(words)
}