You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3123 lines
89 KiB

  1. /* Memoryview object implementation */
  2. #include "Python.h"
  3. #include <stddef.h>
  4. /****************************************************************************/
  5. /* ManagedBuffer Object */
  6. /****************************************************************************/
  7. /*
  8. ManagedBuffer Object:
  9. ---------------------
  10. The purpose of this object is to facilitate the handling of chained
  11. memoryviews that have the same underlying exporting object. PEP-3118
  12. allows the underlying object to change while a view is exported. This
  13. could lead to unexpected results when constructing a new memoryview
  14. from an existing memoryview.
  15. Rather than repeatedly redirecting buffer requests to the original base
  16. object, all chained memoryviews use a single buffer snapshot. This
  17. snapshot is generated by the constructor _PyManagedBuffer_FromObject().
  18. Ownership rules:
  19. ----------------
  20. The master buffer inside a managed buffer is filled in by the original
  21. base object. shape, strides, suboffsets and format are read-only for
  22. all consumers.
  23. A memoryview's buffer is a private copy of the exporter's buffer. shape,
  24. strides and suboffsets belong to the memoryview and are thus writable.
  25. If a memoryview itself exports several buffers via memory_getbuf(), all
  26. buffer copies share shape, strides and suboffsets. In this case, the
  27. arrays are NOT writable.
  28. Reference count assumptions:
  29. ----------------------------
  30. The 'obj' member of a Py_buffer must either be NULL or refer to the
  31. exporting base object. In the Python codebase, all getbufferprocs
  32. return a new reference to view.obj (example: bytes_buffer_getbuffer()).
  33. PyBuffer_Release() decrements view.obj (if non-NULL), so the
  34. releasebufferprocs must NOT decrement view.obj.
  35. */
  36. #define CHECK_MBUF_RELEASED(mbuf) \
  37. if (((_PyManagedBufferObject *)mbuf)->flags&_Py_MANAGED_BUFFER_RELEASED) { \
  38. PyErr_SetString(PyExc_ValueError, \
  39. "operation forbidden on released memoryview object"); \
  40. return NULL; \
  41. }
  42. Py_LOCAL_INLINE(_PyManagedBufferObject *)
  43. mbuf_alloc(void)
  44. {
  45. _PyManagedBufferObject *mbuf;
  46. mbuf = (_PyManagedBufferObject *)
  47. PyObject_GC_New(_PyManagedBufferObject, &_PyManagedBuffer_Type);
  48. if (mbuf == NULL)
  49. return NULL;
  50. mbuf->flags = 0;
  51. mbuf->exports = 0;
  52. mbuf->master.obj = NULL;
  53. _PyObject_GC_TRACK(mbuf);
  54. return mbuf;
  55. }
  56. static PyObject *
  57. _PyManagedBuffer_FromObject(PyObject *base)
  58. {
  59. _PyManagedBufferObject *mbuf;
  60. mbuf = mbuf_alloc();
  61. if (mbuf == NULL)
  62. return NULL;
  63. if (PyObject_GetBuffer(base, &mbuf->master, PyBUF_FULL_RO) < 0) {
  64. mbuf->master.obj = NULL;
  65. Py_DECREF(mbuf);
  66. return NULL;
  67. }
  68. return (PyObject *)mbuf;
  69. }
  70. static void
  71. mbuf_release(_PyManagedBufferObject *self)
  72. {
  73. if (self->flags&_Py_MANAGED_BUFFER_RELEASED)
  74. return;
  75. /* NOTE: at this point self->exports can still be > 0 if this function
  76. is called from mbuf_clear() to break up a reference cycle. */
  77. self->flags |= _Py_MANAGED_BUFFER_RELEASED;
  78. /* PyBuffer_Release() decrements master->obj and sets it to NULL. */
  79. _PyObject_GC_UNTRACK(self);
  80. PyBuffer_Release(&self->master);
  81. }
  82. static void
  83. mbuf_dealloc(_PyManagedBufferObject *self)
  84. {
  85. assert(self->exports == 0);
  86. mbuf_release(self);
  87. if (self->flags&_Py_MANAGED_BUFFER_FREE_FORMAT)
  88. PyMem_Free(self->master.format);
  89. PyObject_GC_Del(self);
  90. }
  91. static int
  92. mbuf_traverse(_PyManagedBufferObject *self, visitproc visit, void *arg)
  93. {
  94. Py_VISIT(self->master.obj);
  95. return 0;
  96. }
  97. static int
  98. mbuf_clear(_PyManagedBufferObject *self)
  99. {
  100. assert(self->exports >= 0);
  101. mbuf_release(self);
  102. return 0;
  103. }
  104. PyTypeObject _PyManagedBuffer_Type = {
  105. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  106. "managedbuffer",
  107. sizeof(_PyManagedBufferObject),
  108. 0,
  109. (destructor)mbuf_dealloc, /* tp_dealloc */
  110. 0, /* tp_print */
  111. 0, /* tp_getattr */
  112. 0, /* tp_setattr */
  113. 0, /* tp_reserved */
  114. 0, /* tp_repr */
  115. 0, /* tp_as_number */
  116. 0, /* tp_as_sequence */
  117. 0, /* tp_as_mapping */
  118. 0, /* tp_hash */
  119. 0, /* tp_call */
  120. 0, /* tp_str */
  121. PyObject_GenericGetAttr, /* tp_getattro */
  122. 0, /* tp_setattro */
  123. 0, /* tp_as_buffer */
  124. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
  125. 0, /* tp_doc */
  126. (traverseproc)mbuf_traverse, /* tp_traverse */
  127. (inquiry)mbuf_clear /* tp_clear */
  128. };
  129. /****************************************************************************/
  130. /* MemoryView Object */
  131. /****************************************************************************/
  132. /* In the process of breaking reference cycles mbuf_release() can be
  133. called before memory_release(). */
  134. #define BASE_INACCESSIBLE(mv) \
  135. (((PyMemoryViewObject *)mv)->flags&_Py_MEMORYVIEW_RELEASED || \
  136. ((PyMemoryViewObject *)mv)->mbuf->flags&_Py_MANAGED_BUFFER_RELEASED)
  137. #define CHECK_RELEASED(mv) \
  138. if (BASE_INACCESSIBLE(mv)) { \
  139. PyErr_SetString(PyExc_ValueError, \
  140. "operation forbidden on released memoryview object"); \
  141. return NULL; \
  142. }
  143. #define CHECK_RELEASED_INT(mv) \
  144. if (BASE_INACCESSIBLE(mv)) { \
  145. PyErr_SetString(PyExc_ValueError, \
  146. "operation forbidden on released memoryview object"); \
  147. return -1; \
  148. }
  149. #define CHECK_LIST_OR_TUPLE(v) \
  150. if (!PyList_Check(v) && !PyTuple_Check(v)) { \
  151. PyErr_SetString(PyExc_TypeError, \
  152. #v " must be a list or a tuple"); \
  153. return NULL; \
  154. }
  155. #define VIEW_ADDR(mv) (&((PyMemoryViewObject *)mv)->view)
  156. /* Check for the presence of suboffsets in the first dimension. */
  157. #define HAVE_PTR(suboffsets, dim) (suboffsets && suboffsets[dim] >= 0)
  158. /* Adjust ptr if suboffsets are present. */
  159. #define ADJUST_PTR(ptr, suboffsets, dim) \
  160. (HAVE_PTR(suboffsets, dim) ? *((char**)ptr) + suboffsets[dim] : ptr)
  161. /* Memoryview buffer properties */
  162. #define MV_C_CONTIGUOUS(flags) (flags&(_Py_MEMORYVIEW_SCALAR|_Py_MEMORYVIEW_C))
  163. #define MV_F_CONTIGUOUS(flags) \
  164. (flags&(_Py_MEMORYVIEW_SCALAR|_Py_MEMORYVIEW_FORTRAN))
  165. #define MV_ANY_CONTIGUOUS(flags) \
  166. (flags&(_Py_MEMORYVIEW_SCALAR|_Py_MEMORYVIEW_C|_Py_MEMORYVIEW_FORTRAN))
  167. /* Fast contiguity test. Caller must ensure suboffsets==NULL and ndim==1. */
  168. #define MV_CONTIGUOUS_NDIM1(view) \
  169. ((view)->shape[0] == 1 || (view)->strides[0] == (view)->itemsize)
  170. /* getbuffer() requests */
  171. #define REQ_INDIRECT(flags) ((flags&PyBUF_INDIRECT) == PyBUF_INDIRECT)
  172. #define REQ_C_CONTIGUOUS(flags) ((flags&PyBUF_C_CONTIGUOUS) == PyBUF_C_CONTIGUOUS)
  173. #define REQ_F_CONTIGUOUS(flags) ((flags&PyBUF_F_CONTIGUOUS) == PyBUF_F_CONTIGUOUS)
  174. #define REQ_ANY_CONTIGUOUS(flags) ((flags&PyBUF_ANY_CONTIGUOUS) == PyBUF_ANY_CONTIGUOUS)
  175. #define REQ_STRIDES(flags) ((flags&PyBUF_STRIDES) == PyBUF_STRIDES)
  176. #define REQ_SHAPE(flags) ((flags&PyBUF_ND) == PyBUF_ND)
  177. #define REQ_WRITABLE(flags) (flags&PyBUF_WRITABLE)
  178. #define REQ_FORMAT(flags) (flags&PyBUF_FORMAT)
  179. PyDoc_STRVAR(memory_doc,
  180. "memoryview($module, object)\n--\n\
  181. \n\
  182. Create a new memoryview object which references the given object.");
  183. /**************************************************************************/
  184. /* Copy memoryview buffers */
  185. /**************************************************************************/
  186. /* The functions in this section take a source and a destination buffer
  187. with the same logical structure: format, itemsize, ndim and shape
  188. are identical, with ndim > 0.
  189. NOTE: All buffers are assumed to have PyBUF_FULL information, which
  190. is the case for memoryviews! */
  191. /* Assumptions: ndim >= 1. The macro tests for a corner case that should
  192. perhaps be explicitly forbidden in the PEP. */
  193. #define HAVE_SUBOFFSETS_IN_LAST_DIM(view) \
  194. (view->suboffsets && view->suboffsets[dest->ndim-1] >= 0)
  195. Py_LOCAL_INLINE(int)
  196. last_dim_is_contiguous(const Py_buffer *dest, const Py_buffer *src)
  197. {
  198. assert(dest->ndim > 0 && src->ndim > 0);
  199. return (!HAVE_SUBOFFSETS_IN_LAST_DIM(dest) &&
  200. !HAVE_SUBOFFSETS_IN_LAST_DIM(src) &&
  201. dest->strides[dest->ndim-1] == dest->itemsize &&
  202. src->strides[src->ndim-1] == src->itemsize);
  203. }
  204. /* This is not a general function for determining format equivalence.
  205. It is used in copy_single() and copy_buffer() to weed out non-matching
  206. formats. Skipping the '@' character is specifically used in slice
  207. assignments, where the lvalue is already known to have a single character
  208. format. This is a performance hack that could be rewritten (if properly
  209. benchmarked). */
  210. Py_LOCAL_INLINE(int)
  211. equiv_format(const Py_buffer *dest, const Py_buffer *src)
  212. {
  213. const char *dfmt, *sfmt;
  214. assert(dest->format && src->format);
  215. dfmt = dest->format[0] == '@' ? dest->format+1 : dest->format;
  216. sfmt = src->format[0] == '@' ? src->format+1 : src->format;
  217. if (strcmp(dfmt, sfmt) != 0 ||
  218. dest->itemsize != src->itemsize) {
  219. return 0;
  220. }
  221. return 1;
  222. }
  223. /* Two shapes are equivalent if they are either equal or identical up
  224. to a zero element at the same position. For example, in NumPy arrays
  225. the shapes [1, 0, 5] and [1, 0, 7] are equivalent. */
  226. Py_LOCAL_INLINE(int)
  227. equiv_shape(const Py_buffer *dest, const Py_buffer *src)
  228. {
  229. int i;
  230. if (dest->ndim != src->ndim)
  231. return 0;
  232. for (i = 0; i < dest->ndim; i++) {
  233. if (dest->shape[i] != src->shape[i])
  234. return 0;
  235. if (dest->shape[i] == 0)
  236. break;
  237. }
  238. return 1;
  239. }
  240. /* Check that the logical structure of the destination and source buffers
  241. is identical. */
  242. static int
  243. equiv_structure(const Py_buffer *dest, const Py_buffer *src)
  244. {
  245. if (!equiv_format(dest, src) ||
  246. !equiv_shape(dest, src)) {
  247. PyErr_SetString(PyExc_ValueError,
  248. "memoryview assignment: lvalue and rvalue have different "
  249. "structures");
  250. return 0;
  251. }
  252. return 1;
  253. }
  254. /* Base case for recursive multi-dimensional copying. Contiguous arrays are
  255. copied with very little overhead. Assumptions: ndim == 1, mem == NULL or
  256. sizeof(mem) == shape[0] * itemsize. */
  257. static void
  258. copy_base(const Py_ssize_t *shape, Py_ssize_t itemsize,
  259. char *dptr, const Py_ssize_t *dstrides, const Py_ssize_t *dsuboffsets,
  260. char *sptr, const Py_ssize_t *sstrides, const Py_ssize_t *ssuboffsets,
  261. char *mem)
  262. {
  263. if (mem == NULL) { /* contiguous */
  264. Py_ssize_t size = shape[0] * itemsize;
  265. if (dptr + size < sptr || sptr + size < dptr)
  266. memcpy(dptr, sptr, size); /* no overlapping */
  267. else
  268. memmove(dptr, sptr, size);
  269. }
  270. else {
  271. char *p;
  272. Py_ssize_t i;
  273. for (i=0, p=mem; i < shape[0]; p+=itemsize, sptr+=sstrides[0], i++) {
  274. char *xsptr = ADJUST_PTR(sptr, ssuboffsets, 0);
  275. memcpy(p, xsptr, itemsize);
  276. }
  277. for (i=0, p=mem; i < shape[0]; p+=itemsize, dptr+=dstrides[0], i++) {
  278. char *xdptr = ADJUST_PTR(dptr, dsuboffsets, 0);
  279. memcpy(xdptr, p, itemsize);
  280. }
  281. }
  282. }
  283. /* Recursively copy a source buffer to a destination buffer. The two buffers
  284. have the same ndim, shape and itemsize. */
  285. static void
  286. copy_rec(const Py_ssize_t *shape, Py_ssize_t ndim, Py_ssize_t itemsize,
  287. char *dptr, const Py_ssize_t *dstrides, const Py_ssize_t *dsuboffsets,
  288. char *sptr, const Py_ssize_t *sstrides, const Py_ssize_t *ssuboffsets,
  289. char *mem)
  290. {
  291. Py_ssize_t i;
  292. assert(ndim >= 1);
  293. if (ndim == 1) {
  294. copy_base(shape, itemsize,
  295. dptr, dstrides, dsuboffsets,
  296. sptr, sstrides, ssuboffsets,
  297. mem);
  298. return;
  299. }
  300. for (i = 0; i < shape[0]; dptr+=dstrides[0], sptr+=sstrides[0], i++) {
  301. char *xdptr = ADJUST_PTR(dptr, dsuboffsets, 0);
  302. char *xsptr = ADJUST_PTR(sptr, ssuboffsets, 0);
  303. copy_rec(shape+1, ndim-1, itemsize,
  304. xdptr, dstrides+1, dsuboffsets ? dsuboffsets+1 : NULL,
  305. xsptr, sstrides+1, ssuboffsets ? ssuboffsets+1 : NULL,
  306. mem);
  307. }
  308. }
  309. /* Faster copying of one-dimensional arrays. */
  310. static int
  311. copy_single(Py_buffer *dest, Py_buffer *src)
  312. {
  313. char *mem = NULL;
  314. assert(dest->ndim == 1);
  315. if (!equiv_structure(dest, src))
  316. return -1;
  317. if (!last_dim_is_contiguous(dest, src)) {
  318. mem = PyMem_Malloc(dest->shape[0] * dest->itemsize);
  319. if (mem == NULL) {
  320. PyErr_NoMemory();
  321. return -1;
  322. }
  323. }
  324. copy_base(dest->shape, dest->itemsize,
  325. dest->buf, dest->strides, dest->suboffsets,
  326. src->buf, src->strides, src->suboffsets,
  327. mem);
  328. if (mem)
  329. PyMem_Free(mem);
  330. return 0;
  331. }
  332. /* Recursively copy src to dest. Both buffers must have the same basic
  333. structure. Copying is atomic, the function never fails with a partial
  334. copy. */
  335. static int
  336. copy_buffer(Py_buffer *dest, Py_buffer *src)
  337. {
  338. char *mem = NULL;
  339. assert(dest->ndim > 0);
  340. if (!equiv_structure(dest, src))
  341. return -1;
  342. if (!last_dim_is_contiguous(dest, src)) {
  343. mem = PyMem_Malloc(dest->shape[dest->ndim-1] * dest->itemsize);
  344. if (mem == NULL) {
  345. PyErr_NoMemory();
  346. return -1;
  347. }
  348. }
  349. copy_rec(dest->shape, dest->ndim, dest->itemsize,
  350. dest->buf, dest->strides, dest->suboffsets,
  351. src->buf, src->strides, src->suboffsets,
  352. mem);
  353. if (mem)
  354. PyMem_Free(mem);
  355. return 0;
  356. }
  357. /* Initialize strides for a C-contiguous array. */
  358. Py_LOCAL_INLINE(void)
  359. init_strides_from_shape(Py_buffer *view)
  360. {
  361. Py_ssize_t i;
  362. assert(view->ndim > 0);
  363. view->strides[view->ndim-1] = view->itemsize;
  364. for (i = view->ndim-2; i >= 0; i--)
  365. view->strides[i] = view->strides[i+1] * view->shape[i+1];
  366. }
  367. /* Initialize strides for a Fortran-contiguous array. */
  368. Py_LOCAL_INLINE(void)
  369. init_fortran_strides_from_shape(Py_buffer *view)
  370. {
  371. Py_ssize_t i;
  372. assert(view->ndim > 0);
  373. view->strides[0] = view->itemsize;
  374. for (i = 1; i < view->ndim; i++)
  375. view->strides[i] = view->strides[i-1] * view->shape[i-1];
  376. }
  377. /* Copy src to a contiguous representation. order is one of 'C', 'F' (Fortran)
  378. or 'A' (Any). Assumptions: src has PyBUF_FULL information, src->ndim >= 1,
  379. len(mem) == src->len. */
  380. static int
  381. buffer_to_contiguous(char *mem, Py_buffer *src, char order)
  382. {
  383. Py_buffer dest;
  384. Py_ssize_t *strides;
  385. int ret;
  386. assert(src->ndim >= 1);
  387. assert(src->shape != NULL);
  388. assert(src->strides != NULL);
  389. strides = PyMem_Malloc(src->ndim * (sizeof *src->strides));
  390. if (strides == NULL) {
  391. PyErr_NoMemory();
  392. return -1;
  393. }
  394. /* initialize dest */
  395. dest = *src;
  396. dest.buf = mem;
  397. /* shape is constant and shared: the logical representation of the
  398. array is unaltered. */
  399. /* The physical representation determined by strides (and possibly
  400. suboffsets) may change. */
  401. dest.strides = strides;
  402. if (order == 'C' || order == 'A') {
  403. init_strides_from_shape(&dest);
  404. }
  405. else {
  406. init_fortran_strides_from_shape(&dest);
  407. }
  408. dest.suboffsets = NULL;
  409. ret = copy_buffer(&dest, src);
  410. PyMem_Free(strides);
  411. return ret;
  412. }
  413. /****************************************************************************/
  414. /* Constructors */
  415. /****************************************************************************/
  416. /* Initialize values that are shared with the managed buffer. */
  417. Py_LOCAL_INLINE(void)
  418. init_shared_values(Py_buffer *dest, const Py_buffer *src)
  419. {
  420. dest->obj = src->obj;
  421. dest->buf = src->buf;
  422. dest->len = src->len;
  423. dest->itemsize = src->itemsize;
  424. dest->readonly = src->readonly;
  425. dest->format = src->format ? src->format : "B";
  426. dest->internal = src->internal;
  427. }
  428. /* Copy shape and strides. Reconstruct missing values. */
  429. static void
  430. init_shape_strides(Py_buffer *dest, const Py_buffer *src)
  431. {
  432. Py_ssize_t i;
  433. if (src->ndim == 0) {
  434. dest->shape = NULL;
  435. dest->strides = NULL;
  436. return;
  437. }
  438. if (src->ndim == 1) {
  439. dest->shape[0] = src->shape ? src->shape[0] : src->len / src->itemsize;
  440. dest->strides[0] = src->strides ? src->strides[0] : src->itemsize;
  441. return;
  442. }
  443. for (i = 0; i < src->ndim; i++)
  444. dest->shape[i] = src->shape[i];
  445. if (src->strides) {
  446. for (i = 0; i < src->ndim; i++)
  447. dest->strides[i] = src->strides[i];
  448. }
  449. else {
  450. init_strides_from_shape(dest);
  451. }
  452. }
  453. Py_LOCAL_INLINE(void)
  454. init_suboffsets(Py_buffer *dest, const Py_buffer *src)
  455. {
  456. Py_ssize_t i;
  457. if (src->suboffsets == NULL) {
  458. dest->suboffsets = NULL;
  459. return;
  460. }
  461. for (i = 0; i < src->ndim; i++)
  462. dest->suboffsets[i] = src->suboffsets[i];
  463. }
  464. /* len = product(shape) * itemsize */
  465. Py_LOCAL_INLINE(void)
  466. init_len(Py_buffer *view)
  467. {
  468. Py_ssize_t i, len;
  469. len = 1;
  470. for (i = 0; i < view->ndim; i++)
  471. len *= view->shape[i];
  472. len *= view->itemsize;
  473. view->len = len;
  474. }
  475. /* Initialize memoryview buffer properties. */
  476. static void
  477. init_flags(PyMemoryViewObject *mv)
  478. {
  479. const Py_buffer *view = &mv->view;
  480. int flags = 0;
  481. switch (view->ndim) {
  482. case 0:
  483. flags |= (_Py_MEMORYVIEW_SCALAR|_Py_MEMORYVIEW_C|
  484. _Py_MEMORYVIEW_FORTRAN);
  485. break;
  486. case 1:
  487. if (MV_CONTIGUOUS_NDIM1(view))
  488. flags |= (_Py_MEMORYVIEW_C|_Py_MEMORYVIEW_FORTRAN);
  489. break;
  490. default:
  491. if (PyBuffer_IsContiguous(view, 'C'))
  492. flags |= _Py_MEMORYVIEW_C;
  493. if (PyBuffer_IsContiguous(view, 'F'))
  494. flags |= _Py_MEMORYVIEW_FORTRAN;
  495. break;
  496. }
  497. if (view->suboffsets) {
  498. flags |= _Py_MEMORYVIEW_PIL;
  499. flags &= ~(_Py_MEMORYVIEW_C|_Py_MEMORYVIEW_FORTRAN);
  500. }
  501. mv->flags = flags;
  502. }
  503. /* Allocate a new memoryview and perform basic initialization. New memoryviews
  504. are exclusively created through the mbuf_add functions. */
  505. Py_LOCAL_INLINE(PyMemoryViewObject *)
  506. memory_alloc(int ndim)
  507. {
  508. PyMemoryViewObject *mv;
  509. mv = (PyMemoryViewObject *)
  510. PyObject_GC_NewVar(PyMemoryViewObject, &PyMemoryView_Type, 3*ndim);
  511. if (mv == NULL)
  512. return NULL;
  513. mv->mbuf = NULL;
  514. mv->hash = -1;
  515. mv->flags = 0;
  516. mv->exports = 0;
  517. mv->view.ndim = ndim;
  518. mv->view.shape = mv->ob_array;
  519. mv->view.strides = mv->ob_array + ndim;
  520. mv->view.suboffsets = mv->ob_array + 2 * ndim;
  521. mv->weakreflist = NULL;
  522. _PyObject_GC_TRACK(mv);
  523. return mv;
  524. }
  525. /*
  526. Return a new memoryview that is registered with mbuf. If src is NULL,
  527. use mbuf->master as the underlying buffer. Otherwise, use src.
  528. The new memoryview has full buffer information: shape and strides
  529. are always present, suboffsets as needed. Arrays are copied to
  530. the memoryview's ob_array field.
  531. */
  532. static PyObject *
  533. mbuf_add_view(_PyManagedBufferObject *mbuf, const Py_buffer *src)
  534. {
  535. PyMemoryViewObject *mv;
  536. Py_buffer *dest;
  537. if (src == NULL)
  538. src = &mbuf->master;
  539. if (src->ndim > PyBUF_MAX_NDIM) {
  540. PyErr_SetString(PyExc_ValueError,
  541. "memoryview: number of dimensions must not exceed "
  542. Py_STRINGIFY(PyBUF_MAX_NDIM));
  543. return NULL;
  544. }
  545. mv = memory_alloc(src->ndim);
  546. if (mv == NULL)
  547. return NULL;
  548. dest = &mv->view;
  549. init_shared_values(dest, src);
  550. init_shape_strides(dest, src);
  551. init_suboffsets(dest, src);
  552. init_flags(mv);
  553. mv->mbuf = mbuf;
  554. Py_INCREF(mbuf);
  555. mbuf->exports++;
  556. return (PyObject *)mv;
  557. }
  558. /* Register an incomplete view: shape, strides, suboffsets and flags still
  559. need to be initialized. Use 'ndim' instead of src->ndim to determine the
  560. size of the memoryview's ob_array.
  561. Assumption: ndim <= PyBUF_MAX_NDIM. */
  562. static PyObject *
  563. mbuf_add_incomplete_view(_PyManagedBufferObject *mbuf, const Py_buffer *src,
  564. int ndim)
  565. {
  566. PyMemoryViewObject *mv;
  567. Py_buffer *dest;
  568. if (src == NULL)
  569. src = &mbuf->master;
  570. assert(ndim <= PyBUF_MAX_NDIM);
  571. mv = memory_alloc(ndim);
  572. if (mv == NULL)
  573. return NULL;
  574. dest = &mv->view;
  575. init_shared_values(dest, src);
  576. mv->mbuf = mbuf;
  577. Py_INCREF(mbuf);
  578. mbuf->exports++;
  579. return (PyObject *)mv;
  580. }
  581. /* Expose a raw memory area as a view of contiguous bytes. flags can be
  582. PyBUF_READ or PyBUF_WRITE. view->format is set to "B" (unsigned bytes).
  583. The memoryview has complete buffer information. */
  584. PyObject *
  585. PyMemoryView_FromMemory(char *mem, Py_ssize_t size, int flags)
  586. {
  587. _PyManagedBufferObject *mbuf;
  588. PyObject *mv;
  589. int readonly;
  590. assert(mem != NULL);
  591. assert(flags == PyBUF_READ || flags == PyBUF_WRITE);
  592. mbuf = mbuf_alloc();
  593. if (mbuf == NULL)
  594. return NULL;
  595. readonly = (flags == PyBUF_WRITE) ? 0 : 1;
  596. (void)PyBuffer_FillInfo(&mbuf->master, NULL, mem, size, readonly,
  597. PyBUF_FULL_RO);
  598. mv = mbuf_add_view(mbuf, NULL);
  599. Py_DECREF(mbuf);
  600. return mv;
  601. }
  602. /* Create a memoryview from a given Py_buffer. For simple byte views,
  603. PyMemoryView_FromMemory() should be used instead.
  604. This function is the only entry point that can create a master buffer
  605. without full information. Because of this fact init_shape_strides()
  606. must be able to reconstruct missing values. */
  607. PyObject *
  608. PyMemoryView_FromBuffer(Py_buffer *info)
  609. {
  610. _PyManagedBufferObject *mbuf;
  611. PyObject *mv;
  612. if (info->buf == NULL) {
  613. PyErr_SetString(PyExc_ValueError,
  614. "PyMemoryView_FromBuffer(): info->buf must not be NULL");
  615. return NULL;
  616. }
  617. mbuf = mbuf_alloc();
  618. if (mbuf == NULL)
  619. return NULL;
  620. /* info->obj is either NULL or a borrowed reference. This reference
  621. should not be decremented in PyBuffer_Release(). */
  622. mbuf->master = *info;
  623. mbuf->master.obj = NULL;
  624. mv = mbuf_add_view(mbuf, NULL);
  625. Py_DECREF(mbuf);
  626. return mv;
  627. }
  628. /* Create a memoryview from an object that implements the buffer protocol.
  629. If the object is a memoryview, the new memoryview must be registered
  630. with the same managed buffer. Otherwise, a new managed buffer is created. */
  631. PyObject *
  632. PyMemoryView_FromObject(PyObject *v)
  633. {
  634. _PyManagedBufferObject *mbuf;
  635. if (PyMemoryView_Check(v)) {
  636. PyMemoryViewObject *mv = (PyMemoryViewObject *)v;
  637. CHECK_RELEASED(mv);
  638. return mbuf_add_view(mv->mbuf, &mv->view);
  639. }
  640. else if (PyObject_CheckBuffer(v)) {
  641. PyObject *ret;
  642. mbuf = (_PyManagedBufferObject *)_PyManagedBuffer_FromObject(v);
  643. if (mbuf == NULL)
  644. return NULL;
  645. ret = mbuf_add_view(mbuf, NULL);
  646. Py_DECREF(mbuf);
  647. return ret;
  648. }
  649. PyErr_Format(PyExc_TypeError,
  650. "memoryview: a bytes-like object is required, not '%.200s'",
  651. Py_TYPE(v)->tp_name);
  652. return NULL;
  653. }
  654. /* Copy the format string from a base object that might vanish. */
  655. static int
  656. mbuf_copy_format(_PyManagedBufferObject *mbuf, const char *fmt)
  657. {
  658. if (fmt != NULL) {
  659. char *cp = PyMem_Malloc(strlen(fmt)+1);
  660. if (cp == NULL) {
  661. PyErr_NoMemory();
  662. return -1;
  663. }
  664. mbuf->master.format = strcpy(cp, fmt);
  665. mbuf->flags |= _Py_MANAGED_BUFFER_FREE_FORMAT;
  666. }
  667. return 0;
  668. }
  669. /*
  670. Return a memoryview that is based on a contiguous copy of src.
  671. Assumptions: src has PyBUF_FULL_RO information, src->ndim > 0.
  672. Ownership rules:
  673. 1) As usual, the returned memoryview has a private copy
  674. of src->shape, src->strides and src->suboffsets.
  675. 2) src->format is copied to the master buffer and released
  676. in mbuf_dealloc(). The releasebufferproc of the bytes
  677. object is NULL, so it does not matter that mbuf_release()
  678. passes the altered format pointer to PyBuffer_Release().
  679. */
  680. static PyObject *
  681. memory_from_contiguous_copy(Py_buffer *src, char order)
  682. {
  683. _PyManagedBufferObject *mbuf;
  684. PyMemoryViewObject *mv;
  685. PyObject *bytes;
  686. Py_buffer *dest;
  687. int i;
  688. assert(src->ndim > 0);
  689. assert(src->shape != NULL);
  690. bytes = PyBytes_FromStringAndSize(NULL, src->len);
  691. if (bytes == NULL)
  692. return NULL;
  693. mbuf = (_PyManagedBufferObject *)_PyManagedBuffer_FromObject(bytes);
  694. Py_DECREF(bytes);
  695. if (mbuf == NULL)
  696. return NULL;
  697. if (mbuf_copy_format(mbuf, src->format) < 0) {
  698. Py_DECREF(mbuf);
  699. return NULL;
  700. }
  701. mv = (PyMemoryViewObject *)mbuf_add_incomplete_view(mbuf, NULL, src->ndim);
  702. Py_DECREF(mbuf);
  703. if (mv == NULL)
  704. return NULL;
  705. dest = &mv->view;
  706. /* shared values are initialized correctly except for itemsize */
  707. dest->itemsize = src->itemsize;
  708. /* shape and strides */
  709. for (i = 0; i < src->ndim; i++) {
  710. dest->shape[i] = src->shape[i];
  711. }
  712. if (order == 'C' || order == 'A') {
  713. init_strides_from_shape(dest);
  714. }
  715. else {
  716. init_fortran_strides_from_shape(dest);
  717. }
  718. /* suboffsets */
  719. dest->suboffsets = NULL;
  720. /* flags */
  721. init_flags(mv);
  722. if (copy_buffer(dest, src) < 0) {
  723. Py_DECREF(mv);
  724. return NULL;
  725. }
  726. return (PyObject *)mv;
  727. }
  728. /*
  729. Return a new memoryview object based on a contiguous exporter with
  730. buffertype={PyBUF_READ, PyBUF_WRITE} and order={'C', 'F'ortran, or 'A'ny}.
  731. The logical structure of the input and output buffers is the same
  732. (i.e. tolist(input) == tolist(output)), but the physical layout in
  733. memory can be explicitly chosen.
  734. As usual, if buffertype=PyBUF_WRITE, the exporter's buffer must be writable,
  735. otherwise it may be writable or read-only.
  736. If the exporter is already contiguous with the desired target order,
  737. the memoryview will be directly based on the exporter.
  738. Otherwise, if the buffertype is PyBUF_READ, the memoryview will be
  739. based on a new bytes object. If order={'C', 'A'ny}, use 'C' order,
  740. 'F'ortran order otherwise.
  741. */
  742. PyObject *
  743. PyMemoryView_GetContiguous(PyObject *obj, int buffertype, char order)
  744. {
  745. PyMemoryViewObject *mv;
  746. PyObject *ret;
  747. Py_buffer *view;
  748. assert(buffertype == PyBUF_READ || buffertype == PyBUF_WRITE);
  749. assert(order == 'C' || order == 'F' || order == 'A');
  750. mv = (PyMemoryViewObject *)PyMemoryView_FromObject(obj);
  751. if (mv == NULL)
  752. return NULL;
  753. view = &mv->view;
  754. if (buffertype == PyBUF_WRITE && view->readonly) {
  755. PyErr_SetString(PyExc_BufferError,
  756. "underlying buffer is not writable");
  757. Py_DECREF(mv);
  758. return NULL;
  759. }
  760. if (PyBuffer_IsContiguous(view, order))
  761. return (PyObject *)mv;
  762. if (buffertype == PyBUF_WRITE) {
  763. PyErr_SetString(PyExc_BufferError,
  764. "writable contiguous buffer requested "
  765. "for a non-contiguous object.");
  766. Py_DECREF(mv);
  767. return NULL;
  768. }
  769. ret = memory_from_contiguous_copy(view, order);
  770. Py_DECREF(mv);
  771. return ret;
  772. }
  773. static PyObject *
  774. memory_new(PyTypeObject *subtype, PyObject *args, PyObject *kwds)
  775. {
  776. PyObject *obj;
  777. static char *kwlist[] = {"object", NULL};
  778. if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:memoryview", kwlist,
  779. &obj)) {
  780. return NULL;
  781. }
  782. return PyMemoryView_FromObject(obj);
  783. }
  784. /****************************************************************************/
  785. /* Previously in abstract.c */
  786. /****************************************************************************/
  787. typedef struct {
  788. Py_buffer view;
  789. Py_ssize_t array[1];
  790. } Py_buffer_full;
  791. int
  792. PyBuffer_ToContiguous(void *buf, Py_buffer *src, Py_ssize_t len, char order)
  793. {
  794. Py_buffer_full *fb = NULL;
  795. int ret;
  796. assert(order == 'C' || order == 'F' || order == 'A');
  797. if (len != src->len) {
  798. PyErr_SetString(PyExc_ValueError,
  799. "PyBuffer_ToContiguous: len != view->len");
  800. return -1;
  801. }
  802. if (PyBuffer_IsContiguous(src, order)) {
  803. memcpy((char *)buf, src->buf, len);
  804. return 0;
  805. }
  806. /* buffer_to_contiguous() assumes PyBUF_FULL */
  807. fb = PyMem_Malloc(sizeof *fb + 3 * src->ndim * (sizeof *fb->array));
  808. if (fb == NULL) {
  809. PyErr_NoMemory();
  810. return -1;
  811. }
  812. fb->view.ndim = src->ndim;
  813. fb->view.shape = fb->array;
  814. fb->view.strides = fb->array + src->ndim;
  815. fb->view.suboffsets = fb->array + 2 * src->ndim;
  816. init_shared_values(&fb->view, src);
  817. init_shape_strides(&fb->view, src);
  818. init_suboffsets(&fb->view, src);
  819. src = &fb->view;
  820. ret = buffer_to_contiguous(buf, src, order);
  821. PyMem_Free(fb);
  822. return ret;
  823. }
  824. /****************************************************************************/
  825. /* Release/GC management */
  826. /****************************************************************************/
  827. /* Inform the managed buffer that this particular memoryview will not access
  828. the underlying buffer again. If no other memoryviews are registered with
  829. the managed buffer, the underlying buffer is released instantly and
  830. marked as inaccessible for both the memoryview and the managed buffer.
  831. This function fails if the memoryview itself has exported buffers. */
  832. static int
  833. _memory_release(PyMemoryViewObject *self)
  834. {
  835. if (self->flags & _Py_MEMORYVIEW_RELEASED)
  836. return 0;
  837. if (self->exports == 0) {
  838. self->flags |= _Py_MEMORYVIEW_RELEASED;
  839. assert(self->mbuf->exports > 0);
  840. if (--self->mbuf->exports == 0)
  841. mbuf_release(self->mbuf);
  842. return 0;
  843. }
  844. if (self->exports > 0) {
  845. PyErr_Format(PyExc_BufferError,
  846. "memoryview has %zd exported buffer%s", self->exports,
  847. self->exports==1 ? "" : "s");
  848. return -1;
  849. }
  850. Py_FatalError("_memory_release(): negative export count");
  851. return -1;
  852. }
  853. static PyObject *
  854. memory_release(PyMemoryViewObject *self, PyObject *noargs)
  855. {
  856. if (_memory_release(self) < 0)
  857. return NULL;
  858. Py_RETURN_NONE;
  859. }
  860. static void
  861. memory_dealloc(PyMemoryViewObject *self)
  862. {
  863. assert(self->exports == 0);
  864. _PyObject_GC_UNTRACK(self);
  865. (void)_memory_release(self);
  866. Py_CLEAR(self->mbuf);
  867. if (self->weakreflist != NULL)
  868. PyObject_ClearWeakRefs((PyObject *) self);
  869. PyObject_GC_Del(self);
  870. }
  871. static int
  872. memory_traverse(PyMemoryViewObject *self, visitproc visit, void *arg)
  873. {
  874. Py_VISIT(self->mbuf);
  875. return 0;
  876. }
  877. static int
  878. memory_clear(PyMemoryViewObject *self)
  879. {
  880. (void)_memory_release(self);
  881. Py_CLEAR(self->mbuf);
  882. return 0;
  883. }
  884. static PyObject *
  885. memory_enter(PyObject *self, PyObject *args)
  886. {
  887. CHECK_RELEASED(self);
  888. Py_INCREF(self);
  889. return self;
  890. }
  891. static PyObject *
  892. memory_exit(PyObject *self, PyObject *args)
  893. {
  894. return memory_release((PyMemoryViewObject *)self, NULL);
  895. }
  896. /****************************************************************************/
  897. /* Casting format and shape */
  898. /****************************************************************************/
  899. #define IS_BYTE_FORMAT(f) (f == 'b' || f == 'B' || f == 'c')
  900. Py_LOCAL_INLINE(Py_ssize_t)
  901. get_native_fmtchar(char *result, const char *fmt)
  902. {
  903. Py_ssize_t size = -1;
  904. if (fmt[0] == '@') fmt++;
  905. switch (fmt[0]) {
  906. case 'c': case 'b': case 'B': size = sizeof(char); break;
  907. case 'h': case 'H': size = sizeof(short); break;
  908. case 'i': case 'I': size = sizeof(int); break;
  909. case 'l': case 'L': size = sizeof(long); break;
  910. #ifdef HAVE_LONG_LONG
  911. case 'q': case 'Q': size = sizeof(PY_LONG_LONG); break;
  912. #endif
  913. case 'n': case 'N': size = sizeof(Py_ssize_t); break;
  914. case 'f': size = sizeof(float); break;
  915. case 'd': size = sizeof(double); break;
  916. #ifdef HAVE_C99_BOOL
  917. case '?': size = sizeof(_Bool); break;
  918. #else
  919. case '?': size = sizeof(char); break;
  920. #endif
  921. case 'P': size = sizeof(void *); break;
  922. }
  923. if (size > 0 && fmt[1] == '\0') {
  924. *result = fmt[0];
  925. return size;
  926. }
  927. return -1;
  928. }
  929. Py_LOCAL_INLINE(char *)
  930. get_native_fmtstr(const char *fmt)
  931. {
  932. int at = 0;
  933. if (fmt[0] == '@') {
  934. at = 1;
  935. fmt++;
  936. }
  937. if (fmt[0] == '\0' || fmt[1] != '\0') {
  938. return NULL;
  939. }
  940. #define RETURN(s) do { return at ? "@" s : s; } while (0)
  941. switch (fmt[0]) {
  942. case 'c': RETURN("c");
  943. case 'b': RETURN("b");
  944. case 'B': RETURN("B");
  945. case 'h': RETURN("h");
  946. case 'H': RETURN("H");
  947. case 'i': RETURN("i");
  948. case 'I': RETURN("I");
  949. case 'l': RETURN("l");
  950. case 'L': RETURN("L");
  951. #ifdef HAVE_LONG_LONG
  952. case 'q': RETURN("q");
  953. case 'Q': RETURN("Q");
  954. #endif
  955. case 'n': RETURN("n");
  956. case 'N': RETURN("N");
  957. case 'f': RETURN("f");
  958. case 'd': RETURN("d");
  959. #ifdef HAVE_C99_BOOL
  960. case '?': RETURN("?");
  961. #else
  962. case '?': RETURN("?");
  963. #endif
  964. case 'P': RETURN("P");
  965. }
  966. return NULL;
  967. }
  968. /* Cast a memoryview's data type to 'format'. The input array must be
  969. C-contiguous. At least one of input-format, output-format must have
  970. byte size. The output array is 1-D, with the same byte length as the
  971. input array. Thus, view->len must be a multiple of the new itemsize. */
  972. static int
  973. cast_to_1D(PyMemoryViewObject *mv, PyObject *format)
  974. {
  975. Py_buffer *view = &mv->view;
  976. PyObject *asciifmt;
  977. char srcchar, destchar;
  978. Py_ssize_t itemsize;
  979. int ret = -1;
  980. assert(view->ndim >= 1);
  981. assert(Py_SIZE(mv) == 3*view->ndim);
  982. assert(view->shape == mv->ob_array);
  983. assert(view->strides == mv->ob_array + view->ndim);
  984. assert(view->suboffsets == mv->ob_array + 2*view->ndim);
  985. if (get_native_fmtchar(&srcchar, view->format) < 0) {
  986. PyErr_SetString(PyExc_ValueError,
  987. "memoryview: source format must be a native single character "
  988. "format prefixed with an optional '@'");
  989. return ret;
  990. }
  991. asciifmt = PyUnicode_AsASCIIString(format);
  992. if (asciifmt == NULL)
  993. return ret;
  994. itemsize = get_native_fmtchar(&destchar, PyBytes_AS_STRING(asciifmt));
  995. if (itemsize < 0) {
  996. PyErr_SetString(PyExc_ValueError,
  997. "memoryview: destination format must be a native single "
  998. "character format prefixed with an optional '@'");
  999. goto out;
  1000. }
  1001. if (!IS_BYTE_FORMAT(srcchar) && !IS_BYTE_FORMAT(destchar)) {
  1002. PyErr_SetString(PyExc_TypeError,
  1003. "memoryview: cannot cast between two non-byte formats");
  1004. goto out;
  1005. }
  1006. if (view->len % itemsize) {
  1007. PyErr_SetString(PyExc_TypeError,
  1008. "memoryview: length is not a multiple of itemsize");
  1009. goto out;
  1010. }
  1011. view->format = get_native_fmtstr(PyBytes_AS_STRING(asciifmt));
  1012. if (view->format == NULL) {
  1013. /* NOT_REACHED: get_native_fmtchar() already validates the format. */
  1014. PyErr_SetString(PyExc_RuntimeError,
  1015. "memoryview: internal error");
  1016. goto out;
  1017. }
  1018. view->itemsize = itemsize;
  1019. view->ndim = 1;
  1020. view->shape[0] = view->len / view->itemsize;
  1021. view->strides[0] = view->itemsize;
  1022. view->suboffsets = NULL;
  1023. init_flags(mv);
  1024. ret = 0;
  1025. out:
  1026. Py_DECREF(asciifmt);
  1027. return ret;
  1028. }
  1029. /* The memoryview must have space for 3*len(seq) elements. */
  1030. static Py_ssize_t
  1031. copy_shape(Py_ssize_t *shape, const PyObject *seq, Py_ssize_t ndim,
  1032. Py_ssize_t itemsize)
  1033. {
  1034. Py_ssize_t x, i;
  1035. Py_ssize_t len = itemsize;
  1036. for (i = 0; i < ndim; i++) {
  1037. PyObject *tmp = PySequence_Fast_GET_ITEM(seq, i);
  1038. if (!PyLong_Check(tmp)) {
  1039. PyErr_SetString(PyExc_TypeError,
  1040. "memoryview.cast(): elements of shape must be integers");
  1041. return -1;
  1042. }
  1043. x = PyLong_AsSsize_t(tmp);
  1044. if (x == -1 && PyErr_Occurred()) {
  1045. return -1;
  1046. }
  1047. if (x <= 0) {
  1048. /* In general elements of shape may be 0, but not for casting. */
  1049. PyErr_Format(PyExc_ValueError,
  1050. "memoryview.cast(): elements of shape must be integers > 0");
  1051. return -1;
  1052. }
  1053. if (x > PY_SSIZE_T_MAX / len) {
  1054. PyErr_Format(PyExc_ValueError,
  1055. "memoryview.cast(): product(shape) > SSIZE_MAX");
  1056. return -1;
  1057. }
  1058. len *= x;
  1059. shape[i] = x;
  1060. }
  1061. return len;
  1062. }
  1063. /* Cast a 1-D array to a new shape. The result array will be C-contiguous.
  1064. If the result array does not have exactly the same byte length as the
  1065. input array, raise ValueError. */
  1066. static int
  1067. cast_to_ND(PyMemoryViewObject *mv, const PyObject *shape, int ndim)
  1068. {
  1069. Py_buffer *view = &mv->view;
  1070. Py_ssize_t len;
  1071. assert(view->ndim == 1); /* ndim from cast_to_1D() */
  1072. assert(Py_SIZE(mv) == 3*(ndim==0?1:ndim)); /* ndim of result array */
  1073. assert(view->shape == mv->ob_array);
  1074. assert(view->strides == mv->ob_array + (ndim==0?1:ndim));
  1075. assert(view->suboffsets == NULL);
  1076. view->ndim = ndim;
  1077. if (view->ndim == 0) {
  1078. view->shape = NULL;
  1079. view->strides = NULL;
  1080. len = view->itemsize;
  1081. }
  1082. else {
  1083. len = copy_shape(view->shape, shape, ndim, view->itemsize);
  1084. if (len < 0)
  1085. return -1;
  1086. init_strides_from_shape(view);
  1087. }
  1088. if (view->len != len) {
  1089. PyErr_SetString(PyExc_TypeError,
  1090. "memoryview: product(shape) * itemsize != buffer size");
  1091. return -1;
  1092. }
  1093. init_flags(mv);
  1094. return 0;
  1095. }
  1096. static int
  1097. zero_in_shape(PyMemoryViewObject *mv)
  1098. {
  1099. Py_buffer *view = &mv->view;
  1100. Py_ssize_t i;
  1101. for (i = 0; i < view->ndim; i++)
  1102. if (view->shape[i] == 0)
  1103. return 1;
  1104. return 0;
  1105. }
  1106. /*
  1107. Cast a copy of 'self' to a different view. The input view must
  1108. be C-contiguous. The function always casts the input view to a
  1109. 1-D output according to 'format'. At least one of input-format,
  1110. output-format must have byte size.
  1111. If 'shape' is given, the 1-D view from the previous step will
  1112. be cast to a C-contiguous view with new shape and strides.
  1113. All casts must result in views that will have the exact byte
  1114. size of the original input. Otherwise, an error is raised.
  1115. */
  1116. static PyObject *
  1117. memory_cast(PyMemoryViewObject *self, PyObject *args, PyObject *kwds)
  1118. {
  1119. static char *kwlist[] = {"format", "shape", NULL};
  1120. PyMemoryViewObject *mv = NULL;
  1121. PyObject *shape = NULL;
  1122. PyObject *format;
  1123. Py_ssize_t ndim = 1;
  1124. CHECK_RELEASED(self);
  1125. if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O", kwlist,
  1126. &format, &shape)) {
  1127. return NULL;
  1128. }
  1129. if (!PyUnicode_Check(format)) {
  1130. PyErr_SetString(PyExc_TypeError,
  1131. "memoryview: format argument must be a string");
  1132. return NULL;
  1133. }
  1134. if (!MV_C_CONTIGUOUS(self->flags)) {
  1135. PyErr_SetString(PyExc_TypeError,
  1136. "memoryview: casts are restricted to C-contiguous views");
  1137. return NULL;
  1138. }
  1139. if ((shape || self->view.ndim != 1) && zero_in_shape(self)) {
  1140. PyErr_SetString(PyExc_TypeError,
  1141. "memoryview: cannot cast view with zeros in shape or strides");
  1142. return NULL;
  1143. }
  1144. if (shape) {
  1145. CHECK_LIST_OR_TUPLE(shape)
  1146. ndim = PySequence_Fast_GET_SIZE(shape);
  1147. if (ndim > PyBUF_MAX_NDIM) {
  1148. PyErr_SetString(PyExc_ValueError,
  1149. "memoryview: number of dimensions must not exceed "
  1150. Py_STRINGIFY(PyBUF_MAX_NDIM));
  1151. return NULL;
  1152. }
  1153. if (self->view.ndim != 1 && ndim != 1) {
  1154. PyErr_SetString(PyExc_TypeError,
  1155. "memoryview: cast must be 1D -> ND or ND -> 1D");
  1156. return NULL;
  1157. }
  1158. }
  1159. mv = (PyMemoryViewObject *)
  1160. mbuf_add_incomplete_view(self->mbuf, &self->view, ndim==0 ? 1 : (int)ndim);
  1161. if (mv == NULL)
  1162. return NULL;
  1163. if (cast_to_1D(mv, format) < 0)
  1164. goto error;
  1165. if (shape && cast_to_ND(mv, shape, (int)ndim) < 0)
  1166. goto error;
  1167. return (PyObject *)mv;
  1168. error:
  1169. Py_DECREF(mv);
  1170. return NULL;
  1171. }
  1172. /**************************************************************************/
  1173. /* getbuffer */
  1174. /**************************************************************************/
  1175. static int
  1176. memory_getbuf(PyMemoryViewObject *self, Py_buffer *view, int flags)
  1177. {
  1178. Py_buffer *base = &self->view;
  1179. int baseflags = self->flags;
  1180. CHECK_RELEASED_INT(self);
  1181. /* start with complete information */
  1182. *view = *base;
  1183. view->obj = NULL;
  1184. if (REQ_WRITABLE(flags) && base->readonly) {
  1185. PyErr_SetString(PyExc_BufferError,
  1186. "memoryview: underlying buffer is not writable");
  1187. return -1;
  1188. }
  1189. if (!REQ_FORMAT(flags)) {
  1190. /* NULL indicates that the buffer's data type has been cast to 'B'.
  1191. view->itemsize is the _previous_ itemsize. If shape is present,
  1192. the equality product(shape) * itemsize = len still holds at this
  1193. point. The equality calcsize(format) = itemsize does _not_ hold
  1194. from here on! */
  1195. view->format = NULL;
  1196. }
  1197. if (REQ_C_CONTIGUOUS(flags) && !MV_C_CONTIGUOUS(baseflags)) {
  1198. PyErr_SetString(PyExc_BufferError,
  1199. "memoryview: underlying buffer is not C-contiguous");
  1200. return -1;
  1201. }
  1202. if (REQ_F_CONTIGUOUS(flags) && !MV_F_CONTIGUOUS(baseflags)) {
  1203. PyErr_SetString(PyExc_BufferError,
  1204. "memoryview: underlying buffer is not Fortran contiguous");
  1205. return -1;
  1206. }
  1207. if (REQ_ANY_CONTIGUOUS(flags) && !MV_ANY_CONTIGUOUS(baseflags)) {
  1208. PyErr_SetString(PyExc_BufferError,
  1209. "memoryview: underlying buffer is not contiguous");
  1210. return -1;
  1211. }
  1212. if (!REQ_INDIRECT(flags) && (baseflags & _Py_MEMORYVIEW_PIL)) {
  1213. PyErr_SetString(PyExc_BufferError,
  1214. "memoryview: underlying buffer requires suboffsets");
  1215. return -1;
  1216. }
  1217. if (!REQ_STRIDES(flags)) {
  1218. if (!MV_C_CONTIGUOUS(baseflags)) {
  1219. PyErr_SetString(PyExc_BufferError,
  1220. "memoryview: underlying buffer is not C-contiguous");
  1221. return -1;
  1222. }
  1223. view->strides = NULL;
  1224. }
  1225. if (!REQ_SHAPE(flags)) {
  1226. /* PyBUF_SIMPLE or PyBUF_WRITABLE: at this point buf is C-contiguous,
  1227. so base->buf = ndbuf->data. */
  1228. if (view->format != NULL) {
  1229. /* PyBUF_SIMPLE|PyBUF_FORMAT and PyBUF_WRITABLE|PyBUF_FORMAT do
  1230. not make sense. */
  1231. PyErr_Format(PyExc_BufferError,
  1232. "memoryview: cannot cast to unsigned bytes if the format flag "
  1233. "is present");
  1234. return -1;
  1235. }
  1236. /* product(shape) * itemsize = len and calcsize(format) = itemsize
  1237. do _not_ hold from here on! */
  1238. view->ndim = 1;
  1239. view->shape = NULL;
  1240. }
  1241. view->obj = (PyObject *)self;
  1242. Py_INCREF(view->obj);
  1243. self->exports++;
  1244. return 0;
  1245. }
  1246. static void
  1247. memory_releasebuf(PyMemoryViewObject *self, Py_buffer *view)
  1248. {
  1249. self->exports--;
  1250. return;
  1251. /* PyBuffer_Release() decrements view->obj after this function returns. */
  1252. }
  1253. /* Buffer methods */
  1254. static PyBufferProcs memory_as_buffer = {
  1255. (getbufferproc)memory_getbuf, /* bf_getbuffer */
  1256. (releasebufferproc)memory_releasebuf, /* bf_releasebuffer */
  1257. };
  1258. /****************************************************************************/
  1259. /* Optimized pack/unpack for all native format specifiers */
  1260. /****************************************************************************/
  1261. /*
  1262. Fix exceptions:
  1263. 1) Include format string in the error message.
  1264. 2) OverflowError -> ValueError.
  1265. 3) The error message from PyNumber_Index() is not ideal.
  1266. */
  1267. static int
  1268. type_error_int(const char *fmt)
  1269. {
  1270. PyErr_Format(PyExc_TypeError,
  1271. "memoryview: invalid type for format '%s'", fmt);
  1272. return -1;
  1273. }
  1274. static int
  1275. value_error_int(const char *fmt)
  1276. {
  1277. PyErr_Format(PyExc_ValueError,
  1278. "memoryview: invalid value for format '%s'", fmt);
  1279. return -1;
  1280. }
  1281. static int
  1282. fix_error_int(const char *fmt)
  1283. {
  1284. assert(PyErr_Occurred());
  1285. if (PyErr_ExceptionMatches(PyExc_TypeError)) {
  1286. PyErr_Clear();
  1287. return type_error_int(fmt);
  1288. }
  1289. else if (PyErr_ExceptionMatches(PyExc_OverflowError) ||
  1290. PyErr_ExceptionMatches(PyExc_ValueError)) {
  1291. PyErr_Clear();
  1292. return value_error_int(fmt);
  1293. }
  1294. return -1;
  1295. }
  1296. /* Accept integer objects or objects with an __index__() method. */
  1297. static long
  1298. pylong_as_ld(PyObject *item)
  1299. {
  1300. PyObject *tmp;
  1301. long ld;
  1302. tmp = PyNumber_Index(item);
  1303. if (tmp == NULL)
  1304. return -1;
  1305. ld = PyLong_AsLong(tmp);
  1306. Py_DECREF(tmp);
  1307. return ld;
  1308. }
  1309. static unsigned long
  1310. pylong_as_lu(PyObject *item)
  1311. {
  1312. PyObject *tmp;
  1313. unsigned long lu;
  1314. tmp = PyNumber_Index(item);
  1315. if (tmp == NULL)
  1316. return (unsigned long)-1;
  1317. lu = PyLong_AsUnsignedLong(tmp);
  1318. Py_DECREF(tmp);
  1319. return lu;
  1320. }
  1321. #ifdef HAVE_LONG_LONG
  1322. static PY_LONG_LONG
  1323. pylong_as_lld(PyObject *item)
  1324. {
  1325. PyObject *tmp;
  1326. PY_LONG_LONG lld;
  1327. tmp = PyNumber_Index(item);
  1328. if (tmp == NULL)
  1329. return -1;
  1330. lld = PyLong_AsLongLong(tmp);
  1331. Py_DECREF(tmp);
  1332. return lld;
  1333. }
  1334. static unsigned PY_LONG_LONG
  1335. pylong_as_llu(PyObject *item)
  1336. {
  1337. PyObject *tmp;
  1338. unsigned PY_LONG_LONG llu;
  1339. tmp = PyNumber_Index(item);
  1340. if (tmp == NULL)
  1341. return (unsigned PY_LONG_LONG)-1;
  1342. llu = PyLong_AsUnsignedLongLong(tmp);
  1343. Py_DECREF(tmp);
  1344. return llu;
  1345. }
  1346. #endif
  1347. static Py_ssize_t
  1348. pylong_as_zd(PyObject *item)
  1349. {
  1350. PyObject *tmp;
  1351. Py_ssize_t zd;
  1352. tmp = PyNumber_Index(item);
  1353. if (tmp == NULL)
  1354. return -1;
  1355. zd = PyLong_AsSsize_t(tmp);
  1356. Py_DECREF(tmp);
  1357. return zd;
  1358. }
  1359. static size_t
  1360. pylong_as_zu(PyObject *item)
  1361. {
  1362. PyObject *tmp;
  1363. size_t zu;
  1364. tmp = PyNumber_Index(item);
  1365. if (tmp == NULL)
  1366. return (size_t)-1;
  1367. zu = PyLong_AsSize_t(tmp);
  1368. Py_DECREF(tmp);
  1369. return zu;
  1370. }
  1371. /* Timings with the ndarray from _testbuffer.c indicate that using the
  1372. struct module is around 15x slower than the two functions below. */
  1373. #define UNPACK_SINGLE(dest, ptr, type) \
  1374. do { \
  1375. type x; \
  1376. memcpy((char *)&x, ptr, sizeof x); \
  1377. dest = x; \
  1378. } while (0)
  1379. /* Unpack a single item. 'fmt' can be any native format character in struct
  1380. module syntax. This function is very sensitive to small changes. With this
  1381. layout gcc automatically generates a fast jump table. */
  1382. Py_LOCAL_INLINE(PyObject *)
  1383. unpack_single(const char *ptr, const char *fmt)
  1384. {
  1385. unsigned PY_LONG_LONG llu;
  1386. unsigned long lu;
  1387. size_t zu;
  1388. PY_LONG_LONG lld;
  1389. long ld;
  1390. Py_ssize_t zd;
  1391. double d;
  1392. unsigned char uc;
  1393. void *p;
  1394. switch (fmt[0]) {
  1395. /* signed integers and fast path for 'B' */
  1396. case 'B': uc = *((unsigned char *)ptr); goto convert_uc;
  1397. case 'b': ld = *((signed char *)ptr); goto convert_ld;
  1398. case 'h': UNPACK_SINGLE(ld, ptr, short); goto convert_ld;
  1399. case 'i': UNPACK_SINGLE(ld, ptr, int); goto convert_ld;
  1400. case 'l': UNPACK_SINGLE(ld, ptr, long); goto convert_ld;
  1401. /* boolean */
  1402. #ifdef HAVE_C99_BOOL
  1403. case '?': UNPACK_SINGLE(ld, ptr, _Bool); goto convert_bool;
  1404. #else
  1405. case '?': UNPACK_SINGLE(ld, ptr, char); goto convert_bool;
  1406. #endif
  1407. /* unsigned integers */
  1408. case 'H': UNPACK_SINGLE(lu, ptr, unsigned short); goto convert_lu;
  1409. case 'I': UNPACK_SINGLE(lu, ptr, unsigned int); goto convert_lu;
  1410. case 'L': UNPACK_SINGLE(lu, ptr, unsigned long); goto convert_lu;
  1411. /* native 64-bit */
  1412. #ifdef HAVE_LONG_LONG
  1413. case 'q': UNPACK_SINGLE(lld, ptr, PY_LONG_LONG); goto convert_lld;
  1414. case 'Q': UNPACK_SINGLE(llu, ptr, unsigned PY_LONG_LONG); goto convert_llu;
  1415. #endif
  1416. /* ssize_t and size_t */
  1417. case 'n': UNPACK_SINGLE(zd, ptr, Py_ssize_t); goto convert_zd;
  1418. case 'N': UNPACK_SINGLE(zu, ptr, size_t); goto convert_zu;
  1419. /* floats */
  1420. case 'f': UNPACK_SINGLE(d, ptr, float); goto convert_double;
  1421. case 'd': UNPACK_SINGLE(d, ptr, double); goto convert_double;
  1422. /* bytes object */
  1423. case 'c': goto convert_bytes;
  1424. /* pointer */
  1425. case 'P': UNPACK_SINGLE(p, ptr, void *); goto convert_pointer;
  1426. /* default */
  1427. default: goto err_format;
  1428. }
  1429. convert_uc:
  1430. /* PyLong_FromUnsignedLong() is slower */
  1431. return PyLong_FromLong(uc);
  1432. convert_ld:
  1433. return PyLong_FromLong(ld);
  1434. convert_lu:
  1435. return PyLong_FromUnsignedLong(lu);
  1436. convert_lld:
  1437. return PyLong_FromLongLong(lld);
  1438. convert_llu:
  1439. return PyLong_FromUnsignedLongLong(llu);
  1440. convert_zd:
  1441. return PyLong_FromSsize_t(zd);
  1442. convert_zu:
  1443. return PyLong_FromSize_t(zu);
  1444. convert_double:
  1445. return PyFloat_FromDouble(d);
  1446. convert_bool:
  1447. return PyBool_FromLong(ld);
  1448. convert_bytes:
  1449. return PyBytes_FromStringAndSize(ptr, 1);
  1450. convert_pointer:
  1451. return PyLong_FromVoidPtr(p);
  1452. err_format:
  1453. PyErr_Format(PyExc_NotImplementedError,
  1454. "memoryview: format %s not supported", fmt);
  1455. return NULL;
  1456. }
  1457. #define PACK_SINGLE(ptr, src, type) \
  1458. do { \
  1459. type x; \
  1460. x = (type)src; \
  1461. memcpy(ptr, (char *)&x, sizeof x); \
  1462. } while (0)
  1463. /* Pack a single item. 'fmt' can be any native format character in
  1464. struct module syntax. */
  1465. static int
  1466. pack_single(char *ptr, PyObject *item, const char *fmt)
  1467. {
  1468. unsigned PY_LONG_LONG llu;
  1469. unsigned long lu;
  1470. size_t zu;
  1471. PY_LONG_LONG lld;
  1472. long ld;
  1473. Py_ssize_t zd;
  1474. double d;
  1475. void *p;
  1476. switch (fmt[0]) {
  1477. /* signed integers */
  1478. case 'b': case 'h': case 'i': case 'l':
  1479. ld = pylong_as_ld(item);
  1480. if (ld == -1 && PyErr_Occurred())
  1481. goto err_occurred;
  1482. switch (fmt[0]) {
  1483. case 'b':
  1484. if (ld < SCHAR_MIN || ld > SCHAR_MAX) goto err_range;
  1485. *((signed char *)ptr) = (signed char)ld; break;
  1486. case 'h':
  1487. if (ld < SHRT_MIN || ld > SHRT_MAX) goto err_range;
  1488. PACK_SINGLE(ptr, ld, short); break;
  1489. case 'i':
  1490. if (ld < INT_MIN || ld > INT_MAX) goto err_range;
  1491. PACK_SINGLE(ptr, ld, int); break;
  1492. default: /* 'l' */
  1493. PACK_SINGLE(ptr, ld, long); break;
  1494. }
  1495. break;
  1496. /* unsigned integers */
  1497. case 'B': case 'H': case 'I': case 'L':
  1498. lu = pylong_as_lu(item);
  1499. if (lu == (unsigned long)-1 && PyErr_Occurred())
  1500. goto err_occurred;
  1501. switch (fmt[0]) {
  1502. case 'B':
  1503. if (lu > UCHAR_MAX) goto err_range;
  1504. *((unsigned char *)ptr) = (unsigned char)lu; break;
  1505. case 'H':
  1506. if (lu > USHRT_MAX) goto err_range;
  1507. PACK_SINGLE(ptr, lu, unsigned short); break;
  1508. case 'I':
  1509. if (lu > UINT_MAX) goto err_range;
  1510. PACK_SINGLE(ptr, lu, unsigned int); break;
  1511. default: /* 'L' */
  1512. PACK_SINGLE(ptr, lu, unsigned long); break;
  1513. }
  1514. break;
  1515. /* native 64-bit */
  1516. #ifdef HAVE_LONG_LONG
  1517. case 'q':
  1518. lld = pylong_as_lld(item);
  1519. if (lld == -1 && PyErr_Occurred())
  1520. goto err_occurred;
  1521. PACK_SINGLE(ptr, lld, PY_LONG_LONG);
  1522. break;
  1523. case 'Q':
  1524. llu = pylong_as_llu(item);
  1525. if (llu == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred())
  1526. goto err_occurred;
  1527. PACK_SINGLE(ptr, llu, unsigned PY_LONG_LONG);
  1528. break;
  1529. #endif
  1530. /* ssize_t and size_t */
  1531. case 'n':
  1532. zd = pylong_as_zd(item);
  1533. if (zd == -1 && PyErr_Occurred())
  1534. goto err_occurred;
  1535. PACK_SINGLE(ptr, zd, Py_ssize_t);
  1536. break;
  1537. case 'N':
  1538. zu = pylong_as_zu(item);
  1539. if (zu == (size_t)-1 && PyErr_Occurred())
  1540. goto err_occurred;
  1541. PACK_SINGLE(ptr, zu, size_t);
  1542. break;
  1543. /* floats */
  1544. case 'f': case 'd':
  1545. d = PyFloat_AsDouble(item);
  1546. if (d == -1.0 && PyErr_Occurred())
  1547. goto err_occurred;
  1548. if (fmt[0] == 'f') {
  1549. PACK_SINGLE(ptr, d, float);
  1550. }
  1551. else {
  1552. PACK_SINGLE(ptr, d, double);
  1553. }
  1554. break;
  1555. /* bool */
  1556. case '?':
  1557. ld = PyObject_IsTrue(item);
  1558. if (ld < 0)
  1559. return -1; /* preserve original error */
  1560. #ifdef HAVE_C99_BOOL
  1561. PACK_SINGLE(ptr, ld, _Bool);
  1562. #else
  1563. PACK_SINGLE(ptr, ld, char);
  1564. #endif
  1565. break;
  1566. /* bytes object */
  1567. case 'c':
  1568. if (!PyBytes_Check(item))
  1569. return type_error_int(fmt);
  1570. if (PyBytes_GET_SIZE(item) != 1)
  1571. return value_error_int(fmt);
  1572. *ptr = PyBytes_AS_STRING(item)[0];
  1573. break;
  1574. /* pointer */
  1575. case 'P':
  1576. p = PyLong_AsVoidPtr(item);
  1577. if (p == NULL && PyErr_Occurred())
  1578. goto err_occurred;
  1579. PACK_SINGLE(ptr, p, void *);
  1580. break;
  1581. /* default */
  1582. default: goto err_format;
  1583. }
  1584. return 0;
  1585. err_occurred:
  1586. return fix_error_int(fmt);
  1587. err_range:
  1588. return value_error_int(fmt);
  1589. err_format:
  1590. PyErr_Format(PyExc_NotImplementedError,
  1591. "memoryview: format %s not supported", fmt);
  1592. return -1;
  1593. }
  1594. /****************************************************************************/
  1595. /* unpack using the struct module */
  1596. /****************************************************************************/
  1597. /* For reasonable performance it is necessary to cache all objects required
  1598. for unpacking. An unpacker can handle the format passed to unpack_from().
  1599. Invariant: All pointer fields of the struct should either be NULL or valid
  1600. pointers. */
  1601. struct unpacker {
  1602. PyObject *unpack_from; /* Struct.unpack_from(format) */
  1603. PyObject *mview; /* cached memoryview */
  1604. char *item; /* buffer for mview */
  1605. Py_ssize_t itemsize; /* len(item) */
  1606. };
  1607. static struct unpacker *
  1608. unpacker_new(void)
  1609. {
  1610. struct unpacker *x = PyMem_Malloc(sizeof *x);
  1611. if (x == NULL) {
  1612. PyErr_NoMemory();
  1613. return NULL;
  1614. }
  1615. x->unpack_from = NULL;
  1616. x->mview = NULL;
  1617. x->item = NULL;
  1618. x->itemsize = 0;
  1619. return x;
  1620. }
  1621. static void
  1622. unpacker_free(struct unpacker *x)
  1623. {
  1624. if (x) {
  1625. Py_XDECREF(x->unpack_from);
  1626. Py_XDECREF(x->mview);
  1627. PyMem_Free(x->item);
  1628. PyMem_Free(x);
  1629. }
  1630. }
  1631. /* Return a new unpacker for the given format. */
  1632. static struct unpacker *
  1633. struct_get_unpacker(const char *fmt, Py_ssize_t itemsize)
  1634. {
  1635. PyObject *structmodule; /* XXX cache these two */
  1636. PyObject *Struct = NULL; /* XXX in globals? */
  1637. PyObject *structobj = NULL;
  1638. PyObject *format = NULL;
  1639. struct unpacker *x = NULL;
  1640. structmodule = PyImport_ImportModule("struct");
  1641. if (structmodule == NULL)
  1642. return NULL;
  1643. Struct = PyObject_GetAttrString(structmodule, "Struct");
  1644. Py_DECREF(structmodule);
  1645. if (Struct == NULL)
  1646. return NULL;
  1647. x = unpacker_new();
  1648. if (x == NULL)
  1649. goto error;
  1650. format = PyBytes_FromString(fmt);
  1651. if (format == NULL)
  1652. goto error;
  1653. structobj = PyObject_CallFunctionObjArgs(Struct, format, NULL);
  1654. if (structobj == NULL)
  1655. goto error;
  1656. x->unpack_from = PyObject_GetAttrString(structobj, "unpack_from");
  1657. if (x->unpack_from == NULL)
  1658. goto error;
  1659. x->item = PyMem_Malloc(itemsize);
  1660. if (x->item == NULL) {
  1661. PyErr_NoMemory();
  1662. goto error;
  1663. }
  1664. x->itemsize = itemsize;
  1665. x->mview = PyMemoryView_FromMemory(x->item, itemsize, PyBUF_WRITE);
  1666. if (x->mview == NULL)
  1667. goto error;
  1668. out:
  1669. Py_XDECREF(Struct);
  1670. Py_XDECREF(format);
  1671. Py_XDECREF(structobj);
  1672. return x;
  1673. error:
  1674. unpacker_free(x);
  1675. x = NULL;
  1676. goto out;
  1677. }
  1678. /* unpack a single item */
  1679. static PyObject *
  1680. struct_unpack_single(const char *ptr, struct unpacker *x)
  1681. {
  1682. PyObject *v;
  1683. memcpy(x->item, ptr, x->itemsize);
  1684. v = PyObject_CallFunctionObjArgs(x->unpack_from, x->mview, NULL);
  1685. if (v == NULL)
  1686. return NULL;
  1687. if (PyTuple_GET_SIZE(v) == 1) {
  1688. PyObject *tmp = PyTuple_GET_ITEM(v, 0);
  1689. Py_INCREF(tmp);
  1690. Py_DECREF(v);
  1691. return tmp;
  1692. }
  1693. return v;
  1694. }
  1695. /****************************************************************************/
  1696. /* Representations */
  1697. /****************************************************************************/
  1698. /* allow explicit form of native format */
  1699. Py_LOCAL_INLINE(const char *)
  1700. adjust_fmt(const Py_buffer *view)
  1701. {
  1702. const char *fmt;
  1703. fmt = (view->format[0] == '@') ? view->format+1 : view->format;
  1704. if (fmt[0] && fmt[1] == '\0')
  1705. return fmt;
  1706. PyErr_Format(PyExc_NotImplementedError,
  1707. "memoryview: unsupported format %s", view->format);
  1708. return NULL;
  1709. }
  1710. /* Base case for multi-dimensional unpacking. Assumption: ndim == 1. */
  1711. static PyObject *
  1712. tolist_base(const char *ptr, const Py_ssize_t *shape,
  1713. const Py_ssize_t *strides, const Py_ssize_t *suboffsets,
  1714. const char *fmt)
  1715. {
  1716. PyObject *lst, *item;
  1717. Py_ssize_t i;
  1718. lst = PyList_New(shape[0]);
  1719. if (lst == NULL)
  1720. return NULL;
  1721. for (i = 0; i < shape[0]; ptr+=strides[0], i++) {
  1722. const char *xptr = ADJUST_PTR(ptr, suboffsets, 0);
  1723. item = unpack_single(xptr, fmt);
  1724. if (item == NULL) {
  1725. Py_DECREF(lst);
  1726. return NULL;
  1727. }
  1728. PyList_SET_ITEM(lst, i, item);
  1729. }
  1730. return lst;
  1731. }
  1732. /* Unpack a multi-dimensional array into a nested list.
  1733. Assumption: ndim >= 1. */
  1734. static PyObject *
  1735. tolist_rec(const char *ptr, Py_ssize_t ndim, const Py_ssize_t *shape,
  1736. const Py_ssize_t *strides, const Py_ssize_t *suboffsets,
  1737. const char *fmt)
  1738. {
  1739. PyObject *lst, *item;
  1740. Py_ssize_t i;
  1741. assert(ndim >= 1);
  1742. assert(shape != NULL);
  1743. assert(strides != NULL);
  1744. if (ndim == 1)
  1745. return tolist_base(ptr, shape, strides, suboffsets, fmt);
  1746. lst = PyList_New(shape[0]);
  1747. if (lst == NULL)
  1748. return NULL;
  1749. for (i = 0; i < shape[0]; ptr+=strides[0], i++) {
  1750. const char *xptr = ADJUST_PTR(ptr, suboffsets, 0);
  1751. item = tolist_rec(xptr, ndim-1, shape+1,
  1752. strides+1, suboffsets ? suboffsets+1 : NULL,
  1753. fmt);
  1754. if (item == NULL) {
  1755. Py_DECREF(lst);
  1756. return NULL;
  1757. }
  1758. PyList_SET_ITEM(lst, i, item);
  1759. }
  1760. return lst;
  1761. }
  1762. /* Return a list representation of the memoryview. Currently only buffers
  1763. with native format strings are supported. */
  1764. static PyObject *
  1765. memory_tolist(PyMemoryViewObject *mv, PyObject *noargs)
  1766. {
  1767. const Py_buffer *view = &(mv->view);
  1768. const char *fmt;
  1769. CHECK_RELEASED(mv);
  1770. fmt = adjust_fmt(view);
  1771. if (fmt == NULL)
  1772. return NULL;
  1773. if (view->ndim == 0) {
  1774. return unpack_single(view->buf, fmt);
  1775. }
  1776. else if (view->ndim == 1) {
  1777. return tolist_base(view->buf, view->shape,
  1778. view->strides, view->suboffsets,
  1779. fmt);
  1780. }
  1781. else {
  1782. return tolist_rec(view->buf, view->ndim, view->shape,
  1783. view->strides, view->suboffsets,
  1784. fmt);
  1785. }
  1786. }
  1787. static PyObject *
  1788. memory_tobytes(PyMemoryViewObject *self, PyObject *dummy)
  1789. {
  1790. Py_buffer *src = VIEW_ADDR(self);
  1791. PyObject *bytes = NULL;
  1792. CHECK_RELEASED(self);
  1793. if (MV_C_CONTIGUOUS(self->flags)) {
  1794. return PyBytes_FromStringAndSize(src->buf, src->len);
  1795. }
  1796. bytes = PyBytes_FromStringAndSize(NULL, src->len);
  1797. if (bytes == NULL)
  1798. return NULL;
  1799. if (buffer_to_contiguous(PyBytes_AS_STRING(bytes), src, 'C') < 0) {
  1800. Py_DECREF(bytes);
  1801. return NULL;
  1802. }
  1803. return bytes;
  1804. }
  1805. static PyObject *
  1806. memory_repr(PyMemoryViewObject *self)
  1807. {
  1808. if (self->flags & _Py_MEMORYVIEW_RELEASED)
  1809. return PyUnicode_FromFormat("<released memory at %p>", self);
  1810. else
  1811. return PyUnicode_FromFormat("<memory at %p>", self);
  1812. }
  1813. /**************************************************************************/
  1814. /* Indexing and slicing */
  1815. /**************************************************************************/
  1816. static char *
  1817. lookup_dimension(Py_buffer *view, char *ptr, int dim, Py_ssize_t index)
  1818. {
  1819. Py_ssize_t nitems; /* items in the given dimension */
  1820. assert(view->shape);
  1821. assert(view->strides);
  1822. nitems = view->shape[dim];
  1823. if (index < 0) {
  1824. index += nitems;
  1825. }
  1826. if (index < 0 || index >= nitems) {
  1827. PyErr_Format(PyExc_IndexError,
  1828. "index out of bounds on dimension %d", dim + 1);
  1829. return NULL;
  1830. }
  1831. ptr += view->strides[dim] * index;
  1832. ptr = ADJUST_PTR(ptr, view->suboffsets, dim);
  1833. return ptr;
  1834. }
  1835. /* Get the pointer to the item at index. */
  1836. static char *
  1837. ptr_from_index(Py_buffer *view, Py_ssize_t index)
  1838. {
  1839. char *ptr = (char *)view->buf;
  1840. return lookup_dimension(view, ptr, 0, index);
  1841. }
  1842. /* Get the pointer to the item at tuple. */
  1843. static char *
  1844. ptr_from_tuple(Py_buffer *view, PyObject *tup)
  1845. {
  1846. char *ptr = (char *)view->buf;
  1847. Py_ssize_t dim, nindices = PyTuple_GET_SIZE(tup);
  1848. if (nindices > view->ndim) {
  1849. PyErr_Format(PyExc_TypeError,
  1850. "cannot index %zd-dimension view with %zd-element tuple",
  1851. view->ndim, nindices);
  1852. return NULL;
  1853. }
  1854. for (dim = 0; dim < nindices; dim++) {
  1855. Py_ssize_t index;
  1856. index = PyNumber_AsSsize_t(PyTuple_GET_ITEM(tup, dim),
  1857. PyExc_IndexError);
  1858. if (index == -1 && PyErr_Occurred())
  1859. return NULL;
  1860. ptr = lookup_dimension(view, ptr, dim, index);
  1861. if (ptr == NULL)
  1862. return NULL;
  1863. }
  1864. return ptr;
  1865. }
  1866. /* Return the item at index. In a one-dimensional view, this is an object
  1867. with the type specified by view->format. Otherwise, the item is a sub-view.
  1868. The function is used in memory_subscript() and memory_as_sequence. */
  1869. static PyObject *
  1870. memory_item(PyMemoryViewObject *self, Py_ssize_t index)
  1871. {
  1872. Py_buffer *view = &(self->view);
  1873. const char *fmt;
  1874. CHECK_RELEASED(self);
  1875. fmt = adjust_fmt(view);
  1876. if (fmt == NULL)
  1877. return NULL;
  1878. if (view->ndim == 0) {
  1879. PyErr_SetString(PyExc_TypeError, "invalid indexing of 0-dim memory");
  1880. return NULL;
  1881. }
  1882. if (view->ndim == 1) {
  1883. char *ptr = ptr_from_index(view, index);
  1884. if (ptr == NULL)
  1885. return NULL;
  1886. return unpack_single(ptr, fmt);
  1887. }
  1888. PyErr_SetString(PyExc_NotImplementedError,
  1889. "multi-dimensional sub-views are not implemented");
  1890. return NULL;
  1891. }
  1892. /* Return the item at position *key* (a tuple of indices). */
  1893. static PyObject *
  1894. memory_item_multi(PyMemoryViewObject *self, PyObject *tup)
  1895. {
  1896. Py_buffer *view = &(self->view);
  1897. const char *fmt;
  1898. Py_ssize_t nindices = PyTuple_GET_SIZE(tup);
  1899. char *ptr;
  1900. CHECK_RELEASED(self);
  1901. fmt = adjust_fmt(view);
  1902. if (fmt == NULL)
  1903. return NULL;
  1904. if (nindices < view->ndim) {
  1905. PyErr_SetString(PyExc_NotImplementedError,
  1906. "sub-views are not implemented");
  1907. return NULL;
  1908. }
  1909. ptr = ptr_from_tuple(view, tup);
  1910. if (ptr == NULL)
  1911. return NULL;
  1912. return unpack_single(ptr, fmt);
  1913. }
  1914. Py_LOCAL_INLINE(int)
  1915. init_slice(Py_buffer *base, PyObject *key, int dim)
  1916. {
  1917. Py_ssize_t start, stop, step, slicelength;
  1918. if (PySlice_GetIndicesEx(key, base->shape[dim],
  1919. &start, &stop, &step, &slicelength) < 0) {
  1920. return -1;
  1921. }
  1922. if (base->suboffsets == NULL || dim == 0) {
  1923. adjust_buf:
  1924. base->buf = (char *)base->buf + base->strides[dim] * start;
  1925. }
  1926. else {
  1927. Py_ssize_t n = dim-1;
  1928. while (n >= 0 && base->suboffsets[n] < 0)
  1929. n--;
  1930. if (n < 0)
  1931. goto adjust_buf; /* all suboffsets are negative */
  1932. base->suboffsets[n] = base->suboffsets[n] + base->strides[dim] * start;
  1933. }
  1934. base->shape[dim] = slicelength;
  1935. base->strides[dim] = base->strides[dim] * step;
  1936. return 0;
  1937. }
  1938. static int
  1939. is_multislice(PyObject *key)
  1940. {
  1941. Py_ssize_t size, i;
  1942. if (!PyTuple_Check(key))
  1943. return 0;
  1944. size = PyTuple_GET_SIZE(key);
  1945. if (size == 0)
  1946. return 0;
  1947. for (i = 0; i < size; i++) {
  1948. PyObject *x = PyTuple_GET_ITEM(key, i);
  1949. if (!PySlice_Check(x))
  1950. return 0;
  1951. }
  1952. return 1;
  1953. }
  1954. static Py_ssize_t
  1955. is_multiindex(PyObject *key)
  1956. {
  1957. Py_ssize_t size, i;
  1958. if (!PyTuple_Check(key))
  1959. return 0;
  1960. size = PyTuple_GET_SIZE(key);
  1961. for (i = 0; i < size; i++) {
  1962. PyObject *x = PyTuple_GET_ITEM(key, i);
  1963. if (!PyIndex_Check(x))
  1964. return 0;
  1965. }
  1966. return 1;
  1967. }
  1968. /* mv[obj] returns an object holding the data for one element if obj
  1969. fully indexes the memoryview or another memoryview object if it
  1970. does not.
  1971. 0-d memoryview objects can be referenced using mv[...] or mv[()]
  1972. but not with anything else. */
  1973. static PyObject *
  1974. memory_subscript(PyMemoryViewObject *self, PyObject *key)
  1975. {
  1976. Py_buffer *view;
  1977. view = &(self->view);
  1978. CHECK_RELEASED(self);
  1979. if (view->ndim == 0) {
  1980. if (PyTuple_Check(key) && PyTuple_GET_SIZE(key) == 0) {
  1981. const char *fmt = adjust_fmt(view);
  1982. if (fmt == NULL)
  1983. return NULL;
  1984. return unpack_single(view->buf, fmt);
  1985. }
  1986. else if (key == Py_Ellipsis) {
  1987. Py_INCREF(self);
  1988. return (PyObject *)self;
  1989. }
  1990. else {
  1991. PyErr_SetString(PyExc_TypeError,
  1992. "invalid indexing of 0-dim memory");
  1993. return NULL;
  1994. }
  1995. }
  1996. if (PyIndex_Check(key)) {
  1997. Py_ssize_t index;
  1998. index = PyNumber_AsSsize_t(key, PyExc_IndexError);
  1999. if (index == -1 && PyErr_Occurred())
  2000. return NULL;
  2001. return memory_item(self, index);
  2002. }
  2003. else if (PySlice_Check(key)) {
  2004. PyMemoryViewObject *sliced;
  2005. sliced = (PyMemoryViewObject *)mbuf_add_view(self->mbuf, view);
  2006. if (sliced == NULL)
  2007. return NULL;
  2008. if (init_slice(&sliced->view, key, 0) < 0) {
  2009. Py_DECREF(sliced);
  2010. return NULL;
  2011. }
  2012. init_len(&sliced->view);
  2013. init_flags(sliced);
  2014. return (PyObject *)sliced;
  2015. }
  2016. else if (is_multiindex(key)) {
  2017. return memory_item_multi(self, key);
  2018. }
  2019. else if (is_multislice(key)) {
  2020. PyErr_SetString(PyExc_NotImplementedError,
  2021. "multi-dimensional slicing is not implemented");
  2022. return NULL;
  2023. }
  2024. PyErr_SetString(PyExc_TypeError, "memoryview: invalid slice key");
  2025. return NULL;
  2026. }
  2027. static int
  2028. memory_ass_sub(PyMemoryViewObject *self, PyObject *key, PyObject *value)
  2029. {
  2030. Py_buffer *view = &(self->view);
  2031. Py_buffer src;
  2032. const char *fmt;
  2033. char *ptr;
  2034. CHECK_RELEASED_INT(self);
  2035. fmt = adjust_fmt(view);
  2036. if (fmt == NULL)
  2037. return -1;
  2038. if (view->readonly) {
  2039. PyErr_SetString(PyExc_TypeError, "cannot modify read-only memory");
  2040. return -1;
  2041. }
  2042. if (value == NULL) {
  2043. PyErr_SetString(PyExc_TypeError, "cannot delete memory");
  2044. return -1;
  2045. }
  2046. if (view->ndim == 0) {
  2047. if (key == Py_Ellipsis ||
  2048. (PyTuple_Check(key) && PyTuple_GET_SIZE(key)==0)) {
  2049. ptr = (char *)view->buf;
  2050. return pack_single(ptr, value, fmt);
  2051. }
  2052. else {
  2053. PyErr_SetString(PyExc_TypeError,
  2054. "invalid indexing of 0-dim memory");
  2055. return -1;
  2056. }
  2057. }
  2058. if (PyIndex_Check(key)) {
  2059. Py_ssize_t index;
  2060. if (1 < view->ndim) {
  2061. PyErr_SetString(PyExc_NotImplementedError,
  2062. "sub-views are not implemented");
  2063. return -1;
  2064. }
  2065. index = PyNumber_AsSsize_t(key, PyExc_IndexError);
  2066. if (index == -1 && PyErr_Occurred())
  2067. return -1;
  2068. ptr = ptr_from_index(view, index);
  2069. if (ptr == NULL)
  2070. return -1;
  2071. return pack_single(ptr, value, fmt);
  2072. }
  2073. /* one-dimensional: fast path */
  2074. if (PySlice_Check(key) && view->ndim == 1) {
  2075. Py_buffer dest; /* sliced view */
  2076. Py_ssize_t arrays[3];
  2077. int ret = -1;
  2078. /* rvalue must be an exporter */
  2079. if (PyObject_GetBuffer(value, &src, PyBUF_FULL_RO) < 0)
  2080. return ret;
  2081. dest = *view;
  2082. dest.shape = &arrays[0]; dest.shape[0] = view->shape[0];
  2083. dest.strides = &arrays[1]; dest.strides[0] = view->strides[0];
  2084. if (view->suboffsets) {
  2085. dest.suboffsets = &arrays[2]; dest.suboffsets[0] = view->suboffsets[0];
  2086. }
  2087. if (init_slice(&dest, key, 0) < 0)
  2088. goto end_block;
  2089. dest.len = dest.shape[0] * dest.itemsize;
  2090. ret = copy_single(&dest, &src);
  2091. end_block:
  2092. PyBuffer_Release(&src);
  2093. return ret;
  2094. }
  2095. if (is_multiindex(key)) {
  2096. char *ptr;
  2097. if (PyTuple_GET_SIZE(key) < view->ndim) {
  2098. PyErr_SetString(PyExc_NotImplementedError,
  2099. "sub-views are not implemented");
  2100. return -1;
  2101. }
  2102. ptr = ptr_from_tuple(view, key);
  2103. if (ptr == NULL)
  2104. return -1;
  2105. return pack_single(ptr, value, fmt);
  2106. }
  2107. if (PySlice_Check(key) || is_multislice(key)) {
  2108. /* Call memory_subscript() to produce a sliced lvalue, then copy
  2109. rvalue into lvalue. This is already implemented in _testbuffer.c. */
  2110. PyErr_SetString(PyExc_NotImplementedError,
  2111. "memoryview slice assignments are currently restricted "
  2112. "to ndim = 1");
  2113. return -1;
  2114. }
  2115. PyErr_SetString(PyExc_TypeError, "memoryview: invalid slice key");
  2116. return -1;
  2117. }
  2118. static Py_ssize_t
  2119. memory_length(PyMemoryViewObject *self)
  2120. {
  2121. CHECK_RELEASED_INT(self);
  2122. return self->view.ndim == 0 ? 1 : self->view.shape[0];
  2123. }
  2124. /* As mapping */
  2125. static PyMappingMethods memory_as_mapping = {
  2126. (lenfunc)memory_length, /* mp_length */
  2127. (binaryfunc)memory_subscript, /* mp_subscript */
  2128. (objobjargproc)memory_ass_sub, /* mp_ass_subscript */
  2129. };
  2130. /* As sequence */
  2131. static PySequenceMethods memory_as_sequence = {
  2132. (lenfunc)memory_length, /* sq_length */
  2133. 0, /* sq_concat */
  2134. 0, /* sq_repeat */
  2135. (ssizeargfunc)memory_item, /* sq_item */
  2136. };
  2137. /**************************************************************************/
  2138. /* Comparisons */
  2139. /**************************************************************************/
  2140. #define MV_COMPARE_EX -1 /* exception */
  2141. #define MV_COMPARE_NOT_IMPL -2 /* not implemented */
  2142. /* Translate a StructError to "not equal". Preserve other exceptions. */
  2143. static int
  2144. fix_struct_error_int(void)
  2145. {
  2146. assert(PyErr_Occurred());
  2147. /* XXX Cannot get at StructError directly? */
  2148. if (PyErr_ExceptionMatches(PyExc_ImportError) ||
  2149. PyErr_ExceptionMatches(PyExc_MemoryError)) {
  2150. return MV_COMPARE_EX;
  2151. }
  2152. /* StructError: invalid or unknown format -> not equal */
  2153. PyErr_Clear();
  2154. return 0;
  2155. }
  2156. /* Unpack and compare single items of p and q using the struct module. */
  2157. static int
  2158. struct_unpack_cmp(const char *p, const char *q,
  2159. struct unpacker *unpack_p, struct unpacker *unpack_q)
  2160. {
  2161. PyObject *v, *w;
  2162. int ret;
  2163. /* At this point any exception from the struct module should not be
  2164. StructError, since both formats have been accepted already. */
  2165. v = struct_unpack_single(p, unpack_p);
  2166. if (v == NULL)
  2167. return MV_COMPARE_EX;
  2168. w = struct_unpack_single(q, unpack_q);
  2169. if (w == NULL) {
  2170. Py_DECREF(v);
  2171. return MV_COMPARE_EX;
  2172. }
  2173. /* MV_COMPARE_EX == -1: exceptions are preserved */
  2174. ret = PyObject_RichCompareBool(v, w, Py_EQ);
  2175. Py_DECREF(v);
  2176. Py_DECREF(w);
  2177. return ret;
  2178. }
  2179. /* Unpack and compare single items of p and q. If both p and q have the same
  2180. single element native format, the comparison uses a fast path (gcc creates
  2181. a jump table and converts memcpy into simple assignments on x86/x64).
  2182. Otherwise, the comparison is delegated to the struct module, which is
  2183. 30-60x slower. */
  2184. #define CMP_SINGLE(p, q, type) \
  2185. do { \
  2186. type x; \
  2187. type y; \
  2188. memcpy((char *)&x, p, sizeof x); \
  2189. memcpy((char *)&y, q, sizeof y); \
  2190. equal = (x == y); \
  2191. } while (0)
  2192. Py_LOCAL_INLINE(int)
  2193. unpack_cmp(const char *p, const char *q, char fmt,
  2194. struct unpacker *unpack_p, struct unpacker *unpack_q)
  2195. {
  2196. int equal;
  2197. switch (fmt) {
  2198. /* signed integers and fast path for 'B' */
  2199. case 'B': return *((unsigned char *)p) == *((unsigned char *)q);
  2200. case 'b': return *((signed char *)p) == *((signed char *)q);
  2201. case 'h': CMP_SINGLE(p, q, short); return equal;
  2202. case 'i': CMP_SINGLE(p, q, int); return equal;
  2203. case 'l': CMP_SINGLE(p, q, long); return equal;
  2204. /* boolean */
  2205. #ifdef HAVE_C99_BOOL
  2206. case '?': CMP_SINGLE(p, q, _Bool); return equal;
  2207. #else
  2208. case '?': CMP_SINGLE(p, q, char); return equal;
  2209. #endif
  2210. /* unsigned integers */
  2211. case 'H': CMP_SINGLE(p, q, unsigned short); return equal;
  2212. case 'I': CMP_SINGLE(p, q, unsigned int); return equal;
  2213. case 'L': CMP_SINGLE(p, q, unsigned long); return equal;
  2214. /* native 64-bit */
  2215. #ifdef HAVE_LONG_LONG
  2216. case 'q': CMP_SINGLE(p, q, PY_LONG_LONG); return equal;
  2217. case 'Q': CMP_SINGLE(p, q, unsigned PY_LONG_LONG); return equal;
  2218. #endif
  2219. /* ssize_t and size_t */
  2220. case 'n': CMP_SINGLE(p, q, Py_ssize_t); return equal;
  2221. case 'N': CMP_SINGLE(p, q, size_t); return equal;
  2222. /* floats */
  2223. /* XXX DBL_EPSILON? */
  2224. case 'f': CMP_SINGLE(p, q, float); return equal;
  2225. case 'd': CMP_SINGLE(p, q, double); return equal;
  2226. /* bytes object */
  2227. case 'c': return *p == *q;
  2228. /* pointer */
  2229. case 'P': CMP_SINGLE(p, q, void *); return equal;
  2230. /* use the struct module */
  2231. case '_':
  2232. assert(unpack_p);
  2233. assert(unpack_q);
  2234. return struct_unpack_cmp(p, q, unpack_p, unpack_q);
  2235. }
  2236. /* NOT REACHED */
  2237. PyErr_SetString(PyExc_RuntimeError,
  2238. "memoryview: internal error in richcompare");
  2239. return MV_COMPARE_EX;
  2240. }
  2241. /* Base case for recursive array comparisons. Assumption: ndim == 1. */
  2242. static int
  2243. cmp_base(const char *p, const char *q, const Py_ssize_t *shape,
  2244. const Py_ssize_t *pstrides, const Py_ssize_t *psuboffsets,
  2245. const Py_ssize_t *qstrides, const Py_ssize_t *qsuboffsets,
  2246. char fmt, struct unpacker *unpack_p, struct unpacker *unpack_q)
  2247. {
  2248. Py_ssize_t i;
  2249. int equal;
  2250. for (i = 0; i < shape[0]; p+=pstrides[0], q+=qstrides[0], i++) {
  2251. const char *xp = ADJUST_PTR(p, psuboffsets, 0);
  2252. const char *xq = ADJUST_PTR(q, qsuboffsets, 0);
  2253. equal = unpack_cmp(xp, xq, fmt, unpack_p, unpack_q);
  2254. if (equal <= 0)
  2255. return equal;
  2256. }
  2257. return 1;
  2258. }
  2259. /* Recursively compare two multi-dimensional arrays that have the same
  2260. logical structure. Assumption: ndim >= 1. */
  2261. static int
  2262. cmp_rec(const char *p, const char *q,
  2263. Py_ssize_t ndim, const Py_ssize_t *shape,
  2264. const Py_ssize_t *pstrides, const Py_ssize_t *psuboffsets,
  2265. const Py_ssize_t *qstrides, const Py_ssize_t *qsuboffsets,
  2266. char fmt, struct unpacker *unpack_p, struct unpacker *unpack_q)
  2267. {
  2268. Py_ssize_t i;
  2269. int equal;
  2270. assert(ndim >= 1);
  2271. assert(shape != NULL);
  2272. assert(pstrides != NULL);
  2273. assert(qstrides != NULL);
  2274. if (ndim == 1) {
  2275. return cmp_base(p, q, shape,
  2276. pstrides, psuboffsets,
  2277. qstrides, qsuboffsets,
  2278. fmt, unpack_p, unpack_q);
  2279. }
  2280. for (i = 0; i < shape[0]; p+=pstrides[0], q+=qstrides[0], i++) {
  2281. const char *xp = ADJUST_PTR(p, psuboffsets, 0);
  2282. const char *xq = ADJUST_PTR(q, qsuboffsets, 0);
  2283. equal = cmp_rec(xp, xq, ndim-1, shape+1,
  2284. pstrides+1, psuboffsets ? psuboffsets+1 : NULL,
  2285. qstrides+1, qsuboffsets ? qsuboffsets+1 : NULL,
  2286. fmt, unpack_p, unpack_q);
  2287. if (equal <= 0)
  2288. return equal;
  2289. }
  2290. return 1;
  2291. }
  2292. static PyObject *
  2293. memory_richcompare(PyObject *v, PyObject *w, int op)
  2294. {
  2295. PyObject *res;
  2296. Py_buffer wbuf, *vv;
  2297. Py_buffer *ww = NULL;
  2298. struct unpacker *unpack_v = NULL;
  2299. struct unpacker *unpack_w = NULL;
  2300. char vfmt, wfmt;
  2301. int equal = MV_COMPARE_NOT_IMPL;
  2302. if (op != Py_EQ && op != Py_NE)
  2303. goto result; /* Py_NotImplemented */
  2304. assert(PyMemoryView_Check(v));
  2305. if (BASE_INACCESSIBLE(v)) {
  2306. equal = (v == w);
  2307. goto result;
  2308. }
  2309. vv = VIEW_ADDR(v);
  2310. if (PyMemoryView_Check(w)) {
  2311. if (BASE_INACCESSIBLE(w)) {
  2312. equal = (v == w);
  2313. goto result;
  2314. }
  2315. ww = VIEW_ADDR(w);
  2316. }
  2317. else {
  2318. if (PyObject_GetBuffer(w, &wbuf, PyBUF_FULL_RO) < 0) {
  2319. PyErr_Clear();
  2320. goto result; /* Py_NotImplemented */
  2321. }
  2322. ww = &wbuf;
  2323. }
  2324. if (!equiv_shape(vv, ww)) {
  2325. PyErr_Clear();
  2326. equal = 0;
  2327. goto result;
  2328. }
  2329. /* Use fast unpacking for identical primitive C type formats. */
  2330. if (get_native_fmtchar(&vfmt, vv->format) < 0)
  2331. vfmt = '_';
  2332. if (get_native_fmtchar(&wfmt, ww->format) < 0)
  2333. wfmt = '_';
  2334. if (vfmt == '_' || wfmt == '_' || vfmt != wfmt) {
  2335. /* Use struct module unpacking. NOTE: Even for equal format strings,
  2336. memcmp() cannot be used for item comparison since it would give
  2337. incorrect results in the case of NaNs or uninitialized padding
  2338. bytes. */
  2339. vfmt = '_';
  2340. unpack_v = struct_get_unpacker(vv->format, vv->itemsize);
  2341. if (unpack_v == NULL) {
  2342. equal = fix_struct_error_int();
  2343. goto result;
  2344. }
  2345. unpack_w = struct_get_unpacker(ww->format, ww->itemsize);
  2346. if (unpack_w == NULL) {
  2347. equal = fix_struct_error_int();
  2348. goto result;
  2349. }
  2350. }
  2351. if (vv->ndim == 0) {
  2352. equal = unpack_cmp(vv->buf, ww->buf,
  2353. vfmt, unpack_v, unpack_w);
  2354. }
  2355. else if (vv->ndim == 1) {
  2356. equal = cmp_base(vv->buf, ww->buf, vv->shape,
  2357. vv->strides, vv->suboffsets,
  2358. ww->strides, ww->suboffsets,
  2359. vfmt, unpack_v, unpack_w);
  2360. }
  2361. else {
  2362. equal = cmp_rec(vv->buf, ww->buf, vv->ndim, vv->shape,
  2363. vv->strides, vv->suboffsets,
  2364. ww->strides, ww->suboffsets,
  2365. vfmt, unpack_v, unpack_w);
  2366. }
  2367. result:
  2368. if (equal < 0) {
  2369. if (equal == MV_COMPARE_NOT_IMPL)
  2370. res = Py_NotImplemented;
  2371. else /* exception */
  2372. res = NULL;
  2373. }
  2374. else if ((equal && op == Py_EQ) || (!equal && op == Py_NE))
  2375. res = Py_True;
  2376. else
  2377. res = Py_False;
  2378. if (ww == &wbuf)
  2379. PyBuffer_Release(ww);
  2380. unpacker_free(unpack_v);
  2381. unpacker_free(unpack_w);
  2382. Py_XINCREF(res);
  2383. return res;
  2384. }
  2385. /**************************************************************************/
  2386. /* Hash */
  2387. /**************************************************************************/
  2388. static Py_hash_t
  2389. memory_hash(PyMemoryViewObject *self)
  2390. {
  2391. if (self->hash == -1) {
  2392. Py_buffer *view = &self->view;
  2393. char *mem = view->buf;
  2394. Py_ssize_t ret;
  2395. char fmt;
  2396. CHECK_RELEASED_INT(self);
  2397. if (!view->readonly) {
  2398. PyErr_SetString(PyExc_ValueError,
  2399. "cannot hash writable memoryview object");
  2400. return -1;
  2401. }
  2402. ret = get_native_fmtchar(&fmt, view->format);
  2403. if (ret < 0 || !IS_BYTE_FORMAT(fmt)) {
  2404. PyErr_SetString(PyExc_ValueError,
  2405. "memoryview: hashing is restricted to formats 'B', 'b' or 'c'");
  2406. return -1;
  2407. }
  2408. if (view->obj != NULL && PyObject_Hash(view->obj) == -1) {
  2409. /* Keep the original error message */
  2410. return -1;
  2411. }
  2412. if (!MV_C_CONTIGUOUS(self->flags)) {
  2413. mem = PyMem_Malloc(view->len);
  2414. if (mem == NULL) {
  2415. PyErr_NoMemory();
  2416. return -1;
  2417. }
  2418. if (buffer_to_contiguous(mem, view, 'C') < 0) {
  2419. PyMem_Free(mem);
  2420. return -1;
  2421. }
  2422. }
  2423. /* Can't fail */
  2424. self->hash = _Py_HashBytes(mem, view->len);
  2425. if (mem != view->buf)
  2426. PyMem_Free(mem);
  2427. }
  2428. return self->hash;
  2429. }
  2430. /**************************************************************************/
  2431. /* getters */
  2432. /**************************************************************************/
  2433. static PyObject *
  2434. _IntTupleFromSsizet(int len, Py_ssize_t *vals)
  2435. {
  2436. int i;
  2437. PyObject *o;
  2438. PyObject *intTuple;
  2439. if (vals == NULL)
  2440. return PyTuple_New(0);
  2441. intTuple = PyTuple_New(len);
  2442. if (!intTuple)
  2443. return NULL;
  2444. for (i=0; i<len; i++) {
  2445. o = PyLong_FromSsize_t(vals[i]);
  2446. if (!o) {
  2447. Py_DECREF(intTuple);
  2448. return NULL;
  2449. }
  2450. PyTuple_SET_ITEM(intTuple, i, o);
  2451. }
  2452. return intTuple;
  2453. }
  2454. static PyObject *
  2455. memory_obj_get(PyMemoryViewObject *self)
  2456. {
  2457. Py_buffer *view = &self->view;
  2458. CHECK_RELEASED(self);
  2459. if (view->obj == NULL) {
  2460. Py_RETURN_NONE;
  2461. }
  2462. Py_INCREF(view->obj);
  2463. return view->obj;
  2464. }
  2465. static PyObject *
  2466. memory_nbytes_get(PyMemoryViewObject *self)
  2467. {
  2468. CHECK_RELEASED(self);
  2469. return PyLong_FromSsize_t(self->view.len);
  2470. }
  2471. static PyObject *
  2472. memory_format_get(PyMemoryViewObject *self)
  2473. {
  2474. CHECK_RELEASED(self);
  2475. return PyUnicode_FromString(self->view.format);
  2476. }
  2477. static PyObject *
  2478. memory_itemsize_get(PyMemoryViewObject *self)
  2479. {
  2480. CHECK_RELEASED(self);
  2481. return PyLong_FromSsize_t(self->view.itemsize);
  2482. }
  2483. static PyObject *
  2484. memory_shape_get(PyMemoryViewObject *self)
  2485. {
  2486. CHECK_RELEASED(self);
  2487. return _IntTupleFromSsizet(self->view.ndim, self->view.shape);
  2488. }
  2489. static PyObject *
  2490. memory_strides_get(PyMemoryViewObject *self)
  2491. {
  2492. CHECK_RELEASED(self);
  2493. return _IntTupleFromSsizet(self->view.ndim, self->view.strides);
  2494. }
  2495. static PyObject *
  2496. memory_suboffsets_get(PyMemoryViewObject *self)
  2497. {
  2498. CHECK_RELEASED(self);
  2499. return _IntTupleFromSsizet(self->view.ndim, self->view.suboffsets);
  2500. }
  2501. static PyObject *
  2502. memory_readonly_get(PyMemoryViewObject *self)
  2503. {
  2504. CHECK_RELEASED(self);
  2505. return PyBool_FromLong(self->view.readonly);
  2506. }
  2507. static PyObject *
  2508. memory_ndim_get(PyMemoryViewObject *self)
  2509. {
  2510. CHECK_RELEASED(self);
  2511. return PyLong_FromLong(self->view.ndim);
  2512. }
  2513. static PyObject *
  2514. memory_c_contiguous(PyMemoryViewObject *self, PyObject *dummy)
  2515. {
  2516. CHECK_RELEASED(self);
  2517. return PyBool_FromLong(MV_C_CONTIGUOUS(self->flags));
  2518. }
  2519. static PyObject *
  2520. memory_f_contiguous(PyMemoryViewObject *self, PyObject *dummy)
  2521. {
  2522. CHECK_RELEASED(self);
  2523. return PyBool_FromLong(MV_F_CONTIGUOUS(self->flags));
  2524. }
  2525. static PyObject *
  2526. memory_contiguous(PyMemoryViewObject *self, PyObject *dummy)
  2527. {
  2528. CHECK_RELEASED(self);
  2529. return PyBool_FromLong(MV_ANY_CONTIGUOUS(self->flags));
  2530. }
  2531. PyDoc_STRVAR(memory_obj_doc,
  2532. "The underlying object of the memoryview.");
  2533. PyDoc_STRVAR(memory_nbytes_doc,
  2534. "The amount of space in bytes that the array would use in\n"
  2535. " a contiguous representation.");
  2536. PyDoc_STRVAR(memory_readonly_doc,
  2537. "A bool indicating whether the memory is read only.");
  2538. PyDoc_STRVAR(memory_itemsize_doc,
  2539. "The size in bytes of each element of the memoryview.");
  2540. PyDoc_STRVAR(memory_format_doc,
  2541. "A string containing the format (in struct module style)\n"
  2542. " for each element in the view.");
  2543. PyDoc_STRVAR(memory_ndim_doc,
  2544. "An integer indicating how many dimensions of a multi-dimensional\n"
  2545. " array the memory represents.");
  2546. PyDoc_STRVAR(memory_shape_doc,
  2547. "A tuple of ndim integers giving the shape of the memory\n"
  2548. " as an N-dimensional array.");
  2549. PyDoc_STRVAR(memory_strides_doc,
  2550. "A tuple of ndim integers giving the size in bytes to access\n"
  2551. " each element for each dimension of the array.");
  2552. PyDoc_STRVAR(memory_suboffsets_doc,
  2553. "A tuple of integers used internally for PIL-style arrays.");
  2554. PyDoc_STRVAR(memory_c_contiguous_doc,
  2555. "A bool indicating whether the memory is C contiguous.");
  2556. PyDoc_STRVAR(memory_f_contiguous_doc,
  2557. "A bool indicating whether the memory is Fortran contiguous.");
  2558. PyDoc_STRVAR(memory_contiguous_doc,
  2559. "A bool indicating whether the memory is contiguous.");
  2560. static PyGetSetDef memory_getsetlist[] = {
  2561. {"obj", (getter)memory_obj_get, NULL, memory_obj_doc},
  2562. {"nbytes", (getter)memory_nbytes_get, NULL, memory_nbytes_doc},
  2563. {"readonly", (getter)memory_readonly_get, NULL, memory_readonly_doc},
  2564. {"itemsize", (getter)memory_itemsize_get, NULL, memory_itemsize_doc},
  2565. {"format", (getter)memory_format_get, NULL, memory_format_doc},
  2566. {"ndim", (getter)memory_ndim_get, NULL, memory_ndim_doc},
  2567. {"shape", (getter)memory_shape_get, NULL, memory_shape_doc},
  2568. {"strides", (getter)memory_strides_get, NULL, memory_strides_doc},
  2569. {"suboffsets", (getter)memory_suboffsets_get, NULL, memory_suboffsets_doc},
  2570. {"c_contiguous", (getter)memory_c_contiguous, NULL, memory_c_contiguous_doc},
  2571. {"f_contiguous", (getter)memory_f_contiguous, NULL, memory_f_contiguous_doc},
  2572. {"contiguous", (getter)memory_contiguous, NULL, memory_contiguous_doc},
  2573. {NULL, NULL, NULL, NULL},
  2574. };
  2575. PyDoc_STRVAR(memory_release_doc,
  2576. "release($self, /)\n--\n\
  2577. \n\
  2578. Release the underlying buffer exposed by the memoryview object.");
  2579. PyDoc_STRVAR(memory_tobytes_doc,
  2580. "tobytes($self, /)\n--\n\
  2581. \n\
  2582. Return the data in the buffer as a byte string.");
  2583. PyDoc_STRVAR(memory_tolist_doc,
  2584. "tolist($self, /)\n--\n\
  2585. \n\
  2586. Return the data in the buffer as a list of elements.");
  2587. PyDoc_STRVAR(memory_cast_doc,
  2588. "cast($self, /, format, *, shape)\n--\n\
  2589. \n\
  2590. Cast a memoryview to a new format or shape.");
  2591. static PyMethodDef memory_methods[] = {
  2592. {"release", (PyCFunction)memory_release, METH_NOARGS, memory_release_doc},
  2593. {"tobytes", (PyCFunction)memory_tobytes, METH_NOARGS, memory_tobytes_doc},
  2594. {"tolist", (PyCFunction)memory_tolist, METH_NOARGS, memory_tolist_doc},
  2595. {"cast", (PyCFunction)memory_cast, METH_VARARGS|METH_KEYWORDS, memory_cast_doc},
  2596. {"__enter__", memory_enter, METH_NOARGS, NULL},
  2597. {"__exit__", memory_exit, METH_VARARGS, NULL},
  2598. {NULL, NULL}
  2599. };
  2600. PyTypeObject PyMemoryView_Type = {
  2601. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  2602. "memoryview", /* tp_name */
  2603. offsetof(PyMemoryViewObject, ob_array), /* tp_basicsize */
  2604. sizeof(Py_ssize_t), /* tp_itemsize */
  2605. (destructor)memory_dealloc, /* tp_dealloc */
  2606. 0, /* tp_print */
  2607. 0, /* tp_getattr */
  2608. 0, /* tp_setattr */
  2609. 0, /* tp_reserved */
  2610. (reprfunc)memory_repr, /* tp_repr */
  2611. 0, /* tp_as_number */
  2612. &memory_as_sequence, /* tp_as_sequence */
  2613. &memory_as_mapping, /* tp_as_mapping */
  2614. (hashfunc)memory_hash, /* tp_hash */
  2615. 0, /* tp_call */
  2616. 0, /* tp_str */
  2617. PyObject_GenericGetAttr, /* tp_getattro */
  2618. 0, /* tp_setattro */
  2619. &memory_as_buffer, /* tp_as_buffer */
  2620. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
  2621. memory_doc, /* tp_doc */
  2622. (traverseproc)memory_traverse, /* tp_traverse */
  2623. (inquiry)memory_clear, /* tp_clear */
  2624. memory_richcompare, /* tp_richcompare */
  2625. offsetof(PyMemoryViewObject, weakreflist),/* tp_weaklistoffset */
  2626. 0, /* tp_iter */
  2627. 0, /* tp_iternext */
  2628. memory_methods, /* tp_methods */
  2629. 0, /* tp_members */
  2630. memory_getsetlist, /* tp_getset */
  2631. 0, /* tp_base */
  2632. 0, /* tp_dict */
  2633. 0, /* tp_descr_get */
  2634. 0, /* tp_descr_set */
  2635. 0, /* tp_dictoffset */
  2636. 0, /* tp_init */
  2637. 0, /* tp_alloc */
  2638. memory_new, /* tp_new */
  2639. };