Manual py3k backport: [svn r74155] Issue #6242: Fix deallocator of io.StringIO and...
[python.git] / Lib / ctypes / _endian.py
blob6de0d47b2ceae0c5f525cb951f18181e7caf88a1
1 ######################################################################
2 # This file should be kept compatible with Python 2.3, see PEP 291. #
3 ######################################################################
4 import sys
5 from ctypes import *
7 _array_type = type(c_int * 3)
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)
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)
34 ################################################################
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.
40 if sys.byteorder == "little":
41 _OTHER_ENDIAN = "__ctype_be__"
43 LittleEndianStructure = Structure
45 class BigEndianStructure(Structure):
46 """Structure with big endian byte order"""
47 __metaclass__ = _swapped_meta
48 _swappedbytes_ = None
50 elif sys.byteorder == "big":
51 _OTHER_ENDIAN = "__ctype_le__"
53 BigEndianStructure = Structure
54 class LittleEndianStructure(Structure):
55 """Structure with little endian byte order"""
56 __metaclass__ = _swapped_meta
57 _swappedbytes_ = None
59 else:
60 raise RuntimeError("Invalid byteorder")