blob: 30d262075374430dee519b1c8019d3867d9525d4 [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"
Victor Stinnera15e2602020-04-08 02:01:56 +02004#include "pycore_abstract.h" // _PyIndex_Check()
Victor Stinnerbcda8f12018-11-21 22:27:47 +01005#include "pycore_object.h"
Sergey Fedoseev234531b2019-02-25 21:59:12 +05006#include "pycore_tupleobject.h"
Victor Stinnere281f7d2018-11-01 02:30:36 +01007#include "pycore_accu.h"
Guido van Rossumc0b618a1997-05-02 03:12:38 +00008
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00009#ifdef STDC_HEADERS
10#include <stddef.h>
11#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000012#include <sys/types.h> /* For size_t */
Guido van Rossum6cd2fe01994-08-29 12:45:32 +000013#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000014
Serhiy Storchakafdd42c42017-03-11 09:19:20 +020015/*[clinic input]
16class list "PyListObject *" "&PyList_Type"
17[clinic start generated code]*/
18/*[clinic end generated code: output=da39a3ee5e6b4b0d input=f9b222678f9f71e0]*/
19
20#include "clinic/listobject.c.h"
21
Tim Peters8d9eb102004-07-31 02:24:20 +000022/* Ensure ob_item has room for at least newsize elements, and set
23 * ob_size to newsize. If newsize > ob_size on entry, the content
24 * of the new slots at exit is undefined heap trash; it's the caller's
Ezio Melotti13925002011-03-16 11:05:33 +020025 * responsibility to overwrite them with sane values.
Tim Peters8d9eb102004-07-31 02:24:20 +000026 * The number of allocated elements may grow, shrink, or stay the same.
27 * Failure is impossible if newsize <= self.allocated on entry, although
28 * that partly relies on an assumption that the system realloc() never
29 * fails when passed a number of bytes <= the number of bytes last
30 * allocated (the C standard doesn't guarantee this, but it's hard to
31 * imagine a realloc implementation where it wouldn't be true).
32 * Note that self->ob_item may change, and even if newsize is less
33 * than ob_size on entry.
34 */
Guido van Rossuma46d51d1995-01-26 22:59:43 +000035static int
Martin v. Löwis18e16552006-02-15 17:27:45 +000036list_resize(PyListObject *self, Py_ssize_t newsize)
Guido van Rossuma46d51d1995-01-26 22:59:43 +000037{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000038 PyObject **items;
Xiang Zhang4cee0492017-02-22 12:32:30 +080039 size_t new_allocated, num_allocated_bytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000040 Py_ssize_t allocated = self->allocated;
Tim Peters65b8b842001-05-26 05:28:40 +000041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000042 /* Bypass realloc() when a previous overallocation is large enough
43 to accommodate the newsize. If the newsize falls lower than half
44 the allocated size, then proceed with the realloc() to shrink the list.
45 */
46 if (allocated >= newsize && newsize >= (allocated >> 1)) {
47 assert(self->ob_item != NULL || newsize == 0);
Victor Stinner60ac6ed2020-02-07 23:18:08 +010048 Py_SET_SIZE(self, newsize);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000049 return 0;
50 }
Raymond Hettinger4bb95402004-02-13 11:36:39 +000051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000052 /* This over-allocates proportional to the list size, making room
53 * for additional growth. The over-allocation is mild, but is
54 * enough to give linear-time amortized behavior over a long
55 * sequence of appends() in the presence of a poorly-performing
56 * system realloc().
Serhiy Storchaka2fe815e2020-03-17 23:46:00 +020057 * Add padding to make the allocated size multiple of 4.
58 * The growth pattern is: 0, 4, 8, 16, 24, 32, 40, 52, 64, 76, ...
Xiang Zhang4cee0492017-02-22 12:32:30 +080059 * Note: new_allocated won't overflow because the largest possible value
60 * is PY_SSIZE_T_MAX * (9 / 8) + 6 which always fits in a size_t.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000061 */
Serhiy Storchaka2fe815e2020-03-17 23:46:00 +020062 new_allocated = ((size_t)newsize + (newsize >> 3) + 6) & ~(size_t)3;
63 /* Do not overallocate if the new size is closer to overalocated size
64 * than to the old size.
65 */
66 if (newsize - Py_SIZE(self) > (Py_ssize_t)(new_allocated - newsize))
67 new_allocated = ((size_t)newsize + 3) & ~(size_t)3;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +000068
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000069 if (newsize == 0)
70 new_allocated = 0;
Xiang Zhang4cee0492017-02-22 12:32:30 +080071 num_allocated_bytes = new_allocated * sizeof(PyObject *);
72 items = (PyObject **)PyMem_Realloc(self->ob_item, num_allocated_bytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000073 if (items == NULL) {
74 PyErr_NoMemory();
75 return -1;
76 }
77 self->ob_item = items;
Victor Stinner60ac6ed2020-02-07 23:18:08 +010078 Py_SET_SIZE(self, newsize);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000079 self->allocated = new_allocated;
80 return 0;
Raymond Hettinger4bb95402004-02-13 11:36:39 +000081}
Guido van Rossuma46d51d1995-01-26 22:59:43 +000082
Pablo Galindo372d7052018-10-28 20:16:26 +000083static int
84list_preallocate_exact(PyListObject *self, Py_ssize_t size)
85{
86 assert(self->ob_item == NULL);
Sergey Fedoseev0e5f7712018-12-30 03:31:36 +050087 assert(size > 0);
Pablo Galindo372d7052018-10-28 20:16:26 +000088
Sergey Fedoseev0e5f7712018-12-30 03:31:36 +050089 PyObject **items = PyMem_New(PyObject*, size);
Pablo Galindo372d7052018-10-28 20:16:26 +000090 if (items == NULL) {
91 PyErr_NoMemory();
92 return -1;
93 }
94 self->ob_item = items;
Sergey Fedoseev0e5f7712018-12-30 03:31:36 +050095 self->allocated = size;
Pablo Galindo372d7052018-10-28 20:16:26 +000096 return 0;
97}
98
Raymond Hettinger0468e412004-05-05 05:37:53 +000099/* Empty list reuse scheme to save calls to malloc and free */
Christian Heimes2202f872008-02-06 14:31:34 +0000100#ifndef PyList_MAXFREELIST
Victor Stinnerb7aa23d2020-05-06 19:05:27 +0200101# define PyList_MAXFREELIST 80
Christian Heimes2202f872008-02-06 14:31:34 +0000102#endif
Victor Stinnerb7aa23d2020-05-06 19:05:27 +0200103
104/* bpo-40521: list free lists are shared by all interpreters. */
105#ifdef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
106# undef PyList_MAXFREELIST
107# define PyList_MAXFREELIST 0
108#endif
109
Christian Heimes2202f872008-02-06 14:31:34 +0000110static PyListObject *free_list[PyList_MAXFREELIST];
111static int numfree = 0;
Raymond Hettinger0468e412004-05-05 05:37:53 +0000112
Victor Stinnerae00a5a2020-04-29 02:29:20 +0200113void
114_PyList_ClearFreeList(void)
Raymond Hettingerfb09f0e2004-10-07 03:58:07 +0000115{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000116 while (numfree) {
Victor Stinnerae00a5a2020-04-29 02:29:20 +0200117 PyListObject *op = free_list[--numfree];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000118 assert(PyList_CheckExact(op));
119 PyObject_GC_Del(op);
120 }
Antoine Pitrou9a812cb2011-11-15 00:00:12 +0100121}
122
123void
Victor Stinnerbed48172019-08-27 00:12:32 +0200124_PyList_Fini(void)
Antoine Pitrou9a812cb2011-11-15 00:00:12 +0100125{
Victor Stinnerae00a5a2020-04-29 02:29:20 +0200126 _PyList_ClearFreeList();
Raymond Hettingerfb09f0e2004-10-07 03:58:07 +0000127}
128
David Malcolm49526f42012-06-22 14:55:41 -0400129/* Print summary info about the state of the optimized allocator */
130void
131_PyList_DebugMallocStats(FILE *out)
132{
133 _PyDebugAllocatorStats(out,
134 "free PyListObject",
135 numfree, sizeof(PyListObject));
136}
137
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000138PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000139PyList_New(Py_ssize_t size)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000140{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000141 PyListObject *op;
Tim Peters3986d4e2004-07-29 02:28:42 +0000142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000143 if (size < 0) {
144 PyErr_BadInternalCall();
145 return NULL;
146 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000147 if (numfree) {
148 numfree--;
149 op = free_list[numfree];
150 _Py_NewReference((PyObject *)op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000151 } else {
152 op = PyObject_GC_New(PyListObject, &PyList_Type);
153 if (op == NULL)
154 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000155 }
156 if (size <= 0)
157 op->ob_item = NULL;
158 else {
Mark Dickinson5d132382016-08-21 08:55:15 +0100159 op->ob_item = (PyObject **) PyMem_Calloc(size, sizeof(PyObject *));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000160 if (op->ob_item == NULL) {
161 Py_DECREF(op);
162 return PyErr_NoMemory();
163 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000164 }
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100165 Py_SET_SIZE(op, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000166 op->allocated = size;
167 _PyObject_GC_TRACK(op);
168 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000169}
170
Sergey Fedoseev2fc46972018-08-11 18:12:07 +0500171static PyObject *
172list_new_prealloc(Py_ssize_t size)
173{
174 PyListObject *op = (PyListObject *) PyList_New(0);
175 if (size == 0 || op == NULL) {
176 return (PyObject *) op;
177 }
178 assert(op->ob_item == NULL);
179 op->ob_item = PyMem_New(PyObject *, size);
180 if (op->ob_item == NULL) {
181 Py_DECREF(op);
182 return PyErr_NoMemory();
183 }
184 op->allocated = size;
185 return (PyObject *) op;
186}
187
Martin v. Löwis18e16552006-02-15 17:27:45 +0000188Py_ssize_t
Fred Drakea2f55112000-07-09 15:16:51 +0000189PyList_Size(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000190{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000191 if (!PyList_Check(op)) {
192 PyErr_BadInternalCall();
193 return -1;
194 }
195 else
196 return Py_SIZE(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000197}
198
Raymond Hettingerf1aa8ae2018-10-10 20:37:28 -0700199static inline int
200valid_index(Py_ssize_t i, Py_ssize_t limit)
201{
202 /* The cast to size_t lets us use just a single comparison
203 to check whether i is in the range: 0 <= i < limit.
204
205 See: Section 14.2 "Bounds Checking" in the Agner Fog
206 optimization manual found at:
207 https://www.agner.org/optimize/optimizing_cpp.pdf
208 */
209 return (size_t) i < (size_t) limit;
210}
211
Raymond Hettingerfdfe6182004-05-05 06:28:16 +0000212static PyObject *indexerr = NULL;
Guido van Rossum929f1b81996-08-09 20:51:27 +0000213
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000214PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000215PyList_GetItem(PyObject *op, Py_ssize_t i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000216{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000217 if (!PyList_Check(op)) {
218 PyErr_BadInternalCall();
219 return NULL;
220 }
Raymond Hettingerf1aa8ae2018-10-10 20:37:28 -0700221 if (!valid_index(i, Py_SIZE(op))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000222 if (indexerr == NULL) {
223 indexerr = PyUnicode_FromString(
224 "list index out of range");
225 if (indexerr == NULL)
226 return NULL;
227 }
228 PyErr_SetObject(PyExc_IndexError, indexerr);
229 return NULL;
230 }
231 return ((PyListObject *)op) -> ob_item[i];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000232}
233
234int
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200235PyList_SetItem(PyObject *op, Py_ssize_t i,
236 PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000237{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200238 PyObject **p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000239 if (!PyList_Check(op)) {
240 Py_XDECREF(newitem);
241 PyErr_BadInternalCall();
242 return -1;
243 }
Raymond Hettingerf1aa8ae2018-10-10 20:37:28 -0700244 if (!valid_index(i, Py_SIZE(op))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 Py_XDECREF(newitem);
246 PyErr_SetString(PyExc_IndexError,
247 "list assignment index out of range");
248 return -1;
249 }
250 p = ((PyListObject *)op) -> ob_item + i;
Serhiy Storchakaec397562016-04-06 09:50:03 +0300251 Py_XSETREF(*p, newitem);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000252 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000253}
254
255static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000256ins1(PyListObject *self, Py_ssize_t where, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000257{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000258 Py_ssize_t i, n = Py_SIZE(self);
259 PyObject **items;
260 if (v == NULL) {
261 PyErr_BadInternalCall();
262 return -1;
263 }
Tim Petersb38e2b62004-07-29 02:29:26 +0000264
Sergey Fedoseeve682b262020-05-25 19:54:40 +0500265 assert((size_t)n + 1 < PY_SSIZE_T_MAX);
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800266 if (list_resize(self, n+1) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000267 return -1;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000269 if (where < 0) {
270 where += n;
271 if (where < 0)
272 where = 0;
273 }
274 if (where > n)
275 where = n;
276 items = self->ob_item;
277 for (i = n; --i >= where; )
278 items[i+1] = items[i];
279 Py_INCREF(v);
280 items[where] = v;
281 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000282}
283
284int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000285PyList_Insert(PyObject *op, Py_ssize_t where, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000286{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000287 if (!PyList_Check(op)) {
288 PyErr_BadInternalCall();
289 return -1;
290 }
291 return ins1((PyListObject *)op, where, newitem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000292}
293
Raymond Hettinger40a03822004-04-12 13:05:09 +0000294static int
295app1(PyListObject *self, PyObject *v)
296{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000297 Py_ssize_t n = PyList_GET_SIZE(self);
Raymond Hettinger40a03822004-04-12 13:05:09 +0000298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000299 assert (v != NULL);
Sergey Fedoseeve682b262020-05-25 19:54:40 +0500300 assert((size_t)n + 1 < PY_SSIZE_T_MAX);
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800301 if (list_resize(self, n+1) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000302 return -1;
Raymond Hettinger40a03822004-04-12 13:05:09 +0000303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000304 Py_INCREF(v);
305 PyList_SET_ITEM(self, n, v);
306 return 0;
Raymond Hettinger40a03822004-04-12 13:05:09 +0000307}
308
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000309int
Fred Drakea2f55112000-07-09 15:16:51 +0000310PyList_Append(PyObject *op, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000311{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000312 if (PyList_Check(op) && (newitem != NULL))
313 return app1((PyListObject *)op, newitem);
314 PyErr_BadInternalCall();
315 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000316}
317
318/* Methods */
319
320static void
Fred Drakea2f55112000-07-09 15:16:51 +0000321list_dealloc(PyListObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000322{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000323 Py_ssize_t i;
324 PyObject_GC_UnTrack(op);
Jeroen Demeyer351c6742019-05-10 19:21:11 +0200325 Py_TRASHCAN_BEGIN(op, list_dealloc)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000326 if (op->ob_item != NULL) {
327 /* Do it backwards, for Christian Tismer.
328 There's a simple test case where somehow this reduces
329 thrashing when a *very* large list is created and
330 immediately deleted. */
331 i = Py_SIZE(op);
332 while (--i >= 0) {
333 Py_XDECREF(op->ob_item[i]);
334 }
335 PyMem_FREE(op->ob_item);
336 }
337 if (numfree < PyList_MAXFREELIST && PyList_CheckExact(op))
338 free_list[numfree++] = op;
339 else
340 Py_TYPE(op)->tp_free((PyObject *)op);
Jeroen Demeyer351c6742019-05-10 19:21:11 +0200341 Py_TRASHCAN_END
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000342}
343
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000344static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000345list_repr(PyListObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000346{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000347 Py_ssize_t i;
Victor Stinner5c733472013-11-18 21:11:57 +0100348 PyObject *s;
Victor Stinner5c733472013-11-18 21:11:57 +0100349 _PyUnicodeWriter writer;
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200350
351 if (Py_SIZE(v) == 0) {
352 return PyUnicode_FromString("[]");
353 }
354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000355 i = Py_ReprEnter((PyObject*)v);
356 if (i != 0) {
357 return i > 0 ? PyUnicode_FromString("[...]") : NULL;
358 }
Tim Petersa7259592001-06-16 05:11:17 +0000359
Victor Stinner5c733472013-11-18 21:11:57 +0100360 _PyUnicodeWriter_Init(&writer);
361 writer.overallocate = 1;
Victor Stinnerb8fb1972013-11-18 22:15:44 +0100362 /* "[" + "1" + ", 2" * (len - 1) + "]" */
363 writer.min_length = 1 + 1 + (2 + 1) * (Py_SIZE(v) - 1) + 1;
Tim Petersa7259592001-06-16 05:11:17 +0000364
Victor Stinner5c733472013-11-18 21:11:57 +0100365 if (_PyUnicodeWriter_WriteChar(&writer, '[') < 0)
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200366 goto error;
Tim Petersa7259592001-06-16 05:11:17 +0000367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000368 /* Do repr() on each element. Note that this may mutate the list,
369 so must refetch the list size on each iteration. */
370 for (i = 0; i < Py_SIZE(v); ++i) {
Victor Stinner5c733472013-11-18 21:11:57 +0100371 if (i > 0) {
Victor Stinner4a587072013-11-19 12:54:53 +0100372 if (_PyUnicodeWriter_WriteASCIIString(&writer, ", ", 2) < 0)
Victor Stinner5c733472013-11-18 21:11:57 +0100373 goto error;
374 }
375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000376 s = PyObject_Repr(v->ob_item[i]);
Victor Stinner5c733472013-11-18 21:11:57 +0100377 if (s == NULL)
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200378 goto error;
Victor Stinner5c733472013-11-18 21:11:57 +0100379
380 if (_PyUnicodeWriter_WriteStr(&writer, s) < 0) {
381 Py_DECREF(s);
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200382 goto error;
Victor Stinner5c733472013-11-18 21:11:57 +0100383 }
384 Py_DECREF(s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000385 }
Victor Stinner5c733472013-11-18 21:11:57 +0100386
Victor Stinner4d3f1092013-11-19 12:09:00 +0100387 writer.overallocate = 0;
Victor Stinner5c733472013-11-18 21:11:57 +0100388 if (_PyUnicodeWriter_WriteChar(&writer, ']') < 0)
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200389 goto error;
Tim Petersa7259592001-06-16 05:11:17 +0000390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000391 Py_ReprLeave((PyObject *)v);
Victor Stinner5c733472013-11-18 21:11:57 +0100392 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200393
394error:
Victor Stinner5c733472013-11-18 21:11:57 +0100395 _PyUnicodeWriter_Dealloc(&writer);
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200396 Py_ReprLeave((PyObject *)v);
397 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000398}
399
Martin v. Löwis18e16552006-02-15 17:27:45 +0000400static Py_ssize_t
Fred Drakea2f55112000-07-09 15:16:51 +0000401list_length(PyListObject *a)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000402{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000403 return Py_SIZE(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000404}
405
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000406static int
Fred Drakea2f55112000-07-09 15:16:51 +0000407list_contains(PyListObject *a, PyObject *el)
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000408{
Dong-hee Na4dbf2d82020-01-28 00:02:23 +0900409 PyObject *item;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000410 Py_ssize_t i;
411 int cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000412
Dong-hee Na4dbf2d82020-01-28 00:02:23 +0900413 for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(a); ++i) {
414 item = PyList_GET_ITEM(a, i);
415 Py_INCREF(item);
Dong-hee Na9e1ed512020-01-28 02:04:25 +0900416 cmp = PyObject_RichCompareBool(item, el, Py_EQ);
Dong-hee Na4dbf2d82020-01-28 00:02:23 +0900417 Py_DECREF(item);
418 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000419 return cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000420}
421
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000422static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000423list_item(PyListObject *a, Py_ssize_t i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000424{
Raymond Hettingerf1aa8ae2018-10-10 20:37:28 -0700425 if (!valid_index(i, Py_SIZE(a))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000426 if (indexerr == NULL) {
427 indexerr = PyUnicode_FromString(
428 "list index out of range");
429 if (indexerr == NULL)
430 return NULL;
431 }
432 PyErr_SetObject(PyExc_IndexError, indexerr);
433 return NULL;
434 }
435 Py_INCREF(a->ob_item[i]);
436 return a->ob_item[i];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000437}
438
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000439static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000440list_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000441{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000442 PyListObject *np;
443 PyObject **src, **dest;
444 Py_ssize_t i, len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000445 len = ihigh - ilow;
Sergey Fedoseev2fc46972018-08-11 18:12:07 +0500446 np = (PyListObject *) list_new_prealloc(len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000447 if (np == NULL)
448 return NULL;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000450 src = a->ob_item + ilow;
451 dest = np->ob_item;
452 for (i = 0; i < len; i++) {
453 PyObject *v = src[i];
454 Py_INCREF(v);
455 dest[i] = v;
456 }
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100457 Py_SET_SIZE(np, len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000458 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000459}
460
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000461PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000462PyList_GetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum234f9421993-06-17 12:35:49 +0000463{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000464 if (!PyList_Check(a)) {
465 PyErr_BadInternalCall();
466 return NULL;
467 }
Sergey Fedoseevef1b88b2019-02-21 11:51:52 +0500468 if (ilow < 0) {
469 ilow = 0;
470 }
471 else if (ilow > Py_SIZE(a)) {
472 ilow = Py_SIZE(a);
473 }
474 if (ihigh < ilow) {
475 ihigh = ilow;
476 }
477 else if (ihigh > Py_SIZE(a)) {
478 ihigh = Py_SIZE(a);
479 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000480 return list_slice((PyListObject *)a, ilow, ihigh);
Guido van Rossum234f9421993-06-17 12:35:49 +0000481}
482
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000483static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000484list_concat(PyListObject *a, PyObject *bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000485{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 Py_ssize_t size;
487 Py_ssize_t i;
488 PyObject **src, **dest;
489 PyListObject *np;
490 if (!PyList_Check(bb)) {
491 PyErr_Format(PyExc_TypeError,
492 "can only concatenate list (not \"%.200s\") to list",
Victor Stinner58ac7002020-02-07 03:04:21 +0100493 Py_TYPE(bb)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 return NULL;
495 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000496#define b ((PyListObject *)bb)
Sergey Fedoseeve682b262020-05-25 19:54:40 +0500497 assert((size_t)Py_SIZE(a) + (size_t)Py_SIZE(b) < PY_SSIZE_T_MAX);
Martin Panterb93d8632016-07-25 02:39:20 +0000498 size = Py_SIZE(a) + Py_SIZE(b);
Sergey Fedoseev2fc46972018-08-11 18:12:07 +0500499 np = (PyListObject *) list_new_prealloc(size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 if (np == NULL) {
501 return NULL;
502 }
503 src = a->ob_item;
504 dest = np->ob_item;
505 for (i = 0; i < Py_SIZE(a); i++) {
506 PyObject *v = src[i];
507 Py_INCREF(v);
508 dest[i] = v;
509 }
510 src = b->ob_item;
511 dest = np->ob_item + Py_SIZE(a);
512 for (i = 0; i < Py_SIZE(b); i++) {
513 PyObject *v = src[i];
514 Py_INCREF(v);
515 dest[i] = v;
516 }
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100517 Py_SET_SIZE(np, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000519#undef b
520}
521
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000522static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000523list_repeat(PyListObject *a, Py_ssize_t n)
Guido van Rossumed98d481991-03-06 13:07:53 +0000524{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 Py_ssize_t i, j;
526 Py_ssize_t size;
527 PyListObject *np;
528 PyObject **p, **items;
529 PyObject *elem;
530 if (n < 0)
531 n = 0;
Mark Dickinsonc0420fd2011-09-19 19:18:37 +0100532 if (n > 0 && Py_SIZE(a) > PY_SSIZE_T_MAX / n)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533 return PyErr_NoMemory();
Mark Dickinsonc0420fd2011-09-19 19:18:37 +0100534 size = Py_SIZE(a) * n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 if (size == 0)
536 return PyList_New(0);
Sergey Fedoseev2fc46972018-08-11 18:12:07 +0500537 np = (PyListObject *) list_new_prealloc(size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 if (np == NULL)
539 return NULL;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000541 if (Py_SIZE(a) == 1) {
Sergey Fedoseev2fc46972018-08-11 18:12:07 +0500542 items = np->ob_item;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000543 elem = a->ob_item[0];
544 for (i = 0; i < n; i++) {
545 items[i] = elem;
546 Py_INCREF(elem);
547 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000548 }
Sergey Fedoseev2fc46972018-08-11 18:12:07 +0500549 else {
550 p = np->ob_item;
551 items = a->ob_item;
552 for (i = 0; i < n; i++) {
553 for (j = 0; j < Py_SIZE(a); j++) {
554 *p = items[j];
555 Py_INCREF(*p);
556 p++;
557 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000558 }
559 }
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100560 Py_SET_SIZE(np, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561 return (PyObject *) np;
Guido van Rossumed98d481991-03-06 13:07:53 +0000562}
563
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000564static int
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200565_list_clear(PyListObject *a)
Armin Rigo93677f02004-07-29 12:40:23 +0000566{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567 Py_ssize_t i;
568 PyObject **item = a->ob_item;
569 if (item != NULL) {
570 /* Because XDECREF can recursively invoke operations on
571 this list, we make it empty first. */
572 i = Py_SIZE(a);
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100573 Py_SET_SIZE(a, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000574 a->ob_item = NULL;
575 a->allocated = 0;
576 while (--i >= 0) {
577 Py_XDECREF(item[i]);
578 }
579 PyMem_FREE(item);
580 }
581 /* Never fails; the return value can be ignored.
582 Note that there is no guarantee that the list is actually empty
583 at this point, because XDECREF may have populated it again! */
584 return 0;
Armin Rigo93677f02004-07-29 12:40:23 +0000585}
586
Tim Peters8fc4a912004-07-31 21:53:19 +0000587/* a[ilow:ihigh] = v if v != NULL.
588 * del a[ilow:ihigh] if v == NULL.
589 *
590 * Special speed gimmick: when v is NULL and ihigh - ilow <= 8, it's
591 * guaranteed the call cannot fail.
592 */
Armin Rigo93677f02004-07-29 12:40:23 +0000593static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000594list_ass_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000595{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 /* Because [X]DECREF can recursively invoke list operations on
597 this list, we must postpone all [X]DECREF activity until
598 after the list is back in its canonical shape. Therefore
599 we must allocate an additional array, 'recycle', into which
600 we temporarily copy the items that are deleted from the
601 list. :-( */
602 PyObject *recycle_on_stack[8];
603 PyObject **recycle = recycle_on_stack; /* will allocate more if needed */
604 PyObject **item;
605 PyObject **vitem = NULL;
606 PyObject *v_as_SF = NULL; /* PySequence_Fast(v) */
607 Py_ssize_t n; /* # of elements in replacement list */
608 Py_ssize_t norig; /* # of elements in list getting replaced */
609 Py_ssize_t d; /* Change in size */
610 Py_ssize_t k;
611 size_t s;
612 int result = -1; /* guilty until proved innocent */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000613#define b ((PyListObject *)v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000614 if (v == NULL)
615 n = 0;
616 else {
617 if (a == b) {
618 /* Special case "a[i:j] = a" -- copy b first */
619 v = list_slice(b, 0, Py_SIZE(b));
620 if (v == NULL)
621 return result;
622 result = list_ass_slice(a, ilow, ihigh, v);
623 Py_DECREF(v);
624 return result;
625 }
626 v_as_SF = PySequence_Fast(v, "can only assign an iterable");
627 if(v_as_SF == NULL)
628 goto Error;
629 n = PySequence_Fast_GET_SIZE(v_as_SF);
630 vitem = PySequence_Fast_ITEMS(v_as_SF);
631 }
632 if (ilow < 0)
633 ilow = 0;
634 else if (ilow > Py_SIZE(a))
635 ilow = Py_SIZE(a);
Tim Peters8d9eb102004-07-31 02:24:20 +0000636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000637 if (ihigh < ilow)
638 ihigh = ilow;
639 else if (ihigh > Py_SIZE(a))
640 ihigh = Py_SIZE(a);
Armin Rigo93677f02004-07-29 12:40:23 +0000641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 norig = ihigh - ilow;
643 assert(norig >= 0);
644 d = n - norig;
645 if (Py_SIZE(a) + d == 0) {
646 Py_XDECREF(v_as_SF);
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200647 return _list_clear(a);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000648 }
649 item = a->ob_item;
650 /* recycle the items that we are about to remove */
651 s = norig * sizeof(PyObject *);
Benjamin Peterson5a7d9232016-09-06 17:58:25 -0700652 /* If norig == 0, item might be NULL, in which case we may not memcpy from it. */
653 if (s) {
654 if (s > sizeof(recycle_on_stack)) {
655 recycle = (PyObject **)PyMem_MALLOC(s);
656 if (recycle == NULL) {
657 PyErr_NoMemory();
658 goto Error;
659 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000660 }
Benjamin Peterson5a7d9232016-09-06 17:58:25 -0700661 memcpy(recycle, &item[ilow], s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000662 }
Tim Peters8d9eb102004-07-31 02:24:20 +0000663
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000664 if (d < 0) { /* Delete -d items */
Victor Stinner2c40f642013-07-19 23:06:21 +0200665 Py_ssize_t tail;
666 tail = (Py_SIZE(a) - ihigh) * sizeof(PyObject *);
667 memmove(&item[ihigh+d], &item[ihigh], tail);
668 if (list_resize(a, Py_SIZE(a) + d) < 0) {
669 memmove(&item[ihigh], &item[ihigh+d], tail);
670 memcpy(&item[ilow], recycle, s);
671 goto Error;
672 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000673 item = a->ob_item;
674 }
675 else if (d > 0) { /* Insert d items */
676 k = Py_SIZE(a);
677 if (list_resize(a, k+d) < 0)
678 goto Error;
679 item = a->ob_item;
680 memmove(&item[ihigh+d], &item[ihigh],
681 (k - ihigh)*sizeof(PyObject *));
682 }
683 for (k = 0; k < n; k++, ilow++) {
684 PyObject *w = vitem[k];
685 Py_XINCREF(w);
686 item[ilow] = w;
687 }
688 for (k = norig - 1; k >= 0; --k)
689 Py_XDECREF(recycle[k]);
690 result = 0;
Tim Peters8d9eb102004-07-31 02:24:20 +0000691 Error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000692 if (recycle != recycle_on_stack)
693 PyMem_FREE(recycle);
694 Py_XDECREF(v_as_SF);
695 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000696#undef b
697}
698
Guido van Rossum234f9421993-06-17 12:35:49 +0000699int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000700PyList_SetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum234f9421993-06-17 12:35:49 +0000701{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000702 if (!PyList_Check(a)) {
703 PyErr_BadInternalCall();
704 return -1;
705 }
706 return list_ass_slice((PyListObject *)a, ilow, ihigh, v);
Guido van Rossum234f9421993-06-17 12:35:49 +0000707}
708
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000709static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000710list_inplace_repeat(PyListObject *self, Py_ssize_t n)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000711{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000712 PyObject **items;
713 Py_ssize_t size, i, j, p;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000714
715
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000716 size = PyList_GET_SIZE(self);
717 if (size == 0 || n == 1) {
718 Py_INCREF(self);
719 return (PyObject *)self;
720 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000721
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000722 if (n < 1) {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200723 (void)_list_clear(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000724 Py_INCREF(self);
725 return (PyObject *)self;
726 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000727
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000728 if (size > PY_SSIZE_T_MAX / n) {
729 return PyErr_NoMemory();
730 }
Christian Heimesaf98da12008-01-27 15:18:18 +0000731
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800732 if (list_resize(self, size*n) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000733 return NULL;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000734
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000735 p = size;
736 items = self->ob_item;
737 for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */
738 for (j = 0; j < size; j++) {
739 PyObject *o = items[j];
740 Py_INCREF(o);
741 items[p++] = o;
742 }
743 }
744 Py_INCREF(self);
745 return (PyObject *)self;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000746}
747
Guido van Rossum4a450d01991-04-03 19:05:18 +0000748static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000749list_ass_item(PyListObject *a, Py_ssize_t i, PyObject *v)
Guido van Rossum4a450d01991-04-03 19:05:18 +0000750{
Raymond Hettingerf1aa8ae2018-10-10 20:37:28 -0700751 if (!valid_index(i, Py_SIZE(a))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000752 PyErr_SetString(PyExc_IndexError,
753 "list assignment index out of range");
754 return -1;
755 }
756 if (v == NULL)
757 return list_ass_slice(a, i, i+1, v);
758 Py_INCREF(v);
Serhiy Storchakaf01e4082016-04-10 18:12:01 +0300759 Py_SETREF(a->ob_item[i], v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000760 return 0;
Guido van Rossum4a450d01991-04-03 19:05:18 +0000761}
762
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200763/*[clinic input]
764list.insert
765
766 index: Py_ssize_t
767 object: object
768 /
769
770Insert object before index.
771[clinic start generated code]*/
772
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000773static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200774list_insert_impl(PyListObject *self, Py_ssize_t index, PyObject *object)
775/*[clinic end generated code: output=7f35e32f60c8cb78 input=858514cf894c7eab]*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000776{
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200777 if (ins1(self, index, object) == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 Py_RETURN_NONE;
779 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000780}
781
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200782/*[clinic input]
783list.clear
784
785Remove all items from list.
786[clinic start generated code]*/
787
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000788static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200789list_clear_impl(PyListObject *self)
790/*[clinic end generated code: output=67a1896c01f74362 input=ca3c1646856742f6]*/
Eli Benderskycbbaa962011-02-25 05:47:53 +0000791{
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200792 _list_clear(self);
Eli Benderskycbbaa962011-02-25 05:47:53 +0000793 Py_RETURN_NONE;
794}
795
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200796/*[clinic input]
797list.copy
798
799Return a shallow copy of the list.
800[clinic start generated code]*/
801
Eli Benderskycbbaa962011-02-25 05:47:53 +0000802static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200803list_copy_impl(PyListObject *self)
804/*[clinic end generated code: output=ec6b72d6209d418e input=6453ab159e84771f]*/
Eli Benderskycbbaa962011-02-25 05:47:53 +0000805{
806 return list_slice(self, 0, Py_SIZE(self));
807}
808
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200809/*[clinic input]
810list.append
811
812 object: object
813 /
814
815Append object to the end of the list.
816[clinic start generated code]*/
817
Eli Benderskycbbaa962011-02-25 05:47:53 +0000818static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200819list_append(PyListObject *self, PyObject *object)
820/*[clinic end generated code: output=7c096003a29c0eae input=43a3fe48a7066e91]*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000821{
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200822 if (app1(self, object) == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 Py_RETURN_NONE;
824 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000825}
826
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200827/*[clinic input]
828list.extend
829
830 iterable: object
831 /
832
833Extend list by appending elements from the iterable.
834[clinic start generated code]*/
835
Barry Warsawdedf6d61998-10-09 16:37:25 +0000836static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200837list_extend(PyListObject *self, PyObject *iterable)
838/*[clinic end generated code: output=630fb3bca0c8e789 input=9ec5ba3a81be3a4d]*/
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000839{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 PyObject *it; /* iter(v) */
841 Py_ssize_t m; /* size of self */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200842 Py_ssize_t n; /* guess for size of iterable */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000843 Py_ssize_t mn; /* m + n */
844 Py_ssize_t i;
845 PyObject *(*iternext)(PyObject *);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000846
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000847 /* Special cases:
848 1) lists and tuples which can use PySequence_Fast ops
849 2) extending self to self requires making a copy first
850 */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200851 if (PyList_CheckExact(iterable) || PyTuple_CheckExact(iterable) ||
852 (PyObject *)self == iterable) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000853 PyObject **src, **dest;
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200854 iterable = PySequence_Fast(iterable, "argument must be iterable");
855 if (!iterable)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000856 return NULL;
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200857 n = PySequence_Fast_GET_SIZE(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 if (n == 0) {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200859 /* short circuit when iterable is empty */
860 Py_DECREF(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000861 Py_RETURN_NONE;
862 }
863 m = Py_SIZE(self);
Martin Panter94b39ce2017-01-14 06:30:37 +0000864 /* It should not be possible to allocate a list large enough to cause
865 an overflow on any relevant platform */
866 assert(m < PY_SSIZE_T_MAX - n);
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800867 if (list_resize(self, m + n) < 0) {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200868 Py_DECREF(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000869 return NULL;
870 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200871 /* note that we may still have self == iterable here for the
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000872 * situation a.extend(a), but the following code works
873 * in that case too. Just make sure to resize self
874 * before calling PySequence_Fast_ITEMS.
875 */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200876 /* populate the end of self with iterable's items */
877 src = PySequence_Fast_ITEMS(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000878 dest = self->ob_item + m;
879 for (i = 0; i < n; i++) {
880 PyObject *o = src[i];
881 Py_INCREF(o);
882 dest[i] = o;
883 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200884 Py_DECREF(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000885 Py_RETURN_NONE;
886 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000887
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200888 it = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 if (it == NULL)
890 return NULL;
Victor Stinner58ac7002020-02-07 03:04:21 +0100891 iternext = *Py_TYPE(it)->tp_iternext;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000893 /* Guess a result list size. */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200894 n = PyObject_LengthHint(iterable, 8);
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800895 if (n < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 Py_DECREF(it);
897 return NULL;
898 }
899 m = Py_SIZE(self);
Martin Panterb93d8632016-07-25 02:39:20 +0000900 if (m > PY_SSIZE_T_MAX - n) {
901 /* m + n overflowed; on the chance that n lied, and there really
902 * is enough room, ignore it. If n was telling the truth, we'll
903 * eventually run out of memory during the loop.
904 */
905 }
906 else {
907 mn = m + n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000908 /* Make room. */
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800909 if (list_resize(self, mn) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 goto error;
911 /* Make the list sane again. */
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100912 Py_SET_SIZE(self, m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000914
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000915 /* Run iterator to exhaustion. */
916 for (;;) {
917 PyObject *item = iternext(it);
918 if (item == NULL) {
919 if (PyErr_Occurred()) {
920 if (PyErr_ExceptionMatches(PyExc_StopIteration))
921 PyErr_Clear();
922 else
923 goto error;
924 }
925 break;
926 }
927 if (Py_SIZE(self) < self->allocated) {
928 /* steals ref */
929 PyList_SET_ITEM(self, Py_SIZE(self), item);
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100930 Py_SET_SIZE(self, Py_SIZE(self) + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 }
932 else {
933 int status = app1(self, item);
934 Py_DECREF(item); /* append creates a new ref */
935 if (status < 0)
936 goto error;
937 }
938 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 /* Cut back result list if initial guess was too large. */
Victor Stinner32fd6ea2013-07-16 21:45:58 +0200941 if (Py_SIZE(self) < self->allocated) {
942 if (list_resize(self, Py_SIZE(self)) < 0)
943 goto error;
944 }
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000945
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 Py_DECREF(it);
947 Py_RETURN_NONE;
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000948
949 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 Py_DECREF(it);
951 return NULL;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000952}
953
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000954PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200955_PyList_Extend(PyListObject *self, PyObject *iterable)
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000956{
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200957 return list_extend(self, iterable);
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000958}
959
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000960static PyObject *
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000961list_inplace_concat(PyListObject *self, PyObject *other)
962{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000963 PyObject *result;
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000964
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200965 result = list_extend(self, other);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 if (result == NULL)
967 return result;
968 Py_DECREF(result);
969 Py_INCREF(self);
970 return (PyObject *)self;
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000971}
972
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200973/*[clinic input]
974list.pop
975
976 index: Py_ssize_t = -1
977 /
978
979Remove and return item at index (default last).
980
981Raises IndexError if list is empty or index is out of range.
982[clinic start generated code]*/
983
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000984static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200985list_pop_impl(PyListObject *self, Py_ssize_t index)
986/*[clinic end generated code: output=6bd69dcb3f17eca8 input=b83675976f329e6f]*/
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000987{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000988 PyObject *v;
989 int status;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000990
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 if (Py_SIZE(self) == 0) {
992 /* Special-case most common failure cause */
993 PyErr_SetString(PyExc_IndexError, "pop from empty list");
994 return NULL;
995 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200996 if (index < 0)
997 index += Py_SIZE(self);
Raymond Hettingerf1aa8ae2018-10-10 20:37:28 -0700998 if (!valid_index(index, Py_SIZE(self))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 PyErr_SetString(PyExc_IndexError, "pop index out of range");
1000 return NULL;
1001 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02001002 v = self->ob_item[index];
1003 if (index == Py_SIZE(self) - 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001004 status = list_resize(self, Py_SIZE(self) - 1);
Victor Stinnerb27cd3e2013-07-08 22:20:44 +02001005 if (status >= 0)
1006 return v; /* and v now owns the reference the list had */
1007 else
1008 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001009 }
1010 Py_INCREF(v);
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02001011 status = list_ass_slice(self, index, index+1, (PyObject *)NULL);
Victor Stinner095d99f2013-07-17 21:58:01 +02001012 if (status < 0) {
1013 Py_DECREF(v);
1014 return NULL;
1015 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 return v;
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +00001017}
1018
Tim Peters8e2e7ca2002-07-19 02:33:08 +00001019/* Reverse a slice of a list in place, from lo up to (exclusive) hi. */
1020static void
1021reverse_slice(PyObject **lo, PyObject **hi)
1022{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001023 assert(lo && hi);
Tim Peters8e2e7ca2002-07-19 02:33:08 +00001024
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001025 --hi;
1026 while (lo < hi) {
1027 PyObject *t = *lo;
1028 *lo = *hi;
1029 *hi = t;
1030 ++lo;
1031 --hi;
1032 }
Tim Peters8e2e7ca2002-07-19 02:33:08 +00001033}
1034
Tim Petersa64dc242002-08-01 02:13:36 +00001035/* Lots of code for an adaptive, stable, natural mergesort. There are many
1036 * pieces to this algorithm; read listsort.txt for overviews and details.
1037 */
Guido van Rossum3f236de1996-12-10 23:55:39 +00001038
Daniel Stutzbach98338222010-12-02 21:55:33 +00001039/* A sortslice contains a pointer to an array of keys and a pointer to
1040 * an array of corresponding values. In other words, keys[i]
1041 * corresponds with values[i]. If values == NULL, then the keys are
1042 * also the values.
1043 *
1044 * Several convenience routines are provided here, so that keys and
1045 * values are always moved in sync.
1046 */
1047
1048typedef struct {
1049 PyObject **keys;
1050 PyObject **values;
1051} sortslice;
1052
1053Py_LOCAL_INLINE(void)
1054sortslice_copy(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j)
1055{
1056 s1->keys[i] = s2->keys[j];
1057 if (s1->values != NULL)
1058 s1->values[i] = s2->values[j];
1059}
1060
1061Py_LOCAL_INLINE(void)
Benjamin Peterson9efdcca2010-12-03 01:44:10 +00001062sortslice_copy_incr(sortslice *dst, sortslice *src)
1063{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001064 *dst->keys++ = *src->keys++;
1065 if (dst->values != NULL)
1066 *dst->values++ = *src->values++;
1067}
1068
1069Py_LOCAL_INLINE(void)
Benjamin Peterson9efdcca2010-12-03 01:44:10 +00001070sortslice_copy_decr(sortslice *dst, sortslice *src)
1071{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001072 *dst->keys-- = *src->keys--;
1073 if (dst->values != NULL)
1074 *dst->values-- = *src->values--;
1075}
1076
1077
1078Py_LOCAL_INLINE(void)
1079sortslice_memcpy(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j,
Benjamin Peterson9efdcca2010-12-03 01:44:10 +00001080 Py_ssize_t n)
1081{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001082 memcpy(&s1->keys[i], &s2->keys[j], sizeof(PyObject *) * n);
1083 if (s1->values != NULL)
1084 memcpy(&s1->values[i], &s2->values[j], sizeof(PyObject *) * n);
1085}
1086
1087Py_LOCAL_INLINE(void)
1088sortslice_memmove(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j,
Benjamin Peterson9efdcca2010-12-03 01:44:10 +00001089 Py_ssize_t n)
1090{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001091 memmove(&s1->keys[i], &s2->keys[j], sizeof(PyObject *) * n);
1092 if (s1->values != NULL)
1093 memmove(&s1->values[i], &s2->values[j], sizeof(PyObject *) * n);
1094}
1095
1096Py_LOCAL_INLINE(void)
Benjamin Peterson9efdcca2010-12-03 01:44:10 +00001097sortslice_advance(sortslice *slice, Py_ssize_t n)
1098{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001099 slice->keys += n;
1100 if (slice->values != NULL)
1101 slice->values += n;
1102}
1103
embg1e34da42018-01-28 20:03:23 -07001104/* Comparison function: ms->key_compare, which is set at run-time in
1105 * listsort_impl to optimize for various special cases.
Tim Petersa64dc242002-08-01 02:13:36 +00001106 * Returns -1 on error, 1 if x < y, 0 if x >= y.
1107 */
Guido van Rossum3f236de1996-12-10 23:55:39 +00001108
embg1e34da42018-01-28 20:03:23 -07001109#define ISLT(X, Y) (*(ms->key_compare))(X, Y, ms)
Tim Peters66860f62002-08-04 17:47:26 +00001110
1111/* Compare X to Y via "<". Goto "fail" if the comparison raises an
Tim Petersa8c974c2002-07-19 03:30:57 +00001112 error. Else "k" is set to true iff X<Y, and an "if (k)" block is
1113 started. It makes more sense in context <wink>. X and Y are PyObject*s.
1114*/
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001115#define IFLT(X, Y) if ((k = ISLT(X, Y)) < 0) goto fail; \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001116 if (k)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001117
embg1e34da42018-01-28 20:03:23 -07001118/* The maximum number of entries in a MergeState's pending-runs stack.
1119 * This is enough to sort arrays of size up to about
1120 * 32 * phi ** MAX_MERGE_PENDING
1121 * where phi ~= 1.618. 85 is ridiculouslylarge enough, good for an array
1122 * with 2**64 elements.
1123 */
1124#define MAX_MERGE_PENDING 85
1125
1126/* When we get into galloping mode, we stay there until both runs win less
1127 * often than MIN_GALLOP consecutive times. See listsort.txt for more info.
1128 */
1129#define MIN_GALLOP 7
1130
1131/* Avoid malloc for small temp arrays. */
1132#define MERGESTATE_TEMP_SIZE 256
1133
1134/* One MergeState exists on the stack per invocation of mergesort. It's just
1135 * a convenient way to pass state around among the helper functions.
1136 */
1137struct s_slice {
1138 sortslice base;
1139 Py_ssize_t len;
1140};
1141
1142typedef struct s_MergeState MergeState;
1143struct s_MergeState {
1144 /* This controls when we get *into* galloping mode. It's initialized
1145 * to MIN_GALLOP. merge_lo and merge_hi tend to nudge it higher for
1146 * random data, and lower for highly structured data.
1147 */
1148 Py_ssize_t min_gallop;
1149
1150 /* 'a' is temp storage to help with merges. It contains room for
1151 * alloced entries.
1152 */
1153 sortslice a; /* may point to temparray below */
1154 Py_ssize_t alloced;
1155
1156 /* A stack of n pending runs yet to be merged. Run #i starts at
1157 * address base[i] and extends for len[i] elements. It's always
1158 * true (so long as the indices are in bounds) that
1159 *
1160 * pending[i].base + pending[i].len == pending[i+1].base
1161 *
1162 * so we could cut the storage for this, but it's a minor amount,
1163 * and keeping all the info explicit simplifies the code.
1164 */
1165 int n;
1166 struct s_slice pending[MAX_MERGE_PENDING];
1167
1168 /* 'a' points to this when possible, rather than muck with malloc. */
1169 PyObject *temparray[MERGESTATE_TEMP_SIZE];
1170
1171 /* This is the function we will use to compare two keys,
1172 * even when none of our special cases apply and we have to use
1173 * safe_object_compare. */
1174 int (*key_compare)(PyObject *, PyObject *, MergeState *);
1175
1176 /* This function is used by unsafe_object_compare to optimize comparisons
1177 * when we know our list is type-homogeneous but we can't assume anything else.
Victor Stinner58ac7002020-02-07 03:04:21 +01001178 * In the pre-sort check it is set equal to Py_TYPE(key)->tp_richcompare */
embg1e34da42018-01-28 20:03:23 -07001179 PyObject *(*key_richcompare)(PyObject *, PyObject *, int);
1180
1181 /* This function is used by unsafe_tuple_compare to compare the first elements
1182 * of tuples. It may be set to safe_object_compare, but the idea is that hopefully
1183 * we can assume more, and use one of the special-case compares. */
1184 int (*tuple_elem_compare)(PyObject *, PyObject *, MergeState *);
1185};
1186
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001187/* binarysort is the best method for sorting small arrays: it does
1188 few compares, but can do data movement quadratic in the number of
1189 elements.
Guido van Rossum42812581998-06-17 14:15:44 +00001190 [lo, hi) is a contiguous slice of a list, and is sorted via
Tim Petersa8c974c2002-07-19 03:30:57 +00001191 binary insertion. This sort is stable.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001192 On entry, must have lo <= start <= hi, and that [lo, start) is already
1193 sorted (pass start == lo if you don't know!).
Tim Petersa8c974c2002-07-19 03:30:57 +00001194 If islt() complains return -1, else 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001195 Even in case of error, the output slice will be some permutation of
1196 the input (nothing is lost or duplicated).
1197*/
Guido van Rossum3f236de1996-12-10 23:55:39 +00001198static int
embg1e34da42018-01-28 20:03:23 -07001199binarysort(MergeState *ms, sortslice lo, PyObject **hi, PyObject **start)
Guido van Rossum3f236de1996-12-10 23:55:39 +00001200{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001201 Py_ssize_t k;
1202 PyObject **l, **p, **r;
1203 PyObject *pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001204
Daniel Stutzbach98338222010-12-02 21:55:33 +00001205 assert(lo.keys <= start && start <= hi);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001206 /* assert [lo, start) is sorted */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001207 if (lo.keys == start)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001208 ++start;
1209 for (; start < hi; ++start) {
1210 /* set l to where *start belongs */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001211 l = lo.keys;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001212 r = start;
1213 pivot = *r;
1214 /* Invariants:
1215 * pivot >= all in [lo, l).
1216 * pivot < all in [r, start).
1217 * The second is vacuously true at the start.
1218 */
1219 assert(l < r);
1220 do {
1221 p = l + ((r - l) >> 1);
1222 IFLT(pivot, *p)
1223 r = p;
1224 else
1225 l = p+1;
1226 } while (l < r);
1227 assert(l == r);
1228 /* The invariants still hold, so pivot >= all in [lo, l) and
1229 pivot < all in [l, start), so pivot belongs at l. Note
1230 that if there are elements equal to pivot, l points to the
1231 first slot after them -- that's why this sort is stable.
1232 Slide over to make room.
1233 Caution: using memmove is much slower under MSVC 5;
1234 we're not usually moving many slots. */
1235 for (p = start; p > l; --p)
1236 *p = *(p-1);
1237 *l = pivot;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001238 if (lo.values != NULL) {
1239 Py_ssize_t offset = lo.values - lo.keys;
1240 p = start + offset;
1241 pivot = *p;
1242 l += offset;
1243 for (p = start + offset; p > l; --p)
1244 *p = *(p-1);
1245 *l = pivot;
1246 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001247 }
1248 return 0;
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001249
1250 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001251 return -1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001252}
1253
Tim Petersa64dc242002-08-01 02:13:36 +00001254/*
1255Return the length of the run beginning at lo, in the slice [lo, hi). lo < hi
1256is required on entry. "A run" is the longest ascending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001257
Tim Petersa64dc242002-08-01 02:13:36 +00001258 lo[0] <= lo[1] <= lo[2] <= ...
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001259
Tim Petersa64dc242002-08-01 02:13:36 +00001260or the longest descending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001261
Tim Petersa64dc242002-08-01 02:13:36 +00001262 lo[0] > lo[1] > lo[2] > ...
Tim Peters3b01a122002-07-19 02:35:45 +00001263
Tim Petersa64dc242002-08-01 02:13:36 +00001264Boolean *descending is set to 0 in the former case, or to 1 in the latter.
1265For its intended use in a stable mergesort, the strictness of the defn of
1266"descending" is needed so that the caller can safely reverse a descending
1267sequence without violating stability (strict > ensures there are no equal
1268elements to get out of order).
1269
1270Returns -1 in case of error.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001271*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001272static Py_ssize_t
embg1e34da42018-01-28 20:03:23 -07001273count_run(MergeState *ms, PyObject **lo, PyObject **hi, int *descending)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001274{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001275 Py_ssize_t k;
1276 Py_ssize_t n;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001278 assert(lo < hi);
1279 *descending = 0;
1280 ++lo;
1281 if (lo == hi)
1282 return 1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001284 n = 2;
1285 IFLT(*lo, *(lo-1)) {
1286 *descending = 1;
1287 for (lo = lo+1; lo < hi; ++lo, ++n) {
1288 IFLT(*lo, *(lo-1))
1289 ;
1290 else
1291 break;
1292 }
1293 }
1294 else {
1295 for (lo = lo+1; lo < hi; ++lo, ++n) {
1296 IFLT(*lo, *(lo-1))
1297 break;
1298 }
1299 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001301 return n;
Tim Petersa64dc242002-08-01 02:13:36 +00001302fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001303 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001304}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001305
Tim Petersa64dc242002-08-01 02:13:36 +00001306/*
1307Locate the proper position of key in a sorted vector; if the vector contains
1308an element equal to key, return the position immediately to the left of
1309the leftmost equal element. [gallop_right() does the same except returns
1310the position to the right of the rightmost equal element (if any).]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001311
Tim Petersa64dc242002-08-01 02:13:36 +00001312"a" is a sorted vector with n elements, starting at a[0]. n must be > 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001313
Tim Petersa64dc242002-08-01 02:13:36 +00001314"hint" is an index at which to begin the search, 0 <= hint < n. The closer
1315hint is to the final result, the faster this runs.
1316
1317The return value is the int k in 0..n such that
1318
1319 a[k-1] < key <= a[k]
1320
1321pretending that *(a-1) is minus infinity and a[n] is plus infinity. IOW,
1322key belongs at index k; or, IOW, the first k elements of a should precede
1323key, and the last n-k should follow key.
1324
1325Returns -1 on error. See listsort.txt for info on the method.
1326*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001327static Py_ssize_t
embg1e34da42018-01-28 20:03:23 -07001328gallop_left(MergeState *ms, PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint)
Tim Petersa64dc242002-08-01 02:13:36 +00001329{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001330 Py_ssize_t ofs;
1331 Py_ssize_t lastofs;
1332 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001334 assert(key && a && n > 0 && hint >= 0 && hint < n);
Tim Petersa64dc242002-08-01 02:13:36 +00001335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336 a += hint;
1337 lastofs = 0;
1338 ofs = 1;
1339 IFLT(*a, key) {
1340 /* a[hint] < key -- gallop right, until
1341 * a[hint + lastofs] < key <= a[hint + ofs]
1342 */
1343 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
1344 while (ofs < maxofs) {
1345 IFLT(a[ofs], key) {
1346 lastofs = ofs;
Alexey Izbyshev6bc59172019-05-23 03:01:08 +03001347 assert(ofs <= (PY_SSIZE_T_MAX - 1) / 2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001348 ofs = (ofs << 1) + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001349 }
1350 else /* key <= a[hint + ofs] */
1351 break;
1352 }
1353 if (ofs > maxofs)
1354 ofs = maxofs;
1355 /* Translate back to offsets relative to &a[0]. */
1356 lastofs += hint;
1357 ofs += hint;
1358 }
1359 else {
1360 /* key <= a[hint] -- gallop left, until
1361 * a[hint - ofs] < key <= a[hint - lastofs]
1362 */
1363 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
1364 while (ofs < maxofs) {
1365 IFLT(*(a-ofs), key)
1366 break;
1367 /* key <= a[hint - ofs] */
1368 lastofs = ofs;
Alexey Izbyshev6bc59172019-05-23 03:01:08 +03001369 assert(ofs <= (PY_SSIZE_T_MAX - 1) / 2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001370 ofs = (ofs << 1) + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001371 }
1372 if (ofs > maxofs)
1373 ofs = maxofs;
1374 /* Translate back to positive offsets relative to &a[0]. */
1375 k = lastofs;
1376 lastofs = hint - ofs;
1377 ofs = hint - k;
1378 }
1379 a -= hint;
Tim Petersa64dc242002-08-01 02:13:36 +00001380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001381 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1382 /* Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the
1383 * right of lastofs but no farther right than ofs. Do a binary
1384 * search, with invariant a[lastofs-1] < key <= a[ofs].
1385 */
1386 ++lastofs;
1387 while (lastofs < ofs) {
1388 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001390 IFLT(a[m], key)
1391 lastofs = m+1; /* a[m] < key */
1392 else
1393 ofs = m; /* key <= a[m] */
1394 }
1395 assert(lastofs == ofs); /* so a[ofs-1] < key <= a[ofs] */
1396 return ofs;
Tim Petersa64dc242002-08-01 02:13:36 +00001397
1398fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001399 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001400}
1401
1402/*
1403Exactly like gallop_left(), except that if key already exists in a[0:n],
1404finds the position immediately to the right of the rightmost equal value.
1405
1406The return value is the int k in 0..n such that
1407
1408 a[k-1] <= key < a[k]
1409
1410or -1 if error.
1411
1412The code duplication is massive, but this is enough different given that
1413we're sticking to "<" comparisons that it's much harder to follow if
1414written as one routine with yet another "left or right?" flag.
1415*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001416static Py_ssize_t
embg1e34da42018-01-28 20:03:23 -07001417gallop_right(MergeState *ms, PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint)
Tim Petersa64dc242002-08-01 02:13:36 +00001418{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001419 Py_ssize_t ofs;
1420 Py_ssize_t lastofs;
1421 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001423 assert(key && a && n > 0 && hint >= 0 && hint < n);
Tim Petersa64dc242002-08-01 02:13:36 +00001424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001425 a += hint;
1426 lastofs = 0;
1427 ofs = 1;
1428 IFLT(key, *a) {
1429 /* key < a[hint] -- gallop left, until
1430 * a[hint - ofs] <= key < a[hint - lastofs]
1431 */
1432 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
1433 while (ofs < maxofs) {
1434 IFLT(key, *(a-ofs)) {
1435 lastofs = ofs;
Alexey Izbyshev6bc59172019-05-23 03:01:08 +03001436 assert(ofs <= (PY_SSIZE_T_MAX - 1) / 2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001437 ofs = (ofs << 1) + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001438 }
1439 else /* a[hint - ofs] <= key */
1440 break;
1441 }
1442 if (ofs > maxofs)
1443 ofs = maxofs;
1444 /* Translate back to positive offsets relative to &a[0]. */
1445 k = lastofs;
1446 lastofs = hint - ofs;
1447 ofs = hint - k;
1448 }
1449 else {
1450 /* a[hint] <= key -- gallop right, until
1451 * a[hint + lastofs] <= key < a[hint + ofs]
1452 */
1453 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
1454 while (ofs < maxofs) {
1455 IFLT(key, a[ofs])
1456 break;
1457 /* a[hint + ofs] <= key */
1458 lastofs = ofs;
Alexey Izbyshev6bc59172019-05-23 03:01:08 +03001459 assert(ofs <= (PY_SSIZE_T_MAX - 1) / 2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001460 ofs = (ofs << 1) + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001461 }
1462 if (ofs > maxofs)
1463 ofs = maxofs;
1464 /* Translate back to offsets relative to &a[0]. */
1465 lastofs += hint;
1466 ofs += hint;
1467 }
1468 a -= hint;
Tim Petersa64dc242002-08-01 02:13:36 +00001469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001470 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1471 /* Now a[lastofs] <= key < a[ofs], so key belongs somewhere to the
1472 * right of lastofs but no farther right than ofs. Do a binary
1473 * search, with invariant a[lastofs-1] <= key < a[ofs].
1474 */
1475 ++lastofs;
1476 while (lastofs < ofs) {
1477 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001479 IFLT(key, a[m])
1480 ofs = m; /* key < a[m] */
1481 else
1482 lastofs = m+1; /* a[m] <= key */
1483 }
1484 assert(lastofs == ofs); /* so a[ofs-1] <= key < a[ofs] */
1485 return ofs;
Tim Petersa64dc242002-08-01 02:13:36 +00001486
1487fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001488 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001489}
1490
Tim Petersa64dc242002-08-01 02:13:36 +00001491/* Conceptually a MergeState's constructor. */
1492static void
Victor Stinner0fcab4a2011-01-04 12:59:15 +00001493merge_init(MergeState *ms, Py_ssize_t list_size, int has_keyfunc)
Tim Petersa64dc242002-08-01 02:13:36 +00001494{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001495 assert(ms != NULL);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001496 if (has_keyfunc) {
1497 /* The temporary space for merging will need at most half the list
1498 * size rounded up. Use the minimum possible space so we can use the
1499 * rest of temparray for other things. In particular, if there is
1500 * enough extra space, listsort() will use it to store the keys.
1501 */
1502 ms->alloced = (list_size + 1) / 2;
1503
1504 /* ms->alloced describes how many keys will be stored at
1505 ms->temparray, but we also need to store the values. Hence,
1506 ms->alloced is capped at half of MERGESTATE_TEMP_SIZE. */
1507 if (MERGESTATE_TEMP_SIZE / 2 < ms->alloced)
1508 ms->alloced = MERGESTATE_TEMP_SIZE / 2;
1509 ms->a.values = &ms->temparray[ms->alloced];
1510 }
1511 else {
1512 ms->alloced = MERGESTATE_TEMP_SIZE;
1513 ms->a.values = NULL;
1514 }
1515 ms->a.keys = ms->temparray;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001516 ms->n = 0;
1517 ms->min_gallop = MIN_GALLOP;
Tim Petersa64dc242002-08-01 02:13:36 +00001518}
1519
1520/* Free all the temp memory owned by the MergeState. This must be called
1521 * when you're done with a MergeState, and may be called before then if
1522 * you want to free the temp memory early.
1523 */
1524static void
1525merge_freemem(MergeState *ms)
1526{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001527 assert(ms != NULL);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001528 if (ms->a.keys != ms->temparray)
1529 PyMem_Free(ms->a.keys);
Tim Petersa64dc242002-08-01 02:13:36 +00001530}
1531
1532/* Ensure enough temp memory for 'need' array slots is available.
1533 * Returns 0 on success and -1 if the memory can't be gotten.
1534 */
1535static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001536merge_getmem(MergeState *ms, Py_ssize_t need)
Tim Petersa64dc242002-08-01 02:13:36 +00001537{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001538 int multiplier;
1539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001540 assert(ms != NULL);
1541 if (need <= ms->alloced)
1542 return 0;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001543
1544 multiplier = ms->a.values != NULL ? 2 : 1;
1545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001546 /* Don't realloc! That can cost cycles to copy the old data, but
1547 * we don't care what's in the block.
1548 */
1549 merge_freemem(ms);
embg1e34da42018-01-28 20:03:23 -07001550 if ((size_t)need > PY_SSIZE_T_MAX / sizeof(PyObject *) / multiplier) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001551 PyErr_NoMemory();
1552 return -1;
1553 }
embg1e34da42018-01-28 20:03:23 -07001554 ms->a.keys = (PyObject **)PyMem_Malloc(multiplier * need
Daniel Stutzbach98338222010-12-02 21:55:33 +00001555 * sizeof(PyObject *));
1556 if (ms->a.keys != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001557 ms->alloced = need;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001558 if (ms->a.values != NULL)
1559 ms->a.values = &ms->a.keys[need];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001560 return 0;
1561 }
1562 PyErr_NoMemory();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001563 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001564}
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001565#define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 : \
1566 merge_getmem(MS, NEED))
Tim Petersa64dc242002-08-01 02:13:36 +00001567
Daniel Stutzbach98338222010-12-02 21:55:33 +00001568/* Merge the na elements starting at ssa with the nb elements starting at
1569 * ssb.keys = ssa.keys + na in a stable way, in-place. na and nb must be > 0.
1570 * Must also have that ssa.keys[na-1] belongs at the end of the merge, and
1571 * should have na <= nb. See listsort.txt for more info. Return 0 if
1572 * successful, -1 if error.
Tim Petersa64dc242002-08-01 02:13:36 +00001573 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001574static Py_ssize_t
Daniel Stutzbach98338222010-12-02 21:55:33 +00001575merge_lo(MergeState *ms, sortslice ssa, Py_ssize_t na,
1576 sortslice ssb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001577{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001578 Py_ssize_t k;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001579 sortslice dest;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001580 int result = -1; /* guilty until proved innocent */
1581 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001582
Daniel Stutzbach98338222010-12-02 21:55:33 +00001583 assert(ms && ssa.keys && ssb.keys && na > 0 && nb > 0);
1584 assert(ssa.keys + na == ssb.keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001585 if (MERGE_GETMEM(ms, na) < 0)
1586 return -1;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001587 sortslice_memcpy(&ms->a, 0, &ssa, 0, na);
1588 dest = ssa;
1589 ssa = ms->a;
Tim Petersa64dc242002-08-01 02:13:36 +00001590
Daniel Stutzbach98338222010-12-02 21:55:33 +00001591 sortslice_copy_incr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001592 --nb;
1593 if (nb == 0)
1594 goto Succeed;
1595 if (na == 1)
1596 goto CopyB;
Tim Petersa64dc242002-08-01 02:13:36 +00001597
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001598 min_gallop = ms->min_gallop;
1599 for (;;) {
1600 Py_ssize_t acount = 0; /* # of times A won in a row */
1601 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001602
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001603 /* Do the straightforward thing until (if ever) one run
1604 * appears to win consistently.
1605 */
1606 for (;;) {
1607 assert(na > 1 && nb > 0);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001608 k = ISLT(ssb.keys[0], ssa.keys[0]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001609 if (k) {
1610 if (k < 0)
1611 goto Fail;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001612 sortslice_copy_incr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001613 ++bcount;
1614 acount = 0;
1615 --nb;
1616 if (nb == 0)
1617 goto Succeed;
1618 if (bcount >= min_gallop)
1619 break;
1620 }
1621 else {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001622 sortslice_copy_incr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001623 ++acount;
1624 bcount = 0;
1625 --na;
1626 if (na == 1)
1627 goto CopyB;
1628 if (acount >= min_gallop)
1629 break;
1630 }
1631 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001632
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001633 /* One run is winning so consistently that galloping may
1634 * be a huge win. So try that, and continue galloping until
1635 * (if ever) neither run appears to be winning consistently
1636 * anymore.
1637 */
1638 ++min_gallop;
1639 do {
1640 assert(na > 1 && nb > 0);
1641 min_gallop -= min_gallop > 1;
1642 ms->min_gallop = min_gallop;
embg1e34da42018-01-28 20:03:23 -07001643 k = gallop_right(ms, ssb.keys[0], ssa.keys, na, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001644 acount = k;
1645 if (k) {
1646 if (k < 0)
1647 goto Fail;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001648 sortslice_memcpy(&dest, 0, &ssa, 0, k);
1649 sortslice_advance(&dest, k);
1650 sortslice_advance(&ssa, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001651 na -= k;
1652 if (na == 1)
1653 goto CopyB;
1654 /* na==0 is impossible now if the comparison
1655 * function is consistent, but we can't assume
1656 * that it is.
1657 */
1658 if (na == 0)
1659 goto Succeed;
1660 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001661 sortslice_copy_incr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001662 --nb;
1663 if (nb == 0)
1664 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001665
embg1e34da42018-01-28 20:03:23 -07001666 k = gallop_left(ms, ssa.keys[0], ssb.keys, nb, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001667 bcount = k;
1668 if (k) {
1669 if (k < 0)
1670 goto Fail;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001671 sortslice_memmove(&dest, 0, &ssb, 0, k);
1672 sortslice_advance(&dest, k);
1673 sortslice_advance(&ssb, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001674 nb -= k;
1675 if (nb == 0)
1676 goto Succeed;
1677 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001678 sortslice_copy_incr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001679 --na;
1680 if (na == 1)
1681 goto CopyB;
1682 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
1683 ++min_gallop; /* penalize it for leaving galloping mode */
1684 ms->min_gallop = min_gallop;
1685 }
Tim Petersa64dc242002-08-01 02:13:36 +00001686Succeed:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001687 result = 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001688Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001689 if (na)
Daniel Stutzbach98338222010-12-02 21:55:33 +00001690 sortslice_memcpy(&dest, 0, &ssa, 0, na);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001691 return result;
Tim Petersa64dc242002-08-01 02:13:36 +00001692CopyB:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001693 assert(na == 1 && nb > 0);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001694 /* The last element of ssa belongs at the end of the merge. */
1695 sortslice_memmove(&dest, 0, &ssb, 0, nb);
1696 sortslice_copy(&dest, nb, &ssa, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001697 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001698}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001699
Daniel Stutzbach98338222010-12-02 21:55:33 +00001700/* Merge the na elements starting at pa with the nb elements starting at
1701 * ssb.keys = ssa.keys + na in a stable way, in-place. na and nb must be > 0.
1702 * Must also have that ssa.keys[na-1] belongs at the end of the merge, and
1703 * should have na >= nb. See listsort.txt for more info. Return 0 if
1704 * successful, -1 if error.
Tim Petersa64dc242002-08-01 02:13:36 +00001705 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001706static Py_ssize_t
Daniel Stutzbach98338222010-12-02 21:55:33 +00001707merge_hi(MergeState *ms, sortslice ssa, Py_ssize_t na,
1708 sortslice ssb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001709{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001710 Py_ssize_t k;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001711 sortslice dest, basea, baseb;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001712 int result = -1; /* guilty until proved innocent */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001713 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001714
Daniel Stutzbach98338222010-12-02 21:55:33 +00001715 assert(ms && ssa.keys && ssb.keys && na > 0 && nb > 0);
1716 assert(ssa.keys + na == ssb.keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001717 if (MERGE_GETMEM(ms, nb) < 0)
1718 return -1;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001719 dest = ssb;
1720 sortslice_advance(&dest, nb-1);
1721 sortslice_memcpy(&ms->a, 0, &ssb, 0, nb);
1722 basea = ssa;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001723 baseb = ms->a;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001724 ssb.keys = ms->a.keys + nb - 1;
1725 if (ssb.values != NULL)
1726 ssb.values = ms->a.values + nb - 1;
1727 sortslice_advance(&ssa, na - 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001728
Daniel Stutzbach98338222010-12-02 21:55:33 +00001729 sortslice_copy_decr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001730 --na;
1731 if (na == 0)
1732 goto Succeed;
1733 if (nb == 1)
1734 goto CopyA;
Tim Petersa64dc242002-08-01 02:13:36 +00001735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 min_gallop = ms->min_gallop;
1737 for (;;) {
1738 Py_ssize_t acount = 0; /* # of times A won in a row */
1739 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001740
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001741 /* Do the straightforward thing until (if ever) one run
1742 * appears to win consistently.
1743 */
1744 for (;;) {
1745 assert(na > 0 && nb > 1);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001746 k = ISLT(ssb.keys[0], ssa.keys[0]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001747 if (k) {
1748 if (k < 0)
1749 goto Fail;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001750 sortslice_copy_decr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001751 ++acount;
1752 bcount = 0;
1753 --na;
1754 if (na == 0)
1755 goto Succeed;
1756 if (acount >= min_gallop)
1757 break;
1758 }
1759 else {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001760 sortslice_copy_decr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001761 ++bcount;
1762 acount = 0;
1763 --nb;
1764 if (nb == 1)
1765 goto CopyA;
1766 if (bcount >= min_gallop)
1767 break;
1768 }
1769 }
Tim Petersa64dc242002-08-01 02:13:36 +00001770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001771 /* One run is winning so consistently that galloping may
1772 * be a huge win. So try that, and continue galloping until
1773 * (if ever) neither run appears to be winning consistently
1774 * anymore.
1775 */
1776 ++min_gallop;
1777 do {
1778 assert(na > 0 && nb > 1);
1779 min_gallop -= min_gallop > 1;
1780 ms->min_gallop = min_gallop;
embg1e34da42018-01-28 20:03:23 -07001781 k = gallop_right(ms, ssb.keys[0], basea.keys, na, na-1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001782 if (k < 0)
1783 goto Fail;
1784 k = na - k;
1785 acount = k;
1786 if (k) {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001787 sortslice_advance(&dest, -k);
1788 sortslice_advance(&ssa, -k);
1789 sortslice_memmove(&dest, 1, &ssa, 1, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001790 na -= k;
1791 if (na == 0)
1792 goto Succeed;
1793 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001794 sortslice_copy_decr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001795 --nb;
1796 if (nb == 1)
1797 goto CopyA;
Tim Petersa64dc242002-08-01 02:13:36 +00001798
embg1e34da42018-01-28 20:03:23 -07001799 k = gallop_left(ms, ssa.keys[0], baseb.keys, nb, nb-1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001800 if (k < 0)
1801 goto Fail;
1802 k = nb - k;
1803 bcount = k;
1804 if (k) {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001805 sortslice_advance(&dest, -k);
1806 sortslice_advance(&ssb, -k);
1807 sortslice_memcpy(&dest, 1, &ssb, 1, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001808 nb -= k;
1809 if (nb == 1)
1810 goto CopyA;
1811 /* nb==0 is impossible now if the comparison
1812 * function is consistent, but we can't assume
1813 * that it is.
1814 */
1815 if (nb == 0)
1816 goto Succeed;
1817 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001818 sortslice_copy_decr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001819 --na;
1820 if (na == 0)
1821 goto Succeed;
1822 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
1823 ++min_gallop; /* penalize it for leaving galloping mode */
1824 ms->min_gallop = min_gallop;
1825 }
Tim Petersa64dc242002-08-01 02:13:36 +00001826Succeed:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001827 result = 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001828Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001829 if (nb)
Daniel Stutzbach98338222010-12-02 21:55:33 +00001830 sortslice_memcpy(&dest, -(nb-1), &baseb, 0, nb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001831 return result;
Tim Petersa64dc242002-08-01 02:13:36 +00001832CopyA:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001833 assert(nb == 1 && na > 0);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001834 /* The first element of ssb belongs at the front of the merge. */
1835 sortslice_memmove(&dest, 1-na, &ssa, 1-na, na);
1836 sortslice_advance(&dest, -na);
1837 sortslice_advance(&ssa, -na);
1838 sortslice_copy(&dest, 0, &ssb, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001839 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001840}
1841
1842/* Merge the two runs at stack indices i and i+1.
1843 * Returns 0 on success, -1 on error.
1844 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001845static Py_ssize_t
1846merge_at(MergeState *ms, Py_ssize_t i)
Tim Petersa64dc242002-08-01 02:13:36 +00001847{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001848 sortslice ssa, ssb;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001849 Py_ssize_t na, nb;
1850 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001851
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001852 assert(ms != NULL);
1853 assert(ms->n >= 2);
1854 assert(i >= 0);
1855 assert(i == ms->n - 2 || i == ms->n - 3);
Tim Petersa64dc242002-08-01 02:13:36 +00001856
Daniel Stutzbach98338222010-12-02 21:55:33 +00001857 ssa = ms->pending[i].base;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001858 na = ms->pending[i].len;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001859 ssb = ms->pending[i+1].base;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001860 nb = ms->pending[i+1].len;
1861 assert(na > 0 && nb > 0);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001862 assert(ssa.keys + na == ssb.keys);
Tim Petersa64dc242002-08-01 02:13:36 +00001863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001864 /* Record the length of the combined runs; if i is the 3rd-last
1865 * run now, also slide over the last run (which isn't involved
1866 * in this merge). The current run i+1 goes away in any case.
1867 */
1868 ms->pending[i].len = na + nb;
1869 if (i == ms->n - 3)
1870 ms->pending[i+1] = ms->pending[i+2];
1871 --ms->n;
Tim Petersa64dc242002-08-01 02:13:36 +00001872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001873 /* Where does b start in a? Elements in a before that can be
1874 * ignored (already in place).
1875 */
embg1e34da42018-01-28 20:03:23 -07001876 k = gallop_right(ms, *ssb.keys, ssa.keys, na, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001877 if (k < 0)
1878 return -1;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001879 sortslice_advance(&ssa, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001880 na -= k;
1881 if (na == 0)
1882 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001884 /* Where does a end in b? Elements in b after that can be
1885 * ignored (already in place).
1886 */
embg1e34da42018-01-28 20:03:23 -07001887 nb = gallop_left(ms, ssa.keys[na-1], ssb.keys, nb, nb-1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001888 if (nb <= 0)
1889 return nb;
Tim Petersa64dc242002-08-01 02:13:36 +00001890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001891 /* Merge what remains of the runs, using a temp array with
1892 * min(na, nb) elements.
1893 */
1894 if (na <= nb)
Daniel Stutzbach98338222010-12-02 21:55:33 +00001895 return merge_lo(ms, ssa, na, ssb, nb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001896 else
Daniel Stutzbach98338222010-12-02 21:55:33 +00001897 return merge_hi(ms, ssa, na, ssb, nb);
Tim Petersa64dc242002-08-01 02:13:36 +00001898}
1899
1900/* Examine the stack of runs waiting to be merged, merging adjacent runs
1901 * until the stack invariants are re-established:
1902 *
1903 * 1. len[-3] > len[-2] + len[-1]
1904 * 2. len[-2] > len[-1]
1905 *
1906 * See listsort.txt for more info.
1907 *
1908 * Returns 0 on success, -1 on error.
1909 */
1910static int
1911merge_collapse(MergeState *ms)
1912{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001913 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001914
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001915 assert(ms);
1916 while (ms->n > 1) {
1917 Py_ssize_t n = ms->n - 2;
Benjamin Petersonb808d592015-02-25 10:12:26 -05001918 if ((n > 0 && p[n-1].len <= p[n].len + p[n+1].len) ||
1919 (n > 1 && p[n-2].len <= p[n-1].len + p[n].len)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001920 if (p[n-1].len < p[n+1].len)
1921 --n;
1922 if (merge_at(ms, n) < 0)
1923 return -1;
1924 }
1925 else if (p[n].len <= p[n+1].len) {
embg1e34da42018-01-28 20:03:23 -07001926 if (merge_at(ms, n) < 0)
1927 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001928 }
1929 else
1930 break;
1931 }
1932 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001933}
1934
1935/* Regardless of invariants, merge all runs on the stack until only one
1936 * remains. This is used at the end of the mergesort.
1937 *
1938 * Returns 0 on success, -1 on error.
1939 */
1940static int
1941merge_force_collapse(MergeState *ms)
1942{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001943 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001945 assert(ms);
1946 while (ms->n > 1) {
1947 Py_ssize_t n = ms->n - 2;
1948 if (n > 0 && p[n-1].len < p[n+1].len)
1949 --n;
1950 if (merge_at(ms, n) < 0)
1951 return -1;
1952 }
1953 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001954}
1955
1956/* Compute a good value for the minimum run length; natural runs shorter
1957 * than this are boosted artificially via binary insertion.
1958 *
1959 * If n < 64, return n (it's too small to bother with fancy stuff).
1960 * Else if n is an exact power of 2, return 32.
1961 * Else return an int k, 32 <= k <= 64, such that n/k is close to, but
1962 * strictly less than, an exact power of 2.
1963 *
1964 * See listsort.txt for more info.
1965 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001966static Py_ssize_t
1967merge_compute_minrun(Py_ssize_t n)
Tim Petersa64dc242002-08-01 02:13:36 +00001968{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001969 Py_ssize_t r = 0; /* becomes 1 if any 1 bits are shifted off */
Tim Petersa64dc242002-08-01 02:13:36 +00001970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001971 assert(n >= 0);
1972 while (n >= 64) {
1973 r |= n & 1;
1974 n >>= 1;
1975 }
1976 return n + r;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001977}
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001978
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001979static void
Daniel Stutzbach98338222010-12-02 21:55:33 +00001980reverse_sortslice(sortslice *s, Py_ssize_t n)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001981{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001982 reverse_slice(s->keys, &s->keys[n]);
1983 if (s->values != NULL)
1984 reverse_slice(s->values, &s->values[n]);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001985}
1986
embg1e34da42018-01-28 20:03:23 -07001987/* Here we define custom comparison functions to optimize for the cases one commonly
1988 * encounters in practice: homogeneous lists, often of one of the basic types. */
1989
1990/* This struct holds the comparison function and helper functions
1991 * selected in the pre-sort check. */
1992
1993/* These are the special case compare functions.
1994 * ms->key_compare will always point to one of these: */
1995
1996/* Heterogeneous compare: default, always safe to fall back on. */
1997static int
1998safe_object_compare(PyObject *v, PyObject *w, MergeState *ms)
1999{
2000 /* No assumptions necessary! */
2001 return PyObject_RichCompareBool(v, w, Py_LT);
2002}
2003
2004/* Homogeneous compare: safe for any two compareable objects of the same type.
2005 * (ms->key_richcompare is set to ob_type->tp_richcompare in the
2006 * pre-sort check.)
2007 */
2008static int
2009unsafe_object_compare(PyObject *v, PyObject *w, MergeState *ms)
2010{
2011 PyObject *res_obj; int res;
2012
2013 /* No assumptions, because we check first: */
Victor Stinner58ac7002020-02-07 03:04:21 +01002014 if (Py_TYPE(v)->tp_richcompare != ms->key_richcompare)
embg1e34da42018-01-28 20:03:23 -07002015 return PyObject_RichCompareBool(v, w, Py_LT);
2016
2017 assert(ms->key_richcompare != NULL);
2018 res_obj = (*(ms->key_richcompare))(v, w, Py_LT);
2019
2020 if (res_obj == Py_NotImplemented) {
2021 Py_DECREF(res_obj);
2022 return PyObject_RichCompareBool(v, w, Py_LT);
2023 }
2024 if (res_obj == NULL)
2025 return -1;
2026
2027 if (PyBool_Check(res_obj)) {
2028 res = (res_obj == Py_True);
2029 }
2030 else {
2031 res = PyObject_IsTrue(res_obj);
2032 }
2033 Py_DECREF(res_obj);
2034
2035 /* Note that we can't assert
2036 * res == PyObject_RichCompareBool(v, w, Py_LT);
2037 * because of evil compare functions like this:
2038 * lambda a, b: int(random.random() * 3) - 1)
2039 * (which is actually in test_sort.py) */
2040 return res;
2041}
2042
2043/* Latin string compare: safe for any two latin (one byte per char) strings. */
2044static int
2045unsafe_latin_compare(PyObject *v, PyObject *w, MergeState *ms)
2046{
Victor Stinner8017b802018-01-29 13:47:06 +01002047 Py_ssize_t len;
2048 int res;
embg1e34da42018-01-28 20:03:23 -07002049
2050 /* Modified from Objects/unicodeobject.c:unicode_compare, assuming: */
Andy Lesterdffe4c02020-03-04 07:15:20 -06002051 assert(Py_IS_TYPE(v, &PyUnicode_Type));
2052 assert(Py_IS_TYPE(w, &PyUnicode_Type));
embg1e34da42018-01-28 20:03:23 -07002053 assert(PyUnicode_KIND(v) == PyUnicode_KIND(w));
2054 assert(PyUnicode_KIND(v) == PyUnicode_1BYTE_KIND);
2055
2056 len = Py_MIN(PyUnicode_GET_LENGTH(v), PyUnicode_GET_LENGTH(w));
2057 res = memcmp(PyUnicode_DATA(v), PyUnicode_DATA(w), len);
2058
2059 res = (res != 0 ?
2060 res < 0 :
2061 PyUnicode_GET_LENGTH(v) < PyUnicode_GET_LENGTH(w));
2062
2063 assert(res == PyObject_RichCompareBool(v, w, Py_LT));;
2064 return res;
2065}
2066
2067/* Bounded int compare: compare any two longs that fit in a single machine word. */
2068static int
2069unsafe_long_compare(PyObject *v, PyObject *w, MergeState *ms)
2070{
2071 PyLongObject *vl, *wl; sdigit v0, w0; int res;
2072
2073 /* Modified from Objects/longobject.c:long_compare, assuming: */
Andy Lesterdffe4c02020-03-04 07:15:20 -06002074 assert(Py_IS_TYPE(v, &PyLong_Type));
2075 assert(Py_IS_TYPE(w, &PyLong_Type));
embg1e34da42018-01-28 20:03:23 -07002076 assert(Py_ABS(Py_SIZE(v)) <= 1);
2077 assert(Py_ABS(Py_SIZE(w)) <= 1);
2078
2079 vl = (PyLongObject*)v;
2080 wl = (PyLongObject*)w;
2081
2082 v0 = Py_SIZE(vl) == 0 ? 0 : (sdigit)vl->ob_digit[0];
2083 w0 = Py_SIZE(wl) == 0 ? 0 : (sdigit)wl->ob_digit[0];
2084
2085 if (Py_SIZE(vl) < 0)
2086 v0 = -v0;
2087 if (Py_SIZE(wl) < 0)
2088 w0 = -w0;
2089
2090 res = v0 < w0;
2091 assert(res == PyObject_RichCompareBool(v, w, Py_LT));
2092 return res;
2093}
2094
2095/* Float compare: compare any two floats. */
2096static int
2097unsafe_float_compare(PyObject *v, PyObject *w, MergeState *ms)
2098{
2099 int res;
2100
2101 /* Modified from Objects/floatobject.c:float_richcompare, assuming: */
Andy Lesterdffe4c02020-03-04 07:15:20 -06002102 assert(Py_IS_TYPE(v, &PyFloat_Type));
2103 assert(Py_IS_TYPE(w, &PyFloat_Type));
embg1e34da42018-01-28 20:03:23 -07002104
2105 res = PyFloat_AS_DOUBLE(v) < PyFloat_AS_DOUBLE(w);
2106 assert(res == PyObject_RichCompareBool(v, w, Py_LT));
2107 return res;
2108}
2109
2110/* Tuple compare: compare *any* two tuples, using
2111 * ms->tuple_elem_compare to compare the first elements, which is set
2112 * using the same pre-sort check as we use for ms->key_compare,
2113 * but run on the list [x[0] for x in L]. This allows us to optimize compares
2114 * on two levels (as long as [x[0] for x in L] is type-homogeneous.) The idea is
2115 * that most tuple compares don't involve x[1:]. */
2116static int
2117unsafe_tuple_compare(PyObject *v, PyObject *w, MergeState *ms)
2118{
2119 PyTupleObject *vt, *wt;
2120 Py_ssize_t i, vlen, wlen;
2121 int k;
2122
2123 /* Modified from Objects/tupleobject.c:tuplerichcompare, assuming: */
Andy Lesterdffe4c02020-03-04 07:15:20 -06002124 assert(Py_IS_TYPE(v, &PyTuple_Type));
2125 assert(Py_IS_TYPE(w, &PyTuple_Type));
embg1e34da42018-01-28 20:03:23 -07002126 assert(Py_SIZE(v) > 0);
2127 assert(Py_SIZE(w) > 0);
2128
2129 vt = (PyTupleObject *)v;
2130 wt = (PyTupleObject *)w;
2131
2132 vlen = Py_SIZE(vt);
2133 wlen = Py_SIZE(wt);
2134
2135 for (i = 0; i < vlen && i < wlen; i++) {
2136 k = PyObject_RichCompareBool(vt->ob_item[i], wt->ob_item[i], Py_EQ);
2137 if (k < 0)
2138 return -1;
2139 if (!k)
2140 break;
2141 }
2142
2143 if (i >= vlen || i >= wlen)
2144 return vlen < wlen;
2145
2146 if (i == 0)
2147 return ms->tuple_elem_compare(vt->ob_item[i], wt->ob_item[i], ms);
2148 else
2149 return PyObject_RichCompareBool(vt->ob_item[i], wt->ob_item[i], Py_LT);
2150}
2151
Tim Petersa64dc242002-08-01 02:13:36 +00002152/* An adaptive, stable, natural mergesort. See listsort.txt.
2153 * Returns Py_None on success, NULL on error. Even in case of error, the
2154 * list will be some permutation of its input state (nothing is lost or
2155 * duplicated).
2156 */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002157/*[clinic input]
2158list.sort
2159
2160 *
2161 key as keyfunc: object = None
Serhiy Storchaka202fda52017-03-12 10:10:47 +02002162 reverse: bool(accept={int}) = False
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002163
Tim Hoffmann5c224762019-06-01 06:10:02 +02002164Sort the list in ascending order and return None.
2165
2166The sort is in-place (i.e. the list itself is modified) and stable (i.e. the
2167order of two equal elements is maintained).
2168
2169If a key function is given, apply it once to each list item and sort them,
2170ascending or descending, according to their function values.
2171
2172The reverse flag can be set to sort in descending order.
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002173[clinic start generated code]*/
2174
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002175static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002176list_sort_impl(PyListObject *self, PyObject *keyfunc, int reverse)
Tim Hoffmann5c224762019-06-01 06:10:02 +02002177/*[clinic end generated code: output=57b9f9c5e23fbe42 input=cb56cd179a713060]*/
Guido van Rossum3f236de1996-12-10 23:55:39 +00002178{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002179 MergeState ms;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002180 Py_ssize_t nremaining;
2181 Py_ssize_t minrun;
Daniel Stutzbach98338222010-12-02 21:55:33 +00002182 sortslice lo;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002183 Py_ssize_t saved_ob_size, saved_allocated;
2184 PyObject **saved_ob_item;
2185 PyObject **final_ob_item;
2186 PyObject *result = NULL; /* guilty until proved innocent */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002187 Py_ssize_t i;
Daniel Stutzbach98338222010-12-02 21:55:33 +00002188 PyObject **keys;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002189
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002190 assert(self != NULL);
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002191 assert(PyList_Check(self));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002192 if (keyfunc == Py_None)
2193 keyfunc = NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002195 /* The list is temporarily made empty, so that mutations performed
2196 * by comparison functions can't affect the slice of memory we're
2197 * sorting (allowing mutations during sorting is a core-dump
2198 * factory, since ob_item may change).
2199 */
2200 saved_ob_size = Py_SIZE(self);
2201 saved_ob_item = self->ob_item;
2202 saved_allocated = self->allocated;
Victor Stinner60ac6ed2020-02-07 23:18:08 +01002203 Py_SET_SIZE(self, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002204 self->ob_item = NULL;
2205 self->allocated = -1; /* any operation will reset it to >= 0 */
Tim Peters330f9e92002-07-19 07:05:44 +00002206
Daniel Stutzbach98338222010-12-02 21:55:33 +00002207 if (keyfunc == NULL) {
2208 keys = NULL;
2209 lo.keys = saved_ob_item;
2210 lo.values = NULL;
2211 }
2212 else {
2213 if (saved_ob_size < MERGESTATE_TEMP_SIZE/2)
2214 /* Leverage stack space we allocated but won't otherwise use */
2215 keys = &ms.temparray[saved_ob_size+1];
2216 else {
2217 keys = PyMem_MALLOC(sizeof(PyObject *) * saved_ob_size);
Benjamin Peterson0823ffb2015-04-23 17:04:36 -04002218 if (keys == NULL) {
2219 PyErr_NoMemory();
2220 goto keyfunc_fail;
2221 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002222 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00002223
2224 for (i = 0; i < saved_ob_size ; i++) {
Petr Viktorinffd97532020-02-11 17:46:57 +01002225 keys[i] = PyObject_CallOneArg(keyfunc, saved_ob_item[i]);
Daniel Stutzbach98338222010-12-02 21:55:33 +00002226 if (keys[i] == NULL) {
2227 for (i=i-1 ; i>=0 ; i--)
2228 Py_DECREF(keys[i]);
Benjamin Peterson4a42cd42014-03-15 12:21:28 -05002229 if (saved_ob_size >= MERGESTATE_TEMP_SIZE/2)
Daniel Stutzbach8eda5f72011-03-02 23:37:50 +00002230 PyMem_FREE(keys);
Daniel Stutzbach98338222010-12-02 21:55:33 +00002231 goto keyfunc_fail;
2232 }
2233 }
2234
2235 lo.keys = keys;
2236 lo.values = saved_ob_item;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002237 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002238
embg1e34da42018-01-28 20:03:23 -07002239
2240 /* The pre-sort check: here's where we decide which compare function to use.
2241 * How much optimization is safe? We test for homogeneity with respect to
2242 * several properties that are expensive to check at compare-time, and
2243 * set ms appropriately. */
2244 if (saved_ob_size > 1) {
2245 /* Assume the first element is representative of the whole list. */
Andy Lesterdffe4c02020-03-04 07:15:20 -06002246 int keys_are_in_tuples = (Py_IS_TYPE(lo.keys[0], &PyTuple_Type) &&
embg1e34da42018-01-28 20:03:23 -07002247 Py_SIZE(lo.keys[0]) > 0);
2248
2249 PyTypeObject* key_type = (keys_are_in_tuples ?
Victor Stinner58ac7002020-02-07 03:04:21 +01002250 Py_TYPE(PyTuple_GET_ITEM(lo.keys[0], 0)) :
2251 Py_TYPE(lo.keys[0]));
embg1e34da42018-01-28 20:03:23 -07002252
2253 int keys_are_all_same_type = 1;
2254 int strings_are_latin = 1;
2255 int ints_are_bounded = 1;
2256
2257 /* Prove that assumption by checking every key. */
embg1e34da42018-01-28 20:03:23 -07002258 for (i=0; i < saved_ob_size; i++) {
2259
2260 if (keys_are_in_tuples &&
Andy Lesterdffe4c02020-03-04 07:15:20 -06002261 !(Py_IS_TYPE(lo.keys[i], &PyTuple_Type) && Py_SIZE(lo.keys[i]) != 0)) {
embg1e34da42018-01-28 20:03:23 -07002262 keys_are_in_tuples = 0;
2263 keys_are_all_same_type = 0;
2264 break;
2265 }
2266
2267 /* Note: for lists of tuples, key is the first element of the tuple
2268 * lo.keys[i], not lo.keys[i] itself! We verify type-homogeneity
2269 * for lists of tuples in the if-statement directly above. */
2270 PyObject *key = (keys_are_in_tuples ?
2271 PyTuple_GET_ITEM(lo.keys[i], 0) :
2272 lo.keys[i]);
2273
Andy Lesterdffe4c02020-03-04 07:15:20 -06002274 if (!Py_IS_TYPE(key, key_type)) {
embg1e34da42018-01-28 20:03:23 -07002275 keys_are_all_same_type = 0;
Rémi Lapeyredd5417a2019-03-25 08:25:37 +01002276 /* If keys are in tuple we must loop over the whole list to make
2277 sure all items are tuples */
2278 if (!keys_are_in_tuples) {
2279 break;
2280 }
embg1e34da42018-01-28 20:03:23 -07002281 }
2282
Rémi Lapeyredd5417a2019-03-25 08:25:37 +01002283 if (keys_are_all_same_type) {
2284 if (key_type == &PyLong_Type &&
2285 ints_are_bounded &&
2286 Py_ABS(Py_SIZE(key)) > 1) {
2287
embg1e34da42018-01-28 20:03:23 -07002288 ints_are_bounded = 0;
Rémi Lapeyredd5417a2019-03-25 08:25:37 +01002289 }
2290 else if (key_type == &PyUnicode_Type &&
2291 strings_are_latin &&
2292 PyUnicode_KIND(key) != PyUnicode_1BYTE_KIND) {
2293
2294 strings_are_latin = 0;
2295 }
2296 }
embg1e34da42018-01-28 20:03:23 -07002297 }
embg1e34da42018-01-28 20:03:23 -07002298
2299 /* Choose the best compare, given what we now know about the keys. */
2300 if (keys_are_all_same_type) {
2301
2302 if (key_type == &PyUnicode_Type && strings_are_latin) {
2303 ms.key_compare = unsafe_latin_compare;
2304 }
2305 else if (key_type == &PyLong_Type && ints_are_bounded) {
2306 ms.key_compare = unsafe_long_compare;
2307 }
2308 else if (key_type == &PyFloat_Type) {
2309 ms.key_compare = unsafe_float_compare;
2310 }
2311 else if ((ms.key_richcompare = key_type->tp_richcompare) != NULL) {
2312 ms.key_compare = unsafe_object_compare;
2313 }
Zackery Spytzebc793d2019-02-21 00:47:14 -07002314 else {
2315 ms.key_compare = safe_object_compare;
2316 }
embg1e34da42018-01-28 20:03:23 -07002317 }
2318 else {
2319 ms.key_compare = safe_object_compare;
2320 }
2321
2322 if (keys_are_in_tuples) {
2323 /* Make sure we're not dealing with tuples of tuples
2324 * (remember: here, key_type refers list [key[0] for key in keys]) */
Rémi Lapeyredd5417a2019-03-25 08:25:37 +01002325 if (key_type == &PyTuple_Type) {
embg1e34da42018-01-28 20:03:23 -07002326 ms.tuple_elem_compare = safe_object_compare;
Rémi Lapeyredd5417a2019-03-25 08:25:37 +01002327 }
2328 else {
embg1e34da42018-01-28 20:03:23 -07002329 ms.tuple_elem_compare = ms.key_compare;
Rémi Lapeyredd5417a2019-03-25 08:25:37 +01002330 }
embg1e34da42018-01-28 20:03:23 -07002331
2332 ms.key_compare = unsafe_tuple_compare;
2333 }
2334 }
2335 /* End of pre-sort check: ms is now set properly! */
2336
Daniel Stutzbach98338222010-12-02 21:55:33 +00002337 merge_init(&ms, saved_ob_size, keys != NULL);
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002339 nremaining = saved_ob_size;
2340 if (nremaining < 2)
2341 goto succeed;
Tim Peters330f9e92002-07-19 07:05:44 +00002342
Benjamin Peterson05380642010-08-23 19:35:39 +00002343 /* Reverse sort stability achieved by initially reversing the list,
2344 applying a stable forward sort, then reversing the final result. */
Daniel Stutzbach98338222010-12-02 21:55:33 +00002345 if (reverse) {
2346 if (keys != NULL)
2347 reverse_slice(&keys[0], &keys[saved_ob_size]);
2348 reverse_slice(&saved_ob_item[0], &saved_ob_item[saved_ob_size]);
2349 }
Benjamin Peterson05380642010-08-23 19:35:39 +00002350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002351 /* March over the array once, left to right, finding natural runs,
2352 * and extending short natural runs to minrun elements.
2353 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002354 minrun = merge_compute_minrun(nremaining);
2355 do {
2356 int descending;
2357 Py_ssize_t n;
Tim Peters330f9e92002-07-19 07:05:44 +00002358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002359 /* Identify next run. */
embg1e34da42018-01-28 20:03:23 -07002360 n = count_run(&ms, lo.keys, lo.keys + nremaining, &descending);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002361 if (n < 0)
2362 goto fail;
2363 if (descending)
Daniel Stutzbach98338222010-12-02 21:55:33 +00002364 reverse_sortslice(&lo, n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002365 /* If short, extend to min(minrun, nremaining). */
2366 if (n < minrun) {
2367 const Py_ssize_t force = nremaining <= minrun ?
2368 nremaining : minrun;
embg1e34da42018-01-28 20:03:23 -07002369 if (binarysort(&ms, lo, lo.keys + force, lo.keys + n) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002370 goto fail;
2371 n = force;
2372 }
2373 /* Push run onto pending-runs stack, and maybe merge. */
2374 assert(ms.n < MAX_MERGE_PENDING);
2375 ms.pending[ms.n].base = lo;
2376 ms.pending[ms.n].len = n;
2377 ++ms.n;
2378 if (merge_collapse(&ms) < 0)
2379 goto fail;
2380 /* Advance to find next run. */
Daniel Stutzbach98338222010-12-02 21:55:33 +00002381 sortslice_advance(&lo, n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002382 nremaining -= n;
2383 } while (nremaining);
Tim Peters330f9e92002-07-19 07:05:44 +00002384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002385 if (merge_force_collapse(&ms) < 0)
2386 goto fail;
2387 assert(ms.n == 1);
Daniel Stutzbach98338222010-12-02 21:55:33 +00002388 assert(keys == NULL
2389 ? ms.pending[0].base.keys == saved_ob_item
2390 : ms.pending[0].base.keys == &keys[0]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002391 assert(ms.pending[0].len == saved_ob_size);
Daniel Stutzbach98338222010-12-02 21:55:33 +00002392 lo = ms.pending[0].base;
Tim Petersa64dc242002-08-01 02:13:36 +00002393
2394succeed:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002395 result = Py_None;
Tim Peters330f9e92002-07-19 07:05:44 +00002396fail:
Daniel Stutzbach98338222010-12-02 21:55:33 +00002397 if (keys != NULL) {
2398 for (i = 0; i < saved_ob_size; i++)
2399 Py_DECREF(keys[i]);
Benjamin Petersonef87f8c2014-03-14 21:54:31 -05002400 if (saved_ob_size >= MERGESTATE_TEMP_SIZE/2)
Daniel Stutzbach98338222010-12-02 21:55:33 +00002401 PyMem_FREE(keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002402 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002403
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002404 if (self->allocated != -1 && result != NULL) {
2405 /* The user mucked with the list during the sort,
2406 * and we don't already have another error to report.
2407 */
2408 PyErr_SetString(PyExc_ValueError, "list modified during sort");
2409 result = NULL;
2410 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002412 if (reverse && saved_ob_size > 1)
2413 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002415 merge_freemem(&ms);
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002416
Daniel Stutzbach98338222010-12-02 21:55:33 +00002417keyfunc_fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002418 final_ob_item = self->ob_item;
2419 i = Py_SIZE(self);
Victor Stinner60ac6ed2020-02-07 23:18:08 +01002420 Py_SET_SIZE(self, saved_ob_size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002421 self->ob_item = saved_ob_item;
2422 self->allocated = saved_allocated;
2423 if (final_ob_item != NULL) {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002424 /* we cannot use _list_clear() for this because it does not
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002425 guarantee that the list is really empty when it returns */
2426 while (--i >= 0) {
2427 Py_XDECREF(final_ob_item[i]);
2428 }
2429 PyMem_FREE(final_ob_item);
2430 }
2431 Py_XINCREF(result);
2432 return result;
Guido van Rossum3f236de1996-12-10 23:55:39 +00002433}
Tim Peters330f9e92002-07-19 07:05:44 +00002434#undef IFLT
Tim Peters66860f62002-08-04 17:47:26 +00002435#undef ISLT
Tim Peters330f9e92002-07-19 07:05:44 +00002436
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002437int
Fred Drakea2f55112000-07-09 15:16:51 +00002438PyList_Sort(PyObject *v)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002439{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002440 if (v == NULL || !PyList_Check(v)) {
2441 PyErr_BadInternalCall();
2442 return -1;
2443 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002444 v = list_sort_impl((PyListObject *)v, NULL, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002445 if (v == NULL)
2446 return -1;
2447 Py_DECREF(v);
2448 return 0;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002449}
2450
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002451/*[clinic input]
2452list.reverse
2453
2454Reverse *IN PLACE*.
2455[clinic start generated code]*/
2456
Guido van Rossumb86c5492001-02-12 22:06:02 +00002457static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002458list_reverse_impl(PyListObject *self)
2459/*[clinic end generated code: output=482544fc451abea9 input=eefd4c3ae1bc9887]*/
Guido van Rossumb86c5492001-02-12 22:06:02 +00002460{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002461 if (Py_SIZE(self) > 1)
2462 reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
2463 Py_RETURN_NONE;
Guido van Rossumed98d481991-03-06 13:07:53 +00002464}
2465
Guido van Rossum84c76f51990-10-30 13:32:20 +00002466int
Fred Drakea2f55112000-07-09 15:16:51 +00002467PyList_Reverse(PyObject *v)
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002468{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002469 PyListObject *self = (PyListObject *)v;
Tim Peters6063e262002-08-08 01:06:39 +00002470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002471 if (v == NULL || !PyList_Check(v)) {
2472 PyErr_BadInternalCall();
2473 return -1;
2474 }
2475 if (Py_SIZE(self) > 1)
2476 reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
2477 return 0;
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002478}
2479
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002480PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00002481PyList_AsTuple(PyObject *v)
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002482{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002483 if (v == NULL || !PyList_Check(v)) {
2484 PyErr_BadInternalCall();
2485 return NULL;
2486 }
Sergey Fedoseev234531b2019-02-25 21:59:12 +05002487 return _PyTuple_FromArray(((PyListObject *)v)->ob_item, Py_SIZE(v));
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002488}
2489
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002490/*[clinic input]
2491list.index
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002492
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002493 value: object
Serhiy Storchaka80ec8362017-03-19 19:37:40 +02002494 start: slice_index(accept={int}) = 0
2495 stop: slice_index(accept={int}, c_default="PY_SSIZE_T_MAX") = sys.maxsize
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002496 /
2497
2498Return first index of value.
2499
2500Raises ValueError if the value is not present.
2501[clinic start generated code]*/
2502
2503static PyObject *
2504list_index_impl(PyListObject *self, PyObject *value, Py_ssize_t start,
2505 Py_ssize_t stop)
Serhiy Storchaka80ec8362017-03-19 19:37:40 +02002506/*[clinic end generated code: output=ec51b88787e4e481 input=40ec5826303a0eb1]*/
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002507{
2508 Py_ssize_t i;
2509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002510 if (start < 0) {
2511 start += Py_SIZE(self);
2512 if (start < 0)
2513 start = 0;
2514 }
2515 if (stop < 0) {
2516 stop += Py_SIZE(self);
2517 if (stop < 0)
2518 stop = 0;
2519 }
2520 for (i = start; i < stop && i < Py_SIZE(self); i++) {
Zackery Spytzd9e561d2019-12-30 12:32:58 -07002521 PyObject *obj = self->ob_item[i];
2522 Py_INCREF(obj);
2523 int cmp = PyObject_RichCompareBool(obj, value, Py_EQ);
2524 Py_DECREF(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002525 if (cmp > 0)
2526 return PyLong_FromSsize_t(i);
2527 else if (cmp < 0)
2528 return NULL;
2529 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002530 PyErr_Format(PyExc_ValueError, "%R is not in list", value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002531 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002532}
2533
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002534/*[clinic input]
2535list.count
2536
2537 value: object
2538 /
2539
2540Return number of occurrences of value.
2541[clinic start generated code]*/
2542
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002543static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002544list_count(PyListObject *self, PyObject *value)
2545/*[clinic end generated code: output=b1f5d284205ae714 input=3bdc3a5e6f749565]*/
Guido van Rossume6f7d181991-10-20 20:20:40 +00002546{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002547 Py_ssize_t count = 0;
2548 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002549
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002550 for (i = 0; i < Py_SIZE(self); i++) {
Zackery Spytzd9e561d2019-12-30 12:32:58 -07002551 PyObject *obj = self->ob_item[i];
Dong-hee Na14d80d02020-01-23 02:36:54 +09002552 if (obj == value) {
2553 count++;
2554 continue;
2555 }
Zackery Spytzd9e561d2019-12-30 12:32:58 -07002556 Py_INCREF(obj);
2557 int cmp = PyObject_RichCompareBool(obj, value, Py_EQ);
2558 Py_DECREF(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002559 if (cmp > 0)
2560 count++;
2561 else if (cmp < 0)
2562 return NULL;
2563 }
2564 return PyLong_FromSsize_t(count);
Guido van Rossume6f7d181991-10-20 20:20:40 +00002565}
2566
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002567/*[clinic input]
2568list.remove
2569
2570 value: object
2571 /
2572
2573Remove first occurrence of value.
2574
2575Raises ValueError if the value is not present.
2576[clinic start generated code]*/
2577
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002578static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002579list_remove(PyListObject *self, PyObject *value)
2580/*[clinic end generated code: output=f087e1951a5e30d1 input=2dc2ba5bb2fb1f82]*/
Guido van Rossumed98d481991-03-06 13:07:53 +00002581{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002582 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002584 for (i = 0; i < Py_SIZE(self); i++) {
Zackery Spytzd9e561d2019-12-30 12:32:58 -07002585 PyObject *obj = self->ob_item[i];
2586 Py_INCREF(obj);
2587 int cmp = PyObject_RichCompareBool(obj, value, Py_EQ);
2588 Py_DECREF(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002589 if (cmp > 0) {
2590 if (list_ass_slice(self, i, i+1,
2591 (PyObject *)NULL) == 0)
2592 Py_RETURN_NONE;
2593 return NULL;
2594 }
2595 else if (cmp < 0)
2596 return NULL;
2597 }
2598 PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
2599 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002600}
2601
Jeremy Hylton8caad492000-06-23 14:18:11 +00002602static int
2603list_traverse(PyListObject *o, visitproc visit, void *arg)
2604{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002605 Py_ssize_t i;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002607 for (i = Py_SIZE(o); --i >= 0; )
2608 Py_VISIT(o->ob_item[i]);
2609 return 0;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002610}
2611
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002612static PyObject *
2613list_richcompare(PyObject *v, PyObject *w, int op)
2614{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002615 PyListObject *vl, *wl;
2616 Py_ssize_t i;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002617
Brian Curtindfc80e32011-08-10 20:28:54 -05002618 if (!PyList_Check(v) || !PyList_Check(w))
2619 Py_RETURN_NOTIMPLEMENTED;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002621 vl = (PyListObject *)v;
2622 wl = (PyListObject *)w;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002623
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002624 if (Py_SIZE(vl) != Py_SIZE(wl) && (op == Py_EQ || op == Py_NE)) {
2625 /* Shortcut: if the lengths differ, the lists differ */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002626 if (op == Py_EQ)
stratakise8b19652017-11-02 11:32:54 +01002627 Py_RETURN_FALSE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002628 else
stratakise8b19652017-11-02 11:32:54 +01002629 Py_RETURN_TRUE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002630 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002631
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002632 /* Search for the first index where items are different */
2633 for (i = 0; i < Py_SIZE(vl) && i < Py_SIZE(wl); i++) {
Dong-hee Na2d5bf562019-12-31 10:04:22 +09002634 PyObject *vitem = vl->ob_item[i];
2635 PyObject *witem = wl->ob_item[i];
Inada Naokidfef9862019-12-31 10:58:37 +09002636 if (vitem == witem) {
2637 continue;
2638 }
Dong-hee Na2d5bf562019-12-31 10:04:22 +09002639
2640 Py_INCREF(vitem);
2641 Py_INCREF(witem);
sweeneydebe7ead62020-02-26 02:00:35 -05002642 int k = PyObject_RichCompareBool(vitem, witem, Py_EQ);
Dong-hee Na2d5bf562019-12-31 10:04:22 +09002643 Py_DECREF(vitem);
2644 Py_DECREF(witem);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002645 if (k < 0)
2646 return NULL;
2647 if (!k)
2648 break;
2649 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002650
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002651 if (i >= Py_SIZE(vl) || i >= Py_SIZE(wl)) {
2652 /* No more items to compare -- compare sizes */
stratakise8b19652017-11-02 11:32:54 +01002653 Py_RETURN_RICHCOMPARE(Py_SIZE(vl), Py_SIZE(wl), op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002654 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002655
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002656 /* We have an item that differs -- shortcuts for EQ/NE */
2657 if (op == Py_EQ) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02002658 Py_RETURN_FALSE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002659 }
2660 if (op == Py_NE) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02002661 Py_RETURN_TRUE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002662 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002663
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002664 /* Compare the final item again using the proper operator */
2665 return PyObject_RichCompare(vl->ob_item[i], wl->ob_item[i], op);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002666}
2667
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002668/*[clinic input]
2669list.__init__
2670
2671 iterable: object(c_default="NULL") = ()
2672 /
2673
2674Built-in mutable sequence.
2675
2676If no argument is given, the constructor creates a new empty list.
2677The argument must be an iterable if specified.
2678[clinic start generated code]*/
2679
Tim Peters6d6c1a32001-08-02 04:15:00 +00002680static int
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002681list___init___impl(PyListObject *self, PyObject *iterable)
2682/*[clinic end generated code: output=0f3c21379d01de48 input=b3f3fe7206af8f6b]*/
Tim Peters6d6c1a32001-08-02 04:15:00 +00002683{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002684 /* Verify list invariants established by PyType_GenericAlloc() */
2685 assert(0 <= Py_SIZE(self));
2686 assert(Py_SIZE(self) <= self->allocated || self->allocated == -1);
2687 assert(self->ob_item != NULL ||
2688 self->allocated == 0 || self->allocated == -1);
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002689
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002690 /* Empty previous contents */
2691 if (self->ob_item != NULL) {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002692 (void)_list_clear(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002693 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002694 if (iterable != NULL) {
Pablo Galindo372d7052018-10-28 20:16:26 +00002695 if (_PyObject_HasLen(iterable)) {
2696 Py_ssize_t iter_len = PyObject_Size(iterable);
2697 if (iter_len == -1) {
2698 if (!PyErr_ExceptionMatches(PyExc_TypeError)) {
2699 return -1;
2700 }
2701 PyErr_Clear();
2702 }
2703 if (iter_len > 0 && self->ob_item == NULL
2704 && list_preallocate_exact(self, iter_len)) {
2705 return -1;
2706 }
2707 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002708 PyObject *rv = list_extend(self, iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002709 if (rv == NULL)
2710 return -1;
2711 Py_DECREF(rv);
2712 }
2713 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002714}
2715
Petr Viktorince105542020-03-30 14:16:16 +02002716static PyObject *
2717list_vectorcall(PyObject *type, PyObject * const*args,
2718 size_t nargsf, PyObject *kwnames)
2719{
2720 if (!_PyArg_NoKwnames("list", kwnames)) {
2721 return NULL;
2722 }
2723 Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
2724 if (!_PyArg_CheckPositional("list", nargs, 0, 1)) {
2725 return NULL;
2726 }
2727
2728 assert(PyType_Check(type));
2729 PyObject *list = PyType_GenericAlloc((PyTypeObject *)type, 0);
2730 if (list == NULL) {
2731 return NULL;
2732 }
2733 if (nargs) {
2734 if (list___init___impl((PyListObject *)list, args[0])) {
2735 Py_DECREF(list);
2736 return NULL;
2737 }
2738 }
2739 return list;
2740}
2741
2742
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002743/*[clinic input]
2744list.__sizeof__
2745
2746Return the size of the list in memory, in bytes.
2747[clinic start generated code]*/
2748
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002749static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002750list___sizeof___impl(PyListObject *self)
2751/*[clinic end generated code: output=3417541f95f9a53e input=b8030a5d5ce8a187]*/
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002752{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002753 Py_ssize_t res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002754
Serhiy Storchaka5c4064e2015-12-19 20:05:25 +02002755 res = _PyObject_SIZE(Py_TYPE(self)) + self->allocated * sizeof(void*);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002756 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002757}
2758
Raymond Hettinger1021c442003-11-07 15:38:09 +00002759static PyObject *list_iter(PyObject *seq);
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002760static PyObject *list_subscript(PyListObject*, PyObject*);
2761
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002762static PyMethodDef list_methods[] = {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002763 {"__getitem__", (PyCFunction)list_subscript, METH_O|METH_COEXIST, "x.__getitem__(y) <==> x[y]"},
2764 LIST___REVERSED___METHODDEF
2765 LIST___SIZEOF___METHODDEF
2766 LIST_CLEAR_METHODDEF
2767 LIST_COPY_METHODDEF
2768 LIST_APPEND_METHODDEF
2769 LIST_INSERT_METHODDEF
2770 LIST_EXTEND_METHODDEF
2771 LIST_POP_METHODDEF
2772 LIST_REMOVE_METHODDEF
2773 LIST_INDEX_METHODDEF
2774 LIST_COUNT_METHODDEF
2775 LIST_REVERSE_METHODDEF
2776 LIST_SORT_METHODDEF
Guido van Rossum48b069a2020-04-07 09:50:06 -07002777 {"__class_getitem__", (PyCFunction)Py_GenericAlias, METH_O|METH_CLASS, PyDoc_STR("See PEP 585")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002778 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002779};
2780
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002781static PySequenceMethods list_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002782 (lenfunc)list_length, /* sq_length */
2783 (binaryfunc)list_concat, /* sq_concat */
2784 (ssizeargfunc)list_repeat, /* sq_repeat */
2785 (ssizeargfunc)list_item, /* sq_item */
2786 0, /* sq_slice */
2787 (ssizeobjargproc)list_ass_item, /* sq_ass_item */
2788 0, /* sq_ass_slice */
2789 (objobjproc)list_contains, /* sq_contains */
2790 (binaryfunc)list_inplace_concat, /* sq_inplace_concat */
2791 (ssizeargfunc)list_inplace_repeat, /* sq_inplace_repeat */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002792};
2793
Jeremy Hyltona4b4c3b2002-07-13 03:51:17 +00002794static PyObject *
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002795list_subscript(PyListObject* self, PyObject* item)
2796{
Victor Stinnera15e2602020-04-08 02:01:56 +02002797 if (_PyIndex_Check(item)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002798 Py_ssize_t i;
2799 i = PyNumber_AsSsize_t(item, PyExc_IndexError);
2800 if (i == -1 && PyErr_Occurred())
2801 return NULL;
2802 if (i < 0)
2803 i += PyList_GET_SIZE(self);
2804 return list_item(self, i);
2805 }
2806 else if (PySlice_Check(item)) {
HongWeipeng3c87a662019-09-08 18:15:56 +08002807 Py_ssize_t start, stop, step, slicelength, i;
2808 size_t cur;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002809 PyObject* result;
2810 PyObject* it;
2811 PyObject **src, **dest;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002812
Serhiy Storchakab879fe82017-04-08 09:53:51 +03002813 if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002814 return NULL;
2815 }
Serhiy Storchakab879fe82017-04-08 09:53:51 +03002816 slicelength = PySlice_AdjustIndices(Py_SIZE(self), &start, &stop,
2817 step);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002819 if (slicelength <= 0) {
2820 return PyList_New(0);
2821 }
2822 else if (step == 1) {
2823 return list_slice(self, start, stop);
2824 }
2825 else {
Sergey Fedoseev2fc46972018-08-11 18:12:07 +05002826 result = list_new_prealloc(slicelength);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002827 if (!result) return NULL;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002829 src = self->ob_item;
2830 dest = ((PyListObject *)result)->ob_item;
2831 for (cur = start, i = 0; i < slicelength;
Mark Dickinsonc7d93b72011-09-25 15:34:32 +01002832 cur += (size_t)step, i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002833 it = src[cur];
2834 Py_INCREF(it);
2835 dest[i] = it;
2836 }
Victor Stinner60ac6ed2020-02-07 23:18:08 +01002837 Py_SET_SIZE(result, slicelength);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002838 return result;
2839 }
2840 }
2841 else {
2842 PyErr_Format(PyExc_TypeError,
Terry Jan Reedyffff1442014-08-02 01:30:37 -04002843 "list indices must be integers or slices, not %.200s",
Victor Stinner58ac7002020-02-07 03:04:21 +01002844 Py_TYPE(item)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002845 return NULL;
2846 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002847}
2848
Tim Peters3b01a122002-07-19 02:35:45 +00002849static int
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002850list_ass_subscript(PyListObject* self, PyObject* item, PyObject* value)
2851{
Victor Stinnera15e2602020-04-08 02:01:56 +02002852 if (_PyIndex_Check(item)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002853 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
2854 if (i == -1 && PyErr_Occurred())
2855 return -1;
2856 if (i < 0)
2857 i += PyList_GET_SIZE(self);
2858 return list_ass_item(self, i, value);
2859 }
2860 else if (PySlice_Check(item)) {
2861 Py_ssize_t start, stop, step, slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002862
Serhiy Storchakab879fe82017-04-08 09:53:51 +03002863 if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002864 return -1;
2865 }
Serhiy Storchakab879fe82017-04-08 09:53:51 +03002866 slicelength = PySlice_AdjustIndices(Py_SIZE(self), &start, &stop,
2867 step);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002868
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002869 if (step == 1)
2870 return list_ass_slice(self, start, stop, value);
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002871
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002872 /* Make sure s[5:2] = [..] inserts at the right place:
2873 before 5, not before 2. */
2874 if ((step < 0 && start < stop) ||
2875 (step > 0 && start > stop))
2876 stop = start;
Thomas Woutersed03b412007-08-28 21:37:11 +00002877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002878 if (value == NULL) {
2879 /* delete slice */
2880 PyObject **garbage;
2881 size_t cur;
2882 Py_ssize_t i;
Victor Stinner35f28032013-11-21 12:16:35 +01002883 int res;
Tim Peters3b01a122002-07-19 02:35:45 +00002884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002885 if (slicelength <= 0)
2886 return 0;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002888 if (step < 0) {
2889 stop = start + 1;
2890 start = stop + step*(slicelength - 1) - 1;
2891 step = -step;
2892 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002894 garbage = (PyObject**)
2895 PyMem_MALLOC(slicelength*sizeof(PyObject*));
2896 if (!garbage) {
2897 PyErr_NoMemory();
2898 return -1;
2899 }
Tim Peters3b01a122002-07-19 02:35:45 +00002900
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002901 /* drawing pictures might help understand these for
2902 loops. Basically, we memmove the parts of the
2903 list that are *not* part of the slice: step-1
2904 items for each item that is part of the slice,
2905 and then tail end of the list that was not
2906 covered by the slice */
2907 for (cur = start, i = 0;
2908 cur < (size_t)stop;
2909 cur += step, i++) {
2910 Py_ssize_t lim = step - 1;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002911
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002912 garbage[i] = PyList_GET_ITEM(self, cur);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002914 if (cur + step >= (size_t)Py_SIZE(self)) {
2915 lim = Py_SIZE(self) - cur - 1;
2916 }
Michael W. Hudson56796f62002-07-29 14:35:04 +00002917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002918 memmove(self->ob_item + cur - i,
2919 self->ob_item + cur + 1,
2920 lim * sizeof(PyObject *));
2921 }
Mark Dickinsonc7d93b72011-09-25 15:34:32 +01002922 cur = start + (size_t)slicelength * step;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002923 if (cur < (size_t)Py_SIZE(self)) {
2924 memmove(self->ob_item + cur - slicelength,
2925 self->ob_item + cur,
2926 (Py_SIZE(self) - cur) *
2927 sizeof(PyObject *));
2928 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002929
Victor Stinner60ac6ed2020-02-07 23:18:08 +01002930 Py_SET_SIZE(self, Py_SIZE(self) - slicelength);
Victor Stinner35f28032013-11-21 12:16:35 +01002931 res = list_resize(self, Py_SIZE(self));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002933 for (i = 0; i < slicelength; i++) {
2934 Py_DECREF(garbage[i]);
2935 }
2936 PyMem_FREE(garbage);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002937
Victor Stinner35f28032013-11-21 12:16:35 +01002938 return res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002939 }
2940 else {
2941 /* assign slice */
2942 PyObject *ins, *seq;
2943 PyObject **garbage, **seqitems, **selfitems;
HongWeipeng3c87a662019-09-08 18:15:56 +08002944 Py_ssize_t i;
2945 size_t cur;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002947 /* protect against a[::-1] = a */
2948 if (self == (PyListObject*)value) {
2949 seq = list_slice((PyListObject*)value, 0,
2950 PyList_GET_SIZE(value));
2951 }
2952 else {
2953 seq = PySequence_Fast(value,
2954 "must assign iterable "
2955 "to extended slice");
2956 }
2957 if (!seq)
2958 return -1;
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002960 if (PySequence_Fast_GET_SIZE(seq) != slicelength) {
2961 PyErr_Format(PyExc_ValueError,
2962 "attempt to assign sequence of "
2963 "size %zd to extended slice of "
2964 "size %zd",
2965 PySequence_Fast_GET_SIZE(seq),
2966 slicelength);
2967 Py_DECREF(seq);
2968 return -1;
2969 }
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002971 if (!slicelength) {
2972 Py_DECREF(seq);
2973 return 0;
2974 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002975
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002976 garbage = (PyObject**)
2977 PyMem_MALLOC(slicelength*sizeof(PyObject*));
2978 if (!garbage) {
2979 Py_DECREF(seq);
2980 PyErr_NoMemory();
2981 return -1;
2982 }
Tim Peters3b01a122002-07-19 02:35:45 +00002983
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002984 selfitems = self->ob_item;
2985 seqitems = PySequence_Fast_ITEMS(seq);
2986 for (cur = start, i = 0; i < slicelength;
Mark Dickinsonc7d93b72011-09-25 15:34:32 +01002987 cur += (size_t)step, i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002988 garbage[i] = selfitems[cur];
2989 ins = seqitems[i];
2990 Py_INCREF(ins);
2991 selfitems[cur] = ins;
2992 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002994 for (i = 0; i < slicelength; i++) {
2995 Py_DECREF(garbage[i]);
2996 }
Tim Peters3b01a122002-07-19 02:35:45 +00002997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002998 PyMem_FREE(garbage);
2999 Py_DECREF(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00003000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003001 return 0;
3002 }
3003 }
3004 else {
3005 PyErr_Format(PyExc_TypeError,
Terry Jan Reedyffff1442014-08-02 01:30:37 -04003006 "list indices must be integers or slices, not %.200s",
Victor Stinner58ac7002020-02-07 03:04:21 +01003007 Py_TYPE(item)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003008 return -1;
3009 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00003010}
3011
3012static PyMappingMethods list_as_mapping = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003013 (lenfunc)list_length,
3014 (binaryfunc)list_subscript,
3015 (objobjargproc)list_ass_subscript
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00003016};
3017
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003018PyTypeObject PyList_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003019 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3020 "list",
3021 sizeof(PyListObject),
3022 0,
3023 (destructor)list_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003024 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003025 0, /* tp_getattr */
3026 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003027 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003028 (reprfunc)list_repr, /* tp_repr */
3029 0, /* tp_as_number */
3030 &list_as_sequence, /* tp_as_sequence */
3031 &list_as_mapping, /* tp_as_mapping */
Georg Brandl00da4e02010-10-18 07:32:48 +00003032 PyObject_HashNotImplemented, /* tp_hash */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003033 0, /* tp_call */
3034 0, /* tp_str */
3035 PyObject_GenericGetAttr, /* tp_getattro */
3036 0, /* tp_setattro */
3037 0, /* tp_as_buffer */
3038 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02003039 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LIST_SUBCLASS, /* tp_flags */
3040 list___init____doc__, /* tp_doc */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003041 (traverseproc)list_traverse, /* tp_traverse */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02003042 (inquiry)_list_clear, /* tp_clear */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003043 list_richcompare, /* tp_richcompare */
3044 0, /* tp_weaklistoffset */
3045 list_iter, /* tp_iter */
3046 0, /* tp_iternext */
3047 list_methods, /* tp_methods */
3048 0, /* tp_members */
3049 0, /* tp_getset */
3050 0, /* tp_base */
3051 0, /* tp_dict */
3052 0, /* tp_descr_get */
3053 0, /* tp_descr_set */
3054 0, /* tp_dictoffset */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02003055 (initproc)list___init__, /* tp_init */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003056 PyType_GenericAlloc, /* tp_alloc */
3057 PyType_GenericNew, /* tp_new */
3058 PyObject_GC_Del, /* tp_free */
Petr Viktorince105542020-03-30 14:16:16 +02003059 .tp_vectorcall = list_vectorcall,
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003060};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00003061
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00003062/*********************** List Iterator **************************/
3063
3064typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003065 PyObject_HEAD
Victor Stinner7660b882013-06-24 23:59:24 +02003066 Py_ssize_t it_index;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003067 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00003068} listiterobject;
3069
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003070static void listiter_dealloc(listiterobject *);
3071static int listiter_traverse(listiterobject *, visitproc, void *);
3072static PyObject *listiter_next(listiterobject *);
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303073static PyObject *listiter_len(listiterobject *, PyObject *);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003074static PyObject *listiter_reduce_general(void *_it, int forward);
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303075static PyObject *listiter_reduce(listiterobject *, PyObject *);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003076static PyObject *listiter_setstate(listiterobject *, PyObject *state);
Raymond Hettinger435bf582004-03-18 22:43:10 +00003077
Armin Rigof5b3e362006-02-11 21:32:43 +00003078PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003079PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
3080PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00003081
3082static PyMethodDef listiter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003083 {"__length_hint__", (PyCFunction)listiter_len, METH_NOARGS, length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003084 {"__reduce__", (PyCFunction)listiter_reduce, METH_NOARGS, reduce_doc},
3085 {"__setstate__", (PyCFunction)listiter_setstate, METH_O, setstate_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003086 {NULL, NULL} /* sentinel */
Raymond Hettinger435bf582004-03-18 22:43:10 +00003087};
3088
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00003089PyTypeObject PyListIter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003090 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3091 "list_iterator", /* tp_name */
3092 sizeof(listiterobject), /* tp_basicsize */
3093 0, /* tp_itemsize */
3094 /* methods */
3095 (destructor)listiter_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003096 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003097 0, /* tp_getattr */
3098 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003099 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003100 0, /* tp_repr */
3101 0, /* tp_as_number */
3102 0, /* tp_as_sequence */
3103 0, /* tp_as_mapping */
3104 0, /* tp_hash */
3105 0, /* tp_call */
3106 0, /* tp_str */
3107 PyObject_GenericGetAttr, /* tp_getattro */
3108 0, /* tp_setattro */
3109 0, /* tp_as_buffer */
3110 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3111 0, /* tp_doc */
3112 (traverseproc)listiter_traverse, /* tp_traverse */
3113 0, /* tp_clear */
3114 0, /* tp_richcompare */
3115 0, /* tp_weaklistoffset */
3116 PyObject_SelfIter, /* tp_iter */
3117 (iternextfunc)listiter_next, /* tp_iternext */
3118 listiter_methods, /* tp_methods */
3119 0, /* tp_members */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00003120};
Raymond Hettinger1021c442003-11-07 15:38:09 +00003121
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003122
3123static PyObject *
3124list_iter(PyObject *seq)
3125{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003126 listiterobject *it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003128 if (!PyList_Check(seq)) {
3129 PyErr_BadInternalCall();
3130 return NULL;
3131 }
3132 it = PyObject_GC_New(listiterobject, &PyListIter_Type);
3133 if (it == NULL)
3134 return NULL;
3135 it->it_index = 0;
3136 Py_INCREF(seq);
3137 it->it_seq = (PyListObject *)seq;
3138 _PyObject_GC_TRACK(it);
3139 return (PyObject *)it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003140}
3141
3142static void
3143listiter_dealloc(listiterobject *it)
3144{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003145 _PyObject_GC_UNTRACK(it);
3146 Py_XDECREF(it->it_seq);
3147 PyObject_GC_Del(it);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003148}
3149
3150static int
3151listiter_traverse(listiterobject *it, visitproc visit, void *arg)
3152{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003153 Py_VISIT(it->it_seq);
3154 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003155}
3156
3157static PyObject *
3158listiter_next(listiterobject *it)
3159{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003160 PyListObject *seq;
3161 PyObject *item;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003163 assert(it != NULL);
3164 seq = it->it_seq;
3165 if (seq == NULL)
3166 return NULL;
3167 assert(PyList_Check(seq));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003169 if (it->it_index < PyList_GET_SIZE(seq)) {
3170 item = PyList_GET_ITEM(seq, it->it_index);
3171 ++it->it_index;
3172 Py_INCREF(item);
3173 return item;
3174 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003175
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003176 it->it_seq = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003177 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003178 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003179}
3180
3181static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303182listiter_len(listiterobject *it, PyObject *Py_UNUSED(ignored))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003183{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003184 Py_ssize_t len;
3185 if (it->it_seq) {
3186 len = PyList_GET_SIZE(it->it_seq) - it->it_index;
3187 if (len >= 0)
3188 return PyLong_FromSsize_t(len);
3189 }
3190 return PyLong_FromLong(0);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003191}
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003192
3193static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303194listiter_reduce(listiterobject *it, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003195{
3196 return listiter_reduce_general(it, 1);
3197}
3198
3199static PyObject *
3200listiter_setstate(listiterobject *it, PyObject *state)
3201{
Victor Stinner7660b882013-06-24 23:59:24 +02003202 Py_ssize_t index = PyLong_AsSsize_t(state);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003203 if (index == -1 && PyErr_Occurred())
3204 return NULL;
3205 if (it->it_seq != NULL) {
3206 if (index < 0)
3207 index = 0;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +00003208 else if (index > PyList_GET_SIZE(it->it_seq))
3209 index = PyList_GET_SIZE(it->it_seq); /* iterator exhausted */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003210 it->it_index = index;
3211 }
3212 Py_RETURN_NONE;
3213}
3214
Raymond Hettinger1021c442003-11-07 15:38:09 +00003215/*********************** List Reverse Iterator **************************/
3216
3217typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003218 PyObject_HEAD
3219 Py_ssize_t it_index;
3220 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger1021c442003-11-07 15:38:09 +00003221} listreviterobject;
3222
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003223static void listreviter_dealloc(listreviterobject *);
3224static int listreviter_traverse(listreviterobject *, visitproc, void *);
3225static PyObject *listreviter_next(listreviterobject *);
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303226static PyObject *listreviter_len(listreviterobject *, PyObject *);
3227static PyObject *listreviter_reduce(listreviterobject *, PyObject *);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003228static PyObject *listreviter_setstate(listreviterobject *, PyObject *);
Raymond Hettingeref9bf402004-03-10 10:10:42 +00003229
Raymond Hettingerf5b64112008-12-02 21:33:45 +00003230static PyMethodDef listreviter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003231 {"__length_hint__", (PyCFunction)listreviter_len, METH_NOARGS, length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003232 {"__reduce__", (PyCFunction)listreviter_reduce, METH_NOARGS, reduce_doc},
3233 {"__setstate__", (PyCFunction)listreviter_setstate, METH_O, setstate_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003234 {NULL, NULL} /* sentinel */
Raymond Hettingeref9bf402004-03-10 10:10:42 +00003235};
3236
Raymond Hettinger1021c442003-11-07 15:38:09 +00003237PyTypeObject PyListRevIter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003238 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3239 "list_reverseiterator", /* tp_name */
3240 sizeof(listreviterobject), /* tp_basicsize */
3241 0, /* tp_itemsize */
3242 /* methods */
3243 (destructor)listreviter_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003244 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003245 0, /* tp_getattr */
3246 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003247 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003248 0, /* tp_repr */
3249 0, /* tp_as_number */
3250 0, /* tp_as_sequence */
3251 0, /* tp_as_mapping */
3252 0, /* tp_hash */
3253 0, /* tp_call */
3254 0, /* tp_str */
3255 PyObject_GenericGetAttr, /* tp_getattro */
3256 0, /* tp_setattro */
3257 0, /* tp_as_buffer */
3258 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3259 0, /* tp_doc */
3260 (traverseproc)listreviter_traverse, /* tp_traverse */
3261 0, /* tp_clear */
3262 0, /* tp_richcompare */
3263 0, /* tp_weaklistoffset */
3264 PyObject_SelfIter, /* tp_iter */
3265 (iternextfunc)listreviter_next, /* tp_iternext */
3266 listreviter_methods, /* tp_methods */
3267 0,
Raymond Hettinger1021c442003-11-07 15:38:09 +00003268};
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003269
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02003270/*[clinic input]
3271list.__reversed__
3272
3273Return a reverse iterator over the list.
3274[clinic start generated code]*/
3275
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003276static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02003277list___reversed___impl(PyListObject *self)
3278/*[clinic end generated code: output=b166f073208c888c input=eadb6e17f8a6a280]*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003279{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003280 listreviterobject *it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003282 it = PyObject_GC_New(listreviterobject, &PyListRevIter_Type);
3283 if (it == NULL)
3284 return NULL;
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02003285 assert(PyList_Check(self));
3286 it->it_index = PyList_GET_SIZE(self) - 1;
3287 Py_INCREF(self);
3288 it->it_seq = self;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003289 PyObject_GC_Track(it);
3290 return (PyObject *)it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003291}
3292
3293static void
3294listreviter_dealloc(listreviterobject *it)
3295{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003296 PyObject_GC_UnTrack(it);
3297 Py_XDECREF(it->it_seq);
3298 PyObject_GC_Del(it);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003299}
3300
3301static int
3302listreviter_traverse(listreviterobject *it, visitproc visit, void *arg)
3303{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003304 Py_VISIT(it->it_seq);
3305 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003306}
3307
3308static PyObject *
3309listreviter_next(listreviterobject *it)
3310{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003311 PyObject *item;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003312 Py_ssize_t index;
3313 PyListObject *seq;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003314
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003315 assert(it != NULL);
3316 seq = it->it_seq;
3317 if (seq == NULL) {
3318 return NULL;
3319 }
3320 assert(PyList_Check(seq));
3321
3322 index = it->it_index;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003323 if (index>=0 && index < PyList_GET_SIZE(seq)) {
3324 item = PyList_GET_ITEM(seq, index);
3325 it->it_index--;
3326 Py_INCREF(item);
3327 return item;
3328 }
3329 it->it_index = -1;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003330 it->it_seq = NULL;
3331 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003332 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003333}
3334
Raymond Hettingerf5b64112008-12-02 21:33:45 +00003335static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303336listreviter_len(listreviterobject *it, PyObject *Py_UNUSED(ignored))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003337{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003338 Py_ssize_t len = it->it_index + 1;
3339 if (it->it_seq == NULL || PyList_GET_SIZE(it->it_seq) < len)
3340 len = 0;
3341 return PyLong_FromSsize_t(len);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003342}
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003343
3344static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303345listreviter_reduce(listreviterobject *it, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003346{
3347 return listiter_reduce_general(it, 0);
3348}
3349
3350static PyObject *
3351listreviter_setstate(listreviterobject *it, PyObject *state)
3352{
3353 Py_ssize_t index = PyLong_AsSsize_t(state);
3354 if (index == -1 && PyErr_Occurred())
3355 return NULL;
3356 if (it->it_seq != NULL) {
3357 if (index < -1)
3358 index = -1;
3359 else if (index > PyList_GET_SIZE(it->it_seq) - 1)
3360 index = PyList_GET_SIZE(it->it_seq) - 1;
3361 it->it_index = index;
3362 }
3363 Py_RETURN_NONE;
3364}
3365
3366/* common pickling support */
3367
3368static PyObject *
3369listiter_reduce_general(void *_it, int forward)
3370{
Serhiy Storchakabb86bf42018-12-11 08:28:18 +02003371 _Py_IDENTIFIER(iter);
3372 _Py_IDENTIFIER(reversed);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003373 PyObject *list;
3374
3375 /* the objects are not the same, index is of different types! */
3376 if (forward) {
3377 listiterobject *it = (listiterobject *)_it;
3378 if (it->it_seq)
Serhiy Storchakabb86bf42018-12-11 08:28:18 +02003379 return Py_BuildValue("N(O)n", _PyEval_GetBuiltinId(&PyId_iter),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003380 it->it_seq, it->it_index);
3381 } else {
3382 listreviterobject *it = (listreviterobject *)_it;
3383 if (it->it_seq)
Serhiy Storchakabb86bf42018-12-11 08:28:18 +02003384 return Py_BuildValue("N(O)n", _PyEval_GetBuiltinId(&PyId_reversed),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003385 it->it_seq, it->it_index);
3386 }
3387 /* empty iterator, create an empty list */
3388 list = PyList_New(0);
3389 if (list == NULL)
3390 return NULL;
Serhiy Storchakabb86bf42018-12-11 08:28:18 +02003391 return Py_BuildValue("N(N)", _PyEval_GetBuiltinId(&PyId_iter), list);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003392}