1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
use std::cmp::min;
use crate::traits::{TWrite, TRead};

/// Dynamically sized inmemory stream.
///
/// Used as buffer with read, write and peek funcs.
pub struct Stream {
    data: Vec<u8>,
    position: usize,
}

/// Errors that can occurred if use read or peek funcs.
///
/// Inmemory stream has error EOF when try read them if it is empty.
///
/// Inmemory stream has error ZeroLength when try read them if buffer`s len is zero.
#[derive(Copy, Clone)]
#[derive(Eq, PartialEq)]
pub enum StreamError {
    EOF,
    ZeroLength,
}

impl Stream {
    /// Create new Stream with zero capacity.
    pub fn new() -> Stream {
        Stream {
            data: Vec::new(),
            position: 0,
        }
    }

    /// Create new Stream with target capacity.
    pub fn with_capacity(capacity: usize) -> Stream {
        Stream {
            data: Vec::with_capacity(capacity),
            position: 0,
        }
    }

    /// Clear bytes that have been read. Has no effect on the allocated capacity.
    pub fn truncate_readied(&mut self) {
        if self.position == self.data.len() {
            self.position = 0;
            self.data.clear();
            return;
        }
        if self.position > 0 {
            let size = self.available();
            self.data.copy_within(self.position.., 0);
            self.data.resize(size, 0);
            self.position = 0;
        }
    }

    /// Truncate the capacity of the stream as much as possible.
    pub fn truncate_capacity(&mut self) {
        self.data.shrink_to_fit();
    }
}

impl TWrite for Stream {
    /// Write one byte to stream.
    fn write_byte(&mut self, byte: u8) {
        self.data.push(byte);
    }

    /// Write bytes to stream.
    fn write(&mut self, buffer: &[u8]) -> usize {
        self.data.extend_from_slice(buffer);
        buffer.len()
    }
}

impl TRead for Stream {
    /// Peek one byte from stream, position don't shift.
    ///
    /// Can return EOF error.
    fn peek_byte(&self) -> Result<u8, StreamError> {
        if self.data.is_empty() {
            return Err(StreamError::EOF);
        }
        if self.position == self.data.len() {
            return Err(StreamError::EOF);
        }
        let byte = self.data[self.position];
        Ok(byte)
    }

    /// Peek bytes from stream, position don't shift.
    ///
    /// Can return EOF, ZeroLength errors.
    fn peek(&self, buffer: &mut [u8]) -> Result<usize, StreamError> {
        if self.data.is_empty() {
            return Err(StreamError::EOF);
        }
        let size = min(buffer.len(), self.available());
        if size == 0 {
            return Err(StreamError::ZeroLength);
        }
        let slice = &mut buffer[..size];
        slice.copy_from_slice(&self.data[..size]);
        Ok(size)
    }

    /// Read one byte from stream, position  shifted.
    ///
    /// Can return EOF error.
    fn read_byte(&mut self) -> Result<u8, StreamError> {
        if self.data.is_empty() {
            return Err(StreamError::EOF);
        }
        if self.position == self.data.len() {
            return Err(StreamError::EOF);
        }
        let byte = self.data[self.position];
        self.position += 1;
        Ok(byte)
    }

    /// Read bytes from stream, position shifted.
    ///
    /// Can return EOF, ZeroLength errors.
    fn read(&mut self, buffer: &mut [u8]) -> Result<usize, StreamError> {
        if self.data.is_empty() {
            return Err(StreamError::EOF);
        }
        if self.position == self.data.len() {
            return Err(StreamError::EOF);
        }
        let size = min(buffer.len(), self.available());
        if size == 0 {
            return Err(StreamError::ZeroLength);
        }
        buffer[..size].copy_from_slice(&self.data[self.position..(self.position + size)]);
        self.position += size;
        Ok(size)
    }


    /// Skip "count" bytes in stream. Return skipped bytes count.
    fn skip(&mut self, count: usize) -> usize {
        let count = min(count, self.available());
        self.position += count;
        count
    }

    /// Skip all bytes in stream. Return skipped bytes count.
    fn skip_all(&mut self) -> usize {
        let count = self.available();
        self.position += count;
        count
    }

    /// View of available bytes in stream.
    fn view(&self) -> &[u8] {
        &self.data[self.position..]
    }

    /// Return available to read bytes.
    fn available(&self) -> usize {
        self.data.len() - self.position
    }
}