-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinstruct.py
More file actions
209 lines (158 loc) · 6.69 KB
/
binstruct.py
File metadata and controls
209 lines (158 loc) · 6.69 KB
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
# binstruct is a Python library for reading writing binary data sources via
# structures
# Copyright (C) 2014 Silvan Wegmann
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
def big_endian(original_class):
"""The big_endian function is a class decorator for classes derived from
:class:`.StructTemplate`. By default a StructTemplate class interpretes its
fields in little endian format. Using this decorator you change this
behavior.
:param original_class: The class you want to turn into a big endian
structure."""
orig_init = original_class.__init__
def __init__(self, *args, **kwargs):
orig_init(self, *args, **kwargs)
self.endian = "big"
original_class.__init__ = __init__
return original_class
class Field(object):
def __init__(self, start, size):
self.start = start
self.size = size
class NumericField(Field):
def __get__(self, instance, owner):
start = instance.start_offset + self.start
values = instance.array[start:start+self.size]
powers = range(len(values))
powers = map(lambda x: 256**x, powers)
if instance.endian == "big":
powers = reversed(list(powers))
summands = map(int.__mul__, values, powers)
return sum(summands)
def validate_set_value(self, value):
if value >= 2**(self.size*8):
raise ValueError("%u does not fit in this field" % value)
def __set__(self, instance, value):
self.validate_set_value(value)
powers = []
for i in range(self.size):
powers.append(int(value % 256))
value //= 256
if instance.endian == "big":
powers = list(reversed(powers))
powers.extend(self.size*[0])
start = instance.start_offset + self.start
instance.array[start:start+self.size] = powers[0:self.size]
class Int8Field(NumericField):
"""A numeric field representing a signed integer of 8 bits."""
def __init__(self, start):
NumericField.__init__(self, start, 1)
class UInt8Field(NumericField):
"""A numeric field representing an unsigned integer of 8 bits."""
def __init__(self, start):
NumericField.__init__(self, start, 1)
class Int16Field(NumericField):
"""A numeric field representing a signed integer of 16 bits."""
def __init__(self, start):
NumericField.__init__(self, start, 2)
class UInt16Field(NumericField):
"""A numeric field representing an unsigned integer of 16 bits."""
def __init__(self, start):
NumericField.__init__(self, start, 2)
class Int32Field(NumericField):
"""A numeric field representing a signed integer of 32 bits."""
def __init__(self, start):
NumericField.__init__(self, start, 4)
class UInt32Field(NumericField):
"""A numeric field representing an unsigned integer of 32 bits."""
def __init__(self, start):
NumericField.__init__(self, start, 4)
class StringField(Field):
"""A field representing a Python string."""
def __init__(self, start, length):
Field.__init__(self, start, length)
def __get__(self, instance, owner):
start = instance.start_offset + self.start
values = instance.array[start:start+self.size]
return "".join(map(chr, values))
def __set__(self, instance, value):
assert len(value) <= self.size
start = instance.start_offset + self.start
instance.array[start:start+len(value)] = list(map(ord, value))
class Subrange(object):
"""A sub range behaves like a list. It returns and modifies the values of
an other list by selecting a subrange of it."""
def __init__(self, array, start_offset, length):
self.array = array
self.start_offset = start_offset
self.length = length
def __len__(self):
return self.length
def __getitem__(self, key):
if type(key) == slice:
return self.array[self.start_offset + key.start:
self.start_offset + key.stop]
else:
return self.array[self.start_offset + key]
def __setitem__(self, key, value):
if type(key) == slice:
self.array[self.start_offset + key.start:
self.start_offset + key.stop] = value
else:
self.array[self.start_offset + key] = value
class RawField(Field):
"""A special field to access data in a raw byte-wise manner."""
def __init__(self, start, size):
self.start = start
self.size = size
def __get__(self, instance, owner):
return Subrange(instance.array, instance.start_offset + self.start,
self.size)
def __set__(self, instance, value):
raise ValueError("Cannot set a raw type field directly")
class ClassWithLengthMetaType(type):
def __len__(self):
return self.clslength()
ClassWithLength = ClassWithLengthMetaType('ClassWithLength', (object, ), {})
class StructTemplate(ClassWithLength):
"""The main class for defining field accessible structures."""
def __init__(self, array, start_offset):
self.array = array
self.start_offset = start_offset
self.endian = "little"
@classmethod
def clslength(cls):
len = 0
for attr in cls.__dict__.values():
if isinstance(attr, Field):
len = max(len, attr.start + attr.size)
return len
def __len__(self):
"""Returns the length of this structure. """
return len(self.__class__)
def set_endianess(self, endianess):
"""Switch the endianess of the defined structure.
:param endianess: A string giving the new endianess. "little" for
little endian and "big" for big endian.
"""
self.endian = endianess
class NestedStructField(Field):
def __init__(self, start, nested_structure_type):
self.start = start
self.nested_structure_type = nested_structure_type
def __get__(self, instance, owner):
return self.nested_structure_type(instance.array, self.start)
def __set__(self, instance, value):
raise ValueError("Cannot set a nested structure")