blob: dcd7b5efe5b0fe7bb0e4c4b20b233f7e7a92b6ed [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 */
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -070052 if (new_allocated > SIZE_MAX - newsize) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000053 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;
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -070062 if (new_allocated <= (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 *);
Benjamin Peterson5a7d9232016-09-06 17:58:25 -0700637 /* If norig == 0, item might be NULL, in which case we may not memcpy from it. */
638 if (s) {
639 if (s > sizeof(recycle_on_stack)) {
640 recycle = (PyObject **)PyMem_MALLOC(s);
641 if (recycle == NULL) {
642 PyErr_NoMemory();
643 goto Error;
644 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000645 }
Benjamin Peterson5a7d9232016-09-06 17:58:25 -0700646 memcpy(recycle, &item[ilow], s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 }
Tim Peters8d9eb102004-07-31 02:24:20 +0000648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000649 if (d < 0) { /* Delete -d items */
Victor Stinner2c40f642013-07-19 23:06:21 +0200650 Py_ssize_t tail;
651 tail = (Py_SIZE(a) - ihigh) * sizeof(PyObject *);
652 memmove(&item[ihigh+d], &item[ihigh], tail);
653 if (list_resize(a, Py_SIZE(a) + d) < 0) {
654 memmove(&item[ihigh], &item[ihigh+d], tail);
655 memcpy(&item[ilow], recycle, s);
656 goto Error;
657 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000658 item = a->ob_item;
659 }
660 else if (d > 0) { /* Insert d items */
661 k = Py_SIZE(a);
662 if (list_resize(a, k+d) < 0)
663 goto Error;
664 item = a->ob_item;
665 memmove(&item[ihigh+d], &item[ihigh],
666 (k - ihigh)*sizeof(PyObject *));
667 }
668 for (k = 0; k < n; k++, ilow++) {
669 PyObject *w = vitem[k];
670 Py_XINCREF(w);
671 item[ilow] = w;
672 }
673 for (k = norig - 1; k >= 0; --k)
674 Py_XDECREF(recycle[k]);
675 result = 0;
Tim Peters8d9eb102004-07-31 02:24:20 +0000676 Error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000677 if (recycle != recycle_on_stack)
678 PyMem_FREE(recycle);
679 Py_XDECREF(v_as_SF);
680 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000681#undef b
682}
683
Guido van Rossum234f9421993-06-17 12:35:49 +0000684int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000685PyList_SetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum234f9421993-06-17 12:35:49 +0000686{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000687 if (!PyList_Check(a)) {
688 PyErr_BadInternalCall();
689 return -1;
690 }
691 return list_ass_slice((PyListObject *)a, ilow, ihigh, v);
Guido van Rossum234f9421993-06-17 12:35:49 +0000692}
693
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000694static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000695list_inplace_repeat(PyListObject *self, Py_ssize_t n)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000696{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000697 PyObject **items;
698 Py_ssize_t size, i, j, p;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000699
700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000701 size = PyList_GET_SIZE(self);
702 if (size == 0 || n == 1) {
703 Py_INCREF(self);
704 return (PyObject *)self;
705 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000707 if (n < 1) {
708 (void)list_clear(self);
709 Py_INCREF(self);
710 return (PyObject *)self;
711 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000712
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000713 if (size > PY_SSIZE_T_MAX / n) {
714 return PyErr_NoMemory();
715 }
Christian Heimesaf98da12008-01-27 15:18:18 +0000716
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800717 if (list_resize(self, size*n) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 return NULL;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000719
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000720 p = size;
721 items = self->ob_item;
722 for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */
723 for (j = 0; j < size; j++) {
724 PyObject *o = items[j];
725 Py_INCREF(o);
726 items[p++] = o;
727 }
728 }
729 Py_INCREF(self);
730 return (PyObject *)self;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000731}
732
Guido van Rossum4a450d01991-04-03 19:05:18 +0000733static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000734list_ass_item(PyListObject *a, Py_ssize_t i, PyObject *v)
Guido van Rossum4a450d01991-04-03 19:05:18 +0000735{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 if (i < 0 || i >= Py_SIZE(a)) {
737 PyErr_SetString(PyExc_IndexError,
738 "list assignment index out of range");
739 return -1;
740 }
741 if (v == NULL)
742 return list_ass_slice(a, i, i+1, v);
743 Py_INCREF(v);
Serhiy Storchakaf01e4082016-04-10 18:12:01 +0300744 Py_SETREF(a->ob_item[i], v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000745 return 0;
Guido van Rossum4a450d01991-04-03 19:05:18 +0000746}
747
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000748static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000749listinsert(PyListObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000750{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000751 Py_ssize_t i;
752 PyObject *v;
753 if (!PyArg_ParseTuple(args, "nO:insert", &i, &v))
754 return NULL;
755 if (ins1(self, i, v) == 0)
756 Py_RETURN_NONE;
757 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000758}
759
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000760static PyObject *
Eli Benderskycbbaa962011-02-25 05:47:53 +0000761listclear(PyListObject *self)
762{
763 list_clear(self);
764 Py_RETURN_NONE;
765}
766
767static PyObject *
768listcopy(PyListObject *self)
769{
770 return list_slice(self, 0, Py_SIZE(self));
771}
772
773static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000774listappend(PyListObject *self, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000775{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000776 if (app1(self, v) == 0)
777 Py_RETURN_NONE;
778 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000779}
780
Barry Warsawdedf6d61998-10-09 16:37:25 +0000781static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000782listextend(PyListObject *self, PyObject *b)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000783{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 PyObject *it; /* iter(v) */
785 Py_ssize_t m; /* size of self */
786 Py_ssize_t n; /* guess for size of b */
787 Py_ssize_t mn; /* m + n */
788 Py_ssize_t i;
789 PyObject *(*iternext)(PyObject *);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000790
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000791 /* Special cases:
792 1) lists and tuples which can use PySequence_Fast ops
793 2) extending self to self requires making a copy first
794 */
795 if (PyList_CheckExact(b) || PyTuple_CheckExact(b) || (PyObject *)self == b) {
796 PyObject **src, **dest;
797 b = PySequence_Fast(b, "argument must be iterable");
798 if (!b)
799 return NULL;
800 n = PySequence_Fast_GET_SIZE(b);
801 if (n == 0) {
802 /* short circuit when b is empty */
803 Py_DECREF(b);
804 Py_RETURN_NONE;
805 }
806 m = Py_SIZE(self);
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800807 if (list_resize(self, m + n) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 Py_DECREF(b);
809 return NULL;
810 }
811 /* note that we may still have self == b here for the
812 * situation a.extend(a), but the following code works
813 * in that case too. Just make sure to resize self
814 * before calling PySequence_Fast_ITEMS.
815 */
816 /* populate the end of self with b's items */
817 src = PySequence_Fast_ITEMS(b);
818 dest = self->ob_item + m;
819 for (i = 0; i < n; i++) {
820 PyObject *o = src[i];
821 Py_INCREF(o);
822 dest[i] = o;
823 }
824 Py_DECREF(b);
825 Py_RETURN_NONE;
826 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000827
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000828 it = PyObject_GetIter(b);
829 if (it == NULL)
830 return NULL;
831 iternext = *it->ob_type->tp_iternext;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000832
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000833 /* Guess a result list size. */
Armin Ronacheraa9a79d2012-10-06 14:03:24 +0200834 n = PyObject_LengthHint(b, 8);
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800835 if (n < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 Py_DECREF(it);
837 return NULL;
838 }
839 m = Py_SIZE(self);
Martin Panterb93d8632016-07-25 02:39:20 +0000840 if (m > PY_SSIZE_T_MAX - n) {
841 /* m + n overflowed; on the chance that n lied, and there really
842 * is enough room, ignore it. If n was telling the truth, we'll
843 * eventually run out of memory during the loop.
844 */
845 }
846 else {
847 mn = m + n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 /* Make room. */
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800849 if (list_resize(self, mn) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000850 goto error;
851 /* Make the list sane again. */
852 Py_SIZE(self) = m;
853 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 /* Run iterator to exhaustion. */
856 for (;;) {
857 PyObject *item = iternext(it);
858 if (item == NULL) {
859 if (PyErr_Occurred()) {
860 if (PyErr_ExceptionMatches(PyExc_StopIteration))
861 PyErr_Clear();
862 else
863 goto error;
864 }
865 break;
866 }
867 if (Py_SIZE(self) < self->allocated) {
868 /* steals ref */
869 PyList_SET_ITEM(self, Py_SIZE(self), item);
870 ++Py_SIZE(self);
871 }
872 else {
873 int status = app1(self, item);
874 Py_DECREF(item); /* append creates a new ref */
875 if (status < 0)
876 goto error;
877 }
878 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 /* Cut back result list if initial guess was too large. */
Victor Stinner32fd6ea2013-07-16 21:45:58 +0200881 if (Py_SIZE(self) < self->allocated) {
882 if (list_resize(self, Py_SIZE(self)) < 0)
883 goto error;
884 }
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 Py_DECREF(it);
887 Py_RETURN_NONE;
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000888
889 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000890 Py_DECREF(it);
891 return NULL;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000892}
893
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000894PyObject *
895_PyList_Extend(PyListObject *self, PyObject *b)
896{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000897 return listextend(self, b);
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000898}
899
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000900static PyObject *
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000901list_inplace_concat(PyListObject *self, PyObject *other)
902{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000903 PyObject *result;
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000904
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000905 result = listextend(self, other);
906 if (result == NULL)
907 return result;
908 Py_DECREF(result);
909 Py_INCREF(self);
910 return (PyObject *)self;
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000911}
912
913static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000914listpop(PyListObject *self, PyObject *args)
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000915{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 Py_ssize_t i = -1;
917 PyObject *v;
918 int status;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 if (!PyArg_ParseTuple(args, "|n:pop", &i))
921 return NULL;
Thomas Wouters89f507f2006-12-13 04:49:30 +0000922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000923 if (Py_SIZE(self) == 0) {
924 /* Special-case most common failure cause */
925 PyErr_SetString(PyExc_IndexError, "pop from empty list");
926 return NULL;
927 }
928 if (i < 0)
929 i += Py_SIZE(self);
930 if (i < 0 || i >= Py_SIZE(self)) {
931 PyErr_SetString(PyExc_IndexError, "pop index out of range");
932 return NULL;
933 }
934 v = self->ob_item[i];
935 if (i == Py_SIZE(self) - 1) {
936 status = list_resize(self, Py_SIZE(self) - 1);
Victor Stinnerb27cd3e2013-07-08 22:20:44 +0200937 if (status >= 0)
938 return v; /* and v now owns the reference the list had */
939 else
940 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 }
942 Py_INCREF(v);
943 status = list_ass_slice(self, i, i+1, (PyObject *)NULL);
Victor Stinner095d99f2013-07-17 21:58:01 +0200944 if (status < 0) {
945 Py_DECREF(v);
946 return NULL;
947 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000948 return v;
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000949}
950
Tim Peters8e2e7ca2002-07-19 02:33:08 +0000951/* Reverse a slice of a list in place, from lo up to (exclusive) hi. */
952static void
953reverse_slice(PyObject **lo, PyObject **hi)
954{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 assert(lo && hi);
Tim Peters8e2e7ca2002-07-19 02:33:08 +0000956
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000957 --hi;
958 while (lo < hi) {
959 PyObject *t = *lo;
960 *lo = *hi;
961 *hi = t;
962 ++lo;
963 --hi;
964 }
Tim Peters8e2e7ca2002-07-19 02:33:08 +0000965}
966
Tim Petersa64dc242002-08-01 02:13:36 +0000967/* Lots of code for an adaptive, stable, natural mergesort. There are many
968 * pieces to this algorithm; read listsort.txt for overviews and details.
969 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000970
Daniel Stutzbach98338222010-12-02 21:55:33 +0000971/* A sortslice contains a pointer to an array of keys and a pointer to
972 * an array of corresponding values. In other words, keys[i]
973 * corresponds with values[i]. If values == NULL, then the keys are
974 * also the values.
975 *
976 * Several convenience routines are provided here, so that keys and
977 * values are always moved in sync.
978 */
979
980typedef struct {
981 PyObject **keys;
982 PyObject **values;
983} sortslice;
984
985Py_LOCAL_INLINE(void)
986sortslice_copy(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j)
987{
988 s1->keys[i] = s2->keys[j];
989 if (s1->values != NULL)
990 s1->values[i] = s2->values[j];
991}
992
993Py_LOCAL_INLINE(void)
Benjamin Peterson9efdcca2010-12-03 01:44:10 +0000994sortslice_copy_incr(sortslice *dst, sortslice *src)
995{
Daniel Stutzbach98338222010-12-02 21:55:33 +0000996 *dst->keys++ = *src->keys++;
997 if (dst->values != NULL)
998 *dst->values++ = *src->values++;
999}
1000
1001Py_LOCAL_INLINE(void)
Benjamin Peterson9efdcca2010-12-03 01:44:10 +00001002sortslice_copy_decr(sortslice *dst, sortslice *src)
1003{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001004 *dst->keys-- = *src->keys--;
1005 if (dst->values != NULL)
1006 *dst->values-- = *src->values--;
1007}
1008
1009
1010Py_LOCAL_INLINE(void)
1011sortslice_memcpy(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j,
Benjamin Peterson9efdcca2010-12-03 01:44:10 +00001012 Py_ssize_t n)
1013{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001014 memcpy(&s1->keys[i], &s2->keys[j], sizeof(PyObject *) * n);
1015 if (s1->values != NULL)
1016 memcpy(&s1->values[i], &s2->values[j], sizeof(PyObject *) * n);
1017}
1018
1019Py_LOCAL_INLINE(void)
1020sortslice_memmove(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j,
Benjamin Peterson9efdcca2010-12-03 01:44:10 +00001021 Py_ssize_t n)
1022{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001023 memmove(&s1->keys[i], &s2->keys[j], sizeof(PyObject *) * n);
1024 if (s1->values != NULL)
1025 memmove(&s1->values[i], &s2->values[j], sizeof(PyObject *) * n);
1026}
1027
1028Py_LOCAL_INLINE(void)
Benjamin Peterson9efdcca2010-12-03 01:44:10 +00001029sortslice_advance(sortslice *slice, Py_ssize_t n)
1030{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001031 slice->keys += n;
1032 if (slice->values != NULL)
1033 slice->values += n;
1034}
1035
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001036/* Comparison function: PyObject_RichCompareBool with Py_LT.
Tim Petersa64dc242002-08-01 02:13:36 +00001037 * Returns -1 on error, 1 if x < y, 0 if x >= y.
1038 */
Guido van Rossum3f236de1996-12-10 23:55:39 +00001039
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001040#define ISLT(X, Y) (PyObject_RichCompareBool(X, Y, Py_LT))
Tim Peters66860f62002-08-04 17:47:26 +00001041
1042/* Compare X to Y via "<". Goto "fail" if the comparison raises an
Tim Petersa8c974c2002-07-19 03:30:57 +00001043 error. Else "k" is set to true iff X<Y, and an "if (k)" block is
1044 started. It makes more sense in context <wink>. X and Y are PyObject*s.
1045*/
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001046#define IFLT(X, Y) if ((k = ISLT(X, Y)) < 0) goto fail; \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047 if (k)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001048
1049/* binarysort is the best method for sorting small arrays: it does
1050 few compares, but can do data movement quadratic in the number of
1051 elements.
Guido van Rossum42812581998-06-17 14:15:44 +00001052 [lo, hi) is a contiguous slice of a list, and is sorted via
Tim Petersa8c974c2002-07-19 03:30:57 +00001053 binary insertion. This sort is stable.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001054 On entry, must have lo <= start <= hi, and that [lo, start) is already
1055 sorted (pass start == lo if you don't know!).
Tim Petersa8c974c2002-07-19 03:30:57 +00001056 If islt() complains return -1, else 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001057 Even in case of error, the output slice will be some permutation of
1058 the input (nothing is lost or duplicated).
1059*/
Guido van Rossum3f236de1996-12-10 23:55:39 +00001060static int
Daniel Stutzbach98338222010-12-02 21:55:33 +00001061binarysort(sortslice lo, PyObject **hi, PyObject **start)
Guido van Rossum3f236de1996-12-10 23:55:39 +00001062{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001063 Py_ssize_t k;
1064 PyObject **l, **p, **r;
1065 PyObject *pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001066
Daniel Stutzbach98338222010-12-02 21:55:33 +00001067 assert(lo.keys <= start && start <= hi);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001068 /* assert [lo, start) is sorted */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001069 if (lo.keys == start)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 ++start;
1071 for (; start < hi; ++start) {
1072 /* set l to where *start belongs */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001073 l = lo.keys;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001074 r = start;
1075 pivot = *r;
1076 /* Invariants:
1077 * pivot >= all in [lo, l).
1078 * pivot < all in [r, start).
1079 * The second is vacuously true at the start.
1080 */
1081 assert(l < r);
1082 do {
1083 p = l + ((r - l) >> 1);
1084 IFLT(pivot, *p)
1085 r = p;
1086 else
1087 l = p+1;
1088 } while (l < r);
1089 assert(l == r);
1090 /* The invariants still hold, so pivot >= all in [lo, l) and
1091 pivot < all in [l, start), so pivot belongs at l. Note
1092 that if there are elements equal to pivot, l points to the
1093 first slot after them -- that's why this sort is stable.
1094 Slide over to make room.
1095 Caution: using memmove is much slower under MSVC 5;
1096 we're not usually moving many slots. */
1097 for (p = start; p > l; --p)
1098 *p = *(p-1);
1099 *l = pivot;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001100 if (lo.values != NULL) {
1101 Py_ssize_t offset = lo.values - lo.keys;
1102 p = start + offset;
1103 pivot = *p;
1104 l += offset;
1105 for (p = start + offset; p > l; --p)
1106 *p = *(p-1);
1107 *l = pivot;
1108 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001109 }
1110 return 0;
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001111
1112 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001113 return -1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001114}
1115
Tim Petersa64dc242002-08-01 02:13:36 +00001116/*
1117Return the length of the run beginning at lo, in the slice [lo, hi). lo < hi
1118is required on entry. "A run" is the longest ascending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001119
Tim Petersa64dc242002-08-01 02:13:36 +00001120 lo[0] <= lo[1] <= lo[2] <= ...
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001121
Tim Petersa64dc242002-08-01 02:13:36 +00001122or the longest descending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001123
Tim Petersa64dc242002-08-01 02:13:36 +00001124 lo[0] > lo[1] > lo[2] > ...
Tim Peters3b01a122002-07-19 02:35:45 +00001125
Tim Petersa64dc242002-08-01 02:13:36 +00001126Boolean *descending is set to 0 in the former case, or to 1 in the latter.
1127For its intended use in a stable mergesort, the strictness of the defn of
1128"descending" is needed so that the caller can safely reverse a descending
1129sequence without violating stability (strict > ensures there are no equal
1130elements to get out of order).
1131
1132Returns -1 in case of error.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001133*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001134static Py_ssize_t
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001135count_run(PyObject **lo, PyObject **hi, int *descending)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001136{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001137 Py_ssize_t k;
1138 Py_ssize_t n;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001139
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001140 assert(lo < hi);
1141 *descending = 0;
1142 ++lo;
1143 if (lo == hi)
1144 return 1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001145
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001146 n = 2;
1147 IFLT(*lo, *(lo-1)) {
1148 *descending = 1;
1149 for (lo = lo+1; lo < hi; ++lo, ++n) {
1150 IFLT(*lo, *(lo-1))
1151 ;
1152 else
1153 break;
1154 }
1155 }
1156 else {
1157 for (lo = lo+1; lo < hi; ++lo, ++n) {
1158 IFLT(*lo, *(lo-1))
1159 break;
1160 }
1161 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001163 return n;
Tim Petersa64dc242002-08-01 02:13:36 +00001164fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001165 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001166}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001167
Tim Petersa64dc242002-08-01 02:13:36 +00001168/*
1169Locate the proper position of key in a sorted vector; if the vector contains
1170an element equal to key, return the position immediately to the left of
1171the leftmost equal element. [gallop_right() does the same except returns
1172the position to the right of the rightmost equal element (if any).]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001173
Tim Petersa64dc242002-08-01 02:13:36 +00001174"a" is a sorted vector with n elements, starting at a[0]. n must be > 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001175
Tim Petersa64dc242002-08-01 02:13:36 +00001176"hint" is an index at which to begin the search, 0 <= hint < n. The closer
1177hint is to the final result, the faster this runs.
1178
1179The return value is the int k in 0..n such that
1180
1181 a[k-1] < key <= a[k]
1182
1183pretending that *(a-1) is minus infinity and a[n] is plus infinity. IOW,
1184key belongs at index k; or, IOW, the first k elements of a should precede
1185key, and the last n-k should follow key.
1186
1187Returns -1 on error. See listsort.txt for info on the method.
1188*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001189static Py_ssize_t
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001190gallop_left(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint)
Tim Petersa64dc242002-08-01 02:13:36 +00001191{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001192 Py_ssize_t ofs;
1193 Py_ssize_t lastofs;
1194 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001196 assert(key && a && n > 0 && hint >= 0 && hint < n);
Tim Petersa64dc242002-08-01 02:13:36 +00001197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001198 a += hint;
1199 lastofs = 0;
1200 ofs = 1;
1201 IFLT(*a, key) {
1202 /* a[hint] < key -- gallop right, until
1203 * a[hint + lastofs] < key <= a[hint + ofs]
1204 */
1205 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
1206 while (ofs < maxofs) {
1207 IFLT(a[ofs], key) {
1208 lastofs = ofs;
1209 ofs = (ofs << 1) + 1;
1210 if (ofs <= 0) /* int overflow */
1211 ofs = maxofs;
1212 }
1213 else /* key <= a[hint + ofs] */
1214 break;
1215 }
1216 if (ofs > maxofs)
1217 ofs = maxofs;
1218 /* Translate back to offsets relative to &a[0]. */
1219 lastofs += hint;
1220 ofs += hint;
1221 }
1222 else {
1223 /* key <= a[hint] -- gallop left, until
1224 * a[hint - ofs] < key <= a[hint - lastofs]
1225 */
1226 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
1227 while (ofs < maxofs) {
1228 IFLT(*(a-ofs), key)
1229 break;
1230 /* key <= a[hint - ofs] */
1231 lastofs = ofs;
1232 ofs = (ofs << 1) + 1;
1233 if (ofs <= 0) /* int overflow */
1234 ofs = maxofs;
1235 }
1236 if (ofs > maxofs)
1237 ofs = maxofs;
1238 /* Translate back to positive offsets relative to &a[0]. */
1239 k = lastofs;
1240 lastofs = hint - ofs;
1241 ofs = hint - k;
1242 }
1243 a -= hint;
Tim Petersa64dc242002-08-01 02:13:36 +00001244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001245 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1246 /* Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the
1247 * right of lastofs but no farther right than ofs. Do a binary
1248 * search, with invariant a[lastofs-1] < key <= a[ofs].
1249 */
1250 ++lastofs;
1251 while (lastofs < ofs) {
1252 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001254 IFLT(a[m], key)
1255 lastofs = m+1; /* a[m] < key */
1256 else
1257 ofs = m; /* key <= a[m] */
1258 }
1259 assert(lastofs == ofs); /* so a[ofs-1] < key <= a[ofs] */
1260 return ofs;
Tim Petersa64dc242002-08-01 02:13:36 +00001261
1262fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001264}
1265
1266/*
1267Exactly like gallop_left(), except that if key already exists in a[0:n],
1268finds the position immediately to the right of the rightmost equal value.
1269
1270The return value is the int k in 0..n such that
1271
1272 a[k-1] <= key < a[k]
1273
1274or -1 if error.
1275
1276The code duplication is massive, but this is enough different given that
1277we're sticking to "<" comparisons that it's much harder to follow if
1278written as one routine with yet another "left or right?" flag.
1279*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001280static Py_ssize_t
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001281gallop_right(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint)
Tim Petersa64dc242002-08-01 02:13:36 +00001282{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001283 Py_ssize_t ofs;
1284 Py_ssize_t lastofs;
1285 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001287 assert(key && a && n > 0 && hint >= 0 && hint < n);
Tim Petersa64dc242002-08-01 02:13:36 +00001288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001289 a += hint;
1290 lastofs = 0;
1291 ofs = 1;
1292 IFLT(key, *a) {
1293 /* key < a[hint] -- gallop left, until
1294 * a[hint - ofs] <= key < a[hint - lastofs]
1295 */
1296 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
1297 while (ofs < maxofs) {
1298 IFLT(key, *(a-ofs)) {
1299 lastofs = ofs;
1300 ofs = (ofs << 1) + 1;
1301 if (ofs <= 0) /* int overflow */
1302 ofs = maxofs;
1303 }
1304 else /* a[hint - ofs] <= key */
1305 break;
1306 }
1307 if (ofs > maxofs)
1308 ofs = maxofs;
1309 /* Translate back to positive offsets relative to &a[0]. */
1310 k = lastofs;
1311 lastofs = hint - ofs;
1312 ofs = hint - k;
1313 }
1314 else {
1315 /* a[hint] <= key -- gallop right, until
1316 * a[hint + lastofs] <= key < a[hint + ofs]
1317 */
1318 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
1319 while (ofs < maxofs) {
1320 IFLT(key, a[ofs])
1321 break;
1322 /* a[hint + ofs] <= key */
1323 lastofs = ofs;
1324 ofs = (ofs << 1) + 1;
1325 if (ofs <= 0) /* int overflow */
1326 ofs = maxofs;
1327 }
1328 if (ofs > maxofs)
1329 ofs = maxofs;
1330 /* Translate back to offsets relative to &a[0]. */
1331 lastofs += hint;
1332 ofs += hint;
1333 }
1334 a -= hint;
Tim Petersa64dc242002-08-01 02:13:36 +00001335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1337 /* Now a[lastofs] <= key < a[ofs], so key belongs somewhere to the
1338 * right of lastofs but no farther right than ofs. Do a binary
1339 * search, with invariant a[lastofs-1] <= key < a[ofs].
1340 */
1341 ++lastofs;
1342 while (lastofs < ofs) {
1343 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001345 IFLT(key, a[m])
1346 ofs = m; /* key < a[m] */
1347 else
1348 lastofs = m+1; /* a[m] <= key */
1349 }
1350 assert(lastofs == ofs); /* so a[ofs-1] <= key < a[ofs] */
1351 return ofs;
Tim Petersa64dc242002-08-01 02:13:36 +00001352
1353fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001354 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001355}
1356
1357/* The maximum number of entries in a MergeState's pending-runs stack.
1358 * This is enough to sort arrays of size up to about
1359 * 32 * phi ** MAX_MERGE_PENDING
1360 * where phi ~= 1.618. 85 is ridiculouslylarge enough, good for an array
1361 * with 2**64 elements.
1362 */
1363#define MAX_MERGE_PENDING 85
1364
Tim Peterse05f65a2002-08-10 05:21:15 +00001365/* When we get into galloping mode, we stay there until both runs win less
1366 * often than MIN_GALLOP consecutive times. See listsort.txt for more info.
Tim Petersa64dc242002-08-01 02:13:36 +00001367 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001368#define MIN_GALLOP 7
Tim Petersa64dc242002-08-01 02:13:36 +00001369
1370/* Avoid malloc for small temp arrays. */
1371#define MERGESTATE_TEMP_SIZE 256
1372
1373/* One MergeState exists on the stack per invocation of mergesort. It's just
1374 * a convenient way to pass state around among the helper functions.
1375 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001376struct s_slice {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001377 sortslice base;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001378 Py_ssize_t len;
Tim Peterse05f65a2002-08-10 05:21:15 +00001379};
1380
Tim Petersa64dc242002-08-01 02:13:36 +00001381typedef struct s_MergeState {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001382 /* This controls when we get *into* galloping mode. It's initialized
1383 * to MIN_GALLOP. merge_lo and merge_hi tend to nudge it higher for
1384 * random data, and lower for highly structured data.
1385 */
1386 Py_ssize_t min_gallop;
Tim Peterse05f65a2002-08-10 05:21:15 +00001387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001388 /* 'a' is temp storage to help with merges. It contains room for
1389 * alloced entries.
1390 */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001391 sortslice a; /* may point to temparray below */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001392 Py_ssize_t alloced;
Tim Petersa64dc242002-08-01 02:13:36 +00001393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001394 /* A stack of n pending runs yet to be merged. Run #i starts at
1395 * address base[i] and extends for len[i] elements. It's always
1396 * true (so long as the indices are in bounds) that
1397 *
1398 * pending[i].base + pending[i].len == pending[i+1].base
1399 *
1400 * so we could cut the storage for this, but it's a minor amount,
1401 * and keeping all the info explicit simplifies the code.
1402 */
1403 int n;
1404 struct s_slice pending[MAX_MERGE_PENDING];
Tim Petersa64dc242002-08-01 02:13:36 +00001405
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001406 /* 'a' points to this when possible, rather than muck with malloc. */
1407 PyObject *temparray[MERGESTATE_TEMP_SIZE];
Tim Petersa64dc242002-08-01 02:13:36 +00001408} MergeState;
1409
1410/* Conceptually a MergeState's constructor. */
1411static void
Victor Stinner0fcab4a2011-01-04 12:59:15 +00001412merge_init(MergeState *ms, Py_ssize_t list_size, int has_keyfunc)
Tim Petersa64dc242002-08-01 02:13:36 +00001413{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001414 assert(ms != NULL);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001415 if (has_keyfunc) {
1416 /* The temporary space for merging will need at most half the list
1417 * size rounded up. Use the minimum possible space so we can use the
1418 * rest of temparray for other things. In particular, if there is
1419 * enough extra space, listsort() will use it to store the keys.
1420 */
1421 ms->alloced = (list_size + 1) / 2;
1422
1423 /* ms->alloced describes how many keys will be stored at
1424 ms->temparray, but we also need to store the values. Hence,
1425 ms->alloced is capped at half of MERGESTATE_TEMP_SIZE. */
1426 if (MERGESTATE_TEMP_SIZE / 2 < ms->alloced)
1427 ms->alloced = MERGESTATE_TEMP_SIZE / 2;
1428 ms->a.values = &ms->temparray[ms->alloced];
1429 }
1430 else {
1431 ms->alloced = MERGESTATE_TEMP_SIZE;
1432 ms->a.values = NULL;
1433 }
1434 ms->a.keys = ms->temparray;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001435 ms->n = 0;
1436 ms->min_gallop = MIN_GALLOP;
Tim Petersa64dc242002-08-01 02:13:36 +00001437}
1438
1439/* Free all the temp memory owned by the MergeState. This must be called
1440 * when you're done with a MergeState, and may be called before then if
1441 * you want to free the temp memory early.
1442 */
1443static void
1444merge_freemem(MergeState *ms)
1445{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001446 assert(ms != NULL);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001447 if (ms->a.keys != ms->temparray)
1448 PyMem_Free(ms->a.keys);
Tim Petersa64dc242002-08-01 02:13:36 +00001449}
1450
1451/* Ensure enough temp memory for 'need' array slots is available.
1452 * Returns 0 on success and -1 if the memory can't be gotten.
1453 */
1454static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001455merge_getmem(MergeState *ms, Py_ssize_t need)
Tim Petersa64dc242002-08-01 02:13:36 +00001456{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001457 int multiplier;
1458
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001459 assert(ms != NULL);
1460 if (need <= ms->alloced)
1461 return 0;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001462
1463 multiplier = ms->a.values != NULL ? 2 : 1;
1464
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001465 /* Don't realloc! That can cost cycles to copy the old data, but
1466 * we don't care what's in the block.
1467 */
1468 merge_freemem(ms);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001469 if ((size_t)need > PY_SSIZE_T_MAX / sizeof(PyObject*) / multiplier) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001470 PyErr_NoMemory();
1471 return -1;
1472 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001473 ms->a.keys = (PyObject**)PyMem_Malloc(multiplier * need
1474 * sizeof(PyObject *));
1475 if (ms->a.keys != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001476 ms->alloced = need;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001477 if (ms->a.values != NULL)
1478 ms->a.values = &ms->a.keys[need];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001479 return 0;
1480 }
1481 PyErr_NoMemory();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001482 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001483}
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001484#define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 : \
1485 merge_getmem(MS, NEED))
Tim Petersa64dc242002-08-01 02:13:36 +00001486
Daniel Stutzbach98338222010-12-02 21:55:33 +00001487/* Merge the na elements starting at ssa with the nb elements starting at
1488 * ssb.keys = ssa.keys + na in a stable way, in-place. na and nb must be > 0.
1489 * Must also have that ssa.keys[na-1] belongs at the end of the merge, and
1490 * should have na <= nb. See listsort.txt for more info. Return 0 if
1491 * successful, -1 if error.
Tim Petersa64dc242002-08-01 02:13:36 +00001492 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001493static Py_ssize_t
Daniel Stutzbach98338222010-12-02 21:55:33 +00001494merge_lo(MergeState *ms, sortslice ssa, Py_ssize_t na,
1495 sortslice ssb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001496{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001497 Py_ssize_t k;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001498 sortslice dest;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001499 int result = -1; /* guilty until proved innocent */
1500 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001501
Daniel Stutzbach98338222010-12-02 21:55:33 +00001502 assert(ms && ssa.keys && ssb.keys && na > 0 && nb > 0);
1503 assert(ssa.keys + na == ssb.keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001504 if (MERGE_GETMEM(ms, na) < 0)
1505 return -1;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001506 sortslice_memcpy(&ms->a, 0, &ssa, 0, na);
1507 dest = ssa;
1508 ssa = ms->a;
Tim Petersa64dc242002-08-01 02:13:36 +00001509
Daniel Stutzbach98338222010-12-02 21:55:33 +00001510 sortslice_copy_incr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001511 --nb;
1512 if (nb == 0)
1513 goto Succeed;
1514 if (na == 1)
1515 goto CopyB;
Tim Petersa64dc242002-08-01 02:13:36 +00001516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001517 min_gallop = ms->min_gallop;
1518 for (;;) {
1519 Py_ssize_t acount = 0; /* # of times A won in a row */
1520 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001522 /* Do the straightforward thing until (if ever) one run
1523 * appears to win consistently.
1524 */
1525 for (;;) {
1526 assert(na > 1 && nb > 0);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001527 k = ISLT(ssb.keys[0], ssa.keys[0]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001528 if (k) {
1529 if (k < 0)
1530 goto Fail;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001531 sortslice_copy_incr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001532 ++bcount;
1533 acount = 0;
1534 --nb;
1535 if (nb == 0)
1536 goto Succeed;
1537 if (bcount >= min_gallop)
1538 break;
1539 }
1540 else {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001541 sortslice_copy_incr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001542 ++acount;
1543 bcount = 0;
1544 --na;
1545 if (na == 1)
1546 goto CopyB;
1547 if (acount >= min_gallop)
1548 break;
1549 }
1550 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001551
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001552 /* One run is winning so consistently that galloping may
1553 * be a huge win. So try that, and continue galloping until
1554 * (if ever) neither run appears to be winning consistently
1555 * anymore.
1556 */
1557 ++min_gallop;
1558 do {
1559 assert(na > 1 && nb > 0);
1560 min_gallop -= min_gallop > 1;
1561 ms->min_gallop = min_gallop;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001562 k = gallop_right(ssb.keys[0], ssa.keys, na, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001563 acount = k;
1564 if (k) {
1565 if (k < 0)
1566 goto Fail;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001567 sortslice_memcpy(&dest, 0, &ssa, 0, k);
1568 sortslice_advance(&dest, k);
1569 sortslice_advance(&ssa, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001570 na -= k;
1571 if (na == 1)
1572 goto CopyB;
1573 /* na==0 is impossible now if the comparison
1574 * function is consistent, but we can't assume
1575 * that it is.
1576 */
1577 if (na == 0)
1578 goto Succeed;
1579 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001580 sortslice_copy_incr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001581 --nb;
1582 if (nb == 0)
1583 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001584
Daniel Stutzbach98338222010-12-02 21:55:33 +00001585 k = gallop_left(ssa.keys[0], ssb.keys, nb, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001586 bcount = k;
1587 if (k) {
1588 if (k < 0)
1589 goto Fail;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001590 sortslice_memmove(&dest, 0, &ssb, 0, k);
1591 sortslice_advance(&dest, k);
1592 sortslice_advance(&ssb, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001593 nb -= k;
1594 if (nb == 0)
1595 goto Succeed;
1596 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001597 sortslice_copy_incr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001598 --na;
1599 if (na == 1)
1600 goto CopyB;
1601 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
1602 ++min_gallop; /* penalize it for leaving galloping mode */
1603 ms->min_gallop = min_gallop;
1604 }
Tim Petersa64dc242002-08-01 02:13:36 +00001605Succeed:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001606 result = 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001607Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001608 if (na)
Daniel Stutzbach98338222010-12-02 21:55:33 +00001609 sortslice_memcpy(&dest, 0, &ssa, 0, na);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001610 return result;
Tim Petersa64dc242002-08-01 02:13:36 +00001611CopyB:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001612 assert(na == 1 && nb > 0);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001613 /* The last element of ssa belongs at the end of the merge. */
1614 sortslice_memmove(&dest, 0, &ssb, 0, nb);
1615 sortslice_copy(&dest, nb, &ssa, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001616 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001617}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001618
Daniel Stutzbach98338222010-12-02 21:55:33 +00001619/* Merge the na elements starting at pa with the nb elements starting at
1620 * ssb.keys = ssa.keys + na in a stable way, in-place. na and nb must be > 0.
1621 * Must also have that ssa.keys[na-1] belongs at the end of the merge, and
1622 * should have na >= nb. See listsort.txt for more info. Return 0 if
1623 * successful, -1 if error.
Tim Petersa64dc242002-08-01 02:13:36 +00001624 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001625static Py_ssize_t
Daniel Stutzbach98338222010-12-02 21:55:33 +00001626merge_hi(MergeState *ms, sortslice ssa, Py_ssize_t na,
1627 sortslice ssb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001628{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001629 Py_ssize_t k;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001630 sortslice dest, basea, baseb;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001631 int result = -1; /* guilty until proved innocent */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001632 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001633
Daniel Stutzbach98338222010-12-02 21:55:33 +00001634 assert(ms && ssa.keys && ssb.keys && na > 0 && nb > 0);
1635 assert(ssa.keys + na == ssb.keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001636 if (MERGE_GETMEM(ms, nb) < 0)
1637 return -1;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001638 dest = ssb;
1639 sortslice_advance(&dest, nb-1);
1640 sortslice_memcpy(&ms->a, 0, &ssb, 0, nb);
1641 basea = ssa;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001642 baseb = ms->a;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001643 ssb.keys = ms->a.keys + nb - 1;
1644 if (ssb.values != NULL)
1645 ssb.values = ms->a.values + nb - 1;
1646 sortslice_advance(&ssa, na - 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001647
Daniel Stutzbach98338222010-12-02 21:55:33 +00001648 sortslice_copy_decr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001649 --na;
1650 if (na == 0)
1651 goto Succeed;
1652 if (nb == 1)
1653 goto CopyA;
Tim Petersa64dc242002-08-01 02:13:36 +00001654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001655 min_gallop = ms->min_gallop;
1656 for (;;) {
1657 Py_ssize_t acount = 0; /* # of times A won in a row */
1658 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001659
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001660 /* Do the straightforward thing until (if ever) one run
1661 * appears to win consistently.
1662 */
1663 for (;;) {
1664 assert(na > 0 && nb > 1);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001665 k = ISLT(ssb.keys[0], ssa.keys[0]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001666 if (k) {
1667 if (k < 0)
1668 goto Fail;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001669 sortslice_copy_decr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001670 ++acount;
1671 bcount = 0;
1672 --na;
1673 if (na == 0)
1674 goto Succeed;
1675 if (acount >= min_gallop)
1676 break;
1677 }
1678 else {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001679 sortslice_copy_decr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001680 ++bcount;
1681 acount = 0;
1682 --nb;
1683 if (nb == 1)
1684 goto CopyA;
1685 if (bcount >= min_gallop)
1686 break;
1687 }
1688 }
Tim Petersa64dc242002-08-01 02:13:36 +00001689
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001690 /* One run is winning so consistently that galloping may
1691 * be a huge win. So try that, and continue galloping until
1692 * (if ever) neither run appears to be winning consistently
1693 * anymore.
1694 */
1695 ++min_gallop;
1696 do {
1697 assert(na > 0 && nb > 1);
1698 min_gallop -= min_gallop > 1;
1699 ms->min_gallop = min_gallop;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001700 k = gallop_right(ssb.keys[0], basea.keys, na, na-1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001701 if (k < 0)
1702 goto Fail;
1703 k = na - k;
1704 acount = k;
1705 if (k) {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001706 sortslice_advance(&dest, -k);
1707 sortslice_advance(&ssa, -k);
1708 sortslice_memmove(&dest, 1, &ssa, 1, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001709 na -= k;
1710 if (na == 0)
1711 goto Succeed;
1712 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001713 sortslice_copy_decr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001714 --nb;
1715 if (nb == 1)
1716 goto CopyA;
Tim Petersa64dc242002-08-01 02:13:36 +00001717
Daniel Stutzbach98338222010-12-02 21:55:33 +00001718 k = gallop_left(ssa.keys[0], baseb.keys, nb, nb-1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001719 if (k < 0)
1720 goto Fail;
1721 k = nb - k;
1722 bcount = k;
1723 if (k) {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001724 sortslice_advance(&dest, -k);
1725 sortslice_advance(&ssb, -k);
1726 sortslice_memcpy(&dest, 1, &ssb, 1, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001727 nb -= k;
1728 if (nb == 1)
1729 goto CopyA;
1730 /* nb==0 is impossible now if the comparison
1731 * function is consistent, but we can't assume
1732 * that it is.
1733 */
1734 if (nb == 0)
1735 goto Succeed;
1736 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001737 sortslice_copy_decr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001738 --na;
1739 if (na == 0)
1740 goto Succeed;
1741 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
1742 ++min_gallop; /* penalize it for leaving galloping mode */
1743 ms->min_gallop = min_gallop;
1744 }
Tim Petersa64dc242002-08-01 02:13:36 +00001745Succeed:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001746 result = 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001747Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001748 if (nb)
Daniel Stutzbach98338222010-12-02 21:55:33 +00001749 sortslice_memcpy(&dest, -(nb-1), &baseb, 0, nb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001750 return result;
Tim Petersa64dc242002-08-01 02:13:36 +00001751CopyA:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001752 assert(nb == 1 && na > 0);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001753 /* The first element of ssb belongs at the front of the merge. */
1754 sortslice_memmove(&dest, 1-na, &ssa, 1-na, na);
1755 sortslice_advance(&dest, -na);
1756 sortslice_advance(&ssa, -na);
1757 sortslice_copy(&dest, 0, &ssb, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001758 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001759}
1760
1761/* Merge the two runs at stack indices i and i+1.
1762 * Returns 0 on success, -1 on error.
1763 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001764static Py_ssize_t
1765merge_at(MergeState *ms, Py_ssize_t i)
Tim Petersa64dc242002-08-01 02:13:36 +00001766{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001767 sortslice ssa, ssb;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001768 Py_ssize_t na, nb;
1769 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001771 assert(ms != NULL);
1772 assert(ms->n >= 2);
1773 assert(i >= 0);
1774 assert(i == ms->n - 2 || i == ms->n - 3);
Tim Petersa64dc242002-08-01 02:13:36 +00001775
Daniel Stutzbach98338222010-12-02 21:55:33 +00001776 ssa = ms->pending[i].base;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001777 na = ms->pending[i].len;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001778 ssb = ms->pending[i+1].base;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001779 nb = ms->pending[i+1].len;
1780 assert(na > 0 && nb > 0);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001781 assert(ssa.keys + na == ssb.keys);
Tim Petersa64dc242002-08-01 02:13:36 +00001782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001783 /* Record the length of the combined runs; if i is the 3rd-last
1784 * run now, also slide over the last run (which isn't involved
1785 * in this merge). The current run i+1 goes away in any case.
1786 */
1787 ms->pending[i].len = na + nb;
1788 if (i == ms->n - 3)
1789 ms->pending[i+1] = ms->pending[i+2];
1790 --ms->n;
Tim Petersa64dc242002-08-01 02:13:36 +00001791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001792 /* Where does b start in a? Elements in a before that can be
1793 * ignored (already in place).
1794 */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001795 k = gallop_right(*ssb.keys, ssa.keys, na, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001796 if (k < 0)
1797 return -1;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001798 sortslice_advance(&ssa, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001799 na -= k;
1800 if (na == 0)
1801 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001802
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001803 /* Where does a end in b? Elements in b after that can be
1804 * ignored (already in place).
1805 */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001806 nb = gallop_left(ssa.keys[na-1], ssb.keys, nb, nb-1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001807 if (nb <= 0)
1808 return nb;
Tim Petersa64dc242002-08-01 02:13:36 +00001809
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001810 /* Merge what remains of the runs, using a temp array with
1811 * min(na, nb) elements.
1812 */
1813 if (na <= nb)
Daniel Stutzbach98338222010-12-02 21:55:33 +00001814 return merge_lo(ms, ssa, na, ssb, nb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001815 else
Daniel Stutzbach98338222010-12-02 21:55:33 +00001816 return merge_hi(ms, ssa, na, ssb, nb);
Tim Petersa64dc242002-08-01 02:13:36 +00001817}
1818
1819/* Examine the stack of runs waiting to be merged, merging adjacent runs
1820 * until the stack invariants are re-established:
1821 *
1822 * 1. len[-3] > len[-2] + len[-1]
1823 * 2. len[-2] > len[-1]
1824 *
1825 * See listsort.txt for more info.
1826 *
1827 * Returns 0 on success, -1 on error.
1828 */
1829static int
1830merge_collapse(MergeState *ms)
1831{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001832 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001834 assert(ms);
1835 while (ms->n > 1) {
1836 Py_ssize_t n = ms->n - 2;
Benjamin Petersonb808d592015-02-25 10:12:26 -05001837 if ((n > 0 && p[n-1].len <= p[n].len + p[n+1].len) ||
1838 (n > 1 && p[n-2].len <= p[n-1].len + p[n].len)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001839 if (p[n-1].len < p[n+1].len)
1840 --n;
1841 if (merge_at(ms, n) < 0)
1842 return -1;
1843 }
1844 else if (p[n].len <= p[n+1].len) {
1845 if (merge_at(ms, n) < 0)
1846 return -1;
1847 }
1848 else
1849 break;
1850 }
1851 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001852}
1853
1854/* Regardless of invariants, merge all runs on the stack until only one
1855 * remains. This is used at the end of the mergesort.
1856 *
1857 * Returns 0 on success, -1 on error.
1858 */
1859static int
1860merge_force_collapse(MergeState *ms)
1861{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001862 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001864 assert(ms);
1865 while (ms->n > 1) {
1866 Py_ssize_t n = ms->n - 2;
1867 if (n > 0 && p[n-1].len < p[n+1].len)
1868 --n;
1869 if (merge_at(ms, n) < 0)
1870 return -1;
1871 }
1872 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001873}
1874
1875/* Compute a good value for the minimum run length; natural runs shorter
1876 * than this are boosted artificially via binary insertion.
1877 *
1878 * If n < 64, return n (it's too small to bother with fancy stuff).
1879 * Else if n is an exact power of 2, return 32.
1880 * Else return an int k, 32 <= k <= 64, such that n/k is close to, but
1881 * strictly less than, an exact power of 2.
1882 *
1883 * See listsort.txt for more info.
1884 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001885static Py_ssize_t
1886merge_compute_minrun(Py_ssize_t n)
Tim Petersa64dc242002-08-01 02:13:36 +00001887{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001888 Py_ssize_t r = 0; /* becomes 1 if any 1 bits are shifted off */
Tim Petersa64dc242002-08-01 02:13:36 +00001889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001890 assert(n >= 0);
1891 while (n >= 64) {
1892 r |= n & 1;
1893 n >>= 1;
1894 }
1895 return n + r;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001896}
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001897
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001898static void
Daniel Stutzbach98338222010-12-02 21:55:33 +00001899reverse_sortslice(sortslice *s, Py_ssize_t n)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001900{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001901 reverse_slice(s->keys, &s->keys[n]);
1902 if (s->values != NULL)
1903 reverse_slice(s->values, &s->values[n]);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001904}
1905
Tim Petersa64dc242002-08-01 02:13:36 +00001906/* An adaptive, stable, natural mergesort. See listsort.txt.
1907 * Returns Py_None on success, NULL on error. Even in case of error, the
1908 * list will be some permutation of its input state (nothing is lost or
1909 * duplicated).
1910 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001911static PyObject *
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001912listsort(PyListObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f236de1996-12-10 23:55:39 +00001913{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001914 MergeState ms;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001915 Py_ssize_t nremaining;
1916 Py_ssize_t minrun;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001917 sortslice lo;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001918 Py_ssize_t saved_ob_size, saved_allocated;
1919 PyObject **saved_ob_item;
1920 PyObject **final_ob_item;
1921 PyObject *result = NULL; /* guilty until proved innocent */
1922 int reverse = 0;
1923 PyObject *keyfunc = NULL;
1924 Py_ssize_t i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001925 static char *kwlist[] = {"key", "reverse", 0};
Daniel Stutzbach98338222010-12-02 21:55:33 +00001926 PyObject **keys;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001928 assert(self != NULL);
1929 assert (PyList_Check(self));
1930 if (args != NULL) {
1931 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:sort",
1932 kwlist, &keyfunc, &reverse))
1933 return NULL;
1934 if (Py_SIZE(args) > 0) {
1935 PyErr_SetString(PyExc_TypeError,
1936 "must use keyword argument for key function");
1937 return NULL;
1938 }
1939 }
1940 if (keyfunc == Py_None)
1941 keyfunc = NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001943 /* The list is temporarily made empty, so that mutations performed
1944 * by comparison functions can't affect the slice of memory we're
1945 * sorting (allowing mutations during sorting is a core-dump
1946 * factory, since ob_item may change).
1947 */
1948 saved_ob_size = Py_SIZE(self);
1949 saved_ob_item = self->ob_item;
1950 saved_allocated = self->allocated;
1951 Py_SIZE(self) = 0;
1952 self->ob_item = NULL;
1953 self->allocated = -1; /* any operation will reset it to >= 0 */
Tim Peters330f9e92002-07-19 07:05:44 +00001954
Daniel Stutzbach98338222010-12-02 21:55:33 +00001955 if (keyfunc == NULL) {
1956 keys = NULL;
1957 lo.keys = saved_ob_item;
1958 lo.values = NULL;
1959 }
1960 else {
1961 if (saved_ob_size < MERGESTATE_TEMP_SIZE/2)
1962 /* Leverage stack space we allocated but won't otherwise use */
1963 keys = &ms.temparray[saved_ob_size+1];
1964 else {
1965 keys = PyMem_MALLOC(sizeof(PyObject *) * saved_ob_size);
Benjamin Peterson0823ffb2015-04-23 17:04:36 -04001966 if (keys == NULL) {
1967 PyErr_NoMemory();
1968 goto keyfunc_fail;
1969 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001970 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001971
1972 for (i = 0; i < saved_ob_size ; i++) {
1973 keys[i] = PyObject_CallFunctionObjArgs(keyfunc, saved_ob_item[i],
1974 NULL);
1975 if (keys[i] == NULL) {
1976 for (i=i-1 ; i>=0 ; i--)
1977 Py_DECREF(keys[i]);
Benjamin Peterson4a42cd42014-03-15 12:21:28 -05001978 if (saved_ob_size >= MERGESTATE_TEMP_SIZE/2)
Daniel Stutzbach8eda5f72011-03-02 23:37:50 +00001979 PyMem_FREE(keys);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001980 goto keyfunc_fail;
1981 }
1982 }
1983
1984 lo.keys = keys;
1985 lo.values = saved_ob_item;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001986 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001987
Daniel Stutzbach98338222010-12-02 21:55:33 +00001988 merge_init(&ms, saved_ob_size, keys != NULL);
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001989
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001990 nremaining = saved_ob_size;
1991 if (nremaining < 2)
1992 goto succeed;
Tim Peters330f9e92002-07-19 07:05:44 +00001993
Benjamin Peterson05380642010-08-23 19:35:39 +00001994 /* Reverse sort stability achieved by initially reversing the list,
1995 applying a stable forward sort, then reversing the final result. */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001996 if (reverse) {
1997 if (keys != NULL)
1998 reverse_slice(&keys[0], &keys[saved_ob_size]);
1999 reverse_slice(&saved_ob_item[0], &saved_ob_item[saved_ob_size]);
2000 }
Benjamin Peterson05380642010-08-23 19:35:39 +00002001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002002 /* March over the array once, left to right, finding natural runs,
2003 * and extending short natural runs to minrun elements.
2004 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002005 minrun = merge_compute_minrun(nremaining);
2006 do {
2007 int descending;
2008 Py_ssize_t n;
Tim Peters330f9e92002-07-19 07:05:44 +00002009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002010 /* Identify next run. */
Daniel Stutzbach98338222010-12-02 21:55:33 +00002011 n = count_run(lo.keys, lo.keys + nremaining, &descending);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002012 if (n < 0)
2013 goto fail;
2014 if (descending)
Daniel Stutzbach98338222010-12-02 21:55:33 +00002015 reverse_sortslice(&lo, n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002016 /* If short, extend to min(minrun, nremaining). */
2017 if (n < minrun) {
2018 const Py_ssize_t force = nremaining <= minrun ?
2019 nremaining : minrun;
Daniel Stutzbach98338222010-12-02 21:55:33 +00002020 if (binarysort(lo, lo.keys + force, lo.keys + n) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002021 goto fail;
2022 n = force;
2023 }
2024 /* Push run onto pending-runs stack, and maybe merge. */
2025 assert(ms.n < MAX_MERGE_PENDING);
2026 ms.pending[ms.n].base = lo;
2027 ms.pending[ms.n].len = n;
2028 ++ms.n;
2029 if (merge_collapse(&ms) < 0)
2030 goto fail;
2031 /* Advance to find next run. */
Daniel Stutzbach98338222010-12-02 21:55:33 +00002032 sortslice_advance(&lo, n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002033 nremaining -= n;
2034 } while (nremaining);
Tim Peters330f9e92002-07-19 07:05:44 +00002035
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002036 if (merge_force_collapse(&ms) < 0)
2037 goto fail;
2038 assert(ms.n == 1);
Daniel Stutzbach98338222010-12-02 21:55:33 +00002039 assert(keys == NULL
2040 ? ms.pending[0].base.keys == saved_ob_item
2041 : ms.pending[0].base.keys == &keys[0]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002042 assert(ms.pending[0].len == saved_ob_size);
Daniel Stutzbach98338222010-12-02 21:55:33 +00002043 lo = ms.pending[0].base;
Tim Petersa64dc242002-08-01 02:13:36 +00002044
2045succeed:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002046 result = Py_None;
Tim Peters330f9e92002-07-19 07:05:44 +00002047fail:
Daniel Stutzbach98338222010-12-02 21:55:33 +00002048 if (keys != NULL) {
2049 for (i = 0; i < saved_ob_size; i++)
2050 Py_DECREF(keys[i]);
Benjamin Petersonef87f8c2014-03-14 21:54:31 -05002051 if (saved_ob_size >= MERGESTATE_TEMP_SIZE/2)
Daniel Stutzbach98338222010-12-02 21:55:33 +00002052 PyMem_FREE(keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002053 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002055 if (self->allocated != -1 && result != NULL) {
2056 /* The user mucked with the list during the sort,
2057 * and we don't already have another error to report.
2058 */
2059 PyErr_SetString(PyExc_ValueError, "list modified during sort");
2060 result = NULL;
2061 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002063 if (reverse && saved_ob_size > 1)
2064 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002066 merge_freemem(&ms);
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002067
Daniel Stutzbach98338222010-12-02 21:55:33 +00002068keyfunc_fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002069 final_ob_item = self->ob_item;
2070 i = Py_SIZE(self);
2071 Py_SIZE(self) = saved_ob_size;
2072 self->ob_item = saved_ob_item;
2073 self->allocated = saved_allocated;
2074 if (final_ob_item != NULL) {
2075 /* we cannot use list_clear() for this because it does not
2076 guarantee that the list is really empty when it returns */
2077 while (--i >= 0) {
2078 Py_XDECREF(final_ob_item[i]);
2079 }
2080 PyMem_FREE(final_ob_item);
2081 }
2082 Py_XINCREF(result);
2083 return result;
Guido van Rossum3f236de1996-12-10 23:55:39 +00002084}
Tim Peters330f9e92002-07-19 07:05:44 +00002085#undef IFLT
Tim Peters66860f62002-08-04 17:47:26 +00002086#undef ISLT
Tim Peters330f9e92002-07-19 07:05:44 +00002087
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002088int
Fred Drakea2f55112000-07-09 15:16:51 +00002089PyList_Sort(PyObject *v)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002090{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002091 if (v == NULL || !PyList_Check(v)) {
2092 PyErr_BadInternalCall();
2093 return -1;
2094 }
2095 v = listsort((PyListObject *)v, (PyObject *)NULL, (PyObject *)NULL);
2096 if (v == NULL)
2097 return -1;
2098 Py_DECREF(v);
2099 return 0;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002100}
2101
Guido van Rossumb86c5492001-02-12 22:06:02 +00002102static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002103listreverse(PyListObject *self)
Guido van Rossumb86c5492001-02-12 22:06:02 +00002104{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002105 if (Py_SIZE(self) > 1)
2106 reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
2107 Py_RETURN_NONE;
Guido van Rossumed98d481991-03-06 13:07:53 +00002108}
2109
Guido van Rossum84c76f51990-10-30 13:32:20 +00002110int
Fred Drakea2f55112000-07-09 15:16:51 +00002111PyList_Reverse(PyObject *v)
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002112{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002113 PyListObject *self = (PyListObject *)v;
Tim Peters6063e262002-08-08 01:06:39 +00002114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002115 if (v == NULL || !PyList_Check(v)) {
2116 PyErr_BadInternalCall();
2117 return -1;
2118 }
2119 if (Py_SIZE(self) > 1)
2120 reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
2121 return 0;
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002122}
2123
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002124PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00002125PyList_AsTuple(PyObject *v)
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002126{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002127 PyObject *w;
2128 PyObject **p, **q;
2129 Py_ssize_t n;
2130 if (v == NULL || !PyList_Check(v)) {
2131 PyErr_BadInternalCall();
2132 return NULL;
2133 }
2134 n = Py_SIZE(v);
2135 w = PyTuple_New(n);
2136 if (w == NULL)
2137 return NULL;
2138 p = ((PyTupleObject *)w)->ob_item;
2139 q = ((PyListObject *)v)->ob_item;
2140 while (--n >= 0) {
2141 Py_INCREF(*q);
2142 *p = *q;
2143 p++;
2144 q++;
2145 }
2146 return w;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002147}
2148
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002149static PyObject *
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002150listindex(PyListObject *self, PyObject *args)
Guido van Rossumed98d481991-03-06 13:07:53 +00002151{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002152 Py_ssize_t i, start=0, stop=Py_SIZE(self);
Amaury Forgeot d'Arc864741b2011-11-06 15:10:48 +01002153 PyObject *v;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002154
Petri Lehtinenebfaabd2011-11-06 21:02:39 +02002155 if (!PyArg_ParseTuple(args, "O|O&O&:index", &v,
2156 _PyEval_SliceIndex, &start,
2157 _PyEval_SliceIndex, &stop))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002158 return NULL;
2159 if (start < 0) {
2160 start += Py_SIZE(self);
2161 if (start < 0)
2162 start = 0;
2163 }
2164 if (stop < 0) {
2165 stop += Py_SIZE(self);
2166 if (stop < 0)
2167 stop = 0;
2168 }
2169 for (i = start; i < stop && i < Py_SIZE(self); i++) {
2170 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2171 if (cmp > 0)
2172 return PyLong_FromSsize_t(i);
2173 else if (cmp < 0)
2174 return NULL;
2175 }
Amaury Forgeot d'Arc864741b2011-11-06 15:10:48 +01002176 PyErr_Format(PyExc_ValueError, "%R is not in list", v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002177 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002178}
2179
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002180static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002181listcount(PyListObject *self, PyObject *v)
Guido van Rossume6f7d181991-10-20 20:20:40 +00002182{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002183 Py_ssize_t count = 0;
2184 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002185
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002186 for (i = 0; i < Py_SIZE(self); i++) {
2187 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2188 if (cmp > 0)
2189 count++;
2190 else if (cmp < 0)
2191 return NULL;
2192 }
2193 return PyLong_FromSsize_t(count);
Guido van Rossume6f7d181991-10-20 20:20:40 +00002194}
2195
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002196static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002197listremove(PyListObject *self, PyObject *v)
Guido van Rossumed98d481991-03-06 13:07:53 +00002198{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002199 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002201 for (i = 0; i < Py_SIZE(self); i++) {
2202 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2203 if (cmp > 0) {
2204 if (list_ass_slice(self, i, i+1,
2205 (PyObject *)NULL) == 0)
2206 Py_RETURN_NONE;
2207 return NULL;
2208 }
2209 else if (cmp < 0)
2210 return NULL;
2211 }
2212 PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
2213 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002214}
2215
Jeremy Hylton8caad492000-06-23 14:18:11 +00002216static int
2217list_traverse(PyListObject *o, visitproc visit, void *arg)
2218{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002219 Py_ssize_t i;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002221 for (i = Py_SIZE(o); --i >= 0; )
2222 Py_VISIT(o->ob_item[i]);
2223 return 0;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002224}
2225
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002226static PyObject *
2227list_richcompare(PyObject *v, PyObject *w, int op)
2228{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002229 PyListObject *vl, *wl;
2230 Py_ssize_t i;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002231
Brian Curtindfc80e32011-08-10 20:28:54 -05002232 if (!PyList_Check(v) || !PyList_Check(w))
2233 Py_RETURN_NOTIMPLEMENTED;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002235 vl = (PyListObject *)v;
2236 wl = (PyListObject *)w;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002238 if (Py_SIZE(vl) != Py_SIZE(wl) && (op == Py_EQ || op == Py_NE)) {
2239 /* Shortcut: if the lengths differ, the lists differ */
2240 PyObject *res;
2241 if (op == Py_EQ)
2242 res = Py_False;
2243 else
2244 res = Py_True;
2245 Py_INCREF(res);
2246 return res;
2247 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002249 /* Search for the first index where items are different */
2250 for (i = 0; i < Py_SIZE(vl) && i < Py_SIZE(wl); i++) {
2251 int k = PyObject_RichCompareBool(vl->ob_item[i],
2252 wl->ob_item[i], Py_EQ);
2253 if (k < 0)
2254 return NULL;
2255 if (!k)
2256 break;
2257 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002259 if (i >= Py_SIZE(vl) || i >= Py_SIZE(wl)) {
2260 /* No more items to compare -- compare sizes */
2261 Py_ssize_t vs = Py_SIZE(vl);
2262 Py_ssize_t ws = Py_SIZE(wl);
2263 int cmp;
2264 PyObject *res;
2265 switch (op) {
2266 case Py_LT: cmp = vs < ws; break;
2267 case Py_LE: cmp = vs <= ws; break;
2268 case Py_EQ: cmp = vs == ws; break;
2269 case Py_NE: cmp = vs != ws; break;
2270 case Py_GT: cmp = vs > ws; break;
2271 case Py_GE: cmp = vs >= ws; break;
2272 default: return NULL; /* cannot happen */
2273 }
2274 if (cmp)
2275 res = Py_True;
2276 else
2277 res = Py_False;
2278 Py_INCREF(res);
2279 return res;
2280 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002282 /* We have an item that differs -- shortcuts for EQ/NE */
2283 if (op == Py_EQ) {
2284 Py_INCREF(Py_False);
2285 return Py_False;
2286 }
2287 if (op == Py_NE) {
2288 Py_INCREF(Py_True);
2289 return Py_True;
2290 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002292 /* Compare the final item again using the proper operator */
2293 return PyObject_RichCompare(vl->ob_item[i], wl->ob_item[i], op);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002294}
2295
Tim Peters6d6c1a32001-08-02 04:15:00 +00002296static int
2297list_init(PyListObject *self, PyObject *args, PyObject *kw)
2298{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002299 PyObject *arg = NULL;
2300 static char *kwlist[] = {"sequence", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002302 if (!PyArg_ParseTupleAndKeywords(args, kw, "|O:list", kwlist, &arg))
2303 return -1;
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002305 /* Verify list invariants established by PyType_GenericAlloc() */
2306 assert(0 <= Py_SIZE(self));
2307 assert(Py_SIZE(self) <= self->allocated || self->allocated == -1);
2308 assert(self->ob_item != NULL ||
2309 self->allocated == 0 || self->allocated == -1);
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002311 /* Empty previous contents */
2312 if (self->ob_item != NULL) {
2313 (void)list_clear(self);
2314 }
2315 if (arg != NULL) {
2316 PyObject *rv = listextend(self, arg);
2317 if (rv == NULL)
2318 return -1;
2319 Py_DECREF(rv);
2320 }
2321 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002322}
2323
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002324static PyObject *
2325list_sizeof(PyListObject *self)
2326{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002327 Py_ssize_t res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002328
Serhiy Storchaka5c4064e2015-12-19 20:05:25 +02002329 res = _PyObject_SIZE(Py_TYPE(self)) + self->allocated * sizeof(void*);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002330 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002331}
2332
Raymond Hettinger1021c442003-11-07 15:38:09 +00002333static PyObject *list_iter(PyObject *seq);
2334static PyObject *list_reversed(PyListObject* seq, PyObject* unused);
2335
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002336PyDoc_STRVAR(getitem_doc,
2337"x.__getitem__(y) <==> x[y]");
Raymond Hettinger1021c442003-11-07 15:38:09 +00002338PyDoc_STRVAR(reversed_doc,
2339"L.__reversed__() -- return a reverse iterator over the list");
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002340PyDoc_STRVAR(sizeof_doc,
2341"L.__sizeof__() -- size of L in memory, in bytes");
Eli Benderskycbbaa962011-02-25 05:47:53 +00002342PyDoc_STRVAR(clear_doc,
2343"L.clear() -> None -- remove all items from L");
2344PyDoc_STRVAR(copy_doc,
2345"L.copy() -> list -- a shallow copy of L");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002346PyDoc_STRVAR(append_doc,
Georg Brandl388349a2011-10-08 18:32:40 +02002347"L.append(object) -> None -- append object to end");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002348PyDoc_STRVAR(extend_doc,
Georg Brandl388349a2011-10-08 18:32:40 +02002349"L.extend(iterable) -> None -- extend list by appending elements from the iterable");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002350PyDoc_STRVAR(insert_doc,
2351"L.insert(index, object) -- insert object before index");
2352PyDoc_STRVAR(pop_doc,
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00002353"L.pop([index]) -> item -- remove and return item at index (default last).\n"
2354"Raises IndexError if list is empty or index is out of range.");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002355PyDoc_STRVAR(remove_doc,
Georg Brandl388349a2011-10-08 18:32:40 +02002356"L.remove(value) -> None -- remove first occurrence of value.\n"
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00002357"Raises ValueError if the value is not present.");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002358PyDoc_STRVAR(index_doc,
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00002359"L.index(value, [start, [stop]]) -> integer -- return first index of value.\n"
2360"Raises ValueError if the value is not present.");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002361PyDoc_STRVAR(count_doc,
2362"L.count(value) -> integer -- return number of occurrences of value");
2363PyDoc_STRVAR(reverse_doc,
2364"L.reverse() -- reverse *IN PLACE*");
2365PyDoc_STRVAR(sort_doc,
Georg Brandl388349a2011-10-08 18:32:40 +02002366"L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*");
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +00002367
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002368static PyObject *list_subscript(PyListObject*, PyObject*);
2369
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002370static PyMethodDef list_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002371 {"__getitem__", (PyCFunction)list_subscript, METH_O|METH_COEXIST, getitem_doc},
2372 {"__reversed__",(PyCFunction)list_reversed, METH_NOARGS, reversed_doc},
2373 {"__sizeof__", (PyCFunction)list_sizeof, METH_NOARGS, sizeof_doc},
Eli Benderskycbbaa962011-02-25 05:47:53 +00002374 {"clear", (PyCFunction)listclear, METH_NOARGS, clear_doc},
2375 {"copy", (PyCFunction)listcopy, METH_NOARGS, copy_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002376 {"append", (PyCFunction)listappend, METH_O, append_doc},
2377 {"insert", (PyCFunction)listinsert, METH_VARARGS, insert_doc},
Eli Benderskycbbaa962011-02-25 05:47:53 +00002378 {"extend", (PyCFunction)listextend, METH_O, extend_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002379 {"pop", (PyCFunction)listpop, METH_VARARGS, pop_doc},
2380 {"remove", (PyCFunction)listremove, METH_O, remove_doc},
2381 {"index", (PyCFunction)listindex, METH_VARARGS, index_doc},
2382 {"count", (PyCFunction)listcount, METH_O, count_doc},
2383 {"reverse", (PyCFunction)listreverse, METH_NOARGS, reverse_doc},
2384 {"sort", (PyCFunction)listsort, METH_VARARGS | METH_KEYWORDS, sort_doc},
2385 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002386};
2387
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002388static PySequenceMethods list_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002389 (lenfunc)list_length, /* sq_length */
2390 (binaryfunc)list_concat, /* sq_concat */
2391 (ssizeargfunc)list_repeat, /* sq_repeat */
2392 (ssizeargfunc)list_item, /* sq_item */
2393 0, /* sq_slice */
2394 (ssizeobjargproc)list_ass_item, /* sq_ass_item */
2395 0, /* sq_ass_slice */
2396 (objobjproc)list_contains, /* sq_contains */
2397 (binaryfunc)list_inplace_concat, /* sq_inplace_concat */
2398 (ssizeargfunc)list_inplace_repeat, /* sq_inplace_repeat */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002399};
2400
Neal Norwitz2c2e8272002-06-14 02:04:18 +00002401PyDoc_STRVAR(list_doc,
Ezio Melotti7f807b72010-03-01 04:08:34 +00002402"list() -> new empty list\n"
2403"list(iterable) -> new list initialized from iterable's items");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002404
Jeremy Hyltona4b4c3b2002-07-13 03:51:17 +00002405static PyObject *
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002406list_subscript(PyListObject* self, PyObject* item)
2407{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002408 if (PyIndex_Check(item)) {
2409 Py_ssize_t i;
2410 i = PyNumber_AsSsize_t(item, PyExc_IndexError);
2411 if (i == -1 && PyErr_Occurred())
2412 return NULL;
2413 if (i < 0)
2414 i += PyList_GET_SIZE(self);
2415 return list_item(self, i);
2416 }
2417 else if (PySlice_Check(item)) {
2418 Py_ssize_t start, stop, step, slicelength, cur, i;
2419 PyObject* result;
2420 PyObject* it;
2421 PyObject **src, **dest;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002422
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002423 if (PySlice_GetIndicesEx(item, Py_SIZE(self),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002424 &start, &stop, &step, &slicelength) < 0) {
2425 return NULL;
2426 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002427
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002428 if (slicelength <= 0) {
2429 return PyList_New(0);
2430 }
2431 else if (step == 1) {
2432 return list_slice(self, start, stop);
2433 }
2434 else {
2435 result = PyList_New(slicelength);
2436 if (!result) return NULL;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002437
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002438 src = self->ob_item;
2439 dest = ((PyListObject *)result)->ob_item;
2440 for (cur = start, i = 0; i < slicelength;
Mark Dickinsonc7d93b72011-09-25 15:34:32 +01002441 cur += (size_t)step, i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002442 it = src[cur];
2443 Py_INCREF(it);
2444 dest[i] = it;
2445 }
Tim Peters3b01a122002-07-19 02:35:45 +00002446
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002447 return result;
2448 }
2449 }
2450 else {
2451 PyErr_Format(PyExc_TypeError,
Terry Jan Reedyffff1442014-08-02 01:30:37 -04002452 "list indices must be integers or slices, not %.200s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002453 item->ob_type->tp_name);
2454 return NULL;
2455 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002456}
2457
Tim Peters3b01a122002-07-19 02:35:45 +00002458static int
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002459list_ass_subscript(PyListObject* self, PyObject* item, PyObject* value)
2460{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002461 if (PyIndex_Check(item)) {
2462 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
2463 if (i == -1 && PyErr_Occurred())
2464 return -1;
2465 if (i < 0)
2466 i += PyList_GET_SIZE(self);
2467 return list_ass_item(self, i, value);
2468 }
2469 else if (PySlice_Check(item)) {
2470 Py_ssize_t start, stop, step, slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002471
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002472 if (PySlice_GetIndicesEx(item, Py_SIZE(self),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002473 &start, &stop, &step, &slicelength) < 0) {
2474 return -1;
2475 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002476
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002477 if (step == 1)
2478 return list_ass_slice(self, start, stop, value);
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002479
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002480 /* Make sure s[5:2] = [..] inserts at the right place:
2481 before 5, not before 2. */
2482 if ((step < 0 && start < stop) ||
2483 (step > 0 && start > stop))
2484 stop = start;
Thomas Woutersed03b412007-08-28 21:37:11 +00002485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002486 if (value == NULL) {
2487 /* delete slice */
2488 PyObject **garbage;
2489 size_t cur;
2490 Py_ssize_t i;
Victor Stinner35f28032013-11-21 12:16:35 +01002491 int res;
Tim Peters3b01a122002-07-19 02:35:45 +00002492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002493 if (slicelength <= 0)
2494 return 0;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002496 if (step < 0) {
2497 stop = start + 1;
2498 start = stop + step*(slicelength - 1) - 1;
2499 step = -step;
2500 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002502 garbage = (PyObject**)
2503 PyMem_MALLOC(slicelength*sizeof(PyObject*));
2504 if (!garbage) {
2505 PyErr_NoMemory();
2506 return -1;
2507 }
Tim Peters3b01a122002-07-19 02:35:45 +00002508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002509 /* drawing pictures might help understand these for
2510 loops. Basically, we memmove the parts of the
2511 list that are *not* part of the slice: step-1
2512 items for each item that is part of the slice,
2513 and then tail end of the list that was not
2514 covered by the slice */
2515 for (cur = start, i = 0;
2516 cur < (size_t)stop;
2517 cur += step, i++) {
2518 Py_ssize_t lim = step - 1;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002520 garbage[i] = PyList_GET_ITEM(self, cur);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002522 if (cur + step >= (size_t)Py_SIZE(self)) {
2523 lim = Py_SIZE(self) - cur - 1;
2524 }
Michael W. Hudson56796f62002-07-29 14:35:04 +00002525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002526 memmove(self->ob_item + cur - i,
2527 self->ob_item + cur + 1,
2528 lim * sizeof(PyObject *));
2529 }
Mark Dickinsonc7d93b72011-09-25 15:34:32 +01002530 cur = start + (size_t)slicelength * step;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002531 if (cur < (size_t)Py_SIZE(self)) {
2532 memmove(self->ob_item + cur - slicelength,
2533 self->ob_item + cur,
2534 (Py_SIZE(self) - cur) *
2535 sizeof(PyObject *));
2536 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002538 Py_SIZE(self) -= slicelength;
Victor Stinner35f28032013-11-21 12:16:35 +01002539 res = list_resize(self, Py_SIZE(self));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002541 for (i = 0; i < slicelength; i++) {
2542 Py_DECREF(garbage[i]);
2543 }
2544 PyMem_FREE(garbage);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002545
Victor Stinner35f28032013-11-21 12:16:35 +01002546 return res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002547 }
2548 else {
2549 /* assign slice */
2550 PyObject *ins, *seq;
2551 PyObject **garbage, **seqitems, **selfitems;
2552 Py_ssize_t cur, i;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002553
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002554 /* protect against a[::-1] = a */
2555 if (self == (PyListObject*)value) {
2556 seq = list_slice((PyListObject*)value, 0,
2557 PyList_GET_SIZE(value));
2558 }
2559 else {
2560 seq = PySequence_Fast(value,
2561 "must assign iterable "
2562 "to extended slice");
2563 }
2564 if (!seq)
2565 return -1;
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002566
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002567 if (PySequence_Fast_GET_SIZE(seq) != slicelength) {
2568 PyErr_Format(PyExc_ValueError,
2569 "attempt to assign sequence of "
2570 "size %zd to extended slice of "
2571 "size %zd",
2572 PySequence_Fast_GET_SIZE(seq),
2573 slicelength);
2574 Py_DECREF(seq);
2575 return -1;
2576 }
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002578 if (!slicelength) {
2579 Py_DECREF(seq);
2580 return 0;
2581 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002583 garbage = (PyObject**)
2584 PyMem_MALLOC(slicelength*sizeof(PyObject*));
2585 if (!garbage) {
2586 Py_DECREF(seq);
2587 PyErr_NoMemory();
2588 return -1;
2589 }
Tim Peters3b01a122002-07-19 02:35:45 +00002590
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002591 selfitems = self->ob_item;
2592 seqitems = PySequence_Fast_ITEMS(seq);
2593 for (cur = start, i = 0; i < slicelength;
Mark Dickinsonc7d93b72011-09-25 15:34:32 +01002594 cur += (size_t)step, i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002595 garbage[i] = selfitems[cur];
2596 ins = seqitems[i];
2597 Py_INCREF(ins);
2598 selfitems[cur] = ins;
2599 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002601 for (i = 0; i < slicelength; i++) {
2602 Py_DECREF(garbage[i]);
2603 }
Tim Peters3b01a122002-07-19 02:35:45 +00002604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002605 PyMem_FREE(garbage);
2606 Py_DECREF(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002608 return 0;
2609 }
2610 }
2611 else {
2612 PyErr_Format(PyExc_TypeError,
Terry Jan Reedyffff1442014-08-02 01:30:37 -04002613 "list indices must be integers or slices, not %.200s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002614 item->ob_type->tp_name);
2615 return -1;
2616 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002617}
2618
2619static PyMappingMethods list_as_mapping = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002620 (lenfunc)list_length,
2621 (binaryfunc)list_subscript,
2622 (objobjargproc)list_ass_subscript
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002623};
2624
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002625PyTypeObject PyList_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002626 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2627 "list",
2628 sizeof(PyListObject),
2629 0,
2630 (destructor)list_dealloc, /* tp_dealloc */
2631 0, /* tp_print */
2632 0, /* tp_getattr */
2633 0, /* tp_setattr */
2634 0, /* tp_reserved */
2635 (reprfunc)list_repr, /* tp_repr */
2636 0, /* tp_as_number */
2637 &list_as_sequence, /* tp_as_sequence */
2638 &list_as_mapping, /* tp_as_mapping */
Georg Brandl00da4e02010-10-18 07:32:48 +00002639 PyObject_HashNotImplemented, /* tp_hash */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002640 0, /* tp_call */
2641 0, /* tp_str */
2642 PyObject_GenericGetAttr, /* tp_getattro */
2643 0, /* tp_setattro */
2644 0, /* tp_as_buffer */
2645 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2646 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LIST_SUBCLASS, /* tp_flags */
2647 list_doc, /* tp_doc */
2648 (traverseproc)list_traverse, /* tp_traverse */
2649 (inquiry)list_clear, /* tp_clear */
2650 list_richcompare, /* tp_richcompare */
2651 0, /* tp_weaklistoffset */
2652 list_iter, /* tp_iter */
2653 0, /* tp_iternext */
2654 list_methods, /* tp_methods */
2655 0, /* tp_members */
2656 0, /* tp_getset */
2657 0, /* tp_base */
2658 0, /* tp_dict */
2659 0, /* tp_descr_get */
2660 0, /* tp_descr_set */
2661 0, /* tp_dictoffset */
2662 (initproc)list_init, /* tp_init */
2663 PyType_GenericAlloc, /* tp_alloc */
2664 PyType_GenericNew, /* tp_new */
2665 PyObject_GC_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002666};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002667
2668
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002669/*********************** List Iterator **************************/
2670
2671typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002672 PyObject_HEAD
Victor Stinner7660b882013-06-24 23:59:24 +02002673 Py_ssize_t it_index;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002674 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002675} listiterobject;
2676
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002677static PyObject *list_iter(PyObject *);
2678static void listiter_dealloc(listiterobject *);
2679static int listiter_traverse(listiterobject *, visitproc, void *);
2680static PyObject *listiter_next(listiterobject *);
2681static PyObject *listiter_len(listiterobject *);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002682static PyObject *listiter_reduce_general(void *_it, int forward);
2683static PyObject *listiter_reduce(listiterobject *);
2684static PyObject *listiter_setstate(listiterobject *, PyObject *state);
Raymond Hettinger435bf582004-03-18 22:43:10 +00002685
Armin Rigof5b3e362006-02-11 21:32:43 +00002686PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002687PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
2688PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002689
2690static PyMethodDef listiter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002691 {"__length_hint__", (PyCFunction)listiter_len, METH_NOARGS, length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002692 {"__reduce__", (PyCFunction)listiter_reduce, METH_NOARGS, reduce_doc},
2693 {"__setstate__", (PyCFunction)listiter_setstate, METH_O, setstate_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002694 {NULL, NULL} /* sentinel */
Raymond Hettinger435bf582004-03-18 22:43:10 +00002695};
2696
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002697PyTypeObject PyListIter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002698 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2699 "list_iterator", /* tp_name */
2700 sizeof(listiterobject), /* tp_basicsize */
2701 0, /* tp_itemsize */
2702 /* methods */
2703 (destructor)listiter_dealloc, /* tp_dealloc */
2704 0, /* tp_print */
2705 0, /* tp_getattr */
2706 0, /* tp_setattr */
2707 0, /* tp_reserved */
2708 0, /* tp_repr */
2709 0, /* tp_as_number */
2710 0, /* tp_as_sequence */
2711 0, /* tp_as_mapping */
2712 0, /* tp_hash */
2713 0, /* tp_call */
2714 0, /* tp_str */
2715 PyObject_GenericGetAttr, /* tp_getattro */
2716 0, /* tp_setattro */
2717 0, /* tp_as_buffer */
2718 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2719 0, /* tp_doc */
2720 (traverseproc)listiter_traverse, /* tp_traverse */
2721 0, /* tp_clear */
2722 0, /* tp_richcompare */
2723 0, /* tp_weaklistoffset */
2724 PyObject_SelfIter, /* tp_iter */
2725 (iternextfunc)listiter_next, /* tp_iternext */
2726 listiter_methods, /* tp_methods */
2727 0, /* tp_members */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002728};
Raymond Hettinger1021c442003-11-07 15:38:09 +00002729
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002730
2731static PyObject *
2732list_iter(PyObject *seq)
2733{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002734 listiterobject *it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002736 if (!PyList_Check(seq)) {
2737 PyErr_BadInternalCall();
2738 return NULL;
2739 }
2740 it = PyObject_GC_New(listiterobject, &PyListIter_Type);
2741 if (it == NULL)
2742 return NULL;
2743 it->it_index = 0;
2744 Py_INCREF(seq);
2745 it->it_seq = (PyListObject *)seq;
2746 _PyObject_GC_TRACK(it);
2747 return (PyObject *)it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002748}
2749
2750static void
2751listiter_dealloc(listiterobject *it)
2752{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002753 _PyObject_GC_UNTRACK(it);
2754 Py_XDECREF(it->it_seq);
2755 PyObject_GC_Del(it);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002756}
2757
2758static int
2759listiter_traverse(listiterobject *it, visitproc visit, void *arg)
2760{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002761 Py_VISIT(it->it_seq);
2762 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002763}
2764
2765static PyObject *
2766listiter_next(listiterobject *it)
2767{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002768 PyListObject *seq;
2769 PyObject *item;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002771 assert(it != NULL);
2772 seq = it->it_seq;
2773 if (seq == NULL)
2774 return NULL;
2775 assert(PyList_Check(seq));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002777 if (it->it_index < PyList_GET_SIZE(seq)) {
2778 item = PyList_GET_ITEM(seq, it->it_index);
2779 ++it->it_index;
2780 Py_INCREF(item);
2781 return item;
2782 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002783
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002784 it->it_seq = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03002785 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002786 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002787}
2788
2789static PyObject *
2790listiter_len(listiterobject *it)
2791{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002792 Py_ssize_t len;
2793 if (it->it_seq) {
2794 len = PyList_GET_SIZE(it->it_seq) - it->it_index;
2795 if (len >= 0)
2796 return PyLong_FromSsize_t(len);
2797 }
2798 return PyLong_FromLong(0);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002799}
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002800
2801static PyObject *
2802listiter_reduce(listiterobject *it)
2803{
2804 return listiter_reduce_general(it, 1);
2805}
2806
2807static PyObject *
2808listiter_setstate(listiterobject *it, PyObject *state)
2809{
Victor Stinner7660b882013-06-24 23:59:24 +02002810 Py_ssize_t index = PyLong_AsSsize_t(state);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002811 if (index == -1 && PyErr_Occurred())
2812 return NULL;
2813 if (it->it_seq != NULL) {
2814 if (index < 0)
2815 index = 0;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +00002816 else if (index > PyList_GET_SIZE(it->it_seq))
2817 index = PyList_GET_SIZE(it->it_seq); /* iterator exhausted */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002818 it->it_index = index;
2819 }
2820 Py_RETURN_NONE;
2821}
2822
Raymond Hettinger1021c442003-11-07 15:38:09 +00002823/*********************** List Reverse Iterator **************************/
2824
2825typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002826 PyObject_HEAD
2827 Py_ssize_t it_index;
2828 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger1021c442003-11-07 15:38:09 +00002829} listreviterobject;
2830
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002831static PyObject *list_reversed(PyListObject *, PyObject *);
2832static void listreviter_dealloc(listreviterobject *);
2833static int listreviter_traverse(listreviterobject *, visitproc, void *);
2834static PyObject *listreviter_next(listreviterobject *);
Raymond Hettingerf5b64112008-12-02 21:33:45 +00002835static PyObject *listreviter_len(listreviterobject *);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002836static PyObject *listreviter_reduce(listreviterobject *);
2837static PyObject *listreviter_setstate(listreviterobject *, PyObject *);
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002838
Raymond Hettingerf5b64112008-12-02 21:33:45 +00002839static PyMethodDef listreviter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002840 {"__length_hint__", (PyCFunction)listreviter_len, METH_NOARGS, length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002841 {"__reduce__", (PyCFunction)listreviter_reduce, METH_NOARGS, reduce_doc},
2842 {"__setstate__", (PyCFunction)listreviter_setstate, METH_O, setstate_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002843 {NULL, NULL} /* sentinel */
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002844};
2845
Raymond Hettinger1021c442003-11-07 15:38:09 +00002846PyTypeObject PyListRevIter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002847 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2848 "list_reverseiterator", /* tp_name */
2849 sizeof(listreviterobject), /* tp_basicsize */
2850 0, /* tp_itemsize */
2851 /* methods */
2852 (destructor)listreviter_dealloc, /* tp_dealloc */
2853 0, /* tp_print */
2854 0, /* tp_getattr */
2855 0, /* tp_setattr */
2856 0, /* tp_reserved */
2857 0, /* tp_repr */
2858 0, /* tp_as_number */
2859 0, /* tp_as_sequence */
2860 0, /* tp_as_mapping */
2861 0, /* tp_hash */
2862 0, /* tp_call */
2863 0, /* tp_str */
2864 PyObject_GenericGetAttr, /* tp_getattro */
2865 0, /* tp_setattro */
2866 0, /* tp_as_buffer */
2867 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2868 0, /* tp_doc */
2869 (traverseproc)listreviter_traverse, /* tp_traverse */
2870 0, /* tp_clear */
2871 0, /* tp_richcompare */
2872 0, /* tp_weaklistoffset */
2873 PyObject_SelfIter, /* tp_iter */
2874 (iternextfunc)listreviter_next, /* tp_iternext */
2875 listreviter_methods, /* tp_methods */
2876 0,
Raymond Hettinger1021c442003-11-07 15:38:09 +00002877};
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002878
2879static PyObject *
2880list_reversed(PyListObject *seq, PyObject *unused)
2881{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002882 listreviterobject *it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002884 it = PyObject_GC_New(listreviterobject, &PyListRevIter_Type);
2885 if (it == NULL)
2886 return NULL;
2887 assert(PyList_Check(seq));
2888 it->it_index = PyList_GET_SIZE(seq) - 1;
2889 Py_INCREF(seq);
2890 it->it_seq = seq;
2891 PyObject_GC_Track(it);
2892 return (PyObject *)it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002893}
2894
2895static void
2896listreviter_dealloc(listreviterobject *it)
2897{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002898 PyObject_GC_UnTrack(it);
2899 Py_XDECREF(it->it_seq);
2900 PyObject_GC_Del(it);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002901}
2902
2903static int
2904listreviter_traverse(listreviterobject *it, visitproc visit, void *arg)
2905{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002906 Py_VISIT(it->it_seq);
2907 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002908}
2909
2910static PyObject *
2911listreviter_next(listreviterobject *it)
2912{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002913 PyObject *item;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03002914 Py_ssize_t index;
2915 PyListObject *seq;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002916
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03002917 assert(it != NULL);
2918 seq = it->it_seq;
2919 if (seq == NULL) {
2920 return NULL;
2921 }
2922 assert(PyList_Check(seq));
2923
2924 index = it->it_index;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002925 if (index>=0 && index < PyList_GET_SIZE(seq)) {
2926 item = PyList_GET_ITEM(seq, index);
2927 it->it_index--;
2928 Py_INCREF(item);
2929 return item;
2930 }
2931 it->it_index = -1;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03002932 it->it_seq = NULL;
2933 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002934 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002935}
2936
Raymond Hettingerf5b64112008-12-02 21:33:45 +00002937static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002938listreviter_len(listreviterobject *it)
2939{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002940 Py_ssize_t len = it->it_index + 1;
2941 if (it->it_seq == NULL || PyList_GET_SIZE(it->it_seq) < len)
2942 len = 0;
2943 return PyLong_FromSsize_t(len);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002944}
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002945
2946static PyObject *
2947listreviter_reduce(listreviterobject *it)
2948{
2949 return listiter_reduce_general(it, 0);
2950}
2951
2952static PyObject *
2953listreviter_setstate(listreviterobject *it, PyObject *state)
2954{
2955 Py_ssize_t index = PyLong_AsSsize_t(state);
2956 if (index == -1 && PyErr_Occurred())
2957 return NULL;
2958 if (it->it_seq != NULL) {
2959 if (index < -1)
2960 index = -1;
2961 else if (index > PyList_GET_SIZE(it->it_seq) - 1)
2962 index = PyList_GET_SIZE(it->it_seq) - 1;
2963 it->it_index = index;
2964 }
2965 Py_RETURN_NONE;
2966}
2967
2968/* common pickling support */
2969
2970static PyObject *
2971listiter_reduce_general(void *_it, int forward)
2972{
2973 PyObject *list;
2974
2975 /* the objects are not the same, index is of different types! */
2976 if (forward) {
2977 listiterobject *it = (listiterobject *)_it;
2978 if (it->it_seq)
Victor Stinner7660b882013-06-24 23:59:24 +02002979 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002980 it->it_seq, it->it_index);
2981 } else {
2982 listreviterobject *it = (listreviterobject *)_it;
2983 if (it->it_seq)
Antoine Pitroua7013882012-04-05 00:04:20 +02002984 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("reversed"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002985 it->it_seq, it->it_index);
2986 }
2987 /* empty iterator, create an empty list */
2988 list = PyList_New(0);
2989 if (list == NULL)
2990 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +02002991 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), list);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002992}