Code Duplication    Length = 16-24 lines in 2 locations

starstruct/elementenum.py 2 locations

@@ 72-95 (lines=24) @@
69
            # recreate the struct with the new format
70
            self._struct = struct.Struct(self.format)
71
72
    def pack(self, msg):
73
        """Pack the provided values into the supplied buffer."""
74
        # The value to pack could be a raw value, an enum value, or a string
75
        # that represents the enum value, first ensure that the value provided
76
        # is a valid value for the referenced enum class.
77
        item = msg[self.name]
78
        if isinstance(item, self.ref):
79
            enum_item = item
80
        elif isinstance(item, str):
81
            try:
82
                enum_item = getattr(self.ref, msg[self.name])
83
            except AttributeError:
84
                enum_name = re.match(r"<enum '(\S+)'>", str(self.ref)).group(1)
85
                msg = '{} is not a valid {}'.format(msg[self.name], enum_name)
86
                raise ValueError(msg)
87
        else:
88
            enum_item = self.ref(item)
89
        data = self._struct.pack(enum_item.value)
90
91
        # If the data does not meet the alignment, add some padding
92
        missing_bytes = len(data) % self._alignment
93
        if missing_bytes:
94
            data += b'\x00' * missing_bytes
95
        return data
96
97
    def unpack(self, msg, buf):
98
        """Unpack data from the supplied buffer using the initialized format."""
@@ 117-132 (lines=16) @@
114
115
        return (member, unused)
116
117
    def make(self, msg):
118
        """Return the "transformed" value for this element"""
119
        # Handle the same conditions that pack handles
120
        item = msg[self.name]
121
        if isinstance(item, self.ref):
122
            enum_item = item
123
        elif isinstance(item, str):
124
            try:
125
                enum_item = getattr(self.ref, msg[self.name])
126
            except AttributeError:
127
                enum_name = re.match(r"<enum '(\S+)'>", str(self.ref)).group(1)
128
                msg = '{} is not a valid {}'.format(msg[self.name], enum_name)
129
                raise ValueError(msg)
130
        else:
131
            enum_item = self.ref(item)
132
        return enum_item
133