blob: 7c02be7276f128642ce5dc7e6835eb69c3164eb1 [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{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000085 fprintf(stderr, "List allocations: %" PY_FORMAT_SIZE_T "d\n",
86 count_alloc);
87 fprintf(stderr, "List reuse through freelist: %" PY_FORMAT_SIZE_T
88 "d\n", count_reuse);
89 fprintf(stderr, "%.2f%% reuse rate\n\n",
90 (100.0*count_reuse/(count_alloc+count_reuse)));
Christian Heimes77c02eb2008-02-09 02:18:51 +000091}
92#endif
93
Raymond Hettinger0468e412004-05-05 05:37:53 +000094/* Empty list reuse scheme to save calls to malloc and free */
Christian Heimes2202f872008-02-06 14:31:34 +000095#ifndef PyList_MAXFREELIST
96#define PyList_MAXFREELIST 80
97#endif
98static PyListObject *free_list[PyList_MAXFREELIST];
99static int numfree = 0;
Raymond Hettinger0468e412004-05-05 05:37:53 +0000100
Antoine Pitrou9a812cb2011-11-15 00:00:12 +0100101int
102PyList_ClearFreeList(void)
Raymond Hettingerfb09f0e2004-10-07 03:58:07 +0000103{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000104 PyListObject *op;
Antoine Pitrou9a812cb2011-11-15 00:00:12 +0100105 int ret = numfree;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000106 while (numfree) {
107 op = free_list[--numfree];
108 assert(PyList_CheckExact(op));
109 PyObject_GC_Del(op);
110 }
Antoine Pitrou9a812cb2011-11-15 00:00:12 +0100111 return ret;
112}
113
114void
115PyList_Fini(void)
116{
117 PyList_ClearFreeList();
Raymond Hettingerfb09f0e2004-10-07 03:58:07 +0000118}
119
David Malcolm49526f42012-06-22 14:55:41 -0400120/* Print summary info about the state of the optimized allocator */
121void
122_PyList_DebugMallocStats(FILE *out)
123{
124 _PyDebugAllocatorStats(out,
125 "free PyListObject",
126 numfree, sizeof(PyListObject));
127}
128
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000129PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000130PyList_New(Py_ssize_t size)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000131{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000132 PyListObject *op;
133 size_t nbytes;
Christian Heimes77c02eb2008-02-09 02:18:51 +0000134#ifdef SHOW_ALLOC_COUNT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000135 static int initialized = 0;
136 if (!initialized) {
137 Py_AtExit(show_alloc);
138 initialized = 1;
139 }
Christian Heimes77c02eb2008-02-09 02:18:51 +0000140#endif
Tim Peters3986d4e2004-07-29 02:28:42 +0000141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000142 if (size < 0) {
143 PyErr_BadInternalCall();
144 return NULL;
145 }
146 /* Check for overflow without an actual overflow,
147 * which can cause compiler to optimise out */
148 if ((size_t)size > PY_SIZE_MAX / sizeof(PyObject *))
149 return PyErr_NoMemory();
150 nbytes = size * sizeof(PyObject *);
151 if (numfree) {
152 numfree--;
153 op = free_list[numfree];
154 _Py_NewReference((PyObject *)op);
Christian Heimes77c02eb2008-02-09 02:18:51 +0000155#ifdef SHOW_ALLOC_COUNT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000156 count_reuse++;
Christian Heimes77c02eb2008-02-09 02:18:51 +0000157#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000158 } else {
159 op = PyObject_GC_New(PyListObject, &PyList_Type);
160 if (op == NULL)
161 return NULL;
Christian Heimes77c02eb2008-02-09 02:18:51 +0000162#ifdef SHOW_ALLOC_COUNT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000163 count_alloc++;
Christian Heimes77c02eb2008-02-09 02:18:51 +0000164#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000165 }
166 if (size <= 0)
167 op->ob_item = NULL;
168 else {
169 op->ob_item = (PyObject **) PyMem_MALLOC(nbytes);
170 if (op->ob_item == NULL) {
171 Py_DECREF(op);
172 return PyErr_NoMemory();
173 }
174 memset(op->ob_item, 0, nbytes);
175 }
176 Py_SIZE(op) = size;
177 op->allocated = size;
178 _PyObject_GC_TRACK(op);
179 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000180}
181
Martin v. Löwis18e16552006-02-15 17:27:45 +0000182Py_ssize_t
Fred Drakea2f55112000-07-09 15:16:51 +0000183PyList_Size(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000184{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000185 if (!PyList_Check(op)) {
186 PyErr_BadInternalCall();
187 return -1;
188 }
189 else
190 return Py_SIZE(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000191}
192
Raymond Hettingerfdfe6182004-05-05 06:28:16 +0000193static PyObject *indexerr = NULL;
Guido van Rossum929f1b81996-08-09 20:51:27 +0000194
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000195PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000196PyList_GetItem(PyObject *op, Py_ssize_t i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000197{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000198 if (!PyList_Check(op)) {
199 PyErr_BadInternalCall();
200 return NULL;
201 }
202 if (i < 0 || i >= Py_SIZE(op)) {
203 if (indexerr == NULL) {
204 indexerr = PyUnicode_FromString(
205 "list index out of range");
206 if (indexerr == NULL)
207 return NULL;
208 }
209 PyErr_SetObject(PyExc_IndexError, indexerr);
210 return NULL;
211 }
212 return ((PyListObject *)op) -> ob_item[i];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000213}
214
215int
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200216PyList_SetItem(PyObject *op, Py_ssize_t i,
217 PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000218{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200219 PyObject **p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000220 if (!PyList_Check(op)) {
221 Py_XDECREF(newitem);
222 PyErr_BadInternalCall();
223 return -1;
224 }
225 if (i < 0 || i >= Py_SIZE(op)) {
226 Py_XDECREF(newitem);
227 PyErr_SetString(PyExc_IndexError,
228 "list assignment index out of range");
229 return -1;
230 }
231 p = ((PyListObject *)op) -> ob_item + i;
Serhiy Storchakaec397562016-04-06 09:50:03 +0300232 Py_XSETREF(*p, newitem);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000233 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000234}
235
236static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000237ins1(PyListObject *self, Py_ssize_t where, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000238{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000239 Py_ssize_t i, n = Py_SIZE(self);
240 PyObject **items;
241 if (v == NULL) {
242 PyErr_BadInternalCall();
243 return -1;
244 }
245 if (n == PY_SSIZE_T_MAX) {
246 PyErr_SetString(PyExc_OverflowError,
247 "cannot add more objects to list");
248 return -1;
249 }
Tim Petersb38e2b62004-07-29 02:29:26 +0000250
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800251 if (list_resize(self, n+1) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000252 return -1;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000254 if (where < 0) {
255 where += n;
256 if (where < 0)
257 where = 0;
258 }
259 if (where > n)
260 where = n;
261 items = self->ob_item;
262 for (i = n; --i >= where; )
263 items[i+1] = items[i];
264 Py_INCREF(v);
265 items[where] = v;
266 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000267}
268
269int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000270PyList_Insert(PyObject *op, Py_ssize_t where, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000271{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000272 if (!PyList_Check(op)) {
273 PyErr_BadInternalCall();
274 return -1;
275 }
276 return ins1((PyListObject *)op, where, newitem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000277}
278
Raymond Hettinger40a03822004-04-12 13:05:09 +0000279static int
280app1(PyListObject *self, PyObject *v)
281{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000282 Py_ssize_t n = PyList_GET_SIZE(self);
Raymond Hettinger40a03822004-04-12 13:05:09 +0000283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000284 assert (v != NULL);
285 if (n == PY_SSIZE_T_MAX) {
286 PyErr_SetString(PyExc_OverflowError,
287 "cannot add more objects to list");
288 return -1;
289 }
Raymond Hettinger40a03822004-04-12 13:05:09 +0000290
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800291 if (list_resize(self, n+1) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000292 return -1;
Raymond Hettinger40a03822004-04-12 13:05:09 +0000293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000294 Py_INCREF(v);
295 PyList_SET_ITEM(self, n, v);
296 return 0;
Raymond Hettinger40a03822004-04-12 13:05:09 +0000297}
298
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000299int
Fred Drakea2f55112000-07-09 15:16:51 +0000300PyList_Append(PyObject *op, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000301{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000302 if (PyList_Check(op) && (newitem != NULL))
303 return app1((PyListObject *)op, newitem);
304 PyErr_BadInternalCall();
305 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000306}
307
308/* Methods */
309
310static void
Fred Drakea2f55112000-07-09 15:16:51 +0000311list_dealloc(PyListObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000312{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000313 Py_ssize_t i;
314 PyObject_GC_UnTrack(op);
315 Py_TRASHCAN_SAFE_BEGIN(op)
316 if (op->ob_item != NULL) {
317 /* Do it backwards, for Christian Tismer.
318 There's a simple test case where somehow this reduces
319 thrashing when a *very* large list is created and
320 immediately deleted. */
321 i = Py_SIZE(op);
322 while (--i >= 0) {
323 Py_XDECREF(op->ob_item[i]);
324 }
325 PyMem_FREE(op->ob_item);
326 }
327 if (numfree < PyList_MAXFREELIST && PyList_CheckExact(op))
328 free_list[numfree++] = op;
329 else
330 Py_TYPE(op)->tp_free((PyObject *)op);
331 Py_TRASHCAN_SAFE_END(op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000332}
333
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000334static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000335list_repr(PyListObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000336{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000337 Py_ssize_t i;
Victor Stinner5c733472013-11-18 21:11:57 +0100338 PyObject *s;
Victor Stinner5c733472013-11-18 21:11:57 +0100339 _PyUnicodeWriter writer;
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200340
341 if (Py_SIZE(v) == 0) {
342 return PyUnicode_FromString("[]");
343 }
344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000345 i = Py_ReprEnter((PyObject*)v);
346 if (i != 0) {
347 return i > 0 ? PyUnicode_FromString("[...]") : NULL;
348 }
Tim Petersa7259592001-06-16 05:11:17 +0000349
Victor Stinner5c733472013-11-18 21:11:57 +0100350 _PyUnicodeWriter_Init(&writer);
351 writer.overallocate = 1;
Victor Stinnerb8fb1972013-11-18 22:15:44 +0100352 /* "[" + "1" + ", 2" * (len - 1) + "]" */
353 writer.min_length = 1 + 1 + (2 + 1) * (Py_SIZE(v) - 1) + 1;
Tim Petersa7259592001-06-16 05:11:17 +0000354
Victor Stinner5c733472013-11-18 21:11:57 +0100355 if (_PyUnicodeWriter_WriteChar(&writer, '[') < 0)
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200356 goto error;
Tim Petersa7259592001-06-16 05:11:17 +0000357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000358 /* Do repr() on each element. Note that this may mutate the list,
359 so must refetch the list size on each iteration. */
360 for (i = 0; i < Py_SIZE(v); ++i) {
Victor Stinner5c733472013-11-18 21:11:57 +0100361 if (i > 0) {
Victor Stinner4a587072013-11-19 12:54:53 +0100362 if (_PyUnicodeWriter_WriteASCIIString(&writer, ", ", 2) < 0)
Victor Stinner5c733472013-11-18 21:11:57 +0100363 goto error;
364 }
365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000366 if (Py_EnterRecursiveCall(" while getting the repr of a list"))
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200367 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000368 s = PyObject_Repr(v->ob_item[i]);
369 Py_LeaveRecursiveCall();
Victor Stinner5c733472013-11-18 21:11:57 +0100370 if (s == NULL)
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200371 goto error;
Victor Stinner5c733472013-11-18 21:11:57 +0100372
373 if (_PyUnicodeWriter_WriteStr(&writer, s) < 0) {
374 Py_DECREF(s);
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200375 goto error;
Victor Stinner5c733472013-11-18 21:11:57 +0100376 }
377 Py_DECREF(s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000378 }
Victor Stinner5c733472013-11-18 21:11:57 +0100379
Victor Stinner4d3f1092013-11-19 12:09:00 +0100380 writer.overallocate = 0;
Victor Stinner5c733472013-11-18 21:11:57 +0100381 if (_PyUnicodeWriter_WriteChar(&writer, ']') < 0)
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200382 goto error;
Tim Petersa7259592001-06-16 05:11:17 +0000383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000384 Py_ReprLeave((PyObject *)v);
Victor Stinner5c733472013-11-18 21:11:57 +0100385 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200386
387error:
Victor Stinner5c733472013-11-18 21:11:57 +0100388 _PyUnicodeWriter_Dealloc(&writer);
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200389 Py_ReprLeave((PyObject *)v);
390 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000391}
392
Martin v. Löwis18e16552006-02-15 17:27:45 +0000393static Py_ssize_t
Fred Drakea2f55112000-07-09 15:16:51 +0000394list_length(PyListObject *a)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000395{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000396 return Py_SIZE(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000397}
398
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000399static int
Fred Drakea2f55112000-07-09 15:16:51 +0000400list_contains(PyListObject *a, PyObject *el)
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000401{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000402 Py_ssize_t i;
403 int cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000405 for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(a); ++i)
406 cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i),
407 Py_EQ);
408 return cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000409}
410
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000411static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000412list_item(PyListObject *a, Py_ssize_t i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000413{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000414 if (i < 0 || i >= Py_SIZE(a)) {
415 if (indexerr == NULL) {
416 indexerr = PyUnicode_FromString(
417 "list index out of range");
418 if (indexerr == NULL)
419 return NULL;
420 }
421 PyErr_SetObject(PyExc_IndexError, indexerr);
422 return NULL;
423 }
424 Py_INCREF(a->ob_item[i]);
425 return a->ob_item[i];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000426}
427
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000428static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000429list_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000430{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 PyListObject *np;
432 PyObject **src, **dest;
433 Py_ssize_t i, len;
434 if (ilow < 0)
435 ilow = 0;
436 else if (ilow > Py_SIZE(a))
437 ilow = Py_SIZE(a);
438 if (ihigh < ilow)
439 ihigh = ilow;
440 else if (ihigh > Py_SIZE(a))
441 ihigh = Py_SIZE(a);
442 len = ihigh - ilow;
443 np = (PyListObject *) PyList_New(len);
444 if (np == NULL)
445 return NULL;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000446
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000447 src = a->ob_item + ilow;
448 dest = np->ob_item;
449 for (i = 0; i < len; i++) {
450 PyObject *v = src[i];
451 Py_INCREF(v);
452 dest[i] = v;
453 }
454 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000455}
456
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000457PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000458PyList_GetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum234f9421993-06-17 12:35:49 +0000459{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 if (!PyList_Check(a)) {
461 PyErr_BadInternalCall();
462 return NULL;
463 }
464 return list_slice((PyListObject *)a, ilow, ihigh);
Guido van Rossum234f9421993-06-17 12:35:49 +0000465}
466
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000467static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000468list_concat(PyListObject *a, PyObject *bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000469{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000470 Py_ssize_t size;
471 Py_ssize_t i;
472 PyObject **src, **dest;
473 PyListObject *np;
474 if (!PyList_Check(bb)) {
475 PyErr_Format(PyExc_TypeError,
476 "can only concatenate list (not \"%.200s\") to list",
477 bb->ob_type->tp_name);
478 return NULL;
479 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000480#define b ((PyListObject *)bb)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000481 size = Py_SIZE(a) + Py_SIZE(b);
482 if (size < 0)
483 return PyErr_NoMemory();
484 np = (PyListObject *) PyList_New(size);
485 if (np == NULL) {
486 return NULL;
487 }
488 src = a->ob_item;
489 dest = np->ob_item;
490 for (i = 0; i < Py_SIZE(a); i++) {
491 PyObject *v = src[i];
492 Py_INCREF(v);
493 dest[i] = v;
494 }
495 src = b->ob_item;
496 dest = np->ob_item + Py_SIZE(a);
497 for (i = 0; i < Py_SIZE(b); i++) {
498 PyObject *v = src[i];
499 Py_INCREF(v);
500 dest[i] = v;
501 }
502 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000503#undef b
504}
505
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000506static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000507list_repeat(PyListObject *a, Py_ssize_t n)
Guido van Rossumed98d481991-03-06 13:07:53 +0000508{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000509 Py_ssize_t i, j;
510 Py_ssize_t size;
511 PyListObject *np;
512 PyObject **p, **items;
513 PyObject *elem;
514 if (n < 0)
515 n = 0;
Mark Dickinsonc0420fd2011-09-19 19:18:37 +0100516 if (n > 0 && Py_SIZE(a) > PY_SSIZE_T_MAX / n)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 return PyErr_NoMemory();
Mark Dickinsonc0420fd2011-09-19 19:18:37 +0100518 size = Py_SIZE(a) * n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 if (size == 0)
520 return PyList_New(0);
521 np = (PyListObject *) PyList_New(size);
522 if (np == NULL)
523 return NULL;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 items = np->ob_item;
526 if (Py_SIZE(a) == 1) {
527 elem = a->ob_item[0];
528 for (i = 0; i < n; i++) {
529 items[i] = elem;
530 Py_INCREF(elem);
531 }
532 return (PyObject *) np;
533 }
534 p = np->ob_item;
535 items = a->ob_item;
536 for (i = 0; i < n; i++) {
537 for (j = 0; j < Py_SIZE(a); j++) {
538 *p = items[j];
539 Py_INCREF(*p);
540 p++;
541 }
542 }
543 return (PyObject *) np;
Guido van Rossumed98d481991-03-06 13:07:53 +0000544}
545
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000546static int
Armin Rigo93677f02004-07-29 12:40:23 +0000547list_clear(PyListObject *a)
548{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000549 Py_ssize_t i;
550 PyObject **item = a->ob_item;
551 if (item != NULL) {
552 /* Because XDECREF can recursively invoke operations on
553 this list, we make it empty first. */
554 i = Py_SIZE(a);
555 Py_SIZE(a) = 0;
556 a->ob_item = NULL;
557 a->allocated = 0;
558 while (--i >= 0) {
559 Py_XDECREF(item[i]);
560 }
561 PyMem_FREE(item);
562 }
563 /* Never fails; the return value can be ignored.
564 Note that there is no guarantee that the list is actually empty
565 at this point, because XDECREF may have populated it again! */
566 return 0;
Armin Rigo93677f02004-07-29 12:40:23 +0000567}
568
Tim Peters8fc4a912004-07-31 21:53:19 +0000569/* a[ilow:ihigh] = v if v != NULL.
570 * del a[ilow:ihigh] if v == NULL.
571 *
572 * Special speed gimmick: when v is NULL and ihigh - ilow <= 8, it's
573 * guaranteed the call cannot fail.
574 */
Armin Rigo93677f02004-07-29 12:40:23 +0000575static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000576list_ass_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000577{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000578 /* Because [X]DECREF can recursively invoke list operations on
579 this list, we must postpone all [X]DECREF activity until
580 after the list is back in its canonical shape. Therefore
581 we must allocate an additional array, 'recycle', into which
582 we temporarily copy the items that are deleted from the
583 list. :-( */
584 PyObject *recycle_on_stack[8];
585 PyObject **recycle = recycle_on_stack; /* will allocate more if needed */
586 PyObject **item;
587 PyObject **vitem = NULL;
588 PyObject *v_as_SF = NULL; /* PySequence_Fast(v) */
589 Py_ssize_t n; /* # of elements in replacement list */
590 Py_ssize_t norig; /* # of elements in list getting replaced */
591 Py_ssize_t d; /* Change in size */
592 Py_ssize_t k;
593 size_t s;
594 int result = -1; /* guilty until proved innocent */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000595#define b ((PyListObject *)v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 if (v == NULL)
597 n = 0;
598 else {
599 if (a == b) {
600 /* Special case "a[i:j] = a" -- copy b first */
601 v = list_slice(b, 0, Py_SIZE(b));
602 if (v == NULL)
603 return result;
604 result = list_ass_slice(a, ilow, ihigh, v);
605 Py_DECREF(v);
606 return result;
607 }
608 v_as_SF = PySequence_Fast(v, "can only assign an iterable");
609 if(v_as_SF == NULL)
610 goto Error;
611 n = PySequence_Fast_GET_SIZE(v_as_SF);
612 vitem = PySequence_Fast_ITEMS(v_as_SF);
613 }
614 if (ilow < 0)
615 ilow = 0;
616 else if (ilow > Py_SIZE(a))
617 ilow = Py_SIZE(a);
Tim Peters8d9eb102004-07-31 02:24:20 +0000618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 if (ihigh < ilow)
620 ihigh = ilow;
621 else if (ihigh > Py_SIZE(a))
622 ihigh = Py_SIZE(a);
Armin Rigo93677f02004-07-29 12:40:23 +0000623
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000624 norig = ihigh - ilow;
625 assert(norig >= 0);
626 d = n - norig;
627 if (Py_SIZE(a) + d == 0) {
628 Py_XDECREF(v_as_SF);
629 return list_clear(a);
630 }
631 item = a->ob_item;
632 /* recycle the items that we are about to remove */
633 s = norig * sizeof(PyObject *);
634 if (s > sizeof(recycle_on_stack)) {
635 recycle = (PyObject **)PyMem_MALLOC(s);
636 if (recycle == NULL) {
637 PyErr_NoMemory();
638 goto Error;
639 }
640 }
641 memcpy(recycle, &item[ilow], s);
Tim Peters8d9eb102004-07-31 02:24:20 +0000642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000643 if (d < 0) { /* Delete -d items */
Victor Stinner2c40f642013-07-19 23:06:21 +0200644 Py_ssize_t tail;
645 tail = (Py_SIZE(a) - ihigh) * sizeof(PyObject *);
646 memmove(&item[ihigh+d], &item[ihigh], tail);
647 if (list_resize(a, Py_SIZE(a) + d) < 0) {
648 memmove(&item[ihigh], &item[ihigh+d], tail);
649 memcpy(&item[ilow], recycle, s);
650 goto Error;
651 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000652 item = a->ob_item;
653 }
654 else if (d > 0) { /* Insert d items */
655 k = Py_SIZE(a);
656 if (list_resize(a, k+d) < 0)
657 goto Error;
658 item = a->ob_item;
659 memmove(&item[ihigh+d], &item[ihigh],
660 (k - ihigh)*sizeof(PyObject *));
661 }
662 for (k = 0; k < n; k++, ilow++) {
663 PyObject *w = vitem[k];
664 Py_XINCREF(w);
665 item[ilow] = w;
666 }
667 for (k = norig - 1; k >= 0; --k)
668 Py_XDECREF(recycle[k]);
669 result = 0;
Tim Peters8d9eb102004-07-31 02:24:20 +0000670 Error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000671 if (recycle != recycle_on_stack)
672 PyMem_FREE(recycle);
673 Py_XDECREF(v_as_SF);
674 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000675#undef b
676}
677
Guido van Rossum234f9421993-06-17 12:35:49 +0000678int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000679PyList_SetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum234f9421993-06-17 12:35:49 +0000680{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000681 if (!PyList_Check(a)) {
682 PyErr_BadInternalCall();
683 return -1;
684 }
685 return list_ass_slice((PyListObject *)a, ilow, ihigh, v);
Guido van Rossum234f9421993-06-17 12:35:49 +0000686}
687
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000688static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000689list_inplace_repeat(PyListObject *self, Py_ssize_t n)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000690{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000691 PyObject **items;
692 Py_ssize_t size, i, j, p;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000693
694
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000695 size = PyList_GET_SIZE(self);
696 if (size == 0 || n == 1) {
697 Py_INCREF(self);
698 return (PyObject *)self;
699 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000701 if (n < 1) {
702 (void)list_clear(self);
703 Py_INCREF(self);
704 return (PyObject *)self;
705 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000707 if (size > PY_SSIZE_T_MAX / n) {
708 return PyErr_NoMemory();
709 }
Christian Heimesaf98da12008-01-27 15:18:18 +0000710
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800711 if (list_resize(self, size*n) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000712 return NULL;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 p = size;
715 items = self->ob_item;
716 for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */
717 for (j = 0; j < size; j++) {
718 PyObject *o = items[j];
719 Py_INCREF(o);
720 items[p++] = o;
721 }
722 }
723 Py_INCREF(self);
724 return (PyObject *)self;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000725}
726
Guido van Rossum4a450d01991-04-03 19:05:18 +0000727static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000728list_ass_item(PyListObject *a, Py_ssize_t i, PyObject *v)
Guido van Rossum4a450d01991-04-03 19:05:18 +0000729{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000730 if (i < 0 || i >= Py_SIZE(a)) {
731 PyErr_SetString(PyExc_IndexError,
732 "list assignment index out of range");
733 return -1;
734 }
735 if (v == NULL)
736 return list_ass_slice(a, i, i+1, v);
737 Py_INCREF(v);
Serhiy Storchakaec397562016-04-06 09:50:03 +0300738 Py_XSETREF(a->ob_item[i], v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 return 0;
Guido van Rossum4a450d01991-04-03 19:05:18 +0000740}
741
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000742static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000743listinsert(PyListObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000744{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000745 Py_ssize_t i;
746 PyObject *v;
747 if (!PyArg_ParseTuple(args, "nO:insert", &i, &v))
748 return NULL;
749 if (ins1(self, i, v) == 0)
750 Py_RETURN_NONE;
751 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000752}
753
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000754static PyObject *
Eli Benderskycbbaa962011-02-25 05:47:53 +0000755listclear(PyListObject *self)
756{
757 list_clear(self);
758 Py_RETURN_NONE;
759}
760
761static PyObject *
762listcopy(PyListObject *self)
763{
764 return list_slice(self, 0, Py_SIZE(self));
765}
766
767static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000768listappend(PyListObject *self, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000769{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000770 if (app1(self, v) == 0)
771 Py_RETURN_NONE;
772 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000773}
774
Barry Warsawdedf6d61998-10-09 16:37:25 +0000775static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000776listextend(PyListObject *self, PyObject *b)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000777{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 PyObject *it; /* iter(v) */
779 Py_ssize_t m; /* size of self */
780 Py_ssize_t n; /* guess for size of b */
781 Py_ssize_t mn; /* m + n */
782 Py_ssize_t i;
783 PyObject *(*iternext)(PyObject *);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000785 /* Special cases:
786 1) lists and tuples which can use PySequence_Fast ops
787 2) extending self to self requires making a copy first
788 */
789 if (PyList_CheckExact(b) || PyTuple_CheckExact(b) || (PyObject *)self == b) {
790 PyObject **src, **dest;
791 b = PySequence_Fast(b, "argument must be iterable");
792 if (!b)
793 return NULL;
794 n = PySequence_Fast_GET_SIZE(b);
795 if (n == 0) {
796 /* short circuit when b is empty */
797 Py_DECREF(b);
798 Py_RETURN_NONE;
799 }
800 m = Py_SIZE(self);
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800801 if (list_resize(self, m + n) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000802 Py_DECREF(b);
803 return NULL;
804 }
805 /* note that we may still have self == b here for the
806 * situation a.extend(a), but the following code works
807 * in that case too. Just make sure to resize self
808 * before calling PySequence_Fast_ITEMS.
809 */
810 /* populate the end of self with b's items */
811 src = PySequence_Fast_ITEMS(b);
812 dest = self->ob_item + m;
813 for (i = 0; i < n; i++) {
814 PyObject *o = src[i];
815 Py_INCREF(o);
816 dest[i] = o;
817 }
818 Py_DECREF(b);
819 Py_RETURN_NONE;
820 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000821
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000822 it = PyObject_GetIter(b);
823 if (it == NULL)
824 return NULL;
825 iternext = *it->ob_type->tp_iternext;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000826
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000827 /* Guess a result list size. */
Armin Ronacheraa9a79d2012-10-06 14:03:24 +0200828 n = PyObject_LengthHint(b, 8);
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800829 if (n < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 Py_DECREF(it);
831 return NULL;
832 }
833 m = Py_SIZE(self);
834 mn = m + n;
835 if (mn >= m) {
836 /* Make room. */
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800837 if (list_resize(self, mn) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 goto error;
839 /* Make the list sane again. */
840 Py_SIZE(self) = m;
841 }
842 /* Else m + n overflowed; on the chance that n lied, and there really
843 * is enough room, ignore it. If n was telling the truth, we'll
844 * eventually run out of memory during the loop.
845 */
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000846
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000847 /* Run iterator to exhaustion. */
848 for (;;) {
849 PyObject *item = iternext(it);
850 if (item == NULL) {
851 if (PyErr_Occurred()) {
852 if (PyErr_ExceptionMatches(PyExc_StopIteration))
853 PyErr_Clear();
854 else
855 goto error;
856 }
857 break;
858 }
859 if (Py_SIZE(self) < self->allocated) {
860 /* steals ref */
861 PyList_SET_ITEM(self, Py_SIZE(self), item);
862 ++Py_SIZE(self);
863 }
864 else {
865 int status = app1(self, item);
866 Py_DECREF(item); /* append creates a new ref */
867 if (status < 0)
868 goto error;
869 }
870 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000871
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000872 /* Cut back result list if initial guess was too large. */
Victor Stinner32fd6ea2013-07-16 21:45:58 +0200873 if (Py_SIZE(self) < self->allocated) {
874 if (list_resize(self, Py_SIZE(self)) < 0)
875 goto error;
876 }
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000878 Py_DECREF(it);
879 Py_RETURN_NONE;
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000880
881 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 Py_DECREF(it);
883 return NULL;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000884}
885
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000886PyObject *
887_PyList_Extend(PyListObject *self, PyObject *b)
888{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 return listextend(self, b);
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000890}
891
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000892static PyObject *
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000893list_inplace_concat(PyListObject *self, PyObject *other)
894{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000895 PyObject *result;
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000897 result = listextend(self, other);
898 if (result == NULL)
899 return result;
900 Py_DECREF(result);
901 Py_INCREF(self);
902 return (PyObject *)self;
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000903}
904
905static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000906listpop(PyListObject *self, PyObject *args)
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000907{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000908 Py_ssize_t i = -1;
909 PyObject *v;
910 int status;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000911
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000912 if (!PyArg_ParseTuple(args, "|n:pop", &i))
913 return NULL;
Thomas Wouters89f507f2006-12-13 04:49:30 +0000914
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000915 if (Py_SIZE(self) == 0) {
916 /* Special-case most common failure cause */
917 PyErr_SetString(PyExc_IndexError, "pop from empty list");
918 return NULL;
919 }
920 if (i < 0)
921 i += Py_SIZE(self);
922 if (i < 0 || i >= Py_SIZE(self)) {
923 PyErr_SetString(PyExc_IndexError, "pop index out of range");
924 return NULL;
925 }
926 v = self->ob_item[i];
927 if (i == Py_SIZE(self) - 1) {
928 status = list_resize(self, Py_SIZE(self) - 1);
Victor Stinnerb27cd3e2013-07-08 22:20:44 +0200929 if (status >= 0)
930 return v; /* and v now owns the reference the list had */
931 else
932 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933 }
934 Py_INCREF(v);
935 status = list_ass_slice(self, i, i+1, (PyObject *)NULL);
Victor Stinner095d99f2013-07-17 21:58:01 +0200936 if (status < 0) {
937 Py_DECREF(v);
938 return NULL;
939 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 return v;
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000941}
942
Tim Peters8e2e7ca2002-07-19 02:33:08 +0000943/* Reverse a slice of a list in place, from lo up to (exclusive) hi. */
944static void
945reverse_slice(PyObject **lo, PyObject **hi)
946{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 assert(lo && hi);
Tim Peters8e2e7ca2002-07-19 02:33:08 +0000948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 --hi;
950 while (lo < hi) {
951 PyObject *t = *lo;
952 *lo = *hi;
953 *hi = t;
954 ++lo;
955 --hi;
956 }
Tim Peters8e2e7ca2002-07-19 02:33:08 +0000957}
958
Tim Petersa64dc242002-08-01 02:13:36 +0000959/* Lots of code for an adaptive, stable, natural mergesort. There are many
960 * pieces to this algorithm; read listsort.txt for overviews and details.
961 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000962
Daniel Stutzbach98338222010-12-02 21:55:33 +0000963/* A sortslice contains a pointer to an array of keys and a pointer to
964 * an array of corresponding values. In other words, keys[i]
965 * corresponds with values[i]. If values == NULL, then the keys are
966 * also the values.
967 *
968 * Several convenience routines are provided here, so that keys and
969 * values are always moved in sync.
970 */
971
972typedef struct {
973 PyObject **keys;
974 PyObject **values;
975} sortslice;
976
977Py_LOCAL_INLINE(void)
978sortslice_copy(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j)
979{
980 s1->keys[i] = s2->keys[j];
981 if (s1->values != NULL)
982 s1->values[i] = s2->values[j];
983}
984
985Py_LOCAL_INLINE(void)
Benjamin Peterson9efdcca2010-12-03 01:44:10 +0000986sortslice_copy_incr(sortslice *dst, sortslice *src)
987{
Daniel Stutzbach98338222010-12-02 21:55:33 +0000988 *dst->keys++ = *src->keys++;
989 if (dst->values != NULL)
990 *dst->values++ = *src->values++;
991}
992
993Py_LOCAL_INLINE(void)
Benjamin Peterson9efdcca2010-12-03 01:44:10 +0000994sortslice_copy_decr(sortslice *dst, sortslice *src)
995{
Daniel Stutzbach98338222010-12-02 21:55:33 +0000996 *dst->keys-- = *src->keys--;
997 if (dst->values != NULL)
998 *dst->values-- = *src->values--;
999}
1000
1001
1002Py_LOCAL_INLINE(void)
1003sortslice_memcpy(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j,
Benjamin Peterson9efdcca2010-12-03 01:44:10 +00001004 Py_ssize_t n)
1005{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001006 memcpy(&s1->keys[i], &s2->keys[j], sizeof(PyObject *) * n);
1007 if (s1->values != NULL)
1008 memcpy(&s1->values[i], &s2->values[j], sizeof(PyObject *) * n);
1009}
1010
1011Py_LOCAL_INLINE(void)
1012sortslice_memmove(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j,
Benjamin Peterson9efdcca2010-12-03 01:44:10 +00001013 Py_ssize_t n)
1014{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001015 memmove(&s1->keys[i], &s2->keys[j], sizeof(PyObject *) * n);
1016 if (s1->values != NULL)
1017 memmove(&s1->values[i], &s2->values[j], sizeof(PyObject *) * n);
1018}
1019
1020Py_LOCAL_INLINE(void)
Benjamin Peterson9efdcca2010-12-03 01:44:10 +00001021sortslice_advance(sortslice *slice, Py_ssize_t n)
1022{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001023 slice->keys += n;
1024 if (slice->values != NULL)
1025 slice->values += n;
1026}
1027
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001028/* Comparison function: PyObject_RichCompareBool with Py_LT.
Tim Petersa64dc242002-08-01 02:13:36 +00001029 * Returns -1 on error, 1 if x < y, 0 if x >= y.
1030 */
Guido van Rossum3f236de1996-12-10 23:55:39 +00001031
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001032#define ISLT(X, Y) (PyObject_RichCompareBool(X, Y, Py_LT))
Tim Peters66860f62002-08-04 17:47:26 +00001033
1034/* Compare X to Y via "<". Goto "fail" if the comparison raises an
Tim Petersa8c974c2002-07-19 03:30:57 +00001035 error. Else "k" is set to true iff X<Y, and an "if (k)" block is
1036 started. It makes more sense in context <wink>. X and Y are PyObject*s.
1037*/
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001038#define IFLT(X, Y) if ((k = ISLT(X, Y)) < 0) goto fail; \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039 if (k)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001040
1041/* binarysort is the best method for sorting small arrays: it does
1042 few compares, but can do data movement quadratic in the number of
1043 elements.
Guido van Rossum42812581998-06-17 14:15:44 +00001044 [lo, hi) is a contiguous slice of a list, and is sorted via
Tim Petersa8c974c2002-07-19 03:30:57 +00001045 binary insertion. This sort is stable.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001046 On entry, must have lo <= start <= hi, and that [lo, start) is already
1047 sorted (pass start == lo if you don't know!).
Tim Petersa8c974c2002-07-19 03:30:57 +00001048 If islt() complains return -1, else 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001049 Even in case of error, the output slice will be some permutation of
1050 the input (nothing is lost or duplicated).
1051*/
Guido van Rossum3f236de1996-12-10 23:55:39 +00001052static int
Daniel Stutzbach98338222010-12-02 21:55:33 +00001053binarysort(sortslice lo, PyObject **hi, PyObject **start)
Guido van Rossum3f236de1996-12-10 23:55:39 +00001054{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001055 Py_ssize_t k;
1056 PyObject **l, **p, **r;
1057 PyObject *pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001058
Daniel Stutzbach98338222010-12-02 21:55:33 +00001059 assert(lo.keys <= start && start <= hi);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001060 /* assert [lo, start) is sorted */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001061 if (lo.keys == start)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001062 ++start;
1063 for (; start < hi; ++start) {
1064 /* set l to where *start belongs */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001065 l = lo.keys;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001066 r = start;
1067 pivot = *r;
1068 /* Invariants:
1069 * pivot >= all in [lo, l).
1070 * pivot < all in [r, start).
1071 * The second is vacuously true at the start.
1072 */
1073 assert(l < r);
1074 do {
1075 p = l + ((r - l) >> 1);
1076 IFLT(pivot, *p)
1077 r = p;
1078 else
1079 l = p+1;
1080 } while (l < r);
1081 assert(l == r);
1082 /* The invariants still hold, so pivot >= all in [lo, l) and
1083 pivot < all in [l, start), so pivot belongs at l. Note
1084 that if there are elements equal to pivot, l points to the
1085 first slot after them -- that's why this sort is stable.
1086 Slide over to make room.
1087 Caution: using memmove is much slower under MSVC 5;
1088 we're not usually moving many slots. */
1089 for (p = start; p > l; --p)
1090 *p = *(p-1);
1091 *l = pivot;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001092 if (lo.values != NULL) {
1093 Py_ssize_t offset = lo.values - lo.keys;
1094 p = start + offset;
1095 pivot = *p;
1096 l += offset;
1097 for (p = start + offset; p > l; --p)
1098 *p = *(p-1);
1099 *l = pivot;
1100 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001101 }
1102 return 0;
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001103
1104 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001105 return -1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001106}
1107
Tim Petersa64dc242002-08-01 02:13:36 +00001108/*
1109Return the length of the run beginning at lo, in the slice [lo, hi). lo < hi
1110is required on entry. "A run" is the longest ascending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001111
Tim Petersa64dc242002-08-01 02:13:36 +00001112 lo[0] <= lo[1] <= lo[2] <= ...
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001113
Tim Petersa64dc242002-08-01 02:13:36 +00001114or the longest descending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001115
Tim Petersa64dc242002-08-01 02:13:36 +00001116 lo[0] > lo[1] > lo[2] > ...
Tim Peters3b01a122002-07-19 02:35:45 +00001117
Tim Petersa64dc242002-08-01 02:13:36 +00001118Boolean *descending is set to 0 in the former case, or to 1 in the latter.
1119For its intended use in a stable mergesort, the strictness of the defn of
1120"descending" is needed so that the caller can safely reverse a descending
1121sequence without violating stability (strict > ensures there are no equal
1122elements to get out of order).
1123
1124Returns -1 in case of error.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001125*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001126static Py_ssize_t
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001127count_run(PyObject **lo, PyObject **hi, int *descending)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001128{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001129 Py_ssize_t k;
1130 Py_ssize_t n;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001132 assert(lo < hi);
1133 *descending = 0;
1134 ++lo;
1135 if (lo == hi)
1136 return 1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001137
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001138 n = 2;
1139 IFLT(*lo, *(lo-1)) {
1140 *descending = 1;
1141 for (lo = lo+1; lo < hi; ++lo, ++n) {
1142 IFLT(*lo, *(lo-1))
1143 ;
1144 else
1145 break;
1146 }
1147 }
1148 else {
1149 for (lo = lo+1; lo < hi; ++lo, ++n) {
1150 IFLT(*lo, *(lo-1))
1151 break;
1152 }
1153 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001154
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001155 return n;
Tim Petersa64dc242002-08-01 02:13:36 +00001156fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001157 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001158}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001159
Tim Petersa64dc242002-08-01 02:13:36 +00001160/*
1161Locate the proper position of key in a sorted vector; if the vector contains
1162an element equal to key, return the position immediately to the left of
1163the leftmost equal element. [gallop_right() does the same except returns
1164the position to the right of the rightmost equal element (if any).]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001165
Tim Petersa64dc242002-08-01 02:13:36 +00001166"a" is a sorted vector with n elements, starting at a[0]. n must be > 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001167
Tim Petersa64dc242002-08-01 02:13:36 +00001168"hint" is an index at which to begin the search, 0 <= hint < n. The closer
1169hint is to the final result, the faster this runs.
1170
1171The return value is the int k in 0..n such that
1172
1173 a[k-1] < key <= a[k]
1174
1175pretending that *(a-1) is minus infinity and a[n] is plus infinity. IOW,
1176key belongs at index k; or, IOW, the first k elements of a should precede
1177key, and the last n-k should follow key.
1178
1179Returns -1 on error. See listsort.txt for info on the method.
1180*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001181static Py_ssize_t
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001182gallop_left(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint)
Tim Petersa64dc242002-08-01 02:13:36 +00001183{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001184 Py_ssize_t ofs;
1185 Py_ssize_t lastofs;
1186 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 assert(key && a && n > 0 && hint >= 0 && hint < n);
Tim Petersa64dc242002-08-01 02:13:36 +00001189
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001190 a += hint;
1191 lastofs = 0;
1192 ofs = 1;
1193 IFLT(*a, key) {
1194 /* a[hint] < key -- gallop right, until
1195 * a[hint + lastofs] < key <= a[hint + ofs]
1196 */
1197 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
1198 while (ofs < maxofs) {
1199 IFLT(a[ofs], key) {
1200 lastofs = ofs;
1201 ofs = (ofs << 1) + 1;
1202 if (ofs <= 0) /* int overflow */
1203 ofs = maxofs;
1204 }
1205 else /* key <= a[hint + ofs] */
1206 break;
1207 }
1208 if (ofs > maxofs)
1209 ofs = maxofs;
1210 /* Translate back to offsets relative to &a[0]. */
1211 lastofs += hint;
1212 ofs += hint;
1213 }
1214 else {
1215 /* key <= a[hint] -- gallop left, until
1216 * a[hint - ofs] < key <= a[hint - lastofs]
1217 */
1218 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
1219 while (ofs < maxofs) {
1220 IFLT(*(a-ofs), key)
1221 break;
1222 /* key <= a[hint - ofs] */
1223 lastofs = ofs;
1224 ofs = (ofs << 1) + 1;
1225 if (ofs <= 0) /* int overflow */
1226 ofs = maxofs;
1227 }
1228 if (ofs > maxofs)
1229 ofs = maxofs;
1230 /* Translate back to positive offsets relative to &a[0]. */
1231 k = lastofs;
1232 lastofs = hint - ofs;
1233 ofs = hint - k;
1234 }
1235 a -= hint;
Tim Petersa64dc242002-08-01 02:13:36 +00001236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001237 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1238 /* Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the
1239 * right of lastofs but no farther right than ofs. Do a binary
1240 * search, with invariant a[lastofs-1] < key <= a[ofs].
1241 */
1242 ++lastofs;
1243 while (lastofs < ofs) {
1244 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001245
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001246 IFLT(a[m], key)
1247 lastofs = m+1; /* a[m] < key */
1248 else
1249 ofs = m; /* key <= a[m] */
1250 }
1251 assert(lastofs == ofs); /* so a[ofs-1] < key <= a[ofs] */
1252 return ofs;
Tim Petersa64dc242002-08-01 02:13:36 +00001253
1254fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001255 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001256}
1257
1258/*
1259Exactly like gallop_left(), except that if key already exists in a[0:n],
1260finds the position immediately to the right of the rightmost equal value.
1261
1262The return value is the int k in 0..n such that
1263
1264 a[k-1] <= key < a[k]
1265
1266or -1 if error.
1267
1268The code duplication is massive, but this is enough different given that
1269we're sticking to "<" comparisons that it's much harder to follow if
1270written as one routine with yet another "left or right?" flag.
1271*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001272static Py_ssize_t
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001273gallop_right(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint)
Tim Petersa64dc242002-08-01 02:13:36 +00001274{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001275 Py_ssize_t ofs;
1276 Py_ssize_t lastofs;
1277 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001279 assert(key && a && n > 0 && hint >= 0 && hint < n);
Tim Petersa64dc242002-08-01 02:13:36 +00001280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001281 a += hint;
1282 lastofs = 0;
1283 ofs = 1;
1284 IFLT(key, *a) {
1285 /* key < a[hint] -- gallop left, until
1286 * a[hint - ofs] <= key < a[hint - lastofs]
1287 */
1288 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
1289 while (ofs < maxofs) {
1290 IFLT(key, *(a-ofs)) {
1291 lastofs = ofs;
1292 ofs = (ofs << 1) + 1;
1293 if (ofs <= 0) /* int overflow */
1294 ofs = maxofs;
1295 }
1296 else /* a[hint - ofs] <= key */
1297 break;
1298 }
1299 if (ofs > maxofs)
1300 ofs = maxofs;
1301 /* Translate back to positive offsets relative to &a[0]. */
1302 k = lastofs;
1303 lastofs = hint - ofs;
1304 ofs = hint - k;
1305 }
1306 else {
1307 /* a[hint] <= key -- gallop right, until
1308 * a[hint + lastofs] <= key < a[hint + ofs]
1309 */
1310 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
1311 while (ofs < maxofs) {
1312 IFLT(key, a[ofs])
1313 break;
1314 /* a[hint + ofs] <= key */
1315 lastofs = ofs;
1316 ofs = (ofs << 1) + 1;
1317 if (ofs <= 0) /* int overflow */
1318 ofs = maxofs;
1319 }
1320 if (ofs > maxofs)
1321 ofs = maxofs;
1322 /* Translate back to offsets relative to &a[0]. */
1323 lastofs += hint;
1324 ofs += hint;
1325 }
1326 a -= hint;
Tim Petersa64dc242002-08-01 02:13:36 +00001327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001328 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1329 /* Now a[lastofs] <= key < a[ofs], so key belongs somewhere to the
1330 * right of lastofs but no farther right than ofs. Do a binary
1331 * search, with invariant a[lastofs-1] <= key < a[ofs].
1332 */
1333 ++lastofs;
1334 while (lastofs < ofs) {
1335 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001337 IFLT(key, a[m])
1338 ofs = m; /* key < a[m] */
1339 else
1340 lastofs = m+1; /* a[m] <= key */
1341 }
1342 assert(lastofs == ofs); /* so a[ofs-1] <= key < a[ofs] */
1343 return ofs;
Tim Petersa64dc242002-08-01 02:13:36 +00001344
1345fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001346 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001347}
1348
1349/* The maximum number of entries in a MergeState's pending-runs stack.
1350 * This is enough to sort arrays of size up to about
1351 * 32 * phi ** MAX_MERGE_PENDING
1352 * where phi ~= 1.618. 85 is ridiculouslylarge enough, good for an array
1353 * with 2**64 elements.
1354 */
1355#define MAX_MERGE_PENDING 85
1356
Tim Peterse05f65a2002-08-10 05:21:15 +00001357/* When we get into galloping mode, we stay there until both runs win less
1358 * often than MIN_GALLOP consecutive times. See listsort.txt for more info.
Tim Petersa64dc242002-08-01 02:13:36 +00001359 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001360#define MIN_GALLOP 7
Tim Petersa64dc242002-08-01 02:13:36 +00001361
1362/* Avoid malloc for small temp arrays. */
1363#define MERGESTATE_TEMP_SIZE 256
1364
1365/* One MergeState exists on the stack per invocation of mergesort. It's just
1366 * a convenient way to pass state around among the helper functions.
1367 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001368struct s_slice {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001369 sortslice base;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001370 Py_ssize_t len;
Tim Peterse05f65a2002-08-10 05:21:15 +00001371};
1372
Tim Petersa64dc242002-08-01 02:13:36 +00001373typedef struct s_MergeState {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001374 /* This controls when we get *into* galloping mode. It's initialized
1375 * to MIN_GALLOP. merge_lo and merge_hi tend to nudge it higher for
1376 * random data, and lower for highly structured data.
1377 */
1378 Py_ssize_t min_gallop;
Tim Peterse05f65a2002-08-10 05:21:15 +00001379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001380 /* 'a' is temp storage to help with merges. It contains room for
1381 * alloced entries.
1382 */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001383 sortslice a; /* may point to temparray below */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001384 Py_ssize_t alloced;
Tim Petersa64dc242002-08-01 02:13:36 +00001385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001386 /* A stack of n pending runs yet to be merged. Run #i starts at
1387 * address base[i] and extends for len[i] elements. It's always
1388 * true (so long as the indices are in bounds) that
1389 *
1390 * pending[i].base + pending[i].len == pending[i+1].base
1391 *
1392 * so we could cut the storage for this, but it's a minor amount,
1393 * and keeping all the info explicit simplifies the code.
1394 */
1395 int n;
1396 struct s_slice pending[MAX_MERGE_PENDING];
Tim Petersa64dc242002-08-01 02:13:36 +00001397
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001398 /* 'a' points to this when possible, rather than muck with malloc. */
1399 PyObject *temparray[MERGESTATE_TEMP_SIZE];
Tim Petersa64dc242002-08-01 02:13:36 +00001400} MergeState;
1401
1402/* Conceptually a MergeState's constructor. */
1403static void
Victor Stinner0fcab4a2011-01-04 12:59:15 +00001404merge_init(MergeState *ms, Py_ssize_t list_size, int has_keyfunc)
Tim Petersa64dc242002-08-01 02:13:36 +00001405{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001406 assert(ms != NULL);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001407 if (has_keyfunc) {
1408 /* The temporary space for merging will need at most half the list
1409 * size rounded up. Use the minimum possible space so we can use the
1410 * rest of temparray for other things. In particular, if there is
1411 * enough extra space, listsort() will use it to store the keys.
1412 */
1413 ms->alloced = (list_size + 1) / 2;
1414
1415 /* ms->alloced describes how many keys will be stored at
1416 ms->temparray, but we also need to store the values. Hence,
1417 ms->alloced is capped at half of MERGESTATE_TEMP_SIZE. */
1418 if (MERGESTATE_TEMP_SIZE / 2 < ms->alloced)
1419 ms->alloced = MERGESTATE_TEMP_SIZE / 2;
1420 ms->a.values = &ms->temparray[ms->alloced];
1421 }
1422 else {
1423 ms->alloced = MERGESTATE_TEMP_SIZE;
1424 ms->a.values = NULL;
1425 }
1426 ms->a.keys = ms->temparray;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001427 ms->n = 0;
1428 ms->min_gallop = MIN_GALLOP;
Tim Petersa64dc242002-08-01 02:13:36 +00001429}
1430
1431/* Free all the temp memory owned by the MergeState. This must be called
1432 * when you're done with a MergeState, and may be called before then if
1433 * you want to free the temp memory early.
1434 */
1435static void
1436merge_freemem(MergeState *ms)
1437{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001438 assert(ms != NULL);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001439 if (ms->a.keys != ms->temparray)
1440 PyMem_Free(ms->a.keys);
Tim Petersa64dc242002-08-01 02:13:36 +00001441}
1442
1443/* Ensure enough temp memory for 'need' array slots is available.
1444 * Returns 0 on success and -1 if the memory can't be gotten.
1445 */
1446static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001447merge_getmem(MergeState *ms, Py_ssize_t need)
Tim Petersa64dc242002-08-01 02:13:36 +00001448{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001449 int multiplier;
1450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001451 assert(ms != NULL);
1452 if (need <= ms->alloced)
1453 return 0;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001454
1455 multiplier = ms->a.values != NULL ? 2 : 1;
1456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001457 /* Don't realloc! That can cost cycles to copy the old data, but
1458 * we don't care what's in the block.
1459 */
1460 merge_freemem(ms);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001461 if ((size_t)need > PY_SSIZE_T_MAX / sizeof(PyObject*) / multiplier) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001462 PyErr_NoMemory();
1463 return -1;
1464 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001465 ms->a.keys = (PyObject**)PyMem_Malloc(multiplier * need
1466 * sizeof(PyObject *));
1467 if (ms->a.keys != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001468 ms->alloced = need;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001469 if (ms->a.values != NULL)
1470 ms->a.values = &ms->a.keys[need];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001471 return 0;
1472 }
1473 PyErr_NoMemory();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001474 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001475}
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001476#define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 : \
1477 merge_getmem(MS, NEED))
Tim Petersa64dc242002-08-01 02:13:36 +00001478
Daniel Stutzbach98338222010-12-02 21:55:33 +00001479/* Merge the na elements starting at ssa with the nb elements starting at
1480 * ssb.keys = ssa.keys + na in a stable way, in-place. na and nb must be > 0.
1481 * Must also have that ssa.keys[na-1] belongs at the end of the merge, and
1482 * should have na <= nb. See listsort.txt for more info. Return 0 if
1483 * successful, -1 if error.
Tim Petersa64dc242002-08-01 02:13:36 +00001484 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001485static Py_ssize_t
Daniel Stutzbach98338222010-12-02 21:55:33 +00001486merge_lo(MergeState *ms, sortslice ssa, Py_ssize_t na,
1487 sortslice ssb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001488{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001489 Py_ssize_t k;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001490 sortslice dest;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001491 int result = -1; /* guilty until proved innocent */
1492 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001493
Daniel Stutzbach98338222010-12-02 21:55:33 +00001494 assert(ms && ssa.keys && ssb.keys && na > 0 && nb > 0);
1495 assert(ssa.keys + na == ssb.keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001496 if (MERGE_GETMEM(ms, na) < 0)
1497 return -1;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001498 sortslice_memcpy(&ms->a, 0, &ssa, 0, na);
1499 dest = ssa;
1500 ssa = ms->a;
Tim Petersa64dc242002-08-01 02:13:36 +00001501
Daniel Stutzbach98338222010-12-02 21:55:33 +00001502 sortslice_copy_incr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001503 --nb;
1504 if (nb == 0)
1505 goto Succeed;
1506 if (na == 1)
1507 goto CopyB;
Tim Petersa64dc242002-08-01 02:13:36 +00001508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001509 min_gallop = ms->min_gallop;
1510 for (;;) {
1511 Py_ssize_t acount = 0; /* # of times A won in a row */
1512 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001514 /* Do the straightforward thing until (if ever) one run
1515 * appears to win consistently.
1516 */
1517 for (;;) {
1518 assert(na > 1 && nb > 0);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001519 k = ISLT(ssb.keys[0], ssa.keys[0]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001520 if (k) {
1521 if (k < 0)
1522 goto Fail;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001523 sortslice_copy_incr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001524 ++bcount;
1525 acount = 0;
1526 --nb;
1527 if (nb == 0)
1528 goto Succeed;
1529 if (bcount >= min_gallop)
1530 break;
1531 }
1532 else {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001533 sortslice_copy_incr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001534 ++acount;
1535 bcount = 0;
1536 --na;
1537 if (na == 1)
1538 goto CopyB;
1539 if (acount >= min_gallop)
1540 break;
1541 }
1542 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001543
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001544 /* One run is winning so consistently that galloping may
1545 * be a huge win. So try that, and continue galloping until
1546 * (if ever) neither run appears to be winning consistently
1547 * anymore.
1548 */
1549 ++min_gallop;
1550 do {
1551 assert(na > 1 && nb > 0);
1552 min_gallop -= min_gallop > 1;
1553 ms->min_gallop = min_gallop;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001554 k = gallop_right(ssb.keys[0], ssa.keys, na, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001555 acount = k;
1556 if (k) {
1557 if (k < 0)
1558 goto Fail;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001559 sortslice_memcpy(&dest, 0, &ssa, 0, k);
1560 sortslice_advance(&dest, k);
1561 sortslice_advance(&ssa, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001562 na -= k;
1563 if (na == 1)
1564 goto CopyB;
1565 /* na==0 is impossible now if the comparison
1566 * function is consistent, but we can't assume
1567 * that it is.
1568 */
1569 if (na == 0)
1570 goto Succeed;
1571 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001572 sortslice_copy_incr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001573 --nb;
1574 if (nb == 0)
1575 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001576
Daniel Stutzbach98338222010-12-02 21:55:33 +00001577 k = gallop_left(ssa.keys[0], ssb.keys, nb, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001578 bcount = k;
1579 if (k) {
1580 if (k < 0)
1581 goto Fail;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001582 sortslice_memmove(&dest, 0, &ssb, 0, k);
1583 sortslice_advance(&dest, k);
1584 sortslice_advance(&ssb, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001585 nb -= k;
1586 if (nb == 0)
1587 goto Succeed;
1588 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001589 sortslice_copy_incr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001590 --na;
1591 if (na == 1)
1592 goto CopyB;
1593 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
1594 ++min_gallop; /* penalize it for leaving galloping mode */
1595 ms->min_gallop = min_gallop;
1596 }
Tim Petersa64dc242002-08-01 02:13:36 +00001597Succeed:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001598 result = 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001599Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001600 if (na)
Daniel Stutzbach98338222010-12-02 21:55:33 +00001601 sortslice_memcpy(&dest, 0, &ssa, 0, na);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001602 return result;
Tim Petersa64dc242002-08-01 02:13:36 +00001603CopyB:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001604 assert(na == 1 && nb > 0);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001605 /* The last element of ssa belongs at the end of the merge. */
1606 sortslice_memmove(&dest, 0, &ssb, 0, nb);
1607 sortslice_copy(&dest, nb, &ssa, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001608 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001609}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001610
Daniel Stutzbach98338222010-12-02 21:55:33 +00001611/* Merge the na elements starting at pa with the nb elements starting at
1612 * ssb.keys = ssa.keys + na in a stable way, in-place. na and nb must be > 0.
1613 * Must also have that ssa.keys[na-1] belongs at the end of the merge, and
1614 * should have na >= nb. See listsort.txt for more info. Return 0 if
1615 * successful, -1 if error.
Tim Petersa64dc242002-08-01 02:13:36 +00001616 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001617static Py_ssize_t
Daniel Stutzbach98338222010-12-02 21:55:33 +00001618merge_hi(MergeState *ms, sortslice ssa, Py_ssize_t na,
1619 sortslice ssb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001620{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001621 Py_ssize_t k;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001622 sortslice dest, basea, baseb;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001623 int result = -1; /* guilty until proved innocent */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001624 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001625
Daniel Stutzbach98338222010-12-02 21:55:33 +00001626 assert(ms && ssa.keys && ssb.keys && na > 0 && nb > 0);
1627 assert(ssa.keys + na == ssb.keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001628 if (MERGE_GETMEM(ms, nb) < 0)
1629 return -1;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001630 dest = ssb;
1631 sortslice_advance(&dest, nb-1);
1632 sortslice_memcpy(&ms->a, 0, &ssb, 0, nb);
1633 basea = ssa;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001634 baseb = ms->a;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001635 ssb.keys = ms->a.keys + nb - 1;
1636 if (ssb.values != NULL)
1637 ssb.values = ms->a.values + nb - 1;
1638 sortslice_advance(&ssa, na - 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001639
Daniel Stutzbach98338222010-12-02 21:55:33 +00001640 sortslice_copy_decr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001641 --na;
1642 if (na == 0)
1643 goto Succeed;
1644 if (nb == 1)
1645 goto CopyA;
Tim Petersa64dc242002-08-01 02:13:36 +00001646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001647 min_gallop = ms->min_gallop;
1648 for (;;) {
1649 Py_ssize_t acount = 0; /* # of times A won in a row */
1650 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001652 /* Do the straightforward thing until (if ever) one run
1653 * appears to win consistently.
1654 */
1655 for (;;) {
1656 assert(na > 0 && nb > 1);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001657 k = ISLT(ssb.keys[0], ssa.keys[0]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001658 if (k) {
1659 if (k < 0)
1660 goto Fail;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001661 sortslice_copy_decr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001662 ++acount;
1663 bcount = 0;
1664 --na;
1665 if (na == 0)
1666 goto Succeed;
1667 if (acount >= min_gallop)
1668 break;
1669 }
1670 else {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001671 sortslice_copy_decr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001672 ++bcount;
1673 acount = 0;
1674 --nb;
1675 if (nb == 1)
1676 goto CopyA;
1677 if (bcount >= min_gallop)
1678 break;
1679 }
1680 }
Tim Petersa64dc242002-08-01 02:13:36 +00001681
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001682 /* One run is winning so consistently that galloping may
1683 * be a huge win. So try that, and continue galloping until
1684 * (if ever) neither run appears to be winning consistently
1685 * anymore.
1686 */
1687 ++min_gallop;
1688 do {
1689 assert(na > 0 && nb > 1);
1690 min_gallop -= min_gallop > 1;
1691 ms->min_gallop = min_gallop;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001692 k = gallop_right(ssb.keys[0], basea.keys, na, na-1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001693 if (k < 0)
1694 goto Fail;
1695 k = na - k;
1696 acount = k;
1697 if (k) {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001698 sortslice_advance(&dest, -k);
1699 sortslice_advance(&ssa, -k);
1700 sortslice_memmove(&dest, 1, &ssa, 1, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001701 na -= k;
1702 if (na == 0)
1703 goto Succeed;
1704 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001705 sortslice_copy_decr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001706 --nb;
1707 if (nb == 1)
1708 goto CopyA;
Tim Petersa64dc242002-08-01 02:13:36 +00001709
Daniel Stutzbach98338222010-12-02 21:55:33 +00001710 k = gallop_left(ssa.keys[0], baseb.keys, nb, nb-1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001711 if (k < 0)
1712 goto Fail;
1713 k = nb - k;
1714 bcount = k;
1715 if (k) {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001716 sortslice_advance(&dest, -k);
1717 sortslice_advance(&ssb, -k);
1718 sortslice_memcpy(&dest, 1, &ssb, 1, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001719 nb -= k;
1720 if (nb == 1)
1721 goto CopyA;
1722 /* nb==0 is impossible now if the comparison
1723 * function is consistent, but we can't assume
1724 * that it is.
1725 */
1726 if (nb == 0)
1727 goto Succeed;
1728 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001729 sortslice_copy_decr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001730 --na;
1731 if (na == 0)
1732 goto Succeed;
1733 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
1734 ++min_gallop; /* penalize it for leaving galloping mode */
1735 ms->min_gallop = min_gallop;
1736 }
Tim Petersa64dc242002-08-01 02:13:36 +00001737Succeed:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001738 result = 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001739Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001740 if (nb)
Daniel Stutzbach98338222010-12-02 21:55:33 +00001741 sortslice_memcpy(&dest, -(nb-1), &baseb, 0, nb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001742 return result;
Tim Petersa64dc242002-08-01 02:13:36 +00001743CopyA:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001744 assert(nb == 1 && na > 0);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001745 /* The first element of ssb belongs at the front of the merge. */
1746 sortslice_memmove(&dest, 1-na, &ssa, 1-na, na);
1747 sortslice_advance(&dest, -na);
1748 sortslice_advance(&ssa, -na);
1749 sortslice_copy(&dest, 0, &ssb, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001750 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001751}
1752
1753/* Merge the two runs at stack indices i and i+1.
1754 * Returns 0 on success, -1 on error.
1755 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001756static Py_ssize_t
1757merge_at(MergeState *ms, Py_ssize_t i)
Tim Petersa64dc242002-08-01 02:13:36 +00001758{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001759 sortslice ssa, ssb;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001760 Py_ssize_t na, nb;
1761 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001762
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001763 assert(ms != NULL);
1764 assert(ms->n >= 2);
1765 assert(i >= 0);
1766 assert(i == ms->n - 2 || i == ms->n - 3);
Tim Petersa64dc242002-08-01 02:13:36 +00001767
Daniel Stutzbach98338222010-12-02 21:55:33 +00001768 ssa = ms->pending[i].base;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001769 na = ms->pending[i].len;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001770 ssb = ms->pending[i+1].base;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001771 nb = ms->pending[i+1].len;
1772 assert(na > 0 && nb > 0);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001773 assert(ssa.keys + na == ssb.keys);
Tim Petersa64dc242002-08-01 02:13:36 +00001774
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001775 /* Record the length of the combined runs; if i is the 3rd-last
1776 * run now, also slide over the last run (which isn't involved
1777 * in this merge). The current run i+1 goes away in any case.
1778 */
1779 ms->pending[i].len = na + nb;
1780 if (i == ms->n - 3)
1781 ms->pending[i+1] = ms->pending[i+2];
1782 --ms->n;
Tim Petersa64dc242002-08-01 02:13:36 +00001783
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001784 /* Where does b start in a? Elements in a before that can be
1785 * ignored (already in place).
1786 */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001787 k = gallop_right(*ssb.keys, ssa.keys, na, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001788 if (k < 0)
1789 return -1;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001790 sortslice_advance(&ssa, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001791 na -= k;
1792 if (na == 0)
1793 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001794
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001795 /* Where does a end in b? Elements in b after that can be
1796 * ignored (already in place).
1797 */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001798 nb = gallop_left(ssa.keys[na-1], ssb.keys, nb, nb-1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001799 if (nb <= 0)
1800 return nb;
Tim Petersa64dc242002-08-01 02:13:36 +00001801
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001802 /* Merge what remains of the runs, using a temp array with
1803 * min(na, nb) elements.
1804 */
1805 if (na <= nb)
Daniel Stutzbach98338222010-12-02 21:55:33 +00001806 return merge_lo(ms, ssa, na, ssb, nb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001807 else
Daniel Stutzbach98338222010-12-02 21:55:33 +00001808 return merge_hi(ms, ssa, na, ssb, nb);
Tim Petersa64dc242002-08-01 02:13:36 +00001809}
1810
1811/* Examine the stack of runs waiting to be merged, merging adjacent runs
1812 * until the stack invariants are re-established:
1813 *
1814 * 1. len[-3] > len[-2] + len[-1]
1815 * 2. len[-2] > len[-1]
1816 *
1817 * See listsort.txt for more info.
1818 *
1819 * Returns 0 on success, -1 on error.
1820 */
1821static int
1822merge_collapse(MergeState *ms)
1823{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001824 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001825
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001826 assert(ms);
1827 while (ms->n > 1) {
1828 Py_ssize_t n = ms->n - 2;
Benjamin Petersonb808d592015-02-25 10:12:26 -05001829 if ((n > 0 && p[n-1].len <= p[n].len + p[n+1].len) ||
1830 (n > 1 && p[n-2].len <= p[n-1].len + p[n].len)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001831 if (p[n-1].len < p[n+1].len)
1832 --n;
1833 if (merge_at(ms, n) < 0)
1834 return -1;
1835 }
1836 else if (p[n].len <= p[n+1].len) {
1837 if (merge_at(ms, n) < 0)
1838 return -1;
1839 }
1840 else
1841 break;
1842 }
1843 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001844}
1845
1846/* Regardless of invariants, merge all runs on the stack until only one
1847 * remains. This is used at the end of the mergesort.
1848 *
1849 * Returns 0 on success, -1 on error.
1850 */
1851static int
1852merge_force_collapse(MergeState *ms)
1853{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001854 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001855
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001856 assert(ms);
1857 while (ms->n > 1) {
1858 Py_ssize_t n = ms->n - 2;
1859 if (n > 0 && p[n-1].len < p[n+1].len)
1860 --n;
1861 if (merge_at(ms, n) < 0)
1862 return -1;
1863 }
1864 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001865}
1866
1867/* Compute a good value for the minimum run length; natural runs shorter
1868 * than this are boosted artificially via binary insertion.
1869 *
1870 * If n < 64, return n (it's too small to bother with fancy stuff).
1871 * Else if n is an exact power of 2, return 32.
1872 * Else return an int k, 32 <= k <= 64, such that n/k is close to, but
1873 * strictly less than, an exact power of 2.
1874 *
1875 * See listsort.txt for more info.
1876 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001877static Py_ssize_t
1878merge_compute_minrun(Py_ssize_t n)
Tim Petersa64dc242002-08-01 02:13:36 +00001879{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001880 Py_ssize_t r = 0; /* becomes 1 if any 1 bits are shifted off */
Tim Petersa64dc242002-08-01 02:13:36 +00001881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001882 assert(n >= 0);
1883 while (n >= 64) {
1884 r |= n & 1;
1885 n >>= 1;
1886 }
1887 return n + r;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001888}
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001889
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001890static void
Daniel Stutzbach98338222010-12-02 21:55:33 +00001891reverse_sortslice(sortslice *s, Py_ssize_t n)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001892{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001893 reverse_slice(s->keys, &s->keys[n]);
1894 if (s->values != NULL)
1895 reverse_slice(s->values, &s->values[n]);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001896}
1897
Tim Petersa64dc242002-08-01 02:13:36 +00001898/* An adaptive, stable, natural mergesort. See listsort.txt.
1899 * Returns Py_None on success, NULL on error. Even in case of error, the
1900 * list will be some permutation of its input state (nothing is lost or
1901 * duplicated).
1902 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001903static PyObject *
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001904listsort(PyListObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f236de1996-12-10 23:55:39 +00001905{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001906 MergeState ms;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001907 Py_ssize_t nremaining;
1908 Py_ssize_t minrun;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001909 sortslice lo;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001910 Py_ssize_t saved_ob_size, saved_allocated;
1911 PyObject **saved_ob_item;
1912 PyObject **final_ob_item;
1913 PyObject *result = NULL; /* guilty until proved innocent */
1914 int reverse = 0;
1915 PyObject *keyfunc = NULL;
1916 Py_ssize_t i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001917 static char *kwlist[] = {"key", "reverse", 0};
Daniel Stutzbach98338222010-12-02 21:55:33 +00001918 PyObject **keys;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001920 assert(self != NULL);
1921 assert (PyList_Check(self));
1922 if (args != NULL) {
1923 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:sort",
1924 kwlist, &keyfunc, &reverse))
1925 return NULL;
1926 if (Py_SIZE(args) > 0) {
1927 PyErr_SetString(PyExc_TypeError,
1928 "must use keyword argument for key function");
1929 return NULL;
1930 }
1931 }
1932 if (keyfunc == Py_None)
1933 keyfunc = NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001934
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001935 /* The list is temporarily made empty, so that mutations performed
1936 * by comparison functions can't affect the slice of memory we're
1937 * sorting (allowing mutations during sorting is a core-dump
1938 * factory, since ob_item may change).
1939 */
1940 saved_ob_size = Py_SIZE(self);
1941 saved_ob_item = self->ob_item;
1942 saved_allocated = self->allocated;
1943 Py_SIZE(self) = 0;
1944 self->ob_item = NULL;
1945 self->allocated = -1; /* any operation will reset it to >= 0 */
Tim Peters330f9e92002-07-19 07:05:44 +00001946
Daniel Stutzbach98338222010-12-02 21:55:33 +00001947 if (keyfunc == NULL) {
1948 keys = NULL;
1949 lo.keys = saved_ob_item;
1950 lo.values = NULL;
1951 }
1952 else {
1953 if (saved_ob_size < MERGESTATE_TEMP_SIZE/2)
1954 /* Leverage stack space we allocated but won't otherwise use */
1955 keys = &ms.temparray[saved_ob_size+1];
1956 else {
1957 keys = PyMem_MALLOC(sizeof(PyObject *) * saved_ob_size);
Benjamin Peterson0823ffb2015-04-23 17:04:36 -04001958 if (keys == NULL) {
1959 PyErr_NoMemory();
1960 goto keyfunc_fail;
1961 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001962 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001963
1964 for (i = 0; i < saved_ob_size ; i++) {
1965 keys[i] = PyObject_CallFunctionObjArgs(keyfunc, saved_ob_item[i],
1966 NULL);
1967 if (keys[i] == NULL) {
1968 for (i=i-1 ; i>=0 ; i--)
1969 Py_DECREF(keys[i]);
Benjamin Peterson4a42cd42014-03-15 12:21:28 -05001970 if (saved_ob_size >= MERGESTATE_TEMP_SIZE/2)
Daniel Stutzbach8eda5f72011-03-02 23:37:50 +00001971 PyMem_FREE(keys);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001972 goto keyfunc_fail;
1973 }
1974 }
1975
1976 lo.keys = keys;
1977 lo.values = saved_ob_item;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001978 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001979
Daniel Stutzbach98338222010-12-02 21:55:33 +00001980 merge_init(&ms, saved_ob_size, keys != NULL);
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001982 nremaining = saved_ob_size;
1983 if (nremaining < 2)
1984 goto succeed;
Tim Peters330f9e92002-07-19 07:05:44 +00001985
Benjamin Peterson05380642010-08-23 19:35:39 +00001986 /* Reverse sort stability achieved by initially reversing the list,
1987 applying a stable forward sort, then reversing the final result. */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001988 if (reverse) {
1989 if (keys != NULL)
1990 reverse_slice(&keys[0], &keys[saved_ob_size]);
1991 reverse_slice(&saved_ob_item[0], &saved_ob_item[saved_ob_size]);
1992 }
Benjamin Peterson05380642010-08-23 19:35:39 +00001993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001994 /* March over the array once, left to right, finding natural runs,
1995 * and extending short natural runs to minrun elements.
1996 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001997 minrun = merge_compute_minrun(nremaining);
1998 do {
1999 int descending;
2000 Py_ssize_t n;
Tim Peters330f9e92002-07-19 07:05:44 +00002001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002002 /* Identify next run. */
Daniel Stutzbach98338222010-12-02 21:55:33 +00002003 n = count_run(lo.keys, lo.keys + nremaining, &descending);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002004 if (n < 0)
2005 goto fail;
2006 if (descending)
Daniel Stutzbach98338222010-12-02 21:55:33 +00002007 reverse_sortslice(&lo, n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002008 /* If short, extend to min(minrun, nremaining). */
2009 if (n < minrun) {
2010 const Py_ssize_t force = nremaining <= minrun ?
2011 nremaining : minrun;
Daniel Stutzbach98338222010-12-02 21:55:33 +00002012 if (binarysort(lo, lo.keys + force, lo.keys + n) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002013 goto fail;
2014 n = force;
2015 }
2016 /* Push run onto pending-runs stack, and maybe merge. */
2017 assert(ms.n < MAX_MERGE_PENDING);
2018 ms.pending[ms.n].base = lo;
2019 ms.pending[ms.n].len = n;
2020 ++ms.n;
2021 if (merge_collapse(&ms) < 0)
2022 goto fail;
2023 /* Advance to find next run. */
Daniel Stutzbach98338222010-12-02 21:55:33 +00002024 sortslice_advance(&lo, n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002025 nremaining -= n;
2026 } while (nremaining);
Tim Peters330f9e92002-07-19 07:05:44 +00002027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002028 if (merge_force_collapse(&ms) < 0)
2029 goto fail;
2030 assert(ms.n == 1);
Daniel Stutzbach98338222010-12-02 21:55:33 +00002031 assert(keys == NULL
2032 ? ms.pending[0].base.keys == saved_ob_item
2033 : ms.pending[0].base.keys == &keys[0]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002034 assert(ms.pending[0].len == saved_ob_size);
Daniel Stutzbach98338222010-12-02 21:55:33 +00002035 lo = ms.pending[0].base;
Tim Petersa64dc242002-08-01 02:13:36 +00002036
2037succeed:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002038 result = Py_None;
Tim Peters330f9e92002-07-19 07:05:44 +00002039fail:
Daniel Stutzbach98338222010-12-02 21:55:33 +00002040 if (keys != NULL) {
2041 for (i = 0; i < saved_ob_size; i++)
2042 Py_DECREF(keys[i]);
Benjamin Petersonef87f8c2014-03-14 21:54:31 -05002043 if (saved_ob_size >= MERGESTATE_TEMP_SIZE/2)
Daniel Stutzbach98338222010-12-02 21:55:33 +00002044 PyMem_FREE(keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002045 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002047 if (self->allocated != -1 && result != NULL) {
2048 /* The user mucked with the list during the sort,
2049 * and we don't already have another error to report.
2050 */
2051 PyErr_SetString(PyExc_ValueError, "list modified during sort");
2052 result = NULL;
2053 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002055 if (reverse && saved_ob_size > 1)
2056 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002058 merge_freemem(&ms);
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002059
Daniel Stutzbach98338222010-12-02 21:55:33 +00002060keyfunc_fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002061 final_ob_item = self->ob_item;
2062 i = Py_SIZE(self);
2063 Py_SIZE(self) = saved_ob_size;
2064 self->ob_item = saved_ob_item;
2065 self->allocated = saved_allocated;
2066 if (final_ob_item != NULL) {
2067 /* we cannot use list_clear() for this because it does not
2068 guarantee that the list is really empty when it returns */
2069 while (--i >= 0) {
2070 Py_XDECREF(final_ob_item[i]);
2071 }
2072 PyMem_FREE(final_ob_item);
2073 }
2074 Py_XINCREF(result);
2075 return result;
Guido van Rossum3f236de1996-12-10 23:55:39 +00002076}
Tim Peters330f9e92002-07-19 07:05:44 +00002077#undef IFLT
Tim Peters66860f62002-08-04 17:47:26 +00002078#undef ISLT
Tim Peters330f9e92002-07-19 07:05:44 +00002079
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002080int
Fred Drakea2f55112000-07-09 15:16:51 +00002081PyList_Sort(PyObject *v)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002082{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002083 if (v == NULL || !PyList_Check(v)) {
2084 PyErr_BadInternalCall();
2085 return -1;
2086 }
2087 v = listsort((PyListObject *)v, (PyObject *)NULL, (PyObject *)NULL);
2088 if (v == NULL)
2089 return -1;
2090 Py_DECREF(v);
2091 return 0;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002092}
2093
Guido van Rossumb86c5492001-02-12 22:06:02 +00002094static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002095listreverse(PyListObject *self)
Guido van Rossumb86c5492001-02-12 22:06:02 +00002096{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002097 if (Py_SIZE(self) > 1)
2098 reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
2099 Py_RETURN_NONE;
Guido van Rossumed98d481991-03-06 13:07:53 +00002100}
2101
Guido van Rossum84c76f51990-10-30 13:32:20 +00002102int
Fred Drakea2f55112000-07-09 15:16:51 +00002103PyList_Reverse(PyObject *v)
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002104{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002105 PyListObject *self = (PyListObject *)v;
Tim Peters6063e262002-08-08 01:06:39 +00002106
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002107 if (v == NULL || !PyList_Check(v)) {
2108 PyErr_BadInternalCall();
2109 return -1;
2110 }
2111 if (Py_SIZE(self) > 1)
2112 reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
2113 return 0;
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002114}
2115
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002116PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00002117PyList_AsTuple(PyObject *v)
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002118{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002119 PyObject *w;
2120 PyObject **p, **q;
2121 Py_ssize_t n;
2122 if (v == NULL || !PyList_Check(v)) {
2123 PyErr_BadInternalCall();
2124 return NULL;
2125 }
2126 n = Py_SIZE(v);
2127 w = PyTuple_New(n);
2128 if (w == NULL)
2129 return NULL;
2130 p = ((PyTupleObject *)w)->ob_item;
2131 q = ((PyListObject *)v)->ob_item;
2132 while (--n >= 0) {
2133 Py_INCREF(*q);
2134 *p = *q;
2135 p++;
2136 q++;
2137 }
2138 return w;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002139}
2140
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002141static PyObject *
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002142listindex(PyListObject *self, PyObject *args)
Guido van Rossumed98d481991-03-06 13:07:53 +00002143{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002144 Py_ssize_t i, start=0, stop=Py_SIZE(self);
Amaury Forgeot d'Arc864741b2011-11-06 15:10:48 +01002145 PyObject *v;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002146
Petri Lehtinenebfaabd2011-11-06 21:02:39 +02002147 if (!PyArg_ParseTuple(args, "O|O&O&:index", &v,
2148 _PyEval_SliceIndex, &start,
2149 _PyEval_SliceIndex, &stop))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002150 return NULL;
2151 if (start < 0) {
2152 start += Py_SIZE(self);
2153 if (start < 0)
2154 start = 0;
2155 }
2156 if (stop < 0) {
2157 stop += Py_SIZE(self);
2158 if (stop < 0)
2159 stop = 0;
2160 }
2161 for (i = start; i < stop && i < Py_SIZE(self); i++) {
2162 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2163 if (cmp > 0)
2164 return PyLong_FromSsize_t(i);
2165 else if (cmp < 0)
2166 return NULL;
2167 }
Amaury Forgeot d'Arc864741b2011-11-06 15:10:48 +01002168 PyErr_Format(PyExc_ValueError, "%R is not in list", v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002169 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002170}
2171
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002172static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002173listcount(PyListObject *self, PyObject *v)
Guido van Rossume6f7d181991-10-20 20:20:40 +00002174{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002175 Py_ssize_t count = 0;
2176 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002178 for (i = 0; i < Py_SIZE(self); i++) {
2179 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2180 if (cmp > 0)
2181 count++;
2182 else if (cmp < 0)
2183 return NULL;
2184 }
2185 return PyLong_FromSsize_t(count);
Guido van Rossume6f7d181991-10-20 20:20:40 +00002186}
2187
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002188static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002189listremove(PyListObject *self, PyObject *v)
Guido van Rossumed98d481991-03-06 13:07:53 +00002190{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002191 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002193 for (i = 0; i < Py_SIZE(self); i++) {
2194 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2195 if (cmp > 0) {
2196 if (list_ass_slice(self, i, i+1,
2197 (PyObject *)NULL) == 0)
2198 Py_RETURN_NONE;
2199 return NULL;
2200 }
2201 else if (cmp < 0)
2202 return NULL;
2203 }
2204 PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
2205 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002206}
2207
Jeremy Hylton8caad492000-06-23 14:18:11 +00002208static int
2209list_traverse(PyListObject *o, visitproc visit, void *arg)
2210{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002211 Py_ssize_t i;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002213 for (i = Py_SIZE(o); --i >= 0; )
2214 Py_VISIT(o->ob_item[i]);
2215 return 0;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002216}
2217
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002218static PyObject *
2219list_richcompare(PyObject *v, PyObject *w, int op)
2220{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002221 PyListObject *vl, *wl;
2222 Py_ssize_t i;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002223
Brian Curtindfc80e32011-08-10 20:28:54 -05002224 if (!PyList_Check(v) || !PyList_Check(w))
2225 Py_RETURN_NOTIMPLEMENTED;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002227 vl = (PyListObject *)v;
2228 wl = (PyListObject *)w;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002230 if (Py_SIZE(vl) != Py_SIZE(wl) && (op == Py_EQ || op == Py_NE)) {
2231 /* Shortcut: if the lengths differ, the lists differ */
2232 PyObject *res;
2233 if (op == Py_EQ)
2234 res = Py_False;
2235 else
2236 res = Py_True;
2237 Py_INCREF(res);
2238 return res;
2239 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002241 /* Search for the first index where items are different */
2242 for (i = 0; i < Py_SIZE(vl) && i < Py_SIZE(wl); i++) {
2243 int k = PyObject_RichCompareBool(vl->ob_item[i],
2244 wl->ob_item[i], Py_EQ);
2245 if (k < 0)
2246 return NULL;
2247 if (!k)
2248 break;
2249 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002251 if (i >= Py_SIZE(vl) || i >= Py_SIZE(wl)) {
2252 /* No more items to compare -- compare sizes */
2253 Py_ssize_t vs = Py_SIZE(vl);
2254 Py_ssize_t ws = Py_SIZE(wl);
2255 int cmp;
2256 PyObject *res;
2257 switch (op) {
2258 case Py_LT: cmp = vs < ws; break;
2259 case Py_LE: cmp = vs <= ws; break;
2260 case Py_EQ: cmp = vs == ws; break;
2261 case Py_NE: cmp = vs != ws; break;
2262 case Py_GT: cmp = vs > ws; break;
2263 case Py_GE: cmp = vs >= ws; break;
2264 default: return NULL; /* cannot happen */
2265 }
2266 if (cmp)
2267 res = Py_True;
2268 else
2269 res = Py_False;
2270 Py_INCREF(res);
2271 return res;
2272 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002274 /* We have an item that differs -- shortcuts for EQ/NE */
2275 if (op == Py_EQ) {
2276 Py_INCREF(Py_False);
2277 return Py_False;
2278 }
2279 if (op == Py_NE) {
2280 Py_INCREF(Py_True);
2281 return Py_True;
2282 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002284 /* Compare the final item again using the proper operator */
2285 return PyObject_RichCompare(vl->ob_item[i], wl->ob_item[i], op);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002286}
2287
Tim Peters6d6c1a32001-08-02 04:15:00 +00002288static int
2289list_init(PyListObject *self, PyObject *args, PyObject *kw)
2290{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002291 PyObject *arg = NULL;
2292 static char *kwlist[] = {"sequence", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002294 if (!PyArg_ParseTupleAndKeywords(args, kw, "|O:list", kwlist, &arg))
2295 return -1;
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002297 /* Verify list invariants established by PyType_GenericAlloc() */
2298 assert(0 <= Py_SIZE(self));
2299 assert(Py_SIZE(self) <= self->allocated || self->allocated == -1);
2300 assert(self->ob_item != NULL ||
2301 self->allocated == 0 || self->allocated == -1);
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002303 /* Empty previous contents */
2304 if (self->ob_item != NULL) {
2305 (void)list_clear(self);
2306 }
2307 if (arg != NULL) {
2308 PyObject *rv = listextend(self, arg);
2309 if (rv == NULL)
2310 return -1;
2311 Py_DECREF(rv);
2312 }
2313 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002314}
2315
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002316static PyObject *
2317list_sizeof(PyListObject *self)
2318{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002319 Py_ssize_t res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002320
Serhiy Storchaka5c4064e2015-12-19 20:05:25 +02002321 res = _PyObject_SIZE(Py_TYPE(self)) + self->allocated * sizeof(void*);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002322 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002323}
2324
Raymond Hettinger1021c442003-11-07 15:38:09 +00002325static PyObject *list_iter(PyObject *seq);
2326static PyObject *list_reversed(PyListObject* seq, PyObject* unused);
2327
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002328PyDoc_STRVAR(getitem_doc,
2329"x.__getitem__(y) <==> x[y]");
Raymond Hettinger1021c442003-11-07 15:38:09 +00002330PyDoc_STRVAR(reversed_doc,
2331"L.__reversed__() -- return a reverse iterator over the list");
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002332PyDoc_STRVAR(sizeof_doc,
2333"L.__sizeof__() -- size of L in memory, in bytes");
Eli Benderskycbbaa962011-02-25 05:47:53 +00002334PyDoc_STRVAR(clear_doc,
2335"L.clear() -> None -- remove all items from L");
2336PyDoc_STRVAR(copy_doc,
2337"L.copy() -> list -- a shallow copy of L");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002338PyDoc_STRVAR(append_doc,
Georg Brandl388349a2011-10-08 18:32:40 +02002339"L.append(object) -> None -- append object to end");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002340PyDoc_STRVAR(extend_doc,
Georg Brandl388349a2011-10-08 18:32:40 +02002341"L.extend(iterable) -> None -- extend list by appending elements from the iterable");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002342PyDoc_STRVAR(insert_doc,
2343"L.insert(index, object) -- insert object before index");
2344PyDoc_STRVAR(pop_doc,
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00002345"L.pop([index]) -> item -- remove and return item at index (default last).\n"
2346"Raises IndexError if list is empty or index is out of range.");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002347PyDoc_STRVAR(remove_doc,
Georg Brandl388349a2011-10-08 18:32:40 +02002348"L.remove(value) -> None -- remove first occurrence of value.\n"
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00002349"Raises ValueError if the value is not present.");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002350PyDoc_STRVAR(index_doc,
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00002351"L.index(value, [start, [stop]]) -> integer -- return first index of value.\n"
2352"Raises ValueError if the value is not present.");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002353PyDoc_STRVAR(count_doc,
2354"L.count(value) -> integer -- return number of occurrences of value");
2355PyDoc_STRVAR(reverse_doc,
2356"L.reverse() -- reverse *IN PLACE*");
2357PyDoc_STRVAR(sort_doc,
Georg Brandl388349a2011-10-08 18:32:40 +02002358"L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*");
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +00002359
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002360static PyObject *list_subscript(PyListObject*, PyObject*);
2361
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002362static PyMethodDef list_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002363 {"__getitem__", (PyCFunction)list_subscript, METH_O|METH_COEXIST, getitem_doc},
2364 {"__reversed__",(PyCFunction)list_reversed, METH_NOARGS, reversed_doc},
2365 {"__sizeof__", (PyCFunction)list_sizeof, METH_NOARGS, sizeof_doc},
Eli Benderskycbbaa962011-02-25 05:47:53 +00002366 {"clear", (PyCFunction)listclear, METH_NOARGS, clear_doc},
2367 {"copy", (PyCFunction)listcopy, METH_NOARGS, copy_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002368 {"append", (PyCFunction)listappend, METH_O, append_doc},
2369 {"insert", (PyCFunction)listinsert, METH_VARARGS, insert_doc},
Eli Benderskycbbaa962011-02-25 05:47:53 +00002370 {"extend", (PyCFunction)listextend, METH_O, extend_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002371 {"pop", (PyCFunction)listpop, METH_VARARGS, pop_doc},
2372 {"remove", (PyCFunction)listremove, METH_O, remove_doc},
2373 {"index", (PyCFunction)listindex, METH_VARARGS, index_doc},
2374 {"count", (PyCFunction)listcount, METH_O, count_doc},
2375 {"reverse", (PyCFunction)listreverse, METH_NOARGS, reverse_doc},
2376 {"sort", (PyCFunction)listsort, METH_VARARGS | METH_KEYWORDS, sort_doc},
2377 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002378};
2379
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002380static PySequenceMethods list_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002381 (lenfunc)list_length, /* sq_length */
2382 (binaryfunc)list_concat, /* sq_concat */
2383 (ssizeargfunc)list_repeat, /* sq_repeat */
2384 (ssizeargfunc)list_item, /* sq_item */
2385 0, /* sq_slice */
2386 (ssizeobjargproc)list_ass_item, /* sq_ass_item */
2387 0, /* sq_ass_slice */
2388 (objobjproc)list_contains, /* sq_contains */
2389 (binaryfunc)list_inplace_concat, /* sq_inplace_concat */
2390 (ssizeargfunc)list_inplace_repeat, /* sq_inplace_repeat */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002391};
2392
Neal Norwitz2c2e8272002-06-14 02:04:18 +00002393PyDoc_STRVAR(list_doc,
Ezio Melotti7f807b72010-03-01 04:08:34 +00002394"list() -> new empty list\n"
2395"list(iterable) -> new list initialized from iterable's items");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002396
Jeremy Hyltona4b4c3b2002-07-13 03:51:17 +00002397static PyObject *
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002398list_subscript(PyListObject* self, PyObject* item)
2399{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002400 if (PyIndex_Check(item)) {
2401 Py_ssize_t i;
2402 i = PyNumber_AsSsize_t(item, PyExc_IndexError);
2403 if (i == -1 && PyErr_Occurred())
2404 return NULL;
2405 if (i < 0)
2406 i += PyList_GET_SIZE(self);
2407 return list_item(self, i);
2408 }
2409 else if (PySlice_Check(item)) {
2410 Py_ssize_t start, stop, step, slicelength, cur, i;
2411 PyObject* result;
2412 PyObject* it;
2413 PyObject **src, **dest;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002414
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002415 if (PySlice_GetIndicesEx(item, Py_SIZE(self),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002416 &start, &stop, &step, &slicelength) < 0) {
2417 return NULL;
2418 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002419
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002420 if (slicelength <= 0) {
2421 return PyList_New(0);
2422 }
2423 else if (step == 1) {
2424 return list_slice(self, start, stop);
2425 }
2426 else {
2427 result = PyList_New(slicelength);
2428 if (!result) return NULL;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002429
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002430 src = self->ob_item;
2431 dest = ((PyListObject *)result)->ob_item;
2432 for (cur = start, i = 0; i < slicelength;
Mark Dickinsonc7d93b72011-09-25 15:34:32 +01002433 cur += (size_t)step, i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002434 it = src[cur];
2435 Py_INCREF(it);
2436 dest[i] = it;
2437 }
Tim Peters3b01a122002-07-19 02:35:45 +00002438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002439 return result;
2440 }
2441 }
2442 else {
2443 PyErr_Format(PyExc_TypeError,
Terry Jan Reedyffff1442014-08-02 01:30:37 -04002444 "list indices must be integers or slices, not %.200s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002445 item->ob_type->tp_name);
2446 return NULL;
2447 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002448}
2449
Tim Peters3b01a122002-07-19 02:35:45 +00002450static int
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002451list_ass_subscript(PyListObject* self, PyObject* item, PyObject* value)
2452{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002453 if (PyIndex_Check(item)) {
2454 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
2455 if (i == -1 && PyErr_Occurred())
2456 return -1;
2457 if (i < 0)
2458 i += PyList_GET_SIZE(self);
2459 return list_ass_item(self, i, value);
2460 }
2461 else if (PySlice_Check(item)) {
2462 Py_ssize_t start, stop, step, slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002463
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002464 if (PySlice_GetIndicesEx(item, Py_SIZE(self),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002465 &start, &stop, &step, &slicelength) < 0) {
2466 return -1;
2467 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002469 if (step == 1)
2470 return list_ass_slice(self, start, stop, value);
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002472 /* Make sure s[5:2] = [..] inserts at the right place:
2473 before 5, not before 2. */
2474 if ((step < 0 && start < stop) ||
2475 (step > 0 && start > stop))
2476 stop = start;
Thomas Woutersed03b412007-08-28 21:37:11 +00002477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002478 if (value == NULL) {
2479 /* delete slice */
2480 PyObject **garbage;
2481 size_t cur;
2482 Py_ssize_t i;
Victor Stinner35f28032013-11-21 12:16:35 +01002483 int res;
Tim Peters3b01a122002-07-19 02:35:45 +00002484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002485 if (slicelength <= 0)
2486 return 0;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002488 if (step < 0) {
2489 stop = start + 1;
2490 start = stop + step*(slicelength - 1) - 1;
2491 step = -step;
2492 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002494 assert((size_t)slicelength <=
2495 PY_SIZE_MAX / sizeof(PyObject*));
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00002496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002497 garbage = (PyObject**)
2498 PyMem_MALLOC(slicelength*sizeof(PyObject*));
2499 if (!garbage) {
2500 PyErr_NoMemory();
2501 return -1;
2502 }
Tim Peters3b01a122002-07-19 02:35:45 +00002503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002504 /* drawing pictures might help understand these for
2505 loops. Basically, we memmove the parts of the
2506 list that are *not* part of the slice: step-1
2507 items for each item that is part of the slice,
2508 and then tail end of the list that was not
2509 covered by the slice */
2510 for (cur = start, i = 0;
2511 cur < (size_t)stop;
2512 cur += step, i++) {
2513 Py_ssize_t lim = step - 1;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002515 garbage[i] = PyList_GET_ITEM(self, cur);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002517 if (cur + step >= (size_t)Py_SIZE(self)) {
2518 lim = Py_SIZE(self) - cur - 1;
2519 }
Michael W. Hudson56796f62002-07-29 14:35:04 +00002520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002521 memmove(self->ob_item + cur - i,
2522 self->ob_item + cur + 1,
2523 lim * sizeof(PyObject *));
2524 }
Mark Dickinsonc7d93b72011-09-25 15:34:32 +01002525 cur = start + (size_t)slicelength * step;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002526 if (cur < (size_t)Py_SIZE(self)) {
2527 memmove(self->ob_item + cur - slicelength,
2528 self->ob_item + cur,
2529 (Py_SIZE(self) - cur) *
2530 sizeof(PyObject *));
2531 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002533 Py_SIZE(self) -= slicelength;
Victor Stinner35f28032013-11-21 12:16:35 +01002534 res = list_resize(self, Py_SIZE(self));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002536 for (i = 0; i < slicelength; i++) {
2537 Py_DECREF(garbage[i]);
2538 }
2539 PyMem_FREE(garbage);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002540
Victor Stinner35f28032013-11-21 12:16:35 +01002541 return res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002542 }
2543 else {
2544 /* assign slice */
2545 PyObject *ins, *seq;
2546 PyObject **garbage, **seqitems, **selfitems;
2547 Py_ssize_t cur, i;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002549 /* protect against a[::-1] = a */
2550 if (self == (PyListObject*)value) {
2551 seq = list_slice((PyListObject*)value, 0,
2552 PyList_GET_SIZE(value));
2553 }
2554 else {
2555 seq = PySequence_Fast(value,
2556 "must assign iterable "
2557 "to extended slice");
2558 }
2559 if (!seq)
2560 return -1;
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002562 if (PySequence_Fast_GET_SIZE(seq) != slicelength) {
2563 PyErr_Format(PyExc_ValueError,
2564 "attempt to assign sequence of "
2565 "size %zd to extended slice of "
2566 "size %zd",
2567 PySequence_Fast_GET_SIZE(seq),
2568 slicelength);
2569 Py_DECREF(seq);
2570 return -1;
2571 }
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002573 if (!slicelength) {
2574 Py_DECREF(seq);
2575 return 0;
2576 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002578 garbage = (PyObject**)
2579 PyMem_MALLOC(slicelength*sizeof(PyObject*));
2580 if (!garbage) {
2581 Py_DECREF(seq);
2582 PyErr_NoMemory();
2583 return -1;
2584 }
Tim Peters3b01a122002-07-19 02:35:45 +00002585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002586 selfitems = self->ob_item;
2587 seqitems = PySequence_Fast_ITEMS(seq);
2588 for (cur = start, i = 0; i < slicelength;
Mark Dickinsonc7d93b72011-09-25 15:34:32 +01002589 cur += (size_t)step, i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002590 garbage[i] = selfitems[cur];
2591 ins = seqitems[i];
2592 Py_INCREF(ins);
2593 selfitems[cur] = ins;
2594 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002596 for (i = 0; i < slicelength; i++) {
2597 Py_DECREF(garbage[i]);
2598 }
Tim Peters3b01a122002-07-19 02:35:45 +00002599
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002600 PyMem_FREE(garbage);
2601 Py_DECREF(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002602
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002603 return 0;
2604 }
2605 }
2606 else {
2607 PyErr_Format(PyExc_TypeError,
Terry Jan Reedyffff1442014-08-02 01:30:37 -04002608 "list indices must be integers or slices, not %.200s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002609 item->ob_type->tp_name);
2610 return -1;
2611 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002612}
2613
2614static PyMappingMethods list_as_mapping = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002615 (lenfunc)list_length,
2616 (binaryfunc)list_subscript,
2617 (objobjargproc)list_ass_subscript
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002618};
2619
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002620PyTypeObject PyList_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002621 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2622 "list",
2623 sizeof(PyListObject),
2624 0,
2625 (destructor)list_dealloc, /* tp_dealloc */
2626 0, /* tp_print */
2627 0, /* tp_getattr */
2628 0, /* tp_setattr */
2629 0, /* tp_reserved */
2630 (reprfunc)list_repr, /* tp_repr */
2631 0, /* tp_as_number */
2632 &list_as_sequence, /* tp_as_sequence */
2633 &list_as_mapping, /* tp_as_mapping */
Georg Brandl00da4e02010-10-18 07:32:48 +00002634 PyObject_HashNotImplemented, /* tp_hash */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002635 0, /* tp_call */
2636 0, /* tp_str */
2637 PyObject_GenericGetAttr, /* tp_getattro */
2638 0, /* tp_setattro */
2639 0, /* tp_as_buffer */
2640 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2641 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LIST_SUBCLASS, /* tp_flags */
2642 list_doc, /* tp_doc */
2643 (traverseproc)list_traverse, /* tp_traverse */
2644 (inquiry)list_clear, /* tp_clear */
2645 list_richcompare, /* tp_richcompare */
2646 0, /* tp_weaklistoffset */
2647 list_iter, /* tp_iter */
2648 0, /* tp_iternext */
2649 list_methods, /* tp_methods */
2650 0, /* tp_members */
2651 0, /* tp_getset */
2652 0, /* tp_base */
2653 0, /* tp_dict */
2654 0, /* tp_descr_get */
2655 0, /* tp_descr_set */
2656 0, /* tp_dictoffset */
2657 (initproc)list_init, /* tp_init */
2658 PyType_GenericAlloc, /* tp_alloc */
2659 PyType_GenericNew, /* tp_new */
2660 PyObject_GC_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002661};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002662
2663
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002664/*********************** List Iterator **************************/
2665
2666typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002667 PyObject_HEAD
Victor Stinner7660b882013-06-24 23:59:24 +02002668 Py_ssize_t it_index;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002669 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002670} listiterobject;
2671
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002672static PyObject *list_iter(PyObject *);
2673static void listiter_dealloc(listiterobject *);
2674static int listiter_traverse(listiterobject *, visitproc, void *);
2675static PyObject *listiter_next(listiterobject *);
2676static PyObject *listiter_len(listiterobject *);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002677static PyObject *listiter_reduce_general(void *_it, int forward);
2678static PyObject *listiter_reduce(listiterobject *);
2679static PyObject *listiter_setstate(listiterobject *, PyObject *state);
Raymond Hettinger435bf582004-03-18 22:43:10 +00002680
Armin Rigof5b3e362006-02-11 21:32:43 +00002681PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002682PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
2683PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002684
2685static PyMethodDef listiter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002686 {"__length_hint__", (PyCFunction)listiter_len, METH_NOARGS, length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002687 {"__reduce__", (PyCFunction)listiter_reduce, METH_NOARGS, reduce_doc},
2688 {"__setstate__", (PyCFunction)listiter_setstate, METH_O, setstate_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002689 {NULL, NULL} /* sentinel */
Raymond Hettinger435bf582004-03-18 22:43:10 +00002690};
2691
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002692PyTypeObject PyListIter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002693 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2694 "list_iterator", /* tp_name */
2695 sizeof(listiterobject), /* tp_basicsize */
2696 0, /* tp_itemsize */
2697 /* methods */
2698 (destructor)listiter_dealloc, /* tp_dealloc */
2699 0, /* tp_print */
2700 0, /* tp_getattr */
2701 0, /* tp_setattr */
2702 0, /* tp_reserved */
2703 0, /* tp_repr */
2704 0, /* tp_as_number */
2705 0, /* tp_as_sequence */
2706 0, /* tp_as_mapping */
2707 0, /* tp_hash */
2708 0, /* tp_call */
2709 0, /* tp_str */
2710 PyObject_GenericGetAttr, /* tp_getattro */
2711 0, /* tp_setattro */
2712 0, /* tp_as_buffer */
2713 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2714 0, /* tp_doc */
2715 (traverseproc)listiter_traverse, /* tp_traverse */
2716 0, /* tp_clear */
2717 0, /* tp_richcompare */
2718 0, /* tp_weaklistoffset */
2719 PyObject_SelfIter, /* tp_iter */
2720 (iternextfunc)listiter_next, /* tp_iternext */
2721 listiter_methods, /* tp_methods */
2722 0, /* tp_members */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002723};
Raymond Hettinger1021c442003-11-07 15:38:09 +00002724
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002725
2726static PyObject *
2727list_iter(PyObject *seq)
2728{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002729 listiterobject *it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002730
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002731 if (!PyList_Check(seq)) {
2732 PyErr_BadInternalCall();
2733 return NULL;
2734 }
2735 it = PyObject_GC_New(listiterobject, &PyListIter_Type);
2736 if (it == NULL)
2737 return NULL;
2738 it->it_index = 0;
2739 Py_INCREF(seq);
2740 it->it_seq = (PyListObject *)seq;
2741 _PyObject_GC_TRACK(it);
2742 return (PyObject *)it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002743}
2744
2745static void
2746listiter_dealloc(listiterobject *it)
2747{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002748 _PyObject_GC_UNTRACK(it);
2749 Py_XDECREF(it->it_seq);
2750 PyObject_GC_Del(it);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002751}
2752
2753static int
2754listiter_traverse(listiterobject *it, visitproc visit, void *arg)
2755{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002756 Py_VISIT(it->it_seq);
2757 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002758}
2759
2760static PyObject *
2761listiter_next(listiterobject *it)
2762{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002763 PyListObject *seq;
2764 PyObject *item;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002765
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002766 assert(it != NULL);
2767 seq = it->it_seq;
2768 if (seq == NULL)
2769 return NULL;
2770 assert(PyList_Check(seq));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002772 if (it->it_index < PyList_GET_SIZE(seq)) {
2773 item = PyList_GET_ITEM(seq, it->it_index);
2774 ++it->it_index;
2775 Py_INCREF(item);
2776 return item;
2777 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002778
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002779 it->it_seq = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03002780 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002781 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002782}
2783
2784static PyObject *
2785listiter_len(listiterobject *it)
2786{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002787 Py_ssize_t len;
2788 if (it->it_seq) {
2789 len = PyList_GET_SIZE(it->it_seq) - it->it_index;
2790 if (len >= 0)
2791 return PyLong_FromSsize_t(len);
2792 }
2793 return PyLong_FromLong(0);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002794}
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002795
2796static PyObject *
2797listiter_reduce(listiterobject *it)
2798{
2799 return listiter_reduce_general(it, 1);
2800}
2801
2802static PyObject *
2803listiter_setstate(listiterobject *it, PyObject *state)
2804{
Victor Stinner7660b882013-06-24 23:59:24 +02002805 Py_ssize_t index = PyLong_AsSsize_t(state);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002806 if (index == -1 && PyErr_Occurred())
2807 return NULL;
2808 if (it->it_seq != NULL) {
2809 if (index < 0)
2810 index = 0;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +00002811 else if (index > PyList_GET_SIZE(it->it_seq))
2812 index = PyList_GET_SIZE(it->it_seq); /* iterator exhausted */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002813 it->it_index = index;
2814 }
2815 Py_RETURN_NONE;
2816}
2817
Raymond Hettinger1021c442003-11-07 15:38:09 +00002818/*********************** List Reverse Iterator **************************/
2819
2820typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002821 PyObject_HEAD
2822 Py_ssize_t it_index;
2823 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger1021c442003-11-07 15:38:09 +00002824} listreviterobject;
2825
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002826static PyObject *list_reversed(PyListObject *, PyObject *);
2827static void listreviter_dealloc(listreviterobject *);
2828static int listreviter_traverse(listreviterobject *, visitproc, void *);
2829static PyObject *listreviter_next(listreviterobject *);
Raymond Hettingerf5b64112008-12-02 21:33:45 +00002830static PyObject *listreviter_len(listreviterobject *);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002831static PyObject *listreviter_reduce(listreviterobject *);
2832static PyObject *listreviter_setstate(listreviterobject *, PyObject *);
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002833
Raymond Hettingerf5b64112008-12-02 21:33:45 +00002834static PyMethodDef listreviter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002835 {"__length_hint__", (PyCFunction)listreviter_len, METH_NOARGS, length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002836 {"__reduce__", (PyCFunction)listreviter_reduce, METH_NOARGS, reduce_doc},
2837 {"__setstate__", (PyCFunction)listreviter_setstate, METH_O, setstate_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002838 {NULL, NULL} /* sentinel */
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002839};
2840
Raymond Hettinger1021c442003-11-07 15:38:09 +00002841PyTypeObject PyListRevIter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002842 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2843 "list_reverseiterator", /* tp_name */
2844 sizeof(listreviterobject), /* tp_basicsize */
2845 0, /* tp_itemsize */
2846 /* methods */
2847 (destructor)listreviter_dealloc, /* tp_dealloc */
2848 0, /* tp_print */
2849 0, /* tp_getattr */
2850 0, /* tp_setattr */
2851 0, /* tp_reserved */
2852 0, /* tp_repr */
2853 0, /* tp_as_number */
2854 0, /* tp_as_sequence */
2855 0, /* tp_as_mapping */
2856 0, /* tp_hash */
2857 0, /* tp_call */
2858 0, /* tp_str */
2859 PyObject_GenericGetAttr, /* tp_getattro */
2860 0, /* tp_setattro */
2861 0, /* tp_as_buffer */
2862 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2863 0, /* tp_doc */
2864 (traverseproc)listreviter_traverse, /* tp_traverse */
2865 0, /* tp_clear */
2866 0, /* tp_richcompare */
2867 0, /* tp_weaklistoffset */
2868 PyObject_SelfIter, /* tp_iter */
2869 (iternextfunc)listreviter_next, /* tp_iternext */
2870 listreviter_methods, /* tp_methods */
2871 0,
Raymond Hettinger1021c442003-11-07 15:38:09 +00002872};
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002873
2874static PyObject *
2875list_reversed(PyListObject *seq, PyObject *unused)
2876{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002877 listreviterobject *it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002879 it = PyObject_GC_New(listreviterobject, &PyListRevIter_Type);
2880 if (it == NULL)
2881 return NULL;
2882 assert(PyList_Check(seq));
2883 it->it_index = PyList_GET_SIZE(seq) - 1;
2884 Py_INCREF(seq);
2885 it->it_seq = seq;
2886 PyObject_GC_Track(it);
2887 return (PyObject *)it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002888}
2889
2890static void
2891listreviter_dealloc(listreviterobject *it)
2892{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002893 PyObject_GC_UnTrack(it);
2894 Py_XDECREF(it->it_seq);
2895 PyObject_GC_Del(it);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002896}
2897
2898static int
2899listreviter_traverse(listreviterobject *it, visitproc visit, void *arg)
2900{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002901 Py_VISIT(it->it_seq);
2902 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002903}
2904
2905static PyObject *
2906listreviter_next(listreviterobject *it)
2907{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002908 PyObject *item;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03002909 Py_ssize_t index;
2910 PyListObject *seq;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002911
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03002912 assert(it != NULL);
2913 seq = it->it_seq;
2914 if (seq == NULL) {
2915 return NULL;
2916 }
2917 assert(PyList_Check(seq));
2918
2919 index = it->it_index;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002920 if (index>=0 && index < PyList_GET_SIZE(seq)) {
2921 item = PyList_GET_ITEM(seq, index);
2922 it->it_index--;
2923 Py_INCREF(item);
2924 return item;
2925 }
2926 it->it_index = -1;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03002927 it->it_seq = NULL;
2928 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002929 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002930}
2931
Raymond Hettingerf5b64112008-12-02 21:33:45 +00002932static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002933listreviter_len(listreviterobject *it)
2934{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002935 Py_ssize_t len = it->it_index + 1;
2936 if (it->it_seq == NULL || PyList_GET_SIZE(it->it_seq) < len)
2937 len = 0;
2938 return PyLong_FromSsize_t(len);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002939}
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002940
2941static PyObject *
2942listreviter_reduce(listreviterobject *it)
2943{
2944 return listiter_reduce_general(it, 0);
2945}
2946
2947static PyObject *
2948listreviter_setstate(listreviterobject *it, PyObject *state)
2949{
2950 Py_ssize_t index = PyLong_AsSsize_t(state);
2951 if (index == -1 && PyErr_Occurred())
2952 return NULL;
2953 if (it->it_seq != NULL) {
2954 if (index < -1)
2955 index = -1;
2956 else if (index > PyList_GET_SIZE(it->it_seq) - 1)
2957 index = PyList_GET_SIZE(it->it_seq) - 1;
2958 it->it_index = index;
2959 }
2960 Py_RETURN_NONE;
2961}
2962
2963/* common pickling support */
2964
2965static PyObject *
2966listiter_reduce_general(void *_it, int forward)
2967{
2968 PyObject *list;
2969
2970 /* the objects are not the same, index is of different types! */
2971 if (forward) {
2972 listiterobject *it = (listiterobject *)_it;
2973 if (it->it_seq)
Victor Stinner7660b882013-06-24 23:59:24 +02002974 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002975 it->it_seq, it->it_index);
2976 } else {
2977 listreviterobject *it = (listreviterobject *)_it;
2978 if (it->it_seq)
Antoine Pitroua7013882012-04-05 00:04:20 +02002979 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("reversed"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002980 it->it_seq, it->it_index);
2981 }
2982 /* empty iterator, create an empty list */
2983 list = PyList_New(0);
2984 if (list == NULL)
2985 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +02002986 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), list);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002987}