Debian Codegraph @

pypy/module/cpyext/test/buffer_test.c

raw symbols SCIP
1 #ifdef _MSC_VER
2 #define _CRT_SECURE_NO_WARNINGS 1
3 #endif
4 #include <Python.h>
5 #include <stdlib.h>
6 #include <stdio.h>
7
8 /*
9 * Adapted from https://jakevdp.github.io/blog/2014/05/05/introduction-to-the-python-buffer-protocol,
10 * which is copyright Jake Vanderplas and released under the BSD license
11 */
12
13 /* Structure defines a 1-dimensional strided array */
14 typedef struct{
15 int* arr;
16 Py_ssize_t length;
17 } MyArray;
18
19 /* initialize the array with integers 0...length */
20 void initialize_MyArray(MyArray* a, long length){
21 int i;
22 a->length = length;
23 a->arr = (int*)malloc(length * sizeof(int));
24 for(i=0; i<length; i++){
25 a->arr[i] = i;
26 }
27 }
28
29 /* free the memory when finished */
30 void deallocate_MyArray(MyArray* a){
31 free(a->arr);
32 a->arr = NULL;
33 }
34
35 /* tools to print the array */
36 char* stringify(MyArray* a, int nmax){
37 char* output = (char*) malloc(nmax * 20);
38 int k, pos = sprintf(&output[0], "[");
39
40 for (k=0; k < a->length && k < nmax; k++){
41 pos += sprintf(&output[pos], " %d", a->arr[k]);
42 }
43 if(a->length > nmax)
44 pos += sprintf(&output[pos], "...");
45 sprintf(&output[pos], " ]");
46 return output;
47 }
48
49 void print_MyArray(MyArray* a, int nmax){
50 char* s = stringify(a, nmax);
51 printf("%s", s);
52 free(s);
53 }
54
55 /* This is where we define the PyMyArray object structure */
56 typedef struct {
57 PyObject_HEAD
58 /* Type-specific fields go below. */
59 MyArray arr;
60 } PyMyArray;
61
62
63 /* This is the __init__ function, implemented in C */
64 static int
65 PyMyArray_init(PyMyArray *self, PyObject *args, PyObject *kwds)
66 {
67 int length = 0;
68 static char *kwlist[] = {"length", NULL};
69 // init may have already been called
70 if (self->arr.arr != NULL) {
71 deallocate_MyArray(&self->arr);
72 }
73
74 if (! PyArg_ParseTupleAndKeywords(args, kwds, "|i", kwlist, &length))
75 return -1;
76
77 if (length < 0)
78 length = 0;
79
80 initialize_MyArray(&self->arr, length);
81
82 return 0;
83 }
84
85
86 /* this function is called when the object is deallocated */
87 static void
88 PyMyArray_dealloc(PyMyArray* self)
89 {
90 deallocate_MyArray(&self->arr);
91 Py_TYPE(self)->tp_free((PyObject*)self);
92 }
93
94
95 /* This function returns the string representation of our object */
96 static PyObject *
97 PyMyArray_str(PyMyArray * self)
98 {
99 char* s = stringify(&self->arr, 10);
100 PyObject* ret = PyUnicode_FromString(s);
101 free(s);
102 return ret;
103 }
104
105 /* Here is the buffer interface function */
106 static int
107 PyMyArray_getbuffer(PyObject *obj, Py_buffer *view, int flags)
108 {
109 PyMyArray* self = (PyMyArray*)obj;
110 if (view == NULL) {
111 PyErr_SetString(PyExc_ValueError, "NULL view in getbuffer");
112 return -1;
113 }
114 if (flags == 0) {
115 PyErr_SetString(PyExc_ValueError, "flags == 0 in getbuffer");
116 return -1;
117 }
118
119 view->obj = (PyObject*)self;
120 view->buf = (void*)self->arr.arr;
121 view->len = self->arr.length * sizeof(int);
122 view->readonly = 0;
123 view->itemsize = sizeof(int);
124 view->format = "i"; // integer
125 view->ndim = 1;
126 view->shape = &self->arr.length; // length-1 sequence of dimensions
127 view->strides = &view->itemsize; // for the simple case we can do this
128 view->suboffsets = NULL;
129 view->internal = NULL;
130
131 Py_INCREF(self); // need to increase the reference count
132 return 0;
133 }
134
135 static PyBufferProcs PyMyArray_as_buffer = {
136 #if PY_MAJOR_VERSION < 3
137 (readbufferproc)0,
138 (writebufferproc)0,
139 (segcountproc)0,
140 (charbufferproc)0,
141 #endif
142 (getbufferproc)PyMyArray_getbuffer,
143 (releasebufferproc)0, // we do not require any special release function
144 };
145
146
147 /* Here is the type structure: we put the above functions in the appropriate place
148 in order to actually define the Python object type */
149 static PyTypeObject PyMyArrayType = {
150 PyVarObject_HEAD_INIT(NULL, 0)
151 "pymyarray.PyMyArray", /* tp_name */
152 sizeof(PyMyArray), /* tp_basicsize */
153 0, /* tp_itemsize */
154 (destructor)PyMyArray_dealloc,/* tp_dealloc */
155 0, /* tp_print */
156 0, /* tp_getattr */
157 0, /* tp_setattr */
158 0, /* tp_reserved */
159 (reprfunc)PyMyArray_str, /* tp_repr */
160 0, /* tp_as_number */
161 0, /* tp_as_sequence */
162 0, /* tp_as_mapping */
163 0, /* tp_hash */
164 0, /* tp_call */
165 (reprfunc)PyMyArray_str, /* tp_str */
166 0, /* tp_getattro */
167 0, /* tp_setattro */
168 &PyMyArray_as_buffer, /* tp_as_buffer */
169 Py_TPFLAGS_DEFAULT, /* tp_flags */
170 "PyMyArray object", /* tp_doc */
171 0, /* tp_traverse */
172 0, /* tp_clear */
173 0, /* tp_richcompare */
174 0, /* tp_weaklistoffset */
175 0, /* tp_iter */
176 0, /* tp_iternext */
177 0, /* tp_methods */
178 0, /* tp_members */
179 0, /* tp_getset */
180 0, /* tp_base */
181 0, /* tp_dict */
182 0, /* tp_descr_get */
183 0, /* tp_descr_set */
184 0, /* tp_dictoffset */
185 (initproc)PyMyArray_init, /* tp_init */
186 };
187
188 /* Copied from numpy tests */
189 /*
190 * Create python string from a FLAG and or the corresponding PyBuf flag
191 * for the use in get_buffer_info.
192 */
193 #define GET_PYBUF_FLAG(FLAG) \
194 buf_flag = PyUnicode_FromString(#FLAG); \
195 if (buf_flag == NULL) { \
196 Py_DECREF(tmp); \
197 return NULL; \
198 } \
199 flag_matches = PyObject_RichCompareBool(buf_flag, tmp, Py_EQ); \
200 Py_DECREF(buf_flag); \
201 if (flag_matches == 1) { \
202 Py_DECREF(tmp); \
203 flags |= PyBUF_##FLAG; \
204 continue; \
205 } \
206 else if (flag_matches == -1) { \
207 Py_DECREF(tmp); \
208 return NULL; \
209 }
210
211
212 /*
213 * Get information for a buffer through PyBuf_GetBuffer with the
214 * corresponding flags or'ed. Note that the python caller has to
215 * make sure that or'ing those flags actually makes sense.
216 * More information should probably be returned for future tests.
217 */
218 static PyObject *
219 get_buffer_info(PyObject *self, PyObject *args)
220 {
221 PyObject *buffer_obj, *pyflags;
222 PyObject *tmp, *buf_flag;
223 Py_buffer buffer;
224 PyObject *shape, *strides;
225 Py_ssize_t i, n;
226 int flag_matches;
227 int flags = 0;
228
229 if (!PyArg_ParseTuple(args, "OO", &buffer_obj, &pyflags)) {
230 return NULL;
231 }
232
233 n = PySequence_Length(pyflags);
234 if (n < 0) {
235 return NULL;
236 }
237
238 for (i=0; i < n; i++) {
239 tmp = PySequence_GetItem(pyflags, i);
240 if (tmp == NULL) {
241 return NULL;
242 }
243
244 GET_PYBUF_FLAG(SIMPLE);
245 GET_PYBUF_FLAG(WRITABLE);
246 GET_PYBUF_FLAG(STRIDES);
247 GET_PYBUF_FLAG(ND);
248 GET_PYBUF_FLAG(C_CONTIGUOUS);
249 GET_PYBUF_FLAG(F_CONTIGUOUS);
250 GET_PYBUF_FLAG(ANY_CONTIGUOUS);
251 GET_PYBUF_FLAG(INDIRECT);
252 GET_PYBUF_FLAG(FORMAT);
253 GET_PYBUF_FLAG(STRIDED);
254 GET_PYBUF_FLAG(STRIDED_RO);
255 GET_PYBUF_FLAG(RECORDS);
256 GET_PYBUF_FLAG(RECORDS_RO);
257 GET_PYBUF_FLAG(FULL);
258 GET_PYBUF_FLAG(FULL_RO);
259 GET_PYBUF_FLAG(CONTIG);
260 GET_PYBUF_FLAG(CONTIG_RO);
261
262 Py_DECREF(tmp);
263
264 /* One of the flags must match */
265 PyErr_SetString(PyExc_ValueError, "invalid flag used.");
266 return NULL;
267 }
268
269 if (PyObject_GetBuffer(buffer_obj, &buffer, flags) < 0) {
270 return NULL;
271 }
272
273 if (buffer.shape == NULL) {
274 Py_INCREF(Py_None);
275 shape = Py_None;
276 }
277 else {
278 shape = PyTuple_New(buffer.ndim);
279 for (i=0; i < buffer.ndim; i++) {
280 PyTuple_SET_ITEM(shape, i, PyLong_FromSsize_t(buffer.shape[i]));
281 }
282 }
283
284 if (buffer.strides == NULL) {
285 Py_INCREF(Py_None);
286 strides = Py_None;
287 }
288 else {
289 strides = PyTuple_New(buffer.ndim);
290 for (i=0; i < buffer.ndim; i++) {
291 PyTuple_SET_ITEM(strides, i, PyLong_FromSsize_t(buffer.strides[i]));
292 }
293 }
294
295 PyBuffer_Release(&buffer);
296 return Py_BuildValue("(NN)", shape, strides);
297 }
298
299
300
301 static PyMethodDef buffer_functions[] = {
302 {"get_buffer_info", (PyCFunction)get_buffer_info, METH_VARARGS, NULL},
303 {NULL, NULL} /* Sentinel */
304 };
305
306 #if PY_MAJOR_VERSION >= 3
307 static struct PyModuleDef moduledef = {
308 PyModuleDef_HEAD_INIT,
309 "buffer_test",
310 "Module Doc",
311 -1,
312 buffer_functions,
313 NULL,
314 NULL,
315 NULL,
316 NULL,
317 };
318 #define INITERROR return NULL
319
320 /* Initialize this module. */
321 #ifdef __GNUC__
322 extern __attribute__((visibility("default")))
323 #else
324 extern __declspec(dllexport)
325 #endif
326
327 PyMODINIT_FUNC
328 PyInit_buffer_test(void)
329
330 #else
331
332 #define INITERROR return
333
334 /* Initialize this module. */
335 #ifdef __GNUC__
336 extern __attribute__((visibility("default")))
337 #else
338 #endif
339
340 PyMODINIT_FUNC
341 initbuffer_test(void)
342 #endif
343 {
344 #if PY_MAJOR_VERSION >= 3
345 PyObject *m= PyModule_Create(&moduledef);
346 #else
347 PyObject *m= Py_InitModule("buffer_test", buffer_functions);
348 #endif
349 if (m == NULL)
350 INITERROR;
351 PyMyArrayType.tp_new = PyType_GenericNew;
352 if (PyType_Ready(&PyMyArrayType) < 0)
353 INITERROR;
354 Py_INCREF(&PyMyArrayType);
355 PyModule_AddObject(m, "PyMyArray", (PyObject *)&PyMyArrayType);
356 #if PY_MAJOR_VERSION >=3
357 return m;
358 #endif
359 }