field_decoder.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536
  1. class field_decoder:
  2. def __init__(self, target: object) -> None:
  3. self.__field = target
  4. def load(self, content: bytes) -> object:
  5. self.__field.set(self.__bytes_decode(content))
  6. return self
  7. def __bytes_decode(self, content: bytes) -> any:
  8. if self.__field.target_type is str:
  9. return self.__decode_str(content)
  10. if self.__field.target_type is bytes:
  11. return content
  12. if self.__field.target_type is int:
  13. return self.__decode_int(content)
  14. if self.__field.target_type is float:
  15. return self.__decode_float(content)
  16. if self.__field.target_type is bool:
  17. return self.__decode_bool(content)
  18. def __decode_bool(self, content: bytes) -> bool:
  19. return True if int.from_bytes(content) != 0 else False
  20. def __decode_float(self, content: bytes) -> float:
  21. return self.__decode_int(content) / pow(10, self.__field.precission)
  22. def __decode_str(self, content: bytes) -> str:
  23. return content.decode("UTF-8")
  24. def __decode_int(self, content: bytes) -> int:
  25. return int.from_bytes(content)