blob: a4966b4bddb53afefb60b3289ca2a90aa8b1db84 [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 *);
34 char *formats;
35 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;
43 struct arraydescr *ob_descr;
44 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 */
Guido van Rossum234f9421993-06-17 12:35:49 +0000514static 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 *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000542newarrayobject(PyTypeObject *type, Py_ssize_t size, 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;
Martin Panterbe8da9c2016-09-07 11:04:41 +0000748 if (ihigh > ilow) {
749 memcpy(np->ob_item, a->ob_item + ilow * a->ob_descr->itemsize,
750 (ihigh-ilow) * a->ob_descr->itemsize);
751 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000752 return (PyObject *)np;
Guido van Rossum778983b1993-02-19 15:55:02 +0000753}
754
Brett Cannon1eb32c22014-10-10 16:26:45 -0400755
756/*[clinic input]
757array.array.__copy__
758
759Return a copy of the array.
760[clinic start generated code]*/
761
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000762static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -0400763array_array___copy___impl(arrayobject *self)
764/*[clinic end generated code: output=dec7c3f925d9619e input=ad1ee5b086965f09]*/
Raymond Hettinger3aa82c02004-03-13 18:18:51 +0000765{
Brett Cannon1eb32c22014-10-10 16:26:45 -0400766 return array_slice(self, 0, Py_SIZE(self));
Raymond Hettinger3aa82c02004-03-13 18:18:51 +0000767}
768
Brett Cannon1eb32c22014-10-10 16:26:45 -0400769/*[clinic input]
770array.array.__deepcopy__
771
772 unused: object
773 /
774
775Return a copy of the array.
776[clinic start generated code]*/
777
778static PyObject *
779array_array___deepcopy__(arrayobject *self, PyObject *unused)
780/*[clinic end generated code: output=1ec748d8e14a9faa input=2405ecb4933748c4]*/
781{
782 return array_array___copy___impl(self);
783}
Raymond Hettinger3aa82c02004-03-13 18:18:51 +0000784
785static PyObject *
Peter Schneider-Kamp9656abd2000-07-13 21:10:57 +0000786array_concat(arrayobject *a, PyObject *bb)
Guido van Rossum778983b1993-02-19 15:55:02 +0000787{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000788 Py_ssize_t size;
789 arrayobject *np;
790 if (!array_Check(bb)) {
791 PyErr_Format(PyExc_TypeError,
792 "can only append array (not \"%.200s\") to array",
793 Py_TYPE(bb)->tp_name);
794 return NULL;
795 }
Guido van Rossum778983b1993-02-19 15:55:02 +0000796#define b ((arrayobject *)bb)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000797 if (a->ob_descr != b->ob_descr) {
798 PyErr_BadArgument();
799 return NULL;
800 }
801 if (Py_SIZE(a) > PY_SSIZE_T_MAX - Py_SIZE(b)) {
802 return PyErr_NoMemory();
803 }
804 size = Py_SIZE(a) + Py_SIZE(b);
805 np = (arrayobject *) newarrayobject(&Arraytype, size, a->ob_descr);
806 if (np == NULL) {
807 return NULL;
808 }
Martin Panterbe8da9c2016-09-07 11:04:41 +0000809 if (Py_SIZE(a) > 0) {
810 memcpy(np->ob_item, a->ob_item, Py_SIZE(a)*a->ob_descr->itemsize);
811 }
812 if (Py_SIZE(b) > 0) {
813 memcpy(np->ob_item + Py_SIZE(a)*a->ob_descr->itemsize,
814 b->ob_item, Py_SIZE(b)*b->ob_descr->itemsize);
815 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000816 return (PyObject *)np;
Guido van Rossum778983b1993-02-19 15:55:02 +0000817#undef b
818}
819
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000820static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000821array_repeat(arrayobject *a, Py_ssize_t n)
Guido van Rossum778983b1993-02-19 15:55:02 +0000822{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 Py_ssize_t size;
824 arrayobject *np;
Georg Brandlc29cc6a2010-12-04 11:02:04 +0000825 Py_ssize_t oldbytes, newbytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000826 if (n < 0)
827 n = 0;
828 if ((Py_SIZE(a) != 0) && (n > PY_SSIZE_T_MAX / Py_SIZE(a))) {
829 return PyErr_NoMemory();
830 }
831 size = Py_SIZE(a) * n;
832 np = (arrayobject *) newarrayobject(&Arraytype, size, a->ob_descr);
833 if (np == NULL)
834 return NULL;
Martin Panterbe8da9c2016-09-07 11:04:41 +0000835 if (size == 0)
Georg Brandlc29cc6a2010-12-04 11:02:04 +0000836 return (PyObject *)np;
837 oldbytes = Py_SIZE(a) * a->ob_descr->itemsize;
838 newbytes = oldbytes * n;
839 /* this follows the code in unicode_repeat */
840 if (oldbytes == 1) {
841 memset(np->ob_item, a->ob_item[0], newbytes);
842 } else {
843 Py_ssize_t done = oldbytes;
844 Py_MEMCPY(np->ob_item, a->ob_item, oldbytes);
845 while (done < newbytes) {
846 Py_ssize_t ncopy = (done <= newbytes-done) ? done : newbytes-done;
847 Py_MEMCPY(np->ob_item+done, np->ob_item, ncopy);
848 done += ncopy;
849 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000850 }
Georg Brandlc29cc6a2010-12-04 11:02:04 +0000851 return (PyObject *)np;
Guido van Rossum778983b1993-02-19 15:55:02 +0000852}
853
854static int
Martin v. Löwisad0a4622006-02-16 14:30:23 +0000855array_ass_slice(arrayobject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum778983b1993-02-19 15:55:02 +0000856{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000857 char *item;
858 Py_ssize_t n; /* Size of replacement array */
859 Py_ssize_t d; /* Change in size */
Guido van Rossum778983b1993-02-19 15:55:02 +0000860#define b ((arrayobject *)v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000861 if (v == NULL)
862 n = 0;
863 else if (array_Check(v)) {
864 n = Py_SIZE(b);
865 if (a == b) {
866 /* Special case "a[i:j] = a" -- copy b first */
867 int ret;
868 v = array_slice(b, 0, n);
869 if (!v)
870 return -1;
871 ret = array_ass_slice(a, ilow, ihigh, v);
872 Py_DECREF(v);
873 return ret;
874 }
875 if (b->ob_descr != a->ob_descr) {
876 PyErr_BadArgument();
877 return -1;
878 }
879 }
880 else {
881 PyErr_Format(PyExc_TypeError,
882 "can only assign array (not \"%.200s\") to array slice",
883 Py_TYPE(v)->tp_name);
884 return -1;
885 }
886 if (ilow < 0)
887 ilow = 0;
888 else if (ilow > Py_SIZE(a))
889 ilow = Py_SIZE(a);
890 if (ihigh < 0)
891 ihigh = 0;
892 if (ihigh < ilow)
893 ihigh = ilow;
894 else if (ihigh > Py_SIZE(a))
895 ihigh = Py_SIZE(a);
896 item = a->ob_item;
897 d = n - (ihigh-ilow);
898 /* Issue #4509: If the array has exported buffers and the slice
899 assignment would change the size of the array, fail early to make
900 sure we don't modify it. */
901 if (d != 0 && a->ob_exports > 0) {
902 PyErr_SetString(PyExc_BufferError,
903 "cannot resize an array that is exporting buffers");
904 return -1;
905 }
906 if (d < 0) { /* Delete -d items */
907 memmove(item + (ihigh+d)*a->ob_descr->itemsize,
908 item + ihigh*a->ob_descr->itemsize,
909 (Py_SIZE(a)-ihigh)*a->ob_descr->itemsize);
910 if (array_resize(a, Py_SIZE(a) + d) == -1)
911 return -1;
912 }
913 else if (d > 0) { /* Insert d items */
914 if (array_resize(a, Py_SIZE(a) + d))
915 return -1;
916 memmove(item + (ihigh+d)*a->ob_descr->itemsize,
917 item + ihigh*a->ob_descr->itemsize,
918 (Py_SIZE(a)-ihigh)*a->ob_descr->itemsize);
919 }
920 if (n > 0)
921 memcpy(item + ilow*a->ob_descr->itemsize, b->ob_item,
922 n*b->ob_descr->itemsize);
923 return 0;
Guido van Rossum778983b1993-02-19 15:55:02 +0000924#undef b
925}
926
927static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000928array_ass_item(arrayobject *a, Py_ssize_t i, PyObject *v)
Guido van Rossum778983b1993-02-19 15:55:02 +0000929{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000930 if (i < 0 || i >= Py_SIZE(a)) {
931 PyErr_SetString(PyExc_IndexError,
932 "array assignment index out of range");
933 return -1;
934 }
935 if (v == NULL)
936 return array_ass_slice(a, i, i+1, v);
937 return (*a->ob_descr->setitem)(a, i, v);
Guido van Rossum778983b1993-02-19 15:55:02 +0000938}
939
940static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000941setarrayitem(PyObject *a, Py_ssize_t i, PyObject *v)
Guido van Rossum778983b1993-02-19 15:55:02 +0000942{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000943 assert(array_Check(a));
944 return array_ass_item((arrayobject *)a, i, v);
Guido van Rossum778983b1993-02-19 15:55:02 +0000945}
946
Martin v. Löwis99866332002-03-01 10:27:01 +0000947static int
Raymond Hettinger49f9bd12004-03-14 05:43:59 +0000948array_iter_extend(arrayobject *self, PyObject *bb)
949{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 PyObject *it, *v;
Raymond Hettinger49f9bd12004-03-14 05:43:59 +0000951
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 it = PyObject_GetIter(bb);
953 if (it == NULL)
954 return -1;
Raymond Hettinger49f9bd12004-03-14 05:43:59 +0000955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000956 while ((v = PyIter_Next(it)) != NULL) {
Mark Dickinson346f0af2010-08-06 09:36:57 +0000957 if (ins1(self, Py_SIZE(self), v) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000958 Py_DECREF(v);
959 Py_DECREF(it);
960 return -1;
961 }
962 Py_DECREF(v);
963 }
964 Py_DECREF(it);
965 if (PyErr_Occurred())
966 return -1;
967 return 0;
Raymond Hettinger49f9bd12004-03-14 05:43:59 +0000968}
969
970static int
Martin v. Löwis99866332002-03-01 10:27:01 +0000971array_do_extend(arrayobject *self, PyObject *bb)
972{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000973 Py_ssize_t size, oldsize, bbsize;
Martin v. Löwis99866332002-03-01 10:27:01 +0000974
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000975 if (!array_Check(bb))
976 return array_iter_extend(self, bb);
977#define b ((arrayobject *)bb)
978 if (self->ob_descr != b->ob_descr) {
979 PyErr_SetString(PyExc_TypeError,
980 "can only extend with array of same kind");
981 return -1;
982 }
983 if ((Py_SIZE(self) > PY_SSIZE_T_MAX - Py_SIZE(b)) ||
984 ((Py_SIZE(self) + Py_SIZE(b)) > PY_SSIZE_T_MAX / self->ob_descr->itemsize)) {
985 PyErr_NoMemory();
986 return -1;
987 }
988 oldsize = Py_SIZE(self);
989 /* Get the size of bb before resizing the array since bb could be self. */
990 bbsize = Py_SIZE(bb);
991 size = oldsize + Py_SIZE(b);
992 if (array_resize(self, size) == -1)
993 return -1;
Martin Panterbe8da9c2016-09-07 11:04:41 +0000994 if (bbsize > 0) {
995 memcpy(self->ob_item + oldsize * self->ob_descr->itemsize,
996 b->ob_item, bbsize * b->ob_descr->itemsize);
997 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998
999 return 0;
Martin v. Löwis99866332002-03-01 10:27:01 +00001000#undef b
1001}
1002
1003static PyObject *
1004array_inplace_concat(arrayobject *self, PyObject *bb)
1005{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001006 if (!array_Check(bb)) {
1007 PyErr_Format(PyExc_TypeError,
1008 "can only extend array with array (not \"%.200s\")",
1009 Py_TYPE(bb)->tp_name);
1010 return NULL;
1011 }
1012 if (array_do_extend(self, bb) == -1)
1013 return NULL;
1014 Py_INCREF(self);
1015 return (PyObject *)self;
Martin v. Löwis99866332002-03-01 10:27:01 +00001016}
1017
1018static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001019array_inplace_repeat(arrayobject *self, Py_ssize_t n)
Martin v. Löwis99866332002-03-01 10:27:01 +00001020{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001021 char *items, *p;
1022 Py_ssize_t size, i;
Martin v. Löwis99866332002-03-01 10:27:01 +00001023
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001024 if (Py_SIZE(self) > 0) {
1025 if (n < 0)
1026 n = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 if ((self->ob_descr->itemsize != 0) &&
1028 (Py_SIZE(self) > PY_SSIZE_T_MAX / self->ob_descr->itemsize)) {
1029 return PyErr_NoMemory();
1030 }
1031 size = Py_SIZE(self) * self->ob_descr->itemsize;
1032 if (n > 0 && size > PY_SSIZE_T_MAX / n) {
1033 return PyErr_NoMemory();
1034 }
1035 if (array_resize(self, n * Py_SIZE(self)) == -1)
1036 return NULL;
1037 items = p = self->ob_item;
1038 for (i = 1; i < n; i++) {
1039 p += size;
1040 memcpy(p, items, size);
1041 }
1042 }
1043 Py_INCREF(self);
1044 return (PyObject *)self;
Martin v. Löwis99866332002-03-01 10:27:01 +00001045}
1046
1047
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001048static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001049ins(arrayobject *self, Py_ssize_t where, PyObject *v)
Guido van Rossum778983b1993-02-19 15:55:02 +00001050{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001051 if (ins1(self, where, v) != 0)
1052 return NULL;
1053 Py_INCREF(Py_None);
1054 return Py_None;
Guido van Rossum778983b1993-02-19 15:55:02 +00001055}
1056
Brett Cannon1eb32c22014-10-10 16:26:45 -04001057/*[clinic input]
1058array.array.count
1059
1060 v: object
1061 /
1062
1063Return number of occurrences of v in the array.
1064[clinic start generated code]*/
1065
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001066static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001067array_array_count(arrayobject *self, PyObject *v)
1068/*[clinic end generated code: output=3dd3624bf7135a3a input=d9bce9d65e39d1f5]*/
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001069{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 Py_ssize_t count = 0;
1071 Py_ssize_t i;
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 for (i = 0; i < Py_SIZE(self); i++) {
Victor Stinner0b142e22013-07-17 23:01:30 +02001074 PyObject *selfi;
1075 int cmp;
1076
1077 selfi = getarrayitem((PyObject *)self, i);
1078 if (selfi == NULL)
1079 return NULL;
1080 cmp = PyObject_RichCompareBool(selfi, v, Py_EQ);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001081 Py_DECREF(selfi);
1082 if (cmp > 0)
1083 count++;
1084 else if (cmp < 0)
1085 return NULL;
1086 }
1087 return PyLong_FromSsize_t(count);
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001088}
1089
Brett Cannon1eb32c22014-10-10 16:26:45 -04001090
1091/*[clinic input]
1092array.array.index
1093
1094 v: object
1095 /
1096
1097Return index of first occurrence of v in the array.
1098[clinic start generated code]*/
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001099
1100static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001101array_array_index(arrayobject *self, PyObject *v)
1102/*[clinic end generated code: output=d48498d325602167 input=cf619898c6649d08]*/
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001103{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001104 Py_ssize_t i;
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 for (i = 0; i < Py_SIZE(self); i++) {
Victor Stinner0b142e22013-07-17 23:01:30 +02001107 PyObject *selfi;
1108 int cmp;
1109
1110 selfi = getarrayitem((PyObject *)self, i);
1111 if (selfi == NULL)
1112 return NULL;
1113 cmp = PyObject_RichCompareBool(selfi, v, Py_EQ);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001114 Py_DECREF(selfi);
1115 if (cmp > 0) {
1116 return PyLong_FromLong((long)i);
1117 }
1118 else if (cmp < 0)
1119 return NULL;
1120 }
1121 PyErr_SetString(PyExc_ValueError, "array.index(x): x not in list");
1122 return NULL;
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001123}
1124
Raymond Hettinger625812f2003-01-07 01:58:52 +00001125static int
1126array_contains(arrayobject *self, PyObject *v)
1127{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001128 Py_ssize_t i;
1129 int cmp;
Raymond Hettinger625812f2003-01-07 01:58:52 +00001130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001131 for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(self); i++) {
1132 PyObject *selfi = getarrayitem((PyObject *)self, i);
Victor Stinner0b142e22013-07-17 23:01:30 +02001133 if (selfi == NULL)
Victor Stinner4755bea2013-07-18 01:12:35 +02001134 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001135 cmp = PyObject_RichCompareBool(selfi, v, Py_EQ);
1136 Py_DECREF(selfi);
1137 }
1138 return cmp;
Raymond Hettinger625812f2003-01-07 01:58:52 +00001139}
1140
Brett Cannon1eb32c22014-10-10 16:26:45 -04001141/*[clinic input]
1142array.array.remove
1143
1144 v: object
1145 /
1146
1147Remove the first occurrence of v in the array.
1148[clinic start generated code]*/
1149
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001150static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001151array_array_remove(arrayobject *self, PyObject *v)
1152/*[clinic end generated code: output=bef06be9fdf9dceb input=0b1e5aed25590027]*/
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001153{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001154 int i;
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001155
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001156 for (i = 0; i < Py_SIZE(self); i++) {
Victor Stinner0b142e22013-07-17 23:01:30 +02001157 PyObject *selfi;
1158 int cmp;
1159
1160 selfi = getarrayitem((PyObject *)self,i);
1161 if (selfi == NULL)
1162 return NULL;
1163 cmp = PyObject_RichCompareBool(selfi, v, Py_EQ);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001164 Py_DECREF(selfi);
1165 if (cmp > 0) {
1166 if (array_ass_slice(self, i, i+1,
1167 (PyObject *)NULL) != 0)
1168 return NULL;
1169 Py_INCREF(Py_None);
1170 return Py_None;
1171 }
1172 else if (cmp < 0)
1173 return NULL;
1174 }
1175 PyErr_SetString(PyExc_ValueError, "array.remove(x): x not in list");
1176 return NULL;
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001177}
1178
Brett Cannon1eb32c22014-10-10 16:26:45 -04001179/*[clinic input]
1180array.array.pop
1181
1182 i: Py_ssize_t = -1
1183 /
1184
1185Return the i-th element and delete it from the array.
1186
1187i defaults to -1.
1188[clinic start generated code]*/
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001189
1190static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001191array_array_pop_impl(arrayobject *self, Py_ssize_t i)
1192/*[clinic end generated code: output=bc1f0c54fe5308e4 input=8e5feb4c1a11cd44]*/
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001193{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 PyObject *v;
Brett Cannon1eb32c22014-10-10 16:26:45 -04001195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001196 if (Py_SIZE(self) == 0) {
1197 /* Special-case most common failure cause */
1198 PyErr_SetString(PyExc_IndexError, "pop from empty array");
1199 return NULL;
1200 }
1201 if (i < 0)
1202 i += Py_SIZE(self);
1203 if (i < 0 || i >= Py_SIZE(self)) {
1204 PyErr_SetString(PyExc_IndexError, "pop index out of range");
1205 return NULL;
1206 }
Victor Stinner0b142e22013-07-17 23:01:30 +02001207 v = getarrayitem((PyObject *)self, i);
1208 if (v == NULL)
1209 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001210 if (array_ass_slice(self, i, i+1, (PyObject *)NULL) != 0) {
1211 Py_DECREF(v);
1212 return NULL;
1213 }
1214 return v;
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001215}
1216
Brett Cannon1eb32c22014-10-10 16:26:45 -04001217/*[clinic input]
1218array.array.extend
1219
1220 bb: object
1221 /
1222
1223Append items to the end of the array.
1224[clinic start generated code]*/
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001225
1226static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001227array_array_extend(arrayobject *self, PyObject *bb)
1228/*[clinic end generated code: output=bbddbc8e8bef871d input=43be86aba5c31e44]*/
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001229{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001230 if (array_do_extend(self, bb) == -1)
1231 return NULL;
1232 Py_INCREF(Py_None);
1233 return Py_None;
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001234}
1235
Brett Cannon1eb32c22014-10-10 16:26:45 -04001236/*[clinic input]
1237array.array.insert
1238
1239 i: Py_ssize_t
1240 v: object
1241 /
1242
1243Insert a new item v into the array before position i.
1244[clinic start generated code]*/
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001245
1246static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001247array_array_insert_impl(arrayobject *self, Py_ssize_t i, PyObject *v)
1248/*[clinic end generated code: output=5a3648e278348564 input=5577d1b4383e9313]*/
Guido van Rossum778983b1993-02-19 15:55:02 +00001249{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001250 return ins(self, i, v);
Guido van Rossum778983b1993-02-19 15:55:02 +00001251}
1252
Brett Cannon1eb32c22014-10-10 16:26:45 -04001253/*[clinic input]
1254array.array.buffer_info
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001255
Brett Cannon1eb32c22014-10-10 16:26:45 -04001256Return a tuple (address, length) giving the current memory address and the length in items of the buffer used to hold array's contents.
1257
1258The length should be multiplied by the itemsize attribute to calculate
1259the buffer length in bytes.
1260[clinic start generated code]*/
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001261
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001262static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001263array_array_buffer_info_impl(arrayobject *self)
1264/*[clinic end generated code: output=9b2a4ec3ae7e98e7 input=a58bae5c6e1ac6a6]*/
Guido van Rossumde4a4ca1997-08-12 14:55:56 +00001265{
Victor Stinner541067a2013-11-14 01:27:12 +01001266 PyObject *retval = NULL, *v;
1267
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001268 retval = PyTuple_New(2);
1269 if (!retval)
1270 return NULL;
Fred Drake541dc3b2000-06-28 17:49:30 +00001271
Victor Stinner541067a2013-11-14 01:27:12 +01001272 v = PyLong_FromVoidPtr(self->ob_item);
1273 if (v == NULL) {
1274 Py_DECREF(retval);
1275 return NULL;
1276 }
1277 PyTuple_SET_ITEM(retval, 0, v);
1278
Serhiy Storchaka9e941d62016-06-23 23:55:34 +03001279 v = PyLong_FromSsize_t(Py_SIZE(self));
Victor Stinner541067a2013-11-14 01:27:12 +01001280 if (v == NULL) {
1281 Py_DECREF(retval);
1282 return NULL;
1283 }
1284 PyTuple_SET_ITEM(retval, 1, v);
Fred Drake541dc3b2000-06-28 17:49:30 +00001285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001286 return retval;
Guido van Rossumde4a4ca1997-08-12 14:55:56 +00001287}
1288
Brett Cannon1eb32c22014-10-10 16:26:45 -04001289/*[clinic input]
1290array.array.append
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001291
Brett Cannon1eb32c22014-10-10 16:26:45 -04001292 v: object
1293 /
1294
1295Append new value v to the end of the array.
1296[clinic start generated code]*/
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001297
Guido van Rossumde4a4ca1997-08-12 14:55:56 +00001298static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001299array_array_append(arrayobject *self, PyObject *v)
1300/*[clinic end generated code: output=745a0669bf8db0e2 input=0b98d9d78e78f0fa]*/
Guido van Rossum778983b1993-02-19 15:55:02 +00001301{
Mark Dickinson346f0af2010-08-06 09:36:57 +00001302 return ins(self, Py_SIZE(self), v);
Guido van Rossum778983b1993-02-19 15:55:02 +00001303}
1304
Brett Cannon1eb32c22014-10-10 16:26:45 -04001305/*[clinic input]
1306array.array.byteswap
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001307
Brett Cannon1eb32c22014-10-10 16:26:45 -04001308Byteswap all items of the array.
1309
1310If the items in the array are not 1, 2, 4, or 8 bytes in size, RuntimeError is
1311raised.
1312[clinic start generated code]*/
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001313
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001314static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001315array_array_byteswap_impl(arrayobject *self)
1316/*[clinic end generated code: output=5f8236cbdf0d90b5 input=6a85591b950a0186]*/
Guido van Rossum778983b1993-02-19 15:55:02 +00001317{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001318 char *p;
1319 Py_ssize_t i;
Fred Drakebf272981999-12-03 17:15:30 +00001320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001321 switch (self->ob_descr->itemsize) {
1322 case 1:
1323 break;
1324 case 2:
1325 for (p = self->ob_item, i = Py_SIZE(self); --i >= 0; p += 2) {
1326 char p0 = p[0];
1327 p[0] = p[1];
1328 p[1] = p0;
1329 }
1330 break;
1331 case 4:
1332 for (p = self->ob_item, i = Py_SIZE(self); --i >= 0; p += 4) {
1333 char p0 = p[0];
1334 char p1 = p[1];
1335 p[0] = p[3];
1336 p[1] = p[2];
1337 p[2] = p1;
1338 p[3] = p0;
1339 }
1340 break;
1341 case 8:
1342 for (p = self->ob_item, i = Py_SIZE(self); --i >= 0; p += 8) {
1343 char p0 = p[0];
1344 char p1 = p[1];
1345 char p2 = p[2];
1346 char p3 = p[3];
1347 p[0] = p[7];
1348 p[1] = p[6];
1349 p[2] = p[5];
1350 p[3] = p[4];
1351 p[4] = p3;
1352 p[5] = p2;
1353 p[6] = p1;
1354 p[7] = p0;
1355 }
1356 break;
1357 default:
1358 PyErr_SetString(PyExc_RuntimeError,
1359 "don't know how to byteswap this array type");
1360 return NULL;
1361 }
1362 Py_INCREF(Py_None);
1363 return Py_None;
Guido van Rossum778983b1993-02-19 15:55:02 +00001364}
1365
Brett Cannon1eb32c22014-10-10 16:26:45 -04001366/*[clinic input]
1367array.array.reverse
1368
1369Reverse the order of the items in the array.
1370[clinic start generated code]*/
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001371
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001372static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001373array_array_reverse_impl(arrayobject *self)
1374/*[clinic end generated code: output=c04868b36f6f4089 input=cd904f01b27d966a]*/
Guido van Rossum778983b1993-02-19 15:55:02 +00001375{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001376 Py_ssize_t itemsize = self->ob_descr->itemsize;
1377 char *p, *q;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001378 /* little buffer to hold items while swapping */
1379 char tmp[256]; /* 8 is probably enough -- but why skimp */
1380 assert((size_t)itemsize <= sizeof(tmp));
Guido van Rossume77a7571993-11-03 15:01:26 +00001381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001382 if (Py_SIZE(self) > 1) {
1383 for (p = self->ob_item,
1384 q = self->ob_item + (Py_SIZE(self) - 1)*itemsize;
1385 p < q;
1386 p += itemsize, q -= itemsize) {
1387 /* memory areas guaranteed disjoint, so memcpy
1388 * is safe (& memmove may be slower).
1389 */
1390 memcpy(tmp, p, itemsize);
1391 memcpy(p, q, itemsize);
1392 memcpy(q, tmp, itemsize);
1393 }
1394 }
Tim Petersbb307342000-09-10 05:22:54 +00001395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001396 Py_INCREF(Py_None);
1397 return Py_None;
Guido van Rossum778983b1993-02-19 15:55:02 +00001398}
Guido van Rossume77a7571993-11-03 15:01:26 +00001399
Brett Cannon1eb32c22014-10-10 16:26:45 -04001400/*[clinic input]
1401array.array.fromfile
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001402
Brett Cannon1eb32c22014-10-10 16:26:45 -04001403 f: object
1404 n: Py_ssize_t
1405 /
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001406
Brett Cannon1eb32c22014-10-10 16:26:45 -04001407Read n objects from the file object f and append them to the end of the array.
1408[clinic start generated code]*/
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001409
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001410static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001411array_array_fromfile_impl(arrayobject *self, PyObject *f, Py_ssize_t n)
1412/*[clinic end generated code: output=ec9f600e10f53510 input=e188afe8e58adf40]*/
Guido van Rossum778983b1993-02-19 15:55:02 +00001413{
Serhiy Storchaka04e6dba2015-04-04 17:06:55 +03001414 PyObject *b, *res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001415 Py_ssize_t itemsize = self->ob_descr->itemsize;
Brett Cannon1eb32c22014-10-10 16:26:45 -04001416 Py_ssize_t nbytes;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001417 _Py_IDENTIFIER(read);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001418 int not_enough_bytes;
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001419
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01001420 if (n < 0) {
1421 PyErr_SetString(PyExc_ValueError, "negative count");
1422 return NULL;
1423 }
1424 if (n > PY_SSIZE_T_MAX / itemsize) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001425 PyErr_NoMemory();
1426 return NULL;
1427 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01001428 nbytes = n * itemsize;
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001429
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001430 b = _PyObject_CallMethodId(f, &PyId_read, "n", nbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001431 if (b == NULL)
1432 return NULL;
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001434 if (!PyBytes_Check(b)) {
1435 PyErr_SetString(PyExc_TypeError,
1436 "read() didn't return bytes");
1437 Py_DECREF(b);
1438 return NULL;
1439 }
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001440
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001441 not_enough_bytes = (PyBytes_GET_SIZE(b) != nbytes);
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001442
Serhiy Storchaka04e6dba2015-04-04 17:06:55 +03001443 res = array_array_frombytes(self, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001444 Py_DECREF(b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001445 if (res == NULL)
1446 return NULL;
Hirokazu Yamamoto54d0df62009-03-06 03:04:07 +00001447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001448 if (not_enough_bytes) {
1449 PyErr_SetString(PyExc_EOFError,
1450 "read() didn't return enough bytes");
1451 Py_DECREF(res);
1452 return NULL;
1453 }
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001454
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001455 return res;
Guido van Rossum778983b1993-02-19 15:55:02 +00001456}
1457
Brett Cannon1eb32c22014-10-10 16:26:45 -04001458/*[clinic input]
1459array.array.tofile
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001460
Brett Cannon1eb32c22014-10-10 16:26:45 -04001461 f: object
1462 /
1463
1464Write all items (as machine values) to the file object f.
1465[clinic start generated code]*/
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001466
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001467static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001468array_array_tofile(arrayobject *self, PyObject *f)
1469/*[clinic end generated code: output=3a2cfa8128df0777 input=b0669a484aab0831]*/
Guido van Rossum778983b1993-02-19 15:55:02 +00001470{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001471 Py_ssize_t nbytes = Py_SIZE(self) * self->ob_descr->itemsize;
1472 /* Write 64K blocks at a time */
1473 /* XXX Make the block size settable */
1474 int BLOCKSIZE = 64*1024;
1475 Py_ssize_t nblocks = (nbytes + BLOCKSIZE - 1) / BLOCKSIZE;
1476 Py_ssize_t i;
Raymond Hettinger36cd2bf2003-01-03 08:24:58 +00001477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001478 if (Py_SIZE(self) == 0)
1479 goto done;
Guido van Rossumb5ddcfd2007-04-11 17:08:28 +00001480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001481 for (i = 0; i < nblocks; i++) {
1482 char* ptr = self->ob_item + i*BLOCKSIZE;
1483 Py_ssize_t size = BLOCKSIZE;
1484 PyObject *bytes, *res;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001485 _Py_IDENTIFIER(write);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001487 if (i*BLOCKSIZE + size > nbytes)
1488 size = nbytes - i*BLOCKSIZE;
1489 bytes = PyBytes_FromStringAndSize(ptr, size);
1490 if (bytes == NULL)
1491 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001492 res = _PyObject_CallMethodId(f, &PyId_write, "O", bytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001493 Py_DECREF(bytes);
1494 if (res == NULL)
1495 return NULL;
1496 Py_DECREF(res); /* drop write result */
1497 }
Guido van Rossumb5ddcfd2007-04-11 17:08:28 +00001498
1499 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001500 Py_INCREF(Py_None);
1501 return Py_None;
Guido van Rossum778983b1993-02-19 15:55:02 +00001502}
1503
Brett Cannon1eb32c22014-10-10 16:26:45 -04001504/*[clinic input]
1505array.array.fromlist
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001506
Brett Cannon1eb32c22014-10-10 16:26:45 -04001507 list: object
1508 /
1509
1510Append items to array from list.
1511[clinic start generated code]*/
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001512
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001513static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001514array_array_fromlist(arrayobject *self, PyObject *list)
1515/*[clinic end generated code: output=26411c2d228a3e3f input=be2605a96c49680f]*/
Guido van Rossum778983b1993-02-19 15:55:02 +00001516{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001517 Py_ssize_t n;
Raymond Hettinger36cd2bf2003-01-03 08:24:58 +00001518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001519 if (!PyList_Check(list)) {
1520 PyErr_SetString(PyExc_TypeError, "arg must be list");
1521 return NULL;
1522 }
1523 n = PyList_Size(list);
1524 if (n > 0) {
1525 Py_ssize_t i, old_size;
1526 old_size = Py_SIZE(self);
1527 if (array_resize(self, old_size + n) == -1)
1528 return NULL;
1529 for (i = 0; i < n; i++) {
1530 PyObject *v = PyList_GetItem(list, i);
1531 if ((*self->ob_descr->setitem)(self,
1532 Py_SIZE(self) - n + i, v) != 0) {
1533 array_resize(self, old_size);
1534 return NULL;
1535 }
1536 }
1537 }
1538 Py_INCREF(Py_None);
1539 return Py_None;
Guido van Rossum778983b1993-02-19 15:55:02 +00001540}
1541
Brett Cannon1eb32c22014-10-10 16:26:45 -04001542/*[clinic input]
1543array.array.tolist
1544
1545Convert array to an ordinary list with the same items.
1546[clinic start generated code]*/
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001547
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001548static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001549array_array_tolist_impl(arrayobject *self)
1550/*[clinic end generated code: output=00b60cc9eab8ef89 input=a8d7784a94f86b53]*/
Guido van Rossum778983b1993-02-19 15:55:02 +00001551{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001552 PyObject *list = PyList_New(Py_SIZE(self));
1553 Py_ssize_t i;
Raymond Hettinger36cd2bf2003-01-03 08:24:58 +00001554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001555 if (list == NULL)
1556 return NULL;
1557 for (i = 0; i < Py_SIZE(self); i++) {
1558 PyObject *v = getarrayitem((PyObject *)self, i);
Victor Stinner4755bea2013-07-18 01:12:35 +02001559 if (v == NULL)
1560 goto error;
1561 if (PyList_SetItem(list, i, v) < 0)
1562 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001563 }
1564 return list;
Victor Stinner4755bea2013-07-18 01:12:35 +02001565
1566error:
1567 Py_DECREF(list);
1568 return NULL;
Guido van Rossum778983b1993-02-19 15:55:02 +00001569}
1570
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001571static PyObject *
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001572frombytes(arrayobject *self, Py_buffer *buffer)
Guido van Rossum778983b1993-02-19 15:55:02 +00001573{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001574 int itemsize = self->ob_descr->itemsize;
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001575 Py_ssize_t n;
1576 if (buffer->itemsize != 1) {
1577 PyBuffer_Release(buffer);
Serhiy Storchakab757c832014-12-05 22:25:22 +02001578 PyErr_SetString(PyExc_TypeError, "a bytes-like object is required");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001579 return NULL;
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001580 }
1581 n = buffer->len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001582 if (n % itemsize != 0) {
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001583 PyBuffer_Release(buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001584 PyErr_SetString(PyExc_ValueError,
Serhiy Storchakab757c832014-12-05 22:25:22 +02001585 "bytes length not a multiple of item size");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001586 return NULL;
1587 }
1588 n = n / itemsize;
1589 if (n > 0) {
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001590 Py_ssize_t old_size = Py_SIZE(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001591 if ((n > PY_SSIZE_T_MAX - old_size) ||
1592 ((old_size + n) > PY_SSIZE_T_MAX / itemsize)) {
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001593 PyBuffer_Release(buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001594 return PyErr_NoMemory();
1595 }
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001596 if (array_resize(self, old_size + n) == -1) {
1597 PyBuffer_Release(buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001598 return NULL;
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001599 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001600 memcpy(self->ob_item + old_size * itemsize,
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001601 buffer->buf, n * itemsize);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001602 }
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001603 PyBuffer_Release(buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001604 Py_INCREF(Py_None);
1605 return Py_None;
Guido van Rossum778983b1993-02-19 15:55:02 +00001606}
1607
Brett Cannon1eb32c22014-10-10 16:26:45 -04001608/*[clinic input]
1609array.array.fromstring
1610
Larry Hastingsdbfdc382015-05-04 06:59:46 -07001611 buffer: Py_buffer(accept={str, buffer})
Brett Cannon1eb32c22014-10-10 16:26:45 -04001612 /
1613
1614Appends 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).
1615
1616This method is deprecated. Use frombytes instead.
1617[clinic start generated code]*/
1618
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001619static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001620array_array_fromstring_impl(arrayobject *self, Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07001621/*[clinic end generated code: output=31c4baa779df84ce input=a3341a512e11d773]*/
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001622{
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001623 if (PyErr_WarnEx(PyExc_DeprecationWarning,
1624 "fromstring() is deprecated. Use frombytes() instead.", 2) != 0)
1625 return NULL;
Brett Cannon1eb32c22014-10-10 16:26:45 -04001626 return frombytes(self, buffer);
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001627}
1628
Brett Cannon1eb32c22014-10-10 16:26:45 -04001629/*[clinic input]
1630array.array.frombytes
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001631
Brett Cannon1eb32c22014-10-10 16:26:45 -04001632 buffer: Py_buffer
1633 /
1634
1635Appends 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).
1636[clinic start generated code]*/
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001637
1638static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001639array_array_frombytes_impl(arrayobject *self, Py_buffer *buffer)
1640/*[clinic end generated code: output=d9842c8f7510a516 input=2bbf2b53ebfcc988]*/
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001641{
Brett Cannon1eb32c22014-10-10 16:26:45 -04001642 return frombytes(self, buffer);
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001643}
1644
Brett Cannon1eb32c22014-10-10 16:26:45 -04001645/*[clinic input]
1646array.array.tobytes
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001647
Brett Cannon1eb32c22014-10-10 16:26:45 -04001648Convert the array to an array of machine values and return the bytes representation.
1649[clinic start generated code]*/
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001650
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001651static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001652array_array_tobytes_impl(arrayobject *self)
1653/*[clinic end generated code: output=87318e4edcdc2bb6 input=90ee495f96de34f5]*/
Guido van Rossum778983b1993-02-19 15:55:02 +00001654{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001655 if (Py_SIZE(self) <= PY_SSIZE_T_MAX / self->ob_descr->itemsize) {
1656 return PyBytes_FromStringAndSize(self->ob_item,
1657 Py_SIZE(self) * self->ob_descr->itemsize);
1658 } else {
1659 return PyErr_NoMemory();
1660 }
Guido van Rossum778983b1993-02-19 15:55:02 +00001661}
1662
Brett Cannon1eb32c22014-10-10 16:26:45 -04001663/*[clinic input]
1664array.array.tostring
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001665
Brett Cannon1eb32c22014-10-10 16:26:45 -04001666Convert the array to an array of machine values and return the bytes representation.
1667
1668This method is deprecated. Use tobytes instead.
1669[clinic start generated code]*/
Martin v. Löwis99866332002-03-01 10:27:01 +00001670
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001671static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001672array_array_tostring_impl(arrayobject *self)
1673/*[clinic end generated code: output=7d6bd92745a2c8f3 input=b6c0ddee7b30457e]*/
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001674{
Victor Stinner9f0b51e2010-11-09 09:38:30 +00001675 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001676 "tostring() is deprecated. Use tobytes() instead.", 2) != 0)
1677 return NULL;
Brett Cannon1eb32c22014-10-10 16:26:45 -04001678 return array_array_tobytes_impl(self);
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001679}
1680
Brett Cannon1eb32c22014-10-10 16:26:45 -04001681/*[clinic input]
1682array.array.fromunicode
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001683
Larry Hastings38337d12015-05-07 23:30:09 -07001684 ustr: Py_UNICODE(zeroes=True)
Brett Cannon1eb32c22014-10-10 16:26:45 -04001685 /
1686
1687Extends this array with data from the unicode string ustr.
1688
1689The array must be a unicode type array; otherwise a ValueError is raised.
1690Use array.frombytes(ustr.encode(...)) to append Unicode data to an array of
1691some other type.
1692[clinic start generated code]*/
Martin v. Löwis99866332002-03-01 10:27:01 +00001693
Martin v. Löwis99866332002-03-01 10:27:01 +00001694static PyObject *
Larry Hastings89964c42015-04-14 18:07:59 -04001695array_array_fromunicode_impl(arrayobject *self, Py_UNICODE *ustr,
1696 Py_ssize_clean_t ustr_length)
Larry Hastings38337d12015-05-07 23:30:09 -07001697/*[clinic end generated code: output=ebb72fc16975e06d input=150f00566ffbca6e]*/
Martin v. Löwis99866332002-03-01 10:27:01 +00001698{
Victor Stinner62bb3942012-08-06 00:46:05 +02001699 char typecode;
Martin v. Löwis99866332002-03-01 10:27:01 +00001700
Victor Stinner62bb3942012-08-06 00:46:05 +02001701 typecode = self->ob_descr->typecode;
Gregory P. Smith9504b132012-12-10 20:20:20 -08001702 if (typecode != 'u') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001703 PyErr_SetString(PyExc_ValueError,
1704 "fromunicode() may only be called on "
1705 "unicode type arrays");
1706 return NULL;
1707 }
Brett Cannon1eb32c22014-10-10 16:26:45 -04001708 if (ustr_length > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001709 Py_ssize_t old_size = Py_SIZE(self);
Brett Cannon1eb32c22014-10-10 16:26:45 -04001710 if (array_resize(self, old_size + ustr_length) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001711 return NULL;
Victor Stinner62bb3942012-08-06 00:46:05 +02001712 memcpy(self->ob_item + old_size * sizeof(Py_UNICODE),
Brett Cannon1eb32c22014-10-10 16:26:45 -04001713 ustr, ustr_length * sizeof(Py_UNICODE));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001714 }
Martin v. Löwis99866332002-03-01 10:27:01 +00001715
Brett Cannon1eb32c22014-10-10 16:26:45 -04001716 Py_RETURN_NONE;
Martin v. Löwis99866332002-03-01 10:27:01 +00001717}
1718
Brett Cannon1eb32c22014-10-10 16:26:45 -04001719/*[clinic input]
1720array.array.tounicode
Martin v. Löwis99866332002-03-01 10:27:01 +00001721
Brett Cannon1eb32c22014-10-10 16:26:45 -04001722Extends this array with data from the unicode string ustr.
1723
1724Convert the array to a unicode string. The array must be a unicode type array;
1725otherwise a ValueError is raised. Use array.tobytes().decode() to obtain a
1726unicode string from an array of some other type.
1727[clinic start generated code]*/
Martin v. Löwis99866332002-03-01 10:27:01 +00001728
1729static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001730array_array_tounicode_impl(arrayobject *self)
1731/*[clinic end generated code: output=08e442378336e1ef input=127242eebe70b66d]*/
Martin v. Löwis99866332002-03-01 10:27:01 +00001732{
Victor Stinner62bb3942012-08-06 00:46:05 +02001733 char typecode;
1734 typecode = self->ob_descr->typecode;
Gregory P. Smith9504b132012-12-10 20:20:20 -08001735 if (typecode != 'u') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 PyErr_SetString(PyExc_ValueError,
1737 "tounicode() may only be called on unicode type arrays");
1738 return NULL;
1739 }
Victor Stinner62bb3942012-08-06 00:46:05 +02001740 return PyUnicode_FromUnicode((Py_UNICODE *) self->ob_item, Py_SIZE(self));
Martin v. Löwis99866332002-03-01 10:27:01 +00001741}
1742
Brett Cannon1eb32c22014-10-10 16:26:45 -04001743/*[clinic input]
1744array.array.__sizeof__
Martin v. Löwis99866332002-03-01 10:27:01 +00001745
Brett Cannon1eb32c22014-10-10 16:26:45 -04001746Size of the array in memory, in bytes.
1747[clinic start generated code]*/
Martin v. Löwis99866332002-03-01 10:27:01 +00001748
Meador Inge03b4d502012-08-10 22:35:45 -05001749static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001750array_array___sizeof___impl(arrayobject *self)
1751/*[clinic end generated code: output=d8e1c61ebbe3eaed input=805586565bf2b3c6]*/
Meador Inge03b4d502012-08-10 22:35:45 -05001752{
1753 Py_ssize_t res;
Serhiy Storchaka5c4064e2015-12-19 20:05:25 +02001754 res = _PyObject_SIZE(Py_TYPE(self)) + self->allocated * self->ob_descr->itemsize;
Meador Inge03b4d502012-08-10 22:35:45 -05001755 return PyLong_FromSsize_t(res);
1756}
1757
Martin v. Löwis99866332002-03-01 10:27:01 +00001758
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001759/*********************** Pickling support ************************/
1760
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001761static const struct mformatdescr {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001762 size_t size;
1763 int is_signed;
1764 int is_big_endian;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001765} mformat_descriptors[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001766 {1, 0, 0}, /* 0: UNSIGNED_INT8 */
1767 {1, 1, 0}, /* 1: SIGNED_INT8 */
1768 {2, 0, 0}, /* 2: UNSIGNED_INT16_LE */
1769 {2, 0, 1}, /* 3: UNSIGNED_INT16_BE */
1770 {2, 1, 0}, /* 4: SIGNED_INT16_LE */
1771 {2, 1, 1}, /* 5: SIGNED_INT16_BE */
1772 {4, 0, 0}, /* 6: UNSIGNED_INT32_LE */
1773 {4, 0, 1}, /* 7: UNSIGNED_INT32_BE */
1774 {4, 1, 0}, /* 8: SIGNED_INT32_LE */
1775 {4, 1, 1}, /* 9: SIGNED_INT32_BE */
1776 {8, 0, 0}, /* 10: UNSIGNED_INT64_LE */
1777 {8, 0, 1}, /* 11: UNSIGNED_INT64_BE */
1778 {8, 1, 0}, /* 12: SIGNED_INT64_LE */
1779 {8, 1, 1}, /* 13: SIGNED_INT64_BE */
1780 {4, 0, 0}, /* 14: IEEE_754_FLOAT_LE */
1781 {4, 0, 1}, /* 15: IEEE_754_FLOAT_BE */
1782 {8, 0, 0}, /* 16: IEEE_754_DOUBLE_LE */
1783 {8, 0, 1}, /* 17: IEEE_754_DOUBLE_BE */
1784 {4, 0, 0}, /* 18: UTF16_LE */
1785 {4, 0, 1}, /* 19: UTF16_BE */
1786 {8, 0, 0}, /* 20: UTF32_LE */
1787 {8, 0, 1} /* 21: UTF32_BE */
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001788};
1789
1790
1791/*
1792 * Internal: This function is used to find the machine format of a given
1793 * array type code. This returns UNKNOWN_FORMAT when the machine format cannot
1794 * be found.
1795 */
1796static enum machine_format_code
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02001797typecode_to_mformat_code(char typecode)
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001798{
Christian Heimes743e0cd2012-10-17 23:52:17 +02001799 const int is_big_endian = PY_BIG_ENDIAN;
1800
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001801 size_t intsize;
1802 int is_signed;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001803
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001804 switch (typecode) {
1805 case 'b':
1806 return SIGNED_INT8;
1807 case 'B':
1808 return UNSIGNED_INT8;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001809
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001810 case 'u':
Victor Stinner62bb3942012-08-06 00:46:05 +02001811 if (sizeof(Py_UNICODE) == 2) {
1812 return UTF16_LE + is_big_endian;
1813 }
1814 if (sizeof(Py_UNICODE) == 4) {
1815 return UTF32_LE + is_big_endian;
1816 }
1817 return UNKNOWN_FORMAT;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001819 case 'f':
1820 if (sizeof(float) == 4) {
1821 const float y = 16711938.0;
1822 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1823 return IEEE_754_FLOAT_BE;
1824 if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1825 return IEEE_754_FLOAT_LE;
1826 }
1827 return UNKNOWN_FORMAT;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001829 case 'd':
1830 if (sizeof(double) == 8) {
1831 const double x = 9006104071832581.0;
1832 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1833 return IEEE_754_DOUBLE_BE;
1834 if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1835 return IEEE_754_DOUBLE_LE;
1836 }
1837 return UNKNOWN_FORMAT;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001838
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001839 /* Integers */
1840 case 'h':
1841 intsize = sizeof(short);
1842 is_signed = 1;
1843 break;
1844 case 'H':
1845 intsize = sizeof(short);
1846 is_signed = 0;
1847 break;
1848 case 'i':
1849 intsize = sizeof(int);
1850 is_signed = 1;
1851 break;
1852 case 'I':
1853 intsize = sizeof(int);
1854 is_signed = 0;
1855 break;
1856 case 'l':
1857 intsize = sizeof(long);
1858 is_signed = 1;
1859 break;
1860 case 'L':
1861 intsize = sizeof(long);
1862 is_signed = 0;
1863 break;
Meador Inge1c9f0c92011-09-20 19:55:51 -05001864#if HAVE_LONG_LONG
1865 case 'q':
1866 intsize = sizeof(PY_LONG_LONG);
1867 is_signed = 1;
1868 break;
1869 case 'Q':
1870 intsize = sizeof(PY_LONG_LONG);
1871 is_signed = 0;
1872 break;
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02001873#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001874 default:
1875 return UNKNOWN_FORMAT;
1876 }
1877 switch (intsize) {
1878 case 2:
1879 return UNSIGNED_INT16_LE + is_big_endian + (2 * is_signed);
1880 case 4:
1881 return UNSIGNED_INT32_LE + is_big_endian + (2 * is_signed);
1882 case 8:
1883 return UNSIGNED_INT64_LE + is_big_endian + (2 * is_signed);
1884 default:
1885 return UNKNOWN_FORMAT;
1886 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001887}
1888
1889/* Forward declaration. */
1890static PyObject *array_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1891
1892/*
1893 * Internal: This function wraps the array constructor--i.e., array_new()--to
1894 * allow the creation of array objects from C code without having to deal
1895 * directly the tuple argument of array_new(). The typecode argument is a
1896 * Unicode character value, like 'i' or 'f' for example, representing an array
1897 * type code. The items argument is a bytes or a list object from which
1898 * contains the initial value of the array.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001899 *
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001900 * On success, this functions returns the array object created. Otherwise,
1901 * NULL is returned to indicate a failure.
1902 */
1903static PyObject *
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02001904make_array(PyTypeObject *arraytype, char typecode, PyObject *items)
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001905{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001906 PyObject *new_args;
1907 PyObject *array_obj;
1908 PyObject *typecode_obj;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001909
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001910 assert(arraytype != NULL);
1911 assert(items != NULL);
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001912
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02001913 typecode_obj = PyUnicode_FromOrdinal(typecode);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001914 if (typecode_obj == NULL)
1915 return NULL;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001916
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001917 new_args = PyTuple_New(2);
1918 if (new_args == NULL)
1919 return NULL;
1920 Py_INCREF(items);
1921 PyTuple_SET_ITEM(new_args, 0, typecode_obj);
1922 PyTuple_SET_ITEM(new_args, 1, items);
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001924 array_obj = array_new(arraytype, new_args, NULL);
1925 Py_DECREF(new_args);
1926 if (array_obj == NULL)
1927 return NULL;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001928
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001929 return array_obj;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001930}
1931
1932/*
1933 * This functions is a special constructor used when unpickling an array. It
1934 * provides a portable way to rebuild an array from its memory representation.
1935 */
Brett Cannon1eb32c22014-10-10 16:26:45 -04001936/*[clinic input]
1937array._array_reconstructor
1938
1939 arraytype: object(type="PyTypeObject *")
Larry Hastingsdbfdc382015-05-04 06:59:46 -07001940 typecode: int(accept={str})
Brett Cannon1eb32c22014-10-10 16:26:45 -04001941 mformat_code: int(type="enum machine_format_code")
1942 items: object
1943 /
1944
1945Internal. Used for pickling support.
1946[clinic start generated code]*/
1947
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001948static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001949array__array_reconstructor_impl(PyObject *module, PyTypeObject *arraytype,
Larry Hastings89964c42015-04-14 18:07:59 -04001950 int typecode,
1951 enum machine_format_code mformat_code,
1952 PyObject *items)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001953/*[clinic end generated code: output=e05263141ba28365 input=2464dc8f4c7736b5]*/
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001954{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001955 PyObject *converted_items;
1956 PyObject *result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001957 struct arraydescr *descr;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001958
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001959 if (!PyType_Check(arraytype)) {
1960 PyErr_Format(PyExc_TypeError,
1961 "first argument must a type object, not %.200s",
1962 Py_TYPE(arraytype)->tp_name);
1963 return NULL;
1964 }
1965 if (!PyType_IsSubtype(arraytype, &Arraytype)) {
1966 PyErr_Format(PyExc_TypeError,
1967 "%.200s is not a subtype of %.200s",
1968 arraytype->tp_name, Arraytype.tp_name);
1969 return NULL;
1970 }
1971 for (descr = descriptors; descr->typecode != '\0'; descr++) {
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02001972 if ((int)descr->typecode == typecode)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001973 break;
1974 }
1975 if (descr->typecode == '\0') {
1976 PyErr_SetString(PyExc_ValueError,
1977 "second argument must be a valid type code");
1978 return NULL;
1979 }
Larry Hastingsdfbeb162014-10-13 10:39:41 +01001980 if (mformat_code < MACHINE_FORMAT_CODE_MIN ||
1981 mformat_code > MACHINE_FORMAT_CODE_MAX) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001982 PyErr_SetString(PyExc_ValueError,
1983 "third argument must be a valid machine format code.");
1984 return NULL;
1985 }
1986 if (!PyBytes_Check(items)) {
1987 PyErr_Format(PyExc_TypeError,
1988 "fourth argument should be bytes, not %.200s",
1989 Py_TYPE(items)->tp_name);
1990 return NULL;
1991 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001993 /* Fast path: No decoding has to be done. */
Larry Hastingsdfbeb162014-10-13 10:39:41 +01001994 if (mformat_code == typecode_to_mformat_code((char)typecode) ||
1995 mformat_code == UNKNOWN_FORMAT) {
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02001996 return make_array(arraytype, (char)typecode, items);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001997 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001999 /* Slow path: Decode the byte string according to the given machine
2000 * format code. This occurs when the computer unpickling the array
2001 * object is architecturally different from the one that pickled the
2002 * array.
2003 */
Larry Hastingsdfbeb162014-10-13 10:39:41 +01002004 if (Py_SIZE(items) % mformat_descriptors[mformat_code].size != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002005 PyErr_SetString(PyExc_ValueError,
2006 "string length not a multiple of item size");
2007 return NULL;
2008 }
Larry Hastingsdfbeb162014-10-13 10:39:41 +01002009 switch (mformat_code) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002010 case IEEE_754_FLOAT_LE:
2011 case IEEE_754_FLOAT_BE: {
2012 int i;
Larry Hastingsdfbeb162014-10-13 10:39:41 +01002013 int le = (mformat_code == IEEE_754_FLOAT_LE) ? 1 : 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002014 Py_ssize_t itemcount = Py_SIZE(items) / 4;
2015 const unsigned char *memstr =
2016 (unsigned char *)PyBytes_AS_STRING(items);
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002018 converted_items = PyList_New(itemcount);
2019 if (converted_items == NULL)
2020 return NULL;
2021 for (i = 0; i < itemcount; i++) {
2022 PyObject *pyfloat = PyFloat_FromDouble(
2023 _PyFloat_Unpack4(&memstr[i * 4], le));
2024 if (pyfloat == NULL) {
2025 Py_DECREF(converted_items);
2026 return NULL;
2027 }
2028 PyList_SET_ITEM(converted_items, i, pyfloat);
2029 }
2030 break;
2031 }
2032 case IEEE_754_DOUBLE_LE:
2033 case IEEE_754_DOUBLE_BE: {
2034 int i;
Larry Hastingsdfbeb162014-10-13 10:39:41 +01002035 int le = (mformat_code == IEEE_754_DOUBLE_LE) ? 1 : 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002036 Py_ssize_t itemcount = Py_SIZE(items) / 8;
2037 const unsigned char *memstr =
2038 (unsigned char *)PyBytes_AS_STRING(items);
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002040 converted_items = PyList_New(itemcount);
2041 if (converted_items == NULL)
2042 return NULL;
2043 for (i = 0; i < itemcount; i++) {
2044 PyObject *pyfloat = PyFloat_FromDouble(
2045 _PyFloat_Unpack8(&memstr[i * 8], le));
2046 if (pyfloat == NULL) {
2047 Py_DECREF(converted_items);
2048 return NULL;
2049 }
2050 PyList_SET_ITEM(converted_items, i, pyfloat);
2051 }
2052 break;
2053 }
2054 case UTF16_LE:
2055 case UTF16_BE: {
Larry Hastingsdfbeb162014-10-13 10:39:41 +01002056 int byteorder = (mformat_code == UTF16_LE) ? -1 : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002057 converted_items = PyUnicode_DecodeUTF16(
2058 PyBytes_AS_STRING(items), Py_SIZE(items),
2059 "strict", &byteorder);
2060 if (converted_items == NULL)
2061 return NULL;
2062 break;
2063 }
2064 case UTF32_LE:
2065 case UTF32_BE: {
Larry Hastingsdfbeb162014-10-13 10:39:41 +01002066 int byteorder = (mformat_code == UTF32_LE) ? -1 : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002067 converted_items = PyUnicode_DecodeUTF32(
2068 PyBytes_AS_STRING(items), Py_SIZE(items),
2069 "strict", &byteorder);
2070 if (converted_items == NULL)
2071 return NULL;
2072 break;
2073 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002074
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002075 case UNSIGNED_INT8:
2076 case SIGNED_INT8:
2077 case UNSIGNED_INT16_LE:
2078 case UNSIGNED_INT16_BE:
2079 case SIGNED_INT16_LE:
2080 case SIGNED_INT16_BE:
2081 case UNSIGNED_INT32_LE:
2082 case UNSIGNED_INT32_BE:
2083 case SIGNED_INT32_LE:
2084 case SIGNED_INT32_BE:
2085 case UNSIGNED_INT64_LE:
2086 case UNSIGNED_INT64_BE:
2087 case SIGNED_INT64_LE:
2088 case SIGNED_INT64_BE: {
2089 int i;
2090 const struct mformatdescr mf_descr =
Larry Hastingsdfbeb162014-10-13 10:39:41 +01002091 mformat_descriptors[mformat_code];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002092 Py_ssize_t itemcount = Py_SIZE(items) / mf_descr.size;
2093 const unsigned char *memstr =
2094 (unsigned char *)PyBytes_AS_STRING(items);
2095 struct arraydescr *descr;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002096
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002097 /* If possible, try to pack array's items using a data type
2098 * that fits better. This may result in an array with narrower
2099 * or wider elements.
2100 *
Martin Panter4c359642016-05-08 13:53:41 +00002101 * For example, if a 32-bit machine pickles an L-code array of
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002102 * unsigned longs, then the array will be unpickled by 64-bit
2103 * machine as an I-code array of unsigned ints.
2104 *
2105 * XXX: Is it possible to write a unit test for this?
2106 */
2107 for (descr = descriptors; descr->typecode != '\0'; descr++) {
2108 if (descr->is_integer_type &&
Victor Stinner706768c2014-08-16 01:03:39 +02002109 (size_t)descr->itemsize == mf_descr.size &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002110 descr->is_signed == mf_descr.is_signed)
2111 typecode = descr->typecode;
2112 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002113
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002114 converted_items = PyList_New(itemcount);
2115 if (converted_items == NULL)
2116 return NULL;
2117 for (i = 0; i < itemcount; i++) {
2118 PyObject *pylong;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002120 pylong = _PyLong_FromByteArray(
2121 &memstr[i * mf_descr.size],
2122 mf_descr.size,
2123 !mf_descr.is_big_endian,
2124 mf_descr.is_signed);
2125 if (pylong == NULL) {
2126 Py_DECREF(converted_items);
2127 return NULL;
2128 }
2129 PyList_SET_ITEM(converted_items, i, pylong);
2130 }
2131 break;
2132 }
2133 case UNKNOWN_FORMAT:
2134 /* Impossible, but needed to shut up GCC about the unhandled
2135 * enumeration value.
2136 */
2137 default:
2138 PyErr_BadArgument();
2139 return NULL;
2140 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002141
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02002142 result = make_array(arraytype, (char)typecode, converted_items);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002143 Py_DECREF(converted_items);
2144 return result;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002145}
2146
Brett Cannon1eb32c22014-10-10 16:26:45 -04002147/*[clinic input]
2148array.array.__reduce_ex__
2149
2150 value: object
2151 /
2152
2153Return state information for pickling.
2154[clinic start generated code]*/
2155
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002156static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04002157array_array___reduce_ex__(arrayobject *self, PyObject *value)
2158/*[clinic end generated code: output=051e0a6175d0eddb input=c36c3f85de7df6cd]*/
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002159{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002160 PyObject *dict;
2161 PyObject *result;
2162 PyObject *array_str;
Brett Cannon1eb32c22014-10-10 16:26:45 -04002163 int typecode = self->ob_descr->typecode;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002164 int mformat_code;
2165 static PyObject *array_reconstructor = NULL;
2166 long protocol;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002167 _Py_IDENTIFIER(_array_reconstructor);
2168 _Py_IDENTIFIER(__dict__);
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002169
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002170 if (array_reconstructor == NULL) {
2171 PyObject *array_module = PyImport_ImportModule("array");
2172 if (array_module == NULL)
2173 return NULL;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002174 array_reconstructor = _PyObject_GetAttrId(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002175 array_module,
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002176 &PyId__array_reconstructor);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002177 Py_DECREF(array_module);
2178 if (array_reconstructor == NULL)
2179 return NULL;
2180 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002182 if (!PyLong_Check(value)) {
2183 PyErr_SetString(PyExc_TypeError,
2184 "__reduce_ex__ argument should an integer");
2185 return NULL;
2186 }
2187 protocol = PyLong_AsLong(value);
2188 if (protocol == -1 && PyErr_Occurred())
2189 return NULL;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002190
Brett Cannon1eb32c22014-10-10 16:26:45 -04002191 dict = _PyObject_GetAttrId((PyObject *)self, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002192 if (dict == NULL) {
2193 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
2194 return NULL;
2195 PyErr_Clear();
2196 dict = Py_None;
2197 Py_INCREF(dict);
2198 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002200 mformat_code = typecode_to_mformat_code(typecode);
2201 if (mformat_code == UNKNOWN_FORMAT || protocol < 3) {
2202 /* Convert the array to a list if we got something weird
2203 * (e.g., non-IEEE floats), or we are pickling the array using
2204 * a Python 2.x compatible protocol.
2205 *
2206 * It is necessary to use a list representation for Python 2.x
2207 * compatible pickle protocol, since Python 2's str objects
2208 * are unpickled as unicode by Python 3. Thus it is impossible
2209 * to make arrays unpicklable by Python 3 by using their memory
2210 * representation, unless we resort to ugly hacks such as
2211 * coercing unicode objects to bytes in array_reconstructor.
2212 */
2213 PyObject *list;
Brett Cannon1eb32c22014-10-10 16:26:45 -04002214 list = array_array_tolist_impl(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002215 if (list == NULL) {
2216 Py_DECREF(dict);
2217 return NULL;
2218 }
2219 result = Py_BuildValue(
Brett Cannon1eb32c22014-10-10 16:26:45 -04002220 "O(CO)O", Py_TYPE(self), typecode, list, dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002221 Py_DECREF(list);
2222 Py_DECREF(dict);
2223 return result;
2224 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002225
Brett Cannon1eb32c22014-10-10 16:26:45 -04002226 array_str = array_array_tobytes_impl(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002227 if (array_str == NULL) {
2228 Py_DECREF(dict);
2229 return NULL;
2230 }
2231 result = Py_BuildValue(
Brett Cannon1eb32c22014-10-10 16:26:45 -04002232 "O(OCiN)O", array_reconstructor, Py_TYPE(self), typecode,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002233 mformat_code, array_str, dict);
2234 Py_DECREF(dict);
2235 return result;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002236}
2237
Martin v. Löwis99866332002-03-01 10:27:01 +00002238static PyObject *
2239array_get_typecode(arrayobject *a, void *closure)
2240{
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02002241 char typecode = a->ob_descr->typecode;
2242 return PyUnicode_FromOrdinal(typecode);
Martin v. Löwis99866332002-03-01 10:27:01 +00002243}
2244
2245static PyObject *
2246array_get_itemsize(arrayobject *a, void *closure)
2247{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002248 return PyLong_FromLong((long)a->ob_descr->itemsize);
Martin v. Löwis99866332002-03-01 10:27:01 +00002249}
2250
2251static PyGetSetDef array_getsets [] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002252 {"typecode", (getter) array_get_typecode, NULL,
2253 "the typecode character used to create the array"},
2254 {"itemsize", (getter) array_get_itemsize, NULL,
2255 "the size, in bytes, of one array item"},
2256 {NULL}
Martin v. Löwis99866332002-03-01 10:27:01 +00002257};
2258
Martin v. Löwis59683e82008-06-13 07:50:45 +00002259static PyMethodDef array_methods[] = {
Brett Cannon1eb32c22014-10-10 16:26:45 -04002260 ARRAY_ARRAY_APPEND_METHODDEF
2261 ARRAY_ARRAY_BUFFER_INFO_METHODDEF
2262 ARRAY_ARRAY_BYTESWAP_METHODDEF
2263 ARRAY_ARRAY___COPY___METHODDEF
2264 ARRAY_ARRAY_COUNT_METHODDEF
2265 ARRAY_ARRAY___DEEPCOPY___METHODDEF
2266 ARRAY_ARRAY_EXTEND_METHODDEF
2267 ARRAY_ARRAY_FROMFILE_METHODDEF
2268 ARRAY_ARRAY_FROMLIST_METHODDEF
2269 ARRAY_ARRAY_FROMSTRING_METHODDEF
2270 ARRAY_ARRAY_FROMBYTES_METHODDEF
2271 ARRAY_ARRAY_FROMUNICODE_METHODDEF
2272 ARRAY_ARRAY_INDEX_METHODDEF
2273 ARRAY_ARRAY_INSERT_METHODDEF
2274 ARRAY_ARRAY_POP_METHODDEF
2275 ARRAY_ARRAY___REDUCE_EX___METHODDEF
2276 ARRAY_ARRAY_REMOVE_METHODDEF
2277 ARRAY_ARRAY_REVERSE_METHODDEF
2278 ARRAY_ARRAY_TOFILE_METHODDEF
2279 ARRAY_ARRAY_TOLIST_METHODDEF
2280 ARRAY_ARRAY_TOSTRING_METHODDEF
2281 ARRAY_ARRAY_TOBYTES_METHODDEF
2282 ARRAY_ARRAY_TOUNICODE_METHODDEF
2283 ARRAY_ARRAY___SIZEOF___METHODDEF
2284 {NULL, NULL} /* sentinel */
Guido van Rossum778983b1993-02-19 15:55:02 +00002285};
2286
Roger E. Masse2919eaa1996-12-09 20:10:36 +00002287static PyObject *
Peter Schneider-Kamp9656abd2000-07-13 21:10:57 +00002288array_repr(arrayobject *a)
Guido van Rossum778983b1993-02-19 15:55:02 +00002289{
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02002290 char typecode;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002291 PyObject *s, *v = NULL;
2292 Py_ssize_t len;
Martin v. Löwis99866332002-03-01 10:27:01 +00002293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002294 len = Py_SIZE(a);
2295 typecode = a->ob_descr->typecode;
2296 if (len == 0) {
Amaury Forgeot d'Arc24aa26b2010-11-25 08:13:35 +00002297 return PyUnicode_FromFormat("array('%c')", (int)typecode);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002298 }
Gregory P. Smith9504b132012-12-10 20:20:20 -08002299 if (typecode == 'u') {
Brett Cannon1eb32c22014-10-10 16:26:45 -04002300 v = array_array_tounicode_impl(a);
Gregory P. Smith9504b132012-12-10 20:20:20 -08002301 } else {
Brett Cannon1eb32c22014-10-10 16:26:45 -04002302 v = array_array_tolist_impl(a);
Gregory P. Smith9504b132012-12-10 20:20:20 -08002303 }
Victor Stinner29ec5952013-02-26 00:27:38 +01002304 if (v == NULL)
2305 return NULL;
Raymond Hettinger88ba1e32003-04-23 17:27:00 +00002306
Amaury Forgeot d'Arc24aa26b2010-11-25 08:13:35 +00002307 s = PyUnicode_FromFormat("array('%c', %R)", (int)typecode, v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002308 Py_DECREF(v);
2309 return s;
Guido van Rossum778983b1993-02-19 15:55:02 +00002310}
2311
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002312static PyObject*
2313array_subscr(arrayobject* self, PyObject* item)
2314{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002315 if (PyIndex_Check(item)) {
2316 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
2317 if (i==-1 && PyErr_Occurred()) {
2318 return NULL;
2319 }
2320 if (i < 0)
2321 i += Py_SIZE(self);
2322 return array_item(self, i);
2323 }
2324 else if (PySlice_Check(item)) {
2325 Py_ssize_t start, stop, step, slicelength, cur, i;
2326 PyObject* result;
2327 arrayobject* ar;
2328 int itemsize = self->ob_descr->itemsize;
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002329
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002330 if (PySlice_GetIndicesEx(item, Py_SIZE(self),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002331 &start, &stop, &step, &slicelength) < 0) {
2332 return NULL;
2333 }
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002335 if (slicelength <= 0) {
2336 return newarrayobject(&Arraytype, 0, self->ob_descr);
2337 }
2338 else if (step == 1) {
2339 PyObject *result = newarrayobject(&Arraytype,
2340 slicelength, self->ob_descr);
2341 if (result == NULL)
2342 return NULL;
2343 memcpy(((arrayobject *)result)->ob_item,
2344 self->ob_item + start * itemsize,
2345 slicelength * itemsize);
2346 return result;
2347 }
2348 else {
2349 result = newarrayobject(&Arraytype, slicelength, self->ob_descr);
2350 if (!result) return NULL;
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002352 ar = (arrayobject*)result;
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002353
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002354 for (cur = start, i = 0; i < slicelength;
2355 cur += step, i++) {
2356 memcpy(ar->ob_item + i*itemsize,
2357 self->ob_item + cur*itemsize,
2358 itemsize);
2359 }
2360
2361 return result;
2362 }
2363 }
2364 else {
2365 PyErr_SetString(PyExc_TypeError,
2366 "array indices must be integers");
2367 return NULL;
2368 }
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002369}
2370
2371static int
2372array_ass_subscr(arrayobject* self, PyObject* item, PyObject* value)
2373{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002374 Py_ssize_t start, stop, step, slicelength, needed;
2375 arrayobject* other;
2376 int itemsize;
Thomas Woutersed03b412007-08-28 21:37:11 +00002377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002378 if (PyIndex_Check(item)) {
2379 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Alexandre Vassalotti47137252009-07-05 19:57:00 +00002380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002381 if (i == -1 && PyErr_Occurred())
2382 return -1;
2383 if (i < 0)
2384 i += Py_SIZE(self);
2385 if (i < 0 || i >= Py_SIZE(self)) {
2386 PyErr_SetString(PyExc_IndexError,
2387 "array assignment index out of range");
2388 return -1;
2389 }
2390 if (value == NULL) {
2391 /* Fall through to slice assignment */
2392 start = i;
2393 stop = i + 1;
2394 step = 1;
2395 slicelength = 1;
2396 }
2397 else
2398 return (*self->ob_descr->setitem)(self, i, value);
2399 }
2400 else if (PySlice_Check(item)) {
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002401 if (PySlice_GetIndicesEx(item,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002402 Py_SIZE(self), &start, &stop,
2403 &step, &slicelength) < 0) {
2404 return -1;
2405 }
2406 }
2407 else {
2408 PyErr_SetString(PyExc_TypeError,
2409 "array indices must be integer");
2410 return -1;
2411 }
2412 if (value == NULL) {
2413 other = NULL;
2414 needed = 0;
2415 }
2416 else if (array_Check(value)) {
2417 other = (arrayobject *)value;
2418 needed = Py_SIZE(other);
2419 if (self == other) {
2420 /* Special case "self[i:j] = self" -- copy self first */
2421 int ret;
2422 value = array_slice(other, 0, needed);
2423 if (value == NULL)
2424 return -1;
2425 ret = array_ass_subscr(self, item, value);
2426 Py_DECREF(value);
2427 return ret;
2428 }
2429 if (other->ob_descr != self->ob_descr) {
2430 PyErr_BadArgument();
2431 return -1;
2432 }
2433 }
2434 else {
2435 PyErr_Format(PyExc_TypeError,
2436 "can only assign array (not \"%.200s\") to array slice",
2437 Py_TYPE(value)->tp_name);
2438 return -1;
2439 }
2440 itemsize = self->ob_descr->itemsize;
2441 /* for 'a[2:1] = ...', the insertion point is 'start', not 'stop' */
2442 if ((step > 0 && stop < start) ||
2443 (step < 0 && stop > start))
2444 stop = start;
Alexandre Vassalotti47137252009-07-05 19:57:00 +00002445
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002446 /* Issue #4509: If the array has exported buffers and the slice
2447 assignment would change the size of the array, fail early to make
2448 sure we don't modify it. */
2449 if ((needed == 0 || slicelength != needed) && self->ob_exports > 0) {
2450 PyErr_SetString(PyExc_BufferError,
2451 "cannot resize an array that is exporting buffers");
2452 return -1;
2453 }
Mark Dickinsonbc099642010-01-29 17:27:24 +00002454
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002455 if (step == 1) {
2456 if (slicelength > needed) {
2457 memmove(self->ob_item + (start + needed) * itemsize,
2458 self->ob_item + stop * itemsize,
2459 (Py_SIZE(self) - stop) * itemsize);
2460 if (array_resize(self, Py_SIZE(self) +
2461 needed - slicelength) < 0)
2462 return -1;
2463 }
2464 else if (slicelength < needed) {
2465 if (array_resize(self, Py_SIZE(self) +
2466 needed - slicelength) < 0)
2467 return -1;
2468 memmove(self->ob_item + (start + needed) * itemsize,
2469 self->ob_item + stop * itemsize,
2470 (Py_SIZE(self) - start - needed) * itemsize);
2471 }
2472 if (needed > 0)
2473 memcpy(self->ob_item + start * itemsize,
2474 other->ob_item, needed * itemsize);
2475 return 0;
2476 }
2477 else if (needed == 0) {
2478 /* Delete slice */
2479 size_t cur;
2480 Py_ssize_t i;
Thomas Woutersed03b412007-08-28 21:37:11 +00002481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002482 if (step < 0) {
2483 stop = start + 1;
2484 start = stop + step * (slicelength - 1) - 1;
2485 step = -step;
2486 }
2487 for (cur = start, i = 0; i < slicelength;
2488 cur += step, i++) {
2489 Py_ssize_t lim = step - 1;
Thomas Woutersed03b412007-08-28 21:37:11 +00002490
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002491 if (cur + step >= (size_t)Py_SIZE(self))
2492 lim = Py_SIZE(self) - cur - 1;
2493 memmove(self->ob_item + (cur - i) * itemsize,
2494 self->ob_item + (cur + 1) * itemsize,
2495 lim * itemsize);
2496 }
Mark Dickinsonc7d93b72011-09-25 15:34:32 +01002497 cur = start + (size_t)slicelength * step;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002498 if (cur < (size_t)Py_SIZE(self)) {
2499 memmove(self->ob_item + (cur-slicelength) * itemsize,
2500 self->ob_item + cur * itemsize,
2501 (Py_SIZE(self) - cur) * itemsize);
2502 }
2503 if (array_resize(self, Py_SIZE(self) - slicelength) < 0)
2504 return -1;
2505 return 0;
2506 }
2507 else {
2508 Py_ssize_t cur, i;
2509
2510 if (needed != slicelength) {
2511 PyErr_Format(PyExc_ValueError,
2512 "attempt to assign array of size %zd "
2513 "to extended slice of size %zd",
2514 needed, slicelength);
2515 return -1;
2516 }
2517 for (cur = start, i = 0; i < slicelength;
2518 cur += step, i++) {
2519 memcpy(self->ob_item + cur * itemsize,
2520 other->ob_item + i * itemsize,
2521 itemsize);
2522 }
2523 return 0;
2524 }
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002525}
2526
2527static PyMappingMethods array_as_mapping = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002528 (lenfunc)array_length,
2529 (binaryfunc)array_subscr,
2530 (objobjargproc)array_ass_subscr
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002531};
2532
Guido van Rossumd8faa362007-04-27 19:54:29 +00002533static const void *emptybuf = "";
2534
Travis E. Oliphantb99f7622007-08-18 11:21:56 +00002535
2536static int
Travis E. Oliphant8ae62b62007-09-23 02:00:13 +00002537array_buffer_getbuf(arrayobject *self, Py_buffer *view, int flags)
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00002538{
Stefan Krah650c1e82015-02-03 21:43:23 +01002539 if (view == NULL) {
2540 PyErr_SetString(PyExc_BufferError,
2541 "array_buffer_getbuf: view==NULL argument is obsolete");
2542 return -1;
2543 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +00002544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002545 view->buf = (void *)self->ob_item;
2546 view->obj = (PyObject*)self;
2547 Py_INCREF(self);
2548 if (view->buf == NULL)
2549 view->buf = (void *)emptybuf;
2550 view->len = (Py_SIZE(self)) * self->ob_descr->itemsize;
2551 view->readonly = 0;
2552 view->ndim = 1;
2553 view->itemsize = self->ob_descr->itemsize;
2554 view->suboffsets = NULL;
2555 view->shape = NULL;
2556 if ((flags & PyBUF_ND)==PyBUF_ND) {
2557 view->shape = &((Py_SIZE(self)));
2558 }
2559 view->strides = NULL;
2560 if ((flags & PyBUF_STRIDES)==PyBUF_STRIDES)
2561 view->strides = &(view->itemsize);
2562 view->format = NULL;
2563 view->internal = NULL;
Victor Stinner62bb3942012-08-06 00:46:05 +02002564 if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002565 view->format = self->ob_descr->formats;
Victor Stinner62bb3942012-08-06 00:46:05 +02002566#ifdef Py_UNICODE_WIDE
2567 if (self->ob_descr->typecode == 'u') {
2568 view->format = "w";
2569 }
2570#endif
2571 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +00002572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002573 self->ob_exports++;
2574 return 0;
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00002575}
2576
Travis E. Oliphantb99f7622007-08-18 11:21:56 +00002577static void
Travis E. Oliphant8ae62b62007-09-23 02:00:13 +00002578array_buffer_relbuf(arrayobject *self, Py_buffer *view)
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00002579{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002580 self->ob_exports--;
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00002581}
2582
Roger E. Masse2919eaa1996-12-09 20:10:36 +00002583static PySequenceMethods array_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002584 (lenfunc)array_length, /*sq_length*/
2585 (binaryfunc)array_concat, /*sq_concat*/
2586 (ssizeargfunc)array_repeat, /*sq_repeat*/
2587 (ssizeargfunc)array_item, /*sq_item*/
2588 0, /*sq_slice*/
2589 (ssizeobjargproc)array_ass_item, /*sq_ass_item*/
2590 0, /*sq_ass_slice*/
2591 (objobjproc)array_contains, /*sq_contains*/
2592 (binaryfunc)array_inplace_concat, /*sq_inplace_concat*/
2593 (ssizeargfunc)array_inplace_repeat /*sq_inplace_repeat*/
Guido van Rossum778983b1993-02-19 15:55:02 +00002594};
2595
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00002596static PyBufferProcs array_as_buffer = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002597 (getbufferproc)array_buffer_getbuf,
2598 (releasebufferproc)array_buffer_relbuf
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00002599};
2600
Roger E. Masse2919eaa1996-12-09 20:10:36 +00002601static PyObject *
Martin v. Löwis99866332002-03-01 10:27:01 +00002602array_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum778983b1993-02-19 15:55:02 +00002603{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002604 int c;
2605 PyObject *initial = NULL, *it = NULL;
2606 struct arraydescr *descr;
Martin v. Löwis99866332002-03-01 10:27:01 +00002607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002608 if (type == &Arraytype && !_PyArg_NoKeywords("array.array()", kwds))
2609 return NULL;
Martin v. Löwis99866332002-03-01 10:27:01 +00002610
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002611 if (!PyArg_ParseTuple(args, "C|O:array", &c, &initial))
2612 return NULL;
Raymond Hettinger84fc9aa2003-04-24 10:41:55 +00002613
Alexandre Vassalotti9730e332013-11-29 20:47:15 -08002614 if (initial && c != 'u') {
2615 if (PyUnicode_Check(initial)) {
2616 PyErr_Format(PyExc_TypeError, "cannot use a str to initialize "
2617 "an array with typecode '%c'", c);
2618 return NULL;
2619 }
2620 else if (array_Check(initial) &&
2621 ((arrayobject*)initial)->ob_descr->typecode == 'u') {
2622 PyErr_Format(PyExc_TypeError, "cannot use a unicode array to "
2623 "initialize an array with typecode '%c'", c);
2624 return NULL;
2625 }
2626 }
2627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002628 if (!(initial == NULL || PyList_Check(initial)
2629 || PyByteArray_Check(initial)
2630 || PyBytes_Check(initial)
2631 || PyTuple_Check(initial)
Alexander Belopolskyef4a03f2011-01-11 21:44:00 +00002632 || ((c=='u') && PyUnicode_Check(initial))
2633 || (array_Check(initial)
2634 && c == ((arrayobject*)initial)->ob_descr->typecode))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002635 it = PyObject_GetIter(initial);
2636 if (it == NULL)
2637 return NULL;
2638 /* We set initial to NULL so that the subsequent code
2639 will create an empty array of the appropriate type
2640 and afterwards we can use array_iter_extend to populate
2641 the array.
2642 */
2643 initial = NULL;
2644 }
2645 for (descr = descriptors; descr->typecode != '\0'; descr++) {
2646 if (descr->typecode == c) {
2647 PyObject *a;
2648 Py_ssize_t len;
Martin v. Löwis99866332002-03-01 10:27:01 +00002649
Alexander Belopolskyef4a03f2011-01-11 21:44:00 +00002650 if (initial == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002651 len = 0;
Alexander Belopolskyef4a03f2011-01-11 21:44:00 +00002652 else if (PyList_Check(initial))
2653 len = PyList_GET_SIZE(initial);
2654 else if (PyTuple_Check(initial) || array_Check(initial))
2655 len = Py_SIZE(initial);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002656 else
Alexander Belopolskyef4a03f2011-01-11 21:44:00 +00002657 len = 0;
Martin v. Löwis99866332002-03-01 10:27:01 +00002658
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002659 a = newarrayobject(type, len, descr);
2660 if (a == NULL)
2661 return NULL;
2662
Alexander Belopolskyef4a03f2011-01-11 21:44:00 +00002663 if (len > 0 && !array_Check(initial)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002664 Py_ssize_t i;
2665 for (i = 0; i < len; i++) {
2666 PyObject *v =
2667 PySequence_GetItem(initial, i);
2668 if (v == NULL) {
2669 Py_DECREF(a);
2670 return NULL;
2671 }
2672 if (setarrayitem(a, i, v) != 0) {
2673 Py_DECREF(v);
2674 Py_DECREF(a);
2675 return NULL;
2676 }
2677 Py_DECREF(v);
2678 }
2679 }
2680 else if (initial != NULL && (PyByteArray_Check(initial) ||
2681 PyBytes_Check(initial))) {
Serhiy Storchaka04e6dba2015-04-04 17:06:55 +03002682 PyObject *v;
Brett Cannon1eb32c22014-10-10 16:26:45 -04002683 v = array_array_frombytes((arrayobject *)a,
Serhiy Storchaka04e6dba2015-04-04 17:06:55 +03002684 initial);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002685 if (v == NULL) {
2686 Py_DECREF(a);
2687 return NULL;
2688 }
2689 Py_DECREF(v);
2690 }
2691 else if (initial != NULL && PyUnicode_Check(initial)) {
Victor Stinner62bb3942012-08-06 00:46:05 +02002692 Py_UNICODE *ustr;
Victor Stinner1fbcaef2011-09-30 01:54:04 +02002693 Py_ssize_t n;
Victor Stinner62bb3942012-08-06 00:46:05 +02002694
2695 ustr = PyUnicode_AsUnicode(initial);
2696 if (ustr == NULL) {
2697 PyErr_NoMemory();
Victor Stinner1fbcaef2011-09-30 01:54:04 +02002698 Py_DECREF(a);
2699 return NULL;
2700 }
Victor Stinner62bb3942012-08-06 00:46:05 +02002701
2702 n = PyUnicode_GET_DATA_SIZE(initial);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002703 if (n > 0) {
2704 arrayobject *self = (arrayobject *)a;
Victor Stinner62bb3942012-08-06 00:46:05 +02002705 char *item = self->ob_item;
2706 item = (char *)PyMem_Realloc(item, n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002707 if (item == NULL) {
2708 PyErr_NoMemory();
2709 Py_DECREF(a);
2710 return NULL;
2711 }
Victor Stinner62bb3942012-08-06 00:46:05 +02002712 self->ob_item = item;
2713 Py_SIZE(self) = n / sizeof(Py_UNICODE);
2714 memcpy(item, ustr, n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002715 self->allocated = Py_SIZE(self);
2716 }
2717 }
Benjamin Peterson682124c2014-10-10 20:58:30 -04002718 else if (initial != NULL && array_Check(initial) && len > 0) {
Alexander Belopolskyef4a03f2011-01-11 21:44:00 +00002719 arrayobject *self = (arrayobject *)a;
2720 arrayobject *other = (arrayobject *)initial;
2721 memcpy(self->ob_item, other->ob_item, len * other->ob_descr->itemsize);
2722 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002723 if (it != NULL) {
2724 if (array_iter_extend((arrayobject *)a, it) == -1) {
2725 Py_DECREF(it);
2726 Py_DECREF(a);
2727 return NULL;
2728 }
2729 Py_DECREF(it);
2730 }
2731 return a;
2732 }
2733 }
2734 PyErr_SetString(PyExc_ValueError,
Meador Inge1c9f0c92011-09-20 19:55:51 -05002735#ifdef HAVE_LONG_LONG
2736 "bad typecode (must be b, B, u, h, H, i, I, l, L, q, Q, f or d)");
2737#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002738 "bad typecode (must be b, B, u, h, H, i, I, l, L, f or d)");
Meador Inge1c9f0c92011-09-20 19:55:51 -05002739#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002740 return NULL;
Guido van Rossum778983b1993-02-19 15:55:02 +00002741}
2742
Guido van Rossum778983b1993-02-19 15:55:02 +00002743
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002744PyDoc_STRVAR(module_doc,
Martin v. Löwis99866332002-03-01 10:27:01 +00002745"This module defines an object type which can efficiently represent\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002746an array of basic values: characters, integers, floating point\n\
2747numbers. Arrays are sequence types and behave very much like lists,\n\
Alexandre Vassalotti9730e332013-11-29 20:47:15 -08002748except that the type of objects stored in them is constrained.\n");
2749
2750PyDoc_STRVAR(arraytype_doc,
2751"array(typecode [, initializer]) -> array\n\
2752\n\
2753Return a new array whose items are restricted by typecode, and\n\
2754initialized from the optional initializer value, which must be a list,\n\
2755string or iterable over elements of the appropriate type.\n\
2756\n\
2757Arrays represent basic values and behave very much like lists, except\n\
2758the type of objects stored in them is constrained. The type is specified\n\
2759at object creation time by using a type code, which is a single character.\n\
2760The following type codes are defined:\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002761\n\
2762 Type code C Type Minimum size in bytes \n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002763 'b' signed integer 1 \n\
2764 'B' unsigned integer 1 \n\
Victor Stinner62bb3942012-08-06 00:46:05 +02002765 'u' Unicode character 2 (see note) \n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002766 'h' signed integer 2 \n\
2767 'H' unsigned integer 2 \n\
2768 'i' signed integer 2 \n\
2769 'I' unsigned integer 2 \n\
2770 'l' signed integer 4 \n\
2771 'L' unsigned integer 4 \n\
Meador Inge1c9f0c92011-09-20 19:55:51 -05002772 'q' signed integer 8 (see note) \n\
2773 'Q' unsigned integer 8 (see note) \n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002774 'f' floating point 4 \n\
2775 'd' floating point 8 \n\
2776\n\
Victor Stinner62bb3942012-08-06 00:46:05 +02002777NOTE: The 'u' typecode corresponds to Python's unicode character. On \n\
2778narrow builds this is 2-bytes on wide builds this is 4-bytes.\n\
2779\n\
Meador Inge1c9f0c92011-09-20 19:55:51 -05002780NOTE: The 'q' and 'Q' type codes are only available if the platform \n\
2781C compiler used to build Python supports 'long long', or, on Windows, \n\
2782'__int64'.\n\
2783\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002784Methods:\n\
2785\n\
2786append() -- append a new item to the end of the array\n\
2787buffer_info() -- return information giving the current memory info\n\
2788byteswap() -- byteswap all the items of the array\n\
Mark Dickinson934896d2009-02-21 20:59:32 +00002789count() -- return number of occurrences of an object\n\
Raymond Hettinger49f9bd12004-03-14 05:43:59 +00002790extend() -- extend array by appending multiple elements from an iterable\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002791fromfile() -- read items from a file object\n\
2792fromlist() -- append items from the list\n\
Florent Xiclunac45fb252011-10-24 13:14:55 +02002793frombytes() -- append items from the string\n\
Mark Dickinson934896d2009-02-21 20:59:32 +00002794index() -- return index of first occurrence of an object\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002795insert() -- insert a new item into the array at a provided position\n\
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00002796pop() -- remove and return item (default last)\n\
Mark Dickinson934896d2009-02-21 20:59:32 +00002797remove() -- remove first occurrence of an object\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002798reverse() -- reverse the order of the items in the array\n\
2799tofile() -- write all items to a file object\n\
2800tolist() -- return the array converted to an ordinary list\n\
Florent Xiclunac45fb252011-10-24 13:14:55 +02002801tobytes() -- return the array converted to a string\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002802\n\
Martin v. Löwis99866332002-03-01 10:27:01 +00002803Attributes:\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002804\n\
2805typecode -- the typecode character used to create the array\n\
2806itemsize -- the length in bytes of one array item\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002807");
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002808
Raymond Hettinger625812f2003-01-07 01:58:52 +00002809static PyObject *array_iter(arrayobject *ao);
2810
Tim Peters0c322792002-07-17 16:49:03 +00002811static PyTypeObject Arraytype = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002812 PyVarObject_HEAD_INIT(NULL, 0)
2813 "array.array",
2814 sizeof(arrayobject),
2815 0,
2816 (destructor)array_dealloc, /* tp_dealloc */
2817 0, /* tp_print */
2818 0, /* tp_getattr */
2819 0, /* tp_setattr */
2820 0, /* tp_reserved */
2821 (reprfunc)array_repr, /* tp_repr */
2822 0, /* tp_as_number*/
2823 &array_as_sequence, /* tp_as_sequence*/
2824 &array_as_mapping, /* tp_as_mapping*/
2825 0, /* tp_hash */
2826 0, /* tp_call */
2827 0, /* tp_str */
2828 PyObject_GenericGetAttr, /* tp_getattro */
2829 0, /* tp_setattro */
2830 &array_as_buffer, /* tp_as_buffer*/
2831 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
2832 arraytype_doc, /* tp_doc */
2833 0, /* tp_traverse */
2834 0, /* tp_clear */
2835 array_richcompare, /* tp_richcompare */
2836 offsetof(arrayobject, weakreflist), /* tp_weaklistoffset */
2837 (getiterfunc)array_iter, /* tp_iter */
2838 0, /* tp_iternext */
2839 array_methods, /* tp_methods */
2840 0, /* tp_members */
2841 array_getsets, /* tp_getset */
2842 0, /* tp_base */
2843 0, /* tp_dict */
2844 0, /* tp_descr_get */
2845 0, /* tp_descr_set */
2846 0, /* tp_dictoffset */
2847 0, /* tp_init */
2848 PyType_GenericAlloc, /* tp_alloc */
2849 array_new, /* tp_new */
2850 PyObject_Del, /* tp_free */
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002851};
2852
Raymond Hettinger625812f2003-01-07 01:58:52 +00002853
2854/*********************** Array Iterator **************************/
2855
Brett Cannon1eb32c22014-10-10 16:26:45 -04002856/*[clinic input]
2857class array.arrayiterator "arrayiterobject *" "&PyArrayIter_Type"
2858[clinic start generated code]*/
2859/*[clinic end generated code: output=da39a3ee5e6b4b0d input=5aefd2d74d8c8e30]*/
Raymond Hettinger625812f2003-01-07 01:58:52 +00002860
2861static PyObject *
2862array_iter(arrayobject *ao)
2863{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002864 arrayiterobject *it;
Raymond Hettinger625812f2003-01-07 01:58:52 +00002865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002866 if (!array_Check(ao)) {
2867 PyErr_BadInternalCall();
2868 return NULL;
2869 }
Raymond Hettinger625812f2003-01-07 01:58:52 +00002870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002871 it = PyObject_GC_New(arrayiterobject, &PyArrayIter_Type);
2872 if (it == NULL)
2873 return NULL;
Raymond Hettinger625812f2003-01-07 01:58:52 +00002874
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002875 Py_INCREF(ao);
2876 it->ao = ao;
2877 it->index = 0;
2878 it->getitem = ao->ob_descr->getitem;
2879 PyObject_GC_Track(it);
2880 return (PyObject *)it;
Raymond Hettinger625812f2003-01-07 01:58:52 +00002881}
2882
2883static PyObject *
Raymond Hettinger625812f2003-01-07 01:58:52 +00002884arrayiter_next(arrayiterobject *it)
2885{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002886 assert(PyArrayIter_Check(it));
2887 if (it->index < Py_SIZE(it->ao))
2888 return (*it->getitem)(it->ao, it->index++);
2889 return NULL;
Raymond Hettinger625812f2003-01-07 01:58:52 +00002890}
2891
2892static void
2893arrayiter_dealloc(arrayiterobject *it)
2894{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002895 PyObject_GC_UnTrack(it);
2896 Py_XDECREF(it->ao);
2897 PyObject_GC_Del(it);
Raymond Hettinger625812f2003-01-07 01:58:52 +00002898}
2899
2900static int
2901arrayiter_traverse(arrayiterobject *it, visitproc visit, void *arg)
2902{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002903 Py_VISIT(it->ao);
2904 return 0;
Raymond Hettinger625812f2003-01-07 01:58:52 +00002905}
2906
Brett Cannon1eb32c22014-10-10 16:26:45 -04002907/*[clinic input]
2908array.arrayiterator.__reduce__
2909
2910Return state information for pickling.
2911[clinic start generated code]*/
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002912
2913static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04002914array_arrayiterator___reduce___impl(arrayiterobject *self)
2915/*[clinic end generated code: output=7898a52e8e66e016 input=a062ea1e9951417a]*/
2916{
2917 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
2918 self->ao, self->index);
2919}
2920
2921/*[clinic input]
2922array.arrayiterator.__setstate__
2923
2924 state: object
2925 /
2926
2927Set state information for unpickling.
2928[clinic start generated code]*/
2929
2930static PyObject *
2931array_arrayiterator___setstate__(arrayiterobject *self, PyObject *state)
2932/*[clinic end generated code: output=397da9904e443cbe input=f47d5ceda19e787b]*/
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002933{
2934 Py_ssize_t index = PyLong_AsSsize_t(state);
2935 if (index == -1 && PyErr_Occurred())
2936 return NULL;
2937 if (index < 0)
2938 index = 0;
Brett Cannon1eb32c22014-10-10 16:26:45 -04002939 else if (index > Py_SIZE(self->ao))
2940 index = Py_SIZE(self->ao); /* iterator exhausted */
2941 self->index = index;
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002942 Py_RETURN_NONE;
2943}
2944
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002945static PyMethodDef arrayiter_methods[] = {
Brett Cannon1eb32c22014-10-10 16:26:45 -04002946 ARRAY_ARRAYITERATOR___REDUCE___METHODDEF
2947 ARRAY_ARRAYITERATOR___SETSTATE___METHODDEF
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002948 {NULL, NULL} /* sentinel */
2949};
2950
Raymond Hettinger625812f2003-01-07 01:58:52 +00002951static PyTypeObject PyArrayIter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002952 PyVarObject_HEAD_INIT(NULL, 0)
2953 "arrayiterator", /* tp_name */
2954 sizeof(arrayiterobject), /* tp_basicsize */
2955 0, /* tp_itemsize */
2956 /* methods */
2957 (destructor)arrayiter_dealloc, /* tp_dealloc */
2958 0, /* tp_print */
2959 0, /* tp_getattr */
2960 0, /* tp_setattr */
2961 0, /* tp_reserved */
2962 0, /* tp_repr */
2963 0, /* tp_as_number */
2964 0, /* tp_as_sequence */
2965 0, /* tp_as_mapping */
2966 0, /* tp_hash */
2967 0, /* tp_call */
2968 0, /* tp_str */
2969 PyObject_GenericGetAttr, /* tp_getattro */
2970 0, /* tp_setattro */
2971 0, /* tp_as_buffer */
2972 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2973 0, /* tp_doc */
2974 (traverseproc)arrayiter_traverse, /* tp_traverse */
2975 0, /* tp_clear */
2976 0, /* tp_richcompare */
2977 0, /* tp_weaklistoffset */
2978 PyObject_SelfIter, /* tp_iter */
2979 (iternextfunc)arrayiter_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002980 arrayiter_methods, /* tp_methods */
Raymond Hettinger625812f2003-01-07 01:58:52 +00002981};
2982
2983
2984/*********************** Install Module **************************/
2985
Martin v. Löwis99866332002-03-01 10:27:01 +00002986/* No functions in array module. */
2987static PyMethodDef a_methods[] = {
Brett Cannon1eb32c22014-10-10 16:26:45 -04002988 ARRAY__ARRAY_RECONSTRUCTOR_METHODDEF
Martin v. Löwis99866332002-03-01 10:27:01 +00002989 {NULL, NULL, 0, NULL} /* Sentinel */
2990};
2991
Nick Coghland5cacbb2015-05-23 22:24:10 +10002992static int
2993array_modexec(PyObject *m)
Guido van Rossum778983b1993-02-19 15:55:02 +00002994{
Georg Brandl4cb0de22011-09-28 21:49:49 +02002995 char buffer[Py_ARRAY_LENGTH(descriptors)], *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002996 PyObject *typecodes;
2997 Py_ssize_t size = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002998 struct arraydescr *descr;
Fred Drake0d40ba42000-02-04 20:33:49 +00002999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003000 if (PyType_Ready(&Arraytype) < 0)
Nick Coghland5cacbb2015-05-23 22:24:10 +10003001 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003002 Py_TYPE(&PyArrayIter_Type) = &PyType_Type;
Fred Drakef4e34842002-04-01 03:45:06 +00003003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003004 Py_INCREF((PyObject *)&Arraytype);
3005 PyModule_AddObject(m, "ArrayType", (PyObject *)&Arraytype);
3006 Py_INCREF((PyObject *)&Arraytype);
3007 PyModule_AddObject(m, "array", (PyObject *)&Arraytype);
Travis E. Oliphantd5c0add2007-10-12 22:05:15 +00003008
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003009 for (descr=descriptors; descr->typecode != '\0'; descr++) {
3010 size++;
3011 }
Travis E. Oliphantd5c0add2007-10-12 22:05:15 +00003012
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003013 p = buffer;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003014 for (descr = descriptors; descr->typecode != '\0'; descr++) {
3015 *p++ = (char)descr->typecode;
3016 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003017 typecodes = PyUnicode_DecodeASCII(buffer, p - buffer, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003018
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003019 PyModule_AddObject(m, "typecodes", typecodes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003020
3021 if (PyErr_Occurred()) {
3022 Py_DECREF(m);
3023 m = NULL;
3024 }
Nick Coghland5cacbb2015-05-23 22:24:10 +10003025 return 0;
3026}
3027
3028static PyModuleDef_Slot arrayslots[] = {
3029 {Py_mod_exec, array_modexec},
3030 {0, NULL}
3031};
3032
3033
3034static struct PyModuleDef arraymodule = {
3035 PyModuleDef_HEAD_INIT,
3036 "array",
3037 module_doc,
3038 0,
3039 a_methods,
3040 arrayslots,
3041 NULL,
3042 NULL,
3043 NULL
3044};
3045
3046
3047PyMODINIT_FUNC
3048PyInit_array(void)
3049{
3050 return PyModuleDef_Init(&arraymodule);
Guido van Rossum778983b1993-02-19 15:55:02 +00003051}