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
//! 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;

macro_rules! read_varint {
  ($type: ty, $self: expr) => {
    {
      let mut shift: $type = 0;
      let mut decoded: $type = 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 $type) << shift;

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

/// 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> {
    read_varint!(u8, self)
  }

  /// 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> {
    read_varint!(u16, self)
  }

  /// 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> {
    read_varint!(u32, self)
  }

  /// 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> {
    read_varint!(u64, self)
  }

  /// 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> {
    read_varint!(u128, self)
  }

  /// 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> {
    read_varint!(usize, self)
  }
}

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

macro_rules! write_varint {
  ($type: ty, $self: expr, $value: expr) => {
    {
      let mut value: $type = $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])
      }
    }
  };
}

/// 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> {
    write_varint!(u8, self, value)
  }

  /// 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> {
    write_varint!(u16, self, value)
  }

  /// 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> {
    write_varint!(u32, self, value)
  }

  /// 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> {
    write_varint!(u64, self, value)
  }

  /// 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> {
    write_varint!(u128, self, value)
  }

  /// 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> {
    write_varint!(usize, self, value)
  }
}

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