pgs_parse/pgs_memory_buffer.rs
1//! # PGS Memory Buffer
2//!
3//! This module defines the `PgsMemoryBuffer`, which represents an in-memory buffer that can be
4//! read from and seeked into. It also includes functionality for reading different byte orders.
5use std::{fmt::Debug, io::Read};
6
7use crate::{pgs_error::Result, PgsSeek};
8
9/// A trait for handling different byte orders.
10///
11/// This trait defines methods for reading unsigned integers in various byte orders.
12pub trait ByteOrder: Default + Debug + Clone {
13 /// Reads a 16-bit unsigned integer from a byte slice.
14 ///
15 /// # Arguments
16 /// * `buf` - A byte slice containing the data to read.
17 ///
18 /// # Returns
19 /// Returns a `Result` containing the 16-bit integer on success, or an `Error` if the read operation fails.
20 fn read_u16(buf: &[u8]) -> Result<u16>;
21
22 /// Reads a 24-bit unsigned integer from a byte slice.
23 ///
24 /// # Arguments
25 /// * `buf` - A byte slice containing the data to read.
26 ///
27 /// # Returns
28 /// Returns a `Result` containing the 24-bit integer on success, or an `Error` if the read operation fails.
29 fn read_u24(buf: &[u8]) -> Result<u32>;
30
31 /// Reads a 32-bit unsigned integer from a byte slice.
32 ///
33 /// # Arguments
34 /// * `buf` - A byte slice containing the data to read.
35 ///
36 /// # Returns
37 /// Returns a `Result` containing the 32-bit integer on success, or an `Error` if the read operation fails.
38 fn read_u32(buf: &[u8]) -> Result<u32>;
39}
40
41/// A struct representing the big-endian byte order.
42#[derive(Clone, Copy, Debug)]
43pub enum BigEndian {}
44
45impl Default for BigEndian {
46 fn default() -> BigEndian {
47 panic!("BigEndian")
48 }
49}
50
51impl ByteOrder for BigEndian {
52 #[inline]
53 fn read_u16(buf: &[u8]) -> Result<u16> {
54 Ok(u16::from_be_bytes(buf[..2].try_into()?))
55 }
56
57 #[inline]
58 fn read_u24(buf: &[u8]) -> Result<u32> {
59 let mut out = [0; 4];
60 out[1..].copy_from_slice(&buf[..3]);
61 Ok(u32::from_be_bytes(out))
62 }
63
64 #[inline]
65 fn read_u32(buf: &[u8]) -> Result<u32> {
66 Ok(u32::from_be_bytes(buf[..4].try_into()?))
67 }
68}
69
70
71/// A struct representing the little-endian byte order.
72#[derive(Clone, Copy, Debug)]
73pub enum LittleEndian {}
74
75impl Default for LittleEndian {
76 fn default() -> LittleEndian {
77 panic!("LittleEndian")
78 }
79}
80
81impl ByteOrder for LittleEndian {
82 #[inline]
83 fn read_u16(buf: &[u8]) -> Result<u16> {
84 Ok(u16::from_le_bytes(buf[..2].try_into()?))
85 }
86
87 #[inline]
88 fn read_u24(buf: &[u8]) -> Result<u32> {
89 let mut out = [0; 4];
90 out[..3].copy_from_slice(&buf[..3]);
91 Ok(u32::from_le_bytes(out))
92 }
93
94 #[inline]
95 fn read_u32(buf: &[u8]) -> Result<u32> {
96 Ok(u32::from_le_bytes(buf[..4].try_into()?))
97 }
98}
99
100/// A trait for reading bytes with support for different byte orders.
101pub trait ReadBytes: Read {
102 /// Reads a single 8-bit unsigned integer.
103 ///
104 /// # Returns
105 /// Returns a `Result` containing the 8-bit integer on success, or an `Error` if the read operation fails.
106 #[inline]
107 fn read_u8(&mut self) -> Result<u8> {
108 let mut buf: [u8; 1] = [0; 1];
109 self.read_exact(&mut buf)?;
110 Ok(buf[0])
111 }
112
113 /// Reads a 16-bit unsigned integer using the specified byte order.
114 ///
115 /// # Type Parameters
116 /// * `T` - The byte order to use for reading the integer.
117 ///
118 /// # Returns
119 /// Returns a `Result` containing the 16-bit integer on success, or an `Error` if the read operation fails.
120 #[inline]
121 fn read_u16<T: ByteOrder>(&mut self) -> Result<u16> {
122 let mut buf: [u8; 2] = [0; 2];
123 self.read_exact(&mut buf)?;
124 T::read_u16(&buf)
125 }
126
127 /// Reads a 24-bit unsigned integer using the specified byte order.
128 ///
129 /// # Type Parameters
130 /// * `T` - The byte order to use for reading the integer.
131 ///
132 /// # Returns
133 /// Returns a `Result` containing the 24-bit integer on success, or an `Error` if the read operation fails.
134 #[inline]
135 fn read_u24<T: ByteOrder>(&mut self) -> Result<u32> {
136 let mut buf = [0; 3];
137 self.read_exact(&mut buf)?;
138 T::read_u24(&buf)
139 }
140
141 /// Reads a 32-bit unsigned integer using the specified byte order.
142 ///
143 /// # Type Parameters
144 /// * `T` - The byte order to use for reading the integer.
145 ///
146 /// # Returns
147 /// Returns a `Result` containing the 32-bit integer on success, or an `Error` if the read operation fails.
148 #[inline]
149 fn read_u32<T: ByteOrder>(&mut self) -> Result<u32> {
150 let mut buffer: [u8; 4] = [0; 4];
151 self.read_exact(&mut buffer)?;
152 T::read_u32(&buffer)
153 }
154}
155
156impl<R: Read + ?Sized> ReadBytes for R {}
157
158/// A memory buffer that supports reading and seeking operations.
159#[derive(Default)]
160pub struct PgsMemoryBuffer {
161 buffer: Vec<u8>,
162 position: usize,
163}
164
165impl PgsMemoryBuffer {
166 /// Creates a new `PgsMemoryBuffer` instance.
167 ///
168 /// # Returns
169 /// Returns a new `PgsMemoryBuffer` with an empty buffer and position set to 0.
170 pub fn new() -> Self {
171 Self {
172 buffer: Vec::new(),
173 position: 0,
174 }
175 }
176
177 /// Reads a fixed number of bytes into a fixed-size array.
178 ///
179 /// # Arguments
180 /// * `N` - The number of bytes to read, specified as a constant generic parameter.
181 ///
182 /// # Returns
183 /// Returns a `Result` containing an array of bytes on success, or an `Error` if the read operation fails.
184 pub fn read_bytes<const N: usize>(&mut self) -> Result<[u8; N]> {
185 let mut buffer: [u8; N] = [0; N];
186 self.read_exact(&mut buffer)?;
187 Ok(buffer)
188 }
189
190 /// Reads a specified number of bytes into a `Vec<u8>`.
191 ///
192 /// # Arguments
193 /// * `length` - The number of bytes to read.
194 ///
195 /// # Returns
196 /// Returns a `Result` containing a vector of bytes on success, or an `Error` if the read operation fails.
197 pub fn read_into_vec(&mut self, length: u32) -> Result<Vec<u8>> {
198 let mut buffer: Vec<u8> = vec![0; length as usize];
199 let buffer_slice = buffer.as_mut_slice();
200 self.read_exact(buffer_slice)?;
201 Ok(buffer)
202 }
203
204 /// Returns a slice of the remaining bytes in the buffer.
205 ///
206 /// # Returns
207 /// Returns a slice of the remaining bytes starting from the current position.
208 pub fn remaining_slice(&self) -> &[u8] {
209 let start_pos = self.position.min(self.buffer.len());
210 &self.buffer.as_slice()[(start_pos)..]
211 }
212}
213
214impl PgsSeek for PgsMemoryBuffer {
215 fn seek(&mut self, to: usize) -> Result<usize> {
216 self.position = to;
217 Ok(self.position)
218 }
219
220 fn pos(&mut self) -> Result<usize> {
221 Ok(self.position)
222 }
223
224 fn len(&self) -> Result<usize> {
225 Ok(self.buffer.len())
226 }
227}
228
229impl Read for PgsMemoryBuffer {
230 /// Reads bytes from the buffer into the provided slice.
231 ///
232 /// # Arguments
233 /// * `buffer` - A mutable byte slice to read into.
234 ///
235 /// # Returns
236 /// Returns a `Result` containing the number of bytes read on success, or an `Error` if the read operation fails.
237 fn read(&mut self, buffer: &mut [u8]) -> std::io::Result<usize> {
238 let len = Read::read(&mut self.remaining_slice(), buffer)?;
239 self.position += len;
240 Ok(len)
241 }
242
243 /// Reads bytes from the buffer into the provided slice, ensuring that the exact number of bytes is read.
244 ///
245 /// # Arguments
246 /// * `buffer` - A mutable byte slice to read into.
247 ///
248 /// # Returns
249 /// Returns a `Result` indicating success or failure of the read operation.
250 fn read_exact(&mut self, buffer: &mut [u8]) -> std::io::Result<()> {
251 let buf_len = buffer.len();
252 Read::read_exact(&mut self.remaining_slice(), buffer)?;
253 self.position += buf_len;
254 Ok(())
255 }
256}
257
258impl From<Vec<u8>> for PgsMemoryBuffer {
259 /// Creates a `PgsMemoryBuffer` from a `Vec<u8>`.
260 ///
261 /// # Arguments
262 /// * `buffer` - A `Vec<u8>` to initialize the `PgsMemoryBuffer`.
263 ///
264 /// # Returns
265 /// Returns a `PgsMemoryBuffer` containing the provided vector.
266 fn from(buffer: Vec<u8>) -> Self {
267 PgsMemoryBuffer {
268 buffer,
269 position: 0,
270 }
271 }
272}
273
274impl From<&[u8]> for PgsMemoryBuffer {
275 /// Creates a `PgsMemoryBuffer` from a byte slice.
276 ///
277 /// # Arguments
278 /// * `buffer` - A byte slice to initialize the `PgsMemoryBuffer`.
279 ///
280 /// # Returns
281 /// Returns a `PgsMemoryBuffer` containing the provided slice.
282 fn from(buffer: &[u8]) -> Self {
283 PgsMemoryBuffer {
284 buffer: Vec::from(buffer),
285 position: 0,
286 }
287 }
288}