forked from cython/cython
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMemoryView.pyx
More file actions
1481 lines (1204 loc) · 48.4 KB
/
Copy pathMemoryView.pyx
File metadata and controls
1481 lines (1204 loc) · 48.4 KB
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
#################### View.MemoryView ####################
# cython: language_level=3str
# cython: binding=False
# This utility provides cython.array and cython.view.memoryview
from __future__ import absolute_import
cimport cython
# from cpython cimport ...
cdef extern from "Python.h":
ctypedef struct PyObject
int PyIndex_Check(object)
PyObject *PyExc_IndexError
PyObject *PyExc_ValueError
cdef extern from "pythread.h":
ctypedef void *PyThread_type_lock
PyThread_type_lock PyThread_allocate_lock()
void PyThread_free_lock(PyThread_type_lock)
cdef extern from "<string.h>":
void *memset(void *b, int c, size_t len)
cdef extern from *:
bint __PYX_CYTHON_ATOMICS_ENABLED()
int __Pyx_GetBuffer(object, Py_buffer *, int) except -1
void __Pyx_ReleaseBuffer(Py_buffer *)
ctypedef struct PyObject
ctypedef Py_ssize_t Py_intptr_t
void Py_INCREF(PyObject *)
void Py_DECREF(PyObject *)
void* PyMem_Malloc(size_t n)
void PyMem_Free(void *p)
void* PyObject_Malloc(size_t n)
void PyObject_Free(void *p)
cdef struct __pyx_memoryview "__pyx_memoryview_obj":
Py_buffer view
PyObject *obj
__Pyx_TypeInfo *typeinfo
ctypedef struct {{memviewslice_name}}:
__pyx_memoryview *memview
char *data
Py_ssize_t shape[{{max_dims}}]
Py_ssize_t strides[{{max_dims}}]
Py_ssize_t suboffsets[{{max_dims}}]
void __PYX_INC_MEMVIEW({{memviewslice_name}} *memslice, int have_gil)
void __PYX_XCLEAR_MEMVIEW({{memviewslice_name}} *memslice, int have_gil)
ctypedef struct __pyx_buffer "Py_buffer":
PyObject *obj
PyObject *Py_None
cdef enum:
PyBUF_C_CONTIGUOUS,
PyBUF_F_CONTIGUOUS,
PyBUF_ANY_CONTIGUOUS
PyBUF_FORMAT
PyBUF_WRITABLE
PyBUF_STRIDES
PyBUF_INDIRECT
PyBUF_ND
PyBUF_RECORDS
PyBUF_RECORDS_RO
ctypedef struct __Pyx_TypeInfo:
pass
cdef extern from *:
ctypedef int __pyx_atomic_int_type
{{memviewslice_name}} slice_copy_contig "__pyx_memoryview_copy_new_contig"(
__Pyx_memviewslice *from_mvs,
char *mode, int ndim,
size_t sizeof_dtype, int contig_flag,
bint dtype_is_object) except * nogil
bint slice_is_contig "__pyx_memviewslice_is_contig" (
{{memviewslice_name}} mvs, char order, int ndim) nogil
bint slices_overlap "__pyx_slices_overlap" ({{memviewslice_name}} *slice1,
{{memviewslice_name}} *slice2,
int ndim, size_t itemsize) nogil
cdef extern from "<stdlib.h>":
void *malloc(size_t) nogil
void free(void *) nogil
void *memcpy(void *dest, void *src, size_t n) nogil
# the sequence abstract base class
cdef object __pyx_collections_abc_Sequence "__pyx_collections_abc_Sequence"
try:
if __import__("sys").version_info >= (3, 3):
__pyx_collections_abc_Sequence = __import__("collections.abc").abc.Sequence
else:
__pyx_collections_abc_Sequence = __import__("collections").Sequence
except:
# it isn't a big problem if this fails
__pyx_collections_abc_Sequence = None
#
### cython.array class
#
@cython.collection_type("sequence")
@cname("__pyx_array")
cdef class array:
cdef:
char *data
Py_ssize_t len
char *format
int ndim
Py_ssize_t *_shape
Py_ssize_t *_strides
Py_ssize_t itemsize
unicode mode # FIXME: this should have been a simple 'char'
bytes _format
void (*callback_free_data)(void *data) noexcept
# cdef object _memview
cdef bint free_data
cdef bint dtype_is_object
def __cinit__(array self, tuple shape, Py_ssize_t itemsize, format not None,
mode="c", bint allocate_buffer=True):
cdef int idx
cdef Py_ssize_t dim
self.ndim = <int> len(shape)
self.itemsize = itemsize
if not self.ndim:
raise ValueError, "Empty shape tuple for cython.array"
if itemsize <= 0:
raise ValueError, "itemsize <= 0 for cython.array"
if not isinstance(format, bytes):
format = format.encode('ASCII')
self._format = format # keep a reference to the byte string
self.format = self._format
# use single malloc() for both shape and strides
self._shape = <Py_ssize_t *> PyObject_Malloc(sizeof(Py_ssize_t)*self.ndim*2)
self._strides = self._shape + self.ndim
if not self._shape:
raise MemoryError, "unable to allocate shape and strides."
# cdef Py_ssize_t dim, stride
for idx, dim in enumerate(shape):
if dim <= 0:
raise ValueError, f"Invalid shape in axis {idx}: {dim}."
self._shape[idx] = dim
cdef char order
if mode == 'c':
order = b'C'
self.mode = u'c'
elif mode == 'fortran':
order = b'F'
self.mode = u'fortran'
else:
raise ValueError, f"Invalid mode, expected 'c' or 'fortran', got {mode}"
self.len = fill_contig_strides_array(self._shape, self._strides, itemsize, self.ndim, order)
self.free_data = allocate_buffer
self.dtype_is_object = format == b'O'
if allocate_buffer:
_allocate_buffer(self)
@cname('getbuffer')
def __getbuffer__(self, Py_buffer *info, int flags):
cdef int bufmode = -1
if flags & (PyBUF_C_CONTIGUOUS | PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS):
if self.mode == u"c":
bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS
elif self.mode == u"fortran":
bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS
if not (flags & bufmode):
raise ValueError, "Can only create a buffer that is contiguous in memory."
info.buf = self.data
info.len = self.len
if flags & PyBUF_STRIDES:
info.ndim = self.ndim
info.shape = self._shape
info.strides = self._strides
else:
info.ndim = 1
info.shape = &self.len if flags & PyBUF_ND else NULL
info.strides = NULL
info.suboffsets = NULL
info.itemsize = self.itemsize
info.readonly = 0
info.format = self.format if flags & PyBUF_FORMAT else NULL
info.obj = self
def __dealloc__(array self):
if self.callback_free_data != NULL:
self.callback_free_data(self.data)
elif self.free_data and self.data is not NULL:
if self.dtype_is_object:
refcount_objects_in_slice(self.data, self._shape, self._strides, self.ndim, inc=False)
free(self.data)
PyObject_Free(self._shape)
@property
def memview(self):
return self.get_memview()
@cname('get_memview')
cdef get_memview(self):
flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE
return memoryview(self, flags, self.dtype_is_object)
def __len__(self):
return self._shape[0]
def __getattr__(self, attr):
return getattr(self.memview, attr)
def __getitem__(self, item):
return self.memview[item]
def __setitem__(self, item, value):
self.memview[item] = value
# Sequence methods
try:
count = __pyx_collections_abc_Sequence.count
index = __pyx_collections_abc_Sequence.index
except:
pass
@cname("__pyx_array_allocate_buffer")
cdef int _allocate_buffer(array self) except -1:
# use malloc() for backwards compatibility
# in case external code wants to change the data pointer
cdef Py_ssize_t i
cdef PyObject **p
self.free_data = True
self.data = <char *>malloc(self.len)
if not self.data:
raise MemoryError, "unable to allocate array data."
if self.dtype_is_object:
p = <PyObject **> self.data
for i in range(self.len // self.itemsize):
p[i] = Py_None
Py_INCREF(Py_None)
return 0
@cname("__pyx_array_new")
cdef array array_cwrapper(tuple shape, Py_ssize_t itemsize, char *format, char *c_mode, char *buf):
cdef array result
cdef str mode = "fortran" if c_mode[0] == b'f' else "c" # this often comes from a constant C string.
if buf is NULL:
result = array.__new__(array, shape, itemsize, format, mode)
else:
result = array.__new__(array, shape, itemsize, format, mode, allocate_buffer=False)
result.data = buf
return result
#
### Memoryview constants and cython.view.memoryview class
#
# Disable generic_contiguous, as it makes trouble verifying contiguity:
# - 'contiguous' or '::1' means the dimension is contiguous with dtype
# - 'indirect_contiguous' means a contiguous list of pointers
# - dtype contiguous must be contiguous in the first or last dimension
# from the start, or from the dimension following the last indirect dimension
#
# e.g.
# int[::indirect_contiguous, ::contiguous, :]
#
# is valid (list of pointers to 2d fortran-contiguous array), but
#
# int[::generic_contiguous, ::contiguous, :]
#
# would mean you'd have assert dimension 0 to be indirect (and pointer contiguous) at runtime.
# So it doesn't bring any performance benefit, and it's only confusing.
@cname('__pyx_MemviewEnum')
cdef class Enum(object):
cdef object name
def __init__(self, name):
self.name = name
def __repr__(self):
return self.name
cdef generic = Enum("<strided and direct or indirect>")
cdef strided = Enum("<strided and direct>") # default
cdef indirect = Enum("<strided and indirect>")
# Disable generic_contiguous, as it is a troublemaker
#cdef generic_contiguous = Enum("<contiguous and direct or indirect>")
cdef contiguous = Enum("<contiguous and direct>")
cdef indirect_contiguous = Enum("<contiguous and indirect>")
# 'follow' is implied when the first or last axis is ::1
# pre-allocate thread locks for reuse
## note that this could be implemented in a more beautiful way in "normal" Cython,
## but this code gets merged into the user module and not everything works there.
cdef int __pyx_memoryview_thread_locks_used = 0
cdef PyThread_type_lock[{{THREAD_LOCKS_PREALLOCATED}}] __pyx_memoryview_thread_locks = [
{{for _ in range(THREAD_LOCKS_PREALLOCATED)}}
PyThread_allocate_lock(),
{{endfor}}
]
@cname('__pyx_memoryview')
cdef class memoryview:
cdef object obj
cdef object _size
cdef object _array_interface
cdef PyThread_type_lock lock
cdef __pyx_atomic_int_type acquisition_count
cdef Py_buffer view
cdef int flags
cdef bint dtype_is_object
cdef __Pyx_TypeInfo *typeinfo
def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False):
self.obj = obj
self.flags = flags
if type(self) is memoryview or obj is not None:
__Pyx_GetBuffer(obj, &self.view, flags)
if <PyObject *> self.view.obj == NULL:
(<__pyx_buffer *> &self.view).obj = Py_None
Py_INCREF(Py_None)
if not __PYX_CYTHON_ATOMICS_ENABLED():
global __pyx_memoryview_thread_locks_used
if __pyx_memoryview_thread_locks_used < {{THREAD_LOCKS_PREALLOCATED}}:
self.lock = __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used]
__pyx_memoryview_thread_locks_used += 1
if self.lock is NULL:
self.lock = PyThread_allocate_lock()
if self.lock is NULL:
raise MemoryError
if flags & PyBUF_FORMAT:
self.dtype_is_object = (self.view.format[0] == b'O' and self.view.format[1] == b'\0')
else:
self.dtype_is_object = dtype_is_object
assert <Py_intptr_t><void*>(&self.acquisition_count) % sizeof(__pyx_atomic_int_type) == 0
self.typeinfo = NULL
def __dealloc__(memoryview self):
if self.obj is not None:
__Pyx_ReleaseBuffer(&self.view)
elif (<__pyx_buffer *> &self.view).obj == Py_None:
# Undo the incref in __cinit__() above.
(<__pyx_buffer *> &self.view).obj = NULL
Py_DECREF(Py_None)
cdef int i
global __pyx_memoryview_thread_locks_used
if self.lock != NULL:
for i in range(__pyx_memoryview_thread_locks_used):
if __pyx_memoryview_thread_locks[i] is self.lock:
__pyx_memoryview_thread_locks_used -= 1
if i != __pyx_memoryview_thread_locks_used:
__pyx_memoryview_thread_locks[i], __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] = (
__pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used], __pyx_memoryview_thread_locks[i])
break
else:
PyThread_free_lock(self.lock)
cdef char *get_item_pointer(memoryview self, object index) except NULL:
cdef Py_ssize_t dim
cdef char *itemp = <char *> self.view.buf
for dim, idx in enumerate(index):
itemp = pybuffer_index(&self.view, itemp, idx, dim)
return itemp
#@cname('__pyx_memoryview_getitem')
def __getitem__(memoryview self, object index):
if index is Ellipsis:
return self
have_slices, indices = _unellipsify(index, self.view.ndim)
cdef char *itemp
if have_slices:
return memview_slice(self, indices)
else:
itemp = self.get_item_pointer(indices)
return self.convert_item_to_object(itemp)
def __setitem__(memoryview self, object index, object value):
if self.view.readonly:
raise TypeError, "Cannot assign to read-only memoryview"
have_slices, index = _unellipsify(index, self.view.ndim)
if have_slices:
obj = self.is_slice(value)
if obj:
self.setitem_slice_assignment(self[index], obj)
else:
self.setitem_slice_assign_scalar(self[index], value)
else:
self.setitem_indexed(index, value)
cdef is_slice(self, obj):
if not isinstance(obj, memoryview):
try:
obj = memoryview(obj, self.flags & ~PyBUF_WRITABLE | PyBUF_ANY_CONTIGUOUS,
self.dtype_is_object)
except TypeError:
return None
return obj
cdef setitem_slice_assignment(self, dst, src):
cdef {{memviewslice_name}} dst_slice
cdef {{memviewslice_name}} src_slice
cdef {{memviewslice_name}} msrc = get_slice_from_memview(src, &src_slice)[0]
cdef {{memviewslice_name}} mdst = get_slice_from_memview(dst, &dst_slice)[0]
memoryview_copy_contents(msrc, mdst, src.ndim, dst.ndim, self.dtype_is_object)
cdef setitem_slice_assign_scalar(self, memoryview dst, value):
cdef int array[128]
cdef void *tmp = NULL
cdef void *item
cdef {{memviewslice_name}} *dst_slice
cdef {{memviewslice_name}} tmp_slice
dst_slice = get_slice_from_memview(dst, &tmp_slice)
if <size_t>self.view.itemsize > sizeof(array):
tmp = PyMem_Malloc(self.view.itemsize)
if tmp == NULL:
raise MemoryError
item = tmp
else:
item = <void *> array
try:
if self.dtype_is_object:
(<PyObject **> item)[0] = <PyObject *> value
else:
self.assign_item_from_object(<char *> item, value)
# It would be easy to support indirect dimensions, but it's easier
# to disallow :)
if self.view.suboffsets != NULL:
assert_direct_dimensions(self.view.suboffsets, self.view.ndim)
slice_assign_scalar(dst_slice, dst.view.ndim, self.view.itemsize,
item, self.dtype_is_object)
finally:
PyMem_Free(tmp)
cdef setitem_indexed(self, index, value):
cdef char *itemp = self.get_item_pointer(index)
self.assign_item_from_object(itemp, value)
cdef convert_item_to_object(self, char *itemp):
"""Only used if instantiated manually by the user, or if Cython doesn't
know how to convert the type"""
import struct
cdef bytes bytesitem
# Do a manual and complete check here instead of this easy hack
bytesitem = itemp[:self.view.itemsize]
try:
result = struct.unpack(self.view.format, bytesitem)
except struct.error:
raise ValueError, "Unable to convert item to object"
else:
if len(self.view.format) == 1:
return result[0]
return result
cdef assign_item_from_object(self, char *itemp, object value):
"""Only used if instantiated manually by the user, or if Cython doesn't
know how to convert the type"""
import struct
cdef char c
cdef bytes bytesvalue
cdef Py_ssize_t i
if isinstance(value, tuple):
bytesvalue = struct.pack(self.view.format, *value)
else:
bytesvalue = struct.pack(self.view.format, value)
for i, c in enumerate(bytesvalue):
itemp[i] = c
@cname('getbuffer')
def __getbuffer__(self, Py_buffer *info, int flags):
if flags & PyBUF_WRITABLE and self.view.readonly:
raise ValueError, "Cannot create writable memory view from read-only memoryview"
if flags & PyBUF_ND:
info.shape = self.view.shape
else:
info.shape = NULL
if flags & PyBUF_STRIDES:
info.strides = self.view.strides
else:
info.strides = NULL
if flags & PyBUF_INDIRECT:
info.suboffsets = self.view.suboffsets
else:
info.suboffsets = NULL
if flags & PyBUF_FORMAT:
info.format = self.view.format
else:
info.format = NULL
info.buf = self.view.buf
info.ndim = self.view.ndim
info.itemsize = self.view.itemsize
info.len = self.view.len
info.readonly = self.view.readonly
info.obj = self
# Some properties that have the same semantics as in NumPy
@property
def T(self):
cdef _memoryviewslice result = memoryview_copy(self)
transpose_memslice(&result.from_slice)
return result
@property
def base(self):
return self._get_base()
cdef _get_base(self):
return self.obj
@property
def shape(self):
return tuple([length for length in self.view.shape[:self.view.ndim]])
@property
def strides(self):
if self.view.strides == NULL:
# Note: we always ask for strides, so if this is not set it's a bug
raise ValueError, "Buffer view does not expose strides"
return tuple([stride for stride in self.view.strides[:self.view.ndim]])
@property
def suboffsets(self):
if self.view.suboffsets == NULL:
return (-1,) * self.view.ndim
return tuple([suboffset for suboffset in self.view.suboffsets[:self.view.ndim]])
@property
def ndim(self):
return self.view.ndim
@property
def itemsize(self):
return self.view.itemsize
@property
def nbytes(self):
return self.size * self.view.itemsize
@property
def size(self):
if self._size is None:
result = 1
for length in self.view.shape[:self.view.ndim]:
result *= length
self._size = result
return self._size
def __len__(self):
if self.view.ndim >= 1:
return self.view.shape[0]
return 0
def __repr__(self):
return "<MemoryView of %r at 0x%x>" % (self.base.__class__.__name__,
id(self))
def __str__(self):
return "<MemoryView of %r object>" % (self.base.__class__.__name__,)
# Support the same attributes as memoryview slices
def is_c_contig(self):
cdef {{memviewslice_name}} *mslice
cdef {{memviewslice_name}} tmp
mslice = get_slice_from_memview(self, &tmp)
return slice_is_contig(mslice[0], 'C', self.view.ndim)
def is_f_contig(self):
cdef {{memviewslice_name}} *mslice
cdef {{memviewslice_name}} tmp
mslice = get_slice_from_memview(self, &tmp)
return slice_is_contig(mslice[0], 'F', self.view.ndim)
def copy(self):
cdef {{memviewslice_name}} mslice
cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS
slice_copy(self, &mslice)
mslice = slice_copy_contig(&mslice, "c", self.view.ndim,
self.view.itemsize,
flags|PyBUF_C_CONTIGUOUS,
self.dtype_is_object)
return memoryview_copy_from_slice(self, &mslice)
def copy_fortran(self):
cdef {{memviewslice_name}} src, dst
cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS
slice_copy(self, &src)
dst = slice_copy_contig(&src, "fortran", self.view.ndim,
self.view.itemsize,
flags|PyBUF_F_CONTIGUOUS,
self.dtype_is_object)
return memoryview_copy_from_slice(self, &dst)
@cname('__pyx_memoryview_new')
cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo):
cdef memoryview result = memoryview(o, flags, dtype_is_object)
result.typeinfo = typeinfo
return result
@cname('__pyx_memoryview_check')
cdef inline bint memoryview_check(object o) noexcept:
return isinstance(o, memoryview)
cdef tuple _unellipsify(object index, int ndim):
"""
Replace all ellipses with full slices and fill incomplete indices with
full slices.
"""
cdef Py_ssize_t idx
tup = <tuple>index if isinstance(index, tuple) else (index,)
result = [slice(None)] * ndim
have_slices = False
seen_ellipsis = False
idx = 0
for item in tup:
if item is Ellipsis:
if not seen_ellipsis:
idx += ndim - len(tup)
seen_ellipsis = True
have_slices = True
else:
if isinstance(item, slice):
have_slices = True
elif not PyIndex_Check(item):
raise TypeError, f"Cannot index with type '{type(item)}'"
result[idx] = item
idx += 1
nslices = ndim - idx
return have_slices or nslices, tuple(result)
cdef int assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim) except -1:
for suboffset in suboffsets[:ndim]:
if suboffset >= 0:
raise ValueError, "Indirect dimensions not supported"
return 0 # return type just used as an error flag
#
### Slicing a memoryview
#
@cname('__pyx_memview_slice')
cdef memoryview memview_slice(memoryview memview, object indices):
cdef int new_ndim = 0, suboffset_dim = -1, dim
cdef bint negative_step
cdef {{memviewslice_name}} src, dst
cdef {{memviewslice_name}} *p_src
# dst is copied by value in memoryview_fromslice -- initialize it
# src is never copied
memset(&dst, 0, sizeof(dst))
cdef _memoryviewslice memviewsliceobj
assert memview.view.ndim > 0
if isinstance(memview, _memoryviewslice):
memviewsliceobj = memview
p_src = &memviewsliceobj.from_slice
else:
slice_copy(memview, &src)
p_src = &src
# Note: don't use variable src at this point
# SubNote: we should be able to declare variables in blocks...
# memoryview_fromslice() will inc our dst slice
dst.memview = p_src.memview
dst.data = p_src.data
# Put everything in temps to avoid this bloody warning:
# "Argument evaluation order in C function call is undefined and
# may not be as expected"
cdef {{memviewslice_name}} *p_dst = &dst
cdef int *p_suboffset_dim = &suboffset_dim
cdef Py_ssize_t start, stop, step, cindex
cdef bint have_start, have_stop, have_step
for dim, index in enumerate(indices):
if PyIndex_Check(index):
cindex = index
slice_memviewslice(
p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim],
dim, new_ndim, p_suboffset_dim,
cindex, 0, 0, # start, stop, step
0, 0, 0, # have_{start,stop,step}
False)
elif index is None:
p_dst.shape[new_ndim] = 1
p_dst.strides[new_ndim] = 0
p_dst.suboffsets[new_ndim] = -1
new_ndim += 1
else:
start = index.start or 0
stop = index.stop or 0
step = index.step or 0
have_start = index.start is not None
have_stop = index.stop is not None
have_step = index.step is not None
slice_memviewslice(
p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim],
dim, new_ndim, p_suboffset_dim,
start, stop, step,
have_start, have_stop, have_step,
True)
new_ndim += 1
if isinstance(memview, _memoryviewslice):
return memoryview_fromslice(dst, new_ndim,
memviewsliceobj.to_object_func,
memviewsliceobj.to_dtype_func,
memview.dtype_is_object)
else:
return memoryview_fromslice(dst, new_ndim, NULL, NULL,
memview.dtype_is_object)
#
### Slicing in a single dimension of a memoryviewslice
#
@cname('__pyx_memoryview_slice_memviewslice')
cdef int slice_memviewslice(
{{memviewslice_name}} *dst,
Py_ssize_t shape, Py_ssize_t stride, Py_ssize_t suboffset,
int dim, int new_ndim, int *suboffset_dim,
Py_ssize_t start, Py_ssize_t stop, Py_ssize_t step,
int have_start, int have_stop, int have_step,
bint is_slice) except -1 nogil:
"""
Create a new slice dst given slice src.
dim - the current src dimension (indexing will make dimensions
disappear)
new_dim - the new dst dimension
suboffset_dim - pointer to a single int initialized to -1 to keep track of
where slicing offsets should be added
"""
cdef Py_ssize_t new_shape
cdef bint negative_step
if not is_slice:
# index is a normal integer-like index
if start < 0:
start += shape
if not 0 <= start < shape:
_err_dim(PyExc_IndexError, "Index out of bounds (axis %d)", dim)
else:
# index is a slice
if have_step:
negative_step = step < 0
if step == 0:
_err_dim(PyExc_ValueError, "Step may not be zero (axis %d)", dim)
else:
negative_step = False
step = 1
# check our bounds and set defaults
if have_start:
if start < 0:
start += shape
if start < 0:
start = 0
elif start >= shape:
if negative_step:
start = shape - 1
else:
start = shape
else:
if negative_step:
start = shape - 1
else:
start = 0
if have_stop:
if stop < 0:
stop += shape
if stop < 0:
stop = 0
elif stop > shape:
stop = shape
else:
if negative_step:
stop = -1
else:
stop = shape
# len = ceil( (stop - start) / step )
with cython.cdivision(True):
new_shape = (stop - start) // step
if (stop - start) - step * new_shape:
new_shape += 1
if new_shape < 0:
new_shape = 0
# shape/strides/suboffsets
dst.strides[new_ndim] = stride * step
dst.shape[new_ndim] = new_shape
dst.suboffsets[new_ndim] = suboffset
# Add the slicing or indexing offsets to the right suboffset or base data *
if suboffset_dim[0] < 0:
dst.data += start * stride
else:
dst.suboffsets[suboffset_dim[0]] += start * stride
if suboffset >= 0:
if not is_slice:
if new_ndim == 0:
dst.data = (<char **> dst.data)[0] + suboffset
else:
_err_dim(PyExc_IndexError, "All dimensions preceding dimension %d "
"must be indexed and not sliced", dim)
else:
suboffset_dim[0] = new_ndim
return 0
#
### Index a memoryview
#
@cname('__pyx_pybuffer_index')
cdef char *pybuffer_index(Py_buffer *view, char *bufp, Py_ssize_t index,
Py_ssize_t dim) except NULL:
cdef Py_ssize_t shape, stride, suboffset = -1
cdef Py_ssize_t itemsize = view.itemsize
cdef char *resultp
if view.ndim == 0:
shape = view.len // itemsize
stride = itemsize
else:
shape = view.shape[dim]
stride = view.strides[dim]
if view.suboffsets != NULL:
suboffset = view.suboffsets[dim]
if index < 0:
index += view.shape[dim]
if index < 0:
raise IndexError, f"Out of bounds on buffer access (axis {dim})"
if index >= shape:
raise IndexError, f"Out of bounds on buffer access (axis {dim})"
resultp = bufp + index * stride
if suboffset >= 0:
resultp = (<char **> resultp)[0] + suboffset
return resultp
#
### Transposing a memoryviewslice
#
@cname('__pyx_memslice_transpose')
cdef int transpose_memslice({{memviewslice_name}} *memslice) except -1 nogil:
cdef int ndim = memslice.memview.view.ndim
cdef Py_ssize_t *shape = memslice.shape
cdef Py_ssize_t *strides = memslice.strides
# reverse strides and shape
cdef int i, j
for i in range(ndim // 2):
j = ndim - 1 - i
strides[i], strides[j] = strides[j], strides[i]
shape[i], shape[j] = shape[j], shape[i]
if memslice.suboffsets[i] >= 0 or memslice.suboffsets[j] >= 0:
_err(PyExc_ValueError, "Cannot transpose memoryview with indirect dimensions")
return 0
#
### Creating new memoryview objects from slices and memoryviews
#
@cython.collection_type("sequence")
@cname('__pyx_memoryviewslice')
cdef class _memoryviewslice(memoryview):
"Internal class for passing memoryview slices to Python"
# We need this to keep our shape/strides/suboffset pointers valid
cdef {{memviewslice_name}} from_slice
# We need this only to print it's class' name
cdef object from_object
cdef object (*to_object_func)(char *)
cdef int (*to_dtype_func)(char *, object) except 0
def __dealloc__(self):
__PYX_XCLEAR_MEMVIEW(&self.from_slice, 1)
cdef convert_item_to_object(self, char *itemp):
if self.to_object_func != NULL:
return self.to_object_func(itemp)
else:
return memoryview.convert_item_to_object(self, itemp)
cdef assign_item_from_object(self, char *itemp, object value):
if self.to_dtype_func != NULL:
self.to_dtype_func(itemp, value)
else:
memoryview.assign_item_from_object(self, itemp, value)
cdef _get_base(self):
return self.from_object
# Sequence methods
try:
count = __pyx_collections_abc_Sequence.count
index = __pyx_collections_abc_Sequence.index
except:
pass
try:
if __pyx_collections_abc_Sequence:
# The main value of registering _memoryviewslice as a
# Sequence is that it can be used in structural pattern
# matching in Python 3.10+
__pyx_collections_abc_Sequence.register(_memoryviewslice)
__pyx_collections_abc_Sequence.register(array)
except:
pass # ignore failure, it's a minor issue
@cname('__pyx_memoryview_fromslice')
cdef memoryview_fromslice({{memviewslice_name}} memviewslice,
int ndim,
object (*to_object_func)(char *),
int (*to_dtype_func)(char *, object) except 0,
bint dtype_is_object):
cdef _memoryviewslice result