home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2011 June / maximum-cd-2011-06.iso / DiscContents / LibO_3.3.1_Win_x86_install_multi.exe / libreoffice1.cab / _endian.py < prev    next >
Encoding:
Python Source  |  2011-02-15  |  2.0 KB  |  61 lines

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