blob: 5bc4577e56f53cfad8fb66d76bfc6d85872439d8 [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* List object implementation */
2
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003#include "Python.h"
4
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00005#ifdef STDC_HEADERS
6#include <stddef.h>
7#else
8#include <sys/types.h> /* For size_t */
9#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000010
Guido van Rossuma46d51d1995-01-26 22:59:43 +000011static int
Raymond Hettinger4bb95402004-02-13 11:36:39 +000012list_resize(PyListObject *self, int newsize)
Guido van Rossuma46d51d1995-01-26 22:59:43 +000013{
Raymond Hettinger4bb95402004-02-13 11:36:39 +000014 PyObject **items;
15 size_t _new_size;
Tim Peters65b8b842001-05-26 05:28:40 +000016
Raymond Hettinger4bb95402004-02-13 11:36:39 +000017 /* Bypass realloc() when a previous overallocation is large enough
18 to accommodate the newsize. If the newsize is 16 smaller than the
19 current size, then proceed with the realloc() to shrink the list.
20 */
21
22 if (self->allocated >= newsize &&
23 self->ob_size < newsize + 16 &&
24 self->ob_item != NULL) {
25 self->ob_size = newsize;
26 return 0;
27 }
28
29 /* This over-allocates proportional to the list size, making room
Tim Peters65b8b842001-05-26 05:28:40 +000030 * 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).
38 */
Raymond Hettinger4bb95402004-02-13 11:36:39 +000039 _new_size = (newsize >> 3) + (self->ob_size < 3 ? 1 : 6) + newsize;
40 items = self->ob_item;
41 if (_new_size <= ((~(size_t)0) / sizeof(PyObject *)))
42 PyMem_RESIZE(items, PyObject *, _new_size);
43 else
44 items = NULL;
45 if (items == NULL) {
46 PyErr_NoMemory();
47 return -1;
48 }
49 self->ob_item = items;
50 self->ob_size = newsize;
51 self->allocated = _new_size;
52 return 0;
53}
Guido van Rossuma46d51d1995-01-26 22:59:43 +000054
Guido van Rossumc0b618a1997-05-02 03:12:38 +000055PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +000056PyList_New(int size)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000057{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000058 PyListObject *op;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +000059 size_t nbytes;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000060 if (size < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +000061 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000062 return NULL;
63 }
Tim Peters7049d812004-01-18 20:31:02 +000064 nbytes = size * sizeof(PyObject *);
Guido van Rossum1e28e5e1992-08-19 16:46:30 +000065 /* Check for overflow */
Tim Peters7049d812004-01-18 20:31:02 +000066 if (nbytes / sizeof(PyObject *) != (size_t)size) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +000067 return PyErr_NoMemory();
Guido van Rossum1e28e5e1992-08-19 16:46:30 +000068 }
Neil Schemenauere83c00e2001-08-29 23:54:21 +000069 op = PyObject_GC_New(PyListObject, &PyList_Type);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000070 if (op == NULL) {
Neil Schemenauere83c00e2001-08-29 23:54:21 +000071 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000072 }
73 if (size <= 0) {
74 op->ob_item = NULL;
75 }
76 else {
Guido van Rossumb18618d2000-05-03 23:44:39 +000077 op->ob_item = (PyObject **) PyMem_MALLOC(nbytes);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000078 if (op->ob_item == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +000079 return PyErr_NoMemory();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000080 }
Tim Peters7049d812004-01-18 20:31:02 +000081 memset(op->ob_item, 0, sizeof(*op->ob_item) * size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000082 }
Neil Schemenauere83c00e2001-08-29 23:54:21 +000083 op->ob_size = size;
Raymond Hettinger4bb95402004-02-13 11:36:39 +000084 op->allocated = size;
Neil Schemenauere83c00e2001-08-29 23:54:21 +000085 _PyObject_GC_TRACK(op);
Guido van Rossumc0b618a1997-05-02 03:12:38 +000086 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000087}
88
89int
Fred Drakea2f55112000-07-09 15:16:51 +000090PyList_Size(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000091{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000092 if (!PyList_Check(op)) {
93 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000094 return -1;
95 }
96 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +000097 return ((PyListObject *)op) -> ob_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000098}
99
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000100static PyObject *indexerr;
Guido van Rossum929f1b81996-08-09 20:51:27 +0000101
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000102PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000103PyList_GetItem(PyObject *op, int i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000104{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000105 if (!PyList_Check(op)) {
106 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000107 return NULL;
108 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000109 if (i < 0 || i >= ((PyListObject *)op) -> ob_size) {
Guido van Rossum929f1b81996-08-09 20:51:27 +0000110 if (indexerr == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000111 indexerr = PyString_FromString(
112 "list index out of range");
113 PyErr_SetObject(PyExc_IndexError, indexerr);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000114 return NULL;
115 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000116 return ((PyListObject *)op) -> ob_item[i];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000117}
118
119int
Fred Drakea2f55112000-07-09 15:16:51 +0000120PyList_SetItem(register PyObject *op, register int i,
121 register PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000122{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000123 register PyObject *olditem;
124 register PyObject **p;
125 if (!PyList_Check(op)) {
126 Py_XDECREF(newitem);
127 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000128 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000129 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000130 if (i < 0 || i >= ((PyListObject *)op) -> ob_size) {
131 Py_XDECREF(newitem);
132 PyErr_SetString(PyExc_IndexError,
133 "list assignment index out of range");
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000134 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000135 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000136 p = ((PyListObject *)op) -> ob_item + i;
Guido van Rossum5fe60581995-03-09 12:12:50 +0000137 olditem = *p;
138 *p = newitem;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000139 Py_XDECREF(olditem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000140 return 0;
141}
142
143static int
Fred Drakea2f55112000-07-09 15:16:51 +0000144ins1(PyListObject *self, int where, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000145{
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000146 int i, n = self->ob_size;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000147 PyObject **items;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000148 if (v == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000149 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000150 return -1;
151 }
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000152 if (n == INT_MAX) {
Trent Micka5846642000-08-13 22:47:45 +0000153 PyErr_SetString(PyExc_OverflowError,
154 "cannot add more objects to list");
155 return -1;
156 }
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000157
158 if (list_resize(self, n+1) == -1)
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000159 return -1;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000160
Guido van Rossum3a3cca52003-04-14 20:58:14 +0000161 if (where < 0) {
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000162 where += n;
Guido van Rossum3a3cca52003-04-14 20:58:14 +0000163 if (where < 0)
164 where = 0;
165 }
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000166 if (where > n)
167 where = n;
168 items = self->ob_item;
169 for (i = n; --i >= where; )
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000170 items[i+1] = items[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000171 Py_INCREF(v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000172 items[where] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000173 return 0;
174}
175
176int
Fred Drakea2f55112000-07-09 15:16:51 +0000177PyList_Insert(PyObject *op, int where, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000178{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000179 if (!PyList_Check(op)) {
180 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000181 return -1;
182 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000183 return ins1((PyListObject *)op, where, newitem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000184}
185
186int
Fred Drakea2f55112000-07-09 15:16:51 +0000187PyList_Append(PyObject *op, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000188{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000189 if (!PyList_Check(op)) {
190 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000191 return -1;
192 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000193 return ins1((PyListObject *)op,
194 (int) ((PyListObject *)op)->ob_size, newitem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000195}
196
197/* Methods */
198
199static void
Fred Drakea2f55112000-07-09 15:16:51 +0000200list_dealloc(PyListObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000201{
202 int i;
Guido van Rossumff413af2002-03-28 20:34:59 +0000203 PyObject_GC_UnTrack(op);
Guido van Rossumd724b232000-03-13 16:01:29 +0000204 Py_TRASHCAN_SAFE_BEGIN(op)
Jack Jansen7874d1f1995-01-19 12:09:27 +0000205 if (op->ob_item != NULL) {
Guido van Rossumfa717011999-06-09 15:19:34 +0000206 /* Do it backwards, for Christian Tismer.
207 There's a simple test case where somehow this reduces
208 thrashing when a *very* large list is created and
209 immediately deleted. */
210 i = op->ob_size;
211 while (--i >= 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000212 Py_XDECREF(op->ob_item[i]);
Jack Jansen7874d1f1995-01-19 12:09:27 +0000213 }
Guido van Rossumb18618d2000-05-03 23:44:39 +0000214 PyMem_FREE(op->ob_item);
Jack Jansen7874d1f1995-01-19 12:09:27 +0000215 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000216 op->ob_type->tp_free((PyObject *)op);
Guido van Rossumd724b232000-03-13 16:01:29 +0000217 Py_TRASHCAN_SAFE_END(op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000218}
219
Guido van Rossum90933611991-06-07 16:10:43 +0000220static int
Fred Drakea2f55112000-07-09 15:16:51 +0000221list_print(PyListObject *op, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000222{
223 int i;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000224
225 i = Py_ReprEnter((PyObject*)op);
226 if (i != 0) {
227 if (i < 0)
228 return i;
229 fprintf(fp, "[...]");
230 return 0;
231 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000232 fprintf(fp, "[");
Guido van Rossum90933611991-06-07 16:10:43 +0000233 for (i = 0; i < op->ob_size; i++) {
234 if (i > 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000235 fprintf(fp, ", ");
Guido van Rossumfb376de1998-04-10 22:47:27 +0000236 if (PyObject_Print(op->ob_item[i], fp, 0) != 0) {
237 Py_ReprLeave((PyObject *)op);
Guido van Rossum90933611991-06-07 16:10:43 +0000238 return -1;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000239 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000240 }
241 fprintf(fp, "]");
Guido van Rossumfb376de1998-04-10 22:47:27 +0000242 Py_ReprLeave((PyObject *)op);
Guido van Rossum90933611991-06-07 16:10:43 +0000243 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000244}
245
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000246static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000247list_repr(PyListObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000248{
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000249 int i;
Tim Petersa7259592001-06-16 05:11:17 +0000250 PyObject *s, *temp;
251 PyObject *pieces = NULL, *result = NULL;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000252
253 i = Py_ReprEnter((PyObject*)v);
254 if (i != 0) {
Tim Petersa7259592001-06-16 05:11:17 +0000255 return i > 0 ? PyString_FromString("[...]") : NULL;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000256 }
Tim Petersa7259592001-06-16 05:11:17 +0000257
258 if (v->ob_size == 0) {
259 result = PyString_FromString("[]");
260 goto Done;
261 }
262
263 pieces = PyList_New(0);
264 if (pieces == NULL)
265 goto Done;
266
267 /* Do repr() on each element. Note that this may mutate the list,
268 so must refetch the list size on each iteration. */
269 for (i = 0; i < v->ob_size; ++i) {
270 int status;
271 s = PyObject_Repr(v->ob_item[i]);
272 if (s == NULL)
273 goto Done;
274 status = PyList_Append(pieces, s);
275 Py_DECREF(s); /* append created a new ref */
276 if (status < 0)
277 goto Done;
278 }
279
280 /* Add "[]" decorations to the first and last items. */
281 assert(PyList_GET_SIZE(pieces) > 0);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000282 s = PyString_FromString("[");
Tim Petersa7259592001-06-16 05:11:17 +0000283 if (s == NULL)
284 goto Done;
285 temp = PyList_GET_ITEM(pieces, 0);
286 PyString_ConcatAndDel(&s, temp);
287 PyList_SET_ITEM(pieces, 0, s);
288 if (s == NULL)
289 goto Done;
290
291 s = PyString_FromString("]");
292 if (s == NULL)
293 goto Done;
294 temp = PyList_GET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1);
295 PyString_ConcatAndDel(&temp, s);
296 PyList_SET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1, temp);
297 if (temp == NULL)
298 goto Done;
299
300 /* Paste them all together with ", " between. */
301 s = PyString_FromString(", ");
302 if (s == NULL)
303 goto Done;
304 result = _PyString_Join(s, pieces);
Tim Peters3b01a122002-07-19 02:35:45 +0000305 Py_DECREF(s);
Tim Petersa7259592001-06-16 05:11:17 +0000306
307Done:
308 Py_XDECREF(pieces);
Guido van Rossumfb376de1998-04-10 22:47:27 +0000309 Py_ReprLeave((PyObject *)v);
Tim Petersa7259592001-06-16 05:11:17 +0000310 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000311}
312
313static int
Fred Drakea2f55112000-07-09 15:16:51 +0000314list_length(PyListObject *a)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000315{
316 return a->ob_size;
317}
318
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000319
320
321static int
Fred Drakea2f55112000-07-09 15:16:51 +0000322list_contains(PyListObject *a, PyObject *el)
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000323{
Raymond Hettingeraae59992002-09-05 14:23:49 +0000324 int i, cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000325
Raymond Hettingeraae59992002-09-05 14:23:49 +0000326 for (i = 0, cmp = 0 ; cmp == 0 && i < a->ob_size; ++i)
327 cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i),
Guido van Rossum65e1cea2001-01-17 22:11:59 +0000328 Py_EQ);
Neal Norwitzbb9c5f52002-09-05 21:32:55 +0000329 return cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000330}
331
332
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000333static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000334list_item(PyListObject *a, int i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000335{
336 if (i < 0 || i >= a->ob_size) {
Guido van Rossum929f1b81996-08-09 20:51:27 +0000337 if (indexerr == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000338 indexerr = PyString_FromString(
339 "list index out of range");
340 PyErr_SetObject(PyExc_IndexError, indexerr);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000341 return NULL;
342 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000343 Py_INCREF(a->ob_item[i]);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000344 return a->ob_item[i];
345}
346
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000347static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000348list_slice(PyListObject *a, int ilow, int ihigh)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000349{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000350 PyListObject *np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000351 int i;
352 if (ilow < 0)
353 ilow = 0;
354 else if (ilow > a->ob_size)
355 ilow = a->ob_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000356 if (ihigh < ilow)
357 ihigh = ilow;
358 else if (ihigh > a->ob_size)
359 ihigh = a->ob_size;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000360 np = (PyListObject *) PyList_New(ihigh - ilow);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000361 if (np == NULL)
362 return NULL;
363 for (i = ilow; i < ihigh; i++) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000364 PyObject *v = a->ob_item[i];
365 Py_INCREF(v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000366 np->ob_item[i - ilow] = v;
367 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000368 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000369}
370
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000371PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000372PyList_GetSlice(PyObject *a, int ilow, int ihigh)
Guido van Rossum234f9421993-06-17 12:35:49 +0000373{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000374 if (!PyList_Check(a)) {
375 PyErr_BadInternalCall();
Guido van Rossum234f9421993-06-17 12:35:49 +0000376 return NULL;
377 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000378 return list_slice((PyListObject *)a, ilow, ihigh);
Guido van Rossum234f9421993-06-17 12:35:49 +0000379}
380
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000381static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000382list_concat(PyListObject *a, PyObject *bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000383{
384 int size;
385 int i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000386 PyListObject *np;
387 if (!PyList_Check(bb)) {
Fred Drakeb6a9ada2000-06-01 03:12:13 +0000388 PyErr_Format(PyExc_TypeError,
Fred Drake914a2ed2000-06-01 14:31:03 +0000389 "can only concatenate list (not \"%.200s\") to list",
390 bb->ob_type->tp_name);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000391 return NULL;
392 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000393#define b ((PyListObject *)bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000394 size = a->ob_size + b->ob_size;
Guido van Rossuma5c0e6d2002-10-11 21:05:56 +0000395 if (size < 0)
396 return PyErr_NoMemory();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000397 np = (PyListObject *) PyList_New(size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000398 if (np == NULL) {
Guido van Rossum90933611991-06-07 16:10:43 +0000399 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000400 }
401 for (i = 0; i < a->ob_size; i++) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000402 PyObject *v = a->ob_item[i];
403 Py_INCREF(v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000404 np->ob_item[i] = v;
405 }
406 for (i = 0; i < b->ob_size; i++) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000407 PyObject *v = b->ob_item[i];
408 Py_INCREF(v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000409 np->ob_item[i + a->ob_size] = v;
410 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000411 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000412#undef b
413}
414
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000415static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000416list_repeat(PyListObject *a, int n)
Guido van Rossumed98d481991-03-06 13:07:53 +0000417{
418 int i, j;
419 int size;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000420 PyListObject *np;
421 PyObject **p;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000422 PyObject *elem;
Guido van Rossumed98d481991-03-06 13:07:53 +0000423 if (n < 0)
424 n = 0;
425 size = a->ob_size * n;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000426 if (size == 0)
427 return PyList_New(0);
Guido van Rossumbfa5a142002-10-11 23:39:35 +0000428 if (n && size/n != a->ob_size)
Guido van Rossuma5c0e6d2002-10-11 21:05:56 +0000429 return PyErr_NoMemory();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000430 np = (PyListObject *) PyList_New(size);
Guido van Rossumed98d481991-03-06 13:07:53 +0000431 if (np == NULL)
432 return NULL;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000433
434 if (a->ob_size == 1) {
435 elem = a->ob_item[0];
436 for (i = 0; i < n; i++) {
437 np->ob_item[i] = elem;
438 Py_INCREF(elem);
439 }
440 return (PyObject *) np;
441 }
Guido van Rossumed98d481991-03-06 13:07:53 +0000442 p = np->ob_item;
443 for (i = 0; i < n; i++) {
444 for (j = 0; j < a->ob_size; j++) {
445 *p = a->ob_item[j];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000446 Py_INCREF(*p);
Guido van Rossumed98d481991-03-06 13:07:53 +0000447 p++;
448 }
449 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000450 return (PyObject *) np;
Guido van Rossumed98d481991-03-06 13:07:53 +0000451}
452
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000453static int
Fred Drakea2f55112000-07-09 15:16:51 +0000454list_ass_slice(PyListObject *a, int ilow, int ihigh, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000455{
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000456 /* Because [X]DECREF can recursively invoke list operations on
457 this list, we must postpone all [X]DECREF activity until
458 after the list is back in its canonical shape. Therefore
459 we must allocate an additional array, 'recycle', into which
460 we temporarily copy the items that are deleted from the
461 list. :-( */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000462 PyObject **recycle, **p;
463 PyObject **item;
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000464 PyObject *v_as_SF = NULL; /* PySequence_Fast(v) */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000465 int n; /* Size of replacement list */
466 int d; /* Change in size */
467 int k; /* Loop index */
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000468 int s;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000469#define b ((PyListObject *)v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000470 if (v == NULL)
471 n = 0;
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000472 else {
473 char msg[256];
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000474 if (a == b) {
475 /* Special case "a[i:j] = a" -- copy b first */
476 int ret;
Michael W. Hudsonda0a0672003-08-15 12:06:41 +0000477 v = list_slice(b, 0, b->ob_size);
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000478 if (v == NULL)
479 return -1;
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000480 ret = list_ass_slice(a, ilow, ihigh, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000481 Py_DECREF(v);
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000482 return ret;
483 }
Michael W. Hudsonb4f49382003-08-14 17:04:28 +0000484
485 PyOS_snprintf(msg, sizeof(msg),
486 "must assign sequence"
487 " (not \"%.200s\") to slice",
488 v->ob_type->tp_name);
489 v_as_SF = PySequence_Fast(v, msg);
490 if(v_as_SF == NULL)
491 return -1;
492 n = PySequence_Fast_GET_SIZE(v_as_SF);
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000493 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000494 if (ilow < 0)
495 ilow = 0;
496 else if (ilow > a->ob_size)
497 ilow = a->ob_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000498 if (ihigh < ilow)
499 ihigh = ilow;
500 else if (ihigh > a->ob_size)
501 ihigh = a->ob_size;
502 item = a->ob_item;
503 d = n - (ihigh-ilow);
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000504 if (ihigh > ilow) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000505 p = recycle = PyMem_NEW(PyObject *, (ihigh-ilow));
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000506 if (recycle == NULL) {
507 PyErr_NoMemory();
508 return -1;
509 }
510 }
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000511 else
512 p = recycle = NULL;
513 if (d <= 0) { /* Delete -d items; recycle ihigh-ilow items */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000514 for (k = ilow; k < ihigh; k++)
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000515 *p++ = item[k];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000516 if (d < 0) {
517 for (/*k = ihigh*/; k < a->ob_size; k++)
518 item[k+d] = item[k];
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000519 list_resize(a, a->ob_size + d);
520 item = a->ob_item;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000521 }
522 }
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000523 else { /* Insert d items; recycle ihigh-ilow items */
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000524 s = a->ob_size;
525 if (list_resize(a, s+d) == -1) {
Guido van Rossumb18618d2000-05-03 23:44:39 +0000526 if (recycle != NULL)
527 PyMem_DEL(recycle);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000528 }
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000529 item = a->ob_item;
530 for (k = s; --k >= ihigh; )
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000531 item[k+d] = item[k];
532 for (/*k = ihigh-1*/; k >= ilow; --k)
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000533 *p++ = item[k];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000534 }
535 for (k = 0; k < n; k++, ilow++) {
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000536 PyObject *w = PySequence_Fast_GET_ITEM(v_as_SF, k);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000537 Py_XINCREF(w);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000538 item[ilow] = w;
539 }
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000540 if (recycle) {
541 while (--p >= recycle)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000542 Py_XDECREF(*p);
543 PyMem_DEL(recycle);
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000544 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000545 if (a->ob_size == 0 && a->ob_item != NULL) {
546 PyMem_FREE(a->ob_item);
547 a->ob_item = NULL;
548 }
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000549 Py_XDECREF(v_as_SF);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000550 return 0;
551#undef b
552}
553
Guido van Rossum234f9421993-06-17 12:35:49 +0000554int
Fred Drakea2f55112000-07-09 15:16:51 +0000555PyList_SetSlice(PyObject *a, int ilow, int ihigh, PyObject *v)
Guido van Rossum234f9421993-06-17 12:35:49 +0000556{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000557 if (!PyList_Check(a)) {
558 PyErr_BadInternalCall();
Guido van Rossum1fc238a1993-07-29 08:25:09 +0000559 return -1;
Guido van Rossum234f9421993-06-17 12:35:49 +0000560 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000561 return list_ass_slice((PyListObject *)a, ilow, ihigh, v);
Guido van Rossum234f9421993-06-17 12:35:49 +0000562}
563
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000564static PyObject *
565list_inplace_repeat(PyListObject *self, int n)
566{
567 PyObject **items;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000568 int size, i, j, p;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000569
570
571 size = PyList_GET_SIZE(self);
572 if (size == 0) {
573 Py_INCREF(self);
574 return (PyObject *)self;
575 }
576
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000577 if (n < 1) {
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000578 items = self->ob_item;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000579 self->ob_item = NULL;
580 self->ob_size = 0;
581 for (i = 0; i < size; i++)
582 Py_XDECREF(items[i]);
583 PyMem_DEL(items);
584 Py_INCREF(self);
585 return (PyObject *)self;
586 }
587
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000588 if (list_resize(self, size*n) == -1)
589 return NULL;
590
591 p = size;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000592 for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */
593 for (j = 0; j < size; j++) {
594 PyObject *o = PyList_GET_ITEM(self, j);
595 Py_INCREF(o);
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000596 PyList_SET_ITEM(self, p++, o);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000597 }
598 }
599 Py_INCREF(self);
600 return (PyObject *)self;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000601}
602
Guido van Rossum4a450d01991-04-03 19:05:18 +0000603static int
Fred Drakea2f55112000-07-09 15:16:51 +0000604list_ass_item(PyListObject *a, int i, PyObject *v)
Guido van Rossum4a450d01991-04-03 19:05:18 +0000605{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000606 PyObject *old_value;
Guido van Rossum4a450d01991-04-03 19:05:18 +0000607 if (i < 0 || i >= a->ob_size) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000608 PyErr_SetString(PyExc_IndexError,
609 "list assignment index out of range");
Guido van Rossum4a450d01991-04-03 19:05:18 +0000610 return -1;
611 }
612 if (v == NULL)
613 return list_ass_slice(a, i, i+1, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000614 Py_INCREF(v);
Guido van Rossumd7047b31995-01-02 19:07:15 +0000615 old_value = a->ob_item[i];
Guido van Rossum4a450d01991-04-03 19:05:18 +0000616 a->ob_item[i] = v;
Tim Peters3b01a122002-07-19 02:35:45 +0000617 Py_DECREF(old_value);
Guido van Rossum4a450d01991-04-03 19:05:18 +0000618 return 0;
619}
620
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000621static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000622ins(PyListObject *self, int where, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000623{
624 if (ins1(self, where, v) != 0)
625 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000626 Py_INCREF(Py_None);
627 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000628}
629
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000630static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000631listinsert(PyListObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000632{
633 int i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000634 PyObject *v;
Guido van Rossumc00a9382000-02-24 21:48:29 +0000635 if (!PyArg_ParseTuple(args, "iO:insert", &i, &v))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000636 return NULL;
Guido van Rossumbf80e541993-02-08 15:49:17 +0000637 return ins(self, i, v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000638}
639
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000640static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000641listappend(PyListObject *self, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000642{
Guido van Rossumbf80e541993-02-08 15:49:17 +0000643 return ins(self, (int) self->ob_size, v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000644}
645
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000646static int
647listextend_internal(PyListObject *self, PyObject *b)
Barry Warsawdedf6d61998-10-09 16:37:25 +0000648{
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000649 register int selflen = PyList_GET_SIZE(self);
Barry Warsawdedf6d61998-10-09 16:37:25 +0000650 int blen;
651 register int i;
652
Jeremy Hyltondb60bb52001-01-03 22:32:16 +0000653 if (PyObject_Size(b) == 0) {
Barry Warsawdedf6d61998-10-09 16:37:25 +0000654 /* short circuit when b is empty */
Jeremy Hyltondb60bb52001-01-03 22:32:16 +0000655 Py_DECREF(b);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000656 return 0;
Jeremy Hyltondb60bb52001-01-03 22:32:16 +0000657 }
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000658
Barry Warsawdedf6d61998-10-09 16:37:25 +0000659 if (self == (PyListObject*)b) {
660 /* as in list_ass_slice() we must special case the
661 * situation: a.extend(a)
662 *
663 * XXX: I think this way ought to be faster than using
664 * list_slice() the way list_ass_slice() does.
665 */
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000666 Py_DECREF(b);
Barry Warsawdedf6d61998-10-09 16:37:25 +0000667 b = PyList_New(selflen);
668 if (!b)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000669 return -1;
Barry Warsawdedf6d61998-10-09 16:37:25 +0000670 for (i = 0; i < selflen; i++) {
671 PyObject *o = PyList_GET_ITEM(self, i);
672 Py_INCREF(o);
673 PyList_SET_ITEM(b, i, o);
674 }
675 }
Barry Warsawdedf6d61998-10-09 16:37:25 +0000676
Jeremy Hylton03657cf2000-07-12 13:05:33 +0000677 blen = PyObject_Size(b);
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000678 if (list_resize(self, selflen + blen) == -1) {
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000679 Py_DECREF(b);
680 return -1;
Barry Warsawdedf6d61998-10-09 16:37:25 +0000681 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000682
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000683 /* populate the end of self with b's items */
Barry Warsawdedf6d61998-10-09 16:37:25 +0000684 for (i = 0; i < blen; i++) {
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000685 PyObject *o = PySequence_Fast_GET_ITEM(b, i);
Barry Warsawdedf6d61998-10-09 16:37:25 +0000686 Py_INCREF(o);
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000687 PyList_SET_ITEM(self, i+selflen, o);
Barry Warsawdedf6d61998-10-09 16:37:25 +0000688 }
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000689 Py_DECREF(b);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000690 return 0;
Barry Warsawdedf6d61998-10-09 16:37:25 +0000691}
692
693
694static PyObject *
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000695list_inplace_concat(PyListObject *self, PyObject *other)
696{
Tim Peters1af03e92001-05-26 19:37:54 +0000697 other = PySequence_Fast(other, "argument to += must be iterable");
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000698 if (!other)
699 return NULL;
700
701 if (listextend_internal(self, other) < 0)
702 return NULL;
703
704 Py_INCREF(self);
705 return (PyObject *)self;
706}
707
708static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000709listextend(PyListObject *self, PyObject *b)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000710{
711
Tim Peters1af03e92001-05-26 19:37:54 +0000712 b = PySequence_Fast(b, "list.extend() argument must be iterable");
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000713 if (!b)
714 return NULL;
715
716 if (listextend_internal(self, b) < 0)
717 return NULL;
718
719 Py_INCREF(Py_None);
720 return Py_None;
721}
722
723static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000724listpop(PyListObject *self, PyObject *args)
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000725{
726 int i = -1;
727 PyObject *v;
Guido van Rossumc00a9382000-02-24 21:48:29 +0000728 if (!PyArg_ParseTuple(args, "|i:pop", &i))
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000729 return NULL;
730 if (self->ob_size == 0) {
731 /* Special-case most common failure cause */
732 PyErr_SetString(PyExc_IndexError, "pop from empty list");
733 return NULL;
734 }
735 if (i < 0)
736 i += self->ob_size;
737 if (i < 0 || i >= self->ob_size) {
738 PyErr_SetString(PyExc_IndexError, "pop index out of range");
739 return NULL;
740 }
741 v = self->ob_item[i];
742 Py_INCREF(v);
743 if (list_ass_slice(self, i, i+1, (PyObject *)NULL) != 0) {
744 Py_DECREF(v);
745 return NULL;
746 }
747 return v;
748}
749
Tim Peters8e2e7ca2002-07-19 02:33:08 +0000750/* Reverse a slice of a list in place, from lo up to (exclusive) hi. */
751static void
752reverse_slice(PyObject **lo, PyObject **hi)
753{
754 assert(lo && hi);
755
756 --hi;
757 while (lo < hi) {
758 PyObject *t = *lo;
759 *lo = *hi;
760 *hi = t;
761 ++lo;
762 --hi;
763 }
764}
765
Tim Petersa64dc242002-08-01 02:13:36 +0000766/* Lots of code for an adaptive, stable, natural mergesort. There are many
767 * pieces to this algorithm; read listsort.txt for overviews and details.
768 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000769
Guido van Rossum3f236de1996-12-10 23:55:39 +0000770/* Comparison function. Takes care of calling a user-supplied
Tim Peters66860f62002-08-04 17:47:26 +0000771 * comparison function (any callable Python object), which must not be
772 * NULL (use the ISLT macro if you don't know, or call PyObject_RichCompareBool
773 * with Py_LT if you know it's NULL).
Tim Petersa64dc242002-08-01 02:13:36 +0000774 * Returns -1 on error, 1 if x < y, 0 if x >= y.
775 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000776static int
Tim Petersa8c974c2002-07-19 03:30:57 +0000777islt(PyObject *x, PyObject *y, PyObject *compare)
Guido van Rossum3f236de1996-12-10 23:55:39 +0000778{
Tim Petersf2a04732002-07-11 21:46:16 +0000779 PyObject *res;
780 PyObject *args;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000781 int i;
782
Tim Peters66860f62002-08-04 17:47:26 +0000783 assert(compare != NULL);
Tim Petersa8c974c2002-07-19 03:30:57 +0000784 /* Call the user's comparison function and translate the 3-way
785 * result into true or false (or error).
786 */
Tim Petersf2a04732002-07-11 21:46:16 +0000787 args = PyTuple_New(2);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000788 if (args == NULL)
Tim Petersa8c974c2002-07-19 03:30:57 +0000789 return -1;
Tim Petersf2a04732002-07-11 21:46:16 +0000790 Py_INCREF(x);
791 Py_INCREF(y);
792 PyTuple_SET_ITEM(args, 0, x);
793 PyTuple_SET_ITEM(args, 1, y);
Tim Peters58cf3612002-07-15 05:16:13 +0000794 res = PyObject_Call(compare, args, NULL);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000795 Py_DECREF(args);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000796 if (res == NULL)
Tim Petersa8c974c2002-07-19 03:30:57 +0000797 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000798 if (!PyInt_Check(res)) {
799 Py_DECREF(res);
800 PyErr_SetString(PyExc_TypeError,
Guido van Rossum9bcd1d71999-04-19 17:44:39 +0000801 "comparison function must return int");
Tim Petersa8c974c2002-07-19 03:30:57 +0000802 return -1;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000803 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000804 i = PyInt_AsLong(res);
805 Py_DECREF(res);
Tim Petersa8c974c2002-07-19 03:30:57 +0000806 return i < 0;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000807}
808
Tim Peters66860f62002-08-04 17:47:26 +0000809/* If COMPARE is NULL, calls PyObject_RichCompareBool with Py_LT, else calls
810 * islt. This avoids a layer of function call in the usual case, and
811 * sorting does many comparisons.
812 * Returns -1 on error, 1 if x < y, 0 if x >= y.
813 */
814#define ISLT(X, Y, COMPARE) ((COMPARE) == NULL ? \
815 PyObject_RichCompareBool(X, Y, Py_LT) : \
816 islt(X, Y, COMPARE))
817
818/* Compare X to Y via "<". Goto "fail" if the comparison raises an
Tim Petersa8c974c2002-07-19 03:30:57 +0000819 error. Else "k" is set to true iff X<Y, and an "if (k)" block is
820 started. It makes more sense in context <wink>. X and Y are PyObject*s.
821*/
Tim Peters66860f62002-08-04 17:47:26 +0000822#define IFLT(X, Y) if ((k = ISLT(X, Y, compare)) < 0) goto fail; \
Tim Petersa8c974c2002-07-19 03:30:57 +0000823 if (k)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000824
825/* binarysort is the best method for sorting small arrays: it does
826 few compares, but can do data movement quadratic in the number of
827 elements.
Guido van Rossum42812581998-06-17 14:15:44 +0000828 [lo, hi) is a contiguous slice of a list, and is sorted via
Tim Petersa8c974c2002-07-19 03:30:57 +0000829 binary insertion. This sort is stable.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000830 On entry, must have lo <= start <= hi, and that [lo, start) is already
831 sorted (pass start == lo if you don't know!).
Tim Petersa8c974c2002-07-19 03:30:57 +0000832 If islt() complains return -1, else 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000833 Even in case of error, the output slice will be some permutation of
834 the input (nothing is lost or duplicated).
835*/
Guido van Rossum3f236de1996-12-10 23:55:39 +0000836static int
Fred Drakea2f55112000-07-09 15:16:51 +0000837binarysort(PyObject **lo, PyObject **hi, PyObject **start, PyObject *compare)
838 /* compare -- comparison function object, or NULL for default */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000839{
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000840 register int k;
841 register PyObject **l, **p, **r;
842 register PyObject *pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000843
Tim Petersa8c974c2002-07-19 03:30:57 +0000844 assert(lo <= start && start <= hi);
845 /* assert [lo, start) is sorted */
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000846 if (lo == start)
847 ++start;
848 for (; start < hi; ++start) {
849 /* set l to where *start belongs */
850 l = lo;
851 r = start;
Guido van Rossuma119c0d1998-05-29 17:56:32 +0000852 pivot = *r;
Tim Peters0fe977c2002-07-19 06:12:32 +0000853 /* Invariants:
854 * pivot >= all in [lo, l).
855 * pivot < all in [r, start).
856 * The second is vacuously true at the start.
857 */
858 assert(l < r);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000859 do {
860 p = l + ((r - l) >> 1);
Tim Petersa8c974c2002-07-19 03:30:57 +0000861 IFLT(pivot, *p)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000862 r = p;
863 else
Tim Peters0fe977c2002-07-19 06:12:32 +0000864 l = p+1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000865 } while (l < r);
Tim Peters0fe977c2002-07-19 06:12:32 +0000866 assert(l == r);
867 /* The invariants still hold, so pivot >= all in [lo, l) and
868 pivot < all in [l, start), so pivot belongs at l. Note
869 that if there are elements equal to pivot, l points to the
870 first slot after them -- that's why this sort is stable.
871 Slide over to make room.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000872 Caution: using memmove is much slower under MSVC 5;
873 we're not usually moving many slots. */
874 for (p = start; p > l; --p)
875 *p = *(p-1);
876 *l = pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000877 }
Guido van Rossum3f236de1996-12-10 23:55:39 +0000878 return 0;
Guido van Rossuma119c0d1998-05-29 17:56:32 +0000879
880 fail:
881 return -1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000882}
883
Tim Petersa64dc242002-08-01 02:13:36 +0000884/*
885Return the length of the run beginning at lo, in the slice [lo, hi). lo < hi
886is required on entry. "A run" is the longest ascending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000887
Tim Petersa64dc242002-08-01 02:13:36 +0000888 lo[0] <= lo[1] <= lo[2] <= ...
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000889
Tim Petersa64dc242002-08-01 02:13:36 +0000890or the longest descending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000891
Tim Petersa64dc242002-08-01 02:13:36 +0000892 lo[0] > lo[1] > lo[2] > ...
Tim Peters3b01a122002-07-19 02:35:45 +0000893
Tim Petersa64dc242002-08-01 02:13:36 +0000894Boolean *descending is set to 0 in the former case, or to 1 in the latter.
895For its intended use in a stable mergesort, the strictness of the defn of
896"descending" is needed so that the caller can safely reverse a descending
897sequence without violating stability (strict > ensures there are no equal
898elements to get out of order).
899
900Returns -1 in case of error.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000901*/
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000902static int
Tim Petersa64dc242002-08-01 02:13:36 +0000903count_run(PyObject **lo, PyObject **hi, PyObject *compare, int *descending)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000904{
Tim Petersa64dc242002-08-01 02:13:36 +0000905 int k;
906 int n;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000907
Tim Petersa64dc242002-08-01 02:13:36 +0000908 assert(lo < hi);
909 *descending = 0;
910 ++lo;
911 if (lo == hi)
912 return 1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000913
Tim Petersa64dc242002-08-01 02:13:36 +0000914 n = 2;
915 IFLT(*lo, *(lo-1)) {
916 *descending = 1;
917 for (lo = lo+1; lo < hi; ++lo, ++n) {
918 IFLT(*lo, *(lo-1))
919 ;
920 else
921 break;
922 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000923 }
Tim Petersa64dc242002-08-01 02:13:36 +0000924 else {
925 for (lo = lo+1; lo < hi; ++lo, ++n) {
926 IFLT(*lo, *(lo-1))
927 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000928 }
929 }
930
Tim Petersa64dc242002-08-01 02:13:36 +0000931 return n;
932fail:
933 return -1;
934}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000935
Tim Petersa64dc242002-08-01 02:13:36 +0000936/*
937Locate the proper position of key in a sorted vector; if the vector contains
938an element equal to key, return the position immediately to the left of
939the leftmost equal element. [gallop_right() does the same except returns
940the position to the right of the rightmost equal element (if any).]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000941
Tim Petersa64dc242002-08-01 02:13:36 +0000942"a" is a sorted vector with n elements, starting at a[0]. n must be > 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000943
Tim Petersa64dc242002-08-01 02:13:36 +0000944"hint" is an index at which to begin the search, 0 <= hint < n. The closer
945hint is to the final result, the faster this runs.
946
947The return value is the int k in 0..n such that
948
949 a[k-1] < key <= a[k]
950
951pretending that *(a-1) is minus infinity and a[n] is plus infinity. IOW,
952key belongs at index k; or, IOW, the first k elements of a should precede
953key, and the last n-k should follow key.
954
955Returns -1 on error. See listsort.txt for info on the method.
956*/
957static int
958gallop_left(PyObject *key, PyObject **a, int n, int hint, PyObject *compare)
959{
960 int ofs;
961 int lastofs;
962 int k;
963
964 assert(key && a && n > 0 && hint >= 0 && hint < n);
965
966 a += hint;
967 lastofs = 0;
968 ofs = 1;
969 IFLT(*a, key) {
970 /* a[hint] < key -- gallop right, until
971 * a[hint + lastofs] < key <= a[hint + ofs]
972 */
973 const int maxofs = n - hint; /* &a[n-1] is highest */
974 while (ofs < maxofs) {
975 IFLT(a[ofs], key) {
976 lastofs = ofs;
977 ofs = (ofs << 1) + 1;
978 if (ofs <= 0) /* int overflow */
979 ofs = maxofs;
980 }
981 else /* key <= a[hint + ofs] */
982 break;
983 }
984 if (ofs > maxofs)
985 ofs = maxofs;
986 /* Translate back to offsets relative to &a[0]. */
987 lastofs += hint;
988 ofs += hint;
989 }
990 else {
991 /* key <= a[hint] -- gallop left, until
992 * a[hint - ofs] < key <= a[hint - lastofs]
993 */
994 const int maxofs = hint + 1; /* &a[0] is lowest */
995 while (ofs < maxofs) {
996 IFLT(*(a-ofs), key)
997 break;
998 /* key <= a[hint - ofs] */
999 lastofs = ofs;
1000 ofs = (ofs << 1) + 1;
1001 if (ofs <= 0) /* int overflow */
1002 ofs = maxofs;
1003 }
1004 if (ofs > maxofs)
1005 ofs = maxofs;
1006 /* Translate back to positive offsets relative to &a[0]. */
1007 k = lastofs;
1008 lastofs = hint - ofs;
1009 ofs = hint - k;
1010 }
1011 a -= hint;
1012
1013 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1014 /* Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the
1015 * right of lastofs but no farther right than ofs. Do a binary
1016 * search, with invariant a[lastofs-1] < key <= a[ofs].
1017 */
1018 ++lastofs;
1019 while (lastofs < ofs) {
1020 int m = lastofs + ((ofs - lastofs) >> 1);
1021
1022 IFLT(a[m], key)
1023 lastofs = m+1; /* a[m] < key */
1024 else
1025 ofs = m; /* key <= a[m] */
1026 }
1027 assert(lastofs == ofs); /* so a[ofs-1] < key <= a[ofs] */
1028 return ofs;
1029
1030fail:
1031 return -1;
1032}
1033
1034/*
1035Exactly like gallop_left(), except that if key already exists in a[0:n],
1036finds the position immediately to the right of the rightmost equal value.
1037
1038The return value is the int k in 0..n such that
1039
1040 a[k-1] <= key < a[k]
1041
1042or -1 if error.
1043
1044The code duplication is massive, but this is enough different given that
1045we're sticking to "<" comparisons that it's much harder to follow if
1046written as one routine with yet another "left or right?" flag.
1047*/
1048static int
1049gallop_right(PyObject *key, PyObject **a, int n, int hint, PyObject *compare)
1050{
1051 int ofs;
1052 int lastofs;
1053 int k;
1054
1055 assert(key && a && n > 0 && hint >= 0 && hint < n);
1056
1057 a += hint;
1058 lastofs = 0;
1059 ofs = 1;
1060 IFLT(key, *a) {
1061 /* key < a[hint] -- gallop left, until
1062 * a[hint - ofs] <= key < a[hint - lastofs]
1063 */
1064 const int maxofs = hint + 1; /* &a[0] is lowest */
1065 while (ofs < maxofs) {
1066 IFLT(key, *(a-ofs)) {
1067 lastofs = ofs;
1068 ofs = (ofs << 1) + 1;
1069 if (ofs <= 0) /* int overflow */
1070 ofs = maxofs;
1071 }
1072 else /* a[hint - ofs] <= key */
1073 break;
1074 }
1075 if (ofs > maxofs)
1076 ofs = maxofs;
1077 /* Translate back to positive offsets relative to &a[0]. */
1078 k = lastofs;
1079 lastofs = hint - ofs;
1080 ofs = hint - k;
1081 }
1082 else {
1083 /* a[hint] <= key -- gallop right, until
1084 * a[hint + lastofs] <= key < a[hint + ofs]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001085 */
Tim Petersa64dc242002-08-01 02:13:36 +00001086 const int maxofs = n - hint; /* &a[n-1] is highest */
1087 while (ofs < maxofs) {
1088 IFLT(key, a[ofs])
1089 break;
1090 /* a[hint + ofs] <= key */
1091 lastofs = ofs;
1092 ofs = (ofs << 1) + 1;
1093 if (ofs <= 0) /* int overflow */
1094 ofs = maxofs;
1095 }
1096 if (ofs > maxofs)
1097 ofs = maxofs;
1098 /* Translate back to offsets relative to &a[0]. */
1099 lastofs += hint;
1100 ofs += hint;
1101 }
1102 a -= hint;
1103
1104 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1105 /* Now a[lastofs] <= key < a[ofs], so key belongs somewhere to the
1106 * right of lastofs but no farther right than ofs. Do a binary
1107 * search, with invariant a[lastofs-1] <= key < a[ofs].
1108 */
1109 ++lastofs;
1110 while (lastofs < ofs) {
1111 int m = lastofs + ((ofs - lastofs) >> 1);
1112
1113 IFLT(key, a[m])
1114 ofs = m; /* key < a[m] */
1115 else
1116 lastofs = m+1; /* a[m] <= key */
1117 }
1118 assert(lastofs == ofs); /* so a[ofs-1] <= key < a[ofs] */
1119 return ofs;
1120
1121fail:
1122 return -1;
1123}
1124
1125/* The maximum number of entries in a MergeState's pending-runs stack.
1126 * This is enough to sort arrays of size up to about
1127 * 32 * phi ** MAX_MERGE_PENDING
1128 * where phi ~= 1.618. 85 is ridiculouslylarge enough, good for an array
1129 * with 2**64 elements.
1130 */
1131#define MAX_MERGE_PENDING 85
1132
Tim Peterse05f65a2002-08-10 05:21:15 +00001133/* When we get into galloping mode, we stay there until both runs win less
1134 * often than MIN_GALLOP consecutive times. See listsort.txt for more info.
Tim Petersa64dc242002-08-01 02:13:36 +00001135 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001136#define MIN_GALLOP 7
Tim Petersa64dc242002-08-01 02:13:36 +00001137
1138/* Avoid malloc for small temp arrays. */
1139#define MERGESTATE_TEMP_SIZE 256
1140
1141/* One MergeState exists on the stack per invocation of mergesort. It's just
1142 * a convenient way to pass state around among the helper functions.
1143 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001144struct s_slice {
1145 PyObject **base;
1146 int len;
1147};
1148
Tim Petersa64dc242002-08-01 02:13:36 +00001149typedef struct s_MergeState {
1150 /* The user-supplied comparison function. or NULL if none given. */
1151 PyObject *compare;
1152
Tim Peterse05f65a2002-08-10 05:21:15 +00001153 /* This controls when we get *into* galloping mode. It's initialized
1154 * to MIN_GALLOP. merge_lo and merge_hi tend to nudge it higher for
1155 * random data, and lower for highly structured data.
1156 */
1157 int min_gallop;
1158
Tim Petersa64dc242002-08-01 02:13:36 +00001159 /* 'a' is temp storage to help with merges. It contains room for
1160 * alloced entries.
1161 */
1162 PyObject **a; /* may point to temparray below */
1163 int alloced;
1164
1165 /* A stack of n pending runs yet to be merged. Run #i starts at
1166 * address base[i] and extends for len[i] elements. It's always
1167 * true (so long as the indices are in bounds) that
1168 *
Tim Peterse05f65a2002-08-10 05:21:15 +00001169 * pending[i].base + pending[i].len == pending[i+1].base
Tim Petersa64dc242002-08-01 02:13:36 +00001170 *
1171 * so we could cut the storage for this, but it's a minor amount,
1172 * and keeping all the info explicit simplifies the code.
1173 */
1174 int n;
Tim Peterse05f65a2002-08-10 05:21:15 +00001175 struct s_slice pending[MAX_MERGE_PENDING];
Tim Petersa64dc242002-08-01 02:13:36 +00001176
1177 /* 'a' points to this when possible, rather than muck with malloc. */
1178 PyObject *temparray[MERGESTATE_TEMP_SIZE];
1179} MergeState;
1180
1181/* Conceptually a MergeState's constructor. */
1182static void
1183merge_init(MergeState *ms, PyObject *compare)
1184{
1185 assert(ms != NULL);
1186 ms->compare = compare;
1187 ms->a = ms->temparray;
1188 ms->alloced = MERGESTATE_TEMP_SIZE;
1189 ms->n = 0;
Tim Peterse05f65a2002-08-10 05:21:15 +00001190 ms->min_gallop = MIN_GALLOP;
Tim Petersa64dc242002-08-01 02:13:36 +00001191}
1192
1193/* Free all the temp memory owned by the MergeState. This must be called
1194 * when you're done with a MergeState, and may be called before then if
1195 * you want to free the temp memory early.
1196 */
1197static void
1198merge_freemem(MergeState *ms)
1199{
1200 assert(ms != NULL);
1201 if (ms->a != ms->temparray)
1202 PyMem_Free(ms->a);
1203 ms->a = ms->temparray;
1204 ms->alloced = MERGESTATE_TEMP_SIZE;
1205}
1206
1207/* Ensure enough temp memory for 'need' array slots is available.
1208 * Returns 0 on success and -1 if the memory can't be gotten.
1209 */
1210static int
1211merge_getmem(MergeState *ms, int need)
1212{
1213 assert(ms != NULL);
1214 if (need <= ms->alloced)
1215 return 0;
1216 /* Don't realloc! That can cost cycles to copy the old data, but
1217 * we don't care what's in the block.
1218 */
1219 merge_freemem(ms);
1220 ms->a = (PyObject **)PyMem_Malloc(need * sizeof(PyObject*));
1221 if (ms->a) {
1222 ms->alloced = need;
1223 return 0;
1224 }
1225 PyErr_NoMemory();
1226 merge_freemem(ms); /* reset to sane state */
1227 return -1;
1228}
1229#define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 : \
1230 merge_getmem(MS, NEED))
1231
1232/* Merge the na elements starting at pa with the nb elements starting at pb
1233 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1234 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1235 * merge, and should have na <= nb. See listsort.txt for more info.
1236 * Return 0 if successful, -1 if error.
1237 */
1238static int
1239merge_lo(MergeState *ms, PyObject **pa, int na, PyObject **pb, int nb)
1240{
1241 int k;
1242 PyObject *compare;
1243 PyObject **dest;
1244 int result = -1; /* guilty until proved innocent */
Tim Peterse05f65a2002-08-10 05:21:15 +00001245 int min_gallop = ms->min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001246
1247 assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
1248 if (MERGE_GETMEM(ms, na) < 0)
1249 return -1;
1250 memcpy(ms->a, pa, na * sizeof(PyObject*));
1251 dest = pa;
1252 pa = ms->a;
1253
1254 *dest++ = *pb++;
1255 --nb;
1256 if (nb == 0)
1257 goto Succeed;
1258 if (na == 1)
1259 goto CopyB;
1260
1261 compare = ms->compare;
1262 for (;;) {
1263 int acount = 0; /* # of times A won in a row */
1264 int bcount = 0; /* # of times B won in a row */
1265
1266 /* Do the straightforward thing until (if ever) one run
1267 * appears to win consistently.
1268 */
1269 for (;;) {
Tim Peterse05f65a2002-08-10 05:21:15 +00001270 assert(na > 1 && nb > 0);
Tim Peters66860f62002-08-04 17:47:26 +00001271 k = ISLT(*pb, *pa, compare);
Tim Petersa64dc242002-08-01 02:13:36 +00001272 if (k) {
1273 if (k < 0)
1274 goto Fail;
1275 *dest++ = *pb++;
1276 ++bcount;
1277 acount = 0;
1278 --nb;
1279 if (nb == 0)
1280 goto Succeed;
Tim Peterse05f65a2002-08-10 05:21:15 +00001281 if (bcount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001282 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001283 }
1284 else {
Tim Petersa64dc242002-08-01 02:13:36 +00001285 *dest++ = *pa++;
1286 ++acount;
1287 bcount = 0;
1288 --na;
1289 if (na == 1)
1290 goto CopyB;
Tim Peterse05f65a2002-08-10 05:21:15 +00001291 if (acount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001292 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001293 }
Tim Petersa64dc242002-08-01 02:13:36 +00001294 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001295
Tim Petersa64dc242002-08-01 02:13:36 +00001296 /* One run is winning so consistently that galloping may
1297 * be a huge win. So try that, and continue galloping until
1298 * (if ever) neither run appears to be winning consistently
1299 * anymore.
1300 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001301 ++min_gallop;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001302 do {
Tim Peterse05f65a2002-08-10 05:21:15 +00001303 assert(na > 1 && nb > 0);
1304 min_gallop -= min_gallop > 1;
1305 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001306 k = gallop_right(*pb, pa, na, 0, compare);
1307 acount = k;
1308 if (k) {
1309 if (k < 0)
1310 goto Fail;
1311 memcpy(dest, pa, k * sizeof(PyObject *));
1312 dest += k;
1313 pa += k;
1314 na -= k;
1315 if (na == 1)
1316 goto CopyB;
1317 /* na==0 is impossible now if the comparison
1318 * function is consistent, but we can't assume
1319 * that it is.
1320 */
1321 if (na == 0)
1322 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001323 }
Tim Petersa64dc242002-08-01 02:13:36 +00001324 *dest++ = *pb++;
1325 --nb;
1326 if (nb == 0)
1327 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001328
Tim Petersa64dc242002-08-01 02:13:36 +00001329 k = gallop_left(*pa, pb, nb, 0, compare);
1330 bcount = k;
1331 if (k) {
1332 if (k < 0)
1333 goto Fail;
1334 memmove(dest, pb, k * sizeof(PyObject *));
1335 dest += k;
1336 pb += k;
1337 nb -= k;
1338 if (nb == 0)
1339 goto Succeed;
1340 }
1341 *dest++ = *pa++;
1342 --na;
1343 if (na == 1)
1344 goto CopyB;
1345 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
Tim Peterse05f65a2002-08-10 05:21:15 +00001346 ++min_gallop; /* penalize it for leaving galloping mode */
1347 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001348 }
1349Succeed:
1350 result = 0;
1351Fail:
1352 if (na)
1353 memcpy(dest, pa, na * sizeof(PyObject*));
1354 return result;
1355CopyB:
1356 assert(na == 1 && nb > 0);
1357 /* The last element of pa belongs at the end of the merge. */
1358 memmove(dest, pb, nb * sizeof(PyObject *));
1359 dest[nb] = *pa;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001360 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001361}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001362
Tim Petersa64dc242002-08-01 02:13:36 +00001363/* Merge the na elements starting at pa with the nb elements starting at pb
1364 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1365 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1366 * merge, and should have na >= nb. See listsort.txt for more info.
1367 * Return 0 if successful, -1 if error.
1368 */
1369static int
1370merge_hi(MergeState *ms, PyObject **pa, int na, PyObject **pb, int nb)
1371{
1372 int k;
1373 PyObject *compare;
1374 PyObject **dest;
1375 int result = -1; /* guilty until proved innocent */
1376 PyObject **basea;
1377 PyObject **baseb;
Tim Peterse05f65a2002-08-10 05:21:15 +00001378 int min_gallop = ms->min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001379
1380 assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
1381 if (MERGE_GETMEM(ms, nb) < 0)
1382 return -1;
1383 dest = pb + nb - 1;
1384 memcpy(ms->a, pb, nb * sizeof(PyObject*));
1385 basea = pa;
1386 baseb = ms->a;
1387 pb = ms->a + nb - 1;
1388 pa += na - 1;
1389
1390 *dest-- = *pa--;
1391 --na;
1392 if (na == 0)
1393 goto Succeed;
1394 if (nb == 1)
1395 goto CopyA;
1396
1397 compare = ms->compare;
1398 for (;;) {
1399 int acount = 0; /* # of times A won in a row */
1400 int bcount = 0; /* # of times B won in a row */
1401
1402 /* Do the straightforward thing until (if ever) one run
1403 * appears to win consistently.
1404 */
1405 for (;;) {
Tim Peterse05f65a2002-08-10 05:21:15 +00001406 assert(na > 0 && nb > 1);
Tim Peters66860f62002-08-04 17:47:26 +00001407 k = ISLT(*pb, *pa, compare);
Tim Petersa64dc242002-08-01 02:13:36 +00001408 if (k) {
1409 if (k < 0)
1410 goto Fail;
1411 *dest-- = *pa--;
1412 ++acount;
1413 bcount = 0;
1414 --na;
1415 if (na == 0)
1416 goto Succeed;
Tim Peterse05f65a2002-08-10 05:21:15 +00001417 if (acount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001418 break;
1419 }
1420 else {
1421 *dest-- = *pb--;
1422 ++bcount;
1423 acount = 0;
1424 --nb;
1425 if (nb == 1)
1426 goto CopyA;
Tim Peterse05f65a2002-08-10 05:21:15 +00001427 if (bcount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001428 break;
1429 }
1430 }
1431
1432 /* One run is winning so consistently that galloping may
1433 * be a huge win. So try that, and continue galloping until
1434 * (if ever) neither run appears to be winning consistently
1435 * anymore.
1436 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001437 ++min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001438 do {
Tim Peterse05f65a2002-08-10 05:21:15 +00001439 assert(na > 0 && nb > 1);
1440 min_gallop -= min_gallop > 1;
1441 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001442 k = gallop_right(*pb, basea, na, na-1, compare);
1443 if (k < 0)
1444 goto Fail;
1445 k = na - k;
1446 acount = k;
1447 if (k) {
1448 dest -= k;
1449 pa -= k;
1450 memmove(dest+1, pa+1, k * sizeof(PyObject *));
1451 na -= k;
1452 if (na == 0)
1453 goto Succeed;
1454 }
1455 *dest-- = *pb--;
1456 --nb;
1457 if (nb == 1)
1458 goto CopyA;
1459
1460 k = gallop_left(*pa, baseb, nb, nb-1, compare);
1461 if (k < 0)
1462 goto Fail;
1463 k = nb - k;
1464 bcount = k;
1465 if (k) {
1466 dest -= k;
1467 pb -= k;
1468 memcpy(dest+1, pb+1, k * sizeof(PyObject *));
1469 nb -= k;
1470 if (nb == 1)
1471 goto CopyA;
1472 /* nb==0 is impossible now if the comparison
1473 * function is consistent, but we can't assume
1474 * that it is.
1475 */
1476 if (nb == 0)
1477 goto Succeed;
1478 }
1479 *dest-- = *pa--;
1480 --na;
1481 if (na == 0)
1482 goto Succeed;
1483 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
Tim Peterse05f65a2002-08-10 05:21:15 +00001484 ++min_gallop; /* penalize it for leaving galloping mode */
1485 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001486 }
1487Succeed:
1488 result = 0;
1489Fail:
1490 if (nb)
1491 memcpy(dest-(nb-1), baseb, nb * sizeof(PyObject*));
1492 return result;
1493CopyA:
1494 assert(nb == 1 && na > 0);
1495 /* The first element of pb belongs at the front of the merge. */
1496 dest -= na;
1497 pa -= na;
1498 memmove(dest+1, pa+1, na * sizeof(PyObject *));
1499 *dest = *pb;
1500 return 0;
1501}
1502
1503/* Merge the two runs at stack indices i and i+1.
1504 * Returns 0 on success, -1 on error.
1505 */
1506static int
1507merge_at(MergeState *ms, int i)
1508{
1509 PyObject **pa, **pb;
1510 int na, nb;
1511 int k;
1512 PyObject *compare;
1513
1514 assert(ms != NULL);
1515 assert(ms->n >= 2);
1516 assert(i >= 0);
1517 assert(i == ms->n - 2 || i == ms->n - 3);
1518
Tim Peterse05f65a2002-08-10 05:21:15 +00001519 pa = ms->pending[i].base;
1520 na = ms->pending[i].len;
1521 pb = ms->pending[i+1].base;
1522 nb = ms->pending[i+1].len;
Tim Petersa64dc242002-08-01 02:13:36 +00001523 assert(na > 0 && nb > 0);
1524 assert(pa + na == pb);
1525
1526 /* Record the length of the combined runs; if i is the 3rd-last
1527 * run now, also slide over the last run (which isn't involved
1528 * in this merge). The current run i+1 goes away in any case.
1529 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001530 ms->pending[i].len = na + nb;
1531 if (i == ms->n - 3)
1532 ms->pending[i+1] = ms->pending[i+2];
Tim Petersa64dc242002-08-01 02:13:36 +00001533 --ms->n;
1534
1535 /* Where does b start in a? Elements in a before that can be
1536 * ignored (already in place).
1537 */
1538 compare = ms->compare;
1539 k = gallop_right(*pb, pa, na, 0, compare);
1540 if (k < 0)
1541 return -1;
1542 pa += k;
1543 na -= k;
1544 if (na == 0)
1545 return 0;
1546
1547 /* Where does a end in b? Elements in b after that can be
1548 * ignored (already in place).
1549 */
1550 nb = gallop_left(pa[na-1], pb, nb, nb-1, compare);
1551 if (nb <= 0)
1552 return nb;
1553
1554 /* Merge what remains of the runs, using a temp array with
1555 * min(na, nb) elements.
1556 */
1557 if (na <= nb)
1558 return merge_lo(ms, pa, na, pb, nb);
1559 else
1560 return merge_hi(ms, pa, na, pb, nb);
1561}
1562
1563/* Examine the stack of runs waiting to be merged, merging adjacent runs
1564 * until the stack invariants are re-established:
1565 *
1566 * 1. len[-3] > len[-2] + len[-1]
1567 * 2. len[-2] > len[-1]
1568 *
1569 * See listsort.txt for more info.
1570 *
1571 * Returns 0 on success, -1 on error.
1572 */
1573static int
1574merge_collapse(MergeState *ms)
1575{
Tim Peterse05f65a2002-08-10 05:21:15 +00001576 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001577
1578 assert(ms);
1579 while (ms->n > 1) {
1580 int n = ms->n - 2;
Tim Peterse05f65a2002-08-10 05:21:15 +00001581 if (n > 0 && p[n-1].len <= p[n].len + p[n+1].len) {
1582 if (p[n-1].len < p[n+1].len)
Tim Petersa64dc242002-08-01 02:13:36 +00001583 --n;
1584 if (merge_at(ms, n) < 0)
1585 return -1;
1586 }
Tim Peterse05f65a2002-08-10 05:21:15 +00001587 else if (p[n].len <= p[n+1].len) {
Tim Petersa64dc242002-08-01 02:13:36 +00001588 if (merge_at(ms, n) < 0)
1589 return -1;
1590 }
1591 else
1592 break;
1593 }
1594 return 0;
1595}
1596
1597/* Regardless of invariants, merge all runs on the stack until only one
1598 * remains. This is used at the end of the mergesort.
1599 *
1600 * Returns 0 on success, -1 on error.
1601 */
1602static int
1603merge_force_collapse(MergeState *ms)
1604{
Tim Peterse05f65a2002-08-10 05:21:15 +00001605 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001606
1607 assert(ms);
1608 while (ms->n > 1) {
1609 int n = ms->n - 2;
Tim Peterse05f65a2002-08-10 05:21:15 +00001610 if (n > 0 && p[n-1].len < p[n+1].len)
Tim Petersa64dc242002-08-01 02:13:36 +00001611 --n;
1612 if (merge_at(ms, n) < 0)
1613 return -1;
1614 }
1615 return 0;
1616}
1617
1618/* Compute a good value for the minimum run length; natural runs shorter
1619 * than this are boosted artificially via binary insertion.
1620 *
1621 * If n < 64, return n (it's too small to bother with fancy stuff).
1622 * Else if n is an exact power of 2, return 32.
1623 * Else return an int k, 32 <= k <= 64, such that n/k is close to, but
1624 * strictly less than, an exact power of 2.
1625 *
1626 * See listsort.txt for more info.
1627 */
1628static int
1629merge_compute_minrun(int n)
1630{
1631 int r = 0; /* becomes 1 if any 1 bits are shifted off */
1632
1633 assert(n >= 0);
1634 while (n >= 64) {
1635 r |= n & 1;
1636 n >>= 1;
1637 }
1638 return n + r;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001639}
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001640
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001641/* Special wrapper to support stable sorting using the decorate-sort-undecorate
1642 pattern. Holds a key which is used for comparisions and the original record
1643 which is returned during the undecorate phase. By exposing only the key
1644 during comparisons, the underlying sort stability characteristics are left
1645 unchanged. Also, if a custom comparison function is used, it will only see
1646 the key instead of a full record. */
1647
1648typedef struct {
1649 PyObject_HEAD
1650 PyObject *key;
1651 PyObject *value;
1652} sortwrapperobject;
1653
1654static PyTypeObject sortwrapper_type;
1655
1656static PyObject *
1657sortwrapper_richcompare(sortwrapperobject *a, sortwrapperobject *b, int op)
1658{
1659 if (!PyObject_TypeCheck(b, &sortwrapper_type)) {
1660 PyErr_SetString(PyExc_TypeError,
1661 "expected a sortwrapperobject");
1662 return NULL;
1663 }
1664 return PyObject_RichCompare(a->key, b->key, op);
1665}
1666
1667static void
1668sortwrapper_dealloc(sortwrapperobject *so)
1669{
1670 Py_XDECREF(so->key);
1671 Py_XDECREF(so->value);
1672 PyObject_Del(so);
1673}
1674
1675PyDoc_STRVAR(sortwrapper_doc, "Object wrapper with a custom sort key.");
1676
1677static PyTypeObject sortwrapper_type = {
1678 PyObject_HEAD_INIT(&PyType_Type)
1679 0, /* ob_size */
1680 "sortwrapper", /* tp_name */
1681 sizeof(sortwrapperobject), /* tp_basicsize */
1682 0, /* tp_itemsize */
1683 /* methods */
1684 (destructor)sortwrapper_dealloc, /* tp_dealloc */
1685 0, /* tp_print */
1686 0, /* tp_getattr */
1687 0, /* tp_setattr */
1688 0, /* tp_compare */
1689 0, /* tp_repr */
1690 0, /* tp_as_number */
1691 0, /* tp_as_sequence */
1692 0, /* tp_as_mapping */
1693 0, /* tp_hash */
1694 0, /* tp_call */
1695 0, /* tp_str */
1696 PyObject_GenericGetAttr, /* tp_getattro */
1697 0, /* tp_setattro */
1698 0, /* tp_as_buffer */
1699 Py_TPFLAGS_DEFAULT |
1700 Py_TPFLAGS_HAVE_RICHCOMPARE, /* tp_flags */
1701 sortwrapper_doc, /* tp_doc */
1702 0, /* tp_traverse */
1703 0, /* tp_clear */
1704 (richcmpfunc)sortwrapper_richcompare, /* tp_richcompare */
1705};
1706
1707/* Returns a new reference to a sortwrapper.
1708 Consumes the references to the two underlying objects. */
1709
1710static PyObject *
1711build_sortwrapper(PyObject *key, PyObject *value)
1712{
1713 sortwrapperobject *so;
1714
1715 so = PyObject_New(sortwrapperobject, &sortwrapper_type);
1716 if (so == NULL)
1717 return NULL;
1718 so->key = key;
1719 so->value = value;
1720 return (PyObject *)so;
1721}
1722
1723/* Returns a new reference to the value underlying the wrapper. */
1724static PyObject *
1725sortwrapper_getvalue(PyObject *so)
1726{
1727 PyObject *value;
1728
1729 if (!PyObject_TypeCheck(so, &sortwrapper_type)) {
1730 PyErr_SetString(PyExc_TypeError,
1731 "expected a sortwrapperobject");
1732 return NULL;
1733 }
1734 value = ((sortwrapperobject *)so)->value;
1735 Py_INCREF(value);
1736 return value;
1737}
1738
1739/* Wrapper for user specified cmp functions in combination with a
1740 specified key function. Makes sure the cmp function is presented
1741 with the actual key instead of the sortwrapper */
1742
1743typedef struct {
1744 PyObject_HEAD
1745 PyObject *func;
1746} cmpwrapperobject;
1747
1748static void
1749cmpwrapper_dealloc(cmpwrapperobject *co)
1750{
1751 Py_XDECREF(co->func);
1752 PyObject_Del(co);
1753}
1754
1755static PyObject *
1756cmpwrapper_call(cmpwrapperobject *co, PyObject *args, PyObject *kwds)
1757{
1758 PyObject *x, *y, *xx, *yy;
1759
1760 if (!PyArg_UnpackTuple(args, "", 2, 2, &x, &y))
1761 return NULL;
1762 if (!PyObject_TypeCheck(x, &sortwrapper_type) ||
Raymond Hettingerae4a2992003-10-16 17:16:30 +00001763 !PyObject_TypeCheck(y, &sortwrapper_type)) {
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001764 PyErr_SetString(PyExc_TypeError,
1765 "expected a sortwrapperobject");
1766 return NULL;
1767 }
1768 xx = ((sortwrapperobject *)x)->key;
1769 yy = ((sortwrapperobject *)y)->key;
1770 return PyObject_CallFunctionObjArgs(co->func, xx, yy, NULL);
1771}
1772
1773PyDoc_STRVAR(cmpwrapper_doc, "cmp() wrapper for sort with custom keys.");
1774
1775static PyTypeObject cmpwrapper_type = {
1776 PyObject_HEAD_INIT(&PyType_Type)
1777 0, /* ob_size */
1778 "cmpwrapper", /* tp_name */
1779 sizeof(cmpwrapperobject), /* tp_basicsize */
1780 0, /* tp_itemsize */
1781 /* methods */
1782 (destructor)cmpwrapper_dealloc, /* tp_dealloc */
1783 0, /* tp_print */
1784 0, /* tp_getattr */
1785 0, /* tp_setattr */
1786 0, /* tp_compare */
1787 0, /* tp_repr */
1788 0, /* tp_as_number */
1789 0, /* tp_as_sequence */
1790 0, /* tp_as_mapping */
1791 0, /* tp_hash */
1792 (ternaryfunc)cmpwrapper_call, /* tp_call */
1793 0, /* tp_str */
1794 PyObject_GenericGetAttr, /* tp_getattro */
1795 0, /* tp_setattro */
1796 0, /* tp_as_buffer */
1797 Py_TPFLAGS_DEFAULT, /* tp_flags */
1798 cmpwrapper_doc, /* tp_doc */
1799};
1800
1801static PyObject *
1802build_cmpwrapper(PyObject *cmpfunc)
1803{
1804 cmpwrapperobject *co;
1805
1806 co = PyObject_New(cmpwrapperobject, &cmpwrapper_type);
1807 if (co == NULL)
1808 return NULL;
1809 Py_INCREF(cmpfunc);
1810 co->func = cmpfunc;
1811 return (PyObject *)co;
1812}
1813
Tim Petersa64dc242002-08-01 02:13:36 +00001814/* An adaptive, stable, natural mergesort. See listsort.txt.
1815 * Returns Py_None on success, NULL on error. Even in case of error, the
1816 * list will be some permutation of its input state (nothing is lost or
1817 * duplicated).
1818 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001819static PyObject *
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001820listsort(PyListObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f236de1996-12-10 23:55:39 +00001821{
Tim Petersa64dc242002-08-01 02:13:36 +00001822 MergeState ms;
1823 PyObject **lo, **hi;
1824 int nremaining;
1825 int minrun;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00001826 int saved_ob_size, saved_allocated;
Tim Petersb9099c32002-11-12 22:08:10 +00001827 PyObject **saved_ob_item;
1828 PyObject **empty_ob_item;
Tim Petersa64dc242002-08-01 02:13:36 +00001829 PyObject *compare = NULL;
1830 PyObject *result = NULL; /* guilty until proved innocent */
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001831 int reverse = 0;
1832 PyObject *keyfunc = NULL;
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001833 int i;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001834 PyObject *key, *value, *kvpair;
1835 static char *kwlist[] = {"cmp", "key", "reverse", 0};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001836
Tim Petersa64dc242002-08-01 02:13:36 +00001837 assert(self != NULL);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001838 assert (PyList_Check(self));
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001839 if (args != NULL) {
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001840 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOi:sort",
1841 kwlist, &compare, &keyfunc, &reverse))
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001842 return NULL;
1843 }
Skip Montanaro4abd5f02003-01-02 20:51:08 +00001844 if (compare == Py_None)
1845 compare = NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001846 if (keyfunc == Py_None)
1847 keyfunc = NULL;
1848 if (compare != NULL && keyfunc != NULL) {
1849 compare = build_cmpwrapper(compare);
1850 if (compare == NULL)
Hye-Shik Chang19cb1932003-12-10 07:31:08 +00001851 return NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001852 } else
1853 Py_XINCREF(compare);
1854
Tim Petersb9099c32002-11-12 22:08:10 +00001855 /* The list is temporarily made empty, so that mutations performed
1856 * by comparison functions can't affect the slice of memory we're
1857 * sorting (allowing mutations during sorting is a core-dump
1858 * factory, since ob_item may change).
1859 */
1860 saved_ob_size = self->ob_size;
1861 saved_ob_item = self->ob_item;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00001862 saved_allocated = self->allocated;
Tim Petersb9099c32002-11-12 22:08:10 +00001863 self->ob_size = 0;
Tim Peters7049d812004-01-18 20:31:02 +00001864 self->ob_item = empty_ob_item = PyMem_NEW(PyObject *, 0);
Raymond Hettinger4bb95402004-02-13 11:36:39 +00001865 self->allocated = 0;
Tim Peters330f9e92002-07-19 07:05:44 +00001866
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001867 if (keyfunc != NULL) {
1868 for (i=0 ; i < saved_ob_size ; i++) {
1869 value = saved_ob_item[i];
1870 key = PyObject_CallFunctionObjArgs(keyfunc, value,
1871 NULL);
1872 if (key == NULL) {
1873 for (i=i-1 ; i>=0 ; i--) {
1874 kvpair = saved_ob_item[i];
1875 value = sortwrapper_getvalue(kvpair);
1876 saved_ob_item[i] = value;
1877 Py_DECREF(kvpair);
1878 }
1879 if (self->ob_item != empty_ob_item
1880 || self->ob_size) {
1881 /* If the list changed *as well* we
1882 have two errors. We let the first
1883 one "win", but we shouldn't let
1884 what's in the list currently
1885 leak. */
1886 (void)list_ass_slice(
1887 self, 0, self->ob_size,
1888 (PyObject *)NULL);
1889 }
1890
1891 goto dsu_fail;
1892 }
1893 kvpair = build_sortwrapper(key, value);
1894 if (kvpair == NULL)
1895 goto dsu_fail;
1896 saved_ob_item[i] = kvpair;
1897 }
1898 }
1899
1900 /* Reverse sort stability achieved by initially reversing the list,
1901 applying a stable forward sort, then reversing the final result. */
1902 if (reverse && saved_ob_size > 1)
1903 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
1904
1905 merge_init(&ms, compare);
1906
Tim Petersb9099c32002-11-12 22:08:10 +00001907 nremaining = saved_ob_size;
Tim Petersa64dc242002-08-01 02:13:36 +00001908 if (nremaining < 2)
1909 goto succeed;
Tim Peters330f9e92002-07-19 07:05:44 +00001910
Tim Petersa64dc242002-08-01 02:13:36 +00001911 /* March over the array once, left to right, finding natural runs,
1912 * and extending short natural runs to minrun elements.
1913 */
Tim Petersb9099c32002-11-12 22:08:10 +00001914 lo = saved_ob_item;
Tim Petersa64dc242002-08-01 02:13:36 +00001915 hi = lo + nremaining;
1916 minrun = merge_compute_minrun(nremaining);
1917 do {
1918 int descending;
1919 int n;
Tim Peters330f9e92002-07-19 07:05:44 +00001920
Tim Petersa64dc242002-08-01 02:13:36 +00001921 /* Identify next run. */
1922 n = count_run(lo, hi, compare, &descending);
1923 if (n < 0)
1924 goto fail;
1925 if (descending)
1926 reverse_slice(lo, lo + n);
1927 /* If short, extend to min(minrun, nremaining). */
1928 if (n < minrun) {
1929 const int force = nremaining <= minrun ?
1930 nremaining : minrun;
1931 if (binarysort(lo, lo + force, lo + n, compare) < 0)
1932 goto fail;
1933 n = force;
1934 }
1935 /* Push run onto pending-runs stack, and maybe merge. */
1936 assert(ms.n < MAX_MERGE_PENDING);
Tim Peterse05f65a2002-08-10 05:21:15 +00001937 ms.pending[ms.n].base = lo;
1938 ms.pending[ms.n].len = n;
Tim Petersa64dc242002-08-01 02:13:36 +00001939 ++ms.n;
1940 if (merge_collapse(&ms) < 0)
1941 goto fail;
1942 /* Advance to find next run. */
1943 lo += n;
1944 nremaining -= n;
1945 } while (nremaining);
1946 assert(lo == hi);
Tim Peters330f9e92002-07-19 07:05:44 +00001947
Tim Petersa64dc242002-08-01 02:13:36 +00001948 if (merge_force_collapse(&ms) < 0)
1949 goto fail;
1950 assert(ms.n == 1);
Tim Petersb9099c32002-11-12 22:08:10 +00001951 assert(ms.pending[0].base == saved_ob_item);
1952 assert(ms.pending[0].len == saved_ob_size);
Tim Petersa64dc242002-08-01 02:13:36 +00001953
1954succeed:
1955 result = Py_None;
Tim Peters330f9e92002-07-19 07:05:44 +00001956fail:
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001957 if (keyfunc != NULL) {
1958 for (i=0 ; i < saved_ob_size ; i++) {
1959 kvpair = saved_ob_item[i];
1960 value = sortwrapper_getvalue(kvpair);
1961 saved_ob_item[i] = value;
1962 Py_DECREF(kvpair);
1963 }
1964 }
1965
Tim Petersb9099c32002-11-12 22:08:10 +00001966 if (self->ob_item != empty_ob_item || self->ob_size) {
1967 /* The user mucked with the list during the sort. */
1968 (void)list_ass_slice(self, 0, self->ob_size, (PyObject *)NULL);
1969 if (result != NULL) {
1970 PyErr_SetString(PyExc_ValueError,
1971 "list modified during sort");
1972 result = NULL;
1973 }
1974 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001975
1976 if (reverse && saved_ob_size > 1)
1977 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
1978
1979 merge_freemem(&ms);
1980
1981dsu_fail:
Tim Petersb9099c32002-11-12 22:08:10 +00001982 if (self->ob_item == empty_ob_item)
1983 PyMem_FREE(empty_ob_item);
1984 self->ob_size = saved_ob_size;
1985 self->ob_item = saved_ob_item;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00001986 self->allocated = saved_allocated;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001987 Py_XDECREF(compare);
Tim Petersa64dc242002-08-01 02:13:36 +00001988 Py_XINCREF(result);
1989 return result;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001990}
Tim Peters330f9e92002-07-19 07:05:44 +00001991#undef IFLT
Tim Peters66860f62002-08-04 17:47:26 +00001992#undef ISLT
Tim Peters330f9e92002-07-19 07:05:44 +00001993
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001994int
Fred Drakea2f55112000-07-09 15:16:51 +00001995PyList_Sort(PyObject *v)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001996{
1997 if (v == NULL || !PyList_Check(v)) {
1998 PyErr_BadInternalCall();
1999 return -1;
2000 }
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002001 v = listsort((PyListObject *)v, (PyObject *)NULL, (PyObject *)NULL);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002002 if (v == NULL)
2003 return -1;
2004 Py_DECREF(v);
2005 return 0;
2006}
2007
Guido van Rossumb86c5492001-02-12 22:06:02 +00002008static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002009listreverse(PyListObject *self)
Guido van Rossumb86c5492001-02-12 22:06:02 +00002010{
Tim Peters326b4482002-07-19 04:04:16 +00002011 if (self->ob_size > 1)
2012 reverse_slice(self->ob_item, self->ob_item + self->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002013 Py_INCREF(Py_None);
2014 return Py_None;
Guido van Rossumed98d481991-03-06 13:07:53 +00002015}
2016
Guido van Rossum84c76f51990-10-30 13:32:20 +00002017int
Fred Drakea2f55112000-07-09 15:16:51 +00002018PyList_Reverse(PyObject *v)
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002019{
Tim Peters6063e262002-08-08 01:06:39 +00002020 PyListObject *self = (PyListObject *)v;
2021
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002022 if (v == NULL || !PyList_Check(v)) {
2023 PyErr_BadInternalCall();
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002024 return -1;
2025 }
Tim Peters6063e262002-08-08 01:06:39 +00002026 if (self->ob_size > 1)
2027 reverse_slice(self->ob_item, self->ob_item + self->ob_size);
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002028 return 0;
2029}
2030
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002031PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00002032PyList_AsTuple(PyObject *v)
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002033{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002034 PyObject *w;
2035 PyObject **p;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002036 int n;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002037 if (v == NULL || !PyList_Check(v)) {
2038 PyErr_BadInternalCall();
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002039 return NULL;
2040 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002041 n = ((PyListObject *)v)->ob_size;
2042 w = PyTuple_New(n);
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002043 if (w == NULL)
2044 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002045 p = ((PyTupleObject *)w)->ob_item;
Thomas Wouters334fb892000-07-25 12:56:38 +00002046 memcpy((void *)p,
2047 (void *)((PyListObject *)v)->ob_item,
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002048 n*sizeof(PyObject *));
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002049 while (--n >= 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002050 Py_INCREF(*p);
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002051 p++;
2052 }
2053 return w;
2054}
2055
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002056static PyObject *
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002057listindex(PyListObject *self, PyObject *args)
Guido van Rossumed98d481991-03-06 13:07:53 +00002058{
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002059 int i, start=0, stop=self->ob_size;
2060 PyObject *v;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002061
Walter Dörwalde8049bef2003-06-17 19:27:39 +00002062 if (!PyArg_ParseTuple(args, "O|O&O&:index", &v,
2063 _PyEval_SliceIndex, &start,
2064 _PyEval_SliceIndex, &stop))
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002065 return NULL;
Guido van Rossum2743d872003-06-17 14:25:14 +00002066 if (start < 0) {
2067 start += self->ob_size;
2068 if (start < 0)
2069 start = 0;
2070 }
2071 if (stop < 0) {
2072 stop += self->ob_size;
2073 if (stop < 0)
2074 stop = 0;
2075 }
2076 else if (stop > self->ob_size)
2077 stop = self->ob_size;
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002078 for (i = start; i < stop; i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002079 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2080 if (cmp > 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002081 return PyInt_FromLong((long)i);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002082 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002083 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002084 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002085 PyErr_SetString(PyExc_ValueError, "list.index(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00002086 return NULL;
2087}
2088
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002089static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002090listcount(PyListObject *self, PyObject *v)
Guido van Rossume6f7d181991-10-20 20:20:40 +00002091{
2092 int count = 0;
2093 int i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002094
Guido van Rossume6f7d181991-10-20 20:20:40 +00002095 for (i = 0; i < self->ob_size; i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002096 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2097 if (cmp > 0)
Guido van Rossume6f7d181991-10-20 20:20:40 +00002098 count++;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002099 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002100 return NULL;
Guido van Rossume6f7d181991-10-20 20:20:40 +00002101 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002102 return PyInt_FromLong((long)count);
Guido van Rossume6f7d181991-10-20 20:20:40 +00002103}
2104
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002105static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002106listremove(PyListObject *self, PyObject *v)
Guido van Rossumed98d481991-03-06 13:07:53 +00002107{
2108 int i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002109
Guido van Rossumed98d481991-03-06 13:07:53 +00002110 for (i = 0; i < self->ob_size; i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002111 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2112 if (cmp > 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002113 if (list_ass_slice(self, i, i+1,
2114 (PyObject *)NULL) != 0)
Guido van Rossumed98d481991-03-06 13:07:53 +00002115 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002116 Py_INCREF(Py_None);
2117 return Py_None;
Guido van Rossumed98d481991-03-06 13:07:53 +00002118 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002119 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002120 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002121 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002122 PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00002123 return NULL;
2124}
2125
Jeremy Hylton8caad492000-06-23 14:18:11 +00002126static int
2127list_traverse(PyListObject *o, visitproc visit, void *arg)
2128{
2129 int i, err;
2130 PyObject *x;
2131
2132 for (i = o->ob_size; --i >= 0; ) {
2133 x = o->ob_item[i];
2134 if (x != NULL) {
2135 err = visit(x, arg);
2136 if (err)
2137 return err;
2138 }
2139 }
2140 return 0;
2141}
2142
2143static int
2144list_clear(PyListObject *lp)
2145{
2146 (void) PyList_SetSlice((PyObject *)lp, 0, lp->ob_size, 0);
2147 return 0;
2148}
2149
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002150static PyObject *
2151list_richcompare(PyObject *v, PyObject *w, int op)
2152{
2153 PyListObject *vl, *wl;
2154 int i;
2155
2156 if (!PyList_Check(v) || !PyList_Check(w)) {
2157 Py_INCREF(Py_NotImplemented);
2158 return Py_NotImplemented;
2159 }
2160
2161 vl = (PyListObject *)v;
2162 wl = (PyListObject *)w;
2163
2164 if (vl->ob_size != wl->ob_size && (op == Py_EQ || op == Py_NE)) {
2165 /* Shortcut: if the lengths differ, the lists differ */
2166 PyObject *res;
2167 if (op == Py_EQ)
2168 res = Py_False;
2169 else
2170 res = Py_True;
2171 Py_INCREF(res);
2172 return res;
2173 }
2174
2175 /* Search for the first index where items are different */
2176 for (i = 0; i < vl->ob_size && i < wl->ob_size; i++) {
2177 int k = PyObject_RichCompareBool(vl->ob_item[i],
2178 wl->ob_item[i], Py_EQ);
2179 if (k < 0)
2180 return NULL;
2181 if (!k)
2182 break;
2183 }
2184
2185 if (i >= vl->ob_size || i >= wl->ob_size) {
2186 /* No more items to compare -- compare sizes */
2187 int vs = vl->ob_size;
2188 int ws = wl->ob_size;
2189 int cmp;
2190 PyObject *res;
2191 switch (op) {
2192 case Py_LT: cmp = vs < ws; break;
Tim Peters6ee42342001-07-06 17:45:43 +00002193 case Py_LE: cmp = vs <= ws; break;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002194 case Py_EQ: cmp = vs == ws; break;
2195 case Py_NE: cmp = vs != ws; break;
2196 case Py_GT: cmp = vs > ws; break;
2197 case Py_GE: cmp = vs >= ws; break;
2198 default: return NULL; /* cannot happen */
2199 }
2200 if (cmp)
2201 res = Py_True;
2202 else
2203 res = Py_False;
2204 Py_INCREF(res);
2205 return res;
2206 }
2207
2208 /* We have an item that differs -- shortcuts for EQ/NE */
2209 if (op == Py_EQ) {
2210 Py_INCREF(Py_False);
2211 return Py_False;
2212 }
2213 if (op == Py_NE) {
2214 Py_INCREF(Py_True);
2215 return Py_True;
2216 }
2217
2218 /* Compare the final item again using the proper operator */
2219 return PyObject_RichCompare(vl->ob_item[i], wl->ob_item[i], op);
2220}
2221
Tim Peters6d6c1a32001-08-02 04:15:00 +00002222/* Adapted from newer code by Tim */
2223static int
2224list_fill(PyListObject *result, PyObject *v)
2225{
2226 PyObject *it; /* iter(v) */
2227 int n; /* guess for result list size */
2228 int i;
2229
2230 n = result->ob_size;
2231
Jeremy Hylton30973412003-12-26 19:05:04 +00002232 /* Special-case list(a_list), for speed. */
2233 if (PyList_Check(v)) {
2234 if (v == (PyObject *)result)
2235 return 0; /* source is destination, we're done */
2236 return list_ass_slice(result, 0, n, v);
2237 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002238
2239 /* Empty previous contents */
2240 if (n != 0) {
2241 if (list_ass_slice(result, 0, n, (PyObject *)NULL) != 0)
2242 return -1;
2243 }
2244
2245 /* Get iterator. There may be some low-level efficiency to be gained
2246 * by caching the tp_iternext slot instead of using PyIter_Next()
2247 * later, but premature optimization is the root etc.
2248 */
2249 it = PyObject_GetIter(v);
2250 if (it == NULL)
2251 return -1;
2252
2253 /* Guess a result list size. */
Raymond Hettinger7832cd62004-01-04 06:08:16 +00002254 n = PyObject_Size(v);
2255 if (n < 0) {
2256 PyErr_Clear();
Tim Peters6d6c1a32001-08-02 04:15:00 +00002257 n = 8; /* arbitrary */
Raymond Hettinger7832cd62004-01-04 06:08:16 +00002258 }
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002259 if (list_resize(result, n) == -1)
Tim Peters6d6c1a32001-08-02 04:15:00 +00002260 goto error;
Neal Norwitz35fc7602002-06-13 21:11:11 +00002261 memset(result->ob_item, 0, sizeof(*result->ob_item) * n);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002262
2263 /* Run iterator to exhaustion. */
2264 for (i = 0; ; i++) {
2265 PyObject *item = PyIter_Next(it);
2266 if (item == NULL) {
2267 if (PyErr_Occurred())
2268 goto error;
2269 break;
2270 }
2271 if (i < n)
2272 PyList_SET_ITEM(result, i, item); /* steals ref */
2273 else {
2274 int status = ins1(result, result->ob_size, item);
2275 Py_DECREF(item); /* append creates a new ref */
2276 if (status < 0)
2277 goto error;
2278 }
2279 }
2280
2281 /* Cut back result list if initial guess was too large. */
2282 if (i < n && result != NULL) {
2283 if (list_ass_slice(result, i, n, (PyObject *)NULL) != 0)
2284 goto error;
2285 }
2286 Py_DECREF(it);
2287 return 0;
2288
2289 error:
2290 Py_DECREF(it);
2291 return -1;
2292}
2293
2294static int
2295list_init(PyListObject *self, PyObject *args, PyObject *kw)
2296{
2297 PyObject *arg = NULL;
2298 static char *kwlist[] = {"sequence", 0};
2299
2300 if (!PyArg_ParseTupleAndKeywords(args, kw, "|O:list", kwlist, &arg))
2301 return -1;
2302 if (arg != NULL)
2303 return list_fill(self, arg);
2304 if (self->ob_size > 0)
2305 return list_ass_slice(self, 0, self->ob_size, (PyObject*)NULL);
2306 return 0;
2307}
2308
Guido van Rossumdbb53d92001-12-03 16:32:18 +00002309static long
2310list_nohash(PyObject *self)
2311{
2312 PyErr_SetString(PyExc_TypeError, "list objects are unhashable");
2313 return -1;
2314}
2315
Raymond Hettinger1021c442003-11-07 15:38:09 +00002316static PyObject *list_iter(PyObject *seq);
2317static PyObject *list_reversed(PyListObject* seq, PyObject* unused);
2318
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002319PyDoc_STRVAR(getitem_doc,
2320"x.__getitem__(y) <==> x[y]");
Raymond Hettinger1021c442003-11-07 15:38:09 +00002321PyDoc_STRVAR(reversed_doc,
2322"L.__reversed__() -- return a reverse iterator over the list");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002323PyDoc_STRVAR(append_doc,
2324"L.append(object) -- append object to end");
2325PyDoc_STRVAR(extend_doc,
Raymond Hettingerf8bcfb12002-12-29 05:49:09 +00002326"L.extend(iterable) -- extend list by appending elements from the iterable");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002327PyDoc_STRVAR(insert_doc,
2328"L.insert(index, object) -- insert object before index");
2329PyDoc_STRVAR(pop_doc,
2330"L.pop([index]) -> item -- remove and return item at index (default last)");
2331PyDoc_STRVAR(remove_doc,
2332"L.remove(value) -- remove first occurrence of value");
2333PyDoc_STRVAR(index_doc,
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002334"L.index(value, [start, [stop]]) -> integer -- return first index of value");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002335PyDoc_STRVAR(count_doc,
2336"L.count(value) -> integer -- return number of occurrences of value");
2337PyDoc_STRVAR(reverse_doc,
2338"L.reverse() -- reverse *IN PLACE*");
2339PyDoc_STRVAR(sort_doc,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002340"L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;\n\
2341cmp(x, y) -> -1, 0, 1");
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +00002342
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002343static PyObject *list_subscript(PyListObject*, PyObject*);
2344
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002345static PyMethodDef list_methods[] = {
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002346 {"__getitem__", (PyCFunction)list_subscript, METH_O|METH_COEXIST, getitem_doc},
Raymond Hettinger1021c442003-11-07 15:38:09 +00002347 {"__reversed__",(PyCFunction)list_reversed, METH_NOARGS, reversed_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002348 {"append", (PyCFunction)listappend, METH_O, append_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002349 {"insert", (PyCFunction)listinsert, METH_VARARGS, insert_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002350 {"extend", (PyCFunction)listextend, METH_O, extend_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002351 {"pop", (PyCFunction)listpop, METH_VARARGS, pop_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002352 {"remove", (PyCFunction)listremove, METH_O, remove_doc},
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002353 {"index", (PyCFunction)listindex, METH_VARARGS, index_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002354 {"count", (PyCFunction)listcount, METH_O, count_doc},
2355 {"reverse", (PyCFunction)listreverse, METH_NOARGS, reverse_doc},
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002356 {"sort", (PyCFunction)listsort, METH_VARARGS | METH_KEYWORDS, sort_doc},
Tim Petersa64dc242002-08-01 02:13:36 +00002357 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002358};
2359
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002360static PySequenceMethods list_as_sequence = {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002361 (inquiry)list_length, /* sq_length */
2362 (binaryfunc)list_concat, /* sq_concat */
2363 (intargfunc)list_repeat, /* sq_repeat */
2364 (intargfunc)list_item, /* sq_item */
2365 (intintargfunc)list_slice, /* sq_slice */
2366 (intobjargproc)list_ass_item, /* sq_ass_item */
2367 (intintobjargproc)list_ass_slice, /* sq_ass_slice */
2368 (objobjproc)list_contains, /* sq_contains */
2369 (binaryfunc)list_inplace_concat, /* sq_inplace_concat */
2370 (intargfunc)list_inplace_repeat, /* sq_inplace_repeat */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002371};
2372
Neal Norwitz2c2e8272002-06-14 02:04:18 +00002373PyDoc_STRVAR(list_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002374"list() -> new list\n"
Neal Norwitz2c2e8272002-06-14 02:04:18 +00002375"list(sequence) -> new list initialized from sequence's items");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002376
Jeremy Hyltona4b4c3b2002-07-13 03:51:17 +00002377static PyObject *
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002378list_subscript(PyListObject* self, PyObject* item)
2379{
2380 if (PyInt_Check(item)) {
2381 long i = PyInt_AS_LONG(item);
2382 if (i < 0)
2383 i += PyList_GET_SIZE(self);
2384 return list_item(self, i);
2385 }
2386 else if (PyLong_Check(item)) {
2387 long i = PyLong_AsLong(item);
2388 if (i == -1 && PyErr_Occurred())
2389 return NULL;
2390 if (i < 0)
2391 i += PyList_GET_SIZE(self);
2392 return list_item(self, i);
2393 }
2394 else if (PySlice_Check(item)) {
2395 int start, stop, step, slicelength, cur, i;
2396 PyObject* result;
2397 PyObject* it;
2398
2399 if (PySlice_GetIndicesEx((PySliceObject*)item, self->ob_size,
2400 &start, &stop, &step, &slicelength) < 0) {
2401 return NULL;
2402 }
2403
2404 if (slicelength <= 0) {
2405 return PyList_New(0);
2406 }
2407 else {
2408 result = PyList_New(slicelength);
2409 if (!result) return NULL;
2410
Tim Peters3b01a122002-07-19 02:35:45 +00002411 for (cur = start, i = 0; i < slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002412 cur += step, i++) {
2413 it = PyList_GET_ITEM(self, cur);
2414 Py_INCREF(it);
2415 PyList_SET_ITEM(result, i, it);
2416 }
Tim Peters3b01a122002-07-19 02:35:45 +00002417
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002418 return result;
2419 }
2420 }
2421 else {
2422 PyErr_SetString(PyExc_TypeError,
2423 "list indices must be integers");
2424 return NULL;
2425 }
2426}
2427
Tim Peters3b01a122002-07-19 02:35:45 +00002428static int
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002429list_ass_subscript(PyListObject* self, PyObject* item, PyObject* value)
2430{
2431 if (PyInt_Check(item)) {
2432 long i = PyInt_AS_LONG(item);
2433 if (i < 0)
2434 i += PyList_GET_SIZE(self);
2435 return list_ass_item(self, i, value);
2436 }
2437 else if (PyLong_Check(item)) {
2438 long i = PyLong_AsLong(item);
2439 if (i == -1 && PyErr_Occurred())
2440 return -1;
2441 if (i < 0)
2442 i += PyList_GET_SIZE(self);
2443 return list_ass_item(self, i, value);
2444 }
2445 else if (PySlice_Check(item)) {
2446 int start, stop, step, slicelength;
2447
2448 if (PySlice_GetIndicesEx((PySliceObject*)item, self->ob_size,
2449 &start, &stop, &step, &slicelength) < 0) {
2450 return -1;
2451 }
2452
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002453 /* treat L[slice(a,b)] = v _exactly_ like L[a:b] = v */
2454 if (step == 1 && ((PySliceObject*)item)->step == Py_None)
2455 return list_ass_slice(self, start, stop, value);
2456
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002457 if (value == NULL) {
2458 /* delete slice */
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002459 PyObject **garbage;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002460 int cur, i, j;
Tim Peters3b01a122002-07-19 02:35:45 +00002461
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002462 if (slicelength <= 0)
2463 return 0;
2464
2465 if (step < 0) {
2466 stop = start + 1;
2467 start = stop + step*(slicelength - 1) - 1;
2468 step = -step;
2469 }
2470
2471 garbage = (PyObject**)
2472 PyMem_MALLOC(slicelength*sizeof(PyObject*));
Tim Peters3b01a122002-07-19 02:35:45 +00002473
2474 /* drawing pictures might help
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002475 understand these for loops */
Guido van Rossum75a20b12002-06-11 12:22:28 +00002476 for (cur = start, i = 0;
2477 cur < stop;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002478 cur += step, i++) {
2479 int lim = step;
2480
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002481 garbage[i] = PyList_GET_ITEM(self, cur);
2482
Michael W. Hudson56796f62002-07-29 14:35:04 +00002483 if (cur + step >= self->ob_size) {
2484 lim = self->ob_size - cur - 1;
2485 }
2486
2487 for (j = 0; j < lim; j++) {
Tim Peters3b01a122002-07-19 02:35:45 +00002488 PyList_SET_ITEM(self, cur + j - i,
Guido van Rossum75a20b12002-06-11 12:22:28 +00002489 PyList_GET_ITEM(self,
2490 cur + j + 1));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002491 }
2492 }
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002493 for (cur = start + slicelength*step + 1;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002494 cur < self->ob_size; cur++) {
2495 PyList_SET_ITEM(self, cur - slicelength,
2496 PyList_GET_ITEM(self, cur));
2497 }
2498 self->ob_size -= slicelength;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002499 list_resize(self, self->ob_size);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002500
2501 for (i = 0; i < slicelength; i++) {
2502 Py_DECREF(garbage[i]);
2503 }
2504 PyMem_FREE(garbage);
2505
2506 return 0;
2507 }
2508 else {
2509 /* assign slice */
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002510 PyObject **garbage, *ins, *seq;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002511 int cur, i;
2512
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002513 /* protect against a[::-1] = a */
Tim Peters3b01a122002-07-19 02:35:45 +00002514 if (self == (PyListObject*)value) {
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002515 seq = list_slice((PyListObject*)value, 0,
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002516 PyList_GET_SIZE(value));
Tim Peters3b01a122002-07-19 02:35:45 +00002517 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002518 else {
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002519 char msg[256];
2520 PyOS_snprintf(msg, sizeof(msg),
2521 "must assign sequence (not \"%.200s\") to extended slice",
2522 value->ob_type->tp_name);
2523 seq = PySequence_Fast(value, msg);
2524 if (!seq)
2525 return -1;
2526 }
2527
2528 if (PySequence_Fast_GET_SIZE(seq) != slicelength) {
2529 PyErr_Format(PyExc_ValueError,
2530 "attempt to assign sequence of size %d to extended slice of size %d",
2531 PySequence_Fast_GET_SIZE(seq),
2532 slicelength);
2533 Py_DECREF(seq);
2534 return -1;
2535 }
2536
2537 if (!slicelength) {
2538 Py_DECREF(seq);
2539 return 0;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002540 }
2541
2542 garbage = (PyObject**)
2543 PyMem_MALLOC(slicelength*sizeof(PyObject*));
Tim Peters3b01a122002-07-19 02:35:45 +00002544
2545 for (cur = start, i = 0; i < slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002546 cur += step, i++) {
2547 garbage[i] = PyList_GET_ITEM(self, cur);
Tim Peters3b01a122002-07-19 02:35:45 +00002548
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002549 ins = PySequence_Fast_GET_ITEM(seq, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002550 Py_INCREF(ins);
2551 PyList_SET_ITEM(self, cur, ins);
2552 }
2553
2554 for (i = 0; i < slicelength; i++) {
2555 Py_DECREF(garbage[i]);
2556 }
Tim Peters3b01a122002-07-19 02:35:45 +00002557
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002558 PyMem_FREE(garbage);
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002559 Py_DECREF(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002560
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002561 return 0;
2562 }
Tim Peters3b01a122002-07-19 02:35:45 +00002563 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002564 else {
Tim Peters3b01a122002-07-19 02:35:45 +00002565 PyErr_SetString(PyExc_TypeError,
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002566 "list indices must be integers");
2567 return -1;
2568 }
2569}
2570
2571static PyMappingMethods list_as_mapping = {
2572 (inquiry)list_length,
2573 (binaryfunc)list_subscript,
2574 (objobjargproc)list_ass_subscript
2575};
2576
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002577PyTypeObject PyList_Type = {
2578 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002579 0,
2580 "list",
Neil Schemenauere83c00e2001-08-29 23:54:21 +00002581 sizeof(PyListObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002582 0,
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002583 (destructor)list_dealloc, /* tp_dealloc */
2584 (printfunc)list_print, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002585 0, /* tp_getattr */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002586 0, /* tp_setattr */
2587 0, /* tp_compare */
2588 (reprfunc)list_repr, /* tp_repr */
2589 0, /* tp_as_number */
2590 &list_as_sequence, /* tp_as_sequence */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002591 &list_as_mapping, /* tp_as_mapping */
Guido van Rossumdbb53d92001-12-03 16:32:18 +00002592 list_nohash, /* tp_hash */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002593 0, /* tp_call */
2594 0, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002595 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002596 0, /* tp_setattro */
2597 0, /* tp_as_buffer */
Neil Schemenauere83c00e2001-08-29 23:54:21 +00002598 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Tim Peters6d6c1a32001-08-02 04:15:00 +00002599 Py_TPFLAGS_BASETYPE, /* tp_flags */
2600 list_doc, /* tp_doc */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002601 (traverseproc)list_traverse, /* tp_traverse */
2602 (inquiry)list_clear, /* tp_clear */
2603 list_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002604 0, /* tp_weaklistoffset */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002605 list_iter, /* tp_iter */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002606 0, /* tp_iternext */
2607 list_methods, /* tp_methods */
2608 0, /* tp_members */
2609 0, /* tp_getset */
2610 0, /* tp_base */
2611 0, /* tp_dict */
2612 0, /* tp_descr_get */
2613 0, /* tp_descr_set */
2614 0, /* tp_dictoffset */
2615 (initproc)list_init, /* tp_init */
2616 PyType_GenericAlloc, /* tp_alloc */
2617 PyType_GenericNew, /* tp_new */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002618 PyObject_GC_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002619};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002620
2621
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002622/*********************** List Iterator **************************/
2623
2624typedef struct {
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002625 PyObject_HEAD
2626 long it_index;
Guido van Rossum86103ae2002-07-16 20:07:32 +00002627 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002628} listiterobject;
2629
2630PyTypeObject PyListIter_Type;
2631
Guido van Rossum5086e492002-07-16 15:56:52 +00002632static PyObject *
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002633list_iter(PyObject *seq)
2634{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002635 listiterobject *it;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002636
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002637 if (!PyList_Check(seq)) {
2638 PyErr_BadInternalCall();
2639 return NULL;
2640 }
2641 it = PyObject_GC_New(listiterobject, &PyListIter_Type);
2642 if (it == NULL)
2643 return NULL;
2644 it->it_index = 0;
2645 Py_INCREF(seq);
2646 it->it_seq = (PyListObject *)seq;
2647 _PyObject_GC_TRACK(it);
2648 return (PyObject *)it;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002649}
2650
2651static void
2652listiter_dealloc(listiterobject *it)
2653{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002654 _PyObject_GC_UNTRACK(it);
Guido van Rossum86103ae2002-07-16 20:07:32 +00002655 Py_XDECREF(it->it_seq);
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002656 PyObject_GC_Del(it);
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002657}
2658
2659static int
2660listiter_traverse(listiterobject *it, visitproc visit, void *arg)
2661{
Guido van Rossum86103ae2002-07-16 20:07:32 +00002662 if (it->it_seq == NULL)
2663 return 0;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002664 return visit((PyObject *)it->it_seq, arg);
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002665}
2666
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002667static PyObject *
Tim Peters93b2cc42002-06-01 05:22:55 +00002668listiter_next(listiterobject *it)
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002669{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002670 PyListObject *seq;
2671 PyObject *item;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002672
Tim Peters93b2cc42002-06-01 05:22:55 +00002673 assert(it != NULL);
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002674 seq = it->it_seq;
Guido van Rossum86103ae2002-07-16 20:07:32 +00002675 if (seq == NULL)
2676 return NULL;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002677 assert(PyList_Check(seq));
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002678
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002679 if (it->it_index < PyList_GET_SIZE(seq)) {
Tim Peters93b2cc42002-06-01 05:22:55 +00002680 item = PyList_GET_ITEM(seq, it->it_index);
2681 ++it->it_index;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002682 Py_INCREF(item);
2683 return item;
2684 }
Guido van Rossum86103ae2002-07-16 20:07:32 +00002685
2686 Py_DECREF(seq);
2687 it->it_seq = NULL;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002688 return NULL;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002689}
2690
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002691PyTypeObject PyListIter_Type = {
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002692 PyObject_HEAD_INIT(&PyType_Type)
2693 0, /* ob_size */
2694 "listiterator", /* tp_name */
2695 sizeof(listiterobject), /* tp_basicsize */
2696 0, /* tp_itemsize */
2697 /* methods */
2698 (destructor)listiter_dealloc, /* tp_dealloc */
2699 0, /* tp_print */
2700 0, /* tp_getattr */
2701 0, /* tp_setattr */
2702 0, /* tp_compare */
2703 0, /* tp_repr */
2704 0, /* tp_as_number */
2705 0, /* tp_as_sequence */
2706 0, /* tp_as_mapping */
2707 0, /* tp_hash */
2708 0, /* tp_call */
2709 0, /* tp_str */
2710 PyObject_GenericGetAttr, /* tp_getattro */
2711 0, /* tp_setattro */
2712 0, /* tp_as_buffer */
2713 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2714 0, /* tp_doc */
2715 (traverseproc)listiter_traverse, /* tp_traverse */
2716 0, /* tp_clear */
2717 0, /* tp_richcompare */
2718 0, /* tp_weaklistoffset */
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +00002719 PyObject_SelfIter, /* tp_iter */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002720 (iternextfunc)listiter_next, /* tp_iternext */
Guido van Rossum86103ae2002-07-16 20:07:32 +00002721 0, /* tp_methods */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002722 0, /* tp_members */
2723 0, /* tp_getset */
2724 0, /* tp_base */
2725 0, /* tp_dict */
2726 0, /* tp_descr_get */
2727 0, /* tp_descr_set */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002728};
Raymond Hettinger1021c442003-11-07 15:38:09 +00002729
2730/*********************** List Reverse Iterator **************************/
2731
2732typedef struct {
2733 PyObject_HEAD
2734 long it_index;
Raymond Hettinger001f2282003-11-08 11:58:44 +00002735 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger1021c442003-11-07 15:38:09 +00002736} listreviterobject;
2737
2738PyTypeObject PyListRevIter_Type;
2739
2740static PyObject *
2741list_reversed(PyListObject *seq, PyObject *unused)
2742{
2743 listreviterobject *it;
2744
2745 it = PyObject_GC_New(listreviterobject, &PyListRevIter_Type);
2746 if (it == NULL)
2747 return NULL;
2748 assert(PyList_Check(seq));
2749 it->it_index = PyList_GET_SIZE(seq) - 1;
2750 Py_INCREF(seq);
2751 it->it_seq = seq;
2752 PyObject_GC_Track(it);
2753 return (PyObject *)it;
2754}
2755
2756static void
2757listreviter_dealloc(listreviterobject *it)
2758{
2759 PyObject_GC_UnTrack(it);
2760 Py_XDECREF(it->it_seq);
2761 PyObject_GC_Del(it);
2762}
2763
2764static int
2765listreviter_traverse(listreviterobject *it, visitproc visit, void *arg)
2766{
2767 if (it->it_seq == NULL)
2768 return 0;
2769 return visit((PyObject *)it->it_seq, arg);
2770}
2771
2772static PyObject *
2773listreviter_next(listreviterobject *it)
2774{
2775 PyObject *item = NULL;
2776
2777 assert(PyList_Check(it->it_seq));
2778 if (it->it_index >= 0) {
2779 assert(it->it_index < PyList_GET_SIZE(it->it_seq));
2780 item = PyList_GET_ITEM(it->it_seq, it->it_index);
2781 it->it_index--;
2782 Py_INCREF(item);
Raymond Hettinger001f2282003-11-08 11:58:44 +00002783 } else if (it->it_seq != NULL) {
2784 Py_DECREF(it->it_seq);
2785 it->it_seq = NULL;
Raymond Hettinger1021c442003-11-07 15:38:09 +00002786 }
2787 return item;
2788}
2789
2790PyTypeObject PyListRevIter_Type = {
2791 PyObject_HEAD_INIT(&PyType_Type)
2792 0, /* ob_size */
2793 "listreverseiterator", /* tp_name */
2794 sizeof(listreviterobject), /* tp_basicsize */
2795 0, /* tp_itemsize */
2796 /* methods */
2797 (destructor)listreviter_dealloc, /* tp_dealloc */
2798 0, /* tp_print */
2799 0, /* tp_getattr */
2800 0, /* tp_setattr */
2801 0, /* tp_compare */
2802 0, /* tp_repr */
2803 0, /* tp_as_number */
2804 0, /* tp_as_sequence */
2805 0, /* tp_as_mapping */
2806 0, /* tp_hash */
2807 0, /* tp_call */
2808 0, /* tp_str */
2809 PyObject_GenericGetAttr, /* tp_getattro */
2810 0, /* tp_setattro */
2811 0, /* tp_as_buffer */
2812 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2813 0, /* tp_doc */
2814 (traverseproc)listreviter_traverse, /* tp_traverse */
2815 0, /* tp_clear */
2816 0, /* tp_richcompare */
2817 0, /* tp_weaklistoffset */
2818 PyObject_SelfIter, /* tp_iter */
2819 (iternextfunc)listreviter_next, /* tp_iternext */
2820 0,
2821};