blob: f73c5993658593e51ddab1f596f8c90bf8043e7a [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
Larry Hastingsdbfdc382015-05-04 06:59:46 -07001603 buffer: Py_buffer(accept={str, buffer})
Brett Cannon1eb32c22014-10-10 16:26:45 -04001604 /
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)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07001613/*[clinic end generated code: output=31c4baa779df84ce input=a3341a512e11d773]*/
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
Larry Hastings38337d12015-05-07 23:30:09 -07001676 ustr: Py_UNICODE(zeroes=True)
Brett Cannon1eb32c22014-10-10 16:26:45 -04001677 /
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 *
Larry Hastings89964c42015-04-14 18:07:59 -04001687array_array_fromunicode_impl(arrayobject *self, Py_UNICODE *ustr,
1688 Py_ssize_clean_t ustr_length)
Larry Hastings38337d12015-05-07 23:30:09 -07001689/*[clinic end generated code: output=ebb72fc16975e06d input=150f00566ffbca6e]*/
Martin v. Löwis99866332002-03-01 10:27:01 +00001690{
Victor Stinner62bb3942012-08-06 00:46:05 +02001691 char typecode;
Martin v. Löwis99866332002-03-01 10:27:01 +00001692
Victor Stinner62bb3942012-08-06 00:46:05 +02001693 typecode = self->ob_descr->typecode;
Gregory P. Smith9504b132012-12-10 20:20:20 -08001694 if (typecode != 'u') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001695 PyErr_SetString(PyExc_ValueError,
1696 "fromunicode() may only be called on "
1697 "unicode type arrays");
1698 return NULL;
1699 }
Brett Cannon1eb32c22014-10-10 16:26:45 -04001700 if (ustr_length > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001701 Py_ssize_t old_size = Py_SIZE(self);
Brett Cannon1eb32c22014-10-10 16:26:45 -04001702 if (array_resize(self, old_size + ustr_length) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001703 return NULL;
Victor Stinner62bb3942012-08-06 00:46:05 +02001704 memcpy(self->ob_item + old_size * sizeof(Py_UNICODE),
Brett Cannon1eb32c22014-10-10 16:26:45 -04001705 ustr, ustr_length * sizeof(Py_UNICODE));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001706 }
Martin v. Löwis99866332002-03-01 10:27:01 +00001707
Brett Cannon1eb32c22014-10-10 16:26:45 -04001708 Py_RETURN_NONE;
Martin v. Löwis99866332002-03-01 10:27:01 +00001709}
1710
Brett Cannon1eb32c22014-10-10 16:26:45 -04001711/*[clinic input]
1712array.array.tounicode
Martin v. Löwis99866332002-03-01 10:27:01 +00001713
Brett Cannon1eb32c22014-10-10 16:26:45 -04001714Extends this array with data from the unicode string ustr.
1715
1716Convert the array to a unicode string. The array must be a unicode type array;
1717otherwise a ValueError is raised. Use array.tobytes().decode() to obtain a
1718unicode string from an array of some other type.
1719[clinic start generated code]*/
Martin v. Löwis99866332002-03-01 10:27:01 +00001720
1721static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001722array_array_tounicode_impl(arrayobject *self)
1723/*[clinic end generated code: output=08e442378336e1ef input=127242eebe70b66d]*/
Martin v. Löwis99866332002-03-01 10:27:01 +00001724{
Victor Stinner62bb3942012-08-06 00:46:05 +02001725 char typecode;
1726 typecode = self->ob_descr->typecode;
Gregory P. Smith9504b132012-12-10 20:20:20 -08001727 if (typecode != 'u') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001728 PyErr_SetString(PyExc_ValueError,
1729 "tounicode() may only be called on unicode type arrays");
1730 return NULL;
1731 }
Victor Stinner62bb3942012-08-06 00:46:05 +02001732 return PyUnicode_FromUnicode((Py_UNICODE *) self->ob_item, Py_SIZE(self));
Martin v. Löwis99866332002-03-01 10:27:01 +00001733}
1734
Brett Cannon1eb32c22014-10-10 16:26:45 -04001735/*[clinic input]
1736array.array.__sizeof__
Martin v. Löwis99866332002-03-01 10:27:01 +00001737
Brett Cannon1eb32c22014-10-10 16:26:45 -04001738Size of the array in memory, in bytes.
1739[clinic start generated code]*/
Martin v. Löwis99866332002-03-01 10:27:01 +00001740
Meador Inge03b4d502012-08-10 22:35:45 -05001741static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001742array_array___sizeof___impl(arrayobject *self)
1743/*[clinic end generated code: output=d8e1c61ebbe3eaed input=805586565bf2b3c6]*/
Meador Inge03b4d502012-08-10 22:35:45 -05001744{
1745 Py_ssize_t res;
Serhiy Storchaka5c4064e2015-12-19 20:05:25 +02001746 res = _PyObject_SIZE(Py_TYPE(self)) + self->allocated * self->ob_descr->itemsize;
Meador Inge03b4d502012-08-10 22:35:45 -05001747 return PyLong_FromSsize_t(res);
1748}
1749
Martin v. Löwis99866332002-03-01 10:27:01 +00001750
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001751/*********************** Pickling support ************************/
1752
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001753static const struct mformatdescr {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001754 size_t size;
1755 int is_signed;
1756 int is_big_endian;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001757} mformat_descriptors[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001758 {1, 0, 0}, /* 0: UNSIGNED_INT8 */
1759 {1, 1, 0}, /* 1: SIGNED_INT8 */
1760 {2, 0, 0}, /* 2: UNSIGNED_INT16_LE */
1761 {2, 0, 1}, /* 3: UNSIGNED_INT16_BE */
1762 {2, 1, 0}, /* 4: SIGNED_INT16_LE */
1763 {2, 1, 1}, /* 5: SIGNED_INT16_BE */
1764 {4, 0, 0}, /* 6: UNSIGNED_INT32_LE */
1765 {4, 0, 1}, /* 7: UNSIGNED_INT32_BE */
1766 {4, 1, 0}, /* 8: SIGNED_INT32_LE */
1767 {4, 1, 1}, /* 9: SIGNED_INT32_BE */
1768 {8, 0, 0}, /* 10: UNSIGNED_INT64_LE */
1769 {8, 0, 1}, /* 11: UNSIGNED_INT64_BE */
1770 {8, 1, 0}, /* 12: SIGNED_INT64_LE */
1771 {8, 1, 1}, /* 13: SIGNED_INT64_BE */
1772 {4, 0, 0}, /* 14: IEEE_754_FLOAT_LE */
1773 {4, 0, 1}, /* 15: IEEE_754_FLOAT_BE */
1774 {8, 0, 0}, /* 16: IEEE_754_DOUBLE_LE */
1775 {8, 0, 1}, /* 17: IEEE_754_DOUBLE_BE */
1776 {4, 0, 0}, /* 18: UTF16_LE */
1777 {4, 0, 1}, /* 19: UTF16_BE */
1778 {8, 0, 0}, /* 20: UTF32_LE */
1779 {8, 0, 1} /* 21: UTF32_BE */
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001780};
1781
1782
1783/*
1784 * Internal: This function is used to find the machine format of a given
1785 * array type code. This returns UNKNOWN_FORMAT when the machine format cannot
1786 * be found.
1787 */
1788static enum machine_format_code
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02001789typecode_to_mformat_code(char typecode)
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001790{
Christian Heimes743e0cd2012-10-17 23:52:17 +02001791 const int is_big_endian = PY_BIG_ENDIAN;
1792
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001793 size_t intsize;
1794 int is_signed;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001796 switch (typecode) {
1797 case 'b':
1798 return SIGNED_INT8;
1799 case 'B':
1800 return UNSIGNED_INT8;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001801
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001802 case 'u':
Victor Stinner62bb3942012-08-06 00:46:05 +02001803 if (sizeof(Py_UNICODE) == 2) {
1804 return UTF16_LE + is_big_endian;
1805 }
1806 if (sizeof(Py_UNICODE) == 4) {
1807 return UTF32_LE + is_big_endian;
1808 }
1809 return UNKNOWN_FORMAT;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001811 case 'f':
1812 if (sizeof(float) == 4) {
1813 const float y = 16711938.0;
1814 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1815 return IEEE_754_FLOAT_BE;
1816 if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1817 return IEEE_754_FLOAT_LE;
1818 }
1819 return UNKNOWN_FORMAT;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001820
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001821 case 'd':
1822 if (sizeof(double) == 8) {
1823 const double x = 9006104071832581.0;
1824 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1825 return IEEE_754_DOUBLE_BE;
1826 if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1827 return IEEE_754_DOUBLE_LE;
1828 }
1829 return UNKNOWN_FORMAT;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001830
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001831 /* Integers */
1832 case 'h':
1833 intsize = sizeof(short);
1834 is_signed = 1;
1835 break;
1836 case 'H':
1837 intsize = sizeof(short);
1838 is_signed = 0;
1839 break;
1840 case 'i':
1841 intsize = sizeof(int);
1842 is_signed = 1;
1843 break;
1844 case 'I':
1845 intsize = sizeof(int);
1846 is_signed = 0;
1847 break;
1848 case 'l':
1849 intsize = sizeof(long);
1850 is_signed = 1;
1851 break;
1852 case 'L':
1853 intsize = sizeof(long);
1854 is_signed = 0;
1855 break;
Meador Inge1c9f0c92011-09-20 19:55:51 -05001856#if HAVE_LONG_LONG
1857 case 'q':
1858 intsize = sizeof(PY_LONG_LONG);
1859 is_signed = 1;
1860 break;
1861 case 'Q':
1862 intsize = sizeof(PY_LONG_LONG);
1863 is_signed = 0;
1864 break;
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02001865#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001866 default:
1867 return UNKNOWN_FORMAT;
1868 }
1869 switch (intsize) {
1870 case 2:
1871 return UNSIGNED_INT16_LE + is_big_endian + (2 * is_signed);
1872 case 4:
1873 return UNSIGNED_INT32_LE + is_big_endian + (2 * is_signed);
1874 case 8:
1875 return UNSIGNED_INT64_LE + is_big_endian + (2 * is_signed);
1876 default:
1877 return UNKNOWN_FORMAT;
1878 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001879}
1880
1881/* Forward declaration. */
1882static PyObject *array_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1883
1884/*
1885 * Internal: This function wraps the array constructor--i.e., array_new()--to
1886 * allow the creation of array objects from C code without having to deal
1887 * directly the tuple argument of array_new(). The typecode argument is a
1888 * Unicode character value, like 'i' or 'f' for example, representing an array
1889 * type code. The items argument is a bytes or a list object from which
1890 * contains the initial value of the array.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001891 *
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001892 * On success, this functions returns the array object created. Otherwise,
1893 * NULL is returned to indicate a failure.
1894 */
1895static PyObject *
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02001896make_array(PyTypeObject *arraytype, char typecode, PyObject *items)
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001897{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001898 PyObject *new_args;
1899 PyObject *array_obj;
1900 PyObject *typecode_obj;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001901
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001902 assert(arraytype != NULL);
1903 assert(items != NULL);
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001904
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02001905 typecode_obj = PyUnicode_FromOrdinal(typecode);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001906 if (typecode_obj == NULL)
1907 return NULL;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001908
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001909 new_args = PyTuple_New(2);
1910 if (new_args == NULL)
1911 return NULL;
1912 Py_INCREF(items);
1913 PyTuple_SET_ITEM(new_args, 0, typecode_obj);
1914 PyTuple_SET_ITEM(new_args, 1, items);
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001916 array_obj = array_new(arraytype, new_args, NULL);
1917 Py_DECREF(new_args);
1918 if (array_obj == NULL)
1919 return NULL;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001921 return array_obj;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001922}
1923
1924/*
1925 * This functions is a special constructor used when unpickling an array. It
1926 * provides a portable way to rebuild an array from its memory representation.
1927 */
Brett Cannon1eb32c22014-10-10 16:26:45 -04001928/*[clinic input]
1929array._array_reconstructor
1930
1931 arraytype: object(type="PyTypeObject *")
Larry Hastingsdbfdc382015-05-04 06:59:46 -07001932 typecode: int(accept={str})
Brett Cannon1eb32c22014-10-10 16:26:45 -04001933 mformat_code: int(type="enum machine_format_code")
1934 items: object
1935 /
1936
1937Internal. Used for pickling support.
1938[clinic start generated code]*/
1939
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001940static PyObject *
Larry Hastings89964c42015-04-14 18:07:59 -04001941array__array_reconstructor_impl(PyModuleDef *module, PyTypeObject *arraytype,
1942 int typecode,
1943 enum machine_format_code mformat_code,
1944 PyObject *items)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07001945/*[clinic end generated code: output=6ecbf0e8e4d92ab9 input=2464dc8f4c7736b5]*/
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001946{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001947 PyObject *converted_items;
1948 PyObject *result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001949 struct arraydescr *descr;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001950
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001951 if (!PyType_Check(arraytype)) {
1952 PyErr_Format(PyExc_TypeError,
1953 "first argument must a type object, not %.200s",
1954 Py_TYPE(arraytype)->tp_name);
1955 return NULL;
1956 }
1957 if (!PyType_IsSubtype(arraytype, &Arraytype)) {
1958 PyErr_Format(PyExc_TypeError,
1959 "%.200s is not a subtype of %.200s",
1960 arraytype->tp_name, Arraytype.tp_name);
1961 return NULL;
1962 }
1963 for (descr = descriptors; descr->typecode != '\0'; descr++) {
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02001964 if ((int)descr->typecode == typecode)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001965 break;
1966 }
1967 if (descr->typecode == '\0') {
1968 PyErr_SetString(PyExc_ValueError,
1969 "second argument must be a valid type code");
1970 return NULL;
1971 }
Larry Hastingsdfbeb162014-10-13 10:39:41 +01001972 if (mformat_code < MACHINE_FORMAT_CODE_MIN ||
1973 mformat_code > MACHINE_FORMAT_CODE_MAX) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001974 PyErr_SetString(PyExc_ValueError,
1975 "third argument must be a valid machine format code.");
1976 return NULL;
1977 }
1978 if (!PyBytes_Check(items)) {
1979 PyErr_Format(PyExc_TypeError,
1980 "fourth argument should be bytes, not %.200s",
1981 Py_TYPE(items)->tp_name);
1982 return NULL;
1983 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001984
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001985 /* Fast path: No decoding has to be done. */
Larry Hastingsdfbeb162014-10-13 10:39:41 +01001986 if (mformat_code == typecode_to_mformat_code((char)typecode) ||
1987 mformat_code == UNKNOWN_FORMAT) {
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02001988 return make_array(arraytype, (char)typecode, items);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001989 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001990
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001991 /* Slow path: Decode the byte string according to the given machine
1992 * format code. This occurs when the computer unpickling the array
1993 * object is architecturally different from the one that pickled the
1994 * array.
1995 */
Larry Hastingsdfbeb162014-10-13 10:39:41 +01001996 if (Py_SIZE(items) % mformat_descriptors[mformat_code].size != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001997 PyErr_SetString(PyExc_ValueError,
1998 "string length not a multiple of item size");
1999 return NULL;
2000 }
Larry Hastingsdfbeb162014-10-13 10:39:41 +01002001 switch (mformat_code) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002002 case IEEE_754_FLOAT_LE:
2003 case IEEE_754_FLOAT_BE: {
2004 int i;
Larry Hastingsdfbeb162014-10-13 10:39:41 +01002005 int le = (mformat_code == IEEE_754_FLOAT_LE) ? 1 : 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002006 Py_ssize_t itemcount = Py_SIZE(items) / 4;
2007 const unsigned char *memstr =
2008 (unsigned char *)PyBytes_AS_STRING(items);
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002010 converted_items = PyList_New(itemcount);
2011 if (converted_items == NULL)
2012 return NULL;
2013 for (i = 0; i < itemcount; i++) {
2014 PyObject *pyfloat = PyFloat_FromDouble(
2015 _PyFloat_Unpack4(&memstr[i * 4], le));
2016 if (pyfloat == NULL) {
2017 Py_DECREF(converted_items);
2018 return NULL;
2019 }
2020 PyList_SET_ITEM(converted_items, i, pyfloat);
2021 }
2022 break;
2023 }
2024 case IEEE_754_DOUBLE_LE:
2025 case IEEE_754_DOUBLE_BE: {
2026 int i;
Larry Hastingsdfbeb162014-10-13 10:39:41 +01002027 int le = (mformat_code == IEEE_754_DOUBLE_LE) ? 1 : 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002028 Py_ssize_t itemcount = Py_SIZE(items) / 8;
2029 const unsigned char *memstr =
2030 (unsigned char *)PyBytes_AS_STRING(items);
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002031
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002032 converted_items = PyList_New(itemcount);
2033 if (converted_items == NULL)
2034 return NULL;
2035 for (i = 0; i < itemcount; i++) {
2036 PyObject *pyfloat = PyFloat_FromDouble(
2037 _PyFloat_Unpack8(&memstr[i * 8], le));
2038 if (pyfloat == NULL) {
2039 Py_DECREF(converted_items);
2040 return NULL;
2041 }
2042 PyList_SET_ITEM(converted_items, i, pyfloat);
2043 }
2044 break;
2045 }
2046 case UTF16_LE:
2047 case UTF16_BE: {
Larry Hastingsdfbeb162014-10-13 10:39:41 +01002048 int byteorder = (mformat_code == UTF16_LE) ? -1 : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002049 converted_items = PyUnicode_DecodeUTF16(
2050 PyBytes_AS_STRING(items), Py_SIZE(items),
2051 "strict", &byteorder);
2052 if (converted_items == NULL)
2053 return NULL;
2054 break;
2055 }
2056 case UTF32_LE:
2057 case UTF32_BE: {
Larry Hastingsdfbeb162014-10-13 10:39:41 +01002058 int byteorder = (mformat_code == UTF32_LE) ? -1 : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002059 converted_items = PyUnicode_DecodeUTF32(
2060 PyBytes_AS_STRING(items), Py_SIZE(items),
2061 "strict", &byteorder);
2062 if (converted_items == NULL)
2063 return NULL;
2064 break;
2065 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002067 case UNSIGNED_INT8:
2068 case SIGNED_INT8:
2069 case UNSIGNED_INT16_LE:
2070 case UNSIGNED_INT16_BE:
2071 case SIGNED_INT16_LE:
2072 case SIGNED_INT16_BE:
2073 case UNSIGNED_INT32_LE:
2074 case UNSIGNED_INT32_BE:
2075 case SIGNED_INT32_LE:
2076 case SIGNED_INT32_BE:
2077 case UNSIGNED_INT64_LE:
2078 case UNSIGNED_INT64_BE:
2079 case SIGNED_INT64_LE:
2080 case SIGNED_INT64_BE: {
2081 int i;
2082 const struct mformatdescr mf_descr =
Larry Hastingsdfbeb162014-10-13 10:39:41 +01002083 mformat_descriptors[mformat_code];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002084 Py_ssize_t itemcount = Py_SIZE(items) / mf_descr.size;
2085 const unsigned char *memstr =
2086 (unsigned char *)PyBytes_AS_STRING(items);
2087 struct arraydescr *descr;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002088
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002089 /* If possible, try to pack array's items using a data type
2090 * that fits better. This may result in an array with narrower
2091 * or wider elements.
2092 *
Martin Panter4c359642016-05-08 13:53:41 +00002093 * For example, if a 32-bit machine pickles an L-code array of
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002094 * unsigned longs, then the array will be unpickled by 64-bit
2095 * machine as an I-code array of unsigned ints.
2096 *
2097 * XXX: Is it possible to write a unit test for this?
2098 */
2099 for (descr = descriptors; descr->typecode != '\0'; descr++) {
2100 if (descr->is_integer_type &&
Victor Stinner706768c2014-08-16 01:03:39 +02002101 (size_t)descr->itemsize == mf_descr.size &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002102 descr->is_signed == mf_descr.is_signed)
2103 typecode = descr->typecode;
2104 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002106 converted_items = PyList_New(itemcount);
2107 if (converted_items == NULL)
2108 return NULL;
2109 for (i = 0; i < itemcount; i++) {
2110 PyObject *pylong;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002112 pylong = _PyLong_FromByteArray(
2113 &memstr[i * mf_descr.size],
2114 mf_descr.size,
2115 !mf_descr.is_big_endian,
2116 mf_descr.is_signed);
2117 if (pylong == NULL) {
2118 Py_DECREF(converted_items);
2119 return NULL;
2120 }
2121 PyList_SET_ITEM(converted_items, i, pylong);
2122 }
2123 break;
2124 }
2125 case UNKNOWN_FORMAT:
2126 /* Impossible, but needed to shut up GCC about the unhandled
2127 * enumeration value.
2128 */
2129 default:
2130 PyErr_BadArgument();
2131 return NULL;
2132 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002133
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02002134 result = make_array(arraytype, (char)typecode, converted_items);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002135 Py_DECREF(converted_items);
2136 return result;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002137}
2138
Brett Cannon1eb32c22014-10-10 16:26:45 -04002139/*[clinic input]
2140array.array.__reduce_ex__
2141
2142 value: object
2143 /
2144
2145Return state information for pickling.
2146[clinic start generated code]*/
2147
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002148static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04002149array_array___reduce_ex__(arrayobject *self, PyObject *value)
2150/*[clinic end generated code: output=051e0a6175d0eddb input=c36c3f85de7df6cd]*/
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002151{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002152 PyObject *dict;
2153 PyObject *result;
2154 PyObject *array_str;
Brett Cannon1eb32c22014-10-10 16:26:45 -04002155 int typecode = self->ob_descr->typecode;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002156 int mformat_code;
2157 static PyObject *array_reconstructor = NULL;
2158 long protocol;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002159 _Py_IDENTIFIER(_array_reconstructor);
2160 _Py_IDENTIFIER(__dict__);
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002161
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002162 if (array_reconstructor == NULL) {
2163 PyObject *array_module = PyImport_ImportModule("array");
2164 if (array_module == NULL)
2165 return NULL;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002166 array_reconstructor = _PyObject_GetAttrId(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002167 array_module,
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002168 &PyId__array_reconstructor);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002169 Py_DECREF(array_module);
2170 if (array_reconstructor == NULL)
2171 return NULL;
2172 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002174 if (!PyLong_Check(value)) {
2175 PyErr_SetString(PyExc_TypeError,
2176 "__reduce_ex__ argument should an integer");
2177 return NULL;
2178 }
2179 protocol = PyLong_AsLong(value);
2180 if (protocol == -1 && PyErr_Occurred())
2181 return NULL;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002182
Brett Cannon1eb32c22014-10-10 16:26:45 -04002183 dict = _PyObject_GetAttrId((PyObject *)self, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002184 if (dict == NULL) {
2185 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
2186 return NULL;
2187 PyErr_Clear();
2188 dict = Py_None;
2189 Py_INCREF(dict);
2190 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002192 mformat_code = typecode_to_mformat_code(typecode);
2193 if (mformat_code == UNKNOWN_FORMAT || protocol < 3) {
2194 /* Convert the array to a list if we got something weird
2195 * (e.g., non-IEEE floats), or we are pickling the array using
2196 * a Python 2.x compatible protocol.
2197 *
2198 * It is necessary to use a list representation for Python 2.x
2199 * compatible pickle protocol, since Python 2's str objects
2200 * are unpickled as unicode by Python 3. Thus it is impossible
2201 * to make arrays unpicklable by Python 3 by using their memory
2202 * representation, unless we resort to ugly hacks such as
2203 * coercing unicode objects to bytes in array_reconstructor.
2204 */
2205 PyObject *list;
Brett Cannon1eb32c22014-10-10 16:26:45 -04002206 list = array_array_tolist_impl(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002207 if (list == NULL) {
2208 Py_DECREF(dict);
2209 return NULL;
2210 }
2211 result = Py_BuildValue(
Brett Cannon1eb32c22014-10-10 16:26:45 -04002212 "O(CO)O", Py_TYPE(self), typecode, list, dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002213 Py_DECREF(list);
2214 Py_DECREF(dict);
2215 return result;
2216 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002217
Brett Cannon1eb32c22014-10-10 16:26:45 -04002218 array_str = array_array_tobytes_impl(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002219 if (array_str == NULL) {
2220 Py_DECREF(dict);
2221 return NULL;
2222 }
2223 result = Py_BuildValue(
Brett Cannon1eb32c22014-10-10 16:26:45 -04002224 "O(OCiN)O", array_reconstructor, Py_TYPE(self), typecode,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002225 mformat_code, array_str, dict);
2226 Py_DECREF(dict);
2227 return result;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002228}
2229
Martin v. Löwis99866332002-03-01 10:27:01 +00002230static PyObject *
2231array_get_typecode(arrayobject *a, void *closure)
2232{
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02002233 char typecode = a->ob_descr->typecode;
2234 return PyUnicode_FromOrdinal(typecode);
Martin v. Löwis99866332002-03-01 10:27:01 +00002235}
2236
2237static PyObject *
2238array_get_itemsize(arrayobject *a, void *closure)
2239{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002240 return PyLong_FromLong((long)a->ob_descr->itemsize);
Martin v. Löwis99866332002-03-01 10:27:01 +00002241}
2242
2243static PyGetSetDef array_getsets [] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002244 {"typecode", (getter) array_get_typecode, NULL,
2245 "the typecode character used to create the array"},
2246 {"itemsize", (getter) array_get_itemsize, NULL,
2247 "the size, in bytes, of one array item"},
2248 {NULL}
Martin v. Löwis99866332002-03-01 10:27:01 +00002249};
2250
Martin v. Löwis59683e82008-06-13 07:50:45 +00002251static PyMethodDef array_methods[] = {
Brett Cannon1eb32c22014-10-10 16:26:45 -04002252 ARRAY_ARRAY_APPEND_METHODDEF
2253 ARRAY_ARRAY_BUFFER_INFO_METHODDEF
2254 ARRAY_ARRAY_BYTESWAP_METHODDEF
2255 ARRAY_ARRAY___COPY___METHODDEF
2256 ARRAY_ARRAY_COUNT_METHODDEF
2257 ARRAY_ARRAY___DEEPCOPY___METHODDEF
2258 ARRAY_ARRAY_EXTEND_METHODDEF
2259 ARRAY_ARRAY_FROMFILE_METHODDEF
2260 ARRAY_ARRAY_FROMLIST_METHODDEF
2261 ARRAY_ARRAY_FROMSTRING_METHODDEF
2262 ARRAY_ARRAY_FROMBYTES_METHODDEF
2263 ARRAY_ARRAY_FROMUNICODE_METHODDEF
2264 ARRAY_ARRAY_INDEX_METHODDEF
2265 ARRAY_ARRAY_INSERT_METHODDEF
2266 ARRAY_ARRAY_POP_METHODDEF
2267 ARRAY_ARRAY___REDUCE_EX___METHODDEF
2268 ARRAY_ARRAY_REMOVE_METHODDEF
2269 ARRAY_ARRAY_REVERSE_METHODDEF
2270 ARRAY_ARRAY_TOFILE_METHODDEF
2271 ARRAY_ARRAY_TOLIST_METHODDEF
2272 ARRAY_ARRAY_TOSTRING_METHODDEF
2273 ARRAY_ARRAY_TOBYTES_METHODDEF
2274 ARRAY_ARRAY_TOUNICODE_METHODDEF
2275 ARRAY_ARRAY___SIZEOF___METHODDEF
2276 {NULL, NULL} /* sentinel */
Guido van Rossum778983b1993-02-19 15:55:02 +00002277};
2278
Roger E. Masse2919eaa1996-12-09 20:10:36 +00002279static PyObject *
Peter Schneider-Kamp9656abd2000-07-13 21:10:57 +00002280array_repr(arrayobject *a)
Guido van Rossum778983b1993-02-19 15:55:02 +00002281{
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02002282 char typecode;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002283 PyObject *s, *v = NULL;
2284 Py_ssize_t len;
Martin v. Löwis99866332002-03-01 10:27:01 +00002285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002286 len = Py_SIZE(a);
2287 typecode = a->ob_descr->typecode;
2288 if (len == 0) {
Amaury Forgeot d'Arc24aa26b2010-11-25 08:13:35 +00002289 return PyUnicode_FromFormat("array('%c')", (int)typecode);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002290 }
Gregory P. Smith9504b132012-12-10 20:20:20 -08002291 if (typecode == 'u') {
Brett Cannon1eb32c22014-10-10 16:26:45 -04002292 v = array_array_tounicode_impl(a);
Gregory P. Smith9504b132012-12-10 20:20:20 -08002293 } else {
Brett Cannon1eb32c22014-10-10 16:26:45 -04002294 v = array_array_tolist_impl(a);
Gregory P. Smith9504b132012-12-10 20:20:20 -08002295 }
Victor Stinner29ec5952013-02-26 00:27:38 +01002296 if (v == NULL)
2297 return NULL;
Raymond Hettinger88ba1e32003-04-23 17:27:00 +00002298
Amaury Forgeot d'Arc24aa26b2010-11-25 08:13:35 +00002299 s = PyUnicode_FromFormat("array('%c', %R)", (int)typecode, v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002300 Py_DECREF(v);
2301 return s;
Guido van Rossum778983b1993-02-19 15:55:02 +00002302}
2303
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002304static PyObject*
2305array_subscr(arrayobject* self, PyObject* item)
2306{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002307 if (PyIndex_Check(item)) {
2308 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
2309 if (i==-1 && PyErr_Occurred()) {
2310 return NULL;
2311 }
2312 if (i < 0)
2313 i += Py_SIZE(self);
2314 return array_item(self, i);
2315 }
2316 else if (PySlice_Check(item)) {
2317 Py_ssize_t start, stop, step, slicelength, cur, i;
2318 PyObject* result;
2319 arrayobject* ar;
2320 int itemsize = self->ob_descr->itemsize;
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002321
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002322 if (PySlice_GetIndicesEx(item, Py_SIZE(self),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002323 &start, &stop, &step, &slicelength) < 0) {
2324 return NULL;
2325 }
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002327 if (slicelength <= 0) {
2328 return newarrayobject(&Arraytype, 0, self->ob_descr);
2329 }
2330 else if (step == 1) {
2331 PyObject *result = newarrayobject(&Arraytype,
2332 slicelength, self->ob_descr);
2333 if (result == NULL)
2334 return NULL;
2335 memcpy(((arrayobject *)result)->ob_item,
2336 self->ob_item + start * itemsize,
2337 slicelength * itemsize);
2338 return result;
2339 }
2340 else {
2341 result = newarrayobject(&Arraytype, slicelength, self->ob_descr);
2342 if (!result) return NULL;
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002344 ar = (arrayobject*)result;
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002346 for (cur = start, i = 0; i < slicelength;
2347 cur += step, i++) {
2348 memcpy(ar->ob_item + i*itemsize,
2349 self->ob_item + cur*itemsize,
2350 itemsize);
2351 }
2352
2353 return result;
2354 }
2355 }
2356 else {
2357 PyErr_SetString(PyExc_TypeError,
2358 "array indices must be integers");
2359 return NULL;
2360 }
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002361}
2362
2363static int
2364array_ass_subscr(arrayobject* self, PyObject* item, PyObject* value)
2365{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002366 Py_ssize_t start, stop, step, slicelength, needed;
2367 arrayobject* other;
2368 int itemsize;
Thomas Woutersed03b412007-08-28 21:37:11 +00002369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002370 if (PyIndex_Check(item)) {
2371 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Alexandre Vassalotti47137252009-07-05 19:57:00 +00002372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002373 if (i == -1 && PyErr_Occurred())
2374 return -1;
2375 if (i < 0)
2376 i += Py_SIZE(self);
2377 if (i < 0 || i >= Py_SIZE(self)) {
2378 PyErr_SetString(PyExc_IndexError,
2379 "array assignment index out of range");
2380 return -1;
2381 }
2382 if (value == NULL) {
2383 /* Fall through to slice assignment */
2384 start = i;
2385 stop = i + 1;
2386 step = 1;
2387 slicelength = 1;
2388 }
2389 else
2390 return (*self->ob_descr->setitem)(self, i, value);
2391 }
2392 else if (PySlice_Check(item)) {
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002393 if (PySlice_GetIndicesEx(item,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002394 Py_SIZE(self), &start, &stop,
2395 &step, &slicelength) < 0) {
2396 return -1;
2397 }
2398 }
2399 else {
2400 PyErr_SetString(PyExc_TypeError,
2401 "array indices must be integer");
2402 return -1;
2403 }
2404 if (value == NULL) {
2405 other = NULL;
2406 needed = 0;
2407 }
2408 else if (array_Check(value)) {
2409 other = (arrayobject *)value;
2410 needed = Py_SIZE(other);
2411 if (self == other) {
2412 /* Special case "self[i:j] = self" -- copy self first */
2413 int ret;
2414 value = array_slice(other, 0, needed);
2415 if (value == NULL)
2416 return -1;
2417 ret = array_ass_subscr(self, item, value);
2418 Py_DECREF(value);
2419 return ret;
2420 }
2421 if (other->ob_descr != self->ob_descr) {
2422 PyErr_BadArgument();
2423 return -1;
2424 }
2425 }
2426 else {
2427 PyErr_Format(PyExc_TypeError,
2428 "can only assign array (not \"%.200s\") to array slice",
2429 Py_TYPE(value)->tp_name);
2430 return -1;
2431 }
2432 itemsize = self->ob_descr->itemsize;
2433 /* for 'a[2:1] = ...', the insertion point is 'start', not 'stop' */
2434 if ((step > 0 && stop < start) ||
2435 (step < 0 && stop > start))
2436 stop = start;
Alexandre Vassalotti47137252009-07-05 19:57:00 +00002437
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002438 /* Issue #4509: If the array has exported buffers and the slice
2439 assignment would change the size of the array, fail early to make
2440 sure we don't modify it. */
2441 if ((needed == 0 || slicelength != needed) && self->ob_exports > 0) {
2442 PyErr_SetString(PyExc_BufferError,
2443 "cannot resize an array that is exporting buffers");
2444 return -1;
2445 }
Mark Dickinsonbc099642010-01-29 17:27:24 +00002446
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002447 if (step == 1) {
2448 if (slicelength > needed) {
2449 memmove(self->ob_item + (start + needed) * itemsize,
2450 self->ob_item + stop * itemsize,
2451 (Py_SIZE(self) - stop) * itemsize);
2452 if (array_resize(self, Py_SIZE(self) +
2453 needed - slicelength) < 0)
2454 return -1;
2455 }
2456 else if (slicelength < needed) {
2457 if (array_resize(self, Py_SIZE(self) +
2458 needed - slicelength) < 0)
2459 return -1;
2460 memmove(self->ob_item + (start + needed) * itemsize,
2461 self->ob_item + stop * itemsize,
2462 (Py_SIZE(self) - start - needed) * itemsize);
2463 }
2464 if (needed > 0)
2465 memcpy(self->ob_item + start * itemsize,
2466 other->ob_item, needed * itemsize);
2467 return 0;
2468 }
2469 else if (needed == 0) {
2470 /* Delete slice */
2471 size_t cur;
2472 Py_ssize_t i;
Thomas Woutersed03b412007-08-28 21:37:11 +00002473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002474 if (step < 0) {
2475 stop = start + 1;
2476 start = stop + step * (slicelength - 1) - 1;
2477 step = -step;
2478 }
2479 for (cur = start, i = 0; i < slicelength;
2480 cur += step, i++) {
2481 Py_ssize_t lim = step - 1;
Thomas Woutersed03b412007-08-28 21:37:11 +00002482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002483 if (cur + step >= (size_t)Py_SIZE(self))
2484 lim = Py_SIZE(self) - cur - 1;
2485 memmove(self->ob_item + (cur - i) * itemsize,
2486 self->ob_item + (cur + 1) * itemsize,
2487 lim * itemsize);
2488 }
Mark Dickinsonc7d93b72011-09-25 15:34:32 +01002489 cur = start + (size_t)slicelength * step;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002490 if (cur < (size_t)Py_SIZE(self)) {
2491 memmove(self->ob_item + (cur-slicelength) * itemsize,
2492 self->ob_item + cur * itemsize,
2493 (Py_SIZE(self) - cur) * itemsize);
2494 }
2495 if (array_resize(self, Py_SIZE(self) - slicelength) < 0)
2496 return -1;
2497 return 0;
2498 }
2499 else {
2500 Py_ssize_t cur, i;
2501
2502 if (needed != slicelength) {
2503 PyErr_Format(PyExc_ValueError,
2504 "attempt to assign array of size %zd "
2505 "to extended slice of size %zd",
2506 needed, slicelength);
2507 return -1;
2508 }
2509 for (cur = start, i = 0; i < slicelength;
2510 cur += step, i++) {
2511 memcpy(self->ob_item + cur * itemsize,
2512 other->ob_item + i * itemsize,
2513 itemsize);
2514 }
2515 return 0;
2516 }
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002517}
2518
2519static PyMappingMethods array_as_mapping = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002520 (lenfunc)array_length,
2521 (binaryfunc)array_subscr,
2522 (objobjargproc)array_ass_subscr
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002523};
2524
Guido van Rossumd8faa362007-04-27 19:54:29 +00002525static const void *emptybuf = "";
2526
Travis E. Oliphantb99f7622007-08-18 11:21:56 +00002527
2528static int
Travis E. Oliphant8ae62b62007-09-23 02:00:13 +00002529array_buffer_getbuf(arrayobject *self, Py_buffer *view, int flags)
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00002530{
Stefan Krah650c1e82015-02-03 21:43:23 +01002531 if (view == NULL) {
2532 PyErr_SetString(PyExc_BufferError,
2533 "array_buffer_getbuf: view==NULL argument is obsolete");
2534 return -1;
2535 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +00002536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002537 view->buf = (void *)self->ob_item;
2538 view->obj = (PyObject*)self;
2539 Py_INCREF(self);
2540 if (view->buf == NULL)
2541 view->buf = (void *)emptybuf;
2542 view->len = (Py_SIZE(self)) * self->ob_descr->itemsize;
2543 view->readonly = 0;
2544 view->ndim = 1;
2545 view->itemsize = self->ob_descr->itemsize;
2546 view->suboffsets = NULL;
2547 view->shape = NULL;
2548 if ((flags & PyBUF_ND)==PyBUF_ND) {
2549 view->shape = &((Py_SIZE(self)));
2550 }
2551 view->strides = NULL;
2552 if ((flags & PyBUF_STRIDES)==PyBUF_STRIDES)
2553 view->strides = &(view->itemsize);
2554 view->format = NULL;
2555 view->internal = NULL;
Victor Stinner62bb3942012-08-06 00:46:05 +02002556 if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002557 view->format = self->ob_descr->formats;
Victor Stinner62bb3942012-08-06 00:46:05 +02002558#ifdef Py_UNICODE_WIDE
2559 if (self->ob_descr->typecode == 'u') {
2560 view->format = "w";
2561 }
2562#endif
2563 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +00002564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002565 self->ob_exports++;
2566 return 0;
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00002567}
2568
Travis E. Oliphantb99f7622007-08-18 11:21:56 +00002569static void
Travis E. Oliphant8ae62b62007-09-23 02:00:13 +00002570array_buffer_relbuf(arrayobject *self, Py_buffer *view)
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00002571{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002572 self->ob_exports--;
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00002573}
2574
Roger E. Masse2919eaa1996-12-09 20:10:36 +00002575static PySequenceMethods array_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002576 (lenfunc)array_length, /*sq_length*/
2577 (binaryfunc)array_concat, /*sq_concat*/
2578 (ssizeargfunc)array_repeat, /*sq_repeat*/
2579 (ssizeargfunc)array_item, /*sq_item*/
2580 0, /*sq_slice*/
2581 (ssizeobjargproc)array_ass_item, /*sq_ass_item*/
2582 0, /*sq_ass_slice*/
2583 (objobjproc)array_contains, /*sq_contains*/
2584 (binaryfunc)array_inplace_concat, /*sq_inplace_concat*/
2585 (ssizeargfunc)array_inplace_repeat /*sq_inplace_repeat*/
Guido van Rossum778983b1993-02-19 15:55:02 +00002586};
2587
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00002588static PyBufferProcs array_as_buffer = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002589 (getbufferproc)array_buffer_getbuf,
2590 (releasebufferproc)array_buffer_relbuf
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00002591};
2592
Roger E. Masse2919eaa1996-12-09 20:10:36 +00002593static PyObject *
Martin v. Löwis99866332002-03-01 10:27:01 +00002594array_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum778983b1993-02-19 15:55:02 +00002595{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002596 int c;
2597 PyObject *initial = NULL, *it = NULL;
2598 struct arraydescr *descr;
Martin v. Löwis99866332002-03-01 10:27:01 +00002599
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002600 if (type == &Arraytype && !_PyArg_NoKeywords("array.array()", kwds))
2601 return NULL;
Martin v. Löwis99866332002-03-01 10:27:01 +00002602
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002603 if (!PyArg_ParseTuple(args, "C|O:array", &c, &initial))
2604 return NULL;
Raymond Hettinger84fc9aa2003-04-24 10:41:55 +00002605
Alexandre Vassalotti9730e332013-11-29 20:47:15 -08002606 if (initial && c != 'u') {
2607 if (PyUnicode_Check(initial)) {
2608 PyErr_Format(PyExc_TypeError, "cannot use a str to initialize "
2609 "an array with typecode '%c'", c);
2610 return NULL;
2611 }
2612 else if (array_Check(initial) &&
2613 ((arrayobject*)initial)->ob_descr->typecode == 'u') {
2614 PyErr_Format(PyExc_TypeError, "cannot use a unicode array to "
2615 "initialize an array with typecode '%c'", c);
2616 return NULL;
2617 }
2618 }
2619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002620 if (!(initial == NULL || PyList_Check(initial)
2621 || PyByteArray_Check(initial)
2622 || PyBytes_Check(initial)
2623 || PyTuple_Check(initial)
Alexander Belopolskyef4a03f2011-01-11 21:44:00 +00002624 || ((c=='u') && PyUnicode_Check(initial))
2625 || (array_Check(initial)
2626 && c == ((arrayobject*)initial)->ob_descr->typecode))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002627 it = PyObject_GetIter(initial);
2628 if (it == NULL)
2629 return NULL;
2630 /* We set initial to NULL so that the subsequent code
2631 will create an empty array of the appropriate type
2632 and afterwards we can use array_iter_extend to populate
2633 the array.
2634 */
2635 initial = NULL;
2636 }
2637 for (descr = descriptors; descr->typecode != '\0'; descr++) {
2638 if (descr->typecode == c) {
2639 PyObject *a;
2640 Py_ssize_t len;
Martin v. Löwis99866332002-03-01 10:27:01 +00002641
Alexander Belopolskyef4a03f2011-01-11 21:44:00 +00002642 if (initial == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002643 len = 0;
Alexander Belopolskyef4a03f2011-01-11 21:44:00 +00002644 else if (PyList_Check(initial))
2645 len = PyList_GET_SIZE(initial);
2646 else if (PyTuple_Check(initial) || array_Check(initial))
2647 len = Py_SIZE(initial);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002648 else
Alexander Belopolskyef4a03f2011-01-11 21:44:00 +00002649 len = 0;
Martin v. Löwis99866332002-03-01 10:27:01 +00002650
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002651 a = newarrayobject(type, len, descr);
2652 if (a == NULL)
2653 return NULL;
2654
Alexander Belopolskyef4a03f2011-01-11 21:44:00 +00002655 if (len > 0 && !array_Check(initial)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002656 Py_ssize_t i;
2657 for (i = 0; i < len; i++) {
2658 PyObject *v =
2659 PySequence_GetItem(initial, i);
2660 if (v == NULL) {
2661 Py_DECREF(a);
2662 return NULL;
2663 }
2664 if (setarrayitem(a, i, v) != 0) {
2665 Py_DECREF(v);
2666 Py_DECREF(a);
2667 return NULL;
2668 }
2669 Py_DECREF(v);
2670 }
2671 }
2672 else if (initial != NULL && (PyByteArray_Check(initial) ||
2673 PyBytes_Check(initial))) {
Serhiy Storchaka04e6dba2015-04-04 17:06:55 +03002674 PyObject *v;
Brett Cannon1eb32c22014-10-10 16:26:45 -04002675 v = array_array_frombytes((arrayobject *)a,
Serhiy Storchaka04e6dba2015-04-04 17:06:55 +03002676 initial);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002677 if (v == NULL) {
2678 Py_DECREF(a);
2679 return NULL;
2680 }
2681 Py_DECREF(v);
2682 }
2683 else if (initial != NULL && PyUnicode_Check(initial)) {
Victor Stinner62bb3942012-08-06 00:46:05 +02002684 Py_UNICODE *ustr;
Victor Stinner1fbcaef2011-09-30 01:54:04 +02002685 Py_ssize_t n;
Victor Stinner62bb3942012-08-06 00:46:05 +02002686
2687 ustr = PyUnicode_AsUnicode(initial);
2688 if (ustr == NULL) {
2689 PyErr_NoMemory();
Victor Stinner1fbcaef2011-09-30 01:54:04 +02002690 Py_DECREF(a);
2691 return NULL;
2692 }
Victor Stinner62bb3942012-08-06 00:46:05 +02002693
2694 n = PyUnicode_GET_DATA_SIZE(initial);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002695 if (n > 0) {
2696 arrayobject *self = (arrayobject *)a;
Victor Stinner62bb3942012-08-06 00:46:05 +02002697 char *item = self->ob_item;
2698 item = (char *)PyMem_Realloc(item, n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002699 if (item == NULL) {
2700 PyErr_NoMemory();
2701 Py_DECREF(a);
2702 return NULL;
2703 }
Victor Stinner62bb3942012-08-06 00:46:05 +02002704 self->ob_item = item;
2705 Py_SIZE(self) = n / sizeof(Py_UNICODE);
2706 memcpy(item, ustr, n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002707 self->allocated = Py_SIZE(self);
2708 }
2709 }
Benjamin Peterson682124c2014-10-10 20:58:30 -04002710 else if (initial != NULL && array_Check(initial) && len > 0) {
Alexander Belopolskyef4a03f2011-01-11 21:44:00 +00002711 arrayobject *self = (arrayobject *)a;
2712 arrayobject *other = (arrayobject *)initial;
2713 memcpy(self->ob_item, other->ob_item, len * other->ob_descr->itemsize);
2714 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002715 if (it != NULL) {
2716 if (array_iter_extend((arrayobject *)a, it) == -1) {
2717 Py_DECREF(it);
2718 Py_DECREF(a);
2719 return NULL;
2720 }
2721 Py_DECREF(it);
2722 }
2723 return a;
2724 }
2725 }
2726 PyErr_SetString(PyExc_ValueError,
Meador Inge1c9f0c92011-09-20 19:55:51 -05002727#ifdef HAVE_LONG_LONG
2728 "bad typecode (must be b, B, u, h, H, i, I, l, L, q, Q, f or d)");
2729#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002730 "bad typecode (must be b, B, u, h, H, i, I, l, L, f or d)");
Meador Inge1c9f0c92011-09-20 19:55:51 -05002731#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002732 return NULL;
Guido van Rossum778983b1993-02-19 15:55:02 +00002733}
2734
Guido van Rossum778983b1993-02-19 15:55:02 +00002735
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002736PyDoc_STRVAR(module_doc,
Martin v. Löwis99866332002-03-01 10:27:01 +00002737"This module defines an object type which can efficiently represent\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002738an array of basic values: characters, integers, floating point\n\
2739numbers. Arrays are sequence types and behave very much like lists,\n\
Alexandre Vassalotti9730e332013-11-29 20:47:15 -08002740except that the type of objects stored in them is constrained.\n");
2741
2742PyDoc_STRVAR(arraytype_doc,
2743"array(typecode [, initializer]) -> array\n\
2744\n\
2745Return a new array whose items are restricted by typecode, and\n\
2746initialized from the optional initializer value, which must be a list,\n\
2747string or iterable over elements of the appropriate type.\n\
2748\n\
2749Arrays represent basic values and behave very much like lists, except\n\
2750the type of objects stored in them is constrained. The type is specified\n\
2751at object creation time by using a type code, which is a single character.\n\
2752The following type codes are defined:\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002753\n\
2754 Type code C Type Minimum size in bytes \n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002755 'b' signed integer 1 \n\
2756 'B' unsigned integer 1 \n\
Victor Stinner62bb3942012-08-06 00:46:05 +02002757 'u' Unicode character 2 (see note) \n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002758 'h' signed integer 2 \n\
2759 'H' unsigned integer 2 \n\
2760 'i' signed integer 2 \n\
2761 'I' unsigned integer 2 \n\
2762 'l' signed integer 4 \n\
2763 'L' unsigned integer 4 \n\
Meador Inge1c9f0c92011-09-20 19:55:51 -05002764 'q' signed integer 8 (see note) \n\
2765 'Q' unsigned integer 8 (see note) \n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002766 'f' floating point 4 \n\
2767 'd' floating point 8 \n\
2768\n\
Victor Stinner62bb3942012-08-06 00:46:05 +02002769NOTE: The 'u' typecode corresponds to Python's unicode character. On \n\
2770narrow builds this is 2-bytes on wide builds this is 4-bytes.\n\
2771\n\
Meador Inge1c9f0c92011-09-20 19:55:51 -05002772NOTE: The 'q' and 'Q' type codes are only available if the platform \n\
2773C compiler used to build Python supports 'long long', or, on Windows, \n\
2774'__int64'.\n\
2775\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002776Methods:\n\
2777\n\
2778append() -- append a new item to the end of the array\n\
2779buffer_info() -- return information giving the current memory info\n\
2780byteswap() -- byteswap all the items of the array\n\
Mark Dickinson934896d2009-02-21 20:59:32 +00002781count() -- return number of occurrences of an object\n\
Raymond Hettinger49f9bd12004-03-14 05:43:59 +00002782extend() -- extend array by appending multiple elements from an iterable\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002783fromfile() -- read items from a file object\n\
2784fromlist() -- append items from the list\n\
Florent Xiclunac45fb252011-10-24 13:14:55 +02002785frombytes() -- append items from the string\n\
Mark Dickinson934896d2009-02-21 20:59:32 +00002786index() -- return index of first occurrence of an object\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002787insert() -- insert a new item into the array at a provided position\n\
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00002788pop() -- remove and return item (default last)\n\
Mark Dickinson934896d2009-02-21 20:59:32 +00002789remove() -- remove first occurrence of an object\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002790reverse() -- reverse the order of the items in the array\n\
2791tofile() -- write all items to a file object\n\
2792tolist() -- return the array converted to an ordinary list\n\
Florent Xiclunac45fb252011-10-24 13:14:55 +02002793tobytes() -- return the array converted to a string\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002794\n\
Martin v. Löwis99866332002-03-01 10:27:01 +00002795Attributes:\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002796\n\
2797typecode -- the typecode character used to create the array\n\
2798itemsize -- the length in bytes of one array item\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002799");
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002800
Raymond Hettinger625812f2003-01-07 01:58:52 +00002801static PyObject *array_iter(arrayobject *ao);
2802
Tim Peters0c322792002-07-17 16:49:03 +00002803static PyTypeObject Arraytype = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002804 PyVarObject_HEAD_INIT(NULL, 0)
2805 "array.array",
2806 sizeof(arrayobject),
2807 0,
2808 (destructor)array_dealloc, /* tp_dealloc */
2809 0, /* tp_print */
2810 0, /* tp_getattr */
2811 0, /* tp_setattr */
2812 0, /* tp_reserved */
2813 (reprfunc)array_repr, /* tp_repr */
2814 0, /* tp_as_number*/
2815 &array_as_sequence, /* tp_as_sequence*/
2816 &array_as_mapping, /* tp_as_mapping*/
2817 0, /* tp_hash */
2818 0, /* tp_call */
2819 0, /* tp_str */
2820 PyObject_GenericGetAttr, /* tp_getattro */
2821 0, /* tp_setattro */
2822 &array_as_buffer, /* tp_as_buffer*/
2823 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
2824 arraytype_doc, /* tp_doc */
2825 0, /* tp_traverse */
2826 0, /* tp_clear */
2827 array_richcompare, /* tp_richcompare */
2828 offsetof(arrayobject, weakreflist), /* tp_weaklistoffset */
2829 (getiterfunc)array_iter, /* tp_iter */
2830 0, /* tp_iternext */
2831 array_methods, /* tp_methods */
2832 0, /* tp_members */
2833 array_getsets, /* tp_getset */
2834 0, /* tp_base */
2835 0, /* tp_dict */
2836 0, /* tp_descr_get */
2837 0, /* tp_descr_set */
2838 0, /* tp_dictoffset */
2839 0, /* tp_init */
2840 PyType_GenericAlloc, /* tp_alloc */
2841 array_new, /* tp_new */
2842 PyObject_Del, /* tp_free */
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002843};
2844
Raymond Hettinger625812f2003-01-07 01:58:52 +00002845
2846/*********************** Array Iterator **************************/
2847
Brett Cannon1eb32c22014-10-10 16:26:45 -04002848/*[clinic input]
2849class array.arrayiterator "arrayiterobject *" "&PyArrayIter_Type"
2850[clinic start generated code]*/
2851/*[clinic end generated code: output=da39a3ee5e6b4b0d input=5aefd2d74d8c8e30]*/
Raymond Hettinger625812f2003-01-07 01:58:52 +00002852
2853static PyObject *
2854array_iter(arrayobject *ao)
2855{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002856 arrayiterobject *it;
Raymond Hettinger625812f2003-01-07 01:58:52 +00002857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002858 if (!array_Check(ao)) {
2859 PyErr_BadInternalCall();
2860 return NULL;
2861 }
Raymond Hettinger625812f2003-01-07 01:58:52 +00002862
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002863 it = PyObject_GC_New(arrayiterobject, &PyArrayIter_Type);
2864 if (it == NULL)
2865 return NULL;
Raymond Hettinger625812f2003-01-07 01:58:52 +00002866
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002867 Py_INCREF(ao);
2868 it->ao = ao;
2869 it->index = 0;
2870 it->getitem = ao->ob_descr->getitem;
2871 PyObject_GC_Track(it);
2872 return (PyObject *)it;
Raymond Hettinger625812f2003-01-07 01:58:52 +00002873}
2874
2875static PyObject *
Raymond Hettinger625812f2003-01-07 01:58:52 +00002876arrayiter_next(arrayiterobject *it)
2877{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002878 assert(PyArrayIter_Check(it));
2879 if (it->index < Py_SIZE(it->ao))
2880 return (*it->getitem)(it->ao, it->index++);
2881 return NULL;
Raymond Hettinger625812f2003-01-07 01:58:52 +00002882}
2883
2884static void
2885arrayiter_dealloc(arrayiterobject *it)
2886{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002887 PyObject_GC_UnTrack(it);
2888 Py_XDECREF(it->ao);
2889 PyObject_GC_Del(it);
Raymond Hettinger625812f2003-01-07 01:58:52 +00002890}
2891
2892static int
2893arrayiter_traverse(arrayiterobject *it, visitproc visit, void *arg)
2894{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002895 Py_VISIT(it->ao);
2896 return 0;
Raymond Hettinger625812f2003-01-07 01:58:52 +00002897}
2898
Brett Cannon1eb32c22014-10-10 16:26:45 -04002899/*[clinic input]
2900array.arrayiterator.__reduce__
2901
2902Return state information for pickling.
2903[clinic start generated code]*/
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002904
2905static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04002906array_arrayiterator___reduce___impl(arrayiterobject *self)
2907/*[clinic end generated code: output=7898a52e8e66e016 input=a062ea1e9951417a]*/
2908{
2909 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
2910 self->ao, self->index);
2911}
2912
2913/*[clinic input]
2914array.arrayiterator.__setstate__
2915
2916 state: object
2917 /
2918
2919Set state information for unpickling.
2920[clinic start generated code]*/
2921
2922static PyObject *
2923array_arrayiterator___setstate__(arrayiterobject *self, PyObject *state)
2924/*[clinic end generated code: output=397da9904e443cbe input=f47d5ceda19e787b]*/
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002925{
2926 Py_ssize_t index = PyLong_AsSsize_t(state);
2927 if (index == -1 && PyErr_Occurred())
2928 return NULL;
2929 if (index < 0)
2930 index = 0;
Brett Cannon1eb32c22014-10-10 16:26:45 -04002931 else if (index > Py_SIZE(self->ao))
2932 index = Py_SIZE(self->ao); /* iterator exhausted */
2933 self->index = index;
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002934 Py_RETURN_NONE;
2935}
2936
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002937static PyMethodDef arrayiter_methods[] = {
Brett Cannon1eb32c22014-10-10 16:26:45 -04002938 ARRAY_ARRAYITERATOR___REDUCE___METHODDEF
2939 ARRAY_ARRAYITERATOR___SETSTATE___METHODDEF
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002940 {NULL, NULL} /* sentinel */
2941};
2942
Raymond Hettinger625812f2003-01-07 01:58:52 +00002943static PyTypeObject PyArrayIter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002944 PyVarObject_HEAD_INIT(NULL, 0)
2945 "arrayiterator", /* tp_name */
2946 sizeof(arrayiterobject), /* tp_basicsize */
2947 0, /* tp_itemsize */
2948 /* methods */
2949 (destructor)arrayiter_dealloc, /* tp_dealloc */
2950 0, /* tp_print */
2951 0, /* tp_getattr */
2952 0, /* tp_setattr */
2953 0, /* tp_reserved */
2954 0, /* tp_repr */
2955 0, /* tp_as_number */
2956 0, /* tp_as_sequence */
2957 0, /* tp_as_mapping */
2958 0, /* tp_hash */
2959 0, /* tp_call */
2960 0, /* tp_str */
2961 PyObject_GenericGetAttr, /* tp_getattro */
2962 0, /* tp_setattro */
2963 0, /* tp_as_buffer */
2964 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2965 0, /* tp_doc */
2966 (traverseproc)arrayiter_traverse, /* tp_traverse */
2967 0, /* tp_clear */
2968 0, /* tp_richcompare */
2969 0, /* tp_weaklistoffset */
2970 PyObject_SelfIter, /* tp_iter */
2971 (iternextfunc)arrayiter_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002972 arrayiter_methods, /* tp_methods */
Raymond Hettinger625812f2003-01-07 01:58:52 +00002973};
2974
2975
2976/*********************** Install Module **************************/
2977
Martin v. Löwis99866332002-03-01 10:27:01 +00002978/* No functions in array module. */
2979static PyMethodDef a_methods[] = {
Brett Cannon1eb32c22014-10-10 16:26:45 -04002980 ARRAY__ARRAY_RECONSTRUCTOR_METHODDEF
Martin v. Löwis99866332002-03-01 10:27:01 +00002981 {NULL, NULL, 0, NULL} /* Sentinel */
2982};
2983
Nick Coghland5cacbb2015-05-23 22:24:10 +10002984static int
2985array_modexec(PyObject *m)
Guido van Rossum778983b1993-02-19 15:55:02 +00002986{
Georg Brandl4cb0de22011-09-28 21:49:49 +02002987 char buffer[Py_ARRAY_LENGTH(descriptors)], *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002988 PyObject *typecodes;
2989 Py_ssize_t size = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002990 struct arraydescr *descr;
Fred Drake0d40ba42000-02-04 20:33:49 +00002991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002992 if (PyType_Ready(&Arraytype) < 0)
Nick Coghland5cacbb2015-05-23 22:24:10 +10002993 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002994 Py_TYPE(&PyArrayIter_Type) = &PyType_Type;
Fred Drakef4e34842002-04-01 03:45:06 +00002995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002996 Py_INCREF((PyObject *)&Arraytype);
2997 PyModule_AddObject(m, "ArrayType", (PyObject *)&Arraytype);
2998 Py_INCREF((PyObject *)&Arraytype);
2999 PyModule_AddObject(m, "array", (PyObject *)&Arraytype);
Travis E. Oliphantd5c0add2007-10-12 22:05:15 +00003000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003001 for (descr=descriptors; descr->typecode != '\0'; descr++) {
3002 size++;
3003 }
Travis E. Oliphantd5c0add2007-10-12 22:05:15 +00003004
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003005 p = buffer;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003006 for (descr = descriptors; descr->typecode != '\0'; descr++) {
3007 *p++ = (char)descr->typecode;
3008 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003009 typecodes = PyUnicode_DecodeASCII(buffer, p - buffer, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003010
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003011 PyModule_AddObject(m, "typecodes", typecodes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003012
3013 if (PyErr_Occurred()) {
3014 Py_DECREF(m);
3015 m = NULL;
3016 }
Nick Coghland5cacbb2015-05-23 22:24:10 +10003017 return 0;
3018}
3019
3020static PyModuleDef_Slot arrayslots[] = {
3021 {Py_mod_exec, array_modexec},
3022 {0, NULL}
3023};
3024
3025
3026static struct PyModuleDef arraymodule = {
3027 PyModuleDef_HEAD_INIT,
3028 "array",
3029 module_doc,
3030 0,
3031 a_methods,
3032 arrayslots,
3033 NULL,
3034 NULL,
3035 NULL
3036};
3037
3038
3039PyMODINIT_FUNC
3040PyInit_array(void)
3041{
3042 return PyModuleDef_Init(&arraymodule);
Guido van Rossum778983b1993-02-19 15:55:02 +00003043}