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);
164 if (where
> self
->ob_size
)
165 where
= self
->ob_size
;
166 for (i
= self
->ob_size
; --i
>= where
; )
167 items
[i
+1] = items
[i
];
170 self
->ob_item
= items
;
176 PyList_Insert(PyObject
*op
, int where
, PyObject
*newitem
)
178 if (!PyList_Check(op
)) {
179 PyErr_BadInternalCall();
182 return ins1((PyListObject
*)op
, where
, newitem
);
186 PyList_Append(PyObject
*op
, PyObject
*newitem
)
188 if (!PyList_Check(op
)) {
189 PyErr_BadInternalCall();
192 return ins1((PyListObject
*)op
,
193 (int) ((PyListObject
*)op
)->ob_size
, newitem
);
199 list_dealloc(PyListObject
*op
)
202 PyObject_GC_UnTrack(op
);
203 Py_TRASHCAN_SAFE_BEGIN(op
)
204 if (op
->ob_item
!= NULL
) {
205 /* Do it backwards, for Christian Tismer.
206 There's a simple test case where somehow this reduces
207 thrashing when a *very* large list is created and
208 immediately deleted. */
211 Py_XDECREF(op
->ob_item
[i
]);
213 PyMem_FREE(op
->ob_item
);
215 op
->ob_type
->tp_free((PyObject
*)op
);
216 Py_TRASHCAN_SAFE_END(op
)
220 list_print(PyListObject
*op
, FILE *fp
, int flags
)
224 i
= Py_ReprEnter((PyObject
*)op
);
228 fprintf(fp
, "[...]");
232 for (i
= 0; i
< op
->ob_size
; i
++) {
235 if (PyObject_Print(op
->ob_item
[i
], fp
, 0) != 0) {
236 Py_ReprLeave((PyObject
*)op
);
241 Py_ReprLeave((PyObject
*)op
);
246 list_repr(PyListObject
*v
)
250 PyObject
*pieces
= NULL
, *result
= NULL
;
252 i
= Py_ReprEnter((PyObject
*)v
);
254 return i
> 0 ? PyString_FromString("[...]") : NULL
;
257 if (v
->ob_size
== 0) {
258 result
= PyString_FromString("[]");
262 pieces
= PyList_New(0);
266 /* Do repr() on each element. Note that this may mutate the list,
267 so must refetch the list size on each iteration. */
268 for (i
= 0; i
< v
->ob_size
; ++i
) {
270 s
= PyObject_Repr(v
->ob_item
[i
]);
273 status
= PyList_Append(pieces
, s
);
274 Py_DECREF(s
); /* append created a new ref */
279 /* Add "[]" decorations to the first and last items. */
280 assert(PyList_GET_SIZE(pieces
) > 0);
281 s
= PyString_FromString("[");
284 temp
= PyList_GET_ITEM(pieces
, 0);
285 PyString_ConcatAndDel(&s
, temp
);
286 PyList_SET_ITEM(pieces
, 0, s
);
290 s
= PyString_FromString("]");
293 temp
= PyList_GET_ITEM(pieces
, PyList_GET_SIZE(pieces
) - 1);
294 PyString_ConcatAndDel(&temp
, s
);
295 PyList_SET_ITEM(pieces
, PyList_GET_SIZE(pieces
) - 1, temp
);
299 /* Paste them all together with ", " between. */
300 s
= PyString_FromString(", ");
303 result
= _PyString_Join(s
, pieces
);
308 Py_ReprLeave((PyObject
*)v
);
313 list_length(PyListObject
*a
)
321 list_contains(PyListObject
*a
, PyObject
*el
)
325 for (i
= 0, cmp
= 0 ; cmp
== 0 && i
< a
->ob_size
; ++i
)
326 cmp
= PyObject_RichCompareBool(el
, PyList_GET_ITEM(a
, i
),
333 list_item(PyListObject
*a
, int i
)
335 if (i
< 0 || i
>= a
->ob_size
) {
336 if (indexerr
== NULL
)
337 indexerr
= PyString_FromString(
338 "list index out of range");
339 PyErr_SetObject(PyExc_IndexError
, indexerr
);
342 Py_INCREF(a
->ob_item
[i
]);
343 return a
->ob_item
[i
];
347 list_slice(PyListObject
*a
, int ilow
, int ihigh
)
353 else if (ilow
> a
->ob_size
)
357 else if (ihigh
> a
->ob_size
)
359 np
= (PyListObject
*) PyList_New(ihigh
- ilow
);
362 for (i
= ilow
; i
< ihigh
; i
++) {
363 PyObject
*v
= a
->ob_item
[i
];
365 np
->ob_item
[i
- ilow
] = v
;
367 return (PyObject
*)np
;
371 PyList_GetSlice(PyObject
*a
, int ilow
, int ihigh
)
373 if (!PyList_Check(a
)) {
374 PyErr_BadInternalCall();
377 return list_slice((PyListObject
*)a
, ilow
, ihigh
);
381 list_concat(PyListObject
*a
, PyObject
*bb
)
386 if (!PyList_Check(bb
)) {
387 PyErr_Format(PyExc_TypeError
,
388 "can only concatenate list (not \"%.200s\") to list",
389 bb
->ob_type
->tp_name
);
392 #define b ((PyListObject *)bb)
393 size
= a
->ob_size
+ b
->ob_size
;
395 return PyErr_NoMemory();
396 np
= (PyListObject
*) PyList_New(size
);
400 for (i
= 0; i
< a
->ob_size
; i
++) {
401 PyObject
*v
= a
->ob_item
[i
];
405 for (i
= 0; i
< b
->ob_size
; i
++) {
406 PyObject
*v
= b
->ob_item
[i
];
408 np
->ob_item
[i
+ a
->ob_size
] = v
;
410 return (PyObject
*)np
;
415 list_repeat(PyListObject
*a
, int n
)
423 size
= a
->ob_size
* n
;
424 if (n
&& size
/n
!= a
->ob_size
)
425 return PyErr_NoMemory();
426 np
= (PyListObject
*) PyList_New(size
);
430 for (i
= 0; i
< n
; i
++) {
431 for (j
= 0; j
< a
->ob_size
; j
++) {
437 return (PyObject
*) np
;
441 list_ass_slice(PyListObject
*a
, int ilow
, int ihigh
, PyObject
*v
)
443 /* Because [X]DECREF can recursively invoke list operations on
444 this list, we must postpone all [X]DECREF activity until
445 after the list is back in its canonical shape. Therefore
446 we must allocate an additional array, 'recycle', into which
447 we temporarily copy the items that are deleted from the
449 PyObject
**recycle
, **p
;
451 PyObject
*v_as_SF
= NULL
; /* PySequence_Fast(v) */
452 int n
; /* Size of replacement list */
453 int d
; /* Change in size */
454 int k
; /* Loop index */
455 #define b ((PyListObject *)v)
460 PyOS_snprintf(msg
, sizeof(msg
),
461 "must assign sequence"
462 " (not \"%.200s\") to slice",
463 v
->ob_type
->tp_name
);
464 v_as_SF
= PySequence_Fast(v
, msg
);
467 n
= PySequence_Fast_GET_SIZE(v_as_SF
);
470 /* Special case "a[i:j] = a" -- copy b first */
472 v
= list_slice(b
, 0, n
);
473 ret
= list_ass_slice(a
, ilow
, ihigh
, v
);
480 else if (ilow
> a
->ob_size
)
484 else if (ihigh
> a
->ob_size
)
487 d
= n
- (ihigh
-ilow
);
489 p
= recycle
= PyMem_NEW(PyObject
*, (ihigh
-ilow
));
492 if (d
<= 0) { /* Delete -d items; recycle ihigh-ilow items */
493 for (k
= ilow
; k
< ihigh
; k
++)
496 for (/*k = ihigh*/; k
< a
->ob_size
; k
++)
499 NRESIZE(item
, PyObject
*, a
->ob_size
); /* Can't fail */
503 else { /* Insert d items; recycle ihigh-ilow items */
504 NRESIZE(item
, PyObject
*, a
->ob_size
+ d
);
511 for (k
= a
->ob_size
; --k
>= ihigh
; )
513 for (/*k = ihigh-1*/; k
>= ilow
; --k
)
518 for (k
= 0; k
< n
; k
++, ilow
++) {
519 PyObject
*w
= PySequence_Fast_GET_ITEM(v_as_SF
, k
);
524 while (--p
>= recycle
)
528 if (a
->ob_size
== 0 && a
->ob_item
!= NULL
) {
529 PyMem_FREE(a
->ob_item
);
538 PyList_SetSlice(PyObject
*a
, int ilow
, int ihigh
, PyObject
*v
)
540 if (!PyList_Check(a
)) {
541 PyErr_BadInternalCall();
544 return list_ass_slice((PyListObject
*)a
, ilow
, ihigh
, v
);
548 list_inplace_repeat(PyListObject
*self
, int n
)
554 size
= PyList_GET_SIZE(self
);
557 return (PyObject
*)self
;
560 items
= self
->ob_item
;
563 self
->ob_item
= NULL
;
565 for (i
= 0; i
< size
; i
++)
566 Py_XDECREF(items
[i
]);
569 return (PyObject
*)self
;
572 NRESIZE(items
, PyObject
*, size
*n
);
577 self
->ob_item
= items
;
578 for (i
= 1; i
< n
; i
++) { /* Start counting at 1, not 0 */
579 for (j
= 0; j
< size
; j
++) {
580 PyObject
*o
= PyList_GET_ITEM(self
, j
);
582 PyList_SET_ITEM(self
, self
->ob_size
++, o
);
586 return (PyObject
*)self
;
592 list_ass_item(PyListObject
*a
, int i
, PyObject
*v
)
595 if (i
< 0 || i
>= a
->ob_size
) {
596 PyErr_SetString(PyExc_IndexError
,
597 "list assignment index out of range");
601 return list_ass_slice(a
, i
, i
+1, v
);
603 old_value
= a
->ob_item
[i
];
605 Py_DECREF(old_value
);
610 ins(PyListObject
*self
, int where
, PyObject
*v
)
612 if (ins1(self
, where
, v
) != 0)
619 listinsert(PyListObject
*self
, PyObject
*args
)
623 if (!PyArg_ParseTuple(args
, "iO:insert", &i
, &v
))
625 return ins(self
, i
, v
);
629 listappend(PyListObject
*self
, PyObject
*v
)
631 return ins(self
, (int) self
->ob_size
, v
);
635 listextend_internal(PyListObject
*self
, PyObject
*b
)
638 int selflen
= PyList_GET_SIZE(self
);
642 if (PyObject_Size(b
) == 0) {
643 /* short circuit when b is empty */
648 if (self
== (PyListObject
*)b
) {
649 /* as in list_ass_slice() we must special case the
650 * situation: a.extend(a)
652 * XXX: I think this way ought to be faster than using
653 * list_slice() the way list_ass_slice() does.
656 b
= PyList_New(selflen
);
659 for (i
= 0; i
< selflen
; i
++) {
660 PyObject
*o
= PyList_GET_ITEM(self
, i
);
662 PyList_SET_ITEM(b
, i
, o
);
666 blen
= PyObject_Size(b
);
668 /* resize a using idiom */
669 items
= self
->ob_item
;
670 NRESIZE(items
, PyObject
*, selflen
+ blen
);
677 self
->ob_item
= items
;
679 /* populate the end of self with b's items */
680 for (i
= 0; i
< blen
; i
++) {
681 PyObject
*o
= PySequence_Fast_GET_ITEM(b
, i
);
683 PyList_SET_ITEM(self
, self
->ob_size
++, o
);
691 list_inplace_concat(PyListObject
*self
, PyObject
*other
)
693 other
= PySequence_Fast(other
, "argument to += must be iterable");
697 if (listextend_internal(self
, other
) < 0)
701 return (PyObject
*)self
;
705 listextend(PyListObject
*self
, PyObject
*b
)
708 b
= PySequence_Fast(b
, "list.extend() argument must be iterable");
712 if (listextend_internal(self
, b
) < 0)
720 listpop(PyListObject
*self
, PyObject
*args
)
724 if (!PyArg_ParseTuple(args
, "|i:pop", &i
))
726 if (self
->ob_size
== 0) {
727 /* Special-case most common failure cause */
728 PyErr_SetString(PyExc_IndexError
, "pop from empty list");
733 if (i
< 0 || i
>= self
->ob_size
) {
734 PyErr_SetString(PyExc_IndexError
, "pop index out of range");
737 v
= self
->ob_item
[i
];
739 if (list_ass_slice(self
, i
, i
+1, (PyObject
*)NULL
) != 0) {
746 /* Reverse a slice of a list in place, from lo up to (exclusive) hi. */
748 reverse_slice(PyObject
**lo
, PyObject
**hi
)
762 /* Lots of code for an adaptive, stable, natural mergesort. There are many
763 * pieces to this algorithm; read listsort.txt for overviews and details.
766 /* Comparison function. Takes care of calling a user-supplied
767 * comparison function (any callable Python object), which must not be
768 * NULL (use the ISLT macro if you don't know, or call PyObject_RichCompareBool
769 * with Py_LT if you know it's NULL).
770 * Returns -1 on error, 1 if x < y, 0 if x >= y.
773 islt(PyObject
*x
, PyObject
*y
, PyObject
*compare
)
779 assert(compare
!= NULL
);
780 /* Call the user's comparison function and translate the 3-way
781 * result into true or false (or error).
783 args
= PyTuple_New(2);
788 PyTuple_SET_ITEM(args
, 0, x
);
789 PyTuple_SET_ITEM(args
, 1, y
);
790 res
= PyObject_Call(compare
, args
, NULL
);
794 if (!PyInt_Check(res
)) {
796 PyErr_SetString(PyExc_TypeError
,
797 "comparison function must return int");
800 i
= PyInt_AsLong(res
);
805 /* If COMPARE is NULL, calls PyObject_RichCompareBool with Py_LT, else calls
806 * islt. This avoids a layer of function call in the usual case, and
807 * sorting does many comparisons.
808 * Returns -1 on error, 1 if x < y, 0 if x >= y.
810 #define ISLT(X, Y, COMPARE) ((COMPARE) == NULL ? \
811 PyObject_RichCompareBool(X, Y, Py_LT) : \
814 /* Compare X to Y via "<". Goto "fail" if the comparison raises an
815 error. Else "k" is set to true iff X<Y, and an "if (k)" block is
816 started. It makes more sense in context <wink>. X and Y are PyObject*s.
818 #define IFLT(X, Y) if ((k = ISLT(X, Y, compare)) < 0) goto fail; \
821 /* binarysort is the best method for sorting small arrays: it does
822 few compares, but can do data movement quadratic in the number of
824 [lo, hi) is a contiguous slice of a list, and is sorted via
825 binary insertion. This sort is stable.
826 On entry, must have lo <= start <= hi, and that [lo, start) is already
827 sorted (pass start == lo if you don't know!).
828 If islt() complains return -1, else 0.
829 Even in case of error, the output slice will be some permutation of
830 the input (nothing is lost or duplicated).
833 binarysort(PyObject
**lo
, PyObject
**hi
, PyObject
**start
, PyObject
*compare
)
834 /* compare -- comparison function object, or NULL for default */
837 register PyObject
**l
, **p
, **r
;
838 register PyObject
*pivot
;
840 assert(lo
<= start
&& start
<= hi
);
841 /* assert [lo, start) is sorted */
844 for (; start
< hi
; ++start
) {
845 /* set l to where *start belongs */
850 * pivot >= all in [lo, l).
851 * pivot < all in [r, start).
852 * The second is vacuously true at the start.
856 p
= l
+ ((r
- l
) >> 1);
863 /* The invariants still hold, so pivot >= all in [lo, l) and
864 pivot < all in [l, start), so pivot belongs at l. Note
865 that if there are elements equal to pivot, l points to the
866 first slot after them -- that's why this sort is stable.
867 Slide over to make room.
868 Caution: using memmove is much slower under MSVC 5;
869 we're not usually moving many slots. */
870 for (p
= start
; p
> l
; --p
)
881 Return the length of the run beginning at lo, in the slice [lo, hi). lo < hi
882 is required on entry. "A run" is the longest ascending sequence, with
884 lo[0] <= lo[1] <= lo[2] <= ...
886 or the longest descending sequence, with
888 lo[0] > lo[1] > lo[2] > ...
890 Boolean *descending is set to 0 in the former case, or to 1 in the latter.
891 For its intended use in a stable mergesort, the strictness of the defn of
892 "descending" is needed so that the caller can safely reverse a descending
893 sequence without violating stability (strict > ensures there are no equal
894 elements to get out of order).
896 Returns -1 in case of error.
899 count_run(PyObject
**lo
, PyObject
**hi
, PyObject
*compare
, int *descending
)
913 for (lo
= lo
+1; lo
< hi
; ++lo
, ++n
) {
921 for (lo
= lo
+1; lo
< hi
; ++lo
, ++n
) {
933 Locate the proper position of key in a sorted vector; if the vector contains
934 an element equal to key, return the position immediately to the left of
935 the leftmost equal element. [gallop_right() does the same except returns
936 the position to the right of the rightmost equal element (if any).]
938 "a" is a sorted vector with n elements, starting at a[0]. n must be > 0.
940 "hint" is an index at which to begin the search, 0 <= hint < n. The closer
941 hint is to the final result, the faster this runs.
943 The return value is the int k in 0..n such that
947 pretending that *(a-1) is minus infinity and a[n] is plus infinity. IOW,
948 key belongs at index k; or, IOW, the first k elements of a should precede
949 key, and the last n-k should follow key.
951 Returns -1 on error. See listsort.txt for info on the method.
954 gallop_left(PyObject
*key
, PyObject
**a
, int n
, int hint
, PyObject
*compare
)
960 assert(key
&& a
&& n
> 0 && hint
>= 0 && hint
< n
);
966 /* a[hint] < key -- gallop right, until
967 * a[hint + lastofs] < key <= a[hint + ofs]
969 const int maxofs
= n
- hint
; /* &a[n-1] is highest */
970 while (ofs
< maxofs
) {
973 ofs
= (ofs
<< 1) + 1;
974 if (ofs
<= 0) /* int overflow */
977 else /* key <= a[hint + ofs] */
982 /* Translate back to offsets relative to &a[0]. */
987 /* key <= a[hint] -- gallop left, until
988 * a[hint - ofs] < key <= a[hint - lastofs]
990 const int maxofs
= hint
+ 1; /* &a[0] is lowest */
991 while (ofs
< maxofs
) {
994 /* key <= a[hint - ofs] */
996 ofs
= (ofs
<< 1) + 1;
997 if (ofs
<= 0) /* int overflow */
1002 /* Translate back to positive offsets relative to &a[0]. */
1004 lastofs
= hint
- ofs
;
1009 assert(-1 <= lastofs
&& lastofs
< ofs
&& ofs
<= n
);
1010 /* Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the
1011 * right of lastofs but no farther right than ofs. Do a binary
1012 * search, with invariant a[lastofs-1] < key <= a[ofs].
1015 while (lastofs
< ofs
) {
1016 int m
= lastofs
+ ((ofs
- lastofs
) >> 1);
1019 lastofs
= m
+1; /* a[m] < key */
1021 ofs
= m
; /* key <= a[m] */
1023 assert(lastofs
== ofs
); /* so a[ofs-1] < key <= a[ofs] */
1031 Exactly like gallop_left(), except that if key already exists in a[0:n],
1032 finds the position immediately to the right of the rightmost equal value.
1034 The return value is the int k in 0..n such that
1036 a[k-1] <= key < a[k]
1040 The code duplication is massive, but this is enough different given that
1041 we're sticking to "<" comparisons that it's much harder to follow if
1042 written as one routine with yet another "left or right?" flag.
1045 gallop_right(PyObject
*key
, PyObject
**a
, int n
, int hint
, PyObject
*compare
)
1051 assert(key
&& a
&& n
> 0 && hint
>= 0 && hint
< n
);
1057 /* key < a[hint] -- gallop left, until
1058 * a[hint - ofs] <= key < a[hint - lastofs]
1060 const int maxofs
= hint
+ 1; /* &a[0] is lowest */
1061 while (ofs
< maxofs
) {
1062 IFLT(key
, *(a
-ofs
)) {
1064 ofs
= (ofs
<< 1) + 1;
1065 if (ofs
<= 0) /* int overflow */
1068 else /* a[hint - ofs] <= key */
1073 /* Translate back to positive offsets relative to &a[0]. */
1075 lastofs
= hint
- ofs
;
1079 /* a[hint] <= key -- gallop right, until
1080 * a[hint + lastofs] <= key < a[hint + ofs]
1082 const int maxofs
= n
- hint
; /* &a[n-1] is highest */
1083 while (ofs
< maxofs
) {
1086 /* a[hint + ofs] <= key */
1088 ofs
= (ofs
<< 1) + 1;
1089 if (ofs
<= 0) /* int overflow */
1094 /* Translate back to offsets relative to &a[0]. */
1100 assert(-1 <= lastofs
&& lastofs
< ofs
&& ofs
<= n
);
1101 /* Now a[lastofs] <= key < a[ofs], so key belongs somewhere to the
1102 * right of lastofs but no farther right than ofs. Do a binary
1103 * search, with invariant a[lastofs-1] <= key < a[ofs].
1106 while (lastofs
< ofs
) {
1107 int m
= lastofs
+ ((ofs
- lastofs
) >> 1);
1110 ofs
= m
; /* key < a[m] */
1112 lastofs
= m
+1; /* a[m] <= key */
1114 assert(lastofs
== ofs
); /* so a[ofs-1] <= key < a[ofs] */
1121 /* The maximum number of entries in a MergeState's pending-runs stack.
1122 * This is enough to sort arrays of size up to about
1123 * 32 * phi ** MAX_MERGE_PENDING
1124 * where phi ~= 1.618. 85 is ridiculouslylarge enough, good for an array
1125 * with 2**64 elements.
1127 #define MAX_MERGE_PENDING 85
1129 /* When we get into galloping mode, we stay there until both runs win less
1130 * often than MIN_GALLOP consecutive times. See listsort.txt for more info.
1132 #define MIN_GALLOP 7
1134 /* Avoid malloc for small temp arrays. */
1135 #define MERGESTATE_TEMP_SIZE 256
1137 /* One MergeState exists on the stack per invocation of mergesort. It's just
1138 * a convenient way to pass state around among the helper functions.
1145 typedef struct s_MergeState
{
1146 /* The user-supplied comparison function. or NULL if none given. */
1149 /* This controls when we get *into* galloping mode. It's initialized
1150 * to MIN_GALLOP. merge_lo and merge_hi tend to nudge it higher for
1151 * random data, and lower for highly structured data.
1155 /* 'a' is temp storage to help with merges. It contains room for
1158 PyObject
**a
; /* may point to temparray below */
1161 /* A stack of n pending runs yet to be merged. Run #i starts at
1162 * address base[i] and extends for len[i] elements. It's always
1163 * true (so long as the indices are in bounds) that
1165 * pending[i].base + pending[i].len == pending[i+1].base
1167 * so we could cut the storage for this, but it's a minor amount,
1168 * and keeping all the info explicit simplifies the code.
1171 struct s_slice pending
[MAX_MERGE_PENDING
];
1173 /* 'a' points to this when possible, rather than muck with malloc. */
1174 PyObject
*temparray
[MERGESTATE_TEMP_SIZE
];
1177 /* Conceptually a MergeState's constructor. */
1179 merge_init(MergeState
*ms
, PyObject
*compare
)
1182 ms
->compare
= compare
;
1183 ms
->a
= ms
->temparray
;
1184 ms
->alloced
= MERGESTATE_TEMP_SIZE
;
1186 ms
->min_gallop
= MIN_GALLOP
;
1189 /* Free all the temp memory owned by the MergeState. This must be called
1190 * when you're done with a MergeState, and may be called before then if
1191 * you want to free the temp memory early.
1194 merge_freemem(MergeState
*ms
)
1197 if (ms
->a
!= ms
->temparray
)
1199 ms
->a
= ms
->temparray
;
1200 ms
->alloced
= MERGESTATE_TEMP_SIZE
;
1203 /* Ensure enough temp memory for 'need' array slots is available.
1204 * Returns 0 on success and -1 if the memory can't be gotten.
1207 merge_getmem(MergeState
*ms
, int need
)
1210 if (need
<= ms
->alloced
)
1212 /* Don't realloc! That can cost cycles to copy the old data, but
1213 * we don't care what's in the block.
1216 ms
->a
= (PyObject
**)PyMem_Malloc(need
* sizeof(PyObject
*));
1222 merge_freemem(ms
); /* reset to sane state */
1225 #define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 : \
1226 merge_getmem(MS, NEED))
1228 /* Merge the na elements starting at pa with the nb elements starting at pb
1229 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1230 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1231 * merge, and should have na <= nb. See listsort.txt for more info.
1232 * Return 0 if successful, -1 if error.
1235 merge_lo(MergeState
*ms
, PyObject
**pa
, int na
, PyObject
**pb
, int nb
)
1240 int result
= -1; /* guilty until proved innocent */
1241 int min_gallop
= ms
->min_gallop
;
1243 assert(ms
&& pa
&& pb
&& na
> 0 && nb
> 0 && pa
+ na
== pb
);
1244 if (MERGE_GETMEM(ms
, na
) < 0)
1246 memcpy(ms
->a
, pa
, na
* sizeof(PyObject
*));
1257 compare
= ms
->compare
;
1259 int acount
= 0; /* # of times A won in a row */
1260 int bcount
= 0; /* # of times B won in a row */
1262 /* Do the straightforward thing until (if ever) one run
1263 * appears to win consistently.
1266 assert(na
> 1 && nb
> 0);
1267 k
= ISLT(*pb
, *pa
, compare
);
1277 if (bcount
>= min_gallop
)
1287 if (acount
>= min_gallop
)
1292 /* One run is winning so consistently that galloping may
1293 * be a huge win. So try that, and continue galloping until
1294 * (if ever) neither run appears to be winning consistently
1299 assert(na
> 1 && nb
> 0);
1300 min_gallop
-= min_gallop
> 1;
1301 ms
->min_gallop
= min_gallop
;
1302 k
= gallop_right(*pb
, pa
, na
, 0, compare
);
1307 memcpy(dest
, pa
, k
* sizeof(PyObject
*));
1313 /* na==0 is impossible now if the comparison
1314 * function is consistent, but we can't assume
1325 k
= gallop_left(*pa
, pb
, nb
, 0, compare
);
1330 memmove(dest
, pb
, k
* sizeof(PyObject
*));
1341 } while (acount
>= MIN_GALLOP
|| bcount
>= MIN_GALLOP
);
1342 ++min_gallop
; /* penalize it for leaving galloping mode */
1343 ms
->min_gallop
= min_gallop
;
1349 memcpy(dest
, pa
, na
* sizeof(PyObject
*));
1352 assert(na
== 1 && nb
> 0);
1353 /* The last element of pa belongs at the end of the merge. */
1354 memmove(dest
, pb
, nb
* sizeof(PyObject
*));
1359 /* Merge the na elements starting at pa with the nb elements starting at pb
1360 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1361 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1362 * merge, and should have na >= nb. See listsort.txt for more info.
1363 * Return 0 if successful, -1 if error.
1366 merge_hi(MergeState
*ms
, PyObject
**pa
, int na
, PyObject
**pb
, int nb
)
1371 int result
= -1; /* guilty until proved innocent */
1374 int min_gallop
= ms
->min_gallop
;
1376 assert(ms
&& pa
&& pb
&& na
> 0 && nb
> 0 && pa
+ na
== pb
);
1377 if (MERGE_GETMEM(ms
, nb
) < 0)
1380 memcpy(ms
->a
, pb
, nb
* sizeof(PyObject
*));
1383 pb
= ms
->a
+ nb
- 1;
1393 compare
= ms
->compare
;
1395 int acount
= 0; /* # of times A won in a row */
1396 int bcount
= 0; /* # of times B won in a row */
1398 /* Do the straightforward thing until (if ever) one run
1399 * appears to win consistently.
1402 assert(na
> 0 && nb
> 1);
1403 k
= ISLT(*pb
, *pa
, compare
);
1413 if (acount
>= min_gallop
)
1423 if (bcount
>= min_gallop
)
1428 /* One run is winning so consistently that galloping may
1429 * be a huge win. So try that, and continue galloping until
1430 * (if ever) neither run appears to be winning consistently
1435 assert(na
> 0 && nb
> 1);
1436 min_gallop
-= min_gallop
> 1;
1437 ms
->min_gallop
= min_gallop
;
1438 k
= gallop_right(*pb
, basea
, na
, na
-1, compare
);
1446 memmove(dest
+1, pa
+1, k
* sizeof(PyObject
*));
1456 k
= gallop_left(*pa
, baseb
, nb
, nb
-1, compare
);
1464 memcpy(dest
+1, pb
+1, k
* sizeof(PyObject
*));
1468 /* nb==0 is impossible now if the comparison
1469 * function is consistent, but we can't assume
1479 } while (acount
>= MIN_GALLOP
|| bcount
>= MIN_GALLOP
);
1480 ++min_gallop
; /* penalize it for leaving galloping mode */
1481 ms
->min_gallop
= min_gallop
;
1487 memcpy(dest
-(nb
-1), baseb
, nb
* sizeof(PyObject
*));
1490 assert(nb
== 1 && na
> 0);
1491 /* The first element of pb belongs at the front of the merge. */
1494 memmove(dest
+1, pa
+1, na
* sizeof(PyObject
*));
1499 /* Merge the two runs at stack indices i and i+1.
1500 * Returns 0 on success, -1 on error.
1503 merge_at(MergeState
*ms
, int i
)
1505 PyObject
**pa
, **pb
;
1513 assert(i
== ms
->n
- 2 || i
== ms
->n
- 3);
1515 pa
= ms
->pending
[i
].base
;
1516 na
= ms
->pending
[i
].len
;
1517 pb
= ms
->pending
[i
+1].base
;
1518 nb
= ms
->pending
[i
+1].len
;
1519 assert(na
> 0 && nb
> 0);
1520 assert(pa
+ na
== pb
);
1522 /* Record the length of the combined runs; if i is the 3rd-last
1523 * run now, also slide over the last run (which isn't involved
1524 * in this merge). The current run i+1 goes away in any case.
1526 ms
->pending
[i
].len
= na
+ nb
;
1528 ms
->pending
[i
+1] = ms
->pending
[i
+2];
1531 /* Where does b start in a? Elements in a before that can be
1532 * ignored (already in place).
1534 compare
= ms
->compare
;
1535 k
= gallop_right(*pb
, pa
, na
, 0, compare
);
1543 /* Where does a end in b? Elements in b after that can be
1544 * ignored (already in place).
1546 nb
= gallop_left(pa
[na
-1], pb
, nb
, nb
-1, compare
);
1550 /* Merge what remains of the runs, using a temp array with
1551 * min(na, nb) elements.
1554 return merge_lo(ms
, pa
, na
, pb
, nb
);
1556 return merge_hi(ms
, pa
, na
, pb
, nb
);
1559 /* Examine the stack of runs waiting to be merged, merging adjacent runs
1560 * until the stack invariants are re-established:
1562 * 1. len[-3] > len[-2] + len[-1]
1563 * 2. len[-2] > len[-1]
1565 * See listsort.txt for more info.
1567 * Returns 0 on success, -1 on error.
1570 merge_collapse(MergeState
*ms
)
1572 struct s_slice
*p
= ms
->pending
;
1577 if (n
> 0 && p
[n
-1].len
<= p
[n
].len
+ p
[n
+1].len
) {
1578 if (p
[n
-1].len
< p
[n
+1].len
)
1580 if (merge_at(ms
, n
) < 0)
1583 else if (p
[n
].len
<= p
[n
+1].len
) {
1584 if (merge_at(ms
, n
) < 0)
1593 /* Regardless of invariants, merge all runs on the stack until only one
1594 * remains. This is used at the end of the mergesort.
1596 * Returns 0 on success, -1 on error.
1599 merge_force_collapse(MergeState
*ms
)
1601 struct s_slice
*p
= ms
->pending
;
1606 if (n
> 0 && p
[n
-1].len
< p
[n
+1].len
)
1608 if (merge_at(ms
, n
) < 0)
1614 /* Compute a good value for the minimum run length; natural runs shorter
1615 * than this are boosted artificially via binary insertion.
1617 * If n < 64, return n (it's too small to bother with fancy stuff).
1618 * Else if n is an exact power of 2, return 32.
1619 * Else return an int k, 32 <= k <= 64, such that n/k is close to, but
1620 * strictly less than, an exact power of 2.
1622 * See listsort.txt for more info.
1625 merge_compute_minrun(int n
)
1627 int r
= 0; /* becomes 1 if any 1 bits are shifted off */
1637 /* An adaptive, stable, natural mergesort. See listsort.txt.
1638 * Returns Py_None on success, NULL on error. Even in case of error, the
1639 * list will be some permutation of its input state (nothing is lost or
1643 listsort(PyListObject
*self
, PyObject
*args
)
1646 PyObject
**lo
, **hi
;
1650 PyObject
**saved_ob_item
;
1651 PyObject
**empty_ob_item
;
1652 PyObject
*compare
= NULL
;
1653 PyObject
*result
= NULL
; /* guilty until proved innocent */
1655 assert(self
!= NULL
);
1657 if (!PyArg_UnpackTuple(args
, "sort", 0, 1, &compare
))
1660 if (compare
== Py_None
)
1663 merge_init(&ms
, compare
);
1665 /* The list is temporarily made empty, so that mutations performed
1666 * by comparison functions can't affect the slice of memory we're
1667 * sorting (allowing mutations during sorting is a core-dump
1668 * factory, since ob_item may change).
1670 saved_ob_size
= self
->ob_size
;
1671 saved_ob_item
= self
->ob_item
;
1673 self
->ob_item
= empty_ob_item
= PyMem_NEW(PyObject
*, 0);
1675 nremaining
= saved_ob_size
;
1679 /* March over the array once, left to right, finding natural runs,
1680 * and extending short natural runs to minrun elements.
1683 hi
= lo
+ nremaining
;
1684 minrun
= merge_compute_minrun(nremaining
);
1689 /* Identify next run. */
1690 n
= count_run(lo
, hi
, compare
, &descending
);
1694 reverse_slice(lo
, lo
+ n
);
1695 /* If short, extend to min(minrun, nremaining). */
1697 const int force
= nremaining
<= minrun
?
1698 nremaining
: minrun
;
1699 if (binarysort(lo
, lo
+ force
, lo
+ n
, compare
) < 0)
1703 /* Push run onto pending-runs stack, and maybe merge. */
1704 assert(ms
.n
< MAX_MERGE_PENDING
);
1705 ms
.pending
[ms
.n
].base
= lo
;
1706 ms
.pending
[ms
.n
].len
= n
;
1708 if (merge_collapse(&ms
) < 0)
1710 /* Advance to find next run. */
1713 } while (nremaining
);
1716 if (merge_force_collapse(&ms
) < 0)
1719 assert(ms
.pending
[0].base
== saved_ob_item
);
1720 assert(ms
.pending
[0].len
== saved_ob_size
);
1725 if (self
->ob_item
!= empty_ob_item
|| self
->ob_size
) {
1726 /* The user mucked with the list during the sort. */
1727 (void)list_ass_slice(self
, 0, self
->ob_size
, (PyObject
*)NULL
);
1728 if (result
!= NULL
) {
1729 PyErr_SetString(PyExc_ValueError
,
1730 "list modified during sort");
1734 if (self
->ob_item
== empty_ob_item
)
1735 PyMem_FREE(empty_ob_item
);
1736 self
->ob_size
= saved_ob_size
;
1737 self
->ob_item
= saved_ob_item
;
1746 PyList_Sort(PyObject
*v
)
1748 if (v
== NULL
|| !PyList_Check(v
)) {
1749 PyErr_BadInternalCall();
1752 v
= listsort((PyListObject
*)v
, (PyObject
*)NULL
);
1760 listreverse(PyListObject
*self
)
1762 if (self
->ob_size
> 1)
1763 reverse_slice(self
->ob_item
, self
->ob_item
+ self
->ob_size
);
1769 PyList_Reverse(PyObject
*v
)
1771 PyListObject
*self
= (PyListObject
*)v
;
1773 if (v
== NULL
|| !PyList_Check(v
)) {
1774 PyErr_BadInternalCall();
1777 if (self
->ob_size
> 1)
1778 reverse_slice(self
->ob_item
, self
->ob_item
+ self
->ob_size
);
1783 PyList_AsTuple(PyObject
*v
)
1788 if (v
== NULL
|| !PyList_Check(v
)) {
1789 PyErr_BadInternalCall();
1792 n
= ((PyListObject
*)v
)->ob_size
;
1796 p
= ((PyTupleObject
*)w
)->ob_item
;
1798 (void *)((PyListObject
*)v
)->ob_item
,
1799 n
*sizeof(PyObject
*));
1808 listindex(PyListObject
*self
, PyObject
*v
)
1812 for (i
= 0; i
< self
->ob_size
; i
++) {
1813 int cmp
= PyObject_RichCompareBool(self
->ob_item
[i
], v
, Py_EQ
);
1815 return PyInt_FromLong((long)i
);
1819 PyErr_SetString(PyExc_ValueError
, "list.index(x): x not in list");
1824 listcount(PyListObject
*self
, PyObject
*v
)
1829 for (i
= 0; i
< self
->ob_size
; i
++) {
1830 int cmp
= PyObject_RichCompareBool(self
->ob_item
[i
], v
, Py_EQ
);
1836 return PyInt_FromLong((long)count
);
1840 listremove(PyListObject
*self
, PyObject
*v
)
1844 for (i
= 0; i
< self
->ob_size
; i
++) {
1845 int cmp
= PyObject_RichCompareBool(self
->ob_item
[i
], v
, Py_EQ
);
1847 if (list_ass_slice(self
, i
, i
+1,
1848 (PyObject
*)NULL
) != 0)
1856 PyErr_SetString(PyExc_ValueError
, "list.remove(x): x not in list");
1861 list_traverse(PyListObject
*o
, visitproc visit
, void *arg
)
1866 for (i
= o
->ob_size
; --i
>= 0; ) {
1869 err
= visit(x
, arg
);
1878 list_clear(PyListObject
*lp
)
1880 (void) PyList_SetSlice((PyObject
*)lp
, 0, lp
->ob_size
, 0);
1885 list_richcompare(PyObject
*v
, PyObject
*w
, int op
)
1887 PyListObject
*vl
, *wl
;
1890 if (!PyList_Check(v
) || !PyList_Check(w
)) {
1891 Py_INCREF(Py_NotImplemented
);
1892 return Py_NotImplemented
;
1895 vl
= (PyListObject
*)v
;
1896 wl
= (PyListObject
*)w
;
1898 if (vl
->ob_size
!= wl
->ob_size
&& (op
== Py_EQ
|| op
== Py_NE
)) {
1899 /* Shortcut: if the lengths differ, the lists differ */
1909 /* Search for the first index where items are different */
1910 for (i
= 0; i
< vl
->ob_size
&& i
< wl
->ob_size
; i
++) {
1911 int k
= PyObject_RichCompareBool(vl
->ob_item
[i
],
1912 wl
->ob_item
[i
], Py_EQ
);
1919 if (i
>= vl
->ob_size
|| i
>= wl
->ob_size
) {
1920 /* No more items to compare -- compare sizes */
1921 int vs
= vl
->ob_size
;
1922 int ws
= wl
->ob_size
;
1926 case Py_LT
: cmp
= vs
< ws
; break;
1927 case Py_LE
: cmp
= vs
<= ws
; break;
1928 case Py_EQ
: cmp
= vs
== ws
; break;
1929 case Py_NE
: cmp
= vs
!= ws
; break;
1930 case Py_GT
: cmp
= vs
> ws
; break;
1931 case Py_GE
: cmp
= vs
>= ws
; break;
1932 default: return NULL
; /* cannot happen */
1942 /* We have an item that differs -- shortcuts for EQ/NE */
1944 Py_INCREF(Py_False
);
1952 /* Compare the final item again using the proper operator */
1953 return PyObject_RichCompare(vl
->ob_item
[i
], wl
->ob_item
[i
], op
);
1956 /* Adapted from newer code by Tim */
1958 list_fill(PyListObject
*result
, PyObject
*v
)
1960 PyObject
*it
; /* iter(v) */
1961 int n
; /* guess for result list size */
1964 n
= result
->ob_size
;
1966 /* Special-case list(a_list), for speed. */
1967 if (PyList_Check(v
)) {
1968 if (v
== (PyObject
*)result
)
1969 return 0; /* source is destination, we're done */
1970 return list_ass_slice(result
, 0, n
, v
);
1973 /* Empty previous contents */
1975 if (list_ass_slice(result
, 0, n
, (PyObject
*)NULL
) != 0)
1979 /* Get iterator. There may be some low-level efficiency to be gained
1980 * by caching the tp_iternext slot instead of using PyIter_Next()
1981 * later, but premature optimization is the root etc.
1983 it
= PyObject_GetIter(v
);
1987 /* Guess a result list size. */
1988 n
= -1; /* unknown */
1989 if (PySequence_Check(v
) &&
1990 v
->ob_type
->tp_as_sequence
->sq_length
) {
1991 n
= PySequence_Size(v
);
1996 n
= 8; /* arbitrary */
1997 NRESIZE(result
->ob_item
, PyObject
*, n
);
1998 if (result
->ob_item
== NULL
) {
2002 memset(result
->ob_item
, 0, sizeof(*result
->ob_item
) * n
);
2003 result
->ob_size
= n
;
2005 /* Run iterator to exhaustion. */
2006 for (i
= 0; ; i
++) {
2007 PyObject
*item
= PyIter_Next(it
);
2009 if (PyErr_Occurred())
2014 PyList_SET_ITEM(result
, i
, item
); /* steals ref */
2016 int status
= ins1(result
, result
->ob_size
, item
);
2017 Py_DECREF(item
); /* append creates a new ref */
2023 /* Cut back result list if initial guess was too large. */
2024 if (i
< n
&& result
!= NULL
) {
2025 if (list_ass_slice(result
, i
, n
, (PyObject
*)NULL
) != 0)
2037 list_init(PyListObject
*self
, PyObject
*args
, PyObject
*kw
)
2039 PyObject
*arg
= NULL
;
2040 static char *kwlist
[] = {"sequence", 0};
2042 if (!PyArg_ParseTupleAndKeywords(args
, kw
, "|O:list", kwlist
, &arg
))
2045 return list_fill(self
, arg
);
2046 if (self
->ob_size
> 0)
2047 return list_ass_slice(self
, 0, self
->ob_size
, (PyObject
*)NULL
);
2052 list_nohash(PyObject
*self
)
2054 PyErr_SetString(PyExc_TypeError
, "list objects are unhashable");
2058 PyDoc_STRVAR(append_doc
,
2059 "L.append(object) -- append object to end");
2060 PyDoc_STRVAR(extend_doc
,
2061 "L.extend(iterable) -- extend list by appending elements from the iterable");
2062 PyDoc_STRVAR(insert_doc
,
2063 "L.insert(index, object) -- insert object before index");
2064 PyDoc_STRVAR(pop_doc
,
2065 "L.pop([index]) -> item -- remove and return item at index (default last)");
2066 PyDoc_STRVAR(remove_doc
,
2067 "L.remove(value) -- remove first occurrence of value");
2068 PyDoc_STRVAR(index_doc
,
2069 "L.index(value) -> integer -- return index of first occurrence of value");
2070 PyDoc_STRVAR(count_doc
,
2071 "L.count(value) -> integer -- return number of occurrences of value");
2072 PyDoc_STRVAR(reverse_doc
,
2073 "L.reverse() -- reverse *IN PLACE*");
2074 PyDoc_STRVAR(sort_doc
,
2075 "L.sort(cmpfunc=None) -- stable sort *IN PLACE*; cmpfunc(x, y) -> -1, 0, 1");
2077 static PyMethodDef list_methods
[] = {
2078 {"append", (PyCFunction
)listappend
, METH_O
, append_doc
},
2079 {"insert", (PyCFunction
)listinsert
, METH_VARARGS
, insert_doc
},
2080 {"extend", (PyCFunction
)listextend
, METH_O
, extend_doc
},
2081 {"pop", (PyCFunction
)listpop
, METH_VARARGS
, pop_doc
},
2082 {"remove", (PyCFunction
)listremove
, METH_O
, remove_doc
},
2083 {"index", (PyCFunction
)listindex
, METH_O
, index_doc
},
2084 {"count", (PyCFunction
)listcount
, METH_O
, count_doc
},
2085 {"reverse", (PyCFunction
)listreverse
, METH_NOARGS
, reverse_doc
},
2086 {"sort", (PyCFunction
)listsort
, METH_VARARGS
, sort_doc
},
2087 {NULL
, NULL
} /* sentinel */
2090 static PySequenceMethods list_as_sequence
= {
2091 (inquiry
)list_length
, /* sq_length */
2092 (binaryfunc
)list_concat
, /* sq_concat */
2093 (intargfunc
)list_repeat
, /* sq_repeat */
2094 (intargfunc
)list_item
, /* sq_item */
2095 (intintargfunc
)list_slice
, /* sq_slice */
2096 (intobjargproc
)list_ass_item
, /* sq_ass_item */
2097 (intintobjargproc
)list_ass_slice
, /* sq_ass_slice */
2098 (objobjproc
)list_contains
, /* sq_contains */
2099 (binaryfunc
)list_inplace_concat
, /* sq_inplace_concat */
2100 (intargfunc
)list_inplace_repeat
, /* sq_inplace_repeat */
2103 PyDoc_STRVAR(list_doc
,
2104 "list() -> new list\n"
2105 "list(sequence) -> new list initialized from sequence's items");
2107 static PyObject
*list_iter(PyObject
*seq
);
2110 list_subscript(PyListObject
* self
, PyObject
* item
)
2112 if (PyInt_Check(item
)) {
2113 long i
= PyInt_AS_LONG(item
);
2115 i
+= PyList_GET_SIZE(self
);
2116 return list_item(self
, i
);
2118 else if (PyLong_Check(item
)) {
2119 long i
= PyLong_AsLong(item
);
2120 if (i
== -1 && PyErr_Occurred())
2123 i
+= PyList_GET_SIZE(self
);
2124 return list_item(self
, i
);
2126 else if (PySlice_Check(item
)) {
2127 int start
, stop
, step
, slicelength
, cur
, i
;
2131 if (PySlice_GetIndicesEx((PySliceObject
*)item
, self
->ob_size
,
2132 &start
, &stop
, &step
, &slicelength
) < 0) {
2136 if (slicelength
<= 0) {
2137 return PyList_New(0);
2140 result
= PyList_New(slicelength
);
2141 if (!result
) return NULL
;
2143 for (cur
= start
, i
= 0; i
< slicelength
;
2145 it
= PyList_GET_ITEM(self
, cur
);
2147 PyList_SET_ITEM(result
, i
, it
);
2154 PyErr_SetString(PyExc_TypeError
,
2155 "list indices must be integers");
2161 list_ass_subscript(PyListObject
* self
, PyObject
* item
, PyObject
* value
)
2163 if (PyInt_Check(item
)) {
2164 long i
= PyInt_AS_LONG(item
);
2166 i
+= PyList_GET_SIZE(self
);
2167 return list_ass_item(self
, i
, value
);
2169 else if (PyLong_Check(item
)) {
2170 long i
= PyLong_AsLong(item
);
2171 if (i
== -1 && PyErr_Occurred())
2174 i
+= PyList_GET_SIZE(self
);
2175 return list_ass_item(self
, i
, value
);
2177 else if (PySlice_Check(item
)) {
2178 int start
, stop
, step
, slicelength
;
2180 if (PySlice_GetIndicesEx((PySliceObject
*)item
, self
->ob_size
,
2181 &start
, &stop
, &step
, &slicelength
) < 0) {
2185 /* treat L[slice(a,b)] = v _exactly_ like L[a:b] = v */
2186 if (step
== 1 && ((PySliceObject
*)item
)->step
== Py_None
)
2187 return list_ass_slice(self
, start
, stop
, value
);
2189 if (value
== NULL
) {
2191 PyObject
**garbage
, **it
;
2194 if (slicelength
<= 0)
2199 start
= stop
+ step
*(slicelength
- 1) - 1;
2203 garbage
= (PyObject
**)
2204 PyMem_MALLOC(slicelength
*sizeof(PyObject
*));
2206 /* drawing pictures might help
2207 understand these for loops */
2208 for (cur
= start
, i
= 0;
2213 garbage
[i
] = PyList_GET_ITEM(self
, cur
);
2215 if (cur
+ step
>= self
->ob_size
) {
2216 lim
= self
->ob_size
- cur
- 1;
2219 for (j
= 0; j
< lim
; j
++) {
2220 PyList_SET_ITEM(self
, cur
+ j
- i
,
2221 PyList_GET_ITEM(self
,
2225 for (cur
= start
+ slicelength
*step
+ 1;
2226 cur
< self
->ob_size
; cur
++) {
2227 PyList_SET_ITEM(self
, cur
- slicelength
,
2228 PyList_GET_ITEM(self
, cur
));
2230 self
->ob_size
-= slicelength
;
2232 NRESIZE(it
, PyObject
*, self
->ob_size
);
2235 for (i
= 0; i
< slicelength
; i
++) {
2236 Py_DECREF(garbage
[i
]);
2238 PyMem_FREE(garbage
);
2244 PyObject
**garbage
, *ins
, *seq
;
2247 /* protect against a[::-1] = a */
2248 if (self
== (PyListObject
*)value
) {
2249 seq
= list_slice((PyListObject
*)value
, 0,
2250 PyList_GET_SIZE(value
));
2254 PyOS_snprintf(msg
, sizeof(msg
),
2255 "must assign sequence (not \"%.200s\") to extended slice",
2256 value
->ob_type
->tp_name
);
2257 seq
= PySequence_Fast(value
, msg
);
2262 if (PySequence_Fast_GET_SIZE(seq
) != slicelength
) {
2263 PyErr_Format(PyExc_ValueError
,
2264 "attempt to assign sequence of size %d to extended slice of size %d",
2265 PySequence_Fast_GET_SIZE(seq
),
2276 garbage
= (PyObject
**)
2277 PyMem_MALLOC(slicelength
*sizeof(PyObject
*));
2279 for (cur
= start
, i
= 0; i
< slicelength
;
2281 garbage
[i
] = PyList_GET_ITEM(self
, cur
);
2283 ins
= PySequence_Fast_GET_ITEM(seq
, i
);
2285 PyList_SET_ITEM(self
, cur
, ins
);
2288 for (i
= 0; i
< slicelength
; i
++) {
2289 Py_DECREF(garbage
[i
]);
2292 PyMem_FREE(garbage
);
2299 PyErr_SetString(PyExc_TypeError
,
2300 "list indices must be integers");
2305 static PyMappingMethods list_as_mapping
= {
2306 (inquiry
)list_length
,
2307 (binaryfunc
)list_subscript
,
2308 (objobjargproc
)list_ass_subscript
2311 PyTypeObject PyList_Type
= {
2312 PyObject_HEAD_INIT(&PyType_Type
)
2315 sizeof(PyListObject
),
2317 (destructor
)list_dealloc
, /* tp_dealloc */
2318 (printfunc
)list_print
, /* tp_print */
2322 (reprfunc
)list_repr
, /* tp_repr */
2323 0, /* tp_as_number */
2324 &list_as_sequence
, /* tp_as_sequence */
2325 &list_as_mapping
, /* tp_as_mapping */
2326 list_nohash
, /* tp_hash */
2329 PyObject_GenericGetAttr
, /* tp_getattro */
2330 0, /* tp_setattro */
2331 0, /* tp_as_buffer */
2332 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_HAVE_GC
|
2333 Py_TPFLAGS_BASETYPE
, /* tp_flags */
2334 list_doc
, /* tp_doc */
2335 (traverseproc
)list_traverse
, /* tp_traverse */
2336 (inquiry
)list_clear
, /* tp_clear */
2337 list_richcompare
, /* tp_richcompare */
2338 0, /* tp_weaklistoffset */
2339 list_iter
, /* tp_iter */
2340 0, /* tp_iternext */
2341 list_methods
, /* tp_methods */
2346 0, /* tp_descr_get */
2347 0, /* tp_descr_set */
2348 0, /* tp_dictoffset */
2349 (initproc
)list_init
, /* tp_init */
2350 PyType_GenericAlloc
, /* tp_alloc */
2351 PyType_GenericNew
, /* tp_new */
2352 PyObject_GC_Del
, /* tp_free */
2356 /*********************** List Iterator **************************/
2361 PyListObject
*it_seq
; /* Set to NULL when iterator is exhausted */
2364 PyTypeObject PyListIter_Type
;
2367 list_iter(PyObject
*seq
)
2371 if (!PyList_Check(seq
)) {
2372 PyErr_BadInternalCall();
2375 it
= PyObject_GC_New(listiterobject
, &PyListIter_Type
);
2380 it
->it_seq
= (PyListObject
*)seq
;
2381 _PyObject_GC_TRACK(it
);
2382 return (PyObject
*)it
;
2386 listiter_dealloc(listiterobject
*it
)
2388 _PyObject_GC_UNTRACK(it
);
2389 Py_XDECREF(it
->it_seq
);
2390 PyObject_GC_Del(it
);
2394 listiter_traverse(listiterobject
*it
, visitproc visit
, void *arg
)
2396 if (it
->it_seq
== NULL
)
2398 return visit((PyObject
*)it
->it_seq
, arg
);
2403 listiter_getiter(PyObject
*it
)
2410 listiter_next(listiterobject
*it
)
2419 assert(PyList_Check(seq
));
2421 if (it
->it_index
< PyList_GET_SIZE(seq
)) {
2422 item
= PyList_GET_ITEM(seq
, it
->it_index
);
2433 PyTypeObject PyListIter_Type
= {
2434 PyObject_HEAD_INIT(&PyType_Type
)
2436 "listiterator", /* tp_name */
2437 sizeof(listiterobject
), /* tp_basicsize */
2438 0, /* tp_itemsize */
2440 (destructor
)listiter_dealloc
, /* tp_dealloc */
2446 0, /* tp_as_number */
2447 0, /* tp_as_sequence */
2448 0, /* tp_as_mapping */
2452 PyObject_GenericGetAttr
, /* tp_getattro */
2453 0, /* tp_setattro */
2454 0, /* tp_as_buffer */
2455 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_HAVE_GC
,/* tp_flags */
2457 (traverseproc
)listiter_traverse
, /* tp_traverse */
2459 0, /* tp_richcompare */
2460 0, /* tp_weaklistoffset */
2461 (getiterfunc
)listiter_getiter
, /* tp_iter */
2462 (iternextfunc
)listiter_next
, /* tp_iternext */
2468 0, /* tp_descr_get */
2469 0, /* tp_descr_set */