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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
//! Common utility funcitons used across different modules
use std::{
    collections::VecDeque,
    io::{BufRead, Read, Write},
};

/// Clamp value to the value between `min` and `max`
#[inline]
pub fn clamp<T>(val: T, min: T, max: T) -> T
where
    T: PartialOrd,
{
    if val < min {
        min
    } else if val > max {
        max
    } else {
        val
    }
}

/// Readable and writable IO queue
pub struct IOQueue {
    chunks: VecDeque<Vec<u8>>,
    offset: usize,
    length: usize,
}

impl IOQueue {
    /// Create new empty queue
    pub fn new() -> Self {
        Self {
            chunks: Default::default(),
            offset: 0,
            length: 0,
        }
    }

    /// Check if queue is empty
    pub fn is_empty(&self) -> bool {
        self.chunks.is_empty()
    }

    /// Number of bytes available to be read from the queue
    pub fn len(&self) -> usize {
        self.length
    }

    /// Drop all but last chunks
    pub fn clear_but_last(&mut self) {
        if self.chunks.len() > 1 {
            self.chunks.drain(1..);
        }
    }

    /// Number of avaiable chunks
    pub fn chunks_count(&self) -> usize {
        self.chunks.len()
    }

    /// Remaining slice at the front of the queue
    pub fn as_slice(&self) -> &[u8] {
        match self.chunks.front() {
            Some(chunk) => &chunk.as_slice()[self.offset..],
            None => &[],
        }
    }

    /// Consume bytes from the front of the queue
    pub fn consume(&mut self, amt: usize) {
        if self.chunks.front().map(|chunk| chunk.len()).unwrap_or(0) > self.offset + amt {
            self.offset += amt;
            self.length -= amt;
        } else {
            if let Some(chunk) = self.chunks.pop_front() {
                self.length -= chunk.len() - self.offset
            }
            self.offset = 0;
        }
    }

    /// Consume single chunk from the queue. Function `consumer` returns number of bytes
    /// to be removed from the queue.
    pub fn consume_with<F, FE>(&mut self, consumer: F) -> Result<usize, FE>
    where
        F: FnOnce(&[u8]) -> Result<usize, FE>,
    {
        let size = consumer(self.as_slice())?;
        self.consume(size);
        Ok(size)
    }
}

impl Write for IOQueue {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        if self.chunks.is_empty() {
            self.chunks.push_back(Default::default());
        }
        let chunk = self.chunks.back_mut().unwrap();
        self.length += buf.len();
        chunk.write(buf)
    }

    fn flush(&mut self) -> std::io::Result<()> {
        if !self.as_slice().is_empty() {
            self.chunks.push_back(Default::default());
        }
        Ok(())
    }
}

impl Read for IOQueue {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        let buf_queue = self.as_slice();
        let size = std::cmp::min(buf.len(), buf_queue.len());
        let src = &buf_queue[..size];
        let dst = &mut buf[..size];
        dst.copy_from_slice(src);
        self.consume(size);
        Ok(size)
    }
}

impl BufRead for IOQueue {
    fn fill_buf(&mut self) -> std::io::Result<&[u8]> {
        Ok(self.as_slice())
    }

    fn consume(&mut self, amt: usize) {
        Self::consume(self, amt)
    }
}

impl Default for IOQueue {
    fn default() -> Self {
        IOQueue::new()
    }
}

/// Simple random number generator
///
/// Imlemented as linear congruential generator LCG. Used here instead
/// of pooling in `rand` crate to reduce dependencies.
/// Formula:
///     X(n) = ((X(n - 1) * a + c) % m) / d
///     a = 214_013
///     c = 2_531_011
///     m = 2 ^ 31
///     d = 2 ^ 16
/// This formula produces 16-bit random number.
pub struct Rnd {
    state: u32,
}

impl Default for Rnd {
    fn default() -> Self {
        Self::new()
    }
}

impl Rnd {
    /// Create new random number generator with seed `0`
    pub fn new() -> Self {
        Self::with_seed(0)
    }

    /// Create new randon number generator with provided `seed` value
    pub fn with_seed(seed: u32) -> Self {
        Self { state: seed }
    }

    fn step(&mut self) -> u32 {
        self.state = self.state.wrapping_mul(214_013).wrapping_add(2_531_011) & 0x7fffffff;
        self.state >> 16
    }

    /// Generate random u32 value
    pub fn next_u32(&mut self) -> u32 {
        (self.step() & 0xffff) << 16 | (self.step() & 0xffff)
    }

    /// Generate random u64 value
    pub fn next_u64(&mut self) -> u64 {
        ((self.next_u32() as u64) << 32) | (self.next_u32() as u64)
    }
}

#[cfg(test)]
mod tests {
    use super::IOQueue;
    use std::io::{BufRead, Read, Write};

    #[test]
    fn test_io_queue() -> std::io::Result<()> {
        let mut queue = IOQueue::new();
        assert!(queue.is_empty());

        queue.write(b"on")?;
        queue.write(b"e")?;
        queue.flush()?;
        queue.write(b",two")?;
        queue.flush()?;
        assert!(!queue.is_empty());

        // make sure flush creates separate chunks
        assert_eq!(queue.as_slice(), b"one");

        // check `Read` implementation
        let mut out = String::new();
        queue.read_to_string(&mut out)?;
        assert_eq!(out, String::from("one,two"));
        assert_eq!(queue.len(), 0);
        assert!(queue.is_empty());

        // make `BufRead` implementation
        queue.write(b"one\nt")?;
        queue.flush()?;
        queue.write(b"wo\nth")?;
        queue.flush()?;
        queue.write(b"ree\n")?;
        let lines = queue.lines().collect::<Result<Vec<_>, _>>()?;
        assert_eq!(
            lines,
            vec!["one".to_string(), "two".to_string(), "three".to_string()]
        );
        Ok(())
    }
}