MCPcopy Create free account
hub / github.com/ARMmbed/DAPLink / Struct

Class Struct

test/tests/usb_msd.py:236–279  ·  view source on GitHub ↗

Base class for a C structure

Source from the content-addressed store, hash-verified

234
235
236class Struct(object):
237 """Base class for a C structure"""
238
239 def __init__(self, name, structure, data):
240 field_list = [field[0] for field in structure]
241 fmt_list = [field[1] for field in structure]
242 format_str = "<" + "".join(fmt_list)
243 struct_size = struct.calcsize(format_str)
244 value_list = struct.unpack(format_str, data[:struct_size])
245 value_dict = {}
246 for name, value in zip(field_list, value_list):
247 value_dict[name] = value
248 self.name = name
249 self.format_str = format_str
250 self.field_list = field_list
251 self.fmt_dict = {k: fmt_list[i] for i, k in enumerate(field_list)}
252 self.value_dict = value_dict
253 self.size = struct_size
254
255 def __getitem__(self, key):
256 return self.value_dict[key]
257
258 def __setitem__(self, key, value):
259 self.value_dict[key] = value
260
261 def __str__(self):
262 desc = ""
263 desc += self.name + ":" + os.linesep
264 for field in self.field_list:
265 value = self.value_dict[field]
266 if isinstance(value, bytes):
267 value = list(bytearray(value))
268 desc += (" %s=%s" + os.linesep) % (field, value)
269 return desc
270
271 def pack(self):
272 """Return a byte representation of this structure"""
273 value_list = []
274 for field in self.field_list:
275 value = self.value_dict[field]
276 if self.fmt_dict[field].endswith('s'):
277 value = six.ensure_binary(value)
278 value_list.append(value)
279 return struct.pack(self.format_str, *value_list)
280
281
282class MBR(Struct):

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected