hexspell/
utils.rs

1//! Helper routines for safely reading integers from byte slices.
2//!
3//! Many parts of the crate need to interpret raw data at specific offsets.
4//! The functions provided here centralize that logic, performing bounds
5//! checks and converting little‑endian byte sequences into native Rust
6//! integers. Errors are reported using [`FileParseError`], allowing callers
7//! to bubble failures up without panicking.
8
9use crate::errors::FileParseError;
10
11pub fn extract_u64(buffer: &[u8], offset: usize) -> Result<u64, FileParseError> {
12    buffer
13        .get(offset..offset + 8)
14        .ok_or(FileParseError::BufferOverflow)
15        .and_then(|bytes| bytes.try_into().map_err(|_| FileParseError::BufferOverflow))
16        .map(u64::from_le_bytes)
17}
18
19pub fn extract_u32(buffer: &[u8], offset: usize) -> Result<u32, FileParseError> {
20    buffer
21        .get(offset..offset + 4)
22        .ok_or(FileParseError::BufferOverflow)
23        .and_then(|bytes| {
24            bytes
25                .try_into()
26                .map_err(|_| FileParseError::BufferOverflow)
27                .map(u32::from_le_bytes)
28        })
29}
30
31pub fn extract_u16(buffer: &[u8], offset: usize) -> Result<u16, FileParseError> {
32    buffer
33        .get(offset..offset + 2)
34        .ok_or(FileParseError::BufferOverflow)
35        .and_then(|bytes| bytes.try_into().map_err(|_| FileParseError::BufferOverflow))
36        .map(u16::from_le_bytes)
37}