reader.rs 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  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_slice(&[0x00]).read_twip() == Ok(-32.0));
  10. assert!(ByteReader::from_slice(&[0x00]).read_prefix_int() == Ok(0x00));
  11. assert!(ByteReader::from_slice(&[0x7f]).read_prefix_int() == Ok(0x7f));
  12. assert!(ByteReader::from_slice(&[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. const DEREF: &'static Fn(&u8) -> u8 = &|s| *s;
  41. impl<'a> ByteReader<iter::Map<slice::Iter<'a, u8>, &'static Fn(&u8) -> u8>> {
  42. /// Create a reader from a borrowed slice, with a copy on each access
  43. pub fn from_slice(lst: &'a [u8]) -> Self {
  44. ByteReader { bytes: lst.iter().map(DEREF) }
  45. }
  46. }
  47. impl<T> ByteReader<T> where T: Iterator<Item=u8> {
  48. /// This gets the next byte, or fails if it's out of input.
  49. pub fn next(&mut self) -> Result<u8, String> {
  50. Ok(try!(self.bytes.next().ok_or("out of input")))
  51. }
  52. /// This reads a one-byte or two-byte float in the rough range of
  53. /// (192 .. -128). We're going to treat all models as if they're
  54. /// supposed to be centered in a 64x64x64 square, so this gives
  55. /// us 128 units on either side of the central square, as well.
  56. pub fn read_twip(&mut self) -> Result<f32, String> {
  57. let b1 = try!(self.next());
  58. if (b1 & 0x80) != 0 {
  59. let b2 = try!(self.next());
  60. let val = ((b1 as u16 & 0x7f) << 8) | b2 as u16;
  61. Ok((val as f32 / 102.0) - 128.0)
  62. } else {
  63. Ok((b1 as f32) - 32.0)
  64. }
  65. }
  66. /// This reads a single byte and treats it as a ratio.
  67. pub fn read_ratio(&mut self) -> Result<f32, String> {
  68. let b = try!(self.next());
  69. Ok(b as f32 / 255.0)
  70. }
  71. /// This reads a 64-bit int with a packed PrefixInteger representation.
  72. /// The shorter the int, the shorter the representation.
  73. pub fn read_prefix_int(&mut self) -> Result<u64, String> {
  74. fn match_bits(n: u8, mask: u8) -> bool {
  75. n & mask == mask
  76. }
  77. let b = try!(self.next());
  78. if match_bits(b, 0xff) { self.continue_prefix_int(8, 0) }
  79. else if match_bits(b, 0xfe) { self.continue_prefix_int(7, 0) }
  80. else if match_bits(b, 0xfc) { self.continue_prefix_int(6, b & 0x01) }
  81. else if match_bits(b, 0xf8) { self.continue_prefix_int(5, b & 0x03) }
  82. else if match_bits(b, 0xf0) { self.continue_prefix_int(4, b & 0x07) }
  83. else if match_bits(b, 0xe0) { self.continue_prefix_int(3, b & 0x0f) }
  84. else if match_bits(b, 0xc0) { self.continue_prefix_int(2, b & 0x1f) }
  85. else if match_bits(b, 0x80) { self.continue_prefix_int(1, b & 0x3f) }
  86. else { self.continue_prefix_int(0, b) }
  87. }
  88. /// This is a helper function for parsing prefix ints, too.
  89. fn continue_prefix_int(&mut self, mut left: u8, upper: u8) -> Result<u64, String> {
  90. let mut ret = upper as u64;
  91. while left > 0 {
  92. left -= 1;
  93. ret = (ret << 8) | try!(self.next()) as u64;
  94. }
  95. Ok(ret)
  96. }
  97. /// This reads a PrefixInteger to find out how many other things to read,
  98. /// and then reads that number of things.
  99. pub fn read_several<F, R>(&mut self, reader: F) -> Result<Vec<R>, String>
  100. where F: Fn(&mut ByteReader<T>) -> Result<R, String>
  101. {
  102. let ct = try!(self.read_prefix_int());
  103. let mut ret = Vec::with_capacity(ct as usize);
  104. for _ in 0..ct {
  105. ret.push(try!(reader(self)))
  106. }
  107. Ok(ret)
  108. }
  109. /// This reads a PrefixInteger number of bytes, and then parses those
  110. /// bytes as a UTF-8 string. This means, importantly, that we cannot
  111. /// naïvely produce values intended to be parsed with this using a
  112. /// basic string length.
  113. pub fn read_string(&mut self) -> Result<String, String> {
  114. let raw_bytes = try!(self.read_several(|r| r.next()));
  115. match String::from_utf8(raw_bytes) {
  116. Ok(s) => Ok(s),
  117. Err(e) => Err(format!("Exception when parsing UTF-8: {:?}", e)),
  118. }
  119. }
  120. }