blob: 6e20aaa7d5f941895300952ddfbb5fec59b8a78f [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;
748 memcpy(np->ob_item, a->ob_item + ilow * a->ob_descr->itemsize,
749 (ihigh-ilow) * a->ob_descr->itemsize);
750 return (PyObject *)np;
Guido van Rossum778983b1993-02-19 15:55:02 +0000751}
752
Brett Cannon1eb32c22014-10-10 16:26:45 -0400753
754/*[clinic input]
755array.array.__copy__
756
757Return a copy of the array.
758[clinic start generated code]*/
759
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000760static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -0400761array_array___copy___impl(arrayobject *self)
762/*[clinic end generated code: output=dec7c3f925d9619e input=ad1ee5b086965f09]*/
Raymond Hettinger3aa82c02004-03-13 18:18:51 +0000763{
Brett Cannon1eb32c22014-10-10 16:26:45 -0400764 return array_slice(self, 0, Py_SIZE(self));
Raymond Hettinger3aa82c02004-03-13 18:18:51 +0000765}
766
Brett Cannon1eb32c22014-10-10 16:26:45 -0400767/*[clinic input]
768array.array.__deepcopy__
769
770 unused: object
771 /
772
773Return a copy of the array.
774[clinic start generated code]*/
775
776static PyObject *
777array_array___deepcopy__(arrayobject *self, PyObject *unused)
778/*[clinic end generated code: output=1ec748d8e14a9faa input=2405ecb4933748c4]*/
779{
780 return array_array___copy___impl(self);
781}
Raymond Hettinger3aa82c02004-03-13 18:18:51 +0000782
783static PyObject *
Peter Schneider-Kamp9656abd2000-07-13 21:10:57 +0000784array_concat(arrayobject *a, PyObject *bb)
Guido van Rossum778983b1993-02-19 15:55:02 +0000785{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000786 Py_ssize_t size;
787 arrayobject *np;
788 if (!array_Check(bb)) {
789 PyErr_Format(PyExc_TypeError,
790 "can only append array (not \"%.200s\") to array",
791 Py_TYPE(bb)->tp_name);
792 return NULL;
793 }
Guido van Rossum778983b1993-02-19 15:55:02 +0000794#define b ((arrayobject *)bb)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000795 if (a->ob_descr != b->ob_descr) {
796 PyErr_BadArgument();
797 return NULL;
798 }
799 if (Py_SIZE(a) > PY_SSIZE_T_MAX - Py_SIZE(b)) {
800 return PyErr_NoMemory();
801 }
802 size = Py_SIZE(a) + Py_SIZE(b);
803 np = (arrayobject *) newarrayobject(&Arraytype, size, a->ob_descr);
804 if (np == NULL) {
805 return NULL;
806 }
807 memcpy(np->ob_item, a->ob_item, Py_SIZE(a)*a->ob_descr->itemsize);
808 memcpy(np->ob_item + Py_SIZE(a)*a->ob_descr->itemsize,
809 b->ob_item, Py_SIZE(b)*b->ob_descr->itemsize);
810 return (PyObject *)np;
Guido van Rossum778983b1993-02-19 15:55:02 +0000811#undef b
812}
813
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000814static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000815array_repeat(arrayobject *a, Py_ssize_t n)
Guido van Rossum778983b1993-02-19 15:55:02 +0000816{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000817 Py_ssize_t size;
818 arrayobject *np;
Georg Brandlc29cc6a2010-12-04 11:02:04 +0000819 Py_ssize_t oldbytes, newbytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000820 if (n < 0)
821 n = 0;
822 if ((Py_SIZE(a) != 0) && (n > PY_SSIZE_T_MAX / Py_SIZE(a))) {
823 return PyErr_NoMemory();
824 }
825 size = Py_SIZE(a) * n;
826 np = (arrayobject *) newarrayobject(&Arraytype, size, a->ob_descr);
827 if (np == NULL)
828 return NULL;
Georg Brandlc29cc6a2010-12-04 11:02:04 +0000829 if (n == 0)
830 return (PyObject *)np;
831 oldbytes = Py_SIZE(a) * a->ob_descr->itemsize;
832 newbytes = oldbytes * n;
833 /* this follows the code in unicode_repeat */
834 if (oldbytes == 1) {
835 memset(np->ob_item, a->ob_item[0], newbytes);
836 } else {
837 Py_ssize_t done = oldbytes;
838 Py_MEMCPY(np->ob_item, a->ob_item, oldbytes);
839 while (done < newbytes) {
840 Py_ssize_t ncopy = (done <= newbytes-done) ? done : newbytes-done;
841 Py_MEMCPY(np->ob_item+done, np->ob_item, ncopy);
842 done += ncopy;
843 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000844 }
Georg Brandlc29cc6a2010-12-04 11:02:04 +0000845 return (PyObject *)np;
Guido van Rossum778983b1993-02-19 15:55:02 +0000846}
847
848static int
Martin v. Löwisad0a4622006-02-16 14:30:23 +0000849array_ass_slice(arrayobject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum778983b1993-02-19 15:55:02 +0000850{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000851 char *item;
852 Py_ssize_t n; /* Size of replacement array */
853 Py_ssize_t d; /* Change in size */
Guido van Rossum778983b1993-02-19 15:55:02 +0000854#define b ((arrayobject *)v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 if (v == NULL)
856 n = 0;
857 else if (array_Check(v)) {
858 n = Py_SIZE(b);
859 if (a == b) {
860 /* Special case "a[i:j] = a" -- copy b first */
861 int ret;
862 v = array_slice(b, 0, n);
863 if (!v)
864 return -1;
865 ret = array_ass_slice(a, ilow, ihigh, v);
866 Py_DECREF(v);
867 return ret;
868 }
869 if (b->ob_descr != a->ob_descr) {
870 PyErr_BadArgument();
871 return -1;
872 }
873 }
874 else {
875 PyErr_Format(PyExc_TypeError,
876 "can only assign array (not \"%.200s\") to array slice",
877 Py_TYPE(v)->tp_name);
878 return -1;
879 }
880 if (ilow < 0)
881 ilow = 0;
882 else if (ilow > Py_SIZE(a))
883 ilow = Py_SIZE(a);
884 if (ihigh < 0)
885 ihigh = 0;
886 if (ihigh < ilow)
887 ihigh = ilow;
888 else if (ihigh > Py_SIZE(a))
889 ihigh = Py_SIZE(a);
890 item = a->ob_item;
891 d = n - (ihigh-ilow);
892 /* Issue #4509: If the array has exported buffers and the slice
893 assignment would change the size of the array, fail early to make
894 sure we don't modify it. */
895 if (d != 0 && a->ob_exports > 0) {
896 PyErr_SetString(PyExc_BufferError,
897 "cannot resize an array that is exporting buffers");
898 return -1;
899 }
900 if (d < 0) { /* Delete -d items */
901 memmove(item + (ihigh+d)*a->ob_descr->itemsize,
902 item + ihigh*a->ob_descr->itemsize,
903 (Py_SIZE(a)-ihigh)*a->ob_descr->itemsize);
904 if (array_resize(a, Py_SIZE(a) + d) == -1)
905 return -1;
906 }
907 else if (d > 0) { /* Insert d items */
908 if (array_resize(a, Py_SIZE(a) + d))
909 return -1;
910 memmove(item + (ihigh+d)*a->ob_descr->itemsize,
911 item + ihigh*a->ob_descr->itemsize,
912 (Py_SIZE(a)-ihigh)*a->ob_descr->itemsize);
913 }
914 if (n > 0)
915 memcpy(item + ilow*a->ob_descr->itemsize, b->ob_item,
916 n*b->ob_descr->itemsize);
917 return 0;
Guido van Rossum778983b1993-02-19 15:55:02 +0000918#undef b
919}
920
921static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000922array_ass_item(arrayobject *a, Py_ssize_t i, PyObject *v)
Guido van Rossum778983b1993-02-19 15:55:02 +0000923{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 if (i < 0 || i >= Py_SIZE(a)) {
925 PyErr_SetString(PyExc_IndexError,
926 "array assignment index out of range");
927 return -1;
928 }
929 if (v == NULL)
930 return array_ass_slice(a, i, i+1, v);
931 return (*a->ob_descr->setitem)(a, i, v);
Guido van Rossum778983b1993-02-19 15:55:02 +0000932}
933
934static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000935setarrayitem(PyObject *a, Py_ssize_t i, PyObject *v)
Guido van Rossum778983b1993-02-19 15:55:02 +0000936{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000937 assert(array_Check(a));
938 return array_ass_item((arrayobject *)a, i, v);
Guido van Rossum778983b1993-02-19 15:55:02 +0000939}
940
Martin v. Löwis99866332002-03-01 10:27:01 +0000941static int
Raymond Hettinger49f9bd12004-03-14 05:43:59 +0000942array_iter_extend(arrayobject *self, PyObject *bb)
943{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000944 PyObject *it, *v;
Raymond Hettinger49f9bd12004-03-14 05:43:59 +0000945
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 it = PyObject_GetIter(bb);
947 if (it == NULL)
948 return -1;
Raymond Hettinger49f9bd12004-03-14 05:43:59 +0000949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 while ((v = PyIter_Next(it)) != NULL) {
Mark Dickinson346f0af2010-08-06 09:36:57 +0000951 if (ins1(self, Py_SIZE(self), v) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 Py_DECREF(v);
953 Py_DECREF(it);
954 return -1;
955 }
956 Py_DECREF(v);
957 }
958 Py_DECREF(it);
959 if (PyErr_Occurred())
960 return -1;
961 return 0;
Raymond Hettinger49f9bd12004-03-14 05:43:59 +0000962}
963
964static int
Martin v. Löwis99866332002-03-01 10:27:01 +0000965array_do_extend(arrayobject *self, PyObject *bb)
966{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000967 Py_ssize_t size, oldsize, bbsize;
Martin v. Löwis99866332002-03-01 10:27:01 +0000968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 if (!array_Check(bb))
970 return array_iter_extend(self, bb);
971#define b ((arrayobject *)bb)
972 if (self->ob_descr != b->ob_descr) {
973 PyErr_SetString(PyExc_TypeError,
974 "can only extend with array of same kind");
975 return -1;
976 }
977 if ((Py_SIZE(self) > PY_SSIZE_T_MAX - Py_SIZE(b)) ||
978 ((Py_SIZE(self) + Py_SIZE(b)) > PY_SSIZE_T_MAX / self->ob_descr->itemsize)) {
979 PyErr_NoMemory();
980 return -1;
981 }
982 oldsize = Py_SIZE(self);
983 /* Get the size of bb before resizing the array since bb could be self. */
984 bbsize = Py_SIZE(bb);
985 size = oldsize + Py_SIZE(b);
986 if (array_resize(self, size) == -1)
987 return -1;
988 memcpy(self->ob_item + oldsize * self->ob_descr->itemsize,
989 b->ob_item, bbsize * b->ob_descr->itemsize);
990
991 return 0;
Martin v. Löwis99866332002-03-01 10:27:01 +0000992#undef b
993}
994
995static PyObject *
996array_inplace_concat(arrayobject *self, PyObject *bb)
997{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998 if (!array_Check(bb)) {
999 PyErr_Format(PyExc_TypeError,
1000 "can only extend array with array (not \"%.200s\")",
1001 Py_TYPE(bb)->tp_name);
1002 return NULL;
1003 }
1004 if (array_do_extend(self, bb) == -1)
1005 return NULL;
1006 Py_INCREF(self);
1007 return (PyObject *)self;
Martin v. Löwis99866332002-03-01 10:27:01 +00001008}
1009
1010static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001011array_inplace_repeat(arrayobject *self, Py_ssize_t n)
Martin v. Löwis99866332002-03-01 10:27:01 +00001012{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001013 char *items, *p;
1014 Py_ssize_t size, i;
Martin v. Löwis99866332002-03-01 10:27:01 +00001015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 if (Py_SIZE(self) > 0) {
1017 if (n < 0)
1018 n = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 if ((self->ob_descr->itemsize != 0) &&
1020 (Py_SIZE(self) > PY_SSIZE_T_MAX / self->ob_descr->itemsize)) {
1021 return PyErr_NoMemory();
1022 }
1023 size = Py_SIZE(self) * self->ob_descr->itemsize;
1024 if (n > 0 && size > PY_SSIZE_T_MAX / n) {
1025 return PyErr_NoMemory();
1026 }
1027 if (array_resize(self, n * Py_SIZE(self)) == -1)
1028 return NULL;
1029 items = p = self->ob_item;
1030 for (i = 1; i < n; i++) {
1031 p += size;
1032 memcpy(p, items, size);
1033 }
1034 }
1035 Py_INCREF(self);
1036 return (PyObject *)self;
Martin v. Löwis99866332002-03-01 10:27:01 +00001037}
1038
1039
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001040static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001041ins(arrayobject *self, Py_ssize_t where, PyObject *v)
Guido van Rossum778983b1993-02-19 15:55:02 +00001042{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 if (ins1(self, where, v) != 0)
1044 return NULL;
1045 Py_INCREF(Py_None);
1046 return Py_None;
Guido van Rossum778983b1993-02-19 15:55:02 +00001047}
1048
Brett Cannon1eb32c22014-10-10 16:26:45 -04001049/*[clinic input]
1050array.array.count
1051
1052 v: object
1053 /
1054
1055Return number of occurrences of v in the array.
1056[clinic start generated code]*/
1057
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001058static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001059array_array_count(arrayobject *self, PyObject *v)
1060/*[clinic end generated code: output=3dd3624bf7135a3a input=d9bce9d65e39d1f5]*/
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001061{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001062 Py_ssize_t count = 0;
1063 Py_ssize_t i;
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001065 for (i = 0; i < Py_SIZE(self); i++) {
Victor Stinner0b142e22013-07-17 23:01:30 +02001066 PyObject *selfi;
1067 int cmp;
1068
1069 selfi = getarrayitem((PyObject *)self, i);
1070 if (selfi == NULL)
1071 return NULL;
1072 cmp = PyObject_RichCompareBool(selfi, v, Py_EQ);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 Py_DECREF(selfi);
1074 if (cmp > 0)
1075 count++;
1076 else if (cmp < 0)
1077 return NULL;
1078 }
1079 return PyLong_FromSsize_t(count);
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001080}
1081
Brett Cannon1eb32c22014-10-10 16:26:45 -04001082
1083/*[clinic input]
1084array.array.index
1085
1086 v: object
1087 /
1088
1089Return index of first occurrence of v in the array.
1090[clinic start generated code]*/
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001091
1092static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001093array_array_index(arrayobject *self, PyObject *v)
1094/*[clinic end generated code: output=d48498d325602167 input=cf619898c6649d08]*/
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001095{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001096 Py_ssize_t i;
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001097
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098 for (i = 0; i < Py_SIZE(self); i++) {
Victor Stinner0b142e22013-07-17 23:01:30 +02001099 PyObject *selfi;
1100 int cmp;
1101
1102 selfi = getarrayitem((PyObject *)self, i);
1103 if (selfi == NULL)
1104 return NULL;
1105 cmp = PyObject_RichCompareBool(selfi, v, Py_EQ);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 Py_DECREF(selfi);
1107 if (cmp > 0) {
1108 return PyLong_FromLong((long)i);
1109 }
1110 else if (cmp < 0)
1111 return NULL;
1112 }
1113 PyErr_SetString(PyExc_ValueError, "array.index(x): x not in list");
1114 return NULL;
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001115}
1116
Raymond Hettinger625812f2003-01-07 01:58:52 +00001117static int
1118array_contains(arrayobject *self, PyObject *v)
1119{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001120 Py_ssize_t i;
1121 int cmp;
Raymond Hettinger625812f2003-01-07 01:58:52 +00001122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001123 for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(self); i++) {
1124 PyObject *selfi = getarrayitem((PyObject *)self, i);
Victor Stinner0b142e22013-07-17 23:01:30 +02001125 if (selfi == NULL)
Victor Stinner4755bea2013-07-18 01:12:35 +02001126 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001127 cmp = PyObject_RichCompareBool(selfi, v, Py_EQ);
1128 Py_DECREF(selfi);
1129 }
1130 return cmp;
Raymond Hettinger625812f2003-01-07 01:58:52 +00001131}
1132
Brett Cannon1eb32c22014-10-10 16:26:45 -04001133/*[clinic input]
1134array.array.remove
1135
1136 v: object
1137 /
1138
1139Remove the first occurrence of v in the array.
1140[clinic start generated code]*/
1141
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001142static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001143array_array_remove(arrayobject *self, PyObject *v)
1144/*[clinic end generated code: output=bef06be9fdf9dceb input=0b1e5aed25590027]*/
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001145{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001146 int i;
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001148 for (i = 0; i < Py_SIZE(self); i++) {
Victor Stinner0b142e22013-07-17 23:01:30 +02001149 PyObject *selfi;
1150 int cmp;
1151
1152 selfi = getarrayitem((PyObject *)self,i);
1153 if (selfi == NULL)
1154 return NULL;
1155 cmp = PyObject_RichCompareBool(selfi, v, Py_EQ);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001156 Py_DECREF(selfi);
1157 if (cmp > 0) {
1158 if (array_ass_slice(self, i, i+1,
1159 (PyObject *)NULL) != 0)
1160 return NULL;
1161 Py_INCREF(Py_None);
1162 return Py_None;
1163 }
1164 else if (cmp < 0)
1165 return NULL;
1166 }
1167 PyErr_SetString(PyExc_ValueError, "array.remove(x): x not in list");
1168 return NULL;
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001169}
1170
Brett Cannon1eb32c22014-10-10 16:26:45 -04001171/*[clinic input]
1172array.array.pop
1173
1174 i: Py_ssize_t = -1
1175 /
1176
1177Return the i-th element and delete it from the array.
1178
1179i defaults to -1.
1180[clinic start generated code]*/
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001181
1182static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001183array_array_pop_impl(arrayobject *self, Py_ssize_t i)
1184/*[clinic end generated code: output=bc1f0c54fe5308e4 input=8e5feb4c1a11cd44]*/
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001185{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001186 PyObject *v;
Brett Cannon1eb32c22014-10-10 16:26:45 -04001187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 if (Py_SIZE(self) == 0) {
1189 /* Special-case most common failure cause */
1190 PyErr_SetString(PyExc_IndexError, "pop from empty array");
1191 return NULL;
1192 }
1193 if (i < 0)
1194 i += Py_SIZE(self);
1195 if (i < 0 || i >= Py_SIZE(self)) {
1196 PyErr_SetString(PyExc_IndexError, "pop index out of range");
1197 return NULL;
1198 }
Victor Stinner0b142e22013-07-17 23:01:30 +02001199 v = getarrayitem((PyObject *)self, i);
1200 if (v == NULL)
1201 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001202 if (array_ass_slice(self, i, i+1, (PyObject *)NULL) != 0) {
1203 Py_DECREF(v);
1204 return NULL;
1205 }
1206 return v;
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001207}
1208
Brett Cannon1eb32c22014-10-10 16:26:45 -04001209/*[clinic input]
1210array.array.extend
1211
1212 bb: object
1213 /
1214
1215Append items to the end of the array.
1216[clinic start generated code]*/
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001217
1218static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001219array_array_extend(arrayobject *self, PyObject *bb)
1220/*[clinic end generated code: output=bbddbc8e8bef871d input=43be86aba5c31e44]*/
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001221{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001222 if (array_do_extend(self, bb) == -1)
1223 return NULL;
1224 Py_INCREF(Py_None);
1225 return Py_None;
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001226}
1227
Brett Cannon1eb32c22014-10-10 16:26:45 -04001228/*[clinic input]
1229array.array.insert
1230
1231 i: Py_ssize_t
1232 v: object
1233 /
1234
1235Insert a new item v into the array before position i.
1236[clinic start generated code]*/
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001237
1238static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001239array_array_insert_impl(arrayobject *self, Py_ssize_t i, PyObject *v)
1240/*[clinic end generated code: output=5a3648e278348564 input=5577d1b4383e9313]*/
Guido van Rossum778983b1993-02-19 15:55:02 +00001241{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001242 return ins(self, i, v);
Guido van Rossum778983b1993-02-19 15:55:02 +00001243}
1244
Brett Cannon1eb32c22014-10-10 16:26:45 -04001245/*[clinic input]
1246array.array.buffer_info
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001247
Brett Cannon1eb32c22014-10-10 16:26:45 -04001248Return a tuple (address, length) giving the current memory address and the length in items of the buffer used to hold array's contents.
1249
1250The length should be multiplied by the itemsize attribute to calculate
1251the buffer length in bytes.
1252[clinic start generated code]*/
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001253
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001254static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001255array_array_buffer_info_impl(arrayobject *self)
1256/*[clinic end generated code: output=9b2a4ec3ae7e98e7 input=a58bae5c6e1ac6a6]*/
Guido van Rossumde4a4ca1997-08-12 14:55:56 +00001257{
Victor Stinner541067a2013-11-14 01:27:12 +01001258 PyObject *retval = NULL, *v;
1259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001260 retval = PyTuple_New(2);
1261 if (!retval)
1262 return NULL;
Fred Drake541dc3b2000-06-28 17:49:30 +00001263
Victor Stinner541067a2013-11-14 01:27:12 +01001264 v = PyLong_FromVoidPtr(self->ob_item);
1265 if (v == NULL) {
1266 Py_DECREF(retval);
1267 return NULL;
1268 }
1269 PyTuple_SET_ITEM(retval, 0, v);
1270
1271 v = PyLong_FromLong((long)(Py_SIZE(self)));
1272 if (v == NULL) {
1273 Py_DECREF(retval);
1274 return NULL;
1275 }
1276 PyTuple_SET_ITEM(retval, 1, v);
Fred Drake541dc3b2000-06-28 17:49:30 +00001277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001278 return retval;
Guido van Rossumde4a4ca1997-08-12 14:55:56 +00001279}
1280
Brett Cannon1eb32c22014-10-10 16:26:45 -04001281/*[clinic input]
1282array.array.append
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001283
Brett Cannon1eb32c22014-10-10 16:26:45 -04001284 v: object
1285 /
1286
1287Append new value v to the end of the array.
1288[clinic start generated code]*/
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001289
Guido van Rossumde4a4ca1997-08-12 14:55:56 +00001290static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001291array_array_append(arrayobject *self, PyObject *v)
1292/*[clinic end generated code: output=745a0669bf8db0e2 input=0b98d9d78e78f0fa]*/
Guido van Rossum778983b1993-02-19 15:55:02 +00001293{
Mark Dickinson346f0af2010-08-06 09:36:57 +00001294 return ins(self, Py_SIZE(self), v);
Guido van Rossum778983b1993-02-19 15:55:02 +00001295}
1296
Brett Cannon1eb32c22014-10-10 16:26:45 -04001297/*[clinic input]
1298array.array.byteswap
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001299
Brett Cannon1eb32c22014-10-10 16:26:45 -04001300Byteswap all items of the array.
1301
1302If the items in the array are not 1, 2, 4, or 8 bytes in size, RuntimeError is
1303raised.
1304[clinic start generated code]*/
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001305
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001306static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001307array_array_byteswap_impl(arrayobject *self)
1308/*[clinic end generated code: output=5f8236cbdf0d90b5 input=6a85591b950a0186]*/
Guido van Rossum778983b1993-02-19 15:55:02 +00001309{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001310 char *p;
1311 Py_ssize_t i;
Fred Drakebf272981999-12-03 17:15:30 +00001312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001313 switch (self->ob_descr->itemsize) {
1314 case 1:
1315 break;
1316 case 2:
1317 for (p = self->ob_item, i = Py_SIZE(self); --i >= 0; p += 2) {
1318 char p0 = p[0];
1319 p[0] = p[1];
1320 p[1] = p0;
1321 }
1322 break;
1323 case 4:
1324 for (p = self->ob_item, i = Py_SIZE(self); --i >= 0; p += 4) {
1325 char p0 = p[0];
1326 char p1 = p[1];
1327 p[0] = p[3];
1328 p[1] = p[2];
1329 p[2] = p1;
1330 p[3] = p0;
1331 }
1332 break;
1333 case 8:
1334 for (p = self->ob_item, i = Py_SIZE(self); --i >= 0; p += 8) {
1335 char p0 = p[0];
1336 char p1 = p[1];
1337 char p2 = p[2];
1338 char p3 = p[3];
1339 p[0] = p[7];
1340 p[1] = p[6];
1341 p[2] = p[5];
1342 p[3] = p[4];
1343 p[4] = p3;
1344 p[5] = p2;
1345 p[6] = p1;
1346 p[7] = p0;
1347 }
1348 break;
1349 default:
1350 PyErr_SetString(PyExc_RuntimeError,
1351 "don't know how to byteswap this array type");
1352 return NULL;
1353 }
1354 Py_INCREF(Py_None);
1355 return Py_None;
Guido van Rossum778983b1993-02-19 15:55:02 +00001356}
1357
Brett Cannon1eb32c22014-10-10 16:26:45 -04001358/*[clinic input]
1359array.array.reverse
1360
1361Reverse the order of the items in the array.
1362[clinic start generated code]*/
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001363
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001364static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001365array_array_reverse_impl(arrayobject *self)
1366/*[clinic end generated code: output=c04868b36f6f4089 input=cd904f01b27d966a]*/
Guido van Rossum778983b1993-02-19 15:55:02 +00001367{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001368 Py_ssize_t itemsize = self->ob_descr->itemsize;
1369 char *p, *q;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001370 /* little buffer to hold items while swapping */
1371 char tmp[256]; /* 8 is probably enough -- but why skimp */
1372 assert((size_t)itemsize <= sizeof(tmp));
Guido van Rossume77a7571993-11-03 15:01:26 +00001373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001374 if (Py_SIZE(self) > 1) {
1375 for (p = self->ob_item,
1376 q = self->ob_item + (Py_SIZE(self) - 1)*itemsize;
1377 p < q;
1378 p += itemsize, q -= itemsize) {
1379 /* memory areas guaranteed disjoint, so memcpy
1380 * is safe (& memmove may be slower).
1381 */
1382 memcpy(tmp, p, itemsize);
1383 memcpy(p, q, itemsize);
1384 memcpy(q, tmp, itemsize);
1385 }
1386 }
Tim Petersbb307342000-09-10 05:22:54 +00001387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001388 Py_INCREF(Py_None);
1389 return Py_None;
Guido van Rossum778983b1993-02-19 15:55:02 +00001390}
Guido van Rossume77a7571993-11-03 15:01:26 +00001391
Brett Cannon1eb32c22014-10-10 16:26:45 -04001392/*[clinic input]
1393array.array.fromfile
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001394
Brett Cannon1eb32c22014-10-10 16:26:45 -04001395 f: object
1396 n: Py_ssize_t
1397 /
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001398
Brett Cannon1eb32c22014-10-10 16:26:45 -04001399Read n objects from the file object f and append them to the end of the array.
1400[clinic start generated code]*/
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001401
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001402static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001403array_array_fromfile_impl(arrayobject *self, PyObject *f, Py_ssize_t n)
1404/*[clinic end generated code: output=ec9f600e10f53510 input=e188afe8e58adf40]*/
Guido van Rossum778983b1993-02-19 15:55:02 +00001405{
Serhiy Storchaka04e6dba2015-04-04 17:06:55 +03001406 PyObject *b, *res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001407 Py_ssize_t itemsize = self->ob_descr->itemsize;
Brett Cannon1eb32c22014-10-10 16:26:45 -04001408 Py_ssize_t nbytes;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001409 _Py_IDENTIFIER(read);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 int not_enough_bytes;
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001411
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01001412 if (n < 0) {
1413 PyErr_SetString(PyExc_ValueError, "negative count");
1414 return NULL;
1415 }
1416 if (n > PY_SSIZE_T_MAX / itemsize) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001417 PyErr_NoMemory();
1418 return NULL;
1419 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01001420 nbytes = n * itemsize;
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001421
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001422 b = _PyObject_CallMethodId(f, &PyId_read, "n", nbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001423 if (b == NULL)
1424 return NULL;
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001426 if (!PyBytes_Check(b)) {
1427 PyErr_SetString(PyExc_TypeError,
1428 "read() didn't return bytes");
1429 Py_DECREF(b);
1430 return NULL;
1431 }
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001432
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001433 not_enough_bytes = (PyBytes_GET_SIZE(b) != nbytes);
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001434
Serhiy Storchaka04e6dba2015-04-04 17:06:55 +03001435 res = array_array_frombytes(self, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001436 Py_DECREF(b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001437 if (res == NULL)
1438 return NULL;
Hirokazu Yamamoto54d0df62009-03-06 03:04:07 +00001439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001440 if (not_enough_bytes) {
1441 PyErr_SetString(PyExc_EOFError,
1442 "read() didn't return enough bytes");
1443 Py_DECREF(res);
1444 return NULL;
1445 }
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001446
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001447 return res;
Guido van Rossum778983b1993-02-19 15:55:02 +00001448}
1449
Brett Cannon1eb32c22014-10-10 16:26:45 -04001450/*[clinic input]
1451array.array.tofile
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001452
Brett Cannon1eb32c22014-10-10 16:26:45 -04001453 f: object
1454 /
1455
1456Write all items (as machine values) to the file object f.
1457[clinic start generated code]*/
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001458
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001459static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001460array_array_tofile(arrayobject *self, PyObject *f)
1461/*[clinic end generated code: output=3a2cfa8128df0777 input=b0669a484aab0831]*/
Guido van Rossum778983b1993-02-19 15:55:02 +00001462{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001463 Py_ssize_t nbytes = Py_SIZE(self) * self->ob_descr->itemsize;
1464 /* Write 64K blocks at a time */
1465 /* XXX Make the block size settable */
1466 int BLOCKSIZE = 64*1024;
1467 Py_ssize_t nblocks = (nbytes + BLOCKSIZE - 1) / BLOCKSIZE;
1468 Py_ssize_t i;
Raymond Hettinger36cd2bf2003-01-03 08:24:58 +00001469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001470 if (Py_SIZE(self) == 0)
1471 goto done;
Guido van Rossumb5ddcfd2007-04-11 17:08:28 +00001472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001473 for (i = 0; i < nblocks; i++) {
1474 char* ptr = self->ob_item + i*BLOCKSIZE;
1475 Py_ssize_t size = BLOCKSIZE;
1476 PyObject *bytes, *res;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001477 _Py_IDENTIFIER(write);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001479 if (i*BLOCKSIZE + size > nbytes)
1480 size = nbytes - i*BLOCKSIZE;
1481 bytes = PyBytes_FromStringAndSize(ptr, size);
1482 if (bytes == NULL)
1483 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001484 res = _PyObject_CallMethodId(f, &PyId_write, "O", bytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001485 Py_DECREF(bytes);
1486 if (res == NULL)
1487 return NULL;
1488 Py_DECREF(res); /* drop write result */
1489 }
Guido van Rossumb5ddcfd2007-04-11 17:08:28 +00001490
1491 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001492 Py_INCREF(Py_None);
1493 return Py_None;
Guido van Rossum778983b1993-02-19 15:55:02 +00001494}
1495
Brett Cannon1eb32c22014-10-10 16:26:45 -04001496/*[clinic input]
1497array.array.fromlist
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001498
Brett Cannon1eb32c22014-10-10 16:26:45 -04001499 list: object
1500 /
1501
1502Append items to array from list.
1503[clinic start generated code]*/
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001504
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001505static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001506array_array_fromlist(arrayobject *self, PyObject *list)
1507/*[clinic end generated code: output=26411c2d228a3e3f input=be2605a96c49680f]*/
Guido van Rossum778983b1993-02-19 15:55:02 +00001508{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001509 Py_ssize_t n;
Raymond Hettinger36cd2bf2003-01-03 08:24:58 +00001510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001511 if (!PyList_Check(list)) {
1512 PyErr_SetString(PyExc_TypeError, "arg must be list");
1513 return NULL;
1514 }
1515 n = PyList_Size(list);
1516 if (n > 0) {
1517 Py_ssize_t i, old_size;
1518 old_size = Py_SIZE(self);
1519 if (array_resize(self, old_size + n) == -1)
1520 return NULL;
1521 for (i = 0; i < n; i++) {
1522 PyObject *v = PyList_GetItem(list, i);
1523 if ((*self->ob_descr->setitem)(self,
1524 Py_SIZE(self) - n + i, v) != 0) {
1525 array_resize(self, old_size);
1526 return NULL;
1527 }
1528 }
1529 }
1530 Py_INCREF(Py_None);
1531 return Py_None;
Guido van Rossum778983b1993-02-19 15:55:02 +00001532}
1533
Brett Cannon1eb32c22014-10-10 16:26:45 -04001534/*[clinic input]
1535array.array.tolist
1536
1537Convert array to an ordinary list with the same items.
1538[clinic start generated code]*/
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001539
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001540static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001541array_array_tolist_impl(arrayobject *self)
1542/*[clinic end generated code: output=00b60cc9eab8ef89 input=a8d7784a94f86b53]*/
Guido van Rossum778983b1993-02-19 15:55:02 +00001543{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001544 PyObject *list = PyList_New(Py_SIZE(self));
1545 Py_ssize_t i;
Raymond Hettinger36cd2bf2003-01-03 08:24:58 +00001546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001547 if (list == NULL)
1548 return NULL;
1549 for (i = 0; i < Py_SIZE(self); i++) {
1550 PyObject *v = getarrayitem((PyObject *)self, i);
Victor Stinner4755bea2013-07-18 01:12:35 +02001551 if (v == NULL)
1552 goto error;
1553 if (PyList_SetItem(list, i, v) < 0)
1554 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001555 }
1556 return list;
Victor Stinner4755bea2013-07-18 01:12:35 +02001557
1558error:
1559 Py_DECREF(list);
1560 return NULL;
Guido van Rossum778983b1993-02-19 15:55:02 +00001561}
1562
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001563static PyObject *
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001564frombytes(arrayobject *self, Py_buffer *buffer)
Guido van Rossum778983b1993-02-19 15:55:02 +00001565{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001566 int itemsize = self->ob_descr->itemsize;
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001567 Py_ssize_t n;
1568 if (buffer->itemsize != 1) {
1569 PyBuffer_Release(buffer);
Serhiy Storchakab757c832014-12-05 22:25:22 +02001570 PyErr_SetString(PyExc_TypeError, "a bytes-like object is required");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001571 return NULL;
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001572 }
1573 n = buffer->len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001574 if (n % itemsize != 0) {
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001575 PyBuffer_Release(buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001576 PyErr_SetString(PyExc_ValueError,
Serhiy Storchakab757c832014-12-05 22:25:22 +02001577 "bytes length not a multiple of item size");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001578 return NULL;
1579 }
1580 n = n / itemsize;
1581 if (n > 0) {
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001582 Py_ssize_t old_size = Py_SIZE(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001583 if ((n > PY_SSIZE_T_MAX - old_size) ||
1584 ((old_size + n) > PY_SSIZE_T_MAX / itemsize)) {
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001585 PyBuffer_Release(buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001586 return PyErr_NoMemory();
1587 }
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001588 if (array_resize(self, old_size + n) == -1) {
1589 PyBuffer_Release(buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001590 return NULL;
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001591 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001592 memcpy(self->ob_item + old_size * itemsize,
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001593 buffer->buf, n * itemsize);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001594 }
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001595 PyBuffer_Release(buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001596 Py_INCREF(Py_None);
1597 return Py_None;
Guido van Rossum778983b1993-02-19 15:55:02 +00001598}
1599
Brett Cannon1eb32c22014-10-10 16:26:45 -04001600/*[clinic input]
1601array.array.fromstring
1602
1603 buffer: Py_buffer(types='str bytes bytearray buffer')
1604 /
1605
1606Appends 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).
1607
1608This method is deprecated. Use frombytes instead.
1609[clinic start generated code]*/
1610
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001611static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001612array_array_fromstring_impl(arrayobject *self, Py_buffer *buffer)
1613/*[clinic end generated code: output=31c4baa779df84ce input=1302d94c97696b84]*/
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001614{
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001615 if (PyErr_WarnEx(PyExc_DeprecationWarning,
1616 "fromstring() is deprecated. Use frombytes() instead.", 2) != 0)
1617 return NULL;
Brett Cannon1eb32c22014-10-10 16:26:45 -04001618 return frombytes(self, buffer);
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001619}
1620
Brett Cannon1eb32c22014-10-10 16:26:45 -04001621/*[clinic input]
1622array.array.frombytes
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001623
Brett Cannon1eb32c22014-10-10 16:26:45 -04001624 buffer: Py_buffer
1625 /
1626
1627Appends 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).
1628[clinic start generated code]*/
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001629
1630static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001631array_array_frombytes_impl(arrayobject *self, Py_buffer *buffer)
1632/*[clinic end generated code: output=d9842c8f7510a516 input=2bbf2b53ebfcc988]*/
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001633{
Brett Cannon1eb32c22014-10-10 16:26:45 -04001634 return frombytes(self, buffer);
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001635}
1636
Brett Cannon1eb32c22014-10-10 16:26:45 -04001637/*[clinic input]
1638array.array.tobytes
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001639
Brett Cannon1eb32c22014-10-10 16:26:45 -04001640Convert the array to an array of machine values and return the bytes representation.
1641[clinic start generated code]*/
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001642
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001643static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001644array_array_tobytes_impl(arrayobject *self)
1645/*[clinic end generated code: output=87318e4edcdc2bb6 input=90ee495f96de34f5]*/
Guido van Rossum778983b1993-02-19 15:55:02 +00001646{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001647 if (Py_SIZE(self) <= PY_SSIZE_T_MAX / self->ob_descr->itemsize) {
1648 return PyBytes_FromStringAndSize(self->ob_item,
1649 Py_SIZE(self) * self->ob_descr->itemsize);
1650 } else {
1651 return PyErr_NoMemory();
1652 }
Guido van Rossum778983b1993-02-19 15:55:02 +00001653}
1654
Brett Cannon1eb32c22014-10-10 16:26:45 -04001655/*[clinic input]
1656array.array.tostring
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001657
Brett Cannon1eb32c22014-10-10 16:26:45 -04001658Convert the array to an array of machine values and return the bytes representation.
1659
1660This method is deprecated. Use tobytes instead.
1661[clinic start generated code]*/
Martin v. Löwis99866332002-03-01 10:27:01 +00001662
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001663static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001664array_array_tostring_impl(arrayobject *self)
1665/*[clinic end generated code: output=7d6bd92745a2c8f3 input=b6c0ddee7b30457e]*/
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001666{
Victor Stinner9f0b51e2010-11-09 09:38:30 +00001667 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001668 "tostring() is deprecated. Use tobytes() instead.", 2) != 0)
1669 return NULL;
Brett Cannon1eb32c22014-10-10 16:26:45 -04001670 return array_array_tobytes_impl(self);
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001671}
1672
Brett Cannon1eb32c22014-10-10 16:26:45 -04001673/*[clinic input]
1674array.array.fromunicode
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001675
Brett Cannon1eb32c22014-10-10 16:26:45 -04001676 ustr: Py_UNICODE(length=True)
1677 /
1678
1679Extends this array with data from the unicode string ustr.
1680
1681The array must be a unicode type array; otherwise a ValueError is raised.
1682Use array.frombytes(ustr.encode(...)) to append Unicode data to an array of
1683some other type.
1684[clinic start generated code]*/
Martin v. Löwis99866332002-03-01 10:27:01 +00001685
Martin v. Löwis99866332002-03-01 10:27:01 +00001686static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001687array_array_fromunicode_impl(arrayobject *self, Py_UNICODE *ustr, Py_ssize_clean_t ustr_length)
1688/*[clinic end generated code: output=3b3f4f133bac725e input=56bcedb5ef70139f]*/
Martin v. Löwis99866332002-03-01 10:27:01 +00001689{
Victor Stinner62bb3942012-08-06 00:46:05 +02001690 char typecode;
Martin v. Löwis99866332002-03-01 10:27:01 +00001691
Victor Stinner62bb3942012-08-06 00:46:05 +02001692 typecode = self->ob_descr->typecode;
Gregory P. Smith9504b132012-12-10 20:20:20 -08001693 if (typecode != 'u') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001694 PyErr_SetString(PyExc_ValueError,
1695 "fromunicode() may only be called on "
1696 "unicode type arrays");
1697 return NULL;
1698 }
Brett Cannon1eb32c22014-10-10 16:26:45 -04001699 if (ustr_length > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001700 Py_ssize_t old_size = Py_SIZE(self);
Brett Cannon1eb32c22014-10-10 16:26:45 -04001701 if (array_resize(self, old_size + ustr_length) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001702 return NULL;
Victor Stinner62bb3942012-08-06 00:46:05 +02001703 memcpy(self->ob_item + old_size * sizeof(Py_UNICODE),
Brett Cannon1eb32c22014-10-10 16:26:45 -04001704 ustr, ustr_length * sizeof(Py_UNICODE));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001705 }
Martin v. Löwis99866332002-03-01 10:27:01 +00001706
Brett Cannon1eb32c22014-10-10 16:26:45 -04001707 Py_RETURN_NONE;
Martin v. Löwis99866332002-03-01 10:27:01 +00001708}
1709
Brett Cannon1eb32c22014-10-10 16:26:45 -04001710/*[clinic input]
1711array.array.tounicode
Martin v. Löwis99866332002-03-01 10:27:01 +00001712
Brett Cannon1eb32c22014-10-10 16:26:45 -04001713Extends this array with data from the unicode string ustr.
1714
1715Convert the array to a unicode string. The array must be a unicode type array;
1716otherwise a ValueError is raised. Use array.tobytes().decode() to obtain a
1717unicode string from an array of some other type.
1718[clinic start generated code]*/
Martin v. Löwis99866332002-03-01 10:27:01 +00001719
1720static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001721array_array_tounicode_impl(arrayobject *self)
1722/*[clinic end generated code: output=08e442378336e1ef input=127242eebe70b66d]*/
Martin v. Löwis99866332002-03-01 10:27:01 +00001723{
Victor Stinner62bb3942012-08-06 00:46:05 +02001724 char typecode;
1725 typecode = self->ob_descr->typecode;
Gregory P. Smith9504b132012-12-10 20:20:20 -08001726 if (typecode != 'u') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001727 PyErr_SetString(PyExc_ValueError,
1728 "tounicode() may only be called on unicode type arrays");
1729 return NULL;
1730 }
Victor Stinner62bb3942012-08-06 00:46:05 +02001731 return PyUnicode_FromUnicode((Py_UNICODE *) self->ob_item, Py_SIZE(self));
Martin v. Löwis99866332002-03-01 10:27:01 +00001732}
1733
Brett Cannon1eb32c22014-10-10 16:26:45 -04001734/*[clinic input]
1735array.array.__sizeof__
Martin v. Löwis99866332002-03-01 10:27:01 +00001736
Brett Cannon1eb32c22014-10-10 16:26:45 -04001737Size of the array in memory, in bytes.
1738[clinic start generated code]*/
Martin v. Löwis99866332002-03-01 10:27:01 +00001739
Meador Inge03b4d502012-08-10 22:35:45 -05001740static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001741array_array___sizeof___impl(arrayobject *self)
1742/*[clinic end generated code: output=d8e1c61ebbe3eaed input=805586565bf2b3c6]*/
Meador Inge03b4d502012-08-10 22:35:45 -05001743{
1744 Py_ssize_t res;
1745 res = sizeof(arrayobject) + self->allocated * self->ob_descr->itemsize;
1746 return PyLong_FromSsize_t(res);
1747}
1748
Martin v. Löwis99866332002-03-01 10:27:01 +00001749
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001750/*********************** Pickling support ************************/
1751
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001752static const struct mformatdescr {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001753 size_t size;
1754 int is_signed;
1755 int is_big_endian;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001756} mformat_descriptors[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001757 {1, 0, 0}, /* 0: UNSIGNED_INT8 */
1758 {1, 1, 0}, /* 1: SIGNED_INT8 */
1759 {2, 0, 0}, /* 2: UNSIGNED_INT16_LE */
1760 {2, 0, 1}, /* 3: UNSIGNED_INT16_BE */
1761 {2, 1, 0}, /* 4: SIGNED_INT16_LE */
1762 {2, 1, 1}, /* 5: SIGNED_INT16_BE */
1763 {4, 0, 0}, /* 6: UNSIGNED_INT32_LE */
1764 {4, 0, 1}, /* 7: UNSIGNED_INT32_BE */
1765 {4, 1, 0}, /* 8: SIGNED_INT32_LE */
1766 {4, 1, 1}, /* 9: SIGNED_INT32_BE */
1767 {8, 0, 0}, /* 10: UNSIGNED_INT64_LE */
1768 {8, 0, 1}, /* 11: UNSIGNED_INT64_BE */
1769 {8, 1, 0}, /* 12: SIGNED_INT64_LE */
1770 {8, 1, 1}, /* 13: SIGNED_INT64_BE */
1771 {4, 0, 0}, /* 14: IEEE_754_FLOAT_LE */
1772 {4, 0, 1}, /* 15: IEEE_754_FLOAT_BE */
1773 {8, 0, 0}, /* 16: IEEE_754_DOUBLE_LE */
1774 {8, 0, 1}, /* 17: IEEE_754_DOUBLE_BE */
1775 {4, 0, 0}, /* 18: UTF16_LE */
1776 {4, 0, 1}, /* 19: UTF16_BE */
1777 {8, 0, 0}, /* 20: UTF32_LE */
1778 {8, 0, 1} /* 21: UTF32_BE */
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001779};
1780
1781
1782/*
1783 * Internal: This function is used to find the machine format of a given
1784 * array type code. This returns UNKNOWN_FORMAT when the machine format cannot
1785 * be found.
1786 */
1787static enum machine_format_code
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02001788typecode_to_mformat_code(char typecode)
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001789{
Christian Heimes743e0cd2012-10-17 23:52:17 +02001790 const int is_big_endian = PY_BIG_ENDIAN;
1791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001792 size_t intsize;
1793 int is_signed;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001794
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001795 switch (typecode) {
1796 case 'b':
1797 return SIGNED_INT8;
1798 case 'B':
1799 return UNSIGNED_INT8;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001800
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001801 case 'u':
Victor Stinner62bb3942012-08-06 00:46:05 +02001802 if (sizeof(Py_UNICODE) == 2) {
1803 return UTF16_LE + is_big_endian;
1804 }
1805 if (sizeof(Py_UNICODE) == 4) {
1806 return UTF32_LE + is_big_endian;
1807 }
1808 return UNKNOWN_FORMAT;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001809
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001810 case 'f':
1811 if (sizeof(float) == 4) {
1812 const float y = 16711938.0;
1813 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1814 return IEEE_754_FLOAT_BE;
1815 if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1816 return IEEE_754_FLOAT_LE;
1817 }
1818 return UNKNOWN_FORMAT;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001819
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001820 case 'd':
1821 if (sizeof(double) == 8) {
1822 const double x = 9006104071832581.0;
1823 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1824 return IEEE_754_DOUBLE_BE;
1825 if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1826 return IEEE_754_DOUBLE_LE;
1827 }
1828 return UNKNOWN_FORMAT;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001829
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001830 /* Integers */
1831 case 'h':
1832 intsize = sizeof(short);
1833 is_signed = 1;
1834 break;
1835 case 'H':
1836 intsize = sizeof(short);
1837 is_signed = 0;
1838 break;
1839 case 'i':
1840 intsize = sizeof(int);
1841 is_signed = 1;
1842 break;
1843 case 'I':
1844 intsize = sizeof(int);
1845 is_signed = 0;
1846 break;
1847 case 'l':
1848 intsize = sizeof(long);
1849 is_signed = 1;
1850 break;
1851 case 'L':
1852 intsize = sizeof(long);
1853 is_signed = 0;
1854 break;
Meador Inge1c9f0c92011-09-20 19:55:51 -05001855#if HAVE_LONG_LONG
1856 case 'q':
1857 intsize = sizeof(PY_LONG_LONG);
1858 is_signed = 1;
1859 break;
1860 case 'Q':
1861 intsize = sizeof(PY_LONG_LONG);
1862 is_signed = 0;
1863 break;
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02001864#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001865 default:
1866 return UNKNOWN_FORMAT;
1867 }
1868 switch (intsize) {
1869 case 2:
1870 return UNSIGNED_INT16_LE + is_big_endian + (2 * is_signed);
1871 case 4:
1872 return UNSIGNED_INT32_LE + is_big_endian + (2 * is_signed);
1873 case 8:
1874 return UNSIGNED_INT64_LE + is_big_endian + (2 * is_signed);
1875 default:
1876 return UNKNOWN_FORMAT;
1877 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001878}
1879
1880/* Forward declaration. */
1881static PyObject *array_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1882
1883/*
1884 * Internal: This function wraps the array constructor--i.e., array_new()--to
1885 * allow the creation of array objects from C code without having to deal
1886 * directly the tuple argument of array_new(). The typecode argument is a
1887 * Unicode character value, like 'i' or 'f' for example, representing an array
1888 * type code. The items argument is a bytes or a list object from which
1889 * contains the initial value of the array.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001890 *
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001891 * On success, this functions returns the array object created. Otherwise,
1892 * NULL is returned to indicate a failure.
1893 */
1894static PyObject *
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02001895make_array(PyTypeObject *arraytype, char typecode, PyObject *items)
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001896{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001897 PyObject *new_args;
1898 PyObject *array_obj;
1899 PyObject *typecode_obj;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001900
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001901 assert(arraytype != NULL);
1902 assert(items != NULL);
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001903
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02001904 typecode_obj = PyUnicode_FromOrdinal(typecode);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001905 if (typecode_obj == NULL)
1906 return NULL;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001907
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001908 new_args = PyTuple_New(2);
1909 if (new_args == NULL)
1910 return NULL;
1911 Py_INCREF(items);
1912 PyTuple_SET_ITEM(new_args, 0, typecode_obj);
1913 PyTuple_SET_ITEM(new_args, 1, items);
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001914
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001915 array_obj = array_new(arraytype, new_args, NULL);
1916 Py_DECREF(new_args);
1917 if (array_obj == NULL)
1918 return NULL;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001920 return array_obj;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001921}
1922
1923/*
1924 * This functions is a special constructor used when unpickling an array. It
1925 * provides a portable way to rebuild an array from its memory representation.
1926 */
Brett Cannon1eb32c22014-10-10 16:26:45 -04001927/*[clinic input]
1928array._array_reconstructor
1929
1930 arraytype: object(type="PyTypeObject *")
1931 typecode: int(types='str')
1932 mformat_code: int(type="enum machine_format_code")
1933 items: object
1934 /
1935
1936Internal. Used for pickling support.
1937[clinic start generated code]*/
1938
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001939static PyObject *
Larry Hastingsdfbeb162014-10-13 10:39:41 +01001940array__array_reconstructor_impl(PyModuleDef *module, PyTypeObject *arraytype, int typecode, enum machine_format_code mformat_code, PyObject *items)
1941/*[clinic end generated code: output=c51081ec91caf7e9 input=f72492708c0a1d50]*/
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001942{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001943 PyObject *converted_items;
1944 PyObject *result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001945 struct arraydescr *descr;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001947 if (!PyType_Check(arraytype)) {
1948 PyErr_Format(PyExc_TypeError,
1949 "first argument must a type object, not %.200s",
1950 Py_TYPE(arraytype)->tp_name);
1951 return NULL;
1952 }
1953 if (!PyType_IsSubtype(arraytype, &Arraytype)) {
1954 PyErr_Format(PyExc_TypeError,
1955 "%.200s is not a subtype of %.200s",
1956 arraytype->tp_name, Arraytype.tp_name);
1957 return NULL;
1958 }
1959 for (descr = descriptors; descr->typecode != '\0'; descr++) {
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02001960 if ((int)descr->typecode == typecode)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001961 break;
1962 }
1963 if (descr->typecode == '\0') {
1964 PyErr_SetString(PyExc_ValueError,
1965 "second argument must be a valid type code");
1966 return NULL;
1967 }
Larry Hastingsdfbeb162014-10-13 10:39:41 +01001968 if (mformat_code < MACHINE_FORMAT_CODE_MIN ||
1969 mformat_code > MACHINE_FORMAT_CODE_MAX) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001970 PyErr_SetString(PyExc_ValueError,
1971 "third argument must be a valid machine format code.");
1972 return NULL;
1973 }
1974 if (!PyBytes_Check(items)) {
1975 PyErr_Format(PyExc_TypeError,
1976 "fourth argument should be bytes, not %.200s",
1977 Py_TYPE(items)->tp_name);
1978 return NULL;
1979 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001981 /* Fast path: No decoding has to be done. */
Larry Hastingsdfbeb162014-10-13 10:39:41 +01001982 if (mformat_code == typecode_to_mformat_code((char)typecode) ||
1983 mformat_code == UNKNOWN_FORMAT) {
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02001984 return make_array(arraytype, (char)typecode, items);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001985 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001987 /* Slow path: Decode the byte string according to the given machine
1988 * format code. This occurs when the computer unpickling the array
1989 * object is architecturally different from the one that pickled the
1990 * array.
1991 */
Larry Hastingsdfbeb162014-10-13 10:39:41 +01001992 if (Py_SIZE(items) % mformat_descriptors[mformat_code].size != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001993 PyErr_SetString(PyExc_ValueError,
1994 "string length not a multiple of item size");
1995 return NULL;
1996 }
Larry Hastingsdfbeb162014-10-13 10:39:41 +01001997 switch (mformat_code) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001998 case IEEE_754_FLOAT_LE:
1999 case IEEE_754_FLOAT_BE: {
2000 int i;
Larry Hastingsdfbeb162014-10-13 10:39:41 +01002001 int le = (mformat_code == IEEE_754_FLOAT_LE) ? 1 : 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002002 Py_ssize_t itemcount = Py_SIZE(items) / 4;
2003 const unsigned char *memstr =
2004 (unsigned char *)PyBytes_AS_STRING(items);
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002005
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002006 converted_items = PyList_New(itemcount);
2007 if (converted_items == NULL)
2008 return NULL;
2009 for (i = 0; i < itemcount; i++) {
2010 PyObject *pyfloat = PyFloat_FromDouble(
2011 _PyFloat_Unpack4(&memstr[i * 4], le));
2012 if (pyfloat == NULL) {
2013 Py_DECREF(converted_items);
2014 return NULL;
2015 }
2016 PyList_SET_ITEM(converted_items, i, pyfloat);
2017 }
2018 break;
2019 }
2020 case IEEE_754_DOUBLE_LE:
2021 case IEEE_754_DOUBLE_BE: {
2022 int i;
Larry Hastingsdfbeb162014-10-13 10:39:41 +01002023 int le = (mformat_code == IEEE_754_DOUBLE_LE) ? 1 : 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002024 Py_ssize_t itemcount = Py_SIZE(items) / 8;
2025 const unsigned char *memstr =
2026 (unsigned char *)PyBytes_AS_STRING(items);
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002028 converted_items = PyList_New(itemcount);
2029 if (converted_items == NULL)
2030 return NULL;
2031 for (i = 0; i < itemcount; i++) {
2032 PyObject *pyfloat = PyFloat_FromDouble(
2033 _PyFloat_Unpack8(&memstr[i * 8], le));
2034 if (pyfloat == NULL) {
2035 Py_DECREF(converted_items);
2036 return NULL;
2037 }
2038 PyList_SET_ITEM(converted_items, i, pyfloat);
2039 }
2040 break;
2041 }
2042 case UTF16_LE:
2043 case UTF16_BE: {
Larry Hastingsdfbeb162014-10-13 10:39:41 +01002044 int byteorder = (mformat_code == UTF16_LE) ? -1 : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002045 converted_items = PyUnicode_DecodeUTF16(
2046 PyBytes_AS_STRING(items), Py_SIZE(items),
2047 "strict", &byteorder);
2048 if (converted_items == NULL)
2049 return NULL;
2050 break;
2051 }
2052 case UTF32_LE:
2053 case UTF32_BE: {
Larry Hastingsdfbeb162014-10-13 10:39:41 +01002054 int byteorder = (mformat_code == UTF32_LE) ? -1 : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002055 converted_items = PyUnicode_DecodeUTF32(
2056 PyBytes_AS_STRING(items), Py_SIZE(items),
2057 "strict", &byteorder);
2058 if (converted_items == NULL)
2059 return NULL;
2060 break;
2061 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002063 case UNSIGNED_INT8:
2064 case SIGNED_INT8:
2065 case UNSIGNED_INT16_LE:
2066 case UNSIGNED_INT16_BE:
2067 case SIGNED_INT16_LE:
2068 case SIGNED_INT16_BE:
2069 case UNSIGNED_INT32_LE:
2070 case UNSIGNED_INT32_BE:
2071 case SIGNED_INT32_LE:
2072 case SIGNED_INT32_BE:
2073 case UNSIGNED_INT64_LE:
2074 case UNSIGNED_INT64_BE:
2075 case SIGNED_INT64_LE:
2076 case SIGNED_INT64_BE: {
2077 int i;
2078 const struct mformatdescr mf_descr =
Larry Hastingsdfbeb162014-10-13 10:39:41 +01002079 mformat_descriptors[mformat_code];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002080 Py_ssize_t itemcount = Py_SIZE(items) / mf_descr.size;
2081 const unsigned char *memstr =
2082 (unsigned char *)PyBytes_AS_STRING(items);
2083 struct arraydescr *descr;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002084
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002085 /* If possible, try to pack array's items using a data type
2086 * that fits better. This may result in an array with narrower
2087 * or wider elements.
2088 *
2089 * For example, if a 32-bit machine pickles a L-code array of
2090 * unsigned longs, then the array will be unpickled by 64-bit
2091 * machine as an I-code array of unsigned ints.
2092 *
2093 * XXX: Is it possible to write a unit test for this?
2094 */
2095 for (descr = descriptors; descr->typecode != '\0'; descr++) {
2096 if (descr->is_integer_type &&
Victor Stinner706768c2014-08-16 01:03:39 +02002097 (size_t)descr->itemsize == mf_descr.size &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002098 descr->is_signed == mf_descr.is_signed)
2099 typecode = descr->typecode;
2100 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002101
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002102 converted_items = PyList_New(itemcount);
2103 if (converted_items == NULL)
2104 return NULL;
2105 for (i = 0; i < itemcount; i++) {
2106 PyObject *pylong;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002107
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002108 pylong = _PyLong_FromByteArray(
2109 &memstr[i * mf_descr.size],
2110 mf_descr.size,
2111 !mf_descr.is_big_endian,
2112 mf_descr.is_signed);
2113 if (pylong == NULL) {
2114 Py_DECREF(converted_items);
2115 return NULL;
2116 }
2117 PyList_SET_ITEM(converted_items, i, pylong);
2118 }
2119 break;
2120 }
2121 case UNKNOWN_FORMAT:
2122 /* Impossible, but needed to shut up GCC about the unhandled
2123 * enumeration value.
2124 */
2125 default:
2126 PyErr_BadArgument();
2127 return NULL;
2128 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002129
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02002130 result = make_array(arraytype, (char)typecode, converted_items);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002131 Py_DECREF(converted_items);
2132 return result;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002133}
2134
Brett Cannon1eb32c22014-10-10 16:26:45 -04002135/*[clinic input]
2136array.array.__reduce_ex__
2137
2138 value: object
2139 /
2140
2141Return state information for pickling.
2142[clinic start generated code]*/
2143
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002144static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04002145array_array___reduce_ex__(arrayobject *self, PyObject *value)
2146/*[clinic end generated code: output=051e0a6175d0eddb input=c36c3f85de7df6cd]*/
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002147{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002148 PyObject *dict;
2149 PyObject *result;
2150 PyObject *array_str;
Brett Cannon1eb32c22014-10-10 16:26:45 -04002151 int typecode = self->ob_descr->typecode;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002152 int mformat_code;
2153 static PyObject *array_reconstructor = NULL;
2154 long protocol;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002155 _Py_IDENTIFIER(_array_reconstructor);
2156 _Py_IDENTIFIER(__dict__);
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002157
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002158 if (array_reconstructor == NULL) {
2159 PyObject *array_module = PyImport_ImportModule("array");
2160 if (array_module == NULL)
2161 return NULL;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002162 array_reconstructor = _PyObject_GetAttrId(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002163 array_module,
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002164 &PyId__array_reconstructor);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002165 Py_DECREF(array_module);
2166 if (array_reconstructor == NULL)
2167 return NULL;
2168 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002169
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002170 if (!PyLong_Check(value)) {
2171 PyErr_SetString(PyExc_TypeError,
2172 "__reduce_ex__ argument should an integer");
2173 return NULL;
2174 }
2175 protocol = PyLong_AsLong(value);
2176 if (protocol == -1 && PyErr_Occurred())
2177 return NULL;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002178
Brett Cannon1eb32c22014-10-10 16:26:45 -04002179 dict = _PyObject_GetAttrId((PyObject *)self, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002180 if (dict == NULL) {
2181 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
2182 return NULL;
2183 PyErr_Clear();
2184 dict = Py_None;
2185 Py_INCREF(dict);
2186 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002188 mformat_code = typecode_to_mformat_code(typecode);
2189 if (mformat_code == UNKNOWN_FORMAT || protocol < 3) {
2190 /* Convert the array to a list if we got something weird
2191 * (e.g., non-IEEE floats), or we are pickling the array using
2192 * a Python 2.x compatible protocol.
2193 *
2194 * It is necessary to use a list representation for Python 2.x
2195 * compatible pickle protocol, since Python 2's str objects
2196 * are unpickled as unicode by Python 3. Thus it is impossible
2197 * to make arrays unpicklable by Python 3 by using their memory
2198 * representation, unless we resort to ugly hacks such as
2199 * coercing unicode objects to bytes in array_reconstructor.
2200 */
2201 PyObject *list;
Brett Cannon1eb32c22014-10-10 16:26:45 -04002202 list = array_array_tolist_impl(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002203 if (list == NULL) {
2204 Py_DECREF(dict);
2205 return NULL;
2206 }
2207 result = Py_BuildValue(
Brett Cannon1eb32c22014-10-10 16:26:45 -04002208 "O(CO)O", Py_TYPE(self), typecode, list, dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002209 Py_DECREF(list);
2210 Py_DECREF(dict);
2211 return result;
2212 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002213
Brett Cannon1eb32c22014-10-10 16:26:45 -04002214 array_str = array_array_tobytes_impl(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002215 if (array_str == NULL) {
2216 Py_DECREF(dict);
2217 return NULL;
2218 }
2219 result = Py_BuildValue(
Brett Cannon1eb32c22014-10-10 16:26:45 -04002220 "O(OCiN)O", array_reconstructor, Py_TYPE(self), typecode,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002221 mformat_code, array_str, dict);
2222 Py_DECREF(dict);
2223 return result;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002224}
2225
Martin v. Löwis99866332002-03-01 10:27:01 +00002226static PyObject *
2227array_get_typecode(arrayobject *a, void *closure)
2228{
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02002229 char typecode = a->ob_descr->typecode;
2230 return PyUnicode_FromOrdinal(typecode);
Martin v. Löwis99866332002-03-01 10:27:01 +00002231}
2232
2233static PyObject *
2234array_get_itemsize(arrayobject *a, void *closure)
2235{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002236 return PyLong_FromLong((long)a->ob_descr->itemsize);
Martin v. Löwis99866332002-03-01 10:27:01 +00002237}
2238
2239static PyGetSetDef array_getsets [] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002240 {"typecode", (getter) array_get_typecode, NULL,
2241 "the typecode character used to create the array"},
2242 {"itemsize", (getter) array_get_itemsize, NULL,
2243 "the size, in bytes, of one array item"},
2244 {NULL}
Martin v. Löwis99866332002-03-01 10:27:01 +00002245};
2246
Martin v. Löwis59683e82008-06-13 07:50:45 +00002247static PyMethodDef array_methods[] = {
Brett Cannon1eb32c22014-10-10 16:26:45 -04002248 ARRAY_ARRAY_APPEND_METHODDEF
2249 ARRAY_ARRAY_BUFFER_INFO_METHODDEF
2250 ARRAY_ARRAY_BYTESWAP_METHODDEF
2251 ARRAY_ARRAY___COPY___METHODDEF
2252 ARRAY_ARRAY_COUNT_METHODDEF
2253 ARRAY_ARRAY___DEEPCOPY___METHODDEF
2254 ARRAY_ARRAY_EXTEND_METHODDEF
2255 ARRAY_ARRAY_FROMFILE_METHODDEF
2256 ARRAY_ARRAY_FROMLIST_METHODDEF
2257 ARRAY_ARRAY_FROMSTRING_METHODDEF
2258 ARRAY_ARRAY_FROMBYTES_METHODDEF
2259 ARRAY_ARRAY_FROMUNICODE_METHODDEF
2260 ARRAY_ARRAY_INDEX_METHODDEF
2261 ARRAY_ARRAY_INSERT_METHODDEF
2262 ARRAY_ARRAY_POP_METHODDEF
2263 ARRAY_ARRAY___REDUCE_EX___METHODDEF
2264 ARRAY_ARRAY_REMOVE_METHODDEF
2265 ARRAY_ARRAY_REVERSE_METHODDEF
2266 ARRAY_ARRAY_TOFILE_METHODDEF
2267 ARRAY_ARRAY_TOLIST_METHODDEF
2268 ARRAY_ARRAY_TOSTRING_METHODDEF
2269 ARRAY_ARRAY_TOBYTES_METHODDEF
2270 ARRAY_ARRAY_TOUNICODE_METHODDEF
2271 ARRAY_ARRAY___SIZEOF___METHODDEF
2272 {NULL, NULL} /* sentinel */
Guido van Rossum778983b1993-02-19 15:55:02 +00002273};
2274
Roger E. Masse2919eaa1996-12-09 20:10:36 +00002275static PyObject *
Peter Schneider-Kamp9656abd2000-07-13 21:10:57 +00002276array_repr(arrayobject *a)
Guido van Rossum778983b1993-02-19 15:55:02 +00002277{
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02002278 char typecode;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002279 PyObject *s, *v = NULL;
2280 Py_ssize_t len;
Martin v. Löwis99866332002-03-01 10:27:01 +00002281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002282 len = Py_SIZE(a);
2283 typecode = a->ob_descr->typecode;
2284 if (len == 0) {
Amaury Forgeot d'Arc24aa26b2010-11-25 08:13:35 +00002285 return PyUnicode_FromFormat("array('%c')", (int)typecode);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002286 }
Gregory P. Smith9504b132012-12-10 20:20:20 -08002287 if (typecode == 'u') {
Brett Cannon1eb32c22014-10-10 16:26:45 -04002288 v = array_array_tounicode_impl(a);
Gregory P. Smith9504b132012-12-10 20:20:20 -08002289 } else {
Brett Cannon1eb32c22014-10-10 16:26:45 -04002290 v = array_array_tolist_impl(a);
Gregory P. Smith9504b132012-12-10 20:20:20 -08002291 }
Victor Stinner29ec5952013-02-26 00:27:38 +01002292 if (v == NULL)
2293 return NULL;
Raymond Hettinger88ba1e32003-04-23 17:27:00 +00002294
Amaury Forgeot d'Arc24aa26b2010-11-25 08:13:35 +00002295 s = PyUnicode_FromFormat("array('%c', %R)", (int)typecode, v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002296 Py_DECREF(v);
2297 return s;
Guido van Rossum778983b1993-02-19 15:55:02 +00002298}
2299
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002300static PyObject*
2301array_subscr(arrayobject* self, PyObject* item)
2302{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002303 if (PyIndex_Check(item)) {
2304 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
2305 if (i==-1 && PyErr_Occurred()) {
2306 return NULL;
2307 }
2308 if (i < 0)
2309 i += Py_SIZE(self);
2310 return array_item(self, i);
2311 }
2312 else if (PySlice_Check(item)) {
2313 Py_ssize_t start, stop, step, slicelength, cur, i;
2314 PyObject* result;
2315 arrayobject* ar;
2316 int itemsize = self->ob_descr->itemsize;
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002317
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002318 if (PySlice_GetIndicesEx(item, Py_SIZE(self),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002319 &start, &stop, &step, &slicelength) < 0) {
2320 return NULL;
2321 }
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002323 if (slicelength <= 0) {
2324 return newarrayobject(&Arraytype, 0, self->ob_descr);
2325 }
2326 else if (step == 1) {
2327 PyObject *result = newarrayobject(&Arraytype,
2328 slicelength, self->ob_descr);
2329 if (result == NULL)
2330 return NULL;
2331 memcpy(((arrayobject *)result)->ob_item,
2332 self->ob_item + start * itemsize,
2333 slicelength * itemsize);
2334 return result;
2335 }
2336 else {
2337 result = newarrayobject(&Arraytype, slicelength, self->ob_descr);
2338 if (!result) return NULL;
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002340 ar = (arrayobject*)result;
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002342 for (cur = start, i = 0; i < slicelength;
2343 cur += step, i++) {
2344 memcpy(ar->ob_item + i*itemsize,
2345 self->ob_item + cur*itemsize,
2346 itemsize);
2347 }
2348
2349 return result;
2350 }
2351 }
2352 else {
2353 PyErr_SetString(PyExc_TypeError,
2354 "array indices must be integers");
2355 return NULL;
2356 }
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002357}
2358
2359static int
2360array_ass_subscr(arrayobject* self, PyObject* item, PyObject* value)
2361{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002362 Py_ssize_t start, stop, step, slicelength, needed;
2363 arrayobject* other;
2364 int itemsize;
Thomas Woutersed03b412007-08-28 21:37:11 +00002365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002366 if (PyIndex_Check(item)) {
2367 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Alexandre Vassalotti47137252009-07-05 19:57:00 +00002368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002369 if (i == -1 && PyErr_Occurred())
2370 return -1;
2371 if (i < 0)
2372 i += Py_SIZE(self);
2373 if (i < 0 || i >= Py_SIZE(self)) {
2374 PyErr_SetString(PyExc_IndexError,
2375 "array assignment index out of range");
2376 return -1;
2377 }
2378 if (value == NULL) {
2379 /* Fall through to slice assignment */
2380 start = i;
2381 stop = i + 1;
2382 step = 1;
2383 slicelength = 1;
2384 }
2385 else
2386 return (*self->ob_descr->setitem)(self, i, value);
2387 }
2388 else if (PySlice_Check(item)) {
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002389 if (PySlice_GetIndicesEx(item,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002390 Py_SIZE(self), &start, &stop,
2391 &step, &slicelength) < 0) {
2392 return -1;
2393 }
2394 }
2395 else {
2396 PyErr_SetString(PyExc_TypeError,
2397 "array indices must be integer");
2398 return -1;
2399 }
2400 if (value == NULL) {
2401 other = NULL;
2402 needed = 0;
2403 }
2404 else if (array_Check(value)) {
2405 other = (arrayobject *)value;
2406 needed = Py_SIZE(other);
2407 if (self == other) {
2408 /* Special case "self[i:j] = self" -- copy self first */
2409 int ret;
2410 value = array_slice(other, 0, needed);
2411 if (value == NULL)
2412 return -1;
2413 ret = array_ass_subscr(self, item, value);
2414 Py_DECREF(value);
2415 return ret;
2416 }
2417 if (other->ob_descr != self->ob_descr) {
2418 PyErr_BadArgument();
2419 return -1;
2420 }
2421 }
2422 else {
2423 PyErr_Format(PyExc_TypeError,
2424 "can only assign array (not \"%.200s\") to array slice",
2425 Py_TYPE(value)->tp_name);
2426 return -1;
2427 }
2428 itemsize = self->ob_descr->itemsize;
2429 /* for 'a[2:1] = ...', the insertion point is 'start', not 'stop' */
2430 if ((step > 0 && stop < start) ||
2431 (step < 0 && stop > start))
2432 stop = start;
Alexandre Vassalotti47137252009-07-05 19:57:00 +00002433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002434 /* Issue #4509: If the array has exported buffers and the slice
2435 assignment would change the size of the array, fail early to make
2436 sure we don't modify it. */
2437 if ((needed == 0 || slicelength != needed) && self->ob_exports > 0) {
2438 PyErr_SetString(PyExc_BufferError,
2439 "cannot resize an array that is exporting buffers");
2440 return -1;
2441 }
Mark Dickinsonbc099642010-01-29 17:27:24 +00002442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002443 if (step == 1) {
2444 if (slicelength > needed) {
2445 memmove(self->ob_item + (start + needed) * itemsize,
2446 self->ob_item + stop * itemsize,
2447 (Py_SIZE(self) - stop) * itemsize);
2448 if (array_resize(self, Py_SIZE(self) +
2449 needed - slicelength) < 0)
2450 return -1;
2451 }
2452 else if (slicelength < needed) {
2453 if (array_resize(self, Py_SIZE(self) +
2454 needed - slicelength) < 0)
2455 return -1;
2456 memmove(self->ob_item + (start + needed) * itemsize,
2457 self->ob_item + stop * itemsize,
2458 (Py_SIZE(self) - start - needed) * itemsize);
2459 }
2460 if (needed > 0)
2461 memcpy(self->ob_item + start * itemsize,
2462 other->ob_item, needed * itemsize);
2463 return 0;
2464 }
2465 else if (needed == 0) {
2466 /* Delete slice */
2467 size_t cur;
2468 Py_ssize_t i;
Thomas Woutersed03b412007-08-28 21:37:11 +00002469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002470 if (step < 0) {
2471 stop = start + 1;
2472 start = stop + step * (slicelength - 1) - 1;
2473 step = -step;
2474 }
2475 for (cur = start, i = 0; i < slicelength;
2476 cur += step, i++) {
2477 Py_ssize_t lim = step - 1;
Thomas Woutersed03b412007-08-28 21:37:11 +00002478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002479 if (cur + step >= (size_t)Py_SIZE(self))
2480 lim = Py_SIZE(self) - cur - 1;
2481 memmove(self->ob_item + (cur - i) * itemsize,
2482 self->ob_item + (cur + 1) * itemsize,
2483 lim * itemsize);
2484 }
Mark Dickinsonc7d93b72011-09-25 15:34:32 +01002485 cur = start + (size_t)slicelength * step;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002486 if (cur < (size_t)Py_SIZE(self)) {
2487 memmove(self->ob_item + (cur-slicelength) * itemsize,
2488 self->ob_item + cur * itemsize,
2489 (Py_SIZE(self) - cur) * itemsize);
2490 }
2491 if (array_resize(self, Py_SIZE(self) - slicelength) < 0)
2492 return -1;
2493 return 0;
2494 }
2495 else {
2496 Py_ssize_t cur, i;
2497
2498 if (needed != slicelength) {
2499 PyErr_Format(PyExc_ValueError,
2500 "attempt to assign array of size %zd "
2501 "to extended slice of size %zd",
2502 needed, slicelength);
2503 return -1;
2504 }
2505 for (cur = start, i = 0; i < slicelength;
2506 cur += step, i++) {
2507 memcpy(self->ob_item + cur * itemsize,
2508 other->ob_item + i * itemsize,
2509 itemsize);
2510 }
2511 return 0;
2512 }
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002513}
2514
2515static PyMappingMethods array_as_mapping = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002516 (lenfunc)array_length,
2517 (binaryfunc)array_subscr,
2518 (objobjargproc)array_ass_subscr
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002519};
2520
Guido van Rossumd8faa362007-04-27 19:54:29 +00002521static const void *emptybuf = "";
2522
Travis E. Oliphantb99f7622007-08-18 11:21:56 +00002523
2524static int
Travis E. Oliphant8ae62b62007-09-23 02:00:13 +00002525array_buffer_getbuf(arrayobject *self, Py_buffer *view, int flags)
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00002526{
Stefan Krah650c1e82015-02-03 21:43:23 +01002527 if (view == NULL) {
2528 PyErr_SetString(PyExc_BufferError,
2529 "array_buffer_getbuf: view==NULL argument is obsolete");
2530 return -1;
2531 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +00002532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002533 view->buf = (void *)self->ob_item;
2534 view->obj = (PyObject*)self;
2535 Py_INCREF(self);
2536 if (view->buf == NULL)
2537 view->buf = (void *)emptybuf;
2538 view->len = (Py_SIZE(self)) * self->ob_descr->itemsize;
2539 view->readonly = 0;
2540 view->ndim = 1;
2541 view->itemsize = self->ob_descr->itemsize;
2542 view->suboffsets = NULL;
2543 view->shape = NULL;
2544 if ((flags & PyBUF_ND)==PyBUF_ND) {
2545 view->shape = &((Py_SIZE(self)));
2546 }
2547 view->strides = NULL;
2548 if ((flags & PyBUF_STRIDES)==PyBUF_STRIDES)
2549 view->strides = &(view->itemsize);
2550 view->format = NULL;
2551 view->internal = NULL;
Victor Stinner62bb3942012-08-06 00:46:05 +02002552 if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002553 view->format = self->ob_descr->formats;
Victor Stinner62bb3942012-08-06 00:46:05 +02002554#ifdef Py_UNICODE_WIDE
2555 if (self->ob_descr->typecode == 'u') {
2556 view->format = "w";
2557 }
2558#endif
2559 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +00002560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002561 self->ob_exports++;
2562 return 0;
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00002563}
2564
Travis E. Oliphantb99f7622007-08-18 11:21:56 +00002565static void
Travis E. Oliphant8ae62b62007-09-23 02:00:13 +00002566array_buffer_relbuf(arrayobject *self, Py_buffer *view)
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00002567{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002568 self->ob_exports--;
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00002569}
2570
Roger E. Masse2919eaa1996-12-09 20:10:36 +00002571static PySequenceMethods array_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002572 (lenfunc)array_length, /*sq_length*/
2573 (binaryfunc)array_concat, /*sq_concat*/
2574 (ssizeargfunc)array_repeat, /*sq_repeat*/
2575 (ssizeargfunc)array_item, /*sq_item*/
2576 0, /*sq_slice*/
2577 (ssizeobjargproc)array_ass_item, /*sq_ass_item*/
2578 0, /*sq_ass_slice*/
2579 (objobjproc)array_contains, /*sq_contains*/
2580 (binaryfunc)array_inplace_concat, /*sq_inplace_concat*/
2581 (ssizeargfunc)array_inplace_repeat /*sq_inplace_repeat*/
Guido van Rossum778983b1993-02-19 15:55:02 +00002582};
2583
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00002584static PyBufferProcs array_as_buffer = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002585 (getbufferproc)array_buffer_getbuf,
2586 (releasebufferproc)array_buffer_relbuf
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00002587};
2588
Roger E. Masse2919eaa1996-12-09 20:10:36 +00002589static PyObject *
Martin v. Löwis99866332002-03-01 10:27:01 +00002590array_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum778983b1993-02-19 15:55:02 +00002591{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002592 int c;
2593 PyObject *initial = NULL, *it = NULL;
2594 struct arraydescr *descr;
Martin v. Löwis99866332002-03-01 10:27:01 +00002595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002596 if (type == &Arraytype && !_PyArg_NoKeywords("array.array()", kwds))
2597 return NULL;
Martin v. Löwis99866332002-03-01 10:27:01 +00002598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002599 if (!PyArg_ParseTuple(args, "C|O:array", &c, &initial))
2600 return NULL;
Raymond Hettinger84fc9aa2003-04-24 10:41:55 +00002601
Alexandre Vassalotti9730e332013-11-29 20:47:15 -08002602 if (initial && c != 'u') {
2603 if (PyUnicode_Check(initial)) {
2604 PyErr_Format(PyExc_TypeError, "cannot use a str to initialize "
2605 "an array with typecode '%c'", c);
2606 return NULL;
2607 }
2608 else if (array_Check(initial) &&
2609 ((arrayobject*)initial)->ob_descr->typecode == 'u') {
2610 PyErr_Format(PyExc_TypeError, "cannot use a unicode array to "
2611 "initialize an array with typecode '%c'", c);
2612 return NULL;
2613 }
2614 }
2615
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002616 if (!(initial == NULL || PyList_Check(initial)
2617 || PyByteArray_Check(initial)
2618 || PyBytes_Check(initial)
2619 || PyTuple_Check(initial)
Alexander Belopolskyef4a03f2011-01-11 21:44:00 +00002620 || ((c=='u') && PyUnicode_Check(initial))
2621 || (array_Check(initial)
2622 && c == ((arrayobject*)initial)->ob_descr->typecode))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002623 it = PyObject_GetIter(initial);
2624 if (it == NULL)
2625 return NULL;
2626 /* We set initial to NULL so that the subsequent code
2627 will create an empty array of the appropriate type
2628 and afterwards we can use array_iter_extend to populate
2629 the array.
2630 */
2631 initial = NULL;
2632 }
2633 for (descr = descriptors; descr->typecode != '\0'; descr++) {
2634 if (descr->typecode == c) {
2635 PyObject *a;
2636 Py_ssize_t len;
Martin v. Löwis99866332002-03-01 10:27:01 +00002637
Alexander Belopolskyef4a03f2011-01-11 21:44:00 +00002638 if (initial == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002639 len = 0;
Alexander Belopolskyef4a03f2011-01-11 21:44:00 +00002640 else if (PyList_Check(initial))
2641 len = PyList_GET_SIZE(initial);
2642 else if (PyTuple_Check(initial) || array_Check(initial))
2643 len = Py_SIZE(initial);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002644 else
Alexander Belopolskyef4a03f2011-01-11 21:44:00 +00002645 len = 0;
Martin v. Löwis99866332002-03-01 10:27:01 +00002646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002647 a = newarrayobject(type, len, descr);
2648 if (a == NULL)
2649 return NULL;
2650
Alexander Belopolskyef4a03f2011-01-11 21:44:00 +00002651 if (len > 0 && !array_Check(initial)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002652 Py_ssize_t i;
2653 for (i = 0; i < len; i++) {
2654 PyObject *v =
2655 PySequence_GetItem(initial, i);
2656 if (v == NULL) {
2657 Py_DECREF(a);
2658 return NULL;
2659 }
2660 if (setarrayitem(a, i, v) != 0) {
2661 Py_DECREF(v);
2662 Py_DECREF(a);
2663 return NULL;
2664 }
2665 Py_DECREF(v);
2666 }
2667 }
2668 else if (initial != NULL && (PyByteArray_Check(initial) ||
2669 PyBytes_Check(initial))) {
Serhiy Storchaka04e6dba2015-04-04 17:06:55 +03002670 PyObject *v;
Brett Cannon1eb32c22014-10-10 16:26:45 -04002671 v = array_array_frombytes((arrayobject *)a,
Serhiy Storchaka04e6dba2015-04-04 17:06:55 +03002672 initial);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002673 if (v == NULL) {
2674 Py_DECREF(a);
2675 return NULL;
2676 }
2677 Py_DECREF(v);
2678 }
2679 else if (initial != NULL && PyUnicode_Check(initial)) {
Victor Stinner62bb3942012-08-06 00:46:05 +02002680 Py_UNICODE *ustr;
Victor Stinner1fbcaef2011-09-30 01:54:04 +02002681 Py_ssize_t n;
Victor Stinner62bb3942012-08-06 00:46:05 +02002682
2683 ustr = PyUnicode_AsUnicode(initial);
2684 if (ustr == NULL) {
2685 PyErr_NoMemory();
Victor Stinner1fbcaef2011-09-30 01:54:04 +02002686 Py_DECREF(a);
2687 return NULL;
2688 }
Victor Stinner62bb3942012-08-06 00:46:05 +02002689
2690 n = PyUnicode_GET_DATA_SIZE(initial);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002691 if (n > 0) {
2692 arrayobject *self = (arrayobject *)a;
Victor Stinner62bb3942012-08-06 00:46:05 +02002693 char *item = self->ob_item;
2694 item = (char *)PyMem_Realloc(item, n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002695 if (item == NULL) {
2696 PyErr_NoMemory();
2697 Py_DECREF(a);
2698 return NULL;
2699 }
Victor Stinner62bb3942012-08-06 00:46:05 +02002700 self->ob_item = item;
2701 Py_SIZE(self) = n / sizeof(Py_UNICODE);
2702 memcpy(item, ustr, n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002703 self->allocated = Py_SIZE(self);
2704 }
2705 }
Benjamin Peterson682124c2014-10-10 20:58:30 -04002706 else if (initial != NULL && array_Check(initial) && len > 0) {
Alexander Belopolskyef4a03f2011-01-11 21:44:00 +00002707 arrayobject *self = (arrayobject *)a;
2708 arrayobject *other = (arrayobject *)initial;
2709 memcpy(self->ob_item, other->ob_item, len * other->ob_descr->itemsize);
2710 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002711 if (it != NULL) {
2712 if (array_iter_extend((arrayobject *)a, it) == -1) {
2713 Py_DECREF(it);
2714 Py_DECREF(a);
2715 return NULL;
2716 }
2717 Py_DECREF(it);
2718 }
2719 return a;
2720 }
2721 }
2722 PyErr_SetString(PyExc_ValueError,
Meador Inge1c9f0c92011-09-20 19:55:51 -05002723#ifdef HAVE_LONG_LONG
2724 "bad typecode (must be b, B, u, h, H, i, I, l, L, q, Q, f or d)");
2725#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002726 "bad typecode (must be b, B, u, h, H, i, I, l, L, f or d)");
Meador Inge1c9f0c92011-09-20 19:55:51 -05002727#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002728 return NULL;
Guido van Rossum778983b1993-02-19 15:55:02 +00002729}
2730
Guido van Rossum778983b1993-02-19 15:55:02 +00002731
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002732PyDoc_STRVAR(module_doc,
Martin v. Löwis99866332002-03-01 10:27:01 +00002733"This module defines an object type which can efficiently represent\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002734an array of basic values: characters, integers, floating point\n\
2735numbers. Arrays are sequence types and behave very much like lists,\n\
Alexandre Vassalotti9730e332013-11-29 20:47:15 -08002736except that the type of objects stored in them is constrained.\n");
2737
2738PyDoc_STRVAR(arraytype_doc,
2739"array(typecode [, initializer]) -> array\n\
2740\n\
2741Return a new array whose items are restricted by typecode, and\n\
2742initialized from the optional initializer value, which must be a list,\n\
2743string or iterable over elements of the appropriate type.\n\
2744\n\
2745Arrays represent basic values and behave very much like lists, except\n\
2746the type of objects stored in them is constrained. The type is specified\n\
2747at object creation time by using a type code, which is a single character.\n\
2748The following type codes are defined:\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002749\n\
2750 Type code C Type Minimum size in bytes \n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002751 'b' signed integer 1 \n\
2752 'B' unsigned integer 1 \n\
Victor Stinner62bb3942012-08-06 00:46:05 +02002753 'u' Unicode character 2 (see note) \n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002754 'h' signed integer 2 \n\
2755 'H' unsigned integer 2 \n\
2756 'i' signed integer 2 \n\
2757 'I' unsigned integer 2 \n\
2758 'l' signed integer 4 \n\
2759 'L' unsigned integer 4 \n\
Meador Inge1c9f0c92011-09-20 19:55:51 -05002760 'q' signed integer 8 (see note) \n\
2761 'Q' unsigned integer 8 (see note) \n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002762 'f' floating point 4 \n\
2763 'd' floating point 8 \n\
2764\n\
Victor Stinner62bb3942012-08-06 00:46:05 +02002765NOTE: The 'u' typecode corresponds to Python's unicode character. On \n\
2766narrow builds this is 2-bytes on wide builds this is 4-bytes.\n\
2767\n\
Meador Inge1c9f0c92011-09-20 19:55:51 -05002768NOTE: The 'q' and 'Q' type codes are only available if the platform \n\
2769C compiler used to build Python supports 'long long', or, on Windows, \n\
2770'__int64'.\n\
2771\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002772Methods:\n\
2773\n\
2774append() -- append a new item to the end of the array\n\
2775buffer_info() -- return information giving the current memory info\n\
2776byteswap() -- byteswap all the items of the array\n\
Mark Dickinson934896d2009-02-21 20:59:32 +00002777count() -- return number of occurrences of an object\n\
Raymond Hettinger49f9bd12004-03-14 05:43:59 +00002778extend() -- extend array by appending multiple elements from an iterable\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002779fromfile() -- read items from a file object\n\
2780fromlist() -- append items from the list\n\
Florent Xiclunac45fb252011-10-24 13:14:55 +02002781frombytes() -- append items from the string\n\
Mark Dickinson934896d2009-02-21 20:59:32 +00002782index() -- return index of first occurrence of an object\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002783insert() -- insert a new item into the array at a provided position\n\
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00002784pop() -- remove and return item (default last)\n\
Mark Dickinson934896d2009-02-21 20:59:32 +00002785remove() -- remove first occurrence of an object\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002786reverse() -- reverse the order of the items in the array\n\
2787tofile() -- write all items to a file object\n\
2788tolist() -- return the array converted to an ordinary list\n\
Florent Xiclunac45fb252011-10-24 13:14:55 +02002789tobytes() -- return the array converted to a string\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002790\n\
Martin v. Löwis99866332002-03-01 10:27:01 +00002791Attributes:\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002792\n\
2793typecode -- the typecode character used to create the array\n\
2794itemsize -- the length in bytes of one array item\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002795");
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002796
Raymond Hettinger625812f2003-01-07 01:58:52 +00002797static PyObject *array_iter(arrayobject *ao);
2798
Tim Peters0c322792002-07-17 16:49:03 +00002799static PyTypeObject Arraytype = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002800 PyVarObject_HEAD_INIT(NULL, 0)
2801 "array.array",
2802 sizeof(arrayobject),
2803 0,
2804 (destructor)array_dealloc, /* tp_dealloc */
2805 0, /* tp_print */
2806 0, /* tp_getattr */
2807 0, /* tp_setattr */
2808 0, /* tp_reserved */
2809 (reprfunc)array_repr, /* tp_repr */
2810 0, /* tp_as_number*/
2811 &array_as_sequence, /* tp_as_sequence*/
2812 &array_as_mapping, /* tp_as_mapping*/
2813 0, /* tp_hash */
2814 0, /* tp_call */
2815 0, /* tp_str */
2816 PyObject_GenericGetAttr, /* tp_getattro */
2817 0, /* tp_setattro */
2818 &array_as_buffer, /* tp_as_buffer*/
2819 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
2820 arraytype_doc, /* tp_doc */
2821 0, /* tp_traverse */
2822 0, /* tp_clear */
2823 array_richcompare, /* tp_richcompare */
2824 offsetof(arrayobject, weakreflist), /* tp_weaklistoffset */
2825 (getiterfunc)array_iter, /* tp_iter */
2826 0, /* tp_iternext */
2827 array_methods, /* tp_methods */
2828 0, /* tp_members */
2829 array_getsets, /* tp_getset */
2830 0, /* tp_base */
2831 0, /* tp_dict */
2832 0, /* tp_descr_get */
2833 0, /* tp_descr_set */
2834 0, /* tp_dictoffset */
2835 0, /* tp_init */
2836 PyType_GenericAlloc, /* tp_alloc */
2837 array_new, /* tp_new */
2838 PyObject_Del, /* tp_free */
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002839};
2840
Raymond Hettinger625812f2003-01-07 01:58:52 +00002841
2842/*********************** Array Iterator **************************/
2843
Brett Cannon1eb32c22014-10-10 16:26:45 -04002844/*[clinic input]
2845class array.arrayiterator "arrayiterobject *" "&PyArrayIter_Type"
2846[clinic start generated code]*/
2847/*[clinic end generated code: output=da39a3ee5e6b4b0d input=5aefd2d74d8c8e30]*/
Raymond Hettinger625812f2003-01-07 01:58:52 +00002848
2849static PyObject *
2850array_iter(arrayobject *ao)
2851{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002852 arrayiterobject *it;
Raymond Hettinger625812f2003-01-07 01:58:52 +00002853
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002854 if (!array_Check(ao)) {
2855 PyErr_BadInternalCall();
2856 return NULL;
2857 }
Raymond Hettinger625812f2003-01-07 01:58:52 +00002858
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002859 it = PyObject_GC_New(arrayiterobject, &PyArrayIter_Type);
2860 if (it == NULL)
2861 return NULL;
Raymond Hettinger625812f2003-01-07 01:58:52 +00002862
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002863 Py_INCREF(ao);
2864 it->ao = ao;
2865 it->index = 0;
2866 it->getitem = ao->ob_descr->getitem;
2867 PyObject_GC_Track(it);
2868 return (PyObject *)it;
Raymond Hettinger625812f2003-01-07 01:58:52 +00002869}
2870
2871static PyObject *
Raymond Hettinger625812f2003-01-07 01:58:52 +00002872arrayiter_next(arrayiterobject *it)
2873{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002874 assert(PyArrayIter_Check(it));
2875 if (it->index < Py_SIZE(it->ao))
2876 return (*it->getitem)(it->ao, it->index++);
2877 return NULL;
Raymond Hettinger625812f2003-01-07 01:58:52 +00002878}
2879
2880static void
2881arrayiter_dealloc(arrayiterobject *it)
2882{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002883 PyObject_GC_UnTrack(it);
2884 Py_XDECREF(it->ao);
2885 PyObject_GC_Del(it);
Raymond Hettinger625812f2003-01-07 01:58:52 +00002886}
2887
2888static int
2889arrayiter_traverse(arrayiterobject *it, visitproc visit, void *arg)
2890{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002891 Py_VISIT(it->ao);
2892 return 0;
Raymond Hettinger625812f2003-01-07 01:58:52 +00002893}
2894
Brett Cannon1eb32c22014-10-10 16:26:45 -04002895/*[clinic input]
2896array.arrayiterator.__reduce__
2897
2898Return state information for pickling.
2899[clinic start generated code]*/
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002900
2901static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04002902array_arrayiterator___reduce___impl(arrayiterobject *self)
2903/*[clinic end generated code: output=7898a52e8e66e016 input=a062ea1e9951417a]*/
2904{
2905 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
2906 self->ao, self->index);
2907}
2908
2909/*[clinic input]
2910array.arrayiterator.__setstate__
2911
2912 state: object
2913 /
2914
2915Set state information for unpickling.
2916[clinic start generated code]*/
2917
2918static PyObject *
2919array_arrayiterator___setstate__(arrayiterobject *self, PyObject *state)
2920/*[clinic end generated code: output=397da9904e443cbe input=f47d5ceda19e787b]*/
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002921{
2922 Py_ssize_t index = PyLong_AsSsize_t(state);
2923 if (index == -1 && PyErr_Occurred())
2924 return NULL;
2925 if (index < 0)
2926 index = 0;
Brett Cannon1eb32c22014-10-10 16:26:45 -04002927 else if (index > Py_SIZE(self->ao))
2928 index = Py_SIZE(self->ao); /* iterator exhausted */
2929 self->index = index;
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002930 Py_RETURN_NONE;
2931}
2932
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002933static PyMethodDef arrayiter_methods[] = {
Brett Cannon1eb32c22014-10-10 16:26:45 -04002934 ARRAY_ARRAYITERATOR___REDUCE___METHODDEF
2935 ARRAY_ARRAYITERATOR___SETSTATE___METHODDEF
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002936 {NULL, NULL} /* sentinel */
2937};
2938
Raymond Hettinger625812f2003-01-07 01:58:52 +00002939static PyTypeObject PyArrayIter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002940 PyVarObject_HEAD_INIT(NULL, 0)
2941 "arrayiterator", /* tp_name */
2942 sizeof(arrayiterobject), /* tp_basicsize */
2943 0, /* tp_itemsize */
2944 /* methods */
2945 (destructor)arrayiter_dealloc, /* tp_dealloc */
2946 0, /* tp_print */
2947 0, /* tp_getattr */
2948 0, /* tp_setattr */
2949 0, /* tp_reserved */
2950 0, /* tp_repr */
2951 0, /* tp_as_number */
2952 0, /* tp_as_sequence */
2953 0, /* tp_as_mapping */
2954 0, /* tp_hash */
2955 0, /* tp_call */
2956 0, /* tp_str */
2957 PyObject_GenericGetAttr, /* tp_getattro */
2958 0, /* tp_setattro */
2959 0, /* tp_as_buffer */
2960 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2961 0, /* tp_doc */
2962 (traverseproc)arrayiter_traverse, /* tp_traverse */
2963 0, /* tp_clear */
2964 0, /* tp_richcompare */
2965 0, /* tp_weaklistoffset */
2966 PyObject_SelfIter, /* tp_iter */
2967 (iternextfunc)arrayiter_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002968 arrayiter_methods, /* tp_methods */
Raymond Hettinger625812f2003-01-07 01:58:52 +00002969};
2970
2971
2972/*********************** Install Module **************************/
2973
Martin v. Löwis99866332002-03-01 10:27:01 +00002974/* No functions in array module. */
2975static PyMethodDef a_methods[] = {
Brett Cannon1eb32c22014-10-10 16:26:45 -04002976 ARRAY__ARRAY_RECONSTRUCTOR_METHODDEF
Martin v. Löwis99866332002-03-01 10:27:01 +00002977 {NULL, NULL, 0, NULL} /* Sentinel */
2978};
2979
Martin v. Löwis1a214512008-06-11 05:26:20 +00002980static struct PyModuleDef arraymodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002981 PyModuleDef_HEAD_INIT,
2982 "array",
2983 module_doc,
2984 -1,
2985 a_methods,
2986 NULL,
2987 NULL,
2988 NULL,
2989 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002990};
2991
Martin v. Löwis99866332002-03-01 10:27:01 +00002992
Mark Hammondfe51c6d2002-08-02 02:27:13 +00002993PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002994PyInit_array(void)
Guido van Rossum778983b1993-02-19 15:55:02 +00002995{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002996 PyObject *m;
Georg Brandl4cb0de22011-09-28 21:49:49 +02002997 char buffer[Py_ARRAY_LENGTH(descriptors)], *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002998 PyObject *typecodes;
2999 Py_ssize_t size = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003000 struct arraydescr *descr;
Fred Drake0d40ba42000-02-04 20:33:49 +00003001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003002 if (PyType_Ready(&Arraytype) < 0)
3003 return NULL;
3004 Py_TYPE(&PyArrayIter_Type) = &PyType_Type;
3005 m = PyModule_Create(&arraymodule);
3006 if (m == NULL)
3007 return NULL;
Fred Drakef4e34842002-04-01 03:45:06 +00003008
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003009 Py_INCREF((PyObject *)&Arraytype);
3010 PyModule_AddObject(m, "ArrayType", (PyObject *)&Arraytype);
3011 Py_INCREF((PyObject *)&Arraytype);
3012 PyModule_AddObject(m, "array", (PyObject *)&Arraytype);
Travis E. Oliphantd5c0add2007-10-12 22:05:15 +00003013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003014 for (descr=descriptors; descr->typecode != '\0'; descr++) {
3015 size++;
3016 }
Travis E. Oliphantd5c0add2007-10-12 22:05:15 +00003017
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003018 p = buffer;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003019 for (descr = descriptors; descr->typecode != '\0'; descr++) {
3020 *p++ = (char)descr->typecode;
3021 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003022 typecodes = PyUnicode_DecodeASCII(buffer, p - buffer, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003023
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003024 PyModule_AddObject(m, "typecodes", typecodes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003025
3026 if (PyErr_Occurred()) {
3027 Py_DECREF(m);
3028 m = NULL;
3029 }
3030 return m;
Guido van Rossum778983b1993-02-19 15:55:02 +00003031}