]>
Commit | Line | Data |
---|---|---|
769ed325 UH |
1 | ## |
2 | ## This file is part of the libsigrokdecode project. | |
3 | ## | |
4 | ## Copyright (C) 2012-2014 Uwe Hermann <uwe@hermann-uwe.de> | |
5 | ## | |
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. | |
10 | ## | |
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. | |
15 | ## | |
16 | ## You should have received a copy of the GNU General Public License | |
4539e9ca | 17 | ## along with this program; if not, see <http://www.gnu.org/licenses/>. |
769ed325 UH |
18 | ## |
19 | ||
fe89c3b4 UH |
20 | from enum import IntEnum, unique |
21 | from itertools import chain | |
22 | ||
769ed325 UH |
23 | # Return the specified BCD number (max. 8 bits) as integer. |
24 | def bcd2int(b): | |
25 | return (b & 0x0f) + ((b >> 4) * 10) | |
c413347e | 26 | |
392a5d1e UH |
27 | def bin2int(s: str): |
28 | return int('0b' + s, 2) | |
29 | ||
c413347e | 30 | def bitpack(bits): |
c7172e5f | 31 | return sum([b << i for i, b in enumerate(bits)]) |
c413347e UH |
32 | |
33 | def bitunpack(num, minbits=0): | |
34 | res = [] | |
35 | while num or minbits > 0: | |
36 | res.append(num & 1) | |
37 | num >>= 1 | |
38 | minbits -= 1 | |
39 | return tuple(res) | |
fe89c3b4 UH |
40 | |
41 | @unique | |
42 | class SrdIntEnum(IntEnum): | |
43 | @classmethod | |
44 | def _prefix(cls, p): | |
45 | return tuple([a.value for a in cls if a.name.startswith(p)]) | |
46 | ||
47 | @classmethod | |
48 | def prefixes(cls, prefix_list): | |
49 | if isinstance(prefix_list, str): | |
50 | prefix_list = prefix_list.split() | |
51 | return tuple(chain(*[cls._prefix(p) for p in prefix_list])) | |
52 | ||
53 | @classmethod | |
54 | def _suffix(cls, s): | |
55 | return tuple([a.value for a in cls if a.name.endswith(s)]) | |
56 | ||
57 | @classmethod | |
58 | def suffixes(cls, suffix_list): | |
59 | if isinstance(suffix_list, str): | |
60 | suffix_list = suffix_list.split() | |
61 | return tuple(chain(*[cls._suffix(s) for s in suffix_list])) | |
62 | ||
63 | @classmethod | |
64 | def from_list(cls, name, l): | |
65 | # Manually construct (Python 3.4 is missing the 'start' argument). | |
66 | # Python defaults to start=1, but we want start=0. | |
67 | return cls(name, [(l[i], i) for i in range(len(l))]) | |
68 | ||
69 | @classmethod | |
70 | def from_str(cls, name, s): | |
71 | return cls.from_list(name, s.split()) |