blob: 043256d8adbf5c0faf95f3a839f045aa3c49a7ad [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* List object implementation */
2
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003#include "Python.h"
Victor Stinnera15e2602020-04-08 02:01:56 +02004#include "pycore_abstract.h" // _PyIndex_Check()
Victor Stinnerbcda8f12018-11-21 22:27:47 +01005#include "pycore_object.h"
Sergey Fedoseev234531b2019-02-25 21:59:12 +05006#include "pycore_tupleobject.h"
Victor Stinnere281f7d2018-11-01 02:30:36 +01007#include "pycore_accu.h"
Guido van Rossumc0b618a1997-05-02 03:12:38 +00008
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00009#ifdef STDC_HEADERS
10#include <stddef.h>
11#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000012#include <sys/types.h> /* For size_t */
Guido van Rossum6cd2fe01994-08-29 12:45:32 +000013#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000014
Serhiy Storchakafdd42c42017-03-11 09:19:20 +020015/*[clinic input]
16class list "PyListObject *" "&PyList_Type"
17[clinic start generated code]*/
18/*[clinic end generated code: output=da39a3ee5e6b4b0d input=f9b222678f9f71e0]*/
19
20#include "clinic/listobject.c.h"
21
Tim Peters8d9eb102004-07-31 02:24:20 +000022/* Ensure ob_item has room for at least newsize elements, and set
23 * ob_size to newsize. If newsize > ob_size on entry, the content
24 * of the new slots at exit is undefined heap trash; it's the caller's
Ezio Melotti13925002011-03-16 11:05:33 +020025 * responsibility to overwrite them with sane values.
Tim Peters8d9eb102004-07-31 02:24:20 +000026 * The number of allocated elements may grow, shrink, or stay the same.
27 * Failure is impossible if newsize <= self.allocated on entry, although
28 * that partly relies on an assumption that the system realloc() never
29 * fails when passed a number of bytes <= the number of bytes last
30 * allocated (the C standard doesn't guarantee this, but it's hard to
31 * imagine a realloc implementation where it wouldn't be true).
32 * Note that self->ob_item may change, and even if newsize is less
33 * than ob_size on entry.
34 */
Guido van Rossuma46d51d1995-01-26 22:59:43 +000035static int
Martin v. Löwis18e16552006-02-15 17:27:45 +000036list_resize(PyListObject *self, Py_ssize_t newsize)
Guido van Rossuma46d51d1995-01-26 22:59:43 +000037{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000038 PyObject **items;
Xiang Zhang4cee0492017-02-22 12:32:30 +080039 size_t new_allocated, num_allocated_bytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000040 Py_ssize_t allocated = self->allocated;
Tim Peters65b8b842001-05-26 05:28:40 +000041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000042 /* Bypass realloc() when a previous overallocation is large enough
43 to accommodate the newsize. If the newsize falls lower than half
44 the allocated size, then proceed with the realloc() to shrink the list.
45 */
46 if (allocated >= newsize && newsize >= (allocated >> 1)) {
47 assert(self->ob_item != NULL || newsize == 0);
Victor Stinner60ac6ed2020-02-07 23:18:08 +010048 Py_SET_SIZE(self, newsize);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000049 return 0;
50 }
Raymond Hettinger4bb95402004-02-13 11:36:39 +000051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000052 /* This over-allocates proportional to the list size, making room
53 * for additional growth. The over-allocation is mild, but is
54 * enough to give linear-time amortized behavior over a long
55 * sequence of appends() in the presence of a poorly-performing
56 * system realloc().
Serhiy Storchaka2fe815e2020-03-17 23:46:00 +020057 * Add padding to make the allocated size multiple of 4.
58 * The growth pattern is: 0, 4, 8, 16, 24, 32, 40, 52, 64, 76, ...
Xiang Zhang4cee0492017-02-22 12:32:30 +080059 * Note: new_allocated won't overflow because the largest possible value
60 * is PY_SSIZE_T_MAX * (9 / 8) + 6 which always fits in a size_t.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000061 */
Serhiy Storchaka2fe815e2020-03-17 23:46:00 +020062 new_allocated = ((size_t)newsize + (newsize >> 3) + 6) & ~(size_t)3;
63 /* Do not overallocate if the new size is closer to overalocated size
64 * than to the old size.
65 */
66 if (newsize - Py_SIZE(self) > (Py_ssize_t)(new_allocated - newsize))
67 new_allocated = ((size_t)newsize + 3) & ~(size_t)3;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +000068
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000069 if (newsize == 0)
70 new_allocated = 0;
Xiang Zhang4cee0492017-02-22 12:32:30 +080071 num_allocated_bytes = new_allocated * sizeof(PyObject *);
72 items = (PyObject **)PyMem_Realloc(self->ob_item, num_allocated_bytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000073 if (items == NULL) {
74 PyErr_NoMemory();
75 return -1;
76 }
77 self->ob_item = items;
Victor Stinner60ac6ed2020-02-07 23:18:08 +010078 Py_SET_SIZE(self, newsize);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000079 self->allocated = new_allocated;
80 return 0;
Raymond Hettinger4bb95402004-02-13 11:36:39 +000081}
Guido van Rossuma46d51d1995-01-26 22:59:43 +000082
Pablo Galindo372d7052018-10-28 20:16:26 +000083static int
84list_preallocate_exact(PyListObject *self, Py_ssize_t size)
85{
86 assert(self->ob_item == NULL);
Sergey Fedoseev0e5f7712018-12-30 03:31:36 +050087 assert(size > 0);
Pablo Galindo372d7052018-10-28 20:16:26 +000088
Sergey Fedoseev0e5f7712018-12-30 03:31:36 +050089 PyObject **items = PyMem_New(PyObject*, size);
Pablo Galindo372d7052018-10-28 20:16:26 +000090 if (items == NULL) {
91 PyErr_NoMemory();
92 return -1;
93 }
94 self->ob_item = items;
Sergey Fedoseev0e5f7712018-12-30 03:31:36 +050095 self->allocated = size;
Pablo Galindo372d7052018-10-28 20:16:26 +000096 return 0;
97}
98
Victor Stinnerae00a5a2020-04-29 02:29:20 +020099void
Victor Stinner88ec9192020-06-05 02:05:41 +0200100_PyList_ClearFreeList(PyThreadState *tstate)
Raymond Hettingerfb09f0e2004-10-07 03:58:07 +0000101{
Victor Stinner88ec9192020-06-05 02:05:41 +0200102 struct _Py_list_state *state = &tstate->interp->list;
103 while (state->numfree) {
104 PyListObject *op = state->free_list[--state->numfree];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000105 assert(PyList_CheckExact(op));
106 PyObject_GC_Del(op);
107 }
Antoine Pitrou9a812cb2011-11-15 00:00:12 +0100108}
109
110void
Victor Stinner88ec9192020-06-05 02:05:41 +0200111_PyList_Fini(PyThreadState *tstate)
Antoine Pitrou9a812cb2011-11-15 00:00:12 +0100112{
Victor Stinner88ec9192020-06-05 02:05:41 +0200113 _PyList_ClearFreeList(tstate);
Raymond Hettingerfb09f0e2004-10-07 03:58:07 +0000114}
115
David Malcolm49526f42012-06-22 14:55:41 -0400116/* Print summary info about the state of the optimized allocator */
117void
118_PyList_DebugMallocStats(FILE *out)
119{
Victor Stinner88ec9192020-06-05 02:05:41 +0200120 PyInterpreterState *interp = _PyInterpreterState_GET();
121 struct _Py_list_state *state = &interp->list;
David Malcolm49526f42012-06-22 14:55:41 -0400122 _PyDebugAllocatorStats(out,
123 "free PyListObject",
Victor Stinner88ec9192020-06-05 02:05:41 +0200124 state->numfree, sizeof(PyListObject));
David Malcolm49526f42012-06-22 14:55:41 -0400125}
126
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000127PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000128PyList_New(Py_ssize_t size)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000129{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000130 if (size < 0) {
131 PyErr_BadInternalCall();
132 return NULL;
133 }
Victor Stinner88ec9192020-06-05 02:05:41 +0200134
135 PyInterpreterState *interp = _PyInterpreterState_GET();
136 struct _Py_list_state *state = &interp->list;
137 PyListObject *op;
138 if (state->numfree) {
139 state->numfree--;
140 op = state->free_list[state->numfree];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000141 _Py_NewReference((PyObject *)op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000142 }
Victor Stinner88ec9192020-06-05 02:05:41 +0200143 else {
144 op = PyObject_GC_New(PyListObject, &PyList_Type);
145 if (op == NULL) {
146 return NULL;
147 }
148 }
149 if (size <= 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000150 op->ob_item = NULL;
Victor Stinner88ec9192020-06-05 02:05:41 +0200151 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000152 else {
Mark Dickinson5d132382016-08-21 08:55:15 +0100153 op->ob_item = (PyObject **) PyMem_Calloc(size, sizeof(PyObject *));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000154 if (op->ob_item == NULL) {
155 Py_DECREF(op);
156 return PyErr_NoMemory();
157 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000158 }
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100159 Py_SET_SIZE(op, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000160 op->allocated = size;
161 _PyObject_GC_TRACK(op);
162 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000163}
164
Sergey Fedoseev2fc46972018-08-11 18:12:07 +0500165static PyObject *
166list_new_prealloc(Py_ssize_t size)
167{
168 PyListObject *op = (PyListObject *) PyList_New(0);
169 if (size == 0 || op == NULL) {
170 return (PyObject *) op;
171 }
172 assert(op->ob_item == NULL);
173 op->ob_item = PyMem_New(PyObject *, size);
174 if (op->ob_item == NULL) {
175 Py_DECREF(op);
176 return PyErr_NoMemory();
177 }
178 op->allocated = size;
179 return (PyObject *) op;
180}
181
Martin v. Löwis18e16552006-02-15 17:27:45 +0000182Py_ssize_t
Fred Drakea2f55112000-07-09 15:16:51 +0000183PyList_Size(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000184{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000185 if (!PyList_Check(op)) {
186 PyErr_BadInternalCall();
187 return -1;
188 }
189 else
190 return Py_SIZE(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000191}
192
Raymond Hettingerf1aa8ae2018-10-10 20:37:28 -0700193static inline int
194valid_index(Py_ssize_t i, Py_ssize_t limit)
195{
196 /* The cast to size_t lets us use just a single comparison
197 to check whether i is in the range: 0 <= i < limit.
198
199 See: Section 14.2 "Bounds Checking" in the Agner Fog
200 optimization manual found at:
201 https://www.agner.org/optimize/optimizing_cpp.pdf
202 */
203 return (size_t) i < (size_t) limit;
204}
205
Raymond Hettingerfdfe6182004-05-05 06:28:16 +0000206static PyObject *indexerr = NULL;
Guido van Rossum929f1b81996-08-09 20:51:27 +0000207
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000208PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000209PyList_GetItem(PyObject *op, Py_ssize_t i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000210{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000211 if (!PyList_Check(op)) {
212 PyErr_BadInternalCall();
213 return NULL;
214 }
Raymond Hettingerf1aa8ae2018-10-10 20:37:28 -0700215 if (!valid_index(i, Py_SIZE(op))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000216 if (indexerr == NULL) {
217 indexerr = PyUnicode_FromString(
218 "list index out of range");
219 if (indexerr == NULL)
220 return NULL;
221 }
222 PyErr_SetObject(PyExc_IndexError, indexerr);
223 return NULL;
224 }
225 return ((PyListObject *)op) -> ob_item[i];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000226}
227
228int
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200229PyList_SetItem(PyObject *op, Py_ssize_t i,
230 PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000231{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200232 PyObject **p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000233 if (!PyList_Check(op)) {
234 Py_XDECREF(newitem);
235 PyErr_BadInternalCall();
236 return -1;
237 }
Raymond Hettingerf1aa8ae2018-10-10 20:37:28 -0700238 if (!valid_index(i, Py_SIZE(op))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000239 Py_XDECREF(newitem);
240 PyErr_SetString(PyExc_IndexError,
241 "list assignment index out of range");
242 return -1;
243 }
244 p = ((PyListObject *)op) -> ob_item + i;
Serhiy Storchakaec397562016-04-06 09:50:03 +0300245 Py_XSETREF(*p, newitem);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000246 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000247}
248
249static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000250ins1(PyListObject *self, Py_ssize_t where, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000251{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000252 Py_ssize_t i, n = Py_SIZE(self);
253 PyObject **items;
254 if (v == NULL) {
255 PyErr_BadInternalCall();
256 return -1;
257 }
Tim Petersb38e2b62004-07-29 02:29:26 +0000258
Sergey Fedoseeve682b262020-05-25 19:54:40 +0500259 assert((size_t)n + 1 < PY_SSIZE_T_MAX);
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800260 if (list_resize(self, n+1) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000261 return -1;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000263 if (where < 0) {
264 where += n;
265 if (where < 0)
266 where = 0;
267 }
268 if (where > n)
269 where = n;
270 items = self->ob_item;
271 for (i = n; --i >= where; )
272 items[i+1] = items[i];
273 Py_INCREF(v);
274 items[where] = v;
275 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000276}
277
278int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000279PyList_Insert(PyObject *op, Py_ssize_t where, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000280{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000281 if (!PyList_Check(op)) {
282 PyErr_BadInternalCall();
283 return -1;
284 }
285 return ins1((PyListObject *)op, where, newitem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000286}
287
Raymond Hettinger40a03822004-04-12 13:05:09 +0000288static int
289app1(PyListObject *self, PyObject *v)
290{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000291 Py_ssize_t n = PyList_GET_SIZE(self);
Raymond Hettinger40a03822004-04-12 13:05:09 +0000292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000293 assert (v != NULL);
Sergey Fedoseeve682b262020-05-25 19:54:40 +0500294 assert((size_t)n + 1 < PY_SSIZE_T_MAX);
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800295 if (list_resize(self, n+1) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000296 return -1;
Raymond Hettinger40a03822004-04-12 13:05:09 +0000297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000298 Py_INCREF(v);
299 PyList_SET_ITEM(self, n, v);
300 return 0;
Raymond Hettinger40a03822004-04-12 13:05:09 +0000301}
302
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000303int
Fred Drakea2f55112000-07-09 15:16:51 +0000304PyList_Append(PyObject *op, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000305{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000306 if (PyList_Check(op) && (newitem != NULL))
307 return app1((PyListObject *)op, newitem);
308 PyErr_BadInternalCall();
309 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000310}
311
312/* Methods */
313
314static void
Fred Drakea2f55112000-07-09 15:16:51 +0000315list_dealloc(PyListObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000316{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000317 Py_ssize_t i;
318 PyObject_GC_UnTrack(op);
Jeroen Demeyer351c6742019-05-10 19:21:11 +0200319 Py_TRASHCAN_BEGIN(op, list_dealloc)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000320 if (op->ob_item != NULL) {
321 /* Do it backwards, for Christian Tismer.
322 There's a simple test case where somehow this reduces
323 thrashing when a *very* large list is created and
324 immediately deleted. */
325 i = Py_SIZE(op);
326 while (--i >= 0) {
327 Py_XDECREF(op->ob_item[i]);
328 }
329 PyMem_FREE(op->ob_item);
330 }
Victor Stinner88ec9192020-06-05 02:05:41 +0200331 PyInterpreterState *interp = _PyInterpreterState_GET();
332 struct _Py_list_state *state = &interp->list;
333 if (state->numfree < PyList_MAXFREELIST && PyList_CheckExact(op)) {
334 state->free_list[state->numfree++] = op;
335 }
336 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000337 Py_TYPE(op)->tp_free((PyObject *)op);
Victor Stinner88ec9192020-06-05 02:05:41 +0200338 }
Jeroen Demeyer351c6742019-05-10 19:21:11 +0200339 Py_TRASHCAN_END
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000340}
341
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000342static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000343list_repr(PyListObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000344{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000345 Py_ssize_t i;
Victor Stinner5c733472013-11-18 21:11:57 +0100346 PyObject *s;
Victor Stinner5c733472013-11-18 21:11:57 +0100347 _PyUnicodeWriter writer;
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200348
349 if (Py_SIZE(v) == 0) {
350 return PyUnicode_FromString("[]");
351 }
352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000353 i = Py_ReprEnter((PyObject*)v);
354 if (i != 0) {
355 return i > 0 ? PyUnicode_FromString("[...]") : NULL;
356 }
Tim Petersa7259592001-06-16 05:11:17 +0000357
Victor Stinner5c733472013-11-18 21:11:57 +0100358 _PyUnicodeWriter_Init(&writer);
359 writer.overallocate = 1;
Victor Stinnerb8fb1972013-11-18 22:15:44 +0100360 /* "[" + "1" + ", 2" * (len - 1) + "]" */
361 writer.min_length = 1 + 1 + (2 + 1) * (Py_SIZE(v) - 1) + 1;
Tim Petersa7259592001-06-16 05:11:17 +0000362
Victor Stinner5c733472013-11-18 21:11:57 +0100363 if (_PyUnicodeWriter_WriteChar(&writer, '[') < 0)
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200364 goto error;
Tim Petersa7259592001-06-16 05:11:17 +0000365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000366 /* Do repr() on each element. Note that this may mutate the list,
367 so must refetch the list size on each iteration. */
368 for (i = 0; i < Py_SIZE(v); ++i) {
Victor Stinner5c733472013-11-18 21:11:57 +0100369 if (i > 0) {
Victor Stinner4a587072013-11-19 12:54:53 +0100370 if (_PyUnicodeWriter_WriteASCIIString(&writer, ", ", 2) < 0)
Victor Stinner5c733472013-11-18 21:11:57 +0100371 goto error;
372 }
373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000374 s = PyObject_Repr(v->ob_item[i]);
Victor Stinner5c733472013-11-18 21:11:57 +0100375 if (s == NULL)
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200376 goto error;
Victor Stinner5c733472013-11-18 21:11:57 +0100377
378 if (_PyUnicodeWriter_WriteStr(&writer, s) < 0) {
379 Py_DECREF(s);
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200380 goto error;
Victor Stinner5c733472013-11-18 21:11:57 +0100381 }
382 Py_DECREF(s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000383 }
Victor Stinner5c733472013-11-18 21:11:57 +0100384
Victor Stinner4d3f1092013-11-19 12:09:00 +0100385 writer.overallocate = 0;
Victor Stinner5c733472013-11-18 21:11:57 +0100386 if (_PyUnicodeWriter_WriteChar(&writer, ']') < 0)
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200387 goto error;
Tim Petersa7259592001-06-16 05:11:17 +0000388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000389 Py_ReprLeave((PyObject *)v);
Victor Stinner5c733472013-11-18 21:11:57 +0100390 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200391
392error:
Victor Stinner5c733472013-11-18 21:11:57 +0100393 _PyUnicodeWriter_Dealloc(&writer);
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200394 Py_ReprLeave((PyObject *)v);
395 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000396}
397
Martin v. Löwis18e16552006-02-15 17:27:45 +0000398static Py_ssize_t
Fred Drakea2f55112000-07-09 15:16:51 +0000399list_length(PyListObject *a)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000400{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000401 return Py_SIZE(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000402}
403
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000404static int
Fred Drakea2f55112000-07-09 15:16:51 +0000405list_contains(PyListObject *a, PyObject *el)
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000406{
Dong-hee Na4dbf2d82020-01-28 00:02:23 +0900407 PyObject *item;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000408 Py_ssize_t i;
409 int cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000410
Dong-hee Na4dbf2d82020-01-28 00:02:23 +0900411 for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(a); ++i) {
412 item = PyList_GET_ITEM(a, i);
413 Py_INCREF(item);
Dong-hee Na9e1ed512020-01-28 02:04:25 +0900414 cmp = PyObject_RichCompareBool(item, el, Py_EQ);
Dong-hee Na4dbf2d82020-01-28 00:02:23 +0900415 Py_DECREF(item);
416 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 return cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000418}
419
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000420static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000421list_item(PyListObject *a, Py_ssize_t i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000422{
Raymond Hettingerf1aa8ae2018-10-10 20:37:28 -0700423 if (!valid_index(i, Py_SIZE(a))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000424 if (indexerr == NULL) {
425 indexerr = PyUnicode_FromString(
426 "list index out of range");
427 if (indexerr == NULL)
428 return NULL;
429 }
430 PyErr_SetObject(PyExc_IndexError, indexerr);
431 return NULL;
432 }
433 Py_INCREF(a->ob_item[i]);
434 return a->ob_item[i];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000435}
436
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000437static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000438list_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000439{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000440 PyListObject *np;
441 PyObject **src, **dest;
442 Py_ssize_t i, len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000443 len = ihigh - ilow;
Sergey Fedoseev2fc46972018-08-11 18:12:07 +0500444 np = (PyListObject *) list_new_prealloc(len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000445 if (np == NULL)
446 return NULL;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000448 src = a->ob_item + ilow;
449 dest = np->ob_item;
450 for (i = 0; i < len; i++) {
451 PyObject *v = src[i];
452 Py_INCREF(v);
453 dest[i] = v;
454 }
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100455 Py_SET_SIZE(np, len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000457}
458
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000459PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000460PyList_GetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum234f9421993-06-17 12:35:49 +0000461{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000462 if (!PyList_Check(a)) {
463 PyErr_BadInternalCall();
464 return NULL;
465 }
Sergey Fedoseevef1b88b2019-02-21 11:51:52 +0500466 if (ilow < 0) {
467 ilow = 0;
468 }
469 else if (ilow > Py_SIZE(a)) {
470 ilow = Py_SIZE(a);
471 }
472 if (ihigh < ilow) {
473 ihigh = ilow;
474 }
475 else if (ihigh > Py_SIZE(a)) {
476 ihigh = Py_SIZE(a);
477 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 return list_slice((PyListObject *)a, ilow, ihigh);
Guido van Rossum234f9421993-06-17 12:35:49 +0000479}
480
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000481static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000482list_concat(PyListObject *a, PyObject *bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000483{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 Py_ssize_t size;
485 Py_ssize_t i;
486 PyObject **src, **dest;
487 PyListObject *np;
488 if (!PyList_Check(bb)) {
489 PyErr_Format(PyExc_TypeError,
490 "can only concatenate list (not \"%.200s\") to list",
Victor Stinner58ac7002020-02-07 03:04:21 +0100491 Py_TYPE(bb)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 return NULL;
493 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000494#define b ((PyListObject *)bb)
Sergey Fedoseeve682b262020-05-25 19:54:40 +0500495 assert((size_t)Py_SIZE(a) + (size_t)Py_SIZE(b) < PY_SSIZE_T_MAX);
Martin Panterb93d8632016-07-25 02:39:20 +0000496 size = Py_SIZE(a) + Py_SIZE(b);
Sergey Fedoseev2fc46972018-08-11 18:12:07 +0500497 np = (PyListObject *) list_new_prealloc(size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000498 if (np == NULL) {
499 return NULL;
500 }
501 src = a->ob_item;
502 dest = np->ob_item;
503 for (i = 0; i < Py_SIZE(a); i++) {
504 PyObject *v = src[i];
505 Py_INCREF(v);
506 dest[i] = v;
507 }
508 src = b->ob_item;
509 dest = np->ob_item + Py_SIZE(a);
510 for (i = 0; i < Py_SIZE(b); i++) {
511 PyObject *v = src[i];
512 Py_INCREF(v);
513 dest[i] = v;
514 }
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100515 Py_SET_SIZE(np, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000517#undef b
518}
519
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000520static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000521list_repeat(PyListObject *a, Py_ssize_t n)
Guido van Rossumed98d481991-03-06 13:07:53 +0000522{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000523 Py_ssize_t i, j;
524 Py_ssize_t size;
525 PyListObject *np;
526 PyObject **p, **items;
527 PyObject *elem;
528 if (n < 0)
529 n = 0;
Mark Dickinsonc0420fd2011-09-19 19:18:37 +0100530 if (n > 0 && Py_SIZE(a) > PY_SSIZE_T_MAX / n)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000531 return PyErr_NoMemory();
Mark Dickinsonc0420fd2011-09-19 19:18:37 +0100532 size = Py_SIZE(a) * n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533 if (size == 0)
534 return PyList_New(0);
Sergey Fedoseev2fc46972018-08-11 18:12:07 +0500535 np = (PyListObject *) list_new_prealloc(size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000536 if (np == NULL)
537 return NULL;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000539 if (Py_SIZE(a) == 1) {
Sergey Fedoseev2fc46972018-08-11 18:12:07 +0500540 items = np->ob_item;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000541 elem = a->ob_item[0];
542 for (i = 0; i < n; i++) {
543 items[i] = elem;
544 Py_INCREF(elem);
545 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 }
Sergey Fedoseev2fc46972018-08-11 18:12:07 +0500547 else {
548 p = np->ob_item;
549 items = a->ob_item;
550 for (i = 0; i < n; i++) {
551 for (j = 0; j < Py_SIZE(a); j++) {
552 *p = items[j];
553 Py_INCREF(*p);
554 p++;
555 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000556 }
557 }
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100558 Py_SET_SIZE(np, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 return (PyObject *) np;
Guido van Rossumed98d481991-03-06 13:07:53 +0000560}
561
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000562static int
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200563_list_clear(PyListObject *a)
Armin Rigo93677f02004-07-29 12:40:23 +0000564{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000565 Py_ssize_t i;
566 PyObject **item = a->ob_item;
567 if (item != NULL) {
568 /* Because XDECREF can recursively invoke operations on
569 this list, we make it empty first. */
570 i = Py_SIZE(a);
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100571 Py_SET_SIZE(a, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000572 a->ob_item = NULL;
573 a->allocated = 0;
574 while (--i >= 0) {
575 Py_XDECREF(item[i]);
576 }
577 PyMem_FREE(item);
578 }
579 /* Never fails; the return value can be ignored.
580 Note that there is no guarantee that the list is actually empty
581 at this point, because XDECREF may have populated it again! */
582 return 0;
Armin Rigo93677f02004-07-29 12:40:23 +0000583}
584
Tim Peters8fc4a912004-07-31 21:53:19 +0000585/* a[ilow:ihigh] = v if v != NULL.
586 * del a[ilow:ihigh] if v == NULL.
587 *
588 * Special speed gimmick: when v is NULL and ihigh - ilow <= 8, it's
589 * guaranteed the call cannot fail.
590 */
Armin Rigo93677f02004-07-29 12:40:23 +0000591static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000592list_ass_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000593{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 /* Because [X]DECREF can recursively invoke list operations on
595 this list, we must postpone all [X]DECREF activity until
596 after the list is back in its canonical shape. Therefore
597 we must allocate an additional array, 'recycle', into which
598 we temporarily copy the items that are deleted from the
599 list. :-( */
600 PyObject *recycle_on_stack[8];
601 PyObject **recycle = recycle_on_stack; /* will allocate more if needed */
602 PyObject **item;
603 PyObject **vitem = NULL;
604 PyObject *v_as_SF = NULL; /* PySequence_Fast(v) */
605 Py_ssize_t n; /* # of elements in replacement list */
606 Py_ssize_t norig; /* # of elements in list getting replaced */
607 Py_ssize_t d; /* Change in size */
608 Py_ssize_t k;
609 size_t s;
610 int result = -1; /* guilty until proved innocent */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000611#define b ((PyListObject *)v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 if (v == NULL)
613 n = 0;
614 else {
615 if (a == b) {
616 /* Special case "a[i:j] = a" -- copy b first */
617 v = list_slice(b, 0, Py_SIZE(b));
618 if (v == NULL)
619 return result;
620 result = list_ass_slice(a, ilow, ihigh, v);
621 Py_DECREF(v);
622 return result;
623 }
624 v_as_SF = PySequence_Fast(v, "can only assign an iterable");
625 if(v_as_SF == NULL)
626 goto Error;
627 n = PySequence_Fast_GET_SIZE(v_as_SF);
628 vitem = PySequence_Fast_ITEMS(v_as_SF);
629 }
630 if (ilow < 0)
631 ilow = 0;
632 else if (ilow > Py_SIZE(a))
633 ilow = Py_SIZE(a);
Tim Peters8d9eb102004-07-31 02:24:20 +0000634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000635 if (ihigh < ilow)
636 ihigh = ilow;
637 else if (ihigh > Py_SIZE(a))
638 ihigh = Py_SIZE(a);
Armin Rigo93677f02004-07-29 12:40:23 +0000639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 norig = ihigh - ilow;
641 assert(norig >= 0);
642 d = n - norig;
643 if (Py_SIZE(a) + d == 0) {
644 Py_XDECREF(v_as_SF);
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200645 return _list_clear(a);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 }
647 item = a->ob_item;
648 /* recycle the items that we are about to remove */
649 s = norig * sizeof(PyObject *);
Benjamin Peterson5a7d9232016-09-06 17:58:25 -0700650 /* If norig == 0, item might be NULL, in which case we may not memcpy from it. */
651 if (s) {
652 if (s > sizeof(recycle_on_stack)) {
653 recycle = (PyObject **)PyMem_MALLOC(s);
654 if (recycle == NULL) {
655 PyErr_NoMemory();
656 goto Error;
657 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000658 }
Benjamin Peterson5a7d9232016-09-06 17:58:25 -0700659 memcpy(recycle, &item[ilow], s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000660 }
Tim Peters8d9eb102004-07-31 02:24:20 +0000661
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000662 if (d < 0) { /* Delete -d items */
Victor Stinner2c40f642013-07-19 23:06:21 +0200663 Py_ssize_t tail;
664 tail = (Py_SIZE(a) - ihigh) * sizeof(PyObject *);
665 memmove(&item[ihigh+d], &item[ihigh], tail);
666 if (list_resize(a, Py_SIZE(a) + d) < 0) {
667 memmove(&item[ihigh], &item[ihigh+d], tail);
668 memcpy(&item[ilow], recycle, s);
669 goto Error;
670 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000671 item = a->ob_item;
672 }
673 else if (d > 0) { /* Insert d items */
674 k = Py_SIZE(a);
675 if (list_resize(a, k+d) < 0)
676 goto Error;
677 item = a->ob_item;
678 memmove(&item[ihigh+d], &item[ihigh],
679 (k - ihigh)*sizeof(PyObject *));
680 }
681 for (k = 0; k < n; k++, ilow++) {
682 PyObject *w = vitem[k];
683 Py_XINCREF(w);
684 item[ilow] = w;
685 }
686 for (k = norig - 1; k >= 0; --k)
687 Py_XDECREF(recycle[k]);
688 result = 0;
Tim Peters8d9eb102004-07-31 02:24:20 +0000689 Error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000690 if (recycle != recycle_on_stack)
691 PyMem_FREE(recycle);
692 Py_XDECREF(v_as_SF);
693 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000694#undef b
695}
696
Guido van Rossum234f9421993-06-17 12:35:49 +0000697int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000698PyList_SetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum234f9421993-06-17 12:35:49 +0000699{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000700 if (!PyList_Check(a)) {
701 PyErr_BadInternalCall();
702 return -1;
703 }
704 return list_ass_slice((PyListObject *)a, ilow, ihigh, v);
Guido van Rossum234f9421993-06-17 12:35:49 +0000705}
706
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000707static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000708list_inplace_repeat(PyListObject *self, Py_ssize_t n)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000709{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000710 PyObject **items;
711 Py_ssize_t size, i, j, p;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000712
713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 size = PyList_GET_SIZE(self);
715 if (size == 0 || n == 1) {
716 Py_INCREF(self);
717 return (PyObject *)self;
718 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000719
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000720 if (n < 1) {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200721 (void)_list_clear(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000722 Py_INCREF(self);
723 return (PyObject *)self;
724 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000725
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000726 if (size > PY_SSIZE_T_MAX / n) {
727 return PyErr_NoMemory();
728 }
Christian Heimesaf98da12008-01-27 15:18:18 +0000729
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800730 if (list_resize(self, size*n) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000731 return NULL;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000732
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000733 p = size;
734 items = self->ob_item;
735 for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */
736 for (j = 0; j < size; j++) {
737 PyObject *o = items[j];
738 Py_INCREF(o);
739 items[p++] = o;
740 }
741 }
742 Py_INCREF(self);
743 return (PyObject *)self;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000744}
745
Guido van Rossum4a450d01991-04-03 19:05:18 +0000746static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000747list_ass_item(PyListObject *a, Py_ssize_t i, PyObject *v)
Guido van Rossum4a450d01991-04-03 19:05:18 +0000748{
Raymond Hettingerf1aa8ae2018-10-10 20:37:28 -0700749 if (!valid_index(i, Py_SIZE(a))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000750 PyErr_SetString(PyExc_IndexError,
751 "list assignment index out of range");
752 return -1;
753 }
754 if (v == NULL)
755 return list_ass_slice(a, i, i+1, v);
756 Py_INCREF(v);
Serhiy Storchakaf01e4082016-04-10 18:12:01 +0300757 Py_SETREF(a->ob_item[i], v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 return 0;
Guido van Rossum4a450d01991-04-03 19:05:18 +0000759}
760
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200761/*[clinic input]
762list.insert
763
764 index: Py_ssize_t
765 object: object
766 /
767
768Insert object before index.
769[clinic start generated code]*/
770
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000771static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200772list_insert_impl(PyListObject *self, Py_ssize_t index, PyObject *object)
773/*[clinic end generated code: output=7f35e32f60c8cb78 input=858514cf894c7eab]*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000774{
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200775 if (ins1(self, index, object) == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000776 Py_RETURN_NONE;
777 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000778}
779
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200780/*[clinic input]
781list.clear
782
783Remove all items from list.
784[clinic start generated code]*/
785
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000786static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200787list_clear_impl(PyListObject *self)
788/*[clinic end generated code: output=67a1896c01f74362 input=ca3c1646856742f6]*/
Eli Benderskycbbaa962011-02-25 05:47:53 +0000789{
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200790 _list_clear(self);
Eli Benderskycbbaa962011-02-25 05:47:53 +0000791 Py_RETURN_NONE;
792}
793
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200794/*[clinic input]
795list.copy
796
797Return a shallow copy of the list.
798[clinic start generated code]*/
799
Eli Benderskycbbaa962011-02-25 05:47:53 +0000800static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200801list_copy_impl(PyListObject *self)
802/*[clinic end generated code: output=ec6b72d6209d418e input=6453ab159e84771f]*/
Eli Benderskycbbaa962011-02-25 05:47:53 +0000803{
804 return list_slice(self, 0, Py_SIZE(self));
805}
806
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200807/*[clinic input]
808list.append
809
810 object: object
811 /
812
813Append object to the end of the list.
814[clinic start generated code]*/
815
Eli Benderskycbbaa962011-02-25 05:47:53 +0000816static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200817list_append(PyListObject *self, PyObject *object)
818/*[clinic end generated code: output=7c096003a29c0eae input=43a3fe48a7066e91]*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000819{
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200820 if (app1(self, object) == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000821 Py_RETURN_NONE;
822 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000823}
824
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200825/*[clinic input]
826list.extend
827
828 iterable: object
829 /
830
831Extend list by appending elements from the iterable.
832[clinic start generated code]*/
833
Barry Warsawdedf6d61998-10-09 16:37:25 +0000834static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200835list_extend(PyListObject *self, PyObject *iterable)
836/*[clinic end generated code: output=630fb3bca0c8e789 input=9ec5ba3a81be3a4d]*/
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000837{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 PyObject *it; /* iter(v) */
839 Py_ssize_t m; /* size of self */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200840 Py_ssize_t n; /* guess for size of iterable */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000841 Py_ssize_t mn; /* m + n */
842 Py_ssize_t i;
843 PyObject *(*iternext)(PyObject *);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000844
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000845 /* Special cases:
846 1) lists and tuples which can use PySequence_Fast ops
847 2) extending self to self requires making a copy first
848 */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200849 if (PyList_CheckExact(iterable) || PyTuple_CheckExact(iterable) ||
850 (PyObject *)self == iterable) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000851 PyObject **src, **dest;
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200852 iterable = PySequence_Fast(iterable, "argument must be iterable");
853 if (!iterable)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000854 return NULL;
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200855 n = PySequence_Fast_GET_SIZE(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000856 if (n == 0) {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200857 /* short circuit when iterable is empty */
858 Py_DECREF(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 Py_RETURN_NONE;
860 }
861 m = Py_SIZE(self);
Martin Panter94b39ce2017-01-14 06:30:37 +0000862 /* It should not be possible to allocate a list large enough to cause
863 an overflow on any relevant platform */
864 assert(m < PY_SSIZE_T_MAX - n);
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800865 if (list_resize(self, m + n) < 0) {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200866 Py_DECREF(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000867 return NULL;
868 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200869 /* note that we may still have self == iterable here for the
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000870 * situation a.extend(a), but the following code works
871 * in that case too. Just make sure to resize self
872 * before calling PySequence_Fast_ITEMS.
873 */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200874 /* populate the end of self with iterable's items */
875 src = PySequence_Fast_ITEMS(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000876 dest = self->ob_item + m;
877 for (i = 0; i < n; i++) {
878 PyObject *o = src[i];
879 Py_INCREF(o);
880 dest[i] = o;
881 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200882 Py_DECREF(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000883 Py_RETURN_NONE;
884 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000885
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200886 it = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000887 if (it == NULL)
888 return NULL;
Victor Stinner58ac7002020-02-07 03:04:21 +0100889 iternext = *Py_TYPE(it)->tp_iternext;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000891 /* Guess a result list size. */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200892 n = PyObject_LengthHint(iterable, 8);
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800893 if (n < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 Py_DECREF(it);
895 return NULL;
896 }
897 m = Py_SIZE(self);
Martin Panterb93d8632016-07-25 02:39:20 +0000898 if (m > PY_SSIZE_T_MAX - n) {
899 /* m + n overflowed; on the chance that n lied, and there really
900 * is enough room, ignore it. If n was telling the truth, we'll
901 * eventually run out of memory during the loop.
902 */
903 }
904 else {
905 mn = m + n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 /* Make room. */
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800907 if (list_resize(self, mn) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000908 goto error;
909 /* Make the list sane again. */
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100910 Py_SET_SIZE(self, m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000911 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 /* Run iterator to exhaustion. */
914 for (;;) {
915 PyObject *item = iternext(it);
916 if (item == NULL) {
917 if (PyErr_Occurred()) {
918 if (PyErr_ExceptionMatches(PyExc_StopIteration))
919 PyErr_Clear();
920 else
921 goto error;
922 }
923 break;
924 }
925 if (Py_SIZE(self) < self->allocated) {
926 /* steals ref */
927 PyList_SET_ITEM(self, Py_SIZE(self), item);
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100928 Py_SET_SIZE(self, Py_SIZE(self) + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000929 }
930 else {
931 int status = app1(self, item);
932 Py_DECREF(item); /* append creates a new ref */
933 if (status < 0)
934 goto error;
935 }
936 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 /* Cut back result list if initial guess was too large. */
Victor Stinner32fd6ea2013-07-16 21:45:58 +0200939 if (Py_SIZE(self) < self->allocated) {
940 if (list_resize(self, Py_SIZE(self)) < 0)
941 goto error;
942 }
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000943
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000944 Py_DECREF(it);
945 Py_RETURN_NONE;
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000946
947 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000948 Py_DECREF(it);
949 return NULL;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000950}
951
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000952PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200953_PyList_Extend(PyListObject *self, PyObject *iterable)
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000954{
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200955 return list_extend(self, iterable);
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000956}
957
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000958static PyObject *
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000959list_inplace_concat(PyListObject *self, PyObject *other)
960{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000961 PyObject *result;
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000962
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200963 result = list_extend(self, other);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000964 if (result == NULL)
965 return result;
966 Py_DECREF(result);
967 Py_INCREF(self);
968 return (PyObject *)self;
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000969}
970
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200971/*[clinic input]
972list.pop
973
974 index: Py_ssize_t = -1
975 /
976
977Remove and return item at index (default last).
978
979Raises IndexError if list is empty or index is out of range.
980[clinic start generated code]*/
981
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000982static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200983list_pop_impl(PyListObject *self, Py_ssize_t index)
984/*[clinic end generated code: output=6bd69dcb3f17eca8 input=b83675976f329e6f]*/
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000985{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 PyObject *v;
987 int status;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000988
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000989 if (Py_SIZE(self) == 0) {
990 /* Special-case most common failure cause */
991 PyErr_SetString(PyExc_IndexError, "pop from empty list");
992 return NULL;
993 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200994 if (index < 0)
995 index += Py_SIZE(self);
Raymond Hettingerf1aa8ae2018-10-10 20:37:28 -0700996 if (!valid_index(index, Py_SIZE(self))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 PyErr_SetString(PyExc_IndexError, "pop index out of range");
998 return NULL;
999 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02001000 v = self->ob_item[index];
1001 if (index == Py_SIZE(self) - 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 status = list_resize(self, Py_SIZE(self) - 1);
Victor Stinnerb27cd3e2013-07-08 22:20:44 +02001003 if (status >= 0)
1004 return v; /* and v now owns the reference the list had */
1005 else
1006 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007 }
1008 Py_INCREF(v);
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02001009 status = list_ass_slice(self, index, index+1, (PyObject *)NULL);
Victor Stinner095d99f2013-07-17 21:58:01 +02001010 if (status < 0) {
1011 Py_DECREF(v);
1012 return NULL;
1013 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 return v;
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +00001015}
1016
Tim Peters8e2e7ca2002-07-19 02:33:08 +00001017/* Reverse a slice of a list in place, from lo up to (exclusive) hi. */
1018static void
1019reverse_slice(PyObject **lo, PyObject **hi)
1020{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001021 assert(lo && hi);
Tim Peters8e2e7ca2002-07-19 02:33:08 +00001022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001023 --hi;
1024 while (lo < hi) {
1025 PyObject *t = *lo;
1026 *lo = *hi;
1027 *hi = t;
1028 ++lo;
1029 --hi;
1030 }
Tim Peters8e2e7ca2002-07-19 02:33:08 +00001031}
1032
Tim Petersa64dc242002-08-01 02:13:36 +00001033/* Lots of code for an adaptive, stable, natural mergesort. There are many
1034 * pieces to this algorithm; read listsort.txt for overviews and details.
1035 */
Guido van Rossum3f236de1996-12-10 23:55:39 +00001036
Daniel Stutzbach98338222010-12-02 21:55:33 +00001037/* A sortslice contains a pointer to an array of keys and a pointer to
1038 * an array of corresponding values. In other words, keys[i]
1039 * corresponds with values[i]. If values == NULL, then the keys are
1040 * also the values.
1041 *
1042 * Several convenience routines are provided here, so that keys and
1043 * values are always moved in sync.
1044 */
1045
1046typedef struct {
1047 PyObject **keys;
1048 PyObject **values;
1049} sortslice;
1050
1051Py_LOCAL_INLINE(void)
1052sortslice_copy(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j)
1053{
1054 s1->keys[i] = s2->keys[j];
1055 if (s1->values != NULL)
1056 s1->values[i] = s2->values[j];
1057}
1058
1059Py_LOCAL_INLINE(void)
Benjamin Peterson9efdcca2010-12-03 01:44:10 +00001060sortslice_copy_incr(sortslice *dst, sortslice *src)
1061{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001062 *dst->keys++ = *src->keys++;
1063 if (dst->values != NULL)
1064 *dst->values++ = *src->values++;
1065}
1066
1067Py_LOCAL_INLINE(void)
Benjamin Peterson9efdcca2010-12-03 01:44:10 +00001068sortslice_copy_decr(sortslice *dst, sortslice *src)
1069{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001070 *dst->keys-- = *src->keys--;
1071 if (dst->values != NULL)
1072 *dst->values-- = *src->values--;
1073}
1074
1075
1076Py_LOCAL_INLINE(void)
1077sortslice_memcpy(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j,
Benjamin Peterson9efdcca2010-12-03 01:44:10 +00001078 Py_ssize_t n)
1079{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001080 memcpy(&s1->keys[i], &s2->keys[j], sizeof(PyObject *) * n);
1081 if (s1->values != NULL)
1082 memcpy(&s1->values[i], &s2->values[j], sizeof(PyObject *) * n);
1083}
1084
1085Py_LOCAL_INLINE(void)
1086sortslice_memmove(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j,
Benjamin Peterson9efdcca2010-12-03 01:44:10 +00001087 Py_ssize_t n)
1088{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001089 memmove(&s1->keys[i], &s2->keys[j], sizeof(PyObject *) * n);
1090 if (s1->values != NULL)
1091 memmove(&s1->values[i], &s2->values[j], sizeof(PyObject *) * n);
1092}
1093
1094Py_LOCAL_INLINE(void)
Benjamin Peterson9efdcca2010-12-03 01:44:10 +00001095sortslice_advance(sortslice *slice, Py_ssize_t n)
1096{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001097 slice->keys += n;
1098 if (slice->values != NULL)
1099 slice->values += n;
1100}
1101
embg1e34da42018-01-28 20:03:23 -07001102/* Comparison function: ms->key_compare, which is set at run-time in
1103 * listsort_impl to optimize for various special cases.
Tim Petersa64dc242002-08-01 02:13:36 +00001104 * Returns -1 on error, 1 if x < y, 0 if x >= y.
1105 */
Guido van Rossum3f236de1996-12-10 23:55:39 +00001106
embg1e34da42018-01-28 20:03:23 -07001107#define ISLT(X, Y) (*(ms->key_compare))(X, Y, ms)
Tim Peters66860f62002-08-04 17:47:26 +00001108
1109/* Compare X to Y via "<". Goto "fail" if the comparison raises an
Tim Petersa8c974c2002-07-19 03:30:57 +00001110 error. Else "k" is set to true iff X<Y, and an "if (k)" block is
1111 started. It makes more sense in context <wink>. X and Y are PyObject*s.
1112*/
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001113#define IFLT(X, Y) if ((k = ISLT(X, Y)) < 0) goto fail; \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001114 if (k)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001115
embg1e34da42018-01-28 20:03:23 -07001116/* The maximum number of entries in a MergeState's pending-runs stack.
1117 * This is enough to sort arrays of size up to about
1118 * 32 * phi ** MAX_MERGE_PENDING
1119 * where phi ~= 1.618. 85 is ridiculouslylarge enough, good for an array
1120 * with 2**64 elements.
1121 */
1122#define MAX_MERGE_PENDING 85
1123
1124/* When we get into galloping mode, we stay there until both runs win less
1125 * often than MIN_GALLOP consecutive times. See listsort.txt for more info.
1126 */
1127#define MIN_GALLOP 7
1128
1129/* Avoid malloc for small temp arrays. */
1130#define MERGESTATE_TEMP_SIZE 256
1131
1132/* One MergeState exists on the stack per invocation of mergesort. It's just
1133 * a convenient way to pass state around among the helper functions.
1134 */
1135struct s_slice {
1136 sortslice base;
1137 Py_ssize_t len;
1138};
1139
1140typedef struct s_MergeState MergeState;
1141struct s_MergeState {
1142 /* This controls when we get *into* galloping mode. It's initialized
1143 * to MIN_GALLOP. merge_lo and merge_hi tend to nudge it higher for
1144 * random data, and lower for highly structured data.
1145 */
1146 Py_ssize_t min_gallop;
1147
1148 /* 'a' is temp storage to help with merges. It contains room for
1149 * alloced entries.
1150 */
1151 sortslice a; /* may point to temparray below */
1152 Py_ssize_t alloced;
1153
1154 /* A stack of n pending runs yet to be merged. Run #i starts at
1155 * address base[i] and extends for len[i] elements. It's always
1156 * true (so long as the indices are in bounds) that
1157 *
1158 * pending[i].base + pending[i].len == pending[i+1].base
1159 *
1160 * so we could cut the storage for this, but it's a minor amount,
1161 * and keeping all the info explicit simplifies the code.
1162 */
1163 int n;
1164 struct s_slice pending[MAX_MERGE_PENDING];
1165
1166 /* 'a' points to this when possible, rather than muck with malloc. */
1167 PyObject *temparray[MERGESTATE_TEMP_SIZE];
1168
1169 /* This is the function we will use to compare two keys,
1170 * even when none of our special cases apply and we have to use
1171 * safe_object_compare. */
1172 int (*key_compare)(PyObject *, PyObject *, MergeState *);
1173
1174 /* This function is used by unsafe_object_compare to optimize comparisons
1175 * when we know our list is type-homogeneous but we can't assume anything else.
Victor Stinner58ac7002020-02-07 03:04:21 +01001176 * In the pre-sort check it is set equal to Py_TYPE(key)->tp_richcompare */
embg1e34da42018-01-28 20:03:23 -07001177 PyObject *(*key_richcompare)(PyObject *, PyObject *, int);
1178
1179 /* This function is used by unsafe_tuple_compare to compare the first elements
1180 * of tuples. It may be set to safe_object_compare, but the idea is that hopefully
1181 * we can assume more, and use one of the special-case compares. */
1182 int (*tuple_elem_compare)(PyObject *, PyObject *, MergeState *);
1183};
1184
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001185/* binarysort is the best method for sorting small arrays: it does
1186 few compares, but can do data movement quadratic in the number of
1187 elements.
Guido van Rossum42812581998-06-17 14:15:44 +00001188 [lo, hi) is a contiguous slice of a list, and is sorted via
Tim Petersa8c974c2002-07-19 03:30:57 +00001189 binary insertion. This sort is stable.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001190 On entry, must have lo <= start <= hi, and that [lo, start) is already
1191 sorted (pass start == lo if you don't know!).
Tim Petersa8c974c2002-07-19 03:30:57 +00001192 If islt() complains return -1, else 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001193 Even in case of error, the output slice will be some permutation of
1194 the input (nothing is lost or duplicated).
1195*/
Guido van Rossum3f236de1996-12-10 23:55:39 +00001196static int
embg1e34da42018-01-28 20:03:23 -07001197binarysort(MergeState *ms, sortslice lo, PyObject **hi, PyObject **start)
Guido van Rossum3f236de1996-12-10 23:55:39 +00001198{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001199 Py_ssize_t k;
1200 PyObject **l, **p, **r;
1201 PyObject *pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001202
Daniel Stutzbach98338222010-12-02 21:55:33 +00001203 assert(lo.keys <= start && start <= hi);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 /* assert [lo, start) is sorted */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001205 if (lo.keys == start)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001206 ++start;
1207 for (; start < hi; ++start) {
1208 /* set l to where *start belongs */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001209 l = lo.keys;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001210 r = start;
1211 pivot = *r;
1212 /* Invariants:
1213 * pivot >= all in [lo, l).
1214 * pivot < all in [r, start).
1215 * The second is vacuously true at the start.
1216 */
1217 assert(l < r);
1218 do {
1219 p = l + ((r - l) >> 1);
1220 IFLT(pivot, *p)
1221 r = p;
1222 else
1223 l = p+1;
1224 } while (l < r);
1225 assert(l == r);
1226 /* The invariants still hold, so pivot >= all in [lo, l) and
1227 pivot < all in [l, start), so pivot belongs at l. Note
1228 that if there are elements equal to pivot, l points to the
1229 first slot after them -- that's why this sort is stable.
1230 Slide over to make room.
1231 Caution: using memmove is much slower under MSVC 5;
1232 we're not usually moving many slots. */
1233 for (p = start; p > l; --p)
1234 *p = *(p-1);
1235 *l = pivot;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001236 if (lo.values != NULL) {
1237 Py_ssize_t offset = lo.values - lo.keys;
1238 p = start + offset;
1239 pivot = *p;
1240 l += offset;
1241 for (p = start + offset; p > l; --p)
1242 *p = *(p-1);
1243 *l = pivot;
1244 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001245 }
1246 return 0;
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001247
1248 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001249 return -1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001250}
1251
Tim Petersa64dc242002-08-01 02:13:36 +00001252/*
1253Return the length of the run beginning at lo, in the slice [lo, hi). lo < hi
1254is required on entry. "A run" is the longest ascending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001255
Tim Petersa64dc242002-08-01 02:13:36 +00001256 lo[0] <= lo[1] <= lo[2] <= ...
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001257
Tim Petersa64dc242002-08-01 02:13:36 +00001258or the longest descending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001259
Tim Petersa64dc242002-08-01 02:13:36 +00001260 lo[0] > lo[1] > lo[2] > ...
Tim Peters3b01a122002-07-19 02:35:45 +00001261
Tim Petersa64dc242002-08-01 02:13:36 +00001262Boolean *descending is set to 0 in the former case, or to 1 in the latter.
1263For its intended use in a stable mergesort, the strictness of the defn of
1264"descending" is needed so that the caller can safely reverse a descending
1265sequence without violating stability (strict > ensures there are no equal
1266elements to get out of order).
1267
1268Returns -1 in case of error.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001269*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001270static Py_ssize_t
embg1e34da42018-01-28 20:03:23 -07001271count_run(MergeState *ms, PyObject **lo, PyObject **hi, int *descending)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001272{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001273 Py_ssize_t k;
1274 Py_ssize_t n;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001276 assert(lo < hi);
1277 *descending = 0;
1278 ++lo;
1279 if (lo == hi)
1280 return 1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001282 n = 2;
1283 IFLT(*lo, *(lo-1)) {
1284 *descending = 1;
1285 for (lo = lo+1; lo < hi; ++lo, ++n) {
1286 IFLT(*lo, *(lo-1))
1287 ;
1288 else
1289 break;
1290 }
1291 }
1292 else {
1293 for (lo = lo+1; lo < hi; ++lo, ++n) {
1294 IFLT(*lo, *(lo-1))
1295 break;
1296 }
1297 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001299 return n;
Tim Petersa64dc242002-08-01 02:13:36 +00001300fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001301 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001302}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001303
Tim Petersa64dc242002-08-01 02:13:36 +00001304/*
1305Locate the proper position of key in a sorted vector; if the vector contains
1306an element equal to key, return the position immediately to the left of
1307the leftmost equal element. [gallop_right() does the same except returns
1308the position to the right of the rightmost equal element (if any).]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001309
Tim Petersa64dc242002-08-01 02:13:36 +00001310"a" is a sorted vector with n elements, starting at a[0]. n must be > 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001311
Tim Petersa64dc242002-08-01 02:13:36 +00001312"hint" is an index at which to begin the search, 0 <= hint < n. The closer
1313hint is to the final result, the faster this runs.
1314
1315The return value is the int k in 0..n such that
1316
1317 a[k-1] < key <= a[k]
1318
1319pretending that *(a-1) is minus infinity and a[n] is plus infinity. IOW,
1320key belongs at index k; or, IOW, the first k elements of a should precede
1321key, and the last n-k should follow key.
1322
1323Returns -1 on error. See listsort.txt for info on the method.
1324*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001325static Py_ssize_t
embg1e34da42018-01-28 20:03:23 -07001326gallop_left(MergeState *ms, PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint)
Tim Petersa64dc242002-08-01 02:13:36 +00001327{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001328 Py_ssize_t ofs;
1329 Py_ssize_t lastofs;
1330 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001332 assert(key && a && n > 0 && hint >= 0 && hint < n);
Tim Petersa64dc242002-08-01 02:13:36 +00001333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001334 a += hint;
1335 lastofs = 0;
1336 ofs = 1;
1337 IFLT(*a, key) {
1338 /* a[hint] < key -- gallop right, until
1339 * a[hint + lastofs] < key <= a[hint + ofs]
1340 */
1341 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
1342 while (ofs < maxofs) {
1343 IFLT(a[ofs], key) {
1344 lastofs = ofs;
Alexey Izbyshev6bc59172019-05-23 03:01:08 +03001345 assert(ofs <= (PY_SSIZE_T_MAX - 1) / 2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001346 ofs = (ofs << 1) + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001347 }
1348 else /* key <= a[hint + ofs] */
1349 break;
1350 }
1351 if (ofs > maxofs)
1352 ofs = maxofs;
1353 /* Translate back to offsets relative to &a[0]. */
1354 lastofs += hint;
1355 ofs += hint;
1356 }
1357 else {
1358 /* key <= a[hint] -- gallop left, until
1359 * a[hint - ofs] < key <= a[hint - lastofs]
1360 */
1361 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
1362 while (ofs < maxofs) {
1363 IFLT(*(a-ofs), key)
1364 break;
1365 /* key <= a[hint - ofs] */
1366 lastofs = ofs;
Alexey Izbyshev6bc59172019-05-23 03:01:08 +03001367 assert(ofs <= (PY_SSIZE_T_MAX - 1) / 2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001368 ofs = (ofs << 1) + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001369 }
1370 if (ofs > maxofs)
1371 ofs = maxofs;
1372 /* Translate back to positive offsets relative to &a[0]. */
1373 k = lastofs;
1374 lastofs = hint - ofs;
1375 ofs = hint - k;
1376 }
1377 a -= hint;
Tim Petersa64dc242002-08-01 02:13:36 +00001378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001379 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1380 /* Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the
1381 * right of lastofs but no farther right than ofs. Do a binary
1382 * search, with invariant a[lastofs-1] < key <= a[ofs].
1383 */
1384 ++lastofs;
1385 while (lastofs < ofs) {
1386 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001388 IFLT(a[m], key)
1389 lastofs = m+1; /* a[m] < key */
1390 else
1391 ofs = m; /* key <= a[m] */
1392 }
1393 assert(lastofs == ofs); /* so a[ofs-1] < key <= a[ofs] */
1394 return ofs;
Tim Petersa64dc242002-08-01 02:13:36 +00001395
1396fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001397 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001398}
1399
1400/*
1401Exactly like gallop_left(), except that if key already exists in a[0:n],
1402finds the position immediately to the right of the rightmost equal value.
1403
1404The return value is the int k in 0..n such that
1405
1406 a[k-1] <= key < a[k]
1407
1408or -1 if error.
1409
1410The code duplication is massive, but this is enough different given that
1411we're sticking to "<" comparisons that it's much harder to follow if
1412written as one routine with yet another "left or right?" flag.
1413*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001414static Py_ssize_t
embg1e34da42018-01-28 20:03:23 -07001415gallop_right(MergeState *ms, PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint)
Tim Petersa64dc242002-08-01 02:13:36 +00001416{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001417 Py_ssize_t ofs;
1418 Py_ssize_t lastofs;
1419 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001420
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001421 assert(key && a && n > 0 && hint >= 0 && hint < n);
Tim Petersa64dc242002-08-01 02:13:36 +00001422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001423 a += hint;
1424 lastofs = 0;
1425 ofs = 1;
1426 IFLT(key, *a) {
1427 /* key < a[hint] -- gallop left, until
1428 * a[hint - ofs] <= key < a[hint - lastofs]
1429 */
1430 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
1431 while (ofs < maxofs) {
1432 IFLT(key, *(a-ofs)) {
1433 lastofs = ofs;
Alexey Izbyshev6bc59172019-05-23 03:01:08 +03001434 assert(ofs <= (PY_SSIZE_T_MAX - 1) / 2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001435 ofs = (ofs << 1) + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001436 }
1437 else /* a[hint - ofs] <= key */
1438 break;
1439 }
1440 if (ofs > maxofs)
1441 ofs = maxofs;
1442 /* Translate back to positive offsets relative to &a[0]. */
1443 k = lastofs;
1444 lastofs = hint - ofs;
1445 ofs = hint - k;
1446 }
1447 else {
1448 /* a[hint] <= key -- gallop right, until
1449 * a[hint + lastofs] <= key < a[hint + ofs]
1450 */
1451 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
1452 while (ofs < maxofs) {
1453 IFLT(key, a[ofs])
1454 break;
1455 /* a[hint + ofs] <= key */
1456 lastofs = ofs;
Alexey Izbyshev6bc59172019-05-23 03:01:08 +03001457 assert(ofs <= (PY_SSIZE_T_MAX - 1) / 2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001458 ofs = (ofs << 1) + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001459 }
1460 if (ofs > maxofs)
1461 ofs = maxofs;
1462 /* Translate back to offsets relative to &a[0]. */
1463 lastofs += hint;
1464 ofs += hint;
1465 }
1466 a -= hint;
Tim Petersa64dc242002-08-01 02:13:36 +00001467
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001468 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1469 /* Now a[lastofs] <= key < a[ofs], so key belongs somewhere to the
1470 * right of lastofs but no farther right than ofs. Do a binary
1471 * search, with invariant a[lastofs-1] <= key < a[ofs].
1472 */
1473 ++lastofs;
1474 while (lastofs < ofs) {
1475 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001476
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001477 IFLT(key, a[m])
1478 ofs = m; /* key < a[m] */
1479 else
1480 lastofs = m+1; /* a[m] <= key */
1481 }
1482 assert(lastofs == ofs); /* so a[ofs-1] <= key < a[ofs] */
1483 return ofs;
Tim Petersa64dc242002-08-01 02:13:36 +00001484
1485fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001486 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001487}
1488
Tim Petersa64dc242002-08-01 02:13:36 +00001489/* Conceptually a MergeState's constructor. */
1490static void
Victor Stinner0fcab4a2011-01-04 12:59:15 +00001491merge_init(MergeState *ms, Py_ssize_t list_size, int has_keyfunc)
Tim Petersa64dc242002-08-01 02:13:36 +00001492{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001493 assert(ms != NULL);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001494 if (has_keyfunc) {
1495 /* The temporary space for merging will need at most half the list
1496 * size rounded up. Use the minimum possible space so we can use the
1497 * rest of temparray for other things. In particular, if there is
1498 * enough extra space, listsort() will use it to store the keys.
1499 */
1500 ms->alloced = (list_size + 1) / 2;
1501
1502 /* ms->alloced describes how many keys will be stored at
1503 ms->temparray, but we also need to store the values. Hence,
1504 ms->alloced is capped at half of MERGESTATE_TEMP_SIZE. */
1505 if (MERGESTATE_TEMP_SIZE / 2 < ms->alloced)
1506 ms->alloced = MERGESTATE_TEMP_SIZE / 2;
1507 ms->a.values = &ms->temparray[ms->alloced];
1508 }
1509 else {
1510 ms->alloced = MERGESTATE_TEMP_SIZE;
1511 ms->a.values = NULL;
1512 }
1513 ms->a.keys = ms->temparray;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001514 ms->n = 0;
1515 ms->min_gallop = MIN_GALLOP;
Tim Petersa64dc242002-08-01 02:13:36 +00001516}
1517
1518/* Free all the temp memory owned by the MergeState. This must be called
1519 * when you're done with a MergeState, and may be called before then if
1520 * you want to free the temp memory early.
1521 */
1522static void
1523merge_freemem(MergeState *ms)
1524{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001525 assert(ms != NULL);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001526 if (ms->a.keys != ms->temparray)
1527 PyMem_Free(ms->a.keys);
Tim Petersa64dc242002-08-01 02:13:36 +00001528}
1529
1530/* Ensure enough temp memory for 'need' array slots is available.
1531 * Returns 0 on success and -1 if the memory can't be gotten.
1532 */
1533static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001534merge_getmem(MergeState *ms, Py_ssize_t need)
Tim Petersa64dc242002-08-01 02:13:36 +00001535{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001536 int multiplier;
1537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001538 assert(ms != NULL);
1539 if (need <= ms->alloced)
1540 return 0;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001541
1542 multiplier = ms->a.values != NULL ? 2 : 1;
1543
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001544 /* Don't realloc! That can cost cycles to copy the old data, but
1545 * we don't care what's in the block.
1546 */
1547 merge_freemem(ms);
embg1e34da42018-01-28 20:03:23 -07001548 if ((size_t)need > PY_SSIZE_T_MAX / sizeof(PyObject *) / multiplier) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001549 PyErr_NoMemory();
1550 return -1;
1551 }
embg1e34da42018-01-28 20:03:23 -07001552 ms->a.keys = (PyObject **)PyMem_Malloc(multiplier * need
Daniel Stutzbach98338222010-12-02 21:55:33 +00001553 * sizeof(PyObject *));
1554 if (ms->a.keys != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001555 ms->alloced = need;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001556 if (ms->a.values != NULL)
1557 ms->a.values = &ms->a.keys[need];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001558 return 0;
1559 }
1560 PyErr_NoMemory();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001561 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001562}
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001563#define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 : \
1564 merge_getmem(MS, NEED))
Tim Petersa64dc242002-08-01 02:13:36 +00001565
Daniel Stutzbach98338222010-12-02 21:55:33 +00001566/* Merge the na elements starting at ssa with the nb elements starting at
1567 * ssb.keys = ssa.keys + na in a stable way, in-place. na and nb must be > 0.
1568 * Must also have that ssa.keys[na-1] belongs at the end of the merge, and
1569 * should have na <= nb. See listsort.txt for more info. Return 0 if
1570 * successful, -1 if error.
Tim Petersa64dc242002-08-01 02:13:36 +00001571 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001572static Py_ssize_t
Daniel Stutzbach98338222010-12-02 21:55:33 +00001573merge_lo(MergeState *ms, sortslice ssa, Py_ssize_t na,
1574 sortslice ssb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001575{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001576 Py_ssize_t k;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001577 sortslice dest;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001578 int result = -1; /* guilty until proved innocent */
1579 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001580
Daniel Stutzbach98338222010-12-02 21:55:33 +00001581 assert(ms && ssa.keys && ssb.keys && na > 0 && nb > 0);
1582 assert(ssa.keys + na == ssb.keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001583 if (MERGE_GETMEM(ms, na) < 0)
1584 return -1;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001585 sortslice_memcpy(&ms->a, 0, &ssa, 0, na);
1586 dest = ssa;
1587 ssa = ms->a;
Tim Petersa64dc242002-08-01 02:13:36 +00001588
Daniel Stutzbach98338222010-12-02 21:55:33 +00001589 sortslice_copy_incr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001590 --nb;
1591 if (nb == 0)
1592 goto Succeed;
1593 if (na == 1)
1594 goto CopyB;
Tim Petersa64dc242002-08-01 02:13:36 +00001595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001596 min_gallop = ms->min_gallop;
1597 for (;;) {
1598 Py_ssize_t acount = 0; /* # of times A won in a row */
1599 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001601 /* Do the straightforward thing until (if ever) one run
1602 * appears to win consistently.
1603 */
1604 for (;;) {
1605 assert(na > 1 && nb > 0);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001606 k = ISLT(ssb.keys[0], ssa.keys[0]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001607 if (k) {
1608 if (k < 0)
1609 goto Fail;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001610 sortslice_copy_incr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001611 ++bcount;
1612 acount = 0;
1613 --nb;
1614 if (nb == 0)
1615 goto Succeed;
1616 if (bcount >= min_gallop)
1617 break;
1618 }
1619 else {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001620 sortslice_copy_incr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001621 ++acount;
1622 bcount = 0;
1623 --na;
1624 if (na == 1)
1625 goto CopyB;
1626 if (acount >= min_gallop)
1627 break;
1628 }
1629 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001631 /* One run is winning so consistently that galloping may
1632 * be a huge win. So try that, and continue galloping until
1633 * (if ever) neither run appears to be winning consistently
1634 * anymore.
1635 */
1636 ++min_gallop;
1637 do {
1638 assert(na > 1 && nb > 0);
1639 min_gallop -= min_gallop > 1;
1640 ms->min_gallop = min_gallop;
embg1e34da42018-01-28 20:03:23 -07001641 k = gallop_right(ms, ssb.keys[0], ssa.keys, na, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001642 acount = k;
1643 if (k) {
1644 if (k < 0)
1645 goto Fail;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001646 sortslice_memcpy(&dest, 0, &ssa, 0, k);
1647 sortslice_advance(&dest, k);
1648 sortslice_advance(&ssa, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001649 na -= k;
1650 if (na == 1)
1651 goto CopyB;
1652 /* na==0 is impossible now if the comparison
1653 * function is consistent, but we can't assume
1654 * that it is.
1655 */
1656 if (na == 0)
1657 goto Succeed;
1658 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001659 sortslice_copy_incr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001660 --nb;
1661 if (nb == 0)
1662 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001663
embg1e34da42018-01-28 20:03:23 -07001664 k = gallop_left(ms, ssa.keys[0], ssb.keys, nb, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001665 bcount = k;
1666 if (k) {
1667 if (k < 0)
1668 goto Fail;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001669 sortslice_memmove(&dest, 0, &ssb, 0, k);
1670 sortslice_advance(&dest, k);
1671 sortslice_advance(&ssb, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001672 nb -= k;
1673 if (nb == 0)
1674 goto Succeed;
1675 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001676 sortslice_copy_incr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001677 --na;
1678 if (na == 1)
1679 goto CopyB;
1680 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
1681 ++min_gallop; /* penalize it for leaving galloping mode */
1682 ms->min_gallop = min_gallop;
1683 }
Tim Petersa64dc242002-08-01 02:13:36 +00001684Succeed:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001685 result = 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001686Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001687 if (na)
Daniel Stutzbach98338222010-12-02 21:55:33 +00001688 sortslice_memcpy(&dest, 0, &ssa, 0, na);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001689 return result;
Tim Petersa64dc242002-08-01 02:13:36 +00001690CopyB:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001691 assert(na == 1 && nb > 0);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001692 /* The last element of ssa belongs at the end of the merge. */
1693 sortslice_memmove(&dest, 0, &ssb, 0, nb);
1694 sortslice_copy(&dest, nb, &ssa, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001695 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001696}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001697
Daniel Stutzbach98338222010-12-02 21:55:33 +00001698/* Merge the na elements starting at pa with the nb elements starting at
1699 * ssb.keys = ssa.keys + na in a stable way, in-place. na and nb must be > 0.
1700 * Must also have that ssa.keys[na-1] belongs at the end of the merge, and
1701 * should have na >= nb. See listsort.txt for more info. Return 0 if
1702 * successful, -1 if error.
Tim Petersa64dc242002-08-01 02:13:36 +00001703 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001704static Py_ssize_t
Daniel Stutzbach98338222010-12-02 21:55:33 +00001705merge_hi(MergeState *ms, sortslice ssa, Py_ssize_t na,
1706 sortslice ssb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001707{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001708 Py_ssize_t k;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001709 sortslice dest, basea, baseb;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001710 int result = -1; /* guilty until proved innocent */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001711 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001712
Daniel Stutzbach98338222010-12-02 21:55:33 +00001713 assert(ms && ssa.keys && ssb.keys && na > 0 && nb > 0);
1714 assert(ssa.keys + na == ssb.keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001715 if (MERGE_GETMEM(ms, nb) < 0)
1716 return -1;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001717 dest = ssb;
1718 sortslice_advance(&dest, nb-1);
1719 sortslice_memcpy(&ms->a, 0, &ssb, 0, nb);
1720 basea = ssa;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001721 baseb = ms->a;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001722 ssb.keys = ms->a.keys + nb - 1;
1723 if (ssb.values != NULL)
1724 ssb.values = ms->a.values + nb - 1;
1725 sortslice_advance(&ssa, na - 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001726
Daniel Stutzbach98338222010-12-02 21:55:33 +00001727 sortslice_copy_decr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001728 --na;
1729 if (na == 0)
1730 goto Succeed;
1731 if (nb == 1)
1732 goto CopyA;
Tim Petersa64dc242002-08-01 02:13:36 +00001733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001734 min_gallop = ms->min_gallop;
1735 for (;;) {
1736 Py_ssize_t acount = 0; /* # of times A won in a row */
1737 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001739 /* Do the straightforward thing until (if ever) one run
1740 * appears to win consistently.
1741 */
1742 for (;;) {
1743 assert(na > 0 && nb > 1);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001744 k = ISLT(ssb.keys[0], ssa.keys[0]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001745 if (k) {
1746 if (k < 0)
1747 goto Fail;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001748 sortslice_copy_decr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001749 ++acount;
1750 bcount = 0;
1751 --na;
1752 if (na == 0)
1753 goto Succeed;
1754 if (acount >= min_gallop)
1755 break;
1756 }
1757 else {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001758 sortslice_copy_decr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001759 ++bcount;
1760 acount = 0;
1761 --nb;
1762 if (nb == 1)
1763 goto CopyA;
1764 if (bcount >= min_gallop)
1765 break;
1766 }
1767 }
Tim Petersa64dc242002-08-01 02:13:36 +00001768
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001769 /* One run is winning so consistently that galloping may
1770 * be a huge win. So try that, and continue galloping until
1771 * (if ever) neither run appears to be winning consistently
1772 * anymore.
1773 */
1774 ++min_gallop;
1775 do {
1776 assert(na > 0 && nb > 1);
1777 min_gallop -= min_gallop > 1;
1778 ms->min_gallop = min_gallop;
embg1e34da42018-01-28 20:03:23 -07001779 k = gallop_right(ms, ssb.keys[0], basea.keys, na, na-1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001780 if (k < 0)
1781 goto Fail;
1782 k = na - k;
1783 acount = k;
1784 if (k) {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001785 sortslice_advance(&dest, -k);
1786 sortslice_advance(&ssa, -k);
1787 sortslice_memmove(&dest, 1, &ssa, 1, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001788 na -= k;
1789 if (na == 0)
1790 goto Succeed;
1791 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001792 sortslice_copy_decr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001793 --nb;
1794 if (nb == 1)
1795 goto CopyA;
Tim Petersa64dc242002-08-01 02:13:36 +00001796
embg1e34da42018-01-28 20:03:23 -07001797 k = gallop_left(ms, ssa.keys[0], baseb.keys, nb, nb-1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001798 if (k < 0)
1799 goto Fail;
1800 k = nb - k;
1801 bcount = k;
1802 if (k) {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001803 sortslice_advance(&dest, -k);
1804 sortslice_advance(&ssb, -k);
1805 sortslice_memcpy(&dest, 1, &ssb, 1, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001806 nb -= k;
1807 if (nb == 1)
1808 goto CopyA;
1809 /* nb==0 is impossible now if the comparison
1810 * function is consistent, but we can't assume
1811 * that it is.
1812 */
1813 if (nb == 0)
1814 goto Succeed;
1815 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001816 sortslice_copy_decr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001817 --na;
1818 if (na == 0)
1819 goto Succeed;
1820 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
1821 ++min_gallop; /* penalize it for leaving galloping mode */
1822 ms->min_gallop = min_gallop;
1823 }
Tim Petersa64dc242002-08-01 02:13:36 +00001824Succeed:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001825 result = 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001826Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001827 if (nb)
Daniel Stutzbach98338222010-12-02 21:55:33 +00001828 sortslice_memcpy(&dest, -(nb-1), &baseb, 0, nb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001829 return result;
Tim Petersa64dc242002-08-01 02:13:36 +00001830CopyA:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001831 assert(nb == 1 && na > 0);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001832 /* The first element of ssb belongs at the front of the merge. */
1833 sortslice_memmove(&dest, 1-na, &ssa, 1-na, na);
1834 sortslice_advance(&dest, -na);
1835 sortslice_advance(&ssa, -na);
1836 sortslice_copy(&dest, 0, &ssb, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001837 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001838}
1839
1840/* Merge the two runs at stack indices i and i+1.
1841 * Returns 0 on success, -1 on error.
1842 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001843static Py_ssize_t
1844merge_at(MergeState *ms, Py_ssize_t i)
Tim Petersa64dc242002-08-01 02:13:36 +00001845{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001846 sortslice ssa, ssb;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001847 Py_ssize_t na, nb;
1848 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001849
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001850 assert(ms != NULL);
1851 assert(ms->n >= 2);
1852 assert(i >= 0);
1853 assert(i == ms->n - 2 || i == ms->n - 3);
Tim Petersa64dc242002-08-01 02:13:36 +00001854
Daniel Stutzbach98338222010-12-02 21:55:33 +00001855 ssa = ms->pending[i].base;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001856 na = ms->pending[i].len;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001857 ssb = ms->pending[i+1].base;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001858 nb = ms->pending[i+1].len;
1859 assert(na > 0 && nb > 0);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001860 assert(ssa.keys + na == ssb.keys);
Tim Petersa64dc242002-08-01 02:13:36 +00001861
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001862 /* Record the length of the combined runs; if i is the 3rd-last
1863 * run now, also slide over the last run (which isn't involved
1864 * in this merge). The current run i+1 goes away in any case.
1865 */
1866 ms->pending[i].len = na + nb;
1867 if (i == ms->n - 3)
1868 ms->pending[i+1] = ms->pending[i+2];
1869 --ms->n;
Tim Petersa64dc242002-08-01 02:13:36 +00001870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001871 /* Where does b start in a? Elements in a before that can be
1872 * ignored (already in place).
1873 */
embg1e34da42018-01-28 20:03:23 -07001874 k = gallop_right(ms, *ssb.keys, ssa.keys, na, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001875 if (k < 0)
1876 return -1;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001877 sortslice_advance(&ssa, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001878 na -= k;
1879 if (na == 0)
1880 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001882 /* Where does a end in b? Elements in b after that can be
1883 * ignored (already in place).
1884 */
embg1e34da42018-01-28 20:03:23 -07001885 nb = gallop_left(ms, ssa.keys[na-1], ssb.keys, nb, nb-1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001886 if (nb <= 0)
1887 return nb;
Tim Petersa64dc242002-08-01 02:13:36 +00001888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001889 /* Merge what remains of the runs, using a temp array with
1890 * min(na, nb) elements.
1891 */
1892 if (na <= nb)
Daniel Stutzbach98338222010-12-02 21:55:33 +00001893 return merge_lo(ms, ssa, na, ssb, nb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001894 else
Daniel Stutzbach98338222010-12-02 21:55:33 +00001895 return merge_hi(ms, ssa, na, ssb, nb);
Tim Petersa64dc242002-08-01 02:13:36 +00001896}
1897
1898/* Examine the stack of runs waiting to be merged, merging adjacent runs
1899 * until the stack invariants are re-established:
1900 *
1901 * 1. len[-3] > len[-2] + len[-1]
1902 * 2. len[-2] > len[-1]
1903 *
1904 * See listsort.txt for more info.
1905 *
1906 * Returns 0 on success, -1 on error.
1907 */
1908static int
1909merge_collapse(MergeState *ms)
1910{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001911 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001913 assert(ms);
1914 while (ms->n > 1) {
1915 Py_ssize_t n = ms->n - 2;
Benjamin Petersonb808d592015-02-25 10:12:26 -05001916 if ((n > 0 && p[n-1].len <= p[n].len + p[n+1].len) ||
1917 (n > 1 && p[n-2].len <= p[n-1].len + p[n].len)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001918 if (p[n-1].len < p[n+1].len)
1919 --n;
1920 if (merge_at(ms, n) < 0)
1921 return -1;
1922 }
1923 else if (p[n].len <= p[n+1].len) {
embg1e34da42018-01-28 20:03:23 -07001924 if (merge_at(ms, n) < 0)
1925 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001926 }
1927 else
1928 break;
1929 }
1930 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001931}
1932
1933/* Regardless of invariants, merge all runs on the stack until only one
1934 * remains. This is used at the end of the mergesort.
1935 *
1936 * Returns 0 on success, -1 on error.
1937 */
1938static int
1939merge_force_collapse(MergeState *ms)
1940{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001941 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001943 assert(ms);
1944 while (ms->n > 1) {
1945 Py_ssize_t n = ms->n - 2;
1946 if (n > 0 && p[n-1].len < p[n+1].len)
1947 --n;
1948 if (merge_at(ms, n) < 0)
1949 return -1;
1950 }
1951 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001952}
1953
1954/* Compute a good value for the minimum run length; natural runs shorter
1955 * than this are boosted artificially via binary insertion.
1956 *
1957 * If n < 64, return n (it's too small to bother with fancy stuff).
1958 * Else if n is an exact power of 2, return 32.
1959 * Else return an int k, 32 <= k <= 64, such that n/k is close to, but
1960 * strictly less than, an exact power of 2.
1961 *
1962 * See listsort.txt for more info.
1963 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001964static Py_ssize_t
1965merge_compute_minrun(Py_ssize_t n)
Tim Petersa64dc242002-08-01 02:13:36 +00001966{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001967 Py_ssize_t r = 0; /* becomes 1 if any 1 bits are shifted off */
Tim Petersa64dc242002-08-01 02:13:36 +00001968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001969 assert(n >= 0);
1970 while (n >= 64) {
1971 r |= n & 1;
1972 n >>= 1;
1973 }
1974 return n + r;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001975}
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001976
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001977static void
Daniel Stutzbach98338222010-12-02 21:55:33 +00001978reverse_sortslice(sortslice *s, Py_ssize_t n)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001979{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001980 reverse_slice(s->keys, &s->keys[n]);
1981 if (s->values != NULL)
1982 reverse_slice(s->values, &s->values[n]);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001983}
1984
embg1e34da42018-01-28 20:03:23 -07001985/* Here we define custom comparison functions to optimize for the cases one commonly
1986 * encounters in practice: homogeneous lists, often of one of the basic types. */
1987
1988/* This struct holds the comparison function and helper functions
1989 * selected in the pre-sort check. */
1990
1991/* These are the special case compare functions.
1992 * ms->key_compare will always point to one of these: */
1993
1994/* Heterogeneous compare: default, always safe to fall back on. */
1995static int
1996safe_object_compare(PyObject *v, PyObject *w, MergeState *ms)
1997{
1998 /* No assumptions necessary! */
1999 return PyObject_RichCompareBool(v, w, Py_LT);
2000}
2001
2002/* Homogeneous compare: safe for any two compareable objects of the same type.
2003 * (ms->key_richcompare is set to ob_type->tp_richcompare in the
2004 * pre-sort check.)
2005 */
2006static int
2007unsafe_object_compare(PyObject *v, PyObject *w, MergeState *ms)
2008{
2009 PyObject *res_obj; int res;
2010
2011 /* No assumptions, because we check first: */
Victor Stinner58ac7002020-02-07 03:04:21 +01002012 if (Py_TYPE(v)->tp_richcompare != ms->key_richcompare)
embg1e34da42018-01-28 20:03:23 -07002013 return PyObject_RichCompareBool(v, w, Py_LT);
2014
2015 assert(ms->key_richcompare != NULL);
2016 res_obj = (*(ms->key_richcompare))(v, w, Py_LT);
2017
2018 if (res_obj == Py_NotImplemented) {
2019 Py_DECREF(res_obj);
2020 return PyObject_RichCompareBool(v, w, Py_LT);
2021 }
2022 if (res_obj == NULL)
2023 return -1;
2024
2025 if (PyBool_Check(res_obj)) {
2026 res = (res_obj == Py_True);
2027 }
2028 else {
2029 res = PyObject_IsTrue(res_obj);
2030 }
2031 Py_DECREF(res_obj);
2032
2033 /* Note that we can't assert
2034 * res == PyObject_RichCompareBool(v, w, Py_LT);
2035 * because of evil compare functions like this:
2036 * lambda a, b: int(random.random() * 3) - 1)
2037 * (which is actually in test_sort.py) */
2038 return res;
2039}
2040
2041/* Latin string compare: safe for any two latin (one byte per char) strings. */
2042static int
2043unsafe_latin_compare(PyObject *v, PyObject *w, MergeState *ms)
2044{
Victor Stinner8017b802018-01-29 13:47:06 +01002045 Py_ssize_t len;
2046 int res;
embg1e34da42018-01-28 20:03:23 -07002047
2048 /* Modified from Objects/unicodeobject.c:unicode_compare, assuming: */
Andy Lesterdffe4c02020-03-04 07:15:20 -06002049 assert(Py_IS_TYPE(v, &PyUnicode_Type));
2050 assert(Py_IS_TYPE(w, &PyUnicode_Type));
embg1e34da42018-01-28 20:03:23 -07002051 assert(PyUnicode_KIND(v) == PyUnicode_KIND(w));
2052 assert(PyUnicode_KIND(v) == PyUnicode_1BYTE_KIND);
2053
2054 len = Py_MIN(PyUnicode_GET_LENGTH(v), PyUnicode_GET_LENGTH(w));
2055 res = memcmp(PyUnicode_DATA(v), PyUnicode_DATA(w), len);
2056
2057 res = (res != 0 ?
2058 res < 0 :
2059 PyUnicode_GET_LENGTH(v) < PyUnicode_GET_LENGTH(w));
2060
2061 assert(res == PyObject_RichCompareBool(v, w, Py_LT));;
2062 return res;
2063}
2064
2065/* Bounded int compare: compare any two longs that fit in a single machine word. */
2066static int
2067unsafe_long_compare(PyObject *v, PyObject *w, MergeState *ms)
2068{
2069 PyLongObject *vl, *wl; sdigit v0, w0; int res;
2070
2071 /* Modified from Objects/longobject.c:long_compare, assuming: */
Andy Lesterdffe4c02020-03-04 07:15:20 -06002072 assert(Py_IS_TYPE(v, &PyLong_Type));
2073 assert(Py_IS_TYPE(w, &PyLong_Type));
embg1e34da42018-01-28 20:03:23 -07002074 assert(Py_ABS(Py_SIZE(v)) <= 1);
2075 assert(Py_ABS(Py_SIZE(w)) <= 1);
2076
2077 vl = (PyLongObject*)v;
2078 wl = (PyLongObject*)w;
2079
2080 v0 = Py_SIZE(vl) == 0 ? 0 : (sdigit)vl->ob_digit[0];
2081 w0 = Py_SIZE(wl) == 0 ? 0 : (sdigit)wl->ob_digit[0];
2082
2083 if (Py_SIZE(vl) < 0)
2084 v0 = -v0;
2085 if (Py_SIZE(wl) < 0)
2086 w0 = -w0;
2087
2088 res = v0 < w0;
2089 assert(res == PyObject_RichCompareBool(v, w, Py_LT));
2090 return res;
2091}
2092
2093/* Float compare: compare any two floats. */
2094static int
2095unsafe_float_compare(PyObject *v, PyObject *w, MergeState *ms)
2096{
2097 int res;
2098
2099 /* Modified from Objects/floatobject.c:float_richcompare, assuming: */
Andy Lesterdffe4c02020-03-04 07:15:20 -06002100 assert(Py_IS_TYPE(v, &PyFloat_Type));
2101 assert(Py_IS_TYPE(w, &PyFloat_Type));
embg1e34da42018-01-28 20:03:23 -07002102
2103 res = PyFloat_AS_DOUBLE(v) < PyFloat_AS_DOUBLE(w);
2104 assert(res == PyObject_RichCompareBool(v, w, Py_LT));
2105 return res;
2106}
2107
2108/* Tuple compare: compare *any* two tuples, using
2109 * ms->tuple_elem_compare to compare the first elements, which is set
2110 * using the same pre-sort check as we use for ms->key_compare,
2111 * but run on the list [x[0] for x in L]. This allows us to optimize compares
2112 * on two levels (as long as [x[0] for x in L] is type-homogeneous.) The idea is
2113 * that most tuple compares don't involve x[1:]. */
2114static int
2115unsafe_tuple_compare(PyObject *v, PyObject *w, MergeState *ms)
2116{
2117 PyTupleObject *vt, *wt;
2118 Py_ssize_t i, vlen, wlen;
2119 int k;
2120
2121 /* Modified from Objects/tupleobject.c:tuplerichcompare, assuming: */
Andy Lesterdffe4c02020-03-04 07:15:20 -06002122 assert(Py_IS_TYPE(v, &PyTuple_Type));
2123 assert(Py_IS_TYPE(w, &PyTuple_Type));
embg1e34da42018-01-28 20:03:23 -07002124 assert(Py_SIZE(v) > 0);
2125 assert(Py_SIZE(w) > 0);
2126
2127 vt = (PyTupleObject *)v;
2128 wt = (PyTupleObject *)w;
2129
2130 vlen = Py_SIZE(vt);
2131 wlen = Py_SIZE(wt);
2132
2133 for (i = 0; i < vlen && i < wlen; i++) {
2134 k = PyObject_RichCompareBool(vt->ob_item[i], wt->ob_item[i], Py_EQ);
2135 if (k < 0)
2136 return -1;
2137 if (!k)
2138 break;
2139 }
2140
2141 if (i >= vlen || i >= wlen)
2142 return vlen < wlen;
2143
2144 if (i == 0)
2145 return ms->tuple_elem_compare(vt->ob_item[i], wt->ob_item[i], ms);
2146 else
2147 return PyObject_RichCompareBool(vt->ob_item[i], wt->ob_item[i], Py_LT);
2148}
2149
Tim Petersa64dc242002-08-01 02:13:36 +00002150/* An adaptive, stable, natural mergesort. See listsort.txt.
2151 * Returns Py_None on success, NULL on error. Even in case of error, the
2152 * list will be some permutation of its input state (nothing is lost or
2153 * duplicated).
2154 */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002155/*[clinic input]
2156list.sort
2157
2158 *
2159 key as keyfunc: object = None
Serhiy Storchaka202fda52017-03-12 10:10:47 +02002160 reverse: bool(accept={int}) = False
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002161
Tim Hoffmann5c224762019-06-01 06:10:02 +02002162Sort the list in ascending order and return None.
2163
2164The sort is in-place (i.e. the list itself is modified) and stable (i.e. the
2165order of two equal elements is maintained).
2166
2167If a key function is given, apply it once to each list item and sort them,
2168ascending or descending, according to their function values.
2169
2170The reverse flag can be set to sort in descending order.
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002171[clinic start generated code]*/
2172
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002173static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002174list_sort_impl(PyListObject *self, PyObject *keyfunc, int reverse)
Tim Hoffmann5c224762019-06-01 06:10:02 +02002175/*[clinic end generated code: output=57b9f9c5e23fbe42 input=cb56cd179a713060]*/
Guido van Rossum3f236de1996-12-10 23:55:39 +00002176{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002177 MergeState ms;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002178 Py_ssize_t nremaining;
2179 Py_ssize_t minrun;
Daniel Stutzbach98338222010-12-02 21:55:33 +00002180 sortslice lo;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002181 Py_ssize_t saved_ob_size, saved_allocated;
2182 PyObject **saved_ob_item;
2183 PyObject **final_ob_item;
2184 PyObject *result = NULL; /* guilty until proved innocent */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002185 Py_ssize_t i;
Daniel Stutzbach98338222010-12-02 21:55:33 +00002186 PyObject **keys;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002188 assert(self != NULL);
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002189 assert(PyList_Check(self));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002190 if (keyfunc == Py_None)
2191 keyfunc = NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002193 /* The list is temporarily made empty, so that mutations performed
2194 * by comparison functions can't affect the slice of memory we're
2195 * sorting (allowing mutations during sorting is a core-dump
2196 * factory, since ob_item may change).
2197 */
2198 saved_ob_size = Py_SIZE(self);
2199 saved_ob_item = self->ob_item;
2200 saved_allocated = self->allocated;
Victor Stinner60ac6ed2020-02-07 23:18:08 +01002201 Py_SET_SIZE(self, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002202 self->ob_item = NULL;
2203 self->allocated = -1; /* any operation will reset it to >= 0 */
Tim Peters330f9e92002-07-19 07:05:44 +00002204
Daniel Stutzbach98338222010-12-02 21:55:33 +00002205 if (keyfunc == NULL) {
2206 keys = NULL;
2207 lo.keys = saved_ob_item;
2208 lo.values = NULL;
2209 }
2210 else {
2211 if (saved_ob_size < MERGESTATE_TEMP_SIZE/2)
2212 /* Leverage stack space we allocated but won't otherwise use */
2213 keys = &ms.temparray[saved_ob_size+1];
2214 else {
2215 keys = PyMem_MALLOC(sizeof(PyObject *) * saved_ob_size);
Benjamin Peterson0823ffb2015-04-23 17:04:36 -04002216 if (keys == NULL) {
2217 PyErr_NoMemory();
2218 goto keyfunc_fail;
2219 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002220 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00002221
2222 for (i = 0; i < saved_ob_size ; i++) {
Petr Viktorinffd97532020-02-11 17:46:57 +01002223 keys[i] = PyObject_CallOneArg(keyfunc, saved_ob_item[i]);
Daniel Stutzbach98338222010-12-02 21:55:33 +00002224 if (keys[i] == NULL) {
2225 for (i=i-1 ; i>=0 ; i--)
2226 Py_DECREF(keys[i]);
Benjamin Peterson4a42cd42014-03-15 12:21:28 -05002227 if (saved_ob_size >= MERGESTATE_TEMP_SIZE/2)
Daniel Stutzbach8eda5f72011-03-02 23:37:50 +00002228 PyMem_FREE(keys);
Daniel Stutzbach98338222010-12-02 21:55:33 +00002229 goto keyfunc_fail;
2230 }
2231 }
2232
2233 lo.keys = keys;
2234 lo.values = saved_ob_item;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002235 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002236
embg1e34da42018-01-28 20:03:23 -07002237
2238 /* The pre-sort check: here's where we decide which compare function to use.
2239 * How much optimization is safe? We test for homogeneity with respect to
2240 * several properties that are expensive to check at compare-time, and
2241 * set ms appropriately. */
2242 if (saved_ob_size > 1) {
2243 /* Assume the first element is representative of the whole list. */
Andy Lesterdffe4c02020-03-04 07:15:20 -06002244 int keys_are_in_tuples = (Py_IS_TYPE(lo.keys[0], &PyTuple_Type) &&
embg1e34da42018-01-28 20:03:23 -07002245 Py_SIZE(lo.keys[0]) > 0);
2246
2247 PyTypeObject* key_type = (keys_are_in_tuples ?
Victor Stinner58ac7002020-02-07 03:04:21 +01002248 Py_TYPE(PyTuple_GET_ITEM(lo.keys[0], 0)) :
2249 Py_TYPE(lo.keys[0]));
embg1e34da42018-01-28 20:03:23 -07002250
2251 int keys_are_all_same_type = 1;
2252 int strings_are_latin = 1;
2253 int ints_are_bounded = 1;
2254
2255 /* Prove that assumption by checking every key. */
embg1e34da42018-01-28 20:03:23 -07002256 for (i=0; i < saved_ob_size; i++) {
2257
2258 if (keys_are_in_tuples &&
Andy Lesterdffe4c02020-03-04 07:15:20 -06002259 !(Py_IS_TYPE(lo.keys[i], &PyTuple_Type) && Py_SIZE(lo.keys[i]) != 0)) {
embg1e34da42018-01-28 20:03:23 -07002260 keys_are_in_tuples = 0;
2261 keys_are_all_same_type = 0;
2262 break;
2263 }
2264
2265 /* Note: for lists of tuples, key is the first element of the tuple
2266 * lo.keys[i], not lo.keys[i] itself! We verify type-homogeneity
2267 * for lists of tuples in the if-statement directly above. */
2268 PyObject *key = (keys_are_in_tuples ?
2269 PyTuple_GET_ITEM(lo.keys[i], 0) :
2270 lo.keys[i]);
2271
Andy Lesterdffe4c02020-03-04 07:15:20 -06002272 if (!Py_IS_TYPE(key, key_type)) {
embg1e34da42018-01-28 20:03:23 -07002273 keys_are_all_same_type = 0;
Rémi Lapeyredd5417a2019-03-25 08:25:37 +01002274 /* If keys are in tuple we must loop over the whole list to make
2275 sure all items are tuples */
2276 if (!keys_are_in_tuples) {
2277 break;
2278 }
embg1e34da42018-01-28 20:03:23 -07002279 }
2280
Rémi Lapeyredd5417a2019-03-25 08:25:37 +01002281 if (keys_are_all_same_type) {
2282 if (key_type == &PyLong_Type &&
2283 ints_are_bounded &&
2284 Py_ABS(Py_SIZE(key)) > 1) {
2285
embg1e34da42018-01-28 20:03:23 -07002286 ints_are_bounded = 0;
Rémi Lapeyredd5417a2019-03-25 08:25:37 +01002287 }
2288 else if (key_type == &PyUnicode_Type &&
2289 strings_are_latin &&
2290 PyUnicode_KIND(key) != PyUnicode_1BYTE_KIND) {
2291
2292 strings_are_latin = 0;
2293 }
2294 }
embg1e34da42018-01-28 20:03:23 -07002295 }
embg1e34da42018-01-28 20:03:23 -07002296
2297 /* Choose the best compare, given what we now know about the keys. */
2298 if (keys_are_all_same_type) {
2299
2300 if (key_type == &PyUnicode_Type && strings_are_latin) {
2301 ms.key_compare = unsafe_latin_compare;
2302 }
2303 else if (key_type == &PyLong_Type && ints_are_bounded) {
2304 ms.key_compare = unsafe_long_compare;
2305 }
2306 else if (key_type == &PyFloat_Type) {
2307 ms.key_compare = unsafe_float_compare;
2308 }
2309 else if ((ms.key_richcompare = key_type->tp_richcompare) != NULL) {
2310 ms.key_compare = unsafe_object_compare;
2311 }
Zackery Spytzebc793d2019-02-21 00:47:14 -07002312 else {
2313 ms.key_compare = safe_object_compare;
2314 }
embg1e34da42018-01-28 20:03:23 -07002315 }
2316 else {
2317 ms.key_compare = safe_object_compare;
2318 }
2319
2320 if (keys_are_in_tuples) {
2321 /* Make sure we're not dealing with tuples of tuples
2322 * (remember: here, key_type refers list [key[0] for key in keys]) */
Rémi Lapeyredd5417a2019-03-25 08:25:37 +01002323 if (key_type == &PyTuple_Type) {
embg1e34da42018-01-28 20:03:23 -07002324 ms.tuple_elem_compare = safe_object_compare;
Rémi Lapeyredd5417a2019-03-25 08:25:37 +01002325 }
2326 else {
embg1e34da42018-01-28 20:03:23 -07002327 ms.tuple_elem_compare = ms.key_compare;
Rémi Lapeyredd5417a2019-03-25 08:25:37 +01002328 }
embg1e34da42018-01-28 20:03:23 -07002329
2330 ms.key_compare = unsafe_tuple_compare;
2331 }
2332 }
2333 /* End of pre-sort check: ms is now set properly! */
2334
Daniel Stutzbach98338222010-12-02 21:55:33 +00002335 merge_init(&ms, saved_ob_size, keys != NULL);
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002337 nremaining = saved_ob_size;
2338 if (nremaining < 2)
2339 goto succeed;
Tim Peters330f9e92002-07-19 07:05:44 +00002340
Benjamin Peterson05380642010-08-23 19:35:39 +00002341 /* Reverse sort stability achieved by initially reversing the list,
2342 applying a stable forward sort, then reversing the final result. */
Daniel Stutzbach98338222010-12-02 21:55:33 +00002343 if (reverse) {
2344 if (keys != NULL)
2345 reverse_slice(&keys[0], &keys[saved_ob_size]);
2346 reverse_slice(&saved_ob_item[0], &saved_ob_item[saved_ob_size]);
2347 }
Benjamin Peterson05380642010-08-23 19:35:39 +00002348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002349 /* March over the array once, left to right, finding natural runs,
2350 * and extending short natural runs to minrun elements.
2351 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002352 minrun = merge_compute_minrun(nremaining);
2353 do {
2354 int descending;
2355 Py_ssize_t n;
Tim Peters330f9e92002-07-19 07:05:44 +00002356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002357 /* Identify next run. */
embg1e34da42018-01-28 20:03:23 -07002358 n = count_run(&ms, lo.keys, lo.keys + nremaining, &descending);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002359 if (n < 0)
2360 goto fail;
2361 if (descending)
Daniel Stutzbach98338222010-12-02 21:55:33 +00002362 reverse_sortslice(&lo, n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002363 /* If short, extend to min(minrun, nremaining). */
2364 if (n < minrun) {
2365 const Py_ssize_t force = nremaining <= minrun ?
2366 nremaining : minrun;
embg1e34da42018-01-28 20:03:23 -07002367 if (binarysort(&ms, lo, lo.keys + force, lo.keys + n) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002368 goto fail;
2369 n = force;
2370 }
2371 /* Push run onto pending-runs stack, and maybe merge. */
2372 assert(ms.n < MAX_MERGE_PENDING);
2373 ms.pending[ms.n].base = lo;
2374 ms.pending[ms.n].len = n;
2375 ++ms.n;
2376 if (merge_collapse(&ms) < 0)
2377 goto fail;
2378 /* Advance to find next run. */
Daniel Stutzbach98338222010-12-02 21:55:33 +00002379 sortslice_advance(&lo, n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002380 nremaining -= n;
2381 } while (nremaining);
Tim Peters330f9e92002-07-19 07:05:44 +00002382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002383 if (merge_force_collapse(&ms) < 0)
2384 goto fail;
2385 assert(ms.n == 1);
Daniel Stutzbach98338222010-12-02 21:55:33 +00002386 assert(keys == NULL
2387 ? ms.pending[0].base.keys == saved_ob_item
2388 : ms.pending[0].base.keys == &keys[0]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002389 assert(ms.pending[0].len == saved_ob_size);
Daniel Stutzbach98338222010-12-02 21:55:33 +00002390 lo = ms.pending[0].base;
Tim Petersa64dc242002-08-01 02:13:36 +00002391
2392succeed:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002393 result = Py_None;
Tim Peters330f9e92002-07-19 07:05:44 +00002394fail:
Daniel Stutzbach98338222010-12-02 21:55:33 +00002395 if (keys != NULL) {
2396 for (i = 0; i < saved_ob_size; i++)
2397 Py_DECREF(keys[i]);
Benjamin Petersonef87f8c2014-03-14 21:54:31 -05002398 if (saved_ob_size >= MERGESTATE_TEMP_SIZE/2)
Daniel Stutzbach98338222010-12-02 21:55:33 +00002399 PyMem_FREE(keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002400 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002402 if (self->allocated != -1 && result != NULL) {
2403 /* The user mucked with the list during the sort,
2404 * and we don't already have another error to report.
2405 */
2406 PyErr_SetString(PyExc_ValueError, "list modified during sort");
2407 result = NULL;
2408 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002410 if (reverse && saved_ob_size > 1)
2411 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002413 merge_freemem(&ms);
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002414
Daniel Stutzbach98338222010-12-02 21:55:33 +00002415keyfunc_fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002416 final_ob_item = self->ob_item;
2417 i = Py_SIZE(self);
Victor Stinner60ac6ed2020-02-07 23:18:08 +01002418 Py_SET_SIZE(self, saved_ob_size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002419 self->ob_item = saved_ob_item;
2420 self->allocated = saved_allocated;
2421 if (final_ob_item != NULL) {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002422 /* we cannot use _list_clear() for this because it does not
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002423 guarantee that the list is really empty when it returns */
2424 while (--i >= 0) {
2425 Py_XDECREF(final_ob_item[i]);
2426 }
2427 PyMem_FREE(final_ob_item);
2428 }
2429 Py_XINCREF(result);
2430 return result;
Guido van Rossum3f236de1996-12-10 23:55:39 +00002431}
Tim Peters330f9e92002-07-19 07:05:44 +00002432#undef IFLT
Tim Peters66860f62002-08-04 17:47:26 +00002433#undef ISLT
Tim Peters330f9e92002-07-19 07:05:44 +00002434
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002435int
Fred Drakea2f55112000-07-09 15:16:51 +00002436PyList_Sort(PyObject *v)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002437{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002438 if (v == NULL || !PyList_Check(v)) {
2439 PyErr_BadInternalCall();
2440 return -1;
2441 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002442 v = list_sort_impl((PyListObject *)v, NULL, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002443 if (v == NULL)
2444 return -1;
2445 Py_DECREF(v);
2446 return 0;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002447}
2448
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002449/*[clinic input]
2450list.reverse
2451
2452Reverse *IN PLACE*.
2453[clinic start generated code]*/
2454
Guido van Rossumb86c5492001-02-12 22:06:02 +00002455static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002456list_reverse_impl(PyListObject *self)
2457/*[clinic end generated code: output=482544fc451abea9 input=eefd4c3ae1bc9887]*/
Guido van Rossumb86c5492001-02-12 22:06:02 +00002458{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002459 if (Py_SIZE(self) > 1)
2460 reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
2461 Py_RETURN_NONE;
Guido van Rossumed98d481991-03-06 13:07:53 +00002462}
2463
Guido van Rossum84c76f51990-10-30 13:32:20 +00002464int
Fred Drakea2f55112000-07-09 15:16:51 +00002465PyList_Reverse(PyObject *v)
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002466{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002467 PyListObject *self = (PyListObject *)v;
Tim Peters6063e262002-08-08 01:06:39 +00002468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002469 if (v == NULL || !PyList_Check(v)) {
2470 PyErr_BadInternalCall();
2471 return -1;
2472 }
2473 if (Py_SIZE(self) > 1)
2474 reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
2475 return 0;
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002476}
2477
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002478PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00002479PyList_AsTuple(PyObject *v)
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002480{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002481 if (v == NULL || !PyList_Check(v)) {
2482 PyErr_BadInternalCall();
2483 return NULL;
2484 }
Sergey Fedoseev234531b2019-02-25 21:59:12 +05002485 return _PyTuple_FromArray(((PyListObject *)v)->ob_item, Py_SIZE(v));
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002486}
2487
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002488/*[clinic input]
2489list.index
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002490
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002491 value: object
Serhiy Storchaka80ec8362017-03-19 19:37:40 +02002492 start: slice_index(accept={int}) = 0
2493 stop: slice_index(accept={int}, c_default="PY_SSIZE_T_MAX") = sys.maxsize
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002494 /
2495
2496Return first index of value.
2497
2498Raises ValueError if the value is not present.
2499[clinic start generated code]*/
2500
2501static PyObject *
2502list_index_impl(PyListObject *self, PyObject *value, Py_ssize_t start,
2503 Py_ssize_t stop)
Serhiy Storchaka80ec8362017-03-19 19:37:40 +02002504/*[clinic end generated code: output=ec51b88787e4e481 input=40ec5826303a0eb1]*/
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002505{
2506 Py_ssize_t i;
2507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002508 if (start < 0) {
2509 start += Py_SIZE(self);
2510 if (start < 0)
2511 start = 0;
2512 }
2513 if (stop < 0) {
2514 stop += Py_SIZE(self);
2515 if (stop < 0)
2516 stop = 0;
2517 }
2518 for (i = start; i < stop && i < Py_SIZE(self); i++) {
Zackery Spytzd9e561d2019-12-30 12:32:58 -07002519 PyObject *obj = self->ob_item[i];
2520 Py_INCREF(obj);
2521 int cmp = PyObject_RichCompareBool(obj, value, Py_EQ);
2522 Py_DECREF(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002523 if (cmp > 0)
2524 return PyLong_FromSsize_t(i);
2525 else if (cmp < 0)
2526 return NULL;
2527 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002528 PyErr_Format(PyExc_ValueError, "%R is not in list", value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002529 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002530}
2531
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002532/*[clinic input]
2533list.count
2534
2535 value: object
2536 /
2537
2538Return number of occurrences of value.
2539[clinic start generated code]*/
2540
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002541static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002542list_count(PyListObject *self, PyObject *value)
2543/*[clinic end generated code: output=b1f5d284205ae714 input=3bdc3a5e6f749565]*/
Guido van Rossume6f7d181991-10-20 20:20:40 +00002544{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002545 Py_ssize_t count = 0;
2546 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002548 for (i = 0; i < Py_SIZE(self); i++) {
Zackery Spytzd9e561d2019-12-30 12:32:58 -07002549 PyObject *obj = self->ob_item[i];
Dong-hee Na14d80d02020-01-23 02:36:54 +09002550 if (obj == value) {
2551 count++;
2552 continue;
2553 }
Zackery Spytzd9e561d2019-12-30 12:32:58 -07002554 Py_INCREF(obj);
2555 int cmp = PyObject_RichCompareBool(obj, value, Py_EQ);
2556 Py_DECREF(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002557 if (cmp > 0)
2558 count++;
2559 else if (cmp < 0)
2560 return NULL;
2561 }
2562 return PyLong_FromSsize_t(count);
Guido van Rossume6f7d181991-10-20 20:20:40 +00002563}
2564
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002565/*[clinic input]
2566list.remove
2567
2568 value: object
2569 /
2570
2571Remove first occurrence of value.
2572
2573Raises ValueError if the value is not present.
2574[clinic start generated code]*/
2575
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002576static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002577list_remove(PyListObject *self, PyObject *value)
2578/*[clinic end generated code: output=f087e1951a5e30d1 input=2dc2ba5bb2fb1f82]*/
Guido van Rossumed98d481991-03-06 13:07:53 +00002579{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002580 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002581
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002582 for (i = 0; i < Py_SIZE(self); i++) {
Zackery Spytzd9e561d2019-12-30 12:32:58 -07002583 PyObject *obj = self->ob_item[i];
2584 Py_INCREF(obj);
2585 int cmp = PyObject_RichCompareBool(obj, value, Py_EQ);
2586 Py_DECREF(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002587 if (cmp > 0) {
2588 if (list_ass_slice(self, i, i+1,
2589 (PyObject *)NULL) == 0)
2590 Py_RETURN_NONE;
2591 return NULL;
2592 }
2593 else if (cmp < 0)
2594 return NULL;
2595 }
2596 PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
2597 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002598}
2599
Jeremy Hylton8caad492000-06-23 14:18:11 +00002600static int
2601list_traverse(PyListObject *o, visitproc visit, void *arg)
2602{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002603 Py_ssize_t i;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002605 for (i = Py_SIZE(o); --i >= 0; )
2606 Py_VISIT(o->ob_item[i]);
2607 return 0;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002608}
2609
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002610static PyObject *
2611list_richcompare(PyObject *v, PyObject *w, int op)
2612{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002613 PyListObject *vl, *wl;
2614 Py_ssize_t i;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002615
Brian Curtindfc80e32011-08-10 20:28:54 -05002616 if (!PyList_Check(v) || !PyList_Check(w))
2617 Py_RETURN_NOTIMPLEMENTED;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002619 vl = (PyListObject *)v;
2620 wl = (PyListObject *)w;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002622 if (Py_SIZE(vl) != Py_SIZE(wl) && (op == Py_EQ || op == Py_NE)) {
2623 /* Shortcut: if the lengths differ, the lists differ */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002624 if (op == Py_EQ)
stratakise8b19652017-11-02 11:32:54 +01002625 Py_RETURN_FALSE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002626 else
stratakise8b19652017-11-02 11:32:54 +01002627 Py_RETURN_TRUE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002628 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002630 /* Search for the first index where items are different */
2631 for (i = 0; i < Py_SIZE(vl) && i < Py_SIZE(wl); i++) {
Dong-hee Na2d5bf562019-12-31 10:04:22 +09002632 PyObject *vitem = vl->ob_item[i];
2633 PyObject *witem = wl->ob_item[i];
Inada Naokidfef9862019-12-31 10:58:37 +09002634 if (vitem == witem) {
2635 continue;
2636 }
Dong-hee Na2d5bf562019-12-31 10:04:22 +09002637
2638 Py_INCREF(vitem);
2639 Py_INCREF(witem);
sweeneydebe7ead62020-02-26 02:00:35 -05002640 int k = PyObject_RichCompareBool(vitem, witem, Py_EQ);
Dong-hee Na2d5bf562019-12-31 10:04:22 +09002641 Py_DECREF(vitem);
2642 Py_DECREF(witem);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002643 if (k < 0)
2644 return NULL;
2645 if (!k)
2646 break;
2647 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002649 if (i >= Py_SIZE(vl) || i >= Py_SIZE(wl)) {
2650 /* No more items to compare -- compare sizes */
stratakise8b19652017-11-02 11:32:54 +01002651 Py_RETURN_RICHCOMPARE(Py_SIZE(vl), Py_SIZE(wl), op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002652 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002654 /* We have an item that differs -- shortcuts for EQ/NE */
2655 if (op == Py_EQ) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02002656 Py_RETURN_FALSE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002657 }
2658 if (op == Py_NE) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02002659 Py_RETURN_TRUE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002660 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002661
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002662 /* Compare the final item again using the proper operator */
2663 return PyObject_RichCompare(vl->ob_item[i], wl->ob_item[i], op);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002664}
2665
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002666/*[clinic input]
2667list.__init__
2668
2669 iterable: object(c_default="NULL") = ()
2670 /
2671
2672Built-in mutable sequence.
2673
2674If no argument is given, the constructor creates a new empty list.
2675The argument must be an iterable if specified.
2676[clinic start generated code]*/
2677
Tim Peters6d6c1a32001-08-02 04:15:00 +00002678static int
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002679list___init___impl(PyListObject *self, PyObject *iterable)
2680/*[clinic end generated code: output=0f3c21379d01de48 input=b3f3fe7206af8f6b]*/
Tim Peters6d6c1a32001-08-02 04:15:00 +00002681{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002682 /* Verify list invariants established by PyType_GenericAlloc() */
2683 assert(0 <= Py_SIZE(self));
2684 assert(Py_SIZE(self) <= self->allocated || self->allocated == -1);
2685 assert(self->ob_item != NULL ||
2686 self->allocated == 0 || self->allocated == -1);
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002687
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002688 /* Empty previous contents */
2689 if (self->ob_item != NULL) {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002690 (void)_list_clear(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002691 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002692 if (iterable != NULL) {
Pablo Galindo372d7052018-10-28 20:16:26 +00002693 if (_PyObject_HasLen(iterable)) {
2694 Py_ssize_t iter_len = PyObject_Size(iterable);
2695 if (iter_len == -1) {
2696 if (!PyErr_ExceptionMatches(PyExc_TypeError)) {
2697 return -1;
2698 }
2699 PyErr_Clear();
2700 }
2701 if (iter_len > 0 && self->ob_item == NULL
2702 && list_preallocate_exact(self, iter_len)) {
2703 return -1;
2704 }
2705 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002706 PyObject *rv = list_extend(self, iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002707 if (rv == NULL)
2708 return -1;
2709 Py_DECREF(rv);
2710 }
2711 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002712}
2713
Petr Viktorince105542020-03-30 14:16:16 +02002714static PyObject *
2715list_vectorcall(PyObject *type, PyObject * const*args,
2716 size_t nargsf, PyObject *kwnames)
2717{
2718 if (!_PyArg_NoKwnames("list", kwnames)) {
2719 return NULL;
2720 }
2721 Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
2722 if (!_PyArg_CheckPositional("list", nargs, 0, 1)) {
2723 return NULL;
2724 }
2725
2726 assert(PyType_Check(type));
2727 PyObject *list = PyType_GenericAlloc((PyTypeObject *)type, 0);
2728 if (list == NULL) {
2729 return NULL;
2730 }
2731 if (nargs) {
2732 if (list___init___impl((PyListObject *)list, args[0])) {
2733 Py_DECREF(list);
2734 return NULL;
2735 }
2736 }
2737 return list;
2738}
2739
2740
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002741/*[clinic input]
2742list.__sizeof__
2743
2744Return the size of the list in memory, in bytes.
2745[clinic start generated code]*/
2746
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002747static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002748list___sizeof___impl(PyListObject *self)
2749/*[clinic end generated code: output=3417541f95f9a53e input=b8030a5d5ce8a187]*/
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002750{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002751 Py_ssize_t res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002752
Serhiy Storchaka5c4064e2015-12-19 20:05:25 +02002753 res = _PyObject_SIZE(Py_TYPE(self)) + self->allocated * sizeof(void*);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002754 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002755}
2756
Raymond Hettinger1021c442003-11-07 15:38:09 +00002757static PyObject *list_iter(PyObject *seq);
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002758static PyObject *list_subscript(PyListObject*, PyObject*);
2759
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002760static PyMethodDef list_methods[] = {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002761 {"__getitem__", (PyCFunction)list_subscript, METH_O|METH_COEXIST, "x.__getitem__(y) <==> x[y]"},
2762 LIST___REVERSED___METHODDEF
2763 LIST___SIZEOF___METHODDEF
2764 LIST_CLEAR_METHODDEF
2765 LIST_COPY_METHODDEF
2766 LIST_APPEND_METHODDEF
2767 LIST_INSERT_METHODDEF
2768 LIST_EXTEND_METHODDEF
2769 LIST_POP_METHODDEF
2770 LIST_REMOVE_METHODDEF
2771 LIST_INDEX_METHODDEF
2772 LIST_COUNT_METHODDEF
2773 LIST_REVERSE_METHODDEF
2774 LIST_SORT_METHODDEF
Guido van Rossum48b069a2020-04-07 09:50:06 -07002775 {"__class_getitem__", (PyCFunction)Py_GenericAlias, METH_O|METH_CLASS, PyDoc_STR("See PEP 585")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002776 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002777};
2778
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002779static PySequenceMethods list_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002780 (lenfunc)list_length, /* sq_length */
2781 (binaryfunc)list_concat, /* sq_concat */
2782 (ssizeargfunc)list_repeat, /* sq_repeat */
2783 (ssizeargfunc)list_item, /* sq_item */
2784 0, /* sq_slice */
2785 (ssizeobjargproc)list_ass_item, /* sq_ass_item */
2786 0, /* sq_ass_slice */
2787 (objobjproc)list_contains, /* sq_contains */
2788 (binaryfunc)list_inplace_concat, /* sq_inplace_concat */
2789 (ssizeargfunc)list_inplace_repeat, /* sq_inplace_repeat */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002790};
2791
Jeremy Hyltona4b4c3b2002-07-13 03:51:17 +00002792static PyObject *
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002793list_subscript(PyListObject* self, PyObject* item)
2794{
Victor Stinnera15e2602020-04-08 02:01:56 +02002795 if (_PyIndex_Check(item)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002796 Py_ssize_t i;
2797 i = PyNumber_AsSsize_t(item, PyExc_IndexError);
2798 if (i == -1 && PyErr_Occurred())
2799 return NULL;
2800 if (i < 0)
2801 i += PyList_GET_SIZE(self);
2802 return list_item(self, i);
2803 }
2804 else if (PySlice_Check(item)) {
HongWeipeng3c87a662019-09-08 18:15:56 +08002805 Py_ssize_t start, stop, step, slicelength, i;
2806 size_t cur;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002807 PyObject* result;
2808 PyObject* it;
2809 PyObject **src, **dest;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002810
Serhiy Storchakab879fe82017-04-08 09:53:51 +03002811 if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002812 return NULL;
2813 }
Serhiy Storchakab879fe82017-04-08 09:53:51 +03002814 slicelength = PySlice_AdjustIndices(Py_SIZE(self), &start, &stop,
2815 step);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002816
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002817 if (slicelength <= 0) {
2818 return PyList_New(0);
2819 }
2820 else if (step == 1) {
2821 return list_slice(self, start, stop);
2822 }
2823 else {
Sergey Fedoseev2fc46972018-08-11 18:12:07 +05002824 result = list_new_prealloc(slicelength);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002825 if (!result) return NULL;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002826
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002827 src = self->ob_item;
2828 dest = ((PyListObject *)result)->ob_item;
2829 for (cur = start, i = 0; i < slicelength;
Mark Dickinsonc7d93b72011-09-25 15:34:32 +01002830 cur += (size_t)step, i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002831 it = src[cur];
2832 Py_INCREF(it);
2833 dest[i] = it;
2834 }
Victor Stinner60ac6ed2020-02-07 23:18:08 +01002835 Py_SET_SIZE(result, slicelength);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002836 return result;
2837 }
2838 }
2839 else {
2840 PyErr_Format(PyExc_TypeError,
Terry Jan Reedyffff1442014-08-02 01:30:37 -04002841 "list indices must be integers or slices, not %.200s",
Victor Stinner58ac7002020-02-07 03:04:21 +01002842 Py_TYPE(item)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002843 return NULL;
2844 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002845}
2846
Tim Peters3b01a122002-07-19 02:35:45 +00002847static int
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002848list_ass_subscript(PyListObject* self, PyObject* item, PyObject* value)
2849{
Victor Stinnera15e2602020-04-08 02:01:56 +02002850 if (_PyIndex_Check(item)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002851 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
2852 if (i == -1 && PyErr_Occurred())
2853 return -1;
2854 if (i < 0)
2855 i += PyList_GET_SIZE(self);
2856 return list_ass_item(self, i, value);
2857 }
2858 else if (PySlice_Check(item)) {
2859 Py_ssize_t start, stop, step, slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002860
Serhiy Storchakab879fe82017-04-08 09:53:51 +03002861 if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002862 return -1;
2863 }
Serhiy Storchakab879fe82017-04-08 09:53:51 +03002864 slicelength = PySlice_AdjustIndices(Py_SIZE(self), &start, &stop,
2865 step);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002866
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002867 if (step == 1)
2868 return list_ass_slice(self, start, stop, value);
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002870 /* Make sure s[5:2] = [..] inserts at the right place:
2871 before 5, not before 2. */
2872 if ((step < 0 && start < stop) ||
2873 (step > 0 && start > stop))
2874 stop = start;
Thomas Woutersed03b412007-08-28 21:37:11 +00002875
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002876 if (value == NULL) {
2877 /* delete slice */
2878 PyObject **garbage;
2879 size_t cur;
2880 Py_ssize_t i;
Victor Stinner35f28032013-11-21 12:16:35 +01002881 int res;
Tim Peters3b01a122002-07-19 02:35:45 +00002882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002883 if (slicelength <= 0)
2884 return 0;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002886 if (step < 0) {
2887 stop = start + 1;
2888 start = stop + step*(slicelength - 1) - 1;
2889 step = -step;
2890 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002892 garbage = (PyObject**)
2893 PyMem_MALLOC(slicelength*sizeof(PyObject*));
2894 if (!garbage) {
2895 PyErr_NoMemory();
2896 return -1;
2897 }
Tim Peters3b01a122002-07-19 02:35:45 +00002898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002899 /* drawing pictures might help understand these for
2900 loops. Basically, we memmove the parts of the
2901 list that are *not* part of the slice: step-1
2902 items for each item that is part of the slice,
2903 and then tail end of the list that was not
2904 covered by the slice */
2905 for (cur = start, i = 0;
2906 cur < (size_t)stop;
2907 cur += step, i++) {
2908 Py_ssize_t lim = step - 1;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002909
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002910 garbage[i] = PyList_GET_ITEM(self, cur);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002911
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002912 if (cur + step >= (size_t)Py_SIZE(self)) {
2913 lim = Py_SIZE(self) - cur - 1;
2914 }
Michael W. Hudson56796f62002-07-29 14:35:04 +00002915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002916 memmove(self->ob_item + cur - i,
2917 self->ob_item + cur + 1,
2918 lim * sizeof(PyObject *));
2919 }
Mark Dickinsonc7d93b72011-09-25 15:34:32 +01002920 cur = start + (size_t)slicelength * step;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002921 if (cur < (size_t)Py_SIZE(self)) {
2922 memmove(self->ob_item + cur - slicelength,
2923 self->ob_item + cur,
2924 (Py_SIZE(self) - cur) *
2925 sizeof(PyObject *));
2926 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002927
Victor Stinner60ac6ed2020-02-07 23:18:08 +01002928 Py_SET_SIZE(self, Py_SIZE(self) - slicelength);
Victor Stinner35f28032013-11-21 12:16:35 +01002929 res = list_resize(self, Py_SIZE(self));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002931 for (i = 0; i < slicelength; i++) {
2932 Py_DECREF(garbage[i]);
2933 }
2934 PyMem_FREE(garbage);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002935
Victor Stinner35f28032013-11-21 12:16:35 +01002936 return res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002937 }
2938 else {
2939 /* assign slice */
2940 PyObject *ins, *seq;
2941 PyObject **garbage, **seqitems, **selfitems;
HongWeipeng3c87a662019-09-08 18:15:56 +08002942 Py_ssize_t i;
2943 size_t cur;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002945 /* protect against a[::-1] = a */
2946 if (self == (PyListObject*)value) {
2947 seq = list_slice((PyListObject*)value, 0,
2948 PyList_GET_SIZE(value));
2949 }
2950 else {
2951 seq = PySequence_Fast(value,
2952 "must assign iterable "
2953 "to extended slice");
2954 }
2955 if (!seq)
2956 return -1;
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002958 if (PySequence_Fast_GET_SIZE(seq) != slicelength) {
2959 PyErr_Format(PyExc_ValueError,
2960 "attempt to assign sequence of "
2961 "size %zd to extended slice of "
2962 "size %zd",
2963 PySequence_Fast_GET_SIZE(seq),
2964 slicelength);
2965 Py_DECREF(seq);
2966 return -1;
2967 }
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002969 if (!slicelength) {
2970 Py_DECREF(seq);
2971 return 0;
2972 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002974 garbage = (PyObject**)
2975 PyMem_MALLOC(slicelength*sizeof(PyObject*));
2976 if (!garbage) {
2977 Py_DECREF(seq);
2978 PyErr_NoMemory();
2979 return -1;
2980 }
Tim Peters3b01a122002-07-19 02:35:45 +00002981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002982 selfitems = self->ob_item;
2983 seqitems = PySequence_Fast_ITEMS(seq);
2984 for (cur = start, i = 0; i < slicelength;
Mark Dickinsonc7d93b72011-09-25 15:34:32 +01002985 cur += (size_t)step, i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002986 garbage[i] = selfitems[cur];
2987 ins = seqitems[i];
2988 Py_INCREF(ins);
2989 selfitems[cur] = ins;
2990 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002992 for (i = 0; i < slicelength; i++) {
2993 Py_DECREF(garbage[i]);
2994 }
Tim Peters3b01a122002-07-19 02:35:45 +00002995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002996 PyMem_FREE(garbage);
2997 Py_DECREF(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002999 return 0;
3000 }
3001 }
3002 else {
3003 PyErr_Format(PyExc_TypeError,
Terry Jan Reedyffff1442014-08-02 01:30:37 -04003004 "list indices must be integers or slices, not %.200s",
Victor Stinner58ac7002020-02-07 03:04:21 +01003005 Py_TYPE(item)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003006 return -1;
3007 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00003008}
3009
3010static PyMappingMethods list_as_mapping = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003011 (lenfunc)list_length,
3012 (binaryfunc)list_subscript,
3013 (objobjargproc)list_ass_subscript
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00003014};
3015
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003016PyTypeObject PyList_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003017 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3018 "list",
3019 sizeof(PyListObject),
3020 0,
3021 (destructor)list_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003022 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003023 0, /* tp_getattr */
3024 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003025 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003026 (reprfunc)list_repr, /* tp_repr */
3027 0, /* tp_as_number */
3028 &list_as_sequence, /* tp_as_sequence */
3029 &list_as_mapping, /* tp_as_mapping */
Georg Brandl00da4e02010-10-18 07:32:48 +00003030 PyObject_HashNotImplemented, /* tp_hash */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003031 0, /* tp_call */
3032 0, /* tp_str */
3033 PyObject_GenericGetAttr, /* tp_getattro */
3034 0, /* tp_setattro */
3035 0, /* tp_as_buffer */
3036 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02003037 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LIST_SUBCLASS, /* tp_flags */
3038 list___init____doc__, /* tp_doc */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003039 (traverseproc)list_traverse, /* tp_traverse */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02003040 (inquiry)_list_clear, /* tp_clear */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003041 list_richcompare, /* tp_richcompare */
3042 0, /* tp_weaklistoffset */
3043 list_iter, /* tp_iter */
3044 0, /* tp_iternext */
3045 list_methods, /* tp_methods */
3046 0, /* tp_members */
3047 0, /* tp_getset */
3048 0, /* tp_base */
3049 0, /* tp_dict */
3050 0, /* tp_descr_get */
3051 0, /* tp_descr_set */
3052 0, /* tp_dictoffset */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02003053 (initproc)list___init__, /* tp_init */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003054 PyType_GenericAlloc, /* tp_alloc */
3055 PyType_GenericNew, /* tp_new */
3056 PyObject_GC_Del, /* tp_free */
Petr Viktorince105542020-03-30 14:16:16 +02003057 .tp_vectorcall = list_vectorcall,
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003058};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00003059
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00003060/*********************** List Iterator **************************/
3061
3062typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003063 PyObject_HEAD
Victor Stinner7660b882013-06-24 23:59:24 +02003064 Py_ssize_t it_index;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003065 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00003066} listiterobject;
3067
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003068static void listiter_dealloc(listiterobject *);
3069static int listiter_traverse(listiterobject *, visitproc, void *);
3070static PyObject *listiter_next(listiterobject *);
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303071static PyObject *listiter_len(listiterobject *, PyObject *);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003072static PyObject *listiter_reduce_general(void *_it, int forward);
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303073static PyObject *listiter_reduce(listiterobject *, PyObject *);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003074static PyObject *listiter_setstate(listiterobject *, PyObject *state);
Raymond Hettinger435bf582004-03-18 22:43:10 +00003075
Armin Rigof5b3e362006-02-11 21:32:43 +00003076PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003077PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
3078PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00003079
3080static PyMethodDef listiter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003081 {"__length_hint__", (PyCFunction)listiter_len, METH_NOARGS, length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003082 {"__reduce__", (PyCFunction)listiter_reduce, METH_NOARGS, reduce_doc},
3083 {"__setstate__", (PyCFunction)listiter_setstate, METH_O, setstate_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003084 {NULL, NULL} /* sentinel */
Raymond Hettinger435bf582004-03-18 22:43:10 +00003085};
3086
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00003087PyTypeObject PyListIter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003088 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3089 "list_iterator", /* tp_name */
3090 sizeof(listiterobject), /* tp_basicsize */
3091 0, /* tp_itemsize */
3092 /* methods */
3093 (destructor)listiter_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003094 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003095 0, /* tp_getattr */
3096 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003097 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003098 0, /* tp_repr */
3099 0, /* tp_as_number */
3100 0, /* tp_as_sequence */
3101 0, /* tp_as_mapping */
3102 0, /* tp_hash */
3103 0, /* tp_call */
3104 0, /* tp_str */
3105 PyObject_GenericGetAttr, /* tp_getattro */
3106 0, /* tp_setattro */
3107 0, /* tp_as_buffer */
3108 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3109 0, /* tp_doc */
3110 (traverseproc)listiter_traverse, /* tp_traverse */
3111 0, /* tp_clear */
3112 0, /* tp_richcompare */
3113 0, /* tp_weaklistoffset */
3114 PyObject_SelfIter, /* tp_iter */
3115 (iternextfunc)listiter_next, /* tp_iternext */
3116 listiter_methods, /* tp_methods */
3117 0, /* tp_members */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00003118};
Raymond Hettinger1021c442003-11-07 15:38:09 +00003119
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003120
3121static PyObject *
3122list_iter(PyObject *seq)
3123{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003124 listiterobject *it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003125
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003126 if (!PyList_Check(seq)) {
3127 PyErr_BadInternalCall();
3128 return NULL;
3129 }
3130 it = PyObject_GC_New(listiterobject, &PyListIter_Type);
3131 if (it == NULL)
3132 return NULL;
3133 it->it_index = 0;
3134 Py_INCREF(seq);
3135 it->it_seq = (PyListObject *)seq;
3136 _PyObject_GC_TRACK(it);
3137 return (PyObject *)it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003138}
3139
3140static void
3141listiter_dealloc(listiterobject *it)
3142{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003143 _PyObject_GC_UNTRACK(it);
3144 Py_XDECREF(it->it_seq);
3145 PyObject_GC_Del(it);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003146}
3147
3148static int
3149listiter_traverse(listiterobject *it, visitproc visit, void *arg)
3150{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003151 Py_VISIT(it->it_seq);
3152 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003153}
3154
3155static PyObject *
3156listiter_next(listiterobject *it)
3157{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003158 PyListObject *seq;
3159 PyObject *item;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003161 assert(it != NULL);
3162 seq = it->it_seq;
3163 if (seq == NULL)
3164 return NULL;
3165 assert(PyList_Check(seq));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003167 if (it->it_index < PyList_GET_SIZE(seq)) {
3168 item = PyList_GET_ITEM(seq, it->it_index);
3169 ++it->it_index;
3170 Py_INCREF(item);
3171 return item;
3172 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003174 it->it_seq = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003175 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003176 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003177}
3178
3179static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303180listiter_len(listiterobject *it, PyObject *Py_UNUSED(ignored))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003181{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003182 Py_ssize_t len;
3183 if (it->it_seq) {
3184 len = PyList_GET_SIZE(it->it_seq) - it->it_index;
3185 if (len >= 0)
3186 return PyLong_FromSsize_t(len);
3187 }
3188 return PyLong_FromLong(0);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003189}
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003190
3191static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303192listiter_reduce(listiterobject *it, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003193{
3194 return listiter_reduce_general(it, 1);
3195}
3196
3197static PyObject *
3198listiter_setstate(listiterobject *it, PyObject *state)
3199{
Victor Stinner7660b882013-06-24 23:59:24 +02003200 Py_ssize_t index = PyLong_AsSsize_t(state);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003201 if (index == -1 && PyErr_Occurred())
3202 return NULL;
3203 if (it->it_seq != NULL) {
3204 if (index < 0)
3205 index = 0;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +00003206 else if (index > PyList_GET_SIZE(it->it_seq))
3207 index = PyList_GET_SIZE(it->it_seq); /* iterator exhausted */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003208 it->it_index = index;
3209 }
3210 Py_RETURN_NONE;
3211}
3212
Raymond Hettinger1021c442003-11-07 15:38:09 +00003213/*********************** List Reverse Iterator **************************/
3214
3215typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003216 PyObject_HEAD
3217 Py_ssize_t it_index;
3218 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger1021c442003-11-07 15:38:09 +00003219} listreviterobject;
3220
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003221static void listreviter_dealloc(listreviterobject *);
3222static int listreviter_traverse(listreviterobject *, visitproc, void *);
3223static PyObject *listreviter_next(listreviterobject *);
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303224static PyObject *listreviter_len(listreviterobject *, PyObject *);
3225static PyObject *listreviter_reduce(listreviterobject *, PyObject *);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003226static PyObject *listreviter_setstate(listreviterobject *, PyObject *);
Raymond Hettingeref9bf402004-03-10 10:10:42 +00003227
Raymond Hettingerf5b64112008-12-02 21:33:45 +00003228static PyMethodDef listreviter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003229 {"__length_hint__", (PyCFunction)listreviter_len, METH_NOARGS, length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003230 {"__reduce__", (PyCFunction)listreviter_reduce, METH_NOARGS, reduce_doc},
3231 {"__setstate__", (PyCFunction)listreviter_setstate, METH_O, setstate_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003232 {NULL, NULL} /* sentinel */
Raymond Hettingeref9bf402004-03-10 10:10:42 +00003233};
3234
Raymond Hettinger1021c442003-11-07 15:38:09 +00003235PyTypeObject PyListRevIter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003236 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3237 "list_reverseiterator", /* tp_name */
3238 sizeof(listreviterobject), /* tp_basicsize */
3239 0, /* tp_itemsize */
3240 /* methods */
3241 (destructor)listreviter_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003242 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003243 0, /* tp_getattr */
3244 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003245 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003246 0, /* tp_repr */
3247 0, /* tp_as_number */
3248 0, /* tp_as_sequence */
3249 0, /* tp_as_mapping */
3250 0, /* tp_hash */
3251 0, /* tp_call */
3252 0, /* tp_str */
3253 PyObject_GenericGetAttr, /* tp_getattro */
3254 0, /* tp_setattro */
3255 0, /* tp_as_buffer */
3256 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3257 0, /* tp_doc */
3258 (traverseproc)listreviter_traverse, /* tp_traverse */
3259 0, /* tp_clear */
3260 0, /* tp_richcompare */
3261 0, /* tp_weaklistoffset */
3262 PyObject_SelfIter, /* tp_iter */
3263 (iternextfunc)listreviter_next, /* tp_iternext */
3264 listreviter_methods, /* tp_methods */
3265 0,
Raymond Hettinger1021c442003-11-07 15:38:09 +00003266};
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003267
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02003268/*[clinic input]
3269list.__reversed__
3270
3271Return a reverse iterator over the list.
3272[clinic start generated code]*/
3273
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003274static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02003275list___reversed___impl(PyListObject *self)
3276/*[clinic end generated code: output=b166f073208c888c input=eadb6e17f8a6a280]*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003277{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003278 listreviterobject *it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003280 it = PyObject_GC_New(listreviterobject, &PyListRevIter_Type);
3281 if (it == NULL)
3282 return NULL;
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02003283 assert(PyList_Check(self));
3284 it->it_index = PyList_GET_SIZE(self) - 1;
3285 Py_INCREF(self);
3286 it->it_seq = self;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003287 PyObject_GC_Track(it);
3288 return (PyObject *)it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003289}
3290
3291static void
3292listreviter_dealloc(listreviterobject *it)
3293{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003294 PyObject_GC_UnTrack(it);
3295 Py_XDECREF(it->it_seq);
3296 PyObject_GC_Del(it);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003297}
3298
3299static int
3300listreviter_traverse(listreviterobject *it, visitproc visit, void *arg)
3301{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003302 Py_VISIT(it->it_seq);
3303 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003304}
3305
3306static PyObject *
3307listreviter_next(listreviterobject *it)
3308{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003309 PyObject *item;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003310 Py_ssize_t index;
3311 PyListObject *seq;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003312
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003313 assert(it != NULL);
3314 seq = it->it_seq;
3315 if (seq == NULL) {
3316 return NULL;
3317 }
3318 assert(PyList_Check(seq));
3319
3320 index = it->it_index;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003321 if (index>=0 && index < PyList_GET_SIZE(seq)) {
3322 item = PyList_GET_ITEM(seq, index);
3323 it->it_index--;
3324 Py_INCREF(item);
3325 return item;
3326 }
3327 it->it_index = -1;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003328 it->it_seq = NULL;
3329 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003330 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003331}
3332
Raymond Hettingerf5b64112008-12-02 21:33:45 +00003333static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303334listreviter_len(listreviterobject *it, PyObject *Py_UNUSED(ignored))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003335{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003336 Py_ssize_t len = it->it_index + 1;
3337 if (it->it_seq == NULL || PyList_GET_SIZE(it->it_seq) < len)
3338 len = 0;
3339 return PyLong_FromSsize_t(len);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003340}
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003341
3342static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303343listreviter_reduce(listreviterobject *it, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003344{
3345 return listiter_reduce_general(it, 0);
3346}
3347
3348static PyObject *
3349listreviter_setstate(listreviterobject *it, PyObject *state)
3350{
3351 Py_ssize_t index = PyLong_AsSsize_t(state);
3352 if (index == -1 && PyErr_Occurred())
3353 return NULL;
3354 if (it->it_seq != NULL) {
3355 if (index < -1)
3356 index = -1;
3357 else if (index > PyList_GET_SIZE(it->it_seq) - 1)
3358 index = PyList_GET_SIZE(it->it_seq) - 1;
3359 it->it_index = index;
3360 }
3361 Py_RETURN_NONE;
3362}
3363
3364/* common pickling support */
3365
3366static PyObject *
3367listiter_reduce_general(void *_it, int forward)
3368{
Serhiy Storchakabb86bf42018-12-11 08:28:18 +02003369 _Py_IDENTIFIER(iter);
3370 _Py_IDENTIFIER(reversed);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003371 PyObject *list;
3372
3373 /* the objects are not the same, index is of different types! */
3374 if (forward) {
3375 listiterobject *it = (listiterobject *)_it;
3376 if (it->it_seq)
Serhiy Storchakabb86bf42018-12-11 08:28:18 +02003377 return Py_BuildValue("N(O)n", _PyEval_GetBuiltinId(&PyId_iter),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003378 it->it_seq, it->it_index);
3379 } else {
3380 listreviterobject *it = (listreviterobject *)_it;
3381 if (it->it_seq)
Serhiy Storchakabb86bf42018-12-11 08:28:18 +02003382 return Py_BuildValue("N(O)n", _PyEval_GetBuiltinId(&PyId_reversed),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003383 it->it_seq, it->it_index);
3384 }
3385 /* empty iterator, create an empty list */
3386 list = PyList_New(0);
3387 if (list == NULL)
3388 return NULL;
Serhiy Storchakabb86bf42018-12-11 08:28:18 +02003389 return Py_BuildValue("N(N)", _PyEval_GetBuiltinId(&PyId_iter), list);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003390}