stream_inmemory/
stream.rs

1use std::cmp::min;
2use crate::traits::{TWrite, TRead};
3
4/// Dynamically sized inmemory stream.
5///
6/// Used as buffer with read, write and peek funcs.
7pub struct Stream {
8    data: Vec<u8>,
9    position: usize,
10}
11
12/// Errors that can occurred if use read or peek funcs.
13///
14/// Inmemory stream has error EOF when try read them if it is empty.
15///
16/// Inmemory stream has error ZeroLength when try read them if buffer`s len is zero.
17#[derive(Copy, Clone)]
18#[derive(Eq, PartialEq)]
19pub enum StreamError {
20    EOF,
21    ZeroLength,
22}
23
24impl Stream {
25    /// Create new Stream with zero capacity.
26    pub fn new() -> Stream {
27        Stream {
28            data: Vec::new(),
29            position: 0,
30        }
31    }
32
33    /// Create new Stream with target capacity.
34    pub fn with_capacity(capacity: usize) -> Stream {
35        Stream {
36            data: Vec::with_capacity(capacity),
37            position: 0,
38        }
39    }
40
41    /// Clear bytes that have been read. Has no effect on the allocated capacity.
42    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    /// Truncate the capacity of the stream as much as possible.
57    pub fn truncate_capacity(&mut self) {
58        self.data.shrink_to_fit();
59    }
60}
61
62impl TWrite for Stream {
63    /// Write one byte to stream.
64    fn write_byte(&mut self, byte: u8) {
65        self.data.push(byte);
66    }
67
68    /// Write bytes to stream.
69    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    /// Peek one byte from stream, position don't shift.
77    ///
78    /// Can return EOF error.
79    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    /// Peek bytes from stream, position don't shift.
91    ///
92    /// Can return EOF, ZeroLength errors.
93    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    /// Read one byte from stream, position  shifted.
107    ///
108    /// Can return EOF error.
109    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    /// Read bytes from stream, position shifted.
122    ///
123    /// Can return EOF, ZeroLength errors.
124    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    /// Skip "count" bytes in stream. Return skipped bytes count.
142    fn skip(&mut self, count: usize) -> usize {
143        let count = min(count, self.available());
144        self.position += count;
145        count
146    }
147
148    /// Skip all bytes in stream. Return skipped bytes count.
149    fn skip_all(&mut self) -> usize {
150        let count = self.available();
151        self.position += count;
152        count
153    }
154
155    /// View of available bytes in stream.
156    fn view(&self) -> &[u8] {
157        &self.data[self.position..]
158    }
159
160    /// Return available to read bytes.
161    fn available(&self) -> usize {
162        self.data.len() - self.position
163    }
164}
165