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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
#[macro_use]
extern crate failure;
pub mod buffer {
    use std::io::Error;
    use std::io::{Read, Seek, SeekFrom, Write};

    /// Specifies the position in a stream to use for seeking.
    #[derive(PartialEq)]
    pub enum SeekOrigin {
        /// Specifies the beginning of a stream.
        Begin,
        /// Specifies the current position within a stream.
        Current,
        /// Specifies the end of a stream.
        End,
    }

    /// Endianness refers to the order of bytes (or sometimes bits) within a binary representation of a number.
    #[derive(PartialEq)]
    pub enum Endianness {
        /// The least significant byte (LSB) value, 0Dh, is at the lowest address.
        /// The other bytes follow in increasing order of significance.
        /// This is akin to right-to-left reading in hexadecimal order.
        Little,
        /// The most significant byte (MSB) value, 0Ah, is at the lowest address.
        /// The other bytes follow in decreasing order of significance.
        /// This is akin to left-to-right reading in hexadecimal order.
        Big,
    }

    /// Writes primitive types in binary to a stream and supports writing strings in a specific encoding.
    pub struct BufferWriter<W: Write> {
        pub writer: W,
    }

    impl<W: Write> BufferWriter<W>
    where
        W: Seek + Read + Write,
    {
        /// Creates a new BufferWriter instance
        pub fn new(writer: W) -> Self {
            BufferWriter { writer: writer }
        }
        /// Gets the position within the current stream.
        pub fn position(&mut self) -> Result<u64, BufferError> {
            self.seek(0, SeekOrigin::Current)
        }
        /// Gets the length in bytes of the stream.
        pub fn len(&mut self) -> Result<u64, BufferError> {
            let old_pos = self.position()?;
            let len = self.seek(0, SeekOrigin::End)?;
            if old_pos != len {
                self.seek(old_pos as i64, SeekOrigin::Begin)?;
            }
            Ok(len)
        }
        pub fn to_vec(&mut self) -> Result<Vec<u8>, BufferError> {
            let mut out: Vec<u8> = vec![];
            self.seek(0, SeekOrigin::Begin)?;
            self.writer.read_to_end(&mut out).unwrap();
            Ok(out)
        }
        pub fn seek(&mut self, position: i64, origin: SeekOrigin) -> Result<u64, BufferError> {
            match origin {
                SeekOrigin::Begin => self.writer.seek(SeekFrom::Start(position as u64)),
                SeekOrigin::Current => self.writer.seek(SeekFrom::Current(position)),
                SeekOrigin::End => self.writer.seek(SeekFrom::End(position)),
            }
            .map(|o| o)
            .map_err(|_e| BufferError::IndexOutOfRange { index: position })
        }

        /// Writes a four-byte unsigned integer to the current stream
        /// and advances the stream position by four bytes.
        pub fn write_u32(&mut self, value: u32) -> Result<u64, BufferError> {
            let data = &[
                (value >> 0) as u8,
                (value >> 8) as u8,
                (value >> 16) as u8,
                (value >> 24) as u8,
            ];
            self.writer
                .write(data)
                .map(|o| o as u64)
                .map_err(|_e| BufferError::IOFailure)
        }

        /// Writes an eight-byte unsigned integer to the current stream
        /// and advances the stream position by eight bytes.
        pub fn write_u64(&mut self, value: u64) -> Result<u64, BufferError> {
            let data = &[
                (value >> 0) as u8,
                (value >> 8) as u8,
                (value >> 16) as u8,
                (value >> 24) as u8,
                (value >> 32) as u8,
                (value >> 40) as u8,
                (value >> 48) as u8,
                (value >> 56) as u8,
            ];
            self.writer
                .write(data)
                .map(|o| o as u64)
                .map_err(|_e| BufferError::IOFailure)
        }

        /// Writes a four-byte signed integer to the current stream
        /// and advances the stream position by four bytes.
        pub fn write_i32(&mut self, value: i32) -> Result<u64, BufferError> {
            let data = &[
                (value >> 0) as u8,
                (value >> 8) as u8,
                (value >> 16) as u8,
                (value >> 24) as u8,
            ];
            self.writer
                .write(data)
                .map(|o| o as u64)
                .map_err(|_e| BufferError::IOFailure)
        }

        /// Writes a two-byte unsigned integer to the current stream
        /// and advances the stream position by two bytes.
        pub fn write_u16(&mut self, value: u16) -> Result<u64, BufferError> {
            let data = &[(value >> 0) as u8, (value >> 8) as u8];
            self.writer
                .write(data)
                .map(|o| o as u64)
                .map_err(|_e| BufferError::IOFailure)
        }

        /// Writes an unsigned byte to the current stream
        /// and advances the stream position by one byte.
        pub fn write_u8(&mut self, value: u8) -> Result<u64, BufferError> {
            self.writer
                .write(&[value])
                .map(|o| o as u64)
                .map_err(|_e| BufferError::IOFailure)
        }

        /// Write out an int 7 bits at a time. The high bit of the byte,
        /// when on, tells reader to continue reading more bytes.
        pub fn write_7bit_int(&mut self, value: i32) -> Result<(), BufferError> {
            let mut v = value as u32;
            while v >= 0x80 {
                self.write_u8((v | 0x80) as u8)?;
                v >>= 7;
            }
            self.write_u8(v as u8)?;
            Ok(())
        }

        /// Writes a length-prefixed string to this stream in UTF8-encoding
        /// and advances the current position of the stream in accordance with the encoding
        /// used and the specific characters being written to the stream.
        pub fn write_string(&mut self, value: String) -> Result<u64, BufferError> {
            let bytes = value.as_bytes();
            self.write_7bit_int(bytes.len() as i32)?;
            self.writer
                .write(bytes)
                .map(|o| o as u64)
                .map_err(|_e| BufferError::IOFailure)
        }

        /// Writes a section of a bytes to the current stream, and advances the current position of the stream
        pub fn write_bytes(&mut self, value: &Vec<u8>) -> Result<u64, BufferError> {
            self.writer
                .write(value)
                .map(|o| o as u64)
                .map_err(|_e| BufferError::IOFailure)
        }
    }

    /// Reads primitive data types as binary values in a specific encoding.
    pub struct BufferReader<R: Read> {
        pub reader: R,
    }

    impl<R: Read> BufferReader<R>
    where
        R: Seek + Read + Write,
    {
        /// Creates a new BufferReader
        pub fn new(reader: R) -> Self {
            BufferReader { reader: reader }
        }
        /// Gets the position within the current stream.
        pub fn position(&mut self) -> Result<u64, BufferError> {
            self.seek(0, SeekOrigin::Current)
        }
        /// Gets the length in bytes of the stream.
        pub fn len(&mut self) -> Result<u64, BufferError> {
            let old_pos = self.position()?;
            let len = self.seek(0, SeekOrigin::End)?;
            if old_pos != len {
                self.seek(old_pos as i64, SeekOrigin::Begin)?;
            }
            Ok(len)
        }
        pub fn seek(&mut self, position: i64, origin: SeekOrigin) -> Result<u64, BufferError> {
            match origin {
                SeekOrigin::Begin => self.reader.seek(SeekFrom::Start(position as u64)),
                SeekOrigin::Current => self.reader.seek(SeekFrom::Current(position)),
                SeekOrigin::End => self.reader.seek(SeekFrom::End(position)),
            }
            .map(|o| o as u64)
            .map_err(|_e| BufferError::IndexOutOfRange { index: position })
        }

        /// Reads in a 32-bit integer in compressed format.
        pub fn read_7bit_int(&mut self) -> Result<i32, BufferError> {
            let mut count: i32 = 0;
            let mut shift = 0;
            let mut b: u8 = 0;
            while {
                // Check for a corrupted stream.  Read a max of 5 bytes.
                // In a future version, add a DataFormatException.
                if shift == 5 * 7 {
                    // 5 bytes max per Int32, shift += 7
                    // too many bytes in what should have been a 7 bit encoded i32.
                    return Err(BufferError::IOFailure);
                }
                // read_u8 handles end of stream cases for us.
                b = self.read_u8()?;
                count |= ((b & 0x7F) as i32) << shift;
                shift += 7;
                (b & 0x80) != 0
            } {}
            Ok(count)
        }
        /// Reads a null-terminated string from the buffer
        pub fn read_string(&mut self) -> Result<String, BufferError> {
            let string_length = self.read_7bit_int()?;
            if string_length < 0 {
                return Err(BufferError::IOFailure);
            }
            if string_length == 0 {
                return Ok(String::default());
            }
            let chars = self.read_bytes(string_length as u64)?;
            String::from_utf8(chars)
                .map(|o| o)
                .map_err(|_e| BufferError::IOFailure)
        }

        /// Reads a 4-byte unsigned integer from the current vector
        /// and advances the position of the cursor by four bytes.
        pub fn read_u32(&mut self) -> Result<u32, BufferError> {
            let size = std::mem::size_of::<u32>() as u64;
            if self.position()? + size > self.len()? {
                return Err(BufferError::EndOfStream);
            }
            let mut buffer = [0u8; 4];
            self.reader
                .read_exact(&mut buffer)
                .map_err(|e| BufferError::ReadFailure { error: e })
                .map(|_b| {
                    ((buffer[0] as u32) << 0)
                        | ((buffer[1] as u32) << 8)
                        | ((buffer[2] as u32) << 16)
                        | ((buffer[3] as u32) << 24)
                })
        }

        /// Reads a 8-byte unsigned integer from the current vector
        /// and advances the position of the cursor by eight bytes.
        pub fn read_u64(&mut self) -> Result<u64, BufferError> {
            let size = std::mem::size_of::<u64>() as u64;
            if self.position()? + size > self.len()? {
                return Err(BufferError::EndOfStream);
            }
            let mut buffer = vec![0u8; 8];
            self.reader
                .read_exact(&mut buffer)
                .map_err(|e| BufferError::ReadFailure { error: e })
                .map(|_b| {
                    let lo = (buffer[0] as u32)
                        | (buffer[1] as u32) << 8
                        | (buffer[2] as u32) << 16
                        | (buffer[3] as u32) << 24;
                    let hi = (buffer[4] as u32)
                        | (buffer[5] as u32) << 8
                        | (buffer[6] as u32) << 16
                        | (buffer[7] as u32) << 24;

                    (hi as u64) << 32 | lo as u64
                })
        }

        /// Reads a 4-byte signed integer from the current vector
        /// and advances the current position of the cursor by four bytes.
        pub fn read_i32(&mut self) -> Result<i32, BufferError> {
            let size = std::mem::size_of::<i32>() as u64;
            if self.position()? + size > self.len()? {
                return Err(BufferError::EndOfStream);
            }
            let mut buffer = [0u8; 4];
            self.reader
                .read_exact(&mut buffer)
                .map_err(|e| BufferError::ReadFailure { error: e })
                .map(|_b| {
                    ((buffer[0] as i32) << 0)
                        | ((buffer[1] as i32) << 8)
                        | ((buffer[2] as i32) << 16)
                        | ((buffer[3] as i32) << 24)
                })
        }

        /// Reads a 2-byte unsigned integer from the current vector using little-endian encoding
        /// and advances the position of the cursor by two bytes.
        pub fn read_u16(&mut self) -> Result<u16, BufferError> {
            let size = std::mem::size_of::<u16>() as u64;
            if self.position()? + size > self.len()? {
                return Err(BufferError::EndOfStream);
            }
            let mut buffer = [0u8; 2];
            self.reader
                .read_exact(&mut buffer)
                .map_err(|e| BufferError::ReadFailure { error: e })
                .map(|_b| (buffer[0] as u16) | (buffer[1] as u16))
        }

        /// Reads the next byte from the current vector
        /// and advances the current position of the cursor by one byte.
        pub fn read_u8(&mut self) -> Result<u8, BufferError> {
            let size = std::mem::size_of::<u8>() as u64;
            if self.position()? + size > self.len()? {
                return Err(BufferError::EndOfStream);
            }
            let mut buffer = [0u8; 1];
            self.reader
                .read_exact(&mut buffer)
                .map_err(|e| BufferError::ReadFailure { error: e })
                .map(|_b| buffer[0])
        }

        /// Reads the specified number of bytes from the current stream
        /// into a byte array and advances the current position by that number of bytes.
        pub fn read_bytes(&mut self, count: u64) -> Result<Vec<u8>, BufferError> {
            if self.position()? + count > self.len()? {
                return Err(BufferError::EndOfStream);
            }
            let mut buffer = vec![0u8; count as usize];
            self.reader
                .read_exact(&mut buffer)
                .map_err(|e| BufferError::ReadFailure { error: e })
                .map(|_b| buffer)
        }

        /// Reads the specified number of bytes at a pointer from the current stream
        /// into a byte array without advancing the current position.
        pub fn read_bytes_at(&mut self, offset: u64, count: u64) -> Result<Vec<u8>, BufferError> {
            if offset + count > self.len()? {
                return Err(BufferError::EndOfStream);
            }
            let current_pos = self.position()?;
            self.seek(offset as i64, SeekOrigin::Begin)?;
            let buffer = self.read_bytes(count)?;
            self.seek(current_pos as i64, SeekOrigin::Begin)?;
            Ok(buffer)
        }
    }

    #[derive(Debug, Fail)]
    pub enum BufferError {
        #[fail(
            display = "seek index ({}) was out of range. Must be non-negative and less than the size of the collection.",
            index
        )]
        IndexOutOfRange { index: i64 },

        #[fail(display = "attempted to read past the end of a stream.")]
        EndOfStream,

        #[fail(display = "unable to read bytes from buffer: {:?}", error)]
        ReadFailure { error: Error },

        #[fail(display = "unable to write data to buffer.")]
        IOFailure,
    }
}

#[cfg(test)]
mod tests {
    #[test]
    fn it_works() {
        use crate::buffer::{BufferReader, BufferWriter, SeekOrigin};
        use std::io::Cursor;
        let mut buffer = BufferWriter::new(Cursor::new(Vec::new()));
        buffer.write_u32(9001).unwrap();
        buffer.write_u32(9002).unwrap();
        buffer.write_string("Hello World!".to_string()).unwrap();
        buffer.seek(0, SeekOrigin::Begin).unwrap();
        buffer.write_u32(9003).unwrap();
        let data = buffer.to_vec().unwrap();
        let mut reader = BufferReader::new(Cursor::new(data));
        assert_eq!(9003, reader.read_u32().unwrap());
        assert_eq!(9002, reader.read_u32().unwrap());
        assert_eq!("Hello World!", reader.read_string().unwrap());
    }
}