source: mainline/tools/xstruct.py@ 7896f23

serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since 7896f23 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
Line 
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"""
30Convert descriptive structure definitions to structure object
31"""
32
33import struct
34import sys
35import types
36
37# Handle long integer conversions nicely in both Python 2 and Python 3
38integer_types = (int, long) if sys.version < '3' else (int,)
39
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)
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
47ranges = {
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),
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:
68 raise ValueError('Variable "%s" value %s out of range %s..%s' %
69 (varname, repr(value), repr(varmin), repr(varmax)))
70
71class 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
100def create(definition):
101 "Create structure object"
102
103 tokens = definition.split(None)
104
105 # Initial byte order tag
106 format = {
107 "little:": lambda: "<",
108 "big:": lambda: ">",
109 "network:": lambda: "!"
110 }[tokens[0]]()
111 inst = Struct()
112 args = []
113
114 # Member tags
115 comment = False
116 variable = None
117 for token in tokens[1:]:
118 if (comment):
119 if (token == "*/"):
120 comment = False
121 continue
122
123 if (token == "/*"):
124 comment = True
125 continue
126
127 if (variable != None):
128 subtokens = token.split("[")
129
130 length = None
131 if (len(subtokens) > 1):
132 length = int(subtokens[1].split("]")[0])
133 format += "%d" % length
134
135 format += variable
136
137 inst.__dict__[subtokens[0]] = None
138 args.append((subtokens[0], variable, length))
139
140 variable = None
141 continue
142
143 if (token[0:8] == "padding["):
144 size = token[8:].split("]")[0]
145 format += "%dx" % int(size)
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]()
160
161 inst.__dict__['_format_'] = format
162 inst.__dict__['_args_'] = args
163 return inst
Note: See TracBrowser for help on using the repository browser.