Changes in tools/xstruct.py [cc1a727:5749372] in mainline
- File:
-
- 1 edited
Legend:
- Unmodified
- Added
- Removed
-
tools/xstruct.py
rcc1a727 r5749372 1 1 # 2 2 # Copyright (c) 2008 Martin Decky 3 # Copyright (c) 2011 Martin Sucha4 3 # All rights reserved. 5 4 # … … 32 31 33 32 import struct 34 import types35 36 ranges = {37 'B': ((int, long), 0x00, 0xff),38 'H': ((int, long), 0x0000, 0xffff),39 'L': ((int, long), 0x00000000, 0xffffffff),40 'Q': ((int, long), 0x0000000000000000, 0xffffffffffffffff),41 'b': ((int, long), -0x80, 0x7f),42 'h': ((int, long), -0x8000, 0x7fff),43 'l': ((int, long), -0x80000000, 0x7fffffff) ,44 'q': ((int, long), -0x8000000000000000, 0x7fffffffffffffff),45 }46 47 def check_range(varname, fmt, value):48 if value == None:49 raise ValueError('Variable "%s" not set' % varname)50 if not fmt in ranges:51 return52 vartype, varmin, varmax = ranges[fmt]53 if not isinstance(value, vartype):54 raise ValueError('Variable "%s" is %s but should be %s' %55 (varname, str(type(value)), str(vartype)))56 if value < varmin or value > varmax:57 raise ValueError('Variable "%s" value %s out of range %s..%s' %58 (varname, repr(value), repr(varmin), repr(varmax)))59 33 60 34 class Struct: … … 64 38 def pack(self): 65 39 args = [] 66 for variable, fmt, length in self._args_: 67 value = self.__dict__[variable] 68 if isinstance(value, list): 69 if length != None and length != len(value): 70 raise ValueError('Variable "%s" length %u does not match %u' % 71 (variable, len(value), length)) 72 for index, item in enumerate(value): 73 check_range(variable + '[' + repr(index) + ']', fmt, item) 40 for variable in self._args_: 41 if (isinstance(self.__dict__[variable], list)): 42 for item in self.__dict__[variable]: 74 43 args.append(item) 75 44 else: 76 check_range(variable, fmt, value)77 args.append(value)45 args.append(self.__dict__[variable]) 46 78 47 return struct.pack(self._format_, *args) 79 80 def unpack(self, data):81 values = struct.unpack(self._format_, data)82 i = 083 for variable, fmt, length in self._args_:84 self.__dict__[variable] = values[i]85 i += 186 48 87 49 def create(definition): … … 115 77 subtokens = token.split("[") 116 78 117 length = None118 79 if (len(subtokens) > 1): 119 length = int(subtokens[1].split("]")[0]) 120 format += "%d" % length 80 format += "%d" % int(subtokens[1].split("]")[0]) 121 81 122 82 format += variable 123 83 124 84 inst.__dict__[subtokens[0]] = None 125 args.append( (subtokens[0], variable, length))85 args.append(subtokens[0]) 126 86 127 87 variable = None
Note:
See TracChangeset
for help on using the changeset viewer.