Coverage Report

Created: 2026-12-01 06:09

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython/Objects/memoryobject.c
Line
Count
Source
1
/*
2
 * Memoryview object implementation
3
 * --------------------------------
4
 *
5
 *   This implementation is a complete rewrite contributed by Stefan Krah in
6
 *   Python 3.3.  Substantial credit goes to Antoine Pitrou (who had already
7
 *   fortified and rewritten the previous implementation) and Nick Coghlan
8
 *   (who came up with the idea of the ManagedBuffer) for analyzing the complex
9
 *   ownership rules.
10
 *
11
 */
12
13
#include "Python.h"
14
#include "pycore_abstract.h"      // _PyIndex_Check()
15
#include "pycore_memoryobject.h"  // _PyManagedBuffer_Type
16
#include "pycore_object.h"        // _PyObject_GC_UNTRACK()
17
#include "pycore_strhex.h"        // _Py_strhex_with_sep()
18
#include <stddef.h>               // offsetof()
19
20
/*[clinic input]
21
class memoryview "PyMemoryViewObject *" "&PyMemoryView_Type"
22
[clinic start generated code]*/
23
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=e2e49d2192835219]*/
24
25
#include "clinic/memoryobject.c.h"
26
27
/****************************************************************************/
28
/*                           ManagedBuffer Object                           */
29
/****************************************************************************/
30
31
/*
32
   ManagedBuffer Object:
33
   ---------------------
34
35
     The purpose of this object is to facilitate the handling of chained
36
     memoryviews that have the same underlying exporting object. PEP-3118
37
     allows the underlying object to change while a view is exported. This
38
     could lead to unexpected results when constructing a new memoryview
39
     from an existing memoryview.
40
41
     Rather than repeatedly redirecting buffer requests to the original base
42
     object, all chained memoryviews use a single buffer snapshot. This
43
     snapshot is generated by the constructor _PyManagedBuffer_FromObject().
44
45
   Ownership rules:
46
   ----------------
47
48
     The master buffer inside a managed buffer is filled in by the original
49
     base object. shape, strides, suboffsets and format are read-only for
50
     all consumers.
51
52
     A memoryview's buffer is a private copy of the exporter's buffer. shape,
53
     strides and suboffsets belong to the memoryview and are thus writable.
54
55
     If a memoryview itself exports several buffers via memory_getbuf(), all
56
     buffer copies share shape, strides and suboffsets. In this case, the
57
     arrays are NOT writable.
58
59
   Reference count assumptions:
60
   ----------------------------
61
62
     The 'obj' member of a Py_buffer must either be NULL or refer to the
63
     exporting base object. In the Python codebase, all getbufferprocs
64
     return a new reference to view.obj (example: bytes_buffer_getbuffer()).
65
66
     PyBuffer_Release() decrements view.obj (if non-NULL), so the
67
     releasebufferprocs must NOT decrement view.obj.
68
*/
69
70
71
static inline _PyManagedBufferObject *
72
mbuf_alloc(void)
73
3.01M
{
74
3.01M
    _PyManagedBufferObject *mbuf;
75
76
3.01M
    mbuf = (_PyManagedBufferObject *)
77
3.01M
        PyObject_GC_New(_PyManagedBufferObject, &_PyManagedBuffer_Type);
78
3.01M
    if (mbuf == NULL)
79
0
        return NULL;
80
3.01M
    mbuf->flags = 0;
81
3.01M
    mbuf->exports = 0;
82
3.01M
    mbuf->master.obj = NULL;
83
3.01M
    _PyObject_GC_TRACK(mbuf);
84
85
3.01M
    return mbuf;
86
3.01M
}
87
88
static PyObject *
89
_PyManagedBuffer_FromObject(PyObject *base, int flags)
90
62.2k
{
91
62.2k
    _PyManagedBufferObject *mbuf;
92
93
62.2k
    mbuf = mbuf_alloc();
94
62.2k
    if (mbuf == NULL)
95
0
        return NULL;
96
97
62.2k
    if (PyObject_GetBuffer(base, &mbuf->master, flags) < 0) {
98
0
        mbuf->master.obj = NULL;
99
0
        Py_DECREF(mbuf);
100
0
        return NULL;
101
0
    }
102
103
62.2k
    return (PyObject *)mbuf;
104
62.2k
}
105
106
static inline int
107
flags_set_released(int *flags, int released)
108
9.30M
{
109
#ifdef Py_GIL_DISABLED
110
    int prev = _Py_atomic_load_int_relaxed(flags);
111
    if (prev & released) {
112
        return 1;
113
    }
114
    if (!_Py_atomic_compare_exchange_int(flags, &prev, prev | released)) {
115
        // RELEASED is the only flag that can change concurrently.
116
        assert(prev & released);
117
        return 1;
118
    }
119
    return 0;
120
#else
121
9.30M
    int prev = *flags;
122
9.30M
    *flags = prev | released;
123
9.30M
    return (prev & released) != 0;
124
9.30M
#endif
125
9.30M
}
126
127
static inline int
128
mv_get_flags(PyMemoryViewObject *mv)
129
15.2M
{
130
15.2M
    return FT_ATOMIC_LOAD_INT_RELAXED(mv->flags);
131
15.2M
}
132
133
static inline int
134
mv_has_flag(PyMemoryViewObject *mv, int bits)
135
12.2M
{
136
12.2M
    return (mv_get_flags(mv) & bits) != 0;
137
12.2M
}
138
139
static inline int
140
mv_set_released(PyMemoryViewObject *mv)
141
3.28M
{
142
3.28M
    return flags_set_released(&mv->flags, _Py_MEMORYVIEW_RELEASED);
143
3.28M
}
144
145
static inline int
146
mbuf_has_flag(_PyManagedBufferObject *mbuf, int bits)
147
11.9M
{
148
11.9M
    return (FT_ATOMIC_LOAD_INT(mbuf->flags) & bits) != 0;
149
11.9M
}
150
151
static inline int
152
mbuf_set_released(_PyManagedBufferObject *mbuf)
153
6.02M
{
154
6.02M
    return flags_set_released(&mbuf->flags, _Py_MANAGED_BUFFER_RELEASED);
155
6.02M
}
156
157
static void
158
mbuf_release(_PyManagedBufferObject *self)
159
6.02M
{
160
6.02M
    if (mbuf_set_released(self)) {
161
3.01M
        return;
162
3.01M
    }
163
164
    /* PyBuffer_Release() decrements master->obj and sets it to NULL. */
165
3.01M
    _PyObject_GC_UNTRACK(self);
166
3.01M
    PyBuffer_Release(&self->master);
167
3.01M
}
168
169
static void
170
mbuf_dealloc(PyObject *_self)
171
3.01M
{
172
3.01M
    _PyManagedBufferObject *self = (_PyManagedBufferObject *)_self;
173
3.01M
    assert(FT_ATOMIC_LOAD_SSIZE_RELAXED(self->exports) == 0);
174
3.01M
    mbuf_release(self);
175
3.01M
    if (mbuf_has_flag(self, _Py_MANAGED_BUFFER_FREE_FORMAT))
176
0
        PyMem_Free(self->master.format);
177
3.01M
    PyObject_GC_Del(self);
178
3.01M
}
179
180
static int
181
mbuf_traverse(PyObject *_self, visitproc visit, void *arg)
182
772
{
183
772
    _PyManagedBufferObject *self = (_PyManagedBufferObject *)_self;
184
772
    Py_VISIT(self->master.obj);
185
772
    return 0;
186
772
}
187
188
static int
189
mbuf_clear(PyObject *_self)
190
0
{
191
0
    _PyManagedBufferObject *self = (_PyManagedBufferObject *)_self;
192
0
    assert(FT_ATOMIC_LOAD_SSIZE_RELAXED(self->exports) >= 0);
193
0
    mbuf_release(self);
194
0
    return 0;
195
0
}
196
197
PyTypeObject _PyManagedBuffer_Type = {
198
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
199
    "managedbuffer",
200
    sizeof(_PyManagedBufferObject),
201
    0,
202
    mbuf_dealloc,                            /* tp_dealloc */
203
    0,                                       /* tp_vectorcall_offset */
204
    0,                                       /* tp_getattr */
205
    0,                                       /* tp_setattr */
206
    0,                                       /* tp_as_async */
207
    0,                                       /* tp_repr */
208
    0,                                       /* tp_as_number */
209
    0,                                       /* tp_as_sequence */
210
    0,                                       /* tp_as_mapping */
211
    0,                                       /* tp_hash */
212
    0,                                       /* tp_call */
213
    0,                                       /* tp_str */
214
    PyObject_GenericGetAttr,                 /* tp_getattro */
215
    0,                                       /* tp_setattro */
216
    0,                                       /* tp_as_buffer */
217
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
218
    0,                                       /* tp_doc */
219
    mbuf_traverse,                           /* tp_traverse */
220
    mbuf_clear                               /* tp_clear */
221
};
222
223
224
/****************************************************************************/
225
/*                             MemoryView Object                            */
226
/****************************************************************************/
227
228
/* In the process of breaking reference cycles mbuf_release() can be
229
   called before memory_release(). */
230
#define BASE_INACCESSIBLE(mv) \
231
8.94M
    (mv_has_flag(_PyMemoryView_CAST(mv), _Py_MEMORYVIEW_RELEASED) || \
232
8.94M
     mbuf_has_flag(_PyMemoryView_CAST(mv)->mbuf, _Py_MANAGED_BUFFER_RELEASED))
233
234
#define CHECK_RELEASED(mv) \
235
4.26M
    if (BASE_INACCESSIBLE(mv)) {                                  \
236
0
        PyErr_SetString(PyExc_ValueError,                         \
237
0
            "operation forbidden on released memoryview object"); \
238
0
        return NULL;                                              \
239
0
    }
240
241
#define CHECK_RELEASED_INT(mv) \
242
4.40M
    if (BASE_INACCESSIBLE(mv)) {                                  \
243
0
        PyErr_SetString(PyExc_ValueError,                         \
244
0
            "operation forbidden on released memoryview object"); \
245
0
        return -1;                                                \
246
0
    }
247
248
#define CHECK_RESTRICTED(mv) \
249
116k
    if (mv_has_flag(_PyMemoryView_CAST(mv), _Py_MEMORYVIEW_RESTRICTED)) { \
250
0
        PyErr_SetString(PyExc_ValueError,                                 \
251
0
            "cannot create new view on restricted memoryview");           \
252
0
        return NULL;                                                      \
253
0
    }
254
255
#define CHECK_RESTRICTED_INT(mv) \
256
2.88M
    if (mv_has_flag(_PyMemoryView_CAST(mv), _Py_MEMORYVIEW_RESTRICTED)) { \
257
0
        PyErr_SetString(PyExc_ValueError,                                 \
258
0
            "cannot create new view on restricted memoryview");           \
259
0
        return -1;                                                        \
260
0
    }
261
262
/* See gh-92888. These macros signal that we need to check the memoryview
263
   again due to possible read after frees. */
264
3.86M
#define CHECK_RELEASED_AGAIN(mv) CHECK_RELEASED(mv)
265
48.2k
#define CHECK_RELEASED_INT_AGAIN(mv) CHECK_RELEASED_INT(mv)
266
267
#define CHECK_LIST_OR_TUPLE(v) \
268
0
    if (!PyList_Check(v) && !PyTuple_Check(v)) { \
269
0
        PyErr_SetString(PyExc_TypeError,         \
270
0
            #v " must be a list or a tuple");    \
271
0
        return NULL;                             \
272
0
    }
273
274
114
#define VIEW_ADDR(mv) (&((PyMemoryViewObject *)mv)->view)
275
276
/* Check for the presence of suboffsets in the first dimension. */
277
3.86M
#define HAVE_PTR(suboffsets, dim) (suboffsets && suboffsets[dim] >= 0)
278
/* Adjust ptr if suboffsets are present. */
279
#define ADJUST_PTR(ptr, suboffsets, dim) \
280
3.86M
    (HAVE_PTR(suboffsets, dim) ? *((char**)ptr) + suboffsets[dim] : ptr)
281
282
/* Memoryview buffer properties */
283
1.67M
#define MV_C_CONTIGUOUS(flags) (flags&(_Py_MEMORYVIEW_SCALAR|_Py_MEMORYVIEW_C))
284
#define MV_F_CONTIGUOUS(flags) \
285
0
    (flags&(_Py_MEMORYVIEW_SCALAR|_Py_MEMORYVIEW_FORTRAN))
286
#define MV_ANY_CONTIGUOUS(flags) \
287
0
    (flags&(_Py_MEMORYVIEW_SCALAR|_Py_MEMORYVIEW_C|_Py_MEMORYVIEW_FORTRAN))
288
289
/* Fast contiguity test. Caller must ensure suboffsets==NULL and ndim==1. */
290
#define MV_CONTIGUOUS_NDIM1(view) \
291
3.18M
    ((view)->shape[0] == 1 || (view)->strides[0] == (view)->itemsize)
292
293
/* getbuffer() requests */
294
5.76M
#define REQ_INDIRECT(flags) ((flags&PyBUF_INDIRECT) == PyBUF_INDIRECT)
295
5.76M
#define REQ_C_CONTIGUOUS(flags) ((flags&PyBUF_C_CONTIGUOUS) == PyBUF_C_CONTIGUOUS)
296
5.76M
#define REQ_F_CONTIGUOUS(flags) ((flags&PyBUF_F_CONTIGUOUS) == PyBUF_F_CONTIGUOUS)
297
5.76M
#define REQ_ANY_CONTIGUOUS(flags) ((flags&PyBUF_ANY_CONTIGUOUS) == PyBUF_ANY_CONTIGUOUS)
298
2.88M
#define REQ_STRIDES(flags) ((flags&PyBUF_STRIDES) == PyBUF_STRIDES)
299
2.88M
#define REQ_SHAPE(flags) ((flags&PyBUF_ND) == PyBUF_ND)
300
5.76M
#define REQ_WRITABLE(flags) (flags&PyBUF_WRITABLE)
301
2.88M
#define REQ_FORMAT(flags) (flags&PyBUF_FORMAT)
302
303
304
/**************************************************************************/
305
/*                       Copy memoryview buffers                          */
306
/**************************************************************************/
307
308
/* The functions in this section take a source and a destination buffer
309
   with the same logical structure: format, itemsize, ndim and shape
310
   are identical, with ndim > 0.
311
312
   NOTE: All buffers are assumed to have PyBUF_FULL information, which
313
   is the case for memoryviews! */
314
315
316
/* Assumptions: ndim >= 1. The macro tests for a corner case that should
317
   perhaps be explicitly forbidden in the PEP. */
318
#define HAVE_SUBOFFSETS_IN_LAST_DIM(view) \
319
192k
    (view->suboffsets && view->suboffsets[view->ndim-1] >= 0)
320
321
static inline int
322
last_dim_is_contiguous(const Py_buffer *dest, const Py_buffer *src)
323
48.2k
{
324
48.2k
    assert(dest->ndim > 0 && src->ndim > 0);
325
48.2k
    return (!HAVE_SUBOFFSETS_IN_LAST_DIM(dest) &&
326
48.2k
            !HAVE_SUBOFFSETS_IN_LAST_DIM(src) &&
327
48.2k
            dest->strides[dest->ndim-1] == dest->itemsize &&
328
48.2k
            src->strides[src->ndim-1] == src->itemsize);
329
48.2k
}
330
331
/* This is not a general function for determining format equivalence.
332
   It is used in copy_single() and copy_buffer() to weed out non-matching
333
   formats. Skipping the '@' character is specifically used in slice
334
   assignments, where the lvalue is already known to have a
335
   format. This is a performance hack that could be rewritten (if properly
336
   benchmarked). */
337
static inline int
338
equiv_format(const Py_buffer *dest, const Py_buffer *src)
339
48.2k
{
340
48.2k
    const char *dfmt, *sfmt;
341
342
48.2k
    assert(dest->format && src->format);
343
48.2k
    dfmt = dest->format[0] == '@' ? dest->format+1 : dest->format;
344
48.2k
    sfmt = src->format[0] == '@' ? src->format+1 : src->format;
345
346
48.2k
    if (strcmp(dfmt, sfmt) != 0 ||
347
48.2k
        dest->itemsize != src->itemsize) {
348
0
        return 0;
349
0
    }
350
351
48.2k
    return 1;
352
48.2k
}
353
354
/* Two shapes are equivalent if they are either equal or identical up
355
   to a zero element at the same position. For example, in NumPy arrays
356
   the shapes [1, 0, 5] and [1, 0, 7] are equivalent. */
357
static inline int
358
equiv_shape(const Py_buffer *dest, const Py_buffer *src)
359
48.3k
{
360
48.3k
    int i;
361
362
48.3k
    if (dest->ndim != src->ndim)
363
0
        return 0;
364
365
96.3k
    for (i = 0; i < dest->ndim; i++) {
366
48.3k
        if (dest->shape[i] != src->shape[i])
367
29
            return 0;
368
48.2k
        if (dest->shape[i] == 0)
369
297
            break;
370
48.2k
    }
371
372
48.2k
    return 1;
373
48.3k
}
374
375
/* Check that the logical structure of the destination and source buffers
376
   is identical. */
377
static int
378
equiv_structure(const Py_buffer *dest, const Py_buffer *src)
379
48.2k
{
380
48.2k
    if (!equiv_format(dest, src) ||
381
48.2k
        !equiv_shape(dest, src)) {
382
0
        PyErr_SetString(PyExc_ValueError,
383
0
            "memoryview assignment: lvalue and rvalue have different "
384
0
            "structures");
385
0
        return 0;
386
0
    }
387
388
48.2k
    return 1;
389
48.2k
}
390
391
/* Base case for recursive multi-dimensional copying. Contiguous arrays are
392
   copied with very little overhead. Assumptions: ndim == 1, mem == NULL or
393
   sizeof(mem) == shape[0] * itemsize. */
394
static void
395
copy_base(const Py_ssize_t *shape, Py_ssize_t itemsize,
396
          char *dptr, const Py_ssize_t *dstrides, const Py_ssize_t *dsuboffsets,
397
          char *sptr, const Py_ssize_t *sstrides, const Py_ssize_t *ssuboffsets,
398
          char *mem)
399
48.2k
{
400
48.2k
    if (mem == NULL) { /* contiguous */
401
48.2k
        Py_ssize_t size = shape[0] * itemsize;
402
48.2k
        if (dptr + size < sptr || sptr + size < dptr)
403
48.2k
            memcpy(dptr, sptr, size); /* no overlapping */
404
0
        else
405
0
            memmove(dptr, sptr, size);
406
48.2k
    }
407
0
    else {
408
0
        char *p;
409
0
        Py_ssize_t i;
410
0
        for (i=0, p=mem; i < shape[0]; p+=itemsize, sptr+=sstrides[0], i++) {
411
0
            char *xsptr = ADJUST_PTR(sptr, ssuboffsets, 0);
412
0
            memcpy(p, xsptr, itemsize);
413
0
        }
414
0
        for (i=0, p=mem; i < shape[0]; p+=itemsize, dptr+=dstrides[0], i++) {
415
0
            char *xdptr = ADJUST_PTR(dptr, dsuboffsets, 0);
416
0
            memcpy(xdptr, p, itemsize);
417
0
        }
418
0
    }
419
420
48.2k
}
421
422
/* Recursively copy a source buffer to a destination buffer. The two buffers
423
   have the same ndim, shape and itemsize. */
424
static void
425
copy_rec(const Py_ssize_t *shape, Py_ssize_t ndim, Py_ssize_t itemsize,
426
         char *dptr, const Py_ssize_t *dstrides, const Py_ssize_t *dsuboffsets,
427
         char *sptr, const Py_ssize_t *sstrides, const Py_ssize_t *ssuboffsets,
428
         char *mem)
429
0
{
430
0
    Py_ssize_t i;
431
432
0
    assert(ndim >= 1);
433
434
0
    if (ndim == 1) {
435
0
        copy_base(shape, itemsize,
436
0
                  dptr, dstrides, dsuboffsets,
437
0
                  sptr, sstrides, ssuboffsets,
438
0
                  mem);
439
0
        return;
440
0
    }
441
442
0
    for (i = 0; i < shape[0]; dptr+=dstrides[0], sptr+=sstrides[0], i++) {
443
0
        char *xdptr = ADJUST_PTR(dptr, dsuboffsets, 0);
444
0
        char *xsptr = ADJUST_PTR(sptr, ssuboffsets, 0);
445
446
0
        copy_rec(shape+1, ndim-1, itemsize,
447
0
                 xdptr, dstrides+1, dsuboffsets ? dsuboffsets+1 : NULL,
448
0
                 xsptr, sstrides+1, ssuboffsets ? ssuboffsets+1 : NULL,
449
0
                 mem);
450
0
    }
451
0
}
452
453
/* Faster copying of one-dimensional arrays. */
454
static int
455
copy_single(PyMemoryViewObject *self, const Py_buffer *dest, const Py_buffer *src)
456
48.2k
{
457
48.2k
    CHECK_RELEASED_INT_AGAIN(self);
458
48.2k
    char *mem = NULL;
459
460
48.2k
    assert(dest->ndim == 1);
461
462
48.2k
    if (!equiv_structure(dest, src))
463
0
        return -1;
464
465
48.2k
    if (!last_dim_is_contiguous(dest, src)) {
466
0
        mem = PyMem_Malloc(dest->shape[0] * dest->itemsize);
467
0
        if (mem == NULL) {
468
0
            PyErr_NoMemory();
469
0
            return -1;
470
0
        }
471
0
    }
472
473
48.2k
    copy_base(dest->shape, dest->itemsize,
474
48.2k
              dest->buf, dest->strides, dest->suboffsets,
475
48.2k
              src->buf, src->strides, src->suboffsets,
476
48.2k
              mem);
477
478
48.2k
    if (mem)
479
0
        PyMem_Free(mem);
480
481
48.2k
    return 0;
482
48.2k
}
483
484
/* Recursively copy src to dest. Both buffers must have the same basic
485
   structure. Copying is atomic, the function never fails with a partial
486
   copy. */
487
static int
488
copy_buffer(const Py_buffer *dest, const Py_buffer *src)
489
0
{
490
0
    char *mem = NULL;
491
492
0
    assert(dest->ndim > 0);
493
494
0
    if (!equiv_structure(dest, src))
495
0
        return -1;
496
497
0
    if (!last_dim_is_contiguous(dest, src)) {
498
0
        mem = PyMem_Malloc(dest->shape[dest->ndim-1] * dest->itemsize);
499
0
        if (mem == NULL) {
500
0
            PyErr_NoMemory();
501
0
            return -1;
502
0
        }
503
0
    }
504
505
0
    copy_rec(dest->shape, dest->ndim, dest->itemsize,
506
0
             dest->buf, dest->strides, dest->suboffsets,
507
0
             src->buf, src->strides, src->suboffsets,
508
0
             mem);
509
510
0
    if (mem)
511
0
        PyMem_Free(mem);
512
513
0
    return 0;
514
0
}
515
516
/* Initialize strides for a C-contiguous array. */
517
static inline void
518
init_strides_from_shape(Py_buffer *view)
519
0
{
520
0
    Py_ssize_t i;
521
522
0
    assert(view->ndim > 0);
523
524
0
    view->strides[view->ndim-1] = view->itemsize;
525
0
    for (i = view->ndim-2; i >= 0; i--)
526
0
        view->strides[i] = view->strides[i+1] * view->shape[i+1];
527
0
}
528
529
/* Initialize strides for a Fortran-contiguous array. */
530
static inline void
531
init_fortran_strides_from_shape(Py_buffer *view)
532
0
{
533
0
    Py_ssize_t i;
534
535
0
    assert(view->ndim > 0);
536
537
0
    view->strides[0] = view->itemsize;
538
0
    for (i = 1; i < view->ndim; i++)
539
0
        view->strides[i] = view->strides[i-1] * view->shape[i-1];
540
0
}
541
542
/* Copy src to a contiguous representation. order is one of 'C', 'F' (Fortran)
543
   or 'A' (Any). Assumptions: src has PyBUF_FULL information, src->ndim >= 1,
544
   len(mem) == src->len. */
545
static int
546
buffer_to_contiguous(char *mem, const Py_buffer *src, char order)
547
0
{
548
0
    Py_buffer dest;
549
0
    Py_ssize_t *strides;
550
0
    int ret;
551
552
0
    assert(src->ndim >= 1);
553
0
    assert(src->shape != NULL);
554
0
    assert(src->strides != NULL);
555
556
0
    strides = PyMem_Malloc(src->ndim * (sizeof *src->strides));
557
0
    if (strides == NULL) {
558
0
        PyErr_NoMemory();
559
0
        return -1;
560
0
    }
561
562
    /* initialize dest */
563
0
    dest = *src;
564
0
    dest.buf = mem;
565
    /* shape is constant and shared: the logical representation of the
566
       array is unaltered. */
567
568
    /* The physical representation determined by strides (and possibly
569
       suboffsets) may change. */
570
0
    dest.strides = strides;
571
0
    if (order == 'C' || order == 'A') {
572
0
        init_strides_from_shape(&dest);
573
0
    }
574
0
    else {
575
0
        init_fortran_strides_from_shape(&dest);
576
0
    }
577
578
0
    dest.suboffsets = NULL;
579
580
0
    ret = copy_buffer(&dest, src);
581
582
0
    PyMem_Free(strides);
583
0
    return ret;
584
0
}
585
586
587
/****************************************************************************/
588
/*                               Constructors                               */
589
/****************************************************************************/
590
591
/* Initialize values that are shared with the managed buffer. */
592
static inline void
593
init_shared_values(Py_buffer *dest, const Py_buffer *src)
594
3.18M
{
595
3.18M
    dest->obj = src->obj;
596
3.18M
    dest->buf = src->buf;
597
3.18M
    dest->len = src->len;
598
3.18M
    dest->itemsize = src->itemsize;
599
3.18M
    dest->readonly = src->readonly;
600
3.18M
    dest->format = src->format ? src->format : "B";
601
3.18M
    dest->internal = src->internal;
602
3.18M
}
603
604
/* Copy shape and strides. Reconstruct missing values. */
605
static void
606
init_shape_strides(Py_buffer *dest, const Py_buffer *src)
607
3.06M
{
608
3.06M
    Py_ssize_t i;
609
610
3.06M
    if (src->ndim == 0) {
611
0
        dest->shape = NULL;
612
0
        dest->strides = NULL;
613
0
        return;
614
0
    }
615
3.06M
    if (src->ndim == 1) {
616
3.06M
        dest->shape[0] = src->shape ? src->shape[0] : src->len / src->itemsize;
617
3.06M
        dest->strides[0] = src->strides ? src->strides[0] : src->itemsize;
618
3.06M
        return;
619
3.06M
    }
620
621
0
    for (i = 0; i < src->ndim; i++)
622
0
        dest->shape[i] = src->shape[i];
623
0
    if (src->strides) {
624
0
        for (i = 0; i < src->ndim; i++)
625
0
            dest->strides[i] = src->strides[i];
626
0
    }
627
0
    else {
628
0
        init_strides_from_shape(dest);
629
0
    }
630
0
}
631
632
static inline void
633
init_suboffsets(Py_buffer *dest, const Py_buffer *src)
634
3.06M
{
635
3.06M
    Py_ssize_t i;
636
637
3.06M
    if (src->suboffsets == NULL) {
638
3.06M
        dest->suboffsets = NULL;
639
3.06M
        return;
640
3.06M
    }
641
0
    for (i = 0; i < src->ndim; i++)
642
0
        dest->suboffsets[i] = src->suboffsets[i];
643
0
}
644
645
/* len = product(shape) * itemsize */
646
static inline void
647
init_len(Py_buffer *view)
648
2.04k
{
649
2.04k
    Py_ssize_t i, len;
650
651
2.04k
    len = 1;
652
4.09k
    for (i = 0; i < view->ndim; i++)
653
2.04k
        len *= view->shape[i];
654
2.04k
    len *= view->itemsize;
655
656
2.04k
    view->len = len;
657
2.04k
}
658
659
/* Initialize memoryview buffer properties. */
660
static void
661
init_flags(PyMemoryViewObject *mv)
662
3.18M
{
663
3.18M
    const Py_buffer *view = &mv->view;
664
3.18M
    int flags = 0;
665
666
3.18M
    switch (view->ndim) {
667
0
    case 0:
668
0
        flags |= (_Py_MEMORYVIEW_SCALAR|_Py_MEMORYVIEW_C|
669
0
                  _Py_MEMORYVIEW_FORTRAN);
670
0
        break;
671
3.18M
    case 1:
672
3.18M
        if (MV_CONTIGUOUS_NDIM1(view))
673
3.18M
            flags |= (_Py_MEMORYVIEW_C|_Py_MEMORYVIEW_FORTRAN);
674
3.18M
        break;
675
0
    default:
676
0
        if (PyBuffer_IsContiguous(view, 'C'))
677
0
            flags |= _Py_MEMORYVIEW_C;
678
0
        if (PyBuffer_IsContiguous(view, 'F'))
679
0
            flags |= _Py_MEMORYVIEW_FORTRAN;
680
0
        break;
681
3.18M
    }
682
683
3.18M
    if (view->suboffsets) {
684
0
        flags |= _Py_MEMORYVIEW_PIL;
685
0
        flags &= ~(_Py_MEMORYVIEW_C|_Py_MEMORYVIEW_FORTRAN);
686
0
    }
687
688
3.18M
    mv->flags = flags;
689
3.18M
}
690
691
/* Allocate a new memoryview and perform basic initialization. New memoryviews
692
   are exclusively created through the mbuf_add functions. */
693
static inline PyMemoryViewObject *
694
memory_alloc(int ndim)
695
3.18M
{
696
3.18M
    PyMemoryViewObject *mv;
697
698
3.18M
    mv = (PyMemoryViewObject *)
699
3.18M
        PyObject_GC_NewVar(PyMemoryViewObject, &PyMemoryView_Type, 3*ndim);
700
3.18M
    if (mv == NULL)
701
0
        return NULL;
702
703
3.18M
    mv->mbuf = NULL;
704
3.18M
    mv->hash = -1;
705
3.18M
    mv->flags = 0;
706
3.18M
    mv->exports = 0;
707
3.18M
    mv->view.ndim = ndim;
708
3.18M
    mv->view.shape = mv->ob_array;
709
3.18M
    mv->view.strides = mv->ob_array + ndim;
710
3.18M
    mv->view.suboffsets = mv->ob_array + 2 * ndim;
711
3.18M
    mv->weakreflist = NULL;
712
713
3.18M
    _PyObject_GC_TRACK(mv);
714
3.18M
    return mv;
715
3.18M
}
716
717
/*
718
   Return a new memoryview that is registered with mbuf. If src is NULL,
719
   use mbuf->master as the underlying buffer. Otherwise, use src.
720
721
   The new memoryview has full buffer information: shape and strides
722
   are always present, suboffsets as needed. Arrays are copied to
723
   the memoryview's ob_array field.
724
 */
725
static PyObject *
726
mbuf_add_view(_PyManagedBufferObject *mbuf, const Py_buffer *src)
727
3.06M
{
728
3.06M
    PyMemoryViewObject *mv;
729
3.06M
    Py_buffer *dest;
730
731
3.06M
    if (src == NULL)
732
3.01M
        src = &mbuf->master;
733
734
3.06M
    if (src->ndim > PyBUF_MAX_NDIM) {
735
0
        PyErr_SetString(PyExc_ValueError,
736
0
            "memoryview: number of dimensions must not exceed "
737
0
            Py_STRINGIFY(PyBUF_MAX_NDIM));
738
0
        return NULL;
739
0
    }
740
741
3.06M
    mv = memory_alloc(src->ndim);
742
3.06M
    if (mv == NULL)
743
0
        return NULL;
744
745
3.06M
    dest = &mv->view;
746
3.06M
    init_shared_values(dest, src);
747
3.06M
    init_shape_strides(dest, src);
748
3.06M
    init_suboffsets(dest, src);
749
3.06M
    init_flags(mv);
750
751
3.06M
    mv->mbuf = (_PyManagedBufferObject*)Py_NewRef(mbuf);
752
3.06M
    FT_ATOMIC_ADD_SSIZE(mbuf->exports, 1);
753
754
3.06M
    return (PyObject *)mv;
755
3.06M
}
756
757
/* Register an incomplete view: shape, strides, suboffsets and flags still
758
   need to be initialized. Use 'ndim' instead of src->ndim to determine the
759
   size of the memoryview's ob_array.
760
761
   Assumption: ndim <= PyBUF_MAX_NDIM. */
762
static PyObject *
763
mbuf_add_incomplete_view(_PyManagedBufferObject *mbuf, const Py_buffer *src,
764
                         int ndim)
765
114k
{
766
114k
    PyMemoryViewObject *mv;
767
114k
    Py_buffer *dest;
768
769
114k
    if (src == NULL)
770
0
        src = &mbuf->master;
771
772
114k
    assert(ndim <= PyBUF_MAX_NDIM);
773
774
114k
    mv = memory_alloc(ndim);
775
114k
    if (mv == NULL)
776
0
        return NULL;
777
778
114k
    dest = &mv->view;
779
114k
    init_shared_values(dest, src);
780
781
114k
    mv->mbuf = (_PyManagedBufferObject*)Py_NewRef(mbuf);
782
114k
    FT_ATOMIC_ADD_SSIZE(mbuf->exports, 1);
783
784
114k
    return (PyObject *)mv;
785
114k
}
786
787
#ifdef Py_GIL_DISABLED
788
static int
789
memoryview_add_export(PyMemoryViewObject *self)
790
{
791
    int result = 0;
792
793
    Py_BEGIN_CRITICAL_SECTION(self);
794
    if (BASE_INACCESSIBLE(self)) {
795
        PyErr_SetString(PyExc_ValueError,
796
            "operation forbidden on released memoryview object");
797
        result = -1;
798
    }
799
    else {
800
        FT_ATOMIC_ADD_SSIZE(self->exports, 1);
801
    }
802
    Py_END_CRITICAL_SECTION();
803
804
    return result;
805
}
806
#endif
807
808
static void
809
mbuf_drop_export(_PyManagedBufferObject *mbuf)
810
3.45M
{
811
#ifdef Py_GIL_DISABLED
812
    Py_ssize_t prev_exports = _Py_atomic_add_ssize(&mbuf->exports, -1);
813
#else
814
3.45M
    Py_ssize_t prev_exports = mbuf->exports--;
815
3.45M
#endif
816
3.45M
    assert(prev_exports > 0);
817
3.45M
    if (prev_exports == 1) {
818
3.01M
        mbuf_release(mbuf);
819
3.01M
    }
820
3.45M
}
821
822
/* Pin the managed buffer for the duration of an operation that reads
823
   self->view. The pin is an export on the managed buffer, so a concurrent
824
   or re-entrant release of this memoryview (or a tp_clear of it) cannot
825
   free the underlying buffer while the operation is running. The pin does
826
   not hold a reference to the managed buffer: the memoryview's own
827
   reference is kept until memory_dealloc(), and the caller holds a
828
   reference to the memoryview through memoryview_unpin(self). Return 0
829
   on success and -1 with an exception on failure. */
830
static inline int
831
memoryview_pin(PyMemoryViewObject *self)
832
278k
{
833
278k
    if (mv_has_flag(self, _Py_MEMORYVIEW_RELEASED)) {
834
0
        PyErr_SetString(PyExc_ValueError,
835
0
            "operation forbidden on released memoryview object");
836
0
        return -1;
837
0
    }
838
278k
    _PyManagedBufferObject *mbuf = self->mbuf;
839
278k
    FT_ATOMIC_ADD_SSIZE(mbuf->exports, 1);
840
278k
    if (BASE_INACCESSIBLE(self)) {
841
0
        mbuf_drop_export(mbuf);
842
0
        PyErr_SetString(PyExc_ValueError,
843
0
            "operation forbidden on released memoryview object");
844
0
        return -1;
845
0
    }
846
278k
    return 0;
847
278k
}
848
849
static inline void
850
memoryview_unpin(PyMemoryViewObject *self)
851
278k
{
852
278k
    mbuf_drop_export(self->mbuf);
853
278k
}
854
855
/* Expose a raw memory area as a view of contiguous bytes. flags can be
856
   PyBUF_READ or PyBUF_WRITE. view->format is set to "B" (unsigned bytes).
857
   The memoryview has complete buffer information. */
858
PyObject *
859
PyMemoryView_FromMemory(char *mem, Py_ssize_t size, int flags)
860
0
{
861
0
    _PyManagedBufferObject *mbuf;
862
0
    PyObject *mv;
863
0
    int readonly;
864
865
0
    assert(mem != NULL);
866
0
    assert(flags == PyBUF_READ || flags == PyBUF_WRITE);
867
868
0
    mbuf = mbuf_alloc();
869
0
    if (mbuf == NULL)
870
0
        return NULL;
871
872
0
    readonly = (flags == PyBUF_WRITE) ? 0 : 1;
873
0
    (void)PyBuffer_FillInfo(&mbuf->master, NULL, mem, size, readonly,
874
0
                            PyBUF_FULL_RO);
875
876
0
    mv = mbuf_add_view(mbuf, NULL);
877
0
    Py_DECREF(mbuf);
878
879
0
    return mv;
880
0
}
881
882
/* Create a memoryview from a given Py_buffer. For simple byte views,
883
   PyMemoryView_FromMemory() should be used instead.
884
   This function is the only entry point that can create a master buffer
885
   without full information. Because of this fact init_shape_strides()
886
   must be able to reconstruct missing values.  */
887
PyObject *
888
PyMemoryView_FromBuffer(const Py_buffer *info)
889
2.94M
{
890
2.94M
    _PyManagedBufferObject *mbuf;
891
2.94M
    PyObject *mv;
892
893
2.94M
    if (info->buf == NULL) {
894
0
        PyErr_SetString(PyExc_ValueError,
895
0
            "PyMemoryView_FromBuffer(): info->buf must not be NULL");
896
0
        return NULL;
897
0
    }
898
899
2.94M
    mbuf = mbuf_alloc();
900
2.94M
    if (mbuf == NULL)
901
0
        return NULL;
902
903
    /* info->obj is either NULL or a borrowed reference. This reference
904
       should not be decremented in PyBuffer_Release(). */
905
2.94M
    mbuf->master = *info;
906
2.94M
    mbuf->master.obj = NULL;
907
908
2.94M
    mv = mbuf_add_view(mbuf, NULL);
909
2.94M
    Py_DECREF(mbuf);
910
911
2.94M
    return mv;
912
2.94M
}
913
914
/* Create a memoryview from an object that implements the buffer protocol,
915
   using the given flags.
916
   If the object is a memoryview, the new memoryview must be registered
917
   with the same managed buffer. Otherwise, a new managed buffer is created. */
918
static PyObject *
919
PyMemoryView_FromObjectAndFlags(PyObject *v, int flags)
920
115k
{
921
115k
    _PyManagedBufferObject *mbuf;
922
923
115k
    if (PyMemoryView_Check(v)) {
924
53.7k
        PyMemoryViewObject *mv = (PyMemoryViewObject *)v;
925
53.7k
        if (memoryview_pin(mv) < 0) {
926
0
            return NULL;
927
0
        }
928
53.7k
        PyObject *result;
929
53.7k
        if (mv_has_flag(mv, _Py_MEMORYVIEW_RESTRICTED)) {
930
0
            PyErr_SetString(PyExc_ValueError,
931
0
                            "cannot create new view on restricted memoryview");
932
0
            result = NULL;
933
0
        }
934
53.7k
        else {
935
53.7k
            result = mbuf_add_view(mv->mbuf, &mv->view);
936
53.7k
        }
937
53.7k
        memoryview_unpin(mv);
938
53.7k
        return result;
939
53.7k
    }
940
62.2k
    else if (PyObject_CheckBuffer(v)) {
941
62.2k
        PyObject *ret;
942
62.2k
        mbuf = (_PyManagedBufferObject *)_PyManagedBuffer_FromObject(v, flags);
943
62.2k
        if (mbuf == NULL)
944
0
            return NULL;
945
62.2k
        ret = mbuf_add_view(mbuf, NULL);
946
62.2k
        Py_DECREF(mbuf);
947
62.2k
        return ret;
948
62.2k
    }
949
950
0
    PyErr_Format(PyExc_TypeError,
951
0
        "memoryview: a bytes-like object is required, not '%.200s'",
952
0
        Py_TYPE(v)->tp_name);
953
0
    return NULL;
954
115k
}
955
956
/* Create a memoryview from an object that implements the buffer protocol,
957
   using the given flags.
958
   If the object is a memoryview, the new memoryview must be registered
959
   with the same managed buffer. Otherwise, a new managed buffer is created. */
960
PyObject *
961
_PyMemoryView_FromBufferProc(PyObject *v, int flags, getbufferproc bufferproc)
962
0
{
963
0
    _PyManagedBufferObject *mbuf = mbuf_alloc();
964
0
    if (mbuf == NULL)
965
0
        return NULL;
966
967
0
    int res = bufferproc(v, &mbuf->master, flags);
968
0
    if (res < 0) {
969
0
        mbuf->master.obj = NULL;
970
0
        Py_DECREF(mbuf);
971
0
        return NULL;
972
0
    }
973
974
0
    PyObject *ret = mbuf_add_view(mbuf, NULL);
975
0
    Py_DECREF(mbuf);
976
0
    return ret;
977
0
}
978
979
/* Create a memoryview from an object that implements the buffer protocol.
980
   If the object is a memoryview, the new memoryview must be registered
981
   with the same managed buffer. Otherwise, a new managed buffer is created. */
982
PyObject *
983
PyMemoryView_FromObject(PyObject *v)
984
115k
{
985
115k
    return PyMemoryView_FromObjectAndFlags(v, PyBUF_FULL_RO);
986
115k
}
987
988
/* Copy the format string from a base object that might vanish. */
989
static int
990
mbuf_copy_format(_PyManagedBufferObject *mbuf, const char *fmt)
991
0
{
992
0
    if (fmt != NULL) {
993
0
        char *cp = PyMem_Malloc(strlen(fmt)+1);
994
0
        if (cp == NULL) {
995
0
            PyErr_NoMemory();
996
0
            return -1;
997
0
        }
998
0
        mbuf->master.format = strcpy(cp, fmt);
999
0
        mbuf->flags |= _Py_MANAGED_BUFFER_FREE_FORMAT;
1000
0
    }
1001
1002
0
    return 0;
1003
0
}
1004
1005
/*
1006
   Return a memoryview that is based on a contiguous copy of src.
1007
   Assumptions: src has PyBUF_FULL_RO information, src->ndim > 0.
1008
1009
   Ownership rules:
1010
     1) As usual, the returned memoryview has a private copy
1011
        of src->shape, src->strides and src->suboffsets.
1012
     2) src->format is copied to the master buffer and released
1013
        in mbuf_dealloc(). The releasebufferproc of the bytes
1014
        object is NULL, so it does not matter that mbuf_release()
1015
        passes the altered format pointer to PyBuffer_Release().
1016
*/
1017
static PyObject *
1018
memory_from_contiguous_copy(const Py_buffer *src, char order)
1019
0
{
1020
0
    _PyManagedBufferObject *mbuf;
1021
0
    PyMemoryViewObject *mv;
1022
0
    PyObject *bytes;
1023
0
    Py_buffer *dest;
1024
0
    int i;
1025
1026
0
    assert(src->ndim > 0);
1027
0
    assert(src->shape != NULL);
1028
1029
0
    bytes = PyBytes_FromStringAndSize(NULL, src->len);
1030
0
    if (bytes == NULL)
1031
0
        return NULL;
1032
1033
0
    mbuf = (_PyManagedBufferObject *)_PyManagedBuffer_FromObject(bytes, PyBUF_FULL_RO);
1034
0
    Py_DECREF(bytes);
1035
0
    if (mbuf == NULL)
1036
0
        return NULL;
1037
1038
0
    if (mbuf_copy_format(mbuf, src->format) < 0) {
1039
0
        Py_DECREF(mbuf);
1040
0
        return NULL;
1041
0
    }
1042
1043
0
    mv = (PyMemoryViewObject *)mbuf_add_incomplete_view(mbuf, NULL, src->ndim);
1044
0
    Py_DECREF(mbuf);
1045
0
    if (mv == NULL)
1046
0
        return NULL;
1047
1048
0
    dest = &mv->view;
1049
1050
    /* shared values are initialized correctly except for itemsize */
1051
0
    dest->itemsize = src->itemsize;
1052
1053
    /* shape and strides */
1054
0
    for (i = 0; i < src->ndim; i++) {
1055
0
        dest->shape[i] = src->shape[i];
1056
0
    }
1057
0
    if (order == 'C' || order == 'A') {
1058
0
        init_strides_from_shape(dest);
1059
0
    }
1060
0
    else {
1061
0
        init_fortran_strides_from_shape(dest);
1062
0
    }
1063
    /* suboffsets */
1064
0
    dest->suboffsets = NULL;
1065
1066
    /* flags */
1067
0
    init_flags(mv);
1068
1069
0
    if (copy_buffer(dest, src) < 0) {
1070
0
        Py_DECREF(mv);
1071
0
        return NULL;
1072
0
    }
1073
1074
0
    return (PyObject *)mv;
1075
0
}
1076
1077
/*
1078
   Return a new memoryview object based on a contiguous exporter with
1079
   buffertype={PyBUF_READ, PyBUF_WRITE} and order={'C', 'F'ortran, or 'A'ny}.
1080
   The logical structure of the input and output buffers is the same
1081
   (i.e. tolist(input) == tolist(output)), but the physical layout in
1082
   memory can be explicitly chosen.
1083
1084
   As usual, if buffertype=PyBUF_WRITE, the exporter's buffer must be writable,
1085
   otherwise it may be writable or read-only.
1086
1087
   If the exporter is already contiguous with the desired target order,
1088
   the memoryview will be directly based on the exporter.
1089
1090
   Otherwise, if the buffertype is PyBUF_READ, the memoryview will be
1091
   based on a new bytes object. If order={'C', 'A'ny}, use 'C' order,
1092
   'F'ortran order otherwise.
1093
*/
1094
PyObject *
1095
PyMemoryView_GetContiguous(PyObject *obj, int buffertype, char order)
1096
0
{
1097
0
    PyMemoryViewObject *mv;
1098
0
    PyObject *ret;
1099
0
    Py_buffer *view;
1100
1101
0
    assert(buffertype == PyBUF_READ || buffertype == PyBUF_WRITE);
1102
0
    assert(order == 'C' || order == 'F' || order == 'A');
1103
1104
0
    mv = (PyMemoryViewObject *)PyMemoryView_FromObject(obj);
1105
0
    if (mv == NULL)
1106
0
        return NULL;
1107
1108
0
    view = &mv->view;
1109
0
    if (buffertype == PyBUF_WRITE && view->readonly) {
1110
0
        PyErr_SetString(PyExc_BufferError,
1111
0
            "underlying buffer is not writable");
1112
0
        Py_DECREF(mv);
1113
0
        return NULL;
1114
0
    }
1115
1116
0
    if (PyBuffer_IsContiguous(view, order))
1117
0
        return (PyObject *)mv;
1118
1119
0
    if (buffertype == PyBUF_WRITE) {
1120
0
        PyErr_SetString(PyExc_BufferError,
1121
0
            "writable contiguous buffer requested "
1122
0
            "for a non-contiguous object.");
1123
0
        Py_DECREF(mv);
1124
0
        return NULL;
1125
0
    }
1126
1127
0
    ret = memory_from_contiguous_copy(view, order);
1128
0
    Py_DECREF(mv);
1129
0
    return ret;
1130
0
}
1131
1132
1133
/*[clinic input]
1134
@vectorcall
1135
@classmethod
1136
memoryview.__new__
1137
1138
    object: object
1139
1140
Create a new memoryview object which references the given object.
1141
[clinic start generated code]*/
1142
1143
static PyObject *
1144
memoryview_impl(PyTypeObject *type, PyObject *object)
1145
/*[clinic end generated code: output=7de78e184ed66db8 input=8e10a66aebe8e657]*/
1146
115k
{
1147
115k
    return PyMemoryView_FromObject(object);
1148
115k
}
1149
1150
1151
/*[clinic input]
1152
@classmethod
1153
memoryview._from_flags
1154
1155
    object: object
1156
    flags: int
1157
1158
Create a new memoryview object which references the given object.
1159
[clinic start generated code]*/
1160
1161
static PyObject *
1162
memoryview__from_flags_impl(PyTypeObject *type, PyObject *object, int flags)
1163
/*[clinic end generated code: output=bf71f9906c266ee2 input=f5f82fd0e744356b]*/
1164
0
{
1165
0
    return PyMemoryView_FromObjectAndFlags(object, flags);
1166
0
}
1167
1168
1169
/****************************************************************************/
1170
/*                         Previously in abstract.c                         */
1171
/****************************************************************************/
1172
1173
typedef struct {
1174
    Py_buffer view;
1175
    Py_ssize_t array[1];
1176
} Py_buffer_full;
1177
1178
int
1179
PyBuffer_ToContiguous(void *buf, const Py_buffer *src, Py_ssize_t len, char order)
1180
42.3M
{
1181
42.3M
    Py_buffer_full *fb = NULL;
1182
42.3M
    int ret;
1183
1184
42.3M
    assert(order == 'C' || order == 'F' || order == 'A');
1185
1186
42.3M
    if (len != src->len) {
1187
0
        PyErr_SetString(PyExc_ValueError,
1188
0
            "PyBuffer_ToContiguous: len != view->len");
1189
0
        return -1;
1190
0
    }
1191
1192
42.3M
    if (PyBuffer_IsContiguous(src, order)) {
1193
42.3M
        memcpy((char *)buf, src->buf, len);
1194
42.3M
        return 0;
1195
42.3M
    }
1196
1197
    /* buffer_to_contiguous() assumes PyBUF_FULL */
1198
0
    fb = PyMem_Malloc(sizeof *fb + 3 * src->ndim * (sizeof *fb->array));
1199
0
    if (fb == NULL) {
1200
0
        PyErr_NoMemory();
1201
0
        return -1;
1202
0
    }
1203
0
    fb->view.ndim = src->ndim;
1204
0
    fb->view.shape = fb->array;
1205
0
    fb->view.strides = fb->array + src->ndim;
1206
0
    fb->view.suboffsets = fb->array + 2 * src->ndim;
1207
1208
0
    init_shared_values(&fb->view, src);
1209
0
    init_shape_strides(&fb->view, src);
1210
0
    init_suboffsets(&fb->view, src);
1211
1212
0
    src = &fb->view;
1213
1214
0
    ret = buffer_to_contiguous(buf, src, order);
1215
0
    PyMem_Free(fb);
1216
0
    return ret;
1217
0
}
1218
1219
static inline Py_ssize_t
1220
get_exports(PyMemoryViewObject *buf)
1221
107k
{
1222
107k
    return FT_ATOMIC_LOAD_SSIZE_RELAXED(buf->exports);
1223
107k
}
1224
1225
1226
/****************************************************************************/
1227
/*                           Release/GC management                          */
1228
/****************************************************************************/
1229
1230
/* Inform the managed buffer that this particular memoryview will not access
1231
   the underlying buffer again. If no other memoryviews are registered with
1232
   the managed buffer, the underlying buffer is released instantly and
1233
   marked as inaccessible for both the memoryview and the managed buffer. */
1234
static void
1235
_memory_release(PyMemoryViewObject *self)
1236
3.28M
{
1237
3.28M
    assert(get_exports(self) == 0);
1238
3.28M
    if (mv_set_released(self)) {
1239
107k
        return;
1240
107k
    }
1241
1242
3.18M
    mbuf_drop_export(self->mbuf);
1243
3.18M
}
1244
1245
/*[clinic input]
1246
memoryview.release
1247
1248
Release the underlying buffer exposed by the memoryview object.
1249
[clinic start generated code]*/
1250
1251
static PyObject *
1252
memoryview_release_impl(PyMemoryViewObject *self)
1253
/*[clinic end generated code: output=d0b7e3ba95b7fcb9 input=bc71d1d51f4a52f0]*/
1254
107k
{
1255
107k
    PyObject *result = NULL;
1256
1257
107k
    Py_BEGIN_CRITICAL_SECTION(self);
1258
107k
    Py_ssize_t exports = get_exports(self);
1259
107k
    if (exports == 0) {
1260
107k
        _memory_release(self);
1261
107k
        result = Py_None;
1262
107k
    }
1263
0
    else if (exports > 0) {
1264
0
        PyErr_Format(PyExc_BufferError,
1265
0
            "memoryview has %zd exported buffer%s", exports,
1266
0
            exports == 1 ? "" : "s");
1267
0
    }
1268
0
    else {
1269
0
        PyErr_SetString(PyExc_SystemError,
1270
0
                        "memoryview: negative export count");
1271
0
    }
1272
107k
    Py_END_CRITICAL_SECTION();
1273
1274
107k
    return result;
1275
107k
}
1276
1277
static void
1278
memory_dealloc(PyObject *_self)
1279
3.18M
{
1280
3.18M
    PyMemoryViewObject *self = (PyMemoryViewObject *)_self;
1281
3.18M
    assert(get_exports(self) == 0);
1282
3.18M
    _PyObject_GC_UNTRACK(self);
1283
3.18M
    _memory_release(self);
1284
3.18M
    Py_CLEAR(self->mbuf);
1285
3.18M
    if (self->weakreflist != NULL)
1286
0
        PyObject_ClearWeakRefs((PyObject *) self);
1287
3.18M
    PyObject_GC_Del(self);
1288
3.18M
}
1289
1290
static int
1291
memory_traverse(PyObject *_self, visitproc visit, void *arg)
1292
796
{
1293
796
    PyMemoryViewObject *self = (PyMemoryViewObject *)_self;
1294
796
    Py_VISIT(self->mbuf);
1295
796
    return 0;
1296
796
}
1297
1298
static int
1299
memory_clear(PyObject *_self)
1300
0
{
1301
0
    PyMemoryViewObject *self = (PyMemoryViewObject *)_self;
1302
0
    if (get_exports(self) == 0) {
1303
0
        _memory_release(self);
1304
0
    }
1305
    /* Keep the reference to self->mbuf until memory_dealloc(): an operation
1306
       that pinned the managed buffer may still be running (see
1307
       memoryview_pin()), and mbuf_clear() already breaks the managed
1308
       buffer's own reference cycle through the exporter. */
1309
0
    return 0;
1310
0
}
1311
1312
static PyObject *
1313
memory_enter(PyObject *self, PyObject *args)
1314
107k
{
1315
107k
    CHECK_RELEASED(self);
1316
107k
    return Py_NewRef(self);
1317
107k
}
1318
1319
/*[clinic input]
1320
memoryview.__exit__
1321
1322
    *exc_info: array
1323
1324
Release the underlying buffer exposed by the memoryview object.
1325
[clinic start generated code]*/
1326
1327
static PyObject *
1328
memoryview___exit___impl(PyMemoryViewObject *self,
1329
                         PyObject * const *exc_info,
1330
                         Py_ssize_t exc_info_length)
1331
/*[clinic end generated code: output=c055c4c69baf495d input=881969146ff4d413]*/
1332
107k
{
1333
107k
    return memoryview_release_impl(self);
1334
107k
}
1335
1336
1337
/****************************************************************************/
1338
/*                         Casting format and shape                         */
1339
/****************************************************************************/
1340
1341
#define IS_BYTE_FORMAT(f) \
1342
114k
    (strcmp(f, "b") == 0 || strcmp(f, "B") == 0 || strcmp(f, "c") == 0)
1343
1344
static inline Py_ssize_t
1345
get_native_fmtchar(const char **result, const char *fmt)
1346
228k
{
1347
228k
    Py_ssize_t size = -1;
1348
1349
228k
    if (fmt[0] == '@') fmt++;
1350
1351
228k
    switch (fmt[0]) {
1352
167k
    case 'c': case 'b': case 'B': size = sizeof(char); break;
1353
0
    case 'h': case 'H': size = sizeof(short); break;
1354
60.3k
    case 'i': case 'I': size = sizeof(int); break;
1355
0
    case 'l': case 'L': size = sizeof(long); break;
1356
0
    case 'q': case 'Q': size = sizeof(long long); break;
1357
0
    case 'n': case 'N': size = sizeof(Py_ssize_t); break;
1358
0
    case 'f': size = sizeof(float); break;
1359
0
    case 'd': size = sizeof(double); break;
1360
0
    case 'e': size = sizeof(float) / 2; break;
1361
0
    case '?': size = sizeof(_Bool); break;
1362
0
    case 'P': size = sizeof(void *); break;
1363
0
    case 'Z': {
1364
0
        switch (fmt[1]) {
1365
0
            case 'f': size = 2*sizeof(float); break;
1366
0
            case 'd': size = 2*sizeof(double); break;
1367
0
        }
1368
0
        if (size > 0 && fmt[2] == '\0') {
1369
0
            *result = fmt;
1370
0
            return size;
1371
0
        }
1372
0
        break;
1373
0
    }
1374
228k
    }
1375
1376
228k
    if (size > 0 && fmt[1] == '\0') {
1377
228k
        *result = fmt;
1378
228k
        return size;
1379
228k
    }
1380
1381
0
    return -1;
1382
228k
}
1383
1384
static inline const char *
1385
get_native_fmtstr(const char *fmt)
1386
114k
{
1387
114k
    int at = 0;
1388
1389
114k
    if (fmt[0] == '@') {
1390
0
        at = 1;
1391
0
        fmt++;
1392
0
    }
1393
114k
    if (fmt[0] == '\0') {
1394
0
        return NULL;
1395
0
    }
1396
114k
    if (fmt[0] == 'Z') {
1397
0
        if (fmt[1] == '\0' || fmt[2] != '\0') {
1398
0
            return NULL;
1399
0
        }
1400
0
    }
1401
114k
    else {
1402
114k
        if (fmt[1] != '\0') {
1403
0
            return NULL;
1404
0
        }
1405
114k
    }
1406
1407
114k
#define RETURN(s) do { return at ? "@" s : s; } while (0)
1408
1409
114k
    switch (fmt[0]) {
1410
0
    case 'c': RETURN("c");
1411
0
    case 'b': RETURN("b");
1412
53.7k
    case 'B': RETURN("B");
1413
0
    case 'h': RETURN("h");
1414
0
    case 'H': RETURN("H");
1415
0
    case 'i': RETURN("i");
1416
60.3k
    case 'I': RETURN("I");
1417
0
    case 'l': RETURN("l");
1418
0
    case 'L': RETURN("L");
1419
0
    case 'q': RETURN("q");
1420
0
    case 'Q': RETURN("Q");
1421
0
    case 'n': RETURN("n");
1422
0
    case 'N': RETURN("N");
1423
0
    case 'f': RETURN("f");
1424
0
    case 'd': RETURN("d");
1425
0
    case 'e': RETURN("e");
1426
0
    case 'Z': {
1427
0
        switch (fmt[1]) {
1428
0
        case 'f': RETURN("Zf");
1429
0
        case 'd': RETURN("Zd");
1430
0
        }
1431
0
        break;
1432
0
    }
1433
0
    case '?': RETURN("?");
1434
0
    case 'P': RETURN("P");
1435
114k
    }
1436
1437
0
    return NULL;
1438
114k
}
1439
1440
1441
/* Cast a memoryview's data type to 'format'. The input array must be
1442
   C-contiguous. At least one of input-format, output-format must have
1443
   byte size. The output array is 1-D, with the same byte length as the
1444
   input array. Thus, view->len must be a multiple of the new itemsize. */
1445
static int
1446
cast_to_1D(PyMemoryViewObject *mv, PyObject *format)
1447
114k
{
1448
114k
    Py_buffer *view = &mv->view;
1449
114k
    PyObject *asciifmt;
1450
114k
    const char *srcfmt, *destfmt;
1451
114k
    Py_ssize_t itemsize;
1452
114k
    int ret = -1;
1453
1454
114k
    assert(view->ndim >= 1);
1455
114k
    assert(Py_SIZE(mv) == 3*view->ndim);
1456
114k
    assert(view->shape == mv->ob_array);
1457
114k
    assert(view->strides == mv->ob_array + view->ndim);
1458
114k
    assert(view->suboffsets == mv->ob_array + 2*view->ndim);
1459
1460
114k
    asciifmt = PyUnicode_AsASCIIString(format);
1461
114k
    if (asciifmt == NULL)
1462
0
        return ret;
1463
1464
114k
    itemsize = get_native_fmtchar(&destfmt, PyBytes_AS_STRING(asciifmt));
1465
114k
    if (itemsize < 0) {
1466
0
        PyErr_SetString(PyExc_ValueError,
1467
0
            "memoryview: destination format must be a native "
1468
0
            "format prefixed with an optional '@'");
1469
0
        goto out;
1470
0
    }
1471
1472
114k
    if ((get_native_fmtchar(&srcfmt, view->format) < 0 ||
1473
114k
         !IS_BYTE_FORMAT(srcfmt)) && !IS_BYTE_FORMAT(destfmt)) {
1474
0
        PyErr_SetString(PyExc_TypeError,
1475
0
            "memoryview: cannot cast between two non-byte formats");
1476
0
        goto out;
1477
0
    }
1478
114k
    if (view->len % itemsize) {
1479
0
        PyErr_SetString(PyExc_TypeError,
1480
0
            "memoryview: length is not a multiple of itemsize");
1481
0
        goto out;
1482
0
    }
1483
1484
114k
    view->format = (char *)get_native_fmtstr(PyBytes_AS_STRING(asciifmt));
1485
114k
    if (view->format == NULL) {
1486
        /* NOT_REACHED: get_native_fmtchar() already validates the format. */
1487
0
        PyErr_SetString(PyExc_RuntimeError,
1488
0
            "memoryview: internal error");
1489
0
        goto out;
1490
0
    }
1491
114k
    view->itemsize = itemsize;
1492
1493
114k
    view->ndim = 1;
1494
114k
    view->shape[0] = view->len / view->itemsize;
1495
114k
    view->strides[0] = view->itemsize;
1496
114k
    view->suboffsets = NULL;
1497
1498
114k
    init_flags(mv);
1499
1500
114k
    ret = 0;
1501
1502
114k
out:
1503
114k
    Py_DECREF(asciifmt);
1504
114k
    return ret;
1505
114k
}
1506
1507
/* The memoryview must have space for 3*len(seq) elements. */
1508
static Py_ssize_t
1509
copy_shape(Py_ssize_t *shape, const PyObject *seq, Py_ssize_t ndim,
1510
           Py_ssize_t itemsize)
1511
0
{
1512
0
    Py_ssize_t x, i;
1513
0
    Py_ssize_t len = itemsize;
1514
1515
0
    for (i = 0; i < ndim; i++) {
1516
0
        PyObject *tmp = PySequence_Fast_GET_ITEM(seq, i);
1517
0
        if (!PyLong_Check(tmp)) {
1518
0
            PyErr_SetString(PyExc_TypeError,
1519
0
                "memoryview.cast(): elements of shape must be integers");
1520
0
            return -1;
1521
0
        }
1522
0
        x = PyLong_AsSsize_t(tmp);
1523
0
        if (x == -1 && PyErr_Occurred()) {
1524
0
            return -1;
1525
0
        }
1526
0
        if (x <= 0) {
1527
            /* In general elements of shape may be 0, but not for casting. */
1528
0
            PyErr_Format(PyExc_ValueError,
1529
0
                "memoryview.cast(): elements of shape must be integers > 0");
1530
0
            return -1;
1531
0
        }
1532
0
        if (x > PY_SSIZE_T_MAX / len) {
1533
0
            PyErr_Format(PyExc_ValueError,
1534
0
                "memoryview.cast(): product(shape) > SSIZE_MAX");
1535
0
            return -1;
1536
0
        }
1537
0
        len *= x;
1538
0
        shape[i] = x;
1539
0
    }
1540
1541
0
    return len;
1542
0
}
1543
1544
/* Cast a 1-D array to a new shape. The result array will be C-contiguous
1545
   ('C') or Fortran-contiguous ('F') according to 'order'.  If the result
1546
   array does not have exactly the same byte length as the input array, raise
1547
   TypeError. */
1548
static int
1549
cast_to_ND(PyMemoryViewObject *mv, const PyObject *shape, int ndim, char order)
1550
0
{
1551
0
    Py_buffer *view = &mv->view;
1552
0
    Py_ssize_t len;
1553
1554
0
    assert(view->ndim == 1); /* ndim from cast_to_1D() */
1555
0
    assert(Py_SIZE(mv) == 3*(ndim==0?1:ndim)); /* ndim of result array */
1556
0
    assert(view->shape == mv->ob_array);
1557
0
    assert(view->strides == mv->ob_array + (ndim==0?1:ndim));
1558
0
    assert(view->suboffsets == NULL);
1559
1560
0
    view->ndim = ndim;
1561
0
    if (view->ndim == 0) {
1562
0
        view->shape = NULL;
1563
0
        view->strides = NULL;
1564
0
        len = view->itemsize;
1565
0
    }
1566
0
    else {
1567
0
        len = copy_shape(view->shape, shape, ndim, view->itemsize);
1568
0
        if (len < 0)
1569
0
            return -1;
1570
0
        if (order == 'F')
1571
0
            init_fortran_strides_from_shape(view);
1572
0
        else
1573
0
            init_strides_from_shape(view);
1574
0
    }
1575
1576
0
    if (view->len != len) {
1577
0
        PyErr_SetString(PyExc_TypeError,
1578
0
            "memoryview: product(shape) * itemsize != buffer size");
1579
0
        return -1;
1580
0
    }
1581
1582
0
    init_flags(mv);
1583
1584
0
    return 0;
1585
0
}
1586
1587
static int
1588
zero_in_shape(PyMemoryViewObject *mv)
1589
0
{
1590
0
    Py_buffer *view = &mv->view;
1591
0
    Py_ssize_t i;
1592
1593
0
    for (i = 0; i < view->ndim; i++)
1594
0
        if (view->shape[i] == 0)
1595
0
            return 1;
1596
1597
0
    return 0;
1598
0
}
1599
1600
/*
1601
   Cast a copy of 'self' to a different view. The input view must
1602
   be C-contiguous. The function always casts the input view to a
1603
   1-D output according to 'format'. At least one of input-format,
1604
   output-format must have byte size.
1605
1606
   If 'shape' is given, the 1-D view from the previous step will
1607
   be cast to a C-contiguous view with new shape and strides.
1608
1609
   All casts must result in views that will have the exact byte
1610
   size of the original input. Otherwise, an error is raised.
1611
*/
1612
static PyObject *
1613
memoryview_cast_pinned(PyMemoryViewObject *self, PyObject *format,
1614
                     PyObject *shape, int order)
1615
114k
{
1616
114k
    PyMemoryViewObject *mv = NULL;
1617
114k
    Py_ssize_t ndim = 1;
1618
1619
114k
    CHECK_RELEASED(self);
1620
114k
    CHECK_RESTRICTED(self);
1621
1622
114k
    if (order != 'C' && order != 'F') {
1623
0
        PyErr_SetString(PyExc_ValueError, "order must be 'C' or 'F'");
1624
0
        return NULL;
1625
0
    }
1626
1627
114k
    int self_flags = mv_get_flags(self);
1628
114k
    if (!MV_C_CONTIGUOUS(self_flags)) {
1629
0
        if (shape || !MV_F_CONTIGUOUS(self_flags)) {
1630
0
            PyErr_SetString(PyExc_TypeError,
1631
0
                "memoryview: casts are restricted to contiguous views");
1632
0
            return NULL;
1633
0
        }
1634
0
    }
1635
114k
    if ((shape || self->view.ndim != 1) && zero_in_shape(self)) {
1636
0
        PyErr_SetString(PyExc_TypeError,
1637
0
            "memoryview: cannot cast view with zeros in shape or strides");
1638
0
        return NULL;
1639
0
    }
1640
114k
    if (shape) {
1641
0
        CHECK_LIST_OR_TUPLE(shape)
1642
0
        ndim = PySequence_Fast_GET_SIZE(shape);
1643
0
        if (ndim > PyBUF_MAX_NDIM) {
1644
0
            PyErr_SetString(PyExc_ValueError,
1645
0
                "memoryview: number of dimensions must not exceed "
1646
0
                Py_STRINGIFY(PyBUF_MAX_NDIM));
1647
0
            return NULL;
1648
0
        }
1649
0
        if (self->view.ndim != 1 && ndim != 1) {
1650
0
            PyErr_SetString(PyExc_TypeError,
1651
0
                "memoryview: cast must be 1D -> ND or ND -> 1D");
1652
0
            return NULL;
1653
0
        }
1654
0
    }
1655
1656
114k
    mv = (PyMemoryViewObject *)
1657
114k
        mbuf_add_incomplete_view(self->mbuf, &self->view, ndim==0 ? 1 : (int)ndim);
1658
114k
    if (mv == NULL)
1659
0
        return NULL;
1660
1661
114k
    if (cast_to_1D(mv, format) < 0)
1662
0
        goto error;
1663
114k
    if (shape && cast_to_ND(mv, shape, (int)ndim, (char)order) < 0)
1664
0
        goto error;
1665
1666
114k
    return (PyObject *)mv;
1667
1668
0
error:
1669
0
    Py_DECREF(mv);
1670
0
    return NULL;
1671
114k
}
1672
1673
/*[clinic input]
1674
memoryview.cast
1675
1676
    format: unicode
1677
    shape: object = NULL
1678
    *
1679
    order: int(accept={str}) = 'C'
1680
1681
Cast a memoryview to a new format or shape.
1682
1683
With a multidimensional *shape*, *order* selects the result
1684
layout: 'C' for C-contiguous (row-major, the default) or 'F'
1685
for Fortran-contiguous (column-major).
1686
[clinic start generated code]*/
1687
1688
static PyObject *
1689
memoryview_cast_impl(PyMemoryViewObject *self, PyObject *format,
1690
                     PyObject *shape, int order)
1691
/*[clinic end generated code: output=6410d87141f6bb56 input=4a1a2326c59caeb3]*/
1692
114k
{
1693
114k
    if (memoryview_pin(self) < 0) {
1694
0
        return NULL;
1695
0
    }
1696
114k
    PyObject *result = memoryview_cast_pinned(self, format, shape, order);
1697
114k
    memoryview_unpin(self);
1698
114k
    return result;
1699
114k
}
1700
1701
static PyObject *
1702
memoryview_toreadonly_pinned(PyMemoryViewObject *self)
1703
0
{
1704
0
    CHECK_RELEASED(self);
1705
0
    CHECK_RESTRICTED(self);
1706
    /* Even if self is already readonly, we still need to create a new
1707
     * object for .release() to work correctly.
1708
     */
1709
0
    self = (PyMemoryViewObject *) mbuf_add_view(self->mbuf, &self->view);
1710
0
    if (self != NULL) {
1711
0
        self->view.readonly = 1;
1712
0
    };
1713
0
    return (PyObject *) self;
1714
0
}
1715
1716
/*[clinic input]
1717
memoryview.toreadonly
1718
1719
Return a readonly version of the memoryview.
1720
[clinic start generated code]*/
1721
1722
static PyObject *
1723
memoryview_toreadonly_impl(PyMemoryViewObject *self)
1724
/*[clinic end generated code: output=2c7e056f04c99e62 input=dc06d20f19ba236f]*/
1725
0
{
1726
0
    if (memoryview_pin(self) < 0) {
1727
0
        return NULL;
1728
0
    }
1729
0
    PyObject *result = memoryview_toreadonly_pinned(self);
1730
0
    memoryview_unpin(self);
1731
0
    return result;
1732
0
}
1733
1734
1735
/**************************************************************************/
1736
/*                               getbuffer                                */
1737
/**************************************************************************/
1738
1739
static int
1740
memory_getbuf(PyObject *_self, Py_buffer *view, int flags)
1741
2.88M
{
1742
2.88M
    PyMemoryViewObject *self = (PyMemoryViewObject *)_self;
1743
2.88M
    Py_buffer *base = &self->view;
1744
2.88M
    int baseflags = mv_get_flags(self);
1745
1746
2.88M
    CHECK_RELEASED_INT(self);
1747
2.88M
    CHECK_RESTRICTED_INT(self);
1748
1749
    /* start with complete information */
1750
2.88M
    *view = *base;
1751
2.88M
    view->obj = NULL;
1752
1753
2.88M
    if (REQ_WRITABLE(flags) && base->readonly) {
1754
0
        PyErr_SetString(PyExc_BufferError,
1755
0
            "memoryview: underlying buffer is not writable");
1756
0
        return -1;
1757
0
    }
1758
2.88M
    if (!REQ_FORMAT(flags)) {
1759
        /* NULL indicates that the buffer's data type has been cast to 'B'.
1760
           view->itemsize is the _previous_ itemsize. If shape is present,
1761
           the equality product(shape) * itemsize = len still holds at this
1762
           point. The equality calcsize(format) = itemsize does _not_ hold
1763
           from here on! */
1764
1.56M
        view->format = NULL;
1765
1.56M
    }
1766
1767
2.88M
    if (REQ_C_CONTIGUOUS(flags) && !MV_C_CONTIGUOUS(baseflags)) {
1768
0
        PyErr_SetString(PyExc_BufferError,
1769
0
            "memoryview: underlying buffer is not C-contiguous");
1770
0
        return -1;
1771
0
    }
1772
2.88M
    if (REQ_F_CONTIGUOUS(flags) && !MV_F_CONTIGUOUS(baseflags)) {
1773
0
        PyErr_SetString(PyExc_BufferError,
1774
0
            "memoryview: underlying buffer is not Fortran contiguous");
1775
0
        return -1;
1776
0
    }
1777
2.88M
    if (REQ_ANY_CONTIGUOUS(flags) && !MV_ANY_CONTIGUOUS(baseflags)) {
1778
0
        PyErr_SetString(PyExc_BufferError,
1779
0
            "memoryview: underlying buffer is not contiguous");
1780
0
        return -1;
1781
0
    }
1782
2.88M
    if (!REQ_INDIRECT(flags) && (baseflags & _Py_MEMORYVIEW_PIL)) {
1783
0
        PyErr_SetString(PyExc_BufferError,
1784
0
            "memoryview: underlying buffer requires suboffsets");
1785
0
        return -1;
1786
0
    }
1787
2.88M
    if (!REQ_STRIDES(flags)) {
1788
1.56M
        if (!MV_C_CONTIGUOUS(baseflags)) {
1789
0
            PyErr_SetString(PyExc_BufferError,
1790
0
                "memoryview: underlying buffer is not C-contiguous");
1791
0
            return -1;
1792
0
        }
1793
1.56M
        view->strides = NULL;
1794
1.56M
    }
1795
2.88M
    if (!REQ_SHAPE(flags)) {
1796
        /* PyBUF_SIMPLE or PyBUF_WRITABLE: at this point buf is C-contiguous,
1797
           so base->buf = ndbuf->data. */
1798
1.56M
        if (view->format != NULL) {
1799
            /* PyBUF_SIMPLE|PyBUF_FORMAT and PyBUF_WRITABLE|PyBUF_FORMAT do
1800
               not make sense. */
1801
0
            PyErr_Format(PyExc_BufferError,
1802
0
                "memoryview: cannot cast to unsigned bytes if the format flag "
1803
0
                "is present");
1804
0
            return -1;
1805
0
        }
1806
        /* product(shape) * itemsize = len and calcsize(format) = itemsize
1807
           do _not_ hold from here on! */
1808
1.56M
        view->ndim = 1;
1809
1.56M
        view->shape = NULL;
1810
1.56M
    }
1811
1812
#ifdef Py_GIL_DISABLED
1813
    /* memoryview_add_export() keeps the buffer alive or fails. */
1814
    if (memoryview_add_export(self) < 0) {
1815
        return -1;
1816
    }
1817
#else
1818
2.88M
    self->exports++;
1819
2.88M
#endif
1820
1821
2.88M
    view->obj = Py_NewRef(self);
1822
2.88M
    return 0;
1823
2.88M
}
1824
1825
static void
1826
memory_releasebuf(PyObject *_self, Py_buffer *view)
1827
2.88M
{
1828
2.88M
    PyMemoryViewObject *self = (PyMemoryViewObject *)_self;
1829
2.88M
    FT_ATOMIC_ADD_SSIZE(self->exports, -1);
1830
2.88M
    return;
1831
    /* PyBuffer_Release() decrements view->obj after this function returns. */
1832
2.88M
}
1833
1834
/* Buffer methods */
1835
static PyBufferProcs memory_as_buffer = {
1836
    memory_getbuf,         /* bf_getbuffer */
1837
    memory_releasebuf,                    /* bf_releasebuffer */
1838
};
1839
1840
1841
/****************************************************************************/
1842
/*           Optimized pack/unpack for all native format specifiers         */
1843
/****************************************************************************/
1844
1845
/*
1846
  Fix exceptions:
1847
     1) Include format string in the error message.
1848
     2) OverflowError -> ValueError.
1849
     3) The error message from PyNumber_Index() is not ideal.
1850
*/
1851
static int
1852
type_error_int(const char *fmt)
1853
0
{
1854
0
    PyErr_Format(PyExc_TypeError,
1855
0
        "memoryview: invalid type for format '%s'", fmt);
1856
0
    return -1;
1857
0
}
1858
1859
static int
1860
value_error_int(const char *fmt)
1861
0
{
1862
0
    PyErr_Format(PyExc_ValueError,
1863
0
        "memoryview: invalid value for format '%s'", fmt);
1864
0
    return -1;
1865
0
}
1866
1867
static int
1868
fix_error_int(const char *fmt)
1869
0
{
1870
0
    assert(PyErr_Occurred());
1871
0
    if (PyErr_ExceptionMatches(PyExc_TypeError)) {
1872
0
        PyErr_Clear();
1873
0
        return type_error_int(fmt);
1874
0
    }
1875
0
    else if (PyErr_ExceptionMatches(PyExc_OverflowError) ||
1876
0
             PyErr_ExceptionMatches(PyExc_ValueError)) {
1877
0
        PyErr_Clear();
1878
0
        return value_error_int(fmt);
1879
0
    }
1880
1881
0
    return -1;
1882
0
}
1883
1884
// UNPACK_TO_BOOL: Return 0 if PTR represents "false", and 1 otherwise.
1885
static const _Bool bool_false = 0;
1886
0
#define UNPACK_TO_BOOL(PTR) (memcmp((PTR), &bool_false, sizeof(_Bool)) != 0)
1887
1888
/* Accept integer objects or objects with an __index__() method. */
1889
static long
1890
pylong_as_ld(PyObject *item)
1891
0
{
1892
0
    PyObject *tmp;
1893
0
    long ld;
1894
1895
0
    tmp = _PyNumber_Index(item);
1896
0
    if (tmp == NULL)
1897
0
        return -1;
1898
1899
0
    ld = PyLong_AsLong(tmp);
1900
0
    Py_DECREF(tmp);
1901
0
    return ld;
1902
0
}
1903
1904
static unsigned long
1905
pylong_as_lu(PyObject *item)
1906
0
{
1907
0
    PyObject *tmp;
1908
0
    unsigned long lu;
1909
1910
0
    tmp = _PyNumber_Index(item);
1911
0
    if (tmp == NULL)
1912
0
        return (unsigned long)-1;
1913
1914
0
    lu = PyLong_AsUnsignedLong(tmp);
1915
0
    Py_DECREF(tmp);
1916
0
    return lu;
1917
0
}
1918
1919
static long long
1920
pylong_as_lld(PyObject *item)
1921
0
{
1922
0
    PyObject *tmp;
1923
0
    long long lld;
1924
1925
0
    tmp = _PyNumber_Index(item);
1926
0
    if (tmp == NULL)
1927
0
        return -1;
1928
1929
0
    lld = PyLong_AsLongLong(tmp);
1930
0
    Py_DECREF(tmp);
1931
0
    return lld;
1932
0
}
1933
1934
static unsigned long long
1935
pylong_as_llu(PyObject *item)
1936
0
{
1937
0
    PyObject *tmp;
1938
0
    unsigned long long llu;
1939
1940
0
    tmp = _PyNumber_Index(item);
1941
0
    if (tmp == NULL)
1942
0
        return (unsigned long long)-1;
1943
1944
0
    llu = PyLong_AsUnsignedLongLong(tmp);
1945
0
    Py_DECREF(tmp);
1946
0
    return llu;
1947
0
}
1948
1949
static Py_ssize_t
1950
pylong_as_zd(PyObject *item)
1951
0
{
1952
0
    PyObject *tmp;
1953
0
    Py_ssize_t zd;
1954
1955
0
    tmp = _PyNumber_Index(item);
1956
0
    if (tmp == NULL)
1957
0
        return -1;
1958
1959
0
    zd = PyLong_AsSsize_t(tmp);
1960
0
    Py_DECREF(tmp);
1961
0
    return zd;
1962
0
}
1963
1964
static size_t
1965
pylong_as_zu(PyObject *item)
1966
0
{
1967
0
    PyObject *tmp;
1968
0
    size_t zu;
1969
1970
0
    tmp = _PyNumber_Index(item);
1971
0
    if (tmp == NULL)
1972
0
        return (size_t)-1;
1973
1974
0
    zu = PyLong_AsSize_t(tmp);
1975
0
    Py_DECREF(tmp);
1976
0
    return zu;
1977
0
}
1978
1979
/* Timings with the ndarray from _testbuffer.c indicate that using the
1980
   struct module is around 15x slower than the two functions below. */
1981
1982
#define UNPACK_SINGLE(dest, ptr, type) \
1983
3.86M
    do {                                   \
1984
3.86M
        type x;                            \
1985
3.86M
        memcpy((char *)&x, ptr, sizeof x); \
1986
3.86M
        dest = x;                          \
1987
3.86M
    } while (0)
1988
1989
/* Unpack a single item. 'fmt' can be any native format in struct
1990
   module syntax. This function is very sensitive to small changes. With this
1991
   layout gcc automatically generates a fast jump table. */
1992
static inline PyObject *
1993
unpack_single(PyMemoryViewObject *self, const char *ptr, const char *fmt)
1994
3.86M
{
1995
3.86M
    unsigned long long llu;
1996
3.86M
    unsigned long lu;
1997
3.86M
    size_t zu;
1998
3.86M
    long long lld;
1999
3.86M
    long ld;
2000
3.86M
    Py_ssize_t zd;
2001
3.86M
    double d[2];
2002
3.86M
    unsigned char uc;
2003
3.86M
    void *p;
2004
2005
3.86M
    CHECK_RELEASED_AGAIN(self);
2006
2007
3.86M
#if PY_LITTLE_ENDIAN
2008
3.86M
    int endian = 1;
2009
#else
2010
    int endian = 0;
2011
#endif
2012
2013
3.86M
    switch (fmt[0]) {
2014
2015
    /* signed integers and fast path for 'B' */
2016
0
    case 'B': uc = *((const unsigned char *)ptr); goto convert_uc;
2017
0
    case 'b': ld =   *((const signed char *)ptr); goto convert_ld;
2018
0
    case 'h': UNPACK_SINGLE(ld, ptr, short); goto convert_ld;
2019
0
    case 'i': UNPACK_SINGLE(ld, ptr, int); goto convert_ld;
2020
0
    case 'l': UNPACK_SINGLE(ld, ptr, long); goto convert_ld;
2021
2022
    /* boolean */
2023
0
    case '?': ld = UNPACK_TO_BOOL(ptr); goto convert_bool;
2024
2025
    /* unsigned integers */
2026
0
    case 'H': UNPACK_SINGLE(lu, ptr, unsigned short); goto convert_lu;
2027
3.86M
    case 'I': UNPACK_SINGLE(lu, ptr, unsigned int); goto convert_lu;
2028
0
    case 'L': UNPACK_SINGLE(lu, ptr, unsigned long); goto convert_lu;
2029
2030
    /* native 64-bit */
2031
0
    case 'q': UNPACK_SINGLE(lld, ptr, long long); goto convert_lld;
2032
0
    case 'Q': UNPACK_SINGLE(llu, ptr, unsigned long long); goto convert_llu;
2033
2034
    /* ssize_t and size_t */
2035
0
    case 'n': UNPACK_SINGLE(zd, ptr, Py_ssize_t); goto convert_zd;
2036
0
    case 'N': UNPACK_SINGLE(zu, ptr, size_t); goto convert_zu;
2037
2038
    /* floats */
2039
0
    case 'f': UNPACK_SINGLE(d[0], ptr, float); goto convert_double;
2040
0
    case 'd': UNPACK_SINGLE(d[0], ptr, double); goto convert_double;
2041
0
    case 'e': d[0] = PyFloat_Unpack2(ptr, endian); goto convert_double;
2042
2043
    /* complexes */
2044
0
    case 'Z': {
2045
0
        switch (fmt[1]) {
2046
0
        case 'f':
2047
0
            d[0] = PyFloat_Unpack4(ptr, endian);
2048
0
            d[1] = PyFloat_Unpack4(ptr + sizeof(float), endian);
2049
0
            goto convert_double_complex;
2050
2051
0
        case 'd':
2052
0
            d[0] = PyFloat_Unpack8(ptr, endian);
2053
0
            d[1] = PyFloat_Unpack8(ptr + sizeof(double), endian);
2054
0
            goto convert_double_complex;
2055
2056
0
        default: goto err_format;
2057
0
        }
2058
0
        break;
2059
0
    }
2060
2061
    /* bytes object */
2062
0
    case 'c': goto convert_bytes;
2063
2064
    /* pointer */
2065
0
    case 'P': UNPACK_SINGLE(p, ptr, void *); goto convert_pointer;
2066
2067
    /* default */
2068
0
    default: goto err_format;
2069
3.86M
    }
2070
2071
0
convert_uc:
2072
    /* PyLong_FromUnsignedLong() is slower */
2073
0
    return PyLong_FromLong(uc);
2074
0
convert_ld:
2075
0
    return PyLong_FromLong(ld);
2076
3.86M
convert_lu:
2077
3.86M
    return PyLong_FromUnsignedLong(lu);
2078
0
convert_lld:
2079
0
    return PyLong_FromLongLong(lld);
2080
0
convert_llu:
2081
0
    return PyLong_FromUnsignedLongLong(llu);
2082
0
convert_zd:
2083
0
    return PyLong_FromSsize_t(zd);
2084
0
convert_zu:
2085
0
    return PyLong_FromSize_t(zu);
2086
0
convert_double:
2087
0
    return PyFloat_FromDouble(d[0]);
2088
0
convert_double_complex:
2089
0
    return PyComplex_FromDoubles(d[0], d[1]);
2090
0
convert_bool:
2091
0
    return PyBool_FromLong(ld);
2092
0
convert_bytes:
2093
0
    return PyBytes_FromStringAndSize(ptr, 1);
2094
0
convert_pointer:
2095
0
    return PyLong_FromVoidPtr(p);
2096
0
err_format:
2097
0
    PyErr_Format(PyExc_NotImplementedError,
2098
0
        "memoryview: format %s not supported", fmt);
2099
0
    return NULL;
2100
3.86M
}
2101
2102
#define PACK_SINGLE(ptr, src, type) \
2103
0
    do {                                     \
2104
0
        type x;                              \
2105
0
        x = (type)src;                       \
2106
0
        memcpy(ptr, (char *)&x, sizeof x);   \
2107
0
    } while (0)
2108
2109
/* Pack a single item. 'fmt' can be any native format in
2110
   struct module syntax. */
2111
static int
2112
pack_single(PyMemoryViewObject *self, char *ptr, PyObject *item, const char *fmt)
2113
0
{
2114
0
    unsigned long long llu;
2115
0
    unsigned long lu;
2116
0
    size_t zu;
2117
0
    long long lld;
2118
0
    long ld;
2119
0
    Py_ssize_t zd;
2120
0
    double d;
2121
0
    Py_complex c;
2122
0
    void *p;
2123
2124
0
#if PY_LITTLE_ENDIAN
2125
0
    int endian = 1;
2126
#else
2127
    int endian = 0;
2128
#endif
2129
0
    switch (fmt[0]) {
2130
    /* signed integers */
2131
0
    case 'b': case 'h': case 'i': case 'l':
2132
0
        ld = pylong_as_ld(item);
2133
0
        if (ld == -1 && PyErr_Occurred())
2134
0
            goto err_occurred;
2135
0
        CHECK_RELEASED_INT_AGAIN(self);
2136
0
        switch (fmt[0]) {
2137
0
        case 'b':
2138
0
            if (ld < SCHAR_MIN || ld > SCHAR_MAX) goto err_range;
2139
0
            *((signed char *)ptr) = (signed char)ld; break;
2140
0
        case 'h':
2141
0
            if (ld < SHRT_MIN || ld > SHRT_MAX) goto err_range;
2142
0
            PACK_SINGLE(ptr, ld, short); break;
2143
0
        case 'i':
2144
0
            if (ld < INT_MIN || ld > INT_MAX) goto err_range;
2145
0
            PACK_SINGLE(ptr, ld, int); break;
2146
0
        default: /* 'l' */
2147
0
            PACK_SINGLE(ptr, ld, long); break;
2148
0
        }
2149
0
        break;
2150
2151
    /* unsigned integers */
2152
0
    case 'B': case 'H': case 'I': case 'L':
2153
0
        lu = pylong_as_lu(item);
2154
0
        if (lu == (unsigned long)-1 && PyErr_Occurred())
2155
0
            goto err_occurred;
2156
0
        CHECK_RELEASED_INT_AGAIN(self);
2157
0
        switch (fmt[0]) {
2158
0
        case 'B':
2159
0
            if (lu > UCHAR_MAX) goto err_range;
2160
0
            *((unsigned char *)ptr) = (unsigned char)lu; break;
2161
0
        case 'H':
2162
0
            if (lu > USHRT_MAX) goto err_range;
2163
0
            PACK_SINGLE(ptr, lu, unsigned short); break;
2164
0
        case 'I':
2165
0
            if (lu > UINT_MAX) goto err_range;
2166
0
            PACK_SINGLE(ptr, lu, unsigned int); break;
2167
0
        default: /* 'L' */
2168
0
            PACK_SINGLE(ptr, lu, unsigned long); break;
2169
0
        }
2170
0
        break;
2171
2172
    /* native 64-bit */
2173
0
    case 'q':
2174
0
        lld = pylong_as_lld(item);
2175
0
        if (lld == -1 && PyErr_Occurred())
2176
0
            goto err_occurred;
2177
0
        CHECK_RELEASED_INT_AGAIN(self);
2178
0
        PACK_SINGLE(ptr, lld, long long);
2179
0
        break;
2180
0
    case 'Q':
2181
0
        llu = pylong_as_llu(item);
2182
0
        if (llu == (unsigned long long)-1 && PyErr_Occurred())
2183
0
            goto err_occurred;
2184
0
        CHECK_RELEASED_INT_AGAIN(self);
2185
0
        PACK_SINGLE(ptr, llu, unsigned long long);
2186
0
        break;
2187
2188
    /* ssize_t and size_t */
2189
0
    case 'n':
2190
0
        zd = pylong_as_zd(item);
2191
0
        if (zd == -1 && PyErr_Occurred())
2192
0
            goto err_occurred;
2193
0
        CHECK_RELEASED_INT_AGAIN(self);
2194
0
        PACK_SINGLE(ptr, zd, Py_ssize_t);
2195
0
        break;
2196
0
    case 'N':
2197
0
        zu = pylong_as_zu(item);
2198
0
        if (zu == (size_t)-1 && PyErr_Occurred())
2199
0
            goto err_occurred;
2200
0
        CHECK_RELEASED_INT_AGAIN(self);
2201
0
        PACK_SINGLE(ptr, zu, size_t);
2202
0
        break;
2203
2204
    /* floats */
2205
0
    case 'f': case 'd': case 'e':
2206
0
        d = PyFloat_AsDouble(item);
2207
0
        if (d == -1.0 && PyErr_Occurred())
2208
0
            goto err_occurred;
2209
0
        CHECK_RELEASED_INT_AGAIN(self);
2210
0
        if (fmt[0] == 'f') {
2211
0
            if (PyFloat_Pack4(d, ptr, endian) < 0) {
2212
0
                goto err_occurred;
2213
0
            }
2214
0
        }
2215
0
        else if (fmt[0] == 'd') {
2216
0
            PACK_SINGLE(ptr, d, double);
2217
0
        }
2218
0
        else {
2219
0
            if (PyFloat_Pack2(d, ptr, endian) < 0) {
2220
0
                goto err_occurred;
2221
0
            }
2222
0
        }
2223
0
        break;
2224
2225
    /* complexes */
2226
0
    case 'Z': {
2227
0
        switch (fmt[1]) {
2228
0
        case 'f': case 'd':
2229
0
            c = PyComplex_AsCComplex(item);
2230
0
            if (c.real == -1.0 && PyErr_Occurred()) {
2231
0
                goto err_occurred;
2232
0
            }
2233
0
            CHECK_RELEASED_INT_AGAIN(self);
2234
0
            if (fmt[1] == 'd') {
2235
0
                double x[2] = {c.real, c.imag};
2236
2237
0
                memcpy(ptr, &x, sizeof(x));
2238
0
            }
2239
0
            else {
2240
0
                char tmp[8];
2241
2242
0
                if (PyFloat_Pack4(c.real, tmp, endian) < 0) {
2243
0
                    goto err_occurred;
2244
0
                }
2245
0
                if (PyFloat_Pack4(c.imag, tmp + 4, endian) < 0) {
2246
0
                    goto err_occurred;
2247
0
                }
2248
0
                memcpy(ptr, tmp, 8);
2249
0
            }
2250
0
            break;
2251
2252
0
        default: goto err_format;
2253
0
        }
2254
0
        break;
2255
0
    }
2256
2257
    /* bool */
2258
0
    case '?':
2259
0
        ld = PyObject_IsTrue(item);
2260
0
        if (ld < 0)
2261
0
            return -1; /* preserve original error */
2262
0
        CHECK_RELEASED_INT_AGAIN(self);
2263
0
        PACK_SINGLE(ptr, ld, _Bool);
2264
0
        break;
2265
2266
    /* bytes object */
2267
0
    case 'c':
2268
0
        if (!PyBytes_Check(item))
2269
0
            return type_error_int(fmt);
2270
0
        if (PyBytes_GET_SIZE(item) != 1)
2271
0
            return value_error_int(fmt);
2272
0
        *ptr = PyBytes_AS_STRING(item)[0];
2273
0
        break;
2274
2275
    /* pointer */
2276
0
    case 'P':
2277
0
        p = PyLong_AsVoidPtr(item);
2278
0
        if (p == NULL && PyErr_Occurred())
2279
0
            goto err_occurred;
2280
0
        CHECK_RELEASED_INT_AGAIN(self);
2281
0
        PACK_SINGLE(ptr, p, void *);
2282
0
        break;
2283
2284
    /* default */
2285
0
    default: goto err_format;
2286
0
    }
2287
2288
0
    return 0;
2289
2290
0
err_occurred:
2291
0
    return fix_error_int(fmt);
2292
0
err_range:
2293
0
    return value_error_int(fmt);
2294
0
err_format:
2295
0
    PyErr_Format(PyExc_NotImplementedError,
2296
0
        "memoryview: format %s not supported", fmt);
2297
0
    return -1;
2298
0
}
2299
2300
2301
/****************************************************************************/
2302
/*                       unpack using the struct module                     */
2303
/****************************************************************************/
2304
2305
/* For reasonable performance it is necessary to cache all objects required
2306
   for unpacking. An unpacker can handle the format passed to unpack_from().
2307
   Invariant: All pointer fields of the struct should either be NULL or valid
2308
   pointers. */
2309
struct unpacker {
2310
    PyObject *unpack_from; /* Struct.unpack_from(format) */
2311
    PyObject *mview;       /* cached memoryview */
2312
    char *item;            /* buffer for mview */
2313
    Py_ssize_t itemsize;   /* len(item) */
2314
};
2315
2316
static struct unpacker *
2317
unpacker_new(void)
2318
0
{
2319
0
    struct unpacker *x = PyMem_Malloc(sizeof *x);
2320
2321
0
    if (x == NULL) {
2322
0
        PyErr_NoMemory();
2323
0
        return NULL;
2324
0
    }
2325
2326
0
    x->unpack_from = NULL;
2327
0
    x->mview = NULL;
2328
0
    x->item = NULL;
2329
0
    x->itemsize = 0;
2330
2331
0
    return x;
2332
0
}
2333
2334
static void
2335
unpacker_free(struct unpacker *x)
2336
228
{
2337
228
    if (x) {
2338
0
        Py_XDECREF(x->unpack_from);
2339
0
        Py_XDECREF(x->mview);
2340
0
        PyMem_Free(x->item);
2341
0
        PyMem_Free(x);
2342
0
    }
2343
228
}
2344
2345
/* Return a new unpacker for the given format. */
2346
static struct unpacker *
2347
struct_get_unpacker(const char *fmt, Py_ssize_t itemsize)
2348
0
{
2349
0
    PyObject *Struct = NULL;    /* XXX cache it in globals? */
2350
0
    PyObject *structobj = NULL;
2351
0
    PyObject *format = NULL;
2352
0
    struct unpacker *x = NULL;
2353
2354
0
    Struct = PyImport_ImportModuleAttrString("struct", "Struct");
2355
0
    if (Struct == NULL)
2356
0
        return NULL;
2357
2358
0
    x = unpacker_new();
2359
0
    if (x == NULL)
2360
0
        goto error;
2361
2362
0
    format = PyBytes_FromString(fmt);
2363
0
    if (format == NULL)
2364
0
        goto error;
2365
2366
0
    structobj = PyObject_CallOneArg(Struct, format);
2367
0
    if (structobj == NULL)
2368
0
        goto error;
2369
2370
0
    x->unpack_from = PyObject_GetAttrString(structobj, "unpack_from");
2371
0
    if (x->unpack_from == NULL)
2372
0
        goto error;
2373
2374
0
    x->item = PyMem_Malloc(itemsize);
2375
0
    if (x->item == NULL) {
2376
0
        PyErr_NoMemory();
2377
0
        goto error;
2378
0
    }
2379
0
    x->itemsize = itemsize;
2380
2381
0
    x->mview = PyMemoryView_FromMemory(x->item, itemsize, PyBUF_WRITE);
2382
0
    if (x->mview == NULL)
2383
0
        goto error;
2384
2385
2386
0
out:
2387
0
    Py_XDECREF(Struct);
2388
0
    Py_XDECREF(format);
2389
0
    Py_XDECREF(structobj);
2390
0
    return x;
2391
2392
0
error:
2393
0
    unpacker_free(x);
2394
0
    x = NULL;
2395
0
    goto out;
2396
0
}
2397
2398
/* unpack a single item */
2399
static PyObject *
2400
struct_unpack_single(const char *ptr, struct unpacker *x)
2401
0
{
2402
0
    PyObject *v;
2403
2404
0
    memcpy(x->item, ptr, x->itemsize);
2405
0
    v = PyObject_CallOneArg(x->unpack_from, x->mview);
2406
0
    if (v == NULL)
2407
0
        return NULL;
2408
2409
0
    if (PyTuple_GET_SIZE(v) == 1) {
2410
0
        PyObject *res = Py_NewRef(PyTuple_GET_ITEM(v, 0));
2411
0
        Py_DECREF(v);
2412
0
        return res;
2413
0
    }
2414
2415
0
    return v;
2416
0
}
2417
2418
2419
/****************************************************************************/
2420
/*                              Representations                             */
2421
/****************************************************************************/
2422
2423
/* allow explicit form of native format */
2424
static inline const char *
2425
adjust_fmt(const Py_buffer *view)
2426
108k
{
2427
108k
    const char *fmt;
2428
2429
108k
    fmt = (view->format[0] == '@') ? view->format+1 : view->format;
2430
108k
    if (fmt[0] == 'Z' && fmt[1] && fmt[2] == '\0')
2431
0
        return fmt;
2432
108k
    if (fmt[0] && fmt[1] == '\0')
2433
108k
        return fmt;
2434
2435
0
    PyErr_Format(PyExc_NotImplementedError,
2436
0
        "memoryview: unsupported format %s", view->format);
2437
0
    return NULL;
2438
108k
}
2439
2440
/* Base case for multi-dimensional unpacking. Assumption: ndim == 1. */
2441
static PyObject *
2442
tolist_base(PyMemoryViewObject *self, const char *ptr, const Py_ssize_t *shape,
2443
            const Py_ssize_t *strides, const Py_ssize_t *suboffsets,
2444
            const char *fmt)
2445
60.3k
{
2446
60.3k
    PyObject *lst, *item;
2447
60.3k
    Py_ssize_t i;
2448
2449
60.3k
    lst = PyList_New(shape[0]);
2450
60.3k
    if (lst == NULL)
2451
0
        return NULL;
2452
2453
3.92M
    for (i = 0; i < shape[0]; ptr+=strides[0], i++) {
2454
3.86M
        const char *xptr = ADJUST_PTR(ptr, suboffsets, 0);
2455
3.86M
        item = unpack_single(self, xptr, fmt);
2456
3.86M
        if (item == NULL) {
2457
0
            Py_DECREF(lst);
2458
0
            return NULL;
2459
0
        }
2460
3.86M
        PyList_SET_ITEM(lst, i, item);
2461
3.86M
    }
2462
2463
60.3k
    return lst;
2464
60.3k
}
2465
2466
/* Unpack a multi-dimensional array into a nested list.
2467
   Assumption: ndim >= 1. */
2468
static PyObject *
2469
tolist_rec(PyMemoryViewObject *self, const char *ptr, Py_ssize_t ndim, const Py_ssize_t *shape,
2470
           const Py_ssize_t *strides, const Py_ssize_t *suboffsets,
2471
           const char *fmt)
2472
0
{
2473
0
    PyObject *lst, *item;
2474
0
    Py_ssize_t i;
2475
2476
0
    assert(ndim >= 1);
2477
0
    assert(shape != NULL);
2478
0
    assert(strides != NULL);
2479
2480
0
    if (ndim == 1)
2481
0
        return tolist_base(self, ptr, shape, strides, suboffsets, fmt);
2482
2483
0
    lst = PyList_New(shape[0]);
2484
0
    if (lst == NULL)
2485
0
        return NULL;
2486
2487
0
    for (i = 0; i < shape[0]; ptr+=strides[0], i++) {
2488
0
        const char *xptr = ADJUST_PTR(ptr, suboffsets, 0);
2489
0
        item = tolist_rec(self, xptr, ndim-1, shape+1,
2490
0
                          strides+1, suboffsets ? suboffsets+1 : NULL,
2491
0
                          fmt);
2492
0
        if (item == NULL) {
2493
0
            Py_DECREF(lst);
2494
0
            return NULL;
2495
0
        }
2496
0
        PyList_SET_ITEM(lst, i, item);
2497
0
    }
2498
2499
0
    return lst;
2500
0
}
2501
2502
/* Return a list representation of the memoryview. Currently only buffers
2503
   with native format strings are supported. */
2504
static PyObject *
2505
memoryview_tolist_pinned(PyMemoryViewObject *self)
2506
60.3k
{
2507
60.3k
    const Py_buffer *view = &self->view;
2508
60.3k
    const char *fmt;
2509
2510
60.3k
    CHECK_RELEASED(self);
2511
2512
60.3k
    fmt = adjust_fmt(view);
2513
60.3k
    if (fmt == NULL)
2514
0
        return NULL;
2515
60.3k
    if (view->ndim == 0) {
2516
0
        return unpack_single(self, view->buf, fmt);
2517
0
    }
2518
60.3k
    else if (view->ndim == 1) {
2519
60.3k
        return tolist_base(self, view->buf, view->shape,
2520
60.3k
                           view->strides, view->suboffsets,
2521
60.3k
                           fmt);
2522
60.3k
    }
2523
0
    else {
2524
0
        return tolist_rec(self, view->buf, view->ndim, view->shape,
2525
0
                          view->strides, view->suboffsets,
2526
0
                          fmt);
2527
0
    }
2528
60.3k
}
2529
2530
/*[clinic input]
2531
memoryview.tolist
2532
2533
Return the data in the buffer as a list of elements.
2534
[clinic start generated code]*/
2535
2536
static PyObject *
2537
memoryview_tolist_impl(PyMemoryViewObject *self)
2538
/*[clinic end generated code: output=a6cda89214fd5a1b input=21e7d0c1860b211a]*/
2539
60.3k
{
2540
60.3k
    if (memoryview_pin(self) < 0) {
2541
0
        return NULL;
2542
0
    }
2543
60.3k
    PyObject *result = memoryview_tolist_pinned(self);
2544
60.3k
    memoryview_unpin(self);
2545
60.3k
    return result;
2546
60.3k
}
2547
2548
2549
static PyObject *
2550
memoryview_tobytes_pinned(PyMemoryViewObject *self, const char *order)
2551
0
{
2552
0
    Py_buffer *src = VIEW_ADDR(self);
2553
0
    char ord = 'C';
2554
2555
0
    CHECK_RELEASED(self);
2556
2557
0
    if (order) {
2558
0
        if (strcmp(order, "F") == 0) {
2559
0
            ord = 'F';
2560
0
        }
2561
0
        else if (strcmp(order, "A") == 0) {
2562
0
            ord = 'A';
2563
0
        }
2564
0
        else if (strcmp(order, "C") != 0) {
2565
0
            PyErr_SetString(PyExc_ValueError,
2566
0
                "order must be 'C', 'F' or 'A'");
2567
0
            return NULL;
2568
0
        }
2569
0
    }
2570
2571
0
    PyBytesWriter *writer = PyBytesWriter_Create(src->len);
2572
0
    if (writer == NULL) {
2573
0
        return NULL;
2574
0
    }
2575
2576
0
    if (PyBuffer_ToContiguous(PyBytesWriter_GetData(writer),
2577
0
                              src, src->len, ord) < 0) {
2578
0
        PyBytesWriter_Discard(writer);
2579
0
        return NULL;
2580
0
    }
2581
2582
0
    return PyBytesWriter_Finish(writer);
2583
0
}
2584
2585
/*[clinic input]
2586
memoryview.tobytes
2587
2588
    order: str(accept={str, NoneType}, c_default="NULL") = 'C'
2589
2590
Return the data in the buffer as a byte string.
2591
2592
Order can be {'C', 'F', 'A'}.  When order is 'C' or 'F', the data of
2593
the original array is converted to C or Fortran order.  For
2594
contiguous views, 'A' returns an exact copy of the physical memory.
2595
In particular, in-memory Fortran order is preserved.  For
2596
non-contiguous views, the data is converted to C first.  order=None
2597
is the same as order='C'.
2598
[clinic start generated code]*/
2599
2600
static PyObject *
2601
memoryview_tobytes_impl(PyMemoryViewObject *self, const char *order)
2602
/*[clinic end generated code: output=1288b62560a32a23 input=119c70aa91791dc8]*/
2603
0
{
2604
0
    if (memoryview_pin(self) < 0) {
2605
0
        return NULL;
2606
0
    }
2607
0
    PyObject *result = memoryview_tobytes_pinned(self, order);
2608
0
    memoryview_unpin(self);
2609
0
    return result;
2610
0
}
2611
2612
2613
static PyObject *
2614
memoryview_hex_pinned(PyMemoryViewObject *self, PyObject *sep,
2615
                    Py_ssize_t bytes_per_sep)
2616
0
{
2617
0
    Py_buffer *src = VIEW_ADDR(self);
2618
2619
0
    CHECK_RELEASED(self);
2620
2621
0
    if (MV_C_CONTIGUOUS(mv_get_flags(self))) {
2622
        // Prevent 'self' from being freed if computing len(sep) mutates 'self'
2623
        // in _Py_strhex_with_sep().
2624
        // See: https://github.com/python/cpython/issues/143195.
2625
#ifdef Py_GIL_DISABLED
2626
        if (memoryview_add_export(self) < 0) {
2627
            return NULL;
2628
        }
2629
#else
2630
0
        self->exports++;
2631
0
#endif
2632
0
        PyObject *ret = _Py_strhex_with_sep(src->buf, src->len, sep, bytes_per_sep);
2633
0
        FT_ATOMIC_ADD_SSIZE(self->exports, -1);
2634
0
        return ret;
2635
0
    }
2636
2637
0
    char *buffer = PyMem_Malloc(src->len);
2638
0
    if (buffer == NULL) {
2639
0
        PyErr_NoMemory();
2640
0
        return NULL;
2641
0
    }
2642
2643
0
    if (PyBuffer_ToContiguous(buffer, src, src->len, 'C') < 0) {
2644
0
        PyMem_Free(buffer);
2645
0
        return NULL;
2646
0
    }
2647
2648
0
    PyObject *ret = _Py_strhex_with_sep(buffer, src->len, sep, bytes_per_sep);
2649
0
    PyMem_Free(buffer);
2650
2651
0
    return ret;
2652
0
}
2653
2654
/*[clinic input]
2655
memoryview.hex
2656
2657
    sep: object = NULL
2658
        An optional single character or byte to separate hex bytes.
2659
    bytes_per_sep: Py_ssize_t = 1
2660
        How many bytes between separators.  Positive values count from
2661
        the right, negative values count from the left.
2662
2663
Return the data in the buffer as a str of hexadecimal numbers.
2664
2665
Example:
2666
>>> value = memoryview(b'\xb9\x01\xef')
2667
>>> value.hex()
2668
'b901ef'
2669
>>> value.hex(':')
2670
'b9:01:ef'
2671
>>> value.hex(':', 2)
2672
'b9:01ef'
2673
>>> value.hex(':', -2)
2674
'b901:ef'
2675
[clinic start generated code]*/
2676
2677
static PyObject *
2678
memoryview_hex_impl(PyMemoryViewObject *self, PyObject *sep,
2679
                    Py_ssize_t bytes_per_sep)
2680
/*[clinic end generated code: output=c9bb00c7a8e86056 input=3f1c5d08906e3b70]*/
2681
0
{
2682
0
    if (memoryview_pin(self) < 0) {
2683
0
        return NULL;
2684
0
    }
2685
0
    PyObject *result = memoryview_hex_pinned(self, sep, bytes_per_sep);
2686
0
    memoryview_unpin(self);
2687
0
    return result;
2688
0
}
2689
2690
2691
static PyObject *
2692
memory_repr(PyObject *_self)
2693
0
{
2694
0
    PyMemoryViewObject *self = (PyMemoryViewObject *)_self;
2695
0
    if (mv_has_flag(self, _Py_MEMORYVIEW_RELEASED))
2696
0
        return PyUnicode_FromFormat("<released memory at %p>", self);
2697
0
    else
2698
0
        return PyUnicode_FromFormat("<memory at %p>", self);
2699
0
}
2700
2701
2702
/**************************************************************************/
2703
/*                          Indexing and slicing                          */
2704
/**************************************************************************/
2705
2706
static char *
2707
lookup_dimension(const Py_buffer *view, char *ptr, int dim, Py_ssize_t index)
2708
0
{
2709
0
    Py_ssize_t nitems; /* items in the given dimension */
2710
2711
0
    assert(view->shape);
2712
0
    assert(view->strides);
2713
2714
0
    nitems = view->shape[dim];
2715
0
    if (index < 0) {
2716
0
        index += nitems;
2717
0
    }
2718
0
    if (index < 0 || index >= nitems) {
2719
0
        PyErr_Format(PyExc_IndexError,
2720
0
                     "index out of bounds on dimension %d", dim + 1);
2721
0
        return NULL;
2722
0
    }
2723
2724
0
    ptr += view->strides[dim] * index;
2725
2726
0
    ptr = ADJUST_PTR(ptr, view->suboffsets, dim);
2727
2728
0
    return ptr;
2729
0
}
2730
2731
/* Get the pointer to the item at index. */
2732
static char *
2733
ptr_from_index(const Py_buffer *view, Py_ssize_t index)
2734
0
{
2735
0
    char *ptr = (char *)view->buf;
2736
0
    return lookup_dimension(view, ptr, 0, index);
2737
0
}
2738
2739
/* Get the pointer to the item at tuple. */
2740
static char *
2741
ptr_from_tuple(const Py_buffer *view, PyObject *tup)
2742
0
{
2743
0
    char *ptr = (char *)view->buf;
2744
0
    Py_ssize_t dim, nindices = PyTuple_GET_SIZE(tup);
2745
2746
0
    if (nindices > view->ndim) {
2747
0
        PyErr_Format(PyExc_TypeError,
2748
0
                     "cannot index %d-dimension view with %zd-element tuple",
2749
0
                     view->ndim, nindices);
2750
0
        return NULL;
2751
0
    }
2752
2753
0
    for (dim = 0; dim < nindices; dim++) {
2754
0
        Py_ssize_t index;
2755
0
        index = PyNumber_AsSsize_t(PyTuple_GET_ITEM(tup, dim),
2756
0
                                   PyExc_IndexError);
2757
0
        if (index == -1 && PyErr_Occurred())
2758
0
            return NULL;
2759
0
        ptr = lookup_dimension(view, ptr, (int)dim, index);
2760
0
        if (ptr == NULL)
2761
0
            return NULL;
2762
0
    }
2763
0
    return ptr;
2764
0
}
2765
2766
/* Return the item at index. In a one-dimensional view, this is an object
2767
   with the type specified by view->format. Otherwise, the item is a sub-view.
2768
   The function is used in memory_subscript_pinned() and by sq_item. */
2769
static PyObject *
2770
memory_item_pinned(PyObject *_self, Py_ssize_t index)
2771
0
{
2772
0
    PyMemoryViewObject *self = (PyMemoryViewObject *)_self;
2773
0
    Py_buffer *view = &(self->view);
2774
0
    const char *fmt;
2775
2776
0
    CHECK_RELEASED(self);
2777
2778
0
    fmt = adjust_fmt(view);
2779
0
    if (fmt == NULL)
2780
0
        return NULL;
2781
2782
0
    if (view->ndim == 0) {
2783
0
        PyErr_SetString(PyExc_TypeError, "invalid indexing of 0-dim memory");
2784
0
        return NULL;
2785
0
    }
2786
0
    if (view->ndim == 1) {
2787
0
        char *ptr = ptr_from_index(view, index);
2788
0
        if (ptr == NULL)
2789
0
            return NULL;
2790
0
        return unpack_single(self, ptr, fmt);
2791
0
    }
2792
2793
0
    PyErr_SetString(PyExc_NotImplementedError,
2794
0
        "multi-dimensional sub-views are not implemented");
2795
0
    return NULL;
2796
0
}
2797
2798
/* Return the item at position *key* (a tuple of indices). */
2799
static PyObject *
2800
memory_item_multi(PyMemoryViewObject *self, PyObject *tup)
2801
0
{
2802
0
    Py_buffer *view = &(self->view);
2803
0
    const char *fmt;
2804
0
    Py_ssize_t nindices = PyTuple_GET_SIZE(tup);
2805
0
    char *ptr;
2806
2807
0
    CHECK_RELEASED(self);
2808
2809
0
    fmt = adjust_fmt(view);
2810
0
    if (fmt == NULL)
2811
0
        return NULL;
2812
2813
0
    if (nindices < view->ndim) {
2814
0
        PyErr_SetString(PyExc_NotImplementedError,
2815
0
                        "sub-views are not implemented");
2816
0
        return NULL;
2817
0
    }
2818
0
    ptr = ptr_from_tuple(view, tup);
2819
0
    if (ptr == NULL)
2820
0
        return NULL;
2821
0
    return unpack_single(self, ptr, fmt);
2822
0
}
2823
2824
static inline int
2825
init_slice(Py_buffer *base, PyObject *key, int dim)
2826
50.2k
{
2827
50.2k
    Py_ssize_t start, stop, step, slicelength;
2828
2829
50.2k
    if (PySlice_Unpack(key, &start, &stop, &step) < 0) {
2830
0
        return -1;
2831
0
    }
2832
50.2k
    slicelength = PySlice_AdjustIndices(base->shape[dim], &start, &stop, step);
2833
2834
2835
50.2k
    if (base->suboffsets == NULL || dim == 0) {
2836
50.2k
    adjust_buf:
2837
50.2k
        base->buf = (char *)base->buf + base->strides[dim] * start;
2838
50.2k
    }
2839
0
    else {
2840
0
        Py_ssize_t n = dim-1;
2841
0
        while (n >= 0 && base->suboffsets[n] < 0)
2842
0
            n--;
2843
0
        if (n < 0)
2844
0
            goto adjust_buf; /* all suboffsets are negative */
2845
0
        base->suboffsets[n] = base->suboffsets[n] + base->strides[dim] * start;
2846
0
    }
2847
50.2k
    base->shape[dim] = slicelength;
2848
50.2k
    base->strides[dim] = base->strides[dim] * step;
2849
2850
50.2k
    return 0;
2851
50.2k
}
2852
2853
static int
2854
is_multislice(PyObject *key)
2855
0
{
2856
0
    Py_ssize_t size, i;
2857
2858
0
    if (!PyTuple_Check(key))
2859
0
        return 0;
2860
0
    size = PyTuple_GET_SIZE(key);
2861
0
    if (size == 0)
2862
0
        return 0;
2863
2864
0
    for (i = 0; i < size; i++) {
2865
0
        PyObject *x = PyTuple_GET_ITEM(key, i);
2866
0
        if (!PySlice_Check(x))
2867
0
            return 0;
2868
0
    }
2869
0
    return 1;
2870
0
}
2871
2872
static Py_ssize_t
2873
is_multiindex(PyObject *key)
2874
0
{
2875
0
    Py_ssize_t size, i;
2876
2877
0
    if (!PyTuple_Check(key))
2878
0
        return 0;
2879
0
    size = PyTuple_GET_SIZE(key);
2880
0
    for (i = 0; i < size; i++) {
2881
0
        PyObject *x = PyTuple_GET_ITEM(key, i);
2882
0
        if (!_PyIndex_Check(x)) {
2883
0
            return 0;
2884
0
        }
2885
0
    }
2886
0
    return 1;
2887
0
}
2888
2889
/* mv[obj] returns an object holding the data for one element if obj
2890
   fully indexes the memoryview or another memoryview object if it
2891
   does not.
2892
2893
   0-d memoryview objects can be referenced using mv[...] or mv[()]
2894
   but not with anything else. */
2895
static PyObject *
2896
memory_subscript_pinned(PyObject *_self, PyObject *key)
2897
2.04k
{
2898
2.04k
    PyMemoryViewObject *self = (PyMemoryViewObject *)_self;
2899
2.04k
    Py_buffer *view;
2900
2.04k
    view = &(self->view);
2901
2902
2.04k
    CHECK_RELEASED(self);
2903
2904
2.04k
    if (view->ndim == 0) {
2905
0
        if (PyTuple_Check(key) && PyTuple_GET_SIZE(key) == 0) {
2906
0
            const char *fmt = adjust_fmt(view);
2907
0
            if (fmt == NULL)
2908
0
                return NULL;
2909
0
            return unpack_single(self, view->buf, fmt);
2910
0
        }
2911
0
        else if (key == Py_Ellipsis) {
2912
0
            return Py_NewRef(self);
2913
0
        }
2914
0
        else {
2915
0
            PyErr_SetString(PyExc_TypeError,
2916
0
                "invalid indexing of 0-dim memory");
2917
0
            return NULL;
2918
0
        }
2919
0
    }
2920
2921
2.04k
    if (_PyIndex_Check(key)) {
2922
0
        Py_ssize_t index;
2923
0
        index = PyNumber_AsSsize_t(key, PyExc_IndexError);
2924
0
        if (index == -1 && PyErr_Occurred())
2925
0
            return NULL;
2926
0
        return memory_item_pinned((PyObject *)self, index);
2927
0
    }
2928
2.04k
    else if (PySlice_Check(key)) {
2929
2.04k
        CHECK_RESTRICTED(self);
2930
2.04k
        PyMemoryViewObject *sliced;
2931
2932
2.04k
        sliced = (PyMemoryViewObject *)mbuf_add_view(self->mbuf, view);
2933
2.04k
        if (sliced == NULL)
2934
0
            return NULL;
2935
2936
2.04k
        if (init_slice(&sliced->view, key, 0) < 0) {
2937
0
            Py_DECREF(sliced);
2938
0
            return NULL;
2939
0
        }
2940
2.04k
        init_len(&sliced->view);
2941
2.04k
        init_flags(sliced);
2942
2943
2.04k
        return (PyObject *)sliced;
2944
2.04k
    }
2945
0
    else if (is_multiindex(key)) {
2946
0
        return memory_item_multi(self, key);
2947
0
    }
2948
0
    else if (is_multislice(key)) {
2949
0
        PyErr_SetString(PyExc_NotImplementedError,
2950
0
            "multi-dimensional slicing is not implemented");
2951
0
        return NULL;
2952
0
    }
2953
2954
0
    PyErr_SetString(PyExc_TypeError, "memoryview: invalid slice key");
2955
0
    return NULL;
2956
2.04k
}
2957
2958
static int
2959
memory_ass_sub_pinned(PyObject *_self, PyObject *key, PyObject *value)
2960
48.2k
{
2961
48.2k
    PyMemoryViewObject *self = (PyMemoryViewObject *)_self;
2962
48.2k
    Py_buffer *view = &(self->view);
2963
48.2k
    Py_buffer src;
2964
48.2k
    const char *fmt;
2965
48.2k
    char *ptr;
2966
2967
48.2k
    CHECK_RELEASED_INT(self);
2968
2969
48.2k
    fmt = adjust_fmt(view);
2970
48.2k
    if (fmt == NULL)
2971
0
        return -1;
2972
2973
48.2k
    if (view->readonly) {
2974
0
        PyErr_SetString(PyExc_TypeError, "cannot modify read-only memory");
2975
0
        return -1;
2976
0
    }
2977
48.2k
    if (value == NULL) {
2978
0
        PyErr_SetString(PyExc_TypeError, "cannot delete memory");
2979
0
        return -1;
2980
0
    }
2981
48.2k
    if (view->ndim == 0) {
2982
0
        if (key == Py_Ellipsis ||
2983
0
            (PyTuple_Check(key) && PyTuple_GET_SIZE(key)==0)) {
2984
0
            ptr = (char *)view->buf;
2985
0
            return pack_single(self, ptr, value, fmt);
2986
0
        }
2987
0
        else {
2988
0
            PyErr_SetString(PyExc_TypeError,
2989
0
                "invalid indexing of 0-dim memory");
2990
0
            return -1;
2991
0
        }
2992
0
    }
2993
2994
48.2k
    if (_PyIndex_Check(key)) {
2995
0
        Py_ssize_t index;
2996
0
        if (1 < view->ndim) {
2997
0
            PyErr_SetString(PyExc_NotImplementedError,
2998
0
                            "sub-views are not implemented");
2999
0
            return -1;
3000
0
        }
3001
0
        index = PyNumber_AsSsize_t(key, PyExc_IndexError);
3002
0
        if (index == -1 && PyErr_Occurred())
3003
0
            return -1;
3004
0
        ptr = ptr_from_index(view, index);
3005
0
        if (ptr == NULL)
3006
0
            return -1;
3007
0
        return pack_single(self, ptr, value, fmt);
3008
0
    }
3009
    /* one-dimensional: fast path */
3010
48.2k
    if (PySlice_Check(key) && view->ndim == 1) {
3011
48.2k
        Py_buffer dest; /* sliced view */
3012
48.2k
        Py_ssize_t arrays[3];
3013
48.2k
        int ret = -1;
3014
3015
        /* rvalue must be an exporter */
3016
48.2k
        if (PyObject_GetBuffer(value, &src, PyBUF_FULL_RO) < 0)
3017
0
            return ret;
3018
3019
48.2k
        dest = *view;
3020
48.2k
        dest.shape = &arrays[0]; dest.shape[0] = view->shape[0];
3021
48.2k
        dest.strides = &arrays[1]; dest.strides[0] = view->strides[0];
3022
48.2k
        if (view->suboffsets) {
3023
0
            dest.suboffsets = &arrays[2]; dest.suboffsets[0] = view->suboffsets[0];
3024
0
        }
3025
3026
48.2k
        if (init_slice(&dest, key, 0) < 0)
3027
0
            goto end_block;
3028
48.2k
        dest.len = dest.shape[0] * dest.itemsize;
3029
3030
48.2k
        ret = copy_single(self, &dest, &src);
3031
3032
48.2k
    end_block:
3033
48.2k
        PyBuffer_Release(&src);
3034
48.2k
        return ret;
3035
48.2k
    }
3036
0
    if (is_multiindex(key)) {
3037
0
        char *ptr;
3038
0
        if (PyTuple_GET_SIZE(key) < view->ndim) {
3039
0
            PyErr_SetString(PyExc_NotImplementedError,
3040
0
                            "sub-views are not implemented");
3041
0
            return -1;
3042
0
        }
3043
0
        ptr = ptr_from_tuple(view, key);
3044
0
        if (ptr == NULL)
3045
0
            return -1;
3046
0
        return pack_single(self, ptr, value, fmt);
3047
0
    }
3048
0
    if (PySlice_Check(key) || is_multislice(key)) {
3049
        /* Call memory_subscript_pinned() to produce a sliced lvalue, then copy
3050
           rvalue into lvalue. This is already implemented in _testbuffer.c. */
3051
0
        PyErr_SetString(PyExc_NotImplementedError,
3052
0
            "memoryview slice assignments are currently restricted "
3053
0
            "to ndim = 1");
3054
0
        return -1;
3055
0
    }
3056
3057
0
    PyErr_SetString(PyExc_TypeError, "memoryview: invalid slice key");
3058
0
    return -1;
3059
0
}
3060
3061
static Py_ssize_t
3062
memory_length(PyObject *_self)
3063
1.42M
{
3064
1.42M
    PyMemoryViewObject *self = (PyMemoryViewObject *)_self;
3065
1.42M
    CHECK_RELEASED_INT(self);
3066
1.42M
    if (self->view.ndim == 0) {
3067
0
        PyErr_SetString(PyExc_TypeError, "0-dim memory has no length");
3068
0
        return -1;
3069
0
    }
3070
1.42M
    return self->view.shape[0];
3071
1.42M
}
3072
3073
static PyObject *
3074
memory_item(PyObject *_self, Py_ssize_t index)
3075
0
{
3076
0
    PyMemoryViewObject *self = (PyMemoryViewObject *)_self;
3077
0
    if (memoryview_pin(self) < 0) {
3078
0
        return NULL;
3079
0
    }
3080
0
    PyObject *result = memory_item_pinned(_self, index);
3081
0
    memoryview_unpin(self);
3082
0
    return result;
3083
0
}
3084
3085
static PyObject *
3086
memory_subscript(PyObject *_self, PyObject *key)
3087
2.04k
{
3088
2.04k
    PyMemoryViewObject *self = (PyMemoryViewObject *)_self;
3089
2.04k
    if (memoryview_pin(self) < 0) {
3090
0
        return NULL;
3091
0
    }
3092
2.04k
    PyObject *result = memory_subscript_pinned(_self, key);
3093
2.04k
    memoryview_unpin(self);
3094
2.04k
    return result;
3095
2.04k
}
3096
3097
static int
3098
memory_ass_sub(PyObject *_self, PyObject *key, PyObject *value)
3099
48.2k
{
3100
48.2k
    PyMemoryViewObject *self = (PyMemoryViewObject *)_self;
3101
48.2k
    if (memoryview_pin(self) < 0) {
3102
0
        return -1;
3103
0
    }
3104
48.2k
    int result = memory_ass_sub_pinned(_self, key, value);
3105
48.2k
    memoryview_unpin(self);
3106
48.2k
    return result;
3107
48.2k
}
3108
3109
/* As mapping */
3110
static PyMappingMethods memory_as_mapping = {
3111
    memory_length,                        /* mp_length */
3112
    memory_subscript,                     /* mp_subscript */
3113
    memory_ass_sub,                       /* mp_ass_subscript */
3114
};
3115
3116
/* As sequence */
3117
static PySequenceMethods memory_as_sequence = {
3118
        memory_length,                    /* sq_length */
3119
        0,                                /* sq_concat */
3120
        0,                                /* sq_repeat */
3121
        memory_item,                      /* sq_item */
3122
};
3123
3124
3125
/****************************************************************************/
3126
/*                              Counting                                    */
3127
/****************************************************************************/
3128
3129
static PyObject *
3130
memoryview_count_pinned(PyMemoryViewObject *self, PyObject *value)
3131
0
{
3132
0
    PyObject *iter = PyObject_GetIter(_PyObject_CAST(self));
3133
0
    if (iter == NULL) {
3134
0
        return NULL;
3135
0
    }
3136
3137
0
    Py_ssize_t count = 0;
3138
0
    PyObject *item = NULL;
3139
0
    while (PyIter_NextItem(iter, &item)) {
3140
0
        if (item == NULL) {
3141
0
            Py_DECREF(iter);
3142
0
            return NULL;
3143
0
        }
3144
0
        if (item == value) {
3145
0
            Py_DECREF(item);
3146
0
            count++;  // no overflow since count <= len(mv) <= PY_SSIZE_T_MAX
3147
0
            continue;
3148
0
        }
3149
0
        int contained = PyObject_RichCompareBool(item, value, Py_EQ);
3150
0
        Py_DECREF(item);
3151
0
        if (contained > 0) { // more likely than 'contained < 0'
3152
0
            count++;  // no overflow since count <= len(mv) <= PY_SSIZE_T_MAX
3153
0
        }
3154
0
        else if (contained < 0) {
3155
0
            Py_DECREF(iter);
3156
0
            return NULL;
3157
0
        }
3158
0
    }
3159
0
    Py_DECREF(iter);
3160
0
    return PyLong_FromSsize_t(count);
3161
0
}
3162
3163
/*[clinic input]
3164
memoryview.count
3165
3166
    value: object
3167
    /
3168
3169
Count the number of occurrences of a value.
3170
[clinic start generated code]*/
3171
3172
static PyObject *
3173
memoryview_count_impl(PyMemoryViewObject *self, PyObject *value)
3174
/*[clinic end generated code: output=a15cb19311985063 input=e3036ce1ed7d1823]*/
3175
0
{
3176
0
    if (memoryview_pin(self) < 0) {
3177
0
        return NULL;
3178
0
    }
3179
0
    PyObject *result = memoryview_count_pinned(self, value);
3180
0
    memoryview_unpin(self);
3181
0
    return result;
3182
0
}
3183
3184
3185
3186
/**************************************************************************/
3187
/*                             Lookup                                     */
3188
/**************************************************************************/
3189
3190
static PyObject *
3191
memoryview_index_pinned(PyMemoryViewObject *self, PyObject *value,
3192
                        Py_ssize_t start, Py_ssize_t stop)
3193
0
{
3194
0
    const Py_buffer *view = &self->view;
3195
0
    CHECK_RELEASED(self);
3196
3197
0
    if (view->ndim == 0) {
3198
0
        PyErr_SetString(PyExc_TypeError, "invalid lookup on 0-dim memory");
3199
0
        return NULL;
3200
0
    }
3201
3202
0
    if (view->ndim == 1) {
3203
0
        Py_ssize_t n = view->shape[0];
3204
3205
0
        if (start < 0) {
3206
0
            start = Py_MAX(start + n, 0);
3207
0
        }
3208
3209
0
        if (stop < 0) {
3210
0
            stop = Py_MAX(stop + n, 0);
3211
0
        }
3212
3213
0
        stop = Py_MIN(stop, n);
3214
0
        assert(stop >= 0);
3215
0
        assert(stop <= n);
3216
3217
0
        start = Py_MIN(start, stop);
3218
0
        assert(0 <= start);
3219
0
        assert(start <= stop);
3220
3221
0
        PyObject *obj = _PyObject_CAST(self);
3222
0
        for (Py_ssize_t index = start; index < stop; index++) {
3223
            // Note: while memoryviews can be mutated during iterations
3224
            // when calling the == operator, their shape cannot. As such,
3225
            // it is safe to assume that the index remains valid for the
3226
            // entire loop.
3227
0
            assert(index < n);
3228
3229
0
            PyObject *item = memory_item_pinned(obj, index);
3230
0
            if (item == NULL) {
3231
0
                return NULL;
3232
0
            }
3233
0
            if (item == value) {
3234
0
                Py_DECREF(item);
3235
0
                return PyLong_FromSsize_t(index);
3236
0
            }
3237
0
            int contained = PyObject_RichCompareBool(item, value, Py_EQ);
3238
0
            Py_DECREF(item);
3239
0
            if (contained > 0) {  // more likely than 'contained < 0'
3240
0
                return PyLong_FromSsize_t(index);
3241
0
            }
3242
0
            else if (contained < 0) {
3243
0
                return NULL;
3244
0
            }
3245
0
        }
3246
3247
0
        PyErr_SetString(PyExc_ValueError, "memoryview.index(x): x not found");
3248
0
        return NULL;
3249
0
    }
3250
3251
0
    PyErr_SetString(PyExc_NotImplementedError,
3252
0
                    "multi-dimensional lookup is not implemented");
3253
0
    return NULL;
3254
3255
0
}
3256
3257
/*[clinic input]
3258
memoryview.index
3259
3260
    value: object
3261
    start: slice_index(accept={int}) = 0
3262
    stop: slice_index(accept={int}, c_default="PY_SSIZE_T_MAX") = sys.maxsize
3263
    /
3264
3265
Return the index of the first occurrence of a value.
3266
3267
Raises ValueError if the value is not present.
3268
[clinic start generated code]*/
3269
3270
static PyObject *
3271
memoryview_index_impl(PyMemoryViewObject *self, PyObject *value,
3272
                      Py_ssize_t start, Py_ssize_t stop)
3273
/*[clinic end generated code: output=e0185e3819e549df input=0697a0165bf90b5a]*/
3274
0
{
3275
0
    if (memoryview_pin(self) < 0) {
3276
0
        return NULL;
3277
0
    }
3278
0
    PyObject *result = memoryview_index_pinned(self, value, start, stop);
3279
0
    memoryview_unpin(self);
3280
0
    return result;
3281
0
}
3282
3283
3284
/**************************************************************************/
3285
/*                             Comparisons                                */
3286
/**************************************************************************/
3287
3288
0
#define MV_COMPARE_EX -1       /* exception */
3289
114
#define MV_COMPARE_NOT_IMPL -2 /* not implemented */
3290
3291
/* Translate a StructError to "not equal". Preserve other exceptions. */
3292
static int
3293
fix_struct_error_int(void)
3294
0
{
3295
0
    assert(PyErr_Occurred());
3296
    /* XXX Cannot get at StructError directly? */
3297
0
    if (PyErr_ExceptionMatches(PyExc_ImportError) ||
3298
0
        PyErr_ExceptionMatches(PyExc_MemoryError)) {
3299
0
        return MV_COMPARE_EX;
3300
0
    }
3301
    /* StructError: invalid or unknown format -> not equal */
3302
0
    PyErr_Clear();
3303
0
    return 0;
3304
0
}
3305
3306
/* Unpack and compare single items of p and q using the struct module. */
3307
static int
3308
struct_unpack_cmp(const char *p, const char *q,
3309
                  struct unpacker *unpack_p, struct unpacker *unpack_q)
3310
0
{
3311
0
    PyObject *v, *w;
3312
0
    int ret;
3313
3314
    /* At this point any exception from the struct module should not be
3315
       StructError, since both formats have been accepted already. */
3316
0
    v = struct_unpack_single(p, unpack_p);
3317
0
    if (v == NULL)
3318
0
        return MV_COMPARE_EX;
3319
3320
0
    w = struct_unpack_single(q, unpack_q);
3321
0
    if (w == NULL) {
3322
0
        Py_DECREF(v);
3323
0
        return MV_COMPARE_EX;
3324
0
    }
3325
3326
    /* MV_COMPARE_EX == -1: exceptions are preserved */
3327
0
    ret = PyObject_RichCompareBool(v, w, Py_EQ);
3328
0
    Py_DECREF(v);
3329
0
    Py_DECREF(w);
3330
3331
0
    return ret;
3332
0
}
3333
3334
/* Unpack and compare single items of p and q. If both p and q have the same
3335
   single element native format, the comparison uses a fast path (gcc creates
3336
   a jump table and converts memcpy into simple assignments on x86/x64).
3337
3338
   Otherwise, the comparison is delegated to the struct module, which is
3339
   30-60x slower. */
3340
#define CMP_SINGLE(p, q, type) \
3341
0
    do {                                 \
3342
0
        type x;                          \
3343
0
        type y;                          \
3344
0
        memcpy((char *)&x, p, sizeof x); \
3345
0
        memcpy((char *)&y, q, sizeof y); \
3346
0
        equal = (x == y);                \
3347
0
    } while (0)
3348
3349
static inline int
3350
unpack_cmp(const char *p, const char *q, const char *fmt,
3351
           struct unpacker *unpack_p, struct unpacker *unpack_q)
3352
91
{
3353
91
    int equal;
3354
3355
91
    switch (fmt[0]) {
3356
3357
    /* signed integers and fast path for 'B' */
3358
91
    case 'B': return *((const unsigned char *)p) == *((const unsigned char *)q);
3359
0
    case 'b': return *((const signed char *)p) == *((const signed char *)q);
3360
0
    case 'h': CMP_SINGLE(p, q, short); return equal;
3361
0
    case 'i': CMP_SINGLE(p, q, int); return equal;
3362
0
    case 'l': CMP_SINGLE(p, q, long); return equal;
3363
3364
    /* boolean */
3365
0
    case '?': return UNPACK_TO_BOOL(p) == UNPACK_TO_BOOL(q);
3366
3367
    /* unsigned integers */
3368
0
    case 'H': CMP_SINGLE(p, q, unsigned short); return equal;
3369
0
    case 'I': CMP_SINGLE(p, q, unsigned int); return equal;
3370
0
    case 'L': CMP_SINGLE(p, q, unsigned long); return equal;
3371
3372
    /* native 64-bit */
3373
0
    case 'q': CMP_SINGLE(p, q, long long); return equal;
3374
0
    case 'Q': CMP_SINGLE(p, q, unsigned long long); return equal;
3375
3376
    /* ssize_t and size_t */
3377
0
    case 'n': CMP_SINGLE(p, q, Py_ssize_t); return equal;
3378
0
    case 'N': CMP_SINGLE(p, q, size_t); return equal;
3379
3380
    /* floats */
3381
    /* XXX DBL_EPSILON? */
3382
0
    case 'f': CMP_SINGLE(p, q, float); return equal;
3383
0
    case 'd': CMP_SINGLE(p, q, double); return equal;
3384
0
    case 'e': {
3385
0
#if PY_LITTLE_ENDIAN
3386
0
        int endian = 1;
3387
#else
3388
        int endian = 0;
3389
#endif
3390
        /* Note: PyFloat_Unpack2 should never fail */
3391
0
        double u = PyFloat_Unpack2(p, endian);
3392
0
        double v = PyFloat_Unpack2(q, endian);
3393
0
        return (u == v);
3394
0
    }
3395
3396
    /* complexes */
3397
0
    case 'Z': {
3398
0
        switch (fmt[1]) {
3399
0
        case 'f':
3400
0
        {
3401
0
             float x[2], y[2];
3402
3403
0
             memcpy(&x, p, sizeof(x));
3404
0
             memcpy(&y, q, sizeof(y));
3405
0
             return (x[0] == y[0]) && (x[1] == y[1]);
3406
0
        }
3407
0
        case 'd':
3408
0
        {
3409
0
             double x[2], y[2];
3410
3411
0
             memcpy(&x, p, sizeof(x));
3412
0
             memcpy(&y, q, sizeof(y));
3413
0
             return (x[0] == y[0]) && (x[1] == y[1]);
3414
0
        }
3415
0
        }
3416
0
        break;
3417
0
    }
3418
3419
    /* bytes object */
3420
0
    case 'c': return *p == *q;
3421
3422
    /* pointer */
3423
0
    case 'P': CMP_SINGLE(p, q, void *); return equal;
3424
3425
    /* use the struct module */
3426
0
    case '_':
3427
0
        assert(unpack_p);
3428
0
        assert(unpack_q);
3429
0
        return struct_unpack_cmp(p, q, unpack_p, unpack_q);
3430
91
    }
3431
3432
    /* NOT REACHED */
3433
0
    PyErr_SetString(PyExc_RuntimeError,
3434
0
        "memoryview: internal error in richcompare");
3435
0
    return MV_COMPARE_EX;
3436
91
}
3437
3438
/* Base case for recursive array comparisons. Assumption: ndim == 1. */
3439
static int
3440
cmp_base(const char *p, const char *q, const Py_ssize_t *shape,
3441
         const Py_ssize_t *pstrides, const Py_ssize_t *psuboffsets,
3442
         const Py_ssize_t *qstrides, const Py_ssize_t *qsuboffsets,
3443
         const char *fmt, struct unpacker *unpack_p, struct unpacker *unpack_q)
3444
85
{
3445
85
    Py_ssize_t i;
3446
85
    int equal;
3447
3448
92
    for (i = 0; i < shape[0]; p+=pstrides[0], q+=qstrides[0], i++) {
3449
91
        const char *xp = ADJUST_PTR(p, psuboffsets, 0);
3450
91
        const char *xq = ADJUST_PTR(q, qsuboffsets, 0);
3451
91
        equal = unpack_cmp(xp, xq, fmt, unpack_p, unpack_q);
3452
91
        if (equal <= 0)
3453
84
            return equal;
3454
91
    }
3455
3456
1
    return 1;
3457
85
}
3458
3459
/* Recursively compare two multi-dimensional arrays that have the same
3460
   logical structure. Assumption: ndim >= 1. */
3461
static int
3462
cmp_rec(const char *p, const char *q,
3463
        Py_ssize_t ndim, const Py_ssize_t *shape,
3464
        const Py_ssize_t *pstrides, const Py_ssize_t *psuboffsets,
3465
        const Py_ssize_t *qstrides, const Py_ssize_t *qsuboffsets,
3466
        const char *fmt, struct unpacker *unpack_p, struct unpacker *unpack_q)
3467
0
{
3468
0
    Py_ssize_t i;
3469
0
    int equal;
3470
3471
0
    assert(ndim >= 1);
3472
0
    assert(shape != NULL);
3473
0
    assert(pstrides != NULL);
3474
0
    assert(qstrides != NULL);
3475
3476
0
    if (ndim == 1) {
3477
0
        return cmp_base(p, q, shape,
3478
0
                        pstrides, psuboffsets,
3479
0
                        qstrides, qsuboffsets,
3480
0
                        fmt, unpack_p, unpack_q);
3481
0
    }
3482
3483
0
    for (i = 0; i < shape[0]; p+=pstrides[0], q+=qstrides[0], i++) {
3484
0
        const char *xp = ADJUST_PTR(p, psuboffsets, 0);
3485
0
        const char *xq = ADJUST_PTR(q, qsuboffsets, 0);
3486
0
        equal = cmp_rec(xp, xq, ndim-1, shape+1,
3487
0
                        pstrides+1, psuboffsets ? psuboffsets+1 : NULL,
3488
0
                        qstrides+1, qsuboffsets ? qsuboffsets+1 : NULL,
3489
0
                        fmt, unpack_p, unpack_q);
3490
0
        if (equal <= 0)
3491
0
            return equal;
3492
0
    }
3493
3494
0
    return 1;
3495
0
}
3496
3497
static PyObject *
3498
memory_richcompare_pinned(PyObject *v, PyObject *w, int op)
3499
114
{
3500
114
    PyObject *res;
3501
114
    Py_buffer wbuf, *vv;
3502
114
    Py_buffer *ww = NULL;
3503
114
    struct unpacker *unpack_v = NULL;
3504
114
    struct unpacker *unpack_w = NULL;
3505
114
    const char *vfmt, *wfmt;
3506
114
    int equal = MV_COMPARE_NOT_IMPL;
3507
3508
114
    if (op != Py_EQ && op != Py_NE)
3509
0
        goto result; /* Py_NotImplemented */
3510
3511
114
    assert(PyMemoryView_Check(v));
3512
114
    if (BASE_INACCESSIBLE(v)) {
3513
0
        equal = (v == w);
3514
0
        goto result;
3515
0
    }
3516
114
    vv = VIEW_ADDR(v);
3517
3518
    // For formats supported by the struct module a memoryview is equal to
3519
    // itself: there is no need to compare individual values.
3520
    // This is not true for float values since they can be NaN, and NaN
3521
    // is not equal to itself.  So only use this optimization on format known to
3522
    // not use floats.
3523
114
    if (v == w) {
3524
0
        const char *format = vv->format;
3525
0
        if (format != NULL) {
3526
0
            if (*format == '@') {
3527
0
                format++;
3528
0
            }
3529
            // Include only formats known by struct, exclude float formats
3530
            // "d" (double), "f" (float) and "e" (16-bit float).
3531
            // Do not optimize "P" format.
3532
0
            if (format[0] != 0
3533
0
                && strchr("bBchHiIlLnNqQ?", format[0]) != NULL
3534
0
                && format[1] == 0)
3535
0
            {
3536
0
                equal = 1;
3537
0
                goto result;
3538
0
            }
3539
0
        }
3540
0
    }
3541
3542
114
    if (PyMemoryView_Check(w)) {
3543
0
        if (BASE_INACCESSIBLE(w)) {
3544
0
            equal = (v == w);
3545
0
            goto result;
3546
0
        }
3547
0
        ww = VIEW_ADDR(w);
3548
0
    }
3549
114
    else {
3550
114
        if (PyObject_GetBuffer(w, &wbuf, PyBUF_FULL_RO) < 0) {
3551
0
            PyErr_Clear();
3552
0
            goto result; /* Py_NotImplemented */
3553
0
        }
3554
114
        ww = &wbuf;
3555
114
    }
3556
3557
114
    if (!equiv_shape(vv, ww)) {
3558
29
        PyErr_Clear();
3559
29
        equal = 0;
3560
29
        goto result;
3561
29
    }
3562
3563
    /* Use fast unpacking for identical primitive C type formats. */
3564
85
    if (get_native_fmtchar(&vfmt, vv->format) < 0)
3565
0
        vfmt = "_";
3566
85
    if (get_native_fmtchar(&wfmt, ww->format) < 0)
3567
0
        wfmt = "_";
3568
85
    if (strcmp(vfmt, "_") == 0 || strcmp(wfmt, "_") == 0 || strcmp(vfmt, wfmt) != 0) {
3569
        /* Use struct module unpacking. NOTE: Even for equal format strings,
3570
           memcmp() cannot be used for item comparison since it would give
3571
           incorrect results in the case of NaNs or uninitialized padding
3572
           bytes. */
3573
0
        vfmt = "_";
3574
0
        unpack_v = struct_get_unpacker(vv->format, vv->itemsize);
3575
0
        if (unpack_v == NULL) {
3576
0
            equal = fix_struct_error_int();
3577
0
            goto result;
3578
0
        }
3579
0
        unpack_w = struct_get_unpacker(ww->format, ww->itemsize);
3580
0
        if (unpack_w == NULL) {
3581
0
            equal = fix_struct_error_int();
3582
0
            goto result;
3583
0
        }
3584
0
    }
3585
3586
85
    if (vv->ndim == 0) {
3587
0
        equal = unpack_cmp(vv->buf, ww->buf,
3588
0
                           vfmt, unpack_v, unpack_w);
3589
0
    }
3590
85
    else if (vv->ndim == 1) {
3591
85
        equal = cmp_base(vv->buf, ww->buf, vv->shape,
3592
85
                         vv->strides, vv->suboffsets,
3593
85
                         ww->strides, ww->suboffsets,
3594
85
                         vfmt, unpack_v, unpack_w);
3595
85
    }
3596
0
    else {
3597
0
        equal = cmp_rec(vv->buf, ww->buf, vv->ndim, vv->shape,
3598
0
                        vv->strides, vv->suboffsets,
3599
0
                        ww->strides, ww->suboffsets,
3600
0
                        vfmt, unpack_v, unpack_w);
3601
0
    }
3602
3603
114
result:
3604
114
    if (equal < 0) {
3605
0
        if (equal == MV_COMPARE_NOT_IMPL)
3606
0
            res = Py_NotImplemented;
3607
0
        else /* exception */
3608
0
            res = NULL;
3609
0
    }
3610
114
    else if ((equal && op == Py_EQ) || (!equal && op == Py_NE))
3611
1
        res = Py_True;
3612
113
    else
3613
113
        res = Py_False;
3614
3615
114
    if (ww == &wbuf)
3616
114
        PyBuffer_Release(ww);
3617
3618
114
    unpacker_free(unpack_v);
3619
114
    unpacker_free(unpack_w);
3620
3621
114
    return Py_XNewRef(res);
3622
85
}
3623
3624
static PyObject *
3625
memory_richcompare(PyObject *v, PyObject *w, int op)
3626
114
{
3627
114
    PyMemoryViewObject *self = (PyMemoryViewObject *)v;
3628
114
    if (memoryview_pin(self) < 0) {
3629
        /* Released memoryviews still compare by identity. */
3630
0
        PyErr_Clear();
3631
0
        return memory_richcompare_pinned(v, w, op);
3632
0
    }
3633
3634
114
    PyMemoryViewObject *other = NULL;
3635
114
    if (PyMemoryView_Check(w) && w != v) {
3636
0
        other = (PyMemoryViewObject *)w;
3637
0
        if (memoryview_pin(other) < 0) {
3638
0
            PyErr_Clear();
3639
0
            memoryview_unpin(self);
3640
0
            return memory_richcompare_pinned(v, w, op);
3641
0
        }
3642
0
    }
3643
3644
114
    PyObject *result = memory_richcompare_pinned(v, w, op);
3645
114
    if (other != NULL) {
3646
0
        memoryview_unpin(other);
3647
0
    }
3648
114
    memoryview_unpin(self);
3649
114
    return result;
3650
114
}
3651
3652
/**************************************************************************/
3653
/*                                Hash                                    */
3654
/**************************************************************************/
3655
3656
static Py_hash_t
3657
memory_hash_pinned(PyObject *_self)
3658
0
{
3659
0
    PyMemoryViewObject *self = (PyMemoryViewObject *)_self;
3660
0
    Py_hash_t hash = FT_ATOMIC_LOAD_SSIZE_RELAXED(self->hash);
3661
0
    if (hash == -1) {
3662
0
        Py_buffer *view = &self->view;
3663
0
        char *mem = view->buf;
3664
0
        Py_ssize_t ret;
3665
0
        const char *fmt;
3666
3667
0
        CHECK_RELEASED_INT(self);
3668
3669
0
        if (!view->readonly) {
3670
0
            PyErr_SetString(PyExc_ValueError,
3671
0
                "cannot hash writable memoryview object");
3672
0
            return -1;
3673
0
        }
3674
0
        ret = get_native_fmtchar(&fmt, view->format);
3675
0
        if (ret < 0 || !IS_BYTE_FORMAT(fmt)) {
3676
0
            PyErr_SetString(PyExc_ValueError,
3677
0
                "memoryview: hashing is restricted to formats 'B', 'b' or 'c'");
3678
0
            return -1;
3679
0
        }
3680
0
        if (view->obj != NULL) {
3681
            // Prevent 'self' from being freed when computing the item's hash.
3682
            // See https://github.com/python/cpython/issues/142664.
3683
#ifdef Py_GIL_DISABLED
3684
            if (memoryview_add_export(self) < 0) {
3685
                return -1;
3686
            }
3687
#else
3688
0
            self->exports++;
3689
0
#endif
3690
0
            Py_hash_t h = PyObject_Hash(view->obj);
3691
0
            FT_ATOMIC_ADD_SSIZE(self->exports, -1);
3692
0
            if (h == -1) {
3693
                /* Keep the original error message */
3694
0
                return -1;
3695
0
            }
3696
0
        }
3697
3698
0
        if (!MV_C_CONTIGUOUS(mv_get_flags(self))) {
3699
0
            mem = PyMem_Malloc(view->len);
3700
0
            if (mem == NULL) {
3701
0
                PyErr_NoMemory();
3702
0
                return -1;
3703
0
            }
3704
0
            if (buffer_to_contiguous(mem, view, 'C') < 0) {
3705
0
                PyMem_Free(mem);
3706
0
                return -1;
3707
0
            }
3708
0
        }
3709
3710
        /* Can't fail */
3711
0
        hash = Py_HashBuffer(mem, view->len);
3712
0
        FT_ATOMIC_STORE_SSIZE_RELAXED(self->hash, hash);
3713
3714
0
        if (mem != view->buf)
3715
0
            PyMem_Free(mem);
3716
0
    }
3717
3718
0
    return hash;
3719
0
}
3720
3721
static Py_hash_t
3722
memory_hash(PyObject *_self)
3723
0
{
3724
0
    PyMemoryViewObject *self = (PyMemoryViewObject *)_self;
3725
0
    Py_hash_t hash = FT_ATOMIC_LOAD_SSIZE_RELAXED(self->hash);
3726
0
    if (hash != -1) {
3727
0
        return hash;
3728
0
    }
3729
0
    if (memoryview_pin(self) < 0) {
3730
0
        return -1;
3731
0
    }
3732
0
    Py_hash_t result = memory_hash_pinned(_self);
3733
0
    memoryview_unpin(self);
3734
0
    return result;
3735
0
}
3736
3737
3738
/**************************************************************************/
3739
/*                                 getters                                */
3740
/**************************************************************************/
3741
3742
static PyObject *
3743
_IntTupleFromSsizet(int len, Py_ssize_t *vals)
3744
0
{
3745
0
    int i;
3746
0
    PyObject *o;
3747
0
    PyObject *intTuple;
3748
3749
0
    if (vals == NULL)
3750
0
        return PyTuple_New(0);
3751
3752
0
    intTuple = PyTuple_New(len);
3753
0
    if (!intTuple)
3754
0
        return NULL;
3755
0
    for (i=0; i<len; i++) {
3756
0
        o = PyLong_FromSsize_t(vals[i]);
3757
0
        if (!o) {
3758
0
            Py_DECREF(intTuple);
3759
0
            return NULL;
3760
0
        }
3761
0
        PyTuple_SET_ITEM(intTuple, i, o);
3762
0
    }
3763
0
    return intTuple;
3764
0
}
3765
3766
static PyObject *
3767
memory_obj_get_pinned(PyObject *_self, void *Py_UNUSED(ignored))
3768
0
{
3769
0
    PyMemoryViewObject *self = (PyMemoryViewObject *)_self;
3770
0
    Py_buffer *view = &self->view;
3771
3772
0
    CHECK_RELEASED(self);
3773
0
    if (view->obj == NULL) {
3774
0
        Py_RETURN_NONE;
3775
0
    }
3776
0
    return Py_NewRef(view->obj);
3777
0
}
3778
3779
static PyObject *
3780
memory_nbytes_get(PyObject *_self, void *Py_UNUSED(ignored))
3781
5
{
3782
5
    PyMemoryViewObject *self = (PyMemoryViewObject *)_self;
3783
5
    CHECK_RELEASED(self);
3784
5
    return PyLong_FromSsize_t(self->view.len);
3785
5
}
3786
3787
static PyObject *
3788
memory_format_get_pinned(PyObject *_self, void *Py_UNUSED(ignored))
3789
0
{
3790
0
    PyMemoryViewObject *self = (PyMemoryViewObject *)_self;
3791
0
    CHECK_RELEASED(self);
3792
0
    return PyUnicode_FromString(self->view.format);
3793
0
}
3794
3795
static PyObject *
3796
memory_itemsize_get(PyObject *_self, void *Py_UNUSED(ignored))
3797
120k
{
3798
120k
    PyMemoryViewObject *self = (PyMemoryViewObject *)_self;
3799
120k
    CHECK_RELEASED(self);
3800
120k
    return PyLong_FromSsize_t(self->view.itemsize);
3801
120k
}
3802
3803
static PyObject *
3804
memory_shape_get(PyObject *_self, void *Py_UNUSED(ignored))
3805
0
{
3806
0
    PyMemoryViewObject *self = (PyMemoryViewObject *)_self;
3807
0
    CHECK_RELEASED(self);
3808
0
    return _IntTupleFromSsizet(self->view.ndim, self->view.shape);
3809
0
}
3810
3811
static PyObject *
3812
memory_strides_get(PyObject *_self, void *Py_UNUSED(ignored))
3813
0
{
3814
0
    PyMemoryViewObject *self = (PyMemoryViewObject *)_self;
3815
0
    CHECK_RELEASED(self);
3816
0
    return _IntTupleFromSsizet(self->view.ndim, self->view.strides);
3817
0
}
3818
3819
static PyObject *
3820
memory_suboffsets_get(PyObject *_self, void *Py_UNUSED(ignored))
3821
0
{
3822
0
    PyMemoryViewObject *self = (PyMemoryViewObject *)_self;
3823
0
    CHECK_RELEASED(self);
3824
0
    return _IntTupleFromSsizet(self->view.ndim, self->view.suboffsets);
3825
0
}
3826
3827
static PyObject *
3828
memory_readonly_get(PyObject *_self, void *Py_UNUSED(ignored))
3829
0
{
3830
0
    PyMemoryViewObject *self = (PyMemoryViewObject *)_self;
3831
0
    CHECK_RELEASED(self);
3832
0
    return PyBool_FromLong(self->view.readonly);
3833
0
}
3834
3835
static PyObject *
3836
memory_ndim_get(PyObject *_self, void *Py_UNUSED(ignored))
3837
0
{
3838
0
    PyMemoryViewObject *self = (PyMemoryViewObject *)_self;
3839
0
    CHECK_RELEASED(self);
3840
0
    return PyLong_FromLong(self->view.ndim);
3841
0
}
3842
3843
static PyObject *
3844
memory_c_contiguous(PyObject *_self, void *Py_UNUSED(ignored))
3845
0
{
3846
0
    PyMemoryViewObject *self = (PyMemoryViewObject *)_self;
3847
0
    CHECK_RELEASED(self);
3848
0
    return PyBool_FromLong(MV_C_CONTIGUOUS(mv_get_flags(self)));
3849
0
}
3850
3851
static PyObject *
3852
memory_f_contiguous(PyObject *_self, void *Py_UNUSED(ignored))
3853
0
{
3854
0
    PyMemoryViewObject *self = (PyMemoryViewObject *)_self;
3855
0
    CHECK_RELEASED(self);
3856
0
    return PyBool_FromLong(MV_F_CONTIGUOUS(mv_get_flags(self)));
3857
0
}
3858
3859
static PyObject *
3860
memory_contiguous(PyObject *_self, void *Py_UNUSED(ignored))
3861
0
{
3862
0
    PyMemoryViewObject *self = (PyMemoryViewObject *)_self;
3863
0
    CHECK_RELEASED(self);
3864
0
    return PyBool_FromLong(MV_ANY_CONTIGUOUS(mv_get_flags(self)));
3865
0
}
3866
3867
#define MEMORYVIEW_PINNED_GETTER(name)                                  \
3868
    static PyObject *                                                   \
3869
    name(PyObject *_self, void *ignored)                                \
3870
0
    {                                                                   \
3871
0
        PyMemoryViewObject *self = (PyMemoryViewObject *)_self;         \
3872
0
        if (memoryview_pin(self) < 0) {                                 \
3873
0
            return NULL;                                                \
3874
0
        }                                                               \
3875
0
        PyObject *result = name##_pinned(_self, ignored);               \
3876
0
        memoryview_unpin(self);                                         \
3877
0
        return result;                                                  \
3878
0
    }
3879
3880
0
MEMORYVIEW_PINNED_GETTER(memory_obj_get)
3881
0
MEMORYVIEW_PINNED_GETTER(memory_format_get)
3882
3883
#undef MEMORYVIEW_PINNED_GETTER
3884
3885
PyDoc_STRVAR(memory_obj_doc,
3886
             "The underlying object of the memoryview.");
3887
PyDoc_STRVAR(memory_nbytes_doc,
3888
             "The amount of space in bytes that the array would use in\n"
3889
             " a contiguous representation.");
3890
PyDoc_STRVAR(memory_readonly_doc,
3891
             "A bool indicating whether the memory is read only.");
3892
PyDoc_STRVAR(memory_itemsize_doc,
3893
             "The size in bytes of each element of the memoryview.");
3894
PyDoc_STRVAR(memory_format_doc,
3895
             "A string containing the format (in struct module style)\n"
3896
             " for each element in the view.");
3897
PyDoc_STRVAR(memory_ndim_doc,
3898
             "An integer indicating how many dimensions of a multi-dimensional\n"
3899
             " array the memory represents.");
3900
PyDoc_STRVAR(memory_shape_doc,
3901
             "A tuple of ndim integers giving the shape of the memory\n"
3902
             " as an N-dimensional array.");
3903
PyDoc_STRVAR(memory_strides_doc,
3904
             "A tuple of ndim integers giving the size in bytes to access\n"
3905
             " each element for each dimension of the array.");
3906
PyDoc_STRVAR(memory_suboffsets_doc,
3907
             "A tuple of integers used internally for PIL-style arrays.");
3908
PyDoc_STRVAR(memory_c_contiguous_doc,
3909
             "A bool indicating whether the memory is C contiguous.");
3910
PyDoc_STRVAR(memory_f_contiguous_doc,
3911
             "A bool indicating whether the memory is Fortran contiguous.");
3912
PyDoc_STRVAR(memory_contiguous_doc,
3913
             "A bool indicating whether the memory is contiguous.");
3914
static PyGetSetDef memory_getsetlist[] = {
3915
    {"obj",             memory_obj_get,        NULL, memory_obj_doc},
3916
    {"nbytes",          memory_nbytes_get,     NULL, memory_nbytes_doc},
3917
    {"readonly",        memory_readonly_get,   NULL, memory_readonly_doc},
3918
    {"itemsize",        memory_itemsize_get,   NULL, memory_itemsize_doc},
3919
    {"format",          memory_format_get,     NULL, memory_format_doc},
3920
    {"ndim",            memory_ndim_get,       NULL, memory_ndim_doc},
3921
    {"shape",           memory_shape_get,      NULL, memory_shape_doc},
3922
    {"strides",         memory_strides_get,    NULL, memory_strides_doc},
3923
    {"suboffsets",      memory_suboffsets_get, NULL, memory_suboffsets_doc},
3924
    {"c_contiguous",    memory_c_contiguous,   NULL, memory_c_contiguous_doc},
3925
    {"f_contiguous",    memory_f_contiguous,   NULL, memory_f_contiguous_doc},
3926
    {"contiguous",      memory_contiguous,     NULL, memory_contiguous_doc},
3927
    {NULL, NULL, NULL, NULL},
3928
};
3929
3930
3931
static PyMethodDef memory_methods[] = {
3932
    MEMORYVIEW_RELEASE_METHODDEF
3933
    MEMORYVIEW_TOBYTES_METHODDEF
3934
    MEMORYVIEW_HEX_METHODDEF
3935
    MEMORYVIEW_TOLIST_METHODDEF
3936
    MEMORYVIEW_CAST_METHODDEF
3937
    MEMORYVIEW_TOREADONLY_METHODDEF
3938
    MEMORYVIEW__FROM_FLAGS_METHODDEF
3939
    MEMORYVIEW_COUNT_METHODDEF
3940
    MEMORYVIEW_INDEX_METHODDEF
3941
    {"__enter__",   memory_enter, METH_NOARGS, NULL},
3942
    MEMORYVIEW___EXIT___METHODDEF
3943
    {"__class_getitem__", Py_GenericAlias, METH_O|METH_CLASS,
3944
     PyDoc_STR("memoryviews are generic over the type of their underlying data")},
3945
    {NULL,          NULL}
3946
};
3947
3948
/**************************************************************************/
3949
/*                          Memoryview Iterator                           */
3950
/**************************************************************************/
3951
3952
PyTypeObject _PyMemoryIter_Type;
3953
3954
typedef struct {
3955
    PyObject_HEAD
3956
    Py_ssize_t it_index;
3957
    PyMemoryViewObject *it_seq; // Set to NULL when iterator is exhausted
3958
    Py_ssize_t it_length;
3959
    const char *it_fmt;
3960
} memoryiterobject;
3961
3962
static void
3963
memoryiter_dealloc(PyObject *self)
3964
0
{
3965
0
    memoryiterobject *it = (memoryiterobject *)self;
3966
0
    _PyObject_GC_UNTRACK(it);
3967
0
    Py_XDECREF(it->it_seq);
3968
0
    PyObject_GC_Del(it);
3969
0
}
3970
3971
static int
3972
memoryiter_traverse(PyObject *self, visitproc visit, void *arg)
3973
0
{
3974
0
    memoryiterobject *it = (memoryiterobject *)self;
3975
0
    Py_VISIT(it->it_seq);
3976
0
    return 0;
3977
0
}
3978
3979
static PyObject *
3980
memoryiter_next(PyObject *self)
3981
0
{
3982
0
    memoryiterobject *it = (memoryiterobject *)self;
3983
0
    PyMemoryViewObject *seq;
3984
0
    Py_ssize_t index;
3985
3986
0
    Py_BEGIN_CRITICAL_SECTION(it);
3987
0
    seq = it->it_seq;
3988
0
    index = it->it_index;
3989
0
    if (seq != NULL) {
3990
0
        if (index >= it->it_length) {
3991
            /* Transfer the iterator's reference to seq before clearing it. */
3992
0
            it->it_seq = NULL;
3993
0
        }
3994
0
        else {
3995
0
            Py_INCREF(seq);
3996
0
        }
3997
0
    }
3998
0
    Py_END_CRITICAL_SECTION();
3999
4000
0
    if (seq == NULL || index >= it->it_length) {
4001
0
        Py_XDECREF(seq);
4002
0
        return NULL;
4003
0
    }
4004
4005
    /* Pin outside the iterator lock: a failed pin may release the buffer. */
4006
0
    if (memoryview_pin(seq) < 0) {
4007
0
        Py_DECREF(seq);
4008
0
        return NULL;
4009
0
    }
4010
4011
0
    Py_BEGIN_CRITICAL_SECTION(it);
4012
0
    index = it->it_index;
4013
0
    if (index < it->it_length) {
4014
0
        it->it_index = index + 1;
4015
0
    }
4016
0
    Py_END_CRITICAL_SECTION();
4017
0
    if (index >= it->it_length) {
4018
0
        memoryview_unpin(seq);
4019
0
        Py_DECREF(seq);
4020
0
        return NULL;
4021
0
    }
4022
4023
0
    Py_buffer *view = &seq->view;
4024
0
    char *ptr = (char *)view->buf;
4025
4026
0
    ptr += view->strides[0] * index;
4027
0
    ptr = ADJUST_PTR(ptr, view->suboffsets, 0);
4028
0
    PyObject *result = NULL;
4029
0
    if (ptr != NULL) {
4030
0
        result = unpack_single(seq, ptr, it->it_fmt);
4031
0
    }
4032
0
    memoryview_unpin(seq);
4033
0
    Py_DECREF(seq);
4034
0
    return result;
4035
0
}
4036
4037
static PyObject *
4038
memory_iter_pinned(PyObject *seq)
4039
0
{
4040
0
    if (!PyMemoryView_Check(seq)) {
4041
0
        PyErr_BadInternalCall();
4042
0
        return NULL;
4043
0
    }
4044
0
    CHECK_RELEASED(seq);
4045
0
    PyMemoryViewObject *obj = (PyMemoryViewObject *)seq;
4046
0
    int ndims = obj->view.ndim;
4047
0
    if (ndims == 0) {
4048
0
        PyErr_SetString(PyExc_TypeError, "invalid indexing of 0-dim memory");
4049
0
        return NULL;
4050
0
    }
4051
0
    if (ndims != 1) {
4052
0
        PyErr_SetString(PyExc_NotImplementedError,
4053
0
            "multi-dimensional sub-views are not implemented");
4054
0
        return NULL;
4055
0
    }
4056
4057
0
    const char *fmt = adjust_fmt(&obj->view);
4058
0
    if (fmt == NULL) {
4059
0
        return NULL;
4060
0
    }
4061
4062
0
    memoryiterobject *it;
4063
0
    it = PyObject_GC_New(memoryiterobject, &_PyMemoryIter_Type);
4064
0
    if (it == NULL) {
4065
0
        return NULL;
4066
0
    }
4067
0
    it->it_fmt = fmt;
4068
0
    it->it_length = memory_length((PyObject *)obj);
4069
0
    it->it_index = 0;
4070
0
    it->it_seq = (PyMemoryViewObject*)Py_NewRef(obj);
4071
0
    _PyObject_GC_TRACK(it);
4072
0
    return (PyObject *)it;
4073
0
}
4074
4075
static PyObject *
4076
memory_iter(PyObject *seq)
4077
0
{
4078
0
    PyMemoryViewObject *self = (PyMemoryViewObject *)seq;
4079
0
    if (memoryview_pin(self) < 0) {
4080
0
        return NULL;
4081
0
    }
4082
0
    PyObject *result = memory_iter_pinned(seq);
4083
0
    memoryview_unpin(self);
4084
0
    return result;
4085
0
}
4086
4087
PyTypeObject _PyMemoryIter_Type = {
4088
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
4089
    .tp_name = "memory_iterator",
4090
    .tp_basicsize = sizeof(memoryiterobject),
4091
    // methods
4092
    .tp_dealloc = memoryiter_dealloc,
4093
    .tp_getattro = PyObject_GenericGetAttr,
4094
    .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
4095
    .tp_traverse = memoryiter_traverse,
4096
    .tp_iter = PyObject_SelfIter,
4097
    .tp_iternext = memoryiter_next,
4098
};
4099
4100
PyTypeObject PyMemoryView_Type = {
4101
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
4102
    "memoryview",                             /* tp_name */
4103
    offsetof(PyMemoryViewObject, ob_array),   /* tp_basicsize */
4104
    sizeof(Py_ssize_t),                       /* tp_itemsize */
4105
    memory_dealloc,                           /* tp_dealloc */
4106
    0,                                        /* tp_vectorcall_offset */
4107
    0,                                        /* tp_getattr */
4108
    0,                                        /* tp_setattr */
4109
    0,                                        /* tp_as_async */
4110
    memory_repr,                              /* tp_repr */
4111
    0,                                        /* tp_as_number */
4112
    &memory_as_sequence,                      /* tp_as_sequence */
4113
    &memory_as_mapping,                       /* tp_as_mapping */
4114
    memory_hash,                              /* tp_hash */
4115
    0,                                        /* tp_call */
4116
    0,                                        /* tp_str */
4117
    PyObject_GenericGetAttr,                  /* tp_getattro */
4118
    0,                                        /* tp_setattro */
4119
    &memory_as_buffer,                        /* tp_as_buffer */
4120
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
4121
       Py_TPFLAGS_SEQUENCE,                   /* tp_flags */
4122
    memoryview__doc__,                        /* tp_doc */
4123
    memory_traverse,                          /* tp_traverse */
4124
    memory_clear,                             /* tp_clear */
4125
    memory_richcompare,                       /* tp_richcompare */
4126
    offsetof(PyMemoryViewObject, weakreflist),/* tp_weaklistoffset */
4127
    memory_iter,                              /* tp_iter */
4128
    0,                                        /* tp_iternext */
4129
    memory_methods,                           /* tp_methods */
4130
    0,                                        /* tp_members */
4131
    memory_getsetlist,                        /* tp_getset */
4132
    0,                                        /* tp_base */
4133
    0,                                        /* tp_dict */
4134
    0,                                        /* tp_descr_get */
4135
    0,                                        /* tp_descr_set */
4136
    0,                                        /* tp_dictoffset */
4137
    0,                                        /* tp_init */
4138
    0,                                        /* tp_alloc */
4139
    memoryview,                               /* tp_new */
4140
    .tp_vectorcall = memoryview_vectorcall,
4141
};