1#![forbid(unsafe_code)]
4
5#[derive(Debug, Clone, Copy)]
7pub struct ByteSource<'a> {
8 data: &'a [u8],
9 pos: usize,
10}
11
12impl<'a> ByteSource<'a> {
13 #[must_use]
15 pub const fn new(data: &'a [u8]) -> Self {
16 Self { data, pos: 0 }
17 }
18
19 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 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 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 pub fn u8(&mut self) -> Option<u8> {
43 let b = self.take(1)?;
44 Some(b[0])
45 }
46}