Skip to content

Commit 054ab48

Browse files
committed
Use from_le_bytes for loading binary data for automata (#82)
1 parent 5be1934 commit 054ab48

File tree

1 file changed

+22
-7
lines changed

1 file changed

+22
-7
lines changed

runtime-rust/src/utils/bin.rs

Lines changed: 22 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -19,19 +19,34 @@
1919
2020
use alloc::vec::Vec;
2121

22-
/// reads a u16 from an array of bytes
22+
/// Reads a `u16` from an array of bytes
23+
///
24+
/// # Panics
25+
///
26+
/// Raise a panic when the given buffer is not long enough
27+
/// from the specified index to accomodate the size of a `u16` value
2328
#[must_use]
2429
pub fn read_u16(buffer: &[u8], index: usize) -> u16 {
25-
u16::from(buffer[index + 1]) << 8 | u16::from(buffer[index])
30+
const SIZE: usize = std::mem::size_of::<u16>();
31+
let bytes: &[u8; SIZE] = buffer[index..(index + SIZE)]
32+
.try_into()
33+
.expect("given buffer cannot contain u16 value");
34+
u16::from_le_bytes(*bytes)
2635
}
2736

28-
/// reads a u32 from an array of bytes
37+
/// Reads a `u32` from an array of bytes
38+
///
39+
/// # Panics
40+
///
41+
/// Raise a panic when the given buffer is not long enough
42+
/// from the specified index to accomodate the size of a `u32` value
2943
#[must_use]
3044
pub fn read_u32(buffer: &[u8], index: usize) -> u32 {
31-
u32::from(buffer[index + 3]) << 24
32-
| u32::from(buffer[index + 2]) << 16
33-
| u32::from(buffer[index + 1]) << 8
34-
| u32::from(buffer[index])
45+
const SIZE: usize = std::mem::size_of::<u32>();
46+
let bytes: &[u8; SIZE] = buffer[index..(index + SIZE)]
47+
.try_into()
48+
.expect("given buffer cannot contain u32 value");
49+
u32::from_le_bytes(*bytes)
3550
}
3651

3752
/// Reads a table of u16 from a byte buffer

0 commit comments

Comments
 (0)