blob: d65c1449eb38e5c308c9983d77bab0e3841817f2 [file] [log] [blame]
Guido van Rossum778983b1993-02-19 15:55:02 +00001/* Array object implementation */
2
3/* An array is a uniform list -- all items have the same type.
4 The item type is restricted to simple C types like int or float */
5
Martin v. Löwis18e16552006-02-15 17:27:45 +00006#define PY_SSIZE_T_CLEAN
Roger E. Masse2919eaa1996-12-09 20:10:36 +00007#include "Python.h"
Victor Stinnercdad2722021-04-22 00:52:52 +02008#include "pycore_moduleobject.h" // _PyModule_GetState()
Erlend Egeberg Aasland75bf1072021-01-02 17:38:47 +01009#include "structmember.h" // PyMemberDef
Victor Stinner4a21e572020-04-15 02:35:41 +020010#include <stddef.h> // offsetof()
Roger E. Masse5817f8f1996-12-09 22:24:19 +000011
Guido van Rossum0c709541994-08-19 12:01:32 +000012#ifdef STDC_HEADERS
13#include <stddef.h>
Guido van Rossum7f1de831999-08-27 20:33:52 +000014#else /* !STDC_HEADERS */
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015#ifdef HAVE_SYS_TYPES_H
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000016#include <sys/types.h> /* For size_t */
Thomas Wouters0e3f5912006-08-11 14:57:12 +000017#endif /* HAVE_SYS_TYPES_H */
Guido van Rossum7f1de831999-08-27 20:33:52 +000018#endif /* !STDC_HEADERS */
Guido van Rossum778983b1993-02-19 15:55:02 +000019
Brett Cannon1eb32c22014-10-10 16:26:45 -040020/*[clinic input]
Brett Cannon1eb32c22014-10-10 16:26:45 -040021module array
22[clinic start generated code]*/
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030023/*[clinic end generated code: output=da39a3ee5e6b4b0d input=7d1b8d7f5958fd83]*/
Brett Cannon1eb32c22014-10-10 16:26:45 -040024
Guido van Rossum778983b1993-02-19 15:55:02 +000025struct arrayobject; /* Forward */
Erlend Egeberg Aasland75bf1072021-01-02 17:38:47 +010026static struct PyModuleDef arraymodule;
Guido van Rossum778983b1993-02-19 15:55:02 +000027
Tim Petersbb307342000-09-10 05:22:54 +000028/* All possible arraydescr values are defined in the vector "descriptors"
29 * below. That's defined later because the appropriate get and set
30 * functions aren't visible yet.
31 */
Guido van Rossum778983b1993-02-19 15:55:02 +000032struct arraydescr {
Victor Stinnerf8bb7d02011-09-30 00:03:59 +020033 char typecode;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000034 int itemsize;
35 PyObject * (*getitem)(struct arrayobject *, Py_ssize_t);
36 int (*setitem)(struct arrayobject *, Py_ssize_t, PyObject *);
Adrian Wielgosik7c17e232017-08-17 12:46:06 +000037 int (*compareitems)(const void *, const void *, Py_ssize_t);
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020038 const char *formats;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000039 int is_integer_type;
40 int is_signed;
Guido van Rossum778983b1993-02-19 15:55:02 +000041};
42
43typedef struct arrayobject {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000044 PyObject_VAR_HEAD
45 char *ob_item;
46 Py_ssize_t allocated;
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020047 const struct arraydescr *ob_descr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000048 PyObject *weakreflist; /* List of weak references */
Hai Shi06cd5b62019-10-21 14:31:46 +080049 Py_ssize_t ob_exports; /* Number of exported buffers */
Guido van Rossum778983b1993-02-19 15:55:02 +000050} arrayobject;
51
Brett Cannon1eb32c22014-10-10 16:26:45 -040052typedef struct {
53 PyObject_HEAD
54 Py_ssize_t index;
55 arrayobject *ao;
56 PyObject* (*getitem)(struct arrayobject *, Py_ssize_t);
57} arrayiterobject;
58
Erlend Egeberg Aasland75bf1072021-01-02 17:38:47 +010059typedef struct {
60 PyTypeObject *ArrayType;
61 PyTypeObject *ArrayIterType;
62} array_state;
Brett Cannon1eb32c22014-10-10 16:26:45 -040063
Erlend Egeberg Aasland75bf1072021-01-02 17:38:47 +010064static array_state *
65get_array_state(PyObject *module)
66{
Victor Stinnercdad2722021-04-22 00:52:52 +020067 return (array_state *)_PyModule_GetState(module);
Erlend Egeberg Aasland75bf1072021-01-02 17:38:47 +010068}
69
70#define find_array_state_by_type(tp) \
71 (get_array_state(_PyType_GetModuleByDef(tp, &arraymodule)))
72#define get_array_state_by_class(cls) \
73 (get_array_state(PyType_GetModule(cls)))
Brett Cannon1eb32c22014-10-10 16:26:45 -040074
Larry Hastingsdfbeb162014-10-13 10:39:41 +010075enum machine_format_code {
76 UNKNOWN_FORMAT = -1,
77 /* UNKNOWN_FORMAT is used to indicate that the machine format for an
78 * array type code cannot be interpreted. When this occurs, a list of
79 * Python objects is used to represent the content of the array
80 * instead of using the memory content of the array directly. In that
81 * case, the array_reconstructor mechanism is bypassed completely, and
82 * the standard array constructor is used instead.
83 *
84 * This is will most likely occur when the machine doesn't use IEEE
85 * floating-point numbers.
86 */
87
88 UNSIGNED_INT8 = 0,
89 SIGNED_INT8 = 1,
90 UNSIGNED_INT16_LE = 2,
91 UNSIGNED_INT16_BE = 3,
92 SIGNED_INT16_LE = 4,
93 SIGNED_INT16_BE = 5,
94 UNSIGNED_INT32_LE = 6,
95 UNSIGNED_INT32_BE = 7,
96 SIGNED_INT32_LE = 8,
97 SIGNED_INT32_BE = 9,
98 UNSIGNED_INT64_LE = 10,
99 UNSIGNED_INT64_BE = 11,
100 SIGNED_INT64_LE = 12,
101 SIGNED_INT64_BE = 13,
102 IEEE_754_FLOAT_LE = 14,
103 IEEE_754_FLOAT_BE = 15,
104 IEEE_754_DOUBLE_LE = 16,
105 IEEE_754_DOUBLE_BE = 17,
106 UTF16_LE = 18,
107 UTF16_BE = 19,
108 UTF32_LE = 20,
109 UTF32_BE = 21
110};
111#define MACHINE_FORMAT_CODE_MIN 0
112#define MACHINE_FORMAT_CODE_MAX 21
113
114
115/*
116 * Must come after arrayobject, arrayiterobject,
117 * and enum machine_code_type definitions.
118 */
Brett Cannon1eb32c22014-10-10 16:26:45 -0400119#include "clinic/arraymodule.c.h"
120
Erlend Egeberg Aasland75bf1072021-01-02 17:38:47 +0100121#define array_Check(op, state) PyObject_TypeCheck(op, state->ArrayType)
Guido van Rossum778983b1993-02-19 15:55:02 +0000122
Raymond Hettinger6e2ee862004-03-14 04:37:50 +0000123static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000124array_resize(arrayobject *self, Py_ssize_t newsize)
Raymond Hettinger6e2ee862004-03-14 04:37:50 +0000125{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000126 char *items;
127 size_t _new_size;
Raymond Hettinger6e2ee862004-03-14 04:37:50 +0000128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000129 if (self->ob_exports > 0 && newsize != Py_SIZE(self)) {
130 PyErr_SetString(PyExc_BufferError,
131 "cannot resize an array that is exporting buffers");
132 return -1;
133 }
Antoine Pitrou3ad3a0d2008-12-18 17:08:32 +0000134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000135 /* Bypass realloc() when a previous overallocation is large enough
136 to accommodate the newsize. If the newsize is 16 smaller than the
137 current size, then proceed with the realloc() to shrink the array.
138 */
Raymond Hettinger6e2ee862004-03-14 04:37:50 +0000139
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000140 if (self->allocated >= newsize &&
141 Py_SIZE(self) < newsize + 16 &&
142 self->ob_item != NULL) {
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100143 Py_SET_SIZE(self, newsize);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000144 return 0;
145 }
Raymond Hettinger6e2ee862004-03-14 04:37:50 +0000146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000147 if (newsize == 0) {
Victor Stinner00d7abd2020-12-01 09:56:42 +0100148 PyMem_Free(self->ob_item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000149 self->ob_item = NULL;
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100150 Py_SET_SIZE(self, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000151 self->allocated = 0;
152 return 0;
153 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000154
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000155 /* This over-allocates proportional to the array size, making room
156 * for additional growth. The over-allocation is mild, but is
157 * enough to give linear-time amortized behavior over a long
158 * sequence of appends() in the presence of a poorly-performing
159 * system realloc().
160 * The growth pattern is: 0, 4, 8, 16, 25, 34, 46, 56, 67, 79, ...
161 * Note, the pattern starts out the same as for lists but then
162 * grows at a smaller rate so that larger arrays only overallocate
163 * by about 1/16th -- this is done because arrays are presumed to be more
164 * memory critical.
165 */
Raymond Hettinger6e2ee862004-03-14 04:37:50 +0000166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000167 _new_size = (newsize >> 4) + (Py_SIZE(self) < 8 ? 3 : 7) + newsize;
168 items = self->ob_item;
169 /* XXX The following multiplication and division does not optimize away
170 like it does for lists since the size is not known at compile time */
171 if (_new_size <= ((~(size_t)0) / self->ob_descr->itemsize))
172 PyMem_RESIZE(items, char, (_new_size * self->ob_descr->itemsize));
173 else
174 items = NULL;
175 if (items == NULL) {
176 PyErr_NoMemory();
177 return -1;
178 }
179 self->ob_item = items;
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100180 Py_SET_SIZE(self, newsize);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000181 self->allocated = _new_size;
182 return 0;
Raymond Hettinger6e2ee862004-03-14 04:37:50 +0000183}
184
Tim Petersbb307342000-09-10 05:22:54 +0000185/****************************************************************************
186Get and Set functions for each type.
187A Get function takes an arrayobject* and an integer index, returning the
188array value at that index wrapped in an appropriate PyObject*.
189A Set function takes an arrayobject, integer index, and PyObject*; sets
190the array value at that index to the raw C data extracted from the PyObject*,
191and returns 0 if successful, else nonzero on failure (PyObject* not of an
192appropriate type or value).
193Note that the basic Get and Set functions do NOT check that the index is
194in bounds; that's the responsibility of the caller.
195****************************************************************************/
Guido van Rossum778983b1993-02-19 15:55:02 +0000196
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000197static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000198b_getitem(arrayobject *ap, Py_ssize_t i)
Guido van Rossum778983b1993-02-19 15:55:02 +0000199{
Disconnect3d13ab5702019-07-11 23:57:42 +0200200 long x = ((signed char *)ap->ob_item)[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000201 return PyLong_FromLong(x);
Guido van Rossum778983b1993-02-19 15:55:02 +0000202}
203
204static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000205b_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
Guido van Rossum778983b1993-02-19 15:55:02 +0000206{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000207 short x;
208 /* PyArg_Parse's 'b' formatter is for an unsigned char, therefore
209 must use the next size up that is signed ('h') and manually do
210 the overflow checking */
211 if (!PyArg_Parse(v, "h;array item must be integer", &x))
212 return -1;
213 else if (x < -128) {
214 PyErr_SetString(PyExc_OverflowError,
215 "signed char is less than minimum");
216 return -1;
217 }
218 else if (x > 127) {
219 PyErr_SetString(PyExc_OverflowError,
220 "signed char is greater than maximum");
221 return -1;
222 }
223 if (i >= 0)
224 ((char *)ap->ob_item)[i] = (char)x;
225 return 0;
Guido van Rossum778983b1993-02-19 15:55:02 +0000226}
227
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000228static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000229BB_getitem(arrayobject *ap, Py_ssize_t i)
Guido van Rossum549ab711997-01-03 19:09:47 +0000230{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000231 long x = ((unsigned char *)ap->ob_item)[i];
232 return PyLong_FromLong(x);
Guido van Rossum549ab711997-01-03 19:09:47 +0000233}
234
Fred Drake541dc3b2000-06-28 17:49:30 +0000235static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000236BB_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
Fred Drake541dc3b2000-06-28 17:49:30 +0000237{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000238 unsigned char x;
239 /* 'B' == unsigned char, maps to PyArg_Parse's 'b' formatter */
240 if (!PyArg_Parse(v, "b;array item must be integer", &x))
241 return -1;
242 if (i >= 0)
243 ((char *)ap->ob_item)[i] = x;
244 return 0;
Fred Drake541dc3b2000-06-28 17:49:30 +0000245}
Guido van Rossum549ab711997-01-03 19:09:47 +0000246
Martin v. Löwis99866332002-03-01 10:27:01 +0000247static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000248u_getitem(arrayobject *ap, Py_ssize_t i)
Martin v. Löwis99866332002-03-01 10:27:01 +0000249{
Inada Naokid5d9a712020-05-11 15:37:25 +0900250 return PyUnicode_FromOrdinal(((wchar_t *) ap->ob_item)[i]);
Martin v. Löwis99866332002-03-01 10:27:01 +0000251}
252
253static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000254u_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
Martin v. Löwis99866332002-03-01 10:27:01 +0000255{
Inada Naokid5d9a712020-05-11 15:37:25 +0900256 PyObject *u;
257 if (!PyArg_Parse(v, "U;array item must be unicode character", &u)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000258 return -1;
Inada Naokid5d9a712020-05-11 15:37:25 +0900259 }
260
261 Py_ssize_t len = PyUnicode_AsWideChar(u, NULL, 0);
262 if (len != 2) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000263 PyErr_SetString(PyExc_TypeError,
264 "array item must be unicode character");
265 return -1;
266 }
Inada Naokid5d9a712020-05-11 15:37:25 +0900267
268 wchar_t w;
269 len = PyUnicode_AsWideChar(u, &w, 1);
270 assert(len == 1);
271
272 if (i >= 0) {
273 ((wchar_t *)ap->ob_item)[i] = w;
274 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000275 return 0;
Martin v. Löwis99866332002-03-01 10:27:01 +0000276}
Martin v. Löwis99866332002-03-01 10:27:01 +0000277
Travis E. Oliphantd5c0add2007-10-12 22:05:15 +0000278
Guido van Rossum549ab711997-01-03 19:09:47 +0000279static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000280h_getitem(arrayobject *ap, Py_ssize_t i)
Guido van Rossum778983b1993-02-19 15:55:02 +0000281{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000282 return PyLong_FromLong((long) ((short *)ap->ob_item)[i]);
Guido van Rossum778983b1993-02-19 15:55:02 +0000283}
284
Travis E. Oliphantd5c0add2007-10-12 22:05:15 +0000285
Guido van Rossum778983b1993-02-19 15:55:02 +0000286static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000287h_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
Guido van Rossum778983b1993-02-19 15:55:02 +0000288{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000289 short x;
290 /* 'h' == signed short, maps to PyArg_Parse's 'h' formatter */
291 if (!PyArg_Parse(v, "h;array item must be integer", &x))
292 return -1;
293 if (i >= 0)
294 ((short *)ap->ob_item)[i] = x;
295 return 0;
Guido van Rossum778983b1993-02-19 15:55:02 +0000296}
297
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000298static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000299HH_getitem(arrayobject *ap, Py_ssize_t i)
Guido van Rossum549ab711997-01-03 19:09:47 +0000300{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000301 return PyLong_FromLong((long) ((unsigned short *)ap->ob_item)[i]);
Guido van Rossum549ab711997-01-03 19:09:47 +0000302}
303
Fred Drake541dc3b2000-06-28 17:49:30 +0000304static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000305HH_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
Fred Drake541dc3b2000-06-28 17:49:30 +0000306{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000307 int x;
308 /* PyArg_Parse's 'h' formatter is for a signed short, therefore
309 must use the next size up and manually do the overflow checking */
310 if (!PyArg_Parse(v, "i;array item must be integer", &x))
311 return -1;
312 else if (x < 0) {
313 PyErr_SetString(PyExc_OverflowError,
314 "unsigned short is less than minimum");
315 return -1;
316 }
317 else if (x > USHRT_MAX) {
318 PyErr_SetString(PyExc_OverflowError,
319 "unsigned short is greater than maximum");
320 return -1;
321 }
322 if (i >= 0)
323 ((short *)ap->ob_item)[i] = (short)x;
324 return 0;
Fred Drake541dc3b2000-06-28 17:49:30 +0000325}
Guido van Rossum549ab711997-01-03 19:09:47 +0000326
327static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000328i_getitem(arrayobject *ap, Py_ssize_t i)
Guido van Rossume77a7571993-11-03 15:01:26 +0000329{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 return PyLong_FromLong((long) ((int *)ap->ob_item)[i]);
Guido van Rossume77a7571993-11-03 15:01:26 +0000331}
332
333static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000334i_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
Guido van Rossume77a7571993-11-03 15:01:26 +0000335{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000336 int x;
337 /* 'i' == signed int, maps to PyArg_Parse's 'i' formatter */
338 if (!PyArg_Parse(v, "i;array item must be integer", &x))
339 return -1;
340 if (i >= 0)
341 ((int *)ap->ob_item)[i] = x;
342 return 0;
Guido van Rossume77a7571993-11-03 15:01:26 +0000343}
344
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000345static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000346II_getitem(arrayobject *ap, Py_ssize_t i)
Guido van Rossum549ab711997-01-03 19:09:47 +0000347{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000348 return PyLong_FromUnsignedLong(
349 (unsigned long) ((unsigned int *)ap->ob_item)[i]);
Guido van Rossum549ab711997-01-03 19:09:47 +0000350}
351
352static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000353II_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
Guido van Rossum549ab711997-01-03 19:09:47 +0000354{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000355 unsigned long x;
orenmn964281a2017-03-09 11:35:28 +0200356 int do_decref = 0; /* if nb_int was called */
357
358 if (!PyLong_Check(v)) {
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +0300359 v = _PyNumber_Index(v);
orenmn964281a2017-03-09 11:35:28 +0200360 if (NULL == v) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000361 return -1;
362 }
orenmn964281a2017-03-09 11:35:28 +0200363 do_decref = 1;
364 }
365 x = PyLong_AsUnsignedLong(v);
366 if (x == (unsigned long)-1 && PyErr_Occurred()) {
367 if (do_decref) {
368 Py_DECREF(v);
369 }
370 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000371 }
372 if (x > UINT_MAX) {
373 PyErr_SetString(PyExc_OverflowError,
orenmn964281a2017-03-09 11:35:28 +0200374 "unsigned int is greater than maximum");
375 if (do_decref) {
376 Py_DECREF(v);
377 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000378 return -1;
379 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000380 if (i >= 0)
381 ((unsigned int *)ap->ob_item)[i] = (unsigned int)x;
orenmn964281a2017-03-09 11:35:28 +0200382
383 if (do_decref) {
384 Py_DECREF(v);
385 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000386 return 0;
Guido van Rossum549ab711997-01-03 19:09:47 +0000387}
388
389static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000390l_getitem(arrayobject *ap, Py_ssize_t i)
Guido van Rossum778983b1993-02-19 15:55:02 +0000391{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000392 return PyLong_FromLong(((long *)ap->ob_item)[i]);
Guido van Rossum778983b1993-02-19 15:55:02 +0000393}
394
395static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000396l_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
Guido van Rossum778983b1993-02-19 15:55:02 +0000397{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000398 long x;
399 if (!PyArg_Parse(v, "l;array item must be integer", &x))
400 return -1;
401 if (i >= 0)
402 ((long *)ap->ob_item)[i] = x;
403 return 0;
Guido van Rossum778983b1993-02-19 15:55:02 +0000404}
405
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000406static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000407LL_getitem(arrayobject *ap, Py_ssize_t i)
Guido van Rossum549ab711997-01-03 19:09:47 +0000408{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000409 return PyLong_FromUnsignedLong(((unsigned long *)ap->ob_item)[i]);
Guido van Rossum549ab711997-01-03 19:09:47 +0000410}
411
412static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000413LL_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
Guido van Rossum549ab711997-01-03 19:09:47 +0000414{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000415 unsigned long x;
orenmn964281a2017-03-09 11:35:28 +0200416 int do_decref = 0; /* if nb_int was called */
417
418 if (!PyLong_Check(v)) {
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +0300419 v = _PyNumber_Index(v);
orenmn964281a2017-03-09 11:35:28 +0200420 if (NULL == v) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 return -1;
422 }
orenmn964281a2017-03-09 11:35:28 +0200423 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000424 }
orenmn964281a2017-03-09 11:35:28 +0200425 x = PyLong_AsUnsignedLong(v);
426 if (x == (unsigned long)-1 && PyErr_Occurred()) {
427 if (do_decref) {
428 Py_DECREF(v);
429 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000430 return -1;
431 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000432 if (i >= 0)
433 ((unsigned long *)ap->ob_item)[i] = x;
orenmn964281a2017-03-09 11:35:28 +0200434
435 if (do_decref) {
436 Py_DECREF(v);
437 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000438 return 0;
Guido van Rossum549ab711997-01-03 19:09:47 +0000439}
440
Meador Inge1c9f0c92011-09-20 19:55:51 -0500441static PyObject *
442q_getitem(arrayobject *ap, Py_ssize_t i)
443{
Benjamin Petersonaf580df2016-09-06 10:46:49 -0700444 return PyLong_FromLongLong(((long long *)ap->ob_item)[i]);
Meador Inge1c9f0c92011-09-20 19:55:51 -0500445}
446
447static int
448q_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
449{
Benjamin Petersonaf580df2016-09-06 10:46:49 -0700450 long long x;
Meador Inge1c9f0c92011-09-20 19:55:51 -0500451 if (!PyArg_Parse(v, "L;array item must be integer", &x))
452 return -1;
453 if (i >= 0)
Benjamin Petersonaf580df2016-09-06 10:46:49 -0700454 ((long long *)ap->ob_item)[i] = x;
Meador Inge1c9f0c92011-09-20 19:55:51 -0500455 return 0;
456}
457
458static PyObject *
459QQ_getitem(arrayobject *ap, Py_ssize_t i)
460{
461 return PyLong_FromUnsignedLongLong(
Benjamin Petersonaf580df2016-09-06 10:46:49 -0700462 ((unsigned long long *)ap->ob_item)[i]);
Meador Inge1c9f0c92011-09-20 19:55:51 -0500463}
464
465static int
466QQ_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
467{
Benjamin Petersonaf580df2016-09-06 10:46:49 -0700468 unsigned long long x;
orenmn964281a2017-03-09 11:35:28 +0200469 int do_decref = 0; /* if nb_int was called */
470
471 if (!PyLong_Check(v)) {
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +0300472 v = _PyNumber_Index(v);
orenmn964281a2017-03-09 11:35:28 +0200473 if (NULL == v) {
Meador Inge1c9f0c92011-09-20 19:55:51 -0500474 return -1;
475 }
orenmn964281a2017-03-09 11:35:28 +0200476 do_decref = 1;
Meador Inge1c9f0c92011-09-20 19:55:51 -0500477 }
orenmn964281a2017-03-09 11:35:28 +0200478 x = PyLong_AsUnsignedLongLong(v);
479 if (x == (unsigned long long)-1 && PyErr_Occurred()) {
480 if (do_decref) {
481 Py_DECREF(v);
482 }
483 return -1;
484 }
Meador Inge1c9f0c92011-09-20 19:55:51 -0500485 if (i >= 0)
Benjamin Petersonaf580df2016-09-06 10:46:49 -0700486 ((unsigned long long *)ap->ob_item)[i] = x;
orenmn964281a2017-03-09 11:35:28 +0200487
488 if (do_decref) {
489 Py_DECREF(v);
490 }
Meador Inge1c9f0c92011-09-20 19:55:51 -0500491 return 0;
492}
Meador Inge1c9f0c92011-09-20 19:55:51 -0500493
Guido van Rossum549ab711997-01-03 19:09:47 +0000494static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000495f_getitem(arrayobject *ap, Py_ssize_t i)
Guido van Rossum778983b1993-02-19 15:55:02 +0000496{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 return PyFloat_FromDouble((double) ((float *)ap->ob_item)[i]);
Guido van Rossum778983b1993-02-19 15:55:02 +0000498}
499
500static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000501f_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
Guido van Rossum778983b1993-02-19 15:55:02 +0000502{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000503 float x;
504 if (!PyArg_Parse(v, "f;array item must be float", &x))
505 return -1;
506 if (i >= 0)
507 ((float *)ap->ob_item)[i] = x;
508 return 0;
Guido van Rossum778983b1993-02-19 15:55:02 +0000509}
510
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000511static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000512d_getitem(arrayobject *ap, Py_ssize_t i)
Guido van Rossum778983b1993-02-19 15:55:02 +0000513{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000514 return PyFloat_FromDouble(((double *)ap->ob_item)[i]);
Guido van Rossum778983b1993-02-19 15:55:02 +0000515}
516
517static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000518d_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
Guido van Rossum778983b1993-02-19 15:55:02 +0000519{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000520 double x;
521 if (!PyArg_Parse(v, "d;array item must be float", &x))
522 return -1;
523 if (i >= 0)
524 ((double *)ap->ob_item)[i] = x;
525 return 0;
Guido van Rossum778983b1993-02-19 15:55:02 +0000526}
527
Adrian Wielgosik7c17e232017-08-17 12:46:06 +0000528#define DEFINE_COMPAREITEMS(code, type) \
529 static int \
530 code##_compareitems(const void *lhs, const void *rhs, Py_ssize_t length) \
531 { \
532 const type *a = lhs, *b = rhs; \
533 for (Py_ssize_t i = 0; i < length; ++i) \
534 if (a[i] != b[i]) \
535 return a[i] < b[i] ? -1 : 1; \
536 return 0; \
537 }
538
539DEFINE_COMPAREITEMS(b, signed char)
540DEFINE_COMPAREITEMS(BB, unsigned char)
Inada Naokid5d9a712020-05-11 15:37:25 +0900541DEFINE_COMPAREITEMS(u, wchar_t)
Adrian Wielgosik7c17e232017-08-17 12:46:06 +0000542DEFINE_COMPAREITEMS(h, short)
543DEFINE_COMPAREITEMS(HH, unsigned short)
544DEFINE_COMPAREITEMS(i, int)
545DEFINE_COMPAREITEMS(II, unsigned int)
546DEFINE_COMPAREITEMS(l, long)
547DEFINE_COMPAREITEMS(LL, unsigned long)
548DEFINE_COMPAREITEMS(q, long long)
549DEFINE_COMPAREITEMS(QQ, unsigned long long)
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000550
Alexandre Vassalottiad077152009-07-15 17:49:23 +0000551/* Description of types.
552 *
553 * Don't forget to update typecode_to_mformat_code() if you add a new
554 * typecode.
555 */
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200556static const struct arraydescr descriptors[] = {
Adrian Wielgosik7c17e232017-08-17 12:46:06 +0000557 {'b', 1, b_getitem, b_setitem, b_compareitems, "b", 1, 1},
558 {'B', 1, BB_getitem, BB_setitem, BB_compareitems, "B", 1, 0},
Inada Naokid5d9a712020-05-11 15:37:25 +0900559 {'u', sizeof(wchar_t), u_getitem, u_setitem, u_compareitems, "u", 0, 0},
Adrian Wielgosik7c17e232017-08-17 12:46:06 +0000560 {'h', sizeof(short), h_getitem, h_setitem, h_compareitems, "h", 1, 1},
561 {'H', sizeof(short), HH_getitem, HH_setitem, HH_compareitems, "H", 1, 0},
562 {'i', sizeof(int), i_getitem, i_setitem, i_compareitems, "i", 1, 1},
563 {'I', sizeof(int), II_getitem, II_setitem, II_compareitems, "I", 1, 0},
564 {'l', sizeof(long), l_getitem, l_setitem, l_compareitems, "l", 1, 1},
565 {'L', sizeof(long), LL_getitem, LL_setitem, LL_compareitems, "L", 1, 0},
566 {'q', sizeof(long long), q_getitem, q_setitem, q_compareitems, "q", 1, 1},
567 {'Q', sizeof(long long), QQ_getitem, QQ_setitem, QQ_compareitems, "Q", 1, 0},
568 {'f', sizeof(float), f_getitem, f_setitem, NULL, "f", 0, 0},
569 {'d', sizeof(double), d_getitem, d_setitem, NULL, "d", 0, 0},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000570 {'\0', 0, 0, 0, 0, 0, 0} /* Sentinel */
Guido van Rossum778983b1993-02-19 15:55:02 +0000571};
Tim Petersbb307342000-09-10 05:22:54 +0000572
573/****************************************************************************
574Implementations of array object methods.
575****************************************************************************/
Brett Cannon1eb32c22014-10-10 16:26:45 -0400576/*[clinic input]
Erlend Egeberg Aasland75bf1072021-01-02 17:38:47 +0100577class array.array "arrayobject *" "ArrayType"
Brett Cannon1eb32c22014-10-10 16:26:45 -0400578[clinic start generated code]*/
Erlend Egeberg Aasland75bf1072021-01-02 17:38:47 +0100579/*[clinic end generated code: output=da39a3ee5e6b4b0d input=a5c29edf59f176a3]*/
Guido van Rossum778983b1993-02-19 15:55:02 +0000580
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000581static PyObject *
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200582newarrayobject(PyTypeObject *type, Py_ssize_t size, const struct arraydescr *descr)
Guido van Rossum778983b1993-02-19 15:55:02 +0000583{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000584 arrayobject *op;
585 size_t nbytes;
Martin v. Löwis99866332002-03-01 10:27:01 +0000586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000587 if (size < 0) {
588 PyErr_BadInternalCall();
589 return NULL;
590 }
Martin v. Löwis99866332002-03-01 10:27:01 +0000591
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000592 /* Check for overflow */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +0100593 if (size > PY_SSIZE_T_MAX / descr->itemsize) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 return PyErr_NoMemory();
595 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +0100596 nbytes = size * descr->itemsize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000597 op = (arrayobject *) type->tp_alloc(type, 0);
598 if (op == NULL) {
599 return NULL;
600 }
601 op->ob_descr = descr;
602 op->allocated = size;
603 op->weakreflist = NULL;
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100604 Py_SET_SIZE(op, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000605 if (size <= 0) {
606 op->ob_item = NULL;
607 }
608 else {
609 op->ob_item = PyMem_NEW(char, nbytes);
610 if (op->ob_item == NULL) {
611 Py_DECREF(op);
612 return PyErr_NoMemory();
613 }
614 }
615 op->ob_exports = 0;
616 return (PyObject *) op;
Guido van Rossum778983b1993-02-19 15:55:02 +0000617}
618
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000619static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000620getarrayitem(PyObject *op, Py_ssize_t i)
Guido van Rossum778983b1993-02-19 15:55:02 +0000621{
Erlend Egeberg Aasland75bf1072021-01-02 17:38:47 +0100622#ifndef NDEBUG
623 array_state *state = find_array_state_by_type(Py_TYPE(op));
624 assert(array_Check(op, state));
625#endif
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200626 arrayobject *ap;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 ap = (arrayobject *)op;
628 assert(i>=0 && i<Py_SIZE(ap));
629 return (*ap->ob_descr->getitem)(ap, i);
Guido van Rossum778983b1993-02-19 15:55:02 +0000630}
631
632static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000633ins1(arrayobject *self, Py_ssize_t where, PyObject *v)
Guido van Rossum778983b1993-02-19 15:55:02 +0000634{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000635 char *items;
636 Py_ssize_t n = Py_SIZE(self);
637 if (v == NULL) {
638 PyErr_BadInternalCall();
639 return -1;
640 }
641 if ((*self->ob_descr->setitem)(self, -1, v) < 0)
642 return -1;
Raymond Hettinger6e2ee862004-03-14 04:37:50 +0000643
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 if (array_resize(self, n+1) == -1)
645 return -1;
646 items = self->ob_item;
647 if (where < 0) {
648 where += n;
649 if (where < 0)
650 where = 0;
651 }
652 if (where > n)
653 where = n;
654 /* appends don't need to call memmove() */
655 if (where != n)
656 memmove(items + (where+1)*self->ob_descr->itemsize,
657 items + where*self->ob_descr->itemsize,
658 (n-where)*self->ob_descr->itemsize);
659 return (*self->ob_descr->setitem)(self, where, v);
Guido van Rossum778983b1993-02-19 15:55:02 +0000660}
661
Guido van Rossum778983b1993-02-19 15:55:02 +0000662/* Methods */
663
664static void
Peter Schneider-Kamp9656abd2000-07-13 21:10:57 +0000665array_dealloc(arrayobject *op)
Guido van Rossum778983b1993-02-19 15:55:02 +0000666{
Erlend Egeberg Aasland75bf1072021-01-02 17:38:47 +0100667 PyTypeObject *tp = Py_TYPE(op);
668
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000669 if (op->weakreflist != NULL)
670 PyObject_ClearWeakRefs((PyObject *) op);
671 if (op->ob_item != NULL)
Victor Stinner00d7abd2020-12-01 09:56:42 +0100672 PyMem_Free(op->ob_item);
Erlend Egeberg Aasland75bf1072021-01-02 17:38:47 +0100673 tp->tp_free(op);
674 Py_DECREF(tp);
Guido van Rossum778983b1993-02-19 15:55:02 +0000675}
676
Guido van Rossum9d19cb82001-01-18 01:02:55 +0000677static PyObject *
678array_richcompare(PyObject *v, PyObject *w, int op)
Guido van Rossum778983b1993-02-19 15:55:02 +0000679{
Erlend Egeberg Aasland75bf1072021-01-02 17:38:47 +0100680 array_state *state = find_array_state_by_type(Py_TYPE(v));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000681 arrayobject *va, *wa;
682 PyObject *vi = NULL;
683 PyObject *wi = NULL;
684 Py_ssize_t i, k;
685 PyObject *res;
Guido van Rossum9d19cb82001-01-18 01:02:55 +0000686
Erlend Egeberg Aasland75bf1072021-01-02 17:38:47 +0100687 if (!array_Check(v, state) || !array_Check(w, state))
Brian Curtindfc80e32011-08-10 20:28:54 -0500688 Py_RETURN_NOTIMPLEMENTED;
Guido van Rossum9d19cb82001-01-18 01:02:55 +0000689
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000690 va = (arrayobject *)v;
691 wa = (arrayobject *)w;
Guido van Rossum9d19cb82001-01-18 01:02:55 +0000692
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000693 if (Py_SIZE(va) != Py_SIZE(wa) && (op == Py_EQ || op == Py_NE)) {
694 /* Shortcut: if the lengths differ, the arrays differ */
695 if (op == Py_EQ)
696 res = Py_False;
697 else
698 res = Py_True;
699 Py_INCREF(res);
700 return res;
701 }
Guido van Rossum9d19cb82001-01-18 01:02:55 +0000702
Adrian Wielgosik7c17e232017-08-17 12:46:06 +0000703 if (va->ob_descr == wa->ob_descr && va->ob_descr->compareitems != NULL) {
704 /* Fast path:
705 arrays with same types can have their buffers compared directly */
706 Py_ssize_t common_length = Py_MIN(Py_SIZE(va), Py_SIZE(wa));
707 int result = va->ob_descr->compareitems(va->ob_item, wa->ob_item,
708 common_length);
709 if (result == 0)
710 goto compare_sizes;
711
712 int cmp;
713 switch (op) {
714 case Py_LT: cmp = result < 0; break;
715 case Py_LE: cmp = result <= 0; break;
716 case Py_EQ: cmp = result == 0; break;
717 case Py_NE: cmp = result != 0; break;
718 case Py_GT: cmp = result > 0; break;
719 case Py_GE: cmp = result >= 0; break;
720 default: return NULL; /* cannot happen */
721 }
722 PyObject *res = cmp ? Py_True : Py_False;
723 Py_INCREF(res);
724 return res;
725 }
726
727
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000728 /* Search for the first index where items are different */
729 k = 1;
730 for (i = 0; i < Py_SIZE(va) && i < Py_SIZE(wa); i++) {
731 vi = getarrayitem(v, i);
732 wi = getarrayitem(w, i);
733 if (vi == NULL || wi == NULL) {
734 Py_XDECREF(vi);
735 Py_XDECREF(wi);
736 return NULL;
737 }
738 k = PyObject_RichCompareBool(vi, wi, Py_EQ);
739 if (k == 0)
740 break; /* Keeping vi and wi alive! */
741 Py_DECREF(vi);
742 Py_DECREF(wi);
743 if (k < 0)
744 return NULL;
745 }
Guido van Rossum9d19cb82001-01-18 01:02:55 +0000746
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000747 if (k) {
748 /* No more items to compare -- compare sizes */
Adrian Wielgosik7c17e232017-08-17 12:46:06 +0000749 compare_sizes: ;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000750 Py_ssize_t vs = Py_SIZE(va);
751 Py_ssize_t ws = Py_SIZE(wa);
752 int cmp;
753 switch (op) {
754 case Py_LT: cmp = vs < ws; break;
755 case Py_LE: cmp = vs <= ws; break;
Adrian Wielgosik7c17e232017-08-17 12:46:06 +0000756 /* If the lengths were not equal,
757 the earlier fast-path check would have caught that. */
758 case Py_EQ: assert(vs == ws); cmp = 1; break;
759 case Py_NE: assert(vs == ws); cmp = 0; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000760 case Py_GT: cmp = vs > ws; break;
761 case Py_GE: cmp = vs >= ws; break;
762 default: return NULL; /* cannot happen */
763 }
764 if (cmp)
765 res = Py_True;
766 else
767 res = Py_False;
768 Py_INCREF(res);
769 return res;
770 }
Guido van Rossum9d19cb82001-01-18 01:02:55 +0000771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000772 /* We have an item that differs. First, shortcuts for EQ/NE */
773 if (op == Py_EQ) {
774 Py_INCREF(Py_False);
775 res = Py_False;
776 }
777 else if (op == Py_NE) {
778 Py_INCREF(Py_True);
779 res = Py_True;
780 }
781 else {
782 /* Compare the final item again using the proper operator */
783 res = PyObject_RichCompare(vi, wi, op);
784 }
785 Py_DECREF(vi);
786 Py_DECREF(wi);
787 return res;
Guido van Rossum778983b1993-02-19 15:55:02 +0000788}
789
Martin v. Löwis18e16552006-02-15 17:27:45 +0000790static Py_ssize_t
Peter Schneider-Kamp9656abd2000-07-13 21:10:57 +0000791array_length(arrayobject *a)
Guido van Rossum778983b1993-02-19 15:55:02 +0000792{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000793 return Py_SIZE(a);
Guido van Rossum778983b1993-02-19 15:55:02 +0000794}
795
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000796static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000797array_item(arrayobject *a, Py_ssize_t i)
Guido van Rossum778983b1993-02-19 15:55:02 +0000798{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000799 if (i < 0 || i >= Py_SIZE(a)) {
800 PyErr_SetString(PyExc_IndexError, "array index out of range");
801 return NULL;
802 }
803 return getarrayitem((PyObject *)a, i);
Guido van Rossum778983b1993-02-19 15:55:02 +0000804}
805
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000806static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000807array_slice(arrayobject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum778983b1993-02-19 15:55:02 +0000808{
Erlend Egeberg Aasland75bf1072021-01-02 17:38:47 +0100809 array_state *state = find_array_state_by_type(Py_TYPE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000810 arrayobject *np;
Erlend Egeberg Aasland75bf1072021-01-02 17:38:47 +0100811
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 if (ilow < 0)
813 ilow = 0;
814 else if (ilow > Py_SIZE(a))
815 ilow = Py_SIZE(a);
816 if (ihigh < 0)
817 ihigh = 0;
818 if (ihigh < ilow)
819 ihigh = ilow;
820 else if (ihigh > Py_SIZE(a))
821 ihigh = Py_SIZE(a);
Erlend Egeberg Aasland75bf1072021-01-02 17:38:47 +0100822 np = (arrayobject *) newarrayobject(state->ArrayType, ihigh - ilow, a->ob_descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 if (np == NULL)
824 return NULL;
Martin Panterbe8da9c2016-09-07 11:04:41 +0000825 if (ihigh > ilow) {
826 memcpy(np->ob_item, a->ob_item + ilow * a->ob_descr->itemsize,
827 (ihigh-ilow) * a->ob_descr->itemsize);
828 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000829 return (PyObject *)np;
Guido van Rossum778983b1993-02-19 15:55:02 +0000830}
831
Brett Cannon1eb32c22014-10-10 16:26:45 -0400832
833/*[clinic input]
834array.array.__copy__
835
836Return a copy of the array.
837[clinic start generated code]*/
838
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000839static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -0400840array_array___copy___impl(arrayobject *self)
841/*[clinic end generated code: output=dec7c3f925d9619e input=ad1ee5b086965f09]*/
Raymond Hettinger3aa82c02004-03-13 18:18:51 +0000842{
Brett Cannon1eb32c22014-10-10 16:26:45 -0400843 return array_slice(self, 0, Py_SIZE(self));
Raymond Hettinger3aa82c02004-03-13 18:18:51 +0000844}
845
Brett Cannon1eb32c22014-10-10 16:26:45 -0400846/*[clinic input]
847array.array.__deepcopy__
848
849 unused: object
850 /
851
852Return a copy of the array.
853[clinic start generated code]*/
854
855static PyObject *
856array_array___deepcopy__(arrayobject *self, PyObject *unused)
857/*[clinic end generated code: output=1ec748d8e14a9faa input=2405ecb4933748c4]*/
858{
859 return array_array___copy___impl(self);
860}
Raymond Hettinger3aa82c02004-03-13 18:18:51 +0000861
862static PyObject *
Peter Schneider-Kamp9656abd2000-07-13 21:10:57 +0000863array_concat(arrayobject *a, PyObject *bb)
Guido van Rossum778983b1993-02-19 15:55:02 +0000864{
Erlend Egeberg Aasland75bf1072021-01-02 17:38:47 +0100865 array_state *state = find_array_state_by_type(Py_TYPE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 Py_ssize_t size;
867 arrayobject *np;
Erlend Egeberg Aasland75bf1072021-01-02 17:38:47 +0100868 if (!array_Check(bb, state)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000869 PyErr_Format(PyExc_TypeError,
870 "can only append array (not \"%.200s\") to array",
871 Py_TYPE(bb)->tp_name);
872 return NULL;
873 }
Guido van Rossum778983b1993-02-19 15:55:02 +0000874#define b ((arrayobject *)bb)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000875 if (a->ob_descr != b->ob_descr) {
876 PyErr_BadArgument();
877 return NULL;
878 }
879 if (Py_SIZE(a) > PY_SSIZE_T_MAX - Py_SIZE(b)) {
880 return PyErr_NoMemory();
881 }
882 size = Py_SIZE(a) + Py_SIZE(b);
Erlend Egeberg Aasland75bf1072021-01-02 17:38:47 +0100883 np = (arrayobject *) newarrayobject(state->ArrayType, size, a->ob_descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000884 if (np == NULL) {
885 return NULL;
886 }
Martin Panterbe8da9c2016-09-07 11:04:41 +0000887 if (Py_SIZE(a) > 0) {
888 memcpy(np->ob_item, a->ob_item, Py_SIZE(a)*a->ob_descr->itemsize);
889 }
890 if (Py_SIZE(b) > 0) {
891 memcpy(np->ob_item + Py_SIZE(a)*a->ob_descr->itemsize,
892 b->ob_item, Py_SIZE(b)*b->ob_descr->itemsize);
893 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 return (PyObject *)np;
Guido van Rossum778983b1993-02-19 15:55:02 +0000895#undef b
896}
897
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000898static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000899array_repeat(arrayobject *a, Py_ssize_t n)
Guido van Rossum778983b1993-02-19 15:55:02 +0000900{
Erlend Egeberg Aasland75bf1072021-01-02 17:38:47 +0100901 array_state *state = find_array_state_by_type(Py_TYPE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000902 Py_ssize_t size;
903 arrayobject *np;
Georg Brandlc29cc6a2010-12-04 11:02:04 +0000904 Py_ssize_t oldbytes, newbytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000905 if (n < 0)
906 n = 0;
907 if ((Py_SIZE(a) != 0) && (n > PY_SSIZE_T_MAX / Py_SIZE(a))) {
908 return PyErr_NoMemory();
909 }
910 size = Py_SIZE(a) * n;
Erlend Egeberg Aasland75bf1072021-01-02 17:38:47 +0100911 np = (arrayobject *) newarrayobject(state->ArrayType, size, a->ob_descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000912 if (np == NULL)
913 return NULL;
Martin Panterbe8da9c2016-09-07 11:04:41 +0000914 if (size == 0)
Georg Brandlc29cc6a2010-12-04 11:02:04 +0000915 return (PyObject *)np;
916 oldbytes = Py_SIZE(a) * a->ob_descr->itemsize;
917 newbytes = oldbytes * n;
918 /* this follows the code in unicode_repeat */
919 if (oldbytes == 1) {
920 memset(np->ob_item, a->ob_item[0], newbytes);
921 } else {
922 Py_ssize_t done = oldbytes;
Christian Heimesf051e432016-09-13 20:22:02 +0200923 memcpy(np->ob_item, a->ob_item, oldbytes);
Georg Brandlc29cc6a2010-12-04 11:02:04 +0000924 while (done < newbytes) {
925 Py_ssize_t ncopy = (done <= newbytes-done) ? done : newbytes-done;
Christian Heimesf051e432016-09-13 20:22:02 +0200926 memcpy(np->ob_item+done, np->ob_item, ncopy);
Georg Brandlc29cc6a2010-12-04 11:02:04 +0000927 done += ncopy;
928 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000929 }
Georg Brandlc29cc6a2010-12-04 11:02:04 +0000930 return (PyObject *)np;
Guido van Rossum778983b1993-02-19 15:55:02 +0000931}
932
933static int
Martin Panter996d72b2016-07-25 02:21:14 +0000934array_del_slice(arrayobject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum778983b1993-02-19 15:55:02 +0000935{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 char *item;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000937 Py_ssize_t d; /* Change in size */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 if (ilow < 0)
939 ilow = 0;
940 else if (ilow > Py_SIZE(a))
941 ilow = Py_SIZE(a);
942 if (ihigh < 0)
943 ihigh = 0;
944 if (ihigh < ilow)
945 ihigh = ilow;
946 else if (ihigh > Py_SIZE(a))
947 ihigh = Py_SIZE(a);
948 item = a->ob_item;
Martin Panter996d72b2016-07-25 02:21:14 +0000949 d = ihigh-ilow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 /* Issue #4509: If the array has exported buffers and the slice
951 assignment would change the size of the array, fail early to make
952 sure we don't modify it. */
953 if (d != 0 && a->ob_exports > 0) {
954 PyErr_SetString(PyExc_BufferError,
955 "cannot resize an array that is exporting buffers");
956 return -1;
957 }
Martin Panter996d72b2016-07-25 02:21:14 +0000958 if (d > 0) { /* Delete d items */
959 memmove(item + (ihigh-d)*a->ob_descr->itemsize,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 item + ihigh*a->ob_descr->itemsize,
961 (Py_SIZE(a)-ihigh)*a->ob_descr->itemsize);
Martin Panter996d72b2016-07-25 02:21:14 +0000962 if (array_resize(a, Py_SIZE(a) - d) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000963 return -1;
964 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000965 return 0;
Guido van Rossum778983b1993-02-19 15:55:02 +0000966}
967
968static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000969array_ass_item(arrayobject *a, Py_ssize_t i, PyObject *v)
Guido van Rossum778983b1993-02-19 15:55:02 +0000970{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 if (i < 0 || i >= Py_SIZE(a)) {
972 PyErr_SetString(PyExc_IndexError,
973 "array assignment index out of range");
974 return -1;
975 }
976 if (v == NULL)
Martin Panter996d72b2016-07-25 02:21:14 +0000977 return array_del_slice(a, i, i+1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 return (*a->ob_descr->setitem)(a, i, v);
Guido van Rossum778983b1993-02-19 15:55:02 +0000979}
980
981static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000982setarrayitem(PyObject *a, Py_ssize_t i, PyObject *v)
Guido van Rossum778983b1993-02-19 15:55:02 +0000983{
Erlend Egeberg Aasland75bf1072021-01-02 17:38:47 +0100984#ifndef NDEBUG
985 array_state *state = find_array_state_by_type(Py_TYPE(a));
986 assert(array_Check(a, state));
987#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000988 return array_ass_item((arrayobject *)a, i, v);
Guido van Rossum778983b1993-02-19 15:55:02 +0000989}
990
Martin v. Löwis99866332002-03-01 10:27:01 +0000991static int
Raymond Hettinger49f9bd12004-03-14 05:43:59 +0000992array_iter_extend(arrayobject *self, PyObject *bb)
993{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000994 PyObject *it, *v;
Raymond Hettinger49f9bd12004-03-14 05:43:59 +0000995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000996 it = PyObject_GetIter(bb);
997 if (it == NULL)
998 return -1;
Raymond Hettinger49f9bd12004-03-14 05:43:59 +0000999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001000 while ((v = PyIter_Next(it)) != NULL) {
Mark Dickinson346f0af2010-08-06 09:36:57 +00001001 if (ins1(self, Py_SIZE(self), v) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 Py_DECREF(v);
1003 Py_DECREF(it);
1004 return -1;
1005 }
1006 Py_DECREF(v);
1007 }
1008 Py_DECREF(it);
1009 if (PyErr_Occurred())
1010 return -1;
1011 return 0;
Raymond Hettinger49f9bd12004-03-14 05:43:59 +00001012}
1013
1014static int
Erlend Egeberg Aasland75bf1072021-01-02 17:38:47 +01001015array_do_extend(array_state *state, arrayobject *self, PyObject *bb)
Martin v. Löwis99866332002-03-01 10:27:01 +00001016{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 Py_ssize_t size, oldsize, bbsize;
Martin v. Löwis99866332002-03-01 10:27:01 +00001018
Erlend Egeberg Aasland75bf1072021-01-02 17:38:47 +01001019 if (!array_Check(bb, state))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 return array_iter_extend(self, bb);
1021#define b ((arrayobject *)bb)
1022 if (self->ob_descr != b->ob_descr) {
1023 PyErr_SetString(PyExc_TypeError,
1024 "can only extend with array of same kind");
1025 return -1;
1026 }
1027 if ((Py_SIZE(self) > PY_SSIZE_T_MAX - Py_SIZE(b)) ||
1028 ((Py_SIZE(self) + Py_SIZE(b)) > PY_SSIZE_T_MAX / self->ob_descr->itemsize)) {
1029 PyErr_NoMemory();
1030 return -1;
1031 }
1032 oldsize = Py_SIZE(self);
1033 /* Get the size of bb before resizing the array since bb could be self. */
1034 bbsize = Py_SIZE(bb);
1035 size = oldsize + Py_SIZE(b);
1036 if (array_resize(self, size) == -1)
1037 return -1;
Martin Panterbe8da9c2016-09-07 11:04:41 +00001038 if (bbsize > 0) {
1039 memcpy(self->ob_item + oldsize * self->ob_descr->itemsize,
1040 b->ob_item, bbsize * b->ob_descr->itemsize);
1041 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042
1043 return 0;
Martin v. Löwis99866332002-03-01 10:27:01 +00001044#undef b
1045}
1046
1047static PyObject *
1048array_inplace_concat(arrayobject *self, PyObject *bb)
1049{
Erlend Egeberg Aasland75bf1072021-01-02 17:38:47 +01001050 array_state *state = find_array_state_by_type(Py_TYPE(self));
1051
1052 if (!array_Check(bb, state)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 PyErr_Format(PyExc_TypeError,
1054 "can only extend array with array (not \"%.200s\")",
1055 Py_TYPE(bb)->tp_name);
1056 return NULL;
1057 }
Erlend Egeberg Aasland75bf1072021-01-02 17:38:47 +01001058 if (array_do_extend(state, self, bb) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001059 return NULL;
1060 Py_INCREF(self);
1061 return (PyObject *)self;
Martin v. Löwis99866332002-03-01 10:27:01 +00001062}
1063
1064static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001065array_inplace_repeat(arrayobject *self, Py_ssize_t n)
Martin v. Löwis99866332002-03-01 10:27:01 +00001066{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001067 char *items, *p;
1068 Py_ssize_t size, i;
Martin v. Löwis99866332002-03-01 10:27:01 +00001069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 if (Py_SIZE(self) > 0) {
1071 if (n < 0)
1072 n = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 if ((self->ob_descr->itemsize != 0) &&
1074 (Py_SIZE(self) > PY_SSIZE_T_MAX / self->ob_descr->itemsize)) {
1075 return PyErr_NoMemory();
1076 }
1077 size = Py_SIZE(self) * self->ob_descr->itemsize;
1078 if (n > 0 && size > PY_SSIZE_T_MAX / n) {
1079 return PyErr_NoMemory();
1080 }
1081 if (array_resize(self, n * Py_SIZE(self)) == -1)
1082 return NULL;
1083 items = p = self->ob_item;
1084 for (i = 1; i < n; i++) {
1085 p += size;
1086 memcpy(p, items, size);
1087 }
1088 }
1089 Py_INCREF(self);
1090 return (PyObject *)self;
Martin v. Löwis99866332002-03-01 10:27:01 +00001091}
1092
1093
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001094static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001095ins(arrayobject *self, Py_ssize_t where, PyObject *v)
Guido van Rossum778983b1993-02-19 15:55:02 +00001096{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097 if (ins1(self, where, v) != 0)
1098 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001099 Py_RETURN_NONE;
Guido van Rossum778983b1993-02-19 15:55:02 +00001100}
1101
Brett Cannon1eb32c22014-10-10 16:26:45 -04001102/*[clinic input]
1103array.array.count
1104
1105 v: object
1106 /
1107
1108Return number of occurrences of v in the array.
1109[clinic start generated code]*/
1110
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001111static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001112array_array_count(arrayobject *self, PyObject *v)
1113/*[clinic end generated code: output=3dd3624bf7135a3a input=d9bce9d65e39d1f5]*/
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001114{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 Py_ssize_t count = 0;
1116 Py_ssize_t i;
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001117
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001118 for (i = 0; i < Py_SIZE(self); i++) {
Victor Stinner0b142e22013-07-17 23:01:30 +02001119 PyObject *selfi;
1120 int cmp;
1121
1122 selfi = getarrayitem((PyObject *)self, i);
1123 if (selfi == NULL)
1124 return NULL;
1125 cmp = PyObject_RichCompareBool(selfi, v, Py_EQ);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 Py_DECREF(selfi);
1127 if (cmp > 0)
1128 count++;
1129 else if (cmp < 0)
1130 return NULL;
1131 }
1132 return PyLong_FromSsize_t(count);
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001133}
1134
Brett Cannon1eb32c22014-10-10 16:26:45 -04001135
1136/*[clinic input]
1137array.array.index
1138
1139 v: object
Zackery Spytzafd12652021-04-02 09:28:35 -06001140 start: slice_index(accept={int}) = 0
1141 stop: slice_index(accept={int}, c_default="PY_SSIZE_T_MAX") = sys.maxsize
Brett Cannon1eb32c22014-10-10 16:26:45 -04001142 /
1143
1144Return index of first occurrence of v in the array.
Zackery Spytzafd12652021-04-02 09:28:35 -06001145
1146Raise ValueError if the value is not present.
Brett Cannon1eb32c22014-10-10 16:26:45 -04001147[clinic start generated code]*/
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001148
1149static PyObject *
Zackery Spytzafd12652021-04-02 09:28:35 -06001150array_array_index_impl(arrayobject *self, PyObject *v, Py_ssize_t start,
1151 Py_ssize_t stop)
1152/*[clinic end generated code: output=c45e777880c99f52 input=089dff7baa7e5a7e]*/
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001153{
Zackery Spytzafd12652021-04-02 09:28:35 -06001154 if (start < 0) {
1155 start += Py_SIZE(self);
1156 if (start < 0) {
1157 start = 0;
1158 }
1159 }
1160 if (stop < 0) {
1161 stop += Py_SIZE(self);
1162 }
1163 // Use Py_SIZE() for every iteration in case the array is mutated
1164 // during PyObject_RichCompareBool()
1165 for (Py_ssize_t i = start; i < stop && i < Py_SIZE(self); i++) {
Victor Stinner0b142e22013-07-17 23:01:30 +02001166 PyObject *selfi;
1167 int cmp;
1168
1169 selfi = getarrayitem((PyObject *)self, i);
1170 if (selfi == NULL)
1171 return NULL;
1172 cmp = PyObject_RichCompareBool(selfi, v, Py_EQ);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001173 Py_DECREF(selfi);
1174 if (cmp > 0) {
WildCard651d3dad52020-06-23 09:21:16 -04001175 return PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001176 }
1177 else if (cmp < 0)
1178 return NULL;
1179 }
Jim Fasarakis-Hilliarda4095ef2017-05-29 20:43:39 +03001180 PyErr_SetString(PyExc_ValueError, "array.index(x): x not in array");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001181 return NULL;
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001182}
1183
Raymond Hettinger625812f2003-01-07 01:58:52 +00001184static int
1185array_contains(arrayobject *self, PyObject *v)
1186{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001187 Py_ssize_t i;
1188 int cmp;
Raymond Hettinger625812f2003-01-07 01:58:52 +00001189
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001190 for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(self); i++) {
1191 PyObject *selfi = getarrayitem((PyObject *)self, i);
Victor Stinner0b142e22013-07-17 23:01:30 +02001192 if (selfi == NULL)
Victor Stinner4755bea2013-07-18 01:12:35 +02001193 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 cmp = PyObject_RichCompareBool(selfi, v, Py_EQ);
1195 Py_DECREF(selfi);
1196 }
1197 return cmp;
Raymond Hettinger625812f2003-01-07 01:58:52 +00001198}
1199
Brett Cannon1eb32c22014-10-10 16:26:45 -04001200/*[clinic input]
1201array.array.remove
1202
1203 v: object
1204 /
1205
1206Remove the first occurrence of v in the array.
1207[clinic start generated code]*/
1208
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001209static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001210array_array_remove(arrayobject *self, PyObject *v)
1211/*[clinic end generated code: output=bef06be9fdf9dceb input=0b1e5aed25590027]*/
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001212{
sthaa3ecb82019-03-20 20:49:39 +01001213 Py_ssize_t i;
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001214
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001215 for (i = 0; i < Py_SIZE(self); i++) {
Victor Stinner0b142e22013-07-17 23:01:30 +02001216 PyObject *selfi;
1217 int cmp;
1218
1219 selfi = getarrayitem((PyObject *)self,i);
1220 if (selfi == NULL)
1221 return NULL;
1222 cmp = PyObject_RichCompareBool(selfi, v, Py_EQ);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001223 Py_DECREF(selfi);
1224 if (cmp > 0) {
Martin Panter996d72b2016-07-25 02:21:14 +00001225 if (array_del_slice(self, i, i+1) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001226 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001227 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001228 }
1229 else if (cmp < 0)
1230 return NULL;
1231 }
Jim Fasarakis-Hilliarda4095ef2017-05-29 20:43:39 +03001232 PyErr_SetString(PyExc_ValueError, "array.remove(x): x not in array");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001233 return NULL;
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001234}
1235
Brett Cannon1eb32c22014-10-10 16:26:45 -04001236/*[clinic input]
1237array.array.pop
1238
1239 i: Py_ssize_t = -1
1240 /
1241
1242Return the i-th element and delete it from the array.
1243
1244i defaults to -1.
1245[clinic start generated code]*/
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001246
1247static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001248array_array_pop_impl(arrayobject *self, Py_ssize_t i)
1249/*[clinic end generated code: output=bc1f0c54fe5308e4 input=8e5feb4c1a11cd44]*/
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001250{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001251 PyObject *v;
Brett Cannon1eb32c22014-10-10 16:26:45 -04001252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001253 if (Py_SIZE(self) == 0) {
1254 /* Special-case most common failure cause */
1255 PyErr_SetString(PyExc_IndexError, "pop from empty array");
1256 return NULL;
1257 }
1258 if (i < 0)
1259 i += Py_SIZE(self);
1260 if (i < 0 || i >= Py_SIZE(self)) {
1261 PyErr_SetString(PyExc_IndexError, "pop index out of range");
1262 return NULL;
1263 }
Victor Stinner0b142e22013-07-17 23:01:30 +02001264 v = getarrayitem((PyObject *)self, i);
1265 if (v == NULL)
1266 return NULL;
Martin Panter996d72b2016-07-25 02:21:14 +00001267 if (array_del_slice(self, i, i+1) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001268 Py_DECREF(v);
1269 return NULL;
1270 }
1271 return v;
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001272}
1273
Brett Cannon1eb32c22014-10-10 16:26:45 -04001274/*[clinic input]
1275array.array.extend
1276
Erlend Egeberg Aasland75bf1072021-01-02 17:38:47 +01001277 cls: defining_class
Brett Cannon1eb32c22014-10-10 16:26:45 -04001278 bb: object
1279 /
1280
1281Append items to the end of the array.
1282[clinic start generated code]*/
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001283
1284static PyObject *
Erlend Egeberg Aasland75bf1072021-01-02 17:38:47 +01001285array_array_extend_impl(arrayobject *self, PyTypeObject *cls, PyObject *bb)
1286/*[clinic end generated code: output=e65eb7588f0bc266 input=8eb6817ec4d2cb62]*/
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001287{
Erlend Egeberg Aasland75bf1072021-01-02 17:38:47 +01001288 array_state *state = get_array_state_by_class(cls);
1289
1290 if (array_do_extend(state, self, bb) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001291 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001292 Py_RETURN_NONE;
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001293}
1294
Brett Cannon1eb32c22014-10-10 16:26:45 -04001295/*[clinic input]
1296array.array.insert
1297
1298 i: Py_ssize_t
1299 v: object
1300 /
1301
1302Insert a new item v into the array before position i.
1303[clinic start generated code]*/
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001304
1305static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001306array_array_insert_impl(arrayobject *self, Py_ssize_t i, PyObject *v)
1307/*[clinic end generated code: output=5a3648e278348564 input=5577d1b4383e9313]*/
Guido van Rossum778983b1993-02-19 15:55:02 +00001308{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001309 return ins(self, i, v);
Guido van Rossum778983b1993-02-19 15:55:02 +00001310}
1311
Brett Cannon1eb32c22014-10-10 16:26:45 -04001312/*[clinic input]
1313array.array.buffer_info
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001314
Brett Cannon1eb32c22014-10-10 16:26:45 -04001315Return a tuple (address, length) giving the current memory address and the length in items of the buffer used to hold array's contents.
1316
1317The length should be multiplied by the itemsize attribute to calculate
1318the buffer length in bytes.
1319[clinic start generated code]*/
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001320
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001321static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001322array_array_buffer_info_impl(arrayobject *self)
1323/*[clinic end generated code: output=9b2a4ec3ae7e98e7 input=a58bae5c6e1ac6a6]*/
Guido van Rossumde4a4ca1997-08-12 14:55:56 +00001324{
Victor Stinner541067a2013-11-14 01:27:12 +01001325 PyObject *retval = NULL, *v;
1326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001327 retval = PyTuple_New(2);
1328 if (!retval)
1329 return NULL;
Fred Drake541dc3b2000-06-28 17:49:30 +00001330
Victor Stinner541067a2013-11-14 01:27:12 +01001331 v = PyLong_FromVoidPtr(self->ob_item);
1332 if (v == NULL) {
1333 Py_DECREF(retval);
1334 return NULL;
1335 }
1336 PyTuple_SET_ITEM(retval, 0, v);
1337
Serhiy Storchaka9e941d62016-06-23 23:55:34 +03001338 v = PyLong_FromSsize_t(Py_SIZE(self));
Victor Stinner541067a2013-11-14 01:27:12 +01001339 if (v == NULL) {
1340 Py_DECREF(retval);
1341 return NULL;
1342 }
1343 PyTuple_SET_ITEM(retval, 1, v);
Fred Drake541dc3b2000-06-28 17:49:30 +00001344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001345 return retval;
Guido van Rossumde4a4ca1997-08-12 14:55:56 +00001346}
1347
Brett Cannon1eb32c22014-10-10 16:26:45 -04001348/*[clinic input]
1349array.array.append
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001350
Brett Cannon1eb32c22014-10-10 16:26:45 -04001351 v: object
1352 /
1353
1354Append new value v to the end of the array.
1355[clinic start generated code]*/
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001356
Guido van Rossumde4a4ca1997-08-12 14:55:56 +00001357static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001358array_array_append(arrayobject *self, PyObject *v)
1359/*[clinic end generated code: output=745a0669bf8db0e2 input=0b98d9d78e78f0fa]*/
Guido van Rossum778983b1993-02-19 15:55:02 +00001360{
Mark Dickinson346f0af2010-08-06 09:36:57 +00001361 return ins(self, Py_SIZE(self), v);
Guido van Rossum778983b1993-02-19 15:55:02 +00001362}
1363
Brett Cannon1eb32c22014-10-10 16:26:45 -04001364/*[clinic input]
1365array.array.byteswap
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001366
Brett Cannon1eb32c22014-10-10 16:26:45 -04001367Byteswap all items of the array.
1368
1369If the items in the array are not 1, 2, 4, or 8 bytes in size, RuntimeError is
1370raised.
1371[clinic start generated code]*/
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001372
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001373static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001374array_array_byteswap_impl(arrayobject *self)
1375/*[clinic end generated code: output=5f8236cbdf0d90b5 input=6a85591b950a0186]*/
Guido van Rossum778983b1993-02-19 15:55:02 +00001376{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001377 char *p;
1378 Py_ssize_t i;
Fred Drakebf272981999-12-03 17:15:30 +00001379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001380 switch (self->ob_descr->itemsize) {
1381 case 1:
1382 break;
1383 case 2:
1384 for (p = self->ob_item, i = Py_SIZE(self); --i >= 0; p += 2) {
1385 char p0 = p[0];
1386 p[0] = p[1];
1387 p[1] = p0;
1388 }
1389 break;
1390 case 4:
1391 for (p = self->ob_item, i = Py_SIZE(self); --i >= 0; p += 4) {
1392 char p0 = p[0];
1393 char p1 = p[1];
1394 p[0] = p[3];
1395 p[1] = p[2];
1396 p[2] = p1;
1397 p[3] = p0;
1398 }
1399 break;
1400 case 8:
1401 for (p = self->ob_item, i = Py_SIZE(self); --i >= 0; p += 8) {
1402 char p0 = p[0];
1403 char p1 = p[1];
1404 char p2 = p[2];
1405 char p3 = p[3];
1406 p[0] = p[7];
1407 p[1] = p[6];
1408 p[2] = p[5];
1409 p[3] = p[4];
1410 p[4] = p3;
1411 p[5] = p2;
1412 p[6] = p1;
1413 p[7] = p0;
1414 }
1415 break;
1416 default:
1417 PyErr_SetString(PyExc_RuntimeError,
1418 "don't know how to byteswap this array type");
1419 return NULL;
1420 }
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001421 Py_RETURN_NONE;
Guido van Rossum778983b1993-02-19 15:55:02 +00001422}
1423
Brett Cannon1eb32c22014-10-10 16:26:45 -04001424/*[clinic input]
1425array.array.reverse
1426
1427Reverse the order of the items in the array.
1428[clinic start generated code]*/
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001429
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001430static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001431array_array_reverse_impl(arrayobject *self)
1432/*[clinic end generated code: output=c04868b36f6f4089 input=cd904f01b27d966a]*/
Guido van Rossum778983b1993-02-19 15:55:02 +00001433{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001434 Py_ssize_t itemsize = self->ob_descr->itemsize;
1435 char *p, *q;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001436 /* little buffer to hold items while swapping */
1437 char tmp[256]; /* 8 is probably enough -- but why skimp */
1438 assert((size_t)itemsize <= sizeof(tmp));
Guido van Rossume77a7571993-11-03 15:01:26 +00001439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001440 if (Py_SIZE(self) > 1) {
1441 for (p = self->ob_item,
1442 q = self->ob_item + (Py_SIZE(self) - 1)*itemsize;
1443 p < q;
1444 p += itemsize, q -= itemsize) {
1445 /* memory areas guaranteed disjoint, so memcpy
1446 * is safe (& memmove may be slower).
1447 */
1448 memcpy(tmp, p, itemsize);
1449 memcpy(p, q, itemsize);
1450 memcpy(q, tmp, itemsize);
1451 }
1452 }
Tim Petersbb307342000-09-10 05:22:54 +00001453
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001454 Py_RETURN_NONE;
Guido van Rossum778983b1993-02-19 15:55:02 +00001455}
Guido van Rossume77a7571993-11-03 15:01:26 +00001456
Brett Cannon1eb32c22014-10-10 16:26:45 -04001457/*[clinic input]
1458array.array.fromfile
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001459
Brett Cannon1eb32c22014-10-10 16:26:45 -04001460 f: object
1461 n: Py_ssize_t
1462 /
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001463
Brett Cannon1eb32c22014-10-10 16:26:45 -04001464Read n objects from the file object f and append them to the end of the array.
1465[clinic start generated code]*/
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001466
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001467static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001468array_array_fromfile_impl(arrayobject *self, PyObject *f, Py_ssize_t n)
1469/*[clinic end generated code: output=ec9f600e10f53510 input=e188afe8e58adf40]*/
Guido van Rossum778983b1993-02-19 15:55:02 +00001470{
Serhiy Storchaka04e6dba2015-04-04 17:06:55 +03001471 PyObject *b, *res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001472 Py_ssize_t itemsize = self->ob_descr->itemsize;
Brett Cannon1eb32c22014-10-10 16:26:45 -04001473 Py_ssize_t nbytes;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001474 _Py_IDENTIFIER(read);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001475 int not_enough_bytes;
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001476
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01001477 if (n < 0) {
1478 PyErr_SetString(PyExc_ValueError, "negative count");
1479 return NULL;
1480 }
1481 if (n > PY_SSIZE_T_MAX / itemsize) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001482 PyErr_NoMemory();
1483 return NULL;
1484 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01001485 nbytes = n * itemsize;
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001486
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001487 b = _PyObject_CallMethodId(f, &PyId_read, "n", nbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001488 if (b == NULL)
1489 return NULL;
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001490
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001491 if (!PyBytes_Check(b)) {
1492 PyErr_SetString(PyExc_TypeError,
1493 "read() didn't return bytes");
1494 Py_DECREF(b);
1495 return NULL;
1496 }
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001498 not_enough_bytes = (PyBytes_GET_SIZE(b) != nbytes);
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001499
Serhiy Storchaka04e6dba2015-04-04 17:06:55 +03001500 res = array_array_frombytes(self, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001501 Py_DECREF(b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001502 if (res == NULL)
1503 return NULL;
Hirokazu Yamamoto54d0df62009-03-06 03:04:07 +00001504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001505 if (not_enough_bytes) {
1506 PyErr_SetString(PyExc_EOFError,
1507 "read() didn't return enough bytes");
1508 Py_DECREF(res);
1509 return NULL;
1510 }
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001512 return res;
Guido van Rossum778983b1993-02-19 15:55:02 +00001513}
1514
Brett Cannon1eb32c22014-10-10 16:26:45 -04001515/*[clinic input]
1516array.array.tofile
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001517
Brett Cannon1eb32c22014-10-10 16:26:45 -04001518 f: object
1519 /
1520
1521Write all items (as machine values) to the file object f.
1522[clinic start generated code]*/
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001523
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001524static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001525array_array_tofile(arrayobject *self, PyObject *f)
1526/*[clinic end generated code: output=3a2cfa8128df0777 input=b0669a484aab0831]*/
Guido van Rossum778983b1993-02-19 15:55:02 +00001527{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001528 Py_ssize_t nbytes = Py_SIZE(self) * self->ob_descr->itemsize;
1529 /* Write 64K blocks at a time */
1530 /* XXX Make the block size settable */
1531 int BLOCKSIZE = 64*1024;
1532 Py_ssize_t nblocks = (nbytes + BLOCKSIZE - 1) / BLOCKSIZE;
1533 Py_ssize_t i;
Raymond Hettinger36cd2bf2003-01-03 08:24:58 +00001534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001535 if (Py_SIZE(self) == 0)
1536 goto done;
Guido van Rossumb5ddcfd2007-04-11 17:08:28 +00001537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001538 for (i = 0; i < nblocks; i++) {
1539 char* ptr = self->ob_item + i*BLOCKSIZE;
1540 Py_ssize_t size = BLOCKSIZE;
1541 PyObject *bytes, *res;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001542 _Py_IDENTIFIER(write);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001543
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001544 if (i*BLOCKSIZE + size > nbytes)
1545 size = nbytes - i*BLOCKSIZE;
1546 bytes = PyBytes_FromStringAndSize(ptr, size);
1547 if (bytes == NULL)
1548 return NULL;
Jeroen Demeyer59ad1102019-07-11 10:59:05 +02001549 res = _PyObject_CallMethodIdOneArg(f, &PyId_write, bytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001550 Py_DECREF(bytes);
1551 if (res == NULL)
1552 return NULL;
1553 Py_DECREF(res); /* drop write result */
1554 }
Guido van Rossumb5ddcfd2007-04-11 17:08:28 +00001555
1556 done:
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001557 Py_RETURN_NONE;
Guido van Rossum778983b1993-02-19 15:55:02 +00001558}
1559
Brett Cannon1eb32c22014-10-10 16:26:45 -04001560/*[clinic input]
1561array.array.fromlist
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001562
Brett Cannon1eb32c22014-10-10 16:26:45 -04001563 list: object
1564 /
1565
1566Append items to array from list.
1567[clinic start generated code]*/
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001568
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001569static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001570array_array_fromlist(arrayobject *self, PyObject *list)
1571/*[clinic end generated code: output=26411c2d228a3e3f input=be2605a96c49680f]*/
Guido van Rossum778983b1993-02-19 15:55:02 +00001572{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001573 Py_ssize_t n;
Raymond Hettinger36cd2bf2003-01-03 08:24:58 +00001574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001575 if (!PyList_Check(list)) {
1576 PyErr_SetString(PyExc_TypeError, "arg must be list");
1577 return NULL;
1578 }
1579 n = PyList_Size(list);
1580 if (n > 0) {
1581 Py_ssize_t i, old_size;
1582 old_size = Py_SIZE(self);
1583 if (array_resize(self, old_size + n) == -1)
1584 return NULL;
1585 for (i = 0; i < n; i++) {
Zackery Spytz99d56b52018-12-08 07:16:55 -07001586 PyObject *v = PyList_GET_ITEM(list, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001587 if ((*self->ob_descr->setitem)(self,
1588 Py_SIZE(self) - n + i, v) != 0) {
1589 array_resize(self, old_size);
1590 return NULL;
1591 }
Zackery Spytz99d56b52018-12-08 07:16:55 -07001592 if (n != PyList_GET_SIZE(list)) {
1593 PyErr_SetString(PyExc_RuntimeError,
1594 "list changed size during iteration");
1595 array_resize(self, old_size);
1596 return NULL;
1597 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001598 }
1599 }
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001600 Py_RETURN_NONE;
Guido van Rossum778983b1993-02-19 15:55:02 +00001601}
1602
Brett Cannon1eb32c22014-10-10 16:26:45 -04001603/*[clinic input]
1604array.array.tolist
1605
1606Convert array to an ordinary list with the same items.
1607[clinic start generated code]*/
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001608
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001609static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001610array_array_tolist_impl(arrayobject *self)
1611/*[clinic end generated code: output=00b60cc9eab8ef89 input=a8d7784a94f86b53]*/
Guido van Rossum778983b1993-02-19 15:55:02 +00001612{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001613 PyObject *list = PyList_New(Py_SIZE(self));
1614 Py_ssize_t i;
Raymond Hettinger36cd2bf2003-01-03 08:24:58 +00001615
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001616 if (list == NULL)
1617 return NULL;
1618 for (i = 0; i < Py_SIZE(self); i++) {
1619 PyObject *v = getarrayitem((PyObject *)self, i);
Victor Stinner4755bea2013-07-18 01:12:35 +02001620 if (v == NULL)
1621 goto error;
Zackery Spytz99d56b52018-12-08 07:16:55 -07001622 PyList_SET_ITEM(list, i, v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001623 }
1624 return list;
Victor Stinner4755bea2013-07-18 01:12:35 +02001625
1626error:
1627 Py_DECREF(list);
1628 return NULL;
Guido van Rossum778983b1993-02-19 15:55:02 +00001629}
1630
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001631static PyObject *
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001632frombytes(arrayobject *self, Py_buffer *buffer)
Guido van Rossum778983b1993-02-19 15:55:02 +00001633{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001634 int itemsize = self->ob_descr->itemsize;
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001635 Py_ssize_t n;
1636 if (buffer->itemsize != 1) {
1637 PyBuffer_Release(buffer);
Serhiy Storchakab757c832014-12-05 22:25:22 +02001638 PyErr_SetString(PyExc_TypeError, "a bytes-like object is required");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001639 return NULL;
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001640 }
1641 n = buffer->len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001642 if (n % itemsize != 0) {
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001643 PyBuffer_Release(buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001644 PyErr_SetString(PyExc_ValueError,
Serhiy Storchakab757c832014-12-05 22:25:22 +02001645 "bytes length not a multiple of item size");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001646 return NULL;
1647 }
1648 n = n / itemsize;
1649 if (n > 0) {
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001650 Py_ssize_t old_size = Py_SIZE(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001651 if ((n > PY_SSIZE_T_MAX - old_size) ||
1652 ((old_size + n) > PY_SSIZE_T_MAX / itemsize)) {
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001653 PyBuffer_Release(buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001654 return PyErr_NoMemory();
1655 }
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001656 if (array_resize(self, old_size + n) == -1) {
1657 PyBuffer_Release(buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001658 return NULL;
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001659 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001660 memcpy(self->ob_item + old_size * itemsize,
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001661 buffer->buf, n * itemsize);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001662 }
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001663 PyBuffer_Release(buffer);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001664 Py_RETURN_NONE;
Guido van Rossum778983b1993-02-19 15:55:02 +00001665}
1666
Brett Cannon1eb32c22014-10-10 16:26:45 -04001667/*[clinic input]
Brett Cannon1eb32c22014-10-10 16:26:45 -04001668array.array.frombytes
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001669
Brett Cannon1eb32c22014-10-10 16:26:45 -04001670 buffer: Py_buffer
1671 /
1672
1673Appends items from the string, interpreting it as an array of machine values, as if it had been read from a file using the fromfile() method).
1674[clinic start generated code]*/
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001675
1676static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001677array_array_frombytes_impl(arrayobject *self, Py_buffer *buffer)
1678/*[clinic end generated code: output=d9842c8f7510a516 input=2bbf2b53ebfcc988]*/
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001679{
Brett Cannon1eb32c22014-10-10 16:26:45 -04001680 return frombytes(self, buffer);
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001681}
1682
Brett Cannon1eb32c22014-10-10 16:26:45 -04001683/*[clinic input]
1684array.array.tobytes
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001685
Brett Cannon1eb32c22014-10-10 16:26:45 -04001686Convert the array to an array of machine values and return the bytes representation.
1687[clinic start generated code]*/
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001688
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001689static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001690array_array_tobytes_impl(arrayobject *self)
1691/*[clinic end generated code: output=87318e4edcdc2bb6 input=90ee495f96de34f5]*/
Guido van Rossum778983b1993-02-19 15:55:02 +00001692{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001693 if (Py_SIZE(self) <= PY_SSIZE_T_MAX / self->ob_descr->itemsize) {
1694 return PyBytes_FromStringAndSize(self->ob_item,
1695 Py_SIZE(self) * self->ob_descr->itemsize);
1696 } else {
1697 return PyErr_NoMemory();
1698 }
Guido van Rossum778983b1993-02-19 15:55:02 +00001699}
1700
Brett Cannon1eb32c22014-10-10 16:26:45 -04001701/*[clinic input]
Brett Cannon1eb32c22014-10-10 16:26:45 -04001702array.array.fromunicode
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001703
Inada Naokid5d9a712020-05-11 15:37:25 +09001704 ustr: unicode
Brett Cannon1eb32c22014-10-10 16:26:45 -04001705 /
1706
1707Extends this array with data from the unicode string ustr.
1708
1709The array must be a unicode type array; otherwise a ValueError is raised.
1710Use array.frombytes(ustr.encode(...)) to append Unicode data to an array of
1711some other type.
1712[clinic start generated code]*/
Martin v. Löwis99866332002-03-01 10:27:01 +00001713
Martin v. Löwis99866332002-03-01 10:27:01 +00001714static PyObject *
Inada Naokid5d9a712020-05-11 15:37:25 +09001715array_array_fromunicode_impl(arrayobject *self, PyObject *ustr)
1716/*[clinic end generated code: output=24359f5e001a7f2b input=025db1fdade7a4ce]*/
Martin v. Löwis99866332002-03-01 10:27:01 +00001717{
Inada Naokid5d9a712020-05-11 15:37:25 +09001718 if (self->ob_descr->typecode != 'u') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001719 PyErr_SetString(PyExc_ValueError,
1720 "fromunicode() may only be called on "
1721 "unicode type arrays");
1722 return NULL;
1723 }
Inada Naokid5d9a712020-05-11 15:37:25 +09001724
1725 Py_ssize_t ustr_length = PyUnicode_AsWideChar(ustr, NULL, 0);
1726 assert(ustr_length > 0);
1727 if (ustr_length > 1) {
1728 ustr_length--; /* trim trailing NUL character */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001729 Py_ssize_t old_size = Py_SIZE(self);
Inada Naokid5d9a712020-05-11 15:37:25 +09001730 if (array_resize(self, old_size + ustr_length) == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001731 return NULL;
Inada Naokid5d9a712020-05-11 15:37:25 +09001732 }
1733
1734 // must not fail
1735 PyUnicode_AsWideChar(
1736 ustr, ((wchar_t *)self->ob_item) + old_size, ustr_length);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001737 }
Martin v. Löwis99866332002-03-01 10:27:01 +00001738
Brett Cannon1eb32c22014-10-10 16:26:45 -04001739 Py_RETURN_NONE;
Martin v. Löwis99866332002-03-01 10:27:01 +00001740}
1741
Brett Cannon1eb32c22014-10-10 16:26:45 -04001742/*[clinic input]
1743array.array.tounicode
Martin v. Löwis99866332002-03-01 10:27:01 +00001744
Brett Cannon1eb32c22014-10-10 16:26:45 -04001745Extends this array with data from the unicode string ustr.
1746
1747Convert the array to a unicode string. The array must be a unicode type array;
1748otherwise a ValueError is raised. Use array.tobytes().decode() to obtain a
1749unicode string from an array of some other type.
1750[clinic start generated code]*/
Martin v. Löwis99866332002-03-01 10:27:01 +00001751
1752static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001753array_array_tounicode_impl(arrayobject *self)
1754/*[clinic end generated code: output=08e442378336e1ef input=127242eebe70b66d]*/
Martin v. Löwis99866332002-03-01 10:27:01 +00001755{
Inada Naokid5d9a712020-05-11 15:37:25 +09001756 if (self->ob_descr->typecode != 'u') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001757 PyErr_SetString(PyExc_ValueError,
1758 "tounicode() may only be called on unicode type arrays");
1759 return NULL;
1760 }
Inada Naokid5d9a712020-05-11 15:37:25 +09001761 return PyUnicode_FromWideChar((wchar_t *) self->ob_item, Py_SIZE(self));
Martin v. Löwis99866332002-03-01 10:27:01 +00001762}
1763
Brett Cannon1eb32c22014-10-10 16:26:45 -04001764/*[clinic input]
1765array.array.__sizeof__
Martin v. Löwis99866332002-03-01 10:27:01 +00001766
Brett Cannon1eb32c22014-10-10 16:26:45 -04001767Size of the array in memory, in bytes.
1768[clinic start generated code]*/
Martin v. Löwis99866332002-03-01 10:27:01 +00001769
Meador Inge03b4d502012-08-10 22:35:45 -05001770static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001771array_array___sizeof___impl(arrayobject *self)
1772/*[clinic end generated code: output=d8e1c61ebbe3eaed input=805586565bf2b3c6]*/
Meador Inge03b4d502012-08-10 22:35:45 -05001773{
1774 Py_ssize_t res;
Serhiy Storchaka5c4064e2015-12-19 20:05:25 +02001775 res = _PyObject_SIZE(Py_TYPE(self)) + self->allocated * self->ob_descr->itemsize;
Meador Inge03b4d502012-08-10 22:35:45 -05001776 return PyLong_FromSsize_t(res);
1777}
1778
Martin v. Löwis99866332002-03-01 10:27:01 +00001779
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001780/*********************** Pickling support ************************/
1781
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001782static const struct mformatdescr {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001783 size_t size;
1784 int is_signed;
1785 int is_big_endian;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001786} mformat_descriptors[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001787 {1, 0, 0}, /* 0: UNSIGNED_INT8 */
1788 {1, 1, 0}, /* 1: SIGNED_INT8 */
1789 {2, 0, 0}, /* 2: UNSIGNED_INT16_LE */
1790 {2, 0, 1}, /* 3: UNSIGNED_INT16_BE */
1791 {2, 1, 0}, /* 4: SIGNED_INT16_LE */
1792 {2, 1, 1}, /* 5: SIGNED_INT16_BE */
1793 {4, 0, 0}, /* 6: UNSIGNED_INT32_LE */
1794 {4, 0, 1}, /* 7: UNSIGNED_INT32_BE */
1795 {4, 1, 0}, /* 8: SIGNED_INT32_LE */
1796 {4, 1, 1}, /* 9: SIGNED_INT32_BE */
1797 {8, 0, 0}, /* 10: UNSIGNED_INT64_LE */
1798 {8, 0, 1}, /* 11: UNSIGNED_INT64_BE */
1799 {8, 1, 0}, /* 12: SIGNED_INT64_LE */
1800 {8, 1, 1}, /* 13: SIGNED_INT64_BE */
1801 {4, 0, 0}, /* 14: IEEE_754_FLOAT_LE */
1802 {4, 0, 1}, /* 15: IEEE_754_FLOAT_BE */
1803 {8, 0, 0}, /* 16: IEEE_754_DOUBLE_LE */
1804 {8, 0, 1}, /* 17: IEEE_754_DOUBLE_BE */
1805 {4, 0, 0}, /* 18: UTF16_LE */
1806 {4, 0, 1}, /* 19: UTF16_BE */
1807 {8, 0, 0}, /* 20: UTF32_LE */
1808 {8, 0, 1} /* 21: UTF32_BE */
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001809};
1810
1811
1812/*
1813 * Internal: This function is used to find the machine format of a given
1814 * array type code. This returns UNKNOWN_FORMAT when the machine format cannot
1815 * be found.
1816 */
1817static enum machine_format_code
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02001818typecode_to_mformat_code(char typecode)
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001819{
Christian Heimes743e0cd2012-10-17 23:52:17 +02001820 const int is_big_endian = PY_BIG_ENDIAN;
1821
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001822 size_t intsize;
1823 int is_signed;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001824
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001825 switch (typecode) {
1826 case 'b':
1827 return SIGNED_INT8;
1828 case 'B':
1829 return UNSIGNED_INT8;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001830
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001831 case 'u':
Victor Stinner62bb3942012-08-06 00:46:05 +02001832 if (sizeof(Py_UNICODE) == 2) {
1833 return UTF16_LE + is_big_endian;
1834 }
1835 if (sizeof(Py_UNICODE) == 4) {
1836 return UTF32_LE + is_big_endian;
1837 }
1838 return UNKNOWN_FORMAT;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001839
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001840 case 'f':
1841 if (sizeof(float) == 4) {
1842 const float y = 16711938.0;
1843 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1844 return IEEE_754_FLOAT_BE;
1845 if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1846 return IEEE_754_FLOAT_LE;
1847 }
1848 return UNKNOWN_FORMAT;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001849
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001850 case 'd':
1851 if (sizeof(double) == 8) {
1852 const double x = 9006104071832581.0;
1853 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1854 return IEEE_754_DOUBLE_BE;
1855 if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1856 return IEEE_754_DOUBLE_LE;
1857 }
1858 return UNKNOWN_FORMAT;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001859
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001860 /* Integers */
1861 case 'h':
1862 intsize = sizeof(short);
1863 is_signed = 1;
1864 break;
1865 case 'H':
1866 intsize = sizeof(short);
1867 is_signed = 0;
1868 break;
1869 case 'i':
1870 intsize = sizeof(int);
1871 is_signed = 1;
1872 break;
1873 case 'I':
1874 intsize = sizeof(int);
1875 is_signed = 0;
1876 break;
1877 case 'l':
1878 intsize = sizeof(long);
1879 is_signed = 1;
1880 break;
1881 case 'L':
1882 intsize = sizeof(long);
1883 is_signed = 0;
1884 break;
Meador Inge1c9f0c92011-09-20 19:55:51 -05001885 case 'q':
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001886 intsize = sizeof(long long);
Meador Inge1c9f0c92011-09-20 19:55:51 -05001887 is_signed = 1;
1888 break;
1889 case 'Q':
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001890 intsize = sizeof(long long);
Meador Inge1c9f0c92011-09-20 19:55:51 -05001891 is_signed = 0;
1892 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001893 default:
1894 return UNKNOWN_FORMAT;
1895 }
1896 switch (intsize) {
1897 case 2:
1898 return UNSIGNED_INT16_LE + is_big_endian + (2 * is_signed);
1899 case 4:
1900 return UNSIGNED_INT32_LE + is_big_endian + (2 * is_signed);
1901 case 8:
1902 return UNSIGNED_INT64_LE + is_big_endian + (2 * is_signed);
1903 default:
1904 return UNKNOWN_FORMAT;
1905 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001906}
1907
1908/* Forward declaration. */
1909static PyObject *array_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1910
1911/*
1912 * Internal: This function wraps the array constructor--i.e., array_new()--to
1913 * allow the creation of array objects from C code without having to deal
1914 * directly the tuple argument of array_new(). The typecode argument is a
1915 * Unicode character value, like 'i' or 'f' for example, representing an array
1916 * type code. The items argument is a bytes or a list object from which
1917 * contains the initial value of the array.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001918 *
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001919 * On success, this functions returns the array object created. Otherwise,
1920 * NULL is returned to indicate a failure.
1921 */
1922static PyObject *
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02001923make_array(PyTypeObject *arraytype, char typecode, PyObject *items)
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001924{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001925 PyObject *new_args;
1926 PyObject *array_obj;
1927 PyObject *typecode_obj;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001928
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001929 assert(arraytype != NULL);
1930 assert(items != NULL);
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001931
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02001932 typecode_obj = PyUnicode_FromOrdinal(typecode);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001933 if (typecode_obj == NULL)
1934 return NULL;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001936 new_args = PyTuple_New(2);
Mat M56935a52017-11-14 01:00:54 -05001937 if (new_args == NULL) {
1938 Py_DECREF(typecode_obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001939 return NULL;
Mat M56935a52017-11-14 01:00:54 -05001940 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001941 Py_INCREF(items);
1942 PyTuple_SET_ITEM(new_args, 0, typecode_obj);
1943 PyTuple_SET_ITEM(new_args, 1, items);
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001945 array_obj = array_new(arraytype, new_args, NULL);
1946 Py_DECREF(new_args);
1947 if (array_obj == NULL)
1948 return NULL;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001950 return array_obj;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001951}
1952
1953/*
1954 * This functions is a special constructor used when unpickling an array. It
1955 * provides a portable way to rebuild an array from its memory representation.
1956 */
Brett Cannon1eb32c22014-10-10 16:26:45 -04001957/*[clinic input]
1958array._array_reconstructor
1959
1960 arraytype: object(type="PyTypeObject *")
Larry Hastingsdbfdc382015-05-04 06:59:46 -07001961 typecode: int(accept={str})
Brett Cannon1eb32c22014-10-10 16:26:45 -04001962 mformat_code: int(type="enum machine_format_code")
1963 items: object
1964 /
1965
1966Internal. Used for pickling support.
1967[clinic start generated code]*/
1968
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001969static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001970array__array_reconstructor_impl(PyObject *module, PyTypeObject *arraytype,
Larry Hastings89964c42015-04-14 18:07:59 -04001971 int typecode,
1972 enum machine_format_code mformat_code,
1973 PyObject *items)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001974/*[clinic end generated code: output=e05263141ba28365 input=2464dc8f4c7736b5]*/
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001975{
Erlend Egeberg Aasland75bf1072021-01-02 17:38:47 +01001976 array_state *state = get_array_state(module);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001977 PyObject *converted_items;
1978 PyObject *result;
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02001979 const struct arraydescr *descr;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001981 if (!PyType_Check(arraytype)) {
1982 PyErr_Format(PyExc_TypeError,
Sylvaina90e64b2017-03-29 20:09:22 +02001983 "first argument must be a type object, not %.200s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001984 Py_TYPE(arraytype)->tp_name);
1985 return NULL;
1986 }
Erlend Egeberg Aasland75bf1072021-01-02 17:38:47 +01001987 if (!PyType_IsSubtype(arraytype, state->ArrayType)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001988 PyErr_Format(PyExc_TypeError,
1989 "%.200s is not a subtype of %.200s",
Erlend Egeberg Aasland75bf1072021-01-02 17:38:47 +01001990 arraytype->tp_name, state->ArrayType->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001991 return NULL;
1992 }
1993 for (descr = descriptors; descr->typecode != '\0'; descr++) {
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02001994 if ((int)descr->typecode == typecode)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001995 break;
1996 }
1997 if (descr->typecode == '\0') {
1998 PyErr_SetString(PyExc_ValueError,
1999 "second argument must be a valid type code");
2000 return NULL;
2001 }
Larry Hastingsdfbeb162014-10-13 10:39:41 +01002002 if (mformat_code < MACHINE_FORMAT_CODE_MIN ||
2003 mformat_code > MACHINE_FORMAT_CODE_MAX) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002004 PyErr_SetString(PyExc_ValueError,
2005 "third argument must be a valid machine format code.");
2006 return NULL;
2007 }
2008 if (!PyBytes_Check(items)) {
2009 PyErr_Format(PyExc_TypeError,
2010 "fourth argument should be bytes, not %.200s",
2011 Py_TYPE(items)->tp_name);
2012 return NULL;
2013 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002015 /* Fast path: No decoding has to be done. */
Larry Hastingsdfbeb162014-10-13 10:39:41 +01002016 if (mformat_code == typecode_to_mformat_code((char)typecode) ||
2017 mformat_code == UNKNOWN_FORMAT) {
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02002018 return make_array(arraytype, (char)typecode, items);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002019 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002021 /* Slow path: Decode the byte string according to the given machine
2022 * format code. This occurs when the computer unpickling the array
2023 * object is architecturally different from the one that pickled the
2024 * array.
2025 */
Larry Hastingsdfbeb162014-10-13 10:39:41 +01002026 if (Py_SIZE(items) % mformat_descriptors[mformat_code].size != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002027 PyErr_SetString(PyExc_ValueError,
2028 "string length not a multiple of item size");
2029 return NULL;
2030 }
Larry Hastingsdfbeb162014-10-13 10:39:41 +01002031 switch (mformat_code) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002032 case IEEE_754_FLOAT_LE:
2033 case IEEE_754_FLOAT_BE: {
sthaa3ecb82019-03-20 20:49:39 +01002034 Py_ssize_t i;
Larry Hastingsdfbeb162014-10-13 10:39:41 +01002035 int le = (mformat_code == IEEE_754_FLOAT_LE) ? 1 : 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002036 Py_ssize_t itemcount = Py_SIZE(items) / 4;
2037 const unsigned char *memstr =
2038 (unsigned char *)PyBytes_AS_STRING(items);
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002040 converted_items = PyList_New(itemcount);
2041 if (converted_items == NULL)
2042 return NULL;
2043 for (i = 0; i < itemcount; i++) {
2044 PyObject *pyfloat = PyFloat_FromDouble(
2045 _PyFloat_Unpack4(&memstr[i * 4], le));
2046 if (pyfloat == NULL) {
2047 Py_DECREF(converted_items);
2048 return NULL;
2049 }
2050 PyList_SET_ITEM(converted_items, i, pyfloat);
2051 }
2052 break;
2053 }
2054 case IEEE_754_DOUBLE_LE:
2055 case IEEE_754_DOUBLE_BE: {
sthaa3ecb82019-03-20 20:49:39 +01002056 Py_ssize_t i;
Larry Hastingsdfbeb162014-10-13 10:39:41 +01002057 int le = (mformat_code == IEEE_754_DOUBLE_LE) ? 1 : 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002058 Py_ssize_t itemcount = Py_SIZE(items) / 8;
2059 const unsigned char *memstr =
2060 (unsigned char *)PyBytes_AS_STRING(items);
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002062 converted_items = PyList_New(itemcount);
2063 if (converted_items == NULL)
2064 return NULL;
2065 for (i = 0; i < itemcount; i++) {
2066 PyObject *pyfloat = PyFloat_FromDouble(
2067 _PyFloat_Unpack8(&memstr[i * 8], le));
2068 if (pyfloat == NULL) {
2069 Py_DECREF(converted_items);
2070 return NULL;
2071 }
2072 PyList_SET_ITEM(converted_items, i, pyfloat);
2073 }
2074 break;
2075 }
2076 case UTF16_LE:
2077 case UTF16_BE: {
Larry Hastingsdfbeb162014-10-13 10:39:41 +01002078 int byteorder = (mformat_code == UTF16_LE) ? -1 : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002079 converted_items = PyUnicode_DecodeUTF16(
2080 PyBytes_AS_STRING(items), Py_SIZE(items),
2081 "strict", &byteorder);
2082 if (converted_items == NULL)
2083 return NULL;
2084 break;
2085 }
2086 case UTF32_LE:
2087 case UTF32_BE: {
Larry Hastingsdfbeb162014-10-13 10:39:41 +01002088 int byteorder = (mformat_code == UTF32_LE) ? -1 : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002089 converted_items = PyUnicode_DecodeUTF32(
2090 PyBytes_AS_STRING(items), Py_SIZE(items),
2091 "strict", &byteorder);
2092 if (converted_items == NULL)
2093 return NULL;
2094 break;
2095 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002096
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002097 case UNSIGNED_INT8:
2098 case SIGNED_INT8:
2099 case UNSIGNED_INT16_LE:
2100 case UNSIGNED_INT16_BE:
2101 case SIGNED_INT16_LE:
2102 case SIGNED_INT16_BE:
2103 case UNSIGNED_INT32_LE:
2104 case UNSIGNED_INT32_BE:
2105 case SIGNED_INT32_LE:
2106 case SIGNED_INT32_BE:
2107 case UNSIGNED_INT64_LE:
2108 case UNSIGNED_INT64_BE:
2109 case SIGNED_INT64_LE:
2110 case SIGNED_INT64_BE: {
sthaa3ecb82019-03-20 20:49:39 +01002111 Py_ssize_t i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002112 const struct mformatdescr mf_descr =
Larry Hastingsdfbeb162014-10-13 10:39:41 +01002113 mformat_descriptors[mformat_code];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002114 Py_ssize_t itemcount = Py_SIZE(items) / mf_descr.size;
2115 const unsigned char *memstr =
2116 (unsigned char *)PyBytes_AS_STRING(items);
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02002117 const struct arraydescr *descr;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002118
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002119 /* If possible, try to pack array's items using a data type
2120 * that fits better. This may result in an array with narrower
2121 * or wider elements.
2122 *
Martin Panter4c359642016-05-08 13:53:41 +00002123 * For example, if a 32-bit machine pickles an L-code array of
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002124 * unsigned longs, then the array will be unpickled by 64-bit
2125 * machine as an I-code array of unsigned ints.
2126 *
2127 * XXX: Is it possible to write a unit test for this?
2128 */
2129 for (descr = descriptors; descr->typecode != '\0'; descr++) {
2130 if (descr->is_integer_type &&
Victor Stinner706768c2014-08-16 01:03:39 +02002131 (size_t)descr->itemsize == mf_descr.size &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002132 descr->is_signed == mf_descr.is_signed)
2133 typecode = descr->typecode;
2134 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002136 converted_items = PyList_New(itemcount);
2137 if (converted_items == NULL)
2138 return NULL;
2139 for (i = 0; i < itemcount; i++) {
2140 PyObject *pylong;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002142 pylong = _PyLong_FromByteArray(
2143 &memstr[i * mf_descr.size],
2144 mf_descr.size,
2145 !mf_descr.is_big_endian,
2146 mf_descr.is_signed);
2147 if (pylong == NULL) {
2148 Py_DECREF(converted_items);
2149 return NULL;
2150 }
2151 PyList_SET_ITEM(converted_items, i, pylong);
2152 }
2153 break;
2154 }
2155 case UNKNOWN_FORMAT:
2156 /* Impossible, but needed to shut up GCC about the unhandled
2157 * enumeration value.
2158 */
2159 default:
2160 PyErr_BadArgument();
2161 return NULL;
2162 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002163
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02002164 result = make_array(arraytype, (char)typecode, converted_items);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002165 Py_DECREF(converted_items);
2166 return result;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002167}
2168
Brett Cannon1eb32c22014-10-10 16:26:45 -04002169/*[clinic input]
2170array.array.__reduce_ex__
2171
2172 value: object
2173 /
2174
2175Return state information for pickling.
2176[clinic start generated code]*/
2177
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002178static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04002179array_array___reduce_ex__(arrayobject *self, PyObject *value)
2180/*[clinic end generated code: output=051e0a6175d0eddb input=c36c3f85de7df6cd]*/
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002181{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002182 PyObject *dict;
2183 PyObject *result;
2184 PyObject *array_str;
Brett Cannon1eb32c22014-10-10 16:26:45 -04002185 int typecode = self->ob_descr->typecode;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002186 int mformat_code;
2187 static PyObject *array_reconstructor = NULL;
2188 long protocol;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002189 _Py_IDENTIFIER(_array_reconstructor);
2190 _Py_IDENTIFIER(__dict__);
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002192 if (array_reconstructor == NULL) {
2193 PyObject *array_module = PyImport_ImportModule("array");
2194 if (array_module == NULL)
2195 return NULL;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002196 array_reconstructor = _PyObject_GetAttrId(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002197 array_module,
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002198 &PyId__array_reconstructor);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002199 Py_DECREF(array_module);
2200 if (array_reconstructor == NULL)
2201 return NULL;
2202 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002204 if (!PyLong_Check(value)) {
2205 PyErr_SetString(PyExc_TypeError,
Sylvaina90e64b2017-03-29 20:09:22 +02002206 "__reduce_ex__ argument should be an integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002207 return NULL;
2208 }
2209 protocol = PyLong_AsLong(value);
2210 if (protocol == -1 && PyErr_Occurred())
2211 return NULL;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002212
Serhiy Storchakaf320be72018-01-25 10:49:40 +02002213 if (_PyObject_LookupAttrId((PyObject *)self, &PyId___dict__, &dict) < 0) {
2214 return NULL;
2215 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002216 if (dict == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002217 dict = Py_None;
2218 Py_INCREF(dict);
2219 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002221 mformat_code = typecode_to_mformat_code(typecode);
2222 if (mformat_code == UNKNOWN_FORMAT || protocol < 3) {
2223 /* Convert the array to a list if we got something weird
2224 * (e.g., non-IEEE floats), or we are pickling the array using
2225 * a Python 2.x compatible protocol.
2226 *
2227 * It is necessary to use a list representation for Python 2.x
2228 * compatible pickle protocol, since Python 2's str objects
2229 * are unpickled as unicode by Python 3. Thus it is impossible
2230 * to make arrays unpicklable by Python 3 by using their memory
2231 * representation, unless we resort to ugly hacks such as
2232 * coercing unicode objects to bytes in array_reconstructor.
2233 */
2234 PyObject *list;
Brett Cannon1eb32c22014-10-10 16:26:45 -04002235 list = array_array_tolist_impl(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002236 if (list == NULL) {
2237 Py_DECREF(dict);
2238 return NULL;
2239 }
2240 result = Py_BuildValue(
Brett Cannon1eb32c22014-10-10 16:26:45 -04002241 "O(CO)O", Py_TYPE(self), typecode, list, dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002242 Py_DECREF(list);
2243 Py_DECREF(dict);
2244 return result;
2245 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002246
Brett Cannon1eb32c22014-10-10 16:26:45 -04002247 array_str = array_array_tobytes_impl(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002248 if (array_str == NULL) {
2249 Py_DECREF(dict);
2250 return NULL;
2251 }
2252 result = Py_BuildValue(
Brett Cannon1eb32c22014-10-10 16:26:45 -04002253 "O(OCiN)O", array_reconstructor, Py_TYPE(self), typecode,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002254 mformat_code, array_str, dict);
2255 Py_DECREF(dict);
2256 return result;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002257}
2258
Martin v. Löwis99866332002-03-01 10:27:01 +00002259static PyObject *
2260array_get_typecode(arrayobject *a, void *closure)
2261{
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02002262 char typecode = a->ob_descr->typecode;
2263 return PyUnicode_FromOrdinal(typecode);
Martin v. Löwis99866332002-03-01 10:27:01 +00002264}
2265
2266static PyObject *
2267array_get_itemsize(arrayobject *a, void *closure)
2268{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002269 return PyLong_FromLong((long)a->ob_descr->itemsize);
Martin v. Löwis99866332002-03-01 10:27:01 +00002270}
2271
2272static PyGetSetDef array_getsets [] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002273 {"typecode", (getter) array_get_typecode, NULL,
2274 "the typecode character used to create the array"},
2275 {"itemsize", (getter) array_get_itemsize, NULL,
2276 "the size, in bytes, of one array item"},
2277 {NULL}
Martin v. Löwis99866332002-03-01 10:27:01 +00002278};
2279
Martin v. Löwis59683e82008-06-13 07:50:45 +00002280static PyMethodDef array_methods[] = {
Brett Cannon1eb32c22014-10-10 16:26:45 -04002281 ARRAY_ARRAY_APPEND_METHODDEF
2282 ARRAY_ARRAY_BUFFER_INFO_METHODDEF
2283 ARRAY_ARRAY_BYTESWAP_METHODDEF
2284 ARRAY_ARRAY___COPY___METHODDEF
2285 ARRAY_ARRAY_COUNT_METHODDEF
2286 ARRAY_ARRAY___DEEPCOPY___METHODDEF
2287 ARRAY_ARRAY_EXTEND_METHODDEF
2288 ARRAY_ARRAY_FROMFILE_METHODDEF
2289 ARRAY_ARRAY_FROMLIST_METHODDEF
Brett Cannon1eb32c22014-10-10 16:26:45 -04002290 ARRAY_ARRAY_FROMBYTES_METHODDEF
2291 ARRAY_ARRAY_FROMUNICODE_METHODDEF
2292 ARRAY_ARRAY_INDEX_METHODDEF
2293 ARRAY_ARRAY_INSERT_METHODDEF
2294 ARRAY_ARRAY_POP_METHODDEF
2295 ARRAY_ARRAY___REDUCE_EX___METHODDEF
2296 ARRAY_ARRAY_REMOVE_METHODDEF
2297 ARRAY_ARRAY_REVERSE_METHODDEF
2298 ARRAY_ARRAY_TOFILE_METHODDEF
2299 ARRAY_ARRAY_TOLIST_METHODDEF
Brett Cannon1eb32c22014-10-10 16:26:45 -04002300 ARRAY_ARRAY_TOBYTES_METHODDEF
2301 ARRAY_ARRAY_TOUNICODE_METHODDEF
2302 ARRAY_ARRAY___SIZEOF___METHODDEF
2303 {NULL, NULL} /* sentinel */
Guido van Rossum778983b1993-02-19 15:55:02 +00002304};
2305
Roger E. Masse2919eaa1996-12-09 20:10:36 +00002306static PyObject *
Peter Schneider-Kamp9656abd2000-07-13 21:10:57 +00002307array_repr(arrayobject *a)
Guido van Rossum778983b1993-02-19 15:55:02 +00002308{
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02002309 char typecode;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002310 PyObject *s, *v = NULL;
2311 Py_ssize_t len;
Martin v. Löwis99866332002-03-01 10:27:01 +00002312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002313 len = Py_SIZE(a);
2314 typecode = a->ob_descr->typecode;
2315 if (len == 0) {
Serhiy Storchakab3a77962017-09-21 14:24:13 +03002316 return PyUnicode_FromFormat("%s('%c')",
2317 _PyType_Name(Py_TYPE(a)), (int)typecode);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002318 }
Gregory P. Smith9504b132012-12-10 20:20:20 -08002319 if (typecode == 'u') {
Brett Cannon1eb32c22014-10-10 16:26:45 -04002320 v = array_array_tounicode_impl(a);
Gregory P. Smith9504b132012-12-10 20:20:20 -08002321 } else {
Brett Cannon1eb32c22014-10-10 16:26:45 -04002322 v = array_array_tolist_impl(a);
Gregory P. Smith9504b132012-12-10 20:20:20 -08002323 }
Victor Stinner29ec5952013-02-26 00:27:38 +01002324 if (v == NULL)
2325 return NULL;
Raymond Hettinger88ba1e32003-04-23 17:27:00 +00002326
Serhiy Storchakab3a77962017-09-21 14:24:13 +03002327 s = PyUnicode_FromFormat("%s('%c', %R)",
2328 _PyType_Name(Py_TYPE(a)), (int)typecode, v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002329 Py_DECREF(v);
2330 return s;
Guido van Rossum778983b1993-02-19 15:55:02 +00002331}
2332
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002333static PyObject*
2334array_subscr(arrayobject* self, PyObject* item)
2335{
Erlend Egeberg Aasland75bf1072021-01-02 17:38:47 +01002336 array_state *state = find_array_state_by_type(Py_TYPE(self));
2337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002338 if (PyIndex_Check(item)) {
2339 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
2340 if (i==-1 && PyErr_Occurred()) {
2341 return NULL;
2342 }
2343 if (i < 0)
2344 i += Py_SIZE(self);
2345 return array_item(self, i);
2346 }
2347 else if (PySlice_Check(item)) {
Zackery Spytz14514d92019-05-17 01:13:03 -06002348 Py_ssize_t start, stop, step, slicelength, i;
2349 size_t cur;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002350 PyObject* result;
2351 arrayobject* ar;
2352 int itemsize = self->ob_descr->itemsize;
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002353
Serhiy Storchakab879fe82017-04-08 09:53:51 +03002354 if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002355 return NULL;
2356 }
Serhiy Storchakab879fe82017-04-08 09:53:51 +03002357 slicelength = PySlice_AdjustIndices(Py_SIZE(self), &start, &stop,
2358 step);
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002360 if (slicelength <= 0) {
Erlend Egeberg Aasland75bf1072021-01-02 17:38:47 +01002361 return newarrayobject(state->ArrayType, 0, self->ob_descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002362 }
2363 else if (step == 1) {
Erlend Egeberg Aasland75bf1072021-01-02 17:38:47 +01002364 PyObject *result = newarrayobject(state->ArrayType,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002365 slicelength, self->ob_descr);
2366 if (result == NULL)
2367 return NULL;
2368 memcpy(((arrayobject *)result)->ob_item,
2369 self->ob_item + start * itemsize,
2370 slicelength * itemsize);
2371 return result;
2372 }
2373 else {
Erlend Egeberg Aasland75bf1072021-01-02 17:38:47 +01002374 result = newarrayobject(state->ArrayType, slicelength, self->ob_descr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002375 if (!result) return NULL;
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002377 ar = (arrayobject*)result;
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002379 for (cur = start, i = 0; i < slicelength;
2380 cur += step, i++) {
2381 memcpy(ar->ob_item + i*itemsize,
2382 self->ob_item + cur*itemsize,
2383 itemsize);
2384 }
2385
2386 return result;
2387 }
2388 }
2389 else {
2390 PyErr_SetString(PyExc_TypeError,
2391 "array indices must be integers");
2392 return NULL;
2393 }
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002394}
2395
2396static int
2397array_ass_subscr(arrayobject* self, PyObject* item, PyObject* value)
2398{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002399 Py_ssize_t start, stop, step, slicelength, needed;
Erlend Egeberg Aasland75bf1072021-01-02 17:38:47 +01002400 array_state* state = find_array_state_by_type(Py_TYPE(self));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002401 arrayobject* other;
2402 int itemsize;
Thomas Woutersed03b412007-08-28 21:37:11 +00002403
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002404 if (PyIndex_Check(item)) {
2405 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Alexandre Vassalotti47137252009-07-05 19:57:00 +00002406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002407 if (i == -1 && PyErr_Occurred())
2408 return -1;
2409 if (i < 0)
2410 i += Py_SIZE(self);
2411 if (i < 0 || i >= Py_SIZE(self)) {
2412 PyErr_SetString(PyExc_IndexError,
2413 "array assignment index out of range");
2414 return -1;
2415 }
2416 if (value == NULL) {
2417 /* Fall through to slice assignment */
2418 start = i;
2419 stop = i + 1;
2420 step = 1;
2421 slicelength = 1;
2422 }
2423 else
2424 return (*self->ob_descr->setitem)(self, i, value);
2425 }
2426 else if (PySlice_Check(item)) {
Serhiy Storchakab879fe82017-04-08 09:53:51 +03002427 if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002428 return -1;
2429 }
Serhiy Storchakab879fe82017-04-08 09:53:51 +03002430 slicelength = PySlice_AdjustIndices(Py_SIZE(self), &start, &stop,
2431 step);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002432 }
2433 else {
2434 PyErr_SetString(PyExc_TypeError,
Sylvaina90e64b2017-03-29 20:09:22 +02002435 "array indices must be integers");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002436 return -1;
2437 }
2438 if (value == NULL) {
2439 other = NULL;
2440 needed = 0;
2441 }
Erlend Egeberg Aasland75bf1072021-01-02 17:38:47 +01002442 else if (array_Check(value, state)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002443 other = (arrayobject *)value;
2444 needed = Py_SIZE(other);
2445 if (self == other) {
2446 /* Special case "self[i:j] = self" -- copy self first */
2447 int ret;
2448 value = array_slice(other, 0, needed);
2449 if (value == NULL)
2450 return -1;
2451 ret = array_ass_subscr(self, item, value);
2452 Py_DECREF(value);
2453 return ret;
2454 }
2455 if (other->ob_descr != self->ob_descr) {
2456 PyErr_BadArgument();
2457 return -1;
2458 }
2459 }
2460 else {
2461 PyErr_Format(PyExc_TypeError,
2462 "can only assign array (not \"%.200s\") to array slice",
2463 Py_TYPE(value)->tp_name);
2464 return -1;
2465 }
2466 itemsize = self->ob_descr->itemsize;
2467 /* for 'a[2:1] = ...', the insertion point is 'start', not 'stop' */
2468 if ((step > 0 && stop < start) ||
2469 (step < 0 && stop > start))
2470 stop = start;
Alexandre Vassalotti47137252009-07-05 19:57:00 +00002471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002472 /* Issue #4509: If the array has exported buffers and the slice
2473 assignment would change the size of the array, fail early to make
2474 sure we don't modify it. */
2475 if ((needed == 0 || slicelength != needed) && self->ob_exports > 0) {
2476 PyErr_SetString(PyExc_BufferError,
2477 "cannot resize an array that is exporting buffers");
2478 return -1;
2479 }
Mark Dickinsonbc099642010-01-29 17:27:24 +00002480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002481 if (step == 1) {
2482 if (slicelength > needed) {
2483 memmove(self->ob_item + (start + needed) * itemsize,
2484 self->ob_item + stop * itemsize,
2485 (Py_SIZE(self) - stop) * itemsize);
2486 if (array_resize(self, Py_SIZE(self) +
2487 needed - slicelength) < 0)
2488 return -1;
2489 }
2490 else if (slicelength < needed) {
2491 if (array_resize(self, Py_SIZE(self) +
2492 needed - slicelength) < 0)
2493 return -1;
2494 memmove(self->ob_item + (start + needed) * itemsize,
2495 self->ob_item + stop * itemsize,
2496 (Py_SIZE(self) - start - needed) * itemsize);
2497 }
2498 if (needed > 0)
2499 memcpy(self->ob_item + start * itemsize,
2500 other->ob_item, needed * itemsize);
2501 return 0;
2502 }
2503 else if (needed == 0) {
2504 /* Delete slice */
2505 size_t cur;
2506 Py_ssize_t i;
Thomas Woutersed03b412007-08-28 21:37:11 +00002507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002508 if (step < 0) {
2509 stop = start + 1;
2510 start = stop + step * (slicelength - 1) - 1;
2511 step = -step;
2512 }
2513 for (cur = start, i = 0; i < slicelength;
2514 cur += step, i++) {
2515 Py_ssize_t lim = step - 1;
Thomas Woutersed03b412007-08-28 21:37:11 +00002516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002517 if (cur + step >= (size_t)Py_SIZE(self))
2518 lim = Py_SIZE(self) - cur - 1;
2519 memmove(self->ob_item + (cur - i) * itemsize,
2520 self->ob_item + (cur + 1) * itemsize,
2521 lim * itemsize);
2522 }
Mark Dickinsonc7d93b72011-09-25 15:34:32 +01002523 cur = start + (size_t)slicelength * step;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002524 if (cur < (size_t)Py_SIZE(self)) {
2525 memmove(self->ob_item + (cur-slicelength) * itemsize,
2526 self->ob_item + cur * itemsize,
2527 (Py_SIZE(self) - cur) * itemsize);
2528 }
2529 if (array_resize(self, Py_SIZE(self) - slicelength) < 0)
2530 return -1;
2531 return 0;
2532 }
2533 else {
Zackery Spytz14514d92019-05-17 01:13:03 -06002534 size_t cur;
2535 Py_ssize_t i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002536
2537 if (needed != slicelength) {
2538 PyErr_Format(PyExc_ValueError,
2539 "attempt to assign array of size %zd "
2540 "to extended slice of size %zd",
2541 needed, slicelength);
2542 return -1;
2543 }
2544 for (cur = start, i = 0; i < slicelength;
2545 cur += step, i++) {
2546 memcpy(self->ob_item + cur * itemsize,
2547 other->ob_item + i * itemsize,
2548 itemsize);
2549 }
2550 return 0;
2551 }
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002552}
2553
Guido van Rossumd8faa362007-04-27 19:54:29 +00002554static const void *emptybuf = "";
2555
Travis E. Oliphantb99f7622007-08-18 11:21:56 +00002556
2557static int
Travis E. Oliphant8ae62b62007-09-23 02:00:13 +00002558array_buffer_getbuf(arrayobject *self, Py_buffer *view, int flags)
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00002559{
Stefan Krah650c1e82015-02-03 21:43:23 +01002560 if (view == NULL) {
2561 PyErr_SetString(PyExc_BufferError,
2562 "array_buffer_getbuf: view==NULL argument is obsolete");
2563 return -1;
2564 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +00002565
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002566 view->buf = (void *)self->ob_item;
2567 view->obj = (PyObject*)self;
2568 Py_INCREF(self);
2569 if (view->buf == NULL)
2570 view->buf = (void *)emptybuf;
Victor Stinnerfe2978b2020-05-27 14:55:10 +02002571 view->len = Py_SIZE(self) * self->ob_descr->itemsize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002572 view->readonly = 0;
2573 view->ndim = 1;
2574 view->itemsize = self->ob_descr->itemsize;
2575 view->suboffsets = NULL;
2576 view->shape = NULL;
2577 if ((flags & PyBUF_ND)==PyBUF_ND) {
Victor Stinnerfe2978b2020-05-27 14:55:10 +02002578 view->shape = &((PyVarObject*)self)->ob_size;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002579 }
2580 view->strides = NULL;
2581 if ((flags & PyBUF_STRIDES)==PyBUF_STRIDES)
2582 view->strides = &(view->itemsize);
2583 view->format = NULL;
2584 view->internal = NULL;
Victor Stinner62bb3942012-08-06 00:46:05 +02002585 if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT) {
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02002586 view->format = (char *)self->ob_descr->formats;
Victor Stinner62bb3942012-08-06 00:46:05 +02002587#ifdef Py_UNICODE_WIDE
2588 if (self->ob_descr->typecode == 'u') {
2589 view->format = "w";
2590 }
2591#endif
2592 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +00002593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002594 self->ob_exports++;
2595 return 0;
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00002596}
2597
Travis E. Oliphantb99f7622007-08-18 11:21:56 +00002598static void
Travis E. Oliphant8ae62b62007-09-23 02:00:13 +00002599array_buffer_relbuf(arrayobject *self, Py_buffer *view)
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00002600{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002601 self->ob_exports--;
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00002602}
2603
Roger E. Masse2919eaa1996-12-09 20:10:36 +00002604static PyObject *
Martin v. Löwis99866332002-03-01 10:27:01 +00002605array_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum778983b1993-02-19 15:55:02 +00002606{
Erlend Egeberg Aasland75bf1072021-01-02 17:38:47 +01002607 array_state *state = find_array_state_by_type(type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002608 int c;
2609 PyObject *initial = NULL, *it = NULL;
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02002610 const struct arraydescr *descr;
Martin v. Löwis99866332002-03-01 10:27:01 +00002611
Erlend Egeberg Aasland75bf1072021-01-02 17:38:47 +01002612 if (type == state->ArrayType && !_PyArg_NoKeywords("array.array", kwds))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002613 return NULL;
Martin v. Löwis99866332002-03-01 10:27:01 +00002614
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002615 if (!PyArg_ParseTuple(args, "C|O:array", &c, &initial))
2616 return NULL;
Raymond Hettinger84fc9aa2003-04-24 10:41:55 +00002617
Steve Dowerb82e17e2019-05-23 08:45:22 -07002618 if (PySys_Audit("array.__new__", "CO",
2619 c, initial ? initial : Py_None) < 0) {
2620 return NULL;
2621 }
2622
Alexandre Vassalotti9730e332013-11-29 20:47:15 -08002623 if (initial && c != 'u') {
2624 if (PyUnicode_Check(initial)) {
2625 PyErr_Format(PyExc_TypeError, "cannot use a str to initialize "
2626 "an array with typecode '%c'", c);
2627 return NULL;
2628 }
Erlend Egeberg Aasland75bf1072021-01-02 17:38:47 +01002629 else if (array_Check(initial, state) &&
Alexandre Vassalotti9730e332013-11-29 20:47:15 -08002630 ((arrayobject*)initial)->ob_descr->typecode == 'u') {
2631 PyErr_Format(PyExc_TypeError, "cannot use a unicode array to "
2632 "initialize an array with typecode '%c'", c);
2633 return NULL;
2634 }
2635 }
2636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002637 if (!(initial == NULL || PyList_Check(initial)
2638 || PyByteArray_Check(initial)
2639 || PyBytes_Check(initial)
2640 || PyTuple_Check(initial)
Alexander Belopolskyef4a03f2011-01-11 21:44:00 +00002641 || ((c=='u') && PyUnicode_Check(initial))
Erlend Egeberg Aasland75bf1072021-01-02 17:38:47 +01002642 || (array_Check(initial, state)
Alexander Belopolskyef4a03f2011-01-11 21:44:00 +00002643 && c == ((arrayobject*)initial)->ob_descr->typecode))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002644 it = PyObject_GetIter(initial);
2645 if (it == NULL)
2646 return NULL;
2647 /* We set initial to NULL so that the subsequent code
2648 will create an empty array of the appropriate type
2649 and afterwards we can use array_iter_extend to populate
2650 the array.
2651 */
2652 initial = NULL;
2653 }
2654 for (descr = descriptors; descr->typecode != '\0'; descr++) {
2655 if (descr->typecode == c) {
2656 PyObject *a;
2657 Py_ssize_t len;
Martin v. Löwis99866332002-03-01 10:27:01 +00002658
Alexander Belopolskyef4a03f2011-01-11 21:44:00 +00002659 if (initial == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002660 len = 0;
Alexander Belopolskyef4a03f2011-01-11 21:44:00 +00002661 else if (PyList_Check(initial))
2662 len = PyList_GET_SIZE(initial);
Erlend Egeberg Aasland75bf1072021-01-02 17:38:47 +01002663 else if (PyTuple_Check(initial) || array_Check(initial, state))
Alexander Belopolskyef4a03f2011-01-11 21:44:00 +00002664 len = Py_SIZE(initial);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002665 else
Alexander Belopolskyef4a03f2011-01-11 21:44:00 +00002666 len = 0;
Martin v. Löwis99866332002-03-01 10:27:01 +00002667
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002668 a = newarrayobject(type, len, descr);
2669 if (a == NULL)
2670 return NULL;
2671
Erlend Egeberg Aasland75bf1072021-01-02 17:38:47 +01002672 if (len > 0 && !array_Check(initial, state)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002673 Py_ssize_t i;
2674 for (i = 0; i < len; i++) {
2675 PyObject *v =
2676 PySequence_GetItem(initial, i);
2677 if (v == NULL) {
2678 Py_DECREF(a);
2679 return NULL;
2680 }
2681 if (setarrayitem(a, i, v) != 0) {
2682 Py_DECREF(v);
2683 Py_DECREF(a);
2684 return NULL;
2685 }
2686 Py_DECREF(v);
2687 }
2688 }
2689 else if (initial != NULL && (PyByteArray_Check(initial) ||
2690 PyBytes_Check(initial))) {
Serhiy Storchaka04e6dba2015-04-04 17:06:55 +03002691 PyObject *v;
Brett Cannon1eb32c22014-10-10 16:26:45 -04002692 v = array_array_frombytes((arrayobject *)a,
Serhiy Storchaka04e6dba2015-04-04 17:06:55 +03002693 initial);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002694 if (v == NULL) {
2695 Py_DECREF(a);
2696 return NULL;
2697 }
2698 Py_DECREF(v);
2699 }
2700 else if (initial != NULL && PyUnicode_Check(initial)) {
Victor Stinner1fbcaef2011-09-30 01:54:04 +02002701 Py_ssize_t n;
Inada Naokid5d9a712020-05-11 15:37:25 +09002702 wchar_t *ustr = PyUnicode_AsWideCharString(initial, &n);
Victor Stinner62bb3942012-08-06 00:46:05 +02002703 if (ustr == NULL) {
Victor Stinner1fbcaef2011-09-30 01:54:04 +02002704 Py_DECREF(a);
2705 return NULL;
2706 }
Victor Stinner62bb3942012-08-06 00:46:05 +02002707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002708 if (n > 0) {
2709 arrayobject *self = (arrayobject *)a;
Inada Naokid5d9a712020-05-11 15:37:25 +09002710 // self->ob_item may be NULL but it is safe.
2711 PyMem_Free(self->ob_item);
2712 self->ob_item = (char *)ustr;
2713 Py_SET_SIZE(self, n);
2714 self->allocated = n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002715 }
2716 }
Erlend Egeberg Aasland75bf1072021-01-02 17:38:47 +01002717 else if (initial != NULL && array_Check(initial, state) && len > 0) {
Alexander Belopolskyef4a03f2011-01-11 21:44:00 +00002718 arrayobject *self = (arrayobject *)a;
2719 arrayobject *other = (arrayobject *)initial;
2720 memcpy(self->ob_item, other->ob_item, len * other->ob_descr->itemsize);
2721 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002722 if (it != NULL) {
2723 if (array_iter_extend((arrayobject *)a, it) == -1) {
2724 Py_DECREF(it);
2725 Py_DECREF(a);
2726 return NULL;
2727 }
2728 Py_DECREF(it);
2729 }
2730 return a;
2731 }
2732 }
2733 PyErr_SetString(PyExc_ValueError,
Meador Inge1c9f0c92011-09-20 19:55:51 -05002734 "bad typecode (must be b, B, u, h, H, i, I, l, L, q, Q, f or d)");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002735 return NULL;
Guido van Rossum778983b1993-02-19 15:55:02 +00002736}
2737
Guido van Rossum778983b1993-02-19 15:55:02 +00002738
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002739PyDoc_STRVAR(module_doc,
Martin v. Löwis99866332002-03-01 10:27:01 +00002740"This module defines an object type which can efficiently represent\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002741an array of basic values: characters, integers, floating point\n\
2742numbers. Arrays are sequence types and behave very much like lists,\n\
Alexandre Vassalotti9730e332013-11-29 20:47:15 -08002743except that the type of objects stored in them is constrained.\n");
2744
2745PyDoc_STRVAR(arraytype_doc,
2746"array(typecode [, initializer]) -> array\n\
2747\n\
2748Return a new array whose items are restricted by typecode, and\n\
2749initialized from the optional initializer value, which must be a list,\n\
2750string or iterable over elements of the appropriate type.\n\
2751\n\
2752Arrays represent basic values and behave very much like lists, except\n\
2753the type of objects stored in them is constrained. The type is specified\n\
2754at object creation time by using a type code, which is a single character.\n\
2755The following type codes are defined:\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002756\n\
oldkaa0735f2018-02-02 16:52:55 +08002757 Type code C Type Minimum size in bytes\n\
2758 'b' signed integer 1\n\
2759 'B' unsigned integer 1\n\
2760 'u' Unicode character 2 (see note)\n\
2761 'h' signed integer 2\n\
2762 'H' unsigned integer 2\n\
2763 'i' signed integer 2\n\
2764 'I' unsigned integer 2\n\
2765 'l' signed integer 4\n\
2766 'L' unsigned integer 4\n\
2767 'q' signed integer 8 (see note)\n\
2768 'Q' unsigned integer 8 (see note)\n\
2769 'f' floating point 4\n\
2770 'd' floating point 8\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002771\n\
oldkaa0735f2018-02-02 16:52:55 +08002772NOTE: The 'u' typecode corresponds to Python's unicode character. On\n\
Victor Stinner62bb3942012-08-06 00:46:05 +02002773narrow builds this is 2-bytes on wide builds this is 4-bytes.\n\
2774\n\
oldkaa0735f2018-02-02 16:52:55 +08002775NOTE: The 'q' and 'Q' type codes are only available if the platform\n\
2776C compiler used to build Python supports 'long long', or, on Windows,\n\
Meador Inge1c9f0c92011-09-20 19:55:51 -05002777'__int64'.\n\
2778\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002779Methods:\n\
2780\n\
2781append() -- append a new item to the end of the array\n\
2782buffer_info() -- return information giving the current memory info\n\
2783byteswap() -- byteswap all the items of the array\n\
Mark Dickinson934896d2009-02-21 20:59:32 +00002784count() -- return number of occurrences of an object\n\
Raymond Hettinger49f9bd12004-03-14 05:43:59 +00002785extend() -- extend array by appending multiple elements from an iterable\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002786fromfile() -- read items from a file object\n\
2787fromlist() -- append items from the list\n\
Florent Xiclunac45fb252011-10-24 13:14:55 +02002788frombytes() -- append items from the string\n\
Mark Dickinson934896d2009-02-21 20:59:32 +00002789index() -- return index of first occurrence of an object\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002790insert() -- insert a new item into the array at a provided position\n\
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00002791pop() -- remove and return item (default last)\n\
Mark Dickinson934896d2009-02-21 20:59:32 +00002792remove() -- remove first occurrence of an object\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002793reverse() -- reverse the order of the items in the array\n\
2794tofile() -- write all items to a file object\n\
2795tolist() -- return the array converted to an ordinary list\n\
Florent Xiclunac45fb252011-10-24 13:14:55 +02002796tobytes() -- return the array converted to a string\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002797\n\
Martin v. Löwis99866332002-03-01 10:27:01 +00002798Attributes:\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002799\n\
2800typecode -- the typecode character used to create the array\n\
2801itemsize -- the length in bytes of one array item\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002802");
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002803
Raymond Hettinger625812f2003-01-07 01:58:52 +00002804static PyObject *array_iter(arrayobject *ao);
2805
Erlend Egeberg Aasland75bf1072021-01-02 17:38:47 +01002806static struct PyMemberDef array_members[] = {
2807 {"__weaklistoffset__", T_PYSSIZET, offsetof(arrayobject, weakreflist), READONLY},
2808 {NULL},
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002809};
2810
Erlend Egeberg Aasland75bf1072021-01-02 17:38:47 +01002811static PyType_Slot array_slots[] = {
2812 {Py_tp_dealloc, array_dealloc},
2813 {Py_tp_repr, array_repr},
2814 {Py_tp_getattro, PyObject_GenericGetAttr},
2815 {Py_tp_doc, (void *)arraytype_doc},
2816 {Py_tp_richcompare, array_richcompare},
2817 {Py_tp_iter, array_iter},
2818 {Py_tp_methods, array_methods},
2819 {Py_tp_members, array_members},
2820 {Py_tp_getset, array_getsets},
2821 {Py_tp_alloc, PyType_GenericAlloc},
2822 {Py_tp_new, array_new},
2823 {Py_tp_free, PyObject_Del},
2824
2825 /* as sequence */
2826 {Py_sq_length, array_length},
2827 {Py_sq_concat, array_concat},
2828 {Py_sq_repeat, array_repeat},
2829 {Py_sq_item, array_item},
2830 {Py_sq_ass_item, array_ass_item},
2831 {Py_sq_contains, array_contains},
2832 {Py_sq_inplace_concat, array_inplace_concat},
2833 {Py_sq_inplace_repeat, array_inplace_repeat},
2834
2835 /* as mapping */
2836 {Py_mp_length, array_length},
2837 {Py_mp_subscript, array_subscr},
2838 {Py_mp_ass_subscript, array_ass_subscr},
2839
2840 /* as buffer */
2841 {Py_bf_getbuffer, array_buffer_getbuf},
2842 {Py_bf_releasebuffer, array_buffer_relbuf},
2843
2844 {0, NULL},
2845};
2846
2847static PyType_Spec array_spec = {
2848 .name = "array.array",
2849 .basicsize = sizeof(arrayobject),
Erlend Egeberg Aaslandc6ad03f2021-04-29 08:47:48 +02002850 .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Mark Shannon069e81a2021-04-30 09:50:28 +01002851 Py_TPFLAGS_IMMUTABLETYPE |
2852 Py_TPFLAGS_SEQUENCE),
Erlend Egeberg Aasland75bf1072021-01-02 17:38:47 +01002853 .slots = array_slots,
2854};
Raymond Hettinger625812f2003-01-07 01:58:52 +00002855
2856/*********************** Array Iterator **************************/
2857
Brett Cannon1eb32c22014-10-10 16:26:45 -04002858/*[clinic input]
Erlend Egeberg Aasland75bf1072021-01-02 17:38:47 +01002859class array.arrayiterator "arrayiterobject *" "find_array_state_by_type(type)->ArrayIterType"
Brett Cannon1eb32c22014-10-10 16:26:45 -04002860[clinic start generated code]*/
Erlend Egeberg Aasland75bf1072021-01-02 17:38:47 +01002861/*[clinic end generated code: output=da39a3ee5e6b4b0d input=fb46d5ef98dd95ff]*/
Raymond Hettinger625812f2003-01-07 01:58:52 +00002862
2863static PyObject *
2864array_iter(arrayobject *ao)
2865{
Erlend Egeberg Aasland75bf1072021-01-02 17:38:47 +01002866 array_state *state = find_array_state_by_type(Py_TYPE(ao));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002867 arrayiterobject *it;
Raymond Hettinger625812f2003-01-07 01:58:52 +00002868
Erlend Egeberg Aasland75bf1072021-01-02 17:38:47 +01002869 if (!array_Check(ao, state)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002870 PyErr_BadInternalCall();
2871 return NULL;
2872 }
Raymond Hettinger625812f2003-01-07 01:58:52 +00002873
Erlend Egeberg Aasland75bf1072021-01-02 17:38:47 +01002874 it = PyObject_GC_New(arrayiterobject, state->ArrayIterType);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002875 if (it == NULL)
2876 return NULL;
Raymond Hettinger625812f2003-01-07 01:58:52 +00002877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002878 Py_INCREF(ao);
2879 it->ao = ao;
2880 it->index = 0;
2881 it->getitem = ao->ob_descr->getitem;
2882 PyObject_GC_Track(it);
2883 return (PyObject *)it;
Raymond Hettinger625812f2003-01-07 01:58:52 +00002884}
2885
2886static PyObject *
Raymond Hettinger625812f2003-01-07 01:58:52 +00002887arrayiter_next(arrayiterobject *it)
2888{
Serhiy Storchakaab0d1982016-03-30 21:11:16 +03002889 arrayobject *ao;
2890
2891 assert(it != NULL);
Erlend Egeberg Aasland75bf1072021-01-02 17:38:47 +01002892#ifndef NDEBUG
2893 array_state *state = find_array_state_by_type(Py_TYPE(it));
2894 assert(PyObject_TypeCheck(it, state->ArrayIterType));
2895#endif
Serhiy Storchakaab0d1982016-03-30 21:11:16 +03002896 ao = it->ao;
2897 if (ao == NULL) {
2898 return NULL;
2899 }
Erlend Egeberg Aasland75bf1072021-01-02 17:38:47 +01002900#ifndef NDEBUG
2901 assert(array_Check(ao, state));
2902#endif
Serhiy Storchakaab0d1982016-03-30 21:11:16 +03002903 if (it->index < Py_SIZE(ao)) {
2904 return (*it->getitem)(ao, it->index++);
2905 }
2906 it->ao = NULL;
2907 Py_DECREF(ao);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002908 return NULL;
Raymond Hettinger625812f2003-01-07 01:58:52 +00002909}
2910
2911static void
2912arrayiter_dealloc(arrayiterobject *it)
2913{
Erlend Egeberg Aasland75bf1072021-01-02 17:38:47 +01002914 PyTypeObject *tp = Py_TYPE(it);
2915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002916 PyObject_GC_UnTrack(it);
2917 Py_XDECREF(it->ao);
2918 PyObject_GC_Del(it);
Erlend Egeberg Aasland75bf1072021-01-02 17:38:47 +01002919 Py_DECREF(tp);
Raymond Hettinger625812f2003-01-07 01:58:52 +00002920}
2921
2922static int
2923arrayiter_traverse(arrayiterobject *it, visitproc visit, void *arg)
2924{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002925 Py_VISIT(it->ao);
2926 return 0;
Raymond Hettinger625812f2003-01-07 01:58:52 +00002927}
2928
Brett Cannon1eb32c22014-10-10 16:26:45 -04002929/*[clinic input]
2930array.arrayiterator.__reduce__
2931
2932Return state information for pickling.
2933[clinic start generated code]*/
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002934
2935static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04002936array_arrayiterator___reduce___impl(arrayiterobject *self)
2937/*[clinic end generated code: output=7898a52e8e66e016 input=a062ea1e9951417a]*/
2938{
Serhiy Storchakabb86bf42018-12-11 08:28:18 +02002939 _Py_IDENTIFIER(iter);
2940 PyObject *func = _PyEval_GetBuiltinId(&PyId_iter);
Serhiy Storchakaab0d1982016-03-30 21:11:16 +03002941 if (self->ao == NULL) {
2942 return Py_BuildValue("N(())", func);
2943 }
2944 return Py_BuildValue("N(O)n", func, self->ao, self->index);
Brett Cannon1eb32c22014-10-10 16:26:45 -04002945}
2946
2947/*[clinic input]
2948array.arrayiterator.__setstate__
2949
2950 state: object
2951 /
2952
2953Set state information for unpickling.
2954[clinic start generated code]*/
2955
2956static PyObject *
2957array_arrayiterator___setstate__(arrayiterobject *self, PyObject *state)
2958/*[clinic end generated code: output=397da9904e443cbe input=f47d5ceda19e787b]*/
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002959{
2960 Py_ssize_t index = PyLong_AsSsize_t(state);
2961 if (index == -1 && PyErr_Occurred())
2962 return NULL;
2963 if (index < 0)
2964 index = 0;
Brett Cannon1eb32c22014-10-10 16:26:45 -04002965 else if (index > Py_SIZE(self->ao))
2966 index = Py_SIZE(self->ao); /* iterator exhausted */
2967 self->index = index;
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002968 Py_RETURN_NONE;
2969}
2970
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002971static PyMethodDef arrayiter_methods[] = {
Brett Cannon1eb32c22014-10-10 16:26:45 -04002972 ARRAY_ARRAYITERATOR___REDUCE___METHODDEF
2973 ARRAY_ARRAYITERATOR___SETSTATE___METHODDEF
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002974 {NULL, NULL} /* sentinel */
2975};
2976
Erlend Egeberg Aasland75bf1072021-01-02 17:38:47 +01002977static PyType_Slot arrayiter_slots[] = {
2978 {Py_tp_dealloc, arrayiter_dealloc},
2979 {Py_tp_getattro, PyObject_GenericGetAttr},
2980 {Py_tp_traverse, arrayiter_traverse},
2981 {Py_tp_iter, PyObject_SelfIter},
2982 {Py_tp_iternext, arrayiter_next},
2983 {Py_tp_methods, arrayiter_methods},
2984 {0, NULL},
2985};
2986
2987static PyType_Spec arrayiter_spec = {
2988 .name = "array.arrayiterator",
2989 .basicsize = sizeof(arrayiterobject),
2990 .flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
2991 .slots = arrayiter_slots,
Raymond Hettinger625812f2003-01-07 01:58:52 +00002992};
2993
2994
2995/*********************** Install Module **************************/
2996
Erlend Egeberg Aaslandb8eb3762021-01-03 14:11:15 +01002997static int
2998array_traverse(PyObject *module, visitproc visit, void *arg)
2999{
3000 array_state *state = get_array_state(module);
3001 Py_VISIT(state->ArrayType);
3002 Py_VISIT(state->ArrayIterType);
3003 return 0;
3004}
3005
3006static int
3007array_clear(PyObject *module)
3008{
3009 array_state *state = get_array_state(module);
3010 Py_CLEAR(state->ArrayType);
3011 Py_CLEAR(state->ArrayIterType);
3012 return 0;
3013}
3014
3015static void
3016array_free(void *module)
3017{
3018 array_clear((PyObject *)module);
3019}
3020
Martin v. Löwis99866332002-03-01 10:27:01 +00003021/* No functions in array module. */
3022static PyMethodDef a_methods[] = {
Brett Cannon1eb32c22014-10-10 16:26:45 -04003023 ARRAY__ARRAY_RECONSTRUCTOR_METHODDEF
Martin v. Löwis99866332002-03-01 10:27:01 +00003024 {NULL, NULL, 0, NULL} /* Sentinel */
3025};
3026
Erlend Egeberg Aaslandb8eb3762021-01-03 14:11:15 +01003027#define CREATE_TYPE(module, type, spec) \
3028do { \
3029 type = (PyTypeObject *)PyType_FromModuleAndSpec(module, spec, NULL); \
3030 if (type == NULL) { \
3031 return -1; \
3032 } \
Erlend Egeberg Aasland75bf1072021-01-02 17:38:47 +01003033} while (0)
3034
Nick Coghland5cacbb2015-05-23 22:24:10 +10003035static int
3036array_modexec(PyObject *m)
Guido van Rossum778983b1993-02-19 15:55:02 +00003037{
Erlend Egeberg Aasland75bf1072021-01-02 17:38:47 +01003038 array_state *state = get_array_state(m);
Georg Brandl4cb0de22011-09-28 21:49:49 +02003039 char buffer[Py_ARRAY_LENGTH(descriptors)], *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003040 PyObject *typecodes;
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02003041 const struct arraydescr *descr;
Fred Drake0d40ba42000-02-04 20:33:49 +00003042
Erlend Egeberg Aasland75bf1072021-01-02 17:38:47 +01003043 CREATE_TYPE(m, state->ArrayType, &array_spec);
3044 CREATE_TYPE(m, state->ArrayIterType, &arrayiter_spec);
3045 Py_SET_TYPE(state->ArrayIterType, &PyType_Type);
Fred Drakef4e34842002-04-01 03:45:06 +00003046
Erlend Egeberg Aasland75bf1072021-01-02 17:38:47 +01003047 Py_INCREF((PyObject *)state->ArrayType);
3048 if (PyModule_AddObject(m, "ArrayType", (PyObject *)state->ArrayType) < 0) {
3049 Py_DECREF((PyObject *)state->ArrayType);
Marco Paolinib44ffc82019-11-15 08:42:51 +00003050 return -1;
3051 }
Pablo Galindoe51dd9d2020-07-05 22:43:14 +01003052
3053 PyObject *abc_mod = PyImport_ImportModule("collections.abc");
3054 if (!abc_mod) {
Erlend Egeberg Aasland75bf1072021-01-02 17:38:47 +01003055 Py_DECREF((PyObject *)state->ArrayType);
Pablo Galindoe51dd9d2020-07-05 22:43:14 +01003056 return -1;
3057 }
3058 PyObject *mutablesequence = PyObject_GetAttrString(abc_mod, "MutableSequence");
3059 Py_DECREF(abc_mod);
3060 if (!mutablesequence) {
Erlend Egeberg Aasland75bf1072021-01-02 17:38:47 +01003061 Py_DECREF((PyObject *)state->ArrayType);
Pablo Galindoe51dd9d2020-07-05 22:43:14 +01003062 return -1;
3063 }
Erlend Egeberg Aasland75bf1072021-01-02 17:38:47 +01003064 PyObject *res = PyObject_CallMethod(mutablesequence, "register", "O",
3065 (PyObject *)state->ArrayType);
Pablo Galindoe51dd9d2020-07-05 22:43:14 +01003066 Py_DECREF(mutablesequence);
3067 if (!res) {
Erlend Egeberg Aasland75bf1072021-01-02 17:38:47 +01003068 Py_DECREF((PyObject *)state->ArrayType);
Pablo Galindoe51dd9d2020-07-05 22:43:14 +01003069 return -1;
3070 }
3071 Py_DECREF(res);
3072
Erlend Egeberg Aasland75bf1072021-01-02 17:38:47 +01003073 if (PyModule_AddType(m, state->ArrayType) < 0) {
Marco Paolinib44ffc82019-11-15 08:42:51 +00003074 return -1;
3075 }
Travis E. Oliphantd5c0add2007-10-12 22:05:15 +00003076
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003077 p = buffer;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003078 for (descr = descriptors; descr->typecode != '\0'; descr++) {
3079 *p++ = (char)descr->typecode;
3080 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003081 typecodes = PyUnicode_DecodeASCII(buffer, p - buffer, NULL);
Marco Paolinib44ffc82019-11-15 08:42:51 +00003082 if (PyModule_AddObject(m, "typecodes", typecodes) < 0) {
3083 Py_XDECREF(typecodes);
3084 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003085 }
Marco Paolinib44ffc82019-11-15 08:42:51 +00003086
Nick Coghland5cacbb2015-05-23 22:24:10 +10003087 return 0;
3088}
3089
3090static PyModuleDef_Slot arrayslots[] = {
3091 {Py_mod_exec, array_modexec},
3092 {0, NULL}
3093};
3094
3095
3096static struct PyModuleDef arraymodule = {
Erlend Egeberg Aasland75bf1072021-01-02 17:38:47 +01003097 .m_base = PyModuleDef_HEAD_INIT,
3098 .m_name = "array",
3099 .m_size = sizeof(array_state),
3100 .m_doc = module_doc,
3101 .m_methods = a_methods,
3102 .m_slots = arrayslots,
Erlend Egeberg Aaslandb8eb3762021-01-03 14:11:15 +01003103 .m_traverse = array_traverse,
3104 .m_clear = array_clear,
3105 .m_free = array_free,
Nick Coghland5cacbb2015-05-23 22:24:10 +10003106};
3107
3108
3109PyMODINIT_FUNC
3110PyInit_array(void)
3111{
3112 return PyModuleDef_Init(&arraymodule);
Guido van Rossum778983b1993-02-19 15:55:02 +00003113}