/
arrayobject.c
1754 lines (1599 loc) · 52.9 KB
/
arrayobject.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
/*
Provide multidimensional arrays as a basic object type in python.
Based on Original Numeric implementation
Copyright (c) 1995, 1996, 1997 Jim Hugunin, hugunin@mit.edu
with contributions from many Numeric Python developers 1995-2004
Heavily modified in 2005 with inspiration from Numarray
by
Travis Oliphant, oliphant@ee.byu.edu
Brigham Young University
maintainer email: oliphant.travis@ieee.org
Numarray design (which provided guidance) by
Space Science Telescope Institute
(J. Todd Miller, Perry Greenfield, Rick White)
*/
#define NPY_NO_DEPRECATED_API NPY_API_VERSION
#define _MULTIARRAYMODULE
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include <structmember.h>
#include "numpy/arrayobject.h"
#include "numpy/arrayscalars.h"
#include "npy_config.h"
#include "npy_pycompat.h"
#include "common.h"
#include "number.h"
#include "usertypes.h"
#include "arraytypes.h"
#include "scalartypes.h"
#include "arrayobject.h"
#include "convert_datatype.h"
#include "conversion_utils.h"
#include "ctors.h"
#include "dtypemeta.h"
#include "methods.h"
#include "descriptor.h"
#include "iterators.h"
#include "mapping.h"
#include "getset.h"
#include "sequence.h"
#include "npy_buffer.h"
#include "array_assign.h"
#include "alloc.h"
#include "mem_overlap.h"
#include "numpyos.h"
#include "strfuncs.h"
#include "binop_override.h"
#include "array_coercion.h"
/*NUMPY_API
Compute the size of an array (in number of items)
*/
NPY_NO_EXPORT npy_intp
PyArray_Size(PyObject *op)
{
if (PyArray_Check(op)) {
return PyArray_SIZE((PyArrayObject *)op);
}
else {
return 0;
}
}
/*NUMPY_API
*
* Precondition: 'arr' is a copy of 'base' (though possibly with different
* strides, ordering, etc.). This function sets the UPDATEIFCOPY flag and the
* ->base pointer on 'arr', so that when 'arr' is destructed, it will copy any
* changes back to 'base'. DEPRECATED, use PyArray_SetWritebackIfCopyBase
*
* Steals a reference to 'base'.
*
* Returns 0 on success, -1 on failure.
*/
NPY_NO_EXPORT int
PyArray_SetUpdateIfCopyBase(PyArrayObject *arr, PyArrayObject *base)
{
int ret;
/* 2017-Nov -10 1.14 (for PyPy only) */
/* 2018-April-21 1.15 (all Python implementations) */
if (DEPRECATE("PyArray_SetUpdateIfCopyBase is deprecated, use "
"PyArray_SetWritebackIfCopyBase instead, and be sure to call "
"PyArray_ResolveWritebackIfCopy before the array is deallocated, "
"i.e. before the last call to Py_DECREF. If cleaning up from an "
"error, PyArray_DiscardWritebackIfCopy may be called instead to "
"throw away the scratch buffer.") < 0)
return -1;
ret = PyArray_SetWritebackIfCopyBase(arr, base);
if (ret >=0) {
PyArray_ENABLEFLAGS(arr, NPY_ARRAY_UPDATEIFCOPY);
PyArray_CLEARFLAGS(arr, NPY_ARRAY_WRITEBACKIFCOPY);
}
return ret;
}
/*NUMPY_API
*
* Precondition: 'arr' is a copy of 'base' (though possibly with different
* strides, ordering, etc.). This function sets the WRITEBACKIFCOPY flag and the
* ->base pointer on 'arr', call PyArray_ResolveWritebackIfCopy to copy any
* changes back to 'base' before deallocating the array.
*
* Steals a reference to 'base'.
*
* Returns 0 on success, -1 on failure.
*/
NPY_NO_EXPORT int
PyArray_SetWritebackIfCopyBase(PyArrayObject *arr, PyArrayObject *base)
{
if (base == NULL) {
PyErr_SetString(PyExc_ValueError,
"Cannot WRITEBACKIFCOPY to NULL array");
return -1;
}
if (PyArray_BASE(arr) != NULL) {
PyErr_SetString(PyExc_ValueError,
"Cannot set array with existing base to WRITEBACKIFCOPY");
goto fail;
}
if (PyArray_FailUnlessWriteable(base, "WRITEBACKIFCOPY base") < 0) {
goto fail;
}
/*
* Any writes to 'arr' will magically turn into writes to 'base', so we
* should warn if necessary.
*/
if (PyArray_FLAGS(base) & NPY_ARRAY_WARN_ON_WRITE) {
PyArray_ENABLEFLAGS(arr, NPY_ARRAY_WARN_ON_WRITE);
}
/*
* Unlike PyArray_SetBaseObject, we do not compress the chain of base
* references.
*/
((PyArrayObject_fields *)arr)->base = (PyObject *)base;
PyArray_ENABLEFLAGS(arr, NPY_ARRAY_WRITEBACKIFCOPY);
PyArray_CLEARFLAGS(base, NPY_ARRAY_WRITEABLE);
return 0;
fail:
Py_DECREF(base);
return -1;
}
/*NUMPY_API
* Sets the 'base' attribute of the array. This steals a reference
* to 'obj'.
*
* Returns 0 on success, -1 on failure.
*/
NPY_NO_EXPORT int
PyArray_SetBaseObject(PyArrayObject *arr, PyObject *obj)
{
if (obj == NULL) {
PyErr_SetString(PyExc_ValueError,
"Cannot set the NumPy array 'base' "
"dependency to NULL after initialization");
return -1;
}
/*
* Allow the base to be set only once. Once the object which
* owns the data is set, it doesn't make sense to change it.
*/
if (PyArray_BASE(arr) != NULL) {
Py_DECREF(obj);
PyErr_SetString(PyExc_ValueError,
"Cannot set the NumPy array 'base' "
"dependency more than once");
return -1;
}
/*
* Don't allow infinite chains of views, always set the base
* to the first owner of the data.
* That is, either the first object which isn't an array,
* or the first object which owns its own data.
*/
while (PyArray_Check(obj) && (PyObject *)arr != obj) {
PyArrayObject *obj_arr = (PyArrayObject *)obj;
PyObject *tmp;
/* Propagate WARN_ON_WRITE through views. */
if (PyArray_FLAGS(obj_arr) & NPY_ARRAY_WARN_ON_WRITE) {
PyArray_ENABLEFLAGS(arr, NPY_ARRAY_WARN_ON_WRITE);
}
/* If this array owns its own data, stop collapsing */
if (PyArray_CHKFLAGS(obj_arr, NPY_ARRAY_OWNDATA)) {
break;
}
tmp = PyArray_BASE(obj_arr);
/* If there's no base, stop collapsing */
if (tmp == NULL) {
break;
}
/* Stop the collapse new base when the would not be of the same
* type (i.e. different subclass).
*/
if (Py_TYPE(tmp) != Py_TYPE(arr)) {
break;
}
Py_INCREF(tmp);
Py_DECREF(obj);
obj = tmp;
}
/* Disallow circular references */
if ((PyObject *)arr == obj) {
Py_DECREF(obj);
PyErr_SetString(PyExc_ValueError,
"Cannot create a circular NumPy array 'base' dependency");
return -1;
}
((PyArrayObject_fields *)arr)->base = obj;
return 0;
}
/**
* Assign an arbitrary object a NumPy array. This is largely basically
* identical to PyArray_FromAny, but assigns directly to the output array.
*
* @param dest Array to be written to
* @param src_object Object to be assigned, array-coercion rules apply.
* @return 0 on success -1 on failures.
*/
/*NUMPY_API*/
NPY_NO_EXPORT int
PyArray_CopyObject(PyArrayObject *dest, PyObject *src_object)
{
int ret = 0;
PyArrayObject *view;
PyArray_Descr *dtype = NULL;
int ndim;
npy_intp dims[NPY_MAXDIMS];
coercion_cache_obj *cache = NULL;
/*
* We have to set the maximum number of dimensions here to support
* sequences within object arrays.
*/
ndim = PyArray_DiscoverDTypeAndShape(src_object,
PyArray_NDIM(dest), dims, &cache,
NPY_DTYPE(PyArray_DESCR(dest)), PyArray_DESCR(dest), &dtype, 0);
if (ndim < 0) {
return -1;
}
if (cache != NULL && !(cache->sequence)) {
/* The input is an array or array object, so assign directly */
assert(cache->converted_obj == src_object);
view = (PyArrayObject *)cache->arr_or_sequence;
Py_DECREF(dtype);
ret = PyArray_AssignArray(dest, view, NULL, NPY_UNSAFE_CASTING);
npy_free_coercion_cache(cache);
return ret;
}
/*
* We may need to broadcast, due to shape mismatches, in this case
* create a temporary array first, and assign that after filling
* it from the sequences/scalar.
*/
if (ndim != PyArray_NDIM(dest) ||
!PyArray_CompareLists(PyArray_DIMS(dest), dims, ndim)) {
/*
* Broadcasting may be necessary, so assign to a view first.
* This branch could lead to a shape mismatch error later.
*/
assert (ndim <= PyArray_NDIM(dest)); /* would error during discovery */
view = (PyArrayObject *) PyArray_NewFromDescr(
&PyArray_Type, dtype, ndim, dims, NULL, NULL,
PyArray_FLAGS(dest) & NPY_ARRAY_F_CONTIGUOUS, NULL);
if (view == NULL) {
npy_free_coercion_cache(cache);
return -1;
}
}
else {
Py_DECREF(dtype);
view = dest;
}
/* Assign the values to `view` (whichever array that is) */
if (cache == NULL) {
/* single (non-array) item, assign immediately */
if (PyArray_Pack(
PyArray_DESCR(view), PyArray_DATA(view), src_object) < 0) {
goto fail;
}
}
else {
if (PyArray_AssignFromCache(view, cache) < 0) {
goto fail;
}
}
if (view == dest) {
return 0;
}
ret = PyArray_AssignArray(dest, view, NULL, NPY_UNSAFE_CASTING);
Py_DECREF(view);
return ret;
fail:
if (view != dest) {
Py_DECREF(view);
}
return -1;
}
/* returns an Array-Scalar Object of the type of arr
from the given pointer to memory -- main Scalar creation function
default new method calls this.
*/
/* Ideally, here the descriptor would contain all the information needed.
So, that we simply need the data and the descriptor, and perhaps
a flag
*/
/*
Given a string return the type-number for
the data-type with that string as the type-object name.
Returns NPY_NOTYPE without setting an error if no type can be
found. Only works for user-defined data-types.
*/
/*NUMPY_API
*/
NPY_NO_EXPORT int
PyArray_TypeNumFromName(char const *str)
{
int i;
PyArray_Descr *descr;
for (i = 0; i < NPY_NUMUSERTYPES; i++) {
descr = userdescrs[i];
if (strcmp(descr->typeobj->tp_name, str) == 0) {
return descr->type_num;
}
}
return NPY_NOTYPE;
}
/*NUMPY_API
*
* If WRITEBACKIFCOPY and self has data, reset the base WRITEABLE flag,
* copy the local data to base, release the local data, and set flags
* appropriately. Return 0 if not relevant, 1 if success, < 0 on failure
*/
NPY_NO_EXPORT int
PyArray_ResolveWritebackIfCopy(PyArrayObject * self)
{
PyArrayObject_fields *fa = (PyArrayObject_fields *)self;
if (fa && fa->base) {
if ((fa->flags & NPY_ARRAY_UPDATEIFCOPY) || (fa->flags & NPY_ARRAY_WRITEBACKIFCOPY)) {
/*
* UPDATEIFCOPY or WRITEBACKIFCOPY means that fa->base's data
* should be updated with the contents
* of self.
* fa->base->flags is not WRITEABLE to protect the relationship
* unlock it.
*/
int retval = 0;
PyArray_ENABLEFLAGS(((PyArrayObject *)fa->base),
NPY_ARRAY_WRITEABLE);
PyArray_CLEARFLAGS(self, NPY_ARRAY_UPDATEIFCOPY);
PyArray_CLEARFLAGS(self, NPY_ARRAY_WRITEBACKIFCOPY);
retval = PyArray_CopyAnyInto((PyArrayObject *)fa->base, self);
Py_DECREF(fa->base);
fa->base = NULL;
if (retval < 0) {
/* this should never happen, how did the two copies of data
* get out of sync?
*/
return retval;
}
return 1;
}
}
return 0;
}
/*********************** end C-API functions **********************/
/* dealloc must not raise an error, best effort try to write
to stderr and clear the error
*/
static NPY_INLINE void
WARN_IN_DEALLOC(PyObject* warning, const char * msg) {
if (PyErr_WarnEx(warning, msg, 1) < 0) {
PyObject * s;
s = PyUnicode_FromString("array_dealloc");
if (s) {
PyErr_WriteUnraisable(s);
Py_DECREF(s);
}
else {
PyErr_WriteUnraisable(Py_None);
}
}
}
/* array object functions */
static void
array_dealloc(PyArrayObject *self)
{
PyArrayObject_fields *fa = (PyArrayObject_fields *)self;
if (_buffer_info_free(fa->_buffer_info, (PyObject *)self) < 0) {
PyErr_WriteUnraisable(NULL);
}
if (fa->weakreflist != NULL) {
PyObject_ClearWeakRefs((PyObject *)self);
}
if (fa->base) {
int retval;
if (PyArray_FLAGS(self) & NPY_ARRAY_WRITEBACKIFCOPY)
{
char const * msg = "WRITEBACKIFCOPY detected in array_dealloc. "
" Required call to PyArray_ResolveWritebackIfCopy or "
"PyArray_DiscardWritebackIfCopy is missing.";
/*
* prevent reaching 0 twice and thus recursing into dealloc.
* Increasing sys.gettotalrefcount, but path should not be taken.
*/
Py_INCREF(self);
WARN_IN_DEALLOC(PyExc_RuntimeWarning, msg);
retval = PyArray_ResolveWritebackIfCopy(self);
if (retval < 0)
{
PyErr_Print();
PyErr_Clear();
}
}
if (PyArray_FLAGS(self) & NPY_ARRAY_UPDATEIFCOPY) {
/* DEPRECATED, remove once the flag is removed */
char const * msg = "UPDATEIFCOPY detected in array_dealloc. "
" Required call to PyArray_ResolveWritebackIfCopy or "
"PyArray_DiscardWritebackIfCopy is missing";
/*
* prevent reaching 0 twice and thus recursing into dealloc.
* Increasing sys.gettotalrefcount, but path should not be taken.
*/
Py_INCREF(self);
/* 2017-Nov-10 1.14 */
WARN_IN_DEALLOC(PyExc_DeprecationWarning, msg);
retval = PyArray_ResolveWritebackIfCopy(self);
if (retval < 0)
{
PyErr_Print();
PyErr_Clear();
}
}
/*
* If fa->base is non-NULL, it is something
* to DECREF -- either a view or a buffer object
*/
Py_XDECREF(fa->base);
}
if ((fa->flags & NPY_ARRAY_OWNDATA) && fa->data) {
/* Free internal references if an Object array */
if (PyDataType_FLAGCHK(fa->descr, NPY_ITEM_REFCOUNT)) {
PyArray_XDECREF(self);
}
if (fa->mem_handler == NULL) {
char *env = getenv("NUMPY_WARN_IF_NO_MEM_POLICY");
if ((env != NULL) && (strncmp(env, "1", 1) == 0)) {
char const * msg = "Trying to dealloc data, but a memory policy "
"is not set. If you take ownership of the data, you must "
"set a base owning the data (e.g. a PyCapsule).";
WARN_IN_DEALLOC(PyExc_RuntimeWarning, msg);
}
// Guess at malloc/free ???
free(fa->data);
}
else {
/*
* In theory `PyArray_NBYTES_ALLOCATED`, but differs somewhere?
* So instead just use the knowledge that 0 is impossible.
*/
size_t nbytes = PyArray_NBYTES(self);
if (nbytes == 0) {
nbytes = 1;
}
PyDataMem_UserFREE(fa->data, nbytes, fa->mem_handler);
Py_DECREF(fa->mem_handler);
}
}
/* must match allocation in PyArray_NewFromDescr */
npy_free_cache_dim(fa->dimensions, 2 * fa->nd);
Py_DECREF(fa->descr);
Py_TYPE(self)->tp_free((PyObject *)self);
}
/*NUMPY_API
* Prints the raw data of the ndarray in a form useful for debugging
* low-level C issues.
*/
NPY_NO_EXPORT void
PyArray_DebugPrint(PyArrayObject *obj)
{
int i;
PyArrayObject_fields *fobj = (PyArrayObject_fields *)obj;
printf("-------------------------------------------------------\n");
printf(" Dump of NumPy ndarray at address %p\n", obj);
if (obj == NULL) {
printf(" It's NULL!\n");
printf("-------------------------------------------------------\n");
fflush(stdout);
return;
}
printf(" ndim : %d\n", fobj->nd);
printf(" shape :");
for (i = 0; i < fobj->nd; ++i) {
printf(" %" NPY_INTP_FMT, fobj->dimensions[i]);
}
printf("\n");
printf(" dtype : ");
PyObject_Print((PyObject *)fobj->descr, stdout, 0);
printf("\n");
printf(" data : %p\n", fobj->data);
printf(" strides:");
for (i = 0; i < fobj->nd; ++i) {
printf(" %" NPY_INTP_FMT, fobj->strides[i]);
}
printf("\n");
printf(" base : %p\n", fobj->base);
printf(" flags :");
if (fobj->flags & NPY_ARRAY_C_CONTIGUOUS)
printf(" NPY_C_CONTIGUOUS");
if (fobj->flags & NPY_ARRAY_F_CONTIGUOUS)
printf(" NPY_F_CONTIGUOUS");
if (fobj->flags & NPY_ARRAY_OWNDATA)
printf(" NPY_OWNDATA");
if (fobj->flags & NPY_ARRAY_ALIGNED)
printf(" NPY_ALIGNED");
if (fobj->flags & NPY_ARRAY_WRITEABLE)
printf(" NPY_WRITEABLE");
if (fobj->flags & NPY_ARRAY_UPDATEIFCOPY)
printf(" NPY_UPDATEIFCOPY");
if (fobj->flags & NPY_ARRAY_WRITEBACKIFCOPY)
printf(" NPY_WRITEBACKIFCOPY");
printf("\n");
if (fobj->base != NULL && PyArray_Check(fobj->base)) {
printf("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
printf("Dump of array's BASE:\n");
PyArray_DebugPrint((PyArrayObject *)fobj->base);
printf(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
}
printf("-------------------------------------------------------\n");
fflush(stdout);
}
/*NUMPY_API
* This function is scheduled to be removed
*
* TO BE REMOVED - NOT USED INTERNALLY.
*/
NPY_NO_EXPORT void
PyArray_SetDatetimeParseFunction(PyObject *NPY_UNUSED(op))
{
}
/*NUMPY_API
*/
NPY_NO_EXPORT int
PyArray_CompareUCS4(npy_ucs4 const *s1, npy_ucs4 const *s2, size_t len)
{
npy_ucs4 c1, c2;
while(len-- > 0) {
c1 = *s1++;
c2 = *s2++;
if (c1 != c2) {
return (c1 < c2) ? -1 : 1;
}
}
return 0;
}
/*NUMPY_API
*/
NPY_NO_EXPORT int
PyArray_CompareString(const char *s1, const char *s2, size_t len)
{
const unsigned char *c1 = (unsigned char *)s1;
const unsigned char *c2 = (unsigned char *)s2;
size_t i;
for(i = 0; i < len; ++i) {
if (c1[i] != c2[i]) {
return (c1[i] > c2[i]) ? 1 : -1;
}
}
return 0;
}
/* Call this from contexts where an array might be written to, but we have no
* way to tell. (E.g., when converting to a read-write buffer.)
*/
NPY_NO_EXPORT int
array_might_be_written(PyArrayObject *obj)
{
const char *msg =
"Numpy has detected that you (may be) writing to an array with\n"
"overlapping memory from np.broadcast_arrays. If this is intentional\n"
"set the WRITEABLE flag True or make a copy immediately before writing.";
if (PyArray_FLAGS(obj) & NPY_ARRAY_WARN_ON_WRITE) {
if (DEPRECATE(msg) < 0) {
return -1;
}
/* Only warn once per array */
while (1) {
PyArray_CLEARFLAGS(obj, NPY_ARRAY_WARN_ON_WRITE);
if (!PyArray_BASE(obj) || !PyArray_Check(PyArray_BASE(obj))) {
break;
}
obj = (PyArrayObject *)PyArray_BASE(obj);
}
}
return 0;
}
/*NUMPY_API
*
* This function does nothing if obj is writeable, and raises an exception
* (and returns -1) if obj is not writeable. It may also do other
* house-keeping, such as issuing warnings on arrays which are transitioning
* to become views. Always call this function at some point before writing to
* an array.
*
* 'name' is a name for the array, used to give better error
* messages. Something like "assignment destination", "output array", or even
* just "array".
*/
NPY_NO_EXPORT int
PyArray_FailUnlessWriteable(PyArrayObject *obj, const char *name)
{
if (!PyArray_ISWRITEABLE(obj)) {
PyErr_Format(PyExc_ValueError, "%s is read-only", name);
return -1;
}
if (array_might_be_written(obj) < 0) {
return -1;
}
return 0;
}
/* This also handles possibly mis-aligned data */
/* Compare s1 and s2 which are not necessarily NULL-terminated.
s1 is of length len1
s2 is of length len2
If they are NULL terminated, then stop comparison.
*/
static int
_myunincmp(npy_ucs4 const *s1, npy_ucs4 const *s2, int len1, int len2)
{
npy_ucs4 const *sptr;
npy_ucs4 *s1t = NULL;
npy_ucs4 *s2t = NULL;
int val;
npy_intp size;
int diff;
/* Replace `s1` and `s2` with aligned copies if needed */
if ((npy_intp)s1 % sizeof(npy_ucs4) != 0) {
size = len1*sizeof(npy_ucs4);
s1t = malloc(size);
memcpy(s1t, s1, size);
s1 = s1t;
}
if ((npy_intp)s2 % sizeof(npy_ucs4) != 0) {
size = len2*sizeof(npy_ucs4);
s2t = malloc(size);
memcpy(s2t, s2, size);
s2 = s1t;
}
val = PyArray_CompareUCS4(s1, s2, PyArray_MIN(len1,len2));
if ((val != 0) || (len1 == len2)) {
goto finish;
}
if (len2 > len1) {
sptr = s2+len1;
val = -1;
diff = len2-len1;
}
else {
sptr = s1+len2;
val = 1;
diff=len1-len2;
}
while (diff--) {
if (*sptr != 0) {
goto finish;
}
sptr++;
}
val = 0;
finish:
/* Cleanup the aligned copies */
if (s1t) {
free(s1t);
}
if (s2t) {
free(s2t);
}
return val;
}
/*
* Compare s1 and s2 which are not necessarily NULL-terminated.
* s1 is of length len1
* s2 is of length len2
* If they are NULL terminated, then stop comparison.
*/
static int
_mystrncmp(char const *s1, char const *s2, int len1, int len2)
{
char const *sptr;
int val;
int diff;
val = memcmp(s1, s2, PyArray_MIN(len1, len2));
if ((val != 0) || (len1 == len2)) {
return val;
}
if (len2 > len1) {
sptr = s2 + len1;
val = -1;
diff = len2 - len1;
}
else {
sptr = s1 + len2;
val = 1;
diff = len1 - len2;
}
while (diff--) {
if (*sptr != 0) {
return val;
}
sptr++;
}
return 0; /* Only happens if NULLs are everywhere */
}
/* Borrowed from Numarray */
#define SMALL_STRING 2048
static void _rstripw(char *s, int n)
{
int i;
for (i = n - 1; i >= 1; i--) { /* Never strip to length 0. */
int c = s[i];
if (!c || NumPyOS_ascii_isspace((int)c)) {
s[i] = 0;
}
else {
break;
}
}
}
static void _unistripw(npy_ucs4 *s, int n)
{
int i;
for (i = n - 1; i >= 1; i--) { /* Never strip to length 0. */
npy_ucs4 c = s[i];
if (!c || NumPyOS_ascii_isspace((int)c)) {
s[i] = 0;
}
else {
break;
}
}
}
static char *
_char_copy_n_strip(char const *original, char *temp, int nc)
{
if (nc > SMALL_STRING) {
temp = malloc(nc);
if (!temp) {
PyErr_NoMemory();
return NULL;
}
}
memcpy(temp, original, nc);
_rstripw(temp, nc);
return temp;
}
static void
_char_release(char *ptr, int nc)
{
if (nc > SMALL_STRING) {
free(ptr);
}
}
static char *
_uni_copy_n_strip(char const *original, char *temp, int nc)
{
if (nc*sizeof(npy_ucs4) > SMALL_STRING) {
temp = malloc(nc*sizeof(npy_ucs4));
if (!temp) {
PyErr_NoMemory();
return NULL;
}
}
memcpy(temp, original, nc*sizeof(npy_ucs4));
_unistripw((npy_ucs4 *)temp, nc);
return temp;
}
static void
_uni_release(char *ptr, int nc)
{
if (nc*sizeof(npy_ucs4) > SMALL_STRING) {
free(ptr);
}
}
/* End borrowed from numarray */
#define _rstrip_loop(CMP) { \
void *aptr, *bptr; \
char atemp[SMALL_STRING], btemp[SMALL_STRING]; \
while(size--) { \
aptr = stripfunc(iself->dataptr, atemp, N1); \
if (!aptr) return -1; \
bptr = stripfunc(iother->dataptr, btemp, N2); \
if (!bptr) { \
relfunc(aptr, N1); \
return -1; \
} \
val = compfunc(aptr, bptr, N1, N2); \
*dptr = (val CMP 0); \
PyArray_ITER_NEXT(iself); \
PyArray_ITER_NEXT(iother); \
dptr += 1; \
relfunc(aptr, N1); \
relfunc(bptr, N2); \
} \
}
#define _reg_loop(CMP) { \
while(size--) { \
val = compfunc((void *)iself->dataptr, \
(void *)iother->dataptr, \
N1, N2); \
*dptr = (val CMP 0); \
PyArray_ITER_NEXT(iself); \
PyArray_ITER_NEXT(iother); \
dptr += 1; \
} \
}
static int
_compare_strings(PyArrayObject *result, PyArrayMultiIterObject *multi,
int cmp_op, void *func, int rstrip)
{
PyArrayIterObject *iself, *iother;
npy_bool *dptr;
npy_intp size;
int val;
int N1, N2;
int (*compfunc)(void *, void *, int, int);
void (*relfunc)(char *, int);
char* (*stripfunc)(char const *, char *, int);
compfunc = func;
dptr = (npy_bool *)PyArray_DATA(result);
iself = multi->iters[0];
iother = multi->iters[1];
size = multi->size;
N1 = PyArray_DESCR(iself->ao)->elsize;
N2 = PyArray_DESCR(iother->ao)->elsize;
if ((void *)compfunc == (void *)_myunincmp) {
N1 >>= 2;
N2 >>= 2;
stripfunc = _uni_copy_n_strip;
relfunc = _uni_release;
}
else {
stripfunc = _char_copy_n_strip;
relfunc = _char_release;
}
switch (cmp_op) {
case Py_EQ:
if (rstrip) {
_rstrip_loop(==);
} else {
_reg_loop(==);
}
break;
case Py_NE:
if (rstrip) {
_rstrip_loop(!=);
} else {
_reg_loop(!=);
}
break;
case Py_LT:
if (rstrip) {
_rstrip_loop(<);
} else {
_reg_loop(<);
}
break;
case Py_LE:
if (rstrip) {
_rstrip_loop(<=);
} else {
_reg_loop(<=);
}
break;
case Py_GT:
if (rstrip) {
_rstrip_loop(>);
} else {
_reg_loop(>);
}
break;
case Py_GE:
if (rstrip) {
_rstrip_loop(>=);
} else {
_reg_loop(>=);
}
break;
default:
PyErr_SetString(PyExc_RuntimeError, "bad comparison operator");
return -1;
}
return 0;
}
#undef _reg_loop
#undef _rstrip_loop
#undef SMALL_STRING
NPY_NO_EXPORT PyObject *
_strings_richcompare(PyArrayObject *self, PyArrayObject *other, int cmp_op,
int rstrip)
{
PyArrayObject *result;
PyArrayMultiIterObject *mit;
int val;
if (PyArray_TYPE(self) != PyArray_TYPE(other)) {
/*
* Comparison between Bytes and Unicode is not defined in Py3K;
* we follow.