1 from .binary import encode_bin, decode_bin
3 class BitStreamReader(object):
5 __slots__ = ["substream", "buffer", "total_size"]
7 def __init__(self, substream):
8 self.substream = substream
13 if self.total_size % 8 != 0:
14 raise ValueError("total size of read data must be a multiple of 8",
18 return self.substream.tell()
20 def seek(self, pos, whence = 0):
23 self.substream.seek(pos, whence)
25 def read(self, count):
27 raise ValueError("count cannot be negative")
33 data = self.buffer[:count]
34 self.buffer = self.buffer[count:]
41 buf = encode_bin(self.substream.read(bytes))
43 self.buffer = buf[count:]
44 self.total_size += len(data)
47 class BitStreamWriter(object):
49 __slots__ = ["substream", "buffer", "pos"]
51 def __init__(self, substream):
52 self.substream = substream
60 bytes = decode_bin("".join(self.buffer))
61 self.substream.write(bytes)
66 return self.substream.tell() + self.pos // 8
68 def seek(self, pos, whence = 0):
70 self.substream.seek(pos, whence)
72 def write(self, data):
75 if type(data) is not str:
76 raise TypeError("data must be a string, not %r" % (type(data),))
77 self.buffer.append(data)