Completed
Pull Request — master (#30)
by
unknown
07:21
created

ElementConstant._packed()   A

Complexity

Conditions 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
c 1
b 0
f 0
dl 0
loc 3
rs 10
1
"""
2
The constant element class for StarStruct
3
4
To be used in the following way:
5
6
ExampleMessage = Message('constant_message', [
7
    ('regular', 'B'),                           # Two regular messages
8
    ('fill_in_later', 'H'),
9
    ('ending_sequence', 'II', (0xAA, 0xBB)),    # An ending sequence to a message
10
                                                # that's always the same
11
])
12
13
:todo: Not sure if alignment is working correctly here, or if it needs to do anything
14
15
"""
16
17
import struct
18
from typing import Optional, Tuple
0 ignored issues
show
Configuration introduced by
The import typing could not be resolved.

This can be caused by one of the following:

1. Missing Dependencies

This error could indicate a configuration issue of Pylint. Make sure that your libraries are available by adding the necessary commands.

# .scrutinizer.yml
before_commands:
    - sudo pip install abc # Python2
    - sudo pip3 install abc # Python3
Tip: We are currently not using virtualenv to run pylint, when installing your modules make sure to use the command for the correct version.

2. Missing __init__.py files

This error could also result from missing __init__.py files in your module folders. Make sure that you place one file in each sub-folder.

Loading history...
19
20
from starstruct.element import register, Element
21
from starstruct.modes import Mode
22
23
24
@register
25
class ElementConstant(Element):
26
    def __init__(self, field, mode=Mode.Native, alignment=1):
27
        self.name = field[0]
28
        self.format = field[1]
29
        self.values = field[2]
30
31
        self._mode = mode
32
        self._alignment = alignment
33
34
    @property
35
    def _struct(self):
36
        return struct.Struct(self._mode.value + self.format)
37
38
    @property
39
    def _packed(self):
40
        return self._struct.pack(*self.values)
41
42
    @staticmethod
43
    def valid(field: list) -> bool:
44
        """
45
        Validate whether this field could supply this element with the corect values
46
        """
47
        return len(field) == 3 \
48
            and isinstance(field[0], str) \
49
            and isinstance(field[1], str) \
50
            and struct.calcsize(field[1]) \
51
            and isinstance(field[2], tuple)
52
53
    def validate(self, msg):
54
        """
55
        Ensure that the supplied message contains the required information for
56
        this element object to operate.
57
58
        Constants will alawys be valid
59
        """
60
        return True
61
62
    def update(self, mode: Optional[Tuple]=None, alignment: Optional[int]=1) -> None:
63
        """change the mode of the struct format"""
64
        if mode:
65
            self._mode = mode
66
67
        if alignment:
68
            self._alignment = alignment
69
70
    def pack(self, msg: dict) -> bytes:
71
        """
72
        Pack the provided values into the supplied buffer.
73
74
        :param msg: The message specifying the values to pack
75
        """
76
        return self._packed
77
78
    def unpack(self, msg: dict, buf: bytes) -> Tuple[bytes, bytes]:
79
        """Unpack data from the supplied buffer using the initialized format."""
80
        return (self._struct.unpack_from(buf), buf[self._struct.size:])
81
82
    def make(self, msg: dict):
83
        """
84
        Return the expected "made" value
85
86
        :param msg: The values to make
87
        """
88
        return self.values
89