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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
//! Varint is an alternative way of storing integer numbers.
//! 
//! Varints allow for the storage of larger integer types in a smaller amount of
//! space. It does this by storing an integer using the `7` lower bits and a flag
//! in the most-significant bit. This flag is set to `1` when more bytes should
//! be read. The groups of `7` bits are then added from the least-significant
//! group first.
//! 
//! ## Example
//! ```
//! // to allow the use of the `VarintWriter::write_*_varint` functions
//! use varint_rs::VarintWriter;
//! // to allow the use of the `VarintReader::read_*_varint` functions
//! use varint_rs::VarintReader;
//! 
//! // an example to use for the buffer
//! use std::io::Cursor;
//! 
//! // create an i32 set to `300`
//! let number: i32 = 300;
//! // create a buffer for the varint to be writen to
//! // an i32 can be `4` bytes maximum, so we pre-allocate the capacity
//! let mut buffer: Cursor<Vec<u8>> = Cursor::new(Vec::with_capacity(4));
//! 
//! // now we can write the varint into the buffer
//! // `300` should only use `2` bytes instead of all `4`
//! // the `write_*_varint` functions may return an `std::io::Error`
//! buffer.write_i32_varint(number).unwrap();
//! 
//! // we reset the cursor pos back to `0`, this isn't varint stuff
//! buffer.set_position(0);
//! 
//! // now we can read the varint from the buffer
//! // we should read `300` which was the number we stored
//! // the `read_*_varint` functions may return an `std::io::Error`
//! let number: i32 = buffer.read_i32_varint().unwrap();
//! ```

pub mod zigzag;
pub use zigzag::Zigzag;

use std::io;

/// The `VarintReader` trait enables reading of varints.
/// 
/// This is pre-implemented on structures which implement `std::io::Read`. It also
/// extends the `std::io::Read` trait to allow for reading from valid *readers*.
pub trait VarintReader: io::Read {
  /// Reads an i8 from a signed 8-bit varint.
  fn read_i8_varint(&mut self) -> Result<i8, io::Error> {
    match self.read_u8_varint() {
      Ok(value) => Ok(value.zigzag()),
      Err(error) => Err(error)
    }
  }

  /// Reads a u8 from an unsigned 8-bit varint.
  fn read_u8_varint(&mut self) -> Result<u8, io::Error> {
    let mut shift: u8 = 0;
    let mut decoded: u8 = 0;
    let mut buf: [u8; 1] = [0];
    let mut next: u8 = 0;

    loop {
      match self.read(&mut buf) {
        Ok(count) => {
          if count == 1 {
            next = buf[0];
          } else {
            Err(io::Error::new(io::ErrorKind::UnexpectedEof, "could not read byte"))?
          }
        },
        Err(error) => Err(error)?
      }

      decoded |= ((next & 0b01111111) as u8) << shift;

      if next & 0b10000000 == 0b10000000 {
        shift += 7;
      } else {
        return Ok(decoded)
      }
    }
  }

  /// Reads an i16 from a signed 16-bit varint.
  fn read_i16_varint(&mut self) -> Result<i16, io::Error> {
    match self.read_u16_varint() {
      Ok(value) => Ok(value.zigzag()),
      Err(error) => Err(error)
    }
  }

  /// Reads a u16 from an unsigned 16-bit varint.
  fn read_u16_varint(&mut self) -> Result<u16, io::Error> {
    let mut shift: u16 = 0;
    let mut decoded: u16 = 0;
    let mut buf: [u8; 1] = [0];
    let mut next: u8 = 0;

    loop {
      match self.read(&mut buf) {
        Ok(count) => {
          if count == 1 {
            next = buf[0];
          } else {
            Err(io::Error::new(io::ErrorKind::UnexpectedEof, "could not read byte"))?
          }
        },
        Err(error) => Err(error)?
      }

      decoded |= ((next & 0b01111111) as u16) << shift;

      if next & 0b10000000 == 0b10000000 {
        shift += 7;
      } else {
        return Ok(decoded)
      }
    }
  }

  /// Reads an i32 from a signed 32-bit varint.
  fn read_i32_varint(&mut self) -> Result<i32, io::Error> {
    match self.read_u32_varint() {
      Ok(value) => Ok(value.zigzag()),
      Err(error) => Err(error)
    }
  }

  /// Reads a u32 from an unsigned 32-bit varint.
  fn read_u32_varint(&mut self) -> Result<u32, io::Error> {
    let mut shift: u32 = 0;
    let mut decoded: u32 = 0;
    let mut buf: [u8; 1] = [0];
    let mut next: u8 = 0;

    loop {
      match self.read(&mut buf) {
        Ok(count) => {
          if count == 1 {
            next = buf[0];
          } else {
            Err(io::Error::new(io::ErrorKind::UnexpectedEof, "could not read byte"))?
          }
        },
        Err(error) => Err(error)?
      }

      decoded |= ((next & 0b01111111) as u32) << shift;

      if next & 0b10000000 == 0b10000000 {
        shift += 7;
      } else {
        return Ok(decoded)
      }
    }
  }

  /// Reads an i64 from a signed 64-bit varint.
  fn read_i64_varint(&mut self) -> Result<i64, io::Error> {
    match self.read_u64_varint() {
      Ok(value) => Ok(value.zigzag()),
      Err(error) => Err(error)
    }
  }

  /// Reads a u64 from an unsigned 64-bit varint.
  fn read_u64_varint(&mut self) -> Result<u64, io::Error> {
    let mut shift: u64 = 0;
    let mut decoded: u64 = 0;
    let mut buf: [u8; 1] = [0];
    let mut next: u8 = 0;

    loop {
      match self.read(&mut buf) {
        Ok(count) => {
          if count == 1 {
            next = buf[0];
          } else {
            Err(io::Error::new(io::ErrorKind::UnexpectedEof, "could not read byte"))?
          }
        },
        Err(error) => Err(error)?
      }

      decoded |= ((next & 0b01111111) as u64) << shift;

      if next & 0b10000000 == 0b10000000 {
        shift += 7;
      } else {
        return Ok(decoded)
      }
    }
  }

  /// Reads an i128 from a signed 128-bit varint.
  fn read_i128_varint(&mut self) -> Result<i128, io::Error> {
    match self.read_u128_varint() {
      Ok(value) => Ok(value.zigzag()),
      Err(error) => Err(error)
    }
  }

  /// Reads a u128 from an unsigned 128-bit varint.
  fn read_u128_varint(&mut self) -> Result<u128, io::Error> {
    let mut shift: u128 = 0;
    let mut decoded: u128 = 0;
    let mut buf: [u8; 1] = [0];
    let mut next: u8 = 0;

    loop {
      match self.read(&mut buf) {
        Ok(count) => {
          if count == 1 {
            next = buf[0];
          } else {
            Err(io::Error::new(io::ErrorKind::UnexpectedEof, "could not read byte"))?
          }
        },
        Err(error) => Err(error)?
      }

      decoded |= ((next & 0b01111111) as u128) << shift;

      if next & 0b10000000 == 0b10000000 {
        shift += 7;
      } else {
        return Ok(decoded)
      }
    }
  }

  /// Reads an isize from a signed size-bit varint.
  fn read_isize_varint(&mut self) -> Result<isize, io::Error> {
    match self.read_usize_varint() {
      Ok(value) => Ok(value.zigzag()),
      Err(error) => Err(error)
    }
  }

  /// Reads a usize from an unsigned size-bit varint.
  fn read_usize_varint(&mut self) -> Result<usize, io::Error> {
    let mut shift: usize = 0;
    let mut decoded: usize = 0;
    let mut buf: [u8; 1] = [0];
    let mut next: u8 = 0;

    loop {
      match self.read(&mut buf) {
        Ok(count) => {
          if count == 1 {
            next = buf[0];
          } else {
            Err(io::Error::new(io::ErrorKind::UnexpectedEof, "could not read byte"))?
          }
        },
        Err(error) => Err(error)?
      }

      decoded |= ((next & 0b01111111) as usize) << shift;

      if next & 0b10000000 == 0b10000000 {
        shift += 7;
      } else {
        return Ok(decoded)
      }
    }
  }
}

impl<R: io::Read> VarintReader for R {}

/// The `VarintWriter` trait enable writing of varints.
/// 
/// This is pre-implemented on structures which implement `std::io::Write`. It also
/// extends the `std::io::Write` trait to allow for writing to valid *writes"*.
pub trait VarintWriter: io::Write {
  /// Writes an i8 to a signed 8-bit varint.
  fn write_i8_varint(&mut self, value: i8) -> Result<(), io::Error> {
    self.write_u8_varint(value.zigzag())
  }

  /// Writes a u8 to an unsigned 8-bit varint.
  fn write_u8_varint(&mut self, value: u8) -> Result<(), io::Error> {
    let mut value: u8 = value;

    if value == 0 {
      self.write_all(&[0])
    } else {
      while value >= 0b10000000 {
        let next: u8 = ((value & 0b01111111) as u8) | 0b10000000;
        value >>= 7;

        match self.write_all(&[next]) {
          Err(error) => Err(error)?,
          Ok(_) => ()
        }
      }

      self.write_all(&[(value & 0b01111111) as u8])
    }
  }

  /// Writes an i16 to a signed 16-bit varint.
  fn write_i16_varint(&mut self, value: i16) -> Result<(), io::Error> {
    self.write_u16_varint(value.zigzag())
  }

  /// Writes a u16 to an unsigned 16-bit varint.
  fn write_u16_varint(&mut self, value: u16) -> Result<(), io::Error> {
    let mut value: u16 = value;

    if value == 0 {
      self.write_all(&[0])
    } else {
      while value >= 0b10000000 {
        let next: u8 = ((value & 0b01111111) as u8) | 0b10000000;
        value >>= 7;

        match self.write_all(&[next]) {
          Err(error) => Err(error)?,
          Ok(_) => ()
        }
      }

      self.write_all(&[(value & 0b01111111) as u8])
    }
  }

  /// Writes an i32 to a signed 32-bit varint.
  fn write_i32_varint(&mut self, value: i32) -> Result<(), io::Error> {
    self.write_u32_varint(value.zigzag())
  }

  /// Writes a u32 to an unsigned 32-bit varint.
  fn write_u32_varint(&mut self, value: u32) -> Result<(), io::Error> {
    let mut value: u32 = value;

    if value == 0 {
      self.write_all(&[0])
    } else {
      while value >= 0b10000000 {
        let next: u8 = ((value & 0b01111111) as u8) | 0b10000000;
        value >>= 7;

        match self.write_all(&[next]) {
          Err(error) => Err(error)?,
          Ok(_) => ()
        }
      }

      self.write_all(&[(value & 0b01111111) as u8])
    }
  }

  /// Writes an i64 to a signed 64-bit varint.
  fn write_i64_varint(&mut self, value: i64) -> Result<(), io::Error> {
    self.write_u64_varint(value.zigzag())
  }

  /// Writes a u64 to an unsigned 64-bit varint.
  fn write_u64_varint(&mut self, value: u64) -> Result<(), io::Error> {
    let mut value: u64 = value;

    if value == 0 {
      self.write_all(&[0])
    } else {
      while value >= 0b10000000 {
        let next: u8 = ((value & 0b01111111) as u8) | 0b10000000;
        value >>= 7;

        match self.write_all(&[next]) {
          Err(error) => Err(error)?,
          Ok(_) => ()
        }
      }

      self.write_all(&[(value & 0b01111111) as u8])
    }
  }

  /// Writes an i128 to a signed 128-bit varint.
  fn write_i128_varint(&mut self, value: i128) -> Result<(), io::Error> {
    self.write_u128_varint(value.zigzag())
  }

  /// Writes a u128 to an unsigned 128-bit varint.
  fn write_u128_varint(&mut self, value: u128) -> Result<(), io::Error> {
    let mut value: u128 = value;

    if value == 0 {
      self.write_all(&[0])
    } else {
      while value >= 0b10000000 {
        let next: u8 = ((value & 0b01111111) as u8) | 0b10000000;
        value >>= 7;

        match self.write_all(&[next]) {
          Err(error) => Err(error)?,
          Ok(_) => ()
        }
      }

      self.write_all(&[(value & 0b01111111) as u8])
    }
  }

  /// Writes an isize to a signed size-bit varint.
  fn write_isize_varint(&mut self, value: isize) -> Result<(), io::Error> {
    self.write_usize_varint(value.zigzag())
  }

  /// Writes a usize to an unsigned size-bit varint.
  fn write_usize_varint(&mut self, value: usize) -> Result<(), io::Error> {
    let mut value: usize = value;

    if value == 0 {
      self.write_all(&[0])
    } else {
      while value >= 0b10000000 {
        let next: u8 = ((value & 0b01111111) as u8) | 0b10000000;
        value >>= 7;

        match self.write_all(&[next]) {
          Err(error) => Err(error)?,
          Ok(_) => ()
        }
      }

      self.write_all(&[(value & 0b01111111) as u8])
    }
  }
}

impl<W: io::Write> VarintWriter for W {}