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