blob: 4d9a23fb993238b9351d9ff081ad9c9e848699e9 [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]
Brett Cannon1eb32c22014-10-10 16:26:45 -040019module array
20[clinic start generated code]*/
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030021/*[clinic end generated code: output=da39a3ee5e6b4b0d input=7d1b8d7f5958fd83]*/
Brett Cannon1eb32c22014-10-10 16:26:45 -040022
Guido van Rossum778983b1993-02-19 15:55:02 +000023struct arrayobject; /* Forward */
24
Tim Petersbb307342000-09-10 05:22:54 +000025/* All possible arraydescr values are defined in the vector "descriptors"
26 * below. That's defined later because the appropriate get and set
27 * functions aren't visible yet.
28 */
Guido van Rossum778983b1993-02-19 15:55:02 +000029struct arraydescr {
Victor Stinnerf8bb7d02011-09-30 00:03:59 +020030 char typecode;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000031 int itemsize;
32 PyObject * (*getitem)(struct arrayobject *, Py_ssize_t);
33 int (*setitem)(struct arrayobject *, Py_ssize_t, PyObject *);
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020034 const char *formats;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000035 int is_integer_type;
36 int is_signed;
Guido van Rossum778983b1993-02-19 15:55:02 +000037};
38
39typedef struct arrayobject {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000040 PyObject_VAR_HEAD
41 char *ob_item;
42 Py_ssize_t allocated;
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020043 const struct arraydescr *ob_descr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000044 PyObject *weakreflist; /* List of weak references */
45 int ob_exports; /* Number of exported buffers */
Guido van Rossum778983b1993-02-19 15:55:02 +000046} arrayobject;
47
Jeremy Hylton938ace62002-07-17 16:30:39 +000048static PyTypeObject Arraytype;
Guido van Rossum778983b1993-02-19 15:55:02 +000049
Brett Cannon1eb32c22014-10-10 16:26:45 -040050typedef struct {
51 PyObject_HEAD
52 Py_ssize_t index;
53 arrayobject *ao;
54 PyObject* (*getitem)(struct arrayobject *, Py_ssize_t);
55} arrayiterobject;
56
57static PyTypeObject PyArrayIter_Type;
58
59#define PyArrayIter_Check(op) PyObject_TypeCheck(op, &PyArrayIter_Type)
60
Larry Hastingsdfbeb162014-10-13 10:39:41 +010061enum machine_format_code {
62 UNKNOWN_FORMAT = -1,
63 /* UNKNOWN_FORMAT is used to indicate that the machine format for an
64 * array type code cannot be interpreted. When this occurs, a list of
65 * Python objects is used to represent the content of the array
66 * instead of using the memory content of the array directly. In that
67 * case, the array_reconstructor mechanism is bypassed completely, and
68 * the standard array constructor is used instead.
69 *
70 * This is will most likely occur when the machine doesn't use IEEE
71 * floating-point numbers.
72 */
73
74 UNSIGNED_INT8 = 0,
75 SIGNED_INT8 = 1,
76 UNSIGNED_INT16_LE = 2,
77 UNSIGNED_INT16_BE = 3,
78 SIGNED_INT16_LE = 4,
79 SIGNED_INT16_BE = 5,
80 UNSIGNED_INT32_LE = 6,
81 UNSIGNED_INT32_BE = 7,
82 SIGNED_INT32_LE = 8,
83 SIGNED_INT32_BE = 9,
84 UNSIGNED_INT64_LE = 10,
85 UNSIGNED_INT64_BE = 11,
86 SIGNED_INT64_LE = 12,
87 SIGNED_INT64_BE = 13,
88 IEEE_754_FLOAT_LE = 14,
89 IEEE_754_FLOAT_BE = 15,
90 IEEE_754_DOUBLE_LE = 16,
91 IEEE_754_DOUBLE_BE = 17,
92 UTF16_LE = 18,
93 UTF16_BE = 19,
94 UTF32_LE = 20,
95 UTF32_BE = 21
96};
97#define MACHINE_FORMAT_CODE_MIN 0
98#define MACHINE_FORMAT_CODE_MAX 21
99
100
101/*
102 * Must come after arrayobject, arrayiterobject,
103 * and enum machine_code_type definitions.
104 */
Brett Cannon1eb32c22014-10-10 16:26:45 -0400105#include "clinic/arraymodule.c.h"
106
Martin v. Löwis99866332002-03-01 10:27:01 +0000107#define array_Check(op) PyObject_TypeCheck(op, &Arraytype)
Christian Heimes90aa7642007-12-19 02:45:37 +0000108#define array_CheckExact(op) (Py_TYPE(op) == &Arraytype)
Guido van Rossum778983b1993-02-19 15:55:02 +0000109
Raymond Hettinger6e2ee862004-03-14 04:37:50 +0000110static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000111array_resize(arrayobject *self, Py_ssize_t newsize)
Raymond Hettinger6e2ee862004-03-14 04:37:50 +0000112{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000113 char *items;
114 size_t _new_size;
Raymond Hettinger6e2ee862004-03-14 04:37:50 +0000115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000116 if (self->ob_exports > 0 && newsize != Py_SIZE(self)) {
117 PyErr_SetString(PyExc_BufferError,
118 "cannot resize an array that is exporting buffers");
119 return -1;
120 }
Antoine Pitrou3ad3a0d2008-12-18 17:08:32 +0000121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000122 /* Bypass realloc() when a previous overallocation is large enough
123 to accommodate the newsize. If the newsize is 16 smaller than the
124 current size, then proceed with the realloc() to shrink the array.
125 */
Raymond Hettinger6e2ee862004-03-14 04:37:50 +0000126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000127 if (self->allocated >= newsize &&
128 Py_SIZE(self) < newsize + 16 &&
129 self->ob_item != NULL) {
130 Py_SIZE(self) = newsize;
131 return 0;
132 }
Raymond Hettinger6e2ee862004-03-14 04:37:50 +0000133
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000134 if (newsize == 0) {
135 PyMem_FREE(self->ob_item);
136 self->ob_item = NULL;
137 Py_SIZE(self) = 0;
138 self->allocated = 0;
139 return 0;
140 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000142 /* This over-allocates proportional to the array size, making room
143 * for additional growth. The over-allocation is mild, but is
144 * enough to give linear-time amortized behavior over a long
145 * sequence of appends() in the presence of a poorly-performing
146 * system realloc().
147 * The growth pattern is: 0, 4, 8, 16, 25, 34, 46, 56, 67, 79, ...
148 * Note, the pattern starts out the same as for lists but then
149 * grows at a smaller rate so that larger arrays only overallocate
150 * by about 1/16th -- this is done because arrays are presumed to be more
151 * memory critical.
152 */
Raymond Hettinger6e2ee862004-03-14 04:37:50 +0000153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000154 _new_size = (newsize >> 4) + (Py_SIZE(self) < 8 ? 3 : 7) + newsize;
155 items = self->ob_item;
156 /* XXX The following multiplication and division does not optimize away
157 like it does for lists since the size is not known at compile time */
158 if (_new_size <= ((~(size_t)0) / self->ob_descr->itemsize))
159 PyMem_RESIZE(items, char, (_new_size * self->ob_descr->itemsize));
160 else
161 items = NULL;
162 if (items == NULL) {
163 PyErr_NoMemory();
164 return -1;
165 }
166 self->ob_item = items;
167 Py_SIZE(self) = newsize;
168 self->allocated = _new_size;
169 return 0;
Raymond Hettinger6e2ee862004-03-14 04:37:50 +0000170}
171
Tim Petersbb307342000-09-10 05:22:54 +0000172/****************************************************************************
173Get and Set functions for each type.
174A Get function takes an arrayobject* and an integer index, returning the
175array value at that index wrapped in an appropriate PyObject*.
176A Set function takes an arrayobject, integer index, and PyObject*; sets
177the array value at that index to the raw C data extracted from the PyObject*,
178and returns 0 if successful, else nonzero on failure (PyObject* not of an
179appropriate type or value).
180Note that the basic Get and Set functions do NOT check that the index is
181in bounds; that's the responsibility of the caller.
182****************************************************************************/
Guido van Rossum778983b1993-02-19 15:55:02 +0000183
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000184static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000185b_getitem(arrayobject *ap, Py_ssize_t i)
Guido van Rossum778983b1993-02-19 15:55:02 +0000186{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000187 long x = ((char *)ap->ob_item)[i];
188 if (x >= 128)
189 x -= 256;
190 return PyLong_FromLong(x);
Guido van Rossum778983b1993-02-19 15:55:02 +0000191}
192
193static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000194b_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
Guido van Rossum778983b1993-02-19 15:55:02 +0000195{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000196 short x;
197 /* PyArg_Parse's 'b' formatter is for an unsigned char, therefore
198 must use the next size up that is signed ('h') and manually do
199 the overflow checking */
200 if (!PyArg_Parse(v, "h;array item must be integer", &x))
201 return -1;
202 else if (x < -128) {
203 PyErr_SetString(PyExc_OverflowError,
204 "signed char is less than minimum");
205 return -1;
206 }
207 else if (x > 127) {
208 PyErr_SetString(PyExc_OverflowError,
209 "signed char is greater than maximum");
210 return -1;
211 }
212 if (i >= 0)
213 ((char *)ap->ob_item)[i] = (char)x;
214 return 0;
Guido van Rossum778983b1993-02-19 15:55:02 +0000215}
216
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000217static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000218BB_getitem(arrayobject *ap, Py_ssize_t i)
Guido van Rossum549ab711997-01-03 19:09:47 +0000219{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000220 long x = ((unsigned char *)ap->ob_item)[i];
221 return PyLong_FromLong(x);
Guido van Rossum549ab711997-01-03 19:09:47 +0000222}
223
Fred Drake541dc3b2000-06-28 17:49:30 +0000224static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000225BB_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
Fred Drake541dc3b2000-06-28 17:49:30 +0000226{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000227 unsigned char x;
228 /* 'B' == unsigned char, maps to PyArg_Parse's 'b' formatter */
229 if (!PyArg_Parse(v, "b;array item must be integer", &x))
230 return -1;
231 if (i >= 0)
232 ((char *)ap->ob_item)[i] = x;
233 return 0;
Fred Drake541dc3b2000-06-28 17:49:30 +0000234}
Guido van Rossum549ab711997-01-03 19:09:47 +0000235
Martin v. Löwis99866332002-03-01 10:27:01 +0000236static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000237u_getitem(arrayobject *ap, Py_ssize_t i)
Martin v. Löwis99866332002-03-01 10:27:01 +0000238{
Victor Stinner62bb3942012-08-06 00:46:05 +0200239 return PyUnicode_FromUnicode(&((Py_UNICODE *) ap->ob_item)[i], 1);
Martin v. Löwis99866332002-03-01 10:27:01 +0000240}
241
242static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000243u_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
Martin v. Löwis99866332002-03-01 10:27:01 +0000244{
Victor Stinner62bb3942012-08-06 00:46:05 +0200245 Py_UNICODE *p;
246 Py_ssize_t len;
Martin v. Löwis99866332002-03-01 10:27:01 +0000247
Victor Stinner62bb3942012-08-06 00:46:05 +0200248 if (!PyArg_Parse(v, "u#;array item must be unicode character", &p, &len))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000249 return -1;
Victor Stinner62bb3942012-08-06 00:46:05 +0200250 if (len != 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000251 PyErr_SetString(PyExc_TypeError,
252 "array item must be unicode character");
253 return -1;
254 }
255 if (i >= 0)
Victor Stinner62bb3942012-08-06 00:46:05 +0200256 ((Py_UNICODE *)ap->ob_item)[i] = p[0];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000257 return 0;
Martin v. Löwis99866332002-03-01 10:27:01 +0000258}
Martin v. Löwis99866332002-03-01 10:27:01 +0000259
Travis E. Oliphantd5c0add2007-10-12 22:05:15 +0000260
Guido van Rossum549ab711997-01-03 19:09:47 +0000261static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000262h_getitem(arrayobject *ap, Py_ssize_t i)
Guido van Rossum778983b1993-02-19 15:55:02 +0000263{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000264 return PyLong_FromLong((long) ((short *)ap->ob_item)[i]);
Guido van Rossum778983b1993-02-19 15:55:02 +0000265}
266
Travis E. Oliphantd5c0add2007-10-12 22:05:15 +0000267
Guido van Rossum778983b1993-02-19 15:55:02 +0000268static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000269h_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
Guido van Rossum778983b1993-02-19 15:55:02 +0000270{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000271 short x;
272 /* 'h' == signed short, maps to PyArg_Parse's 'h' formatter */
273 if (!PyArg_Parse(v, "h;array item must be integer", &x))
274 return -1;
275 if (i >= 0)
276 ((short *)ap->ob_item)[i] = x;
277 return 0;
Guido van Rossum778983b1993-02-19 15:55:02 +0000278}
279
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000280static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000281HH_getitem(arrayobject *ap, Py_ssize_t i)
Guido van Rossum549ab711997-01-03 19:09:47 +0000282{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000283 return PyLong_FromLong((long) ((unsigned short *)ap->ob_item)[i]);
Guido van Rossum549ab711997-01-03 19:09:47 +0000284}
285
Fred Drake541dc3b2000-06-28 17:49:30 +0000286static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000287HH_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
Fred Drake541dc3b2000-06-28 17:49:30 +0000288{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000289 int x;
290 /* PyArg_Parse's 'h' formatter is for a signed short, therefore
291 must use the next size up and manually do the overflow checking */
292 if (!PyArg_Parse(v, "i;array item must be integer", &x))
293 return -1;
294 else if (x < 0) {
295 PyErr_SetString(PyExc_OverflowError,
296 "unsigned short is less than minimum");
297 return -1;
298 }
299 else if (x > USHRT_MAX) {
300 PyErr_SetString(PyExc_OverflowError,
301 "unsigned short is greater than maximum");
302 return -1;
303 }
304 if (i >= 0)
305 ((short *)ap->ob_item)[i] = (short)x;
306 return 0;
Fred Drake541dc3b2000-06-28 17:49:30 +0000307}
Guido van Rossum549ab711997-01-03 19:09:47 +0000308
309static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000310i_getitem(arrayobject *ap, Py_ssize_t i)
Guido van Rossume77a7571993-11-03 15:01:26 +0000311{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000312 return PyLong_FromLong((long) ((int *)ap->ob_item)[i]);
Guido van Rossume77a7571993-11-03 15:01:26 +0000313}
314
315static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000316i_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
Guido van Rossume77a7571993-11-03 15:01:26 +0000317{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000318 int x;
319 /* 'i' == signed int, maps to PyArg_Parse's 'i' formatter */
320 if (!PyArg_Parse(v, "i;array item must be integer", &x))
321 return -1;
322 if (i >= 0)
323 ((int *)ap->ob_item)[i] = x;
324 return 0;
Guido van Rossume77a7571993-11-03 15:01:26 +0000325}
326
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000327static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000328II_getitem(arrayobject *ap, Py_ssize_t i)
Guido van Rossum549ab711997-01-03 19:09:47 +0000329{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 return PyLong_FromUnsignedLong(
331 (unsigned long) ((unsigned int *)ap->ob_item)[i]);
Guido van Rossum549ab711997-01-03 19:09:47 +0000332}
333
334static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000335II_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
Guido van Rossum549ab711997-01-03 19:09:47 +0000336{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000337 unsigned long x;
338 if (PyLong_Check(v)) {
339 x = PyLong_AsUnsignedLong(v);
340 if (x == (unsigned long) -1 && PyErr_Occurred())
341 return -1;
342 }
343 else {
344 long y;
345 if (!PyArg_Parse(v, "l;array item must be integer", &y))
346 return -1;
347 if (y < 0) {
348 PyErr_SetString(PyExc_OverflowError,
349 "unsigned int is less than minimum");
350 return -1;
351 }
352 x = (unsigned long)y;
Tim Petersbb307342000-09-10 05:22:54 +0000353
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000354 }
355 if (x > UINT_MAX) {
356 PyErr_SetString(PyExc_OverflowError,
357 "unsigned int is greater than maximum");
358 return -1;
359 }
Fred Drake541dc3b2000-06-28 17:49:30 +0000360
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000361 if (i >= 0)
362 ((unsigned int *)ap->ob_item)[i] = (unsigned int)x;
363 return 0;
Guido van Rossum549ab711997-01-03 19:09:47 +0000364}
365
366static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000367l_getitem(arrayobject *ap, Py_ssize_t i)
Guido van Rossum778983b1993-02-19 15:55:02 +0000368{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000369 return PyLong_FromLong(((long *)ap->ob_item)[i]);
Guido van Rossum778983b1993-02-19 15:55:02 +0000370}
371
372static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000373l_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
Guido van Rossum778983b1993-02-19 15:55:02 +0000374{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 long x;
376 if (!PyArg_Parse(v, "l;array item must be integer", &x))
377 return -1;
378 if (i >= 0)
379 ((long *)ap->ob_item)[i] = x;
380 return 0;
Guido van Rossum778983b1993-02-19 15:55:02 +0000381}
382
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000383static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000384LL_getitem(arrayobject *ap, Py_ssize_t i)
Guido van Rossum549ab711997-01-03 19:09:47 +0000385{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000386 return PyLong_FromUnsignedLong(((unsigned long *)ap->ob_item)[i]);
Guido van Rossum549ab711997-01-03 19:09:47 +0000387}
388
389static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000390LL_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
Guido van Rossum549ab711997-01-03 19:09:47 +0000391{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000392 unsigned long x;
393 if (PyLong_Check(v)) {
394 x = PyLong_AsUnsignedLong(v);
395 if (x == (unsigned long) -1 && PyErr_Occurred())
396 return -1;
397 }
398 else {
399 long y;
400 if (!PyArg_Parse(v, "l;array item must be integer", &y))
401 return -1;
402 if (y < 0) {
403 PyErr_SetString(PyExc_OverflowError,
404 "unsigned long is less than minimum");
405 return -1;
406 }
407 x = (unsigned long)y;
Tim Petersbb307342000-09-10 05:22:54 +0000408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000409 }
410 if (x > ULONG_MAX) {
411 PyErr_SetString(PyExc_OverflowError,
412 "unsigned long is greater than maximum");
413 return -1;
414 }
Tim Petersbb307342000-09-10 05:22:54 +0000415
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000416 if (i >= 0)
417 ((unsigned long *)ap->ob_item)[i] = x;
418 return 0;
Guido van Rossum549ab711997-01-03 19:09:47 +0000419}
420
Meador Inge1c9f0c92011-09-20 19:55:51 -0500421#ifdef HAVE_LONG_LONG
422
423static PyObject *
424q_getitem(arrayobject *ap, Py_ssize_t i)
425{
426 return PyLong_FromLongLong(((PY_LONG_LONG *)ap->ob_item)[i]);
427}
428
429static int
430q_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
431{
432 PY_LONG_LONG x;
433 if (!PyArg_Parse(v, "L;array item must be integer", &x))
434 return -1;
435 if (i >= 0)
436 ((PY_LONG_LONG *)ap->ob_item)[i] = x;
437 return 0;
438}
439
440static PyObject *
441QQ_getitem(arrayobject *ap, Py_ssize_t i)
442{
443 return PyLong_FromUnsignedLongLong(
444 ((unsigned PY_LONG_LONG *)ap->ob_item)[i]);
445}
446
447static int
448QQ_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
449{
450 unsigned PY_LONG_LONG x;
451 if (PyLong_Check(v)) {
452 x = PyLong_AsUnsignedLongLong(v);
453 if (x == (unsigned PY_LONG_LONG) -1 && PyErr_Occurred())
454 return -1;
455 }
456 else {
457 PY_LONG_LONG y;
458 if (!PyArg_Parse(v, "L;array item must be integer", &y))
459 return -1;
460 if (y < 0) {
461 PyErr_SetString(PyExc_OverflowError,
462 "unsigned long long is less than minimum");
463 return -1;
464 }
465 x = (unsigned PY_LONG_LONG)y;
466 }
467
468 if (i >= 0)
469 ((unsigned PY_LONG_LONG *)ap->ob_item)[i] = x;
470 return 0;
471}
472#endif
473
Guido van Rossum549ab711997-01-03 19:09:47 +0000474static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000475f_getitem(arrayobject *ap, Py_ssize_t i)
Guido van Rossum778983b1993-02-19 15:55:02 +0000476{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 return PyFloat_FromDouble((double) ((float *)ap->ob_item)[i]);
Guido van Rossum778983b1993-02-19 15:55:02 +0000478}
479
480static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000481f_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
Guido van Rossum778983b1993-02-19 15:55:02 +0000482{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 float x;
484 if (!PyArg_Parse(v, "f;array item must be float", &x))
485 return -1;
486 if (i >= 0)
487 ((float *)ap->ob_item)[i] = x;
488 return 0;
Guido van Rossum778983b1993-02-19 15:55:02 +0000489}
490
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000491static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000492d_getitem(arrayobject *ap, Py_ssize_t i)
Guido van Rossum778983b1993-02-19 15:55:02 +0000493{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 return PyFloat_FromDouble(((double *)ap->ob_item)[i]);
Guido van Rossum778983b1993-02-19 15:55:02 +0000495}
496
497static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000498d_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
Guido van Rossum778983b1993-02-19 15:55:02 +0000499{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 double x;
501 if (!PyArg_Parse(v, "d;array item must be float", &x))
502 return -1;
503 if (i >= 0)
504 ((double *)ap->ob_item)[i] = x;
505 return 0;
Guido van Rossum778983b1993-02-19 15:55:02 +0000506}
507
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000508
Alexandre Vassalottiad077152009-07-15 17:49:23 +0000509/* Description of types.
510 *
511 * Don't forget to update typecode_to_mformat_code() if you add a new
512 * typecode.
513 */
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200514static const struct arraydescr descriptors[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000515 {'b', 1, b_getitem, b_setitem, "b", 1, 1},
516 {'B', 1, BB_getitem, BB_setitem, "B", 1, 0},
Victor Stinner62bb3942012-08-06 00:46:05 +0200517 {'u', sizeof(Py_UNICODE), u_getitem, u_setitem, "u", 0, 0},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 {'h', sizeof(short), h_getitem, h_setitem, "h", 1, 1},
519 {'H', sizeof(short), HH_getitem, HH_setitem, "H", 1, 0},
520 {'i', sizeof(int), i_getitem, i_setitem, "i", 1, 1},
521 {'I', sizeof(int), II_getitem, II_setitem, "I", 1, 0},
522 {'l', sizeof(long), l_getitem, l_setitem, "l", 1, 1},
523 {'L', sizeof(long), LL_getitem, LL_setitem, "L", 1, 0},
Meador Inge1c9f0c92011-09-20 19:55:51 -0500524#ifdef HAVE_LONG_LONG
525 {'q', sizeof(PY_LONG_LONG), q_getitem, q_setitem, "q", 1, 1},
526 {'Q', sizeof(PY_LONG_LONG), QQ_getitem, QQ_setitem, "Q", 1, 0},
527#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000528 {'f', sizeof(float), f_getitem, f_setitem, "f", 0, 0},
529 {'d', sizeof(double), d_getitem, d_setitem, "d", 0, 0},
530 {'\0', 0, 0, 0, 0, 0, 0} /* Sentinel */
Guido van Rossum778983b1993-02-19 15:55:02 +0000531};
Tim Petersbb307342000-09-10 05:22:54 +0000532
533/****************************************************************************
534Implementations of array object methods.
535****************************************************************************/
Brett Cannon1eb32c22014-10-10 16:26:45 -0400536/*[clinic input]
537class array.array "arrayobject *" "&Arraytype"
538[clinic start generated code]*/
539/*[clinic end generated code: output=da39a3ee5e6b4b0d input=ad43d37e942a8854]*/
Guido van Rossum778983b1993-02-19 15:55:02 +0000540
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000541static PyObject *
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200542newarrayobject(PyTypeObject *type, Py_ssize_t size, const struct arraydescr *descr)
Guido van Rossum778983b1993-02-19 15:55:02 +0000543{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000544 arrayobject *op;
545 size_t nbytes;
Martin v. Löwis99866332002-03-01 10:27:01 +0000546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000547 if (size < 0) {
548 PyErr_BadInternalCall();
549 return NULL;
550 }
Martin v. Löwis99866332002-03-01 10:27:01 +0000551
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000552 /* Check for overflow */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +0100553 if (size > PY_SSIZE_T_MAX / descr->itemsize) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000554 return PyErr_NoMemory();
555 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +0100556 nbytes = size * descr->itemsize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000557 op = (arrayobject *) type->tp_alloc(type, 0);
558 if (op == NULL) {
559 return NULL;
560 }
561 op->ob_descr = descr;
562 op->allocated = size;
563 op->weakreflist = NULL;
564 Py_SIZE(op) = size;
565 if (size <= 0) {
566 op->ob_item = NULL;
567 }
568 else {
569 op->ob_item = PyMem_NEW(char, nbytes);
570 if (op->ob_item == NULL) {
571 Py_DECREF(op);
572 return PyErr_NoMemory();
573 }
574 }
575 op->ob_exports = 0;
576 return (PyObject *) op;
Guido van Rossum778983b1993-02-19 15:55:02 +0000577}
578
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000579static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000580getarrayitem(PyObject *op, Py_ssize_t i)
Guido van Rossum778983b1993-02-19 15:55:02 +0000581{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200582 arrayobject *ap;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000583 assert(array_Check(op));
584 ap = (arrayobject *)op;
585 assert(i>=0 && i<Py_SIZE(ap));
586 return (*ap->ob_descr->getitem)(ap, i);
Guido van Rossum778983b1993-02-19 15:55:02 +0000587}
588
589static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000590ins1(arrayobject *self, Py_ssize_t where, PyObject *v)
Guido van Rossum778983b1993-02-19 15:55:02 +0000591{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000592 char *items;
593 Py_ssize_t n = Py_SIZE(self);
594 if (v == NULL) {
595 PyErr_BadInternalCall();
596 return -1;
597 }
598 if ((*self->ob_descr->setitem)(self, -1, v) < 0)
599 return -1;
Raymond Hettinger6e2ee862004-03-14 04:37:50 +0000600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000601 if (array_resize(self, n+1) == -1)
602 return -1;
603 items = self->ob_item;
604 if (where < 0) {
605 where += n;
606 if (where < 0)
607 where = 0;
608 }
609 if (where > n)
610 where = n;
611 /* appends don't need to call memmove() */
612 if (where != n)
613 memmove(items + (where+1)*self->ob_descr->itemsize,
614 items + where*self->ob_descr->itemsize,
615 (n-where)*self->ob_descr->itemsize);
616 return (*self->ob_descr->setitem)(self, where, v);
Guido van Rossum778983b1993-02-19 15:55:02 +0000617}
618
Guido van Rossum778983b1993-02-19 15:55:02 +0000619/* Methods */
620
621static void
Peter Schneider-Kamp9656abd2000-07-13 21:10:57 +0000622array_dealloc(arrayobject *op)
Guido van Rossum778983b1993-02-19 15:55:02 +0000623{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000624 if (op->weakreflist != NULL)
625 PyObject_ClearWeakRefs((PyObject *) op);
626 if (op->ob_item != NULL)
627 PyMem_DEL(op->ob_item);
628 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossum778983b1993-02-19 15:55:02 +0000629}
630
Guido van Rossum9d19cb82001-01-18 01:02:55 +0000631static PyObject *
632array_richcompare(PyObject *v, PyObject *w, int op)
Guido van Rossum778983b1993-02-19 15:55:02 +0000633{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 arrayobject *va, *wa;
635 PyObject *vi = NULL;
636 PyObject *wi = NULL;
637 Py_ssize_t i, k;
638 PyObject *res;
Guido van Rossum9d19cb82001-01-18 01:02:55 +0000639
Brian Curtindfc80e32011-08-10 20:28:54 -0500640 if (!array_Check(v) || !array_Check(w))
641 Py_RETURN_NOTIMPLEMENTED;
Guido van Rossum9d19cb82001-01-18 01:02:55 +0000642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000643 va = (arrayobject *)v;
644 wa = (arrayobject *)w;
Guido van Rossum9d19cb82001-01-18 01:02:55 +0000645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 if (Py_SIZE(va) != Py_SIZE(wa) && (op == Py_EQ || op == Py_NE)) {
647 /* Shortcut: if the lengths differ, the arrays differ */
648 if (op == Py_EQ)
649 res = Py_False;
650 else
651 res = Py_True;
652 Py_INCREF(res);
653 return res;
654 }
Guido van Rossum9d19cb82001-01-18 01:02:55 +0000655
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000656 /* Search for the first index where items are different */
657 k = 1;
658 for (i = 0; i < Py_SIZE(va) && i < Py_SIZE(wa); i++) {
659 vi = getarrayitem(v, i);
660 wi = getarrayitem(w, i);
661 if (vi == NULL || wi == NULL) {
662 Py_XDECREF(vi);
663 Py_XDECREF(wi);
664 return NULL;
665 }
666 k = PyObject_RichCompareBool(vi, wi, Py_EQ);
667 if (k == 0)
668 break; /* Keeping vi and wi alive! */
669 Py_DECREF(vi);
670 Py_DECREF(wi);
671 if (k < 0)
672 return NULL;
673 }
Guido van Rossum9d19cb82001-01-18 01:02:55 +0000674
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000675 if (k) {
676 /* No more items to compare -- compare sizes */
677 Py_ssize_t vs = Py_SIZE(va);
678 Py_ssize_t ws = Py_SIZE(wa);
679 int cmp;
680 switch (op) {
681 case Py_LT: cmp = vs < ws; break;
682 case Py_LE: cmp = vs <= ws; break;
683 case Py_EQ: cmp = vs == ws; break;
684 case Py_NE: cmp = vs != ws; break;
685 case Py_GT: cmp = vs > ws; break;
686 case Py_GE: cmp = vs >= ws; break;
687 default: return NULL; /* cannot happen */
688 }
689 if (cmp)
690 res = Py_True;
691 else
692 res = Py_False;
693 Py_INCREF(res);
694 return res;
695 }
Guido van Rossum9d19cb82001-01-18 01:02:55 +0000696
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000697 /* We have an item that differs. First, shortcuts for EQ/NE */
698 if (op == Py_EQ) {
699 Py_INCREF(Py_False);
700 res = Py_False;
701 }
702 else if (op == Py_NE) {
703 Py_INCREF(Py_True);
704 res = Py_True;
705 }
706 else {
707 /* Compare the final item again using the proper operator */
708 res = PyObject_RichCompare(vi, wi, op);
709 }
710 Py_DECREF(vi);
711 Py_DECREF(wi);
712 return res;
Guido van Rossum778983b1993-02-19 15:55:02 +0000713}
714
Martin v. Löwis18e16552006-02-15 17:27:45 +0000715static Py_ssize_t
Peter Schneider-Kamp9656abd2000-07-13 21:10:57 +0000716array_length(arrayobject *a)
Guido van Rossum778983b1993-02-19 15:55:02 +0000717{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 return Py_SIZE(a);
Guido van Rossum778983b1993-02-19 15:55:02 +0000719}
720
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000721static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000722array_item(arrayobject *a, Py_ssize_t i)
Guido van Rossum778983b1993-02-19 15:55:02 +0000723{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000724 if (i < 0 || i >= Py_SIZE(a)) {
725 PyErr_SetString(PyExc_IndexError, "array index out of range");
726 return NULL;
727 }
728 return getarrayitem((PyObject *)a, i);
Guido van Rossum778983b1993-02-19 15:55:02 +0000729}
730
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000731static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000732array_slice(arrayobject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum778983b1993-02-19 15:55:02 +0000733{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000734 arrayobject *np;
735 if (ilow < 0)
736 ilow = 0;
737 else if (ilow > Py_SIZE(a))
738 ilow = Py_SIZE(a);
739 if (ihigh < 0)
740 ihigh = 0;
741 if (ihigh < ilow)
742 ihigh = ilow;
743 else if (ihigh > Py_SIZE(a))
744 ihigh = Py_SIZE(a);
745 np = (arrayobject *) newarrayobject(&Arraytype, ihigh - ilow, a->ob_descr);
746 if (np == NULL)
747 return NULL;
748 memcpy(np->ob_item, a->ob_item + ilow * a->ob_descr->itemsize,
749 (ihigh-ilow) * a->ob_descr->itemsize);
750 return (PyObject *)np;
Guido van Rossum778983b1993-02-19 15:55:02 +0000751}
752
Brett Cannon1eb32c22014-10-10 16:26:45 -0400753
754/*[clinic input]
755array.array.__copy__
756
757Return a copy of the array.
758[clinic start generated code]*/
759
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000760static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -0400761array_array___copy___impl(arrayobject *self)
762/*[clinic end generated code: output=dec7c3f925d9619e input=ad1ee5b086965f09]*/
Raymond Hettinger3aa82c02004-03-13 18:18:51 +0000763{
Brett Cannon1eb32c22014-10-10 16:26:45 -0400764 return array_slice(self, 0, Py_SIZE(self));
Raymond Hettinger3aa82c02004-03-13 18:18:51 +0000765}
766
Brett Cannon1eb32c22014-10-10 16:26:45 -0400767/*[clinic input]
768array.array.__deepcopy__
769
770 unused: object
771 /
772
773Return a copy of the array.
774[clinic start generated code]*/
775
776static PyObject *
777array_array___deepcopy__(arrayobject *self, PyObject *unused)
778/*[clinic end generated code: output=1ec748d8e14a9faa input=2405ecb4933748c4]*/
779{
780 return array_array___copy___impl(self);
781}
Raymond Hettinger3aa82c02004-03-13 18:18:51 +0000782
783static PyObject *
Peter Schneider-Kamp9656abd2000-07-13 21:10:57 +0000784array_concat(arrayobject *a, PyObject *bb)
Guido van Rossum778983b1993-02-19 15:55:02 +0000785{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000786 Py_ssize_t size;
787 arrayobject *np;
788 if (!array_Check(bb)) {
789 PyErr_Format(PyExc_TypeError,
790 "can only append array (not \"%.200s\") to array",
791 Py_TYPE(bb)->tp_name);
792 return NULL;
793 }
Guido van Rossum778983b1993-02-19 15:55:02 +0000794#define b ((arrayobject *)bb)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000795 if (a->ob_descr != b->ob_descr) {
796 PyErr_BadArgument();
797 return NULL;
798 }
799 if (Py_SIZE(a) > PY_SSIZE_T_MAX - Py_SIZE(b)) {
800 return PyErr_NoMemory();
801 }
802 size = Py_SIZE(a) + Py_SIZE(b);
803 np = (arrayobject *) newarrayobject(&Arraytype, size, a->ob_descr);
804 if (np == NULL) {
805 return NULL;
806 }
807 memcpy(np->ob_item, a->ob_item, Py_SIZE(a)*a->ob_descr->itemsize);
808 memcpy(np->ob_item + Py_SIZE(a)*a->ob_descr->itemsize,
809 b->ob_item, Py_SIZE(b)*b->ob_descr->itemsize);
810 return (PyObject *)np;
Guido van Rossum778983b1993-02-19 15:55:02 +0000811#undef b
812}
813
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000814static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000815array_repeat(arrayobject *a, Py_ssize_t n)
Guido van Rossum778983b1993-02-19 15:55:02 +0000816{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000817 Py_ssize_t size;
818 arrayobject *np;
Georg Brandlc29cc6a2010-12-04 11:02:04 +0000819 Py_ssize_t oldbytes, newbytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000820 if (n < 0)
821 n = 0;
822 if ((Py_SIZE(a) != 0) && (n > PY_SSIZE_T_MAX / Py_SIZE(a))) {
823 return PyErr_NoMemory();
824 }
825 size = Py_SIZE(a) * n;
826 np = (arrayobject *) newarrayobject(&Arraytype, size, a->ob_descr);
827 if (np == NULL)
828 return NULL;
Georg Brandlc29cc6a2010-12-04 11:02:04 +0000829 if (n == 0)
830 return (PyObject *)np;
831 oldbytes = Py_SIZE(a) * a->ob_descr->itemsize;
832 newbytes = oldbytes * n;
833 /* this follows the code in unicode_repeat */
834 if (oldbytes == 1) {
835 memset(np->ob_item, a->ob_item[0], newbytes);
836 } else {
837 Py_ssize_t done = oldbytes;
838 Py_MEMCPY(np->ob_item, a->ob_item, oldbytes);
839 while (done < newbytes) {
840 Py_ssize_t ncopy = (done <= newbytes-done) ? done : newbytes-done;
841 Py_MEMCPY(np->ob_item+done, np->ob_item, ncopy);
842 done += ncopy;
843 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000844 }
Georg Brandlc29cc6a2010-12-04 11:02:04 +0000845 return (PyObject *)np;
Guido van Rossum778983b1993-02-19 15:55:02 +0000846}
847
848static int
Martin Panter996d72b2016-07-25 02:21:14 +0000849array_del_slice(arrayobject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum778983b1993-02-19 15:55:02 +0000850{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000851 char *item;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000852 Py_ssize_t d; /* Change in size */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000853 if (ilow < 0)
854 ilow = 0;
855 else if (ilow > Py_SIZE(a))
856 ilow = Py_SIZE(a);
857 if (ihigh < 0)
858 ihigh = 0;
859 if (ihigh < ilow)
860 ihigh = ilow;
861 else if (ihigh > Py_SIZE(a))
862 ihigh = Py_SIZE(a);
863 item = a->ob_item;
Martin Panter996d72b2016-07-25 02:21:14 +0000864 d = ihigh-ilow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000865 /* Issue #4509: If the array has exported buffers and the slice
866 assignment would change the size of the array, fail early to make
867 sure we don't modify it. */
868 if (d != 0 && a->ob_exports > 0) {
869 PyErr_SetString(PyExc_BufferError,
870 "cannot resize an array that is exporting buffers");
871 return -1;
872 }
Martin Panter996d72b2016-07-25 02:21:14 +0000873 if (d > 0) { /* Delete d items */
874 memmove(item + (ihigh-d)*a->ob_descr->itemsize,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000875 item + ihigh*a->ob_descr->itemsize,
876 (Py_SIZE(a)-ihigh)*a->ob_descr->itemsize);
Martin Panter996d72b2016-07-25 02:21:14 +0000877 if (array_resize(a, Py_SIZE(a) - d) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000878 return -1;
879 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 return 0;
Guido van Rossum778983b1993-02-19 15:55:02 +0000881}
882
883static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000884array_ass_item(arrayobject *a, Py_ssize_t i, PyObject *v)
Guido van Rossum778983b1993-02-19 15:55:02 +0000885{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 if (i < 0 || i >= Py_SIZE(a)) {
887 PyErr_SetString(PyExc_IndexError,
888 "array assignment index out of range");
889 return -1;
890 }
891 if (v == NULL)
Martin Panter996d72b2016-07-25 02:21:14 +0000892 return array_del_slice(a, i, i+1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000893 return (*a->ob_descr->setitem)(a, i, v);
Guido van Rossum778983b1993-02-19 15:55:02 +0000894}
895
896static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000897setarrayitem(PyObject *a, Py_ssize_t i, PyObject *v)
Guido van Rossum778983b1993-02-19 15:55:02 +0000898{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000899 assert(array_Check(a));
900 return array_ass_item((arrayobject *)a, i, v);
Guido van Rossum778983b1993-02-19 15:55:02 +0000901}
902
Martin v. Löwis99866332002-03-01 10:27:01 +0000903static int
Raymond Hettinger49f9bd12004-03-14 05:43:59 +0000904array_iter_extend(arrayobject *self, PyObject *bb)
905{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 PyObject *it, *v;
Raymond Hettinger49f9bd12004-03-14 05:43:59 +0000907
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000908 it = PyObject_GetIter(bb);
909 if (it == NULL)
910 return -1;
Raymond Hettinger49f9bd12004-03-14 05:43:59 +0000911
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000912 while ((v = PyIter_Next(it)) != NULL) {
Mark Dickinson346f0af2010-08-06 09:36:57 +0000913 if (ins1(self, Py_SIZE(self), v) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 Py_DECREF(v);
915 Py_DECREF(it);
916 return -1;
917 }
918 Py_DECREF(v);
919 }
920 Py_DECREF(it);
921 if (PyErr_Occurred())
922 return -1;
923 return 0;
Raymond Hettinger49f9bd12004-03-14 05:43:59 +0000924}
925
926static int
Martin v. Löwis99866332002-03-01 10:27:01 +0000927array_do_extend(arrayobject *self, PyObject *bb)
928{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000929 Py_ssize_t size, oldsize, bbsize;
Martin v. Löwis99866332002-03-01 10:27:01 +0000930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 if (!array_Check(bb))
932 return array_iter_extend(self, bb);
933#define b ((arrayobject *)bb)
934 if (self->ob_descr != b->ob_descr) {
935 PyErr_SetString(PyExc_TypeError,
936 "can only extend with array of same kind");
937 return -1;
938 }
939 if ((Py_SIZE(self) > PY_SSIZE_T_MAX - Py_SIZE(b)) ||
940 ((Py_SIZE(self) + Py_SIZE(b)) > PY_SSIZE_T_MAX / self->ob_descr->itemsize)) {
941 PyErr_NoMemory();
942 return -1;
943 }
944 oldsize = Py_SIZE(self);
945 /* Get the size of bb before resizing the array since bb could be self. */
946 bbsize = Py_SIZE(bb);
947 size = oldsize + Py_SIZE(b);
948 if (array_resize(self, size) == -1)
949 return -1;
950 memcpy(self->ob_item + oldsize * self->ob_descr->itemsize,
951 b->ob_item, bbsize * b->ob_descr->itemsize);
952
953 return 0;
Martin v. Löwis99866332002-03-01 10:27:01 +0000954#undef b
955}
956
957static PyObject *
958array_inplace_concat(arrayobject *self, PyObject *bb)
959{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 if (!array_Check(bb)) {
961 PyErr_Format(PyExc_TypeError,
962 "can only extend array with array (not \"%.200s\")",
963 Py_TYPE(bb)->tp_name);
964 return NULL;
965 }
966 if (array_do_extend(self, bb) == -1)
967 return NULL;
968 Py_INCREF(self);
969 return (PyObject *)self;
Martin v. Löwis99866332002-03-01 10:27:01 +0000970}
971
972static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000973array_inplace_repeat(arrayobject *self, Py_ssize_t n)
Martin v. Löwis99866332002-03-01 10:27:01 +0000974{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000975 char *items, *p;
976 Py_ssize_t size, i;
Martin v. Löwis99866332002-03-01 10:27:01 +0000977
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 if (Py_SIZE(self) > 0) {
979 if (n < 0)
980 n = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000981 if ((self->ob_descr->itemsize != 0) &&
982 (Py_SIZE(self) > PY_SSIZE_T_MAX / self->ob_descr->itemsize)) {
983 return PyErr_NoMemory();
984 }
985 size = Py_SIZE(self) * self->ob_descr->itemsize;
986 if (n > 0 && size > PY_SSIZE_T_MAX / n) {
987 return PyErr_NoMemory();
988 }
989 if (array_resize(self, n * Py_SIZE(self)) == -1)
990 return NULL;
991 items = p = self->ob_item;
992 for (i = 1; i < n; i++) {
993 p += size;
994 memcpy(p, items, size);
995 }
996 }
997 Py_INCREF(self);
998 return (PyObject *)self;
Martin v. Löwis99866332002-03-01 10:27:01 +0000999}
1000
1001
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001002static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001003ins(arrayobject *self, Py_ssize_t where, PyObject *v)
Guido van Rossum778983b1993-02-19 15:55:02 +00001004{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 if (ins1(self, where, v) != 0)
1006 return NULL;
1007 Py_INCREF(Py_None);
1008 return Py_None;
Guido van Rossum778983b1993-02-19 15:55:02 +00001009}
1010
Brett Cannon1eb32c22014-10-10 16:26:45 -04001011/*[clinic input]
1012array.array.count
1013
1014 v: object
1015 /
1016
1017Return number of occurrences of v in the array.
1018[clinic start generated code]*/
1019
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001020static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001021array_array_count(arrayobject *self, PyObject *v)
1022/*[clinic end generated code: output=3dd3624bf7135a3a input=d9bce9d65e39d1f5]*/
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001023{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001024 Py_ssize_t count = 0;
1025 Py_ssize_t i;
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001026
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 for (i = 0; i < Py_SIZE(self); i++) {
Victor Stinner0b142e22013-07-17 23:01:30 +02001028 PyObject *selfi;
1029 int cmp;
1030
1031 selfi = getarrayitem((PyObject *)self, i);
1032 if (selfi == NULL)
1033 return NULL;
1034 cmp = PyObject_RichCompareBool(selfi, v, Py_EQ);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001035 Py_DECREF(selfi);
1036 if (cmp > 0)
1037 count++;
1038 else if (cmp < 0)
1039 return NULL;
1040 }
1041 return PyLong_FromSsize_t(count);
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001042}
1043
Brett Cannon1eb32c22014-10-10 16:26:45 -04001044
1045/*[clinic input]
1046array.array.index
1047
1048 v: object
1049 /
1050
1051Return index of first occurrence of v in the array.
1052[clinic start generated code]*/
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001053
1054static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001055array_array_index(arrayobject *self, PyObject *v)
1056/*[clinic end generated code: output=d48498d325602167 input=cf619898c6649d08]*/
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001057{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001058 Py_ssize_t i;
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001060 for (i = 0; i < Py_SIZE(self); i++) {
Victor Stinner0b142e22013-07-17 23:01:30 +02001061 PyObject *selfi;
1062 int cmp;
1063
1064 selfi = getarrayitem((PyObject *)self, i);
1065 if (selfi == NULL)
1066 return NULL;
1067 cmp = PyObject_RichCompareBool(selfi, v, Py_EQ);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001068 Py_DECREF(selfi);
1069 if (cmp > 0) {
1070 return PyLong_FromLong((long)i);
1071 }
1072 else if (cmp < 0)
1073 return NULL;
1074 }
1075 PyErr_SetString(PyExc_ValueError, "array.index(x): x not in list");
1076 return NULL;
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001077}
1078
Raymond Hettinger625812f2003-01-07 01:58:52 +00001079static int
1080array_contains(arrayobject *self, PyObject *v)
1081{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 Py_ssize_t i;
1083 int cmp;
Raymond Hettinger625812f2003-01-07 01:58:52 +00001084
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001085 for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(self); i++) {
1086 PyObject *selfi = getarrayitem((PyObject *)self, i);
Victor Stinner0b142e22013-07-17 23:01:30 +02001087 if (selfi == NULL)
Victor Stinner4755bea2013-07-18 01:12:35 +02001088 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001089 cmp = PyObject_RichCompareBool(selfi, v, Py_EQ);
1090 Py_DECREF(selfi);
1091 }
1092 return cmp;
Raymond Hettinger625812f2003-01-07 01:58:52 +00001093}
1094
Brett Cannon1eb32c22014-10-10 16:26:45 -04001095/*[clinic input]
1096array.array.remove
1097
1098 v: object
1099 /
1100
1101Remove the first occurrence of v in the array.
1102[clinic start generated code]*/
1103
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001104static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001105array_array_remove(arrayobject *self, PyObject *v)
1106/*[clinic end generated code: output=bef06be9fdf9dceb input=0b1e5aed25590027]*/
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001107{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001108 int i;
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001110 for (i = 0; i < Py_SIZE(self); i++) {
Victor Stinner0b142e22013-07-17 23:01:30 +02001111 PyObject *selfi;
1112 int cmp;
1113
1114 selfi = getarrayitem((PyObject *)self,i);
1115 if (selfi == NULL)
1116 return NULL;
1117 cmp = PyObject_RichCompareBool(selfi, v, Py_EQ);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001118 Py_DECREF(selfi);
1119 if (cmp > 0) {
Martin Panter996d72b2016-07-25 02:21:14 +00001120 if (array_del_slice(self, i, i+1) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001121 return NULL;
1122 Py_INCREF(Py_None);
1123 return Py_None;
1124 }
1125 else if (cmp < 0)
1126 return NULL;
1127 }
1128 PyErr_SetString(PyExc_ValueError, "array.remove(x): x not in list");
1129 return NULL;
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001130}
1131
Brett Cannon1eb32c22014-10-10 16:26:45 -04001132/*[clinic input]
1133array.array.pop
1134
1135 i: Py_ssize_t = -1
1136 /
1137
1138Return the i-th element and delete it from the array.
1139
1140i defaults to -1.
1141[clinic start generated code]*/
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001142
1143static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001144array_array_pop_impl(arrayobject *self, Py_ssize_t i)
1145/*[clinic end generated code: output=bc1f0c54fe5308e4 input=8e5feb4c1a11cd44]*/
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001146{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001147 PyObject *v;
Brett Cannon1eb32c22014-10-10 16:26:45 -04001148
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001149 if (Py_SIZE(self) == 0) {
1150 /* Special-case most common failure cause */
1151 PyErr_SetString(PyExc_IndexError, "pop from empty array");
1152 return NULL;
1153 }
1154 if (i < 0)
1155 i += Py_SIZE(self);
1156 if (i < 0 || i >= Py_SIZE(self)) {
1157 PyErr_SetString(PyExc_IndexError, "pop index out of range");
1158 return NULL;
1159 }
Victor Stinner0b142e22013-07-17 23:01:30 +02001160 v = getarrayitem((PyObject *)self, i);
1161 if (v == NULL)
1162 return NULL;
Martin Panter996d72b2016-07-25 02:21:14 +00001163 if (array_del_slice(self, i, i+1) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001164 Py_DECREF(v);
1165 return NULL;
1166 }
1167 return v;
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001168}
1169
Brett Cannon1eb32c22014-10-10 16:26:45 -04001170/*[clinic input]
1171array.array.extend
1172
1173 bb: object
1174 /
1175
1176Append items to the end of the array.
1177[clinic start generated code]*/
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001178
1179static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001180array_array_extend(arrayobject *self, PyObject *bb)
1181/*[clinic end generated code: output=bbddbc8e8bef871d input=43be86aba5c31e44]*/
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001182{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 if (array_do_extend(self, bb) == -1)
1184 return NULL;
1185 Py_INCREF(Py_None);
1186 return Py_None;
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001187}
1188
Brett Cannon1eb32c22014-10-10 16:26:45 -04001189/*[clinic input]
1190array.array.insert
1191
1192 i: Py_ssize_t
1193 v: object
1194 /
1195
1196Insert a new item v into the array before position i.
1197[clinic start generated code]*/
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001198
1199static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001200array_array_insert_impl(arrayobject *self, Py_ssize_t i, PyObject *v)
1201/*[clinic end generated code: output=5a3648e278348564 input=5577d1b4383e9313]*/
Guido van Rossum778983b1993-02-19 15:55:02 +00001202{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001203 return ins(self, i, v);
Guido van Rossum778983b1993-02-19 15:55:02 +00001204}
1205
Brett Cannon1eb32c22014-10-10 16:26:45 -04001206/*[clinic input]
1207array.array.buffer_info
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001208
Brett Cannon1eb32c22014-10-10 16:26:45 -04001209Return a tuple (address, length) giving the current memory address and the length in items of the buffer used to hold array's contents.
1210
1211The length should be multiplied by the itemsize attribute to calculate
1212the buffer length in bytes.
1213[clinic start generated code]*/
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001214
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001215static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001216array_array_buffer_info_impl(arrayobject *self)
1217/*[clinic end generated code: output=9b2a4ec3ae7e98e7 input=a58bae5c6e1ac6a6]*/
Guido van Rossumde4a4ca1997-08-12 14:55:56 +00001218{
Victor Stinner541067a2013-11-14 01:27:12 +01001219 PyObject *retval = NULL, *v;
1220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001221 retval = PyTuple_New(2);
1222 if (!retval)
1223 return NULL;
Fred Drake541dc3b2000-06-28 17:49:30 +00001224
Victor Stinner541067a2013-11-14 01:27:12 +01001225 v = PyLong_FromVoidPtr(self->ob_item);
1226 if (v == NULL) {
1227 Py_DECREF(retval);
1228 return NULL;
1229 }
1230 PyTuple_SET_ITEM(retval, 0, v);
1231
Serhiy Storchaka9e941d62016-06-23 23:55:34 +03001232 v = PyLong_FromSsize_t(Py_SIZE(self));
Victor Stinner541067a2013-11-14 01:27:12 +01001233 if (v == NULL) {
1234 Py_DECREF(retval);
1235 return NULL;
1236 }
1237 PyTuple_SET_ITEM(retval, 1, v);
Fred Drake541dc3b2000-06-28 17:49:30 +00001238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001239 return retval;
Guido van Rossumde4a4ca1997-08-12 14:55:56 +00001240}
1241
Brett Cannon1eb32c22014-10-10 16:26:45 -04001242/*[clinic input]
1243array.array.append
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001244
Brett Cannon1eb32c22014-10-10 16:26:45 -04001245 v: object
1246 /
1247
1248Append new value v to the end of the array.
1249[clinic start generated code]*/
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001250
Guido van Rossumde4a4ca1997-08-12 14:55:56 +00001251static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001252array_array_append(arrayobject *self, PyObject *v)
1253/*[clinic end generated code: output=745a0669bf8db0e2 input=0b98d9d78e78f0fa]*/
Guido van Rossum778983b1993-02-19 15:55:02 +00001254{
Mark Dickinson346f0af2010-08-06 09:36:57 +00001255 return ins(self, Py_SIZE(self), v);
Guido van Rossum778983b1993-02-19 15:55:02 +00001256}
1257
Brett Cannon1eb32c22014-10-10 16:26:45 -04001258/*[clinic input]
1259array.array.byteswap
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001260
Brett Cannon1eb32c22014-10-10 16:26:45 -04001261Byteswap all items of the array.
1262
1263If the items in the array are not 1, 2, 4, or 8 bytes in size, RuntimeError is
1264raised.
1265[clinic start generated code]*/
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001266
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001267static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001268array_array_byteswap_impl(arrayobject *self)
1269/*[clinic end generated code: output=5f8236cbdf0d90b5 input=6a85591b950a0186]*/
Guido van Rossum778983b1993-02-19 15:55:02 +00001270{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001271 char *p;
1272 Py_ssize_t i;
Fred Drakebf272981999-12-03 17:15:30 +00001273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001274 switch (self->ob_descr->itemsize) {
1275 case 1:
1276 break;
1277 case 2:
1278 for (p = self->ob_item, i = Py_SIZE(self); --i >= 0; p += 2) {
1279 char p0 = p[0];
1280 p[0] = p[1];
1281 p[1] = p0;
1282 }
1283 break;
1284 case 4:
1285 for (p = self->ob_item, i = Py_SIZE(self); --i >= 0; p += 4) {
1286 char p0 = p[0];
1287 char p1 = p[1];
1288 p[0] = p[3];
1289 p[1] = p[2];
1290 p[2] = p1;
1291 p[3] = p0;
1292 }
1293 break;
1294 case 8:
1295 for (p = self->ob_item, i = Py_SIZE(self); --i >= 0; p += 8) {
1296 char p0 = p[0];
1297 char p1 = p[1];
1298 char p2 = p[2];
1299 char p3 = p[3];
1300 p[0] = p[7];
1301 p[1] = p[6];
1302 p[2] = p[5];
1303 p[3] = p[4];
1304 p[4] = p3;
1305 p[5] = p2;
1306 p[6] = p1;
1307 p[7] = p0;
1308 }
1309 break;
1310 default:
1311 PyErr_SetString(PyExc_RuntimeError,
1312 "don't know how to byteswap this array type");
1313 return NULL;
1314 }
1315 Py_INCREF(Py_None);
1316 return Py_None;
Guido van Rossum778983b1993-02-19 15:55:02 +00001317}
1318
Brett Cannon1eb32c22014-10-10 16:26:45 -04001319/*[clinic input]
1320array.array.reverse
1321
1322Reverse the order of the items in the array.
1323[clinic start generated code]*/
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001324
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001325static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001326array_array_reverse_impl(arrayobject *self)
1327/*[clinic end generated code: output=c04868b36f6f4089 input=cd904f01b27d966a]*/
Guido van Rossum778983b1993-02-19 15:55:02 +00001328{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001329 Py_ssize_t itemsize = self->ob_descr->itemsize;
1330 char *p, *q;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001331 /* little buffer to hold items while swapping */
1332 char tmp[256]; /* 8 is probably enough -- but why skimp */
1333 assert((size_t)itemsize <= sizeof(tmp));
Guido van Rossume77a7571993-11-03 15:01:26 +00001334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001335 if (Py_SIZE(self) > 1) {
1336 for (p = self->ob_item,
1337 q = self->ob_item + (Py_SIZE(self) - 1)*itemsize;
1338 p < q;
1339 p += itemsize, q -= itemsize) {
1340 /* memory areas guaranteed disjoint, so memcpy
1341 * is safe (& memmove may be slower).
1342 */
1343 memcpy(tmp, p, itemsize);
1344 memcpy(p, q, itemsize);
1345 memcpy(q, tmp, itemsize);
1346 }
1347 }
Tim Petersbb307342000-09-10 05:22:54 +00001348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001349 Py_INCREF(Py_None);
1350 return Py_None;
Guido van Rossum778983b1993-02-19 15:55:02 +00001351}
Guido van Rossume77a7571993-11-03 15:01:26 +00001352
Brett Cannon1eb32c22014-10-10 16:26:45 -04001353/*[clinic input]
1354array.array.fromfile
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001355
Brett Cannon1eb32c22014-10-10 16:26:45 -04001356 f: object
1357 n: Py_ssize_t
1358 /
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001359
Brett Cannon1eb32c22014-10-10 16:26:45 -04001360Read n objects from the file object f and append them to the end of the array.
1361[clinic start generated code]*/
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001362
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001363static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001364array_array_fromfile_impl(arrayobject *self, PyObject *f, Py_ssize_t n)
1365/*[clinic end generated code: output=ec9f600e10f53510 input=e188afe8e58adf40]*/
Guido van Rossum778983b1993-02-19 15:55:02 +00001366{
Serhiy Storchaka04e6dba2015-04-04 17:06:55 +03001367 PyObject *b, *res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001368 Py_ssize_t itemsize = self->ob_descr->itemsize;
Brett Cannon1eb32c22014-10-10 16:26:45 -04001369 Py_ssize_t nbytes;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001370 _Py_IDENTIFIER(read);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001371 int not_enough_bytes;
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001372
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01001373 if (n < 0) {
1374 PyErr_SetString(PyExc_ValueError, "negative count");
1375 return NULL;
1376 }
1377 if (n > PY_SSIZE_T_MAX / itemsize) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001378 PyErr_NoMemory();
1379 return NULL;
1380 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01001381 nbytes = n * itemsize;
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001382
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001383 b = _PyObject_CallMethodId(f, &PyId_read, "n", nbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001384 if (b == NULL)
1385 return NULL;
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001387 if (!PyBytes_Check(b)) {
1388 PyErr_SetString(PyExc_TypeError,
1389 "read() didn't return bytes");
1390 Py_DECREF(b);
1391 return NULL;
1392 }
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001394 not_enough_bytes = (PyBytes_GET_SIZE(b) != nbytes);
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001395
Serhiy Storchaka04e6dba2015-04-04 17:06:55 +03001396 res = array_array_frombytes(self, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001397 Py_DECREF(b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001398 if (res == NULL)
1399 return NULL;
Hirokazu Yamamoto54d0df62009-03-06 03:04:07 +00001400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001401 if (not_enough_bytes) {
1402 PyErr_SetString(PyExc_EOFError,
1403 "read() didn't return enough bytes");
1404 Py_DECREF(res);
1405 return NULL;
1406 }
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001408 return res;
Guido van Rossum778983b1993-02-19 15:55:02 +00001409}
1410
Brett Cannon1eb32c22014-10-10 16:26:45 -04001411/*[clinic input]
1412array.array.tofile
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001413
Brett Cannon1eb32c22014-10-10 16:26:45 -04001414 f: object
1415 /
1416
1417Write all items (as machine values) to the file object f.
1418[clinic start generated code]*/
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001419
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001420static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001421array_array_tofile(arrayobject *self, PyObject *f)
1422/*[clinic end generated code: output=3a2cfa8128df0777 input=b0669a484aab0831]*/
Guido van Rossum778983b1993-02-19 15:55:02 +00001423{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001424 Py_ssize_t nbytes = Py_SIZE(self) * self->ob_descr->itemsize;
1425 /* Write 64K blocks at a time */
1426 /* XXX Make the block size settable */
1427 int BLOCKSIZE = 64*1024;
1428 Py_ssize_t nblocks = (nbytes + BLOCKSIZE - 1) / BLOCKSIZE;
1429 Py_ssize_t i;
Raymond Hettinger36cd2bf2003-01-03 08:24:58 +00001430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001431 if (Py_SIZE(self) == 0)
1432 goto done;
Guido van Rossumb5ddcfd2007-04-11 17:08:28 +00001433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001434 for (i = 0; i < nblocks; i++) {
1435 char* ptr = self->ob_item + i*BLOCKSIZE;
1436 Py_ssize_t size = BLOCKSIZE;
1437 PyObject *bytes, *res;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001438 _Py_IDENTIFIER(write);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001440 if (i*BLOCKSIZE + size > nbytes)
1441 size = nbytes - i*BLOCKSIZE;
1442 bytes = PyBytes_FromStringAndSize(ptr, size);
1443 if (bytes == NULL)
1444 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001445 res = _PyObject_CallMethodId(f, &PyId_write, "O", bytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001446 Py_DECREF(bytes);
1447 if (res == NULL)
1448 return NULL;
1449 Py_DECREF(res); /* drop write result */
1450 }
Guido van Rossumb5ddcfd2007-04-11 17:08:28 +00001451
1452 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001453 Py_INCREF(Py_None);
1454 return Py_None;
Guido van Rossum778983b1993-02-19 15:55:02 +00001455}
1456
Brett Cannon1eb32c22014-10-10 16:26:45 -04001457/*[clinic input]
1458array.array.fromlist
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001459
Brett Cannon1eb32c22014-10-10 16:26:45 -04001460 list: object
1461 /
1462
1463Append items to array from list.
1464[clinic start generated code]*/
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001465
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001466static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001467array_array_fromlist(arrayobject *self, PyObject *list)
1468/*[clinic end generated code: output=26411c2d228a3e3f input=be2605a96c49680f]*/
Guido van Rossum778983b1993-02-19 15:55:02 +00001469{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001470 Py_ssize_t n;
Raymond Hettinger36cd2bf2003-01-03 08:24:58 +00001471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001472 if (!PyList_Check(list)) {
1473 PyErr_SetString(PyExc_TypeError, "arg must be list");
1474 return NULL;
1475 }
1476 n = PyList_Size(list);
1477 if (n > 0) {
1478 Py_ssize_t i, old_size;
1479 old_size = Py_SIZE(self);
1480 if (array_resize(self, old_size + n) == -1)
1481 return NULL;
1482 for (i = 0; i < n; i++) {
1483 PyObject *v = PyList_GetItem(list, i);
1484 if ((*self->ob_descr->setitem)(self,
1485 Py_SIZE(self) - n + i, v) != 0) {
1486 array_resize(self, old_size);
1487 return NULL;
1488 }
1489 }
1490 }
1491 Py_INCREF(Py_None);
1492 return Py_None;
Guido van Rossum778983b1993-02-19 15:55:02 +00001493}
1494
Brett Cannon1eb32c22014-10-10 16:26:45 -04001495/*[clinic input]
1496array.array.tolist
1497
1498Convert array to an ordinary list with the same items.
1499[clinic start generated code]*/
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001500
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001501static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001502array_array_tolist_impl(arrayobject *self)
1503/*[clinic end generated code: output=00b60cc9eab8ef89 input=a8d7784a94f86b53]*/
Guido van Rossum778983b1993-02-19 15:55:02 +00001504{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001505 PyObject *list = PyList_New(Py_SIZE(self));
1506 Py_ssize_t i;
Raymond Hettinger36cd2bf2003-01-03 08:24:58 +00001507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001508 if (list == NULL)
1509 return NULL;
1510 for (i = 0; i < Py_SIZE(self); i++) {
1511 PyObject *v = getarrayitem((PyObject *)self, i);
Victor Stinner4755bea2013-07-18 01:12:35 +02001512 if (v == NULL)
1513 goto error;
1514 if (PyList_SetItem(list, i, v) < 0)
1515 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001516 }
1517 return list;
Victor Stinner4755bea2013-07-18 01:12:35 +02001518
1519error:
1520 Py_DECREF(list);
1521 return NULL;
Guido van Rossum778983b1993-02-19 15:55:02 +00001522}
1523
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001524static PyObject *
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001525frombytes(arrayobject *self, Py_buffer *buffer)
Guido van Rossum778983b1993-02-19 15:55:02 +00001526{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001527 int itemsize = self->ob_descr->itemsize;
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001528 Py_ssize_t n;
1529 if (buffer->itemsize != 1) {
1530 PyBuffer_Release(buffer);
Serhiy Storchakab757c832014-12-05 22:25:22 +02001531 PyErr_SetString(PyExc_TypeError, "a bytes-like object is required");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001532 return NULL;
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001533 }
1534 n = buffer->len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001535 if (n % itemsize != 0) {
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001536 PyBuffer_Release(buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001537 PyErr_SetString(PyExc_ValueError,
Serhiy Storchakab757c832014-12-05 22:25:22 +02001538 "bytes length not a multiple of item size");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001539 return NULL;
1540 }
1541 n = n / itemsize;
1542 if (n > 0) {
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001543 Py_ssize_t old_size = Py_SIZE(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001544 if ((n > PY_SSIZE_T_MAX - old_size) ||
1545 ((old_size + n) > PY_SSIZE_T_MAX / itemsize)) {
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001546 PyBuffer_Release(buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001547 return PyErr_NoMemory();
1548 }
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001549 if (array_resize(self, old_size + n) == -1) {
1550 PyBuffer_Release(buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001551 return NULL;
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001552 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001553 memcpy(self->ob_item + old_size * itemsize,
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001554 buffer->buf, n * itemsize);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001555 }
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001556 PyBuffer_Release(buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001557 Py_INCREF(Py_None);
1558 return Py_None;
Guido van Rossum778983b1993-02-19 15:55:02 +00001559}
1560
Brett Cannon1eb32c22014-10-10 16:26:45 -04001561/*[clinic input]
1562array.array.fromstring
1563
Larry Hastingsdbfdc382015-05-04 06:59:46 -07001564 buffer: Py_buffer(accept={str, buffer})
Brett Cannon1eb32c22014-10-10 16:26:45 -04001565 /
1566
1567Appends 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).
1568
1569This method is deprecated. Use frombytes instead.
1570[clinic start generated code]*/
1571
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001572static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001573array_array_fromstring_impl(arrayobject *self, Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07001574/*[clinic end generated code: output=31c4baa779df84ce input=a3341a512e11d773]*/
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001575{
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001576 if (PyErr_WarnEx(PyExc_DeprecationWarning,
1577 "fromstring() is deprecated. Use frombytes() instead.", 2) != 0)
1578 return NULL;
Brett Cannon1eb32c22014-10-10 16:26:45 -04001579 return frombytes(self, buffer);
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001580}
1581
Brett Cannon1eb32c22014-10-10 16:26:45 -04001582/*[clinic input]
1583array.array.frombytes
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001584
Brett Cannon1eb32c22014-10-10 16:26:45 -04001585 buffer: Py_buffer
1586 /
1587
1588Appends 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).
1589[clinic start generated code]*/
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001590
1591static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001592array_array_frombytes_impl(arrayobject *self, Py_buffer *buffer)
1593/*[clinic end generated code: output=d9842c8f7510a516 input=2bbf2b53ebfcc988]*/
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001594{
Brett Cannon1eb32c22014-10-10 16:26:45 -04001595 return frombytes(self, buffer);
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001596}
1597
Brett Cannon1eb32c22014-10-10 16:26:45 -04001598/*[clinic input]
1599array.array.tobytes
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001600
Brett Cannon1eb32c22014-10-10 16:26:45 -04001601Convert the array to an array of machine values and return the bytes representation.
1602[clinic start generated code]*/
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001603
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001604static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001605array_array_tobytes_impl(arrayobject *self)
1606/*[clinic end generated code: output=87318e4edcdc2bb6 input=90ee495f96de34f5]*/
Guido van Rossum778983b1993-02-19 15:55:02 +00001607{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001608 if (Py_SIZE(self) <= PY_SSIZE_T_MAX / self->ob_descr->itemsize) {
1609 return PyBytes_FromStringAndSize(self->ob_item,
1610 Py_SIZE(self) * self->ob_descr->itemsize);
1611 } else {
1612 return PyErr_NoMemory();
1613 }
Guido van Rossum778983b1993-02-19 15:55:02 +00001614}
1615
Brett Cannon1eb32c22014-10-10 16:26:45 -04001616/*[clinic input]
1617array.array.tostring
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001618
Brett Cannon1eb32c22014-10-10 16:26:45 -04001619Convert the array to an array of machine values and return the bytes representation.
1620
1621This method is deprecated. Use tobytes instead.
1622[clinic start generated code]*/
Martin v. Löwis99866332002-03-01 10:27:01 +00001623
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001624static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001625array_array_tostring_impl(arrayobject *self)
1626/*[clinic end generated code: output=7d6bd92745a2c8f3 input=b6c0ddee7b30457e]*/
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001627{
Victor Stinner9f0b51e2010-11-09 09:38:30 +00001628 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001629 "tostring() is deprecated. Use tobytes() instead.", 2) != 0)
1630 return NULL;
Brett Cannon1eb32c22014-10-10 16:26:45 -04001631 return array_array_tobytes_impl(self);
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001632}
1633
Brett Cannon1eb32c22014-10-10 16:26:45 -04001634/*[clinic input]
1635array.array.fromunicode
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001636
Larry Hastings38337d12015-05-07 23:30:09 -07001637 ustr: Py_UNICODE(zeroes=True)
Brett Cannon1eb32c22014-10-10 16:26:45 -04001638 /
1639
1640Extends this array with data from the unicode string ustr.
1641
1642The array must be a unicode type array; otherwise a ValueError is raised.
1643Use array.frombytes(ustr.encode(...)) to append Unicode data to an array of
1644some other type.
1645[clinic start generated code]*/
Martin v. Löwis99866332002-03-01 10:27:01 +00001646
Martin v. Löwis99866332002-03-01 10:27:01 +00001647static PyObject *
Larry Hastings89964c42015-04-14 18:07:59 -04001648array_array_fromunicode_impl(arrayobject *self, Py_UNICODE *ustr,
1649 Py_ssize_clean_t ustr_length)
Larry Hastings38337d12015-05-07 23:30:09 -07001650/*[clinic end generated code: output=ebb72fc16975e06d input=150f00566ffbca6e]*/
Martin v. Löwis99866332002-03-01 10:27:01 +00001651{
Victor Stinner62bb3942012-08-06 00:46:05 +02001652 char typecode;
Martin v. Löwis99866332002-03-01 10:27:01 +00001653
Victor Stinner62bb3942012-08-06 00:46:05 +02001654 typecode = self->ob_descr->typecode;
Gregory P. Smith9504b132012-12-10 20:20:20 -08001655 if (typecode != 'u') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001656 PyErr_SetString(PyExc_ValueError,
1657 "fromunicode() may only be called on "
1658 "unicode type arrays");
1659 return NULL;
1660 }
Brett Cannon1eb32c22014-10-10 16:26:45 -04001661 if (ustr_length > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001662 Py_ssize_t old_size = Py_SIZE(self);
Brett Cannon1eb32c22014-10-10 16:26:45 -04001663 if (array_resize(self, old_size + ustr_length) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001664 return NULL;
Victor Stinner62bb3942012-08-06 00:46:05 +02001665 memcpy(self->ob_item + old_size * sizeof(Py_UNICODE),
Brett Cannon1eb32c22014-10-10 16:26:45 -04001666 ustr, ustr_length * sizeof(Py_UNICODE));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001667 }
Martin v. Löwis99866332002-03-01 10:27:01 +00001668
Brett Cannon1eb32c22014-10-10 16:26:45 -04001669 Py_RETURN_NONE;
Martin v. Löwis99866332002-03-01 10:27:01 +00001670}
1671
Brett Cannon1eb32c22014-10-10 16:26:45 -04001672/*[clinic input]
1673array.array.tounicode
Martin v. Löwis99866332002-03-01 10:27:01 +00001674
Brett Cannon1eb32c22014-10-10 16:26:45 -04001675Extends this array with data from the unicode string ustr.
1676
1677Convert the array to a unicode string. The array must be a unicode type array;
1678otherwise a ValueError is raised. Use array.tobytes().decode() to obtain a
1679unicode string from an array of some other type.
1680[clinic start generated code]*/
Martin v. Löwis99866332002-03-01 10:27:01 +00001681
1682static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001683array_array_tounicode_impl(arrayobject *self)
1684/*[clinic end generated code: output=08e442378336e1ef input=127242eebe70b66d]*/
Martin v. Löwis99866332002-03-01 10:27:01 +00001685{
Victor Stinner62bb3942012-08-06 00:46:05 +02001686 char typecode;
1687 typecode = self->ob_descr->typecode;
Gregory P. Smith9504b132012-12-10 20:20:20 -08001688 if (typecode != 'u') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001689 PyErr_SetString(PyExc_ValueError,
1690 "tounicode() may only be called on unicode type arrays");
1691 return NULL;
1692 }
Victor Stinner62bb3942012-08-06 00:46:05 +02001693 return PyUnicode_FromUnicode((Py_UNICODE *) self->ob_item, Py_SIZE(self));
Martin v. Löwis99866332002-03-01 10:27:01 +00001694}
1695
Brett Cannon1eb32c22014-10-10 16:26:45 -04001696/*[clinic input]
1697array.array.__sizeof__
Martin v. Löwis99866332002-03-01 10:27:01 +00001698
Brett Cannon1eb32c22014-10-10 16:26:45 -04001699Size of the array in memory, in bytes.
1700[clinic start generated code]*/
Martin v. Löwis99866332002-03-01 10:27:01 +00001701
Meador Inge03b4d502012-08-10 22:35:45 -05001702static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001703array_array___sizeof___impl(arrayobject *self)
1704/*[clinic end generated code: output=d8e1c61ebbe3eaed input=805586565bf2b3c6]*/
Meador Inge03b4d502012-08-10 22:35:45 -05001705{
1706 Py_ssize_t res;
Serhiy Storchaka5c4064e2015-12-19 20:05:25 +02001707 res = _PyObject_SIZE(Py_TYPE(self)) + self->allocated * self->ob_descr->itemsize;
Meador Inge03b4d502012-08-10 22:35:45 -05001708 return PyLong_FromSsize_t(res);
1709}
1710
Martin v. Löwis99866332002-03-01 10:27:01 +00001711
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001712/*********************** Pickling support ************************/
1713
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001714static const struct mformatdescr {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001715 size_t size;
1716 int is_signed;
1717 int is_big_endian;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001718} mformat_descriptors[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001719 {1, 0, 0}, /* 0: UNSIGNED_INT8 */
1720 {1, 1, 0}, /* 1: SIGNED_INT8 */
1721 {2, 0, 0}, /* 2: UNSIGNED_INT16_LE */
1722 {2, 0, 1}, /* 3: UNSIGNED_INT16_BE */
1723 {2, 1, 0}, /* 4: SIGNED_INT16_LE */
1724 {2, 1, 1}, /* 5: SIGNED_INT16_BE */
1725 {4, 0, 0}, /* 6: UNSIGNED_INT32_LE */
1726 {4, 0, 1}, /* 7: UNSIGNED_INT32_BE */
1727 {4, 1, 0}, /* 8: SIGNED_INT32_LE */
1728 {4, 1, 1}, /* 9: SIGNED_INT32_BE */
1729 {8, 0, 0}, /* 10: UNSIGNED_INT64_LE */
1730 {8, 0, 1}, /* 11: UNSIGNED_INT64_BE */
1731 {8, 1, 0}, /* 12: SIGNED_INT64_LE */
1732 {8, 1, 1}, /* 13: SIGNED_INT64_BE */
1733 {4, 0, 0}, /* 14: IEEE_754_FLOAT_LE */
1734 {4, 0, 1}, /* 15: IEEE_754_FLOAT_BE */
1735 {8, 0, 0}, /* 16: IEEE_754_DOUBLE_LE */
1736 {8, 0, 1}, /* 17: IEEE_754_DOUBLE_BE */
1737 {4, 0, 0}, /* 18: UTF16_LE */
1738 {4, 0, 1}, /* 19: UTF16_BE */
1739 {8, 0, 0}, /* 20: UTF32_LE */
1740 {8, 0, 1} /* 21: UTF32_BE */
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001741};
1742
1743
1744/*
1745 * Internal: This function is used to find the machine format of a given
1746 * array type code. This returns UNKNOWN_FORMAT when the machine format cannot
1747 * be found.
1748 */
1749static enum machine_format_code
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02001750typecode_to_mformat_code(char typecode)
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001751{
Christian Heimes743e0cd2012-10-17 23:52:17 +02001752 const int is_big_endian = PY_BIG_ENDIAN;
1753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001754 size_t intsize;
1755 int is_signed;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001756
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001757 switch (typecode) {
1758 case 'b':
1759 return SIGNED_INT8;
1760 case 'B':
1761 return UNSIGNED_INT8;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001762
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001763 case 'u':
Victor Stinner62bb3942012-08-06 00:46:05 +02001764 if (sizeof(Py_UNICODE) == 2) {
1765 return UTF16_LE + is_big_endian;
1766 }
1767 if (sizeof(Py_UNICODE) == 4) {
1768 return UTF32_LE + is_big_endian;
1769 }
1770 return UNKNOWN_FORMAT;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001772 case 'f':
1773 if (sizeof(float) == 4) {
1774 const float y = 16711938.0;
1775 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1776 return IEEE_754_FLOAT_BE;
1777 if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1778 return IEEE_754_FLOAT_LE;
1779 }
1780 return UNKNOWN_FORMAT;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001782 case 'd':
1783 if (sizeof(double) == 8) {
1784 const double x = 9006104071832581.0;
1785 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1786 return IEEE_754_DOUBLE_BE;
1787 if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1788 return IEEE_754_DOUBLE_LE;
1789 }
1790 return UNKNOWN_FORMAT;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001792 /* Integers */
1793 case 'h':
1794 intsize = sizeof(short);
1795 is_signed = 1;
1796 break;
1797 case 'H':
1798 intsize = sizeof(short);
1799 is_signed = 0;
1800 break;
1801 case 'i':
1802 intsize = sizeof(int);
1803 is_signed = 1;
1804 break;
1805 case 'I':
1806 intsize = sizeof(int);
1807 is_signed = 0;
1808 break;
1809 case 'l':
1810 intsize = sizeof(long);
1811 is_signed = 1;
1812 break;
1813 case 'L':
1814 intsize = sizeof(long);
1815 is_signed = 0;
1816 break;
Meador Inge1c9f0c92011-09-20 19:55:51 -05001817#if HAVE_LONG_LONG
1818 case 'q':
1819 intsize = sizeof(PY_LONG_LONG);
1820 is_signed = 1;
1821 break;
1822 case 'Q':
1823 intsize = sizeof(PY_LONG_LONG);
1824 is_signed = 0;
1825 break;
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02001826#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001827 default:
1828 return UNKNOWN_FORMAT;
1829 }
1830 switch (intsize) {
1831 case 2:
1832 return UNSIGNED_INT16_LE + is_big_endian + (2 * is_signed);
1833 case 4:
1834 return UNSIGNED_INT32_LE + is_big_endian + (2 * is_signed);
1835 case 8:
1836 return UNSIGNED_INT64_LE + is_big_endian + (2 * is_signed);
1837 default:
1838 return UNKNOWN_FORMAT;
1839 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001840}
1841
1842/* Forward declaration. */
1843static PyObject *array_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1844
1845/*
1846 * Internal: This function wraps the array constructor--i.e., array_new()--to
1847 * allow the creation of array objects from C code without having to deal
1848 * directly the tuple argument of array_new(). The typecode argument is a
1849 * Unicode character value, like 'i' or 'f' for example, representing an array
1850 * type code. The items argument is a bytes or a list object from which
1851 * contains the initial value of the array.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001852 *
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001853 * On success, this functions returns the array object created. Otherwise,
1854 * NULL is returned to indicate a failure.
1855 */
1856static PyObject *
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02001857make_array(PyTypeObject *arraytype, char typecode, PyObject *items)
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001858{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001859 PyObject *new_args;
1860 PyObject *array_obj;
1861 PyObject *typecode_obj;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001862
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001863 assert(arraytype != NULL);
1864 assert(items != NULL);
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001865
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02001866 typecode_obj = PyUnicode_FromOrdinal(typecode);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001867 if (typecode_obj == NULL)
1868 return NULL;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001870 new_args = PyTuple_New(2);
1871 if (new_args == NULL)
1872 return NULL;
1873 Py_INCREF(items);
1874 PyTuple_SET_ITEM(new_args, 0, typecode_obj);
1875 PyTuple_SET_ITEM(new_args, 1, items);
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001877 array_obj = array_new(arraytype, new_args, NULL);
1878 Py_DECREF(new_args);
1879 if (array_obj == NULL)
1880 return NULL;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001882 return array_obj;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001883}
1884
1885/*
1886 * This functions is a special constructor used when unpickling an array. It
1887 * provides a portable way to rebuild an array from its memory representation.
1888 */
Brett Cannon1eb32c22014-10-10 16:26:45 -04001889/*[clinic input]
1890array._array_reconstructor
1891
1892 arraytype: object(type="PyTypeObject *")
Larry Hastingsdbfdc382015-05-04 06:59:46 -07001893 typecode: int(accept={str})
Brett Cannon1eb32c22014-10-10 16:26:45 -04001894 mformat_code: int(type="enum machine_format_code")
1895 items: object
1896 /
1897
1898Internal. Used for pickling support.
1899[clinic start generated code]*/
1900
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001901static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001902array__array_reconstructor_impl(PyObject *module, PyTypeObject *arraytype,
Larry Hastings89964c42015-04-14 18:07:59 -04001903 int typecode,
1904 enum machine_format_code mformat_code,
1905 PyObject *items)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001906/*[clinic end generated code: output=e05263141ba28365 input=2464dc8f4c7736b5]*/
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001907{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001908 PyObject *converted_items;
1909 PyObject *result;
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02001910 const struct arraydescr *descr;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001911
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001912 if (!PyType_Check(arraytype)) {
1913 PyErr_Format(PyExc_TypeError,
1914 "first argument must a type object, not %.200s",
1915 Py_TYPE(arraytype)->tp_name);
1916 return NULL;
1917 }
1918 if (!PyType_IsSubtype(arraytype, &Arraytype)) {
1919 PyErr_Format(PyExc_TypeError,
1920 "%.200s is not a subtype of %.200s",
1921 arraytype->tp_name, Arraytype.tp_name);
1922 return NULL;
1923 }
1924 for (descr = descriptors; descr->typecode != '\0'; descr++) {
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02001925 if ((int)descr->typecode == typecode)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001926 break;
1927 }
1928 if (descr->typecode == '\0') {
1929 PyErr_SetString(PyExc_ValueError,
1930 "second argument must be a valid type code");
1931 return NULL;
1932 }
Larry Hastingsdfbeb162014-10-13 10:39:41 +01001933 if (mformat_code < MACHINE_FORMAT_CODE_MIN ||
1934 mformat_code > MACHINE_FORMAT_CODE_MAX) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001935 PyErr_SetString(PyExc_ValueError,
1936 "third argument must be a valid machine format code.");
1937 return NULL;
1938 }
1939 if (!PyBytes_Check(items)) {
1940 PyErr_Format(PyExc_TypeError,
1941 "fourth argument should be bytes, not %.200s",
1942 Py_TYPE(items)->tp_name);
1943 return NULL;
1944 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001945
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001946 /* Fast path: No decoding has to be done. */
Larry Hastingsdfbeb162014-10-13 10:39:41 +01001947 if (mformat_code == typecode_to_mformat_code((char)typecode) ||
1948 mformat_code == UNKNOWN_FORMAT) {
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02001949 return make_array(arraytype, (char)typecode, items);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001950 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001951
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001952 /* Slow path: Decode the byte string according to the given machine
1953 * format code. This occurs when the computer unpickling the array
1954 * object is architecturally different from the one that pickled the
1955 * array.
1956 */
Larry Hastingsdfbeb162014-10-13 10:39:41 +01001957 if (Py_SIZE(items) % mformat_descriptors[mformat_code].size != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001958 PyErr_SetString(PyExc_ValueError,
1959 "string length not a multiple of item size");
1960 return NULL;
1961 }
Larry Hastingsdfbeb162014-10-13 10:39:41 +01001962 switch (mformat_code) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001963 case IEEE_754_FLOAT_LE:
1964 case IEEE_754_FLOAT_BE: {
1965 int i;
Larry Hastingsdfbeb162014-10-13 10:39:41 +01001966 int le = (mformat_code == IEEE_754_FLOAT_LE) ? 1 : 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001967 Py_ssize_t itemcount = Py_SIZE(items) / 4;
1968 const unsigned char *memstr =
1969 (unsigned char *)PyBytes_AS_STRING(items);
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001971 converted_items = PyList_New(itemcount);
1972 if (converted_items == NULL)
1973 return NULL;
1974 for (i = 0; i < itemcount; i++) {
1975 PyObject *pyfloat = PyFloat_FromDouble(
1976 _PyFloat_Unpack4(&memstr[i * 4], le));
1977 if (pyfloat == NULL) {
1978 Py_DECREF(converted_items);
1979 return NULL;
1980 }
1981 PyList_SET_ITEM(converted_items, i, pyfloat);
1982 }
1983 break;
1984 }
1985 case IEEE_754_DOUBLE_LE:
1986 case IEEE_754_DOUBLE_BE: {
1987 int i;
Larry Hastingsdfbeb162014-10-13 10:39:41 +01001988 int le = (mformat_code == IEEE_754_DOUBLE_LE) ? 1 : 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001989 Py_ssize_t itemcount = Py_SIZE(items) / 8;
1990 const unsigned char *memstr =
1991 (unsigned char *)PyBytes_AS_STRING(items);
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001993 converted_items = PyList_New(itemcount);
1994 if (converted_items == NULL)
1995 return NULL;
1996 for (i = 0; i < itemcount; i++) {
1997 PyObject *pyfloat = PyFloat_FromDouble(
1998 _PyFloat_Unpack8(&memstr[i * 8], le));
1999 if (pyfloat == NULL) {
2000 Py_DECREF(converted_items);
2001 return NULL;
2002 }
2003 PyList_SET_ITEM(converted_items, i, pyfloat);
2004 }
2005 break;
2006 }
2007 case UTF16_LE:
2008 case UTF16_BE: {
Larry Hastingsdfbeb162014-10-13 10:39:41 +01002009 int byteorder = (mformat_code == UTF16_LE) ? -1 : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002010 converted_items = PyUnicode_DecodeUTF16(
2011 PyBytes_AS_STRING(items), Py_SIZE(items),
2012 "strict", &byteorder);
2013 if (converted_items == NULL)
2014 return NULL;
2015 break;
2016 }
2017 case UTF32_LE:
2018 case UTF32_BE: {
Larry Hastingsdfbeb162014-10-13 10:39:41 +01002019 int byteorder = (mformat_code == UTF32_LE) ? -1 : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002020 converted_items = PyUnicode_DecodeUTF32(
2021 PyBytes_AS_STRING(items), Py_SIZE(items),
2022 "strict", &byteorder);
2023 if (converted_items == NULL)
2024 return NULL;
2025 break;
2026 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002028 case UNSIGNED_INT8:
2029 case SIGNED_INT8:
2030 case UNSIGNED_INT16_LE:
2031 case UNSIGNED_INT16_BE:
2032 case SIGNED_INT16_LE:
2033 case SIGNED_INT16_BE:
2034 case UNSIGNED_INT32_LE:
2035 case UNSIGNED_INT32_BE:
2036 case SIGNED_INT32_LE:
2037 case SIGNED_INT32_BE:
2038 case UNSIGNED_INT64_LE:
2039 case UNSIGNED_INT64_BE:
2040 case SIGNED_INT64_LE:
2041 case SIGNED_INT64_BE: {
2042 int i;
2043 const struct mformatdescr mf_descr =
Larry Hastingsdfbeb162014-10-13 10:39:41 +01002044 mformat_descriptors[mformat_code];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002045 Py_ssize_t itemcount = Py_SIZE(items) / mf_descr.size;
2046 const unsigned char *memstr =
2047 (unsigned char *)PyBytes_AS_STRING(items);
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02002048 const struct arraydescr *descr;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002050 /* If possible, try to pack array's items using a data type
2051 * that fits better. This may result in an array with narrower
2052 * or wider elements.
2053 *
Martin Panter4c359642016-05-08 13:53:41 +00002054 * For example, if a 32-bit machine pickles an L-code array of
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002055 * unsigned longs, then the array will be unpickled by 64-bit
2056 * machine as an I-code array of unsigned ints.
2057 *
2058 * XXX: Is it possible to write a unit test for this?
2059 */
2060 for (descr = descriptors; descr->typecode != '\0'; descr++) {
2061 if (descr->is_integer_type &&
Victor Stinner706768c2014-08-16 01:03:39 +02002062 (size_t)descr->itemsize == mf_descr.size &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002063 descr->is_signed == mf_descr.is_signed)
2064 typecode = descr->typecode;
2065 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002067 converted_items = PyList_New(itemcount);
2068 if (converted_items == NULL)
2069 return NULL;
2070 for (i = 0; i < itemcount; i++) {
2071 PyObject *pylong;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002073 pylong = _PyLong_FromByteArray(
2074 &memstr[i * mf_descr.size],
2075 mf_descr.size,
2076 !mf_descr.is_big_endian,
2077 mf_descr.is_signed);
2078 if (pylong == NULL) {
2079 Py_DECREF(converted_items);
2080 return NULL;
2081 }
2082 PyList_SET_ITEM(converted_items, i, pylong);
2083 }
2084 break;
2085 }
2086 case UNKNOWN_FORMAT:
2087 /* Impossible, but needed to shut up GCC about the unhandled
2088 * enumeration value.
2089 */
2090 default:
2091 PyErr_BadArgument();
2092 return NULL;
2093 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002094
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02002095 result = make_array(arraytype, (char)typecode, converted_items);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002096 Py_DECREF(converted_items);
2097 return result;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002098}
2099
Brett Cannon1eb32c22014-10-10 16:26:45 -04002100/*[clinic input]
2101array.array.__reduce_ex__
2102
2103 value: object
2104 /
2105
2106Return state information for pickling.
2107[clinic start generated code]*/
2108
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002109static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04002110array_array___reduce_ex__(arrayobject *self, PyObject *value)
2111/*[clinic end generated code: output=051e0a6175d0eddb input=c36c3f85de7df6cd]*/
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002112{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002113 PyObject *dict;
2114 PyObject *result;
2115 PyObject *array_str;
Brett Cannon1eb32c22014-10-10 16:26:45 -04002116 int typecode = self->ob_descr->typecode;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002117 int mformat_code;
2118 static PyObject *array_reconstructor = NULL;
2119 long protocol;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002120 _Py_IDENTIFIER(_array_reconstructor);
2121 _Py_IDENTIFIER(__dict__);
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002123 if (array_reconstructor == NULL) {
2124 PyObject *array_module = PyImport_ImportModule("array");
2125 if (array_module == NULL)
2126 return NULL;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002127 array_reconstructor = _PyObject_GetAttrId(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002128 array_module,
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002129 &PyId__array_reconstructor);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002130 Py_DECREF(array_module);
2131 if (array_reconstructor == NULL)
2132 return NULL;
2133 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002135 if (!PyLong_Check(value)) {
2136 PyErr_SetString(PyExc_TypeError,
2137 "__reduce_ex__ argument should an integer");
2138 return NULL;
2139 }
2140 protocol = PyLong_AsLong(value);
2141 if (protocol == -1 && PyErr_Occurred())
2142 return NULL;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002143
Brett Cannon1eb32c22014-10-10 16:26:45 -04002144 dict = _PyObject_GetAttrId((PyObject *)self, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002145 if (dict == NULL) {
2146 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
2147 return NULL;
2148 PyErr_Clear();
2149 dict = Py_None;
2150 Py_INCREF(dict);
2151 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002152
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002153 mformat_code = typecode_to_mformat_code(typecode);
2154 if (mformat_code == UNKNOWN_FORMAT || protocol < 3) {
2155 /* Convert the array to a list if we got something weird
2156 * (e.g., non-IEEE floats), or we are pickling the array using
2157 * a Python 2.x compatible protocol.
2158 *
2159 * It is necessary to use a list representation for Python 2.x
2160 * compatible pickle protocol, since Python 2's str objects
2161 * are unpickled as unicode by Python 3. Thus it is impossible
2162 * to make arrays unpicklable by Python 3 by using their memory
2163 * representation, unless we resort to ugly hacks such as
2164 * coercing unicode objects to bytes in array_reconstructor.
2165 */
2166 PyObject *list;
Brett Cannon1eb32c22014-10-10 16:26:45 -04002167 list = array_array_tolist_impl(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002168 if (list == NULL) {
2169 Py_DECREF(dict);
2170 return NULL;
2171 }
2172 result = Py_BuildValue(
Brett Cannon1eb32c22014-10-10 16:26:45 -04002173 "O(CO)O", Py_TYPE(self), typecode, list, dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002174 Py_DECREF(list);
2175 Py_DECREF(dict);
2176 return result;
2177 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002178
Brett Cannon1eb32c22014-10-10 16:26:45 -04002179 array_str = array_array_tobytes_impl(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002180 if (array_str == NULL) {
2181 Py_DECREF(dict);
2182 return NULL;
2183 }
2184 result = Py_BuildValue(
Brett Cannon1eb32c22014-10-10 16:26:45 -04002185 "O(OCiN)O", array_reconstructor, Py_TYPE(self), typecode,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002186 mformat_code, array_str, dict);
2187 Py_DECREF(dict);
2188 return result;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002189}
2190
Martin v. Löwis99866332002-03-01 10:27:01 +00002191static PyObject *
2192array_get_typecode(arrayobject *a, void *closure)
2193{
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02002194 char typecode = a->ob_descr->typecode;
2195 return PyUnicode_FromOrdinal(typecode);
Martin v. Löwis99866332002-03-01 10:27:01 +00002196}
2197
2198static PyObject *
2199array_get_itemsize(arrayobject *a, void *closure)
2200{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002201 return PyLong_FromLong((long)a->ob_descr->itemsize);
Martin v. Löwis99866332002-03-01 10:27:01 +00002202}
2203
2204static PyGetSetDef array_getsets [] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002205 {"typecode", (getter) array_get_typecode, NULL,
2206 "the typecode character used to create the array"},
2207 {"itemsize", (getter) array_get_itemsize, NULL,
2208 "the size, in bytes, of one array item"},
2209 {NULL}
Martin v. Löwis99866332002-03-01 10:27:01 +00002210};
2211
Martin v. Löwis59683e82008-06-13 07:50:45 +00002212static PyMethodDef array_methods[] = {
Brett Cannon1eb32c22014-10-10 16:26:45 -04002213 ARRAY_ARRAY_APPEND_METHODDEF
2214 ARRAY_ARRAY_BUFFER_INFO_METHODDEF
2215 ARRAY_ARRAY_BYTESWAP_METHODDEF
2216 ARRAY_ARRAY___COPY___METHODDEF
2217 ARRAY_ARRAY_COUNT_METHODDEF
2218 ARRAY_ARRAY___DEEPCOPY___METHODDEF
2219 ARRAY_ARRAY_EXTEND_METHODDEF
2220 ARRAY_ARRAY_FROMFILE_METHODDEF
2221 ARRAY_ARRAY_FROMLIST_METHODDEF
2222 ARRAY_ARRAY_FROMSTRING_METHODDEF
2223 ARRAY_ARRAY_FROMBYTES_METHODDEF
2224 ARRAY_ARRAY_FROMUNICODE_METHODDEF
2225 ARRAY_ARRAY_INDEX_METHODDEF
2226 ARRAY_ARRAY_INSERT_METHODDEF
2227 ARRAY_ARRAY_POP_METHODDEF
2228 ARRAY_ARRAY___REDUCE_EX___METHODDEF
2229 ARRAY_ARRAY_REMOVE_METHODDEF
2230 ARRAY_ARRAY_REVERSE_METHODDEF
2231 ARRAY_ARRAY_TOFILE_METHODDEF
2232 ARRAY_ARRAY_TOLIST_METHODDEF
2233 ARRAY_ARRAY_TOSTRING_METHODDEF
2234 ARRAY_ARRAY_TOBYTES_METHODDEF
2235 ARRAY_ARRAY_TOUNICODE_METHODDEF
2236 ARRAY_ARRAY___SIZEOF___METHODDEF
2237 {NULL, NULL} /* sentinel */
Guido van Rossum778983b1993-02-19 15:55:02 +00002238};
2239
Roger E. Masse2919eaa1996-12-09 20:10:36 +00002240static PyObject *
Peter Schneider-Kamp9656abd2000-07-13 21:10:57 +00002241array_repr(arrayobject *a)
Guido van Rossum778983b1993-02-19 15:55:02 +00002242{
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02002243 char typecode;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002244 PyObject *s, *v = NULL;
2245 Py_ssize_t len;
Martin v. Löwis99866332002-03-01 10:27:01 +00002246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002247 len = Py_SIZE(a);
2248 typecode = a->ob_descr->typecode;
2249 if (len == 0) {
Amaury Forgeot d'Arc24aa26b2010-11-25 08:13:35 +00002250 return PyUnicode_FromFormat("array('%c')", (int)typecode);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002251 }
Gregory P. Smith9504b132012-12-10 20:20:20 -08002252 if (typecode == 'u') {
Brett Cannon1eb32c22014-10-10 16:26:45 -04002253 v = array_array_tounicode_impl(a);
Gregory P. Smith9504b132012-12-10 20:20:20 -08002254 } else {
Brett Cannon1eb32c22014-10-10 16:26:45 -04002255 v = array_array_tolist_impl(a);
Gregory P. Smith9504b132012-12-10 20:20:20 -08002256 }
Victor Stinner29ec5952013-02-26 00:27:38 +01002257 if (v == NULL)
2258 return NULL;
Raymond Hettinger88ba1e32003-04-23 17:27:00 +00002259
Amaury Forgeot d'Arc24aa26b2010-11-25 08:13:35 +00002260 s = PyUnicode_FromFormat("array('%c', %R)", (int)typecode, v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002261 Py_DECREF(v);
2262 return s;
Guido van Rossum778983b1993-02-19 15:55:02 +00002263}
2264
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002265static PyObject*
2266array_subscr(arrayobject* self, PyObject* item)
2267{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002268 if (PyIndex_Check(item)) {
2269 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
2270 if (i==-1 && PyErr_Occurred()) {
2271 return NULL;
2272 }
2273 if (i < 0)
2274 i += Py_SIZE(self);
2275 return array_item(self, i);
2276 }
2277 else if (PySlice_Check(item)) {
2278 Py_ssize_t start, stop, step, slicelength, cur, i;
2279 PyObject* result;
2280 arrayobject* ar;
2281 int itemsize = self->ob_descr->itemsize;
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002282
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002283 if (PySlice_GetIndicesEx(item, Py_SIZE(self),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002284 &start, &stop, &step, &slicelength) < 0) {
2285 return NULL;
2286 }
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002288 if (slicelength <= 0) {
2289 return newarrayobject(&Arraytype, 0, self->ob_descr);
2290 }
2291 else if (step == 1) {
2292 PyObject *result = newarrayobject(&Arraytype,
2293 slicelength, self->ob_descr);
2294 if (result == NULL)
2295 return NULL;
2296 memcpy(((arrayobject *)result)->ob_item,
2297 self->ob_item + start * itemsize,
2298 slicelength * itemsize);
2299 return result;
2300 }
2301 else {
2302 result = newarrayobject(&Arraytype, slicelength, self->ob_descr);
2303 if (!result) return NULL;
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002305 ar = (arrayobject*)result;
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002307 for (cur = start, i = 0; i < slicelength;
2308 cur += step, i++) {
2309 memcpy(ar->ob_item + i*itemsize,
2310 self->ob_item + cur*itemsize,
2311 itemsize);
2312 }
2313
2314 return result;
2315 }
2316 }
2317 else {
2318 PyErr_SetString(PyExc_TypeError,
2319 "array indices must be integers");
2320 return NULL;
2321 }
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002322}
2323
2324static int
2325array_ass_subscr(arrayobject* self, PyObject* item, PyObject* value)
2326{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002327 Py_ssize_t start, stop, step, slicelength, needed;
2328 arrayobject* other;
2329 int itemsize;
Thomas Woutersed03b412007-08-28 21:37:11 +00002330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002331 if (PyIndex_Check(item)) {
2332 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Alexandre Vassalotti47137252009-07-05 19:57:00 +00002333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002334 if (i == -1 && PyErr_Occurred())
2335 return -1;
2336 if (i < 0)
2337 i += Py_SIZE(self);
2338 if (i < 0 || i >= Py_SIZE(self)) {
2339 PyErr_SetString(PyExc_IndexError,
2340 "array assignment index out of range");
2341 return -1;
2342 }
2343 if (value == NULL) {
2344 /* Fall through to slice assignment */
2345 start = i;
2346 stop = i + 1;
2347 step = 1;
2348 slicelength = 1;
2349 }
2350 else
2351 return (*self->ob_descr->setitem)(self, i, value);
2352 }
2353 else if (PySlice_Check(item)) {
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002354 if (PySlice_GetIndicesEx(item,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002355 Py_SIZE(self), &start, &stop,
2356 &step, &slicelength) < 0) {
2357 return -1;
2358 }
2359 }
2360 else {
2361 PyErr_SetString(PyExc_TypeError,
2362 "array indices must be integer");
2363 return -1;
2364 }
2365 if (value == NULL) {
2366 other = NULL;
2367 needed = 0;
2368 }
2369 else if (array_Check(value)) {
2370 other = (arrayobject *)value;
2371 needed = Py_SIZE(other);
2372 if (self == other) {
2373 /* Special case "self[i:j] = self" -- copy self first */
2374 int ret;
2375 value = array_slice(other, 0, needed);
2376 if (value == NULL)
2377 return -1;
2378 ret = array_ass_subscr(self, item, value);
2379 Py_DECREF(value);
2380 return ret;
2381 }
2382 if (other->ob_descr != self->ob_descr) {
2383 PyErr_BadArgument();
2384 return -1;
2385 }
2386 }
2387 else {
2388 PyErr_Format(PyExc_TypeError,
2389 "can only assign array (not \"%.200s\") to array slice",
2390 Py_TYPE(value)->tp_name);
2391 return -1;
2392 }
2393 itemsize = self->ob_descr->itemsize;
2394 /* for 'a[2:1] = ...', the insertion point is 'start', not 'stop' */
2395 if ((step > 0 && stop < start) ||
2396 (step < 0 && stop > start))
2397 stop = start;
Alexandre Vassalotti47137252009-07-05 19:57:00 +00002398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002399 /* Issue #4509: If the array has exported buffers and the slice
2400 assignment would change the size of the array, fail early to make
2401 sure we don't modify it. */
2402 if ((needed == 0 || slicelength != needed) && self->ob_exports > 0) {
2403 PyErr_SetString(PyExc_BufferError,
2404 "cannot resize an array that is exporting buffers");
2405 return -1;
2406 }
Mark Dickinsonbc099642010-01-29 17:27:24 +00002407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002408 if (step == 1) {
2409 if (slicelength > needed) {
2410 memmove(self->ob_item + (start + needed) * itemsize,
2411 self->ob_item + stop * itemsize,
2412 (Py_SIZE(self) - stop) * itemsize);
2413 if (array_resize(self, Py_SIZE(self) +
2414 needed - slicelength) < 0)
2415 return -1;
2416 }
2417 else if (slicelength < needed) {
2418 if (array_resize(self, Py_SIZE(self) +
2419 needed - slicelength) < 0)
2420 return -1;
2421 memmove(self->ob_item + (start + needed) * itemsize,
2422 self->ob_item + stop * itemsize,
2423 (Py_SIZE(self) - start - needed) * itemsize);
2424 }
2425 if (needed > 0)
2426 memcpy(self->ob_item + start * itemsize,
2427 other->ob_item, needed * itemsize);
2428 return 0;
2429 }
2430 else if (needed == 0) {
2431 /* Delete slice */
2432 size_t cur;
2433 Py_ssize_t i;
Thomas Woutersed03b412007-08-28 21:37:11 +00002434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002435 if (step < 0) {
2436 stop = start + 1;
2437 start = stop + step * (slicelength - 1) - 1;
2438 step = -step;
2439 }
2440 for (cur = start, i = 0; i < slicelength;
2441 cur += step, i++) {
2442 Py_ssize_t lim = step - 1;
Thomas Woutersed03b412007-08-28 21:37:11 +00002443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002444 if (cur + step >= (size_t)Py_SIZE(self))
2445 lim = Py_SIZE(self) - cur - 1;
2446 memmove(self->ob_item + (cur - i) * itemsize,
2447 self->ob_item + (cur + 1) * itemsize,
2448 lim * itemsize);
2449 }
Mark Dickinsonc7d93b72011-09-25 15:34:32 +01002450 cur = start + (size_t)slicelength * step;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002451 if (cur < (size_t)Py_SIZE(self)) {
2452 memmove(self->ob_item + (cur-slicelength) * itemsize,
2453 self->ob_item + cur * itemsize,
2454 (Py_SIZE(self) - cur) * itemsize);
2455 }
2456 if (array_resize(self, Py_SIZE(self) - slicelength) < 0)
2457 return -1;
2458 return 0;
2459 }
2460 else {
2461 Py_ssize_t cur, i;
2462
2463 if (needed != slicelength) {
2464 PyErr_Format(PyExc_ValueError,
2465 "attempt to assign array of size %zd "
2466 "to extended slice of size %zd",
2467 needed, slicelength);
2468 return -1;
2469 }
2470 for (cur = start, i = 0; i < slicelength;
2471 cur += step, i++) {
2472 memcpy(self->ob_item + cur * itemsize,
2473 other->ob_item + i * itemsize,
2474 itemsize);
2475 }
2476 return 0;
2477 }
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002478}
2479
2480static PyMappingMethods array_as_mapping = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002481 (lenfunc)array_length,
2482 (binaryfunc)array_subscr,
2483 (objobjargproc)array_ass_subscr
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002484};
2485
Guido van Rossumd8faa362007-04-27 19:54:29 +00002486static const void *emptybuf = "";
2487
Travis E. Oliphantb99f7622007-08-18 11:21:56 +00002488
2489static int
Travis E. Oliphant8ae62b62007-09-23 02:00:13 +00002490array_buffer_getbuf(arrayobject *self, Py_buffer *view, int flags)
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00002491{
Stefan Krah650c1e82015-02-03 21:43:23 +01002492 if (view == NULL) {
2493 PyErr_SetString(PyExc_BufferError,
2494 "array_buffer_getbuf: view==NULL argument is obsolete");
2495 return -1;
2496 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +00002497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002498 view->buf = (void *)self->ob_item;
2499 view->obj = (PyObject*)self;
2500 Py_INCREF(self);
2501 if (view->buf == NULL)
2502 view->buf = (void *)emptybuf;
2503 view->len = (Py_SIZE(self)) * self->ob_descr->itemsize;
2504 view->readonly = 0;
2505 view->ndim = 1;
2506 view->itemsize = self->ob_descr->itemsize;
2507 view->suboffsets = NULL;
2508 view->shape = NULL;
2509 if ((flags & PyBUF_ND)==PyBUF_ND) {
2510 view->shape = &((Py_SIZE(self)));
2511 }
2512 view->strides = NULL;
2513 if ((flags & PyBUF_STRIDES)==PyBUF_STRIDES)
2514 view->strides = &(view->itemsize);
2515 view->format = NULL;
2516 view->internal = NULL;
Victor Stinner62bb3942012-08-06 00:46:05 +02002517 if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT) {
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02002518 view->format = (char *)self->ob_descr->formats;
Victor Stinner62bb3942012-08-06 00:46:05 +02002519#ifdef Py_UNICODE_WIDE
2520 if (self->ob_descr->typecode == 'u') {
2521 view->format = "w";
2522 }
2523#endif
2524 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +00002525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002526 self->ob_exports++;
2527 return 0;
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00002528}
2529
Travis E. Oliphantb99f7622007-08-18 11:21:56 +00002530static void
Travis E. Oliphant8ae62b62007-09-23 02:00:13 +00002531array_buffer_relbuf(arrayobject *self, Py_buffer *view)
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00002532{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002533 self->ob_exports--;
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00002534}
2535
Roger E. Masse2919eaa1996-12-09 20:10:36 +00002536static PySequenceMethods array_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002537 (lenfunc)array_length, /*sq_length*/
2538 (binaryfunc)array_concat, /*sq_concat*/
2539 (ssizeargfunc)array_repeat, /*sq_repeat*/
2540 (ssizeargfunc)array_item, /*sq_item*/
2541 0, /*sq_slice*/
2542 (ssizeobjargproc)array_ass_item, /*sq_ass_item*/
2543 0, /*sq_ass_slice*/
2544 (objobjproc)array_contains, /*sq_contains*/
2545 (binaryfunc)array_inplace_concat, /*sq_inplace_concat*/
2546 (ssizeargfunc)array_inplace_repeat /*sq_inplace_repeat*/
Guido van Rossum778983b1993-02-19 15:55:02 +00002547};
2548
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00002549static PyBufferProcs array_as_buffer = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002550 (getbufferproc)array_buffer_getbuf,
2551 (releasebufferproc)array_buffer_relbuf
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00002552};
2553
Roger E. Masse2919eaa1996-12-09 20:10:36 +00002554static PyObject *
Martin v. Löwis99866332002-03-01 10:27:01 +00002555array_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum778983b1993-02-19 15:55:02 +00002556{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002557 int c;
2558 PyObject *initial = NULL, *it = NULL;
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02002559 const struct arraydescr *descr;
Martin v. Löwis99866332002-03-01 10:27:01 +00002560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002561 if (type == &Arraytype && !_PyArg_NoKeywords("array.array()", kwds))
2562 return NULL;
Martin v. Löwis99866332002-03-01 10:27:01 +00002563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002564 if (!PyArg_ParseTuple(args, "C|O:array", &c, &initial))
2565 return NULL;
Raymond Hettinger84fc9aa2003-04-24 10:41:55 +00002566
Alexandre Vassalotti9730e332013-11-29 20:47:15 -08002567 if (initial && c != 'u') {
2568 if (PyUnicode_Check(initial)) {
2569 PyErr_Format(PyExc_TypeError, "cannot use a str to initialize "
2570 "an array with typecode '%c'", c);
2571 return NULL;
2572 }
2573 else if (array_Check(initial) &&
2574 ((arrayobject*)initial)->ob_descr->typecode == 'u') {
2575 PyErr_Format(PyExc_TypeError, "cannot use a unicode array to "
2576 "initialize an array with typecode '%c'", c);
2577 return NULL;
2578 }
2579 }
2580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002581 if (!(initial == NULL || PyList_Check(initial)
2582 || PyByteArray_Check(initial)
2583 || PyBytes_Check(initial)
2584 || PyTuple_Check(initial)
Alexander Belopolskyef4a03f2011-01-11 21:44:00 +00002585 || ((c=='u') && PyUnicode_Check(initial))
2586 || (array_Check(initial)
2587 && c == ((arrayobject*)initial)->ob_descr->typecode))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002588 it = PyObject_GetIter(initial);
2589 if (it == NULL)
2590 return NULL;
2591 /* We set initial to NULL so that the subsequent code
2592 will create an empty array of the appropriate type
2593 and afterwards we can use array_iter_extend to populate
2594 the array.
2595 */
2596 initial = NULL;
2597 }
2598 for (descr = descriptors; descr->typecode != '\0'; descr++) {
2599 if (descr->typecode == c) {
2600 PyObject *a;
2601 Py_ssize_t len;
Martin v. Löwis99866332002-03-01 10:27:01 +00002602
Alexander Belopolskyef4a03f2011-01-11 21:44:00 +00002603 if (initial == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002604 len = 0;
Alexander Belopolskyef4a03f2011-01-11 21:44:00 +00002605 else if (PyList_Check(initial))
2606 len = PyList_GET_SIZE(initial);
2607 else if (PyTuple_Check(initial) || array_Check(initial))
2608 len = Py_SIZE(initial);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002609 else
Alexander Belopolskyef4a03f2011-01-11 21:44:00 +00002610 len = 0;
Martin v. Löwis99866332002-03-01 10:27:01 +00002611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002612 a = newarrayobject(type, len, descr);
2613 if (a == NULL)
2614 return NULL;
2615
Alexander Belopolskyef4a03f2011-01-11 21:44:00 +00002616 if (len > 0 && !array_Check(initial)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002617 Py_ssize_t i;
2618 for (i = 0; i < len; i++) {
2619 PyObject *v =
2620 PySequence_GetItem(initial, i);
2621 if (v == NULL) {
2622 Py_DECREF(a);
2623 return NULL;
2624 }
2625 if (setarrayitem(a, i, v) != 0) {
2626 Py_DECREF(v);
2627 Py_DECREF(a);
2628 return NULL;
2629 }
2630 Py_DECREF(v);
2631 }
2632 }
2633 else if (initial != NULL && (PyByteArray_Check(initial) ||
2634 PyBytes_Check(initial))) {
Serhiy Storchaka04e6dba2015-04-04 17:06:55 +03002635 PyObject *v;
Brett Cannon1eb32c22014-10-10 16:26:45 -04002636 v = array_array_frombytes((arrayobject *)a,
Serhiy Storchaka04e6dba2015-04-04 17:06:55 +03002637 initial);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002638 if (v == NULL) {
2639 Py_DECREF(a);
2640 return NULL;
2641 }
2642 Py_DECREF(v);
2643 }
2644 else if (initial != NULL && PyUnicode_Check(initial)) {
Victor Stinner62bb3942012-08-06 00:46:05 +02002645 Py_UNICODE *ustr;
Victor Stinner1fbcaef2011-09-30 01:54:04 +02002646 Py_ssize_t n;
Victor Stinner62bb3942012-08-06 00:46:05 +02002647
2648 ustr = PyUnicode_AsUnicode(initial);
2649 if (ustr == NULL) {
2650 PyErr_NoMemory();
Victor Stinner1fbcaef2011-09-30 01:54:04 +02002651 Py_DECREF(a);
2652 return NULL;
2653 }
Victor Stinner62bb3942012-08-06 00:46:05 +02002654
2655 n = PyUnicode_GET_DATA_SIZE(initial);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002656 if (n > 0) {
2657 arrayobject *self = (arrayobject *)a;
Victor Stinner62bb3942012-08-06 00:46:05 +02002658 char *item = self->ob_item;
2659 item = (char *)PyMem_Realloc(item, n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002660 if (item == NULL) {
2661 PyErr_NoMemory();
2662 Py_DECREF(a);
2663 return NULL;
2664 }
Victor Stinner62bb3942012-08-06 00:46:05 +02002665 self->ob_item = item;
2666 Py_SIZE(self) = n / sizeof(Py_UNICODE);
2667 memcpy(item, ustr, n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002668 self->allocated = Py_SIZE(self);
2669 }
2670 }
Benjamin Peterson682124c2014-10-10 20:58:30 -04002671 else if (initial != NULL && array_Check(initial) && len > 0) {
Alexander Belopolskyef4a03f2011-01-11 21:44:00 +00002672 arrayobject *self = (arrayobject *)a;
2673 arrayobject *other = (arrayobject *)initial;
2674 memcpy(self->ob_item, other->ob_item, len * other->ob_descr->itemsize);
2675 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002676 if (it != NULL) {
2677 if (array_iter_extend((arrayobject *)a, it) == -1) {
2678 Py_DECREF(it);
2679 Py_DECREF(a);
2680 return NULL;
2681 }
2682 Py_DECREF(it);
2683 }
2684 return a;
2685 }
2686 }
2687 PyErr_SetString(PyExc_ValueError,
Meador Inge1c9f0c92011-09-20 19:55:51 -05002688#ifdef HAVE_LONG_LONG
2689 "bad typecode (must be b, B, u, h, H, i, I, l, L, q, Q, f or d)");
2690#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002691 "bad typecode (must be b, B, u, h, H, i, I, l, L, f or d)");
Meador Inge1c9f0c92011-09-20 19:55:51 -05002692#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002693 return NULL;
Guido van Rossum778983b1993-02-19 15:55:02 +00002694}
2695
Guido van Rossum778983b1993-02-19 15:55:02 +00002696
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002697PyDoc_STRVAR(module_doc,
Martin v. Löwis99866332002-03-01 10:27:01 +00002698"This module defines an object type which can efficiently represent\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002699an array of basic values: characters, integers, floating point\n\
2700numbers. Arrays are sequence types and behave very much like lists,\n\
Alexandre Vassalotti9730e332013-11-29 20:47:15 -08002701except that the type of objects stored in them is constrained.\n");
2702
2703PyDoc_STRVAR(arraytype_doc,
2704"array(typecode [, initializer]) -> array\n\
2705\n\
2706Return a new array whose items are restricted by typecode, and\n\
2707initialized from the optional initializer value, which must be a list,\n\
2708string or iterable over elements of the appropriate type.\n\
2709\n\
2710Arrays represent basic values and behave very much like lists, except\n\
2711the type of objects stored in them is constrained. The type is specified\n\
2712at object creation time by using a type code, which is a single character.\n\
2713The following type codes are defined:\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002714\n\
2715 Type code C Type Minimum size in bytes \n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002716 'b' signed integer 1 \n\
2717 'B' unsigned integer 1 \n\
Victor Stinner62bb3942012-08-06 00:46:05 +02002718 'u' Unicode character 2 (see note) \n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002719 'h' signed integer 2 \n\
2720 'H' unsigned integer 2 \n\
2721 'i' signed integer 2 \n\
2722 'I' unsigned integer 2 \n\
2723 'l' signed integer 4 \n\
2724 'L' unsigned integer 4 \n\
Meador Inge1c9f0c92011-09-20 19:55:51 -05002725 'q' signed integer 8 (see note) \n\
2726 'Q' unsigned integer 8 (see note) \n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002727 'f' floating point 4 \n\
2728 'd' floating point 8 \n\
2729\n\
Victor Stinner62bb3942012-08-06 00:46:05 +02002730NOTE: The 'u' typecode corresponds to Python's unicode character. On \n\
2731narrow builds this is 2-bytes on wide builds this is 4-bytes.\n\
2732\n\
Meador Inge1c9f0c92011-09-20 19:55:51 -05002733NOTE: The 'q' and 'Q' type codes are only available if the platform \n\
2734C compiler used to build Python supports 'long long', or, on Windows, \n\
2735'__int64'.\n\
2736\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002737Methods:\n\
2738\n\
2739append() -- append a new item to the end of the array\n\
2740buffer_info() -- return information giving the current memory info\n\
2741byteswap() -- byteswap all the items of the array\n\
Mark Dickinson934896d2009-02-21 20:59:32 +00002742count() -- return number of occurrences of an object\n\
Raymond Hettinger49f9bd12004-03-14 05:43:59 +00002743extend() -- extend array by appending multiple elements from an iterable\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002744fromfile() -- read items from a file object\n\
2745fromlist() -- append items from the list\n\
Florent Xiclunac45fb252011-10-24 13:14:55 +02002746frombytes() -- append items from the string\n\
Mark Dickinson934896d2009-02-21 20:59:32 +00002747index() -- return index of first occurrence of an object\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002748insert() -- insert a new item into the array at a provided position\n\
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00002749pop() -- remove and return item (default last)\n\
Mark Dickinson934896d2009-02-21 20:59:32 +00002750remove() -- remove first occurrence of an object\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002751reverse() -- reverse the order of the items in the array\n\
2752tofile() -- write all items to a file object\n\
2753tolist() -- return the array converted to an ordinary list\n\
Florent Xiclunac45fb252011-10-24 13:14:55 +02002754tobytes() -- return the array converted to a string\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002755\n\
Martin v. Löwis99866332002-03-01 10:27:01 +00002756Attributes:\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002757\n\
2758typecode -- the typecode character used to create the array\n\
2759itemsize -- the length in bytes of one array item\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002760");
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002761
Raymond Hettinger625812f2003-01-07 01:58:52 +00002762static PyObject *array_iter(arrayobject *ao);
2763
Tim Peters0c322792002-07-17 16:49:03 +00002764static PyTypeObject Arraytype = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002765 PyVarObject_HEAD_INIT(NULL, 0)
2766 "array.array",
2767 sizeof(arrayobject),
2768 0,
2769 (destructor)array_dealloc, /* tp_dealloc */
2770 0, /* tp_print */
2771 0, /* tp_getattr */
2772 0, /* tp_setattr */
2773 0, /* tp_reserved */
2774 (reprfunc)array_repr, /* tp_repr */
2775 0, /* tp_as_number*/
2776 &array_as_sequence, /* tp_as_sequence*/
2777 &array_as_mapping, /* tp_as_mapping*/
2778 0, /* tp_hash */
2779 0, /* tp_call */
2780 0, /* tp_str */
2781 PyObject_GenericGetAttr, /* tp_getattro */
2782 0, /* tp_setattro */
2783 &array_as_buffer, /* tp_as_buffer*/
2784 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
2785 arraytype_doc, /* tp_doc */
2786 0, /* tp_traverse */
2787 0, /* tp_clear */
2788 array_richcompare, /* tp_richcompare */
2789 offsetof(arrayobject, weakreflist), /* tp_weaklistoffset */
2790 (getiterfunc)array_iter, /* tp_iter */
2791 0, /* tp_iternext */
2792 array_methods, /* tp_methods */
2793 0, /* tp_members */
2794 array_getsets, /* tp_getset */
2795 0, /* tp_base */
2796 0, /* tp_dict */
2797 0, /* tp_descr_get */
2798 0, /* tp_descr_set */
2799 0, /* tp_dictoffset */
2800 0, /* tp_init */
2801 PyType_GenericAlloc, /* tp_alloc */
2802 array_new, /* tp_new */
2803 PyObject_Del, /* tp_free */
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002804};
2805
Raymond Hettinger625812f2003-01-07 01:58:52 +00002806
2807/*********************** Array Iterator **************************/
2808
Brett Cannon1eb32c22014-10-10 16:26:45 -04002809/*[clinic input]
2810class array.arrayiterator "arrayiterobject *" "&PyArrayIter_Type"
2811[clinic start generated code]*/
2812/*[clinic end generated code: output=da39a3ee5e6b4b0d input=5aefd2d74d8c8e30]*/
Raymond Hettinger625812f2003-01-07 01:58:52 +00002813
2814static PyObject *
2815array_iter(arrayobject *ao)
2816{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002817 arrayiterobject *it;
Raymond Hettinger625812f2003-01-07 01:58:52 +00002818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002819 if (!array_Check(ao)) {
2820 PyErr_BadInternalCall();
2821 return NULL;
2822 }
Raymond Hettinger625812f2003-01-07 01:58:52 +00002823
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002824 it = PyObject_GC_New(arrayiterobject, &PyArrayIter_Type);
2825 if (it == NULL)
2826 return NULL;
Raymond Hettinger625812f2003-01-07 01:58:52 +00002827
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002828 Py_INCREF(ao);
2829 it->ao = ao;
2830 it->index = 0;
2831 it->getitem = ao->ob_descr->getitem;
2832 PyObject_GC_Track(it);
2833 return (PyObject *)it;
Raymond Hettinger625812f2003-01-07 01:58:52 +00002834}
2835
2836static PyObject *
Raymond Hettinger625812f2003-01-07 01:58:52 +00002837arrayiter_next(arrayiterobject *it)
2838{
Serhiy Storchakaab0d1982016-03-30 21:11:16 +03002839 arrayobject *ao;
2840
2841 assert(it != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002842 assert(PyArrayIter_Check(it));
Serhiy Storchakaab0d1982016-03-30 21:11:16 +03002843 ao = it->ao;
2844 if (ao == NULL) {
2845 return NULL;
2846 }
2847 assert(array_Check(ao));
2848 if (it->index < Py_SIZE(ao)) {
2849 return (*it->getitem)(ao, it->index++);
2850 }
2851 it->ao = NULL;
2852 Py_DECREF(ao);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002853 return NULL;
Raymond Hettinger625812f2003-01-07 01:58:52 +00002854}
2855
2856static void
2857arrayiter_dealloc(arrayiterobject *it)
2858{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002859 PyObject_GC_UnTrack(it);
2860 Py_XDECREF(it->ao);
2861 PyObject_GC_Del(it);
Raymond Hettinger625812f2003-01-07 01:58:52 +00002862}
2863
2864static int
2865arrayiter_traverse(arrayiterobject *it, visitproc visit, void *arg)
2866{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002867 Py_VISIT(it->ao);
2868 return 0;
Raymond Hettinger625812f2003-01-07 01:58:52 +00002869}
2870
Brett Cannon1eb32c22014-10-10 16:26:45 -04002871/*[clinic input]
2872array.arrayiterator.__reduce__
2873
2874Return state information for pickling.
2875[clinic start generated code]*/
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002876
2877static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04002878array_arrayiterator___reduce___impl(arrayiterobject *self)
2879/*[clinic end generated code: output=7898a52e8e66e016 input=a062ea1e9951417a]*/
2880{
Serhiy Storchakaab0d1982016-03-30 21:11:16 +03002881 PyObject *func = _PyObject_GetBuiltin("iter");
2882 if (self->ao == NULL) {
2883 return Py_BuildValue("N(())", func);
2884 }
2885 return Py_BuildValue("N(O)n", func, self->ao, self->index);
Brett Cannon1eb32c22014-10-10 16:26:45 -04002886}
2887
2888/*[clinic input]
2889array.arrayiterator.__setstate__
2890
2891 state: object
2892 /
2893
2894Set state information for unpickling.
2895[clinic start generated code]*/
2896
2897static PyObject *
2898array_arrayiterator___setstate__(arrayiterobject *self, PyObject *state)
2899/*[clinic end generated code: output=397da9904e443cbe input=f47d5ceda19e787b]*/
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002900{
2901 Py_ssize_t index = PyLong_AsSsize_t(state);
2902 if (index == -1 && PyErr_Occurred())
2903 return NULL;
2904 if (index < 0)
2905 index = 0;
Brett Cannon1eb32c22014-10-10 16:26:45 -04002906 else if (index > Py_SIZE(self->ao))
2907 index = Py_SIZE(self->ao); /* iterator exhausted */
2908 self->index = index;
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002909 Py_RETURN_NONE;
2910}
2911
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002912static PyMethodDef arrayiter_methods[] = {
Brett Cannon1eb32c22014-10-10 16:26:45 -04002913 ARRAY_ARRAYITERATOR___REDUCE___METHODDEF
2914 ARRAY_ARRAYITERATOR___SETSTATE___METHODDEF
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002915 {NULL, NULL} /* sentinel */
2916};
2917
Raymond Hettinger625812f2003-01-07 01:58:52 +00002918static PyTypeObject PyArrayIter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002919 PyVarObject_HEAD_INIT(NULL, 0)
2920 "arrayiterator", /* tp_name */
2921 sizeof(arrayiterobject), /* tp_basicsize */
2922 0, /* tp_itemsize */
2923 /* methods */
2924 (destructor)arrayiter_dealloc, /* tp_dealloc */
2925 0, /* tp_print */
2926 0, /* tp_getattr */
2927 0, /* tp_setattr */
2928 0, /* tp_reserved */
2929 0, /* tp_repr */
2930 0, /* tp_as_number */
2931 0, /* tp_as_sequence */
2932 0, /* tp_as_mapping */
2933 0, /* tp_hash */
2934 0, /* tp_call */
2935 0, /* tp_str */
2936 PyObject_GenericGetAttr, /* tp_getattro */
2937 0, /* tp_setattro */
2938 0, /* tp_as_buffer */
2939 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2940 0, /* tp_doc */
2941 (traverseproc)arrayiter_traverse, /* tp_traverse */
2942 0, /* tp_clear */
2943 0, /* tp_richcompare */
2944 0, /* tp_weaklistoffset */
2945 PyObject_SelfIter, /* tp_iter */
2946 (iternextfunc)arrayiter_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002947 arrayiter_methods, /* tp_methods */
Raymond Hettinger625812f2003-01-07 01:58:52 +00002948};
2949
2950
2951/*********************** Install Module **************************/
2952
Martin v. Löwis99866332002-03-01 10:27:01 +00002953/* No functions in array module. */
2954static PyMethodDef a_methods[] = {
Brett Cannon1eb32c22014-10-10 16:26:45 -04002955 ARRAY__ARRAY_RECONSTRUCTOR_METHODDEF
Martin v. Löwis99866332002-03-01 10:27:01 +00002956 {NULL, NULL, 0, NULL} /* Sentinel */
2957};
2958
Nick Coghland5cacbb2015-05-23 22:24:10 +10002959static int
2960array_modexec(PyObject *m)
Guido van Rossum778983b1993-02-19 15:55:02 +00002961{
Georg Brandl4cb0de22011-09-28 21:49:49 +02002962 char buffer[Py_ARRAY_LENGTH(descriptors)], *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002963 PyObject *typecodes;
2964 Py_ssize_t size = 0;
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02002965 const struct arraydescr *descr;
Fred Drake0d40ba42000-02-04 20:33:49 +00002966
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002967 if (PyType_Ready(&Arraytype) < 0)
Nick Coghland5cacbb2015-05-23 22:24:10 +10002968 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002969 Py_TYPE(&PyArrayIter_Type) = &PyType_Type;
Fred Drakef4e34842002-04-01 03:45:06 +00002970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002971 Py_INCREF((PyObject *)&Arraytype);
2972 PyModule_AddObject(m, "ArrayType", (PyObject *)&Arraytype);
2973 Py_INCREF((PyObject *)&Arraytype);
2974 PyModule_AddObject(m, "array", (PyObject *)&Arraytype);
Travis E. Oliphantd5c0add2007-10-12 22:05:15 +00002975
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002976 for (descr=descriptors; descr->typecode != '\0'; descr++) {
2977 size++;
2978 }
Travis E. Oliphantd5c0add2007-10-12 22:05:15 +00002979
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002980 p = buffer;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002981 for (descr = descriptors; descr->typecode != '\0'; descr++) {
2982 *p++ = (char)descr->typecode;
2983 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002984 typecodes = PyUnicode_DecodeASCII(buffer, p - buffer, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002985
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002986 PyModule_AddObject(m, "typecodes", typecodes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002987
2988 if (PyErr_Occurred()) {
2989 Py_DECREF(m);
2990 m = NULL;
2991 }
Nick Coghland5cacbb2015-05-23 22:24:10 +10002992 return 0;
2993}
2994
2995static PyModuleDef_Slot arrayslots[] = {
2996 {Py_mod_exec, array_modexec},
2997 {0, NULL}
2998};
2999
3000
3001static struct PyModuleDef arraymodule = {
3002 PyModuleDef_HEAD_INIT,
3003 "array",
3004 module_doc,
3005 0,
3006 a_methods,
3007 arrayslots,
3008 NULL,
3009 NULL,
3010 NULL
3011};
3012
3013
3014PyMODINIT_FUNC
3015PyInit_array(void)
3016{
3017 return PyModuleDef_Init(&arraymodule);
Guido van Rossum778983b1993-02-19 15:55:02 +00003018}