blob: b7ef702111ad96bf36eec30e081e7bd1285ec01f [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"
Raymond Hettingercb87bc82004-05-31 00:35:52 +00008#include "structmember.h"
Roger E. Masse5817f8f1996-12-09 22:24:19 +00009
Guido van Rossum0c709541994-08-19 12:01:32 +000010#ifdef STDC_HEADERS
11#include <stddef.h>
Guido van Rossum7f1de831999-08-27 20:33:52 +000012#else /* !STDC_HEADERS */
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013#ifdef HAVE_SYS_TYPES_H
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000014#include <sys/types.h> /* For size_t */
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015#endif /* HAVE_SYS_TYPES_H */
Guido van Rossum7f1de831999-08-27 20:33:52 +000016#endif /* !STDC_HEADERS */
Guido van Rossum778983b1993-02-19 15:55:02 +000017
Brett Cannon1eb32c22014-10-10 16:26:45 -040018/*[clinic input]
19output preset file
20module array
21[clinic start generated code]*/
22/*[clinic end generated code: output=da39a3ee5e6b4b0d input=0909c1a148c69931]*/
23
Guido van Rossum778983b1993-02-19 15:55:02 +000024struct arrayobject; /* Forward */
25
Tim Petersbb307342000-09-10 05:22:54 +000026/* All possible arraydescr values are defined in the vector "descriptors"
27 * below. That's defined later because the appropriate get and set
28 * functions aren't visible yet.
29 */
Guido van Rossum778983b1993-02-19 15:55:02 +000030struct arraydescr {
Victor Stinnerf8bb7d02011-09-30 00:03:59 +020031 char typecode;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000032 int itemsize;
33 PyObject * (*getitem)(struct arrayobject *, Py_ssize_t);
34 int (*setitem)(struct arrayobject *, Py_ssize_t, PyObject *);
35 char *formats;
36 int is_integer_type;
37 int is_signed;
Guido van Rossum778983b1993-02-19 15:55:02 +000038};
39
40typedef struct arrayobject {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000041 PyObject_VAR_HEAD
42 char *ob_item;
43 Py_ssize_t allocated;
44 struct arraydescr *ob_descr;
45 PyObject *weakreflist; /* List of weak references */
46 int ob_exports; /* Number of exported buffers */
Guido van Rossum778983b1993-02-19 15:55:02 +000047} arrayobject;
48
Jeremy Hylton938ace62002-07-17 16:30:39 +000049static PyTypeObject Arraytype;
Guido van Rossum778983b1993-02-19 15:55:02 +000050
Brett Cannon1eb32c22014-10-10 16:26:45 -040051typedef struct {
52 PyObject_HEAD
53 Py_ssize_t index;
54 arrayobject *ao;
55 PyObject* (*getitem)(struct arrayobject *, Py_ssize_t);
56} arrayiterobject;
57
58static PyTypeObject PyArrayIter_Type;
59
60#define PyArrayIter_Check(op) PyObject_TypeCheck(op, &PyArrayIter_Type)
61
Larry Hastingsdfbeb162014-10-13 10:39:41 +010062enum machine_format_code {
63 UNKNOWN_FORMAT = -1,
64 /* UNKNOWN_FORMAT is used to indicate that the machine format for an
65 * array type code cannot be interpreted. When this occurs, a list of
66 * Python objects is used to represent the content of the array
67 * instead of using the memory content of the array directly. In that
68 * case, the array_reconstructor mechanism is bypassed completely, and
69 * the standard array constructor is used instead.
70 *
71 * This is will most likely occur when the machine doesn't use IEEE
72 * floating-point numbers.
73 */
74
75 UNSIGNED_INT8 = 0,
76 SIGNED_INT8 = 1,
77 UNSIGNED_INT16_LE = 2,
78 UNSIGNED_INT16_BE = 3,
79 SIGNED_INT16_LE = 4,
80 SIGNED_INT16_BE = 5,
81 UNSIGNED_INT32_LE = 6,
82 UNSIGNED_INT32_BE = 7,
83 SIGNED_INT32_LE = 8,
84 SIGNED_INT32_BE = 9,
85 UNSIGNED_INT64_LE = 10,
86 UNSIGNED_INT64_BE = 11,
87 SIGNED_INT64_LE = 12,
88 SIGNED_INT64_BE = 13,
89 IEEE_754_FLOAT_LE = 14,
90 IEEE_754_FLOAT_BE = 15,
91 IEEE_754_DOUBLE_LE = 16,
92 IEEE_754_DOUBLE_BE = 17,
93 UTF16_LE = 18,
94 UTF16_BE = 19,
95 UTF32_LE = 20,
96 UTF32_BE = 21
97};
98#define MACHINE_FORMAT_CODE_MIN 0
99#define MACHINE_FORMAT_CODE_MAX 21
100
101
102/*
103 * Must come after arrayobject, arrayiterobject,
104 * and enum machine_code_type definitions.
105 */
Brett Cannon1eb32c22014-10-10 16:26:45 -0400106#include "clinic/arraymodule.c.h"
107
Martin v. Löwis99866332002-03-01 10:27:01 +0000108#define array_Check(op) PyObject_TypeCheck(op, &Arraytype)
Christian Heimes90aa7642007-12-19 02:45:37 +0000109#define array_CheckExact(op) (Py_TYPE(op) == &Arraytype)
Guido van Rossum778983b1993-02-19 15:55:02 +0000110
Raymond Hettinger6e2ee862004-03-14 04:37:50 +0000111static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000112array_resize(arrayobject *self, Py_ssize_t newsize)
Raymond Hettinger6e2ee862004-03-14 04:37:50 +0000113{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000114 char *items;
115 size_t _new_size;
Raymond Hettinger6e2ee862004-03-14 04:37:50 +0000116
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000117 if (self->ob_exports > 0 && newsize != Py_SIZE(self)) {
118 PyErr_SetString(PyExc_BufferError,
119 "cannot resize an array that is exporting buffers");
120 return -1;
121 }
Antoine Pitrou3ad3a0d2008-12-18 17:08:32 +0000122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000123 /* Bypass realloc() when a previous overallocation is large enough
124 to accommodate the newsize. If the newsize is 16 smaller than the
125 current size, then proceed with the realloc() to shrink the array.
126 */
Raymond Hettinger6e2ee862004-03-14 04:37:50 +0000127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000128 if (self->allocated >= newsize &&
129 Py_SIZE(self) < newsize + 16 &&
130 self->ob_item != NULL) {
131 Py_SIZE(self) = newsize;
132 return 0;
133 }
Raymond Hettinger6e2ee862004-03-14 04:37:50 +0000134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000135 if (newsize == 0) {
136 PyMem_FREE(self->ob_item);
137 self->ob_item = NULL;
138 Py_SIZE(self) = 0;
139 self->allocated = 0;
140 return 0;
141 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000143 /* This over-allocates proportional to the array size, making room
144 * for additional growth. The over-allocation is mild, but is
145 * enough to give linear-time amortized behavior over a long
146 * sequence of appends() in the presence of a poorly-performing
147 * system realloc().
148 * The growth pattern is: 0, 4, 8, 16, 25, 34, 46, 56, 67, 79, ...
149 * Note, the pattern starts out the same as for lists but then
150 * grows at a smaller rate so that larger arrays only overallocate
151 * by about 1/16th -- this is done because arrays are presumed to be more
152 * memory critical.
153 */
Raymond Hettinger6e2ee862004-03-14 04:37:50 +0000154
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000155 _new_size = (newsize >> 4) + (Py_SIZE(self) < 8 ? 3 : 7) + newsize;
156 items = self->ob_item;
157 /* XXX The following multiplication and division does not optimize away
158 like it does for lists since the size is not known at compile time */
159 if (_new_size <= ((~(size_t)0) / self->ob_descr->itemsize))
160 PyMem_RESIZE(items, char, (_new_size * self->ob_descr->itemsize));
161 else
162 items = NULL;
163 if (items == NULL) {
164 PyErr_NoMemory();
165 return -1;
166 }
167 self->ob_item = items;
168 Py_SIZE(self) = newsize;
169 self->allocated = _new_size;
170 return 0;
Raymond Hettinger6e2ee862004-03-14 04:37:50 +0000171}
172
Tim Petersbb307342000-09-10 05:22:54 +0000173/****************************************************************************
174Get and Set functions for each type.
175A Get function takes an arrayobject* and an integer index, returning the
176array value at that index wrapped in an appropriate PyObject*.
177A Set function takes an arrayobject, integer index, and PyObject*; sets
178the array value at that index to the raw C data extracted from the PyObject*,
179and returns 0 if successful, else nonzero on failure (PyObject* not of an
180appropriate type or value).
181Note that the basic Get and Set functions do NOT check that the index is
182in bounds; that's the responsibility of the caller.
183****************************************************************************/
Guido van Rossum778983b1993-02-19 15:55:02 +0000184
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000185static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000186b_getitem(arrayobject *ap, Py_ssize_t i)
Guido van Rossum778983b1993-02-19 15:55:02 +0000187{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000188 long x = ((char *)ap->ob_item)[i];
189 if (x >= 128)
190 x -= 256;
191 return PyLong_FromLong(x);
Guido van Rossum778983b1993-02-19 15:55:02 +0000192}
193
194static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000195b_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
Guido van Rossum778983b1993-02-19 15:55:02 +0000196{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000197 short x;
198 /* PyArg_Parse's 'b' formatter is for an unsigned char, therefore
199 must use the next size up that is signed ('h') and manually do
200 the overflow checking */
201 if (!PyArg_Parse(v, "h;array item must be integer", &x))
202 return -1;
203 else if (x < -128) {
204 PyErr_SetString(PyExc_OverflowError,
205 "signed char is less than minimum");
206 return -1;
207 }
208 else if (x > 127) {
209 PyErr_SetString(PyExc_OverflowError,
210 "signed char is greater than maximum");
211 return -1;
212 }
213 if (i >= 0)
214 ((char *)ap->ob_item)[i] = (char)x;
215 return 0;
Guido van Rossum778983b1993-02-19 15:55:02 +0000216}
217
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000218static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000219BB_getitem(arrayobject *ap, Py_ssize_t i)
Guido van Rossum549ab711997-01-03 19:09:47 +0000220{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000221 long x = ((unsigned char *)ap->ob_item)[i];
222 return PyLong_FromLong(x);
Guido van Rossum549ab711997-01-03 19:09:47 +0000223}
224
Fred Drake541dc3b2000-06-28 17:49:30 +0000225static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000226BB_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
Fred Drake541dc3b2000-06-28 17:49:30 +0000227{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000228 unsigned char x;
229 /* 'B' == unsigned char, maps to PyArg_Parse's 'b' formatter */
230 if (!PyArg_Parse(v, "b;array item must be integer", &x))
231 return -1;
232 if (i >= 0)
233 ((char *)ap->ob_item)[i] = x;
234 return 0;
Fred Drake541dc3b2000-06-28 17:49:30 +0000235}
Guido van Rossum549ab711997-01-03 19:09:47 +0000236
Martin v. Löwis99866332002-03-01 10:27:01 +0000237static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000238u_getitem(arrayobject *ap, Py_ssize_t i)
Martin v. Löwis99866332002-03-01 10:27:01 +0000239{
Victor Stinner62bb3942012-08-06 00:46:05 +0200240 return PyUnicode_FromUnicode(&((Py_UNICODE *) ap->ob_item)[i], 1);
Martin v. Löwis99866332002-03-01 10:27:01 +0000241}
242
243static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000244u_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
Martin v. Löwis99866332002-03-01 10:27:01 +0000245{
Victor Stinner62bb3942012-08-06 00:46:05 +0200246 Py_UNICODE *p;
247 Py_ssize_t len;
Martin v. Löwis99866332002-03-01 10:27:01 +0000248
Victor Stinner62bb3942012-08-06 00:46:05 +0200249 if (!PyArg_Parse(v, "u#;array item must be unicode character", &p, &len))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000250 return -1;
Victor Stinner62bb3942012-08-06 00:46:05 +0200251 if (len != 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000252 PyErr_SetString(PyExc_TypeError,
253 "array item must be unicode character");
254 return -1;
255 }
256 if (i >= 0)
Victor Stinner62bb3942012-08-06 00:46:05 +0200257 ((Py_UNICODE *)ap->ob_item)[i] = p[0];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000258 return 0;
Martin v. Löwis99866332002-03-01 10:27:01 +0000259}
Martin v. Löwis99866332002-03-01 10:27:01 +0000260
Travis E. Oliphantd5c0add2007-10-12 22:05:15 +0000261
Guido van Rossum549ab711997-01-03 19:09:47 +0000262static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000263h_getitem(arrayobject *ap, Py_ssize_t i)
Guido van Rossum778983b1993-02-19 15:55:02 +0000264{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000265 return PyLong_FromLong((long) ((short *)ap->ob_item)[i]);
Guido van Rossum778983b1993-02-19 15:55:02 +0000266}
267
Travis E. Oliphantd5c0add2007-10-12 22:05:15 +0000268
Guido van Rossum778983b1993-02-19 15:55:02 +0000269static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000270h_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
Guido van Rossum778983b1993-02-19 15:55:02 +0000271{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000272 short x;
273 /* 'h' == signed short, maps to PyArg_Parse's 'h' formatter */
274 if (!PyArg_Parse(v, "h;array item must be integer", &x))
275 return -1;
276 if (i >= 0)
277 ((short *)ap->ob_item)[i] = x;
278 return 0;
Guido van Rossum778983b1993-02-19 15:55:02 +0000279}
280
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000281static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000282HH_getitem(arrayobject *ap, Py_ssize_t i)
Guido van Rossum549ab711997-01-03 19:09:47 +0000283{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000284 return PyLong_FromLong((long) ((unsigned short *)ap->ob_item)[i]);
Guido van Rossum549ab711997-01-03 19:09:47 +0000285}
286
Fred Drake541dc3b2000-06-28 17:49:30 +0000287static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000288HH_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
Fred Drake541dc3b2000-06-28 17:49:30 +0000289{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000290 int x;
291 /* PyArg_Parse's 'h' formatter is for a signed short, therefore
292 must use the next size up and manually do the overflow checking */
293 if (!PyArg_Parse(v, "i;array item must be integer", &x))
294 return -1;
295 else if (x < 0) {
296 PyErr_SetString(PyExc_OverflowError,
297 "unsigned short is less than minimum");
298 return -1;
299 }
300 else if (x > USHRT_MAX) {
301 PyErr_SetString(PyExc_OverflowError,
302 "unsigned short is greater than maximum");
303 return -1;
304 }
305 if (i >= 0)
306 ((short *)ap->ob_item)[i] = (short)x;
307 return 0;
Fred Drake541dc3b2000-06-28 17:49:30 +0000308}
Guido van Rossum549ab711997-01-03 19:09:47 +0000309
310static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000311i_getitem(arrayobject *ap, Py_ssize_t i)
Guido van Rossume77a7571993-11-03 15:01:26 +0000312{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000313 return PyLong_FromLong((long) ((int *)ap->ob_item)[i]);
Guido van Rossume77a7571993-11-03 15:01:26 +0000314}
315
316static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000317i_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
Guido van Rossume77a7571993-11-03 15:01:26 +0000318{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000319 int x;
320 /* 'i' == signed int, maps to PyArg_Parse's 'i' formatter */
321 if (!PyArg_Parse(v, "i;array item must be integer", &x))
322 return -1;
323 if (i >= 0)
324 ((int *)ap->ob_item)[i] = x;
325 return 0;
Guido van Rossume77a7571993-11-03 15:01:26 +0000326}
327
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000328static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000329II_getitem(arrayobject *ap, Py_ssize_t i)
Guido van Rossum549ab711997-01-03 19:09:47 +0000330{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000331 return PyLong_FromUnsignedLong(
332 (unsigned long) ((unsigned int *)ap->ob_item)[i]);
Guido van Rossum549ab711997-01-03 19:09:47 +0000333}
334
335static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000336II_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
Guido van Rossum549ab711997-01-03 19:09:47 +0000337{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000338 unsigned long x;
339 if (PyLong_Check(v)) {
340 x = PyLong_AsUnsignedLong(v);
341 if (x == (unsigned long) -1 && PyErr_Occurred())
342 return -1;
343 }
344 else {
345 long y;
346 if (!PyArg_Parse(v, "l;array item must be integer", &y))
347 return -1;
348 if (y < 0) {
349 PyErr_SetString(PyExc_OverflowError,
350 "unsigned int is less than minimum");
351 return -1;
352 }
353 x = (unsigned long)y;
Tim Petersbb307342000-09-10 05:22:54 +0000354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000355 }
356 if (x > UINT_MAX) {
357 PyErr_SetString(PyExc_OverflowError,
358 "unsigned int is greater than maximum");
359 return -1;
360 }
Fred Drake541dc3b2000-06-28 17:49:30 +0000361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000362 if (i >= 0)
363 ((unsigned int *)ap->ob_item)[i] = (unsigned int)x;
364 return 0;
Guido van Rossum549ab711997-01-03 19:09:47 +0000365}
366
367static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000368l_getitem(arrayobject *ap, Py_ssize_t i)
Guido van Rossum778983b1993-02-19 15:55:02 +0000369{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000370 return PyLong_FromLong(((long *)ap->ob_item)[i]);
Guido van Rossum778983b1993-02-19 15:55:02 +0000371}
372
373static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000374l_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
Guido van Rossum778983b1993-02-19 15:55:02 +0000375{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000376 long x;
377 if (!PyArg_Parse(v, "l;array item must be integer", &x))
378 return -1;
379 if (i >= 0)
380 ((long *)ap->ob_item)[i] = x;
381 return 0;
Guido van Rossum778983b1993-02-19 15:55:02 +0000382}
383
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000384static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000385LL_getitem(arrayobject *ap, Py_ssize_t i)
Guido van Rossum549ab711997-01-03 19:09:47 +0000386{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000387 return PyLong_FromUnsignedLong(((unsigned long *)ap->ob_item)[i]);
Guido van Rossum549ab711997-01-03 19:09:47 +0000388}
389
390static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000391LL_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
Guido van Rossum549ab711997-01-03 19:09:47 +0000392{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000393 unsigned long x;
394 if (PyLong_Check(v)) {
395 x = PyLong_AsUnsignedLong(v);
396 if (x == (unsigned long) -1 && PyErr_Occurred())
397 return -1;
398 }
399 else {
400 long y;
401 if (!PyArg_Parse(v, "l;array item must be integer", &y))
402 return -1;
403 if (y < 0) {
404 PyErr_SetString(PyExc_OverflowError,
405 "unsigned long is less than minimum");
406 return -1;
407 }
408 x = (unsigned long)y;
Tim Petersbb307342000-09-10 05:22:54 +0000409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000410 }
411 if (x > ULONG_MAX) {
412 PyErr_SetString(PyExc_OverflowError,
413 "unsigned long is greater than maximum");
414 return -1;
415 }
Tim Petersbb307342000-09-10 05:22:54 +0000416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 if (i >= 0)
418 ((unsigned long *)ap->ob_item)[i] = x;
419 return 0;
Guido van Rossum549ab711997-01-03 19:09:47 +0000420}
421
Meador Inge1c9f0c92011-09-20 19:55:51 -0500422#ifdef HAVE_LONG_LONG
423
424static PyObject *
425q_getitem(arrayobject *ap, Py_ssize_t i)
426{
427 return PyLong_FromLongLong(((PY_LONG_LONG *)ap->ob_item)[i]);
428}
429
430static int
431q_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
432{
433 PY_LONG_LONG x;
434 if (!PyArg_Parse(v, "L;array item must be integer", &x))
435 return -1;
436 if (i >= 0)
437 ((PY_LONG_LONG *)ap->ob_item)[i] = x;
438 return 0;
439}
440
441static PyObject *
442QQ_getitem(arrayobject *ap, Py_ssize_t i)
443{
444 return PyLong_FromUnsignedLongLong(
445 ((unsigned PY_LONG_LONG *)ap->ob_item)[i]);
446}
447
448static int
449QQ_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
450{
451 unsigned PY_LONG_LONG x;
452 if (PyLong_Check(v)) {
453 x = PyLong_AsUnsignedLongLong(v);
454 if (x == (unsigned PY_LONG_LONG) -1 && PyErr_Occurred())
455 return -1;
456 }
457 else {
458 PY_LONG_LONG y;
459 if (!PyArg_Parse(v, "L;array item must be integer", &y))
460 return -1;
461 if (y < 0) {
462 PyErr_SetString(PyExc_OverflowError,
463 "unsigned long long is less than minimum");
464 return -1;
465 }
466 x = (unsigned PY_LONG_LONG)y;
467 }
468
469 if (i >= 0)
470 ((unsigned PY_LONG_LONG *)ap->ob_item)[i] = x;
471 return 0;
472}
473#endif
474
Guido van Rossum549ab711997-01-03 19:09:47 +0000475static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000476f_getitem(arrayobject *ap, Py_ssize_t i)
Guido van Rossum778983b1993-02-19 15:55:02 +0000477{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 return PyFloat_FromDouble((double) ((float *)ap->ob_item)[i]);
Guido van Rossum778983b1993-02-19 15:55:02 +0000479}
480
481static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000482f_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
Guido van Rossum778983b1993-02-19 15:55:02 +0000483{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 float x;
485 if (!PyArg_Parse(v, "f;array item must be float", &x))
486 return -1;
487 if (i >= 0)
488 ((float *)ap->ob_item)[i] = x;
489 return 0;
Guido van Rossum778983b1993-02-19 15:55:02 +0000490}
491
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000492static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000493d_getitem(arrayobject *ap, Py_ssize_t i)
Guido van Rossum778983b1993-02-19 15:55:02 +0000494{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000495 return PyFloat_FromDouble(((double *)ap->ob_item)[i]);
Guido van Rossum778983b1993-02-19 15:55:02 +0000496}
497
498static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000499d_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
Guido van Rossum778983b1993-02-19 15:55:02 +0000500{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 double x;
502 if (!PyArg_Parse(v, "d;array item must be float", &x))
503 return -1;
504 if (i >= 0)
505 ((double *)ap->ob_item)[i] = x;
506 return 0;
Guido van Rossum778983b1993-02-19 15:55:02 +0000507}
508
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000509
Alexandre Vassalottiad077152009-07-15 17:49:23 +0000510/* Description of types.
511 *
512 * Don't forget to update typecode_to_mformat_code() if you add a new
513 * typecode.
514 */
Guido van Rossum234f9421993-06-17 12:35:49 +0000515static struct arraydescr descriptors[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 {'b', 1, b_getitem, b_setitem, "b", 1, 1},
517 {'B', 1, BB_getitem, BB_setitem, "B", 1, 0},
Victor Stinner62bb3942012-08-06 00:46:05 +0200518 {'u', sizeof(Py_UNICODE), u_getitem, u_setitem, "u", 0, 0},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 {'h', sizeof(short), h_getitem, h_setitem, "h", 1, 1},
520 {'H', sizeof(short), HH_getitem, HH_setitem, "H", 1, 0},
521 {'i', sizeof(int), i_getitem, i_setitem, "i", 1, 1},
522 {'I', sizeof(int), II_getitem, II_setitem, "I", 1, 0},
523 {'l', sizeof(long), l_getitem, l_setitem, "l", 1, 1},
524 {'L', sizeof(long), LL_getitem, LL_setitem, "L", 1, 0},
Meador Inge1c9f0c92011-09-20 19:55:51 -0500525#ifdef HAVE_LONG_LONG
526 {'q', sizeof(PY_LONG_LONG), q_getitem, q_setitem, "q", 1, 1},
527 {'Q', sizeof(PY_LONG_LONG), QQ_getitem, QQ_setitem, "Q", 1, 0},
528#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000529 {'f', sizeof(float), f_getitem, f_setitem, "f", 0, 0},
530 {'d', sizeof(double), d_getitem, d_setitem, "d", 0, 0},
531 {'\0', 0, 0, 0, 0, 0, 0} /* Sentinel */
Guido van Rossum778983b1993-02-19 15:55:02 +0000532};
Tim Petersbb307342000-09-10 05:22:54 +0000533
534/****************************************************************************
535Implementations of array object methods.
536****************************************************************************/
Brett Cannon1eb32c22014-10-10 16:26:45 -0400537/*[clinic input]
538class array.array "arrayobject *" "&Arraytype"
539[clinic start generated code]*/
540/*[clinic end generated code: output=da39a3ee5e6b4b0d input=ad43d37e942a8854]*/
Guido van Rossum778983b1993-02-19 15:55:02 +0000541
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000542static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000543newarrayobject(PyTypeObject *type, Py_ssize_t size, struct arraydescr *descr)
Guido van Rossum778983b1993-02-19 15:55:02 +0000544{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000545 arrayobject *op;
546 size_t nbytes;
Martin v. Löwis99866332002-03-01 10:27:01 +0000547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000548 if (size < 0) {
549 PyErr_BadInternalCall();
550 return NULL;
551 }
Martin v. Löwis99866332002-03-01 10:27:01 +0000552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000553 /* Check for overflow */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +0100554 if (size > PY_SSIZE_T_MAX / descr->itemsize) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 return PyErr_NoMemory();
556 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +0100557 nbytes = size * descr->itemsize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000558 op = (arrayobject *) type->tp_alloc(type, 0);
559 if (op == NULL) {
560 return NULL;
561 }
562 op->ob_descr = descr;
563 op->allocated = size;
564 op->weakreflist = NULL;
565 Py_SIZE(op) = size;
566 if (size <= 0) {
567 op->ob_item = NULL;
568 }
569 else {
570 op->ob_item = PyMem_NEW(char, nbytes);
571 if (op->ob_item == NULL) {
572 Py_DECREF(op);
573 return PyErr_NoMemory();
574 }
575 }
576 op->ob_exports = 0;
577 return (PyObject *) op;
Guido van Rossum778983b1993-02-19 15:55:02 +0000578}
579
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000580static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000581getarrayitem(PyObject *op, Py_ssize_t i)
Guido van Rossum778983b1993-02-19 15:55:02 +0000582{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200583 arrayobject *ap;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000584 assert(array_Check(op));
585 ap = (arrayobject *)op;
586 assert(i>=0 && i<Py_SIZE(ap));
587 return (*ap->ob_descr->getitem)(ap, i);
Guido van Rossum778983b1993-02-19 15:55:02 +0000588}
589
590static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000591ins1(arrayobject *self, Py_ssize_t where, PyObject *v)
Guido van Rossum778983b1993-02-19 15:55:02 +0000592{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000593 char *items;
594 Py_ssize_t n = Py_SIZE(self);
595 if (v == NULL) {
596 PyErr_BadInternalCall();
597 return -1;
598 }
599 if ((*self->ob_descr->setitem)(self, -1, v) < 0)
600 return -1;
Raymond Hettinger6e2ee862004-03-14 04:37:50 +0000601
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000602 if (array_resize(self, n+1) == -1)
603 return -1;
604 items = self->ob_item;
605 if (where < 0) {
606 where += n;
607 if (where < 0)
608 where = 0;
609 }
610 if (where > n)
611 where = n;
612 /* appends don't need to call memmove() */
613 if (where != n)
614 memmove(items + (where+1)*self->ob_descr->itemsize,
615 items + where*self->ob_descr->itemsize,
616 (n-where)*self->ob_descr->itemsize);
617 return (*self->ob_descr->setitem)(self, where, v);
Guido van Rossum778983b1993-02-19 15:55:02 +0000618}
619
Guido van Rossum778983b1993-02-19 15:55:02 +0000620/* Methods */
621
622static void
Peter Schneider-Kamp9656abd2000-07-13 21:10:57 +0000623array_dealloc(arrayobject *op)
Guido van Rossum778983b1993-02-19 15:55:02 +0000624{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000625 if (op->weakreflist != NULL)
626 PyObject_ClearWeakRefs((PyObject *) op);
627 if (op->ob_item != NULL)
628 PyMem_DEL(op->ob_item);
629 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossum778983b1993-02-19 15:55:02 +0000630}
631
Guido van Rossum9d19cb82001-01-18 01:02:55 +0000632static PyObject *
633array_richcompare(PyObject *v, PyObject *w, int op)
Guido van Rossum778983b1993-02-19 15:55:02 +0000634{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000635 arrayobject *va, *wa;
636 PyObject *vi = NULL;
637 PyObject *wi = NULL;
638 Py_ssize_t i, k;
639 PyObject *res;
Guido van Rossum9d19cb82001-01-18 01:02:55 +0000640
Brian Curtindfc80e32011-08-10 20:28:54 -0500641 if (!array_Check(v) || !array_Check(w))
642 Py_RETURN_NOTIMPLEMENTED;
Guido van Rossum9d19cb82001-01-18 01:02:55 +0000643
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 va = (arrayobject *)v;
645 wa = (arrayobject *)w;
Guido van Rossum9d19cb82001-01-18 01:02:55 +0000646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 if (Py_SIZE(va) != Py_SIZE(wa) && (op == Py_EQ || op == Py_NE)) {
648 /* Shortcut: if the lengths differ, the arrays differ */
649 if (op == Py_EQ)
650 res = Py_False;
651 else
652 res = Py_True;
653 Py_INCREF(res);
654 return res;
655 }
Guido van Rossum9d19cb82001-01-18 01:02:55 +0000656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000657 /* Search for the first index where items are different */
658 k = 1;
659 for (i = 0; i < Py_SIZE(va) && i < Py_SIZE(wa); i++) {
660 vi = getarrayitem(v, i);
661 wi = getarrayitem(w, i);
662 if (vi == NULL || wi == NULL) {
663 Py_XDECREF(vi);
664 Py_XDECREF(wi);
665 return NULL;
666 }
667 k = PyObject_RichCompareBool(vi, wi, Py_EQ);
668 if (k == 0)
669 break; /* Keeping vi and wi alive! */
670 Py_DECREF(vi);
671 Py_DECREF(wi);
672 if (k < 0)
673 return NULL;
674 }
Guido van Rossum9d19cb82001-01-18 01:02:55 +0000675
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 if (k) {
677 /* No more items to compare -- compare sizes */
678 Py_ssize_t vs = Py_SIZE(va);
679 Py_ssize_t ws = Py_SIZE(wa);
680 int cmp;
681 switch (op) {
682 case Py_LT: cmp = vs < ws; break;
683 case Py_LE: cmp = vs <= ws; break;
684 case Py_EQ: cmp = vs == ws; break;
685 case Py_NE: cmp = vs != ws; break;
686 case Py_GT: cmp = vs > ws; break;
687 case Py_GE: cmp = vs >= ws; break;
688 default: return NULL; /* cannot happen */
689 }
690 if (cmp)
691 res = Py_True;
692 else
693 res = Py_False;
694 Py_INCREF(res);
695 return res;
696 }
Guido van Rossum9d19cb82001-01-18 01:02:55 +0000697
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000698 /* We have an item that differs. First, shortcuts for EQ/NE */
699 if (op == Py_EQ) {
700 Py_INCREF(Py_False);
701 res = Py_False;
702 }
703 else if (op == Py_NE) {
704 Py_INCREF(Py_True);
705 res = Py_True;
706 }
707 else {
708 /* Compare the final item again using the proper operator */
709 res = PyObject_RichCompare(vi, wi, op);
710 }
711 Py_DECREF(vi);
712 Py_DECREF(wi);
713 return res;
Guido van Rossum778983b1993-02-19 15:55:02 +0000714}
715
Martin v. Löwis18e16552006-02-15 17:27:45 +0000716static Py_ssize_t
Peter Schneider-Kamp9656abd2000-07-13 21:10:57 +0000717array_length(arrayobject *a)
Guido van Rossum778983b1993-02-19 15:55:02 +0000718{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000719 return Py_SIZE(a);
Guido van Rossum778983b1993-02-19 15:55:02 +0000720}
721
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000722static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000723array_item(arrayobject *a, Py_ssize_t i)
Guido van Rossum778983b1993-02-19 15:55:02 +0000724{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000725 if (i < 0 || i >= Py_SIZE(a)) {
726 PyErr_SetString(PyExc_IndexError, "array index out of range");
727 return NULL;
728 }
729 return getarrayitem((PyObject *)a, i);
Guido van Rossum778983b1993-02-19 15:55:02 +0000730}
731
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000732static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000733array_slice(arrayobject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum778983b1993-02-19 15:55:02 +0000734{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000735 arrayobject *np;
736 if (ilow < 0)
737 ilow = 0;
738 else if (ilow > Py_SIZE(a))
739 ilow = Py_SIZE(a);
740 if (ihigh < 0)
741 ihigh = 0;
742 if (ihigh < ilow)
743 ihigh = ilow;
744 else if (ihigh > Py_SIZE(a))
745 ihigh = Py_SIZE(a);
746 np = (arrayobject *) newarrayobject(&Arraytype, ihigh - ilow, a->ob_descr);
747 if (np == NULL)
748 return NULL;
749 memcpy(np->ob_item, a->ob_item + ilow * a->ob_descr->itemsize,
750 (ihigh-ilow) * a->ob_descr->itemsize);
751 return (PyObject *)np;
Guido van Rossum778983b1993-02-19 15:55:02 +0000752}
753
Brett Cannon1eb32c22014-10-10 16:26:45 -0400754
755/*[clinic input]
756array.array.__copy__
757
758Return a copy of the array.
759[clinic start generated code]*/
760
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000761static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -0400762array_array___copy___impl(arrayobject *self)
763/*[clinic end generated code: output=dec7c3f925d9619e input=ad1ee5b086965f09]*/
Raymond Hettinger3aa82c02004-03-13 18:18:51 +0000764{
Brett Cannon1eb32c22014-10-10 16:26:45 -0400765 return array_slice(self, 0, Py_SIZE(self));
Raymond Hettinger3aa82c02004-03-13 18:18:51 +0000766}
767
Brett Cannon1eb32c22014-10-10 16:26:45 -0400768/*[clinic input]
769array.array.__deepcopy__
770
771 unused: object
772 /
773
774Return a copy of the array.
775[clinic start generated code]*/
776
777static PyObject *
778array_array___deepcopy__(arrayobject *self, PyObject *unused)
779/*[clinic end generated code: output=1ec748d8e14a9faa input=2405ecb4933748c4]*/
780{
781 return array_array___copy___impl(self);
782}
Raymond Hettinger3aa82c02004-03-13 18:18:51 +0000783
784static PyObject *
Peter Schneider-Kamp9656abd2000-07-13 21:10:57 +0000785array_concat(arrayobject *a, PyObject *bb)
Guido van Rossum778983b1993-02-19 15:55:02 +0000786{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 Py_ssize_t size;
788 arrayobject *np;
789 if (!array_Check(bb)) {
790 PyErr_Format(PyExc_TypeError,
791 "can only append array (not \"%.200s\") to array",
792 Py_TYPE(bb)->tp_name);
793 return NULL;
794 }
Guido van Rossum778983b1993-02-19 15:55:02 +0000795#define b ((arrayobject *)bb)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 if (a->ob_descr != b->ob_descr) {
797 PyErr_BadArgument();
798 return NULL;
799 }
800 if (Py_SIZE(a) > PY_SSIZE_T_MAX - Py_SIZE(b)) {
801 return PyErr_NoMemory();
802 }
803 size = Py_SIZE(a) + Py_SIZE(b);
804 np = (arrayobject *) newarrayobject(&Arraytype, size, a->ob_descr);
805 if (np == NULL) {
806 return NULL;
807 }
808 memcpy(np->ob_item, a->ob_item, Py_SIZE(a)*a->ob_descr->itemsize);
809 memcpy(np->ob_item + Py_SIZE(a)*a->ob_descr->itemsize,
810 b->ob_item, Py_SIZE(b)*b->ob_descr->itemsize);
811 return (PyObject *)np;
Guido van Rossum778983b1993-02-19 15:55:02 +0000812#undef b
813}
814
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000815static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000816array_repeat(arrayobject *a, Py_ssize_t n)
Guido van Rossum778983b1993-02-19 15:55:02 +0000817{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000818 Py_ssize_t size;
819 arrayobject *np;
Georg Brandlc29cc6a2010-12-04 11:02:04 +0000820 Py_ssize_t oldbytes, newbytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000821 if (n < 0)
822 n = 0;
823 if ((Py_SIZE(a) != 0) && (n > PY_SSIZE_T_MAX / Py_SIZE(a))) {
824 return PyErr_NoMemory();
825 }
826 size = Py_SIZE(a) * n;
827 np = (arrayobject *) newarrayobject(&Arraytype, size, a->ob_descr);
828 if (np == NULL)
829 return NULL;
Georg Brandlc29cc6a2010-12-04 11:02:04 +0000830 if (n == 0)
831 return (PyObject *)np;
832 oldbytes = Py_SIZE(a) * a->ob_descr->itemsize;
833 newbytes = oldbytes * n;
834 /* this follows the code in unicode_repeat */
835 if (oldbytes == 1) {
836 memset(np->ob_item, a->ob_item[0], newbytes);
837 } else {
838 Py_ssize_t done = oldbytes;
839 Py_MEMCPY(np->ob_item, a->ob_item, oldbytes);
840 while (done < newbytes) {
841 Py_ssize_t ncopy = (done <= newbytes-done) ? done : newbytes-done;
842 Py_MEMCPY(np->ob_item+done, np->ob_item, ncopy);
843 done += ncopy;
844 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000845 }
Georg Brandlc29cc6a2010-12-04 11:02:04 +0000846 return (PyObject *)np;
Guido van Rossum778983b1993-02-19 15:55:02 +0000847}
848
849static int
Martin v. Löwisad0a4622006-02-16 14:30:23 +0000850array_ass_slice(arrayobject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum778983b1993-02-19 15:55:02 +0000851{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000852 char *item;
853 Py_ssize_t n; /* Size of replacement array */
854 Py_ssize_t d; /* Change in size */
Guido van Rossum778983b1993-02-19 15:55:02 +0000855#define b ((arrayobject *)v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000856 if (v == NULL)
857 n = 0;
858 else if (array_Check(v)) {
859 n = Py_SIZE(b);
860 if (a == b) {
861 /* Special case "a[i:j] = a" -- copy b first */
862 int ret;
863 v = array_slice(b, 0, n);
864 if (!v)
865 return -1;
866 ret = array_ass_slice(a, ilow, ihigh, v);
867 Py_DECREF(v);
868 return ret;
869 }
870 if (b->ob_descr != a->ob_descr) {
871 PyErr_BadArgument();
872 return -1;
873 }
874 }
875 else {
876 PyErr_Format(PyExc_TypeError,
877 "can only assign array (not \"%.200s\") to array slice",
878 Py_TYPE(v)->tp_name);
879 return -1;
880 }
881 if (ilow < 0)
882 ilow = 0;
883 else if (ilow > Py_SIZE(a))
884 ilow = Py_SIZE(a);
885 if (ihigh < 0)
886 ihigh = 0;
887 if (ihigh < ilow)
888 ihigh = ilow;
889 else if (ihigh > Py_SIZE(a))
890 ihigh = Py_SIZE(a);
891 item = a->ob_item;
892 d = n - (ihigh-ilow);
893 /* Issue #4509: If the array has exported buffers and the slice
894 assignment would change the size of the array, fail early to make
895 sure we don't modify it. */
896 if (d != 0 && a->ob_exports > 0) {
897 PyErr_SetString(PyExc_BufferError,
898 "cannot resize an array that is exporting buffers");
899 return -1;
900 }
901 if (d < 0) { /* Delete -d items */
902 memmove(item + (ihigh+d)*a->ob_descr->itemsize,
903 item + ihigh*a->ob_descr->itemsize,
904 (Py_SIZE(a)-ihigh)*a->ob_descr->itemsize);
905 if (array_resize(a, Py_SIZE(a) + d) == -1)
906 return -1;
907 }
908 else if (d > 0) { /* Insert d items */
909 if (array_resize(a, Py_SIZE(a) + d))
910 return -1;
911 memmove(item + (ihigh+d)*a->ob_descr->itemsize,
912 item + ihigh*a->ob_descr->itemsize,
913 (Py_SIZE(a)-ihigh)*a->ob_descr->itemsize);
914 }
915 if (n > 0)
916 memcpy(item + ilow*a->ob_descr->itemsize, b->ob_item,
917 n*b->ob_descr->itemsize);
918 return 0;
Guido van Rossum778983b1993-02-19 15:55:02 +0000919#undef b
920}
921
922static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000923array_ass_item(arrayobject *a, Py_ssize_t i, PyObject *v)
Guido van Rossum778983b1993-02-19 15:55:02 +0000924{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000925 if (i < 0 || i >= Py_SIZE(a)) {
926 PyErr_SetString(PyExc_IndexError,
927 "array assignment index out of range");
928 return -1;
929 }
930 if (v == NULL)
931 return array_ass_slice(a, i, i+1, v);
932 return (*a->ob_descr->setitem)(a, i, v);
Guido van Rossum778983b1993-02-19 15:55:02 +0000933}
934
935static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000936setarrayitem(PyObject *a, Py_ssize_t i, PyObject *v)
Guido van Rossum778983b1993-02-19 15:55:02 +0000937{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 assert(array_Check(a));
939 return array_ass_item((arrayobject *)a, i, v);
Guido van Rossum778983b1993-02-19 15:55:02 +0000940}
941
Martin v. Löwis99866332002-03-01 10:27:01 +0000942static int
Raymond Hettinger49f9bd12004-03-14 05:43:59 +0000943array_iter_extend(arrayobject *self, PyObject *bb)
944{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000945 PyObject *it, *v;
Raymond Hettinger49f9bd12004-03-14 05:43:59 +0000946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 it = PyObject_GetIter(bb);
948 if (it == NULL)
949 return -1;
Raymond Hettinger49f9bd12004-03-14 05:43:59 +0000950
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 while ((v = PyIter_Next(it)) != NULL) {
Mark Dickinson346f0af2010-08-06 09:36:57 +0000952 if (ins1(self, Py_SIZE(self), v) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 Py_DECREF(v);
954 Py_DECREF(it);
955 return -1;
956 }
957 Py_DECREF(v);
958 }
959 Py_DECREF(it);
960 if (PyErr_Occurred())
961 return -1;
962 return 0;
Raymond Hettinger49f9bd12004-03-14 05:43:59 +0000963}
964
965static int
Martin v. Löwis99866332002-03-01 10:27:01 +0000966array_do_extend(arrayobject *self, PyObject *bb)
967{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000968 Py_ssize_t size, oldsize, bbsize;
Martin v. Löwis99866332002-03-01 10:27:01 +0000969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000970 if (!array_Check(bb))
971 return array_iter_extend(self, bb);
972#define b ((arrayobject *)bb)
973 if (self->ob_descr != b->ob_descr) {
974 PyErr_SetString(PyExc_TypeError,
975 "can only extend with array of same kind");
976 return -1;
977 }
978 if ((Py_SIZE(self) > PY_SSIZE_T_MAX - Py_SIZE(b)) ||
979 ((Py_SIZE(self) + Py_SIZE(b)) > PY_SSIZE_T_MAX / self->ob_descr->itemsize)) {
980 PyErr_NoMemory();
981 return -1;
982 }
983 oldsize = Py_SIZE(self);
984 /* Get the size of bb before resizing the array since bb could be self. */
985 bbsize = Py_SIZE(bb);
986 size = oldsize + Py_SIZE(b);
987 if (array_resize(self, size) == -1)
988 return -1;
989 memcpy(self->ob_item + oldsize * self->ob_descr->itemsize,
990 b->ob_item, bbsize * b->ob_descr->itemsize);
991
992 return 0;
Martin v. Löwis99866332002-03-01 10:27:01 +0000993#undef b
994}
995
996static PyObject *
997array_inplace_concat(arrayobject *self, PyObject *bb)
998{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 if (!array_Check(bb)) {
1000 PyErr_Format(PyExc_TypeError,
1001 "can only extend array with array (not \"%.200s\")",
1002 Py_TYPE(bb)->tp_name);
1003 return NULL;
1004 }
1005 if (array_do_extend(self, bb) == -1)
1006 return NULL;
1007 Py_INCREF(self);
1008 return (PyObject *)self;
Martin v. Löwis99866332002-03-01 10:27:01 +00001009}
1010
1011static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001012array_inplace_repeat(arrayobject *self, Py_ssize_t n)
Martin v. Löwis99866332002-03-01 10:27:01 +00001013{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 char *items, *p;
1015 Py_ssize_t size, i;
Martin v. Löwis99866332002-03-01 10:27:01 +00001016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 if (Py_SIZE(self) > 0) {
1018 if (n < 0)
1019 n = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 if ((self->ob_descr->itemsize != 0) &&
1021 (Py_SIZE(self) > PY_SSIZE_T_MAX / self->ob_descr->itemsize)) {
1022 return PyErr_NoMemory();
1023 }
1024 size = Py_SIZE(self) * self->ob_descr->itemsize;
1025 if (n > 0 && size > PY_SSIZE_T_MAX / n) {
1026 return PyErr_NoMemory();
1027 }
1028 if (array_resize(self, n * Py_SIZE(self)) == -1)
1029 return NULL;
1030 items = p = self->ob_item;
1031 for (i = 1; i < n; i++) {
1032 p += size;
1033 memcpy(p, items, size);
1034 }
1035 }
1036 Py_INCREF(self);
1037 return (PyObject *)self;
Martin v. Löwis99866332002-03-01 10:27:01 +00001038}
1039
1040
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001041static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001042ins(arrayobject *self, Py_ssize_t where, PyObject *v)
Guido van Rossum778983b1993-02-19 15:55:02 +00001043{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 if (ins1(self, where, v) != 0)
1045 return NULL;
1046 Py_INCREF(Py_None);
1047 return Py_None;
Guido van Rossum778983b1993-02-19 15:55:02 +00001048}
1049
Brett Cannon1eb32c22014-10-10 16:26:45 -04001050/*[clinic input]
1051array.array.count
1052
1053 v: object
1054 /
1055
1056Return number of occurrences of v in the array.
1057[clinic start generated code]*/
1058
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001059static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001060array_array_count(arrayobject *self, PyObject *v)
1061/*[clinic end generated code: output=3dd3624bf7135a3a input=d9bce9d65e39d1f5]*/
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001062{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001063 Py_ssize_t count = 0;
1064 Py_ssize_t i;
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001066 for (i = 0; i < Py_SIZE(self); i++) {
Victor Stinner0b142e22013-07-17 23:01:30 +02001067 PyObject *selfi;
1068 int cmp;
1069
1070 selfi = getarrayitem((PyObject *)self, i);
1071 if (selfi == NULL)
1072 return NULL;
1073 cmp = PyObject_RichCompareBool(selfi, v, Py_EQ);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001074 Py_DECREF(selfi);
1075 if (cmp > 0)
1076 count++;
1077 else if (cmp < 0)
1078 return NULL;
1079 }
1080 return PyLong_FromSsize_t(count);
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001081}
1082
Brett Cannon1eb32c22014-10-10 16:26:45 -04001083
1084/*[clinic input]
1085array.array.index
1086
1087 v: object
1088 /
1089
1090Return index of first occurrence of v in the array.
1091[clinic start generated code]*/
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001092
1093static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001094array_array_index(arrayobject *self, PyObject *v)
1095/*[clinic end generated code: output=d48498d325602167 input=cf619898c6649d08]*/
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001096{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097 Py_ssize_t i;
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001099 for (i = 0; i < Py_SIZE(self); i++) {
Victor Stinner0b142e22013-07-17 23:01:30 +02001100 PyObject *selfi;
1101 int cmp;
1102
1103 selfi = getarrayitem((PyObject *)self, i);
1104 if (selfi == NULL)
1105 return NULL;
1106 cmp = PyObject_RichCompareBool(selfi, v, Py_EQ);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001107 Py_DECREF(selfi);
1108 if (cmp > 0) {
1109 return PyLong_FromLong((long)i);
1110 }
1111 else if (cmp < 0)
1112 return NULL;
1113 }
1114 PyErr_SetString(PyExc_ValueError, "array.index(x): x not in list");
1115 return NULL;
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001116}
1117
Raymond Hettinger625812f2003-01-07 01:58:52 +00001118static int
1119array_contains(arrayobject *self, PyObject *v)
1120{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001121 Py_ssize_t i;
1122 int cmp;
Raymond Hettinger625812f2003-01-07 01:58:52 +00001123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001124 for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(self); i++) {
1125 PyObject *selfi = getarrayitem((PyObject *)self, i);
Victor Stinner0b142e22013-07-17 23:01:30 +02001126 if (selfi == NULL)
Victor Stinner4755bea2013-07-18 01:12:35 +02001127 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001128 cmp = PyObject_RichCompareBool(selfi, v, Py_EQ);
1129 Py_DECREF(selfi);
1130 }
1131 return cmp;
Raymond Hettinger625812f2003-01-07 01:58:52 +00001132}
1133
Brett Cannon1eb32c22014-10-10 16:26:45 -04001134/*[clinic input]
1135array.array.remove
1136
1137 v: object
1138 /
1139
1140Remove the first occurrence of v in the array.
1141[clinic start generated code]*/
1142
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001143static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001144array_array_remove(arrayobject *self, PyObject *v)
1145/*[clinic end generated code: output=bef06be9fdf9dceb input=0b1e5aed25590027]*/
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001146{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001147 int i;
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001148
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001149 for (i = 0; i < Py_SIZE(self); i++) {
Victor Stinner0b142e22013-07-17 23:01:30 +02001150 PyObject *selfi;
1151 int cmp;
1152
1153 selfi = getarrayitem((PyObject *)self,i);
1154 if (selfi == NULL)
1155 return NULL;
1156 cmp = PyObject_RichCompareBool(selfi, v, Py_EQ);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001157 Py_DECREF(selfi);
1158 if (cmp > 0) {
1159 if (array_ass_slice(self, i, i+1,
1160 (PyObject *)NULL) != 0)
1161 return NULL;
1162 Py_INCREF(Py_None);
1163 return Py_None;
1164 }
1165 else if (cmp < 0)
1166 return NULL;
1167 }
1168 PyErr_SetString(PyExc_ValueError, "array.remove(x): x not in list");
1169 return NULL;
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001170}
1171
Brett Cannon1eb32c22014-10-10 16:26:45 -04001172/*[clinic input]
1173array.array.pop
1174
1175 i: Py_ssize_t = -1
1176 /
1177
1178Return the i-th element and delete it from the array.
1179
1180i defaults to -1.
1181[clinic start generated code]*/
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001182
1183static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001184array_array_pop_impl(arrayobject *self, Py_ssize_t i)
1185/*[clinic end generated code: output=bc1f0c54fe5308e4 input=8e5feb4c1a11cd44]*/
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001186{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001187 PyObject *v;
Brett Cannon1eb32c22014-10-10 16:26:45 -04001188
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001189 if (Py_SIZE(self) == 0) {
1190 /* Special-case most common failure cause */
1191 PyErr_SetString(PyExc_IndexError, "pop from empty array");
1192 return NULL;
1193 }
1194 if (i < 0)
1195 i += Py_SIZE(self);
1196 if (i < 0 || i >= Py_SIZE(self)) {
1197 PyErr_SetString(PyExc_IndexError, "pop index out of range");
1198 return NULL;
1199 }
Victor Stinner0b142e22013-07-17 23:01:30 +02001200 v = getarrayitem((PyObject *)self, i);
1201 if (v == NULL)
1202 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001203 if (array_ass_slice(self, i, i+1, (PyObject *)NULL) != 0) {
1204 Py_DECREF(v);
1205 return NULL;
1206 }
1207 return v;
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001208}
1209
Brett Cannon1eb32c22014-10-10 16:26:45 -04001210/*[clinic input]
1211array.array.extend
1212
1213 bb: object
1214 /
1215
1216Append items to the end of the array.
1217[clinic start generated code]*/
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001218
1219static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001220array_array_extend(arrayobject *self, PyObject *bb)
1221/*[clinic end generated code: output=bbddbc8e8bef871d input=43be86aba5c31e44]*/
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001222{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001223 if (array_do_extend(self, bb) == -1)
1224 return NULL;
1225 Py_INCREF(Py_None);
1226 return Py_None;
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001227}
1228
Brett Cannon1eb32c22014-10-10 16:26:45 -04001229/*[clinic input]
1230array.array.insert
1231
1232 i: Py_ssize_t
1233 v: object
1234 /
1235
1236Insert a new item v into the array before position i.
1237[clinic start generated code]*/
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001238
1239static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001240array_array_insert_impl(arrayobject *self, Py_ssize_t i, PyObject *v)
1241/*[clinic end generated code: output=5a3648e278348564 input=5577d1b4383e9313]*/
Guido van Rossum778983b1993-02-19 15:55:02 +00001242{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001243 return ins(self, i, v);
Guido van Rossum778983b1993-02-19 15:55:02 +00001244}
1245
Brett Cannon1eb32c22014-10-10 16:26:45 -04001246/*[clinic input]
1247array.array.buffer_info
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001248
Brett Cannon1eb32c22014-10-10 16:26:45 -04001249Return a tuple (address, length) giving the current memory address and the length in items of the buffer used to hold array's contents.
1250
1251The length should be multiplied by the itemsize attribute to calculate
1252the buffer length in bytes.
1253[clinic start generated code]*/
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001254
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001255static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001256array_array_buffer_info_impl(arrayobject *self)
1257/*[clinic end generated code: output=9b2a4ec3ae7e98e7 input=a58bae5c6e1ac6a6]*/
Guido van Rossumde4a4ca1997-08-12 14:55:56 +00001258{
Victor Stinner541067a2013-11-14 01:27:12 +01001259 PyObject *retval = NULL, *v;
1260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001261 retval = PyTuple_New(2);
1262 if (!retval)
1263 return NULL;
Fred Drake541dc3b2000-06-28 17:49:30 +00001264
Victor Stinner541067a2013-11-14 01:27:12 +01001265 v = PyLong_FromVoidPtr(self->ob_item);
1266 if (v == NULL) {
1267 Py_DECREF(retval);
1268 return NULL;
1269 }
1270 PyTuple_SET_ITEM(retval, 0, v);
1271
1272 v = PyLong_FromLong((long)(Py_SIZE(self)));
1273 if (v == NULL) {
1274 Py_DECREF(retval);
1275 return NULL;
1276 }
1277 PyTuple_SET_ITEM(retval, 1, v);
Fred Drake541dc3b2000-06-28 17:49:30 +00001278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001279 return retval;
Guido van Rossumde4a4ca1997-08-12 14:55:56 +00001280}
1281
Brett Cannon1eb32c22014-10-10 16:26:45 -04001282/*[clinic input]
1283array.array.append
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001284
Brett Cannon1eb32c22014-10-10 16:26:45 -04001285 v: object
1286 /
1287
1288Append new value v to the end of the array.
1289[clinic start generated code]*/
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001290
Guido van Rossumde4a4ca1997-08-12 14:55:56 +00001291static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001292array_array_append(arrayobject *self, PyObject *v)
1293/*[clinic end generated code: output=745a0669bf8db0e2 input=0b98d9d78e78f0fa]*/
Guido van Rossum778983b1993-02-19 15:55:02 +00001294{
Mark Dickinson346f0af2010-08-06 09:36:57 +00001295 return ins(self, Py_SIZE(self), v);
Guido van Rossum778983b1993-02-19 15:55:02 +00001296}
1297
Brett Cannon1eb32c22014-10-10 16:26:45 -04001298/*[clinic input]
1299array.array.byteswap
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001300
Brett Cannon1eb32c22014-10-10 16:26:45 -04001301Byteswap all items of the array.
1302
1303If the items in the array are not 1, 2, 4, or 8 bytes in size, RuntimeError is
1304raised.
1305[clinic start generated code]*/
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001306
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001307static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001308array_array_byteswap_impl(arrayobject *self)
1309/*[clinic end generated code: output=5f8236cbdf0d90b5 input=6a85591b950a0186]*/
Guido van Rossum778983b1993-02-19 15:55:02 +00001310{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001311 char *p;
1312 Py_ssize_t i;
Fred Drakebf272981999-12-03 17:15:30 +00001313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001314 switch (self->ob_descr->itemsize) {
1315 case 1:
1316 break;
1317 case 2:
1318 for (p = self->ob_item, i = Py_SIZE(self); --i >= 0; p += 2) {
1319 char p0 = p[0];
1320 p[0] = p[1];
1321 p[1] = p0;
1322 }
1323 break;
1324 case 4:
1325 for (p = self->ob_item, i = Py_SIZE(self); --i >= 0; p += 4) {
1326 char p0 = p[0];
1327 char p1 = p[1];
1328 p[0] = p[3];
1329 p[1] = p[2];
1330 p[2] = p1;
1331 p[3] = p0;
1332 }
1333 break;
1334 case 8:
1335 for (p = self->ob_item, i = Py_SIZE(self); --i >= 0; p += 8) {
1336 char p0 = p[0];
1337 char p1 = p[1];
1338 char p2 = p[2];
1339 char p3 = p[3];
1340 p[0] = p[7];
1341 p[1] = p[6];
1342 p[2] = p[5];
1343 p[3] = p[4];
1344 p[4] = p3;
1345 p[5] = p2;
1346 p[6] = p1;
1347 p[7] = p0;
1348 }
1349 break;
1350 default:
1351 PyErr_SetString(PyExc_RuntimeError,
1352 "don't know how to byteswap this array type");
1353 return NULL;
1354 }
1355 Py_INCREF(Py_None);
1356 return Py_None;
Guido van Rossum778983b1993-02-19 15:55:02 +00001357}
1358
Brett Cannon1eb32c22014-10-10 16:26:45 -04001359/*[clinic input]
1360array.array.reverse
1361
1362Reverse the order of the items in the array.
1363[clinic start generated code]*/
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001364
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001365static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001366array_array_reverse_impl(arrayobject *self)
1367/*[clinic end generated code: output=c04868b36f6f4089 input=cd904f01b27d966a]*/
Guido van Rossum778983b1993-02-19 15:55:02 +00001368{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001369 Py_ssize_t itemsize = self->ob_descr->itemsize;
1370 char *p, *q;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001371 /* little buffer to hold items while swapping */
1372 char tmp[256]; /* 8 is probably enough -- but why skimp */
1373 assert((size_t)itemsize <= sizeof(tmp));
Guido van Rossume77a7571993-11-03 15:01:26 +00001374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001375 if (Py_SIZE(self) > 1) {
1376 for (p = self->ob_item,
1377 q = self->ob_item + (Py_SIZE(self) - 1)*itemsize;
1378 p < q;
1379 p += itemsize, q -= itemsize) {
1380 /* memory areas guaranteed disjoint, so memcpy
1381 * is safe (& memmove may be slower).
1382 */
1383 memcpy(tmp, p, itemsize);
1384 memcpy(p, q, itemsize);
1385 memcpy(q, tmp, itemsize);
1386 }
1387 }
Tim Petersbb307342000-09-10 05:22:54 +00001388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001389 Py_INCREF(Py_None);
1390 return Py_None;
Guido van Rossum778983b1993-02-19 15:55:02 +00001391}
Guido van Rossume77a7571993-11-03 15:01:26 +00001392
Brett Cannon1eb32c22014-10-10 16:26:45 -04001393/*[clinic input]
1394array.array.fromfile
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001395
Brett Cannon1eb32c22014-10-10 16:26:45 -04001396 f: object
1397 n: Py_ssize_t
1398 /
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001399
Brett Cannon1eb32c22014-10-10 16:26:45 -04001400Read n objects from the file object f and append them to the end of the array.
1401[clinic start generated code]*/
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001402
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001403static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001404array_array_fromfile_impl(arrayobject *self, PyObject *f, Py_ssize_t n)
1405/*[clinic end generated code: output=ec9f600e10f53510 input=e188afe8e58adf40]*/
Guido van Rossum778983b1993-02-19 15:55:02 +00001406{
Brett Cannon1eb32c22014-10-10 16:26:45 -04001407 PyObject *args, *b, *res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001408 Py_ssize_t itemsize = self->ob_descr->itemsize;
Brett Cannon1eb32c22014-10-10 16:26:45 -04001409 Py_ssize_t nbytes;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001410 _Py_IDENTIFIER(read);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001411 int not_enough_bytes;
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001412
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01001413 if (n < 0) {
1414 PyErr_SetString(PyExc_ValueError, "negative count");
1415 return NULL;
1416 }
1417 if (n > PY_SSIZE_T_MAX / itemsize) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001418 PyErr_NoMemory();
1419 return NULL;
1420 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01001421 nbytes = n * itemsize;
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001422
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001423 b = _PyObject_CallMethodId(f, &PyId_read, "n", nbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001424 if (b == NULL)
1425 return NULL;
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001426
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001427 if (!PyBytes_Check(b)) {
1428 PyErr_SetString(PyExc_TypeError,
1429 "read() didn't return bytes");
1430 Py_DECREF(b);
1431 return NULL;
1432 }
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001434 not_enough_bytes = (PyBytes_GET_SIZE(b) != nbytes);
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001436 args = Py_BuildValue("(O)", b);
1437 Py_DECREF(b);
1438 if (args == NULL)
1439 return NULL;
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001440
Brett Cannon1eb32c22014-10-10 16:26:45 -04001441 res = array_array_frombytes(self, args);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001442 Py_DECREF(args);
1443 if (res == NULL)
1444 return NULL;
Hirokazu Yamamoto54d0df62009-03-06 03:04:07 +00001445
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001446 if (not_enough_bytes) {
1447 PyErr_SetString(PyExc_EOFError,
1448 "read() didn't return enough bytes");
1449 Py_DECREF(res);
1450 return NULL;
1451 }
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001453 return res;
Guido van Rossum778983b1993-02-19 15:55:02 +00001454}
1455
Brett Cannon1eb32c22014-10-10 16:26:45 -04001456/*[clinic input]
1457array.array.tofile
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001458
Brett Cannon1eb32c22014-10-10 16:26:45 -04001459 f: object
1460 /
1461
1462Write all items (as machine values) to the file object f.
1463[clinic start generated code]*/
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001464
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001465static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001466array_array_tofile(arrayobject *self, PyObject *f)
1467/*[clinic end generated code: output=3a2cfa8128df0777 input=b0669a484aab0831]*/
Guido van Rossum778983b1993-02-19 15:55:02 +00001468{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001469 Py_ssize_t nbytes = Py_SIZE(self) * self->ob_descr->itemsize;
1470 /* Write 64K blocks at a time */
1471 /* XXX Make the block size settable */
1472 int BLOCKSIZE = 64*1024;
1473 Py_ssize_t nblocks = (nbytes + BLOCKSIZE - 1) / BLOCKSIZE;
1474 Py_ssize_t i;
Raymond Hettinger36cd2bf2003-01-03 08:24:58 +00001475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001476 if (Py_SIZE(self) == 0)
1477 goto done;
Guido van Rossumb5ddcfd2007-04-11 17:08:28 +00001478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001479 for (i = 0; i < nblocks; i++) {
1480 char* ptr = self->ob_item + i*BLOCKSIZE;
1481 Py_ssize_t size = BLOCKSIZE;
1482 PyObject *bytes, *res;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001483 _Py_IDENTIFIER(write);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001485 if (i*BLOCKSIZE + size > nbytes)
1486 size = nbytes - i*BLOCKSIZE;
1487 bytes = PyBytes_FromStringAndSize(ptr, size);
1488 if (bytes == NULL)
1489 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001490 res = _PyObject_CallMethodId(f, &PyId_write, "O", bytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001491 Py_DECREF(bytes);
1492 if (res == NULL)
1493 return NULL;
1494 Py_DECREF(res); /* drop write result */
1495 }
Guido van Rossumb5ddcfd2007-04-11 17:08:28 +00001496
1497 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001498 Py_INCREF(Py_None);
1499 return Py_None;
Guido van Rossum778983b1993-02-19 15:55:02 +00001500}
1501
Brett Cannon1eb32c22014-10-10 16:26:45 -04001502/*[clinic input]
1503array.array.fromlist
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001504
Brett Cannon1eb32c22014-10-10 16:26:45 -04001505 list: object
1506 /
1507
1508Append items to array from list.
1509[clinic start generated code]*/
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001510
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001511static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001512array_array_fromlist(arrayobject *self, PyObject *list)
1513/*[clinic end generated code: output=26411c2d228a3e3f input=be2605a96c49680f]*/
Guido van Rossum778983b1993-02-19 15:55:02 +00001514{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001515 Py_ssize_t n;
Raymond Hettinger36cd2bf2003-01-03 08:24:58 +00001516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001517 if (!PyList_Check(list)) {
1518 PyErr_SetString(PyExc_TypeError, "arg must be list");
1519 return NULL;
1520 }
1521 n = PyList_Size(list);
1522 if (n > 0) {
1523 Py_ssize_t i, old_size;
1524 old_size = Py_SIZE(self);
1525 if (array_resize(self, old_size + n) == -1)
1526 return NULL;
1527 for (i = 0; i < n; i++) {
1528 PyObject *v = PyList_GetItem(list, i);
1529 if ((*self->ob_descr->setitem)(self,
1530 Py_SIZE(self) - n + i, v) != 0) {
1531 array_resize(self, old_size);
1532 return NULL;
1533 }
1534 }
1535 }
1536 Py_INCREF(Py_None);
1537 return Py_None;
Guido van Rossum778983b1993-02-19 15:55:02 +00001538}
1539
Brett Cannon1eb32c22014-10-10 16:26:45 -04001540/*[clinic input]
1541array.array.tolist
1542
1543Convert array to an ordinary list with the same items.
1544[clinic start generated code]*/
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001545
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001546static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001547array_array_tolist_impl(arrayobject *self)
1548/*[clinic end generated code: output=00b60cc9eab8ef89 input=a8d7784a94f86b53]*/
Guido van Rossum778983b1993-02-19 15:55:02 +00001549{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001550 PyObject *list = PyList_New(Py_SIZE(self));
1551 Py_ssize_t i;
Raymond Hettinger36cd2bf2003-01-03 08:24:58 +00001552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001553 if (list == NULL)
1554 return NULL;
1555 for (i = 0; i < Py_SIZE(self); i++) {
1556 PyObject *v = getarrayitem((PyObject *)self, i);
Victor Stinner4755bea2013-07-18 01:12:35 +02001557 if (v == NULL)
1558 goto error;
1559 if (PyList_SetItem(list, i, v) < 0)
1560 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001561 }
1562 return list;
Victor Stinner4755bea2013-07-18 01:12:35 +02001563
1564error:
1565 Py_DECREF(list);
1566 return NULL;
Guido van Rossum778983b1993-02-19 15:55:02 +00001567}
1568
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001569static PyObject *
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001570frombytes(arrayobject *self, Py_buffer *buffer)
Guido van Rossum778983b1993-02-19 15:55:02 +00001571{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001572 int itemsize = self->ob_descr->itemsize;
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001573 Py_ssize_t n;
1574 if (buffer->itemsize != 1) {
1575 PyBuffer_Release(buffer);
1576 PyErr_SetString(PyExc_TypeError, "string/buffer of bytes required.");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001577 return NULL;
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001578 }
1579 n = buffer->len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001580 if (n % itemsize != 0) {
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001581 PyBuffer_Release(buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001582 PyErr_SetString(PyExc_ValueError,
1583 "string length not a multiple of item size");
1584 return NULL;
1585 }
1586 n = n / itemsize;
1587 if (n > 0) {
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001588 Py_ssize_t old_size = Py_SIZE(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001589 if ((n > PY_SSIZE_T_MAX - old_size) ||
1590 ((old_size + n) > PY_SSIZE_T_MAX / itemsize)) {
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001591 PyBuffer_Release(buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001592 return PyErr_NoMemory();
1593 }
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001594 if (array_resize(self, old_size + n) == -1) {
1595 PyBuffer_Release(buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001596 return NULL;
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001597 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001598 memcpy(self->ob_item + old_size * itemsize,
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001599 buffer->buf, n * itemsize);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001600 }
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001601 PyBuffer_Release(buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001602 Py_INCREF(Py_None);
1603 return Py_None;
Guido van Rossum778983b1993-02-19 15:55:02 +00001604}
1605
Brett Cannon1eb32c22014-10-10 16:26:45 -04001606/*[clinic input]
1607array.array.fromstring
1608
1609 buffer: Py_buffer(types='str bytes bytearray buffer')
1610 /
1611
1612Appends 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).
1613
1614This method is deprecated. Use frombytes instead.
1615[clinic start generated code]*/
1616
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001617static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001618array_array_fromstring_impl(arrayobject *self, Py_buffer *buffer)
1619/*[clinic end generated code: output=31c4baa779df84ce input=1302d94c97696b84]*/
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001620{
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001621 if (PyErr_WarnEx(PyExc_DeprecationWarning,
1622 "fromstring() is deprecated. Use frombytes() instead.", 2) != 0)
1623 return NULL;
Brett Cannon1eb32c22014-10-10 16:26:45 -04001624 return frombytes(self, buffer);
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001625}
1626
Brett Cannon1eb32c22014-10-10 16:26:45 -04001627/*[clinic input]
1628array.array.frombytes
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001629
Brett Cannon1eb32c22014-10-10 16:26:45 -04001630 buffer: Py_buffer
1631 /
1632
1633Appends 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).
1634[clinic start generated code]*/
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001635
1636static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001637array_array_frombytes_impl(arrayobject *self, Py_buffer *buffer)
1638/*[clinic end generated code: output=d9842c8f7510a516 input=2bbf2b53ebfcc988]*/
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001639{
Brett Cannon1eb32c22014-10-10 16:26:45 -04001640 return frombytes(self, buffer);
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001641}
1642
Brett Cannon1eb32c22014-10-10 16:26:45 -04001643/*[clinic input]
1644array.array.tobytes
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001645
Brett Cannon1eb32c22014-10-10 16:26:45 -04001646Convert the array to an array of machine values and return the bytes representation.
1647[clinic start generated code]*/
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001648
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001649static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001650array_array_tobytes_impl(arrayobject *self)
1651/*[clinic end generated code: output=87318e4edcdc2bb6 input=90ee495f96de34f5]*/
Guido van Rossum778983b1993-02-19 15:55:02 +00001652{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001653 if (Py_SIZE(self) <= PY_SSIZE_T_MAX / self->ob_descr->itemsize) {
1654 return PyBytes_FromStringAndSize(self->ob_item,
1655 Py_SIZE(self) * self->ob_descr->itemsize);
1656 } else {
1657 return PyErr_NoMemory();
1658 }
Guido van Rossum778983b1993-02-19 15:55:02 +00001659}
1660
Brett Cannon1eb32c22014-10-10 16:26:45 -04001661/*[clinic input]
1662array.array.tostring
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001663
Brett Cannon1eb32c22014-10-10 16:26:45 -04001664Convert the array to an array of machine values and return the bytes representation.
1665
1666This method is deprecated. Use tobytes instead.
1667[clinic start generated code]*/
Martin v. Löwis99866332002-03-01 10:27:01 +00001668
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001669static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001670array_array_tostring_impl(arrayobject *self)
1671/*[clinic end generated code: output=7d6bd92745a2c8f3 input=b6c0ddee7b30457e]*/
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001672{
Victor Stinner9f0b51e2010-11-09 09:38:30 +00001673 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001674 "tostring() is deprecated. Use tobytes() instead.", 2) != 0)
1675 return NULL;
Brett Cannon1eb32c22014-10-10 16:26:45 -04001676 return array_array_tobytes_impl(self);
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001677}
1678
Brett Cannon1eb32c22014-10-10 16:26:45 -04001679/*[clinic input]
1680array.array.fromunicode
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001681
Brett Cannon1eb32c22014-10-10 16:26:45 -04001682 ustr: Py_UNICODE(length=True)
1683 /
1684
1685Extends this array with data from the unicode string ustr.
1686
1687The array must be a unicode type array; otherwise a ValueError is raised.
1688Use array.frombytes(ustr.encode(...)) to append Unicode data to an array of
1689some other type.
1690[clinic start generated code]*/
Martin v. Löwis99866332002-03-01 10:27:01 +00001691
Martin v. Löwis99866332002-03-01 10:27:01 +00001692static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001693array_array_fromunicode_impl(arrayobject *self, Py_UNICODE *ustr, Py_ssize_clean_t ustr_length)
1694/*[clinic end generated code: output=3b3f4f133bac725e input=56bcedb5ef70139f]*/
Martin v. Löwis99866332002-03-01 10:27:01 +00001695{
Victor Stinner62bb3942012-08-06 00:46:05 +02001696 char typecode;
Martin v. Löwis99866332002-03-01 10:27:01 +00001697
Victor Stinner62bb3942012-08-06 00:46:05 +02001698 typecode = self->ob_descr->typecode;
Gregory P. Smith9504b132012-12-10 20:20:20 -08001699 if (typecode != 'u') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001700 PyErr_SetString(PyExc_ValueError,
1701 "fromunicode() may only be called on "
1702 "unicode type arrays");
1703 return NULL;
1704 }
Brett Cannon1eb32c22014-10-10 16:26:45 -04001705 if (ustr_length > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001706 Py_ssize_t old_size = Py_SIZE(self);
Brett Cannon1eb32c22014-10-10 16:26:45 -04001707 if (array_resize(self, old_size + ustr_length) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001708 return NULL;
Victor Stinner62bb3942012-08-06 00:46:05 +02001709 memcpy(self->ob_item + old_size * sizeof(Py_UNICODE),
Brett Cannon1eb32c22014-10-10 16:26:45 -04001710 ustr, ustr_length * sizeof(Py_UNICODE));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001711 }
Martin v. Löwis99866332002-03-01 10:27:01 +00001712
Brett Cannon1eb32c22014-10-10 16:26:45 -04001713 Py_RETURN_NONE;
Martin v. Löwis99866332002-03-01 10:27:01 +00001714}
1715
Brett Cannon1eb32c22014-10-10 16:26:45 -04001716/*[clinic input]
1717array.array.tounicode
Martin v. Löwis99866332002-03-01 10:27:01 +00001718
Brett Cannon1eb32c22014-10-10 16:26:45 -04001719Extends this array with data from the unicode string ustr.
1720
1721Convert the array to a unicode string. The array must be a unicode type array;
1722otherwise a ValueError is raised. Use array.tobytes().decode() to obtain a
1723unicode string from an array of some other type.
1724[clinic start generated code]*/
Martin v. Löwis99866332002-03-01 10:27:01 +00001725
1726static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001727array_array_tounicode_impl(arrayobject *self)
1728/*[clinic end generated code: output=08e442378336e1ef input=127242eebe70b66d]*/
Martin v. Löwis99866332002-03-01 10:27:01 +00001729{
Victor Stinner62bb3942012-08-06 00:46:05 +02001730 char typecode;
1731 typecode = self->ob_descr->typecode;
Gregory P. Smith9504b132012-12-10 20:20:20 -08001732 if (typecode != 'u') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001733 PyErr_SetString(PyExc_ValueError,
1734 "tounicode() may only be called on unicode type arrays");
1735 return NULL;
1736 }
Victor Stinner62bb3942012-08-06 00:46:05 +02001737 return PyUnicode_FromUnicode((Py_UNICODE *) self->ob_item, Py_SIZE(self));
Martin v. Löwis99866332002-03-01 10:27:01 +00001738}
1739
Brett Cannon1eb32c22014-10-10 16:26:45 -04001740/*[clinic input]
1741array.array.__sizeof__
Martin v. Löwis99866332002-03-01 10:27:01 +00001742
Brett Cannon1eb32c22014-10-10 16:26:45 -04001743Size of the array in memory, in bytes.
1744[clinic start generated code]*/
Martin v. Löwis99866332002-03-01 10:27:01 +00001745
Meador Inge03b4d502012-08-10 22:35:45 -05001746static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001747array_array___sizeof___impl(arrayobject *self)
1748/*[clinic end generated code: output=d8e1c61ebbe3eaed input=805586565bf2b3c6]*/
Meador Inge03b4d502012-08-10 22:35:45 -05001749{
1750 Py_ssize_t res;
1751 res = sizeof(arrayobject) + self->allocated * self->ob_descr->itemsize;
1752 return PyLong_FromSsize_t(res);
1753}
1754
Martin v. Löwis99866332002-03-01 10:27:01 +00001755
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001756/*********************** Pickling support ************************/
1757
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001758static const struct mformatdescr {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001759 size_t size;
1760 int is_signed;
1761 int is_big_endian;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001762} mformat_descriptors[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001763 {1, 0, 0}, /* 0: UNSIGNED_INT8 */
1764 {1, 1, 0}, /* 1: SIGNED_INT8 */
1765 {2, 0, 0}, /* 2: UNSIGNED_INT16_LE */
1766 {2, 0, 1}, /* 3: UNSIGNED_INT16_BE */
1767 {2, 1, 0}, /* 4: SIGNED_INT16_LE */
1768 {2, 1, 1}, /* 5: SIGNED_INT16_BE */
1769 {4, 0, 0}, /* 6: UNSIGNED_INT32_LE */
1770 {4, 0, 1}, /* 7: UNSIGNED_INT32_BE */
1771 {4, 1, 0}, /* 8: SIGNED_INT32_LE */
1772 {4, 1, 1}, /* 9: SIGNED_INT32_BE */
1773 {8, 0, 0}, /* 10: UNSIGNED_INT64_LE */
1774 {8, 0, 1}, /* 11: UNSIGNED_INT64_BE */
1775 {8, 1, 0}, /* 12: SIGNED_INT64_LE */
1776 {8, 1, 1}, /* 13: SIGNED_INT64_BE */
1777 {4, 0, 0}, /* 14: IEEE_754_FLOAT_LE */
1778 {4, 0, 1}, /* 15: IEEE_754_FLOAT_BE */
1779 {8, 0, 0}, /* 16: IEEE_754_DOUBLE_LE */
1780 {8, 0, 1}, /* 17: IEEE_754_DOUBLE_BE */
1781 {4, 0, 0}, /* 18: UTF16_LE */
1782 {4, 0, 1}, /* 19: UTF16_BE */
1783 {8, 0, 0}, /* 20: UTF32_LE */
1784 {8, 0, 1} /* 21: UTF32_BE */
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001785};
1786
1787
1788/*
1789 * Internal: This function is used to find the machine format of a given
1790 * array type code. This returns UNKNOWN_FORMAT when the machine format cannot
1791 * be found.
1792 */
1793static enum machine_format_code
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02001794typecode_to_mformat_code(char typecode)
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001795{
Christian Heimes743e0cd2012-10-17 23:52:17 +02001796 const int is_big_endian = PY_BIG_ENDIAN;
1797
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001798 size_t intsize;
1799 int is_signed;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001800
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001801 switch (typecode) {
1802 case 'b':
1803 return SIGNED_INT8;
1804 case 'B':
1805 return UNSIGNED_INT8;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001807 case 'u':
Victor Stinner62bb3942012-08-06 00:46:05 +02001808 if (sizeof(Py_UNICODE) == 2) {
1809 return UTF16_LE + is_big_endian;
1810 }
1811 if (sizeof(Py_UNICODE) == 4) {
1812 return UTF32_LE + is_big_endian;
1813 }
1814 return UNKNOWN_FORMAT;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001816 case 'f':
1817 if (sizeof(float) == 4) {
1818 const float y = 16711938.0;
1819 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1820 return IEEE_754_FLOAT_BE;
1821 if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1822 return IEEE_754_FLOAT_LE;
1823 }
1824 return UNKNOWN_FORMAT;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001825
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001826 case 'd':
1827 if (sizeof(double) == 8) {
1828 const double x = 9006104071832581.0;
1829 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1830 return IEEE_754_DOUBLE_BE;
1831 if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1832 return IEEE_754_DOUBLE_LE;
1833 }
1834 return UNKNOWN_FORMAT;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001836 /* Integers */
1837 case 'h':
1838 intsize = sizeof(short);
1839 is_signed = 1;
1840 break;
1841 case 'H':
1842 intsize = sizeof(short);
1843 is_signed = 0;
1844 break;
1845 case 'i':
1846 intsize = sizeof(int);
1847 is_signed = 1;
1848 break;
1849 case 'I':
1850 intsize = sizeof(int);
1851 is_signed = 0;
1852 break;
1853 case 'l':
1854 intsize = sizeof(long);
1855 is_signed = 1;
1856 break;
1857 case 'L':
1858 intsize = sizeof(long);
1859 is_signed = 0;
1860 break;
Meador Inge1c9f0c92011-09-20 19:55:51 -05001861#if HAVE_LONG_LONG
1862 case 'q':
1863 intsize = sizeof(PY_LONG_LONG);
1864 is_signed = 1;
1865 break;
1866 case 'Q':
1867 intsize = sizeof(PY_LONG_LONG);
1868 is_signed = 0;
1869 break;
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02001870#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001871 default:
1872 return UNKNOWN_FORMAT;
1873 }
1874 switch (intsize) {
1875 case 2:
1876 return UNSIGNED_INT16_LE + is_big_endian + (2 * is_signed);
1877 case 4:
1878 return UNSIGNED_INT32_LE + is_big_endian + (2 * is_signed);
1879 case 8:
1880 return UNSIGNED_INT64_LE + is_big_endian + (2 * is_signed);
1881 default:
1882 return UNKNOWN_FORMAT;
1883 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001884}
1885
1886/* Forward declaration. */
1887static PyObject *array_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1888
1889/*
1890 * Internal: This function wraps the array constructor--i.e., array_new()--to
1891 * allow the creation of array objects from C code without having to deal
1892 * directly the tuple argument of array_new(). The typecode argument is a
1893 * Unicode character value, like 'i' or 'f' for example, representing an array
1894 * type code. The items argument is a bytes or a list object from which
1895 * contains the initial value of the array.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001896 *
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001897 * On success, this functions returns the array object created. Otherwise,
1898 * NULL is returned to indicate a failure.
1899 */
1900static PyObject *
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02001901make_array(PyTypeObject *arraytype, char typecode, PyObject *items)
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001902{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001903 PyObject *new_args;
1904 PyObject *array_obj;
1905 PyObject *typecode_obj;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001907 assert(arraytype != NULL);
1908 assert(items != NULL);
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001909
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02001910 typecode_obj = PyUnicode_FromOrdinal(typecode);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001911 if (typecode_obj == NULL)
1912 return NULL;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001914 new_args = PyTuple_New(2);
1915 if (new_args == NULL)
1916 return NULL;
1917 Py_INCREF(items);
1918 PyTuple_SET_ITEM(new_args, 0, typecode_obj);
1919 PyTuple_SET_ITEM(new_args, 1, items);
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001921 array_obj = array_new(arraytype, new_args, NULL);
1922 Py_DECREF(new_args);
1923 if (array_obj == NULL)
1924 return NULL;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001925
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001926 return array_obj;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001927}
1928
1929/*
1930 * This functions is a special constructor used when unpickling an array. It
1931 * provides a portable way to rebuild an array from its memory representation.
1932 */
Brett Cannon1eb32c22014-10-10 16:26:45 -04001933/*[clinic input]
1934array._array_reconstructor
1935
1936 arraytype: object(type="PyTypeObject *")
1937 typecode: int(types='str')
1938 mformat_code: int(type="enum machine_format_code")
1939 items: object
1940 /
1941
1942Internal. Used for pickling support.
1943[clinic start generated code]*/
1944
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001945static PyObject *
Larry Hastingsdfbeb162014-10-13 10:39:41 +01001946array__array_reconstructor_impl(PyModuleDef *module, PyTypeObject *arraytype, int typecode, enum machine_format_code mformat_code, PyObject *items)
1947/*[clinic end generated code: output=c51081ec91caf7e9 input=f72492708c0a1d50]*/
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001948{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001949 PyObject *converted_items;
1950 PyObject *result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001951 struct arraydescr *descr;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001953 if (!PyType_Check(arraytype)) {
1954 PyErr_Format(PyExc_TypeError,
1955 "first argument must a type object, not %.200s",
1956 Py_TYPE(arraytype)->tp_name);
1957 return NULL;
1958 }
1959 if (!PyType_IsSubtype(arraytype, &Arraytype)) {
1960 PyErr_Format(PyExc_TypeError,
1961 "%.200s is not a subtype of %.200s",
1962 arraytype->tp_name, Arraytype.tp_name);
1963 return NULL;
1964 }
1965 for (descr = descriptors; descr->typecode != '\0'; descr++) {
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02001966 if ((int)descr->typecode == typecode)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001967 break;
1968 }
1969 if (descr->typecode == '\0') {
1970 PyErr_SetString(PyExc_ValueError,
1971 "second argument must be a valid type code");
1972 return NULL;
1973 }
Larry Hastingsdfbeb162014-10-13 10:39:41 +01001974 if (mformat_code < MACHINE_FORMAT_CODE_MIN ||
1975 mformat_code > MACHINE_FORMAT_CODE_MAX) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001976 PyErr_SetString(PyExc_ValueError,
1977 "third argument must be a valid machine format code.");
1978 return NULL;
1979 }
1980 if (!PyBytes_Check(items)) {
1981 PyErr_Format(PyExc_TypeError,
1982 "fourth argument should be bytes, not %.200s",
1983 Py_TYPE(items)->tp_name);
1984 return NULL;
1985 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001987 /* Fast path: No decoding has to be done. */
Larry Hastingsdfbeb162014-10-13 10:39:41 +01001988 if (mformat_code == typecode_to_mformat_code((char)typecode) ||
1989 mformat_code == UNKNOWN_FORMAT) {
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02001990 return make_array(arraytype, (char)typecode, items);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001991 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001993 /* Slow path: Decode the byte string according to the given machine
1994 * format code. This occurs when the computer unpickling the array
1995 * object is architecturally different from the one that pickled the
1996 * array.
1997 */
Larry Hastingsdfbeb162014-10-13 10:39:41 +01001998 if (Py_SIZE(items) % mformat_descriptors[mformat_code].size != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001999 PyErr_SetString(PyExc_ValueError,
2000 "string length not a multiple of item size");
2001 return NULL;
2002 }
Larry Hastingsdfbeb162014-10-13 10:39:41 +01002003 switch (mformat_code) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002004 case IEEE_754_FLOAT_LE:
2005 case IEEE_754_FLOAT_BE: {
2006 int i;
Larry Hastingsdfbeb162014-10-13 10:39:41 +01002007 int le = (mformat_code == IEEE_754_FLOAT_LE) ? 1 : 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002008 Py_ssize_t itemcount = Py_SIZE(items) / 4;
2009 const unsigned char *memstr =
2010 (unsigned char *)PyBytes_AS_STRING(items);
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002012 converted_items = PyList_New(itemcount);
2013 if (converted_items == NULL)
2014 return NULL;
2015 for (i = 0; i < itemcount; i++) {
2016 PyObject *pyfloat = PyFloat_FromDouble(
2017 _PyFloat_Unpack4(&memstr[i * 4], le));
2018 if (pyfloat == NULL) {
2019 Py_DECREF(converted_items);
2020 return NULL;
2021 }
2022 PyList_SET_ITEM(converted_items, i, pyfloat);
2023 }
2024 break;
2025 }
2026 case IEEE_754_DOUBLE_LE:
2027 case IEEE_754_DOUBLE_BE: {
2028 int i;
Larry Hastingsdfbeb162014-10-13 10:39:41 +01002029 int le = (mformat_code == IEEE_754_DOUBLE_LE) ? 1 : 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002030 Py_ssize_t itemcount = Py_SIZE(items) / 8;
2031 const unsigned char *memstr =
2032 (unsigned char *)PyBytes_AS_STRING(items);
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002033
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002034 converted_items = PyList_New(itemcount);
2035 if (converted_items == NULL)
2036 return NULL;
2037 for (i = 0; i < itemcount; i++) {
2038 PyObject *pyfloat = PyFloat_FromDouble(
2039 _PyFloat_Unpack8(&memstr[i * 8], le));
2040 if (pyfloat == NULL) {
2041 Py_DECREF(converted_items);
2042 return NULL;
2043 }
2044 PyList_SET_ITEM(converted_items, i, pyfloat);
2045 }
2046 break;
2047 }
2048 case UTF16_LE:
2049 case UTF16_BE: {
Larry Hastingsdfbeb162014-10-13 10:39:41 +01002050 int byteorder = (mformat_code == UTF16_LE) ? -1 : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002051 converted_items = PyUnicode_DecodeUTF16(
2052 PyBytes_AS_STRING(items), Py_SIZE(items),
2053 "strict", &byteorder);
2054 if (converted_items == NULL)
2055 return NULL;
2056 break;
2057 }
2058 case UTF32_LE:
2059 case UTF32_BE: {
Larry Hastingsdfbeb162014-10-13 10:39:41 +01002060 int byteorder = (mformat_code == UTF32_LE) ? -1 : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002061 converted_items = PyUnicode_DecodeUTF32(
2062 PyBytes_AS_STRING(items), Py_SIZE(items),
2063 "strict", &byteorder);
2064 if (converted_items == NULL)
2065 return NULL;
2066 break;
2067 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002068
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002069 case UNSIGNED_INT8:
2070 case SIGNED_INT8:
2071 case UNSIGNED_INT16_LE:
2072 case UNSIGNED_INT16_BE:
2073 case SIGNED_INT16_LE:
2074 case SIGNED_INT16_BE:
2075 case UNSIGNED_INT32_LE:
2076 case UNSIGNED_INT32_BE:
2077 case SIGNED_INT32_LE:
2078 case SIGNED_INT32_BE:
2079 case UNSIGNED_INT64_LE:
2080 case UNSIGNED_INT64_BE:
2081 case SIGNED_INT64_LE:
2082 case SIGNED_INT64_BE: {
2083 int i;
2084 const struct mformatdescr mf_descr =
Larry Hastingsdfbeb162014-10-13 10:39:41 +01002085 mformat_descriptors[mformat_code];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002086 Py_ssize_t itemcount = Py_SIZE(items) / mf_descr.size;
2087 const unsigned char *memstr =
2088 (unsigned char *)PyBytes_AS_STRING(items);
2089 struct arraydescr *descr;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002090
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002091 /* If possible, try to pack array's items using a data type
2092 * that fits better. This may result in an array with narrower
2093 * or wider elements.
2094 *
2095 * For example, if a 32-bit machine pickles a L-code array of
2096 * unsigned longs, then the array will be unpickled by 64-bit
2097 * machine as an I-code array of unsigned ints.
2098 *
2099 * XXX: Is it possible to write a unit test for this?
2100 */
2101 for (descr = descriptors; descr->typecode != '\0'; descr++) {
2102 if (descr->is_integer_type &&
Victor Stinner706768c2014-08-16 01:03:39 +02002103 (size_t)descr->itemsize == mf_descr.size &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002104 descr->is_signed == mf_descr.is_signed)
2105 typecode = descr->typecode;
2106 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002107
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002108 converted_items = PyList_New(itemcount);
2109 if (converted_items == NULL)
2110 return NULL;
2111 for (i = 0; i < itemcount; i++) {
2112 PyObject *pylong;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002113
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002114 pylong = _PyLong_FromByteArray(
2115 &memstr[i * mf_descr.size],
2116 mf_descr.size,
2117 !mf_descr.is_big_endian,
2118 mf_descr.is_signed);
2119 if (pylong == NULL) {
2120 Py_DECREF(converted_items);
2121 return NULL;
2122 }
2123 PyList_SET_ITEM(converted_items, i, pylong);
2124 }
2125 break;
2126 }
2127 case UNKNOWN_FORMAT:
2128 /* Impossible, but needed to shut up GCC about the unhandled
2129 * enumeration value.
2130 */
2131 default:
2132 PyErr_BadArgument();
2133 return NULL;
2134 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002135
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02002136 result = make_array(arraytype, (char)typecode, converted_items);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002137 Py_DECREF(converted_items);
2138 return result;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002139}
2140
Brett Cannon1eb32c22014-10-10 16:26:45 -04002141/*[clinic input]
2142array.array.__reduce_ex__
2143
2144 value: object
2145 /
2146
2147Return state information for pickling.
2148[clinic start generated code]*/
2149
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002150static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04002151array_array___reduce_ex__(arrayobject *self, PyObject *value)
2152/*[clinic end generated code: output=051e0a6175d0eddb input=c36c3f85de7df6cd]*/
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002153{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002154 PyObject *dict;
2155 PyObject *result;
2156 PyObject *array_str;
Brett Cannon1eb32c22014-10-10 16:26:45 -04002157 int typecode = self->ob_descr->typecode;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002158 int mformat_code;
2159 static PyObject *array_reconstructor = NULL;
2160 long protocol;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002161 _Py_IDENTIFIER(_array_reconstructor);
2162 _Py_IDENTIFIER(__dict__);
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002164 if (array_reconstructor == NULL) {
2165 PyObject *array_module = PyImport_ImportModule("array");
2166 if (array_module == NULL)
2167 return NULL;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002168 array_reconstructor = _PyObject_GetAttrId(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002169 array_module,
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002170 &PyId__array_reconstructor);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002171 Py_DECREF(array_module);
2172 if (array_reconstructor == NULL)
2173 return NULL;
2174 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002175
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002176 if (!PyLong_Check(value)) {
2177 PyErr_SetString(PyExc_TypeError,
2178 "__reduce_ex__ argument should an integer");
2179 return NULL;
2180 }
2181 protocol = PyLong_AsLong(value);
2182 if (protocol == -1 && PyErr_Occurred())
2183 return NULL;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002184
Brett Cannon1eb32c22014-10-10 16:26:45 -04002185 dict = _PyObject_GetAttrId((PyObject *)self, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002186 if (dict == NULL) {
2187 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
2188 return NULL;
2189 PyErr_Clear();
2190 dict = Py_None;
2191 Py_INCREF(dict);
2192 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002194 mformat_code = typecode_to_mformat_code(typecode);
2195 if (mformat_code == UNKNOWN_FORMAT || protocol < 3) {
2196 /* Convert the array to a list if we got something weird
2197 * (e.g., non-IEEE floats), or we are pickling the array using
2198 * a Python 2.x compatible protocol.
2199 *
2200 * It is necessary to use a list representation for Python 2.x
2201 * compatible pickle protocol, since Python 2's str objects
2202 * are unpickled as unicode by Python 3. Thus it is impossible
2203 * to make arrays unpicklable by Python 3 by using their memory
2204 * representation, unless we resort to ugly hacks such as
2205 * coercing unicode objects to bytes in array_reconstructor.
2206 */
2207 PyObject *list;
Brett Cannon1eb32c22014-10-10 16:26:45 -04002208 list = array_array_tolist_impl(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002209 if (list == NULL) {
2210 Py_DECREF(dict);
2211 return NULL;
2212 }
2213 result = Py_BuildValue(
Brett Cannon1eb32c22014-10-10 16:26:45 -04002214 "O(CO)O", Py_TYPE(self), typecode, list, dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002215 Py_DECREF(list);
2216 Py_DECREF(dict);
2217 return result;
2218 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002219
Brett Cannon1eb32c22014-10-10 16:26:45 -04002220 array_str = array_array_tobytes_impl(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002221 if (array_str == NULL) {
2222 Py_DECREF(dict);
2223 return NULL;
2224 }
2225 result = Py_BuildValue(
Brett Cannon1eb32c22014-10-10 16:26:45 -04002226 "O(OCiN)O", array_reconstructor, Py_TYPE(self), typecode,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002227 mformat_code, array_str, dict);
2228 Py_DECREF(dict);
2229 return result;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002230}
2231
Martin v. Löwis99866332002-03-01 10:27:01 +00002232static PyObject *
2233array_get_typecode(arrayobject *a, void *closure)
2234{
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02002235 char typecode = a->ob_descr->typecode;
2236 return PyUnicode_FromOrdinal(typecode);
Martin v. Löwis99866332002-03-01 10:27:01 +00002237}
2238
2239static PyObject *
2240array_get_itemsize(arrayobject *a, void *closure)
2241{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002242 return PyLong_FromLong((long)a->ob_descr->itemsize);
Martin v. Löwis99866332002-03-01 10:27:01 +00002243}
2244
2245static PyGetSetDef array_getsets [] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002246 {"typecode", (getter) array_get_typecode, NULL,
2247 "the typecode character used to create the array"},
2248 {"itemsize", (getter) array_get_itemsize, NULL,
2249 "the size, in bytes, of one array item"},
2250 {NULL}
Martin v. Löwis99866332002-03-01 10:27:01 +00002251};
2252
Martin v. Löwis59683e82008-06-13 07:50:45 +00002253static PyMethodDef array_methods[] = {
Brett Cannon1eb32c22014-10-10 16:26:45 -04002254 ARRAY_ARRAY_APPEND_METHODDEF
2255 ARRAY_ARRAY_BUFFER_INFO_METHODDEF
2256 ARRAY_ARRAY_BYTESWAP_METHODDEF
2257 ARRAY_ARRAY___COPY___METHODDEF
2258 ARRAY_ARRAY_COUNT_METHODDEF
2259 ARRAY_ARRAY___DEEPCOPY___METHODDEF
2260 ARRAY_ARRAY_EXTEND_METHODDEF
2261 ARRAY_ARRAY_FROMFILE_METHODDEF
2262 ARRAY_ARRAY_FROMLIST_METHODDEF
2263 ARRAY_ARRAY_FROMSTRING_METHODDEF
2264 ARRAY_ARRAY_FROMBYTES_METHODDEF
2265 ARRAY_ARRAY_FROMUNICODE_METHODDEF
2266 ARRAY_ARRAY_INDEX_METHODDEF
2267 ARRAY_ARRAY_INSERT_METHODDEF
2268 ARRAY_ARRAY_POP_METHODDEF
2269 ARRAY_ARRAY___REDUCE_EX___METHODDEF
2270 ARRAY_ARRAY_REMOVE_METHODDEF
2271 ARRAY_ARRAY_REVERSE_METHODDEF
2272 ARRAY_ARRAY_TOFILE_METHODDEF
2273 ARRAY_ARRAY_TOLIST_METHODDEF
2274 ARRAY_ARRAY_TOSTRING_METHODDEF
2275 ARRAY_ARRAY_TOBYTES_METHODDEF
2276 ARRAY_ARRAY_TOUNICODE_METHODDEF
2277 ARRAY_ARRAY___SIZEOF___METHODDEF
2278 {NULL, NULL} /* sentinel */
Guido van Rossum778983b1993-02-19 15:55:02 +00002279};
2280
Roger E. Masse2919eaa1996-12-09 20:10:36 +00002281static PyObject *
Peter Schneider-Kamp9656abd2000-07-13 21:10:57 +00002282array_repr(arrayobject *a)
Guido van Rossum778983b1993-02-19 15:55:02 +00002283{
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02002284 char typecode;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002285 PyObject *s, *v = NULL;
2286 Py_ssize_t len;
Martin v. Löwis99866332002-03-01 10:27:01 +00002287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002288 len = Py_SIZE(a);
2289 typecode = a->ob_descr->typecode;
2290 if (len == 0) {
Amaury Forgeot d'Arc24aa26b2010-11-25 08:13:35 +00002291 return PyUnicode_FromFormat("array('%c')", (int)typecode);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002292 }
Gregory P. Smith9504b132012-12-10 20:20:20 -08002293 if (typecode == 'u') {
Brett Cannon1eb32c22014-10-10 16:26:45 -04002294 v = array_array_tounicode_impl(a);
Gregory P. Smith9504b132012-12-10 20:20:20 -08002295 } else {
Brett Cannon1eb32c22014-10-10 16:26:45 -04002296 v = array_array_tolist_impl(a);
Gregory P. Smith9504b132012-12-10 20:20:20 -08002297 }
Victor Stinner29ec5952013-02-26 00:27:38 +01002298 if (v == NULL)
2299 return NULL;
Raymond Hettinger88ba1e32003-04-23 17:27:00 +00002300
Amaury Forgeot d'Arc24aa26b2010-11-25 08:13:35 +00002301 s = PyUnicode_FromFormat("array('%c', %R)", (int)typecode, v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002302 Py_DECREF(v);
2303 return s;
Guido van Rossum778983b1993-02-19 15:55:02 +00002304}
2305
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002306static PyObject*
2307array_subscr(arrayobject* self, PyObject* item)
2308{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002309 if (PyIndex_Check(item)) {
2310 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
2311 if (i==-1 && PyErr_Occurred()) {
2312 return NULL;
2313 }
2314 if (i < 0)
2315 i += Py_SIZE(self);
2316 return array_item(self, i);
2317 }
2318 else if (PySlice_Check(item)) {
2319 Py_ssize_t start, stop, step, slicelength, cur, i;
2320 PyObject* result;
2321 arrayobject* ar;
2322 int itemsize = self->ob_descr->itemsize;
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002323
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002324 if (PySlice_GetIndicesEx(item, Py_SIZE(self),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002325 &start, &stop, &step, &slicelength) < 0) {
2326 return NULL;
2327 }
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002329 if (slicelength <= 0) {
2330 return newarrayobject(&Arraytype, 0, self->ob_descr);
2331 }
2332 else if (step == 1) {
2333 PyObject *result = newarrayobject(&Arraytype,
2334 slicelength, self->ob_descr);
2335 if (result == NULL)
2336 return NULL;
2337 memcpy(((arrayobject *)result)->ob_item,
2338 self->ob_item + start * itemsize,
2339 slicelength * itemsize);
2340 return result;
2341 }
2342 else {
2343 result = newarrayobject(&Arraytype, slicelength, self->ob_descr);
2344 if (!result) return NULL;
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002346 ar = (arrayobject*)result;
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002348 for (cur = start, i = 0; i < slicelength;
2349 cur += step, i++) {
2350 memcpy(ar->ob_item + i*itemsize,
2351 self->ob_item + cur*itemsize,
2352 itemsize);
2353 }
2354
2355 return result;
2356 }
2357 }
2358 else {
2359 PyErr_SetString(PyExc_TypeError,
2360 "array indices must be integers");
2361 return NULL;
2362 }
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002363}
2364
2365static int
2366array_ass_subscr(arrayobject* self, PyObject* item, PyObject* value)
2367{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002368 Py_ssize_t start, stop, step, slicelength, needed;
2369 arrayobject* other;
2370 int itemsize;
Thomas Woutersed03b412007-08-28 21:37:11 +00002371
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002372 if (PyIndex_Check(item)) {
2373 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Alexandre Vassalotti47137252009-07-05 19:57:00 +00002374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002375 if (i == -1 && PyErr_Occurred())
2376 return -1;
2377 if (i < 0)
2378 i += Py_SIZE(self);
2379 if (i < 0 || i >= Py_SIZE(self)) {
2380 PyErr_SetString(PyExc_IndexError,
2381 "array assignment index out of range");
2382 return -1;
2383 }
2384 if (value == NULL) {
2385 /* Fall through to slice assignment */
2386 start = i;
2387 stop = i + 1;
2388 step = 1;
2389 slicelength = 1;
2390 }
2391 else
2392 return (*self->ob_descr->setitem)(self, i, value);
2393 }
2394 else if (PySlice_Check(item)) {
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002395 if (PySlice_GetIndicesEx(item,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002396 Py_SIZE(self), &start, &stop,
2397 &step, &slicelength) < 0) {
2398 return -1;
2399 }
2400 }
2401 else {
2402 PyErr_SetString(PyExc_TypeError,
2403 "array indices must be integer");
2404 return -1;
2405 }
2406 if (value == NULL) {
2407 other = NULL;
2408 needed = 0;
2409 }
2410 else if (array_Check(value)) {
2411 other = (arrayobject *)value;
2412 needed = Py_SIZE(other);
2413 if (self == other) {
2414 /* Special case "self[i:j] = self" -- copy self first */
2415 int ret;
2416 value = array_slice(other, 0, needed);
2417 if (value == NULL)
2418 return -1;
2419 ret = array_ass_subscr(self, item, value);
2420 Py_DECREF(value);
2421 return ret;
2422 }
2423 if (other->ob_descr != self->ob_descr) {
2424 PyErr_BadArgument();
2425 return -1;
2426 }
2427 }
2428 else {
2429 PyErr_Format(PyExc_TypeError,
2430 "can only assign array (not \"%.200s\") to array slice",
2431 Py_TYPE(value)->tp_name);
2432 return -1;
2433 }
2434 itemsize = self->ob_descr->itemsize;
2435 /* for 'a[2:1] = ...', the insertion point is 'start', not 'stop' */
2436 if ((step > 0 && stop < start) ||
2437 (step < 0 && stop > start))
2438 stop = start;
Alexandre Vassalotti47137252009-07-05 19:57:00 +00002439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002440 /* Issue #4509: If the array has exported buffers and the slice
2441 assignment would change the size of the array, fail early to make
2442 sure we don't modify it. */
2443 if ((needed == 0 || slicelength != needed) && self->ob_exports > 0) {
2444 PyErr_SetString(PyExc_BufferError,
2445 "cannot resize an array that is exporting buffers");
2446 return -1;
2447 }
Mark Dickinsonbc099642010-01-29 17:27:24 +00002448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002449 if (step == 1) {
2450 if (slicelength > needed) {
2451 memmove(self->ob_item + (start + needed) * itemsize,
2452 self->ob_item + stop * itemsize,
2453 (Py_SIZE(self) - stop) * itemsize);
2454 if (array_resize(self, Py_SIZE(self) +
2455 needed - slicelength) < 0)
2456 return -1;
2457 }
2458 else if (slicelength < needed) {
2459 if (array_resize(self, Py_SIZE(self) +
2460 needed - slicelength) < 0)
2461 return -1;
2462 memmove(self->ob_item + (start + needed) * itemsize,
2463 self->ob_item + stop * itemsize,
2464 (Py_SIZE(self) - start - needed) * itemsize);
2465 }
2466 if (needed > 0)
2467 memcpy(self->ob_item + start * itemsize,
2468 other->ob_item, needed * itemsize);
2469 return 0;
2470 }
2471 else if (needed == 0) {
2472 /* Delete slice */
2473 size_t cur;
2474 Py_ssize_t i;
Thomas Woutersed03b412007-08-28 21:37:11 +00002475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002476 if (step < 0) {
2477 stop = start + 1;
2478 start = stop + step * (slicelength - 1) - 1;
2479 step = -step;
2480 }
2481 for (cur = start, i = 0; i < slicelength;
2482 cur += step, i++) {
2483 Py_ssize_t lim = step - 1;
Thomas Woutersed03b412007-08-28 21:37:11 +00002484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002485 if (cur + step >= (size_t)Py_SIZE(self))
2486 lim = Py_SIZE(self) - cur - 1;
2487 memmove(self->ob_item + (cur - i) * itemsize,
2488 self->ob_item + (cur + 1) * itemsize,
2489 lim * itemsize);
2490 }
Mark Dickinsonc7d93b72011-09-25 15:34:32 +01002491 cur = start + (size_t)slicelength * step;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002492 if (cur < (size_t)Py_SIZE(self)) {
2493 memmove(self->ob_item + (cur-slicelength) * itemsize,
2494 self->ob_item + cur * itemsize,
2495 (Py_SIZE(self) - cur) * itemsize);
2496 }
2497 if (array_resize(self, Py_SIZE(self) - slicelength) < 0)
2498 return -1;
2499 return 0;
2500 }
2501 else {
2502 Py_ssize_t cur, i;
2503
2504 if (needed != slicelength) {
2505 PyErr_Format(PyExc_ValueError,
2506 "attempt to assign array of size %zd "
2507 "to extended slice of size %zd",
2508 needed, slicelength);
2509 return -1;
2510 }
2511 for (cur = start, i = 0; i < slicelength;
2512 cur += step, i++) {
2513 memcpy(self->ob_item + cur * itemsize,
2514 other->ob_item + i * itemsize,
2515 itemsize);
2516 }
2517 return 0;
2518 }
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002519}
2520
2521static PyMappingMethods array_as_mapping = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002522 (lenfunc)array_length,
2523 (binaryfunc)array_subscr,
2524 (objobjargproc)array_ass_subscr
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002525};
2526
Guido van Rossumd8faa362007-04-27 19:54:29 +00002527static const void *emptybuf = "";
2528
Travis E. Oliphantb99f7622007-08-18 11:21:56 +00002529
2530static int
Travis E. Oliphant8ae62b62007-09-23 02:00:13 +00002531array_buffer_getbuf(arrayobject *self, Py_buffer *view, int flags)
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00002532{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002533 if (view==NULL) goto finish;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +00002534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002535 view->buf = (void *)self->ob_item;
2536 view->obj = (PyObject*)self;
2537 Py_INCREF(self);
2538 if (view->buf == NULL)
2539 view->buf = (void *)emptybuf;
2540 view->len = (Py_SIZE(self)) * self->ob_descr->itemsize;
2541 view->readonly = 0;
2542 view->ndim = 1;
2543 view->itemsize = self->ob_descr->itemsize;
2544 view->suboffsets = NULL;
2545 view->shape = NULL;
2546 if ((flags & PyBUF_ND)==PyBUF_ND) {
2547 view->shape = &((Py_SIZE(self)));
2548 }
2549 view->strides = NULL;
2550 if ((flags & PyBUF_STRIDES)==PyBUF_STRIDES)
2551 view->strides = &(view->itemsize);
2552 view->format = NULL;
2553 view->internal = NULL;
Victor Stinner62bb3942012-08-06 00:46:05 +02002554 if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002555 view->format = self->ob_descr->formats;
Victor Stinner62bb3942012-08-06 00:46:05 +02002556#ifdef Py_UNICODE_WIDE
2557 if (self->ob_descr->typecode == 'u') {
2558 view->format = "w";
2559 }
2560#endif
2561 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +00002562
2563 finish:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002564 self->ob_exports++;
2565 return 0;
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00002566}
2567
Travis E. Oliphantb99f7622007-08-18 11:21:56 +00002568static void
Travis E. Oliphant8ae62b62007-09-23 02:00:13 +00002569array_buffer_relbuf(arrayobject *self, Py_buffer *view)
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00002570{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002571 self->ob_exports--;
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00002572}
2573
Roger E. Masse2919eaa1996-12-09 20:10:36 +00002574static PySequenceMethods array_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002575 (lenfunc)array_length, /*sq_length*/
2576 (binaryfunc)array_concat, /*sq_concat*/
2577 (ssizeargfunc)array_repeat, /*sq_repeat*/
2578 (ssizeargfunc)array_item, /*sq_item*/
2579 0, /*sq_slice*/
2580 (ssizeobjargproc)array_ass_item, /*sq_ass_item*/
2581 0, /*sq_ass_slice*/
2582 (objobjproc)array_contains, /*sq_contains*/
2583 (binaryfunc)array_inplace_concat, /*sq_inplace_concat*/
2584 (ssizeargfunc)array_inplace_repeat /*sq_inplace_repeat*/
Guido van Rossum778983b1993-02-19 15:55:02 +00002585};
2586
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00002587static PyBufferProcs array_as_buffer = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002588 (getbufferproc)array_buffer_getbuf,
2589 (releasebufferproc)array_buffer_relbuf
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00002590};
2591
Roger E. Masse2919eaa1996-12-09 20:10:36 +00002592static PyObject *
Martin v. Löwis99866332002-03-01 10:27:01 +00002593array_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum778983b1993-02-19 15:55:02 +00002594{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002595 int c;
2596 PyObject *initial = NULL, *it = NULL;
2597 struct arraydescr *descr;
Martin v. Löwis99866332002-03-01 10:27:01 +00002598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002599 if (type == &Arraytype && !_PyArg_NoKeywords("array.array()", kwds))
2600 return NULL;
Martin v. Löwis99866332002-03-01 10:27:01 +00002601
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002602 if (!PyArg_ParseTuple(args, "C|O:array", &c, &initial))
2603 return NULL;
Raymond Hettinger84fc9aa2003-04-24 10:41:55 +00002604
Alexandre Vassalotti9730e332013-11-29 20:47:15 -08002605 if (initial && c != 'u') {
2606 if (PyUnicode_Check(initial)) {
2607 PyErr_Format(PyExc_TypeError, "cannot use a str to initialize "
2608 "an array with typecode '%c'", c);
2609 return NULL;
2610 }
2611 else if (array_Check(initial) &&
2612 ((arrayobject*)initial)->ob_descr->typecode == 'u') {
2613 PyErr_Format(PyExc_TypeError, "cannot use a unicode array to "
2614 "initialize an array with typecode '%c'", c);
2615 return NULL;
2616 }
2617 }
2618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002619 if (!(initial == NULL || PyList_Check(initial)
2620 || PyByteArray_Check(initial)
2621 || PyBytes_Check(initial)
2622 || PyTuple_Check(initial)
Alexander Belopolskyef4a03f2011-01-11 21:44:00 +00002623 || ((c=='u') && PyUnicode_Check(initial))
2624 || (array_Check(initial)
2625 && c == ((arrayobject*)initial)->ob_descr->typecode))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002626 it = PyObject_GetIter(initial);
2627 if (it == NULL)
2628 return NULL;
2629 /* We set initial to NULL so that the subsequent code
2630 will create an empty array of the appropriate type
2631 and afterwards we can use array_iter_extend to populate
2632 the array.
2633 */
2634 initial = NULL;
2635 }
2636 for (descr = descriptors; descr->typecode != '\0'; descr++) {
2637 if (descr->typecode == c) {
2638 PyObject *a;
2639 Py_ssize_t len;
Martin v. Löwis99866332002-03-01 10:27:01 +00002640
Alexander Belopolskyef4a03f2011-01-11 21:44:00 +00002641 if (initial == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002642 len = 0;
Alexander Belopolskyef4a03f2011-01-11 21:44:00 +00002643 else if (PyList_Check(initial))
2644 len = PyList_GET_SIZE(initial);
2645 else if (PyTuple_Check(initial) || array_Check(initial))
2646 len = Py_SIZE(initial);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002647 else
Alexander Belopolskyef4a03f2011-01-11 21:44:00 +00002648 len = 0;
Martin v. Löwis99866332002-03-01 10:27:01 +00002649
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002650 a = newarrayobject(type, len, descr);
2651 if (a == NULL)
2652 return NULL;
2653
Alexander Belopolskyef4a03f2011-01-11 21:44:00 +00002654 if (len > 0 && !array_Check(initial)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002655 Py_ssize_t i;
2656 for (i = 0; i < len; i++) {
2657 PyObject *v =
2658 PySequence_GetItem(initial, i);
2659 if (v == NULL) {
2660 Py_DECREF(a);
2661 return NULL;
2662 }
2663 if (setarrayitem(a, i, v) != 0) {
2664 Py_DECREF(v);
2665 Py_DECREF(a);
2666 return NULL;
2667 }
2668 Py_DECREF(v);
2669 }
2670 }
2671 else if (initial != NULL && (PyByteArray_Check(initial) ||
2672 PyBytes_Check(initial))) {
2673 PyObject *t_initial, *v;
2674 t_initial = PyTuple_Pack(1, initial);
2675 if (t_initial == NULL) {
2676 Py_DECREF(a);
2677 return NULL;
2678 }
Brett Cannon1eb32c22014-10-10 16:26:45 -04002679 v = array_array_frombytes((arrayobject *)a,
2680 t_initial);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002681 Py_DECREF(t_initial);
2682 if (v == NULL) {
2683 Py_DECREF(a);
2684 return NULL;
2685 }
2686 Py_DECREF(v);
2687 }
2688 else if (initial != NULL && PyUnicode_Check(initial)) {
Victor Stinner62bb3942012-08-06 00:46:05 +02002689 Py_UNICODE *ustr;
Victor Stinner1fbcaef2011-09-30 01:54:04 +02002690 Py_ssize_t n;
Victor Stinner62bb3942012-08-06 00:46:05 +02002691
2692 ustr = PyUnicode_AsUnicode(initial);
2693 if (ustr == NULL) {
2694 PyErr_NoMemory();
Victor Stinner1fbcaef2011-09-30 01:54:04 +02002695 Py_DECREF(a);
2696 return NULL;
2697 }
Victor Stinner62bb3942012-08-06 00:46:05 +02002698
2699 n = PyUnicode_GET_DATA_SIZE(initial);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002700 if (n > 0) {
2701 arrayobject *self = (arrayobject *)a;
Victor Stinner62bb3942012-08-06 00:46:05 +02002702 char *item = self->ob_item;
2703 item = (char *)PyMem_Realloc(item, n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002704 if (item == NULL) {
2705 PyErr_NoMemory();
2706 Py_DECREF(a);
2707 return NULL;
2708 }
Victor Stinner62bb3942012-08-06 00:46:05 +02002709 self->ob_item = item;
2710 Py_SIZE(self) = n / sizeof(Py_UNICODE);
2711 memcpy(item, ustr, n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002712 self->allocated = Py_SIZE(self);
2713 }
2714 }
Benjamin Peterson682124c2014-10-10 20:58:30 -04002715 else if (initial != NULL && array_Check(initial) && len > 0) {
Alexander Belopolskyef4a03f2011-01-11 21:44:00 +00002716 arrayobject *self = (arrayobject *)a;
2717 arrayobject *other = (arrayobject *)initial;
2718 memcpy(self->ob_item, other->ob_item, len * other->ob_descr->itemsize);
2719 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002720 if (it != NULL) {
2721 if (array_iter_extend((arrayobject *)a, it) == -1) {
2722 Py_DECREF(it);
2723 Py_DECREF(a);
2724 return NULL;
2725 }
2726 Py_DECREF(it);
2727 }
2728 return a;
2729 }
2730 }
2731 PyErr_SetString(PyExc_ValueError,
Meador Inge1c9f0c92011-09-20 19:55:51 -05002732#ifdef HAVE_LONG_LONG
2733 "bad typecode (must be b, B, u, h, H, i, I, l, L, q, Q, f or d)");
2734#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002735 "bad typecode (must be b, B, u, h, H, i, I, l, L, f or d)");
Meador Inge1c9f0c92011-09-20 19:55:51 -05002736#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002737 return NULL;
Guido van Rossum778983b1993-02-19 15:55:02 +00002738}
2739
Guido van Rossum778983b1993-02-19 15:55:02 +00002740
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002741PyDoc_STRVAR(module_doc,
Martin v. Löwis99866332002-03-01 10:27:01 +00002742"This module defines an object type which can efficiently represent\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002743an array of basic values: characters, integers, floating point\n\
2744numbers. Arrays are sequence types and behave very much like lists,\n\
Alexandre Vassalotti9730e332013-11-29 20:47:15 -08002745except that the type of objects stored in them is constrained.\n");
2746
2747PyDoc_STRVAR(arraytype_doc,
2748"array(typecode [, initializer]) -> array\n\
2749\n\
2750Return a new array whose items are restricted by typecode, and\n\
2751initialized from the optional initializer value, which must be a list,\n\
2752string or iterable over elements of the appropriate type.\n\
2753\n\
2754Arrays represent basic values and behave very much like lists, except\n\
2755the type of objects stored in them is constrained. The type is specified\n\
2756at object creation time by using a type code, which is a single character.\n\
2757The following type codes are defined:\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002758\n\
2759 Type code C Type Minimum size in bytes \n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002760 'b' signed integer 1 \n\
2761 'B' unsigned integer 1 \n\
Victor Stinner62bb3942012-08-06 00:46:05 +02002762 'u' Unicode character 2 (see note) \n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002763 'h' signed integer 2 \n\
2764 'H' unsigned integer 2 \n\
2765 'i' signed integer 2 \n\
2766 'I' unsigned integer 2 \n\
2767 'l' signed integer 4 \n\
2768 'L' unsigned integer 4 \n\
Meador Inge1c9f0c92011-09-20 19:55:51 -05002769 'q' signed integer 8 (see note) \n\
2770 'Q' unsigned integer 8 (see note) \n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002771 'f' floating point 4 \n\
2772 'd' floating point 8 \n\
2773\n\
Victor Stinner62bb3942012-08-06 00:46:05 +02002774NOTE: The 'u' typecode corresponds to Python's unicode character. On \n\
2775narrow builds this is 2-bytes on wide builds this is 4-bytes.\n\
2776\n\
Meador Inge1c9f0c92011-09-20 19:55:51 -05002777NOTE: The 'q' and 'Q' type codes are only available if the platform \n\
2778C compiler used to build Python supports 'long long', or, on Windows, \n\
2779'__int64'.\n\
2780\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002781Methods:\n\
2782\n\
2783append() -- append a new item to the end of the array\n\
2784buffer_info() -- return information giving the current memory info\n\
2785byteswap() -- byteswap all the items of the array\n\
Mark Dickinson934896d2009-02-21 20:59:32 +00002786count() -- return number of occurrences of an object\n\
Raymond Hettinger49f9bd12004-03-14 05:43:59 +00002787extend() -- extend array by appending multiple elements from an iterable\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002788fromfile() -- read items from a file object\n\
2789fromlist() -- append items from the list\n\
Florent Xiclunac45fb252011-10-24 13:14:55 +02002790frombytes() -- append items from the string\n\
Mark Dickinson934896d2009-02-21 20:59:32 +00002791index() -- return index of first occurrence of an object\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002792insert() -- insert a new item into the array at a provided position\n\
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00002793pop() -- remove and return item (default last)\n\
Mark Dickinson934896d2009-02-21 20:59:32 +00002794remove() -- remove first occurrence of an object\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002795reverse() -- reverse the order of the items in the array\n\
2796tofile() -- write all items to a file object\n\
2797tolist() -- return the array converted to an ordinary list\n\
Florent Xiclunac45fb252011-10-24 13:14:55 +02002798tobytes() -- return the array converted to a string\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002799\n\
Martin v. Löwis99866332002-03-01 10:27:01 +00002800Attributes:\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002801\n\
2802typecode -- the typecode character used to create the array\n\
2803itemsize -- the length in bytes of one array item\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002804");
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002805
Raymond Hettinger625812f2003-01-07 01:58:52 +00002806static PyObject *array_iter(arrayobject *ao);
2807
Tim Peters0c322792002-07-17 16:49:03 +00002808static PyTypeObject Arraytype = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002809 PyVarObject_HEAD_INIT(NULL, 0)
2810 "array.array",
2811 sizeof(arrayobject),
2812 0,
2813 (destructor)array_dealloc, /* tp_dealloc */
2814 0, /* tp_print */
2815 0, /* tp_getattr */
2816 0, /* tp_setattr */
2817 0, /* tp_reserved */
2818 (reprfunc)array_repr, /* tp_repr */
2819 0, /* tp_as_number*/
2820 &array_as_sequence, /* tp_as_sequence*/
2821 &array_as_mapping, /* tp_as_mapping*/
2822 0, /* tp_hash */
2823 0, /* tp_call */
2824 0, /* tp_str */
2825 PyObject_GenericGetAttr, /* tp_getattro */
2826 0, /* tp_setattro */
2827 &array_as_buffer, /* tp_as_buffer*/
2828 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
2829 arraytype_doc, /* tp_doc */
2830 0, /* tp_traverse */
2831 0, /* tp_clear */
2832 array_richcompare, /* tp_richcompare */
2833 offsetof(arrayobject, weakreflist), /* tp_weaklistoffset */
2834 (getiterfunc)array_iter, /* tp_iter */
2835 0, /* tp_iternext */
2836 array_methods, /* tp_methods */
2837 0, /* tp_members */
2838 array_getsets, /* tp_getset */
2839 0, /* tp_base */
2840 0, /* tp_dict */
2841 0, /* tp_descr_get */
2842 0, /* tp_descr_set */
2843 0, /* tp_dictoffset */
2844 0, /* tp_init */
2845 PyType_GenericAlloc, /* tp_alloc */
2846 array_new, /* tp_new */
2847 PyObject_Del, /* tp_free */
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002848};
2849
Raymond Hettinger625812f2003-01-07 01:58:52 +00002850
2851/*********************** Array Iterator **************************/
2852
Brett Cannon1eb32c22014-10-10 16:26:45 -04002853/*[clinic input]
2854class array.arrayiterator "arrayiterobject *" "&PyArrayIter_Type"
2855[clinic start generated code]*/
2856/*[clinic end generated code: output=da39a3ee5e6b4b0d input=5aefd2d74d8c8e30]*/
Raymond Hettinger625812f2003-01-07 01:58:52 +00002857
2858static PyObject *
2859array_iter(arrayobject *ao)
2860{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002861 arrayiterobject *it;
Raymond Hettinger625812f2003-01-07 01:58:52 +00002862
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002863 if (!array_Check(ao)) {
2864 PyErr_BadInternalCall();
2865 return NULL;
2866 }
Raymond Hettinger625812f2003-01-07 01:58:52 +00002867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002868 it = PyObject_GC_New(arrayiterobject, &PyArrayIter_Type);
2869 if (it == NULL)
2870 return NULL;
Raymond Hettinger625812f2003-01-07 01:58:52 +00002871
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002872 Py_INCREF(ao);
2873 it->ao = ao;
2874 it->index = 0;
2875 it->getitem = ao->ob_descr->getitem;
2876 PyObject_GC_Track(it);
2877 return (PyObject *)it;
Raymond Hettinger625812f2003-01-07 01:58:52 +00002878}
2879
2880static PyObject *
Raymond Hettinger625812f2003-01-07 01:58:52 +00002881arrayiter_next(arrayiterobject *it)
2882{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002883 assert(PyArrayIter_Check(it));
2884 if (it->index < Py_SIZE(it->ao))
2885 return (*it->getitem)(it->ao, it->index++);
2886 return NULL;
Raymond Hettinger625812f2003-01-07 01:58:52 +00002887}
2888
2889static void
2890arrayiter_dealloc(arrayiterobject *it)
2891{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002892 PyObject_GC_UnTrack(it);
2893 Py_XDECREF(it->ao);
2894 PyObject_GC_Del(it);
Raymond Hettinger625812f2003-01-07 01:58:52 +00002895}
2896
2897static int
2898arrayiter_traverse(arrayiterobject *it, visitproc visit, void *arg)
2899{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002900 Py_VISIT(it->ao);
2901 return 0;
Raymond Hettinger625812f2003-01-07 01:58:52 +00002902}
2903
Brett Cannon1eb32c22014-10-10 16:26:45 -04002904/*[clinic input]
2905array.arrayiterator.__reduce__
2906
2907Return state information for pickling.
2908[clinic start generated code]*/
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002909
2910static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04002911array_arrayiterator___reduce___impl(arrayiterobject *self)
2912/*[clinic end generated code: output=7898a52e8e66e016 input=a062ea1e9951417a]*/
2913{
2914 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
2915 self->ao, self->index);
2916}
2917
2918/*[clinic input]
2919array.arrayiterator.__setstate__
2920
2921 state: object
2922 /
2923
2924Set state information for unpickling.
2925[clinic start generated code]*/
2926
2927static PyObject *
2928array_arrayiterator___setstate__(arrayiterobject *self, PyObject *state)
2929/*[clinic end generated code: output=397da9904e443cbe input=f47d5ceda19e787b]*/
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002930{
2931 Py_ssize_t index = PyLong_AsSsize_t(state);
2932 if (index == -1 && PyErr_Occurred())
2933 return NULL;
2934 if (index < 0)
2935 index = 0;
Brett Cannon1eb32c22014-10-10 16:26:45 -04002936 else if (index > Py_SIZE(self->ao))
2937 index = Py_SIZE(self->ao); /* iterator exhausted */
2938 self->index = index;
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002939 Py_RETURN_NONE;
2940}
2941
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002942static PyMethodDef arrayiter_methods[] = {
Brett Cannon1eb32c22014-10-10 16:26:45 -04002943 ARRAY_ARRAYITERATOR___REDUCE___METHODDEF
2944 ARRAY_ARRAYITERATOR___SETSTATE___METHODDEF
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002945 {NULL, NULL} /* sentinel */
2946};
2947
Raymond Hettinger625812f2003-01-07 01:58:52 +00002948static PyTypeObject PyArrayIter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002949 PyVarObject_HEAD_INIT(NULL, 0)
2950 "arrayiterator", /* tp_name */
2951 sizeof(arrayiterobject), /* tp_basicsize */
2952 0, /* tp_itemsize */
2953 /* methods */
2954 (destructor)arrayiter_dealloc, /* tp_dealloc */
2955 0, /* tp_print */
2956 0, /* tp_getattr */
2957 0, /* tp_setattr */
2958 0, /* tp_reserved */
2959 0, /* tp_repr */
2960 0, /* tp_as_number */
2961 0, /* tp_as_sequence */
2962 0, /* tp_as_mapping */
2963 0, /* tp_hash */
2964 0, /* tp_call */
2965 0, /* tp_str */
2966 PyObject_GenericGetAttr, /* tp_getattro */
2967 0, /* tp_setattro */
2968 0, /* tp_as_buffer */
2969 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2970 0, /* tp_doc */
2971 (traverseproc)arrayiter_traverse, /* tp_traverse */
2972 0, /* tp_clear */
2973 0, /* tp_richcompare */
2974 0, /* tp_weaklistoffset */
2975 PyObject_SelfIter, /* tp_iter */
2976 (iternextfunc)arrayiter_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002977 arrayiter_methods, /* tp_methods */
Raymond Hettinger625812f2003-01-07 01:58:52 +00002978};
2979
2980
2981/*********************** Install Module **************************/
2982
Martin v. Löwis99866332002-03-01 10:27:01 +00002983/* No functions in array module. */
2984static PyMethodDef a_methods[] = {
Brett Cannon1eb32c22014-10-10 16:26:45 -04002985 ARRAY__ARRAY_RECONSTRUCTOR_METHODDEF
Martin v. Löwis99866332002-03-01 10:27:01 +00002986 {NULL, NULL, 0, NULL} /* Sentinel */
2987};
2988
Martin v. Löwis1a214512008-06-11 05:26:20 +00002989static struct PyModuleDef arraymodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002990 PyModuleDef_HEAD_INIT,
2991 "array",
2992 module_doc,
2993 -1,
2994 a_methods,
2995 NULL,
2996 NULL,
2997 NULL,
2998 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002999};
3000
Martin v. Löwis99866332002-03-01 10:27:01 +00003001
Mark Hammondfe51c6d2002-08-02 02:27:13 +00003002PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00003003PyInit_array(void)
Guido van Rossum778983b1993-02-19 15:55:02 +00003004{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003005 PyObject *m;
Georg Brandl4cb0de22011-09-28 21:49:49 +02003006 char buffer[Py_ARRAY_LENGTH(descriptors)], *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003007 PyObject *typecodes;
3008 Py_ssize_t size = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003009 struct arraydescr *descr;
Fred Drake0d40ba42000-02-04 20:33:49 +00003010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003011 if (PyType_Ready(&Arraytype) < 0)
3012 return NULL;
3013 Py_TYPE(&PyArrayIter_Type) = &PyType_Type;
3014 m = PyModule_Create(&arraymodule);
3015 if (m == NULL)
3016 return NULL;
Fred Drakef4e34842002-04-01 03:45:06 +00003017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003018 Py_INCREF((PyObject *)&Arraytype);
3019 PyModule_AddObject(m, "ArrayType", (PyObject *)&Arraytype);
3020 Py_INCREF((PyObject *)&Arraytype);
3021 PyModule_AddObject(m, "array", (PyObject *)&Arraytype);
Travis E. Oliphantd5c0add2007-10-12 22:05:15 +00003022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003023 for (descr=descriptors; descr->typecode != '\0'; descr++) {
3024 size++;
3025 }
Travis E. Oliphantd5c0add2007-10-12 22:05:15 +00003026
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003027 p = buffer;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003028 for (descr = descriptors; descr->typecode != '\0'; descr++) {
3029 *p++ = (char)descr->typecode;
3030 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003031 typecodes = PyUnicode_DecodeASCII(buffer, p - buffer, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003032
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003033 PyModule_AddObject(m, "typecodes", typecodes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003034
3035 if (PyErr_Occurred()) {
3036 Py_DECREF(m);
3037 m = NULL;
3038 }
3039 return m;
Guido van Rossum778983b1993-02-19 15:55:02 +00003040}