ยปCore Development>Code coverage>Modules/arraymodule.c

Python code coverage for Modules/arraymodule.c

#countcontent
1n/a/* Array object implementation */
2n/a
3n/a/* An array is a uniform list -- all items have the same type.
4n/a The item type is restricted to simple C types like int or float */
5n/a
6n/a#define PY_SSIZE_T_CLEAN
7n/a#include "Python.h"
8n/a#include "structmember.h"
9n/a
10n/a#ifdef STDC_HEADERS
11n/a#include <stddef.h>
12n/a#else /* !STDC_HEADERS */
13n/a#ifdef HAVE_SYS_TYPES_H
14n/a#include <sys/types.h> /* For size_t */
15n/a#endif /* HAVE_SYS_TYPES_H */
16n/a#endif /* !STDC_HEADERS */
17n/a
18n/a/*[clinic input]
19n/amodule array
20n/a[clinic start generated code]*/
21n/a/*[clinic end generated code: output=da39a3ee5e6b4b0d input=7d1b8d7f5958fd83]*/
22n/a
23n/astruct arrayobject; /* Forward */
24n/a
25n/a/* All possible arraydescr values are defined in the vector "descriptors"
26n/a * below. That's defined later because the appropriate get and set
27n/a * functions aren't visible yet.
28n/a */
29n/astruct arraydescr {
30n/a char typecode;
31n/a int itemsize;
32n/a PyObject * (*getitem)(struct arrayobject *, Py_ssize_t);
33n/a int (*setitem)(struct arrayobject *, Py_ssize_t, PyObject *);
34n/a const char *formats;
35n/a int is_integer_type;
36n/a int is_signed;
37n/a};
38n/a
39n/atypedef struct arrayobject {
40n/a PyObject_VAR_HEAD
41n/a char *ob_item;
42n/a Py_ssize_t allocated;
43n/a const struct arraydescr *ob_descr;
44n/a PyObject *weakreflist; /* List of weak references */
45n/a int ob_exports; /* Number of exported buffers */
46n/a} arrayobject;
47n/a
48n/astatic PyTypeObject Arraytype;
49n/a
50n/atypedef struct {
51n/a PyObject_HEAD
52n/a Py_ssize_t index;
53n/a arrayobject *ao;
54n/a PyObject* (*getitem)(struct arrayobject *, Py_ssize_t);
55n/a} arrayiterobject;
56n/a
57n/astatic PyTypeObject PyArrayIter_Type;
58n/a
59n/a#define PyArrayIter_Check(op) PyObject_TypeCheck(op, &PyArrayIter_Type)
60n/a
61n/aenum machine_format_code {
62n/a UNKNOWN_FORMAT = -1,
63n/a /* UNKNOWN_FORMAT is used to indicate that the machine format for an
64n/a * array type code cannot be interpreted. When this occurs, a list of
65n/a * Python objects is used to represent the content of the array
66n/a * instead of using the memory content of the array directly. In that
67n/a * case, the array_reconstructor mechanism is bypassed completely, and
68n/a * the standard array constructor is used instead.
69n/a *
70n/a * This is will most likely occur when the machine doesn't use IEEE
71n/a * floating-point numbers.
72n/a */
73n/a
74n/a UNSIGNED_INT8 = 0,
75n/a SIGNED_INT8 = 1,
76n/a UNSIGNED_INT16_LE = 2,
77n/a UNSIGNED_INT16_BE = 3,
78n/a SIGNED_INT16_LE = 4,
79n/a SIGNED_INT16_BE = 5,
80n/a UNSIGNED_INT32_LE = 6,
81n/a UNSIGNED_INT32_BE = 7,
82n/a SIGNED_INT32_LE = 8,
83n/a SIGNED_INT32_BE = 9,
84n/a UNSIGNED_INT64_LE = 10,
85n/a UNSIGNED_INT64_BE = 11,
86n/a SIGNED_INT64_LE = 12,
87n/a SIGNED_INT64_BE = 13,
88n/a IEEE_754_FLOAT_LE = 14,
89n/a IEEE_754_FLOAT_BE = 15,
90n/a IEEE_754_DOUBLE_LE = 16,
91n/a IEEE_754_DOUBLE_BE = 17,
92n/a UTF16_LE = 18,
93n/a UTF16_BE = 19,
94n/a UTF32_LE = 20,
95n/a UTF32_BE = 21
96n/a};
97n/a#define MACHINE_FORMAT_CODE_MIN 0
98n/a#define MACHINE_FORMAT_CODE_MAX 21
99n/a
100n/a
101n/a/*
102n/a * Must come after arrayobject, arrayiterobject,
103n/a * and enum machine_code_type definitions.
104n/a */
105n/a#include "clinic/arraymodule.c.h"
106n/a
107n/a#define array_Check(op) PyObject_TypeCheck(op, &Arraytype)
108n/a#define array_CheckExact(op) (Py_TYPE(op) == &Arraytype)
109n/a
110n/astatic int
111n/aarray_resize(arrayobject *self, Py_ssize_t newsize)
112n/a{
113n/a char *items;
114n/a size_t _new_size;
115n/a
116n/a if (self->ob_exports > 0 && newsize != Py_SIZE(self)) {
117n/a PyErr_SetString(PyExc_BufferError,
118n/a "cannot resize an array that is exporting buffers");
119n/a return -1;
120n/a }
121n/a
122n/a /* Bypass realloc() when a previous overallocation is large enough
123n/a to accommodate the newsize. If the newsize is 16 smaller than the
124n/a current size, then proceed with the realloc() to shrink the array.
125n/a */
126n/a
127n/a if (self->allocated >= newsize &&
128n/a Py_SIZE(self) < newsize + 16 &&
129n/a self->ob_item != NULL) {
130n/a Py_SIZE(self) = newsize;
131n/a return 0;
132n/a }
133n/a
134n/a if (newsize == 0) {
135n/a PyMem_FREE(self->ob_item);
136n/a self->ob_item = NULL;
137n/a Py_SIZE(self) = 0;
138n/a self->allocated = 0;
139n/a return 0;
140n/a }
141n/a
142n/a /* This over-allocates proportional to the array size, making room
143n/a * for additional growth. The over-allocation is mild, but is
144n/a * enough to give linear-time amortized behavior over a long
145n/a * sequence of appends() in the presence of a poorly-performing
146n/a * system realloc().
147n/a * The growth pattern is: 0, 4, 8, 16, 25, 34, 46, 56, 67, 79, ...
148n/a * Note, the pattern starts out the same as for lists but then
149n/a * grows at a smaller rate so that larger arrays only overallocate
150n/a * by about 1/16th -- this is done because arrays are presumed to be more
151n/a * memory critical.
152n/a */
153n/a
154n/a _new_size = (newsize >> 4) + (Py_SIZE(self) < 8 ? 3 : 7) + newsize;
155n/a items = self->ob_item;
156n/a /* XXX The following multiplication and division does not optimize away
157n/a like it does for lists since the size is not known at compile time */
158n/a if (_new_size <= ((~(size_t)0) / self->ob_descr->itemsize))
159n/a PyMem_RESIZE(items, char, (_new_size * self->ob_descr->itemsize));
160n/a else
161n/a items = NULL;
162n/a if (items == NULL) {
163n/a PyErr_NoMemory();
164n/a return -1;
165n/a }
166n/a self->ob_item = items;
167n/a Py_SIZE(self) = newsize;
168n/a self->allocated = _new_size;
169n/a return 0;
170n/a}
171n/a
172n/a/****************************************************************************
173n/aGet and Set functions for each type.
174n/aA Get function takes an arrayobject* and an integer index, returning the
175n/aarray value at that index wrapped in an appropriate PyObject*.
176n/aA Set function takes an arrayobject, integer index, and PyObject*; sets
177n/athe array value at that index to the raw C data extracted from the PyObject*,
178n/aand returns 0 if successful, else nonzero on failure (PyObject* not of an
179n/aappropriate type or value).
180n/aNote that the basic Get and Set functions do NOT check that the index is
181n/ain bounds; that's the responsibility of the caller.
182n/a****************************************************************************/
183n/a
184n/astatic PyObject *
185n/ab_getitem(arrayobject *ap, Py_ssize_t i)
186n/a{
187n/a long x = ((char *)ap->ob_item)[i];
188n/a if (x >= 128)
189n/a x -= 256;
190n/a return PyLong_FromLong(x);
191n/a}
192n/a
193n/astatic int
194n/ab_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
195n/a{
196n/a short x;
197n/a /* PyArg_Parse's 'b' formatter is for an unsigned char, therefore
198n/a must use the next size up that is signed ('h') and manually do
199n/a the overflow checking */
200n/a if (!PyArg_Parse(v, "h;array item must be integer", &x))
201n/a return -1;
202n/a else if (x < -128) {
203n/a PyErr_SetString(PyExc_OverflowError,
204n/a "signed char is less than minimum");
205n/a return -1;
206n/a }
207n/a else if (x > 127) {
208n/a PyErr_SetString(PyExc_OverflowError,
209n/a "signed char is greater than maximum");
210n/a return -1;
211n/a }
212n/a if (i >= 0)
213n/a ((char *)ap->ob_item)[i] = (char)x;
214n/a return 0;
215n/a}
216n/a
217n/astatic PyObject *
218n/aBB_getitem(arrayobject *ap, Py_ssize_t i)
219n/a{
220n/a long x = ((unsigned char *)ap->ob_item)[i];
221n/a return PyLong_FromLong(x);
222n/a}
223n/a
224n/astatic int
225n/aBB_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
226n/a{
227n/a unsigned char x;
228n/a /* 'B' == unsigned char, maps to PyArg_Parse's 'b' formatter */
229n/a if (!PyArg_Parse(v, "b;array item must be integer", &x))
230n/a return -1;
231n/a if (i >= 0)
232n/a ((char *)ap->ob_item)[i] = x;
233n/a return 0;
234n/a}
235n/a
236n/astatic PyObject *
237n/au_getitem(arrayobject *ap, Py_ssize_t i)
238n/a{
239n/a return PyUnicode_FromOrdinal(((Py_UNICODE *) ap->ob_item)[i]);
240n/a}
241n/a
242n/astatic int
243n/au_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
244n/a{
245n/a Py_UNICODE *p;
246n/a Py_ssize_t len;
247n/a
248n/a if (!PyArg_Parse(v, "u#;array item must be unicode character", &p, &len))
249n/a return -1;
250n/a if (len != 1) {
251n/a PyErr_SetString(PyExc_TypeError,
252n/a "array item must be unicode character");
253n/a return -1;
254n/a }
255n/a if (i >= 0)
256n/a ((Py_UNICODE *)ap->ob_item)[i] = p[0];
257n/a return 0;
258n/a}
259n/a
260n/a
261n/astatic PyObject *
262n/ah_getitem(arrayobject *ap, Py_ssize_t i)
263n/a{
264n/a return PyLong_FromLong((long) ((short *)ap->ob_item)[i]);
265n/a}
266n/a
267n/a
268n/astatic int
269n/ah_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
270n/a{
271n/a short x;
272n/a /* 'h' == signed short, maps to PyArg_Parse's 'h' formatter */
273n/a if (!PyArg_Parse(v, "h;array item must be integer", &x))
274n/a return -1;
275n/a if (i >= 0)
276n/a ((short *)ap->ob_item)[i] = x;
277n/a return 0;
278n/a}
279n/a
280n/astatic PyObject *
281n/aHH_getitem(arrayobject *ap, Py_ssize_t i)
282n/a{
283n/a return PyLong_FromLong((long) ((unsigned short *)ap->ob_item)[i]);
284n/a}
285n/a
286n/astatic int
287n/aHH_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
288n/a{
289n/a int x;
290n/a /* PyArg_Parse's 'h' formatter is for a signed short, therefore
291n/a must use the next size up and manually do the overflow checking */
292n/a if (!PyArg_Parse(v, "i;array item must be integer", &x))
293n/a return -1;
294n/a else if (x < 0) {
295n/a PyErr_SetString(PyExc_OverflowError,
296n/a "unsigned short is less than minimum");
297n/a return -1;
298n/a }
299n/a else if (x > USHRT_MAX) {
300n/a PyErr_SetString(PyExc_OverflowError,
301n/a "unsigned short is greater than maximum");
302n/a return -1;
303n/a }
304n/a if (i >= 0)
305n/a ((short *)ap->ob_item)[i] = (short)x;
306n/a return 0;
307n/a}
308n/a
309n/astatic PyObject *
310n/ai_getitem(arrayobject *ap, Py_ssize_t i)
311n/a{
312n/a return PyLong_FromLong((long) ((int *)ap->ob_item)[i]);
313n/a}
314n/a
315n/astatic int
316n/ai_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
317n/a{
318n/a int x;
319n/a /* 'i' == signed int, maps to PyArg_Parse's 'i' formatter */
320n/a if (!PyArg_Parse(v, "i;array item must be integer", &x))
321n/a return -1;
322n/a if (i >= 0)
323n/a ((int *)ap->ob_item)[i] = x;
324n/a return 0;
325n/a}
326n/a
327n/astatic PyObject *
328n/aII_getitem(arrayobject *ap, Py_ssize_t i)
329n/a{
330n/a return PyLong_FromUnsignedLong(
331n/a (unsigned long) ((unsigned int *)ap->ob_item)[i]);
332n/a}
333n/a
334n/astatic int
335n/aII_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
336n/a{
337n/a unsigned long x;
338n/a if (PyLong_Check(v)) {
339n/a x = PyLong_AsUnsignedLong(v);
340n/a if (x == (unsigned long) -1 && PyErr_Occurred())
341n/a return -1;
342n/a }
343n/a else {
344n/a long y;
345n/a if (!PyArg_Parse(v, "l;array item must be integer", &y))
346n/a return -1;
347n/a if (y < 0) {
348n/a PyErr_SetString(PyExc_OverflowError,
349n/a "unsigned int is less than minimum");
350n/a return -1;
351n/a }
352n/a x = (unsigned long)y;
353n/a
354n/a }
355n/a if (x > UINT_MAX) {
356n/a PyErr_SetString(PyExc_OverflowError,
357n/a "unsigned int is greater than maximum");
358n/a return -1;
359n/a }
360n/a
361n/a if (i >= 0)
362n/a ((unsigned int *)ap->ob_item)[i] = (unsigned int)x;
363n/a return 0;
364n/a}
365n/a
366n/astatic PyObject *
367n/al_getitem(arrayobject *ap, Py_ssize_t i)
368n/a{
369n/a return PyLong_FromLong(((long *)ap->ob_item)[i]);
370n/a}
371n/a
372n/astatic int
373n/al_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
374n/a{
375n/a long x;
376n/a if (!PyArg_Parse(v, "l;array item must be integer", &x))
377n/a return -1;
378n/a if (i >= 0)
379n/a ((long *)ap->ob_item)[i] = x;
380n/a return 0;
381n/a}
382n/a
383n/astatic PyObject *
384n/aLL_getitem(arrayobject *ap, Py_ssize_t i)
385n/a{
386n/a return PyLong_FromUnsignedLong(((unsigned long *)ap->ob_item)[i]);
387n/a}
388n/a
389n/astatic int
390n/aLL_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
391n/a{
392n/a unsigned long x;
393n/a if (PyLong_Check(v)) {
394n/a x = PyLong_AsUnsignedLong(v);
395n/a if (x == (unsigned long) -1 && PyErr_Occurred())
396n/a return -1;
397n/a }
398n/a else {
399n/a long y;
400n/a if (!PyArg_Parse(v, "l;array item must be integer", &y))
401n/a return -1;
402n/a if (y < 0) {
403n/a PyErr_SetString(PyExc_OverflowError,
404n/a "unsigned long is less than minimum");
405n/a return -1;
406n/a }
407n/a x = (unsigned long)y;
408n/a
409n/a }
410n/a if (x > ULONG_MAX) {
411n/a PyErr_SetString(PyExc_OverflowError,
412n/a "unsigned long is greater than maximum");
413n/a return -1;
414n/a }
415n/a
416n/a if (i >= 0)
417n/a ((unsigned long *)ap->ob_item)[i] = x;
418n/a return 0;
419n/a}
420n/a
421n/astatic PyObject *
422n/aq_getitem(arrayobject *ap, Py_ssize_t i)
423n/a{
424n/a return PyLong_FromLongLong(((long long *)ap->ob_item)[i]);
425n/a}
426n/a
427n/astatic int
428n/aq_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
429n/a{
430n/a long long x;
431n/a if (!PyArg_Parse(v, "L;array item must be integer", &x))
432n/a return -1;
433n/a if (i >= 0)
434n/a ((long long *)ap->ob_item)[i] = x;
435n/a return 0;
436n/a}
437n/a
438n/astatic PyObject *
439n/aQQ_getitem(arrayobject *ap, Py_ssize_t i)
440n/a{
441n/a return PyLong_FromUnsignedLongLong(
442n/a ((unsigned long long *)ap->ob_item)[i]);
443n/a}
444n/a
445n/astatic int
446n/aQQ_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
447n/a{
448n/a unsigned long long x;
449n/a if (PyLong_Check(v)) {
450n/a x = PyLong_AsUnsignedLongLong(v);
451n/a if (x == (unsigned long long) -1 && PyErr_Occurred())
452n/a return -1;
453n/a }
454n/a else {
455n/a long long y;
456n/a if (!PyArg_Parse(v, "L;array item must be integer", &y))
457n/a return -1;
458n/a if (y < 0) {
459n/a PyErr_SetString(PyExc_OverflowError,
460n/a "unsigned long long is less than minimum");
461n/a return -1;
462n/a }
463n/a x = (unsigned long long)y;
464n/a }
465n/a
466n/a if (i >= 0)
467n/a ((unsigned long long *)ap->ob_item)[i] = x;
468n/a return 0;
469n/a}
470n/a
471n/astatic PyObject *
472n/af_getitem(arrayobject *ap, Py_ssize_t i)
473n/a{
474n/a return PyFloat_FromDouble((double) ((float *)ap->ob_item)[i]);
475n/a}
476n/a
477n/astatic int
478n/af_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
479n/a{
480n/a float x;
481n/a if (!PyArg_Parse(v, "f;array item must be float", &x))
482n/a return -1;
483n/a if (i >= 0)
484n/a ((float *)ap->ob_item)[i] = x;
485n/a return 0;
486n/a}
487n/a
488n/astatic PyObject *
489n/ad_getitem(arrayobject *ap, Py_ssize_t i)
490n/a{
491n/a return PyFloat_FromDouble(((double *)ap->ob_item)[i]);
492n/a}
493n/a
494n/astatic int
495n/ad_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
496n/a{
497n/a double x;
498n/a if (!PyArg_Parse(v, "d;array item must be float", &x))
499n/a return -1;
500n/a if (i >= 0)
501n/a ((double *)ap->ob_item)[i] = x;
502n/a return 0;
503n/a}
504n/a
505n/a
506n/a/* Description of types.
507n/a *
508n/a * Don't forget to update typecode_to_mformat_code() if you add a new
509n/a * typecode.
510n/a */
511n/astatic const struct arraydescr descriptors[] = {
512n/a {'b', 1, b_getitem, b_setitem, "b", 1, 1},
513n/a {'B', 1, BB_getitem, BB_setitem, "B", 1, 0},
514n/a {'u', sizeof(Py_UNICODE), u_getitem, u_setitem, "u", 0, 0},
515n/a {'h', sizeof(short), h_getitem, h_setitem, "h", 1, 1},
516n/a {'H', sizeof(short), HH_getitem, HH_setitem, "H", 1, 0},
517n/a {'i', sizeof(int), i_getitem, i_setitem, "i", 1, 1},
518n/a {'I', sizeof(int), II_getitem, II_setitem, "I", 1, 0},
519n/a {'l', sizeof(long), l_getitem, l_setitem, "l", 1, 1},
520n/a {'L', sizeof(long), LL_getitem, LL_setitem, "L", 1, 0},
521n/a {'q', sizeof(long long), q_getitem, q_setitem, "q", 1, 1},
522n/a {'Q', sizeof(long long), QQ_getitem, QQ_setitem, "Q", 1, 0},
523n/a {'f', sizeof(float), f_getitem, f_setitem, "f", 0, 0},
524n/a {'d', sizeof(double), d_getitem, d_setitem, "d", 0, 0},
525n/a {'\0', 0, 0, 0, 0, 0, 0} /* Sentinel */
526n/a};
527n/a
528n/a/****************************************************************************
529n/aImplementations of array object methods.
530n/a****************************************************************************/
531n/a/*[clinic input]
532n/aclass array.array "arrayobject *" "&Arraytype"
533n/a[clinic start generated code]*/
534n/a/*[clinic end generated code: output=da39a3ee5e6b4b0d input=ad43d37e942a8854]*/
535n/a
536n/astatic PyObject *
537n/anewarrayobject(PyTypeObject *type, Py_ssize_t size, const struct arraydescr *descr)
538n/a{
539n/a arrayobject *op;
540n/a size_t nbytes;
541n/a
542n/a if (size < 0) {
543n/a PyErr_BadInternalCall();
544n/a return NULL;
545n/a }
546n/a
547n/a /* Check for overflow */
548n/a if (size > PY_SSIZE_T_MAX / descr->itemsize) {
549n/a return PyErr_NoMemory();
550n/a }
551n/a nbytes = size * descr->itemsize;
552n/a op = (arrayobject *) type->tp_alloc(type, 0);
553n/a if (op == NULL) {
554n/a return NULL;
555n/a }
556n/a op->ob_descr = descr;
557n/a op->allocated = size;
558n/a op->weakreflist = NULL;
559n/a Py_SIZE(op) = size;
560n/a if (size <= 0) {
561n/a op->ob_item = NULL;
562n/a }
563n/a else {
564n/a op->ob_item = PyMem_NEW(char, nbytes);
565n/a if (op->ob_item == NULL) {
566n/a Py_DECREF(op);
567n/a return PyErr_NoMemory();
568n/a }
569n/a }
570n/a op->ob_exports = 0;
571n/a return (PyObject *) op;
572n/a}
573n/a
574n/astatic PyObject *
575n/agetarrayitem(PyObject *op, Py_ssize_t i)
576n/a{
577n/a arrayobject *ap;
578n/a assert(array_Check(op));
579n/a ap = (arrayobject *)op;
580n/a assert(i>=0 && i<Py_SIZE(ap));
581n/a return (*ap->ob_descr->getitem)(ap, i);
582n/a}
583n/a
584n/astatic int
585n/ains1(arrayobject *self, Py_ssize_t where, PyObject *v)
586n/a{
587n/a char *items;
588n/a Py_ssize_t n = Py_SIZE(self);
589n/a if (v == NULL) {
590n/a PyErr_BadInternalCall();
591n/a return -1;
592n/a }
593n/a if ((*self->ob_descr->setitem)(self, -1, v) < 0)
594n/a return -1;
595n/a
596n/a if (array_resize(self, n+1) == -1)
597n/a return -1;
598n/a items = self->ob_item;
599n/a if (where < 0) {
600n/a where += n;
601n/a if (where < 0)
602n/a where = 0;
603n/a }
604n/a if (where > n)
605n/a where = n;
606n/a /* appends don't need to call memmove() */
607n/a if (where != n)
608n/a memmove(items + (where+1)*self->ob_descr->itemsize,
609n/a items + where*self->ob_descr->itemsize,
610n/a (n-where)*self->ob_descr->itemsize);
611n/a return (*self->ob_descr->setitem)(self, where, v);
612n/a}
613n/a
614n/a/* Methods */
615n/a
616n/astatic void
617n/aarray_dealloc(arrayobject *op)
618n/a{
619n/a if (op->weakreflist != NULL)
620n/a PyObject_ClearWeakRefs((PyObject *) op);
621n/a if (op->ob_item != NULL)
622n/a PyMem_DEL(op->ob_item);
623n/a Py_TYPE(op)->tp_free((PyObject *)op);
624n/a}
625n/a
626n/astatic PyObject *
627n/aarray_richcompare(PyObject *v, PyObject *w, int op)
628n/a{
629n/a arrayobject *va, *wa;
630n/a PyObject *vi = NULL;
631n/a PyObject *wi = NULL;
632n/a Py_ssize_t i, k;
633n/a PyObject *res;
634n/a
635n/a if (!array_Check(v) || !array_Check(w))
636n/a Py_RETURN_NOTIMPLEMENTED;
637n/a
638n/a va = (arrayobject *)v;
639n/a wa = (arrayobject *)w;
640n/a
641n/a if (Py_SIZE(va) != Py_SIZE(wa) && (op == Py_EQ || op == Py_NE)) {
642n/a /* Shortcut: if the lengths differ, the arrays differ */
643n/a if (op == Py_EQ)
644n/a res = Py_False;
645n/a else
646n/a res = Py_True;
647n/a Py_INCREF(res);
648n/a return res;
649n/a }
650n/a
651n/a /* Search for the first index where items are different */
652n/a k = 1;
653n/a for (i = 0; i < Py_SIZE(va) && i < Py_SIZE(wa); i++) {
654n/a vi = getarrayitem(v, i);
655n/a wi = getarrayitem(w, i);
656n/a if (vi == NULL || wi == NULL) {
657n/a Py_XDECREF(vi);
658n/a Py_XDECREF(wi);
659n/a return NULL;
660n/a }
661n/a k = PyObject_RichCompareBool(vi, wi, Py_EQ);
662n/a if (k == 0)
663n/a break; /* Keeping vi and wi alive! */
664n/a Py_DECREF(vi);
665n/a Py_DECREF(wi);
666n/a if (k < 0)
667n/a return NULL;
668n/a }
669n/a
670n/a if (k) {
671n/a /* No more items to compare -- compare sizes */
672n/a Py_ssize_t vs = Py_SIZE(va);
673n/a Py_ssize_t ws = Py_SIZE(wa);
674n/a int cmp;
675n/a switch (op) {
676n/a case Py_LT: cmp = vs < ws; break;
677n/a case Py_LE: cmp = vs <= ws; break;
678n/a case Py_EQ: cmp = vs == ws; break;
679n/a case Py_NE: cmp = vs != ws; break;
680n/a case Py_GT: cmp = vs > ws; break;
681n/a case Py_GE: cmp = vs >= ws; break;
682n/a default: return NULL; /* cannot happen */
683n/a }
684n/a if (cmp)
685n/a res = Py_True;
686n/a else
687n/a res = Py_False;
688n/a Py_INCREF(res);
689n/a return res;
690n/a }
691n/a
692n/a /* We have an item that differs. First, shortcuts for EQ/NE */
693n/a if (op == Py_EQ) {
694n/a Py_INCREF(Py_False);
695n/a res = Py_False;
696n/a }
697n/a else if (op == Py_NE) {
698n/a Py_INCREF(Py_True);
699n/a res = Py_True;
700n/a }
701n/a else {
702n/a /* Compare the final item again using the proper operator */
703n/a res = PyObject_RichCompare(vi, wi, op);
704n/a }
705n/a Py_DECREF(vi);
706n/a Py_DECREF(wi);
707n/a return res;
708n/a}
709n/a
710n/astatic Py_ssize_t
711n/aarray_length(arrayobject *a)
712n/a{
713n/a return Py_SIZE(a);
714n/a}
715n/a
716n/astatic PyObject *
717n/aarray_item(arrayobject *a, Py_ssize_t i)
718n/a{
719n/a if (i < 0 || i >= Py_SIZE(a)) {
720n/a PyErr_SetString(PyExc_IndexError, "array index out of range");
721n/a return NULL;
722n/a }
723n/a return getarrayitem((PyObject *)a, i);
724n/a}
725n/a
726n/astatic PyObject *
727n/aarray_slice(arrayobject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
728n/a{
729n/a arrayobject *np;
730n/a if (ilow < 0)
731n/a ilow = 0;
732n/a else if (ilow > Py_SIZE(a))
733n/a ilow = Py_SIZE(a);
734n/a if (ihigh < 0)
735n/a ihigh = 0;
736n/a if (ihigh < ilow)
737n/a ihigh = ilow;
738n/a else if (ihigh > Py_SIZE(a))
739n/a ihigh = Py_SIZE(a);
740n/a np = (arrayobject *) newarrayobject(&Arraytype, ihigh - ilow, a->ob_descr);
741n/a if (np == NULL)
742n/a return NULL;
743n/a if (ihigh > ilow) {
744n/a memcpy(np->ob_item, a->ob_item + ilow * a->ob_descr->itemsize,
745n/a (ihigh-ilow) * a->ob_descr->itemsize);
746n/a }
747n/a return (PyObject *)np;
748n/a}
749n/a
750n/a
751n/a/*[clinic input]
752n/aarray.array.__copy__
753n/a
754n/aReturn a copy of the array.
755n/a[clinic start generated code]*/
756n/a
757n/astatic PyObject *
758n/aarray_array___copy___impl(arrayobject *self)
759n/a/*[clinic end generated code: output=dec7c3f925d9619e input=ad1ee5b086965f09]*/
760n/a{
761n/a return array_slice(self, 0, Py_SIZE(self));
762n/a}
763n/a
764n/a/*[clinic input]
765n/aarray.array.__deepcopy__
766n/a
767n/a unused: object
768n/a /
769n/a
770n/aReturn a copy of the array.
771n/a[clinic start generated code]*/
772n/a
773n/astatic PyObject *
774n/aarray_array___deepcopy__(arrayobject *self, PyObject *unused)
775n/a/*[clinic end generated code: output=1ec748d8e14a9faa input=2405ecb4933748c4]*/
776n/a{
777n/a return array_array___copy___impl(self);
778n/a}
779n/a
780n/astatic PyObject *
781n/aarray_concat(arrayobject *a, PyObject *bb)
782n/a{
783n/a Py_ssize_t size;
784n/a arrayobject *np;
785n/a if (!array_Check(bb)) {
786n/a PyErr_Format(PyExc_TypeError,
787n/a "can only append array (not \"%.200s\") to array",
788n/a Py_TYPE(bb)->tp_name);
789n/a return NULL;
790n/a }
791n/a#define b ((arrayobject *)bb)
792n/a if (a->ob_descr != b->ob_descr) {
793n/a PyErr_BadArgument();
794n/a return NULL;
795n/a }
796n/a if (Py_SIZE(a) > PY_SSIZE_T_MAX - Py_SIZE(b)) {
797n/a return PyErr_NoMemory();
798n/a }
799n/a size = Py_SIZE(a) + Py_SIZE(b);
800n/a np = (arrayobject *) newarrayobject(&Arraytype, size, a->ob_descr);
801n/a if (np == NULL) {
802n/a return NULL;
803n/a }
804n/a if (Py_SIZE(a) > 0) {
805n/a memcpy(np->ob_item, a->ob_item, Py_SIZE(a)*a->ob_descr->itemsize);
806n/a }
807n/a if (Py_SIZE(b) > 0) {
808n/a memcpy(np->ob_item + Py_SIZE(a)*a->ob_descr->itemsize,
809n/a b->ob_item, Py_SIZE(b)*b->ob_descr->itemsize);
810n/a }
811n/a return (PyObject *)np;
812n/a#undef b
813n/a}
814n/a
815n/astatic PyObject *
816n/aarray_repeat(arrayobject *a, Py_ssize_t n)
817n/a{
818n/a Py_ssize_t size;
819n/a arrayobject *np;
820n/a Py_ssize_t oldbytes, newbytes;
821n/a if (n < 0)
822n/a n = 0;
823n/a if ((Py_SIZE(a) != 0) && (n > PY_SSIZE_T_MAX / Py_SIZE(a))) {
824n/a return PyErr_NoMemory();
825n/a }
826n/a size = Py_SIZE(a) * n;
827n/a np = (arrayobject *) newarrayobject(&Arraytype, size, a->ob_descr);
828n/a if (np == NULL)
829n/a return NULL;
830n/a if (size == 0)
831n/a return (PyObject *)np;
832n/a oldbytes = Py_SIZE(a) * a->ob_descr->itemsize;
833n/a newbytes = oldbytes * n;
834n/a /* this follows the code in unicode_repeat */
835n/a if (oldbytes == 1) {
836n/a memset(np->ob_item, a->ob_item[0], newbytes);
837n/a } else {
838n/a Py_ssize_t done = oldbytes;
839n/a memcpy(np->ob_item, a->ob_item, oldbytes);
840n/a while (done < newbytes) {
841n/a Py_ssize_t ncopy = (done <= newbytes-done) ? done : newbytes-done;
842n/a memcpy(np->ob_item+done, np->ob_item, ncopy);
843n/a done += ncopy;
844n/a }
845n/a }
846n/a return (PyObject *)np;
847n/a}
848n/a
849n/astatic int
850n/aarray_del_slice(arrayobject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
851n/a{
852n/a char *item;
853n/a Py_ssize_t d; /* Change in size */
854n/a if (ilow < 0)
855n/a ilow = 0;
856n/a else if (ilow > Py_SIZE(a))
857n/a ilow = Py_SIZE(a);
858n/a if (ihigh < 0)
859n/a ihigh = 0;
860n/a if (ihigh < ilow)
861n/a ihigh = ilow;
862n/a else if (ihigh > Py_SIZE(a))
863n/a ihigh = Py_SIZE(a);
864n/a item = a->ob_item;
865n/a d = ihigh-ilow;
866n/a /* Issue #4509: If the array has exported buffers and the slice
867n/a assignment would change the size of the array, fail early to make
868n/a sure we don't modify it. */
869n/a if (d != 0 && a->ob_exports > 0) {
870n/a PyErr_SetString(PyExc_BufferError,
871n/a "cannot resize an array that is exporting buffers");
872n/a return -1;
873n/a }
874n/a if (d > 0) { /* Delete d items */
875n/a memmove(item + (ihigh-d)*a->ob_descr->itemsize,
876n/a item + ihigh*a->ob_descr->itemsize,
877n/a (Py_SIZE(a)-ihigh)*a->ob_descr->itemsize);
878n/a if (array_resize(a, Py_SIZE(a) - d) == -1)
879n/a return -1;
880n/a }
881n/a return 0;
882n/a}
883n/a
884n/astatic int
885n/aarray_ass_item(arrayobject *a, Py_ssize_t i, PyObject *v)
886n/a{
887n/a if (i < 0 || i >= Py_SIZE(a)) {
888n/a PyErr_SetString(PyExc_IndexError,
889n/a "array assignment index out of range");
890n/a return -1;
891n/a }
892n/a if (v == NULL)
893n/a return array_del_slice(a, i, i+1);
894n/a return (*a->ob_descr->setitem)(a, i, v);
895n/a}
896n/a
897n/astatic int
898n/asetarrayitem(PyObject *a, Py_ssize_t i, PyObject *v)
899n/a{
900n/a assert(array_Check(a));
901n/a return array_ass_item((arrayobject *)a, i, v);
902n/a}
903n/a
904n/astatic int
905n/aarray_iter_extend(arrayobject *self, PyObject *bb)
906n/a{
907n/a PyObject *it, *v;
908n/a
909n/a it = PyObject_GetIter(bb);
910n/a if (it == NULL)
911n/a return -1;
912n/a
913n/a while ((v = PyIter_Next(it)) != NULL) {
914n/a if (ins1(self, Py_SIZE(self), v) != 0) {
915n/a Py_DECREF(v);
916n/a Py_DECREF(it);
917n/a return -1;
918n/a }
919n/a Py_DECREF(v);
920n/a }
921n/a Py_DECREF(it);
922n/a if (PyErr_Occurred())
923n/a return -1;
924n/a return 0;
925n/a}
926n/a
927n/astatic int
928n/aarray_do_extend(arrayobject *self, PyObject *bb)
929n/a{
930n/a Py_ssize_t size, oldsize, bbsize;
931n/a
932n/a if (!array_Check(bb))
933n/a return array_iter_extend(self, bb);
934n/a#define b ((arrayobject *)bb)
935n/a if (self->ob_descr != b->ob_descr) {
936n/a PyErr_SetString(PyExc_TypeError,
937n/a "can only extend with array of same kind");
938n/a return -1;
939n/a }
940n/a if ((Py_SIZE(self) > PY_SSIZE_T_MAX - Py_SIZE(b)) ||
941n/a ((Py_SIZE(self) + Py_SIZE(b)) > PY_SSIZE_T_MAX / self->ob_descr->itemsize)) {
942n/a PyErr_NoMemory();
943n/a return -1;
944n/a }
945n/a oldsize = Py_SIZE(self);
946n/a /* Get the size of bb before resizing the array since bb could be self. */
947n/a bbsize = Py_SIZE(bb);
948n/a size = oldsize + Py_SIZE(b);
949n/a if (array_resize(self, size) == -1)
950n/a return -1;
951n/a if (bbsize > 0) {
952n/a memcpy(self->ob_item + oldsize * self->ob_descr->itemsize,
953n/a b->ob_item, bbsize * b->ob_descr->itemsize);
954n/a }
955n/a
956n/a return 0;
957n/a#undef b
958n/a}
959n/a
960n/astatic PyObject *
961n/aarray_inplace_concat(arrayobject *self, PyObject *bb)
962n/a{
963n/a if (!array_Check(bb)) {
964n/a PyErr_Format(PyExc_TypeError,
965n/a "can only extend array with array (not \"%.200s\")",
966n/a Py_TYPE(bb)->tp_name);
967n/a return NULL;
968n/a }
969n/a if (array_do_extend(self, bb) == -1)
970n/a return NULL;
971n/a Py_INCREF(self);
972n/a return (PyObject *)self;
973n/a}
974n/a
975n/astatic PyObject *
976n/aarray_inplace_repeat(arrayobject *self, Py_ssize_t n)
977n/a{
978n/a char *items, *p;
979n/a Py_ssize_t size, i;
980n/a
981n/a if (Py_SIZE(self) > 0) {
982n/a if (n < 0)
983n/a n = 0;
984n/a if ((self->ob_descr->itemsize != 0) &&
985n/a (Py_SIZE(self) > PY_SSIZE_T_MAX / self->ob_descr->itemsize)) {
986n/a return PyErr_NoMemory();
987n/a }
988n/a size = Py_SIZE(self) * self->ob_descr->itemsize;
989n/a if (n > 0 && size > PY_SSIZE_T_MAX / n) {
990n/a return PyErr_NoMemory();
991n/a }
992n/a if (array_resize(self, n * Py_SIZE(self)) == -1)
993n/a return NULL;
994n/a items = p = self->ob_item;
995n/a for (i = 1; i < n; i++) {
996n/a p += size;
997n/a memcpy(p, items, size);
998n/a }
999n/a }
1000n/a Py_INCREF(self);
1001n/a return (PyObject *)self;
1002n/a}
1003n/a
1004n/a
1005n/astatic PyObject *
1006n/ains(arrayobject *self, Py_ssize_t where, PyObject *v)
1007n/a{
1008n/a if (ins1(self, where, v) != 0)
1009n/a return NULL;
1010n/a Py_RETURN_NONE;
1011n/a}
1012n/a
1013n/a/*[clinic input]
1014n/aarray.array.count
1015n/a
1016n/a v: object
1017n/a /
1018n/a
1019n/aReturn number of occurrences of v in the array.
1020n/a[clinic start generated code]*/
1021n/a
1022n/astatic PyObject *
1023n/aarray_array_count(arrayobject *self, PyObject *v)
1024n/a/*[clinic end generated code: output=3dd3624bf7135a3a input=d9bce9d65e39d1f5]*/
1025n/a{
1026n/a Py_ssize_t count = 0;
1027n/a Py_ssize_t i;
1028n/a
1029n/a for (i = 0; i < Py_SIZE(self); i++) {
1030n/a PyObject *selfi;
1031n/a int cmp;
1032n/a
1033n/a selfi = getarrayitem((PyObject *)self, i);
1034n/a if (selfi == NULL)
1035n/a return NULL;
1036n/a cmp = PyObject_RichCompareBool(selfi, v, Py_EQ);
1037n/a Py_DECREF(selfi);
1038n/a if (cmp > 0)
1039n/a count++;
1040n/a else if (cmp < 0)
1041n/a return NULL;
1042n/a }
1043n/a return PyLong_FromSsize_t(count);
1044n/a}
1045n/a
1046n/a
1047n/a/*[clinic input]
1048n/aarray.array.index
1049n/a
1050n/a v: object
1051n/a /
1052n/a
1053n/aReturn index of first occurrence of v in the array.
1054n/a[clinic start generated code]*/
1055n/a
1056n/astatic PyObject *
1057n/aarray_array_index(arrayobject *self, PyObject *v)
1058n/a/*[clinic end generated code: output=d48498d325602167 input=cf619898c6649d08]*/
1059n/a{
1060n/a Py_ssize_t i;
1061n/a
1062n/a for (i = 0; i < Py_SIZE(self); i++) {
1063n/a PyObject *selfi;
1064n/a int cmp;
1065n/a
1066n/a selfi = getarrayitem((PyObject *)self, i);
1067n/a if (selfi == NULL)
1068n/a return NULL;
1069n/a cmp = PyObject_RichCompareBool(selfi, v, Py_EQ);
1070n/a Py_DECREF(selfi);
1071n/a if (cmp > 0) {
1072n/a return PyLong_FromLong((long)i);
1073n/a }
1074n/a else if (cmp < 0)
1075n/a return NULL;
1076n/a }
1077n/a PyErr_SetString(PyExc_ValueError, "array.index(x): x not in list");
1078n/a return NULL;
1079n/a}
1080n/a
1081n/astatic int
1082n/aarray_contains(arrayobject *self, PyObject *v)
1083n/a{
1084n/a Py_ssize_t i;
1085n/a int cmp;
1086n/a
1087n/a for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(self); i++) {
1088n/a PyObject *selfi = getarrayitem((PyObject *)self, i);
1089n/a if (selfi == NULL)
1090n/a return -1;
1091n/a cmp = PyObject_RichCompareBool(selfi, v, Py_EQ);
1092n/a Py_DECREF(selfi);
1093n/a }
1094n/a return cmp;
1095n/a}
1096n/a
1097n/a/*[clinic input]
1098n/aarray.array.remove
1099n/a
1100n/a v: object
1101n/a /
1102n/a
1103n/aRemove the first occurrence of v in the array.
1104n/a[clinic start generated code]*/
1105n/a
1106n/astatic PyObject *
1107n/aarray_array_remove(arrayobject *self, PyObject *v)
1108n/a/*[clinic end generated code: output=bef06be9fdf9dceb input=0b1e5aed25590027]*/
1109n/a{
1110n/a int i;
1111n/a
1112n/a for (i = 0; i < Py_SIZE(self); i++) {
1113n/a PyObject *selfi;
1114n/a int cmp;
1115n/a
1116n/a selfi = getarrayitem((PyObject *)self,i);
1117n/a if (selfi == NULL)
1118n/a return NULL;
1119n/a cmp = PyObject_RichCompareBool(selfi, v, Py_EQ);
1120n/a Py_DECREF(selfi);
1121n/a if (cmp > 0) {
1122n/a if (array_del_slice(self, i, i+1) != 0)
1123n/a return NULL;
1124n/a Py_RETURN_NONE;
1125n/a }
1126n/a else if (cmp < 0)
1127n/a return NULL;
1128n/a }
1129n/a PyErr_SetString(PyExc_ValueError, "array.remove(x): x not in list");
1130n/a return NULL;
1131n/a}
1132n/a
1133n/a/*[clinic input]
1134n/aarray.array.pop
1135n/a
1136n/a i: Py_ssize_t = -1
1137n/a /
1138n/a
1139n/aReturn the i-th element and delete it from the array.
1140n/a
1141n/ai defaults to -1.
1142n/a[clinic start generated code]*/
1143n/a
1144n/astatic PyObject *
1145n/aarray_array_pop_impl(arrayobject *self, Py_ssize_t i)
1146n/a/*[clinic end generated code: output=bc1f0c54fe5308e4 input=8e5feb4c1a11cd44]*/
1147n/a{
1148n/a PyObject *v;
1149n/a
1150n/a if (Py_SIZE(self) == 0) {
1151n/a /* Special-case most common failure cause */
1152n/a PyErr_SetString(PyExc_IndexError, "pop from empty array");
1153n/a return NULL;
1154n/a }
1155n/a if (i < 0)
1156n/a i += Py_SIZE(self);
1157n/a if (i < 0 || i >= Py_SIZE(self)) {
1158n/a PyErr_SetString(PyExc_IndexError, "pop index out of range");
1159n/a return NULL;
1160n/a }
1161n/a v = getarrayitem((PyObject *)self, i);
1162n/a if (v == NULL)
1163n/a return NULL;
1164n/a if (array_del_slice(self, i, i+1) != 0) {
1165n/a Py_DECREF(v);
1166n/a return NULL;
1167n/a }
1168n/a return v;
1169n/a}
1170n/a
1171n/a/*[clinic input]
1172n/aarray.array.extend
1173n/a
1174n/a bb: object
1175n/a /
1176n/a
1177n/aAppend items to the end of the array.
1178n/a[clinic start generated code]*/
1179n/a
1180n/astatic PyObject *
1181n/aarray_array_extend(arrayobject *self, PyObject *bb)
1182n/a/*[clinic end generated code: output=bbddbc8e8bef871d input=43be86aba5c31e44]*/
1183n/a{
1184n/a if (array_do_extend(self, bb) == -1)
1185n/a return NULL;
1186n/a Py_RETURN_NONE;
1187n/a}
1188n/a
1189n/a/*[clinic input]
1190n/aarray.array.insert
1191n/a
1192n/a i: Py_ssize_t
1193n/a v: object
1194n/a /
1195n/a
1196n/aInsert a new item v into the array before position i.
1197n/a[clinic start generated code]*/
1198n/a
1199n/astatic PyObject *
1200n/aarray_array_insert_impl(arrayobject *self, Py_ssize_t i, PyObject *v)
1201n/a/*[clinic end generated code: output=5a3648e278348564 input=5577d1b4383e9313]*/
1202n/a{
1203n/a return ins(self, i, v);
1204n/a}
1205n/a
1206n/a/*[clinic input]
1207n/aarray.array.buffer_info
1208n/a
1209n/aReturn a tuple (address, length) giving the current memory address and the length in items of the buffer used to hold array's contents.
1210n/a
1211n/aThe length should be multiplied by the itemsize attribute to calculate
1212n/athe buffer length in bytes.
1213n/a[clinic start generated code]*/
1214n/a
1215n/astatic PyObject *
1216n/aarray_array_buffer_info_impl(arrayobject *self)
1217n/a/*[clinic end generated code: output=9b2a4ec3ae7e98e7 input=a58bae5c6e1ac6a6]*/
1218n/a{
1219n/a PyObject *retval = NULL, *v;
1220n/a
1221n/a retval = PyTuple_New(2);
1222n/a if (!retval)
1223n/a return NULL;
1224n/a
1225n/a v = PyLong_FromVoidPtr(self->ob_item);
1226n/a if (v == NULL) {
1227n/a Py_DECREF(retval);
1228n/a return NULL;
1229n/a }
1230n/a PyTuple_SET_ITEM(retval, 0, v);
1231n/a
1232n/a v = PyLong_FromSsize_t(Py_SIZE(self));
1233n/a if (v == NULL) {
1234n/a Py_DECREF(retval);
1235n/a return NULL;
1236n/a }
1237n/a PyTuple_SET_ITEM(retval, 1, v);
1238n/a
1239n/a return retval;
1240n/a}
1241n/a
1242n/a/*[clinic input]
1243n/aarray.array.append
1244n/a
1245n/a v: object
1246n/a /
1247n/a
1248n/aAppend new value v to the end of the array.
1249n/a[clinic start generated code]*/
1250n/a
1251n/astatic PyObject *
1252n/aarray_array_append(arrayobject *self, PyObject *v)
1253n/a/*[clinic end generated code: output=745a0669bf8db0e2 input=0b98d9d78e78f0fa]*/
1254n/a{
1255n/a return ins(self, Py_SIZE(self), v);
1256n/a}
1257n/a
1258n/a/*[clinic input]
1259n/aarray.array.byteswap
1260n/a
1261n/aByteswap all items of the array.
1262n/a
1263n/aIf the items in the array are not 1, 2, 4, or 8 bytes in size, RuntimeError is
1264n/araised.
1265n/a[clinic start generated code]*/
1266n/a
1267n/astatic PyObject *
1268n/aarray_array_byteswap_impl(arrayobject *self)
1269n/a/*[clinic end generated code: output=5f8236cbdf0d90b5 input=6a85591b950a0186]*/
1270n/a{
1271n/a char *p;
1272n/a Py_ssize_t i;
1273n/a
1274n/a switch (self->ob_descr->itemsize) {
1275n/a case 1:
1276n/a break;
1277n/a case 2:
1278n/a for (p = self->ob_item, i = Py_SIZE(self); --i >= 0; p += 2) {
1279n/a char p0 = p[0];
1280n/a p[0] = p[1];
1281n/a p[1] = p0;
1282n/a }
1283n/a break;
1284n/a case 4:
1285n/a for (p = self->ob_item, i = Py_SIZE(self); --i >= 0; p += 4) {
1286n/a char p0 = p[0];
1287n/a char p1 = p[1];
1288n/a p[0] = p[3];
1289n/a p[1] = p[2];
1290n/a p[2] = p1;
1291n/a p[3] = p0;
1292n/a }
1293n/a break;
1294n/a case 8:
1295n/a for (p = self->ob_item, i = Py_SIZE(self); --i >= 0; p += 8) {
1296n/a char p0 = p[0];
1297n/a char p1 = p[1];
1298n/a char p2 = p[2];
1299n/a char p3 = p[3];
1300n/a p[0] = p[7];
1301n/a p[1] = p[6];
1302n/a p[2] = p[5];
1303n/a p[3] = p[4];
1304n/a p[4] = p3;
1305n/a p[5] = p2;
1306n/a p[6] = p1;
1307n/a p[7] = p0;
1308n/a }
1309n/a break;
1310n/a default:
1311n/a PyErr_SetString(PyExc_RuntimeError,
1312n/a "don't know how to byteswap this array type");
1313n/a return NULL;
1314n/a }
1315n/a Py_RETURN_NONE;
1316n/a}
1317n/a
1318n/a/*[clinic input]
1319n/aarray.array.reverse
1320n/a
1321n/aReverse the order of the items in the array.
1322n/a[clinic start generated code]*/
1323n/a
1324n/astatic PyObject *
1325n/aarray_array_reverse_impl(arrayobject *self)
1326n/a/*[clinic end generated code: output=c04868b36f6f4089 input=cd904f01b27d966a]*/
1327n/a{
1328n/a Py_ssize_t itemsize = self->ob_descr->itemsize;
1329n/a char *p, *q;
1330n/a /* little buffer to hold items while swapping */
1331n/a char tmp[256]; /* 8 is probably enough -- but why skimp */
1332n/a assert((size_t)itemsize <= sizeof(tmp));
1333n/a
1334n/a if (Py_SIZE(self) > 1) {
1335n/a for (p = self->ob_item,
1336n/a q = self->ob_item + (Py_SIZE(self) - 1)*itemsize;
1337n/a p < q;
1338n/a p += itemsize, q -= itemsize) {
1339n/a /* memory areas guaranteed disjoint, so memcpy
1340n/a * is safe (& memmove may be slower).
1341n/a */
1342n/a memcpy(tmp, p, itemsize);
1343n/a memcpy(p, q, itemsize);
1344n/a memcpy(q, tmp, itemsize);
1345n/a }
1346n/a }
1347n/a
1348n/a Py_RETURN_NONE;
1349n/a}
1350n/a
1351n/a/*[clinic input]
1352n/aarray.array.fromfile
1353n/a
1354n/a f: object
1355n/a n: Py_ssize_t
1356n/a /
1357n/a
1358n/aRead n objects from the file object f and append them to the end of the array.
1359n/a[clinic start generated code]*/
1360n/a
1361n/astatic PyObject *
1362n/aarray_array_fromfile_impl(arrayobject *self, PyObject *f, Py_ssize_t n)
1363n/a/*[clinic end generated code: output=ec9f600e10f53510 input=e188afe8e58adf40]*/
1364n/a{
1365n/a PyObject *b, *res;
1366n/a Py_ssize_t itemsize = self->ob_descr->itemsize;
1367n/a Py_ssize_t nbytes;
1368n/a _Py_IDENTIFIER(read);
1369n/a int not_enough_bytes;
1370n/a
1371n/a if (n < 0) {
1372n/a PyErr_SetString(PyExc_ValueError, "negative count");
1373n/a return NULL;
1374n/a }
1375n/a if (n > PY_SSIZE_T_MAX / itemsize) {
1376n/a PyErr_NoMemory();
1377n/a return NULL;
1378n/a }
1379n/a nbytes = n * itemsize;
1380n/a
1381n/a b = _PyObject_CallMethodId(f, &PyId_read, "n", nbytes);
1382n/a if (b == NULL)
1383n/a return NULL;
1384n/a
1385n/a if (!PyBytes_Check(b)) {
1386n/a PyErr_SetString(PyExc_TypeError,
1387n/a "read() didn't return bytes");
1388n/a Py_DECREF(b);
1389n/a return NULL;
1390n/a }
1391n/a
1392n/a not_enough_bytes = (PyBytes_GET_SIZE(b) != nbytes);
1393n/a
1394n/a res = array_array_frombytes(self, b);
1395n/a Py_DECREF(b);
1396n/a if (res == NULL)
1397n/a return NULL;
1398n/a
1399n/a if (not_enough_bytes) {
1400n/a PyErr_SetString(PyExc_EOFError,
1401n/a "read() didn't return enough bytes");
1402n/a Py_DECREF(res);
1403n/a return NULL;
1404n/a }
1405n/a
1406n/a return res;
1407n/a}
1408n/a
1409n/a/*[clinic input]
1410n/aarray.array.tofile
1411n/a
1412n/a f: object
1413n/a /
1414n/a
1415n/aWrite all items (as machine values) to the file object f.
1416n/a[clinic start generated code]*/
1417n/a
1418n/astatic PyObject *
1419n/aarray_array_tofile(arrayobject *self, PyObject *f)
1420n/a/*[clinic end generated code: output=3a2cfa8128df0777 input=b0669a484aab0831]*/
1421n/a{
1422n/a Py_ssize_t nbytes = Py_SIZE(self) * self->ob_descr->itemsize;
1423n/a /* Write 64K blocks at a time */
1424n/a /* XXX Make the block size settable */
1425n/a int BLOCKSIZE = 64*1024;
1426n/a Py_ssize_t nblocks = (nbytes + BLOCKSIZE - 1) / BLOCKSIZE;
1427n/a Py_ssize_t i;
1428n/a
1429n/a if (Py_SIZE(self) == 0)
1430n/a goto done;
1431n/a
1432n/a for (i = 0; i < nblocks; i++) {
1433n/a char* ptr = self->ob_item + i*BLOCKSIZE;
1434n/a Py_ssize_t size = BLOCKSIZE;
1435n/a PyObject *bytes, *res;
1436n/a _Py_IDENTIFIER(write);
1437n/a
1438n/a if (i*BLOCKSIZE + size > nbytes)
1439n/a size = nbytes - i*BLOCKSIZE;
1440n/a bytes = PyBytes_FromStringAndSize(ptr, size);
1441n/a if (bytes == NULL)
1442n/a return NULL;
1443n/a res = _PyObject_CallMethodIdObjArgs(f, &PyId_write, bytes, NULL);
1444n/a Py_DECREF(bytes);
1445n/a if (res == NULL)
1446n/a return NULL;
1447n/a Py_DECREF(res); /* drop write result */
1448n/a }
1449n/a
1450n/a done:
1451n/a Py_RETURN_NONE;
1452n/a}
1453n/a
1454n/a/*[clinic input]
1455n/aarray.array.fromlist
1456n/a
1457n/a list: object
1458n/a /
1459n/a
1460n/aAppend items to array from list.
1461n/a[clinic start generated code]*/
1462n/a
1463n/astatic PyObject *
1464n/aarray_array_fromlist(arrayobject *self, PyObject *list)
1465n/a/*[clinic end generated code: output=26411c2d228a3e3f input=be2605a96c49680f]*/
1466n/a{
1467n/a Py_ssize_t n;
1468n/a
1469n/a if (!PyList_Check(list)) {
1470n/a PyErr_SetString(PyExc_TypeError, "arg must be list");
1471n/a return NULL;
1472n/a }
1473n/a n = PyList_Size(list);
1474n/a if (n > 0) {
1475n/a Py_ssize_t i, old_size;
1476n/a old_size = Py_SIZE(self);
1477n/a if (array_resize(self, old_size + n) == -1)
1478n/a return NULL;
1479n/a for (i = 0; i < n; i++) {
1480n/a PyObject *v = PyList_GetItem(list, i);
1481n/a if ((*self->ob_descr->setitem)(self,
1482n/a Py_SIZE(self) - n + i, v) != 0) {
1483n/a array_resize(self, old_size);
1484n/a return NULL;
1485n/a }
1486n/a }
1487n/a }
1488n/a Py_RETURN_NONE;
1489n/a}
1490n/a
1491n/a/*[clinic input]
1492n/aarray.array.tolist
1493n/a
1494n/aConvert array to an ordinary list with the same items.
1495n/a[clinic start generated code]*/
1496n/a
1497n/astatic PyObject *
1498n/aarray_array_tolist_impl(arrayobject *self)
1499n/a/*[clinic end generated code: output=00b60cc9eab8ef89 input=a8d7784a94f86b53]*/
1500n/a{
1501n/a PyObject *list = PyList_New(Py_SIZE(self));
1502n/a Py_ssize_t i;
1503n/a
1504n/a if (list == NULL)
1505n/a return NULL;
1506n/a for (i = 0; i < Py_SIZE(self); i++) {
1507n/a PyObject *v = getarrayitem((PyObject *)self, i);
1508n/a if (v == NULL)
1509n/a goto error;
1510n/a if (PyList_SetItem(list, i, v) < 0)
1511n/a goto error;
1512n/a }
1513n/a return list;
1514n/a
1515n/aerror:
1516n/a Py_DECREF(list);
1517n/a return NULL;
1518n/a}
1519n/a
1520n/astatic PyObject *
1521n/afrombytes(arrayobject *self, Py_buffer *buffer)
1522n/a{
1523n/a int itemsize = self->ob_descr->itemsize;
1524n/a Py_ssize_t n;
1525n/a if (buffer->itemsize != 1) {
1526n/a PyBuffer_Release(buffer);
1527n/a PyErr_SetString(PyExc_TypeError, "a bytes-like object is required");
1528n/a return NULL;
1529n/a }
1530n/a n = buffer->len;
1531n/a if (n % itemsize != 0) {
1532n/a PyBuffer_Release(buffer);
1533n/a PyErr_SetString(PyExc_ValueError,
1534n/a "bytes length not a multiple of item size");
1535n/a return NULL;
1536n/a }
1537n/a n = n / itemsize;
1538n/a if (n > 0) {
1539n/a Py_ssize_t old_size = Py_SIZE(self);
1540n/a if ((n > PY_SSIZE_T_MAX - old_size) ||
1541n/a ((old_size + n) > PY_SSIZE_T_MAX / itemsize)) {
1542n/a PyBuffer_Release(buffer);
1543n/a return PyErr_NoMemory();
1544n/a }
1545n/a if (array_resize(self, old_size + n) == -1) {
1546n/a PyBuffer_Release(buffer);
1547n/a return NULL;
1548n/a }
1549n/a memcpy(self->ob_item + old_size * itemsize,
1550n/a buffer->buf, n * itemsize);
1551n/a }
1552n/a PyBuffer_Release(buffer);
1553n/a Py_RETURN_NONE;
1554n/a}
1555n/a
1556n/a/*[clinic input]
1557n/aarray.array.fromstring
1558n/a
1559n/a buffer: Py_buffer(accept={str, buffer})
1560n/a /
1561n/a
1562n/aAppends items from the string, interpreting it as an array of machine values, as if it had been read from a file using the fromfile() method).
1563n/a
1564n/aThis method is deprecated. Use frombytes instead.
1565n/a[clinic start generated code]*/
1566n/a
1567n/astatic PyObject *
1568n/aarray_array_fromstring_impl(arrayobject *self, Py_buffer *buffer)
1569n/a/*[clinic end generated code: output=31c4baa779df84ce input=a3341a512e11d773]*/
1570n/a{
1571n/a if (PyErr_WarnEx(PyExc_DeprecationWarning,
1572n/a "fromstring() is deprecated. Use frombytes() instead.", 2) != 0)
1573n/a return NULL;
1574n/a return frombytes(self, buffer);
1575n/a}
1576n/a
1577n/a/*[clinic input]
1578n/aarray.array.frombytes
1579n/a
1580n/a buffer: Py_buffer
1581n/a /
1582n/a
1583n/aAppends items from the string, interpreting it as an array of machine values, as if it had been read from a file using the fromfile() method).
1584n/a[clinic start generated code]*/
1585n/a
1586n/astatic PyObject *
1587n/aarray_array_frombytes_impl(arrayobject *self, Py_buffer *buffer)
1588n/a/*[clinic end generated code: output=d9842c8f7510a516 input=2bbf2b53ebfcc988]*/
1589n/a{
1590n/a return frombytes(self, buffer);
1591n/a}
1592n/a
1593n/a/*[clinic input]
1594n/aarray.array.tobytes
1595n/a
1596n/aConvert the array to an array of machine values and return the bytes representation.
1597n/a[clinic start generated code]*/
1598n/a
1599n/astatic PyObject *
1600n/aarray_array_tobytes_impl(arrayobject *self)
1601n/a/*[clinic end generated code: output=87318e4edcdc2bb6 input=90ee495f96de34f5]*/
1602n/a{
1603n/a if (Py_SIZE(self) <= PY_SSIZE_T_MAX / self->ob_descr->itemsize) {
1604n/a return PyBytes_FromStringAndSize(self->ob_item,
1605n/a Py_SIZE(self) * self->ob_descr->itemsize);
1606n/a } else {
1607n/a return PyErr_NoMemory();
1608n/a }
1609n/a}
1610n/a
1611n/a/*[clinic input]
1612n/aarray.array.tostring
1613n/a
1614n/aConvert the array to an array of machine values and return the bytes representation.
1615n/a
1616n/aThis method is deprecated. Use tobytes instead.
1617n/a[clinic start generated code]*/
1618n/a
1619n/astatic PyObject *
1620n/aarray_array_tostring_impl(arrayobject *self)
1621n/a/*[clinic end generated code: output=7d6bd92745a2c8f3 input=b6c0ddee7b30457e]*/
1622n/a{
1623n/a if (PyErr_WarnEx(PyExc_DeprecationWarning,
1624n/a "tostring() is deprecated. Use tobytes() instead.", 2) != 0)
1625n/a return NULL;
1626n/a return array_array_tobytes_impl(self);
1627n/a}
1628n/a
1629n/a/*[clinic input]
1630n/aarray.array.fromunicode
1631n/a
1632n/a ustr: Py_UNICODE(zeroes=True)
1633n/a /
1634n/a
1635n/aExtends this array with data from the unicode string ustr.
1636n/a
1637n/aThe array must be a unicode type array; otherwise a ValueError is raised.
1638n/aUse array.frombytes(ustr.encode(...)) to append Unicode data to an array of
1639n/asome other type.
1640n/a[clinic start generated code]*/
1641n/a
1642n/astatic PyObject *
1643n/aarray_array_fromunicode_impl(arrayobject *self, Py_UNICODE *ustr,
1644n/a Py_ssize_clean_t ustr_length)
1645n/a/*[clinic end generated code: output=ebb72fc16975e06d input=150f00566ffbca6e]*/
1646n/a{
1647n/a char typecode;
1648n/a
1649n/a typecode = self->ob_descr->typecode;
1650n/a if (typecode != 'u') {
1651n/a PyErr_SetString(PyExc_ValueError,
1652n/a "fromunicode() may only be called on "
1653n/a "unicode type arrays");
1654n/a return NULL;
1655n/a }
1656n/a if (ustr_length > 0) {
1657n/a Py_ssize_t old_size = Py_SIZE(self);
1658n/a if (array_resize(self, old_size + ustr_length) == -1)
1659n/a return NULL;
1660n/a memcpy(self->ob_item + old_size * sizeof(Py_UNICODE),
1661n/a ustr, ustr_length * sizeof(Py_UNICODE));
1662n/a }
1663n/a
1664n/a Py_RETURN_NONE;
1665n/a}
1666n/a
1667n/a/*[clinic input]
1668n/aarray.array.tounicode
1669n/a
1670n/aExtends this array with data from the unicode string ustr.
1671n/a
1672n/aConvert the array to a unicode string. The array must be a unicode type array;
1673n/aotherwise a ValueError is raised. Use array.tobytes().decode() to obtain a
1674n/aunicode string from an array of some other type.
1675n/a[clinic start generated code]*/
1676n/a
1677n/astatic PyObject *
1678n/aarray_array_tounicode_impl(arrayobject *self)
1679n/a/*[clinic end generated code: output=08e442378336e1ef input=127242eebe70b66d]*/
1680n/a{
1681n/a char typecode;
1682n/a typecode = self->ob_descr->typecode;
1683n/a if (typecode != 'u') {
1684n/a PyErr_SetString(PyExc_ValueError,
1685n/a "tounicode() may only be called on unicode type arrays");
1686n/a return NULL;
1687n/a }
1688n/a return PyUnicode_FromWideChar((Py_UNICODE *) self->ob_item, Py_SIZE(self));
1689n/a}
1690n/a
1691n/a/*[clinic input]
1692n/aarray.array.__sizeof__
1693n/a
1694n/aSize of the array in memory, in bytes.
1695n/a[clinic start generated code]*/
1696n/a
1697n/astatic PyObject *
1698n/aarray_array___sizeof___impl(arrayobject *self)
1699n/a/*[clinic end generated code: output=d8e1c61ebbe3eaed input=805586565bf2b3c6]*/
1700n/a{
1701n/a Py_ssize_t res;
1702n/a res = _PyObject_SIZE(Py_TYPE(self)) + self->allocated * self->ob_descr->itemsize;
1703n/a return PyLong_FromSsize_t(res);
1704n/a}
1705n/a
1706n/a
1707n/a/*********************** Pickling support ************************/
1708n/a
1709n/astatic const struct mformatdescr {
1710n/a size_t size;
1711n/a int is_signed;
1712n/a int is_big_endian;
1713n/a} mformat_descriptors[] = {
1714n/a {1, 0, 0}, /* 0: UNSIGNED_INT8 */
1715n/a {1, 1, 0}, /* 1: SIGNED_INT8 */
1716n/a {2, 0, 0}, /* 2: UNSIGNED_INT16_LE */
1717n/a {2, 0, 1}, /* 3: UNSIGNED_INT16_BE */
1718n/a {2, 1, 0}, /* 4: SIGNED_INT16_LE */
1719n/a {2, 1, 1}, /* 5: SIGNED_INT16_BE */
1720n/a {4, 0, 0}, /* 6: UNSIGNED_INT32_LE */
1721n/a {4, 0, 1}, /* 7: UNSIGNED_INT32_BE */
1722n/a {4, 1, 0}, /* 8: SIGNED_INT32_LE */
1723n/a {4, 1, 1}, /* 9: SIGNED_INT32_BE */
1724n/a {8, 0, 0}, /* 10: UNSIGNED_INT64_LE */
1725n/a {8, 0, 1}, /* 11: UNSIGNED_INT64_BE */
1726n/a {8, 1, 0}, /* 12: SIGNED_INT64_LE */
1727n/a {8, 1, 1}, /* 13: SIGNED_INT64_BE */
1728n/a {4, 0, 0}, /* 14: IEEE_754_FLOAT_LE */
1729n/a {4, 0, 1}, /* 15: IEEE_754_FLOAT_BE */
1730n/a {8, 0, 0}, /* 16: IEEE_754_DOUBLE_LE */
1731n/a {8, 0, 1}, /* 17: IEEE_754_DOUBLE_BE */
1732n/a {4, 0, 0}, /* 18: UTF16_LE */
1733n/a {4, 0, 1}, /* 19: UTF16_BE */
1734n/a {8, 0, 0}, /* 20: UTF32_LE */
1735n/a {8, 0, 1} /* 21: UTF32_BE */
1736n/a};
1737n/a
1738n/a
1739n/a/*
1740n/a * Internal: This function is used to find the machine format of a given
1741n/a * array type code. This returns UNKNOWN_FORMAT when the machine format cannot
1742n/a * be found.
1743n/a */
1744n/astatic enum machine_format_code
1745n/atypecode_to_mformat_code(char typecode)
1746n/a{
1747n/a const int is_big_endian = PY_BIG_ENDIAN;
1748n/a
1749n/a size_t intsize;
1750n/a int is_signed;
1751n/a
1752n/a switch (typecode) {
1753n/a case 'b':
1754n/a return SIGNED_INT8;
1755n/a case 'B':
1756n/a return UNSIGNED_INT8;
1757n/a
1758n/a case 'u':
1759n/a if (sizeof(Py_UNICODE) == 2) {
1760n/a return UTF16_LE + is_big_endian;
1761n/a }
1762n/a if (sizeof(Py_UNICODE) == 4) {
1763n/a return UTF32_LE + is_big_endian;
1764n/a }
1765n/a return UNKNOWN_FORMAT;
1766n/a
1767n/a case 'f':
1768n/a if (sizeof(float) == 4) {
1769n/a const float y = 16711938.0;
1770n/a if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1771n/a return IEEE_754_FLOAT_BE;
1772n/a if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1773n/a return IEEE_754_FLOAT_LE;
1774n/a }
1775n/a return UNKNOWN_FORMAT;
1776n/a
1777n/a case 'd':
1778n/a if (sizeof(double) == 8) {
1779n/a const double x = 9006104071832581.0;
1780n/a if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1781n/a return IEEE_754_DOUBLE_BE;
1782n/a if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1783n/a return IEEE_754_DOUBLE_LE;
1784n/a }
1785n/a return UNKNOWN_FORMAT;
1786n/a
1787n/a /* Integers */
1788n/a case 'h':
1789n/a intsize = sizeof(short);
1790n/a is_signed = 1;
1791n/a break;
1792n/a case 'H':
1793n/a intsize = sizeof(short);
1794n/a is_signed = 0;
1795n/a break;
1796n/a case 'i':
1797n/a intsize = sizeof(int);
1798n/a is_signed = 1;
1799n/a break;
1800n/a case 'I':
1801n/a intsize = sizeof(int);
1802n/a is_signed = 0;
1803n/a break;
1804n/a case 'l':
1805n/a intsize = sizeof(long);
1806n/a is_signed = 1;
1807n/a break;
1808n/a case 'L':
1809n/a intsize = sizeof(long);
1810n/a is_signed = 0;
1811n/a break;
1812n/a case 'q':
1813n/a intsize = sizeof(long long);
1814n/a is_signed = 1;
1815n/a break;
1816n/a case 'Q':
1817n/a intsize = sizeof(long long);
1818n/a is_signed = 0;
1819n/a break;
1820n/a default:
1821n/a return UNKNOWN_FORMAT;
1822n/a }
1823n/a switch (intsize) {
1824n/a case 2:
1825n/a return UNSIGNED_INT16_LE + is_big_endian + (2 * is_signed);
1826n/a case 4:
1827n/a return UNSIGNED_INT32_LE + is_big_endian + (2 * is_signed);
1828n/a case 8:
1829n/a return UNSIGNED_INT64_LE + is_big_endian + (2 * is_signed);
1830n/a default:
1831n/a return UNKNOWN_FORMAT;
1832n/a }
1833n/a}
1834n/a
1835n/a/* Forward declaration. */
1836n/astatic PyObject *array_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1837n/a
1838n/a/*
1839n/a * Internal: This function wraps the array constructor--i.e., array_new()--to
1840n/a * allow the creation of array objects from C code without having to deal
1841n/a * directly the tuple argument of array_new(). The typecode argument is a
1842n/a * Unicode character value, like 'i' or 'f' for example, representing an array
1843n/a * type code. The items argument is a bytes or a list object from which
1844n/a * contains the initial value of the array.
1845n/a *
1846n/a * On success, this functions returns the array object created. Otherwise,
1847n/a * NULL is returned to indicate a failure.
1848n/a */
1849n/astatic PyObject *
1850n/amake_array(PyTypeObject *arraytype, char typecode, PyObject *items)
1851n/a{
1852n/a PyObject *new_args;
1853n/a PyObject *array_obj;
1854n/a PyObject *typecode_obj;
1855n/a
1856n/a assert(arraytype != NULL);
1857n/a assert(items != NULL);
1858n/a
1859n/a typecode_obj = PyUnicode_FromOrdinal(typecode);
1860n/a if (typecode_obj == NULL)
1861n/a return NULL;
1862n/a
1863n/a new_args = PyTuple_New(2);
1864n/a if (new_args == NULL)
1865n/a return NULL;
1866n/a Py_INCREF(items);
1867n/a PyTuple_SET_ITEM(new_args, 0, typecode_obj);
1868n/a PyTuple_SET_ITEM(new_args, 1, items);
1869n/a
1870n/a array_obj = array_new(arraytype, new_args, NULL);
1871n/a Py_DECREF(new_args);
1872n/a if (array_obj == NULL)
1873n/a return NULL;
1874n/a
1875n/a return array_obj;
1876n/a}
1877n/a
1878n/a/*
1879n/a * This functions is a special constructor used when unpickling an array. It
1880n/a * provides a portable way to rebuild an array from its memory representation.
1881n/a */
1882n/a/*[clinic input]
1883n/aarray._array_reconstructor
1884n/a
1885n/a arraytype: object(type="PyTypeObject *")
1886n/a typecode: int(accept={str})
1887n/a mformat_code: int(type="enum machine_format_code")
1888n/a items: object
1889n/a /
1890n/a
1891n/aInternal. Used for pickling support.
1892n/a[clinic start generated code]*/
1893n/a
1894n/astatic PyObject *
1895n/aarray__array_reconstructor_impl(PyObject *module, PyTypeObject *arraytype,
1896n/a int typecode,
1897n/a enum machine_format_code mformat_code,
1898n/a PyObject *items)
1899n/a/*[clinic end generated code: output=e05263141ba28365 input=2464dc8f4c7736b5]*/
1900n/a{
1901n/a PyObject *converted_items;
1902n/a PyObject *result;
1903n/a const struct arraydescr *descr;
1904n/a
1905n/a if (!PyType_Check(arraytype)) {
1906n/a PyErr_Format(PyExc_TypeError,
1907n/a "first argument must a type object, not %.200s",
1908n/a Py_TYPE(arraytype)->tp_name);
1909n/a return NULL;
1910n/a }
1911n/a if (!PyType_IsSubtype(arraytype, &Arraytype)) {
1912n/a PyErr_Format(PyExc_TypeError,
1913n/a "%.200s is not a subtype of %.200s",
1914n/a arraytype->tp_name, Arraytype.tp_name);
1915n/a return NULL;
1916n/a }
1917n/a for (descr = descriptors; descr->typecode != '\0'; descr++) {
1918n/a if ((int)descr->typecode == typecode)
1919n/a break;
1920n/a }
1921n/a if (descr->typecode == '\0') {
1922n/a PyErr_SetString(PyExc_ValueError,
1923n/a "second argument must be a valid type code");
1924n/a return NULL;
1925n/a }
1926n/a if (mformat_code < MACHINE_FORMAT_CODE_MIN ||
1927n/a mformat_code > MACHINE_FORMAT_CODE_MAX) {
1928n/a PyErr_SetString(PyExc_ValueError,
1929n/a "third argument must be a valid machine format code.");
1930n/a return NULL;
1931n/a }
1932n/a if (!PyBytes_Check(items)) {
1933n/a PyErr_Format(PyExc_TypeError,
1934n/a "fourth argument should be bytes, not %.200s",
1935n/a Py_TYPE(items)->tp_name);
1936n/a return NULL;
1937n/a }
1938n/a
1939n/a /* Fast path: No decoding has to be done. */
1940n/a if (mformat_code == typecode_to_mformat_code((char)typecode) ||
1941n/a mformat_code == UNKNOWN_FORMAT) {
1942n/a return make_array(arraytype, (char)typecode, items);
1943n/a }
1944n/a
1945n/a /* Slow path: Decode the byte string according to the given machine
1946n/a * format code. This occurs when the computer unpickling the array
1947n/a * object is architecturally different from the one that pickled the
1948n/a * array.
1949n/a */
1950n/a if (Py_SIZE(items) % mformat_descriptors[mformat_code].size != 0) {
1951n/a PyErr_SetString(PyExc_ValueError,
1952n/a "string length not a multiple of item size");
1953n/a return NULL;
1954n/a }
1955n/a switch (mformat_code) {
1956n/a case IEEE_754_FLOAT_LE:
1957n/a case IEEE_754_FLOAT_BE: {
1958n/a int i;
1959n/a int le = (mformat_code == IEEE_754_FLOAT_LE) ? 1 : 0;
1960n/a Py_ssize_t itemcount = Py_SIZE(items) / 4;
1961n/a const unsigned char *memstr =
1962n/a (unsigned char *)PyBytes_AS_STRING(items);
1963n/a
1964n/a converted_items = PyList_New(itemcount);
1965n/a if (converted_items == NULL)
1966n/a return NULL;
1967n/a for (i = 0; i < itemcount; i++) {
1968n/a PyObject *pyfloat = PyFloat_FromDouble(
1969n/a _PyFloat_Unpack4(&memstr[i * 4], le));
1970n/a if (pyfloat == NULL) {
1971n/a Py_DECREF(converted_items);
1972n/a return NULL;
1973n/a }
1974n/a PyList_SET_ITEM(converted_items, i, pyfloat);
1975n/a }
1976n/a break;
1977n/a }
1978n/a case IEEE_754_DOUBLE_LE:
1979n/a case IEEE_754_DOUBLE_BE: {
1980n/a int i;
1981n/a int le = (mformat_code == IEEE_754_DOUBLE_LE) ? 1 : 0;
1982n/a Py_ssize_t itemcount = Py_SIZE(items) / 8;
1983n/a const unsigned char *memstr =
1984n/a (unsigned char *)PyBytes_AS_STRING(items);
1985n/a
1986n/a converted_items = PyList_New(itemcount);
1987n/a if (converted_items == NULL)
1988n/a return NULL;
1989n/a for (i = 0; i < itemcount; i++) {
1990n/a PyObject *pyfloat = PyFloat_FromDouble(
1991n/a _PyFloat_Unpack8(&memstr[i * 8], le));
1992n/a if (pyfloat == NULL) {
1993n/a Py_DECREF(converted_items);
1994n/a return NULL;
1995n/a }
1996n/a PyList_SET_ITEM(converted_items, i, pyfloat);
1997n/a }
1998n/a break;
1999n/a }
2000n/a case UTF16_LE:
2001n/a case UTF16_BE: {
2002n/a int byteorder = (mformat_code == UTF16_LE) ? -1 : 1;
2003n/a converted_items = PyUnicode_DecodeUTF16(
2004n/a PyBytes_AS_STRING(items), Py_SIZE(items),
2005n/a "strict", &byteorder);
2006n/a if (converted_items == NULL)
2007n/a return NULL;
2008n/a break;
2009n/a }
2010n/a case UTF32_LE:
2011n/a case UTF32_BE: {
2012n/a int byteorder = (mformat_code == UTF32_LE) ? -1 : 1;
2013n/a converted_items = PyUnicode_DecodeUTF32(
2014n/a PyBytes_AS_STRING(items), Py_SIZE(items),
2015n/a "strict", &byteorder);
2016n/a if (converted_items == NULL)
2017n/a return NULL;
2018n/a break;
2019n/a }
2020n/a
2021n/a case UNSIGNED_INT8:
2022n/a case SIGNED_INT8:
2023n/a case UNSIGNED_INT16_LE:
2024n/a case UNSIGNED_INT16_BE:
2025n/a case SIGNED_INT16_LE:
2026n/a case SIGNED_INT16_BE:
2027n/a case UNSIGNED_INT32_LE:
2028n/a case UNSIGNED_INT32_BE:
2029n/a case SIGNED_INT32_LE:
2030n/a case SIGNED_INT32_BE:
2031n/a case UNSIGNED_INT64_LE:
2032n/a case UNSIGNED_INT64_BE:
2033n/a case SIGNED_INT64_LE:
2034n/a case SIGNED_INT64_BE: {
2035n/a int i;
2036n/a const struct mformatdescr mf_descr =
2037n/a mformat_descriptors[mformat_code];
2038n/a Py_ssize_t itemcount = Py_SIZE(items) / mf_descr.size;
2039n/a const unsigned char *memstr =
2040n/a (unsigned char *)PyBytes_AS_STRING(items);
2041n/a const struct arraydescr *descr;
2042n/a
2043n/a /* If possible, try to pack array's items using a data type
2044n/a * that fits better. This may result in an array with narrower
2045n/a * or wider elements.
2046n/a *
2047n/a * For example, if a 32-bit machine pickles an L-code array of
2048n/a * unsigned longs, then the array will be unpickled by 64-bit
2049n/a * machine as an I-code array of unsigned ints.
2050n/a *
2051n/a * XXX: Is it possible to write a unit test for this?
2052n/a */
2053n/a for (descr = descriptors; descr->typecode != '\0'; descr++) {
2054n/a if (descr->is_integer_type &&
2055n/a (size_t)descr->itemsize == mf_descr.size &&
2056n/a descr->is_signed == mf_descr.is_signed)
2057n/a typecode = descr->typecode;
2058n/a }
2059n/a
2060n/a converted_items = PyList_New(itemcount);
2061n/a if (converted_items == NULL)
2062n/a return NULL;
2063n/a for (i = 0; i < itemcount; i++) {
2064n/a PyObject *pylong;
2065n/a
2066n/a pylong = _PyLong_FromByteArray(
2067n/a &memstr[i * mf_descr.size],
2068n/a mf_descr.size,
2069n/a !mf_descr.is_big_endian,
2070n/a mf_descr.is_signed);
2071n/a if (pylong == NULL) {
2072n/a Py_DECREF(converted_items);
2073n/a return NULL;
2074n/a }
2075n/a PyList_SET_ITEM(converted_items, i, pylong);
2076n/a }
2077n/a break;
2078n/a }
2079n/a case UNKNOWN_FORMAT:
2080n/a /* Impossible, but needed to shut up GCC about the unhandled
2081n/a * enumeration value.
2082n/a */
2083n/a default:
2084n/a PyErr_BadArgument();
2085n/a return NULL;
2086n/a }
2087n/a
2088n/a result = make_array(arraytype, (char)typecode, converted_items);
2089n/a Py_DECREF(converted_items);
2090n/a return result;
2091n/a}
2092n/a
2093n/a/*[clinic input]
2094n/aarray.array.__reduce_ex__
2095n/a
2096n/a value: object
2097n/a /
2098n/a
2099n/aReturn state information for pickling.
2100n/a[clinic start generated code]*/
2101n/a
2102n/astatic PyObject *
2103n/aarray_array___reduce_ex__(arrayobject *self, PyObject *value)
2104n/a/*[clinic end generated code: output=051e0a6175d0eddb input=c36c3f85de7df6cd]*/
2105n/a{
2106n/a PyObject *dict;
2107n/a PyObject *result;
2108n/a PyObject *array_str;
2109n/a int typecode = self->ob_descr->typecode;
2110n/a int mformat_code;
2111n/a static PyObject *array_reconstructor = NULL;
2112n/a long protocol;
2113n/a _Py_IDENTIFIER(_array_reconstructor);
2114n/a _Py_IDENTIFIER(__dict__);
2115n/a
2116n/a if (array_reconstructor == NULL) {
2117n/a PyObject *array_module = PyImport_ImportModule("array");
2118n/a if (array_module == NULL)
2119n/a return NULL;
2120n/a array_reconstructor = _PyObject_GetAttrId(
2121n/a array_module,
2122n/a &PyId__array_reconstructor);
2123n/a Py_DECREF(array_module);
2124n/a if (array_reconstructor == NULL)
2125n/a return NULL;
2126n/a }
2127n/a
2128n/a if (!PyLong_Check(value)) {
2129n/a PyErr_SetString(PyExc_TypeError,
2130n/a "__reduce_ex__ argument should an integer");
2131n/a return NULL;
2132n/a }
2133n/a protocol = PyLong_AsLong(value);
2134n/a if (protocol == -1 && PyErr_Occurred())
2135n/a return NULL;
2136n/a
2137n/a dict = _PyObject_GetAttrId((PyObject *)self, &PyId___dict__);
2138n/a if (dict == NULL) {
2139n/a if (!PyErr_ExceptionMatches(PyExc_AttributeError))
2140n/a return NULL;
2141n/a PyErr_Clear();
2142n/a dict = Py_None;
2143n/a Py_INCREF(dict);
2144n/a }
2145n/a
2146n/a mformat_code = typecode_to_mformat_code(typecode);
2147n/a if (mformat_code == UNKNOWN_FORMAT || protocol < 3) {
2148n/a /* Convert the array to a list if we got something weird
2149n/a * (e.g., non-IEEE floats), or we are pickling the array using
2150n/a * a Python 2.x compatible protocol.
2151n/a *
2152n/a * It is necessary to use a list representation for Python 2.x
2153n/a * compatible pickle protocol, since Python 2's str objects
2154n/a * are unpickled as unicode by Python 3. Thus it is impossible
2155n/a * to make arrays unpicklable by Python 3 by using their memory
2156n/a * representation, unless we resort to ugly hacks such as
2157n/a * coercing unicode objects to bytes in array_reconstructor.
2158n/a */
2159n/a PyObject *list;
2160n/a list = array_array_tolist_impl(self);
2161n/a if (list == NULL) {
2162n/a Py_DECREF(dict);
2163n/a return NULL;
2164n/a }
2165n/a result = Py_BuildValue(
2166n/a "O(CO)O", Py_TYPE(self), typecode, list, dict);
2167n/a Py_DECREF(list);
2168n/a Py_DECREF(dict);
2169n/a return result;
2170n/a }
2171n/a
2172n/a array_str = array_array_tobytes_impl(self);
2173n/a if (array_str == NULL) {
2174n/a Py_DECREF(dict);
2175n/a return NULL;
2176n/a }
2177n/a result = Py_BuildValue(
2178n/a "O(OCiN)O", array_reconstructor, Py_TYPE(self), typecode,
2179n/a mformat_code, array_str, dict);
2180n/a Py_DECREF(dict);
2181n/a return result;
2182n/a}
2183n/a
2184n/astatic PyObject *
2185n/aarray_get_typecode(arrayobject *a, void *closure)
2186n/a{
2187n/a char typecode = a->ob_descr->typecode;
2188n/a return PyUnicode_FromOrdinal(typecode);
2189n/a}
2190n/a
2191n/astatic PyObject *
2192n/aarray_get_itemsize(arrayobject *a, void *closure)
2193n/a{
2194n/a return PyLong_FromLong((long)a->ob_descr->itemsize);
2195n/a}
2196n/a
2197n/astatic PyGetSetDef array_getsets [] = {
2198n/a {"typecode", (getter) array_get_typecode, NULL,
2199n/a "the typecode character used to create the array"},
2200n/a {"itemsize", (getter) array_get_itemsize, NULL,
2201n/a "the size, in bytes, of one array item"},
2202n/a {NULL}
2203n/a};
2204n/a
2205n/astatic PyMethodDef array_methods[] = {
2206n/a ARRAY_ARRAY_APPEND_METHODDEF
2207n/a ARRAY_ARRAY_BUFFER_INFO_METHODDEF
2208n/a ARRAY_ARRAY_BYTESWAP_METHODDEF
2209n/a ARRAY_ARRAY___COPY___METHODDEF
2210n/a ARRAY_ARRAY_COUNT_METHODDEF
2211n/a ARRAY_ARRAY___DEEPCOPY___METHODDEF
2212n/a ARRAY_ARRAY_EXTEND_METHODDEF
2213n/a ARRAY_ARRAY_FROMFILE_METHODDEF
2214n/a ARRAY_ARRAY_FROMLIST_METHODDEF
2215n/a ARRAY_ARRAY_FROMSTRING_METHODDEF
2216n/a ARRAY_ARRAY_FROMBYTES_METHODDEF
2217n/a ARRAY_ARRAY_FROMUNICODE_METHODDEF
2218n/a ARRAY_ARRAY_INDEX_METHODDEF
2219n/a ARRAY_ARRAY_INSERT_METHODDEF
2220n/a ARRAY_ARRAY_POP_METHODDEF
2221n/a ARRAY_ARRAY___REDUCE_EX___METHODDEF
2222n/a ARRAY_ARRAY_REMOVE_METHODDEF
2223n/a ARRAY_ARRAY_REVERSE_METHODDEF
2224n/a ARRAY_ARRAY_TOFILE_METHODDEF
2225n/a ARRAY_ARRAY_TOLIST_METHODDEF
2226n/a ARRAY_ARRAY_TOSTRING_METHODDEF
2227n/a ARRAY_ARRAY_TOBYTES_METHODDEF
2228n/a ARRAY_ARRAY_TOUNICODE_METHODDEF
2229n/a ARRAY_ARRAY___SIZEOF___METHODDEF
2230n/a {NULL, NULL} /* sentinel */
2231n/a};
2232n/a
2233n/astatic PyObject *
2234n/aarray_repr(arrayobject *a)
2235n/a{
2236n/a char typecode;
2237n/a PyObject *s, *v = NULL;
2238n/a Py_ssize_t len;
2239n/a
2240n/a len = Py_SIZE(a);
2241n/a typecode = a->ob_descr->typecode;
2242n/a if (len == 0) {
2243n/a return PyUnicode_FromFormat("array('%c')", (int)typecode);
2244n/a }
2245n/a if (typecode == 'u') {
2246n/a v = array_array_tounicode_impl(a);
2247n/a } else {
2248n/a v = array_array_tolist_impl(a);
2249n/a }
2250n/a if (v == NULL)
2251n/a return NULL;
2252n/a
2253n/a s = PyUnicode_FromFormat("array('%c', %R)", (int)typecode, v);
2254n/a Py_DECREF(v);
2255n/a return s;
2256n/a}
2257n/a
2258n/astatic PyObject*
2259n/aarray_subscr(arrayobject* self, PyObject* item)
2260n/a{
2261n/a if (PyIndex_Check(item)) {
2262n/a Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
2263n/a if (i==-1 && PyErr_Occurred()) {
2264n/a return NULL;
2265n/a }
2266n/a if (i < 0)
2267n/a i += Py_SIZE(self);
2268n/a return array_item(self, i);
2269n/a }
2270n/a else if (PySlice_Check(item)) {
2271n/a Py_ssize_t start, stop, step, slicelength, cur, i;
2272n/a PyObject* result;
2273n/a arrayobject* ar;
2274n/a int itemsize = self->ob_descr->itemsize;
2275n/a
2276n/a if (PySlice_GetIndicesEx(item, Py_SIZE(self),
2277n/a &start, &stop, &step, &slicelength) < 0) {
2278n/a return NULL;
2279n/a }
2280n/a
2281n/a if (slicelength <= 0) {
2282n/a return newarrayobject(&Arraytype, 0, self->ob_descr);
2283n/a }
2284n/a else if (step == 1) {
2285n/a PyObject *result = newarrayobject(&Arraytype,
2286n/a slicelength, self->ob_descr);
2287n/a if (result == NULL)
2288n/a return NULL;
2289n/a memcpy(((arrayobject *)result)->ob_item,
2290n/a self->ob_item + start * itemsize,
2291n/a slicelength * itemsize);
2292n/a return result;
2293n/a }
2294n/a else {
2295n/a result = newarrayobject(&Arraytype, slicelength, self->ob_descr);
2296n/a if (!result) return NULL;
2297n/a
2298n/a ar = (arrayobject*)result;
2299n/a
2300n/a for (cur = start, i = 0; i < slicelength;
2301n/a cur += step, i++) {
2302n/a memcpy(ar->ob_item + i*itemsize,
2303n/a self->ob_item + cur*itemsize,
2304n/a itemsize);
2305n/a }
2306n/a
2307n/a return result;
2308n/a }
2309n/a }
2310n/a else {
2311n/a PyErr_SetString(PyExc_TypeError,
2312n/a "array indices must be integers");
2313n/a return NULL;
2314n/a }
2315n/a}
2316n/a
2317n/astatic int
2318n/aarray_ass_subscr(arrayobject* self, PyObject* item, PyObject* value)
2319n/a{
2320n/a Py_ssize_t start, stop, step, slicelength, needed;
2321n/a arrayobject* other;
2322n/a int itemsize;
2323n/a
2324n/a if (PyIndex_Check(item)) {
2325n/a Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
2326n/a
2327n/a if (i == -1 && PyErr_Occurred())
2328n/a return -1;
2329n/a if (i < 0)
2330n/a i += Py_SIZE(self);
2331n/a if (i < 0 || i >= Py_SIZE(self)) {
2332n/a PyErr_SetString(PyExc_IndexError,
2333n/a "array assignment index out of range");
2334n/a return -1;
2335n/a }
2336n/a if (value == NULL) {
2337n/a /* Fall through to slice assignment */
2338n/a start = i;
2339n/a stop = i + 1;
2340n/a step = 1;
2341n/a slicelength = 1;
2342n/a }
2343n/a else
2344n/a return (*self->ob_descr->setitem)(self, i, value);
2345n/a }
2346n/a else if (PySlice_Check(item)) {
2347n/a if (PySlice_GetIndicesEx(item,
2348n/a Py_SIZE(self), &start, &stop,
2349n/a &step, &slicelength) < 0) {
2350n/a return -1;
2351n/a }
2352n/a }
2353n/a else {
2354n/a PyErr_SetString(PyExc_TypeError,
2355n/a "array indices must be integer");
2356n/a return -1;
2357n/a }
2358n/a if (value == NULL) {
2359n/a other = NULL;
2360n/a needed = 0;
2361n/a }
2362n/a else if (array_Check(value)) {
2363n/a other = (arrayobject *)value;
2364n/a needed = Py_SIZE(other);
2365n/a if (self == other) {
2366n/a /* Special case "self[i:j] = self" -- copy self first */
2367n/a int ret;
2368n/a value = array_slice(other, 0, needed);
2369n/a if (value == NULL)
2370n/a return -1;
2371n/a ret = array_ass_subscr(self, item, value);
2372n/a Py_DECREF(value);
2373n/a return ret;
2374n/a }
2375n/a if (other->ob_descr != self->ob_descr) {
2376n/a PyErr_BadArgument();
2377n/a return -1;
2378n/a }
2379n/a }
2380n/a else {
2381n/a PyErr_Format(PyExc_TypeError,
2382n/a "can only assign array (not \"%.200s\") to array slice",
2383n/a Py_TYPE(value)->tp_name);
2384n/a return -1;
2385n/a }
2386n/a itemsize = self->ob_descr->itemsize;
2387n/a /* for 'a[2:1] = ...', the insertion point is 'start', not 'stop' */
2388n/a if ((step > 0 && stop < start) ||
2389n/a (step < 0 && stop > start))
2390n/a stop = start;
2391n/a
2392n/a /* Issue #4509: If the array has exported buffers and the slice
2393n/a assignment would change the size of the array, fail early to make
2394n/a sure we don't modify it. */
2395n/a if ((needed == 0 || slicelength != needed) && self->ob_exports > 0) {
2396n/a PyErr_SetString(PyExc_BufferError,
2397n/a "cannot resize an array that is exporting buffers");
2398n/a return -1;
2399n/a }
2400n/a
2401n/a if (step == 1) {
2402n/a if (slicelength > needed) {
2403n/a memmove(self->ob_item + (start + needed) * itemsize,
2404n/a self->ob_item + stop * itemsize,
2405n/a (Py_SIZE(self) - stop) * itemsize);
2406n/a if (array_resize(self, Py_SIZE(self) +
2407n/a needed - slicelength) < 0)
2408n/a return -1;
2409n/a }
2410n/a else if (slicelength < needed) {
2411n/a if (array_resize(self, Py_SIZE(self) +
2412n/a needed - slicelength) < 0)
2413n/a return -1;
2414n/a memmove(self->ob_item + (start + needed) * itemsize,
2415n/a self->ob_item + stop * itemsize,
2416n/a (Py_SIZE(self) - start - needed) * itemsize);
2417n/a }
2418n/a if (needed > 0)
2419n/a memcpy(self->ob_item + start * itemsize,
2420n/a other->ob_item, needed * itemsize);
2421n/a return 0;
2422n/a }
2423n/a else if (needed == 0) {
2424n/a /* Delete slice */
2425n/a size_t cur;
2426n/a Py_ssize_t i;
2427n/a
2428n/a if (step < 0) {
2429n/a stop = start + 1;
2430n/a start = stop + step * (slicelength - 1) - 1;
2431n/a step = -step;
2432n/a }
2433n/a for (cur = start, i = 0; i < slicelength;
2434n/a cur += step, i++) {
2435n/a Py_ssize_t lim = step - 1;
2436n/a
2437n/a if (cur + step >= (size_t)Py_SIZE(self))
2438n/a lim = Py_SIZE(self) - cur - 1;
2439n/a memmove(self->ob_item + (cur - i) * itemsize,
2440n/a self->ob_item + (cur + 1) * itemsize,
2441n/a lim * itemsize);
2442n/a }
2443n/a cur = start + (size_t)slicelength * step;
2444n/a if (cur < (size_t)Py_SIZE(self)) {
2445n/a memmove(self->ob_item + (cur-slicelength) * itemsize,
2446n/a self->ob_item + cur * itemsize,
2447n/a (Py_SIZE(self) - cur) * itemsize);
2448n/a }
2449n/a if (array_resize(self, Py_SIZE(self) - slicelength) < 0)
2450n/a return -1;
2451n/a return 0;
2452n/a }
2453n/a else {
2454n/a Py_ssize_t cur, i;
2455n/a
2456n/a if (needed != slicelength) {
2457n/a PyErr_Format(PyExc_ValueError,
2458n/a "attempt to assign array of size %zd "
2459n/a "to extended slice of size %zd",
2460n/a needed, slicelength);
2461n/a return -1;
2462n/a }
2463n/a for (cur = start, i = 0; i < slicelength;
2464n/a cur += step, i++) {
2465n/a memcpy(self->ob_item + cur * itemsize,
2466n/a other->ob_item + i * itemsize,
2467n/a itemsize);
2468n/a }
2469n/a return 0;
2470n/a }
2471n/a}
2472n/a
2473n/astatic PyMappingMethods array_as_mapping = {
2474n/a (lenfunc)array_length,
2475n/a (binaryfunc)array_subscr,
2476n/a (objobjargproc)array_ass_subscr
2477n/a};
2478n/a
2479n/astatic const void *emptybuf = "";
2480n/a
2481n/a
2482n/astatic int
2483n/aarray_buffer_getbuf(arrayobject *self, Py_buffer *view, int flags)
2484n/a{
2485n/a if (view == NULL) {
2486n/a PyErr_SetString(PyExc_BufferError,
2487n/a "array_buffer_getbuf: view==NULL argument is obsolete");
2488n/a return -1;
2489n/a }
2490n/a
2491n/a view->buf = (void *)self->ob_item;
2492n/a view->obj = (PyObject*)self;
2493n/a Py_INCREF(self);
2494n/a if (view->buf == NULL)
2495n/a view->buf = (void *)emptybuf;
2496n/a view->len = (Py_SIZE(self)) * self->ob_descr->itemsize;
2497n/a view->readonly = 0;
2498n/a view->ndim = 1;
2499n/a view->itemsize = self->ob_descr->itemsize;
2500n/a view->suboffsets = NULL;
2501n/a view->shape = NULL;
2502n/a if ((flags & PyBUF_ND)==PyBUF_ND) {
2503n/a view->shape = &((Py_SIZE(self)));
2504n/a }
2505n/a view->strides = NULL;
2506n/a if ((flags & PyBUF_STRIDES)==PyBUF_STRIDES)
2507n/a view->strides = &(view->itemsize);
2508n/a view->format = NULL;
2509n/a view->internal = NULL;
2510n/a if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT) {
2511n/a view->format = (char *)self->ob_descr->formats;
2512n/a#ifdef Py_UNICODE_WIDE
2513n/a if (self->ob_descr->typecode == 'u') {
2514n/a view->format = "w";
2515n/a }
2516n/a#endif
2517n/a }
2518n/a
2519n/a self->ob_exports++;
2520n/a return 0;
2521n/a}
2522n/a
2523n/astatic void
2524n/aarray_buffer_relbuf(arrayobject *self, Py_buffer *view)
2525n/a{
2526n/a self->ob_exports--;
2527n/a}
2528n/a
2529n/astatic PySequenceMethods array_as_sequence = {
2530n/a (lenfunc)array_length, /*sq_length*/
2531n/a (binaryfunc)array_concat, /*sq_concat*/
2532n/a (ssizeargfunc)array_repeat, /*sq_repeat*/
2533n/a (ssizeargfunc)array_item, /*sq_item*/
2534n/a 0, /*sq_slice*/
2535n/a (ssizeobjargproc)array_ass_item, /*sq_ass_item*/
2536n/a 0, /*sq_ass_slice*/
2537n/a (objobjproc)array_contains, /*sq_contains*/
2538n/a (binaryfunc)array_inplace_concat, /*sq_inplace_concat*/
2539n/a (ssizeargfunc)array_inplace_repeat /*sq_inplace_repeat*/
2540n/a};
2541n/a
2542n/astatic PyBufferProcs array_as_buffer = {
2543n/a (getbufferproc)array_buffer_getbuf,
2544n/a (releasebufferproc)array_buffer_relbuf
2545n/a};
2546n/a
2547n/astatic PyObject *
2548n/aarray_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2549n/a{
2550n/a int c;
2551n/a PyObject *initial = NULL, *it = NULL;
2552n/a const struct arraydescr *descr;
2553n/a
2554n/a if (type == &Arraytype && !_PyArg_NoKeywords("array.array()", kwds))
2555n/a return NULL;
2556n/a
2557n/a if (!PyArg_ParseTuple(args, "C|O:array", &c, &initial))
2558n/a return NULL;
2559n/a
2560n/a if (initial && c != 'u') {
2561n/a if (PyUnicode_Check(initial)) {
2562n/a PyErr_Format(PyExc_TypeError, "cannot use a str to initialize "
2563n/a "an array with typecode '%c'", c);
2564n/a return NULL;
2565n/a }
2566n/a else if (array_Check(initial) &&
2567n/a ((arrayobject*)initial)->ob_descr->typecode == 'u') {
2568n/a PyErr_Format(PyExc_TypeError, "cannot use a unicode array to "
2569n/a "initialize an array with typecode '%c'", c);
2570n/a return NULL;
2571n/a }
2572n/a }
2573n/a
2574n/a if (!(initial == NULL || PyList_Check(initial)
2575n/a || PyByteArray_Check(initial)
2576n/a || PyBytes_Check(initial)
2577n/a || PyTuple_Check(initial)
2578n/a || ((c=='u') && PyUnicode_Check(initial))
2579n/a || (array_Check(initial)
2580n/a && c == ((arrayobject*)initial)->ob_descr->typecode))) {
2581n/a it = PyObject_GetIter(initial);
2582n/a if (it == NULL)
2583n/a return NULL;
2584n/a /* We set initial to NULL so that the subsequent code
2585n/a will create an empty array of the appropriate type
2586n/a and afterwards we can use array_iter_extend to populate
2587n/a the array.
2588n/a */
2589n/a initial = NULL;
2590n/a }
2591n/a for (descr = descriptors; descr->typecode != '\0'; descr++) {
2592n/a if (descr->typecode == c) {
2593n/a PyObject *a;
2594n/a Py_ssize_t len;
2595n/a
2596n/a if (initial == NULL)
2597n/a len = 0;
2598n/a else if (PyList_Check(initial))
2599n/a len = PyList_GET_SIZE(initial);
2600n/a else if (PyTuple_Check(initial) || array_Check(initial))
2601n/a len = Py_SIZE(initial);
2602n/a else
2603n/a len = 0;
2604n/a
2605n/a a = newarrayobject(type, len, descr);
2606n/a if (a == NULL)
2607n/a return NULL;
2608n/a
2609n/a if (len > 0 && !array_Check(initial)) {
2610n/a Py_ssize_t i;
2611n/a for (i = 0; i < len; i++) {
2612n/a PyObject *v =
2613n/a PySequence_GetItem(initial, i);
2614n/a if (v == NULL) {
2615n/a Py_DECREF(a);
2616n/a return NULL;
2617n/a }
2618n/a if (setarrayitem(a, i, v) != 0) {
2619n/a Py_DECREF(v);
2620n/a Py_DECREF(a);
2621n/a return NULL;
2622n/a }
2623n/a Py_DECREF(v);
2624n/a }
2625n/a }
2626n/a else if (initial != NULL && (PyByteArray_Check(initial) ||
2627n/a PyBytes_Check(initial))) {
2628n/a PyObject *v;
2629n/a v = array_array_frombytes((arrayobject *)a,
2630n/a initial);
2631n/a if (v == NULL) {
2632n/a Py_DECREF(a);
2633n/a return NULL;
2634n/a }
2635n/a Py_DECREF(v);
2636n/a }
2637n/a else if (initial != NULL && PyUnicode_Check(initial)) {
2638n/a Py_UNICODE *ustr;
2639n/a Py_ssize_t n;
2640n/a
2641n/a ustr = PyUnicode_AsUnicode(initial);
2642n/a if (ustr == NULL) {
2643n/a PyErr_NoMemory();
2644n/a Py_DECREF(a);
2645n/a return NULL;
2646n/a }
2647n/a
2648n/a n = PyUnicode_GET_DATA_SIZE(initial);
2649n/a if (n > 0) {
2650n/a arrayobject *self = (arrayobject *)a;
2651n/a char *item = self->ob_item;
2652n/a item = (char *)PyMem_Realloc(item, n);
2653n/a if (item == NULL) {
2654n/a PyErr_NoMemory();
2655n/a Py_DECREF(a);
2656n/a return NULL;
2657n/a }
2658n/a self->ob_item = item;
2659n/a Py_SIZE(self) = n / sizeof(Py_UNICODE);
2660n/a memcpy(item, ustr, n);
2661n/a self->allocated = Py_SIZE(self);
2662n/a }
2663n/a }
2664n/a else if (initial != NULL && array_Check(initial) && len > 0) {
2665n/a arrayobject *self = (arrayobject *)a;
2666n/a arrayobject *other = (arrayobject *)initial;
2667n/a memcpy(self->ob_item, other->ob_item, len * other->ob_descr->itemsize);
2668n/a }
2669n/a if (it != NULL) {
2670n/a if (array_iter_extend((arrayobject *)a, it) == -1) {
2671n/a Py_DECREF(it);
2672n/a Py_DECREF(a);
2673n/a return NULL;
2674n/a }
2675n/a Py_DECREF(it);
2676n/a }
2677n/a return a;
2678n/a }
2679n/a }
2680n/a PyErr_SetString(PyExc_ValueError,
2681n/a "bad typecode (must be b, B, u, h, H, i, I, l, L, q, Q, f or d)");
2682n/a return NULL;
2683n/a}
2684n/a
2685n/a
2686n/aPyDoc_STRVAR(module_doc,
2687n/a"This module defines an object type which can efficiently represent\n\
2688n/aan array of basic values: characters, integers, floating point\n\
2689n/anumbers. Arrays are sequence types and behave very much like lists,\n\
2690n/aexcept that the type of objects stored in them is constrained.\n");
2691n/a
2692n/aPyDoc_STRVAR(arraytype_doc,
2693n/a"array(typecode [, initializer]) -> array\n\
2694n/a\n\
2695n/aReturn a new array whose items are restricted by typecode, and\n\
2696n/ainitialized from the optional initializer value, which must be a list,\n\
2697n/astring or iterable over elements of the appropriate type.\n\
2698n/a\n\
2699n/aArrays represent basic values and behave very much like lists, except\n\
2700n/athe type of objects stored in them is constrained. The type is specified\n\
2701n/aat object creation time by using a type code, which is a single character.\n\
2702n/aThe following type codes are defined:\n\
2703n/a\n\
2704n/a Type code C Type Minimum size in bytes \n\
2705n/a 'b' signed integer 1 \n\
2706n/a 'B' unsigned integer 1 \n\
2707n/a 'u' Unicode character 2 (see note) \n\
2708n/a 'h' signed integer 2 \n\
2709n/a 'H' unsigned integer 2 \n\
2710n/a 'i' signed integer 2 \n\
2711n/a 'I' unsigned integer 2 \n\
2712n/a 'l' signed integer 4 \n\
2713n/a 'L' unsigned integer 4 \n\
2714n/a 'q' signed integer 8 (see note) \n\
2715n/a 'Q' unsigned integer 8 (see note) \n\
2716n/a 'f' floating point 4 \n\
2717n/a 'd' floating point 8 \n\
2718n/a\n\
2719n/aNOTE: The 'u' typecode corresponds to Python's unicode character. On \n\
2720n/anarrow builds this is 2-bytes on wide builds this is 4-bytes.\n\
2721n/a\n\
2722n/aNOTE: The 'q' and 'Q' type codes are only available if the platform \n\
2723n/aC compiler used to build Python supports 'long long', or, on Windows, \n\
2724n/a'__int64'.\n\
2725n/a\n\
2726n/aMethods:\n\
2727n/a\n\
2728n/aappend() -- append a new item to the end of the array\n\
2729n/abuffer_info() -- return information giving the current memory info\n\
2730n/abyteswap() -- byteswap all the items of the array\n\
2731n/acount() -- return number of occurrences of an object\n\
2732n/aextend() -- extend array by appending multiple elements from an iterable\n\
2733n/afromfile() -- read items from a file object\n\
2734n/afromlist() -- append items from the list\n\
2735n/afrombytes() -- append items from the string\n\
2736n/aindex() -- return index of first occurrence of an object\n\
2737n/ainsert() -- insert a new item into the array at a provided position\n\
2738n/apop() -- remove and return item (default last)\n\
2739n/aremove() -- remove first occurrence of an object\n\
2740n/areverse() -- reverse the order of the items in the array\n\
2741n/atofile() -- write all items to a file object\n\
2742n/atolist() -- return the array converted to an ordinary list\n\
2743n/atobytes() -- return the array converted to a string\n\
2744n/a\n\
2745n/aAttributes:\n\
2746n/a\n\
2747n/atypecode -- the typecode character used to create the array\n\
2748n/aitemsize -- the length in bytes of one array item\n\
2749n/a");
2750n/a
2751n/astatic PyObject *array_iter(arrayobject *ao);
2752n/a
2753n/astatic PyTypeObject Arraytype = {
2754n/a PyVarObject_HEAD_INIT(NULL, 0)
2755n/a "array.array",
2756n/a sizeof(arrayobject),
2757n/a 0,
2758n/a (destructor)array_dealloc, /* tp_dealloc */
2759n/a 0, /* tp_print */
2760n/a 0, /* tp_getattr */
2761n/a 0, /* tp_setattr */
2762n/a 0, /* tp_reserved */
2763n/a (reprfunc)array_repr, /* tp_repr */
2764n/a 0, /* tp_as_number*/
2765n/a &array_as_sequence, /* tp_as_sequence*/
2766n/a &array_as_mapping, /* tp_as_mapping*/
2767n/a 0, /* tp_hash */
2768n/a 0, /* tp_call */
2769n/a 0, /* tp_str */
2770n/a PyObject_GenericGetAttr, /* tp_getattro */
2771n/a 0, /* tp_setattro */
2772n/a &array_as_buffer, /* tp_as_buffer*/
2773n/a Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
2774n/a arraytype_doc, /* tp_doc */
2775n/a 0, /* tp_traverse */
2776n/a 0, /* tp_clear */
2777n/a array_richcompare, /* tp_richcompare */
2778n/a offsetof(arrayobject, weakreflist), /* tp_weaklistoffset */
2779n/a (getiterfunc)array_iter, /* tp_iter */
2780n/a 0, /* tp_iternext */
2781n/a array_methods, /* tp_methods */
2782n/a 0, /* tp_members */
2783n/a array_getsets, /* tp_getset */
2784n/a 0, /* tp_base */
2785n/a 0, /* tp_dict */
2786n/a 0, /* tp_descr_get */
2787n/a 0, /* tp_descr_set */
2788n/a 0, /* tp_dictoffset */
2789n/a 0, /* tp_init */
2790n/a PyType_GenericAlloc, /* tp_alloc */
2791n/a array_new, /* tp_new */
2792n/a PyObject_Del, /* tp_free */
2793n/a};
2794n/a
2795n/a
2796n/a/*********************** Array Iterator **************************/
2797n/a
2798n/a/*[clinic input]
2799n/aclass array.arrayiterator "arrayiterobject *" "&PyArrayIter_Type"
2800n/a[clinic start generated code]*/
2801n/a/*[clinic end generated code: output=da39a3ee5e6b4b0d input=5aefd2d74d8c8e30]*/
2802n/a
2803n/astatic PyObject *
2804n/aarray_iter(arrayobject *ao)
2805n/a{
2806n/a arrayiterobject *it;
2807n/a
2808n/a if (!array_Check(ao)) {
2809n/a PyErr_BadInternalCall();
2810n/a return NULL;
2811n/a }
2812n/a
2813n/a it = PyObject_GC_New(arrayiterobject, &PyArrayIter_Type);
2814n/a if (it == NULL)
2815n/a return NULL;
2816n/a
2817n/a Py_INCREF(ao);
2818n/a it->ao = ao;
2819n/a it->index = 0;
2820n/a it->getitem = ao->ob_descr->getitem;
2821n/a PyObject_GC_Track(it);
2822n/a return (PyObject *)it;
2823n/a}
2824n/a
2825n/astatic PyObject *
2826n/aarrayiter_next(arrayiterobject *it)
2827n/a{
2828n/a arrayobject *ao;
2829n/a
2830n/a assert(it != NULL);
2831n/a assert(PyArrayIter_Check(it));
2832n/a ao = it->ao;
2833n/a if (ao == NULL) {
2834n/a return NULL;
2835n/a }
2836n/a assert(array_Check(ao));
2837n/a if (it->index < Py_SIZE(ao)) {
2838n/a return (*it->getitem)(ao, it->index++);
2839n/a }
2840n/a it->ao = NULL;
2841n/a Py_DECREF(ao);
2842n/a return NULL;
2843n/a}
2844n/a
2845n/astatic void
2846n/aarrayiter_dealloc(arrayiterobject *it)
2847n/a{
2848n/a PyObject_GC_UnTrack(it);
2849n/a Py_XDECREF(it->ao);
2850n/a PyObject_GC_Del(it);
2851n/a}
2852n/a
2853n/astatic int
2854n/aarrayiter_traverse(arrayiterobject *it, visitproc visit, void *arg)
2855n/a{
2856n/a Py_VISIT(it->ao);
2857n/a return 0;
2858n/a}
2859n/a
2860n/a/*[clinic input]
2861n/aarray.arrayiterator.__reduce__
2862n/a
2863n/aReturn state information for pickling.
2864n/a[clinic start generated code]*/
2865n/a
2866n/astatic PyObject *
2867n/aarray_arrayiterator___reduce___impl(arrayiterobject *self)
2868n/a/*[clinic end generated code: output=7898a52e8e66e016 input=a062ea1e9951417a]*/
2869n/a{
2870n/a PyObject *func = _PyObject_GetBuiltin("iter");
2871n/a if (self->ao == NULL) {
2872n/a return Py_BuildValue("N(())", func);
2873n/a }
2874n/a return Py_BuildValue("N(O)n", func, self->ao, self->index);
2875n/a}
2876n/a
2877n/a/*[clinic input]
2878n/aarray.arrayiterator.__setstate__
2879n/a
2880n/a state: object
2881n/a /
2882n/a
2883n/aSet state information for unpickling.
2884n/a[clinic start generated code]*/
2885n/a
2886n/astatic PyObject *
2887n/aarray_arrayiterator___setstate__(arrayiterobject *self, PyObject *state)
2888n/a/*[clinic end generated code: output=397da9904e443cbe input=f47d5ceda19e787b]*/
2889n/a{
2890n/a Py_ssize_t index = PyLong_AsSsize_t(state);
2891n/a if (index == -1 && PyErr_Occurred())
2892n/a return NULL;
2893n/a if (index < 0)
2894n/a index = 0;
2895n/a else if (index > Py_SIZE(self->ao))
2896n/a index = Py_SIZE(self->ao); /* iterator exhausted */
2897n/a self->index = index;
2898n/a Py_RETURN_NONE;
2899n/a}
2900n/a
2901n/astatic PyMethodDef arrayiter_methods[] = {
2902n/a ARRAY_ARRAYITERATOR___REDUCE___METHODDEF
2903n/a ARRAY_ARRAYITERATOR___SETSTATE___METHODDEF
2904n/a {NULL, NULL} /* sentinel */
2905n/a};
2906n/a
2907n/astatic PyTypeObject PyArrayIter_Type = {
2908n/a PyVarObject_HEAD_INIT(NULL, 0)
2909n/a "arrayiterator", /* tp_name */
2910n/a sizeof(arrayiterobject), /* tp_basicsize */
2911n/a 0, /* tp_itemsize */
2912n/a /* methods */
2913n/a (destructor)arrayiter_dealloc, /* tp_dealloc */
2914n/a 0, /* tp_print */
2915n/a 0, /* tp_getattr */
2916n/a 0, /* tp_setattr */
2917n/a 0, /* tp_reserved */
2918n/a 0, /* tp_repr */
2919n/a 0, /* tp_as_number */
2920n/a 0, /* tp_as_sequence */
2921n/a 0, /* tp_as_mapping */
2922n/a 0, /* tp_hash */
2923n/a 0, /* tp_call */
2924n/a 0, /* tp_str */
2925n/a PyObject_GenericGetAttr, /* tp_getattro */
2926n/a 0, /* tp_setattro */
2927n/a 0, /* tp_as_buffer */
2928n/a Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2929n/a 0, /* tp_doc */
2930n/a (traverseproc)arrayiter_traverse, /* tp_traverse */
2931n/a 0, /* tp_clear */
2932n/a 0, /* tp_richcompare */
2933n/a 0, /* tp_weaklistoffset */
2934n/a PyObject_SelfIter, /* tp_iter */
2935n/a (iternextfunc)arrayiter_next, /* tp_iternext */
2936n/a arrayiter_methods, /* tp_methods */
2937n/a};
2938n/a
2939n/a
2940n/a/*********************** Install Module **************************/
2941n/a
2942n/a/* No functions in array module. */
2943n/astatic PyMethodDef a_methods[] = {
2944n/a ARRAY__ARRAY_RECONSTRUCTOR_METHODDEF
2945n/a {NULL, NULL, 0, NULL} /* Sentinel */
2946n/a};
2947n/a
2948n/astatic int
2949n/aarray_modexec(PyObject *m)
2950n/a{
2951n/a char buffer[Py_ARRAY_LENGTH(descriptors)], *p;
2952n/a PyObject *typecodes;
2953n/a Py_ssize_t size = 0;
2954n/a const struct arraydescr *descr;
2955n/a
2956n/a if (PyType_Ready(&Arraytype) < 0)
2957n/a return -1;
2958n/a Py_TYPE(&PyArrayIter_Type) = &PyType_Type;
2959n/a
2960n/a Py_INCREF((PyObject *)&Arraytype);
2961n/a PyModule_AddObject(m, "ArrayType", (PyObject *)&Arraytype);
2962n/a Py_INCREF((PyObject *)&Arraytype);
2963n/a PyModule_AddObject(m, "array", (PyObject *)&Arraytype);
2964n/a
2965n/a for (descr=descriptors; descr->typecode != '\0'; descr++) {
2966n/a size++;
2967n/a }
2968n/a
2969n/a p = buffer;
2970n/a for (descr = descriptors; descr->typecode != '\0'; descr++) {
2971n/a *p++ = (char)descr->typecode;
2972n/a }
2973n/a typecodes = PyUnicode_DecodeASCII(buffer, p - buffer, NULL);
2974n/a
2975n/a PyModule_AddObject(m, "typecodes", typecodes);
2976n/a
2977n/a if (PyErr_Occurred()) {
2978n/a Py_DECREF(m);
2979n/a m = NULL;
2980n/a }
2981n/a return 0;
2982n/a}
2983n/a
2984n/astatic PyModuleDef_Slot arrayslots[] = {
2985n/a {Py_mod_exec, array_modexec},
2986n/a {0, NULL}
2987n/a};
2988n/a
2989n/a
2990n/astatic struct PyModuleDef arraymodule = {
2991n/a PyModuleDef_HEAD_INIT,
2992n/a "array",
2993n/a module_doc,
2994n/a 0,
2995n/a a_methods,
2996n/a arrayslots,
2997n/a NULL,
2998n/a NULL,
2999n/a NULL
3000n/a};
3001n/a
3002n/a
3003n/aPyMODINIT_FUNC
3004n/aPyInit_array(void)
3005n/a{
3006n/a return PyModuleDef_Init(&arraymodule);
3007n/a}