Debian Codegraph @

native/python/pyjp_array.cpp

raw symbols SCIP
1 /*****************************************************************************
2 Licensed under the Apache License, Version 2.0 (the "License");
3 you may not use this file except in compliance with the License.
4 You may obtain a copy of the License at
5
6 http://www.apache.org/licenses/LICENSE-2.0
7
8 Unless required by applicable law or agreed to in writing, software
9 distributed under the License is distributed on an "AS IS" BASIS,
10 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 See the License for the specific language governing permissions and
12 limitations under the License.
13
14 See NOTICE file for details.
15 *****************************************************************************/
16 #include "jpype.h"
17 #include "pyjp.h"
18 #include "jp_array.h"
19 #include "jp_arrayclass.h"
20
21 #ifdef __cplusplus
22 extern "C"
23 {
24 #endif
25
26 /**
27 * Create a new object.
28 *
29 * This is only called from the Python side.
30 *
31 * @param type
32 * @param args
33 * @param kwargs
34 * @return
35 */
36 static PyObject *PyJPArray_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
37 {
38 JP_PY_TRY("PyJPArray_new");
39 auto* self = (PyJPArray*) type->tp_alloc(type, 0);
40 JP_PY_CHECK();
41 self->m_Array = nullptr;
42 self->m_View = nullptr;
43 return (PyObject*) self;
44 JP_PY_CATCH(nullptr);
45 }
46
47 static int PyJPArray_init(PyObject *self, PyObject *args, PyObject *kwargs)
48 {
49 JP_PY_TRY("PyJPArray_init");
50
51 // Cases here.
52 // - We got here with a JPValue
53 // - We get an integer. Just create a new array with desired size.
54 // - We get a sequence. Allocate with desired size and call setItems.
55 // - We get something else.... ???
56
57 PyObject* v;
58 if (!PyArg_ParseTuple(args, "O", &v))
59 return -1;
60
61 JPClass *cls = PyJPClass_getJPClass((PyObject*) Py_TYPE(self));
62 auto* arrayClass = dynamic_cast<JPArrayClass*> (cls);
63 if (arrayClass == nullptr)
64 JP_RAISE(PyExc_TypeError, "Class must be array type");
65
66 JPJavaFrame frame = JPJavaFrame::outer();
67
68 JPValue *value = PyJPValue_getJavaSlot(v);
69 if (value != nullptr)
70 {
71 auto* arrayClass2 = dynamic_cast<JPArrayClass*> (value->getClass());
72 if (arrayClass2 == nullptr)
73 JP_RAISE(PyExc_TypeError, "Class must be array type");
74 if (arrayClass2 != arrayClass)
75 JP_RAISE(PyExc_TypeError, "Array class mismatch");
76 ((PyJPArray*) self)->m_Array = new JPArray(*value);
77 PyJPValue_assignJavaSlot(frame, self, *value);
78 return 0;
79 }
80
81 if (PySequence_Check(v))
82 {
83 JP_TRACE("Sequence");
84 jlong length = PySequence_Size(v);
85 if (length < 0 || length > 2147483647)
86 JP_RAISE(PyExc_ValueError, "Array size invalid");
87 JPValue newArray = arrayClass->newArray(frame, (int) length);
88 ((PyJPArray*) self)->m_Array = new JPArray(newArray);
89 ((PyJPArray*) self)->m_Array->setRange(0, (jsize) length, 1, v);
90 PyJPValue_assignJavaSlot(frame, self, newArray);
91 return 0;
92 }
93
94 if (PyIndex_Check(v))
95 {
96 JP_TRACE("Index");
97 long long length = PyLong_AsLongLong(v);
98 if (length < 0 || length > 2147483647)
99 JP_RAISE(PyExc_ValueError, "Array size invalid");
100 JPValue newArray = arrayClass->newArray(frame, (int) length);
101 ((PyJPArray*) self)->m_Array = new JPArray(newArray);
102 PyJPValue_assignJavaSlot(frame, self, newArray);
103 return 0;
104 }
105
106 JP_FAULT_RETURN("PyJPArray_init.null", 0);
107 JP_RAISE(PyExc_TypeError, "Invalid type");
108 JP_PY_CATCH(-1);
109 }
110
111 static void PyJPArray_dealloc(PyJPArray *self)
112 {
113 JP_PY_TRY("PyJPArray_dealloc");
114 delete self->m_Array;
115 Py_TYPE(self)->tp_free(self);
116 JP_PY_CATCH(); // GCOVR_EXCL_LINE
117 }
118
119 static PyObject *PyJPArray_repr(PyJPArray *self)
120 {
121 JP_PY_TRY("PyJPArray_repr");
122 return PyUnicode_FromFormat("<java array '%s'>", Py_TYPE(self)->tp_name);
123 JP_PY_CATCH(nullptr);
124 }
125
126 static Py_ssize_t PyJPArray_len(PyJPArray *self)
127 {
128 JP_PY_TRY("PyJPArray_len");
129 JPJavaFrame frame = JPJavaFrame::outer();
130 if (self->m_Array == nullptr)
131 JP_RAISE(PyExc_ValueError, "Null array"); // GCOVR_EXCL_LINE
132 return self->m_Array->getLength();
133 JP_PY_CATCH(-1);
134 }
135
136 static PyObject* PyJPArray_length(PyJPArray *self, PyObject *closure)
137 {
138 return PyLong_FromSsize_t(PyJPArray_len(self));
139 }
140
141 static PyObject *PyJPArray_getItem(PyJPArray *self, PyObject *item)
142 {
143 JP_PY_TRY("PyJPArray_getArrayItem");
144 JPJavaFrame frame = JPJavaFrame::outer();
145 if (self->m_Array == nullptr)
146 JP_RAISE(PyExc_ValueError, "Null array");
147
148 if (PyIndex_Check(item))
149 {
150 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
151 if (i == -1 && PyErr_Occurred())
152 return nullptr; // GCOVR_EXCL_LINE
153 return self->m_Array->getItem((jsize) i).keep();
154 }
155
156 if (PySlice_Check(item))
157 {
158 Py_ssize_t start, stop, step, slicelength;
159 auto length = (Py_ssize_t) self->m_Array->getLength();
160
161 if (PySlice_Unpack(item, &start, &stop, &step) < 0)
162 return nullptr;
163
164 slicelength = PySlice_AdjustIndices(length, &start, &stop, step);
165
166 if (slicelength <= 0)
167 {
168 // This should point to a null array so we don't hold worthless
169 // memory, but this is a low priority
170 start = stop = 0;
171 step = 1;
172 }
173
174 JPPyObject tuple = JPPyObject::call(PyTuple_New(0));
175
176 JPPyObject newArray = JPPyObject::claim(Py_TYPE(self)->tp_new(Py_TYPE(self), tuple.get(), nullptr));
177
178 // Copy over the JPValue
179 PyJPValue_assignJavaSlot(frame, newArray.get(),
180 *PyJPValue_getJavaSlot((PyObject*) self));
181
182 // Set up JPArray as slice
183 JPArray *array = ((PyJPArray*) self)->m_Array;
184 ((PyJPArray*) newArray.get())->m_Array = new JPArray(array,
185 (jsize) start, (jsize) stop, (jsize) step);
186 return newArray.keep();
187 }
188
189 JP_RAISE(PyExc_TypeError, "Unsupported getItem type");
190 JP_PY_CATCH(nullptr);
191 }
192
193 static int PyJPArray_assignSubscript(PyJPArray *self, PyObject *item, PyObject *value)
194 {
195 JP_PY_TRY("PyJPArray_assignSubscript");
196 JPJavaFrame frame = JPJavaFrame::outer();
197 // Verified with numpy that item deletion on immutable should
198 // be ValueError
199 if ( value == nullptr)
200 JP_RAISE(PyExc_ValueError, "item deletion not supported");
201 if (self->m_Array == nullptr)
202 JP_RAISE(PyExc_ValueError, "Null array");
203
204 // Watch out for self assignment
205 if (PyObject_IsInstance(value, (PyObject*) PyJPArray_Type))
206 {
207 JPValue *v1 = PyJPValue_getJavaSlot((PyObject*) self);
208 JPValue *v2 = PyJPValue_getJavaSlot((PyObject*) value);
209 if (frame.equals(v1->getJavaObject(), v2->getJavaObject()))
210 JP_RAISE(PyExc_ValueError, "self assignment not support currently");
211 }
212
213 if (PyIndex_Check(item))
214 {
215 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
216 if (i == -1 && PyErr_Occurred())
217 return -1; // GCOVR_EXCL_LINE
218 self->m_Array->setItem((jsize) i, value);
219 return 0;
220 }
221
222 if (PySlice_Check(item))
223 {
224 Py_ssize_t start, stop, step, slicelength;
225 auto length = (Py_ssize_t) self->m_Array->getLength();
226
227 if (PySlice_Unpack(item, &start, &stop, &step) < 0)
228 return -1;
229
230 slicelength = PySlice_AdjustIndices(length, &start, &stop, step);
231
232 if (slicelength <= 0)
233 return 0;
234
235 self->m_Array->setRange((jsize) start, (jsize) slicelength, (jsize) step, value);
236 return 0;
237 }
238 PyErr_Format(PyExc_TypeError,
239 "Java array indices must be integers or slices, not '%s'",
240 Py_TYPE(item)->tp_name);
241 JP_PY_CATCH(-1);
242 }
243
244 static void PyJPArray_releaseBuffer(PyJPArray *self, Py_buffer *view)
245 {
246 JP_PY_TRY("PyJPArrayPrimitive_releaseBuffer");
247 JPContext* context = JPContext_global;
248 if (context->isRunning())
249 {
250 JPJavaFrame frame = JPJavaFrame::outer();
251 if (self->m_View == nullptr || !self->m_View->unreference())
252 return;
253 }
254 delete self->m_View;
255 self->m_View = nullptr;
256 JP_PY_CATCH(); // GCOVR_EXCL_LINE
257 }
258
259 int PyJPArray_getBuffer(PyJPArray *self, Py_buffer *view, int flags)
260 {
261 JP_PY_TRY("PyJPArray_getBuffer");
262 JPJavaFrame frame = JPJavaFrame::outer();
263 if (self->m_Array == nullptr)
264 JP_RAISE(PyExc_ValueError, "Null array");
265
266 if (!self->m_Array->getClass()->isPrimitiveArray())
267 {
268 PyErr_SetString(PyExc_BufferError, "Java array is not primitive array");
269 return -1;
270 }
271
272 if ((flags & PyBUF_WRITEABLE) == PyBUF_WRITEABLE)
273 {
274 PyErr_SetString(PyExc_BufferError, "Java array buffer is not writable");
275 return -1;
276 }
277
278 //Check to see if we are a slice and clone it if necessary
279 jarray obj = self->m_Array->getJava();
280 if (self->m_Array->isSlice())
281 obj = self->m_Array->clone(frame, (PyObject*) self);
282
283 jobject result;
284 try
285 {
286 // Collect the members into a rectangular array if possible.
287 result = frame.collectRectangular(obj);
288 } catch (JPypeException &ex)
289 {
290 // No matter what happens we are only allowed to throw BufferError
291 (void) ex;
292 PyErr_SetString(PyExc_BufferError, "Problem in Java buffer extraction");
293 return -1;
294 }
295
296 if (result == nullptr)
297 {
298 PyErr_SetString(PyExc_BufferError, "Java array buffer is not rectangular primitives");
299 return -1;
300 }
301
302 // If it is rectangular so try to create a view
303 try
304 {
305 if (self->m_View == nullptr)
306 self->m_View = new JPArrayView(self->m_Array, result);
307 JP_PY_CHECK();
308 self->m_View->reference();
309 *view = self->m_View->m_Buffer;
310
311 // If strides are not requested and this is a slice then fail
312 if ((flags & PyBUF_STRIDES) != PyBUF_STRIDES)
313 view->strides = nullptr;
314
315 // If shape is not requested
316 if ((flags & PyBUF_ND) != PyBUF_ND)
317 view->shape = nullptr;
318
319 // If format is not requested
320 if ((flags & PyBUF_FORMAT) != PyBUF_FORMAT)
321 view->format = nullptr;
322
323 // Okay all successful so reference the parent object
324 view->obj = (PyObject*) self;
325 Py_INCREF(view->obj);
326 return 0;
327 } catch (JPypeException &ex) // GCOVR_EXCL_LINE
328 {
329 (void) ex;
330 // GCOVR_EXCL_START
331 // Release the partial buffer so we don't leak
332 PyJPArray_releaseBuffer(self, view);
333
334 // We are only allowed to raise BufferError
335 PyErr_SetString(PyExc_BufferError, "Java array view failed");
336 return -1;
337 // GCOVR_EXCL_STOP
338 }
339 JP_PY_CATCH(-1); // GCOVR_EXCL_LINE
340 }
341
342 int PyJPArrayPrimitive_getBuffer(PyJPArray *self, Py_buffer *view, int flags)
343 {
344 JP_PY_TRY("PyJPArrayPrimitive_getBuffer");
345 JPJavaFrame frame = JPJavaFrame::outer();
346 if (self->m_Array == nullptr)
347 JP_RAISE(PyExc_ValueError, "Null array");
348 try
349 {
350 if ((flags & PyBUF_WRITEABLE) == PyBUF_WRITEABLE)
351 {
352 PyErr_SetString(PyExc_BufferError, "Java array buffer is not writable");
353 return -1;
354 }
355
356 if (self->m_View == nullptr)
357 {
358 self->m_View = new JPArrayView(self->m_Array);
359 }
360 self->m_View->reference();
361 *view = self->m_View->m_Buffer;
362
363 // We are always contiguous so no need to check that here.
364 view->readonly = 1;
365
366 // If strides are not requested and this is a slice then fail
367 if ((flags & PyBUF_STRIDES) != PyBUF_STRIDES)
368 {
369 if (view->strides[0] != view->itemsize)
370 JP_RAISE(PyExc_BufferError, "slices required strides");
371 view->strides = nullptr;
372 }
373
374 // If shape is not requested
375 if ((flags & PyBUF_ND) != PyBUF_ND)
376 {
377 view->shape = nullptr;
378 }
379
380 // If format is not requested
381 if ((flags & PyBUF_FORMAT) != PyBUF_FORMAT)
382 view->format = nullptr;
383
384 // Okay all successful so reference the parent object
385 view->obj = (PyObject*) self;
386 Py_INCREF(view->obj);
387 return 0;
388 } catch (JPypeException &ex)
389 {
390 (void) ex;
391 PyJPArray_releaseBuffer(self, view);
392
393 // We are only allowed to raise BufferError
394 PyErr_SetString(PyExc_BufferError, "Java array view failed");
395 return -1;
396 }
397 JP_PY_CATCH(-1);
398 }
399
400 static const char *length_doc =
401 "Get the length of a Java array\n"
402 "\n"
403 "This method is provided for compatibility with Java syntax.\n"
404 "Generally, the Python style ``len(array)`` should be preferred.\n";
405
406 static PyMethodDef arrayMethods[] = {
407 {"__getitem__", (PyCFunction) (&PyJPArray_getItem), METH_O | METH_COEXIST, ""},
408 {nullptr},
409 };
410
411 static PyGetSetDef arrayGetSets[] = {
412 {"length", (getter) (&PyJPArray_length), nullptr, (length_doc)},
413 {nullptr}
414 };
415
416 static PyType_Slot arraySlots[] = {
417 { Py_tp_new, (void*) PyJPArray_new},
418 { Py_tp_init, (void*) PyJPArray_init},
419 { Py_tp_dealloc, (void*) PyJPArray_dealloc},
420 { Py_tp_repr, (void*) PyJPArray_repr},
421 { Py_tp_methods, (void*) &arrayMethods},
422 { Py_mp_subscript, (void*) &PyJPArray_getItem},
423 { Py_sq_length, (void*) &PyJPArray_len},
424 { Py_tp_getset, (void*) &arrayGetSets},
425 { Py_mp_ass_subscript, (void*) &PyJPArray_assignSubscript},
426 #if PY_VERSION_HEX >= 0x03090000
427 { Py_bf_getbuffer, (void*) &PyJPArray_getBuffer},
428 { Py_bf_releasebuffer, (void*) &PyJPArray_releaseBuffer},
429 #endif
430 {0}
431 };
432
433 #if PY_VERSION_HEX < 0x03090000
434 static PyBufferProcs arrayBuffer = {
435 (getbufferproc) & PyJPArray_getBuffer,
436 (releasebufferproc) & PyJPArray_releaseBuffer
437 };
438 #endif
439
440 PyTypeObject *PyJPArray_Type = nullptr;
441 static PyType_Spec arraySpec = {
442 "_jpype._JArray",
443 sizeof (PyJPArray),
444 0,
445 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
446 arraySlots
447 };
448
449 #if PY_VERSION_HEX < 0x03090000
450 static PyBufferProcs arrayPrimBuffer = {
451 (getbufferproc) & PyJPArrayPrimitive_getBuffer,
452 (releasebufferproc) & PyJPArray_releaseBuffer
453 };
454 #endif
455
456 static PyType_Slot arrayPrimSlots[] = {
457 #if PY_VERSION_HEX >= 0x03090000
458 { Py_bf_getbuffer, (void*) &PyJPArrayPrimitive_getBuffer},
459 { Py_bf_releasebuffer, (void*) &PyJPArray_releaseBuffer},
460 #endif
461 {0}
462 };
463
464 PyTypeObject *PyJPArrayPrimitive_Type = nullptr;
465 static PyType_Spec arrayPrimSpec = {
466 "_jpype._JArrayPrimitive",
467 0,
468 0,
469 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
470 arrayPrimSlots
471 };
472
473 #ifdef __cplusplus
474 }
475 #endif
476
477 void PyJPArray_initType(PyObject * module)
478 {
479 JPPyObject tuple = JPPyTuple_Pack(PyJPObject_Type);
480 PyJPArray_Type = (PyTypeObject*) PyJPClass_FromSpecWithBases(&arraySpec, tuple.get());
481 JP_PY_CHECK();
482 #if PY_VERSION_HEX < 0x03090000
483 PyJPArray_Type->tp_as_buffer = &arrayBuffer;
484 #endif
485 PyModule_AddObject(module, "_JArray", (PyObject*) PyJPArray_Type);
486 JP_PY_CHECK();
487
488 tuple = JPPyTuple_Pack(PyJPArray_Type);
489 PyJPArrayPrimitive_Type = (PyTypeObject*)
490 PyJPClass_FromSpecWithBases(&arrayPrimSpec, tuple.get());
491 #if PY_VERSION_HEX < 0x03090000
492 PyJPArrayPrimitive_Type->tp_as_buffer = &arrayPrimBuffer;
493 #endif
494 JP_PY_CHECK();
495 PyModule_AddObject(module, "_JArrayPrimitive",
496 (PyObject*) PyJPArrayPrimitive_Type);
497 JP_PY_CHECK();
498 }
499
500 JPPyObject PyJPArray_create(JPJavaFrame &frame, PyTypeObject *type, const JPValue & value)
501 {
502 PyObject *obj = type->tp_alloc(type, 0);
503 JP_PY_CHECK();
504 ((PyJPArray*) obj)->m_Array = new JPArray(value);
505 PyJPValue_assignJavaSlot(frame, obj, value);
506 return JPPyObject::claim(obj);
507 }