1
2
3
4 """
5 Implements a way to easily read and write binary types
6 """
7
8 from cStringIO import StringIO
9 import struct
10
11 BYTE = struct.Struct('b')
12 UBYTE = struct.Struct('B')
13 SHORT = struct.Struct('h')
14 USHORT = struct.Struct('H')
15 FLOAT = struct.Struct('f')
16 INT = struct.Struct('i')
17 UINT = struct.Struct('I')
18
20 buffer = None
21
23 """
24 @param input: The input to initially fill the reader with
25 @type input: file/str/buffer
26 """
27 if isinstance(input, file):
28 buffer = input
29 self.write = buffer.write
30 else:
31 if input is not None:
32 buffer = StringIO(input)
33 else:
34 buffer = StringIO()
35 self.write = buffer.write
36 self.data = buffer.getvalue
37
38 self.buffer = buffer
39 self.tell = buffer.tell
40
42 currentPosition = self.tell()
43 self.seek(0)
44 data = self.read()
45 self.seek(currentPosition)
46 return data
47
48 - def seek(self, *arg, **kw):
50
51 - def read(self, *arg, **kw):
53
55 currentPosition = self.tell()
56 self.seek(0, 2)
57 size = self.tell()
58 self.seek(currentPosition)
59 return size
60
63
66
68 return repr(str(self))
69
74
79
83
84 - def readInt(self, unsigned = False):
88
90 currentPosition = self.tell()
91 store = ''
92 while 1:
93 readChar = self.read(1)
94 if readChar in ('\x00', ''):
95 break
96 store = ''.join([store, readChar])
97 return store
98
100 return structType.unpack(self.read(structType.size))
101
102 - def writeByte(self, value, unsigned = False):
105
109
112
113 - def writeInt(self, value, unsigned = False):
116
118 self.write(value + "\x00")
119
121 self.write(structType.pack(*values))
122