/Lib/ctypes/_endian.py
Python | 60 lines | 55 code | 2 blank | 3 comment | 0 complexity | a7ab0a4cd69597fe26678fc2f1f27fcd MD5 | raw file
1###################################################################### 2# This file should be kept compatible with Python 2.3, see PEP 291. # 3###################################################################### 4import sys 5from ctypes import * 6 7_array_type = type(c_int * 3) 8 9def _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 22class _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 40if 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 50elif 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 59else: 60 raise RuntimeError("Invalid byteorder")