1 #define PY_SSIZE_T_CLEAN
2 #include <Python.h>
3 #include "structmember.h"
4 
5 #define NPY_NO_DEPRECATED_API NPY_API_VERSION
6 #define _MULTIARRAYMODULE
7 #include "numpy/arrayobject.h"
8 #include "numpy/arrayscalars.h"
9 
10 #include "numpy/npy_math.h"
11 
12 #include "npy_config.h"
13 
14 #include "npy_ctypes.h"
15 #include "npy_pycompat.h"
16 #include "multiarraymodule.h"
17 
18 #include "common.h"
19 #include "ctors.h"
20 #include "convert_datatype.h"
21 #include "shape.h"
22 #include "npy_buffer.h"
23 #include "lowlevel_strided_loops.h"
24 #include "_datetime.h"
25 #include "datetime_strings.h"
26 #include "array_assign.h"
27 #include "mapping.h" /* for array_item_asarray */
28 #include "templ_common.h" /* for npy_mul_with_overflow_intp */
29 #include "alloc.h"
30 #include <assert.h>
31 
32 #include "get_attr_string.h"
33 #include "array_coercion.h"
34 
35 /*
36  * Reading from a file or a string.
37  *
38  * As much as possible, we try to use the same code for both files and strings,
39  * so the semantics for fromstring and fromfile are the same, especially with
40  * regards to the handling of text representations.
41  */
42 
43 /*
44  * Scanning function for next element parsing and separator skipping.
45  * These functions return:
46  *   - 0 to indicate more data to read
47  *   - -1 when reading stopped at the end of the string/file
48  *   - -2 when reading stopped before the end was reached.
49  *
50  * The dtype specific parsing functions may set the python error state
51  * (they have to get the GIL first) additionally.
52  */
53 typedef int (*next_element)(void **, void *, PyArray_Descr *, void *);
54 typedef int (*skip_separator)(void **, const char *, void *);
55 
56 
57 static npy_bool
string_is_fully_read(char const * start,char const * end)58 string_is_fully_read(char const* start, char const* end) {
59     if (end == NULL) {
60         return *start == '\0';  /* null terminated */
61     }
62     else {
63         return start >= end;  /* fixed length */
64     }
65 }
66 
67 
68 static int
fromstr_next_element(char ** s,void * dptr,PyArray_Descr * dtype,const char * end)69 fromstr_next_element(char **s, void *dptr, PyArray_Descr *dtype,
70                      const char *end)
71 {
72     char *e = *s;
73     int r = dtype->f->fromstr(*s, dptr, &e, dtype);
74     /*
75      * fromstr always returns 0 for basic dtypes; s points to the end of the
76      * parsed string. If s is not changed an error occurred or the end was
77      * reached.
78      */
79     if (*s == e || r < 0) {
80         /* Nothing read, could be end of string or an error (or both) */
81         if (string_is_fully_read(*s, end)) {
82             return -1;
83         }
84         return -2;
85     }
86     *s = e;
87     if (end != NULL && *s > end) {
88         /* Stop the iteration if we read far enough */
89         return -1;
90     }
91     return 0;
92 }
93 
94 static int
fromfile_next_element(FILE ** fp,void * dptr,PyArray_Descr * dtype,void * NPY_UNUSED (stream_data))95 fromfile_next_element(FILE **fp, void *dptr, PyArray_Descr *dtype,
96                       void *NPY_UNUSED(stream_data))
97 {
98     /* the NULL argument is for backwards-compatibility */
99     int r = dtype->f->scanfunc(*fp, dptr, NULL, dtype);
100     /* r can be EOF or the number of items read (0 or 1) */
101     if (r == 1) {
102         return 0;
103     }
104     else if (r == EOF) {
105         return -1;
106     }
107     else {
108         /* unable to read more, but EOF not reached indicating an error. */
109         return -2;
110     }
111 }
112 
113 /*
114  * Remove multiple whitespace from the separator, and add a space to the
115  * beginning and end. This simplifies the separator-skipping code below.
116  */
117 static char *
swab_separator(const char * sep)118 swab_separator(const char *sep)
119 {
120     int skip_space = 0;
121     char *s, *start;
122 
123     s = start = malloc(strlen(sep)+3);
124     if (s == NULL) {
125         PyErr_NoMemory();
126         return NULL;
127     }
128     /* add space to front if there isn't one */
129     if (*sep != '\0' && !isspace(*sep)) {
130         *s = ' '; s++;
131     }
132     while (*sep != '\0') {
133         if (isspace(*sep)) {
134             if (skip_space) {
135                 sep++;
136             }
137             else {
138                 *s = ' ';
139                 s++;
140                 sep++;
141                 skip_space = 1;
142             }
143         }
144         else {
145             *s = *sep;
146             s++;
147             sep++;
148             skip_space = 0;
149         }
150     }
151     /* add space to end if there isn't one */
152     if (s != start && s[-1] == ' ') {
153         *s = ' ';
154         s++;
155     }
156     *s = '\0';
157     return start;
158 }
159 
160 /*
161  * Assuming that the separator is the next bit in the string (file), skip it.
162  *
163  * Single spaces in the separator are matched to arbitrary-long sequences
164  * of whitespace in the input. If the separator consists only of spaces,
165  * it matches one or more whitespace characters.
166  *
167  * If we can't match the separator, return -2.
168  * If we hit the end of the string (file), return -1.
169  * Otherwise, return 0.
170  */
171 static int
fromstr_skip_separator(char ** s,const char * sep,const char * end)172 fromstr_skip_separator(char **s, const char *sep, const char *end)
173 {
174     char *string = *s;
175     int result = 0;
176 
177     while (1) {
178         char c = *string;
179         if (string_is_fully_read(string, end)) {
180             result = -1;
181             break;
182         }
183         else if (*sep == '\0') {
184             if (string != *s) {
185                 /* matched separator */
186                 result = 0;
187                 break;
188             }
189             else {
190                 /* separator was whitespace wildcard that didn't match */
191                 result = -2;
192                 break;
193             }
194         }
195         else if (*sep == ' ') {
196             /* whitespace wildcard */
197             if (!isspace(c)) {
198                 sep++;
199                 continue;
200             }
201         }
202         else if (*sep != c) {
203             result = -2;
204             break;
205         }
206         else {
207             sep++;
208         }
209         string++;
210     }
211     *s = string;
212     return result;
213 }
214 
215 static int
fromfile_skip_separator(FILE ** fp,const char * sep,void * NPY_UNUSED (stream_data))216 fromfile_skip_separator(FILE **fp, const char *sep, void *NPY_UNUSED(stream_data))
217 {
218     int result = 0;
219     const char *sep_start = sep;
220 
221     while (1) {
222         int c = fgetc(*fp);
223 
224         if (c == EOF) {
225             result = -1;
226             break;
227         }
228         else if (*sep == '\0') {
229             ungetc(c, *fp);
230             if (sep != sep_start) {
231                 /* matched separator */
232                 result = 0;
233                 break;
234             }
235             else {
236                 /* separator was whitespace wildcard that didn't match */
237                 result = -2;
238                 break;
239             }
240         }
241         else if (*sep == ' ') {
242             /* whitespace wildcard */
243             if (!isspace(c)) {
244                 sep++;
245                 sep_start++;
246                 ungetc(c, *fp);
247             }
248             else if (sep == sep_start) {
249                 sep_start--;
250             }
251         }
252         else if (*sep != c) {
253             ungetc(c, *fp);
254             result = -2;
255             break;
256         }
257         else {
258             sep++;
259         }
260     }
261     return result;
262 }
263 
264 /*
265  * Change a sub-array field to the base descriptor
266  * and update the dimensions and strides
267  * appropriately.  Dimensions and strides are added
268  * to the end.
269  *
270  * Strides are only added if given (because data is given).
271  */
272 static int
_update_descr_and_dimensions(PyArray_Descr ** des,npy_intp * newdims,npy_intp * newstrides,int oldnd)273 _update_descr_and_dimensions(PyArray_Descr **des, npy_intp *newdims,
274                              npy_intp *newstrides, int oldnd)
275 {
276     PyArray_Descr *old;
277     int newnd;
278     int numnew;
279     npy_intp *mydim;
280     int i;
281     int tuple;
282 
283     old = *des;
284     *des = old->subarray->base;
285 
286 
287     mydim = newdims + oldnd;
288     tuple = PyTuple_Check(old->subarray->shape);
289     if (tuple) {
290         numnew = PyTuple_GET_SIZE(old->subarray->shape);
291     }
292     else {
293         numnew = 1;
294     }
295 
296 
297     newnd = oldnd + numnew;
298     if (newnd > NPY_MAXDIMS) {
299         goto finish;
300     }
301     if (tuple) {
302         for (i = 0; i < numnew; i++) {
303             mydim[i] = (npy_intp) PyLong_AsLong(
304                     PyTuple_GET_ITEM(old->subarray->shape, i));
305         }
306     }
307     else {
308         mydim[0] = (npy_intp) PyLong_AsLong(old->subarray->shape);
309     }
310 
311     if (newstrides) {
312         npy_intp tempsize;
313         npy_intp *mystrides;
314 
315         mystrides = newstrides + oldnd;
316         /* Make new strides -- always C-contiguous */
317         tempsize = (*des)->elsize;
318         for (i = numnew - 1; i >= 0; i--) {
319             mystrides[i] = tempsize;
320             tempsize *= mydim[i] ? mydim[i] : 1;
321         }
322     }
323 
324  finish:
325     Py_INCREF(*des);
326     Py_DECREF(old);
327     return newnd;
328 }
329 
330 NPY_NO_EXPORT void
_unaligned_strided_byte_copy(char * dst,npy_intp outstrides,char * src,npy_intp instrides,npy_intp N,int elsize)331 _unaligned_strided_byte_copy(char *dst, npy_intp outstrides, char *src,
332                              npy_intp instrides, npy_intp N, int elsize)
333 {
334     npy_intp i;
335     char *tout = dst;
336     char *tin = src;
337 
338 #define _COPY_N_SIZE(size) \
339     for(i=0; i<N; i++) { \
340         memcpy(tout, tin, size); \
341         tin += instrides; \
342         tout += outstrides; \
343     } \
344     return
345 
346     switch(elsize) {
347     case 8:
348         _COPY_N_SIZE(8);
349     case 4:
350         _COPY_N_SIZE(4);
351     case 1:
352         _COPY_N_SIZE(1);
353     case 2:
354         _COPY_N_SIZE(2);
355     case 16:
356         _COPY_N_SIZE(16);
357     default:
358         _COPY_N_SIZE(elsize);
359     }
360 #undef _COPY_N_SIZE
361 
362 }
363 
364 NPY_NO_EXPORT void
_strided_byte_swap(void * p,npy_intp stride,npy_intp n,int size)365 _strided_byte_swap(void *p, npy_intp stride, npy_intp n, int size)
366 {
367     char *a, *b, c = 0;
368     int j, m;
369 
370     switch(size) {
371     case 1: /* no byteswap necessary */
372         break;
373     case 4:
374         if (npy_is_aligned((void*)((npy_intp)p | stride), sizeof(npy_uint32))) {
375             for (a = (char*)p; n > 0; n--, a += stride) {
376                 npy_uint32 * a_ = (npy_uint32 *)a;
377                 *a_ = npy_bswap4(*a_);
378             }
379         }
380         else {
381             for (a = (char*)p; n > 0; n--, a += stride) {
382                 npy_bswap4_unaligned(a);
383             }
384         }
385         break;
386     case 8:
387         if (npy_is_aligned((void*)((npy_intp)p | stride), sizeof(npy_uint64))) {
388             for (a = (char*)p; n > 0; n--, a += stride) {
389                 npy_uint64 * a_ = (npy_uint64 *)a;
390                 *a_ = npy_bswap8(*a_);
391             }
392         }
393         else {
394             for (a = (char*)p; n > 0; n--, a += stride) {
395                 npy_bswap8_unaligned(a);
396             }
397         }
398         break;
399     case 2:
400         if (npy_is_aligned((void*)((npy_intp)p | stride), sizeof(npy_uint16))) {
401             for (a = (char*)p; n > 0; n--, a += stride) {
402                 npy_uint16 * a_ = (npy_uint16 *)a;
403                 *a_ = npy_bswap2(*a_);
404             }
405         }
406         else {
407             for (a = (char*)p; n > 0; n--, a += stride) {
408                 npy_bswap2_unaligned(a);
409             }
410         }
411         break;
412     default:
413         m = size/2;
414         for (a = (char *)p; n > 0; n--, a += stride - m) {
415             b = a + (size - 1);
416             for (j = 0; j < m; j++) {
417                 c=*a; *a++ = *b; *b-- = c;
418             }
419         }
420         break;
421     }
422 }
423 
424 NPY_NO_EXPORT void
byte_swap_vector(void * p,npy_intp n,int size)425 byte_swap_vector(void *p, npy_intp n, int size)
426 {
427     _strided_byte_swap(p, (npy_intp) size, n, size);
428     return;
429 }
430 
431 /* If numitems > 1, then dst must be contiguous */
432 NPY_NO_EXPORT void
copy_and_swap(void * dst,void * src,int itemsize,npy_intp numitems,npy_intp srcstrides,int swap)433 copy_and_swap(void *dst, void *src, int itemsize, npy_intp numitems,
434               npy_intp srcstrides, int swap)
435 {
436     if ((numitems == 1) || (itemsize == srcstrides)) {
437         memcpy(dst, src, itemsize*numitems);
438     }
439     else {
440         npy_intp i;
441         char *s1 = (char *)src;
442         char *d1 = (char *)dst;
443 
444         for (i = 0; i < numitems; i++) {
445             memcpy(d1, s1, itemsize);
446             d1 += itemsize;
447             s1 += srcstrides;
448         }
449     }
450 
451     if (swap) {
452         byte_swap_vector(dst, numitems, itemsize);
453     }
454 }
455 
456 
457 /*
458  * Recursive helper to assign using a coercion cache. This function
459  * must consume the cache depth first, just as the cache was originally
460  * produced.
461  */
462 NPY_NO_EXPORT int
PyArray_AssignFromCache_Recursive(PyArrayObject * self,const int ndim,coercion_cache_obj ** cache)463 PyArray_AssignFromCache_Recursive(
464         PyArrayObject *self, const int ndim, coercion_cache_obj **cache)
465 {
466     /* Consume first cache element by extracting information and freeing it */
467     PyObject *original_obj = (*cache)->converted_obj;
468     PyObject *obj = (*cache)->arr_or_sequence;
469     Py_INCREF(obj);
470     npy_bool sequence = (*cache)->sequence;
471     int depth = (*cache)->depth;
472     *cache = npy_unlink_coercion_cache(*cache);
473 
474     /*
475      * The maximum depth is special (specifically for objects), but usually
476      * unrolled in the sequence branch below.
477      */
478     if (NPY_UNLIKELY(depth == ndim)) {
479         /*
480          * We have reached the maximum depth. We should simply assign to the
481          * element in principle. There is one exception. If this is a 0-D
482          * array being stored into a 0-D array (but we do not reach here then).
483          */
484         if (PyArray_ISOBJECT(self)) {
485             assert(ndim != 0);  /* guaranteed by PyArray_AssignFromCache */
486             assert(PyArray_NDIM(self) == 0);
487             Py_DECREF(obj);
488             return PyArray_Pack(PyArray_DESCR(self), PyArray_BYTES(self),
489                                 original_obj);
490         }
491         if (sequence) {
492             /*
493              * Sanity check which may be removed, the error is raised already
494              * in `PyArray_DiscoverDTypeAndShape`.
495              */
496             assert(0);
497             PyErr_SetString(PyExc_RuntimeError,
498                     "setting an array element with a sequence");
499             goto fail;
500         }
501         else if (original_obj != obj || !PyArray_CheckExact(obj)) {
502             /*
503              * If the leave node is an array-like, but not a numpy array,
504              * we pretend it is an arbitrary scalar.  This means that in
505              * most cases (where the dtype is int or float), we will end
506              * up using float(array-like), or int(array-like).  That does
507              * not support general casting, but helps Quantity and masked
508              * arrays, because it allows them to raise an error when
509              * `__float__()` or `__int__()` is called.
510              */
511             Py_DECREF(obj);
512             return PyArray_SETITEM(self, PyArray_BYTES(self), original_obj);
513         }
514     }
515 
516     /* The element is either a sequence, or an array */
517     if (!sequence) {
518         /* Straight forward array assignment */
519         assert(PyArray_Check(obj));
520         if (PyArray_CopyInto(self, (PyArrayObject *)obj) < 0) {
521             goto fail;
522         }
523     }
524     else {
525         assert(depth != ndim);
526         npy_intp length = PySequence_Length(obj);
527         if (length != PyArray_DIMS(self)[0]) {
528             PyErr_SetString(PyExc_RuntimeError,
529                     "Inconsistent object during array creation? "
530                     "Content of sequences changed (length inconsistent).");
531             goto fail;
532         }
533 
534         for (npy_intp i = 0; i < length; i++) {
535             PyObject *value = PySequence_Fast_GET_ITEM(obj, i);
536 
537             if (*cache == NULL || (*cache)->converted_obj != value ||
538                         (*cache)->depth != depth + 1) {
539                 if (ndim != depth + 1) {
540                     PyErr_SetString(PyExc_RuntimeError,
541                             "Inconsistent object during array creation? "
542                             "Content of sequences changed (now too shallow).");
543                     goto fail;
544                 }
545                 /* Straight forward assignment of elements */
546                 char *item;
547                 item = (PyArray_BYTES(self) + i * PyArray_STRIDES(self)[0]);
548                 if (PyArray_Pack(PyArray_DESCR(self), item, value) < 0) {
549                     goto fail;
550                 }
551             }
552             else {
553                 PyArrayObject *view;
554                 view = (PyArrayObject *)array_item_asarray(self, i);
555                 if (view == NULL) {
556                     goto fail;
557                 }
558                 if (PyArray_AssignFromCache_Recursive(view, ndim, cache) < 0) {
559                     Py_DECREF(view);
560                     goto fail;
561                 }
562                 Py_DECREF(view);
563             }
564         }
565     }
566     Py_DECREF(obj);
567     return 0;
568 
569   fail:
570     Py_DECREF(obj);
571     return -1;
572 }
573 
574 
575 /**
576  * Fills an item based on a coercion cache object. It consumes the cache
577  * object while doing so.
578  *
579  * @param self Array to fill.
580  * @param cache coercion_cache_object, will be consumed. The cache must not
581  *        contain a single array (must start with a sequence). The array case
582  *        should be handled by `PyArray_FromArray()` before.
583  * @return 0 on success -1 on failure.
584  */
585 NPY_NO_EXPORT int
PyArray_AssignFromCache(PyArrayObject * self,coercion_cache_obj * cache)586 PyArray_AssignFromCache(PyArrayObject *self, coercion_cache_obj *cache) {
587     int ndim = PyArray_NDIM(self);
588     /*
589      * Do not support ndim == 0 now with an array in the cache.
590      * The ndim == 0 is special because np.array(np.array(0), dtype=object)
591      * should unpack the inner array.
592      * Since the single-array case is special, it is handled previously
593      * in either case.
594      */
595     assert(cache->sequence);
596     assert(ndim != 0);  /* guaranteed if cache contains a sequence */
597 
598     if (PyArray_AssignFromCache_Recursive(self, ndim, &cache) < 0) {
599         /* free the remaining cache. */
600         npy_free_coercion_cache(cache);
601         return -1;
602     }
603 
604     /*
605      * Sanity check, this is the initial call, and when it returns, the
606      * cache has to be fully consumed, otherwise something is wrong.
607      * NOTE: May be nicer to put into a recursion helper.
608      */
609     if (cache != NULL) {
610         PyErr_SetString(PyExc_RuntimeError,
611                 "Inconsistent object during array creation? "
612                 "Content of sequences changed (cache not consumed).");
613         npy_free_coercion_cache(cache);
614         return -1;
615     }
616     return 0;
617 }
618 
619 
620 static void
raise_memory_error(int nd,npy_intp const * dims,PyArray_Descr * descr)621 raise_memory_error(int nd, npy_intp const *dims, PyArray_Descr *descr)
622 {
623     static PyObject *exc_type = NULL;
624 
625     npy_cache_import(
626         "numpy.core._exceptions", "_ArrayMemoryError",
627         &exc_type);
628     if (exc_type == NULL) {
629         goto fail;
630     }
631 
632     PyObject *shape = PyArray_IntTupleFromIntp(nd, dims);
633     if (shape == NULL) {
634         goto fail;
635     }
636 
637     /* produce an error object */
638     PyObject *exc_value = PyTuple_Pack(2, shape, (PyObject *)descr);
639     Py_DECREF(shape);
640     if (exc_value == NULL){
641         goto fail;
642     }
643     PyErr_SetObject(exc_type, exc_value);
644     Py_DECREF(exc_value);
645     return;
646 
647 fail:
648     /* we couldn't raise the formatted exception for some reason */
649     PyErr_WriteUnraisable(NULL);
650     PyErr_NoMemory();
651 }
652 
653 /*
654  * Generic new array creation routine.
655  * Internal variant with calloc argument for PyArray_Zeros.
656  *
657  * steals a reference to descr. On failure or descr->subarray, descr will
658  * be decrefed.
659  */
660 NPY_NO_EXPORT PyObject *
PyArray_NewFromDescr_int(PyTypeObject * subtype,PyArray_Descr * descr,int nd,npy_intp const * dims,npy_intp const * strides,void * data,int flags,PyObject * obj,PyObject * base,int zeroed,int allow_emptystring)661 PyArray_NewFromDescr_int(
662         PyTypeObject *subtype, PyArray_Descr *descr, int nd,
663         npy_intp const *dims, npy_intp const *strides, void *data,
664         int flags, PyObject *obj, PyObject *base, int zeroed,
665         int allow_emptystring)
666 {
667     PyArrayObject_fields *fa;
668     int i;
669     npy_intp nbytes;
670 
671     if (descr->subarray) {
672         PyObject *ret;
673         npy_intp newdims[2*NPY_MAXDIMS];
674         npy_intp *newstrides = NULL;
675         memcpy(newdims, dims, nd*sizeof(npy_intp));
676         if (strides) {
677             newstrides = newdims + NPY_MAXDIMS;
678             memcpy(newstrides, strides, nd*sizeof(npy_intp));
679         }
680         nd =_update_descr_and_dimensions(&descr, newdims,
681                                          newstrides, nd);
682         ret = PyArray_NewFromDescr_int(
683                 subtype, descr,
684                 nd, newdims, newstrides, data,
685                 flags, obj, base,
686                 zeroed, allow_emptystring);
687         return ret;
688     }
689 
690     if ((unsigned int)nd > (unsigned int)NPY_MAXDIMS) {
691         PyErr_Format(PyExc_ValueError,
692                      "number of dimensions must be within [0, %d]",
693                      NPY_MAXDIMS);
694         Py_DECREF(descr);
695         return NULL;
696     }
697 
698     /* Check datatype element size */
699     nbytes = descr->elsize;
700     if (PyDataType_ISUNSIZED(descr)) {
701         if (!PyDataType_ISFLEXIBLE(descr)) {
702             PyErr_SetString(PyExc_TypeError, "Empty data-type");
703             Py_DECREF(descr);
704             return NULL;
705         }
706         else if (PyDataType_ISSTRING(descr) && !allow_emptystring &&
707                  data == NULL) {
708             PyArray_DESCR_REPLACE(descr);
709             if (descr == NULL) {
710                 return NULL;
711             }
712             if (descr->type_num == NPY_STRING) {
713                 nbytes = descr->elsize = 1;
714             }
715             else {
716                 nbytes = descr->elsize = sizeof(npy_ucs4);
717             }
718         }
719     }
720 
721     /* Check dimensions and multiply them to nbytes */
722     for (i = 0; i < nd; i++) {
723         npy_intp dim = dims[i];
724 
725         if (dim == 0) {
726             /*
727              * Compare to PyArray_OverflowMultiplyList that
728              * returns 0 in this case.
729              */
730             continue;
731         }
732 
733         if (dim < 0) {
734             PyErr_SetString(PyExc_ValueError,
735                 "negative dimensions are not allowed");
736             Py_DECREF(descr);
737             return NULL;
738         }
739 
740         /*
741          * Care needs to be taken to avoid integer overflow when
742          * multiplying the dimensions together to get the total size of the
743          * array.
744          */
745         if (npy_mul_with_overflow_intp(&nbytes, nbytes, dim)) {
746             PyErr_SetString(PyExc_ValueError,
747                 "array is too big; `arr.size * arr.dtype.itemsize` "
748                 "is larger than the maximum possible size.");
749             Py_DECREF(descr);
750             return NULL;
751         }
752     }
753 
754     fa = (PyArrayObject_fields *) subtype->tp_alloc(subtype, 0);
755     if (fa == NULL) {
756         Py_DECREF(descr);
757         return NULL;
758     }
759     fa->_buffer_info = NULL;
760     fa->nd = nd;
761     fa->dimensions = NULL;
762     fa->data = NULL;
763 
764     if (data == NULL) {
765         fa->flags = NPY_ARRAY_DEFAULT;
766         if (flags) {
767             fa->flags |= NPY_ARRAY_F_CONTIGUOUS;
768             if (nd > 1) {
769                 fa->flags &= ~NPY_ARRAY_C_CONTIGUOUS;
770             }
771             flags = NPY_ARRAY_F_CONTIGUOUS;
772         }
773     }
774     else {
775         fa->flags = (flags & ~NPY_ARRAY_WRITEBACKIFCOPY);
776         fa->flags &= ~NPY_ARRAY_UPDATEIFCOPY;
777     }
778     fa->descr = descr;
779     fa->base = (PyObject *)NULL;
780     fa->weakreflist = (PyObject *)NULL;
781 
782     if (nd > 0) {
783         fa->dimensions = npy_alloc_cache_dim(2 * nd);
784         if (fa->dimensions == NULL) {
785             PyErr_NoMemory();
786             goto fail;
787         }
788         fa->strides = fa->dimensions + nd;
789         if (nd) {
790             memcpy(fa->dimensions, dims, sizeof(npy_intp)*nd);
791         }
792         if (strides == NULL) {  /* fill it in */
793             _array_fill_strides(fa->strides, dims, nd, descr->elsize,
794                                 flags, &(fa->flags));
795         }
796         else {
797             /*
798              * we allow strides even when we create
799              * the memory, but be careful with this...
800              */
801             if (nd) {
802                 memcpy(fa->strides, strides, sizeof(npy_intp)*nd);
803             }
804         }
805     }
806     else {
807         fa->dimensions = fa->strides = NULL;
808         fa->flags |= NPY_ARRAY_F_CONTIGUOUS;
809     }
810 
811     if (data == NULL) {
812         /*
813          * Allocate something even for zero-space arrays
814          * e.g. shape=(0,) -- otherwise buffer exposure
815          * (a.data) doesn't work as it should.
816          * Could probably just allocate a few bytes here. -- Chuck
817          */
818         if (nbytes == 0) {
819             nbytes = descr->elsize ? descr->elsize : 1;
820         }
821         /*
822          * It is bad to have uninitialized OBJECT pointers
823          * which could also be sub-fields of a VOID array
824          */
825         if (zeroed || PyDataType_FLAGCHK(descr, NPY_NEEDS_INIT)) {
826             data = npy_alloc_cache_zero(nbytes);
827         }
828         else {
829             data = npy_alloc_cache(nbytes);
830         }
831         if (data == NULL) {
832             raise_memory_error(fa->nd, fa->dimensions, descr);
833             goto fail;
834         }
835         fa->flags |= NPY_ARRAY_OWNDATA;
836     }
837     else {
838         /*
839          * If data is passed in, this object won't own it by default.
840          * Caller must arrange for this to be reset if truly desired
841          */
842         fa->flags &= ~NPY_ARRAY_OWNDATA;
843     }
844     fa->data = data;
845 
846     /*
847      * always update the flags to get the right CONTIGUOUS, ALIGN properties
848      * not owned data and input strides may not be aligned and on some
849      * platforms (debian sparc) malloc does not provide enough alignment for
850      * long double types
851      */
852     PyArray_UpdateFlags((PyArrayObject *)fa, NPY_ARRAY_UPDATE_ALL);
853 
854     /* Set the base object. It's important to do it here so that
855      * __array_finalize__ below receives it
856      */
857     if (base != NULL) {
858         Py_INCREF(base);
859         if (PyArray_SetBaseObject((PyArrayObject *)fa, base) < 0) {
860             goto fail;
861         }
862     }
863 
864     /*
865      * call the __array_finalize__
866      * method if a subtype.
867      * If obj is NULL, then call method with Py_None
868      */
869     if ((subtype != &PyArray_Type)) {
870         PyObject *res, *func, *args;
871 
872         func = PyObject_GetAttr((PyObject *)fa, npy_ma_str_array_finalize);
873         if (func && func != Py_None) {
874             if (PyCapsule_CheckExact(func)) {
875                 /* A C-function is stored here */
876                 PyArray_FinalizeFunc *cfunc;
877                 cfunc = PyCapsule_GetPointer(func, NULL);
878                 Py_DECREF(func);
879                 if (cfunc == NULL) {
880                     goto fail;
881                 }
882                 if (cfunc((PyArrayObject *)fa, obj) < 0) {
883                     goto fail;
884                 }
885             }
886             else {
887                 args = PyTuple_New(1);
888                 if (obj == NULL) {
889                     obj=Py_None;
890                 }
891                 Py_INCREF(obj);
892                 PyTuple_SET_ITEM(args, 0, obj);
893                 res = PyObject_Call(func, args, NULL);
894                 Py_DECREF(args);
895                 Py_DECREF(func);
896                 if (res == NULL) {
897                     goto fail;
898                 }
899                 else {
900                     Py_DECREF(res);
901                 }
902             }
903         }
904         else Py_XDECREF(func);
905     }
906     return (PyObject *)fa;
907 
908  fail:
909     Py_DECREF(fa);
910     return NULL;
911 }
912 
913 
914 /*NUMPY_API
915  * Generic new array creation routine.
916  *
917  * steals a reference to descr. On failure or when dtype->subarray is
918  * true, dtype will be decrefed.
919  */
920 NPY_NO_EXPORT PyObject *
PyArray_NewFromDescr(PyTypeObject * subtype,PyArray_Descr * descr,int nd,npy_intp const * dims,npy_intp const * strides,void * data,int flags,PyObject * obj)921 PyArray_NewFromDescr(
922         PyTypeObject *subtype, PyArray_Descr *descr,
923         int nd, npy_intp const *dims, npy_intp const *strides, void *data,
924         int flags, PyObject *obj)
925 {
926     return PyArray_NewFromDescrAndBase(
927             subtype, descr,
928             nd, dims, strides, data,
929             flags, obj, NULL);
930 }
931 
932 /*
933  * Sets the base object using PyArray_SetBaseObject
934  */
935 NPY_NO_EXPORT PyObject *
PyArray_NewFromDescrAndBase(PyTypeObject * subtype,PyArray_Descr * descr,int nd,npy_intp const * dims,npy_intp const * strides,void * data,int flags,PyObject * obj,PyObject * base)936 PyArray_NewFromDescrAndBase(
937         PyTypeObject *subtype, PyArray_Descr *descr,
938         int nd, npy_intp const *dims, npy_intp const *strides, void *data,
939         int flags, PyObject *obj, PyObject *base)
940 {
941     return PyArray_NewFromDescr_int(subtype, descr, nd,
942                                     dims, strides, data,
943                                     flags, obj, base, 0, 0);
944 }
945 
946 /*
947  * Creates a new array with the same shape as the provided one,
948  * with possible memory layout order, data type and shape changes.
949  *
950  * prototype - The array the new one should be like.
951  * order     - NPY_CORDER - C-contiguous result.
952  *             NPY_FORTRANORDER - Fortran-contiguous result.
953  *             NPY_ANYORDER - Fortran if prototype is Fortran, C otherwise.
954  *             NPY_KEEPORDER - Keeps the axis ordering of prototype.
955  * dtype     - If not NULL, overrides the data type of the result.
956  * ndim      - If not -1, overrides the shape of the result.
957  * dims      - If ndim is not -1, overrides the shape of the result.
958  * subok     - If 1, use the prototype's array subtype, otherwise
959  *             always create a base-class array.
960  *
961  * NOTE: If dtype is not NULL, steals the dtype reference.  On failure or when
962  * dtype->subarray is true, dtype will be decrefed.
963  */
964 NPY_NO_EXPORT PyObject *
PyArray_NewLikeArrayWithShape(PyArrayObject * prototype,NPY_ORDER order,PyArray_Descr * dtype,int ndim,npy_intp const * dims,int subok)965 PyArray_NewLikeArrayWithShape(PyArrayObject *prototype, NPY_ORDER order,
966                               PyArray_Descr *dtype, int ndim, npy_intp const *dims, int subok)
967 {
968     PyObject *ret = NULL;
969 
970     if (ndim == -1) {
971         ndim = PyArray_NDIM(prototype);
972         dims = PyArray_DIMS(prototype);
973     }
974     else if (order == NPY_KEEPORDER && (ndim != PyArray_NDIM(prototype))) {
975         order = NPY_CORDER;
976     }
977 
978     /* If no override data type, use the one from the prototype */
979     if (dtype == NULL) {
980         dtype = PyArray_DESCR(prototype);
981         Py_INCREF(dtype);
982     }
983 
984     /* Handle ANYORDER and simple KEEPORDER cases */
985     switch (order) {
986         case NPY_ANYORDER:
987             order = PyArray_ISFORTRAN(prototype) ?
988                                     NPY_FORTRANORDER : NPY_CORDER;
989             break;
990         case NPY_KEEPORDER:
991             if (PyArray_IS_C_CONTIGUOUS(prototype) || ndim <= 1) {
992                 order = NPY_CORDER;
993                 break;
994             }
995             else if (PyArray_IS_F_CONTIGUOUS(prototype)) {
996                 order = NPY_FORTRANORDER;
997                 break;
998             }
999             break;
1000         default:
1001             break;
1002     }
1003 
1004     /* If it's not KEEPORDER, this is simple */
1005     if (order != NPY_KEEPORDER) {
1006         ret = PyArray_NewFromDescr(subok ? Py_TYPE(prototype) : &PyArray_Type,
1007                                         dtype,
1008                                         ndim,
1009                                         dims,
1010                                         NULL,
1011                                         NULL,
1012                                         order,
1013                                         subok ? (PyObject *)prototype : NULL);
1014     }
1015     /* KEEPORDER needs some analysis of the strides */
1016     else {
1017         npy_intp strides[NPY_MAXDIMS], stride;
1018         npy_stride_sort_item strideperm[NPY_MAXDIMS];
1019         int idim;
1020 
1021         PyArray_CreateSortedStridePerm(ndim,
1022                                         PyArray_STRIDES(prototype),
1023                                         strideperm);
1024 
1025         /* Build the new strides */
1026         stride = dtype->elsize;
1027         for (idim = ndim-1; idim >= 0; --idim) {
1028             npy_intp i_perm = strideperm[idim].perm;
1029             strides[i_perm] = stride;
1030             stride *= dims[i_perm];
1031         }
1032 
1033         /* Finally, allocate the array */
1034         ret = PyArray_NewFromDescr(subok ? Py_TYPE(prototype) : &PyArray_Type,
1035                                         dtype,
1036                                         ndim,
1037                                         dims,
1038                                         strides,
1039                                         NULL,
1040                                         0,
1041                                         subok ? (PyObject *)prototype : NULL);
1042     }
1043 
1044     return ret;
1045 }
1046 
1047 /*NUMPY_API
1048  * Creates a new array with the same shape as the provided one,
1049  * with possible memory layout order and data type changes.
1050  *
1051  * prototype - The array the new one should be like.
1052  * order     - NPY_CORDER - C-contiguous result.
1053  *             NPY_FORTRANORDER - Fortran-contiguous result.
1054  *             NPY_ANYORDER - Fortran if prototype is Fortran, C otherwise.
1055  *             NPY_KEEPORDER - Keeps the axis ordering of prototype.
1056  * dtype     - If not NULL, overrides the data type of the result.
1057  * subok     - If 1, use the prototype's array subtype, otherwise
1058  *             always create a base-class array.
1059  *
1060  * NOTE: If dtype is not NULL, steals the dtype reference.  On failure or when
1061  * dtype->subarray is true, dtype will be decrefed.
1062  */
1063 NPY_NO_EXPORT PyObject *
PyArray_NewLikeArray(PyArrayObject * prototype,NPY_ORDER order,PyArray_Descr * dtype,int subok)1064 PyArray_NewLikeArray(PyArrayObject *prototype, NPY_ORDER order,
1065                      PyArray_Descr *dtype, int subok)
1066 {
1067     return PyArray_NewLikeArrayWithShape(prototype, order, dtype, -1, NULL, subok);
1068 }
1069 
1070 /*NUMPY_API
1071  * Generic new array creation routine.
1072  */
1073 NPY_NO_EXPORT PyObject *
PyArray_New(PyTypeObject * subtype,int nd,npy_intp const * dims,int type_num,npy_intp const * strides,void * data,int itemsize,int flags,PyObject * obj)1074 PyArray_New(
1075         PyTypeObject *subtype, int nd, npy_intp const *dims, int type_num,
1076         npy_intp const *strides, void *data, int itemsize, int flags,
1077         PyObject *obj)
1078 {
1079     PyArray_Descr *descr;
1080     PyObject *new;
1081 
1082     descr = PyArray_DescrFromType(type_num);
1083     if (descr == NULL) {
1084         return NULL;
1085     }
1086     if (PyDataType_ISUNSIZED(descr)) {
1087         if (itemsize < 1) {
1088             PyErr_SetString(PyExc_ValueError,
1089                             "data type must provide an itemsize");
1090             Py_DECREF(descr);
1091             return NULL;
1092         }
1093         PyArray_DESCR_REPLACE(descr);
1094         descr->elsize = itemsize;
1095     }
1096     new = PyArray_NewFromDescr(subtype, descr, nd, dims, strides,
1097                                data, flags, obj);
1098     return new;
1099 }
1100 
1101 
1102 NPY_NO_EXPORT PyArray_Descr *
_dtype_from_buffer_3118(PyObject * memoryview)1103 _dtype_from_buffer_3118(PyObject *memoryview)
1104 {
1105     PyArray_Descr *descr;
1106     Py_buffer *view = PyMemoryView_GET_BUFFER(memoryview);
1107     if (view->format != NULL) {
1108         descr = _descriptor_from_pep3118_format(view->format);
1109         if (descr == NULL) {
1110             return NULL;
1111         }
1112     }
1113     else {
1114         /* If no format is specified, just assume a byte array
1115          * TODO: void would make more sense here, as it wouldn't null
1116          *       terminate.
1117          */
1118         descr = PyArray_DescrNewFromType(NPY_STRING);
1119         descr->elsize = view->itemsize;
1120     }
1121     return descr;
1122 }
1123 
1124 
1125 NPY_NO_EXPORT PyObject *
_array_from_buffer_3118(PyObject * memoryview)1126 _array_from_buffer_3118(PyObject *memoryview)
1127 {
1128     /* PEP 3118 */
1129     Py_buffer *view;
1130     PyArray_Descr *descr = NULL;
1131     PyObject *r = NULL;
1132     int nd, flags;
1133     Py_ssize_t d;
1134     npy_intp shape[NPY_MAXDIMS], strides[NPY_MAXDIMS];
1135 
1136     view = PyMemoryView_GET_BUFFER(memoryview);
1137     nd = view->ndim;
1138     descr = _dtype_from_buffer_3118(memoryview);
1139 
1140     if (descr == NULL) {
1141         return NULL;
1142     }
1143 
1144     /* Sanity check */
1145     if (descr->elsize != view->itemsize) {
1146         /* Ctypes has bugs in its PEP3118 implementation, which we need to
1147          * work around.
1148          *
1149          * bpo-10746
1150          * bpo-32780
1151          * bpo-32782
1152          *
1153          * Note that even if the above are fixed in master, we have to drop the
1154          * early patch versions of python to actually make use of the fixes.
1155          */
1156         if (!npy_ctypes_check(Py_TYPE(view->obj))) {
1157             /* This object has no excuse for a broken PEP3118 buffer */
1158             PyErr_Format(
1159                     PyExc_RuntimeError,
1160                    "Item size %zd for PEP 3118 buffer format "
1161                     "string %s does not match the dtype %c item size %d.",
1162                     view->itemsize, view->format, descr->type,
1163                     descr->elsize);
1164             Py_DECREF(descr);
1165             return NULL;
1166         }
1167 
1168         if (PyErr_Warn(
1169                     PyExc_RuntimeWarning,
1170                     "A builtin ctypes object gave a PEP3118 format "
1171                     "string that does not match its itemsize, so a "
1172                     "best-guess will be made of the data type. "
1173                     "Newer versions of python may behave correctly.") < 0) {
1174             Py_DECREF(descr);
1175             return NULL;
1176         }
1177 
1178         /* Thankfully, np.dtype(ctypes_type) works in most cases.
1179          * For an array input, this produces a dtype containing all the
1180          * dimensions, so the array is now 0d.
1181          */
1182         nd = 0;
1183         Py_DECREF(descr);
1184         descr = (PyArray_Descr *)PyObject_CallFunctionObjArgs(
1185                 (PyObject *)&PyArrayDescr_Type, Py_TYPE(view->obj), NULL);
1186         if (descr == NULL) {
1187             return NULL;
1188         }
1189         if (descr->elsize != view->len) {
1190             PyErr_SetString(
1191                     PyExc_RuntimeError,
1192                     "For the given ctypes object, neither the item size "
1193                     "computed from the PEP 3118 buffer format nor from "
1194                     "converting the type to a np.dtype matched the actual "
1195                     "size. This is a bug both in python and numpy");
1196             Py_DECREF(descr);
1197             return NULL;
1198         }
1199     }
1200 
1201     if (view->shape != NULL) {
1202         int k;
1203         if (nd > NPY_MAXDIMS || nd < 0) {
1204             PyErr_Format(PyExc_RuntimeError,
1205                 "PEP3118 dimensions do not satisfy 0 <= ndim <= NPY_MAXDIMS");
1206             goto fail;
1207         }
1208         for (k = 0; k < nd; ++k) {
1209             shape[k] = view->shape[k];
1210         }
1211         if (view->strides != NULL) {
1212             for (k = 0; k < nd; ++k) {
1213                 strides[k] = view->strides[k];
1214             }
1215         }
1216         else {
1217             d = view->len;
1218             for (k = 0; k < nd; ++k) {
1219                 if (view->shape[k] != 0) {
1220                     d /= view->shape[k];
1221                 }
1222                 strides[k] = d;
1223             }
1224         }
1225     }
1226     else {
1227         if (nd == 1) {
1228             shape[0] = view->len / view->itemsize;
1229             strides[0] = view->itemsize;
1230         }
1231         else if (nd > 1) {
1232             PyErr_SetString(PyExc_RuntimeError,
1233                            "ndim computed from the PEP 3118 buffer format "
1234                            "is greater than 1, but shape is NULL.");
1235             goto fail;
1236         }
1237     }
1238 
1239     flags = NPY_ARRAY_BEHAVED & (view->readonly ? ~NPY_ARRAY_WRITEABLE : ~0);
1240     r = PyArray_NewFromDescrAndBase(
1241             &PyArray_Type, descr,
1242             nd, shape, strides, view->buf,
1243             flags, NULL, memoryview);
1244     return r;
1245 
1246 
1247 fail:
1248     Py_XDECREF(r);
1249     Py_XDECREF(descr);
1250     return NULL;
1251 
1252 }
1253 
1254 
1255 /**
1256  * Attempts to extract an array from an array-like object.
1257  *
1258  * array-like is defined as either
1259  *
1260  * * an object implementing the PEP 3118 buffer interface;
1261  * * an object with __array_struct__ or __array_interface__ attributes;
1262  * * an object with an __array__ function.
1263  *
1264  * @param op The object to convert to an array
1265  * @param requested_type a requested dtype instance, may be NULL; The result
1266  *                       DType may be used, but is not enforced.
1267  * @param writeable whether the result must be writeable.
1268  * @param context Unused parameter, must be NULL (should be removed later).
1269  *
1270  * @returns The array object, Py_NotImplemented if op is not array-like,
1271  *          or NULL with an error set. (A new reference to Py_NotImplemented
1272  *          is returned.)
1273  */
1274 NPY_NO_EXPORT PyObject *
_array_from_array_like(PyObject * op,PyArray_Descr * requested_dtype,npy_bool writeable,PyObject * context)1275 _array_from_array_like(PyObject *op,
1276         PyArray_Descr *requested_dtype, npy_bool writeable, PyObject *context) {
1277     PyObject* tmp;
1278 
1279     /*
1280      * If op supports the PEP 3118 buffer interface.
1281      * We skip bytes and unicode since they are considered scalars. Unicode
1282      * would fail but bytes would be incorrectly converted to a uint8 array.
1283      */
1284     if (!PyBytes_Check(op) && !PyUnicode_Check(op)) {
1285         PyObject *memoryview = PyMemoryView_FromObject(op);
1286         if (memoryview == NULL) {
1287             PyErr_Clear();
1288         }
1289         else {
1290             tmp = _array_from_buffer_3118(memoryview);
1291             Py_DECREF(memoryview);
1292             if (tmp == NULL) {
1293                 return NULL;
1294             }
1295 
1296             if (writeable
1297                 && PyArray_FailUnlessWriteable(
1298                         (PyArrayObject *)tmp, "PEP 3118 buffer") < 0) {
1299                 Py_DECREF(tmp);
1300                 return NULL;
1301             }
1302 
1303             return tmp;
1304         }
1305     }
1306 
1307     /*
1308      * If op supports the __array_struct__ or __array_interface__ interface.
1309      */
1310     tmp = PyArray_FromStructInterface(op);
1311     if (tmp == NULL) {
1312         return NULL;
1313     }
1314     if (tmp == Py_NotImplemented) {
1315         /* Until the return, NotImplemented is always a borrowed reference*/
1316         tmp = PyArray_FromInterface(op);
1317         if (tmp == NULL) {
1318             return NULL;
1319         }
1320     }
1321 
1322     /*
1323      * If op supplies the __array__ function.
1324      * The documentation says this should produce a copy, so
1325      * we skip this method if writeable is true, because the intent
1326      * of writeable is to modify the operand.
1327      * XXX: If the implementation is wrong, and/or if actual
1328      *      usage requires this behave differently,
1329      *      this should be changed!
1330      */
1331     if (!writeable && tmp == Py_NotImplemented) {
1332         tmp = PyArray_FromArrayAttr(op, requested_dtype, context);
1333         if (tmp == NULL) {
1334             return NULL;
1335         }
1336     }
1337 
1338     if (tmp != Py_NotImplemented) {
1339         if (writeable &&
1340                 PyArray_FailUnlessWriteable((PyArrayObject *)tmp,
1341                         "array interface object") < 0) {
1342             Py_DECREF(tmp);
1343             return NULL;
1344         }
1345         return tmp;
1346     }
1347 
1348     /* Until here Py_NotImplemented was borrowed */
1349     Py_INCREF(Py_NotImplemented);
1350     return Py_NotImplemented;
1351 }
1352 
1353 
1354 /*NUMPY_API*/
1355 NPY_NO_EXPORT int
PyArray_GetArrayParamsFromObject(PyObject * NPY_UNUSED (op),PyArray_Descr * NPY_UNUSED (requested_dtype),npy_bool NPY_UNUSED (writeable),PyArray_Descr ** NPY_UNUSED (out_dtype),int * NPY_UNUSED (out_ndim),npy_intp * NPY_UNUSED (out_dims),PyArrayObject ** NPY_UNUSED (out_arr),PyObject * NPY_UNUSED (context))1356 PyArray_GetArrayParamsFromObject(PyObject *NPY_UNUSED(op),
1357         PyArray_Descr *NPY_UNUSED(requested_dtype),
1358         npy_bool NPY_UNUSED(writeable),
1359         PyArray_Descr **NPY_UNUSED(out_dtype),
1360         int *NPY_UNUSED(out_ndim), npy_intp *NPY_UNUSED(out_dims),
1361         PyArrayObject **NPY_UNUSED(out_arr), PyObject *NPY_UNUSED(context))
1362 {
1363     /* Deprecated in NumPy 1.19, removed in NumPy 1.20. */
1364     PyErr_SetString(PyExc_RuntimeError,
1365             "PyArray_GetArrayParamsFromObject() C-API function is removed "
1366             "`PyArray_FromAny()` should be used at this time.  New C-API "
1367             "may be exposed in the future (please do request this if it "
1368             "would help you).");
1369     return -1;
1370 }
1371 
1372 
1373 /*
1374  * This function is a legacy implementation to retain subarray dtype
1375  * behaviour in array coercion. The behaviour here makes sense if tuples
1376  * of matching dimensionality are being coerced. Due to the difficulty
1377  * that the result is ill-defined for lists of array-likes, this is deprecated.
1378  *
1379  * WARNING: Do not use this function, it exists purely to support a deprecated
1380  *          code path.
1381  */
1382 static int
setArrayFromSequence(PyArrayObject * a,PyObject * s,int dim,PyArrayObject * dst)1383 setArrayFromSequence(PyArrayObject *a, PyObject *s,
1384                         int dim, PyArrayObject * dst)
1385 {
1386     Py_ssize_t i, slen;
1387     int res = -1;
1388 
1389     /* first recursion, view equal destination */
1390     if (dst == NULL)
1391         dst = a;
1392 
1393     /*
1394      * This code is to ensure that the sequence access below will
1395      * return a lower-dimensional sequence.
1396      */
1397 
1398     /* INCREF on entry DECREF on exit */
1399     Py_INCREF(s);
1400 
1401     PyObject *seq = NULL;
1402 
1403     if (PyArray_Check(s)) {
1404         if (!(PyArray_CheckExact(s))) {
1405             /*
1406              * make sure a base-class array is used so that the dimensionality
1407              * reduction assumption is correct.
1408              */
1409             /* This will DECREF(s) if replaced */
1410             s = PyArray_EnsureArray(s);
1411             if (s == NULL) {
1412                 goto fail;
1413             }
1414         }
1415 
1416         /* dst points to correct array subsection */
1417         if (PyArray_CopyInto(dst, (PyArrayObject *)s) < 0) {
1418             goto fail;
1419         }
1420 
1421         Py_DECREF(s);
1422         return 0;
1423     }
1424 
1425     if (dim > PyArray_NDIM(a)) {
1426         PyErr_Format(PyExc_ValueError,
1427                  "setArrayFromSequence: sequence/array dimensions mismatch.");
1428         goto fail;
1429     }
1430 
1431     /* Try __array__ before using s as a sequence */
1432     PyObject *tmp = _array_from_array_like(s, NULL, 0, NULL);
1433     if (tmp == NULL) {
1434         goto fail;
1435     }
1436     else if (tmp == Py_NotImplemented) {
1437         Py_DECREF(tmp);
1438     }
1439     else {
1440         int r = PyArray_CopyInto(dst, (PyArrayObject *)tmp);
1441         Py_DECREF(tmp);
1442         if (r < 0) {
1443             goto fail;
1444         }
1445         Py_DECREF(s);
1446         return 0;
1447     }
1448 
1449     seq = PySequence_Fast(s, "Could not convert object to sequence");
1450     if (seq == NULL) {
1451         goto fail;
1452     }
1453     slen = PySequence_Fast_GET_SIZE(seq);
1454 
1455     /*
1456      * Either the dimensions match, or the sequence has length 1 and can
1457      * be broadcast to the destination.
1458      */
1459     if (slen != PyArray_DIMS(a)[dim] && slen != 1) {
1460         PyErr_Format(PyExc_ValueError,
1461                  "cannot copy sequence with size %zd to array axis "
1462                  "with dimension %" NPY_INTP_FMT, slen, PyArray_DIMS(a)[dim]);
1463         goto fail;
1464     }
1465 
1466     /* Broadcast the one element from the sequence to all the outputs */
1467     if (slen == 1) {
1468         PyObject *o = PySequence_Fast_GET_ITEM(seq, 0);
1469         npy_intp alen = PyArray_DIM(a, dim);
1470 
1471         for (i = 0; i < alen; i++) {
1472             if ((PyArray_NDIM(a) - dim) > 1) {
1473                 PyArrayObject * tmp =
1474                     (PyArrayObject *)array_item_asarray(dst, i);
1475                 if (tmp == NULL) {
1476                     goto fail;
1477                 }
1478 
1479                 res = setArrayFromSequence(a, o, dim+1, tmp);
1480                 Py_DECREF(tmp);
1481             }
1482             else {
1483                 char * b = (PyArray_BYTES(dst) + i * PyArray_STRIDES(dst)[0]);
1484                 res = PyArray_SETITEM(dst, b, o);
1485             }
1486             if (res < 0) {
1487                 goto fail;
1488             }
1489         }
1490     }
1491     /* Copy element by element */
1492     else {
1493         for (i = 0; i < slen; i++) {
1494             PyObject * o = PySequence_Fast_GET_ITEM(seq, i);
1495             if ((PyArray_NDIM(a) - dim) > 1) {
1496                 PyArrayObject * tmp =
1497                     (PyArrayObject *)array_item_asarray(dst, i);
1498                 if (tmp == NULL) {
1499                     goto fail;
1500                 }
1501 
1502                 res = setArrayFromSequence(a, o, dim+1, tmp);
1503                 Py_DECREF(tmp);
1504             }
1505             else {
1506                 char * b = (PyArray_BYTES(dst) + i * PyArray_STRIDES(dst)[0]);
1507                 res = PyArray_SETITEM(dst, b, o);
1508             }
1509             if (res < 0) {
1510                 goto fail;
1511             }
1512         }
1513     }
1514 
1515     Py_DECREF(seq);
1516     Py_DECREF(s);
1517     return 0;
1518 
1519  fail:
1520     Py_XDECREF(seq);
1521     Py_DECREF(s);
1522     return res;
1523 }
1524 
1525 
1526 
1527 /*NUMPY_API
1528  * Does not check for NPY_ARRAY_ENSURECOPY and NPY_ARRAY_NOTSWAPPED in flags
1529  * Steals a reference to newtype --- which can be NULL
1530  */
1531 NPY_NO_EXPORT PyObject *
PyArray_FromAny(PyObject * op,PyArray_Descr * newtype,int min_depth,int max_depth,int flags,PyObject * context)1532 PyArray_FromAny(PyObject *op, PyArray_Descr *newtype, int min_depth,
1533                 int max_depth, int flags, PyObject *context)
1534 {
1535     /*
1536      * This is the main code to make a NumPy array from a Python
1537      * Object.  It is called from many different places.
1538      */
1539     PyArrayObject *arr = NULL, *ret;
1540     PyArray_Descr *dtype = NULL;
1541     coercion_cache_obj *cache = NULL;
1542     int ndim = 0;
1543     npy_intp dims[NPY_MAXDIMS];
1544 
1545     if (context != NULL) {
1546         PyErr_SetString(PyExc_RuntimeError, "'context' must be NULL");
1547         return NULL;
1548     }
1549 
1550     PyArray_Descr *fixed_descriptor;
1551     PyArray_DTypeMeta *fixed_DType;
1552     if (PyArray_ExtractDTypeAndDescriptor((PyObject *)newtype,
1553             &fixed_descriptor, &fixed_DType) < 0) {
1554         Py_XDECREF(newtype);
1555         return NULL;
1556     }
1557     Py_XDECREF(newtype);
1558 
1559     ndim = PyArray_DiscoverDTypeAndShape(op,
1560             NPY_MAXDIMS, dims, &cache, fixed_DType, fixed_descriptor, &dtype);
1561 
1562     Py_XDECREF(fixed_descriptor);
1563     Py_XDECREF(fixed_DType);
1564     if (ndim < 0) {
1565         return NULL;
1566     }
1567 
1568     if (NPY_UNLIKELY(fixed_descriptor != NULL && PyDataType_HASSUBARRAY(dtype))) {
1569         /*
1570          * When a subarray dtype was passed in, its dimensions are appended
1571          * to the array dimension (causing a dimension mismatch).
1572          * There is a problem with that, because if we coerce from non-arrays
1573          * we do this correctly by element (as defined by tuples), but for
1574          * arrays we first append the dimensions and then assign to the base
1575          * dtype and then assign which causes the problem.
1576          *
1577          * Thus, we check if there is an array included, in that case we
1578          * give a FutureWarning.
1579          * When the warning is removed, PyArray_Pack will have to ensure
1580          * that that it does not append the dimensions when creating the
1581          * subarrays to assign `arr[0] = obj[0]`.
1582          */
1583         int includes_array = 0;
1584         if (cache != NULL) {
1585             /* This is not ideal, but it is a pretty special case */
1586             coercion_cache_obj *next = cache;
1587             while (next != NULL) {
1588                 if (!next->sequence) {
1589                     includes_array = 1;
1590                     break;
1591                 }
1592                 next = next->next;
1593             }
1594         }
1595         if (includes_array) {
1596             npy_free_coercion_cache(cache);
1597 
1598             ret = (PyArrayObject *) PyArray_NewFromDescr(
1599                     &PyArray_Type, dtype, ndim, dims, NULL, NULL,
1600                     flags & NPY_ARRAY_F_CONTIGUOUS, NULL);
1601             if (ret == NULL) {
1602                 return NULL;
1603             }
1604             assert(PyArray_NDIM(ret) != ndim);
1605 
1606             /* NumPy 1.20, 2020-10-01 */
1607             if (DEPRECATE_FUTUREWARNING(
1608                     "creating an array with a subarray dtype will behave "
1609                     "differently when the `np.array()` (or `asarray`, etc.) "
1610                     "call includes an array or array object.\n"
1611                     "If you are converting a single array or a list of arrays,"
1612                     "you can opt-in to the future behaviour using:\n"
1613                     "    np.array(arr, dtype=np.dtype(['f', dtype]))['f']\n"
1614                     "    np.array([arr1, arr2], dtype=np.dtype(['f', dtype]))['f']\n"
1615                     "\n"
1616                     "By including a new field and indexing it after the "
1617                     "conversion.\n"
1618                     "This may lead to a different result or to current failures "
1619                     "succeeding.  (FutureWarning since NumPy 1.20)") < 0) {
1620                 Py_DECREF(ret);
1621                 return NULL;
1622             }
1623 
1624             if (setArrayFromSequence(ret, op, 0, NULL) < 0) {
1625                 Py_DECREF(ret);
1626                 return NULL;
1627             }
1628             return (PyObject *)ret;
1629         }
1630     }
1631 
1632     if (dtype == NULL) {
1633         dtype = PyArray_DescrFromType(NPY_DEFAULT_TYPE);
1634     }
1635 
1636     if (min_depth != 0 && ndim < min_depth) {
1637         PyErr_SetString(PyExc_ValueError,
1638                 "object of too small depth for desired array");
1639         Py_DECREF(dtype);
1640         npy_free_coercion_cache(cache);
1641         return NULL;
1642     }
1643     if (max_depth != 0 && ndim > max_depth) {
1644         PyErr_SetString(PyExc_ValueError,
1645                 "object too deep for desired array");
1646         Py_DECREF(dtype);
1647         npy_free_coercion_cache(cache);
1648         return NULL;
1649     }
1650 
1651     /* Got the correct parameters, but the cache may already hold the result */
1652     if (cache != NULL && !(cache->sequence)) {
1653         /*
1654          * There is only a single array-like and it was converted, it
1655          * may still have the incorrect type, but that is handled below.
1656          */
1657         assert(cache->converted_obj == op);
1658         arr = (PyArrayObject *)(cache->arr_or_sequence);
1659         /* we may need to cast or assert flags (e.g. copy) */
1660         PyObject *res = PyArray_FromArray(arr, dtype, flags);
1661         npy_unlink_coercion_cache(cache);
1662         return res;
1663     }
1664     else if (cache == NULL && PyArray_IsScalar(op, Void) &&
1665             !(((PyVoidScalarObject *)op)->flags & NPY_ARRAY_OWNDATA) &&
1666             newtype == NULL) {
1667         /*
1668          * Special case, we return a *view* into void scalars, mainly to
1669          * allow things similar to the "reversed" assignment:
1670          *    arr[indx]["field"] = val  # instead of arr["field"][indx] = val
1671          *
1672          * It is unclear that this is necessary in this particular code path.
1673          * Note that this path is only activated when the user did _not_
1674          * provide a dtype (newtype is NULL).
1675          */
1676         assert(ndim == 0);
1677 
1678         return PyArray_NewFromDescrAndBase(
1679                 &PyArray_Type, dtype,
1680                 0, NULL, NULL,
1681                 ((PyVoidScalarObject *)op)->obval,
1682                 ((PyVoidScalarObject *)op)->flags,
1683                 NULL, op);
1684     }
1685     else if (cache == 0 && newtype != NULL &&
1686             PyDataType_ISSIGNED(newtype) && PyArray_IsScalar(op, Generic)) {
1687         assert(ndim == 0);
1688         /*
1689          * This is an (possible) inconsistency where:
1690          *
1691          *     np.array(np.float64(np.nan), dtype=np.int64)
1692          *
1693          * behaves differently from:
1694          *
1695          *     np.array([np.float64(np.nan)], dtype=np.int64)
1696          *     arr1d_int64[0] = np.float64(np.nan)
1697          *     np.array(np.array(np.nan), dtype=np.int64)
1698          *
1699          * by not raising an error instead of using typical casting.
1700          * The error is desirable, but to always error seems like a
1701          * larger change to be considered at some other time and it is
1702          * undesirable that 0-D arrays behave differently from scalars.
1703          * This retains the behaviour, largely due to issues in pandas
1704          * which relied on a try/except (although hopefully that will
1705          * have a better solution at some point):
1706          * https://github.com/pandas-dev/pandas/issues/35481
1707          */
1708         return PyArray_FromScalar(op, dtype);
1709     }
1710 
1711     /* There was no array (or array-like) passed in directly. */
1712     if ((flags & NPY_ARRAY_WRITEBACKIFCOPY) ||
1713             (flags & NPY_ARRAY_UPDATEIFCOPY)) {
1714         PyErr_SetString(PyExc_TypeError,
1715                         "WRITEBACKIFCOPY used for non-array input.");
1716         Py_DECREF(dtype);
1717         npy_free_coercion_cache(cache);
1718         return NULL;
1719     }
1720 
1721     /* Create a new array and copy the data */
1722     Py_INCREF(dtype);  /* hold on in case of a subarray that is replaced */
1723     ret = (PyArrayObject *)PyArray_NewFromDescr(
1724             &PyArray_Type, dtype, ndim, dims, NULL, NULL,
1725             flags&NPY_ARRAY_F_CONTIGUOUS, NULL);
1726     if (ret == NULL) {
1727         npy_free_coercion_cache(cache);
1728         Py_DECREF(dtype);
1729         return NULL;
1730     }
1731     if (ndim == PyArray_NDIM(ret)) {
1732         /*
1733          * Appending of dimensions did not occur, so use the actual dtype
1734          * below. This is relevant for S0 or U0 which can be replaced with
1735          * S1 or U1, although that should likely change.
1736          */
1737         Py_SETREF(dtype, PyArray_DESCR(ret));
1738         Py_INCREF(dtype);
1739     }
1740 
1741     if (cache == NULL) {
1742         /* This is a single item. Set it directly. */
1743         assert(ndim == 0);
1744 
1745         if (PyArray_Pack(dtype, PyArray_BYTES(ret), op) < 0) {
1746             Py_DECREF(dtype);
1747             Py_DECREF(ret);
1748             return NULL;
1749         }
1750         Py_DECREF(dtype);
1751         return (PyObject *)ret;
1752     }
1753     assert(ndim != 0);
1754     assert(op == cache->converted_obj);
1755 
1756     /* Decrease the number of dimensions to the detected ones */
1757     int out_ndim = PyArray_NDIM(ret);
1758     PyArray_Descr *out_descr = PyArray_DESCR(ret);
1759     ((PyArrayObject_fields *)ret)->nd = ndim;
1760     ((PyArrayObject_fields *)ret)->descr = dtype;
1761 
1762     int success = PyArray_AssignFromCache(ret, cache);
1763 
1764     ((PyArrayObject_fields *)ret)->nd = out_ndim;
1765     ((PyArrayObject_fields *)ret)->descr = out_descr;
1766     Py_DECREF(dtype);
1767     if (success < 0) {
1768         Py_DECREF(ret);
1769         return NULL;
1770     }
1771     return (PyObject *)ret;
1772 }
1773 
1774 /*
1775  * flags is any of
1776  * NPY_ARRAY_C_CONTIGUOUS (formerly CONTIGUOUS),
1777  * NPY_ARRAY_F_CONTIGUOUS (formerly FORTRAN),
1778  * NPY_ARRAY_ALIGNED,
1779  * NPY_ARRAY_WRITEABLE,
1780  * NPY_ARRAY_NOTSWAPPED,
1781  * NPY_ARRAY_ENSURECOPY,
1782  * NPY_ARRAY_UPDATEIFCOPY,
1783  * NPY_ARRAY_WRITEBACKIFCOPY,
1784  * NPY_ARRAY_FORCECAST,
1785  * NPY_ARRAY_ENSUREARRAY,
1786  * NPY_ARRAY_ELEMENTSTRIDES
1787  *
1788  * or'd (|) together
1789  *
1790  * Any of these flags present means that the returned array should
1791  * guarantee that aspect of the array.  Otherwise the returned array
1792  * won't guarantee it -- it will depend on the object as to whether or
1793  * not it has such features.
1794  *
1795  * Note that NPY_ARRAY_ENSURECOPY is enough
1796  * to guarantee NPY_ARRAY_C_CONTIGUOUS, NPY_ARRAY_ALIGNED and
1797  * NPY_ARRAY_WRITEABLE and therefore it is redundant to include
1798  * those as well.
1799  *
1800  * NPY_ARRAY_BEHAVED == NPY_ARRAY_ALIGNED | NPY_ARRAY_WRITEABLE
1801  * NPY_ARRAY_CARRAY = NPY_ARRAY_C_CONTIGUOUS | NPY_ARRAY_BEHAVED
1802  * NPY_ARRAY_FARRAY = NPY_ARRAY_F_CONTIGUOUS | NPY_ARRAY_BEHAVED
1803  *
1804  * NPY_ARRAY_F_CONTIGUOUS can be set in the FLAGS to request a FORTRAN array.
1805  * Fortran arrays are always behaved (aligned,
1806  * notswapped, and writeable) and not (C) CONTIGUOUS (if > 1d).
1807  *
1808  * NPY_ARRAY_UPDATEIFCOPY is deprecated in favor of
1809  * NPY_ARRAY_WRITEBACKIFCOPY in 1.14
1810 
1811  * NPY_ARRAY_WRITEBACKIFCOPY flag sets this flag in the returned
1812  * array if a copy is made and the base argument points to the (possibly)
1813  * misbehaved array. Before returning to python, PyArray_ResolveWritebackIfCopy
1814  * must be called to update the contents of the original array from the copy.
1815  *
1816  * NPY_ARRAY_FORCECAST will cause a cast to occur regardless of whether or not
1817  * it is safe.
1818  *
1819  * context is passed through to PyArray_GetArrayParamsFromObject
1820  */
1821 
1822 /*NUMPY_API
1823  * steals a reference to descr -- accepts NULL
1824  */
1825 NPY_NO_EXPORT PyObject *
PyArray_CheckFromAny(PyObject * op,PyArray_Descr * descr,int min_depth,int max_depth,int requires,PyObject * context)1826 PyArray_CheckFromAny(PyObject *op, PyArray_Descr *descr, int min_depth,
1827                      int max_depth, int requires, PyObject *context)
1828 {
1829     PyObject *obj;
1830     if (requires & NPY_ARRAY_NOTSWAPPED) {
1831         if (!descr && PyArray_Check(op) &&
1832                 PyArray_ISBYTESWAPPED((PyArrayObject* )op)) {
1833             descr = PyArray_DescrNew(PyArray_DESCR((PyArrayObject *)op));
1834         }
1835         else if (descr && !PyArray_ISNBO(descr->byteorder)) {
1836             PyArray_DESCR_REPLACE(descr);
1837         }
1838         if (descr && descr->byteorder != NPY_IGNORE) {
1839             descr->byteorder = NPY_NATIVE;
1840         }
1841     }
1842 
1843     obj = PyArray_FromAny(op, descr, min_depth, max_depth, requires, context);
1844     if (obj == NULL) {
1845         return NULL;
1846     }
1847     if ((requires & NPY_ARRAY_ELEMENTSTRIDES) &&
1848         !PyArray_ElementStrides(obj)) {
1849         PyObject *ret;
1850         ret = PyArray_NewCopy((PyArrayObject *)obj, NPY_ANYORDER);
1851         Py_DECREF(obj);
1852         obj = ret;
1853     }
1854     return obj;
1855 }
1856 
1857 
1858 /*NUMPY_API
1859  * steals reference to newtype --- acc. NULL
1860  */
1861 NPY_NO_EXPORT PyObject *
PyArray_FromArray(PyArrayObject * arr,PyArray_Descr * newtype,int flags)1862 PyArray_FromArray(PyArrayObject *arr, PyArray_Descr *newtype, int flags)
1863 {
1864 
1865     PyArrayObject *ret = NULL;
1866     int copy = 0;
1867     int arrflags;
1868     PyArray_Descr *oldtype;
1869     NPY_CASTING casting = NPY_SAFE_CASTING;
1870 
1871     oldtype = PyArray_DESCR(arr);
1872     if (newtype == NULL) {
1873         /*
1874          * Check if object is of array with Null newtype.
1875          * If so return it directly instead of checking for casting.
1876          */
1877         if (flags == 0) {
1878             Py_INCREF(arr);
1879             return (PyObject *)arr;
1880         }
1881         newtype = oldtype;
1882         Py_INCREF(oldtype);
1883     }
1884     else if (PyDataType_ISUNSIZED(newtype)) {
1885         PyArray_DESCR_REPLACE(newtype);
1886         if (newtype == NULL) {
1887             return NULL;
1888         }
1889         newtype->elsize = oldtype->elsize;
1890     }
1891 
1892     /* If the casting if forced, use the 'unsafe' casting rule */
1893     if (flags & NPY_ARRAY_FORCECAST) {
1894         casting = NPY_UNSAFE_CASTING;
1895     }
1896 
1897     /* Raise an error if the casting rule isn't followed */
1898     if (!PyArray_CanCastArrayTo(arr, newtype, casting)) {
1899         PyErr_Clear();
1900         npy_set_invalid_cast_error(
1901                 PyArray_DESCR(arr), newtype, casting, PyArray_NDIM(arr) == 0);
1902         Py_DECREF(newtype);
1903         return NULL;
1904     }
1905 
1906     arrflags = PyArray_FLAGS(arr);
1907            /* If a guaranteed copy was requested */
1908     copy = (flags & NPY_ARRAY_ENSURECOPY) ||
1909            /* If C contiguous was requested, and arr is not */
1910            ((flags & NPY_ARRAY_C_CONTIGUOUS) &&
1911                    (!(arrflags & NPY_ARRAY_C_CONTIGUOUS))) ||
1912            /* If an aligned array was requested, and arr is not */
1913            ((flags & NPY_ARRAY_ALIGNED) &&
1914                    (!(arrflags & NPY_ARRAY_ALIGNED))) ||
1915            /* If a Fortran contiguous array was requested, and arr is not */
1916            ((flags & NPY_ARRAY_F_CONTIGUOUS) &&
1917                    (!(arrflags & NPY_ARRAY_F_CONTIGUOUS))) ||
1918            /* If a writeable array was requested, and arr is not */
1919            ((flags & NPY_ARRAY_WRITEABLE) &&
1920                    (!(arrflags & NPY_ARRAY_WRITEABLE))) ||
1921            !PyArray_EquivTypes(oldtype, newtype);
1922 
1923     if (copy) {
1924         NPY_ORDER order = NPY_KEEPORDER;
1925         int subok = 1;
1926 
1927         /* Set the order for the copy being made based on the flags */
1928         if (flags & NPY_ARRAY_F_CONTIGUOUS) {
1929             order = NPY_FORTRANORDER;
1930         }
1931         else if (flags & NPY_ARRAY_C_CONTIGUOUS) {
1932             order = NPY_CORDER;
1933         }
1934 
1935         if ((flags & NPY_ARRAY_ENSUREARRAY)) {
1936             subok = 0;
1937         }
1938         ret = (PyArrayObject *)PyArray_NewLikeArray(arr, order,
1939                                                     newtype, subok);
1940         if (ret == NULL) {
1941             return NULL;
1942         }
1943 
1944         if (PyArray_CopyInto(ret, arr) < 0) {
1945             Py_DECREF(ret);
1946             return NULL;
1947         }
1948 
1949         if (flags & NPY_ARRAY_UPDATEIFCOPY) {
1950             /* This is the ONLY place the NPY_ARRAY_UPDATEIFCOPY flag
1951              * is still used.
1952              * Can be deleted once the flag itself is removed
1953              */
1954 
1955             /* 2017-Nov-10 1.14 */
1956             if (DEPRECATE(
1957                     "NPY_ARRAY_UPDATEIFCOPY, NPY_ARRAY_INOUT_ARRAY, and "
1958                     "NPY_ARRAY_INOUT_FARRAY are deprecated, use NPY_WRITEBACKIFCOPY, "
1959                     "NPY_ARRAY_INOUT_ARRAY2, or NPY_ARRAY_INOUT_FARRAY2 respectively "
1960                     "instead, and call PyArray_ResolveWritebackIfCopy before the "
1961                     "array is deallocated, i.e. before the last call to Py_DECREF.") < 0) {
1962                 Py_DECREF(ret);
1963                 return NULL;
1964             }
1965             Py_INCREF(arr);
1966             if (PyArray_SetWritebackIfCopyBase(ret, arr) < 0) {
1967                 Py_DECREF(ret);
1968                 return NULL;
1969             }
1970             PyArray_ENABLEFLAGS(ret, NPY_ARRAY_UPDATEIFCOPY);
1971             PyArray_CLEARFLAGS(ret, NPY_ARRAY_WRITEBACKIFCOPY);
1972         }
1973         else if (flags & NPY_ARRAY_WRITEBACKIFCOPY) {
1974             Py_INCREF(arr);
1975             if (PyArray_SetWritebackIfCopyBase(ret, arr) < 0) {
1976                 Py_DECREF(ret);
1977                 return NULL;
1978             }
1979         }
1980     }
1981     /*
1982      * If no copy then take an appropriate view if necessary, or
1983      * just return a reference to ret itself.
1984      */
1985     else {
1986         int needview = ((flags & NPY_ARRAY_ENSUREARRAY) &&
1987                         !PyArray_CheckExact(arr));
1988 
1989         Py_DECREF(newtype);
1990         if (needview) {
1991             PyTypeObject *subtype = NULL;
1992 
1993             if (flags & NPY_ARRAY_ENSUREARRAY) {
1994                 subtype = &PyArray_Type;
1995             }
1996 
1997             ret = (PyArrayObject *)PyArray_View(arr, NULL, subtype);
1998             if (ret == NULL) {
1999                 return NULL;
2000             }
2001         }
2002         else {
2003             Py_INCREF(arr);
2004             ret = arr;
2005         }
2006     }
2007 
2008     return (PyObject *)ret;
2009 }
2010 
2011 /*NUMPY_API */
2012 NPY_NO_EXPORT PyObject *
PyArray_FromStructInterface(PyObject * input)2013 PyArray_FromStructInterface(PyObject *input)
2014 {
2015     PyArray_Descr *thetype = NULL;
2016     PyArrayInterface *inter;
2017     PyObject *attr;
2018     char endian = NPY_NATBYTE;
2019 
2020     attr = PyArray_LookupSpecial_OnInstance(input, "__array_struct__");
2021     if (attr == NULL) {
2022         if (PyErr_Occurred()) {
2023             return NULL;
2024         } else {
2025             return Py_NotImplemented;
2026         }
2027     }
2028     if (!PyCapsule_CheckExact(attr)) {
2029         if (PyType_Check(input) && PyObject_HasAttrString(attr, "__get__")) {
2030             /*
2031              * If the input is a class `attr` should be a property-like object.
2032              * This cannot be interpreted as an array, but is a valid.
2033              * (Needed due to the lookup being on the instance rather than type)
2034              */
2035             Py_DECREF(attr);
2036             return Py_NotImplemented;
2037         }
2038         goto fail;
2039     }
2040     inter = PyCapsule_GetPointer(attr, NULL);
2041     if (inter == NULL) {
2042         goto fail;
2043     }
2044     if (inter->two != 2) {
2045         goto fail;
2046     }
2047     if ((inter->flags & NPY_ARRAY_NOTSWAPPED) != NPY_ARRAY_NOTSWAPPED) {
2048         endian = NPY_OPPBYTE;
2049         inter->flags &= ~NPY_ARRAY_NOTSWAPPED;
2050     }
2051 
2052     if (inter->flags & NPY_ARR_HAS_DESCR) {
2053         if (PyArray_DescrConverter(inter->descr, &thetype) == NPY_FAIL) {
2054             thetype = NULL;
2055             PyErr_Clear();
2056         }
2057     }
2058 
2059     if (thetype == NULL) {
2060         PyObject *type_str = PyUnicode_FromFormat(
2061             "%c%c%d", endian, inter->typekind, inter->itemsize);
2062         if (type_str == NULL) {
2063             Py_DECREF(attr);
2064             return NULL;
2065         }
2066         int ok = PyArray_DescrConverter(type_str, &thetype);
2067         Py_DECREF(type_str);
2068         if (ok != NPY_SUCCEED) {
2069             Py_DECREF(attr);
2070             return NULL;
2071         }
2072     }
2073 
2074     PyObject *ret = PyArray_NewFromDescrAndBase(
2075             &PyArray_Type, thetype,
2076             inter->nd, inter->shape, inter->strides, inter->data,
2077             inter->flags, NULL, input);
2078     Py_DECREF(attr);
2079     return ret;
2080 
2081  fail:
2082     PyErr_SetString(PyExc_ValueError, "invalid __array_struct__");
2083     Py_DECREF(attr);
2084     return NULL;
2085 }
2086 
2087 /*
2088  * Checks if the object in descr is the default 'descr' member for the
2089  * __array_interface__ dictionary with 'typestr' member typestr.
2090  */
2091 NPY_NO_EXPORT int
_is_default_descr(PyObject * descr,PyObject * typestr)2092 _is_default_descr(PyObject *descr, PyObject *typestr) {
2093     if (!PyList_Check(descr) || PyList_GET_SIZE(descr) != 1) {
2094         return 0;
2095     }
2096     PyObject *tuple = PyList_GET_ITEM(descr, 0);
2097     if (!(PyTuple_Check(tuple) && PyTuple_GET_SIZE(tuple) == 2)) {
2098         return 0;
2099     }
2100     PyObject *name = PyTuple_GET_ITEM(tuple, 0);
2101     if (!(PyUnicode_Check(name) && PyUnicode_GetLength(name) == 0)) {
2102         return 0;
2103     }
2104     PyObject *typestr2 = PyTuple_GET_ITEM(tuple, 1);
2105     return PyObject_RichCompareBool(typestr, typestr2, Py_EQ);
2106 }
2107 
2108 /*NUMPY_API*/
2109 NPY_NO_EXPORT PyObject *
PyArray_FromInterface(PyObject * origin)2110 PyArray_FromInterface(PyObject *origin)
2111 {
2112     PyObject *iface = NULL;
2113     PyObject *attr = NULL;
2114     PyObject *base = NULL;
2115     PyArrayObject *ret;
2116     PyArray_Descr *dtype = NULL;
2117     char *data = NULL;
2118     Py_buffer view;
2119     int i, n;
2120     npy_intp dims[NPY_MAXDIMS], strides[NPY_MAXDIMS];
2121     int dataflags = NPY_ARRAY_BEHAVED;
2122 
2123     iface = PyArray_LookupSpecial_OnInstance(origin, "__array_interface__");
2124 
2125     if (iface == NULL) {
2126         if (PyErr_Occurred()) {
2127             if (PyErr_ExceptionMatches(PyExc_RecursionError) ||
2128                     PyErr_ExceptionMatches(PyExc_MemoryError)) {
2129                 /* RecursionError and MemoryError are considered fatal */
2130                 return NULL;
2131             }
2132             /*
2133              * This probably be deprecated, but at least shapely raised
2134              * a NotImplementedError expecting it to be cleared (gh-17965)
2135              */
2136             PyErr_Clear();
2137         }
2138         return Py_NotImplemented;
2139     }
2140     if (!PyDict_Check(iface)) {
2141         if (PyType_Check(origin) && PyObject_HasAttrString(iface, "__get__")) {
2142             /*
2143              * If the input is a class `iface` should be a property-like object.
2144              * This cannot be interpreted as an array, but is a valid.
2145              * (Needed due to the lookup being on the instance rather than type)
2146              */
2147             Py_DECREF(iface);
2148             return Py_NotImplemented;
2149         }
2150 
2151         Py_DECREF(iface);
2152         PyErr_SetString(PyExc_ValueError,
2153                 "Invalid __array_interface__ value, must be a dict");
2154         return NULL;
2155     }
2156 
2157     /* Get type string from interface specification */
2158     attr = _PyDict_GetItemStringWithError(iface, "typestr");
2159     if (attr == NULL) {
2160         Py_DECREF(iface);
2161         if (!PyErr_Occurred()) {
2162             PyErr_SetString(PyExc_ValueError,
2163                     "Missing __array_interface__ typestr");
2164         }
2165         return NULL;
2166     }
2167 
2168     /* allow bytes for backwards compatibility */
2169     if (!PyBytes_Check(attr) && !PyUnicode_Check(attr)) {
2170         PyErr_SetString(PyExc_TypeError,
2171                     "__array_interface__ typestr must be a string");
2172         goto fail;
2173     }
2174 
2175     /* Get dtype from type string */
2176     if (PyArray_DescrConverter(attr, &dtype) != NPY_SUCCEED) {
2177         goto fail;
2178     }
2179 
2180     /*
2181      * If the dtype is NPY_VOID, see if there is extra information in
2182      * the 'descr' attribute.
2183      */
2184     if (dtype->type_num == NPY_VOID) {
2185         PyObject *descr = _PyDict_GetItemStringWithError(iface, "descr");
2186         if (descr == NULL && PyErr_Occurred()) {
2187             goto fail;
2188         }
2189         PyArray_Descr *new_dtype = NULL;
2190         if (descr != NULL) {
2191             int is_default = _is_default_descr(descr, attr);
2192             if (is_default < 0) {
2193                 goto fail;
2194             }
2195             if (!is_default) {
2196                 if (PyArray_DescrConverter2(descr, &new_dtype) != NPY_SUCCEED) {
2197                     goto fail;
2198                 }
2199                 if (new_dtype != NULL) {
2200                     Py_DECREF(dtype);
2201                     dtype = new_dtype;
2202                 }
2203             }
2204 
2205         }
2206 
2207     }
2208 
2209     /* Get shape tuple from interface specification */
2210     attr = _PyDict_GetItemStringWithError(iface, "shape");
2211     if (attr == NULL) {
2212         if (PyErr_Occurred()) {
2213             return NULL;
2214         }
2215         /* Shape must be specified when 'data' is specified */
2216         PyObject *data = _PyDict_GetItemStringWithError(iface, "data");
2217         if (data == NULL && PyErr_Occurred()) {
2218             return NULL;
2219         }
2220         else if (data != NULL) {
2221             Py_DECREF(iface);
2222             PyErr_SetString(PyExc_ValueError,
2223                     "Missing __array_interface__ shape");
2224             return NULL;
2225         }
2226         /* Assume shape as scalar otherwise */
2227         else {
2228             /* NOTE: pointers to data and base should be NULL */
2229             n = dims[0] = 0;
2230         }
2231     }
2232     /* Make sure 'shape' is a tuple */
2233     else if (!PyTuple_Check(attr)) {
2234         PyErr_SetString(PyExc_TypeError,
2235                 "shape must be a tuple");
2236         goto fail;
2237     }
2238     /* Get dimensions from shape tuple */
2239     else {
2240         n = PyTuple_GET_SIZE(attr);
2241         for (i = 0; i < n; i++) {
2242             PyObject *tmp = PyTuple_GET_ITEM(attr, i);
2243             dims[i] = PyArray_PyIntAsIntp(tmp);
2244             if (error_converting(dims[i])) {
2245                 goto fail;
2246             }
2247         }
2248     }
2249 
2250     /* Get data buffer from interface specification */
2251     attr = _PyDict_GetItemStringWithError(iface, "data");
2252     if (attr == NULL && PyErr_Occurred()){
2253         return NULL;
2254     }
2255 
2256     /* Case for data access through pointer */
2257     if (attr && PyTuple_Check(attr)) {
2258         PyObject *dataptr;
2259         if (PyTuple_GET_SIZE(attr) != 2) {
2260             PyErr_SetString(PyExc_TypeError,
2261                     "__array_interface__ data must be a 2-tuple with "
2262                     "(data pointer integer, read-only flag)");
2263             goto fail;
2264         }
2265         dataptr = PyTuple_GET_ITEM(attr, 0);
2266         if (PyLong_Check(dataptr)) {
2267             data = PyLong_AsVoidPtr(dataptr);
2268             if (data == NULL && PyErr_Occurred()) {
2269                 goto fail;
2270             }
2271         }
2272         else {
2273             PyErr_SetString(PyExc_TypeError,
2274                     "first element of __array_interface__ data tuple "
2275                     "must be an integer.");
2276             goto fail;
2277         }
2278         if (PyObject_IsTrue(PyTuple_GET_ITEM(attr,1))) {
2279             dataflags &= ~NPY_ARRAY_WRITEABLE;
2280         }
2281         base = origin;
2282     }
2283 
2284     /* Case for data access through buffer */
2285     else if (attr) {
2286         if (attr != Py_None) {
2287             base = attr;
2288         }
2289         else {
2290             base = origin;
2291         }
2292         if (PyObject_GetBuffer(base, &view,
2293                     PyBUF_WRITABLE|PyBUF_SIMPLE) < 0) {
2294             PyErr_Clear();
2295             if (PyObject_GetBuffer(base, &view,
2296                         PyBUF_SIMPLE) < 0) {
2297                 goto fail;
2298             }
2299             dataflags &= ~NPY_ARRAY_WRITEABLE;
2300         }
2301         data = (char *)view.buf;
2302         /*
2303          * In Python 3 both of the deprecated functions PyObject_AsWriteBuffer and
2304          * PyObject_AsReadBuffer that this code replaces release the buffer. It is
2305          * up to the object that supplies the buffer to guarantee that the buffer
2306          * sticks around after the release.
2307          */
2308         PyBuffer_Release(&view);
2309 
2310         /* Get offset number from interface specification */
2311         attr = _PyDict_GetItemStringWithError(iface, "offset");
2312         if (attr == NULL && PyErr_Occurred()) {
2313             goto fail;
2314         }
2315         else if (attr) {
2316             npy_longlong num = PyLong_AsLongLong(attr);
2317             if (error_converting(num)) {
2318                 PyErr_SetString(PyExc_TypeError,
2319                         "__array_interface__ offset must be an integer");
2320                 goto fail;
2321             }
2322             data += num;
2323         }
2324     }
2325 
2326     ret = (PyArrayObject *)PyArray_NewFromDescrAndBase(
2327             &PyArray_Type, dtype,
2328             n, dims, NULL, data,
2329             dataflags, NULL, base);
2330     /*
2331      * Ref to dtype was stolen by PyArray_NewFromDescrAndBase
2332      * Prevent DECREFing dtype in fail codepath by setting to NULL
2333      */
2334     dtype = NULL;
2335     if (ret == NULL) {
2336         goto fail;
2337     }
2338     if (data == NULL) {
2339         if (PyArray_SIZE(ret) > 1) {
2340             PyErr_SetString(PyExc_ValueError,
2341                     "cannot coerce scalar to array with size > 1");
2342             Py_DECREF(ret);
2343             goto fail;
2344         }
2345         if (PyArray_SETITEM(ret, PyArray_DATA(ret), origin) < 0) {
2346             Py_DECREF(ret);
2347             goto fail;
2348         }
2349     }
2350     attr = _PyDict_GetItemStringWithError(iface, "strides");
2351     if (attr == NULL && PyErr_Occurred()){
2352         return NULL;
2353     }
2354     if (attr != NULL && attr != Py_None) {
2355         if (!PyTuple_Check(attr)) {
2356             PyErr_SetString(PyExc_TypeError,
2357                     "strides must be a tuple");
2358             Py_DECREF(ret);
2359             goto fail;
2360         }
2361         if (n != PyTuple_GET_SIZE(attr)) {
2362             PyErr_SetString(PyExc_ValueError,
2363                     "mismatch in length of strides and shape");
2364             Py_DECREF(ret);
2365             goto fail;
2366         }
2367         for (i = 0; i < n; i++) {
2368             PyObject *tmp = PyTuple_GET_ITEM(attr, i);
2369             strides[i] = PyArray_PyIntAsIntp(tmp);
2370             if (error_converting(strides[i])) {
2371                 Py_DECREF(ret);
2372                 goto fail;
2373             }
2374         }
2375         if (n) {
2376             memcpy(PyArray_STRIDES(ret), strides, n*sizeof(npy_intp));
2377         }
2378     }
2379     PyArray_UpdateFlags(ret, NPY_ARRAY_UPDATE_ALL);
2380     Py_DECREF(iface);
2381     return (PyObject *)ret;
2382 
2383  fail:
2384     Py_XDECREF(dtype);
2385     Py_XDECREF(iface);
2386     return NULL;
2387 }
2388 
2389 /*NUMPY_API
2390  */
2391 NPY_NO_EXPORT PyObject *
PyArray_FromArrayAttr(PyObject * op,PyArray_Descr * typecode,PyObject * context)2392 PyArray_FromArrayAttr(PyObject *op, PyArray_Descr *typecode, PyObject *context)
2393 {
2394     PyObject *new;
2395     PyObject *array_meth;
2396 
2397     if (context != NULL) {
2398         PyErr_SetString(PyExc_RuntimeError, "'context' must be NULL");
2399         return NULL;
2400     }
2401     array_meth = PyArray_LookupSpecial_OnInstance(op, "__array__");
2402     if (array_meth == NULL) {
2403         if (PyErr_Occurred()) {
2404             if (PyErr_ExceptionMatches(PyExc_RecursionError) ||
2405                 PyErr_ExceptionMatches(PyExc_MemoryError)) {
2406                 /* RecursionError and MemoryError are considered fatal */
2407                 return NULL;
2408             }
2409             /* This probably be deprecated. */
2410             PyErr_Clear();
2411         }
2412         return Py_NotImplemented;
2413     }
2414     if (PyType_Check(op) && PyObject_HasAttrString(array_meth, "__get__")) {
2415         /*
2416          * If the input is a class `array_meth` may be a property-like object.
2417          * This cannot be interpreted as an array (called), but is a valid.
2418          * Trying `array_meth.__call__()` on this should not be useful.
2419          * (Needed due to the lookup being on the instance rather than type)
2420          */
2421         Py_DECREF(array_meth);
2422         return Py_NotImplemented;
2423     }
2424     if (typecode == NULL) {
2425         new = PyObject_CallFunction(array_meth, NULL);
2426     }
2427     else {
2428         new = PyObject_CallFunction(array_meth, "O", typecode);
2429     }
2430     Py_DECREF(array_meth);
2431     if (new == NULL) {
2432         return NULL;
2433     }
2434     if (!PyArray_Check(new)) {
2435         PyErr_SetString(PyExc_ValueError,
2436                         "object __array__ method not "  \
2437                         "producing an array");
2438         Py_DECREF(new);
2439         return NULL;
2440     }
2441     return new;
2442 }
2443 
2444 /*NUMPY_API
2445 * new reference -- accepts NULL for mintype
2446 */
2447 NPY_NO_EXPORT PyArray_Descr *
PyArray_DescrFromObject(PyObject * op,PyArray_Descr * mintype)2448 PyArray_DescrFromObject(PyObject *op, PyArray_Descr *mintype)
2449 {
2450     PyArray_Descr *dtype;
2451 
2452     dtype = mintype;
2453     Py_XINCREF(dtype);
2454 
2455     if (PyArray_DTypeFromObject(op, NPY_MAXDIMS, &dtype) < 0) {
2456         return NULL;
2457     }
2458 
2459     if (dtype == NULL) {
2460         return PyArray_DescrFromType(NPY_DEFAULT_TYPE);
2461     }
2462     else {
2463         return dtype;
2464     }
2465 }
2466 
2467 /* These are also old calls (should use PyArray_NewFromDescr) */
2468 
2469 /* They all zero-out the memory as previously done */
2470 
2471 /* steals reference to descr -- and enforces native byteorder on it.*/
2472 
2473 /*NUMPY_API
2474   Deprecated, use PyArray_NewFromDescr instead.
2475 */
2476 NPY_NO_EXPORT PyObject *
PyArray_FromDimsAndDataAndDescr(int NPY_UNUSED (nd),int * NPY_UNUSED (d),PyArray_Descr * descr,char * NPY_UNUSED (data))2477 PyArray_FromDimsAndDataAndDescr(int NPY_UNUSED(nd), int *NPY_UNUSED(d),
2478                                 PyArray_Descr *descr,
2479                                 char *NPY_UNUSED(data))
2480 {
2481     PyErr_SetString(PyExc_NotImplementedError,
2482                 "PyArray_FromDimsAndDataAndDescr: use PyArray_NewFromDescr.");
2483     Py_DECREF(descr);
2484     return NULL;
2485 }
2486 
2487 /*NUMPY_API
2488   Deprecated, use PyArray_SimpleNew instead.
2489 */
2490 NPY_NO_EXPORT PyObject *
PyArray_FromDims(int NPY_UNUSED (nd),int * NPY_UNUSED (d),int NPY_UNUSED (type))2491 PyArray_FromDims(int NPY_UNUSED(nd), int *NPY_UNUSED(d), int NPY_UNUSED(type))
2492 {
2493     PyErr_SetString(PyExc_NotImplementedError,
2494                 "PyArray_FromDims: use PyArray_SimpleNew.");
2495     return NULL;
2496 }
2497 
2498 /* end old calls */
2499 
2500 /*NUMPY_API
2501  * This is a quick wrapper around
2502  * PyArray_FromAny(op, NULL, 0, 0, NPY_ARRAY_ENSUREARRAY, NULL)
2503  * that special cases Arrays and PyArray_Scalars up front
2504  * It *steals a reference* to the object
2505  * It also guarantees that the result is PyArray_Type
2506  * Because it decrefs op if any conversion needs to take place
2507  * so it can be used like PyArray_EnsureArray(some_function(...))
2508  */
2509 NPY_NO_EXPORT PyObject *
PyArray_EnsureArray(PyObject * op)2510 PyArray_EnsureArray(PyObject *op)
2511 {
2512     PyObject *new;
2513 
2514     if ((op == NULL) || (PyArray_CheckExact(op))) {
2515         new = op;
2516         Py_XINCREF(new);
2517     }
2518     else if (PyArray_Check(op)) {
2519         new = PyArray_View((PyArrayObject *)op, NULL, &PyArray_Type);
2520     }
2521     else if (PyArray_IsScalar(op, Generic)) {
2522         new = PyArray_FromScalar(op, NULL);
2523     }
2524     else {
2525         new = PyArray_FROM_OF(op, NPY_ARRAY_ENSUREARRAY);
2526     }
2527     Py_XDECREF(op);
2528     return new;
2529 }
2530 
2531 /*NUMPY_API*/
2532 NPY_NO_EXPORT PyObject *
PyArray_EnsureAnyArray(PyObject * op)2533 PyArray_EnsureAnyArray(PyObject *op)
2534 {
2535     if (op && PyArray_Check(op)) {
2536         return op;
2537     }
2538     return PyArray_EnsureArray(op);
2539 }
2540 
2541 /*
2542  * Private implementation of PyArray_CopyAnyInto with an additional order
2543  * parameter.
2544  */
2545 NPY_NO_EXPORT int
PyArray_CopyAsFlat(PyArrayObject * dst,PyArrayObject * src,NPY_ORDER order)2546 PyArray_CopyAsFlat(PyArrayObject *dst, PyArrayObject *src, NPY_ORDER order)
2547 {
2548     PyArray_StridedUnaryOp *stransfer = NULL;
2549     NpyAuxData *transferdata = NULL;
2550     NpyIter *dst_iter, *src_iter;
2551 
2552     NpyIter_IterNextFunc *dst_iternext, *src_iternext;
2553     char **dst_dataptr, **src_dataptr;
2554     npy_intp dst_stride, src_stride;
2555     npy_intp *dst_countptr, *src_countptr;
2556     npy_uint32 baseflags;
2557 
2558     char *dst_data, *src_data;
2559     npy_intp dst_count, src_count, count;
2560     npy_intp src_itemsize;
2561     npy_intp dst_size, src_size;
2562     int needs_api;
2563 
2564     NPY_BEGIN_THREADS_DEF;
2565 
2566     if (PyArray_FailUnlessWriteable(dst, "destination array") < 0) {
2567         return -1;
2568     }
2569 
2570     /*
2571      * If the shapes match and a particular order is forced
2572      * for both, use the more efficient CopyInto
2573      */
2574     if (order != NPY_ANYORDER && order != NPY_KEEPORDER &&
2575             PyArray_NDIM(dst) == PyArray_NDIM(src) &&
2576             PyArray_CompareLists(PyArray_DIMS(dst), PyArray_DIMS(src),
2577                                 PyArray_NDIM(dst))) {
2578         return PyArray_CopyInto(dst, src);
2579     }
2580 
2581     dst_size = PyArray_SIZE(dst);
2582     src_size = PyArray_SIZE(src);
2583     if (dst_size != src_size) {
2584         PyErr_Format(PyExc_ValueError,
2585                 "cannot copy from array of size %" NPY_INTP_FMT " into an array "
2586                 "of size %" NPY_INTP_FMT, src_size, dst_size);
2587         return -1;
2588     }
2589 
2590     /* Zero-sized arrays require nothing be done */
2591     if (dst_size == 0) {
2592         return 0;
2593     }
2594 
2595     baseflags = NPY_ITER_EXTERNAL_LOOP |
2596                 NPY_ITER_DONT_NEGATE_STRIDES |
2597                 NPY_ITER_REFS_OK;
2598 
2599     /*
2600      * This copy is based on matching C-order traversals of src and dst.
2601      * By using two iterators, we can find maximal sub-chunks that
2602      * can be processed at once.
2603      */
2604     dst_iter = NpyIter_New(dst, NPY_ITER_WRITEONLY | baseflags,
2605                                 order,
2606                                 NPY_NO_CASTING,
2607                                 NULL);
2608     if (dst_iter == NULL) {
2609         return -1;
2610     }
2611     src_iter = NpyIter_New(src, NPY_ITER_READONLY | baseflags,
2612                                 order,
2613                                 NPY_NO_CASTING,
2614                                 NULL);
2615     if (src_iter == NULL) {
2616         NpyIter_Deallocate(dst_iter);
2617         return -1;
2618     }
2619 
2620     /* Get all the values needed for the inner loop */
2621     dst_iternext = NpyIter_GetIterNext(dst_iter, NULL);
2622     dst_dataptr = NpyIter_GetDataPtrArray(dst_iter);
2623     /* Since buffering is disabled, we can cache the stride */
2624     dst_stride = NpyIter_GetInnerStrideArray(dst_iter)[0];
2625     dst_countptr = NpyIter_GetInnerLoopSizePtr(dst_iter);
2626 
2627     src_iternext = NpyIter_GetIterNext(src_iter, NULL);
2628     src_dataptr = NpyIter_GetDataPtrArray(src_iter);
2629     /* Since buffering is disabled, we can cache the stride */
2630     src_stride = NpyIter_GetInnerStrideArray(src_iter)[0];
2631     src_countptr = NpyIter_GetInnerLoopSizePtr(src_iter);
2632     src_itemsize = PyArray_DESCR(src)->elsize;
2633 
2634     if (dst_iternext == NULL || src_iternext == NULL) {
2635         NpyIter_Deallocate(dst_iter);
2636         NpyIter_Deallocate(src_iter);
2637         return -1;
2638     }
2639 
2640     needs_api = NpyIter_IterationNeedsAPI(dst_iter) ||
2641                 NpyIter_IterationNeedsAPI(src_iter);
2642 
2643     /*
2644      * Because buffering is disabled in the iterator, the inner loop
2645      * strides will be the same throughout the iteration loop.  Thus,
2646      * we can pass them to this function to take advantage of
2647      * contiguous strides, etc.
2648      */
2649     if (PyArray_GetDTypeTransferFunction(
2650                     IsUintAligned(src) && IsAligned(src) &&
2651                     IsUintAligned(dst) && IsAligned(dst),
2652                     src_stride, dst_stride,
2653                     PyArray_DESCR(src), PyArray_DESCR(dst),
2654                     0,
2655                     &stransfer, &transferdata,
2656                     &needs_api) != NPY_SUCCEED) {
2657         NpyIter_Deallocate(dst_iter);
2658         NpyIter_Deallocate(src_iter);
2659         return -1;
2660     }
2661 
2662     if (!needs_api) {
2663         NPY_BEGIN_THREADS;
2664     }
2665 
2666     dst_count = *dst_countptr;
2667     src_count = *src_countptr;
2668     dst_data = dst_dataptr[0];
2669     src_data = src_dataptr[0];
2670     int res = 0;
2671     for(;;) {
2672         /* Transfer the biggest amount that fits both */
2673         count = (src_count < dst_count) ? src_count : dst_count;
2674         if (stransfer(
2675                 dst_data, dst_stride, src_data, src_stride,
2676                 count, src_itemsize, transferdata) < 0) {
2677             res = -1;
2678             break;
2679         }
2680 
2681         /* If we exhausted the dst block, refresh it */
2682         if (dst_count == count) {
2683             res = dst_iternext(dst_iter);
2684             if (!res) {
2685                 break;
2686             }
2687             dst_count = *dst_countptr;
2688             dst_data = dst_dataptr[0];
2689         }
2690         else {
2691             dst_count -= count;
2692             dst_data += count*dst_stride;
2693         }
2694 
2695         /* If we exhausted the src block, refresh it */
2696         if (src_count == count) {
2697             res = src_iternext(src_iter);
2698             if (!res) {
2699                 break;
2700             }
2701             src_count = *src_countptr;
2702             src_data = src_dataptr[0];
2703         }
2704         else {
2705             src_count -= count;
2706             src_data += count*src_stride;
2707         }
2708     }
2709 
2710     NPY_END_THREADS;
2711 
2712     NPY_AUXDATA_FREE(transferdata);
2713     NpyIter_Deallocate(dst_iter);
2714     NpyIter_Deallocate(src_iter);
2715     if (res > 0) {
2716         /* The iteration stopped successfully, do not report an error */
2717         return 0;
2718     }
2719     return res;
2720 }
2721 
2722 /*NUMPY_API
2723  * Copy an Array into another array -- memory must not overlap
2724  * Does not require src and dest to have "broadcastable" shapes
2725  * (only the same number of elements).
2726  *
2727  * TODO: For NumPy 2.0, this could accept an order parameter which
2728  *       only allows NPY_CORDER and NPY_FORDER.  Could also rename
2729  *       this to CopyAsFlat to make the name more intuitive.
2730  *
2731  * Returns 0 on success, -1 on error.
2732  */
2733 NPY_NO_EXPORT int
PyArray_CopyAnyInto(PyArrayObject * dst,PyArrayObject * src)2734 PyArray_CopyAnyInto(PyArrayObject *dst, PyArrayObject *src)
2735 {
2736     return PyArray_CopyAsFlat(dst, src, NPY_CORDER);
2737 }
2738 
2739 /*NUMPY_API
2740  * Copy an Array into another array.
2741  * Broadcast to the destination shape if necessary.
2742  *
2743  * Returns 0 on success, -1 on failure.
2744  */
2745 NPY_NO_EXPORT int
PyArray_CopyInto(PyArrayObject * dst,PyArrayObject * src)2746 PyArray_CopyInto(PyArrayObject *dst, PyArrayObject *src)
2747 {
2748     return PyArray_AssignArray(dst, src, NULL, NPY_UNSAFE_CASTING);
2749 }
2750 
2751 /*NUMPY_API
2752  * Move the memory of one array into another, allowing for overlapping data.
2753  *
2754  * Returns 0 on success, negative on failure.
2755  */
2756 NPY_NO_EXPORT int
PyArray_MoveInto(PyArrayObject * dst,PyArrayObject * src)2757 PyArray_MoveInto(PyArrayObject *dst, PyArrayObject *src)
2758 {
2759     return PyArray_AssignArray(dst, src, NULL, NPY_UNSAFE_CASTING);
2760 }
2761 
2762 /*NUMPY_API
2763  * PyArray_CheckAxis
2764  *
2765  * check that axis is valid
2766  * convert 0-d arrays to 1-d arrays
2767  */
2768 NPY_NO_EXPORT PyObject *
PyArray_CheckAxis(PyArrayObject * arr,int * axis,int flags)2769 PyArray_CheckAxis(PyArrayObject *arr, int *axis, int flags)
2770 {
2771     PyObject *temp1, *temp2;
2772     int n = PyArray_NDIM(arr);
2773 
2774     if (*axis == NPY_MAXDIMS || n == 0) {
2775         if (n != 1) {
2776             temp1 = PyArray_Ravel(arr,0);
2777             if (temp1 == NULL) {
2778                 *axis = 0;
2779                 return NULL;
2780             }
2781             if (*axis == NPY_MAXDIMS) {
2782                 *axis = PyArray_NDIM((PyArrayObject *)temp1)-1;
2783             }
2784         }
2785         else {
2786             temp1 = (PyObject *)arr;
2787             Py_INCREF(temp1);
2788             *axis = 0;
2789         }
2790         if (!flags && *axis == 0) {
2791             return temp1;
2792         }
2793     }
2794     else {
2795         temp1 = (PyObject *)arr;
2796         Py_INCREF(temp1);
2797     }
2798     if (flags) {
2799         temp2 = PyArray_CheckFromAny((PyObject *)temp1, NULL,
2800                                      0, 0, flags, NULL);
2801         Py_DECREF(temp1);
2802         if (temp2 == NULL) {
2803             return NULL;
2804         }
2805     }
2806     else {
2807         temp2 = (PyObject *)temp1;
2808     }
2809     n = PyArray_NDIM((PyArrayObject *)temp2);
2810     if (check_and_adjust_axis(axis, n) < 0) {
2811         Py_DECREF(temp2);
2812         return NULL;
2813     }
2814     return temp2;
2815 }
2816 
2817 /*NUMPY_API
2818  * Zeros
2819  *
2820  * steals a reference to type. On failure or when dtype->subarray is
2821  * true, dtype will be decrefed.
2822  * accepts NULL type
2823  */
2824 NPY_NO_EXPORT PyObject *
PyArray_Zeros(int nd,npy_intp const * dims,PyArray_Descr * type,int is_f_order)2825 PyArray_Zeros(int nd, npy_intp const *dims, PyArray_Descr *type, int is_f_order)
2826 {
2827     PyArrayObject *ret;
2828 
2829     if (!type) {
2830         type = PyArray_DescrFromType(NPY_DEFAULT_TYPE);
2831     }
2832 
2833     ret = (PyArrayObject *)PyArray_NewFromDescr_int(
2834             &PyArray_Type, type,
2835             nd, dims, NULL, NULL,
2836             is_f_order, NULL, NULL,
2837             1, 0);
2838 
2839     if (ret == NULL) {
2840         return NULL;
2841     }
2842 
2843     /* handle objects */
2844     if (PyDataType_REFCHK(PyArray_DESCR(ret))) {
2845         if (_zerofill(ret) < 0) {
2846             Py_DECREF(ret);
2847             return NULL;
2848         }
2849     }
2850 
2851 
2852     return (PyObject *)ret;
2853 
2854 }
2855 
2856 /*NUMPY_API
2857  * Empty
2858  *
2859  * accepts NULL type
2860  * steals a reference to type
2861  */
2862 NPY_NO_EXPORT PyObject *
PyArray_Empty(int nd,npy_intp const * dims,PyArray_Descr * type,int is_f_order)2863 PyArray_Empty(int nd, npy_intp const *dims, PyArray_Descr *type, int is_f_order)
2864 {
2865     PyArrayObject *ret;
2866 
2867     if (!type) type = PyArray_DescrFromType(NPY_DEFAULT_TYPE);
2868 
2869     /*
2870      * PyArray_NewFromDescr steals a ref,
2871      * but we need to look at type later.
2872      * */
2873     Py_INCREF(type);
2874 
2875     ret = (PyArrayObject *)PyArray_NewFromDescr(&PyArray_Type,
2876                                                 type, nd, dims,
2877                                                 NULL, NULL,
2878                                                 is_f_order, NULL);
2879     if (ret != NULL && PyDataType_REFCHK(type)) {
2880         PyArray_FillObjectArray(ret, Py_None);
2881         if (PyErr_Occurred()) {
2882             Py_DECREF(ret);
2883             Py_DECREF(type);
2884             return NULL;
2885         }
2886     }
2887 
2888     Py_DECREF(type);
2889     return (PyObject *)ret;
2890 }
2891 
2892 /*
2893  * Like ceil(value), but check for overflow.
2894  *
2895  * Return 0 on success, -1 on failure. In case of failure, set a PyExc_Overflow
2896  * exception
2897  */
2898 static npy_intp
_arange_safe_ceil_to_intp(double value)2899 _arange_safe_ceil_to_intp(double value)
2900 {
2901     double ivalue;
2902 
2903     ivalue = npy_ceil(value);
2904     /* condition inverted to handle NaN */
2905     if (npy_isnan(ivalue)) {
2906         PyErr_SetString(PyExc_ValueError,
2907             "arange: cannot compute length");
2908         return -1;
2909     }
2910     if (!(NPY_MIN_INTP <= ivalue && ivalue <= NPY_MAX_INTP)) {
2911         PyErr_SetString(PyExc_OverflowError,
2912                 "arange: overflow while computing length");
2913         return -1;
2914     }
2915 
2916     return (npy_intp)ivalue;
2917 }
2918 
2919 
2920 /*NUMPY_API
2921   Arange,
2922 */
2923 NPY_NO_EXPORT PyObject *
PyArray_Arange(double start,double stop,double step,int type_num)2924 PyArray_Arange(double start, double stop, double step, int type_num)
2925 {
2926     npy_intp length;
2927     PyArrayObject *range;
2928     PyArray_ArrFuncs *funcs;
2929     PyObject *obj;
2930     int ret;
2931     double delta, tmp_len;
2932     NPY_BEGIN_THREADS_DEF;
2933 
2934     delta = stop - start;
2935     tmp_len = delta/step;
2936 
2937     /* Underflow and divide-by-inf check */
2938     if (tmp_len == 0.0 && delta != 0.0) {
2939         if (npy_signbit(tmp_len)) {
2940             length = 0;
2941         }
2942         else {
2943             length = 1;
2944         }
2945     }
2946     else {
2947         length = _arange_safe_ceil_to_intp(tmp_len);
2948         if (error_converting(length)) {
2949             return NULL;
2950         }
2951     }
2952 
2953     if (length <= 0) {
2954         length = 0;
2955         return PyArray_New(&PyArray_Type, 1, &length, type_num,
2956                            NULL, NULL, 0, 0, NULL);
2957     }
2958     range = (PyArrayObject *)PyArray_New(&PyArray_Type, 1, &length, type_num,
2959                         NULL, NULL, 0, 0, NULL);
2960     if (range == NULL) {
2961         return NULL;
2962     }
2963     funcs = PyArray_DESCR(range)->f;
2964 
2965     /*
2966      * place start in the buffer and the next value in the second position
2967      * if length > 2, then call the inner loop, otherwise stop
2968      */
2969     obj = PyFloat_FromDouble(start);
2970     ret = funcs->setitem(obj, PyArray_DATA(range), range);
2971     Py_DECREF(obj);
2972     if (ret < 0) {
2973         goto fail;
2974     }
2975     if (length == 1) {
2976         return (PyObject *)range;
2977     }
2978     obj = PyFloat_FromDouble(start + step);
2979     ret = funcs->setitem(obj, PyArray_BYTES(range)+PyArray_ITEMSIZE(range),
2980                          range);
2981     Py_DECREF(obj);
2982     if (ret < 0) {
2983         goto fail;
2984     }
2985     if (length == 2) {
2986         return (PyObject *)range;
2987     }
2988     if (!funcs->fill) {
2989         PyErr_SetString(PyExc_ValueError,
2990                 "no fill-function for data-type.");
2991         Py_DECREF(range);
2992         return NULL;
2993     }
2994     NPY_BEGIN_THREADS_DESCR(PyArray_DESCR(range));
2995     funcs->fill(PyArray_DATA(range), length, range);
2996     NPY_END_THREADS;
2997     if (PyErr_Occurred()) {
2998         goto fail;
2999     }
3000     return (PyObject *)range;
3001 
3002  fail:
3003     Py_DECREF(range);
3004     return NULL;
3005 }
3006 
3007 /*
3008  * the formula is len = (intp) ceil((stop - start) / step);
3009  */
3010 static npy_intp
_calc_length(PyObject * start,PyObject * stop,PyObject * step,PyObject ** next,int cmplx)3011 _calc_length(PyObject *start, PyObject *stop, PyObject *step, PyObject **next, int cmplx)
3012 {
3013     npy_intp len, tmp;
3014     PyObject *zero, *val;
3015     int next_is_nonzero, val_is_zero;
3016     double value;
3017 
3018     *next = PyNumber_Subtract(stop, start);
3019     if (!(*next)) {
3020         if (PyTuple_Check(stop)) {
3021             PyErr_Clear();
3022             PyErr_SetString(PyExc_TypeError,
3023                             "arange: scalar arguments expected "\
3024                             "instead of a tuple.");
3025         }
3026         return -1;
3027     }
3028 
3029     zero = PyLong_FromLong(0);
3030     if (!zero) {
3031         Py_DECREF(*next);
3032         *next = NULL;
3033         return -1;
3034     }
3035 
3036     next_is_nonzero = PyObject_RichCompareBool(*next, zero, Py_NE);
3037     if (next_is_nonzero == -1) {
3038         Py_DECREF(zero);
3039         Py_DECREF(*next);
3040         *next = NULL;
3041         return -1;
3042     }
3043     val = PyNumber_TrueDivide(*next, step);
3044     Py_DECREF(*next);
3045     *next = NULL;
3046 
3047     if (!val) {
3048         Py_DECREF(zero);
3049         return -1;
3050     }
3051 
3052     val_is_zero = PyObject_RichCompareBool(val, zero, Py_EQ);
3053     Py_DECREF(zero);
3054     if (val_is_zero == -1) {
3055         Py_DECREF(val);
3056         return -1;
3057     }
3058 
3059     if (cmplx && PyComplex_Check(val)) {
3060         value = PyComplex_RealAsDouble(val);
3061         if (error_converting(value)) {
3062             Py_DECREF(val);
3063             return -1;
3064         }
3065         len = _arange_safe_ceil_to_intp(value);
3066         if (error_converting(len)) {
3067             Py_DECREF(val);
3068             return -1;
3069         }
3070         value = PyComplex_ImagAsDouble(val);
3071         Py_DECREF(val);
3072         if (error_converting(value)) {
3073             return -1;
3074         }
3075         tmp = _arange_safe_ceil_to_intp(value);
3076         if (error_converting(tmp)) {
3077             return -1;
3078         }
3079         len = PyArray_MIN(len, tmp);
3080     }
3081     else {
3082         value = PyFloat_AsDouble(val);
3083         Py_DECREF(val);
3084         if (error_converting(value)) {
3085             return -1;
3086         }
3087 
3088         /* Underflow and divide-by-inf check */
3089         if (val_is_zero && next_is_nonzero) {
3090             if (npy_signbit(value)) {
3091                 len = 0;
3092             }
3093             else {
3094                 len = 1;
3095             }
3096         }
3097         else {
3098             len = _arange_safe_ceil_to_intp(value);
3099             if (error_converting(len)) {
3100                 return -1;
3101             }
3102         }
3103     }
3104 
3105     if (len > 0) {
3106         *next = PyNumber_Add(start, step);
3107         if (!*next) {
3108             return -1;
3109         }
3110     }
3111     return len;
3112 }
3113 
3114 /*NUMPY_API
3115  *
3116  * ArangeObj,
3117  *
3118  * this doesn't change the references
3119  */
3120 NPY_NO_EXPORT PyObject *
PyArray_ArangeObj(PyObject * start,PyObject * stop,PyObject * step,PyArray_Descr * dtype)3121 PyArray_ArangeObj(PyObject *start, PyObject *stop, PyObject *step, PyArray_Descr *dtype)
3122 {
3123     PyArrayObject *range;
3124     PyArray_ArrFuncs *funcs;
3125     PyObject *next, *err;
3126     npy_intp length;
3127     PyArray_Descr *native = NULL;
3128     int swap;
3129     NPY_BEGIN_THREADS_DEF;
3130 
3131     /* Datetime arange is handled specially */
3132     if ((dtype != NULL && (dtype->type_num == NPY_DATETIME ||
3133                            dtype->type_num == NPY_TIMEDELTA)) ||
3134             (dtype == NULL && (is_any_numpy_datetime_or_timedelta(start) ||
3135                               is_any_numpy_datetime_or_timedelta(stop) ||
3136                               is_any_numpy_datetime_or_timedelta(step)))) {
3137         return (PyObject *)datetime_arange(start, stop, step, dtype);
3138     }
3139 
3140     if (!dtype) {
3141         PyArray_Descr *deftype;
3142         PyArray_Descr *newtype;
3143 
3144         /* intentionally made to be at least NPY_LONG */
3145         deftype = PyArray_DescrFromType(NPY_LONG);
3146         newtype = PyArray_DescrFromObject(start, deftype);
3147         Py_DECREF(deftype);
3148         if (newtype == NULL) {
3149             return NULL;
3150         }
3151         deftype = newtype;
3152         if (stop && stop != Py_None) {
3153             newtype = PyArray_DescrFromObject(stop, deftype);
3154             Py_DECREF(deftype);
3155             if (newtype == NULL) {
3156                 return NULL;
3157             }
3158             deftype = newtype;
3159         }
3160         if (step && step != Py_None) {
3161             newtype = PyArray_DescrFromObject(step, deftype);
3162             Py_DECREF(deftype);
3163             if (newtype == NULL) {
3164                 return NULL;
3165             }
3166             deftype = newtype;
3167         }
3168         dtype = deftype;
3169     }
3170     else {
3171         Py_INCREF(dtype);
3172     }
3173     if (!step || step == Py_None) {
3174         step = PyLong_FromLong(1);
3175     }
3176     else {
3177         Py_XINCREF(step);
3178     }
3179     if (!stop || stop == Py_None) {
3180         stop = start;
3181         start = PyLong_FromLong(0);
3182     }
3183     else {
3184         Py_INCREF(start);
3185     }
3186     /* calculate the length and next = start + step*/
3187     length = _calc_length(start, stop, step, &next,
3188                           PyTypeNum_ISCOMPLEX(dtype->type_num));
3189     err = PyErr_Occurred();
3190     if (err) {
3191         Py_DECREF(dtype);
3192         if (err && PyErr_GivenExceptionMatches(err, PyExc_OverflowError)) {
3193             PyErr_SetString(PyExc_ValueError, "Maximum allowed size exceeded");
3194         }
3195         goto fail;
3196     }
3197     if (length <= 0) {
3198         length = 0;
3199         range = (PyArrayObject *)PyArray_SimpleNewFromDescr(1, &length, dtype);
3200         Py_DECREF(step);
3201         Py_DECREF(start);
3202         return (PyObject *)range;
3203     }
3204 
3205     /*
3206      * If dtype is not in native byte-order then get native-byte
3207      * order version.  And then swap on the way out.
3208      */
3209     if (!PyArray_ISNBO(dtype->byteorder)) {
3210         native = PyArray_DescrNewByteorder(dtype, NPY_NATBYTE);
3211         swap = 1;
3212     }
3213     else {
3214         native = dtype;
3215         swap = 0;
3216     }
3217 
3218     range = (PyArrayObject *)PyArray_SimpleNewFromDescr(1, &length, native);
3219     if (range == NULL) {
3220         goto fail;
3221     }
3222 
3223     /*
3224      * place start in the buffer and the next value in the second position
3225      * if length > 2, then call the inner loop, otherwise stop
3226      */
3227     funcs = PyArray_DESCR(range)->f;
3228     if (funcs->setitem(start, PyArray_DATA(range), range) < 0) {
3229         goto fail;
3230     }
3231     if (length == 1) {
3232         goto finish;
3233     }
3234     if (funcs->setitem(next, PyArray_BYTES(range)+PyArray_ITEMSIZE(range),
3235                        range) < 0) {
3236         goto fail;
3237     }
3238     if (length == 2) {
3239         goto finish;
3240     }
3241     if (!funcs->fill) {
3242         PyErr_SetString(PyExc_ValueError, "no fill-function for data-type.");
3243         Py_DECREF(range);
3244         goto fail;
3245     }
3246     NPY_BEGIN_THREADS_DESCR(PyArray_DESCR(range));
3247     funcs->fill(PyArray_DATA(range), length, range);
3248     NPY_END_THREADS;
3249     if (PyErr_Occurred()) {
3250         goto fail;
3251     }
3252  finish:
3253     /* TODO: This swapping could be handled on the fly by the nditer */
3254     if (swap) {
3255         PyObject *new;
3256         new = PyArray_Byteswap(range, 1);
3257         Py_DECREF(new);
3258         Py_DECREF(PyArray_DESCR(range));
3259         /* steals the reference */
3260         ((PyArrayObject_fields *)range)->descr = dtype;
3261     }
3262     Py_DECREF(start);
3263     Py_DECREF(step);
3264     Py_DECREF(next);
3265     return (PyObject *)range;
3266 
3267  fail:
3268     Py_DECREF(start);
3269     Py_DECREF(step);
3270     Py_XDECREF(next);
3271     return NULL;
3272 }
3273 
3274 /* This array creation function does not steal the reference to dtype. */
3275 static PyArrayObject *
array_fromfile_binary(FILE * fp,PyArray_Descr * dtype,npy_intp num,size_t * nread)3276 array_fromfile_binary(FILE *fp, PyArray_Descr *dtype, npy_intp num, size_t *nread)
3277 {
3278     PyArrayObject *r;
3279     npy_off_t start, numbytes;
3280     int elsize;
3281 
3282     if (num < 0) {
3283         int fail = 0;
3284         start = npy_ftell(fp);
3285         if (start < 0) {
3286             fail = 1;
3287         }
3288         if (npy_fseek(fp, 0, SEEK_END) < 0) {
3289             fail = 1;
3290         }
3291         numbytes = npy_ftell(fp);
3292         if (numbytes < 0) {
3293             fail = 1;
3294         }
3295         numbytes -= start;
3296         if (npy_fseek(fp, start, SEEK_SET) < 0) {
3297             fail = 1;
3298         }
3299         if (fail) {
3300             PyErr_SetString(PyExc_IOError,
3301                             "could not seek in file");
3302             return NULL;
3303         }
3304         num = numbytes / dtype->elsize;
3305     }
3306 
3307     /*
3308      * Array creation may move sub-array dimensions from the dtype to array
3309      * dimensions, so we need to use the original element size when reading.
3310      */
3311     elsize = dtype->elsize;
3312 
3313     Py_INCREF(dtype);  /* do not steal the original dtype. */
3314     r = (PyArrayObject *)PyArray_NewFromDescr(&PyArray_Type, dtype, 1, &num,
3315                                               NULL, NULL, 0, NULL);
3316     if (r == NULL) {
3317         return NULL;
3318     }
3319 
3320     NPY_BEGIN_ALLOW_THREADS;
3321     *nread = fread(PyArray_DATA(r), elsize, num, fp);
3322     NPY_END_ALLOW_THREADS;
3323     return r;
3324 }
3325 
3326 /*
3327  * Create an array by reading from the given stream, using the passed
3328  * next_element and skip_separator functions.
3329  * Does not steal the reference to dtype.
3330  */
3331 #define FROM_BUFFER_SIZE 4096
3332 static PyArrayObject *
array_from_text(PyArray_Descr * dtype,npy_intp num,char const * sep,size_t * nread,void * stream,next_element next,skip_separator skip_sep,void * stream_data)3333 array_from_text(PyArray_Descr *dtype, npy_intp num, char const *sep, size_t *nread,
3334                 void *stream, next_element next, skip_separator skip_sep,
3335                 void *stream_data)
3336 {
3337     PyArrayObject *r;
3338     npy_intp i;
3339     char *dptr, *clean_sep, *tmp;
3340     int err = 0;
3341     int stop_reading_flag = 0;  /* -1 means end reached; -2 a parsing error */
3342     npy_intp thisbuf = 0;
3343     npy_intp size;
3344     npy_intp bytes, totalbytes;
3345 
3346     size = (num >= 0) ? num : FROM_BUFFER_SIZE;
3347 
3348     /*
3349      * Array creation may move sub-array dimensions from the dtype to array
3350      * dimensions, so we need to use the original dtype when reading.
3351      */
3352     Py_INCREF(dtype);
3353 
3354     r = (PyArrayObject *)
3355         PyArray_NewFromDescr(&PyArray_Type, dtype, 1, &size,
3356                              NULL, NULL, 0, NULL);
3357     if (r == NULL) {
3358         return NULL;
3359     }
3360 
3361     clean_sep = swab_separator(sep);
3362     if (clean_sep == NULL) {
3363         err = 1;
3364         goto fail;
3365     }
3366 
3367     NPY_BEGIN_ALLOW_THREADS;
3368     totalbytes = bytes = size * dtype->elsize;
3369     dptr = PyArray_DATA(r);
3370     for (i = 0; num < 0 || i < num; i++) {
3371         stop_reading_flag = next(&stream, dptr, dtype, stream_data);
3372         if (stop_reading_flag < 0) {
3373             break;
3374         }
3375         *nread += 1;
3376         thisbuf += 1;
3377         dptr += dtype->elsize;
3378         if (num < 0 && thisbuf == size) {
3379             totalbytes += bytes;
3380             tmp = PyDataMem_RENEW(PyArray_DATA(r), totalbytes);
3381             if (tmp == NULL) {
3382                 err = 1;
3383                 break;
3384             }
3385             ((PyArrayObject_fields *)r)->data = tmp;
3386             dptr = tmp + (totalbytes - bytes);
3387             thisbuf = 0;
3388         }
3389         stop_reading_flag = skip_sep(&stream, clean_sep, stream_data);
3390         if (stop_reading_flag < 0) {
3391             if (num == i + 1) {
3392                 /* if we read as much as requested sep is optional */
3393                 stop_reading_flag = -1;
3394             }
3395             break;
3396         }
3397     }
3398     if (num < 0) {
3399         const size_t nsize = PyArray_MAX(*nread,1)*dtype->elsize;
3400 
3401         if (nsize != 0) {
3402             tmp = PyDataMem_RENEW(PyArray_DATA(r), nsize);
3403             if (tmp == NULL) {
3404                 err = 1;
3405             }
3406             else {
3407                 PyArray_DIMS(r)[0] = *nread;
3408                 ((PyArrayObject_fields *)r)->data = tmp;
3409             }
3410         }
3411     }
3412     NPY_END_ALLOW_THREADS;
3413 
3414     free(clean_sep);
3415 
3416     if (stop_reading_flag == -2) {
3417         if (PyErr_Occurred()) {
3418             /* If an error is already set (unlikely), do not create new one */
3419             Py_DECREF(r);
3420             return NULL;
3421         }
3422         /* 2019-09-12, NumPy 1.18 */
3423         if (DEPRECATE(
3424                 "string or file could not be read to its end due to unmatched "
3425                 "data; this will raise a ValueError in the future.") < 0) {
3426             goto fail;
3427         }
3428     }
3429 
3430 fail:
3431     if (err == 1) {
3432         PyErr_NoMemory();
3433     }
3434     if (PyErr_Occurred()) {
3435         Py_DECREF(r);
3436         return NULL;
3437     }
3438     return r;
3439 }
3440 #undef FROM_BUFFER_SIZE
3441 
3442 /*NUMPY_API
3443  *
3444  * Given a ``FILE *`` pointer ``fp``, and a ``PyArray_Descr``, return an
3445  * array corresponding to the data encoded in that file.
3446  *
3447  * The reference to `dtype` is stolen (it is possible that the passed in
3448  * dtype is not held on to).
3449  *
3450  * The number of elements to read is given as ``num``; if it is < 0, then
3451  * then as many as possible are read.
3452  *
3453  * If ``sep`` is NULL or empty, then binary data is assumed, else
3454  * text data, with ``sep`` as the separator between elements. Whitespace in
3455  * the separator matches any length of whitespace in the text, and a match
3456  * for whitespace around the separator is added.
3457  *
3458  * For memory-mapped files, use the buffer interface. No more data than
3459  * necessary is read by this routine.
3460  */
3461 NPY_NO_EXPORT PyObject *
PyArray_FromFile(FILE * fp,PyArray_Descr * dtype,npy_intp num,char * sep)3462 PyArray_FromFile(FILE *fp, PyArray_Descr *dtype, npy_intp num, char *sep)
3463 {
3464     PyArrayObject *ret;
3465     size_t nread = 0;
3466 
3467     if (PyDataType_REFCHK(dtype)) {
3468         PyErr_SetString(PyExc_ValueError,
3469                 "Cannot read into object array");
3470         Py_DECREF(dtype);
3471         return NULL;
3472     }
3473     if (dtype->elsize == 0) {
3474         /* Nothing to read, just create an empty array of the requested type */
3475         return PyArray_NewFromDescr_int(
3476                 &PyArray_Type, dtype,
3477                 1, &num, NULL, NULL,
3478                 0, NULL, NULL,
3479                 0, 1);
3480     }
3481     if ((sep == NULL) || (strlen(sep) == 0)) {
3482         ret = array_fromfile_binary(fp, dtype, num, &nread);
3483     }
3484     else {
3485         if (dtype->f->scanfunc == NULL) {
3486             PyErr_SetString(PyExc_ValueError,
3487                     "Unable to read character files of that array type");
3488             Py_DECREF(dtype);
3489             return NULL;
3490         }
3491         ret = array_from_text(dtype, num, sep, &nread, fp,
3492                 (next_element) fromfile_next_element,
3493                 (skip_separator) fromfile_skip_separator, NULL);
3494     }
3495     if (ret == NULL) {
3496         Py_DECREF(dtype);
3497         return NULL;
3498     }
3499     if (((npy_intp) nread) < num) {
3500         /*
3501          * Realloc memory for smaller number of elements, use original dtype
3502          * which may have include a subarray (and is used for `nread`).
3503          */
3504         const size_t nsize = PyArray_MAX(nread,1) * dtype->elsize;
3505         char *tmp;
3506 
3507         if ((tmp = PyDataMem_RENEW(PyArray_DATA(ret), nsize)) == NULL) {
3508             Py_DECREF(dtype);
3509             Py_DECREF(ret);
3510             return PyErr_NoMemory();
3511         }
3512         ((PyArrayObject_fields *)ret)->data = tmp;
3513         PyArray_DIMS(ret)[0] = nread;
3514     }
3515     Py_DECREF(dtype);
3516     return (PyObject *)ret;
3517 }
3518 
3519 /*NUMPY_API*/
3520 NPY_NO_EXPORT PyObject *
PyArray_FromBuffer(PyObject * buf,PyArray_Descr * type,npy_intp count,npy_intp offset)3521 PyArray_FromBuffer(PyObject *buf, PyArray_Descr *type,
3522                    npy_intp count, npy_intp offset)
3523 {
3524     PyArrayObject *ret;
3525     char *data;
3526     Py_buffer view;
3527     Py_ssize_t ts;
3528     npy_intp s, n;
3529     int itemsize;
3530     int writeable = 1;
3531 
3532 
3533     if (PyDataType_REFCHK(type)) {
3534         PyErr_SetString(PyExc_ValueError,
3535                         "cannot create an OBJECT array from memory"\
3536                         " buffer");
3537         Py_DECREF(type);
3538         return NULL;
3539     }
3540     if (PyDataType_ISUNSIZED(type)) {
3541         PyErr_SetString(PyExc_ValueError,
3542                         "itemsize cannot be zero in type");
3543         Py_DECREF(type);
3544         return NULL;
3545     }
3546 
3547     if (PyObject_GetBuffer(buf, &view, PyBUF_WRITABLE|PyBUF_SIMPLE) < 0) {
3548         writeable = 0;
3549         PyErr_Clear();
3550         if (PyObject_GetBuffer(buf, &view, PyBUF_SIMPLE) < 0) {
3551             Py_DECREF(type);
3552             return NULL;
3553         }
3554     }
3555     data = (char *)view.buf;
3556     ts = view.len;
3557     /*
3558      * In Python 3 both of the deprecated functions PyObject_AsWriteBuffer and
3559      * PyObject_AsReadBuffer that this code replaces release the buffer. It is
3560      * up to the object that supplies the buffer to guarantee that the buffer
3561      * sticks around after the release.
3562      */
3563     PyBuffer_Release(&view);
3564 
3565     if ((offset < 0) || (offset > ts)) {
3566         PyErr_Format(PyExc_ValueError,
3567                      "offset must be non-negative and no greater than buffer "\
3568                      "length (%" NPY_INTP_FMT ")", (npy_intp)ts);
3569         Py_DECREF(type);
3570         return NULL;
3571     }
3572 
3573     data += offset;
3574     s = (npy_intp)ts - offset;
3575     n = (npy_intp)count;
3576     itemsize = type->elsize;
3577     if (n < 0) {
3578         if (itemsize == 0) {
3579             PyErr_SetString(PyExc_ValueError,
3580                             "cannot determine count if itemsize is 0");
3581             Py_DECREF(type);
3582             return NULL;
3583         }
3584         if (s % itemsize != 0) {
3585             PyErr_SetString(PyExc_ValueError,
3586                             "buffer size must be a multiple"\
3587                             " of element size");
3588             Py_DECREF(type);
3589             return NULL;
3590         }
3591         n = s/itemsize;
3592     }
3593     else {
3594         if (s < n*itemsize) {
3595             PyErr_SetString(PyExc_ValueError,
3596                             "buffer is smaller than requested"\
3597                             " size");
3598             Py_DECREF(type);
3599             return NULL;
3600         }
3601     }
3602 
3603     ret = (PyArrayObject *)PyArray_NewFromDescrAndBase(
3604             &PyArray_Type, type,
3605             1, &n, NULL, data,
3606             NPY_ARRAY_DEFAULT, NULL, buf);
3607     if (ret == NULL) {
3608         return NULL;
3609     }
3610 
3611     if (!writeable) {
3612         PyArray_CLEARFLAGS(ret, NPY_ARRAY_WRITEABLE);
3613     }
3614     return (PyObject *)ret;
3615 }
3616 
3617 /*NUMPY_API
3618  *
3619  * Given a pointer to a string ``data``, a string length ``slen``, and
3620  * a ``PyArray_Descr``, return an array corresponding to the data
3621  * encoded in that string.
3622  *
3623  * If the dtype is NULL, the default array type is used (double).
3624  * If non-null, the reference is stolen.
3625  *
3626  * If ``slen`` is < 0, then the end of string is used for text data.
3627  * It is an error for ``slen`` to be < 0 for binary data (since embedded NULLs
3628  * would be the norm).
3629  *
3630  * The number of elements to read is given as ``num``; if it is < 0, then
3631  * then as many as possible are read.
3632  *
3633  * If ``sep`` is NULL or empty, then binary data is assumed, else
3634  * text data, with ``sep`` as the separator between elements. Whitespace in
3635  * the separator matches any length of whitespace in the text, and a match
3636  * for whitespace around the separator is added.
3637  */
3638 NPY_NO_EXPORT PyObject *
PyArray_FromString(char * data,npy_intp slen,PyArray_Descr * dtype,npy_intp num,char * sep)3639 PyArray_FromString(char *data, npy_intp slen, PyArray_Descr *dtype,
3640                    npy_intp num, char *sep)
3641 {
3642     int itemsize;
3643     PyArrayObject *ret;
3644     npy_bool binary;
3645 
3646     if (dtype == NULL) {
3647         dtype=PyArray_DescrFromType(NPY_DEFAULT_TYPE);
3648         if (dtype == NULL) {
3649             return NULL;
3650         }
3651     }
3652     if (PyDataType_FLAGCHK(dtype, NPY_ITEM_IS_POINTER) ||
3653                     PyDataType_REFCHK(dtype)) {
3654         PyErr_SetString(PyExc_ValueError,
3655                         "Cannot create an object array from"    \
3656                         " a string");
3657         Py_DECREF(dtype);
3658         return NULL;
3659     }
3660     itemsize = dtype->elsize;
3661     if (itemsize == 0) {
3662         PyErr_SetString(PyExc_ValueError, "zero-valued itemsize");
3663         Py_DECREF(dtype);
3664         return NULL;
3665     }
3666 
3667     binary = ((sep == NULL) || (strlen(sep) == 0));
3668     if (binary) {
3669         if (num < 0 ) {
3670             if (slen % itemsize != 0) {
3671                 PyErr_SetString(PyExc_ValueError,
3672                                 "string size must be a "\
3673                                 "multiple of element size");
3674                 Py_DECREF(dtype);
3675                 return NULL;
3676             }
3677             num = slen/itemsize;
3678         }
3679         else {
3680             if (slen < num*itemsize) {
3681                 PyErr_SetString(PyExc_ValueError,
3682                                 "string is smaller than " \
3683                                 "requested size");
3684                 Py_DECREF(dtype);
3685                 return NULL;
3686             }
3687         }
3688         /*
3689          * NewFromDescr may replace dtype to absorb subarray shape
3690          * into the array, so get size beforehand.
3691          */
3692         npy_intp size_to_copy = num*dtype->elsize;
3693         ret = (PyArrayObject *)
3694             PyArray_NewFromDescr(&PyArray_Type, dtype,
3695                                  1, &num, NULL, NULL,
3696                                  0, NULL);
3697         if (ret == NULL) {
3698             return NULL;
3699         }
3700         memcpy(PyArray_DATA(ret), data, size_to_copy);
3701     }
3702     else {
3703         /* read from character-based string */
3704         size_t nread = 0;
3705         char *end;
3706 
3707         if (dtype->f->fromstr == NULL) {
3708             PyErr_SetString(PyExc_ValueError,
3709                             "don't know how to read "       \
3710                             "character strings with that "  \
3711                             "array type");
3712             Py_DECREF(dtype);
3713             return NULL;
3714         }
3715         if (slen < 0) {
3716             end = NULL;
3717         }
3718         else {
3719             end = data + slen;
3720         }
3721         ret = array_from_text(dtype, num, sep, &nread,
3722                               data,
3723                               (next_element) fromstr_next_element,
3724                               (skip_separator) fromstr_skip_separator,
3725                               end);
3726         Py_DECREF(dtype);
3727     }
3728     return (PyObject *)ret;
3729 }
3730 
3731 /*NUMPY_API
3732  *
3733  * steals a reference to dtype (which cannot be NULL)
3734  */
3735 NPY_NO_EXPORT PyObject *
PyArray_FromIter(PyObject * obj,PyArray_Descr * dtype,npy_intp count)3736 PyArray_FromIter(PyObject *obj, PyArray_Descr *dtype, npy_intp count)
3737 {
3738     PyObject *value;
3739     PyObject *iter = PyObject_GetIter(obj);
3740     PyArrayObject *ret = NULL;
3741     npy_intp i, elsize, elcount;
3742     char *item, *new_data;
3743 
3744     if (iter == NULL) {
3745         goto done;
3746     }
3747     if (PyDataType_ISUNSIZED(dtype)) {
3748         PyErr_SetString(PyExc_ValueError,
3749                 "Must specify length when using variable-size data-type.");
3750         goto done;
3751     }
3752     if (count < 0) {
3753         elcount = PyObject_LengthHint(obj, 0);
3754         if (elcount < 0) {
3755             goto done;
3756         }
3757     }
3758     else {
3759         elcount = count;
3760     }
3761 
3762     elsize = dtype->elsize;
3763 
3764     /*
3765      * We would need to alter the memory RENEW code to decrement any
3766      * reference counts before throwing away any memory.
3767      */
3768     if (PyDataType_REFCHK(dtype)) {
3769         PyErr_SetString(PyExc_ValueError,
3770                 "cannot create object arrays from iterator");
3771         goto done;
3772     }
3773 
3774     ret = (PyArrayObject *)PyArray_NewFromDescr(&PyArray_Type, dtype, 1,
3775                                                 &elcount, NULL,NULL, 0, NULL);
3776     dtype = NULL;
3777     if (ret == NULL) {
3778         goto done;
3779     }
3780     for (i = 0; (i < count || count == -1) &&
3781              (value = PyIter_Next(iter)); i++) {
3782         if (i >= elcount && elsize != 0) {
3783             npy_intp nbytes;
3784             /*
3785               Grow PyArray_DATA(ret):
3786               this is similar for the strategy for PyListObject, but we use
3787               50% overallocation => 0, 4, 8, 14, 23, 36, 56, 86 ...
3788             */
3789             elcount = (i >> 1) + (i < 4 ? 4 : 2) + i;
3790             if (!npy_mul_with_overflow_intp(&nbytes, elcount, elsize)) {
3791                 new_data = PyDataMem_RENEW(PyArray_DATA(ret), nbytes);
3792             }
3793             else {
3794                 new_data = NULL;
3795             }
3796             if (new_data == NULL) {
3797                 PyErr_SetString(PyExc_MemoryError,
3798                         "cannot allocate array memory");
3799                 Py_DECREF(value);
3800                 goto done;
3801             }
3802             ((PyArrayObject_fields *)ret)->data = new_data;
3803         }
3804         PyArray_DIMS(ret)[0] = i + 1;
3805 
3806         if (((item = index2ptr(ret, i)) == NULL) ||
3807                 PyArray_SETITEM(ret, item, value) == -1) {
3808             Py_DECREF(value);
3809             goto done;
3810         }
3811         Py_DECREF(value);
3812     }
3813 
3814 
3815     if (PyErr_Occurred()) {
3816         goto done;
3817     }
3818     if (i < count) {
3819         PyErr_SetString(PyExc_ValueError,
3820                 "iterator too short");
3821         goto done;
3822     }
3823 
3824     /*
3825      * Realloc the data so that don't keep extra memory tied up
3826      * (assuming realloc is reasonably good about reusing space...)
3827      */
3828     if (i == 0 || elsize == 0) {
3829         /* The size cannot be zero for PyDataMem_RENEW. */
3830         goto done;
3831     }
3832     new_data = PyDataMem_RENEW(PyArray_DATA(ret), i * elsize);
3833     if (new_data == NULL) {
3834         PyErr_SetString(PyExc_MemoryError,
3835                 "cannot allocate array memory");
3836         goto done;
3837     }
3838     ((PyArrayObject_fields *)ret)->data = new_data;
3839 
3840  done:
3841     Py_XDECREF(iter);
3842     Py_XDECREF(dtype);
3843     if (PyErr_Occurred()) {
3844         Py_XDECREF(ret);
3845         return NULL;
3846     }
3847     return (PyObject *)ret;
3848 }
3849 
3850 /*
3851  * This is the main array creation routine.
3852  *
3853  * Flags argument has multiple related meanings
3854  * depending on data and strides:
3855  *
3856  * If data is given, then flags is flags associated with data.
3857  * If strides is not given, then a contiguous strides array will be created
3858  * and the NPY_ARRAY_C_CONTIGUOUS bit will be set.  If the flags argument
3859  * has the NPY_ARRAY_F_CONTIGUOUS bit set, then a FORTRAN-style strides array will be
3860  * created (and of course the NPY_ARRAY_F_CONTIGUOUS flag bit will be set).
3861  *
3862  * If data is not given but created here, then flags will be NPY_ARRAY_DEFAULT
3863  * and a non-zero flags argument can be used to indicate a FORTRAN style
3864  * array is desired.
3865  *
3866  * Dimensions and itemsize must have been checked for validity.
3867  */
3868 
3869 NPY_NO_EXPORT void
_array_fill_strides(npy_intp * strides,npy_intp const * dims,int nd,size_t itemsize,int inflag,int * objflags)3870 _array_fill_strides(npy_intp *strides, npy_intp const *dims, int nd, size_t itemsize,
3871                     int inflag, int *objflags)
3872 {
3873     int i;
3874 #if NPY_RELAXED_STRIDES_CHECKING
3875     npy_bool not_cf_contig = 0;
3876     npy_bool nod = 0; /* A dim != 1 was found */
3877 
3878     /* Check if new array is both F- and C-contiguous */
3879     for (i = 0; i < nd; i++) {
3880         if (dims[i] != 1) {
3881             if (nod) {
3882                 not_cf_contig = 1;
3883                 break;
3884             }
3885             nod = 1;
3886         }
3887     }
3888 #endif /* NPY_RELAXED_STRIDES_CHECKING */
3889 
3890     /* Only make Fortran strides if not contiguous as well */
3891     if ((inflag & (NPY_ARRAY_F_CONTIGUOUS|NPY_ARRAY_C_CONTIGUOUS)) ==
3892                                             NPY_ARRAY_F_CONTIGUOUS) {
3893         for (i = 0; i < nd; i++) {
3894             strides[i] = itemsize;
3895             if (dims[i]) {
3896                 itemsize *= dims[i];
3897             }
3898 #if NPY_RELAXED_STRIDES_CHECKING
3899             else {
3900                 not_cf_contig = 0;
3901             }
3902 #if NPY_RELAXED_STRIDES_DEBUG
3903             /* For testing purpose only */
3904             if (dims[i] == 1) {
3905                 strides[i] = NPY_MAX_INTP;
3906             }
3907 #endif /* NPY_RELAXED_STRIDES_DEBUG */
3908 #endif /* NPY_RELAXED_STRIDES_CHECKING */
3909         }
3910 #if NPY_RELAXED_STRIDES_CHECKING
3911         if (not_cf_contig) {
3912 #else /* not NPY_RELAXED_STRIDES_CHECKING */
3913         if ((nd > 1) && ((strides[0] != strides[nd-1]) || (dims[nd-1] > 1))) {
3914 #endif /* not NPY_RELAXED_STRIDES_CHECKING */
3915             *objflags = ((*objflags)|NPY_ARRAY_F_CONTIGUOUS) &
3916                                             ~NPY_ARRAY_C_CONTIGUOUS;
3917         }
3918         else {
3919             *objflags |= (NPY_ARRAY_F_CONTIGUOUS|NPY_ARRAY_C_CONTIGUOUS);
3920         }
3921     }
3922     else {
3923         for (i = nd - 1; i >= 0; i--) {
3924             strides[i] = itemsize;
3925             if (dims[i]) {
3926                 itemsize *= dims[i];
3927             }
3928 #if NPY_RELAXED_STRIDES_CHECKING
3929             else {
3930                 not_cf_contig = 0;
3931             }
3932 #if NPY_RELAXED_STRIDES_DEBUG
3933             /* For testing purpose only */
3934             if (dims[i] == 1) {
3935                 strides[i] = NPY_MAX_INTP;
3936             }
3937 #endif /* NPY_RELAXED_STRIDES_DEBUG */
3938 #endif /* NPY_RELAXED_STRIDES_CHECKING */
3939         }
3940 #if NPY_RELAXED_STRIDES_CHECKING
3941         if (not_cf_contig) {
3942 #else /* not NPY_RELAXED_STRIDES_CHECKING */
3943         if ((nd > 1) && ((strides[0] != strides[nd-1]) || (dims[0] > 1))) {
3944 #endif /* not NPY_RELAXED_STRIDES_CHECKING */
3945             *objflags = ((*objflags)|NPY_ARRAY_C_CONTIGUOUS) &
3946                                             ~NPY_ARRAY_F_CONTIGUOUS;
3947         }
3948         else {
3949             *objflags |= (NPY_ARRAY_C_CONTIGUOUS|NPY_ARRAY_F_CONTIGUOUS);
3950         }
3951     }
3952     return;
3953 }
3954 
3955 /*
3956  * Calls arr_of_subclass.__array_wrap__(towrap), in order to make 'towrap'
3957  * have the same ndarray subclass as 'arr_of_subclass'.
3958  */
3959 NPY_NO_EXPORT PyArrayObject *
3960 PyArray_SubclassWrap(PyArrayObject *arr_of_subclass, PyArrayObject *towrap)
3961 {
3962     PyObject *wrapped = PyObject_CallMethod((PyObject *)arr_of_subclass,
3963                                         "__array_wrap__", "O", towrap);
3964     if (wrapped == NULL) {
3965         return NULL;
3966     }
3967     if (!PyArray_Check(wrapped)) {
3968         PyErr_SetString(PyExc_RuntimeError,
3969                 "ndarray subclass __array_wrap__ method returned an "
3970                 "object which was not an instance of an ndarray subclass");
3971         Py_DECREF(wrapped);
3972         return NULL;
3973     }
3974 
3975     return (PyArrayObject *)wrapped;
3976 }
3977