reader.rs 4.9 KB

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