blob: f0615c995c535dc8aab46f1fda0548add9810d12 [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 Stinner62bb3942012-08-06 00:46:05 +0200177 return PyUnicode_FromUnicode(&((Py_UNICODE *) ap->ob_item)[i], 1);
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 Stinner62bb3942012-08-06 00:46:05 +0200183 Py_UNICODE *p;
184 Py_ssize_t len;
Martin v. Löwis99866332002-03-01 10:27:01 +0000185
Victor Stinner62bb3942012-08-06 00:46:05 +0200186 if (!PyArg_Parse(v, "u#;array item must be unicode character", &p, &len))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000187 return -1;
Victor Stinner62bb3942012-08-06 00:46:05 +0200188 if (len != 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000189 PyErr_SetString(PyExc_TypeError,
190 "array item must be unicode character");
191 return -1;
192 }
193 if (i >= 0)
Victor Stinner62bb3942012-08-06 00:46:05 +0200194 ((Py_UNICODE *)ap->ob_item)[i] = p[0];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000195 return 0;
Martin v. Löwis99866332002-03-01 10:27:01 +0000196}
Martin v. Löwis99866332002-03-01 10:27:01 +0000197
Travis E. Oliphantd5c0add2007-10-12 22:05:15 +0000198
Guido van Rossum549ab711997-01-03 19:09:47 +0000199static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000200h_getitem(arrayobject *ap, Py_ssize_t i)
Guido van Rossum778983b1993-02-19 15:55:02 +0000201{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000202 return PyLong_FromLong((long) ((short *)ap->ob_item)[i]);
Guido van Rossum778983b1993-02-19 15:55:02 +0000203}
204
Travis E. Oliphantd5c0add2007-10-12 22:05:15 +0000205
Guido van Rossum778983b1993-02-19 15:55:02 +0000206static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000207h_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
Guido van Rossum778983b1993-02-19 15:55:02 +0000208{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000209 short x;
210 /* 'h' == signed short, maps to PyArg_Parse's 'h' formatter */
211 if (!PyArg_Parse(v, "h;array item must be integer", &x))
212 return -1;
213 if (i >= 0)
214 ((short *)ap->ob_item)[i] = x;
215 return 0;
Guido van Rossum778983b1993-02-19 15:55:02 +0000216}
217
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000218static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000219HH_getitem(arrayobject *ap, Py_ssize_t i)
Guido van Rossum549ab711997-01-03 19:09:47 +0000220{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000221 return PyLong_FromLong((long) ((unsigned short *)ap->ob_item)[i]);
Guido van Rossum549ab711997-01-03 19:09:47 +0000222}
223
Fred Drake541dc3b2000-06-28 17:49:30 +0000224static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000225HH_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
Fred Drake541dc3b2000-06-28 17:49:30 +0000226{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000227 int x;
228 /* PyArg_Parse's 'h' formatter is for a signed short, therefore
229 must use the next size up and manually do the overflow checking */
230 if (!PyArg_Parse(v, "i;array item must be integer", &x))
231 return -1;
232 else if (x < 0) {
233 PyErr_SetString(PyExc_OverflowError,
234 "unsigned short is less than minimum");
235 return -1;
236 }
237 else if (x > USHRT_MAX) {
238 PyErr_SetString(PyExc_OverflowError,
239 "unsigned short is greater than maximum");
240 return -1;
241 }
242 if (i >= 0)
243 ((short *)ap->ob_item)[i] = (short)x;
244 return 0;
Fred Drake541dc3b2000-06-28 17:49:30 +0000245}
Guido van Rossum549ab711997-01-03 19:09:47 +0000246
247static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000248i_getitem(arrayobject *ap, Py_ssize_t i)
Guido van Rossume77a7571993-11-03 15:01:26 +0000249{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000250 return PyLong_FromLong((long) ((int *)ap->ob_item)[i]);
Guido van Rossume77a7571993-11-03 15:01:26 +0000251}
252
253static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000254i_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
Guido van Rossume77a7571993-11-03 15:01:26 +0000255{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000256 int x;
257 /* 'i' == signed int, maps to PyArg_Parse's 'i' formatter */
258 if (!PyArg_Parse(v, "i;array item must be integer", &x))
259 return -1;
260 if (i >= 0)
261 ((int *)ap->ob_item)[i] = x;
262 return 0;
Guido van Rossume77a7571993-11-03 15:01:26 +0000263}
264
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000265static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000266II_getitem(arrayobject *ap, Py_ssize_t i)
Guido van Rossum549ab711997-01-03 19:09:47 +0000267{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000268 return PyLong_FromUnsignedLong(
269 (unsigned long) ((unsigned int *)ap->ob_item)[i]);
Guido van Rossum549ab711997-01-03 19:09:47 +0000270}
271
272static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000273II_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
Guido van Rossum549ab711997-01-03 19:09:47 +0000274{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000275 unsigned long x;
276 if (PyLong_Check(v)) {
277 x = PyLong_AsUnsignedLong(v);
278 if (x == (unsigned long) -1 && PyErr_Occurred())
279 return -1;
280 }
281 else {
282 long y;
283 if (!PyArg_Parse(v, "l;array item must be integer", &y))
284 return -1;
285 if (y < 0) {
286 PyErr_SetString(PyExc_OverflowError,
287 "unsigned int is less than minimum");
288 return -1;
289 }
290 x = (unsigned long)y;
Tim Petersbb307342000-09-10 05:22:54 +0000291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000292 }
293 if (x > UINT_MAX) {
294 PyErr_SetString(PyExc_OverflowError,
295 "unsigned int is greater than maximum");
296 return -1;
297 }
Fred Drake541dc3b2000-06-28 17:49:30 +0000298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000299 if (i >= 0)
300 ((unsigned int *)ap->ob_item)[i] = (unsigned int)x;
301 return 0;
Guido van Rossum549ab711997-01-03 19:09:47 +0000302}
303
304static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000305l_getitem(arrayobject *ap, Py_ssize_t i)
Guido van Rossum778983b1993-02-19 15:55:02 +0000306{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000307 return PyLong_FromLong(((long *)ap->ob_item)[i]);
Guido van Rossum778983b1993-02-19 15:55:02 +0000308}
309
310static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000311l_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
Guido van Rossum778983b1993-02-19 15:55:02 +0000312{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000313 long x;
314 if (!PyArg_Parse(v, "l;array item must be integer", &x))
315 return -1;
316 if (i >= 0)
317 ((long *)ap->ob_item)[i] = x;
318 return 0;
Guido van Rossum778983b1993-02-19 15:55:02 +0000319}
320
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000321static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000322LL_getitem(arrayobject *ap, Py_ssize_t i)
Guido van Rossum549ab711997-01-03 19:09:47 +0000323{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000324 return PyLong_FromUnsignedLong(((unsigned long *)ap->ob_item)[i]);
Guido van Rossum549ab711997-01-03 19:09:47 +0000325}
326
327static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000328LL_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
Guido van Rossum549ab711997-01-03 19:09:47 +0000329{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 unsigned long x;
331 if (PyLong_Check(v)) {
332 x = PyLong_AsUnsignedLong(v);
333 if (x == (unsigned long) -1 && PyErr_Occurred())
334 return -1;
335 }
336 else {
337 long y;
338 if (!PyArg_Parse(v, "l;array item must be integer", &y))
339 return -1;
340 if (y < 0) {
341 PyErr_SetString(PyExc_OverflowError,
342 "unsigned long is less than minimum");
343 return -1;
344 }
345 x = (unsigned long)y;
Tim Petersbb307342000-09-10 05:22:54 +0000346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000347 }
348 if (x > ULONG_MAX) {
349 PyErr_SetString(PyExc_OverflowError,
350 "unsigned long is greater than maximum");
351 return -1;
352 }
Tim Petersbb307342000-09-10 05:22:54 +0000353
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000354 if (i >= 0)
355 ((unsigned long *)ap->ob_item)[i] = x;
356 return 0;
Guido van Rossum549ab711997-01-03 19:09:47 +0000357}
358
Meador Inge1c9f0c92011-09-20 19:55:51 -0500359#ifdef HAVE_LONG_LONG
360
361static PyObject *
362q_getitem(arrayobject *ap, Py_ssize_t i)
363{
364 return PyLong_FromLongLong(((PY_LONG_LONG *)ap->ob_item)[i]);
365}
366
367static int
368q_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
369{
370 PY_LONG_LONG x;
371 if (!PyArg_Parse(v, "L;array item must be integer", &x))
372 return -1;
373 if (i >= 0)
374 ((PY_LONG_LONG *)ap->ob_item)[i] = x;
375 return 0;
376}
377
378static PyObject *
379QQ_getitem(arrayobject *ap, Py_ssize_t i)
380{
381 return PyLong_FromUnsignedLongLong(
382 ((unsigned PY_LONG_LONG *)ap->ob_item)[i]);
383}
384
385static int
386QQ_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
387{
388 unsigned PY_LONG_LONG x;
389 if (PyLong_Check(v)) {
390 x = PyLong_AsUnsignedLongLong(v);
391 if (x == (unsigned PY_LONG_LONG) -1 && PyErr_Occurred())
392 return -1;
393 }
394 else {
395 PY_LONG_LONG y;
396 if (!PyArg_Parse(v, "L;array item must be integer", &y))
397 return -1;
398 if (y < 0) {
399 PyErr_SetString(PyExc_OverflowError,
400 "unsigned long long is less than minimum");
401 return -1;
402 }
403 x = (unsigned PY_LONG_LONG)y;
404 }
405
406 if (i >= 0)
407 ((unsigned PY_LONG_LONG *)ap->ob_item)[i] = x;
408 return 0;
409}
410#endif
411
Guido van Rossum549ab711997-01-03 19:09:47 +0000412static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000413f_getitem(arrayobject *ap, Py_ssize_t i)
Guido van Rossum778983b1993-02-19 15:55:02 +0000414{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000415 return PyFloat_FromDouble((double) ((float *)ap->ob_item)[i]);
Guido van Rossum778983b1993-02-19 15:55:02 +0000416}
417
418static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000419f_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
Guido van Rossum778983b1993-02-19 15:55:02 +0000420{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 float x;
422 if (!PyArg_Parse(v, "f;array item must be float", &x))
423 return -1;
424 if (i >= 0)
425 ((float *)ap->ob_item)[i] = x;
426 return 0;
Guido van Rossum778983b1993-02-19 15:55:02 +0000427}
428
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000429static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000430d_getitem(arrayobject *ap, Py_ssize_t i)
Guido van Rossum778983b1993-02-19 15:55:02 +0000431{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000432 return PyFloat_FromDouble(((double *)ap->ob_item)[i]);
Guido van Rossum778983b1993-02-19 15:55:02 +0000433}
434
435static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000436d_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
Guido van Rossum778983b1993-02-19 15:55:02 +0000437{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000438 double x;
439 if (!PyArg_Parse(v, "d;array item must be float", &x))
440 return -1;
441 if (i >= 0)
442 ((double *)ap->ob_item)[i] = x;
443 return 0;
Guido van Rossum778983b1993-02-19 15:55:02 +0000444}
445
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000446
Alexandre Vassalottiad077152009-07-15 17:49:23 +0000447/* Description of types.
448 *
449 * Don't forget to update typecode_to_mformat_code() if you add a new
450 * typecode.
451 */
Guido van Rossum234f9421993-06-17 12:35:49 +0000452static struct arraydescr descriptors[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000453 {'b', 1, b_getitem, b_setitem, "b", 1, 1},
454 {'B', 1, BB_getitem, BB_setitem, "B", 1, 0},
Victor Stinner62bb3942012-08-06 00:46:05 +0200455 {'u', sizeof(Py_UNICODE), u_getitem, u_setitem, "u", 0, 0},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 {'h', sizeof(short), h_getitem, h_setitem, "h", 1, 1},
457 {'H', sizeof(short), HH_getitem, HH_setitem, "H", 1, 0},
458 {'i', sizeof(int), i_getitem, i_setitem, "i", 1, 1},
459 {'I', sizeof(int), II_getitem, II_setitem, "I", 1, 0},
460 {'l', sizeof(long), l_getitem, l_setitem, "l", 1, 1},
461 {'L', sizeof(long), LL_getitem, LL_setitem, "L", 1, 0},
Meador Inge1c9f0c92011-09-20 19:55:51 -0500462#ifdef HAVE_LONG_LONG
463 {'q', sizeof(PY_LONG_LONG), q_getitem, q_setitem, "q", 1, 1},
464 {'Q', sizeof(PY_LONG_LONG), QQ_getitem, QQ_setitem, "Q", 1, 0},
465#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000466 {'f', sizeof(float), f_getitem, f_setitem, "f", 0, 0},
467 {'d', sizeof(double), d_getitem, d_setitem, "d", 0, 0},
468 {'\0', 0, 0, 0, 0, 0, 0} /* Sentinel */
Guido van Rossum778983b1993-02-19 15:55:02 +0000469};
Tim Petersbb307342000-09-10 05:22:54 +0000470
471/****************************************************************************
472Implementations of array object methods.
473****************************************************************************/
Guido van Rossum778983b1993-02-19 15:55:02 +0000474
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000475static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000476newarrayobject(PyTypeObject *type, Py_ssize_t size, struct arraydescr *descr)
Guido van Rossum778983b1993-02-19 15:55:02 +0000477{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 arrayobject *op;
479 size_t nbytes;
Martin v. Löwis99866332002-03-01 10:27:01 +0000480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000481 if (size < 0) {
482 PyErr_BadInternalCall();
483 return NULL;
484 }
Martin v. Löwis99866332002-03-01 10:27:01 +0000485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 nbytes = size * descr->itemsize;
487 /* Check for overflow */
488 if (nbytes / descr->itemsize != (size_t)size) {
489 return PyErr_NoMemory();
490 }
491 op = (arrayobject *) type->tp_alloc(type, 0);
492 if (op == NULL) {
493 return NULL;
494 }
495 op->ob_descr = descr;
496 op->allocated = size;
497 op->weakreflist = NULL;
498 Py_SIZE(op) = size;
499 if (size <= 0) {
500 op->ob_item = NULL;
501 }
502 else {
503 op->ob_item = PyMem_NEW(char, nbytes);
504 if (op->ob_item == NULL) {
505 Py_DECREF(op);
506 return PyErr_NoMemory();
507 }
508 }
509 op->ob_exports = 0;
510 return (PyObject *) op;
Guido van Rossum778983b1993-02-19 15:55:02 +0000511}
512
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000513static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000514getarrayitem(PyObject *op, Py_ssize_t i)
Guido van Rossum778983b1993-02-19 15:55:02 +0000515{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 register arrayobject *ap;
517 assert(array_Check(op));
518 ap = (arrayobject *)op;
519 assert(i>=0 && i<Py_SIZE(ap));
520 return (*ap->ob_descr->getitem)(ap, i);
Guido van Rossum778983b1993-02-19 15:55:02 +0000521}
522
523static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000524ins1(arrayobject *self, Py_ssize_t where, PyObject *v)
Guido van Rossum778983b1993-02-19 15:55:02 +0000525{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 char *items;
527 Py_ssize_t n = Py_SIZE(self);
528 if (v == NULL) {
529 PyErr_BadInternalCall();
530 return -1;
531 }
532 if ((*self->ob_descr->setitem)(self, -1, v) < 0)
533 return -1;
Raymond Hettinger6e2ee862004-03-14 04:37:50 +0000534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 if (array_resize(self, n+1) == -1)
536 return -1;
537 items = self->ob_item;
538 if (where < 0) {
539 where += n;
540 if (where < 0)
541 where = 0;
542 }
543 if (where > n)
544 where = n;
545 /* appends don't need to call memmove() */
546 if (where != n)
547 memmove(items + (where+1)*self->ob_descr->itemsize,
548 items + where*self->ob_descr->itemsize,
549 (n-where)*self->ob_descr->itemsize);
550 return (*self->ob_descr->setitem)(self, where, v);
Guido van Rossum778983b1993-02-19 15:55:02 +0000551}
552
Guido van Rossum778983b1993-02-19 15:55:02 +0000553/* Methods */
554
555static void
Peter Schneider-Kamp9656abd2000-07-13 21:10:57 +0000556array_dealloc(arrayobject *op)
Guido van Rossum778983b1993-02-19 15:55:02 +0000557{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000558 if (op->weakreflist != NULL)
559 PyObject_ClearWeakRefs((PyObject *) op);
560 if (op->ob_item != NULL)
561 PyMem_DEL(op->ob_item);
562 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossum778983b1993-02-19 15:55:02 +0000563}
564
Guido van Rossum9d19cb82001-01-18 01:02:55 +0000565static PyObject *
566array_richcompare(PyObject *v, PyObject *w, int op)
Guido van Rossum778983b1993-02-19 15:55:02 +0000567{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000568 arrayobject *va, *wa;
569 PyObject *vi = NULL;
570 PyObject *wi = NULL;
571 Py_ssize_t i, k;
572 PyObject *res;
Guido van Rossum9d19cb82001-01-18 01:02:55 +0000573
Brian Curtindfc80e32011-08-10 20:28:54 -0500574 if (!array_Check(v) || !array_Check(w))
575 Py_RETURN_NOTIMPLEMENTED;
Guido van Rossum9d19cb82001-01-18 01:02:55 +0000576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577 va = (arrayobject *)v;
578 wa = (arrayobject *)w;
Guido van Rossum9d19cb82001-01-18 01:02:55 +0000579
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000580 if (Py_SIZE(va) != Py_SIZE(wa) && (op == Py_EQ || op == Py_NE)) {
581 /* Shortcut: if the lengths differ, the arrays differ */
582 if (op == Py_EQ)
583 res = Py_False;
584 else
585 res = Py_True;
586 Py_INCREF(res);
587 return res;
588 }
Guido van Rossum9d19cb82001-01-18 01:02:55 +0000589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000590 /* Search for the first index where items are different */
591 k = 1;
592 for (i = 0; i < Py_SIZE(va) && i < Py_SIZE(wa); i++) {
593 vi = getarrayitem(v, i);
594 wi = getarrayitem(w, i);
595 if (vi == NULL || wi == NULL) {
596 Py_XDECREF(vi);
597 Py_XDECREF(wi);
598 return NULL;
599 }
600 k = PyObject_RichCompareBool(vi, wi, Py_EQ);
601 if (k == 0)
602 break; /* Keeping vi and wi alive! */
603 Py_DECREF(vi);
604 Py_DECREF(wi);
605 if (k < 0)
606 return NULL;
607 }
Guido van Rossum9d19cb82001-01-18 01:02:55 +0000608
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 if (k) {
610 /* No more items to compare -- compare sizes */
611 Py_ssize_t vs = Py_SIZE(va);
612 Py_ssize_t ws = Py_SIZE(wa);
613 int cmp;
614 switch (op) {
615 case Py_LT: cmp = vs < ws; break;
616 case Py_LE: cmp = vs <= ws; break;
617 case Py_EQ: cmp = vs == ws; break;
618 case Py_NE: cmp = vs != ws; break;
619 case Py_GT: cmp = vs > ws; break;
620 case Py_GE: cmp = vs >= ws; break;
621 default: return NULL; /* cannot happen */
622 }
623 if (cmp)
624 res = Py_True;
625 else
626 res = Py_False;
627 Py_INCREF(res);
628 return res;
629 }
Guido van Rossum9d19cb82001-01-18 01:02:55 +0000630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000631 /* We have an item that differs. First, shortcuts for EQ/NE */
632 if (op == Py_EQ) {
633 Py_INCREF(Py_False);
634 res = Py_False;
635 }
636 else if (op == Py_NE) {
637 Py_INCREF(Py_True);
638 res = Py_True;
639 }
640 else {
641 /* Compare the final item again using the proper operator */
642 res = PyObject_RichCompare(vi, wi, op);
643 }
644 Py_DECREF(vi);
645 Py_DECREF(wi);
646 return res;
Guido van Rossum778983b1993-02-19 15:55:02 +0000647}
648
Martin v. Löwis18e16552006-02-15 17:27:45 +0000649static Py_ssize_t
Peter Schneider-Kamp9656abd2000-07-13 21:10:57 +0000650array_length(arrayobject *a)
Guido van Rossum778983b1993-02-19 15:55:02 +0000651{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000652 return Py_SIZE(a);
Guido van Rossum778983b1993-02-19 15:55:02 +0000653}
654
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000655static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000656array_item(arrayobject *a, Py_ssize_t i)
Guido van Rossum778983b1993-02-19 15:55:02 +0000657{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000658 if (i < 0 || i >= Py_SIZE(a)) {
659 PyErr_SetString(PyExc_IndexError, "array index out of range");
660 return NULL;
661 }
662 return getarrayitem((PyObject *)a, i);
Guido van Rossum778983b1993-02-19 15:55:02 +0000663}
664
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000665static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000666array_slice(arrayobject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum778983b1993-02-19 15:55:02 +0000667{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 arrayobject *np;
669 if (ilow < 0)
670 ilow = 0;
671 else if (ilow > Py_SIZE(a))
672 ilow = Py_SIZE(a);
673 if (ihigh < 0)
674 ihigh = 0;
675 if (ihigh < ilow)
676 ihigh = ilow;
677 else if (ihigh > Py_SIZE(a))
678 ihigh = Py_SIZE(a);
679 np = (arrayobject *) newarrayobject(&Arraytype, ihigh - ilow, a->ob_descr);
680 if (np == NULL)
681 return NULL;
682 memcpy(np->ob_item, a->ob_item + ilow * a->ob_descr->itemsize,
683 (ihigh-ilow) * a->ob_descr->itemsize);
684 return (PyObject *)np;
Guido van Rossum778983b1993-02-19 15:55:02 +0000685}
686
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000687static PyObject *
Raymond Hettinger3aa82c02004-03-13 18:18:51 +0000688array_copy(arrayobject *a, PyObject *unused)
689{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000690 return array_slice(a, 0, Py_SIZE(a));
Raymond Hettinger3aa82c02004-03-13 18:18:51 +0000691}
692
693PyDoc_STRVAR(copy_doc,
694"copy(array)\n\
695\n\
696 Return a copy of the array.");
697
698static PyObject *
Peter Schneider-Kamp9656abd2000-07-13 21:10:57 +0000699array_concat(arrayobject *a, PyObject *bb)
Guido van Rossum778983b1993-02-19 15:55:02 +0000700{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000701 Py_ssize_t size;
702 arrayobject *np;
703 if (!array_Check(bb)) {
704 PyErr_Format(PyExc_TypeError,
705 "can only append array (not \"%.200s\") to array",
706 Py_TYPE(bb)->tp_name);
707 return NULL;
708 }
Guido van Rossum778983b1993-02-19 15:55:02 +0000709#define b ((arrayobject *)bb)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000710 if (a->ob_descr != b->ob_descr) {
711 PyErr_BadArgument();
712 return NULL;
713 }
714 if (Py_SIZE(a) > PY_SSIZE_T_MAX - Py_SIZE(b)) {
715 return PyErr_NoMemory();
716 }
717 size = Py_SIZE(a) + Py_SIZE(b);
718 np = (arrayobject *) newarrayobject(&Arraytype, size, a->ob_descr);
719 if (np == NULL) {
720 return NULL;
721 }
722 memcpy(np->ob_item, a->ob_item, Py_SIZE(a)*a->ob_descr->itemsize);
723 memcpy(np->ob_item + Py_SIZE(a)*a->ob_descr->itemsize,
724 b->ob_item, Py_SIZE(b)*b->ob_descr->itemsize);
725 return (PyObject *)np;
Guido van Rossum778983b1993-02-19 15:55:02 +0000726#undef b
727}
728
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000729static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000730array_repeat(arrayobject *a, Py_ssize_t n)
Guido van Rossum778983b1993-02-19 15:55:02 +0000731{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 Py_ssize_t size;
733 arrayobject *np;
Georg Brandlc29cc6a2010-12-04 11:02:04 +0000734 Py_ssize_t oldbytes, newbytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000735 if (n < 0)
736 n = 0;
737 if ((Py_SIZE(a) != 0) && (n > PY_SSIZE_T_MAX / Py_SIZE(a))) {
738 return PyErr_NoMemory();
739 }
740 size = Py_SIZE(a) * n;
741 np = (arrayobject *) newarrayobject(&Arraytype, size, a->ob_descr);
742 if (np == NULL)
743 return NULL;
Georg Brandlc29cc6a2010-12-04 11:02:04 +0000744 if (n == 0)
745 return (PyObject *)np;
746 oldbytes = Py_SIZE(a) * a->ob_descr->itemsize;
747 newbytes = oldbytes * n;
748 /* this follows the code in unicode_repeat */
749 if (oldbytes == 1) {
750 memset(np->ob_item, a->ob_item[0], newbytes);
751 } else {
752 Py_ssize_t done = oldbytes;
753 Py_MEMCPY(np->ob_item, a->ob_item, oldbytes);
754 while (done < newbytes) {
755 Py_ssize_t ncopy = (done <= newbytes-done) ? done : newbytes-done;
756 Py_MEMCPY(np->ob_item+done, np->ob_item, ncopy);
757 done += ncopy;
758 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000759 }
Georg Brandlc29cc6a2010-12-04 11:02:04 +0000760 return (PyObject *)np;
Guido van Rossum778983b1993-02-19 15:55:02 +0000761}
762
763static int
Martin v. Löwisad0a4622006-02-16 14:30:23 +0000764array_ass_slice(arrayobject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum778983b1993-02-19 15:55:02 +0000765{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000766 char *item;
767 Py_ssize_t n; /* Size of replacement array */
768 Py_ssize_t d; /* Change in size */
Guido van Rossum778983b1993-02-19 15:55:02 +0000769#define b ((arrayobject *)v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000770 if (v == NULL)
771 n = 0;
772 else if (array_Check(v)) {
773 n = Py_SIZE(b);
774 if (a == b) {
775 /* Special case "a[i:j] = a" -- copy b first */
776 int ret;
777 v = array_slice(b, 0, n);
778 if (!v)
779 return -1;
780 ret = array_ass_slice(a, ilow, ihigh, v);
781 Py_DECREF(v);
782 return ret;
783 }
784 if (b->ob_descr != a->ob_descr) {
785 PyErr_BadArgument();
786 return -1;
787 }
788 }
789 else {
790 PyErr_Format(PyExc_TypeError,
791 "can only assign array (not \"%.200s\") to array slice",
792 Py_TYPE(v)->tp_name);
793 return -1;
794 }
795 if (ilow < 0)
796 ilow = 0;
797 else if (ilow > Py_SIZE(a))
798 ilow = Py_SIZE(a);
799 if (ihigh < 0)
800 ihigh = 0;
801 if (ihigh < ilow)
802 ihigh = ilow;
803 else if (ihigh > Py_SIZE(a))
804 ihigh = Py_SIZE(a);
805 item = a->ob_item;
806 d = n - (ihigh-ilow);
807 /* Issue #4509: If the array has exported buffers and the slice
808 assignment would change the size of the array, fail early to make
809 sure we don't modify it. */
810 if (d != 0 && a->ob_exports > 0) {
811 PyErr_SetString(PyExc_BufferError,
812 "cannot resize an array that is exporting buffers");
813 return -1;
814 }
815 if (d < 0) { /* Delete -d items */
816 memmove(item + (ihigh+d)*a->ob_descr->itemsize,
817 item + ihigh*a->ob_descr->itemsize,
818 (Py_SIZE(a)-ihigh)*a->ob_descr->itemsize);
819 if (array_resize(a, Py_SIZE(a) + d) == -1)
820 return -1;
821 }
822 else if (d > 0) { /* Insert d items */
823 if (array_resize(a, Py_SIZE(a) + d))
824 return -1;
825 memmove(item + (ihigh+d)*a->ob_descr->itemsize,
826 item + ihigh*a->ob_descr->itemsize,
827 (Py_SIZE(a)-ihigh)*a->ob_descr->itemsize);
828 }
829 if (n > 0)
830 memcpy(item + ilow*a->ob_descr->itemsize, b->ob_item,
831 n*b->ob_descr->itemsize);
832 return 0;
Guido van Rossum778983b1993-02-19 15:55:02 +0000833#undef b
834}
835
836static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000837array_ass_item(arrayobject *a, Py_ssize_t i, PyObject *v)
Guido van Rossum778983b1993-02-19 15:55:02 +0000838{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 if (i < 0 || i >= Py_SIZE(a)) {
840 PyErr_SetString(PyExc_IndexError,
841 "array assignment index out of range");
842 return -1;
843 }
844 if (v == NULL)
845 return array_ass_slice(a, i, i+1, v);
846 return (*a->ob_descr->setitem)(a, i, v);
Guido van Rossum778983b1993-02-19 15:55:02 +0000847}
848
849static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000850setarrayitem(PyObject *a, Py_ssize_t i, PyObject *v)
Guido van Rossum778983b1993-02-19 15:55:02 +0000851{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000852 assert(array_Check(a));
853 return array_ass_item((arrayobject *)a, i, v);
Guido van Rossum778983b1993-02-19 15:55:02 +0000854}
855
Martin v. Löwis99866332002-03-01 10:27:01 +0000856static int
Raymond Hettinger49f9bd12004-03-14 05:43:59 +0000857array_iter_extend(arrayobject *self, PyObject *bb)
858{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 PyObject *it, *v;
Raymond Hettinger49f9bd12004-03-14 05:43:59 +0000860
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000861 it = PyObject_GetIter(bb);
862 if (it == NULL)
863 return -1;
Raymond Hettinger49f9bd12004-03-14 05:43:59 +0000864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000865 while ((v = PyIter_Next(it)) != NULL) {
Mark Dickinson346f0af2010-08-06 09:36:57 +0000866 if (ins1(self, Py_SIZE(self), v) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000867 Py_DECREF(v);
868 Py_DECREF(it);
869 return -1;
870 }
871 Py_DECREF(v);
872 }
873 Py_DECREF(it);
874 if (PyErr_Occurred())
875 return -1;
876 return 0;
Raymond Hettinger49f9bd12004-03-14 05:43:59 +0000877}
878
879static int
Martin v. Löwis99866332002-03-01 10:27:01 +0000880array_do_extend(arrayobject *self, PyObject *bb)
881{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 Py_ssize_t size, oldsize, bbsize;
Martin v. Löwis99866332002-03-01 10:27:01 +0000883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000884 if (!array_Check(bb))
885 return array_iter_extend(self, bb);
886#define b ((arrayobject *)bb)
887 if (self->ob_descr != b->ob_descr) {
888 PyErr_SetString(PyExc_TypeError,
889 "can only extend with array of same kind");
890 return -1;
891 }
892 if ((Py_SIZE(self) > PY_SSIZE_T_MAX - Py_SIZE(b)) ||
893 ((Py_SIZE(self) + Py_SIZE(b)) > PY_SSIZE_T_MAX / self->ob_descr->itemsize)) {
894 PyErr_NoMemory();
895 return -1;
896 }
897 oldsize = Py_SIZE(self);
898 /* Get the size of bb before resizing the array since bb could be self. */
899 bbsize = Py_SIZE(bb);
900 size = oldsize + Py_SIZE(b);
901 if (array_resize(self, size) == -1)
902 return -1;
903 memcpy(self->ob_item + oldsize * self->ob_descr->itemsize,
904 b->ob_item, bbsize * b->ob_descr->itemsize);
905
906 return 0;
Martin v. Löwis99866332002-03-01 10:27:01 +0000907#undef b
908}
909
910static PyObject *
911array_inplace_concat(arrayobject *self, PyObject *bb)
912{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 if (!array_Check(bb)) {
914 PyErr_Format(PyExc_TypeError,
915 "can only extend array with array (not \"%.200s\")",
916 Py_TYPE(bb)->tp_name);
917 return NULL;
918 }
919 if (array_do_extend(self, bb) == -1)
920 return NULL;
921 Py_INCREF(self);
922 return (PyObject *)self;
Martin v. Löwis99866332002-03-01 10:27:01 +0000923}
924
925static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000926array_inplace_repeat(arrayobject *self, Py_ssize_t n)
Martin v. Löwis99866332002-03-01 10:27:01 +0000927{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 char *items, *p;
929 Py_ssize_t size, i;
Martin v. Löwis99866332002-03-01 10:27:01 +0000930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 if (Py_SIZE(self) > 0) {
932 if (n < 0)
933 n = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 if ((self->ob_descr->itemsize != 0) &&
935 (Py_SIZE(self) > PY_SSIZE_T_MAX / self->ob_descr->itemsize)) {
936 return PyErr_NoMemory();
937 }
938 size = Py_SIZE(self) * self->ob_descr->itemsize;
939 if (n > 0 && size > PY_SSIZE_T_MAX / n) {
940 return PyErr_NoMemory();
941 }
942 if (array_resize(self, n * Py_SIZE(self)) == -1)
943 return NULL;
944 items = p = self->ob_item;
945 for (i = 1; i < n; i++) {
946 p += size;
947 memcpy(p, items, size);
948 }
949 }
950 Py_INCREF(self);
951 return (PyObject *)self;
Martin v. Löwis99866332002-03-01 10:27:01 +0000952}
953
954
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000955static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000956ins(arrayobject *self, Py_ssize_t where, PyObject *v)
Guido van Rossum778983b1993-02-19 15:55:02 +0000957{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000958 if (ins1(self, where, v) != 0)
959 return NULL;
960 Py_INCREF(Py_None);
961 return Py_None;
Guido van Rossum778983b1993-02-19 15:55:02 +0000962}
963
Roger E. Masse2919eaa1996-12-09 20:10:36 +0000964static PyObject *
Raymond Hettinger36cd2bf2003-01-03 08:24:58 +0000965array_count(arrayobject *self, PyObject *v)
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +0000966{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000967 Py_ssize_t count = 0;
968 Py_ssize_t i;
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +0000969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000970 for (i = 0; i < Py_SIZE(self); i++) {
971 PyObject *selfi = getarrayitem((PyObject *)self, i);
972 int cmp = PyObject_RichCompareBool(selfi, v, Py_EQ);
973 Py_DECREF(selfi);
974 if (cmp > 0)
975 count++;
976 else if (cmp < 0)
977 return NULL;
978 }
979 return PyLong_FromSsize_t(count);
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +0000980}
981
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000982PyDoc_STRVAR(count_doc,
Tim Peters077a11d2000-09-16 22:31:29 +0000983"count(x)\n\
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +0000984\n\
Mark Dickinson934896d2009-02-21 20:59:32 +0000985Return number of occurrences of x in the array.");
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +0000986
987static PyObject *
Raymond Hettinger36cd2bf2003-01-03 08:24:58 +0000988array_index(arrayobject *self, PyObject *v)
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +0000989{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000990 Py_ssize_t i;
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +0000991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992 for (i = 0; i < Py_SIZE(self); i++) {
993 PyObject *selfi = getarrayitem((PyObject *)self, i);
994 int cmp = PyObject_RichCompareBool(selfi, v, Py_EQ);
995 Py_DECREF(selfi);
996 if (cmp > 0) {
997 return PyLong_FromLong((long)i);
998 }
999 else if (cmp < 0)
1000 return NULL;
1001 }
1002 PyErr_SetString(PyExc_ValueError, "array.index(x): x not in list");
1003 return NULL;
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001004}
1005
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001006PyDoc_STRVAR(index_doc,
Tim Peters077a11d2000-09-16 22:31:29 +00001007"index(x)\n\
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001008\n\
Mark Dickinson934896d2009-02-21 20:59:32 +00001009Return index of first occurrence of x in the array.");
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001010
Raymond Hettinger625812f2003-01-07 01:58:52 +00001011static int
1012array_contains(arrayobject *self, PyObject *v)
1013{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 Py_ssize_t i;
1015 int cmp;
Raymond Hettinger625812f2003-01-07 01:58:52 +00001016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(self); i++) {
1018 PyObject *selfi = getarrayitem((PyObject *)self, i);
1019 cmp = PyObject_RichCompareBool(selfi, v, Py_EQ);
1020 Py_DECREF(selfi);
1021 }
1022 return cmp;
Raymond Hettinger625812f2003-01-07 01:58:52 +00001023}
1024
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001025static PyObject *
Raymond Hettinger36cd2bf2003-01-03 08:24:58 +00001026array_remove(arrayobject *self, PyObject *v)
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001027{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 int i;
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001030 for (i = 0; i < Py_SIZE(self); i++) {
1031 PyObject *selfi = getarrayitem((PyObject *)self,i);
1032 int cmp = PyObject_RichCompareBool(selfi, v, Py_EQ);
1033 Py_DECREF(selfi);
1034 if (cmp > 0) {
1035 if (array_ass_slice(self, i, i+1,
1036 (PyObject *)NULL) != 0)
1037 return NULL;
1038 Py_INCREF(Py_None);
1039 return Py_None;
1040 }
1041 else if (cmp < 0)
1042 return NULL;
1043 }
1044 PyErr_SetString(PyExc_ValueError, "array.remove(x): x not in list");
1045 return NULL;
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001046}
1047
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001048PyDoc_STRVAR(remove_doc,
Tim Peters077a11d2000-09-16 22:31:29 +00001049"remove(x)\n\
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001050\n\
Mark Dickinson934896d2009-02-21 20:59:32 +00001051Remove the first occurrence of x in the array.");
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001052
1053static PyObject *
1054array_pop(arrayobject *self, PyObject *args)
1055{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001056 Py_ssize_t i = -1;
1057 PyObject *v;
1058 if (!PyArg_ParseTuple(args, "|n:pop", &i))
1059 return NULL;
1060 if (Py_SIZE(self) == 0) {
1061 /* Special-case most common failure cause */
1062 PyErr_SetString(PyExc_IndexError, "pop from empty array");
1063 return NULL;
1064 }
1065 if (i < 0)
1066 i += Py_SIZE(self);
1067 if (i < 0 || i >= Py_SIZE(self)) {
1068 PyErr_SetString(PyExc_IndexError, "pop index out of range");
1069 return NULL;
1070 }
1071 v = getarrayitem((PyObject *)self,i);
1072 if (array_ass_slice(self, i, i+1, (PyObject *)NULL) != 0) {
1073 Py_DECREF(v);
1074 return NULL;
1075 }
1076 return v;
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001077}
1078
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001079PyDoc_STRVAR(pop_doc,
Tim Peters077a11d2000-09-16 22:31:29 +00001080"pop([i])\n\
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001081\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001082Return the i-th element and delete it from the array. i defaults to -1.");
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001083
1084static PyObject *
Raymond Hettinger36cd2bf2003-01-03 08:24:58 +00001085array_extend(arrayobject *self, PyObject *bb)
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001086{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001087 if (array_do_extend(self, bb) == -1)
1088 return NULL;
1089 Py_INCREF(Py_None);
1090 return Py_None;
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001091}
1092
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001093PyDoc_STRVAR(extend_doc,
Raymond Hettinger49f9bd12004-03-14 05:43:59 +00001094"extend(array or iterable)\n\
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001095\n\
Raymond Hettinger49f9bd12004-03-14 05:43:59 +00001096 Append items to the end of the array.");
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001097
1098static PyObject *
Peter Schneider-Kamp9656abd2000-07-13 21:10:57 +00001099array_insert(arrayobject *self, PyObject *args)
Guido van Rossum778983b1993-02-19 15:55:02 +00001100{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001101 Py_ssize_t i;
1102 PyObject *v;
1103 if (!PyArg_ParseTuple(args, "nO:insert", &i, &v))
1104 return NULL;
1105 return ins(self, i, v);
Guido van Rossum778983b1993-02-19 15:55:02 +00001106}
1107
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001108PyDoc_STRVAR(insert_doc,
Tim Peters077a11d2000-09-16 22:31:29 +00001109"insert(i,x)\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001110\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001111Insert a new item x into the array before position i.");
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001112
1113
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001114static PyObject *
Raymond Hettinger36cd2bf2003-01-03 08:24:58 +00001115array_buffer_info(arrayobject *self, PyObject *unused)
Guido van Rossumde4a4ca1997-08-12 14:55:56 +00001116{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001117 PyObject* retval = NULL;
1118 retval = PyTuple_New(2);
1119 if (!retval)
1120 return NULL;
Fred Drake541dc3b2000-06-28 17:49:30 +00001121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001122 PyTuple_SET_ITEM(retval, 0, PyLong_FromVoidPtr(self->ob_item));
1123 PyTuple_SET_ITEM(retval, 1, PyLong_FromLong((long)(Py_SIZE(self))));
Fred Drake541dc3b2000-06-28 17:49:30 +00001124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001125 return retval;
Guido van Rossumde4a4ca1997-08-12 14:55:56 +00001126}
1127
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001128PyDoc_STRVAR(buffer_info_doc,
Tim Peters077a11d2000-09-16 22:31:29 +00001129"buffer_info() -> (address, length)\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001130\n\
1131Return a tuple (address, length) giving the current memory address and\n\
Guido van Rossum702d08e2001-07-27 16:05:32 +00001132the length in items of the buffer used to hold array's contents\n\
1133The length should be multiplied by the itemsize attribute to calculate\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001134the buffer length in bytes.");
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001135
1136
Guido van Rossumde4a4ca1997-08-12 14:55:56 +00001137static PyObject *
Raymond Hettinger36cd2bf2003-01-03 08:24:58 +00001138array_append(arrayobject *self, PyObject *v)
Guido van Rossum778983b1993-02-19 15:55:02 +00001139{
Mark Dickinson346f0af2010-08-06 09:36:57 +00001140 return ins(self, Py_SIZE(self), v);
Guido van Rossum778983b1993-02-19 15:55:02 +00001141}
1142
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001143PyDoc_STRVAR(append_doc,
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001144"append(x)\n\
1145\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001146Append new value x to the end of the array.");
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001147
1148
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001149static PyObject *
Raymond Hettinger36cd2bf2003-01-03 08:24:58 +00001150array_byteswap(arrayobject *self, PyObject *unused)
Guido van Rossum778983b1993-02-19 15:55:02 +00001151{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001152 char *p;
1153 Py_ssize_t i;
Fred Drakebf272981999-12-03 17:15:30 +00001154
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001155 switch (self->ob_descr->itemsize) {
1156 case 1:
1157 break;
1158 case 2:
1159 for (p = self->ob_item, i = Py_SIZE(self); --i >= 0; p += 2) {
1160 char p0 = p[0];
1161 p[0] = p[1];
1162 p[1] = p0;
1163 }
1164 break;
1165 case 4:
1166 for (p = self->ob_item, i = Py_SIZE(self); --i >= 0; p += 4) {
1167 char p0 = p[0];
1168 char p1 = p[1];
1169 p[0] = p[3];
1170 p[1] = p[2];
1171 p[2] = p1;
1172 p[3] = p0;
1173 }
1174 break;
1175 case 8:
1176 for (p = self->ob_item, i = Py_SIZE(self); --i >= 0; p += 8) {
1177 char p0 = p[0];
1178 char p1 = p[1];
1179 char p2 = p[2];
1180 char p3 = p[3];
1181 p[0] = p[7];
1182 p[1] = p[6];
1183 p[2] = p[5];
1184 p[3] = p[4];
1185 p[4] = p3;
1186 p[5] = p2;
1187 p[6] = p1;
1188 p[7] = p0;
1189 }
1190 break;
1191 default:
1192 PyErr_SetString(PyExc_RuntimeError,
1193 "don't know how to byteswap this array type");
1194 return NULL;
1195 }
1196 Py_INCREF(Py_None);
1197 return Py_None;
Guido van Rossum778983b1993-02-19 15:55:02 +00001198}
1199
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001200PyDoc_STRVAR(byteswap_doc,
Fred Drakebf272981999-12-03 17:15:30 +00001201"byteswap()\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001202\n\
Fred Drakebf272981999-12-03 17:15:30 +00001203Byteswap 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 +000012044, or 8 bytes in size, RuntimeError is raised.");
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001205
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001206static PyObject *
Raymond Hettinger36cd2bf2003-01-03 08:24:58 +00001207array_reverse(arrayobject *self, PyObject *unused)
Guido van Rossum778983b1993-02-19 15:55:02 +00001208{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 register Py_ssize_t itemsize = self->ob_descr->itemsize;
1210 register char *p, *q;
1211 /* little buffer to hold items while swapping */
1212 char tmp[256]; /* 8 is probably enough -- but why skimp */
1213 assert((size_t)itemsize <= sizeof(tmp));
Guido van Rossume77a7571993-11-03 15:01:26 +00001214
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001215 if (Py_SIZE(self) > 1) {
1216 for (p = self->ob_item,
1217 q = self->ob_item + (Py_SIZE(self) - 1)*itemsize;
1218 p < q;
1219 p += itemsize, q -= itemsize) {
1220 /* memory areas guaranteed disjoint, so memcpy
1221 * is safe (& memmove may be slower).
1222 */
1223 memcpy(tmp, p, itemsize);
1224 memcpy(p, q, itemsize);
1225 memcpy(q, tmp, itemsize);
1226 }
1227 }
Tim Petersbb307342000-09-10 05:22:54 +00001228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 Py_INCREF(Py_None);
1230 return Py_None;
Guido van Rossum778983b1993-02-19 15:55:02 +00001231}
Guido van Rossume77a7571993-11-03 15:01:26 +00001232
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001233PyDoc_STRVAR(reverse_doc,
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001234"reverse()\n\
1235\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001236Reverse the order of the items in the array.");
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001237
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001238
1239/* Forward */
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001240static PyObject *array_frombytes(arrayobject *self, PyObject *args);
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001241
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001242static PyObject *
Peter Schneider-Kamp9656abd2000-07-13 21:10:57 +00001243array_fromfile(arrayobject *self, PyObject *args)
Guido van Rossum778983b1993-02-19 15:55:02 +00001244{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001245 PyObject *f, *b, *res;
1246 Py_ssize_t itemsize = self->ob_descr->itemsize;
1247 Py_ssize_t n, nbytes;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001248 _Py_IDENTIFIER(read);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001249 int not_enough_bytes;
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001251 if (!PyArg_ParseTuple(args, "On:fromfile", &f, &n))
1252 return NULL;
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001254 nbytes = n * itemsize;
1255 if (nbytes < 0 || nbytes/itemsize != n) {
1256 PyErr_NoMemory();
1257 return NULL;
1258 }
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001259
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001260 b = _PyObject_CallMethodId(f, &PyId_read, "n", nbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001261 if (b == NULL)
1262 return NULL;
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001264 if (!PyBytes_Check(b)) {
1265 PyErr_SetString(PyExc_TypeError,
1266 "read() didn't return bytes");
1267 Py_DECREF(b);
1268 return NULL;
1269 }
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001271 not_enough_bytes = (PyBytes_GET_SIZE(b) != nbytes);
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001273 args = Py_BuildValue("(O)", b);
1274 Py_DECREF(b);
1275 if (args == NULL)
1276 return NULL;
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001277
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001278 res = array_frombytes(self, args);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001279 Py_DECREF(args);
1280 if (res == NULL)
1281 return NULL;
Hirokazu Yamamoto54d0df62009-03-06 03:04:07 +00001282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001283 if (not_enough_bytes) {
1284 PyErr_SetString(PyExc_EOFError,
1285 "read() didn't return enough bytes");
1286 Py_DECREF(res);
1287 return NULL;
1288 }
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001290 return res;
Guido van Rossum778983b1993-02-19 15:55:02 +00001291}
1292
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001293PyDoc_STRVAR(fromfile_doc,
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001294"fromfile(f, n)\n\
1295\n\
1296Read n objects from the file object f and append them to the end of the\n\
Georg Brandlf25ef502008-02-01 11:30:18 +00001297array.");
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001298
1299
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001300static PyObject *
Raymond Hettinger36cd2bf2003-01-03 08:24:58 +00001301array_tofile(arrayobject *self, PyObject *f)
Guido van Rossum778983b1993-02-19 15:55:02 +00001302{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001303 Py_ssize_t nbytes = Py_SIZE(self) * self->ob_descr->itemsize;
1304 /* Write 64K blocks at a time */
1305 /* XXX Make the block size settable */
1306 int BLOCKSIZE = 64*1024;
1307 Py_ssize_t nblocks = (nbytes + BLOCKSIZE - 1) / BLOCKSIZE;
1308 Py_ssize_t i;
Raymond Hettinger36cd2bf2003-01-03 08:24:58 +00001309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001310 if (Py_SIZE(self) == 0)
1311 goto done;
Guido van Rossumb5ddcfd2007-04-11 17:08:28 +00001312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001313 for (i = 0; i < nblocks; i++) {
1314 char* ptr = self->ob_item + i*BLOCKSIZE;
1315 Py_ssize_t size = BLOCKSIZE;
1316 PyObject *bytes, *res;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001317 _Py_IDENTIFIER(write);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001318
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001319 if (i*BLOCKSIZE + size > nbytes)
1320 size = nbytes - i*BLOCKSIZE;
1321 bytes = PyBytes_FromStringAndSize(ptr, size);
1322 if (bytes == NULL)
1323 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001324 res = _PyObject_CallMethodId(f, &PyId_write, "O", bytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001325 Py_DECREF(bytes);
1326 if (res == NULL)
1327 return NULL;
1328 Py_DECREF(res); /* drop write result */
1329 }
Guido van Rossumb5ddcfd2007-04-11 17:08:28 +00001330
1331 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001332 Py_INCREF(Py_None);
1333 return Py_None;
Guido van Rossum778983b1993-02-19 15:55:02 +00001334}
1335
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001336PyDoc_STRVAR(tofile_doc,
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001337"tofile(f)\n\
1338\n\
Georg Brandlf25ef502008-02-01 11:30:18 +00001339Write all items (as machine values) to the file object f.");
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001340
1341
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001342static PyObject *
Raymond Hettinger36cd2bf2003-01-03 08:24:58 +00001343array_fromlist(arrayobject *self, PyObject *list)
Guido van Rossum778983b1993-02-19 15:55:02 +00001344{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001345 Py_ssize_t n;
Raymond Hettinger36cd2bf2003-01-03 08:24:58 +00001346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001347 if (!PyList_Check(list)) {
1348 PyErr_SetString(PyExc_TypeError, "arg must be list");
1349 return NULL;
1350 }
1351 n = PyList_Size(list);
1352 if (n > 0) {
1353 Py_ssize_t i, old_size;
1354 old_size = Py_SIZE(self);
1355 if (array_resize(self, old_size + n) == -1)
1356 return NULL;
1357 for (i = 0; i < n; i++) {
1358 PyObject *v = PyList_GetItem(list, i);
1359 if ((*self->ob_descr->setitem)(self,
1360 Py_SIZE(self) - n + i, v) != 0) {
1361 array_resize(self, old_size);
1362 return NULL;
1363 }
1364 }
1365 }
1366 Py_INCREF(Py_None);
1367 return Py_None;
Guido van Rossum778983b1993-02-19 15:55:02 +00001368}
1369
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001370PyDoc_STRVAR(fromlist_doc,
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001371"fromlist(list)\n\
1372\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001373Append items to array from list.");
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001374
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001375static PyObject *
Raymond Hettinger36cd2bf2003-01-03 08:24:58 +00001376array_tolist(arrayobject *self, PyObject *unused)
Guido van Rossum778983b1993-02-19 15:55:02 +00001377{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001378 PyObject *list = PyList_New(Py_SIZE(self));
1379 Py_ssize_t i;
Raymond Hettinger36cd2bf2003-01-03 08:24:58 +00001380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001381 if (list == NULL)
1382 return NULL;
1383 for (i = 0; i < Py_SIZE(self); i++) {
1384 PyObject *v = getarrayitem((PyObject *)self, i);
1385 if (v == NULL) {
1386 Py_DECREF(list);
1387 return NULL;
1388 }
1389 PyList_SetItem(list, i, v);
1390 }
1391 return list;
Guido van Rossum778983b1993-02-19 15:55:02 +00001392}
1393
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001394PyDoc_STRVAR(tolist_doc,
Guido van Rossumfc6aba51998-10-14 02:52:31 +00001395"tolist() -> list\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001396\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001397Convert array to an ordinary list with the same items.");
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001398
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001399static PyObject *
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001400frombytes(arrayobject *self, Py_buffer *buffer)
Guido van Rossum778983b1993-02-19 15:55:02 +00001401{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001402 int itemsize = self->ob_descr->itemsize;
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001403 Py_ssize_t n;
1404 if (buffer->itemsize != 1) {
1405 PyBuffer_Release(buffer);
1406 PyErr_SetString(PyExc_TypeError, "string/buffer of bytes required.");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001407 return NULL;
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001408 }
1409 n = buffer->len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 if (n % itemsize != 0) {
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001411 PyBuffer_Release(buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001412 PyErr_SetString(PyExc_ValueError,
1413 "string length not a multiple of item size");
1414 return NULL;
1415 }
1416 n = n / itemsize;
1417 if (n > 0) {
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001418 Py_ssize_t old_size = Py_SIZE(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001419 if ((n > PY_SSIZE_T_MAX - old_size) ||
1420 ((old_size + n) > PY_SSIZE_T_MAX / itemsize)) {
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001421 PyBuffer_Release(buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001422 return PyErr_NoMemory();
1423 }
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001424 if (array_resize(self, old_size + n) == -1) {
1425 PyBuffer_Release(buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001426 return NULL;
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001427 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001428 memcpy(self->ob_item + old_size * itemsize,
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001429 buffer->buf, n * itemsize);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001430 }
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001431 PyBuffer_Release(buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001432 Py_INCREF(Py_None);
1433 return Py_None;
Guido van Rossum778983b1993-02-19 15:55:02 +00001434}
1435
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001436static PyObject *
1437array_fromstring(arrayobject *self, PyObject *args)
1438{
1439 Py_buffer buffer;
1440 if (PyErr_WarnEx(PyExc_DeprecationWarning,
1441 "fromstring() is deprecated. Use frombytes() instead.", 2) != 0)
1442 return NULL;
1443 if (!PyArg_ParseTuple(args, "s*:fromstring", &buffer))
1444 return NULL;
1445 else
1446 return frombytes(self, &buffer);
1447}
1448
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001449PyDoc_STRVAR(fromstring_doc,
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001450"fromstring(string)\n\
1451\n\
1452Appends items from the string, interpreting it as an array of machine\n\
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001453values, as if it had been read from a file using the fromfile() method).\n\
1454\n\
1455This method is deprecated. Use frombytes instead.");
1456
1457
1458static PyObject *
1459array_frombytes(arrayobject *self, PyObject *args)
1460{
1461 Py_buffer buffer;
1462 if (!PyArg_ParseTuple(args, "y*:frombytes", &buffer))
1463 return NULL;
1464 else
1465 return frombytes(self, &buffer);
1466}
1467
1468PyDoc_STRVAR(frombytes_doc,
1469"frombytes(bytestring)\n\
1470\n\
1471Appends items from the string, interpreting it as an array of machine\n\
Walter Dörwald93b30b52007-06-22 12:21:53 +00001472values, as if it had been read from a file using the fromfile() method).");
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001473
1474
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001475static PyObject *
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001476array_tobytes(arrayobject *self, PyObject *unused)
Guido van Rossum778983b1993-02-19 15:55:02 +00001477{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001478 if (Py_SIZE(self) <= PY_SSIZE_T_MAX / self->ob_descr->itemsize) {
1479 return PyBytes_FromStringAndSize(self->ob_item,
1480 Py_SIZE(self) * self->ob_descr->itemsize);
1481 } else {
1482 return PyErr_NoMemory();
1483 }
Guido van Rossum778983b1993-02-19 15:55:02 +00001484}
1485
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001486PyDoc_STRVAR(tobytes_doc,
1487"tobytes() -> bytes\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001488\n\
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001489Convert the array to an array of machine values and return the bytes\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001490representation.");
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001491
Martin v. Löwis99866332002-03-01 10:27:01 +00001492
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001493static PyObject *
1494array_tostring(arrayobject *self, PyObject *unused)
1495{
Victor Stinner9f0b51e2010-11-09 09:38:30 +00001496 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001497 "tostring() is deprecated. Use tobytes() instead.", 2) != 0)
1498 return NULL;
1499 return array_tobytes(self, unused);
1500}
1501
1502PyDoc_STRVAR(tostring_doc,
1503"tostring() -> bytes\n\
1504\n\
1505Convert the array to an array of machine values and return the bytes\n\
1506representation.\n\
1507\n\
1508This method is deprecated. Use tobytes instead.");
1509
Martin v. Löwis99866332002-03-01 10:27:01 +00001510
Martin v. Löwis99866332002-03-01 10:27:01 +00001511static PyObject *
1512array_fromunicode(arrayobject *self, PyObject *args)
1513{
Victor Stinner62bb3942012-08-06 00:46:05 +02001514 Py_UNICODE *ustr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001515 Py_ssize_t n;
Victor Stinner62bb3942012-08-06 00:46:05 +02001516 char typecode;
Martin v. Löwis99866332002-03-01 10:27:01 +00001517
Victor Stinner62bb3942012-08-06 00:46:05 +02001518 if (!PyArg_ParseTuple(args, "u#:fromunicode", &ustr, &n))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001519 return NULL;
Victor Stinner62bb3942012-08-06 00:46:05 +02001520 typecode = self->ob_descr->typecode;
1521 if ((typecode != 'u')) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001522 PyErr_SetString(PyExc_ValueError,
1523 "fromunicode() may only be called on "
1524 "unicode type arrays");
1525 return NULL;
1526 }
1527 if (n > 0) {
1528 Py_ssize_t old_size = Py_SIZE(self);
1529 if (array_resize(self, old_size + n) == -1)
1530 return NULL;
Victor Stinner62bb3942012-08-06 00:46:05 +02001531 memcpy(self->ob_item + old_size * sizeof(Py_UNICODE),
1532 ustr, n * sizeof(Py_UNICODE));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001533 }
Martin v. Löwis99866332002-03-01 10:27:01 +00001534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001535 Py_INCREF(Py_None);
1536 return Py_None;
Martin v. Löwis99866332002-03-01 10:27:01 +00001537}
1538
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001539PyDoc_STRVAR(fromunicode_doc,
Martin v. Löwis99866332002-03-01 10:27:01 +00001540"fromunicode(ustr)\n\
1541\n\
1542Extends this array with data from the unicode string ustr.\n\
Travis E. Oliphantb99f7622007-08-18 11:21:56 +00001543The array must be a unicode type array; otherwise a ValueError\n\
Florent Xiclunac45fb252011-10-24 13:14:55 +02001544is raised. Use array.frombytes(ustr.encode(...)) to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001545append Unicode data to an array of some other type.");
Martin v. Löwis99866332002-03-01 10:27:01 +00001546
1547
1548static PyObject *
Raymond Hettinger36cd2bf2003-01-03 08:24:58 +00001549array_tounicode(arrayobject *self, PyObject *unused)
Martin v. Löwis99866332002-03-01 10:27:01 +00001550{
Victor Stinner62bb3942012-08-06 00:46:05 +02001551 char typecode;
1552 typecode = self->ob_descr->typecode;
1553 if ((typecode != 'u')) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001554 PyErr_SetString(PyExc_ValueError,
1555 "tounicode() may only be called on unicode type arrays");
1556 return NULL;
1557 }
Victor Stinner62bb3942012-08-06 00:46:05 +02001558 return PyUnicode_FromUnicode((Py_UNICODE *) self->ob_item, Py_SIZE(self));
Martin v. Löwis99866332002-03-01 10:27:01 +00001559}
1560
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001561PyDoc_STRVAR(tounicode_doc,
Martin v. Löwis99866332002-03-01 10:27:01 +00001562"tounicode() -> unicode\n\
1563\n\
1564Convert the array to a unicode string. The array must be\n\
Travis E. Oliphantb99f7622007-08-18 11:21:56 +00001565a unicode type array; otherwise a ValueError is raised. Use\n\
Florent Xiclunac45fb252011-10-24 13:14:55 +02001566array.tobytes().decode() to obtain a unicode string from\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001567an array of some other type.");
Martin v. Löwis99866332002-03-01 10:27:01 +00001568
Martin v. Löwis99866332002-03-01 10:27:01 +00001569
1570
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001571/*********************** Pickling support ************************/
1572
1573enum machine_format_code {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001574 UNKNOWN_FORMAT = -1,
1575 /* UNKNOWN_FORMAT is used to indicate that the machine format for an
1576 * array type code cannot be interpreted. When this occurs, a list of
1577 * Python objects is used to represent the content of the array
1578 * instead of using the memory content of the array directly. In that
1579 * case, the array_reconstructor mechanism is bypassed completely, and
1580 * the standard array constructor is used instead.
1581 *
1582 * This is will most likely occur when the machine doesn't use IEEE
1583 * floating-point numbers.
1584 */
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001586 UNSIGNED_INT8 = 0,
1587 SIGNED_INT8 = 1,
1588 UNSIGNED_INT16_LE = 2,
1589 UNSIGNED_INT16_BE = 3,
1590 SIGNED_INT16_LE = 4,
1591 SIGNED_INT16_BE = 5,
1592 UNSIGNED_INT32_LE = 6,
1593 UNSIGNED_INT32_BE = 7,
1594 SIGNED_INT32_LE = 8,
1595 SIGNED_INT32_BE = 9,
1596 UNSIGNED_INT64_LE = 10,
1597 UNSIGNED_INT64_BE = 11,
1598 SIGNED_INT64_LE = 12,
1599 SIGNED_INT64_BE = 13,
1600 IEEE_754_FLOAT_LE = 14,
1601 IEEE_754_FLOAT_BE = 15,
1602 IEEE_754_DOUBLE_LE = 16,
1603 IEEE_754_DOUBLE_BE = 17,
1604 UTF16_LE = 18,
1605 UTF16_BE = 19,
1606 UTF32_LE = 20,
1607 UTF32_BE = 21
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001608};
1609#define MACHINE_FORMAT_CODE_MIN 0
1610#define MACHINE_FORMAT_CODE_MAX 21
1611
1612static const struct mformatdescr {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001613 size_t size;
1614 int is_signed;
1615 int is_big_endian;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001616} mformat_descriptors[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001617 {1, 0, 0}, /* 0: UNSIGNED_INT8 */
1618 {1, 1, 0}, /* 1: SIGNED_INT8 */
1619 {2, 0, 0}, /* 2: UNSIGNED_INT16_LE */
1620 {2, 0, 1}, /* 3: UNSIGNED_INT16_BE */
1621 {2, 1, 0}, /* 4: SIGNED_INT16_LE */
1622 {2, 1, 1}, /* 5: SIGNED_INT16_BE */
1623 {4, 0, 0}, /* 6: UNSIGNED_INT32_LE */
1624 {4, 0, 1}, /* 7: UNSIGNED_INT32_BE */
1625 {4, 1, 0}, /* 8: SIGNED_INT32_LE */
1626 {4, 1, 1}, /* 9: SIGNED_INT32_BE */
1627 {8, 0, 0}, /* 10: UNSIGNED_INT64_LE */
1628 {8, 0, 1}, /* 11: UNSIGNED_INT64_BE */
1629 {8, 1, 0}, /* 12: SIGNED_INT64_LE */
1630 {8, 1, 1}, /* 13: SIGNED_INT64_BE */
1631 {4, 0, 0}, /* 14: IEEE_754_FLOAT_LE */
1632 {4, 0, 1}, /* 15: IEEE_754_FLOAT_BE */
1633 {8, 0, 0}, /* 16: IEEE_754_DOUBLE_LE */
1634 {8, 0, 1}, /* 17: IEEE_754_DOUBLE_BE */
1635 {4, 0, 0}, /* 18: UTF16_LE */
1636 {4, 0, 1}, /* 19: UTF16_BE */
1637 {8, 0, 0}, /* 20: UTF32_LE */
1638 {8, 0, 1} /* 21: UTF32_BE */
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001639};
1640
1641
1642/*
1643 * Internal: This function is used to find the machine format of a given
1644 * array type code. This returns UNKNOWN_FORMAT when the machine format cannot
1645 * be found.
1646 */
1647static enum machine_format_code
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02001648typecode_to_mformat_code(char typecode)
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001649{
Alexandre Vassalotti7aaa7702009-07-17 03:51:27 +00001650#ifdef WORDS_BIGENDIAN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001651 const int is_big_endian = 1;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001652#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001653 const int is_big_endian = 0;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001654#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001655 size_t intsize;
1656 int is_signed;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001657
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001658 switch (typecode) {
1659 case 'b':
1660 return SIGNED_INT8;
1661 case 'B':
1662 return UNSIGNED_INT8;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001663
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001664 case 'u':
Victor Stinner62bb3942012-08-06 00:46:05 +02001665 if (sizeof(Py_UNICODE) == 2) {
1666 return UTF16_LE + is_big_endian;
1667 }
1668 if (sizeof(Py_UNICODE) == 4) {
1669 return UTF32_LE + is_big_endian;
1670 }
1671 return UNKNOWN_FORMAT;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001672
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001673 case 'f':
1674 if (sizeof(float) == 4) {
1675 const float y = 16711938.0;
1676 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1677 return IEEE_754_FLOAT_BE;
1678 if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1679 return IEEE_754_FLOAT_LE;
1680 }
1681 return UNKNOWN_FORMAT;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001682
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001683 case 'd':
1684 if (sizeof(double) == 8) {
1685 const double x = 9006104071832581.0;
1686 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1687 return IEEE_754_DOUBLE_BE;
1688 if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1689 return IEEE_754_DOUBLE_LE;
1690 }
1691 return UNKNOWN_FORMAT;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001692
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001693 /* Integers */
1694 case 'h':
1695 intsize = sizeof(short);
1696 is_signed = 1;
1697 break;
1698 case 'H':
1699 intsize = sizeof(short);
1700 is_signed = 0;
1701 break;
1702 case 'i':
1703 intsize = sizeof(int);
1704 is_signed = 1;
1705 break;
1706 case 'I':
1707 intsize = sizeof(int);
1708 is_signed = 0;
1709 break;
1710 case 'l':
1711 intsize = sizeof(long);
1712 is_signed = 1;
1713 break;
1714 case 'L':
1715 intsize = sizeof(long);
1716 is_signed = 0;
1717 break;
Meador Inge1c9f0c92011-09-20 19:55:51 -05001718#if HAVE_LONG_LONG
1719 case 'q':
1720 intsize = sizeof(PY_LONG_LONG);
1721 is_signed = 1;
1722 break;
1723 case 'Q':
1724 intsize = sizeof(PY_LONG_LONG);
1725 is_signed = 0;
1726 break;
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02001727#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001728 default:
1729 return UNKNOWN_FORMAT;
1730 }
1731 switch (intsize) {
1732 case 2:
1733 return UNSIGNED_INT16_LE + is_big_endian + (2 * is_signed);
1734 case 4:
1735 return UNSIGNED_INT32_LE + is_big_endian + (2 * is_signed);
1736 case 8:
1737 return UNSIGNED_INT64_LE + is_big_endian + (2 * is_signed);
1738 default:
1739 return UNKNOWN_FORMAT;
1740 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001741}
1742
1743/* Forward declaration. */
1744static PyObject *array_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1745
1746/*
1747 * Internal: This function wraps the array constructor--i.e., array_new()--to
1748 * allow the creation of array objects from C code without having to deal
1749 * directly the tuple argument of array_new(). The typecode argument is a
1750 * Unicode character value, like 'i' or 'f' for example, representing an array
1751 * type code. The items argument is a bytes or a list object from which
1752 * contains the initial value of the array.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001753 *
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001754 * On success, this functions returns the array object created. Otherwise,
1755 * NULL is returned to indicate a failure.
1756 */
1757static PyObject *
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02001758make_array(PyTypeObject *arraytype, char typecode, PyObject *items)
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001759{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001760 PyObject *new_args;
1761 PyObject *array_obj;
1762 PyObject *typecode_obj;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001763
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001764 assert(arraytype != NULL);
1765 assert(items != NULL);
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001766
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02001767 typecode_obj = PyUnicode_FromOrdinal(typecode);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001768 if (typecode_obj == NULL)
1769 return NULL;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001771 new_args = PyTuple_New(2);
1772 if (new_args == NULL)
1773 return NULL;
1774 Py_INCREF(items);
1775 PyTuple_SET_ITEM(new_args, 0, typecode_obj);
1776 PyTuple_SET_ITEM(new_args, 1, items);
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001777
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001778 array_obj = array_new(arraytype, new_args, NULL);
1779 Py_DECREF(new_args);
1780 if (array_obj == NULL)
1781 return NULL;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001783 return array_obj;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001784}
1785
1786/*
1787 * This functions is a special constructor used when unpickling an array. It
1788 * provides a portable way to rebuild an array from its memory representation.
1789 */
1790static PyObject *
1791array_reconstructor(PyObject *self, PyObject *args)
1792{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001793 PyTypeObject *arraytype;
1794 PyObject *items;
1795 PyObject *converted_items;
1796 PyObject *result;
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02001797 int typecode;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001798 enum machine_format_code mformat_code;
1799 struct arraydescr *descr;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001800
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001801 if (!PyArg_ParseTuple(args, "OCiO:array._array_reconstructor",
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02001802 &arraytype, &typecode, &mformat_code, &items))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001803 return NULL;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001804
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001805 if (!PyType_Check(arraytype)) {
1806 PyErr_Format(PyExc_TypeError,
1807 "first argument must a type object, not %.200s",
1808 Py_TYPE(arraytype)->tp_name);
1809 return NULL;
1810 }
1811 if (!PyType_IsSubtype(arraytype, &Arraytype)) {
1812 PyErr_Format(PyExc_TypeError,
1813 "%.200s is not a subtype of %.200s",
1814 arraytype->tp_name, Arraytype.tp_name);
1815 return NULL;
1816 }
1817 for (descr = descriptors; descr->typecode != '\0'; descr++) {
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02001818 if ((int)descr->typecode == typecode)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001819 break;
1820 }
1821 if (descr->typecode == '\0') {
1822 PyErr_SetString(PyExc_ValueError,
1823 "second argument must be a valid type code");
1824 return NULL;
1825 }
1826 if (mformat_code < MACHINE_FORMAT_CODE_MIN ||
1827 mformat_code > MACHINE_FORMAT_CODE_MAX) {
1828 PyErr_SetString(PyExc_ValueError,
1829 "third argument must be a valid machine format code.");
1830 return NULL;
1831 }
1832 if (!PyBytes_Check(items)) {
1833 PyErr_Format(PyExc_TypeError,
1834 "fourth argument should be bytes, not %.200s",
1835 Py_TYPE(items)->tp_name);
1836 return NULL;
1837 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001838
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001839 /* Fast path: No decoding has to be done. */
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02001840 if (mformat_code == typecode_to_mformat_code((char)typecode) ||
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001841 mformat_code == UNKNOWN_FORMAT) {
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02001842 return make_array(arraytype, (char)typecode, items);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001843 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001844
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001845 /* Slow path: Decode the byte string according to the given machine
1846 * format code. This occurs when the computer unpickling the array
1847 * object is architecturally different from the one that pickled the
1848 * array.
1849 */
1850 if (Py_SIZE(items) % mformat_descriptors[mformat_code].size != 0) {
1851 PyErr_SetString(PyExc_ValueError,
1852 "string length not a multiple of item size");
1853 return NULL;
1854 }
1855 switch (mformat_code) {
1856 case IEEE_754_FLOAT_LE:
1857 case IEEE_754_FLOAT_BE: {
1858 int i;
1859 int le = (mformat_code == IEEE_754_FLOAT_LE) ? 1 : 0;
1860 Py_ssize_t itemcount = Py_SIZE(items) / 4;
1861 const unsigned char *memstr =
1862 (unsigned char *)PyBytes_AS_STRING(items);
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001864 converted_items = PyList_New(itemcount);
1865 if (converted_items == NULL)
1866 return NULL;
1867 for (i = 0; i < itemcount; i++) {
1868 PyObject *pyfloat = PyFloat_FromDouble(
1869 _PyFloat_Unpack4(&memstr[i * 4], le));
1870 if (pyfloat == NULL) {
1871 Py_DECREF(converted_items);
1872 return NULL;
1873 }
1874 PyList_SET_ITEM(converted_items, i, pyfloat);
1875 }
1876 break;
1877 }
1878 case IEEE_754_DOUBLE_LE:
1879 case IEEE_754_DOUBLE_BE: {
1880 int i;
1881 int le = (mformat_code == IEEE_754_DOUBLE_LE) ? 1 : 0;
1882 Py_ssize_t itemcount = Py_SIZE(items) / 8;
1883 const unsigned char *memstr =
1884 (unsigned char *)PyBytes_AS_STRING(items);
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001886 converted_items = PyList_New(itemcount);
1887 if (converted_items == NULL)
1888 return NULL;
1889 for (i = 0; i < itemcount; i++) {
1890 PyObject *pyfloat = PyFloat_FromDouble(
1891 _PyFloat_Unpack8(&memstr[i * 8], le));
1892 if (pyfloat == NULL) {
1893 Py_DECREF(converted_items);
1894 return NULL;
1895 }
1896 PyList_SET_ITEM(converted_items, i, pyfloat);
1897 }
1898 break;
1899 }
1900 case UTF16_LE:
1901 case UTF16_BE: {
1902 int byteorder = (mformat_code == UTF16_LE) ? -1 : 1;
1903 converted_items = PyUnicode_DecodeUTF16(
1904 PyBytes_AS_STRING(items), Py_SIZE(items),
1905 "strict", &byteorder);
1906 if (converted_items == NULL)
1907 return NULL;
1908 break;
1909 }
1910 case UTF32_LE:
1911 case UTF32_BE: {
1912 int byteorder = (mformat_code == UTF32_LE) ? -1 : 1;
1913 converted_items = PyUnicode_DecodeUTF32(
1914 PyBytes_AS_STRING(items), Py_SIZE(items),
1915 "strict", &byteorder);
1916 if (converted_items == NULL)
1917 return NULL;
1918 break;
1919 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001921 case UNSIGNED_INT8:
1922 case SIGNED_INT8:
1923 case UNSIGNED_INT16_LE:
1924 case UNSIGNED_INT16_BE:
1925 case SIGNED_INT16_LE:
1926 case SIGNED_INT16_BE:
1927 case UNSIGNED_INT32_LE:
1928 case UNSIGNED_INT32_BE:
1929 case SIGNED_INT32_LE:
1930 case SIGNED_INT32_BE:
1931 case UNSIGNED_INT64_LE:
1932 case UNSIGNED_INT64_BE:
1933 case SIGNED_INT64_LE:
1934 case SIGNED_INT64_BE: {
1935 int i;
1936 const struct mformatdescr mf_descr =
1937 mformat_descriptors[mformat_code];
1938 Py_ssize_t itemcount = Py_SIZE(items) / mf_descr.size;
1939 const unsigned char *memstr =
1940 (unsigned char *)PyBytes_AS_STRING(items);
1941 struct arraydescr *descr;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001943 /* If possible, try to pack array's items using a data type
1944 * that fits better. This may result in an array with narrower
1945 * or wider elements.
1946 *
1947 * For example, if a 32-bit machine pickles a L-code array of
1948 * unsigned longs, then the array will be unpickled by 64-bit
1949 * machine as an I-code array of unsigned ints.
1950 *
1951 * XXX: Is it possible to write a unit test for this?
1952 */
1953 for (descr = descriptors; descr->typecode != '\0'; descr++) {
1954 if (descr->is_integer_type &&
1955 descr->itemsize == mf_descr.size &&
1956 descr->is_signed == mf_descr.is_signed)
1957 typecode = descr->typecode;
1958 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001960 converted_items = PyList_New(itemcount);
1961 if (converted_items == NULL)
1962 return NULL;
1963 for (i = 0; i < itemcount; i++) {
1964 PyObject *pylong;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001965
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001966 pylong = _PyLong_FromByteArray(
1967 &memstr[i * mf_descr.size],
1968 mf_descr.size,
1969 !mf_descr.is_big_endian,
1970 mf_descr.is_signed);
1971 if (pylong == NULL) {
1972 Py_DECREF(converted_items);
1973 return NULL;
1974 }
1975 PyList_SET_ITEM(converted_items, i, pylong);
1976 }
1977 break;
1978 }
1979 case UNKNOWN_FORMAT:
1980 /* Impossible, but needed to shut up GCC about the unhandled
1981 * enumeration value.
1982 */
1983 default:
1984 PyErr_BadArgument();
1985 return NULL;
1986 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001987
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02001988 result = make_array(arraytype, (char)typecode, converted_items);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001989 Py_DECREF(converted_items);
1990 return result;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001991}
1992
1993static PyObject *
1994array_reduce_ex(arrayobject *array, PyObject *value)
1995{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001996 PyObject *dict;
1997 PyObject *result;
1998 PyObject *array_str;
1999 int typecode = array->ob_descr->typecode;
2000 int mformat_code;
2001 static PyObject *array_reconstructor = NULL;
2002 long protocol;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002003 _Py_IDENTIFIER(_array_reconstructor);
2004 _Py_IDENTIFIER(__dict__);
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002005
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002006 if (array_reconstructor == NULL) {
2007 PyObject *array_module = PyImport_ImportModule("array");
2008 if (array_module == NULL)
2009 return NULL;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002010 array_reconstructor = _PyObject_GetAttrId(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002011 array_module,
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002012 &PyId__array_reconstructor);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002013 Py_DECREF(array_module);
2014 if (array_reconstructor == NULL)
2015 return NULL;
2016 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002018 if (!PyLong_Check(value)) {
2019 PyErr_SetString(PyExc_TypeError,
2020 "__reduce_ex__ argument should an integer");
2021 return NULL;
2022 }
2023 protocol = PyLong_AsLong(value);
2024 if (protocol == -1 && PyErr_Occurred())
2025 return NULL;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002026
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002027 dict = _PyObject_GetAttrId((PyObject *)array, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002028 if (dict == NULL) {
2029 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
2030 return NULL;
2031 PyErr_Clear();
2032 dict = Py_None;
2033 Py_INCREF(dict);
2034 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002035
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002036 mformat_code = typecode_to_mformat_code(typecode);
2037 if (mformat_code == UNKNOWN_FORMAT || protocol < 3) {
2038 /* Convert the array to a list if we got something weird
2039 * (e.g., non-IEEE floats), or we are pickling the array using
2040 * a Python 2.x compatible protocol.
2041 *
2042 * It is necessary to use a list representation for Python 2.x
2043 * compatible pickle protocol, since Python 2's str objects
2044 * are unpickled as unicode by Python 3. Thus it is impossible
2045 * to make arrays unpicklable by Python 3 by using their memory
2046 * representation, unless we resort to ugly hacks such as
2047 * coercing unicode objects to bytes in array_reconstructor.
2048 */
2049 PyObject *list;
2050 list = array_tolist(array, NULL);
2051 if (list == NULL) {
2052 Py_DECREF(dict);
2053 return NULL;
2054 }
2055 result = Py_BuildValue(
2056 "O(CO)O", Py_TYPE(array), typecode, list, dict);
2057 Py_DECREF(list);
2058 Py_DECREF(dict);
2059 return result;
2060 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002061
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00002062 array_str = array_tobytes(array, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002063 if (array_str == NULL) {
2064 Py_DECREF(dict);
2065 return NULL;
2066 }
2067 result = Py_BuildValue(
2068 "O(OCiN)O", array_reconstructor, Py_TYPE(array), typecode,
2069 mformat_code, array_str, dict);
2070 Py_DECREF(dict);
2071 return result;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002072}
2073
2074PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
2075
Martin v. Löwis99866332002-03-01 10:27:01 +00002076static PyObject *
2077array_get_typecode(arrayobject *a, void *closure)
2078{
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02002079 char typecode = a->ob_descr->typecode;
2080 return PyUnicode_FromOrdinal(typecode);
Martin v. Löwis99866332002-03-01 10:27:01 +00002081}
2082
2083static PyObject *
2084array_get_itemsize(arrayobject *a, void *closure)
2085{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002086 return PyLong_FromLong((long)a->ob_descr->itemsize);
Martin v. Löwis99866332002-03-01 10:27:01 +00002087}
2088
2089static PyGetSetDef array_getsets [] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002090 {"typecode", (getter) array_get_typecode, NULL,
2091 "the typecode character used to create the array"},
2092 {"itemsize", (getter) array_get_itemsize, NULL,
2093 "the size, in bytes, of one array item"},
2094 {NULL}
Martin v. Löwis99866332002-03-01 10:27:01 +00002095};
2096
Martin v. Löwis59683e82008-06-13 07:50:45 +00002097static PyMethodDef array_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002098 {"append", (PyCFunction)array_append, METH_O,
2099 append_doc},
2100 {"buffer_info", (PyCFunction)array_buffer_info, METH_NOARGS,
2101 buffer_info_doc},
2102 {"byteswap", (PyCFunction)array_byteswap, METH_NOARGS,
2103 byteswap_doc},
2104 {"__copy__", (PyCFunction)array_copy, METH_NOARGS,
2105 copy_doc},
2106 {"count", (PyCFunction)array_count, METH_O,
2107 count_doc},
2108 {"__deepcopy__",(PyCFunction)array_copy, METH_O,
2109 copy_doc},
2110 {"extend", (PyCFunction)array_extend, METH_O,
2111 extend_doc},
2112 {"fromfile", (PyCFunction)array_fromfile, METH_VARARGS,
2113 fromfile_doc},
2114 {"fromlist", (PyCFunction)array_fromlist, METH_O,
2115 fromlist_doc},
2116 {"fromstring", (PyCFunction)array_fromstring, METH_VARARGS,
2117 fromstring_doc},
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00002118 {"frombytes", (PyCFunction)array_frombytes, METH_VARARGS,
2119 frombytes_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002120 {"fromunicode", (PyCFunction)array_fromunicode, METH_VARARGS,
2121 fromunicode_doc},
2122 {"index", (PyCFunction)array_index, METH_O,
2123 index_doc},
2124 {"insert", (PyCFunction)array_insert, METH_VARARGS,
2125 insert_doc},
2126 {"pop", (PyCFunction)array_pop, METH_VARARGS,
2127 pop_doc},
2128 {"__reduce_ex__", (PyCFunction)array_reduce_ex, METH_O,
2129 reduce_doc},
2130 {"remove", (PyCFunction)array_remove, METH_O,
2131 remove_doc},
2132 {"reverse", (PyCFunction)array_reverse, METH_NOARGS,
2133 reverse_doc},
2134/* {"sort", (PyCFunction)array_sort, METH_VARARGS,
2135 sort_doc},*/
2136 {"tofile", (PyCFunction)array_tofile, METH_O,
2137 tofile_doc},
2138 {"tolist", (PyCFunction)array_tolist, METH_NOARGS,
2139 tolist_doc},
2140 {"tostring", (PyCFunction)array_tostring, METH_NOARGS,
2141 tostring_doc},
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00002142 {"tobytes", (PyCFunction)array_tobytes, METH_NOARGS,
2143 tobytes_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002144 {"tounicode", (PyCFunction)array_tounicode, METH_NOARGS,
2145 tounicode_doc},
2146 {NULL, NULL} /* sentinel */
Guido van Rossum778983b1993-02-19 15:55:02 +00002147};
2148
Roger E. Masse2919eaa1996-12-09 20:10:36 +00002149static PyObject *
Peter Schneider-Kamp9656abd2000-07-13 21:10:57 +00002150array_repr(arrayobject *a)
Guido van Rossum778983b1993-02-19 15:55:02 +00002151{
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02002152 char typecode;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002153 PyObject *s, *v = NULL;
2154 Py_ssize_t len;
Martin v. Löwis99866332002-03-01 10:27:01 +00002155
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002156 len = Py_SIZE(a);
2157 typecode = a->ob_descr->typecode;
2158 if (len == 0) {
Amaury Forgeot d'Arc24aa26b2010-11-25 08:13:35 +00002159 return PyUnicode_FromFormat("array('%c')", (int)typecode);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002160 }
Brett Cannon4a5e5de2011-06-07 20:09:32 -07002161 if (typecode == 'u')
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002162 v = array_tounicode(a, NULL);
2163 else
2164 v = array_tolist(a, NULL);
Raymond Hettinger88ba1e32003-04-23 17:27:00 +00002165
Amaury Forgeot d'Arc24aa26b2010-11-25 08:13:35 +00002166 s = PyUnicode_FromFormat("array('%c', %R)", (int)typecode, v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002167 Py_DECREF(v);
2168 return s;
Guido van Rossum778983b1993-02-19 15:55:02 +00002169}
2170
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002171static PyObject*
2172array_subscr(arrayobject* self, PyObject* item)
2173{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002174 if (PyIndex_Check(item)) {
2175 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
2176 if (i==-1 && PyErr_Occurred()) {
2177 return NULL;
2178 }
2179 if (i < 0)
2180 i += Py_SIZE(self);
2181 return array_item(self, i);
2182 }
2183 else if (PySlice_Check(item)) {
2184 Py_ssize_t start, stop, step, slicelength, cur, i;
2185 PyObject* result;
2186 arrayobject* ar;
2187 int itemsize = self->ob_descr->itemsize;
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002188
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002189 if (PySlice_GetIndicesEx(item, Py_SIZE(self),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002190 &start, &stop, &step, &slicelength) < 0) {
2191 return NULL;
2192 }
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002194 if (slicelength <= 0) {
2195 return newarrayobject(&Arraytype, 0, self->ob_descr);
2196 }
2197 else if (step == 1) {
2198 PyObject *result = newarrayobject(&Arraytype,
2199 slicelength, self->ob_descr);
2200 if (result == NULL)
2201 return NULL;
2202 memcpy(((arrayobject *)result)->ob_item,
2203 self->ob_item + start * itemsize,
2204 slicelength * itemsize);
2205 return result;
2206 }
2207 else {
2208 result = newarrayobject(&Arraytype, slicelength, self->ob_descr);
2209 if (!result) return NULL;
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002211 ar = (arrayobject*)result;
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002213 for (cur = start, i = 0; i < slicelength;
2214 cur += step, i++) {
2215 memcpy(ar->ob_item + i*itemsize,
2216 self->ob_item + cur*itemsize,
2217 itemsize);
2218 }
2219
2220 return result;
2221 }
2222 }
2223 else {
2224 PyErr_SetString(PyExc_TypeError,
2225 "array indices must be integers");
2226 return NULL;
2227 }
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002228}
2229
2230static int
2231array_ass_subscr(arrayobject* self, PyObject* item, PyObject* value)
2232{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002233 Py_ssize_t start, stop, step, slicelength, needed;
2234 arrayobject* other;
2235 int itemsize;
Thomas Woutersed03b412007-08-28 21:37:11 +00002236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002237 if (PyIndex_Check(item)) {
2238 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Alexandre Vassalotti47137252009-07-05 19:57:00 +00002239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002240 if (i == -1 && PyErr_Occurred())
2241 return -1;
2242 if (i < 0)
2243 i += Py_SIZE(self);
2244 if (i < 0 || i >= Py_SIZE(self)) {
2245 PyErr_SetString(PyExc_IndexError,
2246 "array assignment index out of range");
2247 return -1;
2248 }
2249 if (value == NULL) {
2250 /* Fall through to slice assignment */
2251 start = i;
2252 stop = i + 1;
2253 step = 1;
2254 slicelength = 1;
2255 }
2256 else
2257 return (*self->ob_descr->setitem)(self, i, value);
2258 }
2259 else if (PySlice_Check(item)) {
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002260 if (PySlice_GetIndicesEx(item,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002261 Py_SIZE(self), &start, &stop,
2262 &step, &slicelength) < 0) {
2263 return -1;
2264 }
2265 }
2266 else {
2267 PyErr_SetString(PyExc_TypeError,
2268 "array indices must be integer");
2269 return -1;
2270 }
2271 if (value == NULL) {
2272 other = NULL;
2273 needed = 0;
2274 }
2275 else if (array_Check(value)) {
2276 other = (arrayobject *)value;
2277 needed = Py_SIZE(other);
2278 if (self == other) {
2279 /* Special case "self[i:j] = self" -- copy self first */
2280 int ret;
2281 value = array_slice(other, 0, needed);
2282 if (value == NULL)
2283 return -1;
2284 ret = array_ass_subscr(self, item, value);
2285 Py_DECREF(value);
2286 return ret;
2287 }
2288 if (other->ob_descr != self->ob_descr) {
2289 PyErr_BadArgument();
2290 return -1;
2291 }
2292 }
2293 else {
2294 PyErr_Format(PyExc_TypeError,
2295 "can only assign array (not \"%.200s\") to array slice",
2296 Py_TYPE(value)->tp_name);
2297 return -1;
2298 }
2299 itemsize = self->ob_descr->itemsize;
2300 /* for 'a[2:1] = ...', the insertion point is 'start', not 'stop' */
2301 if ((step > 0 && stop < start) ||
2302 (step < 0 && stop > start))
2303 stop = start;
Alexandre Vassalotti47137252009-07-05 19:57:00 +00002304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002305 /* Issue #4509: If the array has exported buffers and the slice
2306 assignment would change the size of the array, fail early to make
2307 sure we don't modify it. */
2308 if ((needed == 0 || slicelength != needed) && self->ob_exports > 0) {
2309 PyErr_SetString(PyExc_BufferError,
2310 "cannot resize an array that is exporting buffers");
2311 return -1;
2312 }
Mark Dickinsonbc099642010-01-29 17:27:24 +00002313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002314 if (step == 1) {
2315 if (slicelength > needed) {
2316 memmove(self->ob_item + (start + needed) * itemsize,
2317 self->ob_item + stop * itemsize,
2318 (Py_SIZE(self) - stop) * itemsize);
2319 if (array_resize(self, Py_SIZE(self) +
2320 needed - slicelength) < 0)
2321 return -1;
2322 }
2323 else if (slicelength < needed) {
2324 if (array_resize(self, Py_SIZE(self) +
2325 needed - slicelength) < 0)
2326 return -1;
2327 memmove(self->ob_item + (start + needed) * itemsize,
2328 self->ob_item + stop * itemsize,
2329 (Py_SIZE(self) - start - needed) * itemsize);
2330 }
2331 if (needed > 0)
2332 memcpy(self->ob_item + start * itemsize,
2333 other->ob_item, needed * itemsize);
2334 return 0;
2335 }
2336 else if (needed == 0) {
2337 /* Delete slice */
2338 size_t cur;
2339 Py_ssize_t i;
Thomas Woutersed03b412007-08-28 21:37:11 +00002340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002341 if (step < 0) {
2342 stop = start + 1;
2343 start = stop + step * (slicelength - 1) - 1;
2344 step = -step;
2345 }
2346 for (cur = start, i = 0; i < slicelength;
2347 cur += step, i++) {
2348 Py_ssize_t lim = step - 1;
Thomas Woutersed03b412007-08-28 21:37:11 +00002349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002350 if (cur + step >= (size_t)Py_SIZE(self))
2351 lim = Py_SIZE(self) - cur - 1;
2352 memmove(self->ob_item + (cur - i) * itemsize,
2353 self->ob_item + (cur + 1) * itemsize,
2354 lim * itemsize);
2355 }
Mark Dickinsonc7d93b72011-09-25 15:34:32 +01002356 cur = start + (size_t)slicelength * step;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002357 if (cur < (size_t)Py_SIZE(self)) {
2358 memmove(self->ob_item + (cur-slicelength) * itemsize,
2359 self->ob_item + cur * itemsize,
2360 (Py_SIZE(self) - cur) * itemsize);
2361 }
2362 if (array_resize(self, Py_SIZE(self) - slicelength) < 0)
2363 return -1;
2364 return 0;
2365 }
2366 else {
2367 Py_ssize_t cur, i;
2368
2369 if (needed != slicelength) {
2370 PyErr_Format(PyExc_ValueError,
2371 "attempt to assign array of size %zd "
2372 "to extended slice of size %zd",
2373 needed, slicelength);
2374 return -1;
2375 }
2376 for (cur = start, i = 0; i < slicelength;
2377 cur += step, i++) {
2378 memcpy(self->ob_item + cur * itemsize,
2379 other->ob_item + i * itemsize,
2380 itemsize);
2381 }
2382 return 0;
2383 }
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002384}
2385
2386static PyMappingMethods array_as_mapping = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002387 (lenfunc)array_length,
2388 (binaryfunc)array_subscr,
2389 (objobjargproc)array_ass_subscr
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002390};
2391
Guido van Rossumd8faa362007-04-27 19:54:29 +00002392static const void *emptybuf = "";
2393
Travis E. Oliphantb99f7622007-08-18 11:21:56 +00002394
2395static int
Travis E. Oliphant8ae62b62007-09-23 02:00:13 +00002396array_buffer_getbuf(arrayobject *self, Py_buffer *view, int flags)
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00002397{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002398 if (view==NULL) goto finish;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +00002399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002400 view->buf = (void *)self->ob_item;
2401 view->obj = (PyObject*)self;
2402 Py_INCREF(self);
2403 if (view->buf == NULL)
2404 view->buf = (void *)emptybuf;
2405 view->len = (Py_SIZE(self)) * self->ob_descr->itemsize;
2406 view->readonly = 0;
2407 view->ndim = 1;
2408 view->itemsize = self->ob_descr->itemsize;
2409 view->suboffsets = NULL;
2410 view->shape = NULL;
2411 if ((flags & PyBUF_ND)==PyBUF_ND) {
2412 view->shape = &((Py_SIZE(self)));
2413 }
2414 view->strides = NULL;
2415 if ((flags & PyBUF_STRIDES)==PyBUF_STRIDES)
2416 view->strides = &(view->itemsize);
2417 view->format = NULL;
2418 view->internal = NULL;
Victor Stinner62bb3942012-08-06 00:46:05 +02002419 if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002420 view->format = self->ob_descr->formats;
Victor Stinner62bb3942012-08-06 00:46:05 +02002421#ifdef Py_UNICODE_WIDE
2422 if (self->ob_descr->typecode == 'u') {
2423 view->format = "w";
2424 }
2425#endif
2426 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +00002427
2428 finish:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002429 self->ob_exports++;
2430 return 0;
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00002431}
2432
Travis E. Oliphantb99f7622007-08-18 11:21:56 +00002433static void
Travis E. Oliphant8ae62b62007-09-23 02:00:13 +00002434array_buffer_relbuf(arrayobject *self, Py_buffer *view)
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00002435{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002436 self->ob_exports--;
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00002437}
2438
Roger E. Masse2919eaa1996-12-09 20:10:36 +00002439static PySequenceMethods array_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002440 (lenfunc)array_length, /*sq_length*/
2441 (binaryfunc)array_concat, /*sq_concat*/
2442 (ssizeargfunc)array_repeat, /*sq_repeat*/
2443 (ssizeargfunc)array_item, /*sq_item*/
2444 0, /*sq_slice*/
2445 (ssizeobjargproc)array_ass_item, /*sq_ass_item*/
2446 0, /*sq_ass_slice*/
2447 (objobjproc)array_contains, /*sq_contains*/
2448 (binaryfunc)array_inplace_concat, /*sq_inplace_concat*/
2449 (ssizeargfunc)array_inplace_repeat /*sq_inplace_repeat*/
Guido van Rossum778983b1993-02-19 15:55:02 +00002450};
2451
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00002452static PyBufferProcs array_as_buffer = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002453 (getbufferproc)array_buffer_getbuf,
2454 (releasebufferproc)array_buffer_relbuf
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00002455};
2456
Roger E. Masse2919eaa1996-12-09 20:10:36 +00002457static PyObject *
Martin v. Löwis99866332002-03-01 10:27:01 +00002458array_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum778983b1993-02-19 15:55:02 +00002459{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002460 int c;
2461 PyObject *initial = NULL, *it = NULL;
2462 struct arraydescr *descr;
Martin v. Löwis99866332002-03-01 10:27:01 +00002463
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002464 if (type == &Arraytype && !_PyArg_NoKeywords("array.array()", kwds))
2465 return NULL;
Martin v. Löwis99866332002-03-01 10:27:01 +00002466
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002467 if (!PyArg_ParseTuple(args, "C|O:array", &c, &initial))
2468 return NULL;
Raymond Hettinger84fc9aa2003-04-24 10:41:55 +00002469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002470 if (!(initial == NULL || PyList_Check(initial)
2471 || PyByteArray_Check(initial)
2472 || PyBytes_Check(initial)
2473 || PyTuple_Check(initial)
Alexander Belopolskyef4a03f2011-01-11 21:44:00 +00002474 || ((c=='u') && PyUnicode_Check(initial))
2475 || (array_Check(initial)
2476 && c == ((arrayobject*)initial)->ob_descr->typecode))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002477 it = PyObject_GetIter(initial);
2478 if (it == NULL)
2479 return NULL;
2480 /* We set initial to NULL so that the subsequent code
2481 will create an empty array of the appropriate type
2482 and afterwards we can use array_iter_extend to populate
2483 the array.
2484 */
2485 initial = NULL;
2486 }
2487 for (descr = descriptors; descr->typecode != '\0'; descr++) {
2488 if (descr->typecode == c) {
2489 PyObject *a;
2490 Py_ssize_t len;
Martin v. Löwis99866332002-03-01 10:27:01 +00002491
Alexander Belopolskyef4a03f2011-01-11 21:44:00 +00002492 if (initial == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002493 len = 0;
Alexander Belopolskyef4a03f2011-01-11 21:44:00 +00002494 else if (PyList_Check(initial))
2495 len = PyList_GET_SIZE(initial);
2496 else if (PyTuple_Check(initial) || array_Check(initial))
2497 len = Py_SIZE(initial);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002498 else
Alexander Belopolskyef4a03f2011-01-11 21:44:00 +00002499 len = 0;
Martin v. Löwis99866332002-03-01 10:27:01 +00002500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002501 a = newarrayobject(type, len, descr);
2502 if (a == NULL)
2503 return NULL;
2504
Alexander Belopolskyef4a03f2011-01-11 21:44:00 +00002505 if (len > 0 && !array_Check(initial)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002506 Py_ssize_t i;
2507 for (i = 0; i < len; i++) {
2508 PyObject *v =
2509 PySequence_GetItem(initial, i);
2510 if (v == NULL) {
2511 Py_DECREF(a);
2512 return NULL;
2513 }
2514 if (setarrayitem(a, i, v) != 0) {
2515 Py_DECREF(v);
2516 Py_DECREF(a);
2517 return NULL;
2518 }
2519 Py_DECREF(v);
2520 }
2521 }
2522 else if (initial != NULL && (PyByteArray_Check(initial) ||
2523 PyBytes_Check(initial))) {
2524 PyObject *t_initial, *v;
2525 t_initial = PyTuple_Pack(1, initial);
2526 if (t_initial == NULL) {
2527 Py_DECREF(a);
2528 return NULL;
2529 }
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00002530 v = array_frombytes((arrayobject *)a,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002531 t_initial);
2532 Py_DECREF(t_initial);
2533 if (v == NULL) {
2534 Py_DECREF(a);
2535 return NULL;
2536 }
2537 Py_DECREF(v);
2538 }
2539 else if (initial != NULL && PyUnicode_Check(initial)) {
Victor Stinner62bb3942012-08-06 00:46:05 +02002540 Py_UNICODE *ustr;
Victor Stinner1fbcaef2011-09-30 01:54:04 +02002541 Py_ssize_t n;
Victor Stinner62bb3942012-08-06 00:46:05 +02002542
2543 ustr = PyUnicode_AsUnicode(initial);
2544 if (ustr == NULL) {
2545 PyErr_NoMemory();
Victor Stinner1fbcaef2011-09-30 01:54:04 +02002546 Py_DECREF(a);
2547 return NULL;
2548 }
Victor Stinner62bb3942012-08-06 00:46:05 +02002549
2550 n = PyUnicode_GET_DATA_SIZE(initial);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002551 if (n > 0) {
2552 arrayobject *self = (arrayobject *)a;
Victor Stinner62bb3942012-08-06 00:46:05 +02002553 char *item = self->ob_item;
2554 item = (char *)PyMem_Realloc(item, n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002555 if (item == NULL) {
2556 PyErr_NoMemory();
2557 Py_DECREF(a);
2558 return NULL;
2559 }
Victor Stinner62bb3942012-08-06 00:46:05 +02002560 self->ob_item = item;
2561 Py_SIZE(self) = n / sizeof(Py_UNICODE);
2562 memcpy(item, ustr, n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002563 self->allocated = Py_SIZE(self);
2564 }
2565 }
Alexander Belopolskyef4a03f2011-01-11 21:44:00 +00002566 else if (initial != NULL && array_Check(initial)) {
2567 arrayobject *self = (arrayobject *)a;
2568 arrayobject *other = (arrayobject *)initial;
2569 memcpy(self->ob_item, other->ob_item, len * other->ob_descr->itemsize);
2570 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002571 if (it != NULL) {
2572 if (array_iter_extend((arrayobject *)a, it) == -1) {
2573 Py_DECREF(it);
2574 Py_DECREF(a);
2575 return NULL;
2576 }
2577 Py_DECREF(it);
2578 }
2579 return a;
2580 }
2581 }
2582 PyErr_SetString(PyExc_ValueError,
Meador Inge1c9f0c92011-09-20 19:55:51 -05002583#ifdef HAVE_LONG_LONG
2584 "bad typecode (must be b, B, u, h, H, i, I, l, L, q, Q, f or d)");
2585#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002586 "bad typecode (must be b, B, u, h, H, i, I, l, L, f or d)");
Meador Inge1c9f0c92011-09-20 19:55:51 -05002587#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002588 return NULL;
Guido van Rossum778983b1993-02-19 15:55:02 +00002589}
2590
Guido van Rossum778983b1993-02-19 15:55:02 +00002591
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002592PyDoc_STRVAR(module_doc,
Martin v. Löwis99866332002-03-01 10:27:01 +00002593"This module defines an object type which can efficiently represent\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002594an array of basic values: characters, integers, floating point\n\
2595numbers. Arrays are sequence types and behave very much like lists,\n\
2596except that the type of objects stored in them is constrained. The\n\
2597type is specified at object creation time by using a type code, which\n\
2598is a single character. The following type codes are defined:\n\
2599\n\
2600 Type code C Type Minimum size in bytes \n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002601 'b' signed integer 1 \n\
2602 'B' unsigned integer 1 \n\
Victor Stinner62bb3942012-08-06 00:46:05 +02002603 'u' Unicode character 2 (see note) \n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002604 'h' signed integer 2 \n\
2605 'H' unsigned integer 2 \n\
2606 'i' signed integer 2 \n\
2607 'I' unsigned integer 2 \n\
2608 'l' signed integer 4 \n\
2609 'L' unsigned integer 4 \n\
Meador Inge1c9f0c92011-09-20 19:55:51 -05002610 'q' signed integer 8 (see note) \n\
2611 'Q' unsigned integer 8 (see note) \n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002612 'f' floating point 4 \n\
2613 'd' floating point 8 \n\
2614\n\
Victor Stinner62bb3942012-08-06 00:46:05 +02002615NOTE: The 'u' typecode corresponds to Python's unicode character. On \n\
2616narrow builds this is 2-bytes on wide builds this is 4-bytes.\n\
2617\n\
Meador Inge1c9f0c92011-09-20 19:55:51 -05002618NOTE: The 'q' and 'Q' type codes are only available if the platform \n\
2619C compiler used to build Python supports 'long long', or, on Windows, \n\
2620'__int64'.\n\
2621\n\
Martin v. Löwis99866332002-03-01 10:27:01 +00002622The constructor is:\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002623\n\
2624array(typecode [, initializer]) -- create a new array\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002625");
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002626
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002627PyDoc_STRVAR(arraytype_doc,
Martin v. Löwis99866332002-03-01 10:27:01 +00002628"array(typecode [, initializer]) -> array\n\
2629\n\
2630Return a new array whose items are restricted by typecode, and\n\
Raymond Hettinger6ab78cd2004-08-29 07:50:43 +00002631initialized from the optional initializer value, which must be a list,\n\
Florent Xicluna0e686cb2011-12-09 23:41:19 +01002632string or iterable over elements of the appropriate type.\n\
Martin v. Löwis99866332002-03-01 10:27:01 +00002633\n\
2634Arrays represent basic values and behave very much like lists, except\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002635the type of objects stored in them is constrained.\n\
2636\n\
2637Methods:\n\
2638\n\
2639append() -- append a new item to the end of the array\n\
2640buffer_info() -- return information giving the current memory info\n\
2641byteswap() -- byteswap all the items of the array\n\
Mark Dickinson934896d2009-02-21 20:59:32 +00002642count() -- return number of occurrences of an object\n\
Raymond Hettinger49f9bd12004-03-14 05:43:59 +00002643extend() -- extend array by appending multiple elements from an iterable\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002644fromfile() -- read items from a file object\n\
2645fromlist() -- append items from the list\n\
Florent Xiclunac45fb252011-10-24 13:14:55 +02002646frombytes() -- append items from the string\n\
Mark Dickinson934896d2009-02-21 20:59:32 +00002647index() -- return index of first occurrence of an object\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002648insert() -- insert a new item into the array at a provided position\n\
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00002649pop() -- remove and return item (default last)\n\
Mark Dickinson934896d2009-02-21 20:59:32 +00002650remove() -- remove first occurrence of an object\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002651reverse() -- reverse the order of the items in the array\n\
2652tofile() -- write all items to a file object\n\
2653tolist() -- return the array converted to an ordinary list\n\
Florent Xiclunac45fb252011-10-24 13:14:55 +02002654tobytes() -- return the array converted to a string\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002655\n\
Martin v. Löwis99866332002-03-01 10:27:01 +00002656Attributes:\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002657\n\
2658typecode -- the typecode character used to create the array\n\
2659itemsize -- the length in bytes of one array item\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002660");
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002661
Raymond Hettinger625812f2003-01-07 01:58:52 +00002662static PyObject *array_iter(arrayobject *ao);
2663
Tim Peters0c322792002-07-17 16:49:03 +00002664static PyTypeObject Arraytype = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002665 PyVarObject_HEAD_INIT(NULL, 0)
2666 "array.array",
2667 sizeof(arrayobject),
2668 0,
2669 (destructor)array_dealloc, /* tp_dealloc */
2670 0, /* tp_print */
2671 0, /* tp_getattr */
2672 0, /* tp_setattr */
2673 0, /* tp_reserved */
2674 (reprfunc)array_repr, /* tp_repr */
2675 0, /* tp_as_number*/
2676 &array_as_sequence, /* tp_as_sequence*/
2677 &array_as_mapping, /* tp_as_mapping*/
2678 0, /* tp_hash */
2679 0, /* tp_call */
2680 0, /* tp_str */
2681 PyObject_GenericGetAttr, /* tp_getattro */
2682 0, /* tp_setattro */
2683 &array_as_buffer, /* tp_as_buffer*/
2684 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
2685 arraytype_doc, /* tp_doc */
2686 0, /* tp_traverse */
2687 0, /* tp_clear */
2688 array_richcompare, /* tp_richcompare */
2689 offsetof(arrayobject, weakreflist), /* tp_weaklistoffset */
2690 (getiterfunc)array_iter, /* tp_iter */
2691 0, /* tp_iternext */
2692 array_methods, /* tp_methods */
2693 0, /* tp_members */
2694 array_getsets, /* tp_getset */
2695 0, /* tp_base */
2696 0, /* tp_dict */
2697 0, /* tp_descr_get */
2698 0, /* tp_descr_set */
2699 0, /* tp_dictoffset */
2700 0, /* tp_init */
2701 PyType_GenericAlloc, /* tp_alloc */
2702 array_new, /* tp_new */
2703 PyObject_Del, /* tp_free */
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002704};
2705
Raymond Hettinger625812f2003-01-07 01:58:52 +00002706
2707/*********************** Array Iterator **************************/
2708
2709typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002710 PyObject_HEAD
2711 Py_ssize_t index;
2712 arrayobject *ao;
2713 PyObject * (*getitem)(struct arrayobject *, Py_ssize_t);
Raymond Hettinger625812f2003-01-07 01:58:52 +00002714} arrayiterobject;
2715
2716static PyTypeObject PyArrayIter_Type;
2717
2718#define PyArrayIter_Check(op) PyObject_TypeCheck(op, &PyArrayIter_Type)
2719
2720static PyObject *
2721array_iter(arrayobject *ao)
2722{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002723 arrayiterobject *it;
Raymond Hettinger625812f2003-01-07 01:58:52 +00002724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002725 if (!array_Check(ao)) {
2726 PyErr_BadInternalCall();
2727 return NULL;
2728 }
Raymond Hettinger625812f2003-01-07 01:58:52 +00002729
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002730 it = PyObject_GC_New(arrayiterobject, &PyArrayIter_Type);
2731 if (it == NULL)
2732 return NULL;
Raymond Hettinger625812f2003-01-07 01:58:52 +00002733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002734 Py_INCREF(ao);
2735 it->ao = ao;
2736 it->index = 0;
2737 it->getitem = ao->ob_descr->getitem;
2738 PyObject_GC_Track(it);
2739 return (PyObject *)it;
Raymond Hettinger625812f2003-01-07 01:58:52 +00002740}
2741
2742static PyObject *
Raymond Hettinger625812f2003-01-07 01:58:52 +00002743arrayiter_next(arrayiterobject *it)
2744{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002745 assert(PyArrayIter_Check(it));
2746 if (it->index < Py_SIZE(it->ao))
2747 return (*it->getitem)(it->ao, it->index++);
2748 return NULL;
Raymond Hettinger625812f2003-01-07 01:58:52 +00002749}
2750
2751static void
2752arrayiter_dealloc(arrayiterobject *it)
2753{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002754 PyObject_GC_UnTrack(it);
2755 Py_XDECREF(it->ao);
2756 PyObject_GC_Del(it);
Raymond Hettinger625812f2003-01-07 01:58:52 +00002757}
2758
2759static int
2760arrayiter_traverse(arrayiterobject *it, visitproc visit, void *arg)
2761{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002762 Py_VISIT(it->ao);
2763 return 0;
Raymond Hettinger625812f2003-01-07 01:58:52 +00002764}
2765
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002766static PyObject *
2767arrayiter_reduce(arrayiterobject *it)
2768{
Antoine Pitroua7013882012-04-05 00:04:20 +02002769 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002770 it->ao, it->index);
2771}
2772
2773static PyObject *
2774arrayiter_setstate(arrayiterobject *it, PyObject *state)
2775{
2776 Py_ssize_t index = PyLong_AsSsize_t(state);
2777 if (index == -1 && PyErr_Occurred())
2778 return NULL;
2779 if (index < 0)
2780 index = 0;
2781 it->index = index;
2782 Py_RETURN_NONE;
2783}
2784
2785PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
2786static PyMethodDef arrayiter_methods[] = {
2787 {"__reduce__", (PyCFunction)arrayiter_reduce, METH_NOARGS,
2788 reduce_doc},
2789 {"__setstate__", (PyCFunction)arrayiter_setstate, METH_O,
2790 setstate_doc},
2791 {NULL, NULL} /* sentinel */
2792};
2793
Raymond Hettinger625812f2003-01-07 01:58:52 +00002794static PyTypeObject PyArrayIter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002795 PyVarObject_HEAD_INIT(NULL, 0)
2796 "arrayiterator", /* tp_name */
2797 sizeof(arrayiterobject), /* tp_basicsize */
2798 0, /* tp_itemsize */
2799 /* methods */
2800 (destructor)arrayiter_dealloc, /* tp_dealloc */
2801 0, /* tp_print */
2802 0, /* tp_getattr */
2803 0, /* tp_setattr */
2804 0, /* tp_reserved */
2805 0, /* tp_repr */
2806 0, /* tp_as_number */
2807 0, /* tp_as_sequence */
2808 0, /* tp_as_mapping */
2809 0, /* tp_hash */
2810 0, /* tp_call */
2811 0, /* tp_str */
2812 PyObject_GenericGetAttr, /* tp_getattro */
2813 0, /* tp_setattro */
2814 0, /* tp_as_buffer */
2815 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2816 0, /* tp_doc */
2817 (traverseproc)arrayiter_traverse, /* tp_traverse */
2818 0, /* tp_clear */
2819 0, /* tp_richcompare */
2820 0, /* tp_weaklistoffset */
2821 PyObject_SelfIter, /* tp_iter */
2822 (iternextfunc)arrayiter_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002823 arrayiter_methods, /* tp_methods */
Raymond Hettinger625812f2003-01-07 01:58:52 +00002824};
2825
2826
2827/*********************** Install Module **************************/
2828
Martin v. Löwis99866332002-03-01 10:27:01 +00002829/* No functions in array module. */
2830static PyMethodDef a_methods[] = {
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002831 {"_array_reconstructor", array_reconstructor, METH_VARARGS,
2832 PyDoc_STR("Internal. Used for pickling support.")},
Martin v. Löwis99866332002-03-01 10:27:01 +00002833 {NULL, NULL, 0, NULL} /* Sentinel */
2834};
2835
Martin v. Löwis1a214512008-06-11 05:26:20 +00002836static struct PyModuleDef arraymodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002837 PyModuleDef_HEAD_INIT,
2838 "array",
2839 module_doc,
2840 -1,
2841 a_methods,
2842 NULL,
2843 NULL,
2844 NULL,
2845 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002846};
2847
Martin v. Löwis99866332002-03-01 10:27:01 +00002848
Mark Hammondfe51c6d2002-08-02 02:27:13 +00002849PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002850PyInit_array(void)
Guido van Rossum778983b1993-02-19 15:55:02 +00002851{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002852 PyObject *m;
Georg Brandl4cb0de22011-09-28 21:49:49 +02002853 char buffer[Py_ARRAY_LENGTH(descriptors)], *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002854 PyObject *typecodes;
2855 Py_ssize_t size = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002856 struct arraydescr *descr;
Fred Drake0d40ba42000-02-04 20:33:49 +00002857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002858 if (PyType_Ready(&Arraytype) < 0)
2859 return NULL;
2860 Py_TYPE(&PyArrayIter_Type) = &PyType_Type;
2861 m = PyModule_Create(&arraymodule);
2862 if (m == NULL)
2863 return NULL;
Fred Drakef4e34842002-04-01 03:45:06 +00002864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002865 Py_INCREF((PyObject *)&Arraytype);
2866 PyModule_AddObject(m, "ArrayType", (PyObject *)&Arraytype);
2867 Py_INCREF((PyObject *)&Arraytype);
2868 PyModule_AddObject(m, "array", (PyObject *)&Arraytype);
Travis E. Oliphantd5c0add2007-10-12 22:05:15 +00002869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002870 for (descr=descriptors; descr->typecode != '\0'; descr++) {
2871 size++;
2872 }
Travis E. Oliphantd5c0add2007-10-12 22:05:15 +00002873
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002874 p = buffer;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002875 for (descr = descriptors; descr->typecode != '\0'; descr++) {
2876 *p++ = (char)descr->typecode;
2877 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002878 typecodes = PyUnicode_DecodeASCII(buffer, p - buffer, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002879
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002880 PyModule_AddObject(m, "typecodes", typecodes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002881
2882 if (PyErr_Occurred()) {
2883 Py_DECREF(m);
2884 m = NULL;
2885 }
2886 return m;
Guido van Rossum778983b1993-02-19 15:55:02 +00002887}