Skip to main content

iso_bmff/isobmff/
buf.rs

1//! Sequential byte source — monomorphized, no `Box`.
2
3#![forbid(unsafe_code)]
4
5/// Sequential byte source over a slice.
6#[derive(Debug, Clone, Copy)]
7pub struct ByteSource<'a> {
8    data: &'a [u8],
9    pos: usize,
10}
11
12impl<'a> ByteSource<'a> {
13    /// Wrap a slice.
14    #[must_use]
15    pub const fn new(data: &'a [u8]) -> Self {
16        Self { data, pos: 0 }
17    }
18
19    /// Take `n` bytes or `None` if truncated.
20    pub fn take(&mut self, n: usize) -> Option<&'a [u8]> {
21        let end = self.pos.checked_add(n)?;
22        let slice = self.data.get(self.pos..end)?;
23        self.pos = end;
24        Some(slice)
25    }
26
27    /// Read big-endian `u32`.
28    pub fn u32(&mut self) -> Option<u32> {
29        let b = self.take(4)?;
30        Some(u32::from_be_bytes([b[0], b[1], b[2], b[3]]))
31    }
32
33    /// Read big-endian `u64`.
34    pub fn u64(&mut self) -> Option<u64> {
35        let b = self.take(8)?;
36        Some(u64::from_be_bytes([
37            b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7],
38        ]))
39    }
40
41    /// Read `u8`.
42    pub fn u8(&mut self) -> Option<u8> {
43        let b = self.take(1)?;
44        Some(b[0])
45    }
46}