source: mainline/tools/xstruct.py@ 093e956

lfn serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since 093e956 was a35b458, checked in by Jiří Zárevúcky <zarevucky.jiri@…>, 7 years ago

style: Remove trailing whitespace on _all_ lines, including empty ones, for particular file types.

Command used: tools/srepl '\s\+$' '' -- *.c *.h *.py *.sh *.s *.S *.ag

Currently, whitespace on empty lines is very inconsistent.
There are two basic choices: Either remove the whitespace, or keep empty lines
indented to the level of surrounding code. The former is AFAICT more common,
and also much easier to do automatically.

Alternatively, we could write script for automatic indentation, and use that
instead. However, if such a script exists, it's possible to use the indented
style locally, by having the editor apply relevant conversions on load/save,
without affecting remote repository. IMO, it makes more sense to adopt
the simpler rule.

  • Property mode set to 100644
File size: 4.9 KB
RevLine 
[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]30Convert descriptive structure definitions to structure object
[8c25a4a]31"""
32
33import struct
[6582b36]34import sys
[cc1a727]35import types
36
[67435b1]37# Handle long integer conversions nicely in both Python 2 and Python 3
[6582b36]38integer_types = (int, long) if sys.version < '3' else (int,)
39
[67435b1]40# Ensure that 's' format for struct receives correct data type depending
[1b20da0]41# on Python version (needed due to different way to encode into bytes)
[67435b1]42ensure_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]47ranges = {
[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
58def 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:
[1b20da0]68 raise ValueError('Variable "%s" value %s out of range %s..%s' %
[cc1a727]69 (varname, repr(value), repr(varmin), repr(varmax)))
[8c25a4a]70
[0516fd7]71class Struct:
72 def size(self):
73 return struct.calcsize(self._format_)
[a35b458]74
[0516fd7]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)
[1b20da0]90 args.append(value)
[5749372]91 return struct.pack(self._format_, *args)
[a35b458]92
[cc1a727]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
100def create(definition):
101 "Create structure object"
[a35b458]102
[8c25a4a]103 tokens = definition.split(None)
[a35b458]104
[8c25a4a]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 = []
[a35b458]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
[a35b458]122
[b3105ff6]123 if (token == "/*"):
124 comment = True
[8f2a852]125 continue
[a35b458]126
[8f2a852]127 if (variable != None):
128 subtokens = token.split("[")
[a35b458]129
[cc1a727]130 length = None
[8f2a852]131 if (len(subtokens) > 1):
[cc1a727]132 length = int(subtokens[1].split("]")[0])
133 format += "%d" % length
[a35b458]134
[8f2a852]135 format += variable
[a35b458]136
[8f2a852]137 inst.__dict__[subtokens[0]] = None
[cc1a727]138 args.append((subtokens[0], variable, length))
[a35b458]139
[8f2a852]140 variable = None
141 continue
[a35b458]142
[8f2a852]143 if (token[0:8] == "padding["):
[0516fd7]144 size = token[8:].split("]")[0]
145 format += "%dx" % int(size)
[8f2a852]146 continue
[a35b458]147
[8f2a852]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",
[a35b458]154
[8f2a852]155 "int8_t": lambda: "b",
156 "int16_t": lambda: "h",
157 "int32_t": lambda: "l",
158 "int64_t": lambda: "q"
159 }[token]()
[a35b458]160
[0516fd7]161 inst.__dict__['_format_'] = format
[5749372]162 inst.__dict__['_args_'] = args
[0516fd7]163 return inst
Note: See TracBrowser for help on using the repository browser.