Debian Codegraph @

lib_pypy/_ctypes/array.py

raw symbols SCIP
1 from _rawffi import alt as _ffi
2 import _rawffi
3
4 from _ctypes.basics import _CData, cdata_from_address, _CDataMeta, sizeof, _ctypes_property
5 from _ctypes.basics import keepalive_key, store_reference, ensure_objects
6 from _ctypes.basics import CArgObject, as_ffi_pointer
7 from _pypy_generic_alias import GenericAlias
8 import sys, __pypy__, struct
9
10 class ArrayMeta(_CDataMeta):
11 def __new__(self, name, cls, typedict):
12 res = type.__new__(self, name, cls, typedict)
13
14 if cls == (_CData,): # this is the Array class defined below
15 res._ffiarray = None
16 return res
17 if not hasattr(res, '_length_'):
18 raise AttributeError(
19 "class must define a '_length_' attribute, "
20 "which must be a positive integer")
21 if not isinstance(res._length_, int):
22 raise TypeError("The '_length_' attribute must be an integer")
23 if res._length_ < 0:
24 raise ValueError("The '_length_' attribute must not be negative")
25 ffiarray = res._ffiarray = _rawffi.Array(res._type_._ffishape_)
26 subletter = getattr(res._type_, '_type_', None)
27 if subletter == 'c':
28 def getvalue(self):
29 return _rawffi.charp2string(self._buffer.buffer,
30 self._length_)
31 def setvalue(self, val):
32 # we don't want to have buffers here
33 if len(val) > self._length_:
34 raise ValueError("%r too long" % (val,))
35 if isinstance(val, str):
36 _rawffi.rawstring2charp(self._buffer.buffer, val)
37 else:
38 for i in range(len(val)):
39 self[i] = val[i]
40 if len(val) < self._length_:
41 self._buffer[len(val)] = b'\x00'
42 res.value = _ctypes_property(getvalue, setvalue)
43
44 def getraw(self):
45 return _rawffi.charp2rawstring(self._buffer.buffer,
46 self._length_)
47
48 def setraw(self, buffer):
49 if len(buffer) > self._length_:
50 raise ValueError("%r too long" % (buffer,))
51 _rawffi.rawstring2charp(self._buffer.buffer, buffer)
52 res.raw = property(getraw, setraw)
53 elif subletter == 'u':
54 def getvalue(self):
55 return _rawffi.wcharp2unicode(self._buffer.buffer,
56 self._length_)
57
58 def setvalue(self, val):
59 # we don't want to have buffers here
60 if len(val) > self._length_:
61 raise ValueError("%r too long" % (val,))
62 if isinstance(val, str):
63 target = self._buffer
64 else:
65 target = self
66 for i in range(len(val)):
67 target[i] = val[i]
68 if len(val) < self._length_:
69 target[len(val)] = u'\x00'
70 res.value = _ctypes_property(getvalue, setvalue)
71
72 res._ffishape_ = (ffiarray, res._length_)
73 res._fficompositesize_ = res._sizeofinstances()
74 return res
75
76 from_address = cdata_from_address
77
78 def _sizeofinstances(self):
79 if self._ffiarray is None:
80 raise TypeError("abstract class")
81 size, alignment = self._ffiarray.size_alignment(self._length_)
82 return size
83
84 def _alignmentofinstances(self):
85 return self._type_._alignmentofinstances()
86
87 def _CData_output(self, resarray, base=None, index=-1):
88 from _rawffi.alt import types
89 # If a char_p or unichar_p is received, skip the string interpretation
90 try:
91 deref = type(base)._deref_ffiargtype()
92 except AttributeError:
93 deref = None
94 if deref != types.char_p and deref != types.unichar_p:
95 # this seems to be a string if we're array of char, surprise!
96 from ctypes import c_char, c_wchar
97 if self._type_ is c_char:
98 return _rawffi.charp2string(resarray.buffer, self._length_)
99 if self._type_ is c_wchar:
100 return _rawffi.wcharp2unicode(resarray.buffer, self._length_)
101 res = self.__new__(self)
102 ffiarray = self._ffiarray.fromaddress(resarray.buffer, self._length_)
103 res._buffer = ffiarray
104 if base is not None:
105 res._base = base
106 res._index = index
107 return res
108
109 def _CData_retval(self, resbuffer):
110 raise NotImplementedError
111
112 def from_param(self, value):
113 # array accepts very strange parameters as part of structure
114 # or function argument...
115 from ctypes import c_char, c_wchar
116 if isinstance(value, self):
117 return value
118 if hasattr(self, '_type_'):
119 if issubclass(self._type_, c_char):
120 if isinstance(value, bytes):
121 if len(value) > self._length_:
122 raise ValueError("Invalid length")
123 value = self(*value)
124 elif not isinstance(value, self):
125 raise TypeError("expected bytes, %s found"
126 % (value.__class__.__name__,))
127 elif issubclass(self._type_, c_wchar):
128 if isinstance(value, str):
129 if len(value) > self._length_:
130 raise ValueError("Invalid length")
131 value = self(*value)
132 elif not isinstance(value, self):
133 raise TypeError("expected unicode string, %s found"
134 % (value.__class__.__name__,))
135 if isinstance(value, tuple):
136 if len(value) > self._length_:
137 raise RuntimeError("Invalid length")
138 value = self(*value)
139 return _CDataMeta.from_param(self, value)
140
141 def _build_ffiargtype(self):
142 return _ffi.types.Pointer(self._type_.get_ffi_argtype())
143
144 def _deref_ffiargtype(self):
145 return self._type_.get_ffi_argtype()
146
147 def _getformat(self):
148 shape = []
149 tp = self
150 while hasattr(tp, '_length_'):
151 shape.append(tp._length_)
152 tp = tp._type_
153 return "(%s)%s" % (','.join([str(n) for n in shape]), tp._getformat())
154
155 def _has_pointer(self):
156 return self._type_._is_pointer_like() or self._type_._has_pointer()
157
158
159 def array_get_slice_params(self, index):
160 if hasattr(self, '_length_'):
161 start, stop, step = index.indices(self._length_)
162 else:
163 step = index.step
164 if step is None:
165 step = 1
166 start = index.start
167 stop = index.stop
168 if start is None:
169 if step > 0:
170 start = 0
171 else:
172 raise ValueError("slice start is required for step < 0")
173 if stop is None:
174 raise ValueError("slice stop is required")
175
176 return start, stop, step
177
178 def array_slice_setitem(self, index, value):
179 start, stop, step = self._get_slice_params(index)
180
181 if ((step < 0 and stop >= start) or
182 (step > 0 and start >= stop)):
183 slicelength = 0
184 elif step < 0:
185 slicelength = (stop - start + 1) / step + 1
186 else:
187 slicelength = (stop - start - 1) / step + 1;
188
189 if slicelength != len(value):
190 raise ValueError("Can only assign slices of the same length")
191 for i, j in enumerate(range(start, stop, step)):
192 self[j] = value[i]
193
194 def array_slice_getitem(self, index):
195 start, stop, step = self._get_slice_params(index)
196 l = [self[i] for i in range(start, stop, step)]
197 letter = getattr(self._type_, '_type_', None)
198 if letter == 'c':
199 return b"".join(l)
200 if letter == 'u':
201 return u"".join(l)
202 return l
203
204 class Array(_CData, metaclass=ArrayMeta):
205 _ffiargshape_ = 'P'
206
207 def __init__(self, *args):
208 if not hasattr(self, '_buffer'):
209 self._buffer = self._ffiarray(self._length_, autofree=True)
210 for i, arg in enumerate(args):
211 self[i] = arg
212 _init_no_arg_ = __init__
213
214 def _fix_index(self, index):
215 if index < 0:
216 index += self._length_
217 if 0 <= index < self._length_:
218 return index
219 else:
220 raise IndexError
221
222 _get_slice_params = array_get_slice_params
223 _slice_getitem = array_slice_getitem
224 _slice_setitem = array_slice_setitem
225
226 def _subarray(self, index):
227 """Return a _rawffi array of length 1 whose address is the same as
228 the index'th item of self."""
229 address = self._buffer.itemaddress(index)
230 return self._ffiarray.fromaddress(address, 1)
231
232 def __setitem__(self, index, value):
233 if isinstance(index, slice):
234 self._slice_setitem(index, value)
235 return
236 index = self._fix_index(index)
237 cobj = self._type_.from_param(value)
238 if ensure_objects(cobj) is not None:
239 store_reference(self, index, cobj._objects)
240 arg = cobj._get_buffer_value()
241 if self._type_._fficompositesize_ is None:
242 self._buffer[index] = arg
243 # something more sophisticated, cannot set field directly
244 else:
245 from ctypes import memmove
246 dest = self._buffer.itemaddress(index)
247 memmove(dest, arg, self._type_._fficompositesize_)
248
249 def __getitem__(self, index):
250 if isinstance(index, slice):
251 return self._slice_getitem(index)
252 index = self._fix_index(index)
253 return self._type_._CData_output(self._subarray(index), self, index)
254
255 def __len__(self):
256 return self._length_
257
258 def _get_buffer_for_param(self):
259 return CArgObject(self, self._buffer.byptr())
260
261 def _get_buffer_value(self):
262 return self._buffer.buffer
263
264 def _to_ffi_param(self):
265 return self._get_buffer_value()
266
267 def _as_ffi_pointer_(self, ffitype):
268 return as_ffi_pointer(self, ffitype)
269
270 def __buffer__(self, flags):
271 shape = []
272 tp = type(self)
273 while hasattr(tp, '_length_'):
274 shape.append(tp._length_)
275 tp = tp._type_
276 fmt = tp._getformat()
277 itemsize = sizeof(tp)
278 return __pypy__.newmemoryview(memoryview(self._buffer), itemsize, fmt, shape)
279
280 def __class_getitem__(self, item):
281 return GenericAlias(self, item)
282
283 ARRAY_CACHE = {}
284
285 def create_array_type(base, length):
286 if not hasattr(length, '__index__'):
287 raise TypeError("Can't multiply a ctypes type by a non-int of type %s" % type(length).__name__)
288 length = int(length)
289 if length < 0:
290 raise ValueError("Array length must be >= 0")
291 if length * base._sizeofinstances() > sys.maxsize:
292 raise OverflowError("array too large")
293 key = (base, length)
294 try:
295 return ARRAY_CACHE[key]
296 except KeyError:
297 name = "%s_Array_%d" % (base.__name__, length)
298 tpdict = dict(
299 _length_ = length,
300 _type_ = base
301 )
302 cls = ArrayMeta(name, (Array,), tpdict)
303 ARRAY_CACHE[key] = cls
304 return cls
305
306 byteorder = {'little': '<', 'big': '>'}
307 swappedorder = {'little': '>', 'big': '<'}
308
309 def get_format_str(typ):
310 return typ._getformat()