1 /* List object implementation */
8 #include <sys/types.h> /* For size_t */
14 unsigned int nbits
= 0;
15 unsigned int n2
= (unsigned int)n
>> 5;
18 * If n < 256, to a multiple of 8.
19 * If n < 2048, to a multiple of 64.
20 * If n < 16384, to a multiple of 512.
21 * If n < 131072, to a multiple of 4096.
22 * If n < 1048576, to a multiple of 32768.
23 * If n < 8388608, to a multiple of 262144.
24 * If n < 67108864, to a multiple of 2097152.
25 * If n < 536870912, to a multiple of 16777216.
27 * If n < 2**(5+3*i), to a multiple of 2**(3*i).
29 * This over-allocates proportional to the list size, making room
30 * for additional growth. The over-allocation is mild, but is
31 * enough to give linear-time amortized behavior over a long
32 * sequence of appends() in the presence of a poorly-performing
33 * system realloc() (which is a reality, e.g., across all flavors
34 * of Windows, with Win9x behavior being particularly bad -- and
35 * we've still got address space fragmentation problems on Win9x
36 * even with this scheme, although it requires much longer lists to
37 * provoke them than it used to).
43 return ((n
>> nbits
) + 1) << nbits
;
46 #define NRESIZE(var, type, nitems) \
48 size_t _new_size = roundupsize(nitems); \
49 if (_new_size <= ((~(size_t)0) / sizeof(type))) \
50 PyMem_RESIZE(var, type, _new_size); \
61 PyErr_BadInternalCall();
64 nbytes
= size
* sizeof(PyObject
*);
65 /* Check for overflow */
66 if (nbytes
/ sizeof(PyObject
*) != (size_t)size
) {
67 return PyErr_NoMemory();
69 op
= PyObject_GC_New(PyListObject
, &PyList_Type
);
77 op
->ob_item
= (PyObject
**) PyMem_MALLOC(nbytes
);
78 if (op
->ob_item
== NULL
) {
79 return PyErr_NoMemory();
81 memset(op
->ob_item
, 0, sizeof(*op
->ob_item
) * size
);
84 _PyObject_GC_TRACK(op
);
85 return (PyObject
*) op
;
89 PyList_Size(PyObject
*op
)
91 if (!PyList_Check(op
)) {
92 PyErr_BadInternalCall();
96 return ((PyListObject
*)op
) -> ob_size
;
99 static PyObject
*indexerr
;
102 PyList_GetItem(PyObject
*op
, int i
)
104 if (!PyList_Check(op
)) {
105 PyErr_BadInternalCall();
108 if (i
< 0 || i
>= ((PyListObject
*)op
) -> ob_size
) {
109 if (indexerr
== NULL
)
110 indexerr
= PyString_FromString(
111 "list index out of range");
112 PyErr_SetObject(PyExc_IndexError
, indexerr
);
115 return ((PyListObject
*)op
) -> ob_item
[i
];
119 PyList_SetItem(register PyObject
*op
, register int i
,
120 register PyObject
*newitem
)
122 register PyObject
*olditem
;
123 register PyObject
**p
;
124 if (!PyList_Check(op
)) {
126 PyErr_BadInternalCall();
129 if (i
< 0 || i
>= ((PyListObject
*)op
) -> ob_size
) {
131 PyErr_SetString(PyExc_IndexError
,
132 "list assignment index out of range");
135 p
= ((PyListObject
*)op
) -> ob_item
+ i
;
143 ins1(PyListObject
*self
, int where
, PyObject
*v
)
148 PyErr_BadInternalCall();
151 if (self
->ob_size
== INT_MAX
) {
152 PyErr_SetString(PyExc_OverflowError
,
153 "cannot add more objects to list");
156 items
= self
->ob_item
;
157 NRESIZE(items
, PyObject
*, self
->ob_size
+1);
163 where
+= self
->ob_size
;
167 if (where
> self
->ob_size
)
168 where
= self
->ob_size
;
169 for (i
= self
->ob_size
; --i
>= where
; )
170 items
[i
+1] = items
[i
];
173 self
->ob_item
= items
;
179 PyList_Insert(PyObject
*op
, int where
, PyObject
*newitem
)
181 if (!PyList_Check(op
)) {
182 PyErr_BadInternalCall();
185 return ins1((PyListObject
*)op
, where
, newitem
);
189 PyList_Append(PyObject
*op
, PyObject
*newitem
)
191 if (!PyList_Check(op
)) {
192 PyErr_BadInternalCall();
195 return ins1((PyListObject
*)op
,
196 (int) ((PyListObject
*)op
)->ob_size
, newitem
);
202 list_dealloc(PyListObject
*op
)
205 PyObject_GC_UnTrack(op
);
206 Py_TRASHCAN_SAFE_BEGIN(op
)
207 if (op
->ob_item
!= NULL
) {
208 /* Do it backwards, for Christian Tismer.
209 There's a simple test case where somehow this reduces
210 thrashing when a *very* large list is created and
211 immediately deleted. */
214 Py_XDECREF(op
->ob_item
[i
]);
216 PyMem_FREE(op
->ob_item
);
218 op
->ob_type
->tp_free((PyObject
*)op
);
219 Py_TRASHCAN_SAFE_END(op
)
223 list_print(PyListObject
*op
, FILE *fp
, int flags
)
227 i
= Py_ReprEnter((PyObject
*)op
);
231 fprintf(fp
, "[...]");
235 for (i
= 0; i
< op
->ob_size
; i
++) {
238 if (PyObject_Print(op
->ob_item
[i
], fp
, 0) != 0) {
239 Py_ReprLeave((PyObject
*)op
);
244 Py_ReprLeave((PyObject
*)op
);
249 list_repr(PyListObject
*v
)
253 PyObject
*pieces
= NULL
, *result
= NULL
;
255 i
= Py_ReprEnter((PyObject
*)v
);
257 return i
> 0 ? PyString_FromString("[...]") : NULL
;
260 if (v
->ob_size
== 0) {
261 result
= PyString_FromString("[]");
265 pieces
= PyList_New(0);
269 /* Do repr() on each element. Note that this may mutate the list,
270 so must refetch the list size on each iteration. */
271 for (i
= 0; i
< v
->ob_size
; ++i
) {
273 s
= PyObject_Repr(v
->ob_item
[i
]);
276 status
= PyList_Append(pieces
, s
);
277 Py_DECREF(s
); /* append created a new ref */
282 /* Add "[]" decorations to the first and last items. */
283 assert(PyList_GET_SIZE(pieces
) > 0);
284 s
= PyString_FromString("[");
287 temp
= PyList_GET_ITEM(pieces
, 0);
288 PyString_ConcatAndDel(&s
, temp
);
289 PyList_SET_ITEM(pieces
, 0, s
);
293 s
= PyString_FromString("]");
296 temp
= PyList_GET_ITEM(pieces
, PyList_GET_SIZE(pieces
) - 1);
297 PyString_ConcatAndDel(&temp
, s
);
298 PyList_SET_ITEM(pieces
, PyList_GET_SIZE(pieces
) - 1, temp
);
302 /* Paste them all together with ", " between. */
303 s
= PyString_FromString(", ");
306 result
= _PyString_Join(s
, pieces
);
311 Py_ReprLeave((PyObject
*)v
);
316 list_length(PyListObject
*a
)
324 list_contains(PyListObject
*a
, PyObject
*el
)
328 for (i
= 0, cmp
= 0 ; cmp
== 0 && i
< a
->ob_size
; ++i
)
329 cmp
= PyObject_RichCompareBool(el
, PyList_GET_ITEM(a
, i
),
336 list_item(PyListObject
*a
, int i
)
338 if (i
< 0 || i
>= a
->ob_size
) {
339 if (indexerr
== NULL
)
340 indexerr
= PyString_FromString(
341 "list index out of range");
342 PyErr_SetObject(PyExc_IndexError
, indexerr
);
345 Py_INCREF(a
->ob_item
[i
]);
346 return a
->ob_item
[i
];
350 list_slice(PyListObject
*a
, int ilow
, int ihigh
)
356 else if (ilow
> a
->ob_size
)
360 else if (ihigh
> a
->ob_size
)
362 np
= (PyListObject
*) PyList_New(ihigh
- ilow
);
365 for (i
= ilow
; i
< ihigh
; i
++) {
366 PyObject
*v
= a
->ob_item
[i
];
368 np
->ob_item
[i
- ilow
] = v
;
370 return (PyObject
*)np
;
374 PyList_GetSlice(PyObject
*a
, int ilow
, int ihigh
)
376 if (!PyList_Check(a
)) {
377 PyErr_BadInternalCall();
380 return list_slice((PyListObject
*)a
, ilow
, ihigh
);
384 list_concat(PyListObject
*a
, PyObject
*bb
)
389 if (!PyList_Check(bb
)) {
390 PyErr_Format(PyExc_TypeError
,
391 "can only concatenate list (not \"%.200s\") to list",
392 bb
->ob_type
->tp_name
);
395 #define b ((PyListObject *)bb)
396 size
= a
->ob_size
+ b
->ob_size
;
398 return PyErr_NoMemory();
399 np
= (PyListObject
*) PyList_New(size
);
403 for (i
= 0; i
< a
->ob_size
; i
++) {
404 PyObject
*v
= a
->ob_item
[i
];
408 for (i
= 0; i
< b
->ob_size
; i
++) {
409 PyObject
*v
= b
->ob_item
[i
];
411 np
->ob_item
[i
+ a
->ob_size
] = v
;
413 return (PyObject
*)np
;
418 list_repeat(PyListObject
*a
, int n
)
427 size
= a
->ob_size
* n
;
429 return PyList_New(0);
430 if (n
&& size
/n
!= a
->ob_size
)
431 return PyErr_NoMemory();
432 np
= (PyListObject
*) PyList_New(size
);
436 if (a
->ob_size
== 1) {
437 elem
= a
->ob_item
[0];
438 for (i
= 0; i
< n
; i
++) {
439 np
->ob_item
[i
] = elem
;
442 return (PyObject
*) np
;
445 for (i
= 0; i
< n
; i
++) {
446 for (j
= 0; j
< a
->ob_size
; j
++) {
452 return (PyObject
*) np
;
456 list_ass_slice(PyListObject
*a
, int ilow
, int ihigh
, PyObject
*v
)
458 /* Because [X]DECREF can recursively invoke list operations on
459 this list, we must postpone all [X]DECREF activity until
460 after the list is back in its canonical shape. Therefore
461 we must allocate an additional array, 'recycle', into which
462 we temporarily copy the items that are deleted from the
464 PyObject
**recycle
, **p
;
466 PyObject
*v_as_SF
= NULL
; /* PySequence_Fast(v) */
467 int n
; /* Size of replacement list */
468 int d
; /* Change in size */
469 int k
; /* Loop index */
470 #define b ((PyListObject *)v)
476 /* Special case "a[i:j] = a" -- copy b first */
478 v
= list_slice(b
, 0, b
->ob_size
);
481 ret
= list_ass_slice(a
, ilow
, ihigh
, v
);
486 PyOS_snprintf(msg
, sizeof(msg
),
487 "must assign sequence"
488 " (not \"%.200s\") to slice",
489 v
->ob_type
->tp_name
);
490 v_as_SF
= PySequence_Fast(v
, msg
);
493 n
= PySequence_Fast_GET_SIZE(v_as_SF
);
497 else if (ilow
> a
->ob_size
)
501 else if (ihigh
> a
->ob_size
)
504 d
= n
- (ihigh
-ilow
);
506 p
= recycle
= PyMem_NEW(PyObject
*, (ihigh
-ilow
));
507 if (recycle
== NULL
) {
514 if (d
<= 0) { /* Delete -d items; recycle ihigh-ilow items */
515 for (k
= ilow
; k
< ihigh
; k
++)
518 for (/*k = ihigh*/; k
< a
->ob_size
; k
++)
521 NRESIZE(item
, PyObject
*, a
->ob_size
); /* Can't fail */
525 else { /* Insert d items; recycle ihigh-ilow items */
526 NRESIZE(item
, PyObject
*, a
->ob_size
+ d
);
533 for (k
= a
->ob_size
; --k
>= ihigh
; )
535 for (/*k = ihigh-1*/; k
>= ilow
; --k
)
540 for (k
= 0; k
< n
; k
++, ilow
++) {
541 PyObject
*w
= PySequence_Fast_GET_ITEM(v_as_SF
, k
);
546 while (--p
>= recycle
)
550 if (a
->ob_size
== 0 && a
->ob_item
!= NULL
) {
551 PyMem_FREE(a
->ob_item
);
560 PyList_SetSlice(PyObject
*a
, int ilow
, int ihigh
, PyObject
*v
)
562 if (!PyList_Check(a
)) {
563 PyErr_BadInternalCall();
566 return list_ass_slice((PyListObject
*)a
, ilow
, ihigh
, v
);
570 list_inplace_repeat(PyListObject
*self
, int n
)
576 size
= PyList_GET_SIZE(self
);
579 return (PyObject
*)self
;
582 items
= self
->ob_item
;
585 self
->ob_item
= NULL
;
587 for (i
= 0; i
< size
; i
++)
588 Py_XDECREF(items
[i
]);
591 return (PyObject
*)self
;
594 NRESIZE(items
, PyObject
*, size
*n
);
599 self
->ob_item
= items
;
600 for (i
= 1; i
< n
; i
++) { /* Start counting at 1, not 0 */
601 for (j
= 0; j
< size
; j
++) {
602 PyObject
*o
= PyList_GET_ITEM(self
, j
);
604 PyList_SET_ITEM(self
, self
->ob_size
++, o
);
608 return (PyObject
*)self
;
614 list_ass_item(PyListObject
*a
, int i
, PyObject
*v
)
617 if (i
< 0 || i
>= a
->ob_size
) {
618 PyErr_SetString(PyExc_IndexError
,
619 "list assignment index out of range");
623 return list_ass_slice(a
, i
, i
+1, v
);
625 old_value
= a
->ob_item
[i
];
627 Py_DECREF(old_value
);
632 ins(PyListObject
*self
, int where
, PyObject
*v
)
634 if (ins1(self
, where
, v
) != 0)
641 listinsert(PyListObject
*self
, PyObject
*args
)
645 if (!PyArg_ParseTuple(args
, "iO:insert", &i
, &v
))
647 return ins(self
, i
, v
);
651 listappend(PyListObject
*self
, PyObject
*v
)
653 return ins(self
, (int) self
->ob_size
, v
);
657 listextend_internal(PyListObject
*self
, PyObject
*b
)
660 int selflen
= PyList_GET_SIZE(self
);
664 if (PyObject_Size(b
) == 0) {
665 /* short circuit when b is empty */
670 if (self
== (PyListObject
*)b
) {
671 /* as in list_ass_slice() we must special case the
672 * situation: a.extend(a)
674 * XXX: I think this way ought to be faster than using
675 * list_slice() the way list_ass_slice() does.
678 b
= PyList_New(selflen
);
681 for (i
= 0; i
< selflen
; i
++) {
682 PyObject
*o
= PyList_GET_ITEM(self
, i
);
684 PyList_SET_ITEM(b
, i
, o
);
688 blen
= PyObject_Size(b
);
690 /* resize a using idiom */
691 items
= self
->ob_item
;
692 NRESIZE(items
, PyObject
*, selflen
+ blen
);
699 self
->ob_item
= items
;
701 /* populate the end of self with b's items */
702 for (i
= 0; i
< blen
; i
++) {
703 PyObject
*o
= PySequence_Fast_GET_ITEM(b
, i
);
705 PyList_SET_ITEM(self
, self
->ob_size
++, o
);
713 list_inplace_concat(PyListObject
*self
, PyObject
*other
)
715 other
= PySequence_Fast(other
, "argument to += must be iterable");
719 if (listextend_internal(self
, other
) < 0)
723 return (PyObject
*)self
;
727 listextend(PyListObject
*self
, PyObject
*b
)
730 b
= PySequence_Fast(b
, "list.extend() argument must be iterable");
734 if (listextend_internal(self
, b
) < 0)
742 listpop(PyListObject
*self
, PyObject
*args
)
746 if (!PyArg_ParseTuple(args
, "|i:pop", &i
))
748 if (self
->ob_size
== 0) {
749 /* Special-case most common failure cause */
750 PyErr_SetString(PyExc_IndexError
, "pop from empty list");
755 if (i
< 0 || i
>= self
->ob_size
) {
756 PyErr_SetString(PyExc_IndexError
, "pop index out of range");
759 v
= self
->ob_item
[i
];
761 if (list_ass_slice(self
, i
, i
+1, (PyObject
*)NULL
) != 0) {
768 /* Reverse a slice of a list in place, from lo up to (exclusive) hi. */
770 reverse_slice(PyObject
**lo
, PyObject
**hi
)
784 /* Lots of code for an adaptive, stable, natural mergesort. There are many
785 * pieces to this algorithm; read listsort.txt for overviews and details.
788 /* Comparison function. Takes care of calling a user-supplied
789 * comparison function (any callable Python object), which must not be
790 * NULL (use the ISLT macro if you don't know, or call PyObject_RichCompareBool
791 * with Py_LT if you know it's NULL).
792 * Returns -1 on error, 1 if x < y, 0 if x >= y.
795 islt(PyObject
*x
, PyObject
*y
, PyObject
*compare
)
801 assert(compare
!= NULL
);
802 /* Call the user's comparison function and translate the 3-way
803 * result into true or false (or error).
805 args
= PyTuple_New(2);
810 PyTuple_SET_ITEM(args
, 0, x
);
811 PyTuple_SET_ITEM(args
, 1, y
);
812 res
= PyObject_Call(compare
, args
, NULL
);
816 if (!PyInt_Check(res
)) {
818 PyErr_SetString(PyExc_TypeError
,
819 "comparison function must return int");
822 i
= PyInt_AsLong(res
);
827 /* If COMPARE is NULL, calls PyObject_RichCompareBool with Py_LT, else calls
828 * islt. This avoids a layer of function call in the usual case, and
829 * sorting does many comparisons.
830 * Returns -1 on error, 1 if x < y, 0 if x >= y.
832 #define ISLT(X, Y, COMPARE) ((COMPARE) == NULL ? \
833 PyObject_RichCompareBool(X, Y, Py_LT) : \
836 /* Compare X to Y via "<". Goto "fail" if the comparison raises an
837 error. Else "k" is set to true iff X<Y, and an "if (k)" block is
838 started. It makes more sense in context <wink>. X and Y are PyObject*s.
840 #define IFLT(X, Y) if ((k = ISLT(X, Y, compare)) < 0) goto fail; \
843 /* binarysort is the best method for sorting small arrays: it does
844 few compares, but can do data movement quadratic in the number of
846 [lo, hi) is a contiguous slice of a list, and is sorted via
847 binary insertion. This sort is stable.
848 On entry, must have lo <= start <= hi, and that [lo, start) is already
849 sorted (pass start == lo if you don't know!).
850 If islt() complains return -1, else 0.
851 Even in case of error, the output slice will be some permutation of
852 the input (nothing is lost or duplicated).
855 binarysort(PyObject
**lo
, PyObject
**hi
, PyObject
**start
, PyObject
*compare
)
856 /* compare -- comparison function object, or NULL for default */
859 register PyObject
**l
, **p
, **r
;
860 register PyObject
*pivot
;
862 assert(lo
<= start
&& start
<= hi
);
863 /* assert [lo, start) is sorted */
866 for (; start
< hi
; ++start
) {
867 /* set l to where *start belongs */
872 * pivot >= all in [lo, l).
873 * pivot < all in [r, start).
874 * The second is vacuously true at the start.
878 p
= l
+ ((r
- l
) >> 1);
885 /* The invariants still hold, so pivot >= all in [lo, l) and
886 pivot < all in [l, start), so pivot belongs at l. Note
887 that if there are elements equal to pivot, l points to the
888 first slot after them -- that's why this sort is stable.
889 Slide over to make room.
890 Caution: using memmove is much slower under MSVC 5;
891 we're not usually moving many slots. */
892 for (p
= start
; p
> l
; --p
)
903 Return the length of the run beginning at lo, in the slice [lo, hi). lo < hi
904 is required on entry. "A run" is the longest ascending sequence, with
906 lo[0] <= lo[1] <= lo[2] <= ...
908 or the longest descending sequence, with
910 lo[0] > lo[1] > lo[2] > ...
912 Boolean *descending is set to 0 in the former case, or to 1 in the latter.
913 For its intended use in a stable mergesort, the strictness of the defn of
914 "descending" is needed so that the caller can safely reverse a descending
915 sequence without violating stability (strict > ensures there are no equal
916 elements to get out of order).
918 Returns -1 in case of error.
921 count_run(PyObject
**lo
, PyObject
**hi
, PyObject
*compare
, int *descending
)
935 for (lo
= lo
+1; lo
< hi
; ++lo
, ++n
) {
943 for (lo
= lo
+1; lo
< hi
; ++lo
, ++n
) {
955 Locate the proper position of key in a sorted vector; if the vector contains
956 an element equal to key, return the position immediately to the left of
957 the leftmost equal element. [gallop_right() does the same except returns
958 the position to the right of the rightmost equal element (if any).]
960 "a" is a sorted vector with n elements, starting at a[0]. n must be > 0.
962 "hint" is an index at which to begin the search, 0 <= hint < n. The closer
963 hint is to the final result, the faster this runs.
965 The return value is the int k in 0..n such that
969 pretending that *(a-1) is minus infinity and a[n] is plus infinity. IOW,
970 key belongs at index k; or, IOW, the first k elements of a should precede
971 key, and the last n-k should follow key.
973 Returns -1 on error. See listsort.txt for info on the method.
976 gallop_left(PyObject
*key
, PyObject
**a
, int n
, int hint
, PyObject
*compare
)
982 assert(key
&& a
&& n
> 0 && hint
>= 0 && hint
< n
);
988 /* a[hint] < key -- gallop right, until
989 * a[hint + lastofs] < key <= a[hint + ofs]
991 const int maxofs
= n
- hint
; /* &a[n-1] is highest */
992 while (ofs
< maxofs
) {
995 ofs
= (ofs
<< 1) + 1;
996 if (ofs
<= 0) /* int overflow */
999 else /* key <= a[hint + ofs] */
1004 /* Translate back to offsets relative to &a[0]. */
1009 /* key <= a[hint] -- gallop left, until
1010 * a[hint - ofs] < key <= a[hint - lastofs]
1012 const int maxofs
= hint
+ 1; /* &a[0] is lowest */
1013 while (ofs
< maxofs
) {
1016 /* key <= a[hint - ofs] */
1018 ofs
= (ofs
<< 1) + 1;
1019 if (ofs
<= 0) /* int overflow */
1024 /* Translate back to positive offsets relative to &a[0]. */
1026 lastofs
= hint
- ofs
;
1031 assert(-1 <= lastofs
&& lastofs
< ofs
&& ofs
<= n
);
1032 /* Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the
1033 * right of lastofs but no farther right than ofs. Do a binary
1034 * search, with invariant a[lastofs-1] < key <= a[ofs].
1037 while (lastofs
< ofs
) {
1038 int m
= lastofs
+ ((ofs
- lastofs
) >> 1);
1041 lastofs
= m
+1; /* a[m] < key */
1043 ofs
= m
; /* key <= a[m] */
1045 assert(lastofs
== ofs
); /* so a[ofs-1] < key <= a[ofs] */
1053 Exactly like gallop_left(), except that if key already exists in a[0:n],
1054 finds the position immediately to the right of the rightmost equal value.
1056 The return value is the int k in 0..n such that
1058 a[k-1] <= key < a[k]
1062 The code duplication is massive, but this is enough different given that
1063 we're sticking to "<" comparisons that it's much harder to follow if
1064 written as one routine with yet another "left or right?" flag.
1067 gallop_right(PyObject
*key
, PyObject
**a
, int n
, int hint
, PyObject
*compare
)
1073 assert(key
&& a
&& n
> 0 && hint
>= 0 && hint
< n
);
1079 /* key < a[hint] -- gallop left, until
1080 * a[hint - ofs] <= key < a[hint - lastofs]
1082 const int maxofs
= hint
+ 1; /* &a[0] is lowest */
1083 while (ofs
< maxofs
) {
1084 IFLT(key
, *(a
-ofs
)) {
1086 ofs
= (ofs
<< 1) + 1;
1087 if (ofs
<= 0) /* int overflow */
1090 else /* a[hint - ofs] <= key */
1095 /* Translate back to positive offsets relative to &a[0]. */
1097 lastofs
= hint
- ofs
;
1101 /* a[hint] <= key -- gallop right, until
1102 * a[hint + lastofs] <= key < a[hint + ofs]
1104 const int maxofs
= n
- hint
; /* &a[n-1] is highest */
1105 while (ofs
< maxofs
) {
1108 /* a[hint + ofs] <= key */
1110 ofs
= (ofs
<< 1) + 1;
1111 if (ofs
<= 0) /* int overflow */
1116 /* Translate back to offsets relative to &a[0]. */
1122 assert(-1 <= lastofs
&& lastofs
< ofs
&& ofs
<= n
);
1123 /* Now a[lastofs] <= key < a[ofs], so key belongs somewhere to the
1124 * right of lastofs but no farther right than ofs. Do a binary
1125 * search, with invariant a[lastofs-1] <= key < a[ofs].
1128 while (lastofs
< ofs
) {
1129 int m
= lastofs
+ ((ofs
- lastofs
) >> 1);
1132 ofs
= m
; /* key < a[m] */
1134 lastofs
= m
+1; /* a[m] <= key */
1136 assert(lastofs
== ofs
); /* so a[ofs-1] <= key < a[ofs] */
1143 /* The maximum number of entries in a MergeState's pending-runs stack.
1144 * This is enough to sort arrays of size up to about
1145 * 32 * phi ** MAX_MERGE_PENDING
1146 * where phi ~= 1.618. 85 is ridiculouslylarge enough, good for an array
1147 * with 2**64 elements.
1149 #define MAX_MERGE_PENDING 85
1151 /* When we get into galloping mode, we stay there until both runs win less
1152 * often than MIN_GALLOP consecutive times. See listsort.txt for more info.
1154 #define MIN_GALLOP 7
1156 /* Avoid malloc for small temp arrays. */
1157 #define MERGESTATE_TEMP_SIZE 256
1159 /* One MergeState exists on the stack per invocation of mergesort. It's just
1160 * a convenient way to pass state around among the helper functions.
1167 typedef struct s_MergeState
{
1168 /* The user-supplied comparison function. or NULL if none given. */
1171 /* This controls when we get *into* galloping mode. It's initialized
1172 * to MIN_GALLOP. merge_lo and merge_hi tend to nudge it higher for
1173 * random data, and lower for highly structured data.
1177 /* 'a' is temp storage to help with merges. It contains room for
1180 PyObject
**a
; /* may point to temparray below */
1183 /* A stack of n pending runs yet to be merged. Run #i starts at
1184 * address base[i] and extends for len[i] elements. It's always
1185 * true (so long as the indices are in bounds) that
1187 * pending[i].base + pending[i].len == pending[i+1].base
1189 * so we could cut the storage for this, but it's a minor amount,
1190 * and keeping all the info explicit simplifies the code.
1193 struct s_slice pending
[MAX_MERGE_PENDING
];
1195 /* 'a' points to this when possible, rather than muck with malloc. */
1196 PyObject
*temparray
[MERGESTATE_TEMP_SIZE
];
1199 /* Conceptually a MergeState's constructor. */
1201 merge_init(MergeState
*ms
, PyObject
*compare
)
1204 ms
->compare
= compare
;
1205 ms
->a
= ms
->temparray
;
1206 ms
->alloced
= MERGESTATE_TEMP_SIZE
;
1208 ms
->min_gallop
= MIN_GALLOP
;
1211 /* Free all the temp memory owned by the MergeState. This must be called
1212 * when you're done with a MergeState, and may be called before then if
1213 * you want to free the temp memory early.
1216 merge_freemem(MergeState
*ms
)
1219 if (ms
->a
!= ms
->temparray
)
1221 ms
->a
= ms
->temparray
;
1222 ms
->alloced
= MERGESTATE_TEMP_SIZE
;
1225 /* Ensure enough temp memory for 'need' array slots is available.
1226 * Returns 0 on success and -1 if the memory can't be gotten.
1229 merge_getmem(MergeState
*ms
, int need
)
1232 if (need
<= ms
->alloced
)
1234 /* Don't realloc! That can cost cycles to copy the old data, but
1235 * we don't care what's in the block.
1238 ms
->a
= (PyObject
**)PyMem_Malloc(need
* sizeof(PyObject
*));
1244 merge_freemem(ms
); /* reset to sane state */
1247 #define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 : \
1248 merge_getmem(MS, NEED))
1250 /* Merge the na elements starting at pa with the nb elements starting at pb
1251 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1252 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1253 * merge, and should have na <= nb. See listsort.txt for more info.
1254 * Return 0 if successful, -1 if error.
1257 merge_lo(MergeState
*ms
, PyObject
**pa
, int na
, PyObject
**pb
, int nb
)
1262 int result
= -1; /* guilty until proved innocent */
1263 int min_gallop
= ms
->min_gallop
;
1265 assert(ms
&& pa
&& pb
&& na
> 0 && nb
> 0 && pa
+ na
== pb
);
1266 if (MERGE_GETMEM(ms
, na
) < 0)
1268 memcpy(ms
->a
, pa
, na
* sizeof(PyObject
*));
1279 compare
= ms
->compare
;
1281 int acount
= 0; /* # of times A won in a row */
1282 int bcount
= 0; /* # of times B won in a row */
1284 /* Do the straightforward thing until (if ever) one run
1285 * appears to win consistently.
1288 assert(na
> 1 && nb
> 0);
1289 k
= ISLT(*pb
, *pa
, compare
);
1299 if (bcount
>= min_gallop
)
1309 if (acount
>= min_gallop
)
1314 /* One run is winning so consistently that galloping may
1315 * be a huge win. So try that, and continue galloping until
1316 * (if ever) neither run appears to be winning consistently
1321 assert(na
> 1 && nb
> 0);
1322 min_gallop
-= min_gallop
> 1;
1323 ms
->min_gallop
= min_gallop
;
1324 k
= gallop_right(*pb
, pa
, na
, 0, compare
);
1329 memcpy(dest
, pa
, k
* sizeof(PyObject
*));
1335 /* na==0 is impossible now if the comparison
1336 * function is consistent, but we can't assume
1347 k
= gallop_left(*pa
, pb
, nb
, 0, compare
);
1352 memmove(dest
, pb
, k
* sizeof(PyObject
*));
1363 } while (acount
>= MIN_GALLOP
|| bcount
>= MIN_GALLOP
);
1364 ++min_gallop
; /* penalize it for leaving galloping mode */
1365 ms
->min_gallop
= min_gallop
;
1371 memcpy(dest
, pa
, na
* sizeof(PyObject
*));
1374 assert(na
== 1 && nb
> 0);
1375 /* The last element of pa belongs at the end of the merge. */
1376 memmove(dest
, pb
, nb
* sizeof(PyObject
*));
1381 /* Merge the na elements starting at pa with the nb elements starting at pb
1382 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1383 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1384 * merge, and should have na >= nb. See listsort.txt for more info.
1385 * Return 0 if successful, -1 if error.
1388 merge_hi(MergeState
*ms
, PyObject
**pa
, int na
, PyObject
**pb
, int nb
)
1393 int result
= -1; /* guilty until proved innocent */
1396 int min_gallop
= ms
->min_gallop
;
1398 assert(ms
&& pa
&& pb
&& na
> 0 && nb
> 0 && pa
+ na
== pb
);
1399 if (MERGE_GETMEM(ms
, nb
) < 0)
1402 memcpy(ms
->a
, pb
, nb
* sizeof(PyObject
*));
1405 pb
= ms
->a
+ nb
- 1;
1415 compare
= ms
->compare
;
1417 int acount
= 0; /* # of times A won in a row */
1418 int bcount
= 0; /* # of times B won in a row */
1420 /* Do the straightforward thing until (if ever) one run
1421 * appears to win consistently.
1424 assert(na
> 0 && nb
> 1);
1425 k
= ISLT(*pb
, *pa
, compare
);
1435 if (acount
>= min_gallop
)
1445 if (bcount
>= min_gallop
)
1450 /* One run is winning so consistently that galloping may
1451 * be a huge win. So try that, and continue galloping until
1452 * (if ever) neither run appears to be winning consistently
1457 assert(na
> 0 && nb
> 1);
1458 min_gallop
-= min_gallop
> 1;
1459 ms
->min_gallop
= min_gallop
;
1460 k
= gallop_right(*pb
, basea
, na
, na
-1, compare
);
1468 memmove(dest
+1, pa
+1, k
* sizeof(PyObject
*));
1478 k
= gallop_left(*pa
, baseb
, nb
, nb
-1, compare
);
1486 memcpy(dest
+1, pb
+1, k
* sizeof(PyObject
*));
1490 /* nb==0 is impossible now if the comparison
1491 * function is consistent, but we can't assume
1501 } while (acount
>= MIN_GALLOP
|| bcount
>= MIN_GALLOP
);
1502 ++min_gallop
; /* penalize it for leaving galloping mode */
1503 ms
->min_gallop
= min_gallop
;
1509 memcpy(dest
-(nb
-1), baseb
, nb
* sizeof(PyObject
*));
1512 assert(nb
== 1 && na
> 0);
1513 /* The first element of pb belongs at the front of the merge. */
1516 memmove(dest
+1, pa
+1, na
* sizeof(PyObject
*));
1521 /* Merge the two runs at stack indices i and i+1.
1522 * Returns 0 on success, -1 on error.
1525 merge_at(MergeState
*ms
, int i
)
1527 PyObject
**pa
, **pb
;
1535 assert(i
== ms
->n
- 2 || i
== ms
->n
- 3);
1537 pa
= ms
->pending
[i
].base
;
1538 na
= ms
->pending
[i
].len
;
1539 pb
= ms
->pending
[i
+1].base
;
1540 nb
= ms
->pending
[i
+1].len
;
1541 assert(na
> 0 && nb
> 0);
1542 assert(pa
+ na
== pb
);
1544 /* Record the length of the combined runs; if i is the 3rd-last
1545 * run now, also slide over the last run (which isn't involved
1546 * in this merge). The current run i+1 goes away in any case.
1548 ms
->pending
[i
].len
= na
+ nb
;
1550 ms
->pending
[i
+1] = ms
->pending
[i
+2];
1553 /* Where does b start in a? Elements in a before that can be
1554 * ignored (already in place).
1556 compare
= ms
->compare
;
1557 k
= gallop_right(*pb
, pa
, na
, 0, compare
);
1565 /* Where does a end in b? Elements in b after that can be
1566 * ignored (already in place).
1568 nb
= gallop_left(pa
[na
-1], pb
, nb
, nb
-1, compare
);
1572 /* Merge what remains of the runs, using a temp array with
1573 * min(na, nb) elements.
1576 return merge_lo(ms
, pa
, na
, pb
, nb
);
1578 return merge_hi(ms
, pa
, na
, pb
, nb
);
1581 /* Examine the stack of runs waiting to be merged, merging adjacent runs
1582 * until the stack invariants are re-established:
1584 * 1. len[-3] > len[-2] + len[-1]
1585 * 2. len[-2] > len[-1]
1587 * See listsort.txt for more info.
1589 * Returns 0 on success, -1 on error.
1592 merge_collapse(MergeState
*ms
)
1594 struct s_slice
*p
= ms
->pending
;
1599 if (n
> 0 && p
[n
-1].len
<= p
[n
].len
+ p
[n
+1].len
) {
1600 if (p
[n
-1].len
< p
[n
+1].len
)
1602 if (merge_at(ms
, n
) < 0)
1605 else if (p
[n
].len
<= p
[n
+1].len
) {
1606 if (merge_at(ms
, n
) < 0)
1615 /* Regardless of invariants, merge all runs on the stack until only one
1616 * remains. This is used at the end of the mergesort.
1618 * Returns 0 on success, -1 on error.
1621 merge_force_collapse(MergeState
*ms
)
1623 struct s_slice
*p
= ms
->pending
;
1628 if (n
> 0 && p
[n
-1].len
< p
[n
+1].len
)
1630 if (merge_at(ms
, n
) < 0)
1636 /* Compute a good value for the minimum run length; natural runs shorter
1637 * than this are boosted artificially via binary insertion.
1639 * If n < 64, return n (it's too small to bother with fancy stuff).
1640 * Else if n is an exact power of 2, return 32.
1641 * Else return an int k, 32 <= k <= 64, such that n/k is close to, but
1642 * strictly less than, an exact power of 2.
1644 * See listsort.txt for more info.
1647 merge_compute_minrun(int n
)
1649 int r
= 0; /* becomes 1 if any 1 bits are shifted off */
1659 /* An adaptive, stable, natural mergesort. See listsort.txt.
1660 * Returns Py_None on success, NULL on error. Even in case of error, the
1661 * list will be some permutation of its input state (nothing is lost or
1665 listsort(PyListObject
*self
, PyObject
*args
)
1668 PyObject
**lo
, **hi
;
1672 PyObject
**saved_ob_item
;
1673 PyObject
**empty_ob_item
;
1674 PyObject
*compare
= NULL
;
1675 PyObject
*result
= NULL
; /* guilty until proved innocent */
1677 assert(self
!= NULL
);
1679 if (!PyArg_UnpackTuple(args
, "sort", 0, 1, &compare
))
1682 if (compare
== Py_None
)
1685 merge_init(&ms
, compare
);
1687 /* The list is temporarily made empty, so that mutations performed
1688 * by comparison functions can't affect the slice of memory we're
1689 * sorting (allowing mutations during sorting is a core-dump
1690 * factory, since ob_item may change).
1692 saved_ob_size
= self
->ob_size
;
1693 saved_ob_item
= self
->ob_item
;
1695 self
->ob_item
= empty_ob_item
= PyMem_NEW(PyObject
*, 0);
1697 nremaining
= saved_ob_size
;
1701 /* March over the array once, left to right, finding natural runs,
1702 * and extending short natural runs to minrun elements.
1705 hi
= lo
+ nremaining
;
1706 minrun
= merge_compute_minrun(nremaining
);
1711 /* Identify next run. */
1712 n
= count_run(lo
, hi
, compare
, &descending
);
1716 reverse_slice(lo
, lo
+ n
);
1717 /* If short, extend to min(minrun, nremaining). */
1719 const int force
= nremaining
<= minrun
?
1720 nremaining
: minrun
;
1721 if (binarysort(lo
, lo
+ force
, lo
+ n
, compare
) < 0)
1725 /* Push run onto pending-runs stack, and maybe merge. */
1726 assert(ms
.n
< MAX_MERGE_PENDING
);
1727 ms
.pending
[ms
.n
].base
= lo
;
1728 ms
.pending
[ms
.n
].len
= n
;
1730 if (merge_collapse(&ms
) < 0)
1732 /* Advance to find next run. */
1735 } while (nremaining
);
1738 if (merge_force_collapse(&ms
) < 0)
1741 assert(ms
.pending
[0].base
== saved_ob_item
);
1742 assert(ms
.pending
[0].len
== saved_ob_size
);
1747 if (self
->ob_item
!= empty_ob_item
|| self
->ob_size
) {
1748 /* The user mucked with the list during the sort. */
1749 (void)list_ass_slice(self
, 0, self
->ob_size
, (PyObject
*)NULL
);
1750 if (result
!= NULL
) {
1751 PyErr_SetString(PyExc_ValueError
,
1752 "list modified during sort");
1756 if (self
->ob_item
== empty_ob_item
)
1757 PyMem_FREE(empty_ob_item
);
1758 self
->ob_size
= saved_ob_size
;
1759 self
->ob_item
= saved_ob_item
;
1768 PyList_Sort(PyObject
*v
)
1770 if (v
== NULL
|| !PyList_Check(v
)) {
1771 PyErr_BadInternalCall();
1774 v
= listsort((PyListObject
*)v
, (PyObject
*)NULL
);
1782 listreverse(PyListObject
*self
)
1784 if (self
->ob_size
> 1)
1785 reverse_slice(self
->ob_item
, self
->ob_item
+ self
->ob_size
);
1791 PyList_Reverse(PyObject
*v
)
1793 PyListObject
*self
= (PyListObject
*)v
;
1795 if (v
== NULL
|| !PyList_Check(v
)) {
1796 PyErr_BadInternalCall();
1799 if (self
->ob_size
> 1)
1800 reverse_slice(self
->ob_item
, self
->ob_item
+ self
->ob_size
);
1805 PyList_AsTuple(PyObject
*v
)
1810 if (v
== NULL
|| !PyList_Check(v
)) {
1811 PyErr_BadInternalCall();
1814 n
= ((PyListObject
*)v
)->ob_size
;
1818 p
= ((PyTupleObject
*)w
)->ob_item
;
1820 (void *)((PyListObject
*)v
)->ob_item
,
1821 n
*sizeof(PyObject
*));
1830 listindex(PyListObject
*self
, PyObject
*args
)
1832 int i
, start
=0, stop
=self
->ob_size
;
1835 if (!PyArg_ParseTuple(args
, "O|O&O&:index", &v
,
1836 _PyEval_SliceIndex
, &start
,
1837 _PyEval_SliceIndex
, &stop
))
1840 start
+= self
->ob_size
;
1845 stop
+= self
->ob_size
;
1849 else if (stop
> self
->ob_size
)
1850 stop
= self
->ob_size
;
1851 for (i
= start
; i
< stop
; i
++) {
1852 int cmp
= PyObject_RichCompareBool(self
->ob_item
[i
], v
, Py_EQ
);
1854 return PyInt_FromLong((long)i
);
1858 PyErr_SetString(PyExc_ValueError
, "list.index(x): x not in list");
1863 listcount(PyListObject
*self
, PyObject
*v
)
1868 for (i
= 0; i
< self
->ob_size
; i
++) {
1869 int cmp
= PyObject_RichCompareBool(self
->ob_item
[i
], v
, Py_EQ
);
1875 return PyInt_FromLong((long)count
);
1879 listremove(PyListObject
*self
, PyObject
*v
)
1883 for (i
= 0; i
< self
->ob_size
; i
++) {
1884 int cmp
= PyObject_RichCompareBool(self
->ob_item
[i
], v
, Py_EQ
);
1886 if (list_ass_slice(self
, i
, i
+1,
1887 (PyObject
*)NULL
) != 0)
1895 PyErr_SetString(PyExc_ValueError
, "list.remove(x): x not in list");
1900 list_traverse(PyListObject
*o
, visitproc visit
, void *arg
)
1905 for (i
= o
->ob_size
; --i
>= 0; ) {
1908 err
= visit(x
, arg
);
1917 list_clear(PyListObject
*lp
)
1919 (void) PyList_SetSlice((PyObject
*)lp
, 0, lp
->ob_size
, 0);
1924 list_richcompare(PyObject
*v
, PyObject
*w
, int op
)
1926 PyListObject
*vl
, *wl
;
1929 if (!PyList_Check(v
) || !PyList_Check(w
)) {
1930 Py_INCREF(Py_NotImplemented
);
1931 return Py_NotImplemented
;
1934 vl
= (PyListObject
*)v
;
1935 wl
= (PyListObject
*)w
;
1937 if (vl
->ob_size
!= wl
->ob_size
&& (op
== Py_EQ
|| op
== Py_NE
)) {
1938 /* Shortcut: if the lengths differ, the lists differ */
1948 /* Search for the first index where items are different */
1949 for (i
= 0; i
< vl
->ob_size
&& i
< wl
->ob_size
; i
++) {
1950 int k
= PyObject_RichCompareBool(vl
->ob_item
[i
],
1951 wl
->ob_item
[i
], Py_EQ
);
1958 if (i
>= vl
->ob_size
|| i
>= wl
->ob_size
) {
1959 /* No more items to compare -- compare sizes */
1960 int vs
= vl
->ob_size
;
1961 int ws
= wl
->ob_size
;
1965 case Py_LT
: cmp
= vs
< ws
; break;
1966 case Py_LE
: cmp
= vs
<= ws
; break;
1967 case Py_EQ
: cmp
= vs
== ws
; break;
1968 case Py_NE
: cmp
= vs
!= ws
; break;
1969 case Py_GT
: cmp
= vs
> ws
; break;
1970 case Py_GE
: cmp
= vs
>= ws
; break;
1971 default: return NULL
; /* cannot happen */
1981 /* We have an item that differs -- shortcuts for EQ/NE */
1983 Py_INCREF(Py_False
);
1991 /* Compare the final item again using the proper operator */
1992 return PyObject_RichCompare(vl
->ob_item
[i
], wl
->ob_item
[i
], op
);
1995 /* Adapted from newer code by Tim */
1997 list_fill(PyListObject
*result
, PyObject
*v
)
1999 PyObject
*it
; /* iter(v) */
2000 int n
; /* guess for result list size */
2003 n
= result
->ob_size
;
2005 /* Special-case list(a_list), for speed. */
2006 if (PyList_Check(v
)) {
2007 if (v
== (PyObject
*)result
)
2008 return 0; /* source is destination, we're done */
2009 return list_ass_slice(result
, 0, n
, v
);
2012 /* Empty previous contents */
2014 if (list_ass_slice(result
, 0, n
, (PyObject
*)NULL
) != 0)
2018 /* Get iterator. There may be some low-level efficiency to be gained
2019 * by caching the tp_iternext slot instead of using PyIter_Next()
2020 * later, but premature optimization is the root etc.
2022 it
= PyObject_GetIter(v
);
2026 /* Guess a result list size. */
2027 n
= -1; /* unknown */
2028 if (PySequence_Check(v
) &&
2029 v
->ob_type
->tp_as_sequence
->sq_length
) {
2030 n
= PySequence_Size(v
);
2035 n
= 8; /* arbitrary */
2036 NRESIZE(result
->ob_item
, PyObject
*, n
);
2037 if (result
->ob_item
== NULL
) {
2041 memset(result
->ob_item
, 0, sizeof(*result
->ob_item
) * n
);
2042 result
->ob_size
= n
;
2044 /* Run iterator to exhaustion. */
2045 for (i
= 0; ; i
++) {
2046 PyObject
*item
= PyIter_Next(it
);
2048 if (PyErr_Occurred())
2053 PyList_SET_ITEM(result
, i
, item
); /* steals ref */
2055 int status
= ins1(result
, result
->ob_size
, item
);
2056 Py_DECREF(item
); /* append creates a new ref */
2062 /* Cut back result list if initial guess was too large. */
2063 if (i
< n
&& result
!= NULL
) {
2064 if (list_ass_slice(result
, i
, n
, (PyObject
*)NULL
) != 0)
2076 list_init(PyListObject
*self
, PyObject
*args
, PyObject
*kw
)
2078 PyObject
*arg
= NULL
;
2079 static char *kwlist
[] = {"sequence", 0};
2081 if (!PyArg_ParseTupleAndKeywords(args
, kw
, "|O:list", kwlist
, &arg
))
2084 return list_fill(self
, arg
);
2085 if (self
->ob_size
> 0)
2086 return list_ass_slice(self
, 0, self
->ob_size
, (PyObject
*)NULL
);
2091 list_nohash(PyObject
*self
)
2093 PyErr_SetString(PyExc_TypeError
, "list objects are unhashable");
2097 PyDoc_STRVAR(append_doc
,
2098 "L.append(object) -- append object to end");
2099 PyDoc_STRVAR(extend_doc
,
2100 "L.extend(iterable) -- extend list by appending elements from the iterable");
2101 PyDoc_STRVAR(insert_doc
,
2102 "L.insert(index, object) -- insert object before index");
2103 PyDoc_STRVAR(pop_doc
,
2104 "L.pop([index]) -> item -- remove and return item at index (default last)");
2105 PyDoc_STRVAR(remove_doc
,
2106 "L.remove(value) -- remove first occurrence of value");
2107 PyDoc_STRVAR(index_doc
,
2108 "L.index(value, [start, [stop]]) -> integer -- return first index of value");
2109 PyDoc_STRVAR(count_doc
,
2110 "L.count(value) -> integer -- return number of occurrences of value");
2111 PyDoc_STRVAR(reverse_doc
,
2112 "L.reverse() -- reverse *IN PLACE*");
2113 PyDoc_STRVAR(sort_doc
,
2114 "L.sort(cmpfunc=None) -- stable sort *IN PLACE*; cmpfunc(x, y) -> -1, 0, 1");
2116 static PyMethodDef list_methods
[] = {
2117 {"append", (PyCFunction
)listappend
, METH_O
, append_doc
},
2118 {"insert", (PyCFunction
)listinsert
, METH_VARARGS
, insert_doc
},
2119 {"extend", (PyCFunction
)listextend
, METH_O
, extend_doc
},
2120 {"pop", (PyCFunction
)listpop
, METH_VARARGS
, pop_doc
},
2121 {"remove", (PyCFunction
)listremove
, METH_O
, remove_doc
},
2122 {"index", (PyCFunction
)listindex
, METH_VARARGS
, index_doc
},
2123 {"count", (PyCFunction
)listcount
, METH_O
, count_doc
},
2124 {"reverse", (PyCFunction
)listreverse
, METH_NOARGS
, reverse_doc
},
2125 {"sort", (PyCFunction
)listsort
, METH_VARARGS
, sort_doc
},
2126 {NULL
, NULL
} /* sentinel */
2129 static PySequenceMethods list_as_sequence
= {
2130 (inquiry
)list_length
, /* sq_length */
2131 (binaryfunc
)list_concat
, /* sq_concat */
2132 (intargfunc
)list_repeat
, /* sq_repeat */
2133 (intargfunc
)list_item
, /* sq_item */
2134 (intintargfunc
)list_slice
, /* sq_slice */
2135 (intobjargproc
)list_ass_item
, /* sq_ass_item */
2136 (intintobjargproc
)list_ass_slice
, /* sq_ass_slice */
2137 (objobjproc
)list_contains
, /* sq_contains */
2138 (binaryfunc
)list_inplace_concat
, /* sq_inplace_concat */
2139 (intargfunc
)list_inplace_repeat
, /* sq_inplace_repeat */
2142 PyDoc_STRVAR(list_doc
,
2143 "list() -> new list\n"
2144 "list(sequence) -> new list initialized from sequence's items");
2146 static PyObject
*list_iter(PyObject
*seq
);
2149 list_subscript(PyListObject
* self
, PyObject
* item
)
2151 if (PyInt_Check(item
)) {
2152 long i
= PyInt_AS_LONG(item
);
2154 i
+= PyList_GET_SIZE(self
);
2155 return list_item(self
, i
);
2157 else if (PyLong_Check(item
)) {
2158 long i
= PyLong_AsLong(item
);
2159 if (i
== -1 && PyErr_Occurred())
2162 i
+= PyList_GET_SIZE(self
);
2163 return list_item(self
, i
);
2165 else if (PySlice_Check(item
)) {
2166 int start
, stop
, step
, slicelength
, cur
, i
;
2170 if (PySlice_GetIndicesEx((PySliceObject
*)item
, self
->ob_size
,
2171 &start
, &stop
, &step
, &slicelength
) < 0) {
2175 if (slicelength
<= 0) {
2176 return PyList_New(0);
2179 result
= PyList_New(slicelength
);
2180 if (!result
) return NULL
;
2182 for (cur
= start
, i
= 0; i
< slicelength
;
2184 it
= PyList_GET_ITEM(self
, cur
);
2186 PyList_SET_ITEM(result
, i
, it
);
2193 PyErr_SetString(PyExc_TypeError
,
2194 "list indices must be integers");
2200 list_ass_subscript(PyListObject
* self
, PyObject
* item
, PyObject
* value
)
2202 if (PyInt_Check(item
)) {
2203 long i
= PyInt_AS_LONG(item
);
2205 i
+= PyList_GET_SIZE(self
);
2206 return list_ass_item(self
, i
, value
);
2208 else if (PyLong_Check(item
)) {
2209 long i
= PyLong_AsLong(item
);
2210 if (i
== -1 && PyErr_Occurred())
2213 i
+= PyList_GET_SIZE(self
);
2214 return list_ass_item(self
, i
, value
);
2216 else if (PySlice_Check(item
)) {
2217 int start
, stop
, step
, slicelength
;
2219 if (PySlice_GetIndicesEx((PySliceObject
*)item
, self
->ob_size
,
2220 &start
, &stop
, &step
, &slicelength
) < 0) {
2224 /* treat L[slice(a,b)] = v _exactly_ like L[a:b] = v */
2225 if (step
== 1 && ((PySliceObject
*)item
)->step
== Py_None
)
2226 return list_ass_slice(self
, start
, stop
, value
);
2228 if (value
== NULL
) {
2230 PyObject
**garbage
, **it
;
2233 if (slicelength
<= 0)
2238 start
= stop
+ step
*(slicelength
- 1) - 1;
2242 garbage
= (PyObject
**)
2243 PyMem_MALLOC(slicelength
*sizeof(PyObject
*));
2245 /* drawing pictures might help
2246 understand these for loops */
2247 for (cur
= start
, i
= 0;
2252 garbage
[i
] = PyList_GET_ITEM(self
, cur
);
2254 if (cur
+ step
>= self
->ob_size
) {
2255 lim
= self
->ob_size
- cur
- 1;
2258 for (j
= 0; j
< lim
; j
++) {
2259 PyList_SET_ITEM(self
, cur
+ j
- i
,
2260 PyList_GET_ITEM(self
,
2264 for (cur
= start
+ slicelength
*step
+ 1;
2265 cur
< self
->ob_size
; cur
++) {
2266 PyList_SET_ITEM(self
, cur
- slicelength
,
2267 PyList_GET_ITEM(self
, cur
));
2269 self
->ob_size
-= slicelength
;
2271 NRESIZE(it
, PyObject
*, self
->ob_size
);
2274 for (i
= 0; i
< slicelength
; i
++) {
2275 Py_DECREF(garbage
[i
]);
2277 PyMem_FREE(garbage
);
2283 PyObject
**garbage
, *ins
, *seq
;
2286 /* protect against a[::-1] = a */
2287 if (self
== (PyListObject
*)value
) {
2288 seq
= list_slice((PyListObject
*)value
, 0,
2289 PyList_GET_SIZE(value
));
2293 PyOS_snprintf(msg
, sizeof(msg
),
2294 "must assign sequence (not \"%.200s\") to extended slice",
2295 value
->ob_type
->tp_name
);
2296 seq
= PySequence_Fast(value
, msg
);
2301 if (PySequence_Fast_GET_SIZE(seq
) != slicelength
) {
2302 PyErr_Format(PyExc_ValueError
,
2303 "attempt to assign sequence of size %d to extended slice of size %d",
2304 PySequence_Fast_GET_SIZE(seq
),
2315 garbage
= (PyObject
**)
2316 PyMem_MALLOC(slicelength
*sizeof(PyObject
*));
2318 for (cur
= start
, i
= 0; i
< slicelength
;
2320 garbage
[i
] = PyList_GET_ITEM(self
, cur
);
2322 ins
= PySequence_Fast_GET_ITEM(seq
, i
);
2324 PyList_SET_ITEM(self
, cur
, ins
);
2327 for (i
= 0; i
< slicelength
; i
++) {
2328 Py_DECREF(garbage
[i
]);
2331 PyMem_FREE(garbage
);
2338 PyErr_SetString(PyExc_TypeError
,
2339 "list indices must be integers");
2344 static PyMappingMethods list_as_mapping
= {
2345 (inquiry
)list_length
,
2346 (binaryfunc
)list_subscript
,
2347 (objobjargproc
)list_ass_subscript
2350 PyTypeObject PyList_Type
= {
2351 PyObject_HEAD_INIT(&PyType_Type
)
2354 sizeof(PyListObject
),
2356 (destructor
)list_dealloc
, /* tp_dealloc */
2357 (printfunc
)list_print
, /* tp_print */
2361 (reprfunc
)list_repr
, /* tp_repr */
2362 0, /* tp_as_number */
2363 &list_as_sequence
, /* tp_as_sequence */
2364 &list_as_mapping
, /* tp_as_mapping */
2365 list_nohash
, /* tp_hash */
2368 PyObject_GenericGetAttr
, /* tp_getattro */
2369 0, /* tp_setattro */
2370 0, /* tp_as_buffer */
2371 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_HAVE_GC
|
2372 Py_TPFLAGS_BASETYPE
, /* tp_flags */
2373 list_doc
, /* tp_doc */
2374 (traverseproc
)list_traverse
, /* tp_traverse */
2375 (inquiry
)list_clear
, /* tp_clear */
2376 list_richcompare
, /* tp_richcompare */
2377 0, /* tp_weaklistoffset */
2378 list_iter
, /* tp_iter */
2379 0, /* tp_iternext */
2380 list_methods
, /* tp_methods */
2385 0, /* tp_descr_get */
2386 0, /* tp_descr_set */
2387 0, /* tp_dictoffset */
2388 (initproc
)list_init
, /* tp_init */
2389 PyType_GenericAlloc
, /* tp_alloc */
2390 PyType_GenericNew
, /* tp_new */
2391 PyObject_GC_Del
, /* tp_free */
2395 /*********************** List Iterator **************************/
2400 PyListObject
*it_seq
; /* Set to NULL when iterator is exhausted */
2403 PyTypeObject PyListIter_Type
;
2406 list_iter(PyObject
*seq
)
2410 if (!PyList_Check(seq
)) {
2411 PyErr_BadInternalCall();
2414 it
= PyObject_GC_New(listiterobject
, &PyListIter_Type
);
2419 it
->it_seq
= (PyListObject
*)seq
;
2420 _PyObject_GC_TRACK(it
);
2421 return (PyObject
*)it
;
2425 listiter_dealloc(listiterobject
*it
)
2427 _PyObject_GC_UNTRACK(it
);
2428 Py_XDECREF(it
->it_seq
);
2429 PyObject_GC_Del(it
);
2433 listiter_traverse(listiterobject
*it
, visitproc visit
, void *arg
)
2435 if (it
->it_seq
== NULL
)
2437 return visit((PyObject
*)it
->it_seq
, arg
);
2441 listiter_next(listiterobject
*it
)
2450 assert(PyList_Check(seq
));
2452 if (it
->it_index
< PyList_GET_SIZE(seq
)) {
2453 item
= PyList_GET_ITEM(seq
, it
->it_index
);
2464 PyTypeObject PyListIter_Type
= {
2465 PyObject_HEAD_INIT(&PyType_Type
)
2467 "listiterator", /* tp_name */
2468 sizeof(listiterobject
), /* tp_basicsize */
2469 0, /* tp_itemsize */
2471 (destructor
)listiter_dealloc
, /* tp_dealloc */
2477 0, /* tp_as_number */
2478 0, /* tp_as_sequence */
2479 0, /* tp_as_mapping */
2483 PyObject_GenericGetAttr
, /* tp_getattro */
2484 0, /* tp_setattro */
2485 0, /* tp_as_buffer */
2486 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_HAVE_GC
,/* tp_flags */
2488 (traverseproc
)listiter_traverse
, /* tp_traverse */
2490 0, /* tp_richcompare */
2491 0, /* tp_weaklistoffset */
2492 PyObject_SelfIter
, /* tp_iter */
2493 (iternextfunc
)listiter_next
, /* tp_iternext */
2499 0, /* tp_descr_get */
2500 0, /* tp_descr_set */