[8c25a4a] | 1 | #
|
---|
| 2 | # Copyright (c) 2008 Martin Decky
|
---|
[cc1a727] | 3 | # Copyright (c) 2011 Martin Sucha
|
---|
[8c25a4a] | 4 | # All rights reserved.
|
---|
| 5 | #
|
---|
| 6 | # Redistribution and use in source and binary forms, with or without
|
---|
| 7 | # modification, are permitted provided that the following conditions
|
---|
| 8 | # are met:
|
---|
| 9 | #
|
---|
| 10 | # - Redistributions of source code must retain the above copyright
|
---|
| 11 | # notice, this list of conditions and the following disclaimer.
|
---|
| 12 | # - Redistributions in binary form must reproduce the above copyright
|
---|
| 13 | # notice, this list of conditions and the following disclaimer in the
|
---|
| 14 | # documentation and/or other materials provided with the distribution.
|
---|
| 15 | # - The name of the author may not be used to endorse or promote products
|
---|
| 16 | # derived from this software without specific prior written permission.
|
---|
| 17 | #
|
---|
| 18 | # THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
|
---|
| 19 | # IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
|
---|
| 20 | # OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
---|
| 21 | # IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
|
---|
| 22 | # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
---|
| 23 | # NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
---|
| 24 | # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
---|
| 25 | # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
---|
| 26 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
|
---|
| 27 | # THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
---|
| 28 | #
|
---|
| 29 | """
|
---|
[0516fd7] | 30 | Convert descriptive structure definitions to structure object
|
---|
[8c25a4a] | 31 | """
|
---|
| 32 |
|
---|
| 33 | import struct
|
---|
[6582b36] | 34 | import sys
|
---|
[cc1a727] | 35 | import types
|
---|
| 36 |
|
---|
[67435b1] | 37 | # Handle long integer conversions nicely in both Python 2 and Python 3
|
---|
[6582b36] | 38 | integer_types = (int, long) if sys.version < '3' else (int,)
|
---|
| 39 |
|
---|
[67435b1] | 40 | # Ensure that 's' format for struct receives correct data type depending
|
---|
| 41 | # on Python version (needed due to different way to encode into bytes)
|
---|
| 42 | ensure_string = \
|
---|
| 43 | (lambda value: value if type(value) is str else bytes(value)) \
|
---|
| 44 | if sys.version < '3' else \
|
---|
| 45 | (lambda value: bytes(value, 'ascii') if type(value) is str else value)
|
---|
| 46 |
|
---|
[cc1a727] | 47 | ranges = {
|
---|
[6582b36] | 48 | 'B': (integer_types, 0x00, 0xff),
|
---|
| 49 | 'H': (integer_types, 0x0000, 0xffff),
|
---|
| 50 | 'L': (integer_types, 0x00000000, 0xffffffff),
|
---|
| 51 | 'Q': (integer_types, 0x0000000000000000, 0xffffffffffffffff),
|
---|
| 52 | 'b': (integer_types, -0x80, 0x7f),
|
---|
| 53 | 'h': (integer_types, -0x8000, 0x7fff),
|
---|
| 54 | 'l': (integer_types, -0x80000000, 0x7fffffff) ,
|
---|
| 55 | 'q': (integer_types, -0x8000000000000000, 0x7fffffffffffffff),
|
---|
[cc1a727] | 56 | }
|
---|
| 57 |
|
---|
| 58 | def check_range(varname, fmt, value):
|
---|
| 59 | if value == None:
|
---|
| 60 | raise ValueError('Variable "%s" not set' % varname)
|
---|
| 61 | if not fmt in ranges:
|
---|
| 62 | return
|
---|
| 63 | vartype, varmin, varmax = ranges[fmt]
|
---|
| 64 | if not isinstance(value, vartype):
|
---|
| 65 | raise ValueError('Variable "%s" is %s but should be %s' %
|
---|
| 66 | (varname, str(type(value)), str(vartype)))
|
---|
| 67 | if value < varmin or value > varmax:
|
---|
| 68 | raise ValueError('Variable "%s" value %s out of range %s..%s' %
|
---|
| 69 | (varname, repr(value), repr(varmin), repr(varmax)))
|
---|
[8c25a4a] | 70 |
|
---|
[0516fd7] | 71 | class Struct:
|
---|
| 72 | def size(self):
|
---|
| 73 | return struct.calcsize(self._format_)
|
---|
| 74 |
|
---|
| 75 | def pack(self):
|
---|
[5749372] | 76 | args = []
|
---|
[cc1a727] | 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)
|
---|
[5749372] | 85 | args.append(item)
|
---|
| 86 | else:
|
---|
[67435b1] | 87 | if (fmt == "s"):
|
---|
| 88 | value = ensure_string(value)
|
---|
[cc1a727] | 89 | check_range(variable, fmt, value)
|
---|
| 90 | args.append(value)
|
---|
[5749372] | 91 | return struct.pack(self._format_, *args)
|
---|
[cc1a727] | 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
|
---|
[0516fd7] | 99 |
|
---|
| 100 | def create(definition):
|
---|
| 101 | "Create structure object"
|
---|
[8c25a4a] | 102 |
|
---|
| 103 | tokens = definition.split(None)
|
---|
| 104 |
|
---|
| 105 | # Initial byte order tag
|
---|
[0516fd7] | 106 | format = {
|
---|
[8c25a4a] | 107 | "little:": lambda: "<",
|
---|
| 108 | "big:": lambda: ">",
|
---|
| 109 | "network:": lambda: "!"
|
---|
| 110 | }[tokens[0]]()
|
---|
[0516fd7] | 111 | inst = Struct()
|
---|
[5749372] | 112 | args = []
|
---|
[b3105ff6] | 113 |
|
---|
[8c25a4a] | 114 | # Member tags
|
---|
[b3105ff6] | 115 | comment = False
|
---|
[8f2a852] | 116 | variable = None
|
---|
[8c25a4a] | 117 | for token in tokens[1:]:
|
---|
[b3105ff6] | 118 | if (comment):
|
---|
| 119 | if (token == "*/"):
|
---|
| 120 | comment = False
|
---|
| 121 | continue
|
---|
| 122 |
|
---|
| 123 | if (token == "/*"):
|
---|
| 124 | comment = True
|
---|
[8f2a852] | 125 | continue
|
---|
| 126 |
|
---|
| 127 | if (variable != None):
|
---|
| 128 | subtokens = token.split("[")
|
---|
| 129 |
|
---|
[cc1a727] | 130 | length = None
|
---|
[8f2a852] | 131 | if (len(subtokens) > 1):
|
---|
[cc1a727] | 132 | length = int(subtokens[1].split("]")[0])
|
---|
| 133 | format += "%d" % length
|
---|
[8f2a852] | 134 |
|
---|
| 135 | format += variable
|
---|
| 136 |
|
---|
| 137 | inst.__dict__[subtokens[0]] = None
|
---|
[cc1a727] | 138 | args.append((subtokens[0], variable, length))
|
---|
[8f2a852] | 139 |
|
---|
| 140 | variable = None
|
---|
| 141 | continue
|
---|
| 142 |
|
---|
| 143 | if (token[0:8] == "padding["):
|
---|
[0516fd7] | 144 | size = token[8:].split("]")[0]
|
---|
| 145 | format += "%dx" % int(size)
|
---|
[8f2a852] | 146 | continue
|
---|
| 147 |
|
---|
| 148 | variable = {
|
---|
| 149 | "char": lambda: "s",
|
---|
| 150 | "uint8_t": lambda: "B",
|
---|
| 151 | "uint16_t": lambda: "H",
|
---|
| 152 | "uint32_t": lambda: "L",
|
---|
| 153 | "uint64_t": lambda: "Q",
|
---|
| 154 |
|
---|
| 155 | "int8_t": lambda: "b",
|
---|
| 156 | "int16_t": lambda: "h",
|
---|
| 157 | "int32_t": lambda: "l",
|
---|
| 158 | "int64_t": lambda: "q"
|
---|
| 159 | }[token]()
|
---|
[8c25a4a] | 160 |
|
---|
[0516fd7] | 161 | inst.__dict__['_format_'] = format
|
---|
[5749372] | 162 | inst.__dict__['_args_'] = args
|
---|
[0516fd7] | 163 | return inst
|
---|