blob: b0e58bf2834f3791d1cc8dc2d27a3fd29b6d92d7 [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
Serhiy Storchakafdd42c42017-03-11 09:19:20 +020012/*[clinic input]
13class list "PyListObject *" "&PyList_Type"
14[clinic start generated code]*/
15/*[clinic end generated code: output=da39a3ee5e6b4b0d input=f9b222678f9f71e0]*/
16
17#include "clinic/listobject.c.h"
18
Tim Peters8d9eb102004-07-31 02:24:20 +000019/* Ensure ob_item has room for at least newsize elements, and set
20 * ob_size to newsize. If newsize > ob_size on entry, the content
21 * of the new slots at exit is undefined heap trash; it's the caller's
Ezio Melotti13925002011-03-16 11:05:33 +020022 * responsibility to overwrite them with sane values.
Tim Peters8d9eb102004-07-31 02:24:20 +000023 * The number of allocated elements may grow, shrink, or stay the same.
24 * Failure is impossible if newsize <= self.allocated on entry, although
25 * that partly relies on an assumption that the system realloc() never
26 * fails when passed a number of bytes <= the number of bytes last
27 * allocated (the C standard doesn't guarantee this, but it's hard to
28 * imagine a realloc implementation where it wouldn't be true).
29 * Note that self->ob_item may change, and even if newsize is less
30 * than ob_size on entry.
31 */
Guido van Rossuma46d51d1995-01-26 22:59:43 +000032static int
Martin v. Löwis18e16552006-02-15 17:27:45 +000033list_resize(PyListObject *self, Py_ssize_t newsize)
Guido van Rossuma46d51d1995-01-26 22:59:43 +000034{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000035 PyObject **items;
Xiang Zhang4cee0492017-02-22 12:32:30 +080036 size_t new_allocated, num_allocated_bytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000037 Py_ssize_t allocated = self->allocated;
Tim Peters65b8b842001-05-26 05:28:40 +000038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000039 /* Bypass realloc() when a previous overallocation is large enough
40 to accommodate the newsize. If the newsize falls lower than half
41 the allocated size, then proceed with the realloc() to shrink the list.
42 */
43 if (allocated >= newsize && newsize >= (allocated >> 1)) {
44 assert(self->ob_item != NULL || newsize == 0);
45 Py_SIZE(self) = newsize;
46 return 0;
47 }
Raymond Hettinger4bb95402004-02-13 11:36:39 +000048
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000049 /* This over-allocates proportional to the list size, making room
50 * for additional growth. The over-allocation is mild, but is
51 * enough to give linear-time amortized behavior over a long
52 * sequence of appends() in the presence of a poorly-performing
53 * system realloc().
54 * The growth pattern is: 0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ...
Xiang Zhang4cee0492017-02-22 12:32:30 +080055 * Note: new_allocated won't overflow because the largest possible value
56 * is PY_SSIZE_T_MAX * (9 / 8) + 6 which always fits in a size_t.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000057 */
Xiang Zhang4cee0492017-02-22 12:32:30 +080058 new_allocated = (size_t)newsize + (newsize >> 3) + (newsize < 9 ? 3 : 6);
59 if (new_allocated > (size_t)PY_SSIZE_T_MAX / sizeof(PyObject *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000060 PyErr_NoMemory();
61 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000062 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +000063
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000064 if (newsize == 0)
65 new_allocated = 0;
Xiang Zhang4cee0492017-02-22 12:32:30 +080066 num_allocated_bytes = new_allocated * sizeof(PyObject *);
67 items = (PyObject **)PyMem_Realloc(self->ob_item, num_allocated_bytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000068 if (items == NULL) {
69 PyErr_NoMemory();
70 return -1;
71 }
72 self->ob_item = items;
73 Py_SIZE(self) = newsize;
74 self->allocated = new_allocated;
75 return 0;
Raymond Hettinger4bb95402004-02-13 11:36:39 +000076}
Guido van Rossuma46d51d1995-01-26 22:59:43 +000077
Christian Heimes77c02eb2008-02-09 02:18:51 +000078/* Debug statistic to compare allocations with reuse through the free list */
79#undef SHOW_ALLOC_COUNT
80#ifdef SHOW_ALLOC_COUNT
81static size_t count_alloc = 0;
82static size_t count_reuse = 0;
83
84static void
85show_alloc(void)
86{
Serhiy Storchaka7e160ce2016-07-03 21:03:53 +030087 PyObject *xoptions, *value;
88 _Py_IDENTIFIER(showalloccount);
89
90 xoptions = PySys_GetXOptions();
91 if (xoptions == NULL)
92 return;
93 value = _PyDict_GetItemId(xoptions, &PyId_showalloccount);
94 if (value != Py_True)
95 return;
96
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000097 fprintf(stderr, "List allocations: %" PY_FORMAT_SIZE_T "d\n",
98 count_alloc);
99 fprintf(stderr, "List reuse through freelist: %" PY_FORMAT_SIZE_T
100 "d\n", count_reuse);
101 fprintf(stderr, "%.2f%% reuse rate\n\n",
102 (100.0*count_reuse/(count_alloc+count_reuse)));
Christian Heimes77c02eb2008-02-09 02:18:51 +0000103}
104#endif
105
Raymond Hettinger0468e412004-05-05 05:37:53 +0000106/* Empty list reuse scheme to save calls to malloc and free */
Christian Heimes2202f872008-02-06 14:31:34 +0000107#ifndef PyList_MAXFREELIST
108#define PyList_MAXFREELIST 80
109#endif
110static PyListObject *free_list[PyList_MAXFREELIST];
111static int numfree = 0;
Raymond Hettinger0468e412004-05-05 05:37:53 +0000112
Antoine Pitrou9a812cb2011-11-15 00:00:12 +0100113int
114PyList_ClearFreeList(void)
Raymond Hettingerfb09f0e2004-10-07 03:58:07 +0000115{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000116 PyListObject *op;
Antoine Pitrou9a812cb2011-11-15 00:00:12 +0100117 int ret = numfree;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000118 while (numfree) {
119 op = free_list[--numfree];
120 assert(PyList_CheckExact(op));
121 PyObject_GC_Del(op);
122 }
Antoine Pitrou9a812cb2011-11-15 00:00:12 +0100123 return ret;
124}
125
126void
127PyList_Fini(void)
128{
129 PyList_ClearFreeList();
Raymond Hettingerfb09f0e2004-10-07 03:58:07 +0000130}
131
David Malcolm49526f42012-06-22 14:55:41 -0400132/* Print summary info about the state of the optimized allocator */
133void
134_PyList_DebugMallocStats(FILE *out)
135{
136 _PyDebugAllocatorStats(out,
137 "free PyListObject",
138 numfree, sizeof(PyListObject));
139}
140
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000141PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000142PyList_New(Py_ssize_t size)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000143{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000144 PyListObject *op;
Christian Heimes77c02eb2008-02-09 02:18:51 +0000145#ifdef SHOW_ALLOC_COUNT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000146 static int initialized = 0;
147 if (!initialized) {
148 Py_AtExit(show_alloc);
149 initialized = 1;
150 }
Christian Heimes77c02eb2008-02-09 02:18:51 +0000151#endif
Tim Peters3986d4e2004-07-29 02:28:42 +0000152
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000153 if (size < 0) {
154 PyErr_BadInternalCall();
155 return NULL;
156 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000157 if (numfree) {
158 numfree--;
159 op = free_list[numfree];
160 _Py_NewReference((PyObject *)op);
Christian Heimes77c02eb2008-02-09 02:18:51 +0000161#ifdef SHOW_ALLOC_COUNT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000162 count_reuse++;
Christian Heimes77c02eb2008-02-09 02:18:51 +0000163#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000164 } else {
165 op = PyObject_GC_New(PyListObject, &PyList_Type);
166 if (op == NULL)
167 return NULL;
Christian Heimes77c02eb2008-02-09 02:18:51 +0000168#ifdef SHOW_ALLOC_COUNT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000169 count_alloc++;
Christian Heimes77c02eb2008-02-09 02:18:51 +0000170#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000171 }
172 if (size <= 0)
173 op->ob_item = NULL;
174 else {
Mark Dickinson5d132382016-08-21 08:55:15 +0100175 op->ob_item = (PyObject **) PyMem_Calloc(size, sizeof(PyObject *));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000176 if (op->ob_item == NULL) {
177 Py_DECREF(op);
178 return PyErr_NoMemory();
179 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000180 }
181 Py_SIZE(op) = size;
182 op->allocated = size;
183 _PyObject_GC_TRACK(op);
184 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000185}
186
Martin v. Löwis18e16552006-02-15 17:27:45 +0000187Py_ssize_t
Fred Drakea2f55112000-07-09 15:16:51 +0000188PyList_Size(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000189{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000190 if (!PyList_Check(op)) {
191 PyErr_BadInternalCall();
192 return -1;
193 }
194 else
195 return Py_SIZE(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000196}
197
Raymond Hettingerfdfe6182004-05-05 06:28:16 +0000198static PyObject *indexerr = NULL;
Guido van Rossum929f1b81996-08-09 20:51:27 +0000199
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000200PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000201PyList_GetItem(PyObject *op, Py_ssize_t i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000202{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000203 if (!PyList_Check(op)) {
204 PyErr_BadInternalCall();
205 return NULL;
206 }
207 if (i < 0 || i >= Py_SIZE(op)) {
208 if (indexerr == NULL) {
209 indexerr = PyUnicode_FromString(
210 "list index out of range");
211 if (indexerr == NULL)
212 return NULL;
213 }
214 PyErr_SetObject(PyExc_IndexError, indexerr);
215 return NULL;
216 }
217 return ((PyListObject *)op) -> ob_item[i];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000218}
219
220int
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200221PyList_SetItem(PyObject *op, Py_ssize_t i,
222 PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000223{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200224 PyObject **p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000225 if (!PyList_Check(op)) {
226 Py_XDECREF(newitem);
227 PyErr_BadInternalCall();
228 return -1;
229 }
230 if (i < 0 || i >= Py_SIZE(op)) {
231 Py_XDECREF(newitem);
232 PyErr_SetString(PyExc_IndexError,
233 "list assignment index out of range");
234 return -1;
235 }
236 p = ((PyListObject *)op) -> ob_item + i;
Serhiy Storchakaec397562016-04-06 09:50:03 +0300237 Py_XSETREF(*p, newitem);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000238 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000239}
240
241static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000242ins1(PyListObject *self, Py_ssize_t where, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000243{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000244 Py_ssize_t i, n = Py_SIZE(self);
245 PyObject **items;
246 if (v == NULL) {
247 PyErr_BadInternalCall();
248 return -1;
249 }
250 if (n == PY_SSIZE_T_MAX) {
251 PyErr_SetString(PyExc_OverflowError,
252 "cannot add more objects to list");
253 return -1;
254 }
Tim Petersb38e2b62004-07-29 02:29:26 +0000255
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800256 if (list_resize(self, n+1) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000257 return -1;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000259 if (where < 0) {
260 where += n;
261 if (where < 0)
262 where = 0;
263 }
264 if (where > n)
265 where = n;
266 items = self->ob_item;
267 for (i = n; --i >= where; )
268 items[i+1] = items[i];
269 Py_INCREF(v);
270 items[where] = v;
271 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000272}
273
274int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000275PyList_Insert(PyObject *op, Py_ssize_t where, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000276{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000277 if (!PyList_Check(op)) {
278 PyErr_BadInternalCall();
279 return -1;
280 }
281 return ins1((PyListObject *)op, where, newitem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000282}
283
Raymond Hettinger40a03822004-04-12 13:05:09 +0000284static int
285app1(PyListObject *self, PyObject *v)
286{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000287 Py_ssize_t n = PyList_GET_SIZE(self);
Raymond Hettinger40a03822004-04-12 13:05:09 +0000288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000289 assert (v != NULL);
290 if (n == PY_SSIZE_T_MAX) {
291 PyErr_SetString(PyExc_OverflowError,
292 "cannot add more objects to list");
293 return -1;
294 }
Raymond Hettinger40a03822004-04-12 13:05:09 +0000295
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800296 if (list_resize(self, n+1) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000297 return -1;
Raymond Hettinger40a03822004-04-12 13:05:09 +0000298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000299 Py_INCREF(v);
300 PyList_SET_ITEM(self, n, v);
301 return 0;
Raymond Hettinger40a03822004-04-12 13:05:09 +0000302}
303
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000304int
Fred Drakea2f55112000-07-09 15:16:51 +0000305PyList_Append(PyObject *op, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000306{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000307 if (PyList_Check(op) && (newitem != NULL))
308 return app1((PyListObject *)op, newitem);
309 PyErr_BadInternalCall();
310 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000311}
312
313/* Methods */
314
315static void
Fred Drakea2f55112000-07-09 15:16:51 +0000316list_dealloc(PyListObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000317{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000318 Py_ssize_t i;
319 PyObject_GC_UnTrack(op);
320 Py_TRASHCAN_SAFE_BEGIN(op)
321 if (op->ob_item != NULL) {
322 /* Do it backwards, for Christian Tismer.
323 There's a simple test case where somehow this reduces
324 thrashing when a *very* large list is created and
325 immediately deleted. */
326 i = Py_SIZE(op);
327 while (--i >= 0) {
328 Py_XDECREF(op->ob_item[i]);
329 }
330 PyMem_FREE(op->ob_item);
331 }
332 if (numfree < PyList_MAXFREELIST && PyList_CheckExact(op))
333 free_list[numfree++] = op;
334 else
335 Py_TYPE(op)->tp_free((PyObject *)op);
336 Py_TRASHCAN_SAFE_END(op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000337}
338
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000339static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000340list_repr(PyListObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000341{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000342 Py_ssize_t i;
Victor Stinner5c733472013-11-18 21:11:57 +0100343 PyObject *s;
Victor Stinner5c733472013-11-18 21:11:57 +0100344 _PyUnicodeWriter writer;
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200345
346 if (Py_SIZE(v) == 0) {
347 return PyUnicode_FromString("[]");
348 }
349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000350 i = Py_ReprEnter((PyObject*)v);
351 if (i != 0) {
352 return i > 0 ? PyUnicode_FromString("[...]") : NULL;
353 }
Tim Petersa7259592001-06-16 05:11:17 +0000354
Victor Stinner5c733472013-11-18 21:11:57 +0100355 _PyUnicodeWriter_Init(&writer);
356 writer.overallocate = 1;
Victor Stinnerb8fb1972013-11-18 22:15:44 +0100357 /* "[" + "1" + ", 2" * (len - 1) + "]" */
358 writer.min_length = 1 + 1 + (2 + 1) * (Py_SIZE(v) - 1) + 1;
Tim Petersa7259592001-06-16 05:11:17 +0000359
Victor Stinner5c733472013-11-18 21:11:57 +0100360 if (_PyUnicodeWriter_WriteChar(&writer, '[') < 0)
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200361 goto error;
Tim Petersa7259592001-06-16 05:11:17 +0000362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000363 /* Do repr() on each element. Note that this may mutate the list,
364 so must refetch the list size on each iteration. */
365 for (i = 0; i < Py_SIZE(v); ++i) {
Victor Stinner5c733472013-11-18 21:11:57 +0100366 if (i > 0) {
Victor Stinner4a587072013-11-19 12:54:53 +0100367 if (_PyUnicodeWriter_WriteASCIIString(&writer, ", ", 2) < 0)
Victor Stinner5c733472013-11-18 21:11:57 +0100368 goto error;
369 }
370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000371 if (Py_EnterRecursiveCall(" while getting the repr of a list"))
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200372 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000373 s = PyObject_Repr(v->ob_item[i]);
374 Py_LeaveRecursiveCall();
Victor Stinner5c733472013-11-18 21:11:57 +0100375 if (s == NULL)
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200376 goto error;
Victor Stinner5c733472013-11-18 21:11:57 +0100377
378 if (_PyUnicodeWriter_WriteStr(&writer, s) < 0) {
379 Py_DECREF(s);
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200380 goto error;
Victor Stinner5c733472013-11-18 21:11:57 +0100381 }
382 Py_DECREF(s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000383 }
Victor Stinner5c733472013-11-18 21:11:57 +0100384
Victor Stinner4d3f1092013-11-19 12:09:00 +0100385 writer.overallocate = 0;
Victor Stinner5c733472013-11-18 21:11:57 +0100386 if (_PyUnicodeWriter_WriteChar(&writer, ']') < 0)
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200387 goto error;
Tim Petersa7259592001-06-16 05:11:17 +0000388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000389 Py_ReprLeave((PyObject *)v);
Victor Stinner5c733472013-11-18 21:11:57 +0100390 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200391
392error:
Victor Stinner5c733472013-11-18 21:11:57 +0100393 _PyUnicodeWriter_Dealloc(&writer);
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200394 Py_ReprLeave((PyObject *)v);
395 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000396}
397
Martin v. Löwis18e16552006-02-15 17:27:45 +0000398static Py_ssize_t
Fred Drakea2f55112000-07-09 15:16:51 +0000399list_length(PyListObject *a)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000400{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000401 return Py_SIZE(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000402}
403
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000404static int
Fred Drakea2f55112000-07-09 15:16:51 +0000405list_contains(PyListObject *a, PyObject *el)
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000406{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000407 Py_ssize_t i;
408 int cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000410 for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(a); ++i)
411 cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i),
412 Py_EQ);
413 return cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000414}
415
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000416static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000417list_item(PyListObject *a, Py_ssize_t i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000418{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000419 if (i < 0 || i >= Py_SIZE(a)) {
420 if (indexerr == NULL) {
421 indexerr = PyUnicode_FromString(
422 "list index out of range");
423 if (indexerr == NULL)
424 return NULL;
425 }
426 PyErr_SetObject(PyExc_IndexError, indexerr);
427 return NULL;
428 }
429 Py_INCREF(a->ob_item[i]);
430 return a->ob_item[i];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000431}
432
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000433static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000434list_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000435{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000436 PyListObject *np;
437 PyObject **src, **dest;
438 Py_ssize_t i, len;
439 if (ilow < 0)
440 ilow = 0;
441 else if (ilow > Py_SIZE(a))
442 ilow = Py_SIZE(a);
443 if (ihigh < ilow)
444 ihigh = ilow;
445 else if (ihigh > Py_SIZE(a))
446 ihigh = Py_SIZE(a);
447 len = ihigh - ilow;
448 np = (PyListObject *) PyList_New(len);
449 if (np == NULL)
450 return NULL;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000451
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000452 src = a->ob_item + ilow;
453 dest = np->ob_item;
454 for (i = 0; i < len; i++) {
455 PyObject *v = src[i];
456 Py_INCREF(v);
457 dest[i] = v;
458 }
459 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000460}
461
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000462PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000463PyList_GetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum234f9421993-06-17 12:35:49 +0000464{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000465 if (!PyList_Check(a)) {
466 PyErr_BadInternalCall();
467 return NULL;
468 }
469 return list_slice((PyListObject *)a, ilow, ihigh);
Guido van Rossum234f9421993-06-17 12:35:49 +0000470}
471
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000472static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000473list_concat(PyListObject *a, PyObject *bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000474{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000475 Py_ssize_t size;
476 Py_ssize_t i;
477 PyObject **src, **dest;
478 PyListObject *np;
479 if (!PyList_Check(bb)) {
480 PyErr_Format(PyExc_TypeError,
481 "can only concatenate list (not \"%.200s\") to list",
482 bb->ob_type->tp_name);
483 return NULL;
484 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000485#define b ((PyListObject *)bb)
Martin Panterb93d8632016-07-25 02:39:20 +0000486 if (Py_SIZE(a) > PY_SSIZE_T_MAX - Py_SIZE(b))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000487 return PyErr_NoMemory();
Martin Panterb93d8632016-07-25 02:39:20 +0000488 size = Py_SIZE(a) + Py_SIZE(b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 np = (PyListObject *) PyList_New(size);
490 if (np == NULL) {
491 return NULL;
492 }
493 src = a->ob_item;
494 dest = np->ob_item;
495 for (i = 0; i < Py_SIZE(a); i++) {
496 PyObject *v = src[i];
497 Py_INCREF(v);
498 dest[i] = v;
499 }
500 src = b->ob_item;
501 dest = np->ob_item + Py_SIZE(a);
502 for (i = 0; i < Py_SIZE(b); i++) {
503 PyObject *v = src[i];
504 Py_INCREF(v);
505 dest[i] = v;
506 }
507 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000508#undef b
509}
510
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000511static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000512list_repeat(PyListObject *a, Py_ssize_t n)
Guido van Rossumed98d481991-03-06 13:07:53 +0000513{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000514 Py_ssize_t i, j;
515 Py_ssize_t size;
516 PyListObject *np;
517 PyObject **p, **items;
518 PyObject *elem;
519 if (n < 0)
520 n = 0;
Mark Dickinsonc0420fd2011-09-19 19:18:37 +0100521 if (n > 0 && Py_SIZE(a) > PY_SSIZE_T_MAX / n)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000522 return PyErr_NoMemory();
Mark Dickinsonc0420fd2011-09-19 19:18:37 +0100523 size = Py_SIZE(a) * n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000524 if (size == 0)
525 return PyList_New(0);
526 np = (PyListObject *) PyList_New(size);
527 if (np == NULL)
528 return NULL;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 items = np->ob_item;
531 if (Py_SIZE(a) == 1) {
532 elem = a->ob_item[0];
533 for (i = 0; i < n; i++) {
534 items[i] = elem;
535 Py_INCREF(elem);
536 }
537 return (PyObject *) np;
538 }
539 p = np->ob_item;
540 items = a->ob_item;
541 for (i = 0; i < n; i++) {
542 for (j = 0; j < Py_SIZE(a); j++) {
543 *p = items[j];
544 Py_INCREF(*p);
545 p++;
546 }
547 }
548 return (PyObject *) np;
Guido van Rossumed98d481991-03-06 13:07:53 +0000549}
550
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000551static int
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200552_list_clear(PyListObject *a)
Armin Rigo93677f02004-07-29 12:40:23 +0000553{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000554 Py_ssize_t i;
555 PyObject **item = a->ob_item;
556 if (item != NULL) {
557 /* Because XDECREF can recursively invoke operations on
558 this list, we make it empty first. */
559 i = Py_SIZE(a);
560 Py_SIZE(a) = 0;
561 a->ob_item = NULL;
562 a->allocated = 0;
563 while (--i >= 0) {
564 Py_XDECREF(item[i]);
565 }
566 PyMem_FREE(item);
567 }
568 /* Never fails; the return value can be ignored.
569 Note that there is no guarantee that the list is actually empty
570 at this point, because XDECREF may have populated it again! */
571 return 0;
Armin Rigo93677f02004-07-29 12:40:23 +0000572}
573
Tim Peters8fc4a912004-07-31 21:53:19 +0000574/* a[ilow:ihigh] = v if v != NULL.
575 * del a[ilow:ihigh] if v == NULL.
576 *
577 * Special speed gimmick: when v is NULL and ihigh - ilow <= 8, it's
578 * guaranteed the call cannot fail.
579 */
Armin Rigo93677f02004-07-29 12:40:23 +0000580static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000581list_ass_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000582{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000583 /* Because [X]DECREF can recursively invoke list operations on
584 this list, we must postpone all [X]DECREF activity until
585 after the list is back in its canonical shape. Therefore
586 we must allocate an additional array, 'recycle', into which
587 we temporarily copy the items that are deleted from the
588 list. :-( */
589 PyObject *recycle_on_stack[8];
590 PyObject **recycle = recycle_on_stack; /* will allocate more if needed */
591 PyObject **item;
592 PyObject **vitem = NULL;
593 PyObject *v_as_SF = NULL; /* PySequence_Fast(v) */
594 Py_ssize_t n; /* # of elements in replacement list */
595 Py_ssize_t norig; /* # of elements in list getting replaced */
596 Py_ssize_t d; /* Change in size */
597 Py_ssize_t k;
598 size_t s;
599 int result = -1; /* guilty until proved innocent */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000600#define b ((PyListObject *)v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000601 if (v == NULL)
602 n = 0;
603 else {
604 if (a == b) {
605 /* Special case "a[i:j] = a" -- copy b first */
606 v = list_slice(b, 0, Py_SIZE(b));
607 if (v == NULL)
608 return result;
609 result = list_ass_slice(a, ilow, ihigh, v);
610 Py_DECREF(v);
611 return result;
612 }
613 v_as_SF = PySequence_Fast(v, "can only assign an iterable");
614 if(v_as_SF == NULL)
615 goto Error;
616 n = PySequence_Fast_GET_SIZE(v_as_SF);
617 vitem = PySequence_Fast_ITEMS(v_as_SF);
618 }
619 if (ilow < 0)
620 ilow = 0;
621 else if (ilow > Py_SIZE(a))
622 ilow = Py_SIZE(a);
Tim Peters8d9eb102004-07-31 02:24:20 +0000623
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000624 if (ihigh < ilow)
625 ihigh = ilow;
626 else if (ihigh > Py_SIZE(a))
627 ihigh = Py_SIZE(a);
Armin Rigo93677f02004-07-29 12:40:23 +0000628
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000629 norig = ihigh - ilow;
630 assert(norig >= 0);
631 d = n - norig;
632 if (Py_SIZE(a) + d == 0) {
633 Py_XDECREF(v_as_SF);
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200634 return _list_clear(a);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000635 }
636 item = a->ob_item;
637 /* recycle the items that we are about to remove */
638 s = norig * sizeof(PyObject *);
Benjamin Peterson5a7d9232016-09-06 17:58:25 -0700639 /* If norig == 0, item might be NULL, in which case we may not memcpy from it. */
640 if (s) {
641 if (s > sizeof(recycle_on_stack)) {
642 recycle = (PyObject **)PyMem_MALLOC(s);
643 if (recycle == NULL) {
644 PyErr_NoMemory();
645 goto Error;
646 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 }
Benjamin Peterson5a7d9232016-09-06 17:58:25 -0700648 memcpy(recycle, &item[ilow], s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000649 }
Tim Peters8d9eb102004-07-31 02:24:20 +0000650
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000651 if (d < 0) { /* Delete -d items */
Victor Stinner2c40f642013-07-19 23:06:21 +0200652 Py_ssize_t tail;
653 tail = (Py_SIZE(a) - ihigh) * sizeof(PyObject *);
654 memmove(&item[ihigh+d], &item[ihigh], tail);
655 if (list_resize(a, Py_SIZE(a) + d) < 0) {
656 memmove(&item[ihigh], &item[ihigh+d], tail);
657 memcpy(&item[ilow], recycle, s);
658 goto Error;
659 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000660 item = a->ob_item;
661 }
662 else if (d > 0) { /* Insert d items */
663 k = Py_SIZE(a);
664 if (list_resize(a, k+d) < 0)
665 goto Error;
666 item = a->ob_item;
667 memmove(&item[ihigh+d], &item[ihigh],
668 (k - ihigh)*sizeof(PyObject *));
669 }
670 for (k = 0; k < n; k++, ilow++) {
671 PyObject *w = vitem[k];
672 Py_XINCREF(w);
673 item[ilow] = w;
674 }
675 for (k = norig - 1; k >= 0; --k)
676 Py_XDECREF(recycle[k]);
677 result = 0;
Tim Peters8d9eb102004-07-31 02:24:20 +0000678 Error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000679 if (recycle != recycle_on_stack)
680 PyMem_FREE(recycle);
681 Py_XDECREF(v_as_SF);
682 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000683#undef b
684}
685
Guido van Rossum234f9421993-06-17 12:35:49 +0000686int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000687PyList_SetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum234f9421993-06-17 12:35:49 +0000688{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000689 if (!PyList_Check(a)) {
690 PyErr_BadInternalCall();
691 return -1;
692 }
693 return list_ass_slice((PyListObject *)a, ilow, ihigh, v);
Guido van Rossum234f9421993-06-17 12:35:49 +0000694}
695
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000696static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000697list_inplace_repeat(PyListObject *self, Py_ssize_t n)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000698{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000699 PyObject **items;
700 Py_ssize_t size, i, j, p;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000701
702
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000703 size = PyList_GET_SIZE(self);
704 if (size == 0 || n == 1) {
705 Py_INCREF(self);
706 return (PyObject *)self;
707 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000709 if (n < 1) {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200710 (void)_list_clear(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000711 Py_INCREF(self);
712 return (PyObject *)self;
713 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 if (size > PY_SSIZE_T_MAX / n) {
716 return PyErr_NoMemory();
717 }
Christian Heimesaf98da12008-01-27 15:18:18 +0000718
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800719 if (list_resize(self, size*n) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000720 return NULL;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000721
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000722 p = size;
723 items = self->ob_item;
724 for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */
725 for (j = 0; j < size; j++) {
726 PyObject *o = items[j];
727 Py_INCREF(o);
728 items[p++] = o;
729 }
730 }
731 Py_INCREF(self);
732 return (PyObject *)self;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000733}
734
Guido van Rossum4a450d01991-04-03 19:05:18 +0000735static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000736list_ass_item(PyListObject *a, Py_ssize_t i, PyObject *v)
Guido van Rossum4a450d01991-04-03 19:05:18 +0000737{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000738 if (i < 0 || i >= Py_SIZE(a)) {
739 PyErr_SetString(PyExc_IndexError,
740 "list assignment index out of range");
741 return -1;
742 }
743 if (v == NULL)
744 return list_ass_slice(a, i, i+1, v);
745 Py_INCREF(v);
Serhiy Storchakaf01e4082016-04-10 18:12:01 +0300746 Py_SETREF(a->ob_item[i], v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000747 return 0;
Guido van Rossum4a450d01991-04-03 19:05:18 +0000748}
749
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200750/*[clinic input]
751list.insert
752
753 index: Py_ssize_t
754 object: object
755 /
756
757Insert object before index.
758[clinic start generated code]*/
759
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000760static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200761list_insert_impl(PyListObject *self, Py_ssize_t index, PyObject *object)
762/*[clinic end generated code: output=7f35e32f60c8cb78 input=858514cf894c7eab]*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000763{
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200764 if (ins1(self, index, object) == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000765 Py_RETURN_NONE;
766 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000767}
768
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200769/*[clinic input]
770list.clear
771
772Remove all items from list.
773[clinic start generated code]*/
774
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000775static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200776list_clear_impl(PyListObject *self)
777/*[clinic end generated code: output=67a1896c01f74362 input=ca3c1646856742f6]*/
Eli Benderskycbbaa962011-02-25 05:47:53 +0000778{
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200779 _list_clear(self);
Eli Benderskycbbaa962011-02-25 05:47:53 +0000780 Py_RETURN_NONE;
781}
782
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200783/*[clinic input]
784list.copy
785
786Return a shallow copy of the list.
787[clinic start generated code]*/
788
Eli Benderskycbbaa962011-02-25 05:47:53 +0000789static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200790list_copy_impl(PyListObject *self)
791/*[clinic end generated code: output=ec6b72d6209d418e input=6453ab159e84771f]*/
Eli Benderskycbbaa962011-02-25 05:47:53 +0000792{
793 return list_slice(self, 0, Py_SIZE(self));
794}
795
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200796/*[clinic input]
797list.append
798
799 object: object
800 /
801
802Append object to the end of the list.
803[clinic start generated code]*/
804
Eli Benderskycbbaa962011-02-25 05:47:53 +0000805static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200806list_append(PyListObject *self, PyObject *object)
807/*[clinic end generated code: output=7c096003a29c0eae input=43a3fe48a7066e91]*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000808{
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200809 if (app1(self, object) == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000810 Py_RETURN_NONE;
811 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000812}
813
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200814/*[clinic input]
815list.extend
816
817 iterable: object
818 /
819
820Extend list by appending elements from the iterable.
821[clinic start generated code]*/
822
Barry Warsawdedf6d61998-10-09 16:37:25 +0000823static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200824list_extend(PyListObject *self, PyObject *iterable)
825/*[clinic end generated code: output=630fb3bca0c8e789 input=9ec5ba3a81be3a4d]*/
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000826{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000827 PyObject *it; /* iter(v) */
828 Py_ssize_t m; /* size of self */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200829 Py_ssize_t n; /* guess for size of iterable */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 Py_ssize_t mn; /* m + n */
831 Py_ssize_t i;
832 PyObject *(*iternext)(PyObject *);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000834 /* Special cases:
835 1) lists and tuples which can use PySequence_Fast ops
836 2) extending self to self requires making a copy first
837 */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200838 if (PyList_CheckExact(iterable) || PyTuple_CheckExact(iterable) ||
839 (PyObject *)self == iterable) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 PyObject **src, **dest;
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200841 iterable = PySequence_Fast(iterable, "argument must be iterable");
842 if (!iterable)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000843 return NULL;
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200844 n = PySequence_Fast_GET_SIZE(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000845 if (n == 0) {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200846 /* short circuit when iterable is empty */
847 Py_DECREF(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 Py_RETURN_NONE;
849 }
850 m = Py_SIZE(self);
Martin Panter94b39ce2017-01-14 06:30:37 +0000851 /* It should not be possible to allocate a list large enough to cause
852 an overflow on any relevant platform */
853 assert(m < PY_SSIZE_T_MAX - n);
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800854 if (list_resize(self, m + n) < 0) {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200855 Py_DECREF(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000856 return NULL;
857 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200858 /* note that we may still have self == iterable here for the
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 * situation a.extend(a), but the following code works
860 * in that case too. Just make sure to resize self
861 * before calling PySequence_Fast_ITEMS.
862 */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200863 /* populate the end of self with iterable's items */
864 src = PySequence_Fast_ITEMS(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000865 dest = self->ob_item + m;
866 for (i = 0; i < n; i++) {
867 PyObject *o = src[i];
868 Py_INCREF(o);
869 dest[i] = o;
870 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200871 Py_DECREF(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000872 Py_RETURN_NONE;
873 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000874
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200875 it = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000876 if (it == NULL)
877 return NULL;
878 iternext = *it->ob_type->tp_iternext;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 /* Guess a result list size. */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200881 n = PyObject_LengthHint(iterable, 8);
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800882 if (n < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000883 Py_DECREF(it);
884 return NULL;
885 }
886 m = Py_SIZE(self);
Martin Panterb93d8632016-07-25 02:39:20 +0000887 if (m > PY_SSIZE_T_MAX - n) {
888 /* m + n overflowed; on the chance that n lied, and there really
889 * is enough room, ignore it. If n was telling the truth, we'll
890 * eventually run out of memory during the loop.
891 */
892 }
893 else {
894 mn = m + n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000895 /* Make room. */
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800896 if (list_resize(self, mn) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000897 goto error;
898 /* Make the list sane again. */
899 Py_SIZE(self) = m;
900 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000901
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000902 /* Run iterator to exhaustion. */
903 for (;;) {
904 PyObject *item = iternext(it);
905 if (item == NULL) {
906 if (PyErr_Occurred()) {
907 if (PyErr_ExceptionMatches(PyExc_StopIteration))
908 PyErr_Clear();
909 else
910 goto error;
911 }
912 break;
913 }
914 if (Py_SIZE(self) < self->allocated) {
915 /* steals ref */
916 PyList_SET_ITEM(self, Py_SIZE(self), item);
917 ++Py_SIZE(self);
918 }
919 else {
920 int status = app1(self, item);
921 Py_DECREF(item); /* append creates a new ref */
922 if (status < 0)
923 goto error;
924 }
925 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000926
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000927 /* Cut back result list if initial guess was too large. */
Victor Stinner32fd6ea2013-07-16 21:45:58 +0200928 if (Py_SIZE(self) < self->allocated) {
929 if (list_resize(self, Py_SIZE(self)) < 0)
930 goto error;
931 }
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933 Py_DECREF(it);
934 Py_RETURN_NONE;
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000935
936 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000937 Py_DECREF(it);
938 return NULL;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000939}
940
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000941PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200942_PyList_Extend(PyListObject *self, PyObject *iterable)
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000943{
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200944 return list_extend(self, iterable);
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000945}
946
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000947static PyObject *
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000948list_inplace_concat(PyListObject *self, PyObject *other)
949{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 PyObject *result;
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000951
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200952 result = list_extend(self, other);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 if (result == NULL)
954 return result;
955 Py_DECREF(result);
956 Py_INCREF(self);
957 return (PyObject *)self;
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000958}
959
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200960/*[clinic input]
961list.pop
962
963 index: Py_ssize_t = -1
964 /
965
966Remove and return item at index (default last).
967
968Raises IndexError if list is empty or index is out of range.
969[clinic start generated code]*/
970
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000971static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200972list_pop_impl(PyListObject *self, Py_ssize_t index)
973/*[clinic end generated code: output=6bd69dcb3f17eca8 input=b83675976f329e6f]*/
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000974{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000975 PyObject *v;
976 int status;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000977
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 if (Py_SIZE(self) == 0) {
979 /* Special-case most common failure cause */
980 PyErr_SetString(PyExc_IndexError, "pop from empty list");
981 return NULL;
982 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200983 if (index < 0)
984 index += Py_SIZE(self);
985 if (index < 0 || index >= Py_SIZE(self)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 PyErr_SetString(PyExc_IndexError, "pop index out of range");
987 return NULL;
988 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200989 v = self->ob_item[index];
990 if (index == Py_SIZE(self) - 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 status = list_resize(self, Py_SIZE(self) - 1);
Victor Stinnerb27cd3e2013-07-08 22:20:44 +0200992 if (status >= 0)
993 return v; /* and v now owns the reference the list had */
994 else
995 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000996 }
997 Py_INCREF(v);
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200998 status = list_ass_slice(self, index, index+1, (PyObject *)NULL);
Victor Stinner095d99f2013-07-17 21:58:01 +0200999 if (status < 0) {
1000 Py_DECREF(v);
1001 return NULL;
1002 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001003 return v;
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +00001004}
1005
Tim Peters8e2e7ca2002-07-19 02:33:08 +00001006/* Reverse a slice of a list in place, from lo up to (exclusive) hi. */
1007static void
1008reverse_slice(PyObject **lo, PyObject **hi)
1009{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001010 assert(lo && hi);
Tim Peters8e2e7ca2002-07-19 02:33:08 +00001011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001012 --hi;
1013 while (lo < hi) {
1014 PyObject *t = *lo;
1015 *lo = *hi;
1016 *hi = t;
1017 ++lo;
1018 --hi;
1019 }
Tim Peters8e2e7ca2002-07-19 02:33:08 +00001020}
1021
Tim Petersa64dc242002-08-01 02:13:36 +00001022/* Lots of code for an adaptive, stable, natural mergesort. There are many
1023 * pieces to this algorithm; read listsort.txt for overviews and details.
1024 */
Guido van Rossum3f236de1996-12-10 23:55:39 +00001025
Daniel Stutzbach98338222010-12-02 21:55:33 +00001026/* A sortslice contains a pointer to an array of keys and a pointer to
1027 * an array of corresponding values. In other words, keys[i]
1028 * corresponds with values[i]. If values == NULL, then the keys are
1029 * also the values.
1030 *
1031 * Several convenience routines are provided here, so that keys and
1032 * values are always moved in sync.
1033 */
1034
1035typedef struct {
1036 PyObject **keys;
1037 PyObject **values;
1038} sortslice;
1039
1040Py_LOCAL_INLINE(void)
1041sortslice_copy(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j)
1042{
1043 s1->keys[i] = s2->keys[j];
1044 if (s1->values != NULL)
1045 s1->values[i] = s2->values[j];
1046}
1047
1048Py_LOCAL_INLINE(void)
Benjamin Peterson9efdcca2010-12-03 01:44:10 +00001049sortslice_copy_incr(sortslice *dst, sortslice *src)
1050{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001051 *dst->keys++ = *src->keys++;
1052 if (dst->values != NULL)
1053 *dst->values++ = *src->values++;
1054}
1055
1056Py_LOCAL_INLINE(void)
Benjamin Peterson9efdcca2010-12-03 01:44:10 +00001057sortslice_copy_decr(sortslice *dst, sortslice *src)
1058{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001059 *dst->keys-- = *src->keys--;
1060 if (dst->values != NULL)
1061 *dst->values-- = *src->values--;
1062}
1063
1064
1065Py_LOCAL_INLINE(void)
1066sortslice_memcpy(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j,
Benjamin Peterson9efdcca2010-12-03 01:44:10 +00001067 Py_ssize_t n)
1068{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001069 memcpy(&s1->keys[i], &s2->keys[j], sizeof(PyObject *) * n);
1070 if (s1->values != NULL)
1071 memcpy(&s1->values[i], &s2->values[j], sizeof(PyObject *) * n);
1072}
1073
1074Py_LOCAL_INLINE(void)
1075sortslice_memmove(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j,
Benjamin Peterson9efdcca2010-12-03 01:44:10 +00001076 Py_ssize_t n)
1077{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001078 memmove(&s1->keys[i], &s2->keys[j], sizeof(PyObject *) * n);
1079 if (s1->values != NULL)
1080 memmove(&s1->values[i], &s2->values[j], sizeof(PyObject *) * n);
1081}
1082
1083Py_LOCAL_INLINE(void)
Benjamin Peterson9efdcca2010-12-03 01:44:10 +00001084sortslice_advance(sortslice *slice, Py_ssize_t n)
1085{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001086 slice->keys += n;
1087 if (slice->values != NULL)
1088 slice->values += n;
1089}
1090
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001091/* Comparison function: PyObject_RichCompareBool with Py_LT.
Tim Petersa64dc242002-08-01 02:13:36 +00001092 * Returns -1 on error, 1 if x < y, 0 if x >= y.
1093 */
Guido van Rossum3f236de1996-12-10 23:55:39 +00001094
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001095#define ISLT(X, Y) (PyObject_RichCompareBool(X, Y, Py_LT))
Tim Peters66860f62002-08-04 17:47:26 +00001096
1097/* Compare X to Y via "<". Goto "fail" if the comparison raises an
Tim Petersa8c974c2002-07-19 03:30:57 +00001098 error. Else "k" is set to true iff X<Y, and an "if (k)" block is
1099 started. It makes more sense in context <wink>. X and Y are PyObject*s.
1100*/
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001101#define IFLT(X, Y) if ((k = ISLT(X, Y)) < 0) goto fail; \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001102 if (k)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001103
1104/* binarysort is the best method for sorting small arrays: it does
1105 few compares, but can do data movement quadratic in the number of
1106 elements.
Guido van Rossum42812581998-06-17 14:15:44 +00001107 [lo, hi) is a contiguous slice of a list, and is sorted via
Tim Petersa8c974c2002-07-19 03:30:57 +00001108 binary insertion. This sort is stable.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001109 On entry, must have lo <= start <= hi, and that [lo, start) is already
1110 sorted (pass start == lo if you don't know!).
Tim Petersa8c974c2002-07-19 03:30:57 +00001111 If islt() complains return -1, else 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001112 Even in case of error, the output slice will be some permutation of
1113 the input (nothing is lost or duplicated).
1114*/
Guido van Rossum3f236de1996-12-10 23:55:39 +00001115static int
Daniel Stutzbach98338222010-12-02 21:55:33 +00001116binarysort(sortslice lo, PyObject **hi, PyObject **start)
Guido van Rossum3f236de1996-12-10 23:55:39 +00001117{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001118 Py_ssize_t k;
1119 PyObject **l, **p, **r;
1120 PyObject *pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001121
Daniel Stutzbach98338222010-12-02 21:55:33 +00001122 assert(lo.keys <= start && start <= hi);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001123 /* assert [lo, start) is sorted */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001124 if (lo.keys == start)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001125 ++start;
1126 for (; start < hi; ++start) {
1127 /* set l to where *start belongs */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001128 l = lo.keys;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001129 r = start;
1130 pivot = *r;
1131 /* Invariants:
1132 * pivot >= all in [lo, l).
1133 * pivot < all in [r, start).
1134 * The second is vacuously true at the start.
1135 */
1136 assert(l < r);
1137 do {
1138 p = l + ((r - l) >> 1);
1139 IFLT(pivot, *p)
1140 r = p;
1141 else
1142 l = p+1;
1143 } while (l < r);
1144 assert(l == r);
1145 /* The invariants still hold, so pivot >= all in [lo, l) and
1146 pivot < all in [l, start), so pivot belongs at l. Note
1147 that if there are elements equal to pivot, l points to the
1148 first slot after them -- that's why this sort is stable.
1149 Slide over to make room.
1150 Caution: using memmove is much slower under MSVC 5;
1151 we're not usually moving many slots. */
1152 for (p = start; p > l; --p)
1153 *p = *(p-1);
1154 *l = pivot;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001155 if (lo.values != NULL) {
1156 Py_ssize_t offset = lo.values - lo.keys;
1157 p = start + offset;
1158 pivot = *p;
1159 l += offset;
1160 for (p = start + offset; p > l; --p)
1161 *p = *(p-1);
1162 *l = pivot;
1163 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001164 }
1165 return 0;
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001166
1167 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001168 return -1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001169}
1170
Tim Petersa64dc242002-08-01 02:13:36 +00001171/*
1172Return the length of the run beginning at lo, in the slice [lo, hi). lo < hi
1173is required on entry. "A run" is the longest ascending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001174
Tim Petersa64dc242002-08-01 02:13:36 +00001175 lo[0] <= lo[1] <= lo[2] <= ...
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001176
Tim Petersa64dc242002-08-01 02:13:36 +00001177or the longest descending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001178
Tim Petersa64dc242002-08-01 02:13:36 +00001179 lo[0] > lo[1] > lo[2] > ...
Tim Peters3b01a122002-07-19 02:35:45 +00001180
Tim Petersa64dc242002-08-01 02:13:36 +00001181Boolean *descending is set to 0 in the former case, or to 1 in the latter.
1182For its intended use in a stable mergesort, the strictness of the defn of
1183"descending" is needed so that the caller can safely reverse a descending
1184sequence without violating stability (strict > ensures there are no equal
1185elements to get out of order).
1186
1187Returns -1 in case of error.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001188*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001189static Py_ssize_t
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001190count_run(PyObject **lo, PyObject **hi, int *descending)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001191{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001192 Py_ssize_t k;
1193 Py_ssize_t n;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 assert(lo < hi);
1196 *descending = 0;
1197 ++lo;
1198 if (lo == hi)
1199 return 1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001201 n = 2;
1202 IFLT(*lo, *(lo-1)) {
1203 *descending = 1;
1204 for (lo = lo+1; lo < hi; ++lo, ++n) {
1205 IFLT(*lo, *(lo-1))
1206 ;
1207 else
1208 break;
1209 }
1210 }
1211 else {
1212 for (lo = lo+1; lo < hi; ++lo, ++n) {
1213 IFLT(*lo, *(lo-1))
1214 break;
1215 }
1216 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001218 return n;
Tim Petersa64dc242002-08-01 02:13:36 +00001219fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001220 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001221}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001222
Tim Petersa64dc242002-08-01 02:13:36 +00001223/*
1224Locate the proper position of key in a sorted vector; if the vector contains
1225an element equal to key, return the position immediately to the left of
1226the leftmost equal element. [gallop_right() does the same except returns
1227the position to the right of the rightmost equal element (if any).]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001228
Tim Petersa64dc242002-08-01 02:13:36 +00001229"a" is a sorted vector with n elements, starting at a[0]. n must be > 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001230
Tim Petersa64dc242002-08-01 02:13:36 +00001231"hint" is an index at which to begin the search, 0 <= hint < n. The closer
1232hint is to the final result, the faster this runs.
1233
1234The return value is the int k in 0..n such that
1235
1236 a[k-1] < key <= a[k]
1237
1238pretending that *(a-1) is minus infinity and a[n] is plus infinity. IOW,
1239key belongs at index k; or, IOW, the first k elements of a should precede
1240key, and the last n-k should follow key.
1241
1242Returns -1 on error. See listsort.txt for info on the method.
1243*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001244static Py_ssize_t
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001245gallop_left(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint)
Tim Petersa64dc242002-08-01 02:13:36 +00001246{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001247 Py_ssize_t ofs;
1248 Py_ssize_t lastofs;
1249 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001251 assert(key && a && n > 0 && hint >= 0 && hint < n);
Tim Petersa64dc242002-08-01 02:13:36 +00001252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001253 a += hint;
1254 lastofs = 0;
1255 ofs = 1;
1256 IFLT(*a, key) {
1257 /* a[hint] < key -- gallop right, until
1258 * a[hint + lastofs] < key <= a[hint + ofs]
1259 */
1260 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
1261 while (ofs < maxofs) {
1262 IFLT(a[ofs], key) {
1263 lastofs = ofs;
1264 ofs = (ofs << 1) + 1;
1265 if (ofs <= 0) /* int overflow */
1266 ofs = maxofs;
1267 }
1268 else /* key <= a[hint + ofs] */
1269 break;
1270 }
1271 if (ofs > maxofs)
1272 ofs = maxofs;
1273 /* Translate back to offsets relative to &a[0]. */
1274 lastofs += hint;
1275 ofs += hint;
1276 }
1277 else {
1278 /* key <= a[hint] -- gallop left, until
1279 * a[hint - ofs] < key <= a[hint - lastofs]
1280 */
1281 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
1282 while (ofs < maxofs) {
1283 IFLT(*(a-ofs), key)
1284 break;
1285 /* key <= a[hint - ofs] */
1286 lastofs = ofs;
1287 ofs = (ofs << 1) + 1;
1288 if (ofs <= 0) /* int overflow */
1289 ofs = maxofs;
1290 }
1291 if (ofs > maxofs)
1292 ofs = maxofs;
1293 /* Translate back to positive offsets relative to &a[0]. */
1294 k = lastofs;
1295 lastofs = hint - ofs;
1296 ofs = hint - k;
1297 }
1298 a -= hint;
Tim Petersa64dc242002-08-01 02:13:36 +00001299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001300 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1301 /* Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the
1302 * right of lastofs but no farther right than ofs. Do a binary
1303 * search, with invariant a[lastofs-1] < key <= a[ofs].
1304 */
1305 ++lastofs;
1306 while (lastofs < ofs) {
1307 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001309 IFLT(a[m], key)
1310 lastofs = m+1; /* a[m] < key */
1311 else
1312 ofs = m; /* key <= a[m] */
1313 }
1314 assert(lastofs == ofs); /* so a[ofs-1] < key <= a[ofs] */
1315 return ofs;
Tim Petersa64dc242002-08-01 02:13:36 +00001316
1317fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001318 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001319}
1320
1321/*
1322Exactly like gallop_left(), except that if key already exists in a[0:n],
1323finds the position immediately to the right of the rightmost equal value.
1324
1325The return value is the int k in 0..n such that
1326
1327 a[k-1] <= key < a[k]
1328
1329or -1 if error.
1330
1331The code duplication is massive, but this is enough different given that
1332we're sticking to "<" comparisons that it's much harder to follow if
1333written as one routine with yet another "left or right?" flag.
1334*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001335static Py_ssize_t
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001336gallop_right(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint)
Tim Petersa64dc242002-08-01 02:13:36 +00001337{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001338 Py_ssize_t ofs;
1339 Py_ssize_t lastofs;
1340 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001342 assert(key && a && n > 0 && hint >= 0 && hint < n);
Tim Petersa64dc242002-08-01 02:13:36 +00001343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001344 a += hint;
1345 lastofs = 0;
1346 ofs = 1;
1347 IFLT(key, *a) {
1348 /* key < a[hint] -- gallop left, until
1349 * a[hint - ofs] <= key < a[hint - lastofs]
1350 */
1351 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
1352 while (ofs < maxofs) {
1353 IFLT(key, *(a-ofs)) {
1354 lastofs = ofs;
1355 ofs = (ofs << 1) + 1;
1356 if (ofs <= 0) /* int overflow */
1357 ofs = maxofs;
1358 }
1359 else /* a[hint - ofs] <= key */
1360 break;
1361 }
1362 if (ofs > maxofs)
1363 ofs = maxofs;
1364 /* Translate back to positive offsets relative to &a[0]. */
1365 k = lastofs;
1366 lastofs = hint - ofs;
1367 ofs = hint - k;
1368 }
1369 else {
1370 /* a[hint] <= key -- gallop right, until
1371 * a[hint + lastofs] <= key < a[hint + ofs]
1372 */
1373 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
1374 while (ofs < maxofs) {
1375 IFLT(key, a[ofs])
1376 break;
1377 /* a[hint + ofs] <= key */
1378 lastofs = ofs;
1379 ofs = (ofs << 1) + 1;
1380 if (ofs <= 0) /* int overflow */
1381 ofs = maxofs;
1382 }
1383 if (ofs > maxofs)
1384 ofs = maxofs;
1385 /* Translate back to offsets relative to &a[0]. */
1386 lastofs += hint;
1387 ofs += hint;
1388 }
1389 a -= hint;
Tim Petersa64dc242002-08-01 02:13:36 +00001390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001391 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1392 /* Now a[lastofs] <= key < a[ofs], so key belongs somewhere to the
1393 * right of lastofs but no farther right than ofs. Do a binary
1394 * search, with invariant a[lastofs-1] <= key < a[ofs].
1395 */
1396 ++lastofs;
1397 while (lastofs < ofs) {
1398 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001400 IFLT(key, a[m])
1401 ofs = m; /* key < a[m] */
1402 else
1403 lastofs = m+1; /* a[m] <= key */
1404 }
1405 assert(lastofs == ofs); /* so a[ofs-1] <= key < a[ofs] */
1406 return ofs;
Tim Petersa64dc242002-08-01 02:13:36 +00001407
1408fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001409 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001410}
1411
1412/* The maximum number of entries in a MergeState's pending-runs stack.
1413 * This is enough to sort arrays of size up to about
1414 * 32 * phi ** MAX_MERGE_PENDING
1415 * where phi ~= 1.618. 85 is ridiculouslylarge enough, good for an array
1416 * with 2**64 elements.
1417 */
1418#define MAX_MERGE_PENDING 85
1419
Tim Peterse05f65a2002-08-10 05:21:15 +00001420/* When we get into galloping mode, we stay there until both runs win less
1421 * often than MIN_GALLOP consecutive times. See listsort.txt for more info.
Tim Petersa64dc242002-08-01 02:13:36 +00001422 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001423#define MIN_GALLOP 7
Tim Petersa64dc242002-08-01 02:13:36 +00001424
1425/* Avoid malloc for small temp arrays. */
1426#define MERGESTATE_TEMP_SIZE 256
1427
1428/* One MergeState exists on the stack per invocation of mergesort. It's just
1429 * a convenient way to pass state around among the helper functions.
1430 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001431struct s_slice {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001432 sortslice base;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001433 Py_ssize_t len;
Tim Peterse05f65a2002-08-10 05:21:15 +00001434};
1435
Tim Petersa64dc242002-08-01 02:13:36 +00001436typedef struct s_MergeState {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001437 /* This controls when we get *into* galloping mode. It's initialized
1438 * to MIN_GALLOP. merge_lo and merge_hi tend to nudge it higher for
1439 * random data, and lower for highly structured data.
1440 */
1441 Py_ssize_t min_gallop;
Tim Peterse05f65a2002-08-10 05:21:15 +00001442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001443 /* 'a' is temp storage to help with merges. It contains room for
1444 * alloced entries.
1445 */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001446 sortslice a; /* may point to temparray below */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001447 Py_ssize_t alloced;
Tim Petersa64dc242002-08-01 02:13:36 +00001448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001449 /* A stack of n pending runs yet to be merged. Run #i starts at
1450 * address base[i] and extends for len[i] elements. It's always
1451 * true (so long as the indices are in bounds) that
1452 *
1453 * pending[i].base + pending[i].len == pending[i+1].base
1454 *
1455 * so we could cut the storage for this, but it's a minor amount,
1456 * and keeping all the info explicit simplifies the code.
1457 */
1458 int n;
1459 struct s_slice pending[MAX_MERGE_PENDING];
Tim Petersa64dc242002-08-01 02:13:36 +00001460
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001461 /* 'a' points to this when possible, rather than muck with malloc. */
1462 PyObject *temparray[MERGESTATE_TEMP_SIZE];
Tim Petersa64dc242002-08-01 02:13:36 +00001463} MergeState;
1464
1465/* Conceptually a MergeState's constructor. */
1466static void
Victor Stinner0fcab4a2011-01-04 12:59:15 +00001467merge_init(MergeState *ms, Py_ssize_t list_size, int has_keyfunc)
Tim Petersa64dc242002-08-01 02:13:36 +00001468{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001469 assert(ms != NULL);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001470 if (has_keyfunc) {
1471 /* The temporary space for merging will need at most half the list
1472 * size rounded up. Use the minimum possible space so we can use the
1473 * rest of temparray for other things. In particular, if there is
1474 * enough extra space, listsort() will use it to store the keys.
1475 */
1476 ms->alloced = (list_size + 1) / 2;
1477
1478 /* ms->alloced describes how many keys will be stored at
1479 ms->temparray, but we also need to store the values. Hence,
1480 ms->alloced is capped at half of MERGESTATE_TEMP_SIZE. */
1481 if (MERGESTATE_TEMP_SIZE / 2 < ms->alloced)
1482 ms->alloced = MERGESTATE_TEMP_SIZE / 2;
1483 ms->a.values = &ms->temparray[ms->alloced];
1484 }
1485 else {
1486 ms->alloced = MERGESTATE_TEMP_SIZE;
1487 ms->a.values = NULL;
1488 }
1489 ms->a.keys = ms->temparray;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001490 ms->n = 0;
1491 ms->min_gallop = MIN_GALLOP;
Tim Petersa64dc242002-08-01 02:13:36 +00001492}
1493
1494/* Free all the temp memory owned by the MergeState. This must be called
1495 * when you're done with a MergeState, and may be called before then if
1496 * you want to free the temp memory early.
1497 */
1498static void
1499merge_freemem(MergeState *ms)
1500{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001501 assert(ms != NULL);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001502 if (ms->a.keys != ms->temparray)
1503 PyMem_Free(ms->a.keys);
Tim Petersa64dc242002-08-01 02:13:36 +00001504}
1505
1506/* Ensure enough temp memory for 'need' array slots is available.
1507 * Returns 0 on success and -1 if the memory can't be gotten.
1508 */
1509static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001510merge_getmem(MergeState *ms, Py_ssize_t need)
Tim Petersa64dc242002-08-01 02:13:36 +00001511{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001512 int multiplier;
1513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001514 assert(ms != NULL);
1515 if (need <= ms->alloced)
1516 return 0;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001517
1518 multiplier = ms->a.values != NULL ? 2 : 1;
1519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001520 /* Don't realloc! That can cost cycles to copy the old data, but
1521 * we don't care what's in the block.
1522 */
1523 merge_freemem(ms);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001524 if ((size_t)need > PY_SSIZE_T_MAX / sizeof(PyObject*) / multiplier) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001525 PyErr_NoMemory();
1526 return -1;
1527 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001528 ms->a.keys = (PyObject**)PyMem_Malloc(multiplier * need
1529 * sizeof(PyObject *));
1530 if (ms->a.keys != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001531 ms->alloced = need;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001532 if (ms->a.values != NULL)
1533 ms->a.values = &ms->a.keys[need];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001534 return 0;
1535 }
1536 PyErr_NoMemory();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001537 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001538}
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001539#define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 : \
1540 merge_getmem(MS, NEED))
Tim Petersa64dc242002-08-01 02:13:36 +00001541
Daniel Stutzbach98338222010-12-02 21:55:33 +00001542/* Merge the na elements starting at ssa with the nb elements starting at
1543 * ssb.keys = ssa.keys + na in a stable way, in-place. na and nb must be > 0.
1544 * Must also have that ssa.keys[na-1] belongs at the end of the merge, and
1545 * should have na <= nb. See listsort.txt for more info. Return 0 if
1546 * successful, -1 if error.
Tim Petersa64dc242002-08-01 02:13:36 +00001547 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001548static Py_ssize_t
Daniel Stutzbach98338222010-12-02 21:55:33 +00001549merge_lo(MergeState *ms, sortslice ssa, Py_ssize_t na,
1550 sortslice ssb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001551{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001552 Py_ssize_t k;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001553 sortslice dest;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001554 int result = -1; /* guilty until proved innocent */
1555 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001556
Daniel Stutzbach98338222010-12-02 21:55:33 +00001557 assert(ms && ssa.keys && ssb.keys && na > 0 && nb > 0);
1558 assert(ssa.keys + na == ssb.keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001559 if (MERGE_GETMEM(ms, na) < 0)
1560 return -1;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001561 sortslice_memcpy(&ms->a, 0, &ssa, 0, na);
1562 dest = ssa;
1563 ssa = ms->a;
Tim Petersa64dc242002-08-01 02:13:36 +00001564
Daniel Stutzbach98338222010-12-02 21:55:33 +00001565 sortslice_copy_incr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001566 --nb;
1567 if (nb == 0)
1568 goto Succeed;
1569 if (na == 1)
1570 goto CopyB;
Tim Petersa64dc242002-08-01 02:13:36 +00001571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001572 min_gallop = ms->min_gallop;
1573 for (;;) {
1574 Py_ssize_t acount = 0; /* # of times A won in a row */
1575 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001577 /* Do the straightforward thing until (if ever) one run
1578 * appears to win consistently.
1579 */
1580 for (;;) {
1581 assert(na > 1 && nb > 0);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001582 k = ISLT(ssb.keys[0], ssa.keys[0]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001583 if (k) {
1584 if (k < 0)
1585 goto Fail;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001586 sortslice_copy_incr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001587 ++bcount;
1588 acount = 0;
1589 --nb;
1590 if (nb == 0)
1591 goto Succeed;
1592 if (bcount >= min_gallop)
1593 break;
1594 }
1595 else {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001596 sortslice_copy_incr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001597 ++acount;
1598 bcount = 0;
1599 --na;
1600 if (na == 1)
1601 goto CopyB;
1602 if (acount >= min_gallop)
1603 break;
1604 }
1605 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001607 /* One run is winning so consistently that galloping may
1608 * be a huge win. So try that, and continue galloping until
1609 * (if ever) neither run appears to be winning consistently
1610 * anymore.
1611 */
1612 ++min_gallop;
1613 do {
1614 assert(na > 1 && nb > 0);
1615 min_gallop -= min_gallop > 1;
1616 ms->min_gallop = min_gallop;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001617 k = gallop_right(ssb.keys[0], ssa.keys, na, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001618 acount = k;
1619 if (k) {
1620 if (k < 0)
1621 goto Fail;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001622 sortslice_memcpy(&dest, 0, &ssa, 0, k);
1623 sortslice_advance(&dest, k);
1624 sortslice_advance(&ssa, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001625 na -= k;
1626 if (na == 1)
1627 goto CopyB;
1628 /* na==0 is impossible now if the comparison
1629 * function is consistent, but we can't assume
1630 * that it is.
1631 */
1632 if (na == 0)
1633 goto Succeed;
1634 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001635 sortslice_copy_incr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001636 --nb;
1637 if (nb == 0)
1638 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001639
Daniel Stutzbach98338222010-12-02 21:55:33 +00001640 k = gallop_left(ssa.keys[0], ssb.keys, nb, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001641 bcount = k;
1642 if (k) {
1643 if (k < 0)
1644 goto Fail;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001645 sortslice_memmove(&dest, 0, &ssb, 0, k);
1646 sortslice_advance(&dest, k);
1647 sortslice_advance(&ssb, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001648 nb -= k;
1649 if (nb == 0)
1650 goto Succeed;
1651 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001652 sortslice_copy_incr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001653 --na;
1654 if (na == 1)
1655 goto CopyB;
1656 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
1657 ++min_gallop; /* penalize it for leaving galloping mode */
1658 ms->min_gallop = min_gallop;
1659 }
Tim Petersa64dc242002-08-01 02:13:36 +00001660Succeed:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001661 result = 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001662Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001663 if (na)
Daniel Stutzbach98338222010-12-02 21:55:33 +00001664 sortslice_memcpy(&dest, 0, &ssa, 0, na);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001665 return result;
Tim Petersa64dc242002-08-01 02:13:36 +00001666CopyB:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001667 assert(na == 1 && nb > 0);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001668 /* The last element of ssa belongs at the end of the merge. */
1669 sortslice_memmove(&dest, 0, &ssb, 0, nb);
1670 sortslice_copy(&dest, nb, &ssa, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001671 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001672}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001673
Daniel Stutzbach98338222010-12-02 21:55:33 +00001674/* Merge the na elements starting at pa with the nb elements starting at
1675 * ssb.keys = ssa.keys + na in a stable way, in-place. na and nb must be > 0.
1676 * Must also have that ssa.keys[na-1] belongs at the end of the merge, and
1677 * should have na >= nb. See listsort.txt for more info. Return 0 if
1678 * successful, -1 if error.
Tim Petersa64dc242002-08-01 02:13:36 +00001679 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001680static Py_ssize_t
Daniel Stutzbach98338222010-12-02 21:55:33 +00001681merge_hi(MergeState *ms, sortslice ssa, Py_ssize_t na,
1682 sortslice ssb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001683{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001684 Py_ssize_t k;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001685 sortslice dest, basea, baseb;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001686 int result = -1; /* guilty until proved innocent */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001687 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001688
Daniel Stutzbach98338222010-12-02 21:55:33 +00001689 assert(ms && ssa.keys && ssb.keys && na > 0 && nb > 0);
1690 assert(ssa.keys + na == ssb.keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001691 if (MERGE_GETMEM(ms, nb) < 0)
1692 return -1;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001693 dest = ssb;
1694 sortslice_advance(&dest, nb-1);
1695 sortslice_memcpy(&ms->a, 0, &ssb, 0, nb);
1696 basea = ssa;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001697 baseb = ms->a;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001698 ssb.keys = ms->a.keys + nb - 1;
1699 if (ssb.values != NULL)
1700 ssb.values = ms->a.values + nb - 1;
1701 sortslice_advance(&ssa, na - 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001702
Daniel Stutzbach98338222010-12-02 21:55:33 +00001703 sortslice_copy_decr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001704 --na;
1705 if (na == 0)
1706 goto Succeed;
1707 if (nb == 1)
1708 goto CopyA;
Tim Petersa64dc242002-08-01 02:13:36 +00001709
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001710 min_gallop = ms->min_gallop;
1711 for (;;) {
1712 Py_ssize_t acount = 0; /* # of times A won in a row */
1713 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001715 /* Do the straightforward thing until (if ever) one run
1716 * appears to win consistently.
1717 */
1718 for (;;) {
1719 assert(na > 0 && nb > 1);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001720 k = ISLT(ssb.keys[0], ssa.keys[0]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001721 if (k) {
1722 if (k < 0)
1723 goto Fail;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001724 sortslice_copy_decr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001725 ++acount;
1726 bcount = 0;
1727 --na;
1728 if (na == 0)
1729 goto Succeed;
1730 if (acount >= min_gallop)
1731 break;
1732 }
1733 else {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001734 sortslice_copy_decr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001735 ++bcount;
1736 acount = 0;
1737 --nb;
1738 if (nb == 1)
1739 goto CopyA;
1740 if (bcount >= min_gallop)
1741 break;
1742 }
1743 }
Tim Petersa64dc242002-08-01 02:13:36 +00001744
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001745 /* One run is winning so consistently that galloping may
1746 * be a huge win. So try that, and continue galloping until
1747 * (if ever) neither run appears to be winning consistently
1748 * anymore.
1749 */
1750 ++min_gallop;
1751 do {
1752 assert(na > 0 && nb > 1);
1753 min_gallop -= min_gallop > 1;
1754 ms->min_gallop = min_gallop;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001755 k = gallop_right(ssb.keys[0], basea.keys, na, na-1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001756 if (k < 0)
1757 goto Fail;
1758 k = na - k;
1759 acount = k;
1760 if (k) {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001761 sortslice_advance(&dest, -k);
1762 sortslice_advance(&ssa, -k);
1763 sortslice_memmove(&dest, 1, &ssa, 1, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001764 na -= k;
1765 if (na == 0)
1766 goto Succeed;
1767 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001768 sortslice_copy_decr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001769 --nb;
1770 if (nb == 1)
1771 goto CopyA;
Tim Petersa64dc242002-08-01 02:13:36 +00001772
Daniel Stutzbach98338222010-12-02 21:55:33 +00001773 k = gallop_left(ssa.keys[0], baseb.keys, nb, nb-1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001774 if (k < 0)
1775 goto Fail;
1776 k = nb - k;
1777 bcount = k;
1778 if (k) {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001779 sortslice_advance(&dest, -k);
1780 sortslice_advance(&ssb, -k);
1781 sortslice_memcpy(&dest, 1, &ssb, 1, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001782 nb -= k;
1783 if (nb == 1)
1784 goto CopyA;
1785 /* nb==0 is impossible now if the comparison
1786 * function is consistent, but we can't assume
1787 * that it is.
1788 */
1789 if (nb == 0)
1790 goto Succeed;
1791 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001792 sortslice_copy_decr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001793 --na;
1794 if (na == 0)
1795 goto Succeed;
1796 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
1797 ++min_gallop; /* penalize it for leaving galloping mode */
1798 ms->min_gallop = min_gallop;
1799 }
Tim Petersa64dc242002-08-01 02:13:36 +00001800Succeed:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001801 result = 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001802Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001803 if (nb)
Daniel Stutzbach98338222010-12-02 21:55:33 +00001804 sortslice_memcpy(&dest, -(nb-1), &baseb, 0, nb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001805 return result;
Tim Petersa64dc242002-08-01 02:13:36 +00001806CopyA:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001807 assert(nb == 1 && na > 0);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001808 /* The first element of ssb belongs at the front of the merge. */
1809 sortslice_memmove(&dest, 1-na, &ssa, 1-na, na);
1810 sortslice_advance(&dest, -na);
1811 sortslice_advance(&ssa, -na);
1812 sortslice_copy(&dest, 0, &ssb, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001813 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001814}
1815
1816/* Merge the two runs at stack indices i and i+1.
1817 * Returns 0 on success, -1 on error.
1818 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001819static Py_ssize_t
1820merge_at(MergeState *ms, Py_ssize_t i)
Tim Petersa64dc242002-08-01 02:13:36 +00001821{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001822 sortslice ssa, ssb;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001823 Py_ssize_t na, nb;
1824 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001825
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001826 assert(ms != NULL);
1827 assert(ms->n >= 2);
1828 assert(i >= 0);
1829 assert(i == ms->n - 2 || i == ms->n - 3);
Tim Petersa64dc242002-08-01 02:13:36 +00001830
Daniel Stutzbach98338222010-12-02 21:55:33 +00001831 ssa = ms->pending[i].base;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001832 na = ms->pending[i].len;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001833 ssb = ms->pending[i+1].base;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001834 nb = ms->pending[i+1].len;
1835 assert(na > 0 && nb > 0);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001836 assert(ssa.keys + na == ssb.keys);
Tim Petersa64dc242002-08-01 02:13:36 +00001837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001838 /* Record the length of the combined runs; if i is the 3rd-last
1839 * run now, also slide over the last run (which isn't involved
1840 * in this merge). The current run i+1 goes away in any case.
1841 */
1842 ms->pending[i].len = na + nb;
1843 if (i == ms->n - 3)
1844 ms->pending[i+1] = ms->pending[i+2];
1845 --ms->n;
Tim Petersa64dc242002-08-01 02:13:36 +00001846
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001847 /* Where does b start in a? Elements in a before that can be
1848 * ignored (already in place).
1849 */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001850 k = gallop_right(*ssb.keys, ssa.keys, na, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001851 if (k < 0)
1852 return -1;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001853 sortslice_advance(&ssa, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001854 na -= k;
1855 if (na == 0)
1856 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001858 /* Where does a end in b? Elements in b after that can be
1859 * ignored (already in place).
1860 */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001861 nb = gallop_left(ssa.keys[na-1], ssb.keys, nb, nb-1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001862 if (nb <= 0)
1863 return nb;
Tim Petersa64dc242002-08-01 02:13:36 +00001864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001865 /* Merge what remains of the runs, using a temp array with
1866 * min(na, nb) elements.
1867 */
1868 if (na <= nb)
Daniel Stutzbach98338222010-12-02 21:55:33 +00001869 return merge_lo(ms, ssa, na, ssb, nb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001870 else
Daniel Stutzbach98338222010-12-02 21:55:33 +00001871 return merge_hi(ms, ssa, na, ssb, nb);
Tim Petersa64dc242002-08-01 02:13:36 +00001872}
1873
1874/* Examine the stack of runs waiting to be merged, merging adjacent runs
1875 * until the stack invariants are re-established:
1876 *
1877 * 1. len[-3] > len[-2] + len[-1]
1878 * 2. len[-2] > len[-1]
1879 *
1880 * See listsort.txt for more info.
1881 *
1882 * Returns 0 on success, -1 on error.
1883 */
1884static int
1885merge_collapse(MergeState *ms)
1886{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001887 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001889 assert(ms);
1890 while (ms->n > 1) {
1891 Py_ssize_t n = ms->n - 2;
Benjamin Petersonb808d592015-02-25 10:12:26 -05001892 if ((n > 0 && p[n-1].len <= p[n].len + p[n+1].len) ||
1893 (n > 1 && p[n-2].len <= p[n-1].len + p[n].len)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001894 if (p[n-1].len < p[n+1].len)
1895 --n;
1896 if (merge_at(ms, n) < 0)
1897 return -1;
1898 }
1899 else if (p[n].len <= p[n+1].len) {
1900 if (merge_at(ms, n) < 0)
1901 return -1;
1902 }
1903 else
1904 break;
1905 }
1906 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001907}
1908
1909/* Regardless of invariants, merge all runs on the stack until only one
1910 * remains. This is used at the end of the mergesort.
1911 *
1912 * Returns 0 on success, -1 on error.
1913 */
1914static int
1915merge_force_collapse(MergeState *ms)
1916{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001917 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001918
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001919 assert(ms);
1920 while (ms->n > 1) {
1921 Py_ssize_t n = ms->n - 2;
1922 if (n > 0 && p[n-1].len < p[n+1].len)
1923 --n;
1924 if (merge_at(ms, n) < 0)
1925 return -1;
1926 }
1927 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001928}
1929
1930/* Compute a good value for the minimum run length; natural runs shorter
1931 * than this are boosted artificially via binary insertion.
1932 *
1933 * If n < 64, return n (it's too small to bother with fancy stuff).
1934 * Else if n is an exact power of 2, return 32.
1935 * Else return an int k, 32 <= k <= 64, such that n/k is close to, but
1936 * strictly less than, an exact power of 2.
1937 *
1938 * See listsort.txt for more info.
1939 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001940static Py_ssize_t
1941merge_compute_minrun(Py_ssize_t n)
Tim Petersa64dc242002-08-01 02:13:36 +00001942{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001943 Py_ssize_t r = 0; /* becomes 1 if any 1 bits are shifted off */
Tim Petersa64dc242002-08-01 02:13:36 +00001944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001945 assert(n >= 0);
1946 while (n >= 64) {
1947 r |= n & 1;
1948 n >>= 1;
1949 }
1950 return n + r;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001951}
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001952
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001953static void
Daniel Stutzbach98338222010-12-02 21:55:33 +00001954reverse_sortslice(sortslice *s, Py_ssize_t n)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001955{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001956 reverse_slice(s->keys, &s->keys[n]);
1957 if (s->values != NULL)
1958 reverse_slice(s->values, &s->values[n]);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001959}
1960
Tim Petersa64dc242002-08-01 02:13:36 +00001961/* An adaptive, stable, natural mergesort. See listsort.txt.
1962 * Returns Py_None on success, NULL on error. Even in case of error, the
1963 * list will be some permutation of its input state (nothing is lost or
1964 * duplicated).
1965 */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02001966/*[clinic input]
1967list.sort
1968
1969 *
1970 key as keyfunc: object = None
1971 reverse: int(c_default="0") = False
1972
1973Stable sort *IN PLACE*.
1974[clinic start generated code]*/
1975
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001976static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02001977list_sort_impl(PyListObject *self, PyObject *keyfunc, int reverse)
1978/*[clinic end generated code: output=57b9f9c5e23fbe42 input=5029c13c9209d86a]*/
Guido van Rossum3f236de1996-12-10 23:55:39 +00001979{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001980 MergeState ms;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001981 Py_ssize_t nremaining;
1982 Py_ssize_t minrun;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001983 sortslice lo;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001984 Py_ssize_t saved_ob_size, saved_allocated;
1985 PyObject **saved_ob_item;
1986 PyObject **final_ob_item;
1987 PyObject *result = NULL; /* guilty until proved innocent */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001988 Py_ssize_t i;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001989 PyObject **keys;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001990
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001991 assert(self != NULL);
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02001992 assert(PyList_Check(self));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001993 if (keyfunc == Py_None)
1994 keyfunc = NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001996 /* The list is temporarily made empty, so that mutations performed
1997 * by comparison functions can't affect the slice of memory we're
1998 * sorting (allowing mutations during sorting is a core-dump
1999 * factory, since ob_item may change).
2000 */
2001 saved_ob_size = Py_SIZE(self);
2002 saved_ob_item = self->ob_item;
2003 saved_allocated = self->allocated;
2004 Py_SIZE(self) = 0;
2005 self->ob_item = NULL;
2006 self->allocated = -1; /* any operation will reset it to >= 0 */
Tim Peters330f9e92002-07-19 07:05:44 +00002007
Daniel Stutzbach98338222010-12-02 21:55:33 +00002008 if (keyfunc == NULL) {
2009 keys = NULL;
2010 lo.keys = saved_ob_item;
2011 lo.values = NULL;
2012 }
2013 else {
2014 if (saved_ob_size < MERGESTATE_TEMP_SIZE/2)
2015 /* Leverage stack space we allocated but won't otherwise use */
2016 keys = &ms.temparray[saved_ob_size+1];
2017 else {
2018 keys = PyMem_MALLOC(sizeof(PyObject *) * saved_ob_size);
Benjamin Peterson0823ffb2015-04-23 17:04:36 -04002019 if (keys == NULL) {
2020 PyErr_NoMemory();
2021 goto keyfunc_fail;
2022 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002023 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00002024
2025 for (i = 0; i < saved_ob_size ; i++) {
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01002026 keys[i] = PyObject_CallFunctionObjArgs(keyfunc, saved_ob_item[i],
2027 NULL);
Daniel Stutzbach98338222010-12-02 21:55:33 +00002028 if (keys[i] == NULL) {
2029 for (i=i-1 ; i>=0 ; i--)
2030 Py_DECREF(keys[i]);
Benjamin Peterson4a42cd42014-03-15 12:21:28 -05002031 if (saved_ob_size >= MERGESTATE_TEMP_SIZE/2)
Daniel Stutzbach8eda5f72011-03-02 23:37:50 +00002032 PyMem_FREE(keys);
Daniel Stutzbach98338222010-12-02 21:55:33 +00002033 goto keyfunc_fail;
2034 }
2035 }
2036
2037 lo.keys = keys;
2038 lo.values = saved_ob_item;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002039 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002040
Daniel Stutzbach98338222010-12-02 21:55:33 +00002041 merge_init(&ms, saved_ob_size, keys != NULL);
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002043 nremaining = saved_ob_size;
2044 if (nremaining < 2)
2045 goto succeed;
Tim Peters330f9e92002-07-19 07:05:44 +00002046
Benjamin Peterson05380642010-08-23 19:35:39 +00002047 /* Reverse sort stability achieved by initially reversing the list,
2048 applying a stable forward sort, then reversing the final result. */
Daniel Stutzbach98338222010-12-02 21:55:33 +00002049 if (reverse) {
2050 if (keys != NULL)
2051 reverse_slice(&keys[0], &keys[saved_ob_size]);
2052 reverse_slice(&saved_ob_item[0], &saved_ob_item[saved_ob_size]);
2053 }
Benjamin Peterson05380642010-08-23 19:35:39 +00002054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002055 /* March over the array once, left to right, finding natural runs,
2056 * and extending short natural runs to minrun elements.
2057 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002058 minrun = merge_compute_minrun(nremaining);
2059 do {
2060 int descending;
2061 Py_ssize_t n;
Tim Peters330f9e92002-07-19 07:05:44 +00002062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002063 /* Identify next run. */
Daniel Stutzbach98338222010-12-02 21:55:33 +00002064 n = count_run(lo.keys, lo.keys + nremaining, &descending);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002065 if (n < 0)
2066 goto fail;
2067 if (descending)
Daniel Stutzbach98338222010-12-02 21:55:33 +00002068 reverse_sortslice(&lo, n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002069 /* If short, extend to min(minrun, nremaining). */
2070 if (n < minrun) {
2071 const Py_ssize_t force = nremaining <= minrun ?
2072 nremaining : minrun;
Daniel Stutzbach98338222010-12-02 21:55:33 +00002073 if (binarysort(lo, lo.keys + force, lo.keys + n) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002074 goto fail;
2075 n = force;
2076 }
2077 /* Push run onto pending-runs stack, and maybe merge. */
2078 assert(ms.n < MAX_MERGE_PENDING);
2079 ms.pending[ms.n].base = lo;
2080 ms.pending[ms.n].len = n;
2081 ++ms.n;
2082 if (merge_collapse(&ms) < 0)
2083 goto fail;
2084 /* Advance to find next run. */
Daniel Stutzbach98338222010-12-02 21:55:33 +00002085 sortslice_advance(&lo, n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002086 nremaining -= n;
2087 } while (nremaining);
Tim Peters330f9e92002-07-19 07:05:44 +00002088
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002089 if (merge_force_collapse(&ms) < 0)
2090 goto fail;
2091 assert(ms.n == 1);
Daniel Stutzbach98338222010-12-02 21:55:33 +00002092 assert(keys == NULL
2093 ? ms.pending[0].base.keys == saved_ob_item
2094 : ms.pending[0].base.keys == &keys[0]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002095 assert(ms.pending[0].len == saved_ob_size);
Daniel Stutzbach98338222010-12-02 21:55:33 +00002096 lo = ms.pending[0].base;
Tim Petersa64dc242002-08-01 02:13:36 +00002097
2098succeed:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002099 result = Py_None;
Tim Peters330f9e92002-07-19 07:05:44 +00002100fail:
Daniel Stutzbach98338222010-12-02 21:55:33 +00002101 if (keys != NULL) {
2102 for (i = 0; i < saved_ob_size; i++)
2103 Py_DECREF(keys[i]);
Benjamin Petersonef87f8c2014-03-14 21:54:31 -05002104 if (saved_ob_size >= MERGESTATE_TEMP_SIZE/2)
Daniel Stutzbach98338222010-12-02 21:55:33 +00002105 PyMem_FREE(keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002106 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002107
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002108 if (self->allocated != -1 && result != NULL) {
2109 /* The user mucked with the list during the sort,
2110 * and we don't already have another error to report.
2111 */
2112 PyErr_SetString(PyExc_ValueError, "list modified during sort");
2113 result = NULL;
2114 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002116 if (reverse && saved_ob_size > 1)
2117 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002118
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002119 merge_freemem(&ms);
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002120
Daniel Stutzbach98338222010-12-02 21:55:33 +00002121keyfunc_fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002122 final_ob_item = self->ob_item;
2123 i = Py_SIZE(self);
2124 Py_SIZE(self) = saved_ob_size;
2125 self->ob_item = saved_ob_item;
2126 self->allocated = saved_allocated;
2127 if (final_ob_item != NULL) {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002128 /* we cannot use _list_clear() for this because it does not
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002129 guarantee that the list is really empty when it returns */
2130 while (--i >= 0) {
2131 Py_XDECREF(final_ob_item[i]);
2132 }
2133 PyMem_FREE(final_ob_item);
2134 }
2135 Py_XINCREF(result);
2136 return result;
Guido van Rossum3f236de1996-12-10 23:55:39 +00002137}
Tim Peters330f9e92002-07-19 07:05:44 +00002138#undef IFLT
Tim Peters66860f62002-08-04 17:47:26 +00002139#undef ISLT
Tim Peters330f9e92002-07-19 07:05:44 +00002140
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002141int
Fred Drakea2f55112000-07-09 15:16:51 +00002142PyList_Sort(PyObject *v)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002143{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002144 if (v == NULL || !PyList_Check(v)) {
2145 PyErr_BadInternalCall();
2146 return -1;
2147 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002148 v = list_sort_impl((PyListObject *)v, NULL, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002149 if (v == NULL)
2150 return -1;
2151 Py_DECREF(v);
2152 return 0;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002153}
2154
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002155/*[clinic input]
2156list.reverse
2157
2158Reverse *IN PLACE*.
2159[clinic start generated code]*/
2160
Guido van Rossumb86c5492001-02-12 22:06:02 +00002161static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002162list_reverse_impl(PyListObject *self)
2163/*[clinic end generated code: output=482544fc451abea9 input=eefd4c3ae1bc9887]*/
Guido van Rossumb86c5492001-02-12 22:06:02 +00002164{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002165 if (Py_SIZE(self) > 1)
2166 reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
2167 Py_RETURN_NONE;
Guido van Rossumed98d481991-03-06 13:07:53 +00002168}
2169
Guido van Rossum84c76f51990-10-30 13:32:20 +00002170int
Fred Drakea2f55112000-07-09 15:16:51 +00002171PyList_Reverse(PyObject *v)
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002172{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002173 PyListObject *self = (PyListObject *)v;
Tim Peters6063e262002-08-08 01:06:39 +00002174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002175 if (v == NULL || !PyList_Check(v)) {
2176 PyErr_BadInternalCall();
2177 return -1;
2178 }
2179 if (Py_SIZE(self) > 1)
2180 reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
2181 return 0;
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002182}
2183
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002184PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00002185PyList_AsTuple(PyObject *v)
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002186{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002187 PyObject *w;
2188 PyObject **p, **q;
2189 Py_ssize_t n;
2190 if (v == NULL || !PyList_Check(v)) {
2191 PyErr_BadInternalCall();
2192 return NULL;
2193 }
2194 n = Py_SIZE(v);
2195 w = PyTuple_New(n);
2196 if (w == NULL)
2197 return NULL;
2198 p = ((PyTupleObject *)w)->ob_item;
2199 q = ((PyListObject *)v)->ob_item;
2200 while (--n >= 0) {
2201 Py_INCREF(*q);
2202 *p = *q;
2203 p++;
2204 q++;
2205 }
2206 return w;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002207}
2208
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002209/*[clinic input]
2210list.index
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002211
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002212 value: object
2213 start: object(converter="_PyEval_SliceIndex", type="Py_ssize_t") = 0
2214 stop: object(converter="_PyEval_SliceIndex", type="Py_ssize_t", c_default="PY_SSIZE_T_MAX") = sys.maxsize
2215 /
2216
2217Return first index of value.
2218
2219Raises ValueError if the value is not present.
2220[clinic start generated code]*/
2221
2222static PyObject *
2223list_index_impl(PyListObject *self, PyObject *value, Py_ssize_t start,
2224 Py_ssize_t stop)
2225/*[clinic end generated code: output=ec51b88787e4e481 input=70b7247e398a6999]*/
2226{
2227 Py_ssize_t i;
2228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002229 if (start < 0) {
2230 start += Py_SIZE(self);
2231 if (start < 0)
2232 start = 0;
2233 }
2234 if (stop < 0) {
2235 stop += Py_SIZE(self);
2236 if (stop < 0)
2237 stop = 0;
2238 }
2239 for (i = start; i < stop && i < Py_SIZE(self); i++) {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002240 int cmp = PyObject_RichCompareBool(self->ob_item[i], value, Py_EQ);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002241 if (cmp > 0)
2242 return PyLong_FromSsize_t(i);
2243 else if (cmp < 0)
2244 return NULL;
2245 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002246 PyErr_Format(PyExc_ValueError, "%R is not in list", value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002247 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002248}
2249
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002250/*[clinic input]
2251list.count
2252
2253 value: object
2254 /
2255
2256Return number of occurrences of value.
2257[clinic start generated code]*/
2258
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002259static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002260list_count(PyListObject *self, PyObject *value)
2261/*[clinic end generated code: output=b1f5d284205ae714 input=3bdc3a5e6f749565]*/
Guido van Rossume6f7d181991-10-20 20:20:40 +00002262{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002263 Py_ssize_t count = 0;
2264 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002265
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002266 for (i = 0; i < Py_SIZE(self); i++) {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002267 int cmp = PyObject_RichCompareBool(self->ob_item[i], value, Py_EQ);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002268 if (cmp > 0)
2269 count++;
2270 else if (cmp < 0)
2271 return NULL;
2272 }
2273 return PyLong_FromSsize_t(count);
Guido van Rossume6f7d181991-10-20 20:20:40 +00002274}
2275
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002276/*[clinic input]
2277list.remove
2278
2279 value: object
2280 /
2281
2282Remove first occurrence of value.
2283
2284Raises ValueError if the value is not present.
2285[clinic start generated code]*/
2286
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002287static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002288list_remove(PyListObject *self, PyObject *value)
2289/*[clinic end generated code: output=f087e1951a5e30d1 input=2dc2ba5bb2fb1f82]*/
Guido van Rossumed98d481991-03-06 13:07:53 +00002290{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002291 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002293 for (i = 0; i < Py_SIZE(self); i++) {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002294 int cmp = PyObject_RichCompareBool(self->ob_item[i], value, Py_EQ);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002295 if (cmp > 0) {
2296 if (list_ass_slice(self, i, i+1,
2297 (PyObject *)NULL) == 0)
2298 Py_RETURN_NONE;
2299 return NULL;
2300 }
2301 else if (cmp < 0)
2302 return NULL;
2303 }
2304 PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
2305 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002306}
2307
Jeremy Hylton8caad492000-06-23 14:18:11 +00002308static int
2309list_traverse(PyListObject *o, visitproc visit, void *arg)
2310{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002311 Py_ssize_t i;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002313 for (i = Py_SIZE(o); --i >= 0; )
2314 Py_VISIT(o->ob_item[i]);
2315 return 0;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002316}
2317
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002318static PyObject *
2319list_richcompare(PyObject *v, PyObject *w, int op)
2320{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002321 PyListObject *vl, *wl;
2322 Py_ssize_t i;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002323
Brian Curtindfc80e32011-08-10 20:28:54 -05002324 if (!PyList_Check(v) || !PyList_Check(w))
2325 Py_RETURN_NOTIMPLEMENTED;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002327 vl = (PyListObject *)v;
2328 wl = (PyListObject *)w;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002330 if (Py_SIZE(vl) != Py_SIZE(wl) && (op == Py_EQ || op == Py_NE)) {
2331 /* Shortcut: if the lengths differ, the lists differ */
2332 PyObject *res;
2333 if (op == Py_EQ)
2334 res = Py_False;
2335 else
2336 res = Py_True;
2337 Py_INCREF(res);
2338 return res;
2339 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002341 /* Search for the first index where items are different */
2342 for (i = 0; i < Py_SIZE(vl) && i < Py_SIZE(wl); i++) {
2343 int k = PyObject_RichCompareBool(vl->ob_item[i],
2344 wl->ob_item[i], Py_EQ);
2345 if (k < 0)
2346 return NULL;
2347 if (!k)
2348 break;
2349 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002351 if (i >= Py_SIZE(vl) || i >= Py_SIZE(wl)) {
2352 /* No more items to compare -- compare sizes */
2353 Py_ssize_t vs = Py_SIZE(vl);
2354 Py_ssize_t ws = Py_SIZE(wl);
2355 int cmp;
2356 PyObject *res;
2357 switch (op) {
2358 case Py_LT: cmp = vs < ws; break;
2359 case Py_LE: cmp = vs <= ws; break;
2360 case Py_EQ: cmp = vs == ws; break;
2361 case Py_NE: cmp = vs != ws; break;
2362 case Py_GT: cmp = vs > ws; break;
2363 case Py_GE: cmp = vs >= ws; break;
2364 default: return NULL; /* cannot happen */
2365 }
2366 if (cmp)
2367 res = Py_True;
2368 else
2369 res = Py_False;
2370 Py_INCREF(res);
2371 return res;
2372 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002374 /* We have an item that differs -- shortcuts for EQ/NE */
2375 if (op == Py_EQ) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02002376 Py_RETURN_FALSE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002377 }
2378 if (op == Py_NE) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02002379 Py_RETURN_TRUE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002380 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002382 /* Compare the final item again using the proper operator */
2383 return PyObject_RichCompare(vl->ob_item[i], wl->ob_item[i], op);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002384}
2385
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002386/*[clinic input]
2387list.__init__
2388
2389 iterable: object(c_default="NULL") = ()
2390 /
2391
2392Built-in mutable sequence.
2393
2394If no argument is given, the constructor creates a new empty list.
2395The argument must be an iterable if specified.
2396[clinic start generated code]*/
2397
Tim Peters6d6c1a32001-08-02 04:15:00 +00002398static int
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002399list___init___impl(PyListObject *self, PyObject *iterable)
2400/*[clinic end generated code: output=0f3c21379d01de48 input=b3f3fe7206af8f6b]*/
Tim Peters6d6c1a32001-08-02 04:15:00 +00002401{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002402 /* Verify list invariants established by PyType_GenericAlloc() */
2403 assert(0 <= Py_SIZE(self));
2404 assert(Py_SIZE(self) <= self->allocated || self->allocated == -1);
2405 assert(self->ob_item != NULL ||
2406 self->allocated == 0 || self->allocated == -1);
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002408 /* Empty previous contents */
2409 if (self->ob_item != NULL) {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002410 (void)_list_clear(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002411 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002412 if (iterable != NULL) {
2413 PyObject *rv = list_extend(self, iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002414 if (rv == NULL)
2415 return -1;
2416 Py_DECREF(rv);
2417 }
2418 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002419}
2420
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002421/*[clinic input]
2422list.__sizeof__
2423
2424Return the size of the list in memory, in bytes.
2425[clinic start generated code]*/
2426
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002427static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002428list___sizeof___impl(PyListObject *self)
2429/*[clinic end generated code: output=3417541f95f9a53e input=b8030a5d5ce8a187]*/
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002430{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002431 Py_ssize_t res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002432
Serhiy Storchaka5c4064e2015-12-19 20:05:25 +02002433 res = _PyObject_SIZE(Py_TYPE(self)) + self->allocated * sizeof(void*);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002434 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002435}
2436
Raymond Hettinger1021c442003-11-07 15:38:09 +00002437static PyObject *list_iter(PyObject *seq);
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002438static PyObject *list_subscript(PyListObject*, PyObject*);
2439
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002440static PyMethodDef list_methods[] = {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002441 {"__getitem__", (PyCFunction)list_subscript, METH_O|METH_COEXIST, "x.__getitem__(y) <==> x[y]"},
2442 LIST___REVERSED___METHODDEF
2443 LIST___SIZEOF___METHODDEF
2444 LIST_CLEAR_METHODDEF
2445 LIST_COPY_METHODDEF
2446 LIST_APPEND_METHODDEF
2447 LIST_INSERT_METHODDEF
2448 LIST_EXTEND_METHODDEF
2449 LIST_POP_METHODDEF
2450 LIST_REMOVE_METHODDEF
2451 LIST_INDEX_METHODDEF
2452 LIST_COUNT_METHODDEF
2453 LIST_REVERSE_METHODDEF
2454 LIST_SORT_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002455 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002456};
2457
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002458static PySequenceMethods list_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002459 (lenfunc)list_length, /* sq_length */
2460 (binaryfunc)list_concat, /* sq_concat */
2461 (ssizeargfunc)list_repeat, /* sq_repeat */
2462 (ssizeargfunc)list_item, /* sq_item */
2463 0, /* sq_slice */
2464 (ssizeobjargproc)list_ass_item, /* sq_ass_item */
2465 0, /* sq_ass_slice */
2466 (objobjproc)list_contains, /* sq_contains */
2467 (binaryfunc)list_inplace_concat, /* sq_inplace_concat */
2468 (ssizeargfunc)list_inplace_repeat, /* sq_inplace_repeat */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002469};
2470
Jeremy Hyltona4b4c3b2002-07-13 03:51:17 +00002471static PyObject *
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002472list_subscript(PyListObject* self, PyObject* item)
2473{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002474 if (PyIndex_Check(item)) {
2475 Py_ssize_t i;
2476 i = PyNumber_AsSsize_t(item, PyExc_IndexError);
2477 if (i == -1 && PyErr_Occurred())
2478 return NULL;
2479 if (i < 0)
2480 i += PyList_GET_SIZE(self);
2481 return list_item(self, i);
2482 }
2483 else if (PySlice_Check(item)) {
2484 Py_ssize_t start, stop, step, slicelength, cur, i;
2485 PyObject* result;
2486 PyObject* it;
2487 PyObject **src, **dest;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002488
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002489 if (PySlice_GetIndicesEx(item, Py_SIZE(self),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002490 &start, &stop, &step, &slicelength) < 0) {
2491 return NULL;
2492 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002494 if (slicelength <= 0) {
2495 return PyList_New(0);
2496 }
2497 else if (step == 1) {
2498 return list_slice(self, start, stop);
2499 }
2500 else {
2501 result = PyList_New(slicelength);
2502 if (!result) return NULL;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002504 src = self->ob_item;
2505 dest = ((PyListObject *)result)->ob_item;
2506 for (cur = start, i = 0; i < slicelength;
Mark Dickinsonc7d93b72011-09-25 15:34:32 +01002507 cur += (size_t)step, i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002508 it = src[cur];
2509 Py_INCREF(it);
2510 dest[i] = it;
2511 }
Tim Peters3b01a122002-07-19 02:35:45 +00002512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002513 return result;
2514 }
2515 }
2516 else {
2517 PyErr_Format(PyExc_TypeError,
Terry Jan Reedyffff1442014-08-02 01:30:37 -04002518 "list indices must be integers or slices, not %.200s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002519 item->ob_type->tp_name);
2520 return NULL;
2521 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002522}
2523
Tim Peters3b01a122002-07-19 02:35:45 +00002524static int
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002525list_ass_subscript(PyListObject* self, PyObject* item, PyObject* value)
2526{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002527 if (PyIndex_Check(item)) {
2528 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
2529 if (i == -1 && PyErr_Occurred())
2530 return -1;
2531 if (i < 0)
2532 i += PyList_GET_SIZE(self);
2533 return list_ass_item(self, i, value);
2534 }
2535 else if (PySlice_Check(item)) {
2536 Py_ssize_t start, stop, step, slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002537
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002538 if (PySlice_GetIndicesEx(item, Py_SIZE(self),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002539 &start, &stop, &step, &slicelength) < 0) {
2540 return -1;
2541 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002542
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002543 if (step == 1)
2544 return list_ass_slice(self, start, stop, value);
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002546 /* Make sure s[5:2] = [..] inserts at the right place:
2547 before 5, not before 2. */
2548 if ((step < 0 && start < stop) ||
2549 (step > 0 && start > stop))
2550 stop = start;
Thomas Woutersed03b412007-08-28 21:37:11 +00002551
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002552 if (value == NULL) {
2553 /* delete slice */
2554 PyObject **garbage;
2555 size_t cur;
2556 Py_ssize_t i;
Victor Stinner35f28032013-11-21 12:16:35 +01002557 int res;
Tim Peters3b01a122002-07-19 02:35:45 +00002558
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002559 if (slicelength <= 0)
2560 return 0;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002562 if (step < 0) {
2563 stop = start + 1;
2564 start = stop + step*(slicelength - 1) - 1;
2565 step = -step;
2566 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002568 garbage = (PyObject**)
2569 PyMem_MALLOC(slicelength*sizeof(PyObject*));
2570 if (!garbage) {
2571 PyErr_NoMemory();
2572 return -1;
2573 }
Tim Peters3b01a122002-07-19 02:35:45 +00002574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002575 /* drawing pictures might help understand these for
2576 loops. Basically, we memmove the parts of the
2577 list that are *not* part of the slice: step-1
2578 items for each item that is part of the slice,
2579 and then tail end of the list that was not
2580 covered by the slice */
2581 for (cur = start, i = 0;
2582 cur < (size_t)stop;
2583 cur += step, i++) {
2584 Py_ssize_t lim = step - 1;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002586 garbage[i] = PyList_GET_ITEM(self, cur);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002588 if (cur + step >= (size_t)Py_SIZE(self)) {
2589 lim = Py_SIZE(self) - cur - 1;
2590 }
Michael W. Hudson56796f62002-07-29 14:35:04 +00002591
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002592 memmove(self->ob_item + cur - i,
2593 self->ob_item + cur + 1,
2594 lim * sizeof(PyObject *));
2595 }
Mark Dickinsonc7d93b72011-09-25 15:34:32 +01002596 cur = start + (size_t)slicelength * step;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002597 if (cur < (size_t)Py_SIZE(self)) {
2598 memmove(self->ob_item + cur - slicelength,
2599 self->ob_item + cur,
2600 (Py_SIZE(self) - cur) *
2601 sizeof(PyObject *));
2602 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002603
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002604 Py_SIZE(self) -= slicelength;
Victor Stinner35f28032013-11-21 12:16:35 +01002605 res = list_resize(self, Py_SIZE(self));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002607 for (i = 0; i < slicelength; i++) {
2608 Py_DECREF(garbage[i]);
2609 }
2610 PyMem_FREE(garbage);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002611
Victor Stinner35f28032013-11-21 12:16:35 +01002612 return res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002613 }
2614 else {
2615 /* assign slice */
2616 PyObject *ins, *seq;
2617 PyObject **garbage, **seqitems, **selfitems;
2618 Py_ssize_t cur, i;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002620 /* protect against a[::-1] = a */
2621 if (self == (PyListObject*)value) {
2622 seq = list_slice((PyListObject*)value, 0,
2623 PyList_GET_SIZE(value));
2624 }
2625 else {
2626 seq = PySequence_Fast(value,
2627 "must assign iterable "
2628 "to extended slice");
2629 }
2630 if (!seq)
2631 return -1;
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002632
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002633 if (PySequence_Fast_GET_SIZE(seq) != slicelength) {
2634 PyErr_Format(PyExc_ValueError,
2635 "attempt to assign sequence of "
2636 "size %zd to extended slice of "
2637 "size %zd",
2638 PySequence_Fast_GET_SIZE(seq),
2639 slicelength);
2640 Py_DECREF(seq);
2641 return -1;
2642 }
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002643
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002644 if (!slicelength) {
2645 Py_DECREF(seq);
2646 return 0;
2647 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002649 garbage = (PyObject**)
2650 PyMem_MALLOC(slicelength*sizeof(PyObject*));
2651 if (!garbage) {
2652 Py_DECREF(seq);
2653 PyErr_NoMemory();
2654 return -1;
2655 }
Tim Peters3b01a122002-07-19 02:35:45 +00002656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002657 selfitems = self->ob_item;
2658 seqitems = PySequence_Fast_ITEMS(seq);
2659 for (cur = start, i = 0; i < slicelength;
Mark Dickinsonc7d93b72011-09-25 15:34:32 +01002660 cur += (size_t)step, i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002661 garbage[i] = selfitems[cur];
2662 ins = seqitems[i];
2663 Py_INCREF(ins);
2664 selfitems[cur] = ins;
2665 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002666
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002667 for (i = 0; i < slicelength; i++) {
2668 Py_DECREF(garbage[i]);
2669 }
Tim Peters3b01a122002-07-19 02:35:45 +00002670
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002671 PyMem_FREE(garbage);
2672 Py_DECREF(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002673
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002674 return 0;
2675 }
2676 }
2677 else {
2678 PyErr_Format(PyExc_TypeError,
Terry Jan Reedyffff1442014-08-02 01:30:37 -04002679 "list indices must be integers or slices, not %.200s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002680 item->ob_type->tp_name);
2681 return -1;
2682 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002683}
2684
2685static PyMappingMethods list_as_mapping = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002686 (lenfunc)list_length,
2687 (binaryfunc)list_subscript,
2688 (objobjargproc)list_ass_subscript
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002689};
2690
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002691PyTypeObject PyList_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002692 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2693 "list",
2694 sizeof(PyListObject),
2695 0,
2696 (destructor)list_dealloc, /* tp_dealloc */
2697 0, /* tp_print */
2698 0, /* tp_getattr */
2699 0, /* tp_setattr */
2700 0, /* tp_reserved */
2701 (reprfunc)list_repr, /* tp_repr */
2702 0, /* tp_as_number */
2703 &list_as_sequence, /* tp_as_sequence */
2704 &list_as_mapping, /* tp_as_mapping */
Georg Brandl00da4e02010-10-18 07:32:48 +00002705 PyObject_HashNotImplemented, /* tp_hash */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002706 0, /* tp_call */
2707 0, /* tp_str */
2708 PyObject_GenericGetAttr, /* tp_getattro */
2709 0, /* tp_setattro */
2710 0, /* tp_as_buffer */
2711 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002712 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LIST_SUBCLASS, /* tp_flags */
2713 list___init____doc__, /* tp_doc */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002714 (traverseproc)list_traverse, /* tp_traverse */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002715 (inquiry)_list_clear, /* tp_clear */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002716 list_richcompare, /* tp_richcompare */
2717 0, /* tp_weaklistoffset */
2718 list_iter, /* tp_iter */
2719 0, /* tp_iternext */
2720 list_methods, /* tp_methods */
2721 0, /* tp_members */
2722 0, /* tp_getset */
2723 0, /* tp_base */
2724 0, /* tp_dict */
2725 0, /* tp_descr_get */
2726 0, /* tp_descr_set */
2727 0, /* tp_dictoffset */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002728 (initproc)list___init__, /* tp_init */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002729 PyType_GenericAlloc, /* tp_alloc */
2730 PyType_GenericNew, /* tp_new */
2731 PyObject_GC_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002732};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002733
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002734/*********************** List Iterator **************************/
2735
2736typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002737 PyObject_HEAD
Victor Stinner7660b882013-06-24 23:59:24 +02002738 Py_ssize_t it_index;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002739 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002740} listiterobject;
2741
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002742static void listiter_dealloc(listiterobject *);
2743static int listiter_traverse(listiterobject *, visitproc, void *);
2744static PyObject *listiter_next(listiterobject *);
2745static PyObject *listiter_len(listiterobject *);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002746static PyObject *listiter_reduce_general(void *_it, int forward);
2747static PyObject *listiter_reduce(listiterobject *);
2748static PyObject *listiter_setstate(listiterobject *, PyObject *state);
Raymond Hettinger435bf582004-03-18 22:43:10 +00002749
Armin Rigof5b3e362006-02-11 21:32:43 +00002750PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002751PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
2752PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002753
2754static PyMethodDef listiter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002755 {"__length_hint__", (PyCFunction)listiter_len, METH_NOARGS, length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002756 {"__reduce__", (PyCFunction)listiter_reduce, METH_NOARGS, reduce_doc},
2757 {"__setstate__", (PyCFunction)listiter_setstate, METH_O, setstate_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002758 {NULL, NULL} /* sentinel */
Raymond Hettinger435bf582004-03-18 22:43:10 +00002759};
2760
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002761PyTypeObject PyListIter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002762 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2763 "list_iterator", /* tp_name */
2764 sizeof(listiterobject), /* tp_basicsize */
2765 0, /* tp_itemsize */
2766 /* methods */
2767 (destructor)listiter_dealloc, /* tp_dealloc */
2768 0, /* tp_print */
2769 0, /* tp_getattr */
2770 0, /* tp_setattr */
2771 0, /* tp_reserved */
2772 0, /* tp_repr */
2773 0, /* tp_as_number */
2774 0, /* tp_as_sequence */
2775 0, /* tp_as_mapping */
2776 0, /* tp_hash */
2777 0, /* tp_call */
2778 0, /* tp_str */
2779 PyObject_GenericGetAttr, /* tp_getattro */
2780 0, /* tp_setattro */
2781 0, /* tp_as_buffer */
2782 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2783 0, /* tp_doc */
2784 (traverseproc)listiter_traverse, /* tp_traverse */
2785 0, /* tp_clear */
2786 0, /* tp_richcompare */
2787 0, /* tp_weaklistoffset */
2788 PyObject_SelfIter, /* tp_iter */
2789 (iternextfunc)listiter_next, /* tp_iternext */
2790 listiter_methods, /* tp_methods */
2791 0, /* tp_members */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002792};
Raymond Hettinger1021c442003-11-07 15:38:09 +00002793
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002794
2795static PyObject *
2796list_iter(PyObject *seq)
2797{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002798 listiterobject *it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002799
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002800 if (!PyList_Check(seq)) {
2801 PyErr_BadInternalCall();
2802 return NULL;
2803 }
2804 it = PyObject_GC_New(listiterobject, &PyListIter_Type);
2805 if (it == NULL)
2806 return NULL;
2807 it->it_index = 0;
2808 Py_INCREF(seq);
2809 it->it_seq = (PyListObject *)seq;
2810 _PyObject_GC_TRACK(it);
2811 return (PyObject *)it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002812}
2813
2814static void
2815listiter_dealloc(listiterobject *it)
2816{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002817 _PyObject_GC_UNTRACK(it);
2818 Py_XDECREF(it->it_seq);
2819 PyObject_GC_Del(it);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002820}
2821
2822static int
2823listiter_traverse(listiterobject *it, visitproc visit, void *arg)
2824{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002825 Py_VISIT(it->it_seq);
2826 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002827}
2828
2829static PyObject *
2830listiter_next(listiterobject *it)
2831{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002832 PyListObject *seq;
2833 PyObject *item;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002834
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002835 assert(it != NULL);
2836 seq = it->it_seq;
2837 if (seq == NULL)
2838 return NULL;
2839 assert(PyList_Check(seq));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002840
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002841 if (it->it_index < PyList_GET_SIZE(seq)) {
2842 item = PyList_GET_ITEM(seq, it->it_index);
2843 ++it->it_index;
2844 Py_INCREF(item);
2845 return item;
2846 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002847
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002848 it->it_seq = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03002849 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002850 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002851}
2852
2853static PyObject *
2854listiter_len(listiterobject *it)
2855{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002856 Py_ssize_t len;
2857 if (it->it_seq) {
2858 len = PyList_GET_SIZE(it->it_seq) - it->it_index;
2859 if (len >= 0)
2860 return PyLong_FromSsize_t(len);
2861 }
2862 return PyLong_FromLong(0);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002863}
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002864
2865static PyObject *
2866listiter_reduce(listiterobject *it)
2867{
2868 return listiter_reduce_general(it, 1);
2869}
2870
2871static PyObject *
2872listiter_setstate(listiterobject *it, PyObject *state)
2873{
Victor Stinner7660b882013-06-24 23:59:24 +02002874 Py_ssize_t index = PyLong_AsSsize_t(state);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002875 if (index == -1 && PyErr_Occurred())
2876 return NULL;
2877 if (it->it_seq != NULL) {
2878 if (index < 0)
2879 index = 0;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +00002880 else if (index > PyList_GET_SIZE(it->it_seq))
2881 index = PyList_GET_SIZE(it->it_seq); /* iterator exhausted */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002882 it->it_index = index;
2883 }
2884 Py_RETURN_NONE;
2885}
2886
Raymond Hettinger1021c442003-11-07 15:38:09 +00002887/*********************** List Reverse Iterator **************************/
2888
2889typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002890 PyObject_HEAD
2891 Py_ssize_t it_index;
2892 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger1021c442003-11-07 15:38:09 +00002893} listreviterobject;
2894
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002895static void listreviter_dealloc(listreviterobject *);
2896static int listreviter_traverse(listreviterobject *, visitproc, void *);
2897static PyObject *listreviter_next(listreviterobject *);
Raymond Hettingerf5b64112008-12-02 21:33:45 +00002898static PyObject *listreviter_len(listreviterobject *);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002899static PyObject *listreviter_reduce(listreviterobject *);
2900static PyObject *listreviter_setstate(listreviterobject *, PyObject *);
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002901
Raymond Hettingerf5b64112008-12-02 21:33:45 +00002902static PyMethodDef listreviter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002903 {"__length_hint__", (PyCFunction)listreviter_len, METH_NOARGS, length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002904 {"__reduce__", (PyCFunction)listreviter_reduce, METH_NOARGS, reduce_doc},
2905 {"__setstate__", (PyCFunction)listreviter_setstate, METH_O, setstate_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002906 {NULL, NULL} /* sentinel */
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002907};
2908
Raymond Hettinger1021c442003-11-07 15:38:09 +00002909PyTypeObject PyListRevIter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002910 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2911 "list_reverseiterator", /* tp_name */
2912 sizeof(listreviterobject), /* tp_basicsize */
2913 0, /* tp_itemsize */
2914 /* methods */
2915 (destructor)listreviter_dealloc, /* tp_dealloc */
2916 0, /* tp_print */
2917 0, /* tp_getattr */
2918 0, /* tp_setattr */
2919 0, /* tp_reserved */
2920 0, /* tp_repr */
2921 0, /* tp_as_number */
2922 0, /* tp_as_sequence */
2923 0, /* tp_as_mapping */
2924 0, /* tp_hash */
2925 0, /* tp_call */
2926 0, /* tp_str */
2927 PyObject_GenericGetAttr, /* tp_getattro */
2928 0, /* tp_setattro */
2929 0, /* tp_as_buffer */
2930 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2931 0, /* tp_doc */
2932 (traverseproc)listreviter_traverse, /* tp_traverse */
2933 0, /* tp_clear */
2934 0, /* tp_richcompare */
2935 0, /* tp_weaklistoffset */
2936 PyObject_SelfIter, /* tp_iter */
2937 (iternextfunc)listreviter_next, /* tp_iternext */
2938 listreviter_methods, /* tp_methods */
2939 0,
Raymond Hettinger1021c442003-11-07 15:38:09 +00002940};
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002941
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002942/*[clinic input]
2943list.__reversed__
2944
2945Return a reverse iterator over the list.
2946[clinic start generated code]*/
2947
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002948static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002949list___reversed___impl(PyListObject *self)
2950/*[clinic end generated code: output=b166f073208c888c input=eadb6e17f8a6a280]*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002951{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002952 listreviterobject *it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002953
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002954 it = PyObject_GC_New(listreviterobject, &PyListRevIter_Type);
2955 if (it == NULL)
2956 return NULL;
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002957 assert(PyList_Check(self));
2958 it->it_index = PyList_GET_SIZE(self) - 1;
2959 Py_INCREF(self);
2960 it->it_seq = self;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002961 PyObject_GC_Track(it);
2962 return (PyObject *)it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002963}
2964
2965static void
2966listreviter_dealloc(listreviterobject *it)
2967{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002968 PyObject_GC_UnTrack(it);
2969 Py_XDECREF(it->it_seq);
2970 PyObject_GC_Del(it);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002971}
2972
2973static int
2974listreviter_traverse(listreviterobject *it, visitproc visit, void *arg)
2975{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002976 Py_VISIT(it->it_seq);
2977 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002978}
2979
2980static PyObject *
2981listreviter_next(listreviterobject *it)
2982{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002983 PyObject *item;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03002984 Py_ssize_t index;
2985 PyListObject *seq;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002986
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03002987 assert(it != NULL);
2988 seq = it->it_seq;
2989 if (seq == NULL) {
2990 return NULL;
2991 }
2992 assert(PyList_Check(seq));
2993
2994 index = it->it_index;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002995 if (index>=0 && index < PyList_GET_SIZE(seq)) {
2996 item = PyList_GET_ITEM(seq, index);
2997 it->it_index--;
2998 Py_INCREF(item);
2999 return item;
3000 }
3001 it->it_index = -1;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003002 it->it_seq = NULL;
3003 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003004 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003005}
3006
Raymond Hettingerf5b64112008-12-02 21:33:45 +00003007static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003008listreviter_len(listreviterobject *it)
3009{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003010 Py_ssize_t len = it->it_index + 1;
3011 if (it->it_seq == NULL || PyList_GET_SIZE(it->it_seq) < len)
3012 len = 0;
3013 return PyLong_FromSsize_t(len);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003014}
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003015
3016static PyObject *
3017listreviter_reduce(listreviterobject *it)
3018{
3019 return listiter_reduce_general(it, 0);
3020}
3021
3022static PyObject *
3023listreviter_setstate(listreviterobject *it, PyObject *state)
3024{
3025 Py_ssize_t index = PyLong_AsSsize_t(state);
3026 if (index == -1 && PyErr_Occurred())
3027 return NULL;
3028 if (it->it_seq != NULL) {
3029 if (index < -1)
3030 index = -1;
3031 else if (index > PyList_GET_SIZE(it->it_seq) - 1)
3032 index = PyList_GET_SIZE(it->it_seq) - 1;
3033 it->it_index = index;
3034 }
3035 Py_RETURN_NONE;
3036}
3037
3038/* common pickling support */
3039
3040static PyObject *
3041listiter_reduce_general(void *_it, int forward)
3042{
3043 PyObject *list;
3044
3045 /* the objects are not the same, index is of different types! */
3046 if (forward) {
3047 listiterobject *it = (listiterobject *)_it;
3048 if (it->it_seq)
Victor Stinner7660b882013-06-24 23:59:24 +02003049 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003050 it->it_seq, it->it_index);
3051 } else {
3052 listreviterobject *it = (listreviterobject *)_it;
3053 if (it->it_seq)
Antoine Pitroua7013882012-04-05 00:04:20 +02003054 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("reversed"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003055 it->it_seq, it->it_index);
3056 }
3057 /* empty iterator, create an empty list */
3058 list = PyList_New(0);
3059 if (list == NULL)
3060 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +02003061 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), list);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003062}