blob: 35a49dad80f6bf7fe766a4451c178af07dd242a5 [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* List object implementation */
2
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003#include "Python.h"
Antoine Pitrou0197ff92012-03-22 14:38:16 +01004#include "accu.h"
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00006#ifdef STDC_HEADERS
7#include <stddef.h>
8#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00009#include <sys/types.h> /* For size_t */
Guido van Rossum6cd2fe01994-08-29 12:45:32 +000010#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000011
Tim Peters8d9eb102004-07-31 02:24:20 +000012/* Ensure ob_item has room for at least newsize elements, and set
13 * ob_size to newsize. If newsize > ob_size on entry, the content
14 * of the new slots at exit is undefined heap trash; it's the caller's
Ezio Melotti13925002011-03-16 11:05:33 +020015 * responsibility to overwrite them with sane values.
Tim Peters8d9eb102004-07-31 02:24:20 +000016 * The number of allocated elements may grow, shrink, or stay the same.
17 * Failure is impossible if newsize <= self.allocated on entry, although
18 * that partly relies on an assumption that the system realloc() never
19 * fails when passed a number of bytes <= the number of bytes last
20 * allocated (the C standard doesn't guarantee this, but it's hard to
21 * imagine a realloc implementation where it wouldn't be true).
22 * Note that self->ob_item may change, and even if newsize is less
23 * than ob_size on entry.
24 */
Guido van Rossuma46d51d1995-01-26 22:59:43 +000025static int
Martin v. Löwis18e16552006-02-15 17:27:45 +000026list_resize(PyListObject *self, Py_ssize_t newsize)
Guido van Rossuma46d51d1995-01-26 22:59:43 +000027{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000028 PyObject **items;
29 size_t new_allocated;
30 Py_ssize_t allocated = self->allocated;
Tim Peters65b8b842001-05-26 05:28:40 +000031
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000032 /* Bypass realloc() when a previous overallocation is large enough
33 to accommodate the newsize. If the newsize falls lower than half
34 the allocated size, then proceed with the realloc() to shrink the list.
35 */
36 if (allocated >= newsize && newsize >= (allocated >> 1)) {
37 assert(self->ob_item != NULL || newsize == 0);
38 Py_SIZE(self) = newsize;
39 return 0;
40 }
Raymond Hettinger4bb95402004-02-13 11:36:39 +000041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000042 /* This over-allocates proportional to the list size, making room
43 * for additional growth. The over-allocation is mild, but is
44 * enough to give linear-time amortized behavior over a long
45 * sequence of appends() in the presence of a poorly-performing
46 * system realloc().
47 * The growth pattern is: 0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ...
48 */
49 new_allocated = (newsize >> 3) + (newsize < 9 ? 3 : 6);
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +000050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000051 /* check for integer overflow */
52 if (new_allocated > PY_SIZE_MAX - newsize) {
53 PyErr_NoMemory();
54 return -1;
55 } else {
56 new_allocated += newsize;
57 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +000058
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000059 if (newsize == 0)
60 new_allocated = 0;
61 items = self->ob_item;
Mark Dickinsonc0420fd2011-09-19 19:18:37 +010062 if (new_allocated <= (PY_SIZE_MAX / sizeof(PyObject *)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000063 PyMem_RESIZE(items, PyObject *, new_allocated);
64 else
65 items = NULL;
66 if (items == NULL) {
67 PyErr_NoMemory();
68 return -1;
69 }
70 self->ob_item = items;
71 Py_SIZE(self) = newsize;
72 self->allocated = new_allocated;
73 return 0;
Raymond Hettinger4bb95402004-02-13 11:36:39 +000074}
Guido van Rossuma46d51d1995-01-26 22:59:43 +000075
Christian Heimes77c02eb2008-02-09 02:18:51 +000076/* Debug statistic to compare allocations with reuse through the free list */
77#undef SHOW_ALLOC_COUNT
78#ifdef SHOW_ALLOC_COUNT
79static size_t count_alloc = 0;
80static size_t count_reuse = 0;
81
82static void
83show_alloc(void)
84{
Serhiy Storchaka7e160ce2016-07-03 21:03:53 +030085 PyObject *xoptions, *value;
86 _Py_IDENTIFIER(showalloccount);
87
88 xoptions = PySys_GetXOptions();
89 if (xoptions == NULL)
90 return;
91 value = _PyDict_GetItemId(xoptions, &PyId_showalloccount);
92 if (value != Py_True)
93 return;
94
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000095 fprintf(stderr, "List allocations: %" PY_FORMAT_SIZE_T "d\n",
96 count_alloc);
97 fprintf(stderr, "List reuse through freelist: %" PY_FORMAT_SIZE_T
98 "d\n", count_reuse);
99 fprintf(stderr, "%.2f%% reuse rate\n\n",
100 (100.0*count_reuse/(count_alloc+count_reuse)));
Christian Heimes77c02eb2008-02-09 02:18:51 +0000101}
102#endif
103
Raymond Hettinger0468e412004-05-05 05:37:53 +0000104/* Empty list reuse scheme to save calls to malloc and free */
Christian Heimes2202f872008-02-06 14:31:34 +0000105#ifndef PyList_MAXFREELIST
106#define PyList_MAXFREELIST 80
107#endif
108static PyListObject *free_list[PyList_MAXFREELIST];
109static int numfree = 0;
Raymond Hettinger0468e412004-05-05 05:37:53 +0000110
Antoine Pitrou9a812cb2011-11-15 00:00:12 +0100111int
112PyList_ClearFreeList(void)
Raymond Hettingerfb09f0e2004-10-07 03:58:07 +0000113{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000114 PyListObject *op;
Antoine Pitrou9a812cb2011-11-15 00:00:12 +0100115 int ret = numfree;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000116 while (numfree) {
117 op = free_list[--numfree];
118 assert(PyList_CheckExact(op));
119 PyObject_GC_Del(op);
120 }
Antoine Pitrou9a812cb2011-11-15 00:00:12 +0100121 return ret;
122}
123
124void
125PyList_Fini(void)
126{
127 PyList_ClearFreeList();
Raymond Hettingerfb09f0e2004-10-07 03:58:07 +0000128}
129
David Malcolm49526f42012-06-22 14:55:41 -0400130/* Print summary info about the state of the optimized allocator */
131void
132_PyList_DebugMallocStats(FILE *out)
133{
134 _PyDebugAllocatorStats(out,
135 "free PyListObject",
136 numfree, sizeof(PyListObject));
137}
138
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000139PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000140PyList_New(Py_ssize_t size)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000141{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000142 PyListObject *op;
Christian Heimes77c02eb2008-02-09 02:18:51 +0000143#ifdef SHOW_ALLOC_COUNT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000144 static int initialized = 0;
145 if (!initialized) {
146 Py_AtExit(show_alloc);
147 initialized = 1;
148 }
Christian Heimes77c02eb2008-02-09 02:18:51 +0000149#endif
Tim Peters3986d4e2004-07-29 02:28:42 +0000150
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000151 if (size < 0) {
152 PyErr_BadInternalCall();
153 return NULL;
154 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000155 if (numfree) {
156 numfree--;
157 op = free_list[numfree];
158 _Py_NewReference((PyObject *)op);
Christian Heimes77c02eb2008-02-09 02:18:51 +0000159#ifdef SHOW_ALLOC_COUNT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000160 count_reuse++;
Christian Heimes77c02eb2008-02-09 02:18:51 +0000161#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000162 } else {
163 op = PyObject_GC_New(PyListObject, &PyList_Type);
164 if (op == NULL)
165 return NULL;
Christian Heimes77c02eb2008-02-09 02:18:51 +0000166#ifdef SHOW_ALLOC_COUNT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000167 count_alloc++;
Christian Heimes77c02eb2008-02-09 02:18:51 +0000168#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000169 }
170 if (size <= 0)
171 op->ob_item = NULL;
172 else {
Mark Dickinson5d132382016-08-21 08:55:15 +0100173 op->ob_item = (PyObject **) PyMem_Calloc(size, sizeof(PyObject *));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000174 if (op->ob_item == NULL) {
175 Py_DECREF(op);
176 return PyErr_NoMemory();
177 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000178 }
179 Py_SIZE(op) = size;
180 op->allocated = size;
181 _PyObject_GC_TRACK(op);
182 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000183}
184
Martin v. Löwis18e16552006-02-15 17:27:45 +0000185Py_ssize_t
Fred Drakea2f55112000-07-09 15:16:51 +0000186PyList_Size(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000187{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000188 if (!PyList_Check(op)) {
189 PyErr_BadInternalCall();
190 return -1;
191 }
192 else
193 return Py_SIZE(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000194}
195
Raymond Hettingerfdfe6182004-05-05 06:28:16 +0000196static PyObject *indexerr = NULL;
Guido van Rossum929f1b81996-08-09 20:51:27 +0000197
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000198PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000199PyList_GetItem(PyObject *op, Py_ssize_t i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000200{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000201 if (!PyList_Check(op)) {
202 PyErr_BadInternalCall();
203 return NULL;
204 }
205 if (i < 0 || i >= Py_SIZE(op)) {
206 if (indexerr == NULL) {
207 indexerr = PyUnicode_FromString(
208 "list index out of range");
209 if (indexerr == NULL)
210 return NULL;
211 }
212 PyErr_SetObject(PyExc_IndexError, indexerr);
213 return NULL;
214 }
215 return ((PyListObject *)op) -> ob_item[i];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000216}
217
218int
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200219PyList_SetItem(PyObject *op, Py_ssize_t i,
220 PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000221{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200222 PyObject **p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000223 if (!PyList_Check(op)) {
224 Py_XDECREF(newitem);
225 PyErr_BadInternalCall();
226 return -1;
227 }
228 if (i < 0 || i >= Py_SIZE(op)) {
229 Py_XDECREF(newitem);
230 PyErr_SetString(PyExc_IndexError,
231 "list assignment index out of range");
232 return -1;
233 }
234 p = ((PyListObject *)op) -> ob_item + i;
Serhiy Storchakaec397562016-04-06 09:50:03 +0300235 Py_XSETREF(*p, newitem);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000236 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000237}
238
239static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000240ins1(PyListObject *self, Py_ssize_t where, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000241{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000242 Py_ssize_t i, n = Py_SIZE(self);
243 PyObject **items;
244 if (v == NULL) {
245 PyErr_BadInternalCall();
246 return -1;
247 }
248 if (n == PY_SSIZE_T_MAX) {
249 PyErr_SetString(PyExc_OverflowError,
250 "cannot add more objects to list");
251 return -1;
252 }
Tim Petersb38e2b62004-07-29 02:29:26 +0000253
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800254 if (list_resize(self, n+1) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000255 return -1;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000256
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000257 if (where < 0) {
258 where += n;
259 if (where < 0)
260 where = 0;
261 }
262 if (where > n)
263 where = n;
264 items = self->ob_item;
265 for (i = n; --i >= where; )
266 items[i+1] = items[i];
267 Py_INCREF(v);
268 items[where] = v;
269 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000270}
271
272int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000273PyList_Insert(PyObject *op, Py_ssize_t where, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000274{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000275 if (!PyList_Check(op)) {
276 PyErr_BadInternalCall();
277 return -1;
278 }
279 return ins1((PyListObject *)op, where, newitem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000280}
281
Raymond Hettinger40a03822004-04-12 13:05:09 +0000282static int
283app1(PyListObject *self, PyObject *v)
284{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000285 Py_ssize_t n = PyList_GET_SIZE(self);
Raymond Hettinger40a03822004-04-12 13:05:09 +0000286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000287 assert (v != NULL);
288 if (n == PY_SSIZE_T_MAX) {
289 PyErr_SetString(PyExc_OverflowError,
290 "cannot add more objects to list");
291 return -1;
292 }
Raymond Hettinger40a03822004-04-12 13:05:09 +0000293
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800294 if (list_resize(self, n+1) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000295 return -1;
Raymond Hettinger40a03822004-04-12 13:05:09 +0000296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000297 Py_INCREF(v);
298 PyList_SET_ITEM(self, n, v);
299 return 0;
Raymond Hettinger40a03822004-04-12 13:05:09 +0000300}
301
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000302int
Fred Drakea2f55112000-07-09 15:16:51 +0000303PyList_Append(PyObject *op, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000304{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000305 if (PyList_Check(op) && (newitem != NULL))
306 return app1((PyListObject *)op, newitem);
307 PyErr_BadInternalCall();
308 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000309}
310
311/* Methods */
312
313static void
Fred Drakea2f55112000-07-09 15:16:51 +0000314list_dealloc(PyListObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000315{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000316 Py_ssize_t i;
317 PyObject_GC_UnTrack(op);
318 Py_TRASHCAN_SAFE_BEGIN(op)
319 if (op->ob_item != NULL) {
320 /* Do it backwards, for Christian Tismer.
321 There's a simple test case where somehow this reduces
322 thrashing when a *very* large list is created and
323 immediately deleted. */
324 i = Py_SIZE(op);
325 while (--i >= 0) {
326 Py_XDECREF(op->ob_item[i]);
327 }
328 PyMem_FREE(op->ob_item);
329 }
330 if (numfree < PyList_MAXFREELIST && PyList_CheckExact(op))
331 free_list[numfree++] = op;
332 else
333 Py_TYPE(op)->tp_free((PyObject *)op);
334 Py_TRASHCAN_SAFE_END(op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000335}
336
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000337static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000338list_repr(PyListObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000339{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000340 Py_ssize_t i;
Victor Stinner5c733472013-11-18 21:11:57 +0100341 PyObject *s;
Victor Stinner5c733472013-11-18 21:11:57 +0100342 _PyUnicodeWriter writer;
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200343
344 if (Py_SIZE(v) == 0) {
345 return PyUnicode_FromString("[]");
346 }
347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000348 i = Py_ReprEnter((PyObject*)v);
349 if (i != 0) {
350 return i > 0 ? PyUnicode_FromString("[...]") : NULL;
351 }
Tim Petersa7259592001-06-16 05:11:17 +0000352
Victor Stinner5c733472013-11-18 21:11:57 +0100353 _PyUnicodeWriter_Init(&writer);
354 writer.overallocate = 1;
Victor Stinnerb8fb1972013-11-18 22:15:44 +0100355 /* "[" + "1" + ", 2" * (len - 1) + "]" */
356 writer.min_length = 1 + 1 + (2 + 1) * (Py_SIZE(v) - 1) + 1;
Tim Petersa7259592001-06-16 05:11:17 +0000357
Victor Stinner5c733472013-11-18 21:11:57 +0100358 if (_PyUnicodeWriter_WriteChar(&writer, '[') < 0)
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200359 goto error;
Tim Petersa7259592001-06-16 05:11:17 +0000360
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000361 /* Do repr() on each element. Note that this may mutate the list,
362 so must refetch the list size on each iteration. */
363 for (i = 0; i < Py_SIZE(v); ++i) {
Victor Stinner5c733472013-11-18 21:11:57 +0100364 if (i > 0) {
Victor Stinner4a587072013-11-19 12:54:53 +0100365 if (_PyUnicodeWriter_WriteASCIIString(&writer, ", ", 2) < 0)
Victor Stinner5c733472013-11-18 21:11:57 +0100366 goto error;
367 }
368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000369 if (Py_EnterRecursiveCall(" while getting the repr of a list"))
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200370 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000371 s = PyObject_Repr(v->ob_item[i]);
372 Py_LeaveRecursiveCall();
Victor Stinner5c733472013-11-18 21:11:57 +0100373 if (s == NULL)
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200374 goto error;
Victor Stinner5c733472013-11-18 21:11:57 +0100375
376 if (_PyUnicodeWriter_WriteStr(&writer, s) < 0) {
377 Py_DECREF(s);
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200378 goto error;
Victor Stinner5c733472013-11-18 21:11:57 +0100379 }
380 Py_DECREF(s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000381 }
Victor Stinner5c733472013-11-18 21:11:57 +0100382
Victor Stinner4d3f1092013-11-19 12:09:00 +0100383 writer.overallocate = 0;
Victor Stinner5c733472013-11-18 21:11:57 +0100384 if (_PyUnicodeWriter_WriteChar(&writer, ']') < 0)
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200385 goto error;
Tim Petersa7259592001-06-16 05:11:17 +0000386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000387 Py_ReprLeave((PyObject *)v);
Victor Stinner5c733472013-11-18 21:11:57 +0100388 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200389
390error:
Victor Stinner5c733472013-11-18 21:11:57 +0100391 _PyUnicodeWriter_Dealloc(&writer);
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200392 Py_ReprLeave((PyObject *)v);
393 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000394}
395
Martin v. Löwis18e16552006-02-15 17:27:45 +0000396static Py_ssize_t
Fred Drakea2f55112000-07-09 15:16:51 +0000397list_length(PyListObject *a)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000398{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000399 return Py_SIZE(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000400}
401
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000402static int
Fred Drakea2f55112000-07-09 15:16:51 +0000403list_contains(PyListObject *a, PyObject *el)
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000404{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000405 Py_ssize_t i;
406 int cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000408 for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(a); ++i)
409 cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i),
410 Py_EQ);
411 return cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000412}
413
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000414static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000415list_item(PyListObject *a, Py_ssize_t i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000416{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 if (i < 0 || i >= Py_SIZE(a)) {
418 if (indexerr == NULL) {
419 indexerr = PyUnicode_FromString(
420 "list index out of range");
421 if (indexerr == NULL)
422 return NULL;
423 }
424 PyErr_SetObject(PyExc_IndexError, indexerr);
425 return NULL;
426 }
427 Py_INCREF(a->ob_item[i]);
428 return a->ob_item[i];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000429}
430
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000431static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000432list_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000433{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000434 PyListObject *np;
435 PyObject **src, **dest;
436 Py_ssize_t i, len;
437 if (ilow < 0)
438 ilow = 0;
439 else if (ilow > Py_SIZE(a))
440 ilow = Py_SIZE(a);
441 if (ihigh < ilow)
442 ihigh = ilow;
443 else if (ihigh > Py_SIZE(a))
444 ihigh = Py_SIZE(a);
445 len = ihigh - ilow;
446 np = (PyListObject *) PyList_New(len);
447 if (np == NULL)
448 return NULL;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000450 src = a->ob_item + ilow;
451 dest = np->ob_item;
452 for (i = 0; i < len; i++) {
453 PyObject *v = src[i];
454 Py_INCREF(v);
455 dest[i] = v;
456 }
457 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000458}
459
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000460PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000461PyList_GetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum234f9421993-06-17 12:35:49 +0000462{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000463 if (!PyList_Check(a)) {
464 PyErr_BadInternalCall();
465 return NULL;
466 }
467 return list_slice((PyListObject *)a, ilow, ihigh);
Guido van Rossum234f9421993-06-17 12:35:49 +0000468}
469
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000470static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000471list_concat(PyListObject *a, PyObject *bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000472{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000473 Py_ssize_t size;
474 Py_ssize_t i;
475 PyObject **src, **dest;
476 PyListObject *np;
477 if (!PyList_Check(bb)) {
478 PyErr_Format(PyExc_TypeError,
479 "can only concatenate list (not \"%.200s\") to list",
480 bb->ob_type->tp_name);
481 return NULL;
482 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000483#define b ((PyListObject *)bb)
Martin Panterb93d8632016-07-25 02:39:20 +0000484 if (Py_SIZE(a) > PY_SSIZE_T_MAX - Py_SIZE(b))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 return PyErr_NoMemory();
Martin Panterb93d8632016-07-25 02:39:20 +0000486 size = Py_SIZE(a) + Py_SIZE(b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000487 np = (PyListObject *) PyList_New(size);
488 if (np == NULL) {
489 return NULL;
490 }
491 src = a->ob_item;
492 dest = np->ob_item;
493 for (i = 0; i < Py_SIZE(a); i++) {
494 PyObject *v = src[i];
495 Py_INCREF(v);
496 dest[i] = v;
497 }
498 src = b->ob_item;
499 dest = np->ob_item + Py_SIZE(a);
500 for (i = 0; i < Py_SIZE(b); i++) {
501 PyObject *v = src[i];
502 Py_INCREF(v);
503 dest[i] = v;
504 }
505 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000506#undef b
507}
508
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000509static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000510list_repeat(PyListObject *a, Py_ssize_t n)
Guido van Rossumed98d481991-03-06 13:07:53 +0000511{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 Py_ssize_t i, j;
513 Py_ssize_t size;
514 PyListObject *np;
515 PyObject **p, **items;
516 PyObject *elem;
517 if (n < 0)
518 n = 0;
Mark Dickinsonc0420fd2011-09-19 19:18:37 +0100519 if (n > 0 && Py_SIZE(a) > PY_SSIZE_T_MAX / n)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000520 return PyErr_NoMemory();
Mark Dickinsonc0420fd2011-09-19 19:18:37 +0100521 size = Py_SIZE(a) * n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000522 if (size == 0)
523 return PyList_New(0);
524 np = (PyListObject *) PyList_New(size);
525 if (np == NULL)
526 return NULL;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000528 items = np->ob_item;
529 if (Py_SIZE(a) == 1) {
530 elem = a->ob_item[0];
531 for (i = 0; i < n; i++) {
532 items[i] = elem;
533 Py_INCREF(elem);
534 }
535 return (PyObject *) np;
536 }
537 p = np->ob_item;
538 items = a->ob_item;
539 for (i = 0; i < n; i++) {
540 for (j = 0; j < Py_SIZE(a); j++) {
541 *p = items[j];
542 Py_INCREF(*p);
543 p++;
544 }
545 }
546 return (PyObject *) np;
Guido van Rossumed98d481991-03-06 13:07:53 +0000547}
548
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000549static int
Armin Rigo93677f02004-07-29 12:40:23 +0000550list_clear(PyListObject *a)
551{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000552 Py_ssize_t i;
553 PyObject **item = a->ob_item;
554 if (item != NULL) {
555 /* Because XDECREF can recursively invoke operations on
556 this list, we make it empty first. */
557 i = Py_SIZE(a);
558 Py_SIZE(a) = 0;
559 a->ob_item = NULL;
560 a->allocated = 0;
561 while (--i >= 0) {
562 Py_XDECREF(item[i]);
563 }
564 PyMem_FREE(item);
565 }
566 /* Never fails; the return value can be ignored.
567 Note that there is no guarantee that the list is actually empty
568 at this point, because XDECREF may have populated it again! */
569 return 0;
Armin Rigo93677f02004-07-29 12:40:23 +0000570}
571
Tim Peters8fc4a912004-07-31 21:53:19 +0000572/* a[ilow:ihigh] = v if v != NULL.
573 * del a[ilow:ihigh] if v == NULL.
574 *
575 * Special speed gimmick: when v is NULL and ihigh - ilow <= 8, it's
576 * guaranteed the call cannot fail.
577 */
Armin Rigo93677f02004-07-29 12:40:23 +0000578static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000579list_ass_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000580{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000581 /* Because [X]DECREF can recursively invoke list operations on
582 this list, we must postpone all [X]DECREF activity until
583 after the list is back in its canonical shape. Therefore
584 we must allocate an additional array, 'recycle', into which
585 we temporarily copy the items that are deleted from the
586 list. :-( */
587 PyObject *recycle_on_stack[8];
588 PyObject **recycle = recycle_on_stack; /* will allocate more if needed */
589 PyObject **item;
590 PyObject **vitem = NULL;
591 PyObject *v_as_SF = NULL; /* PySequence_Fast(v) */
592 Py_ssize_t n; /* # of elements in replacement list */
593 Py_ssize_t norig; /* # of elements in list getting replaced */
594 Py_ssize_t d; /* Change in size */
595 Py_ssize_t k;
596 size_t s;
597 int result = -1; /* guilty until proved innocent */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000598#define b ((PyListObject *)v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000599 if (v == NULL)
600 n = 0;
601 else {
602 if (a == b) {
603 /* Special case "a[i:j] = a" -- copy b first */
604 v = list_slice(b, 0, Py_SIZE(b));
605 if (v == NULL)
606 return result;
607 result = list_ass_slice(a, ilow, ihigh, v);
608 Py_DECREF(v);
609 return result;
610 }
611 v_as_SF = PySequence_Fast(v, "can only assign an iterable");
612 if(v_as_SF == NULL)
613 goto Error;
614 n = PySequence_Fast_GET_SIZE(v_as_SF);
615 vitem = PySequence_Fast_ITEMS(v_as_SF);
616 }
617 if (ilow < 0)
618 ilow = 0;
619 else if (ilow > Py_SIZE(a))
620 ilow = Py_SIZE(a);
Tim Peters8d9eb102004-07-31 02:24:20 +0000621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 if (ihigh < ilow)
623 ihigh = ilow;
624 else if (ihigh > Py_SIZE(a))
625 ihigh = Py_SIZE(a);
Armin Rigo93677f02004-07-29 12:40:23 +0000626
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 norig = ihigh - ilow;
628 assert(norig >= 0);
629 d = n - norig;
630 if (Py_SIZE(a) + d == 0) {
631 Py_XDECREF(v_as_SF);
632 return list_clear(a);
633 }
634 item = a->ob_item;
635 /* recycle the items that we are about to remove */
636 s = norig * sizeof(PyObject *);
637 if (s > sizeof(recycle_on_stack)) {
638 recycle = (PyObject **)PyMem_MALLOC(s);
639 if (recycle == NULL) {
640 PyErr_NoMemory();
641 goto Error;
642 }
643 }
644 memcpy(recycle, &item[ilow], s);
Tim Peters8d9eb102004-07-31 02:24:20 +0000645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 if (d < 0) { /* Delete -d items */
Victor Stinner2c40f642013-07-19 23:06:21 +0200647 Py_ssize_t tail;
648 tail = (Py_SIZE(a) - ihigh) * sizeof(PyObject *);
649 memmove(&item[ihigh+d], &item[ihigh], tail);
650 if (list_resize(a, Py_SIZE(a) + d) < 0) {
651 memmove(&item[ihigh], &item[ihigh+d], tail);
652 memcpy(&item[ilow], recycle, s);
653 goto Error;
654 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000655 item = a->ob_item;
656 }
657 else if (d > 0) { /* Insert d items */
658 k = Py_SIZE(a);
659 if (list_resize(a, k+d) < 0)
660 goto Error;
661 item = a->ob_item;
662 memmove(&item[ihigh+d], &item[ihigh],
663 (k - ihigh)*sizeof(PyObject *));
664 }
665 for (k = 0; k < n; k++, ilow++) {
666 PyObject *w = vitem[k];
667 Py_XINCREF(w);
668 item[ilow] = w;
669 }
670 for (k = norig - 1; k >= 0; --k)
671 Py_XDECREF(recycle[k]);
672 result = 0;
Tim Peters8d9eb102004-07-31 02:24:20 +0000673 Error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000674 if (recycle != recycle_on_stack)
675 PyMem_FREE(recycle);
676 Py_XDECREF(v_as_SF);
677 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000678#undef b
679}
680
Guido van Rossum234f9421993-06-17 12:35:49 +0000681int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000682PyList_SetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum234f9421993-06-17 12:35:49 +0000683{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000684 if (!PyList_Check(a)) {
685 PyErr_BadInternalCall();
686 return -1;
687 }
688 return list_ass_slice((PyListObject *)a, ilow, ihigh, v);
Guido van Rossum234f9421993-06-17 12:35:49 +0000689}
690
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000691static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000692list_inplace_repeat(PyListObject *self, Py_ssize_t n)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000693{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000694 PyObject **items;
695 Py_ssize_t size, i, j, p;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000696
697
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000698 size = PyList_GET_SIZE(self);
699 if (size == 0 || n == 1) {
700 Py_INCREF(self);
701 return (PyObject *)self;
702 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000703
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000704 if (n < 1) {
705 (void)list_clear(self);
706 Py_INCREF(self);
707 return (PyObject *)self;
708 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000709
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000710 if (size > PY_SSIZE_T_MAX / n) {
711 return PyErr_NoMemory();
712 }
Christian Heimesaf98da12008-01-27 15:18:18 +0000713
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800714 if (list_resize(self, size*n) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 return NULL;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000716
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000717 p = size;
718 items = self->ob_item;
719 for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */
720 for (j = 0; j < size; j++) {
721 PyObject *o = items[j];
722 Py_INCREF(o);
723 items[p++] = o;
724 }
725 }
726 Py_INCREF(self);
727 return (PyObject *)self;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000728}
729
Guido van Rossum4a450d01991-04-03 19:05:18 +0000730static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000731list_ass_item(PyListObject *a, Py_ssize_t i, PyObject *v)
Guido van Rossum4a450d01991-04-03 19:05:18 +0000732{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000733 if (i < 0 || i >= Py_SIZE(a)) {
734 PyErr_SetString(PyExc_IndexError,
735 "list assignment index out of range");
736 return -1;
737 }
738 if (v == NULL)
739 return list_ass_slice(a, i, i+1, v);
740 Py_INCREF(v);
Serhiy Storchakaf01e4082016-04-10 18:12:01 +0300741 Py_SETREF(a->ob_item[i], v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000742 return 0;
Guido van Rossum4a450d01991-04-03 19:05:18 +0000743}
744
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000745static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000746listinsert(PyListObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000747{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000748 Py_ssize_t i;
749 PyObject *v;
750 if (!PyArg_ParseTuple(args, "nO:insert", &i, &v))
751 return NULL;
752 if (ins1(self, i, v) == 0)
753 Py_RETURN_NONE;
754 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000755}
756
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000757static PyObject *
Eli Benderskycbbaa962011-02-25 05:47:53 +0000758listclear(PyListObject *self)
759{
760 list_clear(self);
761 Py_RETURN_NONE;
762}
763
764static PyObject *
765listcopy(PyListObject *self)
766{
767 return list_slice(self, 0, Py_SIZE(self));
768}
769
770static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000771listappend(PyListObject *self, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000772{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000773 if (app1(self, v) == 0)
774 Py_RETURN_NONE;
775 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000776}
777
Barry Warsawdedf6d61998-10-09 16:37:25 +0000778static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000779listextend(PyListObject *self, PyObject *b)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000780{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 PyObject *it; /* iter(v) */
782 Py_ssize_t m; /* size of self */
783 Py_ssize_t n; /* guess for size of b */
784 Py_ssize_t mn; /* m + n */
785 Py_ssize_t i;
786 PyObject *(*iternext)(PyObject *);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000787
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000788 /* Special cases:
789 1) lists and tuples which can use PySequence_Fast ops
790 2) extending self to self requires making a copy first
791 */
792 if (PyList_CheckExact(b) || PyTuple_CheckExact(b) || (PyObject *)self == b) {
793 PyObject **src, **dest;
794 b = PySequence_Fast(b, "argument must be iterable");
795 if (!b)
796 return NULL;
797 n = PySequence_Fast_GET_SIZE(b);
798 if (n == 0) {
799 /* short circuit when b is empty */
800 Py_DECREF(b);
801 Py_RETURN_NONE;
802 }
803 m = Py_SIZE(self);
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800804 if (list_resize(self, m + n) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000805 Py_DECREF(b);
806 return NULL;
807 }
808 /* note that we may still have self == b here for the
809 * situation a.extend(a), but the following code works
810 * in that case too. Just make sure to resize self
811 * before calling PySequence_Fast_ITEMS.
812 */
813 /* populate the end of self with b's items */
814 src = PySequence_Fast_ITEMS(b);
815 dest = self->ob_item + m;
816 for (i = 0; i < n; i++) {
817 PyObject *o = src[i];
818 Py_INCREF(o);
819 dest[i] = o;
820 }
821 Py_DECREF(b);
822 Py_RETURN_NONE;
823 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000824
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000825 it = PyObject_GetIter(b);
826 if (it == NULL)
827 return NULL;
828 iternext = *it->ob_type->tp_iternext;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000829
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 /* Guess a result list size. */
Armin Ronacheraa9a79d2012-10-06 14:03:24 +0200831 n = PyObject_LengthHint(b, 8);
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800832 if (n < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000833 Py_DECREF(it);
834 return NULL;
835 }
836 m = Py_SIZE(self);
Martin Panterb93d8632016-07-25 02:39:20 +0000837 if (m > PY_SSIZE_T_MAX - n) {
838 /* m + n overflowed; on the chance that n lied, and there really
839 * is enough room, ignore it. If n was telling the truth, we'll
840 * eventually run out of memory during the loop.
841 */
842 }
843 else {
844 mn = m + n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000845 /* Make room. */
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800846 if (list_resize(self, mn) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000847 goto error;
848 /* Make the list sane again. */
849 Py_SIZE(self) = m;
850 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000851
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000852 /* Run iterator to exhaustion. */
853 for (;;) {
854 PyObject *item = iternext(it);
855 if (item == NULL) {
856 if (PyErr_Occurred()) {
857 if (PyErr_ExceptionMatches(PyExc_StopIteration))
858 PyErr_Clear();
859 else
860 goto error;
861 }
862 break;
863 }
864 if (Py_SIZE(self) < self->allocated) {
865 /* steals ref */
866 PyList_SET_ITEM(self, Py_SIZE(self), item);
867 ++Py_SIZE(self);
868 }
869 else {
870 int status = app1(self, item);
871 Py_DECREF(item); /* append creates a new ref */
872 if (status < 0)
873 goto error;
874 }
875 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000877 /* Cut back result list if initial guess was too large. */
Victor Stinner32fd6ea2013-07-16 21:45:58 +0200878 if (Py_SIZE(self) < self->allocated) {
879 if (list_resize(self, Py_SIZE(self)) < 0)
880 goto error;
881 }
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000883 Py_DECREF(it);
884 Py_RETURN_NONE;
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000885
886 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000887 Py_DECREF(it);
888 return NULL;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000889}
890
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000891PyObject *
892_PyList_Extend(PyListObject *self, PyObject *b)
893{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 return listextend(self, b);
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000895}
896
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000897static PyObject *
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000898list_inplace_concat(PyListObject *self, PyObject *other)
899{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000900 PyObject *result;
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000901
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000902 result = listextend(self, other);
903 if (result == NULL)
904 return result;
905 Py_DECREF(result);
906 Py_INCREF(self);
907 return (PyObject *)self;
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000908}
909
910static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000911listpop(PyListObject *self, PyObject *args)
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000912{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 Py_ssize_t i = -1;
914 PyObject *v;
915 int status;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000916
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000917 if (!PyArg_ParseTuple(args, "|n:pop", &i))
918 return NULL;
Thomas Wouters89f507f2006-12-13 04:49:30 +0000919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 if (Py_SIZE(self) == 0) {
921 /* Special-case most common failure cause */
922 PyErr_SetString(PyExc_IndexError, "pop from empty list");
923 return NULL;
924 }
925 if (i < 0)
926 i += Py_SIZE(self);
927 if (i < 0 || i >= Py_SIZE(self)) {
928 PyErr_SetString(PyExc_IndexError, "pop index out of range");
929 return NULL;
930 }
931 v = self->ob_item[i];
932 if (i == Py_SIZE(self) - 1) {
933 status = list_resize(self, Py_SIZE(self) - 1);
Victor Stinnerb27cd3e2013-07-08 22:20:44 +0200934 if (status >= 0)
935 return v; /* and v now owns the reference the list had */
936 else
937 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 }
939 Py_INCREF(v);
940 status = list_ass_slice(self, i, i+1, (PyObject *)NULL);
Victor Stinner095d99f2013-07-17 21:58:01 +0200941 if (status < 0) {
942 Py_DECREF(v);
943 return NULL;
944 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000945 return v;
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000946}
947
Tim Peters8e2e7ca2002-07-19 02:33:08 +0000948/* Reverse a slice of a list in place, from lo up to (exclusive) hi. */
949static void
950reverse_slice(PyObject **lo, PyObject **hi)
951{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 assert(lo && hi);
Tim Peters8e2e7ca2002-07-19 02:33:08 +0000953
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000954 --hi;
955 while (lo < hi) {
956 PyObject *t = *lo;
957 *lo = *hi;
958 *hi = t;
959 ++lo;
960 --hi;
961 }
Tim Peters8e2e7ca2002-07-19 02:33:08 +0000962}
963
Tim Petersa64dc242002-08-01 02:13:36 +0000964/* Lots of code for an adaptive, stable, natural mergesort. There are many
965 * pieces to this algorithm; read listsort.txt for overviews and details.
966 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000967
Daniel Stutzbach98338222010-12-02 21:55:33 +0000968/* A sortslice contains a pointer to an array of keys and a pointer to
969 * an array of corresponding values. In other words, keys[i]
970 * corresponds with values[i]. If values == NULL, then the keys are
971 * also the values.
972 *
973 * Several convenience routines are provided here, so that keys and
974 * values are always moved in sync.
975 */
976
977typedef struct {
978 PyObject **keys;
979 PyObject **values;
980} sortslice;
981
982Py_LOCAL_INLINE(void)
983sortslice_copy(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j)
984{
985 s1->keys[i] = s2->keys[j];
986 if (s1->values != NULL)
987 s1->values[i] = s2->values[j];
988}
989
990Py_LOCAL_INLINE(void)
Benjamin Peterson9efdcca2010-12-03 01:44:10 +0000991sortslice_copy_incr(sortslice *dst, sortslice *src)
992{
Daniel Stutzbach98338222010-12-02 21:55:33 +0000993 *dst->keys++ = *src->keys++;
994 if (dst->values != NULL)
995 *dst->values++ = *src->values++;
996}
997
998Py_LOCAL_INLINE(void)
Benjamin Peterson9efdcca2010-12-03 01:44:10 +0000999sortslice_copy_decr(sortslice *dst, sortslice *src)
1000{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001001 *dst->keys-- = *src->keys--;
1002 if (dst->values != NULL)
1003 *dst->values-- = *src->values--;
1004}
1005
1006
1007Py_LOCAL_INLINE(void)
1008sortslice_memcpy(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j,
Benjamin Peterson9efdcca2010-12-03 01:44:10 +00001009 Py_ssize_t n)
1010{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001011 memcpy(&s1->keys[i], &s2->keys[j], sizeof(PyObject *) * n);
1012 if (s1->values != NULL)
1013 memcpy(&s1->values[i], &s2->values[j], sizeof(PyObject *) * n);
1014}
1015
1016Py_LOCAL_INLINE(void)
1017sortslice_memmove(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j,
Benjamin Peterson9efdcca2010-12-03 01:44:10 +00001018 Py_ssize_t n)
1019{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001020 memmove(&s1->keys[i], &s2->keys[j], sizeof(PyObject *) * n);
1021 if (s1->values != NULL)
1022 memmove(&s1->values[i], &s2->values[j], sizeof(PyObject *) * n);
1023}
1024
1025Py_LOCAL_INLINE(void)
Benjamin Peterson9efdcca2010-12-03 01:44:10 +00001026sortslice_advance(sortslice *slice, Py_ssize_t n)
1027{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001028 slice->keys += n;
1029 if (slice->values != NULL)
1030 slice->values += n;
1031}
1032
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001033/* Comparison function: PyObject_RichCompareBool with Py_LT.
Tim Petersa64dc242002-08-01 02:13:36 +00001034 * Returns -1 on error, 1 if x < y, 0 if x >= y.
1035 */
Guido van Rossum3f236de1996-12-10 23:55:39 +00001036
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001037#define ISLT(X, Y) (PyObject_RichCompareBool(X, Y, Py_LT))
Tim Peters66860f62002-08-04 17:47:26 +00001038
1039/* Compare X to Y via "<". Goto "fail" if the comparison raises an
Tim Petersa8c974c2002-07-19 03:30:57 +00001040 error. Else "k" is set to true iff X<Y, and an "if (k)" block is
1041 started. It makes more sense in context <wink>. X and Y are PyObject*s.
1042*/
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001043#define IFLT(X, Y) if ((k = ISLT(X, Y)) < 0) goto fail; \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 if (k)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001045
1046/* binarysort is the best method for sorting small arrays: it does
1047 few compares, but can do data movement quadratic in the number of
1048 elements.
Guido van Rossum42812581998-06-17 14:15:44 +00001049 [lo, hi) is a contiguous slice of a list, and is sorted via
Tim Petersa8c974c2002-07-19 03:30:57 +00001050 binary insertion. This sort is stable.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001051 On entry, must have lo <= start <= hi, and that [lo, start) is already
1052 sorted (pass start == lo if you don't know!).
Tim Petersa8c974c2002-07-19 03:30:57 +00001053 If islt() complains return -1, else 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001054 Even in case of error, the output slice will be some permutation of
1055 the input (nothing is lost or duplicated).
1056*/
Guido van Rossum3f236de1996-12-10 23:55:39 +00001057static int
Daniel Stutzbach98338222010-12-02 21:55:33 +00001058binarysort(sortslice lo, PyObject **hi, PyObject **start)
Guido van Rossum3f236de1996-12-10 23:55:39 +00001059{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001060 Py_ssize_t k;
1061 PyObject **l, **p, **r;
1062 PyObject *pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001063
Daniel Stutzbach98338222010-12-02 21:55:33 +00001064 assert(lo.keys <= start && start <= hi);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001065 /* assert [lo, start) is sorted */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001066 if (lo.keys == start)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001067 ++start;
1068 for (; start < hi; ++start) {
1069 /* set l to where *start belongs */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001070 l = lo.keys;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 r = start;
1072 pivot = *r;
1073 /* Invariants:
1074 * pivot >= all in [lo, l).
1075 * pivot < all in [r, start).
1076 * The second is vacuously true at the start.
1077 */
1078 assert(l < r);
1079 do {
1080 p = l + ((r - l) >> 1);
1081 IFLT(pivot, *p)
1082 r = p;
1083 else
1084 l = p+1;
1085 } while (l < r);
1086 assert(l == r);
1087 /* The invariants still hold, so pivot >= all in [lo, l) and
1088 pivot < all in [l, start), so pivot belongs at l. Note
1089 that if there are elements equal to pivot, l points to the
1090 first slot after them -- that's why this sort is stable.
1091 Slide over to make room.
1092 Caution: using memmove is much slower under MSVC 5;
1093 we're not usually moving many slots. */
1094 for (p = start; p > l; --p)
1095 *p = *(p-1);
1096 *l = pivot;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001097 if (lo.values != NULL) {
1098 Py_ssize_t offset = lo.values - lo.keys;
1099 p = start + offset;
1100 pivot = *p;
1101 l += offset;
1102 for (p = start + offset; p > l; --p)
1103 *p = *(p-1);
1104 *l = pivot;
1105 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 }
1107 return 0;
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001108
1109 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001110 return -1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001111}
1112
Tim Petersa64dc242002-08-01 02:13:36 +00001113/*
1114Return the length of the run beginning at lo, in the slice [lo, hi). lo < hi
1115is required on entry. "A run" is the longest ascending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001116
Tim Petersa64dc242002-08-01 02:13:36 +00001117 lo[0] <= lo[1] <= lo[2] <= ...
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001118
Tim Petersa64dc242002-08-01 02:13:36 +00001119or the longest descending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001120
Tim Petersa64dc242002-08-01 02:13:36 +00001121 lo[0] > lo[1] > lo[2] > ...
Tim Peters3b01a122002-07-19 02:35:45 +00001122
Tim Petersa64dc242002-08-01 02:13:36 +00001123Boolean *descending is set to 0 in the former case, or to 1 in the latter.
1124For its intended use in a stable mergesort, the strictness of the defn of
1125"descending" is needed so that the caller can safely reverse a descending
1126sequence without violating stability (strict > ensures there are no equal
1127elements to get out of order).
1128
1129Returns -1 in case of error.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001130*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001131static Py_ssize_t
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001132count_run(PyObject **lo, PyObject **hi, int *descending)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001133{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001134 Py_ssize_t k;
1135 Py_ssize_t n;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001136
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001137 assert(lo < hi);
1138 *descending = 0;
1139 ++lo;
1140 if (lo == hi)
1141 return 1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001143 n = 2;
1144 IFLT(*lo, *(lo-1)) {
1145 *descending = 1;
1146 for (lo = lo+1; lo < hi; ++lo, ++n) {
1147 IFLT(*lo, *(lo-1))
1148 ;
1149 else
1150 break;
1151 }
1152 }
1153 else {
1154 for (lo = lo+1; lo < hi; ++lo, ++n) {
1155 IFLT(*lo, *(lo-1))
1156 break;
1157 }
1158 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001159
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001160 return n;
Tim Petersa64dc242002-08-01 02:13:36 +00001161fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001162 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001163}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001164
Tim Petersa64dc242002-08-01 02:13:36 +00001165/*
1166Locate the proper position of key in a sorted vector; if the vector contains
1167an element equal to key, return the position immediately to the left of
1168the leftmost equal element. [gallop_right() does the same except returns
1169the position to the right of the rightmost equal element (if any).]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001170
Tim Petersa64dc242002-08-01 02:13:36 +00001171"a" is a sorted vector with n elements, starting at a[0]. n must be > 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001172
Tim Petersa64dc242002-08-01 02:13:36 +00001173"hint" is an index at which to begin the search, 0 <= hint < n. The closer
1174hint is to the final result, the faster this runs.
1175
1176The return value is the int k in 0..n such that
1177
1178 a[k-1] < key <= a[k]
1179
1180pretending that *(a-1) is minus infinity and a[n] is plus infinity. IOW,
1181key belongs at index k; or, IOW, the first k elements of a should precede
1182key, and the last n-k should follow key.
1183
1184Returns -1 on error. See listsort.txt for info on the method.
1185*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001186static Py_ssize_t
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001187gallop_left(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint)
Tim Petersa64dc242002-08-01 02:13:36 +00001188{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001189 Py_ssize_t ofs;
1190 Py_ssize_t lastofs;
1191 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001193 assert(key && a && n > 0 && hint >= 0 && hint < n);
Tim Petersa64dc242002-08-01 02:13:36 +00001194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 a += hint;
1196 lastofs = 0;
1197 ofs = 1;
1198 IFLT(*a, key) {
1199 /* a[hint] < key -- gallop right, until
1200 * a[hint + lastofs] < key <= a[hint + ofs]
1201 */
1202 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
1203 while (ofs < maxofs) {
1204 IFLT(a[ofs], key) {
1205 lastofs = ofs;
1206 ofs = (ofs << 1) + 1;
1207 if (ofs <= 0) /* int overflow */
1208 ofs = maxofs;
1209 }
1210 else /* key <= a[hint + ofs] */
1211 break;
1212 }
1213 if (ofs > maxofs)
1214 ofs = maxofs;
1215 /* Translate back to offsets relative to &a[0]. */
1216 lastofs += hint;
1217 ofs += hint;
1218 }
1219 else {
1220 /* key <= a[hint] -- gallop left, until
1221 * a[hint - ofs] < key <= a[hint - lastofs]
1222 */
1223 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
1224 while (ofs < maxofs) {
1225 IFLT(*(a-ofs), key)
1226 break;
1227 /* key <= a[hint - ofs] */
1228 lastofs = ofs;
1229 ofs = (ofs << 1) + 1;
1230 if (ofs <= 0) /* int overflow */
1231 ofs = maxofs;
1232 }
1233 if (ofs > maxofs)
1234 ofs = maxofs;
1235 /* Translate back to positive offsets relative to &a[0]. */
1236 k = lastofs;
1237 lastofs = hint - ofs;
1238 ofs = hint - k;
1239 }
1240 a -= hint;
Tim Petersa64dc242002-08-01 02:13:36 +00001241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001242 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1243 /* Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the
1244 * right of lastofs but no farther right than ofs. Do a binary
1245 * search, with invariant a[lastofs-1] < key <= a[ofs].
1246 */
1247 ++lastofs;
1248 while (lastofs < ofs) {
1249 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001251 IFLT(a[m], key)
1252 lastofs = m+1; /* a[m] < key */
1253 else
1254 ofs = m; /* key <= a[m] */
1255 }
1256 assert(lastofs == ofs); /* so a[ofs-1] < key <= a[ofs] */
1257 return ofs;
Tim Petersa64dc242002-08-01 02:13:36 +00001258
1259fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001260 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001261}
1262
1263/*
1264Exactly like gallop_left(), except that if key already exists in a[0:n],
1265finds the position immediately to the right of the rightmost equal value.
1266
1267The return value is the int k in 0..n such that
1268
1269 a[k-1] <= key < a[k]
1270
1271or -1 if error.
1272
1273The code duplication is massive, but this is enough different given that
1274we're sticking to "<" comparisons that it's much harder to follow if
1275written as one routine with yet another "left or right?" flag.
1276*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001277static Py_ssize_t
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001278gallop_right(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint)
Tim Petersa64dc242002-08-01 02:13:36 +00001279{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001280 Py_ssize_t ofs;
1281 Py_ssize_t lastofs;
1282 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001284 assert(key && a && n > 0 && hint >= 0 && hint < n);
Tim Petersa64dc242002-08-01 02:13:36 +00001285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001286 a += hint;
1287 lastofs = 0;
1288 ofs = 1;
1289 IFLT(key, *a) {
1290 /* key < a[hint] -- gallop left, until
1291 * a[hint - ofs] <= key < a[hint - lastofs]
1292 */
1293 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
1294 while (ofs < maxofs) {
1295 IFLT(key, *(a-ofs)) {
1296 lastofs = ofs;
1297 ofs = (ofs << 1) + 1;
1298 if (ofs <= 0) /* int overflow */
1299 ofs = maxofs;
1300 }
1301 else /* a[hint - ofs] <= key */
1302 break;
1303 }
1304 if (ofs > maxofs)
1305 ofs = maxofs;
1306 /* Translate back to positive offsets relative to &a[0]. */
1307 k = lastofs;
1308 lastofs = hint - ofs;
1309 ofs = hint - k;
1310 }
1311 else {
1312 /* a[hint] <= key -- gallop right, until
1313 * a[hint + lastofs] <= key < a[hint + ofs]
1314 */
1315 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
1316 while (ofs < maxofs) {
1317 IFLT(key, a[ofs])
1318 break;
1319 /* a[hint + ofs] <= key */
1320 lastofs = ofs;
1321 ofs = (ofs << 1) + 1;
1322 if (ofs <= 0) /* int overflow */
1323 ofs = maxofs;
1324 }
1325 if (ofs > maxofs)
1326 ofs = maxofs;
1327 /* Translate back to offsets relative to &a[0]. */
1328 lastofs += hint;
1329 ofs += hint;
1330 }
1331 a -= hint;
Tim Petersa64dc242002-08-01 02:13:36 +00001332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001333 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1334 /* Now a[lastofs] <= key < a[ofs], so key belongs somewhere to the
1335 * right of lastofs but no farther right than ofs. Do a binary
1336 * search, with invariant a[lastofs-1] <= key < a[ofs].
1337 */
1338 ++lastofs;
1339 while (lastofs < ofs) {
1340 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001342 IFLT(key, a[m])
1343 ofs = m; /* key < a[m] */
1344 else
1345 lastofs = m+1; /* a[m] <= key */
1346 }
1347 assert(lastofs == ofs); /* so a[ofs-1] <= key < a[ofs] */
1348 return ofs;
Tim Petersa64dc242002-08-01 02:13:36 +00001349
1350fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001351 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001352}
1353
1354/* The maximum number of entries in a MergeState's pending-runs stack.
1355 * This is enough to sort arrays of size up to about
1356 * 32 * phi ** MAX_MERGE_PENDING
1357 * where phi ~= 1.618. 85 is ridiculouslylarge enough, good for an array
1358 * with 2**64 elements.
1359 */
1360#define MAX_MERGE_PENDING 85
1361
Tim Peterse05f65a2002-08-10 05:21:15 +00001362/* When we get into galloping mode, we stay there until both runs win less
1363 * often than MIN_GALLOP consecutive times. See listsort.txt for more info.
Tim Petersa64dc242002-08-01 02:13:36 +00001364 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001365#define MIN_GALLOP 7
Tim Petersa64dc242002-08-01 02:13:36 +00001366
1367/* Avoid malloc for small temp arrays. */
1368#define MERGESTATE_TEMP_SIZE 256
1369
1370/* One MergeState exists on the stack per invocation of mergesort. It's just
1371 * a convenient way to pass state around among the helper functions.
1372 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001373struct s_slice {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001374 sortslice base;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001375 Py_ssize_t len;
Tim Peterse05f65a2002-08-10 05:21:15 +00001376};
1377
Tim Petersa64dc242002-08-01 02:13:36 +00001378typedef struct s_MergeState {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001379 /* This controls when we get *into* galloping mode. It's initialized
1380 * to MIN_GALLOP. merge_lo and merge_hi tend to nudge it higher for
1381 * random data, and lower for highly structured data.
1382 */
1383 Py_ssize_t min_gallop;
Tim Peterse05f65a2002-08-10 05:21:15 +00001384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001385 /* 'a' is temp storage to help with merges. It contains room for
1386 * alloced entries.
1387 */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001388 sortslice a; /* may point to temparray below */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001389 Py_ssize_t alloced;
Tim Petersa64dc242002-08-01 02:13:36 +00001390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001391 /* A stack of n pending runs yet to be merged. Run #i starts at
1392 * address base[i] and extends for len[i] elements. It's always
1393 * true (so long as the indices are in bounds) that
1394 *
1395 * pending[i].base + pending[i].len == pending[i+1].base
1396 *
1397 * so we could cut the storage for this, but it's a minor amount,
1398 * and keeping all the info explicit simplifies the code.
1399 */
1400 int n;
1401 struct s_slice pending[MAX_MERGE_PENDING];
Tim Petersa64dc242002-08-01 02:13:36 +00001402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001403 /* 'a' points to this when possible, rather than muck with malloc. */
1404 PyObject *temparray[MERGESTATE_TEMP_SIZE];
Tim Petersa64dc242002-08-01 02:13:36 +00001405} MergeState;
1406
1407/* Conceptually a MergeState's constructor. */
1408static void
Victor Stinner0fcab4a2011-01-04 12:59:15 +00001409merge_init(MergeState *ms, Py_ssize_t list_size, int has_keyfunc)
Tim Petersa64dc242002-08-01 02:13:36 +00001410{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001411 assert(ms != NULL);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001412 if (has_keyfunc) {
1413 /* The temporary space for merging will need at most half the list
1414 * size rounded up. Use the minimum possible space so we can use the
1415 * rest of temparray for other things. In particular, if there is
1416 * enough extra space, listsort() will use it to store the keys.
1417 */
1418 ms->alloced = (list_size + 1) / 2;
1419
1420 /* ms->alloced describes how many keys will be stored at
1421 ms->temparray, but we also need to store the values. Hence,
1422 ms->alloced is capped at half of MERGESTATE_TEMP_SIZE. */
1423 if (MERGESTATE_TEMP_SIZE / 2 < ms->alloced)
1424 ms->alloced = MERGESTATE_TEMP_SIZE / 2;
1425 ms->a.values = &ms->temparray[ms->alloced];
1426 }
1427 else {
1428 ms->alloced = MERGESTATE_TEMP_SIZE;
1429 ms->a.values = NULL;
1430 }
1431 ms->a.keys = ms->temparray;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001432 ms->n = 0;
1433 ms->min_gallop = MIN_GALLOP;
Tim Petersa64dc242002-08-01 02:13:36 +00001434}
1435
1436/* Free all the temp memory owned by the MergeState. This must be called
1437 * when you're done with a MergeState, and may be called before then if
1438 * you want to free the temp memory early.
1439 */
1440static void
1441merge_freemem(MergeState *ms)
1442{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001443 assert(ms != NULL);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001444 if (ms->a.keys != ms->temparray)
1445 PyMem_Free(ms->a.keys);
Tim Petersa64dc242002-08-01 02:13:36 +00001446}
1447
1448/* Ensure enough temp memory for 'need' array slots is available.
1449 * Returns 0 on success and -1 if the memory can't be gotten.
1450 */
1451static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001452merge_getmem(MergeState *ms, Py_ssize_t need)
Tim Petersa64dc242002-08-01 02:13:36 +00001453{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001454 int multiplier;
1455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001456 assert(ms != NULL);
1457 if (need <= ms->alloced)
1458 return 0;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001459
1460 multiplier = ms->a.values != NULL ? 2 : 1;
1461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001462 /* Don't realloc! That can cost cycles to copy the old data, but
1463 * we don't care what's in the block.
1464 */
1465 merge_freemem(ms);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001466 if ((size_t)need > PY_SSIZE_T_MAX / sizeof(PyObject*) / multiplier) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001467 PyErr_NoMemory();
1468 return -1;
1469 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001470 ms->a.keys = (PyObject**)PyMem_Malloc(multiplier * need
1471 * sizeof(PyObject *));
1472 if (ms->a.keys != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001473 ms->alloced = need;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001474 if (ms->a.values != NULL)
1475 ms->a.values = &ms->a.keys[need];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001476 return 0;
1477 }
1478 PyErr_NoMemory();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001479 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001480}
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001481#define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 : \
1482 merge_getmem(MS, NEED))
Tim Petersa64dc242002-08-01 02:13:36 +00001483
Daniel Stutzbach98338222010-12-02 21:55:33 +00001484/* Merge the na elements starting at ssa with the nb elements starting at
1485 * ssb.keys = ssa.keys + na in a stable way, in-place. na and nb must be > 0.
1486 * Must also have that ssa.keys[na-1] belongs at the end of the merge, and
1487 * should have na <= nb. See listsort.txt for more info. Return 0 if
1488 * successful, -1 if error.
Tim Petersa64dc242002-08-01 02:13:36 +00001489 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001490static Py_ssize_t
Daniel Stutzbach98338222010-12-02 21:55:33 +00001491merge_lo(MergeState *ms, sortslice ssa, Py_ssize_t na,
1492 sortslice ssb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001493{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001494 Py_ssize_t k;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001495 sortslice dest;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001496 int result = -1; /* guilty until proved innocent */
1497 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001498
Daniel Stutzbach98338222010-12-02 21:55:33 +00001499 assert(ms && ssa.keys && ssb.keys && na > 0 && nb > 0);
1500 assert(ssa.keys + na == ssb.keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001501 if (MERGE_GETMEM(ms, na) < 0)
1502 return -1;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001503 sortslice_memcpy(&ms->a, 0, &ssa, 0, na);
1504 dest = ssa;
1505 ssa = ms->a;
Tim Petersa64dc242002-08-01 02:13:36 +00001506
Daniel Stutzbach98338222010-12-02 21:55:33 +00001507 sortslice_copy_incr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001508 --nb;
1509 if (nb == 0)
1510 goto Succeed;
1511 if (na == 1)
1512 goto CopyB;
Tim Petersa64dc242002-08-01 02:13:36 +00001513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001514 min_gallop = ms->min_gallop;
1515 for (;;) {
1516 Py_ssize_t acount = 0; /* # of times A won in a row */
1517 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001519 /* Do the straightforward thing until (if ever) one run
1520 * appears to win consistently.
1521 */
1522 for (;;) {
1523 assert(na > 1 && nb > 0);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001524 k = ISLT(ssb.keys[0], ssa.keys[0]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001525 if (k) {
1526 if (k < 0)
1527 goto Fail;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001528 sortslice_copy_incr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001529 ++bcount;
1530 acount = 0;
1531 --nb;
1532 if (nb == 0)
1533 goto Succeed;
1534 if (bcount >= min_gallop)
1535 break;
1536 }
1537 else {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001538 sortslice_copy_incr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001539 ++acount;
1540 bcount = 0;
1541 --na;
1542 if (na == 1)
1543 goto CopyB;
1544 if (acount >= min_gallop)
1545 break;
1546 }
1547 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001549 /* One run is winning so consistently that galloping may
1550 * be a huge win. So try that, and continue galloping until
1551 * (if ever) neither run appears to be winning consistently
1552 * anymore.
1553 */
1554 ++min_gallop;
1555 do {
1556 assert(na > 1 && nb > 0);
1557 min_gallop -= min_gallop > 1;
1558 ms->min_gallop = min_gallop;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001559 k = gallop_right(ssb.keys[0], ssa.keys, na, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001560 acount = k;
1561 if (k) {
1562 if (k < 0)
1563 goto Fail;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001564 sortslice_memcpy(&dest, 0, &ssa, 0, k);
1565 sortslice_advance(&dest, k);
1566 sortslice_advance(&ssa, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001567 na -= k;
1568 if (na == 1)
1569 goto CopyB;
1570 /* na==0 is impossible now if the comparison
1571 * function is consistent, but we can't assume
1572 * that it is.
1573 */
1574 if (na == 0)
1575 goto Succeed;
1576 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001577 sortslice_copy_incr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001578 --nb;
1579 if (nb == 0)
1580 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001581
Daniel Stutzbach98338222010-12-02 21:55:33 +00001582 k = gallop_left(ssa.keys[0], ssb.keys, nb, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001583 bcount = k;
1584 if (k) {
1585 if (k < 0)
1586 goto Fail;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001587 sortslice_memmove(&dest, 0, &ssb, 0, k);
1588 sortslice_advance(&dest, k);
1589 sortslice_advance(&ssb, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001590 nb -= k;
1591 if (nb == 0)
1592 goto Succeed;
1593 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001594 sortslice_copy_incr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001595 --na;
1596 if (na == 1)
1597 goto CopyB;
1598 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
1599 ++min_gallop; /* penalize it for leaving galloping mode */
1600 ms->min_gallop = min_gallop;
1601 }
Tim Petersa64dc242002-08-01 02:13:36 +00001602Succeed:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001603 result = 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001604Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001605 if (na)
Daniel Stutzbach98338222010-12-02 21:55:33 +00001606 sortslice_memcpy(&dest, 0, &ssa, 0, na);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001607 return result;
Tim Petersa64dc242002-08-01 02:13:36 +00001608CopyB:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001609 assert(na == 1 && nb > 0);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001610 /* The last element of ssa belongs at the end of the merge. */
1611 sortslice_memmove(&dest, 0, &ssb, 0, nb);
1612 sortslice_copy(&dest, nb, &ssa, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001613 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001614}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001615
Daniel Stutzbach98338222010-12-02 21:55:33 +00001616/* Merge the na elements starting at pa with the nb elements starting at
1617 * ssb.keys = ssa.keys + na in a stable way, in-place. na and nb must be > 0.
1618 * Must also have that ssa.keys[na-1] belongs at the end of the merge, and
1619 * should have na >= nb. See listsort.txt for more info. Return 0 if
1620 * successful, -1 if error.
Tim Petersa64dc242002-08-01 02:13:36 +00001621 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001622static Py_ssize_t
Daniel Stutzbach98338222010-12-02 21:55:33 +00001623merge_hi(MergeState *ms, sortslice ssa, Py_ssize_t na,
1624 sortslice ssb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001625{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001626 Py_ssize_t k;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001627 sortslice dest, basea, baseb;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001628 int result = -1; /* guilty until proved innocent */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001629 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001630
Daniel Stutzbach98338222010-12-02 21:55:33 +00001631 assert(ms && ssa.keys && ssb.keys && na > 0 && nb > 0);
1632 assert(ssa.keys + na == ssb.keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001633 if (MERGE_GETMEM(ms, nb) < 0)
1634 return -1;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001635 dest = ssb;
1636 sortslice_advance(&dest, nb-1);
1637 sortslice_memcpy(&ms->a, 0, &ssb, 0, nb);
1638 basea = ssa;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001639 baseb = ms->a;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001640 ssb.keys = ms->a.keys + nb - 1;
1641 if (ssb.values != NULL)
1642 ssb.values = ms->a.values + nb - 1;
1643 sortslice_advance(&ssa, na - 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001644
Daniel Stutzbach98338222010-12-02 21:55:33 +00001645 sortslice_copy_decr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001646 --na;
1647 if (na == 0)
1648 goto Succeed;
1649 if (nb == 1)
1650 goto CopyA;
Tim Petersa64dc242002-08-01 02:13:36 +00001651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001652 min_gallop = ms->min_gallop;
1653 for (;;) {
1654 Py_ssize_t acount = 0; /* # of times A won in a row */
1655 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001657 /* Do the straightforward thing until (if ever) one run
1658 * appears to win consistently.
1659 */
1660 for (;;) {
1661 assert(na > 0 && nb > 1);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001662 k = ISLT(ssb.keys[0], ssa.keys[0]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001663 if (k) {
1664 if (k < 0)
1665 goto Fail;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001666 sortslice_copy_decr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001667 ++acount;
1668 bcount = 0;
1669 --na;
1670 if (na == 0)
1671 goto Succeed;
1672 if (acount >= min_gallop)
1673 break;
1674 }
1675 else {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001676 sortslice_copy_decr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001677 ++bcount;
1678 acount = 0;
1679 --nb;
1680 if (nb == 1)
1681 goto CopyA;
1682 if (bcount >= min_gallop)
1683 break;
1684 }
1685 }
Tim Petersa64dc242002-08-01 02:13:36 +00001686
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001687 /* One run is winning so consistently that galloping may
1688 * be a huge win. So try that, and continue galloping until
1689 * (if ever) neither run appears to be winning consistently
1690 * anymore.
1691 */
1692 ++min_gallop;
1693 do {
1694 assert(na > 0 && nb > 1);
1695 min_gallop -= min_gallop > 1;
1696 ms->min_gallop = min_gallop;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001697 k = gallop_right(ssb.keys[0], basea.keys, na, na-1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001698 if (k < 0)
1699 goto Fail;
1700 k = na - k;
1701 acount = k;
1702 if (k) {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001703 sortslice_advance(&dest, -k);
1704 sortslice_advance(&ssa, -k);
1705 sortslice_memmove(&dest, 1, &ssa, 1, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001706 na -= k;
1707 if (na == 0)
1708 goto Succeed;
1709 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001710 sortslice_copy_decr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001711 --nb;
1712 if (nb == 1)
1713 goto CopyA;
Tim Petersa64dc242002-08-01 02:13:36 +00001714
Daniel Stutzbach98338222010-12-02 21:55:33 +00001715 k = gallop_left(ssa.keys[0], baseb.keys, nb, nb-1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001716 if (k < 0)
1717 goto Fail;
1718 k = nb - k;
1719 bcount = k;
1720 if (k) {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001721 sortslice_advance(&dest, -k);
1722 sortslice_advance(&ssb, -k);
1723 sortslice_memcpy(&dest, 1, &ssb, 1, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001724 nb -= k;
1725 if (nb == 1)
1726 goto CopyA;
1727 /* nb==0 is impossible now if the comparison
1728 * function is consistent, but we can't assume
1729 * that it is.
1730 */
1731 if (nb == 0)
1732 goto Succeed;
1733 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001734 sortslice_copy_decr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001735 --na;
1736 if (na == 0)
1737 goto Succeed;
1738 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
1739 ++min_gallop; /* penalize it for leaving galloping mode */
1740 ms->min_gallop = min_gallop;
1741 }
Tim Petersa64dc242002-08-01 02:13:36 +00001742Succeed:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001743 result = 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001744Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001745 if (nb)
Daniel Stutzbach98338222010-12-02 21:55:33 +00001746 sortslice_memcpy(&dest, -(nb-1), &baseb, 0, nb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001747 return result;
Tim Petersa64dc242002-08-01 02:13:36 +00001748CopyA:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001749 assert(nb == 1 && na > 0);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001750 /* The first element of ssb belongs at the front of the merge. */
1751 sortslice_memmove(&dest, 1-na, &ssa, 1-na, na);
1752 sortslice_advance(&dest, -na);
1753 sortslice_advance(&ssa, -na);
1754 sortslice_copy(&dest, 0, &ssb, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001755 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001756}
1757
1758/* Merge the two runs at stack indices i and i+1.
1759 * Returns 0 on success, -1 on error.
1760 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001761static Py_ssize_t
1762merge_at(MergeState *ms, Py_ssize_t i)
Tim Petersa64dc242002-08-01 02:13:36 +00001763{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001764 sortslice ssa, ssb;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001765 Py_ssize_t na, nb;
1766 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001768 assert(ms != NULL);
1769 assert(ms->n >= 2);
1770 assert(i >= 0);
1771 assert(i == ms->n - 2 || i == ms->n - 3);
Tim Petersa64dc242002-08-01 02:13:36 +00001772
Daniel Stutzbach98338222010-12-02 21:55:33 +00001773 ssa = ms->pending[i].base;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001774 na = ms->pending[i].len;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001775 ssb = ms->pending[i+1].base;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001776 nb = ms->pending[i+1].len;
1777 assert(na > 0 && nb > 0);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001778 assert(ssa.keys + na == ssb.keys);
Tim Petersa64dc242002-08-01 02:13:36 +00001779
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001780 /* Record the length of the combined runs; if i is the 3rd-last
1781 * run now, also slide over the last run (which isn't involved
1782 * in this merge). The current run i+1 goes away in any case.
1783 */
1784 ms->pending[i].len = na + nb;
1785 if (i == ms->n - 3)
1786 ms->pending[i+1] = ms->pending[i+2];
1787 --ms->n;
Tim Petersa64dc242002-08-01 02:13:36 +00001788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001789 /* Where does b start in a? Elements in a before that can be
1790 * ignored (already in place).
1791 */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001792 k = gallop_right(*ssb.keys, ssa.keys, na, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001793 if (k < 0)
1794 return -1;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001795 sortslice_advance(&ssa, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001796 na -= k;
1797 if (na == 0)
1798 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001799
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001800 /* Where does a end in b? Elements in b after that can be
1801 * ignored (already in place).
1802 */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001803 nb = gallop_left(ssa.keys[na-1], ssb.keys, nb, nb-1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001804 if (nb <= 0)
1805 return nb;
Tim Petersa64dc242002-08-01 02:13:36 +00001806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001807 /* Merge what remains of the runs, using a temp array with
1808 * min(na, nb) elements.
1809 */
1810 if (na <= nb)
Daniel Stutzbach98338222010-12-02 21:55:33 +00001811 return merge_lo(ms, ssa, na, ssb, nb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001812 else
Daniel Stutzbach98338222010-12-02 21:55:33 +00001813 return merge_hi(ms, ssa, na, ssb, nb);
Tim Petersa64dc242002-08-01 02:13:36 +00001814}
1815
1816/* Examine the stack of runs waiting to be merged, merging adjacent runs
1817 * until the stack invariants are re-established:
1818 *
1819 * 1. len[-3] > len[-2] + len[-1]
1820 * 2. len[-2] > len[-1]
1821 *
1822 * See listsort.txt for more info.
1823 *
1824 * Returns 0 on success, -1 on error.
1825 */
1826static int
1827merge_collapse(MergeState *ms)
1828{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001829 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001830
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001831 assert(ms);
1832 while (ms->n > 1) {
1833 Py_ssize_t n = ms->n - 2;
Benjamin Petersonb808d592015-02-25 10:12:26 -05001834 if ((n > 0 && p[n-1].len <= p[n].len + p[n+1].len) ||
1835 (n > 1 && p[n-2].len <= p[n-1].len + p[n].len)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001836 if (p[n-1].len < p[n+1].len)
1837 --n;
1838 if (merge_at(ms, n) < 0)
1839 return -1;
1840 }
1841 else if (p[n].len <= p[n+1].len) {
1842 if (merge_at(ms, n) < 0)
1843 return -1;
1844 }
1845 else
1846 break;
1847 }
1848 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001849}
1850
1851/* Regardless of invariants, merge all runs on the stack until only one
1852 * remains. This is used at the end of the mergesort.
1853 *
1854 * Returns 0 on success, -1 on error.
1855 */
1856static int
1857merge_force_collapse(MergeState *ms)
1858{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001859 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001860
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001861 assert(ms);
1862 while (ms->n > 1) {
1863 Py_ssize_t n = ms->n - 2;
1864 if (n > 0 && p[n-1].len < p[n+1].len)
1865 --n;
1866 if (merge_at(ms, n) < 0)
1867 return -1;
1868 }
1869 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001870}
1871
1872/* Compute a good value for the minimum run length; natural runs shorter
1873 * than this are boosted artificially via binary insertion.
1874 *
1875 * If n < 64, return n (it's too small to bother with fancy stuff).
1876 * Else if n is an exact power of 2, return 32.
1877 * Else return an int k, 32 <= k <= 64, such that n/k is close to, but
1878 * strictly less than, an exact power of 2.
1879 *
1880 * See listsort.txt for more info.
1881 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001882static Py_ssize_t
1883merge_compute_minrun(Py_ssize_t n)
Tim Petersa64dc242002-08-01 02:13:36 +00001884{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001885 Py_ssize_t r = 0; /* becomes 1 if any 1 bits are shifted off */
Tim Petersa64dc242002-08-01 02:13:36 +00001886
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001887 assert(n >= 0);
1888 while (n >= 64) {
1889 r |= n & 1;
1890 n >>= 1;
1891 }
1892 return n + r;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001893}
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001894
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001895static void
Daniel Stutzbach98338222010-12-02 21:55:33 +00001896reverse_sortslice(sortslice *s, Py_ssize_t n)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001897{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001898 reverse_slice(s->keys, &s->keys[n]);
1899 if (s->values != NULL)
1900 reverse_slice(s->values, &s->values[n]);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001901}
1902
Tim Petersa64dc242002-08-01 02:13:36 +00001903/* An adaptive, stable, natural mergesort. See listsort.txt.
1904 * Returns Py_None on success, NULL on error. Even in case of error, the
1905 * list will be some permutation of its input state (nothing is lost or
1906 * duplicated).
1907 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001908static PyObject *
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001909listsort(PyListObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f236de1996-12-10 23:55:39 +00001910{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001911 MergeState ms;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001912 Py_ssize_t nremaining;
1913 Py_ssize_t minrun;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001914 sortslice lo;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001915 Py_ssize_t saved_ob_size, saved_allocated;
1916 PyObject **saved_ob_item;
1917 PyObject **final_ob_item;
1918 PyObject *result = NULL; /* guilty until proved innocent */
1919 int reverse = 0;
1920 PyObject *keyfunc = NULL;
1921 Py_ssize_t i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001922 static char *kwlist[] = {"key", "reverse", 0};
Daniel Stutzbach98338222010-12-02 21:55:33 +00001923 PyObject **keys;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001925 assert(self != NULL);
1926 assert (PyList_Check(self));
1927 if (args != NULL) {
1928 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:sort",
1929 kwlist, &keyfunc, &reverse))
1930 return NULL;
1931 if (Py_SIZE(args) > 0) {
1932 PyErr_SetString(PyExc_TypeError,
1933 "must use keyword argument for key function");
1934 return NULL;
1935 }
1936 }
1937 if (keyfunc == Py_None)
1938 keyfunc = NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001940 /* The list is temporarily made empty, so that mutations performed
1941 * by comparison functions can't affect the slice of memory we're
1942 * sorting (allowing mutations during sorting is a core-dump
1943 * factory, since ob_item may change).
1944 */
1945 saved_ob_size = Py_SIZE(self);
1946 saved_ob_item = self->ob_item;
1947 saved_allocated = self->allocated;
1948 Py_SIZE(self) = 0;
1949 self->ob_item = NULL;
1950 self->allocated = -1; /* any operation will reset it to >= 0 */
Tim Peters330f9e92002-07-19 07:05:44 +00001951
Daniel Stutzbach98338222010-12-02 21:55:33 +00001952 if (keyfunc == NULL) {
1953 keys = NULL;
1954 lo.keys = saved_ob_item;
1955 lo.values = NULL;
1956 }
1957 else {
1958 if (saved_ob_size < MERGESTATE_TEMP_SIZE/2)
1959 /* Leverage stack space we allocated but won't otherwise use */
1960 keys = &ms.temparray[saved_ob_size+1];
1961 else {
1962 keys = PyMem_MALLOC(sizeof(PyObject *) * saved_ob_size);
Benjamin Peterson0823ffb2015-04-23 17:04:36 -04001963 if (keys == NULL) {
1964 PyErr_NoMemory();
1965 goto keyfunc_fail;
1966 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001967 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001968
1969 for (i = 0; i < saved_ob_size ; i++) {
1970 keys[i] = PyObject_CallFunctionObjArgs(keyfunc, saved_ob_item[i],
1971 NULL);
1972 if (keys[i] == NULL) {
1973 for (i=i-1 ; i>=0 ; i--)
1974 Py_DECREF(keys[i]);
Benjamin Peterson4a42cd42014-03-15 12:21:28 -05001975 if (saved_ob_size >= MERGESTATE_TEMP_SIZE/2)
Daniel Stutzbach8eda5f72011-03-02 23:37:50 +00001976 PyMem_FREE(keys);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001977 goto keyfunc_fail;
1978 }
1979 }
1980
1981 lo.keys = keys;
1982 lo.values = saved_ob_item;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001983 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001984
Daniel Stutzbach98338222010-12-02 21:55:33 +00001985 merge_init(&ms, saved_ob_size, keys != NULL);
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001987 nremaining = saved_ob_size;
1988 if (nremaining < 2)
1989 goto succeed;
Tim Peters330f9e92002-07-19 07:05:44 +00001990
Benjamin Peterson05380642010-08-23 19:35:39 +00001991 /* Reverse sort stability achieved by initially reversing the list,
1992 applying a stable forward sort, then reversing the final result. */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001993 if (reverse) {
1994 if (keys != NULL)
1995 reverse_slice(&keys[0], &keys[saved_ob_size]);
1996 reverse_slice(&saved_ob_item[0], &saved_ob_item[saved_ob_size]);
1997 }
Benjamin Peterson05380642010-08-23 19:35:39 +00001998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001999 /* March over the array once, left to right, finding natural runs,
2000 * and extending short natural runs to minrun elements.
2001 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002002 minrun = merge_compute_minrun(nremaining);
2003 do {
2004 int descending;
2005 Py_ssize_t n;
Tim Peters330f9e92002-07-19 07:05:44 +00002006
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002007 /* Identify next run. */
Daniel Stutzbach98338222010-12-02 21:55:33 +00002008 n = count_run(lo.keys, lo.keys + nremaining, &descending);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002009 if (n < 0)
2010 goto fail;
2011 if (descending)
Daniel Stutzbach98338222010-12-02 21:55:33 +00002012 reverse_sortslice(&lo, n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002013 /* If short, extend to min(minrun, nremaining). */
2014 if (n < minrun) {
2015 const Py_ssize_t force = nremaining <= minrun ?
2016 nremaining : minrun;
Daniel Stutzbach98338222010-12-02 21:55:33 +00002017 if (binarysort(lo, lo.keys + force, lo.keys + n) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002018 goto fail;
2019 n = force;
2020 }
2021 /* Push run onto pending-runs stack, and maybe merge. */
2022 assert(ms.n < MAX_MERGE_PENDING);
2023 ms.pending[ms.n].base = lo;
2024 ms.pending[ms.n].len = n;
2025 ++ms.n;
2026 if (merge_collapse(&ms) < 0)
2027 goto fail;
2028 /* Advance to find next run. */
Daniel Stutzbach98338222010-12-02 21:55:33 +00002029 sortslice_advance(&lo, n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002030 nremaining -= n;
2031 } while (nremaining);
Tim Peters330f9e92002-07-19 07:05:44 +00002032
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002033 if (merge_force_collapse(&ms) < 0)
2034 goto fail;
2035 assert(ms.n == 1);
Daniel Stutzbach98338222010-12-02 21:55:33 +00002036 assert(keys == NULL
2037 ? ms.pending[0].base.keys == saved_ob_item
2038 : ms.pending[0].base.keys == &keys[0]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002039 assert(ms.pending[0].len == saved_ob_size);
Daniel Stutzbach98338222010-12-02 21:55:33 +00002040 lo = ms.pending[0].base;
Tim Petersa64dc242002-08-01 02:13:36 +00002041
2042succeed:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002043 result = Py_None;
Tim Peters330f9e92002-07-19 07:05:44 +00002044fail:
Daniel Stutzbach98338222010-12-02 21:55:33 +00002045 if (keys != NULL) {
2046 for (i = 0; i < saved_ob_size; i++)
2047 Py_DECREF(keys[i]);
Benjamin Petersonef87f8c2014-03-14 21:54:31 -05002048 if (saved_ob_size >= MERGESTATE_TEMP_SIZE/2)
Daniel Stutzbach98338222010-12-02 21:55:33 +00002049 PyMem_FREE(keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002050 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002052 if (self->allocated != -1 && result != NULL) {
2053 /* The user mucked with the list during the sort,
2054 * and we don't already have another error to report.
2055 */
2056 PyErr_SetString(PyExc_ValueError, "list modified during sort");
2057 result = NULL;
2058 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002060 if (reverse && saved_ob_size > 1)
2061 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002063 merge_freemem(&ms);
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002064
Daniel Stutzbach98338222010-12-02 21:55:33 +00002065keyfunc_fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002066 final_ob_item = self->ob_item;
2067 i = Py_SIZE(self);
2068 Py_SIZE(self) = saved_ob_size;
2069 self->ob_item = saved_ob_item;
2070 self->allocated = saved_allocated;
2071 if (final_ob_item != NULL) {
2072 /* we cannot use list_clear() for this because it does not
2073 guarantee that the list is really empty when it returns */
2074 while (--i >= 0) {
2075 Py_XDECREF(final_ob_item[i]);
2076 }
2077 PyMem_FREE(final_ob_item);
2078 }
2079 Py_XINCREF(result);
2080 return result;
Guido van Rossum3f236de1996-12-10 23:55:39 +00002081}
Tim Peters330f9e92002-07-19 07:05:44 +00002082#undef IFLT
Tim Peters66860f62002-08-04 17:47:26 +00002083#undef ISLT
Tim Peters330f9e92002-07-19 07:05:44 +00002084
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002085int
Fred Drakea2f55112000-07-09 15:16:51 +00002086PyList_Sort(PyObject *v)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002087{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002088 if (v == NULL || !PyList_Check(v)) {
2089 PyErr_BadInternalCall();
2090 return -1;
2091 }
2092 v = listsort((PyListObject *)v, (PyObject *)NULL, (PyObject *)NULL);
2093 if (v == NULL)
2094 return -1;
2095 Py_DECREF(v);
2096 return 0;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002097}
2098
Guido van Rossumb86c5492001-02-12 22:06:02 +00002099static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002100listreverse(PyListObject *self)
Guido van Rossumb86c5492001-02-12 22:06:02 +00002101{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002102 if (Py_SIZE(self) > 1)
2103 reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
2104 Py_RETURN_NONE;
Guido van Rossumed98d481991-03-06 13:07:53 +00002105}
2106
Guido van Rossum84c76f51990-10-30 13:32:20 +00002107int
Fred Drakea2f55112000-07-09 15:16:51 +00002108PyList_Reverse(PyObject *v)
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002109{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002110 PyListObject *self = (PyListObject *)v;
Tim Peters6063e262002-08-08 01:06:39 +00002111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002112 if (v == NULL || !PyList_Check(v)) {
2113 PyErr_BadInternalCall();
2114 return -1;
2115 }
2116 if (Py_SIZE(self) > 1)
2117 reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
2118 return 0;
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002119}
2120
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002121PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00002122PyList_AsTuple(PyObject *v)
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002123{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002124 PyObject *w;
2125 PyObject **p, **q;
2126 Py_ssize_t n;
2127 if (v == NULL || !PyList_Check(v)) {
2128 PyErr_BadInternalCall();
2129 return NULL;
2130 }
2131 n = Py_SIZE(v);
2132 w = PyTuple_New(n);
2133 if (w == NULL)
2134 return NULL;
2135 p = ((PyTupleObject *)w)->ob_item;
2136 q = ((PyListObject *)v)->ob_item;
2137 while (--n >= 0) {
2138 Py_INCREF(*q);
2139 *p = *q;
2140 p++;
2141 q++;
2142 }
2143 return w;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002144}
2145
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002146static PyObject *
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002147listindex(PyListObject *self, PyObject *args)
Guido van Rossumed98d481991-03-06 13:07:53 +00002148{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002149 Py_ssize_t i, start=0, stop=Py_SIZE(self);
Amaury Forgeot d'Arc864741b2011-11-06 15:10:48 +01002150 PyObject *v;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002151
Petri Lehtinenebfaabd2011-11-06 21:02:39 +02002152 if (!PyArg_ParseTuple(args, "O|O&O&:index", &v,
2153 _PyEval_SliceIndex, &start,
2154 _PyEval_SliceIndex, &stop))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002155 return NULL;
2156 if (start < 0) {
2157 start += Py_SIZE(self);
2158 if (start < 0)
2159 start = 0;
2160 }
2161 if (stop < 0) {
2162 stop += Py_SIZE(self);
2163 if (stop < 0)
2164 stop = 0;
2165 }
2166 for (i = start; i < stop && i < Py_SIZE(self); i++) {
2167 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2168 if (cmp > 0)
2169 return PyLong_FromSsize_t(i);
2170 else if (cmp < 0)
2171 return NULL;
2172 }
Amaury Forgeot d'Arc864741b2011-11-06 15:10:48 +01002173 PyErr_Format(PyExc_ValueError, "%R is not in list", v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002174 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002175}
2176
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002177static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002178listcount(PyListObject *self, PyObject *v)
Guido van Rossume6f7d181991-10-20 20:20:40 +00002179{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002180 Py_ssize_t count = 0;
2181 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002182
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002183 for (i = 0; i < Py_SIZE(self); i++) {
2184 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2185 if (cmp > 0)
2186 count++;
2187 else if (cmp < 0)
2188 return NULL;
2189 }
2190 return PyLong_FromSsize_t(count);
Guido van Rossume6f7d181991-10-20 20:20:40 +00002191}
2192
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002193static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002194listremove(PyListObject *self, PyObject *v)
Guido van Rossumed98d481991-03-06 13:07:53 +00002195{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002196 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002198 for (i = 0; i < Py_SIZE(self); i++) {
2199 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2200 if (cmp > 0) {
2201 if (list_ass_slice(self, i, i+1,
2202 (PyObject *)NULL) == 0)
2203 Py_RETURN_NONE;
2204 return NULL;
2205 }
2206 else if (cmp < 0)
2207 return NULL;
2208 }
2209 PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
2210 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002211}
2212
Jeremy Hylton8caad492000-06-23 14:18:11 +00002213static int
2214list_traverse(PyListObject *o, visitproc visit, void *arg)
2215{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002216 Py_ssize_t i;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002218 for (i = Py_SIZE(o); --i >= 0; )
2219 Py_VISIT(o->ob_item[i]);
2220 return 0;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002221}
2222
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002223static PyObject *
2224list_richcompare(PyObject *v, PyObject *w, int op)
2225{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002226 PyListObject *vl, *wl;
2227 Py_ssize_t i;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002228
Brian Curtindfc80e32011-08-10 20:28:54 -05002229 if (!PyList_Check(v) || !PyList_Check(w))
2230 Py_RETURN_NOTIMPLEMENTED;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002232 vl = (PyListObject *)v;
2233 wl = (PyListObject *)w;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002235 if (Py_SIZE(vl) != Py_SIZE(wl) && (op == Py_EQ || op == Py_NE)) {
2236 /* Shortcut: if the lengths differ, the lists differ */
2237 PyObject *res;
2238 if (op == Py_EQ)
2239 res = Py_False;
2240 else
2241 res = Py_True;
2242 Py_INCREF(res);
2243 return res;
2244 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002245
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002246 /* Search for the first index where items are different */
2247 for (i = 0; i < Py_SIZE(vl) && i < Py_SIZE(wl); i++) {
2248 int k = PyObject_RichCompareBool(vl->ob_item[i],
2249 wl->ob_item[i], Py_EQ);
2250 if (k < 0)
2251 return NULL;
2252 if (!k)
2253 break;
2254 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002255
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002256 if (i >= Py_SIZE(vl) || i >= Py_SIZE(wl)) {
2257 /* No more items to compare -- compare sizes */
2258 Py_ssize_t vs = Py_SIZE(vl);
2259 Py_ssize_t ws = Py_SIZE(wl);
2260 int cmp;
2261 PyObject *res;
2262 switch (op) {
2263 case Py_LT: cmp = vs < ws; break;
2264 case Py_LE: cmp = vs <= ws; break;
2265 case Py_EQ: cmp = vs == ws; break;
2266 case Py_NE: cmp = vs != ws; break;
2267 case Py_GT: cmp = vs > ws; break;
2268 case Py_GE: cmp = vs >= ws; break;
2269 default: return NULL; /* cannot happen */
2270 }
2271 if (cmp)
2272 res = Py_True;
2273 else
2274 res = Py_False;
2275 Py_INCREF(res);
2276 return res;
2277 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002279 /* We have an item that differs -- shortcuts for EQ/NE */
2280 if (op == Py_EQ) {
2281 Py_INCREF(Py_False);
2282 return Py_False;
2283 }
2284 if (op == Py_NE) {
2285 Py_INCREF(Py_True);
2286 return Py_True;
2287 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002289 /* Compare the final item again using the proper operator */
2290 return PyObject_RichCompare(vl->ob_item[i], wl->ob_item[i], op);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002291}
2292
Tim Peters6d6c1a32001-08-02 04:15:00 +00002293static int
2294list_init(PyListObject *self, PyObject *args, PyObject *kw)
2295{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002296 PyObject *arg = NULL;
2297 static char *kwlist[] = {"sequence", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002299 if (!PyArg_ParseTupleAndKeywords(args, kw, "|O:list", kwlist, &arg))
2300 return -1;
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002302 /* Verify list invariants established by PyType_GenericAlloc() */
2303 assert(0 <= Py_SIZE(self));
2304 assert(Py_SIZE(self) <= self->allocated || self->allocated == -1);
2305 assert(self->ob_item != NULL ||
2306 self->allocated == 0 || self->allocated == -1);
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002308 /* Empty previous contents */
2309 if (self->ob_item != NULL) {
2310 (void)list_clear(self);
2311 }
2312 if (arg != NULL) {
2313 PyObject *rv = listextend(self, arg);
2314 if (rv == NULL)
2315 return -1;
2316 Py_DECREF(rv);
2317 }
2318 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002319}
2320
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002321static PyObject *
2322list_sizeof(PyListObject *self)
2323{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002324 Py_ssize_t res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002325
Serhiy Storchaka5c4064e2015-12-19 20:05:25 +02002326 res = _PyObject_SIZE(Py_TYPE(self)) + self->allocated * sizeof(void*);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002327 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002328}
2329
Raymond Hettinger1021c442003-11-07 15:38:09 +00002330static PyObject *list_iter(PyObject *seq);
2331static PyObject *list_reversed(PyListObject* seq, PyObject* unused);
2332
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002333PyDoc_STRVAR(getitem_doc,
2334"x.__getitem__(y) <==> x[y]");
Raymond Hettinger1021c442003-11-07 15:38:09 +00002335PyDoc_STRVAR(reversed_doc,
2336"L.__reversed__() -- return a reverse iterator over the list");
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002337PyDoc_STRVAR(sizeof_doc,
2338"L.__sizeof__() -- size of L in memory, in bytes");
Eli Benderskycbbaa962011-02-25 05:47:53 +00002339PyDoc_STRVAR(clear_doc,
2340"L.clear() -> None -- remove all items from L");
2341PyDoc_STRVAR(copy_doc,
2342"L.copy() -> list -- a shallow copy of L");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002343PyDoc_STRVAR(append_doc,
Georg Brandl388349a2011-10-08 18:32:40 +02002344"L.append(object) -> None -- append object to end");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002345PyDoc_STRVAR(extend_doc,
Georg Brandl388349a2011-10-08 18:32:40 +02002346"L.extend(iterable) -> None -- extend list by appending elements from the iterable");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002347PyDoc_STRVAR(insert_doc,
2348"L.insert(index, object) -- insert object before index");
2349PyDoc_STRVAR(pop_doc,
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00002350"L.pop([index]) -> item -- remove and return item at index (default last).\n"
2351"Raises IndexError if list is empty or index is out of range.");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002352PyDoc_STRVAR(remove_doc,
Georg Brandl388349a2011-10-08 18:32:40 +02002353"L.remove(value) -> None -- remove first occurrence of value.\n"
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00002354"Raises ValueError if the value is not present.");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002355PyDoc_STRVAR(index_doc,
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00002356"L.index(value, [start, [stop]]) -> integer -- return first index of value.\n"
2357"Raises ValueError if the value is not present.");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002358PyDoc_STRVAR(count_doc,
2359"L.count(value) -> integer -- return number of occurrences of value");
2360PyDoc_STRVAR(reverse_doc,
2361"L.reverse() -- reverse *IN PLACE*");
2362PyDoc_STRVAR(sort_doc,
Georg Brandl388349a2011-10-08 18:32:40 +02002363"L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*");
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +00002364
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002365static PyObject *list_subscript(PyListObject*, PyObject*);
2366
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002367static PyMethodDef list_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002368 {"__getitem__", (PyCFunction)list_subscript, METH_O|METH_COEXIST, getitem_doc},
2369 {"__reversed__",(PyCFunction)list_reversed, METH_NOARGS, reversed_doc},
2370 {"__sizeof__", (PyCFunction)list_sizeof, METH_NOARGS, sizeof_doc},
Eli Benderskycbbaa962011-02-25 05:47:53 +00002371 {"clear", (PyCFunction)listclear, METH_NOARGS, clear_doc},
2372 {"copy", (PyCFunction)listcopy, METH_NOARGS, copy_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002373 {"append", (PyCFunction)listappend, METH_O, append_doc},
2374 {"insert", (PyCFunction)listinsert, METH_VARARGS, insert_doc},
Eli Benderskycbbaa962011-02-25 05:47:53 +00002375 {"extend", (PyCFunction)listextend, METH_O, extend_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002376 {"pop", (PyCFunction)listpop, METH_VARARGS, pop_doc},
2377 {"remove", (PyCFunction)listremove, METH_O, remove_doc},
2378 {"index", (PyCFunction)listindex, METH_VARARGS, index_doc},
2379 {"count", (PyCFunction)listcount, METH_O, count_doc},
2380 {"reverse", (PyCFunction)listreverse, METH_NOARGS, reverse_doc},
2381 {"sort", (PyCFunction)listsort, METH_VARARGS | METH_KEYWORDS, sort_doc},
2382 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002383};
2384
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002385static PySequenceMethods list_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002386 (lenfunc)list_length, /* sq_length */
2387 (binaryfunc)list_concat, /* sq_concat */
2388 (ssizeargfunc)list_repeat, /* sq_repeat */
2389 (ssizeargfunc)list_item, /* sq_item */
2390 0, /* sq_slice */
2391 (ssizeobjargproc)list_ass_item, /* sq_ass_item */
2392 0, /* sq_ass_slice */
2393 (objobjproc)list_contains, /* sq_contains */
2394 (binaryfunc)list_inplace_concat, /* sq_inplace_concat */
2395 (ssizeargfunc)list_inplace_repeat, /* sq_inplace_repeat */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002396};
2397
Neal Norwitz2c2e8272002-06-14 02:04:18 +00002398PyDoc_STRVAR(list_doc,
Ezio Melotti7f807b72010-03-01 04:08:34 +00002399"list() -> new empty list\n"
2400"list(iterable) -> new list initialized from iterable's items");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002401
Jeremy Hyltona4b4c3b2002-07-13 03:51:17 +00002402static PyObject *
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002403list_subscript(PyListObject* self, PyObject* item)
2404{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002405 if (PyIndex_Check(item)) {
2406 Py_ssize_t i;
2407 i = PyNumber_AsSsize_t(item, PyExc_IndexError);
2408 if (i == -1 && PyErr_Occurred())
2409 return NULL;
2410 if (i < 0)
2411 i += PyList_GET_SIZE(self);
2412 return list_item(self, i);
2413 }
2414 else if (PySlice_Check(item)) {
2415 Py_ssize_t start, stop, step, slicelength, cur, i;
2416 PyObject* result;
2417 PyObject* it;
2418 PyObject **src, **dest;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002419
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002420 if (PySlice_GetIndicesEx(item, Py_SIZE(self),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002421 &start, &stop, &step, &slicelength) < 0) {
2422 return NULL;
2423 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002425 if (slicelength <= 0) {
2426 return PyList_New(0);
2427 }
2428 else if (step == 1) {
2429 return list_slice(self, start, stop);
2430 }
2431 else {
2432 result = PyList_New(slicelength);
2433 if (!result) return NULL;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002435 src = self->ob_item;
2436 dest = ((PyListObject *)result)->ob_item;
2437 for (cur = start, i = 0; i < slicelength;
Mark Dickinsonc7d93b72011-09-25 15:34:32 +01002438 cur += (size_t)step, i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002439 it = src[cur];
2440 Py_INCREF(it);
2441 dest[i] = it;
2442 }
Tim Peters3b01a122002-07-19 02:35:45 +00002443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002444 return result;
2445 }
2446 }
2447 else {
2448 PyErr_Format(PyExc_TypeError,
Terry Jan Reedyffff1442014-08-02 01:30:37 -04002449 "list indices must be integers or slices, not %.200s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002450 item->ob_type->tp_name);
2451 return NULL;
2452 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002453}
2454
Tim Peters3b01a122002-07-19 02:35:45 +00002455static int
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002456list_ass_subscript(PyListObject* self, PyObject* item, PyObject* value)
2457{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002458 if (PyIndex_Check(item)) {
2459 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
2460 if (i == -1 && PyErr_Occurred())
2461 return -1;
2462 if (i < 0)
2463 i += PyList_GET_SIZE(self);
2464 return list_ass_item(self, i, value);
2465 }
2466 else if (PySlice_Check(item)) {
2467 Py_ssize_t start, stop, step, slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002468
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002469 if (PySlice_GetIndicesEx(item, Py_SIZE(self),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002470 &start, &stop, &step, &slicelength) < 0) {
2471 return -1;
2472 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002474 if (step == 1)
2475 return list_ass_slice(self, start, stop, value);
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002476
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002477 /* Make sure s[5:2] = [..] inserts at the right place:
2478 before 5, not before 2. */
2479 if ((step < 0 && start < stop) ||
2480 (step > 0 && start > stop))
2481 stop = start;
Thomas Woutersed03b412007-08-28 21:37:11 +00002482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002483 if (value == NULL) {
2484 /* delete slice */
2485 PyObject **garbage;
2486 size_t cur;
2487 Py_ssize_t i;
Victor Stinner35f28032013-11-21 12:16:35 +01002488 int res;
Tim Peters3b01a122002-07-19 02:35:45 +00002489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002490 if (slicelength <= 0)
2491 return 0;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002493 if (step < 0) {
2494 stop = start + 1;
2495 start = stop + step*(slicelength - 1) - 1;
2496 step = -step;
2497 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002499 garbage = (PyObject**)
2500 PyMem_MALLOC(slicelength*sizeof(PyObject*));
2501 if (!garbage) {
2502 PyErr_NoMemory();
2503 return -1;
2504 }
Tim Peters3b01a122002-07-19 02:35:45 +00002505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002506 /* drawing pictures might help understand these for
2507 loops. Basically, we memmove the parts of the
2508 list that are *not* part of the slice: step-1
2509 items for each item that is part of the slice,
2510 and then tail end of the list that was not
2511 covered by the slice */
2512 for (cur = start, i = 0;
2513 cur < (size_t)stop;
2514 cur += step, i++) {
2515 Py_ssize_t lim = step - 1;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002517 garbage[i] = PyList_GET_ITEM(self, cur);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002519 if (cur + step >= (size_t)Py_SIZE(self)) {
2520 lim = Py_SIZE(self) - cur - 1;
2521 }
Michael W. Hudson56796f62002-07-29 14:35:04 +00002522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002523 memmove(self->ob_item + cur - i,
2524 self->ob_item + cur + 1,
2525 lim * sizeof(PyObject *));
2526 }
Mark Dickinsonc7d93b72011-09-25 15:34:32 +01002527 cur = start + (size_t)slicelength * step;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002528 if (cur < (size_t)Py_SIZE(self)) {
2529 memmove(self->ob_item + cur - slicelength,
2530 self->ob_item + cur,
2531 (Py_SIZE(self) - cur) *
2532 sizeof(PyObject *));
2533 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002535 Py_SIZE(self) -= slicelength;
Victor Stinner35f28032013-11-21 12:16:35 +01002536 res = list_resize(self, Py_SIZE(self));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002538 for (i = 0; i < slicelength; i++) {
2539 Py_DECREF(garbage[i]);
2540 }
2541 PyMem_FREE(garbage);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002542
Victor Stinner35f28032013-11-21 12:16:35 +01002543 return res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002544 }
2545 else {
2546 /* assign slice */
2547 PyObject *ins, *seq;
2548 PyObject **garbage, **seqitems, **selfitems;
2549 Py_ssize_t cur, i;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002550
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002551 /* protect against a[::-1] = a */
2552 if (self == (PyListObject*)value) {
2553 seq = list_slice((PyListObject*)value, 0,
2554 PyList_GET_SIZE(value));
2555 }
2556 else {
2557 seq = PySequence_Fast(value,
2558 "must assign iterable "
2559 "to extended slice");
2560 }
2561 if (!seq)
2562 return -1;
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002564 if (PySequence_Fast_GET_SIZE(seq) != slicelength) {
2565 PyErr_Format(PyExc_ValueError,
2566 "attempt to assign sequence of "
2567 "size %zd to extended slice of "
2568 "size %zd",
2569 PySequence_Fast_GET_SIZE(seq),
2570 slicelength);
2571 Py_DECREF(seq);
2572 return -1;
2573 }
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002575 if (!slicelength) {
2576 Py_DECREF(seq);
2577 return 0;
2578 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002579
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002580 garbage = (PyObject**)
2581 PyMem_MALLOC(slicelength*sizeof(PyObject*));
2582 if (!garbage) {
2583 Py_DECREF(seq);
2584 PyErr_NoMemory();
2585 return -1;
2586 }
Tim Peters3b01a122002-07-19 02:35:45 +00002587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002588 selfitems = self->ob_item;
2589 seqitems = PySequence_Fast_ITEMS(seq);
2590 for (cur = start, i = 0; i < slicelength;
Mark Dickinsonc7d93b72011-09-25 15:34:32 +01002591 cur += (size_t)step, i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002592 garbage[i] = selfitems[cur];
2593 ins = seqitems[i];
2594 Py_INCREF(ins);
2595 selfitems[cur] = ins;
2596 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002597
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002598 for (i = 0; i < slicelength; i++) {
2599 Py_DECREF(garbage[i]);
2600 }
Tim Peters3b01a122002-07-19 02:35:45 +00002601
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002602 PyMem_FREE(garbage);
2603 Py_DECREF(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002605 return 0;
2606 }
2607 }
2608 else {
2609 PyErr_Format(PyExc_TypeError,
Terry Jan Reedyffff1442014-08-02 01:30:37 -04002610 "list indices must be integers or slices, not %.200s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002611 item->ob_type->tp_name);
2612 return -1;
2613 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002614}
2615
2616static PyMappingMethods list_as_mapping = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002617 (lenfunc)list_length,
2618 (binaryfunc)list_subscript,
2619 (objobjargproc)list_ass_subscript
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002620};
2621
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002622PyTypeObject PyList_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002623 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2624 "list",
2625 sizeof(PyListObject),
2626 0,
2627 (destructor)list_dealloc, /* tp_dealloc */
2628 0, /* tp_print */
2629 0, /* tp_getattr */
2630 0, /* tp_setattr */
2631 0, /* tp_reserved */
2632 (reprfunc)list_repr, /* tp_repr */
2633 0, /* tp_as_number */
2634 &list_as_sequence, /* tp_as_sequence */
2635 &list_as_mapping, /* tp_as_mapping */
Georg Brandl00da4e02010-10-18 07:32:48 +00002636 PyObject_HashNotImplemented, /* tp_hash */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002637 0, /* tp_call */
2638 0, /* tp_str */
2639 PyObject_GenericGetAttr, /* tp_getattro */
2640 0, /* tp_setattro */
2641 0, /* tp_as_buffer */
2642 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2643 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LIST_SUBCLASS, /* tp_flags */
2644 list_doc, /* tp_doc */
2645 (traverseproc)list_traverse, /* tp_traverse */
2646 (inquiry)list_clear, /* tp_clear */
2647 list_richcompare, /* tp_richcompare */
2648 0, /* tp_weaklistoffset */
2649 list_iter, /* tp_iter */
2650 0, /* tp_iternext */
2651 list_methods, /* tp_methods */
2652 0, /* tp_members */
2653 0, /* tp_getset */
2654 0, /* tp_base */
2655 0, /* tp_dict */
2656 0, /* tp_descr_get */
2657 0, /* tp_descr_set */
2658 0, /* tp_dictoffset */
2659 (initproc)list_init, /* tp_init */
2660 PyType_GenericAlloc, /* tp_alloc */
2661 PyType_GenericNew, /* tp_new */
2662 PyObject_GC_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002663};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002664
2665
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002666/*********************** List Iterator **************************/
2667
2668typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002669 PyObject_HEAD
Victor Stinner7660b882013-06-24 23:59:24 +02002670 Py_ssize_t it_index;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002671 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002672} listiterobject;
2673
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002674static PyObject *list_iter(PyObject *);
2675static void listiter_dealloc(listiterobject *);
2676static int listiter_traverse(listiterobject *, visitproc, void *);
2677static PyObject *listiter_next(listiterobject *);
2678static PyObject *listiter_len(listiterobject *);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002679static PyObject *listiter_reduce_general(void *_it, int forward);
2680static PyObject *listiter_reduce(listiterobject *);
2681static PyObject *listiter_setstate(listiterobject *, PyObject *state);
Raymond Hettinger435bf582004-03-18 22:43:10 +00002682
Armin Rigof5b3e362006-02-11 21:32:43 +00002683PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002684PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
2685PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002686
2687static PyMethodDef listiter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002688 {"__length_hint__", (PyCFunction)listiter_len, METH_NOARGS, length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002689 {"__reduce__", (PyCFunction)listiter_reduce, METH_NOARGS, reduce_doc},
2690 {"__setstate__", (PyCFunction)listiter_setstate, METH_O, setstate_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002691 {NULL, NULL} /* sentinel */
Raymond Hettinger435bf582004-03-18 22:43:10 +00002692};
2693
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002694PyTypeObject PyListIter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002695 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2696 "list_iterator", /* tp_name */
2697 sizeof(listiterobject), /* tp_basicsize */
2698 0, /* tp_itemsize */
2699 /* methods */
2700 (destructor)listiter_dealloc, /* tp_dealloc */
2701 0, /* tp_print */
2702 0, /* tp_getattr */
2703 0, /* tp_setattr */
2704 0, /* tp_reserved */
2705 0, /* tp_repr */
2706 0, /* tp_as_number */
2707 0, /* tp_as_sequence */
2708 0, /* tp_as_mapping */
2709 0, /* tp_hash */
2710 0, /* tp_call */
2711 0, /* tp_str */
2712 PyObject_GenericGetAttr, /* tp_getattro */
2713 0, /* tp_setattro */
2714 0, /* tp_as_buffer */
2715 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2716 0, /* tp_doc */
2717 (traverseproc)listiter_traverse, /* tp_traverse */
2718 0, /* tp_clear */
2719 0, /* tp_richcompare */
2720 0, /* tp_weaklistoffset */
2721 PyObject_SelfIter, /* tp_iter */
2722 (iternextfunc)listiter_next, /* tp_iternext */
2723 listiter_methods, /* tp_methods */
2724 0, /* tp_members */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002725};
Raymond Hettinger1021c442003-11-07 15:38:09 +00002726
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002727
2728static PyObject *
2729list_iter(PyObject *seq)
2730{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002731 listiterobject *it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002732
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002733 if (!PyList_Check(seq)) {
2734 PyErr_BadInternalCall();
2735 return NULL;
2736 }
2737 it = PyObject_GC_New(listiterobject, &PyListIter_Type);
2738 if (it == NULL)
2739 return NULL;
2740 it->it_index = 0;
2741 Py_INCREF(seq);
2742 it->it_seq = (PyListObject *)seq;
2743 _PyObject_GC_TRACK(it);
2744 return (PyObject *)it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002745}
2746
2747static void
2748listiter_dealloc(listiterobject *it)
2749{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002750 _PyObject_GC_UNTRACK(it);
2751 Py_XDECREF(it->it_seq);
2752 PyObject_GC_Del(it);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002753}
2754
2755static int
2756listiter_traverse(listiterobject *it, visitproc visit, void *arg)
2757{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002758 Py_VISIT(it->it_seq);
2759 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002760}
2761
2762static PyObject *
2763listiter_next(listiterobject *it)
2764{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002765 PyListObject *seq;
2766 PyObject *item;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002768 assert(it != NULL);
2769 seq = it->it_seq;
2770 if (seq == NULL)
2771 return NULL;
2772 assert(PyList_Check(seq));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002774 if (it->it_index < PyList_GET_SIZE(seq)) {
2775 item = PyList_GET_ITEM(seq, it->it_index);
2776 ++it->it_index;
2777 Py_INCREF(item);
2778 return item;
2779 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002781 it->it_seq = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03002782 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002783 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002784}
2785
2786static PyObject *
2787listiter_len(listiterobject *it)
2788{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002789 Py_ssize_t len;
2790 if (it->it_seq) {
2791 len = PyList_GET_SIZE(it->it_seq) - it->it_index;
2792 if (len >= 0)
2793 return PyLong_FromSsize_t(len);
2794 }
2795 return PyLong_FromLong(0);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002796}
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002797
2798static PyObject *
2799listiter_reduce(listiterobject *it)
2800{
2801 return listiter_reduce_general(it, 1);
2802}
2803
2804static PyObject *
2805listiter_setstate(listiterobject *it, PyObject *state)
2806{
Victor Stinner7660b882013-06-24 23:59:24 +02002807 Py_ssize_t index = PyLong_AsSsize_t(state);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002808 if (index == -1 && PyErr_Occurred())
2809 return NULL;
2810 if (it->it_seq != NULL) {
2811 if (index < 0)
2812 index = 0;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +00002813 else if (index > PyList_GET_SIZE(it->it_seq))
2814 index = PyList_GET_SIZE(it->it_seq); /* iterator exhausted */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002815 it->it_index = index;
2816 }
2817 Py_RETURN_NONE;
2818}
2819
Raymond Hettinger1021c442003-11-07 15:38:09 +00002820/*********************** List Reverse Iterator **************************/
2821
2822typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002823 PyObject_HEAD
2824 Py_ssize_t it_index;
2825 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger1021c442003-11-07 15:38:09 +00002826} listreviterobject;
2827
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002828static PyObject *list_reversed(PyListObject *, PyObject *);
2829static void listreviter_dealloc(listreviterobject *);
2830static int listreviter_traverse(listreviterobject *, visitproc, void *);
2831static PyObject *listreviter_next(listreviterobject *);
Raymond Hettingerf5b64112008-12-02 21:33:45 +00002832static PyObject *listreviter_len(listreviterobject *);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002833static PyObject *listreviter_reduce(listreviterobject *);
2834static PyObject *listreviter_setstate(listreviterobject *, PyObject *);
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002835
Raymond Hettingerf5b64112008-12-02 21:33:45 +00002836static PyMethodDef listreviter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002837 {"__length_hint__", (PyCFunction)listreviter_len, METH_NOARGS, length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002838 {"__reduce__", (PyCFunction)listreviter_reduce, METH_NOARGS, reduce_doc},
2839 {"__setstate__", (PyCFunction)listreviter_setstate, METH_O, setstate_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002840 {NULL, NULL} /* sentinel */
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002841};
2842
Raymond Hettinger1021c442003-11-07 15:38:09 +00002843PyTypeObject PyListRevIter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002844 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2845 "list_reverseiterator", /* tp_name */
2846 sizeof(listreviterobject), /* tp_basicsize */
2847 0, /* tp_itemsize */
2848 /* methods */
2849 (destructor)listreviter_dealloc, /* tp_dealloc */
2850 0, /* tp_print */
2851 0, /* tp_getattr */
2852 0, /* tp_setattr */
2853 0, /* tp_reserved */
2854 0, /* tp_repr */
2855 0, /* tp_as_number */
2856 0, /* tp_as_sequence */
2857 0, /* tp_as_mapping */
2858 0, /* tp_hash */
2859 0, /* tp_call */
2860 0, /* tp_str */
2861 PyObject_GenericGetAttr, /* tp_getattro */
2862 0, /* tp_setattro */
2863 0, /* tp_as_buffer */
2864 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2865 0, /* tp_doc */
2866 (traverseproc)listreviter_traverse, /* tp_traverse */
2867 0, /* tp_clear */
2868 0, /* tp_richcompare */
2869 0, /* tp_weaklistoffset */
2870 PyObject_SelfIter, /* tp_iter */
2871 (iternextfunc)listreviter_next, /* tp_iternext */
2872 listreviter_methods, /* tp_methods */
2873 0,
Raymond Hettinger1021c442003-11-07 15:38:09 +00002874};
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002875
2876static PyObject *
2877list_reversed(PyListObject *seq, PyObject *unused)
2878{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002879 listreviterobject *it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002880
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002881 it = PyObject_GC_New(listreviterobject, &PyListRevIter_Type);
2882 if (it == NULL)
2883 return NULL;
2884 assert(PyList_Check(seq));
2885 it->it_index = PyList_GET_SIZE(seq) - 1;
2886 Py_INCREF(seq);
2887 it->it_seq = seq;
2888 PyObject_GC_Track(it);
2889 return (PyObject *)it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002890}
2891
2892static void
2893listreviter_dealloc(listreviterobject *it)
2894{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002895 PyObject_GC_UnTrack(it);
2896 Py_XDECREF(it->it_seq);
2897 PyObject_GC_Del(it);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002898}
2899
2900static int
2901listreviter_traverse(listreviterobject *it, visitproc visit, void *arg)
2902{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002903 Py_VISIT(it->it_seq);
2904 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002905}
2906
2907static PyObject *
2908listreviter_next(listreviterobject *it)
2909{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002910 PyObject *item;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03002911 Py_ssize_t index;
2912 PyListObject *seq;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002913
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03002914 assert(it != NULL);
2915 seq = it->it_seq;
2916 if (seq == NULL) {
2917 return NULL;
2918 }
2919 assert(PyList_Check(seq));
2920
2921 index = it->it_index;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002922 if (index>=0 && index < PyList_GET_SIZE(seq)) {
2923 item = PyList_GET_ITEM(seq, index);
2924 it->it_index--;
2925 Py_INCREF(item);
2926 return item;
2927 }
2928 it->it_index = -1;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03002929 it->it_seq = NULL;
2930 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002931 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002932}
2933
Raymond Hettingerf5b64112008-12-02 21:33:45 +00002934static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002935listreviter_len(listreviterobject *it)
2936{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002937 Py_ssize_t len = it->it_index + 1;
2938 if (it->it_seq == NULL || PyList_GET_SIZE(it->it_seq) < len)
2939 len = 0;
2940 return PyLong_FromSsize_t(len);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002941}
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002942
2943static PyObject *
2944listreviter_reduce(listreviterobject *it)
2945{
2946 return listiter_reduce_general(it, 0);
2947}
2948
2949static PyObject *
2950listreviter_setstate(listreviterobject *it, PyObject *state)
2951{
2952 Py_ssize_t index = PyLong_AsSsize_t(state);
2953 if (index == -1 && PyErr_Occurred())
2954 return NULL;
2955 if (it->it_seq != NULL) {
2956 if (index < -1)
2957 index = -1;
2958 else if (index > PyList_GET_SIZE(it->it_seq) - 1)
2959 index = PyList_GET_SIZE(it->it_seq) - 1;
2960 it->it_index = index;
2961 }
2962 Py_RETURN_NONE;
2963}
2964
2965/* common pickling support */
2966
2967static PyObject *
2968listiter_reduce_general(void *_it, int forward)
2969{
2970 PyObject *list;
2971
2972 /* the objects are not the same, index is of different types! */
2973 if (forward) {
2974 listiterobject *it = (listiterobject *)_it;
2975 if (it->it_seq)
Victor Stinner7660b882013-06-24 23:59:24 +02002976 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002977 it->it_seq, it->it_index);
2978 } else {
2979 listreviterobject *it = (listreviterobject *)_it;
2980 if (it->it_seq)
Antoine Pitroua7013882012-04-05 00:04:20 +02002981 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("reversed"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002982 it->it_seq, it->it_index);
2983 }
2984 /* empty iterator, create an empty list */
2985 list = PyList_New(0);
2986 if (list == NULL)
2987 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +02002988 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), list);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002989}