summaryrefslogtreecommitdiff
path: root/src/deserialise/d_stream/mod.rs
blob: 05ed6a27baf5f28f0d2f40c5de56329f7dba2c67 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// Copyright 2022-2024 Gabriel Bjørnager Jensen.

use crate::error::{Error, Result};

use std::fmt::{Debug, Formatter};

#[derive(Clone)]
pub struct DStream<'a> {
	data: &'a [u8],
	len:  usize,
}

impl DStream<'_> {
	pub fn take(&mut self, len: usize) -> Result<&[u8]> {
		if self.len < len { return Err(Error::EndOfDStream { len: self.len, ok_len: len } ) }

		let start = self.data.len() - self.len;
		let stop  = start + len;

		self.len -= len;

		Ok(&self.data[start..stop])
	}
}

impl Debug for DStream<'_> {
	fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
		let stop  = self.data.len();
		let start = self.data.len() - self.len;

		write!(f, "[")?;

		for v in &self.data[start..stop] { write!(f, "{v:#02X},")? };

		write!(f, "]")?;

		Ok(())
	}
}

impl<'a> From<&'a [u8]> for DStream<'a> {
	fn from(value: &'a [u8]) -> Self { Self {
		data: value,
		len:  value.len(),
	} }
}

impl<'a, const N: usize> From<&'a [u8; N]> for DStream<'a> {
	fn from(value: &'a [u8; N]) -> Self { Self {
		data: value,
		len:  N,
	} }
}