Wraps a file-like object to provide access to structured data from a binary file. Byte-order is configurable. `base_offset` is added to any base value provided to calculate actual location for reads.
| 7 | |
| 8 | |
| 9 | class StreamReader: |
| 10 | """Wraps a file-like object to provide access to structured data from a binary file. |
| 11 | |
| 12 | Byte-order is configurable. `base_offset` is added to any base value provided to |
| 13 | calculate actual location for reads. |
| 14 | """ |
| 15 | |
| 16 | def __init__(self, stream, byte_order, base_offset=0): |
| 17 | super(StreamReader, self).__init__() |
| 18 | self._stream = stream |
| 19 | self._byte_order = LITTLE_ENDIAN if byte_order == LITTLE_ENDIAN else BIG_ENDIAN |
| 20 | self._base_offset = base_offset |
| 21 | |
| 22 | def read(self, count): |
| 23 | """Allow pass-through read() call.""" |
| 24 | return self._stream.read(count) |
| 25 | |
| 26 | def read_byte(self, base, offset=0): |
| 27 | """Return the int value of the byte at the file position defined by |
| 28 | self._base_offset + `base` + `offset`. |
| 29 | |
| 30 | If `base` is None, the byte is read from the current position in the stream. |
| 31 | """ |
| 32 | fmt = "B" |
| 33 | return self._read_int(fmt, base, offset) |
| 34 | |
| 35 | def read_long(self, base, offset=0): |
| 36 | """Return the int value of the four bytes at the file position defined by |
| 37 | self._base_offset + `base` + `offset`. |
| 38 | |
| 39 | If `base` is None, the long is read from the current position in the stream. The |
| 40 | endian setting of this instance is used to interpret the byte layout of the |
| 41 | long. |
| 42 | """ |
| 43 | fmt = "<L" if self._byte_order is LITTLE_ENDIAN else ">L" |
| 44 | return self._read_int(fmt, base, offset) |
| 45 | |
| 46 | def read_short(self, base, offset=0): |
| 47 | """Return the int value of the two bytes at the file position determined by |
| 48 | `base` and `offset`, similarly to ``read_long()`` above.""" |
| 49 | fmt = b"<H" if self._byte_order is LITTLE_ENDIAN else b">H" |
| 50 | return self._read_int(fmt, base, offset) |
| 51 | |
| 52 | def read_str(self, char_count, base, offset=0): |
| 53 | """Return a string containing the `char_count` bytes at the file position |
| 54 | determined by self._base_offset + `base` + `offset`.""" |
| 55 | |
| 56 | def str_struct(char_count): |
| 57 | format_ = "%ds" % char_count |
| 58 | return Struct(format_) |
| 59 | |
| 60 | struct = str_struct(char_count) |
| 61 | chars = self._unpack_item(struct, base, offset) |
| 62 | unicode_str = chars.decode("UTF-8") |
| 63 | return unicode_str |
| 64 | |
| 65 | def seek(self, base, offset=0): |
| 66 | location = self._base_offset + base + offset |
no outgoing calls
searching dependent graphs…