logo

oasis-root

Compiled tree of Oasis Linux based on own branch at <https://hacktivis.me/git/oasis/> git clone https://anongit.hacktivis.me/git/oasis-root.git

_endian.py (2000B)


  1. import sys
  2. from ctypes import *
  3. _array_type = type(Array)
  4. def _other_endian(typ):
  5. """Return the type with the 'other' byte order. Simple types like
  6. c_int and so on already have __ctype_be__ and __ctype_le__
  7. attributes which contain the types, for more complicated types
  8. arrays and structures are supported.
  9. """
  10. # check _OTHER_ENDIAN attribute (present if typ is primitive type)
  11. if hasattr(typ, _OTHER_ENDIAN):
  12. return getattr(typ, _OTHER_ENDIAN)
  13. # if typ is array
  14. if isinstance(typ, _array_type):
  15. return _other_endian(typ._type_) * typ._length_
  16. # if typ is structure
  17. if issubclass(typ, Structure):
  18. return typ
  19. raise TypeError("This type does not support other endian: %s" % typ)
  20. class _swapped_meta(type(Structure)):
  21. def __setattr__(self, attrname, value):
  22. if attrname == "_fields_":
  23. fields = []
  24. for desc in value:
  25. name = desc[0]
  26. typ = desc[1]
  27. rest = desc[2:]
  28. fields.append((name, _other_endian(typ)) + rest)
  29. value = fields
  30. super().__setattr__(attrname, value)
  31. ################################################################
  32. # Note: The Structure metaclass checks for the *presence* (not the
  33. # value!) of a _swapped_bytes_ attribute to determine the bit order in
  34. # structures containing bit fields.
  35. if sys.byteorder == "little":
  36. _OTHER_ENDIAN = "__ctype_be__"
  37. LittleEndianStructure = Structure
  38. class BigEndianStructure(Structure, metaclass=_swapped_meta):
  39. """Structure with big endian byte order"""
  40. __slots__ = ()
  41. _swappedbytes_ = None
  42. elif sys.byteorder == "big":
  43. _OTHER_ENDIAN = "__ctype_le__"
  44. BigEndianStructure = Structure
  45. class LittleEndianStructure(Structure, metaclass=_swapped_meta):
  46. """Structure with little endian byte order"""
  47. __slots__ = ()
  48. _swappedbytes_ = None
  49. else:
  50. raise RuntimeError("Invalid byteorder")