var_int/
lib.rs

1extern crate byteorder;
2
3use std::io::{Read, Write, Error, ErrorKind, self};
4
5use byteorder::{ReadBytesExt, WriteBytesExt};
6
7pub trait VarIntRead: Read {
8    fn read_varint_u32(&mut self) -> io::Result<u32> {
9        const PART: u32 = 0x7F;
10        let mut size = 0;
11        let mut val = 0u32;
12        loop {
13            let b = self.read_u8()? as u32;
14            val |= (b & PART) << (size * 7);
15            size += 1;
16            if size > 5{
17                return Err(Error::from(ErrorKind::InvalidInput));
18            }
19            if (b & 0x80) == 0 {
20                break;
21            }
22        }
23        Ok(val)
24    }
25}
26
27pub trait VarIntWrite: Write {
28    fn write_varint_u32(&mut self, val: u32) -> io::Result<()> {
29        const PART: u32 = 0x7F;
30        let mut val = val;
31        loop {
32            if (val & !PART) == 0 {
33                self.write_u8(val as u8)?;
34                return Ok(());
35            }
36            self.write_u8(((val & PART) | 0x80) as u8)?;
37            val >>= 7;
38        }
39    }
40}
41
42impl <R: Read + Sized> VarIntRead for R {
43}
44
45impl <W: Write + Sized> VarIntWrite for W {
46}