-
Notifications
You must be signed in to change notification settings - Fork 0
/
structio.py
289 lines (208 loc) · 8.29 KB
/
structio.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
import io
import struct
_endians = {'big': '>', 'little': '<'}
_float_formats = {2: 'e', 4: 'f', 8: 'd'}
class Struct:
def __init__(self, endian='little', encoding='utf-8', errors='ignore'):
self.endian = endian
self.encoding = encoding
self.errors = errors
def _get_endian(self, endian):
if endian is None:
return self.endian
else:
return endian
def unpack_bool(self, b):
if isinstance(b, int):
return b != 0
elif len(b) == 1:
return b != b'\x00'
else:
raise ValueError('expected int or bytes object of length 1')
def pack_bool(self, boolean):
if boolean:
return b'\x01'
else:
return b'\x00'
def unpack_bits(self, b):
if isinstance(b, int):
number = b
elif len(b) == 1:
number = self.unpack_int(b)
else:
raise ValueError('expected int or bytes object of length 1')
return [number >> i & 1 for i in range(8)]
def pack_bits(self, bits):
return self.pack_int(sum(bits[i] << i for i in range(8)), 1)
def unpack_int(self, b, endian=None, signed=False):
return int.from_bytes(b, self._get_endian(endian), signed=signed)
def pack_int(self, number, size, endian=None, signed=False):
return number.to_bytes(size, self._get_endian(endian), signed=signed)
def _get_format(self, size, endian=None):
if size not in _float_formats:
raise ValueError("float size '{}' not supported".format(size))
if endian not in _endians:
raise ValueError("endian '{}' is not recognized".format(endian))
return _endians[endian] + _float_formats[size]
def unpack_float(self, b, size, endian=None):
return struct.unpack(self._get_format(size, self._get_endian(endian)), b)[0]
def pack_float(self, number, size, endian=None):
return struct.pack(self._get_format(size, self._get_endian(endian)), number)
def unpack_str(self, b):
return b.decode(self.encoding, errors=self.errors)
def pack_str(self, string):
return string.encode(self.encoding, errors=self.errors)
def unpack_cstr(self, b, start=0):
end = b.find(b'\x00', start)
if end == -1:
raise ValueError('null termination not found')
string = self.unpack_str(b[start:end])
return string, end - start + 1
def pack_cstr(self, string):
return self.pack_str(string) + b'\x00'
def unpack_pstr(self, b, size, endian=None, start=0):
length = self.unpack_int(b[start:start + size], endian)
string = self.unpack_str(b[start + size:start + size + length])
return string, size + length
def pack_pstr(self, string, size, endian=None):
b = self.pack_str(string)
return self.pack_int(len(b), size, endian) + b
def unpack_7bint(self, b, start=0):
number = 0
i = 0
byte = b[start]
while byte > 127:
number += (byte & 0b01111111) << (7 * i)
i += 1
byte = b[start + i]
number += byte << (7 * i)
return number, i + 1
def pack_7bint(self, number):
b = b''
while number > 127:
b += self.pack_int(number & 0b01111111 | 0b10000000, 1)
number >>= 7
b += self.pack_int(number, 1)
return b
class StructIO(io.BytesIO):
def __init__(self, b=b'', endian='little', encoding='utf-8', errors='ignore'):
super().__init__(b)
self.endian = endian
self.encoding = encoding
self.errors = errors
@property
def buffer(self):
return self.getvalue()
@buffer.setter
def buffer(self, b):
position = self.tell()
self.seek(0)
self.write(b)
self.truncate()
if position < len(b):
self.seek(position)
def __len__(self):
position = self.tell()
self.seek(0, 2)
length = self.tell()
self.seek(position)
return length
def __eq__(self, other):
return self.getvalue() == other.getvalue()
def _get_endian(self, endian):
if endian is None:
return self.endian
else:
return endian
def copy(self):
return StructIO(self.getvalue(), self.endian, self.encoding, self.errors)
def clear(self):
self.seek(0)
self.truncate()
def find(self, bytes_sequence, n=1):
start = self.tell()
content = self.getvalue()
location = content.find(bytes_sequence, start)
for i in range(1, n):
location = content.find(bytes_sequence, location + 1)
if location == -1:
break
return location
def index(self, bytes_sequence, n=1):
location = self.find(bytes_sequence, n)
if location == -1:
raise ValueError('{} not found'.format(bytes_sequence))
return location
def read_bool(self):
return self.read(1) != b'\x00'
def write_bool(self, boolean):
if boolean:
return self.write(b'\x01')
else:
return self.write(b'\x00')
def read_bits(self):
number = self.read_int(1)
return [number >> i & 1 for i in range(8)]
def write_bits(self, bits):
return self.write_int(sum(bits[i] << i for i in range(8)), 1)
def read_int(self, size, endian=None, signed=False):
return int.from_bytes(self.read(size), self._get_endian(endian), signed=signed)
def write_int(self, number, size, endian=None, signed=False):
return self.write(number.to_bytes(size, self._get_endian(endian), signed=signed))
def _get_format(self, size, endian=None):
if size not in _float_formats:
raise ValueError("float size '{}' not supported".format(size))
if endian not in _endians:
raise ValueError("endian '{}' is not recognized".format(endian))
return _endians[endian] + _float_formats[size]
def read_float(self, size, endian=None):
return struct.unpack(self._get_format(size, self._get_endian(endian)), self.read(size))[0]
def write_float(self, number, size, endian=None):
return self.write(struct.pack(self._get_format(size, self._get_endian(endian)), number))
def read_str(self, length):
return self.read(length).decode(self.encoding, errors=self.errors)
def write_str(self, string):
return self.write(string.encode(self.encoding, errors=self.errors))
def read_cstr(self):
start = self.tell()
end = self.find(b'\x00')
if end == -1:
raise ValueError('null termination not found')
string = self.read_str(end - start)
self.seek(1, 1)
return string
def write_cstr(self, string):
return self.write_str(string) + self.write(b'\x00')
def skip_cstr(self):
end = self.find(b'\x00')
if end == -1:
raise ValueError('null termination not found')
return self.seek(end + 1)
def read_pstr(self, size, endian=None):
return self.read_str(self.read_int(size, endian))
def write_pstr(self, string, size, endian=None):
b = string.encode(self.encoding, errors=self.errors)
return self.write_int(len(b), size, endian) + self.write(b)
def skip_pstr(self, size, endian=None):
return self.seek(self.read_int(size, endian), 1)
def read_7bint(self):
number = 0
i = 0
byte = self.read_int(1)
while byte > 127:
number += (byte & 0b01111111) << (7 * i)
i += 1
byte = self.read_int(1)
number += byte << (7 * i)
return number
def write_7bint(self, number):
length = 0
while number > 127:
length += self.write_int(number & 0b01111111 | 0b10000000, 1)
number >>= 7
length += self.write_int(number, 1)
return length
def skip_7bint(self):
while self.read_int(1) > 127:
pass
return self.tell()