blob: a5bacf3a52e04d98b401073dafc9ff4ff3d8f04e [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
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00008#include <sys/types.h> /* For size_t */
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00009#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000010
Tim Peters8d9eb102004-07-31 02:24:20 +000011/* Ensure ob_item has room for at least newsize elements, and set
12 * ob_size to newsize. If newsize > ob_size on entry, the content
13 * of the new slots at exit is undefined heap trash; it's the caller's
14 * responsiblity to overwrite them with sane values.
15 * The number of allocated elements may grow, shrink, or stay the same.
16 * Failure is impossible if newsize <= self.allocated on entry, although
17 * that partly relies on an assumption that the system realloc() never
18 * fails when passed a number of bytes <= the number of bytes last
19 * allocated (the C standard doesn't guarantee this, but it's hard to
20 * imagine a realloc implementation where it wouldn't be true).
21 * Note that self->ob_item may change, and even if newsize is less
22 * than ob_size on entry.
23 */
Guido van Rossuma46d51d1995-01-26 22:59:43 +000024static int
Martin v. Löwis18e16552006-02-15 17:27:45 +000025list_resize(PyListObject *self, Py_ssize_t newsize)
Guido van Rossuma46d51d1995-01-26 22:59:43 +000026{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +000027 PyObject **items;
28 size_t new_allocated;
29 Py_ssize_t allocated = self->allocated;
Tim Peters65b8b842001-05-26 05:28:40 +000030
Antoine Pitrouc7c96a92010-05-09 15:15:40 +000031 /* Bypass realloc() when a previous overallocation is large enough
32 to accommodate the newsize. If the newsize falls lower than half
33 the allocated size, then proceed with the realloc() to shrink the list.
34 */
35 if (allocated >= newsize && newsize >= (allocated >> 1)) {
36 assert(self->ob_item != NULL || newsize == 0);
37 Py_SIZE(self) = newsize;
38 return 0;
39 }
Raymond Hettinger4bb95402004-02-13 11:36:39 +000040
Antoine Pitrouc7c96a92010-05-09 15:15:40 +000041 /* This over-allocates proportional to the list size, making room
42 * for additional growth. The over-allocation is mild, but is
43 * enough to give linear-time amortized behavior over a long
44 * sequence of appends() in the presence of a poorly-performing
45 * system realloc().
46 * The growth pattern is: 0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ...
47 */
48 new_allocated = (newsize >> 3) + (newsize < 9 ? 3 : 6);
Gregory P. Smith9d534572008-06-11 07:41:16 +000049
Antoine Pitrouc7c96a92010-05-09 15:15:40 +000050 /* check for integer overflow */
51 if (new_allocated > PY_SIZE_MAX - newsize) {
52 PyErr_NoMemory();
53 return -1;
54 } else {
55 new_allocated += newsize;
56 }
Gregory P. Smith9d534572008-06-11 07:41:16 +000057
Antoine Pitrouc7c96a92010-05-09 15:15:40 +000058 if (newsize == 0)
59 new_allocated = 0;
60 items = self->ob_item;
61 if (new_allocated <= ((~(size_t)0) / sizeof(PyObject *)))
62 PyMem_RESIZE(items, PyObject *, new_allocated);
63 else
64 items = NULL;
65 if (items == NULL) {
66 PyErr_NoMemory();
67 return -1;
68 }
69 self->ob_item = items;
70 Py_SIZE(self) = newsize;
71 self->allocated = new_allocated;
72 return 0;
Raymond Hettinger4bb95402004-02-13 11:36:39 +000073}
Guido van Rossuma46d51d1995-01-26 22:59:43 +000074
Christian Heimesb4ee4a12008-02-07 17:15:30 +000075/* Debug statistic to compare allocations with reuse through the free list */
76#undef SHOW_ALLOC_COUNT
77#ifdef SHOW_ALLOC_COUNT
78static size_t count_alloc = 0;
79static size_t count_reuse = 0;
80
81static void
82show_alloc(void)
83{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +000084 fprintf(stderr, "List allocations: %" PY_FORMAT_SIZE_T "d\n",
85 count_alloc);
86 fprintf(stderr, "List reuse through freelist: %" PY_FORMAT_SIZE_T
87 "d\n", count_reuse);
88 fprintf(stderr, "%.2f%% reuse rate\n\n",
89 (100.0*count_reuse/(count_alloc+count_reuse)));
Christian Heimesb4ee4a12008-02-07 17:15:30 +000090}
91#endif
92
Raymond Hettinger0468e412004-05-05 05:37:53 +000093/* Empty list reuse scheme to save calls to malloc and free */
Christian Heimes5b970ad2008-02-06 13:33:44 +000094#ifndef PyList_MAXFREELIST
95#define PyList_MAXFREELIST 80
96#endif
97static PyListObject *free_list[PyList_MAXFREELIST];
98static int numfree = 0;
Raymond Hettinger0468e412004-05-05 05:37:53 +000099
Raymond Hettingerfb09f0e2004-10-07 03:58:07 +0000100void
101PyList_Fini(void)
102{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000103 PyListObject *op;
Raymond Hettingerfb09f0e2004-10-07 03:58:07 +0000104
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000105 while (numfree) {
106 op = free_list[--numfree];
107 assert(PyList_CheckExact(op));
108 PyObject_GC_Del(op);
109 }
Raymond Hettingerfb09f0e2004-10-07 03:58:07 +0000110}
111
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000112PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000113PyList_New(Py_ssize_t size)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000114{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000115 PyListObject *op;
116 size_t nbytes;
Christian Heimesb4ee4a12008-02-07 17:15:30 +0000117#ifdef SHOW_ALLOC_COUNT
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000118 static int initialized = 0;
119 if (!initialized) {
120 Py_AtExit(show_alloc);
121 initialized = 1;
122 }
Christian Heimesb4ee4a12008-02-07 17:15:30 +0000123#endif
Tim Peters3986d4e2004-07-29 02:28:42 +0000124
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000125 if (size < 0) {
126 PyErr_BadInternalCall();
127 return NULL;
128 }
129 /* Check for overflow without an actual overflow,
130 * which can cause compiler to optimise out */
131 if ((size_t)size > PY_SIZE_MAX / sizeof(PyObject *))
132 return PyErr_NoMemory();
133 nbytes = size * sizeof(PyObject *);
134 if (numfree) {
135 numfree--;
136 op = free_list[numfree];
137 _Py_NewReference((PyObject *)op);
Christian Heimesb4ee4a12008-02-07 17:15:30 +0000138#ifdef SHOW_ALLOC_COUNT
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000139 count_reuse++;
Christian Heimesb4ee4a12008-02-07 17:15:30 +0000140#endif
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000141 } else {
142 op = PyObject_GC_New(PyListObject, &PyList_Type);
143 if (op == NULL)
144 return NULL;
Christian Heimesb4ee4a12008-02-07 17:15:30 +0000145#ifdef SHOW_ALLOC_COUNT
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000146 count_alloc++;
Christian Heimesb4ee4a12008-02-07 17:15:30 +0000147#endif
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000148 }
149 if (size <= 0)
150 op->ob_item = NULL;
151 else {
152 op->ob_item = (PyObject **) PyMem_MALLOC(nbytes);
153 if (op->ob_item == NULL) {
154 Py_DECREF(op);
155 return PyErr_NoMemory();
156 }
157 memset(op->ob_item, 0, nbytes);
158 }
159 Py_SIZE(op) = size;
160 op->allocated = size;
161 _PyObject_GC_TRACK(op);
162 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000163}
164
Martin v. Löwis18e16552006-02-15 17:27:45 +0000165Py_ssize_t
Fred Drakea2f55112000-07-09 15:16:51 +0000166PyList_Size(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000167{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000168 if (!PyList_Check(op)) {
169 PyErr_BadInternalCall();
170 return -1;
171 }
172 else
173 return Py_SIZE(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000174}
175
Raymond Hettingerfdfe6182004-05-05 06:28:16 +0000176static PyObject *indexerr = NULL;
Guido van Rossum929f1b81996-08-09 20:51:27 +0000177
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000178PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000179PyList_GetItem(PyObject *op, Py_ssize_t i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000180{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000181 if (!PyList_Check(op)) {
182 PyErr_BadInternalCall();
183 return NULL;
184 }
185 if (i < 0 || i >= Py_SIZE(op)) {
186 if (indexerr == NULL)
187 indexerr = PyString_FromString(
188 "list index out of range");
189 PyErr_SetObject(PyExc_IndexError, indexerr);
190 return NULL;
191 }
192 return ((PyListObject *)op) -> ob_item[i];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000193}
194
195int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000196PyList_SetItem(register PyObject *op, register Py_ssize_t i,
Fred Drakea2f55112000-07-09 15:16:51 +0000197 register PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000198{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000199 register PyObject *olditem;
200 register PyObject **p;
201 if (!PyList_Check(op)) {
202 Py_XDECREF(newitem);
203 PyErr_BadInternalCall();
204 return -1;
205 }
206 if (i < 0 || i >= Py_SIZE(op)) {
207 Py_XDECREF(newitem);
208 PyErr_SetString(PyExc_IndexError,
209 "list assignment index out of range");
210 return -1;
211 }
212 p = ((PyListObject *)op) -> ob_item + i;
213 olditem = *p;
214 *p = newitem;
215 Py_XDECREF(olditem);
216 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000217}
218
219static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000220ins1(PyListObject *self, Py_ssize_t where, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000221{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000222 Py_ssize_t i, n = Py_SIZE(self);
223 PyObject **items;
224 if (v == NULL) {
225 PyErr_BadInternalCall();
226 return -1;
227 }
228 if (n == PY_SSIZE_T_MAX) {
229 PyErr_SetString(PyExc_OverflowError,
230 "cannot add more objects to list");
231 return -1;
232 }
Tim Petersb38e2b62004-07-29 02:29:26 +0000233
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000234 if (list_resize(self, n+1) == -1)
235 return -1;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000236
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000237 if (where < 0) {
238 where += n;
239 if (where < 0)
240 where = 0;
241 }
242 if (where > n)
243 where = n;
244 items = self->ob_item;
245 for (i = n; --i >= where; )
246 items[i+1] = items[i];
247 Py_INCREF(v);
248 items[where] = v;
249 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000250}
251
252int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000253PyList_Insert(PyObject *op, Py_ssize_t where, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000254{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000255 if (!PyList_Check(op)) {
256 PyErr_BadInternalCall();
257 return -1;
258 }
259 return ins1((PyListObject *)op, where, newitem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000260}
261
Raymond Hettinger40a03822004-04-12 13:05:09 +0000262static int
263app1(PyListObject *self, PyObject *v)
264{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000265 Py_ssize_t n = PyList_GET_SIZE(self);
Raymond Hettinger40a03822004-04-12 13:05:09 +0000266
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000267 assert (v != NULL);
268 if (n == PY_SSIZE_T_MAX) {
269 PyErr_SetString(PyExc_OverflowError,
270 "cannot add more objects to list");
271 return -1;
272 }
Raymond Hettinger40a03822004-04-12 13:05:09 +0000273
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000274 if (list_resize(self, n+1) == -1)
275 return -1;
Raymond Hettinger40a03822004-04-12 13:05:09 +0000276
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000277 Py_INCREF(v);
278 PyList_SET_ITEM(self, n, v);
279 return 0;
Raymond Hettinger40a03822004-04-12 13:05:09 +0000280}
281
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000282int
Fred Drakea2f55112000-07-09 15:16:51 +0000283PyList_Append(PyObject *op, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000284{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000285 if (PyList_Check(op) && (newitem != NULL))
286 return app1((PyListObject *)op, newitem);
287 PyErr_BadInternalCall();
288 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000289}
290
291/* Methods */
292
293static void
Fred Drakea2f55112000-07-09 15:16:51 +0000294list_dealloc(PyListObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000295{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000296 Py_ssize_t i;
297 PyObject_GC_UnTrack(op);
298 Py_TRASHCAN_SAFE_BEGIN(op)
299 if (op->ob_item != NULL) {
300 /* Do it backwards, for Christian Tismer.
301 There's a simple test case where somehow this reduces
302 thrashing when a *very* large list is created and
303 immediately deleted. */
304 i = Py_SIZE(op);
305 while (--i >= 0) {
306 Py_XDECREF(op->ob_item[i]);
307 }
308 PyMem_FREE(op->ob_item);
309 }
310 if (numfree < PyList_MAXFREELIST && PyList_CheckExact(op))
311 free_list[numfree++] = op;
312 else
313 Py_TYPE(op)->tp_free((PyObject *)op);
314 Py_TRASHCAN_SAFE_END(op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000315}
316
Guido van Rossum90933611991-06-07 16:10:43 +0000317static int
Fred Drakea2f55112000-07-09 15:16:51 +0000318list_print(PyListObject *op, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000319{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000320 int rc;
321 Py_ssize_t i;
322 PyObject *item;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000323
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000324 rc = Py_ReprEnter((PyObject*)op);
325 if (rc != 0) {
326 if (rc < 0)
327 return rc;
328 Py_BEGIN_ALLOW_THREADS
329 fprintf(fp, "[...]");
330 Py_END_ALLOW_THREADS
331 return 0;
332 }
333 Py_BEGIN_ALLOW_THREADS
334 fprintf(fp, "[");
335 Py_END_ALLOW_THREADS
336 for (i = 0; i < Py_SIZE(op); i++) {
337 item = op->ob_item[i];
338 Py_INCREF(item);
339 if (i > 0) {
340 Py_BEGIN_ALLOW_THREADS
341 fprintf(fp, ", ");
342 Py_END_ALLOW_THREADS
343 }
344 if (PyObject_Print(item, fp, 0) != 0) {
345 Py_DECREF(item);
346 Py_ReprLeave((PyObject *)op);
347 return -1;
348 }
349 Py_DECREF(item);
350 }
351 Py_BEGIN_ALLOW_THREADS
352 fprintf(fp, "]");
353 Py_END_ALLOW_THREADS
354 Py_ReprLeave((PyObject *)op);
355 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000356}
357
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000358static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000359list_repr(PyListObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000360{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000361 Py_ssize_t i;
362 PyObject *s, *temp;
363 PyObject *pieces = NULL, *result = NULL;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000364
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000365 i = Py_ReprEnter((PyObject*)v);
366 if (i != 0) {
367 return i > 0 ? PyString_FromString("[...]") : NULL;
368 }
Tim Petersa7259592001-06-16 05:11:17 +0000369
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000370 if (Py_SIZE(v) == 0) {
371 result = PyString_FromString("[]");
372 goto Done;
373 }
Tim Petersa7259592001-06-16 05:11:17 +0000374
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000375 pieces = PyList_New(0);
376 if (pieces == NULL)
377 goto Done;
Tim Petersa7259592001-06-16 05:11:17 +0000378
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000379 /* Do repr() on each element. Note that this may mutate the list,
380 so must refetch the list size on each iteration. */
381 for (i = 0; i < Py_SIZE(v); ++i) {
382 int status;
383 if (Py_EnterRecursiveCall(" while getting the repr of a list"))
384 goto Done;
385 s = PyObject_Repr(v->ob_item[i]);
386 Py_LeaveRecursiveCall();
387 if (s == NULL)
388 goto Done;
389 status = PyList_Append(pieces, s);
390 Py_DECREF(s); /* append created a new ref */
391 if (status < 0)
392 goto Done;
393 }
Tim Petersa7259592001-06-16 05:11:17 +0000394
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000395 /* Add "[]" decorations to the first and last items. */
396 assert(PyList_GET_SIZE(pieces) > 0);
397 s = PyString_FromString("[");
398 if (s == NULL)
399 goto Done;
400 temp = PyList_GET_ITEM(pieces, 0);
401 PyString_ConcatAndDel(&s, temp);
402 PyList_SET_ITEM(pieces, 0, s);
403 if (s == NULL)
404 goto Done;
Tim Petersa7259592001-06-16 05:11:17 +0000405
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000406 s = PyString_FromString("]");
407 if (s == NULL)
408 goto Done;
409 temp = PyList_GET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1);
410 PyString_ConcatAndDel(&temp, s);
411 PyList_SET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1, temp);
412 if (temp == NULL)
413 goto Done;
Tim Petersa7259592001-06-16 05:11:17 +0000414
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000415 /* Paste them all together with ", " between. */
416 s = PyString_FromString(", ");
417 if (s == NULL)
418 goto Done;
419 result = _PyString_Join(s, pieces);
420 Py_DECREF(s);
Tim Petersa7259592001-06-16 05:11:17 +0000421
422Done:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000423 Py_XDECREF(pieces);
424 Py_ReprLeave((PyObject *)v);
425 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000426}
427
Martin v. Löwis18e16552006-02-15 17:27:45 +0000428static Py_ssize_t
Fred Drakea2f55112000-07-09 15:16:51 +0000429list_length(PyListObject *a)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000430{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000431 return Py_SIZE(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000432}
433
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000434static int
Fred Drakea2f55112000-07-09 15:16:51 +0000435list_contains(PyListObject *a, PyObject *el)
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000436{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000437 Py_ssize_t i;
438 int cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000439
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000440 for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(a); ++i)
441 cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i),
442 Py_EQ);
443 return cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000444}
445
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000446static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000447list_item(PyListObject *a, Py_ssize_t i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000448{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000449 if (i < 0 || i >= Py_SIZE(a)) {
450 if (indexerr == NULL)
451 indexerr = PyString_FromString(
452 "list index out of range");
453 PyErr_SetObject(PyExc_IndexError, indexerr);
454 return NULL;
455 }
456 Py_INCREF(a->ob_item[i]);
457 return a->ob_item[i];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000458}
459
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000460static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000461list_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000462{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000463 PyListObject *np;
464 PyObject **src, **dest;
465 Py_ssize_t i, len;
466 if (ilow < 0)
467 ilow = 0;
468 else if (ilow > Py_SIZE(a))
469 ilow = Py_SIZE(a);
470 if (ihigh < ilow)
471 ihigh = ilow;
472 else if (ihigh > Py_SIZE(a))
473 ihigh = Py_SIZE(a);
474 len = ihigh - ilow;
475 np = (PyListObject *) PyList_New(len);
476 if (np == NULL)
477 return NULL;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000478
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000479 src = a->ob_item + ilow;
480 dest = np->ob_item;
481 for (i = 0; i < len; i++) {
482 PyObject *v = src[i];
483 Py_INCREF(v);
484 dest[i] = v;
485 }
486 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000487}
488
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000489PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000490PyList_GetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum234f9421993-06-17 12:35:49 +0000491{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000492 if (!PyList_Check(a)) {
493 PyErr_BadInternalCall();
494 return NULL;
495 }
496 return list_slice((PyListObject *)a, ilow, ihigh);
Guido van Rossum234f9421993-06-17 12:35:49 +0000497}
498
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000499static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000500list_concat(PyListObject *a, PyObject *bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000501{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000502 Py_ssize_t size;
503 Py_ssize_t i;
504 PyObject **src, **dest;
505 PyListObject *np;
506 if (!PyList_Check(bb)) {
507 PyErr_Format(PyExc_TypeError,
508 "can only concatenate list (not \"%.200s\") to list",
509 bb->ob_type->tp_name);
510 return NULL;
511 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000512#define b ((PyListObject *)bb)
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000513 size = Py_SIZE(a) + Py_SIZE(b);
514 if (size < 0)
515 return PyErr_NoMemory();
516 np = (PyListObject *) PyList_New(size);
517 if (np == NULL) {
518 return NULL;
519 }
520 src = a->ob_item;
521 dest = np->ob_item;
522 for (i = 0; i < Py_SIZE(a); i++) {
523 PyObject *v = src[i];
524 Py_INCREF(v);
525 dest[i] = v;
526 }
527 src = b->ob_item;
528 dest = np->ob_item + Py_SIZE(a);
529 for (i = 0; i < Py_SIZE(b); i++) {
530 PyObject *v = src[i];
531 Py_INCREF(v);
532 dest[i] = v;
533 }
534 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000535#undef b
536}
537
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000538static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000539list_repeat(PyListObject *a, Py_ssize_t n)
Guido van Rossumed98d481991-03-06 13:07:53 +0000540{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000541 Py_ssize_t i, j;
542 Py_ssize_t size;
543 PyListObject *np;
544 PyObject **p, **items;
545 PyObject *elem;
546 if (n < 0)
547 n = 0;
548 size = Py_SIZE(a) * n;
549 if (n && size/n != Py_SIZE(a))
550 return PyErr_NoMemory();
551 if (size == 0)
552 return PyList_New(0);
553 np = (PyListObject *) PyList_New(size);
554 if (np == NULL)
555 return NULL;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000556
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000557 items = np->ob_item;
558 if (Py_SIZE(a) == 1) {
559 elem = a->ob_item[0];
560 for (i = 0; i < n; i++) {
561 items[i] = elem;
562 Py_INCREF(elem);
563 }
564 return (PyObject *) np;
565 }
566 p = np->ob_item;
567 items = a->ob_item;
568 for (i = 0; i < n; i++) {
569 for (j = 0; j < Py_SIZE(a); j++) {
570 *p = items[j];
571 Py_INCREF(*p);
572 p++;
573 }
574 }
575 return (PyObject *) np;
Guido van Rossumed98d481991-03-06 13:07:53 +0000576}
577
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000578static int
Armin Rigo93677f02004-07-29 12:40:23 +0000579list_clear(PyListObject *a)
580{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000581 Py_ssize_t i;
582 PyObject **item = a->ob_item;
583 if (item != NULL) {
584 /* Because XDECREF can recursively invoke operations on
585 this list, we make it empty first. */
586 i = Py_SIZE(a);
587 Py_SIZE(a) = 0;
588 a->ob_item = NULL;
589 a->allocated = 0;
590 while (--i >= 0) {
591 Py_XDECREF(item[i]);
592 }
593 PyMem_FREE(item);
594 }
595 /* Never fails; the return value can be ignored.
596 Note that there is no guarantee that the list is actually empty
597 at this point, because XDECREF may have populated it again! */
598 return 0;
Armin Rigo93677f02004-07-29 12:40:23 +0000599}
600
Tim Peters8fc4a912004-07-31 21:53:19 +0000601/* a[ilow:ihigh] = v if v != NULL.
602 * del a[ilow:ihigh] if v == NULL.
603 *
604 * Special speed gimmick: when v is NULL and ihigh - ilow <= 8, it's
605 * guaranteed the call cannot fail.
606 */
Armin Rigo93677f02004-07-29 12:40:23 +0000607static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000608list_ass_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000609{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000610 /* Because [X]DECREF can recursively invoke list operations on
611 this list, we must postpone all [X]DECREF activity until
612 after the list is back in its canonical shape. Therefore
613 we must allocate an additional array, 'recycle', into which
614 we temporarily copy the items that are deleted from the
615 list. :-( */
616 PyObject *recycle_on_stack[8];
617 PyObject **recycle = recycle_on_stack; /* will allocate more if needed */
618 PyObject **item;
619 PyObject **vitem = NULL;
620 PyObject *v_as_SF = NULL; /* PySequence_Fast(v) */
621 Py_ssize_t n; /* # of elements in replacement list */
622 Py_ssize_t norig; /* # of elements in list getting replaced */
623 Py_ssize_t d; /* Change in size */
624 Py_ssize_t k;
625 size_t s;
626 int result = -1; /* guilty until proved innocent */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000627#define b ((PyListObject *)v)
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000628 if (v == NULL)
629 n = 0;
630 else {
631 if (a == b) {
632 /* Special case "a[i:j] = a" -- copy b first */
633 v = list_slice(b, 0, Py_SIZE(b));
634 if (v == NULL)
635 return result;
636 result = list_ass_slice(a, ilow, ihigh, v);
637 Py_DECREF(v);
638 return result;
639 }
640 v_as_SF = PySequence_Fast(v, "can only assign an iterable");
641 if(v_as_SF == NULL)
642 goto Error;
643 n = PySequence_Fast_GET_SIZE(v_as_SF);
644 vitem = PySequence_Fast_ITEMS(v_as_SF);
645 }
646 if (ilow < 0)
647 ilow = 0;
648 else if (ilow > Py_SIZE(a))
649 ilow = Py_SIZE(a);
Tim Peters8d9eb102004-07-31 02:24:20 +0000650
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000651 if (ihigh < ilow)
652 ihigh = ilow;
653 else if (ihigh > Py_SIZE(a))
654 ihigh = Py_SIZE(a);
Armin Rigo93677f02004-07-29 12:40:23 +0000655
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000656 norig = ihigh - ilow;
657 assert(norig >= 0);
658 d = n - norig;
659 if (Py_SIZE(a) + d == 0) {
660 Py_XDECREF(v_as_SF);
661 return list_clear(a);
662 }
663 item = a->ob_item;
664 /* recycle the items that we are about to remove */
665 s = norig * sizeof(PyObject *);
666 if (s > sizeof(recycle_on_stack)) {
667 recycle = (PyObject **)PyMem_MALLOC(s);
668 if (recycle == NULL) {
669 PyErr_NoMemory();
670 goto Error;
671 }
672 }
673 memcpy(recycle, &item[ilow], s);
Tim Peters8d9eb102004-07-31 02:24:20 +0000674
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000675 if (d < 0) { /* Delete -d items */
676 memmove(&item[ihigh+d], &item[ihigh],
677 (Py_SIZE(a) - ihigh)*sizeof(PyObject *));
678 list_resize(a, Py_SIZE(a) + d);
679 item = a->ob_item;
680 }
681 else if (d > 0) { /* Insert d items */
682 k = Py_SIZE(a);
683 if (list_resize(a, k+d) < 0)
684 goto Error;
685 item = a->ob_item;
686 memmove(&item[ihigh+d], &item[ihigh],
687 (k - ihigh)*sizeof(PyObject *));
688 }
689 for (k = 0; k < n; k++, ilow++) {
690 PyObject *w = vitem[k];
691 Py_XINCREF(w);
692 item[ilow] = w;
693 }
694 for (k = norig - 1; k >= 0; --k)
695 Py_XDECREF(recycle[k]);
696 result = 0;
Tim Peters8d9eb102004-07-31 02:24:20 +0000697 Error:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000698 if (recycle != recycle_on_stack)
699 PyMem_FREE(recycle);
700 Py_XDECREF(v_as_SF);
701 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000702#undef b
703}
704
Guido van Rossum234f9421993-06-17 12:35:49 +0000705int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000706PyList_SetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum234f9421993-06-17 12:35:49 +0000707{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000708 if (!PyList_Check(a)) {
709 PyErr_BadInternalCall();
710 return -1;
711 }
712 return list_ass_slice((PyListObject *)a, ilow, ihigh, v);
Guido van Rossum234f9421993-06-17 12:35:49 +0000713}
714
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000715static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000716list_inplace_repeat(PyListObject *self, Py_ssize_t n)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000717{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000718 PyObject **items;
719 Py_ssize_t size, i, j, p;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000720
721
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000722 size = PyList_GET_SIZE(self);
723 if (size == 0 || n == 1) {
724 Py_INCREF(self);
725 return (PyObject *)self;
726 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000727
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000728 if (n < 1) {
729 (void)list_clear(self);
730 Py_INCREF(self);
731 return (PyObject *)self;
732 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000733
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000734 if (size > PY_SSIZE_T_MAX / n) {
735 return PyErr_NoMemory();
736 }
Guido van Rossum8d5cf4e2008-01-25 19:50:26 +0000737
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000738 if (list_resize(self, size*n) == -1)
739 return NULL;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000740
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000741 p = size;
742 items = self->ob_item;
743 for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */
744 for (j = 0; j < size; j++) {
745 PyObject *o = items[j];
746 Py_INCREF(o);
747 items[p++] = o;
748 }
749 }
750 Py_INCREF(self);
751 return (PyObject *)self;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000752}
753
Guido van Rossum4a450d01991-04-03 19:05:18 +0000754static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000755list_ass_item(PyListObject *a, Py_ssize_t i, PyObject *v)
Guido van Rossum4a450d01991-04-03 19:05:18 +0000756{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000757 PyObject *old_value;
758 if (i < 0 || i >= Py_SIZE(a)) {
759 PyErr_SetString(PyExc_IndexError,
760 "list assignment index out of range");
761 return -1;
762 }
763 if (v == NULL)
764 return list_ass_slice(a, i, i+1, v);
765 Py_INCREF(v);
766 old_value = a->ob_item[i];
767 a->ob_item[i] = v;
768 Py_DECREF(old_value);
769 return 0;
Guido van Rossum4a450d01991-04-03 19:05:18 +0000770}
771
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000772static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000773listinsert(PyListObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000774{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000775 Py_ssize_t i;
776 PyObject *v;
777 if (!PyArg_ParseTuple(args, "nO:insert", &i, &v))
778 return NULL;
779 if (ins1(self, i, v) == 0)
780 Py_RETURN_NONE;
781 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000782}
783
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000784static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000785listappend(PyListObject *self, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000786{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000787 if (app1(self, v) == 0)
788 Py_RETURN_NONE;
789 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000790}
791
Barry Warsawdedf6d61998-10-09 16:37:25 +0000792static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000793listextend(PyListObject *self, PyObject *b)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000794{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000795 PyObject *it; /* iter(v) */
796 Py_ssize_t m; /* size of self */
797 Py_ssize_t n; /* guess for size of b */
798 Py_ssize_t mn; /* m + n */
799 Py_ssize_t i;
800 PyObject *(*iternext)(PyObject *);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000801
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000802 /* Special cases:
803 1) lists and tuples which can use PySequence_Fast ops
804 2) extending self to self requires making a copy first
805 */
806 if (PyList_CheckExact(b) || PyTuple_CheckExact(b) || (PyObject *)self == b) {
807 PyObject **src, **dest;
808 b = PySequence_Fast(b, "argument must be iterable");
809 if (!b)
810 return NULL;
811 n = PySequence_Fast_GET_SIZE(b);
812 if (n == 0) {
813 /* short circuit when b is empty */
814 Py_DECREF(b);
815 Py_RETURN_NONE;
816 }
817 m = Py_SIZE(self);
818 if (list_resize(self, m + n) == -1) {
819 Py_DECREF(b);
820 return NULL;
821 }
822 /* note that we may still have self == b here for the
823 * situation a.extend(a), but the following code works
824 * in that case too. Just make sure to resize self
825 * before calling PySequence_Fast_ITEMS.
826 */
827 /* populate the end of self with b's items */
828 src = PySequence_Fast_ITEMS(b);
829 dest = self->ob_item + m;
830 for (i = 0; i < n; i++) {
831 PyObject *o = src[i];
832 Py_INCREF(o);
833 dest[i] = o;
834 }
835 Py_DECREF(b);
836 Py_RETURN_NONE;
837 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000838
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000839 it = PyObject_GetIter(b);
840 if (it == NULL)
841 return NULL;
842 iternext = *it->ob_type->tp_iternext;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000843
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000844 /* Guess a result list size. */
845 n = _PyObject_LengthHint(b, 8);
846 if (n == -1) {
847 Py_DECREF(it);
848 return NULL;
849 }
850 m = Py_SIZE(self);
851 mn = m + n;
852 if (mn >= m) {
853 /* Make room. */
854 if (list_resize(self, mn) == -1)
855 goto error;
856 /* Make the list sane again. */
857 Py_SIZE(self) = m;
858 }
859 /* Else m + n overflowed; on the chance that n lied, and there really
860 * is enough room, ignore it. If n was telling the truth, we'll
861 * eventually run out of memory during the loop.
862 */
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000863
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000864 /* Run iterator to exhaustion. */
865 for (;;) {
866 PyObject *item = iternext(it);
867 if (item == NULL) {
868 if (PyErr_Occurred()) {
869 if (PyErr_ExceptionMatches(PyExc_StopIteration))
870 PyErr_Clear();
871 else
872 goto error;
873 }
874 break;
875 }
876 if (Py_SIZE(self) < self->allocated) {
877 /* steals ref */
878 PyList_SET_ITEM(self, Py_SIZE(self), item);
879 ++Py_SIZE(self);
880 }
881 else {
882 int status = app1(self, item);
883 Py_DECREF(item); /* append creates a new ref */
884 if (status < 0)
885 goto error;
886 }
887 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000888
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000889 /* Cut back result list if initial guess was too large. */
890 if (Py_SIZE(self) < self->allocated)
891 list_resize(self, Py_SIZE(self)); /* shrinking can't fail */
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000892
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000893 Py_DECREF(it);
894 Py_RETURN_NONE;
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000895
896 error:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000897 Py_DECREF(it);
898 return NULL;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000899}
900
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000901PyObject *
902_PyList_Extend(PyListObject *self, PyObject *b)
903{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000904 return listextend(self, b);
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000905}
906
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000907static PyObject *
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000908list_inplace_concat(PyListObject *self, PyObject *other)
909{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000910 PyObject *result;
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000911
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000912 result = listextend(self, other);
913 if (result == NULL)
914 return result;
915 Py_DECREF(result);
916 Py_INCREF(self);
917 return (PyObject *)self;
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000918}
919
920static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000921listpop(PyListObject *self, PyObject *args)
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000922{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000923 Py_ssize_t i = -1;
924 PyObject *v;
925 int status;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000926
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000927 if (!PyArg_ParseTuple(args, "|n:pop", &i))
928 return NULL;
Armin Rigo7ccbca92006-10-04 12:17:45 +0000929
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000930 if (Py_SIZE(self) == 0) {
931 /* Special-case most common failure cause */
932 PyErr_SetString(PyExc_IndexError, "pop from empty list");
933 return NULL;
934 }
935 if (i < 0)
936 i += Py_SIZE(self);
937 if (i < 0 || i >= Py_SIZE(self)) {
938 PyErr_SetString(PyExc_IndexError, "pop index out of range");
939 return NULL;
940 }
941 v = self->ob_item[i];
942 if (i == Py_SIZE(self) - 1) {
943 status = list_resize(self, Py_SIZE(self) - 1);
944 assert(status >= 0);
945 return v; /* and v now owns the reference the list had */
946 }
947 Py_INCREF(v);
948 status = list_ass_slice(self, i, i+1, (PyObject *)NULL);
949 assert(status >= 0);
950 /* Use status, so that in a release build compilers don't
951 * complain about the unused name.
952 */
953 (void) status;
Brett Cannon651dd522004-08-08 21:21:18 +0000954
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000955 return v;
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000956}
957
Tim Peters8e2e7ca2002-07-19 02:33:08 +0000958/* Reverse a slice of a list in place, from lo up to (exclusive) hi. */
959static void
960reverse_slice(PyObject **lo, PyObject **hi)
961{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000962 assert(lo && hi);
Tim Peters8e2e7ca2002-07-19 02:33:08 +0000963
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000964 --hi;
965 while (lo < hi) {
966 PyObject *t = *lo;
967 *lo = *hi;
968 *hi = t;
969 ++lo;
970 --hi;
971 }
Tim Peters8e2e7ca2002-07-19 02:33:08 +0000972}
973
Tim Petersa64dc242002-08-01 02:13:36 +0000974/* Lots of code for an adaptive, stable, natural mergesort. There are many
975 * pieces to this algorithm; read listsort.txt for overviews and details.
976 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000977
Guido van Rossum3f236de1996-12-10 23:55:39 +0000978/* Comparison function. Takes care of calling a user-supplied
Tim Peters66860f62002-08-04 17:47:26 +0000979 * comparison function (any callable Python object), which must not be
980 * NULL (use the ISLT macro if you don't know, or call PyObject_RichCompareBool
981 * with Py_LT if you know it's NULL).
Tim Petersa64dc242002-08-01 02:13:36 +0000982 * Returns -1 on error, 1 if x < y, 0 if x >= y.
983 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000984static int
Tim Petersa8c974c2002-07-19 03:30:57 +0000985islt(PyObject *x, PyObject *y, PyObject *compare)
Guido van Rossum3f236de1996-12-10 23:55:39 +0000986{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000987 PyObject *res;
988 PyObject *args;
989 Py_ssize_t i;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000990
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000991 assert(compare != NULL);
992 /* Call the user's comparison function and translate the 3-way
993 * result into true or false (or error).
994 */
995 args = PyTuple_New(2);
996 if (args == NULL)
997 return -1;
998 Py_INCREF(x);
999 Py_INCREF(y);
1000 PyTuple_SET_ITEM(args, 0, x);
1001 PyTuple_SET_ITEM(args, 1, y);
1002 res = PyObject_Call(compare, args, NULL);
1003 Py_DECREF(args);
1004 if (res == NULL)
1005 return -1;
1006 if (!PyInt_Check(res)) {
1007 PyErr_Format(PyExc_TypeError,
1008 "comparison function must return int, not %.200s",
1009 res->ob_type->tp_name);
1010 Py_DECREF(res);
1011 return -1;
1012 }
1013 i = PyInt_AsLong(res);
1014 Py_DECREF(res);
1015 return i < 0;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001016}
1017
Tim Peters66860f62002-08-04 17:47:26 +00001018/* If COMPARE is NULL, calls PyObject_RichCompareBool with Py_LT, else calls
1019 * islt. This avoids a layer of function call in the usual case, and
1020 * sorting does many comparisons.
1021 * Returns -1 on error, 1 if x < y, 0 if x >= y.
1022 */
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001023#define ISLT(X, Y, COMPARE) ((COMPARE) == NULL ? \
1024 PyObject_RichCompareBool(X, Y, Py_LT) : \
1025 islt(X, Y, COMPARE))
Tim Peters66860f62002-08-04 17:47:26 +00001026
1027/* Compare X to Y via "<". Goto "fail" if the comparison raises an
Tim Petersa8c974c2002-07-19 03:30:57 +00001028 error. Else "k" is set to true iff X<Y, and an "if (k)" block is
1029 started. It makes more sense in context <wink>. X and Y are PyObject*s.
1030*/
Tim Peters66860f62002-08-04 17:47:26 +00001031#define IFLT(X, Y) if ((k = ISLT(X, Y, compare)) < 0) goto fail; \
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001032 if (k)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001033
1034/* binarysort is the best method for sorting small arrays: it does
1035 few compares, but can do data movement quadratic in the number of
1036 elements.
Guido van Rossum42812581998-06-17 14:15:44 +00001037 [lo, hi) is a contiguous slice of a list, and is sorted via
Tim Petersa8c974c2002-07-19 03:30:57 +00001038 binary insertion. This sort is stable.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001039 On entry, must have lo <= start <= hi, and that [lo, start) is already
1040 sorted (pass start == lo if you don't know!).
Tim Petersa8c974c2002-07-19 03:30:57 +00001041 If islt() complains return -1, else 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001042 Even in case of error, the output slice will be some permutation of
1043 the input (nothing is lost or duplicated).
1044*/
Guido van Rossum3f236de1996-12-10 23:55:39 +00001045static int
Fred Drakea2f55112000-07-09 15:16:51 +00001046binarysort(PyObject **lo, PyObject **hi, PyObject **start, PyObject *compare)
1047 /* compare -- comparison function object, or NULL for default */
Guido van Rossum3f236de1996-12-10 23:55:39 +00001048{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001049 register Py_ssize_t k;
1050 register PyObject **l, **p, **r;
1051 register PyObject *pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001052
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001053 assert(lo <= start && start <= hi);
1054 /* assert [lo, start) is sorted */
1055 if (lo == start)
1056 ++start;
1057 for (; start < hi; ++start) {
1058 /* set l to where *start belongs */
1059 l = lo;
1060 r = start;
1061 pivot = *r;
1062 /* Invariants:
1063 * pivot >= all in [lo, l).
1064 * pivot < all in [r, start).
1065 * The second is vacuously true at the start.
1066 */
1067 assert(l < r);
1068 do {
1069 p = l + ((r - l) >> 1);
1070 IFLT(pivot, *p)
1071 r = p;
1072 else
1073 l = p+1;
1074 } while (l < r);
1075 assert(l == r);
1076 /* The invariants still hold, so pivot >= all in [lo, l) and
1077 pivot < all in [l, start), so pivot belongs at l. Note
1078 that if there are elements equal to pivot, l points to the
1079 first slot after them -- that's why this sort is stable.
1080 Slide over to make room.
1081 Caution: using memmove is much slower under MSVC 5;
1082 we're not usually moving many slots. */
1083 for (p = start; p > l; --p)
1084 *p = *(p-1);
1085 *l = pivot;
1086 }
1087 return 0;
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001088
1089 fail:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001090 return -1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001091}
1092
Tim Petersa64dc242002-08-01 02:13:36 +00001093/*
1094Return the length of the run beginning at lo, in the slice [lo, hi). lo < hi
1095is required on entry. "A run" is the longest ascending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001096
Tim Petersa64dc242002-08-01 02:13:36 +00001097 lo[0] <= lo[1] <= lo[2] <= ...
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001098
Tim Petersa64dc242002-08-01 02:13:36 +00001099or the longest descending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001100
Tim Petersa64dc242002-08-01 02:13:36 +00001101 lo[0] > lo[1] > lo[2] > ...
Tim Peters3b01a122002-07-19 02:35:45 +00001102
Tim Petersa64dc242002-08-01 02:13:36 +00001103Boolean *descending is set to 0 in the former case, or to 1 in the latter.
1104For its intended use in a stable mergesort, the strictness of the defn of
1105"descending" is needed so that the caller can safely reverse a descending
1106sequence without violating stability (strict > ensures there are no equal
1107elements to get out of order).
1108
1109Returns -1 in case of error.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001110*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001111static Py_ssize_t
Tim Petersa64dc242002-08-01 02:13:36 +00001112count_run(PyObject **lo, PyObject **hi, PyObject *compare, int *descending)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001113{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001114 Py_ssize_t k;
1115 Py_ssize_t n;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001116
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001117 assert(lo < hi);
1118 *descending = 0;
1119 ++lo;
1120 if (lo == hi)
1121 return 1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001122
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001123 n = 2;
1124 IFLT(*lo, *(lo-1)) {
1125 *descending = 1;
1126 for (lo = lo+1; lo < hi; ++lo, ++n) {
1127 IFLT(*lo, *(lo-1))
1128 ;
1129 else
1130 break;
1131 }
1132 }
1133 else {
1134 for (lo = lo+1; lo < hi; ++lo, ++n) {
1135 IFLT(*lo, *(lo-1))
1136 break;
1137 }
1138 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001139
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001140 return n;
Tim Petersa64dc242002-08-01 02:13:36 +00001141fail:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001142 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001143}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001144
Tim Petersa64dc242002-08-01 02:13:36 +00001145/*
1146Locate the proper position of key in a sorted vector; if the vector contains
1147an element equal to key, return the position immediately to the left of
1148the leftmost equal element. [gallop_right() does the same except returns
1149the position to the right of the rightmost equal element (if any).]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001150
Tim Petersa64dc242002-08-01 02:13:36 +00001151"a" is a sorted vector with n elements, starting at a[0]. n must be > 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001152
Tim Petersa64dc242002-08-01 02:13:36 +00001153"hint" is an index at which to begin the search, 0 <= hint < n. The closer
1154hint is to the final result, the faster this runs.
1155
1156The return value is the int k in 0..n such that
1157
1158 a[k-1] < key <= a[k]
1159
1160pretending that *(a-1) is minus infinity and a[n] is plus infinity. IOW,
1161key belongs at index k; or, IOW, the first k elements of a should precede
1162key, and the last n-k should follow key.
1163
1164Returns -1 on error. See listsort.txt for info on the method.
1165*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001166static Py_ssize_t
1167gallop_left(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint, PyObject *compare)
Tim Petersa64dc242002-08-01 02:13:36 +00001168{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001169 Py_ssize_t ofs;
1170 Py_ssize_t lastofs;
1171 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001172
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001173 assert(key && a && n > 0 && hint >= 0 && hint < n);
Tim Petersa64dc242002-08-01 02:13:36 +00001174
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001175 a += hint;
1176 lastofs = 0;
1177 ofs = 1;
1178 IFLT(*a, key) {
1179 /* a[hint] < key -- gallop right, until
1180 * a[hint + lastofs] < key <= a[hint + ofs]
1181 */
1182 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
1183 while (ofs < maxofs) {
1184 IFLT(a[ofs], key) {
1185 lastofs = ofs;
1186 ofs = (ofs << 1) + 1;
1187 if (ofs <= 0) /* int overflow */
1188 ofs = maxofs;
1189 }
1190 else /* key <= a[hint + ofs] */
1191 break;
1192 }
1193 if (ofs > maxofs)
1194 ofs = maxofs;
1195 /* Translate back to offsets relative to &a[0]. */
1196 lastofs += hint;
1197 ofs += hint;
1198 }
1199 else {
1200 /* key <= a[hint] -- gallop left, until
1201 * a[hint - ofs] < key <= a[hint - lastofs]
1202 */
1203 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
1204 while (ofs < maxofs) {
1205 IFLT(*(a-ofs), key)
1206 break;
1207 /* key <= a[hint - ofs] */
1208 lastofs = ofs;
1209 ofs = (ofs << 1) + 1;
1210 if (ofs <= 0) /* int overflow */
1211 ofs = maxofs;
1212 }
1213 if (ofs > maxofs)
1214 ofs = maxofs;
1215 /* Translate back to positive offsets relative to &a[0]. */
1216 k = lastofs;
1217 lastofs = hint - ofs;
1218 ofs = hint - k;
1219 }
1220 a -= hint;
Tim Petersa64dc242002-08-01 02:13:36 +00001221
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001222 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1223 /* Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the
1224 * right of lastofs but no farther right than ofs. Do a binary
1225 * search, with invariant a[lastofs-1] < key <= a[ofs].
1226 */
1227 ++lastofs;
1228 while (lastofs < ofs) {
1229 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001230
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001231 IFLT(a[m], key)
1232 lastofs = m+1; /* a[m] < key */
1233 else
1234 ofs = m; /* key <= a[m] */
1235 }
1236 assert(lastofs == ofs); /* so a[ofs-1] < key <= a[ofs] */
1237 return ofs;
Tim Petersa64dc242002-08-01 02:13:36 +00001238
1239fail:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001240 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001241}
1242
1243/*
1244Exactly like gallop_left(), except that if key already exists in a[0:n],
1245finds the position immediately to the right of the rightmost equal value.
1246
1247The return value is the int k in 0..n such that
1248
1249 a[k-1] <= key < a[k]
1250
1251or -1 if error.
1252
1253The code duplication is massive, but this is enough different given that
1254we're sticking to "<" comparisons that it's much harder to follow if
1255written as one routine with yet another "left or right?" flag.
1256*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001257static Py_ssize_t
1258gallop_right(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint, PyObject *compare)
Tim Petersa64dc242002-08-01 02:13:36 +00001259{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001260 Py_ssize_t ofs;
1261 Py_ssize_t lastofs;
1262 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001263
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001264 assert(key && a && n > 0 && hint >= 0 && hint < n);
Tim Petersa64dc242002-08-01 02:13:36 +00001265
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001266 a += hint;
1267 lastofs = 0;
1268 ofs = 1;
1269 IFLT(key, *a) {
1270 /* key < a[hint] -- gallop left, until
1271 * a[hint - ofs] <= key < a[hint - lastofs]
1272 */
1273 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
1274 while (ofs < maxofs) {
1275 IFLT(key, *(a-ofs)) {
1276 lastofs = ofs;
1277 ofs = (ofs << 1) + 1;
1278 if (ofs <= 0) /* int overflow */
1279 ofs = maxofs;
1280 }
1281 else /* a[hint - ofs] <= key */
1282 break;
1283 }
1284 if (ofs > maxofs)
1285 ofs = maxofs;
1286 /* Translate back to positive offsets relative to &a[0]. */
1287 k = lastofs;
1288 lastofs = hint - ofs;
1289 ofs = hint - k;
1290 }
1291 else {
1292 /* a[hint] <= key -- gallop right, until
1293 * a[hint + lastofs] <= key < a[hint + ofs]
1294 */
1295 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
1296 while (ofs < maxofs) {
1297 IFLT(key, a[ofs])
1298 break;
1299 /* a[hint + ofs] <= key */
1300 lastofs = ofs;
1301 ofs = (ofs << 1) + 1;
1302 if (ofs <= 0) /* int overflow */
1303 ofs = maxofs;
1304 }
1305 if (ofs > maxofs)
1306 ofs = maxofs;
1307 /* Translate back to offsets relative to &a[0]. */
1308 lastofs += hint;
1309 ofs += hint;
1310 }
1311 a -= hint;
Tim Petersa64dc242002-08-01 02:13:36 +00001312
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001313 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1314 /* Now a[lastofs] <= key < a[ofs], so key belongs somewhere to the
1315 * right of lastofs but no farther right than ofs. Do a binary
1316 * search, with invariant a[lastofs-1] <= key < a[ofs].
1317 */
1318 ++lastofs;
1319 while (lastofs < ofs) {
1320 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001321
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001322 IFLT(key, a[m])
1323 ofs = m; /* key < a[m] */
1324 else
1325 lastofs = m+1; /* a[m] <= key */
1326 }
1327 assert(lastofs == ofs); /* so a[ofs-1] <= key < a[ofs] */
1328 return ofs;
Tim Petersa64dc242002-08-01 02:13:36 +00001329
1330fail:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001331 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001332}
1333
1334/* The maximum number of entries in a MergeState's pending-runs stack.
1335 * This is enough to sort arrays of size up to about
1336 * 32 * phi ** MAX_MERGE_PENDING
1337 * where phi ~= 1.618. 85 is ridiculouslylarge enough, good for an array
1338 * with 2**64 elements.
1339 */
1340#define MAX_MERGE_PENDING 85
1341
Tim Peterse05f65a2002-08-10 05:21:15 +00001342/* When we get into galloping mode, we stay there until both runs win less
1343 * often than MIN_GALLOP consecutive times. See listsort.txt for more info.
Tim Petersa64dc242002-08-01 02:13:36 +00001344 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001345#define MIN_GALLOP 7
Tim Petersa64dc242002-08-01 02:13:36 +00001346
1347/* Avoid malloc for small temp arrays. */
1348#define MERGESTATE_TEMP_SIZE 256
1349
1350/* One MergeState exists on the stack per invocation of mergesort. It's just
1351 * a convenient way to pass state around among the helper functions.
1352 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001353struct s_slice {
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001354 PyObject **base;
1355 Py_ssize_t len;
Tim Peterse05f65a2002-08-10 05:21:15 +00001356};
1357
Tim Petersa64dc242002-08-01 02:13:36 +00001358typedef struct s_MergeState {
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001359 /* The user-supplied comparison function. or NULL if none given. */
1360 PyObject *compare;
Tim Petersa64dc242002-08-01 02:13:36 +00001361
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001362 /* This controls when we get *into* galloping mode. It's initialized
1363 * to MIN_GALLOP. merge_lo and merge_hi tend to nudge it higher for
1364 * random data, and lower for highly structured data.
1365 */
1366 Py_ssize_t min_gallop;
Tim Peterse05f65a2002-08-10 05:21:15 +00001367
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001368 /* 'a' is temp storage to help with merges. It contains room for
1369 * alloced entries.
1370 */
1371 PyObject **a; /* may point to temparray below */
1372 Py_ssize_t alloced;
Tim Petersa64dc242002-08-01 02:13:36 +00001373
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001374 /* A stack of n pending runs yet to be merged. Run #i starts at
1375 * address base[i] and extends for len[i] elements. It's always
1376 * true (so long as the indices are in bounds) that
1377 *
1378 * pending[i].base + pending[i].len == pending[i+1].base
1379 *
1380 * so we could cut the storage for this, but it's a minor amount,
1381 * and keeping all the info explicit simplifies the code.
1382 */
1383 int n;
1384 struct s_slice pending[MAX_MERGE_PENDING];
Tim Petersa64dc242002-08-01 02:13:36 +00001385
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001386 /* 'a' points to this when possible, rather than muck with malloc. */
1387 PyObject *temparray[MERGESTATE_TEMP_SIZE];
Tim Petersa64dc242002-08-01 02:13:36 +00001388} MergeState;
1389
1390/* Conceptually a MergeState's constructor. */
1391static void
1392merge_init(MergeState *ms, PyObject *compare)
1393{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001394 assert(ms != NULL);
1395 ms->compare = compare;
1396 ms->a = ms->temparray;
1397 ms->alloced = MERGESTATE_TEMP_SIZE;
1398 ms->n = 0;
1399 ms->min_gallop = MIN_GALLOP;
Tim Petersa64dc242002-08-01 02:13:36 +00001400}
1401
1402/* Free all the temp memory owned by the MergeState. This must be called
1403 * when you're done with a MergeState, and may be called before then if
1404 * you want to free the temp memory early.
1405 */
1406static void
1407merge_freemem(MergeState *ms)
1408{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001409 assert(ms != NULL);
1410 if (ms->a != ms->temparray)
1411 PyMem_Free(ms->a);
1412 ms->a = ms->temparray;
1413 ms->alloced = MERGESTATE_TEMP_SIZE;
Tim Petersa64dc242002-08-01 02:13:36 +00001414}
1415
1416/* Ensure enough temp memory for 'need' array slots is available.
1417 * Returns 0 on success and -1 if the memory can't be gotten.
1418 */
1419static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001420merge_getmem(MergeState *ms, Py_ssize_t need)
Tim Petersa64dc242002-08-01 02:13:36 +00001421{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001422 assert(ms != NULL);
1423 if (need <= ms->alloced)
1424 return 0;
1425 /* Don't realloc! That can cost cycles to copy the old data, but
1426 * we don't care what's in the block.
1427 */
1428 merge_freemem(ms);
1429 if ((size_t)need > PY_SSIZE_T_MAX / sizeof(PyObject*)) {
1430 PyErr_NoMemory();
1431 return -1;
1432 }
1433 ms->a = (PyObject **)PyMem_Malloc(need * sizeof(PyObject*));
1434 if (ms->a) {
1435 ms->alloced = need;
1436 return 0;
1437 }
1438 PyErr_NoMemory();
1439 merge_freemem(ms); /* reset to sane state */
1440 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001441}
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001442#define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 : \
1443 merge_getmem(MS, NEED))
Tim Petersa64dc242002-08-01 02:13:36 +00001444
1445/* Merge the na elements starting at pa with the nb elements starting at pb
1446 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1447 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1448 * merge, and should have na <= nb. See listsort.txt for more info.
1449 * Return 0 if successful, -1 if error.
1450 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001451static Py_ssize_t
1452merge_lo(MergeState *ms, PyObject **pa, Py_ssize_t na,
1453 PyObject **pb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001454{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001455 Py_ssize_t k;
1456 PyObject *compare;
1457 PyObject **dest;
1458 int result = -1; /* guilty until proved innocent */
1459 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001460
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001461 assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
1462 if (MERGE_GETMEM(ms, na) < 0)
1463 return -1;
1464 memcpy(ms->a, pa, na * sizeof(PyObject*));
1465 dest = pa;
1466 pa = ms->a;
Tim Petersa64dc242002-08-01 02:13:36 +00001467
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001468 *dest++ = *pb++;
1469 --nb;
1470 if (nb == 0)
1471 goto Succeed;
1472 if (na == 1)
1473 goto CopyB;
Tim Petersa64dc242002-08-01 02:13:36 +00001474
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001475 min_gallop = ms->min_gallop;
1476 compare = ms->compare;
1477 for (;;) {
1478 Py_ssize_t acount = 0; /* # of times A won in a row */
1479 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001480
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001481 /* Do the straightforward thing until (if ever) one run
1482 * appears to win consistently.
1483 */
1484 for (;;) {
1485 assert(na > 1 && nb > 0);
1486 k = ISLT(*pb, *pa, compare);
1487 if (k) {
1488 if (k < 0)
1489 goto Fail;
1490 *dest++ = *pb++;
1491 ++bcount;
1492 acount = 0;
1493 --nb;
1494 if (nb == 0)
1495 goto Succeed;
1496 if (bcount >= min_gallop)
1497 break;
1498 }
1499 else {
1500 *dest++ = *pa++;
1501 ++acount;
1502 bcount = 0;
1503 --na;
1504 if (na == 1)
1505 goto CopyB;
1506 if (acount >= min_gallop)
1507 break;
1508 }
1509 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001510
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001511 /* One run is winning so consistently that galloping may
1512 * be a huge win. So try that, and continue galloping until
1513 * (if ever) neither run appears to be winning consistently
1514 * anymore.
1515 */
1516 ++min_gallop;
1517 do {
1518 assert(na > 1 && nb > 0);
1519 min_gallop -= min_gallop > 1;
1520 ms->min_gallop = min_gallop;
1521 k = gallop_right(*pb, pa, na, 0, compare);
1522 acount = k;
1523 if (k) {
1524 if (k < 0)
1525 goto Fail;
1526 memcpy(dest, pa, k * sizeof(PyObject *));
1527 dest += k;
1528 pa += k;
1529 na -= k;
1530 if (na == 1)
1531 goto CopyB;
1532 /* na==0 is impossible now if the comparison
1533 * function is consistent, but we can't assume
1534 * that it is.
1535 */
1536 if (na == 0)
1537 goto Succeed;
1538 }
1539 *dest++ = *pb++;
1540 --nb;
1541 if (nb == 0)
1542 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001543
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001544 k = gallop_left(*pa, pb, nb, 0, compare);
1545 bcount = k;
1546 if (k) {
1547 if (k < 0)
1548 goto Fail;
1549 memmove(dest, pb, k * sizeof(PyObject *));
1550 dest += k;
1551 pb += k;
1552 nb -= k;
1553 if (nb == 0)
1554 goto Succeed;
1555 }
1556 *dest++ = *pa++;
1557 --na;
1558 if (na == 1)
1559 goto CopyB;
1560 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
1561 ++min_gallop; /* penalize it for leaving galloping mode */
1562 ms->min_gallop = min_gallop;
1563 }
Tim Petersa64dc242002-08-01 02:13:36 +00001564Succeed:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001565 result = 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001566Fail:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001567 if (na)
1568 memcpy(dest, pa, na * sizeof(PyObject*));
1569 return result;
Tim Petersa64dc242002-08-01 02:13:36 +00001570CopyB:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001571 assert(na == 1 && nb > 0);
1572 /* The last element of pa belongs at the end of the merge. */
1573 memmove(dest, pb, nb * sizeof(PyObject *));
1574 dest[nb] = *pa;
1575 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001576}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001577
Tim Petersa64dc242002-08-01 02:13:36 +00001578/* Merge the na elements starting at pa with the nb elements starting at pb
1579 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1580 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1581 * merge, and should have na >= nb. See listsort.txt for more info.
1582 * Return 0 if successful, -1 if error.
1583 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001584static Py_ssize_t
1585merge_hi(MergeState *ms, PyObject **pa, Py_ssize_t na, PyObject **pb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001586{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001587 Py_ssize_t k;
1588 PyObject *compare;
1589 PyObject **dest;
1590 int result = -1; /* guilty until proved innocent */
1591 PyObject **basea;
1592 PyObject **baseb;
1593 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001594
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001595 assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
1596 if (MERGE_GETMEM(ms, nb) < 0)
1597 return -1;
1598 dest = pb + nb - 1;
1599 memcpy(ms->a, pb, nb * sizeof(PyObject*));
1600 basea = pa;
1601 baseb = ms->a;
1602 pb = ms->a + nb - 1;
1603 pa += na - 1;
Tim Petersa64dc242002-08-01 02:13:36 +00001604
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001605 *dest-- = *pa--;
1606 --na;
1607 if (na == 0)
1608 goto Succeed;
1609 if (nb == 1)
1610 goto CopyA;
Tim Petersa64dc242002-08-01 02:13:36 +00001611
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001612 min_gallop = ms->min_gallop;
1613 compare = ms->compare;
1614 for (;;) {
1615 Py_ssize_t acount = 0; /* # of times A won in a row */
1616 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001617
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001618 /* Do the straightforward thing until (if ever) one run
1619 * appears to win consistently.
1620 */
1621 for (;;) {
1622 assert(na > 0 && nb > 1);
1623 k = ISLT(*pb, *pa, compare);
1624 if (k) {
1625 if (k < 0)
1626 goto Fail;
1627 *dest-- = *pa--;
1628 ++acount;
1629 bcount = 0;
1630 --na;
1631 if (na == 0)
1632 goto Succeed;
1633 if (acount >= min_gallop)
1634 break;
1635 }
1636 else {
1637 *dest-- = *pb--;
1638 ++bcount;
1639 acount = 0;
1640 --nb;
1641 if (nb == 1)
1642 goto CopyA;
1643 if (bcount >= min_gallop)
1644 break;
1645 }
1646 }
Tim Petersa64dc242002-08-01 02:13:36 +00001647
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001648 /* One run is winning so consistently that galloping may
1649 * be a huge win. So try that, and continue galloping until
1650 * (if ever) neither run appears to be winning consistently
1651 * anymore.
1652 */
1653 ++min_gallop;
1654 do {
1655 assert(na > 0 && nb > 1);
1656 min_gallop -= min_gallop > 1;
1657 ms->min_gallop = min_gallop;
1658 k = gallop_right(*pb, basea, na, na-1, compare);
1659 if (k < 0)
1660 goto Fail;
1661 k = na - k;
1662 acount = k;
1663 if (k) {
1664 dest -= k;
1665 pa -= k;
1666 memmove(dest+1, pa+1, k * sizeof(PyObject *));
1667 na -= k;
1668 if (na == 0)
1669 goto Succeed;
1670 }
1671 *dest-- = *pb--;
1672 --nb;
1673 if (nb == 1)
1674 goto CopyA;
Tim Petersa64dc242002-08-01 02:13:36 +00001675
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001676 k = gallop_left(*pa, baseb, nb, nb-1, compare);
1677 if (k < 0)
1678 goto Fail;
1679 k = nb - k;
1680 bcount = k;
1681 if (k) {
1682 dest -= k;
1683 pb -= k;
1684 memcpy(dest+1, pb+1, k * sizeof(PyObject *));
1685 nb -= k;
1686 if (nb == 1)
1687 goto CopyA;
1688 /* nb==0 is impossible now if the comparison
1689 * function is consistent, but we can't assume
1690 * that it is.
1691 */
1692 if (nb == 0)
1693 goto Succeed;
1694 }
1695 *dest-- = *pa--;
1696 --na;
1697 if (na == 0)
1698 goto Succeed;
1699 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
1700 ++min_gallop; /* penalize it for leaving galloping mode */
1701 ms->min_gallop = min_gallop;
1702 }
Tim Petersa64dc242002-08-01 02:13:36 +00001703Succeed:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001704 result = 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001705Fail:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001706 if (nb)
1707 memcpy(dest-(nb-1), baseb, nb * sizeof(PyObject*));
1708 return result;
Tim Petersa64dc242002-08-01 02:13:36 +00001709CopyA:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001710 assert(nb == 1 && na > 0);
1711 /* The first element of pb belongs at the front of the merge. */
1712 dest -= na;
1713 pa -= na;
1714 memmove(dest+1, pa+1, na * sizeof(PyObject *));
1715 *dest = *pb;
1716 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001717}
1718
1719/* Merge the two runs at stack indices i and i+1.
1720 * Returns 0 on success, -1 on error.
1721 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001722static Py_ssize_t
1723merge_at(MergeState *ms, Py_ssize_t i)
Tim Petersa64dc242002-08-01 02:13:36 +00001724{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001725 PyObject **pa, **pb;
1726 Py_ssize_t na, nb;
1727 Py_ssize_t k;
1728 PyObject *compare;
Tim Petersa64dc242002-08-01 02:13:36 +00001729
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001730 assert(ms != NULL);
1731 assert(ms->n >= 2);
1732 assert(i >= 0);
1733 assert(i == ms->n - 2 || i == ms->n - 3);
Tim Petersa64dc242002-08-01 02:13:36 +00001734
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001735 pa = ms->pending[i].base;
1736 na = ms->pending[i].len;
1737 pb = ms->pending[i+1].base;
1738 nb = ms->pending[i+1].len;
1739 assert(na > 0 && nb > 0);
1740 assert(pa + na == pb);
Tim Petersa64dc242002-08-01 02:13:36 +00001741
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001742 /* Record the length of the combined runs; if i is the 3rd-last
1743 * run now, also slide over the last run (which isn't involved
1744 * in this merge). The current run i+1 goes away in any case.
1745 */
1746 ms->pending[i].len = na + nb;
1747 if (i == ms->n - 3)
1748 ms->pending[i+1] = ms->pending[i+2];
1749 --ms->n;
Tim Petersa64dc242002-08-01 02:13:36 +00001750
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001751 /* Where does b start in a? Elements in a before that can be
1752 * ignored (already in place).
1753 */
1754 compare = ms->compare;
1755 k = gallop_right(*pb, pa, na, 0, compare);
1756 if (k < 0)
1757 return -1;
1758 pa += k;
1759 na -= k;
1760 if (na == 0)
1761 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001762
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001763 /* Where does a end in b? Elements in b after that can be
1764 * ignored (already in place).
1765 */
1766 nb = gallop_left(pa[na-1], pb, nb, nb-1, compare);
1767 if (nb <= 0)
1768 return nb;
Tim Petersa64dc242002-08-01 02:13:36 +00001769
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001770 /* Merge what remains of the runs, using a temp array with
1771 * min(na, nb) elements.
1772 */
1773 if (na <= nb)
1774 return merge_lo(ms, pa, na, pb, nb);
1775 else
1776 return merge_hi(ms, pa, na, pb, nb);
Tim Petersa64dc242002-08-01 02:13:36 +00001777}
1778
1779/* Examine the stack of runs waiting to be merged, merging adjacent runs
1780 * until the stack invariants are re-established:
1781 *
1782 * 1. len[-3] > len[-2] + len[-1]
1783 * 2. len[-2] > len[-1]
1784 *
1785 * See listsort.txt for more info.
1786 *
1787 * Returns 0 on success, -1 on error.
1788 */
1789static int
1790merge_collapse(MergeState *ms)
1791{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001792 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001793
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001794 assert(ms);
1795 while (ms->n > 1) {
1796 Py_ssize_t n = ms->n - 2;
1797 if (n > 0 && p[n-1].len <= p[n].len + p[n+1].len) {
1798 if (p[n-1].len < p[n+1].len)
1799 --n;
1800 if (merge_at(ms, n) < 0)
1801 return -1;
1802 }
1803 else if (p[n].len <= p[n+1].len) {
1804 if (merge_at(ms, n) < 0)
1805 return -1;
1806 }
1807 else
1808 break;
1809 }
1810 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001811}
1812
1813/* Regardless of invariants, merge all runs on the stack until only one
1814 * remains. This is used at the end of the mergesort.
1815 *
1816 * Returns 0 on success, -1 on error.
1817 */
1818static int
1819merge_force_collapse(MergeState *ms)
1820{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001821 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001822
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001823 assert(ms);
1824 while (ms->n > 1) {
1825 Py_ssize_t n = ms->n - 2;
1826 if (n > 0 && p[n-1].len < p[n+1].len)
1827 --n;
1828 if (merge_at(ms, n) < 0)
1829 return -1;
1830 }
1831 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001832}
1833
1834/* Compute a good value for the minimum run length; natural runs shorter
1835 * than this are boosted artificially via binary insertion.
1836 *
1837 * If n < 64, return n (it's too small to bother with fancy stuff).
1838 * Else if n is an exact power of 2, return 32.
1839 * Else return an int k, 32 <= k <= 64, such that n/k is close to, but
1840 * strictly less than, an exact power of 2.
1841 *
1842 * See listsort.txt for more info.
1843 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001844static Py_ssize_t
1845merge_compute_minrun(Py_ssize_t n)
Tim Petersa64dc242002-08-01 02:13:36 +00001846{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001847 Py_ssize_t r = 0; /* becomes 1 if any 1 bits are shifted off */
Tim Petersa64dc242002-08-01 02:13:36 +00001848
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001849 assert(n >= 0);
1850 while (n >= 64) {
1851 r |= n & 1;
1852 n >>= 1;
1853 }
1854 return n + r;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001855}
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001856
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001857/* Special wrapper to support stable sorting using the decorate-sort-undecorate
Andrew M. Kuchling55be9ea2004-09-10 12:59:54 +00001858 pattern. Holds a key which is used for comparisons and the original record
Tim Petersb38e2b62004-07-29 02:29:26 +00001859 which is returned during the undecorate phase. By exposing only the key
1860 during comparisons, the underlying sort stability characteristics are left
1861 unchanged. Also, if a custom comparison function is used, it will only see
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001862 the key instead of a full record. */
1863
1864typedef struct {
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001865 PyObject_HEAD
1866 PyObject *key;
1867 PyObject *value;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001868} sortwrapperobject;
1869
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001870PyDoc_STRVAR(sortwrapper_doc, "Object wrapper with a custom sort key.");
Anthony Baxter377be112006-04-11 06:54:30 +00001871static PyObject *
1872sortwrapper_richcompare(sortwrapperobject *, sortwrapperobject *, int);
1873static void
1874sortwrapper_dealloc(sortwrapperobject *);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001875
1876static PyTypeObject sortwrapper_type = {
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001877 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1878 "sortwrapper", /* tp_name */
1879 sizeof(sortwrapperobject), /* tp_basicsize */
1880 0, /* tp_itemsize */
1881 /* methods */
1882 (destructor)sortwrapper_dealloc, /* tp_dealloc */
1883 0, /* tp_print */
1884 0, /* tp_getattr */
1885 0, /* tp_setattr */
1886 0, /* tp_compare */
1887 0, /* tp_repr */
1888 0, /* tp_as_number */
1889 0, /* tp_as_sequence */
1890 0, /* tp_as_mapping */
1891 0, /* tp_hash */
1892 0, /* tp_call */
1893 0, /* tp_str */
1894 PyObject_GenericGetAttr, /* tp_getattro */
1895 0, /* tp_setattro */
1896 0, /* tp_as_buffer */
1897 Py_TPFLAGS_DEFAULT |
1898 Py_TPFLAGS_HAVE_RICHCOMPARE, /* tp_flags */
1899 sortwrapper_doc, /* tp_doc */
1900 0, /* tp_traverse */
1901 0, /* tp_clear */
1902 (richcmpfunc)sortwrapper_richcompare, /* tp_richcompare */
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001903};
1904
Anthony Baxter377be112006-04-11 06:54:30 +00001905
1906static PyObject *
1907sortwrapper_richcompare(sortwrapperobject *a, sortwrapperobject *b, int op)
1908{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001909 if (!PyObject_TypeCheck(b, &sortwrapper_type)) {
1910 PyErr_SetString(PyExc_TypeError,
1911 "expected a sortwrapperobject");
1912 return NULL;
1913 }
1914 return PyObject_RichCompare(a->key, b->key, op);
Anthony Baxter377be112006-04-11 06:54:30 +00001915}
1916
1917static void
1918sortwrapper_dealloc(sortwrapperobject *so)
1919{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001920 Py_XDECREF(so->key);
1921 Py_XDECREF(so->value);
1922 PyObject_Del(so);
Anthony Baxter377be112006-04-11 06:54:30 +00001923}
1924
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001925/* Returns a new reference to a sortwrapper.
1926 Consumes the references to the two underlying objects. */
1927
1928static PyObject *
1929build_sortwrapper(PyObject *key, PyObject *value)
1930{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001931 sortwrapperobject *so;
Tim Petersb38e2b62004-07-29 02:29:26 +00001932
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001933 so = PyObject_New(sortwrapperobject, &sortwrapper_type);
1934 if (so == NULL)
1935 return NULL;
1936 so->key = key;
1937 so->value = value;
1938 return (PyObject *)so;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001939}
1940
1941/* Returns a new reference to the value underlying the wrapper. */
1942static PyObject *
1943sortwrapper_getvalue(PyObject *so)
1944{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001945 PyObject *value;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001946
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001947 if (!PyObject_TypeCheck(so, &sortwrapper_type)) {
1948 PyErr_SetString(PyExc_TypeError,
1949 "expected a sortwrapperobject");
1950 return NULL;
1951 }
1952 value = ((sortwrapperobject *)so)->value;
1953 Py_INCREF(value);
1954 return value;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001955}
1956
1957/* Wrapper for user specified cmp functions in combination with a
1958 specified key function. Makes sure the cmp function is presented
1959 with the actual key instead of the sortwrapper */
1960
1961typedef struct {
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001962 PyObject_HEAD
1963 PyObject *func;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001964} cmpwrapperobject;
1965
1966static void
1967cmpwrapper_dealloc(cmpwrapperobject *co)
1968{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001969 Py_XDECREF(co->func);
1970 PyObject_Del(co);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001971}
1972
1973static PyObject *
1974cmpwrapper_call(cmpwrapperobject *co, PyObject *args, PyObject *kwds)
1975{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001976 PyObject *x, *y, *xx, *yy;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001977
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001978 if (!PyArg_UnpackTuple(args, "", 2, 2, &x, &y))
1979 return NULL;
1980 if (!PyObject_TypeCheck(x, &sortwrapper_type) ||
1981 !PyObject_TypeCheck(y, &sortwrapper_type)) {
1982 PyErr_SetString(PyExc_TypeError,
1983 "expected a sortwrapperobject");
1984 return NULL;
1985 }
1986 xx = ((sortwrapperobject *)x)->key;
1987 yy = ((sortwrapperobject *)y)->key;
1988 return PyObject_CallFunctionObjArgs(co->func, xx, yy, NULL);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001989}
1990
1991PyDoc_STRVAR(cmpwrapper_doc, "cmp() wrapper for sort with custom keys.");
1992
1993static PyTypeObject cmpwrapper_type = {
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001994 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1995 "cmpwrapper", /* tp_name */
1996 sizeof(cmpwrapperobject), /* tp_basicsize */
1997 0, /* tp_itemsize */
1998 /* methods */
1999 (destructor)cmpwrapper_dealloc, /* tp_dealloc */
2000 0, /* tp_print */
2001 0, /* tp_getattr */
2002 0, /* tp_setattr */
2003 0, /* tp_compare */
2004 0, /* tp_repr */
2005 0, /* tp_as_number */
2006 0, /* tp_as_sequence */
2007 0, /* tp_as_mapping */
2008 0, /* tp_hash */
2009 (ternaryfunc)cmpwrapper_call, /* tp_call */
2010 0, /* tp_str */
2011 PyObject_GenericGetAttr, /* tp_getattro */
2012 0, /* tp_setattro */
2013 0, /* tp_as_buffer */
2014 Py_TPFLAGS_DEFAULT, /* tp_flags */
2015 cmpwrapper_doc, /* tp_doc */
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002016};
2017
2018static PyObject *
2019build_cmpwrapper(PyObject *cmpfunc)
2020{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002021 cmpwrapperobject *co;
Tim Petersb38e2b62004-07-29 02:29:26 +00002022
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002023 co = PyObject_New(cmpwrapperobject, &cmpwrapper_type);
2024 if (co == NULL)
2025 return NULL;
2026 Py_INCREF(cmpfunc);
2027 co->func = cmpfunc;
2028 return (PyObject *)co;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002029}
2030
Tim Petersa64dc242002-08-01 02:13:36 +00002031/* An adaptive, stable, natural mergesort. See listsort.txt.
2032 * Returns Py_None on success, NULL on error. Even in case of error, the
2033 * list will be some permutation of its input state (nothing is lost or
2034 * duplicated).
2035 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002036static PyObject *
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002037listsort(PyListObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f236de1996-12-10 23:55:39 +00002038{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002039 MergeState ms;
2040 PyObject **lo, **hi;
2041 Py_ssize_t nremaining;
2042 Py_ssize_t minrun;
2043 Py_ssize_t saved_ob_size, saved_allocated;
2044 PyObject **saved_ob_item;
2045 PyObject **final_ob_item;
2046 PyObject *compare = NULL;
2047 PyObject *result = NULL; /* guilty until proved innocent */
2048 int reverse = 0;
2049 PyObject *keyfunc = NULL;
2050 Py_ssize_t i;
2051 PyObject *key, *value, *kvpair;
2052 static char *kwlist[] = {"cmp", "key", "reverse", 0};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002053
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002054 assert(self != NULL);
2055 assert (PyList_Check(self));
2056 if (args != NULL) {
2057 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOi:sort",
2058 kwlist, &compare, &keyfunc, &reverse))
2059 return NULL;
2060 }
2061 if (compare == Py_None)
2062 compare = NULL;
2063 if (compare != NULL &&
2064 PyErr_WarnPy3k("the cmp argument is not supported in 3.x", 1) < 0)
2065 return NULL;
2066 if (keyfunc == Py_None)
2067 keyfunc = NULL;
2068 if (compare != NULL && keyfunc != NULL) {
2069 compare = build_cmpwrapper(compare);
2070 if (compare == NULL)
2071 return NULL;
2072 } else
2073 Py_XINCREF(compare);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002074
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002075 /* The list is temporarily made empty, so that mutations performed
2076 * by comparison functions can't affect the slice of memory we're
2077 * sorting (allowing mutations during sorting is a core-dump
2078 * factory, since ob_item may change).
2079 */
2080 saved_ob_size = Py_SIZE(self);
2081 saved_ob_item = self->ob_item;
2082 saved_allocated = self->allocated;
2083 Py_SIZE(self) = 0;
2084 self->ob_item = NULL;
2085 self->allocated = -1; /* any operation will reset it to >= 0 */
Tim Peters330f9e92002-07-19 07:05:44 +00002086
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002087 if (keyfunc != NULL) {
2088 for (i=0 ; i < saved_ob_size ; i++) {
2089 value = saved_ob_item[i];
2090 key = PyObject_CallFunctionObjArgs(keyfunc, value,
2091 NULL);
2092 if (key == NULL) {
2093 for (i=i-1 ; i>=0 ; i--) {
2094 kvpair = saved_ob_item[i];
2095 value = sortwrapper_getvalue(kvpair);
2096 saved_ob_item[i] = value;
2097 Py_DECREF(kvpair);
2098 }
2099 goto dsu_fail;
2100 }
2101 kvpair = build_sortwrapper(key, value);
2102 if (kvpair == NULL)
2103 goto dsu_fail;
2104 saved_ob_item[i] = kvpair;
2105 }
2106 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002107
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002108 /* Reverse sort stability achieved by initially reversing the list,
2109 applying a stable forward sort, then reversing the final result. */
2110 if (reverse && saved_ob_size > 1)
2111 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002112
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002113 merge_init(&ms, compare);
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002114
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002115 nremaining = saved_ob_size;
2116 if (nremaining < 2)
2117 goto succeed;
Tim Peters330f9e92002-07-19 07:05:44 +00002118
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002119 /* March over the array once, left to right, finding natural runs,
2120 * and extending short natural runs to minrun elements.
2121 */
2122 lo = saved_ob_item;
2123 hi = lo + nremaining;
2124 minrun = merge_compute_minrun(nremaining);
2125 do {
2126 int descending;
2127 Py_ssize_t n;
Tim Peters330f9e92002-07-19 07:05:44 +00002128
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002129 /* Identify next run. */
2130 n = count_run(lo, hi, compare, &descending);
2131 if (n < 0)
2132 goto fail;
2133 if (descending)
2134 reverse_slice(lo, lo + n);
2135 /* If short, extend to min(minrun, nremaining). */
2136 if (n < minrun) {
2137 const Py_ssize_t force = nremaining <= minrun ?
2138 nremaining : minrun;
2139 if (binarysort(lo, lo + force, lo + n, compare) < 0)
2140 goto fail;
2141 n = force;
2142 }
2143 /* Push run onto pending-runs stack, and maybe merge. */
2144 assert(ms.n < MAX_MERGE_PENDING);
2145 ms.pending[ms.n].base = lo;
2146 ms.pending[ms.n].len = n;
2147 ++ms.n;
2148 if (merge_collapse(&ms) < 0)
2149 goto fail;
2150 /* Advance to find next run. */
2151 lo += n;
2152 nremaining -= n;
2153 } while (nremaining);
2154 assert(lo == hi);
Tim Peters330f9e92002-07-19 07:05:44 +00002155
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002156 if (merge_force_collapse(&ms) < 0)
2157 goto fail;
2158 assert(ms.n == 1);
2159 assert(ms.pending[0].base == saved_ob_item);
2160 assert(ms.pending[0].len == saved_ob_size);
Tim Petersa64dc242002-08-01 02:13:36 +00002161
2162succeed:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002163 result = Py_None;
Tim Peters330f9e92002-07-19 07:05:44 +00002164fail:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002165 if (keyfunc != NULL) {
2166 for (i=0 ; i < saved_ob_size ; i++) {
2167 kvpair = saved_ob_item[i];
2168 value = sortwrapper_getvalue(kvpair);
2169 saved_ob_item[i] = value;
2170 Py_DECREF(kvpair);
2171 }
2172 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002173
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002174 if (self->allocated != -1 && result != NULL) {
2175 /* The user mucked with the list during the sort,
2176 * and we don't already have another error to report.
2177 */
2178 PyErr_SetString(PyExc_ValueError, "list modified during sort");
2179 result = NULL;
2180 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002181
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002182 if (reverse && saved_ob_size > 1)
2183 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002184
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002185 merge_freemem(&ms);
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002186
2187dsu_fail:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002188 final_ob_item = self->ob_item;
2189 i = Py_SIZE(self);
2190 Py_SIZE(self) = saved_ob_size;
2191 self->ob_item = saved_ob_item;
2192 self->allocated = saved_allocated;
2193 if (final_ob_item != NULL) {
2194 /* we cannot use list_clear() for this because it does not
2195 guarantee that the list is really empty when it returns */
2196 while (--i >= 0) {
2197 Py_XDECREF(final_ob_item[i]);
2198 }
2199 PyMem_FREE(final_ob_item);
2200 }
2201 Py_XDECREF(compare);
2202 Py_XINCREF(result);
2203 return result;
Guido van Rossum3f236de1996-12-10 23:55:39 +00002204}
Tim Peters330f9e92002-07-19 07:05:44 +00002205#undef IFLT
Tim Peters66860f62002-08-04 17:47:26 +00002206#undef ISLT
Tim Peters330f9e92002-07-19 07:05:44 +00002207
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002208int
Fred Drakea2f55112000-07-09 15:16:51 +00002209PyList_Sort(PyObject *v)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002210{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002211 if (v == NULL || !PyList_Check(v)) {
2212 PyErr_BadInternalCall();
2213 return -1;
2214 }
2215 v = listsort((PyListObject *)v, (PyObject *)NULL, (PyObject *)NULL);
2216 if (v == NULL)
2217 return -1;
2218 Py_DECREF(v);
2219 return 0;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002220}
2221
Guido van Rossumb86c5492001-02-12 22:06:02 +00002222static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002223listreverse(PyListObject *self)
Guido van Rossumb86c5492001-02-12 22:06:02 +00002224{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002225 if (Py_SIZE(self) > 1)
2226 reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
2227 Py_RETURN_NONE;
Guido van Rossumed98d481991-03-06 13:07:53 +00002228}
2229
Guido van Rossum84c76f51990-10-30 13:32:20 +00002230int
Fred Drakea2f55112000-07-09 15:16:51 +00002231PyList_Reverse(PyObject *v)
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002232{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002233 PyListObject *self = (PyListObject *)v;
Tim Peters6063e262002-08-08 01:06:39 +00002234
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002235 if (v == NULL || !PyList_Check(v)) {
2236 PyErr_BadInternalCall();
2237 return -1;
2238 }
2239 if (Py_SIZE(self) > 1)
2240 reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
2241 return 0;
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002242}
2243
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002244PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00002245PyList_AsTuple(PyObject *v)
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002246{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002247 PyObject *w;
2248 PyObject **p, **q;
2249 Py_ssize_t n;
2250 if (v == NULL || !PyList_Check(v)) {
2251 PyErr_BadInternalCall();
2252 return NULL;
2253 }
2254 n = Py_SIZE(v);
2255 w = PyTuple_New(n);
2256 if (w == NULL)
2257 return NULL;
2258 p = ((PyTupleObject *)w)->ob_item;
2259 q = ((PyListObject *)v)->ob_item;
2260 while (--n >= 0) {
2261 Py_INCREF(*q);
2262 *p = *q;
2263 p++;
2264 q++;
2265 }
2266 return w;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002267}
2268
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002269static PyObject *
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002270listindex(PyListObject *self, PyObject *args)
Guido van Rossumed98d481991-03-06 13:07:53 +00002271{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002272 Py_ssize_t i, start=0, stop=Py_SIZE(self);
2273 PyObject *v;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002274
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002275 if (!PyArg_ParseTuple(args, "O|O&O&:index", &v,
2276 _PyEval_SliceIndex, &start,
2277 _PyEval_SliceIndex, &stop))
2278 return NULL;
2279 if (start < 0) {
2280 start += Py_SIZE(self);
2281 if (start < 0)
2282 start = 0;
2283 }
2284 if (stop < 0) {
2285 stop += Py_SIZE(self);
2286 if (stop < 0)
2287 stop = 0;
2288 }
2289 for (i = start; i < stop && i < Py_SIZE(self); i++) {
2290 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2291 if (cmp > 0)
2292 return PyInt_FromSsize_t(i);
2293 else if (cmp < 0)
2294 return NULL;
2295 }
2296 PyErr_SetString(PyExc_ValueError, "list.index(x): x not in list");
2297 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002298}
2299
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002300static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002301listcount(PyListObject *self, PyObject *v)
Guido van Rossume6f7d181991-10-20 20:20:40 +00002302{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002303 Py_ssize_t count = 0;
2304 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002305
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002306 for (i = 0; i < Py_SIZE(self); i++) {
2307 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2308 if (cmp > 0)
2309 count++;
2310 else if (cmp < 0)
2311 return NULL;
2312 }
2313 return PyInt_FromSsize_t(count);
Guido van Rossume6f7d181991-10-20 20:20:40 +00002314}
2315
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002316static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002317listremove(PyListObject *self, PyObject *v)
Guido van Rossumed98d481991-03-06 13:07:53 +00002318{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002319 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002320
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002321 for (i = 0; i < Py_SIZE(self); i++) {
2322 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2323 if (cmp > 0) {
2324 if (list_ass_slice(self, i, i+1,
2325 (PyObject *)NULL) == 0)
2326 Py_RETURN_NONE;
2327 return NULL;
2328 }
2329 else if (cmp < 0)
2330 return NULL;
2331 }
2332 PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
2333 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002334}
2335
Jeremy Hylton8caad492000-06-23 14:18:11 +00002336static int
2337list_traverse(PyListObject *o, visitproc visit, void *arg)
2338{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002339 Py_ssize_t i;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002340
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002341 for (i = Py_SIZE(o); --i >= 0; )
2342 Py_VISIT(o->ob_item[i]);
2343 return 0;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002344}
2345
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002346static PyObject *
2347list_richcompare(PyObject *v, PyObject *w, int op)
2348{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002349 PyListObject *vl, *wl;
2350 Py_ssize_t i;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002351
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002352 if (!PyList_Check(v) || !PyList_Check(w)) {
2353 Py_INCREF(Py_NotImplemented);
2354 return Py_NotImplemented;
2355 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002356
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002357 vl = (PyListObject *)v;
2358 wl = (PyListObject *)w;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002359
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002360 if (Py_SIZE(vl) != Py_SIZE(wl) && (op == Py_EQ || op == Py_NE)) {
2361 /* Shortcut: if the lengths differ, the lists differ */
2362 PyObject *res;
2363 if (op == Py_EQ)
2364 res = Py_False;
2365 else
2366 res = Py_True;
2367 Py_INCREF(res);
2368 return res;
2369 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002370
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002371 /* Search for the first index where items are different */
2372 for (i = 0; i < Py_SIZE(vl) && i < Py_SIZE(wl); i++) {
2373 int k = PyObject_RichCompareBool(vl->ob_item[i],
2374 wl->ob_item[i], Py_EQ);
2375 if (k < 0)
2376 return NULL;
2377 if (!k)
2378 break;
2379 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002380
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002381 if (i >= Py_SIZE(vl) || i >= Py_SIZE(wl)) {
2382 /* No more items to compare -- compare sizes */
2383 Py_ssize_t vs = Py_SIZE(vl);
2384 Py_ssize_t ws = Py_SIZE(wl);
2385 int cmp;
2386 PyObject *res;
2387 switch (op) {
2388 case Py_LT: cmp = vs < ws; break;
2389 case Py_LE: cmp = vs <= ws; break;
2390 case Py_EQ: cmp = vs == ws; break;
2391 case Py_NE: cmp = vs != ws; break;
2392 case Py_GT: cmp = vs > ws; break;
2393 case Py_GE: cmp = vs >= ws; break;
2394 default: return NULL; /* cannot happen */
2395 }
2396 if (cmp)
2397 res = Py_True;
2398 else
2399 res = Py_False;
2400 Py_INCREF(res);
2401 return res;
2402 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002403
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002404 /* We have an item that differs -- shortcuts for EQ/NE */
2405 if (op == Py_EQ) {
2406 Py_INCREF(Py_False);
2407 return Py_False;
2408 }
2409 if (op == Py_NE) {
2410 Py_INCREF(Py_True);
2411 return Py_True;
2412 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002413
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002414 /* Compare the final item again using the proper operator */
2415 return PyObject_RichCompare(vl->ob_item[i], wl->ob_item[i], op);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002416}
2417
Tim Peters6d6c1a32001-08-02 04:15:00 +00002418static int
2419list_init(PyListObject *self, PyObject *args, PyObject *kw)
2420{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002421 PyObject *arg = NULL;
2422 static char *kwlist[] = {"sequence", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002423
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002424 if (!PyArg_ParseTupleAndKeywords(args, kw, "|O:list", kwlist, &arg))
2425 return -1;
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002426
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002427 /* Verify list invariants established by PyType_GenericAlloc() */
2428 assert(0 <= Py_SIZE(self));
2429 assert(Py_SIZE(self) <= self->allocated || self->allocated == -1);
2430 assert(self->ob_item != NULL ||
2431 self->allocated == 0 || self->allocated == -1);
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002432
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002433 /* Empty previous contents */
2434 if (self->ob_item != NULL) {
2435 (void)list_clear(self);
2436 }
2437 if (arg != NULL) {
2438 PyObject *rv = listextend(self, arg);
2439 if (rv == NULL)
2440 return -1;
2441 Py_DECREF(rv);
2442 }
2443 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002444}
2445
Robert Schuppenies51df0642008-06-01 16:16:17 +00002446static PyObject *
2447list_sizeof(PyListObject *self)
2448{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002449 Py_ssize_t res;
Robert Schuppenies51df0642008-06-01 16:16:17 +00002450
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002451 res = sizeof(PyListObject) + self->allocated * sizeof(void*);
2452 return PyInt_FromSsize_t(res);
Robert Schuppenies51df0642008-06-01 16:16:17 +00002453}
2454
Raymond Hettinger1021c442003-11-07 15:38:09 +00002455static PyObject *list_iter(PyObject *seq);
2456static PyObject *list_reversed(PyListObject* seq, PyObject* unused);
2457
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002458PyDoc_STRVAR(getitem_doc,
2459"x.__getitem__(y) <==> x[y]");
Raymond Hettinger1021c442003-11-07 15:38:09 +00002460PyDoc_STRVAR(reversed_doc,
2461"L.__reversed__() -- return a reverse iterator over the list");
Robert Schuppenies51df0642008-06-01 16:16:17 +00002462PyDoc_STRVAR(sizeof_doc,
Georg Brandl7a6de8b2008-06-01 16:42:16 +00002463"L.__sizeof__() -- size of L in memory, in bytes");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002464PyDoc_STRVAR(append_doc,
2465"L.append(object) -- append object to end");
2466PyDoc_STRVAR(extend_doc,
Raymond Hettingerf8bcfb12002-12-29 05:49:09 +00002467"L.extend(iterable) -- extend list by appending elements from the iterable");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002468PyDoc_STRVAR(insert_doc,
2469"L.insert(index, object) -- insert object before index");
2470PyDoc_STRVAR(pop_doc,
Benjamin Petersonbe2c0a92008-10-04 21:33:08 +00002471"L.pop([index]) -> item -- remove and return item at index (default last).\n"
2472"Raises IndexError if list is empty or index is out of range.");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002473PyDoc_STRVAR(remove_doc,
Benjamin Petersonbe2c0a92008-10-04 21:33:08 +00002474"L.remove(value) -- remove first occurrence of value.\n"
2475"Raises ValueError if the value is not present.");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002476PyDoc_STRVAR(index_doc,
Benjamin Petersonbe2c0a92008-10-04 21:33:08 +00002477"L.index(value, [start, [stop]]) -> integer -- return first index of value.\n"
2478"Raises ValueError if the value is not present.");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002479PyDoc_STRVAR(count_doc,
2480"L.count(value) -> integer -- return number of occurrences of value");
2481PyDoc_STRVAR(reverse_doc,
2482"L.reverse() -- reverse *IN PLACE*");
2483PyDoc_STRVAR(sort_doc,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002484"L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;\n\
2485cmp(x, y) -> -1, 0, 1");
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +00002486
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002487static PyObject *list_subscript(PyListObject*, PyObject*);
2488
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002489static PyMethodDef list_methods[] = {
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002490 {"__getitem__", (PyCFunction)list_subscript, METH_O|METH_COEXIST, getitem_doc},
2491 {"__reversed__",(PyCFunction)list_reversed, METH_NOARGS, reversed_doc},
2492 {"__sizeof__", (PyCFunction)list_sizeof, METH_NOARGS, sizeof_doc},
2493 {"append", (PyCFunction)listappend, METH_O, append_doc},
2494 {"insert", (PyCFunction)listinsert, METH_VARARGS, insert_doc},
2495 {"extend", (PyCFunction)listextend, METH_O, extend_doc},
2496 {"pop", (PyCFunction)listpop, METH_VARARGS, pop_doc},
2497 {"remove", (PyCFunction)listremove, METH_O, remove_doc},
2498 {"index", (PyCFunction)listindex, METH_VARARGS, index_doc},
2499 {"count", (PyCFunction)listcount, METH_O, count_doc},
2500 {"reverse", (PyCFunction)listreverse, METH_NOARGS, reverse_doc},
2501 {"sort", (PyCFunction)listsort, METH_VARARGS | METH_KEYWORDS, sort_doc},
2502 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002503};
2504
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002505static PySequenceMethods list_as_sequence = {
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002506 (lenfunc)list_length, /* sq_length */
2507 (binaryfunc)list_concat, /* sq_concat */
2508 (ssizeargfunc)list_repeat, /* sq_repeat */
2509 (ssizeargfunc)list_item, /* sq_item */
2510 (ssizessizeargfunc)list_slice, /* sq_slice */
2511 (ssizeobjargproc)list_ass_item, /* sq_ass_item */
2512 (ssizessizeobjargproc)list_ass_slice, /* sq_ass_slice */
2513 (objobjproc)list_contains, /* sq_contains */
2514 (binaryfunc)list_inplace_concat, /* sq_inplace_concat */
2515 (ssizeargfunc)list_inplace_repeat, /* sq_inplace_repeat */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002516};
2517
Neal Norwitz2c2e8272002-06-14 02:04:18 +00002518PyDoc_STRVAR(list_doc,
Ezio Melotti56f16822010-03-01 04:05:56 +00002519"list() -> new empty list\n"
2520"list(iterable) -> new list initialized from iterable's items");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002521
Guido van Rossum38fff8c2006-03-07 18:50:55 +00002522
Jeremy Hyltona4b4c3b2002-07-13 03:51:17 +00002523static PyObject *
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002524list_subscript(PyListObject* self, PyObject* item)
2525{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002526 if (PyIndex_Check(item)) {
2527 Py_ssize_t i;
2528 i = PyNumber_AsSsize_t(item, PyExc_IndexError);
2529 if (i == -1 && PyErr_Occurred())
2530 return NULL;
2531 if (i < 0)
2532 i += PyList_GET_SIZE(self);
2533 return list_item(self, i);
2534 }
2535 else if (PySlice_Check(item)) {
2536 Py_ssize_t start, stop, step, slicelength, cur, i;
2537 PyObject* result;
2538 PyObject* it;
2539 PyObject **src, **dest;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002540
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002541 if (PySlice_GetIndicesEx((PySliceObject*)item, Py_SIZE(self),
2542 &start, &stop, &step, &slicelength) < 0) {
2543 return NULL;
2544 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002545
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002546 if (slicelength <= 0) {
2547 return PyList_New(0);
2548 }
2549 else if (step == 1) {
2550 return list_slice(self, start, stop);
2551 }
2552 else {
2553 result = PyList_New(slicelength);
2554 if (!result) return NULL;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002555
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002556 src = self->ob_item;
2557 dest = ((PyListObject *)result)->ob_item;
2558 for (cur = start, i = 0; i < slicelength;
2559 cur += step, i++) {
2560 it = src[cur];
2561 Py_INCREF(it);
2562 dest[i] = it;
2563 }
Tim Peters3b01a122002-07-19 02:35:45 +00002564
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002565 return result;
2566 }
2567 }
2568 else {
2569 PyErr_Format(PyExc_TypeError,
2570 "list indices must be integers, not %.200s",
2571 item->ob_type->tp_name);
2572 return NULL;
2573 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002574}
2575
Tim Peters3b01a122002-07-19 02:35:45 +00002576static int
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002577list_ass_subscript(PyListObject* self, PyObject* item, PyObject* value)
2578{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002579 if (PyIndex_Check(item)) {
2580 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
2581 if (i == -1 && PyErr_Occurred())
2582 return -1;
2583 if (i < 0)
2584 i += PyList_GET_SIZE(self);
2585 return list_ass_item(self, i, value);
2586 }
2587 else if (PySlice_Check(item)) {
2588 Py_ssize_t start, stop, step, slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002589
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002590 if (PySlice_GetIndicesEx((PySliceObject*)item, Py_SIZE(self),
2591 &start, &stop, &step, &slicelength) < 0) {
2592 return -1;
2593 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002594
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002595 if (step == 1)
2596 return list_ass_slice(self, start, stop, value);
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002597
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002598 /* Make sure s[5:2] = [..] inserts at the right place:
2599 before 5, not before 2. */
2600 if ((step < 0 && start < stop) ||
2601 (step > 0 && start > stop))
2602 stop = start;
Thomas Wouters3ccec682007-08-28 15:28:19 +00002603
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002604 if (value == NULL) {
2605 /* delete slice */
2606 PyObject **garbage;
2607 size_t cur;
2608 Py_ssize_t i;
Tim Peters3b01a122002-07-19 02:35:45 +00002609
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002610 if (slicelength <= 0)
2611 return 0;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002612
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002613 if (step < 0) {
2614 stop = start + 1;
2615 start = stop + step*(slicelength - 1) - 1;
2616 step = -step;
2617 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002618
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002619 assert((size_t)slicelength <=
2620 PY_SIZE_MAX / sizeof(PyObject*));
Gregory P. Smith9d534572008-06-11 07:41:16 +00002621
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002622 garbage = (PyObject**)
2623 PyMem_MALLOC(slicelength*sizeof(PyObject*));
2624 if (!garbage) {
2625 PyErr_NoMemory();
2626 return -1;
2627 }
Tim Peters3b01a122002-07-19 02:35:45 +00002628
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002629 /* drawing pictures might help understand these for
2630 loops. Basically, we memmove the parts of the
2631 list that are *not* part of the slice: step-1
2632 items for each item that is part of the slice,
2633 and then tail end of the list that was not
2634 covered by the slice */
2635 for (cur = start, i = 0;
2636 cur < (size_t)stop;
2637 cur += step, i++) {
2638 Py_ssize_t lim = step - 1;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002639
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002640 garbage[i] = PyList_GET_ITEM(self, cur);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002641
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002642 if (cur + step >= (size_t)Py_SIZE(self)) {
2643 lim = Py_SIZE(self) - cur - 1;
2644 }
Michael W. Hudson56796f62002-07-29 14:35:04 +00002645
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002646 memmove(self->ob_item + cur - i,
2647 self->ob_item + cur + 1,
2648 lim * sizeof(PyObject *));
2649 }
2650 cur = start + slicelength*step;
2651 if (cur < (size_t)Py_SIZE(self)) {
2652 memmove(self->ob_item + cur - slicelength,
2653 self->ob_item + cur,
2654 (Py_SIZE(self) - cur) *
2655 sizeof(PyObject *));
2656 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002657
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002658 Py_SIZE(self) -= slicelength;
2659 list_resize(self, Py_SIZE(self));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002660
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002661 for (i = 0; i < slicelength; i++) {
2662 Py_DECREF(garbage[i]);
2663 }
2664 PyMem_FREE(garbage);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002665
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002666 return 0;
2667 }
2668 else {
2669 /* assign slice */
2670 PyObject *ins, *seq;
2671 PyObject **garbage, **seqitems, **selfitems;
2672 Py_ssize_t cur, i;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002673
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002674 /* protect against a[::-1] = a */
2675 if (self == (PyListObject*)value) {
2676 seq = list_slice((PyListObject*)value, 0,
2677 PyList_GET_SIZE(value));
2678 }
2679 else {
2680 seq = PySequence_Fast(value,
2681 "must assign iterable "
2682 "to extended slice");
2683 }
2684 if (!seq)
2685 return -1;
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002686
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002687 if (PySequence_Fast_GET_SIZE(seq) != slicelength) {
2688 PyErr_Format(PyExc_ValueError,
2689 "attempt to assign sequence of "
2690 "size %zd to extended slice of "
2691 "size %zd",
2692 PySequence_Fast_GET_SIZE(seq),
2693 slicelength);
2694 Py_DECREF(seq);
2695 return -1;
2696 }
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002697
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002698 if (!slicelength) {
2699 Py_DECREF(seq);
2700 return 0;
2701 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002702
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002703 garbage = (PyObject**)
2704 PyMem_MALLOC(slicelength*sizeof(PyObject*));
2705 if (!garbage) {
2706 Py_DECREF(seq);
2707 PyErr_NoMemory();
2708 return -1;
2709 }
Tim Peters3b01a122002-07-19 02:35:45 +00002710
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002711 selfitems = self->ob_item;
2712 seqitems = PySequence_Fast_ITEMS(seq);
2713 for (cur = start, i = 0; i < slicelength;
2714 cur += step, i++) {
2715 garbage[i] = selfitems[cur];
2716 ins = seqitems[i];
2717 Py_INCREF(ins);
2718 selfitems[cur] = ins;
2719 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002720
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002721 for (i = 0; i < slicelength; i++) {
2722 Py_DECREF(garbage[i]);
2723 }
Tim Peters3b01a122002-07-19 02:35:45 +00002724
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002725 PyMem_FREE(garbage);
2726 Py_DECREF(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002727
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002728 return 0;
2729 }
2730 }
2731 else {
2732 PyErr_Format(PyExc_TypeError,
2733 "list indices must be integers, not %.200s",
2734 item->ob_type->tp_name);
2735 return -1;
2736 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002737}
2738
2739static PyMappingMethods list_as_mapping = {
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002740 (lenfunc)list_length,
2741 (binaryfunc)list_subscript,
2742 (objobjargproc)list_ass_subscript
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002743};
2744
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002745PyTypeObject PyList_Type = {
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002746 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2747 "list",
2748 sizeof(PyListObject),
2749 0,
2750 (destructor)list_dealloc, /* tp_dealloc */
2751 (printfunc)list_print, /* tp_print */
2752 0, /* tp_getattr */
2753 0, /* tp_setattr */
2754 0, /* tp_compare */
2755 (reprfunc)list_repr, /* tp_repr */
2756 0, /* tp_as_number */
2757 &list_as_sequence, /* tp_as_sequence */
2758 &list_as_mapping, /* tp_as_mapping */
2759 (hashfunc)PyObject_HashNotImplemented, /* tp_hash */
2760 0, /* tp_call */
2761 0, /* tp_str */
2762 PyObject_GenericGetAttr, /* tp_getattro */
2763 0, /* tp_setattro */
2764 0, /* tp_as_buffer */
2765 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2766 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LIST_SUBCLASS, /* tp_flags */
2767 list_doc, /* tp_doc */
2768 (traverseproc)list_traverse, /* tp_traverse */
2769 (inquiry)list_clear, /* tp_clear */
2770 list_richcompare, /* tp_richcompare */
2771 0, /* tp_weaklistoffset */
2772 list_iter, /* tp_iter */
2773 0, /* tp_iternext */
2774 list_methods, /* tp_methods */
2775 0, /* tp_members */
2776 0, /* tp_getset */
2777 0, /* tp_base */
2778 0, /* tp_dict */
2779 0, /* tp_descr_get */
2780 0, /* tp_descr_set */
2781 0, /* tp_dictoffset */
2782 (initproc)list_init, /* tp_init */
2783 PyType_GenericAlloc, /* tp_alloc */
2784 PyType_GenericNew, /* tp_new */
2785 PyObject_GC_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002786};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002787
2788
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002789/*********************** List Iterator **************************/
2790
2791typedef struct {
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002792 PyObject_HEAD
2793 long it_index;
2794 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002795} listiterobject;
2796
Anthony Baxter377be112006-04-11 06:54:30 +00002797static PyObject *list_iter(PyObject *);
2798static void listiter_dealloc(listiterobject *);
2799static int listiter_traverse(listiterobject *, visitproc, void *);
2800static PyObject *listiter_next(listiterobject *);
2801static PyObject *listiter_len(listiterobject *);
2802
2803PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
2804
2805static PyMethodDef listiter_methods[] = {
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002806 {"__length_hint__", (PyCFunction)listiter_len, METH_NOARGS, length_hint_doc},
2807 {NULL, NULL} /* sentinel */
Anthony Baxter377be112006-04-11 06:54:30 +00002808};
2809
2810PyTypeObject PyListIter_Type = {
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002811 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2812 "listiterator", /* tp_name */
2813 sizeof(listiterobject), /* tp_basicsize */
2814 0, /* tp_itemsize */
2815 /* methods */
2816 (destructor)listiter_dealloc, /* tp_dealloc */
2817 0, /* tp_print */
2818 0, /* tp_getattr */
2819 0, /* tp_setattr */
2820 0, /* tp_compare */
2821 0, /* tp_repr */
2822 0, /* tp_as_number */
2823 0, /* tp_as_sequence */
2824 0, /* tp_as_mapping */
2825 0, /* tp_hash */
2826 0, /* tp_call */
2827 0, /* tp_str */
2828 PyObject_GenericGetAttr, /* tp_getattro */
2829 0, /* tp_setattro */
2830 0, /* tp_as_buffer */
2831 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2832 0, /* tp_doc */
2833 (traverseproc)listiter_traverse, /* tp_traverse */
2834 0, /* tp_clear */
2835 0, /* tp_richcompare */
2836 0, /* tp_weaklistoffset */
2837 PyObject_SelfIter, /* tp_iter */
2838 (iternextfunc)listiter_next, /* tp_iternext */
2839 listiter_methods, /* tp_methods */
2840 0, /* tp_members */
Anthony Baxter377be112006-04-11 06:54:30 +00002841};
2842
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002843
Guido van Rossum5086e492002-07-16 15:56:52 +00002844static PyObject *
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002845list_iter(PyObject *seq)
2846{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002847 listiterobject *it;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002848
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002849 if (!PyList_Check(seq)) {
2850 PyErr_BadInternalCall();
2851 return NULL;
2852 }
2853 it = PyObject_GC_New(listiterobject, &PyListIter_Type);
2854 if (it == NULL)
2855 return NULL;
2856 it->it_index = 0;
2857 Py_INCREF(seq);
2858 it->it_seq = (PyListObject *)seq;
2859 _PyObject_GC_TRACK(it);
2860 return (PyObject *)it;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002861}
2862
2863static void
2864listiter_dealloc(listiterobject *it)
2865{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002866 _PyObject_GC_UNTRACK(it);
2867 Py_XDECREF(it->it_seq);
2868 PyObject_GC_Del(it);
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002869}
2870
2871static int
2872listiter_traverse(listiterobject *it, visitproc visit, void *arg)
2873{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002874 Py_VISIT(it->it_seq);
2875 return 0;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002876}
2877
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002878static PyObject *
Tim Peters93b2cc42002-06-01 05:22:55 +00002879listiter_next(listiterobject *it)
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002880{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002881 PyListObject *seq;
2882 PyObject *item;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002883
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002884 assert(it != NULL);
2885 seq = it->it_seq;
2886 if (seq == NULL)
2887 return NULL;
2888 assert(PyList_Check(seq));
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002889
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002890 if (it->it_index < PyList_GET_SIZE(seq)) {
2891 item = PyList_GET_ITEM(seq, it->it_index);
2892 ++it->it_index;
2893 Py_INCREF(item);
2894 return item;
2895 }
Guido van Rossum86103ae2002-07-16 20:07:32 +00002896
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002897 Py_DECREF(seq);
2898 it->it_seq = NULL;
2899 return NULL;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002900}
2901
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002902static PyObject *
Raymond Hettinger435bf582004-03-18 22:43:10 +00002903listiter_len(listiterobject *it)
2904{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002905 Py_ssize_t len;
2906 if (it->it_seq) {
2907 len = PyList_GET_SIZE(it->it_seq) - it->it_index;
2908 if (len >= 0)
2909 return PyInt_FromSsize_t(len);
2910 }
2911 return PyInt_FromLong(0);
Raymond Hettinger435bf582004-03-18 22:43:10 +00002912}
Anthony Baxter377be112006-04-11 06:54:30 +00002913/*********************** List Reverse Iterator **************************/
Raymond Hettinger435bf582004-03-18 22:43:10 +00002914
Anthony Baxter377be112006-04-11 06:54:30 +00002915typedef struct {
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002916 PyObject_HEAD
2917 Py_ssize_t it_index;
2918 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Anthony Baxter377be112006-04-11 06:54:30 +00002919} listreviterobject;
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002920
Anthony Baxter377be112006-04-11 06:54:30 +00002921static PyObject *list_reversed(PyListObject *, PyObject *);
2922static void listreviter_dealloc(listreviterobject *);
2923static int listreviter_traverse(listreviterobject *, visitproc, void *);
2924static PyObject *listreviter_next(listreviterobject *);
Georg Brandlfa71a902008-12-05 09:08:28 +00002925static PyObject *listreviter_len(listreviterobject *);
Anthony Baxter377be112006-04-11 06:54:30 +00002926
Georg Brandlfa71a902008-12-05 09:08:28 +00002927static PyMethodDef listreviter_methods[] = {
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002928 {"__length_hint__", (PyCFunction)listreviter_len, METH_NOARGS, length_hint_doc},
2929 {NULL, NULL} /* sentinel */
Raymond Hettinger435bf582004-03-18 22:43:10 +00002930};
2931
Anthony Baxter377be112006-04-11 06:54:30 +00002932PyTypeObject PyListRevIter_Type = {
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002933 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2934 "listreverseiterator", /* tp_name */
2935 sizeof(listreviterobject), /* tp_basicsize */
2936 0, /* tp_itemsize */
2937 /* methods */
2938 (destructor)listreviter_dealloc, /* tp_dealloc */
2939 0, /* tp_print */
2940 0, /* tp_getattr */
2941 0, /* tp_setattr */
2942 0, /* tp_compare */
2943 0, /* tp_repr */
2944 0, /* tp_as_number */
2945 0, /* tp_as_sequence */
2946 0, /* tp_as_mapping */
2947 0, /* tp_hash */
2948 0, /* tp_call */
2949 0, /* tp_str */
2950 PyObject_GenericGetAttr, /* tp_getattro */
2951 0, /* tp_setattro */
2952 0, /* tp_as_buffer */
2953 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2954 0, /* tp_doc */
2955 (traverseproc)listreviter_traverse, /* tp_traverse */
2956 0, /* tp_clear */
2957 0, /* tp_richcompare */
2958 0, /* tp_weaklistoffset */
2959 PyObject_SelfIter, /* tp_iter */
2960 (iternextfunc)listreviter_next, /* tp_iternext */
2961 listreviter_methods, /* tp_methods */
2962 0,
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002963};
Raymond Hettinger1021c442003-11-07 15:38:09 +00002964
Raymond Hettinger1021c442003-11-07 15:38:09 +00002965static PyObject *
2966list_reversed(PyListObject *seq, PyObject *unused)
2967{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002968 listreviterobject *it;
Raymond Hettinger1021c442003-11-07 15:38:09 +00002969
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002970 it = PyObject_GC_New(listreviterobject, &PyListRevIter_Type);
2971 if (it == NULL)
2972 return NULL;
2973 assert(PyList_Check(seq));
2974 it->it_index = PyList_GET_SIZE(seq) - 1;
2975 Py_INCREF(seq);
2976 it->it_seq = seq;
2977 PyObject_GC_Track(it);
2978 return (PyObject *)it;
Raymond Hettinger1021c442003-11-07 15:38:09 +00002979}
2980
2981static void
2982listreviter_dealloc(listreviterobject *it)
2983{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002984 PyObject_GC_UnTrack(it);
2985 Py_XDECREF(it->it_seq);
2986 PyObject_GC_Del(it);
Raymond Hettinger1021c442003-11-07 15:38:09 +00002987}
2988
2989static int
2990listreviter_traverse(listreviterobject *it, visitproc visit, void *arg)
2991{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002992 Py_VISIT(it->it_seq);
2993 return 0;
Raymond Hettinger1021c442003-11-07 15:38:09 +00002994}
2995
2996static PyObject *
2997listreviter_next(listreviterobject *it)
2998{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002999 PyObject *item;
3000 Py_ssize_t index = it->it_index;
3001 PyListObject *seq = it->it_seq;
Raymond Hettinger1021c442003-11-07 15:38:09 +00003002
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00003003 if (index>=0 && index < PyList_GET_SIZE(seq)) {
3004 item = PyList_GET_ITEM(seq, index);
3005 it->it_index--;
3006 Py_INCREF(item);
3007 return item;
3008 }
3009 it->it_index = -1;
3010 if (seq != NULL) {
3011 it->it_seq = NULL;
3012 Py_DECREF(seq);
3013 }
3014 return NULL;
Raymond Hettinger1021c442003-11-07 15:38:09 +00003015}
3016
Georg Brandlfa71a902008-12-05 09:08:28 +00003017static PyObject *
Raymond Hettingeref9bf402004-03-10 10:10:42 +00003018listreviter_len(listreviterobject *it)
3019{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00003020 Py_ssize_t len = it->it_index + 1;
3021 if (it->it_seq == NULL || PyList_GET_SIZE(it->it_seq) < len)
3022 len = 0;
3023 return PyLong_FromSsize_t(len);
Raymond Hettingeref9bf402004-03-10 10:10:42 +00003024}