blob: 904bea317c9da8a44ffef5390b5f0cc3196bb0b5 [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
Victor Stinnerae00a5a2020-04-29 02:29:20 +0200106void
107_PyList_ClearFreeList(void)
Raymond Hettingerfb09f0e2004-10-07 03:58:07 +0000108{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000109 while (numfree) {
Victor Stinnerae00a5a2020-04-29 02:29:20 +0200110 PyListObject *op = free_list[--numfree];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000111 assert(PyList_CheckExact(op));
112 PyObject_GC_Del(op);
113 }
Antoine Pitrou9a812cb2011-11-15 00:00:12 +0100114}
115
116void
Victor Stinnerbed48172019-08-27 00:12:32 +0200117_PyList_Fini(void)
Antoine Pitrou9a812cb2011-11-15 00:00:12 +0100118{
Victor Stinnerae00a5a2020-04-29 02:29:20 +0200119 _PyList_ClearFreeList();
Raymond Hettingerfb09f0e2004-10-07 03:58:07 +0000120}
121
David Malcolm49526f42012-06-22 14:55:41 -0400122/* Print summary info about the state of the optimized allocator */
123void
124_PyList_DebugMallocStats(FILE *out)
125{
126 _PyDebugAllocatorStats(out,
127 "free PyListObject",
128 numfree, sizeof(PyListObject));
129}
130
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000131PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000132PyList_New(Py_ssize_t size)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000133{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000134 PyListObject *op;
Tim Peters3986d4e2004-07-29 02:28:42 +0000135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000136 if (size < 0) {
137 PyErr_BadInternalCall();
138 return NULL;
139 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000140 if (numfree) {
141 numfree--;
142 op = free_list[numfree];
143 _Py_NewReference((PyObject *)op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000144 } else {
145 op = PyObject_GC_New(PyListObject, &PyList_Type);
146 if (op == NULL)
147 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000148 }
149 if (size <= 0)
150 op->ob_item = NULL;
151 else {
Mark Dickinson5d132382016-08-21 08:55:15 +0100152 op->ob_item = (PyObject **) PyMem_Calloc(size, sizeof(PyObject *));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000153 if (op->ob_item == NULL) {
154 Py_DECREF(op);
155 return PyErr_NoMemory();
156 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000157 }
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100158 Py_SET_SIZE(op, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000159 op->allocated = size;
160 _PyObject_GC_TRACK(op);
161 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000162}
163
Sergey Fedoseev2fc46972018-08-11 18:12:07 +0500164static PyObject *
165list_new_prealloc(Py_ssize_t size)
166{
167 PyListObject *op = (PyListObject *) PyList_New(0);
168 if (size == 0 || op == NULL) {
169 return (PyObject *) op;
170 }
171 assert(op->ob_item == NULL);
172 op->ob_item = PyMem_New(PyObject *, size);
173 if (op->ob_item == NULL) {
174 Py_DECREF(op);
175 return PyErr_NoMemory();
176 }
177 op->allocated = size;
178 return (PyObject *) op;
179}
180
Martin v. Löwis18e16552006-02-15 17:27:45 +0000181Py_ssize_t
Fred Drakea2f55112000-07-09 15:16:51 +0000182PyList_Size(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000183{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000184 if (!PyList_Check(op)) {
185 PyErr_BadInternalCall();
186 return -1;
187 }
188 else
189 return Py_SIZE(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000190}
191
Raymond Hettingerf1aa8ae2018-10-10 20:37:28 -0700192static inline int
193valid_index(Py_ssize_t i, Py_ssize_t limit)
194{
195 /* The cast to size_t lets us use just a single comparison
196 to check whether i is in the range: 0 <= i < limit.
197
198 See: Section 14.2 "Bounds Checking" in the Agner Fog
199 optimization manual found at:
200 https://www.agner.org/optimize/optimizing_cpp.pdf
201 */
202 return (size_t) i < (size_t) limit;
203}
204
Raymond Hettingerfdfe6182004-05-05 06:28:16 +0000205static PyObject *indexerr = NULL;
Guido van Rossum929f1b81996-08-09 20:51:27 +0000206
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000207PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000208PyList_GetItem(PyObject *op, Py_ssize_t i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000209{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000210 if (!PyList_Check(op)) {
211 PyErr_BadInternalCall();
212 return NULL;
213 }
Raymond Hettingerf1aa8ae2018-10-10 20:37:28 -0700214 if (!valid_index(i, Py_SIZE(op))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000215 if (indexerr == NULL) {
216 indexerr = PyUnicode_FromString(
217 "list index out of range");
218 if (indexerr == NULL)
219 return NULL;
220 }
221 PyErr_SetObject(PyExc_IndexError, indexerr);
222 return NULL;
223 }
224 return ((PyListObject *)op) -> ob_item[i];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000225}
226
227int
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200228PyList_SetItem(PyObject *op, Py_ssize_t i,
229 PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000230{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200231 PyObject **p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000232 if (!PyList_Check(op)) {
233 Py_XDECREF(newitem);
234 PyErr_BadInternalCall();
235 return -1;
236 }
Raymond Hettingerf1aa8ae2018-10-10 20:37:28 -0700237 if (!valid_index(i, Py_SIZE(op))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000238 Py_XDECREF(newitem);
239 PyErr_SetString(PyExc_IndexError,
240 "list assignment index out of range");
241 return -1;
242 }
243 p = ((PyListObject *)op) -> ob_item + i;
Serhiy Storchakaec397562016-04-06 09:50:03 +0300244 Py_XSETREF(*p, newitem);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000246}
247
248static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000249ins1(PyListObject *self, Py_ssize_t where, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000250{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000251 Py_ssize_t i, n = Py_SIZE(self);
252 PyObject **items;
253 if (v == NULL) {
254 PyErr_BadInternalCall();
255 return -1;
256 }
257 if (n == PY_SSIZE_T_MAX) {
258 PyErr_SetString(PyExc_OverflowError,
259 "cannot add more objects to list");
260 return -1;
261 }
Tim Petersb38e2b62004-07-29 02:29:26 +0000262
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800263 if (list_resize(self, n+1) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000264 return -1;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000265
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000266 if (where < 0) {
267 where += n;
268 if (where < 0)
269 where = 0;
270 }
271 if (where > n)
272 where = n;
273 items = self->ob_item;
274 for (i = n; --i >= where; )
275 items[i+1] = items[i];
276 Py_INCREF(v);
277 items[where] = v;
278 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000279}
280
281int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000282PyList_Insert(PyObject *op, Py_ssize_t where, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000283{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000284 if (!PyList_Check(op)) {
285 PyErr_BadInternalCall();
286 return -1;
287 }
288 return ins1((PyListObject *)op, where, newitem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000289}
290
Raymond Hettinger40a03822004-04-12 13:05:09 +0000291static int
292app1(PyListObject *self, PyObject *v)
293{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000294 Py_ssize_t n = PyList_GET_SIZE(self);
Raymond Hettinger40a03822004-04-12 13:05:09 +0000295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000296 assert (v != NULL);
297 if (n == PY_SSIZE_T_MAX) {
298 PyErr_SetString(PyExc_OverflowError,
299 "cannot add more objects to list");
300 return -1;
301 }
Raymond Hettinger40a03822004-04-12 13:05:09 +0000302
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800303 if (list_resize(self, n+1) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000304 return -1;
Raymond Hettinger40a03822004-04-12 13:05:09 +0000305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000306 Py_INCREF(v);
307 PyList_SET_ITEM(self, n, v);
308 return 0;
Raymond Hettinger40a03822004-04-12 13:05:09 +0000309}
310
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000311int
Fred Drakea2f55112000-07-09 15:16:51 +0000312PyList_Append(PyObject *op, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000313{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000314 if (PyList_Check(op) && (newitem != NULL))
315 return app1((PyListObject *)op, newitem);
316 PyErr_BadInternalCall();
317 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000318}
319
320/* Methods */
321
322static void
Fred Drakea2f55112000-07-09 15:16:51 +0000323list_dealloc(PyListObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000324{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000325 Py_ssize_t i;
326 PyObject_GC_UnTrack(op);
Jeroen Demeyer351c6742019-05-10 19:21:11 +0200327 Py_TRASHCAN_BEGIN(op, list_dealloc)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000328 if (op->ob_item != NULL) {
329 /* Do it backwards, for Christian Tismer.
330 There's a simple test case where somehow this reduces
331 thrashing when a *very* large list is created and
332 immediately deleted. */
333 i = Py_SIZE(op);
334 while (--i >= 0) {
335 Py_XDECREF(op->ob_item[i]);
336 }
337 PyMem_FREE(op->ob_item);
338 }
339 if (numfree < PyList_MAXFREELIST && PyList_CheckExact(op))
340 free_list[numfree++] = op;
341 else
342 Py_TYPE(op)->tp_free((PyObject *)op);
Jeroen Demeyer351c6742019-05-10 19:21:11 +0200343 Py_TRASHCAN_END
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000344}
345
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000346static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000347list_repr(PyListObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000348{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000349 Py_ssize_t i;
Victor Stinner5c733472013-11-18 21:11:57 +0100350 PyObject *s;
Victor Stinner5c733472013-11-18 21:11:57 +0100351 _PyUnicodeWriter writer;
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200352
353 if (Py_SIZE(v) == 0) {
354 return PyUnicode_FromString("[]");
355 }
356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000357 i = Py_ReprEnter((PyObject*)v);
358 if (i != 0) {
359 return i > 0 ? PyUnicode_FromString("[...]") : NULL;
360 }
Tim Petersa7259592001-06-16 05:11:17 +0000361
Victor Stinner5c733472013-11-18 21:11:57 +0100362 _PyUnicodeWriter_Init(&writer);
363 writer.overallocate = 1;
Victor Stinnerb8fb1972013-11-18 22:15:44 +0100364 /* "[" + "1" + ", 2" * (len - 1) + "]" */
365 writer.min_length = 1 + 1 + (2 + 1) * (Py_SIZE(v) - 1) + 1;
Tim Petersa7259592001-06-16 05:11:17 +0000366
Victor Stinner5c733472013-11-18 21:11:57 +0100367 if (_PyUnicodeWriter_WriteChar(&writer, '[') < 0)
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200368 goto error;
Tim Petersa7259592001-06-16 05:11:17 +0000369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000370 /* Do repr() on each element. Note that this may mutate the list,
371 so must refetch the list size on each iteration. */
372 for (i = 0; i < Py_SIZE(v); ++i) {
Victor Stinner5c733472013-11-18 21:11:57 +0100373 if (i > 0) {
Victor Stinner4a587072013-11-19 12:54:53 +0100374 if (_PyUnicodeWriter_WriteASCIIString(&writer, ", ", 2) < 0)
Victor Stinner5c733472013-11-18 21:11:57 +0100375 goto error;
376 }
377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000378 s = PyObject_Repr(v->ob_item[i]);
Victor Stinner5c733472013-11-18 21:11:57 +0100379 if (s == NULL)
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200380 goto error;
Victor Stinner5c733472013-11-18 21:11:57 +0100381
382 if (_PyUnicodeWriter_WriteStr(&writer, s) < 0) {
383 Py_DECREF(s);
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200384 goto error;
Victor Stinner5c733472013-11-18 21:11:57 +0100385 }
386 Py_DECREF(s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000387 }
Victor Stinner5c733472013-11-18 21:11:57 +0100388
Victor Stinner4d3f1092013-11-19 12:09:00 +0100389 writer.overallocate = 0;
Victor Stinner5c733472013-11-18 21:11:57 +0100390 if (_PyUnicodeWriter_WriteChar(&writer, ']') < 0)
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200391 goto error;
Tim Petersa7259592001-06-16 05:11:17 +0000392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000393 Py_ReprLeave((PyObject *)v);
Victor Stinner5c733472013-11-18 21:11:57 +0100394 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200395
396error:
Victor Stinner5c733472013-11-18 21:11:57 +0100397 _PyUnicodeWriter_Dealloc(&writer);
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200398 Py_ReprLeave((PyObject *)v);
399 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000400}
401
Martin v. Löwis18e16552006-02-15 17:27:45 +0000402static Py_ssize_t
Fred Drakea2f55112000-07-09 15:16:51 +0000403list_length(PyListObject *a)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000404{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000405 return Py_SIZE(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000406}
407
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000408static int
Fred Drakea2f55112000-07-09 15:16:51 +0000409list_contains(PyListObject *a, PyObject *el)
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000410{
Dong-hee Na4dbf2d82020-01-28 00:02:23 +0900411 PyObject *item;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000412 Py_ssize_t i;
413 int cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000414
Dong-hee Na4dbf2d82020-01-28 00:02:23 +0900415 for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(a); ++i) {
416 item = PyList_GET_ITEM(a, i);
417 Py_INCREF(item);
Dong-hee Na9e1ed512020-01-28 02:04:25 +0900418 cmp = PyObject_RichCompareBool(item, el, Py_EQ);
Dong-hee Na4dbf2d82020-01-28 00:02:23 +0900419 Py_DECREF(item);
420 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 return cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000422}
423
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000424static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000425list_item(PyListObject *a, Py_ssize_t i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000426{
Raymond Hettingerf1aa8ae2018-10-10 20:37:28 -0700427 if (!valid_index(i, Py_SIZE(a))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000428 if (indexerr == NULL) {
429 indexerr = PyUnicode_FromString(
430 "list index out of range");
431 if (indexerr == NULL)
432 return NULL;
433 }
434 PyErr_SetObject(PyExc_IndexError, indexerr);
435 return NULL;
436 }
437 Py_INCREF(a->ob_item[i]);
438 return a->ob_item[i];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000439}
440
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000441static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000442list_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000443{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000444 PyListObject *np;
445 PyObject **src, **dest;
446 Py_ssize_t i, len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000447 len = ihigh - ilow;
Sergey Fedoseev2fc46972018-08-11 18:12:07 +0500448 np = (PyListObject *) list_new_prealloc(len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000449 if (np == NULL)
450 return NULL;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000451
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000452 src = a->ob_item + ilow;
453 dest = np->ob_item;
454 for (i = 0; i < len; i++) {
455 PyObject *v = src[i];
456 Py_INCREF(v);
457 dest[i] = v;
458 }
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100459 Py_SET_SIZE(np, len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000461}
462
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000463PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000464PyList_GetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum234f9421993-06-17 12:35:49 +0000465{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000466 if (!PyList_Check(a)) {
467 PyErr_BadInternalCall();
468 return NULL;
469 }
Sergey Fedoseevef1b88b2019-02-21 11:51:52 +0500470 if (ilow < 0) {
471 ilow = 0;
472 }
473 else if (ilow > Py_SIZE(a)) {
474 ilow = Py_SIZE(a);
475 }
476 if (ihigh < ilow) {
477 ihigh = ilow;
478 }
479 else if (ihigh > Py_SIZE(a)) {
480 ihigh = Py_SIZE(a);
481 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 return list_slice((PyListObject *)a, ilow, ihigh);
Guido van Rossum234f9421993-06-17 12:35:49 +0000483}
484
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000485static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000486list_concat(PyListObject *a, PyObject *bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000487{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 Py_ssize_t size;
489 Py_ssize_t i;
490 PyObject **src, **dest;
491 PyListObject *np;
492 if (!PyList_Check(bb)) {
493 PyErr_Format(PyExc_TypeError,
494 "can only concatenate list (not \"%.200s\") to list",
Victor Stinner58ac7002020-02-07 03:04:21 +0100495 Py_TYPE(bb)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000496 return NULL;
497 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000498#define b ((PyListObject *)bb)
Martin Panterb93d8632016-07-25 02:39:20 +0000499 if (Py_SIZE(a) > PY_SSIZE_T_MAX - Py_SIZE(b))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 return PyErr_NoMemory();
Martin Panterb93d8632016-07-25 02:39:20 +0000501 size = Py_SIZE(a) + Py_SIZE(b);
Sergey Fedoseev2fc46972018-08-11 18:12:07 +0500502 np = (PyListObject *) list_new_prealloc(size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000503 if (np == NULL) {
504 return NULL;
505 }
506 src = a->ob_item;
507 dest = np->ob_item;
508 for (i = 0; i < Py_SIZE(a); i++) {
509 PyObject *v = src[i];
510 Py_INCREF(v);
511 dest[i] = v;
512 }
513 src = b->ob_item;
514 dest = np->ob_item + Py_SIZE(a);
515 for (i = 0; i < Py_SIZE(b); i++) {
516 PyObject *v = src[i];
517 Py_INCREF(v);
518 dest[i] = v;
519 }
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100520 Py_SET_SIZE(np, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000522#undef b
523}
524
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000525static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000526list_repeat(PyListObject *a, Py_ssize_t n)
Guido van Rossumed98d481991-03-06 13:07:53 +0000527{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000528 Py_ssize_t i, j;
529 Py_ssize_t size;
530 PyListObject *np;
531 PyObject **p, **items;
532 PyObject *elem;
533 if (n < 0)
534 n = 0;
Mark Dickinsonc0420fd2011-09-19 19:18:37 +0100535 if (n > 0 && Py_SIZE(a) > PY_SSIZE_T_MAX / n)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000536 return PyErr_NoMemory();
Mark Dickinsonc0420fd2011-09-19 19:18:37 +0100537 size = Py_SIZE(a) * n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 if (size == 0)
539 return PyList_New(0);
Sergey Fedoseev2fc46972018-08-11 18:12:07 +0500540 np = (PyListObject *) list_new_prealloc(size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000541 if (np == NULL)
542 return NULL;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000543
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000544 if (Py_SIZE(a) == 1) {
Sergey Fedoseev2fc46972018-08-11 18:12:07 +0500545 items = np->ob_item;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 elem = a->ob_item[0];
547 for (i = 0; i < n; i++) {
548 items[i] = elem;
549 Py_INCREF(elem);
550 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 }
Sergey Fedoseev2fc46972018-08-11 18:12:07 +0500552 else {
553 p = np->ob_item;
554 items = a->ob_item;
555 for (i = 0; i < n; i++) {
556 for (j = 0; j < Py_SIZE(a); j++) {
557 *p = items[j];
558 Py_INCREF(*p);
559 p++;
560 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561 }
562 }
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100563 Py_SET_SIZE(np, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000564 return (PyObject *) np;
Guido van Rossumed98d481991-03-06 13:07:53 +0000565}
566
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000567static int
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200568_list_clear(PyListObject *a)
Armin Rigo93677f02004-07-29 12:40:23 +0000569{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000570 Py_ssize_t i;
571 PyObject **item = a->ob_item;
572 if (item != NULL) {
573 /* Because XDECREF can recursively invoke operations on
574 this list, we make it empty first. */
575 i = Py_SIZE(a);
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100576 Py_SET_SIZE(a, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577 a->ob_item = NULL;
578 a->allocated = 0;
579 while (--i >= 0) {
580 Py_XDECREF(item[i]);
581 }
582 PyMem_FREE(item);
583 }
584 /* Never fails; the return value can be ignored.
585 Note that there is no guarantee that the list is actually empty
586 at this point, because XDECREF may have populated it again! */
587 return 0;
Armin Rigo93677f02004-07-29 12:40:23 +0000588}
589
Tim Peters8fc4a912004-07-31 21:53:19 +0000590/* a[ilow:ihigh] = v if v != NULL.
591 * del a[ilow:ihigh] if v == NULL.
592 *
593 * Special speed gimmick: when v is NULL and ihigh - ilow <= 8, it's
594 * guaranteed the call cannot fail.
595 */
Armin Rigo93677f02004-07-29 12:40:23 +0000596static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000597list_ass_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000598{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000599 /* Because [X]DECREF can recursively invoke list operations on
600 this list, we must postpone all [X]DECREF activity until
601 after the list is back in its canonical shape. Therefore
602 we must allocate an additional array, 'recycle', into which
603 we temporarily copy the items that are deleted from the
604 list. :-( */
605 PyObject *recycle_on_stack[8];
606 PyObject **recycle = recycle_on_stack; /* will allocate more if needed */
607 PyObject **item;
608 PyObject **vitem = NULL;
609 PyObject *v_as_SF = NULL; /* PySequence_Fast(v) */
610 Py_ssize_t n; /* # of elements in replacement list */
611 Py_ssize_t norig; /* # of elements in list getting replaced */
612 Py_ssize_t d; /* Change in size */
613 Py_ssize_t k;
614 size_t s;
615 int result = -1; /* guilty until proved innocent */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000616#define b ((PyListObject *)v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000617 if (v == NULL)
618 n = 0;
619 else {
620 if (a == b) {
621 /* Special case "a[i:j] = a" -- copy b first */
622 v = list_slice(b, 0, Py_SIZE(b));
623 if (v == NULL)
624 return result;
625 result = list_ass_slice(a, ilow, ihigh, v);
626 Py_DECREF(v);
627 return result;
628 }
629 v_as_SF = PySequence_Fast(v, "can only assign an iterable");
630 if(v_as_SF == NULL)
631 goto Error;
632 n = PySequence_Fast_GET_SIZE(v_as_SF);
633 vitem = PySequence_Fast_ITEMS(v_as_SF);
634 }
635 if (ilow < 0)
636 ilow = 0;
637 else if (ilow > Py_SIZE(a))
638 ilow = Py_SIZE(a);
Tim Peters8d9eb102004-07-31 02:24:20 +0000639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 if (ihigh < ilow)
641 ihigh = ilow;
642 else if (ihigh > Py_SIZE(a))
643 ihigh = Py_SIZE(a);
Armin Rigo93677f02004-07-29 12:40:23 +0000644
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000645 norig = ihigh - ilow;
646 assert(norig >= 0);
647 d = n - norig;
648 if (Py_SIZE(a) + d == 0) {
649 Py_XDECREF(v_as_SF);
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200650 return _list_clear(a);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000651 }
652 item = a->ob_item;
653 /* recycle the items that we are about to remove */
654 s = norig * sizeof(PyObject *);
Benjamin Peterson5a7d9232016-09-06 17:58:25 -0700655 /* If norig == 0, item might be NULL, in which case we may not memcpy from it. */
656 if (s) {
657 if (s > sizeof(recycle_on_stack)) {
658 recycle = (PyObject **)PyMem_MALLOC(s);
659 if (recycle == NULL) {
660 PyErr_NoMemory();
661 goto Error;
662 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000663 }
Benjamin Peterson5a7d9232016-09-06 17:58:25 -0700664 memcpy(recycle, &item[ilow], s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000665 }
Tim Peters8d9eb102004-07-31 02:24:20 +0000666
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000667 if (d < 0) { /* Delete -d items */
Victor Stinner2c40f642013-07-19 23:06:21 +0200668 Py_ssize_t tail;
669 tail = (Py_SIZE(a) - ihigh) * sizeof(PyObject *);
670 memmove(&item[ihigh+d], &item[ihigh], tail);
671 if (list_resize(a, Py_SIZE(a) + d) < 0) {
672 memmove(&item[ihigh], &item[ihigh+d], tail);
673 memcpy(&item[ilow], recycle, s);
674 goto Error;
675 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 item = a->ob_item;
677 }
678 else if (d > 0) { /* Insert d items */
679 k = Py_SIZE(a);
680 if (list_resize(a, k+d) < 0)
681 goto Error;
682 item = a->ob_item;
683 memmove(&item[ihigh+d], &item[ihigh],
684 (k - ihigh)*sizeof(PyObject *));
685 }
686 for (k = 0; k < n; k++, ilow++) {
687 PyObject *w = vitem[k];
688 Py_XINCREF(w);
689 item[ilow] = w;
690 }
691 for (k = norig - 1; k >= 0; --k)
692 Py_XDECREF(recycle[k]);
693 result = 0;
Tim Peters8d9eb102004-07-31 02:24:20 +0000694 Error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000695 if (recycle != recycle_on_stack)
696 PyMem_FREE(recycle);
697 Py_XDECREF(v_as_SF);
698 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000699#undef b
700}
701
Guido van Rossum234f9421993-06-17 12:35:49 +0000702int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000703PyList_SetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum234f9421993-06-17 12:35:49 +0000704{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000705 if (!PyList_Check(a)) {
706 PyErr_BadInternalCall();
707 return -1;
708 }
709 return list_ass_slice((PyListObject *)a, ilow, ihigh, v);
Guido van Rossum234f9421993-06-17 12:35:49 +0000710}
711
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000712static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000713list_inplace_repeat(PyListObject *self, Py_ssize_t n)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000714{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 PyObject **items;
716 Py_ssize_t size, i, j, p;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000717
718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000719 size = PyList_GET_SIZE(self);
720 if (size == 0 || n == 1) {
721 Py_INCREF(self);
722 return (PyObject *)self;
723 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000725 if (n < 1) {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200726 (void)_list_clear(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000727 Py_INCREF(self);
728 return (PyObject *)self;
729 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000730
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000731 if (size > PY_SSIZE_T_MAX / n) {
732 return PyErr_NoMemory();
733 }
Christian Heimesaf98da12008-01-27 15:18:18 +0000734
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800735 if (list_resize(self, size*n) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 return NULL;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000738 p = size;
739 items = self->ob_item;
740 for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */
741 for (j = 0; j < size; j++) {
742 PyObject *o = items[j];
743 Py_INCREF(o);
744 items[p++] = o;
745 }
746 }
747 Py_INCREF(self);
748 return (PyObject *)self;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000749}
750
Guido van Rossum4a450d01991-04-03 19:05:18 +0000751static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000752list_ass_item(PyListObject *a, Py_ssize_t i, PyObject *v)
Guido van Rossum4a450d01991-04-03 19:05:18 +0000753{
Raymond Hettingerf1aa8ae2018-10-10 20:37:28 -0700754 if (!valid_index(i, Py_SIZE(a))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000755 PyErr_SetString(PyExc_IndexError,
756 "list assignment index out of range");
757 return -1;
758 }
759 if (v == NULL)
760 return list_ass_slice(a, i, i+1, v);
761 Py_INCREF(v);
Serhiy Storchakaf01e4082016-04-10 18:12:01 +0300762 Py_SETREF(a->ob_item[i], v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000763 return 0;
Guido van Rossum4a450d01991-04-03 19:05:18 +0000764}
765
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200766/*[clinic input]
767list.insert
768
769 index: Py_ssize_t
770 object: object
771 /
772
773Insert object before index.
774[clinic start generated code]*/
775
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000776static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200777list_insert_impl(PyListObject *self, Py_ssize_t index, PyObject *object)
778/*[clinic end generated code: output=7f35e32f60c8cb78 input=858514cf894c7eab]*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000779{
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200780 if (ins1(self, index, object) == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 Py_RETURN_NONE;
782 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000783}
784
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200785/*[clinic input]
786list.clear
787
788Remove all items from list.
789[clinic start generated code]*/
790
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000791static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200792list_clear_impl(PyListObject *self)
793/*[clinic end generated code: output=67a1896c01f74362 input=ca3c1646856742f6]*/
Eli Benderskycbbaa962011-02-25 05:47:53 +0000794{
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200795 _list_clear(self);
Eli Benderskycbbaa962011-02-25 05:47:53 +0000796 Py_RETURN_NONE;
797}
798
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200799/*[clinic input]
800list.copy
801
802Return a shallow copy of the list.
803[clinic start generated code]*/
804
Eli Benderskycbbaa962011-02-25 05:47:53 +0000805static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200806list_copy_impl(PyListObject *self)
807/*[clinic end generated code: output=ec6b72d6209d418e input=6453ab159e84771f]*/
Eli Benderskycbbaa962011-02-25 05:47:53 +0000808{
809 return list_slice(self, 0, Py_SIZE(self));
810}
811
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200812/*[clinic input]
813list.append
814
815 object: object
816 /
817
818Append object to the end of the list.
819[clinic start generated code]*/
820
Eli Benderskycbbaa962011-02-25 05:47:53 +0000821static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200822list_append(PyListObject *self, PyObject *object)
823/*[clinic end generated code: output=7c096003a29c0eae input=43a3fe48a7066e91]*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000824{
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200825 if (app1(self, object) == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000826 Py_RETURN_NONE;
827 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000828}
829
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200830/*[clinic input]
831list.extend
832
833 iterable: object
834 /
835
836Extend list by appending elements from the iterable.
837[clinic start generated code]*/
838
Barry Warsawdedf6d61998-10-09 16:37:25 +0000839static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200840list_extend(PyListObject *self, PyObject *iterable)
841/*[clinic end generated code: output=630fb3bca0c8e789 input=9ec5ba3a81be3a4d]*/
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000842{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000843 PyObject *it; /* iter(v) */
844 Py_ssize_t m; /* size of self */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200845 Py_ssize_t n; /* guess for size of iterable */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000846 Py_ssize_t mn; /* m + n */
847 Py_ssize_t i;
848 PyObject *(*iternext)(PyObject *);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000849
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000850 /* Special cases:
851 1) lists and tuples which can use PySequence_Fast ops
852 2) extending self to self requires making a copy first
853 */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200854 if (PyList_CheckExact(iterable) || PyTuple_CheckExact(iterable) ||
855 (PyObject *)self == iterable) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000856 PyObject **src, **dest;
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200857 iterable = PySequence_Fast(iterable, "argument must be iterable");
858 if (!iterable)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 return NULL;
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200860 n = PySequence_Fast_GET_SIZE(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000861 if (n == 0) {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200862 /* short circuit when iterable is empty */
863 Py_DECREF(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 Py_RETURN_NONE;
865 }
866 m = Py_SIZE(self);
Martin Panter94b39ce2017-01-14 06:30:37 +0000867 /* It should not be possible to allocate a list large enough to cause
868 an overflow on any relevant platform */
869 assert(m < PY_SSIZE_T_MAX - n);
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800870 if (list_resize(self, m + n) < 0) {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200871 Py_DECREF(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000872 return NULL;
873 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200874 /* note that we may still have self == iterable here for the
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000875 * situation a.extend(a), but the following code works
876 * in that case too. Just make sure to resize self
877 * before calling PySequence_Fast_ITEMS.
878 */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200879 /* populate the end of self with iterable's items */
880 src = PySequence_Fast_ITEMS(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 dest = self->ob_item + m;
882 for (i = 0; i < n; i++) {
883 PyObject *o = src[i];
884 Py_INCREF(o);
885 dest[i] = o;
886 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200887 Py_DECREF(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000888 Py_RETURN_NONE;
889 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000890
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200891 it = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000892 if (it == NULL)
893 return NULL;
Victor Stinner58ac7002020-02-07 03:04:21 +0100894 iternext = *Py_TYPE(it)->tp_iternext;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 /* Guess a result list size. */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200897 n = PyObject_LengthHint(iterable, 8);
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800898 if (n < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000899 Py_DECREF(it);
900 return NULL;
901 }
902 m = Py_SIZE(self);
Martin Panterb93d8632016-07-25 02:39:20 +0000903 if (m > PY_SSIZE_T_MAX - n) {
904 /* m + n overflowed; on the chance that n lied, and there really
905 * is enough room, ignore it. If n was telling the truth, we'll
906 * eventually run out of memory during the loop.
907 */
908 }
909 else {
910 mn = m + n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000911 /* Make room. */
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800912 if (list_resize(self, mn) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 goto error;
914 /* Make the list sane again. */
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100915 Py_SET_SIZE(self, m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 /* Run iterator to exhaustion. */
919 for (;;) {
920 PyObject *item = iternext(it);
921 if (item == NULL) {
922 if (PyErr_Occurred()) {
923 if (PyErr_ExceptionMatches(PyExc_StopIteration))
924 PyErr_Clear();
925 else
926 goto error;
927 }
928 break;
929 }
930 if (Py_SIZE(self) < self->allocated) {
931 /* steals ref */
932 PyList_SET_ITEM(self, Py_SIZE(self), item);
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100933 Py_SET_SIZE(self, Py_SIZE(self) + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 }
935 else {
936 int status = app1(self, item);
937 Py_DECREF(item); /* append creates a new ref */
938 if (status < 0)
939 goto error;
940 }
941 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000943 /* Cut back result list if initial guess was too large. */
Victor Stinner32fd6ea2013-07-16 21:45:58 +0200944 if (Py_SIZE(self) < self->allocated) {
945 if (list_resize(self, Py_SIZE(self)) < 0)
946 goto error;
947 }
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 Py_DECREF(it);
950 Py_RETURN_NONE;
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000951
952 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 Py_DECREF(it);
954 return NULL;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000955}
956
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000957PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200958_PyList_Extend(PyListObject *self, PyObject *iterable)
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000959{
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200960 return list_extend(self, iterable);
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000961}
962
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000963static PyObject *
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000964list_inplace_concat(PyListObject *self, PyObject *other)
965{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 PyObject *result;
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000967
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200968 result = list_extend(self, other);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 if (result == NULL)
970 return result;
971 Py_DECREF(result);
972 Py_INCREF(self);
973 return (PyObject *)self;
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000974}
975
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200976/*[clinic input]
977list.pop
978
979 index: Py_ssize_t = -1
980 /
981
982Remove and return item at index (default last).
983
984Raises IndexError if list is empty or index is out of range.
985[clinic start generated code]*/
986
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000987static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200988list_pop_impl(PyListObject *self, Py_ssize_t index)
989/*[clinic end generated code: output=6bd69dcb3f17eca8 input=b83675976f329e6f]*/
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000990{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 PyObject *v;
992 int status;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000994 if (Py_SIZE(self) == 0) {
995 /* Special-case most common failure cause */
996 PyErr_SetString(PyExc_IndexError, "pop from empty list");
997 return NULL;
998 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200999 if (index < 0)
1000 index += Py_SIZE(self);
Raymond Hettingerf1aa8ae2018-10-10 20:37:28 -07001001 if (!valid_index(index, Py_SIZE(self))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 PyErr_SetString(PyExc_IndexError, "pop index out of range");
1003 return NULL;
1004 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02001005 v = self->ob_item[index];
1006 if (index == Py_SIZE(self) - 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007 status = list_resize(self, Py_SIZE(self) - 1);
Victor Stinnerb27cd3e2013-07-08 22:20:44 +02001008 if (status >= 0)
1009 return v; /* and v now owns the reference the list had */
1010 else
1011 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001012 }
1013 Py_INCREF(v);
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02001014 status = list_ass_slice(self, index, index+1, (PyObject *)NULL);
Victor Stinner095d99f2013-07-17 21:58:01 +02001015 if (status < 0) {
1016 Py_DECREF(v);
1017 return NULL;
1018 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 return v;
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +00001020}
1021
Tim Peters8e2e7ca2002-07-19 02:33:08 +00001022/* Reverse a slice of a list in place, from lo up to (exclusive) hi. */
1023static void
1024reverse_slice(PyObject **lo, PyObject **hi)
1025{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001026 assert(lo && hi);
Tim Peters8e2e7ca2002-07-19 02:33:08 +00001027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 --hi;
1029 while (lo < hi) {
1030 PyObject *t = *lo;
1031 *lo = *hi;
1032 *hi = t;
1033 ++lo;
1034 --hi;
1035 }
Tim Peters8e2e7ca2002-07-19 02:33:08 +00001036}
1037
Tim Petersa64dc242002-08-01 02:13:36 +00001038/* Lots of code for an adaptive, stable, natural mergesort. There are many
1039 * pieces to this algorithm; read listsort.txt for overviews and details.
1040 */
Guido van Rossum3f236de1996-12-10 23:55:39 +00001041
Daniel Stutzbach98338222010-12-02 21:55:33 +00001042/* A sortslice contains a pointer to an array of keys and a pointer to
1043 * an array of corresponding values. In other words, keys[i]
1044 * corresponds with values[i]. If values == NULL, then the keys are
1045 * also the values.
1046 *
1047 * Several convenience routines are provided here, so that keys and
1048 * values are always moved in sync.
1049 */
1050
1051typedef struct {
1052 PyObject **keys;
1053 PyObject **values;
1054} sortslice;
1055
1056Py_LOCAL_INLINE(void)
1057sortslice_copy(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j)
1058{
1059 s1->keys[i] = s2->keys[j];
1060 if (s1->values != NULL)
1061 s1->values[i] = s2->values[j];
1062}
1063
1064Py_LOCAL_INLINE(void)
Benjamin Peterson9efdcca2010-12-03 01:44:10 +00001065sortslice_copy_incr(sortslice *dst, sortslice *src)
1066{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001067 *dst->keys++ = *src->keys++;
1068 if (dst->values != NULL)
1069 *dst->values++ = *src->values++;
1070}
1071
1072Py_LOCAL_INLINE(void)
Benjamin Peterson9efdcca2010-12-03 01:44:10 +00001073sortslice_copy_decr(sortslice *dst, sortslice *src)
1074{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001075 *dst->keys-- = *src->keys--;
1076 if (dst->values != NULL)
1077 *dst->values-- = *src->values--;
1078}
1079
1080
1081Py_LOCAL_INLINE(void)
1082sortslice_memcpy(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j,
Benjamin Peterson9efdcca2010-12-03 01:44:10 +00001083 Py_ssize_t n)
1084{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001085 memcpy(&s1->keys[i], &s2->keys[j], sizeof(PyObject *) * n);
1086 if (s1->values != NULL)
1087 memcpy(&s1->values[i], &s2->values[j], sizeof(PyObject *) * n);
1088}
1089
1090Py_LOCAL_INLINE(void)
1091sortslice_memmove(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j,
Benjamin Peterson9efdcca2010-12-03 01:44:10 +00001092 Py_ssize_t n)
1093{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001094 memmove(&s1->keys[i], &s2->keys[j], sizeof(PyObject *) * n);
1095 if (s1->values != NULL)
1096 memmove(&s1->values[i], &s2->values[j], sizeof(PyObject *) * n);
1097}
1098
1099Py_LOCAL_INLINE(void)
Benjamin Peterson9efdcca2010-12-03 01:44:10 +00001100sortslice_advance(sortslice *slice, Py_ssize_t n)
1101{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001102 slice->keys += n;
1103 if (slice->values != NULL)
1104 slice->values += n;
1105}
1106
embg1e34da42018-01-28 20:03:23 -07001107/* Comparison function: ms->key_compare, which is set at run-time in
1108 * listsort_impl to optimize for various special cases.
Tim Petersa64dc242002-08-01 02:13:36 +00001109 * Returns -1 on error, 1 if x < y, 0 if x >= y.
1110 */
Guido van Rossum3f236de1996-12-10 23:55:39 +00001111
embg1e34da42018-01-28 20:03:23 -07001112#define ISLT(X, Y) (*(ms->key_compare))(X, Y, ms)
Tim Peters66860f62002-08-04 17:47:26 +00001113
1114/* Compare X to Y via "<". Goto "fail" if the comparison raises an
Tim Petersa8c974c2002-07-19 03:30:57 +00001115 error. Else "k" is set to true iff X<Y, and an "if (k)" block is
1116 started. It makes more sense in context <wink>. X and Y are PyObject*s.
1117*/
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001118#define IFLT(X, Y) if ((k = ISLT(X, Y)) < 0) goto fail; \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001119 if (k)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001120
embg1e34da42018-01-28 20:03:23 -07001121/* The maximum number of entries in a MergeState's pending-runs stack.
1122 * This is enough to sort arrays of size up to about
1123 * 32 * phi ** MAX_MERGE_PENDING
1124 * where phi ~= 1.618. 85 is ridiculouslylarge enough, good for an array
1125 * with 2**64 elements.
1126 */
1127#define MAX_MERGE_PENDING 85
1128
1129/* When we get into galloping mode, we stay there until both runs win less
1130 * often than MIN_GALLOP consecutive times. See listsort.txt for more info.
1131 */
1132#define MIN_GALLOP 7
1133
1134/* Avoid malloc for small temp arrays. */
1135#define MERGESTATE_TEMP_SIZE 256
1136
1137/* One MergeState exists on the stack per invocation of mergesort. It's just
1138 * a convenient way to pass state around among the helper functions.
1139 */
1140struct s_slice {
1141 sortslice base;
1142 Py_ssize_t len;
1143};
1144
1145typedef struct s_MergeState MergeState;
1146struct s_MergeState {
1147 /* This controls when we get *into* galloping mode. It's initialized
1148 * to MIN_GALLOP. merge_lo and merge_hi tend to nudge it higher for
1149 * random data, and lower for highly structured data.
1150 */
1151 Py_ssize_t min_gallop;
1152
1153 /* 'a' is temp storage to help with merges. It contains room for
1154 * alloced entries.
1155 */
1156 sortslice a; /* may point to temparray below */
1157 Py_ssize_t alloced;
1158
1159 /* A stack of n pending runs yet to be merged. Run #i starts at
1160 * address base[i] and extends for len[i] elements. It's always
1161 * true (so long as the indices are in bounds) that
1162 *
1163 * pending[i].base + pending[i].len == pending[i+1].base
1164 *
1165 * so we could cut the storage for this, but it's a minor amount,
1166 * and keeping all the info explicit simplifies the code.
1167 */
1168 int n;
1169 struct s_slice pending[MAX_MERGE_PENDING];
1170
1171 /* 'a' points to this when possible, rather than muck with malloc. */
1172 PyObject *temparray[MERGESTATE_TEMP_SIZE];
1173
1174 /* This is the function we will use to compare two keys,
1175 * even when none of our special cases apply and we have to use
1176 * safe_object_compare. */
1177 int (*key_compare)(PyObject *, PyObject *, MergeState *);
1178
1179 /* This function is used by unsafe_object_compare to optimize comparisons
1180 * when we know our list is type-homogeneous but we can't assume anything else.
Victor Stinner58ac7002020-02-07 03:04:21 +01001181 * In the pre-sort check it is set equal to Py_TYPE(key)->tp_richcompare */
embg1e34da42018-01-28 20:03:23 -07001182 PyObject *(*key_richcompare)(PyObject *, PyObject *, int);
1183
1184 /* This function is used by unsafe_tuple_compare to compare the first elements
1185 * of tuples. It may be set to safe_object_compare, but the idea is that hopefully
1186 * we can assume more, and use one of the special-case compares. */
1187 int (*tuple_elem_compare)(PyObject *, PyObject *, MergeState *);
1188};
1189
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001190/* binarysort is the best method for sorting small arrays: it does
1191 few compares, but can do data movement quadratic in the number of
1192 elements.
Guido van Rossum42812581998-06-17 14:15:44 +00001193 [lo, hi) is a contiguous slice of a list, and is sorted via
Tim Petersa8c974c2002-07-19 03:30:57 +00001194 binary insertion. This sort is stable.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001195 On entry, must have lo <= start <= hi, and that [lo, start) is already
1196 sorted (pass start == lo if you don't know!).
Tim Petersa8c974c2002-07-19 03:30:57 +00001197 If islt() complains return -1, else 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001198 Even in case of error, the output slice will be some permutation of
1199 the input (nothing is lost or duplicated).
1200*/
Guido van Rossum3f236de1996-12-10 23:55:39 +00001201static int
embg1e34da42018-01-28 20:03:23 -07001202binarysort(MergeState *ms, sortslice lo, PyObject **hi, PyObject **start)
Guido van Rossum3f236de1996-12-10 23:55:39 +00001203{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001204 Py_ssize_t k;
1205 PyObject **l, **p, **r;
1206 PyObject *pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001207
Daniel Stutzbach98338222010-12-02 21:55:33 +00001208 assert(lo.keys <= start && start <= hi);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 /* assert [lo, start) is sorted */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001210 if (lo.keys == start)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001211 ++start;
1212 for (; start < hi; ++start) {
1213 /* set l to where *start belongs */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001214 l = lo.keys;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001215 r = start;
1216 pivot = *r;
1217 /* Invariants:
1218 * pivot >= all in [lo, l).
1219 * pivot < all in [r, start).
1220 * The second is vacuously true at the start.
1221 */
1222 assert(l < r);
1223 do {
1224 p = l + ((r - l) >> 1);
1225 IFLT(pivot, *p)
1226 r = p;
1227 else
1228 l = p+1;
1229 } while (l < r);
1230 assert(l == r);
1231 /* The invariants still hold, so pivot >= all in [lo, l) and
1232 pivot < all in [l, start), so pivot belongs at l. Note
1233 that if there are elements equal to pivot, l points to the
1234 first slot after them -- that's why this sort is stable.
1235 Slide over to make room.
1236 Caution: using memmove is much slower under MSVC 5;
1237 we're not usually moving many slots. */
1238 for (p = start; p > l; --p)
1239 *p = *(p-1);
1240 *l = pivot;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001241 if (lo.values != NULL) {
1242 Py_ssize_t offset = lo.values - lo.keys;
1243 p = start + offset;
1244 pivot = *p;
1245 l += offset;
1246 for (p = start + offset; p > l; --p)
1247 *p = *(p-1);
1248 *l = pivot;
1249 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001250 }
1251 return 0;
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001252
1253 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001254 return -1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001255}
1256
Tim Petersa64dc242002-08-01 02:13:36 +00001257/*
1258Return the length of the run beginning at lo, in the slice [lo, hi). lo < hi
1259is required on entry. "A run" is the longest ascending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001260
Tim Petersa64dc242002-08-01 02:13:36 +00001261 lo[0] <= lo[1] <= lo[2] <= ...
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001262
Tim Petersa64dc242002-08-01 02:13:36 +00001263or the longest descending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001264
Tim Petersa64dc242002-08-01 02:13:36 +00001265 lo[0] > lo[1] > lo[2] > ...
Tim Peters3b01a122002-07-19 02:35:45 +00001266
Tim Petersa64dc242002-08-01 02:13:36 +00001267Boolean *descending is set to 0 in the former case, or to 1 in the latter.
1268For its intended use in a stable mergesort, the strictness of the defn of
1269"descending" is needed so that the caller can safely reverse a descending
1270sequence without violating stability (strict > ensures there are no equal
1271elements to get out of order).
1272
1273Returns -1 in case of error.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001274*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001275static Py_ssize_t
embg1e34da42018-01-28 20:03:23 -07001276count_run(MergeState *ms, PyObject **lo, PyObject **hi, int *descending)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001277{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001278 Py_ssize_t k;
1279 Py_ssize_t n;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001281 assert(lo < hi);
1282 *descending = 0;
1283 ++lo;
1284 if (lo == hi)
1285 return 1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001287 n = 2;
1288 IFLT(*lo, *(lo-1)) {
1289 *descending = 1;
1290 for (lo = lo+1; lo < hi; ++lo, ++n) {
1291 IFLT(*lo, *(lo-1))
1292 ;
1293 else
1294 break;
1295 }
1296 }
1297 else {
1298 for (lo = lo+1; lo < hi; ++lo, ++n) {
1299 IFLT(*lo, *(lo-1))
1300 break;
1301 }
1302 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001304 return n;
Tim Petersa64dc242002-08-01 02:13:36 +00001305fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001306 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001307}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001308
Tim Petersa64dc242002-08-01 02:13:36 +00001309/*
1310Locate the proper position of key in a sorted vector; if the vector contains
1311an element equal to key, return the position immediately to the left of
1312the leftmost equal element. [gallop_right() does the same except returns
1313the position to the right of the rightmost equal element (if any).]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001314
Tim Petersa64dc242002-08-01 02:13:36 +00001315"a" is a sorted vector with n elements, starting at a[0]. n must be > 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001316
Tim Petersa64dc242002-08-01 02:13:36 +00001317"hint" is an index at which to begin the search, 0 <= hint < n. The closer
1318hint is to the final result, the faster this runs.
1319
1320The return value is the int k in 0..n such that
1321
1322 a[k-1] < key <= a[k]
1323
1324pretending that *(a-1) is minus infinity and a[n] is plus infinity. IOW,
1325key belongs at index k; or, IOW, the first k elements of a should precede
1326key, and the last n-k should follow key.
1327
1328Returns -1 on error. See listsort.txt for info on the method.
1329*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001330static Py_ssize_t
embg1e34da42018-01-28 20:03:23 -07001331gallop_left(MergeState *ms, PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint)
Tim Petersa64dc242002-08-01 02:13:36 +00001332{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001333 Py_ssize_t ofs;
1334 Py_ssize_t lastofs;
1335 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001337 assert(key && a && n > 0 && hint >= 0 && hint < n);
Tim Petersa64dc242002-08-01 02:13:36 +00001338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001339 a += hint;
1340 lastofs = 0;
1341 ofs = 1;
1342 IFLT(*a, key) {
1343 /* a[hint] < key -- gallop right, until
1344 * a[hint + lastofs] < key <= a[hint + ofs]
1345 */
1346 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
1347 while (ofs < maxofs) {
1348 IFLT(a[ofs], key) {
1349 lastofs = ofs;
Alexey Izbyshev6bc59172019-05-23 03:01:08 +03001350 assert(ofs <= (PY_SSIZE_T_MAX - 1) / 2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001351 ofs = (ofs << 1) + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001352 }
1353 else /* key <= a[hint + ofs] */
1354 break;
1355 }
1356 if (ofs > maxofs)
1357 ofs = maxofs;
1358 /* Translate back to offsets relative to &a[0]. */
1359 lastofs += hint;
1360 ofs += hint;
1361 }
1362 else {
1363 /* key <= a[hint] -- gallop left, until
1364 * a[hint - ofs] < key <= a[hint - lastofs]
1365 */
1366 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
1367 while (ofs < maxofs) {
1368 IFLT(*(a-ofs), key)
1369 break;
1370 /* key <= a[hint - ofs] */
1371 lastofs = ofs;
Alexey Izbyshev6bc59172019-05-23 03:01:08 +03001372 assert(ofs <= (PY_SSIZE_T_MAX - 1) / 2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001373 ofs = (ofs << 1) + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001374 }
1375 if (ofs > maxofs)
1376 ofs = maxofs;
1377 /* Translate back to positive offsets relative to &a[0]. */
1378 k = lastofs;
1379 lastofs = hint - ofs;
1380 ofs = hint - k;
1381 }
1382 a -= hint;
Tim Petersa64dc242002-08-01 02:13:36 +00001383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001384 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1385 /* Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the
1386 * right of lastofs but no farther right than ofs. Do a binary
1387 * search, with invariant a[lastofs-1] < key <= a[ofs].
1388 */
1389 ++lastofs;
1390 while (lastofs < ofs) {
1391 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001393 IFLT(a[m], key)
1394 lastofs = m+1; /* a[m] < key */
1395 else
1396 ofs = m; /* key <= a[m] */
1397 }
1398 assert(lastofs == ofs); /* so a[ofs-1] < key <= a[ofs] */
1399 return ofs;
Tim Petersa64dc242002-08-01 02:13:36 +00001400
1401fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001402 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001403}
1404
1405/*
1406Exactly like gallop_left(), except that if key already exists in a[0:n],
1407finds the position immediately to the right of the rightmost equal value.
1408
1409The return value is the int k in 0..n such that
1410
1411 a[k-1] <= key < a[k]
1412
1413or -1 if error.
1414
1415The code duplication is massive, but this is enough different given that
1416we're sticking to "<" comparisons that it's much harder to follow if
1417written as one routine with yet another "left or right?" flag.
1418*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001419static Py_ssize_t
embg1e34da42018-01-28 20:03:23 -07001420gallop_right(MergeState *ms, PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint)
Tim Petersa64dc242002-08-01 02:13:36 +00001421{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001422 Py_ssize_t ofs;
1423 Py_ssize_t lastofs;
1424 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001426 assert(key && a && n > 0 && hint >= 0 && hint < n);
Tim Petersa64dc242002-08-01 02:13:36 +00001427
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001428 a += hint;
1429 lastofs = 0;
1430 ofs = 1;
1431 IFLT(key, *a) {
1432 /* key < a[hint] -- gallop left, until
1433 * a[hint - ofs] <= key < a[hint - lastofs]
1434 */
1435 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
1436 while (ofs < maxofs) {
1437 IFLT(key, *(a-ofs)) {
1438 lastofs = ofs;
Alexey Izbyshev6bc59172019-05-23 03:01:08 +03001439 assert(ofs <= (PY_SSIZE_T_MAX - 1) / 2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001440 ofs = (ofs << 1) + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001441 }
1442 else /* a[hint - ofs] <= key */
1443 break;
1444 }
1445 if (ofs > maxofs)
1446 ofs = maxofs;
1447 /* Translate back to positive offsets relative to &a[0]. */
1448 k = lastofs;
1449 lastofs = hint - ofs;
1450 ofs = hint - k;
1451 }
1452 else {
1453 /* a[hint] <= key -- gallop right, until
1454 * a[hint + lastofs] <= key < a[hint + ofs]
1455 */
1456 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
1457 while (ofs < maxofs) {
1458 IFLT(key, a[ofs])
1459 break;
1460 /* a[hint + ofs] <= key */
1461 lastofs = ofs;
Alexey Izbyshev6bc59172019-05-23 03:01:08 +03001462 assert(ofs <= (PY_SSIZE_T_MAX - 1) / 2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001463 ofs = (ofs << 1) + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001464 }
1465 if (ofs > maxofs)
1466 ofs = maxofs;
1467 /* Translate back to offsets relative to &a[0]. */
1468 lastofs += hint;
1469 ofs += hint;
1470 }
1471 a -= hint;
Tim Petersa64dc242002-08-01 02:13:36 +00001472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001473 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1474 /* Now a[lastofs] <= key < a[ofs], so key belongs somewhere to the
1475 * right of lastofs but no farther right than ofs. Do a binary
1476 * search, with invariant a[lastofs-1] <= key < a[ofs].
1477 */
1478 ++lastofs;
1479 while (lastofs < ofs) {
1480 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001482 IFLT(key, a[m])
1483 ofs = m; /* key < a[m] */
1484 else
1485 lastofs = m+1; /* a[m] <= key */
1486 }
1487 assert(lastofs == ofs); /* so a[ofs-1] <= key < a[ofs] */
1488 return ofs;
Tim Petersa64dc242002-08-01 02:13:36 +00001489
1490fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001491 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001492}
1493
Tim Petersa64dc242002-08-01 02:13:36 +00001494/* Conceptually a MergeState's constructor. */
1495static void
Victor Stinner0fcab4a2011-01-04 12:59:15 +00001496merge_init(MergeState *ms, Py_ssize_t list_size, int has_keyfunc)
Tim Petersa64dc242002-08-01 02:13:36 +00001497{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001498 assert(ms != NULL);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001499 if (has_keyfunc) {
1500 /* The temporary space for merging will need at most half the list
1501 * size rounded up. Use the minimum possible space so we can use the
1502 * rest of temparray for other things. In particular, if there is
1503 * enough extra space, listsort() will use it to store the keys.
1504 */
1505 ms->alloced = (list_size + 1) / 2;
1506
1507 /* ms->alloced describes how many keys will be stored at
1508 ms->temparray, but we also need to store the values. Hence,
1509 ms->alloced is capped at half of MERGESTATE_TEMP_SIZE. */
1510 if (MERGESTATE_TEMP_SIZE / 2 < ms->alloced)
1511 ms->alloced = MERGESTATE_TEMP_SIZE / 2;
1512 ms->a.values = &ms->temparray[ms->alloced];
1513 }
1514 else {
1515 ms->alloced = MERGESTATE_TEMP_SIZE;
1516 ms->a.values = NULL;
1517 }
1518 ms->a.keys = ms->temparray;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001519 ms->n = 0;
1520 ms->min_gallop = MIN_GALLOP;
Tim Petersa64dc242002-08-01 02:13:36 +00001521}
1522
1523/* Free all the temp memory owned by the MergeState. This must be called
1524 * when you're done with a MergeState, and may be called before then if
1525 * you want to free the temp memory early.
1526 */
1527static void
1528merge_freemem(MergeState *ms)
1529{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001530 assert(ms != NULL);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001531 if (ms->a.keys != ms->temparray)
1532 PyMem_Free(ms->a.keys);
Tim Petersa64dc242002-08-01 02:13:36 +00001533}
1534
1535/* Ensure enough temp memory for 'need' array slots is available.
1536 * Returns 0 on success and -1 if the memory can't be gotten.
1537 */
1538static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001539merge_getmem(MergeState *ms, Py_ssize_t need)
Tim Petersa64dc242002-08-01 02:13:36 +00001540{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001541 int multiplier;
1542
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001543 assert(ms != NULL);
1544 if (need <= ms->alloced)
1545 return 0;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001546
1547 multiplier = ms->a.values != NULL ? 2 : 1;
1548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001549 /* Don't realloc! That can cost cycles to copy the old data, but
1550 * we don't care what's in the block.
1551 */
1552 merge_freemem(ms);
embg1e34da42018-01-28 20:03:23 -07001553 if ((size_t)need > PY_SSIZE_T_MAX / sizeof(PyObject *) / multiplier) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001554 PyErr_NoMemory();
1555 return -1;
1556 }
embg1e34da42018-01-28 20:03:23 -07001557 ms->a.keys = (PyObject **)PyMem_Malloc(multiplier * need
Daniel Stutzbach98338222010-12-02 21:55:33 +00001558 * sizeof(PyObject *));
1559 if (ms->a.keys != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001560 ms->alloced = need;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001561 if (ms->a.values != NULL)
1562 ms->a.values = &ms->a.keys[need];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001563 return 0;
1564 }
1565 PyErr_NoMemory();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001566 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001567}
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001568#define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 : \
1569 merge_getmem(MS, NEED))
Tim Petersa64dc242002-08-01 02:13:36 +00001570
Daniel Stutzbach98338222010-12-02 21:55:33 +00001571/* Merge the na elements starting at ssa with the nb elements starting at
1572 * ssb.keys = ssa.keys + na in a stable way, in-place. na and nb must be > 0.
1573 * Must also have that ssa.keys[na-1] belongs at the end of the merge, and
1574 * should have na <= nb. See listsort.txt for more info. Return 0 if
1575 * successful, -1 if error.
Tim Petersa64dc242002-08-01 02:13:36 +00001576 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001577static Py_ssize_t
Daniel Stutzbach98338222010-12-02 21:55:33 +00001578merge_lo(MergeState *ms, sortslice ssa, Py_ssize_t na,
1579 sortslice ssb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001580{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001581 Py_ssize_t k;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001582 sortslice dest;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001583 int result = -1; /* guilty until proved innocent */
1584 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001585
Daniel Stutzbach98338222010-12-02 21:55:33 +00001586 assert(ms && ssa.keys && ssb.keys && na > 0 && nb > 0);
1587 assert(ssa.keys + na == ssb.keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001588 if (MERGE_GETMEM(ms, na) < 0)
1589 return -1;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001590 sortslice_memcpy(&ms->a, 0, &ssa, 0, na);
1591 dest = ssa;
1592 ssa = ms->a;
Tim Petersa64dc242002-08-01 02:13:36 +00001593
Daniel Stutzbach98338222010-12-02 21:55:33 +00001594 sortslice_copy_incr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001595 --nb;
1596 if (nb == 0)
1597 goto Succeed;
1598 if (na == 1)
1599 goto CopyB;
Tim Petersa64dc242002-08-01 02:13:36 +00001600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001601 min_gallop = ms->min_gallop;
1602 for (;;) {
1603 Py_ssize_t acount = 0; /* # of times A won in a row */
1604 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001606 /* Do the straightforward thing until (if ever) one run
1607 * appears to win consistently.
1608 */
1609 for (;;) {
1610 assert(na > 1 && nb > 0);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001611 k = ISLT(ssb.keys[0], ssa.keys[0]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001612 if (k) {
1613 if (k < 0)
1614 goto Fail;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001615 sortslice_copy_incr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001616 ++bcount;
1617 acount = 0;
1618 --nb;
1619 if (nb == 0)
1620 goto Succeed;
1621 if (bcount >= min_gallop)
1622 break;
1623 }
1624 else {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001625 sortslice_copy_incr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001626 ++acount;
1627 bcount = 0;
1628 --na;
1629 if (na == 1)
1630 goto CopyB;
1631 if (acount >= min_gallop)
1632 break;
1633 }
1634 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001636 /* One run is winning so consistently that galloping may
1637 * be a huge win. So try that, and continue galloping until
1638 * (if ever) neither run appears to be winning consistently
1639 * anymore.
1640 */
1641 ++min_gallop;
1642 do {
1643 assert(na > 1 && nb > 0);
1644 min_gallop -= min_gallop > 1;
1645 ms->min_gallop = min_gallop;
embg1e34da42018-01-28 20:03:23 -07001646 k = gallop_right(ms, ssb.keys[0], ssa.keys, na, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001647 acount = k;
1648 if (k) {
1649 if (k < 0)
1650 goto Fail;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001651 sortslice_memcpy(&dest, 0, &ssa, 0, k);
1652 sortslice_advance(&dest, k);
1653 sortslice_advance(&ssa, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001654 na -= k;
1655 if (na == 1)
1656 goto CopyB;
1657 /* na==0 is impossible now if the comparison
1658 * function is consistent, but we can't assume
1659 * that it is.
1660 */
1661 if (na == 0)
1662 goto Succeed;
1663 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001664 sortslice_copy_incr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001665 --nb;
1666 if (nb == 0)
1667 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001668
embg1e34da42018-01-28 20:03:23 -07001669 k = gallop_left(ms, ssa.keys[0], ssb.keys, nb, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001670 bcount = k;
1671 if (k) {
1672 if (k < 0)
1673 goto Fail;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001674 sortslice_memmove(&dest, 0, &ssb, 0, k);
1675 sortslice_advance(&dest, k);
1676 sortslice_advance(&ssb, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001677 nb -= k;
1678 if (nb == 0)
1679 goto Succeed;
1680 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001681 sortslice_copy_incr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001682 --na;
1683 if (na == 1)
1684 goto CopyB;
1685 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
1686 ++min_gallop; /* penalize it for leaving galloping mode */
1687 ms->min_gallop = min_gallop;
1688 }
Tim Petersa64dc242002-08-01 02:13:36 +00001689Succeed:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001690 result = 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001691Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001692 if (na)
Daniel Stutzbach98338222010-12-02 21:55:33 +00001693 sortslice_memcpy(&dest, 0, &ssa, 0, na);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001694 return result;
Tim Petersa64dc242002-08-01 02:13:36 +00001695CopyB:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001696 assert(na == 1 && nb > 0);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001697 /* The last element of ssa belongs at the end of the merge. */
1698 sortslice_memmove(&dest, 0, &ssb, 0, nb);
1699 sortslice_copy(&dest, nb, &ssa, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001700 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001701}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001702
Daniel Stutzbach98338222010-12-02 21:55:33 +00001703/* Merge the na elements starting at pa with the nb elements starting at
1704 * ssb.keys = ssa.keys + na in a stable way, in-place. na and nb must be > 0.
1705 * Must also have that ssa.keys[na-1] belongs at the end of the merge, and
1706 * should have na >= nb. See listsort.txt for more info. Return 0 if
1707 * successful, -1 if error.
Tim Petersa64dc242002-08-01 02:13:36 +00001708 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001709static Py_ssize_t
Daniel Stutzbach98338222010-12-02 21:55:33 +00001710merge_hi(MergeState *ms, sortslice ssa, Py_ssize_t na,
1711 sortslice ssb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001712{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001713 Py_ssize_t k;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001714 sortslice dest, basea, baseb;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001715 int result = -1; /* guilty until proved innocent */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001716 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001717
Daniel Stutzbach98338222010-12-02 21:55:33 +00001718 assert(ms && ssa.keys && ssb.keys && na > 0 && nb > 0);
1719 assert(ssa.keys + na == ssb.keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001720 if (MERGE_GETMEM(ms, nb) < 0)
1721 return -1;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001722 dest = ssb;
1723 sortslice_advance(&dest, nb-1);
1724 sortslice_memcpy(&ms->a, 0, &ssb, 0, nb);
1725 basea = ssa;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001726 baseb = ms->a;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001727 ssb.keys = ms->a.keys + nb - 1;
1728 if (ssb.values != NULL)
1729 ssb.values = ms->a.values + nb - 1;
1730 sortslice_advance(&ssa, na - 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001731
Daniel Stutzbach98338222010-12-02 21:55:33 +00001732 sortslice_copy_decr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001733 --na;
1734 if (na == 0)
1735 goto Succeed;
1736 if (nb == 1)
1737 goto CopyA;
Tim Petersa64dc242002-08-01 02:13:36 +00001738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001739 min_gallop = ms->min_gallop;
1740 for (;;) {
1741 Py_ssize_t acount = 0; /* # of times A won in a row */
1742 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001744 /* Do the straightforward thing until (if ever) one run
1745 * appears to win consistently.
1746 */
1747 for (;;) {
1748 assert(na > 0 && nb > 1);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001749 k = ISLT(ssb.keys[0], ssa.keys[0]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001750 if (k) {
1751 if (k < 0)
1752 goto Fail;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001753 sortslice_copy_decr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001754 ++acount;
1755 bcount = 0;
1756 --na;
1757 if (na == 0)
1758 goto Succeed;
1759 if (acount >= min_gallop)
1760 break;
1761 }
1762 else {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001763 sortslice_copy_decr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001764 ++bcount;
1765 acount = 0;
1766 --nb;
1767 if (nb == 1)
1768 goto CopyA;
1769 if (bcount >= min_gallop)
1770 break;
1771 }
1772 }
Tim Petersa64dc242002-08-01 02:13:36 +00001773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001774 /* One run is winning so consistently that galloping may
1775 * be a huge win. So try that, and continue galloping until
1776 * (if ever) neither run appears to be winning consistently
1777 * anymore.
1778 */
1779 ++min_gallop;
1780 do {
1781 assert(na > 0 && nb > 1);
1782 min_gallop -= min_gallop > 1;
1783 ms->min_gallop = min_gallop;
embg1e34da42018-01-28 20:03:23 -07001784 k = gallop_right(ms, ssb.keys[0], basea.keys, na, na-1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001785 if (k < 0)
1786 goto Fail;
1787 k = na - k;
1788 acount = k;
1789 if (k) {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001790 sortslice_advance(&dest, -k);
1791 sortslice_advance(&ssa, -k);
1792 sortslice_memmove(&dest, 1, &ssa, 1, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001793 na -= k;
1794 if (na == 0)
1795 goto Succeed;
1796 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001797 sortslice_copy_decr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001798 --nb;
1799 if (nb == 1)
1800 goto CopyA;
Tim Petersa64dc242002-08-01 02:13:36 +00001801
embg1e34da42018-01-28 20:03:23 -07001802 k = gallop_left(ms, ssa.keys[0], baseb.keys, nb, nb-1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001803 if (k < 0)
1804 goto Fail;
1805 k = nb - k;
1806 bcount = k;
1807 if (k) {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001808 sortslice_advance(&dest, -k);
1809 sortslice_advance(&ssb, -k);
1810 sortslice_memcpy(&dest, 1, &ssb, 1, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001811 nb -= k;
1812 if (nb == 1)
1813 goto CopyA;
1814 /* nb==0 is impossible now if the comparison
1815 * function is consistent, but we can't assume
1816 * that it is.
1817 */
1818 if (nb == 0)
1819 goto Succeed;
1820 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001821 sortslice_copy_decr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001822 --na;
1823 if (na == 0)
1824 goto Succeed;
1825 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
1826 ++min_gallop; /* penalize it for leaving galloping mode */
1827 ms->min_gallop = min_gallop;
1828 }
Tim Petersa64dc242002-08-01 02:13:36 +00001829Succeed:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001830 result = 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001831Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001832 if (nb)
Daniel Stutzbach98338222010-12-02 21:55:33 +00001833 sortslice_memcpy(&dest, -(nb-1), &baseb, 0, nb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001834 return result;
Tim Petersa64dc242002-08-01 02:13:36 +00001835CopyA:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001836 assert(nb == 1 && na > 0);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001837 /* The first element of ssb belongs at the front of the merge. */
1838 sortslice_memmove(&dest, 1-na, &ssa, 1-na, na);
1839 sortslice_advance(&dest, -na);
1840 sortslice_advance(&ssa, -na);
1841 sortslice_copy(&dest, 0, &ssb, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001842 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001843}
1844
1845/* Merge the two runs at stack indices i and i+1.
1846 * Returns 0 on success, -1 on error.
1847 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001848static Py_ssize_t
1849merge_at(MergeState *ms, Py_ssize_t i)
Tim Petersa64dc242002-08-01 02:13:36 +00001850{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001851 sortslice ssa, ssb;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001852 Py_ssize_t na, nb;
1853 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001855 assert(ms != NULL);
1856 assert(ms->n >= 2);
1857 assert(i >= 0);
1858 assert(i == ms->n - 2 || i == ms->n - 3);
Tim Petersa64dc242002-08-01 02:13:36 +00001859
Daniel Stutzbach98338222010-12-02 21:55:33 +00001860 ssa = ms->pending[i].base;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001861 na = ms->pending[i].len;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001862 ssb = ms->pending[i+1].base;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001863 nb = ms->pending[i+1].len;
1864 assert(na > 0 && nb > 0);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001865 assert(ssa.keys + na == ssb.keys);
Tim Petersa64dc242002-08-01 02:13:36 +00001866
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001867 /* Record the length of the combined runs; if i is the 3rd-last
1868 * run now, also slide over the last run (which isn't involved
1869 * in this merge). The current run i+1 goes away in any case.
1870 */
1871 ms->pending[i].len = na + nb;
1872 if (i == ms->n - 3)
1873 ms->pending[i+1] = ms->pending[i+2];
1874 --ms->n;
Tim Petersa64dc242002-08-01 02:13:36 +00001875
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001876 /* Where does b start in a? Elements in a before that can be
1877 * ignored (already in place).
1878 */
embg1e34da42018-01-28 20:03:23 -07001879 k = gallop_right(ms, *ssb.keys, ssa.keys, na, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001880 if (k < 0)
1881 return -1;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001882 sortslice_advance(&ssa, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001883 na -= k;
1884 if (na == 0)
1885 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001886
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001887 /* Where does a end in b? Elements in b after that can be
1888 * ignored (already in place).
1889 */
embg1e34da42018-01-28 20:03:23 -07001890 nb = gallop_left(ms, ssa.keys[na-1], ssb.keys, nb, nb-1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001891 if (nb <= 0)
1892 return nb;
Tim Petersa64dc242002-08-01 02:13:36 +00001893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001894 /* Merge what remains of the runs, using a temp array with
1895 * min(na, nb) elements.
1896 */
1897 if (na <= nb)
Daniel Stutzbach98338222010-12-02 21:55:33 +00001898 return merge_lo(ms, ssa, na, ssb, nb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001899 else
Daniel Stutzbach98338222010-12-02 21:55:33 +00001900 return merge_hi(ms, ssa, na, ssb, nb);
Tim Petersa64dc242002-08-01 02:13:36 +00001901}
1902
1903/* Examine the stack of runs waiting to be merged, merging adjacent runs
1904 * until the stack invariants are re-established:
1905 *
1906 * 1. len[-3] > len[-2] + len[-1]
1907 * 2. len[-2] > len[-1]
1908 *
1909 * See listsort.txt for more info.
1910 *
1911 * Returns 0 on success, -1 on error.
1912 */
1913static int
1914merge_collapse(MergeState *ms)
1915{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001916 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001918 assert(ms);
1919 while (ms->n > 1) {
1920 Py_ssize_t n = ms->n - 2;
Benjamin Petersonb808d592015-02-25 10:12:26 -05001921 if ((n > 0 && p[n-1].len <= p[n].len + p[n+1].len) ||
1922 (n > 1 && p[n-2].len <= p[n-1].len + p[n].len)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001923 if (p[n-1].len < p[n+1].len)
1924 --n;
1925 if (merge_at(ms, n) < 0)
1926 return -1;
1927 }
1928 else if (p[n].len <= p[n+1].len) {
embg1e34da42018-01-28 20:03:23 -07001929 if (merge_at(ms, n) < 0)
1930 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001931 }
1932 else
1933 break;
1934 }
1935 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001936}
1937
1938/* Regardless of invariants, merge all runs on the stack until only one
1939 * remains. This is used at the end of the mergesort.
1940 *
1941 * Returns 0 on success, -1 on error.
1942 */
1943static int
1944merge_force_collapse(MergeState *ms)
1945{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001946 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001947
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001948 assert(ms);
1949 while (ms->n > 1) {
1950 Py_ssize_t n = ms->n - 2;
1951 if (n > 0 && p[n-1].len < p[n+1].len)
1952 --n;
1953 if (merge_at(ms, n) < 0)
1954 return -1;
1955 }
1956 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001957}
1958
1959/* Compute a good value for the minimum run length; natural runs shorter
1960 * than this are boosted artificially via binary insertion.
1961 *
1962 * If n < 64, return n (it's too small to bother with fancy stuff).
1963 * Else if n is an exact power of 2, return 32.
1964 * Else return an int k, 32 <= k <= 64, such that n/k is close to, but
1965 * strictly less than, an exact power of 2.
1966 *
1967 * See listsort.txt for more info.
1968 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001969static Py_ssize_t
1970merge_compute_minrun(Py_ssize_t n)
Tim Petersa64dc242002-08-01 02:13:36 +00001971{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001972 Py_ssize_t r = 0; /* becomes 1 if any 1 bits are shifted off */
Tim Petersa64dc242002-08-01 02:13:36 +00001973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001974 assert(n >= 0);
1975 while (n >= 64) {
1976 r |= n & 1;
1977 n >>= 1;
1978 }
1979 return n + r;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001980}
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001981
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001982static void
Daniel Stutzbach98338222010-12-02 21:55:33 +00001983reverse_sortslice(sortslice *s, Py_ssize_t n)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001984{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001985 reverse_slice(s->keys, &s->keys[n]);
1986 if (s->values != NULL)
1987 reverse_slice(s->values, &s->values[n]);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001988}
1989
embg1e34da42018-01-28 20:03:23 -07001990/* Here we define custom comparison functions to optimize for the cases one commonly
1991 * encounters in practice: homogeneous lists, often of one of the basic types. */
1992
1993/* This struct holds the comparison function and helper functions
1994 * selected in the pre-sort check. */
1995
1996/* These are the special case compare functions.
1997 * ms->key_compare will always point to one of these: */
1998
1999/* Heterogeneous compare: default, always safe to fall back on. */
2000static int
2001safe_object_compare(PyObject *v, PyObject *w, MergeState *ms)
2002{
2003 /* No assumptions necessary! */
2004 return PyObject_RichCompareBool(v, w, Py_LT);
2005}
2006
2007/* Homogeneous compare: safe for any two compareable objects of the same type.
2008 * (ms->key_richcompare is set to ob_type->tp_richcompare in the
2009 * pre-sort check.)
2010 */
2011static int
2012unsafe_object_compare(PyObject *v, PyObject *w, MergeState *ms)
2013{
2014 PyObject *res_obj; int res;
2015
2016 /* No assumptions, because we check first: */
Victor Stinner58ac7002020-02-07 03:04:21 +01002017 if (Py_TYPE(v)->tp_richcompare != ms->key_richcompare)
embg1e34da42018-01-28 20:03:23 -07002018 return PyObject_RichCompareBool(v, w, Py_LT);
2019
2020 assert(ms->key_richcompare != NULL);
2021 res_obj = (*(ms->key_richcompare))(v, w, Py_LT);
2022
2023 if (res_obj == Py_NotImplemented) {
2024 Py_DECREF(res_obj);
2025 return PyObject_RichCompareBool(v, w, Py_LT);
2026 }
2027 if (res_obj == NULL)
2028 return -1;
2029
2030 if (PyBool_Check(res_obj)) {
2031 res = (res_obj == Py_True);
2032 }
2033 else {
2034 res = PyObject_IsTrue(res_obj);
2035 }
2036 Py_DECREF(res_obj);
2037
2038 /* Note that we can't assert
2039 * res == PyObject_RichCompareBool(v, w, Py_LT);
2040 * because of evil compare functions like this:
2041 * lambda a, b: int(random.random() * 3) - 1)
2042 * (which is actually in test_sort.py) */
2043 return res;
2044}
2045
2046/* Latin string compare: safe for any two latin (one byte per char) strings. */
2047static int
2048unsafe_latin_compare(PyObject *v, PyObject *w, MergeState *ms)
2049{
Victor Stinner8017b802018-01-29 13:47:06 +01002050 Py_ssize_t len;
2051 int res;
embg1e34da42018-01-28 20:03:23 -07002052
2053 /* Modified from Objects/unicodeobject.c:unicode_compare, assuming: */
Andy Lesterdffe4c02020-03-04 07:15:20 -06002054 assert(Py_IS_TYPE(v, &PyUnicode_Type));
2055 assert(Py_IS_TYPE(w, &PyUnicode_Type));
embg1e34da42018-01-28 20:03:23 -07002056 assert(PyUnicode_KIND(v) == PyUnicode_KIND(w));
2057 assert(PyUnicode_KIND(v) == PyUnicode_1BYTE_KIND);
2058
2059 len = Py_MIN(PyUnicode_GET_LENGTH(v), PyUnicode_GET_LENGTH(w));
2060 res = memcmp(PyUnicode_DATA(v), PyUnicode_DATA(w), len);
2061
2062 res = (res != 0 ?
2063 res < 0 :
2064 PyUnicode_GET_LENGTH(v) < PyUnicode_GET_LENGTH(w));
2065
2066 assert(res == PyObject_RichCompareBool(v, w, Py_LT));;
2067 return res;
2068}
2069
2070/* Bounded int compare: compare any two longs that fit in a single machine word. */
2071static int
2072unsafe_long_compare(PyObject *v, PyObject *w, MergeState *ms)
2073{
2074 PyLongObject *vl, *wl; sdigit v0, w0; int res;
2075
2076 /* Modified from Objects/longobject.c:long_compare, assuming: */
Andy Lesterdffe4c02020-03-04 07:15:20 -06002077 assert(Py_IS_TYPE(v, &PyLong_Type));
2078 assert(Py_IS_TYPE(w, &PyLong_Type));
embg1e34da42018-01-28 20:03:23 -07002079 assert(Py_ABS(Py_SIZE(v)) <= 1);
2080 assert(Py_ABS(Py_SIZE(w)) <= 1);
2081
2082 vl = (PyLongObject*)v;
2083 wl = (PyLongObject*)w;
2084
2085 v0 = Py_SIZE(vl) == 0 ? 0 : (sdigit)vl->ob_digit[0];
2086 w0 = Py_SIZE(wl) == 0 ? 0 : (sdigit)wl->ob_digit[0];
2087
2088 if (Py_SIZE(vl) < 0)
2089 v0 = -v0;
2090 if (Py_SIZE(wl) < 0)
2091 w0 = -w0;
2092
2093 res = v0 < w0;
2094 assert(res == PyObject_RichCompareBool(v, w, Py_LT));
2095 return res;
2096}
2097
2098/* Float compare: compare any two floats. */
2099static int
2100unsafe_float_compare(PyObject *v, PyObject *w, MergeState *ms)
2101{
2102 int res;
2103
2104 /* Modified from Objects/floatobject.c:float_richcompare, assuming: */
Andy Lesterdffe4c02020-03-04 07:15:20 -06002105 assert(Py_IS_TYPE(v, &PyFloat_Type));
2106 assert(Py_IS_TYPE(w, &PyFloat_Type));
embg1e34da42018-01-28 20:03:23 -07002107
2108 res = PyFloat_AS_DOUBLE(v) < PyFloat_AS_DOUBLE(w);
2109 assert(res == PyObject_RichCompareBool(v, w, Py_LT));
2110 return res;
2111}
2112
2113/* Tuple compare: compare *any* two tuples, using
2114 * ms->tuple_elem_compare to compare the first elements, which is set
2115 * using the same pre-sort check as we use for ms->key_compare,
2116 * but run on the list [x[0] for x in L]. This allows us to optimize compares
2117 * on two levels (as long as [x[0] for x in L] is type-homogeneous.) The idea is
2118 * that most tuple compares don't involve x[1:]. */
2119static int
2120unsafe_tuple_compare(PyObject *v, PyObject *w, MergeState *ms)
2121{
2122 PyTupleObject *vt, *wt;
2123 Py_ssize_t i, vlen, wlen;
2124 int k;
2125
2126 /* Modified from Objects/tupleobject.c:tuplerichcompare, assuming: */
Andy Lesterdffe4c02020-03-04 07:15:20 -06002127 assert(Py_IS_TYPE(v, &PyTuple_Type));
2128 assert(Py_IS_TYPE(w, &PyTuple_Type));
embg1e34da42018-01-28 20:03:23 -07002129 assert(Py_SIZE(v) > 0);
2130 assert(Py_SIZE(w) > 0);
2131
2132 vt = (PyTupleObject *)v;
2133 wt = (PyTupleObject *)w;
2134
2135 vlen = Py_SIZE(vt);
2136 wlen = Py_SIZE(wt);
2137
2138 for (i = 0; i < vlen && i < wlen; i++) {
2139 k = PyObject_RichCompareBool(vt->ob_item[i], wt->ob_item[i], Py_EQ);
2140 if (k < 0)
2141 return -1;
2142 if (!k)
2143 break;
2144 }
2145
2146 if (i >= vlen || i >= wlen)
2147 return vlen < wlen;
2148
2149 if (i == 0)
2150 return ms->tuple_elem_compare(vt->ob_item[i], wt->ob_item[i], ms);
2151 else
2152 return PyObject_RichCompareBool(vt->ob_item[i], wt->ob_item[i], Py_LT);
2153}
2154
Tim Petersa64dc242002-08-01 02:13:36 +00002155/* An adaptive, stable, natural mergesort. See listsort.txt.
2156 * Returns Py_None on success, NULL on error. Even in case of error, the
2157 * list will be some permutation of its input state (nothing is lost or
2158 * duplicated).
2159 */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002160/*[clinic input]
2161list.sort
2162
2163 *
2164 key as keyfunc: object = None
Serhiy Storchaka202fda52017-03-12 10:10:47 +02002165 reverse: bool(accept={int}) = False
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002166
Tim Hoffmann5c224762019-06-01 06:10:02 +02002167Sort the list in ascending order and return None.
2168
2169The sort is in-place (i.e. the list itself is modified) and stable (i.e. the
2170order of two equal elements is maintained).
2171
2172If a key function is given, apply it once to each list item and sort them,
2173ascending or descending, according to their function values.
2174
2175The reverse flag can be set to sort in descending order.
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002176[clinic start generated code]*/
2177
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002178static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002179list_sort_impl(PyListObject *self, PyObject *keyfunc, int reverse)
Tim Hoffmann5c224762019-06-01 06:10:02 +02002180/*[clinic end generated code: output=57b9f9c5e23fbe42 input=cb56cd179a713060]*/
Guido van Rossum3f236de1996-12-10 23:55:39 +00002181{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002182 MergeState ms;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002183 Py_ssize_t nremaining;
2184 Py_ssize_t minrun;
Daniel Stutzbach98338222010-12-02 21:55:33 +00002185 sortslice lo;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002186 Py_ssize_t saved_ob_size, saved_allocated;
2187 PyObject **saved_ob_item;
2188 PyObject **final_ob_item;
2189 PyObject *result = NULL; /* guilty until proved innocent */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002190 Py_ssize_t i;
Daniel Stutzbach98338222010-12-02 21:55:33 +00002191 PyObject **keys;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002193 assert(self != NULL);
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002194 assert(PyList_Check(self));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002195 if (keyfunc == Py_None)
2196 keyfunc = NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002198 /* The list is temporarily made empty, so that mutations performed
2199 * by comparison functions can't affect the slice of memory we're
2200 * sorting (allowing mutations during sorting is a core-dump
2201 * factory, since ob_item may change).
2202 */
2203 saved_ob_size = Py_SIZE(self);
2204 saved_ob_item = self->ob_item;
2205 saved_allocated = self->allocated;
Victor Stinner60ac6ed2020-02-07 23:18:08 +01002206 Py_SET_SIZE(self, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002207 self->ob_item = NULL;
2208 self->allocated = -1; /* any operation will reset it to >= 0 */
Tim Peters330f9e92002-07-19 07:05:44 +00002209
Daniel Stutzbach98338222010-12-02 21:55:33 +00002210 if (keyfunc == NULL) {
2211 keys = NULL;
2212 lo.keys = saved_ob_item;
2213 lo.values = NULL;
2214 }
2215 else {
2216 if (saved_ob_size < MERGESTATE_TEMP_SIZE/2)
2217 /* Leverage stack space we allocated but won't otherwise use */
2218 keys = &ms.temparray[saved_ob_size+1];
2219 else {
2220 keys = PyMem_MALLOC(sizeof(PyObject *) * saved_ob_size);
Benjamin Peterson0823ffb2015-04-23 17:04:36 -04002221 if (keys == NULL) {
2222 PyErr_NoMemory();
2223 goto keyfunc_fail;
2224 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002225 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00002226
2227 for (i = 0; i < saved_ob_size ; i++) {
Petr Viktorinffd97532020-02-11 17:46:57 +01002228 keys[i] = PyObject_CallOneArg(keyfunc, saved_ob_item[i]);
Daniel Stutzbach98338222010-12-02 21:55:33 +00002229 if (keys[i] == NULL) {
2230 for (i=i-1 ; i>=0 ; i--)
2231 Py_DECREF(keys[i]);
Benjamin Peterson4a42cd42014-03-15 12:21:28 -05002232 if (saved_ob_size >= MERGESTATE_TEMP_SIZE/2)
Daniel Stutzbach8eda5f72011-03-02 23:37:50 +00002233 PyMem_FREE(keys);
Daniel Stutzbach98338222010-12-02 21:55:33 +00002234 goto keyfunc_fail;
2235 }
2236 }
2237
2238 lo.keys = keys;
2239 lo.values = saved_ob_item;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002240 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002241
embg1e34da42018-01-28 20:03:23 -07002242
2243 /* The pre-sort check: here's where we decide which compare function to use.
2244 * How much optimization is safe? We test for homogeneity with respect to
2245 * several properties that are expensive to check at compare-time, and
2246 * set ms appropriately. */
2247 if (saved_ob_size > 1) {
2248 /* Assume the first element is representative of the whole list. */
Andy Lesterdffe4c02020-03-04 07:15:20 -06002249 int keys_are_in_tuples = (Py_IS_TYPE(lo.keys[0], &PyTuple_Type) &&
embg1e34da42018-01-28 20:03:23 -07002250 Py_SIZE(lo.keys[0]) > 0);
2251
2252 PyTypeObject* key_type = (keys_are_in_tuples ?
Victor Stinner58ac7002020-02-07 03:04:21 +01002253 Py_TYPE(PyTuple_GET_ITEM(lo.keys[0], 0)) :
2254 Py_TYPE(lo.keys[0]));
embg1e34da42018-01-28 20:03:23 -07002255
2256 int keys_are_all_same_type = 1;
2257 int strings_are_latin = 1;
2258 int ints_are_bounded = 1;
2259
2260 /* Prove that assumption by checking every key. */
embg1e34da42018-01-28 20:03:23 -07002261 for (i=0; i < saved_ob_size; i++) {
2262
2263 if (keys_are_in_tuples &&
Andy Lesterdffe4c02020-03-04 07:15:20 -06002264 !(Py_IS_TYPE(lo.keys[i], &PyTuple_Type) && Py_SIZE(lo.keys[i]) != 0)) {
embg1e34da42018-01-28 20:03:23 -07002265 keys_are_in_tuples = 0;
2266 keys_are_all_same_type = 0;
2267 break;
2268 }
2269
2270 /* Note: for lists of tuples, key is the first element of the tuple
2271 * lo.keys[i], not lo.keys[i] itself! We verify type-homogeneity
2272 * for lists of tuples in the if-statement directly above. */
2273 PyObject *key = (keys_are_in_tuples ?
2274 PyTuple_GET_ITEM(lo.keys[i], 0) :
2275 lo.keys[i]);
2276
Andy Lesterdffe4c02020-03-04 07:15:20 -06002277 if (!Py_IS_TYPE(key, key_type)) {
embg1e34da42018-01-28 20:03:23 -07002278 keys_are_all_same_type = 0;
Rémi Lapeyredd5417a2019-03-25 08:25:37 +01002279 /* If keys are in tuple we must loop over the whole list to make
2280 sure all items are tuples */
2281 if (!keys_are_in_tuples) {
2282 break;
2283 }
embg1e34da42018-01-28 20:03:23 -07002284 }
2285
Rémi Lapeyredd5417a2019-03-25 08:25:37 +01002286 if (keys_are_all_same_type) {
2287 if (key_type == &PyLong_Type &&
2288 ints_are_bounded &&
2289 Py_ABS(Py_SIZE(key)) > 1) {
2290
embg1e34da42018-01-28 20:03:23 -07002291 ints_are_bounded = 0;
Rémi Lapeyredd5417a2019-03-25 08:25:37 +01002292 }
2293 else if (key_type == &PyUnicode_Type &&
2294 strings_are_latin &&
2295 PyUnicode_KIND(key) != PyUnicode_1BYTE_KIND) {
2296
2297 strings_are_latin = 0;
2298 }
2299 }
embg1e34da42018-01-28 20:03:23 -07002300 }
embg1e34da42018-01-28 20:03:23 -07002301
2302 /* Choose the best compare, given what we now know about the keys. */
2303 if (keys_are_all_same_type) {
2304
2305 if (key_type == &PyUnicode_Type && strings_are_latin) {
2306 ms.key_compare = unsafe_latin_compare;
2307 }
2308 else if (key_type == &PyLong_Type && ints_are_bounded) {
2309 ms.key_compare = unsafe_long_compare;
2310 }
2311 else if (key_type == &PyFloat_Type) {
2312 ms.key_compare = unsafe_float_compare;
2313 }
2314 else if ((ms.key_richcompare = key_type->tp_richcompare) != NULL) {
2315 ms.key_compare = unsafe_object_compare;
2316 }
Zackery Spytzebc793d2019-02-21 00:47:14 -07002317 else {
2318 ms.key_compare = safe_object_compare;
2319 }
embg1e34da42018-01-28 20:03:23 -07002320 }
2321 else {
2322 ms.key_compare = safe_object_compare;
2323 }
2324
2325 if (keys_are_in_tuples) {
2326 /* Make sure we're not dealing with tuples of tuples
2327 * (remember: here, key_type refers list [key[0] for key in keys]) */
Rémi Lapeyredd5417a2019-03-25 08:25:37 +01002328 if (key_type == &PyTuple_Type) {
embg1e34da42018-01-28 20:03:23 -07002329 ms.tuple_elem_compare = safe_object_compare;
Rémi Lapeyredd5417a2019-03-25 08:25:37 +01002330 }
2331 else {
embg1e34da42018-01-28 20:03:23 -07002332 ms.tuple_elem_compare = ms.key_compare;
Rémi Lapeyredd5417a2019-03-25 08:25:37 +01002333 }
embg1e34da42018-01-28 20:03:23 -07002334
2335 ms.key_compare = unsafe_tuple_compare;
2336 }
2337 }
2338 /* End of pre-sort check: ms is now set properly! */
2339
Daniel Stutzbach98338222010-12-02 21:55:33 +00002340 merge_init(&ms, saved_ob_size, keys != NULL);
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002342 nremaining = saved_ob_size;
2343 if (nremaining < 2)
2344 goto succeed;
Tim Peters330f9e92002-07-19 07:05:44 +00002345
Benjamin Peterson05380642010-08-23 19:35:39 +00002346 /* Reverse sort stability achieved by initially reversing the list,
2347 applying a stable forward sort, then reversing the final result. */
Daniel Stutzbach98338222010-12-02 21:55:33 +00002348 if (reverse) {
2349 if (keys != NULL)
2350 reverse_slice(&keys[0], &keys[saved_ob_size]);
2351 reverse_slice(&saved_ob_item[0], &saved_ob_item[saved_ob_size]);
2352 }
Benjamin Peterson05380642010-08-23 19:35:39 +00002353
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002354 /* March over the array once, left to right, finding natural runs,
2355 * and extending short natural runs to minrun elements.
2356 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002357 minrun = merge_compute_minrun(nremaining);
2358 do {
2359 int descending;
2360 Py_ssize_t n;
Tim Peters330f9e92002-07-19 07:05:44 +00002361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002362 /* Identify next run. */
embg1e34da42018-01-28 20:03:23 -07002363 n = count_run(&ms, lo.keys, lo.keys + nremaining, &descending);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002364 if (n < 0)
2365 goto fail;
2366 if (descending)
Daniel Stutzbach98338222010-12-02 21:55:33 +00002367 reverse_sortslice(&lo, n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002368 /* If short, extend to min(minrun, nremaining). */
2369 if (n < minrun) {
2370 const Py_ssize_t force = nremaining <= minrun ?
2371 nremaining : minrun;
embg1e34da42018-01-28 20:03:23 -07002372 if (binarysort(&ms, lo, lo.keys + force, lo.keys + n) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002373 goto fail;
2374 n = force;
2375 }
2376 /* Push run onto pending-runs stack, and maybe merge. */
2377 assert(ms.n < MAX_MERGE_PENDING);
2378 ms.pending[ms.n].base = lo;
2379 ms.pending[ms.n].len = n;
2380 ++ms.n;
2381 if (merge_collapse(&ms) < 0)
2382 goto fail;
2383 /* Advance to find next run. */
Daniel Stutzbach98338222010-12-02 21:55:33 +00002384 sortslice_advance(&lo, n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002385 nremaining -= n;
2386 } while (nremaining);
Tim Peters330f9e92002-07-19 07:05:44 +00002387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002388 if (merge_force_collapse(&ms) < 0)
2389 goto fail;
2390 assert(ms.n == 1);
Daniel Stutzbach98338222010-12-02 21:55:33 +00002391 assert(keys == NULL
2392 ? ms.pending[0].base.keys == saved_ob_item
2393 : ms.pending[0].base.keys == &keys[0]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002394 assert(ms.pending[0].len == saved_ob_size);
Daniel Stutzbach98338222010-12-02 21:55:33 +00002395 lo = ms.pending[0].base;
Tim Petersa64dc242002-08-01 02:13:36 +00002396
2397succeed:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002398 result = Py_None;
Tim Peters330f9e92002-07-19 07:05:44 +00002399fail:
Daniel Stutzbach98338222010-12-02 21:55:33 +00002400 if (keys != NULL) {
2401 for (i = 0; i < saved_ob_size; i++)
2402 Py_DECREF(keys[i]);
Benjamin Petersonef87f8c2014-03-14 21:54:31 -05002403 if (saved_ob_size >= MERGESTATE_TEMP_SIZE/2)
Daniel Stutzbach98338222010-12-02 21:55:33 +00002404 PyMem_FREE(keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002405 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002407 if (self->allocated != -1 && result != NULL) {
2408 /* The user mucked with the list during the sort,
2409 * and we don't already have another error to report.
2410 */
2411 PyErr_SetString(PyExc_ValueError, "list modified during sort");
2412 result = NULL;
2413 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002415 if (reverse && saved_ob_size > 1)
2416 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002418 merge_freemem(&ms);
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002419
Daniel Stutzbach98338222010-12-02 21:55:33 +00002420keyfunc_fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002421 final_ob_item = self->ob_item;
2422 i = Py_SIZE(self);
Victor Stinner60ac6ed2020-02-07 23:18:08 +01002423 Py_SET_SIZE(self, saved_ob_size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002424 self->ob_item = saved_ob_item;
2425 self->allocated = saved_allocated;
2426 if (final_ob_item != NULL) {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002427 /* we cannot use _list_clear() for this because it does not
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002428 guarantee that the list is really empty when it returns */
2429 while (--i >= 0) {
2430 Py_XDECREF(final_ob_item[i]);
2431 }
2432 PyMem_FREE(final_ob_item);
2433 }
2434 Py_XINCREF(result);
2435 return result;
Guido van Rossum3f236de1996-12-10 23:55:39 +00002436}
Tim Peters330f9e92002-07-19 07:05:44 +00002437#undef IFLT
Tim Peters66860f62002-08-04 17:47:26 +00002438#undef ISLT
Tim Peters330f9e92002-07-19 07:05:44 +00002439
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002440int
Fred Drakea2f55112000-07-09 15:16:51 +00002441PyList_Sort(PyObject *v)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002442{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002443 if (v == NULL || !PyList_Check(v)) {
2444 PyErr_BadInternalCall();
2445 return -1;
2446 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002447 v = list_sort_impl((PyListObject *)v, NULL, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002448 if (v == NULL)
2449 return -1;
2450 Py_DECREF(v);
2451 return 0;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002452}
2453
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002454/*[clinic input]
2455list.reverse
2456
2457Reverse *IN PLACE*.
2458[clinic start generated code]*/
2459
Guido van Rossumb86c5492001-02-12 22:06:02 +00002460static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002461list_reverse_impl(PyListObject *self)
2462/*[clinic end generated code: output=482544fc451abea9 input=eefd4c3ae1bc9887]*/
Guido van Rossumb86c5492001-02-12 22:06:02 +00002463{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002464 if (Py_SIZE(self) > 1)
2465 reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
2466 Py_RETURN_NONE;
Guido van Rossumed98d481991-03-06 13:07:53 +00002467}
2468
Guido van Rossum84c76f51990-10-30 13:32:20 +00002469int
Fred Drakea2f55112000-07-09 15:16:51 +00002470PyList_Reverse(PyObject *v)
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002471{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002472 PyListObject *self = (PyListObject *)v;
Tim Peters6063e262002-08-08 01:06:39 +00002473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002474 if (v == NULL || !PyList_Check(v)) {
2475 PyErr_BadInternalCall();
2476 return -1;
2477 }
2478 if (Py_SIZE(self) > 1)
2479 reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
2480 return 0;
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002481}
2482
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002483PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00002484PyList_AsTuple(PyObject *v)
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002485{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002486 if (v == NULL || !PyList_Check(v)) {
2487 PyErr_BadInternalCall();
2488 return NULL;
2489 }
Sergey Fedoseev234531b2019-02-25 21:59:12 +05002490 return _PyTuple_FromArray(((PyListObject *)v)->ob_item, Py_SIZE(v));
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002491}
2492
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002493/*[clinic input]
2494list.index
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002495
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002496 value: object
Serhiy Storchaka80ec8362017-03-19 19:37:40 +02002497 start: slice_index(accept={int}) = 0
2498 stop: slice_index(accept={int}, c_default="PY_SSIZE_T_MAX") = sys.maxsize
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002499 /
2500
2501Return first index of value.
2502
2503Raises ValueError if the value is not present.
2504[clinic start generated code]*/
2505
2506static PyObject *
2507list_index_impl(PyListObject *self, PyObject *value, Py_ssize_t start,
2508 Py_ssize_t stop)
Serhiy Storchaka80ec8362017-03-19 19:37:40 +02002509/*[clinic end generated code: output=ec51b88787e4e481 input=40ec5826303a0eb1]*/
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002510{
2511 Py_ssize_t i;
2512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002513 if (start < 0) {
2514 start += Py_SIZE(self);
2515 if (start < 0)
2516 start = 0;
2517 }
2518 if (stop < 0) {
2519 stop += Py_SIZE(self);
2520 if (stop < 0)
2521 stop = 0;
2522 }
2523 for (i = start; i < stop && i < Py_SIZE(self); i++) {
Zackery Spytzd9e561d2019-12-30 12:32:58 -07002524 PyObject *obj = self->ob_item[i];
2525 Py_INCREF(obj);
2526 int cmp = PyObject_RichCompareBool(obj, value, Py_EQ);
2527 Py_DECREF(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002528 if (cmp > 0)
2529 return PyLong_FromSsize_t(i);
2530 else if (cmp < 0)
2531 return NULL;
2532 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002533 PyErr_Format(PyExc_ValueError, "%R is not in list", value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002534 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002535}
2536
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002537/*[clinic input]
2538list.count
2539
2540 value: object
2541 /
2542
2543Return number of occurrences of value.
2544[clinic start generated code]*/
2545
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002546static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002547list_count(PyListObject *self, PyObject *value)
2548/*[clinic end generated code: output=b1f5d284205ae714 input=3bdc3a5e6f749565]*/
Guido van Rossume6f7d181991-10-20 20:20:40 +00002549{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002550 Py_ssize_t count = 0;
2551 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002553 for (i = 0; i < Py_SIZE(self); i++) {
Zackery Spytzd9e561d2019-12-30 12:32:58 -07002554 PyObject *obj = self->ob_item[i];
Dong-hee Na14d80d02020-01-23 02:36:54 +09002555 if (obj == value) {
2556 count++;
2557 continue;
2558 }
Zackery Spytzd9e561d2019-12-30 12:32:58 -07002559 Py_INCREF(obj);
2560 int cmp = PyObject_RichCompareBool(obj, value, Py_EQ);
2561 Py_DECREF(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002562 if (cmp > 0)
2563 count++;
2564 else if (cmp < 0)
2565 return NULL;
2566 }
2567 return PyLong_FromSsize_t(count);
Guido van Rossume6f7d181991-10-20 20:20:40 +00002568}
2569
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002570/*[clinic input]
2571list.remove
2572
2573 value: object
2574 /
2575
2576Remove first occurrence of value.
2577
2578Raises ValueError if the value is not present.
2579[clinic start generated code]*/
2580
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002581static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002582list_remove(PyListObject *self, PyObject *value)
2583/*[clinic end generated code: output=f087e1951a5e30d1 input=2dc2ba5bb2fb1f82]*/
Guido van Rossumed98d481991-03-06 13:07:53 +00002584{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002585 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002587 for (i = 0; i < Py_SIZE(self); i++) {
Zackery Spytzd9e561d2019-12-30 12:32:58 -07002588 PyObject *obj = self->ob_item[i];
2589 Py_INCREF(obj);
2590 int cmp = PyObject_RichCompareBool(obj, value, Py_EQ);
2591 Py_DECREF(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002592 if (cmp > 0) {
2593 if (list_ass_slice(self, i, i+1,
2594 (PyObject *)NULL) == 0)
2595 Py_RETURN_NONE;
2596 return NULL;
2597 }
2598 else if (cmp < 0)
2599 return NULL;
2600 }
2601 PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
2602 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002603}
2604
Jeremy Hylton8caad492000-06-23 14:18:11 +00002605static int
2606list_traverse(PyListObject *o, visitproc visit, void *arg)
2607{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002608 Py_ssize_t i;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002610 for (i = Py_SIZE(o); --i >= 0; )
2611 Py_VISIT(o->ob_item[i]);
2612 return 0;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002613}
2614
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002615static PyObject *
2616list_richcompare(PyObject *v, PyObject *w, int op)
2617{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002618 PyListObject *vl, *wl;
2619 Py_ssize_t i;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002620
Brian Curtindfc80e32011-08-10 20:28:54 -05002621 if (!PyList_Check(v) || !PyList_Check(w))
2622 Py_RETURN_NOTIMPLEMENTED;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002623
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002624 vl = (PyListObject *)v;
2625 wl = (PyListObject *)w;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002626
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002627 if (Py_SIZE(vl) != Py_SIZE(wl) && (op == Py_EQ || op == Py_NE)) {
2628 /* Shortcut: if the lengths differ, the lists differ */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002629 if (op == Py_EQ)
stratakise8b19652017-11-02 11:32:54 +01002630 Py_RETURN_FALSE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002631 else
stratakise8b19652017-11-02 11:32:54 +01002632 Py_RETURN_TRUE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002633 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002635 /* Search for the first index where items are different */
2636 for (i = 0; i < Py_SIZE(vl) && i < Py_SIZE(wl); i++) {
Dong-hee Na2d5bf562019-12-31 10:04:22 +09002637 PyObject *vitem = vl->ob_item[i];
2638 PyObject *witem = wl->ob_item[i];
Inada Naokidfef9862019-12-31 10:58:37 +09002639 if (vitem == witem) {
2640 continue;
2641 }
Dong-hee Na2d5bf562019-12-31 10:04:22 +09002642
2643 Py_INCREF(vitem);
2644 Py_INCREF(witem);
sweeneydebe7ead62020-02-26 02:00:35 -05002645 int k = PyObject_RichCompareBool(vitem, witem, Py_EQ);
Dong-hee Na2d5bf562019-12-31 10:04:22 +09002646 Py_DECREF(vitem);
2647 Py_DECREF(witem);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002648 if (k < 0)
2649 return NULL;
2650 if (!k)
2651 break;
2652 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002654 if (i >= Py_SIZE(vl) || i >= Py_SIZE(wl)) {
2655 /* No more items to compare -- compare sizes */
stratakise8b19652017-11-02 11:32:54 +01002656 Py_RETURN_RICHCOMPARE(Py_SIZE(vl), Py_SIZE(wl), op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002657 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002658
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002659 /* We have an item that differs -- shortcuts for EQ/NE */
2660 if (op == Py_EQ) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02002661 Py_RETURN_FALSE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002662 }
2663 if (op == Py_NE) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02002664 Py_RETURN_TRUE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002665 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002666
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002667 /* Compare the final item again using the proper operator */
2668 return PyObject_RichCompare(vl->ob_item[i], wl->ob_item[i], op);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002669}
2670
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002671/*[clinic input]
2672list.__init__
2673
2674 iterable: object(c_default="NULL") = ()
2675 /
2676
2677Built-in mutable sequence.
2678
2679If no argument is given, the constructor creates a new empty list.
2680The argument must be an iterable if specified.
2681[clinic start generated code]*/
2682
Tim Peters6d6c1a32001-08-02 04:15:00 +00002683static int
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002684list___init___impl(PyListObject *self, PyObject *iterable)
2685/*[clinic end generated code: output=0f3c21379d01de48 input=b3f3fe7206af8f6b]*/
Tim Peters6d6c1a32001-08-02 04:15:00 +00002686{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002687 /* Verify list invariants established by PyType_GenericAlloc() */
2688 assert(0 <= Py_SIZE(self));
2689 assert(Py_SIZE(self) <= self->allocated || self->allocated == -1);
2690 assert(self->ob_item != NULL ||
2691 self->allocated == 0 || self->allocated == -1);
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002692
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002693 /* Empty previous contents */
2694 if (self->ob_item != NULL) {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002695 (void)_list_clear(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002696 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002697 if (iterable != NULL) {
Pablo Galindo372d7052018-10-28 20:16:26 +00002698 if (_PyObject_HasLen(iterable)) {
2699 Py_ssize_t iter_len = PyObject_Size(iterable);
2700 if (iter_len == -1) {
2701 if (!PyErr_ExceptionMatches(PyExc_TypeError)) {
2702 return -1;
2703 }
2704 PyErr_Clear();
2705 }
2706 if (iter_len > 0 && self->ob_item == NULL
2707 && list_preallocate_exact(self, iter_len)) {
2708 return -1;
2709 }
2710 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002711 PyObject *rv = list_extend(self, iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002712 if (rv == NULL)
2713 return -1;
2714 Py_DECREF(rv);
2715 }
2716 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002717}
2718
Petr Viktorince105542020-03-30 14:16:16 +02002719static PyObject *
2720list_vectorcall(PyObject *type, PyObject * const*args,
2721 size_t nargsf, PyObject *kwnames)
2722{
2723 if (!_PyArg_NoKwnames("list", kwnames)) {
2724 return NULL;
2725 }
2726 Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
2727 if (!_PyArg_CheckPositional("list", nargs, 0, 1)) {
2728 return NULL;
2729 }
2730
2731 assert(PyType_Check(type));
2732 PyObject *list = PyType_GenericAlloc((PyTypeObject *)type, 0);
2733 if (list == NULL) {
2734 return NULL;
2735 }
2736 if (nargs) {
2737 if (list___init___impl((PyListObject *)list, args[0])) {
2738 Py_DECREF(list);
2739 return NULL;
2740 }
2741 }
2742 return list;
2743}
2744
2745
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002746/*[clinic input]
2747list.__sizeof__
2748
2749Return the size of the list in memory, in bytes.
2750[clinic start generated code]*/
2751
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002752static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002753list___sizeof___impl(PyListObject *self)
2754/*[clinic end generated code: output=3417541f95f9a53e input=b8030a5d5ce8a187]*/
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002755{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002756 Py_ssize_t res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002757
Serhiy Storchaka5c4064e2015-12-19 20:05:25 +02002758 res = _PyObject_SIZE(Py_TYPE(self)) + self->allocated * sizeof(void*);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002759 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002760}
2761
Raymond Hettinger1021c442003-11-07 15:38:09 +00002762static PyObject *list_iter(PyObject *seq);
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002763static PyObject *list_subscript(PyListObject*, PyObject*);
2764
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002765static PyMethodDef list_methods[] = {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002766 {"__getitem__", (PyCFunction)list_subscript, METH_O|METH_COEXIST, "x.__getitem__(y) <==> x[y]"},
2767 LIST___REVERSED___METHODDEF
2768 LIST___SIZEOF___METHODDEF
2769 LIST_CLEAR_METHODDEF
2770 LIST_COPY_METHODDEF
2771 LIST_APPEND_METHODDEF
2772 LIST_INSERT_METHODDEF
2773 LIST_EXTEND_METHODDEF
2774 LIST_POP_METHODDEF
2775 LIST_REMOVE_METHODDEF
2776 LIST_INDEX_METHODDEF
2777 LIST_COUNT_METHODDEF
2778 LIST_REVERSE_METHODDEF
2779 LIST_SORT_METHODDEF
Guido van Rossum48b069a2020-04-07 09:50:06 -07002780 {"__class_getitem__", (PyCFunction)Py_GenericAlias, METH_O|METH_CLASS, PyDoc_STR("See PEP 585")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002781 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002782};
2783
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002784static PySequenceMethods list_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002785 (lenfunc)list_length, /* sq_length */
2786 (binaryfunc)list_concat, /* sq_concat */
2787 (ssizeargfunc)list_repeat, /* sq_repeat */
2788 (ssizeargfunc)list_item, /* sq_item */
2789 0, /* sq_slice */
2790 (ssizeobjargproc)list_ass_item, /* sq_ass_item */
2791 0, /* sq_ass_slice */
2792 (objobjproc)list_contains, /* sq_contains */
2793 (binaryfunc)list_inplace_concat, /* sq_inplace_concat */
2794 (ssizeargfunc)list_inplace_repeat, /* sq_inplace_repeat */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002795};
2796
Jeremy Hyltona4b4c3b2002-07-13 03:51:17 +00002797static PyObject *
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002798list_subscript(PyListObject* self, PyObject* item)
2799{
Victor Stinnera15e2602020-04-08 02:01:56 +02002800 if (_PyIndex_Check(item)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002801 Py_ssize_t i;
2802 i = PyNumber_AsSsize_t(item, PyExc_IndexError);
2803 if (i == -1 && PyErr_Occurred())
2804 return NULL;
2805 if (i < 0)
2806 i += PyList_GET_SIZE(self);
2807 return list_item(self, i);
2808 }
2809 else if (PySlice_Check(item)) {
HongWeipeng3c87a662019-09-08 18:15:56 +08002810 Py_ssize_t start, stop, step, slicelength, i;
2811 size_t cur;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002812 PyObject* result;
2813 PyObject* it;
2814 PyObject **src, **dest;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002815
Serhiy Storchakab879fe82017-04-08 09:53:51 +03002816 if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002817 return NULL;
2818 }
Serhiy Storchakab879fe82017-04-08 09:53:51 +03002819 slicelength = PySlice_AdjustIndices(Py_SIZE(self), &start, &stop,
2820 step);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002821
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002822 if (slicelength <= 0) {
2823 return PyList_New(0);
2824 }
2825 else if (step == 1) {
2826 return list_slice(self, start, stop);
2827 }
2828 else {
Sergey Fedoseev2fc46972018-08-11 18:12:07 +05002829 result = list_new_prealloc(slicelength);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002830 if (!result) return NULL;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002831
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002832 src = self->ob_item;
2833 dest = ((PyListObject *)result)->ob_item;
2834 for (cur = start, i = 0; i < slicelength;
Mark Dickinsonc7d93b72011-09-25 15:34:32 +01002835 cur += (size_t)step, i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002836 it = src[cur];
2837 Py_INCREF(it);
2838 dest[i] = it;
2839 }
Victor Stinner60ac6ed2020-02-07 23:18:08 +01002840 Py_SET_SIZE(result, slicelength);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002841 return result;
2842 }
2843 }
2844 else {
2845 PyErr_Format(PyExc_TypeError,
Terry Jan Reedyffff1442014-08-02 01:30:37 -04002846 "list indices must be integers or slices, not %.200s",
Victor Stinner58ac7002020-02-07 03:04:21 +01002847 Py_TYPE(item)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002848 return NULL;
2849 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002850}
2851
Tim Peters3b01a122002-07-19 02:35:45 +00002852static int
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002853list_ass_subscript(PyListObject* self, PyObject* item, PyObject* value)
2854{
Victor Stinnera15e2602020-04-08 02:01:56 +02002855 if (_PyIndex_Check(item)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002856 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
2857 if (i == -1 && PyErr_Occurred())
2858 return -1;
2859 if (i < 0)
2860 i += PyList_GET_SIZE(self);
2861 return list_ass_item(self, i, value);
2862 }
2863 else if (PySlice_Check(item)) {
2864 Py_ssize_t start, stop, step, slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002865
Serhiy Storchakab879fe82017-04-08 09:53:51 +03002866 if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002867 return -1;
2868 }
Serhiy Storchakab879fe82017-04-08 09:53:51 +03002869 slicelength = PySlice_AdjustIndices(Py_SIZE(self), &start, &stop,
2870 step);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002871
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002872 if (step == 1)
2873 return list_ass_slice(self, start, stop, value);
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002874
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002875 /* Make sure s[5:2] = [..] inserts at the right place:
2876 before 5, not before 2. */
2877 if ((step < 0 && start < stop) ||
2878 (step > 0 && start > stop))
2879 stop = start;
Thomas Woutersed03b412007-08-28 21:37:11 +00002880
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002881 if (value == NULL) {
2882 /* delete slice */
2883 PyObject **garbage;
2884 size_t cur;
2885 Py_ssize_t i;
Victor Stinner35f28032013-11-21 12:16:35 +01002886 int res;
Tim Peters3b01a122002-07-19 02:35:45 +00002887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002888 if (slicelength <= 0)
2889 return 0;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002891 if (step < 0) {
2892 stop = start + 1;
2893 start = stop + step*(slicelength - 1) - 1;
2894 step = -step;
2895 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002897 garbage = (PyObject**)
2898 PyMem_MALLOC(slicelength*sizeof(PyObject*));
2899 if (!garbage) {
2900 PyErr_NoMemory();
2901 return -1;
2902 }
Tim Peters3b01a122002-07-19 02:35:45 +00002903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002904 /* drawing pictures might help understand these for
2905 loops. Basically, we memmove the parts of the
2906 list that are *not* part of the slice: step-1
2907 items for each item that is part of the slice,
2908 and then tail end of the list that was not
2909 covered by the slice */
2910 for (cur = start, i = 0;
2911 cur < (size_t)stop;
2912 cur += step, i++) {
2913 Py_ssize_t lim = step - 1;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002914
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002915 garbage[i] = PyList_GET_ITEM(self, cur);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002916
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002917 if (cur + step >= (size_t)Py_SIZE(self)) {
2918 lim = Py_SIZE(self) - cur - 1;
2919 }
Michael W. Hudson56796f62002-07-29 14:35:04 +00002920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002921 memmove(self->ob_item + cur - i,
2922 self->ob_item + cur + 1,
2923 lim * sizeof(PyObject *));
2924 }
Mark Dickinsonc7d93b72011-09-25 15:34:32 +01002925 cur = start + (size_t)slicelength * step;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002926 if (cur < (size_t)Py_SIZE(self)) {
2927 memmove(self->ob_item + cur - slicelength,
2928 self->ob_item + cur,
2929 (Py_SIZE(self) - cur) *
2930 sizeof(PyObject *));
2931 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002932
Victor Stinner60ac6ed2020-02-07 23:18:08 +01002933 Py_SET_SIZE(self, Py_SIZE(self) - slicelength);
Victor Stinner35f28032013-11-21 12:16:35 +01002934 res = list_resize(self, Py_SIZE(self));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002936 for (i = 0; i < slicelength; i++) {
2937 Py_DECREF(garbage[i]);
2938 }
2939 PyMem_FREE(garbage);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002940
Victor Stinner35f28032013-11-21 12:16:35 +01002941 return res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002942 }
2943 else {
2944 /* assign slice */
2945 PyObject *ins, *seq;
2946 PyObject **garbage, **seqitems, **selfitems;
HongWeipeng3c87a662019-09-08 18:15:56 +08002947 Py_ssize_t i;
2948 size_t cur;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002950 /* protect against a[::-1] = a */
2951 if (self == (PyListObject*)value) {
2952 seq = list_slice((PyListObject*)value, 0,
2953 PyList_GET_SIZE(value));
2954 }
2955 else {
2956 seq = PySequence_Fast(value,
2957 "must assign iterable "
2958 "to extended slice");
2959 }
2960 if (!seq)
2961 return -1;
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002962
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002963 if (PySequence_Fast_GET_SIZE(seq) != slicelength) {
2964 PyErr_Format(PyExc_ValueError,
2965 "attempt to assign sequence of "
2966 "size %zd to extended slice of "
2967 "size %zd",
2968 PySequence_Fast_GET_SIZE(seq),
2969 slicelength);
2970 Py_DECREF(seq);
2971 return -1;
2972 }
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002974 if (!slicelength) {
2975 Py_DECREF(seq);
2976 return 0;
2977 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002978
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002979 garbage = (PyObject**)
2980 PyMem_MALLOC(slicelength*sizeof(PyObject*));
2981 if (!garbage) {
2982 Py_DECREF(seq);
2983 PyErr_NoMemory();
2984 return -1;
2985 }
Tim Peters3b01a122002-07-19 02:35:45 +00002986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002987 selfitems = self->ob_item;
2988 seqitems = PySequence_Fast_ITEMS(seq);
2989 for (cur = start, i = 0; i < slicelength;
Mark Dickinsonc7d93b72011-09-25 15:34:32 +01002990 cur += (size_t)step, i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002991 garbage[i] = selfitems[cur];
2992 ins = seqitems[i];
2993 Py_INCREF(ins);
2994 selfitems[cur] = ins;
2995 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002996
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002997 for (i = 0; i < slicelength; i++) {
2998 Py_DECREF(garbage[i]);
2999 }
Tim Peters3b01a122002-07-19 02:35:45 +00003000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003001 PyMem_FREE(garbage);
3002 Py_DECREF(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00003003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003004 return 0;
3005 }
3006 }
3007 else {
3008 PyErr_Format(PyExc_TypeError,
Terry Jan Reedyffff1442014-08-02 01:30:37 -04003009 "list indices must be integers or slices, not %.200s",
Victor Stinner58ac7002020-02-07 03:04:21 +01003010 Py_TYPE(item)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003011 return -1;
3012 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00003013}
3014
3015static PyMappingMethods list_as_mapping = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003016 (lenfunc)list_length,
3017 (binaryfunc)list_subscript,
3018 (objobjargproc)list_ass_subscript
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00003019};
3020
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003021PyTypeObject PyList_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003022 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3023 "list",
3024 sizeof(PyListObject),
3025 0,
3026 (destructor)list_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003027 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003028 0, /* tp_getattr */
3029 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003030 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003031 (reprfunc)list_repr, /* tp_repr */
3032 0, /* tp_as_number */
3033 &list_as_sequence, /* tp_as_sequence */
3034 &list_as_mapping, /* tp_as_mapping */
Georg Brandl00da4e02010-10-18 07:32:48 +00003035 PyObject_HashNotImplemented, /* tp_hash */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003036 0, /* tp_call */
3037 0, /* tp_str */
3038 PyObject_GenericGetAttr, /* tp_getattro */
3039 0, /* tp_setattro */
3040 0, /* tp_as_buffer */
3041 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02003042 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LIST_SUBCLASS, /* tp_flags */
3043 list___init____doc__, /* tp_doc */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003044 (traverseproc)list_traverse, /* tp_traverse */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02003045 (inquiry)_list_clear, /* tp_clear */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003046 list_richcompare, /* tp_richcompare */
3047 0, /* tp_weaklistoffset */
3048 list_iter, /* tp_iter */
3049 0, /* tp_iternext */
3050 list_methods, /* tp_methods */
3051 0, /* tp_members */
3052 0, /* tp_getset */
3053 0, /* tp_base */
3054 0, /* tp_dict */
3055 0, /* tp_descr_get */
3056 0, /* tp_descr_set */
3057 0, /* tp_dictoffset */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02003058 (initproc)list___init__, /* tp_init */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003059 PyType_GenericAlloc, /* tp_alloc */
3060 PyType_GenericNew, /* tp_new */
3061 PyObject_GC_Del, /* tp_free */
Petr Viktorince105542020-03-30 14:16:16 +02003062 .tp_vectorcall = list_vectorcall,
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003063};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00003064
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00003065/*********************** List Iterator **************************/
3066
3067typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003068 PyObject_HEAD
Victor Stinner7660b882013-06-24 23:59:24 +02003069 Py_ssize_t it_index;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003070 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00003071} listiterobject;
3072
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003073static void listiter_dealloc(listiterobject *);
3074static int listiter_traverse(listiterobject *, visitproc, void *);
3075static PyObject *listiter_next(listiterobject *);
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303076static PyObject *listiter_len(listiterobject *, PyObject *);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003077static PyObject *listiter_reduce_general(void *_it, int forward);
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303078static PyObject *listiter_reduce(listiterobject *, PyObject *);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003079static PyObject *listiter_setstate(listiterobject *, PyObject *state);
Raymond Hettinger435bf582004-03-18 22:43:10 +00003080
Armin Rigof5b3e362006-02-11 21:32:43 +00003081PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003082PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
3083PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00003084
3085static PyMethodDef listiter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003086 {"__length_hint__", (PyCFunction)listiter_len, METH_NOARGS, length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003087 {"__reduce__", (PyCFunction)listiter_reduce, METH_NOARGS, reduce_doc},
3088 {"__setstate__", (PyCFunction)listiter_setstate, METH_O, setstate_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003089 {NULL, NULL} /* sentinel */
Raymond Hettinger435bf582004-03-18 22:43:10 +00003090};
3091
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00003092PyTypeObject PyListIter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003093 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3094 "list_iterator", /* tp_name */
3095 sizeof(listiterobject), /* tp_basicsize */
3096 0, /* tp_itemsize */
3097 /* methods */
3098 (destructor)listiter_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003099 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003100 0, /* tp_getattr */
3101 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003102 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003103 0, /* tp_repr */
3104 0, /* tp_as_number */
3105 0, /* tp_as_sequence */
3106 0, /* tp_as_mapping */
3107 0, /* tp_hash */
3108 0, /* tp_call */
3109 0, /* tp_str */
3110 PyObject_GenericGetAttr, /* tp_getattro */
3111 0, /* tp_setattro */
3112 0, /* tp_as_buffer */
3113 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3114 0, /* tp_doc */
3115 (traverseproc)listiter_traverse, /* tp_traverse */
3116 0, /* tp_clear */
3117 0, /* tp_richcompare */
3118 0, /* tp_weaklistoffset */
3119 PyObject_SelfIter, /* tp_iter */
3120 (iternextfunc)listiter_next, /* tp_iternext */
3121 listiter_methods, /* tp_methods */
3122 0, /* tp_members */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00003123};
Raymond Hettinger1021c442003-11-07 15:38:09 +00003124
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003125
3126static PyObject *
3127list_iter(PyObject *seq)
3128{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003129 listiterobject *it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003131 if (!PyList_Check(seq)) {
3132 PyErr_BadInternalCall();
3133 return NULL;
3134 }
3135 it = PyObject_GC_New(listiterobject, &PyListIter_Type);
3136 if (it == NULL)
3137 return NULL;
3138 it->it_index = 0;
3139 Py_INCREF(seq);
3140 it->it_seq = (PyListObject *)seq;
3141 _PyObject_GC_TRACK(it);
3142 return (PyObject *)it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003143}
3144
3145static void
3146listiter_dealloc(listiterobject *it)
3147{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003148 _PyObject_GC_UNTRACK(it);
3149 Py_XDECREF(it->it_seq);
3150 PyObject_GC_Del(it);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003151}
3152
3153static int
3154listiter_traverse(listiterobject *it, visitproc visit, void *arg)
3155{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003156 Py_VISIT(it->it_seq);
3157 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003158}
3159
3160static PyObject *
3161listiter_next(listiterobject *it)
3162{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003163 PyListObject *seq;
3164 PyObject *item;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003166 assert(it != NULL);
3167 seq = it->it_seq;
3168 if (seq == NULL)
3169 return NULL;
3170 assert(PyList_Check(seq));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003171
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003172 if (it->it_index < PyList_GET_SIZE(seq)) {
3173 item = PyList_GET_ITEM(seq, it->it_index);
3174 ++it->it_index;
3175 Py_INCREF(item);
3176 return item;
3177 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003179 it->it_seq = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003180 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003181 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003182}
3183
3184static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303185listiter_len(listiterobject *it, PyObject *Py_UNUSED(ignored))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003186{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003187 Py_ssize_t len;
3188 if (it->it_seq) {
3189 len = PyList_GET_SIZE(it->it_seq) - it->it_index;
3190 if (len >= 0)
3191 return PyLong_FromSsize_t(len);
3192 }
3193 return PyLong_FromLong(0);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003194}
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003195
3196static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303197listiter_reduce(listiterobject *it, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003198{
3199 return listiter_reduce_general(it, 1);
3200}
3201
3202static PyObject *
3203listiter_setstate(listiterobject *it, PyObject *state)
3204{
Victor Stinner7660b882013-06-24 23:59:24 +02003205 Py_ssize_t index = PyLong_AsSsize_t(state);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003206 if (index == -1 && PyErr_Occurred())
3207 return NULL;
3208 if (it->it_seq != NULL) {
3209 if (index < 0)
3210 index = 0;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +00003211 else if (index > PyList_GET_SIZE(it->it_seq))
3212 index = PyList_GET_SIZE(it->it_seq); /* iterator exhausted */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003213 it->it_index = index;
3214 }
3215 Py_RETURN_NONE;
3216}
3217
Raymond Hettinger1021c442003-11-07 15:38:09 +00003218/*********************** List Reverse Iterator **************************/
3219
3220typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003221 PyObject_HEAD
3222 Py_ssize_t it_index;
3223 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger1021c442003-11-07 15:38:09 +00003224} listreviterobject;
3225
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003226static void listreviter_dealloc(listreviterobject *);
3227static int listreviter_traverse(listreviterobject *, visitproc, void *);
3228static PyObject *listreviter_next(listreviterobject *);
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303229static PyObject *listreviter_len(listreviterobject *, PyObject *);
3230static PyObject *listreviter_reduce(listreviterobject *, PyObject *);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003231static PyObject *listreviter_setstate(listreviterobject *, PyObject *);
Raymond Hettingeref9bf402004-03-10 10:10:42 +00003232
Raymond Hettingerf5b64112008-12-02 21:33:45 +00003233static PyMethodDef listreviter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003234 {"__length_hint__", (PyCFunction)listreviter_len, METH_NOARGS, length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003235 {"__reduce__", (PyCFunction)listreviter_reduce, METH_NOARGS, reduce_doc},
3236 {"__setstate__", (PyCFunction)listreviter_setstate, METH_O, setstate_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003237 {NULL, NULL} /* sentinel */
Raymond Hettingeref9bf402004-03-10 10:10:42 +00003238};
3239
Raymond Hettinger1021c442003-11-07 15:38:09 +00003240PyTypeObject PyListRevIter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003241 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3242 "list_reverseiterator", /* tp_name */
3243 sizeof(listreviterobject), /* tp_basicsize */
3244 0, /* tp_itemsize */
3245 /* methods */
3246 (destructor)listreviter_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003247 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003248 0, /* tp_getattr */
3249 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003250 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003251 0, /* tp_repr */
3252 0, /* tp_as_number */
3253 0, /* tp_as_sequence */
3254 0, /* tp_as_mapping */
3255 0, /* tp_hash */
3256 0, /* tp_call */
3257 0, /* tp_str */
3258 PyObject_GenericGetAttr, /* tp_getattro */
3259 0, /* tp_setattro */
3260 0, /* tp_as_buffer */
3261 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3262 0, /* tp_doc */
3263 (traverseproc)listreviter_traverse, /* tp_traverse */
3264 0, /* tp_clear */
3265 0, /* tp_richcompare */
3266 0, /* tp_weaklistoffset */
3267 PyObject_SelfIter, /* tp_iter */
3268 (iternextfunc)listreviter_next, /* tp_iternext */
3269 listreviter_methods, /* tp_methods */
3270 0,
Raymond Hettinger1021c442003-11-07 15:38:09 +00003271};
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003272
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02003273/*[clinic input]
3274list.__reversed__
3275
3276Return a reverse iterator over the list.
3277[clinic start generated code]*/
3278
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003279static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02003280list___reversed___impl(PyListObject *self)
3281/*[clinic end generated code: output=b166f073208c888c input=eadb6e17f8a6a280]*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003282{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003283 listreviterobject *it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003285 it = PyObject_GC_New(listreviterobject, &PyListRevIter_Type);
3286 if (it == NULL)
3287 return NULL;
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02003288 assert(PyList_Check(self));
3289 it->it_index = PyList_GET_SIZE(self) - 1;
3290 Py_INCREF(self);
3291 it->it_seq = self;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003292 PyObject_GC_Track(it);
3293 return (PyObject *)it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003294}
3295
3296static void
3297listreviter_dealloc(listreviterobject *it)
3298{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003299 PyObject_GC_UnTrack(it);
3300 Py_XDECREF(it->it_seq);
3301 PyObject_GC_Del(it);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003302}
3303
3304static int
3305listreviter_traverse(listreviterobject *it, visitproc visit, void *arg)
3306{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003307 Py_VISIT(it->it_seq);
3308 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003309}
3310
3311static PyObject *
3312listreviter_next(listreviterobject *it)
3313{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003314 PyObject *item;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003315 Py_ssize_t index;
3316 PyListObject *seq;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003317
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003318 assert(it != NULL);
3319 seq = it->it_seq;
3320 if (seq == NULL) {
3321 return NULL;
3322 }
3323 assert(PyList_Check(seq));
3324
3325 index = it->it_index;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003326 if (index>=0 && index < PyList_GET_SIZE(seq)) {
3327 item = PyList_GET_ITEM(seq, index);
3328 it->it_index--;
3329 Py_INCREF(item);
3330 return item;
3331 }
3332 it->it_index = -1;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003333 it->it_seq = NULL;
3334 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003335 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003336}
3337
Raymond Hettingerf5b64112008-12-02 21:33:45 +00003338static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303339listreviter_len(listreviterobject *it, PyObject *Py_UNUSED(ignored))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003340{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003341 Py_ssize_t len = it->it_index + 1;
3342 if (it->it_seq == NULL || PyList_GET_SIZE(it->it_seq) < len)
3343 len = 0;
3344 return PyLong_FromSsize_t(len);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003345}
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003346
3347static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303348listreviter_reduce(listreviterobject *it, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003349{
3350 return listiter_reduce_general(it, 0);
3351}
3352
3353static PyObject *
3354listreviter_setstate(listreviterobject *it, PyObject *state)
3355{
3356 Py_ssize_t index = PyLong_AsSsize_t(state);
3357 if (index == -1 && PyErr_Occurred())
3358 return NULL;
3359 if (it->it_seq != NULL) {
3360 if (index < -1)
3361 index = -1;
3362 else if (index > PyList_GET_SIZE(it->it_seq) - 1)
3363 index = PyList_GET_SIZE(it->it_seq) - 1;
3364 it->it_index = index;
3365 }
3366 Py_RETURN_NONE;
3367}
3368
3369/* common pickling support */
3370
3371static PyObject *
3372listiter_reduce_general(void *_it, int forward)
3373{
Serhiy Storchakabb86bf42018-12-11 08:28:18 +02003374 _Py_IDENTIFIER(iter);
3375 _Py_IDENTIFIER(reversed);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003376 PyObject *list;
3377
3378 /* the objects are not the same, index is of different types! */
3379 if (forward) {
3380 listiterobject *it = (listiterobject *)_it;
3381 if (it->it_seq)
Serhiy Storchakabb86bf42018-12-11 08:28:18 +02003382 return Py_BuildValue("N(O)n", _PyEval_GetBuiltinId(&PyId_iter),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003383 it->it_seq, it->it_index);
3384 } else {
3385 listreviterobject *it = (listreviterobject *)_it;
3386 if (it->it_seq)
Serhiy Storchakabb86bf42018-12-11 08:28:18 +02003387 return Py_BuildValue("N(O)n", _PyEval_GetBuiltinId(&PyId_reversed),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003388 it->it_seq, it->it_index);
3389 }
3390 /* empty iterator, create an empty list */
3391 list = PyList_New(0);
3392 if (list == NULL)
3393 return NULL;
Serhiy Storchakabb86bf42018-12-11 08:28:18 +02003394 return Py_BuildValue("N(N)", _PyEval_GetBuiltinId(&PyId_iter), list);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003395}