binary_modifier/memory/
memory.rs

1use std::io::{Error, ErrorKind, Read, Write};
2
3use crate::{BinaryError, Result, SeekStream};
4
5pub struct MemoryStream<'a> {
6    pub buffer: &'a mut [u8],
7    pub position: usize,
8}
9
10impl<'a> MemoryStream<'a> {
11    pub fn new_vec(buffer: &'a mut Vec<u8>) -> Self {
12        Self {
13            buffer,
14            position: 0,
15        }
16    }
17
18    pub fn get_buffer(&self) -> Vec<u8> {
19        self.buffer.to_vec()
20    }
21}
22
23/// This implements the `SeekStream` trait from main.rs into `MemoryStream`
24impl<'a> SeekStream for MemoryStream<'a> {
25    /// TUpdates the position of a mutable reference to a struct and returns the new
26    /// position.
27    ///
28    /// Arguments:
29    ///
30    /// * `to`: The `to` parameter is the position to which the seek operation should move the current
31    /// position. It is of type `usize`
32    ///
33    /// Returns:
34    ///
35    /// The `seek` function is returning a `Result` enum with a value of `Ok(self.position)`.
36    fn seek(&mut self, to: usize) -> Result<usize> {
37        self.position = to;
38        Ok(self.position)
39    }
40    /// Returns the current position of a mutable reference.
41    ///
42    /// Returns:
43    ///
44    /// The `tell` function is returning a `Result` enum with a value of `usize`.
45    fn tell(&mut self) -> Result<usize> {
46        Ok(self.position)
47    }
48    /// Returns the length of the buffer as a `Result` containing a `usize`.
49    ///
50    /// Returns:
51    ///
52    /// The `len` function is returning a `Result` type with a value of `usize`.
53    fn len(&self) -> Result<usize> {
54        Ok(self.buffer.len())
55    }
56}
57
58impl<'a> Read for MemoryStream<'a> {
59    fn read(&mut self, buffer: &mut [u8]) -> std::io::Result<usize> {
60        if self.position + buffer.len() > self.buffer.len() {
61            return Err(Error::new(
62                ErrorKind::UnexpectedEof,
63                BinaryError::ReadPastEof,
64            ));
65        }
66
67        let mut idx = 0;
68        for i in self.position..self.position + buffer.len() {
69            buffer[idx] = self.buffer[i];
70            idx += 1;
71        }
72
73        self.position += buffer.len();
74
75        Ok(buffer.len())
76    }
77}
78
79impl<'a> Write for MemoryStream<'a> {
80    fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
81        self.buffer.clone_from_slice(bytes);
82        self.position += bytes.len();
83        Ok(bytes.len())
84    }
85
86    fn flush(&mut self) -> std::io::Result<()> {
87        Ok(())
88    }
89}
90
91impl Into<Vec<u8>> for MemoryStream<'_> {
92    fn into(self) -> Vec<u8> {
93        self.buffer.to_vec()
94    }
95}