use std::io;
use std::io::{Read, Result};
use fixed::FixedInt;
use varint::{VarInt, MSB};
pub trait VarIntReader {
fn read_varint<VI: VarInt>(&mut self) -> Result<VI>;
}
impl<R: Read> VarIntReader for R {
fn read_varint<VI: VarInt>(&mut self) -> Result<VI> {
const BUFLEN: usize = 10;
let mut buf = [0 as u8; BUFLEN];
let mut i = 0;
loop {
if i >= BUFLEN {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"Unterminated varint",
));
}
let read = try!(self.read(&mut buf[i..i + 1]));
if read == 0 && i == 0 {
return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "Reached EOF"));
}
if buf[i] & MSB == 0 {
break;
}
i += 1;
}
let (result, _) = VI::decode_var(&buf[0..i + 1]);
Ok(result)
}
}
pub trait FixedIntReader {
fn read_fixedint<FI: FixedInt>(&mut self) -> Result<FI>;
}
impl<R: Read> FixedIntReader for R {
fn read_fixedint<FI: FixedInt>(&mut self) -> Result<FI> {
let mut buf = [0 as u8; 8];
let read = try!(self.read(&mut buf[0..FI::required_space()]));
if read == 0 {
return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "Reached EOF"));
}
Ok(FI::decode_fixed(&buf[0..read]))
}
}