| 1 | #
|
|---|
| 2 | # Copyright (c) 2008 Martin Decky
|
|---|
| 3 | # Copyright (c) 2011 Martin Sucha
|
|---|
| 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 | """
|
|---|
| 30 | Convert descriptive structure definitions to structure object
|
|---|
| 31 | """
|
|---|
| 32 |
|
|---|
| 33 | import struct
|
|---|
| 34 | import types
|
|---|
| 35 |
|
|---|
| 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 | return
|
|---|
| 52 | 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 |
|
|---|
| 60 | class Struct:
|
|---|
| 61 | def size(self):
|
|---|
| 62 | return struct.calcsize(self._format_)
|
|---|
| 63 |
|
|---|
| 64 | def pack(self):
|
|---|
| 65 | 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)
|
|---|
| 74 | args.append(item)
|
|---|
| 75 | else:
|
|---|
| 76 | check_range(variable, fmt, value)
|
|---|
| 77 | args.append(value)
|
|---|
| 78 | return struct.pack(self._format_, *args)
|
|---|
| 79 |
|
|---|
| 80 | def unpack(self, data):
|
|---|
| 81 | values = struct.unpack(self._format_, data)
|
|---|
| 82 | i = 0
|
|---|
| 83 | for variable, fmt, length in self._args_:
|
|---|
| 84 | self.__dict__[variable] = values[i]
|
|---|
| 85 | i += 1
|
|---|
| 86 |
|
|---|
| 87 | def create(definition):
|
|---|
| 88 | "Create structure object"
|
|---|
| 89 |
|
|---|
| 90 | tokens = definition.split(None)
|
|---|
| 91 |
|
|---|
| 92 | # Initial byte order tag
|
|---|
| 93 | format = {
|
|---|
| 94 | "little:": lambda: "<",
|
|---|
| 95 | "big:": lambda: ">",
|
|---|
| 96 | "network:": lambda: "!"
|
|---|
| 97 | }[tokens[0]]()
|
|---|
| 98 | inst = Struct()
|
|---|
| 99 | args = []
|
|---|
| 100 |
|
|---|
| 101 | # Member tags
|
|---|
| 102 | comment = False
|
|---|
| 103 | variable = None
|
|---|
| 104 | for token in tokens[1:]:
|
|---|
| 105 | if (comment):
|
|---|
| 106 | if (token == "*/"):
|
|---|
| 107 | comment = False
|
|---|
| 108 | continue
|
|---|
| 109 |
|
|---|
| 110 | if (token == "/*"):
|
|---|
| 111 | comment = True
|
|---|
| 112 | continue
|
|---|
| 113 |
|
|---|
| 114 | if (variable != None):
|
|---|
| 115 | subtokens = token.split("[")
|
|---|
| 116 |
|
|---|
| 117 | length = None
|
|---|
| 118 | if (len(subtokens) > 1):
|
|---|
| 119 | length = int(subtokens[1].split("]")[0])
|
|---|
| 120 | format += "%d" % length
|
|---|
| 121 |
|
|---|
| 122 | format += variable
|
|---|
| 123 |
|
|---|
| 124 | inst.__dict__[subtokens[0]] = None
|
|---|
| 125 | args.append((subtokens[0], variable, length))
|
|---|
| 126 |
|
|---|
| 127 | variable = None
|
|---|
| 128 | continue
|
|---|
| 129 |
|
|---|
| 130 | if (token[0:8] == "padding["):
|
|---|
| 131 | size = token[8:].split("]")[0]
|
|---|
| 132 | format += "%dx" % int(size)
|
|---|
| 133 | continue
|
|---|
| 134 |
|
|---|
| 135 | variable = {
|
|---|
| 136 | "char": lambda: "s",
|
|---|
| 137 | "uint8_t": lambda: "B",
|
|---|
| 138 | "uint16_t": lambda: "H",
|
|---|
| 139 | "uint32_t": lambda: "L",
|
|---|
| 140 | "uint64_t": lambda: "Q",
|
|---|
| 141 |
|
|---|
| 142 | "int8_t": lambda: "b",
|
|---|
| 143 | "int16_t": lambda: "h",
|
|---|
| 144 | "int32_t": lambda: "l",
|
|---|
| 145 | "int64_t": lambda: "q"
|
|---|
| 146 | }[token]()
|
|---|
| 147 |
|
|---|
| 148 | inst.__dict__['_format_'] = format
|
|---|
| 149 | inst.__dict__['_args_'] = args
|
|---|
| 150 | return inst
|
|---|