mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-17 15:55:14 +00:00
craft-pe: give the header reader its own field helper
This commit is contained in:
1 parent
4123d1235b
commit
a8d29a8779
1 file changed
+13
-15
+13
-15
@@ -1,37 +1,35 @@
|
||||
//! Checked little-endian reads over untrusted bytes. Every read returns `None` when out of range.
|
||||
//! Bounds-checked little-endian field reads for the header parser: out of range is `None`.
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(crate) struct Reader<'a> {
|
||||
data: &'a [u8],
|
||||
}
|
||||
pub(crate) struct Reader<'a>(&'a [u8]);
|
||||
|
||||
impl<'a> Reader<'a> {
|
||||
pub(crate) fn new(data: &'a [u8]) -> Self {
|
||||
Reader { data }
|
||||
Self(data)
|
||||
}
|
||||
|
||||
/// `len` bytes at `off`.
|
||||
pub(crate) fn slice(&self, off: usize, len: usize) -> Option<&'a [u8]> {
|
||||
let end = off.checked_add(len)?;
|
||||
self.data.get(off..end)
|
||||
self.0.get(off..off.checked_add(len)?)
|
||||
}
|
||||
|
||||
fn field<const N: usize>(&self, off: usize) -> Option<[u8; N]> {
|
||||
self.0.get(off..)?.first_chunk::<N>().copied()
|
||||
}
|
||||
|
||||
pub(crate) fn u8(&self, off: usize) -> Option<u8> {
|
||||
self.data.get(off).copied()
|
||||
}
|
||||
|
||||
fn arr<const N: usize>(&self, off: usize) -> Option<[u8; N]> {
|
||||
self.slice(off, N)?.try_into().ok()
|
||||
self.field::<1>(off).map(|[b]| b)
|
||||
}
|
||||
|
||||
pub(crate) fn u16_le(&self, off: usize) -> Option<u16> {
|
||||
self.arr(off).map(u16::from_le_bytes)
|
||||
Some(u16::from_le_bytes(self.field(off)?))
|
||||
}
|
||||
|
||||
pub(crate) fn u32_le(&self, off: usize) -> Option<u32> {
|
||||
self.arr(off).map(u32::from_le_bytes)
|
||||
Some(u32::from_le_bytes(self.field(off)?))
|
||||
}
|
||||
|
||||
pub(crate) fn u64_le(&self, off: usize) -> Option<u64> {
|
||||
self.arr(off).map(u64::from_le_bytes)
|
||||
Some(u64::from_le_bytes(self.field(off)?))
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user