stream_inmemory/
stream.rs1use std::cmp::min;
2use crate::traits::{TWrite, TRead};
3
4pub struct Stream {
8 data: Vec<u8>,
9 position: usize,
10}
11
12#[derive(Copy, Clone)]
18#[derive(Eq, PartialEq)]
19pub enum StreamError {
20 EOF,
21 ZeroLength,
22}
23
24impl Stream {
25 pub fn new() -> Stream {
27 Stream {
28 data: Vec::new(),
29 position: 0,
30 }
31 }
32
33 pub fn with_capacity(capacity: usize) -> Stream {
35 Stream {
36 data: Vec::with_capacity(capacity),
37 position: 0,
38 }
39 }
40
41 pub fn truncate_readied(&mut self) {
43 if self.position == self.data.len() {
44 self.position = 0;
45 self.data.clear();
46 return;
47 }
48 if self.position > 0 {
49 let size = self.available();
50 self.data.copy_within(self.position.., 0);
51 self.data.resize(size, 0);
52 self.position = 0;
53 }
54 }
55
56 pub fn truncate_capacity(&mut self) {
58 self.data.shrink_to_fit();
59 }
60}
61
62impl TWrite for Stream {
63 fn write_byte(&mut self, byte: u8) {
65 self.data.push(byte);
66 }
67
68 fn write(&mut self, buffer: &[u8]) -> usize {
70 self.data.extend_from_slice(buffer);
71 buffer.len()
72 }
73}
74
75impl TRead for Stream {
76 fn peek_byte(&self) -> Result<u8, StreamError> {
80 if self.data.is_empty() {
81 return Err(StreamError::EOF);
82 }
83 if self.position == self.data.len() {
84 return Err(StreamError::EOF);
85 }
86 let byte = self.data[self.position];
87 Ok(byte)
88 }
89
90 fn peek(&self, buffer: &mut [u8]) -> Result<usize, StreamError> {
94 if self.data.is_empty() {
95 return Err(StreamError::EOF);
96 }
97 let size = min(buffer.len(), self.available());
98 if size == 0 {
99 return Err(StreamError::ZeroLength);
100 }
101 let slice = &mut buffer[..size];
102 slice.copy_from_slice(&self.data[..size]);
103 Ok(size)
104 }
105
106 fn read_byte(&mut self) -> Result<u8, StreamError> {
110 if self.data.is_empty() {
111 return Err(StreamError::EOF);
112 }
113 if self.position == self.data.len() {
114 return Err(StreamError::EOF);
115 }
116 let byte = self.data[self.position];
117 self.position += 1;
118 Ok(byte)
119 }
120
121 fn read(&mut self, buffer: &mut [u8]) -> Result<usize, StreamError> {
125 if self.data.is_empty() {
126 return Err(StreamError::EOF);
127 }
128 if self.position == self.data.len() {
129 return Err(StreamError::EOF);
130 }
131 let size = min(buffer.len(), self.available());
132 if size == 0 {
133 return Err(StreamError::ZeroLength);
134 }
135 buffer[..size].copy_from_slice(&self.data[self.position..(self.position + size)]);
136 self.position += size;
137 Ok(size)
138 }
139
140
141 fn skip(&mut self, count: usize) -> usize {
143 let count = min(count, self.available());
144 self.position += count;
145 count
146 }
147
148 fn skip_all(&mut self) -> usize {
150 let count = self.available();
151 self.position += count;
152 count
153 }
154
155 fn view(&self) -> &[u8] {
157 &self.data[self.position..]
158 }
159
160 fn available(&self) -> usize {
162 self.data.len() - self.position
163 }
164}
165