blob: 7d2f006617ba50e165847544eb1b464e20c8c2ce [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
101#define PyList_MAXFREELIST 80
102#endif
103static PyListObject *free_list[PyList_MAXFREELIST];
104static int numfree = 0;
Raymond Hettinger0468e412004-05-05 05:37:53 +0000105
Antoine Pitrou9a812cb2011-11-15 00:00:12 +0100106int
107PyList_ClearFreeList(void)
Raymond Hettingerfb09f0e2004-10-07 03:58:07 +0000108{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000109 PyListObject *op;
Antoine Pitrou9a812cb2011-11-15 00:00:12 +0100110 int ret = numfree;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000111 while (numfree) {
112 op = free_list[--numfree];
113 assert(PyList_CheckExact(op));
114 PyObject_GC_Del(op);
115 }
Antoine Pitrou9a812cb2011-11-15 00:00:12 +0100116 return ret;
117}
118
119void
Victor Stinnerbed48172019-08-27 00:12:32 +0200120_PyList_Fini(void)
Antoine Pitrou9a812cb2011-11-15 00:00:12 +0100121{
122 PyList_ClearFreeList();
Raymond Hettingerfb09f0e2004-10-07 03:58:07 +0000123}
124
David Malcolm49526f42012-06-22 14:55:41 -0400125/* Print summary info about the state of the optimized allocator */
126void
127_PyList_DebugMallocStats(FILE *out)
128{
129 _PyDebugAllocatorStats(out,
130 "free PyListObject",
131 numfree, sizeof(PyListObject));
132}
133
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000134PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000135PyList_New(Py_ssize_t size)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000136{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000137 PyListObject *op;
Tim Peters3986d4e2004-07-29 02:28:42 +0000138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000139 if (size < 0) {
140 PyErr_BadInternalCall();
141 return NULL;
142 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000143 if (numfree) {
144 numfree--;
145 op = free_list[numfree];
146 _Py_NewReference((PyObject *)op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000147 } else {
148 op = PyObject_GC_New(PyListObject, &PyList_Type);
149 if (op == NULL)
150 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000151 }
152 if (size <= 0)
153 op->ob_item = NULL;
154 else {
Mark Dickinson5d132382016-08-21 08:55:15 +0100155 op->ob_item = (PyObject **) PyMem_Calloc(size, sizeof(PyObject *));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000156 if (op->ob_item == NULL) {
157 Py_DECREF(op);
158 return PyErr_NoMemory();
159 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000160 }
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100161 Py_SET_SIZE(op, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000162 op->allocated = size;
163 _PyObject_GC_TRACK(op);
164 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000165}
166
Sergey Fedoseev2fc46972018-08-11 18:12:07 +0500167static PyObject *
168list_new_prealloc(Py_ssize_t size)
169{
170 PyListObject *op = (PyListObject *) PyList_New(0);
171 if (size == 0 || op == NULL) {
172 return (PyObject *) op;
173 }
174 assert(op->ob_item == NULL);
175 op->ob_item = PyMem_New(PyObject *, size);
176 if (op->ob_item == NULL) {
177 Py_DECREF(op);
178 return PyErr_NoMemory();
179 }
180 op->allocated = size;
181 return (PyObject *) op;
182}
183
Martin v. Löwis18e16552006-02-15 17:27:45 +0000184Py_ssize_t
Fred Drakea2f55112000-07-09 15:16:51 +0000185PyList_Size(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000186{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000187 if (!PyList_Check(op)) {
188 PyErr_BadInternalCall();
189 return -1;
190 }
191 else
192 return Py_SIZE(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000193}
194
Raymond Hettingerf1aa8ae2018-10-10 20:37:28 -0700195static inline int
196valid_index(Py_ssize_t i, Py_ssize_t limit)
197{
198 /* The cast to size_t lets us use just a single comparison
199 to check whether i is in the range: 0 <= i < limit.
200
201 See: Section 14.2 "Bounds Checking" in the Agner Fog
202 optimization manual found at:
203 https://www.agner.org/optimize/optimizing_cpp.pdf
204 */
205 return (size_t) i < (size_t) limit;
206}
207
Raymond Hettingerfdfe6182004-05-05 06:28:16 +0000208static PyObject *indexerr = NULL;
Guido van Rossum929f1b81996-08-09 20:51:27 +0000209
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000210PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000211PyList_GetItem(PyObject *op, Py_ssize_t i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000212{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000213 if (!PyList_Check(op)) {
214 PyErr_BadInternalCall();
215 return NULL;
216 }
Raymond Hettingerf1aa8ae2018-10-10 20:37:28 -0700217 if (!valid_index(i, Py_SIZE(op))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000218 if (indexerr == NULL) {
219 indexerr = PyUnicode_FromString(
220 "list index out of range");
221 if (indexerr == NULL)
222 return NULL;
223 }
224 PyErr_SetObject(PyExc_IndexError, indexerr);
225 return NULL;
226 }
227 return ((PyListObject *)op) -> ob_item[i];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000228}
229
230int
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200231PyList_SetItem(PyObject *op, Py_ssize_t i,
232 PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000233{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200234 PyObject **p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000235 if (!PyList_Check(op)) {
236 Py_XDECREF(newitem);
237 PyErr_BadInternalCall();
238 return -1;
239 }
Raymond Hettingerf1aa8ae2018-10-10 20:37:28 -0700240 if (!valid_index(i, Py_SIZE(op))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000241 Py_XDECREF(newitem);
242 PyErr_SetString(PyExc_IndexError,
243 "list assignment index out of range");
244 return -1;
245 }
246 p = ((PyListObject *)op) -> ob_item + i;
Serhiy Storchakaec397562016-04-06 09:50:03 +0300247 Py_XSETREF(*p, newitem);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000248 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000249}
250
251static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000252ins1(PyListObject *self, Py_ssize_t where, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000253{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000254 Py_ssize_t i, n = Py_SIZE(self);
255 PyObject **items;
256 if (v == NULL) {
257 PyErr_BadInternalCall();
258 return -1;
259 }
260 if (n == PY_SSIZE_T_MAX) {
261 PyErr_SetString(PyExc_OverflowError,
262 "cannot add more objects to list");
263 return -1;
264 }
Tim Petersb38e2b62004-07-29 02:29:26 +0000265
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);
300 if (n == PY_SSIZE_T_MAX) {
301 PyErr_SetString(PyExc_OverflowError,
302 "cannot add more objects to list");
303 return -1;
304 }
Raymond Hettinger40a03822004-04-12 13:05:09 +0000305
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800306 if (list_resize(self, n+1) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000307 return -1;
Raymond Hettinger40a03822004-04-12 13:05:09 +0000308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000309 Py_INCREF(v);
310 PyList_SET_ITEM(self, n, v);
311 return 0;
Raymond Hettinger40a03822004-04-12 13:05:09 +0000312}
313
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000314int
Fred Drakea2f55112000-07-09 15:16:51 +0000315PyList_Append(PyObject *op, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000316{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000317 if (PyList_Check(op) && (newitem != NULL))
318 return app1((PyListObject *)op, newitem);
319 PyErr_BadInternalCall();
320 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000321}
322
323/* Methods */
324
325static void
Fred Drakea2f55112000-07-09 15:16:51 +0000326list_dealloc(PyListObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000327{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000328 Py_ssize_t i;
329 PyObject_GC_UnTrack(op);
Jeroen Demeyer351c6742019-05-10 19:21:11 +0200330 Py_TRASHCAN_BEGIN(op, list_dealloc)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000331 if (op->ob_item != NULL) {
332 /* Do it backwards, for Christian Tismer.
333 There's a simple test case where somehow this reduces
334 thrashing when a *very* large list is created and
335 immediately deleted. */
336 i = Py_SIZE(op);
337 while (--i >= 0) {
338 Py_XDECREF(op->ob_item[i]);
339 }
340 PyMem_FREE(op->ob_item);
341 }
342 if (numfree < PyList_MAXFREELIST && PyList_CheckExact(op))
343 free_list[numfree++] = op;
344 else
345 Py_TYPE(op)->tp_free((PyObject *)op);
Jeroen Demeyer351c6742019-05-10 19:21:11 +0200346 Py_TRASHCAN_END
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000347}
348
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000349static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000350list_repr(PyListObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000351{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000352 Py_ssize_t i;
Victor Stinner5c733472013-11-18 21:11:57 +0100353 PyObject *s;
Victor Stinner5c733472013-11-18 21:11:57 +0100354 _PyUnicodeWriter writer;
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200355
356 if (Py_SIZE(v) == 0) {
357 return PyUnicode_FromString("[]");
358 }
359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000360 i = Py_ReprEnter((PyObject*)v);
361 if (i != 0) {
362 return i > 0 ? PyUnicode_FromString("[...]") : NULL;
363 }
Tim Petersa7259592001-06-16 05:11:17 +0000364
Victor Stinner5c733472013-11-18 21:11:57 +0100365 _PyUnicodeWriter_Init(&writer);
366 writer.overallocate = 1;
Victor Stinnerb8fb1972013-11-18 22:15:44 +0100367 /* "[" + "1" + ", 2" * (len - 1) + "]" */
368 writer.min_length = 1 + 1 + (2 + 1) * (Py_SIZE(v) - 1) + 1;
Tim Petersa7259592001-06-16 05:11:17 +0000369
Victor Stinner5c733472013-11-18 21:11:57 +0100370 if (_PyUnicodeWriter_WriteChar(&writer, '[') < 0)
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200371 goto error;
Tim Petersa7259592001-06-16 05:11:17 +0000372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000373 /* Do repr() on each element. Note that this may mutate the list,
374 so must refetch the list size on each iteration. */
375 for (i = 0; i < Py_SIZE(v); ++i) {
Victor Stinner5c733472013-11-18 21:11:57 +0100376 if (i > 0) {
Victor Stinner4a587072013-11-19 12:54:53 +0100377 if (_PyUnicodeWriter_WriteASCIIString(&writer, ", ", 2) < 0)
Victor Stinner5c733472013-11-18 21:11:57 +0100378 goto error;
379 }
380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000381 s = PyObject_Repr(v->ob_item[i]);
Victor Stinner5c733472013-11-18 21:11:57 +0100382 if (s == NULL)
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200383 goto error;
Victor Stinner5c733472013-11-18 21:11:57 +0100384
385 if (_PyUnicodeWriter_WriteStr(&writer, s) < 0) {
386 Py_DECREF(s);
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200387 goto error;
Victor Stinner5c733472013-11-18 21:11:57 +0100388 }
389 Py_DECREF(s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000390 }
Victor Stinner5c733472013-11-18 21:11:57 +0100391
Victor Stinner4d3f1092013-11-19 12:09:00 +0100392 writer.overallocate = 0;
Victor Stinner5c733472013-11-18 21:11:57 +0100393 if (_PyUnicodeWriter_WriteChar(&writer, ']') < 0)
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200394 goto error;
Tim Petersa7259592001-06-16 05:11:17 +0000395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000396 Py_ReprLeave((PyObject *)v);
Victor Stinner5c733472013-11-18 21:11:57 +0100397 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200398
399error:
Victor Stinner5c733472013-11-18 21:11:57 +0100400 _PyUnicodeWriter_Dealloc(&writer);
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200401 Py_ReprLeave((PyObject *)v);
402 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000403}
404
Martin v. Löwis18e16552006-02-15 17:27:45 +0000405static Py_ssize_t
Fred Drakea2f55112000-07-09 15:16:51 +0000406list_length(PyListObject *a)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000407{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000408 return Py_SIZE(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000409}
410
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000411static int
Fred Drakea2f55112000-07-09 15:16:51 +0000412list_contains(PyListObject *a, PyObject *el)
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000413{
Dong-hee Na4dbf2d82020-01-28 00:02:23 +0900414 PyObject *item;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000415 Py_ssize_t i;
416 int cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000417
Dong-hee Na4dbf2d82020-01-28 00:02:23 +0900418 for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(a); ++i) {
419 item = PyList_GET_ITEM(a, i);
420 Py_INCREF(item);
Dong-hee Na9e1ed512020-01-28 02:04:25 +0900421 cmp = PyObject_RichCompareBool(item, el, Py_EQ);
Dong-hee Na4dbf2d82020-01-28 00:02:23 +0900422 Py_DECREF(item);
423 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000424 return cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000425}
426
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000427static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000428list_item(PyListObject *a, Py_ssize_t i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000429{
Raymond Hettingerf1aa8ae2018-10-10 20:37:28 -0700430 if (!valid_index(i, Py_SIZE(a))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 if (indexerr == NULL) {
432 indexerr = PyUnicode_FromString(
433 "list index out of range");
434 if (indexerr == NULL)
435 return NULL;
436 }
437 PyErr_SetObject(PyExc_IndexError, indexerr);
438 return NULL;
439 }
440 Py_INCREF(a->ob_item[i]);
441 return a->ob_item[i];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000442}
443
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000444static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000445list_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000446{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000447 PyListObject *np;
448 PyObject **src, **dest;
449 Py_ssize_t i, len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000450 len = ihigh - ilow;
Sergey Fedoseev2fc46972018-08-11 18:12:07 +0500451 np = (PyListObject *) list_new_prealloc(len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000452 if (np == NULL)
453 return NULL;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000454
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000455 src = a->ob_item + ilow;
456 dest = np->ob_item;
457 for (i = 0; i < len; i++) {
458 PyObject *v = src[i];
459 Py_INCREF(v);
460 dest[i] = v;
461 }
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100462 Py_SET_SIZE(np, len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000463 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000464}
465
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000466PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000467PyList_GetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum234f9421993-06-17 12:35:49 +0000468{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469 if (!PyList_Check(a)) {
470 PyErr_BadInternalCall();
471 return NULL;
472 }
Sergey Fedoseevef1b88b2019-02-21 11:51:52 +0500473 if (ilow < 0) {
474 ilow = 0;
475 }
476 else if (ilow > Py_SIZE(a)) {
477 ilow = Py_SIZE(a);
478 }
479 if (ihigh < ilow) {
480 ihigh = ilow;
481 }
482 else if (ihigh > Py_SIZE(a)) {
483 ihigh = Py_SIZE(a);
484 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 return list_slice((PyListObject *)a, ilow, ihigh);
Guido van Rossum234f9421993-06-17 12:35:49 +0000486}
487
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000488static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000489list_concat(PyListObject *a, PyObject *bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000490{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000491 Py_ssize_t size;
492 Py_ssize_t i;
493 PyObject **src, **dest;
494 PyListObject *np;
495 if (!PyList_Check(bb)) {
496 PyErr_Format(PyExc_TypeError,
497 "can only concatenate list (not \"%.200s\") to list",
Victor Stinner58ac7002020-02-07 03:04:21 +0100498 Py_TYPE(bb)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000499 return NULL;
500 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000501#define b ((PyListObject *)bb)
Martin Panterb93d8632016-07-25 02:39:20 +0000502 if (Py_SIZE(a) > PY_SSIZE_T_MAX - Py_SIZE(b))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000503 return PyErr_NoMemory();
Martin Panterb93d8632016-07-25 02:39:20 +0000504 size = Py_SIZE(a) + Py_SIZE(b);
Sergey Fedoseev2fc46972018-08-11 18:12:07 +0500505 np = (PyListObject *) list_new_prealloc(size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 if (np == NULL) {
507 return NULL;
508 }
509 src = a->ob_item;
510 dest = np->ob_item;
511 for (i = 0; i < Py_SIZE(a); i++) {
512 PyObject *v = src[i];
513 Py_INCREF(v);
514 dest[i] = v;
515 }
516 src = b->ob_item;
517 dest = np->ob_item + Py_SIZE(a);
518 for (i = 0; i < Py_SIZE(b); i++) {
519 PyObject *v = src[i];
520 Py_INCREF(v);
521 dest[i] = v;
522 }
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100523 Py_SET_SIZE(np, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000524 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000525#undef b
526}
527
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000528static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000529list_repeat(PyListObject *a, Py_ssize_t n)
Guido van Rossumed98d481991-03-06 13:07:53 +0000530{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000531 Py_ssize_t i, j;
532 Py_ssize_t size;
533 PyListObject *np;
534 PyObject **p, **items;
535 PyObject *elem;
536 if (n < 0)
537 n = 0;
Mark Dickinsonc0420fd2011-09-19 19:18:37 +0100538 if (n > 0 && Py_SIZE(a) > PY_SSIZE_T_MAX / n)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000539 return PyErr_NoMemory();
Mark Dickinsonc0420fd2011-09-19 19:18:37 +0100540 size = Py_SIZE(a) * n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000541 if (size == 0)
542 return PyList_New(0);
Sergey Fedoseev2fc46972018-08-11 18:12:07 +0500543 np = (PyListObject *) list_new_prealloc(size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000544 if (np == NULL)
545 return NULL;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000547 if (Py_SIZE(a) == 1) {
Sergey Fedoseev2fc46972018-08-11 18:12:07 +0500548 items = np->ob_item;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000549 elem = a->ob_item[0];
550 for (i = 0; i < n; i++) {
551 items[i] = elem;
552 Py_INCREF(elem);
553 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000554 }
Sergey Fedoseev2fc46972018-08-11 18:12:07 +0500555 else {
556 p = np->ob_item;
557 items = a->ob_item;
558 for (i = 0; i < n; i++) {
559 for (j = 0; j < Py_SIZE(a); j++) {
560 *p = items[j];
561 Py_INCREF(*p);
562 p++;
563 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000564 }
565 }
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100566 Py_SET_SIZE(np, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567 return (PyObject *) np;
Guido van Rossumed98d481991-03-06 13:07:53 +0000568}
569
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000570static int
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200571_list_clear(PyListObject *a)
Armin Rigo93677f02004-07-29 12:40:23 +0000572{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000573 Py_ssize_t i;
574 PyObject **item = a->ob_item;
575 if (item != NULL) {
576 /* Because XDECREF can recursively invoke operations on
577 this list, we make it empty first. */
578 i = Py_SIZE(a);
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100579 Py_SET_SIZE(a, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000580 a->ob_item = NULL;
581 a->allocated = 0;
582 while (--i >= 0) {
583 Py_XDECREF(item[i]);
584 }
585 PyMem_FREE(item);
586 }
587 /* Never fails; the return value can be ignored.
588 Note that there is no guarantee that the list is actually empty
589 at this point, because XDECREF may have populated it again! */
590 return 0;
Armin Rigo93677f02004-07-29 12:40:23 +0000591}
592
Tim Peters8fc4a912004-07-31 21:53:19 +0000593/* a[ilow:ihigh] = v if v != NULL.
594 * del a[ilow:ihigh] if v == NULL.
595 *
596 * Special speed gimmick: when v is NULL and ihigh - ilow <= 8, it's
597 * guaranteed the call cannot fail.
598 */
Armin Rigo93677f02004-07-29 12:40:23 +0000599static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000600list_ass_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000601{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000602 /* Because [X]DECREF can recursively invoke list operations on
603 this list, we must postpone all [X]DECREF activity until
604 after the list is back in its canonical shape. Therefore
605 we must allocate an additional array, 'recycle', into which
606 we temporarily copy the items that are deleted from the
607 list. :-( */
608 PyObject *recycle_on_stack[8];
609 PyObject **recycle = recycle_on_stack; /* will allocate more if needed */
610 PyObject **item;
611 PyObject **vitem = NULL;
612 PyObject *v_as_SF = NULL; /* PySequence_Fast(v) */
613 Py_ssize_t n; /* # of elements in replacement list */
614 Py_ssize_t norig; /* # of elements in list getting replaced */
615 Py_ssize_t d; /* Change in size */
616 Py_ssize_t k;
617 size_t s;
618 int result = -1; /* guilty until proved innocent */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000619#define b ((PyListObject *)v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000620 if (v == NULL)
621 n = 0;
622 else {
623 if (a == b) {
624 /* Special case "a[i:j] = a" -- copy b first */
625 v = list_slice(b, 0, Py_SIZE(b));
626 if (v == NULL)
627 return result;
628 result = list_ass_slice(a, ilow, ihigh, v);
629 Py_DECREF(v);
630 return result;
631 }
632 v_as_SF = PySequence_Fast(v, "can only assign an iterable");
633 if(v_as_SF == NULL)
634 goto Error;
635 n = PySequence_Fast_GET_SIZE(v_as_SF);
636 vitem = PySequence_Fast_ITEMS(v_as_SF);
637 }
638 if (ilow < 0)
639 ilow = 0;
640 else if (ilow > Py_SIZE(a))
641 ilow = Py_SIZE(a);
Tim Peters8d9eb102004-07-31 02:24:20 +0000642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000643 if (ihigh < ilow)
644 ihigh = ilow;
645 else if (ihigh > Py_SIZE(a))
646 ihigh = Py_SIZE(a);
Armin Rigo93677f02004-07-29 12:40:23 +0000647
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000648 norig = ihigh - ilow;
649 assert(norig >= 0);
650 d = n - norig;
651 if (Py_SIZE(a) + d == 0) {
652 Py_XDECREF(v_as_SF);
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200653 return _list_clear(a);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000654 }
655 item = a->ob_item;
656 /* recycle the items that we are about to remove */
657 s = norig * sizeof(PyObject *);
Benjamin Peterson5a7d9232016-09-06 17:58:25 -0700658 /* If norig == 0, item might be NULL, in which case we may not memcpy from it. */
659 if (s) {
660 if (s > sizeof(recycle_on_stack)) {
661 recycle = (PyObject **)PyMem_MALLOC(s);
662 if (recycle == NULL) {
663 PyErr_NoMemory();
664 goto Error;
665 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000666 }
Benjamin Peterson5a7d9232016-09-06 17:58:25 -0700667 memcpy(recycle, &item[ilow], s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 }
Tim Peters8d9eb102004-07-31 02:24:20 +0000669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 if (d < 0) { /* Delete -d items */
Victor Stinner2c40f642013-07-19 23:06:21 +0200671 Py_ssize_t tail;
672 tail = (Py_SIZE(a) - ihigh) * sizeof(PyObject *);
673 memmove(&item[ihigh+d], &item[ihigh], tail);
674 if (list_resize(a, Py_SIZE(a) + d) < 0) {
675 memmove(&item[ihigh], &item[ihigh+d], tail);
676 memcpy(&item[ilow], recycle, s);
677 goto Error;
678 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000679 item = a->ob_item;
680 }
681 else if (d > 0) { /* Insert d items */
682 k = Py_SIZE(a);
683 if (list_resize(a, k+d) < 0)
684 goto Error;
685 item = a->ob_item;
686 memmove(&item[ihigh+d], &item[ihigh],
687 (k - ihigh)*sizeof(PyObject *));
688 }
689 for (k = 0; k < n; k++, ilow++) {
690 PyObject *w = vitem[k];
691 Py_XINCREF(w);
692 item[ilow] = w;
693 }
694 for (k = norig - 1; k >= 0; --k)
695 Py_XDECREF(recycle[k]);
696 result = 0;
Tim Peters8d9eb102004-07-31 02:24:20 +0000697 Error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000698 if (recycle != recycle_on_stack)
699 PyMem_FREE(recycle);
700 Py_XDECREF(v_as_SF);
701 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000702#undef b
703}
704
Guido van Rossum234f9421993-06-17 12:35:49 +0000705int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000706PyList_SetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum234f9421993-06-17 12:35:49 +0000707{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708 if (!PyList_Check(a)) {
709 PyErr_BadInternalCall();
710 return -1;
711 }
712 return list_ass_slice((PyListObject *)a, ilow, ihigh, v);
Guido van Rossum234f9421993-06-17 12:35:49 +0000713}
714
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000715static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000716list_inplace_repeat(PyListObject *self, Py_ssize_t n)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000717{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 PyObject **items;
719 Py_ssize_t size, i, j, p;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000720
721
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000722 size = PyList_GET_SIZE(self);
723 if (size == 0 || n == 1) {
724 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 (n < 1) {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200729 (void)_list_clear(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000730 Py_INCREF(self);
731 return (PyObject *)self;
732 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000734 if (size > PY_SSIZE_T_MAX / n) {
735 return PyErr_NoMemory();
736 }
Christian Heimesaf98da12008-01-27 15:18:18 +0000737
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800738 if (list_resize(self, size*n) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 return NULL;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000740
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000741 p = size;
742 items = self->ob_item;
743 for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */
744 for (j = 0; j < size; j++) {
745 PyObject *o = items[j];
746 Py_INCREF(o);
747 items[p++] = o;
748 }
749 }
750 Py_INCREF(self);
751 return (PyObject *)self;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000752}
753
Guido van Rossum4a450d01991-04-03 19:05:18 +0000754static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000755list_ass_item(PyListObject *a, Py_ssize_t i, PyObject *v)
Guido van Rossum4a450d01991-04-03 19:05:18 +0000756{
Raymond Hettingerf1aa8ae2018-10-10 20:37:28 -0700757 if (!valid_index(i, Py_SIZE(a))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 PyErr_SetString(PyExc_IndexError,
759 "list assignment index out of range");
760 return -1;
761 }
762 if (v == NULL)
763 return list_ass_slice(a, i, i+1, v);
764 Py_INCREF(v);
Serhiy Storchakaf01e4082016-04-10 18:12:01 +0300765 Py_SETREF(a->ob_item[i], v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000766 return 0;
Guido van Rossum4a450d01991-04-03 19:05:18 +0000767}
768
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200769/*[clinic input]
770list.insert
771
772 index: Py_ssize_t
773 object: object
774 /
775
776Insert object before index.
777[clinic start generated code]*/
778
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000779static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200780list_insert_impl(PyListObject *self, Py_ssize_t index, PyObject *object)
781/*[clinic end generated code: output=7f35e32f60c8cb78 input=858514cf894c7eab]*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000782{
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200783 if (ins1(self, index, object) == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 Py_RETURN_NONE;
785 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000786}
787
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200788/*[clinic input]
789list.clear
790
791Remove all items from list.
792[clinic start generated code]*/
793
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000794static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200795list_clear_impl(PyListObject *self)
796/*[clinic end generated code: output=67a1896c01f74362 input=ca3c1646856742f6]*/
Eli Benderskycbbaa962011-02-25 05:47:53 +0000797{
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200798 _list_clear(self);
Eli Benderskycbbaa962011-02-25 05:47:53 +0000799 Py_RETURN_NONE;
800}
801
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200802/*[clinic input]
803list.copy
804
805Return a shallow copy of the list.
806[clinic start generated code]*/
807
Eli Benderskycbbaa962011-02-25 05:47:53 +0000808static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200809list_copy_impl(PyListObject *self)
810/*[clinic end generated code: output=ec6b72d6209d418e input=6453ab159e84771f]*/
Eli Benderskycbbaa962011-02-25 05:47:53 +0000811{
812 return list_slice(self, 0, Py_SIZE(self));
813}
814
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200815/*[clinic input]
816list.append
817
818 object: object
819 /
820
821Append object to the end of the list.
822[clinic start generated code]*/
823
Eli Benderskycbbaa962011-02-25 05:47:53 +0000824static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200825list_append(PyListObject *self, PyObject *object)
826/*[clinic end generated code: output=7c096003a29c0eae input=43a3fe48a7066e91]*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000827{
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200828 if (app1(self, object) == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000829 Py_RETURN_NONE;
830 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000831}
832
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200833/*[clinic input]
834list.extend
835
836 iterable: object
837 /
838
839Extend list by appending elements from the iterable.
840[clinic start generated code]*/
841
Barry Warsawdedf6d61998-10-09 16:37:25 +0000842static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200843list_extend(PyListObject *self, PyObject *iterable)
844/*[clinic end generated code: output=630fb3bca0c8e789 input=9ec5ba3a81be3a4d]*/
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000845{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000846 PyObject *it; /* iter(v) */
847 Py_ssize_t m; /* size of self */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200848 Py_ssize_t n; /* guess for size of iterable */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 Py_ssize_t mn; /* m + n */
850 Py_ssize_t i;
851 PyObject *(*iternext)(PyObject *);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000853 /* Special cases:
854 1) lists and tuples which can use PySequence_Fast ops
855 2) extending self to self requires making a copy first
856 */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200857 if (PyList_CheckExact(iterable) || PyTuple_CheckExact(iterable) ||
858 (PyObject *)self == iterable) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 PyObject **src, **dest;
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200860 iterable = PySequence_Fast(iterable, "argument must be iterable");
861 if (!iterable)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 return NULL;
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200863 n = PySequence_Fast_GET_SIZE(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 if (n == 0) {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200865 /* short circuit when iterable is empty */
866 Py_DECREF(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000867 Py_RETURN_NONE;
868 }
869 m = Py_SIZE(self);
Martin Panter94b39ce2017-01-14 06:30:37 +0000870 /* It should not be possible to allocate a list large enough to cause
871 an overflow on any relevant platform */
872 assert(m < PY_SSIZE_T_MAX - n);
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800873 if (list_resize(self, m + n) < 0) {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200874 Py_DECREF(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000875 return NULL;
876 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200877 /* note that we may still have self == iterable here for the
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000878 * situation a.extend(a), but the following code works
879 * in that case too. Just make sure to resize self
880 * before calling PySequence_Fast_ITEMS.
881 */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200882 /* populate the end of self with iterable's items */
883 src = PySequence_Fast_ITEMS(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000884 dest = self->ob_item + m;
885 for (i = 0; i < n; i++) {
886 PyObject *o = src[i];
887 Py_INCREF(o);
888 dest[i] = o;
889 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200890 Py_DECREF(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000891 Py_RETURN_NONE;
892 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000893
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200894 it = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000895 if (it == NULL)
896 return NULL;
Victor Stinner58ac7002020-02-07 03:04:21 +0100897 iternext = *Py_TYPE(it)->tp_iternext;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000899 /* Guess a result list size. */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200900 n = PyObject_LengthHint(iterable, 8);
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800901 if (n < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000902 Py_DECREF(it);
903 return NULL;
904 }
905 m = Py_SIZE(self);
Martin Panterb93d8632016-07-25 02:39:20 +0000906 if (m > PY_SSIZE_T_MAX - n) {
907 /* m + n overflowed; on the chance that n lied, and there really
908 * is enough room, ignore it. If n was telling the truth, we'll
909 * eventually run out of memory during the loop.
910 */
911 }
912 else {
913 mn = m + n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 /* Make room. */
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800915 if (list_resize(self, mn) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 goto error;
917 /* Make the list sane again. */
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100918 Py_SET_SIZE(self, m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000919 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 /* Run iterator to exhaustion. */
922 for (;;) {
923 PyObject *item = iternext(it);
924 if (item == NULL) {
925 if (PyErr_Occurred()) {
926 if (PyErr_ExceptionMatches(PyExc_StopIteration))
927 PyErr_Clear();
928 else
929 goto error;
930 }
931 break;
932 }
933 if (Py_SIZE(self) < self->allocated) {
934 /* steals ref */
935 PyList_SET_ITEM(self, Py_SIZE(self), item);
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100936 Py_SET_SIZE(self, Py_SIZE(self) + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000937 }
938 else {
939 int status = app1(self, item);
940 Py_DECREF(item); /* append creates a new ref */
941 if (status < 0)
942 goto error;
943 }
944 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000945
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 /* Cut back result list if initial guess was too large. */
Victor Stinner32fd6ea2013-07-16 21:45:58 +0200947 if (Py_SIZE(self) < self->allocated) {
948 if (list_resize(self, Py_SIZE(self)) < 0)
949 goto error;
950 }
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000951
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 Py_DECREF(it);
953 Py_RETURN_NONE;
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000954
955 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000956 Py_DECREF(it);
957 return NULL;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000958}
959
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000960PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200961_PyList_Extend(PyListObject *self, PyObject *iterable)
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000962{
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200963 return list_extend(self, iterable);
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000964}
965
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000966static PyObject *
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000967list_inplace_concat(PyListObject *self, PyObject *other)
968{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 PyObject *result;
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000970
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200971 result = list_extend(self, other);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 if (result == NULL)
973 return result;
974 Py_DECREF(result);
975 Py_INCREF(self);
976 return (PyObject *)self;
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000977}
978
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200979/*[clinic input]
980list.pop
981
982 index: Py_ssize_t = -1
983 /
984
985Remove and return item at index (default last).
986
987Raises IndexError if list is empty or index is out of range.
988[clinic start generated code]*/
989
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000990static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200991list_pop_impl(PyListObject *self, Py_ssize_t index)
992/*[clinic end generated code: output=6bd69dcb3f17eca8 input=b83675976f329e6f]*/
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000993{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000994 PyObject *v;
995 int status;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000996
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 if (Py_SIZE(self) == 0) {
998 /* Special-case most common failure cause */
999 PyErr_SetString(PyExc_IndexError, "pop from empty list");
1000 return NULL;
1001 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02001002 if (index < 0)
1003 index += Py_SIZE(self);
Raymond Hettingerf1aa8ae2018-10-10 20:37:28 -07001004 if (!valid_index(index, Py_SIZE(self))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 PyErr_SetString(PyExc_IndexError, "pop index out of range");
1006 return NULL;
1007 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02001008 v = self->ob_item[index];
1009 if (index == Py_SIZE(self) - 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001010 status = list_resize(self, Py_SIZE(self) - 1);
Victor Stinnerb27cd3e2013-07-08 22:20:44 +02001011 if (status >= 0)
1012 return v; /* and v now owns the reference the list had */
1013 else
1014 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 }
1016 Py_INCREF(v);
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02001017 status = list_ass_slice(self, index, index+1, (PyObject *)NULL);
Victor Stinner095d99f2013-07-17 21:58:01 +02001018 if (status < 0) {
1019 Py_DECREF(v);
1020 return NULL;
1021 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001022 return v;
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +00001023}
1024
Tim Peters8e2e7ca2002-07-19 02:33:08 +00001025/* Reverse a slice of a list in place, from lo up to (exclusive) hi. */
1026static void
1027reverse_slice(PyObject **lo, PyObject **hi)
1028{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 assert(lo && hi);
Tim Peters8e2e7ca2002-07-19 02:33:08 +00001030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 --hi;
1032 while (lo < hi) {
1033 PyObject *t = *lo;
1034 *lo = *hi;
1035 *hi = t;
1036 ++lo;
1037 --hi;
1038 }
Tim Peters8e2e7ca2002-07-19 02:33:08 +00001039}
1040
Tim Petersa64dc242002-08-01 02:13:36 +00001041/* Lots of code for an adaptive, stable, natural mergesort. There are many
1042 * pieces to this algorithm; read listsort.txt for overviews and details.
1043 */
Guido van Rossum3f236de1996-12-10 23:55:39 +00001044
Daniel Stutzbach98338222010-12-02 21:55:33 +00001045/* A sortslice contains a pointer to an array of keys and a pointer to
1046 * an array of corresponding values. In other words, keys[i]
1047 * corresponds with values[i]. If values == NULL, then the keys are
1048 * also the values.
1049 *
1050 * Several convenience routines are provided here, so that keys and
1051 * values are always moved in sync.
1052 */
1053
1054typedef struct {
1055 PyObject **keys;
1056 PyObject **values;
1057} sortslice;
1058
1059Py_LOCAL_INLINE(void)
1060sortslice_copy(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j)
1061{
1062 s1->keys[i] = s2->keys[j];
1063 if (s1->values != NULL)
1064 s1->values[i] = s2->values[j];
1065}
1066
1067Py_LOCAL_INLINE(void)
Benjamin Peterson9efdcca2010-12-03 01:44:10 +00001068sortslice_copy_incr(sortslice *dst, sortslice *src)
1069{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001070 *dst->keys++ = *src->keys++;
1071 if (dst->values != NULL)
1072 *dst->values++ = *src->values++;
1073}
1074
1075Py_LOCAL_INLINE(void)
Benjamin Peterson9efdcca2010-12-03 01:44:10 +00001076sortslice_copy_decr(sortslice *dst, sortslice *src)
1077{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001078 *dst->keys-- = *src->keys--;
1079 if (dst->values != NULL)
1080 *dst->values-- = *src->values--;
1081}
1082
1083
1084Py_LOCAL_INLINE(void)
1085sortslice_memcpy(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j,
Benjamin Peterson9efdcca2010-12-03 01:44:10 +00001086 Py_ssize_t n)
1087{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001088 memcpy(&s1->keys[i], &s2->keys[j], sizeof(PyObject *) * n);
1089 if (s1->values != NULL)
1090 memcpy(&s1->values[i], &s2->values[j], sizeof(PyObject *) * n);
1091}
1092
1093Py_LOCAL_INLINE(void)
1094sortslice_memmove(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j,
Benjamin Peterson9efdcca2010-12-03 01:44:10 +00001095 Py_ssize_t n)
1096{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001097 memmove(&s1->keys[i], &s2->keys[j], sizeof(PyObject *) * n);
1098 if (s1->values != NULL)
1099 memmove(&s1->values[i], &s2->values[j], sizeof(PyObject *) * n);
1100}
1101
1102Py_LOCAL_INLINE(void)
Benjamin Peterson9efdcca2010-12-03 01:44:10 +00001103sortslice_advance(sortslice *slice, Py_ssize_t n)
1104{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001105 slice->keys += n;
1106 if (slice->values != NULL)
1107 slice->values += n;
1108}
1109
embg1e34da42018-01-28 20:03:23 -07001110/* Comparison function: ms->key_compare, which is set at run-time in
1111 * listsort_impl to optimize for various special cases.
Tim Petersa64dc242002-08-01 02:13:36 +00001112 * Returns -1 on error, 1 if x < y, 0 if x >= y.
1113 */
Guido van Rossum3f236de1996-12-10 23:55:39 +00001114
embg1e34da42018-01-28 20:03:23 -07001115#define ISLT(X, Y) (*(ms->key_compare))(X, Y, ms)
Tim Peters66860f62002-08-04 17:47:26 +00001116
1117/* Compare X to Y via "<". Goto "fail" if the comparison raises an
Tim Petersa8c974c2002-07-19 03:30:57 +00001118 error. Else "k" is set to true iff X<Y, and an "if (k)" block is
1119 started. It makes more sense in context <wink>. X and Y are PyObject*s.
1120*/
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001121#define IFLT(X, Y) if ((k = ISLT(X, Y)) < 0) goto fail; \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001122 if (k)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001123
embg1e34da42018-01-28 20:03:23 -07001124/* The maximum number of entries in a MergeState's pending-runs stack.
1125 * This is enough to sort arrays of size up to about
1126 * 32 * phi ** MAX_MERGE_PENDING
1127 * where phi ~= 1.618. 85 is ridiculouslylarge enough, good for an array
1128 * with 2**64 elements.
1129 */
1130#define MAX_MERGE_PENDING 85
1131
1132/* When we get into galloping mode, we stay there until both runs win less
1133 * often than MIN_GALLOP consecutive times. See listsort.txt for more info.
1134 */
1135#define MIN_GALLOP 7
1136
1137/* Avoid malloc for small temp arrays. */
1138#define MERGESTATE_TEMP_SIZE 256
1139
1140/* One MergeState exists on the stack per invocation of mergesort. It's just
1141 * a convenient way to pass state around among the helper functions.
1142 */
1143struct s_slice {
1144 sortslice base;
1145 Py_ssize_t len;
1146};
1147
1148typedef struct s_MergeState MergeState;
1149struct s_MergeState {
1150 /* This controls when we get *into* galloping mode. It's initialized
1151 * to MIN_GALLOP. merge_lo and merge_hi tend to nudge it higher for
1152 * random data, and lower for highly structured data.
1153 */
1154 Py_ssize_t min_gallop;
1155
1156 /* 'a' is temp storage to help with merges. It contains room for
1157 * alloced entries.
1158 */
1159 sortslice a; /* may point to temparray below */
1160 Py_ssize_t alloced;
1161
1162 /* A stack of n pending runs yet to be merged. Run #i starts at
1163 * address base[i] and extends for len[i] elements. It's always
1164 * true (so long as the indices are in bounds) that
1165 *
1166 * pending[i].base + pending[i].len == pending[i+1].base
1167 *
1168 * so we could cut the storage for this, but it's a minor amount,
1169 * and keeping all the info explicit simplifies the code.
1170 */
1171 int n;
1172 struct s_slice pending[MAX_MERGE_PENDING];
1173
1174 /* 'a' points to this when possible, rather than muck with malloc. */
1175 PyObject *temparray[MERGESTATE_TEMP_SIZE];
1176
1177 /* This is the function we will use to compare two keys,
1178 * even when none of our special cases apply and we have to use
1179 * safe_object_compare. */
1180 int (*key_compare)(PyObject *, PyObject *, MergeState *);
1181
1182 /* This function is used by unsafe_object_compare to optimize comparisons
1183 * when we know our list is type-homogeneous but we can't assume anything else.
Victor Stinner58ac7002020-02-07 03:04:21 +01001184 * In the pre-sort check it is set equal to Py_TYPE(key)->tp_richcompare */
embg1e34da42018-01-28 20:03:23 -07001185 PyObject *(*key_richcompare)(PyObject *, PyObject *, int);
1186
1187 /* This function is used by unsafe_tuple_compare to compare the first elements
1188 * of tuples. It may be set to safe_object_compare, but the idea is that hopefully
1189 * we can assume more, and use one of the special-case compares. */
1190 int (*tuple_elem_compare)(PyObject *, PyObject *, MergeState *);
1191};
1192
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001193/* binarysort is the best method for sorting small arrays: it does
1194 few compares, but can do data movement quadratic in the number of
1195 elements.
Guido van Rossum42812581998-06-17 14:15:44 +00001196 [lo, hi) is a contiguous slice of a list, and is sorted via
Tim Petersa8c974c2002-07-19 03:30:57 +00001197 binary insertion. This sort is stable.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001198 On entry, must have lo <= start <= hi, and that [lo, start) is already
1199 sorted (pass start == lo if you don't know!).
Tim Petersa8c974c2002-07-19 03:30:57 +00001200 If islt() complains return -1, else 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001201 Even in case of error, the output slice will be some permutation of
1202 the input (nothing is lost or duplicated).
1203*/
Guido van Rossum3f236de1996-12-10 23:55:39 +00001204static int
embg1e34da42018-01-28 20:03:23 -07001205binarysort(MergeState *ms, sortslice lo, PyObject **hi, PyObject **start)
Guido van Rossum3f236de1996-12-10 23:55:39 +00001206{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001207 Py_ssize_t k;
1208 PyObject **l, **p, **r;
1209 PyObject *pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001210
Daniel Stutzbach98338222010-12-02 21:55:33 +00001211 assert(lo.keys <= start && start <= hi);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001212 /* assert [lo, start) is sorted */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001213 if (lo.keys == start)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001214 ++start;
1215 for (; start < hi; ++start) {
1216 /* set l to where *start belongs */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001217 l = lo.keys;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001218 r = start;
1219 pivot = *r;
1220 /* Invariants:
1221 * pivot >= all in [lo, l).
1222 * pivot < all in [r, start).
1223 * The second is vacuously true at the start.
1224 */
1225 assert(l < r);
1226 do {
1227 p = l + ((r - l) >> 1);
1228 IFLT(pivot, *p)
1229 r = p;
1230 else
1231 l = p+1;
1232 } while (l < r);
1233 assert(l == r);
1234 /* The invariants still hold, so pivot >= all in [lo, l) and
1235 pivot < all in [l, start), so pivot belongs at l. Note
1236 that if there are elements equal to pivot, l points to the
1237 first slot after them -- that's why this sort is stable.
1238 Slide over to make room.
1239 Caution: using memmove is much slower under MSVC 5;
1240 we're not usually moving many slots. */
1241 for (p = start; p > l; --p)
1242 *p = *(p-1);
1243 *l = pivot;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001244 if (lo.values != NULL) {
1245 Py_ssize_t offset = lo.values - lo.keys;
1246 p = start + offset;
1247 pivot = *p;
1248 l += offset;
1249 for (p = start + offset; p > l; --p)
1250 *p = *(p-1);
1251 *l = pivot;
1252 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001253 }
1254 return 0;
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001255
1256 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001257 return -1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001258}
1259
Tim Petersa64dc242002-08-01 02:13:36 +00001260/*
1261Return the length of the run beginning at lo, in the slice [lo, hi). lo < hi
1262is required on entry. "A run" is the longest ascending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001263
Tim Petersa64dc242002-08-01 02:13:36 +00001264 lo[0] <= lo[1] <= lo[2] <= ...
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001265
Tim Petersa64dc242002-08-01 02:13:36 +00001266or the longest descending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001267
Tim Petersa64dc242002-08-01 02:13:36 +00001268 lo[0] > lo[1] > lo[2] > ...
Tim Peters3b01a122002-07-19 02:35:45 +00001269
Tim Petersa64dc242002-08-01 02:13:36 +00001270Boolean *descending is set to 0 in the former case, or to 1 in the latter.
1271For its intended use in a stable mergesort, the strictness of the defn of
1272"descending" is needed so that the caller can safely reverse a descending
1273sequence without violating stability (strict > ensures there are no equal
1274elements to get out of order).
1275
1276Returns -1 in case of error.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001277*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001278static Py_ssize_t
embg1e34da42018-01-28 20:03:23 -07001279count_run(MergeState *ms, PyObject **lo, PyObject **hi, int *descending)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001280{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001281 Py_ssize_t k;
1282 Py_ssize_t n;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001284 assert(lo < hi);
1285 *descending = 0;
1286 ++lo;
1287 if (lo == hi)
1288 return 1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001290 n = 2;
1291 IFLT(*lo, *(lo-1)) {
1292 *descending = 1;
1293 for (lo = lo+1; lo < hi; ++lo, ++n) {
1294 IFLT(*lo, *(lo-1))
1295 ;
1296 else
1297 break;
1298 }
1299 }
1300 else {
1301 for (lo = lo+1; lo < hi; ++lo, ++n) {
1302 IFLT(*lo, *(lo-1))
1303 break;
1304 }
1305 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001307 return n;
Tim Petersa64dc242002-08-01 02:13:36 +00001308fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001309 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001310}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001311
Tim Petersa64dc242002-08-01 02:13:36 +00001312/*
1313Locate the proper position of key in a sorted vector; if the vector contains
1314an element equal to key, return the position immediately to the left of
1315the leftmost equal element. [gallop_right() does the same except returns
1316the position to the right of the rightmost equal element (if any).]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001317
Tim Petersa64dc242002-08-01 02:13:36 +00001318"a" is a sorted vector with n elements, starting at a[0]. n must be > 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001319
Tim Petersa64dc242002-08-01 02:13:36 +00001320"hint" is an index at which to begin the search, 0 <= hint < n. The closer
1321hint is to the final result, the faster this runs.
1322
1323The return value is the int k in 0..n such that
1324
1325 a[k-1] < key <= a[k]
1326
1327pretending that *(a-1) is minus infinity and a[n] is plus infinity. IOW,
1328key belongs at index k; or, IOW, the first k elements of a should precede
1329key, and the last n-k should follow key.
1330
1331Returns -1 on error. See listsort.txt for info on the method.
1332*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001333static Py_ssize_t
embg1e34da42018-01-28 20:03:23 -07001334gallop_left(MergeState *ms, PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint)
Tim Petersa64dc242002-08-01 02:13:36 +00001335{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336 Py_ssize_t ofs;
1337 Py_ssize_t lastofs;
1338 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001340 assert(key && a && n > 0 && hint >= 0 && hint < n);
Tim Petersa64dc242002-08-01 02:13:36 +00001341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001342 a += hint;
1343 lastofs = 0;
1344 ofs = 1;
1345 IFLT(*a, key) {
1346 /* a[hint] < key -- gallop right, until
1347 * a[hint + lastofs] < key <= a[hint + ofs]
1348 */
1349 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
1350 while (ofs < maxofs) {
1351 IFLT(a[ofs], key) {
1352 lastofs = ofs;
Alexey Izbyshev6bc59172019-05-23 03:01:08 +03001353 assert(ofs <= (PY_SSIZE_T_MAX - 1) / 2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001354 ofs = (ofs << 1) + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001355 }
1356 else /* key <= a[hint + ofs] */
1357 break;
1358 }
1359 if (ofs > maxofs)
1360 ofs = maxofs;
1361 /* Translate back to offsets relative to &a[0]. */
1362 lastofs += hint;
1363 ofs += hint;
1364 }
1365 else {
1366 /* key <= a[hint] -- gallop left, until
1367 * a[hint - ofs] < key <= a[hint - lastofs]
1368 */
1369 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
1370 while (ofs < maxofs) {
1371 IFLT(*(a-ofs), key)
1372 break;
1373 /* key <= a[hint - ofs] */
1374 lastofs = ofs;
Alexey Izbyshev6bc59172019-05-23 03:01:08 +03001375 assert(ofs <= (PY_SSIZE_T_MAX - 1) / 2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001376 ofs = (ofs << 1) + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001377 }
1378 if (ofs > maxofs)
1379 ofs = maxofs;
1380 /* Translate back to positive offsets relative to &a[0]. */
1381 k = lastofs;
1382 lastofs = hint - ofs;
1383 ofs = hint - k;
1384 }
1385 a -= hint;
Tim Petersa64dc242002-08-01 02:13:36 +00001386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001387 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1388 /* Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the
1389 * right of lastofs but no farther right than ofs. Do a binary
1390 * search, with invariant a[lastofs-1] < key <= a[ofs].
1391 */
1392 ++lastofs;
1393 while (lastofs < ofs) {
1394 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001396 IFLT(a[m], key)
1397 lastofs = m+1; /* a[m] < key */
1398 else
1399 ofs = m; /* key <= a[m] */
1400 }
1401 assert(lastofs == ofs); /* so a[ofs-1] < key <= a[ofs] */
1402 return ofs;
Tim Petersa64dc242002-08-01 02:13:36 +00001403
1404fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001405 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001406}
1407
1408/*
1409Exactly like gallop_left(), except that if key already exists in a[0:n],
1410finds the position immediately to the right of the rightmost equal value.
1411
1412The return value is the int k in 0..n such that
1413
1414 a[k-1] <= key < a[k]
1415
1416or -1 if error.
1417
1418The code duplication is massive, but this is enough different given that
1419we're sticking to "<" comparisons that it's much harder to follow if
1420written as one routine with yet another "left or right?" flag.
1421*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001422static Py_ssize_t
embg1e34da42018-01-28 20:03:23 -07001423gallop_right(MergeState *ms, PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint)
Tim Petersa64dc242002-08-01 02:13:36 +00001424{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001425 Py_ssize_t ofs;
1426 Py_ssize_t lastofs;
1427 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001428
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001429 assert(key && a && n > 0 && hint >= 0 && hint < n);
Tim Petersa64dc242002-08-01 02:13:36 +00001430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001431 a += hint;
1432 lastofs = 0;
1433 ofs = 1;
1434 IFLT(key, *a) {
1435 /* key < a[hint] -- gallop left, until
1436 * a[hint - ofs] <= key < a[hint - lastofs]
1437 */
1438 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
1439 while (ofs < maxofs) {
1440 IFLT(key, *(a-ofs)) {
1441 lastofs = ofs;
Alexey Izbyshev6bc59172019-05-23 03:01:08 +03001442 assert(ofs <= (PY_SSIZE_T_MAX - 1) / 2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001443 ofs = (ofs << 1) + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001444 }
1445 else /* a[hint - ofs] <= key */
1446 break;
1447 }
1448 if (ofs > maxofs)
1449 ofs = maxofs;
1450 /* Translate back to positive offsets relative to &a[0]. */
1451 k = lastofs;
1452 lastofs = hint - ofs;
1453 ofs = hint - k;
1454 }
1455 else {
1456 /* a[hint] <= key -- gallop right, until
1457 * a[hint + lastofs] <= key < a[hint + ofs]
1458 */
1459 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
1460 while (ofs < maxofs) {
1461 IFLT(key, a[ofs])
1462 break;
1463 /* a[hint + ofs] <= key */
1464 lastofs = ofs;
Alexey Izbyshev6bc59172019-05-23 03:01:08 +03001465 assert(ofs <= (PY_SSIZE_T_MAX - 1) / 2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001466 ofs = (ofs << 1) + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001467 }
1468 if (ofs > maxofs)
1469 ofs = maxofs;
1470 /* Translate back to offsets relative to &a[0]. */
1471 lastofs += hint;
1472 ofs += hint;
1473 }
1474 a -= hint;
Tim Petersa64dc242002-08-01 02:13:36 +00001475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001476 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1477 /* Now a[lastofs] <= key < a[ofs], so key belongs somewhere to the
1478 * right of lastofs but no farther right than ofs. Do a binary
1479 * search, with invariant a[lastofs-1] <= key < a[ofs].
1480 */
1481 ++lastofs;
1482 while (lastofs < ofs) {
1483 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001485 IFLT(key, a[m])
1486 ofs = m; /* key < a[m] */
1487 else
1488 lastofs = m+1; /* a[m] <= key */
1489 }
1490 assert(lastofs == ofs); /* so a[ofs-1] <= key < a[ofs] */
1491 return ofs;
Tim Petersa64dc242002-08-01 02:13:36 +00001492
1493fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001494 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001495}
1496
Tim Petersa64dc242002-08-01 02:13:36 +00001497/* Conceptually a MergeState's constructor. */
1498static void
Victor Stinner0fcab4a2011-01-04 12:59:15 +00001499merge_init(MergeState *ms, Py_ssize_t list_size, int has_keyfunc)
Tim Petersa64dc242002-08-01 02:13:36 +00001500{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001501 assert(ms != NULL);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001502 if (has_keyfunc) {
1503 /* The temporary space for merging will need at most half the list
1504 * size rounded up. Use the minimum possible space so we can use the
1505 * rest of temparray for other things. In particular, if there is
1506 * enough extra space, listsort() will use it to store the keys.
1507 */
1508 ms->alloced = (list_size + 1) / 2;
1509
1510 /* ms->alloced describes how many keys will be stored at
1511 ms->temparray, but we also need to store the values. Hence,
1512 ms->alloced is capped at half of MERGESTATE_TEMP_SIZE. */
1513 if (MERGESTATE_TEMP_SIZE / 2 < ms->alloced)
1514 ms->alloced = MERGESTATE_TEMP_SIZE / 2;
1515 ms->a.values = &ms->temparray[ms->alloced];
1516 }
1517 else {
1518 ms->alloced = MERGESTATE_TEMP_SIZE;
1519 ms->a.values = NULL;
1520 }
1521 ms->a.keys = ms->temparray;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001522 ms->n = 0;
1523 ms->min_gallop = MIN_GALLOP;
Tim Petersa64dc242002-08-01 02:13:36 +00001524}
1525
1526/* Free all the temp memory owned by the MergeState. This must be called
1527 * when you're done with a MergeState, and may be called before then if
1528 * you want to free the temp memory early.
1529 */
1530static void
1531merge_freemem(MergeState *ms)
1532{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001533 assert(ms != NULL);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001534 if (ms->a.keys != ms->temparray)
1535 PyMem_Free(ms->a.keys);
Tim Petersa64dc242002-08-01 02:13:36 +00001536}
1537
1538/* Ensure enough temp memory for 'need' array slots is available.
1539 * Returns 0 on success and -1 if the memory can't be gotten.
1540 */
1541static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001542merge_getmem(MergeState *ms, Py_ssize_t need)
Tim Petersa64dc242002-08-01 02:13:36 +00001543{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001544 int multiplier;
1545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001546 assert(ms != NULL);
1547 if (need <= ms->alloced)
1548 return 0;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001549
1550 multiplier = ms->a.values != NULL ? 2 : 1;
1551
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001552 /* Don't realloc! That can cost cycles to copy the old data, but
1553 * we don't care what's in the block.
1554 */
1555 merge_freemem(ms);
embg1e34da42018-01-28 20:03:23 -07001556 if ((size_t)need > PY_SSIZE_T_MAX / sizeof(PyObject *) / multiplier) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001557 PyErr_NoMemory();
1558 return -1;
1559 }
embg1e34da42018-01-28 20:03:23 -07001560 ms->a.keys = (PyObject **)PyMem_Malloc(multiplier * need
Daniel Stutzbach98338222010-12-02 21:55:33 +00001561 * sizeof(PyObject *));
1562 if (ms->a.keys != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001563 ms->alloced = need;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001564 if (ms->a.values != NULL)
1565 ms->a.values = &ms->a.keys[need];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001566 return 0;
1567 }
1568 PyErr_NoMemory();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001569 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001570}
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001571#define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 : \
1572 merge_getmem(MS, NEED))
Tim Petersa64dc242002-08-01 02:13:36 +00001573
Daniel Stutzbach98338222010-12-02 21:55:33 +00001574/* Merge the na elements starting at ssa with the nb elements starting at
1575 * ssb.keys = ssa.keys + na in a stable way, in-place. na and nb must be > 0.
1576 * Must also have that ssa.keys[na-1] belongs at the end of the merge, and
1577 * should have na <= nb. See listsort.txt for more info. Return 0 if
1578 * successful, -1 if error.
Tim Petersa64dc242002-08-01 02:13:36 +00001579 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001580static Py_ssize_t
Daniel Stutzbach98338222010-12-02 21:55:33 +00001581merge_lo(MergeState *ms, sortslice ssa, Py_ssize_t na,
1582 sortslice ssb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001583{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001584 Py_ssize_t k;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001585 sortslice dest;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001586 int result = -1; /* guilty until proved innocent */
1587 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001588
Daniel Stutzbach98338222010-12-02 21:55:33 +00001589 assert(ms && ssa.keys && ssb.keys && na > 0 && nb > 0);
1590 assert(ssa.keys + na == ssb.keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001591 if (MERGE_GETMEM(ms, na) < 0)
1592 return -1;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001593 sortslice_memcpy(&ms->a, 0, &ssa, 0, na);
1594 dest = ssa;
1595 ssa = ms->a;
Tim Petersa64dc242002-08-01 02:13:36 +00001596
Daniel Stutzbach98338222010-12-02 21:55:33 +00001597 sortslice_copy_incr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001598 --nb;
1599 if (nb == 0)
1600 goto Succeed;
1601 if (na == 1)
1602 goto CopyB;
Tim Petersa64dc242002-08-01 02:13:36 +00001603
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001604 min_gallop = ms->min_gallop;
1605 for (;;) {
1606 Py_ssize_t acount = 0; /* # of times A won in a row */
1607 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001608
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001609 /* Do the straightforward thing until (if ever) one run
1610 * appears to win consistently.
1611 */
1612 for (;;) {
1613 assert(na > 1 && nb > 0);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001614 k = ISLT(ssb.keys[0], ssa.keys[0]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001615 if (k) {
1616 if (k < 0)
1617 goto Fail;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001618 sortslice_copy_incr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001619 ++bcount;
1620 acount = 0;
1621 --nb;
1622 if (nb == 0)
1623 goto Succeed;
1624 if (bcount >= min_gallop)
1625 break;
1626 }
1627 else {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001628 sortslice_copy_incr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001629 ++acount;
1630 bcount = 0;
1631 --na;
1632 if (na == 1)
1633 goto CopyB;
1634 if (acount >= min_gallop)
1635 break;
1636 }
1637 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001639 /* One run is winning so consistently that galloping may
1640 * be a huge win. So try that, and continue galloping until
1641 * (if ever) neither run appears to be winning consistently
1642 * anymore.
1643 */
1644 ++min_gallop;
1645 do {
1646 assert(na > 1 && nb > 0);
1647 min_gallop -= min_gallop > 1;
1648 ms->min_gallop = min_gallop;
embg1e34da42018-01-28 20:03:23 -07001649 k = gallop_right(ms, ssb.keys[0], ssa.keys, na, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001650 acount = k;
1651 if (k) {
1652 if (k < 0)
1653 goto Fail;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001654 sortslice_memcpy(&dest, 0, &ssa, 0, k);
1655 sortslice_advance(&dest, k);
1656 sortslice_advance(&ssa, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001657 na -= k;
1658 if (na == 1)
1659 goto CopyB;
1660 /* na==0 is impossible now if the comparison
1661 * function is consistent, but we can't assume
1662 * that it is.
1663 */
1664 if (na == 0)
1665 goto Succeed;
1666 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001667 sortslice_copy_incr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001668 --nb;
1669 if (nb == 0)
1670 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001671
embg1e34da42018-01-28 20:03:23 -07001672 k = gallop_left(ms, ssa.keys[0], ssb.keys, nb, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001673 bcount = k;
1674 if (k) {
1675 if (k < 0)
1676 goto Fail;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001677 sortslice_memmove(&dest, 0, &ssb, 0, k);
1678 sortslice_advance(&dest, k);
1679 sortslice_advance(&ssb, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001680 nb -= k;
1681 if (nb == 0)
1682 goto Succeed;
1683 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001684 sortslice_copy_incr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001685 --na;
1686 if (na == 1)
1687 goto CopyB;
1688 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
1689 ++min_gallop; /* penalize it for leaving galloping mode */
1690 ms->min_gallop = min_gallop;
1691 }
Tim Petersa64dc242002-08-01 02:13:36 +00001692Succeed:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001693 result = 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001694Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001695 if (na)
Daniel Stutzbach98338222010-12-02 21:55:33 +00001696 sortslice_memcpy(&dest, 0, &ssa, 0, na);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001697 return result;
Tim Petersa64dc242002-08-01 02:13:36 +00001698CopyB:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001699 assert(na == 1 && nb > 0);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001700 /* The last element of ssa belongs at the end of the merge. */
1701 sortslice_memmove(&dest, 0, &ssb, 0, nb);
1702 sortslice_copy(&dest, nb, &ssa, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001703 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001704}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001705
Daniel Stutzbach98338222010-12-02 21:55:33 +00001706/* Merge the na elements starting at pa with the nb elements starting at
1707 * ssb.keys = ssa.keys + na in a stable way, in-place. na and nb must be > 0.
1708 * Must also have that ssa.keys[na-1] belongs at the end of the merge, and
1709 * should have na >= nb. See listsort.txt for more info. Return 0 if
1710 * successful, -1 if error.
Tim Petersa64dc242002-08-01 02:13:36 +00001711 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001712static Py_ssize_t
Daniel Stutzbach98338222010-12-02 21:55:33 +00001713merge_hi(MergeState *ms, sortslice ssa, Py_ssize_t na,
1714 sortslice ssb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001715{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001716 Py_ssize_t k;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001717 sortslice dest, basea, baseb;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001718 int result = -1; /* guilty until proved innocent */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001719 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001720
Daniel Stutzbach98338222010-12-02 21:55:33 +00001721 assert(ms && ssa.keys && ssb.keys && na > 0 && nb > 0);
1722 assert(ssa.keys + na == ssb.keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001723 if (MERGE_GETMEM(ms, nb) < 0)
1724 return -1;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001725 dest = ssb;
1726 sortslice_advance(&dest, nb-1);
1727 sortslice_memcpy(&ms->a, 0, &ssb, 0, nb);
1728 basea = ssa;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001729 baseb = ms->a;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001730 ssb.keys = ms->a.keys + nb - 1;
1731 if (ssb.values != NULL)
1732 ssb.values = ms->a.values + nb - 1;
1733 sortslice_advance(&ssa, na - 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001734
Daniel Stutzbach98338222010-12-02 21:55:33 +00001735 sortslice_copy_decr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 --na;
1737 if (na == 0)
1738 goto Succeed;
1739 if (nb == 1)
1740 goto CopyA;
Tim Petersa64dc242002-08-01 02:13:36 +00001741
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001742 min_gallop = ms->min_gallop;
1743 for (;;) {
1744 Py_ssize_t acount = 0; /* # of times A won in a row */
1745 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001746
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001747 /* Do the straightforward thing until (if ever) one run
1748 * appears to win consistently.
1749 */
1750 for (;;) {
1751 assert(na > 0 && nb > 1);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001752 k = ISLT(ssb.keys[0], ssa.keys[0]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001753 if (k) {
1754 if (k < 0)
1755 goto Fail;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001756 sortslice_copy_decr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001757 ++acount;
1758 bcount = 0;
1759 --na;
1760 if (na == 0)
1761 goto Succeed;
1762 if (acount >= min_gallop)
1763 break;
1764 }
1765 else {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001766 sortslice_copy_decr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001767 ++bcount;
1768 acount = 0;
1769 --nb;
1770 if (nb == 1)
1771 goto CopyA;
1772 if (bcount >= min_gallop)
1773 break;
1774 }
1775 }
Tim Petersa64dc242002-08-01 02:13:36 +00001776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001777 /* One run is winning so consistently that galloping may
1778 * be a huge win. So try that, and continue galloping until
1779 * (if ever) neither run appears to be winning consistently
1780 * anymore.
1781 */
1782 ++min_gallop;
1783 do {
1784 assert(na > 0 && nb > 1);
1785 min_gallop -= min_gallop > 1;
1786 ms->min_gallop = min_gallop;
embg1e34da42018-01-28 20:03:23 -07001787 k = gallop_right(ms, ssb.keys[0], basea.keys, na, na-1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001788 if (k < 0)
1789 goto Fail;
1790 k = na - k;
1791 acount = k;
1792 if (k) {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001793 sortslice_advance(&dest, -k);
1794 sortslice_advance(&ssa, -k);
1795 sortslice_memmove(&dest, 1, &ssa, 1, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001796 na -= k;
1797 if (na == 0)
1798 goto Succeed;
1799 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001800 sortslice_copy_decr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001801 --nb;
1802 if (nb == 1)
1803 goto CopyA;
Tim Petersa64dc242002-08-01 02:13:36 +00001804
embg1e34da42018-01-28 20:03:23 -07001805 k = gallop_left(ms, ssa.keys[0], baseb.keys, nb, nb-1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001806 if (k < 0)
1807 goto Fail;
1808 k = nb - k;
1809 bcount = k;
1810 if (k) {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001811 sortslice_advance(&dest, -k);
1812 sortslice_advance(&ssb, -k);
1813 sortslice_memcpy(&dest, 1, &ssb, 1, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001814 nb -= k;
1815 if (nb == 1)
1816 goto CopyA;
1817 /* nb==0 is impossible now if the comparison
1818 * function is consistent, but we can't assume
1819 * that it is.
1820 */
1821 if (nb == 0)
1822 goto Succeed;
1823 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001824 sortslice_copy_decr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001825 --na;
1826 if (na == 0)
1827 goto Succeed;
1828 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
1829 ++min_gallop; /* penalize it for leaving galloping mode */
1830 ms->min_gallop = min_gallop;
1831 }
Tim Petersa64dc242002-08-01 02:13:36 +00001832Succeed:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001833 result = 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001834Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001835 if (nb)
Daniel Stutzbach98338222010-12-02 21:55:33 +00001836 sortslice_memcpy(&dest, -(nb-1), &baseb, 0, nb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001837 return result;
Tim Petersa64dc242002-08-01 02:13:36 +00001838CopyA:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001839 assert(nb == 1 && na > 0);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001840 /* The first element of ssb belongs at the front of the merge. */
1841 sortslice_memmove(&dest, 1-na, &ssa, 1-na, na);
1842 sortslice_advance(&dest, -na);
1843 sortslice_advance(&ssa, -na);
1844 sortslice_copy(&dest, 0, &ssb, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001845 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001846}
1847
1848/* Merge the two runs at stack indices i and i+1.
1849 * Returns 0 on success, -1 on error.
1850 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001851static Py_ssize_t
1852merge_at(MergeState *ms, Py_ssize_t i)
Tim Petersa64dc242002-08-01 02:13:36 +00001853{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001854 sortslice ssa, ssb;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001855 Py_ssize_t na, nb;
1856 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001858 assert(ms != NULL);
1859 assert(ms->n >= 2);
1860 assert(i >= 0);
1861 assert(i == ms->n - 2 || i == ms->n - 3);
Tim Petersa64dc242002-08-01 02:13:36 +00001862
Daniel Stutzbach98338222010-12-02 21:55:33 +00001863 ssa = ms->pending[i].base;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001864 na = ms->pending[i].len;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001865 ssb = ms->pending[i+1].base;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001866 nb = ms->pending[i+1].len;
1867 assert(na > 0 && nb > 0);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001868 assert(ssa.keys + na == ssb.keys);
Tim Petersa64dc242002-08-01 02:13:36 +00001869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001870 /* Record the length of the combined runs; if i is the 3rd-last
1871 * run now, also slide over the last run (which isn't involved
1872 * in this merge). The current run i+1 goes away in any case.
1873 */
1874 ms->pending[i].len = na + nb;
1875 if (i == ms->n - 3)
1876 ms->pending[i+1] = ms->pending[i+2];
1877 --ms->n;
Tim Petersa64dc242002-08-01 02:13:36 +00001878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001879 /* Where does b start in a? Elements in a before that can be
1880 * ignored (already in place).
1881 */
embg1e34da42018-01-28 20:03:23 -07001882 k = gallop_right(ms, *ssb.keys, ssa.keys, na, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001883 if (k < 0)
1884 return -1;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001885 sortslice_advance(&ssa, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001886 na -= k;
1887 if (na == 0)
1888 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001890 /* Where does a end in b? Elements in b after that can be
1891 * ignored (already in place).
1892 */
embg1e34da42018-01-28 20:03:23 -07001893 nb = gallop_left(ms, ssa.keys[na-1], ssb.keys, nb, nb-1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001894 if (nb <= 0)
1895 return nb;
Tim Petersa64dc242002-08-01 02:13:36 +00001896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001897 /* Merge what remains of the runs, using a temp array with
1898 * min(na, nb) elements.
1899 */
1900 if (na <= nb)
Daniel Stutzbach98338222010-12-02 21:55:33 +00001901 return merge_lo(ms, ssa, na, ssb, nb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001902 else
Daniel Stutzbach98338222010-12-02 21:55:33 +00001903 return merge_hi(ms, ssa, na, ssb, nb);
Tim Petersa64dc242002-08-01 02:13:36 +00001904}
1905
1906/* Examine the stack of runs waiting to be merged, merging adjacent runs
1907 * until the stack invariants are re-established:
1908 *
1909 * 1. len[-3] > len[-2] + len[-1]
1910 * 2. len[-2] > len[-1]
1911 *
1912 * See listsort.txt for more info.
1913 *
1914 * Returns 0 on success, -1 on error.
1915 */
1916static int
1917merge_collapse(MergeState *ms)
1918{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001919 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001921 assert(ms);
1922 while (ms->n > 1) {
1923 Py_ssize_t n = ms->n - 2;
Benjamin Petersonb808d592015-02-25 10:12:26 -05001924 if ((n > 0 && p[n-1].len <= p[n].len + p[n+1].len) ||
1925 (n > 1 && p[n-2].len <= p[n-1].len + p[n].len)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001926 if (p[n-1].len < p[n+1].len)
1927 --n;
1928 if (merge_at(ms, n) < 0)
1929 return -1;
1930 }
1931 else if (p[n].len <= p[n+1].len) {
embg1e34da42018-01-28 20:03:23 -07001932 if (merge_at(ms, n) < 0)
1933 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001934 }
1935 else
1936 break;
1937 }
1938 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001939}
1940
1941/* Regardless of invariants, merge all runs on the stack until only one
1942 * remains. This is used at the end of the mergesort.
1943 *
1944 * Returns 0 on success, -1 on error.
1945 */
1946static int
1947merge_force_collapse(MergeState *ms)
1948{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001949 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001950
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001951 assert(ms);
1952 while (ms->n > 1) {
1953 Py_ssize_t n = ms->n - 2;
1954 if (n > 0 && p[n-1].len < p[n+1].len)
1955 --n;
1956 if (merge_at(ms, n) < 0)
1957 return -1;
1958 }
1959 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001960}
1961
1962/* Compute a good value for the minimum run length; natural runs shorter
1963 * than this are boosted artificially via binary insertion.
1964 *
1965 * If n < 64, return n (it's too small to bother with fancy stuff).
1966 * Else if n is an exact power of 2, return 32.
1967 * Else return an int k, 32 <= k <= 64, such that n/k is close to, but
1968 * strictly less than, an exact power of 2.
1969 *
1970 * See listsort.txt for more info.
1971 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001972static Py_ssize_t
1973merge_compute_minrun(Py_ssize_t n)
Tim Petersa64dc242002-08-01 02:13:36 +00001974{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001975 Py_ssize_t r = 0; /* becomes 1 if any 1 bits are shifted off */
Tim Petersa64dc242002-08-01 02:13:36 +00001976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001977 assert(n >= 0);
1978 while (n >= 64) {
1979 r |= n & 1;
1980 n >>= 1;
1981 }
1982 return n + r;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001983}
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001984
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001985static void
Daniel Stutzbach98338222010-12-02 21:55:33 +00001986reverse_sortslice(sortslice *s, Py_ssize_t n)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001987{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001988 reverse_slice(s->keys, &s->keys[n]);
1989 if (s->values != NULL)
1990 reverse_slice(s->values, &s->values[n]);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001991}
1992
embg1e34da42018-01-28 20:03:23 -07001993/* Here we define custom comparison functions to optimize for the cases one commonly
1994 * encounters in practice: homogeneous lists, often of one of the basic types. */
1995
1996/* This struct holds the comparison function and helper functions
1997 * selected in the pre-sort check. */
1998
1999/* These are the special case compare functions.
2000 * ms->key_compare will always point to one of these: */
2001
2002/* Heterogeneous compare: default, always safe to fall back on. */
2003static int
2004safe_object_compare(PyObject *v, PyObject *w, MergeState *ms)
2005{
2006 /* No assumptions necessary! */
2007 return PyObject_RichCompareBool(v, w, Py_LT);
2008}
2009
2010/* Homogeneous compare: safe for any two compareable objects of the same type.
2011 * (ms->key_richcompare is set to ob_type->tp_richcompare in the
2012 * pre-sort check.)
2013 */
2014static int
2015unsafe_object_compare(PyObject *v, PyObject *w, MergeState *ms)
2016{
2017 PyObject *res_obj; int res;
2018
2019 /* No assumptions, because we check first: */
Victor Stinner58ac7002020-02-07 03:04:21 +01002020 if (Py_TYPE(v)->tp_richcompare != ms->key_richcompare)
embg1e34da42018-01-28 20:03:23 -07002021 return PyObject_RichCompareBool(v, w, Py_LT);
2022
2023 assert(ms->key_richcompare != NULL);
2024 res_obj = (*(ms->key_richcompare))(v, w, Py_LT);
2025
2026 if (res_obj == Py_NotImplemented) {
2027 Py_DECREF(res_obj);
2028 return PyObject_RichCompareBool(v, w, Py_LT);
2029 }
2030 if (res_obj == NULL)
2031 return -1;
2032
2033 if (PyBool_Check(res_obj)) {
2034 res = (res_obj == Py_True);
2035 }
2036 else {
2037 res = PyObject_IsTrue(res_obj);
2038 }
2039 Py_DECREF(res_obj);
2040
2041 /* Note that we can't assert
2042 * res == PyObject_RichCompareBool(v, w, Py_LT);
2043 * because of evil compare functions like this:
2044 * lambda a, b: int(random.random() * 3) - 1)
2045 * (which is actually in test_sort.py) */
2046 return res;
2047}
2048
2049/* Latin string compare: safe for any two latin (one byte per char) strings. */
2050static int
2051unsafe_latin_compare(PyObject *v, PyObject *w, MergeState *ms)
2052{
Victor Stinner8017b802018-01-29 13:47:06 +01002053 Py_ssize_t len;
2054 int res;
embg1e34da42018-01-28 20:03:23 -07002055
2056 /* Modified from Objects/unicodeobject.c:unicode_compare, assuming: */
Andy Lesterdffe4c02020-03-04 07:15:20 -06002057 assert(Py_IS_TYPE(v, &PyUnicode_Type));
2058 assert(Py_IS_TYPE(w, &PyUnicode_Type));
embg1e34da42018-01-28 20:03:23 -07002059 assert(PyUnicode_KIND(v) == PyUnicode_KIND(w));
2060 assert(PyUnicode_KIND(v) == PyUnicode_1BYTE_KIND);
2061
2062 len = Py_MIN(PyUnicode_GET_LENGTH(v), PyUnicode_GET_LENGTH(w));
2063 res = memcmp(PyUnicode_DATA(v), PyUnicode_DATA(w), len);
2064
2065 res = (res != 0 ?
2066 res < 0 :
2067 PyUnicode_GET_LENGTH(v) < PyUnicode_GET_LENGTH(w));
2068
2069 assert(res == PyObject_RichCompareBool(v, w, Py_LT));;
2070 return res;
2071}
2072
2073/* Bounded int compare: compare any two longs that fit in a single machine word. */
2074static int
2075unsafe_long_compare(PyObject *v, PyObject *w, MergeState *ms)
2076{
2077 PyLongObject *vl, *wl; sdigit v0, w0; int res;
2078
2079 /* Modified from Objects/longobject.c:long_compare, assuming: */
Andy Lesterdffe4c02020-03-04 07:15:20 -06002080 assert(Py_IS_TYPE(v, &PyLong_Type));
2081 assert(Py_IS_TYPE(w, &PyLong_Type));
embg1e34da42018-01-28 20:03:23 -07002082 assert(Py_ABS(Py_SIZE(v)) <= 1);
2083 assert(Py_ABS(Py_SIZE(w)) <= 1);
2084
2085 vl = (PyLongObject*)v;
2086 wl = (PyLongObject*)w;
2087
2088 v0 = Py_SIZE(vl) == 0 ? 0 : (sdigit)vl->ob_digit[0];
2089 w0 = Py_SIZE(wl) == 0 ? 0 : (sdigit)wl->ob_digit[0];
2090
2091 if (Py_SIZE(vl) < 0)
2092 v0 = -v0;
2093 if (Py_SIZE(wl) < 0)
2094 w0 = -w0;
2095
2096 res = v0 < w0;
2097 assert(res == PyObject_RichCompareBool(v, w, Py_LT));
2098 return res;
2099}
2100
2101/* Float compare: compare any two floats. */
2102static int
2103unsafe_float_compare(PyObject *v, PyObject *w, MergeState *ms)
2104{
2105 int res;
2106
2107 /* Modified from Objects/floatobject.c:float_richcompare, assuming: */
Andy Lesterdffe4c02020-03-04 07:15:20 -06002108 assert(Py_IS_TYPE(v, &PyFloat_Type));
2109 assert(Py_IS_TYPE(w, &PyFloat_Type));
embg1e34da42018-01-28 20:03:23 -07002110
2111 res = PyFloat_AS_DOUBLE(v) < PyFloat_AS_DOUBLE(w);
2112 assert(res == PyObject_RichCompareBool(v, w, Py_LT));
2113 return res;
2114}
2115
2116/* Tuple compare: compare *any* two tuples, using
2117 * ms->tuple_elem_compare to compare the first elements, which is set
2118 * using the same pre-sort check as we use for ms->key_compare,
2119 * but run on the list [x[0] for x in L]. This allows us to optimize compares
2120 * on two levels (as long as [x[0] for x in L] is type-homogeneous.) The idea is
2121 * that most tuple compares don't involve x[1:]. */
2122static int
2123unsafe_tuple_compare(PyObject *v, PyObject *w, MergeState *ms)
2124{
2125 PyTupleObject *vt, *wt;
2126 Py_ssize_t i, vlen, wlen;
2127 int k;
2128
2129 /* Modified from Objects/tupleobject.c:tuplerichcompare, assuming: */
Andy Lesterdffe4c02020-03-04 07:15:20 -06002130 assert(Py_IS_TYPE(v, &PyTuple_Type));
2131 assert(Py_IS_TYPE(w, &PyTuple_Type));
embg1e34da42018-01-28 20:03:23 -07002132 assert(Py_SIZE(v) > 0);
2133 assert(Py_SIZE(w) > 0);
2134
2135 vt = (PyTupleObject *)v;
2136 wt = (PyTupleObject *)w;
2137
2138 vlen = Py_SIZE(vt);
2139 wlen = Py_SIZE(wt);
2140
2141 for (i = 0; i < vlen && i < wlen; i++) {
2142 k = PyObject_RichCompareBool(vt->ob_item[i], wt->ob_item[i], Py_EQ);
2143 if (k < 0)
2144 return -1;
2145 if (!k)
2146 break;
2147 }
2148
2149 if (i >= vlen || i >= wlen)
2150 return vlen < wlen;
2151
2152 if (i == 0)
2153 return ms->tuple_elem_compare(vt->ob_item[i], wt->ob_item[i], ms);
2154 else
2155 return PyObject_RichCompareBool(vt->ob_item[i], wt->ob_item[i], Py_LT);
2156}
2157
Tim Petersa64dc242002-08-01 02:13:36 +00002158/* An adaptive, stable, natural mergesort. See listsort.txt.
2159 * Returns Py_None on success, NULL on error. Even in case of error, the
2160 * list will be some permutation of its input state (nothing is lost or
2161 * duplicated).
2162 */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002163/*[clinic input]
2164list.sort
2165
2166 *
2167 key as keyfunc: object = None
Serhiy Storchaka202fda52017-03-12 10:10:47 +02002168 reverse: bool(accept={int}) = False
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002169
Tim Hoffmann5c224762019-06-01 06:10:02 +02002170Sort the list in ascending order and return None.
2171
2172The sort is in-place (i.e. the list itself is modified) and stable (i.e. the
2173order of two equal elements is maintained).
2174
2175If a key function is given, apply it once to each list item and sort them,
2176ascending or descending, according to their function values.
2177
2178The reverse flag can be set to sort in descending order.
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002179[clinic start generated code]*/
2180
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002181static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002182list_sort_impl(PyListObject *self, PyObject *keyfunc, int reverse)
Tim Hoffmann5c224762019-06-01 06:10:02 +02002183/*[clinic end generated code: output=57b9f9c5e23fbe42 input=cb56cd179a713060]*/
Guido van Rossum3f236de1996-12-10 23:55:39 +00002184{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002185 MergeState ms;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002186 Py_ssize_t nremaining;
2187 Py_ssize_t minrun;
Daniel Stutzbach98338222010-12-02 21:55:33 +00002188 sortslice lo;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002189 Py_ssize_t saved_ob_size, saved_allocated;
2190 PyObject **saved_ob_item;
2191 PyObject **final_ob_item;
2192 PyObject *result = NULL; /* guilty until proved innocent */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002193 Py_ssize_t i;
Daniel Stutzbach98338222010-12-02 21:55:33 +00002194 PyObject **keys;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002196 assert(self != NULL);
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002197 assert(PyList_Check(self));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002198 if (keyfunc == Py_None)
2199 keyfunc = NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002201 /* The list is temporarily made empty, so that mutations performed
2202 * by comparison functions can't affect the slice of memory we're
2203 * sorting (allowing mutations during sorting is a core-dump
2204 * factory, since ob_item may change).
2205 */
2206 saved_ob_size = Py_SIZE(self);
2207 saved_ob_item = self->ob_item;
2208 saved_allocated = self->allocated;
Victor Stinner60ac6ed2020-02-07 23:18:08 +01002209 Py_SET_SIZE(self, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002210 self->ob_item = NULL;
2211 self->allocated = -1; /* any operation will reset it to >= 0 */
Tim Peters330f9e92002-07-19 07:05:44 +00002212
Daniel Stutzbach98338222010-12-02 21:55:33 +00002213 if (keyfunc == NULL) {
2214 keys = NULL;
2215 lo.keys = saved_ob_item;
2216 lo.values = NULL;
2217 }
2218 else {
2219 if (saved_ob_size < MERGESTATE_TEMP_SIZE/2)
2220 /* Leverage stack space we allocated but won't otherwise use */
2221 keys = &ms.temparray[saved_ob_size+1];
2222 else {
2223 keys = PyMem_MALLOC(sizeof(PyObject *) * saved_ob_size);
Benjamin Peterson0823ffb2015-04-23 17:04:36 -04002224 if (keys == NULL) {
2225 PyErr_NoMemory();
2226 goto keyfunc_fail;
2227 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002228 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00002229
2230 for (i = 0; i < saved_ob_size ; i++) {
Petr Viktorinffd97532020-02-11 17:46:57 +01002231 keys[i] = PyObject_CallOneArg(keyfunc, saved_ob_item[i]);
Daniel Stutzbach98338222010-12-02 21:55:33 +00002232 if (keys[i] == NULL) {
2233 for (i=i-1 ; i>=0 ; i--)
2234 Py_DECREF(keys[i]);
Benjamin Peterson4a42cd42014-03-15 12:21:28 -05002235 if (saved_ob_size >= MERGESTATE_TEMP_SIZE/2)
Daniel Stutzbach8eda5f72011-03-02 23:37:50 +00002236 PyMem_FREE(keys);
Daniel Stutzbach98338222010-12-02 21:55:33 +00002237 goto keyfunc_fail;
2238 }
2239 }
2240
2241 lo.keys = keys;
2242 lo.values = saved_ob_item;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002243 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002244
embg1e34da42018-01-28 20:03:23 -07002245
2246 /* The pre-sort check: here's where we decide which compare function to use.
2247 * How much optimization is safe? We test for homogeneity with respect to
2248 * several properties that are expensive to check at compare-time, and
2249 * set ms appropriately. */
2250 if (saved_ob_size > 1) {
2251 /* Assume the first element is representative of the whole list. */
Andy Lesterdffe4c02020-03-04 07:15:20 -06002252 int keys_are_in_tuples = (Py_IS_TYPE(lo.keys[0], &PyTuple_Type) &&
embg1e34da42018-01-28 20:03:23 -07002253 Py_SIZE(lo.keys[0]) > 0);
2254
2255 PyTypeObject* key_type = (keys_are_in_tuples ?
Victor Stinner58ac7002020-02-07 03:04:21 +01002256 Py_TYPE(PyTuple_GET_ITEM(lo.keys[0], 0)) :
2257 Py_TYPE(lo.keys[0]));
embg1e34da42018-01-28 20:03:23 -07002258
2259 int keys_are_all_same_type = 1;
2260 int strings_are_latin = 1;
2261 int ints_are_bounded = 1;
2262
2263 /* Prove that assumption by checking every key. */
embg1e34da42018-01-28 20:03:23 -07002264 for (i=0; i < saved_ob_size; i++) {
2265
2266 if (keys_are_in_tuples &&
Andy Lesterdffe4c02020-03-04 07:15:20 -06002267 !(Py_IS_TYPE(lo.keys[i], &PyTuple_Type) && Py_SIZE(lo.keys[i]) != 0)) {
embg1e34da42018-01-28 20:03:23 -07002268 keys_are_in_tuples = 0;
2269 keys_are_all_same_type = 0;
2270 break;
2271 }
2272
2273 /* Note: for lists of tuples, key is the first element of the tuple
2274 * lo.keys[i], not lo.keys[i] itself! We verify type-homogeneity
2275 * for lists of tuples in the if-statement directly above. */
2276 PyObject *key = (keys_are_in_tuples ?
2277 PyTuple_GET_ITEM(lo.keys[i], 0) :
2278 lo.keys[i]);
2279
Andy Lesterdffe4c02020-03-04 07:15:20 -06002280 if (!Py_IS_TYPE(key, key_type)) {
embg1e34da42018-01-28 20:03:23 -07002281 keys_are_all_same_type = 0;
Rémi Lapeyredd5417a2019-03-25 08:25:37 +01002282 /* If keys are in tuple we must loop over the whole list to make
2283 sure all items are tuples */
2284 if (!keys_are_in_tuples) {
2285 break;
2286 }
embg1e34da42018-01-28 20:03:23 -07002287 }
2288
Rémi Lapeyredd5417a2019-03-25 08:25:37 +01002289 if (keys_are_all_same_type) {
2290 if (key_type == &PyLong_Type &&
2291 ints_are_bounded &&
2292 Py_ABS(Py_SIZE(key)) > 1) {
2293
embg1e34da42018-01-28 20:03:23 -07002294 ints_are_bounded = 0;
Rémi Lapeyredd5417a2019-03-25 08:25:37 +01002295 }
2296 else if (key_type == &PyUnicode_Type &&
2297 strings_are_latin &&
2298 PyUnicode_KIND(key) != PyUnicode_1BYTE_KIND) {
2299
2300 strings_are_latin = 0;
2301 }
2302 }
embg1e34da42018-01-28 20:03:23 -07002303 }
embg1e34da42018-01-28 20:03:23 -07002304
2305 /* Choose the best compare, given what we now know about the keys. */
2306 if (keys_are_all_same_type) {
2307
2308 if (key_type == &PyUnicode_Type && strings_are_latin) {
2309 ms.key_compare = unsafe_latin_compare;
2310 }
2311 else if (key_type == &PyLong_Type && ints_are_bounded) {
2312 ms.key_compare = unsafe_long_compare;
2313 }
2314 else if (key_type == &PyFloat_Type) {
2315 ms.key_compare = unsafe_float_compare;
2316 }
2317 else if ((ms.key_richcompare = key_type->tp_richcompare) != NULL) {
2318 ms.key_compare = unsafe_object_compare;
2319 }
Zackery Spytzebc793d2019-02-21 00:47:14 -07002320 else {
2321 ms.key_compare = safe_object_compare;
2322 }
embg1e34da42018-01-28 20:03:23 -07002323 }
2324 else {
2325 ms.key_compare = safe_object_compare;
2326 }
2327
2328 if (keys_are_in_tuples) {
2329 /* Make sure we're not dealing with tuples of tuples
2330 * (remember: here, key_type refers list [key[0] for key in keys]) */
Rémi Lapeyredd5417a2019-03-25 08:25:37 +01002331 if (key_type == &PyTuple_Type) {
embg1e34da42018-01-28 20:03:23 -07002332 ms.tuple_elem_compare = safe_object_compare;
Rémi Lapeyredd5417a2019-03-25 08:25:37 +01002333 }
2334 else {
embg1e34da42018-01-28 20:03:23 -07002335 ms.tuple_elem_compare = ms.key_compare;
Rémi Lapeyredd5417a2019-03-25 08:25:37 +01002336 }
embg1e34da42018-01-28 20:03:23 -07002337
2338 ms.key_compare = unsafe_tuple_compare;
2339 }
2340 }
2341 /* End of pre-sort check: ms is now set properly! */
2342
Daniel Stutzbach98338222010-12-02 21:55:33 +00002343 merge_init(&ms, saved_ob_size, keys != NULL);
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002345 nremaining = saved_ob_size;
2346 if (nremaining < 2)
2347 goto succeed;
Tim Peters330f9e92002-07-19 07:05:44 +00002348
Benjamin Peterson05380642010-08-23 19:35:39 +00002349 /* Reverse sort stability achieved by initially reversing the list,
2350 applying a stable forward sort, then reversing the final result. */
Daniel Stutzbach98338222010-12-02 21:55:33 +00002351 if (reverse) {
2352 if (keys != NULL)
2353 reverse_slice(&keys[0], &keys[saved_ob_size]);
2354 reverse_slice(&saved_ob_item[0], &saved_ob_item[saved_ob_size]);
2355 }
Benjamin Peterson05380642010-08-23 19:35:39 +00002356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002357 /* March over the array once, left to right, finding natural runs,
2358 * and extending short natural runs to minrun elements.
2359 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002360 minrun = merge_compute_minrun(nremaining);
2361 do {
2362 int descending;
2363 Py_ssize_t n;
Tim Peters330f9e92002-07-19 07:05:44 +00002364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002365 /* Identify next run. */
embg1e34da42018-01-28 20:03:23 -07002366 n = count_run(&ms, lo.keys, lo.keys + nremaining, &descending);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002367 if (n < 0)
2368 goto fail;
2369 if (descending)
Daniel Stutzbach98338222010-12-02 21:55:33 +00002370 reverse_sortslice(&lo, n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002371 /* If short, extend to min(minrun, nremaining). */
2372 if (n < minrun) {
2373 const Py_ssize_t force = nremaining <= minrun ?
2374 nremaining : minrun;
embg1e34da42018-01-28 20:03:23 -07002375 if (binarysort(&ms, lo, lo.keys + force, lo.keys + n) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002376 goto fail;
2377 n = force;
2378 }
2379 /* Push run onto pending-runs stack, and maybe merge. */
2380 assert(ms.n < MAX_MERGE_PENDING);
2381 ms.pending[ms.n].base = lo;
2382 ms.pending[ms.n].len = n;
2383 ++ms.n;
2384 if (merge_collapse(&ms) < 0)
2385 goto fail;
2386 /* Advance to find next run. */
Daniel Stutzbach98338222010-12-02 21:55:33 +00002387 sortslice_advance(&lo, n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002388 nremaining -= n;
2389 } while (nremaining);
Tim Peters330f9e92002-07-19 07:05:44 +00002390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002391 if (merge_force_collapse(&ms) < 0)
2392 goto fail;
2393 assert(ms.n == 1);
Daniel Stutzbach98338222010-12-02 21:55:33 +00002394 assert(keys == NULL
2395 ? ms.pending[0].base.keys == saved_ob_item
2396 : ms.pending[0].base.keys == &keys[0]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002397 assert(ms.pending[0].len == saved_ob_size);
Daniel Stutzbach98338222010-12-02 21:55:33 +00002398 lo = ms.pending[0].base;
Tim Petersa64dc242002-08-01 02:13:36 +00002399
2400succeed:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002401 result = Py_None;
Tim Peters330f9e92002-07-19 07:05:44 +00002402fail:
Daniel Stutzbach98338222010-12-02 21:55:33 +00002403 if (keys != NULL) {
2404 for (i = 0; i < saved_ob_size; i++)
2405 Py_DECREF(keys[i]);
Benjamin Petersonef87f8c2014-03-14 21:54:31 -05002406 if (saved_ob_size >= MERGESTATE_TEMP_SIZE/2)
Daniel Stutzbach98338222010-12-02 21:55:33 +00002407 PyMem_FREE(keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002408 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002410 if (self->allocated != -1 && result != NULL) {
2411 /* The user mucked with the list during the sort,
2412 * and we don't already have another error to report.
2413 */
2414 PyErr_SetString(PyExc_ValueError, "list modified during sort");
2415 result = NULL;
2416 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002418 if (reverse && saved_ob_size > 1)
2419 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002420
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002421 merge_freemem(&ms);
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002422
Daniel Stutzbach98338222010-12-02 21:55:33 +00002423keyfunc_fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002424 final_ob_item = self->ob_item;
2425 i = Py_SIZE(self);
Victor Stinner60ac6ed2020-02-07 23:18:08 +01002426 Py_SET_SIZE(self, saved_ob_size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002427 self->ob_item = saved_ob_item;
2428 self->allocated = saved_allocated;
2429 if (final_ob_item != NULL) {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002430 /* we cannot use _list_clear() for this because it does not
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002431 guarantee that the list is really empty when it returns */
2432 while (--i >= 0) {
2433 Py_XDECREF(final_ob_item[i]);
2434 }
2435 PyMem_FREE(final_ob_item);
2436 }
2437 Py_XINCREF(result);
2438 return result;
Guido van Rossum3f236de1996-12-10 23:55:39 +00002439}
Tim Peters330f9e92002-07-19 07:05:44 +00002440#undef IFLT
Tim Peters66860f62002-08-04 17:47:26 +00002441#undef ISLT
Tim Peters330f9e92002-07-19 07:05:44 +00002442
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002443int
Fred Drakea2f55112000-07-09 15:16:51 +00002444PyList_Sort(PyObject *v)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002445{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002446 if (v == NULL || !PyList_Check(v)) {
2447 PyErr_BadInternalCall();
2448 return -1;
2449 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002450 v = list_sort_impl((PyListObject *)v, NULL, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002451 if (v == NULL)
2452 return -1;
2453 Py_DECREF(v);
2454 return 0;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002455}
2456
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002457/*[clinic input]
2458list.reverse
2459
2460Reverse *IN PLACE*.
2461[clinic start generated code]*/
2462
Guido van Rossumb86c5492001-02-12 22:06:02 +00002463static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002464list_reverse_impl(PyListObject *self)
2465/*[clinic end generated code: output=482544fc451abea9 input=eefd4c3ae1bc9887]*/
Guido van Rossumb86c5492001-02-12 22:06:02 +00002466{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002467 if (Py_SIZE(self) > 1)
2468 reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
2469 Py_RETURN_NONE;
Guido van Rossumed98d481991-03-06 13:07:53 +00002470}
2471
Guido van Rossum84c76f51990-10-30 13:32:20 +00002472int
Fred Drakea2f55112000-07-09 15:16:51 +00002473PyList_Reverse(PyObject *v)
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002474{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002475 PyListObject *self = (PyListObject *)v;
Tim Peters6063e262002-08-08 01:06:39 +00002476
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002477 if (v == NULL || !PyList_Check(v)) {
2478 PyErr_BadInternalCall();
2479 return -1;
2480 }
2481 if (Py_SIZE(self) > 1)
2482 reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
2483 return 0;
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002484}
2485
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002486PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00002487PyList_AsTuple(PyObject *v)
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002488{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002489 if (v == NULL || !PyList_Check(v)) {
2490 PyErr_BadInternalCall();
2491 return NULL;
2492 }
Sergey Fedoseev234531b2019-02-25 21:59:12 +05002493 return _PyTuple_FromArray(((PyListObject *)v)->ob_item, Py_SIZE(v));
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002494}
2495
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002496/*[clinic input]
2497list.index
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002498
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002499 value: object
Serhiy Storchaka80ec8362017-03-19 19:37:40 +02002500 start: slice_index(accept={int}) = 0
2501 stop: slice_index(accept={int}, c_default="PY_SSIZE_T_MAX") = sys.maxsize
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002502 /
2503
2504Return first index of value.
2505
2506Raises ValueError if the value is not present.
2507[clinic start generated code]*/
2508
2509static PyObject *
2510list_index_impl(PyListObject *self, PyObject *value, Py_ssize_t start,
2511 Py_ssize_t stop)
Serhiy Storchaka80ec8362017-03-19 19:37:40 +02002512/*[clinic end generated code: output=ec51b88787e4e481 input=40ec5826303a0eb1]*/
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002513{
2514 Py_ssize_t i;
2515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002516 if (start < 0) {
2517 start += Py_SIZE(self);
2518 if (start < 0)
2519 start = 0;
2520 }
2521 if (stop < 0) {
2522 stop += Py_SIZE(self);
2523 if (stop < 0)
2524 stop = 0;
2525 }
2526 for (i = start; i < stop && i < Py_SIZE(self); i++) {
Zackery Spytzd9e561d2019-12-30 12:32:58 -07002527 PyObject *obj = self->ob_item[i];
2528 Py_INCREF(obj);
2529 int cmp = PyObject_RichCompareBool(obj, value, Py_EQ);
2530 Py_DECREF(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002531 if (cmp > 0)
2532 return PyLong_FromSsize_t(i);
2533 else if (cmp < 0)
2534 return NULL;
2535 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002536 PyErr_Format(PyExc_ValueError, "%R is not in list", value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002537 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002538}
2539
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002540/*[clinic input]
2541list.count
2542
2543 value: object
2544 /
2545
2546Return number of occurrences of value.
2547[clinic start generated code]*/
2548
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002549static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002550list_count(PyListObject *self, PyObject *value)
2551/*[clinic end generated code: output=b1f5d284205ae714 input=3bdc3a5e6f749565]*/
Guido van Rossume6f7d181991-10-20 20:20:40 +00002552{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002553 Py_ssize_t count = 0;
2554 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002556 for (i = 0; i < Py_SIZE(self); i++) {
Zackery Spytzd9e561d2019-12-30 12:32:58 -07002557 PyObject *obj = self->ob_item[i];
Dong-hee Na14d80d02020-01-23 02:36:54 +09002558 if (obj == value) {
2559 count++;
2560 continue;
2561 }
Zackery Spytzd9e561d2019-12-30 12:32:58 -07002562 Py_INCREF(obj);
2563 int cmp = PyObject_RichCompareBool(obj, value, Py_EQ);
2564 Py_DECREF(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002565 if (cmp > 0)
2566 count++;
2567 else if (cmp < 0)
2568 return NULL;
2569 }
2570 return PyLong_FromSsize_t(count);
Guido van Rossume6f7d181991-10-20 20:20:40 +00002571}
2572
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002573/*[clinic input]
2574list.remove
2575
2576 value: object
2577 /
2578
2579Remove first occurrence of value.
2580
2581Raises ValueError if the value is not present.
2582[clinic start generated code]*/
2583
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002584static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002585list_remove(PyListObject *self, PyObject *value)
2586/*[clinic end generated code: output=f087e1951a5e30d1 input=2dc2ba5bb2fb1f82]*/
Guido van Rossumed98d481991-03-06 13:07:53 +00002587{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002588 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002590 for (i = 0; i < Py_SIZE(self); i++) {
Zackery Spytzd9e561d2019-12-30 12:32:58 -07002591 PyObject *obj = self->ob_item[i];
2592 Py_INCREF(obj);
2593 int cmp = PyObject_RichCompareBool(obj, value, Py_EQ);
2594 Py_DECREF(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002595 if (cmp > 0) {
2596 if (list_ass_slice(self, i, i+1,
2597 (PyObject *)NULL) == 0)
2598 Py_RETURN_NONE;
2599 return NULL;
2600 }
2601 else if (cmp < 0)
2602 return NULL;
2603 }
2604 PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
2605 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002606}
2607
Jeremy Hylton8caad492000-06-23 14:18:11 +00002608static int
2609list_traverse(PyListObject *o, visitproc visit, void *arg)
2610{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002611 Py_ssize_t i;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002613 for (i = Py_SIZE(o); --i >= 0; )
2614 Py_VISIT(o->ob_item[i]);
2615 return 0;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002616}
2617
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002618static PyObject *
2619list_richcompare(PyObject *v, PyObject *w, int op)
2620{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002621 PyListObject *vl, *wl;
2622 Py_ssize_t i;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002623
Brian Curtindfc80e32011-08-10 20:28:54 -05002624 if (!PyList_Check(v) || !PyList_Check(w))
2625 Py_RETURN_NOTIMPLEMENTED;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002626
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002627 vl = (PyListObject *)v;
2628 wl = (PyListObject *)w;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002630 if (Py_SIZE(vl) != Py_SIZE(wl) && (op == Py_EQ || op == Py_NE)) {
2631 /* Shortcut: if the lengths differ, the lists differ */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002632 if (op == Py_EQ)
stratakise8b19652017-11-02 11:32:54 +01002633 Py_RETURN_FALSE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002634 else
stratakise8b19652017-11-02 11:32:54 +01002635 Py_RETURN_TRUE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002636 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002637
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002638 /* Search for the first index where items are different */
2639 for (i = 0; i < Py_SIZE(vl) && i < Py_SIZE(wl); i++) {
Dong-hee Na2d5bf562019-12-31 10:04:22 +09002640 PyObject *vitem = vl->ob_item[i];
2641 PyObject *witem = wl->ob_item[i];
Inada Naokidfef9862019-12-31 10:58:37 +09002642 if (vitem == witem) {
2643 continue;
2644 }
Dong-hee Na2d5bf562019-12-31 10:04:22 +09002645
2646 Py_INCREF(vitem);
2647 Py_INCREF(witem);
sweeneydebe7ead62020-02-26 02:00:35 -05002648 int k = PyObject_RichCompareBool(vitem, witem, Py_EQ);
Dong-hee Na2d5bf562019-12-31 10:04:22 +09002649 Py_DECREF(vitem);
2650 Py_DECREF(witem);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002651 if (k < 0)
2652 return NULL;
2653 if (!k)
2654 break;
2655 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002657 if (i >= Py_SIZE(vl) || i >= Py_SIZE(wl)) {
2658 /* No more items to compare -- compare sizes */
stratakise8b19652017-11-02 11:32:54 +01002659 Py_RETURN_RICHCOMPARE(Py_SIZE(vl), Py_SIZE(wl), op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002660 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002661
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002662 /* We have an item that differs -- shortcuts for EQ/NE */
2663 if (op == Py_EQ) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02002664 Py_RETURN_FALSE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002665 }
2666 if (op == Py_NE) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02002667 Py_RETURN_TRUE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002668 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002670 /* Compare the final item again using the proper operator */
2671 return PyObject_RichCompare(vl->ob_item[i], wl->ob_item[i], op);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002672}
2673
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002674/*[clinic input]
2675list.__init__
2676
2677 iterable: object(c_default="NULL") = ()
2678 /
2679
2680Built-in mutable sequence.
2681
2682If no argument is given, the constructor creates a new empty list.
2683The argument must be an iterable if specified.
2684[clinic start generated code]*/
2685
Tim Peters6d6c1a32001-08-02 04:15:00 +00002686static int
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002687list___init___impl(PyListObject *self, PyObject *iterable)
2688/*[clinic end generated code: output=0f3c21379d01de48 input=b3f3fe7206af8f6b]*/
Tim Peters6d6c1a32001-08-02 04:15:00 +00002689{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002690 /* Verify list invariants established by PyType_GenericAlloc() */
2691 assert(0 <= Py_SIZE(self));
2692 assert(Py_SIZE(self) <= self->allocated || self->allocated == -1);
2693 assert(self->ob_item != NULL ||
2694 self->allocated == 0 || self->allocated == -1);
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002695
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002696 /* Empty previous contents */
2697 if (self->ob_item != NULL) {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002698 (void)_list_clear(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002699 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002700 if (iterable != NULL) {
Pablo Galindo372d7052018-10-28 20:16:26 +00002701 if (_PyObject_HasLen(iterable)) {
2702 Py_ssize_t iter_len = PyObject_Size(iterable);
2703 if (iter_len == -1) {
2704 if (!PyErr_ExceptionMatches(PyExc_TypeError)) {
2705 return -1;
2706 }
2707 PyErr_Clear();
2708 }
2709 if (iter_len > 0 && self->ob_item == NULL
2710 && list_preallocate_exact(self, iter_len)) {
2711 return -1;
2712 }
2713 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002714 PyObject *rv = list_extend(self, iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002715 if (rv == NULL)
2716 return -1;
2717 Py_DECREF(rv);
2718 }
2719 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002720}
2721
Petr Viktorince105542020-03-30 14:16:16 +02002722static PyObject *
2723list_vectorcall(PyObject *type, PyObject * const*args,
2724 size_t nargsf, PyObject *kwnames)
2725{
2726 if (!_PyArg_NoKwnames("list", kwnames)) {
2727 return NULL;
2728 }
2729 Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
2730 if (!_PyArg_CheckPositional("list", nargs, 0, 1)) {
2731 return NULL;
2732 }
2733
2734 assert(PyType_Check(type));
2735 PyObject *list = PyType_GenericAlloc((PyTypeObject *)type, 0);
2736 if (list == NULL) {
2737 return NULL;
2738 }
2739 if (nargs) {
2740 if (list___init___impl((PyListObject *)list, args[0])) {
2741 Py_DECREF(list);
2742 return NULL;
2743 }
2744 }
2745 return list;
2746}
2747
2748
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002749/*[clinic input]
2750list.__sizeof__
2751
2752Return the size of the list in memory, in bytes.
2753[clinic start generated code]*/
2754
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002755static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002756list___sizeof___impl(PyListObject *self)
2757/*[clinic end generated code: output=3417541f95f9a53e input=b8030a5d5ce8a187]*/
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002758{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002759 Py_ssize_t res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002760
Serhiy Storchaka5c4064e2015-12-19 20:05:25 +02002761 res = _PyObject_SIZE(Py_TYPE(self)) + self->allocated * sizeof(void*);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002762 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002763}
2764
Raymond Hettinger1021c442003-11-07 15:38:09 +00002765static PyObject *list_iter(PyObject *seq);
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002766static PyObject *list_subscript(PyListObject*, PyObject*);
2767
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002768static PyMethodDef list_methods[] = {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002769 {"__getitem__", (PyCFunction)list_subscript, METH_O|METH_COEXIST, "x.__getitem__(y) <==> x[y]"},
2770 LIST___REVERSED___METHODDEF
2771 LIST___SIZEOF___METHODDEF
2772 LIST_CLEAR_METHODDEF
2773 LIST_COPY_METHODDEF
2774 LIST_APPEND_METHODDEF
2775 LIST_INSERT_METHODDEF
2776 LIST_EXTEND_METHODDEF
2777 LIST_POP_METHODDEF
2778 LIST_REMOVE_METHODDEF
2779 LIST_INDEX_METHODDEF
2780 LIST_COUNT_METHODDEF
2781 LIST_REVERSE_METHODDEF
2782 LIST_SORT_METHODDEF
Guido van Rossum48b069a2020-04-07 09:50:06 -07002783 {"__class_getitem__", (PyCFunction)Py_GenericAlias, METH_O|METH_CLASS, PyDoc_STR("See PEP 585")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002784 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002785};
2786
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002787static PySequenceMethods list_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002788 (lenfunc)list_length, /* sq_length */
2789 (binaryfunc)list_concat, /* sq_concat */
2790 (ssizeargfunc)list_repeat, /* sq_repeat */
2791 (ssizeargfunc)list_item, /* sq_item */
2792 0, /* sq_slice */
2793 (ssizeobjargproc)list_ass_item, /* sq_ass_item */
2794 0, /* sq_ass_slice */
2795 (objobjproc)list_contains, /* sq_contains */
2796 (binaryfunc)list_inplace_concat, /* sq_inplace_concat */
2797 (ssizeargfunc)list_inplace_repeat, /* sq_inplace_repeat */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002798};
2799
Jeremy Hyltona4b4c3b2002-07-13 03:51:17 +00002800static PyObject *
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002801list_subscript(PyListObject* self, PyObject* item)
2802{
Victor Stinnera15e2602020-04-08 02:01:56 +02002803 if (_PyIndex_Check(item)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002804 Py_ssize_t i;
2805 i = PyNumber_AsSsize_t(item, PyExc_IndexError);
2806 if (i == -1 && PyErr_Occurred())
2807 return NULL;
2808 if (i < 0)
2809 i += PyList_GET_SIZE(self);
2810 return list_item(self, i);
2811 }
2812 else if (PySlice_Check(item)) {
HongWeipeng3c87a662019-09-08 18:15:56 +08002813 Py_ssize_t start, stop, step, slicelength, i;
2814 size_t cur;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002815 PyObject* result;
2816 PyObject* it;
2817 PyObject **src, **dest;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002818
Serhiy Storchakab879fe82017-04-08 09:53:51 +03002819 if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002820 return NULL;
2821 }
Serhiy Storchakab879fe82017-04-08 09:53:51 +03002822 slicelength = PySlice_AdjustIndices(Py_SIZE(self), &start, &stop,
2823 step);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002824
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002825 if (slicelength <= 0) {
2826 return PyList_New(0);
2827 }
2828 else if (step == 1) {
2829 return list_slice(self, start, stop);
2830 }
2831 else {
Sergey Fedoseev2fc46972018-08-11 18:12:07 +05002832 result = list_new_prealloc(slicelength);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002833 if (!result) return NULL;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002834
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002835 src = self->ob_item;
2836 dest = ((PyListObject *)result)->ob_item;
2837 for (cur = start, i = 0; i < slicelength;
Mark Dickinsonc7d93b72011-09-25 15:34:32 +01002838 cur += (size_t)step, i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002839 it = src[cur];
2840 Py_INCREF(it);
2841 dest[i] = it;
2842 }
Victor Stinner60ac6ed2020-02-07 23:18:08 +01002843 Py_SET_SIZE(result, slicelength);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002844 return result;
2845 }
2846 }
2847 else {
2848 PyErr_Format(PyExc_TypeError,
Terry Jan Reedyffff1442014-08-02 01:30:37 -04002849 "list indices must be integers or slices, not %.200s",
Victor Stinner58ac7002020-02-07 03:04:21 +01002850 Py_TYPE(item)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002851 return NULL;
2852 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002853}
2854
Tim Peters3b01a122002-07-19 02:35:45 +00002855static int
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002856list_ass_subscript(PyListObject* self, PyObject* item, PyObject* value)
2857{
Victor Stinnera15e2602020-04-08 02:01:56 +02002858 if (_PyIndex_Check(item)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002859 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
2860 if (i == -1 && PyErr_Occurred())
2861 return -1;
2862 if (i < 0)
2863 i += PyList_GET_SIZE(self);
2864 return list_ass_item(self, i, value);
2865 }
2866 else if (PySlice_Check(item)) {
2867 Py_ssize_t start, stop, step, slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002868
Serhiy Storchakab879fe82017-04-08 09:53:51 +03002869 if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002870 return -1;
2871 }
Serhiy Storchakab879fe82017-04-08 09:53:51 +03002872 slicelength = PySlice_AdjustIndices(Py_SIZE(self), &start, &stop,
2873 step);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002874
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002875 if (step == 1)
2876 return list_ass_slice(self, start, stop, value);
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002878 /* Make sure s[5:2] = [..] inserts at the right place:
2879 before 5, not before 2. */
2880 if ((step < 0 && start < stop) ||
2881 (step > 0 && start > stop))
2882 stop = start;
Thomas Woutersed03b412007-08-28 21:37:11 +00002883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002884 if (value == NULL) {
2885 /* delete slice */
2886 PyObject **garbage;
2887 size_t cur;
2888 Py_ssize_t i;
Victor Stinner35f28032013-11-21 12:16:35 +01002889 int res;
Tim Peters3b01a122002-07-19 02:35:45 +00002890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002891 if (slicelength <= 0)
2892 return 0;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002894 if (step < 0) {
2895 stop = start + 1;
2896 start = stop + step*(slicelength - 1) - 1;
2897 step = -step;
2898 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002899
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002900 garbage = (PyObject**)
2901 PyMem_MALLOC(slicelength*sizeof(PyObject*));
2902 if (!garbage) {
2903 PyErr_NoMemory();
2904 return -1;
2905 }
Tim Peters3b01a122002-07-19 02:35:45 +00002906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002907 /* drawing pictures might help understand these for
2908 loops. Basically, we memmove the parts of the
2909 list that are *not* part of the slice: step-1
2910 items for each item that is part of the slice,
2911 and then tail end of the list that was not
2912 covered by the slice */
2913 for (cur = start, i = 0;
2914 cur < (size_t)stop;
2915 cur += step, i++) {
2916 Py_ssize_t lim = step - 1;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002918 garbage[i] = PyList_GET_ITEM(self, cur);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002920 if (cur + step >= (size_t)Py_SIZE(self)) {
2921 lim = Py_SIZE(self) - cur - 1;
2922 }
Michael W. Hudson56796f62002-07-29 14:35:04 +00002923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002924 memmove(self->ob_item + cur - i,
2925 self->ob_item + cur + 1,
2926 lim * sizeof(PyObject *));
2927 }
Mark Dickinsonc7d93b72011-09-25 15:34:32 +01002928 cur = start + (size_t)slicelength * step;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002929 if (cur < (size_t)Py_SIZE(self)) {
2930 memmove(self->ob_item + cur - slicelength,
2931 self->ob_item + cur,
2932 (Py_SIZE(self) - cur) *
2933 sizeof(PyObject *));
2934 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002935
Victor Stinner60ac6ed2020-02-07 23:18:08 +01002936 Py_SET_SIZE(self, Py_SIZE(self) - slicelength);
Victor Stinner35f28032013-11-21 12:16:35 +01002937 res = list_resize(self, Py_SIZE(self));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002938
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002939 for (i = 0; i < slicelength; i++) {
2940 Py_DECREF(garbage[i]);
2941 }
2942 PyMem_FREE(garbage);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002943
Victor Stinner35f28032013-11-21 12:16:35 +01002944 return res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002945 }
2946 else {
2947 /* assign slice */
2948 PyObject *ins, *seq;
2949 PyObject **garbage, **seqitems, **selfitems;
HongWeipeng3c87a662019-09-08 18:15:56 +08002950 Py_ssize_t i;
2951 size_t cur;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002953 /* protect against a[::-1] = a */
2954 if (self == (PyListObject*)value) {
2955 seq = list_slice((PyListObject*)value, 0,
2956 PyList_GET_SIZE(value));
2957 }
2958 else {
2959 seq = PySequence_Fast(value,
2960 "must assign iterable "
2961 "to extended slice");
2962 }
2963 if (!seq)
2964 return -1;
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002965
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002966 if (PySequence_Fast_GET_SIZE(seq) != slicelength) {
2967 PyErr_Format(PyExc_ValueError,
2968 "attempt to assign sequence of "
2969 "size %zd to extended slice of "
2970 "size %zd",
2971 PySequence_Fast_GET_SIZE(seq),
2972 slicelength);
2973 Py_DECREF(seq);
2974 return -1;
2975 }
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002977 if (!slicelength) {
2978 Py_DECREF(seq);
2979 return 0;
2980 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002982 garbage = (PyObject**)
2983 PyMem_MALLOC(slicelength*sizeof(PyObject*));
2984 if (!garbage) {
2985 Py_DECREF(seq);
2986 PyErr_NoMemory();
2987 return -1;
2988 }
Tim Peters3b01a122002-07-19 02:35:45 +00002989
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002990 selfitems = self->ob_item;
2991 seqitems = PySequence_Fast_ITEMS(seq);
2992 for (cur = start, i = 0; i < slicelength;
Mark Dickinsonc7d93b72011-09-25 15:34:32 +01002993 cur += (size_t)step, i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002994 garbage[i] = selfitems[cur];
2995 ins = seqitems[i];
2996 Py_INCREF(ins);
2997 selfitems[cur] = ins;
2998 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003000 for (i = 0; i < slicelength; i++) {
3001 Py_DECREF(garbage[i]);
3002 }
Tim Peters3b01a122002-07-19 02:35:45 +00003003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003004 PyMem_FREE(garbage);
3005 Py_DECREF(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00003006
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003007 return 0;
3008 }
3009 }
3010 else {
3011 PyErr_Format(PyExc_TypeError,
Terry Jan Reedyffff1442014-08-02 01:30:37 -04003012 "list indices must be integers or slices, not %.200s",
Victor Stinner58ac7002020-02-07 03:04:21 +01003013 Py_TYPE(item)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003014 return -1;
3015 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00003016}
3017
3018static PyMappingMethods list_as_mapping = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003019 (lenfunc)list_length,
3020 (binaryfunc)list_subscript,
3021 (objobjargproc)list_ass_subscript
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00003022};
3023
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003024PyTypeObject PyList_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003025 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3026 "list",
3027 sizeof(PyListObject),
3028 0,
3029 (destructor)list_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003030 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003031 0, /* tp_getattr */
3032 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003033 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003034 (reprfunc)list_repr, /* tp_repr */
3035 0, /* tp_as_number */
3036 &list_as_sequence, /* tp_as_sequence */
3037 &list_as_mapping, /* tp_as_mapping */
Georg Brandl00da4e02010-10-18 07:32:48 +00003038 PyObject_HashNotImplemented, /* tp_hash */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003039 0, /* tp_call */
3040 0, /* tp_str */
3041 PyObject_GenericGetAttr, /* tp_getattro */
3042 0, /* tp_setattro */
3043 0, /* tp_as_buffer */
3044 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02003045 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LIST_SUBCLASS, /* tp_flags */
3046 list___init____doc__, /* tp_doc */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003047 (traverseproc)list_traverse, /* tp_traverse */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02003048 (inquiry)_list_clear, /* tp_clear */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003049 list_richcompare, /* tp_richcompare */
3050 0, /* tp_weaklistoffset */
3051 list_iter, /* tp_iter */
3052 0, /* tp_iternext */
3053 list_methods, /* tp_methods */
3054 0, /* tp_members */
3055 0, /* tp_getset */
3056 0, /* tp_base */
3057 0, /* tp_dict */
3058 0, /* tp_descr_get */
3059 0, /* tp_descr_set */
3060 0, /* tp_dictoffset */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02003061 (initproc)list___init__, /* tp_init */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003062 PyType_GenericAlloc, /* tp_alloc */
3063 PyType_GenericNew, /* tp_new */
3064 PyObject_GC_Del, /* tp_free */
Petr Viktorince105542020-03-30 14:16:16 +02003065 .tp_vectorcall = list_vectorcall,
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003066};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00003067
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00003068/*********************** List Iterator **************************/
3069
3070typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003071 PyObject_HEAD
Victor Stinner7660b882013-06-24 23:59:24 +02003072 Py_ssize_t it_index;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003073 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00003074} listiterobject;
3075
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003076static void listiter_dealloc(listiterobject *);
3077static int listiter_traverse(listiterobject *, visitproc, void *);
3078static PyObject *listiter_next(listiterobject *);
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303079static PyObject *listiter_len(listiterobject *, PyObject *);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003080static PyObject *listiter_reduce_general(void *_it, int forward);
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303081static PyObject *listiter_reduce(listiterobject *, PyObject *);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003082static PyObject *listiter_setstate(listiterobject *, PyObject *state);
Raymond Hettinger435bf582004-03-18 22:43:10 +00003083
Armin Rigof5b3e362006-02-11 21:32:43 +00003084PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003085PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
3086PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00003087
3088static PyMethodDef listiter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003089 {"__length_hint__", (PyCFunction)listiter_len, METH_NOARGS, length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003090 {"__reduce__", (PyCFunction)listiter_reduce, METH_NOARGS, reduce_doc},
3091 {"__setstate__", (PyCFunction)listiter_setstate, METH_O, setstate_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003092 {NULL, NULL} /* sentinel */
Raymond Hettinger435bf582004-03-18 22:43:10 +00003093};
3094
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00003095PyTypeObject PyListIter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003096 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3097 "list_iterator", /* tp_name */
3098 sizeof(listiterobject), /* tp_basicsize */
3099 0, /* tp_itemsize */
3100 /* methods */
3101 (destructor)listiter_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003102 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003103 0, /* tp_getattr */
3104 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003105 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003106 0, /* tp_repr */
3107 0, /* tp_as_number */
3108 0, /* tp_as_sequence */
3109 0, /* tp_as_mapping */
3110 0, /* tp_hash */
3111 0, /* tp_call */
3112 0, /* tp_str */
3113 PyObject_GenericGetAttr, /* tp_getattro */
3114 0, /* tp_setattro */
3115 0, /* tp_as_buffer */
3116 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3117 0, /* tp_doc */
3118 (traverseproc)listiter_traverse, /* tp_traverse */
3119 0, /* tp_clear */
3120 0, /* tp_richcompare */
3121 0, /* tp_weaklistoffset */
3122 PyObject_SelfIter, /* tp_iter */
3123 (iternextfunc)listiter_next, /* tp_iternext */
3124 listiter_methods, /* tp_methods */
3125 0, /* tp_members */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00003126};
Raymond Hettinger1021c442003-11-07 15:38:09 +00003127
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003128
3129static PyObject *
3130list_iter(PyObject *seq)
3131{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003132 listiterobject *it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003133
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003134 if (!PyList_Check(seq)) {
3135 PyErr_BadInternalCall();
3136 return NULL;
3137 }
3138 it = PyObject_GC_New(listiterobject, &PyListIter_Type);
3139 if (it == NULL)
3140 return NULL;
3141 it->it_index = 0;
3142 Py_INCREF(seq);
3143 it->it_seq = (PyListObject *)seq;
3144 _PyObject_GC_TRACK(it);
3145 return (PyObject *)it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003146}
3147
3148static void
3149listiter_dealloc(listiterobject *it)
3150{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003151 _PyObject_GC_UNTRACK(it);
3152 Py_XDECREF(it->it_seq);
3153 PyObject_GC_Del(it);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003154}
3155
3156static int
3157listiter_traverse(listiterobject *it, visitproc visit, void *arg)
3158{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003159 Py_VISIT(it->it_seq);
3160 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003161}
3162
3163static PyObject *
3164listiter_next(listiterobject *it)
3165{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003166 PyListObject *seq;
3167 PyObject *item;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003169 assert(it != NULL);
3170 seq = it->it_seq;
3171 if (seq == NULL)
3172 return NULL;
3173 assert(PyList_Check(seq));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003175 if (it->it_index < PyList_GET_SIZE(seq)) {
3176 item = PyList_GET_ITEM(seq, it->it_index);
3177 ++it->it_index;
3178 Py_INCREF(item);
3179 return item;
3180 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003182 it->it_seq = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003183 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003184 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003185}
3186
3187static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303188listiter_len(listiterobject *it, PyObject *Py_UNUSED(ignored))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003189{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003190 Py_ssize_t len;
3191 if (it->it_seq) {
3192 len = PyList_GET_SIZE(it->it_seq) - it->it_index;
3193 if (len >= 0)
3194 return PyLong_FromSsize_t(len);
3195 }
3196 return PyLong_FromLong(0);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003197}
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003198
3199static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303200listiter_reduce(listiterobject *it, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003201{
3202 return listiter_reduce_general(it, 1);
3203}
3204
3205static PyObject *
3206listiter_setstate(listiterobject *it, PyObject *state)
3207{
Victor Stinner7660b882013-06-24 23:59:24 +02003208 Py_ssize_t index = PyLong_AsSsize_t(state);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003209 if (index == -1 && PyErr_Occurred())
3210 return NULL;
3211 if (it->it_seq != NULL) {
3212 if (index < 0)
3213 index = 0;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +00003214 else if (index > PyList_GET_SIZE(it->it_seq))
3215 index = PyList_GET_SIZE(it->it_seq); /* iterator exhausted */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003216 it->it_index = index;
3217 }
3218 Py_RETURN_NONE;
3219}
3220
Raymond Hettinger1021c442003-11-07 15:38:09 +00003221/*********************** List Reverse Iterator **************************/
3222
3223typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003224 PyObject_HEAD
3225 Py_ssize_t it_index;
3226 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger1021c442003-11-07 15:38:09 +00003227} listreviterobject;
3228
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003229static void listreviter_dealloc(listreviterobject *);
3230static int listreviter_traverse(listreviterobject *, visitproc, void *);
3231static PyObject *listreviter_next(listreviterobject *);
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303232static PyObject *listreviter_len(listreviterobject *, PyObject *);
3233static PyObject *listreviter_reduce(listreviterobject *, PyObject *);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003234static PyObject *listreviter_setstate(listreviterobject *, PyObject *);
Raymond Hettingeref9bf402004-03-10 10:10:42 +00003235
Raymond Hettingerf5b64112008-12-02 21:33:45 +00003236static PyMethodDef listreviter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003237 {"__length_hint__", (PyCFunction)listreviter_len, METH_NOARGS, length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003238 {"__reduce__", (PyCFunction)listreviter_reduce, METH_NOARGS, reduce_doc},
3239 {"__setstate__", (PyCFunction)listreviter_setstate, METH_O, setstate_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003240 {NULL, NULL} /* sentinel */
Raymond Hettingeref9bf402004-03-10 10:10:42 +00003241};
3242
Raymond Hettinger1021c442003-11-07 15:38:09 +00003243PyTypeObject PyListRevIter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003244 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3245 "list_reverseiterator", /* tp_name */
3246 sizeof(listreviterobject), /* tp_basicsize */
3247 0, /* tp_itemsize */
3248 /* methods */
3249 (destructor)listreviter_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003250 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003251 0, /* tp_getattr */
3252 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003253 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003254 0, /* tp_repr */
3255 0, /* tp_as_number */
3256 0, /* tp_as_sequence */
3257 0, /* tp_as_mapping */
3258 0, /* tp_hash */
3259 0, /* tp_call */
3260 0, /* tp_str */
3261 PyObject_GenericGetAttr, /* tp_getattro */
3262 0, /* tp_setattro */
3263 0, /* tp_as_buffer */
3264 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3265 0, /* tp_doc */
3266 (traverseproc)listreviter_traverse, /* tp_traverse */
3267 0, /* tp_clear */
3268 0, /* tp_richcompare */
3269 0, /* tp_weaklistoffset */
3270 PyObject_SelfIter, /* tp_iter */
3271 (iternextfunc)listreviter_next, /* tp_iternext */
3272 listreviter_methods, /* tp_methods */
3273 0,
Raymond Hettinger1021c442003-11-07 15:38:09 +00003274};
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003275
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02003276/*[clinic input]
3277list.__reversed__
3278
3279Return a reverse iterator over the list.
3280[clinic start generated code]*/
3281
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003282static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02003283list___reversed___impl(PyListObject *self)
3284/*[clinic end generated code: output=b166f073208c888c input=eadb6e17f8a6a280]*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003285{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003286 listreviterobject *it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003288 it = PyObject_GC_New(listreviterobject, &PyListRevIter_Type);
3289 if (it == NULL)
3290 return NULL;
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02003291 assert(PyList_Check(self));
3292 it->it_index = PyList_GET_SIZE(self) - 1;
3293 Py_INCREF(self);
3294 it->it_seq = self;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003295 PyObject_GC_Track(it);
3296 return (PyObject *)it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003297}
3298
3299static void
3300listreviter_dealloc(listreviterobject *it)
3301{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003302 PyObject_GC_UnTrack(it);
3303 Py_XDECREF(it->it_seq);
3304 PyObject_GC_Del(it);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003305}
3306
3307static int
3308listreviter_traverse(listreviterobject *it, visitproc visit, void *arg)
3309{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003310 Py_VISIT(it->it_seq);
3311 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003312}
3313
3314static PyObject *
3315listreviter_next(listreviterobject *it)
3316{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003317 PyObject *item;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003318 Py_ssize_t index;
3319 PyListObject *seq;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003320
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003321 assert(it != NULL);
3322 seq = it->it_seq;
3323 if (seq == NULL) {
3324 return NULL;
3325 }
3326 assert(PyList_Check(seq));
3327
3328 index = it->it_index;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003329 if (index>=0 && index < PyList_GET_SIZE(seq)) {
3330 item = PyList_GET_ITEM(seq, index);
3331 it->it_index--;
3332 Py_INCREF(item);
3333 return item;
3334 }
3335 it->it_index = -1;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003336 it->it_seq = NULL;
3337 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003338 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003339}
3340
Raymond Hettingerf5b64112008-12-02 21:33:45 +00003341static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303342listreviter_len(listreviterobject *it, PyObject *Py_UNUSED(ignored))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003343{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003344 Py_ssize_t len = it->it_index + 1;
3345 if (it->it_seq == NULL || PyList_GET_SIZE(it->it_seq) < len)
3346 len = 0;
3347 return PyLong_FromSsize_t(len);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003348}
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003349
3350static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303351listreviter_reduce(listreviterobject *it, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003352{
3353 return listiter_reduce_general(it, 0);
3354}
3355
3356static PyObject *
3357listreviter_setstate(listreviterobject *it, PyObject *state)
3358{
3359 Py_ssize_t index = PyLong_AsSsize_t(state);
3360 if (index == -1 && PyErr_Occurred())
3361 return NULL;
3362 if (it->it_seq != NULL) {
3363 if (index < -1)
3364 index = -1;
3365 else if (index > PyList_GET_SIZE(it->it_seq) - 1)
3366 index = PyList_GET_SIZE(it->it_seq) - 1;
3367 it->it_index = index;
3368 }
3369 Py_RETURN_NONE;
3370}
3371
3372/* common pickling support */
3373
3374static PyObject *
3375listiter_reduce_general(void *_it, int forward)
3376{
Serhiy Storchakabb86bf42018-12-11 08:28:18 +02003377 _Py_IDENTIFIER(iter);
3378 _Py_IDENTIFIER(reversed);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003379 PyObject *list;
3380
3381 /* the objects are not the same, index is of different types! */
3382 if (forward) {
3383 listiterobject *it = (listiterobject *)_it;
3384 if (it->it_seq)
Serhiy Storchakabb86bf42018-12-11 08:28:18 +02003385 return Py_BuildValue("N(O)n", _PyEval_GetBuiltinId(&PyId_iter),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003386 it->it_seq, it->it_index);
3387 } else {
3388 listreviterobject *it = (listreviterobject *)_it;
3389 if (it->it_seq)
Serhiy Storchakabb86bf42018-12-11 08:28:18 +02003390 return Py_BuildValue("N(O)n", _PyEval_GetBuiltinId(&PyId_reversed),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003391 it->it_seq, it->it_index);
3392 }
3393 /* empty iterator, create an empty list */
3394 list = PyList_New(0);
3395 if (list == NULL)
3396 return NULL;
Serhiy Storchakabb86bf42018-12-11 08:28:18 +02003397 return Py_BuildValue("N(N)", _PyEval_GetBuiltinId(&PyId_iter), list);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003398}