blob: 78aa8dea08ac2fbfd90a14c31ef80d8622e1e412 [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"
Eric Snow2ebc5ce2017-09-07 23:51:28 -06004#include "internal/pystate.h"
Antoine Pitrou0197ff92012-03-22 14:38:16 +01005#include "accu.h"
Guido van Rossumc0b618a1997-05-02 03:12:38 +00006
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00007#ifdef STDC_HEADERS
8#include <stddef.h>
9#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000010#include <sys/types.h> /* For size_t */
Guido van Rossum6cd2fe01994-08-29 12:45:32 +000011#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000012
Serhiy Storchakafdd42c42017-03-11 09:19:20 +020013/*[clinic input]
14class list "PyListObject *" "&PyList_Type"
15[clinic start generated code]*/
16/*[clinic end generated code: output=da39a3ee5e6b4b0d input=f9b222678f9f71e0]*/
17
18#include "clinic/listobject.c.h"
19
Tim Peters8d9eb102004-07-31 02:24:20 +000020/* Ensure ob_item has room for at least newsize elements, and set
21 * ob_size to newsize. If newsize > ob_size on entry, the content
22 * of the new slots at exit is undefined heap trash; it's the caller's
Ezio Melotti13925002011-03-16 11:05:33 +020023 * responsibility to overwrite them with sane values.
Tim Peters8d9eb102004-07-31 02:24:20 +000024 * The number of allocated elements may grow, shrink, or stay the same.
25 * Failure is impossible if newsize <= self.allocated on entry, although
26 * that partly relies on an assumption that the system realloc() never
27 * fails when passed a number of bytes <= the number of bytes last
28 * allocated (the C standard doesn't guarantee this, but it's hard to
29 * imagine a realloc implementation where it wouldn't be true).
30 * Note that self->ob_item may change, and even if newsize is less
31 * than ob_size on entry.
32 */
Guido van Rossuma46d51d1995-01-26 22:59:43 +000033static int
Martin v. Löwis18e16552006-02-15 17:27:45 +000034list_resize(PyListObject *self, Py_ssize_t newsize)
Guido van Rossuma46d51d1995-01-26 22:59:43 +000035{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000036 PyObject **items;
Xiang Zhang4cee0492017-02-22 12:32:30 +080037 size_t new_allocated, num_allocated_bytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000038 Py_ssize_t allocated = self->allocated;
Tim Peters65b8b842001-05-26 05:28:40 +000039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000040 /* Bypass realloc() when a previous overallocation is large enough
41 to accommodate the newsize. If the newsize falls lower than half
42 the allocated size, then proceed with the realloc() to shrink the list.
43 */
44 if (allocated >= newsize && newsize >= (allocated >> 1)) {
45 assert(self->ob_item != NULL || newsize == 0);
46 Py_SIZE(self) = newsize;
47 return 0;
48 }
Raymond Hettinger4bb95402004-02-13 11:36:39 +000049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000050 /* This over-allocates proportional to the list size, making room
51 * for additional growth. The over-allocation is mild, but is
52 * enough to give linear-time amortized behavior over a long
53 * sequence of appends() in the presence of a poorly-performing
54 * system realloc().
55 * The growth pattern is: 0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ...
Xiang Zhang4cee0492017-02-22 12:32:30 +080056 * Note: new_allocated won't overflow because the largest possible value
57 * is PY_SSIZE_T_MAX * (9 / 8) + 6 which always fits in a size_t.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000058 */
Xiang Zhang4cee0492017-02-22 12:32:30 +080059 new_allocated = (size_t)newsize + (newsize >> 3) + (newsize < 9 ? 3 : 6);
60 if (new_allocated > (size_t)PY_SSIZE_T_MAX / sizeof(PyObject *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000061 PyErr_NoMemory();
62 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000063 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +000064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000065 if (newsize == 0)
66 new_allocated = 0;
Xiang Zhang4cee0492017-02-22 12:32:30 +080067 num_allocated_bytes = new_allocated * sizeof(PyObject *);
68 items = (PyObject **)PyMem_Realloc(self->ob_item, num_allocated_bytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000069 if (items == NULL) {
70 PyErr_NoMemory();
71 return -1;
72 }
73 self->ob_item = items;
74 Py_SIZE(self) = newsize;
75 self->allocated = new_allocated;
76 return 0;
Raymond Hettinger4bb95402004-02-13 11:36:39 +000077}
Guido van Rossuma46d51d1995-01-26 22:59:43 +000078
Christian Heimes77c02eb2008-02-09 02:18:51 +000079/* Debug statistic to compare allocations with reuse through the free list */
80#undef SHOW_ALLOC_COUNT
81#ifdef SHOW_ALLOC_COUNT
82static size_t count_alloc = 0;
83static size_t count_reuse = 0;
84
85static void
86show_alloc(void)
87{
Victor Stinner25420fe2017-11-20 18:12:22 -080088 PyInterpreterState *interp = PyThreadState_GET()->interp;
Miss Islington (bot)bc2e1102018-02-21 21:44:08 -080089 if (!interp->core_config.show_alloc_count) {
Serhiy Storchaka7e160ce2016-07-03 21:03:53 +030090 return;
Victor Stinner25420fe2017-11-20 18:12:22 -080091 }
Serhiy Storchaka7e160ce2016-07-03 21:03:53 +030092
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000093 fprintf(stderr, "List allocations: %" PY_FORMAT_SIZE_T "d\n",
94 count_alloc);
95 fprintf(stderr, "List reuse through freelist: %" PY_FORMAT_SIZE_T
96 "d\n", count_reuse);
97 fprintf(stderr, "%.2f%% reuse rate\n\n",
98 (100.0*count_reuse/(count_alloc+count_reuse)));
Christian Heimes77c02eb2008-02-09 02:18:51 +000099}
100#endif
101
Raymond Hettinger0468e412004-05-05 05:37:53 +0000102/* Empty list reuse scheme to save calls to malloc and free */
Christian Heimes2202f872008-02-06 14:31:34 +0000103#ifndef PyList_MAXFREELIST
104#define PyList_MAXFREELIST 80
105#endif
106static PyListObject *free_list[PyList_MAXFREELIST];
107static int numfree = 0;
Raymond Hettinger0468e412004-05-05 05:37:53 +0000108
Antoine Pitrou9a812cb2011-11-15 00:00:12 +0100109int
110PyList_ClearFreeList(void)
Raymond Hettingerfb09f0e2004-10-07 03:58:07 +0000111{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000112 PyListObject *op;
Antoine Pitrou9a812cb2011-11-15 00:00:12 +0100113 int ret = numfree;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000114 while (numfree) {
115 op = free_list[--numfree];
116 assert(PyList_CheckExact(op));
117 PyObject_GC_Del(op);
118 }
Antoine Pitrou9a812cb2011-11-15 00:00:12 +0100119 return ret;
120}
121
122void
123PyList_Fini(void)
124{
125 PyList_ClearFreeList();
Raymond Hettingerfb09f0e2004-10-07 03:58:07 +0000126}
127
David Malcolm49526f42012-06-22 14:55:41 -0400128/* Print summary info about the state of the optimized allocator */
129void
130_PyList_DebugMallocStats(FILE *out)
131{
132 _PyDebugAllocatorStats(out,
133 "free PyListObject",
134 numfree, sizeof(PyListObject));
135}
136
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000137PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000138PyList_New(Py_ssize_t size)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000139{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000140 PyListObject *op;
Christian Heimes77c02eb2008-02-09 02:18:51 +0000141#ifdef SHOW_ALLOC_COUNT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000142 static int initialized = 0;
143 if (!initialized) {
144 Py_AtExit(show_alloc);
145 initialized = 1;
146 }
Christian Heimes77c02eb2008-02-09 02:18:51 +0000147#endif
Tim Peters3986d4e2004-07-29 02:28:42 +0000148
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000149 if (size < 0) {
150 PyErr_BadInternalCall();
151 return NULL;
152 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000153 if (numfree) {
154 numfree--;
155 op = free_list[numfree];
156 _Py_NewReference((PyObject *)op);
Christian Heimes77c02eb2008-02-09 02:18:51 +0000157#ifdef SHOW_ALLOC_COUNT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000158 count_reuse++;
Christian Heimes77c02eb2008-02-09 02:18:51 +0000159#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000160 } else {
161 op = PyObject_GC_New(PyListObject, &PyList_Type);
162 if (op == NULL)
163 return NULL;
Christian Heimes77c02eb2008-02-09 02:18:51 +0000164#ifdef SHOW_ALLOC_COUNT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000165 count_alloc++;
Christian Heimes77c02eb2008-02-09 02:18:51 +0000166#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000167 }
168 if (size <= 0)
169 op->ob_item = NULL;
170 else {
Mark Dickinson5d132382016-08-21 08:55:15 +0100171 op->ob_item = (PyObject **) PyMem_Calloc(size, sizeof(PyObject *));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000172 if (op->ob_item == NULL) {
173 Py_DECREF(op);
174 return PyErr_NoMemory();
175 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000176 }
177 Py_SIZE(op) = size;
178 op->allocated = size;
179 _PyObject_GC_TRACK(op);
180 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000181}
182
Martin v. Löwis18e16552006-02-15 17:27:45 +0000183Py_ssize_t
Fred Drakea2f55112000-07-09 15:16:51 +0000184PyList_Size(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000185{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000186 if (!PyList_Check(op)) {
187 PyErr_BadInternalCall();
188 return -1;
189 }
190 else
191 return Py_SIZE(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000192}
193
Raymond Hettingerfdfe6182004-05-05 06:28:16 +0000194static PyObject *indexerr = NULL;
Guido van Rossum929f1b81996-08-09 20:51:27 +0000195
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000196PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000197PyList_GetItem(PyObject *op, Py_ssize_t i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000198{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000199 if (!PyList_Check(op)) {
200 PyErr_BadInternalCall();
201 return NULL;
202 }
203 if (i < 0 || i >= Py_SIZE(op)) {
204 if (indexerr == NULL) {
205 indexerr = PyUnicode_FromString(
206 "list index out of range");
207 if (indexerr == NULL)
208 return NULL;
209 }
210 PyErr_SetObject(PyExc_IndexError, indexerr);
211 return NULL;
212 }
213 return ((PyListObject *)op) -> ob_item[i];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000214}
215
216int
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200217PyList_SetItem(PyObject *op, Py_ssize_t i,
218 PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000219{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200220 PyObject **p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000221 if (!PyList_Check(op)) {
222 Py_XDECREF(newitem);
223 PyErr_BadInternalCall();
224 return -1;
225 }
226 if (i < 0 || i >= Py_SIZE(op)) {
227 Py_XDECREF(newitem);
228 PyErr_SetString(PyExc_IndexError,
229 "list assignment index out of range");
230 return -1;
231 }
232 p = ((PyListObject *)op) -> ob_item + i;
Serhiy Storchakaec397562016-04-06 09:50:03 +0300233 Py_XSETREF(*p, newitem);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000234 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000235}
236
237static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000238ins1(PyListObject *self, Py_ssize_t where, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000239{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000240 Py_ssize_t i, n = Py_SIZE(self);
241 PyObject **items;
242 if (v == NULL) {
243 PyErr_BadInternalCall();
244 return -1;
245 }
246 if (n == PY_SSIZE_T_MAX) {
247 PyErr_SetString(PyExc_OverflowError,
248 "cannot add more objects to list");
249 return -1;
250 }
Tim Petersb38e2b62004-07-29 02:29:26 +0000251
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800252 if (list_resize(self, n+1) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000253 return -1;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000255 if (where < 0) {
256 where += n;
257 if (where < 0)
258 where = 0;
259 }
260 if (where > n)
261 where = n;
262 items = self->ob_item;
263 for (i = n; --i >= where; )
264 items[i+1] = items[i];
265 Py_INCREF(v);
266 items[where] = v;
267 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000268}
269
270int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000271PyList_Insert(PyObject *op, Py_ssize_t where, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000272{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000273 if (!PyList_Check(op)) {
274 PyErr_BadInternalCall();
275 return -1;
276 }
277 return ins1((PyListObject *)op, where, newitem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000278}
279
Raymond Hettinger40a03822004-04-12 13:05:09 +0000280static int
281app1(PyListObject *self, PyObject *v)
282{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000283 Py_ssize_t n = PyList_GET_SIZE(self);
Raymond Hettinger40a03822004-04-12 13:05:09 +0000284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000285 assert (v != NULL);
286 if (n == PY_SSIZE_T_MAX) {
287 PyErr_SetString(PyExc_OverflowError,
288 "cannot add more objects to list");
289 return -1;
290 }
Raymond Hettinger40a03822004-04-12 13:05:09 +0000291
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800292 if (list_resize(self, n+1) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000293 return -1;
Raymond Hettinger40a03822004-04-12 13:05:09 +0000294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000295 Py_INCREF(v);
296 PyList_SET_ITEM(self, n, v);
297 return 0;
Raymond Hettinger40a03822004-04-12 13:05:09 +0000298}
299
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000300int
Fred Drakea2f55112000-07-09 15:16:51 +0000301PyList_Append(PyObject *op, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000302{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000303 if (PyList_Check(op) && (newitem != NULL))
304 return app1((PyListObject *)op, newitem);
305 PyErr_BadInternalCall();
306 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000307}
308
309/* Methods */
310
311static void
Fred Drakea2f55112000-07-09 15:16:51 +0000312list_dealloc(PyListObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000313{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000314 Py_ssize_t i;
315 PyObject_GC_UnTrack(op);
316 Py_TRASHCAN_SAFE_BEGIN(op)
317 if (op->ob_item != NULL) {
318 /* Do it backwards, for Christian Tismer.
319 There's a simple test case where somehow this reduces
320 thrashing when a *very* large list is created and
321 immediately deleted. */
322 i = Py_SIZE(op);
323 while (--i >= 0) {
324 Py_XDECREF(op->ob_item[i]);
325 }
326 PyMem_FREE(op->ob_item);
327 }
328 if (numfree < PyList_MAXFREELIST && PyList_CheckExact(op))
329 free_list[numfree++] = op;
330 else
331 Py_TYPE(op)->tp_free((PyObject *)op);
332 Py_TRASHCAN_SAFE_END(op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000333}
334
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000335static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000336list_repr(PyListObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000337{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000338 Py_ssize_t i;
Victor Stinner5c733472013-11-18 21:11:57 +0100339 PyObject *s;
Victor Stinner5c733472013-11-18 21:11:57 +0100340 _PyUnicodeWriter writer;
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200341
342 if (Py_SIZE(v) == 0) {
343 return PyUnicode_FromString("[]");
344 }
345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000346 i = Py_ReprEnter((PyObject*)v);
347 if (i != 0) {
348 return i > 0 ? PyUnicode_FromString("[...]") : NULL;
349 }
Tim Petersa7259592001-06-16 05:11:17 +0000350
Victor Stinner5c733472013-11-18 21:11:57 +0100351 _PyUnicodeWriter_Init(&writer);
352 writer.overallocate = 1;
Victor Stinnerb8fb1972013-11-18 22:15:44 +0100353 /* "[" + "1" + ", 2" * (len - 1) + "]" */
354 writer.min_length = 1 + 1 + (2 + 1) * (Py_SIZE(v) - 1) + 1;
Tim Petersa7259592001-06-16 05:11:17 +0000355
Victor Stinner5c733472013-11-18 21:11:57 +0100356 if (_PyUnicodeWriter_WriteChar(&writer, '[') < 0)
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200357 goto error;
Tim Petersa7259592001-06-16 05:11:17 +0000358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000359 /* Do repr() on each element. Note that this may mutate the list,
360 so must refetch the list size on each iteration. */
361 for (i = 0; i < Py_SIZE(v); ++i) {
Victor Stinner5c733472013-11-18 21:11:57 +0100362 if (i > 0) {
Victor Stinner4a587072013-11-19 12:54:53 +0100363 if (_PyUnicodeWriter_WriteASCIIString(&writer, ", ", 2) < 0)
Victor Stinner5c733472013-11-18 21:11:57 +0100364 goto error;
365 }
366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000367 s = PyObject_Repr(v->ob_item[i]);
Victor Stinner5c733472013-11-18 21:11:57 +0100368 if (s == NULL)
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200369 goto error;
Victor Stinner5c733472013-11-18 21:11:57 +0100370
371 if (_PyUnicodeWriter_WriteStr(&writer, s) < 0) {
372 Py_DECREF(s);
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200373 goto error;
Victor Stinner5c733472013-11-18 21:11:57 +0100374 }
375 Py_DECREF(s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000376 }
Victor Stinner5c733472013-11-18 21:11:57 +0100377
Victor Stinner4d3f1092013-11-19 12:09:00 +0100378 writer.overallocate = 0;
Victor Stinner5c733472013-11-18 21:11:57 +0100379 if (_PyUnicodeWriter_WriteChar(&writer, ']') < 0)
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200380 goto error;
Tim Petersa7259592001-06-16 05:11:17 +0000381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000382 Py_ReprLeave((PyObject *)v);
Victor Stinner5c733472013-11-18 21:11:57 +0100383 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200384
385error:
Victor Stinner5c733472013-11-18 21:11:57 +0100386 _PyUnicodeWriter_Dealloc(&writer);
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200387 Py_ReprLeave((PyObject *)v);
388 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000389}
390
Martin v. Löwis18e16552006-02-15 17:27:45 +0000391static Py_ssize_t
Fred Drakea2f55112000-07-09 15:16:51 +0000392list_length(PyListObject *a)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000393{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000394 return Py_SIZE(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000395}
396
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000397static int
Fred Drakea2f55112000-07-09 15:16:51 +0000398list_contains(PyListObject *a, PyObject *el)
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000399{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000400 Py_ssize_t i;
401 int cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000403 for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(a); ++i)
404 cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i),
405 Py_EQ);
406 return cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000407}
408
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000409static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000410list_item(PyListObject *a, Py_ssize_t i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000411{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000412 if (i < 0 || i >= Py_SIZE(a)) {
413 if (indexerr == NULL) {
414 indexerr = PyUnicode_FromString(
415 "list index out of range");
416 if (indexerr == NULL)
417 return NULL;
418 }
419 PyErr_SetObject(PyExc_IndexError, indexerr);
420 return NULL;
421 }
422 Py_INCREF(a->ob_item[i]);
423 return a->ob_item[i];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000424}
425
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000426static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000427list_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000428{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000429 PyListObject *np;
430 PyObject **src, **dest;
431 Py_ssize_t i, len;
432 if (ilow < 0)
433 ilow = 0;
434 else if (ilow > Py_SIZE(a))
435 ilow = Py_SIZE(a);
436 if (ihigh < ilow)
437 ihigh = ilow;
438 else if (ihigh > Py_SIZE(a))
439 ihigh = Py_SIZE(a);
440 len = ihigh - ilow;
441 np = (PyListObject *) PyList_New(len);
442 if (np == NULL)
443 return NULL;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000445 src = a->ob_item + ilow;
446 dest = np->ob_item;
447 for (i = 0; i < len; i++) {
448 PyObject *v = src[i];
449 Py_INCREF(v);
450 dest[i] = v;
451 }
452 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000453}
454
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000455PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000456PyList_GetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum234f9421993-06-17 12:35:49 +0000457{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000458 if (!PyList_Check(a)) {
459 PyErr_BadInternalCall();
460 return NULL;
461 }
462 return list_slice((PyListObject *)a, ilow, ihigh);
Guido van Rossum234f9421993-06-17 12:35:49 +0000463}
464
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000465static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000466list_concat(PyListObject *a, PyObject *bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000467{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000468 Py_ssize_t size;
469 Py_ssize_t i;
470 PyObject **src, **dest;
471 PyListObject *np;
472 if (!PyList_Check(bb)) {
473 PyErr_Format(PyExc_TypeError,
474 "can only concatenate list (not \"%.200s\") to list",
475 bb->ob_type->tp_name);
476 return NULL;
477 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000478#define b ((PyListObject *)bb)
Martin Panterb93d8632016-07-25 02:39:20 +0000479 if (Py_SIZE(a) > PY_SSIZE_T_MAX - Py_SIZE(b))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000480 return PyErr_NoMemory();
Martin Panterb93d8632016-07-25 02:39:20 +0000481 size = Py_SIZE(a) + Py_SIZE(b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 np = (PyListObject *) PyList_New(size);
483 if (np == NULL) {
484 return NULL;
485 }
486 src = a->ob_item;
487 dest = np->ob_item;
488 for (i = 0; i < Py_SIZE(a); i++) {
489 PyObject *v = src[i];
490 Py_INCREF(v);
491 dest[i] = v;
492 }
493 src = b->ob_item;
494 dest = np->ob_item + Py_SIZE(a);
495 for (i = 0; i < Py_SIZE(b); i++) {
496 PyObject *v = src[i];
497 Py_INCREF(v);
498 dest[i] = v;
499 }
500 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000501#undef b
502}
503
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000504static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000505list_repeat(PyListObject *a, Py_ssize_t n)
Guido van Rossumed98d481991-03-06 13:07:53 +0000506{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 Py_ssize_t i, j;
508 Py_ssize_t size;
509 PyListObject *np;
510 PyObject **p, **items;
511 PyObject *elem;
512 if (n < 0)
513 n = 0;
Mark Dickinsonc0420fd2011-09-19 19:18:37 +0100514 if (n > 0 && Py_SIZE(a) > PY_SSIZE_T_MAX / n)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000515 return PyErr_NoMemory();
Mark Dickinsonc0420fd2011-09-19 19:18:37 +0100516 size = Py_SIZE(a) * n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 if (size == 0)
518 return PyList_New(0);
519 np = (PyListObject *) PyList_New(size);
520 if (np == NULL)
521 return NULL;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000523 items = np->ob_item;
524 if (Py_SIZE(a) == 1) {
525 elem = a->ob_item[0];
526 for (i = 0; i < n; i++) {
527 items[i] = elem;
528 Py_INCREF(elem);
529 }
530 return (PyObject *) np;
531 }
532 p = np->ob_item;
533 items = a->ob_item;
534 for (i = 0; i < n; i++) {
535 for (j = 0; j < Py_SIZE(a); j++) {
536 *p = items[j];
537 Py_INCREF(*p);
538 p++;
539 }
540 }
541 return (PyObject *) np;
Guido van Rossumed98d481991-03-06 13:07:53 +0000542}
543
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000544static int
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200545_list_clear(PyListObject *a)
Armin Rigo93677f02004-07-29 12:40:23 +0000546{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000547 Py_ssize_t i;
548 PyObject **item = a->ob_item;
549 if (item != NULL) {
550 /* Because XDECREF can recursively invoke operations on
551 this list, we make it empty first. */
552 i = Py_SIZE(a);
553 Py_SIZE(a) = 0;
554 a->ob_item = NULL;
555 a->allocated = 0;
556 while (--i >= 0) {
557 Py_XDECREF(item[i]);
558 }
559 PyMem_FREE(item);
560 }
561 /* Never fails; the return value can be ignored.
562 Note that there is no guarantee that the list is actually empty
563 at this point, because XDECREF may have populated it again! */
564 return 0;
Armin Rigo93677f02004-07-29 12:40:23 +0000565}
566
Tim Peters8fc4a912004-07-31 21:53:19 +0000567/* a[ilow:ihigh] = v if v != NULL.
568 * del a[ilow:ihigh] if v == NULL.
569 *
570 * Special speed gimmick: when v is NULL and ihigh - ilow <= 8, it's
571 * guaranteed the call cannot fail.
572 */
Armin Rigo93677f02004-07-29 12:40:23 +0000573static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000574list_ass_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000575{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000576 /* Because [X]DECREF can recursively invoke list operations on
577 this list, we must postpone all [X]DECREF activity until
578 after the list is back in its canonical shape. Therefore
579 we must allocate an additional array, 'recycle', into which
580 we temporarily copy the items that are deleted from the
581 list. :-( */
582 PyObject *recycle_on_stack[8];
583 PyObject **recycle = recycle_on_stack; /* will allocate more if needed */
584 PyObject **item;
585 PyObject **vitem = NULL;
586 PyObject *v_as_SF = NULL; /* PySequence_Fast(v) */
587 Py_ssize_t n; /* # of elements in replacement list */
588 Py_ssize_t norig; /* # of elements in list getting replaced */
589 Py_ssize_t d; /* Change in size */
590 Py_ssize_t k;
591 size_t s;
592 int result = -1; /* guilty until proved innocent */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000593#define b ((PyListObject *)v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 if (v == NULL)
595 n = 0;
596 else {
597 if (a == b) {
598 /* Special case "a[i:j] = a" -- copy b first */
599 v = list_slice(b, 0, Py_SIZE(b));
600 if (v == NULL)
601 return result;
602 result = list_ass_slice(a, ilow, ihigh, v);
603 Py_DECREF(v);
604 return result;
605 }
606 v_as_SF = PySequence_Fast(v, "can only assign an iterable");
607 if(v_as_SF == NULL)
608 goto Error;
609 n = PySequence_Fast_GET_SIZE(v_as_SF);
610 vitem = PySequence_Fast_ITEMS(v_as_SF);
611 }
612 if (ilow < 0)
613 ilow = 0;
614 else if (ilow > Py_SIZE(a))
615 ilow = Py_SIZE(a);
Tim Peters8d9eb102004-07-31 02:24:20 +0000616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000617 if (ihigh < ilow)
618 ihigh = ilow;
619 else if (ihigh > Py_SIZE(a))
620 ihigh = Py_SIZE(a);
Armin Rigo93677f02004-07-29 12:40:23 +0000621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 norig = ihigh - ilow;
623 assert(norig >= 0);
624 d = n - norig;
625 if (Py_SIZE(a) + d == 0) {
626 Py_XDECREF(v_as_SF);
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200627 return _list_clear(a);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000628 }
629 item = a->ob_item;
630 /* recycle the items that we are about to remove */
631 s = norig * sizeof(PyObject *);
Benjamin Peterson5a7d9232016-09-06 17:58:25 -0700632 /* If norig == 0, item might be NULL, in which case we may not memcpy from it. */
633 if (s) {
634 if (s > sizeof(recycle_on_stack)) {
635 recycle = (PyObject **)PyMem_MALLOC(s);
636 if (recycle == NULL) {
637 PyErr_NoMemory();
638 goto Error;
639 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 }
Benjamin Peterson5a7d9232016-09-06 17:58:25 -0700641 memcpy(recycle, &item[ilow], s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 }
Tim Peters8d9eb102004-07-31 02:24:20 +0000643
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 if (d < 0) { /* Delete -d items */
Victor Stinner2c40f642013-07-19 23:06:21 +0200645 Py_ssize_t tail;
646 tail = (Py_SIZE(a) - ihigh) * sizeof(PyObject *);
647 memmove(&item[ihigh+d], &item[ihigh], tail);
648 if (list_resize(a, Py_SIZE(a) + d) < 0) {
649 memmove(&item[ihigh], &item[ihigh+d], tail);
650 memcpy(&item[ilow], recycle, s);
651 goto Error;
652 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000653 item = a->ob_item;
654 }
655 else if (d > 0) { /* Insert d items */
656 k = Py_SIZE(a);
657 if (list_resize(a, k+d) < 0)
658 goto Error;
659 item = a->ob_item;
660 memmove(&item[ihigh+d], &item[ihigh],
661 (k - ihigh)*sizeof(PyObject *));
662 }
663 for (k = 0; k < n; k++, ilow++) {
664 PyObject *w = vitem[k];
665 Py_XINCREF(w);
666 item[ilow] = w;
667 }
668 for (k = norig - 1; k >= 0; --k)
669 Py_XDECREF(recycle[k]);
670 result = 0;
Tim Peters8d9eb102004-07-31 02:24:20 +0000671 Error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000672 if (recycle != recycle_on_stack)
673 PyMem_FREE(recycle);
674 Py_XDECREF(v_as_SF);
675 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000676#undef b
677}
678
Guido van Rossum234f9421993-06-17 12:35:49 +0000679int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000680PyList_SetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum234f9421993-06-17 12:35:49 +0000681{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000682 if (!PyList_Check(a)) {
683 PyErr_BadInternalCall();
684 return -1;
685 }
686 return list_ass_slice((PyListObject *)a, ilow, ihigh, v);
Guido van Rossum234f9421993-06-17 12:35:49 +0000687}
688
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000689static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000690list_inplace_repeat(PyListObject *self, Py_ssize_t n)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000691{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000692 PyObject **items;
693 Py_ssize_t size, i, j, p;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000694
695
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000696 size = PyList_GET_SIZE(self);
697 if (size == 0 || n == 1) {
698 Py_INCREF(self);
699 return (PyObject *)self;
700 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000701
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000702 if (n < 1) {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200703 (void)_list_clear(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000704 Py_INCREF(self);
705 return (PyObject *)self;
706 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708 if (size > PY_SSIZE_T_MAX / n) {
709 return PyErr_NoMemory();
710 }
Christian Heimesaf98da12008-01-27 15:18:18 +0000711
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800712 if (list_resize(self, size*n) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000713 return NULL;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 p = size;
716 items = self->ob_item;
717 for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */
718 for (j = 0; j < size; j++) {
719 PyObject *o = items[j];
720 Py_INCREF(o);
721 items[p++] = o;
722 }
723 }
724 Py_INCREF(self);
725 return (PyObject *)self;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000726}
727
Guido van Rossum4a450d01991-04-03 19:05:18 +0000728static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000729list_ass_item(PyListObject *a, Py_ssize_t i, PyObject *v)
Guido van Rossum4a450d01991-04-03 19:05:18 +0000730{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000731 if (i < 0 || i >= Py_SIZE(a)) {
732 PyErr_SetString(PyExc_IndexError,
733 "list assignment index out of range");
734 return -1;
735 }
736 if (v == NULL)
737 return list_ass_slice(a, i, i+1, v);
738 Py_INCREF(v);
Serhiy Storchakaf01e4082016-04-10 18:12:01 +0300739 Py_SETREF(a->ob_item[i], v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000740 return 0;
Guido van Rossum4a450d01991-04-03 19:05:18 +0000741}
742
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200743/*[clinic input]
744list.insert
745
746 index: Py_ssize_t
747 object: object
748 /
749
750Insert object before index.
751[clinic start generated code]*/
752
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000753static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200754list_insert_impl(PyListObject *self, Py_ssize_t index, PyObject *object)
755/*[clinic end generated code: output=7f35e32f60c8cb78 input=858514cf894c7eab]*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000756{
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200757 if (ins1(self, index, object) == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 Py_RETURN_NONE;
759 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000760}
761
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200762/*[clinic input]
763list.clear
764
765Remove all items from list.
766[clinic start generated code]*/
767
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000768static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200769list_clear_impl(PyListObject *self)
770/*[clinic end generated code: output=67a1896c01f74362 input=ca3c1646856742f6]*/
Eli Benderskycbbaa962011-02-25 05:47:53 +0000771{
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200772 _list_clear(self);
Eli Benderskycbbaa962011-02-25 05:47:53 +0000773 Py_RETURN_NONE;
774}
775
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200776/*[clinic input]
777list.copy
778
779Return a shallow copy of the list.
780[clinic start generated code]*/
781
Eli Benderskycbbaa962011-02-25 05:47:53 +0000782static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200783list_copy_impl(PyListObject *self)
784/*[clinic end generated code: output=ec6b72d6209d418e input=6453ab159e84771f]*/
Eli Benderskycbbaa962011-02-25 05:47:53 +0000785{
786 return list_slice(self, 0, Py_SIZE(self));
787}
788
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200789/*[clinic input]
790list.append
791
792 object: object
793 /
794
795Append object to the end of the list.
796[clinic start generated code]*/
797
Eli Benderskycbbaa962011-02-25 05:47:53 +0000798static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200799list_append(PyListObject *self, PyObject *object)
800/*[clinic end generated code: output=7c096003a29c0eae input=43a3fe48a7066e91]*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000801{
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200802 if (app1(self, object) == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 Py_RETURN_NONE;
804 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000805}
806
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200807/*[clinic input]
808list.extend
809
810 iterable: object
811 /
812
813Extend list by appending elements from the iterable.
814[clinic start generated code]*/
815
Barry Warsawdedf6d61998-10-09 16:37:25 +0000816static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200817list_extend(PyListObject *self, PyObject *iterable)
818/*[clinic end generated code: output=630fb3bca0c8e789 input=9ec5ba3a81be3a4d]*/
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000819{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000820 PyObject *it; /* iter(v) */
821 Py_ssize_t m; /* size of self */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200822 Py_ssize_t n; /* guess for size of iterable */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 Py_ssize_t mn; /* m + n */
824 Py_ssize_t i;
825 PyObject *(*iternext)(PyObject *);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000826
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000827 /* Special cases:
828 1) lists and tuples which can use PySequence_Fast ops
829 2) extending self to self requires making a copy first
830 */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200831 if (PyList_CheckExact(iterable) || PyTuple_CheckExact(iterable) ||
832 (PyObject *)self == iterable) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000833 PyObject **src, **dest;
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200834 iterable = PySequence_Fast(iterable, "argument must be iterable");
835 if (!iterable)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 return NULL;
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200837 n = PySequence_Fast_GET_SIZE(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 if (n == 0) {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200839 /* short circuit when iterable is empty */
840 Py_DECREF(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000841 Py_RETURN_NONE;
842 }
843 m = Py_SIZE(self);
Martin Panter94b39ce2017-01-14 06:30:37 +0000844 /* It should not be possible to allocate a list large enough to cause
845 an overflow on any relevant platform */
846 assert(m < PY_SSIZE_T_MAX - n);
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800847 if (list_resize(self, m + n) < 0) {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200848 Py_DECREF(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 return NULL;
850 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200851 /* note that we may still have self == iterable here for the
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000852 * situation a.extend(a), but the following code works
853 * in that case too. Just make sure to resize self
854 * before calling PySequence_Fast_ITEMS.
855 */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200856 /* populate the end of self with iterable's items */
857 src = PySequence_Fast_ITEMS(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 dest = self->ob_item + m;
859 for (i = 0; i < n; i++) {
860 PyObject *o = src[i];
861 Py_INCREF(o);
862 dest[i] = o;
863 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200864 Py_DECREF(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000865 Py_RETURN_NONE;
866 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000867
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200868 it = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000869 if (it == NULL)
870 return NULL;
871 iternext = *it->ob_type->tp_iternext;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000873 /* Guess a result list size. */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200874 n = PyObject_LengthHint(iterable, 8);
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800875 if (n < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000876 Py_DECREF(it);
877 return NULL;
878 }
879 m = Py_SIZE(self);
Martin Panterb93d8632016-07-25 02:39:20 +0000880 if (m > PY_SSIZE_T_MAX - n) {
881 /* m + n overflowed; on the chance that n lied, and there really
882 * is enough room, ignore it. If n was telling the truth, we'll
883 * eventually run out of memory during the loop.
884 */
885 }
886 else {
887 mn = m + n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000888 /* Make room. */
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800889 if (list_resize(self, mn) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000890 goto error;
891 /* Make the list sane again. */
892 Py_SIZE(self) = m;
893 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000895 /* Run iterator to exhaustion. */
896 for (;;) {
897 PyObject *item = iternext(it);
898 if (item == NULL) {
899 if (PyErr_Occurred()) {
900 if (PyErr_ExceptionMatches(PyExc_StopIteration))
901 PyErr_Clear();
902 else
903 goto error;
904 }
905 break;
906 }
907 if (Py_SIZE(self) < self->allocated) {
908 /* steals ref */
909 PyList_SET_ITEM(self, Py_SIZE(self), item);
910 ++Py_SIZE(self);
911 }
912 else {
913 int status = app1(self, item);
914 Py_DECREF(item); /* append creates a new ref */
915 if (status < 0)
916 goto error;
917 }
918 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 /* Cut back result list if initial guess was too large. */
Victor Stinner32fd6ea2013-07-16 21:45:58 +0200921 if (Py_SIZE(self) < self->allocated) {
922 if (list_resize(self, Py_SIZE(self)) < 0)
923 goto error;
924 }
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000925
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 Py_DECREF(it);
927 Py_RETURN_NONE;
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000928
929 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000930 Py_DECREF(it);
931 return NULL;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000932}
933
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000934PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200935_PyList_Extend(PyListObject *self, PyObject *iterable)
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000936{
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200937 return list_extend(self, iterable);
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000938}
939
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000940static PyObject *
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000941list_inplace_concat(PyListObject *self, PyObject *other)
942{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000943 PyObject *result;
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000944
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200945 result = list_extend(self, other);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 if (result == NULL)
947 return result;
948 Py_DECREF(result);
949 Py_INCREF(self);
950 return (PyObject *)self;
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000951}
952
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200953/*[clinic input]
954list.pop
955
956 index: Py_ssize_t = -1
957 /
958
959Remove and return item at index (default last).
960
961Raises IndexError if list is empty or index is out of range.
962[clinic start generated code]*/
963
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000964static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200965list_pop_impl(PyListObject *self, Py_ssize_t index)
966/*[clinic end generated code: output=6bd69dcb3f17eca8 input=b83675976f329e6f]*/
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000967{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000968 PyObject *v;
969 int status;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 if (Py_SIZE(self) == 0) {
972 /* Special-case most common failure cause */
973 PyErr_SetString(PyExc_IndexError, "pop from empty list");
974 return NULL;
975 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200976 if (index < 0)
977 index += Py_SIZE(self);
978 if (index < 0 || index >= Py_SIZE(self)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 PyErr_SetString(PyExc_IndexError, "pop index out of range");
980 return NULL;
981 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200982 v = self->ob_item[index];
983 if (index == Py_SIZE(self) - 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000984 status = list_resize(self, Py_SIZE(self) - 1);
Victor Stinnerb27cd3e2013-07-08 22:20:44 +0200985 if (status >= 0)
986 return v; /* and v now owns the reference the list had */
987 else
988 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000989 }
990 Py_INCREF(v);
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200991 status = list_ass_slice(self, index, index+1, (PyObject *)NULL);
Victor Stinner095d99f2013-07-17 21:58:01 +0200992 if (status < 0) {
993 Py_DECREF(v);
994 return NULL;
995 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000996 return v;
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000997}
998
Tim Peters8e2e7ca2002-07-19 02:33:08 +0000999/* Reverse a slice of a list in place, from lo up to (exclusive) hi. */
1000static void
1001reverse_slice(PyObject **lo, PyObject **hi)
1002{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001003 assert(lo && hi);
Tim Peters8e2e7ca2002-07-19 02:33:08 +00001004
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 --hi;
1006 while (lo < hi) {
1007 PyObject *t = *lo;
1008 *lo = *hi;
1009 *hi = t;
1010 ++lo;
1011 --hi;
1012 }
Tim Peters8e2e7ca2002-07-19 02:33:08 +00001013}
1014
Tim Petersa64dc242002-08-01 02:13:36 +00001015/* Lots of code for an adaptive, stable, natural mergesort. There are many
1016 * pieces to this algorithm; read listsort.txt for overviews and details.
1017 */
Guido van Rossum3f236de1996-12-10 23:55:39 +00001018
Daniel Stutzbach98338222010-12-02 21:55:33 +00001019/* A sortslice contains a pointer to an array of keys and a pointer to
1020 * an array of corresponding values. In other words, keys[i]
1021 * corresponds with values[i]. If values == NULL, then the keys are
1022 * also the values.
1023 *
1024 * Several convenience routines are provided here, so that keys and
1025 * values are always moved in sync.
1026 */
1027
1028typedef struct {
1029 PyObject **keys;
1030 PyObject **values;
1031} sortslice;
1032
1033Py_LOCAL_INLINE(void)
1034sortslice_copy(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j)
1035{
1036 s1->keys[i] = s2->keys[j];
1037 if (s1->values != NULL)
1038 s1->values[i] = s2->values[j];
1039}
1040
1041Py_LOCAL_INLINE(void)
Benjamin Peterson9efdcca2010-12-03 01:44:10 +00001042sortslice_copy_incr(sortslice *dst, sortslice *src)
1043{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001044 *dst->keys++ = *src->keys++;
1045 if (dst->values != NULL)
1046 *dst->values++ = *src->values++;
1047}
1048
1049Py_LOCAL_INLINE(void)
Benjamin Peterson9efdcca2010-12-03 01:44:10 +00001050sortslice_copy_decr(sortslice *dst, sortslice *src)
1051{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001052 *dst->keys-- = *src->keys--;
1053 if (dst->values != NULL)
1054 *dst->values-- = *src->values--;
1055}
1056
1057
1058Py_LOCAL_INLINE(void)
1059sortslice_memcpy(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j,
Benjamin Peterson9efdcca2010-12-03 01:44:10 +00001060 Py_ssize_t n)
1061{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001062 memcpy(&s1->keys[i], &s2->keys[j], sizeof(PyObject *) * n);
1063 if (s1->values != NULL)
1064 memcpy(&s1->values[i], &s2->values[j], sizeof(PyObject *) * n);
1065}
1066
1067Py_LOCAL_INLINE(void)
1068sortslice_memmove(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j,
Benjamin Peterson9efdcca2010-12-03 01:44:10 +00001069 Py_ssize_t n)
1070{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001071 memmove(&s1->keys[i], &s2->keys[j], sizeof(PyObject *) * n);
1072 if (s1->values != NULL)
1073 memmove(&s1->values[i], &s2->values[j], sizeof(PyObject *) * n);
1074}
1075
1076Py_LOCAL_INLINE(void)
Benjamin Peterson9efdcca2010-12-03 01:44:10 +00001077sortslice_advance(sortslice *slice, Py_ssize_t n)
1078{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001079 slice->keys += n;
1080 if (slice->values != NULL)
1081 slice->values += n;
1082}
1083
embg1e34da42018-01-28 20:03:23 -07001084/* Comparison function: ms->key_compare, which is set at run-time in
1085 * listsort_impl to optimize for various special cases.
Tim Petersa64dc242002-08-01 02:13:36 +00001086 * Returns -1 on error, 1 if x < y, 0 if x >= y.
1087 */
Guido van Rossum3f236de1996-12-10 23:55:39 +00001088
embg1e34da42018-01-28 20:03:23 -07001089#define ISLT(X, Y) (*(ms->key_compare))(X, Y, ms)
Tim Peters66860f62002-08-04 17:47:26 +00001090
1091/* Compare X to Y via "<". Goto "fail" if the comparison raises an
Tim Petersa8c974c2002-07-19 03:30:57 +00001092 error. Else "k" is set to true iff X<Y, and an "if (k)" block is
1093 started. It makes more sense in context <wink>. X and Y are PyObject*s.
1094*/
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001095#define IFLT(X, Y) if ((k = ISLT(X, Y)) < 0) goto fail; \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001096 if (k)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001097
embg1e34da42018-01-28 20:03:23 -07001098/* The maximum number of entries in a MergeState's pending-runs stack.
1099 * This is enough to sort arrays of size up to about
1100 * 32 * phi ** MAX_MERGE_PENDING
1101 * where phi ~= 1.618. 85 is ridiculouslylarge enough, good for an array
1102 * with 2**64 elements.
1103 */
1104#define MAX_MERGE_PENDING 85
1105
1106/* When we get into galloping mode, we stay there until both runs win less
1107 * often than MIN_GALLOP consecutive times. See listsort.txt for more info.
1108 */
1109#define MIN_GALLOP 7
1110
1111/* Avoid malloc for small temp arrays. */
1112#define MERGESTATE_TEMP_SIZE 256
1113
1114/* One MergeState exists on the stack per invocation of mergesort. It's just
1115 * a convenient way to pass state around among the helper functions.
1116 */
1117struct s_slice {
1118 sortslice base;
1119 Py_ssize_t len;
1120};
1121
1122typedef struct s_MergeState MergeState;
1123struct s_MergeState {
1124 /* This controls when we get *into* galloping mode. It's initialized
1125 * to MIN_GALLOP. merge_lo and merge_hi tend to nudge it higher for
1126 * random data, and lower for highly structured data.
1127 */
1128 Py_ssize_t min_gallop;
1129
1130 /* 'a' is temp storage to help with merges. It contains room for
1131 * alloced entries.
1132 */
1133 sortslice a; /* may point to temparray below */
1134 Py_ssize_t alloced;
1135
1136 /* A stack of n pending runs yet to be merged. Run #i starts at
1137 * address base[i] and extends for len[i] elements. It's always
1138 * true (so long as the indices are in bounds) that
1139 *
1140 * pending[i].base + pending[i].len == pending[i+1].base
1141 *
1142 * so we could cut the storage for this, but it's a minor amount,
1143 * and keeping all the info explicit simplifies the code.
1144 */
1145 int n;
1146 struct s_slice pending[MAX_MERGE_PENDING];
1147
1148 /* 'a' points to this when possible, rather than muck with malloc. */
1149 PyObject *temparray[MERGESTATE_TEMP_SIZE];
1150
1151 /* This is the function we will use to compare two keys,
1152 * even when none of our special cases apply and we have to use
1153 * safe_object_compare. */
1154 int (*key_compare)(PyObject *, PyObject *, MergeState *);
1155
1156 /* This function is used by unsafe_object_compare to optimize comparisons
1157 * when we know our list is type-homogeneous but we can't assume anything else.
1158 * In the pre-sort check it is set equal to key->ob_type->tp_richcompare */
1159 PyObject *(*key_richcompare)(PyObject *, PyObject *, int);
1160
1161 /* This function is used by unsafe_tuple_compare to compare the first elements
1162 * of tuples. It may be set to safe_object_compare, but the idea is that hopefully
1163 * we can assume more, and use one of the special-case compares. */
1164 int (*tuple_elem_compare)(PyObject *, PyObject *, MergeState *);
1165};
1166
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001167/* binarysort is the best method for sorting small arrays: it does
1168 few compares, but can do data movement quadratic in the number of
1169 elements.
Guido van Rossum42812581998-06-17 14:15:44 +00001170 [lo, hi) is a contiguous slice of a list, and is sorted via
Tim Petersa8c974c2002-07-19 03:30:57 +00001171 binary insertion. This sort is stable.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001172 On entry, must have lo <= start <= hi, and that [lo, start) is already
1173 sorted (pass start == lo if you don't know!).
Tim Petersa8c974c2002-07-19 03:30:57 +00001174 If islt() complains return -1, else 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001175 Even in case of error, the output slice will be some permutation of
1176 the input (nothing is lost or duplicated).
1177*/
Guido van Rossum3f236de1996-12-10 23:55:39 +00001178static int
embg1e34da42018-01-28 20:03:23 -07001179binarysort(MergeState *ms, sortslice lo, PyObject **hi, PyObject **start)
Guido van Rossum3f236de1996-12-10 23:55:39 +00001180{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001181 Py_ssize_t k;
1182 PyObject **l, **p, **r;
1183 PyObject *pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001184
Daniel Stutzbach98338222010-12-02 21:55:33 +00001185 assert(lo.keys <= start && start <= hi);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001186 /* assert [lo, start) is sorted */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001187 if (lo.keys == start)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 ++start;
1189 for (; start < hi; ++start) {
1190 /* set l to where *start belongs */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001191 l = lo.keys;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001192 r = start;
1193 pivot = *r;
1194 /* Invariants:
1195 * pivot >= all in [lo, l).
1196 * pivot < all in [r, start).
1197 * The second is vacuously true at the start.
1198 */
1199 assert(l < r);
1200 do {
1201 p = l + ((r - l) >> 1);
1202 IFLT(pivot, *p)
1203 r = p;
1204 else
1205 l = p+1;
1206 } while (l < r);
1207 assert(l == r);
1208 /* The invariants still hold, so pivot >= all in [lo, l) and
1209 pivot < all in [l, start), so pivot belongs at l. Note
1210 that if there are elements equal to pivot, l points to the
1211 first slot after them -- that's why this sort is stable.
1212 Slide over to make room.
1213 Caution: using memmove is much slower under MSVC 5;
1214 we're not usually moving many slots. */
1215 for (p = start; p > l; --p)
1216 *p = *(p-1);
1217 *l = pivot;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001218 if (lo.values != NULL) {
1219 Py_ssize_t offset = lo.values - lo.keys;
1220 p = start + offset;
1221 pivot = *p;
1222 l += offset;
1223 for (p = start + offset; p > l; --p)
1224 *p = *(p-1);
1225 *l = pivot;
1226 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001227 }
1228 return 0;
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001229
1230 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001231 return -1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001232}
1233
Tim Petersa64dc242002-08-01 02:13:36 +00001234/*
1235Return the length of the run beginning at lo, in the slice [lo, hi). lo < hi
1236is required on entry. "A run" is the longest ascending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001237
Tim Petersa64dc242002-08-01 02:13:36 +00001238 lo[0] <= lo[1] <= lo[2] <= ...
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001239
Tim Petersa64dc242002-08-01 02:13:36 +00001240or the longest descending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001241
Tim Petersa64dc242002-08-01 02:13:36 +00001242 lo[0] > lo[1] > lo[2] > ...
Tim Peters3b01a122002-07-19 02:35:45 +00001243
Tim Petersa64dc242002-08-01 02:13:36 +00001244Boolean *descending is set to 0 in the former case, or to 1 in the latter.
1245For its intended use in a stable mergesort, the strictness of the defn of
1246"descending" is needed so that the caller can safely reverse a descending
1247sequence without violating stability (strict > ensures there are no equal
1248elements to get out of order).
1249
1250Returns -1 in case of error.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001251*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001252static Py_ssize_t
embg1e34da42018-01-28 20:03:23 -07001253count_run(MergeState *ms, PyObject **lo, PyObject **hi, int *descending)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001254{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001255 Py_ssize_t k;
1256 Py_ssize_t n;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258 assert(lo < hi);
1259 *descending = 0;
1260 ++lo;
1261 if (lo == hi)
1262 return 1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001264 n = 2;
1265 IFLT(*lo, *(lo-1)) {
1266 *descending = 1;
1267 for (lo = lo+1; lo < hi; ++lo, ++n) {
1268 IFLT(*lo, *(lo-1))
1269 ;
1270 else
1271 break;
1272 }
1273 }
1274 else {
1275 for (lo = lo+1; lo < hi; ++lo, ++n) {
1276 IFLT(*lo, *(lo-1))
1277 break;
1278 }
1279 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001281 return n;
Tim Petersa64dc242002-08-01 02:13:36 +00001282fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001283 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001284}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001285
Tim Petersa64dc242002-08-01 02:13:36 +00001286/*
1287Locate the proper position of key in a sorted vector; if the vector contains
1288an element equal to key, return the position immediately to the left of
1289the leftmost equal element. [gallop_right() does the same except returns
1290the position to the right of the rightmost equal element (if any).]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001291
Tim Petersa64dc242002-08-01 02:13:36 +00001292"a" is a sorted vector with n elements, starting at a[0]. n must be > 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001293
Tim Petersa64dc242002-08-01 02:13:36 +00001294"hint" is an index at which to begin the search, 0 <= hint < n. The closer
1295hint is to the final result, the faster this runs.
1296
1297The return value is the int k in 0..n such that
1298
1299 a[k-1] < key <= a[k]
1300
1301pretending that *(a-1) is minus infinity and a[n] is plus infinity. IOW,
1302key belongs at index k; or, IOW, the first k elements of a should precede
1303key, and the last n-k should follow key.
1304
1305Returns -1 on error. See listsort.txt for info on the method.
1306*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001307static Py_ssize_t
embg1e34da42018-01-28 20:03:23 -07001308gallop_left(MergeState *ms, PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint)
Tim Petersa64dc242002-08-01 02:13:36 +00001309{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001310 Py_ssize_t ofs;
1311 Py_ssize_t lastofs;
1312 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001314 assert(key && a && n > 0 && hint >= 0 && hint < n);
Tim Petersa64dc242002-08-01 02:13:36 +00001315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001316 a += hint;
1317 lastofs = 0;
1318 ofs = 1;
1319 IFLT(*a, key) {
1320 /* a[hint] < key -- gallop right, until
1321 * a[hint + lastofs] < key <= a[hint + ofs]
1322 */
1323 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
1324 while (ofs < maxofs) {
1325 IFLT(a[ofs], key) {
1326 lastofs = ofs;
Miss Islington (bot)367fe572019-05-22 17:18:55 -07001327 assert(ofs <= (PY_SSIZE_T_MAX - 1) / 2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001328 ofs = (ofs << 1) + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001329 }
1330 else /* key <= a[hint + ofs] */
1331 break;
1332 }
1333 if (ofs > maxofs)
1334 ofs = maxofs;
1335 /* Translate back to offsets relative to &a[0]. */
1336 lastofs += hint;
1337 ofs += hint;
1338 }
1339 else {
1340 /* key <= a[hint] -- gallop left, until
1341 * a[hint - ofs] < key <= a[hint - lastofs]
1342 */
1343 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
1344 while (ofs < maxofs) {
1345 IFLT(*(a-ofs), key)
1346 break;
1347 /* key <= a[hint - ofs] */
1348 lastofs = ofs;
Miss Islington (bot)367fe572019-05-22 17:18:55 -07001349 assert(ofs <= (PY_SSIZE_T_MAX - 1) / 2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001350 ofs = (ofs << 1) + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001351 }
1352 if (ofs > maxofs)
1353 ofs = maxofs;
1354 /* Translate back to positive offsets relative to &a[0]. */
1355 k = lastofs;
1356 lastofs = hint - ofs;
1357 ofs = hint - k;
1358 }
1359 a -= hint;
Tim Petersa64dc242002-08-01 02:13:36 +00001360
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001361 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1362 /* Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the
1363 * right of lastofs but no farther right than ofs. Do a binary
1364 * search, with invariant a[lastofs-1] < key <= a[ofs].
1365 */
1366 ++lastofs;
1367 while (lastofs < ofs) {
1368 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001370 IFLT(a[m], key)
1371 lastofs = m+1; /* a[m] < key */
1372 else
1373 ofs = m; /* key <= a[m] */
1374 }
1375 assert(lastofs == ofs); /* so a[ofs-1] < key <= a[ofs] */
1376 return ofs;
Tim Petersa64dc242002-08-01 02:13:36 +00001377
1378fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001379 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001380}
1381
1382/*
1383Exactly like gallop_left(), except that if key already exists in a[0:n],
1384finds the position immediately to the right of the rightmost equal value.
1385
1386The return value is the int k in 0..n such that
1387
1388 a[k-1] <= key < a[k]
1389
1390or -1 if error.
1391
1392The code duplication is massive, but this is enough different given that
1393we're sticking to "<" comparisons that it's much harder to follow if
1394written as one routine with yet another "left or right?" flag.
1395*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001396static Py_ssize_t
embg1e34da42018-01-28 20:03:23 -07001397gallop_right(MergeState *ms, PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint)
Tim Petersa64dc242002-08-01 02:13:36 +00001398{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001399 Py_ssize_t ofs;
1400 Py_ssize_t lastofs;
1401 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001403 assert(key && a && n > 0 && hint >= 0 && hint < n);
Tim Petersa64dc242002-08-01 02:13:36 +00001404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001405 a += hint;
1406 lastofs = 0;
1407 ofs = 1;
1408 IFLT(key, *a) {
1409 /* key < a[hint] -- gallop left, until
1410 * a[hint - ofs] <= key < a[hint - lastofs]
1411 */
1412 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
1413 while (ofs < maxofs) {
1414 IFLT(key, *(a-ofs)) {
1415 lastofs = ofs;
Miss Islington (bot)367fe572019-05-22 17:18:55 -07001416 assert(ofs <= (PY_SSIZE_T_MAX - 1) / 2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001417 ofs = (ofs << 1) + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001418 }
1419 else /* a[hint - ofs] <= key */
1420 break;
1421 }
1422 if (ofs > maxofs)
1423 ofs = maxofs;
1424 /* Translate back to positive offsets relative to &a[0]. */
1425 k = lastofs;
1426 lastofs = hint - ofs;
1427 ofs = hint - k;
1428 }
1429 else {
1430 /* a[hint] <= key -- gallop right, until
1431 * a[hint + lastofs] <= key < a[hint + ofs]
1432 */
1433 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
1434 while (ofs < maxofs) {
1435 IFLT(key, a[ofs])
1436 break;
1437 /* a[hint + ofs] <= key */
1438 lastofs = ofs;
Miss Islington (bot)367fe572019-05-22 17:18:55 -07001439 assert(ofs <= (PY_SSIZE_T_MAX - 1) / 2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001440 ofs = (ofs << 1) + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001441 }
1442 if (ofs > maxofs)
1443 ofs = maxofs;
1444 /* Translate back to offsets relative to &a[0]. */
1445 lastofs += hint;
1446 ofs += hint;
1447 }
1448 a -= hint;
Tim Petersa64dc242002-08-01 02:13:36 +00001449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001450 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1451 /* Now a[lastofs] <= key < a[ofs], so key belongs somewhere to the
1452 * right of lastofs but no farther right than ofs. Do a binary
1453 * search, with invariant a[lastofs-1] <= key < a[ofs].
1454 */
1455 ++lastofs;
1456 while (lastofs < ofs) {
1457 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001458
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001459 IFLT(key, a[m])
1460 ofs = m; /* key < a[m] */
1461 else
1462 lastofs = m+1; /* a[m] <= key */
1463 }
1464 assert(lastofs == ofs); /* so a[ofs-1] <= key < a[ofs] */
1465 return ofs;
Tim Petersa64dc242002-08-01 02:13:36 +00001466
1467fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001468 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001469}
1470
Tim Petersa64dc242002-08-01 02:13:36 +00001471/* Conceptually a MergeState's constructor. */
1472static void
Victor Stinner0fcab4a2011-01-04 12:59:15 +00001473merge_init(MergeState *ms, Py_ssize_t list_size, int has_keyfunc)
Tim Petersa64dc242002-08-01 02:13:36 +00001474{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001475 assert(ms != NULL);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001476 if (has_keyfunc) {
1477 /* The temporary space for merging will need at most half the list
1478 * size rounded up. Use the minimum possible space so we can use the
1479 * rest of temparray for other things. In particular, if there is
1480 * enough extra space, listsort() will use it to store the keys.
1481 */
1482 ms->alloced = (list_size + 1) / 2;
1483
1484 /* ms->alloced describes how many keys will be stored at
1485 ms->temparray, but we also need to store the values. Hence,
1486 ms->alloced is capped at half of MERGESTATE_TEMP_SIZE. */
1487 if (MERGESTATE_TEMP_SIZE / 2 < ms->alloced)
1488 ms->alloced = MERGESTATE_TEMP_SIZE / 2;
1489 ms->a.values = &ms->temparray[ms->alloced];
1490 }
1491 else {
1492 ms->alloced = MERGESTATE_TEMP_SIZE;
1493 ms->a.values = NULL;
1494 }
1495 ms->a.keys = ms->temparray;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001496 ms->n = 0;
1497 ms->min_gallop = MIN_GALLOP;
Tim Petersa64dc242002-08-01 02:13:36 +00001498}
1499
1500/* Free all the temp memory owned by the MergeState. This must be called
1501 * when you're done with a MergeState, and may be called before then if
1502 * you want to free the temp memory early.
1503 */
1504static void
1505merge_freemem(MergeState *ms)
1506{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001507 assert(ms != NULL);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001508 if (ms->a.keys != ms->temparray)
1509 PyMem_Free(ms->a.keys);
Tim Petersa64dc242002-08-01 02:13:36 +00001510}
1511
1512/* Ensure enough temp memory for 'need' array slots is available.
1513 * Returns 0 on success and -1 if the memory can't be gotten.
1514 */
1515static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001516merge_getmem(MergeState *ms, Py_ssize_t need)
Tim Petersa64dc242002-08-01 02:13:36 +00001517{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001518 int multiplier;
1519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001520 assert(ms != NULL);
1521 if (need <= ms->alloced)
1522 return 0;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001523
1524 multiplier = ms->a.values != NULL ? 2 : 1;
1525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001526 /* Don't realloc! That can cost cycles to copy the old data, but
1527 * we don't care what's in the block.
1528 */
1529 merge_freemem(ms);
embg1e34da42018-01-28 20:03:23 -07001530 if ((size_t)need > PY_SSIZE_T_MAX / sizeof(PyObject *) / multiplier) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001531 PyErr_NoMemory();
1532 return -1;
1533 }
embg1e34da42018-01-28 20:03:23 -07001534 ms->a.keys = (PyObject **)PyMem_Malloc(multiplier * need
Daniel Stutzbach98338222010-12-02 21:55:33 +00001535 * sizeof(PyObject *));
1536 if (ms->a.keys != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001537 ms->alloced = need;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001538 if (ms->a.values != NULL)
1539 ms->a.values = &ms->a.keys[need];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001540 return 0;
1541 }
1542 PyErr_NoMemory();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001543 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001544}
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001545#define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 : \
1546 merge_getmem(MS, NEED))
Tim Petersa64dc242002-08-01 02:13:36 +00001547
Daniel Stutzbach98338222010-12-02 21:55:33 +00001548/* Merge the na elements starting at ssa with the nb elements starting at
1549 * ssb.keys = ssa.keys + na in a stable way, in-place. na and nb must be > 0.
1550 * Must also have that ssa.keys[na-1] belongs at the end of the merge, and
1551 * should have na <= nb. See listsort.txt for more info. Return 0 if
1552 * successful, -1 if error.
Tim Petersa64dc242002-08-01 02:13:36 +00001553 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001554static Py_ssize_t
Daniel Stutzbach98338222010-12-02 21:55:33 +00001555merge_lo(MergeState *ms, sortslice ssa, Py_ssize_t na,
1556 sortslice ssb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001557{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001558 Py_ssize_t k;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001559 sortslice dest;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001560 int result = -1; /* guilty until proved innocent */
1561 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001562
Daniel Stutzbach98338222010-12-02 21:55:33 +00001563 assert(ms && ssa.keys && ssb.keys && na > 0 && nb > 0);
1564 assert(ssa.keys + na == ssb.keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001565 if (MERGE_GETMEM(ms, na) < 0)
1566 return -1;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001567 sortslice_memcpy(&ms->a, 0, &ssa, 0, na);
1568 dest = ssa;
1569 ssa = ms->a;
Tim Petersa64dc242002-08-01 02:13:36 +00001570
Daniel Stutzbach98338222010-12-02 21:55:33 +00001571 sortslice_copy_incr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001572 --nb;
1573 if (nb == 0)
1574 goto Succeed;
1575 if (na == 1)
1576 goto CopyB;
Tim Petersa64dc242002-08-01 02:13:36 +00001577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001578 min_gallop = ms->min_gallop;
1579 for (;;) {
1580 Py_ssize_t acount = 0; /* # of times A won in a row */
1581 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001583 /* Do the straightforward thing until (if ever) one run
1584 * appears to win consistently.
1585 */
1586 for (;;) {
1587 assert(na > 1 && nb > 0);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001588 k = ISLT(ssb.keys[0], ssa.keys[0]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001589 if (k) {
1590 if (k < 0)
1591 goto Fail;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001592 sortslice_copy_incr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001593 ++bcount;
1594 acount = 0;
1595 --nb;
1596 if (nb == 0)
1597 goto Succeed;
1598 if (bcount >= min_gallop)
1599 break;
1600 }
1601 else {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001602 sortslice_copy_incr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001603 ++acount;
1604 bcount = 0;
1605 --na;
1606 if (na == 1)
1607 goto CopyB;
1608 if (acount >= min_gallop)
1609 break;
1610 }
1611 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001613 /* One run is winning so consistently that galloping may
1614 * be a huge win. So try that, and continue galloping until
1615 * (if ever) neither run appears to be winning consistently
1616 * anymore.
1617 */
1618 ++min_gallop;
1619 do {
1620 assert(na > 1 && nb > 0);
1621 min_gallop -= min_gallop > 1;
1622 ms->min_gallop = min_gallop;
embg1e34da42018-01-28 20:03:23 -07001623 k = gallop_right(ms, ssb.keys[0], ssa.keys, na, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001624 acount = k;
1625 if (k) {
1626 if (k < 0)
1627 goto Fail;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001628 sortslice_memcpy(&dest, 0, &ssa, 0, k);
1629 sortslice_advance(&dest, k);
1630 sortslice_advance(&ssa, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001631 na -= k;
1632 if (na == 1)
1633 goto CopyB;
1634 /* na==0 is impossible now if the comparison
1635 * function is consistent, but we can't assume
1636 * that it is.
1637 */
1638 if (na == 0)
1639 goto Succeed;
1640 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001641 sortslice_copy_incr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001642 --nb;
1643 if (nb == 0)
1644 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001645
embg1e34da42018-01-28 20:03:23 -07001646 k = gallop_left(ms, ssa.keys[0], ssb.keys, nb, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001647 bcount = k;
1648 if (k) {
1649 if (k < 0)
1650 goto Fail;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001651 sortslice_memmove(&dest, 0, &ssb, 0, k);
1652 sortslice_advance(&dest, k);
1653 sortslice_advance(&ssb, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001654 nb -= k;
1655 if (nb == 0)
1656 goto Succeed;
1657 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001658 sortslice_copy_incr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001659 --na;
1660 if (na == 1)
1661 goto CopyB;
1662 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
1663 ++min_gallop; /* penalize it for leaving galloping mode */
1664 ms->min_gallop = min_gallop;
1665 }
Tim Petersa64dc242002-08-01 02:13:36 +00001666Succeed:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001667 result = 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001668Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001669 if (na)
Daniel Stutzbach98338222010-12-02 21:55:33 +00001670 sortslice_memcpy(&dest, 0, &ssa, 0, na);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001671 return result;
Tim Petersa64dc242002-08-01 02:13:36 +00001672CopyB:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001673 assert(na == 1 && nb > 0);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001674 /* The last element of ssa belongs at the end of the merge. */
1675 sortslice_memmove(&dest, 0, &ssb, 0, nb);
1676 sortslice_copy(&dest, nb, &ssa, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001677 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001678}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001679
Daniel Stutzbach98338222010-12-02 21:55:33 +00001680/* Merge the na elements starting at pa with the nb elements starting at
1681 * ssb.keys = ssa.keys + na in a stable way, in-place. na and nb must be > 0.
1682 * Must also have that ssa.keys[na-1] belongs at the end of the merge, and
1683 * should have na >= nb. See listsort.txt for more info. Return 0 if
1684 * successful, -1 if error.
Tim Petersa64dc242002-08-01 02:13:36 +00001685 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001686static Py_ssize_t
Daniel Stutzbach98338222010-12-02 21:55:33 +00001687merge_hi(MergeState *ms, sortslice ssa, Py_ssize_t na,
1688 sortslice ssb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001689{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001690 Py_ssize_t k;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001691 sortslice dest, basea, baseb;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001692 int result = -1; /* guilty until proved innocent */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001693 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001694
Daniel Stutzbach98338222010-12-02 21:55:33 +00001695 assert(ms && ssa.keys && ssb.keys && na > 0 && nb > 0);
1696 assert(ssa.keys + na == ssb.keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001697 if (MERGE_GETMEM(ms, nb) < 0)
1698 return -1;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001699 dest = ssb;
1700 sortslice_advance(&dest, nb-1);
1701 sortslice_memcpy(&ms->a, 0, &ssb, 0, nb);
1702 basea = ssa;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001703 baseb = ms->a;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001704 ssb.keys = ms->a.keys + nb - 1;
1705 if (ssb.values != NULL)
1706 ssb.values = ms->a.values + nb - 1;
1707 sortslice_advance(&ssa, na - 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001708
Daniel Stutzbach98338222010-12-02 21:55:33 +00001709 sortslice_copy_decr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001710 --na;
1711 if (na == 0)
1712 goto Succeed;
1713 if (nb == 1)
1714 goto CopyA;
Tim Petersa64dc242002-08-01 02:13:36 +00001715
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001716 min_gallop = ms->min_gallop;
1717 for (;;) {
1718 Py_ssize_t acount = 0; /* # of times A won in a row */
1719 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001720
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001721 /* Do the straightforward thing until (if ever) one run
1722 * appears to win consistently.
1723 */
1724 for (;;) {
1725 assert(na > 0 && nb > 1);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001726 k = ISLT(ssb.keys[0], ssa.keys[0]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001727 if (k) {
1728 if (k < 0)
1729 goto Fail;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001730 sortslice_copy_decr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001731 ++acount;
1732 bcount = 0;
1733 --na;
1734 if (na == 0)
1735 goto Succeed;
1736 if (acount >= min_gallop)
1737 break;
1738 }
1739 else {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001740 sortslice_copy_decr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001741 ++bcount;
1742 acount = 0;
1743 --nb;
1744 if (nb == 1)
1745 goto CopyA;
1746 if (bcount >= min_gallop)
1747 break;
1748 }
1749 }
Tim Petersa64dc242002-08-01 02:13:36 +00001750
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001751 /* One run is winning so consistently that galloping may
1752 * be a huge win. So try that, and continue galloping until
1753 * (if ever) neither run appears to be winning consistently
1754 * anymore.
1755 */
1756 ++min_gallop;
1757 do {
1758 assert(na > 0 && nb > 1);
1759 min_gallop -= min_gallop > 1;
1760 ms->min_gallop = min_gallop;
embg1e34da42018-01-28 20:03:23 -07001761 k = gallop_right(ms, ssb.keys[0], basea.keys, na, na-1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001762 if (k < 0)
1763 goto Fail;
1764 k = na - k;
1765 acount = k;
1766 if (k) {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001767 sortslice_advance(&dest, -k);
1768 sortslice_advance(&ssa, -k);
1769 sortslice_memmove(&dest, 1, &ssa, 1, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001770 na -= k;
1771 if (na == 0)
1772 goto Succeed;
1773 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001774 sortslice_copy_decr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001775 --nb;
1776 if (nb == 1)
1777 goto CopyA;
Tim Petersa64dc242002-08-01 02:13:36 +00001778
embg1e34da42018-01-28 20:03:23 -07001779 k = gallop_left(ms, ssa.keys[0], baseb.keys, nb, nb-1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001780 if (k < 0)
1781 goto Fail;
1782 k = nb - k;
1783 bcount = k;
1784 if (k) {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001785 sortslice_advance(&dest, -k);
1786 sortslice_advance(&ssb, -k);
1787 sortslice_memcpy(&dest, 1, &ssb, 1, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001788 nb -= k;
1789 if (nb == 1)
1790 goto CopyA;
1791 /* nb==0 is impossible now if the comparison
1792 * function is consistent, but we can't assume
1793 * that it is.
1794 */
1795 if (nb == 0)
1796 goto Succeed;
1797 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001798 sortslice_copy_decr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001799 --na;
1800 if (na == 0)
1801 goto Succeed;
1802 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
1803 ++min_gallop; /* penalize it for leaving galloping mode */
1804 ms->min_gallop = min_gallop;
1805 }
Tim Petersa64dc242002-08-01 02:13:36 +00001806Succeed:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001807 result = 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001808Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001809 if (nb)
Daniel Stutzbach98338222010-12-02 21:55:33 +00001810 sortslice_memcpy(&dest, -(nb-1), &baseb, 0, nb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001811 return result;
Tim Petersa64dc242002-08-01 02:13:36 +00001812CopyA:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001813 assert(nb == 1 && na > 0);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001814 /* The first element of ssb belongs at the front of the merge. */
1815 sortslice_memmove(&dest, 1-na, &ssa, 1-na, na);
1816 sortslice_advance(&dest, -na);
1817 sortslice_advance(&ssa, -na);
1818 sortslice_copy(&dest, 0, &ssb, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001819 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001820}
1821
1822/* Merge the two runs at stack indices i and i+1.
1823 * Returns 0 on success, -1 on error.
1824 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001825static Py_ssize_t
1826merge_at(MergeState *ms, Py_ssize_t i)
Tim Petersa64dc242002-08-01 02:13:36 +00001827{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001828 sortslice ssa, ssb;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001829 Py_ssize_t na, nb;
1830 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001831
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001832 assert(ms != NULL);
1833 assert(ms->n >= 2);
1834 assert(i >= 0);
1835 assert(i == ms->n - 2 || i == ms->n - 3);
Tim Petersa64dc242002-08-01 02:13:36 +00001836
Daniel Stutzbach98338222010-12-02 21:55:33 +00001837 ssa = ms->pending[i].base;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001838 na = ms->pending[i].len;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001839 ssb = ms->pending[i+1].base;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001840 nb = ms->pending[i+1].len;
1841 assert(na > 0 && nb > 0);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001842 assert(ssa.keys + na == ssb.keys);
Tim Petersa64dc242002-08-01 02:13:36 +00001843
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001844 /* Record the length of the combined runs; if i is the 3rd-last
1845 * run now, also slide over the last run (which isn't involved
1846 * in this merge). The current run i+1 goes away in any case.
1847 */
1848 ms->pending[i].len = na + nb;
1849 if (i == ms->n - 3)
1850 ms->pending[i+1] = ms->pending[i+2];
1851 --ms->n;
Tim Petersa64dc242002-08-01 02:13:36 +00001852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001853 /* Where does b start in a? Elements in a before that can be
1854 * ignored (already in place).
1855 */
embg1e34da42018-01-28 20:03:23 -07001856 k = gallop_right(ms, *ssb.keys, ssa.keys, na, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001857 if (k < 0)
1858 return -1;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001859 sortslice_advance(&ssa, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001860 na -= k;
1861 if (na == 0)
1862 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001864 /* Where does a end in b? Elements in b after that can be
1865 * ignored (already in place).
1866 */
embg1e34da42018-01-28 20:03:23 -07001867 nb = gallop_left(ms, ssa.keys[na-1], ssb.keys, nb, nb-1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001868 if (nb <= 0)
1869 return nb;
Tim Petersa64dc242002-08-01 02:13:36 +00001870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001871 /* Merge what remains of the runs, using a temp array with
1872 * min(na, nb) elements.
1873 */
1874 if (na <= nb)
Daniel Stutzbach98338222010-12-02 21:55:33 +00001875 return merge_lo(ms, ssa, na, ssb, nb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001876 else
Daniel Stutzbach98338222010-12-02 21:55:33 +00001877 return merge_hi(ms, ssa, na, ssb, nb);
Tim Petersa64dc242002-08-01 02:13:36 +00001878}
1879
1880/* Examine the stack of runs waiting to be merged, merging adjacent runs
1881 * until the stack invariants are re-established:
1882 *
1883 * 1. len[-3] > len[-2] + len[-1]
1884 * 2. len[-2] > len[-1]
1885 *
1886 * See listsort.txt for more info.
1887 *
1888 * Returns 0 on success, -1 on error.
1889 */
1890static int
1891merge_collapse(MergeState *ms)
1892{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001893 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001895 assert(ms);
1896 while (ms->n > 1) {
1897 Py_ssize_t n = ms->n - 2;
Benjamin Petersonb808d592015-02-25 10:12:26 -05001898 if ((n > 0 && p[n-1].len <= p[n].len + p[n+1].len) ||
1899 (n > 1 && p[n-2].len <= p[n-1].len + p[n].len)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001900 if (p[n-1].len < p[n+1].len)
1901 --n;
1902 if (merge_at(ms, n) < 0)
1903 return -1;
1904 }
1905 else if (p[n].len <= p[n+1].len) {
embg1e34da42018-01-28 20:03:23 -07001906 if (merge_at(ms, n) < 0)
1907 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001908 }
1909 else
1910 break;
1911 }
1912 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001913}
1914
1915/* Regardless of invariants, merge all runs on the stack until only one
1916 * remains. This is used at the end of the mergesort.
1917 *
1918 * Returns 0 on success, -1 on error.
1919 */
1920static int
1921merge_force_collapse(MergeState *ms)
1922{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001923 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001925 assert(ms);
1926 while (ms->n > 1) {
1927 Py_ssize_t n = ms->n - 2;
1928 if (n > 0 && p[n-1].len < p[n+1].len)
1929 --n;
1930 if (merge_at(ms, n) < 0)
1931 return -1;
1932 }
1933 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001934}
1935
1936/* Compute a good value for the minimum run length; natural runs shorter
1937 * than this are boosted artificially via binary insertion.
1938 *
1939 * If n < 64, return n (it's too small to bother with fancy stuff).
1940 * Else if n is an exact power of 2, return 32.
1941 * Else return an int k, 32 <= k <= 64, such that n/k is close to, but
1942 * strictly less than, an exact power of 2.
1943 *
1944 * See listsort.txt for more info.
1945 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001946static Py_ssize_t
1947merge_compute_minrun(Py_ssize_t n)
Tim Petersa64dc242002-08-01 02:13:36 +00001948{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001949 Py_ssize_t r = 0; /* becomes 1 if any 1 bits are shifted off */
Tim Petersa64dc242002-08-01 02:13:36 +00001950
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001951 assert(n >= 0);
1952 while (n >= 64) {
1953 r |= n & 1;
1954 n >>= 1;
1955 }
1956 return n + r;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001957}
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001958
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001959static void
Daniel Stutzbach98338222010-12-02 21:55:33 +00001960reverse_sortslice(sortslice *s, Py_ssize_t n)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001961{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001962 reverse_slice(s->keys, &s->keys[n]);
1963 if (s->values != NULL)
1964 reverse_slice(s->values, &s->values[n]);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001965}
1966
embg1e34da42018-01-28 20:03:23 -07001967/* Here we define custom comparison functions to optimize for the cases one commonly
1968 * encounters in practice: homogeneous lists, often of one of the basic types. */
1969
1970/* This struct holds the comparison function and helper functions
1971 * selected in the pre-sort check. */
1972
1973/* These are the special case compare functions.
1974 * ms->key_compare will always point to one of these: */
1975
1976/* Heterogeneous compare: default, always safe to fall back on. */
1977static int
1978safe_object_compare(PyObject *v, PyObject *w, MergeState *ms)
1979{
1980 /* No assumptions necessary! */
1981 return PyObject_RichCompareBool(v, w, Py_LT);
1982}
1983
1984/* Homogeneous compare: safe for any two compareable objects of the same type.
1985 * (ms->key_richcompare is set to ob_type->tp_richcompare in the
1986 * pre-sort check.)
1987 */
1988static int
1989unsafe_object_compare(PyObject *v, PyObject *w, MergeState *ms)
1990{
1991 PyObject *res_obj; int res;
1992
1993 /* No assumptions, because we check first: */
1994 if (v->ob_type->tp_richcompare != ms->key_richcompare)
1995 return PyObject_RichCompareBool(v, w, Py_LT);
1996
1997 assert(ms->key_richcompare != NULL);
1998 res_obj = (*(ms->key_richcompare))(v, w, Py_LT);
1999
2000 if (res_obj == Py_NotImplemented) {
2001 Py_DECREF(res_obj);
2002 return PyObject_RichCompareBool(v, w, Py_LT);
2003 }
2004 if (res_obj == NULL)
2005 return -1;
2006
2007 if (PyBool_Check(res_obj)) {
2008 res = (res_obj == Py_True);
2009 }
2010 else {
2011 res = PyObject_IsTrue(res_obj);
2012 }
2013 Py_DECREF(res_obj);
2014
2015 /* Note that we can't assert
2016 * res == PyObject_RichCompareBool(v, w, Py_LT);
2017 * because of evil compare functions like this:
2018 * lambda a, b: int(random.random() * 3) - 1)
2019 * (which is actually in test_sort.py) */
2020 return res;
2021}
2022
2023/* Latin string compare: safe for any two latin (one byte per char) strings. */
2024static int
2025unsafe_latin_compare(PyObject *v, PyObject *w, MergeState *ms)
2026{
Victor Stinner8017b802018-01-29 13:47:06 +01002027 Py_ssize_t len;
2028 int res;
embg1e34da42018-01-28 20:03:23 -07002029
2030 /* Modified from Objects/unicodeobject.c:unicode_compare, assuming: */
2031 assert(v->ob_type == w->ob_type);
2032 assert(v->ob_type == &PyUnicode_Type);
2033 assert(PyUnicode_KIND(v) == PyUnicode_KIND(w));
2034 assert(PyUnicode_KIND(v) == PyUnicode_1BYTE_KIND);
2035
2036 len = Py_MIN(PyUnicode_GET_LENGTH(v), PyUnicode_GET_LENGTH(w));
2037 res = memcmp(PyUnicode_DATA(v), PyUnicode_DATA(w), len);
2038
2039 res = (res != 0 ?
2040 res < 0 :
2041 PyUnicode_GET_LENGTH(v) < PyUnicode_GET_LENGTH(w));
2042
2043 assert(res == PyObject_RichCompareBool(v, w, Py_LT));;
2044 return res;
2045}
2046
2047/* Bounded int compare: compare any two longs that fit in a single machine word. */
2048static int
2049unsafe_long_compare(PyObject *v, PyObject *w, MergeState *ms)
2050{
2051 PyLongObject *vl, *wl; sdigit v0, w0; int res;
2052
2053 /* Modified from Objects/longobject.c:long_compare, assuming: */
2054 assert(v->ob_type == w->ob_type);
2055 assert(v->ob_type == &PyLong_Type);
2056 assert(Py_ABS(Py_SIZE(v)) <= 1);
2057 assert(Py_ABS(Py_SIZE(w)) <= 1);
2058
2059 vl = (PyLongObject*)v;
2060 wl = (PyLongObject*)w;
2061
2062 v0 = Py_SIZE(vl) == 0 ? 0 : (sdigit)vl->ob_digit[0];
2063 w0 = Py_SIZE(wl) == 0 ? 0 : (sdigit)wl->ob_digit[0];
2064
2065 if (Py_SIZE(vl) < 0)
2066 v0 = -v0;
2067 if (Py_SIZE(wl) < 0)
2068 w0 = -w0;
2069
2070 res = v0 < w0;
2071 assert(res == PyObject_RichCompareBool(v, w, Py_LT));
2072 return res;
2073}
2074
2075/* Float compare: compare any two floats. */
2076static int
2077unsafe_float_compare(PyObject *v, PyObject *w, MergeState *ms)
2078{
2079 int res;
2080
2081 /* Modified from Objects/floatobject.c:float_richcompare, assuming: */
2082 assert(v->ob_type == w->ob_type);
2083 assert(v->ob_type == &PyFloat_Type);
2084
2085 res = PyFloat_AS_DOUBLE(v) < PyFloat_AS_DOUBLE(w);
2086 assert(res == PyObject_RichCompareBool(v, w, Py_LT));
2087 return res;
2088}
2089
2090/* Tuple compare: compare *any* two tuples, using
2091 * ms->tuple_elem_compare to compare the first elements, which is set
2092 * using the same pre-sort check as we use for ms->key_compare,
2093 * but run on the list [x[0] for x in L]. This allows us to optimize compares
2094 * on two levels (as long as [x[0] for x in L] is type-homogeneous.) The idea is
2095 * that most tuple compares don't involve x[1:]. */
2096static int
2097unsafe_tuple_compare(PyObject *v, PyObject *w, MergeState *ms)
2098{
2099 PyTupleObject *vt, *wt;
2100 Py_ssize_t i, vlen, wlen;
2101 int k;
2102
2103 /* Modified from Objects/tupleobject.c:tuplerichcompare, assuming: */
2104 assert(v->ob_type == w->ob_type);
2105 assert(v->ob_type == &PyTuple_Type);
2106 assert(Py_SIZE(v) > 0);
2107 assert(Py_SIZE(w) > 0);
2108
2109 vt = (PyTupleObject *)v;
2110 wt = (PyTupleObject *)w;
2111
2112 vlen = Py_SIZE(vt);
2113 wlen = Py_SIZE(wt);
2114
2115 for (i = 0; i < vlen && i < wlen; i++) {
2116 k = PyObject_RichCompareBool(vt->ob_item[i], wt->ob_item[i], Py_EQ);
2117 if (k < 0)
2118 return -1;
2119 if (!k)
2120 break;
2121 }
2122
2123 if (i >= vlen || i >= wlen)
2124 return vlen < wlen;
2125
2126 if (i == 0)
2127 return ms->tuple_elem_compare(vt->ob_item[i], wt->ob_item[i], ms);
2128 else
2129 return PyObject_RichCompareBool(vt->ob_item[i], wt->ob_item[i], Py_LT);
2130}
2131
Tim Petersa64dc242002-08-01 02:13:36 +00002132/* An adaptive, stable, natural mergesort. See listsort.txt.
2133 * Returns Py_None on success, NULL on error. Even in case of error, the
2134 * list will be some permutation of its input state (nothing is lost or
2135 * duplicated).
2136 */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002137/*[clinic input]
2138list.sort
2139
2140 *
2141 key as keyfunc: object = None
Serhiy Storchaka202fda52017-03-12 10:10:47 +02002142 reverse: bool(accept={int}) = False
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002143
2144Stable sort *IN PLACE*.
2145[clinic start generated code]*/
2146
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002147static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002148list_sort_impl(PyListObject *self, PyObject *keyfunc, int reverse)
Serhiy Storchaka202fda52017-03-12 10:10:47 +02002149/*[clinic end generated code: output=57b9f9c5e23fbe42 input=b0fcf743982c5b90]*/
Guido van Rossum3f236de1996-12-10 23:55:39 +00002150{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002151 MergeState ms;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002152 Py_ssize_t nremaining;
2153 Py_ssize_t minrun;
Daniel Stutzbach98338222010-12-02 21:55:33 +00002154 sortslice lo;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002155 Py_ssize_t saved_ob_size, saved_allocated;
2156 PyObject **saved_ob_item;
2157 PyObject **final_ob_item;
2158 PyObject *result = NULL; /* guilty until proved innocent */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002159 Py_ssize_t i;
Daniel Stutzbach98338222010-12-02 21:55:33 +00002160 PyObject **keys;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002161
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002162 assert(self != NULL);
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002163 assert(PyList_Check(self));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002164 if (keyfunc == Py_None)
2165 keyfunc = NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002167 /* The list is temporarily made empty, so that mutations performed
2168 * by comparison functions can't affect the slice of memory we're
2169 * sorting (allowing mutations during sorting is a core-dump
2170 * factory, since ob_item may change).
2171 */
2172 saved_ob_size = Py_SIZE(self);
2173 saved_ob_item = self->ob_item;
2174 saved_allocated = self->allocated;
2175 Py_SIZE(self) = 0;
2176 self->ob_item = NULL;
2177 self->allocated = -1; /* any operation will reset it to >= 0 */
Tim Peters330f9e92002-07-19 07:05:44 +00002178
Daniel Stutzbach98338222010-12-02 21:55:33 +00002179 if (keyfunc == NULL) {
2180 keys = NULL;
2181 lo.keys = saved_ob_item;
2182 lo.values = NULL;
2183 }
2184 else {
2185 if (saved_ob_size < MERGESTATE_TEMP_SIZE/2)
2186 /* Leverage stack space we allocated but won't otherwise use */
2187 keys = &ms.temparray[saved_ob_size+1];
2188 else {
2189 keys = PyMem_MALLOC(sizeof(PyObject *) * saved_ob_size);
Benjamin Peterson0823ffb2015-04-23 17:04:36 -04002190 if (keys == NULL) {
2191 PyErr_NoMemory();
2192 goto keyfunc_fail;
2193 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002194 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00002195
2196 for (i = 0; i < saved_ob_size ; i++) {
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01002197 keys[i] = PyObject_CallFunctionObjArgs(keyfunc, saved_ob_item[i],
2198 NULL);
Daniel Stutzbach98338222010-12-02 21:55:33 +00002199 if (keys[i] == NULL) {
2200 for (i=i-1 ; i>=0 ; i--)
2201 Py_DECREF(keys[i]);
Benjamin Peterson4a42cd42014-03-15 12:21:28 -05002202 if (saved_ob_size >= MERGESTATE_TEMP_SIZE/2)
Daniel Stutzbach8eda5f72011-03-02 23:37:50 +00002203 PyMem_FREE(keys);
Daniel Stutzbach98338222010-12-02 21:55:33 +00002204 goto keyfunc_fail;
2205 }
2206 }
2207
2208 lo.keys = keys;
2209 lo.values = saved_ob_item;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002210 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002211
embg1e34da42018-01-28 20:03:23 -07002212
2213 /* The pre-sort check: here's where we decide which compare function to use.
2214 * How much optimization is safe? We test for homogeneity with respect to
2215 * several properties that are expensive to check at compare-time, and
2216 * set ms appropriately. */
2217 if (saved_ob_size > 1) {
2218 /* Assume the first element is representative of the whole list. */
2219 int keys_are_in_tuples = (lo.keys[0]->ob_type == &PyTuple_Type &&
2220 Py_SIZE(lo.keys[0]) > 0);
2221
2222 PyTypeObject* key_type = (keys_are_in_tuples ?
2223 PyTuple_GET_ITEM(lo.keys[0], 0)->ob_type :
2224 lo.keys[0]->ob_type);
2225
2226 int keys_are_all_same_type = 1;
2227 int strings_are_latin = 1;
2228 int ints_are_bounded = 1;
2229
2230 /* Prove that assumption by checking every key. */
embg1e34da42018-01-28 20:03:23 -07002231 for (i=0; i < saved_ob_size; i++) {
2232
2233 if (keys_are_in_tuples &&
2234 !(lo.keys[i]->ob_type == &PyTuple_Type && Py_SIZE(lo.keys[i]) != 0)) {
2235 keys_are_in_tuples = 0;
2236 keys_are_all_same_type = 0;
2237 break;
2238 }
2239
2240 /* Note: for lists of tuples, key is the first element of the tuple
2241 * lo.keys[i], not lo.keys[i] itself! We verify type-homogeneity
2242 * for lists of tuples in the if-statement directly above. */
2243 PyObject *key = (keys_are_in_tuples ?
2244 PyTuple_GET_ITEM(lo.keys[i], 0) :
2245 lo.keys[i]);
2246
2247 if (key->ob_type != key_type) {
2248 keys_are_all_same_type = 0;
Miss Islington (bot)9dbb09f2019-03-25 00:47:55 -07002249 /* If keys are in tuple we must loop over the whole list to make
2250 sure all items are tuples */
2251 if (!keys_are_in_tuples) {
2252 break;
2253 }
embg1e34da42018-01-28 20:03:23 -07002254 }
2255
Miss Islington (bot)9dbb09f2019-03-25 00:47:55 -07002256 if (keys_are_all_same_type) {
2257 if (key_type == &PyLong_Type &&
2258 ints_are_bounded &&
2259 Py_ABS(Py_SIZE(key)) > 1) {
2260
embg1e34da42018-01-28 20:03:23 -07002261 ints_are_bounded = 0;
Miss Islington (bot)9dbb09f2019-03-25 00:47:55 -07002262 }
2263 else if (key_type == &PyUnicode_Type &&
2264 strings_are_latin &&
2265 PyUnicode_KIND(key) != PyUnicode_1BYTE_KIND) {
2266
2267 strings_are_latin = 0;
2268 }
2269 }
embg1e34da42018-01-28 20:03:23 -07002270 }
embg1e34da42018-01-28 20:03:23 -07002271
2272 /* Choose the best compare, given what we now know about the keys. */
2273 if (keys_are_all_same_type) {
2274
2275 if (key_type == &PyUnicode_Type && strings_are_latin) {
2276 ms.key_compare = unsafe_latin_compare;
2277 }
2278 else if (key_type == &PyLong_Type && ints_are_bounded) {
2279 ms.key_compare = unsafe_long_compare;
2280 }
2281 else if (key_type == &PyFloat_Type) {
2282 ms.key_compare = unsafe_float_compare;
2283 }
2284 else if ((ms.key_richcompare = key_type->tp_richcompare) != NULL) {
2285 ms.key_compare = unsafe_object_compare;
2286 }
Miss Islington (bot)0e73ea22019-02-21 00:05:22 -08002287 else {
2288 ms.key_compare = safe_object_compare;
2289 }
embg1e34da42018-01-28 20:03:23 -07002290 }
2291 else {
2292 ms.key_compare = safe_object_compare;
2293 }
2294
2295 if (keys_are_in_tuples) {
2296 /* Make sure we're not dealing with tuples of tuples
2297 * (remember: here, key_type refers list [key[0] for key in keys]) */
Miss Islington (bot)9dbb09f2019-03-25 00:47:55 -07002298 if (key_type == &PyTuple_Type) {
embg1e34da42018-01-28 20:03:23 -07002299 ms.tuple_elem_compare = safe_object_compare;
Miss Islington (bot)9dbb09f2019-03-25 00:47:55 -07002300 }
2301 else {
embg1e34da42018-01-28 20:03:23 -07002302 ms.tuple_elem_compare = ms.key_compare;
Miss Islington (bot)9dbb09f2019-03-25 00:47:55 -07002303 }
embg1e34da42018-01-28 20:03:23 -07002304
2305 ms.key_compare = unsafe_tuple_compare;
2306 }
2307 }
2308 /* End of pre-sort check: ms is now set properly! */
2309
Daniel Stutzbach98338222010-12-02 21:55:33 +00002310 merge_init(&ms, saved_ob_size, keys != NULL);
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002312 nremaining = saved_ob_size;
2313 if (nremaining < 2)
2314 goto succeed;
Tim Peters330f9e92002-07-19 07:05:44 +00002315
Benjamin Peterson05380642010-08-23 19:35:39 +00002316 /* Reverse sort stability achieved by initially reversing the list,
2317 applying a stable forward sort, then reversing the final result. */
Daniel Stutzbach98338222010-12-02 21:55:33 +00002318 if (reverse) {
2319 if (keys != NULL)
2320 reverse_slice(&keys[0], &keys[saved_ob_size]);
2321 reverse_slice(&saved_ob_item[0], &saved_ob_item[saved_ob_size]);
2322 }
Benjamin Peterson05380642010-08-23 19:35:39 +00002323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002324 /* March over the array once, left to right, finding natural runs,
2325 * and extending short natural runs to minrun elements.
2326 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002327 minrun = merge_compute_minrun(nremaining);
2328 do {
2329 int descending;
2330 Py_ssize_t n;
Tim Peters330f9e92002-07-19 07:05:44 +00002331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002332 /* Identify next run. */
embg1e34da42018-01-28 20:03:23 -07002333 n = count_run(&ms, lo.keys, lo.keys + nremaining, &descending);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002334 if (n < 0)
2335 goto fail;
2336 if (descending)
Daniel Stutzbach98338222010-12-02 21:55:33 +00002337 reverse_sortslice(&lo, n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002338 /* If short, extend to min(minrun, nremaining). */
2339 if (n < minrun) {
2340 const Py_ssize_t force = nremaining <= minrun ?
2341 nremaining : minrun;
embg1e34da42018-01-28 20:03:23 -07002342 if (binarysort(&ms, lo, lo.keys + force, lo.keys + n) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002343 goto fail;
2344 n = force;
2345 }
2346 /* Push run onto pending-runs stack, and maybe merge. */
2347 assert(ms.n < MAX_MERGE_PENDING);
2348 ms.pending[ms.n].base = lo;
2349 ms.pending[ms.n].len = n;
2350 ++ms.n;
2351 if (merge_collapse(&ms) < 0)
2352 goto fail;
2353 /* Advance to find next run. */
Daniel Stutzbach98338222010-12-02 21:55:33 +00002354 sortslice_advance(&lo, n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002355 nremaining -= n;
2356 } while (nremaining);
Tim Peters330f9e92002-07-19 07:05:44 +00002357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002358 if (merge_force_collapse(&ms) < 0)
2359 goto fail;
2360 assert(ms.n == 1);
Daniel Stutzbach98338222010-12-02 21:55:33 +00002361 assert(keys == NULL
2362 ? ms.pending[0].base.keys == saved_ob_item
2363 : ms.pending[0].base.keys == &keys[0]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002364 assert(ms.pending[0].len == saved_ob_size);
Daniel Stutzbach98338222010-12-02 21:55:33 +00002365 lo = ms.pending[0].base;
Tim Petersa64dc242002-08-01 02:13:36 +00002366
2367succeed:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002368 result = Py_None;
Tim Peters330f9e92002-07-19 07:05:44 +00002369fail:
Daniel Stutzbach98338222010-12-02 21:55:33 +00002370 if (keys != NULL) {
2371 for (i = 0; i < saved_ob_size; i++)
2372 Py_DECREF(keys[i]);
Benjamin Petersonef87f8c2014-03-14 21:54:31 -05002373 if (saved_ob_size >= MERGESTATE_TEMP_SIZE/2)
Daniel Stutzbach98338222010-12-02 21:55:33 +00002374 PyMem_FREE(keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002375 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002377 if (self->allocated != -1 && result != NULL) {
2378 /* The user mucked with the list during the sort,
2379 * and we don't already have another error to report.
2380 */
2381 PyErr_SetString(PyExc_ValueError, "list modified during sort");
2382 result = NULL;
2383 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002385 if (reverse && saved_ob_size > 1)
2386 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002388 merge_freemem(&ms);
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002389
Daniel Stutzbach98338222010-12-02 21:55:33 +00002390keyfunc_fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002391 final_ob_item = self->ob_item;
2392 i = Py_SIZE(self);
2393 Py_SIZE(self) = saved_ob_size;
2394 self->ob_item = saved_ob_item;
2395 self->allocated = saved_allocated;
2396 if (final_ob_item != NULL) {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002397 /* we cannot use _list_clear() for this because it does not
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002398 guarantee that the list is really empty when it returns */
2399 while (--i >= 0) {
2400 Py_XDECREF(final_ob_item[i]);
2401 }
2402 PyMem_FREE(final_ob_item);
2403 }
2404 Py_XINCREF(result);
2405 return result;
Guido van Rossum3f236de1996-12-10 23:55:39 +00002406}
Tim Peters330f9e92002-07-19 07:05:44 +00002407#undef IFLT
Tim Peters66860f62002-08-04 17:47:26 +00002408#undef ISLT
Tim Peters330f9e92002-07-19 07:05:44 +00002409
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002410int
Fred Drakea2f55112000-07-09 15:16:51 +00002411PyList_Sort(PyObject *v)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002412{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002413 if (v == NULL || !PyList_Check(v)) {
2414 PyErr_BadInternalCall();
2415 return -1;
2416 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002417 v = list_sort_impl((PyListObject *)v, NULL, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002418 if (v == NULL)
2419 return -1;
2420 Py_DECREF(v);
2421 return 0;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002422}
2423
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002424/*[clinic input]
2425list.reverse
2426
2427Reverse *IN PLACE*.
2428[clinic start generated code]*/
2429
Guido van Rossumb86c5492001-02-12 22:06:02 +00002430static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002431list_reverse_impl(PyListObject *self)
2432/*[clinic end generated code: output=482544fc451abea9 input=eefd4c3ae1bc9887]*/
Guido van Rossumb86c5492001-02-12 22:06:02 +00002433{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002434 if (Py_SIZE(self) > 1)
2435 reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
2436 Py_RETURN_NONE;
Guido van Rossumed98d481991-03-06 13:07:53 +00002437}
2438
Guido van Rossum84c76f51990-10-30 13:32:20 +00002439int
Fred Drakea2f55112000-07-09 15:16:51 +00002440PyList_Reverse(PyObject *v)
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002441{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002442 PyListObject *self = (PyListObject *)v;
Tim Peters6063e262002-08-08 01:06:39 +00002443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002444 if (v == NULL || !PyList_Check(v)) {
2445 PyErr_BadInternalCall();
2446 return -1;
2447 }
2448 if (Py_SIZE(self) > 1)
2449 reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
2450 return 0;
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002451}
2452
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002453PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00002454PyList_AsTuple(PyObject *v)
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002455{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002456 PyObject *w;
2457 PyObject **p, **q;
2458 Py_ssize_t n;
2459 if (v == NULL || !PyList_Check(v)) {
2460 PyErr_BadInternalCall();
2461 return NULL;
2462 }
2463 n = Py_SIZE(v);
2464 w = PyTuple_New(n);
2465 if (w == NULL)
2466 return NULL;
2467 p = ((PyTupleObject *)w)->ob_item;
2468 q = ((PyListObject *)v)->ob_item;
2469 while (--n >= 0) {
2470 Py_INCREF(*q);
2471 *p = *q;
2472 p++;
2473 q++;
2474 }
2475 return w;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002476}
2477
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002478/*[clinic input]
2479list.index
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002480
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002481 value: object
Serhiy Storchaka80ec8362017-03-19 19:37:40 +02002482 start: slice_index(accept={int}) = 0
2483 stop: slice_index(accept={int}, c_default="PY_SSIZE_T_MAX") = sys.maxsize
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002484 /
2485
2486Return first index of value.
2487
2488Raises ValueError if the value is not present.
2489[clinic start generated code]*/
2490
2491static PyObject *
2492list_index_impl(PyListObject *self, PyObject *value, Py_ssize_t start,
2493 Py_ssize_t stop)
Serhiy Storchaka80ec8362017-03-19 19:37:40 +02002494/*[clinic end generated code: output=ec51b88787e4e481 input=40ec5826303a0eb1]*/
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002495{
2496 Py_ssize_t i;
2497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002498 if (start < 0) {
2499 start += Py_SIZE(self);
2500 if (start < 0)
2501 start = 0;
2502 }
2503 if (stop < 0) {
2504 stop += Py_SIZE(self);
2505 if (stop < 0)
2506 stop = 0;
2507 }
2508 for (i = start; i < stop && i < Py_SIZE(self); i++) {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002509 int cmp = PyObject_RichCompareBool(self->ob_item[i], value, Py_EQ);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002510 if (cmp > 0)
2511 return PyLong_FromSsize_t(i);
2512 else if (cmp < 0)
2513 return NULL;
2514 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002515 PyErr_Format(PyExc_ValueError, "%R is not in list", value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002516 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002517}
2518
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002519/*[clinic input]
2520list.count
2521
2522 value: object
2523 /
2524
2525Return number of occurrences of value.
2526[clinic start generated code]*/
2527
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002528static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002529list_count(PyListObject *self, PyObject *value)
2530/*[clinic end generated code: output=b1f5d284205ae714 input=3bdc3a5e6f749565]*/
Guido van Rossume6f7d181991-10-20 20:20:40 +00002531{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002532 Py_ssize_t count = 0;
2533 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002535 for (i = 0; i < Py_SIZE(self); i++) {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002536 int cmp = PyObject_RichCompareBool(self->ob_item[i], value, Py_EQ);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002537 if (cmp > 0)
2538 count++;
2539 else if (cmp < 0)
2540 return NULL;
2541 }
2542 return PyLong_FromSsize_t(count);
Guido van Rossume6f7d181991-10-20 20:20:40 +00002543}
2544
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002545/*[clinic input]
2546list.remove
2547
2548 value: object
2549 /
2550
2551Remove first occurrence of value.
2552
2553Raises ValueError if the value is not present.
2554[clinic start generated code]*/
2555
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002556static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002557list_remove(PyListObject *self, PyObject *value)
2558/*[clinic end generated code: output=f087e1951a5e30d1 input=2dc2ba5bb2fb1f82]*/
Guido van Rossumed98d481991-03-06 13:07:53 +00002559{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002560 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002562 for (i = 0; i < Py_SIZE(self); i++) {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002563 int cmp = PyObject_RichCompareBool(self->ob_item[i], value, Py_EQ);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002564 if (cmp > 0) {
2565 if (list_ass_slice(self, i, i+1,
2566 (PyObject *)NULL) == 0)
2567 Py_RETURN_NONE;
2568 return NULL;
2569 }
2570 else if (cmp < 0)
2571 return NULL;
2572 }
2573 PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
2574 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002575}
2576
Jeremy Hylton8caad492000-06-23 14:18:11 +00002577static int
2578list_traverse(PyListObject *o, visitproc visit, void *arg)
2579{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002580 Py_ssize_t i;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002581
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002582 for (i = Py_SIZE(o); --i >= 0; )
2583 Py_VISIT(o->ob_item[i]);
2584 return 0;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002585}
2586
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002587static PyObject *
2588list_richcompare(PyObject *v, PyObject *w, int op)
2589{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002590 PyListObject *vl, *wl;
2591 Py_ssize_t i;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002592
Brian Curtindfc80e32011-08-10 20:28:54 -05002593 if (!PyList_Check(v) || !PyList_Check(w))
2594 Py_RETURN_NOTIMPLEMENTED;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002596 vl = (PyListObject *)v;
2597 wl = (PyListObject *)w;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002599 if (Py_SIZE(vl) != Py_SIZE(wl) && (op == Py_EQ || op == Py_NE)) {
2600 /* Shortcut: if the lengths differ, the lists differ */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002601 if (op == Py_EQ)
stratakise8b19652017-11-02 11:32:54 +01002602 Py_RETURN_FALSE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002603 else
stratakise8b19652017-11-02 11:32:54 +01002604 Py_RETURN_TRUE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002605 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002607 /* Search for the first index where items are different */
2608 for (i = 0; i < Py_SIZE(vl) && i < Py_SIZE(wl); i++) {
2609 int k = PyObject_RichCompareBool(vl->ob_item[i],
2610 wl->ob_item[i], Py_EQ);
2611 if (k < 0)
2612 return NULL;
2613 if (!k)
2614 break;
2615 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002617 if (i >= Py_SIZE(vl) || i >= Py_SIZE(wl)) {
2618 /* No more items to compare -- compare sizes */
stratakise8b19652017-11-02 11:32:54 +01002619 Py_RETURN_RICHCOMPARE(Py_SIZE(vl), Py_SIZE(wl), op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002620 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002622 /* We have an item that differs -- shortcuts for EQ/NE */
2623 if (op == Py_EQ) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02002624 Py_RETURN_FALSE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002625 }
2626 if (op == Py_NE) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02002627 Py_RETURN_TRUE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002628 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002630 /* Compare the final item again using the proper operator */
2631 return PyObject_RichCompare(vl->ob_item[i], wl->ob_item[i], op);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002632}
2633
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002634/*[clinic input]
2635list.__init__
2636
2637 iterable: object(c_default="NULL") = ()
2638 /
2639
2640Built-in mutable sequence.
2641
2642If no argument is given, the constructor creates a new empty list.
2643The argument must be an iterable if specified.
2644[clinic start generated code]*/
2645
Tim Peters6d6c1a32001-08-02 04:15:00 +00002646static int
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002647list___init___impl(PyListObject *self, PyObject *iterable)
2648/*[clinic end generated code: output=0f3c21379d01de48 input=b3f3fe7206af8f6b]*/
Tim Peters6d6c1a32001-08-02 04:15:00 +00002649{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002650 /* Verify list invariants established by PyType_GenericAlloc() */
2651 assert(0 <= Py_SIZE(self));
2652 assert(Py_SIZE(self) <= self->allocated || self->allocated == -1);
2653 assert(self->ob_item != NULL ||
2654 self->allocated == 0 || self->allocated == -1);
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002655
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002656 /* Empty previous contents */
2657 if (self->ob_item != NULL) {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002658 (void)_list_clear(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002659 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002660 if (iterable != NULL) {
2661 PyObject *rv = list_extend(self, iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002662 if (rv == NULL)
2663 return -1;
2664 Py_DECREF(rv);
2665 }
2666 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002667}
2668
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002669/*[clinic input]
2670list.__sizeof__
2671
2672Return the size of the list in memory, in bytes.
2673[clinic start generated code]*/
2674
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002675static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002676list___sizeof___impl(PyListObject *self)
2677/*[clinic end generated code: output=3417541f95f9a53e input=b8030a5d5ce8a187]*/
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002678{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002679 Py_ssize_t res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002680
Serhiy Storchaka5c4064e2015-12-19 20:05:25 +02002681 res = _PyObject_SIZE(Py_TYPE(self)) + self->allocated * sizeof(void*);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002682 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002683}
2684
Raymond Hettinger1021c442003-11-07 15:38:09 +00002685static PyObject *list_iter(PyObject *seq);
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002686static PyObject *list_subscript(PyListObject*, PyObject*);
2687
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002688static PyMethodDef list_methods[] = {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002689 {"__getitem__", (PyCFunction)list_subscript, METH_O|METH_COEXIST, "x.__getitem__(y) <==> x[y]"},
2690 LIST___REVERSED___METHODDEF
2691 LIST___SIZEOF___METHODDEF
2692 LIST_CLEAR_METHODDEF
2693 LIST_COPY_METHODDEF
2694 LIST_APPEND_METHODDEF
2695 LIST_INSERT_METHODDEF
2696 LIST_EXTEND_METHODDEF
2697 LIST_POP_METHODDEF
2698 LIST_REMOVE_METHODDEF
2699 LIST_INDEX_METHODDEF
2700 LIST_COUNT_METHODDEF
2701 LIST_REVERSE_METHODDEF
2702 LIST_SORT_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002703 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002704};
2705
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002706static PySequenceMethods list_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002707 (lenfunc)list_length, /* sq_length */
2708 (binaryfunc)list_concat, /* sq_concat */
2709 (ssizeargfunc)list_repeat, /* sq_repeat */
2710 (ssizeargfunc)list_item, /* sq_item */
2711 0, /* sq_slice */
2712 (ssizeobjargproc)list_ass_item, /* sq_ass_item */
2713 0, /* sq_ass_slice */
2714 (objobjproc)list_contains, /* sq_contains */
2715 (binaryfunc)list_inplace_concat, /* sq_inplace_concat */
2716 (ssizeargfunc)list_inplace_repeat, /* sq_inplace_repeat */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002717};
2718
Jeremy Hyltona4b4c3b2002-07-13 03:51:17 +00002719static PyObject *
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002720list_subscript(PyListObject* self, PyObject* item)
2721{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002722 if (PyIndex_Check(item)) {
2723 Py_ssize_t i;
2724 i = PyNumber_AsSsize_t(item, PyExc_IndexError);
2725 if (i == -1 && PyErr_Occurred())
2726 return NULL;
2727 if (i < 0)
2728 i += PyList_GET_SIZE(self);
2729 return list_item(self, i);
2730 }
2731 else if (PySlice_Check(item)) {
2732 Py_ssize_t start, stop, step, slicelength, cur, i;
2733 PyObject* result;
2734 PyObject* it;
2735 PyObject **src, **dest;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002736
Serhiy Storchakab879fe82017-04-08 09:53:51 +03002737 if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002738 return NULL;
2739 }
Serhiy Storchakab879fe82017-04-08 09:53:51 +03002740 slicelength = PySlice_AdjustIndices(Py_SIZE(self), &start, &stop,
2741 step);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002742
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002743 if (slicelength <= 0) {
2744 return PyList_New(0);
2745 }
2746 else if (step == 1) {
2747 return list_slice(self, start, stop);
2748 }
2749 else {
2750 result = PyList_New(slicelength);
2751 if (!result) return NULL;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002752
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002753 src = self->ob_item;
2754 dest = ((PyListObject *)result)->ob_item;
2755 for (cur = start, i = 0; i < slicelength;
Mark Dickinsonc7d93b72011-09-25 15:34:32 +01002756 cur += (size_t)step, i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002757 it = src[cur];
2758 Py_INCREF(it);
2759 dest[i] = it;
2760 }
Tim Peters3b01a122002-07-19 02:35:45 +00002761
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002762 return result;
2763 }
2764 }
2765 else {
2766 PyErr_Format(PyExc_TypeError,
Terry Jan Reedyffff1442014-08-02 01:30:37 -04002767 "list indices must be integers or slices, not %.200s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002768 item->ob_type->tp_name);
2769 return NULL;
2770 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002771}
2772
Tim Peters3b01a122002-07-19 02:35:45 +00002773static int
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002774list_ass_subscript(PyListObject* self, PyObject* item, PyObject* value)
2775{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002776 if (PyIndex_Check(item)) {
2777 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
2778 if (i == -1 && PyErr_Occurred())
2779 return -1;
2780 if (i < 0)
2781 i += PyList_GET_SIZE(self);
2782 return list_ass_item(self, i, value);
2783 }
2784 else if (PySlice_Check(item)) {
2785 Py_ssize_t start, stop, step, slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002786
Serhiy Storchakab879fe82017-04-08 09:53:51 +03002787 if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002788 return -1;
2789 }
Serhiy Storchakab879fe82017-04-08 09:53:51 +03002790 slicelength = PySlice_AdjustIndices(Py_SIZE(self), &start, &stop,
2791 step);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002792
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002793 if (step == 1)
2794 return list_ass_slice(self, start, stop, value);
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002796 /* Make sure s[5:2] = [..] inserts at the right place:
2797 before 5, not before 2. */
2798 if ((step < 0 && start < stop) ||
2799 (step > 0 && start > stop))
2800 stop = start;
Thomas Woutersed03b412007-08-28 21:37:11 +00002801
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002802 if (value == NULL) {
2803 /* delete slice */
2804 PyObject **garbage;
2805 size_t cur;
2806 Py_ssize_t i;
Victor Stinner35f28032013-11-21 12:16:35 +01002807 int res;
Tim Peters3b01a122002-07-19 02:35:45 +00002808
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002809 if (slicelength <= 0)
2810 return 0;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002811
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002812 if (step < 0) {
2813 stop = start + 1;
2814 start = stop + step*(slicelength - 1) - 1;
2815 step = -step;
2816 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002817
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002818 garbage = (PyObject**)
2819 PyMem_MALLOC(slicelength*sizeof(PyObject*));
2820 if (!garbage) {
2821 PyErr_NoMemory();
2822 return -1;
2823 }
Tim Peters3b01a122002-07-19 02:35:45 +00002824
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002825 /* drawing pictures might help understand these for
2826 loops. Basically, we memmove the parts of the
2827 list that are *not* part of the slice: step-1
2828 items for each item that is part of the slice,
2829 and then tail end of the list that was not
2830 covered by the slice */
2831 for (cur = start, i = 0;
2832 cur < (size_t)stop;
2833 cur += step, i++) {
2834 Py_ssize_t lim = step - 1;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002836 garbage[i] = PyList_GET_ITEM(self, cur);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002838 if (cur + step >= (size_t)Py_SIZE(self)) {
2839 lim = Py_SIZE(self) - cur - 1;
2840 }
Michael W. Hudson56796f62002-07-29 14:35:04 +00002841
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002842 memmove(self->ob_item + cur - i,
2843 self->ob_item + cur + 1,
2844 lim * sizeof(PyObject *));
2845 }
Mark Dickinsonc7d93b72011-09-25 15:34:32 +01002846 cur = start + (size_t)slicelength * step;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002847 if (cur < (size_t)Py_SIZE(self)) {
2848 memmove(self->ob_item + cur - slicelength,
2849 self->ob_item + cur,
2850 (Py_SIZE(self) - cur) *
2851 sizeof(PyObject *));
2852 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002853
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002854 Py_SIZE(self) -= slicelength;
Victor Stinner35f28032013-11-21 12:16:35 +01002855 res = list_resize(self, Py_SIZE(self));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002856
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002857 for (i = 0; i < slicelength; i++) {
2858 Py_DECREF(garbage[i]);
2859 }
2860 PyMem_FREE(garbage);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002861
Victor Stinner35f28032013-11-21 12:16:35 +01002862 return res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002863 }
2864 else {
2865 /* assign slice */
2866 PyObject *ins, *seq;
2867 PyObject **garbage, **seqitems, **selfitems;
2868 Py_ssize_t cur, i;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002870 /* protect against a[::-1] = a */
2871 if (self == (PyListObject*)value) {
2872 seq = list_slice((PyListObject*)value, 0,
2873 PyList_GET_SIZE(value));
2874 }
2875 else {
2876 seq = PySequence_Fast(value,
2877 "must assign iterable "
2878 "to extended slice");
2879 }
2880 if (!seq)
2881 return -1;
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002883 if (PySequence_Fast_GET_SIZE(seq) != slicelength) {
2884 PyErr_Format(PyExc_ValueError,
2885 "attempt to assign sequence of "
2886 "size %zd to extended slice of "
2887 "size %zd",
2888 PySequence_Fast_GET_SIZE(seq),
2889 slicelength);
2890 Py_DECREF(seq);
2891 return -1;
2892 }
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002894 if (!slicelength) {
2895 Py_DECREF(seq);
2896 return 0;
2897 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002899 garbage = (PyObject**)
2900 PyMem_MALLOC(slicelength*sizeof(PyObject*));
2901 if (!garbage) {
2902 Py_DECREF(seq);
2903 PyErr_NoMemory();
2904 return -1;
2905 }
Tim Peters3b01a122002-07-19 02:35:45 +00002906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002907 selfitems = self->ob_item;
2908 seqitems = PySequence_Fast_ITEMS(seq);
2909 for (cur = start, i = 0; i < slicelength;
Mark Dickinsonc7d93b72011-09-25 15:34:32 +01002910 cur += (size_t)step, i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002911 garbage[i] = selfitems[cur];
2912 ins = seqitems[i];
2913 Py_INCREF(ins);
2914 selfitems[cur] = ins;
2915 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002916
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002917 for (i = 0; i < slicelength; i++) {
2918 Py_DECREF(garbage[i]);
2919 }
Tim Peters3b01a122002-07-19 02:35:45 +00002920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002921 PyMem_FREE(garbage);
2922 Py_DECREF(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002924 return 0;
2925 }
2926 }
2927 else {
2928 PyErr_Format(PyExc_TypeError,
Terry Jan Reedyffff1442014-08-02 01:30:37 -04002929 "list indices must be integers or slices, not %.200s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002930 item->ob_type->tp_name);
2931 return -1;
2932 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002933}
2934
2935static PyMappingMethods list_as_mapping = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002936 (lenfunc)list_length,
2937 (binaryfunc)list_subscript,
2938 (objobjargproc)list_ass_subscript
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002939};
2940
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002941PyTypeObject PyList_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002942 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2943 "list",
2944 sizeof(PyListObject),
2945 0,
2946 (destructor)list_dealloc, /* tp_dealloc */
2947 0, /* tp_print */
2948 0, /* tp_getattr */
2949 0, /* tp_setattr */
2950 0, /* tp_reserved */
2951 (reprfunc)list_repr, /* tp_repr */
2952 0, /* tp_as_number */
2953 &list_as_sequence, /* tp_as_sequence */
2954 &list_as_mapping, /* tp_as_mapping */
Georg Brandl00da4e02010-10-18 07:32:48 +00002955 PyObject_HashNotImplemented, /* tp_hash */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002956 0, /* tp_call */
2957 0, /* tp_str */
2958 PyObject_GenericGetAttr, /* tp_getattro */
2959 0, /* tp_setattro */
2960 0, /* tp_as_buffer */
2961 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002962 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LIST_SUBCLASS, /* tp_flags */
2963 list___init____doc__, /* tp_doc */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002964 (traverseproc)list_traverse, /* tp_traverse */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002965 (inquiry)_list_clear, /* tp_clear */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002966 list_richcompare, /* tp_richcompare */
2967 0, /* tp_weaklistoffset */
2968 list_iter, /* tp_iter */
2969 0, /* tp_iternext */
2970 list_methods, /* tp_methods */
2971 0, /* tp_members */
2972 0, /* tp_getset */
2973 0, /* tp_base */
2974 0, /* tp_dict */
2975 0, /* tp_descr_get */
2976 0, /* tp_descr_set */
2977 0, /* tp_dictoffset */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002978 (initproc)list___init__, /* tp_init */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002979 PyType_GenericAlloc, /* tp_alloc */
2980 PyType_GenericNew, /* tp_new */
2981 PyObject_GC_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002982};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002983
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002984/*********************** List Iterator **************************/
2985
2986typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002987 PyObject_HEAD
Victor Stinner7660b882013-06-24 23:59:24 +02002988 Py_ssize_t it_index;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002989 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002990} listiterobject;
2991
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002992static void listiter_dealloc(listiterobject *);
2993static int listiter_traverse(listiterobject *, visitproc, void *);
2994static PyObject *listiter_next(listiterobject *);
2995static PyObject *listiter_len(listiterobject *);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002996static PyObject *listiter_reduce_general(void *_it, int forward);
2997static PyObject *listiter_reduce(listiterobject *);
2998static PyObject *listiter_setstate(listiterobject *, PyObject *state);
Raymond Hettinger435bf582004-03-18 22:43:10 +00002999
Armin Rigof5b3e362006-02-11 21:32:43 +00003000PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003001PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
3002PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00003003
3004static PyMethodDef listiter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003005 {"__length_hint__", (PyCFunction)listiter_len, METH_NOARGS, length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003006 {"__reduce__", (PyCFunction)listiter_reduce, METH_NOARGS, reduce_doc},
3007 {"__setstate__", (PyCFunction)listiter_setstate, METH_O, setstate_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003008 {NULL, NULL} /* sentinel */
Raymond Hettinger435bf582004-03-18 22:43:10 +00003009};
3010
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00003011PyTypeObject PyListIter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003012 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3013 "list_iterator", /* tp_name */
3014 sizeof(listiterobject), /* tp_basicsize */
3015 0, /* tp_itemsize */
3016 /* methods */
3017 (destructor)listiter_dealloc, /* tp_dealloc */
3018 0, /* tp_print */
3019 0, /* tp_getattr */
3020 0, /* tp_setattr */
3021 0, /* tp_reserved */
3022 0, /* tp_repr */
3023 0, /* tp_as_number */
3024 0, /* tp_as_sequence */
3025 0, /* tp_as_mapping */
3026 0, /* tp_hash */
3027 0, /* tp_call */
3028 0, /* tp_str */
3029 PyObject_GenericGetAttr, /* tp_getattro */
3030 0, /* tp_setattro */
3031 0, /* tp_as_buffer */
3032 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3033 0, /* tp_doc */
3034 (traverseproc)listiter_traverse, /* tp_traverse */
3035 0, /* tp_clear */
3036 0, /* tp_richcompare */
3037 0, /* tp_weaklistoffset */
3038 PyObject_SelfIter, /* tp_iter */
3039 (iternextfunc)listiter_next, /* tp_iternext */
3040 listiter_methods, /* tp_methods */
3041 0, /* tp_members */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00003042};
Raymond Hettinger1021c442003-11-07 15:38:09 +00003043
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003044
3045static PyObject *
3046list_iter(PyObject *seq)
3047{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003048 listiterobject *it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003050 if (!PyList_Check(seq)) {
3051 PyErr_BadInternalCall();
3052 return NULL;
3053 }
3054 it = PyObject_GC_New(listiterobject, &PyListIter_Type);
3055 if (it == NULL)
3056 return NULL;
3057 it->it_index = 0;
3058 Py_INCREF(seq);
3059 it->it_seq = (PyListObject *)seq;
3060 _PyObject_GC_TRACK(it);
3061 return (PyObject *)it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003062}
3063
3064static void
3065listiter_dealloc(listiterobject *it)
3066{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003067 _PyObject_GC_UNTRACK(it);
3068 Py_XDECREF(it->it_seq);
3069 PyObject_GC_Del(it);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003070}
3071
3072static int
3073listiter_traverse(listiterobject *it, visitproc visit, void *arg)
3074{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003075 Py_VISIT(it->it_seq);
3076 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003077}
3078
3079static PyObject *
3080listiter_next(listiterobject *it)
3081{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003082 PyListObject *seq;
3083 PyObject *item;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003084
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003085 assert(it != NULL);
3086 seq = it->it_seq;
3087 if (seq == NULL)
3088 return NULL;
3089 assert(PyList_Check(seq));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003090
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003091 if (it->it_index < PyList_GET_SIZE(seq)) {
3092 item = PyList_GET_ITEM(seq, it->it_index);
3093 ++it->it_index;
3094 Py_INCREF(item);
3095 return item;
3096 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003097
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003098 it->it_seq = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003099 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003100 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003101}
3102
3103static PyObject *
3104listiter_len(listiterobject *it)
3105{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003106 Py_ssize_t len;
3107 if (it->it_seq) {
3108 len = PyList_GET_SIZE(it->it_seq) - it->it_index;
3109 if (len >= 0)
3110 return PyLong_FromSsize_t(len);
3111 }
3112 return PyLong_FromLong(0);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003113}
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003114
3115static PyObject *
3116listiter_reduce(listiterobject *it)
3117{
3118 return listiter_reduce_general(it, 1);
3119}
3120
3121static PyObject *
3122listiter_setstate(listiterobject *it, PyObject *state)
3123{
Victor Stinner7660b882013-06-24 23:59:24 +02003124 Py_ssize_t index = PyLong_AsSsize_t(state);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003125 if (index == -1 && PyErr_Occurred())
3126 return NULL;
3127 if (it->it_seq != NULL) {
3128 if (index < 0)
3129 index = 0;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +00003130 else if (index > PyList_GET_SIZE(it->it_seq))
3131 index = PyList_GET_SIZE(it->it_seq); /* iterator exhausted */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003132 it->it_index = index;
3133 }
3134 Py_RETURN_NONE;
3135}
3136
Raymond Hettinger1021c442003-11-07 15:38:09 +00003137/*********************** List Reverse Iterator **************************/
3138
3139typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003140 PyObject_HEAD
3141 Py_ssize_t it_index;
3142 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger1021c442003-11-07 15:38:09 +00003143} listreviterobject;
3144
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003145static void listreviter_dealloc(listreviterobject *);
3146static int listreviter_traverse(listreviterobject *, visitproc, void *);
3147static PyObject *listreviter_next(listreviterobject *);
Raymond Hettingerf5b64112008-12-02 21:33:45 +00003148static PyObject *listreviter_len(listreviterobject *);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003149static PyObject *listreviter_reduce(listreviterobject *);
3150static PyObject *listreviter_setstate(listreviterobject *, PyObject *);
Raymond Hettingeref9bf402004-03-10 10:10:42 +00003151
Raymond Hettingerf5b64112008-12-02 21:33:45 +00003152static PyMethodDef listreviter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003153 {"__length_hint__", (PyCFunction)listreviter_len, METH_NOARGS, length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003154 {"__reduce__", (PyCFunction)listreviter_reduce, METH_NOARGS, reduce_doc},
3155 {"__setstate__", (PyCFunction)listreviter_setstate, METH_O, setstate_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003156 {NULL, NULL} /* sentinel */
Raymond Hettingeref9bf402004-03-10 10:10:42 +00003157};
3158
Raymond Hettinger1021c442003-11-07 15:38:09 +00003159PyTypeObject PyListRevIter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003160 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3161 "list_reverseiterator", /* tp_name */
3162 sizeof(listreviterobject), /* tp_basicsize */
3163 0, /* tp_itemsize */
3164 /* methods */
3165 (destructor)listreviter_dealloc, /* tp_dealloc */
3166 0, /* tp_print */
3167 0, /* tp_getattr */
3168 0, /* tp_setattr */
3169 0, /* tp_reserved */
3170 0, /* tp_repr */
3171 0, /* tp_as_number */
3172 0, /* tp_as_sequence */
3173 0, /* tp_as_mapping */
3174 0, /* tp_hash */
3175 0, /* tp_call */
3176 0, /* tp_str */
3177 PyObject_GenericGetAttr, /* tp_getattro */
3178 0, /* tp_setattro */
3179 0, /* tp_as_buffer */
3180 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3181 0, /* tp_doc */
3182 (traverseproc)listreviter_traverse, /* tp_traverse */
3183 0, /* tp_clear */
3184 0, /* tp_richcompare */
3185 0, /* tp_weaklistoffset */
3186 PyObject_SelfIter, /* tp_iter */
3187 (iternextfunc)listreviter_next, /* tp_iternext */
3188 listreviter_methods, /* tp_methods */
3189 0,
Raymond Hettinger1021c442003-11-07 15:38:09 +00003190};
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003191
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02003192/*[clinic input]
3193list.__reversed__
3194
3195Return a reverse iterator over the list.
3196[clinic start generated code]*/
3197
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003198static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02003199list___reversed___impl(PyListObject *self)
3200/*[clinic end generated code: output=b166f073208c888c input=eadb6e17f8a6a280]*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003201{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003202 listreviterobject *it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003204 it = PyObject_GC_New(listreviterobject, &PyListRevIter_Type);
3205 if (it == NULL)
3206 return NULL;
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02003207 assert(PyList_Check(self));
3208 it->it_index = PyList_GET_SIZE(self) - 1;
3209 Py_INCREF(self);
3210 it->it_seq = self;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003211 PyObject_GC_Track(it);
3212 return (PyObject *)it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003213}
3214
3215static void
3216listreviter_dealloc(listreviterobject *it)
3217{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003218 PyObject_GC_UnTrack(it);
3219 Py_XDECREF(it->it_seq);
3220 PyObject_GC_Del(it);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003221}
3222
3223static int
3224listreviter_traverse(listreviterobject *it, visitproc visit, void *arg)
3225{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003226 Py_VISIT(it->it_seq);
3227 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003228}
3229
3230static PyObject *
3231listreviter_next(listreviterobject *it)
3232{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003233 PyObject *item;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003234 Py_ssize_t index;
3235 PyListObject *seq;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003236
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003237 assert(it != NULL);
3238 seq = it->it_seq;
3239 if (seq == NULL) {
3240 return NULL;
3241 }
3242 assert(PyList_Check(seq));
3243
3244 index = it->it_index;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003245 if (index>=0 && index < PyList_GET_SIZE(seq)) {
3246 item = PyList_GET_ITEM(seq, index);
3247 it->it_index--;
3248 Py_INCREF(item);
3249 return item;
3250 }
3251 it->it_index = -1;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003252 it->it_seq = NULL;
3253 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003254 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003255}
3256
Raymond Hettingerf5b64112008-12-02 21:33:45 +00003257static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003258listreviter_len(listreviterobject *it)
3259{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003260 Py_ssize_t len = it->it_index + 1;
3261 if (it->it_seq == NULL || PyList_GET_SIZE(it->it_seq) < len)
3262 len = 0;
3263 return PyLong_FromSsize_t(len);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003264}
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003265
3266static PyObject *
3267listreviter_reduce(listreviterobject *it)
3268{
3269 return listiter_reduce_general(it, 0);
3270}
3271
3272static PyObject *
3273listreviter_setstate(listreviterobject *it, PyObject *state)
3274{
3275 Py_ssize_t index = PyLong_AsSsize_t(state);
3276 if (index == -1 && PyErr_Occurred())
3277 return NULL;
3278 if (it->it_seq != NULL) {
3279 if (index < -1)
3280 index = -1;
3281 else if (index > PyList_GET_SIZE(it->it_seq) - 1)
3282 index = PyList_GET_SIZE(it->it_seq) - 1;
3283 it->it_index = index;
3284 }
3285 Py_RETURN_NONE;
3286}
3287
3288/* common pickling support */
3289
3290static PyObject *
3291listiter_reduce_general(void *_it, int forward)
3292{
3293 PyObject *list;
3294
3295 /* the objects are not the same, index is of different types! */
3296 if (forward) {
3297 listiterobject *it = (listiterobject *)_it;
3298 if (it->it_seq)
Victor Stinner7660b882013-06-24 23:59:24 +02003299 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003300 it->it_seq, it->it_index);
3301 } else {
3302 listreviterobject *it = (listreviterobject *)_it;
3303 if (it->it_seq)
Antoine Pitroua7013882012-04-05 00:04:20 +02003304 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("reversed"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003305 it->it_seq, it->it_index);
3306 }
3307 /* empty iterator, create an empty list */
3308 list = PyList_New(0);
3309 if (list == NULL)
3310 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +02003311 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), list);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003312}