summaryrefslogtreecommitdiff
path: root/src/dstream/mod.rs
blob: a9cfa891975c20b396d2735d7f09b79666ed6eb2 (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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
// Copyright 2024 Gabriel Bjørnager Jensen.
//
// This file is part of bzipper.
//
// bzipper is free software: you can redistribute
// it and/or modify it under the terms of the GNU
// Lesser General Public License as published by
// the Free Software Foundation, either version 3
// of the License, or (at your option) any later
// version.
//
// bzipper is distributed in the hope that it will
// be useful, but WITHOUT ANY WARRANTY; without
// even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Less-
// er General Public License along with bzipper. If
// not, see <https://www.gnu.org/licenses/>.

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

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

/// Byte stream for deserialisation.
///
/// This type borrows a byte slice (hence [`new`](Dstream::new)), keeping track internally of the used bytes.
///
/// The stream may be converted to an [`Sstream`] using [`to_sstream`](Dstream::to_sstream).
#[derive(Clone)]
pub struct Dstream<'a> {
	data: &'a [u8],
	len:  usize,
}

impl<'a> Dstream<'a> {
	/// Constructs a new byte stream.
	#[inline(always)]
	#[must_use]
	pub fn new<T: AsRef<[u8]> + ?Sized>(buf: &'a T) -> Self { Self {
		data: buf.as_ref(),
		len:  buf.as_ref().len(),
	} }

	/// Takes bytes from the stream.
	///
	/// # Errors
	///
	/// If the internal buffer doesn't hold at least the requested ammount of bytes, an [`EndOfDStream`](Error::EndOfDStream) error is returned.
	pub fn take(&mut self, len: usize) -> Result<&[u8]> {
		if self.len < len { return Err(Error::EndOfDStream { req: len, rem: self.len } ) }

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

		self.len -= len;

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

	/// Takes a single byte from the stream.
	///
	/// # Errors
	///
	/// If the internal buffer doesn't hold at least the requested ammount of bytes, an [`EndOfDStream`](Error::EndOfDStream) error is returned.
	pub fn take_byte(&mut self) -> Result<u8> {
		const LEN: usize = 0x1;

		if self.len < LEN { return Err(Error::EndOfDStream { req: LEN, rem: self.len } ) }

		self.len -= LEN;

		let index = self.data.len() - self.len;
		Ok(self.data[index])
	}

	/// Takes a slice of the remaining data.
	#[must_use]
	pub fn as_slice(&self) -> &[u8] {
		let stop  = self.data.len();
		let start = stop - self.len;

		&self.data[start..stop]
	}

	/// Converts the stream to a `Sstream` object.
	///
	/// The returned object owns a copy of the remaining data.
	#[inline(always)]
	#[must_use]
	pub fn to_sstream(&self) -> Sstream {
		Sstream(self.as_slice().to_vec())
	}
}

impl Debug for Dstream<'_> {
	fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
		write!(f, "[")?;

		for v in self.as_slice() { write!(f, "{v:#02X},")? };

		write!(f, "]")?;

		Ok(())
	}
}

impl<'a> From<&'a [u8]> for Dstream<'a> {
	fn from(value: &'a [u8]) -> Self { Self::new(value) }
}

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