blob: 8637cb52b107d7f6754d003f77a0ba8e584205bf [file] [log] [blame]
Guido van Rossum778983b1993-02-19 15:55:02 +00001/* Array object implementation */
2
3/* An array is a uniform list -- all items have the same type.
4 The item type is restricted to simple C types like int or float */
5
Martin v. Löwis18e16552006-02-15 17:27:45 +00006#define PY_SSIZE_T_CLEAN
Roger E. Masse2919eaa1996-12-09 20:10:36 +00007#include "Python.h"
Raymond Hettingercb87bc82004-05-31 00:35:52 +00008#include "structmember.h"
Roger E. Masse5817f8f1996-12-09 22:24:19 +00009
Guido van Rossum0c709541994-08-19 12:01:32 +000010#ifdef STDC_HEADERS
11#include <stddef.h>
Guido van Rossum7f1de831999-08-27 20:33:52 +000012#else /* !STDC_HEADERS */
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013#ifdef HAVE_SYS_TYPES_H
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000014#include <sys/types.h> /* For size_t */
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015#endif /* HAVE_SYS_TYPES_H */
Guido van Rossum7f1de831999-08-27 20:33:52 +000016#endif /* !STDC_HEADERS */
Guido van Rossum778983b1993-02-19 15:55:02 +000017
Brett Cannon1eb32c22014-10-10 16:26:45 -040018/*[clinic input]
Brett Cannon1eb32c22014-10-10 16:26:45 -040019module array
20[clinic start generated code]*/
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030021/*[clinic end generated code: output=da39a3ee5e6b4b0d input=7d1b8d7f5958fd83]*/
Brett Cannon1eb32c22014-10-10 16:26:45 -040022
Guido van Rossum778983b1993-02-19 15:55:02 +000023struct arrayobject; /* Forward */
24
Tim Petersbb307342000-09-10 05:22:54 +000025/* All possible arraydescr values are defined in the vector "descriptors"
26 * below. That's defined later because the appropriate get and set
27 * functions aren't visible yet.
28 */
Guido van Rossum778983b1993-02-19 15:55:02 +000029struct arraydescr {
Victor Stinnerf8bb7d02011-09-30 00:03:59 +020030 char typecode;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000031 int itemsize;
32 PyObject * (*getitem)(struct arrayobject *, Py_ssize_t);
33 int (*setitem)(struct arrayobject *, Py_ssize_t, PyObject *);
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020034 const char *formats;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000035 int is_integer_type;
36 int is_signed;
Guido van Rossum778983b1993-02-19 15:55:02 +000037};
38
39typedef struct arrayobject {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000040 PyObject_VAR_HEAD
41 char *ob_item;
42 Py_ssize_t allocated;
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020043 const struct arraydescr *ob_descr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000044 PyObject *weakreflist; /* List of weak references */
45 int ob_exports; /* Number of exported buffers */
Guido van Rossum778983b1993-02-19 15:55:02 +000046} arrayobject;
47
Jeremy Hylton938ace62002-07-17 16:30:39 +000048static PyTypeObject Arraytype;
Guido van Rossum778983b1993-02-19 15:55:02 +000049
Brett Cannon1eb32c22014-10-10 16:26:45 -040050typedef struct {
51 PyObject_HEAD
52 Py_ssize_t index;
53 arrayobject *ao;
54 PyObject* (*getitem)(struct arrayobject *, Py_ssize_t);
55} arrayiterobject;
56
57static PyTypeObject PyArrayIter_Type;
58
59#define PyArrayIter_Check(op) PyObject_TypeCheck(op, &PyArrayIter_Type)
60
Larry Hastingsdfbeb162014-10-13 10:39:41 +010061enum machine_format_code {
62 UNKNOWN_FORMAT = -1,
63 /* UNKNOWN_FORMAT is used to indicate that the machine format for an
64 * array type code cannot be interpreted. When this occurs, a list of
65 * Python objects is used to represent the content of the array
66 * instead of using the memory content of the array directly. In that
67 * case, the array_reconstructor mechanism is bypassed completely, and
68 * the standard array constructor is used instead.
69 *
70 * This is will most likely occur when the machine doesn't use IEEE
71 * floating-point numbers.
72 */
73
74 UNSIGNED_INT8 = 0,
75 SIGNED_INT8 = 1,
76 UNSIGNED_INT16_LE = 2,
77 UNSIGNED_INT16_BE = 3,
78 SIGNED_INT16_LE = 4,
79 SIGNED_INT16_BE = 5,
80 UNSIGNED_INT32_LE = 6,
81 UNSIGNED_INT32_BE = 7,
82 SIGNED_INT32_LE = 8,
83 SIGNED_INT32_BE = 9,
84 UNSIGNED_INT64_LE = 10,
85 UNSIGNED_INT64_BE = 11,
86 SIGNED_INT64_LE = 12,
87 SIGNED_INT64_BE = 13,
88 IEEE_754_FLOAT_LE = 14,
89 IEEE_754_FLOAT_BE = 15,
90 IEEE_754_DOUBLE_LE = 16,
91 IEEE_754_DOUBLE_BE = 17,
92 UTF16_LE = 18,
93 UTF16_BE = 19,
94 UTF32_LE = 20,
95 UTF32_BE = 21
96};
97#define MACHINE_FORMAT_CODE_MIN 0
98#define MACHINE_FORMAT_CODE_MAX 21
99
100
101/*
102 * Must come after arrayobject, arrayiterobject,
103 * and enum machine_code_type definitions.
104 */
Brett Cannon1eb32c22014-10-10 16:26:45 -0400105#include "clinic/arraymodule.c.h"
106
Martin v. Löwis99866332002-03-01 10:27:01 +0000107#define array_Check(op) PyObject_TypeCheck(op, &Arraytype)
Christian Heimes90aa7642007-12-19 02:45:37 +0000108#define array_CheckExact(op) (Py_TYPE(op) == &Arraytype)
Guido van Rossum778983b1993-02-19 15:55:02 +0000109
Raymond Hettinger6e2ee862004-03-14 04:37:50 +0000110static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000111array_resize(arrayobject *self, Py_ssize_t newsize)
Raymond Hettinger6e2ee862004-03-14 04:37:50 +0000112{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000113 char *items;
114 size_t _new_size;
Raymond Hettinger6e2ee862004-03-14 04:37:50 +0000115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000116 if (self->ob_exports > 0 && newsize != Py_SIZE(self)) {
117 PyErr_SetString(PyExc_BufferError,
118 "cannot resize an array that is exporting buffers");
119 return -1;
120 }
Antoine Pitrou3ad3a0d2008-12-18 17:08:32 +0000121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000122 /* Bypass realloc() when a previous overallocation is large enough
123 to accommodate the newsize. If the newsize is 16 smaller than the
124 current size, then proceed with the realloc() to shrink the array.
125 */
Raymond Hettinger6e2ee862004-03-14 04:37:50 +0000126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000127 if (self->allocated >= newsize &&
128 Py_SIZE(self) < newsize + 16 &&
129 self->ob_item != NULL) {
130 Py_SIZE(self) = newsize;
131 return 0;
132 }
Raymond Hettinger6e2ee862004-03-14 04:37:50 +0000133
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000134 if (newsize == 0) {
135 PyMem_FREE(self->ob_item);
136 self->ob_item = NULL;
137 Py_SIZE(self) = 0;
138 self->allocated = 0;
139 return 0;
140 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000142 /* This over-allocates proportional to the array size, making room
143 * for additional growth. The over-allocation is mild, but is
144 * enough to give linear-time amortized behavior over a long
145 * sequence of appends() in the presence of a poorly-performing
146 * system realloc().
147 * The growth pattern is: 0, 4, 8, 16, 25, 34, 46, 56, 67, 79, ...
148 * Note, the pattern starts out the same as for lists but then
149 * grows at a smaller rate so that larger arrays only overallocate
150 * by about 1/16th -- this is done because arrays are presumed to be more
151 * memory critical.
152 */
Raymond Hettinger6e2ee862004-03-14 04:37:50 +0000153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000154 _new_size = (newsize >> 4) + (Py_SIZE(self) < 8 ? 3 : 7) + newsize;
155 items = self->ob_item;
156 /* XXX The following multiplication and division does not optimize away
157 like it does for lists since the size is not known at compile time */
158 if (_new_size <= ((~(size_t)0) / self->ob_descr->itemsize))
159 PyMem_RESIZE(items, char, (_new_size * self->ob_descr->itemsize));
160 else
161 items = NULL;
162 if (items == NULL) {
163 PyErr_NoMemory();
164 return -1;
165 }
166 self->ob_item = items;
167 Py_SIZE(self) = newsize;
168 self->allocated = _new_size;
169 return 0;
Raymond Hettinger6e2ee862004-03-14 04:37:50 +0000170}
171
Tim Petersbb307342000-09-10 05:22:54 +0000172/****************************************************************************
173Get and Set functions for each type.
174A Get function takes an arrayobject* and an integer index, returning the
175array value at that index wrapped in an appropriate PyObject*.
176A Set function takes an arrayobject, integer index, and PyObject*; sets
177the array value at that index to the raw C data extracted from the PyObject*,
178and returns 0 if successful, else nonzero on failure (PyObject* not of an
179appropriate type or value).
180Note that the basic Get and Set functions do NOT check that the index is
181in bounds; that's the responsibility of the caller.
182****************************************************************************/
Guido van Rossum778983b1993-02-19 15:55:02 +0000183
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000184static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000185b_getitem(arrayobject *ap, Py_ssize_t i)
Guido van Rossum778983b1993-02-19 15:55:02 +0000186{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000187 long x = ((char *)ap->ob_item)[i];
188 if (x >= 128)
189 x -= 256;
190 return PyLong_FromLong(x);
Guido van Rossum778983b1993-02-19 15:55:02 +0000191}
192
193static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000194b_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
Guido van Rossum778983b1993-02-19 15:55:02 +0000195{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000196 short x;
197 /* PyArg_Parse's 'b' formatter is for an unsigned char, therefore
198 must use the next size up that is signed ('h') and manually do
199 the overflow checking */
200 if (!PyArg_Parse(v, "h;array item must be integer", &x))
201 return -1;
202 else if (x < -128) {
203 PyErr_SetString(PyExc_OverflowError,
204 "signed char is less than minimum");
205 return -1;
206 }
207 else if (x > 127) {
208 PyErr_SetString(PyExc_OverflowError,
209 "signed char is greater than maximum");
210 return -1;
211 }
212 if (i >= 0)
213 ((char *)ap->ob_item)[i] = (char)x;
214 return 0;
Guido van Rossum778983b1993-02-19 15:55:02 +0000215}
216
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000217static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000218BB_getitem(arrayobject *ap, Py_ssize_t i)
Guido van Rossum549ab711997-01-03 19:09:47 +0000219{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000220 long x = ((unsigned char *)ap->ob_item)[i];
221 return PyLong_FromLong(x);
Guido van Rossum549ab711997-01-03 19:09:47 +0000222}
223
Fred Drake541dc3b2000-06-28 17:49:30 +0000224static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000225BB_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
Fred Drake541dc3b2000-06-28 17:49:30 +0000226{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000227 unsigned char x;
228 /* 'B' == unsigned char, maps to PyArg_Parse's 'b' formatter */
229 if (!PyArg_Parse(v, "b;array item must be integer", &x))
230 return -1;
231 if (i >= 0)
232 ((char *)ap->ob_item)[i] = x;
233 return 0;
Fred Drake541dc3b2000-06-28 17:49:30 +0000234}
Guido van Rossum549ab711997-01-03 19:09:47 +0000235
Martin v. Löwis99866332002-03-01 10:27:01 +0000236static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000237u_getitem(arrayobject *ap, Py_ssize_t i)
Martin v. Löwis99866332002-03-01 10:27:01 +0000238{
Victor Stinner62bb3942012-08-06 00:46:05 +0200239 return PyUnicode_FromUnicode(&((Py_UNICODE *) ap->ob_item)[i], 1);
Martin v. Löwis99866332002-03-01 10:27:01 +0000240}
241
242static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000243u_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
Martin v. Löwis99866332002-03-01 10:27:01 +0000244{
Victor Stinner62bb3942012-08-06 00:46:05 +0200245 Py_UNICODE *p;
246 Py_ssize_t len;
Martin v. Löwis99866332002-03-01 10:27:01 +0000247
Victor Stinner62bb3942012-08-06 00:46:05 +0200248 if (!PyArg_Parse(v, "u#;array item must be unicode character", &p, &len))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000249 return -1;
Victor Stinner62bb3942012-08-06 00:46:05 +0200250 if (len != 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000251 PyErr_SetString(PyExc_TypeError,
252 "array item must be unicode character");
253 return -1;
254 }
255 if (i >= 0)
Victor Stinner62bb3942012-08-06 00:46:05 +0200256 ((Py_UNICODE *)ap->ob_item)[i] = p[0];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000257 return 0;
Martin v. Löwis99866332002-03-01 10:27:01 +0000258}
Martin v. Löwis99866332002-03-01 10:27:01 +0000259
Travis E. Oliphantd5c0add2007-10-12 22:05:15 +0000260
Guido van Rossum549ab711997-01-03 19:09:47 +0000261static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000262h_getitem(arrayobject *ap, Py_ssize_t i)
Guido van Rossum778983b1993-02-19 15:55:02 +0000263{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000264 return PyLong_FromLong((long) ((short *)ap->ob_item)[i]);
Guido van Rossum778983b1993-02-19 15:55:02 +0000265}
266
Travis E. Oliphantd5c0add2007-10-12 22:05:15 +0000267
Guido van Rossum778983b1993-02-19 15:55:02 +0000268static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000269h_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
Guido van Rossum778983b1993-02-19 15:55:02 +0000270{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000271 short x;
272 /* 'h' == signed short, maps to PyArg_Parse's 'h' formatter */
273 if (!PyArg_Parse(v, "h;array item must be integer", &x))
274 return -1;
275 if (i >= 0)
276 ((short *)ap->ob_item)[i] = x;
277 return 0;
Guido van Rossum778983b1993-02-19 15:55:02 +0000278}
279
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000280static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000281HH_getitem(arrayobject *ap, Py_ssize_t i)
Guido van Rossum549ab711997-01-03 19:09:47 +0000282{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000283 return PyLong_FromLong((long) ((unsigned short *)ap->ob_item)[i]);
Guido van Rossum549ab711997-01-03 19:09:47 +0000284}
285
Fred Drake541dc3b2000-06-28 17:49:30 +0000286static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000287HH_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
Fred Drake541dc3b2000-06-28 17:49:30 +0000288{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000289 int x;
290 /* PyArg_Parse's 'h' formatter is for a signed short, therefore
291 must use the next size up and manually do the overflow checking */
292 if (!PyArg_Parse(v, "i;array item must be integer", &x))
293 return -1;
294 else if (x < 0) {
295 PyErr_SetString(PyExc_OverflowError,
296 "unsigned short is less than minimum");
297 return -1;
298 }
299 else if (x > USHRT_MAX) {
300 PyErr_SetString(PyExc_OverflowError,
301 "unsigned short is greater than maximum");
302 return -1;
303 }
304 if (i >= 0)
305 ((short *)ap->ob_item)[i] = (short)x;
306 return 0;
Fred Drake541dc3b2000-06-28 17:49:30 +0000307}
Guido van Rossum549ab711997-01-03 19:09:47 +0000308
309static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000310i_getitem(arrayobject *ap, Py_ssize_t i)
Guido van Rossume77a7571993-11-03 15:01:26 +0000311{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000312 return PyLong_FromLong((long) ((int *)ap->ob_item)[i]);
Guido van Rossume77a7571993-11-03 15:01:26 +0000313}
314
315static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000316i_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
Guido van Rossume77a7571993-11-03 15:01:26 +0000317{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000318 int x;
319 /* 'i' == signed int, maps to PyArg_Parse's 'i' formatter */
320 if (!PyArg_Parse(v, "i;array item must be integer", &x))
321 return -1;
322 if (i >= 0)
323 ((int *)ap->ob_item)[i] = x;
324 return 0;
Guido van Rossume77a7571993-11-03 15:01:26 +0000325}
326
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000327static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000328II_getitem(arrayobject *ap, Py_ssize_t i)
Guido van Rossum549ab711997-01-03 19:09:47 +0000329{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 return PyLong_FromUnsignedLong(
331 (unsigned long) ((unsigned int *)ap->ob_item)[i]);
Guido van Rossum549ab711997-01-03 19:09:47 +0000332}
333
334static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000335II_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
Guido van Rossum549ab711997-01-03 19:09:47 +0000336{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000337 unsigned long x;
338 if (PyLong_Check(v)) {
339 x = PyLong_AsUnsignedLong(v);
340 if (x == (unsigned long) -1 && PyErr_Occurred())
341 return -1;
342 }
343 else {
344 long y;
345 if (!PyArg_Parse(v, "l;array item must be integer", &y))
346 return -1;
347 if (y < 0) {
348 PyErr_SetString(PyExc_OverflowError,
349 "unsigned int is less than minimum");
350 return -1;
351 }
352 x = (unsigned long)y;
Tim Petersbb307342000-09-10 05:22:54 +0000353
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000354 }
355 if (x > UINT_MAX) {
356 PyErr_SetString(PyExc_OverflowError,
357 "unsigned int is greater than maximum");
358 return -1;
359 }
Fred Drake541dc3b2000-06-28 17:49:30 +0000360
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000361 if (i >= 0)
362 ((unsigned int *)ap->ob_item)[i] = (unsigned int)x;
363 return 0;
Guido van Rossum549ab711997-01-03 19:09:47 +0000364}
365
366static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000367l_getitem(arrayobject *ap, Py_ssize_t i)
Guido van Rossum778983b1993-02-19 15:55:02 +0000368{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000369 return PyLong_FromLong(((long *)ap->ob_item)[i]);
Guido van Rossum778983b1993-02-19 15:55:02 +0000370}
371
372static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000373l_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
Guido van Rossum778983b1993-02-19 15:55:02 +0000374{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 long x;
376 if (!PyArg_Parse(v, "l;array item must be integer", &x))
377 return -1;
378 if (i >= 0)
379 ((long *)ap->ob_item)[i] = x;
380 return 0;
Guido van Rossum778983b1993-02-19 15:55:02 +0000381}
382
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000383static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000384LL_getitem(arrayobject *ap, Py_ssize_t i)
Guido van Rossum549ab711997-01-03 19:09:47 +0000385{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000386 return PyLong_FromUnsignedLong(((unsigned long *)ap->ob_item)[i]);
Guido van Rossum549ab711997-01-03 19:09:47 +0000387}
388
389static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000390LL_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
Guido van Rossum549ab711997-01-03 19:09:47 +0000391{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000392 unsigned long x;
393 if (PyLong_Check(v)) {
394 x = PyLong_AsUnsignedLong(v);
395 if (x == (unsigned long) -1 && PyErr_Occurred())
396 return -1;
397 }
398 else {
399 long y;
400 if (!PyArg_Parse(v, "l;array item must be integer", &y))
401 return -1;
402 if (y < 0) {
403 PyErr_SetString(PyExc_OverflowError,
404 "unsigned long is less than minimum");
405 return -1;
406 }
407 x = (unsigned long)y;
Tim Petersbb307342000-09-10 05:22:54 +0000408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000409 }
410 if (x > ULONG_MAX) {
411 PyErr_SetString(PyExc_OverflowError,
412 "unsigned long is greater than maximum");
413 return -1;
414 }
Tim Petersbb307342000-09-10 05:22:54 +0000415
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000416 if (i >= 0)
417 ((unsigned long *)ap->ob_item)[i] = x;
418 return 0;
Guido van Rossum549ab711997-01-03 19:09:47 +0000419}
420
Meador Inge1c9f0c92011-09-20 19:55:51 -0500421static PyObject *
422q_getitem(arrayobject *ap, Py_ssize_t i)
423{
424 return PyLong_FromLongLong(((PY_LONG_LONG *)ap->ob_item)[i]);
425}
426
427static int
428q_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
429{
430 PY_LONG_LONG x;
431 if (!PyArg_Parse(v, "L;array item must be integer", &x))
432 return -1;
433 if (i >= 0)
434 ((PY_LONG_LONG *)ap->ob_item)[i] = x;
435 return 0;
436}
437
438static PyObject *
439QQ_getitem(arrayobject *ap, Py_ssize_t i)
440{
441 return PyLong_FromUnsignedLongLong(
442 ((unsigned PY_LONG_LONG *)ap->ob_item)[i]);
443}
444
445static int
446QQ_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
447{
448 unsigned PY_LONG_LONG x;
449 if (PyLong_Check(v)) {
450 x = PyLong_AsUnsignedLongLong(v);
451 if (x == (unsigned PY_LONG_LONG) -1 && PyErr_Occurred())
452 return -1;
453 }
454 else {
455 PY_LONG_LONG y;
456 if (!PyArg_Parse(v, "L;array item must be integer", &y))
457 return -1;
458 if (y < 0) {
459 PyErr_SetString(PyExc_OverflowError,
460 "unsigned long long is less than minimum");
461 return -1;
462 }
463 x = (unsigned PY_LONG_LONG)y;
464 }
465
466 if (i >= 0)
467 ((unsigned PY_LONG_LONG *)ap->ob_item)[i] = x;
468 return 0;
469}
Meador Inge1c9f0c92011-09-20 19:55:51 -0500470
Guido van Rossum549ab711997-01-03 19:09:47 +0000471static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000472f_getitem(arrayobject *ap, Py_ssize_t i)
Guido van Rossum778983b1993-02-19 15:55:02 +0000473{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 return PyFloat_FromDouble((double) ((float *)ap->ob_item)[i]);
Guido van Rossum778983b1993-02-19 15:55:02 +0000475}
476
477static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000478f_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
Guido van Rossum778983b1993-02-19 15:55:02 +0000479{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000480 float x;
481 if (!PyArg_Parse(v, "f;array item must be float", &x))
482 return -1;
483 if (i >= 0)
484 ((float *)ap->ob_item)[i] = x;
485 return 0;
Guido van Rossum778983b1993-02-19 15:55:02 +0000486}
487
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000488static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000489d_getitem(arrayobject *ap, Py_ssize_t i)
Guido van Rossum778983b1993-02-19 15:55:02 +0000490{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000491 return PyFloat_FromDouble(((double *)ap->ob_item)[i]);
Guido van Rossum778983b1993-02-19 15:55:02 +0000492}
493
494static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000495d_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
Guido van Rossum778983b1993-02-19 15:55:02 +0000496{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 double x;
498 if (!PyArg_Parse(v, "d;array item must be float", &x))
499 return -1;
500 if (i >= 0)
501 ((double *)ap->ob_item)[i] = x;
502 return 0;
Guido van Rossum778983b1993-02-19 15:55:02 +0000503}
504
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000505
Alexandre Vassalottiad077152009-07-15 17:49:23 +0000506/* Description of types.
507 *
508 * Don't forget to update typecode_to_mformat_code() if you add a new
509 * typecode.
510 */
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200511static const struct arraydescr descriptors[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 {'b', 1, b_getitem, b_setitem, "b", 1, 1},
513 {'B', 1, BB_getitem, BB_setitem, "B", 1, 0},
Victor Stinner62bb3942012-08-06 00:46:05 +0200514 {'u', sizeof(Py_UNICODE), u_getitem, u_setitem, "u", 0, 0},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000515 {'h', sizeof(short), h_getitem, h_setitem, "h", 1, 1},
516 {'H', sizeof(short), HH_getitem, HH_setitem, "H", 1, 0},
517 {'i', sizeof(int), i_getitem, i_setitem, "i", 1, 1},
518 {'I', sizeof(int), II_getitem, II_setitem, "I", 1, 0},
519 {'l', sizeof(long), l_getitem, l_setitem, "l", 1, 1},
520 {'L', sizeof(long), LL_getitem, LL_setitem, "L", 1, 0},
Meador Inge1c9f0c92011-09-20 19:55:51 -0500521 {'q', sizeof(PY_LONG_LONG), q_getitem, q_setitem, "q", 1, 1},
522 {'Q', sizeof(PY_LONG_LONG), QQ_getitem, QQ_setitem, "Q", 1, 0},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000523 {'f', sizeof(float), f_getitem, f_setitem, "f", 0, 0},
524 {'d', sizeof(double), d_getitem, d_setitem, "d", 0, 0},
525 {'\0', 0, 0, 0, 0, 0, 0} /* Sentinel */
Guido van Rossum778983b1993-02-19 15:55:02 +0000526};
Tim Petersbb307342000-09-10 05:22:54 +0000527
528/****************************************************************************
529Implementations of array object methods.
530****************************************************************************/
Brett Cannon1eb32c22014-10-10 16:26:45 -0400531/*[clinic input]
532class array.array "arrayobject *" "&Arraytype"
533[clinic start generated code]*/
534/*[clinic end generated code: output=da39a3ee5e6b4b0d input=ad43d37e942a8854]*/
Guido van Rossum778983b1993-02-19 15:55:02 +0000535
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000536static PyObject *
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200537newarrayobject(PyTypeObject *type, Py_ssize_t size, const struct arraydescr *descr)
Guido van Rossum778983b1993-02-19 15:55:02 +0000538{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000539 arrayobject *op;
540 size_t nbytes;
Martin v. Löwis99866332002-03-01 10:27:01 +0000541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000542 if (size < 0) {
543 PyErr_BadInternalCall();
544 return NULL;
545 }
Martin v. Löwis99866332002-03-01 10:27:01 +0000546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000547 /* Check for overflow */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +0100548 if (size > PY_SSIZE_T_MAX / descr->itemsize) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000549 return PyErr_NoMemory();
550 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +0100551 nbytes = size * descr->itemsize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000552 op = (arrayobject *) type->tp_alloc(type, 0);
553 if (op == NULL) {
554 return NULL;
555 }
556 op->ob_descr = descr;
557 op->allocated = size;
558 op->weakreflist = NULL;
559 Py_SIZE(op) = size;
560 if (size <= 0) {
561 op->ob_item = NULL;
562 }
563 else {
564 op->ob_item = PyMem_NEW(char, nbytes);
565 if (op->ob_item == NULL) {
566 Py_DECREF(op);
567 return PyErr_NoMemory();
568 }
569 }
570 op->ob_exports = 0;
571 return (PyObject *) op;
Guido van Rossum778983b1993-02-19 15:55:02 +0000572}
573
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000574static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000575getarrayitem(PyObject *op, Py_ssize_t i)
Guido van Rossum778983b1993-02-19 15:55:02 +0000576{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200577 arrayobject *ap;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000578 assert(array_Check(op));
579 ap = (arrayobject *)op;
580 assert(i>=0 && i<Py_SIZE(ap));
581 return (*ap->ob_descr->getitem)(ap, i);
Guido van Rossum778983b1993-02-19 15:55:02 +0000582}
583
584static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000585ins1(arrayobject *self, Py_ssize_t where, PyObject *v)
Guido van Rossum778983b1993-02-19 15:55:02 +0000586{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000587 char *items;
588 Py_ssize_t n = Py_SIZE(self);
589 if (v == NULL) {
590 PyErr_BadInternalCall();
591 return -1;
592 }
593 if ((*self->ob_descr->setitem)(self, -1, v) < 0)
594 return -1;
Raymond Hettinger6e2ee862004-03-14 04:37:50 +0000595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 if (array_resize(self, n+1) == -1)
597 return -1;
598 items = self->ob_item;
599 if (where < 0) {
600 where += n;
601 if (where < 0)
602 where = 0;
603 }
604 if (where > n)
605 where = n;
606 /* appends don't need to call memmove() */
607 if (where != n)
608 memmove(items + (where+1)*self->ob_descr->itemsize,
609 items + where*self->ob_descr->itemsize,
610 (n-where)*self->ob_descr->itemsize);
611 return (*self->ob_descr->setitem)(self, where, v);
Guido van Rossum778983b1993-02-19 15:55:02 +0000612}
613
Guido van Rossum778983b1993-02-19 15:55:02 +0000614/* Methods */
615
616static void
Peter Schneider-Kamp9656abd2000-07-13 21:10:57 +0000617array_dealloc(arrayobject *op)
Guido van Rossum778983b1993-02-19 15:55:02 +0000618{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 if (op->weakreflist != NULL)
620 PyObject_ClearWeakRefs((PyObject *) op);
621 if (op->ob_item != NULL)
622 PyMem_DEL(op->ob_item);
623 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossum778983b1993-02-19 15:55:02 +0000624}
625
Guido van Rossum9d19cb82001-01-18 01:02:55 +0000626static PyObject *
627array_richcompare(PyObject *v, PyObject *w, int op)
Guido van Rossum778983b1993-02-19 15:55:02 +0000628{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000629 arrayobject *va, *wa;
630 PyObject *vi = NULL;
631 PyObject *wi = NULL;
632 Py_ssize_t i, k;
633 PyObject *res;
Guido van Rossum9d19cb82001-01-18 01:02:55 +0000634
Brian Curtindfc80e32011-08-10 20:28:54 -0500635 if (!array_Check(v) || !array_Check(w))
636 Py_RETURN_NOTIMPLEMENTED;
Guido van Rossum9d19cb82001-01-18 01:02:55 +0000637
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 va = (arrayobject *)v;
639 wa = (arrayobject *)w;
Guido van Rossum9d19cb82001-01-18 01:02:55 +0000640
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 if (Py_SIZE(va) != Py_SIZE(wa) && (op == Py_EQ || op == Py_NE)) {
642 /* Shortcut: if the lengths differ, the arrays differ */
643 if (op == Py_EQ)
644 res = Py_False;
645 else
646 res = Py_True;
647 Py_INCREF(res);
648 return res;
649 }
Guido van Rossum9d19cb82001-01-18 01:02:55 +0000650
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000651 /* Search for the first index where items are different */
652 k = 1;
653 for (i = 0; i < Py_SIZE(va) && i < Py_SIZE(wa); i++) {
654 vi = getarrayitem(v, i);
655 wi = getarrayitem(w, i);
656 if (vi == NULL || wi == NULL) {
657 Py_XDECREF(vi);
658 Py_XDECREF(wi);
659 return NULL;
660 }
661 k = PyObject_RichCompareBool(vi, wi, Py_EQ);
662 if (k == 0)
663 break; /* Keeping vi and wi alive! */
664 Py_DECREF(vi);
665 Py_DECREF(wi);
666 if (k < 0)
667 return NULL;
668 }
Guido van Rossum9d19cb82001-01-18 01:02:55 +0000669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 if (k) {
671 /* No more items to compare -- compare sizes */
672 Py_ssize_t vs = Py_SIZE(va);
673 Py_ssize_t ws = Py_SIZE(wa);
674 int cmp;
675 switch (op) {
676 case Py_LT: cmp = vs < ws; break;
677 case Py_LE: cmp = vs <= ws; break;
678 case Py_EQ: cmp = vs == ws; break;
679 case Py_NE: cmp = vs != ws; break;
680 case Py_GT: cmp = vs > ws; break;
681 case Py_GE: cmp = vs >= ws; break;
682 default: return NULL; /* cannot happen */
683 }
684 if (cmp)
685 res = Py_True;
686 else
687 res = Py_False;
688 Py_INCREF(res);
689 return res;
690 }
Guido van Rossum9d19cb82001-01-18 01:02:55 +0000691
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000692 /* We have an item that differs. First, shortcuts for EQ/NE */
693 if (op == Py_EQ) {
694 Py_INCREF(Py_False);
695 res = Py_False;
696 }
697 else if (op == Py_NE) {
698 Py_INCREF(Py_True);
699 res = Py_True;
700 }
701 else {
702 /* Compare the final item again using the proper operator */
703 res = PyObject_RichCompare(vi, wi, op);
704 }
705 Py_DECREF(vi);
706 Py_DECREF(wi);
707 return res;
Guido van Rossum778983b1993-02-19 15:55:02 +0000708}
709
Martin v. Löwis18e16552006-02-15 17:27:45 +0000710static Py_ssize_t
Peter Schneider-Kamp9656abd2000-07-13 21:10:57 +0000711array_length(arrayobject *a)
Guido van Rossum778983b1993-02-19 15:55:02 +0000712{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000713 return Py_SIZE(a);
Guido van Rossum778983b1993-02-19 15:55:02 +0000714}
715
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000716static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000717array_item(arrayobject *a, Py_ssize_t i)
Guido van Rossum778983b1993-02-19 15:55:02 +0000718{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000719 if (i < 0 || i >= Py_SIZE(a)) {
720 PyErr_SetString(PyExc_IndexError, "array index out of range");
721 return NULL;
722 }
723 return getarrayitem((PyObject *)a, i);
Guido van Rossum778983b1993-02-19 15:55:02 +0000724}
725
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000726static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000727array_slice(arrayobject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum778983b1993-02-19 15:55:02 +0000728{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000729 arrayobject *np;
730 if (ilow < 0)
731 ilow = 0;
732 else if (ilow > Py_SIZE(a))
733 ilow = Py_SIZE(a);
734 if (ihigh < 0)
735 ihigh = 0;
736 if (ihigh < ilow)
737 ihigh = ilow;
738 else if (ihigh > Py_SIZE(a))
739 ihigh = Py_SIZE(a);
740 np = (arrayobject *) newarrayobject(&Arraytype, ihigh - ilow, a->ob_descr);
741 if (np == NULL)
742 return NULL;
743 memcpy(np->ob_item, a->ob_item + ilow * a->ob_descr->itemsize,
744 (ihigh-ilow) * a->ob_descr->itemsize);
745 return (PyObject *)np;
Guido van Rossum778983b1993-02-19 15:55:02 +0000746}
747
Brett Cannon1eb32c22014-10-10 16:26:45 -0400748
749/*[clinic input]
750array.array.__copy__
751
752Return a copy of the array.
753[clinic start generated code]*/
754
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000755static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -0400756array_array___copy___impl(arrayobject *self)
757/*[clinic end generated code: output=dec7c3f925d9619e input=ad1ee5b086965f09]*/
Raymond Hettinger3aa82c02004-03-13 18:18:51 +0000758{
Brett Cannon1eb32c22014-10-10 16:26:45 -0400759 return array_slice(self, 0, Py_SIZE(self));
Raymond Hettinger3aa82c02004-03-13 18:18:51 +0000760}
761
Brett Cannon1eb32c22014-10-10 16:26:45 -0400762/*[clinic input]
763array.array.__deepcopy__
764
765 unused: object
766 /
767
768Return a copy of the array.
769[clinic start generated code]*/
770
771static PyObject *
772array_array___deepcopy__(arrayobject *self, PyObject *unused)
773/*[clinic end generated code: output=1ec748d8e14a9faa input=2405ecb4933748c4]*/
774{
775 return array_array___copy___impl(self);
776}
Raymond Hettinger3aa82c02004-03-13 18:18:51 +0000777
778static PyObject *
Peter Schneider-Kamp9656abd2000-07-13 21:10:57 +0000779array_concat(arrayobject *a, PyObject *bb)
Guido van Rossum778983b1993-02-19 15:55:02 +0000780{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 Py_ssize_t size;
782 arrayobject *np;
783 if (!array_Check(bb)) {
784 PyErr_Format(PyExc_TypeError,
785 "can only append array (not \"%.200s\") to array",
786 Py_TYPE(bb)->tp_name);
787 return NULL;
788 }
Guido van Rossum778983b1993-02-19 15:55:02 +0000789#define b ((arrayobject *)bb)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 if (a->ob_descr != b->ob_descr) {
791 PyErr_BadArgument();
792 return NULL;
793 }
794 if (Py_SIZE(a) > PY_SSIZE_T_MAX - Py_SIZE(b)) {
795 return PyErr_NoMemory();
796 }
797 size = Py_SIZE(a) + Py_SIZE(b);
798 np = (arrayobject *) newarrayobject(&Arraytype, size, a->ob_descr);
799 if (np == NULL) {
800 return NULL;
801 }
802 memcpy(np->ob_item, a->ob_item, Py_SIZE(a)*a->ob_descr->itemsize);
803 memcpy(np->ob_item + Py_SIZE(a)*a->ob_descr->itemsize,
804 b->ob_item, Py_SIZE(b)*b->ob_descr->itemsize);
805 return (PyObject *)np;
Guido van Rossum778983b1993-02-19 15:55:02 +0000806#undef b
807}
808
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000809static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000810array_repeat(arrayobject *a, Py_ssize_t n)
Guido van Rossum778983b1993-02-19 15:55:02 +0000811{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 Py_ssize_t size;
813 arrayobject *np;
Georg Brandlc29cc6a2010-12-04 11:02:04 +0000814 Py_ssize_t oldbytes, newbytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000815 if (n < 0)
816 n = 0;
817 if ((Py_SIZE(a) != 0) && (n > PY_SSIZE_T_MAX / Py_SIZE(a))) {
818 return PyErr_NoMemory();
819 }
820 size = Py_SIZE(a) * n;
821 np = (arrayobject *) newarrayobject(&Arraytype, size, a->ob_descr);
822 if (np == NULL)
823 return NULL;
Georg Brandlc29cc6a2010-12-04 11:02:04 +0000824 if (n == 0)
825 return (PyObject *)np;
826 oldbytes = Py_SIZE(a) * a->ob_descr->itemsize;
827 newbytes = oldbytes * n;
828 /* this follows the code in unicode_repeat */
829 if (oldbytes == 1) {
830 memset(np->ob_item, a->ob_item[0], newbytes);
831 } else {
832 Py_ssize_t done = oldbytes;
833 Py_MEMCPY(np->ob_item, a->ob_item, oldbytes);
834 while (done < newbytes) {
835 Py_ssize_t ncopy = (done <= newbytes-done) ? done : newbytes-done;
836 Py_MEMCPY(np->ob_item+done, np->ob_item, ncopy);
837 done += ncopy;
838 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 }
Georg Brandlc29cc6a2010-12-04 11:02:04 +0000840 return (PyObject *)np;
Guido van Rossum778983b1993-02-19 15:55:02 +0000841}
842
843static int
Martin Panter996d72b2016-07-25 02:21:14 +0000844array_del_slice(arrayobject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum778983b1993-02-19 15:55:02 +0000845{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000846 char *item;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000847 Py_ssize_t d; /* Change in size */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 if (ilow < 0)
849 ilow = 0;
850 else if (ilow > Py_SIZE(a))
851 ilow = Py_SIZE(a);
852 if (ihigh < 0)
853 ihigh = 0;
854 if (ihigh < ilow)
855 ihigh = ilow;
856 else if (ihigh > Py_SIZE(a))
857 ihigh = Py_SIZE(a);
858 item = a->ob_item;
Martin Panter996d72b2016-07-25 02:21:14 +0000859 d = ihigh-ilow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000860 /* Issue #4509: If the array has exported buffers and the slice
861 assignment would change the size of the array, fail early to make
862 sure we don't modify it. */
863 if (d != 0 && a->ob_exports > 0) {
864 PyErr_SetString(PyExc_BufferError,
865 "cannot resize an array that is exporting buffers");
866 return -1;
867 }
Martin Panter996d72b2016-07-25 02:21:14 +0000868 if (d > 0) { /* Delete d items */
869 memmove(item + (ihigh-d)*a->ob_descr->itemsize,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000870 item + ihigh*a->ob_descr->itemsize,
871 (Py_SIZE(a)-ihigh)*a->ob_descr->itemsize);
Martin Panter996d72b2016-07-25 02:21:14 +0000872 if (array_resize(a, Py_SIZE(a) - d) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000873 return -1;
874 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000875 return 0;
Guido van Rossum778983b1993-02-19 15:55:02 +0000876}
877
878static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000879array_ass_item(arrayobject *a, Py_ssize_t i, PyObject *v)
Guido van Rossum778983b1993-02-19 15:55:02 +0000880{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 if (i < 0 || i >= Py_SIZE(a)) {
882 PyErr_SetString(PyExc_IndexError,
883 "array assignment index out of range");
884 return -1;
885 }
886 if (v == NULL)
Martin Panter996d72b2016-07-25 02:21:14 +0000887 return array_del_slice(a, i, i+1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000888 return (*a->ob_descr->setitem)(a, i, v);
Guido van Rossum778983b1993-02-19 15:55:02 +0000889}
890
891static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000892setarrayitem(PyObject *a, Py_ssize_t i, PyObject *v)
Guido van Rossum778983b1993-02-19 15:55:02 +0000893{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 assert(array_Check(a));
895 return array_ass_item((arrayobject *)a, i, v);
Guido van Rossum778983b1993-02-19 15:55:02 +0000896}
897
Martin v. Löwis99866332002-03-01 10:27:01 +0000898static int
Raymond Hettinger49f9bd12004-03-14 05:43:59 +0000899array_iter_extend(arrayobject *self, PyObject *bb)
900{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000901 PyObject *it, *v;
Raymond Hettinger49f9bd12004-03-14 05:43:59 +0000902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000903 it = PyObject_GetIter(bb);
904 if (it == NULL)
905 return -1;
Raymond Hettinger49f9bd12004-03-14 05:43:59 +0000906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 while ((v = PyIter_Next(it)) != NULL) {
Mark Dickinson346f0af2010-08-06 09:36:57 +0000908 if (ins1(self, Py_SIZE(self), v) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000909 Py_DECREF(v);
910 Py_DECREF(it);
911 return -1;
912 }
913 Py_DECREF(v);
914 }
915 Py_DECREF(it);
916 if (PyErr_Occurred())
917 return -1;
918 return 0;
Raymond Hettinger49f9bd12004-03-14 05:43:59 +0000919}
920
921static int
Martin v. Löwis99866332002-03-01 10:27:01 +0000922array_do_extend(arrayobject *self, PyObject *bb)
923{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 Py_ssize_t size, oldsize, bbsize;
Martin v. Löwis99866332002-03-01 10:27:01 +0000925
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 if (!array_Check(bb))
927 return array_iter_extend(self, bb);
928#define b ((arrayobject *)bb)
929 if (self->ob_descr != b->ob_descr) {
930 PyErr_SetString(PyExc_TypeError,
931 "can only extend with array of same kind");
932 return -1;
933 }
934 if ((Py_SIZE(self) > PY_SSIZE_T_MAX - Py_SIZE(b)) ||
935 ((Py_SIZE(self) + Py_SIZE(b)) > PY_SSIZE_T_MAX / self->ob_descr->itemsize)) {
936 PyErr_NoMemory();
937 return -1;
938 }
939 oldsize = Py_SIZE(self);
940 /* Get the size of bb before resizing the array since bb could be self. */
941 bbsize = Py_SIZE(bb);
942 size = oldsize + Py_SIZE(b);
943 if (array_resize(self, size) == -1)
944 return -1;
945 memcpy(self->ob_item + oldsize * self->ob_descr->itemsize,
946 b->ob_item, bbsize * b->ob_descr->itemsize);
947
948 return 0;
Martin v. Löwis99866332002-03-01 10:27:01 +0000949#undef b
950}
951
952static PyObject *
953array_inplace_concat(arrayobject *self, PyObject *bb)
954{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 if (!array_Check(bb)) {
956 PyErr_Format(PyExc_TypeError,
957 "can only extend array with array (not \"%.200s\")",
958 Py_TYPE(bb)->tp_name);
959 return NULL;
960 }
961 if (array_do_extend(self, bb) == -1)
962 return NULL;
963 Py_INCREF(self);
964 return (PyObject *)self;
Martin v. Löwis99866332002-03-01 10:27:01 +0000965}
966
967static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000968array_inplace_repeat(arrayobject *self, Py_ssize_t n)
Martin v. Löwis99866332002-03-01 10:27:01 +0000969{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000970 char *items, *p;
971 Py_ssize_t size, i;
Martin v. Löwis99866332002-03-01 10:27:01 +0000972
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000973 if (Py_SIZE(self) > 0) {
974 if (n < 0)
975 n = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000976 if ((self->ob_descr->itemsize != 0) &&
977 (Py_SIZE(self) > PY_SSIZE_T_MAX / self->ob_descr->itemsize)) {
978 return PyErr_NoMemory();
979 }
980 size = Py_SIZE(self) * self->ob_descr->itemsize;
981 if (n > 0 && size > PY_SSIZE_T_MAX / n) {
982 return PyErr_NoMemory();
983 }
984 if (array_resize(self, n * Py_SIZE(self)) == -1)
985 return NULL;
986 items = p = self->ob_item;
987 for (i = 1; i < n; i++) {
988 p += size;
989 memcpy(p, items, size);
990 }
991 }
992 Py_INCREF(self);
993 return (PyObject *)self;
Martin v. Löwis99866332002-03-01 10:27:01 +0000994}
995
996
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000997static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000998ins(arrayobject *self, Py_ssize_t where, PyObject *v)
Guido van Rossum778983b1993-02-19 15:55:02 +0000999{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001000 if (ins1(self, where, v) != 0)
1001 return NULL;
1002 Py_INCREF(Py_None);
1003 return Py_None;
Guido van Rossum778983b1993-02-19 15:55:02 +00001004}
1005
Brett Cannon1eb32c22014-10-10 16:26:45 -04001006/*[clinic input]
1007array.array.count
1008
1009 v: object
1010 /
1011
1012Return number of occurrences of v in the array.
1013[clinic start generated code]*/
1014
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001015static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001016array_array_count(arrayobject *self, PyObject *v)
1017/*[clinic end generated code: output=3dd3624bf7135a3a input=d9bce9d65e39d1f5]*/
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001018{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 Py_ssize_t count = 0;
1020 Py_ssize_t i;
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001022 for (i = 0; i < Py_SIZE(self); i++) {
Victor Stinner0b142e22013-07-17 23:01:30 +02001023 PyObject *selfi;
1024 int cmp;
1025
1026 selfi = getarrayitem((PyObject *)self, i);
1027 if (selfi == NULL)
1028 return NULL;
1029 cmp = PyObject_RichCompareBool(selfi, v, Py_EQ);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001030 Py_DECREF(selfi);
1031 if (cmp > 0)
1032 count++;
1033 else if (cmp < 0)
1034 return NULL;
1035 }
1036 return PyLong_FromSsize_t(count);
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001037}
1038
Brett Cannon1eb32c22014-10-10 16:26:45 -04001039
1040/*[clinic input]
1041array.array.index
1042
1043 v: object
1044 /
1045
1046Return index of first occurrence of v in the array.
1047[clinic start generated code]*/
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001048
1049static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001050array_array_index(arrayobject *self, PyObject *v)
1051/*[clinic end generated code: output=d48498d325602167 input=cf619898c6649d08]*/
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001052{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 Py_ssize_t i;
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055 for (i = 0; i < Py_SIZE(self); i++) {
Victor Stinner0b142e22013-07-17 23:01:30 +02001056 PyObject *selfi;
1057 int cmp;
1058
1059 selfi = getarrayitem((PyObject *)self, i);
1060 if (selfi == NULL)
1061 return NULL;
1062 cmp = PyObject_RichCompareBool(selfi, v, Py_EQ);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001063 Py_DECREF(selfi);
1064 if (cmp > 0) {
1065 return PyLong_FromLong((long)i);
1066 }
1067 else if (cmp < 0)
1068 return NULL;
1069 }
1070 PyErr_SetString(PyExc_ValueError, "array.index(x): x not in list");
1071 return NULL;
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001072}
1073
Raymond Hettinger625812f2003-01-07 01:58:52 +00001074static int
1075array_contains(arrayobject *self, PyObject *v)
1076{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001077 Py_ssize_t i;
1078 int cmp;
Raymond Hettinger625812f2003-01-07 01:58:52 +00001079
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001080 for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(self); i++) {
1081 PyObject *selfi = getarrayitem((PyObject *)self, i);
Victor Stinner0b142e22013-07-17 23:01:30 +02001082 if (selfi == NULL)
Victor Stinner4755bea2013-07-18 01:12:35 +02001083 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 cmp = PyObject_RichCompareBool(selfi, v, Py_EQ);
1085 Py_DECREF(selfi);
1086 }
1087 return cmp;
Raymond Hettinger625812f2003-01-07 01:58:52 +00001088}
1089
Brett Cannon1eb32c22014-10-10 16:26:45 -04001090/*[clinic input]
1091array.array.remove
1092
1093 v: object
1094 /
1095
1096Remove the first occurrence of v in the array.
1097[clinic start generated code]*/
1098
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001099static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001100array_array_remove(arrayobject *self, PyObject *v)
1101/*[clinic end generated code: output=bef06be9fdf9dceb input=0b1e5aed25590027]*/
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001102{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001103 int i;
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001104
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001105 for (i = 0; i < Py_SIZE(self); i++) {
Victor Stinner0b142e22013-07-17 23:01:30 +02001106 PyObject *selfi;
1107 int cmp;
1108
1109 selfi = getarrayitem((PyObject *)self,i);
1110 if (selfi == NULL)
1111 return NULL;
1112 cmp = PyObject_RichCompareBool(selfi, v, Py_EQ);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001113 Py_DECREF(selfi);
1114 if (cmp > 0) {
Martin Panter996d72b2016-07-25 02:21:14 +00001115 if (array_del_slice(self, i, i+1) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001116 return NULL;
1117 Py_INCREF(Py_None);
1118 return Py_None;
1119 }
1120 else if (cmp < 0)
1121 return NULL;
1122 }
1123 PyErr_SetString(PyExc_ValueError, "array.remove(x): x not in list");
1124 return NULL;
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001125}
1126
Brett Cannon1eb32c22014-10-10 16:26:45 -04001127/*[clinic input]
1128array.array.pop
1129
1130 i: Py_ssize_t = -1
1131 /
1132
1133Return the i-th element and delete it from the array.
1134
1135i defaults to -1.
1136[clinic start generated code]*/
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001137
1138static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001139array_array_pop_impl(arrayobject *self, Py_ssize_t i)
1140/*[clinic end generated code: output=bc1f0c54fe5308e4 input=8e5feb4c1a11cd44]*/
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001141{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142 PyObject *v;
Brett Cannon1eb32c22014-10-10 16:26:45 -04001143
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001144 if (Py_SIZE(self) == 0) {
1145 /* Special-case most common failure cause */
1146 PyErr_SetString(PyExc_IndexError, "pop from empty array");
1147 return NULL;
1148 }
1149 if (i < 0)
1150 i += Py_SIZE(self);
1151 if (i < 0 || i >= Py_SIZE(self)) {
1152 PyErr_SetString(PyExc_IndexError, "pop index out of range");
1153 return NULL;
1154 }
Victor Stinner0b142e22013-07-17 23:01:30 +02001155 v = getarrayitem((PyObject *)self, i);
1156 if (v == NULL)
1157 return NULL;
Martin Panter996d72b2016-07-25 02:21:14 +00001158 if (array_del_slice(self, i, i+1) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001159 Py_DECREF(v);
1160 return NULL;
1161 }
1162 return v;
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001163}
1164
Brett Cannon1eb32c22014-10-10 16:26:45 -04001165/*[clinic input]
1166array.array.extend
1167
1168 bb: object
1169 /
1170
1171Append items to the end of the array.
1172[clinic start generated code]*/
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001173
1174static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001175array_array_extend(arrayobject *self, PyObject *bb)
1176/*[clinic end generated code: output=bbddbc8e8bef871d input=43be86aba5c31e44]*/
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001177{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178 if (array_do_extend(self, bb) == -1)
1179 return NULL;
1180 Py_INCREF(Py_None);
1181 return Py_None;
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001182}
1183
Brett Cannon1eb32c22014-10-10 16:26:45 -04001184/*[clinic input]
1185array.array.insert
1186
1187 i: Py_ssize_t
1188 v: object
1189 /
1190
1191Insert a new item v into the array before position i.
1192[clinic start generated code]*/
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001193
1194static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001195array_array_insert_impl(arrayobject *self, Py_ssize_t i, PyObject *v)
1196/*[clinic end generated code: output=5a3648e278348564 input=5577d1b4383e9313]*/
Guido van Rossum778983b1993-02-19 15:55:02 +00001197{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001198 return ins(self, i, v);
Guido van Rossum778983b1993-02-19 15:55:02 +00001199}
1200
Brett Cannon1eb32c22014-10-10 16:26:45 -04001201/*[clinic input]
1202array.array.buffer_info
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001203
Brett Cannon1eb32c22014-10-10 16:26:45 -04001204Return a tuple (address, length) giving the current memory address and the length in items of the buffer used to hold array's contents.
1205
1206The length should be multiplied by the itemsize attribute to calculate
1207the buffer length in bytes.
1208[clinic start generated code]*/
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001209
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001210static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001211array_array_buffer_info_impl(arrayobject *self)
1212/*[clinic end generated code: output=9b2a4ec3ae7e98e7 input=a58bae5c6e1ac6a6]*/
Guido van Rossumde4a4ca1997-08-12 14:55:56 +00001213{
Victor Stinner541067a2013-11-14 01:27:12 +01001214 PyObject *retval = NULL, *v;
1215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001216 retval = PyTuple_New(2);
1217 if (!retval)
1218 return NULL;
Fred Drake541dc3b2000-06-28 17:49:30 +00001219
Victor Stinner541067a2013-11-14 01:27:12 +01001220 v = PyLong_FromVoidPtr(self->ob_item);
1221 if (v == NULL) {
1222 Py_DECREF(retval);
1223 return NULL;
1224 }
1225 PyTuple_SET_ITEM(retval, 0, v);
1226
Serhiy Storchaka9e941d62016-06-23 23:55:34 +03001227 v = PyLong_FromSsize_t(Py_SIZE(self));
Victor Stinner541067a2013-11-14 01:27:12 +01001228 if (v == NULL) {
1229 Py_DECREF(retval);
1230 return NULL;
1231 }
1232 PyTuple_SET_ITEM(retval, 1, v);
Fred Drake541dc3b2000-06-28 17:49:30 +00001233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 return retval;
Guido van Rossumde4a4ca1997-08-12 14:55:56 +00001235}
1236
Brett Cannon1eb32c22014-10-10 16:26:45 -04001237/*[clinic input]
1238array.array.append
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001239
Brett Cannon1eb32c22014-10-10 16:26:45 -04001240 v: object
1241 /
1242
1243Append new value v to the end of the array.
1244[clinic start generated code]*/
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001245
Guido van Rossumde4a4ca1997-08-12 14:55:56 +00001246static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001247array_array_append(arrayobject *self, PyObject *v)
1248/*[clinic end generated code: output=745a0669bf8db0e2 input=0b98d9d78e78f0fa]*/
Guido van Rossum778983b1993-02-19 15:55:02 +00001249{
Mark Dickinson346f0af2010-08-06 09:36:57 +00001250 return ins(self, Py_SIZE(self), v);
Guido van Rossum778983b1993-02-19 15:55:02 +00001251}
1252
Brett Cannon1eb32c22014-10-10 16:26:45 -04001253/*[clinic input]
1254array.array.byteswap
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001255
Brett Cannon1eb32c22014-10-10 16:26:45 -04001256Byteswap all items of the array.
1257
1258If the items in the array are not 1, 2, 4, or 8 bytes in size, RuntimeError is
1259raised.
1260[clinic start generated code]*/
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001261
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001262static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001263array_array_byteswap_impl(arrayobject *self)
1264/*[clinic end generated code: output=5f8236cbdf0d90b5 input=6a85591b950a0186]*/
Guido van Rossum778983b1993-02-19 15:55:02 +00001265{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001266 char *p;
1267 Py_ssize_t i;
Fred Drakebf272981999-12-03 17:15:30 +00001268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001269 switch (self->ob_descr->itemsize) {
1270 case 1:
1271 break;
1272 case 2:
1273 for (p = self->ob_item, i = Py_SIZE(self); --i >= 0; p += 2) {
1274 char p0 = p[0];
1275 p[0] = p[1];
1276 p[1] = p0;
1277 }
1278 break;
1279 case 4:
1280 for (p = self->ob_item, i = Py_SIZE(self); --i >= 0; p += 4) {
1281 char p0 = p[0];
1282 char p1 = p[1];
1283 p[0] = p[3];
1284 p[1] = p[2];
1285 p[2] = p1;
1286 p[3] = p0;
1287 }
1288 break;
1289 case 8:
1290 for (p = self->ob_item, i = Py_SIZE(self); --i >= 0; p += 8) {
1291 char p0 = p[0];
1292 char p1 = p[1];
1293 char p2 = p[2];
1294 char p3 = p[3];
1295 p[0] = p[7];
1296 p[1] = p[6];
1297 p[2] = p[5];
1298 p[3] = p[4];
1299 p[4] = p3;
1300 p[5] = p2;
1301 p[6] = p1;
1302 p[7] = p0;
1303 }
1304 break;
1305 default:
1306 PyErr_SetString(PyExc_RuntimeError,
1307 "don't know how to byteswap this array type");
1308 return NULL;
1309 }
1310 Py_INCREF(Py_None);
1311 return Py_None;
Guido van Rossum778983b1993-02-19 15:55:02 +00001312}
1313
Brett Cannon1eb32c22014-10-10 16:26:45 -04001314/*[clinic input]
1315array.array.reverse
1316
1317Reverse the order of the items in the array.
1318[clinic start generated code]*/
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001319
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001320static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001321array_array_reverse_impl(arrayobject *self)
1322/*[clinic end generated code: output=c04868b36f6f4089 input=cd904f01b27d966a]*/
Guido van Rossum778983b1993-02-19 15:55:02 +00001323{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001324 Py_ssize_t itemsize = self->ob_descr->itemsize;
1325 char *p, *q;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001326 /* little buffer to hold items while swapping */
1327 char tmp[256]; /* 8 is probably enough -- but why skimp */
1328 assert((size_t)itemsize <= sizeof(tmp));
Guido van Rossume77a7571993-11-03 15:01:26 +00001329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001330 if (Py_SIZE(self) > 1) {
1331 for (p = self->ob_item,
1332 q = self->ob_item + (Py_SIZE(self) - 1)*itemsize;
1333 p < q;
1334 p += itemsize, q -= itemsize) {
1335 /* memory areas guaranteed disjoint, so memcpy
1336 * is safe (& memmove may be slower).
1337 */
1338 memcpy(tmp, p, itemsize);
1339 memcpy(p, q, itemsize);
1340 memcpy(q, tmp, itemsize);
1341 }
1342 }
Tim Petersbb307342000-09-10 05:22:54 +00001343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001344 Py_INCREF(Py_None);
1345 return Py_None;
Guido van Rossum778983b1993-02-19 15:55:02 +00001346}
Guido van Rossume77a7571993-11-03 15:01:26 +00001347
Brett Cannon1eb32c22014-10-10 16:26:45 -04001348/*[clinic input]
1349array.array.fromfile
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001350
Brett Cannon1eb32c22014-10-10 16:26:45 -04001351 f: object
1352 n: Py_ssize_t
1353 /
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001354
Brett Cannon1eb32c22014-10-10 16:26:45 -04001355Read n objects from the file object f and append them to the end of the array.
1356[clinic start generated code]*/
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001357
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001358static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001359array_array_fromfile_impl(arrayobject *self, PyObject *f, Py_ssize_t n)
1360/*[clinic end generated code: output=ec9f600e10f53510 input=e188afe8e58adf40]*/
Guido van Rossum778983b1993-02-19 15:55:02 +00001361{
Serhiy Storchaka04e6dba2015-04-04 17:06:55 +03001362 PyObject *b, *res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001363 Py_ssize_t itemsize = self->ob_descr->itemsize;
Brett Cannon1eb32c22014-10-10 16:26:45 -04001364 Py_ssize_t nbytes;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001365 _Py_IDENTIFIER(read);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001366 int not_enough_bytes;
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001367
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01001368 if (n < 0) {
1369 PyErr_SetString(PyExc_ValueError, "negative count");
1370 return NULL;
1371 }
1372 if (n > PY_SSIZE_T_MAX / itemsize) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001373 PyErr_NoMemory();
1374 return NULL;
1375 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01001376 nbytes = n * itemsize;
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001377
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001378 b = _PyObject_CallMethodId(f, &PyId_read, "n", nbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001379 if (b == NULL)
1380 return NULL;
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001382 if (!PyBytes_Check(b)) {
1383 PyErr_SetString(PyExc_TypeError,
1384 "read() didn't return bytes");
1385 Py_DECREF(b);
1386 return NULL;
1387 }
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001389 not_enough_bytes = (PyBytes_GET_SIZE(b) != nbytes);
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001390
Serhiy Storchaka04e6dba2015-04-04 17:06:55 +03001391 res = array_array_frombytes(self, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001392 Py_DECREF(b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001393 if (res == NULL)
1394 return NULL;
Hirokazu Yamamoto54d0df62009-03-06 03:04:07 +00001395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001396 if (not_enough_bytes) {
1397 PyErr_SetString(PyExc_EOFError,
1398 "read() didn't return enough bytes");
1399 Py_DECREF(res);
1400 return NULL;
1401 }
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001403 return res;
Guido van Rossum778983b1993-02-19 15:55:02 +00001404}
1405
Brett Cannon1eb32c22014-10-10 16:26:45 -04001406/*[clinic input]
1407array.array.tofile
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001408
Brett Cannon1eb32c22014-10-10 16:26:45 -04001409 f: object
1410 /
1411
1412Write all items (as machine values) to the file object f.
1413[clinic start generated code]*/
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001414
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001415static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001416array_array_tofile(arrayobject *self, PyObject *f)
1417/*[clinic end generated code: output=3a2cfa8128df0777 input=b0669a484aab0831]*/
Guido van Rossum778983b1993-02-19 15:55:02 +00001418{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001419 Py_ssize_t nbytes = Py_SIZE(self) * self->ob_descr->itemsize;
1420 /* Write 64K blocks at a time */
1421 /* XXX Make the block size settable */
1422 int BLOCKSIZE = 64*1024;
1423 Py_ssize_t nblocks = (nbytes + BLOCKSIZE - 1) / BLOCKSIZE;
1424 Py_ssize_t i;
Raymond Hettinger36cd2bf2003-01-03 08:24:58 +00001425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001426 if (Py_SIZE(self) == 0)
1427 goto done;
Guido van Rossumb5ddcfd2007-04-11 17:08:28 +00001428
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001429 for (i = 0; i < nblocks; i++) {
1430 char* ptr = self->ob_item + i*BLOCKSIZE;
1431 Py_ssize_t size = BLOCKSIZE;
1432 PyObject *bytes, *res;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001433 _Py_IDENTIFIER(write);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001435 if (i*BLOCKSIZE + size > nbytes)
1436 size = nbytes - i*BLOCKSIZE;
1437 bytes = PyBytes_FromStringAndSize(ptr, size);
1438 if (bytes == NULL)
1439 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001440 res = _PyObject_CallMethodId(f, &PyId_write, "O", bytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001441 Py_DECREF(bytes);
1442 if (res == NULL)
1443 return NULL;
1444 Py_DECREF(res); /* drop write result */
1445 }
Guido van Rossumb5ddcfd2007-04-11 17:08:28 +00001446
1447 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001448 Py_INCREF(Py_None);
1449 return Py_None;
Guido van Rossum778983b1993-02-19 15:55:02 +00001450}
1451
Brett Cannon1eb32c22014-10-10 16:26:45 -04001452/*[clinic input]
1453array.array.fromlist
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001454
Brett Cannon1eb32c22014-10-10 16:26:45 -04001455 list: object
1456 /
1457
1458Append items to array from list.
1459[clinic start generated code]*/
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001460
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001461static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001462array_array_fromlist(arrayobject *self, PyObject *list)
1463/*[clinic end generated code: output=26411c2d228a3e3f input=be2605a96c49680f]*/
Guido van Rossum778983b1993-02-19 15:55:02 +00001464{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001465 Py_ssize_t n;
Raymond Hettinger36cd2bf2003-01-03 08:24:58 +00001466
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001467 if (!PyList_Check(list)) {
1468 PyErr_SetString(PyExc_TypeError, "arg must be list");
1469 return NULL;
1470 }
1471 n = PyList_Size(list);
1472 if (n > 0) {
1473 Py_ssize_t i, old_size;
1474 old_size = Py_SIZE(self);
1475 if (array_resize(self, old_size + n) == -1)
1476 return NULL;
1477 for (i = 0; i < n; i++) {
1478 PyObject *v = PyList_GetItem(list, i);
1479 if ((*self->ob_descr->setitem)(self,
1480 Py_SIZE(self) - n + i, v) != 0) {
1481 array_resize(self, old_size);
1482 return NULL;
1483 }
1484 }
1485 }
1486 Py_INCREF(Py_None);
1487 return Py_None;
Guido van Rossum778983b1993-02-19 15:55:02 +00001488}
1489
Brett Cannon1eb32c22014-10-10 16:26:45 -04001490/*[clinic input]
1491array.array.tolist
1492
1493Convert array to an ordinary list with the same items.
1494[clinic start generated code]*/
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001495
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001496static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001497array_array_tolist_impl(arrayobject *self)
1498/*[clinic end generated code: output=00b60cc9eab8ef89 input=a8d7784a94f86b53]*/
Guido van Rossum778983b1993-02-19 15:55:02 +00001499{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001500 PyObject *list = PyList_New(Py_SIZE(self));
1501 Py_ssize_t i;
Raymond Hettinger36cd2bf2003-01-03 08:24:58 +00001502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001503 if (list == NULL)
1504 return NULL;
1505 for (i = 0; i < Py_SIZE(self); i++) {
1506 PyObject *v = getarrayitem((PyObject *)self, i);
Victor Stinner4755bea2013-07-18 01:12:35 +02001507 if (v == NULL)
1508 goto error;
1509 if (PyList_SetItem(list, i, v) < 0)
1510 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001511 }
1512 return list;
Victor Stinner4755bea2013-07-18 01:12:35 +02001513
1514error:
1515 Py_DECREF(list);
1516 return NULL;
Guido van Rossum778983b1993-02-19 15:55:02 +00001517}
1518
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001519static PyObject *
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001520frombytes(arrayobject *self, Py_buffer *buffer)
Guido van Rossum778983b1993-02-19 15:55:02 +00001521{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001522 int itemsize = self->ob_descr->itemsize;
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001523 Py_ssize_t n;
1524 if (buffer->itemsize != 1) {
1525 PyBuffer_Release(buffer);
Serhiy Storchakab757c832014-12-05 22:25:22 +02001526 PyErr_SetString(PyExc_TypeError, "a bytes-like object is required");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001527 return NULL;
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001528 }
1529 n = buffer->len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001530 if (n % itemsize != 0) {
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001531 PyBuffer_Release(buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001532 PyErr_SetString(PyExc_ValueError,
Serhiy Storchakab757c832014-12-05 22:25:22 +02001533 "bytes length not a multiple of item size");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001534 return NULL;
1535 }
1536 n = n / itemsize;
1537 if (n > 0) {
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001538 Py_ssize_t old_size = Py_SIZE(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001539 if ((n > PY_SSIZE_T_MAX - old_size) ||
1540 ((old_size + n) > PY_SSIZE_T_MAX / itemsize)) {
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001541 PyBuffer_Release(buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001542 return PyErr_NoMemory();
1543 }
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001544 if (array_resize(self, old_size + n) == -1) {
1545 PyBuffer_Release(buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001546 return NULL;
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001547 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001548 memcpy(self->ob_item + old_size * itemsize,
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001549 buffer->buf, n * itemsize);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001550 }
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001551 PyBuffer_Release(buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001552 Py_INCREF(Py_None);
1553 return Py_None;
Guido van Rossum778983b1993-02-19 15:55:02 +00001554}
1555
Brett Cannon1eb32c22014-10-10 16:26:45 -04001556/*[clinic input]
1557array.array.fromstring
1558
Larry Hastingsdbfdc382015-05-04 06:59:46 -07001559 buffer: Py_buffer(accept={str, buffer})
Brett Cannon1eb32c22014-10-10 16:26:45 -04001560 /
1561
1562Appends 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).
1563
1564This method is deprecated. Use frombytes instead.
1565[clinic start generated code]*/
1566
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001567static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001568array_array_fromstring_impl(arrayobject *self, Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07001569/*[clinic end generated code: output=31c4baa779df84ce input=a3341a512e11d773]*/
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001570{
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001571 if (PyErr_WarnEx(PyExc_DeprecationWarning,
1572 "fromstring() is deprecated. Use frombytes() instead.", 2) != 0)
1573 return NULL;
Brett Cannon1eb32c22014-10-10 16:26:45 -04001574 return frombytes(self, buffer);
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001575}
1576
Brett Cannon1eb32c22014-10-10 16:26:45 -04001577/*[clinic input]
1578array.array.frombytes
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001579
Brett Cannon1eb32c22014-10-10 16:26:45 -04001580 buffer: Py_buffer
1581 /
1582
1583Appends 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).
1584[clinic start generated code]*/
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001585
1586static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001587array_array_frombytes_impl(arrayobject *self, Py_buffer *buffer)
1588/*[clinic end generated code: output=d9842c8f7510a516 input=2bbf2b53ebfcc988]*/
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001589{
Brett Cannon1eb32c22014-10-10 16:26:45 -04001590 return frombytes(self, buffer);
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001591}
1592
Brett Cannon1eb32c22014-10-10 16:26:45 -04001593/*[clinic input]
1594array.array.tobytes
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001595
Brett Cannon1eb32c22014-10-10 16:26:45 -04001596Convert the array to an array of machine values and return the bytes representation.
1597[clinic start generated code]*/
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001598
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001599static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001600array_array_tobytes_impl(arrayobject *self)
1601/*[clinic end generated code: output=87318e4edcdc2bb6 input=90ee495f96de34f5]*/
Guido van Rossum778983b1993-02-19 15:55:02 +00001602{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001603 if (Py_SIZE(self) <= PY_SSIZE_T_MAX / self->ob_descr->itemsize) {
1604 return PyBytes_FromStringAndSize(self->ob_item,
1605 Py_SIZE(self) * self->ob_descr->itemsize);
1606 } else {
1607 return PyErr_NoMemory();
1608 }
Guido van Rossum778983b1993-02-19 15:55:02 +00001609}
1610
Brett Cannon1eb32c22014-10-10 16:26:45 -04001611/*[clinic input]
1612array.array.tostring
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001613
Brett Cannon1eb32c22014-10-10 16:26:45 -04001614Convert the array to an array of machine values and return the bytes representation.
1615
1616This method is deprecated. Use tobytes instead.
1617[clinic start generated code]*/
Martin v. Löwis99866332002-03-01 10:27:01 +00001618
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001619static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001620array_array_tostring_impl(arrayobject *self)
1621/*[clinic end generated code: output=7d6bd92745a2c8f3 input=b6c0ddee7b30457e]*/
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001622{
Victor Stinner9f0b51e2010-11-09 09:38:30 +00001623 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001624 "tostring() is deprecated. Use tobytes() instead.", 2) != 0)
1625 return NULL;
Brett Cannon1eb32c22014-10-10 16:26:45 -04001626 return array_array_tobytes_impl(self);
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001627}
1628
Brett Cannon1eb32c22014-10-10 16:26:45 -04001629/*[clinic input]
1630array.array.fromunicode
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001631
Larry Hastings38337d12015-05-07 23:30:09 -07001632 ustr: Py_UNICODE(zeroes=True)
Brett Cannon1eb32c22014-10-10 16:26:45 -04001633 /
1634
1635Extends this array with data from the unicode string ustr.
1636
1637The array must be a unicode type array; otherwise a ValueError is raised.
1638Use array.frombytes(ustr.encode(...)) to append Unicode data to an array of
1639some other type.
1640[clinic start generated code]*/
Martin v. Löwis99866332002-03-01 10:27:01 +00001641
Martin v. Löwis99866332002-03-01 10:27:01 +00001642static PyObject *
Larry Hastings89964c42015-04-14 18:07:59 -04001643array_array_fromunicode_impl(arrayobject *self, Py_UNICODE *ustr,
1644 Py_ssize_clean_t ustr_length)
Larry Hastings38337d12015-05-07 23:30:09 -07001645/*[clinic end generated code: output=ebb72fc16975e06d input=150f00566ffbca6e]*/
Martin v. Löwis99866332002-03-01 10:27:01 +00001646{
Victor Stinner62bb3942012-08-06 00:46:05 +02001647 char typecode;
Martin v. Löwis99866332002-03-01 10:27:01 +00001648
Victor Stinner62bb3942012-08-06 00:46:05 +02001649 typecode = self->ob_descr->typecode;
Gregory P. Smith9504b132012-12-10 20:20:20 -08001650 if (typecode != 'u') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001651 PyErr_SetString(PyExc_ValueError,
1652 "fromunicode() may only be called on "
1653 "unicode type arrays");
1654 return NULL;
1655 }
Brett Cannon1eb32c22014-10-10 16:26:45 -04001656 if (ustr_length > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001657 Py_ssize_t old_size = Py_SIZE(self);
Brett Cannon1eb32c22014-10-10 16:26:45 -04001658 if (array_resize(self, old_size + ustr_length) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001659 return NULL;
Victor Stinner62bb3942012-08-06 00:46:05 +02001660 memcpy(self->ob_item + old_size * sizeof(Py_UNICODE),
Brett Cannon1eb32c22014-10-10 16:26:45 -04001661 ustr, ustr_length * sizeof(Py_UNICODE));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001662 }
Martin v. Löwis99866332002-03-01 10:27:01 +00001663
Brett Cannon1eb32c22014-10-10 16:26:45 -04001664 Py_RETURN_NONE;
Martin v. Löwis99866332002-03-01 10:27:01 +00001665}
1666
Brett Cannon1eb32c22014-10-10 16:26:45 -04001667/*[clinic input]
1668array.array.tounicode
Martin v. Löwis99866332002-03-01 10:27:01 +00001669
Brett Cannon1eb32c22014-10-10 16:26:45 -04001670Extends this array with data from the unicode string ustr.
1671
1672Convert the array to a unicode string. The array must be a unicode type array;
1673otherwise a ValueError is raised. Use array.tobytes().decode() to obtain a
1674unicode string from an array of some other type.
1675[clinic start generated code]*/
Martin v. Löwis99866332002-03-01 10:27:01 +00001676
1677static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001678array_array_tounicode_impl(arrayobject *self)
1679/*[clinic end generated code: output=08e442378336e1ef input=127242eebe70b66d]*/
Martin v. Löwis99866332002-03-01 10:27:01 +00001680{
Victor Stinner62bb3942012-08-06 00:46:05 +02001681 char typecode;
1682 typecode = self->ob_descr->typecode;
Gregory P. Smith9504b132012-12-10 20:20:20 -08001683 if (typecode != 'u') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001684 PyErr_SetString(PyExc_ValueError,
1685 "tounicode() may only be called on unicode type arrays");
1686 return NULL;
1687 }
Victor Stinner62bb3942012-08-06 00:46:05 +02001688 return PyUnicode_FromUnicode((Py_UNICODE *) self->ob_item, Py_SIZE(self));
Martin v. Löwis99866332002-03-01 10:27:01 +00001689}
1690
Brett Cannon1eb32c22014-10-10 16:26:45 -04001691/*[clinic input]
1692array.array.__sizeof__
Martin v. Löwis99866332002-03-01 10:27:01 +00001693
Brett Cannon1eb32c22014-10-10 16:26:45 -04001694Size of the array in memory, in bytes.
1695[clinic start generated code]*/
Martin v. Löwis99866332002-03-01 10:27:01 +00001696
Meador Inge03b4d502012-08-10 22:35:45 -05001697static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04001698array_array___sizeof___impl(arrayobject *self)
1699/*[clinic end generated code: output=d8e1c61ebbe3eaed input=805586565bf2b3c6]*/
Meador Inge03b4d502012-08-10 22:35:45 -05001700{
1701 Py_ssize_t res;
Serhiy Storchaka5c4064e2015-12-19 20:05:25 +02001702 res = _PyObject_SIZE(Py_TYPE(self)) + self->allocated * self->ob_descr->itemsize;
Meador Inge03b4d502012-08-10 22:35:45 -05001703 return PyLong_FromSsize_t(res);
1704}
1705
Martin v. Löwis99866332002-03-01 10:27:01 +00001706
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001707/*********************** Pickling support ************************/
1708
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001709static const struct mformatdescr {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001710 size_t size;
1711 int is_signed;
1712 int is_big_endian;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001713} mformat_descriptors[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001714 {1, 0, 0}, /* 0: UNSIGNED_INT8 */
1715 {1, 1, 0}, /* 1: SIGNED_INT8 */
1716 {2, 0, 0}, /* 2: UNSIGNED_INT16_LE */
1717 {2, 0, 1}, /* 3: UNSIGNED_INT16_BE */
1718 {2, 1, 0}, /* 4: SIGNED_INT16_LE */
1719 {2, 1, 1}, /* 5: SIGNED_INT16_BE */
1720 {4, 0, 0}, /* 6: UNSIGNED_INT32_LE */
1721 {4, 0, 1}, /* 7: UNSIGNED_INT32_BE */
1722 {4, 1, 0}, /* 8: SIGNED_INT32_LE */
1723 {4, 1, 1}, /* 9: SIGNED_INT32_BE */
1724 {8, 0, 0}, /* 10: UNSIGNED_INT64_LE */
1725 {8, 0, 1}, /* 11: UNSIGNED_INT64_BE */
1726 {8, 1, 0}, /* 12: SIGNED_INT64_LE */
1727 {8, 1, 1}, /* 13: SIGNED_INT64_BE */
1728 {4, 0, 0}, /* 14: IEEE_754_FLOAT_LE */
1729 {4, 0, 1}, /* 15: IEEE_754_FLOAT_BE */
1730 {8, 0, 0}, /* 16: IEEE_754_DOUBLE_LE */
1731 {8, 0, 1}, /* 17: IEEE_754_DOUBLE_BE */
1732 {4, 0, 0}, /* 18: UTF16_LE */
1733 {4, 0, 1}, /* 19: UTF16_BE */
1734 {8, 0, 0}, /* 20: UTF32_LE */
1735 {8, 0, 1} /* 21: UTF32_BE */
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001736};
1737
1738
1739/*
1740 * Internal: This function is used to find the machine format of a given
1741 * array type code. This returns UNKNOWN_FORMAT when the machine format cannot
1742 * be found.
1743 */
1744static enum machine_format_code
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02001745typecode_to_mformat_code(char typecode)
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001746{
Christian Heimes743e0cd2012-10-17 23:52:17 +02001747 const int is_big_endian = PY_BIG_ENDIAN;
1748
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001749 size_t intsize;
1750 int is_signed;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001751
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001752 switch (typecode) {
1753 case 'b':
1754 return SIGNED_INT8;
1755 case 'B':
1756 return UNSIGNED_INT8;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001758 case 'u':
Victor Stinner62bb3942012-08-06 00:46:05 +02001759 if (sizeof(Py_UNICODE) == 2) {
1760 return UTF16_LE + is_big_endian;
1761 }
1762 if (sizeof(Py_UNICODE) == 4) {
1763 return UTF32_LE + is_big_endian;
1764 }
1765 return UNKNOWN_FORMAT;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001766
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001767 case 'f':
1768 if (sizeof(float) == 4) {
1769 const float y = 16711938.0;
1770 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1771 return IEEE_754_FLOAT_BE;
1772 if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1773 return IEEE_754_FLOAT_LE;
1774 }
1775 return UNKNOWN_FORMAT;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001777 case 'd':
1778 if (sizeof(double) == 8) {
1779 const double x = 9006104071832581.0;
1780 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1781 return IEEE_754_DOUBLE_BE;
1782 if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1783 return IEEE_754_DOUBLE_LE;
1784 }
1785 return UNKNOWN_FORMAT;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001787 /* Integers */
1788 case 'h':
1789 intsize = sizeof(short);
1790 is_signed = 1;
1791 break;
1792 case 'H':
1793 intsize = sizeof(short);
1794 is_signed = 0;
1795 break;
1796 case 'i':
1797 intsize = sizeof(int);
1798 is_signed = 1;
1799 break;
1800 case 'I':
1801 intsize = sizeof(int);
1802 is_signed = 0;
1803 break;
1804 case 'l':
1805 intsize = sizeof(long);
1806 is_signed = 1;
1807 break;
1808 case 'L':
1809 intsize = sizeof(long);
1810 is_signed = 0;
1811 break;
Meador Inge1c9f0c92011-09-20 19:55:51 -05001812 case 'q':
1813 intsize = sizeof(PY_LONG_LONG);
1814 is_signed = 1;
1815 break;
1816 case 'Q':
1817 intsize = sizeof(PY_LONG_LONG);
1818 is_signed = 0;
1819 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001820 default:
1821 return UNKNOWN_FORMAT;
1822 }
1823 switch (intsize) {
1824 case 2:
1825 return UNSIGNED_INT16_LE + is_big_endian + (2 * is_signed);
1826 case 4:
1827 return UNSIGNED_INT32_LE + is_big_endian + (2 * is_signed);
1828 case 8:
1829 return UNSIGNED_INT64_LE + is_big_endian + (2 * is_signed);
1830 default:
1831 return UNKNOWN_FORMAT;
1832 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001833}
1834
1835/* Forward declaration. */
1836static PyObject *array_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1837
1838/*
1839 * Internal: This function wraps the array constructor--i.e., array_new()--to
1840 * allow the creation of array objects from C code without having to deal
1841 * directly the tuple argument of array_new(). The typecode argument is a
1842 * Unicode character value, like 'i' or 'f' for example, representing an array
1843 * type code. The items argument is a bytes or a list object from which
1844 * contains the initial value of the array.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001845 *
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001846 * On success, this functions returns the array object created. Otherwise,
1847 * NULL is returned to indicate a failure.
1848 */
1849static PyObject *
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02001850make_array(PyTypeObject *arraytype, char typecode, PyObject *items)
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001851{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001852 PyObject *new_args;
1853 PyObject *array_obj;
1854 PyObject *typecode_obj;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001855
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001856 assert(arraytype != NULL);
1857 assert(items != NULL);
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001858
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02001859 typecode_obj = PyUnicode_FromOrdinal(typecode);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001860 if (typecode_obj == NULL)
1861 return NULL;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001862
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001863 new_args = PyTuple_New(2);
1864 if (new_args == NULL)
1865 return NULL;
1866 Py_INCREF(items);
1867 PyTuple_SET_ITEM(new_args, 0, typecode_obj);
1868 PyTuple_SET_ITEM(new_args, 1, items);
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001870 array_obj = array_new(arraytype, new_args, NULL);
1871 Py_DECREF(new_args);
1872 if (array_obj == NULL)
1873 return NULL;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001874
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001875 return array_obj;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001876}
1877
1878/*
1879 * This functions is a special constructor used when unpickling an array. It
1880 * provides a portable way to rebuild an array from its memory representation.
1881 */
Brett Cannon1eb32c22014-10-10 16:26:45 -04001882/*[clinic input]
1883array._array_reconstructor
1884
1885 arraytype: object(type="PyTypeObject *")
Larry Hastingsdbfdc382015-05-04 06:59:46 -07001886 typecode: int(accept={str})
Brett Cannon1eb32c22014-10-10 16:26:45 -04001887 mformat_code: int(type="enum machine_format_code")
1888 items: object
1889 /
1890
1891Internal. Used for pickling support.
1892[clinic start generated code]*/
1893
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001894static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001895array__array_reconstructor_impl(PyObject *module, PyTypeObject *arraytype,
Larry Hastings89964c42015-04-14 18:07:59 -04001896 int typecode,
1897 enum machine_format_code mformat_code,
1898 PyObject *items)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001899/*[clinic end generated code: output=e05263141ba28365 input=2464dc8f4c7736b5]*/
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001900{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001901 PyObject *converted_items;
1902 PyObject *result;
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02001903 const struct arraydescr *descr;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001904
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001905 if (!PyType_Check(arraytype)) {
1906 PyErr_Format(PyExc_TypeError,
1907 "first argument must a type object, not %.200s",
1908 Py_TYPE(arraytype)->tp_name);
1909 return NULL;
1910 }
1911 if (!PyType_IsSubtype(arraytype, &Arraytype)) {
1912 PyErr_Format(PyExc_TypeError,
1913 "%.200s is not a subtype of %.200s",
1914 arraytype->tp_name, Arraytype.tp_name);
1915 return NULL;
1916 }
1917 for (descr = descriptors; descr->typecode != '\0'; descr++) {
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02001918 if ((int)descr->typecode == typecode)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001919 break;
1920 }
1921 if (descr->typecode == '\0') {
1922 PyErr_SetString(PyExc_ValueError,
1923 "second argument must be a valid type code");
1924 return NULL;
1925 }
Larry Hastingsdfbeb162014-10-13 10:39:41 +01001926 if (mformat_code < MACHINE_FORMAT_CODE_MIN ||
1927 mformat_code > MACHINE_FORMAT_CODE_MAX) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001928 PyErr_SetString(PyExc_ValueError,
1929 "third argument must be a valid machine format code.");
1930 return NULL;
1931 }
1932 if (!PyBytes_Check(items)) {
1933 PyErr_Format(PyExc_TypeError,
1934 "fourth argument should be bytes, not %.200s",
1935 Py_TYPE(items)->tp_name);
1936 return NULL;
1937 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001938
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001939 /* Fast path: No decoding has to be done. */
Larry Hastingsdfbeb162014-10-13 10:39:41 +01001940 if (mformat_code == typecode_to_mformat_code((char)typecode) ||
1941 mformat_code == UNKNOWN_FORMAT) {
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02001942 return make_array(arraytype, (char)typecode, items);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001943 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001945 /* Slow path: Decode the byte string according to the given machine
1946 * format code. This occurs when the computer unpickling the array
1947 * object is architecturally different from the one that pickled the
1948 * array.
1949 */
Larry Hastingsdfbeb162014-10-13 10:39:41 +01001950 if (Py_SIZE(items) % mformat_descriptors[mformat_code].size != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001951 PyErr_SetString(PyExc_ValueError,
1952 "string length not a multiple of item size");
1953 return NULL;
1954 }
Larry Hastingsdfbeb162014-10-13 10:39:41 +01001955 switch (mformat_code) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001956 case IEEE_754_FLOAT_LE:
1957 case IEEE_754_FLOAT_BE: {
1958 int i;
Larry Hastingsdfbeb162014-10-13 10:39:41 +01001959 int le = (mformat_code == IEEE_754_FLOAT_LE) ? 1 : 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001960 Py_ssize_t itemcount = Py_SIZE(items) / 4;
1961 const unsigned char *memstr =
1962 (unsigned char *)PyBytes_AS_STRING(items);
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001964 converted_items = PyList_New(itemcount);
1965 if (converted_items == NULL)
1966 return NULL;
1967 for (i = 0; i < itemcount; i++) {
1968 PyObject *pyfloat = PyFloat_FromDouble(
1969 _PyFloat_Unpack4(&memstr[i * 4], le));
1970 if (pyfloat == NULL) {
1971 Py_DECREF(converted_items);
1972 return NULL;
1973 }
1974 PyList_SET_ITEM(converted_items, i, pyfloat);
1975 }
1976 break;
1977 }
1978 case IEEE_754_DOUBLE_LE:
1979 case IEEE_754_DOUBLE_BE: {
1980 int i;
Larry Hastingsdfbeb162014-10-13 10:39:41 +01001981 int le = (mformat_code == IEEE_754_DOUBLE_LE) ? 1 : 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001982 Py_ssize_t itemcount = Py_SIZE(items) / 8;
1983 const unsigned char *memstr =
1984 (unsigned char *)PyBytes_AS_STRING(items);
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001986 converted_items = PyList_New(itemcount);
1987 if (converted_items == NULL)
1988 return NULL;
1989 for (i = 0; i < itemcount; i++) {
1990 PyObject *pyfloat = PyFloat_FromDouble(
1991 _PyFloat_Unpack8(&memstr[i * 8], le));
1992 if (pyfloat == NULL) {
1993 Py_DECREF(converted_items);
1994 return NULL;
1995 }
1996 PyList_SET_ITEM(converted_items, i, pyfloat);
1997 }
1998 break;
1999 }
2000 case UTF16_LE:
2001 case UTF16_BE: {
Larry Hastingsdfbeb162014-10-13 10:39:41 +01002002 int byteorder = (mformat_code == UTF16_LE) ? -1 : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002003 converted_items = PyUnicode_DecodeUTF16(
2004 PyBytes_AS_STRING(items), Py_SIZE(items),
2005 "strict", &byteorder);
2006 if (converted_items == NULL)
2007 return NULL;
2008 break;
2009 }
2010 case UTF32_LE:
2011 case UTF32_BE: {
Larry Hastingsdfbeb162014-10-13 10:39:41 +01002012 int byteorder = (mformat_code == UTF32_LE) ? -1 : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002013 converted_items = PyUnicode_DecodeUTF32(
2014 PyBytes_AS_STRING(items), Py_SIZE(items),
2015 "strict", &byteorder);
2016 if (converted_items == NULL)
2017 return NULL;
2018 break;
2019 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002021 case UNSIGNED_INT8:
2022 case SIGNED_INT8:
2023 case UNSIGNED_INT16_LE:
2024 case UNSIGNED_INT16_BE:
2025 case SIGNED_INT16_LE:
2026 case SIGNED_INT16_BE:
2027 case UNSIGNED_INT32_LE:
2028 case UNSIGNED_INT32_BE:
2029 case SIGNED_INT32_LE:
2030 case SIGNED_INT32_BE:
2031 case UNSIGNED_INT64_LE:
2032 case UNSIGNED_INT64_BE:
2033 case SIGNED_INT64_LE:
2034 case SIGNED_INT64_BE: {
2035 int i;
2036 const struct mformatdescr mf_descr =
Larry Hastingsdfbeb162014-10-13 10:39:41 +01002037 mformat_descriptors[mformat_code];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002038 Py_ssize_t itemcount = Py_SIZE(items) / mf_descr.size;
2039 const unsigned char *memstr =
2040 (unsigned char *)PyBytes_AS_STRING(items);
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02002041 const struct arraydescr *descr;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002043 /* If possible, try to pack array's items using a data type
2044 * that fits better. This may result in an array with narrower
2045 * or wider elements.
2046 *
Martin Panter4c359642016-05-08 13:53:41 +00002047 * For example, if a 32-bit machine pickles an L-code array of
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002048 * unsigned longs, then the array will be unpickled by 64-bit
2049 * machine as an I-code array of unsigned ints.
2050 *
2051 * XXX: Is it possible to write a unit test for this?
2052 */
2053 for (descr = descriptors; descr->typecode != '\0'; descr++) {
2054 if (descr->is_integer_type &&
Victor Stinner706768c2014-08-16 01:03:39 +02002055 (size_t)descr->itemsize == mf_descr.size &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002056 descr->is_signed == mf_descr.is_signed)
2057 typecode = descr->typecode;
2058 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002060 converted_items = PyList_New(itemcount);
2061 if (converted_items == NULL)
2062 return NULL;
2063 for (i = 0; i < itemcount; i++) {
2064 PyObject *pylong;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002066 pylong = _PyLong_FromByteArray(
2067 &memstr[i * mf_descr.size],
2068 mf_descr.size,
2069 !mf_descr.is_big_endian,
2070 mf_descr.is_signed);
2071 if (pylong == NULL) {
2072 Py_DECREF(converted_items);
2073 return NULL;
2074 }
2075 PyList_SET_ITEM(converted_items, i, pylong);
2076 }
2077 break;
2078 }
2079 case UNKNOWN_FORMAT:
2080 /* Impossible, but needed to shut up GCC about the unhandled
2081 * enumeration value.
2082 */
2083 default:
2084 PyErr_BadArgument();
2085 return NULL;
2086 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002087
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02002088 result = make_array(arraytype, (char)typecode, converted_items);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002089 Py_DECREF(converted_items);
2090 return result;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002091}
2092
Brett Cannon1eb32c22014-10-10 16:26:45 -04002093/*[clinic input]
2094array.array.__reduce_ex__
2095
2096 value: object
2097 /
2098
2099Return state information for pickling.
2100[clinic start generated code]*/
2101
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002102static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04002103array_array___reduce_ex__(arrayobject *self, PyObject *value)
2104/*[clinic end generated code: output=051e0a6175d0eddb input=c36c3f85de7df6cd]*/
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002105{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002106 PyObject *dict;
2107 PyObject *result;
2108 PyObject *array_str;
Brett Cannon1eb32c22014-10-10 16:26:45 -04002109 int typecode = self->ob_descr->typecode;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002110 int mformat_code;
2111 static PyObject *array_reconstructor = NULL;
2112 long protocol;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002113 _Py_IDENTIFIER(_array_reconstructor);
2114 _Py_IDENTIFIER(__dict__);
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002116 if (array_reconstructor == NULL) {
2117 PyObject *array_module = PyImport_ImportModule("array");
2118 if (array_module == NULL)
2119 return NULL;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002120 array_reconstructor = _PyObject_GetAttrId(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002121 array_module,
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002122 &PyId__array_reconstructor);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002123 Py_DECREF(array_module);
2124 if (array_reconstructor == NULL)
2125 return NULL;
2126 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002128 if (!PyLong_Check(value)) {
2129 PyErr_SetString(PyExc_TypeError,
2130 "__reduce_ex__ argument should an integer");
2131 return NULL;
2132 }
2133 protocol = PyLong_AsLong(value);
2134 if (protocol == -1 && PyErr_Occurred())
2135 return NULL;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002136
Brett Cannon1eb32c22014-10-10 16:26:45 -04002137 dict = _PyObject_GetAttrId((PyObject *)self, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002138 if (dict == NULL) {
2139 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
2140 return NULL;
2141 PyErr_Clear();
2142 dict = Py_None;
2143 Py_INCREF(dict);
2144 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002145
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002146 mformat_code = typecode_to_mformat_code(typecode);
2147 if (mformat_code == UNKNOWN_FORMAT || protocol < 3) {
2148 /* Convert the array to a list if we got something weird
2149 * (e.g., non-IEEE floats), or we are pickling the array using
2150 * a Python 2.x compatible protocol.
2151 *
2152 * It is necessary to use a list representation for Python 2.x
2153 * compatible pickle protocol, since Python 2's str objects
2154 * are unpickled as unicode by Python 3. Thus it is impossible
2155 * to make arrays unpicklable by Python 3 by using their memory
2156 * representation, unless we resort to ugly hacks such as
2157 * coercing unicode objects to bytes in array_reconstructor.
2158 */
2159 PyObject *list;
Brett Cannon1eb32c22014-10-10 16:26:45 -04002160 list = array_array_tolist_impl(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002161 if (list == NULL) {
2162 Py_DECREF(dict);
2163 return NULL;
2164 }
2165 result = Py_BuildValue(
Brett Cannon1eb32c22014-10-10 16:26:45 -04002166 "O(CO)O", Py_TYPE(self), typecode, list, dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002167 Py_DECREF(list);
2168 Py_DECREF(dict);
2169 return result;
2170 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002171
Brett Cannon1eb32c22014-10-10 16:26:45 -04002172 array_str = array_array_tobytes_impl(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002173 if (array_str == NULL) {
2174 Py_DECREF(dict);
2175 return NULL;
2176 }
2177 result = Py_BuildValue(
Brett Cannon1eb32c22014-10-10 16:26:45 -04002178 "O(OCiN)O", array_reconstructor, Py_TYPE(self), typecode,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002179 mformat_code, array_str, dict);
2180 Py_DECREF(dict);
2181 return result;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002182}
2183
Martin v. Löwis99866332002-03-01 10:27:01 +00002184static PyObject *
2185array_get_typecode(arrayobject *a, void *closure)
2186{
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02002187 char typecode = a->ob_descr->typecode;
2188 return PyUnicode_FromOrdinal(typecode);
Martin v. Löwis99866332002-03-01 10:27:01 +00002189}
2190
2191static PyObject *
2192array_get_itemsize(arrayobject *a, void *closure)
2193{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002194 return PyLong_FromLong((long)a->ob_descr->itemsize);
Martin v. Löwis99866332002-03-01 10:27:01 +00002195}
2196
2197static PyGetSetDef array_getsets [] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002198 {"typecode", (getter) array_get_typecode, NULL,
2199 "the typecode character used to create the array"},
2200 {"itemsize", (getter) array_get_itemsize, NULL,
2201 "the size, in bytes, of one array item"},
2202 {NULL}
Martin v. Löwis99866332002-03-01 10:27:01 +00002203};
2204
Martin v. Löwis59683e82008-06-13 07:50:45 +00002205static PyMethodDef array_methods[] = {
Brett Cannon1eb32c22014-10-10 16:26:45 -04002206 ARRAY_ARRAY_APPEND_METHODDEF
2207 ARRAY_ARRAY_BUFFER_INFO_METHODDEF
2208 ARRAY_ARRAY_BYTESWAP_METHODDEF
2209 ARRAY_ARRAY___COPY___METHODDEF
2210 ARRAY_ARRAY_COUNT_METHODDEF
2211 ARRAY_ARRAY___DEEPCOPY___METHODDEF
2212 ARRAY_ARRAY_EXTEND_METHODDEF
2213 ARRAY_ARRAY_FROMFILE_METHODDEF
2214 ARRAY_ARRAY_FROMLIST_METHODDEF
2215 ARRAY_ARRAY_FROMSTRING_METHODDEF
2216 ARRAY_ARRAY_FROMBYTES_METHODDEF
2217 ARRAY_ARRAY_FROMUNICODE_METHODDEF
2218 ARRAY_ARRAY_INDEX_METHODDEF
2219 ARRAY_ARRAY_INSERT_METHODDEF
2220 ARRAY_ARRAY_POP_METHODDEF
2221 ARRAY_ARRAY___REDUCE_EX___METHODDEF
2222 ARRAY_ARRAY_REMOVE_METHODDEF
2223 ARRAY_ARRAY_REVERSE_METHODDEF
2224 ARRAY_ARRAY_TOFILE_METHODDEF
2225 ARRAY_ARRAY_TOLIST_METHODDEF
2226 ARRAY_ARRAY_TOSTRING_METHODDEF
2227 ARRAY_ARRAY_TOBYTES_METHODDEF
2228 ARRAY_ARRAY_TOUNICODE_METHODDEF
2229 ARRAY_ARRAY___SIZEOF___METHODDEF
2230 {NULL, NULL} /* sentinel */
Guido van Rossum778983b1993-02-19 15:55:02 +00002231};
2232
Roger E. Masse2919eaa1996-12-09 20:10:36 +00002233static PyObject *
Peter Schneider-Kamp9656abd2000-07-13 21:10:57 +00002234array_repr(arrayobject *a)
Guido van Rossum778983b1993-02-19 15:55:02 +00002235{
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02002236 char typecode;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002237 PyObject *s, *v = NULL;
2238 Py_ssize_t len;
Martin v. Löwis99866332002-03-01 10:27:01 +00002239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002240 len = Py_SIZE(a);
2241 typecode = a->ob_descr->typecode;
2242 if (len == 0) {
Amaury Forgeot d'Arc24aa26b2010-11-25 08:13:35 +00002243 return PyUnicode_FromFormat("array('%c')", (int)typecode);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002244 }
Gregory P. Smith9504b132012-12-10 20:20:20 -08002245 if (typecode == 'u') {
Brett Cannon1eb32c22014-10-10 16:26:45 -04002246 v = array_array_tounicode_impl(a);
Gregory P. Smith9504b132012-12-10 20:20:20 -08002247 } else {
Brett Cannon1eb32c22014-10-10 16:26:45 -04002248 v = array_array_tolist_impl(a);
Gregory P. Smith9504b132012-12-10 20:20:20 -08002249 }
Victor Stinner29ec5952013-02-26 00:27:38 +01002250 if (v == NULL)
2251 return NULL;
Raymond Hettinger88ba1e32003-04-23 17:27:00 +00002252
Amaury Forgeot d'Arc24aa26b2010-11-25 08:13:35 +00002253 s = PyUnicode_FromFormat("array('%c', %R)", (int)typecode, v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002254 Py_DECREF(v);
2255 return s;
Guido van Rossum778983b1993-02-19 15:55:02 +00002256}
2257
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002258static PyObject*
2259array_subscr(arrayobject* self, PyObject* item)
2260{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002261 if (PyIndex_Check(item)) {
2262 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
2263 if (i==-1 && PyErr_Occurred()) {
2264 return NULL;
2265 }
2266 if (i < 0)
2267 i += Py_SIZE(self);
2268 return array_item(self, i);
2269 }
2270 else if (PySlice_Check(item)) {
2271 Py_ssize_t start, stop, step, slicelength, cur, i;
2272 PyObject* result;
2273 arrayobject* ar;
2274 int itemsize = self->ob_descr->itemsize;
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002275
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002276 if (PySlice_GetIndicesEx(item, Py_SIZE(self),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002277 &start, &stop, &step, &slicelength) < 0) {
2278 return NULL;
2279 }
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002281 if (slicelength <= 0) {
2282 return newarrayobject(&Arraytype, 0, self->ob_descr);
2283 }
2284 else if (step == 1) {
2285 PyObject *result = newarrayobject(&Arraytype,
2286 slicelength, self->ob_descr);
2287 if (result == NULL)
2288 return NULL;
2289 memcpy(((arrayobject *)result)->ob_item,
2290 self->ob_item + start * itemsize,
2291 slicelength * itemsize);
2292 return result;
2293 }
2294 else {
2295 result = newarrayobject(&Arraytype, slicelength, self->ob_descr);
2296 if (!result) return NULL;
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002298 ar = (arrayobject*)result;
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002300 for (cur = start, i = 0; i < slicelength;
2301 cur += step, i++) {
2302 memcpy(ar->ob_item + i*itemsize,
2303 self->ob_item + cur*itemsize,
2304 itemsize);
2305 }
2306
2307 return result;
2308 }
2309 }
2310 else {
2311 PyErr_SetString(PyExc_TypeError,
2312 "array indices must be integers");
2313 return NULL;
2314 }
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002315}
2316
2317static int
2318array_ass_subscr(arrayobject* self, PyObject* item, PyObject* value)
2319{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002320 Py_ssize_t start, stop, step, slicelength, needed;
2321 arrayobject* other;
2322 int itemsize;
Thomas Woutersed03b412007-08-28 21:37:11 +00002323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002324 if (PyIndex_Check(item)) {
2325 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Alexandre Vassalotti47137252009-07-05 19:57:00 +00002326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002327 if (i == -1 && PyErr_Occurred())
2328 return -1;
2329 if (i < 0)
2330 i += Py_SIZE(self);
2331 if (i < 0 || i >= Py_SIZE(self)) {
2332 PyErr_SetString(PyExc_IndexError,
2333 "array assignment index out of range");
2334 return -1;
2335 }
2336 if (value == NULL) {
2337 /* Fall through to slice assignment */
2338 start = i;
2339 stop = i + 1;
2340 step = 1;
2341 slicelength = 1;
2342 }
2343 else
2344 return (*self->ob_descr->setitem)(self, i, value);
2345 }
2346 else if (PySlice_Check(item)) {
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002347 if (PySlice_GetIndicesEx(item,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002348 Py_SIZE(self), &start, &stop,
2349 &step, &slicelength) < 0) {
2350 return -1;
2351 }
2352 }
2353 else {
2354 PyErr_SetString(PyExc_TypeError,
2355 "array indices must be integer");
2356 return -1;
2357 }
2358 if (value == NULL) {
2359 other = NULL;
2360 needed = 0;
2361 }
2362 else if (array_Check(value)) {
2363 other = (arrayobject *)value;
2364 needed = Py_SIZE(other);
2365 if (self == other) {
2366 /* Special case "self[i:j] = self" -- copy self first */
2367 int ret;
2368 value = array_slice(other, 0, needed);
2369 if (value == NULL)
2370 return -1;
2371 ret = array_ass_subscr(self, item, value);
2372 Py_DECREF(value);
2373 return ret;
2374 }
2375 if (other->ob_descr != self->ob_descr) {
2376 PyErr_BadArgument();
2377 return -1;
2378 }
2379 }
2380 else {
2381 PyErr_Format(PyExc_TypeError,
2382 "can only assign array (not \"%.200s\") to array slice",
2383 Py_TYPE(value)->tp_name);
2384 return -1;
2385 }
2386 itemsize = self->ob_descr->itemsize;
2387 /* for 'a[2:1] = ...', the insertion point is 'start', not 'stop' */
2388 if ((step > 0 && stop < start) ||
2389 (step < 0 && stop > start))
2390 stop = start;
Alexandre Vassalotti47137252009-07-05 19:57:00 +00002391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002392 /* Issue #4509: If the array has exported buffers and the slice
2393 assignment would change the size of the array, fail early to make
2394 sure we don't modify it. */
2395 if ((needed == 0 || slicelength != needed) && self->ob_exports > 0) {
2396 PyErr_SetString(PyExc_BufferError,
2397 "cannot resize an array that is exporting buffers");
2398 return -1;
2399 }
Mark Dickinsonbc099642010-01-29 17:27:24 +00002400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002401 if (step == 1) {
2402 if (slicelength > needed) {
2403 memmove(self->ob_item + (start + needed) * itemsize,
2404 self->ob_item + stop * itemsize,
2405 (Py_SIZE(self) - stop) * itemsize);
2406 if (array_resize(self, Py_SIZE(self) +
2407 needed - slicelength) < 0)
2408 return -1;
2409 }
2410 else if (slicelength < needed) {
2411 if (array_resize(self, Py_SIZE(self) +
2412 needed - slicelength) < 0)
2413 return -1;
2414 memmove(self->ob_item + (start + needed) * itemsize,
2415 self->ob_item + stop * itemsize,
2416 (Py_SIZE(self) - start - needed) * itemsize);
2417 }
2418 if (needed > 0)
2419 memcpy(self->ob_item + start * itemsize,
2420 other->ob_item, needed * itemsize);
2421 return 0;
2422 }
2423 else if (needed == 0) {
2424 /* Delete slice */
2425 size_t cur;
2426 Py_ssize_t i;
Thomas Woutersed03b412007-08-28 21:37:11 +00002427
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002428 if (step < 0) {
2429 stop = start + 1;
2430 start = stop + step * (slicelength - 1) - 1;
2431 step = -step;
2432 }
2433 for (cur = start, i = 0; i < slicelength;
2434 cur += step, i++) {
2435 Py_ssize_t lim = step - 1;
Thomas Woutersed03b412007-08-28 21:37:11 +00002436
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002437 if (cur + step >= (size_t)Py_SIZE(self))
2438 lim = Py_SIZE(self) - cur - 1;
2439 memmove(self->ob_item + (cur - i) * itemsize,
2440 self->ob_item + (cur + 1) * itemsize,
2441 lim * itemsize);
2442 }
Mark Dickinsonc7d93b72011-09-25 15:34:32 +01002443 cur = start + (size_t)slicelength * step;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002444 if (cur < (size_t)Py_SIZE(self)) {
2445 memmove(self->ob_item + (cur-slicelength) * itemsize,
2446 self->ob_item + cur * itemsize,
2447 (Py_SIZE(self) - cur) * itemsize);
2448 }
2449 if (array_resize(self, Py_SIZE(self) - slicelength) < 0)
2450 return -1;
2451 return 0;
2452 }
2453 else {
2454 Py_ssize_t cur, i;
2455
2456 if (needed != slicelength) {
2457 PyErr_Format(PyExc_ValueError,
2458 "attempt to assign array of size %zd "
2459 "to extended slice of size %zd",
2460 needed, slicelength);
2461 return -1;
2462 }
2463 for (cur = start, i = 0; i < slicelength;
2464 cur += step, i++) {
2465 memcpy(self->ob_item + cur * itemsize,
2466 other->ob_item + i * itemsize,
2467 itemsize);
2468 }
2469 return 0;
2470 }
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002471}
2472
2473static PyMappingMethods array_as_mapping = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002474 (lenfunc)array_length,
2475 (binaryfunc)array_subscr,
2476 (objobjargproc)array_ass_subscr
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002477};
2478
Guido van Rossumd8faa362007-04-27 19:54:29 +00002479static const void *emptybuf = "";
2480
Travis E. Oliphantb99f7622007-08-18 11:21:56 +00002481
2482static int
Travis E. Oliphant8ae62b62007-09-23 02:00:13 +00002483array_buffer_getbuf(arrayobject *self, Py_buffer *view, int flags)
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00002484{
Stefan Krah650c1e82015-02-03 21:43:23 +01002485 if (view == NULL) {
2486 PyErr_SetString(PyExc_BufferError,
2487 "array_buffer_getbuf: view==NULL argument is obsolete");
2488 return -1;
2489 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +00002490
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002491 view->buf = (void *)self->ob_item;
2492 view->obj = (PyObject*)self;
2493 Py_INCREF(self);
2494 if (view->buf == NULL)
2495 view->buf = (void *)emptybuf;
2496 view->len = (Py_SIZE(self)) * self->ob_descr->itemsize;
2497 view->readonly = 0;
2498 view->ndim = 1;
2499 view->itemsize = self->ob_descr->itemsize;
2500 view->suboffsets = NULL;
2501 view->shape = NULL;
2502 if ((flags & PyBUF_ND)==PyBUF_ND) {
2503 view->shape = &((Py_SIZE(self)));
2504 }
2505 view->strides = NULL;
2506 if ((flags & PyBUF_STRIDES)==PyBUF_STRIDES)
2507 view->strides = &(view->itemsize);
2508 view->format = NULL;
2509 view->internal = NULL;
Victor Stinner62bb3942012-08-06 00:46:05 +02002510 if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT) {
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02002511 view->format = (char *)self->ob_descr->formats;
Victor Stinner62bb3942012-08-06 00:46:05 +02002512#ifdef Py_UNICODE_WIDE
2513 if (self->ob_descr->typecode == 'u') {
2514 view->format = "w";
2515 }
2516#endif
2517 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +00002518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002519 self->ob_exports++;
2520 return 0;
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00002521}
2522
Travis E. Oliphantb99f7622007-08-18 11:21:56 +00002523static void
Travis E. Oliphant8ae62b62007-09-23 02:00:13 +00002524array_buffer_relbuf(arrayobject *self, Py_buffer *view)
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00002525{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002526 self->ob_exports--;
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00002527}
2528
Roger E. Masse2919eaa1996-12-09 20:10:36 +00002529static PySequenceMethods array_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002530 (lenfunc)array_length, /*sq_length*/
2531 (binaryfunc)array_concat, /*sq_concat*/
2532 (ssizeargfunc)array_repeat, /*sq_repeat*/
2533 (ssizeargfunc)array_item, /*sq_item*/
2534 0, /*sq_slice*/
2535 (ssizeobjargproc)array_ass_item, /*sq_ass_item*/
2536 0, /*sq_ass_slice*/
2537 (objobjproc)array_contains, /*sq_contains*/
2538 (binaryfunc)array_inplace_concat, /*sq_inplace_concat*/
2539 (ssizeargfunc)array_inplace_repeat /*sq_inplace_repeat*/
Guido van Rossum778983b1993-02-19 15:55:02 +00002540};
2541
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00002542static PyBufferProcs array_as_buffer = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002543 (getbufferproc)array_buffer_getbuf,
2544 (releasebufferproc)array_buffer_relbuf
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00002545};
2546
Roger E. Masse2919eaa1996-12-09 20:10:36 +00002547static PyObject *
Martin v. Löwis99866332002-03-01 10:27:01 +00002548array_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum778983b1993-02-19 15:55:02 +00002549{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002550 int c;
2551 PyObject *initial = NULL, *it = NULL;
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02002552 const struct arraydescr *descr;
Martin v. Löwis99866332002-03-01 10:27:01 +00002553
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002554 if (type == &Arraytype && !_PyArg_NoKeywords("array.array()", kwds))
2555 return NULL;
Martin v. Löwis99866332002-03-01 10:27:01 +00002556
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002557 if (!PyArg_ParseTuple(args, "C|O:array", &c, &initial))
2558 return NULL;
Raymond Hettinger84fc9aa2003-04-24 10:41:55 +00002559
Alexandre Vassalotti9730e332013-11-29 20:47:15 -08002560 if (initial && c != 'u') {
2561 if (PyUnicode_Check(initial)) {
2562 PyErr_Format(PyExc_TypeError, "cannot use a str to initialize "
2563 "an array with typecode '%c'", c);
2564 return NULL;
2565 }
2566 else if (array_Check(initial) &&
2567 ((arrayobject*)initial)->ob_descr->typecode == 'u') {
2568 PyErr_Format(PyExc_TypeError, "cannot use a unicode array to "
2569 "initialize an array with typecode '%c'", c);
2570 return NULL;
2571 }
2572 }
2573
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002574 if (!(initial == NULL || PyList_Check(initial)
2575 || PyByteArray_Check(initial)
2576 || PyBytes_Check(initial)
2577 || PyTuple_Check(initial)
Alexander Belopolskyef4a03f2011-01-11 21:44:00 +00002578 || ((c=='u') && PyUnicode_Check(initial))
2579 || (array_Check(initial)
2580 && c == ((arrayobject*)initial)->ob_descr->typecode))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002581 it = PyObject_GetIter(initial);
2582 if (it == NULL)
2583 return NULL;
2584 /* We set initial to NULL so that the subsequent code
2585 will create an empty array of the appropriate type
2586 and afterwards we can use array_iter_extend to populate
2587 the array.
2588 */
2589 initial = NULL;
2590 }
2591 for (descr = descriptors; descr->typecode != '\0'; descr++) {
2592 if (descr->typecode == c) {
2593 PyObject *a;
2594 Py_ssize_t len;
Martin v. Löwis99866332002-03-01 10:27:01 +00002595
Alexander Belopolskyef4a03f2011-01-11 21:44:00 +00002596 if (initial == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002597 len = 0;
Alexander Belopolskyef4a03f2011-01-11 21:44:00 +00002598 else if (PyList_Check(initial))
2599 len = PyList_GET_SIZE(initial);
2600 else if (PyTuple_Check(initial) || array_Check(initial))
2601 len = Py_SIZE(initial);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002602 else
Alexander Belopolskyef4a03f2011-01-11 21:44:00 +00002603 len = 0;
Martin v. Löwis99866332002-03-01 10:27:01 +00002604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002605 a = newarrayobject(type, len, descr);
2606 if (a == NULL)
2607 return NULL;
2608
Alexander Belopolskyef4a03f2011-01-11 21:44:00 +00002609 if (len > 0 && !array_Check(initial)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002610 Py_ssize_t i;
2611 for (i = 0; i < len; i++) {
2612 PyObject *v =
2613 PySequence_GetItem(initial, i);
2614 if (v == NULL) {
2615 Py_DECREF(a);
2616 return NULL;
2617 }
2618 if (setarrayitem(a, i, v) != 0) {
2619 Py_DECREF(v);
2620 Py_DECREF(a);
2621 return NULL;
2622 }
2623 Py_DECREF(v);
2624 }
2625 }
2626 else if (initial != NULL && (PyByteArray_Check(initial) ||
2627 PyBytes_Check(initial))) {
Serhiy Storchaka04e6dba2015-04-04 17:06:55 +03002628 PyObject *v;
Brett Cannon1eb32c22014-10-10 16:26:45 -04002629 v = array_array_frombytes((arrayobject *)a,
Serhiy Storchaka04e6dba2015-04-04 17:06:55 +03002630 initial);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002631 if (v == NULL) {
2632 Py_DECREF(a);
2633 return NULL;
2634 }
2635 Py_DECREF(v);
2636 }
2637 else if (initial != NULL && PyUnicode_Check(initial)) {
Victor Stinner62bb3942012-08-06 00:46:05 +02002638 Py_UNICODE *ustr;
Victor Stinner1fbcaef2011-09-30 01:54:04 +02002639 Py_ssize_t n;
Victor Stinner62bb3942012-08-06 00:46:05 +02002640
2641 ustr = PyUnicode_AsUnicode(initial);
2642 if (ustr == NULL) {
2643 PyErr_NoMemory();
Victor Stinner1fbcaef2011-09-30 01:54:04 +02002644 Py_DECREF(a);
2645 return NULL;
2646 }
Victor Stinner62bb3942012-08-06 00:46:05 +02002647
2648 n = PyUnicode_GET_DATA_SIZE(initial);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002649 if (n > 0) {
2650 arrayobject *self = (arrayobject *)a;
Victor Stinner62bb3942012-08-06 00:46:05 +02002651 char *item = self->ob_item;
2652 item = (char *)PyMem_Realloc(item, n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002653 if (item == NULL) {
2654 PyErr_NoMemory();
2655 Py_DECREF(a);
2656 return NULL;
2657 }
Victor Stinner62bb3942012-08-06 00:46:05 +02002658 self->ob_item = item;
2659 Py_SIZE(self) = n / sizeof(Py_UNICODE);
2660 memcpy(item, ustr, n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002661 self->allocated = Py_SIZE(self);
2662 }
2663 }
Benjamin Peterson682124c2014-10-10 20:58:30 -04002664 else if (initial != NULL && array_Check(initial) && len > 0) {
Alexander Belopolskyef4a03f2011-01-11 21:44:00 +00002665 arrayobject *self = (arrayobject *)a;
2666 arrayobject *other = (arrayobject *)initial;
2667 memcpy(self->ob_item, other->ob_item, len * other->ob_descr->itemsize);
2668 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002669 if (it != NULL) {
2670 if (array_iter_extend((arrayobject *)a, it) == -1) {
2671 Py_DECREF(it);
2672 Py_DECREF(a);
2673 return NULL;
2674 }
2675 Py_DECREF(it);
2676 }
2677 return a;
2678 }
2679 }
2680 PyErr_SetString(PyExc_ValueError,
Meador Inge1c9f0c92011-09-20 19:55:51 -05002681 "bad typecode (must be b, B, u, h, H, i, I, l, L, q, Q, f or d)");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002682 return NULL;
Guido van Rossum778983b1993-02-19 15:55:02 +00002683}
2684
Guido van Rossum778983b1993-02-19 15:55:02 +00002685
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002686PyDoc_STRVAR(module_doc,
Martin v. Löwis99866332002-03-01 10:27:01 +00002687"This module defines an object type which can efficiently represent\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002688an array of basic values: characters, integers, floating point\n\
2689numbers. Arrays are sequence types and behave very much like lists,\n\
Alexandre Vassalotti9730e332013-11-29 20:47:15 -08002690except that the type of objects stored in them is constrained.\n");
2691
2692PyDoc_STRVAR(arraytype_doc,
2693"array(typecode [, initializer]) -> array\n\
2694\n\
2695Return a new array whose items are restricted by typecode, and\n\
2696initialized from the optional initializer value, which must be a list,\n\
2697string or iterable over elements of the appropriate type.\n\
2698\n\
2699Arrays represent basic values and behave very much like lists, except\n\
2700the type of objects stored in them is constrained. The type is specified\n\
2701at object creation time by using a type code, which is a single character.\n\
2702The following type codes are defined:\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002703\n\
2704 Type code C Type Minimum size in bytes \n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002705 'b' signed integer 1 \n\
2706 'B' unsigned integer 1 \n\
Victor Stinner62bb3942012-08-06 00:46:05 +02002707 'u' Unicode character 2 (see note) \n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002708 'h' signed integer 2 \n\
2709 'H' unsigned integer 2 \n\
2710 'i' signed integer 2 \n\
2711 'I' unsigned integer 2 \n\
2712 'l' signed integer 4 \n\
2713 'L' unsigned integer 4 \n\
Meador Inge1c9f0c92011-09-20 19:55:51 -05002714 'q' signed integer 8 (see note) \n\
2715 'Q' unsigned integer 8 (see note) \n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002716 'f' floating point 4 \n\
2717 'd' floating point 8 \n\
2718\n\
Victor Stinner62bb3942012-08-06 00:46:05 +02002719NOTE: The 'u' typecode corresponds to Python's unicode character. On \n\
2720narrow builds this is 2-bytes on wide builds this is 4-bytes.\n\
2721\n\
Meador Inge1c9f0c92011-09-20 19:55:51 -05002722NOTE: The 'q' and 'Q' type codes are only available if the platform \n\
2723C compiler used to build Python supports 'long long', or, on Windows, \n\
2724'__int64'.\n\
2725\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002726Methods:\n\
2727\n\
2728append() -- append a new item to the end of the array\n\
2729buffer_info() -- return information giving the current memory info\n\
2730byteswap() -- byteswap all the items of the array\n\
Mark Dickinson934896d2009-02-21 20:59:32 +00002731count() -- return number of occurrences of an object\n\
Raymond Hettinger49f9bd12004-03-14 05:43:59 +00002732extend() -- extend array by appending multiple elements from an iterable\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002733fromfile() -- read items from a file object\n\
2734fromlist() -- append items from the list\n\
Florent Xiclunac45fb252011-10-24 13:14:55 +02002735frombytes() -- append items from the string\n\
Mark Dickinson934896d2009-02-21 20:59:32 +00002736index() -- return index of first occurrence of an object\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002737insert() -- insert a new item into the array at a provided position\n\
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00002738pop() -- remove and return item (default last)\n\
Mark Dickinson934896d2009-02-21 20:59:32 +00002739remove() -- remove first occurrence of an object\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002740reverse() -- reverse the order of the items in the array\n\
2741tofile() -- write all items to a file object\n\
2742tolist() -- return the array converted to an ordinary list\n\
Florent Xiclunac45fb252011-10-24 13:14:55 +02002743tobytes() -- return the array converted to a string\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002744\n\
Martin v. Löwis99866332002-03-01 10:27:01 +00002745Attributes:\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002746\n\
2747typecode -- the typecode character used to create the array\n\
2748itemsize -- the length in bytes of one array item\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002749");
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002750
Raymond Hettinger625812f2003-01-07 01:58:52 +00002751static PyObject *array_iter(arrayobject *ao);
2752
Tim Peters0c322792002-07-17 16:49:03 +00002753static PyTypeObject Arraytype = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002754 PyVarObject_HEAD_INIT(NULL, 0)
2755 "array.array",
2756 sizeof(arrayobject),
2757 0,
2758 (destructor)array_dealloc, /* tp_dealloc */
2759 0, /* tp_print */
2760 0, /* tp_getattr */
2761 0, /* tp_setattr */
2762 0, /* tp_reserved */
2763 (reprfunc)array_repr, /* tp_repr */
2764 0, /* tp_as_number*/
2765 &array_as_sequence, /* tp_as_sequence*/
2766 &array_as_mapping, /* tp_as_mapping*/
2767 0, /* tp_hash */
2768 0, /* tp_call */
2769 0, /* tp_str */
2770 PyObject_GenericGetAttr, /* tp_getattro */
2771 0, /* tp_setattro */
2772 &array_as_buffer, /* tp_as_buffer*/
2773 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
2774 arraytype_doc, /* tp_doc */
2775 0, /* tp_traverse */
2776 0, /* tp_clear */
2777 array_richcompare, /* tp_richcompare */
2778 offsetof(arrayobject, weakreflist), /* tp_weaklistoffset */
2779 (getiterfunc)array_iter, /* tp_iter */
2780 0, /* tp_iternext */
2781 array_methods, /* tp_methods */
2782 0, /* tp_members */
2783 array_getsets, /* tp_getset */
2784 0, /* tp_base */
2785 0, /* tp_dict */
2786 0, /* tp_descr_get */
2787 0, /* tp_descr_set */
2788 0, /* tp_dictoffset */
2789 0, /* tp_init */
2790 PyType_GenericAlloc, /* tp_alloc */
2791 array_new, /* tp_new */
2792 PyObject_Del, /* tp_free */
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002793};
2794
Raymond Hettinger625812f2003-01-07 01:58:52 +00002795
2796/*********************** Array Iterator **************************/
2797
Brett Cannon1eb32c22014-10-10 16:26:45 -04002798/*[clinic input]
2799class array.arrayiterator "arrayiterobject *" "&PyArrayIter_Type"
2800[clinic start generated code]*/
2801/*[clinic end generated code: output=da39a3ee5e6b4b0d input=5aefd2d74d8c8e30]*/
Raymond Hettinger625812f2003-01-07 01:58:52 +00002802
2803static PyObject *
2804array_iter(arrayobject *ao)
2805{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002806 arrayiterobject *it;
Raymond Hettinger625812f2003-01-07 01:58:52 +00002807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002808 if (!array_Check(ao)) {
2809 PyErr_BadInternalCall();
2810 return NULL;
2811 }
Raymond Hettinger625812f2003-01-07 01:58:52 +00002812
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002813 it = PyObject_GC_New(arrayiterobject, &PyArrayIter_Type);
2814 if (it == NULL)
2815 return NULL;
Raymond Hettinger625812f2003-01-07 01:58:52 +00002816
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002817 Py_INCREF(ao);
2818 it->ao = ao;
2819 it->index = 0;
2820 it->getitem = ao->ob_descr->getitem;
2821 PyObject_GC_Track(it);
2822 return (PyObject *)it;
Raymond Hettinger625812f2003-01-07 01:58:52 +00002823}
2824
2825static PyObject *
Raymond Hettinger625812f2003-01-07 01:58:52 +00002826arrayiter_next(arrayiterobject *it)
2827{
Serhiy Storchakaab0d1982016-03-30 21:11:16 +03002828 arrayobject *ao;
2829
2830 assert(it != NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002831 assert(PyArrayIter_Check(it));
Serhiy Storchakaab0d1982016-03-30 21:11:16 +03002832 ao = it->ao;
2833 if (ao == NULL) {
2834 return NULL;
2835 }
2836 assert(array_Check(ao));
2837 if (it->index < Py_SIZE(ao)) {
2838 return (*it->getitem)(ao, it->index++);
2839 }
2840 it->ao = NULL;
2841 Py_DECREF(ao);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002842 return NULL;
Raymond Hettinger625812f2003-01-07 01:58:52 +00002843}
2844
2845static void
2846arrayiter_dealloc(arrayiterobject *it)
2847{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002848 PyObject_GC_UnTrack(it);
2849 Py_XDECREF(it->ao);
2850 PyObject_GC_Del(it);
Raymond Hettinger625812f2003-01-07 01:58:52 +00002851}
2852
2853static int
2854arrayiter_traverse(arrayiterobject *it, visitproc visit, void *arg)
2855{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002856 Py_VISIT(it->ao);
2857 return 0;
Raymond Hettinger625812f2003-01-07 01:58:52 +00002858}
2859
Brett Cannon1eb32c22014-10-10 16:26:45 -04002860/*[clinic input]
2861array.arrayiterator.__reduce__
2862
2863Return state information for pickling.
2864[clinic start generated code]*/
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002865
2866static PyObject *
Brett Cannon1eb32c22014-10-10 16:26:45 -04002867array_arrayiterator___reduce___impl(arrayiterobject *self)
2868/*[clinic end generated code: output=7898a52e8e66e016 input=a062ea1e9951417a]*/
2869{
Serhiy Storchakaab0d1982016-03-30 21:11:16 +03002870 PyObject *func = _PyObject_GetBuiltin("iter");
2871 if (self->ao == NULL) {
2872 return Py_BuildValue("N(())", func);
2873 }
2874 return Py_BuildValue("N(O)n", func, self->ao, self->index);
Brett Cannon1eb32c22014-10-10 16:26:45 -04002875}
2876
2877/*[clinic input]
2878array.arrayiterator.__setstate__
2879
2880 state: object
2881 /
2882
2883Set state information for unpickling.
2884[clinic start generated code]*/
2885
2886static PyObject *
2887array_arrayiterator___setstate__(arrayiterobject *self, PyObject *state)
2888/*[clinic end generated code: output=397da9904e443cbe input=f47d5ceda19e787b]*/
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002889{
2890 Py_ssize_t index = PyLong_AsSsize_t(state);
2891 if (index == -1 && PyErr_Occurred())
2892 return NULL;
2893 if (index < 0)
2894 index = 0;
Brett Cannon1eb32c22014-10-10 16:26:45 -04002895 else if (index > Py_SIZE(self->ao))
2896 index = Py_SIZE(self->ao); /* iterator exhausted */
2897 self->index = index;
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002898 Py_RETURN_NONE;
2899}
2900
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002901static PyMethodDef arrayiter_methods[] = {
Brett Cannon1eb32c22014-10-10 16:26:45 -04002902 ARRAY_ARRAYITERATOR___REDUCE___METHODDEF
2903 ARRAY_ARRAYITERATOR___SETSTATE___METHODDEF
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002904 {NULL, NULL} /* sentinel */
2905};
2906
Raymond Hettinger625812f2003-01-07 01:58:52 +00002907static PyTypeObject PyArrayIter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002908 PyVarObject_HEAD_INIT(NULL, 0)
2909 "arrayiterator", /* tp_name */
2910 sizeof(arrayiterobject), /* tp_basicsize */
2911 0, /* tp_itemsize */
2912 /* methods */
2913 (destructor)arrayiter_dealloc, /* tp_dealloc */
2914 0, /* tp_print */
2915 0, /* tp_getattr */
2916 0, /* tp_setattr */
2917 0, /* tp_reserved */
2918 0, /* tp_repr */
2919 0, /* tp_as_number */
2920 0, /* tp_as_sequence */
2921 0, /* tp_as_mapping */
2922 0, /* tp_hash */
2923 0, /* tp_call */
2924 0, /* tp_str */
2925 PyObject_GenericGetAttr, /* tp_getattro */
2926 0, /* tp_setattro */
2927 0, /* tp_as_buffer */
2928 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2929 0, /* tp_doc */
2930 (traverseproc)arrayiter_traverse, /* tp_traverse */
2931 0, /* tp_clear */
2932 0, /* tp_richcompare */
2933 0, /* tp_weaklistoffset */
2934 PyObject_SelfIter, /* tp_iter */
2935 (iternextfunc)arrayiter_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002936 arrayiter_methods, /* tp_methods */
Raymond Hettinger625812f2003-01-07 01:58:52 +00002937};
2938
2939
2940/*********************** Install Module **************************/
2941
Martin v. Löwis99866332002-03-01 10:27:01 +00002942/* No functions in array module. */
2943static PyMethodDef a_methods[] = {
Brett Cannon1eb32c22014-10-10 16:26:45 -04002944 ARRAY__ARRAY_RECONSTRUCTOR_METHODDEF
Martin v. Löwis99866332002-03-01 10:27:01 +00002945 {NULL, NULL, 0, NULL} /* Sentinel */
2946};
2947
Nick Coghland5cacbb2015-05-23 22:24:10 +10002948static int
2949array_modexec(PyObject *m)
Guido van Rossum778983b1993-02-19 15:55:02 +00002950{
Georg Brandl4cb0de22011-09-28 21:49:49 +02002951 char buffer[Py_ARRAY_LENGTH(descriptors)], *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002952 PyObject *typecodes;
2953 Py_ssize_t size = 0;
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02002954 const struct arraydescr *descr;
Fred Drake0d40ba42000-02-04 20:33:49 +00002955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002956 if (PyType_Ready(&Arraytype) < 0)
Nick Coghland5cacbb2015-05-23 22:24:10 +10002957 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002958 Py_TYPE(&PyArrayIter_Type) = &PyType_Type;
Fred Drakef4e34842002-04-01 03:45:06 +00002959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002960 Py_INCREF((PyObject *)&Arraytype);
2961 PyModule_AddObject(m, "ArrayType", (PyObject *)&Arraytype);
2962 Py_INCREF((PyObject *)&Arraytype);
2963 PyModule_AddObject(m, "array", (PyObject *)&Arraytype);
Travis E. Oliphantd5c0add2007-10-12 22:05:15 +00002964
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002965 for (descr=descriptors; descr->typecode != '\0'; descr++) {
2966 size++;
2967 }
Travis E. Oliphantd5c0add2007-10-12 22:05:15 +00002968
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002969 p = buffer;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002970 for (descr = descriptors; descr->typecode != '\0'; descr++) {
2971 *p++ = (char)descr->typecode;
2972 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002973 typecodes = PyUnicode_DecodeASCII(buffer, p - buffer, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002974
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002975 PyModule_AddObject(m, "typecodes", typecodes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002976
2977 if (PyErr_Occurred()) {
2978 Py_DECREF(m);
2979 m = NULL;
2980 }
Nick Coghland5cacbb2015-05-23 22:24:10 +10002981 return 0;
2982}
2983
2984static PyModuleDef_Slot arrayslots[] = {
2985 {Py_mod_exec, array_modexec},
2986 {0, NULL}
2987};
2988
2989
2990static struct PyModuleDef arraymodule = {
2991 PyModuleDef_HEAD_INIT,
2992 "array",
2993 module_doc,
2994 0,
2995 a_methods,
2996 arrayslots,
2997 NULL,
2998 NULL,
2999 NULL
3000};
3001
3002
3003PyMODINIT_FUNC
3004PyInit_array(void)
3005{
3006 return PyModuleDef_Init(&arraymodule);
Guido van Rossum778983b1993-02-19 15:55:02 +00003007}