2 ## This file is part of the libsigrokdecode project.
4 ## Copyright (C) 2012-2020 Uwe Hermann <uwe@hermann-uwe.de>
6 ## This program is free software; you can redistribute it and/or modify
7 ## it under the terms of the GNU General Public License as published by
8 ## the Free Software Foundation; either version 2 of the License, or
9 ## (at your option) any later version.
11 ## This program is distributed in the hope that it will be useful,
12 ## but WITHOUT ANY WARRANTY; without even the implied warranty of
13 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 ## GNU General Public License for more details.
16 ## You should have received a copy of the GNU General Public License
17 ## along with this program; if not, see <http://www.gnu.org/licenses/>.
20 from enum import Enum, IntEnum, unique
21 from itertools import chain
24 # Return the specified BCD number (max. 8 bits) as integer.
26 return (b & 0x0f) + ((b >> 4) * 10)
29 return int('0b' + s, 2)
32 return sum([b << i for i, b in enumerate(bits)])
34 def bitunpack(num, minbits=0):
36 while num or minbits > 0:
43 class SrdStrEnum(Enum):
45 def from_list(cls, name, l):
46 # Keys are limited/converted to [A-Z0-9_], values can be any string.
47 items = [(re.sub('[^A-Z0-9_]', '_', l[i]), l[i]) for i in range(len(l))]
48 return cls(name, items)
51 def from_str(cls, name, s):
52 return cls.from_list(name, s.split())
55 class SrdIntEnum(IntEnum):
58 return tuple([a.value for a in cls if a.name.startswith(p)])
61 def prefixes(cls, prefix_list):
62 if isinstance(prefix_list, str):
63 prefix_list = prefix_list.split()
64 return tuple(chain(*[cls._prefix(p) for p in prefix_list]))
68 return tuple([a.value for a in cls if a.name.endswith(s)])
71 def suffixes(cls, suffix_list):
72 if isinstance(suffix_list, str):
73 suffix_list = suffix_list.split()
74 return tuple(chain(*[cls._suffix(s) for s in suffix_list]))
77 def from_list(cls, name, l):
78 # Manually construct (Python 3.4 is missing the 'start' argument).
79 # Python defaults to start=1, but we want start=0.
80 return cls(name, [(l[i], i) for i in range(len(l))])
83 def from_str(cls, name, s):
84 return cls.from_list(name, s.split())