Skip to main content

Crate safe_read

Crate safe_read 

Source
Expand description

Panic-free bounded integer readers over an untrusted byte slice.

Every read returns a benign default (0 / None) when the requested window is out of range — never a panic. This is the shared front door for every offset/length field parsed from an attacker-controllable forensic image, so each reader crate does not re-derive its own bounds-checked helpers.

Two flavours per width:

  • le_u32(data, off) -> u32 — returns 0 out of range (the common case; the parser then rejects the structurally-invalid record through its own validation).
  • try_le_u32(data, off) -> Option<u32> — returns None out of range, for the callers that must distinguish a genuine 0 field from an absent/truncated one.
use safe_read::{le_u32, be_u16, u8, try_le_u32};
assert_eq!(le_u32(&[0x78, 0x56, 0x34, 0x12], 0), 0x1234_5678);
assert_eq!(be_u16(&[0xaa, 0x12, 0x34], 1), 0x1234);
assert_eq!(u8(&[0xab], 0), 0xab);
// Out of range: 0 for the plain readers, None for the `try_` twins:
assert_eq!(le_u32(&[1, 2, 3], 0), 0);
assert_eq!(try_le_u32(&[1, 2, 3], 0), None);

#![no_std] — pure slice arithmetic, no allocation.

Functions§

be_u16
Read a u16 at off; 0 if out of range. Never panics.
be_u32
Read a u32 at off; 0 if out of range. Never panics.
be_u64
Read a u64 at off; 0 if out of range. Never panics.
le_u16
Read a u16 at off; 0 if out of range. Never panics.
le_u32
Read a u32 at off; 0 if out of range. Never panics.
le_u64
Read a u64 at off; 0 if out of range. Never panics.
try_be_u16
Read a u16 at off; None if out of range. Never panics. Use when 0 must be distinguished from absent/truncated.
try_be_u32
Read a u32 at off; None if out of range. Never panics. Use when 0 must be distinguished from absent/truncated.
try_be_u64
Read a u64 at off; None if out of range. Never panics. Use when 0 must be distinguished from absent/truncated.
try_le_u16
Read a u16 at off; None if out of range. Never panics. Use when 0 must be distinguished from absent/truncated.
try_le_u32
Read a u32 at off; None if out of range. Never panics. Use when 0 must be distinguished from absent/truncated.
try_le_u64
Read a u64 at off; None if out of range. Never panics. Use when 0 must be distinguished from absent/truncated.
try_u8
Read a single byte at off; None if off is past the end. Never panics.
u8
Read a single byte at off; 0 if off is past the end. Never panics. (Endianness is irrelevant for one byte; provided so callers never index data[off] directly.)