1 /* Array object implementation */
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 */
7 #include "structmember.h"
11 #else /* !STDC_HEADERS */
12 #ifndef DONT_HAVE_SYS_TYPES_H
13 #include <sys/types.h> /* For size_t */
14 #endif /* DONT_HAVE_SYS_TYPES_H */
15 #endif /* !STDC_HEADERS */
17 struct arrayobject
; /* Forward */
19 /* All possible arraydescr values are defined in the vector "descriptors"
20 * below. That's defined later because the appropriate get and set
21 * functions aren't visible yet.
26 PyObject
* (*getitem
)(struct arrayobject
*, int);
27 int (*setitem
)(struct arrayobject
*, int, PyObject
*);
30 typedef struct arrayobject
{
35 struct arraydescr
*ob_descr
;
36 PyObject
*weakreflist
; /* List of weak references */
39 static PyTypeObject Arraytype
;
41 #define array_Check(op) PyObject_TypeCheck(op, &Arraytype)
42 #define array_CheckExact(op) ((op)->ob_type == &Arraytype)
45 array_resize(arrayobject
*self
, int newsize
)
50 /* Bypass realloc() when a previous overallocation is large enough
51 to accommodate the newsize. If the newsize is 16 smaller than the
52 current size, then proceed with the realloc() to shrink the list.
55 if (self
->allocated
>= newsize
&&
56 self
->ob_size
< newsize
+ 16 &&
57 self
->ob_item
!= NULL
) {
58 self
->ob_size
= newsize
;
62 /* This over-allocates proportional to the array size, making room
63 * for additional growth. The over-allocation is mild, but is
64 * enough to give linear-time amortized behavior over a long
65 * sequence of appends() in the presence of a poorly-performing
67 * The growth pattern is: 0, 4, 8, 16, 25, 34, 46, 56, 67, 79, ...
68 * Note, the pattern starts out the same as for lists but then
69 * grows at a smaller rate so that larger arrays only overallocate
70 * by about 1/16th -- this is done because arrays are presumed to be more
74 _new_size
= (newsize
>> 4) + (self
->ob_size
< 8 ? 3 : 7) + newsize
;
75 items
= self
->ob_item
;
76 /* XXX The following multiplication and division does not optimize away
77 like it does for lists since the size is not known at compile time */
78 if (_new_size
<= ((~(size_t)0) / self
->ob_descr
->itemsize
))
79 PyMem_RESIZE(items
, char, (_new_size
* self
->ob_descr
->itemsize
));
86 self
->ob_item
= items
;
87 self
->ob_size
= newsize
;
88 self
->allocated
= _new_size
;
92 /****************************************************************************
93 Get and Set functions for each type.
94 A Get function takes an arrayobject* and an integer index, returning the
95 array value at that index wrapped in an appropriate PyObject*.
96 A Set function takes an arrayobject, integer index, and PyObject*; sets
97 the array value at that index to the raw C data extracted from the PyObject*,
98 and returns 0 if successful, else nonzero on failure (PyObject* not of an
99 appropriate type or value).
100 Note that the basic Get and Set functions do NOT check that the index is
101 in bounds; that's the responsibility of the caller.
102 ****************************************************************************/
105 c_getitem(arrayobject
*ap
, int i
)
107 return PyString_FromStringAndSize(&((char *)ap
->ob_item
)[i
], 1);
111 c_setitem(arrayobject
*ap
, int i
, PyObject
*v
)
114 if (!PyArg_Parse(v
, "c;array item must be char", &x
))
117 ((char *)ap
->ob_item
)[i
] = x
;
122 b_getitem(arrayobject
*ap
, int i
)
124 long x
= ((char *)ap
->ob_item
)[i
];
127 return PyInt_FromLong(x
);
131 b_setitem(arrayobject
*ap
, int i
, PyObject
*v
)
134 /* PyArg_Parse's 'b' formatter is for an unsigned char, therefore
135 must use the next size up that is signed ('h') and manually do
136 the overflow checking */
137 if (!PyArg_Parse(v
, "h;array item must be integer", &x
))
140 PyErr_SetString(PyExc_OverflowError
,
141 "signed char is less than minimum");
145 PyErr_SetString(PyExc_OverflowError
,
146 "signed char is greater than maximum");
150 ((char *)ap
->ob_item
)[i
] = (char)x
;
155 BB_getitem(arrayobject
*ap
, int i
)
157 long x
= ((unsigned char *)ap
->ob_item
)[i
];
158 return PyInt_FromLong(x
);
162 BB_setitem(arrayobject
*ap
, int i
, PyObject
*v
)
165 /* 'B' == unsigned char, maps to PyArg_Parse's 'b' formatter */
166 if (!PyArg_Parse(v
, "b;array item must be integer", &x
))
169 ((char *)ap
->ob_item
)[i
] = x
;
173 #ifdef Py_USING_UNICODE
175 u_getitem(arrayobject
*ap
, int i
)
177 return PyUnicode_FromUnicode(&((Py_UNICODE
*) ap
->ob_item
)[i
], 1);
181 u_setitem(arrayobject
*ap
, int i
, PyObject
*v
)
186 if (!PyArg_Parse(v
, "u#;array item must be unicode character", &p
, &len
))
189 PyErr_SetString(PyExc_TypeError
, "array item must be unicode character");
193 ((Py_UNICODE
*)ap
->ob_item
)[i
] = p
[0];
199 h_getitem(arrayobject
*ap
, int i
)
201 return PyInt_FromLong((long) ((short *)ap
->ob_item
)[i
]);
205 h_setitem(arrayobject
*ap
, int i
, PyObject
*v
)
208 /* 'h' == signed short, maps to PyArg_Parse's 'h' formatter */
209 if (!PyArg_Parse(v
, "h;array item must be integer", &x
))
212 ((short *)ap
->ob_item
)[i
] = x
;
217 HH_getitem(arrayobject
*ap
, int i
)
219 return PyInt_FromLong((long) ((unsigned short *)ap
->ob_item
)[i
]);
223 HH_setitem(arrayobject
*ap
, int i
, PyObject
*v
)
226 /* PyArg_Parse's 'h' formatter is for a signed short, therefore
227 must use the next size up and manually do the overflow checking */
228 if (!PyArg_Parse(v
, "i;array item must be integer", &x
))
231 PyErr_SetString(PyExc_OverflowError
,
232 "unsigned short is less than minimum");
235 else if (x
> USHRT_MAX
) {
236 PyErr_SetString(PyExc_OverflowError
,
237 "unsigned short is greater than maximum");
241 ((short *)ap
->ob_item
)[i
] = (short)x
;
246 i_getitem(arrayobject
*ap
, int i
)
248 return PyInt_FromLong((long) ((int *)ap
->ob_item
)[i
]);
252 i_setitem(arrayobject
*ap
, int i
, PyObject
*v
)
255 /* 'i' == signed int, maps to PyArg_Parse's 'i' formatter */
256 if (!PyArg_Parse(v
, "i;array item must be integer", &x
))
259 ((int *)ap
->ob_item
)[i
] = x
;
264 II_getitem(arrayobject
*ap
, int i
)
266 return PyLong_FromUnsignedLong(
267 (unsigned long) ((unsigned int *)ap
->ob_item
)[i
]);
271 II_setitem(arrayobject
*ap
, int i
, PyObject
*v
)
274 if (PyLong_Check(v
)) {
275 x
= PyLong_AsUnsignedLong(v
);
276 if (x
== (unsigned long) -1 && PyErr_Occurred())
281 if (!PyArg_Parse(v
, "l;array item must be integer", &y
))
284 PyErr_SetString(PyExc_OverflowError
,
285 "unsigned int is less than minimum");
288 x
= (unsigned long)y
;
292 PyErr_SetString(PyExc_OverflowError
,
293 "unsigned int is greater than maximum");
298 ((unsigned int *)ap
->ob_item
)[i
] = (unsigned int)x
;
303 l_getitem(arrayobject
*ap
, int i
)
305 return PyInt_FromLong(((long *)ap
->ob_item
)[i
]);
309 l_setitem(arrayobject
*ap
, int i
, PyObject
*v
)
312 if (!PyArg_Parse(v
, "l;array item must be integer", &x
))
315 ((long *)ap
->ob_item
)[i
] = x
;
320 LL_getitem(arrayobject
*ap
, int i
)
322 return PyLong_FromUnsignedLong(((unsigned long *)ap
->ob_item
)[i
]);
326 LL_setitem(arrayobject
*ap
, int i
, PyObject
*v
)
329 if (PyLong_Check(v
)) {
330 x
= PyLong_AsUnsignedLong(v
);
331 if (x
== (unsigned long) -1 && PyErr_Occurred())
336 if (!PyArg_Parse(v
, "l;array item must be integer", &y
))
339 PyErr_SetString(PyExc_OverflowError
,
340 "unsigned long is less than minimum");
343 x
= (unsigned long)y
;
347 PyErr_SetString(PyExc_OverflowError
,
348 "unsigned long is greater than maximum");
353 ((unsigned long *)ap
->ob_item
)[i
] = x
;
358 f_getitem(arrayobject
*ap
, int i
)
360 return PyFloat_FromDouble((double) ((float *)ap
->ob_item
)[i
]);
364 f_setitem(arrayobject
*ap
, int i
, PyObject
*v
)
367 if (!PyArg_Parse(v
, "f;array item must be float", &x
))
370 ((float *)ap
->ob_item
)[i
] = x
;
375 d_getitem(arrayobject
*ap
, int i
)
377 return PyFloat_FromDouble(((double *)ap
->ob_item
)[i
]);
381 d_setitem(arrayobject
*ap
, int i
, PyObject
*v
)
384 if (!PyArg_Parse(v
, "d;array item must be float", &x
))
387 ((double *)ap
->ob_item
)[i
] = x
;
391 /* Description of types */
392 static struct arraydescr descriptors
[] = {
393 {'c', sizeof(char), c_getitem
, c_setitem
},
394 {'b', sizeof(char), b_getitem
, b_setitem
},
395 {'B', sizeof(char), BB_getitem
, BB_setitem
},
396 #ifdef Py_USING_UNICODE
397 {'u', sizeof(Py_UNICODE
), u_getitem
, u_setitem
},
399 {'h', sizeof(short), h_getitem
, h_setitem
},
400 {'H', sizeof(short), HH_getitem
, HH_setitem
},
401 {'i', sizeof(int), i_getitem
, i_setitem
},
402 {'I', sizeof(int), II_getitem
, II_setitem
},
403 {'l', sizeof(long), l_getitem
, l_setitem
},
404 {'L', sizeof(long), LL_getitem
, LL_setitem
},
405 {'f', sizeof(float), f_getitem
, f_setitem
},
406 {'d', sizeof(double), d_getitem
, d_setitem
},
407 {'\0', 0, 0, 0} /* Sentinel */
410 /****************************************************************************
411 Implementations of array object methods.
412 ****************************************************************************/
415 newarrayobject(PyTypeObject
*type
, int size
, struct arraydescr
*descr
)
421 PyErr_BadInternalCall();
425 nbytes
= size
* descr
->itemsize
;
426 /* Check for overflow */
427 if (nbytes
/ descr
->itemsize
!= (size_t)size
) {
428 return PyErr_NoMemory();
430 op
= (arrayobject
*) type
->tp_alloc(type
, 0);
439 op
->ob_item
= PyMem_NEW(char, nbytes
);
440 if (op
->ob_item
== NULL
) {
442 return PyErr_NoMemory();
445 op
->ob_descr
= descr
;
446 op
->allocated
= size
;
447 op
->weakreflist
= NULL
;
448 return (PyObject
*) op
;
452 getarrayitem(PyObject
*op
, int i
)
454 register arrayobject
*ap
;
455 assert(array_Check(op
));
456 ap
= (arrayobject
*)op
;
457 assert(i
>=0 && i
<ap
->ob_size
);
458 return (*ap
->ob_descr
->getitem
)(ap
, i
);
462 ins1(arrayobject
*self
, int where
, PyObject
*v
)
465 int n
= self
->ob_size
;
467 PyErr_BadInternalCall();
470 if ((*self
->ob_descr
->setitem
)(self
, -1, v
) < 0)
473 if (array_resize(self
, n
+1) == -1)
475 items
= self
->ob_item
;
483 /* appends don't need to call memmove() */
485 memmove(items
+ (where
+1)*self
->ob_descr
->itemsize
,
486 items
+ where
*self
->ob_descr
->itemsize
,
487 (n
-where
)*self
->ob_descr
->itemsize
);
488 return (*self
->ob_descr
->setitem
)(self
, where
, v
);
494 array_dealloc(arrayobject
*op
)
496 if (op
->weakreflist
!= NULL
)
497 PyObject_ClearWeakRefs((PyObject
*) op
);
498 if (op
->ob_item
!= NULL
)
499 PyMem_DEL(op
->ob_item
);
500 op
->ob_type
->tp_free((PyObject
*)op
);
504 array_richcompare(PyObject
*v
, PyObject
*w
, int op
)
506 arrayobject
*va
, *wa
;
512 if (!array_Check(v
) || !array_Check(w
)) {
513 Py_INCREF(Py_NotImplemented
);
514 return Py_NotImplemented
;
517 va
= (arrayobject
*)v
;
518 wa
= (arrayobject
*)w
;
520 if (va
->ob_size
!= wa
->ob_size
&& (op
== Py_EQ
|| op
== Py_NE
)) {
521 /* Shortcut: if the lengths differ, the arrays differ */
530 /* Search for the first index where items are different */
532 for (i
= 0; i
< va
->ob_size
&& i
< wa
->ob_size
; i
++) {
533 vi
= getarrayitem(v
, i
);
534 wi
= getarrayitem(w
, i
);
535 if (vi
== NULL
|| wi
== NULL
) {
540 k
= PyObject_RichCompareBool(vi
, wi
, Py_EQ
);
542 break; /* Keeping vi and wi alive! */
550 /* No more items to compare -- compare sizes */
551 int vs
= va
->ob_size
;
552 int ws
= wa
->ob_size
;
555 case Py_LT
: cmp
= vs
< ws
; break;
556 case Py_LE
: cmp
= vs
<= ws
; break;
557 case Py_EQ
: cmp
= vs
== ws
; break;
558 case Py_NE
: cmp
= vs
!= ws
; break;
559 case Py_GT
: cmp
= vs
> ws
; break;
560 case Py_GE
: cmp
= vs
>= ws
; break;
561 default: return NULL
; /* cannot happen */
571 /* We have an item that differs. First, shortcuts for EQ/NE */
576 else if (op
== Py_NE
) {
581 /* Compare the final item again using the proper operator */
582 res
= PyObject_RichCompare(vi
, wi
, op
);
590 array_length(arrayobject
*a
)
596 array_item(arrayobject
*a
, int i
)
598 if (i
< 0 || i
>= a
->ob_size
) {
599 PyErr_SetString(PyExc_IndexError
, "array index out of range");
602 return getarrayitem((PyObject
*)a
, i
);
606 array_slice(arrayobject
*a
, int ilow
, int ihigh
)
611 else if (ilow
> a
->ob_size
)
617 else if (ihigh
> a
->ob_size
)
619 np
= (arrayobject
*) newarrayobject(&Arraytype
, ihigh
- ilow
, a
->ob_descr
);
622 memcpy(np
->ob_item
, a
->ob_item
+ ilow
* a
->ob_descr
->itemsize
,
623 (ihigh
-ilow
) * a
->ob_descr
->itemsize
);
624 return (PyObject
*)np
;
628 array_copy(arrayobject
*a
, PyObject
*unused
)
630 return array_slice(a
, 0, a
->ob_size
);
633 PyDoc_STRVAR(copy_doc
,
636 Return a copy of the array.");
639 array_concat(arrayobject
*a
, PyObject
*bb
)
643 if (!array_Check(bb
)) {
644 PyErr_Format(PyExc_TypeError
,
645 "can only append array (not \"%.200s\") to array",
646 bb
->ob_type
->tp_name
);
649 #define b ((arrayobject *)bb)
650 if (a
->ob_descr
!= b
->ob_descr
) {
654 size
= a
->ob_size
+ b
->ob_size
;
655 np
= (arrayobject
*) newarrayobject(&Arraytype
, size
, a
->ob_descr
);
659 memcpy(np
->ob_item
, a
->ob_item
, a
->ob_size
*a
->ob_descr
->itemsize
);
660 memcpy(np
->ob_item
+ a
->ob_size
*a
->ob_descr
->itemsize
,
661 b
->ob_item
, b
->ob_size
*b
->ob_descr
->itemsize
);
662 return (PyObject
*)np
;
667 array_repeat(arrayobject
*a
, int n
)
676 size
= a
->ob_size
* n
;
677 np
= (arrayobject
*) newarrayobject(&Arraytype
, size
, a
->ob_descr
);
681 nbytes
= a
->ob_size
* a
->ob_descr
->itemsize
;
682 for (i
= 0; i
< n
; i
++) {
683 memcpy(p
, a
->ob_item
, nbytes
);
686 return (PyObject
*) np
;
690 array_ass_slice(arrayobject
*a
, int ilow
, int ihigh
, PyObject
*v
)
693 int n
; /* Size of replacement array */
694 int d
; /* Change in size */
695 #define b ((arrayobject *)v)
698 else if (array_Check(v
)) {
701 /* Special case "a[i:j] = a" -- copy b first */
703 v
= array_slice(b
, 0, n
);
704 ret
= array_ass_slice(a
, ilow
, ihigh
, v
);
708 if (b
->ob_descr
!= a
->ob_descr
) {
714 PyErr_Format(PyExc_TypeError
,
715 "can only assign array (not \"%.200s\") to array slice",
716 v
->ob_type
->tp_name
);
721 else if (ilow
> a
->ob_size
)
727 else if (ihigh
> a
->ob_size
)
730 d
= n
- (ihigh
-ilow
);
731 if (d
< 0) { /* Delete -d items */
732 memmove(item
+ (ihigh
+d
)*a
->ob_descr
->itemsize
,
733 item
+ ihigh
*a
->ob_descr
->itemsize
,
734 (a
->ob_size
-ihigh
)*a
->ob_descr
->itemsize
);
736 PyMem_RESIZE(item
, char, a
->ob_size
*a
->ob_descr
->itemsize
);
739 a
->allocated
= a
->ob_size
;
741 else if (d
> 0) { /* Insert d items */
742 PyMem_RESIZE(item
, char,
743 (a
->ob_size
+ d
)*a
->ob_descr
->itemsize
);
748 memmove(item
+ (ihigh
+d
)*a
->ob_descr
->itemsize
,
749 item
+ ihigh
*a
->ob_descr
->itemsize
,
750 (a
->ob_size
-ihigh
)*a
->ob_descr
->itemsize
);
753 a
->allocated
= a
->ob_size
;
756 memcpy(item
+ ilow
*a
->ob_descr
->itemsize
, b
->ob_item
,
757 n
*b
->ob_descr
->itemsize
);
763 array_ass_item(arrayobject
*a
, int i
, PyObject
*v
)
765 if (i
< 0 || i
>= a
->ob_size
) {
766 PyErr_SetString(PyExc_IndexError
,
767 "array assignment index out of range");
771 return array_ass_slice(a
, i
, i
+1, v
);
772 return (*a
->ob_descr
->setitem
)(a
, i
, v
);
776 setarrayitem(PyObject
*a
, int i
, PyObject
*v
)
778 assert(array_Check(a
));
779 return array_ass_item((arrayobject
*)a
, i
, v
);
783 array_iter_extend(arrayobject
*self
, PyObject
*bb
)
787 it
= PyObject_GetIter(bb
);
791 while ((v
= PyIter_Next(it
)) != NULL
) {
792 if (ins1(self
, (int) self
->ob_size
, v
) != 0) {
800 if (PyErr_Occurred())
806 array_do_extend(arrayobject
*self
, PyObject
*bb
)
810 if (!array_Check(bb
))
811 return array_iter_extend(self
, bb
);
812 #define b ((arrayobject *)bb)
813 if (self
->ob_descr
!= b
->ob_descr
) {
814 PyErr_SetString(PyExc_TypeError
,
815 "can only extend with array of same kind");
818 size
= self
->ob_size
+ b
->ob_size
;
819 PyMem_RESIZE(self
->ob_item
, char, size
*self
->ob_descr
->itemsize
);
820 if (self
->ob_item
== NULL
) {
825 memcpy(self
->ob_item
+ self
->ob_size
*self
->ob_descr
->itemsize
,
826 b
->ob_item
, b
->ob_size
*b
->ob_descr
->itemsize
);
827 self
->ob_size
= size
;
828 self
->allocated
= size
;
835 array_inplace_concat(arrayobject
*self
, PyObject
*bb
)
837 if (!array_Check(bb
)) {
838 PyErr_Format(PyExc_TypeError
,
839 "can only extend array with array (not \"%.200s\")",
840 bb
->ob_type
->tp_name
);
843 if (array_do_extend(self
, bb
) == -1)
846 return (PyObject
*)self
;
850 array_inplace_repeat(arrayobject
*self
, int n
)
855 if (self
->ob_size
> 0) {
858 items
= self
->ob_item
;
859 size
= self
->ob_size
* self
->ob_descr
->itemsize
;
862 self
->ob_item
= NULL
;
867 PyMem_Resize(items
, char, n
* size
);
869 return PyErr_NoMemory();
871 for (i
= 1; i
< n
; i
++) {
873 memcpy(p
, items
, size
);
875 self
->ob_item
= items
;
877 self
->allocated
= self
->ob_size
;
881 return (PyObject
*)self
;
886 ins(arrayobject
*self
, int where
, PyObject
*v
)
888 if (ins1(self
, where
, v
) != 0)
895 array_count(arrayobject
*self
, PyObject
*v
)
900 for (i
= 0; i
< self
->ob_size
; i
++) {
901 PyObject
*selfi
= getarrayitem((PyObject
*)self
, i
);
902 int cmp
= PyObject_RichCompareBool(selfi
, v
, Py_EQ
);
909 return PyInt_FromLong((long)count
);
912 PyDoc_STRVAR(count_doc
,
915 Return number of occurences of x in the array.");
918 array_index(arrayobject
*self
, PyObject
*v
)
922 for (i
= 0; i
< self
->ob_size
; i
++) {
923 PyObject
*selfi
= getarrayitem((PyObject
*)self
, i
);
924 int cmp
= PyObject_RichCompareBool(selfi
, v
, Py_EQ
);
927 return PyInt_FromLong((long)i
);
932 PyErr_SetString(PyExc_ValueError
, "array.index(x): x not in list");
936 PyDoc_STRVAR(index_doc
,
939 Return index of first occurence of x in the array.");
942 array_contains(arrayobject
*self
, PyObject
*v
)
946 for (i
= 0, cmp
= 0 ; cmp
== 0 && i
< self
->ob_size
; i
++) {
947 PyObject
*selfi
= getarrayitem((PyObject
*)self
, i
);
948 cmp
= PyObject_RichCompareBool(selfi
, v
, Py_EQ
);
955 array_remove(arrayobject
*self
, PyObject
*v
)
959 for (i
= 0; i
< self
->ob_size
; i
++) {
960 PyObject
*selfi
= getarrayitem((PyObject
*)self
,i
);
961 int cmp
= PyObject_RichCompareBool(selfi
, v
, Py_EQ
);
964 if (array_ass_slice(self
, i
, i
+1,
965 (PyObject
*)NULL
) != 0)
973 PyErr_SetString(PyExc_ValueError
, "array.remove(x): x not in list");
977 PyDoc_STRVAR(remove_doc
,
980 Remove the first occurence of x in the array.");
983 array_pop(arrayobject
*self
, PyObject
*args
)
987 if (!PyArg_ParseTuple(args
, "|i:pop", &i
))
989 if (self
->ob_size
== 0) {
990 /* Special-case most common failure cause */
991 PyErr_SetString(PyExc_IndexError
, "pop from empty array");
996 if (i
< 0 || i
>= self
->ob_size
) {
997 PyErr_SetString(PyExc_IndexError
, "pop index out of range");
1000 v
= getarrayitem((PyObject
*)self
,i
);
1001 if (array_ass_slice(self
, i
, i
+1, (PyObject
*)NULL
) != 0) {
1008 PyDoc_STRVAR(pop_doc
,
1011 Return the i-th element and delete it from the array. i defaults to -1.");
1014 array_extend(arrayobject
*self
, PyObject
*bb
)
1016 if (array_do_extend(self
, bb
) == -1)
1022 PyDoc_STRVAR(extend_doc
,
1023 "extend(array or iterable)\n\
1025 Append items to the end of the array.");
1028 array_insert(arrayobject
*self
, PyObject
*args
)
1032 if (!PyArg_ParseTuple(args
, "iO:insert", &i
, &v
))
1034 return ins(self
, i
, v
);
1037 PyDoc_STRVAR(insert_doc
,
1040 Insert a new item x into the array before position i.");
1044 array_buffer_info(arrayobject
*self
, PyObject
*unused
)
1046 PyObject
* retval
= NULL
;
1047 retval
= PyTuple_New(2);
1051 PyTuple_SET_ITEM(retval
, 0, PyLong_FromVoidPtr(self
->ob_item
));
1052 PyTuple_SET_ITEM(retval
, 1, PyInt_FromLong((long)(self
->ob_size
)));
1057 PyDoc_STRVAR(buffer_info_doc
,
1058 "buffer_info() -> (address, length)\n\
1060 Return a tuple (address, length) giving the current memory address and\n\
1061 the length in items of the buffer used to hold array's contents\n\
1062 The length should be multiplied by the itemsize attribute to calculate\n\
1063 the buffer length in bytes.");
1067 array_append(arrayobject
*self
, PyObject
*v
)
1069 return ins(self
, (int) self
->ob_size
, v
);
1072 PyDoc_STRVAR(append_doc
,
1075 Append new value x to the end of the array.");
1079 array_byteswap(arrayobject
*self
, PyObject
*unused
)
1084 switch (self
->ob_descr
->itemsize
) {
1088 for (p
= self
->ob_item
, i
= self
->ob_size
; --i
>= 0; p
+= 2) {
1095 for (p
= self
->ob_item
, i
= self
->ob_size
; --i
>= 0; p
+= 4) {
1105 for (p
= self
->ob_item
, i
= self
->ob_size
; --i
>= 0; p
+= 8) {
1121 PyErr_SetString(PyExc_RuntimeError
,
1122 "don't know how to byteswap this array type");
1129 PyDoc_STRVAR(byteswap_doc
,
1132 Byteswap all items of the array. If the items in the array are not 1, 2,\n\
1133 4, or 8 bytes in size, RuntimeError is raised.");
1136 array_reduce(arrayobject
*array
)
1138 PyObject
*dict
, *result
;
1140 dict
= PyObject_GetAttrString((PyObject
*)array
, "__dict__");
1146 result
= Py_BuildValue("O(cs#)O",
1148 array
->ob_descr
->typecode
,
1150 array
->ob_size
* array
->ob_descr
->itemsize
,
1156 PyDoc_STRVAR(array_doc
, "Return state information for pickling.");
1159 array_reverse(arrayobject
*self
, PyObject
*unused
)
1161 register int itemsize
= self
->ob_descr
->itemsize
;
1162 register char *p
, *q
;
1163 /* little buffer to hold items while swapping */
1164 char tmp
[256]; /* 8 is probably enough -- but why skimp */
1165 assert(itemsize
<= sizeof(tmp
));
1167 if (self
->ob_size
> 1) {
1168 for (p
= self
->ob_item
,
1169 q
= self
->ob_item
+ (self
->ob_size
- 1)*itemsize
;
1171 p
+= itemsize
, q
-= itemsize
) {
1172 /* memory areas guaranteed disjoint, so memcpy
1173 * is safe (& memmove may be slower).
1175 memcpy(tmp
, p
, itemsize
);
1176 memcpy(p
, q
, itemsize
);
1177 memcpy(q
, tmp
, itemsize
);
1185 PyDoc_STRVAR(reverse_doc
,
1188 Reverse the order of the items in the array.");
1191 array_fromfile(arrayobject
*self
, PyObject
*args
)
1196 if (!PyArg_ParseTuple(args
, "Oi:fromfile", &f
, &n
))
1198 fp
= PyFile_AsFile(f
);
1200 PyErr_SetString(PyExc_TypeError
, "arg1 must be open file");
1204 char *item
= self
->ob_item
;
1205 int itemsize
= self
->ob_descr
->itemsize
;
1209 /* Be careful here about overflow */
1210 if ((newlength
= self
->ob_size
+ n
) <= 0 ||
1211 (newbytes
= newlength
* itemsize
) / itemsize
!=
1214 PyMem_RESIZE(item
, char, newbytes
);
1220 self
->ob_item
= item
;
1222 self
->allocated
= self
->ob_size
;
1223 nread
= fread(item
+ (self
->ob_size
- n
) * itemsize
,
1225 if (nread
< (size_t)n
) {
1226 self
->ob_size
-= (n
- nread
);
1227 PyMem_RESIZE(item
, char, self
->ob_size
*itemsize
);
1228 self
->ob_item
= item
;
1229 self
->allocated
= self
->ob_size
;
1230 PyErr_SetString(PyExc_EOFError
,
1231 "not enough items in file");
1239 PyDoc_STRVAR(fromfile_doc
,
1242 Read n objects from the file object f and append them to the end of the\n\
1243 array. Also called as read.");
1247 array_tofile(arrayobject
*self
, PyObject
*f
)
1251 fp
= PyFile_AsFile(f
);
1253 PyErr_SetString(PyExc_TypeError
, "arg must be open file");
1256 if (self
->ob_size
> 0) {
1257 if (fwrite(self
->ob_item
, self
->ob_descr
->itemsize
,
1258 self
->ob_size
, fp
) != (size_t)self
->ob_size
) {
1259 PyErr_SetFromErrno(PyExc_IOError
);
1268 PyDoc_STRVAR(tofile_doc
,
1271 Write all items (as machine values) to the file object f. Also called as\n\
1276 array_fromlist(arrayobject
*self
, PyObject
*list
)
1279 int itemsize
= self
->ob_descr
->itemsize
;
1281 if (!PyList_Check(list
)) {
1282 PyErr_SetString(PyExc_TypeError
, "arg must be list");
1285 n
= PyList_Size(list
);
1287 char *item
= self
->ob_item
;
1289 PyMem_RESIZE(item
, char, (self
->ob_size
+ n
) * itemsize
);
1294 self
->ob_item
= item
;
1296 self
->allocated
= self
->ob_size
;
1297 for (i
= 0; i
< n
; i
++) {
1298 PyObject
*v
= PyList_GetItem(list
, i
);
1299 if ((*self
->ob_descr
->setitem
)(self
,
1300 self
->ob_size
- n
+ i
, v
) != 0) {
1302 PyMem_RESIZE(item
, char,
1303 self
->ob_size
* itemsize
);
1304 self
->ob_item
= item
;
1305 self
->allocated
= self
->ob_size
;
1314 PyDoc_STRVAR(fromlist_doc
,
1317 Append items to array from list.");
1321 array_tolist(arrayobject
*self
, PyObject
*unused
)
1323 PyObject
*list
= PyList_New(self
->ob_size
);
1328 for (i
= 0; i
< self
->ob_size
; i
++) {
1329 PyObject
*v
= getarrayitem((PyObject
*)self
, i
);
1334 PyList_SetItem(list
, i
, v
);
1339 PyDoc_STRVAR(tolist_doc
,
1340 "tolist() -> list\n\
1342 Convert array to an ordinary list with the same items.");
1346 array_fromstring(arrayobject
*self
, PyObject
*args
)
1350 int itemsize
= self
->ob_descr
->itemsize
;
1351 if (!PyArg_ParseTuple(args
, "s#:fromstring", &str
, &n
))
1353 if (n
% itemsize
!= 0) {
1354 PyErr_SetString(PyExc_ValueError
,
1355 "string length not a multiple of item size");
1360 char *item
= self
->ob_item
;
1361 PyMem_RESIZE(item
, char, (self
->ob_size
+ n
) * itemsize
);
1366 self
->ob_item
= item
;
1368 self
->allocated
= self
->ob_size
;
1369 memcpy(item
+ (self
->ob_size
- n
) * itemsize
,
1376 PyDoc_STRVAR(fromstring_doc
,
1377 "fromstring(string)\n\
1379 Appends items from the string, interpreting it as an array of machine\n\
1380 values,as if it had been read from a file using the fromfile() method).");
1384 array_tostring(arrayobject
*self
, PyObject
*unused
)
1386 return PyString_FromStringAndSize(self
->ob_item
,
1387 self
->ob_size
* self
->ob_descr
->itemsize
);
1390 PyDoc_STRVAR(tostring_doc
,
1391 "tostring() -> string\n\
1393 Convert the array to an array of machine values and return the string\n\
1398 #ifdef Py_USING_UNICODE
1400 array_fromunicode(arrayobject
*self
, PyObject
*args
)
1405 if (!PyArg_ParseTuple(args
, "u#:fromunicode", &ustr
, &n
))
1407 if (self
->ob_descr
->typecode
!= 'u') {
1408 PyErr_SetString(PyExc_ValueError
,
1409 "fromunicode() may only be called on "
1414 Py_UNICODE
*item
= (Py_UNICODE
*) self
->ob_item
;
1415 PyMem_RESIZE(item
, Py_UNICODE
, self
->ob_size
+ n
);
1420 self
->ob_item
= (char *) item
;
1422 self
->allocated
= self
->ob_size
;
1423 memcpy(item
+ self
->ob_size
- n
,
1424 ustr
, n
* sizeof(Py_UNICODE
));
1431 PyDoc_STRVAR(fromunicode_doc
,
1432 "fromunicode(ustr)\n\
1434 Extends this array with data from the unicode string ustr.\n\
1435 The array must be a type 'u' array; otherwise a ValueError\n\
1436 is raised. Use array.fromstring(ustr.decode(...)) to\n\
1437 append Unicode data to an array of some other type.");
1441 array_tounicode(arrayobject
*self
, PyObject
*unused
)
1443 if (self
->ob_descr
->typecode
!= 'u') {
1444 PyErr_SetString(PyExc_ValueError
,
1445 "tounicode() may only be called on type 'u' arrays");
1448 return PyUnicode_FromUnicode((Py_UNICODE
*) self
->ob_item
, self
->ob_size
);
1451 PyDoc_STRVAR(tounicode_doc
,
1452 "tounicode() -> unicode\n\
1454 Convert the array to a unicode string. The array must be\n\
1455 a type 'u' array; otherwise a ValueError is raised. Use\n\
1456 array.tostring().decode() to obtain a unicode string from\n\
1457 an array of some other type.");
1459 #endif /* Py_USING_UNICODE */
1463 array_get_typecode(arrayobject
*a
, void *closure
)
1465 char tc
= a
->ob_descr
->typecode
;
1466 return PyString_FromStringAndSize(&tc
, 1);
1470 array_get_itemsize(arrayobject
*a
, void *closure
)
1472 return PyInt_FromLong((long)a
->ob_descr
->itemsize
);
1475 static PyGetSetDef array_getsets
[] = {
1476 {"typecode", (getter
) array_get_typecode
, NULL
,
1477 "the typecode character used to create the array"},
1478 {"itemsize", (getter
) array_get_itemsize
, NULL
,
1479 "the size, in bytes, of one array item"},
1483 PyMethodDef array_methods
[] = {
1484 {"append", (PyCFunction
)array_append
, METH_O
,
1486 {"buffer_info", (PyCFunction
)array_buffer_info
, METH_NOARGS
,
1488 {"byteswap", (PyCFunction
)array_byteswap
, METH_NOARGS
,
1490 {"__copy__", (PyCFunction
)array_copy
, METH_NOARGS
,
1492 {"count", (PyCFunction
)array_count
, METH_O
,
1494 {"__deepcopy__",(PyCFunction
)array_copy
, METH_NOARGS
,
1496 {"extend", (PyCFunction
)array_extend
, METH_O
,
1498 {"fromfile", (PyCFunction
)array_fromfile
, METH_VARARGS
,
1500 {"fromlist", (PyCFunction
)array_fromlist
, METH_O
,
1502 {"fromstring", (PyCFunction
)array_fromstring
, METH_VARARGS
,
1504 #ifdef Py_USING_UNICODE
1505 {"fromunicode", (PyCFunction
)array_fromunicode
, METH_VARARGS
,
1508 {"index", (PyCFunction
)array_index
, METH_O
,
1510 {"insert", (PyCFunction
)array_insert
, METH_VARARGS
,
1512 {"pop", (PyCFunction
)array_pop
, METH_VARARGS
,
1514 {"read", (PyCFunction
)array_fromfile
, METH_VARARGS
,
1516 {"__reduce__", (PyCFunction
)array_reduce
, METH_NOARGS
,
1518 {"remove", (PyCFunction
)array_remove
, METH_O
,
1520 {"reverse", (PyCFunction
)array_reverse
, METH_NOARGS
,
1522 /* {"sort", (PyCFunction)array_sort, METH_VARARGS,
1524 {"tofile", (PyCFunction
)array_tofile
, METH_O
,
1526 {"tolist", (PyCFunction
)array_tolist
, METH_NOARGS
,
1528 {"tostring", (PyCFunction
)array_tostring
, METH_NOARGS
,
1530 #ifdef Py_USING_UNICODE
1531 {"tounicode", (PyCFunction
)array_tounicode
, METH_NOARGS
,
1534 {"write", (PyCFunction
)array_tofile
, METH_O
,
1536 {NULL
, NULL
} /* sentinel */
1540 array_repr(arrayobject
*a
)
1542 char buf
[256], typecode
;
1543 PyObject
*s
, *t
, *v
= NULL
;
1547 typecode
= a
->ob_descr
->typecode
;
1549 PyOS_snprintf(buf
, sizeof(buf
), "array('%c')", typecode
);
1550 return PyString_FromString(buf
);
1553 if (typecode
== 'c')
1554 v
= array_tostring(a
, NULL
);
1555 #ifdef Py_USING_UNICODE
1556 else if (typecode
== 'u')
1557 v
= array_tounicode(a
, NULL
);
1560 v
= array_tolist(a
, NULL
);
1561 t
= PyObject_Repr(v
);
1564 PyOS_snprintf(buf
, sizeof(buf
), "array('%c', ", typecode
);
1565 s
= PyString_FromString(buf
);
1566 PyString_ConcatAndDel(&s
, t
);
1567 PyString_ConcatAndDel(&s
, PyString_FromString(")"));
1572 array_subscr(arrayobject
* self
, PyObject
* item
)
1574 if (PyInt_Check(item
)) {
1575 long i
= PyInt_AS_LONG(item
);
1578 return array_item(self
, i
);
1580 else if (PyLong_Check(item
)) {
1581 long i
= PyLong_AsLong(item
);
1582 if (i
== -1 && PyErr_Occurred())
1586 return array_item(self
, i
);
1588 else if (PySlice_Check(item
)) {
1589 int start
, stop
, step
, slicelength
, cur
, i
;
1592 int itemsize
= self
->ob_descr
->itemsize
;
1594 if (PySlice_GetIndicesEx((PySliceObject
*)item
, self
->ob_size
,
1595 &start
, &stop
, &step
, &slicelength
) < 0) {
1599 if (slicelength
<= 0) {
1600 return newarrayobject(&Arraytype
, 0, self
->ob_descr
);
1603 result
= newarrayobject(&Arraytype
, slicelength
, self
->ob_descr
);
1604 if (!result
) return NULL
;
1606 ar
= (arrayobject
*)result
;
1608 for (cur
= start
, i
= 0; i
< slicelength
;
1610 memcpy(ar
->ob_item
+ i
*itemsize
,
1611 self
->ob_item
+ cur
*itemsize
,
1619 PyErr_SetString(PyExc_TypeError
,
1620 "list indices must be integers");
1626 array_ass_subscr(arrayobject
* self
, PyObject
* item
, PyObject
* value
)
1628 if (PyInt_Check(item
)) {
1629 long i
= PyInt_AS_LONG(item
);
1632 return array_ass_item(self
, i
, value
);
1634 else if (PyLong_Check(item
)) {
1635 long i
= PyLong_AsLong(item
);
1636 if (i
== -1 && PyErr_Occurred())
1640 return array_ass_item(self
, i
, value
);
1642 else if (PySlice_Check(item
)) {
1643 int start
, stop
, step
, slicelength
;
1644 int itemsize
= self
->ob_descr
->itemsize
;
1646 if (PySlice_GetIndicesEx((PySliceObject
*)item
, self
->ob_size
,
1647 &start
, &stop
, &step
, &slicelength
) < 0) {
1651 /* treat A[slice(a,b)] = v _exactly_ like A[a:b] = v */
1652 if (step
== 1 && ((PySliceObject
*)item
)->step
== Py_None
)
1653 return array_ass_slice(self
, start
, stop
, value
);
1655 if (value
== NULL
) {
1659 if (slicelength
<= 0)
1664 start
= stop
+ step
*(slicelength
- 1) - 1;
1668 for (cur
= start
, i
= 0; i
< slicelength
- 1;
1670 memmove(self
->ob_item
+ (cur
- i
)*itemsize
,
1671 self
->ob_item
+ (cur
+ 1)*itemsize
,
1672 (step
- 1) * itemsize
);
1674 extra
= self
->ob_size
- (cur
+ 1);
1676 memmove(self
->ob_item
+ (cur
- i
)*itemsize
,
1677 self
->ob_item
+ (cur
+ 1)*itemsize
,
1681 self
->ob_size
-= slicelength
;
1682 self
->ob_item
= PyMem_REALLOC(self
->ob_item
, itemsize
*self
->ob_size
);
1683 self
->allocated
= self
->ob_size
;
1692 if (!array_Check(value
)) {
1693 PyErr_Format(PyExc_TypeError
,
1694 "must assign array (not \"%.200s\") to slice",
1695 value
->ob_type
->tp_name
);
1699 av
= (arrayobject
*)value
;
1701 if (av
->ob_size
!= slicelength
) {
1702 PyErr_Format(PyExc_ValueError
,
1703 "attempt to assign array of size %d to extended slice of size %d",
1704 av
->ob_size
, slicelength
);
1711 /* protect against a[::-1] = a */
1713 value
= array_slice(av
, 0, av
->ob_size
);
1714 av
= (arrayobject
*)value
;
1720 for (cur
= start
, i
= 0; i
< slicelength
;
1722 memcpy(self
->ob_item
+ cur
*itemsize
,
1723 av
->ob_item
+ i
*itemsize
,
1733 PyErr_SetString(PyExc_TypeError
,
1734 "list indices must be integers");
1739 static PyMappingMethods array_as_mapping
= {
1740 (inquiry
)array_length
,
1741 (binaryfunc
)array_subscr
,
1742 (objobjargproc
)array_ass_subscr
1746 array_buffer_getreadbuf(arrayobject
*self
, int index
, const void **ptr
)
1749 PyErr_SetString(PyExc_SystemError
,
1750 "Accessing non-existent array segment");
1753 *ptr
= (void *)self
->ob_item
;
1754 return self
->ob_size
*self
->ob_descr
->itemsize
;
1758 array_buffer_getwritebuf(arrayobject
*self
, int index
, const void **ptr
)
1761 PyErr_SetString(PyExc_SystemError
,
1762 "Accessing non-existent array segment");
1765 *ptr
= (void *)self
->ob_item
;
1766 return self
->ob_size
*self
->ob_descr
->itemsize
;
1770 array_buffer_getsegcount(arrayobject
*self
, int *lenp
)
1773 *lenp
= self
->ob_size
*self
->ob_descr
->itemsize
;
1777 static PySequenceMethods array_as_sequence
= {
1778 (inquiry
)array_length
, /*sq_length*/
1779 (binaryfunc
)array_concat
, /*sq_concat*/
1780 (intargfunc
)array_repeat
, /*sq_repeat*/
1781 (intargfunc
)array_item
, /*sq_item*/
1782 (intintargfunc
)array_slice
, /*sq_slice*/
1783 (intobjargproc
)array_ass_item
, /*sq_ass_item*/
1784 (intintobjargproc
)array_ass_slice
, /*sq_ass_slice*/
1785 (objobjproc
)array_contains
, /*sq_contains*/
1786 (binaryfunc
)array_inplace_concat
, /*sq_inplace_concat*/
1787 (intargfunc
)array_inplace_repeat
/*sq_inplace_repeat*/
1790 static PyBufferProcs array_as_buffer
= {
1791 (getreadbufferproc
)array_buffer_getreadbuf
,
1792 (getwritebufferproc
)array_buffer_getwritebuf
,
1793 (getsegcountproc
)array_buffer_getsegcount
,
1797 array_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
1800 PyObject
*initial
= NULL
, *it
= NULL
;
1801 struct arraydescr
*descr
;
1803 if (!_PyArg_NoKeywords("array.array()", kwds
))
1806 if (!PyArg_ParseTuple(args
, "c|O:array", &c
, &initial
))
1809 if (!(initial
== NULL
|| PyList_Check(initial
)
1810 || PyString_Check(initial
) || PyTuple_Check(initial
)
1811 || (c
== 'u' && PyUnicode_Check(initial
)))) {
1812 it
= PyObject_GetIter(initial
);
1815 /* We set initial to NULL so that the subsequent code
1816 will create an empty array of the appropriate type
1817 and afterwards we can use array_iter_extend to populate
1822 for (descr
= descriptors
; descr
->typecode
!= '\0'; descr
++) {
1823 if (descr
->typecode
== c
) {
1827 if (initial
== NULL
|| !(PyList_Check(initial
)
1828 || PyTuple_Check(initial
)))
1831 len
= PySequence_Size(initial
);
1833 a
= newarrayobject(type
, len
, descr
);
1839 for (i
= 0; i
< len
; i
++) {
1841 PySequence_GetItem(initial
, i
);
1846 if (setarrayitem(a
, i
, v
) != 0) {
1853 } else if (initial
!= NULL
&& PyString_Check(initial
)) {
1854 PyObject
*t_initial
= PyTuple_Pack(1,
1857 array_fromstring((arrayobject
*)a
,
1859 Py_DECREF(t_initial
);
1865 #ifdef Py_USING_UNICODE
1866 } else if (initial
!= NULL
&& PyUnicode_Check(initial
)) {
1867 int n
= PyUnicode_GET_DATA_SIZE(initial
);
1869 arrayobject
*self
= (arrayobject
*)a
;
1870 char *item
= self
->ob_item
;
1871 item
= PyMem_Realloc(item
, n
);
1877 self
->ob_item
= item
;
1878 self
->ob_size
= n
/ sizeof(Py_UNICODE
);
1879 memcpy(item
, PyUnicode_AS_DATA(initial
), n
);
1880 self
->allocated
= self
->ob_size
;
1885 if (array_iter_extend((arrayobject
*)a
, it
) == -1) {
1895 PyErr_SetString(PyExc_ValueError
,
1896 "bad typecode (must be c, b, B, u, h, H, i, I, l, L, f or d)");
1901 PyDoc_STRVAR(module_doc
,
1902 "This module defines an object type which can efficiently represent\n\
1903 an array of basic values: characters, integers, floating point\n\
1904 numbers. Arrays are sequence types and behave very much like lists,\n\
1905 except that the type of objects stored in them is constrained. The\n\
1906 type is specified at object creation time by using a type code, which\n\
1907 is a single character. The following type codes are defined:\n\
1909 Type code C Type Minimum size in bytes \n\
1911 'b' signed integer 1 \n\
1912 'B' unsigned integer 1 \n\
1913 'u' Unicode character 2 \n\
1914 'h' signed integer 2 \n\
1915 'H' unsigned integer 2 \n\
1916 'i' signed integer 2 \n\
1917 'I' unsigned integer 2 \n\
1918 'l' signed integer 4 \n\
1919 'L' unsigned integer 4 \n\
1920 'f' floating point 4 \n\
1921 'd' floating point 8 \n\
1923 The constructor is:\n\
1925 array(typecode [, initializer]) -- create a new array\n\
1928 PyDoc_STRVAR(arraytype_doc
,
1929 "array(typecode [, initializer]) -> array\n\
1931 Return a new array whose items are restricted by typecode, and\n\
1932 initialized from the optional initializer value, which must be a list,\n\
1933 string. or iterable over elements of the appropriate type.\n\
1935 Arrays represent basic values and behave very much like lists, except\n\
1936 the type of objects stored in them is constrained.\n\
1940 append() -- append a new item to the end of the array\n\
1941 buffer_info() -- return information giving the current memory info\n\
1942 byteswap() -- byteswap all the items of the array\n\
1943 count() -- return number of occurences of an object\n\
1944 extend() -- extend array by appending multiple elements from an iterable\n\
1945 fromfile() -- read items from a file object\n\
1946 fromlist() -- append items from the list\n\
1947 fromstring() -- append items from the string\n\
1948 index() -- return index of first occurence of an object\n\
1949 insert() -- insert a new item into the array at a provided position\n\
1950 pop() -- remove and return item (default last)\n\
1951 read() -- DEPRECATED, use fromfile()\n\
1952 remove() -- remove first occurence of an object\n\
1953 reverse() -- reverse the order of the items in the array\n\
1954 tofile() -- write all items to a file object\n\
1955 tolist() -- return the array converted to an ordinary list\n\
1956 tostring() -- return the array converted to a string\n\
1957 write() -- DEPRECATED, use tofile()\n\
1961 typecode -- the typecode character used to create the array\n\
1962 itemsize -- the length in bytes of one array item\n\
1965 static PyObject
*array_iter(arrayobject
*ao
);
1967 static PyTypeObject Arraytype
= {
1968 PyObject_HEAD_INIT(NULL
)
1971 sizeof(arrayobject
),
1973 (destructor
)array_dealloc
, /* tp_dealloc */
1978 (reprfunc
)array_repr
, /* tp_repr */
1979 0, /* tp_as _number*/
1980 &array_as_sequence
, /* tp_as _sequence*/
1981 &array_as_mapping
, /* tp_as _mapping*/
1985 PyObject_GenericGetAttr
, /* tp_getattro */
1986 0, /* tp_setattro */
1987 &array_as_buffer
, /* tp_as_buffer*/
1988 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
| Py_TPFLAGS_HAVE_WEAKREFS
, /* tp_flags */
1989 arraytype_doc
, /* tp_doc */
1990 0, /* tp_traverse */
1992 array_richcompare
, /* tp_richcompare */
1993 offsetof(arrayobject
, weakreflist
), /* tp_weaklistoffset */
1994 (getiterfunc
)array_iter
, /* tp_iter */
1995 0, /* tp_iternext */
1996 array_methods
, /* tp_methods */
1998 array_getsets
, /* tp_getset */
2001 0, /* tp_descr_get */
2002 0, /* tp_descr_set */
2003 0, /* tp_dictoffset */
2005 PyType_GenericAlloc
, /* tp_alloc */
2006 array_new
, /* tp_new */
2007 PyObject_Del
, /* tp_free */
2011 /*********************** Array Iterator **************************/
2017 PyObject
* (*getitem
)(struct arrayobject
*, int);
2020 static PyTypeObject PyArrayIter_Type
;
2022 #define PyArrayIter_Check(op) PyObject_TypeCheck(op, &PyArrayIter_Type)
2025 array_iter(arrayobject
*ao
)
2027 arrayiterobject
*it
;
2029 if (!array_Check(ao
)) {
2030 PyErr_BadInternalCall();
2034 it
= PyObject_GC_New(arrayiterobject
, &PyArrayIter_Type
);
2041 it
->getitem
= ao
->ob_descr
->getitem
;
2042 PyObject_GC_Track(it
);
2043 return (PyObject
*)it
;
2047 arrayiter_next(arrayiterobject
*it
)
2049 assert(PyArrayIter_Check(it
));
2050 if (it
->index
< it
->ao
->ob_size
)
2051 return (*it
->getitem
)(it
->ao
, it
->index
++);
2056 arrayiter_dealloc(arrayiterobject
*it
)
2058 PyObject_GC_UnTrack(it
);
2060 PyObject_GC_Del(it
);
2064 arrayiter_traverse(arrayiterobject
*it
, visitproc visit
, void *arg
)
2067 return visit((PyObject
*)(it
->ao
), arg
);
2071 static PyTypeObject PyArrayIter_Type
= {
2072 PyObject_HEAD_INIT(NULL
)
2074 "arrayiterator", /* tp_name */
2075 sizeof(arrayiterobject
), /* tp_basicsize */
2076 0, /* tp_itemsize */
2078 (destructor
)arrayiter_dealloc
, /* tp_dealloc */
2084 0, /* tp_as_number */
2085 0, /* tp_as_sequence */
2086 0, /* tp_as_mapping */
2090 PyObject_GenericGetAttr
, /* tp_getattro */
2091 0, /* tp_setattro */
2092 0, /* tp_as_buffer */
2093 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_HAVE_GC
,/* tp_flags */
2095 (traverseproc
)arrayiter_traverse
, /* tp_traverse */
2097 0, /* tp_richcompare */
2098 0, /* tp_weaklistoffset */
2099 PyObject_SelfIter
, /* tp_iter */
2100 (iternextfunc
)arrayiter_next
, /* tp_iternext */
2105 /*********************** Install Module **************************/
2107 /* No functions in array module. */
2108 static PyMethodDef a_methods
[] = {
2109 {NULL
, NULL
, 0, NULL
} /* Sentinel */
2118 Arraytype
.ob_type
= &PyType_Type
;
2119 PyArrayIter_Type
.ob_type
= &PyType_Type
;
2120 m
= Py_InitModule3("array", a_methods
, module_doc
);
2124 Py_INCREF((PyObject
*)&Arraytype
);
2125 PyModule_AddObject(m
, "ArrayType", (PyObject
*)&Arraytype
);
2126 Py_INCREF((PyObject
*)&Arraytype
);
2127 PyModule_AddObject(m
, "array", (PyObject
*)&Arraytype
);
2128 /* No need to check the error here, the caller will do that */