blob: b0921c85a550e0402e7d99b61ab5ab738ce0062d [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
18struct arrayobject; /* Forward */
19
Tim Petersbb307342000-09-10 05:22:54 +000020/* All possible arraydescr values are defined in the vector "descriptors"
21 * below. That's defined later because the appropriate get and set
22 * functions aren't visible yet.
23 */
Guido van Rossum778983b1993-02-19 15:55:02 +000024struct arraydescr {
Victor Stinnerf8bb7d02011-09-30 00:03:59 +020025 char typecode;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000026 int itemsize;
27 PyObject * (*getitem)(struct arrayobject *, Py_ssize_t);
28 int (*setitem)(struct arrayobject *, Py_ssize_t, PyObject *);
29 char *formats;
30 int is_integer_type;
31 int is_signed;
Guido van Rossum778983b1993-02-19 15:55:02 +000032};
33
34typedef struct arrayobject {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000035 PyObject_VAR_HEAD
36 char *ob_item;
37 Py_ssize_t allocated;
38 struct arraydescr *ob_descr;
39 PyObject *weakreflist; /* List of weak references */
40 int ob_exports; /* Number of exported buffers */
Guido van Rossum778983b1993-02-19 15:55:02 +000041} arrayobject;
42
Jeremy Hylton938ace62002-07-17 16:30:39 +000043static PyTypeObject Arraytype;
Guido van Rossum778983b1993-02-19 15:55:02 +000044
Martin v. Löwis99866332002-03-01 10:27:01 +000045#define array_Check(op) PyObject_TypeCheck(op, &Arraytype)
Christian Heimes90aa7642007-12-19 02:45:37 +000046#define array_CheckExact(op) (Py_TYPE(op) == &Arraytype)
Guido van Rossum778983b1993-02-19 15:55:02 +000047
Raymond Hettinger6e2ee862004-03-14 04:37:50 +000048static int
Martin v. Löwis18e16552006-02-15 17:27:45 +000049array_resize(arrayobject *self, Py_ssize_t newsize)
Raymond Hettinger6e2ee862004-03-14 04:37:50 +000050{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000051 char *items;
52 size_t _new_size;
Raymond Hettinger6e2ee862004-03-14 04:37:50 +000053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000054 if (self->ob_exports > 0 && newsize != Py_SIZE(self)) {
55 PyErr_SetString(PyExc_BufferError,
56 "cannot resize an array that is exporting buffers");
57 return -1;
58 }
Antoine Pitrou3ad3a0d2008-12-18 17:08:32 +000059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000060 /* Bypass realloc() when a previous overallocation is large enough
61 to accommodate the newsize. If the newsize is 16 smaller than the
62 current size, then proceed with the realloc() to shrink the array.
63 */
Raymond Hettinger6e2ee862004-03-14 04:37:50 +000064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000065 if (self->allocated >= newsize &&
66 Py_SIZE(self) < newsize + 16 &&
67 self->ob_item != NULL) {
68 Py_SIZE(self) = newsize;
69 return 0;
70 }
Raymond Hettinger6e2ee862004-03-14 04:37:50 +000071
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000072 if (newsize == 0) {
73 PyMem_FREE(self->ob_item);
74 self->ob_item = NULL;
75 Py_SIZE(self) = 0;
76 self->allocated = 0;
77 return 0;
78 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +000079
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000080 /* This over-allocates proportional to the array size, making room
81 * for additional growth. The over-allocation is mild, but is
82 * enough to give linear-time amortized behavior over a long
83 * sequence of appends() in the presence of a poorly-performing
84 * system realloc().
85 * The growth pattern is: 0, 4, 8, 16, 25, 34, 46, 56, 67, 79, ...
86 * Note, the pattern starts out the same as for lists but then
87 * grows at a smaller rate so that larger arrays only overallocate
88 * by about 1/16th -- this is done because arrays are presumed to be more
89 * memory critical.
90 */
Raymond Hettinger6e2ee862004-03-14 04:37:50 +000091
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000092 _new_size = (newsize >> 4) + (Py_SIZE(self) < 8 ? 3 : 7) + newsize;
93 items = self->ob_item;
94 /* XXX The following multiplication and division does not optimize away
95 like it does for lists since the size is not known at compile time */
96 if (_new_size <= ((~(size_t)0) / self->ob_descr->itemsize))
97 PyMem_RESIZE(items, char, (_new_size * self->ob_descr->itemsize));
98 else
99 items = NULL;
100 if (items == NULL) {
101 PyErr_NoMemory();
102 return -1;
103 }
104 self->ob_item = items;
105 Py_SIZE(self) = newsize;
106 self->allocated = _new_size;
107 return 0;
Raymond Hettinger6e2ee862004-03-14 04:37:50 +0000108}
109
Tim Petersbb307342000-09-10 05:22:54 +0000110/****************************************************************************
111Get and Set functions for each type.
112A Get function takes an arrayobject* and an integer index, returning the
113array value at that index wrapped in an appropriate PyObject*.
114A Set function takes an arrayobject, integer index, and PyObject*; sets
115the array value at that index to the raw C data extracted from the PyObject*,
116and returns 0 if successful, else nonzero on failure (PyObject* not of an
117appropriate type or value).
118Note that the basic Get and Set functions do NOT check that the index is
119in bounds; that's the responsibility of the caller.
120****************************************************************************/
Guido van Rossum778983b1993-02-19 15:55:02 +0000121
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000122static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000123b_getitem(arrayobject *ap, Py_ssize_t i)
Guido van Rossum778983b1993-02-19 15:55:02 +0000124{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000125 long x = ((char *)ap->ob_item)[i];
126 if (x >= 128)
127 x -= 256;
128 return PyLong_FromLong(x);
Guido van Rossum778983b1993-02-19 15:55:02 +0000129}
130
131static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000132b_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
Guido van Rossum778983b1993-02-19 15:55:02 +0000133{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000134 short x;
135 /* PyArg_Parse's 'b' formatter is for an unsigned char, therefore
136 must use the next size up that is signed ('h') and manually do
137 the overflow checking */
138 if (!PyArg_Parse(v, "h;array item must be integer", &x))
139 return -1;
140 else if (x < -128) {
141 PyErr_SetString(PyExc_OverflowError,
142 "signed char is less than minimum");
143 return -1;
144 }
145 else if (x > 127) {
146 PyErr_SetString(PyExc_OverflowError,
147 "signed char is greater than maximum");
148 return -1;
149 }
150 if (i >= 0)
151 ((char *)ap->ob_item)[i] = (char)x;
152 return 0;
Guido van Rossum778983b1993-02-19 15:55:02 +0000153}
154
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000155static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000156BB_getitem(arrayobject *ap, Py_ssize_t i)
Guido van Rossum549ab711997-01-03 19:09:47 +0000157{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000158 long x = ((unsigned char *)ap->ob_item)[i];
159 return PyLong_FromLong(x);
Guido van Rossum549ab711997-01-03 19:09:47 +0000160}
161
Fred Drake541dc3b2000-06-28 17:49:30 +0000162static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000163BB_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
Fred Drake541dc3b2000-06-28 17:49:30 +0000164{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000165 unsigned char x;
166 /* 'B' == unsigned char, maps to PyArg_Parse's 'b' formatter */
167 if (!PyArg_Parse(v, "b;array item must be integer", &x))
168 return -1;
169 if (i >= 0)
170 ((char *)ap->ob_item)[i] = x;
171 return 0;
Fred Drake541dc3b2000-06-28 17:49:30 +0000172}
Guido van Rossum549ab711997-01-03 19:09:47 +0000173
Martin v. Löwis99866332002-03-01 10:27:01 +0000174static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000175u_getitem(arrayobject *ap, Py_ssize_t i)
Martin v. Löwis99866332002-03-01 10:27:01 +0000176{
Victor Stinner8dba4e02011-09-30 00:51:10 +0200177 return PyUnicode_FromOrdinal(((Py_UCS4 *) ap->ob_item)[i]);
Martin v. Löwis99866332002-03-01 10:27:01 +0000178}
179
180static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000181u_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
Martin v. Löwis99866332002-03-01 10:27:01 +0000182{
Victor Stinner8dba4e02011-09-30 00:51:10 +0200183 PyObject *p;
Martin v. Löwis99866332002-03-01 10:27:01 +0000184
Victor Stinner8dba4e02011-09-30 00:51:10 +0200185 if (!PyArg_Parse(v, "U;array item must be unicode character", &p))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000186 return -1;
Victor Stinner8dba4e02011-09-30 00:51:10 +0200187 if (PyUnicode_READY(p))
188 return -1;
189 if (PyUnicode_GET_LENGTH(p) != 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000190 PyErr_SetString(PyExc_TypeError,
191 "array item must be unicode character");
192 return -1;
193 }
194 if (i >= 0)
Victor Stinner8dba4e02011-09-30 00:51:10 +0200195 ((Py_UCS4 *)ap->ob_item)[i] = PyUnicode_READ_CHAR(p, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000196 return 0;
Martin v. Löwis99866332002-03-01 10:27:01 +0000197}
Martin v. Löwis99866332002-03-01 10:27:01 +0000198
Travis E. Oliphantd5c0add2007-10-12 22:05:15 +0000199
Guido van Rossum549ab711997-01-03 19:09:47 +0000200static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000201h_getitem(arrayobject *ap, Py_ssize_t i)
Guido van Rossum778983b1993-02-19 15:55:02 +0000202{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000203 return PyLong_FromLong((long) ((short *)ap->ob_item)[i]);
Guido van Rossum778983b1993-02-19 15:55:02 +0000204}
205
Travis E. Oliphantd5c0add2007-10-12 22:05:15 +0000206
Guido van Rossum778983b1993-02-19 15:55:02 +0000207static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000208h_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
Guido van Rossum778983b1993-02-19 15:55:02 +0000209{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000210 short x;
211 /* 'h' == signed short, maps to PyArg_Parse's 'h' formatter */
212 if (!PyArg_Parse(v, "h;array item must be integer", &x))
213 return -1;
214 if (i >= 0)
215 ((short *)ap->ob_item)[i] = x;
216 return 0;
Guido van Rossum778983b1993-02-19 15:55:02 +0000217}
218
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000219static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000220HH_getitem(arrayobject *ap, Py_ssize_t i)
Guido van Rossum549ab711997-01-03 19:09:47 +0000221{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000222 return PyLong_FromLong((long) ((unsigned short *)ap->ob_item)[i]);
Guido van Rossum549ab711997-01-03 19:09:47 +0000223}
224
Fred Drake541dc3b2000-06-28 17:49:30 +0000225static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000226HH_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
Fred Drake541dc3b2000-06-28 17:49:30 +0000227{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000228 int x;
229 /* PyArg_Parse's 'h' formatter is for a signed short, therefore
230 must use the next size up and manually do the overflow checking */
231 if (!PyArg_Parse(v, "i;array item must be integer", &x))
232 return -1;
233 else if (x < 0) {
234 PyErr_SetString(PyExc_OverflowError,
235 "unsigned short is less than minimum");
236 return -1;
237 }
238 else if (x > USHRT_MAX) {
239 PyErr_SetString(PyExc_OverflowError,
240 "unsigned short is greater than maximum");
241 return -1;
242 }
243 if (i >= 0)
244 ((short *)ap->ob_item)[i] = (short)x;
245 return 0;
Fred Drake541dc3b2000-06-28 17:49:30 +0000246}
Guido van Rossum549ab711997-01-03 19:09:47 +0000247
248static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000249i_getitem(arrayobject *ap, Py_ssize_t i)
Guido van Rossume77a7571993-11-03 15:01:26 +0000250{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000251 return PyLong_FromLong((long) ((int *)ap->ob_item)[i]);
Guido van Rossume77a7571993-11-03 15:01:26 +0000252}
253
254static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000255i_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
Guido van Rossume77a7571993-11-03 15:01:26 +0000256{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000257 int x;
258 /* 'i' == signed int, maps to PyArg_Parse's 'i' formatter */
259 if (!PyArg_Parse(v, "i;array item must be integer", &x))
260 return -1;
261 if (i >= 0)
262 ((int *)ap->ob_item)[i] = x;
263 return 0;
Guido van Rossume77a7571993-11-03 15:01:26 +0000264}
265
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000266static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000267II_getitem(arrayobject *ap, Py_ssize_t i)
Guido van Rossum549ab711997-01-03 19:09:47 +0000268{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000269 return PyLong_FromUnsignedLong(
270 (unsigned long) ((unsigned int *)ap->ob_item)[i]);
Guido van Rossum549ab711997-01-03 19:09:47 +0000271}
272
273static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000274II_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
Guido van Rossum549ab711997-01-03 19:09:47 +0000275{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000276 unsigned long x;
277 if (PyLong_Check(v)) {
278 x = PyLong_AsUnsignedLong(v);
279 if (x == (unsigned long) -1 && PyErr_Occurred())
280 return -1;
281 }
282 else {
283 long y;
284 if (!PyArg_Parse(v, "l;array item must be integer", &y))
285 return -1;
286 if (y < 0) {
287 PyErr_SetString(PyExc_OverflowError,
288 "unsigned int is less than minimum");
289 return -1;
290 }
291 x = (unsigned long)y;
Tim Petersbb307342000-09-10 05:22:54 +0000292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000293 }
294 if (x > UINT_MAX) {
295 PyErr_SetString(PyExc_OverflowError,
296 "unsigned int is greater than maximum");
297 return -1;
298 }
Fred Drake541dc3b2000-06-28 17:49:30 +0000299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000300 if (i >= 0)
301 ((unsigned int *)ap->ob_item)[i] = (unsigned int)x;
302 return 0;
Guido van Rossum549ab711997-01-03 19:09:47 +0000303}
304
305static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000306l_getitem(arrayobject *ap, Py_ssize_t i)
Guido van Rossum778983b1993-02-19 15:55:02 +0000307{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000308 return PyLong_FromLong(((long *)ap->ob_item)[i]);
Guido van Rossum778983b1993-02-19 15:55:02 +0000309}
310
311static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000312l_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
Guido van Rossum778983b1993-02-19 15:55:02 +0000313{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000314 long x;
315 if (!PyArg_Parse(v, "l;array item must be integer", &x))
316 return -1;
317 if (i >= 0)
318 ((long *)ap->ob_item)[i] = x;
319 return 0;
Guido van Rossum778983b1993-02-19 15:55:02 +0000320}
321
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000322static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000323LL_getitem(arrayobject *ap, Py_ssize_t i)
Guido van Rossum549ab711997-01-03 19:09:47 +0000324{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000325 return PyLong_FromUnsignedLong(((unsigned long *)ap->ob_item)[i]);
Guido van Rossum549ab711997-01-03 19:09:47 +0000326}
327
328static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000329LL_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
Guido van Rossum549ab711997-01-03 19:09:47 +0000330{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000331 unsigned long x;
332 if (PyLong_Check(v)) {
333 x = PyLong_AsUnsignedLong(v);
334 if (x == (unsigned long) -1 && PyErr_Occurred())
335 return -1;
336 }
337 else {
338 long y;
339 if (!PyArg_Parse(v, "l;array item must be integer", &y))
340 return -1;
341 if (y < 0) {
342 PyErr_SetString(PyExc_OverflowError,
343 "unsigned long is less than minimum");
344 return -1;
345 }
346 x = (unsigned long)y;
Tim Petersbb307342000-09-10 05:22:54 +0000347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000348 }
349 if (x > ULONG_MAX) {
350 PyErr_SetString(PyExc_OverflowError,
351 "unsigned long is greater than maximum");
352 return -1;
353 }
Tim Petersbb307342000-09-10 05:22:54 +0000354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000355 if (i >= 0)
356 ((unsigned long *)ap->ob_item)[i] = x;
357 return 0;
Guido van Rossum549ab711997-01-03 19:09:47 +0000358}
359
Meador Inge1c9f0c92011-09-20 19:55:51 -0500360#ifdef HAVE_LONG_LONG
361
362static PyObject *
363q_getitem(arrayobject *ap, Py_ssize_t i)
364{
365 return PyLong_FromLongLong(((PY_LONG_LONG *)ap->ob_item)[i]);
366}
367
368static int
369q_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
370{
371 PY_LONG_LONG x;
372 if (!PyArg_Parse(v, "L;array item must be integer", &x))
373 return -1;
374 if (i >= 0)
375 ((PY_LONG_LONG *)ap->ob_item)[i] = x;
376 return 0;
377}
378
379static PyObject *
380QQ_getitem(arrayobject *ap, Py_ssize_t i)
381{
382 return PyLong_FromUnsignedLongLong(
383 ((unsigned PY_LONG_LONG *)ap->ob_item)[i]);
384}
385
386static int
387QQ_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
388{
389 unsigned PY_LONG_LONG x;
390 if (PyLong_Check(v)) {
391 x = PyLong_AsUnsignedLongLong(v);
392 if (x == (unsigned PY_LONG_LONG) -1 && PyErr_Occurred())
393 return -1;
394 }
395 else {
396 PY_LONG_LONG y;
397 if (!PyArg_Parse(v, "L;array item must be integer", &y))
398 return -1;
399 if (y < 0) {
400 PyErr_SetString(PyExc_OverflowError,
401 "unsigned long long is less than minimum");
402 return -1;
403 }
404 x = (unsigned PY_LONG_LONG)y;
405 }
406
407 if (i >= 0)
408 ((unsigned PY_LONG_LONG *)ap->ob_item)[i] = x;
409 return 0;
410}
411#endif
412
Guido van Rossum549ab711997-01-03 19:09:47 +0000413static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000414f_getitem(arrayobject *ap, Py_ssize_t i)
Guido van Rossum778983b1993-02-19 15:55:02 +0000415{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000416 return PyFloat_FromDouble((double) ((float *)ap->ob_item)[i]);
Guido van Rossum778983b1993-02-19 15:55:02 +0000417}
418
419static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000420f_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
Guido van Rossum778983b1993-02-19 15:55:02 +0000421{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000422 float x;
423 if (!PyArg_Parse(v, "f;array item must be float", &x))
424 return -1;
425 if (i >= 0)
426 ((float *)ap->ob_item)[i] = x;
427 return 0;
Guido van Rossum778983b1993-02-19 15:55:02 +0000428}
429
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000430static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000431d_getitem(arrayobject *ap, Py_ssize_t i)
Guido van Rossum778983b1993-02-19 15:55:02 +0000432{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000433 return PyFloat_FromDouble(((double *)ap->ob_item)[i]);
Guido van Rossum778983b1993-02-19 15:55:02 +0000434}
435
436static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000437d_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
Guido van Rossum778983b1993-02-19 15:55:02 +0000438{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000439 double x;
440 if (!PyArg_Parse(v, "d;array item must be float", &x))
441 return -1;
442 if (i >= 0)
443 ((double *)ap->ob_item)[i] = x;
444 return 0;
Guido van Rossum778983b1993-02-19 15:55:02 +0000445}
446
Victor Stinner8dba4e02011-09-30 00:51:10 +0200447#if SIZEOF_INT == 4
448# define STRUCT_LONG_FORMAT "I"
449#elif SIZEOF_LONG == 4
450# define STRUCT_LONG_FORMAT "L"
451#else
452# error "Unable to get struct format for Py_UCS4"
453#endif
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000454
Alexandre Vassalottiad077152009-07-15 17:49:23 +0000455/* Description of types.
456 *
457 * Don't forget to update typecode_to_mformat_code() if you add a new
458 * typecode.
459 */
Guido van Rossum234f9421993-06-17 12:35:49 +0000460static struct arraydescr descriptors[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 {'b', 1, b_getitem, b_setitem, "b", 1, 1},
462 {'B', 1, BB_getitem, BB_setitem, "B", 1, 0},
Victor Stinner8dba4e02011-09-30 00:51:10 +0200463 {'u', sizeof(Py_UCS4), u_getitem, u_setitem, STRUCT_LONG_FORMAT, 0, 0},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000464 {'h', sizeof(short), h_getitem, h_setitem, "h", 1, 1},
465 {'H', sizeof(short), HH_getitem, HH_setitem, "H", 1, 0},
466 {'i', sizeof(int), i_getitem, i_setitem, "i", 1, 1},
467 {'I', sizeof(int), II_getitem, II_setitem, "I", 1, 0},
468 {'l', sizeof(long), l_getitem, l_setitem, "l", 1, 1},
469 {'L', sizeof(long), LL_getitem, LL_setitem, "L", 1, 0},
Meador Inge1c9f0c92011-09-20 19:55:51 -0500470#ifdef HAVE_LONG_LONG
471 {'q', sizeof(PY_LONG_LONG), q_getitem, q_setitem, "q", 1, 1},
472 {'Q', sizeof(PY_LONG_LONG), QQ_getitem, QQ_setitem, "Q", 1, 0},
473#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 {'f', sizeof(float), f_getitem, f_setitem, "f", 0, 0},
475 {'d', sizeof(double), d_getitem, d_setitem, "d", 0, 0},
476 {'\0', 0, 0, 0, 0, 0, 0} /* Sentinel */
Guido van Rossum778983b1993-02-19 15:55:02 +0000477};
Tim Petersbb307342000-09-10 05:22:54 +0000478
479/****************************************************************************
480Implementations of array object methods.
481****************************************************************************/
Guido van Rossum778983b1993-02-19 15:55:02 +0000482
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000483static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000484newarrayobject(PyTypeObject *type, Py_ssize_t size, struct arraydescr *descr)
Guido van Rossum778983b1993-02-19 15:55:02 +0000485{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 arrayobject *op;
487 size_t nbytes;
Martin v. Löwis99866332002-03-01 10:27:01 +0000488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 if (size < 0) {
490 PyErr_BadInternalCall();
491 return NULL;
492 }
Martin v. Löwis99866332002-03-01 10:27:01 +0000493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 nbytes = size * descr->itemsize;
495 /* Check for overflow */
496 if (nbytes / descr->itemsize != (size_t)size) {
497 return PyErr_NoMemory();
498 }
499 op = (arrayobject *) type->tp_alloc(type, 0);
500 if (op == NULL) {
501 return NULL;
502 }
503 op->ob_descr = descr;
504 op->allocated = size;
505 op->weakreflist = NULL;
506 Py_SIZE(op) = size;
507 if (size <= 0) {
508 op->ob_item = NULL;
509 }
510 else {
511 op->ob_item = PyMem_NEW(char, nbytes);
512 if (op->ob_item == NULL) {
513 Py_DECREF(op);
514 return PyErr_NoMemory();
515 }
516 }
517 op->ob_exports = 0;
518 return (PyObject *) op;
Guido van Rossum778983b1993-02-19 15:55:02 +0000519}
520
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000521static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000522getarrayitem(PyObject *op, Py_ssize_t i)
Guido van Rossum778983b1993-02-19 15:55:02 +0000523{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000524 register arrayobject *ap;
525 assert(array_Check(op));
526 ap = (arrayobject *)op;
527 assert(i>=0 && i<Py_SIZE(ap));
528 return (*ap->ob_descr->getitem)(ap, i);
Guido van Rossum778983b1993-02-19 15:55:02 +0000529}
530
531static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000532ins1(arrayobject *self, Py_ssize_t where, PyObject *v)
Guido van Rossum778983b1993-02-19 15:55:02 +0000533{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 char *items;
535 Py_ssize_t n = Py_SIZE(self);
536 if (v == NULL) {
537 PyErr_BadInternalCall();
538 return -1;
539 }
540 if ((*self->ob_descr->setitem)(self, -1, v) < 0)
541 return -1;
Raymond Hettinger6e2ee862004-03-14 04:37:50 +0000542
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000543 if (array_resize(self, n+1) == -1)
544 return -1;
545 items = self->ob_item;
546 if (where < 0) {
547 where += n;
548 if (where < 0)
549 where = 0;
550 }
551 if (where > n)
552 where = n;
553 /* appends don't need to call memmove() */
554 if (where != n)
555 memmove(items + (where+1)*self->ob_descr->itemsize,
556 items + where*self->ob_descr->itemsize,
557 (n-where)*self->ob_descr->itemsize);
558 return (*self->ob_descr->setitem)(self, where, v);
Guido van Rossum778983b1993-02-19 15:55:02 +0000559}
560
Guido van Rossum778983b1993-02-19 15:55:02 +0000561/* Methods */
562
563static void
Peter Schneider-Kamp9656abd2000-07-13 21:10:57 +0000564array_dealloc(arrayobject *op)
Guido van Rossum778983b1993-02-19 15:55:02 +0000565{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000566 if (op->weakreflist != NULL)
567 PyObject_ClearWeakRefs((PyObject *) op);
568 if (op->ob_item != NULL)
569 PyMem_DEL(op->ob_item);
570 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossum778983b1993-02-19 15:55:02 +0000571}
572
Guido van Rossum9d19cb82001-01-18 01:02:55 +0000573static PyObject *
574array_richcompare(PyObject *v, PyObject *w, int op)
Guido van Rossum778983b1993-02-19 15:55:02 +0000575{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000576 arrayobject *va, *wa;
577 PyObject *vi = NULL;
578 PyObject *wi = NULL;
579 Py_ssize_t i, k;
580 PyObject *res;
Guido van Rossum9d19cb82001-01-18 01:02:55 +0000581
Brian Curtindfc80e32011-08-10 20:28:54 -0500582 if (!array_Check(v) || !array_Check(w))
583 Py_RETURN_NOTIMPLEMENTED;
Guido van Rossum9d19cb82001-01-18 01:02:55 +0000584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000585 va = (arrayobject *)v;
586 wa = (arrayobject *)w;
Guido van Rossum9d19cb82001-01-18 01:02:55 +0000587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000588 if (Py_SIZE(va) != Py_SIZE(wa) && (op == Py_EQ || op == Py_NE)) {
589 /* Shortcut: if the lengths differ, the arrays differ */
590 if (op == Py_EQ)
591 res = Py_False;
592 else
593 res = Py_True;
594 Py_INCREF(res);
595 return res;
596 }
Guido van Rossum9d19cb82001-01-18 01:02:55 +0000597
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000598 /* Search for the first index where items are different */
599 k = 1;
600 for (i = 0; i < Py_SIZE(va) && i < Py_SIZE(wa); i++) {
601 vi = getarrayitem(v, i);
602 wi = getarrayitem(w, i);
603 if (vi == NULL || wi == NULL) {
604 Py_XDECREF(vi);
605 Py_XDECREF(wi);
606 return NULL;
607 }
608 k = PyObject_RichCompareBool(vi, wi, Py_EQ);
609 if (k == 0)
610 break; /* Keeping vi and wi alive! */
611 Py_DECREF(vi);
612 Py_DECREF(wi);
613 if (k < 0)
614 return NULL;
615 }
Guido van Rossum9d19cb82001-01-18 01:02:55 +0000616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000617 if (k) {
618 /* No more items to compare -- compare sizes */
619 Py_ssize_t vs = Py_SIZE(va);
620 Py_ssize_t ws = Py_SIZE(wa);
621 int cmp;
622 switch (op) {
623 case Py_LT: cmp = vs < ws; break;
624 case Py_LE: cmp = vs <= ws; break;
625 case Py_EQ: cmp = vs == ws; break;
626 case Py_NE: cmp = vs != ws; break;
627 case Py_GT: cmp = vs > ws; break;
628 case Py_GE: cmp = vs >= ws; break;
629 default: return NULL; /* cannot happen */
630 }
631 if (cmp)
632 res = Py_True;
633 else
634 res = Py_False;
635 Py_INCREF(res);
636 return res;
637 }
Guido van Rossum9d19cb82001-01-18 01:02:55 +0000638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000639 /* We have an item that differs. First, shortcuts for EQ/NE */
640 if (op == Py_EQ) {
641 Py_INCREF(Py_False);
642 res = Py_False;
643 }
644 else if (op == Py_NE) {
645 Py_INCREF(Py_True);
646 res = Py_True;
647 }
648 else {
649 /* Compare the final item again using the proper operator */
650 res = PyObject_RichCompare(vi, wi, op);
651 }
652 Py_DECREF(vi);
653 Py_DECREF(wi);
654 return res;
Guido van Rossum778983b1993-02-19 15:55:02 +0000655}
656
Martin v. Löwis18e16552006-02-15 17:27:45 +0000657static Py_ssize_t
Peter Schneider-Kamp9656abd2000-07-13 21:10:57 +0000658array_length(arrayobject *a)
Guido van Rossum778983b1993-02-19 15:55:02 +0000659{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000660 return Py_SIZE(a);
Guido van Rossum778983b1993-02-19 15:55:02 +0000661}
662
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000663static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000664array_item(arrayobject *a, Py_ssize_t i)
Guido van Rossum778983b1993-02-19 15:55:02 +0000665{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000666 if (i < 0 || i >= Py_SIZE(a)) {
667 PyErr_SetString(PyExc_IndexError, "array index out of range");
668 return NULL;
669 }
670 return getarrayitem((PyObject *)a, i);
Guido van Rossum778983b1993-02-19 15:55:02 +0000671}
672
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000673static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000674array_slice(arrayobject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum778983b1993-02-19 15:55:02 +0000675{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 arrayobject *np;
677 if (ilow < 0)
678 ilow = 0;
679 else if (ilow > Py_SIZE(a))
680 ilow = Py_SIZE(a);
681 if (ihigh < 0)
682 ihigh = 0;
683 if (ihigh < ilow)
684 ihigh = ilow;
685 else if (ihigh > Py_SIZE(a))
686 ihigh = Py_SIZE(a);
687 np = (arrayobject *) newarrayobject(&Arraytype, ihigh - ilow, a->ob_descr);
688 if (np == NULL)
689 return NULL;
690 memcpy(np->ob_item, a->ob_item + ilow * a->ob_descr->itemsize,
691 (ihigh-ilow) * a->ob_descr->itemsize);
692 return (PyObject *)np;
Guido van Rossum778983b1993-02-19 15:55:02 +0000693}
694
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000695static PyObject *
Raymond Hettinger3aa82c02004-03-13 18:18:51 +0000696array_copy(arrayobject *a, PyObject *unused)
697{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000698 return array_slice(a, 0, Py_SIZE(a));
Raymond Hettinger3aa82c02004-03-13 18:18:51 +0000699}
700
701PyDoc_STRVAR(copy_doc,
702"copy(array)\n\
703\n\
704 Return a copy of the array.");
705
706static PyObject *
Peter Schneider-Kamp9656abd2000-07-13 21:10:57 +0000707array_concat(arrayobject *a, PyObject *bb)
Guido van Rossum778983b1993-02-19 15:55:02 +0000708{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000709 Py_ssize_t size;
710 arrayobject *np;
711 if (!array_Check(bb)) {
712 PyErr_Format(PyExc_TypeError,
713 "can only append array (not \"%.200s\") to array",
714 Py_TYPE(bb)->tp_name);
715 return NULL;
716 }
Guido van Rossum778983b1993-02-19 15:55:02 +0000717#define b ((arrayobject *)bb)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 if (a->ob_descr != b->ob_descr) {
719 PyErr_BadArgument();
720 return NULL;
721 }
722 if (Py_SIZE(a) > PY_SSIZE_T_MAX - Py_SIZE(b)) {
723 return PyErr_NoMemory();
724 }
725 size = Py_SIZE(a) + Py_SIZE(b);
726 np = (arrayobject *) newarrayobject(&Arraytype, size, a->ob_descr);
727 if (np == NULL) {
728 return NULL;
729 }
730 memcpy(np->ob_item, a->ob_item, Py_SIZE(a)*a->ob_descr->itemsize);
731 memcpy(np->ob_item + Py_SIZE(a)*a->ob_descr->itemsize,
732 b->ob_item, Py_SIZE(b)*b->ob_descr->itemsize);
733 return (PyObject *)np;
Guido van Rossum778983b1993-02-19 15:55:02 +0000734#undef b
735}
736
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000737static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000738array_repeat(arrayobject *a, Py_ssize_t n)
Guido van Rossum778983b1993-02-19 15:55:02 +0000739{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000740 Py_ssize_t size;
741 arrayobject *np;
Georg Brandlc29cc6a2010-12-04 11:02:04 +0000742 Py_ssize_t oldbytes, newbytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000743 if (n < 0)
744 n = 0;
745 if ((Py_SIZE(a) != 0) && (n > PY_SSIZE_T_MAX / Py_SIZE(a))) {
746 return PyErr_NoMemory();
747 }
748 size = Py_SIZE(a) * n;
749 np = (arrayobject *) newarrayobject(&Arraytype, size, a->ob_descr);
750 if (np == NULL)
751 return NULL;
Georg Brandlc29cc6a2010-12-04 11:02:04 +0000752 if (n == 0)
753 return (PyObject *)np;
754 oldbytes = Py_SIZE(a) * a->ob_descr->itemsize;
755 newbytes = oldbytes * n;
756 /* this follows the code in unicode_repeat */
757 if (oldbytes == 1) {
758 memset(np->ob_item, a->ob_item[0], newbytes);
759 } else {
760 Py_ssize_t done = oldbytes;
761 Py_MEMCPY(np->ob_item, a->ob_item, oldbytes);
762 while (done < newbytes) {
763 Py_ssize_t ncopy = (done <= newbytes-done) ? done : newbytes-done;
764 Py_MEMCPY(np->ob_item+done, np->ob_item, ncopy);
765 done += ncopy;
766 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000767 }
Georg Brandlc29cc6a2010-12-04 11:02:04 +0000768 return (PyObject *)np;
Guido van Rossum778983b1993-02-19 15:55:02 +0000769}
770
771static int
Martin v. Löwisad0a4622006-02-16 14:30:23 +0000772array_ass_slice(arrayobject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum778983b1993-02-19 15:55:02 +0000773{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000774 char *item;
775 Py_ssize_t n; /* Size of replacement array */
776 Py_ssize_t d; /* Change in size */
Guido van Rossum778983b1993-02-19 15:55:02 +0000777#define b ((arrayobject *)v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 if (v == NULL)
779 n = 0;
780 else if (array_Check(v)) {
781 n = Py_SIZE(b);
782 if (a == b) {
783 /* Special case "a[i:j] = a" -- copy b first */
784 int ret;
785 v = array_slice(b, 0, n);
786 if (!v)
787 return -1;
788 ret = array_ass_slice(a, ilow, ihigh, v);
789 Py_DECREF(v);
790 return ret;
791 }
792 if (b->ob_descr != a->ob_descr) {
793 PyErr_BadArgument();
794 return -1;
795 }
796 }
797 else {
798 PyErr_Format(PyExc_TypeError,
799 "can only assign array (not \"%.200s\") to array slice",
800 Py_TYPE(v)->tp_name);
801 return -1;
802 }
803 if (ilow < 0)
804 ilow = 0;
805 else if (ilow > Py_SIZE(a))
806 ilow = Py_SIZE(a);
807 if (ihigh < 0)
808 ihigh = 0;
809 if (ihigh < ilow)
810 ihigh = ilow;
811 else if (ihigh > Py_SIZE(a))
812 ihigh = Py_SIZE(a);
813 item = a->ob_item;
814 d = n - (ihigh-ilow);
815 /* Issue #4509: If the array has exported buffers and the slice
816 assignment would change the size of the array, fail early to make
817 sure we don't modify it. */
818 if (d != 0 && a->ob_exports > 0) {
819 PyErr_SetString(PyExc_BufferError,
820 "cannot resize an array that is exporting buffers");
821 return -1;
822 }
823 if (d < 0) { /* Delete -d items */
824 memmove(item + (ihigh+d)*a->ob_descr->itemsize,
825 item + ihigh*a->ob_descr->itemsize,
826 (Py_SIZE(a)-ihigh)*a->ob_descr->itemsize);
827 if (array_resize(a, Py_SIZE(a) + d) == -1)
828 return -1;
829 }
830 else if (d > 0) { /* Insert d items */
831 if (array_resize(a, Py_SIZE(a) + d))
832 return -1;
833 memmove(item + (ihigh+d)*a->ob_descr->itemsize,
834 item + ihigh*a->ob_descr->itemsize,
835 (Py_SIZE(a)-ihigh)*a->ob_descr->itemsize);
836 }
837 if (n > 0)
838 memcpy(item + ilow*a->ob_descr->itemsize, b->ob_item,
839 n*b->ob_descr->itemsize);
840 return 0;
Guido van Rossum778983b1993-02-19 15:55:02 +0000841#undef b
842}
843
844static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000845array_ass_item(arrayobject *a, Py_ssize_t i, PyObject *v)
Guido van Rossum778983b1993-02-19 15:55:02 +0000846{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000847 if (i < 0 || i >= Py_SIZE(a)) {
848 PyErr_SetString(PyExc_IndexError,
849 "array assignment index out of range");
850 return -1;
851 }
852 if (v == NULL)
853 return array_ass_slice(a, i, i+1, v);
854 return (*a->ob_descr->setitem)(a, i, v);
Guido van Rossum778983b1993-02-19 15:55:02 +0000855}
856
857static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000858setarrayitem(PyObject *a, Py_ssize_t i, PyObject *v)
Guido van Rossum778983b1993-02-19 15:55:02 +0000859{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000860 assert(array_Check(a));
861 return array_ass_item((arrayobject *)a, i, v);
Guido van Rossum778983b1993-02-19 15:55:02 +0000862}
863
Martin v. Löwis99866332002-03-01 10:27:01 +0000864static int
Raymond Hettinger49f9bd12004-03-14 05:43:59 +0000865array_iter_extend(arrayobject *self, PyObject *bb)
866{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000867 PyObject *it, *v;
Raymond Hettinger49f9bd12004-03-14 05:43:59 +0000868
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000869 it = PyObject_GetIter(bb);
870 if (it == NULL)
871 return -1;
Raymond Hettinger49f9bd12004-03-14 05:43:59 +0000872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000873 while ((v = PyIter_Next(it)) != NULL) {
Mark Dickinson346f0af2010-08-06 09:36:57 +0000874 if (ins1(self, Py_SIZE(self), v) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000875 Py_DECREF(v);
876 Py_DECREF(it);
877 return -1;
878 }
879 Py_DECREF(v);
880 }
881 Py_DECREF(it);
882 if (PyErr_Occurred())
883 return -1;
884 return 0;
Raymond Hettinger49f9bd12004-03-14 05:43:59 +0000885}
886
887static int
Martin v. Löwis99866332002-03-01 10:27:01 +0000888array_do_extend(arrayobject *self, PyObject *bb)
889{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000890 Py_ssize_t size, oldsize, bbsize;
Martin v. Löwis99866332002-03-01 10:27:01 +0000891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000892 if (!array_Check(bb))
893 return array_iter_extend(self, bb);
894#define b ((arrayobject *)bb)
895 if (self->ob_descr != b->ob_descr) {
896 PyErr_SetString(PyExc_TypeError,
897 "can only extend with array of same kind");
898 return -1;
899 }
900 if ((Py_SIZE(self) > PY_SSIZE_T_MAX - Py_SIZE(b)) ||
901 ((Py_SIZE(self) + Py_SIZE(b)) > PY_SSIZE_T_MAX / self->ob_descr->itemsize)) {
902 PyErr_NoMemory();
903 return -1;
904 }
905 oldsize = Py_SIZE(self);
906 /* Get the size of bb before resizing the array since bb could be self. */
907 bbsize = Py_SIZE(bb);
908 size = oldsize + Py_SIZE(b);
909 if (array_resize(self, size) == -1)
910 return -1;
911 memcpy(self->ob_item + oldsize * self->ob_descr->itemsize,
912 b->ob_item, bbsize * b->ob_descr->itemsize);
913
914 return 0;
Martin v. Löwis99866332002-03-01 10:27:01 +0000915#undef b
916}
917
918static PyObject *
919array_inplace_concat(arrayobject *self, PyObject *bb)
920{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 if (!array_Check(bb)) {
922 PyErr_Format(PyExc_TypeError,
923 "can only extend array with array (not \"%.200s\")",
924 Py_TYPE(bb)->tp_name);
925 return NULL;
926 }
927 if (array_do_extend(self, bb) == -1)
928 return NULL;
929 Py_INCREF(self);
930 return (PyObject *)self;
Martin v. Löwis99866332002-03-01 10:27:01 +0000931}
932
933static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000934array_inplace_repeat(arrayobject *self, Py_ssize_t n)
Martin v. Löwis99866332002-03-01 10:27:01 +0000935{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 char *items, *p;
937 Py_ssize_t size, i;
Martin v. Löwis99866332002-03-01 10:27:01 +0000938
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 if (Py_SIZE(self) > 0) {
940 if (n < 0)
941 n = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 if ((self->ob_descr->itemsize != 0) &&
943 (Py_SIZE(self) > PY_SSIZE_T_MAX / self->ob_descr->itemsize)) {
944 return PyErr_NoMemory();
945 }
946 size = Py_SIZE(self) * self->ob_descr->itemsize;
947 if (n > 0 && size > PY_SSIZE_T_MAX / n) {
948 return PyErr_NoMemory();
949 }
950 if (array_resize(self, n * Py_SIZE(self)) == -1)
951 return NULL;
952 items = p = self->ob_item;
953 for (i = 1; i < n; i++) {
954 p += size;
955 memcpy(p, items, size);
956 }
957 }
958 Py_INCREF(self);
959 return (PyObject *)self;
Martin v. Löwis99866332002-03-01 10:27:01 +0000960}
961
962
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000963static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000964ins(arrayobject *self, Py_ssize_t where, PyObject *v)
Guido van Rossum778983b1993-02-19 15:55:02 +0000965{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 if (ins1(self, where, v) != 0)
967 return NULL;
968 Py_INCREF(Py_None);
969 return Py_None;
Guido van Rossum778983b1993-02-19 15:55:02 +0000970}
971
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000972static PyObject *
Raymond Hettinger36cd2bf2003-01-03 08:24:58 +0000973array_count(arrayobject *self, PyObject *v)
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +0000974{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000975 Py_ssize_t count = 0;
976 Py_ssize_t i;
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +0000977
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 for (i = 0; i < Py_SIZE(self); i++) {
979 PyObject *selfi = getarrayitem((PyObject *)self, i);
980 int cmp = PyObject_RichCompareBool(selfi, v, Py_EQ);
981 Py_DECREF(selfi);
982 if (cmp > 0)
983 count++;
984 else if (cmp < 0)
985 return NULL;
986 }
987 return PyLong_FromSsize_t(count);
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +0000988}
989
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000990PyDoc_STRVAR(count_doc,
Tim Peters077a11d2000-09-16 22:31:29 +0000991"count(x)\n\
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +0000992\n\
Mark Dickinson934896d2009-02-21 20:59:32 +0000993Return number of occurrences of x in the array.");
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +0000994
995static PyObject *
Raymond Hettinger36cd2bf2003-01-03 08:24:58 +0000996array_index(arrayobject *self, PyObject *v)
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +0000997{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998 Py_ssize_t i;
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +0000999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001000 for (i = 0; i < Py_SIZE(self); i++) {
1001 PyObject *selfi = getarrayitem((PyObject *)self, i);
1002 int cmp = PyObject_RichCompareBool(selfi, v, Py_EQ);
1003 Py_DECREF(selfi);
1004 if (cmp > 0) {
1005 return PyLong_FromLong((long)i);
1006 }
1007 else if (cmp < 0)
1008 return NULL;
1009 }
1010 PyErr_SetString(PyExc_ValueError, "array.index(x): x not in list");
1011 return NULL;
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001012}
1013
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001014PyDoc_STRVAR(index_doc,
Tim Peters077a11d2000-09-16 22:31:29 +00001015"index(x)\n\
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001016\n\
Mark Dickinson934896d2009-02-21 20:59:32 +00001017Return index of first occurrence of x in the array.");
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001018
Raymond Hettinger625812f2003-01-07 01:58:52 +00001019static int
1020array_contains(arrayobject *self, PyObject *v)
1021{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001022 Py_ssize_t i;
1023 int cmp;
Raymond Hettinger625812f2003-01-07 01:58:52 +00001024
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001025 for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(self); i++) {
1026 PyObject *selfi = getarrayitem((PyObject *)self, i);
1027 cmp = PyObject_RichCompareBool(selfi, v, Py_EQ);
1028 Py_DECREF(selfi);
1029 }
1030 return cmp;
Raymond Hettinger625812f2003-01-07 01:58:52 +00001031}
1032
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001033static PyObject *
Raymond Hettinger36cd2bf2003-01-03 08:24:58 +00001034array_remove(arrayobject *self, PyObject *v)
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001035{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001036 int i;
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 for (i = 0; i < Py_SIZE(self); i++) {
1039 PyObject *selfi = getarrayitem((PyObject *)self,i);
1040 int cmp = PyObject_RichCompareBool(selfi, v, Py_EQ);
1041 Py_DECREF(selfi);
1042 if (cmp > 0) {
1043 if (array_ass_slice(self, i, i+1,
1044 (PyObject *)NULL) != 0)
1045 return NULL;
1046 Py_INCREF(Py_None);
1047 return Py_None;
1048 }
1049 else if (cmp < 0)
1050 return NULL;
1051 }
1052 PyErr_SetString(PyExc_ValueError, "array.remove(x): x not in list");
1053 return NULL;
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001054}
1055
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001056PyDoc_STRVAR(remove_doc,
Tim Peters077a11d2000-09-16 22:31:29 +00001057"remove(x)\n\
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001058\n\
Mark Dickinson934896d2009-02-21 20:59:32 +00001059Remove the first occurrence of x in the array.");
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001060
1061static PyObject *
1062array_pop(arrayobject *self, PyObject *args)
1063{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001064 Py_ssize_t i = -1;
1065 PyObject *v;
1066 if (!PyArg_ParseTuple(args, "|n:pop", &i))
1067 return NULL;
1068 if (Py_SIZE(self) == 0) {
1069 /* Special-case most common failure cause */
1070 PyErr_SetString(PyExc_IndexError, "pop from empty array");
1071 return NULL;
1072 }
1073 if (i < 0)
1074 i += Py_SIZE(self);
1075 if (i < 0 || i >= Py_SIZE(self)) {
1076 PyErr_SetString(PyExc_IndexError, "pop index out of range");
1077 return NULL;
1078 }
1079 v = getarrayitem((PyObject *)self,i);
1080 if (array_ass_slice(self, i, i+1, (PyObject *)NULL) != 0) {
1081 Py_DECREF(v);
1082 return NULL;
1083 }
1084 return v;
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001085}
1086
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001087PyDoc_STRVAR(pop_doc,
Tim Peters077a11d2000-09-16 22:31:29 +00001088"pop([i])\n\
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001089\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001090Return the i-th element and delete it from the array. i defaults to -1.");
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001091
1092static PyObject *
Raymond Hettinger36cd2bf2003-01-03 08:24:58 +00001093array_extend(arrayobject *self, PyObject *bb)
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001094{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001095 if (array_do_extend(self, bb) == -1)
1096 return NULL;
1097 Py_INCREF(Py_None);
1098 return Py_None;
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001099}
1100
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001101PyDoc_STRVAR(extend_doc,
Raymond Hettinger49f9bd12004-03-14 05:43:59 +00001102"extend(array or iterable)\n\
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001103\n\
Raymond Hettinger49f9bd12004-03-14 05:43:59 +00001104 Append items to the end of the array.");
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001105
1106static PyObject *
Peter Schneider-Kamp9656abd2000-07-13 21:10:57 +00001107array_insert(arrayobject *self, PyObject *args)
Guido van Rossum778983b1993-02-19 15:55:02 +00001108{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001109 Py_ssize_t i;
1110 PyObject *v;
1111 if (!PyArg_ParseTuple(args, "nO:insert", &i, &v))
1112 return NULL;
1113 return ins(self, i, v);
Guido van Rossum778983b1993-02-19 15:55:02 +00001114}
1115
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001116PyDoc_STRVAR(insert_doc,
Tim Peters077a11d2000-09-16 22:31:29 +00001117"insert(i,x)\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001118\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001119Insert a new item x into the array before position i.");
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001120
1121
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001122static PyObject *
Raymond Hettinger36cd2bf2003-01-03 08:24:58 +00001123array_buffer_info(arrayobject *self, PyObject *unused)
Guido van Rossumde4a4ca1997-08-12 14:55:56 +00001124{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001125 PyObject* retval = NULL;
1126 retval = PyTuple_New(2);
1127 if (!retval)
1128 return NULL;
Fred Drake541dc3b2000-06-28 17:49:30 +00001129
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001130 PyTuple_SET_ITEM(retval, 0, PyLong_FromVoidPtr(self->ob_item));
1131 PyTuple_SET_ITEM(retval, 1, PyLong_FromLong((long)(Py_SIZE(self))));
Fred Drake541dc3b2000-06-28 17:49:30 +00001132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001133 return retval;
Guido van Rossumde4a4ca1997-08-12 14:55:56 +00001134}
1135
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001136PyDoc_STRVAR(buffer_info_doc,
Tim Peters077a11d2000-09-16 22:31:29 +00001137"buffer_info() -> (address, length)\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001138\n\
1139Return a tuple (address, length) giving the current memory address and\n\
Guido van Rossum702d08e2001-07-27 16:05:32 +00001140the length in items of the buffer used to hold array's contents\n\
1141The length should be multiplied by the itemsize attribute to calculate\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001142the buffer length in bytes.");
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001143
1144
Guido van Rossumde4a4ca1997-08-12 14:55:56 +00001145static PyObject *
Raymond Hettinger36cd2bf2003-01-03 08:24:58 +00001146array_append(arrayobject *self, PyObject *v)
Guido van Rossum778983b1993-02-19 15:55:02 +00001147{
Mark Dickinson346f0af2010-08-06 09:36:57 +00001148 return ins(self, Py_SIZE(self), v);
Guido van Rossum778983b1993-02-19 15:55:02 +00001149}
1150
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001151PyDoc_STRVAR(append_doc,
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001152"append(x)\n\
1153\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001154Append new value x to the end of the array.");
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001155
1156
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001157static PyObject *
Raymond Hettinger36cd2bf2003-01-03 08:24:58 +00001158array_byteswap(arrayobject *self, PyObject *unused)
Guido van Rossum778983b1993-02-19 15:55:02 +00001159{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001160 char *p;
1161 Py_ssize_t i;
Fred Drakebf272981999-12-03 17:15:30 +00001162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001163 switch (self->ob_descr->itemsize) {
1164 case 1:
1165 break;
1166 case 2:
1167 for (p = self->ob_item, i = Py_SIZE(self); --i >= 0; p += 2) {
1168 char p0 = p[0];
1169 p[0] = p[1];
1170 p[1] = p0;
1171 }
1172 break;
1173 case 4:
1174 for (p = self->ob_item, i = Py_SIZE(self); --i >= 0; p += 4) {
1175 char p0 = p[0];
1176 char p1 = p[1];
1177 p[0] = p[3];
1178 p[1] = p[2];
1179 p[2] = p1;
1180 p[3] = p0;
1181 }
1182 break;
1183 case 8:
1184 for (p = self->ob_item, i = Py_SIZE(self); --i >= 0; p += 8) {
1185 char p0 = p[0];
1186 char p1 = p[1];
1187 char p2 = p[2];
1188 char p3 = p[3];
1189 p[0] = p[7];
1190 p[1] = p[6];
1191 p[2] = p[5];
1192 p[3] = p[4];
1193 p[4] = p3;
1194 p[5] = p2;
1195 p[6] = p1;
1196 p[7] = p0;
1197 }
1198 break;
1199 default:
1200 PyErr_SetString(PyExc_RuntimeError,
1201 "don't know how to byteswap this array type");
1202 return NULL;
1203 }
1204 Py_INCREF(Py_None);
1205 return Py_None;
Guido van Rossum778983b1993-02-19 15:55:02 +00001206}
1207
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001208PyDoc_STRVAR(byteswap_doc,
Fred Drakebf272981999-12-03 17:15:30 +00001209"byteswap()\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001210\n\
Fred Drakebf272981999-12-03 17:15:30 +00001211Byteswap all items of the array. If the items in the array are not 1, 2,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012124, or 8 bytes in size, RuntimeError is raised.");
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001213
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001214static PyObject *
Raymond Hettinger36cd2bf2003-01-03 08:24:58 +00001215array_reverse(arrayobject *self, PyObject *unused)
Guido van Rossum778983b1993-02-19 15:55:02 +00001216{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001217 register Py_ssize_t itemsize = self->ob_descr->itemsize;
1218 register char *p, *q;
1219 /* little buffer to hold items while swapping */
1220 char tmp[256]; /* 8 is probably enough -- but why skimp */
1221 assert((size_t)itemsize <= sizeof(tmp));
Guido van Rossume77a7571993-11-03 15:01:26 +00001222
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001223 if (Py_SIZE(self) > 1) {
1224 for (p = self->ob_item,
1225 q = self->ob_item + (Py_SIZE(self) - 1)*itemsize;
1226 p < q;
1227 p += itemsize, q -= itemsize) {
1228 /* memory areas guaranteed disjoint, so memcpy
1229 * is safe (& memmove may be slower).
1230 */
1231 memcpy(tmp, p, itemsize);
1232 memcpy(p, q, itemsize);
1233 memcpy(q, tmp, itemsize);
1234 }
1235 }
Tim Petersbb307342000-09-10 05:22:54 +00001236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001237 Py_INCREF(Py_None);
1238 return Py_None;
Guido van Rossum778983b1993-02-19 15:55:02 +00001239}
Guido van Rossume77a7571993-11-03 15:01:26 +00001240
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001241PyDoc_STRVAR(reverse_doc,
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001242"reverse()\n\
1243\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001244Reverse the order of the items in the array.");
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001245
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001246
1247/* Forward */
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001248static PyObject *array_frombytes(arrayobject *self, PyObject *args);
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001249
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001250static PyObject *
Peter Schneider-Kamp9656abd2000-07-13 21:10:57 +00001251array_fromfile(arrayobject *self, PyObject *args)
Guido van Rossum778983b1993-02-19 15:55:02 +00001252{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001253 PyObject *f, *b, *res;
1254 Py_ssize_t itemsize = self->ob_descr->itemsize;
1255 Py_ssize_t n, nbytes;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001256 _Py_IDENTIFIER(read);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001257 int not_enough_bytes;
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001259 if (!PyArg_ParseTuple(args, "On:fromfile", &f, &n))
1260 return NULL;
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001262 nbytes = n * itemsize;
1263 if (nbytes < 0 || nbytes/itemsize != n) {
1264 PyErr_NoMemory();
1265 return NULL;
1266 }
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001267
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001268 b = _PyObject_CallMethodId(f, &PyId_read, "n", nbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001269 if (b == NULL)
1270 return NULL;
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 if (!PyBytes_Check(b)) {
1273 PyErr_SetString(PyExc_TypeError,
1274 "read() didn't return bytes");
1275 Py_DECREF(b);
1276 return NULL;
1277 }
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001279 not_enough_bytes = (PyBytes_GET_SIZE(b) != nbytes);
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001281 args = Py_BuildValue("(O)", b);
1282 Py_DECREF(b);
1283 if (args == NULL)
1284 return NULL;
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001285
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001286 res = array_frombytes(self, args);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001287 Py_DECREF(args);
1288 if (res == NULL)
1289 return NULL;
Hirokazu Yamamoto54d0df62009-03-06 03:04:07 +00001290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001291 if (not_enough_bytes) {
1292 PyErr_SetString(PyExc_EOFError,
1293 "read() didn't return enough bytes");
1294 Py_DECREF(res);
1295 return NULL;
1296 }
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001298 return res;
Guido van Rossum778983b1993-02-19 15:55:02 +00001299}
1300
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001301PyDoc_STRVAR(fromfile_doc,
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001302"fromfile(f, n)\n\
1303\n\
1304Read n objects from the file object f and append them to the end of the\n\
Georg Brandlf25ef502008-02-01 11:30:18 +00001305array.");
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001306
1307
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001308static PyObject *
Raymond Hettinger36cd2bf2003-01-03 08:24:58 +00001309array_tofile(arrayobject *self, PyObject *f)
Guido van Rossum778983b1993-02-19 15:55:02 +00001310{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001311 Py_ssize_t nbytes = Py_SIZE(self) * self->ob_descr->itemsize;
1312 /* Write 64K blocks at a time */
1313 /* XXX Make the block size settable */
1314 int BLOCKSIZE = 64*1024;
1315 Py_ssize_t nblocks = (nbytes + BLOCKSIZE - 1) / BLOCKSIZE;
1316 Py_ssize_t i;
Raymond Hettinger36cd2bf2003-01-03 08:24:58 +00001317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001318 if (Py_SIZE(self) == 0)
1319 goto done;
Guido van Rossumb5ddcfd2007-04-11 17:08:28 +00001320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001321 for (i = 0; i < nblocks; i++) {
1322 char* ptr = self->ob_item + i*BLOCKSIZE;
1323 Py_ssize_t size = BLOCKSIZE;
1324 PyObject *bytes, *res;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001325 _Py_IDENTIFIER(write);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001327 if (i*BLOCKSIZE + size > nbytes)
1328 size = nbytes - i*BLOCKSIZE;
1329 bytes = PyBytes_FromStringAndSize(ptr, size);
1330 if (bytes == NULL)
1331 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001332 res = _PyObject_CallMethodId(f, &PyId_write, "O", bytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001333 Py_DECREF(bytes);
1334 if (res == NULL)
1335 return NULL;
1336 Py_DECREF(res); /* drop write result */
1337 }
Guido van Rossumb5ddcfd2007-04-11 17:08:28 +00001338
1339 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001340 Py_INCREF(Py_None);
1341 return Py_None;
Guido van Rossum778983b1993-02-19 15:55:02 +00001342}
1343
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001344PyDoc_STRVAR(tofile_doc,
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001345"tofile(f)\n\
1346\n\
Georg Brandlf25ef502008-02-01 11:30:18 +00001347Write all items (as machine values) to the file object f.");
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001348
1349
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001350static PyObject *
Raymond Hettinger36cd2bf2003-01-03 08:24:58 +00001351array_fromlist(arrayobject *self, PyObject *list)
Guido van Rossum778983b1993-02-19 15:55:02 +00001352{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001353 Py_ssize_t n;
Raymond Hettinger36cd2bf2003-01-03 08:24:58 +00001354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001355 if (!PyList_Check(list)) {
1356 PyErr_SetString(PyExc_TypeError, "arg must be list");
1357 return NULL;
1358 }
1359 n = PyList_Size(list);
1360 if (n > 0) {
1361 Py_ssize_t i, old_size;
1362 old_size = Py_SIZE(self);
1363 if (array_resize(self, old_size + n) == -1)
1364 return NULL;
1365 for (i = 0; i < n; i++) {
1366 PyObject *v = PyList_GetItem(list, i);
1367 if ((*self->ob_descr->setitem)(self,
1368 Py_SIZE(self) - n + i, v) != 0) {
1369 array_resize(self, old_size);
1370 return NULL;
1371 }
1372 }
1373 }
1374 Py_INCREF(Py_None);
1375 return Py_None;
Guido van Rossum778983b1993-02-19 15:55:02 +00001376}
1377
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001378PyDoc_STRVAR(fromlist_doc,
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001379"fromlist(list)\n\
1380\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001381Append items to array from list.");
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001382
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001383static PyObject *
Raymond Hettinger36cd2bf2003-01-03 08:24:58 +00001384array_tolist(arrayobject *self, PyObject *unused)
Guido van Rossum778983b1993-02-19 15:55:02 +00001385{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001386 PyObject *list = PyList_New(Py_SIZE(self));
1387 Py_ssize_t i;
Raymond Hettinger36cd2bf2003-01-03 08:24:58 +00001388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001389 if (list == NULL)
1390 return NULL;
1391 for (i = 0; i < Py_SIZE(self); i++) {
1392 PyObject *v = getarrayitem((PyObject *)self, i);
1393 if (v == NULL) {
1394 Py_DECREF(list);
1395 return NULL;
1396 }
1397 PyList_SetItem(list, i, v);
1398 }
1399 return list;
Guido van Rossum778983b1993-02-19 15:55:02 +00001400}
1401
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001402PyDoc_STRVAR(tolist_doc,
Guido van Rossumfc6aba51998-10-14 02:52:31 +00001403"tolist() -> list\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001404\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001405Convert array to an ordinary list with the same items.");
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001406
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001407static PyObject *
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001408frombytes(arrayobject *self, Py_buffer *buffer)
Guido van Rossum778983b1993-02-19 15:55:02 +00001409{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 int itemsize = self->ob_descr->itemsize;
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001411 Py_ssize_t n;
1412 if (buffer->itemsize != 1) {
1413 PyBuffer_Release(buffer);
1414 PyErr_SetString(PyExc_TypeError, "string/buffer of bytes required.");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001415 return NULL;
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001416 }
1417 n = buffer->len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001418 if (n % itemsize != 0) {
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001419 PyBuffer_Release(buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001420 PyErr_SetString(PyExc_ValueError,
1421 "string length not a multiple of item size");
1422 return NULL;
1423 }
1424 n = n / itemsize;
1425 if (n > 0) {
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001426 Py_ssize_t old_size = Py_SIZE(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001427 if ((n > PY_SSIZE_T_MAX - old_size) ||
1428 ((old_size + n) > PY_SSIZE_T_MAX / itemsize)) {
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001429 PyBuffer_Release(buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001430 return PyErr_NoMemory();
1431 }
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001432 if (array_resize(self, old_size + n) == -1) {
1433 PyBuffer_Release(buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001434 return NULL;
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001435 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001436 memcpy(self->ob_item + old_size * itemsize,
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001437 buffer->buf, n * itemsize);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001438 }
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001439 PyBuffer_Release(buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001440 Py_INCREF(Py_None);
1441 return Py_None;
Guido van Rossum778983b1993-02-19 15:55:02 +00001442}
1443
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001444static PyObject *
1445array_fromstring(arrayobject *self, PyObject *args)
1446{
1447 Py_buffer buffer;
1448 if (PyErr_WarnEx(PyExc_DeprecationWarning,
1449 "fromstring() is deprecated. Use frombytes() instead.", 2) != 0)
1450 return NULL;
1451 if (!PyArg_ParseTuple(args, "s*:fromstring", &buffer))
1452 return NULL;
1453 else
1454 return frombytes(self, &buffer);
1455}
1456
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001457PyDoc_STRVAR(fromstring_doc,
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001458"fromstring(string)\n\
1459\n\
1460Appends items from the string, interpreting it as an array of machine\n\
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001461values, as if it had been read from a file using the fromfile() method).\n\
1462\n\
1463This method is deprecated. Use frombytes instead.");
1464
1465
1466static PyObject *
1467array_frombytes(arrayobject *self, PyObject *args)
1468{
1469 Py_buffer buffer;
1470 if (!PyArg_ParseTuple(args, "y*:frombytes", &buffer))
1471 return NULL;
1472 else
1473 return frombytes(self, &buffer);
1474}
1475
1476PyDoc_STRVAR(frombytes_doc,
1477"frombytes(bytestring)\n\
1478\n\
1479Appends items from the string, interpreting it as an array of machine\n\
Walter Dörwald93b30b52007-06-22 12:21:53 +00001480values, as if it had been read from a file using the fromfile() method).");
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001481
1482
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001483static PyObject *
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001484array_tobytes(arrayobject *self, PyObject *unused)
Guido van Rossum778983b1993-02-19 15:55:02 +00001485{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001486 if (Py_SIZE(self) <= PY_SSIZE_T_MAX / self->ob_descr->itemsize) {
1487 return PyBytes_FromStringAndSize(self->ob_item,
1488 Py_SIZE(self) * self->ob_descr->itemsize);
1489 } else {
1490 return PyErr_NoMemory();
1491 }
Guido van Rossum778983b1993-02-19 15:55:02 +00001492}
1493
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001494PyDoc_STRVAR(tobytes_doc,
1495"tobytes() -> bytes\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001496\n\
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001497Convert the array to an array of machine values and return the bytes\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001498representation.");
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001499
Martin v. Löwis99866332002-03-01 10:27:01 +00001500
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001501static PyObject *
1502array_tostring(arrayobject *self, PyObject *unused)
1503{
Victor Stinner9f0b51e2010-11-09 09:38:30 +00001504 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001505 "tostring() is deprecated. Use tobytes() instead.", 2) != 0)
1506 return NULL;
1507 return array_tobytes(self, unused);
1508}
1509
1510PyDoc_STRVAR(tostring_doc,
1511"tostring() -> bytes\n\
1512\n\
1513Convert the array to an array of machine values and return the bytes\n\
1514representation.\n\
1515\n\
1516This method is deprecated. Use tobytes instead.");
1517
Martin v. Löwis99866332002-03-01 10:27:01 +00001518
Martin v. Löwis99866332002-03-01 10:27:01 +00001519static PyObject *
1520array_fromunicode(arrayobject *self, PyObject *args)
1521{
Victor Stinner8dba4e02011-09-30 00:51:10 +02001522 PyObject *ustr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001523 Py_ssize_t n;
Martin v. Löwis99866332002-03-01 10:27:01 +00001524
Victor Stinner8dba4e02011-09-30 00:51:10 +02001525 if (!PyArg_ParseTuple(args, "U:fromunicode", &ustr))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001526 return NULL;
Victor Stinner8dba4e02011-09-30 00:51:10 +02001527 if (self->ob_descr->typecode != 'u') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001528 PyErr_SetString(PyExc_ValueError,
1529 "fromunicode() may only be called on "
1530 "unicode type arrays");
1531 return NULL;
1532 }
Victor Stinner8dba4e02011-09-30 00:51:10 +02001533 if (PyUnicode_READY(ustr))
1534 return NULL;
1535 n = PyUnicode_GET_LENGTH(ustr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001536 if (n > 0) {
1537 Py_ssize_t old_size = Py_SIZE(self);
1538 if (array_resize(self, old_size + n) == -1)
1539 return NULL;
Victor Stinner8dba4e02011-09-30 00:51:10 +02001540 if (!PyUnicode_AsUCS4(ustr, (Py_UCS4 *)self->ob_item + old_size, n, 0))
1541 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001542 }
Martin v. Löwis99866332002-03-01 10:27:01 +00001543
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001544 Py_INCREF(Py_None);
1545 return Py_None;
Martin v. Löwis99866332002-03-01 10:27:01 +00001546}
1547
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001548PyDoc_STRVAR(fromunicode_doc,
Martin v. Löwis99866332002-03-01 10:27:01 +00001549"fromunicode(ustr)\n\
1550\n\
1551Extends this array with data from the unicode string ustr.\n\
Travis E. Oliphantb99f7622007-08-18 11:21:56 +00001552The array must be a unicode type array; otherwise a ValueError\n\
Florent Xiclunac45fb252011-10-24 13:14:55 +02001553is raised. Use array.frombytes(ustr.encode(...)) to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001554append Unicode data to an array of some other type.");
Martin v. Löwis99866332002-03-01 10:27:01 +00001555
1556
1557static PyObject *
Raymond Hettinger36cd2bf2003-01-03 08:24:58 +00001558array_tounicode(arrayobject *self, PyObject *unused)
Martin v. Löwis99866332002-03-01 10:27:01 +00001559{
Victor Stinner8dba4e02011-09-30 00:51:10 +02001560 if (self->ob_descr->typecode != 'u') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001561 PyErr_SetString(PyExc_ValueError,
1562 "tounicode() may only be called on unicode type arrays");
1563 return NULL;
1564 }
Victor Stinner8dba4e02011-09-30 00:51:10 +02001565 return PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND,
1566 (Py_UCS4 *) self->ob_item,
1567 Py_SIZE(self));
Martin v. Löwis99866332002-03-01 10:27:01 +00001568}
1569
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001570PyDoc_STRVAR(tounicode_doc,
Martin v. Löwis99866332002-03-01 10:27:01 +00001571"tounicode() -> unicode\n\
1572\n\
1573Convert the array to a unicode string. The array must be\n\
Travis E. Oliphantb99f7622007-08-18 11:21:56 +00001574a unicode type array; otherwise a ValueError is raised. Use\n\
Florent Xiclunac45fb252011-10-24 13:14:55 +02001575array.tobytes().decode() to obtain a unicode string from\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001576an array of some other type.");
Martin v. Löwis99866332002-03-01 10:27:01 +00001577
Martin v. Löwis99866332002-03-01 10:27:01 +00001578
1579
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001580/*********************** Pickling support ************************/
1581
1582enum machine_format_code {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001583 UNKNOWN_FORMAT = -1,
1584 /* UNKNOWN_FORMAT is used to indicate that the machine format for an
1585 * array type code cannot be interpreted. When this occurs, a list of
1586 * Python objects is used to represent the content of the array
1587 * instead of using the memory content of the array directly. In that
1588 * case, the array_reconstructor mechanism is bypassed completely, and
1589 * the standard array constructor is used instead.
1590 *
1591 * This is will most likely occur when the machine doesn't use IEEE
1592 * floating-point numbers.
1593 */
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001594
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001595 UNSIGNED_INT8 = 0,
1596 SIGNED_INT8 = 1,
1597 UNSIGNED_INT16_LE = 2,
1598 UNSIGNED_INT16_BE = 3,
1599 SIGNED_INT16_LE = 4,
1600 SIGNED_INT16_BE = 5,
1601 UNSIGNED_INT32_LE = 6,
1602 UNSIGNED_INT32_BE = 7,
1603 SIGNED_INT32_LE = 8,
1604 SIGNED_INT32_BE = 9,
1605 UNSIGNED_INT64_LE = 10,
1606 UNSIGNED_INT64_BE = 11,
1607 SIGNED_INT64_LE = 12,
1608 SIGNED_INT64_BE = 13,
1609 IEEE_754_FLOAT_LE = 14,
1610 IEEE_754_FLOAT_BE = 15,
1611 IEEE_754_DOUBLE_LE = 16,
1612 IEEE_754_DOUBLE_BE = 17,
1613 UTF16_LE = 18,
1614 UTF16_BE = 19,
1615 UTF32_LE = 20,
1616 UTF32_BE = 21
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001617};
1618#define MACHINE_FORMAT_CODE_MIN 0
1619#define MACHINE_FORMAT_CODE_MAX 21
1620
1621static const struct mformatdescr {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001622 size_t size;
1623 int is_signed;
1624 int is_big_endian;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001625} mformat_descriptors[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001626 {1, 0, 0}, /* 0: UNSIGNED_INT8 */
1627 {1, 1, 0}, /* 1: SIGNED_INT8 */
1628 {2, 0, 0}, /* 2: UNSIGNED_INT16_LE */
1629 {2, 0, 1}, /* 3: UNSIGNED_INT16_BE */
1630 {2, 1, 0}, /* 4: SIGNED_INT16_LE */
1631 {2, 1, 1}, /* 5: SIGNED_INT16_BE */
1632 {4, 0, 0}, /* 6: UNSIGNED_INT32_LE */
1633 {4, 0, 1}, /* 7: UNSIGNED_INT32_BE */
1634 {4, 1, 0}, /* 8: SIGNED_INT32_LE */
1635 {4, 1, 1}, /* 9: SIGNED_INT32_BE */
1636 {8, 0, 0}, /* 10: UNSIGNED_INT64_LE */
1637 {8, 0, 1}, /* 11: UNSIGNED_INT64_BE */
1638 {8, 1, 0}, /* 12: SIGNED_INT64_LE */
1639 {8, 1, 1}, /* 13: SIGNED_INT64_BE */
1640 {4, 0, 0}, /* 14: IEEE_754_FLOAT_LE */
1641 {4, 0, 1}, /* 15: IEEE_754_FLOAT_BE */
1642 {8, 0, 0}, /* 16: IEEE_754_DOUBLE_LE */
1643 {8, 0, 1}, /* 17: IEEE_754_DOUBLE_BE */
1644 {4, 0, 0}, /* 18: UTF16_LE */
1645 {4, 0, 1}, /* 19: UTF16_BE */
1646 {8, 0, 0}, /* 20: UTF32_LE */
1647 {8, 0, 1} /* 21: UTF32_BE */
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001648};
1649
1650
1651/*
1652 * Internal: This function is used to find the machine format of a given
1653 * array type code. This returns UNKNOWN_FORMAT when the machine format cannot
1654 * be found.
1655 */
1656static enum machine_format_code
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02001657typecode_to_mformat_code(char typecode)
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001658{
Alexandre Vassalotti7aaa7702009-07-17 03:51:27 +00001659#ifdef WORDS_BIGENDIAN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001660 const int is_big_endian = 1;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001661#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001662 const int is_big_endian = 0;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001663#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001664 size_t intsize;
1665 int is_signed;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001666
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001667 switch (typecode) {
1668 case 'b':
1669 return SIGNED_INT8;
1670 case 'B':
1671 return UNSIGNED_INT8;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001672
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001673 case 'u':
Victor Stinner8dba4e02011-09-30 00:51:10 +02001674 return UTF32_LE + is_big_endian;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001675
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001676 case 'f':
1677 if (sizeof(float) == 4) {
1678 const float y = 16711938.0;
1679 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1680 return IEEE_754_FLOAT_BE;
1681 if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1682 return IEEE_754_FLOAT_LE;
1683 }
1684 return UNKNOWN_FORMAT;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001685
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001686 case 'd':
1687 if (sizeof(double) == 8) {
1688 const double x = 9006104071832581.0;
1689 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1690 return IEEE_754_DOUBLE_BE;
1691 if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1692 return IEEE_754_DOUBLE_LE;
1693 }
1694 return UNKNOWN_FORMAT;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001695
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001696 /* Integers */
1697 case 'h':
1698 intsize = sizeof(short);
1699 is_signed = 1;
1700 break;
1701 case 'H':
1702 intsize = sizeof(short);
1703 is_signed = 0;
1704 break;
1705 case 'i':
1706 intsize = sizeof(int);
1707 is_signed = 1;
1708 break;
1709 case 'I':
1710 intsize = sizeof(int);
1711 is_signed = 0;
1712 break;
1713 case 'l':
1714 intsize = sizeof(long);
1715 is_signed = 1;
1716 break;
1717 case 'L':
1718 intsize = sizeof(long);
1719 is_signed = 0;
1720 break;
Meador Inge1c9f0c92011-09-20 19:55:51 -05001721#if HAVE_LONG_LONG
1722 case 'q':
1723 intsize = sizeof(PY_LONG_LONG);
1724 is_signed = 1;
1725 break;
1726 case 'Q':
1727 intsize = sizeof(PY_LONG_LONG);
1728 is_signed = 0;
1729 break;
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02001730#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001731 default:
1732 return UNKNOWN_FORMAT;
1733 }
1734 switch (intsize) {
1735 case 2:
1736 return UNSIGNED_INT16_LE + is_big_endian + (2 * is_signed);
1737 case 4:
1738 return UNSIGNED_INT32_LE + is_big_endian + (2 * is_signed);
1739 case 8:
1740 return UNSIGNED_INT64_LE + is_big_endian + (2 * is_signed);
1741 default:
1742 return UNKNOWN_FORMAT;
1743 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001744}
1745
1746/* Forward declaration. */
1747static PyObject *array_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1748
1749/*
1750 * Internal: This function wraps the array constructor--i.e., array_new()--to
1751 * allow the creation of array objects from C code without having to deal
1752 * directly the tuple argument of array_new(). The typecode argument is a
1753 * Unicode character value, like 'i' or 'f' for example, representing an array
1754 * type code. The items argument is a bytes or a list object from which
1755 * contains the initial value of the array.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001756 *
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001757 * On success, this functions returns the array object created. Otherwise,
1758 * NULL is returned to indicate a failure.
1759 */
1760static PyObject *
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02001761make_array(PyTypeObject *arraytype, char typecode, PyObject *items)
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001762{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001763 PyObject *new_args;
1764 PyObject *array_obj;
1765 PyObject *typecode_obj;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001766
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001767 assert(arraytype != NULL);
1768 assert(items != NULL);
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001769
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02001770 typecode_obj = PyUnicode_FromOrdinal(typecode);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001771 if (typecode_obj == NULL)
1772 return NULL;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001774 new_args = PyTuple_New(2);
1775 if (new_args == NULL)
1776 return NULL;
1777 Py_INCREF(items);
1778 PyTuple_SET_ITEM(new_args, 0, typecode_obj);
1779 PyTuple_SET_ITEM(new_args, 1, items);
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001781 array_obj = array_new(arraytype, new_args, NULL);
1782 Py_DECREF(new_args);
1783 if (array_obj == NULL)
1784 return NULL;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001785
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001786 return array_obj;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001787}
1788
1789/*
1790 * This functions is a special constructor used when unpickling an array. It
1791 * provides a portable way to rebuild an array from its memory representation.
1792 */
1793static PyObject *
1794array_reconstructor(PyObject *self, PyObject *args)
1795{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001796 PyTypeObject *arraytype;
1797 PyObject *items;
1798 PyObject *converted_items;
1799 PyObject *result;
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02001800 int typecode;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001801 enum machine_format_code mformat_code;
1802 struct arraydescr *descr;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001803
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001804 if (!PyArg_ParseTuple(args, "OCiO:array._array_reconstructor",
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02001805 &arraytype, &typecode, &mformat_code, &items))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001806 return NULL;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001808 if (!PyType_Check(arraytype)) {
1809 PyErr_Format(PyExc_TypeError,
1810 "first argument must a type object, not %.200s",
1811 Py_TYPE(arraytype)->tp_name);
1812 return NULL;
1813 }
1814 if (!PyType_IsSubtype(arraytype, &Arraytype)) {
1815 PyErr_Format(PyExc_TypeError,
1816 "%.200s is not a subtype of %.200s",
1817 arraytype->tp_name, Arraytype.tp_name);
1818 return NULL;
1819 }
1820 for (descr = descriptors; descr->typecode != '\0'; descr++) {
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02001821 if ((int)descr->typecode == typecode)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001822 break;
1823 }
1824 if (descr->typecode == '\0') {
1825 PyErr_SetString(PyExc_ValueError,
1826 "second argument must be a valid type code");
1827 return NULL;
1828 }
1829 if (mformat_code < MACHINE_FORMAT_CODE_MIN ||
1830 mformat_code > MACHINE_FORMAT_CODE_MAX) {
1831 PyErr_SetString(PyExc_ValueError,
1832 "third argument must be a valid machine format code.");
1833 return NULL;
1834 }
1835 if (!PyBytes_Check(items)) {
1836 PyErr_Format(PyExc_TypeError,
1837 "fourth argument should be bytes, not %.200s",
1838 Py_TYPE(items)->tp_name);
1839 return NULL;
1840 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001841
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001842 /* Fast path: No decoding has to be done. */
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02001843 if (mformat_code == typecode_to_mformat_code((char)typecode) ||
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001844 mformat_code == UNKNOWN_FORMAT) {
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02001845 return make_array(arraytype, (char)typecode, items);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001846 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001847
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001848 /* Slow path: Decode the byte string according to the given machine
1849 * format code. This occurs when the computer unpickling the array
1850 * object is architecturally different from the one that pickled the
1851 * array.
1852 */
1853 if (Py_SIZE(items) % mformat_descriptors[mformat_code].size != 0) {
1854 PyErr_SetString(PyExc_ValueError,
1855 "string length not a multiple of item size");
1856 return NULL;
1857 }
1858 switch (mformat_code) {
1859 case IEEE_754_FLOAT_LE:
1860 case IEEE_754_FLOAT_BE: {
1861 int i;
1862 int le = (mformat_code == IEEE_754_FLOAT_LE) ? 1 : 0;
1863 Py_ssize_t itemcount = Py_SIZE(items) / 4;
1864 const unsigned char *memstr =
1865 (unsigned char *)PyBytes_AS_STRING(items);
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001866
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001867 converted_items = PyList_New(itemcount);
1868 if (converted_items == NULL)
1869 return NULL;
1870 for (i = 0; i < itemcount; i++) {
1871 PyObject *pyfloat = PyFloat_FromDouble(
1872 _PyFloat_Unpack4(&memstr[i * 4], le));
1873 if (pyfloat == NULL) {
1874 Py_DECREF(converted_items);
1875 return NULL;
1876 }
1877 PyList_SET_ITEM(converted_items, i, pyfloat);
1878 }
1879 break;
1880 }
1881 case IEEE_754_DOUBLE_LE:
1882 case IEEE_754_DOUBLE_BE: {
1883 int i;
1884 int le = (mformat_code == IEEE_754_DOUBLE_LE) ? 1 : 0;
1885 Py_ssize_t itemcount = Py_SIZE(items) / 8;
1886 const unsigned char *memstr =
1887 (unsigned char *)PyBytes_AS_STRING(items);
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001889 converted_items = PyList_New(itemcount);
1890 if (converted_items == NULL)
1891 return NULL;
1892 for (i = 0; i < itemcount; i++) {
1893 PyObject *pyfloat = PyFloat_FromDouble(
1894 _PyFloat_Unpack8(&memstr[i * 8], le));
1895 if (pyfloat == NULL) {
1896 Py_DECREF(converted_items);
1897 return NULL;
1898 }
1899 PyList_SET_ITEM(converted_items, i, pyfloat);
1900 }
1901 break;
1902 }
1903 case UTF16_LE:
1904 case UTF16_BE: {
1905 int byteorder = (mformat_code == UTF16_LE) ? -1 : 1;
1906 converted_items = PyUnicode_DecodeUTF16(
1907 PyBytes_AS_STRING(items), Py_SIZE(items),
1908 "strict", &byteorder);
1909 if (converted_items == NULL)
1910 return NULL;
1911 break;
1912 }
1913 case UTF32_LE:
1914 case UTF32_BE: {
1915 int byteorder = (mformat_code == UTF32_LE) ? -1 : 1;
1916 converted_items = PyUnicode_DecodeUTF32(
1917 PyBytes_AS_STRING(items), Py_SIZE(items),
1918 "strict", &byteorder);
1919 if (converted_items == NULL)
1920 return NULL;
1921 break;
1922 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001924 case UNSIGNED_INT8:
1925 case SIGNED_INT8:
1926 case UNSIGNED_INT16_LE:
1927 case UNSIGNED_INT16_BE:
1928 case SIGNED_INT16_LE:
1929 case SIGNED_INT16_BE:
1930 case UNSIGNED_INT32_LE:
1931 case UNSIGNED_INT32_BE:
1932 case SIGNED_INT32_LE:
1933 case SIGNED_INT32_BE:
1934 case UNSIGNED_INT64_LE:
1935 case UNSIGNED_INT64_BE:
1936 case SIGNED_INT64_LE:
1937 case SIGNED_INT64_BE: {
1938 int i;
1939 const struct mformatdescr mf_descr =
1940 mformat_descriptors[mformat_code];
1941 Py_ssize_t itemcount = Py_SIZE(items) / mf_descr.size;
1942 const unsigned char *memstr =
1943 (unsigned char *)PyBytes_AS_STRING(items);
1944 struct arraydescr *descr;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001945
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001946 /* If possible, try to pack array's items using a data type
1947 * that fits better. This may result in an array with narrower
1948 * or wider elements.
1949 *
1950 * For example, if a 32-bit machine pickles a L-code array of
1951 * unsigned longs, then the array will be unpickled by 64-bit
1952 * machine as an I-code array of unsigned ints.
1953 *
1954 * XXX: Is it possible to write a unit test for this?
1955 */
1956 for (descr = descriptors; descr->typecode != '\0'; descr++) {
1957 if (descr->is_integer_type &&
1958 descr->itemsize == mf_descr.size &&
1959 descr->is_signed == mf_descr.is_signed)
1960 typecode = descr->typecode;
1961 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001962
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001963 converted_items = PyList_New(itemcount);
1964 if (converted_items == NULL)
1965 return NULL;
1966 for (i = 0; i < itemcount; i++) {
1967 PyObject *pylong;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001969 pylong = _PyLong_FromByteArray(
1970 &memstr[i * mf_descr.size],
1971 mf_descr.size,
1972 !mf_descr.is_big_endian,
1973 mf_descr.is_signed);
1974 if (pylong == NULL) {
1975 Py_DECREF(converted_items);
1976 return NULL;
1977 }
1978 PyList_SET_ITEM(converted_items, i, pylong);
1979 }
1980 break;
1981 }
1982 case UNKNOWN_FORMAT:
1983 /* Impossible, but needed to shut up GCC about the unhandled
1984 * enumeration value.
1985 */
1986 default:
1987 PyErr_BadArgument();
1988 return NULL;
1989 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001990
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02001991 result = make_array(arraytype, (char)typecode, converted_items);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001992 Py_DECREF(converted_items);
1993 return result;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001994}
1995
1996static PyObject *
1997array_reduce_ex(arrayobject *array, PyObject *value)
1998{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001999 PyObject *dict;
2000 PyObject *result;
2001 PyObject *array_str;
2002 int typecode = array->ob_descr->typecode;
2003 int mformat_code;
2004 static PyObject *array_reconstructor = NULL;
2005 long protocol;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002006 _Py_IDENTIFIER(_array_reconstructor);
2007 _Py_IDENTIFIER(__dict__);
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002008
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002009 if (array_reconstructor == NULL) {
2010 PyObject *array_module = PyImport_ImportModule("array");
2011 if (array_module == NULL)
2012 return NULL;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002013 array_reconstructor = _PyObject_GetAttrId(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002014 array_module,
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002015 &PyId__array_reconstructor);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002016 Py_DECREF(array_module);
2017 if (array_reconstructor == NULL)
2018 return NULL;
2019 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002021 if (!PyLong_Check(value)) {
2022 PyErr_SetString(PyExc_TypeError,
2023 "__reduce_ex__ argument should an integer");
2024 return NULL;
2025 }
2026 protocol = PyLong_AsLong(value);
2027 if (protocol == -1 && PyErr_Occurred())
2028 return NULL;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002029
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002030 dict = _PyObject_GetAttrId((PyObject *)array, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002031 if (dict == NULL) {
2032 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
2033 return NULL;
2034 PyErr_Clear();
2035 dict = Py_None;
2036 Py_INCREF(dict);
2037 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002039 mformat_code = typecode_to_mformat_code(typecode);
2040 if (mformat_code == UNKNOWN_FORMAT || protocol < 3) {
2041 /* Convert the array to a list if we got something weird
2042 * (e.g., non-IEEE floats), or we are pickling the array using
2043 * a Python 2.x compatible protocol.
2044 *
2045 * It is necessary to use a list representation for Python 2.x
2046 * compatible pickle protocol, since Python 2's str objects
2047 * are unpickled as unicode by Python 3. Thus it is impossible
2048 * to make arrays unpicklable by Python 3 by using their memory
2049 * representation, unless we resort to ugly hacks such as
2050 * coercing unicode objects to bytes in array_reconstructor.
2051 */
2052 PyObject *list;
2053 list = array_tolist(array, NULL);
2054 if (list == NULL) {
2055 Py_DECREF(dict);
2056 return NULL;
2057 }
2058 result = Py_BuildValue(
2059 "O(CO)O", Py_TYPE(array), typecode, list, dict);
2060 Py_DECREF(list);
2061 Py_DECREF(dict);
2062 return result;
2063 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002064
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00002065 array_str = array_tobytes(array, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002066 if (array_str == NULL) {
2067 Py_DECREF(dict);
2068 return NULL;
2069 }
2070 result = Py_BuildValue(
2071 "O(OCiN)O", array_reconstructor, Py_TYPE(array), typecode,
2072 mformat_code, array_str, dict);
2073 Py_DECREF(dict);
2074 return result;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002075}
2076
2077PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
2078
Martin v. Löwis99866332002-03-01 10:27:01 +00002079static PyObject *
2080array_get_typecode(arrayobject *a, void *closure)
2081{
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02002082 char typecode = a->ob_descr->typecode;
2083 return PyUnicode_FromOrdinal(typecode);
Martin v. Löwis99866332002-03-01 10:27:01 +00002084}
2085
2086static PyObject *
2087array_get_itemsize(arrayobject *a, void *closure)
2088{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002089 return PyLong_FromLong((long)a->ob_descr->itemsize);
Martin v. Löwis99866332002-03-01 10:27:01 +00002090}
2091
2092static PyGetSetDef array_getsets [] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002093 {"typecode", (getter) array_get_typecode, NULL,
2094 "the typecode character used to create the array"},
2095 {"itemsize", (getter) array_get_itemsize, NULL,
2096 "the size, in bytes, of one array item"},
2097 {NULL}
Martin v. Löwis99866332002-03-01 10:27:01 +00002098};
2099
Martin v. Löwis59683e82008-06-13 07:50:45 +00002100static PyMethodDef array_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002101 {"append", (PyCFunction)array_append, METH_O,
2102 append_doc},
2103 {"buffer_info", (PyCFunction)array_buffer_info, METH_NOARGS,
2104 buffer_info_doc},
2105 {"byteswap", (PyCFunction)array_byteswap, METH_NOARGS,
2106 byteswap_doc},
2107 {"__copy__", (PyCFunction)array_copy, METH_NOARGS,
2108 copy_doc},
2109 {"count", (PyCFunction)array_count, METH_O,
2110 count_doc},
2111 {"__deepcopy__",(PyCFunction)array_copy, METH_O,
2112 copy_doc},
2113 {"extend", (PyCFunction)array_extend, METH_O,
2114 extend_doc},
2115 {"fromfile", (PyCFunction)array_fromfile, METH_VARARGS,
2116 fromfile_doc},
2117 {"fromlist", (PyCFunction)array_fromlist, METH_O,
2118 fromlist_doc},
2119 {"fromstring", (PyCFunction)array_fromstring, METH_VARARGS,
2120 fromstring_doc},
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00002121 {"frombytes", (PyCFunction)array_frombytes, METH_VARARGS,
2122 frombytes_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002123 {"fromunicode", (PyCFunction)array_fromunicode, METH_VARARGS,
2124 fromunicode_doc},
2125 {"index", (PyCFunction)array_index, METH_O,
2126 index_doc},
2127 {"insert", (PyCFunction)array_insert, METH_VARARGS,
2128 insert_doc},
2129 {"pop", (PyCFunction)array_pop, METH_VARARGS,
2130 pop_doc},
2131 {"__reduce_ex__", (PyCFunction)array_reduce_ex, METH_O,
2132 reduce_doc},
2133 {"remove", (PyCFunction)array_remove, METH_O,
2134 remove_doc},
2135 {"reverse", (PyCFunction)array_reverse, METH_NOARGS,
2136 reverse_doc},
2137/* {"sort", (PyCFunction)array_sort, METH_VARARGS,
2138 sort_doc},*/
2139 {"tofile", (PyCFunction)array_tofile, METH_O,
2140 tofile_doc},
2141 {"tolist", (PyCFunction)array_tolist, METH_NOARGS,
2142 tolist_doc},
2143 {"tostring", (PyCFunction)array_tostring, METH_NOARGS,
2144 tostring_doc},
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00002145 {"tobytes", (PyCFunction)array_tobytes, METH_NOARGS,
2146 tobytes_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002147 {"tounicode", (PyCFunction)array_tounicode, METH_NOARGS,
2148 tounicode_doc},
2149 {NULL, NULL} /* sentinel */
Guido van Rossum778983b1993-02-19 15:55:02 +00002150};
2151
Roger E. Masse2919eaa1996-12-09 20:10:36 +00002152static PyObject *
Peter Schneider-Kamp9656abd2000-07-13 21:10:57 +00002153array_repr(arrayobject *a)
Guido van Rossum778983b1993-02-19 15:55:02 +00002154{
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02002155 char typecode;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002156 PyObject *s, *v = NULL;
2157 Py_ssize_t len;
Martin v. Löwis99866332002-03-01 10:27:01 +00002158
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002159 len = Py_SIZE(a);
2160 typecode = a->ob_descr->typecode;
2161 if (len == 0) {
Amaury Forgeot d'Arc24aa26b2010-11-25 08:13:35 +00002162 return PyUnicode_FromFormat("array('%c')", (int)typecode);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002163 }
Brett Cannon4a5e5de2011-06-07 20:09:32 -07002164 if (typecode == 'u')
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002165 v = array_tounicode(a, NULL);
2166 else
2167 v = array_tolist(a, NULL);
Raymond Hettinger88ba1e32003-04-23 17:27:00 +00002168
Amaury Forgeot d'Arc24aa26b2010-11-25 08:13:35 +00002169 s = PyUnicode_FromFormat("array('%c', %R)", (int)typecode, v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002170 Py_DECREF(v);
2171 return s;
Guido van Rossum778983b1993-02-19 15:55:02 +00002172}
2173
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002174static PyObject*
2175array_subscr(arrayobject* self, PyObject* item)
2176{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002177 if (PyIndex_Check(item)) {
2178 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
2179 if (i==-1 && PyErr_Occurred()) {
2180 return NULL;
2181 }
2182 if (i < 0)
2183 i += Py_SIZE(self);
2184 return array_item(self, i);
2185 }
2186 else if (PySlice_Check(item)) {
2187 Py_ssize_t start, stop, step, slicelength, cur, i;
2188 PyObject* result;
2189 arrayobject* ar;
2190 int itemsize = self->ob_descr->itemsize;
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002191
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002192 if (PySlice_GetIndicesEx(item, Py_SIZE(self),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002193 &start, &stop, &step, &slicelength) < 0) {
2194 return NULL;
2195 }
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002196
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002197 if (slicelength <= 0) {
2198 return newarrayobject(&Arraytype, 0, self->ob_descr);
2199 }
2200 else if (step == 1) {
2201 PyObject *result = newarrayobject(&Arraytype,
2202 slicelength, self->ob_descr);
2203 if (result == NULL)
2204 return NULL;
2205 memcpy(((arrayobject *)result)->ob_item,
2206 self->ob_item + start * itemsize,
2207 slicelength * itemsize);
2208 return result;
2209 }
2210 else {
2211 result = newarrayobject(&Arraytype, slicelength, self->ob_descr);
2212 if (!result) return NULL;
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002214 ar = (arrayobject*)result;
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002216 for (cur = start, i = 0; i < slicelength;
2217 cur += step, i++) {
2218 memcpy(ar->ob_item + i*itemsize,
2219 self->ob_item + cur*itemsize,
2220 itemsize);
2221 }
2222
2223 return result;
2224 }
2225 }
2226 else {
2227 PyErr_SetString(PyExc_TypeError,
2228 "array indices must be integers");
2229 return NULL;
2230 }
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002231}
2232
2233static int
2234array_ass_subscr(arrayobject* self, PyObject* item, PyObject* value)
2235{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002236 Py_ssize_t start, stop, step, slicelength, needed;
2237 arrayobject* other;
2238 int itemsize;
Thomas Woutersed03b412007-08-28 21:37:11 +00002239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002240 if (PyIndex_Check(item)) {
2241 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Alexandre Vassalotti47137252009-07-05 19:57:00 +00002242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002243 if (i == -1 && PyErr_Occurred())
2244 return -1;
2245 if (i < 0)
2246 i += Py_SIZE(self);
2247 if (i < 0 || i >= Py_SIZE(self)) {
2248 PyErr_SetString(PyExc_IndexError,
2249 "array assignment index out of range");
2250 return -1;
2251 }
2252 if (value == NULL) {
2253 /* Fall through to slice assignment */
2254 start = i;
2255 stop = i + 1;
2256 step = 1;
2257 slicelength = 1;
2258 }
2259 else
2260 return (*self->ob_descr->setitem)(self, i, value);
2261 }
2262 else if (PySlice_Check(item)) {
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002263 if (PySlice_GetIndicesEx(item,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002264 Py_SIZE(self), &start, &stop,
2265 &step, &slicelength) < 0) {
2266 return -1;
2267 }
2268 }
2269 else {
2270 PyErr_SetString(PyExc_TypeError,
2271 "array indices must be integer");
2272 return -1;
2273 }
2274 if (value == NULL) {
2275 other = NULL;
2276 needed = 0;
2277 }
2278 else if (array_Check(value)) {
2279 other = (arrayobject *)value;
2280 needed = Py_SIZE(other);
2281 if (self == other) {
2282 /* Special case "self[i:j] = self" -- copy self first */
2283 int ret;
2284 value = array_slice(other, 0, needed);
2285 if (value == NULL)
2286 return -1;
2287 ret = array_ass_subscr(self, item, value);
2288 Py_DECREF(value);
2289 return ret;
2290 }
2291 if (other->ob_descr != self->ob_descr) {
2292 PyErr_BadArgument();
2293 return -1;
2294 }
2295 }
2296 else {
2297 PyErr_Format(PyExc_TypeError,
2298 "can only assign array (not \"%.200s\") to array slice",
2299 Py_TYPE(value)->tp_name);
2300 return -1;
2301 }
2302 itemsize = self->ob_descr->itemsize;
2303 /* for 'a[2:1] = ...', the insertion point is 'start', not 'stop' */
2304 if ((step > 0 && stop < start) ||
2305 (step < 0 && stop > start))
2306 stop = start;
Alexandre Vassalotti47137252009-07-05 19:57:00 +00002307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002308 /* Issue #4509: If the array has exported buffers and the slice
2309 assignment would change the size of the array, fail early to make
2310 sure we don't modify it. */
2311 if ((needed == 0 || slicelength != needed) && self->ob_exports > 0) {
2312 PyErr_SetString(PyExc_BufferError,
2313 "cannot resize an array that is exporting buffers");
2314 return -1;
2315 }
Mark Dickinsonbc099642010-01-29 17:27:24 +00002316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002317 if (step == 1) {
2318 if (slicelength > needed) {
2319 memmove(self->ob_item + (start + needed) * itemsize,
2320 self->ob_item + stop * itemsize,
2321 (Py_SIZE(self) - stop) * itemsize);
2322 if (array_resize(self, Py_SIZE(self) +
2323 needed - slicelength) < 0)
2324 return -1;
2325 }
2326 else if (slicelength < needed) {
2327 if (array_resize(self, Py_SIZE(self) +
2328 needed - slicelength) < 0)
2329 return -1;
2330 memmove(self->ob_item + (start + needed) * itemsize,
2331 self->ob_item + stop * itemsize,
2332 (Py_SIZE(self) - start - needed) * itemsize);
2333 }
2334 if (needed > 0)
2335 memcpy(self->ob_item + start * itemsize,
2336 other->ob_item, needed * itemsize);
2337 return 0;
2338 }
2339 else if (needed == 0) {
2340 /* Delete slice */
2341 size_t cur;
2342 Py_ssize_t i;
Thomas Woutersed03b412007-08-28 21:37:11 +00002343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002344 if (step < 0) {
2345 stop = start + 1;
2346 start = stop + step * (slicelength - 1) - 1;
2347 step = -step;
2348 }
2349 for (cur = start, i = 0; i < slicelength;
2350 cur += step, i++) {
2351 Py_ssize_t lim = step - 1;
Thomas Woutersed03b412007-08-28 21:37:11 +00002352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002353 if (cur + step >= (size_t)Py_SIZE(self))
2354 lim = Py_SIZE(self) - cur - 1;
2355 memmove(self->ob_item + (cur - i) * itemsize,
2356 self->ob_item + (cur + 1) * itemsize,
2357 lim * itemsize);
2358 }
Mark Dickinsonc7d93b72011-09-25 15:34:32 +01002359 cur = start + (size_t)slicelength * step;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002360 if (cur < (size_t)Py_SIZE(self)) {
2361 memmove(self->ob_item + (cur-slicelength) * itemsize,
2362 self->ob_item + cur * itemsize,
2363 (Py_SIZE(self) - cur) * itemsize);
2364 }
2365 if (array_resize(self, Py_SIZE(self) - slicelength) < 0)
2366 return -1;
2367 return 0;
2368 }
2369 else {
2370 Py_ssize_t cur, i;
2371
2372 if (needed != slicelength) {
2373 PyErr_Format(PyExc_ValueError,
2374 "attempt to assign array of size %zd "
2375 "to extended slice of size %zd",
2376 needed, slicelength);
2377 return -1;
2378 }
2379 for (cur = start, i = 0; i < slicelength;
2380 cur += step, i++) {
2381 memcpy(self->ob_item + cur * itemsize,
2382 other->ob_item + i * itemsize,
2383 itemsize);
2384 }
2385 return 0;
2386 }
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002387}
2388
2389static PyMappingMethods array_as_mapping = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002390 (lenfunc)array_length,
2391 (binaryfunc)array_subscr,
2392 (objobjargproc)array_ass_subscr
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002393};
2394
Guido van Rossumd8faa362007-04-27 19:54:29 +00002395static const void *emptybuf = "";
2396
Travis E. Oliphantb99f7622007-08-18 11:21:56 +00002397
2398static int
Travis E. Oliphant8ae62b62007-09-23 02:00:13 +00002399array_buffer_getbuf(arrayobject *self, Py_buffer *view, int flags)
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00002400{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002401 if (view==NULL) goto finish;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +00002402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002403 view->buf = (void *)self->ob_item;
2404 view->obj = (PyObject*)self;
2405 Py_INCREF(self);
2406 if (view->buf == NULL)
2407 view->buf = (void *)emptybuf;
2408 view->len = (Py_SIZE(self)) * self->ob_descr->itemsize;
2409 view->readonly = 0;
2410 view->ndim = 1;
2411 view->itemsize = self->ob_descr->itemsize;
2412 view->suboffsets = NULL;
2413 view->shape = NULL;
2414 if ((flags & PyBUF_ND)==PyBUF_ND) {
2415 view->shape = &((Py_SIZE(self)));
2416 }
2417 view->strides = NULL;
2418 if ((flags & PyBUF_STRIDES)==PyBUF_STRIDES)
2419 view->strides = &(view->itemsize);
2420 view->format = NULL;
2421 view->internal = NULL;
Victor Stinner8dba4e02011-09-30 00:51:10 +02002422 if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002423 view->format = self->ob_descr->formats;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +00002424
2425 finish:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002426 self->ob_exports++;
2427 return 0;
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00002428}
2429
Travis E. Oliphantb99f7622007-08-18 11:21:56 +00002430static void
Travis E. Oliphant8ae62b62007-09-23 02:00:13 +00002431array_buffer_relbuf(arrayobject *self, Py_buffer *view)
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00002432{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002433 self->ob_exports--;
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00002434}
2435
Roger E. Masse2919eaa1996-12-09 20:10:36 +00002436static PySequenceMethods array_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002437 (lenfunc)array_length, /*sq_length*/
2438 (binaryfunc)array_concat, /*sq_concat*/
2439 (ssizeargfunc)array_repeat, /*sq_repeat*/
2440 (ssizeargfunc)array_item, /*sq_item*/
2441 0, /*sq_slice*/
2442 (ssizeobjargproc)array_ass_item, /*sq_ass_item*/
2443 0, /*sq_ass_slice*/
2444 (objobjproc)array_contains, /*sq_contains*/
2445 (binaryfunc)array_inplace_concat, /*sq_inplace_concat*/
2446 (ssizeargfunc)array_inplace_repeat /*sq_inplace_repeat*/
Guido van Rossum778983b1993-02-19 15:55:02 +00002447};
2448
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00002449static PyBufferProcs array_as_buffer = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002450 (getbufferproc)array_buffer_getbuf,
2451 (releasebufferproc)array_buffer_relbuf
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00002452};
2453
Roger E. Masse2919eaa1996-12-09 20:10:36 +00002454static PyObject *
Martin v. Löwis99866332002-03-01 10:27:01 +00002455array_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum778983b1993-02-19 15:55:02 +00002456{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002457 int c;
2458 PyObject *initial = NULL, *it = NULL;
2459 struct arraydescr *descr;
Martin v. Löwis99866332002-03-01 10:27:01 +00002460
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002461 if (type == &Arraytype && !_PyArg_NoKeywords("array.array()", kwds))
2462 return NULL;
Martin v. Löwis99866332002-03-01 10:27:01 +00002463
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002464 if (!PyArg_ParseTuple(args, "C|O:array", &c, &initial))
2465 return NULL;
Raymond Hettinger84fc9aa2003-04-24 10:41:55 +00002466
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002467 if (!(initial == NULL || PyList_Check(initial)
2468 || PyByteArray_Check(initial)
2469 || PyBytes_Check(initial)
2470 || PyTuple_Check(initial)
Alexander Belopolskyef4a03f2011-01-11 21:44:00 +00002471 || ((c=='u') && PyUnicode_Check(initial))
2472 || (array_Check(initial)
2473 && c == ((arrayobject*)initial)->ob_descr->typecode))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002474 it = PyObject_GetIter(initial);
2475 if (it == NULL)
2476 return NULL;
2477 /* We set initial to NULL so that the subsequent code
2478 will create an empty array of the appropriate type
2479 and afterwards we can use array_iter_extend to populate
2480 the array.
2481 */
2482 initial = NULL;
2483 }
2484 for (descr = descriptors; descr->typecode != '\0'; descr++) {
2485 if (descr->typecode == c) {
2486 PyObject *a;
2487 Py_ssize_t len;
Martin v. Löwis99866332002-03-01 10:27:01 +00002488
Alexander Belopolskyef4a03f2011-01-11 21:44:00 +00002489 if (initial == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002490 len = 0;
Alexander Belopolskyef4a03f2011-01-11 21:44:00 +00002491 else if (PyList_Check(initial))
2492 len = PyList_GET_SIZE(initial);
2493 else if (PyTuple_Check(initial) || array_Check(initial))
2494 len = Py_SIZE(initial);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002495 else
Alexander Belopolskyef4a03f2011-01-11 21:44:00 +00002496 len = 0;
Martin v. Löwis99866332002-03-01 10:27:01 +00002497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002498 a = newarrayobject(type, len, descr);
2499 if (a == NULL)
2500 return NULL;
2501
Alexander Belopolskyef4a03f2011-01-11 21:44:00 +00002502 if (len > 0 && !array_Check(initial)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002503 Py_ssize_t i;
2504 for (i = 0; i < len; i++) {
2505 PyObject *v =
2506 PySequence_GetItem(initial, i);
2507 if (v == NULL) {
2508 Py_DECREF(a);
2509 return NULL;
2510 }
2511 if (setarrayitem(a, i, v) != 0) {
2512 Py_DECREF(v);
2513 Py_DECREF(a);
2514 return NULL;
2515 }
2516 Py_DECREF(v);
2517 }
2518 }
2519 else if (initial != NULL && (PyByteArray_Check(initial) ||
2520 PyBytes_Check(initial))) {
2521 PyObject *t_initial, *v;
2522 t_initial = PyTuple_Pack(1, initial);
2523 if (t_initial == NULL) {
2524 Py_DECREF(a);
2525 return NULL;
2526 }
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00002527 v = array_frombytes((arrayobject *)a,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002528 t_initial);
2529 Py_DECREF(t_initial);
2530 if (v == NULL) {
2531 Py_DECREF(a);
2532 return NULL;
2533 }
2534 Py_DECREF(v);
2535 }
2536 else if (initial != NULL && PyUnicode_Check(initial)) {
Victor Stinner1fbcaef2011-09-30 01:54:04 +02002537 Py_ssize_t n;
2538 if (PyUnicode_READY(initial)) {
2539 Py_DECREF(a);
2540 return NULL;
2541 }
2542 n = PyUnicode_GET_LENGTH(initial);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002543 if (n > 0) {
2544 arrayobject *self = (arrayobject *)a;
Victor Stinner1fbcaef2011-09-30 01:54:04 +02002545 Py_UCS4 *item = (Py_UCS4 *)self->ob_item;
Victor Stinner1fe99a22011-09-30 01:55:49 +02002546 item = (Py_UCS4 *)PyMem_Realloc(item, n * sizeof(Py_UCS4));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002547 if (item == NULL) {
2548 PyErr_NoMemory();
2549 Py_DECREF(a);
2550 return NULL;
2551 }
Victor Stinner1fbcaef2011-09-30 01:54:04 +02002552 self->ob_item = (char*)item;
2553 Py_SIZE(self) = n;
2554 if (!PyUnicode_AsUCS4(initial, item, n, 0))
2555 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002556 self->allocated = Py_SIZE(self);
2557 }
2558 }
Alexander Belopolskyef4a03f2011-01-11 21:44:00 +00002559 else if (initial != NULL && array_Check(initial)) {
2560 arrayobject *self = (arrayobject *)a;
2561 arrayobject *other = (arrayobject *)initial;
2562 memcpy(self->ob_item, other->ob_item, len * other->ob_descr->itemsize);
2563 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002564 if (it != NULL) {
2565 if (array_iter_extend((arrayobject *)a, it) == -1) {
2566 Py_DECREF(it);
2567 Py_DECREF(a);
2568 return NULL;
2569 }
2570 Py_DECREF(it);
2571 }
2572 return a;
2573 }
2574 }
2575 PyErr_SetString(PyExc_ValueError,
Meador Inge1c9f0c92011-09-20 19:55:51 -05002576#ifdef HAVE_LONG_LONG
2577 "bad typecode (must be b, B, u, h, H, i, I, l, L, q, Q, f or d)");
2578#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002579 "bad typecode (must be b, B, u, h, H, i, I, l, L, f or d)");
Meador Inge1c9f0c92011-09-20 19:55:51 -05002580#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002581 return NULL;
Guido van Rossum778983b1993-02-19 15:55:02 +00002582}
2583
Guido van Rossum778983b1993-02-19 15:55:02 +00002584
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002585PyDoc_STRVAR(module_doc,
Martin v. Löwis99866332002-03-01 10:27:01 +00002586"This module defines an object type which can efficiently represent\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002587an array of basic values: characters, integers, floating point\n\
2588numbers. Arrays are sequence types and behave very much like lists,\n\
2589except that the type of objects stored in them is constrained. The\n\
2590type is specified at object creation time by using a type code, which\n\
2591is a single character. The following type codes are defined:\n\
2592\n\
2593 Type code C Type Minimum size in bytes \n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002594 'b' signed integer 1 \n\
2595 'B' unsigned integer 1 \n\
Ezio Melotti90bf5f12011-10-25 10:05:34 +03002596 'u' Unicode character 4 \n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002597 'h' signed integer 2 \n\
2598 'H' unsigned integer 2 \n\
2599 'i' signed integer 2 \n\
2600 'I' unsigned integer 2 \n\
2601 'l' signed integer 4 \n\
2602 'L' unsigned integer 4 \n\
Meador Inge1c9f0c92011-09-20 19:55:51 -05002603 'q' signed integer 8 (see note) \n\
2604 'Q' unsigned integer 8 (see note) \n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002605 'f' floating point 4 \n\
2606 'd' floating point 8 \n\
2607\n\
Meador Inge1c9f0c92011-09-20 19:55:51 -05002608NOTE: The 'q' and 'Q' type codes are only available if the platform \n\
2609C compiler used to build Python supports 'long long', or, on Windows, \n\
2610'__int64'.\n\
2611\n\
Martin v. Löwis99866332002-03-01 10:27:01 +00002612The constructor is:\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002613\n\
2614array(typecode [, initializer]) -- create a new array\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002615");
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002616
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002617PyDoc_STRVAR(arraytype_doc,
Martin v. Löwis99866332002-03-01 10:27:01 +00002618"array(typecode [, initializer]) -> array\n\
2619\n\
2620Return a new array whose items are restricted by typecode, and\n\
Raymond Hettinger6ab78cd2004-08-29 07:50:43 +00002621initialized from the optional initializer value, which must be a list,\n\
Florent Xicluna0e686cb2011-12-09 23:41:19 +01002622string or iterable over elements of the appropriate type.\n\
Martin v. Löwis99866332002-03-01 10:27:01 +00002623\n\
2624Arrays represent basic values and behave very much like lists, except\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002625the type of objects stored in them is constrained.\n\
2626\n\
2627Methods:\n\
2628\n\
2629append() -- append a new item to the end of the array\n\
2630buffer_info() -- return information giving the current memory info\n\
2631byteswap() -- byteswap all the items of the array\n\
Mark Dickinson934896d2009-02-21 20:59:32 +00002632count() -- return number of occurrences of an object\n\
Raymond Hettinger49f9bd12004-03-14 05:43:59 +00002633extend() -- extend array by appending multiple elements from an iterable\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002634fromfile() -- read items from a file object\n\
2635fromlist() -- append items from the list\n\
Florent Xiclunac45fb252011-10-24 13:14:55 +02002636frombytes() -- append items from the string\n\
Mark Dickinson934896d2009-02-21 20:59:32 +00002637index() -- return index of first occurrence of an object\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002638insert() -- insert a new item into the array at a provided position\n\
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00002639pop() -- remove and return item (default last)\n\
Mark Dickinson934896d2009-02-21 20:59:32 +00002640remove() -- remove first occurrence of an object\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002641reverse() -- reverse the order of the items in the array\n\
2642tofile() -- write all items to a file object\n\
2643tolist() -- return the array converted to an ordinary list\n\
Florent Xiclunac45fb252011-10-24 13:14:55 +02002644tobytes() -- return the array converted to a string\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002645\n\
Martin v. Löwis99866332002-03-01 10:27:01 +00002646Attributes:\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002647\n\
2648typecode -- the typecode character used to create the array\n\
2649itemsize -- the length in bytes of one array item\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002650");
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002651
Raymond Hettinger625812f2003-01-07 01:58:52 +00002652static PyObject *array_iter(arrayobject *ao);
2653
Tim Peters0c322792002-07-17 16:49:03 +00002654static PyTypeObject Arraytype = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002655 PyVarObject_HEAD_INIT(NULL, 0)
2656 "array.array",
2657 sizeof(arrayobject),
2658 0,
2659 (destructor)array_dealloc, /* tp_dealloc */
2660 0, /* tp_print */
2661 0, /* tp_getattr */
2662 0, /* tp_setattr */
2663 0, /* tp_reserved */
2664 (reprfunc)array_repr, /* tp_repr */
2665 0, /* tp_as_number*/
2666 &array_as_sequence, /* tp_as_sequence*/
2667 &array_as_mapping, /* tp_as_mapping*/
2668 0, /* tp_hash */
2669 0, /* tp_call */
2670 0, /* tp_str */
2671 PyObject_GenericGetAttr, /* tp_getattro */
2672 0, /* tp_setattro */
2673 &array_as_buffer, /* tp_as_buffer*/
2674 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
2675 arraytype_doc, /* tp_doc */
2676 0, /* tp_traverse */
2677 0, /* tp_clear */
2678 array_richcompare, /* tp_richcompare */
2679 offsetof(arrayobject, weakreflist), /* tp_weaklistoffset */
2680 (getiterfunc)array_iter, /* tp_iter */
2681 0, /* tp_iternext */
2682 array_methods, /* tp_methods */
2683 0, /* tp_members */
2684 array_getsets, /* tp_getset */
2685 0, /* tp_base */
2686 0, /* tp_dict */
2687 0, /* tp_descr_get */
2688 0, /* tp_descr_set */
2689 0, /* tp_dictoffset */
2690 0, /* tp_init */
2691 PyType_GenericAlloc, /* tp_alloc */
2692 array_new, /* tp_new */
2693 PyObject_Del, /* tp_free */
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002694};
2695
Raymond Hettinger625812f2003-01-07 01:58:52 +00002696
2697/*********************** Array Iterator **************************/
2698
2699typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002700 PyObject_HEAD
2701 Py_ssize_t index;
2702 arrayobject *ao;
2703 PyObject * (*getitem)(struct arrayobject *, Py_ssize_t);
Raymond Hettinger625812f2003-01-07 01:58:52 +00002704} arrayiterobject;
2705
2706static PyTypeObject PyArrayIter_Type;
2707
2708#define PyArrayIter_Check(op) PyObject_TypeCheck(op, &PyArrayIter_Type)
2709
2710static PyObject *
2711array_iter(arrayobject *ao)
2712{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002713 arrayiterobject *it;
Raymond Hettinger625812f2003-01-07 01:58:52 +00002714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002715 if (!array_Check(ao)) {
2716 PyErr_BadInternalCall();
2717 return NULL;
2718 }
Raymond Hettinger625812f2003-01-07 01:58:52 +00002719
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002720 it = PyObject_GC_New(arrayiterobject, &PyArrayIter_Type);
2721 if (it == NULL)
2722 return NULL;
Raymond Hettinger625812f2003-01-07 01:58:52 +00002723
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002724 Py_INCREF(ao);
2725 it->ao = ao;
2726 it->index = 0;
2727 it->getitem = ao->ob_descr->getitem;
2728 PyObject_GC_Track(it);
2729 return (PyObject *)it;
Raymond Hettinger625812f2003-01-07 01:58:52 +00002730}
2731
2732static PyObject *
Raymond Hettinger625812f2003-01-07 01:58:52 +00002733arrayiter_next(arrayiterobject *it)
2734{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002735 assert(PyArrayIter_Check(it));
2736 if (it->index < Py_SIZE(it->ao))
2737 return (*it->getitem)(it->ao, it->index++);
2738 return NULL;
Raymond Hettinger625812f2003-01-07 01:58:52 +00002739}
2740
2741static void
2742arrayiter_dealloc(arrayiterobject *it)
2743{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002744 PyObject_GC_UnTrack(it);
2745 Py_XDECREF(it->ao);
2746 PyObject_GC_Del(it);
Raymond Hettinger625812f2003-01-07 01:58:52 +00002747}
2748
2749static int
2750arrayiter_traverse(arrayiterobject *it, visitproc visit, void *arg)
2751{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002752 Py_VISIT(it->ao);
2753 return 0;
Raymond Hettinger625812f2003-01-07 01:58:52 +00002754}
2755
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002756static PyObject *
2757arrayiter_reduce(arrayiterobject *it)
2758{
Antoine Pitroua7013882012-04-05 00:04:20 +02002759 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002760 it->ao, it->index);
2761}
2762
2763static PyObject *
2764arrayiter_setstate(arrayiterobject *it, PyObject *state)
2765{
2766 Py_ssize_t index = PyLong_AsSsize_t(state);
2767 if (index == -1 && PyErr_Occurred())
2768 return NULL;
2769 if (index < 0)
2770 index = 0;
2771 it->index = index;
2772 Py_RETURN_NONE;
2773}
2774
2775PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
2776static PyMethodDef arrayiter_methods[] = {
2777 {"__reduce__", (PyCFunction)arrayiter_reduce, METH_NOARGS,
2778 reduce_doc},
2779 {"__setstate__", (PyCFunction)arrayiter_setstate, METH_O,
2780 setstate_doc},
2781 {NULL, NULL} /* sentinel */
2782};
2783
Raymond Hettinger625812f2003-01-07 01:58:52 +00002784static PyTypeObject PyArrayIter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002785 PyVarObject_HEAD_INIT(NULL, 0)
2786 "arrayiterator", /* tp_name */
2787 sizeof(arrayiterobject), /* tp_basicsize */
2788 0, /* tp_itemsize */
2789 /* methods */
2790 (destructor)arrayiter_dealloc, /* tp_dealloc */
2791 0, /* tp_print */
2792 0, /* tp_getattr */
2793 0, /* tp_setattr */
2794 0, /* tp_reserved */
2795 0, /* tp_repr */
2796 0, /* tp_as_number */
2797 0, /* tp_as_sequence */
2798 0, /* tp_as_mapping */
2799 0, /* tp_hash */
2800 0, /* tp_call */
2801 0, /* tp_str */
2802 PyObject_GenericGetAttr, /* tp_getattro */
2803 0, /* tp_setattro */
2804 0, /* tp_as_buffer */
2805 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2806 0, /* tp_doc */
2807 (traverseproc)arrayiter_traverse, /* tp_traverse */
2808 0, /* tp_clear */
2809 0, /* tp_richcompare */
2810 0, /* tp_weaklistoffset */
2811 PyObject_SelfIter, /* tp_iter */
2812 (iternextfunc)arrayiter_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002813 arrayiter_methods, /* tp_methods */
Raymond Hettinger625812f2003-01-07 01:58:52 +00002814};
2815
2816
2817/*********************** Install Module **************************/
2818
Martin v. Löwis99866332002-03-01 10:27:01 +00002819/* No functions in array module. */
2820static PyMethodDef a_methods[] = {
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002821 {"_array_reconstructor", array_reconstructor, METH_VARARGS,
2822 PyDoc_STR("Internal. Used for pickling support.")},
Martin v. Löwis99866332002-03-01 10:27:01 +00002823 {NULL, NULL, 0, NULL} /* Sentinel */
2824};
2825
Martin v. Löwis1a214512008-06-11 05:26:20 +00002826static struct PyModuleDef arraymodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002827 PyModuleDef_HEAD_INIT,
2828 "array",
2829 module_doc,
2830 -1,
2831 a_methods,
2832 NULL,
2833 NULL,
2834 NULL,
2835 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002836};
2837
Martin v. Löwis99866332002-03-01 10:27:01 +00002838
Mark Hammondfe51c6d2002-08-02 02:27:13 +00002839PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002840PyInit_array(void)
Guido van Rossum778983b1993-02-19 15:55:02 +00002841{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002842 PyObject *m;
Georg Brandl4cb0de22011-09-28 21:49:49 +02002843 char buffer[Py_ARRAY_LENGTH(descriptors)], *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002844 PyObject *typecodes;
2845 Py_ssize_t size = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002846 struct arraydescr *descr;
Fred Drake0d40ba42000-02-04 20:33:49 +00002847
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002848 if (PyType_Ready(&Arraytype) < 0)
2849 return NULL;
2850 Py_TYPE(&PyArrayIter_Type) = &PyType_Type;
2851 m = PyModule_Create(&arraymodule);
2852 if (m == NULL)
2853 return NULL;
Fred Drakef4e34842002-04-01 03:45:06 +00002854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002855 Py_INCREF((PyObject *)&Arraytype);
2856 PyModule_AddObject(m, "ArrayType", (PyObject *)&Arraytype);
2857 Py_INCREF((PyObject *)&Arraytype);
2858 PyModule_AddObject(m, "array", (PyObject *)&Arraytype);
Travis E. Oliphantd5c0add2007-10-12 22:05:15 +00002859
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002860 for (descr=descriptors; descr->typecode != '\0'; descr++) {
2861 size++;
2862 }
Travis E. Oliphantd5c0add2007-10-12 22:05:15 +00002863
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002864 p = buffer;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002865 for (descr = descriptors; descr->typecode != '\0'; descr++) {
2866 *p++ = (char)descr->typecode;
2867 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002868 typecodes = PyUnicode_DecodeASCII(buffer, p - buffer, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002869
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002870 PyModule_AddObject(m, "typecodes", typecodes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002871
2872 if (PyErr_Occurred()) {
2873 Py_DECREF(m);
2874 m = NULL;
2875 }
2876 return m;
Guido van Rossum778983b1993-02-19 15:55:02 +00002877}