blob: 6b37cacafeb9c1d5556737671e07b4968e667c24 [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 /* Check for overflow */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +0100487 if (size > PY_SSIZE_T_MAX / descr->itemsize) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 return PyErr_NoMemory();
489 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +0100490 nbytes = size * descr->itemsize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000491 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++) {
Victor Stinner0b142e22013-07-17 23:01:30 +0200971 PyObject *selfi;
972 int cmp;
973
974 selfi = getarrayitem((PyObject *)self, i);
975 if (selfi == NULL)
976 return NULL;
977 cmp = PyObject_RichCompareBool(selfi, v, Py_EQ);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 Py_DECREF(selfi);
979 if (cmp > 0)
980 count++;
981 else if (cmp < 0)
982 return NULL;
983 }
984 return PyLong_FromSsize_t(count);
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +0000985}
986
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000987PyDoc_STRVAR(count_doc,
Tim Peters077a11d2000-09-16 22:31:29 +0000988"count(x)\n\
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +0000989\n\
Mark Dickinson934896d2009-02-21 20:59:32 +0000990Return number of occurrences of x in the array.");
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +0000991
992static PyObject *
Raymond Hettinger36cd2bf2003-01-03 08:24:58 +0000993array_index(arrayobject *self, PyObject *v)
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +0000994{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000995 Py_ssize_t i;
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +0000996
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 for (i = 0; i < Py_SIZE(self); i++) {
Victor Stinner0b142e22013-07-17 23:01:30 +0200998 PyObject *selfi;
999 int cmp;
1000
1001 selfi = getarrayitem((PyObject *)self, i);
1002 if (selfi == NULL)
1003 return NULL;
1004 cmp = PyObject_RichCompareBool(selfi, v, Py_EQ);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 Py_DECREF(selfi);
1006 if (cmp > 0) {
1007 return PyLong_FromLong((long)i);
1008 }
1009 else if (cmp < 0)
1010 return NULL;
1011 }
1012 PyErr_SetString(PyExc_ValueError, "array.index(x): x not in list");
1013 return NULL;
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001014}
1015
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001016PyDoc_STRVAR(index_doc,
Tim Peters077a11d2000-09-16 22:31:29 +00001017"index(x)\n\
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001018\n\
Mark Dickinson934896d2009-02-21 20:59:32 +00001019Return index of first occurrence of x in the array.");
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001020
Raymond Hettinger625812f2003-01-07 01:58:52 +00001021static int
1022array_contains(arrayobject *self, PyObject *v)
1023{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001024 Py_ssize_t i;
1025 int cmp;
Raymond Hettinger625812f2003-01-07 01:58:52 +00001026
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(self); i++) {
1028 PyObject *selfi = getarrayitem((PyObject *)self, i);
Victor Stinner0b142e22013-07-17 23:01:30 +02001029 if (selfi == NULL)
1030 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 cmp = PyObject_RichCompareBool(selfi, v, Py_EQ);
1032 Py_DECREF(selfi);
1033 }
1034 return cmp;
Raymond Hettinger625812f2003-01-07 01:58:52 +00001035}
1036
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001037static PyObject *
Raymond Hettinger36cd2bf2003-01-03 08:24:58 +00001038array_remove(arrayobject *self, PyObject *v)
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001039{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 int i;
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 for (i = 0; i < Py_SIZE(self); i++) {
Victor Stinner0b142e22013-07-17 23:01:30 +02001043 PyObject *selfi;
1044 int cmp;
1045
1046 selfi = getarrayitem((PyObject *)self,i);
1047 if (selfi == NULL)
1048 return NULL;
1049 cmp = PyObject_RichCompareBool(selfi, v, Py_EQ);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 Py_DECREF(selfi);
1051 if (cmp > 0) {
1052 if (array_ass_slice(self, i, i+1,
1053 (PyObject *)NULL) != 0)
1054 return NULL;
1055 Py_INCREF(Py_None);
1056 return Py_None;
1057 }
1058 else if (cmp < 0)
1059 return NULL;
1060 }
1061 PyErr_SetString(PyExc_ValueError, "array.remove(x): x not in list");
1062 return NULL;
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001063}
1064
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001065PyDoc_STRVAR(remove_doc,
Tim Peters077a11d2000-09-16 22:31:29 +00001066"remove(x)\n\
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001067\n\
Mark Dickinson934896d2009-02-21 20:59:32 +00001068Remove the first occurrence of x in the array.");
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001069
1070static PyObject *
1071array_pop(arrayobject *self, PyObject *args)
1072{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 Py_ssize_t i = -1;
1074 PyObject *v;
1075 if (!PyArg_ParseTuple(args, "|n:pop", &i))
1076 return NULL;
1077 if (Py_SIZE(self) == 0) {
1078 /* Special-case most common failure cause */
1079 PyErr_SetString(PyExc_IndexError, "pop from empty array");
1080 return NULL;
1081 }
1082 if (i < 0)
1083 i += Py_SIZE(self);
1084 if (i < 0 || i >= Py_SIZE(self)) {
1085 PyErr_SetString(PyExc_IndexError, "pop index out of range");
1086 return NULL;
1087 }
Victor Stinner0b142e22013-07-17 23:01:30 +02001088 v = getarrayitem((PyObject *)self, i);
1089 if (v == NULL)
1090 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 if (array_ass_slice(self, i, i+1, (PyObject *)NULL) != 0) {
1092 Py_DECREF(v);
1093 return NULL;
1094 }
1095 return v;
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001096}
1097
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001098PyDoc_STRVAR(pop_doc,
Tim Peters077a11d2000-09-16 22:31:29 +00001099"pop([i])\n\
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001100\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001101Return the i-th element and delete it from the array. i defaults to -1.");
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001102
1103static PyObject *
Raymond Hettinger36cd2bf2003-01-03 08:24:58 +00001104array_extend(arrayobject *self, PyObject *bb)
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001105{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 if (array_do_extend(self, bb) == -1)
1107 return NULL;
1108 Py_INCREF(Py_None);
1109 return Py_None;
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001110}
1111
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001112PyDoc_STRVAR(extend_doc,
Raymond Hettinger49f9bd12004-03-14 05:43:59 +00001113"extend(array or iterable)\n\
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001114\n\
Raymond Hettinger49f9bd12004-03-14 05:43:59 +00001115 Append items to the end of the array.");
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00001116
1117static PyObject *
Peter Schneider-Kamp9656abd2000-07-13 21:10:57 +00001118array_insert(arrayobject *self, PyObject *args)
Guido van Rossum778983b1993-02-19 15:55:02 +00001119{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001120 Py_ssize_t i;
1121 PyObject *v;
1122 if (!PyArg_ParseTuple(args, "nO:insert", &i, &v))
1123 return NULL;
1124 return ins(self, i, v);
Guido van Rossum778983b1993-02-19 15:55:02 +00001125}
1126
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001127PyDoc_STRVAR(insert_doc,
Tim Peters077a11d2000-09-16 22:31:29 +00001128"insert(i,x)\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001129\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001130Insert a new item x into the array before position i.");
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001131
1132
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001133static PyObject *
Raymond Hettinger36cd2bf2003-01-03 08:24:58 +00001134array_buffer_info(arrayobject *self, PyObject *unused)
Guido van Rossumde4a4ca1997-08-12 14:55:56 +00001135{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136 PyObject* retval = NULL;
1137 retval = PyTuple_New(2);
1138 if (!retval)
1139 return NULL;
Fred Drake541dc3b2000-06-28 17:49:30 +00001140
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001141 PyTuple_SET_ITEM(retval, 0, PyLong_FromVoidPtr(self->ob_item));
1142 PyTuple_SET_ITEM(retval, 1, PyLong_FromLong((long)(Py_SIZE(self))));
Fred Drake541dc3b2000-06-28 17:49:30 +00001143
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001144 return retval;
Guido van Rossumde4a4ca1997-08-12 14:55:56 +00001145}
1146
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001147PyDoc_STRVAR(buffer_info_doc,
Tim Peters077a11d2000-09-16 22:31:29 +00001148"buffer_info() -> (address, length)\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001149\n\
1150Return a tuple (address, length) giving the current memory address and\n\
Guido van Rossum702d08e2001-07-27 16:05:32 +00001151the length in items of the buffer used to hold array's contents\n\
1152The length should be multiplied by the itemsize attribute to calculate\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001153the buffer length in bytes.");
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001154
1155
Guido van Rossumde4a4ca1997-08-12 14:55:56 +00001156static PyObject *
Raymond Hettinger36cd2bf2003-01-03 08:24:58 +00001157array_append(arrayobject *self, PyObject *v)
Guido van Rossum778983b1993-02-19 15:55:02 +00001158{
Mark Dickinson346f0af2010-08-06 09:36:57 +00001159 return ins(self, Py_SIZE(self), v);
Guido van Rossum778983b1993-02-19 15:55:02 +00001160}
1161
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001162PyDoc_STRVAR(append_doc,
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001163"append(x)\n\
1164\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001165Append new value x to the end of the array.");
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001166
1167
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001168static PyObject *
Raymond Hettinger36cd2bf2003-01-03 08:24:58 +00001169array_byteswap(arrayobject *self, PyObject *unused)
Guido van Rossum778983b1993-02-19 15:55:02 +00001170{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001171 char *p;
1172 Py_ssize_t i;
Fred Drakebf272981999-12-03 17:15:30 +00001173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001174 switch (self->ob_descr->itemsize) {
1175 case 1:
1176 break;
1177 case 2:
1178 for (p = self->ob_item, i = Py_SIZE(self); --i >= 0; p += 2) {
1179 char p0 = p[0];
1180 p[0] = p[1];
1181 p[1] = p0;
1182 }
1183 break;
1184 case 4:
1185 for (p = self->ob_item, i = Py_SIZE(self); --i >= 0; p += 4) {
1186 char p0 = p[0];
1187 char p1 = p[1];
1188 p[0] = p[3];
1189 p[1] = p[2];
1190 p[2] = p1;
1191 p[3] = p0;
1192 }
1193 break;
1194 case 8:
1195 for (p = self->ob_item, i = Py_SIZE(self); --i >= 0; p += 8) {
1196 char p0 = p[0];
1197 char p1 = p[1];
1198 char p2 = p[2];
1199 char p3 = p[3];
1200 p[0] = p[7];
1201 p[1] = p[6];
1202 p[2] = p[5];
1203 p[3] = p[4];
1204 p[4] = p3;
1205 p[5] = p2;
1206 p[6] = p1;
1207 p[7] = p0;
1208 }
1209 break;
1210 default:
1211 PyErr_SetString(PyExc_RuntimeError,
1212 "don't know how to byteswap this array type");
1213 return NULL;
1214 }
1215 Py_INCREF(Py_None);
1216 return Py_None;
Guido van Rossum778983b1993-02-19 15:55:02 +00001217}
1218
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001219PyDoc_STRVAR(byteswap_doc,
Fred Drakebf272981999-12-03 17:15:30 +00001220"byteswap()\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001221\n\
Fred Drakebf272981999-12-03 17:15:30 +00001222Byteswap 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 +000012234, or 8 bytes in size, RuntimeError is raised.");
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001224
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001225static PyObject *
Raymond Hettinger36cd2bf2003-01-03 08:24:58 +00001226array_reverse(arrayobject *self, PyObject *unused)
Guido van Rossum778983b1993-02-19 15:55:02 +00001227{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001228 register Py_ssize_t itemsize = self->ob_descr->itemsize;
1229 register char *p, *q;
1230 /* little buffer to hold items while swapping */
1231 char tmp[256]; /* 8 is probably enough -- but why skimp */
1232 assert((size_t)itemsize <= sizeof(tmp));
Guido van Rossume77a7571993-11-03 15:01:26 +00001233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 if (Py_SIZE(self) > 1) {
1235 for (p = self->ob_item,
1236 q = self->ob_item + (Py_SIZE(self) - 1)*itemsize;
1237 p < q;
1238 p += itemsize, q -= itemsize) {
1239 /* memory areas guaranteed disjoint, so memcpy
1240 * is safe (& memmove may be slower).
1241 */
1242 memcpy(tmp, p, itemsize);
1243 memcpy(p, q, itemsize);
1244 memcpy(q, tmp, itemsize);
1245 }
1246 }
Tim Petersbb307342000-09-10 05:22:54 +00001247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001248 Py_INCREF(Py_None);
1249 return Py_None;
Guido van Rossum778983b1993-02-19 15:55:02 +00001250}
Guido van Rossume77a7571993-11-03 15:01:26 +00001251
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001252PyDoc_STRVAR(reverse_doc,
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001253"reverse()\n\
1254\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001255Reverse the order of the items in the array.");
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001256
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001257
1258/* Forward */
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001259static PyObject *array_frombytes(arrayobject *self, PyObject *args);
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001260
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001261static PyObject *
Peter Schneider-Kamp9656abd2000-07-13 21:10:57 +00001262array_fromfile(arrayobject *self, PyObject *args)
Guido van Rossum778983b1993-02-19 15:55:02 +00001263{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001264 PyObject *f, *b, *res;
1265 Py_ssize_t itemsize = self->ob_descr->itemsize;
1266 Py_ssize_t n, nbytes;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001267 _Py_IDENTIFIER(read);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001268 int not_enough_bytes;
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001270 if (!PyArg_ParseTuple(args, "On:fromfile", &f, &n))
1271 return NULL;
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001272
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01001273 if (n < 0) {
1274 PyErr_SetString(PyExc_ValueError, "negative count");
1275 return NULL;
1276 }
1277 if (n > PY_SSIZE_T_MAX / itemsize) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001278 PyErr_NoMemory();
1279 return NULL;
1280 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01001281 nbytes = n * itemsize;
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001282
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001283 b = _PyObject_CallMethodId(f, &PyId_read, "n", nbytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001284 if (b == NULL)
1285 return NULL;
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001287 if (!PyBytes_Check(b)) {
1288 PyErr_SetString(PyExc_TypeError,
1289 "read() didn't return bytes");
1290 Py_DECREF(b);
1291 return NULL;
1292 }
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001294 not_enough_bytes = (PyBytes_GET_SIZE(b) != nbytes);
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001296 args = Py_BuildValue("(O)", b);
1297 Py_DECREF(b);
1298 if (args == NULL)
1299 return NULL;
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001300
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001301 res = array_frombytes(self, args);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001302 Py_DECREF(args);
1303 if (res == NULL)
1304 return NULL;
Hirokazu Yamamoto54d0df62009-03-06 03:04:07 +00001305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001306 if (not_enough_bytes) {
1307 PyErr_SetString(PyExc_EOFError,
1308 "read() didn't return enough bytes");
1309 Py_DECREF(res);
1310 return NULL;
1311 }
Guido van Rossum2c94aa52007-05-24 19:02:32 +00001312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001313 return res;
Guido van Rossum778983b1993-02-19 15:55:02 +00001314}
1315
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001316PyDoc_STRVAR(fromfile_doc,
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001317"fromfile(f, n)\n\
1318\n\
1319Read n objects from the file object f and append them to the end of the\n\
Georg Brandlf25ef502008-02-01 11:30:18 +00001320array.");
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001321
1322
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001323static PyObject *
Raymond Hettinger36cd2bf2003-01-03 08:24:58 +00001324array_tofile(arrayobject *self, PyObject *f)
Guido van Rossum778983b1993-02-19 15:55:02 +00001325{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001326 Py_ssize_t nbytes = Py_SIZE(self) * self->ob_descr->itemsize;
1327 /* Write 64K blocks at a time */
1328 /* XXX Make the block size settable */
1329 int BLOCKSIZE = 64*1024;
1330 Py_ssize_t nblocks = (nbytes + BLOCKSIZE - 1) / BLOCKSIZE;
1331 Py_ssize_t i;
Raymond Hettinger36cd2bf2003-01-03 08:24:58 +00001332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001333 if (Py_SIZE(self) == 0)
1334 goto done;
Guido van Rossumb5ddcfd2007-04-11 17:08:28 +00001335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336 for (i = 0; i < nblocks; i++) {
1337 char* ptr = self->ob_item + i*BLOCKSIZE;
1338 Py_ssize_t size = BLOCKSIZE;
1339 PyObject *bytes, *res;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001340 _Py_IDENTIFIER(write);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001342 if (i*BLOCKSIZE + size > nbytes)
1343 size = nbytes - i*BLOCKSIZE;
1344 bytes = PyBytes_FromStringAndSize(ptr, size);
1345 if (bytes == NULL)
1346 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001347 res = _PyObject_CallMethodId(f, &PyId_write, "O", bytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001348 Py_DECREF(bytes);
1349 if (res == NULL)
1350 return NULL;
1351 Py_DECREF(res); /* drop write result */
1352 }
Guido van Rossumb5ddcfd2007-04-11 17:08:28 +00001353
1354 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001355 Py_INCREF(Py_None);
1356 return Py_None;
Guido van Rossum778983b1993-02-19 15:55:02 +00001357}
1358
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001359PyDoc_STRVAR(tofile_doc,
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001360"tofile(f)\n\
1361\n\
Georg Brandlf25ef502008-02-01 11:30:18 +00001362Write all items (as machine values) to the file object f.");
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001363
1364
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001365static PyObject *
Raymond Hettinger36cd2bf2003-01-03 08:24:58 +00001366array_fromlist(arrayobject *self, PyObject *list)
Guido van Rossum778983b1993-02-19 15:55:02 +00001367{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001368 Py_ssize_t n;
Raymond Hettinger36cd2bf2003-01-03 08:24:58 +00001369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001370 if (!PyList_Check(list)) {
1371 PyErr_SetString(PyExc_TypeError, "arg must be list");
1372 return NULL;
1373 }
1374 n = PyList_Size(list);
1375 if (n > 0) {
1376 Py_ssize_t i, old_size;
1377 old_size = Py_SIZE(self);
1378 if (array_resize(self, old_size + n) == -1)
1379 return NULL;
1380 for (i = 0; i < n; i++) {
1381 PyObject *v = PyList_GetItem(list, i);
1382 if ((*self->ob_descr->setitem)(self,
1383 Py_SIZE(self) - n + i, v) != 0) {
1384 array_resize(self, old_size);
1385 return NULL;
1386 }
1387 }
1388 }
1389 Py_INCREF(Py_None);
1390 return Py_None;
Guido van Rossum778983b1993-02-19 15:55:02 +00001391}
1392
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001393PyDoc_STRVAR(fromlist_doc,
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001394"fromlist(list)\n\
1395\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001396Append items to array from list.");
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001397
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001398static PyObject *
Raymond Hettinger36cd2bf2003-01-03 08:24:58 +00001399array_tolist(arrayobject *self, PyObject *unused)
Guido van Rossum778983b1993-02-19 15:55:02 +00001400{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001401 PyObject *list = PyList_New(Py_SIZE(self));
1402 Py_ssize_t i;
Raymond Hettinger36cd2bf2003-01-03 08:24:58 +00001403
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001404 if (list == NULL)
1405 return NULL;
1406 for (i = 0; i < Py_SIZE(self); i++) {
1407 PyObject *v = getarrayitem((PyObject *)self, i);
1408 if (v == NULL) {
1409 Py_DECREF(list);
1410 return NULL;
1411 }
1412 PyList_SetItem(list, i, v);
1413 }
1414 return list;
Guido van Rossum778983b1993-02-19 15:55:02 +00001415}
1416
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001417PyDoc_STRVAR(tolist_doc,
Guido van Rossumfc6aba51998-10-14 02:52:31 +00001418"tolist() -> list\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001419\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001420Convert array to an ordinary list with the same items.");
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001421
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001422static PyObject *
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001423frombytes(arrayobject *self, Py_buffer *buffer)
Guido van Rossum778983b1993-02-19 15:55:02 +00001424{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001425 int itemsize = self->ob_descr->itemsize;
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001426 Py_ssize_t n;
1427 if (buffer->itemsize != 1) {
1428 PyBuffer_Release(buffer);
1429 PyErr_SetString(PyExc_TypeError, "string/buffer of bytes required.");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001430 return NULL;
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001431 }
1432 n = buffer->len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001433 if (n % itemsize != 0) {
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001434 PyBuffer_Release(buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001435 PyErr_SetString(PyExc_ValueError,
1436 "string length not a multiple of item size");
1437 return NULL;
1438 }
1439 n = n / itemsize;
1440 if (n > 0) {
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001441 Py_ssize_t old_size = Py_SIZE(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001442 if ((n > PY_SSIZE_T_MAX - old_size) ||
1443 ((old_size + n) > PY_SSIZE_T_MAX / itemsize)) {
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001444 PyBuffer_Release(buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001445 return PyErr_NoMemory();
1446 }
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001447 if (array_resize(self, old_size + n) == -1) {
1448 PyBuffer_Release(buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001449 return NULL;
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001450 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001451 memcpy(self->ob_item + old_size * itemsize,
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001452 buffer->buf, n * itemsize);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001453 }
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001454 PyBuffer_Release(buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001455 Py_INCREF(Py_None);
1456 return Py_None;
Guido van Rossum778983b1993-02-19 15:55:02 +00001457}
1458
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001459static PyObject *
1460array_fromstring(arrayobject *self, PyObject *args)
1461{
1462 Py_buffer buffer;
1463 if (PyErr_WarnEx(PyExc_DeprecationWarning,
1464 "fromstring() is deprecated. Use frombytes() instead.", 2) != 0)
1465 return NULL;
1466 if (!PyArg_ParseTuple(args, "s*:fromstring", &buffer))
1467 return NULL;
1468 else
1469 return frombytes(self, &buffer);
1470}
1471
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001472PyDoc_STRVAR(fromstring_doc,
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001473"fromstring(string)\n\
1474\n\
1475Appends items from the string, interpreting it as an array of machine\n\
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001476values, as if it had been read from a file using the fromfile() method).\n\
1477\n\
1478This method is deprecated. Use frombytes instead.");
1479
1480
1481static PyObject *
1482array_frombytes(arrayobject *self, PyObject *args)
1483{
1484 Py_buffer buffer;
1485 if (!PyArg_ParseTuple(args, "y*:frombytes", &buffer))
1486 return NULL;
1487 else
1488 return frombytes(self, &buffer);
1489}
1490
1491PyDoc_STRVAR(frombytes_doc,
1492"frombytes(bytestring)\n\
1493\n\
1494Appends items from the string, interpreting it as an array of machine\n\
Walter Dörwald93b30b52007-06-22 12:21:53 +00001495values, as if it had been read from a file using the fromfile() method).");
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001496
1497
Roger E. Masse2919eaa1996-12-09 20:10:36 +00001498static PyObject *
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001499array_tobytes(arrayobject *self, PyObject *unused)
Guido van Rossum778983b1993-02-19 15:55:02 +00001500{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001501 if (Py_SIZE(self) <= PY_SSIZE_T_MAX / self->ob_descr->itemsize) {
1502 return PyBytes_FromStringAndSize(self->ob_item,
1503 Py_SIZE(self) * self->ob_descr->itemsize);
1504 } else {
1505 return PyErr_NoMemory();
1506 }
Guido van Rossum778983b1993-02-19 15:55:02 +00001507}
1508
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001509PyDoc_STRVAR(tobytes_doc,
1510"tobytes() -> bytes\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001511\n\
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001512Convert the array to an array of machine values and return the bytes\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001513representation.");
Guido van Rossumb39b90d1998-10-13 14:27:22 +00001514
Martin v. Löwis99866332002-03-01 10:27:01 +00001515
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001516static PyObject *
1517array_tostring(arrayobject *self, PyObject *unused)
1518{
Victor Stinner9f0b51e2010-11-09 09:38:30 +00001519 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00001520 "tostring() is deprecated. Use tobytes() instead.", 2) != 0)
1521 return NULL;
1522 return array_tobytes(self, unused);
1523}
1524
1525PyDoc_STRVAR(tostring_doc,
1526"tostring() -> bytes\n\
1527\n\
1528Convert the array to an array of machine values and return the bytes\n\
1529representation.\n\
1530\n\
1531This method is deprecated. Use tobytes instead.");
1532
Martin v. Löwis99866332002-03-01 10:27:01 +00001533
Martin v. Löwis99866332002-03-01 10:27:01 +00001534static PyObject *
1535array_fromunicode(arrayobject *self, PyObject *args)
1536{
Victor Stinner62bb3942012-08-06 00:46:05 +02001537 Py_UNICODE *ustr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001538 Py_ssize_t n;
Victor Stinner62bb3942012-08-06 00:46:05 +02001539 char typecode;
Martin v. Löwis99866332002-03-01 10:27:01 +00001540
Victor Stinner62bb3942012-08-06 00:46:05 +02001541 if (!PyArg_ParseTuple(args, "u#:fromunicode", &ustr, &n))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001542 return NULL;
Victor Stinner62bb3942012-08-06 00:46:05 +02001543 typecode = self->ob_descr->typecode;
Gregory P. Smith9504b132012-12-10 20:20:20 -08001544 if (typecode != 'u') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001545 PyErr_SetString(PyExc_ValueError,
1546 "fromunicode() may only be called on "
1547 "unicode type arrays");
1548 return NULL;
1549 }
1550 if (n > 0) {
1551 Py_ssize_t old_size = Py_SIZE(self);
1552 if (array_resize(self, old_size + n) == -1)
1553 return NULL;
Victor Stinner62bb3942012-08-06 00:46:05 +02001554 memcpy(self->ob_item + old_size * sizeof(Py_UNICODE),
1555 ustr, n * sizeof(Py_UNICODE));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001556 }
Martin v. Löwis99866332002-03-01 10:27:01 +00001557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001558 Py_INCREF(Py_None);
1559 return Py_None;
Martin v. Löwis99866332002-03-01 10:27:01 +00001560}
1561
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001562PyDoc_STRVAR(fromunicode_doc,
Martin v. Löwis99866332002-03-01 10:27:01 +00001563"fromunicode(ustr)\n\
1564\n\
1565Extends this array with data from the unicode string ustr.\n\
Travis E. Oliphantb99f7622007-08-18 11:21:56 +00001566The array must be a unicode type array; otherwise a ValueError\n\
Florent Xiclunac45fb252011-10-24 13:14:55 +02001567is raised. Use array.frombytes(ustr.encode(...)) to\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001568append Unicode data to an array of some other type.");
Martin v. Löwis99866332002-03-01 10:27:01 +00001569
1570
1571static PyObject *
Raymond Hettinger36cd2bf2003-01-03 08:24:58 +00001572array_tounicode(arrayobject *self, PyObject *unused)
Martin v. Löwis99866332002-03-01 10:27:01 +00001573{
Victor Stinner62bb3942012-08-06 00:46:05 +02001574 char typecode;
1575 typecode = self->ob_descr->typecode;
Gregory P. Smith9504b132012-12-10 20:20:20 -08001576 if (typecode != 'u') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001577 PyErr_SetString(PyExc_ValueError,
1578 "tounicode() may only be called on unicode type arrays");
1579 return NULL;
1580 }
Victor Stinner62bb3942012-08-06 00:46:05 +02001581 return PyUnicode_FromUnicode((Py_UNICODE *) self->ob_item, Py_SIZE(self));
Martin v. Löwis99866332002-03-01 10:27:01 +00001582}
1583
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001584PyDoc_STRVAR(tounicode_doc,
Martin v. Löwis99866332002-03-01 10:27:01 +00001585"tounicode() -> unicode\n\
1586\n\
1587Convert the array to a unicode string. The array must be\n\
Travis E. Oliphantb99f7622007-08-18 11:21:56 +00001588a unicode type array; otherwise a ValueError is raised. Use\n\
Florent Xiclunac45fb252011-10-24 13:14:55 +02001589array.tobytes().decode() to obtain a unicode string from\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001590an array of some other type.");
Martin v. Löwis99866332002-03-01 10:27:01 +00001591
Martin v. Löwis99866332002-03-01 10:27:01 +00001592
Meador Inge03b4d502012-08-10 22:35:45 -05001593static PyObject *
1594array_sizeof(arrayobject *self, PyObject *unused)
1595{
1596 Py_ssize_t res;
1597 res = sizeof(arrayobject) + self->allocated * self->ob_descr->itemsize;
1598 return PyLong_FromSsize_t(res);
1599}
1600
1601PyDoc_STRVAR(sizeof_doc,
1602"__sizeof__() -> int\n\
1603\n\
1604Size of the array in memory, in bytes.");
1605
Martin v. Löwis99866332002-03-01 10:27:01 +00001606
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001607/*********************** Pickling support ************************/
1608
1609enum machine_format_code {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001610 UNKNOWN_FORMAT = -1,
1611 /* UNKNOWN_FORMAT is used to indicate that the machine format for an
1612 * array type code cannot be interpreted. When this occurs, a list of
1613 * Python objects is used to represent the content of the array
1614 * instead of using the memory content of the array directly. In that
1615 * case, the array_reconstructor mechanism is bypassed completely, and
1616 * the standard array constructor is used instead.
1617 *
1618 * This is will most likely occur when the machine doesn't use IEEE
1619 * floating-point numbers.
1620 */
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001622 UNSIGNED_INT8 = 0,
1623 SIGNED_INT8 = 1,
1624 UNSIGNED_INT16_LE = 2,
1625 UNSIGNED_INT16_BE = 3,
1626 SIGNED_INT16_LE = 4,
1627 SIGNED_INT16_BE = 5,
1628 UNSIGNED_INT32_LE = 6,
1629 UNSIGNED_INT32_BE = 7,
1630 SIGNED_INT32_LE = 8,
1631 SIGNED_INT32_BE = 9,
1632 UNSIGNED_INT64_LE = 10,
1633 UNSIGNED_INT64_BE = 11,
1634 SIGNED_INT64_LE = 12,
1635 SIGNED_INT64_BE = 13,
1636 IEEE_754_FLOAT_LE = 14,
1637 IEEE_754_FLOAT_BE = 15,
1638 IEEE_754_DOUBLE_LE = 16,
1639 IEEE_754_DOUBLE_BE = 17,
1640 UTF16_LE = 18,
1641 UTF16_BE = 19,
1642 UTF32_LE = 20,
1643 UTF32_BE = 21
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001644};
1645#define MACHINE_FORMAT_CODE_MIN 0
1646#define MACHINE_FORMAT_CODE_MAX 21
1647
1648static const struct mformatdescr {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001649 size_t size;
1650 int is_signed;
1651 int is_big_endian;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001652} mformat_descriptors[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001653 {1, 0, 0}, /* 0: UNSIGNED_INT8 */
1654 {1, 1, 0}, /* 1: SIGNED_INT8 */
1655 {2, 0, 0}, /* 2: UNSIGNED_INT16_LE */
1656 {2, 0, 1}, /* 3: UNSIGNED_INT16_BE */
1657 {2, 1, 0}, /* 4: SIGNED_INT16_LE */
1658 {2, 1, 1}, /* 5: SIGNED_INT16_BE */
1659 {4, 0, 0}, /* 6: UNSIGNED_INT32_LE */
1660 {4, 0, 1}, /* 7: UNSIGNED_INT32_BE */
1661 {4, 1, 0}, /* 8: SIGNED_INT32_LE */
1662 {4, 1, 1}, /* 9: SIGNED_INT32_BE */
1663 {8, 0, 0}, /* 10: UNSIGNED_INT64_LE */
1664 {8, 0, 1}, /* 11: UNSIGNED_INT64_BE */
1665 {8, 1, 0}, /* 12: SIGNED_INT64_LE */
1666 {8, 1, 1}, /* 13: SIGNED_INT64_BE */
1667 {4, 0, 0}, /* 14: IEEE_754_FLOAT_LE */
1668 {4, 0, 1}, /* 15: IEEE_754_FLOAT_BE */
1669 {8, 0, 0}, /* 16: IEEE_754_DOUBLE_LE */
1670 {8, 0, 1}, /* 17: IEEE_754_DOUBLE_BE */
1671 {4, 0, 0}, /* 18: UTF16_LE */
1672 {4, 0, 1}, /* 19: UTF16_BE */
1673 {8, 0, 0}, /* 20: UTF32_LE */
1674 {8, 0, 1} /* 21: UTF32_BE */
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001675};
1676
1677
1678/*
1679 * Internal: This function is used to find the machine format of a given
1680 * array type code. This returns UNKNOWN_FORMAT when the machine format cannot
1681 * be found.
1682 */
1683static enum machine_format_code
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02001684typecode_to_mformat_code(char typecode)
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001685{
Christian Heimes743e0cd2012-10-17 23:52:17 +02001686 const int is_big_endian = PY_BIG_ENDIAN;
1687
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001688 size_t intsize;
1689 int is_signed;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001690
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001691 switch (typecode) {
1692 case 'b':
1693 return SIGNED_INT8;
1694 case 'B':
1695 return UNSIGNED_INT8;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001696
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001697 case 'u':
Victor Stinner62bb3942012-08-06 00:46:05 +02001698 if (sizeof(Py_UNICODE) == 2) {
1699 return UTF16_LE + is_big_endian;
1700 }
1701 if (sizeof(Py_UNICODE) == 4) {
1702 return UTF32_LE + is_big_endian;
1703 }
1704 return UNKNOWN_FORMAT;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001706 case 'f':
1707 if (sizeof(float) == 4) {
1708 const float y = 16711938.0;
1709 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1710 return IEEE_754_FLOAT_BE;
1711 if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1712 return IEEE_754_FLOAT_LE;
1713 }
1714 return UNKNOWN_FORMAT;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001715
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001716 case 'd':
1717 if (sizeof(double) == 8) {
1718 const double x = 9006104071832581.0;
1719 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1720 return IEEE_754_DOUBLE_BE;
1721 if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1722 return IEEE_754_DOUBLE_LE;
1723 }
1724 return UNKNOWN_FORMAT;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001725
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001726 /* Integers */
1727 case 'h':
1728 intsize = sizeof(short);
1729 is_signed = 1;
1730 break;
1731 case 'H':
1732 intsize = sizeof(short);
1733 is_signed = 0;
1734 break;
1735 case 'i':
1736 intsize = sizeof(int);
1737 is_signed = 1;
1738 break;
1739 case 'I':
1740 intsize = sizeof(int);
1741 is_signed = 0;
1742 break;
1743 case 'l':
1744 intsize = sizeof(long);
1745 is_signed = 1;
1746 break;
1747 case 'L':
1748 intsize = sizeof(long);
1749 is_signed = 0;
1750 break;
Meador Inge1c9f0c92011-09-20 19:55:51 -05001751#if HAVE_LONG_LONG
1752 case 'q':
1753 intsize = sizeof(PY_LONG_LONG);
1754 is_signed = 1;
1755 break;
1756 case 'Q':
1757 intsize = sizeof(PY_LONG_LONG);
1758 is_signed = 0;
1759 break;
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02001760#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001761 default:
1762 return UNKNOWN_FORMAT;
1763 }
1764 switch (intsize) {
1765 case 2:
1766 return UNSIGNED_INT16_LE + is_big_endian + (2 * is_signed);
1767 case 4:
1768 return UNSIGNED_INT32_LE + is_big_endian + (2 * is_signed);
1769 case 8:
1770 return UNSIGNED_INT64_LE + is_big_endian + (2 * is_signed);
1771 default:
1772 return UNKNOWN_FORMAT;
1773 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001774}
1775
1776/* Forward declaration. */
1777static PyObject *array_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1778
1779/*
1780 * Internal: This function wraps the array constructor--i.e., array_new()--to
1781 * allow the creation of array objects from C code without having to deal
1782 * directly the tuple argument of array_new(). The typecode argument is a
1783 * Unicode character value, like 'i' or 'f' for example, representing an array
1784 * type code. The items argument is a bytes or a list object from which
1785 * contains the initial value of the array.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001786 *
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001787 * On success, this functions returns the array object created. Otherwise,
1788 * NULL is returned to indicate a failure.
1789 */
1790static PyObject *
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02001791make_array(PyTypeObject *arraytype, char typecode, PyObject *items)
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001792{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001793 PyObject *new_args;
1794 PyObject *array_obj;
1795 PyObject *typecode_obj;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001796
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001797 assert(arraytype != NULL);
1798 assert(items != NULL);
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001799
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02001800 typecode_obj = PyUnicode_FromOrdinal(typecode);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001801 if (typecode_obj == NULL)
1802 return NULL;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001803
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001804 new_args = PyTuple_New(2);
1805 if (new_args == NULL)
1806 return NULL;
1807 Py_INCREF(items);
1808 PyTuple_SET_ITEM(new_args, 0, typecode_obj);
1809 PyTuple_SET_ITEM(new_args, 1, items);
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001811 array_obj = array_new(arraytype, new_args, NULL);
1812 Py_DECREF(new_args);
1813 if (array_obj == NULL)
1814 return NULL;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001816 return array_obj;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001817}
1818
1819/*
1820 * This functions is a special constructor used when unpickling an array. It
1821 * provides a portable way to rebuild an array from its memory representation.
1822 */
1823static PyObject *
1824array_reconstructor(PyObject *self, PyObject *args)
1825{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001826 PyTypeObject *arraytype;
1827 PyObject *items;
1828 PyObject *converted_items;
1829 PyObject *result;
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02001830 int typecode;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001831 enum machine_format_code mformat_code;
1832 struct arraydescr *descr;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001834 if (!PyArg_ParseTuple(args, "OCiO:array._array_reconstructor",
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02001835 &arraytype, &typecode, &mformat_code, &items))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001836 return NULL;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001838 if (!PyType_Check(arraytype)) {
1839 PyErr_Format(PyExc_TypeError,
1840 "first argument must a type object, not %.200s",
1841 Py_TYPE(arraytype)->tp_name);
1842 return NULL;
1843 }
1844 if (!PyType_IsSubtype(arraytype, &Arraytype)) {
1845 PyErr_Format(PyExc_TypeError,
1846 "%.200s is not a subtype of %.200s",
1847 arraytype->tp_name, Arraytype.tp_name);
1848 return NULL;
1849 }
1850 for (descr = descriptors; descr->typecode != '\0'; descr++) {
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02001851 if ((int)descr->typecode == typecode)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001852 break;
1853 }
1854 if (descr->typecode == '\0') {
1855 PyErr_SetString(PyExc_ValueError,
1856 "second argument must be a valid type code");
1857 return NULL;
1858 }
1859 if (mformat_code < MACHINE_FORMAT_CODE_MIN ||
1860 mformat_code > MACHINE_FORMAT_CODE_MAX) {
1861 PyErr_SetString(PyExc_ValueError,
1862 "third argument must be a valid machine format code.");
1863 return NULL;
1864 }
1865 if (!PyBytes_Check(items)) {
1866 PyErr_Format(PyExc_TypeError,
1867 "fourth argument should be bytes, not %.200s",
1868 Py_TYPE(items)->tp_name);
1869 return NULL;
1870 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001871
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001872 /* Fast path: No decoding has to be done. */
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02001873 if (mformat_code == typecode_to_mformat_code((char)typecode) ||
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001874 mformat_code == UNKNOWN_FORMAT) {
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02001875 return make_array(arraytype, (char)typecode, items);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001876 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001878 /* Slow path: Decode the byte string according to the given machine
1879 * format code. This occurs when the computer unpickling the array
1880 * object is architecturally different from the one that pickled the
1881 * array.
1882 */
1883 if (Py_SIZE(items) % mformat_descriptors[mformat_code].size != 0) {
1884 PyErr_SetString(PyExc_ValueError,
1885 "string length not a multiple of item size");
1886 return NULL;
1887 }
1888 switch (mformat_code) {
1889 case IEEE_754_FLOAT_LE:
1890 case IEEE_754_FLOAT_BE: {
1891 int i;
1892 int le = (mformat_code == IEEE_754_FLOAT_LE) ? 1 : 0;
1893 Py_ssize_t itemcount = Py_SIZE(items) / 4;
1894 const unsigned char *memstr =
1895 (unsigned char *)PyBytes_AS_STRING(items);
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001897 converted_items = PyList_New(itemcount);
1898 if (converted_items == NULL)
1899 return NULL;
1900 for (i = 0; i < itemcount; i++) {
1901 PyObject *pyfloat = PyFloat_FromDouble(
1902 _PyFloat_Unpack4(&memstr[i * 4], le));
1903 if (pyfloat == NULL) {
1904 Py_DECREF(converted_items);
1905 return NULL;
1906 }
1907 PyList_SET_ITEM(converted_items, i, pyfloat);
1908 }
1909 break;
1910 }
1911 case IEEE_754_DOUBLE_LE:
1912 case IEEE_754_DOUBLE_BE: {
1913 int i;
1914 int le = (mformat_code == IEEE_754_DOUBLE_LE) ? 1 : 0;
1915 Py_ssize_t itemcount = Py_SIZE(items) / 8;
1916 const unsigned char *memstr =
1917 (unsigned char *)PyBytes_AS_STRING(items);
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001918
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001919 converted_items = PyList_New(itemcount);
1920 if (converted_items == NULL)
1921 return NULL;
1922 for (i = 0; i < itemcount; i++) {
1923 PyObject *pyfloat = PyFloat_FromDouble(
1924 _PyFloat_Unpack8(&memstr[i * 8], le));
1925 if (pyfloat == NULL) {
1926 Py_DECREF(converted_items);
1927 return NULL;
1928 }
1929 PyList_SET_ITEM(converted_items, i, pyfloat);
1930 }
1931 break;
1932 }
1933 case UTF16_LE:
1934 case UTF16_BE: {
1935 int byteorder = (mformat_code == UTF16_LE) ? -1 : 1;
1936 converted_items = PyUnicode_DecodeUTF16(
1937 PyBytes_AS_STRING(items), Py_SIZE(items),
1938 "strict", &byteorder);
1939 if (converted_items == NULL)
1940 return NULL;
1941 break;
1942 }
1943 case UTF32_LE:
1944 case UTF32_BE: {
1945 int byteorder = (mformat_code == UTF32_LE) ? -1 : 1;
1946 converted_items = PyUnicode_DecodeUTF32(
1947 PyBytes_AS_STRING(items), Py_SIZE(items),
1948 "strict", &byteorder);
1949 if (converted_items == NULL)
1950 return NULL;
1951 break;
1952 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001953
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001954 case UNSIGNED_INT8:
1955 case SIGNED_INT8:
1956 case UNSIGNED_INT16_LE:
1957 case UNSIGNED_INT16_BE:
1958 case SIGNED_INT16_LE:
1959 case SIGNED_INT16_BE:
1960 case UNSIGNED_INT32_LE:
1961 case UNSIGNED_INT32_BE:
1962 case SIGNED_INT32_LE:
1963 case SIGNED_INT32_BE:
1964 case UNSIGNED_INT64_LE:
1965 case UNSIGNED_INT64_BE:
1966 case SIGNED_INT64_LE:
1967 case SIGNED_INT64_BE: {
1968 int i;
1969 const struct mformatdescr mf_descr =
1970 mformat_descriptors[mformat_code];
1971 Py_ssize_t itemcount = Py_SIZE(items) / mf_descr.size;
1972 const unsigned char *memstr =
1973 (unsigned char *)PyBytes_AS_STRING(items);
1974 struct arraydescr *descr;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001975
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001976 /* If possible, try to pack array's items using a data type
1977 * that fits better. This may result in an array with narrower
1978 * or wider elements.
1979 *
1980 * For example, if a 32-bit machine pickles a L-code array of
1981 * unsigned longs, then the array will be unpickled by 64-bit
1982 * machine as an I-code array of unsigned ints.
1983 *
1984 * XXX: Is it possible to write a unit test for this?
1985 */
1986 for (descr = descriptors; descr->typecode != '\0'; descr++) {
1987 if (descr->is_integer_type &&
1988 descr->itemsize == mf_descr.size &&
1989 descr->is_signed == mf_descr.is_signed)
1990 typecode = descr->typecode;
1991 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001993 converted_items = PyList_New(itemcount);
1994 if (converted_items == NULL)
1995 return NULL;
1996 for (i = 0; i < itemcount; i++) {
1997 PyObject *pylong;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00001998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001999 pylong = _PyLong_FromByteArray(
2000 &memstr[i * mf_descr.size],
2001 mf_descr.size,
2002 !mf_descr.is_big_endian,
2003 mf_descr.is_signed);
2004 if (pylong == NULL) {
2005 Py_DECREF(converted_items);
2006 return NULL;
2007 }
2008 PyList_SET_ITEM(converted_items, i, pylong);
2009 }
2010 break;
2011 }
2012 case UNKNOWN_FORMAT:
2013 /* Impossible, but needed to shut up GCC about the unhandled
2014 * enumeration value.
2015 */
2016 default:
2017 PyErr_BadArgument();
2018 return NULL;
2019 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002020
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02002021 result = make_array(arraytype, (char)typecode, converted_items);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002022 Py_DECREF(converted_items);
2023 return result;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002024}
2025
2026static PyObject *
2027array_reduce_ex(arrayobject *array, PyObject *value)
2028{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002029 PyObject *dict;
2030 PyObject *result;
2031 PyObject *array_str;
2032 int typecode = array->ob_descr->typecode;
2033 int mformat_code;
2034 static PyObject *array_reconstructor = NULL;
2035 long protocol;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002036 _Py_IDENTIFIER(_array_reconstructor);
2037 _Py_IDENTIFIER(__dict__);
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002039 if (array_reconstructor == NULL) {
2040 PyObject *array_module = PyImport_ImportModule("array");
2041 if (array_module == NULL)
2042 return NULL;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002043 array_reconstructor = _PyObject_GetAttrId(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002044 array_module,
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002045 &PyId__array_reconstructor);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002046 Py_DECREF(array_module);
2047 if (array_reconstructor == NULL)
2048 return NULL;
2049 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002051 if (!PyLong_Check(value)) {
2052 PyErr_SetString(PyExc_TypeError,
2053 "__reduce_ex__ argument should an integer");
2054 return NULL;
2055 }
2056 protocol = PyLong_AsLong(value);
2057 if (protocol == -1 && PyErr_Occurred())
2058 return NULL;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002059
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002060 dict = _PyObject_GetAttrId((PyObject *)array, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002061 if (dict == NULL) {
2062 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
2063 return NULL;
2064 PyErr_Clear();
2065 dict = Py_None;
2066 Py_INCREF(dict);
2067 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002068
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002069 mformat_code = typecode_to_mformat_code(typecode);
2070 if (mformat_code == UNKNOWN_FORMAT || protocol < 3) {
2071 /* Convert the array to a list if we got something weird
2072 * (e.g., non-IEEE floats), or we are pickling the array using
2073 * a Python 2.x compatible protocol.
2074 *
2075 * It is necessary to use a list representation for Python 2.x
2076 * compatible pickle protocol, since Python 2's str objects
2077 * are unpickled as unicode by Python 3. Thus it is impossible
2078 * to make arrays unpicklable by Python 3 by using their memory
2079 * representation, unless we resort to ugly hacks such as
2080 * coercing unicode objects to bytes in array_reconstructor.
2081 */
2082 PyObject *list;
2083 list = array_tolist(array, NULL);
2084 if (list == NULL) {
2085 Py_DECREF(dict);
2086 return NULL;
2087 }
2088 result = Py_BuildValue(
2089 "O(CO)O", Py_TYPE(array), typecode, list, dict);
2090 Py_DECREF(list);
2091 Py_DECREF(dict);
2092 return result;
2093 }
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002094
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00002095 array_str = array_tobytes(array, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002096 if (array_str == NULL) {
2097 Py_DECREF(dict);
2098 return NULL;
2099 }
2100 result = Py_BuildValue(
2101 "O(OCiN)O", array_reconstructor, Py_TYPE(array), typecode,
2102 mformat_code, array_str, dict);
2103 Py_DECREF(dict);
2104 return result;
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002105}
2106
2107PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
2108
Martin v. Löwis99866332002-03-01 10:27:01 +00002109static PyObject *
2110array_get_typecode(arrayobject *a, void *closure)
2111{
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02002112 char typecode = a->ob_descr->typecode;
2113 return PyUnicode_FromOrdinal(typecode);
Martin v. Löwis99866332002-03-01 10:27:01 +00002114}
2115
2116static PyObject *
2117array_get_itemsize(arrayobject *a, void *closure)
2118{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002119 return PyLong_FromLong((long)a->ob_descr->itemsize);
Martin v. Löwis99866332002-03-01 10:27:01 +00002120}
2121
2122static PyGetSetDef array_getsets [] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002123 {"typecode", (getter) array_get_typecode, NULL,
2124 "the typecode character used to create the array"},
2125 {"itemsize", (getter) array_get_itemsize, NULL,
2126 "the size, in bytes, of one array item"},
2127 {NULL}
Martin v. Löwis99866332002-03-01 10:27:01 +00002128};
2129
Martin v. Löwis59683e82008-06-13 07:50:45 +00002130static PyMethodDef array_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002131 {"append", (PyCFunction)array_append, METH_O,
2132 append_doc},
Eli Bendersky03ab4d32012-12-31 15:34:20 -08002133 {"buffer_info", (PyCFunction)array_buffer_info, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002134 buffer_info_doc},
2135 {"byteswap", (PyCFunction)array_byteswap, METH_NOARGS,
2136 byteswap_doc},
2137 {"__copy__", (PyCFunction)array_copy, METH_NOARGS,
2138 copy_doc},
2139 {"count", (PyCFunction)array_count, METH_O,
2140 count_doc},
Eli Bendersky03ab4d32012-12-31 15:34:20 -08002141 {"__deepcopy__", (PyCFunction)array_copy, METH_O,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002142 copy_doc},
Eli Bendersky03ab4d32012-12-31 15:34:20 -08002143 {"extend", (PyCFunction)array_extend, METH_O,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002144 extend_doc},
2145 {"fromfile", (PyCFunction)array_fromfile, METH_VARARGS,
2146 fromfile_doc},
2147 {"fromlist", (PyCFunction)array_fromlist, METH_O,
2148 fromlist_doc},
2149 {"fromstring", (PyCFunction)array_fromstring, METH_VARARGS,
2150 fromstring_doc},
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00002151 {"frombytes", (PyCFunction)array_frombytes, METH_VARARGS,
2152 frombytes_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002153 {"fromunicode", (PyCFunction)array_fromunicode, METH_VARARGS,
2154 fromunicode_doc},
2155 {"index", (PyCFunction)array_index, METH_O,
2156 index_doc},
2157 {"insert", (PyCFunction)array_insert, METH_VARARGS,
2158 insert_doc},
2159 {"pop", (PyCFunction)array_pop, METH_VARARGS,
2160 pop_doc},
Eli Bendersky03ab4d32012-12-31 15:34:20 -08002161 {"__reduce_ex__", (PyCFunction)array_reduce_ex, METH_O,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002162 reduce_doc},
2163 {"remove", (PyCFunction)array_remove, METH_O,
2164 remove_doc},
2165 {"reverse", (PyCFunction)array_reverse, METH_NOARGS,
2166 reverse_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002167 {"tofile", (PyCFunction)array_tofile, METH_O,
2168 tofile_doc},
2169 {"tolist", (PyCFunction)array_tolist, METH_NOARGS,
2170 tolist_doc},
2171 {"tostring", (PyCFunction)array_tostring, METH_NOARGS,
2172 tostring_doc},
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00002173 {"tobytes", (PyCFunction)array_tobytes, METH_NOARGS,
2174 tobytes_doc},
Eli Bendersky03ab4d32012-12-31 15:34:20 -08002175 {"tounicode", (PyCFunction)array_tounicode, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002176 tounicode_doc},
Meador Inge03b4d502012-08-10 22:35:45 -05002177 {"__sizeof__", (PyCFunction)array_sizeof, METH_NOARGS,
2178 sizeof_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002179 {NULL, NULL} /* sentinel */
Guido van Rossum778983b1993-02-19 15:55:02 +00002180};
2181
Roger E. Masse2919eaa1996-12-09 20:10:36 +00002182static PyObject *
Peter Schneider-Kamp9656abd2000-07-13 21:10:57 +00002183array_repr(arrayobject *a)
Guido van Rossum778983b1993-02-19 15:55:02 +00002184{
Victor Stinnerf8bb7d02011-09-30 00:03:59 +02002185 char typecode;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002186 PyObject *s, *v = NULL;
2187 Py_ssize_t len;
Martin v. Löwis99866332002-03-01 10:27:01 +00002188
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002189 len = Py_SIZE(a);
2190 typecode = a->ob_descr->typecode;
2191 if (len == 0) {
Amaury Forgeot d'Arc24aa26b2010-11-25 08:13:35 +00002192 return PyUnicode_FromFormat("array('%c')", (int)typecode);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002193 }
Gregory P. Smith9504b132012-12-10 20:20:20 -08002194 if (typecode == 'u') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002195 v = array_tounicode(a, NULL);
Gregory P. Smith9504b132012-12-10 20:20:20 -08002196 } else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002197 v = array_tolist(a, NULL);
Gregory P. Smith9504b132012-12-10 20:20:20 -08002198 }
Victor Stinner29ec5952013-02-26 00:27:38 +01002199 if (v == NULL)
2200 return NULL;
Raymond Hettinger88ba1e32003-04-23 17:27:00 +00002201
Amaury Forgeot d'Arc24aa26b2010-11-25 08:13:35 +00002202 s = PyUnicode_FromFormat("array('%c', %R)", (int)typecode, v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002203 Py_DECREF(v);
2204 return s;
Guido van Rossum778983b1993-02-19 15:55:02 +00002205}
2206
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002207static PyObject*
2208array_subscr(arrayobject* self, PyObject* item)
2209{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002210 if (PyIndex_Check(item)) {
2211 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
2212 if (i==-1 && PyErr_Occurred()) {
2213 return NULL;
2214 }
2215 if (i < 0)
2216 i += Py_SIZE(self);
2217 return array_item(self, i);
2218 }
2219 else if (PySlice_Check(item)) {
2220 Py_ssize_t start, stop, step, slicelength, cur, i;
2221 PyObject* result;
2222 arrayobject* ar;
2223 int itemsize = self->ob_descr->itemsize;
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002224
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002225 if (PySlice_GetIndicesEx(item, Py_SIZE(self),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002226 &start, &stop, &step, &slicelength) < 0) {
2227 return NULL;
2228 }
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002230 if (slicelength <= 0) {
2231 return newarrayobject(&Arraytype, 0, self->ob_descr);
2232 }
2233 else if (step == 1) {
2234 PyObject *result = newarrayobject(&Arraytype,
2235 slicelength, self->ob_descr);
2236 if (result == NULL)
2237 return NULL;
2238 memcpy(((arrayobject *)result)->ob_item,
2239 self->ob_item + start * itemsize,
2240 slicelength * itemsize);
2241 return result;
2242 }
2243 else {
2244 result = newarrayobject(&Arraytype, slicelength, self->ob_descr);
2245 if (!result) return NULL;
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002247 ar = (arrayobject*)result;
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002249 for (cur = start, i = 0; i < slicelength;
2250 cur += step, i++) {
2251 memcpy(ar->ob_item + i*itemsize,
2252 self->ob_item + cur*itemsize,
2253 itemsize);
2254 }
2255
2256 return result;
2257 }
2258 }
2259 else {
2260 PyErr_SetString(PyExc_TypeError,
2261 "array indices must be integers");
2262 return NULL;
2263 }
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002264}
2265
2266static int
2267array_ass_subscr(arrayobject* self, PyObject* item, PyObject* value)
2268{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002269 Py_ssize_t start, stop, step, slicelength, needed;
2270 arrayobject* other;
2271 int itemsize;
Thomas Woutersed03b412007-08-28 21:37:11 +00002272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002273 if (PyIndex_Check(item)) {
2274 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Alexandre Vassalotti47137252009-07-05 19:57:00 +00002275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002276 if (i == -1 && PyErr_Occurred())
2277 return -1;
2278 if (i < 0)
2279 i += Py_SIZE(self);
2280 if (i < 0 || i >= Py_SIZE(self)) {
2281 PyErr_SetString(PyExc_IndexError,
2282 "array assignment index out of range");
2283 return -1;
2284 }
2285 if (value == NULL) {
2286 /* Fall through to slice assignment */
2287 start = i;
2288 stop = i + 1;
2289 step = 1;
2290 slicelength = 1;
2291 }
2292 else
2293 return (*self->ob_descr->setitem)(self, i, value);
2294 }
2295 else if (PySlice_Check(item)) {
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002296 if (PySlice_GetIndicesEx(item,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002297 Py_SIZE(self), &start, &stop,
2298 &step, &slicelength) < 0) {
2299 return -1;
2300 }
2301 }
2302 else {
2303 PyErr_SetString(PyExc_TypeError,
2304 "array indices must be integer");
2305 return -1;
2306 }
2307 if (value == NULL) {
2308 other = NULL;
2309 needed = 0;
2310 }
2311 else if (array_Check(value)) {
2312 other = (arrayobject *)value;
2313 needed = Py_SIZE(other);
2314 if (self == other) {
2315 /* Special case "self[i:j] = self" -- copy self first */
2316 int ret;
2317 value = array_slice(other, 0, needed);
2318 if (value == NULL)
2319 return -1;
2320 ret = array_ass_subscr(self, item, value);
2321 Py_DECREF(value);
2322 return ret;
2323 }
2324 if (other->ob_descr != self->ob_descr) {
2325 PyErr_BadArgument();
2326 return -1;
2327 }
2328 }
2329 else {
2330 PyErr_Format(PyExc_TypeError,
2331 "can only assign array (not \"%.200s\") to array slice",
2332 Py_TYPE(value)->tp_name);
2333 return -1;
2334 }
2335 itemsize = self->ob_descr->itemsize;
2336 /* for 'a[2:1] = ...', the insertion point is 'start', not 'stop' */
2337 if ((step > 0 && stop < start) ||
2338 (step < 0 && stop > start))
2339 stop = start;
Alexandre Vassalotti47137252009-07-05 19:57:00 +00002340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002341 /* Issue #4509: If the array has exported buffers and the slice
2342 assignment would change the size of the array, fail early to make
2343 sure we don't modify it. */
2344 if ((needed == 0 || slicelength != needed) && self->ob_exports > 0) {
2345 PyErr_SetString(PyExc_BufferError,
2346 "cannot resize an array that is exporting buffers");
2347 return -1;
2348 }
Mark Dickinsonbc099642010-01-29 17:27:24 +00002349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002350 if (step == 1) {
2351 if (slicelength > needed) {
2352 memmove(self->ob_item + (start + needed) * itemsize,
2353 self->ob_item + stop * itemsize,
2354 (Py_SIZE(self) - stop) * itemsize);
2355 if (array_resize(self, Py_SIZE(self) +
2356 needed - slicelength) < 0)
2357 return -1;
2358 }
2359 else if (slicelength < needed) {
2360 if (array_resize(self, Py_SIZE(self) +
2361 needed - slicelength) < 0)
2362 return -1;
2363 memmove(self->ob_item + (start + needed) * itemsize,
2364 self->ob_item + stop * itemsize,
2365 (Py_SIZE(self) - start - needed) * itemsize);
2366 }
2367 if (needed > 0)
2368 memcpy(self->ob_item + start * itemsize,
2369 other->ob_item, needed * itemsize);
2370 return 0;
2371 }
2372 else if (needed == 0) {
2373 /* Delete slice */
2374 size_t cur;
2375 Py_ssize_t i;
Thomas Woutersed03b412007-08-28 21:37:11 +00002376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002377 if (step < 0) {
2378 stop = start + 1;
2379 start = stop + step * (slicelength - 1) - 1;
2380 step = -step;
2381 }
2382 for (cur = start, i = 0; i < slicelength;
2383 cur += step, i++) {
2384 Py_ssize_t lim = step - 1;
Thomas Woutersed03b412007-08-28 21:37:11 +00002385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002386 if (cur + step >= (size_t)Py_SIZE(self))
2387 lim = Py_SIZE(self) - cur - 1;
2388 memmove(self->ob_item + (cur - i) * itemsize,
2389 self->ob_item + (cur + 1) * itemsize,
2390 lim * itemsize);
2391 }
Mark Dickinsonc7d93b72011-09-25 15:34:32 +01002392 cur = start + (size_t)slicelength * step;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002393 if (cur < (size_t)Py_SIZE(self)) {
2394 memmove(self->ob_item + (cur-slicelength) * itemsize,
2395 self->ob_item + cur * itemsize,
2396 (Py_SIZE(self) - cur) * itemsize);
2397 }
2398 if (array_resize(self, Py_SIZE(self) - slicelength) < 0)
2399 return -1;
2400 return 0;
2401 }
2402 else {
2403 Py_ssize_t cur, i;
2404
2405 if (needed != slicelength) {
2406 PyErr_Format(PyExc_ValueError,
2407 "attempt to assign array of size %zd "
2408 "to extended slice of size %zd",
2409 needed, slicelength);
2410 return -1;
2411 }
2412 for (cur = start, i = 0; i < slicelength;
2413 cur += step, i++) {
2414 memcpy(self->ob_item + cur * itemsize,
2415 other->ob_item + i * itemsize,
2416 itemsize);
2417 }
2418 return 0;
2419 }
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002420}
2421
2422static PyMappingMethods array_as_mapping = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002423 (lenfunc)array_length,
2424 (binaryfunc)array_subscr,
2425 (objobjargproc)array_ass_subscr
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002426};
2427
Guido van Rossumd8faa362007-04-27 19:54:29 +00002428static const void *emptybuf = "";
2429
Travis E. Oliphantb99f7622007-08-18 11:21:56 +00002430
2431static int
Travis E. Oliphant8ae62b62007-09-23 02:00:13 +00002432array_buffer_getbuf(arrayobject *self, Py_buffer *view, int flags)
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00002433{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002434 if (view==NULL) goto finish;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +00002435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002436 view->buf = (void *)self->ob_item;
2437 view->obj = (PyObject*)self;
2438 Py_INCREF(self);
2439 if (view->buf == NULL)
2440 view->buf = (void *)emptybuf;
2441 view->len = (Py_SIZE(self)) * self->ob_descr->itemsize;
2442 view->readonly = 0;
2443 view->ndim = 1;
2444 view->itemsize = self->ob_descr->itemsize;
2445 view->suboffsets = NULL;
2446 view->shape = NULL;
2447 if ((flags & PyBUF_ND)==PyBUF_ND) {
2448 view->shape = &((Py_SIZE(self)));
2449 }
2450 view->strides = NULL;
2451 if ((flags & PyBUF_STRIDES)==PyBUF_STRIDES)
2452 view->strides = &(view->itemsize);
2453 view->format = NULL;
2454 view->internal = NULL;
Victor Stinner62bb3942012-08-06 00:46:05 +02002455 if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002456 view->format = self->ob_descr->formats;
Victor Stinner62bb3942012-08-06 00:46:05 +02002457#ifdef Py_UNICODE_WIDE
2458 if (self->ob_descr->typecode == 'u') {
2459 view->format = "w";
2460 }
2461#endif
2462 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +00002463
2464 finish:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002465 self->ob_exports++;
2466 return 0;
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00002467}
2468
Travis E. Oliphantb99f7622007-08-18 11:21:56 +00002469static void
Travis E. Oliphant8ae62b62007-09-23 02:00:13 +00002470array_buffer_relbuf(arrayobject *self, Py_buffer *view)
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00002471{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002472 self->ob_exports--;
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00002473}
2474
Roger E. Masse2919eaa1996-12-09 20:10:36 +00002475static PySequenceMethods array_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002476 (lenfunc)array_length, /*sq_length*/
2477 (binaryfunc)array_concat, /*sq_concat*/
2478 (ssizeargfunc)array_repeat, /*sq_repeat*/
2479 (ssizeargfunc)array_item, /*sq_item*/
2480 0, /*sq_slice*/
2481 (ssizeobjargproc)array_ass_item, /*sq_ass_item*/
2482 0, /*sq_ass_slice*/
2483 (objobjproc)array_contains, /*sq_contains*/
2484 (binaryfunc)array_inplace_concat, /*sq_inplace_concat*/
2485 (ssizeargfunc)array_inplace_repeat /*sq_inplace_repeat*/
Guido van Rossum778983b1993-02-19 15:55:02 +00002486};
2487
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00002488static PyBufferProcs array_as_buffer = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002489 (getbufferproc)array_buffer_getbuf,
2490 (releasebufferproc)array_buffer_relbuf
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00002491};
2492
Roger E. Masse2919eaa1996-12-09 20:10:36 +00002493static PyObject *
Martin v. Löwis99866332002-03-01 10:27:01 +00002494array_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossum778983b1993-02-19 15:55:02 +00002495{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002496 int c;
2497 PyObject *initial = NULL, *it = NULL;
2498 struct arraydescr *descr;
Martin v. Löwis99866332002-03-01 10:27:01 +00002499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002500 if (type == &Arraytype && !_PyArg_NoKeywords("array.array()", kwds))
2501 return NULL;
Martin v. Löwis99866332002-03-01 10:27:01 +00002502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002503 if (!PyArg_ParseTuple(args, "C|O:array", &c, &initial))
2504 return NULL;
Raymond Hettinger84fc9aa2003-04-24 10:41:55 +00002505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002506 if (!(initial == NULL || PyList_Check(initial)
2507 || PyByteArray_Check(initial)
2508 || PyBytes_Check(initial)
2509 || PyTuple_Check(initial)
Alexander Belopolskyef4a03f2011-01-11 21:44:00 +00002510 || ((c=='u') && PyUnicode_Check(initial))
2511 || (array_Check(initial)
2512 && c == ((arrayobject*)initial)->ob_descr->typecode))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002513 it = PyObject_GetIter(initial);
2514 if (it == NULL)
2515 return NULL;
2516 /* We set initial to NULL so that the subsequent code
2517 will create an empty array of the appropriate type
2518 and afterwards we can use array_iter_extend to populate
2519 the array.
2520 */
2521 initial = NULL;
2522 }
2523 for (descr = descriptors; descr->typecode != '\0'; descr++) {
2524 if (descr->typecode == c) {
2525 PyObject *a;
2526 Py_ssize_t len;
Martin v. Löwis99866332002-03-01 10:27:01 +00002527
Alexander Belopolskyef4a03f2011-01-11 21:44:00 +00002528 if (initial == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002529 len = 0;
Alexander Belopolskyef4a03f2011-01-11 21:44:00 +00002530 else if (PyList_Check(initial))
2531 len = PyList_GET_SIZE(initial);
2532 else if (PyTuple_Check(initial) || array_Check(initial))
2533 len = Py_SIZE(initial);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002534 else
Alexander Belopolskyef4a03f2011-01-11 21:44:00 +00002535 len = 0;
Martin v. Löwis99866332002-03-01 10:27:01 +00002536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002537 a = newarrayobject(type, len, descr);
2538 if (a == NULL)
2539 return NULL;
2540
Alexander Belopolskyef4a03f2011-01-11 21:44:00 +00002541 if (len > 0 && !array_Check(initial)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002542 Py_ssize_t i;
2543 for (i = 0; i < len; i++) {
2544 PyObject *v =
2545 PySequence_GetItem(initial, i);
2546 if (v == NULL) {
2547 Py_DECREF(a);
2548 return NULL;
2549 }
2550 if (setarrayitem(a, i, v) != 0) {
2551 Py_DECREF(v);
2552 Py_DECREF(a);
2553 return NULL;
2554 }
2555 Py_DECREF(v);
2556 }
2557 }
2558 else if (initial != NULL && (PyByteArray_Check(initial) ||
2559 PyBytes_Check(initial))) {
2560 PyObject *t_initial, *v;
2561 t_initial = PyTuple_Pack(1, initial);
2562 if (t_initial == NULL) {
2563 Py_DECREF(a);
2564 return NULL;
2565 }
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +00002566 v = array_frombytes((arrayobject *)a,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002567 t_initial);
2568 Py_DECREF(t_initial);
2569 if (v == NULL) {
2570 Py_DECREF(a);
2571 return NULL;
2572 }
2573 Py_DECREF(v);
2574 }
2575 else if (initial != NULL && PyUnicode_Check(initial)) {
Victor Stinner62bb3942012-08-06 00:46:05 +02002576 Py_UNICODE *ustr;
Victor Stinner1fbcaef2011-09-30 01:54:04 +02002577 Py_ssize_t n;
Victor Stinner62bb3942012-08-06 00:46:05 +02002578
2579 ustr = PyUnicode_AsUnicode(initial);
2580 if (ustr == NULL) {
2581 PyErr_NoMemory();
Victor Stinner1fbcaef2011-09-30 01:54:04 +02002582 Py_DECREF(a);
2583 return NULL;
2584 }
Victor Stinner62bb3942012-08-06 00:46:05 +02002585
2586 n = PyUnicode_GET_DATA_SIZE(initial);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002587 if (n > 0) {
2588 arrayobject *self = (arrayobject *)a;
Victor Stinner62bb3942012-08-06 00:46:05 +02002589 char *item = self->ob_item;
2590 item = (char *)PyMem_Realloc(item, n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002591 if (item == NULL) {
2592 PyErr_NoMemory();
2593 Py_DECREF(a);
2594 return NULL;
2595 }
Victor Stinner62bb3942012-08-06 00:46:05 +02002596 self->ob_item = item;
2597 Py_SIZE(self) = n / sizeof(Py_UNICODE);
2598 memcpy(item, ustr, n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002599 self->allocated = Py_SIZE(self);
2600 }
2601 }
Alexander Belopolskyef4a03f2011-01-11 21:44:00 +00002602 else if (initial != NULL && array_Check(initial)) {
2603 arrayobject *self = (arrayobject *)a;
2604 arrayobject *other = (arrayobject *)initial;
2605 memcpy(self->ob_item, other->ob_item, len * other->ob_descr->itemsize);
2606 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002607 if (it != NULL) {
2608 if (array_iter_extend((arrayobject *)a, it) == -1) {
2609 Py_DECREF(it);
2610 Py_DECREF(a);
2611 return NULL;
2612 }
2613 Py_DECREF(it);
2614 }
2615 return a;
2616 }
2617 }
2618 PyErr_SetString(PyExc_ValueError,
Meador Inge1c9f0c92011-09-20 19:55:51 -05002619#ifdef HAVE_LONG_LONG
2620 "bad typecode (must be b, B, u, h, H, i, I, l, L, q, Q, f or d)");
2621#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002622 "bad typecode (must be b, B, u, h, H, i, I, l, L, f or d)");
Meador Inge1c9f0c92011-09-20 19:55:51 -05002623#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002624 return NULL;
Guido van Rossum778983b1993-02-19 15:55:02 +00002625}
2626
Guido van Rossum778983b1993-02-19 15:55:02 +00002627
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002628PyDoc_STRVAR(module_doc,
Martin v. Löwis99866332002-03-01 10:27:01 +00002629"This module defines an object type which can efficiently represent\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002630an array of basic values: characters, integers, floating point\n\
2631numbers. Arrays are sequence types and behave very much like lists,\n\
2632except that the type of objects stored in them is constrained. The\n\
2633type is specified at object creation time by using a type code, which\n\
2634is a single character. The following type codes are defined:\n\
2635\n\
2636 Type code C Type Minimum size in bytes \n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002637 'b' signed integer 1 \n\
2638 'B' unsigned integer 1 \n\
Victor Stinner62bb3942012-08-06 00:46:05 +02002639 'u' Unicode character 2 (see note) \n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002640 'h' signed integer 2 \n\
2641 'H' unsigned integer 2 \n\
2642 'i' signed integer 2 \n\
2643 'I' unsigned integer 2 \n\
2644 'l' signed integer 4 \n\
2645 'L' unsigned integer 4 \n\
Meador Inge1c9f0c92011-09-20 19:55:51 -05002646 'q' signed integer 8 (see note) \n\
2647 'Q' unsigned integer 8 (see note) \n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002648 'f' floating point 4 \n\
2649 'd' floating point 8 \n\
2650\n\
Victor Stinner62bb3942012-08-06 00:46:05 +02002651NOTE: The 'u' typecode corresponds to Python's unicode character. On \n\
2652narrow builds this is 2-bytes on wide builds this is 4-bytes.\n\
2653\n\
Meador Inge1c9f0c92011-09-20 19:55:51 -05002654NOTE: The 'q' and 'Q' type codes are only available if the platform \n\
2655C compiler used to build Python supports 'long long', or, on Windows, \n\
2656'__int64'.\n\
2657\n\
Martin v. Löwis99866332002-03-01 10:27:01 +00002658The constructor is:\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002659\n\
2660array(typecode [, initializer]) -- create a new array\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002661");
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002662
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002663PyDoc_STRVAR(arraytype_doc,
Martin v. Löwis99866332002-03-01 10:27:01 +00002664"array(typecode [, initializer]) -> array\n\
2665\n\
2666Return a new array whose items are restricted by typecode, and\n\
Raymond Hettinger6ab78cd2004-08-29 07:50:43 +00002667initialized from the optional initializer value, which must be a list,\n\
Florent Xicluna0e686cb2011-12-09 23:41:19 +01002668string or iterable over elements of the appropriate type.\n\
Martin v. Löwis99866332002-03-01 10:27:01 +00002669\n\
2670Arrays represent basic values and behave very much like lists, except\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002671the type of objects stored in them is constrained.\n\
2672\n\
2673Methods:\n\
2674\n\
2675append() -- append a new item to the end of the array\n\
2676buffer_info() -- return information giving the current memory info\n\
2677byteswap() -- byteswap all the items of the array\n\
Mark Dickinson934896d2009-02-21 20:59:32 +00002678count() -- return number of occurrences of an object\n\
Raymond Hettinger49f9bd12004-03-14 05:43:59 +00002679extend() -- extend array by appending multiple elements from an iterable\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002680fromfile() -- read items from a file object\n\
2681fromlist() -- append items from the list\n\
Florent Xiclunac45fb252011-10-24 13:14:55 +02002682frombytes() -- append items from the string\n\
Mark Dickinson934896d2009-02-21 20:59:32 +00002683index() -- return index of first occurrence of an object\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002684insert() -- insert a new item into the array at a provided position\n\
Peter Schneider-Kamp5a65c2d2000-07-31 20:52:21 +00002685pop() -- remove and return item (default last)\n\
Mark Dickinson934896d2009-02-21 20:59:32 +00002686remove() -- remove first occurrence of an object\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002687reverse() -- reverse the order of the items in the array\n\
2688tofile() -- write all items to a file object\n\
2689tolist() -- return the array converted to an ordinary list\n\
Florent Xiclunac45fb252011-10-24 13:14:55 +02002690tobytes() -- return the array converted to a string\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002691\n\
Martin v. Löwis99866332002-03-01 10:27:01 +00002692Attributes:\n\
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002693\n\
2694typecode -- the typecode character used to create the array\n\
2695itemsize -- the length in bytes of one array item\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002696");
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002697
Raymond Hettinger625812f2003-01-07 01:58:52 +00002698static PyObject *array_iter(arrayobject *ao);
2699
Tim Peters0c322792002-07-17 16:49:03 +00002700static PyTypeObject Arraytype = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002701 PyVarObject_HEAD_INIT(NULL, 0)
2702 "array.array",
2703 sizeof(arrayobject),
2704 0,
2705 (destructor)array_dealloc, /* tp_dealloc */
2706 0, /* tp_print */
2707 0, /* tp_getattr */
2708 0, /* tp_setattr */
2709 0, /* tp_reserved */
2710 (reprfunc)array_repr, /* tp_repr */
2711 0, /* tp_as_number*/
2712 &array_as_sequence, /* tp_as_sequence*/
2713 &array_as_mapping, /* tp_as_mapping*/
2714 0, /* tp_hash */
2715 0, /* tp_call */
2716 0, /* tp_str */
2717 PyObject_GenericGetAttr, /* tp_getattro */
2718 0, /* tp_setattro */
2719 &array_as_buffer, /* tp_as_buffer*/
2720 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
2721 arraytype_doc, /* tp_doc */
2722 0, /* tp_traverse */
2723 0, /* tp_clear */
2724 array_richcompare, /* tp_richcompare */
2725 offsetof(arrayobject, weakreflist), /* tp_weaklistoffset */
2726 (getiterfunc)array_iter, /* tp_iter */
2727 0, /* tp_iternext */
2728 array_methods, /* tp_methods */
2729 0, /* tp_members */
2730 array_getsets, /* tp_getset */
2731 0, /* tp_base */
2732 0, /* tp_dict */
2733 0, /* tp_descr_get */
2734 0, /* tp_descr_set */
2735 0, /* tp_dictoffset */
2736 0, /* tp_init */
2737 PyType_GenericAlloc, /* tp_alloc */
2738 array_new, /* tp_new */
2739 PyObject_Del, /* tp_free */
Guido van Rossumb39b90d1998-10-13 14:27:22 +00002740};
2741
Raymond Hettinger625812f2003-01-07 01:58:52 +00002742
2743/*********************** Array Iterator **************************/
2744
2745typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002746 PyObject_HEAD
2747 Py_ssize_t index;
2748 arrayobject *ao;
2749 PyObject * (*getitem)(struct arrayobject *, Py_ssize_t);
Raymond Hettinger625812f2003-01-07 01:58:52 +00002750} arrayiterobject;
2751
2752static PyTypeObject PyArrayIter_Type;
2753
2754#define PyArrayIter_Check(op) PyObject_TypeCheck(op, &PyArrayIter_Type)
2755
2756static PyObject *
2757array_iter(arrayobject *ao)
2758{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002759 arrayiterobject *it;
Raymond Hettinger625812f2003-01-07 01:58:52 +00002760
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002761 if (!array_Check(ao)) {
2762 PyErr_BadInternalCall();
2763 return NULL;
2764 }
Raymond Hettinger625812f2003-01-07 01:58:52 +00002765
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002766 it = PyObject_GC_New(arrayiterobject, &PyArrayIter_Type);
2767 if (it == NULL)
2768 return NULL;
Raymond Hettinger625812f2003-01-07 01:58:52 +00002769
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002770 Py_INCREF(ao);
2771 it->ao = ao;
2772 it->index = 0;
2773 it->getitem = ao->ob_descr->getitem;
2774 PyObject_GC_Track(it);
2775 return (PyObject *)it;
Raymond Hettinger625812f2003-01-07 01:58:52 +00002776}
2777
2778static PyObject *
Raymond Hettinger625812f2003-01-07 01:58:52 +00002779arrayiter_next(arrayiterobject *it)
2780{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002781 assert(PyArrayIter_Check(it));
2782 if (it->index < Py_SIZE(it->ao))
2783 return (*it->getitem)(it->ao, it->index++);
2784 return NULL;
Raymond Hettinger625812f2003-01-07 01:58:52 +00002785}
2786
2787static void
2788arrayiter_dealloc(arrayiterobject *it)
2789{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002790 PyObject_GC_UnTrack(it);
2791 Py_XDECREF(it->ao);
2792 PyObject_GC_Del(it);
Raymond Hettinger625812f2003-01-07 01:58:52 +00002793}
2794
2795static int
2796arrayiter_traverse(arrayiterobject *it, visitproc visit, void *arg)
2797{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002798 Py_VISIT(it->ao);
2799 return 0;
Raymond Hettinger625812f2003-01-07 01:58:52 +00002800}
2801
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002802static PyObject *
2803arrayiter_reduce(arrayiterobject *it)
2804{
Antoine Pitroua7013882012-04-05 00:04:20 +02002805 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002806 it->ao, it->index);
2807}
2808
2809static PyObject *
2810arrayiter_setstate(arrayiterobject *it, PyObject *state)
2811{
2812 Py_ssize_t index = PyLong_AsSsize_t(state);
2813 if (index == -1 && PyErr_Occurred())
2814 return NULL;
2815 if (index < 0)
2816 index = 0;
2817 it->index = index;
2818 Py_RETURN_NONE;
2819}
2820
2821PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
2822static PyMethodDef arrayiter_methods[] = {
2823 {"__reduce__", (PyCFunction)arrayiter_reduce, METH_NOARGS,
2824 reduce_doc},
2825 {"__setstate__", (PyCFunction)arrayiter_setstate, METH_O,
2826 setstate_doc},
2827 {NULL, NULL} /* sentinel */
2828};
2829
Raymond Hettinger625812f2003-01-07 01:58:52 +00002830static PyTypeObject PyArrayIter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002831 PyVarObject_HEAD_INIT(NULL, 0)
2832 "arrayiterator", /* tp_name */
2833 sizeof(arrayiterobject), /* tp_basicsize */
2834 0, /* tp_itemsize */
2835 /* methods */
2836 (destructor)arrayiter_dealloc, /* tp_dealloc */
2837 0, /* tp_print */
2838 0, /* tp_getattr */
2839 0, /* tp_setattr */
2840 0, /* tp_reserved */
2841 0, /* tp_repr */
2842 0, /* tp_as_number */
2843 0, /* tp_as_sequence */
2844 0, /* tp_as_mapping */
2845 0, /* tp_hash */
2846 0, /* tp_call */
2847 0, /* tp_str */
2848 PyObject_GenericGetAttr, /* tp_getattro */
2849 0, /* tp_setattro */
2850 0, /* tp_as_buffer */
2851 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2852 0, /* tp_doc */
2853 (traverseproc)arrayiter_traverse, /* tp_traverse */
2854 0, /* tp_clear */
2855 0, /* tp_richcompare */
2856 0, /* tp_weaklistoffset */
2857 PyObject_SelfIter, /* tp_iter */
2858 (iternextfunc)arrayiter_next, /* tp_iternext */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002859 arrayiter_methods, /* tp_methods */
Raymond Hettinger625812f2003-01-07 01:58:52 +00002860};
2861
2862
2863/*********************** Install Module **************************/
2864
Martin v. Löwis99866332002-03-01 10:27:01 +00002865/* No functions in array module. */
2866static PyMethodDef a_methods[] = {
Alexandre Vassalottiad077152009-07-15 17:49:23 +00002867 {"_array_reconstructor", array_reconstructor, METH_VARARGS,
2868 PyDoc_STR("Internal. Used for pickling support.")},
Martin v. Löwis99866332002-03-01 10:27:01 +00002869 {NULL, NULL, 0, NULL} /* Sentinel */
2870};
2871
Martin v. Löwis1a214512008-06-11 05:26:20 +00002872static struct PyModuleDef arraymodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002873 PyModuleDef_HEAD_INIT,
2874 "array",
2875 module_doc,
2876 -1,
2877 a_methods,
2878 NULL,
2879 NULL,
2880 NULL,
2881 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002882};
2883
Martin v. Löwis99866332002-03-01 10:27:01 +00002884
Mark Hammondfe51c6d2002-08-02 02:27:13 +00002885PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002886PyInit_array(void)
Guido van Rossum778983b1993-02-19 15:55:02 +00002887{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002888 PyObject *m;
Georg Brandl4cb0de22011-09-28 21:49:49 +02002889 char buffer[Py_ARRAY_LENGTH(descriptors)], *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002890 PyObject *typecodes;
2891 Py_ssize_t size = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002892 struct arraydescr *descr;
Fred Drake0d40ba42000-02-04 20:33:49 +00002893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002894 if (PyType_Ready(&Arraytype) < 0)
2895 return NULL;
2896 Py_TYPE(&PyArrayIter_Type) = &PyType_Type;
2897 m = PyModule_Create(&arraymodule);
2898 if (m == NULL)
2899 return NULL;
Fred Drakef4e34842002-04-01 03:45:06 +00002900
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002901 Py_INCREF((PyObject *)&Arraytype);
2902 PyModule_AddObject(m, "ArrayType", (PyObject *)&Arraytype);
2903 Py_INCREF((PyObject *)&Arraytype);
2904 PyModule_AddObject(m, "array", (PyObject *)&Arraytype);
Travis E. Oliphantd5c0add2007-10-12 22:05:15 +00002905
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002906 for (descr=descriptors; descr->typecode != '\0'; descr++) {
2907 size++;
2908 }
Travis E. Oliphantd5c0add2007-10-12 22:05:15 +00002909
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002910 p = buffer;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002911 for (descr = descriptors; descr->typecode != '\0'; descr++) {
2912 *p++ = (char)descr->typecode;
2913 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002914 typecodes = PyUnicode_DecodeASCII(buffer, p - buffer, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002915
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002916 PyModule_AddObject(m, "typecodes", typecodes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002917
2918 if (PyErr_Occurred()) {
2919 Py_DECREF(m);
2920 m = NULL;
2921 }
2922 return m;
Guido van Rossum778983b1993-02-19 15:55:02 +00002923}