refs_core/bytes.rs
1//! Bounds-checked little-endian readers (the Paranoid Gatekeeper standard).
2//!
3//! ReFS is a **little-endian** on-disk format (Windows/NT platform), so these
4//! mirror `xfs-core`'s big-endian helpers with LE decode. Every reader yields
5//! `0` when the requested range lies outside the buffer, so a malformed or
6//! truncated image can never panic a parser. Callers that need to distinguish
7//! "field absent" from "field is zero" bounds-check the buffer length up front
8//! and surface [`crate::RefsError::Truncated`].
9
10/// Read a little-endian `u16` at `off`, or `0` if out of range.
11#[must_use]
12pub fn le_u16(data: &[u8], off: usize) -> u16 {
13 let mut b = [0u8; 2];
14 if let Some(s) = data.get(off..off + 2) {
15 b.copy_from_slice(s);
16 }
17 u16::from_le_bytes(b)
18}
19
20/// Read a little-endian `u32` at `off`, or `0` if out of range.
21#[must_use]
22pub fn le_u32(data: &[u8], off: usize) -> u32 {
23 let mut b = [0u8; 4];
24 if let Some(s) = data.get(off..off + 4) {
25 b.copy_from_slice(s);
26 }
27 u32::from_le_bytes(b)
28}
29
30/// Read a little-endian `u64` at `off`, or `0` if out of range.
31#[must_use]
32pub fn le_u64(data: &[u8], off: usize) -> u64 {
33 let mut b = [0u8; 8];
34 if let Some(s) = data.get(off..off + 8) {
35 b.copy_from_slice(s);
36 }
37 u64::from_le_bytes(b)
38}
39
40/// Read a single byte at `off`, or `0` if out of range.
41#[must_use]
42pub fn u8_at(data: &[u8], off: usize) -> u8 {
43 data.get(off).copied().unwrap_or(0)
44}
45
46/// Best-effort ASCII rendering of a byte slice — printable ASCII kept, every
47/// other byte shown as `.`. Used to render the offending value legibly in
48/// fail-loud "unrecognized signature" errors (show the unrecognized value).
49#[must_use]
50pub fn ascii(bytes: &[u8]) -> String {
51 bytes
52 .iter()
53 .map(|&c| {
54 if (0x20..0x7f).contains(&c) {
55 c as char
56 } else {
57 '.'
58 }
59 })
60 .collect()
61}