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 */
10 #else /* !STDC_HEADERS */
11 #ifndef DONT_HAVE_SYS_TYPES_H
12 #include <sys/types.h> /* For size_t */
13 #endif /* DONT_HAVE_SYS_TYPES_H */
14 #endif /* !STDC_HEADERS */
18 struct arrayobject
; /* Forward */
20 /* All possible arraydescr values are defined in the vector "descriptors"
21 * below. That's defined later because the appropriate get and set
22 * functions aren't visible yet.
27 PyObject
* (*getitem
)(struct arrayobject
*, int);
28 int (*setitem
)(struct arrayobject
*, int, PyObject
*);
31 typedef struct arrayobject
{
35 struct arraydescr
*ob_descr
;
38 staticforward PyTypeObject Arraytype
;
40 #define array_Check(op) PyObject_TypeCheck(op, &Arraytype)
41 #define array_CheckExact(op) ((op)->ob_type == &Arraytype)
43 /****************************************************************************
44 Get and Set functions for each type.
45 A Get function takes an arrayobject* and an integer index, returning the
46 array value at that index wrapped in an appropriate PyObject*.
47 A Set function takes an arrayobject, integer index, and PyObject*; sets
48 the array value at that index to the raw C data extracted from the PyObject*,
49 and returns 0 if successful, else nonzero on failure (PyObject* not of an
50 appropriate type or value).
51 Note that the basic Get and Set functions do NOT check that the index is
52 in bounds; that's the responsibility of the caller.
53 ****************************************************************************/
56 c_getitem(arrayobject
*ap
, int i
)
58 return PyString_FromStringAndSize(&((char *)ap
->ob_item
)[i
], 1);
62 c_setitem(arrayobject
*ap
, int i
, PyObject
*v
)
65 if (!PyArg_Parse(v
, "c;array item must be char", &x
))
68 ((char *)ap
->ob_item
)[i
] = x
;
73 b_getitem(arrayobject
*ap
, int i
)
75 long x
= ((char *)ap
->ob_item
)[i
];
78 return PyInt_FromLong(x
);
82 b_setitem(arrayobject
*ap
, int i
, PyObject
*v
)
85 /* PyArg_Parse's 'b' formatter is for an unsigned char, therefore
86 must use the next size up that is signed ('h') and manually do
87 the overflow checking */
88 if (!PyArg_Parse(v
, "h;array item must be integer", &x
))
91 PyErr_SetString(PyExc_OverflowError
,
92 "signed char is less than minimum");
96 PyErr_SetString(PyExc_OverflowError
,
97 "signed char is greater than maximum");
101 ((char *)ap
->ob_item
)[i
] = (char)x
;
106 BB_getitem(arrayobject
*ap
, int i
)
108 long x
= ((unsigned char *)ap
->ob_item
)[i
];
109 return PyInt_FromLong(x
);
113 BB_setitem(arrayobject
*ap
, int i
, PyObject
*v
)
116 /* 'B' == unsigned char, maps to PyArg_Parse's 'b' formatter */
117 if (!PyArg_Parse(v
, "b;array item must be integer", &x
))
120 ((char *)ap
->ob_item
)[i
] = x
;
124 #ifdef Py_USING_UNICODE
126 u_getitem(arrayobject
*ap
, int i
)
128 return PyUnicode_FromUnicode(&((Py_UNICODE
*) ap
->ob_item
)[i
], 1);
132 u_setitem(arrayobject
*ap
, int i
, PyObject
*v
)
137 if (!PyArg_Parse(v
, "u#;array item must be unicode character", &p
, &len
))
140 PyErr_SetString(PyExc_TypeError
, "array item must be unicode character");
144 ((Py_UNICODE
*)ap
->ob_item
)[i
] = p
[0];
150 h_getitem(arrayobject
*ap
, int i
)
152 return PyInt_FromLong((long) ((short *)ap
->ob_item
)[i
]);
156 h_setitem(arrayobject
*ap
, int i
, PyObject
*v
)
159 /* 'h' == signed short, maps to PyArg_Parse's 'h' formatter */
160 if (!PyArg_Parse(v
, "h;array item must be integer", &x
))
163 ((short *)ap
->ob_item
)[i
] = x
;
168 HH_getitem(arrayobject
*ap
, int i
)
170 return PyInt_FromLong((long) ((unsigned short *)ap
->ob_item
)[i
]);
174 HH_setitem(arrayobject
*ap
, int i
, PyObject
*v
)
177 /* PyArg_Parse's 'h' formatter is for a signed short, therefore
178 must use the next size up and manually do the overflow checking */
179 if (!PyArg_Parse(v
, "i;array item must be integer", &x
))
182 PyErr_SetString(PyExc_OverflowError
,
183 "unsigned short is less than minimum");
186 else if (x
> USHRT_MAX
) {
187 PyErr_SetString(PyExc_OverflowError
,
188 "unsigned short is greater than maximum");
192 ((short *)ap
->ob_item
)[i
] = (short)x
;
197 i_getitem(arrayobject
*ap
, int i
)
199 return PyInt_FromLong((long) ((int *)ap
->ob_item
)[i
]);
203 i_setitem(arrayobject
*ap
, int i
, PyObject
*v
)
206 /* 'i' == signed int, maps to PyArg_Parse's 'i' formatter */
207 if (!PyArg_Parse(v
, "i;array item must be integer", &x
))
210 ((int *)ap
->ob_item
)[i
] = x
;
215 II_getitem(arrayobject
*ap
, int i
)
217 return PyLong_FromUnsignedLong(
218 (unsigned long) ((unsigned int *)ap
->ob_item
)[i
]);
222 II_setitem(arrayobject
*ap
, int i
, PyObject
*v
)
225 if (PyLong_Check(v
)) {
226 x
= PyLong_AsUnsignedLong(v
);
227 if (x
== (unsigned long) -1 && PyErr_Occurred())
232 if (!PyArg_Parse(v
, "l;array item must be integer", &y
))
235 PyErr_SetString(PyExc_OverflowError
,
236 "unsigned int is less than minimum");
239 x
= (unsigned long)y
;
243 PyErr_SetString(PyExc_OverflowError
,
244 "unsigned int is greater than maximum");
249 ((unsigned int *)ap
->ob_item
)[i
] = (unsigned int)x
;
254 l_getitem(arrayobject
*ap
, int i
)
256 return PyInt_FromLong(((long *)ap
->ob_item
)[i
]);
260 l_setitem(arrayobject
*ap
, int i
, PyObject
*v
)
263 if (!PyArg_Parse(v
, "l;array item must be integer", &x
))
266 ((long *)ap
->ob_item
)[i
] = x
;
271 LL_getitem(arrayobject
*ap
, int i
)
273 return PyLong_FromUnsignedLong(((unsigned long *)ap
->ob_item
)[i
]);
277 LL_setitem(arrayobject
*ap
, int i
, PyObject
*v
)
280 if (PyLong_Check(v
)) {
281 x
= PyLong_AsUnsignedLong(v
);
282 if (x
== (unsigned long) -1 && PyErr_Occurred())
287 if (!PyArg_Parse(v
, "l;array item must be integer", &y
))
290 PyErr_SetString(PyExc_OverflowError
,
291 "unsigned long is less than minimum");
294 x
= (unsigned long)y
;
298 PyErr_SetString(PyExc_OverflowError
,
299 "unsigned long is greater than maximum");
304 ((unsigned long *)ap
->ob_item
)[i
] = x
;
309 f_getitem(arrayobject
*ap
, int i
)
311 return PyFloat_FromDouble((double) ((float *)ap
->ob_item
)[i
]);
315 f_setitem(arrayobject
*ap
, int i
, PyObject
*v
)
318 if (!PyArg_Parse(v
, "f;array item must be float", &x
))
321 ((float *)ap
->ob_item
)[i
] = x
;
326 d_getitem(arrayobject
*ap
, int i
)
328 return PyFloat_FromDouble(((double *)ap
->ob_item
)[i
]);
332 d_setitem(arrayobject
*ap
, int i
, PyObject
*v
)
335 if (!PyArg_Parse(v
, "d;array item must be float", &x
))
338 ((double *)ap
->ob_item
)[i
] = x
;
342 /* Description of types */
343 static struct arraydescr descriptors
[] = {
344 {'c', sizeof(char), c_getitem
, c_setitem
},
345 {'b', sizeof(char), b_getitem
, b_setitem
},
346 {'B', sizeof(char), BB_getitem
, BB_setitem
},
347 #ifdef Py_USING_UNICODE
348 {'u', sizeof(Py_UNICODE
), u_getitem
, u_setitem
},
350 {'h', sizeof(short), h_getitem
, h_setitem
},
351 {'H', sizeof(short), HH_getitem
, HH_setitem
},
352 {'i', sizeof(int), i_getitem
, i_setitem
},
353 {'I', sizeof(int), II_getitem
, II_setitem
},
354 {'l', sizeof(long), l_getitem
, l_setitem
},
355 {'L', sizeof(long), LL_getitem
, LL_setitem
},
356 {'f', sizeof(float), f_getitem
, f_setitem
},
357 {'d', sizeof(double), d_getitem
, d_setitem
},
358 {'\0', 0, 0, 0} /* Sentinel */
361 /****************************************************************************
362 Implementations of array object methods.
363 ****************************************************************************/
366 newarrayobject(PyTypeObject
*type
, int size
, struct arraydescr
*descr
)
372 PyErr_BadInternalCall();
376 nbytes
= size
* descr
->itemsize
;
377 /* Check for overflow */
378 if (nbytes
/ descr
->itemsize
!= (size_t)size
) {
379 return PyErr_NoMemory();
381 op
= (arrayobject
*) type
->tp_alloc(type
, 0);
390 op
->ob_item
= PyMem_NEW(char, nbytes
);
391 if (op
->ob_item
== NULL
) {
393 return PyErr_NoMemory();
396 op
->ob_descr
= descr
;
397 return (PyObject
*) op
;
401 getarrayitem(PyObject
*op
, int i
)
403 register arrayobject
*ap
;
404 assert(array_Check(op
));
405 ap
= (arrayobject
*)op
;
406 if (i
< 0 || i
>= ap
->ob_size
) {
407 PyErr_SetString(PyExc_IndexError
, "array index out of range");
410 return (*ap
->ob_descr
->getitem
)(ap
, i
);
414 ins1(arrayobject
*self
, int where
, PyObject
*v
)
418 PyErr_BadInternalCall();
421 if ((*self
->ob_descr
->setitem
)(self
, -1, v
) < 0)
423 items
= self
->ob_item
;
424 PyMem_RESIZE(items
, char,
425 (self
->ob_size
+1) * self
->ob_descr
->itemsize
);
432 if (where
> self
->ob_size
)
433 where
= self
->ob_size
;
434 memmove(items
+ (where
+1)*self
->ob_descr
->itemsize
,
435 items
+ where
*self
->ob_descr
->itemsize
,
436 (self
->ob_size
-where
)*self
->ob_descr
->itemsize
);
437 self
->ob_item
= items
;
439 return (*self
->ob_descr
->setitem
)(self
, where
, v
);
445 array_dealloc(arrayobject
*op
)
447 if (op
->ob_item
!= NULL
)
448 PyMem_DEL(op
->ob_item
);
449 op
->ob_type
->tp_free((PyObject
*)op
);
453 array_richcompare(PyObject
*v
, PyObject
*w
, int op
)
455 arrayobject
*va
, *wa
;
461 if (!array_Check(v
) || !array_Check(w
)) {
462 Py_INCREF(Py_NotImplemented
);
463 return Py_NotImplemented
;
466 va
= (arrayobject
*)v
;
467 wa
= (arrayobject
*)w
;
469 if (va
->ob_size
!= wa
->ob_size
&& (op
== Py_EQ
|| op
== Py_NE
)) {
470 /* Shortcut: if the lengths differ, the arrays differ */
479 /* Search for the first index where items are different */
481 for (i
= 0; i
< va
->ob_size
&& i
< wa
->ob_size
; i
++) {
482 vi
= getarrayitem(v
, i
);
483 wi
= getarrayitem(w
, i
);
484 if (vi
== NULL
|| wi
== NULL
) {
489 k
= PyObject_RichCompareBool(vi
, wi
, Py_EQ
);
491 break; /* Keeping vi and wi alive! */
499 /* No more items to compare -- compare sizes */
500 int vs
= va
->ob_size
;
501 int ws
= wa
->ob_size
;
504 case Py_LT
: cmp
= vs
< ws
; break;
505 case Py_LE
: cmp
= vs
<= ws
; break;
506 case Py_EQ
: cmp
= vs
== ws
; break;
507 case Py_NE
: cmp
= vs
!= ws
; break;
508 case Py_GT
: cmp
= vs
> ws
; break;
509 case Py_GE
: cmp
= vs
>= ws
; break;
510 default: return NULL
; /* cannot happen */
520 /* We have an item that differs. First, shortcuts for EQ/NE */
525 else if (op
== Py_NE
) {
530 /* Compare the final item again using the proper operator */
531 res
= PyObject_RichCompare(vi
, wi
, op
);
539 array_length(arrayobject
*a
)
545 array_item(arrayobject
*a
, int i
)
547 if (i
< 0 || i
>= a
->ob_size
) {
548 PyErr_SetString(PyExc_IndexError
, "array index out of range");
551 return getarrayitem((PyObject
*)a
, i
);
555 array_slice(arrayobject
*a
, int ilow
, int ihigh
)
560 else if (ilow
> a
->ob_size
)
566 else if (ihigh
> a
->ob_size
)
568 np
= (arrayobject
*) newarrayobject(&Arraytype
, ihigh
- ilow
, a
->ob_descr
);
571 memcpy(np
->ob_item
, a
->ob_item
+ ilow
* a
->ob_descr
->itemsize
,
572 (ihigh
-ilow
) * a
->ob_descr
->itemsize
);
573 return (PyObject
*)np
;
577 array_concat(arrayobject
*a
, PyObject
*bb
)
581 if (!array_Check(bb
)) {
582 PyErr_Format(PyExc_TypeError
,
583 "can only append array (not \"%.200s\") to array",
584 bb
->ob_type
->tp_name
);
587 #define b ((arrayobject *)bb)
588 if (a
->ob_descr
!= b
->ob_descr
) {
592 size
= a
->ob_size
+ b
->ob_size
;
593 np
= (arrayobject
*) newarrayobject(&Arraytype
, size
, a
->ob_descr
);
597 memcpy(np
->ob_item
, a
->ob_item
, a
->ob_size
*a
->ob_descr
->itemsize
);
598 memcpy(np
->ob_item
+ a
->ob_size
*a
->ob_descr
->itemsize
,
599 b
->ob_item
, b
->ob_size
*b
->ob_descr
->itemsize
);
600 return (PyObject
*)np
;
605 array_repeat(arrayobject
*a
, int n
)
614 size
= a
->ob_size
* n
;
615 np
= (arrayobject
*) newarrayobject(&Arraytype
, size
, a
->ob_descr
);
619 nbytes
= a
->ob_size
* a
->ob_descr
->itemsize
;
620 for (i
= 0; i
< n
; i
++) {
621 memcpy(p
, a
->ob_item
, nbytes
);
624 return (PyObject
*) np
;
628 array_ass_slice(arrayobject
*a
, int ilow
, int ihigh
, PyObject
*v
)
631 int n
; /* Size of replacement array */
632 int d
; /* Change in size */
633 #define b ((arrayobject *)v)
636 else if (array_Check(v
)) {
639 /* Special case "a[i:j] = a" -- copy b first */
641 v
= array_slice(b
, 0, n
);
642 ret
= array_ass_slice(a
, ilow
, ihigh
, v
);
646 if (b
->ob_descr
!= a
->ob_descr
) {
652 PyErr_Format(PyExc_TypeError
,
653 "can only assign array (not \"%.200s\") to array slice",
654 v
->ob_type
->tp_name
);
659 else if (ilow
> a
->ob_size
)
665 else if (ihigh
> a
->ob_size
)
668 d
= n
- (ihigh
-ilow
);
669 if (d
< 0) { /* Delete -d items */
670 memmove(item
+ (ihigh
+d
)*a
->ob_descr
->itemsize
,
671 item
+ ihigh
*a
->ob_descr
->itemsize
,
672 (a
->ob_size
-ihigh
)*a
->ob_descr
->itemsize
);
674 PyMem_RESIZE(item
, char, a
->ob_size
*a
->ob_descr
->itemsize
);
678 else if (d
> 0) { /* Insert d items */
679 PyMem_RESIZE(item
, char,
680 (a
->ob_size
+ d
)*a
->ob_descr
->itemsize
);
685 memmove(item
+ (ihigh
+d
)*a
->ob_descr
->itemsize
,
686 item
+ ihigh
*a
->ob_descr
->itemsize
,
687 (a
->ob_size
-ihigh
)*a
->ob_descr
->itemsize
);
692 memcpy(item
+ ilow
*a
->ob_descr
->itemsize
, b
->ob_item
,
693 n
*b
->ob_descr
->itemsize
);
699 array_ass_item(arrayobject
*a
, int i
, PyObject
*v
)
701 if (i
< 0 || i
>= a
->ob_size
) {
702 PyErr_SetString(PyExc_IndexError
,
703 "array assignment index out of range");
707 return array_ass_slice(a
, i
, i
+1, v
);
708 return (*a
->ob_descr
->setitem
)(a
, i
, v
);
712 setarrayitem(PyObject
*a
, int i
, PyObject
*v
)
714 assert(array_Check(a
));
715 return array_ass_item((arrayobject
*)a
, i
, v
);
719 array_do_extend(arrayobject
*self
, PyObject
*bb
)
723 if (!array_Check(bb
)) {
724 PyErr_Format(PyExc_TypeError
,
725 "can only extend array with array (not \"%.200s\")",
726 bb
->ob_type
->tp_name
);
729 #define b ((arrayobject *)bb)
730 if (self
->ob_descr
!= b
->ob_descr
) {
731 PyErr_SetString(PyExc_TypeError
,
732 "can only extend with array of same kind");
735 size
= self
->ob_size
+ b
->ob_size
;
736 PyMem_RESIZE(self
->ob_item
, char, size
*self
->ob_descr
->itemsize
);
737 if (self
->ob_item
== NULL
) {
742 memcpy(self
->ob_item
+ self
->ob_size
*self
->ob_descr
->itemsize
,
743 b
->ob_item
, b
->ob_size
*b
->ob_descr
->itemsize
);
744 self
->ob_size
= size
;
751 array_inplace_concat(arrayobject
*self
, PyObject
*bb
)
753 if (array_do_extend(self
, bb
) == -1)
756 return (PyObject
*)self
;
760 array_inplace_repeat(arrayobject
*self
, int n
)
765 if (self
->ob_size
> 0) {
768 items
= self
->ob_item
;
769 size
= self
->ob_size
* self
->ob_descr
->itemsize
;
772 self
->ob_item
= NULL
;
776 PyMem_Resize(items
, char, n
* size
);
778 return PyErr_NoMemory();
780 for (i
= 1; i
< n
; i
++) {
782 memcpy(p
, items
, size
);
784 self
->ob_item
= items
;
789 return (PyObject
*)self
;
794 ins(arrayobject
*self
, int where
, PyObject
*v
)
796 if (ins1(self
, where
, v
) != 0)
803 array_count(arrayobject
*self
, PyObject
*args
)
809 if (!PyArg_ParseTuple(args
, "O:count", &v
))
811 for (i
= 0; i
< self
->ob_size
; i
++) {
812 PyObject
*selfi
= getarrayitem((PyObject
*)self
, i
);
813 int cmp
= PyObject_RichCompareBool(selfi
, v
, Py_EQ
);
820 return PyInt_FromLong((long)count
);
823 PyDoc_STRVAR(count_doc
,
826 Return number of occurences of x in the array.");
829 array_index(arrayobject
*self
, PyObject
*args
)
834 if (!PyArg_ParseTuple(args
, "O:index", &v
))
836 for (i
= 0; i
< self
->ob_size
; i
++) {
837 PyObject
*selfi
= getarrayitem((PyObject
*)self
, i
);
838 int cmp
= PyObject_RichCompareBool(selfi
, v
, Py_EQ
);
841 return PyInt_FromLong((long)i
);
846 PyErr_SetString(PyExc_ValueError
, "array.index(x): x not in list");
850 PyDoc_STRVAR(index_doc
,
853 Return index of first occurence of x in the array.");
856 array_remove(arrayobject
*self
, PyObject
*args
)
861 if (!PyArg_ParseTuple(args
, "O:remove", &v
))
863 for (i
= 0; i
< self
->ob_size
; i
++) {
864 PyObject
*selfi
= getarrayitem((PyObject
*)self
,i
);
865 int cmp
= PyObject_RichCompareBool(selfi
, v
, Py_EQ
);
868 if (array_ass_slice(self
, i
, i
+1,
869 (PyObject
*)NULL
) != 0)
877 PyErr_SetString(PyExc_ValueError
, "array.remove(x): x not in list");
881 PyDoc_STRVAR(remove_doc
,
884 Remove the first occurence of x in the array.");
887 array_pop(arrayobject
*self
, PyObject
*args
)
891 if (!PyArg_ParseTuple(args
, "|i:pop", &i
))
893 if (self
->ob_size
== 0) {
894 /* Special-case most common failure cause */
895 PyErr_SetString(PyExc_IndexError
, "pop from empty array");
900 if (i
< 0 || i
>= self
->ob_size
) {
901 PyErr_SetString(PyExc_IndexError
, "pop index out of range");
904 v
= getarrayitem((PyObject
*)self
,i
);
905 if (array_ass_slice(self
, i
, i
+1, (PyObject
*)NULL
) != 0) {
912 PyDoc_STRVAR(pop_doc
,
915 Return the i-th element and delete it from the array. i defaults to -1.");
918 array_extend(arrayobject
*self
, PyObject
*args
)
922 if (!PyArg_ParseTuple(args
, "O:extend", &bb
))
924 if (array_do_extend(self
, bb
) == -1)
930 PyDoc_STRVAR(extend_doc
,
933 Append array items to the end of the array.");
936 array_insert(arrayobject
*self
, PyObject
*args
)
940 if (!PyArg_ParseTuple(args
, "iO:insert", &i
, &v
))
942 return ins(self
, i
, v
);
945 PyDoc_STRVAR(insert_doc
,
948 Insert a new item x into the array before position i.");
952 array_buffer_info(arrayobject
*self
, PyObject
*args
)
954 PyObject
* retval
= NULL
;
955 if (!PyArg_ParseTuple(args
, ":buffer_info"))
957 retval
= PyTuple_New(2);
961 PyTuple_SET_ITEM(retval
, 0, PyLong_FromVoidPtr(self
->ob_item
));
962 PyTuple_SET_ITEM(retval
, 1, PyInt_FromLong((long)(self
->ob_size
)));
967 PyDoc_STRVAR(buffer_info_doc
,
968 "buffer_info() -> (address, length)\n\
970 Return a tuple (address, length) giving the current memory address and\n\
971 the length in items of the buffer used to hold array's contents\n\
972 The length should be multiplied by the itemsize attribute to calculate\n\
973 the buffer length in bytes.");
977 array_append(arrayobject
*self
, PyObject
*args
)
980 if (!PyArg_ParseTuple(args
, "O:append", &v
))
982 return ins(self
, (int) self
->ob_size
, v
);
985 PyDoc_STRVAR(append_doc
,
988 Append new value x to the end of the array.");
992 array_byteswap(arrayobject
*self
, PyObject
*args
)
997 if (!PyArg_ParseTuple(args
, ":byteswap"))
1000 switch (self
->ob_descr
->itemsize
) {
1004 for (p
= self
->ob_item
, i
= self
->ob_size
; --i
>= 0; p
+= 2) {
1011 for (p
= self
->ob_item
, i
= self
->ob_size
; --i
>= 0; p
+= 4) {
1021 for (p
= self
->ob_item
, i
= self
->ob_size
; --i
>= 0; p
+= 8) {
1037 PyErr_SetString(PyExc_RuntimeError
,
1038 "don't know how to byteswap this array type");
1045 PyDoc_STRVAR(byteswap_doc
,
1048 Byteswap all items of the array. If the items in the array are not 1, 2,\n\
1049 4, or 8 bytes in size, RuntimeError is raised.");
1052 array_reverse(arrayobject
*self
, PyObject
*args
)
1054 register int itemsize
= self
->ob_descr
->itemsize
;
1055 register char *p
, *q
;
1056 /* little buffer to hold items while swapping */
1057 char tmp
[256]; /* 8 is probably enough -- but why skimp */
1058 assert(itemsize
<= sizeof(tmp
));
1060 if (!PyArg_ParseTuple(args
, ":reverse"))
1063 if (self
->ob_size
> 1) {
1064 for (p
= self
->ob_item
,
1065 q
= self
->ob_item
+ (self
->ob_size
- 1)*itemsize
;
1067 p
+= itemsize
, q
-= itemsize
) {
1068 /* memory areas guaranteed disjoint, so memcpy
1069 * is safe (& memmove may be slower).
1071 memcpy(tmp
, p
, itemsize
);
1072 memcpy(p
, q
, itemsize
);
1073 memcpy(q
, tmp
, itemsize
);
1081 PyDoc_STRVAR(reverse_doc
,
1084 Reverse the order of the items in the array.");
1087 array_fromfile(arrayobject
*self
, PyObject
*args
)
1092 if (!PyArg_ParseTuple(args
, "Oi:fromfile", &f
, &n
))
1094 fp
= PyFile_AsFile(f
);
1096 PyErr_SetString(PyExc_TypeError
, "arg1 must be open file");
1100 char *item
= self
->ob_item
;
1101 int itemsize
= self
->ob_descr
->itemsize
;
1105 /* Be careful here about overflow */
1106 if ((newlength
= self
->ob_size
+ n
) <= 0 ||
1107 (newbytes
= newlength
* itemsize
) / itemsize
!=
1110 PyMem_RESIZE(item
, char, newbytes
);
1116 self
->ob_item
= item
;
1118 nread
= fread(item
+ (self
->ob_size
- n
) * itemsize
,
1120 if (nread
< (size_t)n
) {
1121 self
->ob_size
-= (n
- nread
);
1122 PyMem_RESIZE(item
, char, self
->ob_size
*itemsize
);
1123 self
->ob_item
= item
;
1124 PyErr_SetString(PyExc_EOFError
,
1125 "not enough items in file");
1133 PyDoc_STRVAR(fromfile_doc
,
1136 Read n objects from the file object f and append them to the end of the\n\
1137 array. Also called as read.");
1141 array_tofile(arrayobject
*self
, PyObject
*args
)
1145 if (!PyArg_ParseTuple(args
, "O:tofile", &f
))
1147 fp
= PyFile_AsFile(f
);
1149 PyErr_SetString(PyExc_TypeError
, "arg must be open file");
1152 if (self
->ob_size
> 0) {
1153 if (fwrite(self
->ob_item
, self
->ob_descr
->itemsize
,
1154 self
->ob_size
, fp
) != (size_t)self
->ob_size
) {
1155 PyErr_SetFromErrno(PyExc_IOError
);
1164 PyDoc_STRVAR(tofile_doc
,
1167 Write all items (as machine values) to the file object f. Also called as\n\
1172 array_fromlist(arrayobject
*self
, PyObject
*args
)
1176 int itemsize
= self
->ob_descr
->itemsize
;
1177 if (!PyArg_ParseTuple(args
, "O:fromlist", &list
))
1179 if (!PyList_Check(list
)) {
1180 PyErr_SetString(PyExc_TypeError
, "arg must be list");
1183 n
= PyList_Size(list
);
1185 char *item
= self
->ob_item
;
1187 PyMem_RESIZE(item
, char, (self
->ob_size
+ n
) * itemsize
);
1192 self
->ob_item
= item
;
1194 for (i
= 0; i
< n
; i
++) {
1195 PyObject
*v
= PyList_GetItem(list
, i
);
1196 if ((*self
->ob_descr
->setitem
)(self
,
1197 self
->ob_size
- n
+ i
, v
) != 0) {
1199 PyMem_RESIZE(item
, char,
1200 self
->ob_size
* itemsize
);
1201 self
->ob_item
= item
;
1210 PyDoc_STRVAR(fromlist_doc
,
1213 Append items to array from list.");
1217 array_tolist(arrayobject
*self
, PyObject
*args
)
1219 PyObject
*list
= PyList_New(self
->ob_size
);
1221 if (!PyArg_ParseTuple(args
, ":tolist"))
1225 for (i
= 0; i
< self
->ob_size
; i
++) {
1226 PyObject
*v
= getarrayitem((PyObject
*)self
, i
);
1231 PyList_SetItem(list
, i
, v
);
1236 PyDoc_STRVAR(tolist_doc
,
1237 "tolist() -> list\n\
1239 Convert array to an ordinary list with the same items.");
1243 array_fromstring(arrayobject
*self
, PyObject
*args
)
1247 int itemsize
= self
->ob_descr
->itemsize
;
1248 if (!PyArg_ParseTuple(args
, "s#:fromstring", &str
, &n
))
1250 if (n
% itemsize
!= 0) {
1251 PyErr_SetString(PyExc_ValueError
,
1252 "string length not a multiple of item size");
1257 char *item
= self
->ob_item
;
1258 PyMem_RESIZE(item
, char, (self
->ob_size
+ n
) * itemsize
);
1263 self
->ob_item
= item
;
1265 memcpy(item
+ (self
->ob_size
- n
) * itemsize
,
1272 PyDoc_STRVAR(fromstring_doc
,
1273 "fromstring(string)\n\
1275 Appends items from the string, interpreting it as an array of machine\n\
1276 values,as if it had been read from a file using the fromfile() method).");
1280 array_tostring(arrayobject
*self
, PyObject
*args
)
1282 if (!PyArg_ParseTuple(args
, ":tostring"))
1284 return PyString_FromStringAndSize(self
->ob_item
,
1285 self
->ob_size
* self
->ob_descr
->itemsize
);
1288 PyDoc_STRVAR(tostring_doc
,
1289 "tostring() -> string\n\
1291 Convert the array to an array of machine values and return the string\n\
1296 #ifdef Py_USING_UNICODE
1298 array_fromunicode(arrayobject
*self
, PyObject
*args
)
1303 if (!PyArg_ParseTuple(args
, "u#:fromunicode", &ustr
, &n
))
1305 if (self
->ob_descr
->typecode
!= 'u') {
1306 PyErr_SetString(PyExc_ValueError
,
1307 "fromunicode() may only be called on "
1312 Py_UNICODE
*item
= (Py_UNICODE
*) self
->ob_item
;
1313 PyMem_RESIZE(item
, Py_UNICODE
, self
->ob_size
+ n
);
1318 self
->ob_item
= (char *) item
;
1320 memcpy(item
+ self
->ob_size
- n
,
1321 ustr
, n
* sizeof(Py_UNICODE
));
1328 PyDoc_STRVAR(fromunicode_doc
,
1329 "fromunicode(ustr)\n\
1331 Extends this array with data from the unicode string ustr.\n\
1332 The array must be a type 'u' array; otherwise a ValueError\n\
1333 is raised. Use array.fromstring(ustr.decode(...)) to\n\
1334 append Unicode data to an array of some other type.");
1338 array_tounicode(arrayobject
*self
, PyObject
*args
)
1340 if (!PyArg_ParseTuple(args
, ":tounicode"))
1342 if (self
->ob_descr
->typecode
!= 'u') {
1343 PyErr_SetString(PyExc_ValueError
,
1344 "tounicode() may only be called on type 'u' arrays");
1347 return PyUnicode_FromUnicode((Py_UNICODE
*) self
->ob_item
, self
->ob_size
);
1350 PyDoc_STRVAR(tounicode_doc
,
1351 "tounicode() -> unicode\n\
1353 Convert the array to a unicode string. The array must be\n\
1354 a type 'u' array; otherwise a ValueError is raised. Use\n\
1355 array.tostring().decode() to obtain a unicode string from\n\
1356 an array of some other type.");
1358 #endif /* Py_USING_UNICODE */
1362 array_get_typecode(arrayobject
*a
, void *closure
)
1364 char tc
= a
->ob_descr
->typecode
;
1365 return PyString_FromStringAndSize(&tc
, 1);
1369 array_get_itemsize(arrayobject
*a
, void *closure
)
1371 return PyInt_FromLong((long)a
->ob_descr
->itemsize
);
1374 static PyGetSetDef array_getsets
[] = {
1375 {"typecode", (getter
) array_get_typecode
, NULL
,
1376 "the typecode character used to create the array"},
1377 {"itemsize", (getter
) array_get_itemsize
, NULL
,
1378 "the size, in bytes, of one array item"},
1382 PyMethodDef array_methods
[] = {
1383 {"append", (PyCFunction
)array_append
, METH_VARARGS
,
1385 {"buffer_info", (PyCFunction
)array_buffer_info
, METH_VARARGS
,
1387 {"byteswap", (PyCFunction
)array_byteswap
, METH_VARARGS
,
1389 {"count", (PyCFunction
)array_count
, METH_VARARGS
,
1391 {"extend", (PyCFunction
)array_extend
, METH_VARARGS
,
1393 {"fromfile", (PyCFunction
)array_fromfile
, METH_VARARGS
,
1395 {"fromlist", (PyCFunction
)array_fromlist
, METH_VARARGS
,
1397 {"fromstring", (PyCFunction
)array_fromstring
, METH_VARARGS
,
1399 #ifdef Py_USING_UNICODE
1400 {"fromunicode", (PyCFunction
)array_fromunicode
, METH_VARARGS
,
1403 {"index", (PyCFunction
)array_index
, METH_VARARGS
,
1405 {"insert", (PyCFunction
)array_insert
, METH_VARARGS
,
1407 {"pop", (PyCFunction
)array_pop
, METH_VARARGS
,
1409 {"read", (PyCFunction
)array_fromfile
, METH_VARARGS
,
1411 {"remove", (PyCFunction
)array_remove
, METH_VARARGS
,
1413 {"reverse", (PyCFunction
)array_reverse
, METH_VARARGS
,
1415 /* {"sort", (PyCFunction)array_sort, METH_VARARGS,
1417 {"tofile", (PyCFunction
)array_tofile
, METH_VARARGS
,
1419 {"tolist", (PyCFunction
)array_tolist
, METH_VARARGS
,
1421 {"tostring", (PyCFunction
)array_tostring
, METH_VARARGS
,
1423 #ifdef Py_USING_UNICODE
1424 {"tounicode", (PyCFunction
)array_tounicode
, METH_VARARGS
,
1427 {"write", (PyCFunction
)array_tofile
, METH_VARARGS
,
1429 {NULL
, NULL
} /* sentinel */
1433 array_repr(arrayobject
*a
)
1435 char buf
[256], typecode
;
1436 PyObject
*s
, *t
, *comma
, *v
;
1440 typecode
= a
->ob_descr
->typecode
;
1442 PyOS_snprintf(buf
, sizeof(buf
), "array('%c')", typecode
);
1443 return PyString_FromString(buf
);
1446 if (typecode
== 'c' || typecode
== 'u') {
1447 PyObject
*t_empty
= PyTuple_New(0);
1448 PyOS_snprintf(buf
, sizeof(buf
), "array('%c', ", typecode
);
1449 s
= PyString_FromString(buf
);
1450 #ifdef Py_USING_UNICODE
1451 if (typecode
== 'c')
1453 v
= array_tostring(a
, t_empty
);
1454 #ifdef Py_USING_UNICODE
1456 v
= array_tounicode(a
, t_empty
);
1459 t
= PyObject_Repr(v
);
1461 PyString_ConcatAndDel(&s
, t
);
1462 PyString_ConcatAndDel(&s
, PyString_FromString(")"));
1465 PyOS_snprintf(buf
, sizeof(buf
), "array('%c', [", typecode
);
1466 s
= PyString_FromString(buf
);
1467 comma
= PyString_FromString(", ");
1468 for (i
= 0; i
< len
&& !PyErr_Occurred(); i
++) {
1470 PyString_Concat(&s
, comma
);
1471 v
= (a
->ob_descr
->getitem
)(a
, i
);
1472 t
= PyObject_Repr(v
);
1474 PyString_ConcatAndDel(&s
, t
);
1477 PyString_ConcatAndDel(&s
, PyString_FromString("])"));
1482 array_subscr(arrayobject
* self
, PyObject
* item
)
1484 if (PyInt_Check(item
)) {
1485 long i
= PyInt_AS_LONG(item
);
1488 return array_item(self
, i
);
1490 else if (PyLong_Check(item
)) {
1491 long i
= PyLong_AsLong(item
);
1492 if (i
== -1 && PyErr_Occurred())
1496 return array_item(self
, i
);
1498 else if (PySlice_Check(item
)) {
1499 int start
, stop
, step
, slicelength
, cur
, i
;
1502 int itemsize
= self
->ob_descr
->itemsize
;
1504 if (PySlice_GetIndicesEx((PySliceObject
*)item
, self
->ob_size
,
1505 &start
, &stop
, &step
, &slicelength
) < 0) {
1509 if (slicelength
<= 0) {
1510 return newarrayobject(&Arraytype
, 0, self
->ob_descr
);
1513 result
= newarrayobject(&Arraytype
, slicelength
, self
->ob_descr
);
1514 if (!result
) return NULL
;
1516 ar
= (arrayobject
*)result
;
1518 for (cur
= start
, i
= 0; i
< slicelength
;
1520 memcpy(ar
->ob_item
+ i
*itemsize
,
1521 self
->ob_item
+ cur
*itemsize
,
1529 PyErr_SetString(PyExc_TypeError
,
1530 "list indices must be integers");
1536 array_ass_subscr(arrayobject
* self
, PyObject
* item
, PyObject
* value
)
1538 if (PyInt_Check(item
)) {
1539 long i
= PyInt_AS_LONG(item
);
1542 return array_ass_item(self
, i
, value
);
1544 else if (PyLong_Check(item
)) {
1545 long i
= PyLong_AsLong(item
);
1546 if (i
== -1 && PyErr_Occurred())
1550 return array_ass_item(self
, i
, value
);
1552 else if (PySlice_Check(item
)) {
1553 int start
, stop
, step
, slicelength
;
1554 int itemsize
= self
->ob_descr
->itemsize
;
1556 if (PySlice_GetIndicesEx((PySliceObject
*)item
, self
->ob_size
,
1557 &start
, &stop
, &step
, &slicelength
) < 0) {
1561 /* treat A[slice(a,b)] = v _exactly_ like A[a:b] = v */
1562 if (step
== 1 && ((PySliceObject
*)item
)->step
== Py_None
)
1563 return array_ass_slice(self
, start
, stop
, value
);
1565 if (value
== NULL
) {
1569 if (slicelength
<= 0)
1574 start
= stop
+ step
*(slicelength
- 1) - 1;
1578 for (cur
= start
, i
= 0; cur
< stop
;
1580 memmove(self
->ob_item
+ (cur
- i
)*itemsize
,
1581 self
->ob_item
+ (cur
+ 1)*itemsize
,
1582 (step
- 1) * itemsize
);
1584 if (self
->ob_size
> (start
+ slicelength
*step
)) {
1585 memmove(self
->ob_item
+ (start
+ slicelength
*(step
- 1))*itemsize
,
1586 self
->ob_item
+ (start
+ slicelength
*step
)*itemsize
,
1587 (self
->ob_size
- (start
+ slicelength
*step
))*itemsize
);
1590 self
->ob_size
-= slicelength
;
1591 self
->ob_item
= PyMem_REALLOC(self
->ob_item
, itemsize
*self
->ob_size
);
1601 if (!array_Check(value
)) {
1602 PyErr_Format(PyExc_TypeError
,
1603 "must assign array (not \"%.200s\") to slice",
1604 value
->ob_type
->tp_name
);
1608 av
= (arrayobject
*)value
;
1610 if (av
->ob_size
!= slicelength
) {
1611 PyErr_Format(PyExc_ValueError
,
1612 "attempt to assign array of size %d to extended slice of size %d",
1613 av
->ob_size
, slicelength
);
1620 /* protect against a[::-1] = a */
1622 value
= array_slice(av
, 0, av
->ob_size
);
1623 av
= (arrayobject
*)value
;
1629 for (cur
= start
, i
= 0; i
< slicelength
;
1631 memcpy(self
->ob_item
+ cur
*itemsize
,
1632 av
->ob_item
+ i
*itemsize
,
1642 PyErr_SetString(PyExc_TypeError
,
1643 "list indices must be integers");
1648 static PyMappingMethods array_as_mapping
= {
1649 (inquiry
)array_length
,
1650 (binaryfunc
)array_subscr
,
1651 (objobjargproc
)array_ass_subscr
1655 array_buffer_getreadbuf(arrayobject
*self
, int index
, const void **ptr
)
1658 PyErr_SetString(PyExc_SystemError
,
1659 "Accessing non-existent array segment");
1662 *ptr
= (void *)self
->ob_item
;
1663 return self
->ob_size
*self
->ob_descr
->itemsize
;
1667 array_buffer_getwritebuf(arrayobject
*self
, int index
, const void **ptr
)
1670 PyErr_SetString(PyExc_SystemError
,
1671 "Accessing non-existent array segment");
1674 *ptr
= (void *)self
->ob_item
;
1675 return self
->ob_size
*self
->ob_descr
->itemsize
;
1679 array_buffer_getsegcount(arrayobject
*self
, int *lenp
)
1682 *lenp
= self
->ob_size
*self
->ob_descr
->itemsize
;
1686 static PySequenceMethods array_as_sequence
= {
1687 (inquiry
)array_length
, /*sq_length*/
1688 (binaryfunc
)array_concat
, /*sq_concat*/
1689 (intargfunc
)array_repeat
, /*sq_repeat*/
1690 (intargfunc
)array_item
, /*sq_item*/
1691 (intintargfunc
)array_slice
, /*sq_slice*/
1692 (intobjargproc
)array_ass_item
, /*sq_ass_item*/
1693 (intintobjargproc
)array_ass_slice
, /*sq_ass_slice*/
1694 NULL
, /*sq_contains*/
1695 (binaryfunc
)array_inplace_concat
, /*sq_inplace_concat*/
1696 (intargfunc
)array_inplace_repeat
/*sq_inplace_repeat*/
1699 static PyBufferProcs array_as_buffer
= {
1700 (getreadbufferproc
)array_buffer_getreadbuf
,
1701 (getwritebufferproc
)array_buffer_getwritebuf
,
1702 (getsegcountproc
)array_buffer_getsegcount
,
1706 array_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
1709 PyObject
*initial
= NULL
;
1710 struct arraydescr
*descr
;
1713 int i
= PyObject_Length(kwds
);
1717 PyErr_SetString(PyExc_TypeError
,
1718 "array.array constructor takes "
1719 "no keyword arguments");
1724 if (!PyArg_ParseTuple(args
, "c|O:array", &c
, &initial
))
1727 if (!(initial
== NULL
|| PyList_Check(initial
)
1728 || PyString_Check(initial
)
1729 || (c
== 'u' && PyUnicode_Check(initial
)))) {
1730 PyErr_SetString(PyExc_TypeError
,
1731 "array initializer must be list or string");
1734 for (descr
= descriptors
; descr
->typecode
!= '\0'; descr
++) {
1735 if (descr
->typecode
== c
) {
1738 if (initial
== NULL
|| !PyList_Check(initial
))
1741 len
= PyList_Size(initial
);
1743 a
= newarrayobject(type
, len
, descr
);
1749 for (i
= 0; i
< len
; i
++) {
1751 PyList_GetItem(initial
, i
);
1752 if (setarrayitem(a
, i
, v
) != 0) {
1758 if (initial
!= NULL
&& PyString_Check(initial
)) {
1759 PyObject
*t_initial
= Py_BuildValue("(O)",
1762 array_fromstring((arrayobject
*)a
,
1764 Py_DECREF(t_initial
);
1770 #ifdef Py_USING_UNICODE
1771 } else if (initial
!= NULL
&& PyUnicode_Check(initial
)) {
1772 int n
= PyUnicode_GET_DATA_SIZE(initial
);
1774 arrayobject
*self
= (arrayobject
*)a
;
1775 char *item
= self
->ob_item
;
1776 item
= PyMem_Realloc(item
, n
);
1782 self
->ob_item
= item
;
1783 self
->ob_size
= n
/ sizeof(Py_UNICODE
);
1784 memcpy(item
, PyUnicode_AS_DATA(initial
), n
);
1791 PyErr_SetString(PyExc_ValueError
,
1792 "bad typecode (must be c, b, B, u, h, H, i, I, l, L, f or d)");
1797 PyDoc_STRVAR(module_doc
,
1798 "This module defines an object type which can efficiently represent\n\
1799 an array of basic values: characters, integers, floating point\n\
1800 numbers. Arrays are sequence types and behave very much like lists,\n\
1801 except that the type of objects stored in them is constrained. The\n\
1802 type is specified at object creation time by using a type code, which\n\
1803 is a single character. The following type codes are defined:\n\
1805 Type code C Type Minimum size in bytes \n\
1807 'b' signed integer 1 \n\
1808 'B' unsigned integer 1 \n\
1809 'u' Unicode character 2 \n\
1810 'h' signed integer 2 \n\
1811 'H' unsigned integer 2 \n\
1812 'i' signed integer 2 \n\
1813 'I' unsigned integer 2 \n\
1814 'l' signed integer 4 \n\
1815 'L' unsigned integer 4 \n\
1816 'f' floating point 4 \n\
1817 'd' floating point 8 \n\
1819 The constructor is:\n\
1821 array(typecode [, initializer]) -- create a new array\n\
1824 PyDoc_STRVAR(arraytype_doc
,
1825 "array(typecode [, initializer]) -> array\n\
1827 Return a new array whose items are restricted by typecode, and\n\
1828 initialized from the optional initializer value, which must be a list\n\
1831 Arrays represent basic values and behave very much like lists, except\n\
1832 the type of objects stored in them is constrained.\n\
1836 append() -- append a new item to the end of the array\n\
1837 buffer_info() -- return information giving the current memory info\n\
1838 byteswap() -- byteswap all the items of the array\n\
1839 count() -- return number of occurences of an object\n\
1840 extend() -- extend array by appending array elements\n\
1841 fromfile() -- read items from a file object\n\
1842 fromlist() -- append items from the list\n\
1843 fromstring() -- append items from the string\n\
1844 index() -- return index of first occurence of an object\n\
1845 insert() -- insert a new item into the array at a provided position\n\
1846 pop() -- remove and return item (default last)\n\
1847 read() -- DEPRECATED, use fromfile()\n\
1848 remove() -- remove first occurence of an object\n\
1849 reverse() -- reverse the order of the items in the array\n\
1850 tofile() -- write all items to a file object\n\
1851 tolist() -- return the array converted to an ordinary list\n\
1852 tostring() -- return the array converted to a string\n\
1853 write() -- DEPRECATED, use tofile()\n\
1857 typecode -- the typecode character used to create the array\n\
1858 itemsize -- the length in bytes of one array item\n\
1861 statichere PyTypeObject Arraytype
= {
1862 PyObject_HEAD_INIT(NULL
)
1865 sizeof(arrayobject
),
1867 (destructor
)array_dealloc
, /* tp_dealloc */
1872 (reprfunc
)array_repr
, /* tp_repr */
1873 0, /* tp_as _number*/
1874 &array_as_sequence
, /* tp_as _sequence*/
1875 &array_as_mapping
, /* tp_as _mapping*/
1879 DELAYED(PyObject_GenericGetAttr
), /* tp_getattro */
1880 0, /* tp_setattro */
1881 &array_as_buffer
, /* tp_as_buffer*/
1882 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
, /* tp_flags */
1883 arraytype_doc
, /* tp_doc */
1884 0, /* tp_traverse */
1886 array_richcompare
, /* tp_richcompare */
1887 0, /* tp_weaklistoffset */
1889 0, /* tp_iternext */
1890 array_methods
, /* tp_methods */
1892 array_getsets
, /* tp_getset */
1895 0, /* tp_descr_get */
1896 0, /* tp_descr_set */
1897 0, /* tp_dictoffset */
1899 DELAYED(PyType_GenericAlloc
), /* tp_alloc */
1900 array_new
, /* tp_new */
1901 DELAYED(PyObject_Del
), /* tp_free */
1904 /* No functions in array module. */
1905 static PyMethodDef a_methods
[] = {
1906 {NULL
, NULL
, 0, NULL
} /* Sentinel */
1915 Arraytype
.ob_type
= &PyType_Type
;
1916 Arraytype
.tp_getattro
= PyObject_GenericGetAttr
;
1917 Arraytype
.tp_alloc
= PyType_GenericAlloc
;
1918 Arraytype
.tp_free
= PyObject_Del
;
1919 m
= Py_InitModule3("array", a_methods
, module_doc
);
1921 Py_INCREF((PyObject
*)&Arraytype
);
1922 PyModule_AddObject(m
, "ArrayType", (PyObject
*)&Arraytype
);
1923 Py_INCREF((PyObject
*)&Arraytype
);
1924 PyModule_AddObject(m
, "array", (PyObject
*)&Arraytype
);
1925 /* No need to check the error here, the caller will do that */