binary_modifier/memory/
memory.rs1use 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
23impl<'a> SeekStream for MemoryStream<'a> {
25 fn seek(&mut self, to: usize) -> Result<usize> {
37 self.position = to;
38 Ok(self.position)
39 }
40 fn tell(&mut self) -> Result<usize> {
46 Ok(self.position)
47 }
48 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}