blob: ddc0fee41ab1b2bd45a4b31abe697fcaa99336c3 [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"
Antoine Pitrou0197ff92012-03-22 14:38:16 +01004#include "accu.h"
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00006#ifdef STDC_HEADERS
7#include <stddef.h>
8#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00009#include <sys/types.h> /* For size_t */
Guido van Rossum6cd2fe01994-08-29 12:45:32 +000010#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000011
Tim Peters8d9eb102004-07-31 02:24:20 +000012/* Ensure ob_item has room for at least newsize elements, and set
13 * ob_size to newsize. If newsize > ob_size on entry, the content
14 * of the new slots at exit is undefined heap trash; it's the caller's
Ezio Melotti13925002011-03-16 11:05:33 +020015 * responsibility to overwrite them with sane values.
Tim Peters8d9eb102004-07-31 02:24:20 +000016 * The number of allocated elements may grow, shrink, or stay the same.
17 * Failure is impossible if newsize <= self.allocated on entry, although
18 * that partly relies on an assumption that the system realloc() never
19 * fails when passed a number of bytes <= the number of bytes last
20 * allocated (the C standard doesn't guarantee this, but it's hard to
21 * imagine a realloc implementation where it wouldn't be true).
22 * Note that self->ob_item may change, and even if newsize is less
23 * than ob_size on entry.
24 */
Guido van Rossuma46d51d1995-01-26 22:59:43 +000025static int
Martin v. Löwis18e16552006-02-15 17:27:45 +000026list_resize(PyListObject *self, Py_ssize_t newsize)
Guido van Rossuma46d51d1995-01-26 22:59:43 +000027{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000028 PyObject **items;
29 size_t new_allocated;
30 Py_ssize_t allocated = self->allocated;
Tim Peters65b8b842001-05-26 05:28:40 +000031
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000032 /* Bypass realloc() when a previous overallocation is large enough
33 to accommodate the newsize. If the newsize falls lower than half
34 the allocated size, then proceed with the realloc() to shrink the list.
35 */
36 if (allocated >= newsize && newsize >= (allocated >> 1)) {
37 assert(self->ob_item != NULL || newsize == 0);
38 Py_SIZE(self) = newsize;
39 return 0;
40 }
Raymond Hettinger4bb95402004-02-13 11:36:39 +000041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000042 /* This over-allocates proportional to the list size, making room
43 * for additional growth. The over-allocation is mild, but is
44 * enough to give linear-time amortized behavior over a long
45 * sequence of appends() in the presence of a poorly-performing
46 * system realloc().
47 * The growth pattern is: 0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ...
48 */
49 new_allocated = (newsize >> 3) + (newsize < 9 ? 3 : 6);
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +000050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000051 /* check for integer overflow */
52 if (new_allocated > PY_SIZE_MAX - newsize) {
53 PyErr_NoMemory();
54 return -1;
55 } else {
56 new_allocated += newsize;
57 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +000058
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000059 if (newsize == 0)
60 new_allocated = 0;
61 items = self->ob_item;
Mark Dickinsonc0420fd2011-09-19 19:18:37 +010062 if (new_allocated <= (PY_SIZE_MAX / sizeof(PyObject *)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000063 PyMem_RESIZE(items, PyObject *, new_allocated);
64 else
65 items = NULL;
66 if (items == NULL) {
67 PyErr_NoMemory();
68 return -1;
69 }
70 self->ob_item = items;
71 Py_SIZE(self) = newsize;
72 self->allocated = new_allocated;
73 return 0;
Raymond Hettinger4bb95402004-02-13 11:36:39 +000074}
Guido van Rossuma46d51d1995-01-26 22:59:43 +000075
Christian Heimes77c02eb2008-02-09 02:18:51 +000076/* Debug statistic to compare allocations with reuse through the free list */
77#undef SHOW_ALLOC_COUNT
78#ifdef SHOW_ALLOC_COUNT
79static size_t count_alloc = 0;
80static size_t count_reuse = 0;
81
82static void
83show_alloc(void)
84{
Serhiy Storchaka7e160ce2016-07-03 21:03:53 +030085 PyObject *xoptions, *value;
86 _Py_IDENTIFIER(showalloccount);
87
88 xoptions = PySys_GetXOptions();
89 if (xoptions == NULL)
90 return;
91 value = _PyDict_GetItemId(xoptions, &PyId_showalloccount);
92 if (value != Py_True)
93 return;
94
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000095 fprintf(stderr, "List allocations: %" PY_FORMAT_SIZE_T "d\n",
96 count_alloc);
97 fprintf(stderr, "List reuse through freelist: %" PY_FORMAT_SIZE_T
98 "d\n", count_reuse);
99 fprintf(stderr, "%.2f%% reuse rate\n\n",
100 (100.0*count_reuse/(count_alloc+count_reuse)));
Christian Heimes77c02eb2008-02-09 02:18:51 +0000101}
102#endif
103
Raymond Hettinger0468e412004-05-05 05:37:53 +0000104/* Empty list reuse scheme to save calls to malloc and free */
Christian Heimes2202f872008-02-06 14:31:34 +0000105#ifndef PyList_MAXFREELIST
106#define PyList_MAXFREELIST 80
107#endif
108static PyListObject *free_list[PyList_MAXFREELIST];
109static int numfree = 0;
Raymond Hettinger0468e412004-05-05 05:37:53 +0000110
Antoine Pitrou9a812cb2011-11-15 00:00:12 +0100111int
112PyList_ClearFreeList(void)
Raymond Hettingerfb09f0e2004-10-07 03:58:07 +0000113{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000114 PyListObject *op;
Antoine Pitrou9a812cb2011-11-15 00:00:12 +0100115 int ret = numfree;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000116 while (numfree) {
117 op = free_list[--numfree];
118 assert(PyList_CheckExact(op));
119 PyObject_GC_Del(op);
120 }
Antoine Pitrou9a812cb2011-11-15 00:00:12 +0100121 return ret;
122}
123
124void
125PyList_Fini(void)
126{
127 PyList_ClearFreeList();
Raymond Hettingerfb09f0e2004-10-07 03:58:07 +0000128}
129
David Malcolm49526f42012-06-22 14:55:41 -0400130/* Print summary info about the state of the optimized allocator */
131void
132_PyList_DebugMallocStats(FILE *out)
133{
134 _PyDebugAllocatorStats(out,
135 "free PyListObject",
136 numfree, sizeof(PyListObject));
137}
138
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000139PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000140PyList_New(Py_ssize_t size)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000141{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000142 PyListObject *op;
143 size_t nbytes;
Christian Heimes77c02eb2008-02-09 02:18:51 +0000144#ifdef SHOW_ALLOC_COUNT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000145 static int initialized = 0;
146 if (!initialized) {
147 Py_AtExit(show_alloc);
148 initialized = 1;
149 }
Christian Heimes77c02eb2008-02-09 02:18:51 +0000150#endif
Tim Peters3986d4e2004-07-29 02:28:42 +0000151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000152 if (size < 0) {
153 PyErr_BadInternalCall();
154 return NULL;
155 }
156 /* Check for overflow without an actual overflow,
157 * which can cause compiler to optimise out */
158 if ((size_t)size > PY_SIZE_MAX / sizeof(PyObject *))
159 return PyErr_NoMemory();
160 nbytes = size * sizeof(PyObject *);
161 if (numfree) {
162 numfree--;
163 op = free_list[numfree];
164 _Py_NewReference((PyObject *)op);
Christian Heimes77c02eb2008-02-09 02:18:51 +0000165#ifdef SHOW_ALLOC_COUNT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000166 count_reuse++;
Christian Heimes77c02eb2008-02-09 02:18:51 +0000167#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000168 } else {
169 op = PyObject_GC_New(PyListObject, &PyList_Type);
170 if (op == NULL)
171 return NULL;
Christian Heimes77c02eb2008-02-09 02:18:51 +0000172#ifdef SHOW_ALLOC_COUNT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000173 count_alloc++;
Christian Heimes77c02eb2008-02-09 02:18:51 +0000174#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175 }
176 if (size <= 0)
177 op->ob_item = NULL;
178 else {
179 op->ob_item = (PyObject **) PyMem_MALLOC(nbytes);
180 if (op->ob_item == NULL) {
181 Py_DECREF(op);
182 return PyErr_NoMemory();
183 }
184 memset(op->ob_item, 0, nbytes);
185 }
186 Py_SIZE(op) = size;
187 op->allocated = size;
188 _PyObject_GC_TRACK(op);
189 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000190}
191
Martin v. Löwis18e16552006-02-15 17:27:45 +0000192Py_ssize_t
Fred Drakea2f55112000-07-09 15:16:51 +0000193PyList_Size(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000194{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000195 if (!PyList_Check(op)) {
196 PyErr_BadInternalCall();
197 return -1;
198 }
199 else
200 return Py_SIZE(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000201}
202
Raymond Hettingerfdfe6182004-05-05 06:28:16 +0000203static PyObject *indexerr = NULL;
Guido van Rossum929f1b81996-08-09 20:51:27 +0000204
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000205PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000206PyList_GetItem(PyObject *op, Py_ssize_t i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000207{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000208 if (!PyList_Check(op)) {
209 PyErr_BadInternalCall();
210 return NULL;
211 }
212 if (i < 0 || i >= Py_SIZE(op)) {
213 if (indexerr == NULL) {
214 indexerr = PyUnicode_FromString(
215 "list index out of range");
216 if (indexerr == NULL)
217 return NULL;
218 }
219 PyErr_SetObject(PyExc_IndexError, indexerr);
220 return NULL;
221 }
222 return ((PyListObject *)op) -> ob_item[i];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000223}
224
225int
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200226PyList_SetItem(PyObject *op, Py_ssize_t i,
227 PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000228{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200229 PyObject **p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000230 if (!PyList_Check(op)) {
231 Py_XDECREF(newitem);
232 PyErr_BadInternalCall();
233 return -1;
234 }
235 if (i < 0 || i >= Py_SIZE(op)) {
236 Py_XDECREF(newitem);
237 PyErr_SetString(PyExc_IndexError,
238 "list assignment index out of range");
239 return -1;
240 }
241 p = ((PyListObject *)op) -> ob_item + i;
Serhiy Storchakaec397562016-04-06 09:50:03 +0300242 Py_XSETREF(*p, newitem);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000243 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000244}
245
246static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000247ins1(PyListObject *self, Py_ssize_t where, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000248{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000249 Py_ssize_t i, n = Py_SIZE(self);
250 PyObject **items;
251 if (v == NULL) {
252 PyErr_BadInternalCall();
253 return -1;
254 }
255 if (n == PY_SSIZE_T_MAX) {
256 PyErr_SetString(PyExc_OverflowError,
257 "cannot add more objects to list");
258 return -1;
259 }
Tim Petersb38e2b62004-07-29 02:29:26 +0000260
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800261 if (list_resize(self, n+1) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000262 return -1;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000264 if (where < 0) {
265 where += n;
266 if (where < 0)
267 where = 0;
268 }
269 if (where > n)
270 where = n;
271 items = self->ob_item;
272 for (i = n; --i >= where; )
273 items[i+1] = items[i];
274 Py_INCREF(v);
275 items[where] = v;
276 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000277}
278
279int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000280PyList_Insert(PyObject *op, Py_ssize_t where, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000281{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000282 if (!PyList_Check(op)) {
283 PyErr_BadInternalCall();
284 return -1;
285 }
286 return ins1((PyListObject *)op, where, newitem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000287}
288
Raymond Hettinger40a03822004-04-12 13:05:09 +0000289static int
290app1(PyListObject *self, PyObject *v)
291{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000292 Py_ssize_t n = PyList_GET_SIZE(self);
Raymond Hettinger40a03822004-04-12 13:05:09 +0000293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000294 assert (v != NULL);
295 if (n == PY_SSIZE_T_MAX) {
296 PyErr_SetString(PyExc_OverflowError,
297 "cannot add more objects to list");
298 return -1;
299 }
Raymond Hettinger40a03822004-04-12 13:05:09 +0000300
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800301 if (list_resize(self, n+1) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000302 return -1;
Raymond Hettinger40a03822004-04-12 13:05:09 +0000303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000304 Py_INCREF(v);
305 PyList_SET_ITEM(self, n, v);
306 return 0;
Raymond Hettinger40a03822004-04-12 13:05:09 +0000307}
308
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000309int
Fred Drakea2f55112000-07-09 15:16:51 +0000310PyList_Append(PyObject *op, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000311{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000312 if (PyList_Check(op) && (newitem != NULL))
313 return app1((PyListObject *)op, newitem);
314 PyErr_BadInternalCall();
315 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000316}
317
318/* Methods */
319
320static void
Fred Drakea2f55112000-07-09 15:16:51 +0000321list_dealloc(PyListObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000322{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000323 Py_ssize_t i;
324 PyObject_GC_UnTrack(op);
325 Py_TRASHCAN_SAFE_BEGIN(op)
326 if (op->ob_item != NULL) {
327 /* Do it backwards, for Christian Tismer.
328 There's a simple test case where somehow this reduces
329 thrashing when a *very* large list is created and
330 immediately deleted. */
331 i = Py_SIZE(op);
332 while (--i >= 0) {
333 Py_XDECREF(op->ob_item[i]);
334 }
335 PyMem_FREE(op->ob_item);
336 }
337 if (numfree < PyList_MAXFREELIST && PyList_CheckExact(op))
338 free_list[numfree++] = op;
339 else
340 Py_TYPE(op)->tp_free((PyObject *)op);
341 Py_TRASHCAN_SAFE_END(op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000342}
343
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000344static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000345list_repr(PyListObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000346{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000347 Py_ssize_t i;
Victor Stinner5c733472013-11-18 21:11:57 +0100348 PyObject *s;
Victor Stinner5c733472013-11-18 21:11:57 +0100349 _PyUnicodeWriter writer;
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200350
351 if (Py_SIZE(v) == 0) {
352 return PyUnicode_FromString("[]");
353 }
354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000355 i = Py_ReprEnter((PyObject*)v);
356 if (i != 0) {
357 return i > 0 ? PyUnicode_FromString("[...]") : NULL;
358 }
Tim Petersa7259592001-06-16 05:11:17 +0000359
Victor Stinner5c733472013-11-18 21:11:57 +0100360 _PyUnicodeWriter_Init(&writer);
361 writer.overallocate = 1;
Victor Stinnerb8fb1972013-11-18 22:15:44 +0100362 /* "[" + "1" + ", 2" * (len - 1) + "]" */
363 writer.min_length = 1 + 1 + (2 + 1) * (Py_SIZE(v) - 1) + 1;
Tim Petersa7259592001-06-16 05:11:17 +0000364
Victor Stinner5c733472013-11-18 21:11:57 +0100365 if (_PyUnicodeWriter_WriteChar(&writer, '[') < 0)
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200366 goto error;
Tim Petersa7259592001-06-16 05:11:17 +0000367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000368 /* Do repr() on each element. Note that this may mutate the list,
369 so must refetch the list size on each iteration. */
370 for (i = 0; i < Py_SIZE(v); ++i) {
Victor Stinner5c733472013-11-18 21:11:57 +0100371 if (i > 0) {
Victor Stinner4a587072013-11-19 12:54:53 +0100372 if (_PyUnicodeWriter_WriteASCIIString(&writer, ", ", 2) < 0)
Victor Stinner5c733472013-11-18 21:11:57 +0100373 goto error;
374 }
375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000376 if (Py_EnterRecursiveCall(" while getting the repr of a list"))
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200377 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000378 s = PyObject_Repr(v->ob_item[i]);
379 Py_LeaveRecursiveCall();
Victor Stinner5c733472013-11-18 21:11:57 +0100380 if (s == NULL)
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200381 goto error;
Victor Stinner5c733472013-11-18 21:11:57 +0100382
383 if (_PyUnicodeWriter_WriteStr(&writer, s) < 0) {
384 Py_DECREF(s);
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200385 goto error;
Victor Stinner5c733472013-11-18 21:11:57 +0100386 }
387 Py_DECREF(s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000388 }
Victor Stinner5c733472013-11-18 21:11:57 +0100389
Victor Stinner4d3f1092013-11-19 12:09:00 +0100390 writer.overallocate = 0;
Victor Stinner5c733472013-11-18 21:11:57 +0100391 if (_PyUnicodeWriter_WriteChar(&writer, ']') < 0)
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200392 goto error;
Tim Petersa7259592001-06-16 05:11:17 +0000393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000394 Py_ReprLeave((PyObject *)v);
Victor Stinner5c733472013-11-18 21:11:57 +0100395 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200396
397error:
Victor Stinner5c733472013-11-18 21:11:57 +0100398 _PyUnicodeWriter_Dealloc(&writer);
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200399 Py_ReprLeave((PyObject *)v);
400 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000401}
402
Martin v. Löwis18e16552006-02-15 17:27:45 +0000403static Py_ssize_t
Fred Drakea2f55112000-07-09 15:16:51 +0000404list_length(PyListObject *a)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000405{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000406 return Py_SIZE(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000407}
408
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000409static int
Fred Drakea2f55112000-07-09 15:16:51 +0000410list_contains(PyListObject *a, PyObject *el)
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000411{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000412 Py_ssize_t i;
413 int cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000415 for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(a); ++i)
416 cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i),
417 Py_EQ);
418 return cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000419}
420
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000421static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000422list_item(PyListObject *a, Py_ssize_t i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000423{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000424 if (i < 0 || i >= Py_SIZE(a)) {
425 if (indexerr == NULL) {
426 indexerr = PyUnicode_FromString(
427 "list index out of range");
428 if (indexerr == NULL)
429 return NULL;
430 }
431 PyErr_SetObject(PyExc_IndexError, indexerr);
432 return NULL;
433 }
434 Py_INCREF(a->ob_item[i]);
435 return a->ob_item[i];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000436}
437
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000438static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000439list_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000440{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000441 PyListObject *np;
442 PyObject **src, **dest;
443 Py_ssize_t i, len;
444 if (ilow < 0)
445 ilow = 0;
446 else if (ilow > Py_SIZE(a))
447 ilow = Py_SIZE(a);
448 if (ihigh < ilow)
449 ihigh = ilow;
450 else if (ihigh > Py_SIZE(a))
451 ihigh = Py_SIZE(a);
452 len = ihigh - ilow;
453 np = (PyListObject *) PyList_New(len);
454 if (np == NULL)
455 return NULL;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000457 src = a->ob_item + ilow;
458 dest = np->ob_item;
459 for (i = 0; i < len; i++) {
460 PyObject *v = src[i];
461 Py_INCREF(v);
462 dest[i] = v;
463 }
464 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000465}
466
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000467PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000468PyList_GetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum234f9421993-06-17 12:35:49 +0000469{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000470 if (!PyList_Check(a)) {
471 PyErr_BadInternalCall();
472 return NULL;
473 }
474 return list_slice((PyListObject *)a, ilow, ihigh);
Guido van Rossum234f9421993-06-17 12:35:49 +0000475}
476
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000477static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000478list_concat(PyListObject *a, PyObject *bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000479{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000480 Py_ssize_t size;
481 Py_ssize_t i;
482 PyObject **src, **dest;
483 PyListObject *np;
484 if (!PyList_Check(bb)) {
485 PyErr_Format(PyExc_TypeError,
486 "can only concatenate list (not \"%.200s\") to list",
487 bb->ob_type->tp_name);
488 return NULL;
489 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000490#define b ((PyListObject *)bb)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000491 size = Py_SIZE(a) + Py_SIZE(b);
492 if (size < 0)
493 return PyErr_NoMemory();
494 np = (PyListObject *) PyList_New(size);
495 if (np == NULL) {
496 return NULL;
497 }
498 src = a->ob_item;
499 dest = np->ob_item;
500 for (i = 0; i < Py_SIZE(a); i++) {
501 PyObject *v = src[i];
502 Py_INCREF(v);
503 dest[i] = v;
504 }
505 src = b->ob_item;
506 dest = np->ob_item + Py_SIZE(a);
507 for (i = 0; i < Py_SIZE(b); i++) {
508 PyObject *v = src[i];
509 Py_INCREF(v);
510 dest[i] = v;
511 }
512 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000513#undef b
514}
515
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000516static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000517list_repeat(PyListObject *a, Py_ssize_t n)
Guido van Rossumed98d481991-03-06 13:07:53 +0000518{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 Py_ssize_t i, j;
520 Py_ssize_t size;
521 PyListObject *np;
522 PyObject **p, **items;
523 PyObject *elem;
524 if (n < 0)
525 n = 0;
Mark Dickinsonc0420fd2011-09-19 19:18:37 +0100526 if (n > 0 && Py_SIZE(a) > PY_SSIZE_T_MAX / n)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000527 return PyErr_NoMemory();
Mark Dickinsonc0420fd2011-09-19 19:18:37 +0100528 size = Py_SIZE(a) * n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000529 if (size == 0)
530 return PyList_New(0);
531 np = (PyListObject *) PyList_New(size);
532 if (np == NULL)
533 return NULL;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 items = np->ob_item;
536 if (Py_SIZE(a) == 1) {
537 elem = a->ob_item[0];
538 for (i = 0; i < n; i++) {
539 items[i] = elem;
540 Py_INCREF(elem);
541 }
542 return (PyObject *) np;
543 }
544 p = np->ob_item;
545 items = a->ob_item;
546 for (i = 0; i < n; i++) {
547 for (j = 0; j < Py_SIZE(a); j++) {
548 *p = items[j];
549 Py_INCREF(*p);
550 p++;
551 }
552 }
553 return (PyObject *) np;
Guido van Rossumed98d481991-03-06 13:07:53 +0000554}
555
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000556static int
Armin Rigo93677f02004-07-29 12:40:23 +0000557list_clear(PyListObject *a)
558{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 Py_ssize_t i;
560 PyObject **item = a->ob_item;
561 if (item != NULL) {
562 /* Because XDECREF can recursively invoke operations on
563 this list, we make it empty first. */
564 i = Py_SIZE(a);
565 Py_SIZE(a) = 0;
566 a->ob_item = NULL;
567 a->allocated = 0;
568 while (--i >= 0) {
569 Py_XDECREF(item[i]);
570 }
571 PyMem_FREE(item);
572 }
573 /* Never fails; the return value can be ignored.
574 Note that there is no guarantee that the list is actually empty
575 at this point, because XDECREF may have populated it again! */
576 return 0;
Armin Rigo93677f02004-07-29 12:40:23 +0000577}
578
Tim Peters8fc4a912004-07-31 21:53:19 +0000579/* a[ilow:ihigh] = v if v != NULL.
580 * del a[ilow:ihigh] if v == NULL.
581 *
582 * Special speed gimmick: when v is NULL and ihigh - ilow <= 8, it's
583 * guaranteed the call cannot fail.
584 */
Armin Rigo93677f02004-07-29 12:40:23 +0000585static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000586list_ass_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000587{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000588 /* Because [X]DECREF can recursively invoke list operations on
589 this list, we must postpone all [X]DECREF activity until
590 after the list is back in its canonical shape. Therefore
591 we must allocate an additional array, 'recycle', into which
592 we temporarily copy the items that are deleted from the
593 list. :-( */
594 PyObject *recycle_on_stack[8];
595 PyObject **recycle = recycle_on_stack; /* will allocate more if needed */
596 PyObject **item;
597 PyObject **vitem = NULL;
598 PyObject *v_as_SF = NULL; /* PySequence_Fast(v) */
599 Py_ssize_t n; /* # of elements in replacement list */
600 Py_ssize_t norig; /* # of elements in list getting replaced */
601 Py_ssize_t d; /* Change in size */
602 Py_ssize_t k;
603 size_t s;
604 int result = -1; /* guilty until proved innocent */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000605#define b ((PyListObject *)v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 if (v == NULL)
607 n = 0;
608 else {
609 if (a == b) {
610 /* Special case "a[i:j] = a" -- copy b first */
611 v = list_slice(b, 0, Py_SIZE(b));
612 if (v == NULL)
613 return result;
614 result = list_ass_slice(a, ilow, ihigh, v);
615 Py_DECREF(v);
616 return result;
617 }
618 v_as_SF = PySequence_Fast(v, "can only assign an iterable");
619 if(v_as_SF == NULL)
620 goto Error;
621 n = PySequence_Fast_GET_SIZE(v_as_SF);
622 vitem = PySequence_Fast_ITEMS(v_as_SF);
623 }
624 if (ilow < 0)
625 ilow = 0;
626 else if (ilow > Py_SIZE(a))
627 ilow = Py_SIZE(a);
Tim Peters8d9eb102004-07-31 02:24:20 +0000628
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000629 if (ihigh < ilow)
630 ihigh = ilow;
631 else if (ihigh > Py_SIZE(a))
632 ihigh = Py_SIZE(a);
Armin Rigo93677f02004-07-29 12:40:23 +0000633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 norig = ihigh - ilow;
635 assert(norig >= 0);
636 d = n - norig;
637 if (Py_SIZE(a) + d == 0) {
638 Py_XDECREF(v_as_SF);
639 return list_clear(a);
640 }
641 item = a->ob_item;
642 /* recycle the items that we are about to remove */
643 s = norig * sizeof(PyObject *);
644 if (s > sizeof(recycle_on_stack)) {
645 recycle = (PyObject **)PyMem_MALLOC(s);
646 if (recycle == NULL) {
647 PyErr_NoMemory();
648 goto Error;
649 }
650 }
651 memcpy(recycle, &item[ilow], s);
Tim Peters8d9eb102004-07-31 02:24:20 +0000652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000653 if (d < 0) { /* Delete -d items */
Victor Stinner2c40f642013-07-19 23:06:21 +0200654 Py_ssize_t tail;
655 tail = (Py_SIZE(a) - ihigh) * sizeof(PyObject *);
656 memmove(&item[ihigh+d], &item[ihigh], tail);
657 if (list_resize(a, Py_SIZE(a) + d) < 0) {
658 memmove(&item[ihigh], &item[ihigh+d], tail);
659 memcpy(&item[ilow], recycle, s);
660 goto Error;
661 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000662 item = a->ob_item;
663 }
664 else if (d > 0) { /* Insert d items */
665 k = Py_SIZE(a);
666 if (list_resize(a, k+d) < 0)
667 goto Error;
668 item = a->ob_item;
669 memmove(&item[ihigh+d], &item[ihigh],
670 (k - ihigh)*sizeof(PyObject *));
671 }
672 for (k = 0; k < n; k++, ilow++) {
673 PyObject *w = vitem[k];
674 Py_XINCREF(w);
675 item[ilow] = w;
676 }
677 for (k = norig - 1; k >= 0; --k)
678 Py_XDECREF(recycle[k]);
679 result = 0;
Tim Peters8d9eb102004-07-31 02:24:20 +0000680 Error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000681 if (recycle != recycle_on_stack)
682 PyMem_FREE(recycle);
683 Py_XDECREF(v_as_SF);
684 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000685#undef b
686}
687
Guido van Rossum234f9421993-06-17 12:35:49 +0000688int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000689PyList_SetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum234f9421993-06-17 12:35:49 +0000690{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000691 if (!PyList_Check(a)) {
692 PyErr_BadInternalCall();
693 return -1;
694 }
695 return list_ass_slice((PyListObject *)a, ilow, ihigh, v);
Guido van Rossum234f9421993-06-17 12:35:49 +0000696}
697
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000698static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000699list_inplace_repeat(PyListObject *self, Py_ssize_t n)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000700{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000701 PyObject **items;
702 Py_ssize_t size, i, j, p;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000703
704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000705 size = PyList_GET_SIZE(self);
706 if (size == 0 || n == 1) {
707 Py_INCREF(self);
708 return (PyObject *)self;
709 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000710
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000711 if (n < 1) {
712 (void)list_clear(self);
713 Py_INCREF(self);
714 return (PyObject *)self;
715 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000716
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000717 if (size > PY_SSIZE_T_MAX / n) {
718 return PyErr_NoMemory();
719 }
Christian Heimesaf98da12008-01-27 15:18:18 +0000720
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800721 if (list_resize(self, size*n) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000722 return NULL;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000723
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000724 p = size;
725 items = self->ob_item;
726 for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */
727 for (j = 0; j < size; j++) {
728 PyObject *o = items[j];
729 Py_INCREF(o);
730 items[p++] = o;
731 }
732 }
733 Py_INCREF(self);
734 return (PyObject *)self;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000735}
736
Guido van Rossum4a450d01991-04-03 19:05:18 +0000737static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000738list_ass_item(PyListObject *a, Py_ssize_t i, PyObject *v)
Guido van Rossum4a450d01991-04-03 19:05:18 +0000739{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000740 if (i < 0 || i >= Py_SIZE(a)) {
741 PyErr_SetString(PyExc_IndexError,
742 "list assignment index out of range");
743 return -1;
744 }
745 if (v == NULL)
746 return list_ass_slice(a, i, i+1, v);
747 Py_INCREF(v);
Serhiy Storchakaf01e4082016-04-10 18:12:01 +0300748 Py_SETREF(a->ob_item[i], v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000749 return 0;
Guido van Rossum4a450d01991-04-03 19:05:18 +0000750}
751
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000752static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000753listinsert(PyListObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000754{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000755 Py_ssize_t i;
756 PyObject *v;
757 if (!PyArg_ParseTuple(args, "nO:insert", &i, &v))
758 return NULL;
759 if (ins1(self, i, v) == 0)
760 Py_RETURN_NONE;
761 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000762}
763
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000764static PyObject *
Eli Benderskycbbaa962011-02-25 05:47:53 +0000765listclear(PyListObject *self)
766{
767 list_clear(self);
768 Py_RETURN_NONE;
769}
770
771static PyObject *
772listcopy(PyListObject *self)
773{
774 return list_slice(self, 0, Py_SIZE(self));
775}
776
777static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000778listappend(PyListObject *self, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000779{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000780 if (app1(self, v) == 0)
781 Py_RETURN_NONE;
782 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000783}
784
Barry Warsawdedf6d61998-10-09 16:37:25 +0000785static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000786listextend(PyListObject *self, PyObject *b)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000787{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000788 PyObject *it; /* iter(v) */
789 Py_ssize_t m; /* size of self */
790 Py_ssize_t n; /* guess for size of b */
791 Py_ssize_t mn; /* m + n */
792 Py_ssize_t i;
793 PyObject *(*iternext)(PyObject *);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000794
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000795 /* Special cases:
796 1) lists and tuples which can use PySequence_Fast ops
797 2) extending self to self requires making a copy first
798 */
799 if (PyList_CheckExact(b) || PyTuple_CheckExact(b) || (PyObject *)self == b) {
800 PyObject **src, **dest;
801 b = PySequence_Fast(b, "argument must be iterable");
802 if (!b)
803 return NULL;
804 n = PySequence_Fast_GET_SIZE(b);
805 if (n == 0) {
806 /* short circuit when b is empty */
807 Py_DECREF(b);
808 Py_RETURN_NONE;
809 }
810 m = Py_SIZE(self);
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800811 if (list_resize(self, m + n) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 Py_DECREF(b);
813 return NULL;
814 }
815 /* note that we may still have self == b here for the
816 * situation a.extend(a), but the following code works
817 * in that case too. Just make sure to resize self
818 * before calling PySequence_Fast_ITEMS.
819 */
820 /* populate the end of self with b's items */
821 src = PySequence_Fast_ITEMS(b);
822 dest = self->ob_item + m;
823 for (i = 0; i < n; i++) {
824 PyObject *o = src[i];
825 Py_INCREF(o);
826 dest[i] = o;
827 }
828 Py_DECREF(b);
829 Py_RETURN_NONE;
830 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000831
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000832 it = PyObject_GetIter(b);
833 if (it == NULL)
834 return NULL;
835 iternext = *it->ob_type->tp_iternext;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000836
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000837 /* Guess a result list size. */
Armin Ronacheraa9a79d2012-10-06 14:03:24 +0200838 n = PyObject_LengthHint(b, 8);
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800839 if (n < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 Py_DECREF(it);
841 return NULL;
842 }
843 m = Py_SIZE(self);
844 mn = m + n;
845 if (mn >= m) {
846 /* Make room. */
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800847 if (list_resize(self, mn) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 goto error;
849 /* Make the list sane again. */
850 Py_SIZE(self) = m;
851 }
852 /* Else m + n overflowed; on the chance that n lied, and there really
853 * is enough room, ignore it. If n was telling the truth, we'll
854 * eventually run out of memory during the loop.
855 */
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000856
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000857 /* Run iterator to exhaustion. */
858 for (;;) {
859 PyObject *item = iternext(it);
860 if (item == NULL) {
861 if (PyErr_Occurred()) {
862 if (PyErr_ExceptionMatches(PyExc_StopIteration))
863 PyErr_Clear();
864 else
865 goto error;
866 }
867 break;
868 }
869 if (Py_SIZE(self) < self->allocated) {
870 /* steals ref */
871 PyList_SET_ITEM(self, Py_SIZE(self), item);
872 ++Py_SIZE(self);
873 }
874 else {
875 int status = app1(self, item);
876 Py_DECREF(item); /* append creates a new ref */
877 if (status < 0)
878 goto error;
879 }
880 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 /* Cut back result list if initial guess was too large. */
Victor Stinner32fd6ea2013-07-16 21:45:58 +0200883 if (Py_SIZE(self) < self->allocated) {
884 if (list_resize(self, Py_SIZE(self)) < 0)
885 goto error;
886 }
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000888 Py_DECREF(it);
889 Py_RETURN_NONE;
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000890
891 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000892 Py_DECREF(it);
893 return NULL;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000894}
895
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000896PyObject *
897_PyList_Extend(PyListObject *self, PyObject *b)
898{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000899 return listextend(self, b);
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000900}
901
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000902static PyObject *
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000903list_inplace_concat(PyListObject *self, PyObject *other)
904{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000905 PyObject *result;
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 result = listextend(self, other);
908 if (result == NULL)
909 return result;
910 Py_DECREF(result);
911 Py_INCREF(self);
912 return (PyObject *)self;
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000913}
914
915static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000916listpop(PyListObject *self, PyObject *args)
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000917{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 Py_ssize_t i = -1;
919 PyObject *v;
920 int status;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 if (!PyArg_ParseTuple(args, "|n:pop", &i))
923 return NULL;
Thomas Wouters89f507f2006-12-13 04:49:30 +0000924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000925 if (Py_SIZE(self) == 0) {
926 /* Special-case most common failure cause */
927 PyErr_SetString(PyExc_IndexError, "pop from empty list");
928 return NULL;
929 }
930 if (i < 0)
931 i += Py_SIZE(self);
932 if (i < 0 || i >= Py_SIZE(self)) {
933 PyErr_SetString(PyExc_IndexError, "pop index out of range");
934 return NULL;
935 }
936 v = self->ob_item[i];
937 if (i == Py_SIZE(self) - 1) {
938 status = list_resize(self, Py_SIZE(self) - 1);
Victor Stinnerb27cd3e2013-07-08 22:20:44 +0200939 if (status >= 0)
940 return v; /* and v now owns the reference the list had */
941 else
942 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000943 }
944 Py_INCREF(v);
945 status = list_ass_slice(self, i, i+1, (PyObject *)NULL);
Victor Stinner095d99f2013-07-17 21:58:01 +0200946 if (status < 0) {
947 Py_DECREF(v);
948 return NULL;
949 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 return v;
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000951}
952
Tim Peters8e2e7ca2002-07-19 02:33:08 +0000953/* Reverse a slice of a list in place, from lo up to (exclusive) hi. */
954static void
955reverse_slice(PyObject **lo, PyObject **hi)
956{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000957 assert(lo && hi);
Tim Peters8e2e7ca2002-07-19 02:33:08 +0000958
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 --hi;
960 while (lo < hi) {
961 PyObject *t = *lo;
962 *lo = *hi;
963 *hi = t;
964 ++lo;
965 --hi;
966 }
Tim Peters8e2e7ca2002-07-19 02:33:08 +0000967}
968
Tim Petersa64dc242002-08-01 02:13:36 +0000969/* Lots of code for an adaptive, stable, natural mergesort. There are many
970 * pieces to this algorithm; read listsort.txt for overviews and details.
971 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000972
Daniel Stutzbach98338222010-12-02 21:55:33 +0000973/* A sortslice contains a pointer to an array of keys and a pointer to
974 * an array of corresponding values. In other words, keys[i]
975 * corresponds with values[i]. If values == NULL, then the keys are
976 * also the values.
977 *
978 * Several convenience routines are provided here, so that keys and
979 * values are always moved in sync.
980 */
981
982typedef struct {
983 PyObject **keys;
984 PyObject **values;
985} sortslice;
986
987Py_LOCAL_INLINE(void)
988sortslice_copy(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j)
989{
990 s1->keys[i] = s2->keys[j];
991 if (s1->values != NULL)
992 s1->values[i] = s2->values[j];
993}
994
995Py_LOCAL_INLINE(void)
Benjamin Peterson9efdcca2010-12-03 01:44:10 +0000996sortslice_copy_incr(sortslice *dst, sortslice *src)
997{
Daniel Stutzbach98338222010-12-02 21:55:33 +0000998 *dst->keys++ = *src->keys++;
999 if (dst->values != NULL)
1000 *dst->values++ = *src->values++;
1001}
1002
1003Py_LOCAL_INLINE(void)
Benjamin Peterson9efdcca2010-12-03 01:44:10 +00001004sortslice_copy_decr(sortslice *dst, sortslice *src)
1005{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001006 *dst->keys-- = *src->keys--;
1007 if (dst->values != NULL)
1008 *dst->values-- = *src->values--;
1009}
1010
1011
1012Py_LOCAL_INLINE(void)
1013sortslice_memcpy(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j,
Benjamin Peterson9efdcca2010-12-03 01:44:10 +00001014 Py_ssize_t n)
1015{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001016 memcpy(&s1->keys[i], &s2->keys[j], sizeof(PyObject *) * n);
1017 if (s1->values != NULL)
1018 memcpy(&s1->values[i], &s2->values[j], sizeof(PyObject *) * n);
1019}
1020
1021Py_LOCAL_INLINE(void)
1022sortslice_memmove(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j,
Benjamin Peterson9efdcca2010-12-03 01:44:10 +00001023 Py_ssize_t n)
1024{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001025 memmove(&s1->keys[i], &s2->keys[j], sizeof(PyObject *) * n);
1026 if (s1->values != NULL)
1027 memmove(&s1->values[i], &s2->values[j], sizeof(PyObject *) * n);
1028}
1029
1030Py_LOCAL_INLINE(void)
Benjamin Peterson9efdcca2010-12-03 01:44:10 +00001031sortslice_advance(sortslice *slice, Py_ssize_t n)
1032{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001033 slice->keys += n;
1034 if (slice->values != NULL)
1035 slice->values += n;
1036}
1037
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001038/* Comparison function: PyObject_RichCompareBool with Py_LT.
Tim Petersa64dc242002-08-01 02:13:36 +00001039 * Returns -1 on error, 1 if x < y, 0 if x >= y.
1040 */
Guido van Rossum3f236de1996-12-10 23:55:39 +00001041
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001042#define ISLT(X, Y) (PyObject_RichCompareBool(X, Y, Py_LT))
Tim Peters66860f62002-08-04 17:47:26 +00001043
1044/* Compare X to Y via "<". Goto "fail" if the comparison raises an
Tim Petersa8c974c2002-07-19 03:30:57 +00001045 error. Else "k" is set to true iff X<Y, and an "if (k)" block is
1046 started. It makes more sense in context <wink>. X and Y are PyObject*s.
1047*/
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001048#define IFLT(X, Y) if ((k = ISLT(X, Y)) < 0) goto fail; \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 if (k)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001050
1051/* binarysort is the best method for sorting small arrays: it does
1052 few compares, but can do data movement quadratic in the number of
1053 elements.
Guido van Rossum42812581998-06-17 14:15:44 +00001054 [lo, hi) is a contiguous slice of a list, and is sorted via
Tim Petersa8c974c2002-07-19 03:30:57 +00001055 binary insertion. This sort is stable.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001056 On entry, must have lo <= start <= hi, and that [lo, start) is already
1057 sorted (pass start == lo if you don't know!).
Tim Petersa8c974c2002-07-19 03:30:57 +00001058 If islt() complains return -1, else 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001059 Even in case of error, the output slice will be some permutation of
1060 the input (nothing is lost or duplicated).
1061*/
Guido van Rossum3f236de1996-12-10 23:55:39 +00001062static int
Daniel Stutzbach98338222010-12-02 21:55:33 +00001063binarysort(sortslice lo, PyObject **hi, PyObject **start)
Guido van Rossum3f236de1996-12-10 23:55:39 +00001064{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001065 Py_ssize_t k;
1066 PyObject **l, **p, **r;
1067 PyObject *pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001068
Daniel Stutzbach98338222010-12-02 21:55:33 +00001069 assert(lo.keys <= start && start <= hi);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 /* assert [lo, start) is sorted */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001071 if (lo.keys == start)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001072 ++start;
1073 for (; start < hi; ++start) {
1074 /* set l to where *start belongs */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001075 l = lo.keys;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001076 r = start;
1077 pivot = *r;
1078 /* Invariants:
1079 * pivot >= all in [lo, l).
1080 * pivot < all in [r, start).
1081 * The second is vacuously true at the start.
1082 */
1083 assert(l < r);
1084 do {
1085 p = l + ((r - l) >> 1);
1086 IFLT(pivot, *p)
1087 r = p;
1088 else
1089 l = p+1;
1090 } while (l < r);
1091 assert(l == r);
1092 /* The invariants still hold, so pivot >= all in [lo, l) and
1093 pivot < all in [l, start), so pivot belongs at l. Note
1094 that if there are elements equal to pivot, l points to the
1095 first slot after them -- that's why this sort is stable.
1096 Slide over to make room.
1097 Caution: using memmove is much slower under MSVC 5;
1098 we're not usually moving many slots. */
1099 for (p = start; p > l; --p)
1100 *p = *(p-1);
1101 *l = pivot;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001102 if (lo.values != NULL) {
1103 Py_ssize_t offset = lo.values - lo.keys;
1104 p = start + offset;
1105 pivot = *p;
1106 l += offset;
1107 for (p = start + offset; p > l; --p)
1108 *p = *(p-1);
1109 *l = pivot;
1110 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001111 }
1112 return 0;
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001113
1114 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 return -1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001116}
1117
Tim Petersa64dc242002-08-01 02:13:36 +00001118/*
1119Return the length of the run beginning at lo, in the slice [lo, hi). lo < hi
1120is required on entry. "A run" is the longest ascending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001121
Tim Petersa64dc242002-08-01 02:13:36 +00001122 lo[0] <= lo[1] <= lo[2] <= ...
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001123
Tim Petersa64dc242002-08-01 02:13:36 +00001124or the longest descending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001125
Tim Petersa64dc242002-08-01 02:13:36 +00001126 lo[0] > lo[1] > lo[2] > ...
Tim Peters3b01a122002-07-19 02:35:45 +00001127
Tim Petersa64dc242002-08-01 02:13:36 +00001128Boolean *descending is set to 0 in the former case, or to 1 in the latter.
1129For its intended use in a stable mergesort, the strictness of the defn of
1130"descending" is needed so that the caller can safely reverse a descending
1131sequence without violating stability (strict > ensures there are no equal
1132elements to get out of order).
1133
1134Returns -1 in case of error.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001135*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001136static Py_ssize_t
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001137count_run(PyObject **lo, PyObject **hi, int *descending)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001138{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001139 Py_ssize_t k;
1140 Py_ssize_t n;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142 assert(lo < hi);
1143 *descending = 0;
1144 ++lo;
1145 if (lo == hi)
1146 return 1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001148 n = 2;
1149 IFLT(*lo, *(lo-1)) {
1150 *descending = 1;
1151 for (lo = lo+1; lo < hi; ++lo, ++n) {
1152 IFLT(*lo, *(lo-1))
1153 ;
1154 else
1155 break;
1156 }
1157 }
1158 else {
1159 for (lo = lo+1; lo < hi; ++lo, ++n) {
1160 IFLT(*lo, *(lo-1))
1161 break;
1162 }
1163 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001165 return n;
Tim Petersa64dc242002-08-01 02:13:36 +00001166fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001167 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001168}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001169
Tim Petersa64dc242002-08-01 02:13:36 +00001170/*
1171Locate the proper position of key in a sorted vector; if the vector contains
1172an element equal to key, return the position immediately to the left of
1173the leftmost equal element. [gallop_right() does the same except returns
1174the position to the right of the rightmost equal element (if any).]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001175
Tim Petersa64dc242002-08-01 02:13:36 +00001176"a" is a sorted vector with n elements, starting at a[0]. n must be > 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001177
Tim Petersa64dc242002-08-01 02:13:36 +00001178"hint" is an index at which to begin the search, 0 <= hint < n. The closer
1179hint is to the final result, the faster this runs.
1180
1181The return value is the int k in 0..n such that
1182
1183 a[k-1] < key <= a[k]
1184
1185pretending that *(a-1) is minus infinity and a[n] is plus infinity. IOW,
1186key belongs at index k; or, IOW, the first k elements of a should precede
1187key, and the last n-k should follow key.
1188
1189Returns -1 on error. See listsort.txt for info on the method.
1190*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001191static Py_ssize_t
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001192gallop_left(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint)
Tim Petersa64dc242002-08-01 02:13:36 +00001193{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 Py_ssize_t ofs;
1195 Py_ssize_t lastofs;
1196 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001198 assert(key && a && n > 0 && hint >= 0 && hint < n);
Tim Petersa64dc242002-08-01 02:13:36 +00001199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001200 a += hint;
1201 lastofs = 0;
1202 ofs = 1;
1203 IFLT(*a, key) {
1204 /* a[hint] < key -- gallop right, until
1205 * a[hint + lastofs] < key <= a[hint + ofs]
1206 */
1207 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
1208 while (ofs < maxofs) {
1209 IFLT(a[ofs], key) {
1210 lastofs = ofs;
1211 ofs = (ofs << 1) + 1;
1212 if (ofs <= 0) /* int overflow */
1213 ofs = maxofs;
1214 }
1215 else /* key <= a[hint + ofs] */
1216 break;
1217 }
1218 if (ofs > maxofs)
1219 ofs = maxofs;
1220 /* Translate back to offsets relative to &a[0]. */
1221 lastofs += hint;
1222 ofs += hint;
1223 }
1224 else {
1225 /* key <= a[hint] -- gallop left, until
1226 * a[hint - ofs] < key <= a[hint - lastofs]
1227 */
1228 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
1229 while (ofs < maxofs) {
1230 IFLT(*(a-ofs), key)
1231 break;
1232 /* key <= a[hint - ofs] */
1233 lastofs = ofs;
1234 ofs = (ofs << 1) + 1;
1235 if (ofs <= 0) /* int overflow */
1236 ofs = maxofs;
1237 }
1238 if (ofs > maxofs)
1239 ofs = maxofs;
1240 /* Translate back to positive offsets relative to &a[0]. */
1241 k = lastofs;
1242 lastofs = hint - ofs;
1243 ofs = hint - k;
1244 }
1245 a -= hint;
Tim Petersa64dc242002-08-01 02:13:36 +00001246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001247 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1248 /* Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the
1249 * right of lastofs but no farther right than ofs. Do a binary
1250 * search, with invariant a[lastofs-1] < key <= a[ofs].
1251 */
1252 ++lastofs;
1253 while (lastofs < ofs) {
1254 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001255
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001256 IFLT(a[m], key)
1257 lastofs = m+1; /* a[m] < key */
1258 else
1259 ofs = m; /* key <= a[m] */
1260 }
1261 assert(lastofs == ofs); /* so a[ofs-1] < key <= a[ofs] */
1262 return ofs;
Tim Petersa64dc242002-08-01 02:13:36 +00001263
1264fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001265 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001266}
1267
1268/*
1269Exactly like gallop_left(), except that if key already exists in a[0:n],
1270finds the position immediately to the right of the rightmost equal value.
1271
1272The return value is the int k in 0..n such that
1273
1274 a[k-1] <= key < a[k]
1275
1276or -1 if error.
1277
1278The code duplication is massive, but this is enough different given that
1279we're sticking to "<" comparisons that it's much harder to follow if
1280written as one routine with yet another "left or right?" flag.
1281*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001282static Py_ssize_t
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001283gallop_right(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint)
Tim Petersa64dc242002-08-01 02:13:36 +00001284{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001285 Py_ssize_t ofs;
1286 Py_ssize_t lastofs;
1287 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001289 assert(key && a && n > 0 && hint >= 0 && hint < n);
Tim Petersa64dc242002-08-01 02:13:36 +00001290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001291 a += hint;
1292 lastofs = 0;
1293 ofs = 1;
1294 IFLT(key, *a) {
1295 /* key < a[hint] -- gallop left, until
1296 * a[hint - ofs] <= key < a[hint - lastofs]
1297 */
1298 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
1299 while (ofs < maxofs) {
1300 IFLT(key, *(a-ofs)) {
1301 lastofs = ofs;
1302 ofs = (ofs << 1) + 1;
1303 if (ofs <= 0) /* int overflow */
1304 ofs = maxofs;
1305 }
1306 else /* a[hint - ofs] <= key */
1307 break;
1308 }
1309 if (ofs > maxofs)
1310 ofs = maxofs;
1311 /* Translate back to positive offsets relative to &a[0]. */
1312 k = lastofs;
1313 lastofs = hint - ofs;
1314 ofs = hint - k;
1315 }
1316 else {
1317 /* a[hint] <= key -- gallop right, until
1318 * a[hint + lastofs] <= key < a[hint + ofs]
1319 */
1320 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
1321 while (ofs < maxofs) {
1322 IFLT(key, a[ofs])
1323 break;
1324 /* a[hint + ofs] <= key */
1325 lastofs = ofs;
1326 ofs = (ofs << 1) + 1;
1327 if (ofs <= 0) /* int overflow */
1328 ofs = maxofs;
1329 }
1330 if (ofs > maxofs)
1331 ofs = maxofs;
1332 /* Translate back to offsets relative to &a[0]. */
1333 lastofs += hint;
1334 ofs += hint;
1335 }
1336 a -= hint;
Tim Petersa64dc242002-08-01 02:13:36 +00001337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001338 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1339 /* Now a[lastofs] <= key < a[ofs], so key belongs somewhere to the
1340 * right of lastofs but no farther right than ofs. Do a binary
1341 * search, with invariant a[lastofs-1] <= key < a[ofs].
1342 */
1343 ++lastofs;
1344 while (lastofs < ofs) {
1345 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001347 IFLT(key, a[m])
1348 ofs = m; /* key < a[m] */
1349 else
1350 lastofs = m+1; /* a[m] <= key */
1351 }
1352 assert(lastofs == ofs); /* so a[ofs-1] <= key < a[ofs] */
1353 return ofs;
Tim Petersa64dc242002-08-01 02:13:36 +00001354
1355fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001356 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001357}
1358
1359/* The maximum number of entries in a MergeState's pending-runs stack.
1360 * This is enough to sort arrays of size up to about
1361 * 32 * phi ** MAX_MERGE_PENDING
1362 * where phi ~= 1.618. 85 is ridiculouslylarge enough, good for an array
1363 * with 2**64 elements.
1364 */
1365#define MAX_MERGE_PENDING 85
1366
Tim Peterse05f65a2002-08-10 05:21:15 +00001367/* When we get into galloping mode, we stay there until both runs win less
1368 * often than MIN_GALLOP consecutive times. See listsort.txt for more info.
Tim Petersa64dc242002-08-01 02:13:36 +00001369 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001370#define MIN_GALLOP 7
Tim Petersa64dc242002-08-01 02:13:36 +00001371
1372/* Avoid malloc for small temp arrays. */
1373#define MERGESTATE_TEMP_SIZE 256
1374
1375/* One MergeState exists on the stack per invocation of mergesort. It's just
1376 * a convenient way to pass state around among the helper functions.
1377 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001378struct s_slice {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001379 sortslice base;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001380 Py_ssize_t len;
Tim Peterse05f65a2002-08-10 05:21:15 +00001381};
1382
Tim Petersa64dc242002-08-01 02:13:36 +00001383typedef struct s_MergeState {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001384 /* This controls when we get *into* galloping mode. It's initialized
1385 * to MIN_GALLOP. merge_lo and merge_hi tend to nudge it higher for
1386 * random data, and lower for highly structured data.
1387 */
1388 Py_ssize_t min_gallop;
Tim Peterse05f65a2002-08-10 05:21:15 +00001389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001390 /* 'a' is temp storage to help with merges. It contains room for
1391 * alloced entries.
1392 */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001393 sortslice a; /* may point to temparray below */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001394 Py_ssize_t alloced;
Tim Petersa64dc242002-08-01 02:13:36 +00001395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001396 /* A stack of n pending runs yet to be merged. Run #i starts at
1397 * address base[i] and extends for len[i] elements. It's always
1398 * true (so long as the indices are in bounds) that
1399 *
1400 * pending[i].base + pending[i].len == pending[i+1].base
1401 *
1402 * so we could cut the storage for this, but it's a minor amount,
1403 * and keeping all the info explicit simplifies the code.
1404 */
1405 int n;
1406 struct s_slice pending[MAX_MERGE_PENDING];
Tim Petersa64dc242002-08-01 02:13:36 +00001407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001408 /* 'a' points to this when possible, rather than muck with malloc. */
1409 PyObject *temparray[MERGESTATE_TEMP_SIZE];
Tim Petersa64dc242002-08-01 02:13:36 +00001410} MergeState;
1411
1412/* Conceptually a MergeState's constructor. */
1413static void
Victor Stinner0fcab4a2011-01-04 12:59:15 +00001414merge_init(MergeState *ms, Py_ssize_t list_size, int has_keyfunc)
Tim Petersa64dc242002-08-01 02:13:36 +00001415{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001416 assert(ms != NULL);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001417 if (has_keyfunc) {
1418 /* The temporary space for merging will need at most half the list
1419 * size rounded up. Use the minimum possible space so we can use the
1420 * rest of temparray for other things. In particular, if there is
1421 * enough extra space, listsort() will use it to store the keys.
1422 */
1423 ms->alloced = (list_size + 1) / 2;
1424
1425 /* ms->alloced describes how many keys will be stored at
1426 ms->temparray, but we also need to store the values. Hence,
1427 ms->alloced is capped at half of MERGESTATE_TEMP_SIZE. */
1428 if (MERGESTATE_TEMP_SIZE / 2 < ms->alloced)
1429 ms->alloced = MERGESTATE_TEMP_SIZE / 2;
1430 ms->a.values = &ms->temparray[ms->alloced];
1431 }
1432 else {
1433 ms->alloced = MERGESTATE_TEMP_SIZE;
1434 ms->a.values = NULL;
1435 }
1436 ms->a.keys = ms->temparray;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001437 ms->n = 0;
1438 ms->min_gallop = MIN_GALLOP;
Tim Petersa64dc242002-08-01 02:13:36 +00001439}
1440
1441/* Free all the temp memory owned by the MergeState. This must be called
1442 * when you're done with a MergeState, and may be called before then if
1443 * you want to free the temp memory early.
1444 */
1445static void
1446merge_freemem(MergeState *ms)
1447{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001448 assert(ms != NULL);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001449 if (ms->a.keys != ms->temparray)
1450 PyMem_Free(ms->a.keys);
Tim Petersa64dc242002-08-01 02:13:36 +00001451}
1452
1453/* Ensure enough temp memory for 'need' array slots is available.
1454 * Returns 0 on success and -1 if the memory can't be gotten.
1455 */
1456static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001457merge_getmem(MergeState *ms, Py_ssize_t need)
Tim Petersa64dc242002-08-01 02:13:36 +00001458{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001459 int multiplier;
1460
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001461 assert(ms != NULL);
1462 if (need <= ms->alloced)
1463 return 0;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001464
1465 multiplier = ms->a.values != NULL ? 2 : 1;
1466
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001467 /* Don't realloc! That can cost cycles to copy the old data, but
1468 * we don't care what's in the block.
1469 */
1470 merge_freemem(ms);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001471 if ((size_t)need > PY_SSIZE_T_MAX / sizeof(PyObject*) / multiplier) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001472 PyErr_NoMemory();
1473 return -1;
1474 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001475 ms->a.keys = (PyObject**)PyMem_Malloc(multiplier * need
1476 * sizeof(PyObject *));
1477 if (ms->a.keys != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001478 ms->alloced = need;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001479 if (ms->a.values != NULL)
1480 ms->a.values = &ms->a.keys[need];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001481 return 0;
1482 }
1483 PyErr_NoMemory();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001484 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001485}
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001486#define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 : \
1487 merge_getmem(MS, NEED))
Tim Petersa64dc242002-08-01 02:13:36 +00001488
Daniel Stutzbach98338222010-12-02 21:55:33 +00001489/* Merge the na elements starting at ssa with the nb elements starting at
1490 * ssb.keys = ssa.keys + na in a stable way, in-place. na and nb must be > 0.
1491 * Must also have that ssa.keys[na-1] belongs at the end of the merge, and
1492 * should have na <= nb. See listsort.txt for more info. Return 0 if
1493 * successful, -1 if error.
Tim Petersa64dc242002-08-01 02:13:36 +00001494 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001495static Py_ssize_t
Daniel Stutzbach98338222010-12-02 21:55:33 +00001496merge_lo(MergeState *ms, sortslice ssa, Py_ssize_t na,
1497 sortslice ssb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001498{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001499 Py_ssize_t k;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001500 sortslice dest;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001501 int result = -1; /* guilty until proved innocent */
1502 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001503
Daniel Stutzbach98338222010-12-02 21:55:33 +00001504 assert(ms && ssa.keys && ssb.keys && na > 0 && nb > 0);
1505 assert(ssa.keys + na == ssb.keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001506 if (MERGE_GETMEM(ms, na) < 0)
1507 return -1;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001508 sortslice_memcpy(&ms->a, 0, &ssa, 0, na);
1509 dest = ssa;
1510 ssa = ms->a;
Tim Petersa64dc242002-08-01 02:13:36 +00001511
Daniel Stutzbach98338222010-12-02 21:55:33 +00001512 sortslice_copy_incr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001513 --nb;
1514 if (nb == 0)
1515 goto Succeed;
1516 if (na == 1)
1517 goto CopyB;
Tim Petersa64dc242002-08-01 02:13:36 +00001518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001519 min_gallop = ms->min_gallop;
1520 for (;;) {
1521 Py_ssize_t acount = 0; /* # of times A won in a row */
1522 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001524 /* Do the straightforward thing until (if ever) one run
1525 * appears to win consistently.
1526 */
1527 for (;;) {
1528 assert(na > 1 && nb > 0);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001529 k = ISLT(ssb.keys[0], ssa.keys[0]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001530 if (k) {
1531 if (k < 0)
1532 goto Fail;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001533 sortslice_copy_incr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001534 ++bcount;
1535 acount = 0;
1536 --nb;
1537 if (nb == 0)
1538 goto Succeed;
1539 if (bcount >= min_gallop)
1540 break;
1541 }
1542 else {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001543 sortslice_copy_incr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001544 ++acount;
1545 bcount = 0;
1546 --na;
1547 if (na == 1)
1548 goto CopyB;
1549 if (acount >= min_gallop)
1550 break;
1551 }
1552 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001553
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001554 /* One run is winning so consistently that galloping may
1555 * be a huge win. So try that, and continue galloping until
1556 * (if ever) neither run appears to be winning consistently
1557 * anymore.
1558 */
1559 ++min_gallop;
1560 do {
1561 assert(na > 1 && nb > 0);
1562 min_gallop -= min_gallop > 1;
1563 ms->min_gallop = min_gallop;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001564 k = gallop_right(ssb.keys[0], ssa.keys, na, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001565 acount = k;
1566 if (k) {
1567 if (k < 0)
1568 goto Fail;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001569 sortslice_memcpy(&dest, 0, &ssa, 0, k);
1570 sortslice_advance(&dest, k);
1571 sortslice_advance(&ssa, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001572 na -= k;
1573 if (na == 1)
1574 goto CopyB;
1575 /* na==0 is impossible now if the comparison
1576 * function is consistent, but we can't assume
1577 * that it is.
1578 */
1579 if (na == 0)
1580 goto Succeed;
1581 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001582 sortslice_copy_incr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001583 --nb;
1584 if (nb == 0)
1585 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001586
Daniel Stutzbach98338222010-12-02 21:55:33 +00001587 k = gallop_left(ssa.keys[0], ssb.keys, nb, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001588 bcount = k;
1589 if (k) {
1590 if (k < 0)
1591 goto Fail;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001592 sortslice_memmove(&dest, 0, &ssb, 0, k);
1593 sortslice_advance(&dest, k);
1594 sortslice_advance(&ssb, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001595 nb -= k;
1596 if (nb == 0)
1597 goto Succeed;
1598 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001599 sortslice_copy_incr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001600 --na;
1601 if (na == 1)
1602 goto CopyB;
1603 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
1604 ++min_gallop; /* penalize it for leaving galloping mode */
1605 ms->min_gallop = min_gallop;
1606 }
Tim Petersa64dc242002-08-01 02:13:36 +00001607Succeed:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001608 result = 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001609Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001610 if (na)
Daniel Stutzbach98338222010-12-02 21:55:33 +00001611 sortslice_memcpy(&dest, 0, &ssa, 0, na);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001612 return result;
Tim Petersa64dc242002-08-01 02:13:36 +00001613CopyB:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001614 assert(na == 1 && nb > 0);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001615 /* The last element of ssa belongs at the end of the merge. */
1616 sortslice_memmove(&dest, 0, &ssb, 0, nb);
1617 sortslice_copy(&dest, nb, &ssa, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001618 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001619}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001620
Daniel Stutzbach98338222010-12-02 21:55:33 +00001621/* Merge the na elements starting at pa with the nb elements starting at
1622 * ssb.keys = ssa.keys + na in a stable way, in-place. na and nb must be > 0.
1623 * Must also have that ssa.keys[na-1] belongs at the end of the merge, and
1624 * should have na >= nb. See listsort.txt for more info. Return 0 if
1625 * successful, -1 if error.
Tim Petersa64dc242002-08-01 02:13:36 +00001626 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001627static Py_ssize_t
Daniel Stutzbach98338222010-12-02 21:55:33 +00001628merge_hi(MergeState *ms, sortslice ssa, Py_ssize_t na,
1629 sortslice ssb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001630{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001631 Py_ssize_t k;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001632 sortslice dest, basea, baseb;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001633 int result = -1; /* guilty until proved innocent */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001634 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001635
Daniel Stutzbach98338222010-12-02 21:55:33 +00001636 assert(ms && ssa.keys && ssb.keys && na > 0 && nb > 0);
1637 assert(ssa.keys + na == ssb.keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001638 if (MERGE_GETMEM(ms, nb) < 0)
1639 return -1;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001640 dest = ssb;
1641 sortslice_advance(&dest, nb-1);
1642 sortslice_memcpy(&ms->a, 0, &ssb, 0, nb);
1643 basea = ssa;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001644 baseb = ms->a;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001645 ssb.keys = ms->a.keys + nb - 1;
1646 if (ssb.values != NULL)
1647 ssb.values = ms->a.values + nb - 1;
1648 sortslice_advance(&ssa, na - 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001649
Daniel Stutzbach98338222010-12-02 21:55:33 +00001650 sortslice_copy_decr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001651 --na;
1652 if (na == 0)
1653 goto Succeed;
1654 if (nb == 1)
1655 goto CopyA;
Tim Petersa64dc242002-08-01 02:13:36 +00001656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001657 min_gallop = ms->min_gallop;
1658 for (;;) {
1659 Py_ssize_t acount = 0; /* # of times A won in a row */
1660 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001661
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001662 /* Do the straightforward thing until (if ever) one run
1663 * appears to win consistently.
1664 */
1665 for (;;) {
1666 assert(na > 0 && nb > 1);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001667 k = ISLT(ssb.keys[0], ssa.keys[0]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001668 if (k) {
1669 if (k < 0)
1670 goto Fail;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001671 sortslice_copy_decr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001672 ++acount;
1673 bcount = 0;
1674 --na;
1675 if (na == 0)
1676 goto Succeed;
1677 if (acount >= min_gallop)
1678 break;
1679 }
1680 else {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001681 sortslice_copy_decr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001682 ++bcount;
1683 acount = 0;
1684 --nb;
1685 if (nb == 1)
1686 goto CopyA;
1687 if (bcount >= min_gallop)
1688 break;
1689 }
1690 }
Tim Petersa64dc242002-08-01 02:13:36 +00001691
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001692 /* One run is winning so consistently that galloping may
1693 * be a huge win. So try that, and continue galloping until
1694 * (if ever) neither run appears to be winning consistently
1695 * anymore.
1696 */
1697 ++min_gallop;
1698 do {
1699 assert(na > 0 && nb > 1);
1700 min_gallop -= min_gallop > 1;
1701 ms->min_gallop = min_gallop;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001702 k = gallop_right(ssb.keys[0], basea.keys, na, na-1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001703 if (k < 0)
1704 goto Fail;
1705 k = na - k;
1706 acount = k;
1707 if (k) {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001708 sortslice_advance(&dest, -k);
1709 sortslice_advance(&ssa, -k);
1710 sortslice_memmove(&dest, 1, &ssa, 1, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001711 na -= k;
1712 if (na == 0)
1713 goto Succeed;
1714 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001715 sortslice_copy_decr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001716 --nb;
1717 if (nb == 1)
1718 goto CopyA;
Tim Petersa64dc242002-08-01 02:13:36 +00001719
Daniel Stutzbach98338222010-12-02 21:55:33 +00001720 k = gallop_left(ssa.keys[0], baseb.keys, nb, nb-1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001721 if (k < 0)
1722 goto Fail;
1723 k = nb - k;
1724 bcount = k;
1725 if (k) {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001726 sortslice_advance(&dest, -k);
1727 sortslice_advance(&ssb, -k);
1728 sortslice_memcpy(&dest, 1, &ssb, 1, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001729 nb -= k;
1730 if (nb == 1)
1731 goto CopyA;
1732 /* nb==0 is impossible now if the comparison
1733 * function is consistent, but we can't assume
1734 * that it is.
1735 */
1736 if (nb == 0)
1737 goto Succeed;
1738 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001739 sortslice_copy_decr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001740 --na;
1741 if (na == 0)
1742 goto Succeed;
1743 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
1744 ++min_gallop; /* penalize it for leaving galloping mode */
1745 ms->min_gallop = min_gallop;
1746 }
Tim Petersa64dc242002-08-01 02:13:36 +00001747Succeed:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001748 result = 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001749Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001750 if (nb)
Daniel Stutzbach98338222010-12-02 21:55:33 +00001751 sortslice_memcpy(&dest, -(nb-1), &baseb, 0, nb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001752 return result;
Tim Petersa64dc242002-08-01 02:13:36 +00001753CopyA:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001754 assert(nb == 1 && na > 0);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001755 /* The first element of ssb belongs at the front of the merge. */
1756 sortslice_memmove(&dest, 1-na, &ssa, 1-na, na);
1757 sortslice_advance(&dest, -na);
1758 sortslice_advance(&ssa, -na);
1759 sortslice_copy(&dest, 0, &ssb, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001760 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001761}
1762
1763/* Merge the two runs at stack indices i and i+1.
1764 * Returns 0 on success, -1 on error.
1765 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001766static Py_ssize_t
1767merge_at(MergeState *ms, Py_ssize_t i)
Tim Petersa64dc242002-08-01 02:13:36 +00001768{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001769 sortslice ssa, ssb;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001770 Py_ssize_t na, nb;
1771 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001772
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001773 assert(ms != NULL);
1774 assert(ms->n >= 2);
1775 assert(i >= 0);
1776 assert(i == ms->n - 2 || i == ms->n - 3);
Tim Petersa64dc242002-08-01 02:13:36 +00001777
Daniel Stutzbach98338222010-12-02 21:55:33 +00001778 ssa = ms->pending[i].base;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001779 na = ms->pending[i].len;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001780 ssb = ms->pending[i+1].base;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001781 nb = ms->pending[i+1].len;
1782 assert(na > 0 && nb > 0);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001783 assert(ssa.keys + na == ssb.keys);
Tim Petersa64dc242002-08-01 02:13:36 +00001784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001785 /* Record the length of the combined runs; if i is the 3rd-last
1786 * run now, also slide over the last run (which isn't involved
1787 * in this merge). The current run i+1 goes away in any case.
1788 */
1789 ms->pending[i].len = na + nb;
1790 if (i == ms->n - 3)
1791 ms->pending[i+1] = ms->pending[i+2];
1792 --ms->n;
Tim Petersa64dc242002-08-01 02:13:36 +00001793
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001794 /* Where does b start in a? Elements in a before that can be
1795 * ignored (already in place).
1796 */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001797 k = gallop_right(*ssb.keys, ssa.keys, na, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001798 if (k < 0)
1799 return -1;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001800 sortslice_advance(&ssa, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001801 na -= k;
1802 if (na == 0)
1803 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001804
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001805 /* Where does a end in b? Elements in b after that can be
1806 * ignored (already in place).
1807 */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001808 nb = gallop_left(ssa.keys[na-1], ssb.keys, nb, nb-1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001809 if (nb <= 0)
1810 return nb;
Tim Petersa64dc242002-08-01 02:13:36 +00001811
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001812 /* Merge what remains of the runs, using a temp array with
1813 * min(na, nb) elements.
1814 */
1815 if (na <= nb)
Daniel Stutzbach98338222010-12-02 21:55:33 +00001816 return merge_lo(ms, ssa, na, ssb, nb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001817 else
Daniel Stutzbach98338222010-12-02 21:55:33 +00001818 return merge_hi(ms, ssa, na, ssb, nb);
Tim Petersa64dc242002-08-01 02:13:36 +00001819}
1820
1821/* Examine the stack of runs waiting to be merged, merging adjacent runs
1822 * until the stack invariants are re-established:
1823 *
1824 * 1. len[-3] > len[-2] + len[-1]
1825 * 2. len[-2] > len[-1]
1826 *
1827 * See listsort.txt for more info.
1828 *
1829 * Returns 0 on success, -1 on error.
1830 */
1831static int
1832merge_collapse(MergeState *ms)
1833{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001834 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001836 assert(ms);
1837 while (ms->n > 1) {
1838 Py_ssize_t n = ms->n - 2;
Benjamin Petersonb808d592015-02-25 10:12:26 -05001839 if ((n > 0 && p[n-1].len <= p[n].len + p[n+1].len) ||
1840 (n > 1 && p[n-2].len <= p[n-1].len + p[n].len)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001841 if (p[n-1].len < p[n+1].len)
1842 --n;
1843 if (merge_at(ms, n) < 0)
1844 return -1;
1845 }
1846 else if (p[n].len <= p[n+1].len) {
1847 if (merge_at(ms, n) < 0)
1848 return -1;
1849 }
1850 else
1851 break;
1852 }
1853 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001854}
1855
1856/* Regardless of invariants, merge all runs on the stack until only one
1857 * remains. This is used at the end of the mergesort.
1858 *
1859 * Returns 0 on success, -1 on error.
1860 */
1861static int
1862merge_force_collapse(MergeState *ms)
1863{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001864 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001866 assert(ms);
1867 while (ms->n > 1) {
1868 Py_ssize_t n = ms->n - 2;
1869 if (n > 0 && p[n-1].len < p[n+1].len)
1870 --n;
1871 if (merge_at(ms, n) < 0)
1872 return -1;
1873 }
1874 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001875}
1876
1877/* Compute a good value for the minimum run length; natural runs shorter
1878 * than this are boosted artificially via binary insertion.
1879 *
1880 * If n < 64, return n (it's too small to bother with fancy stuff).
1881 * Else if n is an exact power of 2, return 32.
1882 * Else return an int k, 32 <= k <= 64, such that n/k is close to, but
1883 * strictly less than, an exact power of 2.
1884 *
1885 * See listsort.txt for more info.
1886 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001887static Py_ssize_t
1888merge_compute_minrun(Py_ssize_t n)
Tim Petersa64dc242002-08-01 02:13:36 +00001889{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001890 Py_ssize_t r = 0; /* becomes 1 if any 1 bits are shifted off */
Tim Petersa64dc242002-08-01 02:13:36 +00001891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001892 assert(n >= 0);
1893 while (n >= 64) {
1894 r |= n & 1;
1895 n >>= 1;
1896 }
1897 return n + r;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001898}
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001899
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001900static void
Daniel Stutzbach98338222010-12-02 21:55:33 +00001901reverse_sortslice(sortslice *s, Py_ssize_t n)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001902{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001903 reverse_slice(s->keys, &s->keys[n]);
1904 if (s->values != NULL)
1905 reverse_slice(s->values, &s->values[n]);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001906}
1907
Tim Petersa64dc242002-08-01 02:13:36 +00001908/* An adaptive, stable, natural mergesort. See listsort.txt.
1909 * Returns Py_None on success, NULL on error. Even in case of error, the
1910 * list will be some permutation of its input state (nothing is lost or
1911 * duplicated).
1912 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001913static PyObject *
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001914listsort(PyListObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f236de1996-12-10 23:55:39 +00001915{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001916 MergeState ms;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001917 Py_ssize_t nremaining;
1918 Py_ssize_t minrun;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001919 sortslice lo;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001920 Py_ssize_t saved_ob_size, saved_allocated;
1921 PyObject **saved_ob_item;
1922 PyObject **final_ob_item;
1923 PyObject *result = NULL; /* guilty until proved innocent */
1924 int reverse = 0;
1925 PyObject *keyfunc = NULL;
1926 Py_ssize_t i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001927 static char *kwlist[] = {"key", "reverse", 0};
Daniel Stutzbach98338222010-12-02 21:55:33 +00001928 PyObject **keys;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001929
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001930 assert(self != NULL);
1931 assert (PyList_Check(self));
1932 if (args != NULL) {
1933 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:sort",
1934 kwlist, &keyfunc, &reverse))
1935 return NULL;
1936 if (Py_SIZE(args) > 0) {
1937 PyErr_SetString(PyExc_TypeError,
1938 "must use keyword argument for key function");
1939 return NULL;
1940 }
1941 }
1942 if (keyfunc == Py_None)
1943 keyfunc = NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001945 /* The list is temporarily made empty, so that mutations performed
1946 * by comparison functions can't affect the slice of memory we're
1947 * sorting (allowing mutations during sorting is a core-dump
1948 * factory, since ob_item may change).
1949 */
1950 saved_ob_size = Py_SIZE(self);
1951 saved_ob_item = self->ob_item;
1952 saved_allocated = self->allocated;
1953 Py_SIZE(self) = 0;
1954 self->ob_item = NULL;
1955 self->allocated = -1; /* any operation will reset it to >= 0 */
Tim Peters330f9e92002-07-19 07:05:44 +00001956
Daniel Stutzbach98338222010-12-02 21:55:33 +00001957 if (keyfunc == NULL) {
1958 keys = NULL;
1959 lo.keys = saved_ob_item;
1960 lo.values = NULL;
1961 }
1962 else {
1963 if (saved_ob_size < MERGESTATE_TEMP_SIZE/2)
1964 /* Leverage stack space we allocated but won't otherwise use */
1965 keys = &ms.temparray[saved_ob_size+1];
1966 else {
1967 keys = PyMem_MALLOC(sizeof(PyObject *) * saved_ob_size);
Benjamin Peterson0823ffb2015-04-23 17:04:36 -04001968 if (keys == NULL) {
1969 PyErr_NoMemory();
1970 goto keyfunc_fail;
1971 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001972 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001973
1974 for (i = 0; i < saved_ob_size ; i++) {
1975 keys[i] = PyObject_CallFunctionObjArgs(keyfunc, saved_ob_item[i],
1976 NULL);
1977 if (keys[i] == NULL) {
1978 for (i=i-1 ; i>=0 ; i--)
1979 Py_DECREF(keys[i]);
Benjamin Peterson4a42cd42014-03-15 12:21:28 -05001980 if (saved_ob_size >= MERGESTATE_TEMP_SIZE/2)
Daniel Stutzbach8eda5f72011-03-02 23:37:50 +00001981 PyMem_FREE(keys);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001982 goto keyfunc_fail;
1983 }
1984 }
1985
1986 lo.keys = keys;
1987 lo.values = saved_ob_item;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001988 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001989
Daniel Stutzbach98338222010-12-02 21:55:33 +00001990 merge_init(&ms, saved_ob_size, keys != NULL);
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001992 nremaining = saved_ob_size;
1993 if (nremaining < 2)
1994 goto succeed;
Tim Peters330f9e92002-07-19 07:05:44 +00001995
Benjamin Peterson05380642010-08-23 19:35:39 +00001996 /* Reverse sort stability achieved by initially reversing the list,
1997 applying a stable forward sort, then reversing the final result. */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001998 if (reverse) {
1999 if (keys != NULL)
2000 reverse_slice(&keys[0], &keys[saved_ob_size]);
2001 reverse_slice(&saved_ob_item[0], &saved_ob_item[saved_ob_size]);
2002 }
Benjamin Peterson05380642010-08-23 19:35:39 +00002003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002004 /* March over the array once, left to right, finding natural runs,
2005 * and extending short natural runs to minrun elements.
2006 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002007 minrun = merge_compute_minrun(nremaining);
2008 do {
2009 int descending;
2010 Py_ssize_t n;
Tim Peters330f9e92002-07-19 07:05:44 +00002011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002012 /* Identify next run. */
Daniel Stutzbach98338222010-12-02 21:55:33 +00002013 n = count_run(lo.keys, lo.keys + nremaining, &descending);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002014 if (n < 0)
2015 goto fail;
2016 if (descending)
Daniel Stutzbach98338222010-12-02 21:55:33 +00002017 reverse_sortslice(&lo, n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002018 /* If short, extend to min(minrun, nremaining). */
2019 if (n < minrun) {
2020 const Py_ssize_t force = nremaining <= minrun ?
2021 nremaining : minrun;
Daniel Stutzbach98338222010-12-02 21:55:33 +00002022 if (binarysort(lo, lo.keys + force, lo.keys + n) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002023 goto fail;
2024 n = force;
2025 }
2026 /* Push run onto pending-runs stack, and maybe merge. */
2027 assert(ms.n < MAX_MERGE_PENDING);
2028 ms.pending[ms.n].base = lo;
2029 ms.pending[ms.n].len = n;
2030 ++ms.n;
2031 if (merge_collapse(&ms) < 0)
2032 goto fail;
2033 /* Advance to find next run. */
Daniel Stutzbach98338222010-12-02 21:55:33 +00002034 sortslice_advance(&lo, n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002035 nremaining -= n;
2036 } while (nremaining);
Tim Peters330f9e92002-07-19 07:05:44 +00002037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002038 if (merge_force_collapse(&ms) < 0)
2039 goto fail;
2040 assert(ms.n == 1);
Daniel Stutzbach98338222010-12-02 21:55:33 +00002041 assert(keys == NULL
2042 ? ms.pending[0].base.keys == saved_ob_item
2043 : ms.pending[0].base.keys == &keys[0]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002044 assert(ms.pending[0].len == saved_ob_size);
Daniel Stutzbach98338222010-12-02 21:55:33 +00002045 lo = ms.pending[0].base;
Tim Petersa64dc242002-08-01 02:13:36 +00002046
2047succeed:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002048 result = Py_None;
Tim Peters330f9e92002-07-19 07:05:44 +00002049fail:
Daniel Stutzbach98338222010-12-02 21:55:33 +00002050 if (keys != NULL) {
2051 for (i = 0; i < saved_ob_size; i++)
2052 Py_DECREF(keys[i]);
Benjamin Petersonef87f8c2014-03-14 21:54:31 -05002053 if (saved_ob_size >= MERGESTATE_TEMP_SIZE/2)
Daniel Stutzbach98338222010-12-02 21:55:33 +00002054 PyMem_FREE(keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002055 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002057 if (self->allocated != -1 && result != NULL) {
2058 /* The user mucked with the list during the sort,
2059 * and we don't already have another error to report.
2060 */
2061 PyErr_SetString(PyExc_ValueError, "list modified during sort");
2062 result = NULL;
2063 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002065 if (reverse && saved_ob_size > 1)
2066 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002068 merge_freemem(&ms);
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002069
Daniel Stutzbach98338222010-12-02 21:55:33 +00002070keyfunc_fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002071 final_ob_item = self->ob_item;
2072 i = Py_SIZE(self);
2073 Py_SIZE(self) = saved_ob_size;
2074 self->ob_item = saved_ob_item;
2075 self->allocated = saved_allocated;
2076 if (final_ob_item != NULL) {
2077 /* we cannot use list_clear() for this because it does not
2078 guarantee that the list is really empty when it returns */
2079 while (--i >= 0) {
2080 Py_XDECREF(final_ob_item[i]);
2081 }
2082 PyMem_FREE(final_ob_item);
2083 }
2084 Py_XINCREF(result);
2085 return result;
Guido van Rossum3f236de1996-12-10 23:55:39 +00002086}
Tim Peters330f9e92002-07-19 07:05:44 +00002087#undef IFLT
Tim Peters66860f62002-08-04 17:47:26 +00002088#undef ISLT
Tim Peters330f9e92002-07-19 07:05:44 +00002089
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002090int
Fred Drakea2f55112000-07-09 15:16:51 +00002091PyList_Sort(PyObject *v)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002092{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002093 if (v == NULL || !PyList_Check(v)) {
2094 PyErr_BadInternalCall();
2095 return -1;
2096 }
2097 v = listsort((PyListObject *)v, (PyObject *)NULL, (PyObject *)NULL);
2098 if (v == NULL)
2099 return -1;
2100 Py_DECREF(v);
2101 return 0;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002102}
2103
Guido van Rossumb86c5492001-02-12 22:06:02 +00002104static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002105listreverse(PyListObject *self)
Guido van Rossumb86c5492001-02-12 22:06:02 +00002106{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002107 if (Py_SIZE(self) > 1)
2108 reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
2109 Py_RETURN_NONE;
Guido van Rossumed98d481991-03-06 13:07:53 +00002110}
2111
Guido van Rossum84c76f51990-10-30 13:32:20 +00002112int
Fred Drakea2f55112000-07-09 15:16:51 +00002113PyList_Reverse(PyObject *v)
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002114{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002115 PyListObject *self = (PyListObject *)v;
Tim Peters6063e262002-08-08 01:06:39 +00002116
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002117 if (v == NULL || !PyList_Check(v)) {
2118 PyErr_BadInternalCall();
2119 return -1;
2120 }
2121 if (Py_SIZE(self) > 1)
2122 reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
2123 return 0;
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002124}
2125
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002126PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00002127PyList_AsTuple(PyObject *v)
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002128{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002129 PyObject *w;
2130 PyObject **p, **q;
2131 Py_ssize_t n;
2132 if (v == NULL || !PyList_Check(v)) {
2133 PyErr_BadInternalCall();
2134 return NULL;
2135 }
2136 n = Py_SIZE(v);
2137 w = PyTuple_New(n);
2138 if (w == NULL)
2139 return NULL;
2140 p = ((PyTupleObject *)w)->ob_item;
2141 q = ((PyListObject *)v)->ob_item;
2142 while (--n >= 0) {
2143 Py_INCREF(*q);
2144 *p = *q;
2145 p++;
2146 q++;
2147 }
2148 return w;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002149}
2150
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002151static PyObject *
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002152listindex(PyListObject *self, PyObject *args)
Guido van Rossumed98d481991-03-06 13:07:53 +00002153{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002154 Py_ssize_t i, start=0, stop=Py_SIZE(self);
Amaury Forgeot d'Arc864741b2011-11-06 15:10:48 +01002155 PyObject *v;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002156
Petri Lehtinenebfaabd2011-11-06 21:02:39 +02002157 if (!PyArg_ParseTuple(args, "O|O&O&:index", &v,
2158 _PyEval_SliceIndex, &start,
2159 _PyEval_SliceIndex, &stop))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002160 return NULL;
2161 if (start < 0) {
2162 start += Py_SIZE(self);
2163 if (start < 0)
2164 start = 0;
2165 }
2166 if (stop < 0) {
2167 stop += Py_SIZE(self);
2168 if (stop < 0)
2169 stop = 0;
2170 }
2171 for (i = start; i < stop && i < Py_SIZE(self); i++) {
2172 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2173 if (cmp > 0)
2174 return PyLong_FromSsize_t(i);
2175 else if (cmp < 0)
2176 return NULL;
2177 }
Amaury Forgeot d'Arc864741b2011-11-06 15:10:48 +01002178 PyErr_Format(PyExc_ValueError, "%R is not in list", v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002179 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002180}
2181
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002182static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002183listcount(PyListObject *self, PyObject *v)
Guido van Rossume6f7d181991-10-20 20:20:40 +00002184{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002185 Py_ssize_t count = 0;
2186 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002188 for (i = 0; i < Py_SIZE(self); i++) {
2189 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2190 if (cmp > 0)
2191 count++;
2192 else if (cmp < 0)
2193 return NULL;
2194 }
2195 return PyLong_FromSsize_t(count);
Guido van Rossume6f7d181991-10-20 20:20:40 +00002196}
2197
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002198static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002199listremove(PyListObject *self, PyObject *v)
Guido van Rossumed98d481991-03-06 13:07:53 +00002200{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002201 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002202
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002203 for (i = 0; i < Py_SIZE(self); i++) {
2204 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2205 if (cmp > 0) {
2206 if (list_ass_slice(self, i, i+1,
2207 (PyObject *)NULL) == 0)
2208 Py_RETURN_NONE;
2209 return NULL;
2210 }
2211 else if (cmp < 0)
2212 return NULL;
2213 }
2214 PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
2215 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002216}
2217
Jeremy Hylton8caad492000-06-23 14:18:11 +00002218static int
2219list_traverse(PyListObject *o, visitproc visit, void *arg)
2220{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002221 Py_ssize_t i;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002222
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002223 for (i = Py_SIZE(o); --i >= 0; )
2224 Py_VISIT(o->ob_item[i]);
2225 return 0;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002226}
2227
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002228static PyObject *
2229list_richcompare(PyObject *v, PyObject *w, int op)
2230{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002231 PyListObject *vl, *wl;
2232 Py_ssize_t i;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002233
Brian Curtindfc80e32011-08-10 20:28:54 -05002234 if (!PyList_Check(v) || !PyList_Check(w))
2235 Py_RETURN_NOTIMPLEMENTED;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002237 vl = (PyListObject *)v;
2238 wl = (PyListObject *)w;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002240 if (Py_SIZE(vl) != Py_SIZE(wl) && (op == Py_EQ || op == Py_NE)) {
2241 /* Shortcut: if the lengths differ, the lists differ */
2242 PyObject *res;
2243 if (op == Py_EQ)
2244 res = Py_False;
2245 else
2246 res = Py_True;
2247 Py_INCREF(res);
2248 return res;
2249 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002251 /* Search for the first index where items are different */
2252 for (i = 0; i < Py_SIZE(vl) && i < Py_SIZE(wl); i++) {
2253 int k = PyObject_RichCompareBool(vl->ob_item[i],
2254 wl->ob_item[i], Py_EQ);
2255 if (k < 0)
2256 return NULL;
2257 if (!k)
2258 break;
2259 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002261 if (i >= Py_SIZE(vl) || i >= Py_SIZE(wl)) {
2262 /* No more items to compare -- compare sizes */
2263 Py_ssize_t vs = Py_SIZE(vl);
2264 Py_ssize_t ws = Py_SIZE(wl);
2265 int cmp;
2266 PyObject *res;
2267 switch (op) {
2268 case Py_LT: cmp = vs < ws; break;
2269 case Py_LE: cmp = vs <= ws; break;
2270 case Py_EQ: cmp = vs == ws; break;
2271 case Py_NE: cmp = vs != ws; break;
2272 case Py_GT: cmp = vs > ws; break;
2273 case Py_GE: cmp = vs >= ws; break;
2274 default: return NULL; /* cannot happen */
2275 }
2276 if (cmp)
2277 res = Py_True;
2278 else
2279 res = Py_False;
2280 Py_INCREF(res);
2281 return res;
2282 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002284 /* We have an item that differs -- shortcuts for EQ/NE */
2285 if (op == Py_EQ) {
2286 Py_INCREF(Py_False);
2287 return Py_False;
2288 }
2289 if (op == Py_NE) {
2290 Py_INCREF(Py_True);
2291 return Py_True;
2292 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002294 /* Compare the final item again using the proper operator */
2295 return PyObject_RichCompare(vl->ob_item[i], wl->ob_item[i], op);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002296}
2297
Tim Peters6d6c1a32001-08-02 04:15:00 +00002298static int
2299list_init(PyListObject *self, PyObject *args, PyObject *kw)
2300{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002301 PyObject *arg = NULL;
2302 static char *kwlist[] = {"sequence", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002304 if (!PyArg_ParseTupleAndKeywords(args, kw, "|O:list", kwlist, &arg))
2305 return -1;
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002307 /* Verify list invariants established by PyType_GenericAlloc() */
2308 assert(0 <= Py_SIZE(self));
2309 assert(Py_SIZE(self) <= self->allocated || self->allocated == -1);
2310 assert(self->ob_item != NULL ||
2311 self->allocated == 0 || self->allocated == -1);
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002313 /* Empty previous contents */
2314 if (self->ob_item != NULL) {
2315 (void)list_clear(self);
2316 }
2317 if (arg != NULL) {
2318 PyObject *rv = listextend(self, arg);
2319 if (rv == NULL)
2320 return -1;
2321 Py_DECREF(rv);
2322 }
2323 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002324}
2325
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002326static PyObject *
2327list_sizeof(PyListObject *self)
2328{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002329 Py_ssize_t res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002330
Serhiy Storchaka5c4064e2015-12-19 20:05:25 +02002331 res = _PyObject_SIZE(Py_TYPE(self)) + self->allocated * sizeof(void*);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002332 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002333}
2334
Raymond Hettinger1021c442003-11-07 15:38:09 +00002335static PyObject *list_iter(PyObject *seq);
2336static PyObject *list_reversed(PyListObject* seq, PyObject* unused);
2337
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002338PyDoc_STRVAR(getitem_doc,
2339"x.__getitem__(y) <==> x[y]");
Raymond Hettinger1021c442003-11-07 15:38:09 +00002340PyDoc_STRVAR(reversed_doc,
2341"L.__reversed__() -- return a reverse iterator over the list");
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002342PyDoc_STRVAR(sizeof_doc,
2343"L.__sizeof__() -- size of L in memory, in bytes");
Eli Benderskycbbaa962011-02-25 05:47:53 +00002344PyDoc_STRVAR(clear_doc,
2345"L.clear() -> None -- remove all items from L");
2346PyDoc_STRVAR(copy_doc,
2347"L.copy() -> list -- a shallow copy of L");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002348PyDoc_STRVAR(append_doc,
Georg Brandl388349a2011-10-08 18:32:40 +02002349"L.append(object) -> None -- append object to end");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002350PyDoc_STRVAR(extend_doc,
Georg Brandl388349a2011-10-08 18:32:40 +02002351"L.extend(iterable) -> None -- extend list by appending elements from the iterable");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002352PyDoc_STRVAR(insert_doc,
2353"L.insert(index, object) -- insert object before index");
2354PyDoc_STRVAR(pop_doc,
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00002355"L.pop([index]) -> item -- remove and return item at index (default last).\n"
2356"Raises IndexError if list is empty or index is out of range.");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002357PyDoc_STRVAR(remove_doc,
Georg Brandl388349a2011-10-08 18:32:40 +02002358"L.remove(value) -> None -- remove first occurrence of value.\n"
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00002359"Raises ValueError if the value is not present.");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002360PyDoc_STRVAR(index_doc,
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00002361"L.index(value, [start, [stop]]) -> integer -- return first index of value.\n"
2362"Raises ValueError if the value is not present.");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002363PyDoc_STRVAR(count_doc,
2364"L.count(value) -> integer -- return number of occurrences of value");
2365PyDoc_STRVAR(reverse_doc,
2366"L.reverse() -- reverse *IN PLACE*");
2367PyDoc_STRVAR(sort_doc,
Georg Brandl388349a2011-10-08 18:32:40 +02002368"L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*");
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +00002369
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002370static PyObject *list_subscript(PyListObject*, PyObject*);
2371
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002372static PyMethodDef list_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002373 {"__getitem__", (PyCFunction)list_subscript, METH_O|METH_COEXIST, getitem_doc},
2374 {"__reversed__",(PyCFunction)list_reversed, METH_NOARGS, reversed_doc},
2375 {"__sizeof__", (PyCFunction)list_sizeof, METH_NOARGS, sizeof_doc},
Eli Benderskycbbaa962011-02-25 05:47:53 +00002376 {"clear", (PyCFunction)listclear, METH_NOARGS, clear_doc},
2377 {"copy", (PyCFunction)listcopy, METH_NOARGS, copy_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002378 {"append", (PyCFunction)listappend, METH_O, append_doc},
2379 {"insert", (PyCFunction)listinsert, METH_VARARGS, insert_doc},
Eli Benderskycbbaa962011-02-25 05:47:53 +00002380 {"extend", (PyCFunction)listextend, METH_O, extend_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002381 {"pop", (PyCFunction)listpop, METH_VARARGS, pop_doc},
2382 {"remove", (PyCFunction)listremove, METH_O, remove_doc},
2383 {"index", (PyCFunction)listindex, METH_VARARGS, index_doc},
2384 {"count", (PyCFunction)listcount, METH_O, count_doc},
2385 {"reverse", (PyCFunction)listreverse, METH_NOARGS, reverse_doc},
2386 {"sort", (PyCFunction)listsort, METH_VARARGS | METH_KEYWORDS, sort_doc},
2387 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002388};
2389
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002390static PySequenceMethods list_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002391 (lenfunc)list_length, /* sq_length */
2392 (binaryfunc)list_concat, /* sq_concat */
2393 (ssizeargfunc)list_repeat, /* sq_repeat */
2394 (ssizeargfunc)list_item, /* sq_item */
2395 0, /* sq_slice */
2396 (ssizeobjargproc)list_ass_item, /* sq_ass_item */
2397 0, /* sq_ass_slice */
2398 (objobjproc)list_contains, /* sq_contains */
2399 (binaryfunc)list_inplace_concat, /* sq_inplace_concat */
2400 (ssizeargfunc)list_inplace_repeat, /* sq_inplace_repeat */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002401};
2402
Neal Norwitz2c2e8272002-06-14 02:04:18 +00002403PyDoc_STRVAR(list_doc,
Ezio Melotti7f807b72010-03-01 04:08:34 +00002404"list() -> new empty list\n"
2405"list(iterable) -> new list initialized from iterable's items");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002406
Jeremy Hyltona4b4c3b2002-07-13 03:51:17 +00002407static PyObject *
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002408list_subscript(PyListObject* self, PyObject* item)
2409{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002410 if (PyIndex_Check(item)) {
2411 Py_ssize_t i;
2412 i = PyNumber_AsSsize_t(item, PyExc_IndexError);
2413 if (i == -1 && PyErr_Occurred())
2414 return NULL;
2415 if (i < 0)
2416 i += PyList_GET_SIZE(self);
2417 return list_item(self, i);
2418 }
2419 else if (PySlice_Check(item)) {
2420 Py_ssize_t start, stop, step, slicelength, cur, i;
2421 PyObject* result;
2422 PyObject* it;
2423 PyObject **src, **dest;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002424
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002425 if (PySlice_GetIndicesEx(item, Py_SIZE(self),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002426 &start, &stop, &step, &slicelength) < 0) {
2427 return NULL;
2428 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002429
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002430 if (slicelength <= 0) {
2431 return PyList_New(0);
2432 }
2433 else if (step == 1) {
2434 return list_slice(self, start, stop);
2435 }
2436 else {
2437 result = PyList_New(slicelength);
2438 if (!result) return NULL;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002440 src = self->ob_item;
2441 dest = ((PyListObject *)result)->ob_item;
2442 for (cur = start, i = 0; i < slicelength;
Mark Dickinsonc7d93b72011-09-25 15:34:32 +01002443 cur += (size_t)step, i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002444 it = src[cur];
2445 Py_INCREF(it);
2446 dest[i] = it;
2447 }
Tim Peters3b01a122002-07-19 02:35:45 +00002448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002449 return result;
2450 }
2451 }
2452 else {
2453 PyErr_Format(PyExc_TypeError,
Terry Jan Reedyffff1442014-08-02 01:30:37 -04002454 "list indices must be integers or slices, not %.200s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002455 item->ob_type->tp_name);
2456 return NULL;
2457 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002458}
2459
Tim Peters3b01a122002-07-19 02:35:45 +00002460static int
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002461list_ass_subscript(PyListObject* self, PyObject* item, PyObject* value)
2462{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002463 if (PyIndex_Check(item)) {
2464 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
2465 if (i == -1 && PyErr_Occurred())
2466 return -1;
2467 if (i < 0)
2468 i += PyList_GET_SIZE(self);
2469 return list_ass_item(self, i, value);
2470 }
2471 else if (PySlice_Check(item)) {
2472 Py_ssize_t start, stop, step, slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002473
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002474 if (PySlice_GetIndicesEx(item, Py_SIZE(self),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002475 &start, &stop, &step, &slicelength) < 0) {
2476 return -1;
2477 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002479 if (step == 1)
2480 return list_ass_slice(self, start, stop, value);
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002482 /* Make sure s[5:2] = [..] inserts at the right place:
2483 before 5, not before 2. */
2484 if ((step < 0 && start < stop) ||
2485 (step > 0 && start > stop))
2486 stop = start;
Thomas Woutersed03b412007-08-28 21:37:11 +00002487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002488 if (value == NULL) {
2489 /* delete slice */
2490 PyObject **garbage;
2491 size_t cur;
2492 Py_ssize_t i;
Victor Stinner35f28032013-11-21 12:16:35 +01002493 int res;
Tim Peters3b01a122002-07-19 02:35:45 +00002494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002495 if (slicelength <= 0)
2496 return 0;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002498 if (step < 0) {
2499 stop = start + 1;
2500 start = stop + step*(slicelength - 1) - 1;
2501 step = -step;
2502 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002504 assert((size_t)slicelength <=
2505 PY_SIZE_MAX / sizeof(PyObject*));
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00002506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002507 garbage = (PyObject**)
2508 PyMem_MALLOC(slicelength*sizeof(PyObject*));
2509 if (!garbage) {
2510 PyErr_NoMemory();
2511 return -1;
2512 }
Tim Peters3b01a122002-07-19 02:35:45 +00002513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002514 /* drawing pictures might help understand these for
2515 loops. Basically, we memmove the parts of the
2516 list that are *not* part of the slice: step-1
2517 items for each item that is part of the slice,
2518 and then tail end of the list that was not
2519 covered by the slice */
2520 for (cur = start, i = 0;
2521 cur < (size_t)stop;
2522 cur += step, i++) {
2523 Py_ssize_t lim = step - 1;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002525 garbage[i] = PyList_GET_ITEM(self, cur);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002527 if (cur + step >= (size_t)Py_SIZE(self)) {
2528 lim = Py_SIZE(self) - cur - 1;
2529 }
Michael W. Hudson56796f62002-07-29 14:35:04 +00002530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002531 memmove(self->ob_item + cur - i,
2532 self->ob_item + cur + 1,
2533 lim * sizeof(PyObject *));
2534 }
Mark Dickinsonc7d93b72011-09-25 15:34:32 +01002535 cur = start + (size_t)slicelength * step;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002536 if (cur < (size_t)Py_SIZE(self)) {
2537 memmove(self->ob_item + cur - slicelength,
2538 self->ob_item + cur,
2539 (Py_SIZE(self) - cur) *
2540 sizeof(PyObject *));
2541 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002542
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002543 Py_SIZE(self) -= slicelength;
Victor Stinner35f28032013-11-21 12:16:35 +01002544 res = list_resize(self, Py_SIZE(self));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002546 for (i = 0; i < slicelength; i++) {
2547 Py_DECREF(garbage[i]);
2548 }
2549 PyMem_FREE(garbage);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002550
Victor Stinner35f28032013-11-21 12:16:35 +01002551 return res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002552 }
2553 else {
2554 /* assign slice */
2555 PyObject *ins, *seq;
2556 PyObject **garbage, **seqitems, **selfitems;
2557 Py_ssize_t cur, i;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002558
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002559 /* protect against a[::-1] = a */
2560 if (self == (PyListObject*)value) {
2561 seq = list_slice((PyListObject*)value, 0,
2562 PyList_GET_SIZE(value));
2563 }
2564 else {
2565 seq = PySequence_Fast(value,
2566 "must assign iterable "
2567 "to extended slice");
2568 }
2569 if (!seq)
2570 return -1;
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002572 if (PySequence_Fast_GET_SIZE(seq) != slicelength) {
2573 PyErr_Format(PyExc_ValueError,
2574 "attempt to assign sequence of "
2575 "size %zd to extended slice of "
2576 "size %zd",
2577 PySequence_Fast_GET_SIZE(seq),
2578 slicelength);
2579 Py_DECREF(seq);
2580 return -1;
2581 }
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002583 if (!slicelength) {
2584 Py_DECREF(seq);
2585 return 0;
2586 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002588 garbage = (PyObject**)
2589 PyMem_MALLOC(slicelength*sizeof(PyObject*));
2590 if (!garbage) {
2591 Py_DECREF(seq);
2592 PyErr_NoMemory();
2593 return -1;
2594 }
Tim Peters3b01a122002-07-19 02:35:45 +00002595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002596 selfitems = self->ob_item;
2597 seqitems = PySequence_Fast_ITEMS(seq);
2598 for (cur = start, i = 0; i < slicelength;
Mark Dickinsonc7d93b72011-09-25 15:34:32 +01002599 cur += (size_t)step, i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002600 garbage[i] = selfitems[cur];
2601 ins = seqitems[i];
2602 Py_INCREF(ins);
2603 selfitems[cur] = ins;
2604 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002606 for (i = 0; i < slicelength; i++) {
2607 Py_DECREF(garbage[i]);
2608 }
Tim Peters3b01a122002-07-19 02:35:45 +00002609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002610 PyMem_FREE(garbage);
2611 Py_DECREF(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002613 return 0;
2614 }
2615 }
2616 else {
2617 PyErr_Format(PyExc_TypeError,
Terry Jan Reedyffff1442014-08-02 01:30:37 -04002618 "list indices must be integers or slices, not %.200s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002619 item->ob_type->tp_name);
2620 return -1;
2621 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002622}
2623
2624static PyMappingMethods list_as_mapping = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002625 (lenfunc)list_length,
2626 (binaryfunc)list_subscript,
2627 (objobjargproc)list_ass_subscript
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002628};
2629
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002630PyTypeObject PyList_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002631 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2632 "list",
2633 sizeof(PyListObject),
2634 0,
2635 (destructor)list_dealloc, /* tp_dealloc */
2636 0, /* tp_print */
2637 0, /* tp_getattr */
2638 0, /* tp_setattr */
2639 0, /* tp_reserved */
2640 (reprfunc)list_repr, /* tp_repr */
2641 0, /* tp_as_number */
2642 &list_as_sequence, /* tp_as_sequence */
2643 &list_as_mapping, /* tp_as_mapping */
Georg Brandl00da4e02010-10-18 07:32:48 +00002644 PyObject_HashNotImplemented, /* tp_hash */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002645 0, /* tp_call */
2646 0, /* tp_str */
2647 PyObject_GenericGetAttr, /* tp_getattro */
2648 0, /* tp_setattro */
2649 0, /* tp_as_buffer */
2650 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2651 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LIST_SUBCLASS, /* tp_flags */
2652 list_doc, /* tp_doc */
2653 (traverseproc)list_traverse, /* tp_traverse */
2654 (inquiry)list_clear, /* tp_clear */
2655 list_richcompare, /* tp_richcompare */
2656 0, /* tp_weaklistoffset */
2657 list_iter, /* tp_iter */
2658 0, /* tp_iternext */
2659 list_methods, /* tp_methods */
2660 0, /* tp_members */
2661 0, /* tp_getset */
2662 0, /* tp_base */
2663 0, /* tp_dict */
2664 0, /* tp_descr_get */
2665 0, /* tp_descr_set */
2666 0, /* tp_dictoffset */
2667 (initproc)list_init, /* tp_init */
2668 PyType_GenericAlloc, /* tp_alloc */
2669 PyType_GenericNew, /* tp_new */
2670 PyObject_GC_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002671};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002672
2673
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002674/*********************** List Iterator **************************/
2675
2676typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002677 PyObject_HEAD
Victor Stinner7660b882013-06-24 23:59:24 +02002678 Py_ssize_t it_index;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002679 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002680} listiterobject;
2681
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002682static PyObject *list_iter(PyObject *);
2683static void listiter_dealloc(listiterobject *);
2684static int listiter_traverse(listiterobject *, visitproc, void *);
2685static PyObject *listiter_next(listiterobject *);
2686static PyObject *listiter_len(listiterobject *);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002687static PyObject *listiter_reduce_general(void *_it, int forward);
2688static PyObject *listiter_reduce(listiterobject *);
2689static PyObject *listiter_setstate(listiterobject *, PyObject *state);
Raymond Hettinger435bf582004-03-18 22:43:10 +00002690
Armin Rigof5b3e362006-02-11 21:32:43 +00002691PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002692PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
2693PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002694
2695static PyMethodDef listiter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002696 {"__length_hint__", (PyCFunction)listiter_len, METH_NOARGS, length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002697 {"__reduce__", (PyCFunction)listiter_reduce, METH_NOARGS, reduce_doc},
2698 {"__setstate__", (PyCFunction)listiter_setstate, METH_O, setstate_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002699 {NULL, NULL} /* sentinel */
Raymond Hettinger435bf582004-03-18 22:43:10 +00002700};
2701
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002702PyTypeObject PyListIter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002703 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2704 "list_iterator", /* tp_name */
2705 sizeof(listiterobject), /* tp_basicsize */
2706 0, /* tp_itemsize */
2707 /* methods */
2708 (destructor)listiter_dealloc, /* tp_dealloc */
2709 0, /* tp_print */
2710 0, /* tp_getattr */
2711 0, /* tp_setattr */
2712 0, /* tp_reserved */
2713 0, /* tp_repr */
2714 0, /* tp_as_number */
2715 0, /* tp_as_sequence */
2716 0, /* tp_as_mapping */
2717 0, /* tp_hash */
2718 0, /* tp_call */
2719 0, /* tp_str */
2720 PyObject_GenericGetAttr, /* tp_getattro */
2721 0, /* tp_setattro */
2722 0, /* tp_as_buffer */
2723 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2724 0, /* tp_doc */
2725 (traverseproc)listiter_traverse, /* tp_traverse */
2726 0, /* tp_clear */
2727 0, /* tp_richcompare */
2728 0, /* tp_weaklistoffset */
2729 PyObject_SelfIter, /* tp_iter */
2730 (iternextfunc)listiter_next, /* tp_iternext */
2731 listiter_methods, /* tp_methods */
2732 0, /* tp_members */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002733};
Raymond Hettinger1021c442003-11-07 15:38:09 +00002734
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002735
2736static PyObject *
2737list_iter(PyObject *seq)
2738{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002739 listiterobject *it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002740
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002741 if (!PyList_Check(seq)) {
2742 PyErr_BadInternalCall();
2743 return NULL;
2744 }
2745 it = PyObject_GC_New(listiterobject, &PyListIter_Type);
2746 if (it == NULL)
2747 return NULL;
2748 it->it_index = 0;
2749 Py_INCREF(seq);
2750 it->it_seq = (PyListObject *)seq;
2751 _PyObject_GC_TRACK(it);
2752 return (PyObject *)it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002753}
2754
2755static void
2756listiter_dealloc(listiterobject *it)
2757{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002758 _PyObject_GC_UNTRACK(it);
2759 Py_XDECREF(it->it_seq);
2760 PyObject_GC_Del(it);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002761}
2762
2763static int
2764listiter_traverse(listiterobject *it, visitproc visit, void *arg)
2765{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002766 Py_VISIT(it->it_seq);
2767 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002768}
2769
2770static PyObject *
2771listiter_next(listiterobject *it)
2772{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002773 PyListObject *seq;
2774 PyObject *item;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002775
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002776 assert(it != NULL);
2777 seq = it->it_seq;
2778 if (seq == NULL)
2779 return NULL;
2780 assert(PyList_Check(seq));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002782 if (it->it_index < PyList_GET_SIZE(seq)) {
2783 item = PyList_GET_ITEM(seq, it->it_index);
2784 ++it->it_index;
2785 Py_INCREF(item);
2786 return item;
2787 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002789 it->it_seq = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03002790 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002791 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002792}
2793
2794static PyObject *
2795listiter_len(listiterobject *it)
2796{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002797 Py_ssize_t len;
2798 if (it->it_seq) {
2799 len = PyList_GET_SIZE(it->it_seq) - it->it_index;
2800 if (len >= 0)
2801 return PyLong_FromSsize_t(len);
2802 }
2803 return PyLong_FromLong(0);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002804}
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002805
2806static PyObject *
2807listiter_reduce(listiterobject *it)
2808{
2809 return listiter_reduce_general(it, 1);
2810}
2811
2812static PyObject *
2813listiter_setstate(listiterobject *it, PyObject *state)
2814{
Victor Stinner7660b882013-06-24 23:59:24 +02002815 Py_ssize_t index = PyLong_AsSsize_t(state);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002816 if (index == -1 && PyErr_Occurred())
2817 return NULL;
2818 if (it->it_seq != NULL) {
2819 if (index < 0)
2820 index = 0;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +00002821 else if (index > PyList_GET_SIZE(it->it_seq))
2822 index = PyList_GET_SIZE(it->it_seq); /* iterator exhausted */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002823 it->it_index = index;
2824 }
2825 Py_RETURN_NONE;
2826}
2827
Raymond Hettinger1021c442003-11-07 15:38:09 +00002828/*********************** List Reverse Iterator **************************/
2829
2830typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002831 PyObject_HEAD
2832 Py_ssize_t it_index;
2833 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger1021c442003-11-07 15:38:09 +00002834} listreviterobject;
2835
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002836static PyObject *list_reversed(PyListObject *, PyObject *);
2837static void listreviter_dealloc(listreviterobject *);
2838static int listreviter_traverse(listreviterobject *, visitproc, void *);
2839static PyObject *listreviter_next(listreviterobject *);
Raymond Hettingerf5b64112008-12-02 21:33:45 +00002840static PyObject *listreviter_len(listreviterobject *);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002841static PyObject *listreviter_reduce(listreviterobject *);
2842static PyObject *listreviter_setstate(listreviterobject *, PyObject *);
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002843
Raymond Hettingerf5b64112008-12-02 21:33:45 +00002844static PyMethodDef listreviter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002845 {"__length_hint__", (PyCFunction)listreviter_len, METH_NOARGS, length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002846 {"__reduce__", (PyCFunction)listreviter_reduce, METH_NOARGS, reduce_doc},
2847 {"__setstate__", (PyCFunction)listreviter_setstate, METH_O, setstate_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002848 {NULL, NULL} /* sentinel */
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002849};
2850
Raymond Hettinger1021c442003-11-07 15:38:09 +00002851PyTypeObject PyListRevIter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002852 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2853 "list_reverseiterator", /* tp_name */
2854 sizeof(listreviterobject), /* tp_basicsize */
2855 0, /* tp_itemsize */
2856 /* methods */
2857 (destructor)listreviter_dealloc, /* tp_dealloc */
2858 0, /* tp_print */
2859 0, /* tp_getattr */
2860 0, /* tp_setattr */
2861 0, /* tp_reserved */
2862 0, /* tp_repr */
2863 0, /* tp_as_number */
2864 0, /* tp_as_sequence */
2865 0, /* tp_as_mapping */
2866 0, /* tp_hash */
2867 0, /* tp_call */
2868 0, /* tp_str */
2869 PyObject_GenericGetAttr, /* tp_getattro */
2870 0, /* tp_setattro */
2871 0, /* tp_as_buffer */
2872 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2873 0, /* tp_doc */
2874 (traverseproc)listreviter_traverse, /* tp_traverse */
2875 0, /* tp_clear */
2876 0, /* tp_richcompare */
2877 0, /* tp_weaklistoffset */
2878 PyObject_SelfIter, /* tp_iter */
2879 (iternextfunc)listreviter_next, /* tp_iternext */
2880 listreviter_methods, /* tp_methods */
2881 0,
Raymond Hettinger1021c442003-11-07 15:38:09 +00002882};
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002883
2884static PyObject *
2885list_reversed(PyListObject *seq, PyObject *unused)
2886{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002887 listreviterobject *it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002889 it = PyObject_GC_New(listreviterobject, &PyListRevIter_Type);
2890 if (it == NULL)
2891 return NULL;
2892 assert(PyList_Check(seq));
2893 it->it_index = PyList_GET_SIZE(seq) - 1;
2894 Py_INCREF(seq);
2895 it->it_seq = seq;
2896 PyObject_GC_Track(it);
2897 return (PyObject *)it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002898}
2899
2900static void
2901listreviter_dealloc(listreviterobject *it)
2902{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002903 PyObject_GC_UnTrack(it);
2904 Py_XDECREF(it->it_seq);
2905 PyObject_GC_Del(it);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002906}
2907
2908static int
2909listreviter_traverse(listreviterobject *it, visitproc visit, void *arg)
2910{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002911 Py_VISIT(it->it_seq);
2912 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002913}
2914
2915static PyObject *
2916listreviter_next(listreviterobject *it)
2917{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002918 PyObject *item;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03002919 Py_ssize_t index;
2920 PyListObject *seq;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002921
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03002922 assert(it != NULL);
2923 seq = it->it_seq;
2924 if (seq == NULL) {
2925 return NULL;
2926 }
2927 assert(PyList_Check(seq));
2928
2929 index = it->it_index;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002930 if (index>=0 && index < PyList_GET_SIZE(seq)) {
2931 item = PyList_GET_ITEM(seq, index);
2932 it->it_index--;
2933 Py_INCREF(item);
2934 return item;
2935 }
2936 it->it_index = -1;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03002937 it->it_seq = NULL;
2938 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002939 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002940}
2941
Raymond Hettingerf5b64112008-12-02 21:33:45 +00002942static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002943listreviter_len(listreviterobject *it)
2944{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002945 Py_ssize_t len = it->it_index + 1;
2946 if (it->it_seq == NULL || PyList_GET_SIZE(it->it_seq) < len)
2947 len = 0;
2948 return PyLong_FromSsize_t(len);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002949}
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002950
2951static PyObject *
2952listreviter_reduce(listreviterobject *it)
2953{
2954 return listiter_reduce_general(it, 0);
2955}
2956
2957static PyObject *
2958listreviter_setstate(listreviterobject *it, PyObject *state)
2959{
2960 Py_ssize_t index = PyLong_AsSsize_t(state);
2961 if (index == -1 && PyErr_Occurred())
2962 return NULL;
2963 if (it->it_seq != NULL) {
2964 if (index < -1)
2965 index = -1;
2966 else if (index > PyList_GET_SIZE(it->it_seq) - 1)
2967 index = PyList_GET_SIZE(it->it_seq) - 1;
2968 it->it_index = index;
2969 }
2970 Py_RETURN_NONE;
2971}
2972
2973/* common pickling support */
2974
2975static PyObject *
2976listiter_reduce_general(void *_it, int forward)
2977{
2978 PyObject *list;
2979
2980 /* the objects are not the same, index is of different types! */
2981 if (forward) {
2982 listiterobject *it = (listiterobject *)_it;
2983 if (it->it_seq)
Victor Stinner7660b882013-06-24 23:59:24 +02002984 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002985 it->it_seq, it->it_index);
2986 } else {
2987 listreviterobject *it = (listreviterobject *)_it;
2988 if (it->it_seq)
Antoine Pitroua7013882012-04-05 00:04:20 +02002989 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("reversed"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002990 it->it_seq, it->it_index);
2991 }
2992 /* empty iterator, create an empty list */
2993 list = PyList_New(0);
2994 if (list == NULL)
2995 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +02002996 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), list);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002997}