Exemplo n.º 1
0
    def parse(
        self, data: typing.Union[typing.AnyStr, typing.Enum]
    ) -> typing.Union[None, typing.Enum]:
        """Parse ``data`` from string.

        Args:
            data: raw data

        Returns:
            The parsed enum data. If ``data`` is *unset*, ``None`` will
            be returned.

        Warns:
            ZeekValueWarning: If ``date`` is not defined in the enum namespace.

        """
        if isinstance(data, enum.Enum):
            return data
        if isinstance(data, str):
            data = data.encode('ascii')

        if data == self.unset_field:
            return None
        data_str = data.decode('ascii')
        item = self.enum_namespaces.get()
        if item is None:
            warnings.warn('unrecognised enum value: %s' % data_str,
                          ZeekValueWarning)
            return enum.IntFlag('<unknown>',
                                [(data_str, enum.auto())])[data_str]
        return item
Exemplo n.º 2
0
    class BlockWrapper:
        Flags = enum.IntFlag('BlockWrapper.Flags', ['INTERNAL', 'USED'])

        def __init__(self, block):
            self.block = block
            self.flags = 0

        def add_flag(self, f):
            self.flags |= f

        def can_merge(self):
            return self.flags == self.Flags.INTERNAL

        def __getattr__(self, n):
            return getattr(self.block, n)
Exemplo n.º 3
0
def convert_fields_to_struct_fields(fields, verbose=False):
    total_bits = 0
    struct_fields = []
    for identifier, op, options in fields:
        s_field = None
        if op == "&":
            bits = len(options)
            description = f"{bits}-bit bitfield"
            f_enum = enum.IntFlag(
                identifier, [(op, 1 << i) for (i, op) in enumerate(options)]
            )
            s_field = identifier / construct.FlagsEnum(
                construct.BitsInteger(bits), f_enum
            )
        elif op == "|":
            bits = math.ceil(math.log2(len(options)))
            description = f"{bits}-bit enum"

            if set(options) == {True, False}:
                s_field = identifier / construct.Flag
            else:
                f_enum = enum.IntEnum(
                    identifier, [(op, 1 << i) for (i, op) in enumerate(options)]
                )
                s_field = identifier / construct.Enum(
                    construct.BitsInteger(bits), f_enum
                )

        struct_fields.append(s_field)
        if verbose:
            print(f"{identifier:15}: {description} ({len(options)} options)")
        assert bits == s_field.sizeof()
        total_bits += bits
    if verbose:
        print(f"Total bits: {total_bits}")
    return (struct_fields, total_bits)
Exemplo n.º 4
0
class EnumConverter(enum.IntFlag):
    """Mixin used for converting enums."""
    @classmethod
    async def convert(cls, ctx, argument):
        try:
            return cls[argument.lower()]
        except KeyError:
            raise commands.BadArgument(
                f'{argument} is not a valid {ctx.__name__}')

    @classmethod
    def random_example(cls, ctx):
        return random.choice(list(cls)).name


ActionFlag = enum.IntFlag('ActionFlag', list(_mod_actions), type=EnumConverter)
_default_flags = (2**len(_mod_actions) - 1) & ~ActionFlag.hackban

for key, value in list(_mod_actions.items()):
    _mod_actions[f'auto-{key}'] = value._replace(repr=f'auto-{value.repr}')


class ModLogError(Exception):
    pass


class ModLogEntry(db.Table, table_name='modlog'):
    id = db.Column(db.Serial, primary_key=True)
    channel_id = db.Column(db.BigInt)
    message_id = db.Column(db.BigInt)
    guild_id = db.Column(db.BigInt)
Exemplo n.º 5
0
class TestFieldPart:
    """Tests class FieldPart"""
    @pytest.mark.parametrize('name', [b'name', 2])
    def test_should_raise_error_when_name_is_not_a_string(self, name):
        with pytest.raises(TypeError):
            FieldPart(name, 2, 2)

    @pytest.mark.parametrize('name', [' hello', 'hello ', 'foo-bar', 'f@o'])
    def test_should_raise_error_when_given_name_is_not_correct(self, name):
        with pytest.raises(ValueError) as exc_info:
            FieldPart(name, 2, 2)

        assert (
            'FieldPart name must starts with a letter and follow standard'
            f' rules for declaring a variable in python but you provided {name}'
        ) == str(exc_info.value)

    @pytest.mark.parametrize('default', [4.5, '4'])
    def test_should_raise_error_when_default_is_not_an_integer(self, default):
        with pytest.raises(TypeError):
            FieldPart('part', default, 3)

    @pytest.mark.parametrize('default', [-1, 8])
    def test_should_raise_error_when_default_is_not_in_valid_boundaries(
            self, default):
        with pytest.raises(ValueError) as exc_info:
            FieldPart('part', default, 3)

        assert f'default must be between 0 and 7 but you provided {default}' == str(
            exc_info.value)

    @pytest.mark.parametrize('size', [4.5, '4'])
    def test_should_raise_error_when_size_is_not_an_integer(self, size):
        with pytest.raises(TypeError):
            FieldPart('part', 2, size)

    @pytest.mark.parametrize('enumeration', [{
        'hello': 2
    }, [(2, 'hello')], {
        2: 3.4
    }])
    def test_should_raise_error_when_enumeration_is_not_correct(
            self, enumeration):
        with pytest.raises(TypeError):
            FieldPart('part', 2, 3, enumeration)

    @pytest.mark.parametrize('enumeration',
                             [{
                                 1: 'MF',
                                 2: 'DF',
                                 4: 'reserved'
                             },
                              enum.IntFlag('Flag', 'MF DF reserved')])
    def test_should_correctly_instantiate_byte_part_object(self, enumeration):
        # these are flags present in IPV4 header :D
        # For more information, you can look here: https://en.wikipedia.org/wiki/IPv4
        part = FieldPart('flags', 0b010, 3, enumeration)

        assert 'flags' == part.name
        assert 2 == part.default == part.value
        assert 3 == part.size
        assert {1: 'MF', 2: 'DF', 4: 'reserved'} == part.enumeration
        assert not part.hex

    # test of hex property

    @pytest.mark.parametrize('value', [1, 'yes'])
    def test_should_raise_error_when_giving_incorrect_value_to_hex_property(
            self, value):
        part = FieldPart('flags', 0b010, 3)
        with pytest.raises(TypeError) as exc_info:
            part.hex = value

        assert f'hex value must be a boolean but you provided {value}' == str(
            exc_info.value)

    def test_should_set_hex_property_when_giving_correct_value(self):
        part = FieldPart('flags', 0b010, 3)
        part.hex = True
        assert part.hex

    # test of value property

    @pytest.mark.parametrize('value', [b'value', 4.5])
    def test_should_raise_error_when_given_value_is_not_of_correct_type(
            self, value):
        part = FieldPart('banana', 2, 3)
        with pytest.raises(TypeError) as exc_info:
            part.value = value

        assert f'{part.name} value must be a positive integer but you provided {value}' == str(
            exc_info.value)

    @pytest.mark.parametrize('value', [-1, 8])
    def test_should_raise_error_when_value_is_not_valid_boundaries(
            self, value):
        part = FieldPart('banana', 2, 3)
        with pytest.raises(ValueError) as exc_info:
            part.value = value

        assert f'{part.name} value must be between 0 and 7 but you provided {value}' == str(
            exc_info.value)

    def test_should_set_field_part_value_when_given_value_is_correct(self):
        part = FieldPart('part', 2, 3)
        given_value = 6
        part.value = given_value

        assert given_value == part.value

    # test of __repr__ method

    @pytest.mark.parametrize(
        ('enumeration', 'representation', 'hexadecimal'),
        [({
            1: 'MF',
            4: 'reserved',
            20: 'DF',
            17: 'danger'
        }, 'FieldPart(name=flags, default=DF, value=danger)', False),
         (None, 'FieldPart(name=flags, default=20, value=17)', False),
         (None, 'FieldPart(name=flags, default=0x14, value=0x11)', True)])
    def test_should_correctly_represent_field_part(self, enumeration,
                                                   representation,
                                                   hexadecimal):
        part = FieldPart('flags', 20, 6, enumeration, hex=hexadecimal)
        part.value = 17

        assert representation == repr(part)

    # test of clone method

    def test_should_return_a_correct_copy_of_field_part_when_calling_clone_method(
            self):
        part = FieldPart('part', 2, 3)
        cloned_part = part.clone()

        assert cloned_part == part
        assert cloned_part is not part
Exemplo n.º 6
0
    import dataclasses
except ImportError:
    dataclasses = None  # type: ignore

MyNamedTuple = collections.namedtuple('A', ['x', 'y'])
MyTypedNamedTuple = NamedTuple('MyTypedNamedTuple', [('f1', int), ('f2', str)])


class MyEnum(enum.Enum):
    E1 = 5
    E2 = enum.auto()
    E3 = 'abc'


MyIntEnum = enum.IntEnum('MyIntEnum', 'I1 I2 I3')
MyIntFlag = enum.IntFlag('MyIntFlag', 'F1 F2 F3')
MyFlag = enum.Flag('MyFlag', 'F1 F2 F3')  # pylint: disable=too-many-function-args


class DefinesGetState:
    def __init__(self, value):
        self.value = value

    def __getstate__(self):
        return self.value

    def __eq__(self, other):
        return type(other) is type(self) and other.value == self.value


class DefinesGetAndSetState(DefinesGetState):
def load_yaml():
    global REGISTERS

    if REGISTERS is not None:
        return

    here = os.path.dirname(os.path.realpath(__file__))
    yaml_filename = os.path.abspath(
        os.path.join(here, "../../data/regmap.yaml"))

    with open(yaml_filename, "r") as f:
        s = f.read()

    raw_regs = yaml.load(s, Loader=yaml.Loader)

    REGISTERS = []

    for raw_name, raw_reg in raw_regs.items():
        raw_modes = raw_reg.get("modes", None)
        if raw_modes is None or raw_modes == "None":
            modes = None
        elif isinstance(raw_modes, str):
            try:
                modes = [get_mode(raw_modes)]
            except ValueError:
                continue
        else:  # assumed to be a list
            modes = []
            for m in raw_modes:
                try:
                    modes.append(get_mode(m))
                except ValueError:
                    pass

            if len(modes) == 0:
                continue

        full_name = raw_name.strip().lower()

        try:
            prefix, stripped_name = full_name.split("_", 1)
        except ValueError:
            stripped_name = full_name
        else:
            if prefix in PREFIX_TO_MODE_MAP.keys():
                mode = PREFIX_TO_MODE_MAP[prefix]

                if mode is None:
                    continue

                assert PREFIX_TO_MODE_MAP[prefix] == modes[0] and len(
                    modes) == 1
            else:
                stripped_name = full_name

        addr = raw_reg["address"]
        assert type(addr) == int

        readable, writable = [
            c in raw_reg.get("access", "rw").strip().lower() for c in "rw"
        ]
        category = Category(raw_reg["category"].strip().lower())
        data_type = DataType(raw_reg["type"].strip().lower())

        reg = Register(
            full_name=full_name,
            stripped_name=stripped_name,
            addr=addr,
            modes=modes,
            readable=readable,
            writable=writable,
            category=category,
            data_type=data_type,
        )

        try:
            reg.float_scale = float(raw_reg["scale"])
        except (KeyError, ValueError):
            pass
        else:
            assert reg.data_type == DataType.INT32

        if data_type == DataType.ENUM:
            enum_values = {
                str(k).upper(): int(d["value"])
                for k, d in raw_reg["values"].items()
            }
            reg.enum = enum.IntEnum(full_name + "_enum", enum_values)

        if data_type == DataType.BITSET:
            flags = {}
            masks = {}

            for k, v in [(str(k).upper(), int(d["value"]))
                         for k, d in raw_reg["bits"].items()]:
                if v == 0:
                    continue

                if v & (v - 1) == 0:  # is power of 2
                    flags[k] = v
                else:
                    masks[k] = v

            reg.bitset_flags = enum.IntFlag(full_name + "_bitset_flags", flags)
            reg.bitset_masks = enum.IntEnum(full_name + "_bitset_masks", masks)

        REGISTERS.append(reg)
Exemplo n.º 8
0
                                                 'STORED_PLAYLIST',
                                                 'PLAYLIST',
                                                 'PLAYER',
                                                 'MIXER',
                                                 'OUTPUT',
                                                 'OPTIONS',
                                                 'PARTITION',
                                                 'STICKER',
                                                 'SUBSCRIPTION',
                                                 'MESSAGE',
                                                 'CONNECT',
                                                 'IDLE',
                                                 'TIMEOUT'])}
EVENTS['NONE'] = 0
EVENTS['ANY'] = EVENTS['CONNECT'] - 1
Event = enum.IntFlag('Event', EVENTS)
del EVENTS

Event.__doc__ = """
An enumeration of possible events for the idle request.
Possible values are:
- An MPD SUBSYSTEM name (in uppercase).
- ANY - match any subsystem.
- CONNECT - client is connected to server.
- IDLE - client is idle.
- TIMEOUT - flagged in the return value if a timeout ocurred.
"""


class RequestPassive(Request):
    """
Exemplo n.º 9
0
def _rstrip(iterable, pred):
    cache = []
    cache_append = cache.append
    for x in iterable:
        if pred(x):
            cache_append(x)
        else:
            for y in cache:
                yield y
            del cache[:]
            yield x


PciFillFlag = enum.IntFlag(
    'PciFillFlag',
    dict((''.join(x.capitalize() for x in k.split('_')[2:]), getattr(lib, k))
         for k in dir(lib) if k.startswith('PCI_FILL_')))

PciFillFlag.All = PciFillFlag(
    sum(v.value for v in PciFillFlag if v.value < PciFillFlag.Rescan))


class PciCapType(enum.Enum):
    Normal = lib.PCI_CAP_NORMAL
    Extended = lib.PCI_CAP_EXTENDED


PciCapId = enum.IntEnum(
    'PciCapId',
    dict((''.join(x.capitalize() for x in k.split('_')[3:]), getattr(lib, k))
         for k in dir(lib) if k.startswith('PCI_CAP_ID_')))
Exemplo n.º 10
0
        for b in bwrap:
            if prev is not None and b.can_merge():
                prev.merge(b.block)
            else:
                if prev is not None:
                    yield prev
                prev = b.block
        if prev is not None:
            yield prev

    return list(process_blocks(bwrap))


# Graph writing functions

GraphDisplayFlags = enum.IntFlag('GraphDisplayFlags',
                                 ['REGISTERS', 'INSTRUCTIONS'])


def block_name(b):
    return f"block_at_{b.starting_line()}"


def rebuild_line(instr, args):
    args_s = ' ' + ','.join(args) if args else ''
    return f"<FONT COLOR=\"blue4\">{instr}</FONT>{args_s}"


def write_line(f, nl, line_parts, alt=False):
    style = 'BGCOLOR="gray78"' if not alt else 'BGCOLOR="gray70"'
    print(f"""<TR>
<TD {style}><FONT COLOR="gray30">{nl+1}</FONT></TD>
Exemplo n.º 11
0
        key_ = key.encode('utf-8') + b'\0'
        val_ = val.encode('utf-8') + b'\0'

        if lib.pci_set_param(pacc, ffi.from_buffer(key_),
                             ffi.from_buffer(val_)) != 0:
            raise KeyError(key)

    def __delitem__(self, key: str):
        raise KeyError(key)

    def __repr__(self):
        return repr(dict(self.items()))


PciAccessType = enum.IntFlag(
    'PciAccessType',
    dict((''.join(x.capitalize() for x in k.split('_')[2:]), getattr(lib, k))
         for k in dir(lib) if k.startswith('PCI_ACCESS_')))

PciLookupMode = enum.IntFlag(
    'PciLookupMode',
    dict((''.join(x.capitalize() for x in k.split('_')[2:]), getattr(lib, k))
         for k in dir(lib) if k.startswith('PCI_LOOKUP_')))


class Pci:
    def __init__(self):
        self._pacc = lib.pci_alloc()
        lib.pci_init(self._pacc)

    def close(self):
        if self._pacc is not None: