-
-
Notifications
You must be signed in to change notification settings - Fork 9.5k
/
ctors.c
3961 lines (3635 loc) · 116 KB
/
ctors.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include "structmember.h"
#define NPY_NO_DEPRECATED_API NPY_API_VERSION
#define _MULTIARRAYMODULE
#include "numpy/arrayobject.h"
#include "numpy/arrayscalars.h"
#include "numpy/npy_math.h"
#include "npy_config.h"
#include "npy_ctypes.h"
#include "npy_pycompat.h"
#include "multiarraymodule.h"
#include "common.h"
#include "ctors.h"
#include "convert_datatype.h"
#include "shape.h"
#include "npy_buffer.h"
#include "lowlevel_strided_loops.h"
#include "_datetime.h"
#include "datetime_strings.h"
#include "array_assign.h"
#include "mapping.h" /* for array_item_asarray */
#include "templ_common.h" /* for npy_mul_with_overflow_intp */
#include "alloc.h"
#include <assert.h>
#include "get_attr_string.h"
#include "array_coercion.h"
/*
* Reading from a file or a string.
*
* As much as possible, we try to use the same code for both files and strings,
* so the semantics for fromstring and fromfile are the same, especially with
* regards to the handling of text representations.
*/
/*
* Scanning function for next element parsing and separator skipping.
* These functions return:
* - 0 to indicate more data to read
* - -1 when reading stopped at the end of the string/file
* - -2 when reading stopped before the end was reached.
*
* The dtype specific parsing functions may set the python error state
* (they have to get the GIL first) additionally.
*/
typedef int (*next_element)(void **, void *, PyArray_Descr *, void *);
typedef int (*skip_separator)(void **, const char *, void *);
static npy_bool
string_is_fully_read(char const* start, char const* end) {
if (end == NULL) {
return *start == '\0'; /* null terminated */
}
else {
return start >= end; /* fixed length */
}
}
static int
fromstr_next_element(char **s, void *dptr, PyArray_Descr *dtype,
const char *end)
{
char *e = *s;
int r = dtype->f->fromstr(*s, dptr, &e, dtype);
/*
* fromstr always returns 0 for basic dtypes; s points to the end of the
* parsed string. If s is not changed an error occurred or the end was
* reached.
*/
if (*s == e || r < 0) {
/* Nothing read, could be end of string or an error (or both) */
if (string_is_fully_read(*s, end)) {
return -1;
}
return -2;
}
*s = e;
if (end != NULL && *s > end) {
/* Stop the iteration if we read far enough */
return -1;
}
return 0;
}
static int
fromfile_next_element(FILE **fp, void *dptr, PyArray_Descr *dtype,
void *NPY_UNUSED(stream_data))
{
/* the NULL argument is for backwards-compatibility */
int r = dtype->f->scanfunc(*fp, dptr, NULL, dtype);
/* r can be EOF or the number of items read (0 or 1) */
if (r == 1) {
return 0;
}
else if (r == EOF) {
return -1;
}
else {
/* unable to read more, but EOF not reached indicating an error. */
return -2;
}
}
/*
* Remove multiple whitespace from the separator, and add a space to the
* beginning and end. This simplifies the separator-skipping code below.
*/
static char *
swab_separator(const char *sep)
{
int skip_space = 0;
char *s, *start;
s = start = malloc(strlen(sep)+3);
if (s == NULL) {
PyErr_NoMemory();
return NULL;
}
/* add space to front if there isn't one */
if (*sep != '\0' && !isspace(*sep)) {
*s = ' '; s++;
}
while (*sep != '\0') {
if (isspace(*sep)) {
if (skip_space) {
sep++;
}
else {
*s = ' ';
s++;
sep++;
skip_space = 1;
}
}
else {
*s = *sep;
s++;
sep++;
skip_space = 0;
}
}
/* add space to end if there isn't one */
if (s != start && s[-1] == ' ') {
*s = ' ';
s++;
}
*s = '\0';
return start;
}
/*
* Assuming that the separator is the next bit in the string (file), skip it.
*
* Single spaces in the separator are matched to arbitrary-long sequences
* of whitespace in the input. If the separator consists only of spaces,
* it matches one or more whitespace characters.
*
* If we can't match the separator, return -2.
* If we hit the end of the string (file), return -1.
* Otherwise, return 0.
*/
static int
fromstr_skip_separator(char **s, const char *sep, const char *end)
{
char *string = *s;
int result = 0;
while (1) {
char c = *string;
if (string_is_fully_read(string, end)) {
result = -1;
break;
}
else if (*sep == '\0') {
if (string != *s) {
/* matched separator */
result = 0;
break;
}
else {
/* separator was whitespace wildcard that didn't match */
result = -2;
break;
}
}
else if (*sep == ' ') {
/* whitespace wildcard */
if (!isspace(c)) {
sep++;
continue;
}
}
else if (*sep != c) {
result = -2;
break;
}
else {
sep++;
}
string++;
}
*s = string;
return result;
}
static int
fromfile_skip_separator(FILE **fp, const char *sep, void *NPY_UNUSED(stream_data))
{
int result = 0;
const char *sep_start = sep;
while (1) {
int c = fgetc(*fp);
if (c == EOF) {
result = -1;
break;
}
else if (*sep == '\0') {
ungetc(c, *fp);
if (sep != sep_start) {
/* matched separator */
result = 0;
break;
}
else {
/* separator was whitespace wildcard that didn't match */
result = -2;
break;
}
}
else if (*sep == ' ') {
/* whitespace wildcard */
if (!isspace(c)) {
sep++;
sep_start++;
ungetc(c, *fp);
}
else if (sep == sep_start) {
sep_start--;
}
}
else if (*sep != c) {
ungetc(c, *fp);
result = -2;
break;
}
else {
sep++;
}
}
return result;
}
/*
* Change a sub-array field to the base descriptor
* and update the dimensions and strides
* appropriately. Dimensions and strides are added
* to the end.
*
* Strides are only added if given (because data is given).
*/
static int
_update_descr_and_dimensions(PyArray_Descr **des, npy_intp *newdims,
npy_intp *newstrides, int oldnd)
{
PyArray_Descr *old;
int newnd;
int numnew;
npy_intp *mydim;
int i;
int tuple;
old = *des;
*des = old->subarray->base;
mydim = newdims + oldnd;
tuple = PyTuple_Check(old->subarray->shape);
if (tuple) {
numnew = PyTuple_GET_SIZE(old->subarray->shape);
}
else {
numnew = 1;
}
newnd = oldnd + numnew;
if (newnd > NPY_MAXDIMS) {
goto finish;
}
if (tuple) {
for (i = 0; i < numnew; i++) {
mydim[i] = (npy_intp) PyLong_AsLong(
PyTuple_GET_ITEM(old->subarray->shape, i));
}
}
else {
mydim[0] = (npy_intp) PyLong_AsLong(old->subarray->shape);
}
if (newstrides) {
npy_intp tempsize;
npy_intp *mystrides;
mystrides = newstrides + oldnd;
/* Make new strides -- always C-contiguous */
tempsize = (*des)->elsize;
for (i = numnew - 1; i >= 0; i--) {
mystrides[i] = tempsize;
tempsize *= mydim[i] ? mydim[i] : 1;
}
}
finish:
Py_INCREF(*des);
Py_DECREF(old);
return newnd;
}
NPY_NO_EXPORT void
_unaligned_strided_byte_copy(char *dst, npy_intp outstrides, char *src,
npy_intp instrides, npy_intp N, int elsize)
{
npy_intp i;
char *tout = dst;
char *tin = src;
#define _COPY_N_SIZE(size) \
for(i=0; i<N; i++) { \
memcpy(tout, tin, size); \
tin += instrides; \
tout += outstrides; \
} \
return
switch(elsize) {
case 8:
_COPY_N_SIZE(8);
case 4:
_COPY_N_SIZE(4);
case 1:
_COPY_N_SIZE(1);
case 2:
_COPY_N_SIZE(2);
case 16:
_COPY_N_SIZE(16);
default:
_COPY_N_SIZE(elsize);
}
#undef _COPY_N_SIZE
}
NPY_NO_EXPORT void
_strided_byte_swap(void *p, npy_intp stride, npy_intp n, int size)
{
char *a, *b, c = 0;
int j, m;
switch(size) {
case 1: /* no byteswap necessary */
break;
case 4:
if (npy_is_aligned((void*)((npy_intp)p | stride), sizeof(npy_uint32))) {
for (a = (char*)p; n > 0; n--, a += stride) {
npy_uint32 * a_ = (npy_uint32 *)a;
*a_ = npy_bswap4(*a_);
}
}
else {
for (a = (char*)p; n > 0; n--, a += stride) {
npy_bswap4_unaligned(a);
}
}
break;
case 8:
if (npy_is_aligned((void*)((npy_intp)p | stride), sizeof(npy_uint64))) {
for (a = (char*)p; n > 0; n--, a += stride) {
npy_uint64 * a_ = (npy_uint64 *)a;
*a_ = npy_bswap8(*a_);
}
}
else {
for (a = (char*)p; n > 0; n--, a += stride) {
npy_bswap8_unaligned(a);
}
}
break;
case 2:
if (npy_is_aligned((void*)((npy_intp)p | stride), sizeof(npy_uint16))) {
for (a = (char*)p; n > 0; n--, a += stride) {
npy_uint16 * a_ = (npy_uint16 *)a;
*a_ = npy_bswap2(*a_);
}
}
else {
for (a = (char*)p; n > 0; n--, a += stride) {
npy_bswap2_unaligned(a);
}
}
break;
default:
m = size/2;
for (a = (char *)p; n > 0; n--, a += stride - m) {
b = a + (size - 1);
for (j = 0; j < m; j++) {
c=*a; *a++ = *b; *b-- = c;
}
}
break;
}
}
NPY_NO_EXPORT void
byte_swap_vector(void *p, npy_intp n, int size)
{
_strided_byte_swap(p, (npy_intp) size, n, size);
return;
}
/* If numitems > 1, then dst must be contiguous */
NPY_NO_EXPORT void
copy_and_swap(void *dst, void *src, int itemsize, npy_intp numitems,
npy_intp srcstrides, int swap)
{
if ((numitems == 1) || (itemsize == srcstrides)) {
memcpy(dst, src, itemsize*numitems);
}
else {
npy_intp i;
char *s1 = (char *)src;
char *d1 = (char *)dst;
for (i = 0; i < numitems; i++) {
memcpy(d1, s1, itemsize);
d1 += itemsize;
s1 += srcstrides;
}
}
if (swap) {
byte_swap_vector(dst, numitems, itemsize);
}
}
/*
* Recursive helper to assign using a coercion cache. This function
* must consume the cache depth first, just as the cache was originally
* produced.
*/
NPY_NO_EXPORT int
PyArray_AssignFromCache_Recursive(
PyArrayObject *self, const int ndim, coercion_cache_obj **cache)
{
/* Consume first cache element by extracting information and freeing it */
PyObject *original_obj = (*cache)->converted_obj;
PyObject *obj = (*cache)->arr_or_sequence;
Py_INCREF(obj);
npy_bool sequence = (*cache)->sequence;
int depth = (*cache)->depth;
*cache = npy_unlink_coercion_cache(*cache);
/*
* The maximum depth is special (specifically for objects), but usually
* unrolled in the sequence branch below.
*/
if (NPY_UNLIKELY(depth == ndim)) {
/*
* We have reached the maximum depth. We should simply assign to the
* element in principle. There is one exception. If this is a 0-D
* array being stored into a 0-D array (but we do not reach here then).
*/
if (PyArray_ISOBJECT(self)) {
assert(ndim != 0); /* guaranteed by PyArray_AssignFromCache */
assert(PyArray_NDIM(self) == 0);
Py_DECREF(obj);
return PyArray_Pack(PyArray_DESCR(self), PyArray_BYTES(self),
original_obj);
}
if (sequence) {
/*
* Sanity check which may be removed, the error is raised already
* in `PyArray_DiscoverDTypeAndShape`.
*/
assert(0);
PyErr_SetString(PyExc_RuntimeError,
"setting an array element with a sequence");
goto fail;
}
else if (original_obj != obj || !PyArray_CheckExact(obj)) {
/*
* If the leave node is an array-like, but not a numpy array,
* we pretend it is an arbitrary scalar. This means that in
* most cases (where the dtype is int or float), we will end
* up using float(array-like), or int(array-like). That does
* not support general casting, but helps Quantity and masked
* arrays, because it allows them to raise an error when
* `__float__()` or `__int__()` is called.
*/
Py_DECREF(obj);
return PyArray_SETITEM(self, PyArray_BYTES(self), original_obj);
}
}
/* The element is either a sequence, or an array */
if (!sequence) {
/* Straight forward array assignment */
assert(PyArray_Check(obj));
if (PyArray_CopyInto(self, (PyArrayObject *)obj) < 0) {
goto fail;
}
}
else {
assert(depth != ndim);
npy_intp length = PySequence_Length(obj);
if (length != PyArray_DIMS(self)[0]) {
PyErr_SetString(PyExc_RuntimeError,
"Inconsistent object during array creation? "
"Content of sequences changed (length inconsistent).");
goto fail;
}
for (npy_intp i = 0; i < length; i++) {
PyObject *value = PySequence_Fast_GET_ITEM(obj, i);
if (*cache == NULL || (*cache)->converted_obj != value ||
(*cache)->depth != depth + 1) {
if (ndim != depth + 1) {
PyErr_SetString(PyExc_RuntimeError,
"Inconsistent object during array creation? "
"Content of sequences changed (now too shallow).");
goto fail;
}
/* Straight forward assignment of elements */
char *item;
item = (PyArray_BYTES(self) + i * PyArray_STRIDES(self)[0]);
if (PyArray_Pack(PyArray_DESCR(self), item, value) < 0) {
goto fail;
}
}
else {
PyArrayObject *view;
view = (PyArrayObject *)array_item_asarray(self, i);
if (view < 0) {
goto fail;
}
if (PyArray_AssignFromCache_Recursive(view, ndim, cache) < 0) {
Py_DECREF(view);
goto fail;
}
Py_DECREF(view);
}
}
}
Py_DECREF(obj);
return 0;
fail:
Py_DECREF(obj);
return -1;
}
/**
* Fills an item based on a coercion cache object. It consumes the cache
* object while doing so.
*
* @param self Array to fill.
* @param cache coercion_cache_object, will be consumed. The cache must not
* contain a single array (must start with a sequence). The array case
* should be handled by `PyArray_FromArray()` before.
* @return 0 on success -1 on failure.
*/
NPY_NO_EXPORT int
PyArray_AssignFromCache(PyArrayObject *self, coercion_cache_obj *cache) {
int ndim = PyArray_NDIM(self);
/*
* Do not support ndim == 0 now with an array in the cache.
* The ndim == 0 is special because np.array(np.array(0), dtype=object)
* should unpack the inner array.
* Since the single-array case is special, it is handled previously
* in either case.
*/
assert(cache->sequence);
assert(ndim != 0); /* guaranteed if cache contains a sequence */
if (PyArray_AssignFromCache_Recursive(self, ndim, &cache) < 0) {
/* free the remaining cache. */
npy_free_coercion_cache(cache);
return -1;
}
/*
* Sanity check, this is the initial call, and when it returns, the
* cache has to be fully consumed, otherwise something is wrong.
* NOTE: May be nicer to put into a recursion helper.
*/
if (cache != NULL) {
PyErr_SetString(PyExc_RuntimeError,
"Inconsistent object during array creation? "
"Content of sequences changed (cache not consumed).");
npy_free_coercion_cache(cache);
return -1;
}
return 0;
}
static void
raise_memory_error(int nd, npy_intp const *dims, PyArray_Descr *descr)
{
static PyObject *exc_type = NULL;
npy_cache_import(
"numpy.core._exceptions", "_ArrayMemoryError",
&exc_type);
if (exc_type == NULL) {
goto fail;
}
PyObject *shape = PyArray_IntTupleFromIntp(nd, dims);
if (shape == NULL) {
goto fail;
}
/* produce an error object */
PyObject *exc_value = PyTuple_Pack(2, shape, (PyObject *)descr);
Py_DECREF(shape);
if (exc_value == NULL){
goto fail;
}
PyErr_SetObject(exc_type, exc_value);
Py_DECREF(exc_value);
return;
fail:
/* we couldn't raise the formatted exception for some reason */
PyErr_WriteUnraisable(NULL);
PyErr_NoMemory();
}
/*
* Generic new array creation routine.
* Internal variant with calloc argument for PyArray_Zeros.
*
* steals a reference to descr. On failure or descr->subarray, descr will
* be decrefed.
*/
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)
{
PyArrayObject_fields *fa;
int i;
npy_intp nbytes;
if (descr->subarray) {
PyObject *ret;
npy_intp newdims[2*NPY_MAXDIMS];
npy_intp *newstrides = NULL;
memcpy(newdims, dims, nd*sizeof(npy_intp));
if (strides) {
newstrides = newdims + NPY_MAXDIMS;
memcpy(newstrides, strides, nd*sizeof(npy_intp));
}
nd =_update_descr_and_dimensions(&descr, newdims,
newstrides, nd);
ret = PyArray_NewFromDescr_int(
subtype, descr,
nd, newdims, newstrides, data,
flags, obj, base,
zeroed, allow_emptystring);
return ret;
}
if ((unsigned int)nd > (unsigned int)NPY_MAXDIMS) {
PyErr_Format(PyExc_ValueError,
"number of dimensions must be within [0, %d]",
NPY_MAXDIMS);
Py_DECREF(descr);
return NULL;
}
/* Check datatype element size */
nbytes = descr->elsize;
if (PyDataType_ISUNSIZED(descr)) {
if (!PyDataType_ISFLEXIBLE(descr)) {
PyErr_SetString(PyExc_TypeError, "Empty data-type");
Py_DECREF(descr);
return NULL;
}
else if (PyDataType_ISSTRING(descr) && !allow_emptystring &&
data == NULL) {
PyArray_DESCR_REPLACE(descr);
if (descr == NULL) {
return NULL;
}
if (descr->type_num == NPY_STRING) {
nbytes = descr->elsize = 1;
}
else {
nbytes = descr->elsize = sizeof(npy_ucs4);
}
}
}
/* Check dimensions and multiply them to nbytes */
for (i = 0; i < nd; i++) {
npy_intp dim = dims[i];
if (dim == 0) {
/*
* Compare to PyArray_OverflowMultiplyList that
* returns 0 in this case.
*/
continue;
}
if (dim < 0) {
PyErr_SetString(PyExc_ValueError,
"negative dimensions are not allowed");
Py_DECREF(descr);
return NULL;
}
/*
* Care needs to be taken to avoid integer overflow when
* multiplying the dimensions together to get the total size of the
* array.
*/
if (npy_mul_with_overflow_intp(&nbytes, nbytes, dim)) {
PyErr_SetString(PyExc_ValueError,
"array is too big; `arr.size * arr.dtype.itemsize` "
"is larger than the maximum possible size.");
Py_DECREF(descr);
return NULL;
}
}
fa = (PyArrayObject_fields *) subtype->tp_alloc(subtype, 0);
if (fa == NULL) {
Py_DECREF(descr);
return NULL;
}
fa->_buffer_info = NULL;
fa->nd = nd;
fa->dimensions = NULL;
fa->data = NULL;
if (data == NULL) {
fa->flags = NPY_ARRAY_DEFAULT;
if (flags) {
fa->flags |= NPY_ARRAY_F_CONTIGUOUS;
if (nd > 1) {
fa->flags &= ~NPY_ARRAY_C_CONTIGUOUS;
}
flags = NPY_ARRAY_F_CONTIGUOUS;
}
}
else {
fa->flags = (flags & ~NPY_ARRAY_WRITEBACKIFCOPY);
fa->flags &= ~NPY_ARRAY_UPDATEIFCOPY;
}
fa->descr = descr;
fa->base = (PyObject *)NULL;
fa->weakreflist = (PyObject *)NULL;
if (nd > 0) {
fa->dimensions = npy_alloc_cache_dim(2 * nd);
if (fa->dimensions == NULL) {
PyErr_NoMemory();
goto fail;
}
fa->strides = fa->dimensions + nd;
if (nd) {
memcpy(fa->dimensions, dims, sizeof(npy_intp)*nd);
}
if (strides == NULL) { /* fill it in */
_array_fill_strides(fa->strides, dims, nd, descr->elsize,
flags, &(fa->flags));
}
else {
/*
* we allow strides even when we create
* the memory, but be careful with this...
*/
if (nd) {
memcpy(fa->strides, strides, sizeof(npy_intp)*nd);
}
}
}
else {
fa->dimensions = fa->strides = NULL;
fa->flags |= NPY_ARRAY_F_CONTIGUOUS;
}
if (data == NULL) {
/*
* Allocate something even for zero-space arrays
* e.g. shape=(0,) -- otherwise buffer exposure
* (a.data) doesn't work as it should.
* Could probably just allocate a few bytes here. -- Chuck
*/
if (nbytes == 0) {
nbytes = descr->elsize ? descr->elsize : 1;
}
/*
* It is bad to have uninitialized OBJECT pointers
* which could also be sub-fields of a VOID array
*/
if (zeroed || PyDataType_FLAGCHK(descr, NPY_NEEDS_INIT)) {
data = npy_alloc_cache_zero(nbytes);
}
else {
data = npy_alloc_cache(nbytes);
}
if (data == NULL) {
raise_memory_error(fa->nd, fa->dimensions, descr);
goto fail;
}
fa->flags |= NPY_ARRAY_OWNDATA;
}
else {
/*
* If data is passed in, this object won't own it by default.
* Caller must arrange for this to be reset if truly desired
*/
fa->flags &= ~NPY_ARRAY_OWNDATA;
}
fa->data = data;
/*
* always update the flags to get the right CONTIGUOUS, ALIGN properties
* not owned data and input strides may not be aligned and on some
* platforms (debian sparc) malloc does not provide enough alignment for
* long double types
*/
PyArray_UpdateFlags((PyArrayObject *)fa, NPY_ARRAY_UPDATE_ALL);
/* Set the base object. It's important to do it here so that
* __array_finalize__ below receives it
*/
if (base != NULL) {
Py_INCREF(base);
if (PyArray_SetBaseObject((PyArrayObject *)fa, base) < 0) {
goto fail;
}
}
/*
* call the __array_finalize__
* method if a subtype.
* If obj is NULL, then call method with Py_None
*/
if ((subtype != &PyArray_Type)) {
PyObject *res, *func, *args;
func = PyObject_GetAttr((PyObject *)fa, npy_ma_str_array_finalize);
if (func && func != Py_None) {
if (PyCapsule_CheckExact(func)) {
/* A C-function is stored here */
PyArray_FinalizeFunc *cfunc;
cfunc = PyCapsule_GetPointer(func, NULL);
Py_DECREF(func);
if (cfunc == NULL) {
goto fail;
}
if (cfunc((PyArrayObject *)fa, obj) < 0) {
goto fail;
}
}
else {
args = PyTuple_New(1);
if (obj == NULL) {
obj=Py_None;
}
Py_INCREF(obj);
PyTuple_SET_ITEM(args, 0, obj);
res = PyObject_Call(func, args, NULL);
Py_DECREF(args);
Py_DECREF(func);
if (res == NULL) {
goto fail;
}
else {
Py_DECREF(res);
}
}
}
else Py_XDECREF(func);
}
return (PyObject *)fa;
fail:
Py_DECREF(fa);
return NULL;
}
/*NUMPY_API
* Generic new array creation routine.
*
* steals a reference to descr. On failure or when dtype->subarray is
* true, dtype will be decrefed.
*/
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)
{
return PyArray_NewFromDescrAndBase(
subtype, descr,
nd, dims, strides, data,
flags, obj, NULL);
}
/*
* Sets the base object using PyArray_SetBaseObject
*/
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)
{
return PyArray_NewFromDescr_int(subtype, descr, nd,
dims, strides, data,
flags, obj, base, 0, 0);
}
/*
* Creates a new array with the same shape as the provided one,
* with possible memory layout order, data type and shape changes.
*
* prototype - The array the new one should be like.
* order - NPY_CORDER - C-contiguous result.
* NPY_FORTRANORDER - Fortran-contiguous result.
* NPY_ANYORDER - Fortran if prototype is Fortran, C otherwise.
* NPY_KEEPORDER - Keeps the axis ordering of prototype.
* dtype - If not NULL, overrides the data type of the result.
* ndim - If not -1, overrides the shape of the result.
* dims - If ndim is not -1, overrides the shape of the result.
* subok - If 1, use the prototype's array subtype, otherwise
* always create a base-class array.
*
* NOTE: If dtype is not NULL, steals the dtype reference. On failure or when
* dtype->subarray is true, dtype will be decrefed.
*/
NPY_NO_EXPORT PyObject *
PyArray_NewLikeArrayWithShape(PyArrayObject *prototype, NPY_ORDER order,
PyArray_Descr *dtype, int ndim, npy_intp const *dims, int subok)
{
PyObject *ret = NULL;
if (ndim == -1) {
ndim = PyArray_NDIM(prototype);
dims = PyArray_DIMS(prototype);
}
else if (order == NPY_KEEPORDER && (ndim != PyArray_NDIM(prototype))) {
order = NPY_CORDER;
}
/* If no override data type, use the one from the prototype */
if (dtype == NULL) {
dtype = PyArray_DESCR(prototype);
Py_INCREF(dtype);
}
/* Handle ANYORDER and simple KEEPORDER cases */
switch (order) {
case NPY_ANYORDER:
order = PyArray_ISFORTRAN(prototype) ?
NPY_FORTRANORDER : NPY_CORDER;
break;
case NPY_KEEPORDER:
if (PyArray_IS_C_CONTIGUOUS(prototype) || ndim <= 1) {
order = NPY_CORDER;
break;
}
else if (PyArray_IS_F_CONTIGUOUS(prototype)) {
order = NPY_FORTRANORDER;
break;
}
break;
default: