Completed
Push — master ( 09e12b...15e96c )
by Aaron
07:32
created

BitField.unpack()   A

Complexity

Conditions 3

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
c 1
b 0
f 0
dl 0
loc 5
rs 9.4285
1
import functools
2
3
4
class BitField(object):
5
    def __init__(self, enum):
6
        if not all(isinstance(member.value, int) for member in enum):
7
            msg = 'Enum {} members must have integer values'.format(repr(enum))
8
            raise TypeError(msg)
9
        self.enum = enum
10
11
    def __repr__(self):
12
        return 'BitField({})'.format(self.enum)
13
14
    def __str__(self):
15
        return 'BitField({})'.format(self.enum)
16
17
    def pack(self, arg):
18
        """
19
        Take a list (or single value) and bitwise-or all the values together
20
        """
21
        # Handle a variety of inputs: list or single, enum or raw
22
        if isinstance(arg, list):
23
            values = [self.enum(value) for value in arg]
24
        else:
25
            values = [self.enum(arg)]
26
27
        # left side is an integer, right side is an enum value
28
        return functools.reduce(lambda x, y: x | y.value, values, 0)
29
30
    def unpack(self, val):
31
        """
32
        Take a single number and split it out into all values that are present
33
        """
34
        return frozenset(e for e in self.enum if e.value & val)
35
36
    def make(self, arg):
37
        """
38
        Take an input list and return a frozenset
39
40
        useful for testing
41
        """
42
        # Handle the same inputs as the pack function
43
        if isinstance(arg, list):
44
            values = [self.enum(value) for value in arg]
45
        else:
46
            values = [self.enum(arg)]
47
48
        # return this list as a frozenset
49
        return frozenset(values)
50