Source code for mtc.base.enums
import enum
import io
from typing import Self
from .parser import Parser
from .utils import int_to_bytes, bytes_to_int
[docs]
class Enum(Parser, metaclass=EnumMeta):
"""Base class for handling enums"""
EnumClass: type[enum.IntEnum]
size_in_bytes: int
def __init__(self, /, value: int) -> None:
self.value = self.EnumClass(value)
[docs]
def to_bytes(self) -> bytes:
return int_to_bytes(self.value, self.size_in_bytes)
[docs]
@classmethod
def parse(cls, stream: io.BufferedIOBase) -> Self:
n = bytes_to_int(stream.read(cls.size_in_bytes))
try:
obj = cls(n)
except ValueError:
raise cls.ParsingError(stream.tell() - cls.size_in_bytes, stream.tell(), f"Invalid value {n}")
return obj
[docs]
@classmethod
def skip(cls, stream: io.BufferedIOBase) -> None:
stream.seek(cls.size_in_bytes,io.SEEK_CUR)
[docs]
def print(self) -> str:
return f"{self.size_in_bytes} {self.__class__.__name__} {self.value.name}({self.value})"
__all__ = ["Enum"]