| 1 | |
use std::{fs,io,iter,slice,vec};
|
| 1 |
use std::{fs,io,iter,mem,slice,vec};
|
| 2 |
use bzip2::bufread::BzDecoder;
|
| 2 | 3 |
|
| 3 | 4 |
/// A `ByteReader` is just a tiny wrapper over a mutable byte iterator, so we
|
| 4 | 5 |
/// can parse things more easily.
|
|
| 6 | 7 |
bytes: Rd,
|
| 7 | 8 |
}
|
| 8 | 9 |
|
| 9 | |
impl<R: io::Read>
|
| 10 | |
ByteReader<iter::FilterMap<io::Bytes<R>,
|
| 11 | |
&'static Fn(io::Result<u8>) -> Option<u8>>>
|
| 10 |
impl<R: io::Read> ByteReader<iter::FilterMap<io::Bytes<R>, &'static Fn(io::Result<u8>) -> Option<u8>>>
|
| 12 | 11 |
{
|
| 13 | 12 |
/// Create a ByteReader from any type that implement Read
|
| 14 | 13 |
pub fn from_reader(r: R) -> Self {
|
|
| 35 | 34 |
}
|
| 36 | 35 |
}
|
| 37 | 36 |
|
| 38 | |
impl<'a> ByteReader<iter::Map<slice::Iter<'a, u8>, &'static Fn(&u8) -> u8>> {
|
| 37 |
impl<'a> ByteReader<iter::Cloned<slice::Iter<'a, u8>>> {
|
| 39 | 38 |
/// Create a reader from a borrowed slice, with a copy on each access
|
| 40 | 39 |
pub fn from_slice(lst: &'a [u8]) -> Self {
|
| 41 | |
const DEREF: &'static Fn(&u8) -> u8 = &|s| *s;
|
| 42 | |
ByteReader { bytes: lst.iter().map(DEREF) }
|
| 40 |
ByteReader { bytes: lst.iter().cloned() }
|
| 41 |
}
|
| 42 |
}
|
| 43 |
|
| 44 |
impl<R: io::BufRead> ByteReader<iter::FilterMap<io::Bytes<BzDecoder<R>>, &'static Fn(io::Result<u8>) -> Option<u8>>> {
|
| 45 |
pub fn from_compressed_reader(r: R) -> Self {
|
| 46 |
ByteReader::from_reader(BzDecoder::new(r))
|
| 47 |
}
|
| 48 |
}
|
| 49 |
|
| 50 |
impl ByteReader<iter::FilterMap<io::Bytes<BzDecoder<io::BufReader<fs::File>>>, &'static Fn(io::Result<u8>) -> Option<u8>>> {
|
| 51 |
pub fn from_compressed_file(path: &str) -> io::Result<Self> {
|
| 52 |
let f = try!(fs::File::open(path));
|
| 53 |
Ok(ByteReader::from_compressed_reader(io::BufReader::new(f)))
|
| 43 | 54 |
}
|
| 44 | 55 |
}
|
| 45 | 56 |
|
|
| 79 | 90 |
pub fn read_ratio(&mut self) -> Result<f32, String> {
|
| 80 | 91 |
let b = try!(self.next());
|
| 81 | 92 |
Ok(b as f32 / 255.0)
|
| 93 |
}
|
| 94 |
|
| 95 |
pub fn read_u32be(&mut self) -> Result<u32, String> {
|
| 96 |
let a = try!(self.next());
|
| 97 |
let b = try!(self.next());
|
| 98 |
let c = try!(self.next());
|
| 99 |
let d = try!(self.next());
|
| 100 |
let rs = [ d, c, b, a ];
|
| 101 |
unsafe { Ok(mem::transmute::<[u8;4],u32>(rs)) }
|
| 102 |
}
|
| 103 |
|
| 104 |
pub fn read_u16be(&mut self) -> Result<u16, String> {
|
| 105 |
let a = try!(self.next());
|
| 106 |
let b = try!(self.next());
|
| 107 |
let rs = [ b, a ];
|
| 108 |
unsafe { Ok(mem::transmute::<[u8;2],u16>(rs)) }
|
| 82 | 109 |
}
|
| 83 | 110 |
|
| 84 | 111 |
/// This reads a 64-bit int with a packed PrefixInteger representation.
|