| 69 | (varname, repr(value), repr(varmin), repr(varmax))) |
| 70 | |
| 71 | class Struct: |
| 72 | def size(self): |
| 73 | return struct.calcsize(self._format_) |
| 74 | |
| 75 | def pack(self): |
| 76 | args = [] |
| 77 | for variable, fmt, length in self._args_: |
| 78 | value = self.__dict__[variable] |
| 79 | if isinstance(value, list): |
| 80 | if length != None and length != len(value): |
| 81 | raise ValueError('Variable "%s" length %u does not match %u' % |
| 82 | (variable, len(value), length)) |
| 83 | for index, item in enumerate(value): |
| 84 | check_range(variable + '[' + repr(index) + ']', fmt, item) |
| 85 | args.append(item) |
| 86 | else: |
| 87 | if (fmt == "s"): |
| 88 | value = ensure_string(value) |
| 89 | check_range(variable, fmt, value) |
| 90 | args.append(value) |
| 91 | return struct.pack(self._format_, *args) |
| 92 | |
| 93 | def unpack(self, data): |
| 94 | values = struct.unpack(self._format_, data) |
| 95 | i = 0 |
| 96 | for variable, fmt, length in self._args_: |
| 97 | self.__dict__[variable] = values[i] |
| 98 | i += 1 |
| 99 | |
| 100 | def create(definition): |
| 101 | "Create structure object" |