blob: ca9df599a0bd443ae599dba7a41fb90e9ffb25f2 [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 Stinner384621c2020-06-22 17:27:35 +02004#include "pycore_abstract.h" // _PyIndex_Check()
5#include "pycore_interp.h" // PyInterpreterState.list
6#include "pycore_object.h" // _PyObject_GC_TRACK()
7#include "pycore_tuple.h" // _PyTuple_FromArray()
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
Victor Stinner522691c2020-06-23 16:40:40 +020022
23static struct _Py_list_state *
24get_list_state(void)
25{
26 PyInterpreterState *interp = _PyInterpreterState_GET();
27 return &interp->list;
28}
29
30
Tim Peters8d9eb102004-07-31 02:24:20 +000031/* Ensure ob_item has room for at least newsize elements, and set
32 * ob_size to newsize. If newsize > ob_size on entry, the content
33 * of the new slots at exit is undefined heap trash; it's the caller's
Ezio Melotti13925002011-03-16 11:05:33 +020034 * responsibility to overwrite them with sane values.
Tim Peters8d9eb102004-07-31 02:24:20 +000035 * The number of allocated elements may grow, shrink, or stay the same.
36 * Failure is impossible if newsize <= self.allocated on entry, although
37 * that partly relies on an assumption that the system realloc() never
38 * fails when passed a number of bytes <= the number of bytes last
39 * allocated (the C standard doesn't guarantee this, but it's hard to
40 * imagine a realloc implementation where it wouldn't be true).
41 * Note that self->ob_item may change, and even if newsize is less
42 * than ob_size on entry.
43 */
Guido van Rossuma46d51d1995-01-26 22:59:43 +000044static int
Martin v. Löwis18e16552006-02-15 17:27:45 +000045list_resize(PyListObject *self, Py_ssize_t newsize)
Guido van Rossuma46d51d1995-01-26 22:59:43 +000046{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000047 PyObject **items;
Xiang Zhang4cee0492017-02-22 12:32:30 +080048 size_t new_allocated, num_allocated_bytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000049 Py_ssize_t allocated = self->allocated;
Tim Peters65b8b842001-05-26 05:28:40 +000050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000051 /* Bypass realloc() when a previous overallocation is large enough
52 to accommodate the newsize. If the newsize falls lower than half
53 the allocated size, then proceed with the realloc() to shrink the list.
54 */
55 if (allocated >= newsize && newsize >= (allocated >> 1)) {
56 assert(self->ob_item != NULL || newsize == 0);
Victor Stinner60ac6ed2020-02-07 23:18:08 +010057 Py_SET_SIZE(self, newsize);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000058 return 0;
59 }
Raymond Hettinger4bb95402004-02-13 11:36:39 +000060
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000061 /* This over-allocates proportional to the list size, making room
62 * for additional growth. The over-allocation is mild, but is
63 * enough to give linear-time amortized behavior over a long
64 * sequence of appends() in the presence of a poorly-performing
65 * system realloc().
Serhiy Storchaka2fe815e2020-03-17 23:46:00 +020066 * Add padding to make the allocated size multiple of 4.
67 * The growth pattern is: 0, 4, 8, 16, 24, 32, 40, 52, 64, 76, ...
Xiang Zhang4cee0492017-02-22 12:32:30 +080068 * Note: new_allocated won't overflow because the largest possible value
69 * is PY_SSIZE_T_MAX * (9 / 8) + 6 which always fits in a size_t.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000070 */
Serhiy Storchaka2fe815e2020-03-17 23:46:00 +020071 new_allocated = ((size_t)newsize + (newsize >> 3) + 6) & ~(size_t)3;
Jeong Ukjae5b963702020-06-30 03:56:56 +090072 /* Do not overallocate if the new size is closer to overallocated size
Serhiy Storchaka2fe815e2020-03-17 23:46:00 +020073 * than to the old size.
74 */
75 if (newsize - Py_SIZE(self) > (Py_ssize_t)(new_allocated - newsize))
76 new_allocated = ((size_t)newsize + 3) & ~(size_t)3;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +000077
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000078 if (newsize == 0)
79 new_allocated = 0;
Xiang Zhang4cee0492017-02-22 12:32:30 +080080 num_allocated_bytes = new_allocated * sizeof(PyObject *);
81 items = (PyObject **)PyMem_Realloc(self->ob_item, num_allocated_bytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000082 if (items == NULL) {
83 PyErr_NoMemory();
84 return -1;
85 }
86 self->ob_item = items;
Victor Stinner60ac6ed2020-02-07 23:18:08 +010087 Py_SET_SIZE(self, newsize);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000088 self->allocated = new_allocated;
89 return 0;
Raymond Hettinger4bb95402004-02-13 11:36:39 +000090}
Guido van Rossuma46d51d1995-01-26 22:59:43 +000091
Pablo Galindo372d7052018-10-28 20:16:26 +000092static int
93list_preallocate_exact(PyListObject *self, Py_ssize_t size)
94{
95 assert(self->ob_item == NULL);
Sergey Fedoseev0e5f7712018-12-30 03:31:36 +050096 assert(size > 0);
Pablo Galindo372d7052018-10-28 20:16:26 +000097
Sergey Fedoseev0e5f7712018-12-30 03:31:36 +050098 PyObject **items = PyMem_New(PyObject*, size);
Pablo Galindo372d7052018-10-28 20:16:26 +000099 if (items == NULL) {
100 PyErr_NoMemory();
101 return -1;
102 }
103 self->ob_item = items;
Sergey Fedoseev0e5f7712018-12-30 03:31:36 +0500104 self->allocated = size;
Pablo Galindo372d7052018-10-28 20:16:26 +0000105 return 0;
106}
107
Victor Stinnerae00a5a2020-04-29 02:29:20 +0200108void
Victor Stinner88ec9192020-06-05 02:05:41 +0200109_PyList_ClearFreeList(PyThreadState *tstate)
Raymond Hettingerfb09f0e2004-10-07 03:58:07 +0000110{
Victor Stinner88ec9192020-06-05 02:05:41 +0200111 struct _Py_list_state *state = &tstate->interp->list;
112 while (state->numfree) {
113 PyListObject *op = state->free_list[--state->numfree];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000114 assert(PyList_CheckExact(op));
115 PyObject_GC_Del(op);
116 }
Antoine Pitrou9a812cb2011-11-15 00:00:12 +0100117}
118
119void
Victor Stinner88ec9192020-06-05 02:05:41 +0200120_PyList_Fini(PyThreadState *tstate)
Antoine Pitrou9a812cb2011-11-15 00:00:12 +0100121{
Victor Stinner88ec9192020-06-05 02:05:41 +0200122 _PyList_ClearFreeList(tstate);
Victor Stinnerbcb19832020-06-08 02:14:47 +0200123#ifdef Py_DEBUG
124 struct _Py_list_state *state = &tstate->interp->list;
125 state->numfree = -1;
126#endif
Raymond Hettingerfb09f0e2004-10-07 03:58:07 +0000127}
128
David Malcolm49526f42012-06-22 14:55:41 -0400129/* Print summary info about the state of the optimized allocator */
130void
131_PyList_DebugMallocStats(FILE *out)
132{
Victor Stinner522691c2020-06-23 16:40:40 +0200133 struct _Py_list_state *state = get_list_state();
David Malcolm49526f42012-06-22 14:55:41 -0400134 _PyDebugAllocatorStats(out,
135 "free PyListObject",
Victor Stinner88ec9192020-06-05 02:05:41 +0200136 state->numfree, sizeof(PyListObject));
David Malcolm49526f42012-06-22 14:55:41 -0400137}
138
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000139PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000140PyList_New(Py_ssize_t size)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000141{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000142 if (size < 0) {
143 PyErr_BadInternalCall();
144 return NULL;
145 }
Victor Stinner88ec9192020-06-05 02:05:41 +0200146
Victor Stinner522691c2020-06-23 16:40:40 +0200147 struct _Py_list_state *state = get_list_state();
Victor Stinner88ec9192020-06-05 02:05:41 +0200148 PyListObject *op;
Victor Stinnerbcb19832020-06-08 02:14:47 +0200149#ifdef Py_DEBUG
150 // PyList_New() must not be called after _PyList_Fini()
151 assert(state->numfree != -1);
152#endif
Victor Stinner88ec9192020-06-05 02:05:41 +0200153 if (state->numfree) {
154 state->numfree--;
155 op = state->free_list[state->numfree];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000156 _Py_NewReference((PyObject *)op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000157 }
Victor Stinner88ec9192020-06-05 02:05:41 +0200158 else {
159 op = PyObject_GC_New(PyListObject, &PyList_Type);
160 if (op == NULL) {
161 return NULL;
162 }
163 }
164 if (size <= 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000165 op->ob_item = NULL;
Victor Stinner88ec9192020-06-05 02:05:41 +0200166 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000167 else {
Mark Dickinson5d132382016-08-21 08:55:15 +0100168 op->ob_item = (PyObject **) PyMem_Calloc(size, sizeof(PyObject *));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000169 if (op->ob_item == NULL) {
170 Py_DECREF(op);
171 return PyErr_NoMemory();
172 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000173 }
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100174 Py_SET_SIZE(op, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175 op->allocated = size;
176 _PyObject_GC_TRACK(op);
177 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000178}
179
Sergey Fedoseev2fc46972018-08-11 18:12:07 +0500180static PyObject *
181list_new_prealloc(Py_ssize_t size)
182{
183 PyListObject *op = (PyListObject *) PyList_New(0);
184 if (size == 0 || op == NULL) {
185 return (PyObject *) op;
186 }
187 assert(op->ob_item == NULL);
188 op->ob_item = PyMem_New(PyObject *, size);
189 if (op->ob_item == NULL) {
190 Py_DECREF(op);
191 return PyErr_NoMemory();
192 }
193 op->allocated = size;
194 return (PyObject *) op;
195}
196
Martin v. Löwis18e16552006-02-15 17:27:45 +0000197Py_ssize_t
Fred Drakea2f55112000-07-09 15:16:51 +0000198PyList_Size(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000199{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000200 if (!PyList_Check(op)) {
201 PyErr_BadInternalCall();
202 return -1;
203 }
204 else
205 return Py_SIZE(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000206}
207
Raymond Hettingerf1aa8ae2018-10-10 20:37:28 -0700208static inline int
209valid_index(Py_ssize_t i, Py_ssize_t limit)
210{
211 /* The cast to size_t lets us use just a single comparison
212 to check whether i is in the range: 0 <= i < limit.
213
214 See: Section 14.2 "Bounds Checking" in the Agner Fog
215 optimization manual found at:
216 https://www.agner.org/optimize/optimizing_cpp.pdf
217 */
218 return (size_t) i < (size_t) limit;
219}
220
Raymond Hettingerfdfe6182004-05-05 06:28:16 +0000221static PyObject *indexerr = NULL;
Guido van Rossum929f1b81996-08-09 20:51:27 +0000222
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000223PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000224PyList_GetItem(PyObject *op, Py_ssize_t i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000225{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000226 if (!PyList_Check(op)) {
227 PyErr_BadInternalCall();
228 return NULL;
229 }
Raymond Hettingerf1aa8ae2018-10-10 20:37:28 -0700230 if (!valid_index(i, Py_SIZE(op))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000231 if (indexerr == NULL) {
232 indexerr = PyUnicode_FromString(
233 "list index out of range");
234 if (indexerr == NULL)
235 return NULL;
236 }
237 PyErr_SetObject(PyExc_IndexError, indexerr);
238 return NULL;
239 }
240 return ((PyListObject *)op) -> ob_item[i];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000241}
242
243int
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200244PyList_SetItem(PyObject *op, Py_ssize_t i,
245 PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000246{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200247 PyObject **p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000248 if (!PyList_Check(op)) {
249 Py_XDECREF(newitem);
250 PyErr_BadInternalCall();
251 return -1;
252 }
Raymond Hettingerf1aa8ae2018-10-10 20:37:28 -0700253 if (!valid_index(i, Py_SIZE(op))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000254 Py_XDECREF(newitem);
255 PyErr_SetString(PyExc_IndexError,
256 "list assignment index out of range");
257 return -1;
258 }
259 p = ((PyListObject *)op) -> ob_item + i;
Serhiy Storchakaec397562016-04-06 09:50:03 +0300260 Py_XSETREF(*p, newitem);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000261 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000262}
263
264static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000265ins1(PyListObject *self, Py_ssize_t where, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000266{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000267 Py_ssize_t i, n = Py_SIZE(self);
268 PyObject **items;
269 if (v == NULL) {
270 PyErr_BadInternalCall();
271 return -1;
272 }
Tim Petersb38e2b62004-07-29 02:29:26 +0000273
Sergey Fedoseeve682b262020-05-25 19:54:40 +0500274 assert((size_t)n + 1 < PY_SSIZE_T_MAX);
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800275 if (list_resize(self, n+1) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000276 return -1;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000278 if (where < 0) {
279 where += n;
280 if (where < 0)
281 where = 0;
282 }
283 if (where > n)
284 where = n;
285 items = self->ob_item;
286 for (i = n; --i >= where; )
287 items[i+1] = items[i];
288 Py_INCREF(v);
289 items[where] = v;
290 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000291}
292
293int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000294PyList_Insert(PyObject *op, Py_ssize_t where, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000295{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000296 if (!PyList_Check(op)) {
297 PyErr_BadInternalCall();
298 return -1;
299 }
300 return ins1((PyListObject *)op, where, newitem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000301}
302
Raymond Hettinger40a03822004-04-12 13:05:09 +0000303static int
304app1(PyListObject *self, PyObject *v)
305{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000306 Py_ssize_t n = PyList_GET_SIZE(self);
Raymond Hettinger40a03822004-04-12 13:05:09 +0000307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000308 assert (v != NULL);
Sergey Fedoseeve682b262020-05-25 19:54:40 +0500309 assert((size_t)n + 1 < PY_SSIZE_T_MAX);
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800310 if (list_resize(self, n+1) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000311 return -1;
Raymond Hettinger40a03822004-04-12 13:05:09 +0000312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000313 Py_INCREF(v);
314 PyList_SET_ITEM(self, n, v);
315 return 0;
Raymond Hettinger40a03822004-04-12 13:05:09 +0000316}
317
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000318int
Fred Drakea2f55112000-07-09 15:16:51 +0000319PyList_Append(PyObject *op, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000320{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000321 if (PyList_Check(op) && (newitem != NULL))
322 return app1((PyListObject *)op, newitem);
323 PyErr_BadInternalCall();
324 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000325}
326
327/* Methods */
328
329static void
Fred Drakea2f55112000-07-09 15:16:51 +0000330list_dealloc(PyListObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000331{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000332 Py_ssize_t i;
333 PyObject_GC_UnTrack(op);
Jeroen Demeyer351c6742019-05-10 19:21:11 +0200334 Py_TRASHCAN_BEGIN(op, list_dealloc)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000335 if (op->ob_item != NULL) {
336 /* Do it backwards, for Christian Tismer.
337 There's a simple test case where somehow this reduces
338 thrashing when a *very* large list is created and
339 immediately deleted. */
340 i = Py_SIZE(op);
341 while (--i >= 0) {
342 Py_XDECREF(op->ob_item[i]);
343 }
Victor Stinner00d7abd2020-12-01 09:56:42 +0100344 PyMem_Free(op->ob_item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000345 }
Victor Stinner522691c2020-06-23 16:40:40 +0200346 struct _Py_list_state *state = get_list_state();
Victor Stinnerbcb19832020-06-08 02:14:47 +0200347#ifdef Py_DEBUG
348 // list_dealloc() must not be called after _PyList_Fini()
349 assert(state->numfree != -1);
350#endif
Victor Stinner88ec9192020-06-05 02:05:41 +0200351 if (state->numfree < PyList_MAXFREELIST && PyList_CheckExact(op)) {
352 state->free_list[state->numfree++] = op;
353 }
354 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000355 Py_TYPE(op)->tp_free((PyObject *)op);
Victor Stinner88ec9192020-06-05 02:05:41 +0200356 }
Jeroen Demeyer351c6742019-05-10 19:21:11 +0200357 Py_TRASHCAN_END
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000358}
359
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000360static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000361list_repr(PyListObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000362{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000363 Py_ssize_t i;
Victor Stinner5c733472013-11-18 21:11:57 +0100364 PyObject *s;
Victor Stinner5c733472013-11-18 21:11:57 +0100365 _PyUnicodeWriter writer;
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200366
367 if (Py_SIZE(v) == 0) {
368 return PyUnicode_FromString("[]");
369 }
370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000371 i = Py_ReprEnter((PyObject*)v);
372 if (i != 0) {
373 return i > 0 ? PyUnicode_FromString("[...]") : NULL;
374 }
Tim Petersa7259592001-06-16 05:11:17 +0000375
Victor Stinner5c733472013-11-18 21:11:57 +0100376 _PyUnicodeWriter_Init(&writer);
377 writer.overallocate = 1;
Victor Stinnerb8fb1972013-11-18 22:15:44 +0100378 /* "[" + "1" + ", 2" * (len - 1) + "]" */
379 writer.min_length = 1 + 1 + (2 + 1) * (Py_SIZE(v) - 1) + 1;
Tim Petersa7259592001-06-16 05:11:17 +0000380
Victor Stinner5c733472013-11-18 21:11:57 +0100381 if (_PyUnicodeWriter_WriteChar(&writer, '[') < 0)
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200382 goto error;
Tim Petersa7259592001-06-16 05:11:17 +0000383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000384 /* Do repr() on each element. Note that this may mutate the list,
385 so must refetch the list size on each iteration. */
386 for (i = 0; i < Py_SIZE(v); ++i) {
Victor Stinner5c733472013-11-18 21:11:57 +0100387 if (i > 0) {
Victor Stinner4a587072013-11-19 12:54:53 +0100388 if (_PyUnicodeWriter_WriteASCIIString(&writer, ", ", 2) < 0)
Victor Stinner5c733472013-11-18 21:11:57 +0100389 goto error;
390 }
391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000392 s = PyObject_Repr(v->ob_item[i]);
Victor Stinner5c733472013-11-18 21:11:57 +0100393 if (s == NULL)
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200394 goto error;
Victor Stinner5c733472013-11-18 21:11:57 +0100395
396 if (_PyUnicodeWriter_WriteStr(&writer, s) < 0) {
397 Py_DECREF(s);
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200398 goto error;
Victor Stinner5c733472013-11-18 21:11:57 +0100399 }
400 Py_DECREF(s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000401 }
Victor Stinner5c733472013-11-18 21:11:57 +0100402
Victor Stinner4d3f1092013-11-19 12:09:00 +0100403 writer.overallocate = 0;
Victor Stinner5c733472013-11-18 21:11:57 +0100404 if (_PyUnicodeWriter_WriteChar(&writer, ']') < 0)
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200405 goto error;
Tim Petersa7259592001-06-16 05:11:17 +0000406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000407 Py_ReprLeave((PyObject *)v);
Victor Stinner5c733472013-11-18 21:11:57 +0100408 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200409
410error:
Victor Stinner5c733472013-11-18 21:11:57 +0100411 _PyUnicodeWriter_Dealloc(&writer);
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200412 Py_ReprLeave((PyObject *)v);
413 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000414}
415
Martin v. Löwis18e16552006-02-15 17:27:45 +0000416static Py_ssize_t
Fred Drakea2f55112000-07-09 15:16:51 +0000417list_length(PyListObject *a)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000418{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000419 return Py_SIZE(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000420}
421
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000422static int
Fred Drakea2f55112000-07-09 15:16:51 +0000423list_contains(PyListObject *a, PyObject *el)
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000424{
Dong-hee Na4dbf2d82020-01-28 00:02:23 +0900425 PyObject *item;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000426 Py_ssize_t i;
427 int cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000428
Dong-hee Na4dbf2d82020-01-28 00:02:23 +0900429 for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(a); ++i) {
430 item = PyList_GET_ITEM(a, i);
431 Py_INCREF(item);
Dong-hee Na9e1ed512020-01-28 02:04:25 +0900432 cmp = PyObject_RichCompareBool(item, el, Py_EQ);
Dong-hee Na4dbf2d82020-01-28 00:02:23 +0900433 Py_DECREF(item);
434 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435 return cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000436}
437
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000438static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000439list_item(PyListObject *a, Py_ssize_t i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000440{
Raymond Hettingerf1aa8ae2018-10-10 20:37:28 -0700441 if (!valid_index(i, Py_SIZE(a))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000442 if (indexerr == NULL) {
443 indexerr = PyUnicode_FromString(
444 "list index out of range");
445 if (indexerr == NULL)
446 return NULL;
447 }
448 PyErr_SetObject(PyExc_IndexError, indexerr);
449 return NULL;
450 }
451 Py_INCREF(a->ob_item[i]);
452 return a->ob_item[i];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000453}
454
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000455static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000456list_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000457{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000458 PyListObject *np;
459 PyObject **src, **dest;
460 Py_ssize_t i, len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 len = ihigh - ilow;
Sergey Fedoseev2fc46972018-08-11 18:12:07 +0500462 np = (PyListObject *) list_new_prealloc(len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000463 if (np == NULL)
464 return NULL;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000466 src = a->ob_item + ilow;
467 dest = np->ob_item;
468 for (i = 0; i < len; i++) {
469 PyObject *v = src[i];
470 Py_INCREF(v);
471 dest[i] = v;
472 }
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100473 Py_SET_SIZE(np, len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000475}
476
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000477PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000478PyList_GetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum234f9421993-06-17 12:35:49 +0000479{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000480 if (!PyList_Check(a)) {
481 PyErr_BadInternalCall();
482 return NULL;
483 }
Sergey Fedoseevef1b88b2019-02-21 11:51:52 +0500484 if (ilow < 0) {
485 ilow = 0;
486 }
487 else if (ilow > Py_SIZE(a)) {
488 ilow = Py_SIZE(a);
489 }
490 if (ihigh < ilow) {
491 ihigh = ilow;
492 }
493 else if (ihigh > Py_SIZE(a)) {
494 ihigh = Py_SIZE(a);
495 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000496 return list_slice((PyListObject *)a, ilow, ihigh);
Guido van Rossum234f9421993-06-17 12:35:49 +0000497}
498
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000499static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000500list_concat(PyListObject *a, PyObject *bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000501{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 Py_ssize_t size;
503 Py_ssize_t i;
504 PyObject **src, **dest;
505 PyListObject *np;
506 if (!PyList_Check(bb)) {
507 PyErr_Format(PyExc_TypeError,
508 "can only concatenate list (not \"%.200s\") to list",
Victor Stinner58ac7002020-02-07 03:04:21 +0100509 Py_TYPE(bb)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 return NULL;
511 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000512#define b ((PyListObject *)bb)
Sergey Fedoseeve682b262020-05-25 19:54:40 +0500513 assert((size_t)Py_SIZE(a) + (size_t)Py_SIZE(b) < PY_SSIZE_T_MAX);
Martin Panterb93d8632016-07-25 02:39:20 +0000514 size = Py_SIZE(a) + Py_SIZE(b);
Sergey Fedoseev2fc46972018-08-11 18:12:07 +0500515 np = (PyListObject *) list_new_prealloc(size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 if (np == NULL) {
517 return NULL;
518 }
519 src = a->ob_item;
520 dest = np->ob_item;
521 for (i = 0; i < Py_SIZE(a); i++) {
522 PyObject *v = src[i];
523 Py_INCREF(v);
524 dest[i] = v;
525 }
526 src = b->ob_item;
527 dest = np->ob_item + Py_SIZE(a);
528 for (i = 0; i < Py_SIZE(b); i++) {
529 PyObject *v = src[i];
530 Py_INCREF(v);
531 dest[i] = v;
532 }
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100533 Py_SET_SIZE(np, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000535#undef b
536}
537
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000538static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000539list_repeat(PyListObject *a, Py_ssize_t n)
Guido van Rossumed98d481991-03-06 13:07:53 +0000540{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000541 Py_ssize_t i, j;
542 Py_ssize_t size;
543 PyListObject *np;
544 PyObject **p, **items;
545 PyObject *elem;
546 if (n < 0)
547 n = 0;
Mark Dickinsonc0420fd2011-09-19 19:18:37 +0100548 if (n > 0 && Py_SIZE(a) > PY_SSIZE_T_MAX / n)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000549 return PyErr_NoMemory();
Mark Dickinsonc0420fd2011-09-19 19:18:37 +0100550 size = Py_SIZE(a) * n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 if (size == 0)
552 return PyList_New(0);
Sergey Fedoseev2fc46972018-08-11 18:12:07 +0500553 np = (PyListObject *) list_new_prealloc(size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000554 if (np == NULL)
555 return NULL;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000556
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000557 if (Py_SIZE(a) == 1) {
Sergey Fedoseev2fc46972018-08-11 18:12:07 +0500558 items = np->ob_item;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 elem = a->ob_item[0];
560 for (i = 0; i < n; i++) {
561 items[i] = elem;
562 Py_INCREF(elem);
563 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000564 }
Sergey Fedoseev2fc46972018-08-11 18:12:07 +0500565 else {
566 p = np->ob_item;
567 items = a->ob_item;
568 for (i = 0; i < n; i++) {
569 for (j = 0; j < Py_SIZE(a); j++) {
570 *p = items[j];
571 Py_INCREF(*p);
572 p++;
573 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000574 }
575 }
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100576 Py_SET_SIZE(np, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577 return (PyObject *) np;
Guido van Rossumed98d481991-03-06 13:07:53 +0000578}
579
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000580static int
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200581_list_clear(PyListObject *a)
Armin Rigo93677f02004-07-29 12:40:23 +0000582{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000583 Py_ssize_t i;
584 PyObject **item = a->ob_item;
585 if (item != NULL) {
586 /* Because XDECREF can recursively invoke operations on
587 this list, we make it empty first. */
588 i = Py_SIZE(a);
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100589 Py_SET_SIZE(a, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000590 a->ob_item = NULL;
591 a->allocated = 0;
592 while (--i >= 0) {
593 Py_XDECREF(item[i]);
594 }
Victor Stinner00d7abd2020-12-01 09:56:42 +0100595 PyMem_Free(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 }
597 /* Never fails; the return value can be ignored.
598 Note that there is no guarantee that the list is actually empty
599 at this point, because XDECREF may have populated it again! */
600 return 0;
Armin Rigo93677f02004-07-29 12:40:23 +0000601}
602
Tim Peters8fc4a912004-07-31 21:53:19 +0000603/* a[ilow:ihigh] = v if v != NULL.
604 * del a[ilow:ihigh] if v == NULL.
605 *
606 * Special speed gimmick: when v is NULL and ihigh - ilow <= 8, it's
607 * guaranteed the call cannot fail.
608 */
Armin Rigo93677f02004-07-29 12:40:23 +0000609static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000610list_ass_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000611{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 /* Because [X]DECREF can recursively invoke list operations on
613 this list, we must postpone all [X]DECREF activity until
614 after the list is back in its canonical shape. Therefore
615 we must allocate an additional array, 'recycle', into which
616 we temporarily copy the items that are deleted from the
617 list. :-( */
618 PyObject *recycle_on_stack[8];
619 PyObject **recycle = recycle_on_stack; /* will allocate more if needed */
620 PyObject **item;
621 PyObject **vitem = NULL;
622 PyObject *v_as_SF = NULL; /* PySequence_Fast(v) */
623 Py_ssize_t n; /* # of elements in replacement list */
624 Py_ssize_t norig; /* # of elements in list getting replaced */
625 Py_ssize_t d; /* Change in size */
626 Py_ssize_t k;
627 size_t s;
628 int result = -1; /* guilty until proved innocent */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000629#define b ((PyListObject *)v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 if (v == NULL)
631 n = 0;
632 else {
633 if (a == b) {
634 /* Special case "a[i:j] = a" -- copy b first */
635 v = list_slice(b, 0, Py_SIZE(b));
636 if (v == NULL)
637 return result;
638 result = list_ass_slice(a, ilow, ihigh, v);
639 Py_DECREF(v);
640 return result;
641 }
642 v_as_SF = PySequence_Fast(v, "can only assign an iterable");
643 if(v_as_SF == NULL)
644 goto Error;
645 n = PySequence_Fast_GET_SIZE(v_as_SF);
646 vitem = PySequence_Fast_ITEMS(v_as_SF);
647 }
648 if (ilow < 0)
649 ilow = 0;
650 else if (ilow > Py_SIZE(a))
651 ilow = Py_SIZE(a);
Tim Peters8d9eb102004-07-31 02:24:20 +0000652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000653 if (ihigh < ilow)
654 ihigh = ilow;
655 else if (ihigh > Py_SIZE(a))
656 ihigh = Py_SIZE(a);
Armin Rigo93677f02004-07-29 12:40:23 +0000657
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000658 norig = ihigh - ilow;
659 assert(norig >= 0);
660 d = n - norig;
661 if (Py_SIZE(a) + d == 0) {
662 Py_XDECREF(v_as_SF);
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200663 return _list_clear(a);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000664 }
665 item = a->ob_item;
666 /* recycle the items that we are about to remove */
667 s = norig * sizeof(PyObject *);
Benjamin Peterson5a7d9232016-09-06 17:58:25 -0700668 /* If norig == 0, item might be NULL, in which case we may not memcpy from it. */
669 if (s) {
670 if (s > sizeof(recycle_on_stack)) {
Victor Stinner00d7abd2020-12-01 09:56:42 +0100671 recycle = (PyObject **)PyMem_Malloc(s);
Benjamin Peterson5a7d9232016-09-06 17:58:25 -0700672 if (recycle == NULL) {
673 PyErr_NoMemory();
674 goto Error;
675 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 }
Benjamin Peterson5a7d9232016-09-06 17:58:25 -0700677 memcpy(recycle, &item[ilow], s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000678 }
Tim Peters8d9eb102004-07-31 02:24:20 +0000679
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000680 if (d < 0) { /* Delete -d items */
Victor Stinner2c40f642013-07-19 23:06:21 +0200681 Py_ssize_t tail;
682 tail = (Py_SIZE(a) - ihigh) * sizeof(PyObject *);
683 memmove(&item[ihigh+d], &item[ihigh], tail);
684 if (list_resize(a, Py_SIZE(a) + d) < 0) {
685 memmove(&item[ihigh], &item[ihigh+d], tail);
686 memcpy(&item[ilow], recycle, s);
687 goto Error;
688 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000689 item = a->ob_item;
690 }
691 else if (d > 0) { /* Insert d items */
692 k = Py_SIZE(a);
693 if (list_resize(a, k+d) < 0)
694 goto Error;
695 item = a->ob_item;
696 memmove(&item[ihigh+d], &item[ihigh],
697 (k - ihigh)*sizeof(PyObject *));
698 }
699 for (k = 0; k < n; k++, ilow++) {
700 PyObject *w = vitem[k];
701 Py_XINCREF(w);
702 item[ilow] = w;
703 }
704 for (k = norig - 1; k >= 0; --k)
705 Py_XDECREF(recycle[k]);
706 result = 0;
Tim Peters8d9eb102004-07-31 02:24:20 +0000707 Error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708 if (recycle != recycle_on_stack)
Victor Stinner00d7abd2020-12-01 09:56:42 +0100709 PyMem_Free(recycle);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000710 Py_XDECREF(v_as_SF);
711 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000712#undef b
713}
714
Guido van Rossum234f9421993-06-17 12:35:49 +0000715int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000716PyList_SetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum234f9421993-06-17 12:35:49 +0000717{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 if (!PyList_Check(a)) {
719 PyErr_BadInternalCall();
720 return -1;
721 }
722 return list_ass_slice((PyListObject *)a, ilow, ihigh, v);
Guido van Rossum234f9421993-06-17 12:35:49 +0000723}
724
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000725static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000726list_inplace_repeat(PyListObject *self, Py_ssize_t n)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000727{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000728 PyObject **items;
729 Py_ssize_t size, i, j, p;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000730
731
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 size = PyList_GET_SIZE(self);
733 if (size == 0 || n == 1) {
734 Py_INCREF(self);
735 return (PyObject *)self;
736 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000738 if (n < 1) {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200739 (void)_list_clear(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000740 Py_INCREF(self);
741 return (PyObject *)self;
742 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000744 if (size > PY_SSIZE_T_MAX / n) {
745 return PyErr_NoMemory();
746 }
Christian Heimesaf98da12008-01-27 15:18:18 +0000747
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800748 if (list_resize(self, size*n) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000749 return NULL;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000750
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000751 p = size;
752 items = self->ob_item;
753 for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */
754 for (j = 0; j < size; j++) {
755 PyObject *o = items[j];
756 Py_INCREF(o);
757 items[p++] = o;
758 }
759 }
760 Py_INCREF(self);
761 return (PyObject *)self;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000762}
763
Guido van Rossum4a450d01991-04-03 19:05:18 +0000764static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000765list_ass_item(PyListObject *a, Py_ssize_t i, PyObject *v)
Guido van Rossum4a450d01991-04-03 19:05:18 +0000766{
Raymond Hettingerf1aa8ae2018-10-10 20:37:28 -0700767 if (!valid_index(i, Py_SIZE(a))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000768 PyErr_SetString(PyExc_IndexError,
769 "list assignment index out of range");
770 return -1;
771 }
772 if (v == NULL)
773 return list_ass_slice(a, i, i+1, v);
774 Py_INCREF(v);
Serhiy Storchakaf01e4082016-04-10 18:12:01 +0300775 Py_SETREF(a->ob_item[i], v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000776 return 0;
Guido van Rossum4a450d01991-04-03 19:05:18 +0000777}
778
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200779/*[clinic input]
780list.insert
781
782 index: Py_ssize_t
783 object: object
784 /
785
786Insert object before index.
787[clinic start generated code]*/
788
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000789static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200790list_insert_impl(PyListObject *self, Py_ssize_t index, PyObject *object)
791/*[clinic end generated code: output=7f35e32f60c8cb78 input=858514cf894c7eab]*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000792{
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200793 if (ins1(self, index, object) == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000794 Py_RETURN_NONE;
795 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000796}
797
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200798/*[clinic input]
799list.clear
800
801Remove all items from list.
802[clinic start generated code]*/
803
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000804static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200805list_clear_impl(PyListObject *self)
806/*[clinic end generated code: output=67a1896c01f74362 input=ca3c1646856742f6]*/
Eli Benderskycbbaa962011-02-25 05:47:53 +0000807{
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200808 _list_clear(self);
Eli Benderskycbbaa962011-02-25 05:47:53 +0000809 Py_RETURN_NONE;
810}
811
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200812/*[clinic input]
813list.copy
814
815Return a shallow copy of the list.
816[clinic start generated code]*/
817
Eli Benderskycbbaa962011-02-25 05:47:53 +0000818static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200819list_copy_impl(PyListObject *self)
820/*[clinic end generated code: output=ec6b72d6209d418e input=6453ab159e84771f]*/
Eli Benderskycbbaa962011-02-25 05:47:53 +0000821{
822 return list_slice(self, 0, Py_SIZE(self));
823}
824
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200825/*[clinic input]
826list.append
827
828 object: object
829 /
830
831Append object to the end of the list.
832[clinic start generated code]*/
833
Eli Benderskycbbaa962011-02-25 05:47:53 +0000834static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200835list_append(PyListObject *self, PyObject *object)
836/*[clinic end generated code: output=7c096003a29c0eae input=43a3fe48a7066e91]*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000837{
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200838 if (app1(self, object) == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 Py_RETURN_NONE;
840 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000841}
842
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200843/*[clinic input]
844list.extend
845
846 iterable: object
847 /
848
849Extend list by appending elements from the iterable.
850[clinic start generated code]*/
851
Barry Warsawdedf6d61998-10-09 16:37:25 +0000852static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200853list_extend(PyListObject *self, PyObject *iterable)
854/*[clinic end generated code: output=630fb3bca0c8e789 input=9ec5ba3a81be3a4d]*/
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000855{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000856 PyObject *it; /* iter(v) */
857 Py_ssize_t m; /* size of self */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200858 Py_ssize_t n; /* guess for size of iterable */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 Py_ssize_t mn; /* m + n */
860 Py_ssize_t i;
861 PyObject *(*iternext)(PyObject *);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000862
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000863 /* Special cases:
864 1) lists and tuples which can use PySequence_Fast ops
865 2) extending self to self requires making a copy first
866 */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200867 if (PyList_CheckExact(iterable) || PyTuple_CheckExact(iterable) ||
868 (PyObject *)self == iterable) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000869 PyObject **src, **dest;
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200870 iterable = PySequence_Fast(iterable, "argument must be iterable");
871 if (!iterable)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000872 return NULL;
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200873 n = PySequence_Fast_GET_SIZE(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000874 if (n == 0) {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200875 /* short circuit when iterable is empty */
876 Py_DECREF(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000877 Py_RETURN_NONE;
878 }
879 m = Py_SIZE(self);
Martin Panter94b39ce2017-01-14 06:30:37 +0000880 /* It should not be possible to allocate a list large enough to cause
881 an overflow on any relevant platform */
882 assert(m < PY_SSIZE_T_MAX - n);
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800883 if (list_resize(self, m + n) < 0) {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200884 Py_DECREF(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000885 return NULL;
886 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200887 /* note that we may still have self == iterable here for the
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000888 * situation a.extend(a), but the following code works
889 * in that case too. Just make sure to resize self
890 * before calling PySequence_Fast_ITEMS.
891 */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200892 /* populate the end of self with iterable's items */
893 src = PySequence_Fast_ITEMS(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 dest = self->ob_item + m;
895 for (i = 0; i < n; i++) {
896 PyObject *o = src[i];
897 Py_INCREF(o);
898 dest[i] = o;
899 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200900 Py_DECREF(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000901 Py_RETURN_NONE;
902 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000903
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200904 it = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000905 if (it == NULL)
906 return NULL;
Victor Stinner58ac7002020-02-07 03:04:21 +0100907 iternext = *Py_TYPE(it)->tp_iternext;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000908
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000909 /* Guess a result list size. */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200910 n = PyObject_LengthHint(iterable, 8);
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800911 if (n < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000912 Py_DECREF(it);
913 return NULL;
914 }
915 m = Py_SIZE(self);
Martin Panterb93d8632016-07-25 02:39:20 +0000916 if (m > PY_SSIZE_T_MAX - n) {
917 /* m + n overflowed; on the chance that n lied, and there really
918 * is enough room, ignore it. If n was telling the truth, we'll
919 * eventually run out of memory during the loop.
920 */
921 }
922 else {
923 mn = m + n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 /* Make room. */
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800925 if (list_resize(self, mn) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 goto error;
927 /* Make the list sane again. */
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100928 Py_SET_SIZE(self, m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000929 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 /* Run iterator to exhaustion. */
932 for (;;) {
933 PyObject *item = iternext(it);
934 if (item == NULL) {
935 if (PyErr_Occurred()) {
936 if (PyErr_ExceptionMatches(PyExc_StopIteration))
937 PyErr_Clear();
938 else
939 goto error;
940 }
941 break;
942 }
943 if (Py_SIZE(self) < self->allocated) {
944 /* steals ref */
945 PyList_SET_ITEM(self, Py_SIZE(self), item);
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100946 Py_SET_SIZE(self, Py_SIZE(self) + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 }
948 else {
949 int status = app1(self, item);
950 Py_DECREF(item); /* append creates a new ref */
951 if (status < 0)
952 goto error;
953 }
954 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000956 /* Cut back result list if initial guess was too large. */
Victor Stinner32fd6ea2013-07-16 21:45:58 +0200957 if (Py_SIZE(self) < self->allocated) {
958 if (list_resize(self, Py_SIZE(self)) < 0)
959 goto error;
960 }
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962 Py_DECREF(it);
963 Py_RETURN_NONE;
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000964
965 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 Py_DECREF(it);
967 return NULL;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000968}
969
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000970PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200971_PyList_Extend(PyListObject *self, PyObject *iterable)
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000972{
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200973 return list_extend(self, iterable);
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000974}
975
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000976static PyObject *
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000977list_inplace_concat(PyListObject *self, PyObject *other)
978{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 PyObject *result;
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000980
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200981 result = list_extend(self, other);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 if (result == NULL)
983 return result;
984 Py_DECREF(result);
985 Py_INCREF(self);
986 return (PyObject *)self;
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000987}
988
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200989/*[clinic input]
990list.pop
991
992 index: Py_ssize_t = -1
993 /
994
995Remove and return item at index (default last).
996
997Raises IndexError if list is empty or index is out of range.
998[clinic start generated code]*/
999
Raymond Hettinger97bc6182004-03-11 07:34:19 +00001000static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02001001list_pop_impl(PyListObject *self, Py_ssize_t index)
1002/*[clinic end generated code: output=6bd69dcb3f17eca8 input=b83675976f329e6f]*/
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +00001003{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001004 PyObject *v;
1005 int status;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +00001006
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007 if (Py_SIZE(self) == 0) {
1008 /* Special-case most common failure cause */
1009 PyErr_SetString(PyExc_IndexError, "pop from empty list");
1010 return NULL;
1011 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02001012 if (index < 0)
1013 index += Py_SIZE(self);
Raymond Hettingerf1aa8ae2018-10-10 20:37:28 -07001014 if (!valid_index(index, Py_SIZE(self))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 PyErr_SetString(PyExc_IndexError, "pop index out of range");
1016 return NULL;
1017 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02001018 v = self->ob_item[index];
1019 if (index == Py_SIZE(self) - 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 status = list_resize(self, Py_SIZE(self) - 1);
Victor Stinnerb27cd3e2013-07-08 22:20:44 +02001021 if (status >= 0)
1022 return v; /* and v now owns the reference the list had */
1023 else
1024 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001025 }
1026 Py_INCREF(v);
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02001027 status = list_ass_slice(self, index, index+1, (PyObject *)NULL);
Victor Stinner095d99f2013-07-17 21:58:01 +02001028 if (status < 0) {
1029 Py_DECREF(v);
1030 return NULL;
1031 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001032 return v;
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +00001033}
1034
Tim Peters8e2e7ca2002-07-19 02:33:08 +00001035/* Reverse a slice of a list in place, from lo up to (exclusive) hi. */
1036static void
1037reverse_slice(PyObject **lo, PyObject **hi)
1038{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039 assert(lo && hi);
Tim Peters8e2e7ca2002-07-19 02:33:08 +00001040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001041 --hi;
1042 while (lo < hi) {
1043 PyObject *t = *lo;
1044 *lo = *hi;
1045 *hi = t;
1046 ++lo;
1047 --hi;
1048 }
Tim Peters8e2e7ca2002-07-19 02:33:08 +00001049}
1050
Tim Petersa64dc242002-08-01 02:13:36 +00001051/* Lots of code for an adaptive, stable, natural mergesort. There are many
1052 * pieces to this algorithm; read listsort.txt for overviews and details.
1053 */
Guido van Rossum3f236de1996-12-10 23:55:39 +00001054
Daniel Stutzbach98338222010-12-02 21:55:33 +00001055/* A sortslice contains a pointer to an array of keys and a pointer to
1056 * an array of corresponding values. In other words, keys[i]
1057 * corresponds with values[i]. If values == NULL, then the keys are
1058 * also the values.
1059 *
1060 * Several convenience routines are provided here, so that keys and
1061 * values are always moved in sync.
1062 */
1063
1064typedef struct {
1065 PyObject **keys;
1066 PyObject **values;
1067} sortslice;
1068
1069Py_LOCAL_INLINE(void)
1070sortslice_copy(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j)
1071{
1072 s1->keys[i] = s2->keys[j];
1073 if (s1->values != NULL)
1074 s1->values[i] = s2->values[j];
1075}
1076
1077Py_LOCAL_INLINE(void)
Benjamin Peterson9efdcca2010-12-03 01:44:10 +00001078sortslice_copy_incr(sortslice *dst, sortslice *src)
1079{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001080 *dst->keys++ = *src->keys++;
1081 if (dst->values != NULL)
1082 *dst->values++ = *src->values++;
1083}
1084
1085Py_LOCAL_INLINE(void)
Benjamin Peterson9efdcca2010-12-03 01:44:10 +00001086sortslice_copy_decr(sortslice *dst, sortslice *src)
1087{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001088 *dst->keys-- = *src->keys--;
1089 if (dst->values != NULL)
1090 *dst->values-- = *src->values--;
1091}
1092
1093
1094Py_LOCAL_INLINE(void)
1095sortslice_memcpy(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j,
Benjamin Peterson9efdcca2010-12-03 01:44:10 +00001096 Py_ssize_t n)
1097{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001098 memcpy(&s1->keys[i], &s2->keys[j], sizeof(PyObject *) * n);
1099 if (s1->values != NULL)
1100 memcpy(&s1->values[i], &s2->values[j], sizeof(PyObject *) * n);
1101}
1102
1103Py_LOCAL_INLINE(void)
1104sortslice_memmove(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j,
Benjamin Peterson9efdcca2010-12-03 01:44:10 +00001105 Py_ssize_t n)
1106{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001107 memmove(&s1->keys[i], &s2->keys[j], sizeof(PyObject *) * n);
1108 if (s1->values != NULL)
1109 memmove(&s1->values[i], &s2->values[j], sizeof(PyObject *) * n);
1110}
1111
1112Py_LOCAL_INLINE(void)
Benjamin Peterson9efdcca2010-12-03 01:44:10 +00001113sortslice_advance(sortslice *slice, Py_ssize_t n)
1114{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001115 slice->keys += n;
1116 if (slice->values != NULL)
1117 slice->values += n;
1118}
1119
embg1e34da42018-01-28 20:03:23 -07001120/* Comparison function: ms->key_compare, which is set at run-time in
1121 * listsort_impl to optimize for various special cases.
Tim Petersa64dc242002-08-01 02:13:36 +00001122 * Returns -1 on error, 1 if x < y, 0 if x >= y.
1123 */
Guido van Rossum3f236de1996-12-10 23:55:39 +00001124
embg1e34da42018-01-28 20:03:23 -07001125#define ISLT(X, Y) (*(ms->key_compare))(X, Y, ms)
Tim Peters66860f62002-08-04 17:47:26 +00001126
1127/* Compare X to Y via "<". Goto "fail" if the comparison raises an
Tim Petersa8c974c2002-07-19 03:30:57 +00001128 error. Else "k" is set to true iff X<Y, and an "if (k)" block is
1129 started. It makes more sense in context <wink>. X and Y are PyObject*s.
1130*/
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001131#define IFLT(X, Y) if ((k = ISLT(X, Y)) < 0) goto fail; \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001132 if (k)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001133
embg1e34da42018-01-28 20:03:23 -07001134/* The maximum number of entries in a MergeState's pending-runs stack.
1135 * This is enough to sort arrays of size up to about
1136 * 32 * phi ** MAX_MERGE_PENDING
1137 * where phi ~= 1.618. 85 is ridiculouslylarge enough, good for an array
1138 * with 2**64 elements.
1139 */
1140#define MAX_MERGE_PENDING 85
1141
1142/* When we get into galloping mode, we stay there until both runs win less
1143 * often than MIN_GALLOP consecutive times. See listsort.txt for more info.
1144 */
1145#define MIN_GALLOP 7
1146
1147/* Avoid malloc for small temp arrays. */
1148#define MERGESTATE_TEMP_SIZE 256
1149
1150/* One MergeState exists on the stack per invocation of mergesort. It's just
1151 * a convenient way to pass state around among the helper functions.
1152 */
1153struct s_slice {
1154 sortslice base;
1155 Py_ssize_t len;
1156};
1157
1158typedef struct s_MergeState MergeState;
1159struct s_MergeState {
1160 /* This controls when we get *into* galloping mode. It's initialized
1161 * to MIN_GALLOP. merge_lo and merge_hi tend to nudge it higher for
1162 * random data, and lower for highly structured data.
1163 */
1164 Py_ssize_t min_gallop;
1165
1166 /* 'a' is temp storage to help with merges. It contains room for
1167 * alloced entries.
1168 */
1169 sortslice a; /* may point to temparray below */
1170 Py_ssize_t alloced;
1171
1172 /* A stack of n pending runs yet to be merged. Run #i starts at
1173 * address base[i] and extends for len[i] elements. It's always
1174 * true (so long as the indices are in bounds) that
1175 *
1176 * pending[i].base + pending[i].len == pending[i+1].base
1177 *
1178 * so we could cut the storage for this, but it's a minor amount,
1179 * and keeping all the info explicit simplifies the code.
1180 */
1181 int n;
1182 struct s_slice pending[MAX_MERGE_PENDING];
1183
1184 /* 'a' points to this when possible, rather than muck with malloc. */
1185 PyObject *temparray[MERGESTATE_TEMP_SIZE];
1186
1187 /* This is the function we will use to compare two keys,
1188 * even when none of our special cases apply and we have to use
1189 * safe_object_compare. */
1190 int (*key_compare)(PyObject *, PyObject *, MergeState *);
1191
1192 /* This function is used by unsafe_object_compare to optimize comparisons
1193 * when we know our list is type-homogeneous but we can't assume anything else.
Victor Stinner58ac7002020-02-07 03:04:21 +01001194 * In the pre-sort check it is set equal to Py_TYPE(key)->tp_richcompare */
embg1e34da42018-01-28 20:03:23 -07001195 PyObject *(*key_richcompare)(PyObject *, PyObject *, int);
1196
1197 /* This function is used by unsafe_tuple_compare to compare the first elements
1198 * of tuples. It may be set to safe_object_compare, but the idea is that hopefully
1199 * we can assume more, and use one of the special-case compares. */
1200 int (*tuple_elem_compare)(PyObject *, PyObject *, MergeState *);
1201};
1202
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001203/* binarysort is the best method for sorting small arrays: it does
1204 few compares, but can do data movement quadratic in the number of
1205 elements.
Guido van Rossum42812581998-06-17 14:15:44 +00001206 [lo, hi) is a contiguous slice of a list, and is sorted via
Tim Petersa8c974c2002-07-19 03:30:57 +00001207 binary insertion. This sort is stable.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001208 On entry, must have lo <= start <= hi, and that [lo, start) is already
1209 sorted (pass start == lo if you don't know!).
Tim Petersa8c974c2002-07-19 03:30:57 +00001210 If islt() complains return -1, else 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001211 Even in case of error, the output slice will be some permutation of
1212 the input (nothing is lost or duplicated).
1213*/
Guido van Rossum3f236de1996-12-10 23:55:39 +00001214static int
embg1e34da42018-01-28 20:03:23 -07001215binarysort(MergeState *ms, sortslice lo, PyObject **hi, PyObject **start)
Guido van Rossum3f236de1996-12-10 23:55:39 +00001216{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001217 Py_ssize_t k;
1218 PyObject **l, **p, **r;
1219 PyObject *pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001220
Daniel Stutzbach98338222010-12-02 21:55:33 +00001221 assert(lo.keys <= start && start <= hi);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001222 /* assert [lo, start) is sorted */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001223 if (lo.keys == start)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001224 ++start;
1225 for (; start < hi; ++start) {
1226 /* set l to where *start belongs */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001227 l = lo.keys;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001228 r = start;
1229 pivot = *r;
1230 /* Invariants:
1231 * pivot >= all in [lo, l).
1232 * pivot < all in [r, start).
1233 * The second is vacuously true at the start.
1234 */
1235 assert(l < r);
1236 do {
1237 p = l + ((r - l) >> 1);
1238 IFLT(pivot, *p)
1239 r = p;
1240 else
1241 l = p+1;
1242 } while (l < r);
1243 assert(l == r);
1244 /* The invariants still hold, so pivot >= all in [lo, l) and
1245 pivot < all in [l, start), so pivot belongs at l. Note
1246 that if there are elements equal to pivot, l points to the
1247 first slot after them -- that's why this sort is stable.
1248 Slide over to make room.
1249 Caution: using memmove is much slower under MSVC 5;
1250 we're not usually moving many slots. */
1251 for (p = start; p > l; --p)
1252 *p = *(p-1);
1253 *l = pivot;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001254 if (lo.values != NULL) {
1255 Py_ssize_t offset = lo.values - lo.keys;
1256 p = start + offset;
1257 pivot = *p;
1258 l += offset;
1259 for (p = start + offset; p > l; --p)
1260 *p = *(p-1);
1261 *l = pivot;
1262 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 }
1264 return 0;
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001265
1266 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001267 return -1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001268}
1269
Tim Petersa64dc242002-08-01 02:13:36 +00001270/*
1271Return the length of the run beginning at lo, in the slice [lo, hi). lo < hi
1272is required on entry. "A run" is the longest ascending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001273
Tim Petersa64dc242002-08-01 02:13:36 +00001274 lo[0] <= lo[1] <= lo[2] <= ...
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001275
Tim Petersa64dc242002-08-01 02:13:36 +00001276or the longest descending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001277
Tim Petersa64dc242002-08-01 02:13:36 +00001278 lo[0] > lo[1] > lo[2] > ...
Tim Peters3b01a122002-07-19 02:35:45 +00001279
Tim Petersa64dc242002-08-01 02:13:36 +00001280Boolean *descending is set to 0 in the former case, or to 1 in the latter.
1281For its intended use in a stable mergesort, the strictness of the defn of
1282"descending" is needed so that the caller can safely reverse a descending
1283sequence without violating stability (strict > ensures there are no equal
1284elements to get out of order).
1285
1286Returns -1 in case of error.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001287*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001288static Py_ssize_t
embg1e34da42018-01-28 20:03:23 -07001289count_run(MergeState *ms, PyObject **lo, PyObject **hi, int *descending)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001290{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001291 Py_ssize_t k;
1292 Py_ssize_t n;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001294 assert(lo < hi);
1295 *descending = 0;
1296 ++lo;
1297 if (lo == hi)
1298 return 1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001300 n = 2;
1301 IFLT(*lo, *(lo-1)) {
1302 *descending = 1;
1303 for (lo = lo+1; lo < hi; ++lo, ++n) {
1304 IFLT(*lo, *(lo-1))
1305 ;
1306 else
1307 break;
1308 }
1309 }
1310 else {
1311 for (lo = lo+1; lo < hi; ++lo, ++n) {
1312 IFLT(*lo, *(lo-1))
1313 break;
1314 }
1315 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001317 return n;
Tim Petersa64dc242002-08-01 02:13:36 +00001318fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001319 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001320}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001321
Tim Petersa64dc242002-08-01 02:13:36 +00001322/*
1323Locate the proper position of key in a sorted vector; if the vector contains
1324an element equal to key, return the position immediately to the left of
1325the leftmost equal element. [gallop_right() does the same except returns
1326the position to the right of the rightmost equal element (if any).]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001327
Tim Petersa64dc242002-08-01 02:13:36 +00001328"a" is a sorted vector with n elements, starting at a[0]. n must be > 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001329
Tim Petersa64dc242002-08-01 02:13:36 +00001330"hint" is an index at which to begin the search, 0 <= hint < n. The closer
1331hint is to the final result, the faster this runs.
1332
1333The return value is the int k in 0..n such that
1334
1335 a[k-1] < key <= a[k]
1336
1337pretending that *(a-1) is minus infinity and a[n] is plus infinity. IOW,
1338key belongs at index k; or, IOW, the first k elements of a should precede
1339key, and the last n-k should follow key.
1340
1341Returns -1 on error. See listsort.txt for info on the method.
1342*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001343static Py_ssize_t
embg1e34da42018-01-28 20:03:23 -07001344gallop_left(MergeState *ms, PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint)
Tim Petersa64dc242002-08-01 02:13:36 +00001345{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001346 Py_ssize_t ofs;
1347 Py_ssize_t lastofs;
1348 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001350 assert(key && a && n > 0 && hint >= 0 && hint < n);
Tim Petersa64dc242002-08-01 02:13:36 +00001351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001352 a += hint;
1353 lastofs = 0;
1354 ofs = 1;
1355 IFLT(*a, key) {
1356 /* a[hint] < key -- gallop right, until
1357 * a[hint + lastofs] < key <= a[hint + ofs]
1358 */
1359 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
1360 while (ofs < maxofs) {
1361 IFLT(a[ofs], key) {
1362 lastofs = ofs;
Alexey Izbyshev6bc59172019-05-23 03:01:08 +03001363 assert(ofs <= (PY_SSIZE_T_MAX - 1) / 2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001364 ofs = (ofs << 1) + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001365 }
1366 else /* key <= a[hint + ofs] */
1367 break;
1368 }
1369 if (ofs > maxofs)
1370 ofs = maxofs;
1371 /* Translate back to offsets relative to &a[0]. */
1372 lastofs += hint;
1373 ofs += hint;
1374 }
1375 else {
1376 /* key <= a[hint] -- gallop left, until
1377 * a[hint - ofs] < key <= a[hint - lastofs]
1378 */
1379 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
1380 while (ofs < maxofs) {
1381 IFLT(*(a-ofs), key)
1382 break;
1383 /* key <= a[hint - ofs] */
1384 lastofs = ofs;
Alexey Izbyshev6bc59172019-05-23 03:01:08 +03001385 assert(ofs <= (PY_SSIZE_T_MAX - 1) / 2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001386 ofs = (ofs << 1) + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001387 }
1388 if (ofs > maxofs)
1389 ofs = maxofs;
1390 /* Translate back to positive offsets relative to &a[0]. */
1391 k = lastofs;
1392 lastofs = hint - ofs;
1393 ofs = hint - k;
1394 }
1395 a -= hint;
Tim Petersa64dc242002-08-01 02:13:36 +00001396
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001397 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1398 /* Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the
1399 * right of lastofs but no farther right than ofs. Do a binary
1400 * search, with invariant a[lastofs-1] < key <= a[ofs].
1401 */
1402 ++lastofs;
1403 while (lastofs < ofs) {
1404 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001405
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001406 IFLT(a[m], key)
1407 lastofs = m+1; /* a[m] < key */
1408 else
1409 ofs = m; /* key <= a[m] */
1410 }
1411 assert(lastofs == ofs); /* so a[ofs-1] < key <= a[ofs] */
1412 return ofs;
Tim Petersa64dc242002-08-01 02:13:36 +00001413
1414fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001415 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001416}
1417
1418/*
1419Exactly like gallop_left(), except that if key already exists in a[0:n],
1420finds the position immediately to the right of the rightmost equal value.
1421
1422The return value is the int k in 0..n such that
1423
1424 a[k-1] <= key < a[k]
1425
1426or -1 if error.
1427
1428The code duplication is massive, but this is enough different given that
1429we're sticking to "<" comparisons that it's much harder to follow if
1430written as one routine with yet another "left or right?" flag.
1431*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001432static Py_ssize_t
embg1e34da42018-01-28 20:03:23 -07001433gallop_right(MergeState *ms, PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint)
Tim Petersa64dc242002-08-01 02:13:36 +00001434{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001435 Py_ssize_t ofs;
1436 Py_ssize_t lastofs;
1437 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001439 assert(key && a && n > 0 && hint >= 0 && hint < n);
Tim Petersa64dc242002-08-01 02:13:36 +00001440
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001441 a += hint;
1442 lastofs = 0;
1443 ofs = 1;
1444 IFLT(key, *a) {
1445 /* key < a[hint] -- gallop left, until
1446 * a[hint - ofs] <= key < a[hint - lastofs]
1447 */
1448 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
1449 while (ofs < maxofs) {
1450 IFLT(key, *(a-ofs)) {
1451 lastofs = ofs;
Alexey Izbyshev6bc59172019-05-23 03:01:08 +03001452 assert(ofs <= (PY_SSIZE_T_MAX - 1) / 2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001453 ofs = (ofs << 1) + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001454 }
1455 else /* a[hint - ofs] <= key */
1456 break;
1457 }
1458 if (ofs > maxofs)
1459 ofs = maxofs;
1460 /* Translate back to positive offsets relative to &a[0]. */
1461 k = lastofs;
1462 lastofs = hint - ofs;
1463 ofs = hint - k;
1464 }
1465 else {
1466 /* a[hint] <= key -- gallop right, until
1467 * a[hint + lastofs] <= key < a[hint + ofs]
1468 */
1469 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
1470 while (ofs < maxofs) {
1471 IFLT(key, a[ofs])
1472 break;
1473 /* a[hint + ofs] <= key */
1474 lastofs = ofs;
Alexey Izbyshev6bc59172019-05-23 03:01:08 +03001475 assert(ofs <= (PY_SSIZE_T_MAX - 1) / 2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001476 ofs = (ofs << 1) + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001477 }
1478 if (ofs > maxofs)
1479 ofs = maxofs;
1480 /* Translate back to offsets relative to &a[0]. */
1481 lastofs += hint;
1482 ofs += hint;
1483 }
1484 a -= hint;
Tim Petersa64dc242002-08-01 02:13:36 +00001485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001486 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1487 /* Now a[lastofs] <= key < a[ofs], so key belongs somewhere to the
1488 * right of lastofs but no farther right than ofs. Do a binary
1489 * search, with invariant a[lastofs-1] <= key < a[ofs].
1490 */
1491 ++lastofs;
1492 while (lastofs < ofs) {
1493 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001495 IFLT(key, a[m])
1496 ofs = m; /* key < a[m] */
1497 else
1498 lastofs = m+1; /* a[m] <= key */
1499 }
1500 assert(lastofs == ofs); /* so a[ofs-1] <= key < a[ofs] */
1501 return ofs;
Tim Petersa64dc242002-08-01 02:13:36 +00001502
1503fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001504 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001505}
1506
Tim Petersa64dc242002-08-01 02:13:36 +00001507/* Conceptually a MergeState's constructor. */
1508static void
Victor Stinner0fcab4a2011-01-04 12:59:15 +00001509merge_init(MergeState *ms, Py_ssize_t list_size, int has_keyfunc)
Tim Petersa64dc242002-08-01 02:13:36 +00001510{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001511 assert(ms != NULL);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001512 if (has_keyfunc) {
1513 /* The temporary space for merging will need at most half the list
1514 * size rounded up. Use the minimum possible space so we can use the
1515 * rest of temparray for other things. In particular, if there is
1516 * enough extra space, listsort() will use it to store the keys.
1517 */
1518 ms->alloced = (list_size + 1) / 2;
1519
1520 /* ms->alloced describes how many keys will be stored at
1521 ms->temparray, but we also need to store the values. Hence,
1522 ms->alloced is capped at half of MERGESTATE_TEMP_SIZE. */
1523 if (MERGESTATE_TEMP_SIZE / 2 < ms->alloced)
1524 ms->alloced = MERGESTATE_TEMP_SIZE / 2;
1525 ms->a.values = &ms->temparray[ms->alloced];
1526 }
1527 else {
1528 ms->alloced = MERGESTATE_TEMP_SIZE;
1529 ms->a.values = NULL;
1530 }
1531 ms->a.keys = ms->temparray;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001532 ms->n = 0;
1533 ms->min_gallop = MIN_GALLOP;
Tim Petersa64dc242002-08-01 02:13:36 +00001534}
1535
1536/* Free all the temp memory owned by the MergeState. This must be called
1537 * when you're done with a MergeState, and may be called before then if
1538 * you want to free the temp memory early.
1539 */
1540static void
1541merge_freemem(MergeState *ms)
1542{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001543 assert(ms != NULL);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001544 if (ms->a.keys != ms->temparray)
1545 PyMem_Free(ms->a.keys);
Tim Petersa64dc242002-08-01 02:13:36 +00001546}
1547
1548/* Ensure enough temp memory for 'need' array slots is available.
1549 * Returns 0 on success and -1 if the memory can't be gotten.
1550 */
1551static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001552merge_getmem(MergeState *ms, Py_ssize_t need)
Tim Petersa64dc242002-08-01 02:13:36 +00001553{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001554 int multiplier;
1555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001556 assert(ms != NULL);
1557 if (need <= ms->alloced)
1558 return 0;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001559
1560 multiplier = ms->a.values != NULL ? 2 : 1;
1561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001562 /* Don't realloc! That can cost cycles to copy the old data, but
1563 * we don't care what's in the block.
1564 */
1565 merge_freemem(ms);
embg1e34da42018-01-28 20:03:23 -07001566 if ((size_t)need > PY_SSIZE_T_MAX / sizeof(PyObject *) / multiplier) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001567 PyErr_NoMemory();
1568 return -1;
1569 }
embg1e34da42018-01-28 20:03:23 -07001570 ms->a.keys = (PyObject **)PyMem_Malloc(multiplier * need
Daniel Stutzbach98338222010-12-02 21:55:33 +00001571 * sizeof(PyObject *));
1572 if (ms->a.keys != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001573 ms->alloced = need;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001574 if (ms->a.values != NULL)
1575 ms->a.values = &ms->a.keys[need];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001576 return 0;
1577 }
1578 PyErr_NoMemory();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001579 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001580}
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001581#define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 : \
1582 merge_getmem(MS, NEED))
Tim Petersa64dc242002-08-01 02:13:36 +00001583
Daniel Stutzbach98338222010-12-02 21:55:33 +00001584/* Merge the na elements starting at ssa with the nb elements starting at
1585 * ssb.keys = ssa.keys + na in a stable way, in-place. na and nb must be > 0.
1586 * Must also have that ssa.keys[na-1] belongs at the end of the merge, and
1587 * should have na <= nb. See listsort.txt for more info. Return 0 if
1588 * successful, -1 if error.
Tim Petersa64dc242002-08-01 02:13:36 +00001589 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001590static Py_ssize_t
Daniel Stutzbach98338222010-12-02 21:55:33 +00001591merge_lo(MergeState *ms, sortslice ssa, Py_ssize_t na,
1592 sortslice ssb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001593{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001594 Py_ssize_t k;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001595 sortslice dest;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001596 int result = -1; /* guilty until proved innocent */
1597 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001598
Daniel Stutzbach98338222010-12-02 21:55:33 +00001599 assert(ms && ssa.keys && ssb.keys && na > 0 && nb > 0);
1600 assert(ssa.keys + na == ssb.keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001601 if (MERGE_GETMEM(ms, na) < 0)
1602 return -1;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001603 sortslice_memcpy(&ms->a, 0, &ssa, 0, na);
1604 dest = ssa;
1605 ssa = ms->a;
Tim Petersa64dc242002-08-01 02:13:36 +00001606
Daniel Stutzbach98338222010-12-02 21:55:33 +00001607 sortslice_copy_incr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001608 --nb;
1609 if (nb == 0)
1610 goto Succeed;
1611 if (na == 1)
1612 goto CopyB;
Tim Petersa64dc242002-08-01 02:13:36 +00001613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001614 min_gallop = ms->min_gallop;
1615 for (;;) {
1616 Py_ssize_t acount = 0; /* # of times A won in a row */
1617 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001619 /* Do the straightforward thing until (if ever) one run
1620 * appears to win consistently.
1621 */
1622 for (;;) {
1623 assert(na > 1 && nb > 0);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001624 k = ISLT(ssb.keys[0], ssa.keys[0]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001625 if (k) {
1626 if (k < 0)
1627 goto Fail;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001628 sortslice_copy_incr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001629 ++bcount;
1630 acount = 0;
1631 --nb;
1632 if (nb == 0)
1633 goto Succeed;
1634 if (bcount >= min_gallop)
1635 break;
1636 }
1637 else {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001638 sortslice_copy_incr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001639 ++acount;
1640 bcount = 0;
1641 --na;
1642 if (na == 1)
1643 goto CopyB;
1644 if (acount >= min_gallop)
1645 break;
1646 }
1647 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001649 /* One run is winning so consistently that galloping may
1650 * be a huge win. So try that, and continue galloping until
1651 * (if ever) neither run appears to be winning consistently
1652 * anymore.
1653 */
1654 ++min_gallop;
1655 do {
1656 assert(na > 1 && nb > 0);
1657 min_gallop -= min_gallop > 1;
1658 ms->min_gallop = min_gallop;
embg1e34da42018-01-28 20:03:23 -07001659 k = gallop_right(ms, ssb.keys[0], ssa.keys, na, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001660 acount = k;
1661 if (k) {
1662 if (k < 0)
1663 goto Fail;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001664 sortslice_memcpy(&dest, 0, &ssa, 0, k);
1665 sortslice_advance(&dest, k);
1666 sortslice_advance(&ssa, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001667 na -= k;
1668 if (na == 1)
1669 goto CopyB;
1670 /* na==0 is impossible now if the comparison
1671 * function is consistent, but we can't assume
1672 * that it is.
1673 */
1674 if (na == 0)
1675 goto Succeed;
1676 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001677 sortslice_copy_incr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001678 --nb;
1679 if (nb == 0)
1680 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001681
embg1e34da42018-01-28 20:03:23 -07001682 k = gallop_left(ms, ssa.keys[0], ssb.keys, nb, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001683 bcount = k;
1684 if (k) {
1685 if (k < 0)
1686 goto Fail;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001687 sortslice_memmove(&dest, 0, &ssb, 0, k);
1688 sortslice_advance(&dest, k);
1689 sortslice_advance(&ssb, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001690 nb -= k;
1691 if (nb == 0)
1692 goto Succeed;
1693 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001694 sortslice_copy_incr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001695 --na;
1696 if (na == 1)
1697 goto CopyB;
1698 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
1699 ++min_gallop; /* penalize it for leaving galloping mode */
1700 ms->min_gallop = min_gallop;
1701 }
Tim Petersa64dc242002-08-01 02:13:36 +00001702Succeed:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001703 result = 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001704Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001705 if (na)
Daniel Stutzbach98338222010-12-02 21:55:33 +00001706 sortslice_memcpy(&dest, 0, &ssa, 0, na);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001707 return result;
Tim Petersa64dc242002-08-01 02:13:36 +00001708CopyB:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001709 assert(na == 1 && nb > 0);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001710 /* The last element of ssa belongs at the end of the merge. */
1711 sortslice_memmove(&dest, 0, &ssb, 0, nb);
1712 sortslice_copy(&dest, nb, &ssa, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001713 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001714}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001715
Daniel Stutzbach98338222010-12-02 21:55:33 +00001716/* Merge the na elements starting at pa with the nb elements starting at
1717 * ssb.keys = ssa.keys + na in a stable way, in-place. na and nb must be > 0.
1718 * Must also have that ssa.keys[na-1] belongs at the end of the merge, and
1719 * should have na >= nb. See listsort.txt for more info. Return 0 if
1720 * successful, -1 if error.
Tim Petersa64dc242002-08-01 02:13:36 +00001721 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001722static Py_ssize_t
Daniel Stutzbach98338222010-12-02 21:55:33 +00001723merge_hi(MergeState *ms, sortslice ssa, Py_ssize_t na,
1724 sortslice ssb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001725{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001726 Py_ssize_t k;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001727 sortslice dest, basea, baseb;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001728 int result = -1; /* guilty until proved innocent */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001729 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001730
Daniel Stutzbach98338222010-12-02 21:55:33 +00001731 assert(ms && ssa.keys && ssb.keys && na > 0 && nb > 0);
1732 assert(ssa.keys + na == ssb.keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001733 if (MERGE_GETMEM(ms, nb) < 0)
1734 return -1;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001735 dest = ssb;
1736 sortslice_advance(&dest, nb-1);
1737 sortslice_memcpy(&ms->a, 0, &ssb, 0, nb);
1738 basea = ssa;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001739 baseb = ms->a;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001740 ssb.keys = ms->a.keys + nb - 1;
1741 if (ssb.values != NULL)
1742 ssb.values = ms->a.values + nb - 1;
1743 sortslice_advance(&ssa, na - 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001744
Daniel Stutzbach98338222010-12-02 21:55:33 +00001745 sortslice_copy_decr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001746 --na;
1747 if (na == 0)
1748 goto Succeed;
1749 if (nb == 1)
1750 goto CopyA;
Tim Petersa64dc242002-08-01 02:13:36 +00001751
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001752 min_gallop = ms->min_gallop;
1753 for (;;) {
1754 Py_ssize_t acount = 0; /* # of times A won in a row */
1755 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001756
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001757 /* Do the straightforward thing until (if ever) one run
1758 * appears to win consistently.
1759 */
1760 for (;;) {
1761 assert(na > 0 && nb > 1);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001762 k = ISLT(ssb.keys[0], ssa.keys[0]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001763 if (k) {
1764 if (k < 0)
1765 goto Fail;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001766 sortslice_copy_decr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001767 ++acount;
1768 bcount = 0;
1769 --na;
1770 if (na == 0)
1771 goto Succeed;
1772 if (acount >= min_gallop)
1773 break;
1774 }
1775 else {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001776 sortslice_copy_decr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001777 ++bcount;
1778 acount = 0;
1779 --nb;
1780 if (nb == 1)
1781 goto CopyA;
1782 if (bcount >= min_gallop)
1783 break;
1784 }
1785 }
Tim Petersa64dc242002-08-01 02:13:36 +00001786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001787 /* One run is winning so consistently that galloping may
1788 * be a huge win. So try that, and continue galloping until
1789 * (if ever) neither run appears to be winning consistently
1790 * anymore.
1791 */
1792 ++min_gallop;
1793 do {
1794 assert(na > 0 && nb > 1);
1795 min_gallop -= min_gallop > 1;
1796 ms->min_gallop = min_gallop;
embg1e34da42018-01-28 20:03:23 -07001797 k = gallop_right(ms, ssb.keys[0], basea.keys, na, na-1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001798 if (k < 0)
1799 goto Fail;
1800 k = na - k;
1801 acount = k;
1802 if (k) {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001803 sortslice_advance(&dest, -k);
1804 sortslice_advance(&ssa, -k);
1805 sortslice_memmove(&dest, 1, &ssa, 1, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001806 na -= k;
1807 if (na == 0)
1808 goto Succeed;
1809 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001810 sortslice_copy_decr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001811 --nb;
1812 if (nb == 1)
1813 goto CopyA;
Tim Petersa64dc242002-08-01 02:13:36 +00001814
embg1e34da42018-01-28 20:03:23 -07001815 k = gallop_left(ms, ssa.keys[0], baseb.keys, nb, nb-1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001816 if (k < 0)
1817 goto Fail;
1818 k = nb - k;
1819 bcount = k;
1820 if (k) {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001821 sortslice_advance(&dest, -k);
1822 sortslice_advance(&ssb, -k);
1823 sortslice_memcpy(&dest, 1, &ssb, 1, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001824 nb -= k;
1825 if (nb == 1)
1826 goto CopyA;
1827 /* nb==0 is impossible now if the comparison
1828 * function is consistent, but we can't assume
1829 * that it is.
1830 */
1831 if (nb == 0)
1832 goto Succeed;
1833 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001834 sortslice_copy_decr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001835 --na;
1836 if (na == 0)
1837 goto Succeed;
1838 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
1839 ++min_gallop; /* penalize it for leaving galloping mode */
1840 ms->min_gallop = min_gallop;
1841 }
Tim Petersa64dc242002-08-01 02:13:36 +00001842Succeed:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001843 result = 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001844Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001845 if (nb)
Daniel Stutzbach98338222010-12-02 21:55:33 +00001846 sortslice_memcpy(&dest, -(nb-1), &baseb, 0, nb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001847 return result;
Tim Petersa64dc242002-08-01 02:13:36 +00001848CopyA:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001849 assert(nb == 1 && na > 0);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001850 /* The first element of ssb belongs at the front of the merge. */
1851 sortslice_memmove(&dest, 1-na, &ssa, 1-na, na);
1852 sortslice_advance(&dest, -na);
1853 sortslice_advance(&ssa, -na);
1854 sortslice_copy(&dest, 0, &ssb, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001855 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001856}
1857
1858/* Merge the two runs at stack indices i and i+1.
1859 * Returns 0 on success, -1 on error.
1860 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001861static Py_ssize_t
1862merge_at(MergeState *ms, Py_ssize_t i)
Tim Petersa64dc242002-08-01 02:13:36 +00001863{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001864 sortslice ssa, ssb;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001865 Py_ssize_t na, nb;
1866 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001868 assert(ms != NULL);
1869 assert(ms->n >= 2);
1870 assert(i >= 0);
1871 assert(i == ms->n - 2 || i == ms->n - 3);
Tim Petersa64dc242002-08-01 02:13:36 +00001872
Daniel Stutzbach98338222010-12-02 21:55:33 +00001873 ssa = ms->pending[i].base;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001874 na = ms->pending[i].len;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001875 ssb = ms->pending[i+1].base;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001876 nb = ms->pending[i+1].len;
1877 assert(na > 0 && nb > 0);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001878 assert(ssa.keys + na == ssb.keys);
Tim Petersa64dc242002-08-01 02:13:36 +00001879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001880 /* Record the length of the combined runs; if i is the 3rd-last
1881 * run now, also slide over the last run (which isn't involved
1882 * in this merge). The current run i+1 goes away in any case.
1883 */
1884 ms->pending[i].len = na + nb;
1885 if (i == ms->n - 3)
1886 ms->pending[i+1] = ms->pending[i+2];
1887 --ms->n;
Tim Petersa64dc242002-08-01 02:13:36 +00001888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001889 /* Where does b start in a? Elements in a before that can be
1890 * ignored (already in place).
1891 */
embg1e34da42018-01-28 20:03:23 -07001892 k = gallop_right(ms, *ssb.keys, ssa.keys, na, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001893 if (k < 0)
1894 return -1;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001895 sortslice_advance(&ssa, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001896 na -= k;
1897 if (na == 0)
1898 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001899
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001900 /* Where does a end in b? Elements in b after that can be
1901 * ignored (already in place).
1902 */
embg1e34da42018-01-28 20:03:23 -07001903 nb = gallop_left(ms, ssa.keys[na-1], ssb.keys, nb, nb-1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001904 if (nb <= 0)
1905 return nb;
Tim Petersa64dc242002-08-01 02:13:36 +00001906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001907 /* Merge what remains of the runs, using a temp array with
1908 * min(na, nb) elements.
1909 */
1910 if (na <= nb)
Daniel Stutzbach98338222010-12-02 21:55:33 +00001911 return merge_lo(ms, ssa, na, ssb, nb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001912 else
Daniel Stutzbach98338222010-12-02 21:55:33 +00001913 return merge_hi(ms, ssa, na, ssb, nb);
Tim Petersa64dc242002-08-01 02:13:36 +00001914}
1915
1916/* Examine the stack of runs waiting to be merged, merging adjacent runs
1917 * until the stack invariants are re-established:
1918 *
1919 * 1. len[-3] > len[-2] + len[-1]
1920 * 2. len[-2] > len[-1]
1921 *
1922 * See listsort.txt for more info.
1923 *
1924 * Returns 0 on success, -1 on error.
1925 */
1926static int
1927merge_collapse(MergeState *ms)
1928{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001929 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001931 assert(ms);
1932 while (ms->n > 1) {
1933 Py_ssize_t n = ms->n - 2;
Benjamin Petersonb808d592015-02-25 10:12:26 -05001934 if ((n > 0 && p[n-1].len <= p[n].len + p[n+1].len) ||
1935 (n > 1 && p[n-2].len <= p[n-1].len + p[n].len)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001936 if (p[n-1].len < p[n+1].len)
1937 --n;
1938 if (merge_at(ms, n) < 0)
1939 return -1;
1940 }
1941 else if (p[n].len <= p[n+1].len) {
embg1e34da42018-01-28 20:03:23 -07001942 if (merge_at(ms, n) < 0)
1943 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001944 }
1945 else
1946 break;
1947 }
1948 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001949}
1950
1951/* Regardless of invariants, merge all runs on the stack until only one
1952 * remains. This is used at the end of the mergesort.
1953 *
1954 * Returns 0 on success, -1 on error.
1955 */
1956static int
1957merge_force_collapse(MergeState *ms)
1958{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001959 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001961 assert(ms);
1962 while (ms->n > 1) {
1963 Py_ssize_t n = ms->n - 2;
1964 if (n > 0 && p[n-1].len < p[n+1].len)
1965 --n;
1966 if (merge_at(ms, n) < 0)
1967 return -1;
1968 }
1969 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001970}
1971
1972/* Compute a good value for the minimum run length; natural runs shorter
1973 * than this are boosted artificially via binary insertion.
1974 *
1975 * If n < 64, return n (it's too small to bother with fancy stuff).
1976 * Else if n is an exact power of 2, return 32.
1977 * Else return an int k, 32 <= k <= 64, such that n/k is close to, but
1978 * strictly less than, an exact power of 2.
1979 *
1980 * See listsort.txt for more info.
1981 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001982static Py_ssize_t
1983merge_compute_minrun(Py_ssize_t n)
Tim Petersa64dc242002-08-01 02:13:36 +00001984{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001985 Py_ssize_t r = 0; /* becomes 1 if any 1 bits are shifted off */
Tim Petersa64dc242002-08-01 02:13:36 +00001986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001987 assert(n >= 0);
1988 while (n >= 64) {
1989 r |= n & 1;
1990 n >>= 1;
1991 }
1992 return n + r;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001993}
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001994
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001995static void
Daniel Stutzbach98338222010-12-02 21:55:33 +00001996reverse_sortslice(sortslice *s, Py_ssize_t n)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001997{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001998 reverse_slice(s->keys, &s->keys[n]);
1999 if (s->values != NULL)
2000 reverse_slice(s->values, &s->values[n]);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002001}
2002
embg1e34da42018-01-28 20:03:23 -07002003/* Here we define custom comparison functions to optimize for the cases one commonly
2004 * encounters in practice: homogeneous lists, often of one of the basic types. */
2005
2006/* This struct holds the comparison function and helper functions
2007 * selected in the pre-sort check. */
2008
2009/* These are the special case compare functions.
2010 * ms->key_compare will always point to one of these: */
2011
2012/* Heterogeneous compare: default, always safe to fall back on. */
2013static int
2014safe_object_compare(PyObject *v, PyObject *w, MergeState *ms)
2015{
2016 /* No assumptions necessary! */
2017 return PyObject_RichCompareBool(v, w, Py_LT);
2018}
2019
2020/* Homogeneous compare: safe for any two compareable objects of the same type.
2021 * (ms->key_richcompare is set to ob_type->tp_richcompare in the
2022 * pre-sort check.)
2023 */
2024static int
2025unsafe_object_compare(PyObject *v, PyObject *w, MergeState *ms)
2026{
2027 PyObject *res_obj; int res;
2028
2029 /* No assumptions, because we check first: */
Victor Stinner58ac7002020-02-07 03:04:21 +01002030 if (Py_TYPE(v)->tp_richcompare != ms->key_richcompare)
embg1e34da42018-01-28 20:03:23 -07002031 return PyObject_RichCompareBool(v, w, Py_LT);
2032
2033 assert(ms->key_richcompare != NULL);
2034 res_obj = (*(ms->key_richcompare))(v, w, Py_LT);
2035
2036 if (res_obj == Py_NotImplemented) {
2037 Py_DECREF(res_obj);
2038 return PyObject_RichCompareBool(v, w, Py_LT);
2039 }
2040 if (res_obj == NULL)
2041 return -1;
2042
2043 if (PyBool_Check(res_obj)) {
2044 res = (res_obj == Py_True);
2045 }
2046 else {
2047 res = PyObject_IsTrue(res_obj);
2048 }
2049 Py_DECREF(res_obj);
2050
2051 /* Note that we can't assert
2052 * res == PyObject_RichCompareBool(v, w, Py_LT);
2053 * because of evil compare functions like this:
2054 * lambda a, b: int(random.random() * 3) - 1)
2055 * (which is actually in test_sort.py) */
2056 return res;
2057}
2058
2059/* Latin string compare: safe for any two latin (one byte per char) strings. */
2060static int
2061unsafe_latin_compare(PyObject *v, PyObject *w, MergeState *ms)
2062{
Victor Stinner8017b802018-01-29 13:47:06 +01002063 Py_ssize_t len;
2064 int res;
embg1e34da42018-01-28 20:03:23 -07002065
2066 /* Modified from Objects/unicodeobject.c:unicode_compare, assuming: */
Andy Lesterdffe4c02020-03-04 07:15:20 -06002067 assert(Py_IS_TYPE(v, &PyUnicode_Type));
2068 assert(Py_IS_TYPE(w, &PyUnicode_Type));
embg1e34da42018-01-28 20:03:23 -07002069 assert(PyUnicode_KIND(v) == PyUnicode_KIND(w));
2070 assert(PyUnicode_KIND(v) == PyUnicode_1BYTE_KIND);
2071
2072 len = Py_MIN(PyUnicode_GET_LENGTH(v), PyUnicode_GET_LENGTH(w));
2073 res = memcmp(PyUnicode_DATA(v), PyUnicode_DATA(w), len);
2074
2075 res = (res != 0 ?
2076 res < 0 :
2077 PyUnicode_GET_LENGTH(v) < PyUnicode_GET_LENGTH(w));
2078
2079 assert(res == PyObject_RichCompareBool(v, w, Py_LT));;
2080 return res;
2081}
2082
2083/* Bounded int compare: compare any two longs that fit in a single machine word. */
2084static int
2085unsafe_long_compare(PyObject *v, PyObject *w, MergeState *ms)
2086{
2087 PyLongObject *vl, *wl; sdigit v0, w0; int res;
2088
2089 /* Modified from Objects/longobject.c:long_compare, assuming: */
Andy Lesterdffe4c02020-03-04 07:15:20 -06002090 assert(Py_IS_TYPE(v, &PyLong_Type));
2091 assert(Py_IS_TYPE(w, &PyLong_Type));
embg1e34da42018-01-28 20:03:23 -07002092 assert(Py_ABS(Py_SIZE(v)) <= 1);
2093 assert(Py_ABS(Py_SIZE(w)) <= 1);
2094
2095 vl = (PyLongObject*)v;
2096 wl = (PyLongObject*)w;
2097
2098 v0 = Py_SIZE(vl) == 0 ? 0 : (sdigit)vl->ob_digit[0];
2099 w0 = Py_SIZE(wl) == 0 ? 0 : (sdigit)wl->ob_digit[0];
2100
2101 if (Py_SIZE(vl) < 0)
2102 v0 = -v0;
2103 if (Py_SIZE(wl) < 0)
2104 w0 = -w0;
2105
2106 res = v0 < w0;
2107 assert(res == PyObject_RichCompareBool(v, w, Py_LT));
2108 return res;
2109}
2110
2111/* Float compare: compare any two floats. */
2112static int
2113unsafe_float_compare(PyObject *v, PyObject *w, MergeState *ms)
2114{
2115 int res;
2116
2117 /* Modified from Objects/floatobject.c:float_richcompare, assuming: */
Andy Lesterdffe4c02020-03-04 07:15:20 -06002118 assert(Py_IS_TYPE(v, &PyFloat_Type));
2119 assert(Py_IS_TYPE(w, &PyFloat_Type));
embg1e34da42018-01-28 20:03:23 -07002120
2121 res = PyFloat_AS_DOUBLE(v) < PyFloat_AS_DOUBLE(w);
2122 assert(res == PyObject_RichCompareBool(v, w, Py_LT));
2123 return res;
2124}
2125
2126/* Tuple compare: compare *any* two tuples, using
2127 * ms->tuple_elem_compare to compare the first elements, which is set
2128 * using the same pre-sort check as we use for ms->key_compare,
2129 * but run on the list [x[0] for x in L]. This allows us to optimize compares
2130 * on two levels (as long as [x[0] for x in L] is type-homogeneous.) The idea is
2131 * that most tuple compares don't involve x[1:]. */
2132static int
2133unsafe_tuple_compare(PyObject *v, PyObject *w, MergeState *ms)
2134{
2135 PyTupleObject *vt, *wt;
2136 Py_ssize_t i, vlen, wlen;
2137 int k;
2138
2139 /* Modified from Objects/tupleobject.c:tuplerichcompare, assuming: */
Andy Lesterdffe4c02020-03-04 07:15:20 -06002140 assert(Py_IS_TYPE(v, &PyTuple_Type));
2141 assert(Py_IS_TYPE(w, &PyTuple_Type));
embg1e34da42018-01-28 20:03:23 -07002142 assert(Py_SIZE(v) > 0);
2143 assert(Py_SIZE(w) > 0);
2144
2145 vt = (PyTupleObject *)v;
2146 wt = (PyTupleObject *)w;
2147
2148 vlen = Py_SIZE(vt);
2149 wlen = Py_SIZE(wt);
2150
2151 for (i = 0; i < vlen && i < wlen; i++) {
2152 k = PyObject_RichCompareBool(vt->ob_item[i], wt->ob_item[i], Py_EQ);
2153 if (k < 0)
2154 return -1;
2155 if (!k)
2156 break;
2157 }
2158
2159 if (i >= vlen || i >= wlen)
2160 return vlen < wlen;
2161
2162 if (i == 0)
2163 return ms->tuple_elem_compare(vt->ob_item[i], wt->ob_item[i], ms);
2164 else
2165 return PyObject_RichCompareBool(vt->ob_item[i], wt->ob_item[i], Py_LT);
2166}
2167
Tim Petersa64dc242002-08-01 02:13:36 +00002168/* An adaptive, stable, natural mergesort. See listsort.txt.
2169 * Returns Py_None on success, NULL on error. Even in case of error, the
2170 * list will be some permutation of its input state (nothing is lost or
2171 * duplicated).
2172 */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002173/*[clinic input]
2174list.sort
2175
2176 *
2177 key as keyfunc: object = None
Serhiy Storchaka202fda52017-03-12 10:10:47 +02002178 reverse: bool(accept={int}) = False
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002179
Tim Hoffmann5c224762019-06-01 06:10:02 +02002180Sort the list in ascending order and return None.
2181
2182The sort is in-place (i.e. the list itself is modified) and stable (i.e. the
2183order of two equal elements is maintained).
2184
2185If a key function is given, apply it once to each list item and sort them,
2186ascending or descending, according to their function values.
2187
2188The reverse flag can be set to sort in descending order.
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002189[clinic start generated code]*/
2190
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002191static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002192list_sort_impl(PyListObject *self, PyObject *keyfunc, int reverse)
Tim Hoffmann5c224762019-06-01 06:10:02 +02002193/*[clinic end generated code: output=57b9f9c5e23fbe42 input=cb56cd179a713060]*/
Guido van Rossum3f236de1996-12-10 23:55:39 +00002194{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002195 MergeState ms;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002196 Py_ssize_t nremaining;
2197 Py_ssize_t minrun;
Daniel Stutzbach98338222010-12-02 21:55:33 +00002198 sortslice lo;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002199 Py_ssize_t saved_ob_size, saved_allocated;
2200 PyObject **saved_ob_item;
2201 PyObject **final_ob_item;
2202 PyObject *result = NULL; /* guilty until proved innocent */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002203 Py_ssize_t i;
Daniel Stutzbach98338222010-12-02 21:55:33 +00002204 PyObject **keys;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002205
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002206 assert(self != NULL);
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002207 assert(PyList_Check(self));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002208 if (keyfunc == Py_None)
2209 keyfunc = NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002211 /* The list is temporarily made empty, so that mutations performed
2212 * by comparison functions can't affect the slice of memory we're
2213 * sorting (allowing mutations during sorting is a core-dump
2214 * factory, since ob_item may change).
2215 */
2216 saved_ob_size = Py_SIZE(self);
2217 saved_ob_item = self->ob_item;
2218 saved_allocated = self->allocated;
Victor Stinner60ac6ed2020-02-07 23:18:08 +01002219 Py_SET_SIZE(self, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002220 self->ob_item = NULL;
2221 self->allocated = -1; /* any operation will reset it to >= 0 */
Tim Peters330f9e92002-07-19 07:05:44 +00002222
Daniel Stutzbach98338222010-12-02 21:55:33 +00002223 if (keyfunc == NULL) {
2224 keys = NULL;
2225 lo.keys = saved_ob_item;
2226 lo.values = NULL;
2227 }
2228 else {
2229 if (saved_ob_size < MERGESTATE_TEMP_SIZE/2)
2230 /* Leverage stack space we allocated but won't otherwise use */
2231 keys = &ms.temparray[saved_ob_size+1];
2232 else {
Victor Stinner00d7abd2020-12-01 09:56:42 +01002233 keys = PyMem_Malloc(sizeof(PyObject *) * saved_ob_size);
Benjamin Peterson0823ffb2015-04-23 17:04:36 -04002234 if (keys == NULL) {
2235 PyErr_NoMemory();
2236 goto keyfunc_fail;
2237 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002238 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00002239
2240 for (i = 0; i < saved_ob_size ; i++) {
Petr Viktorinffd97532020-02-11 17:46:57 +01002241 keys[i] = PyObject_CallOneArg(keyfunc, saved_ob_item[i]);
Daniel Stutzbach98338222010-12-02 21:55:33 +00002242 if (keys[i] == NULL) {
2243 for (i=i-1 ; i>=0 ; i--)
2244 Py_DECREF(keys[i]);
Benjamin Peterson4a42cd42014-03-15 12:21:28 -05002245 if (saved_ob_size >= MERGESTATE_TEMP_SIZE/2)
Victor Stinner00d7abd2020-12-01 09:56:42 +01002246 PyMem_Free(keys);
Daniel Stutzbach98338222010-12-02 21:55:33 +00002247 goto keyfunc_fail;
2248 }
2249 }
2250
2251 lo.keys = keys;
2252 lo.values = saved_ob_item;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002253 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002254
embg1e34da42018-01-28 20:03:23 -07002255
2256 /* The pre-sort check: here's where we decide which compare function to use.
2257 * How much optimization is safe? We test for homogeneity with respect to
2258 * several properties that are expensive to check at compare-time, and
2259 * set ms appropriately. */
2260 if (saved_ob_size > 1) {
2261 /* Assume the first element is representative of the whole list. */
Andy Lesterdffe4c02020-03-04 07:15:20 -06002262 int keys_are_in_tuples = (Py_IS_TYPE(lo.keys[0], &PyTuple_Type) &&
embg1e34da42018-01-28 20:03:23 -07002263 Py_SIZE(lo.keys[0]) > 0);
2264
2265 PyTypeObject* key_type = (keys_are_in_tuples ?
Victor Stinner58ac7002020-02-07 03:04:21 +01002266 Py_TYPE(PyTuple_GET_ITEM(lo.keys[0], 0)) :
2267 Py_TYPE(lo.keys[0]));
embg1e34da42018-01-28 20:03:23 -07002268
2269 int keys_are_all_same_type = 1;
2270 int strings_are_latin = 1;
2271 int ints_are_bounded = 1;
2272
2273 /* Prove that assumption by checking every key. */
embg1e34da42018-01-28 20:03:23 -07002274 for (i=0; i < saved_ob_size; i++) {
2275
2276 if (keys_are_in_tuples &&
Andy Lesterdffe4c02020-03-04 07:15:20 -06002277 !(Py_IS_TYPE(lo.keys[i], &PyTuple_Type) && Py_SIZE(lo.keys[i]) != 0)) {
embg1e34da42018-01-28 20:03:23 -07002278 keys_are_in_tuples = 0;
2279 keys_are_all_same_type = 0;
2280 break;
2281 }
2282
2283 /* Note: for lists of tuples, key is the first element of the tuple
2284 * lo.keys[i], not lo.keys[i] itself! We verify type-homogeneity
2285 * for lists of tuples in the if-statement directly above. */
2286 PyObject *key = (keys_are_in_tuples ?
2287 PyTuple_GET_ITEM(lo.keys[i], 0) :
2288 lo.keys[i]);
2289
Andy Lesterdffe4c02020-03-04 07:15:20 -06002290 if (!Py_IS_TYPE(key, key_type)) {
embg1e34da42018-01-28 20:03:23 -07002291 keys_are_all_same_type = 0;
Rémi Lapeyredd5417a2019-03-25 08:25:37 +01002292 /* If keys are in tuple we must loop over the whole list to make
2293 sure all items are tuples */
2294 if (!keys_are_in_tuples) {
2295 break;
2296 }
embg1e34da42018-01-28 20:03:23 -07002297 }
2298
Rémi Lapeyredd5417a2019-03-25 08:25:37 +01002299 if (keys_are_all_same_type) {
2300 if (key_type == &PyLong_Type &&
2301 ints_are_bounded &&
2302 Py_ABS(Py_SIZE(key)) > 1) {
2303
embg1e34da42018-01-28 20:03:23 -07002304 ints_are_bounded = 0;
Rémi Lapeyredd5417a2019-03-25 08:25:37 +01002305 }
2306 else if (key_type == &PyUnicode_Type &&
2307 strings_are_latin &&
2308 PyUnicode_KIND(key) != PyUnicode_1BYTE_KIND) {
2309
2310 strings_are_latin = 0;
2311 }
2312 }
embg1e34da42018-01-28 20:03:23 -07002313 }
embg1e34da42018-01-28 20:03:23 -07002314
2315 /* Choose the best compare, given what we now know about the keys. */
2316 if (keys_are_all_same_type) {
2317
2318 if (key_type == &PyUnicode_Type && strings_are_latin) {
2319 ms.key_compare = unsafe_latin_compare;
2320 }
2321 else if (key_type == &PyLong_Type && ints_are_bounded) {
2322 ms.key_compare = unsafe_long_compare;
2323 }
2324 else if (key_type == &PyFloat_Type) {
2325 ms.key_compare = unsafe_float_compare;
2326 }
2327 else if ((ms.key_richcompare = key_type->tp_richcompare) != NULL) {
2328 ms.key_compare = unsafe_object_compare;
2329 }
Zackery Spytzebc793d2019-02-21 00:47:14 -07002330 else {
2331 ms.key_compare = safe_object_compare;
2332 }
embg1e34da42018-01-28 20:03:23 -07002333 }
2334 else {
2335 ms.key_compare = safe_object_compare;
2336 }
2337
2338 if (keys_are_in_tuples) {
2339 /* Make sure we're not dealing with tuples of tuples
2340 * (remember: here, key_type refers list [key[0] for key in keys]) */
Rémi Lapeyredd5417a2019-03-25 08:25:37 +01002341 if (key_type == &PyTuple_Type) {
embg1e34da42018-01-28 20:03:23 -07002342 ms.tuple_elem_compare = safe_object_compare;
Rémi Lapeyredd5417a2019-03-25 08:25:37 +01002343 }
2344 else {
embg1e34da42018-01-28 20:03:23 -07002345 ms.tuple_elem_compare = ms.key_compare;
Rémi Lapeyredd5417a2019-03-25 08:25:37 +01002346 }
embg1e34da42018-01-28 20:03:23 -07002347
2348 ms.key_compare = unsafe_tuple_compare;
2349 }
2350 }
2351 /* End of pre-sort check: ms is now set properly! */
2352
Daniel Stutzbach98338222010-12-02 21:55:33 +00002353 merge_init(&ms, saved_ob_size, keys != NULL);
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002355 nremaining = saved_ob_size;
2356 if (nremaining < 2)
2357 goto succeed;
Tim Peters330f9e92002-07-19 07:05:44 +00002358
Benjamin Peterson05380642010-08-23 19:35:39 +00002359 /* Reverse sort stability achieved by initially reversing the list,
2360 applying a stable forward sort, then reversing the final result. */
Daniel Stutzbach98338222010-12-02 21:55:33 +00002361 if (reverse) {
2362 if (keys != NULL)
2363 reverse_slice(&keys[0], &keys[saved_ob_size]);
2364 reverse_slice(&saved_ob_item[0], &saved_ob_item[saved_ob_size]);
2365 }
Benjamin Peterson05380642010-08-23 19:35:39 +00002366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002367 /* March over the array once, left to right, finding natural runs,
2368 * and extending short natural runs to minrun elements.
2369 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002370 minrun = merge_compute_minrun(nremaining);
2371 do {
2372 int descending;
2373 Py_ssize_t n;
Tim Peters330f9e92002-07-19 07:05:44 +00002374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002375 /* Identify next run. */
embg1e34da42018-01-28 20:03:23 -07002376 n = count_run(&ms, lo.keys, lo.keys + nremaining, &descending);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002377 if (n < 0)
2378 goto fail;
2379 if (descending)
Daniel Stutzbach98338222010-12-02 21:55:33 +00002380 reverse_sortslice(&lo, n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002381 /* If short, extend to min(minrun, nremaining). */
2382 if (n < minrun) {
2383 const Py_ssize_t force = nremaining <= minrun ?
2384 nremaining : minrun;
embg1e34da42018-01-28 20:03:23 -07002385 if (binarysort(&ms, lo, lo.keys + force, lo.keys + n) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002386 goto fail;
2387 n = force;
2388 }
2389 /* Push run onto pending-runs stack, and maybe merge. */
2390 assert(ms.n < MAX_MERGE_PENDING);
2391 ms.pending[ms.n].base = lo;
2392 ms.pending[ms.n].len = n;
2393 ++ms.n;
2394 if (merge_collapse(&ms) < 0)
2395 goto fail;
2396 /* Advance to find next run. */
Daniel Stutzbach98338222010-12-02 21:55:33 +00002397 sortslice_advance(&lo, n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002398 nremaining -= n;
2399 } while (nremaining);
Tim Peters330f9e92002-07-19 07:05:44 +00002400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002401 if (merge_force_collapse(&ms) < 0)
2402 goto fail;
2403 assert(ms.n == 1);
Daniel Stutzbach98338222010-12-02 21:55:33 +00002404 assert(keys == NULL
2405 ? ms.pending[0].base.keys == saved_ob_item
2406 : ms.pending[0].base.keys == &keys[0]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002407 assert(ms.pending[0].len == saved_ob_size);
Daniel Stutzbach98338222010-12-02 21:55:33 +00002408 lo = ms.pending[0].base;
Tim Petersa64dc242002-08-01 02:13:36 +00002409
2410succeed:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002411 result = Py_None;
Tim Peters330f9e92002-07-19 07:05:44 +00002412fail:
Daniel Stutzbach98338222010-12-02 21:55:33 +00002413 if (keys != NULL) {
2414 for (i = 0; i < saved_ob_size; i++)
2415 Py_DECREF(keys[i]);
Benjamin Petersonef87f8c2014-03-14 21:54:31 -05002416 if (saved_ob_size >= MERGESTATE_TEMP_SIZE/2)
Victor Stinner00d7abd2020-12-01 09:56:42 +01002417 PyMem_Free(keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002418 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002419
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002420 if (self->allocated != -1 && result != NULL) {
2421 /* The user mucked with the list during the sort,
2422 * and we don't already have another error to report.
2423 */
2424 PyErr_SetString(PyExc_ValueError, "list modified during sort");
2425 result = NULL;
2426 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002427
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002428 if (reverse && saved_ob_size > 1)
2429 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002431 merge_freemem(&ms);
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002432
Daniel Stutzbach98338222010-12-02 21:55:33 +00002433keyfunc_fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002434 final_ob_item = self->ob_item;
2435 i = Py_SIZE(self);
Victor Stinner60ac6ed2020-02-07 23:18:08 +01002436 Py_SET_SIZE(self, saved_ob_size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002437 self->ob_item = saved_ob_item;
2438 self->allocated = saved_allocated;
2439 if (final_ob_item != NULL) {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002440 /* we cannot use _list_clear() for this because it does not
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002441 guarantee that the list is really empty when it returns */
2442 while (--i >= 0) {
2443 Py_XDECREF(final_ob_item[i]);
2444 }
Victor Stinner00d7abd2020-12-01 09:56:42 +01002445 PyMem_Free(final_ob_item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002446 }
2447 Py_XINCREF(result);
2448 return result;
Guido van Rossum3f236de1996-12-10 23:55:39 +00002449}
Tim Peters330f9e92002-07-19 07:05:44 +00002450#undef IFLT
Tim Peters66860f62002-08-04 17:47:26 +00002451#undef ISLT
Tim Peters330f9e92002-07-19 07:05:44 +00002452
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002453int
Fred Drakea2f55112000-07-09 15:16:51 +00002454PyList_Sort(PyObject *v)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002455{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002456 if (v == NULL || !PyList_Check(v)) {
2457 PyErr_BadInternalCall();
2458 return -1;
2459 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002460 v = list_sort_impl((PyListObject *)v, NULL, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002461 if (v == NULL)
2462 return -1;
2463 Py_DECREF(v);
2464 return 0;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002465}
2466
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002467/*[clinic input]
2468list.reverse
2469
2470Reverse *IN PLACE*.
2471[clinic start generated code]*/
2472
Guido van Rossumb86c5492001-02-12 22:06:02 +00002473static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002474list_reverse_impl(PyListObject *self)
2475/*[clinic end generated code: output=482544fc451abea9 input=eefd4c3ae1bc9887]*/
Guido van Rossumb86c5492001-02-12 22:06:02 +00002476{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002477 if (Py_SIZE(self) > 1)
2478 reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
2479 Py_RETURN_NONE;
Guido van Rossumed98d481991-03-06 13:07:53 +00002480}
2481
Guido van Rossum84c76f51990-10-30 13:32:20 +00002482int
Fred Drakea2f55112000-07-09 15:16:51 +00002483PyList_Reverse(PyObject *v)
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002484{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002485 PyListObject *self = (PyListObject *)v;
Tim Peters6063e262002-08-08 01:06:39 +00002486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002487 if (v == NULL || !PyList_Check(v)) {
2488 PyErr_BadInternalCall();
2489 return -1;
2490 }
2491 if (Py_SIZE(self) > 1)
2492 reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
2493 return 0;
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002494}
2495
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002496PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00002497PyList_AsTuple(PyObject *v)
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002498{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002499 if (v == NULL || !PyList_Check(v)) {
2500 PyErr_BadInternalCall();
2501 return NULL;
2502 }
Sergey Fedoseev234531b2019-02-25 21:59:12 +05002503 return _PyTuple_FromArray(((PyListObject *)v)->ob_item, Py_SIZE(v));
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002504}
2505
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002506/*[clinic input]
2507list.index
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002508
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002509 value: object
Serhiy Storchaka80ec8362017-03-19 19:37:40 +02002510 start: slice_index(accept={int}) = 0
2511 stop: slice_index(accept={int}, c_default="PY_SSIZE_T_MAX") = sys.maxsize
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002512 /
2513
2514Return first index of value.
2515
2516Raises ValueError if the value is not present.
2517[clinic start generated code]*/
2518
2519static PyObject *
2520list_index_impl(PyListObject *self, PyObject *value, Py_ssize_t start,
2521 Py_ssize_t stop)
Serhiy Storchaka80ec8362017-03-19 19:37:40 +02002522/*[clinic end generated code: output=ec51b88787e4e481 input=40ec5826303a0eb1]*/
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002523{
2524 Py_ssize_t i;
2525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002526 if (start < 0) {
2527 start += Py_SIZE(self);
2528 if (start < 0)
2529 start = 0;
2530 }
2531 if (stop < 0) {
2532 stop += Py_SIZE(self);
2533 if (stop < 0)
2534 stop = 0;
2535 }
2536 for (i = start; i < stop && i < Py_SIZE(self); i++) {
Zackery Spytzd9e561d2019-12-30 12:32:58 -07002537 PyObject *obj = self->ob_item[i];
2538 Py_INCREF(obj);
2539 int cmp = PyObject_RichCompareBool(obj, value, Py_EQ);
2540 Py_DECREF(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002541 if (cmp > 0)
2542 return PyLong_FromSsize_t(i);
2543 else if (cmp < 0)
2544 return NULL;
2545 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002546 PyErr_Format(PyExc_ValueError, "%R is not in list", value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002547 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002548}
2549
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002550/*[clinic input]
2551list.count
2552
2553 value: object
2554 /
2555
2556Return number of occurrences of value.
2557[clinic start generated code]*/
2558
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002559static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002560list_count(PyListObject *self, PyObject *value)
2561/*[clinic end generated code: output=b1f5d284205ae714 input=3bdc3a5e6f749565]*/
Guido van Rossume6f7d181991-10-20 20:20:40 +00002562{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002563 Py_ssize_t count = 0;
2564 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002565
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002566 for (i = 0; i < Py_SIZE(self); i++) {
Zackery Spytzd9e561d2019-12-30 12:32:58 -07002567 PyObject *obj = self->ob_item[i];
Dong-hee Na14d80d02020-01-23 02:36:54 +09002568 if (obj == value) {
2569 count++;
2570 continue;
2571 }
Zackery Spytzd9e561d2019-12-30 12:32:58 -07002572 Py_INCREF(obj);
2573 int cmp = PyObject_RichCompareBool(obj, value, Py_EQ);
2574 Py_DECREF(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002575 if (cmp > 0)
2576 count++;
2577 else if (cmp < 0)
2578 return NULL;
2579 }
2580 return PyLong_FromSsize_t(count);
Guido van Rossume6f7d181991-10-20 20:20:40 +00002581}
2582
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002583/*[clinic input]
2584list.remove
2585
2586 value: object
2587 /
2588
2589Remove first occurrence of value.
2590
2591Raises ValueError if the value is not present.
2592[clinic start generated code]*/
2593
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002594static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002595list_remove(PyListObject *self, PyObject *value)
2596/*[clinic end generated code: output=f087e1951a5e30d1 input=2dc2ba5bb2fb1f82]*/
Guido van Rossumed98d481991-03-06 13:07:53 +00002597{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002598 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002599
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002600 for (i = 0; i < Py_SIZE(self); i++) {
Zackery Spytzd9e561d2019-12-30 12:32:58 -07002601 PyObject *obj = self->ob_item[i];
2602 Py_INCREF(obj);
2603 int cmp = PyObject_RichCompareBool(obj, value, Py_EQ);
2604 Py_DECREF(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002605 if (cmp > 0) {
2606 if (list_ass_slice(self, i, i+1,
2607 (PyObject *)NULL) == 0)
2608 Py_RETURN_NONE;
2609 return NULL;
2610 }
2611 else if (cmp < 0)
2612 return NULL;
2613 }
2614 PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
2615 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002616}
2617
Jeremy Hylton8caad492000-06-23 14:18:11 +00002618static int
2619list_traverse(PyListObject *o, visitproc visit, void *arg)
2620{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002621 Py_ssize_t i;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002622
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002623 for (i = Py_SIZE(o); --i >= 0; )
2624 Py_VISIT(o->ob_item[i]);
2625 return 0;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002626}
2627
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002628static PyObject *
2629list_richcompare(PyObject *v, PyObject *w, int op)
2630{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002631 PyListObject *vl, *wl;
2632 Py_ssize_t i;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002633
Brian Curtindfc80e32011-08-10 20:28:54 -05002634 if (!PyList_Check(v) || !PyList_Check(w))
2635 Py_RETURN_NOTIMPLEMENTED;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002637 vl = (PyListObject *)v;
2638 wl = (PyListObject *)w;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002640 if (Py_SIZE(vl) != Py_SIZE(wl) && (op == Py_EQ || op == Py_NE)) {
2641 /* Shortcut: if the lengths differ, the lists differ */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002642 if (op == Py_EQ)
stratakise8b19652017-11-02 11:32:54 +01002643 Py_RETURN_FALSE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002644 else
stratakise8b19652017-11-02 11:32:54 +01002645 Py_RETURN_TRUE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002646 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002647
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002648 /* Search for the first index where items are different */
2649 for (i = 0; i < Py_SIZE(vl) && i < Py_SIZE(wl); i++) {
Dong-hee Na2d5bf562019-12-31 10:04:22 +09002650 PyObject *vitem = vl->ob_item[i];
2651 PyObject *witem = wl->ob_item[i];
Inada Naokidfef9862019-12-31 10:58:37 +09002652 if (vitem == witem) {
2653 continue;
2654 }
Dong-hee Na2d5bf562019-12-31 10:04:22 +09002655
2656 Py_INCREF(vitem);
2657 Py_INCREF(witem);
sweeneydebe7ead62020-02-26 02:00:35 -05002658 int k = PyObject_RichCompareBool(vitem, witem, Py_EQ);
Dong-hee Na2d5bf562019-12-31 10:04:22 +09002659 Py_DECREF(vitem);
2660 Py_DECREF(witem);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002661 if (k < 0)
2662 return NULL;
2663 if (!k)
2664 break;
2665 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002666
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002667 if (i >= Py_SIZE(vl) || i >= Py_SIZE(wl)) {
2668 /* No more items to compare -- compare sizes */
stratakise8b19652017-11-02 11:32:54 +01002669 Py_RETURN_RICHCOMPARE(Py_SIZE(vl), Py_SIZE(wl), op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002670 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002671
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002672 /* We have an item that differs -- shortcuts for EQ/NE */
2673 if (op == Py_EQ) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02002674 Py_RETURN_FALSE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002675 }
2676 if (op == Py_NE) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02002677 Py_RETURN_TRUE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002678 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002679
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002680 /* Compare the final item again using the proper operator */
2681 return PyObject_RichCompare(vl->ob_item[i], wl->ob_item[i], op);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002682}
2683
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002684/*[clinic input]
2685list.__init__
2686
2687 iterable: object(c_default="NULL") = ()
2688 /
2689
2690Built-in mutable sequence.
2691
2692If no argument is given, the constructor creates a new empty list.
2693The argument must be an iterable if specified.
2694[clinic start generated code]*/
2695
Tim Peters6d6c1a32001-08-02 04:15:00 +00002696static int
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002697list___init___impl(PyListObject *self, PyObject *iterable)
2698/*[clinic end generated code: output=0f3c21379d01de48 input=b3f3fe7206af8f6b]*/
Tim Peters6d6c1a32001-08-02 04:15:00 +00002699{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002700 /* Verify list invariants established by PyType_GenericAlloc() */
2701 assert(0 <= Py_SIZE(self));
2702 assert(Py_SIZE(self) <= self->allocated || self->allocated == -1);
2703 assert(self->ob_item != NULL ||
2704 self->allocated == 0 || self->allocated == -1);
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002706 /* Empty previous contents */
2707 if (self->ob_item != NULL) {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002708 (void)_list_clear(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002709 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002710 if (iterable != NULL) {
Pablo Galindo372d7052018-10-28 20:16:26 +00002711 if (_PyObject_HasLen(iterable)) {
2712 Py_ssize_t iter_len = PyObject_Size(iterable);
2713 if (iter_len == -1) {
2714 if (!PyErr_ExceptionMatches(PyExc_TypeError)) {
2715 return -1;
2716 }
2717 PyErr_Clear();
2718 }
2719 if (iter_len > 0 && self->ob_item == NULL
2720 && list_preallocate_exact(self, iter_len)) {
2721 return -1;
2722 }
2723 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002724 PyObject *rv = list_extend(self, iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002725 if (rv == NULL)
2726 return -1;
2727 Py_DECREF(rv);
2728 }
2729 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002730}
2731
Petr Viktorince105542020-03-30 14:16:16 +02002732static PyObject *
2733list_vectorcall(PyObject *type, PyObject * const*args,
2734 size_t nargsf, PyObject *kwnames)
2735{
2736 if (!_PyArg_NoKwnames("list", kwnames)) {
2737 return NULL;
2738 }
2739 Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
2740 if (!_PyArg_CheckPositional("list", nargs, 0, 1)) {
2741 return NULL;
2742 }
2743
2744 assert(PyType_Check(type));
2745 PyObject *list = PyType_GenericAlloc((PyTypeObject *)type, 0);
2746 if (list == NULL) {
2747 return NULL;
2748 }
2749 if (nargs) {
2750 if (list___init___impl((PyListObject *)list, args[0])) {
2751 Py_DECREF(list);
2752 return NULL;
2753 }
2754 }
2755 return list;
2756}
2757
2758
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002759/*[clinic input]
2760list.__sizeof__
2761
2762Return the size of the list in memory, in bytes.
2763[clinic start generated code]*/
2764
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002765static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002766list___sizeof___impl(PyListObject *self)
2767/*[clinic end generated code: output=3417541f95f9a53e input=b8030a5d5ce8a187]*/
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002768{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002769 Py_ssize_t res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002770
Serhiy Storchaka5c4064e2015-12-19 20:05:25 +02002771 res = _PyObject_SIZE(Py_TYPE(self)) + self->allocated * sizeof(void*);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002772 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002773}
2774
Raymond Hettinger1021c442003-11-07 15:38:09 +00002775static PyObject *list_iter(PyObject *seq);
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002776static PyObject *list_subscript(PyListObject*, PyObject*);
2777
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002778static PyMethodDef list_methods[] = {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002779 {"__getitem__", (PyCFunction)list_subscript, METH_O|METH_COEXIST, "x.__getitem__(y) <==> x[y]"},
2780 LIST___REVERSED___METHODDEF
2781 LIST___SIZEOF___METHODDEF
2782 LIST_CLEAR_METHODDEF
2783 LIST_COPY_METHODDEF
2784 LIST_APPEND_METHODDEF
2785 LIST_INSERT_METHODDEF
2786 LIST_EXTEND_METHODDEF
2787 LIST_POP_METHODDEF
2788 LIST_REMOVE_METHODDEF
2789 LIST_INDEX_METHODDEF
2790 LIST_COUNT_METHODDEF
2791 LIST_REVERSE_METHODDEF
2792 LIST_SORT_METHODDEF
Guido van Rossum48b069a2020-04-07 09:50:06 -07002793 {"__class_getitem__", (PyCFunction)Py_GenericAlias, METH_O|METH_CLASS, PyDoc_STR("See PEP 585")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002794 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002795};
2796
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002797static PySequenceMethods list_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002798 (lenfunc)list_length, /* sq_length */
2799 (binaryfunc)list_concat, /* sq_concat */
2800 (ssizeargfunc)list_repeat, /* sq_repeat */
2801 (ssizeargfunc)list_item, /* sq_item */
2802 0, /* sq_slice */
2803 (ssizeobjargproc)list_ass_item, /* sq_ass_item */
2804 0, /* sq_ass_slice */
2805 (objobjproc)list_contains, /* sq_contains */
2806 (binaryfunc)list_inplace_concat, /* sq_inplace_concat */
2807 (ssizeargfunc)list_inplace_repeat, /* sq_inplace_repeat */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002808};
2809
Jeremy Hyltona4b4c3b2002-07-13 03:51:17 +00002810static PyObject *
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002811list_subscript(PyListObject* self, PyObject* item)
2812{
Victor Stinnera15e2602020-04-08 02:01:56 +02002813 if (_PyIndex_Check(item)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002814 Py_ssize_t i;
2815 i = PyNumber_AsSsize_t(item, PyExc_IndexError);
2816 if (i == -1 && PyErr_Occurred())
2817 return NULL;
2818 if (i < 0)
2819 i += PyList_GET_SIZE(self);
2820 return list_item(self, i);
2821 }
2822 else if (PySlice_Check(item)) {
HongWeipeng3c87a662019-09-08 18:15:56 +08002823 Py_ssize_t start, stop, step, slicelength, i;
2824 size_t cur;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002825 PyObject* result;
2826 PyObject* it;
2827 PyObject **src, **dest;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002828
Serhiy Storchakab879fe82017-04-08 09:53:51 +03002829 if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002830 return NULL;
2831 }
Serhiy Storchakab879fe82017-04-08 09:53:51 +03002832 slicelength = PySlice_AdjustIndices(Py_SIZE(self), &start, &stop,
2833 step);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002834
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002835 if (slicelength <= 0) {
2836 return PyList_New(0);
2837 }
2838 else if (step == 1) {
2839 return list_slice(self, start, stop);
2840 }
2841 else {
Sergey Fedoseev2fc46972018-08-11 18:12:07 +05002842 result = list_new_prealloc(slicelength);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002843 if (!result) return NULL;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002844
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002845 src = self->ob_item;
2846 dest = ((PyListObject *)result)->ob_item;
2847 for (cur = start, i = 0; i < slicelength;
Mark Dickinsonc7d93b72011-09-25 15:34:32 +01002848 cur += (size_t)step, i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002849 it = src[cur];
2850 Py_INCREF(it);
2851 dest[i] = it;
2852 }
Victor Stinner60ac6ed2020-02-07 23:18:08 +01002853 Py_SET_SIZE(result, slicelength);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002854 return result;
2855 }
2856 }
2857 else {
2858 PyErr_Format(PyExc_TypeError,
Terry Jan Reedyffff1442014-08-02 01:30:37 -04002859 "list indices must be integers or slices, not %.200s",
Victor Stinner58ac7002020-02-07 03:04:21 +01002860 Py_TYPE(item)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002861 return NULL;
2862 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002863}
2864
Tim Peters3b01a122002-07-19 02:35:45 +00002865static int
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002866list_ass_subscript(PyListObject* self, PyObject* item, PyObject* value)
2867{
Victor Stinnera15e2602020-04-08 02:01:56 +02002868 if (_PyIndex_Check(item)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002869 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
2870 if (i == -1 && PyErr_Occurred())
2871 return -1;
2872 if (i < 0)
2873 i += PyList_GET_SIZE(self);
2874 return list_ass_item(self, i, value);
2875 }
2876 else if (PySlice_Check(item)) {
2877 Py_ssize_t start, stop, step, slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002878
Serhiy Storchakab879fe82017-04-08 09:53:51 +03002879 if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002880 return -1;
2881 }
Serhiy Storchakab879fe82017-04-08 09:53:51 +03002882 slicelength = PySlice_AdjustIndices(Py_SIZE(self), &start, &stop,
2883 step);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002885 if (step == 1)
2886 return list_ass_slice(self, start, stop, value);
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002888 /* Make sure s[5:2] = [..] inserts at the right place:
2889 before 5, not before 2. */
2890 if ((step < 0 && start < stop) ||
2891 (step > 0 && start > stop))
2892 stop = start;
Thomas Woutersed03b412007-08-28 21:37:11 +00002893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002894 if (value == NULL) {
2895 /* delete slice */
2896 PyObject **garbage;
2897 size_t cur;
2898 Py_ssize_t i;
Victor Stinner35f28032013-11-21 12:16:35 +01002899 int res;
Tim Peters3b01a122002-07-19 02:35:45 +00002900
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002901 if (slicelength <= 0)
2902 return 0;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002904 if (step < 0) {
2905 stop = start + 1;
2906 start = stop + step*(slicelength - 1) - 1;
2907 step = -step;
2908 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002909
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002910 garbage = (PyObject**)
Victor Stinner00d7abd2020-12-01 09:56:42 +01002911 PyMem_Malloc(slicelength*sizeof(PyObject*));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002912 if (!garbage) {
2913 PyErr_NoMemory();
2914 return -1;
2915 }
Tim Peters3b01a122002-07-19 02:35:45 +00002916
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002917 /* drawing pictures might help understand these for
2918 loops. Basically, we memmove the parts of the
2919 list that are *not* part of the slice: step-1
2920 items for each item that is part of the slice,
2921 and then tail end of the list that was not
2922 covered by the slice */
2923 for (cur = start, i = 0;
2924 cur < (size_t)stop;
2925 cur += step, i++) {
2926 Py_ssize_t lim = step - 1;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002928 garbage[i] = PyList_GET_ITEM(self, cur);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002929
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002930 if (cur + step >= (size_t)Py_SIZE(self)) {
2931 lim = Py_SIZE(self) - cur - 1;
2932 }
Michael W. Hudson56796f62002-07-29 14:35:04 +00002933
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002934 memmove(self->ob_item + cur - i,
2935 self->ob_item + cur + 1,
2936 lim * sizeof(PyObject *));
2937 }
Mark Dickinsonc7d93b72011-09-25 15:34:32 +01002938 cur = start + (size_t)slicelength * step;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002939 if (cur < (size_t)Py_SIZE(self)) {
2940 memmove(self->ob_item + cur - slicelength,
2941 self->ob_item + cur,
2942 (Py_SIZE(self) - cur) *
2943 sizeof(PyObject *));
2944 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002945
Victor Stinner60ac6ed2020-02-07 23:18:08 +01002946 Py_SET_SIZE(self, Py_SIZE(self) - slicelength);
Victor Stinner35f28032013-11-21 12:16:35 +01002947 res = list_resize(self, Py_SIZE(self));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002949 for (i = 0; i < slicelength; i++) {
2950 Py_DECREF(garbage[i]);
2951 }
Victor Stinner00d7abd2020-12-01 09:56:42 +01002952 PyMem_Free(garbage);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002953
Victor Stinner35f28032013-11-21 12:16:35 +01002954 return res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002955 }
2956 else {
2957 /* assign slice */
2958 PyObject *ins, *seq;
2959 PyObject **garbage, **seqitems, **selfitems;
HongWeipeng3c87a662019-09-08 18:15:56 +08002960 Py_ssize_t i;
2961 size_t cur;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002962
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002963 /* protect against a[::-1] = a */
2964 if (self == (PyListObject*)value) {
2965 seq = list_slice((PyListObject*)value, 0,
2966 PyList_GET_SIZE(value));
2967 }
2968 else {
2969 seq = PySequence_Fast(value,
2970 "must assign iterable "
2971 "to extended slice");
2972 }
2973 if (!seq)
2974 return -1;
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002975
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002976 if (PySequence_Fast_GET_SIZE(seq) != slicelength) {
2977 PyErr_Format(PyExc_ValueError,
2978 "attempt to assign sequence of "
2979 "size %zd to extended slice of "
2980 "size %zd",
2981 PySequence_Fast_GET_SIZE(seq),
2982 slicelength);
2983 Py_DECREF(seq);
2984 return -1;
2985 }
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002987 if (!slicelength) {
2988 Py_DECREF(seq);
2989 return 0;
2990 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002992 garbage = (PyObject**)
Victor Stinner00d7abd2020-12-01 09:56:42 +01002993 PyMem_Malloc(slicelength*sizeof(PyObject*));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002994 if (!garbage) {
2995 Py_DECREF(seq);
2996 PyErr_NoMemory();
2997 return -1;
2998 }
Tim Peters3b01a122002-07-19 02:35:45 +00002999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003000 selfitems = self->ob_item;
3001 seqitems = PySequence_Fast_ITEMS(seq);
3002 for (cur = start, i = 0; i < slicelength;
Mark Dickinsonc7d93b72011-09-25 15:34:32 +01003003 cur += (size_t)step, i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003004 garbage[i] = selfitems[cur];
3005 ins = seqitems[i];
3006 Py_INCREF(ins);
3007 selfitems[cur] = ins;
3008 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00003009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003010 for (i = 0; i < slicelength; i++) {
3011 Py_DECREF(garbage[i]);
3012 }
Tim Peters3b01a122002-07-19 02:35:45 +00003013
Victor Stinner00d7abd2020-12-01 09:56:42 +01003014 PyMem_Free(garbage);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003015 Py_DECREF(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00003016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003017 return 0;
3018 }
3019 }
3020 else {
3021 PyErr_Format(PyExc_TypeError,
Terry Jan Reedyffff1442014-08-02 01:30:37 -04003022 "list indices must be integers or slices, not %.200s",
Victor Stinner58ac7002020-02-07 03:04:21 +01003023 Py_TYPE(item)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003024 return -1;
3025 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00003026}
3027
3028static PyMappingMethods list_as_mapping = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003029 (lenfunc)list_length,
3030 (binaryfunc)list_subscript,
3031 (objobjargproc)list_ass_subscript
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00003032};
3033
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003034PyTypeObject PyList_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003035 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3036 "list",
3037 sizeof(PyListObject),
3038 0,
3039 (destructor)list_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003040 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003041 0, /* tp_getattr */
3042 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003043 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003044 (reprfunc)list_repr, /* tp_repr */
3045 0, /* tp_as_number */
3046 &list_as_sequence, /* tp_as_sequence */
3047 &list_as_mapping, /* tp_as_mapping */
Georg Brandl00da4e02010-10-18 07:32:48 +00003048 PyObject_HashNotImplemented, /* tp_hash */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003049 0, /* tp_call */
3050 0, /* tp_str */
3051 PyObject_GenericGetAttr, /* tp_getattro */
3052 0, /* tp_setattro */
3053 0, /* tp_as_buffer */
3054 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02003055 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LIST_SUBCLASS, /* tp_flags */
3056 list___init____doc__, /* tp_doc */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003057 (traverseproc)list_traverse, /* tp_traverse */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02003058 (inquiry)_list_clear, /* tp_clear */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003059 list_richcompare, /* tp_richcompare */
3060 0, /* tp_weaklistoffset */
3061 list_iter, /* tp_iter */
3062 0, /* tp_iternext */
3063 list_methods, /* tp_methods */
3064 0, /* tp_members */
3065 0, /* tp_getset */
3066 0, /* tp_base */
3067 0, /* tp_dict */
3068 0, /* tp_descr_get */
3069 0, /* tp_descr_set */
3070 0, /* tp_dictoffset */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02003071 (initproc)list___init__, /* tp_init */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003072 PyType_GenericAlloc, /* tp_alloc */
3073 PyType_GenericNew, /* tp_new */
3074 PyObject_GC_Del, /* tp_free */
Petr Viktorince105542020-03-30 14:16:16 +02003075 .tp_vectorcall = list_vectorcall,
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003076};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00003077
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00003078/*********************** List Iterator **************************/
3079
3080typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003081 PyObject_HEAD
Victor Stinner7660b882013-06-24 23:59:24 +02003082 Py_ssize_t it_index;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003083 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00003084} listiterobject;
3085
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003086static void listiter_dealloc(listiterobject *);
3087static int listiter_traverse(listiterobject *, visitproc, void *);
3088static PyObject *listiter_next(listiterobject *);
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303089static PyObject *listiter_len(listiterobject *, PyObject *);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003090static PyObject *listiter_reduce_general(void *_it, int forward);
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303091static PyObject *listiter_reduce(listiterobject *, PyObject *);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003092static PyObject *listiter_setstate(listiterobject *, PyObject *state);
Raymond Hettinger435bf582004-03-18 22:43:10 +00003093
Armin Rigof5b3e362006-02-11 21:32:43 +00003094PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003095PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
3096PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00003097
3098static PyMethodDef listiter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003099 {"__length_hint__", (PyCFunction)listiter_len, METH_NOARGS, length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003100 {"__reduce__", (PyCFunction)listiter_reduce, METH_NOARGS, reduce_doc},
3101 {"__setstate__", (PyCFunction)listiter_setstate, METH_O, setstate_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003102 {NULL, NULL} /* sentinel */
Raymond Hettinger435bf582004-03-18 22:43:10 +00003103};
3104
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00003105PyTypeObject PyListIter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003106 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3107 "list_iterator", /* tp_name */
3108 sizeof(listiterobject), /* tp_basicsize */
3109 0, /* tp_itemsize */
3110 /* methods */
3111 (destructor)listiter_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003112 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003113 0, /* tp_getattr */
3114 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003115 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003116 0, /* tp_repr */
3117 0, /* tp_as_number */
3118 0, /* tp_as_sequence */
3119 0, /* tp_as_mapping */
3120 0, /* tp_hash */
3121 0, /* tp_call */
3122 0, /* tp_str */
3123 PyObject_GenericGetAttr, /* tp_getattro */
3124 0, /* tp_setattro */
3125 0, /* tp_as_buffer */
3126 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3127 0, /* tp_doc */
3128 (traverseproc)listiter_traverse, /* tp_traverse */
3129 0, /* tp_clear */
3130 0, /* tp_richcompare */
3131 0, /* tp_weaklistoffset */
3132 PyObject_SelfIter, /* tp_iter */
3133 (iternextfunc)listiter_next, /* tp_iternext */
3134 listiter_methods, /* tp_methods */
3135 0, /* tp_members */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00003136};
Raymond Hettinger1021c442003-11-07 15:38:09 +00003137
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003138
3139static PyObject *
3140list_iter(PyObject *seq)
3141{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003142 listiterobject *it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003143
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003144 if (!PyList_Check(seq)) {
3145 PyErr_BadInternalCall();
3146 return NULL;
3147 }
3148 it = PyObject_GC_New(listiterobject, &PyListIter_Type);
3149 if (it == NULL)
3150 return NULL;
3151 it->it_index = 0;
3152 Py_INCREF(seq);
3153 it->it_seq = (PyListObject *)seq;
3154 _PyObject_GC_TRACK(it);
3155 return (PyObject *)it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003156}
3157
3158static void
3159listiter_dealloc(listiterobject *it)
3160{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003161 _PyObject_GC_UNTRACK(it);
3162 Py_XDECREF(it->it_seq);
3163 PyObject_GC_Del(it);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003164}
3165
3166static int
3167listiter_traverse(listiterobject *it, visitproc visit, void *arg)
3168{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003169 Py_VISIT(it->it_seq);
3170 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003171}
3172
3173static PyObject *
3174listiter_next(listiterobject *it)
3175{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003176 PyListObject *seq;
3177 PyObject *item;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003179 assert(it != NULL);
3180 seq = it->it_seq;
3181 if (seq == NULL)
3182 return NULL;
3183 assert(PyList_Check(seq));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003184
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003185 if (it->it_index < PyList_GET_SIZE(seq)) {
3186 item = PyList_GET_ITEM(seq, it->it_index);
3187 ++it->it_index;
3188 Py_INCREF(item);
3189 return item;
3190 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003192 it->it_seq = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003193 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003194 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003195}
3196
3197static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303198listiter_len(listiterobject *it, PyObject *Py_UNUSED(ignored))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003199{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003200 Py_ssize_t len;
3201 if (it->it_seq) {
3202 len = PyList_GET_SIZE(it->it_seq) - it->it_index;
3203 if (len >= 0)
3204 return PyLong_FromSsize_t(len);
3205 }
3206 return PyLong_FromLong(0);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003207}
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003208
3209static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303210listiter_reduce(listiterobject *it, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003211{
3212 return listiter_reduce_general(it, 1);
3213}
3214
3215static PyObject *
3216listiter_setstate(listiterobject *it, PyObject *state)
3217{
Victor Stinner7660b882013-06-24 23:59:24 +02003218 Py_ssize_t index = PyLong_AsSsize_t(state);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003219 if (index == -1 && PyErr_Occurred())
3220 return NULL;
3221 if (it->it_seq != NULL) {
3222 if (index < 0)
3223 index = 0;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +00003224 else if (index > PyList_GET_SIZE(it->it_seq))
3225 index = PyList_GET_SIZE(it->it_seq); /* iterator exhausted */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003226 it->it_index = index;
3227 }
3228 Py_RETURN_NONE;
3229}
3230
Raymond Hettinger1021c442003-11-07 15:38:09 +00003231/*********************** List Reverse Iterator **************************/
3232
3233typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003234 PyObject_HEAD
3235 Py_ssize_t it_index;
3236 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger1021c442003-11-07 15:38:09 +00003237} listreviterobject;
3238
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003239static void listreviter_dealloc(listreviterobject *);
3240static int listreviter_traverse(listreviterobject *, visitproc, void *);
3241static PyObject *listreviter_next(listreviterobject *);
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303242static PyObject *listreviter_len(listreviterobject *, PyObject *);
3243static PyObject *listreviter_reduce(listreviterobject *, PyObject *);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003244static PyObject *listreviter_setstate(listreviterobject *, PyObject *);
Raymond Hettingeref9bf402004-03-10 10:10:42 +00003245
Raymond Hettingerf5b64112008-12-02 21:33:45 +00003246static PyMethodDef listreviter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003247 {"__length_hint__", (PyCFunction)listreviter_len, METH_NOARGS, length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003248 {"__reduce__", (PyCFunction)listreviter_reduce, METH_NOARGS, reduce_doc},
3249 {"__setstate__", (PyCFunction)listreviter_setstate, METH_O, setstate_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003250 {NULL, NULL} /* sentinel */
Raymond Hettingeref9bf402004-03-10 10:10:42 +00003251};
3252
Raymond Hettinger1021c442003-11-07 15:38:09 +00003253PyTypeObject PyListRevIter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003254 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3255 "list_reverseiterator", /* tp_name */
3256 sizeof(listreviterobject), /* tp_basicsize */
3257 0, /* tp_itemsize */
3258 /* methods */
3259 (destructor)listreviter_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003260 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003261 0, /* tp_getattr */
3262 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003263 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003264 0, /* tp_repr */
3265 0, /* tp_as_number */
3266 0, /* tp_as_sequence */
3267 0, /* tp_as_mapping */
3268 0, /* tp_hash */
3269 0, /* tp_call */
3270 0, /* tp_str */
3271 PyObject_GenericGetAttr, /* tp_getattro */
3272 0, /* tp_setattro */
3273 0, /* tp_as_buffer */
3274 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3275 0, /* tp_doc */
3276 (traverseproc)listreviter_traverse, /* tp_traverse */
3277 0, /* tp_clear */
3278 0, /* tp_richcompare */
3279 0, /* tp_weaklistoffset */
3280 PyObject_SelfIter, /* tp_iter */
3281 (iternextfunc)listreviter_next, /* tp_iternext */
3282 listreviter_methods, /* tp_methods */
3283 0,
Raymond Hettinger1021c442003-11-07 15:38:09 +00003284};
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003285
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02003286/*[clinic input]
3287list.__reversed__
3288
3289Return a reverse iterator over the list.
3290[clinic start generated code]*/
3291
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003292static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02003293list___reversed___impl(PyListObject *self)
3294/*[clinic end generated code: output=b166f073208c888c input=eadb6e17f8a6a280]*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003295{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003296 listreviterobject *it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003298 it = PyObject_GC_New(listreviterobject, &PyListRevIter_Type);
3299 if (it == NULL)
3300 return NULL;
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02003301 assert(PyList_Check(self));
3302 it->it_index = PyList_GET_SIZE(self) - 1;
3303 Py_INCREF(self);
3304 it->it_seq = self;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003305 PyObject_GC_Track(it);
3306 return (PyObject *)it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003307}
3308
3309static void
3310listreviter_dealloc(listreviterobject *it)
3311{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003312 PyObject_GC_UnTrack(it);
3313 Py_XDECREF(it->it_seq);
3314 PyObject_GC_Del(it);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003315}
3316
3317static int
3318listreviter_traverse(listreviterobject *it, visitproc visit, void *arg)
3319{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003320 Py_VISIT(it->it_seq);
3321 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003322}
3323
3324static PyObject *
3325listreviter_next(listreviterobject *it)
3326{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003327 PyObject *item;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003328 Py_ssize_t index;
3329 PyListObject *seq;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003330
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003331 assert(it != NULL);
3332 seq = it->it_seq;
3333 if (seq == NULL) {
3334 return NULL;
3335 }
3336 assert(PyList_Check(seq));
3337
3338 index = it->it_index;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003339 if (index>=0 && index < PyList_GET_SIZE(seq)) {
3340 item = PyList_GET_ITEM(seq, index);
3341 it->it_index--;
3342 Py_INCREF(item);
3343 return item;
3344 }
3345 it->it_index = -1;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003346 it->it_seq = NULL;
3347 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003348 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003349}
3350
Raymond Hettingerf5b64112008-12-02 21:33:45 +00003351static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303352listreviter_len(listreviterobject *it, PyObject *Py_UNUSED(ignored))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003353{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003354 Py_ssize_t len = it->it_index + 1;
3355 if (it->it_seq == NULL || PyList_GET_SIZE(it->it_seq) < len)
3356 len = 0;
3357 return PyLong_FromSsize_t(len);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003358}
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003359
3360static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303361listreviter_reduce(listreviterobject *it, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003362{
3363 return listiter_reduce_general(it, 0);
3364}
3365
3366static PyObject *
3367listreviter_setstate(listreviterobject *it, PyObject *state)
3368{
3369 Py_ssize_t index = PyLong_AsSsize_t(state);
3370 if (index == -1 && PyErr_Occurred())
3371 return NULL;
3372 if (it->it_seq != NULL) {
3373 if (index < -1)
3374 index = -1;
3375 else if (index > PyList_GET_SIZE(it->it_seq) - 1)
3376 index = PyList_GET_SIZE(it->it_seq) - 1;
3377 it->it_index = index;
3378 }
3379 Py_RETURN_NONE;
3380}
3381
3382/* common pickling support */
3383
3384static PyObject *
3385listiter_reduce_general(void *_it, int forward)
3386{
Serhiy Storchakabb86bf42018-12-11 08:28:18 +02003387 _Py_IDENTIFIER(iter);
3388 _Py_IDENTIFIER(reversed);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003389 PyObject *list;
3390
3391 /* the objects are not the same, index is of different types! */
3392 if (forward) {
3393 listiterobject *it = (listiterobject *)_it;
3394 if (it->it_seq)
Serhiy Storchakabb86bf42018-12-11 08:28:18 +02003395 return Py_BuildValue("N(O)n", _PyEval_GetBuiltinId(&PyId_iter),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003396 it->it_seq, it->it_index);
3397 } else {
3398 listreviterobject *it = (listreviterobject *)_it;
3399 if (it->it_seq)
Serhiy Storchakabb86bf42018-12-11 08:28:18 +02003400 return Py_BuildValue("N(O)n", _PyEval_GetBuiltinId(&PyId_reversed),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003401 it->it_seq, it->it_index);
3402 }
3403 /* empty iterator, create an empty list */
3404 list = PyList_New(0);
3405 if (list == NULL)
3406 return NULL;
Serhiy Storchakabb86bf42018-12-11 08:28:18 +02003407 return Py_BuildValue("N(N)", _PyEval_GetBuiltinId(&PyId_iter), list);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003408}