Debian Codegraph @

pypy/module/_rawffi/interp_array.py

raw symbols SCIP
1
2 """ Interpreter-level implementation of array, exposing ll-structure
3 to app-level with apropriate interface
4 """
5
6 from pypy.interpreter.gateway import interp2app, unwrap_spec
7 from pypy.interpreter.typedef import TypeDef, GetSetProperty, interp_attrproperty_w
8 from rpython.rtyper.lltypesystem import lltype, rffi
9 from rpython.rlib.rarithmetic import r_uint
10 from rpython.rlib import rgc, clibffi
11 from pypy.interpreter.error import OperationError, oefmt
12 from pypy.interpreter.buffer import RawBufferView
13
14 from pypy.module._rawffi.interp_rawffi import (
15 segfault_exception, W_DataShape, W_DataInstance, unwrap_value, wrap_value,
16 TYPEMAP, size_alignment, unpack_shape_with_length, read_ptr, write_ptr,)
17 from pypy.module._rawffi.buffer import RawFFIBuffer
18
19
20 class W_Array(W_DataShape):
21 def __init__(self, basicffitype, size):
22 # A W_Array represent the C type '*T', which can also represent
23 # the type of pointers to arrays of T. So the following fields
24 # are used to describe T only. It is 'basicffitype' possibly
25 # repeated until reaching the length 'size'.
26 self.basicffitype = basicffitype
27 self.size = size
28 self.alignment = size_alignment(basicffitype)[1]
29
30 def allocate(self, space, length, autofree=False):
31 if autofree:
32 return W_ArrayInstanceAutoFree(space, self, length)
33 return W_ArrayInstance(space, self, length)
34
35 def get_basic_ffi_type(self):
36 return self.basicffitype
37
38 @unwrap_spec(length=int, autofree=int)
39 def descr_call(self, space, length, w_items=None, autofree=False):
40 result = self.allocate(space, length, bool(autofree))
41 if not space.is_none(w_items):
42 items_w = space.unpackiterable(w_items)
43 iterlength = len(items_w)
44 if iterlength > length:
45 raise oefmt(space.w_ValueError,
46 "too many items for specified array length")
47 for num in range(iterlength):
48 w_item = items_w[num]
49 unwrap_value(space, write_ptr, result.ll_buffer, num,
50 self.itemcode, w_item)
51 return result
52
53 def descr_repr(self, space):
54 return space.newtext("<_rawffi.Array '%s' (%d, %d)>" % (self.itemcode,
55 self.size,
56 self.alignment))
57
58 @unwrap_spec(address=r_uint, length=int)
59 def fromaddress(self, space, address, length):
60 return W_ArrayInstance(space, self, length, address)
61
62 PRIMITIVE_ARRAY_TYPES = {}
63 for _code in TYPEMAP:
64 PRIMITIVE_ARRAY_TYPES[_code] = W_Array(TYPEMAP[_code],
65 size_alignment(TYPEMAP[_code])[0])
66 PRIMITIVE_ARRAY_TYPES[_code].itemcode = _code
67 ARRAY_OF_PTRS = PRIMITIVE_ARRAY_TYPES['P']
68
69 def descr_new_array(space, w_type, w_shape):
70 return unpack_shape_with_length(space, w_shape)
71
72 W_Array.typedef = TypeDef(
73 'Array',
74 __new__ = interp2app(descr_new_array),
75 __call__ = interp2app(W_Array.descr_call),
76 __repr__ = interp2app(W_Array.descr_repr),
77 fromaddress = interp2app(W_Array.fromaddress),
78 size_alignment = interp2app(W_Array.descr_size_alignment)
79 )
80 W_Array.typedef.acceptable_as_base_class = False
81
82
83 class W_ArrayInstance(W_DataInstance):
84 def __init__(self, space, shape, length, address=r_uint(0)):
85 memsize = shape.size * length
86 # For W_ArrayInstances that are used as the result value of a
87 # function call, ffi_call() writes 8 bytes into it even if the
88 # function's result type asks for less.
89 memsize = clibffi.adjust_return_size(memsize)
90 W_DataInstance.__init__(self, space, memsize, address)
91 self.length = length
92 self.shape = shape
93 self.fmt = shape.itemcode
94 self.itemsize = shape.size
95
96 def descr_repr(self, space):
97 addr = rffi.cast(lltype.Unsigned, self.ll_buffer)
98 return space.newtext("<_rawffi array %x of length %d>" % (addr,
99 self.length))
100
101 # This only allows non-negative indexes. Arrays of shape 'c' also
102 # support simple slices.
103
104 def setitem(self, space, num, w_value):
105 if not self.ll_buffer:
106 raise segfault_exception(space, "setting element of freed array")
107 if num >= self.length or num < 0:
108 raise OperationError(space.w_IndexError, space.w_None)
109 unwrap_value(space, write_ptr, self.ll_buffer, num, self.fmt, w_value)
110
111 def descr_setitem(self, space, w_index, w_value):
112 try:
113 num = space.int_w(w_index)
114 except OperationError as e:
115 if not e.match(space, space.w_TypeError):
116 raise
117 self.setslice(space, w_index, w_value)
118 else:
119 self.setitem(space, num, w_value)
120
121 def getitem(self, space, num):
122 if not self.ll_buffer:
123 raise segfault_exception(space, "accessing elements of freed array")
124 if num >= self.length or num < 0:
125 raise OperationError(space.w_IndexError, space.w_None)
126 return wrap_value(space, read_ptr, self.ll_buffer, num, self.fmt)
127
128 def descr_getitem(self, space, w_index):
129 try:
130 num = space.int_w(w_index)
131 except OperationError as e:
132 if not e.match(space, space.w_TypeError):
133 raise
134 return self.getslice(space, w_index)
135 else:
136 return self.getitem(space, num)
137
138 def getlength(self, space):
139 return space.newint(self.length)
140
141 @unwrap_spec(num=int)
142 def descr_itemaddress(self, space, num):
143 ptr = rffi.ptradd(self.ll_buffer, self.itemsize * num)
144 return space.newint(rffi.cast(lltype.Unsigned, ptr))
145
146 def getrawsize(self):
147 return self.itemsize * self.length
148
149 def decodeslice(self, space, w_slice):
150 if not space.isinstance_w(w_slice, space.w_slice):
151 raise oefmt(space.w_TypeError, "index must be int or slice")
152 if self.fmt != 'c':
153 raise oefmt(space.w_TypeError, "only 'c' arrays support slicing")
154 w_start = space.getattr(w_slice, space.newtext('start'))
155 w_stop = space.getattr(w_slice, space.newtext('stop'))
156 w_step = space.getattr(w_slice, space.newtext('step'))
157
158 if space.is_w(w_start, space.w_None):
159 start = 0
160 else:
161 start = space.int_w(w_start)
162 if space.is_w(w_stop, space.w_None):
163 stop = self.length
164 else:
165 stop = space.int_w(w_stop)
166 if not space.is_w(w_step, space.w_None):
167 step = space.int_w(w_step)
168 if step != 1:
169 raise oefmt(space.w_ValueError, "no step support")
170 if not (0 <= start <= stop <= self.length):
171 raise oefmt(space.w_ValueError, "slice out of bounds")
172 if not self.ll_buffer:
173 raise segfault_exception(space, "accessing a freed array")
174 return start, stop
175
176 def getslice(self, space, w_slice):
177 start, stop = self.decodeslice(space, w_slice)
178 ll_buffer = self.ll_buffer
179 result = [ll_buffer[i] for i in range(start, stop)]
180 return space.newbytes(''.join(result))
181
182 def setslice(self, space, w_slice, w_value):
183 start, stop = self.decodeslice(space, w_slice)
184 value = space.bytes_w(w_value)
185 if start + len(value) != stop:
186 raise oefmt(space.w_ValueError, "cannot resize array")
187 ll_buffer = self.ll_buffer
188 for i in range(len(value)):
189 ll_buffer[start + i] = value[i]
190
191 def buffer_w(self, space, flags):
192 return RawBufferView(
193 RawFFIBuffer(self), self.shape.itemcode, self.shape.size,
194 w_obj=self)
195
196
197 W_ArrayInstance.typedef = TypeDef(
198 'ArrayInstance', None, None, "read-write",
199 __repr__ = interp2app(W_ArrayInstance.descr_repr),
200 __setitem__ = interp2app(W_ArrayInstance.descr_setitem),
201 __getitem__ = interp2app(W_ArrayInstance.descr_getitem),
202 __len__ = interp2app(W_ArrayInstance.getlength),
203 buffer = GetSetProperty(W_ArrayInstance.getbuffer),
204 shape = interp_attrproperty_w('shape', W_ArrayInstance),
205 free = interp2app(W_ArrayInstance.free),
206 byptr = interp2app(W_ArrayInstance.byptr),
207 itemaddress = interp2app(W_ArrayInstance.descr_itemaddress),
208 )
209 W_ArrayInstance.typedef.acceptable_as_base_class = False
210
211
212 class W_ArrayInstanceAutoFree(W_ArrayInstance):
213 def __init__(self, space, shape, length):
214 W_ArrayInstance.__init__(self, space, shape, length, 0)
215
216 @rgc.must_be_light_finalizer
217 def __del__(self):
218 if self.ll_buffer:
219 self._free()
220
221
222 W_ArrayInstanceAutoFree.typedef = TypeDef(
223 'ArrayInstanceAutoFree', None, None, "read-write",
224 __repr__ = interp2app(W_ArrayInstance.descr_repr),
225 __setitem__ = interp2app(W_ArrayInstance.descr_setitem),
226 __getitem__ = interp2app(W_ArrayInstance.descr_getitem),
227 __len__ = interp2app(W_ArrayInstance.getlength),
228 buffer = GetSetProperty(W_ArrayInstance.getbuffer),
229 shape = interp_attrproperty_w('shape', W_ArrayInstance),
230 byptr = interp2app(W_ArrayInstance.byptr),
231 itemaddress = interp2app(W_ArrayInstance.descr_itemaddress),
232 )
233 W_ArrayInstanceAutoFree.typedef.acceptable_as_base_class = False