reader.rs 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. use std::{fs,io,iter,slice,vec};
  2. /// A `ByteReader` is just a tiny wrapper over a mutable byte iterator, so we
  3. /// can parse things more easily.
  4. pub struct ByteReader<Rd> {
  5. bytes: Rd,
  6. }
  7. pub type ByteReaderT = ByteReader<Iterator<Item=u8>>;
  8. const MK_OK: &'static Fn(io::Result<u8>) -> Option<u8> = &|s| s.ok();
  9. impl<R: io::Read>
  10. ByteReader<iter::FilterMap<io::Bytes<R>,
  11. &'static Fn(io::Result<u8>) -> Option<u8>>>
  12. {
  13. /// Create a ByteReader from any type that implement Read
  14. pub fn from_reader(r: R) -> Self {
  15. let bytes = r.bytes().filter_map(MK_OK);
  16. ByteReader { bytes: bytes }
  17. }
  18. }
  19. impl ByteReader<iter::FilterMap<io::Bytes<fs::File>,
  20. &'static Fn(io::Result<u8>) -> Option<u8>>>
  21. {
  22. /// Create a reader by opening a named file for reading
  23. pub fn from_file(path: &str) -> io::Result<Self> {
  24. let f = try!(fs::File::open(path));
  25. Ok(ByteReader::from_reader(f))
  26. }
  27. }
  28. impl ByteReader<vec::IntoIter<u8>> {
  29. /// Create a reader from a vector of u8s
  30. pub fn from_vec(lst: Vec<u8>) -> Self {
  31. ByteReader { bytes: lst.into_iter() }
  32. }
  33. }
  34. impl<'a> ByteReader<slice::Iter<'a, u8>> {
  35. pub fn from_slice(lst: &'a [u8]) -> Self {
  36. ByteReader { bytes: lst.iter() }
  37. }
  38. }
  39. impl<T> ByteReader<T> where T: Iterator<Item=u8> {
  40. /// This gets the next byte, or fails if it's out of input.
  41. pub fn next(&mut self) -> Result<u8, String> {
  42. Ok(try!(self.bytes.next().ok_or("out of input")))
  43. }
  44. /// This reads a one-byte or two-byte float in the rough range of
  45. /// (192 .. -128). We're going to treat all models as if they're
  46. /// supposed to be centered in a 64x64x64 square, so this gives
  47. /// us 128 units on either side of the central square, as well.
  48. pub fn read_twip(&mut self) -> Result<f32, String> {
  49. let b1 = try!(self.next());
  50. if (b1 & 0x80) != 0 {
  51. let b2 = try!(self.next());
  52. let val = ((b1 as u16 & 0x7f) << 8) | b2 as u16;
  53. Ok((val as f32 / 102.0) - 128.0)
  54. } else {
  55. Ok((b1 as f32) - 32.0)
  56. }
  57. }
  58. /// This reads a single byte and treats it as a ratio.
  59. pub fn read_ratio(&mut self) -> Result<f32, String> {
  60. let b = try!(self.next());
  61. Ok(b as f32 / 255.0)
  62. }
  63. /// This reads a 64-bit int with a packed PrefixInteger representation.
  64. /// The shorter the int, the shorter the representation.
  65. pub fn read_prefix_int(&mut self) -> Result<u64, String> {
  66. fn match_bits(n: u8, mask: u8) -> bool {
  67. n & mask == mask
  68. }
  69. let b = try!(self.next());
  70. if match_bits(b, 0xff) { self.continue_prefix_int(8, 0) }
  71. else if match_bits(b, 0xfe) { self.continue_prefix_int(7, 0) }
  72. else if match_bits(b, 0xfc) { self.continue_prefix_int(6, b & 0x01) }
  73. else if match_bits(b, 0xf8) { self.continue_prefix_int(5, b & 0x03) }
  74. else if match_bits(b, 0xf0) { self.continue_prefix_int(4, b & 0x07) }
  75. else if match_bits(b, 0xe0) { self.continue_prefix_int(3, b & 0x0f) }
  76. else if match_bits(b, 0xc0) { self.continue_prefix_int(2, b & 0x1f) }
  77. else if match_bits(b, 0x80) { self.continue_prefix_int(1, b & 0x3f) }
  78. else { self.continue_prefix_int(0, b) }
  79. }
  80. /// This is a helper function for parsing prefix ints, too.
  81. fn continue_prefix_int(&mut self, mut left: u8, upper: u8) -> Result<u64, String> {
  82. let mut ret = upper as u64;
  83. while left > 0 {
  84. left -= 1;
  85. ret = (ret << 8) | try!(self.next()) as u64;
  86. }
  87. Ok(ret)
  88. }
  89. /// This reads a PrefixInteger to find out how many other things to read,
  90. /// and then reads that number of things.
  91. pub fn read_several<F, R>(&mut self, reader: F) -> Result<Vec<R>, String>
  92. where F: Fn(&mut ByteReader<T>) -> Result<R, String>
  93. {
  94. let ct = try!(self.read_prefix_int());
  95. let mut ret = Vec::with_capacity(ct as usize);
  96. for _ in 0..ct {
  97. ret.push(try!(reader(self)))
  98. }
  99. Ok(ret)
  100. }
  101. /// This reads a PrefixInteger number of bytes, and then parses those
  102. /// bytes as a UTF-8 string. This means, importantly, that we cannot
  103. /// naïvely produce values intended to be parsed with this using a
  104. /// basic string length.
  105. pub fn read_string(&mut self) -> Result<String, String> {
  106. let raw_bytes = try!(self.read_several(|r| r.next()));
  107. match String::from_utf8(raw_bytes) {
  108. Ok(s) => Ok(s),
  109. Err(e) => Err(format!("Exception when parsing UTF-8: {:?}", e)),
  110. }
  111. }
  112. }