blob: 533ee7436d31133e3ba3be94eb268560f18926fb [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* List object implementation */
2
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003#include "Python.h"
Victor Stinner384621c2020-06-22 17:27:35 +02004#include "pycore_abstract.h" // _PyIndex_Check()
5#include "pycore_interp.h" // PyInterpreterState.list
6#include "pycore_object.h" // _PyObject_GC_TRACK()
7#include "pycore_tuple.h" // _PyTuple_FromArray()
Guido van Rossumc0b618a1997-05-02 03:12:38 +00008
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00009#ifdef STDC_HEADERS
10#include <stddef.h>
11#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000012#include <sys/types.h> /* For size_t */
Guido van Rossum6cd2fe01994-08-29 12:45:32 +000013#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000014
Serhiy Storchakafdd42c42017-03-11 09:19:20 +020015/*[clinic input]
16class list "PyListObject *" "&PyList_Type"
17[clinic start generated code]*/
18/*[clinic end generated code: output=da39a3ee5e6b4b0d input=f9b222678f9f71e0]*/
19
20#include "clinic/listobject.c.h"
21
Victor Stinner522691c2020-06-23 16:40:40 +020022
23static struct _Py_list_state *
24get_list_state(void)
25{
26 PyInterpreterState *interp = _PyInterpreterState_GET();
27 return &interp->list;
28}
29
30
Tim Peters8d9eb102004-07-31 02:24:20 +000031/* Ensure ob_item has room for at least newsize elements, and set
32 * ob_size to newsize. If newsize > ob_size on entry, the content
33 * of the new slots at exit is undefined heap trash; it's the caller's
Ezio Melotti13925002011-03-16 11:05:33 +020034 * responsibility to overwrite them with sane values.
Tim Peters8d9eb102004-07-31 02:24:20 +000035 * The number of allocated elements may grow, shrink, or stay the same.
36 * Failure is impossible if newsize <= self.allocated on entry, although
37 * that partly relies on an assumption that the system realloc() never
38 * fails when passed a number of bytes <= the number of bytes last
39 * allocated (the C standard doesn't guarantee this, but it's hard to
40 * imagine a realloc implementation where it wouldn't be true).
41 * Note that self->ob_item may change, and even if newsize is less
42 * than ob_size on entry.
43 */
Guido van Rossuma46d51d1995-01-26 22:59:43 +000044static int
Martin v. Löwis18e16552006-02-15 17:27:45 +000045list_resize(PyListObject *self, Py_ssize_t newsize)
Guido van Rossuma46d51d1995-01-26 22:59:43 +000046{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000047 PyObject **items;
Xiang Zhang4cee0492017-02-22 12:32:30 +080048 size_t new_allocated, num_allocated_bytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000049 Py_ssize_t allocated = self->allocated;
Tim Peters65b8b842001-05-26 05:28:40 +000050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000051 /* Bypass realloc() when a previous overallocation is large enough
52 to accommodate the newsize. If the newsize falls lower than half
53 the allocated size, then proceed with the realloc() to shrink the list.
54 */
55 if (allocated >= newsize && newsize >= (allocated >> 1)) {
56 assert(self->ob_item != NULL || newsize == 0);
Victor Stinner60ac6ed2020-02-07 23:18:08 +010057 Py_SET_SIZE(self, newsize);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000058 return 0;
59 }
Raymond Hettinger4bb95402004-02-13 11:36:39 +000060
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000061 /* This over-allocates proportional to the list size, making room
62 * for additional growth. The over-allocation is mild, but is
63 * enough to give linear-time amortized behavior over a long
64 * sequence of appends() in the presence of a poorly-performing
65 * system realloc().
Serhiy Storchaka2fe815e2020-03-17 23:46:00 +020066 * Add padding to make the allocated size multiple of 4.
67 * The growth pattern is: 0, 4, 8, 16, 24, 32, 40, 52, 64, 76, ...
Xiang Zhang4cee0492017-02-22 12:32:30 +080068 * Note: new_allocated won't overflow because the largest possible value
69 * is PY_SSIZE_T_MAX * (9 / 8) + 6 which always fits in a size_t.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000070 */
Serhiy Storchaka2fe815e2020-03-17 23:46:00 +020071 new_allocated = ((size_t)newsize + (newsize >> 3) + 6) & ~(size_t)3;
Jeong Ukjae5b963702020-06-30 03:56:56 +090072 /* Do not overallocate if the new size is closer to overallocated size
Serhiy Storchaka2fe815e2020-03-17 23:46:00 +020073 * than to the old size.
74 */
75 if (newsize - Py_SIZE(self) > (Py_ssize_t)(new_allocated - newsize))
76 new_allocated = ((size_t)newsize + 3) & ~(size_t)3;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +000077
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000078 if (newsize == 0)
79 new_allocated = 0;
Xiang Zhang4cee0492017-02-22 12:32:30 +080080 num_allocated_bytes = new_allocated * sizeof(PyObject *);
81 items = (PyObject **)PyMem_Realloc(self->ob_item, num_allocated_bytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000082 if (items == NULL) {
83 PyErr_NoMemory();
84 return -1;
85 }
86 self->ob_item = items;
Victor Stinner60ac6ed2020-02-07 23:18:08 +010087 Py_SET_SIZE(self, newsize);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000088 self->allocated = new_allocated;
89 return 0;
Raymond Hettinger4bb95402004-02-13 11:36:39 +000090}
Guido van Rossuma46d51d1995-01-26 22:59:43 +000091
Pablo Galindo372d7052018-10-28 20:16:26 +000092static int
93list_preallocate_exact(PyListObject *self, Py_ssize_t size)
94{
95 assert(self->ob_item == NULL);
Sergey Fedoseev0e5f7712018-12-30 03:31:36 +050096 assert(size > 0);
Pablo Galindo372d7052018-10-28 20:16:26 +000097
Sergey Fedoseev0e5f7712018-12-30 03:31:36 +050098 PyObject **items = PyMem_New(PyObject*, size);
Pablo Galindo372d7052018-10-28 20:16:26 +000099 if (items == NULL) {
100 PyErr_NoMemory();
101 return -1;
102 }
103 self->ob_item = items;
Sergey Fedoseev0e5f7712018-12-30 03:31:36 +0500104 self->allocated = size;
Pablo Galindo372d7052018-10-28 20:16:26 +0000105 return 0;
106}
107
Victor Stinnerae00a5a2020-04-29 02:29:20 +0200108void
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100109_PyList_ClearFreeList(PyInterpreterState *interp)
Raymond Hettingerfb09f0e2004-10-07 03:58:07 +0000110{
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100111 struct _Py_list_state *state = &interp->list;
Victor Stinner88ec9192020-06-05 02:05:41 +0200112 while (state->numfree) {
113 PyListObject *op = state->free_list[--state->numfree];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000114 assert(PyList_CheckExact(op));
115 PyObject_GC_Del(op);
116 }
Antoine Pitrou9a812cb2011-11-15 00:00:12 +0100117}
118
119void
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100120_PyList_Fini(PyInterpreterState *interp)
Antoine Pitrou9a812cb2011-11-15 00:00:12 +0100121{
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100122 _PyList_ClearFreeList(interp);
Victor Stinnerbcb19832020-06-08 02:14:47 +0200123#ifdef Py_DEBUG
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100124 struct _Py_list_state *state = &interp->list;
Victor Stinnerbcb19832020-06-08 02:14:47 +0200125 state->numfree = -1;
126#endif
Raymond Hettingerfb09f0e2004-10-07 03:58:07 +0000127}
128
David Malcolm49526f42012-06-22 14:55:41 -0400129/* Print summary info about the state of the optimized allocator */
130void
131_PyList_DebugMallocStats(FILE *out)
132{
Victor Stinner522691c2020-06-23 16:40:40 +0200133 struct _Py_list_state *state = get_list_state();
David Malcolm49526f42012-06-22 14:55:41 -0400134 _PyDebugAllocatorStats(out,
135 "free PyListObject",
Victor Stinner88ec9192020-06-05 02:05:41 +0200136 state->numfree, sizeof(PyListObject));
David Malcolm49526f42012-06-22 14:55:41 -0400137}
138
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000139PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000140PyList_New(Py_ssize_t size)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000141{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000142 if (size < 0) {
143 PyErr_BadInternalCall();
144 return NULL;
145 }
Victor Stinner88ec9192020-06-05 02:05:41 +0200146
Victor Stinner522691c2020-06-23 16:40:40 +0200147 struct _Py_list_state *state = get_list_state();
Victor Stinner88ec9192020-06-05 02:05:41 +0200148 PyListObject *op;
Victor Stinnerbcb19832020-06-08 02:14:47 +0200149#ifdef Py_DEBUG
150 // PyList_New() must not be called after _PyList_Fini()
151 assert(state->numfree != -1);
152#endif
Victor Stinner88ec9192020-06-05 02:05:41 +0200153 if (state->numfree) {
154 state->numfree--;
155 op = state->free_list[state->numfree];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000156 _Py_NewReference((PyObject *)op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000157 }
Victor Stinner88ec9192020-06-05 02:05:41 +0200158 else {
159 op = PyObject_GC_New(PyListObject, &PyList_Type);
160 if (op == NULL) {
161 return NULL;
162 }
163 }
164 if (size <= 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000165 op->ob_item = NULL;
Victor Stinner88ec9192020-06-05 02:05:41 +0200166 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000167 else {
Mark Dickinson5d132382016-08-21 08:55:15 +0100168 op->ob_item = (PyObject **) PyMem_Calloc(size, sizeof(PyObject *));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000169 if (op->ob_item == NULL) {
170 Py_DECREF(op);
171 return PyErr_NoMemory();
172 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000173 }
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100174 Py_SET_SIZE(op, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175 op->allocated = size;
176 _PyObject_GC_TRACK(op);
177 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000178}
179
Sergey Fedoseev2fc46972018-08-11 18:12:07 +0500180static PyObject *
181list_new_prealloc(Py_ssize_t size)
182{
Miss Islington (bot)761c6412021-07-29 05:05:30 -0700183 assert(size > 0);
Sergey Fedoseev2fc46972018-08-11 18:12:07 +0500184 PyListObject *op = (PyListObject *) PyList_New(0);
Miss Islington (bot)761c6412021-07-29 05:05:30 -0700185 if (op == NULL) {
186 return NULL;
Sergey Fedoseev2fc46972018-08-11 18:12:07 +0500187 }
188 assert(op->ob_item == NULL);
189 op->ob_item = PyMem_New(PyObject *, size);
190 if (op->ob_item == NULL) {
191 Py_DECREF(op);
192 return PyErr_NoMemory();
193 }
194 op->allocated = size;
195 return (PyObject *) op;
196}
197
Martin v. Löwis18e16552006-02-15 17:27:45 +0000198Py_ssize_t
Fred Drakea2f55112000-07-09 15:16:51 +0000199PyList_Size(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000200{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000201 if (!PyList_Check(op)) {
202 PyErr_BadInternalCall();
203 return -1;
204 }
205 else
206 return Py_SIZE(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000207}
208
Raymond Hettingerf1aa8ae2018-10-10 20:37:28 -0700209static inline int
210valid_index(Py_ssize_t i, Py_ssize_t limit)
211{
212 /* The cast to size_t lets us use just a single comparison
213 to check whether i is in the range: 0 <= i < limit.
214
215 See: Section 14.2 "Bounds Checking" in the Agner Fog
216 optimization manual found at:
217 https://www.agner.org/optimize/optimizing_cpp.pdf
218 */
219 return (size_t) i < (size_t) limit;
220}
221
Raymond Hettingerfdfe6182004-05-05 06:28:16 +0000222static PyObject *indexerr = NULL;
Guido van Rossum929f1b81996-08-09 20:51:27 +0000223
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000224PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000225PyList_GetItem(PyObject *op, Py_ssize_t i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000226{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000227 if (!PyList_Check(op)) {
228 PyErr_BadInternalCall();
229 return NULL;
230 }
Raymond Hettingerf1aa8ae2018-10-10 20:37:28 -0700231 if (!valid_index(i, Py_SIZE(op))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000232 if (indexerr == NULL) {
233 indexerr = PyUnicode_FromString(
234 "list index out of range");
235 if (indexerr == NULL)
236 return NULL;
237 }
238 PyErr_SetObject(PyExc_IndexError, indexerr);
239 return NULL;
240 }
241 return ((PyListObject *)op) -> ob_item[i];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000242}
243
244int
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200245PyList_SetItem(PyObject *op, Py_ssize_t i,
246 PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000247{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200248 PyObject **p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000249 if (!PyList_Check(op)) {
250 Py_XDECREF(newitem);
251 PyErr_BadInternalCall();
252 return -1;
253 }
Raymond Hettingerf1aa8ae2018-10-10 20:37:28 -0700254 if (!valid_index(i, Py_SIZE(op))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000255 Py_XDECREF(newitem);
256 PyErr_SetString(PyExc_IndexError,
257 "list assignment index out of range");
258 return -1;
259 }
260 p = ((PyListObject *)op) -> ob_item + i;
Serhiy Storchakaec397562016-04-06 09:50:03 +0300261 Py_XSETREF(*p, newitem);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000262 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000263}
264
265static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000266ins1(PyListObject *self, Py_ssize_t where, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000267{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000268 Py_ssize_t i, n = Py_SIZE(self);
269 PyObject **items;
270 if (v == NULL) {
271 PyErr_BadInternalCall();
272 return -1;
273 }
Tim Petersb38e2b62004-07-29 02:29:26 +0000274
Sergey Fedoseeve682b262020-05-25 19:54:40 +0500275 assert((size_t)n + 1 < PY_SSIZE_T_MAX);
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800276 if (list_resize(self, n+1) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000277 return -1;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000279 if (where < 0) {
280 where += n;
281 if (where < 0)
282 where = 0;
283 }
284 if (where > n)
285 where = n;
286 items = self->ob_item;
287 for (i = n; --i >= where; )
288 items[i+1] = items[i];
289 Py_INCREF(v);
290 items[where] = v;
291 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000292}
293
294int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000295PyList_Insert(PyObject *op, Py_ssize_t where, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000296{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000297 if (!PyList_Check(op)) {
298 PyErr_BadInternalCall();
299 return -1;
300 }
301 return ins1((PyListObject *)op, where, newitem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000302}
303
Raymond Hettinger40a03822004-04-12 13:05:09 +0000304static int
305app1(PyListObject *self, PyObject *v)
306{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000307 Py_ssize_t n = PyList_GET_SIZE(self);
Raymond Hettinger40a03822004-04-12 13:05:09 +0000308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000309 assert (v != NULL);
Sergey Fedoseeve682b262020-05-25 19:54:40 +0500310 assert((size_t)n + 1 < PY_SSIZE_T_MAX);
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800311 if (list_resize(self, n+1) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000312 return -1;
Raymond Hettinger40a03822004-04-12 13:05:09 +0000313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000314 Py_INCREF(v);
315 PyList_SET_ITEM(self, n, v);
316 return 0;
Raymond Hettinger40a03822004-04-12 13:05:09 +0000317}
318
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000319int
Fred Drakea2f55112000-07-09 15:16:51 +0000320PyList_Append(PyObject *op, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000321{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000322 if (PyList_Check(op) && (newitem != NULL))
323 return app1((PyListObject *)op, newitem);
324 PyErr_BadInternalCall();
325 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000326}
327
328/* Methods */
329
330static void
Fred Drakea2f55112000-07-09 15:16:51 +0000331list_dealloc(PyListObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000332{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000333 Py_ssize_t i;
334 PyObject_GC_UnTrack(op);
Jeroen Demeyer351c6742019-05-10 19:21:11 +0200335 Py_TRASHCAN_BEGIN(op, list_dealloc)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000336 if (op->ob_item != NULL) {
337 /* Do it backwards, for Christian Tismer.
338 There's a simple test case where somehow this reduces
339 thrashing when a *very* large list is created and
340 immediately deleted. */
341 i = Py_SIZE(op);
342 while (--i >= 0) {
343 Py_XDECREF(op->ob_item[i]);
344 }
Victor Stinner00d7abd2020-12-01 09:56:42 +0100345 PyMem_Free(op->ob_item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000346 }
Victor Stinner522691c2020-06-23 16:40:40 +0200347 struct _Py_list_state *state = get_list_state();
Victor Stinnerbcb19832020-06-08 02:14:47 +0200348#ifdef Py_DEBUG
349 // list_dealloc() must not be called after _PyList_Fini()
350 assert(state->numfree != -1);
351#endif
Victor Stinner88ec9192020-06-05 02:05:41 +0200352 if (state->numfree < PyList_MAXFREELIST && PyList_CheckExact(op)) {
353 state->free_list[state->numfree++] = op;
354 }
355 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000356 Py_TYPE(op)->tp_free((PyObject *)op);
Victor Stinner88ec9192020-06-05 02:05:41 +0200357 }
Jeroen Demeyer351c6742019-05-10 19:21:11 +0200358 Py_TRASHCAN_END
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000359}
360
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000361static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000362list_repr(PyListObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000363{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000364 Py_ssize_t i;
Victor Stinner5c733472013-11-18 21:11:57 +0100365 PyObject *s;
Victor Stinner5c733472013-11-18 21:11:57 +0100366 _PyUnicodeWriter writer;
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200367
368 if (Py_SIZE(v) == 0) {
369 return PyUnicode_FromString("[]");
370 }
371
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000372 i = Py_ReprEnter((PyObject*)v);
373 if (i != 0) {
374 return i > 0 ? PyUnicode_FromString("[...]") : NULL;
375 }
Tim Petersa7259592001-06-16 05:11:17 +0000376
Victor Stinner5c733472013-11-18 21:11:57 +0100377 _PyUnicodeWriter_Init(&writer);
378 writer.overallocate = 1;
Victor Stinnerb8fb1972013-11-18 22:15:44 +0100379 /* "[" + "1" + ", 2" * (len - 1) + "]" */
380 writer.min_length = 1 + 1 + (2 + 1) * (Py_SIZE(v) - 1) + 1;
Tim Petersa7259592001-06-16 05:11:17 +0000381
Victor Stinner5c733472013-11-18 21:11:57 +0100382 if (_PyUnicodeWriter_WriteChar(&writer, '[') < 0)
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200383 goto error;
Tim Petersa7259592001-06-16 05:11:17 +0000384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000385 /* Do repr() on each element. Note that this may mutate the list,
386 so must refetch the list size on each iteration. */
387 for (i = 0; i < Py_SIZE(v); ++i) {
Victor Stinner5c733472013-11-18 21:11:57 +0100388 if (i > 0) {
Victor Stinner4a587072013-11-19 12:54:53 +0100389 if (_PyUnicodeWriter_WriteASCIIString(&writer, ", ", 2) < 0)
Victor Stinner5c733472013-11-18 21:11:57 +0100390 goto error;
391 }
392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000393 s = PyObject_Repr(v->ob_item[i]);
Victor Stinner5c733472013-11-18 21:11:57 +0100394 if (s == NULL)
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200395 goto error;
Victor Stinner5c733472013-11-18 21:11:57 +0100396
397 if (_PyUnicodeWriter_WriteStr(&writer, s) < 0) {
398 Py_DECREF(s);
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200399 goto error;
Victor Stinner5c733472013-11-18 21:11:57 +0100400 }
401 Py_DECREF(s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000402 }
Victor Stinner5c733472013-11-18 21:11:57 +0100403
Victor Stinner4d3f1092013-11-19 12:09:00 +0100404 writer.overallocate = 0;
Victor Stinner5c733472013-11-18 21:11:57 +0100405 if (_PyUnicodeWriter_WriteChar(&writer, ']') < 0)
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200406 goto error;
Tim Petersa7259592001-06-16 05:11:17 +0000407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000408 Py_ReprLeave((PyObject *)v);
Victor Stinner5c733472013-11-18 21:11:57 +0100409 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200410
411error:
Victor Stinner5c733472013-11-18 21:11:57 +0100412 _PyUnicodeWriter_Dealloc(&writer);
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200413 Py_ReprLeave((PyObject *)v);
414 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000415}
416
Martin v. Löwis18e16552006-02-15 17:27:45 +0000417static Py_ssize_t
Fred Drakea2f55112000-07-09 15:16:51 +0000418list_length(PyListObject *a)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000419{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 return Py_SIZE(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000421}
422
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000423static int
Fred Drakea2f55112000-07-09 15:16:51 +0000424list_contains(PyListObject *a, PyObject *el)
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000425{
Dong-hee Na4dbf2d82020-01-28 00:02:23 +0900426 PyObject *item;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000427 Py_ssize_t i;
428 int cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000429
Dong-hee Na4dbf2d82020-01-28 00:02:23 +0900430 for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(a); ++i) {
431 item = PyList_GET_ITEM(a, i);
432 Py_INCREF(item);
Dong-hee Na9e1ed512020-01-28 02:04:25 +0900433 cmp = PyObject_RichCompareBool(item, el, Py_EQ);
Dong-hee Na4dbf2d82020-01-28 00:02:23 +0900434 Py_DECREF(item);
435 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000436 return cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000437}
438
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000439static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000440list_item(PyListObject *a, Py_ssize_t i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000441{
Raymond Hettingerf1aa8ae2018-10-10 20:37:28 -0700442 if (!valid_index(i, Py_SIZE(a))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000443 if (indexerr == NULL) {
444 indexerr = PyUnicode_FromString(
445 "list index out of range");
446 if (indexerr == NULL)
447 return NULL;
448 }
449 PyErr_SetObject(PyExc_IndexError, indexerr);
450 return NULL;
451 }
452 Py_INCREF(a->ob_item[i]);
453 return a->ob_item[i];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000454}
455
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000456static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000457list_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000458{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000459 PyListObject *np;
460 PyObject **src, **dest;
461 Py_ssize_t i, len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000462 len = ihigh - ilow;
Miss Islington (bot)761c6412021-07-29 05:05:30 -0700463 if (len <= 0) {
464 return PyList_New(0);
465 }
Sergey Fedoseev2fc46972018-08-11 18:12:07 +0500466 np = (PyListObject *) list_new_prealloc(len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000467 if (np == NULL)
468 return NULL;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000470 src = a->ob_item + ilow;
471 dest = np->ob_item;
472 for (i = 0; i < len; i++) {
473 PyObject *v = src[i];
474 Py_INCREF(v);
475 dest[i] = v;
476 }
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100477 Py_SET_SIZE(np, len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000479}
480
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000481PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000482PyList_GetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum234f9421993-06-17 12:35:49 +0000483{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 if (!PyList_Check(a)) {
485 PyErr_BadInternalCall();
486 return NULL;
487 }
Sergey Fedoseevef1b88b2019-02-21 11:51:52 +0500488 if (ilow < 0) {
489 ilow = 0;
490 }
491 else if (ilow > Py_SIZE(a)) {
492 ilow = Py_SIZE(a);
493 }
494 if (ihigh < ilow) {
495 ihigh = ilow;
496 }
497 else if (ihigh > Py_SIZE(a)) {
498 ihigh = Py_SIZE(a);
499 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 return list_slice((PyListObject *)a, ilow, ihigh);
Guido van Rossum234f9421993-06-17 12:35:49 +0000501}
502
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000503static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000504list_concat(PyListObject *a, PyObject *bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000505{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 Py_ssize_t size;
507 Py_ssize_t i;
508 PyObject **src, **dest;
509 PyListObject *np;
510 if (!PyList_Check(bb)) {
511 PyErr_Format(PyExc_TypeError,
512 "can only concatenate list (not \"%.200s\") to list",
Victor Stinner58ac7002020-02-07 03:04:21 +0100513 Py_TYPE(bb)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000514 return NULL;
515 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000516#define b ((PyListObject *)bb)
Sergey Fedoseeve682b262020-05-25 19:54:40 +0500517 assert((size_t)Py_SIZE(a) + (size_t)Py_SIZE(b) < PY_SSIZE_T_MAX);
Martin Panterb93d8632016-07-25 02:39:20 +0000518 size = Py_SIZE(a) + Py_SIZE(b);
Miss Islington (bot)761c6412021-07-29 05:05:30 -0700519 if (size == 0) {
520 return PyList_New(0);
521 }
Sergey Fedoseev2fc46972018-08-11 18:12:07 +0500522 np = (PyListObject *) list_new_prealloc(size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000523 if (np == NULL) {
524 return NULL;
525 }
526 src = a->ob_item;
527 dest = np->ob_item;
528 for (i = 0; i < Py_SIZE(a); i++) {
529 PyObject *v = src[i];
530 Py_INCREF(v);
531 dest[i] = v;
532 }
533 src = b->ob_item;
534 dest = np->ob_item + Py_SIZE(a);
535 for (i = 0; i < Py_SIZE(b); i++) {
536 PyObject *v = src[i];
537 Py_INCREF(v);
538 dest[i] = v;
539 }
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100540 Py_SET_SIZE(np, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000541 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000542#undef b
543}
544
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000545static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000546list_repeat(PyListObject *a, Py_ssize_t n)
Guido van Rossumed98d481991-03-06 13:07:53 +0000547{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000548 Py_ssize_t i, j;
549 Py_ssize_t size;
550 PyListObject *np;
551 PyObject **p, **items;
552 PyObject *elem;
553 if (n < 0)
554 n = 0;
Mark Dickinsonc0420fd2011-09-19 19:18:37 +0100555 if (n > 0 && Py_SIZE(a) > PY_SSIZE_T_MAX / n)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000556 return PyErr_NoMemory();
Mark Dickinsonc0420fd2011-09-19 19:18:37 +0100557 size = Py_SIZE(a) * n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000558 if (size == 0)
559 return PyList_New(0);
Sergey Fedoseev2fc46972018-08-11 18:12:07 +0500560 np = (PyListObject *) list_new_prealloc(size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561 if (np == NULL)
562 return NULL;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000564 if (Py_SIZE(a) == 1) {
Sergey Fedoseev2fc46972018-08-11 18:12:07 +0500565 items = np->ob_item;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000566 elem = a->ob_item[0];
567 for (i = 0; i < n; i++) {
568 items[i] = elem;
569 Py_INCREF(elem);
570 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000571 }
Sergey Fedoseev2fc46972018-08-11 18:12:07 +0500572 else {
573 p = np->ob_item;
574 items = a->ob_item;
575 for (i = 0; i < n; i++) {
576 for (j = 0; j < Py_SIZE(a); j++) {
577 *p = items[j];
578 Py_INCREF(*p);
579 p++;
580 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000581 }
582 }
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100583 Py_SET_SIZE(np, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000584 return (PyObject *) np;
Guido van Rossumed98d481991-03-06 13:07:53 +0000585}
586
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000587static int
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200588_list_clear(PyListObject *a)
Armin Rigo93677f02004-07-29 12:40:23 +0000589{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000590 Py_ssize_t i;
591 PyObject **item = a->ob_item;
592 if (item != NULL) {
593 /* Because XDECREF can recursively invoke operations on
594 this list, we make it empty first. */
595 i = Py_SIZE(a);
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100596 Py_SET_SIZE(a, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000597 a->ob_item = NULL;
598 a->allocated = 0;
599 while (--i >= 0) {
600 Py_XDECREF(item[i]);
601 }
Victor Stinner00d7abd2020-12-01 09:56:42 +0100602 PyMem_Free(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000603 }
604 /* Never fails; the return value can be ignored.
605 Note that there is no guarantee that the list is actually empty
606 at this point, because XDECREF may have populated it again! */
607 return 0;
Armin Rigo93677f02004-07-29 12:40:23 +0000608}
609
Tim Peters8fc4a912004-07-31 21:53:19 +0000610/* a[ilow:ihigh] = v if v != NULL.
611 * del a[ilow:ihigh] if v == NULL.
612 *
613 * Special speed gimmick: when v is NULL and ihigh - ilow <= 8, it's
614 * guaranteed the call cannot fail.
615 */
Armin Rigo93677f02004-07-29 12:40:23 +0000616static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000617list_ass_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000618{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 /* Because [X]DECREF can recursively invoke list operations on
620 this list, we must postpone all [X]DECREF activity until
621 after the list is back in its canonical shape. Therefore
622 we must allocate an additional array, 'recycle', into which
623 we temporarily copy the items that are deleted from the
624 list. :-( */
625 PyObject *recycle_on_stack[8];
626 PyObject **recycle = recycle_on_stack; /* will allocate more if needed */
627 PyObject **item;
628 PyObject **vitem = NULL;
629 PyObject *v_as_SF = NULL; /* PySequence_Fast(v) */
630 Py_ssize_t n; /* # of elements in replacement list */
631 Py_ssize_t norig; /* # of elements in list getting replaced */
632 Py_ssize_t d; /* Change in size */
633 Py_ssize_t k;
634 size_t s;
635 int result = -1; /* guilty until proved innocent */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000636#define b ((PyListObject *)v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000637 if (v == NULL)
638 n = 0;
639 else {
640 if (a == b) {
641 /* Special case "a[i:j] = a" -- copy b first */
642 v = list_slice(b, 0, Py_SIZE(b));
643 if (v == NULL)
644 return result;
645 result = list_ass_slice(a, ilow, ihigh, v);
646 Py_DECREF(v);
647 return result;
648 }
649 v_as_SF = PySequence_Fast(v, "can only assign an iterable");
650 if(v_as_SF == NULL)
651 goto Error;
652 n = PySequence_Fast_GET_SIZE(v_as_SF);
653 vitem = PySequence_Fast_ITEMS(v_as_SF);
654 }
655 if (ilow < 0)
656 ilow = 0;
657 else if (ilow > Py_SIZE(a))
658 ilow = Py_SIZE(a);
Tim Peters8d9eb102004-07-31 02:24:20 +0000659
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000660 if (ihigh < ilow)
661 ihigh = ilow;
662 else if (ihigh > Py_SIZE(a))
663 ihigh = Py_SIZE(a);
Armin Rigo93677f02004-07-29 12:40:23 +0000664
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000665 norig = ihigh - ilow;
666 assert(norig >= 0);
667 d = n - norig;
668 if (Py_SIZE(a) + d == 0) {
669 Py_XDECREF(v_as_SF);
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200670 return _list_clear(a);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000671 }
672 item = a->ob_item;
673 /* recycle the items that we are about to remove */
674 s = norig * sizeof(PyObject *);
Benjamin Peterson5a7d9232016-09-06 17:58:25 -0700675 /* If norig == 0, item might be NULL, in which case we may not memcpy from it. */
676 if (s) {
677 if (s > sizeof(recycle_on_stack)) {
Victor Stinner00d7abd2020-12-01 09:56:42 +0100678 recycle = (PyObject **)PyMem_Malloc(s);
Benjamin Peterson5a7d9232016-09-06 17:58:25 -0700679 if (recycle == NULL) {
680 PyErr_NoMemory();
681 goto Error;
682 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000683 }
Benjamin Peterson5a7d9232016-09-06 17:58:25 -0700684 memcpy(recycle, &item[ilow], s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000685 }
Tim Peters8d9eb102004-07-31 02:24:20 +0000686
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000687 if (d < 0) { /* Delete -d items */
Victor Stinner2c40f642013-07-19 23:06:21 +0200688 Py_ssize_t tail;
689 tail = (Py_SIZE(a) - ihigh) * sizeof(PyObject *);
690 memmove(&item[ihigh+d], &item[ihigh], tail);
691 if (list_resize(a, Py_SIZE(a) + d) < 0) {
692 memmove(&item[ihigh], &item[ihigh+d], tail);
693 memcpy(&item[ilow], recycle, s);
694 goto Error;
695 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000696 item = a->ob_item;
697 }
698 else if (d > 0) { /* Insert d items */
699 k = Py_SIZE(a);
700 if (list_resize(a, k+d) < 0)
701 goto Error;
702 item = a->ob_item;
703 memmove(&item[ihigh+d], &item[ihigh],
704 (k - ihigh)*sizeof(PyObject *));
705 }
706 for (k = 0; k < n; k++, ilow++) {
707 PyObject *w = vitem[k];
708 Py_XINCREF(w);
709 item[ilow] = w;
710 }
711 for (k = norig - 1; k >= 0; --k)
712 Py_XDECREF(recycle[k]);
713 result = 0;
Tim Peters8d9eb102004-07-31 02:24:20 +0000714 Error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 if (recycle != recycle_on_stack)
Victor Stinner00d7abd2020-12-01 09:56:42 +0100716 PyMem_Free(recycle);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000717 Py_XDECREF(v_as_SF);
718 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000719#undef b
720}
721
Guido van Rossum234f9421993-06-17 12:35:49 +0000722int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000723PyList_SetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum234f9421993-06-17 12:35:49 +0000724{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000725 if (!PyList_Check(a)) {
726 PyErr_BadInternalCall();
727 return -1;
728 }
729 return list_ass_slice((PyListObject *)a, ilow, ihigh, v);
Guido van Rossum234f9421993-06-17 12:35:49 +0000730}
731
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000732static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000733list_inplace_repeat(PyListObject *self, Py_ssize_t n)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000734{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000735 PyObject **items;
736 Py_ssize_t size, i, j, p;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000737
738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 size = PyList_GET_SIZE(self);
740 if (size == 0 || n == 1) {
741 Py_INCREF(self);
742 return (PyObject *)self;
743 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000744
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000745 if (n < 1) {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200746 (void)_list_clear(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000747 Py_INCREF(self);
748 return (PyObject *)self;
749 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000750
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000751 if (size > PY_SSIZE_T_MAX / n) {
752 return PyErr_NoMemory();
753 }
Christian Heimesaf98da12008-01-27 15:18:18 +0000754
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800755 if (list_resize(self, size*n) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 return NULL;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 p = size;
759 items = self->ob_item;
760 for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */
761 for (j = 0; j < size; j++) {
762 PyObject *o = items[j];
763 Py_INCREF(o);
764 items[p++] = o;
765 }
766 }
767 Py_INCREF(self);
768 return (PyObject *)self;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000769}
770
Guido van Rossum4a450d01991-04-03 19:05:18 +0000771static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000772list_ass_item(PyListObject *a, Py_ssize_t i, PyObject *v)
Guido van Rossum4a450d01991-04-03 19:05:18 +0000773{
Raymond Hettingerf1aa8ae2018-10-10 20:37:28 -0700774 if (!valid_index(i, Py_SIZE(a))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000775 PyErr_SetString(PyExc_IndexError,
776 "list assignment index out of range");
777 return -1;
778 }
779 if (v == NULL)
780 return list_ass_slice(a, i, i+1, v);
781 Py_INCREF(v);
Serhiy Storchakaf01e4082016-04-10 18:12:01 +0300782 Py_SETREF(a->ob_item[i], v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000783 return 0;
Guido van Rossum4a450d01991-04-03 19:05:18 +0000784}
785
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200786/*[clinic input]
787list.insert
788
789 index: Py_ssize_t
790 object: object
791 /
792
793Insert object before index.
794[clinic start generated code]*/
795
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000796static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200797list_insert_impl(PyListObject *self, Py_ssize_t index, PyObject *object)
798/*[clinic end generated code: output=7f35e32f60c8cb78 input=858514cf894c7eab]*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000799{
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200800 if (ins1(self, index, object) == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000801 Py_RETURN_NONE;
802 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000803}
804
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200805/*[clinic input]
806list.clear
807
808Remove all items from list.
809[clinic start generated code]*/
810
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000811static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200812list_clear_impl(PyListObject *self)
813/*[clinic end generated code: output=67a1896c01f74362 input=ca3c1646856742f6]*/
Eli Benderskycbbaa962011-02-25 05:47:53 +0000814{
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200815 _list_clear(self);
Eli Benderskycbbaa962011-02-25 05:47:53 +0000816 Py_RETURN_NONE;
817}
818
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200819/*[clinic input]
820list.copy
821
822Return a shallow copy of the list.
823[clinic start generated code]*/
824
Eli Benderskycbbaa962011-02-25 05:47:53 +0000825static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200826list_copy_impl(PyListObject *self)
827/*[clinic end generated code: output=ec6b72d6209d418e input=6453ab159e84771f]*/
Eli Benderskycbbaa962011-02-25 05:47:53 +0000828{
829 return list_slice(self, 0, Py_SIZE(self));
830}
831
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200832/*[clinic input]
833list.append
834
835 object: object
836 /
837
838Append object to the end of the list.
839[clinic start generated code]*/
840
Eli Benderskycbbaa962011-02-25 05:47:53 +0000841static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200842list_append(PyListObject *self, PyObject *object)
843/*[clinic end generated code: output=7c096003a29c0eae input=43a3fe48a7066e91]*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000844{
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200845 if (app1(self, object) == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000846 Py_RETURN_NONE;
847 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000848}
849
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200850/*[clinic input]
851list.extend
852
853 iterable: object
854 /
855
856Extend list by appending elements from the iterable.
857[clinic start generated code]*/
858
Barry Warsawdedf6d61998-10-09 16:37:25 +0000859static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200860list_extend(PyListObject *self, PyObject *iterable)
861/*[clinic end generated code: output=630fb3bca0c8e789 input=9ec5ba3a81be3a4d]*/
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000862{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000863 PyObject *it; /* iter(v) */
864 Py_ssize_t m; /* size of self */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200865 Py_ssize_t n; /* guess for size of iterable */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 Py_ssize_t mn; /* m + n */
867 Py_ssize_t i;
868 PyObject *(*iternext)(PyObject *);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000870 /* Special cases:
871 1) lists and tuples which can use PySequence_Fast ops
872 2) extending self to self requires making a copy first
873 */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200874 if (PyList_CheckExact(iterable) || PyTuple_CheckExact(iterable) ||
875 (PyObject *)self == iterable) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000876 PyObject **src, **dest;
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200877 iterable = PySequence_Fast(iterable, "argument must be iterable");
878 if (!iterable)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000879 return NULL;
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200880 n = PySequence_Fast_GET_SIZE(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 if (n == 0) {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200882 /* short circuit when iterable is empty */
883 Py_DECREF(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000884 Py_RETURN_NONE;
885 }
886 m = Py_SIZE(self);
Martin Panter94b39ce2017-01-14 06:30:37 +0000887 /* It should not be possible to allocate a list large enough to cause
888 an overflow on any relevant platform */
889 assert(m < PY_SSIZE_T_MAX - n);
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800890 if (list_resize(self, m + n) < 0) {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200891 Py_DECREF(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000892 return NULL;
893 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200894 /* note that we may still have self == iterable here for the
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000895 * situation a.extend(a), but the following code works
896 * in that case too. Just make sure to resize self
897 * before calling PySequence_Fast_ITEMS.
898 */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200899 /* populate the end of self with iterable's items */
900 src = PySequence_Fast_ITEMS(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000901 dest = self->ob_item + m;
902 for (i = 0; i < n; i++) {
903 PyObject *o = src[i];
904 Py_INCREF(o);
905 dest[i] = o;
906 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200907 Py_DECREF(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000908 Py_RETURN_NONE;
909 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000910
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200911 it = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000912 if (it == NULL)
913 return NULL;
Victor Stinner58ac7002020-02-07 03:04:21 +0100914 iternext = *Py_TYPE(it)->tp_iternext;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 /* Guess a result list size. */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200917 n = PyObject_LengthHint(iterable, 8);
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800918 if (n < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000919 Py_DECREF(it);
920 return NULL;
921 }
922 m = Py_SIZE(self);
Martin Panterb93d8632016-07-25 02:39:20 +0000923 if (m > PY_SSIZE_T_MAX - n) {
924 /* m + n overflowed; on the chance that n lied, and there really
925 * is enough room, ignore it. If n was telling the truth, we'll
926 * eventually run out of memory during the loop.
927 */
928 }
929 else {
930 mn = m + n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 /* Make room. */
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800932 if (list_resize(self, mn) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933 goto error;
934 /* Make the list sane again. */
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100935 Py_SET_SIZE(self, m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 /* Run iterator to exhaustion. */
939 for (;;) {
940 PyObject *item = iternext(it);
941 if (item == NULL) {
942 if (PyErr_Occurred()) {
943 if (PyErr_ExceptionMatches(PyExc_StopIteration))
944 PyErr_Clear();
945 else
946 goto error;
947 }
948 break;
949 }
950 if (Py_SIZE(self) < self->allocated) {
951 /* steals ref */
952 PyList_SET_ITEM(self, Py_SIZE(self), item);
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100953 Py_SET_SIZE(self, Py_SIZE(self) + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000954 }
955 else {
956 int status = app1(self, item);
957 Py_DECREF(item); /* append creates a new ref */
958 if (status < 0)
959 goto error;
960 }
961 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000962
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000963 /* Cut back result list if initial guess was too large. */
Victor Stinner32fd6ea2013-07-16 21:45:58 +0200964 if (Py_SIZE(self) < self->allocated) {
965 if (list_resize(self, Py_SIZE(self)) < 0)
966 goto error;
967 }
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 Py_DECREF(it);
970 Py_RETURN_NONE;
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000971
972 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000973 Py_DECREF(it);
974 return NULL;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000975}
976
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000977PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200978_PyList_Extend(PyListObject *self, PyObject *iterable)
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000979{
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200980 return list_extend(self, iterable);
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000981}
982
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000983static PyObject *
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000984list_inplace_concat(PyListObject *self, PyObject *other)
985{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 PyObject *result;
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000987
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200988 result = list_extend(self, other);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000989 if (result == NULL)
990 return result;
991 Py_DECREF(result);
992 Py_INCREF(self);
993 return (PyObject *)self;
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000994}
995
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200996/*[clinic input]
997list.pop
998
999 index: Py_ssize_t = -1
1000 /
1001
1002Remove and return item at index (default last).
1003
1004Raises IndexError if list is empty or index is out of range.
1005[clinic start generated code]*/
1006
Raymond Hettinger97bc6182004-03-11 07:34:19 +00001007static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02001008list_pop_impl(PyListObject *self, Py_ssize_t index)
1009/*[clinic end generated code: output=6bd69dcb3f17eca8 input=b83675976f329e6f]*/
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +00001010{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001011 PyObject *v;
1012 int status;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +00001013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 if (Py_SIZE(self) == 0) {
1015 /* Special-case most common failure cause */
1016 PyErr_SetString(PyExc_IndexError, "pop from empty list");
1017 return NULL;
1018 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02001019 if (index < 0)
1020 index += Py_SIZE(self);
Raymond Hettingerf1aa8ae2018-10-10 20:37:28 -07001021 if (!valid_index(index, Py_SIZE(self))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001022 PyErr_SetString(PyExc_IndexError, "pop index out of range");
1023 return NULL;
1024 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02001025 v = self->ob_item[index];
1026 if (index == Py_SIZE(self) - 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 status = list_resize(self, Py_SIZE(self) - 1);
Victor Stinnerb27cd3e2013-07-08 22:20:44 +02001028 if (status >= 0)
1029 return v; /* and v now owns the reference the list had */
1030 else
1031 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001032 }
1033 Py_INCREF(v);
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02001034 status = list_ass_slice(self, index, index+1, (PyObject *)NULL);
Victor Stinner095d99f2013-07-17 21:58:01 +02001035 if (status < 0) {
1036 Py_DECREF(v);
1037 return NULL;
1038 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039 return v;
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +00001040}
1041
Tim Peters8e2e7ca2002-07-19 02:33:08 +00001042/* Reverse a slice of a list in place, from lo up to (exclusive) hi. */
1043static void
1044reverse_slice(PyObject **lo, PyObject **hi)
1045{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 assert(lo && hi);
Tim Peters8e2e7ca2002-07-19 02:33:08 +00001047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 --hi;
1049 while (lo < hi) {
1050 PyObject *t = *lo;
1051 *lo = *hi;
1052 *hi = t;
1053 ++lo;
1054 --hi;
1055 }
Tim Peters8e2e7ca2002-07-19 02:33:08 +00001056}
1057
Tim Petersa64dc242002-08-01 02:13:36 +00001058/* Lots of code for an adaptive, stable, natural mergesort. There are many
1059 * pieces to this algorithm; read listsort.txt for overviews and details.
1060 */
Guido van Rossum3f236de1996-12-10 23:55:39 +00001061
Daniel Stutzbach98338222010-12-02 21:55:33 +00001062/* A sortslice contains a pointer to an array of keys and a pointer to
1063 * an array of corresponding values. In other words, keys[i]
1064 * corresponds with values[i]. If values == NULL, then the keys are
1065 * also the values.
1066 *
1067 * Several convenience routines are provided here, so that keys and
1068 * values are always moved in sync.
1069 */
1070
1071typedef struct {
1072 PyObject **keys;
1073 PyObject **values;
1074} sortslice;
1075
1076Py_LOCAL_INLINE(void)
1077sortslice_copy(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j)
1078{
1079 s1->keys[i] = s2->keys[j];
1080 if (s1->values != NULL)
1081 s1->values[i] = s2->values[j];
1082}
1083
1084Py_LOCAL_INLINE(void)
Benjamin Peterson9efdcca2010-12-03 01:44:10 +00001085sortslice_copy_incr(sortslice *dst, sortslice *src)
1086{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001087 *dst->keys++ = *src->keys++;
1088 if (dst->values != NULL)
1089 *dst->values++ = *src->values++;
1090}
1091
1092Py_LOCAL_INLINE(void)
Benjamin Peterson9efdcca2010-12-03 01:44:10 +00001093sortslice_copy_decr(sortslice *dst, sortslice *src)
1094{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001095 *dst->keys-- = *src->keys--;
1096 if (dst->values != NULL)
1097 *dst->values-- = *src->values--;
1098}
1099
1100
1101Py_LOCAL_INLINE(void)
1102sortslice_memcpy(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j,
Benjamin Peterson9efdcca2010-12-03 01:44:10 +00001103 Py_ssize_t n)
1104{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001105 memcpy(&s1->keys[i], &s2->keys[j], sizeof(PyObject *) * n);
1106 if (s1->values != NULL)
1107 memcpy(&s1->values[i], &s2->values[j], sizeof(PyObject *) * n);
1108}
1109
1110Py_LOCAL_INLINE(void)
1111sortslice_memmove(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j,
Benjamin Peterson9efdcca2010-12-03 01:44:10 +00001112 Py_ssize_t n)
1113{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001114 memmove(&s1->keys[i], &s2->keys[j], sizeof(PyObject *) * n);
1115 if (s1->values != NULL)
1116 memmove(&s1->values[i], &s2->values[j], sizeof(PyObject *) * n);
1117}
1118
1119Py_LOCAL_INLINE(void)
Benjamin Peterson9efdcca2010-12-03 01:44:10 +00001120sortslice_advance(sortslice *slice, Py_ssize_t n)
1121{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001122 slice->keys += n;
1123 if (slice->values != NULL)
1124 slice->values += n;
1125}
1126
embg1e34da42018-01-28 20:03:23 -07001127/* Comparison function: ms->key_compare, which is set at run-time in
1128 * listsort_impl to optimize for various special cases.
Tim Petersa64dc242002-08-01 02:13:36 +00001129 * Returns -1 on error, 1 if x < y, 0 if x >= y.
1130 */
Guido van Rossum3f236de1996-12-10 23:55:39 +00001131
embg1e34da42018-01-28 20:03:23 -07001132#define ISLT(X, Y) (*(ms->key_compare))(X, Y, ms)
Tim Peters66860f62002-08-04 17:47:26 +00001133
1134/* Compare X to Y via "<". Goto "fail" if the comparison raises an
Tim Petersa8c974c2002-07-19 03:30:57 +00001135 error. Else "k" is set to true iff X<Y, and an "if (k)" block is
1136 started. It makes more sense in context <wink>. X and Y are PyObject*s.
1137*/
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001138#define IFLT(X, Y) if ((k = ISLT(X, Y)) < 0) goto fail; \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001139 if (k)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001140
embg1e34da42018-01-28 20:03:23 -07001141/* The maximum number of entries in a MergeState's pending-runs stack.
1142 * This is enough to sort arrays of size up to about
1143 * 32 * phi ** MAX_MERGE_PENDING
1144 * where phi ~= 1.618. 85 is ridiculouslylarge enough, good for an array
1145 * with 2**64 elements.
1146 */
1147#define MAX_MERGE_PENDING 85
1148
1149/* When we get into galloping mode, we stay there until both runs win less
1150 * often than MIN_GALLOP consecutive times. See listsort.txt for more info.
1151 */
1152#define MIN_GALLOP 7
1153
1154/* Avoid malloc for small temp arrays. */
1155#define MERGESTATE_TEMP_SIZE 256
1156
1157/* One MergeState exists on the stack per invocation of mergesort. It's just
1158 * a convenient way to pass state around among the helper functions.
1159 */
1160struct s_slice {
1161 sortslice base;
1162 Py_ssize_t len;
1163};
1164
1165typedef struct s_MergeState MergeState;
1166struct s_MergeState {
1167 /* This controls when we get *into* galloping mode. It's initialized
1168 * to MIN_GALLOP. merge_lo and merge_hi tend to nudge it higher for
1169 * random data, and lower for highly structured data.
1170 */
1171 Py_ssize_t min_gallop;
1172
1173 /* 'a' is temp storage to help with merges. It contains room for
1174 * alloced entries.
1175 */
1176 sortslice a; /* may point to temparray below */
1177 Py_ssize_t alloced;
1178
1179 /* A stack of n pending runs yet to be merged. Run #i starts at
1180 * address base[i] and extends for len[i] elements. It's always
1181 * true (so long as the indices are in bounds) that
1182 *
1183 * pending[i].base + pending[i].len == pending[i+1].base
1184 *
1185 * so we could cut the storage for this, but it's a minor amount,
1186 * and keeping all the info explicit simplifies the code.
1187 */
1188 int n;
1189 struct s_slice pending[MAX_MERGE_PENDING];
1190
1191 /* 'a' points to this when possible, rather than muck with malloc. */
1192 PyObject *temparray[MERGESTATE_TEMP_SIZE];
1193
1194 /* This is the function we will use to compare two keys,
1195 * even when none of our special cases apply and we have to use
1196 * safe_object_compare. */
1197 int (*key_compare)(PyObject *, PyObject *, MergeState *);
1198
1199 /* This function is used by unsafe_object_compare to optimize comparisons
1200 * when we know our list is type-homogeneous but we can't assume anything else.
Victor Stinner58ac7002020-02-07 03:04:21 +01001201 * In the pre-sort check it is set equal to Py_TYPE(key)->tp_richcompare */
embg1e34da42018-01-28 20:03:23 -07001202 PyObject *(*key_richcompare)(PyObject *, PyObject *, int);
1203
1204 /* This function is used by unsafe_tuple_compare to compare the first elements
1205 * of tuples. It may be set to safe_object_compare, but the idea is that hopefully
1206 * we can assume more, and use one of the special-case compares. */
1207 int (*tuple_elem_compare)(PyObject *, PyObject *, MergeState *);
1208};
1209
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001210/* binarysort is the best method for sorting small arrays: it does
1211 few compares, but can do data movement quadratic in the number of
1212 elements.
Guido van Rossum42812581998-06-17 14:15:44 +00001213 [lo, hi) is a contiguous slice of a list, and is sorted via
Tim Petersa8c974c2002-07-19 03:30:57 +00001214 binary insertion. This sort is stable.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001215 On entry, must have lo <= start <= hi, and that [lo, start) is already
1216 sorted (pass start == lo if you don't know!).
Tim Petersa8c974c2002-07-19 03:30:57 +00001217 If islt() complains return -1, else 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001218 Even in case of error, the output slice will be some permutation of
1219 the input (nothing is lost or duplicated).
1220*/
Guido van Rossum3f236de1996-12-10 23:55:39 +00001221static int
embg1e34da42018-01-28 20:03:23 -07001222binarysort(MergeState *ms, sortslice lo, PyObject **hi, PyObject **start)
Guido van Rossum3f236de1996-12-10 23:55:39 +00001223{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001224 Py_ssize_t k;
1225 PyObject **l, **p, **r;
1226 PyObject *pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001227
Daniel Stutzbach98338222010-12-02 21:55:33 +00001228 assert(lo.keys <= start && start <= hi);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 /* assert [lo, start) is sorted */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001230 if (lo.keys == start)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001231 ++start;
1232 for (; start < hi; ++start) {
1233 /* set l to where *start belongs */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001234 l = lo.keys;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001235 r = start;
1236 pivot = *r;
1237 /* Invariants:
1238 * pivot >= all in [lo, l).
1239 * pivot < all in [r, start).
1240 * The second is vacuously true at the start.
1241 */
1242 assert(l < r);
1243 do {
1244 p = l + ((r - l) >> 1);
1245 IFLT(pivot, *p)
1246 r = p;
1247 else
1248 l = p+1;
1249 } while (l < r);
1250 assert(l == r);
1251 /* The invariants still hold, so pivot >= all in [lo, l) and
1252 pivot < all in [l, start), so pivot belongs at l. Note
1253 that if there are elements equal to pivot, l points to the
1254 first slot after them -- that's why this sort is stable.
1255 Slide over to make room.
1256 Caution: using memmove is much slower under MSVC 5;
1257 we're not usually moving many slots. */
1258 for (p = start; p > l; --p)
1259 *p = *(p-1);
1260 *l = pivot;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001261 if (lo.values != NULL) {
1262 Py_ssize_t offset = lo.values - lo.keys;
1263 p = start + offset;
1264 pivot = *p;
1265 l += offset;
1266 for (p = start + offset; p > l; --p)
1267 *p = *(p-1);
1268 *l = pivot;
1269 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001270 }
1271 return 0;
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001272
1273 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001274 return -1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001275}
1276
Tim Petersa64dc242002-08-01 02:13:36 +00001277/*
1278Return the length of the run beginning at lo, in the slice [lo, hi). lo < hi
1279is required on entry. "A run" is the longest ascending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001280
Tim Petersa64dc242002-08-01 02:13:36 +00001281 lo[0] <= lo[1] <= lo[2] <= ...
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001282
Tim Petersa64dc242002-08-01 02:13:36 +00001283or the longest descending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001284
Tim Petersa64dc242002-08-01 02:13:36 +00001285 lo[0] > lo[1] > lo[2] > ...
Tim Peters3b01a122002-07-19 02:35:45 +00001286
Tim Petersa64dc242002-08-01 02:13:36 +00001287Boolean *descending is set to 0 in the former case, or to 1 in the latter.
1288For its intended use in a stable mergesort, the strictness of the defn of
1289"descending" is needed so that the caller can safely reverse a descending
1290sequence without violating stability (strict > ensures there are no equal
1291elements to get out of order).
1292
1293Returns -1 in case of error.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001294*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001295static Py_ssize_t
embg1e34da42018-01-28 20:03:23 -07001296count_run(MergeState *ms, PyObject **lo, PyObject **hi, int *descending)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001297{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001298 Py_ssize_t k;
1299 Py_ssize_t n;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001301 assert(lo < hi);
1302 *descending = 0;
1303 ++lo;
1304 if (lo == hi)
1305 return 1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001307 n = 2;
1308 IFLT(*lo, *(lo-1)) {
1309 *descending = 1;
1310 for (lo = lo+1; lo < hi; ++lo, ++n) {
1311 IFLT(*lo, *(lo-1))
1312 ;
1313 else
1314 break;
1315 }
1316 }
1317 else {
1318 for (lo = lo+1; lo < hi; ++lo, ++n) {
1319 IFLT(*lo, *(lo-1))
1320 break;
1321 }
1322 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001324 return n;
Tim Petersa64dc242002-08-01 02:13:36 +00001325fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001326 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001327}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001328
Tim Petersa64dc242002-08-01 02:13:36 +00001329/*
1330Locate the proper position of key in a sorted vector; if the vector contains
1331an element equal to key, return the position immediately to the left of
1332the leftmost equal element. [gallop_right() does the same except returns
1333the position to the right of the rightmost equal element (if any).]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001334
Tim Petersa64dc242002-08-01 02:13:36 +00001335"a" is a sorted vector with n elements, starting at a[0]. n must be > 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001336
Tim Petersa64dc242002-08-01 02:13:36 +00001337"hint" is an index at which to begin the search, 0 <= hint < n. The closer
1338hint is to the final result, the faster this runs.
1339
1340The return value is the int k in 0..n such that
1341
1342 a[k-1] < key <= a[k]
1343
1344pretending that *(a-1) is minus infinity and a[n] is plus infinity. IOW,
1345key belongs at index k; or, IOW, the first k elements of a should precede
1346key, and the last n-k should follow key.
1347
1348Returns -1 on error. See listsort.txt for info on the method.
1349*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001350static Py_ssize_t
embg1e34da42018-01-28 20:03:23 -07001351gallop_left(MergeState *ms, PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint)
Tim Petersa64dc242002-08-01 02:13:36 +00001352{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001353 Py_ssize_t ofs;
1354 Py_ssize_t lastofs;
1355 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001357 assert(key && a && n > 0 && hint >= 0 && hint < n);
Tim Petersa64dc242002-08-01 02:13:36 +00001358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001359 a += hint;
1360 lastofs = 0;
1361 ofs = 1;
1362 IFLT(*a, key) {
1363 /* a[hint] < key -- gallop right, until
1364 * a[hint + lastofs] < key <= a[hint + ofs]
1365 */
1366 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
1367 while (ofs < maxofs) {
1368 IFLT(a[ofs], key) {
1369 lastofs = ofs;
Alexey Izbyshev6bc59172019-05-23 03:01:08 +03001370 assert(ofs <= (PY_SSIZE_T_MAX - 1) / 2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001371 ofs = (ofs << 1) + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001372 }
1373 else /* key <= a[hint + ofs] */
1374 break;
1375 }
1376 if (ofs > maxofs)
1377 ofs = maxofs;
1378 /* Translate back to offsets relative to &a[0]. */
1379 lastofs += hint;
1380 ofs += hint;
1381 }
1382 else {
1383 /* key <= a[hint] -- gallop left, until
1384 * a[hint - ofs] < key <= a[hint - lastofs]
1385 */
1386 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
1387 while (ofs < maxofs) {
1388 IFLT(*(a-ofs), key)
1389 break;
1390 /* key <= a[hint - ofs] */
1391 lastofs = ofs;
Alexey Izbyshev6bc59172019-05-23 03:01:08 +03001392 assert(ofs <= (PY_SSIZE_T_MAX - 1) / 2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001393 ofs = (ofs << 1) + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001394 }
1395 if (ofs > maxofs)
1396 ofs = maxofs;
1397 /* Translate back to positive offsets relative to &a[0]. */
1398 k = lastofs;
1399 lastofs = hint - ofs;
1400 ofs = hint - k;
1401 }
1402 a -= hint;
Tim Petersa64dc242002-08-01 02:13:36 +00001403
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001404 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1405 /* Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the
1406 * right of lastofs but no farther right than ofs. Do a binary
1407 * search, with invariant a[lastofs-1] < key <= a[ofs].
1408 */
1409 ++lastofs;
1410 while (lastofs < ofs) {
1411 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001413 IFLT(a[m], key)
1414 lastofs = m+1; /* a[m] < key */
1415 else
1416 ofs = m; /* key <= a[m] */
1417 }
1418 assert(lastofs == ofs); /* so a[ofs-1] < key <= a[ofs] */
1419 return ofs;
Tim Petersa64dc242002-08-01 02:13:36 +00001420
1421fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001422 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001423}
1424
1425/*
1426Exactly like gallop_left(), except that if key already exists in a[0:n],
1427finds the position immediately to the right of the rightmost equal value.
1428
1429The return value is the int k in 0..n such that
1430
1431 a[k-1] <= key < a[k]
1432
1433or -1 if error.
1434
1435The code duplication is massive, but this is enough different given that
1436we're sticking to "<" comparisons that it's much harder to follow if
1437written as one routine with yet another "left or right?" flag.
1438*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001439static Py_ssize_t
embg1e34da42018-01-28 20:03:23 -07001440gallop_right(MergeState *ms, PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint)
Tim Petersa64dc242002-08-01 02:13:36 +00001441{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001442 Py_ssize_t ofs;
1443 Py_ssize_t lastofs;
1444 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001445
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001446 assert(key && a && n > 0 && hint >= 0 && hint < n);
Tim Petersa64dc242002-08-01 02:13:36 +00001447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001448 a += hint;
1449 lastofs = 0;
1450 ofs = 1;
1451 IFLT(key, *a) {
1452 /* key < a[hint] -- gallop left, until
1453 * a[hint - ofs] <= key < a[hint - lastofs]
1454 */
1455 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
1456 while (ofs < maxofs) {
1457 IFLT(key, *(a-ofs)) {
1458 lastofs = ofs;
Alexey Izbyshev6bc59172019-05-23 03:01:08 +03001459 assert(ofs <= (PY_SSIZE_T_MAX - 1) / 2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001460 ofs = (ofs << 1) + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001461 }
1462 else /* a[hint - ofs] <= key */
1463 break;
1464 }
1465 if (ofs > maxofs)
1466 ofs = maxofs;
1467 /* Translate back to positive offsets relative to &a[0]. */
1468 k = lastofs;
1469 lastofs = hint - ofs;
1470 ofs = hint - k;
1471 }
1472 else {
1473 /* a[hint] <= key -- gallop right, until
1474 * a[hint + lastofs] <= key < a[hint + ofs]
1475 */
1476 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
1477 while (ofs < maxofs) {
1478 IFLT(key, a[ofs])
1479 break;
1480 /* a[hint + ofs] <= key */
1481 lastofs = ofs;
Alexey Izbyshev6bc59172019-05-23 03:01:08 +03001482 assert(ofs <= (PY_SSIZE_T_MAX - 1) / 2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001483 ofs = (ofs << 1) + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001484 }
1485 if (ofs > maxofs)
1486 ofs = maxofs;
1487 /* Translate back to offsets relative to &a[0]. */
1488 lastofs += hint;
1489 ofs += hint;
1490 }
1491 a -= hint;
Tim Petersa64dc242002-08-01 02:13:36 +00001492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001493 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1494 /* Now a[lastofs] <= key < a[ofs], so key belongs somewhere to the
1495 * right of lastofs but no farther right than ofs. Do a binary
1496 * search, with invariant a[lastofs-1] <= key < a[ofs].
1497 */
1498 ++lastofs;
1499 while (lastofs < ofs) {
1500 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001502 IFLT(key, a[m])
1503 ofs = m; /* key < a[m] */
1504 else
1505 lastofs = m+1; /* a[m] <= key */
1506 }
1507 assert(lastofs == ofs); /* so a[ofs-1] <= key < a[ofs] */
1508 return ofs;
Tim Petersa64dc242002-08-01 02:13:36 +00001509
1510fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001511 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001512}
1513
Tim Petersa64dc242002-08-01 02:13:36 +00001514/* Conceptually a MergeState's constructor. */
1515static void
Victor Stinner0fcab4a2011-01-04 12:59:15 +00001516merge_init(MergeState *ms, Py_ssize_t list_size, int has_keyfunc)
Tim Petersa64dc242002-08-01 02:13:36 +00001517{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001518 assert(ms != NULL);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001519 if (has_keyfunc) {
1520 /* The temporary space for merging will need at most half the list
1521 * size rounded up. Use the minimum possible space so we can use the
1522 * rest of temparray for other things. In particular, if there is
1523 * enough extra space, listsort() will use it to store the keys.
1524 */
1525 ms->alloced = (list_size + 1) / 2;
1526
1527 /* ms->alloced describes how many keys will be stored at
1528 ms->temparray, but we also need to store the values. Hence,
1529 ms->alloced is capped at half of MERGESTATE_TEMP_SIZE. */
1530 if (MERGESTATE_TEMP_SIZE / 2 < ms->alloced)
1531 ms->alloced = MERGESTATE_TEMP_SIZE / 2;
1532 ms->a.values = &ms->temparray[ms->alloced];
1533 }
1534 else {
1535 ms->alloced = MERGESTATE_TEMP_SIZE;
1536 ms->a.values = NULL;
1537 }
1538 ms->a.keys = ms->temparray;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001539 ms->n = 0;
1540 ms->min_gallop = MIN_GALLOP;
Tim Petersa64dc242002-08-01 02:13:36 +00001541}
1542
1543/* Free all the temp memory owned by the MergeState. This must be called
1544 * when you're done with a MergeState, and may be called before then if
1545 * you want to free the temp memory early.
1546 */
1547static void
1548merge_freemem(MergeState *ms)
1549{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001550 assert(ms != NULL);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001551 if (ms->a.keys != ms->temparray)
1552 PyMem_Free(ms->a.keys);
Tim Petersa64dc242002-08-01 02:13:36 +00001553}
1554
1555/* Ensure enough temp memory for 'need' array slots is available.
1556 * Returns 0 on success and -1 if the memory can't be gotten.
1557 */
1558static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001559merge_getmem(MergeState *ms, Py_ssize_t need)
Tim Petersa64dc242002-08-01 02:13:36 +00001560{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001561 int multiplier;
1562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001563 assert(ms != NULL);
1564 if (need <= ms->alloced)
1565 return 0;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001566
1567 multiplier = ms->a.values != NULL ? 2 : 1;
1568
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001569 /* Don't realloc! That can cost cycles to copy the old data, but
1570 * we don't care what's in the block.
1571 */
1572 merge_freemem(ms);
embg1e34da42018-01-28 20:03:23 -07001573 if ((size_t)need > PY_SSIZE_T_MAX / sizeof(PyObject *) / multiplier) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001574 PyErr_NoMemory();
1575 return -1;
1576 }
embg1e34da42018-01-28 20:03:23 -07001577 ms->a.keys = (PyObject **)PyMem_Malloc(multiplier * need
Daniel Stutzbach98338222010-12-02 21:55:33 +00001578 * sizeof(PyObject *));
1579 if (ms->a.keys != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001580 ms->alloced = need;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001581 if (ms->a.values != NULL)
1582 ms->a.values = &ms->a.keys[need];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001583 return 0;
1584 }
1585 PyErr_NoMemory();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001586 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001587}
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001588#define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 : \
1589 merge_getmem(MS, NEED))
Tim Petersa64dc242002-08-01 02:13:36 +00001590
Daniel Stutzbach98338222010-12-02 21:55:33 +00001591/* Merge the na elements starting at ssa with the nb elements starting at
1592 * ssb.keys = ssa.keys + na in a stable way, in-place. na and nb must be > 0.
1593 * Must also have that ssa.keys[na-1] belongs at the end of the merge, and
1594 * should have na <= nb. See listsort.txt for more info. Return 0 if
1595 * successful, -1 if error.
Tim Petersa64dc242002-08-01 02:13:36 +00001596 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001597static Py_ssize_t
Daniel Stutzbach98338222010-12-02 21:55:33 +00001598merge_lo(MergeState *ms, sortslice ssa, Py_ssize_t na,
1599 sortslice ssb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001600{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001601 Py_ssize_t k;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001602 sortslice dest;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001603 int result = -1; /* guilty until proved innocent */
1604 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001605
Daniel Stutzbach98338222010-12-02 21:55:33 +00001606 assert(ms && ssa.keys && ssb.keys && na > 0 && nb > 0);
1607 assert(ssa.keys + na == ssb.keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001608 if (MERGE_GETMEM(ms, na) < 0)
1609 return -1;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001610 sortslice_memcpy(&ms->a, 0, &ssa, 0, na);
1611 dest = ssa;
1612 ssa = ms->a;
Tim Petersa64dc242002-08-01 02:13:36 +00001613
Daniel Stutzbach98338222010-12-02 21:55:33 +00001614 sortslice_copy_incr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001615 --nb;
1616 if (nb == 0)
1617 goto Succeed;
1618 if (na == 1)
1619 goto CopyB;
Tim Petersa64dc242002-08-01 02:13:36 +00001620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001621 min_gallop = ms->min_gallop;
1622 for (;;) {
1623 Py_ssize_t acount = 0; /* # of times A won in a row */
1624 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001626 /* Do the straightforward thing until (if ever) one run
1627 * appears to win consistently.
1628 */
1629 for (;;) {
1630 assert(na > 1 && nb > 0);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001631 k = ISLT(ssb.keys[0], ssa.keys[0]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001632 if (k) {
1633 if (k < 0)
1634 goto Fail;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001635 sortslice_copy_incr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001636 ++bcount;
1637 acount = 0;
1638 --nb;
1639 if (nb == 0)
1640 goto Succeed;
1641 if (bcount >= min_gallop)
1642 break;
1643 }
1644 else {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001645 sortslice_copy_incr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001646 ++acount;
1647 bcount = 0;
1648 --na;
1649 if (na == 1)
1650 goto CopyB;
1651 if (acount >= min_gallop)
1652 break;
1653 }
1654 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001655
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001656 /* One run is winning so consistently that galloping may
1657 * be a huge win. So try that, and continue galloping until
1658 * (if ever) neither run appears to be winning consistently
1659 * anymore.
1660 */
1661 ++min_gallop;
1662 do {
1663 assert(na > 1 && nb > 0);
1664 min_gallop -= min_gallop > 1;
1665 ms->min_gallop = min_gallop;
embg1e34da42018-01-28 20:03:23 -07001666 k = gallop_right(ms, ssb.keys[0], ssa.keys, na, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001667 acount = k;
1668 if (k) {
1669 if (k < 0)
1670 goto Fail;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001671 sortslice_memcpy(&dest, 0, &ssa, 0, k);
1672 sortslice_advance(&dest, k);
1673 sortslice_advance(&ssa, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001674 na -= k;
1675 if (na == 1)
1676 goto CopyB;
1677 /* na==0 is impossible now if the comparison
1678 * function is consistent, but we can't assume
1679 * that it is.
1680 */
1681 if (na == 0)
1682 goto Succeed;
1683 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001684 sortslice_copy_incr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001685 --nb;
1686 if (nb == 0)
1687 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001688
embg1e34da42018-01-28 20:03:23 -07001689 k = gallop_left(ms, ssa.keys[0], ssb.keys, nb, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001690 bcount = k;
1691 if (k) {
1692 if (k < 0)
1693 goto Fail;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001694 sortslice_memmove(&dest, 0, &ssb, 0, k);
1695 sortslice_advance(&dest, k);
1696 sortslice_advance(&ssb, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001697 nb -= k;
1698 if (nb == 0)
1699 goto Succeed;
1700 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001701 sortslice_copy_incr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001702 --na;
1703 if (na == 1)
1704 goto CopyB;
1705 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
1706 ++min_gallop; /* penalize it for leaving galloping mode */
1707 ms->min_gallop = min_gallop;
1708 }
Tim Petersa64dc242002-08-01 02:13:36 +00001709Succeed:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001710 result = 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001711Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001712 if (na)
Daniel Stutzbach98338222010-12-02 21:55:33 +00001713 sortslice_memcpy(&dest, 0, &ssa, 0, na);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001714 return result;
Tim Petersa64dc242002-08-01 02:13:36 +00001715CopyB:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001716 assert(na == 1 && nb > 0);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001717 /* The last element of ssa belongs at the end of the merge. */
1718 sortslice_memmove(&dest, 0, &ssb, 0, nb);
1719 sortslice_copy(&dest, nb, &ssa, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001720 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001721}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001722
Daniel Stutzbach98338222010-12-02 21:55:33 +00001723/* Merge the na elements starting at pa with the nb elements starting at
1724 * ssb.keys = ssa.keys + na in a stable way, in-place. na and nb must be > 0.
1725 * Must also have that ssa.keys[na-1] belongs at the end of the merge, and
1726 * should have na >= nb. See listsort.txt for more info. Return 0 if
1727 * successful, -1 if error.
Tim Petersa64dc242002-08-01 02:13:36 +00001728 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001729static Py_ssize_t
Daniel Stutzbach98338222010-12-02 21:55:33 +00001730merge_hi(MergeState *ms, sortslice ssa, Py_ssize_t na,
1731 sortslice ssb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001732{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001733 Py_ssize_t k;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001734 sortslice dest, basea, baseb;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001735 int result = -1; /* guilty until proved innocent */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001737
Daniel Stutzbach98338222010-12-02 21:55:33 +00001738 assert(ms && ssa.keys && ssb.keys && na > 0 && nb > 0);
1739 assert(ssa.keys + na == ssb.keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001740 if (MERGE_GETMEM(ms, nb) < 0)
1741 return -1;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001742 dest = ssb;
1743 sortslice_advance(&dest, nb-1);
1744 sortslice_memcpy(&ms->a, 0, &ssb, 0, nb);
1745 basea = ssa;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001746 baseb = ms->a;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001747 ssb.keys = ms->a.keys + nb - 1;
1748 if (ssb.values != NULL)
1749 ssb.values = ms->a.values + nb - 1;
1750 sortslice_advance(&ssa, na - 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001751
Daniel Stutzbach98338222010-12-02 21:55:33 +00001752 sortslice_copy_decr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001753 --na;
1754 if (na == 0)
1755 goto Succeed;
1756 if (nb == 1)
1757 goto CopyA;
Tim Petersa64dc242002-08-01 02:13:36 +00001758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001759 min_gallop = ms->min_gallop;
1760 for (;;) {
1761 Py_ssize_t acount = 0; /* # of times A won in a row */
1762 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001763
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001764 /* Do the straightforward thing until (if ever) one run
1765 * appears to win consistently.
1766 */
1767 for (;;) {
1768 assert(na > 0 && nb > 1);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001769 k = ISLT(ssb.keys[0], ssa.keys[0]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001770 if (k) {
1771 if (k < 0)
1772 goto Fail;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001773 sortslice_copy_decr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001774 ++acount;
1775 bcount = 0;
1776 --na;
1777 if (na == 0)
1778 goto Succeed;
1779 if (acount >= min_gallop)
1780 break;
1781 }
1782 else {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001783 sortslice_copy_decr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001784 ++bcount;
1785 acount = 0;
1786 --nb;
1787 if (nb == 1)
1788 goto CopyA;
1789 if (bcount >= min_gallop)
1790 break;
1791 }
1792 }
Tim Petersa64dc242002-08-01 02:13:36 +00001793
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001794 /* One run is winning so consistently that galloping may
1795 * be a huge win. So try that, and continue galloping until
1796 * (if ever) neither run appears to be winning consistently
1797 * anymore.
1798 */
1799 ++min_gallop;
1800 do {
1801 assert(na > 0 && nb > 1);
1802 min_gallop -= min_gallop > 1;
1803 ms->min_gallop = min_gallop;
embg1e34da42018-01-28 20:03:23 -07001804 k = gallop_right(ms, ssb.keys[0], basea.keys, na, na-1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001805 if (k < 0)
1806 goto Fail;
1807 k = na - k;
1808 acount = k;
1809 if (k) {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001810 sortslice_advance(&dest, -k);
1811 sortslice_advance(&ssa, -k);
1812 sortslice_memmove(&dest, 1, &ssa, 1, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001813 na -= k;
1814 if (na == 0)
1815 goto Succeed;
1816 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001817 sortslice_copy_decr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001818 --nb;
1819 if (nb == 1)
1820 goto CopyA;
Tim Petersa64dc242002-08-01 02:13:36 +00001821
embg1e34da42018-01-28 20:03:23 -07001822 k = gallop_left(ms, ssa.keys[0], baseb.keys, nb, nb-1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001823 if (k < 0)
1824 goto Fail;
1825 k = nb - k;
1826 bcount = k;
1827 if (k) {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001828 sortslice_advance(&dest, -k);
1829 sortslice_advance(&ssb, -k);
1830 sortslice_memcpy(&dest, 1, &ssb, 1, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001831 nb -= k;
1832 if (nb == 1)
1833 goto CopyA;
1834 /* nb==0 is impossible now if the comparison
1835 * function is consistent, but we can't assume
1836 * that it is.
1837 */
1838 if (nb == 0)
1839 goto Succeed;
1840 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001841 sortslice_copy_decr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001842 --na;
1843 if (na == 0)
1844 goto Succeed;
1845 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
1846 ++min_gallop; /* penalize it for leaving galloping mode */
1847 ms->min_gallop = min_gallop;
1848 }
Tim Petersa64dc242002-08-01 02:13:36 +00001849Succeed:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001850 result = 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001851Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001852 if (nb)
Daniel Stutzbach98338222010-12-02 21:55:33 +00001853 sortslice_memcpy(&dest, -(nb-1), &baseb, 0, nb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001854 return result;
Tim Petersa64dc242002-08-01 02:13:36 +00001855CopyA:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001856 assert(nb == 1 && na > 0);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001857 /* The first element of ssb belongs at the front of the merge. */
1858 sortslice_memmove(&dest, 1-na, &ssa, 1-na, na);
1859 sortslice_advance(&dest, -na);
1860 sortslice_advance(&ssa, -na);
1861 sortslice_copy(&dest, 0, &ssb, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001862 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001863}
1864
1865/* Merge the two runs at stack indices i and i+1.
1866 * Returns 0 on success, -1 on error.
1867 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001868static Py_ssize_t
1869merge_at(MergeState *ms, Py_ssize_t i)
Tim Petersa64dc242002-08-01 02:13:36 +00001870{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001871 sortslice ssa, ssb;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001872 Py_ssize_t na, nb;
1873 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001874
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001875 assert(ms != NULL);
1876 assert(ms->n >= 2);
1877 assert(i >= 0);
1878 assert(i == ms->n - 2 || i == ms->n - 3);
Tim Petersa64dc242002-08-01 02:13:36 +00001879
Daniel Stutzbach98338222010-12-02 21:55:33 +00001880 ssa = ms->pending[i].base;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001881 na = ms->pending[i].len;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001882 ssb = ms->pending[i+1].base;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001883 nb = ms->pending[i+1].len;
1884 assert(na > 0 && nb > 0);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001885 assert(ssa.keys + na == ssb.keys);
Tim Petersa64dc242002-08-01 02:13:36 +00001886
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001887 /* Record the length of the combined runs; if i is the 3rd-last
1888 * run now, also slide over the last run (which isn't involved
1889 * in this merge). The current run i+1 goes away in any case.
1890 */
1891 ms->pending[i].len = na + nb;
1892 if (i == ms->n - 3)
1893 ms->pending[i+1] = ms->pending[i+2];
1894 --ms->n;
Tim Petersa64dc242002-08-01 02:13:36 +00001895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001896 /* Where does b start in a? Elements in a before that can be
1897 * ignored (already in place).
1898 */
embg1e34da42018-01-28 20:03:23 -07001899 k = gallop_right(ms, *ssb.keys, ssa.keys, na, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001900 if (k < 0)
1901 return -1;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001902 sortslice_advance(&ssa, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001903 na -= k;
1904 if (na == 0)
1905 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001907 /* Where does a end in b? Elements in b after that can be
1908 * ignored (already in place).
1909 */
embg1e34da42018-01-28 20:03:23 -07001910 nb = gallop_left(ms, ssa.keys[na-1], ssb.keys, nb, nb-1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001911 if (nb <= 0)
1912 return nb;
Tim Petersa64dc242002-08-01 02:13:36 +00001913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001914 /* Merge what remains of the runs, using a temp array with
1915 * min(na, nb) elements.
1916 */
1917 if (na <= nb)
Daniel Stutzbach98338222010-12-02 21:55:33 +00001918 return merge_lo(ms, ssa, na, ssb, nb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001919 else
Daniel Stutzbach98338222010-12-02 21:55:33 +00001920 return merge_hi(ms, ssa, na, ssb, nb);
Tim Petersa64dc242002-08-01 02:13:36 +00001921}
1922
1923/* Examine the stack of runs waiting to be merged, merging adjacent runs
1924 * until the stack invariants are re-established:
1925 *
1926 * 1. len[-3] > len[-2] + len[-1]
1927 * 2. len[-2] > len[-1]
1928 *
1929 * See listsort.txt for more info.
1930 *
1931 * Returns 0 on success, -1 on error.
1932 */
1933static int
1934merge_collapse(MergeState *ms)
1935{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001936 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001938 assert(ms);
1939 while (ms->n > 1) {
1940 Py_ssize_t n = ms->n - 2;
Benjamin Petersonb808d592015-02-25 10:12:26 -05001941 if ((n > 0 && p[n-1].len <= p[n].len + p[n+1].len) ||
1942 (n > 1 && p[n-2].len <= p[n-1].len + p[n].len)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001943 if (p[n-1].len < p[n+1].len)
1944 --n;
1945 if (merge_at(ms, n) < 0)
1946 return -1;
1947 }
1948 else if (p[n].len <= p[n+1].len) {
embg1e34da42018-01-28 20:03:23 -07001949 if (merge_at(ms, n) < 0)
1950 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001951 }
1952 else
1953 break;
1954 }
1955 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001956}
1957
1958/* Regardless of invariants, merge all runs on the stack until only one
1959 * remains. This is used at the end of the mergesort.
1960 *
1961 * Returns 0 on success, -1 on error.
1962 */
1963static int
1964merge_force_collapse(MergeState *ms)
1965{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001966 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001967
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001968 assert(ms);
1969 while (ms->n > 1) {
1970 Py_ssize_t n = ms->n - 2;
1971 if (n > 0 && p[n-1].len < p[n+1].len)
1972 --n;
1973 if (merge_at(ms, n) < 0)
1974 return -1;
1975 }
1976 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001977}
1978
1979/* Compute a good value for the minimum run length; natural runs shorter
1980 * than this are boosted artificially via binary insertion.
1981 *
1982 * If n < 64, return n (it's too small to bother with fancy stuff).
1983 * Else if n is an exact power of 2, return 32.
1984 * Else return an int k, 32 <= k <= 64, such that n/k is close to, but
1985 * strictly less than, an exact power of 2.
1986 *
1987 * See listsort.txt for more info.
1988 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001989static Py_ssize_t
1990merge_compute_minrun(Py_ssize_t n)
Tim Petersa64dc242002-08-01 02:13:36 +00001991{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001992 Py_ssize_t r = 0; /* becomes 1 if any 1 bits are shifted off */
Tim Petersa64dc242002-08-01 02:13:36 +00001993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001994 assert(n >= 0);
1995 while (n >= 64) {
1996 r |= n & 1;
1997 n >>= 1;
1998 }
1999 return n + r;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002000}
Guido van Rossuma119c0d1998-05-29 17:56:32 +00002001
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002002static void
Daniel Stutzbach98338222010-12-02 21:55:33 +00002003reverse_sortslice(sortslice *s, Py_ssize_t n)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002004{
Daniel Stutzbach98338222010-12-02 21:55:33 +00002005 reverse_slice(s->keys, &s->keys[n]);
2006 if (s->values != NULL)
2007 reverse_slice(s->values, &s->values[n]);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002008}
2009
embg1e34da42018-01-28 20:03:23 -07002010/* Here we define custom comparison functions to optimize for the cases one commonly
2011 * encounters in practice: homogeneous lists, often of one of the basic types. */
2012
2013/* This struct holds the comparison function and helper functions
2014 * selected in the pre-sort check. */
2015
2016/* These are the special case compare functions.
2017 * ms->key_compare will always point to one of these: */
2018
2019/* Heterogeneous compare: default, always safe to fall back on. */
2020static int
2021safe_object_compare(PyObject *v, PyObject *w, MergeState *ms)
2022{
2023 /* No assumptions necessary! */
2024 return PyObject_RichCompareBool(v, w, Py_LT);
2025}
2026
Christian Claussdcfbe4f2021-10-07 16:31:33 +02002027/* Homogeneous compare: safe for any two comparable objects of the same type.
embg1e34da42018-01-28 20:03:23 -07002028 * (ms->key_richcompare is set to ob_type->tp_richcompare in the
2029 * pre-sort check.)
2030 */
2031static int
2032unsafe_object_compare(PyObject *v, PyObject *w, MergeState *ms)
2033{
2034 PyObject *res_obj; int res;
2035
2036 /* No assumptions, because we check first: */
Victor Stinner58ac7002020-02-07 03:04:21 +01002037 if (Py_TYPE(v)->tp_richcompare != ms->key_richcompare)
embg1e34da42018-01-28 20:03:23 -07002038 return PyObject_RichCompareBool(v, w, Py_LT);
2039
2040 assert(ms->key_richcompare != NULL);
2041 res_obj = (*(ms->key_richcompare))(v, w, Py_LT);
2042
2043 if (res_obj == Py_NotImplemented) {
2044 Py_DECREF(res_obj);
2045 return PyObject_RichCompareBool(v, w, Py_LT);
2046 }
2047 if (res_obj == NULL)
2048 return -1;
2049
2050 if (PyBool_Check(res_obj)) {
2051 res = (res_obj == Py_True);
2052 }
2053 else {
2054 res = PyObject_IsTrue(res_obj);
2055 }
2056 Py_DECREF(res_obj);
2057
2058 /* Note that we can't assert
2059 * res == PyObject_RichCompareBool(v, w, Py_LT);
2060 * because of evil compare functions like this:
2061 * lambda a, b: int(random.random() * 3) - 1)
2062 * (which is actually in test_sort.py) */
2063 return res;
2064}
2065
2066/* Latin string compare: safe for any two latin (one byte per char) strings. */
2067static int
2068unsafe_latin_compare(PyObject *v, PyObject *w, MergeState *ms)
2069{
Victor Stinner8017b802018-01-29 13:47:06 +01002070 Py_ssize_t len;
2071 int res;
embg1e34da42018-01-28 20:03:23 -07002072
2073 /* Modified from Objects/unicodeobject.c:unicode_compare, assuming: */
Andy Lesterdffe4c02020-03-04 07:15:20 -06002074 assert(Py_IS_TYPE(v, &PyUnicode_Type));
2075 assert(Py_IS_TYPE(w, &PyUnicode_Type));
embg1e34da42018-01-28 20:03:23 -07002076 assert(PyUnicode_KIND(v) == PyUnicode_KIND(w));
2077 assert(PyUnicode_KIND(v) == PyUnicode_1BYTE_KIND);
2078
2079 len = Py_MIN(PyUnicode_GET_LENGTH(v), PyUnicode_GET_LENGTH(w));
2080 res = memcmp(PyUnicode_DATA(v), PyUnicode_DATA(w), len);
2081
2082 res = (res != 0 ?
2083 res < 0 :
2084 PyUnicode_GET_LENGTH(v) < PyUnicode_GET_LENGTH(w));
2085
2086 assert(res == PyObject_RichCompareBool(v, w, Py_LT));;
2087 return res;
2088}
2089
2090/* Bounded int compare: compare any two longs that fit in a single machine word. */
2091static int
2092unsafe_long_compare(PyObject *v, PyObject *w, MergeState *ms)
2093{
2094 PyLongObject *vl, *wl; sdigit v0, w0; int res;
2095
2096 /* Modified from Objects/longobject.c:long_compare, assuming: */
Andy Lesterdffe4c02020-03-04 07:15:20 -06002097 assert(Py_IS_TYPE(v, &PyLong_Type));
2098 assert(Py_IS_TYPE(w, &PyLong_Type));
embg1e34da42018-01-28 20:03:23 -07002099 assert(Py_ABS(Py_SIZE(v)) <= 1);
2100 assert(Py_ABS(Py_SIZE(w)) <= 1);
2101
2102 vl = (PyLongObject*)v;
2103 wl = (PyLongObject*)w;
2104
2105 v0 = Py_SIZE(vl) == 0 ? 0 : (sdigit)vl->ob_digit[0];
2106 w0 = Py_SIZE(wl) == 0 ? 0 : (sdigit)wl->ob_digit[0];
2107
2108 if (Py_SIZE(vl) < 0)
2109 v0 = -v0;
2110 if (Py_SIZE(wl) < 0)
2111 w0 = -w0;
2112
2113 res = v0 < w0;
2114 assert(res == PyObject_RichCompareBool(v, w, Py_LT));
2115 return res;
2116}
2117
2118/* Float compare: compare any two floats. */
2119static int
2120unsafe_float_compare(PyObject *v, PyObject *w, MergeState *ms)
2121{
2122 int res;
2123
2124 /* Modified from Objects/floatobject.c:float_richcompare, assuming: */
Andy Lesterdffe4c02020-03-04 07:15:20 -06002125 assert(Py_IS_TYPE(v, &PyFloat_Type));
2126 assert(Py_IS_TYPE(w, &PyFloat_Type));
embg1e34da42018-01-28 20:03:23 -07002127
2128 res = PyFloat_AS_DOUBLE(v) < PyFloat_AS_DOUBLE(w);
2129 assert(res == PyObject_RichCompareBool(v, w, Py_LT));
2130 return res;
2131}
2132
2133/* Tuple compare: compare *any* two tuples, using
2134 * ms->tuple_elem_compare to compare the first elements, which is set
2135 * using the same pre-sort check as we use for ms->key_compare,
2136 * but run on the list [x[0] for x in L]. This allows us to optimize compares
2137 * on two levels (as long as [x[0] for x in L] is type-homogeneous.) The idea is
2138 * that most tuple compares don't involve x[1:]. */
2139static int
2140unsafe_tuple_compare(PyObject *v, PyObject *w, MergeState *ms)
2141{
2142 PyTupleObject *vt, *wt;
2143 Py_ssize_t i, vlen, wlen;
2144 int k;
2145
2146 /* Modified from Objects/tupleobject.c:tuplerichcompare, assuming: */
Andy Lesterdffe4c02020-03-04 07:15:20 -06002147 assert(Py_IS_TYPE(v, &PyTuple_Type));
2148 assert(Py_IS_TYPE(w, &PyTuple_Type));
embg1e34da42018-01-28 20:03:23 -07002149 assert(Py_SIZE(v) > 0);
2150 assert(Py_SIZE(w) > 0);
2151
2152 vt = (PyTupleObject *)v;
2153 wt = (PyTupleObject *)w;
2154
2155 vlen = Py_SIZE(vt);
2156 wlen = Py_SIZE(wt);
2157
2158 for (i = 0; i < vlen && i < wlen; i++) {
2159 k = PyObject_RichCompareBool(vt->ob_item[i], wt->ob_item[i], Py_EQ);
2160 if (k < 0)
2161 return -1;
2162 if (!k)
2163 break;
2164 }
2165
2166 if (i >= vlen || i >= wlen)
2167 return vlen < wlen;
2168
2169 if (i == 0)
2170 return ms->tuple_elem_compare(vt->ob_item[i], wt->ob_item[i], ms);
2171 else
2172 return PyObject_RichCompareBool(vt->ob_item[i], wt->ob_item[i], Py_LT);
2173}
2174
Tim Petersa64dc242002-08-01 02:13:36 +00002175/* An adaptive, stable, natural mergesort. See listsort.txt.
2176 * Returns Py_None on success, NULL on error. Even in case of error, the
2177 * list will be some permutation of its input state (nothing is lost or
2178 * duplicated).
2179 */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002180/*[clinic input]
2181list.sort
2182
2183 *
2184 key as keyfunc: object = None
Serhiy Storchaka202fda52017-03-12 10:10:47 +02002185 reverse: bool(accept={int}) = False
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002186
Tim Hoffmann5c224762019-06-01 06:10:02 +02002187Sort the list in ascending order and return None.
2188
2189The sort is in-place (i.e. the list itself is modified) and stable (i.e. the
2190order of two equal elements is maintained).
2191
2192If a key function is given, apply it once to each list item and sort them,
2193ascending or descending, according to their function values.
2194
2195The reverse flag can be set to sort in descending order.
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002196[clinic start generated code]*/
2197
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002198static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002199list_sort_impl(PyListObject *self, PyObject *keyfunc, int reverse)
Tim Hoffmann5c224762019-06-01 06:10:02 +02002200/*[clinic end generated code: output=57b9f9c5e23fbe42 input=cb56cd179a713060]*/
Guido van Rossum3f236de1996-12-10 23:55:39 +00002201{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002202 MergeState ms;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002203 Py_ssize_t nremaining;
2204 Py_ssize_t minrun;
Daniel Stutzbach98338222010-12-02 21:55:33 +00002205 sortslice lo;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002206 Py_ssize_t saved_ob_size, saved_allocated;
2207 PyObject **saved_ob_item;
2208 PyObject **final_ob_item;
2209 PyObject *result = NULL; /* guilty until proved innocent */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002210 Py_ssize_t i;
Daniel Stutzbach98338222010-12-02 21:55:33 +00002211 PyObject **keys;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002213 assert(self != NULL);
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002214 assert(PyList_Check(self));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002215 if (keyfunc == Py_None)
2216 keyfunc = NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002218 /* The list is temporarily made empty, so that mutations performed
2219 * by comparison functions can't affect the slice of memory we're
2220 * sorting (allowing mutations during sorting is a core-dump
2221 * factory, since ob_item may change).
2222 */
2223 saved_ob_size = Py_SIZE(self);
2224 saved_ob_item = self->ob_item;
2225 saved_allocated = self->allocated;
Victor Stinner60ac6ed2020-02-07 23:18:08 +01002226 Py_SET_SIZE(self, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002227 self->ob_item = NULL;
2228 self->allocated = -1; /* any operation will reset it to >= 0 */
Tim Peters330f9e92002-07-19 07:05:44 +00002229
Daniel Stutzbach98338222010-12-02 21:55:33 +00002230 if (keyfunc == NULL) {
2231 keys = NULL;
2232 lo.keys = saved_ob_item;
2233 lo.values = NULL;
2234 }
2235 else {
2236 if (saved_ob_size < MERGESTATE_TEMP_SIZE/2)
2237 /* Leverage stack space we allocated but won't otherwise use */
2238 keys = &ms.temparray[saved_ob_size+1];
2239 else {
Victor Stinner00d7abd2020-12-01 09:56:42 +01002240 keys = PyMem_Malloc(sizeof(PyObject *) * saved_ob_size);
Benjamin Peterson0823ffb2015-04-23 17:04:36 -04002241 if (keys == NULL) {
2242 PyErr_NoMemory();
2243 goto keyfunc_fail;
2244 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002245 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00002246
2247 for (i = 0; i < saved_ob_size ; i++) {
Petr Viktorinffd97532020-02-11 17:46:57 +01002248 keys[i] = PyObject_CallOneArg(keyfunc, saved_ob_item[i]);
Daniel Stutzbach98338222010-12-02 21:55:33 +00002249 if (keys[i] == NULL) {
2250 for (i=i-1 ; i>=0 ; i--)
2251 Py_DECREF(keys[i]);
Benjamin Peterson4a42cd42014-03-15 12:21:28 -05002252 if (saved_ob_size >= MERGESTATE_TEMP_SIZE/2)
Victor Stinner00d7abd2020-12-01 09:56:42 +01002253 PyMem_Free(keys);
Daniel Stutzbach98338222010-12-02 21:55:33 +00002254 goto keyfunc_fail;
2255 }
2256 }
2257
2258 lo.keys = keys;
2259 lo.values = saved_ob_item;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002260 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002261
embg1e34da42018-01-28 20:03:23 -07002262
2263 /* The pre-sort check: here's where we decide which compare function to use.
2264 * How much optimization is safe? We test for homogeneity with respect to
2265 * several properties that are expensive to check at compare-time, and
2266 * set ms appropriately. */
2267 if (saved_ob_size > 1) {
2268 /* Assume the first element is representative of the whole list. */
Andy Lesterdffe4c02020-03-04 07:15:20 -06002269 int keys_are_in_tuples = (Py_IS_TYPE(lo.keys[0], &PyTuple_Type) &&
embg1e34da42018-01-28 20:03:23 -07002270 Py_SIZE(lo.keys[0]) > 0);
2271
2272 PyTypeObject* key_type = (keys_are_in_tuples ?
Victor Stinner58ac7002020-02-07 03:04:21 +01002273 Py_TYPE(PyTuple_GET_ITEM(lo.keys[0], 0)) :
2274 Py_TYPE(lo.keys[0]));
embg1e34da42018-01-28 20:03:23 -07002275
2276 int keys_are_all_same_type = 1;
2277 int strings_are_latin = 1;
2278 int ints_are_bounded = 1;
2279
2280 /* Prove that assumption by checking every key. */
embg1e34da42018-01-28 20:03:23 -07002281 for (i=0; i < saved_ob_size; i++) {
2282
2283 if (keys_are_in_tuples &&
Andy Lesterdffe4c02020-03-04 07:15:20 -06002284 !(Py_IS_TYPE(lo.keys[i], &PyTuple_Type) && Py_SIZE(lo.keys[i]) != 0)) {
embg1e34da42018-01-28 20:03:23 -07002285 keys_are_in_tuples = 0;
2286 keys_are_all_same_type = 0;
2287 break;
2288 }
2289
2290 /* Note: for lists of tuples, key is the first element of the tuple
2291 * lo.keys[i], not lo.keys[i] itself! We verify type-homogeneity
2292 * for lists of tuples in the if-statement directly above. */
2293 PyObject *key = (keys_are_in_tuples ?
2294 PyTuple_GET_ITEM(lo.keys[i], 0) :
2295 lo.keys[i]);
2296
Andy Lesterdffe4c02020-03-04 07:15:20 -06002297 if (!Py_IS_TYPE(key, key_type)) {
embg1e34da42018-01-28 20:03:23 -07002298 keys_are_all_same_type = 0;
Rémi Lapeyredd5417a2019-03-25 08:25:37 +01002299 /* If keys are in tuple we must loop over the whole list to make
2300 sure all items are tuples */
2301 if (!keys_are_in_tuples) {
2302 break;
2303 }
embg1e34da42018-01-28 20:03:23 -07002304 }
2305
Rémi Lapeyredd5417a2019-03-25 08:25:37 +01002306 if (keys_are_all_same_type) {
2307 if (key_type == &PyLong_Type &&
2308 ints_are_bounded &&
2309 Py_ABS(Py_SIZE(key)) > 1) {
2310
embg1e34da42018-01-28 20:03:23 -07002311 ints_are_bounded = 0;
Rémi Lapeyredd5417a2019-03-25 08:25:37 +01002312 }
2313 else if (key_type == &PyUnicode_Type &&
2314 strings_are_latin &&
2315 PyUnicode_KIND(key) != PyUnicode_1BYTE_KIND) {
2316
2317 strings_are_latin = 0;
2318 }
2319 }
embg1e34da42018-01-28 20:03:23 -07002320 }
embg1e34da42018-01-28 20:03:23 -07002321
2322 /* Choose the best compare, given what we now know about the keys. */
2323 if (keys_are_all_same_type) {
2324
2325 if (key_type == &PyUnicode_Type && strings_are_latin) {
2326 ms.key_compare = unsafe_latin_compare;
2327 }
2328 else if (key_type == &PyLong_Type && ints_are_bounded) {
2329 ms.key_compare = unsafe_long_compare;
2330 }
2331 else if (key_type == &PyFloat_Type) {
2332 ms.key_compare = unsafe_float_compare;
2333 }
2334 else if ((ms.key_richcompare = key_type->tp_richcompare) != NULL) {
2335 ms.key_compare = unsafe_object_compare;
2336 }
Zackery Spytzebc793d2019-02-21 00:47:14 -07002337 else {
2338 ms.key_compare = safe_object_compare;
2339 }
embg1e34da42018-01-28 20:03:23 -07002340 }
2341 else {
2342 ms.key_compare = safe_object_compare;
2343 }
2344
2345 if (keys_are_in_tuples) {
2346 /* Make sure we're not dealing with tuples of tuples
2347 * (remember: here, key_type refers list [key[0] for key in keys]) */
Rémi Lapeyredd5417a2019-03-25 08:25:37 +01002348 if (key_type == &PyTuple_Type) {
embg1e34da42018-01-28 20:03:23 -07002349 ms.tuple_elem_compare = safe_object_compare;
Rémi Lapeyredd5417a2019-03-25 08:25:37 +01002350 }
2351 else {
embg1e34da42018-01-28 20:03:23 -07002352 ms.tuple_elem_compare = ms.key_compare;
Rémi Lapeyredd5417a2019-03-25 08:25:37 +01002353 }
embg1e34da42018-01-28 20:03:23 -07002354
2355 ms.key_compare = unsafe_tuple_compare;
2356 }
2357 }
2358 /* End of pre-sort check: ms is now set properly! */
2359
Daniel Stutzbach98338222010-12-02 21:55:33 +00002360 merge_init(&ms, saved_ob_size, keys != NULL);
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002362 nremaining = saved_ob_size;
2363 if (nremaining < 2)
2364 goto succeed;
Tim Peters330f9e92002-07-19 07:05:44 +00002365
Benjamin Peterson05380642010-08-23 19:35:39 +00002366 /* Reverse sort stability achieved by initially reversing the list,
2367 applying a stable forward sort, then reversing the final result. */
Daniel Stutzbach98338222010-12-02 21:55:33 +00002368 if (reverse) {
2369 if (keys != NULL)
2370 reverse_slice(&keys[0], &keys[saved_ob_size]);
2371 reverse_slice(&saved_ob_item[0], &saved_ob_item[saved_ob_size]);
2372 }
Benjamin Peterson05380642010-08-23 19:35:39 +00002373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002374 /* March over the array once, left to right, finding natural runs,
2375 * and extending short natural runs to minrun elements.
2376 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002377 minrun = merge_compute_minrun(nremaining);
2378 do {
2379 int descending;
2380 Py_ssize_t n;
Tim Peters330f9e92002-07-19 07:05:44 +00002381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002382 /* Identify next run. */
embg1e34da42018-01-28 20:03:23 -07002383 n = count_run(&ms, lo.keys, lo.keys + nremaining, &descending);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002384 if (n < 0)
2385 goto fail;
2386 if (descending)
Daniel Stutzbach98338222010-12-02 21:55:33 +00002387 reverse_sortslice(&lo, n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002388 /* If short, extend to min(minrun, nremaining). */
2389 if (n < minrun) {
2390 const Py_ssize_t force = nremaining <= minrun ?
2391 nremaining : minrun;
embg1e34da42018-01-28 20:03:23 -07002392 if (binarysort(&ms, lo, lo.keys + force, lo.keys + n) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002393 goto fail;
2394 n = force;
2395 }
2396 /* Push run onto pending-runs stack, and maybe merge. */
2397 assert(ms.n < MAX_MERGE_PENDING);
2398 ms.pending[ms.n].base = lo;
2399 ms.pending[ms.n].len = n;
2400 ++ms.n;
2401 if (merge_collapse(&ms) < 0)
2402 goto fail;
2403 /* Advance to find next run. */
Daniel Stutzbach98338222010-12-02 21:55:33 +00002404 sortslice_advance(&lo, n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002405 nremaining -= n;
2406 } while (nremaining);
Tim Peters330f9e92002-07-19 07:05:44 +00002407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002408 if (merge_force_collapse(&ms) < 0)
2409 goto fail;
2410 assert(ms.n == 1);
Daniel Stutzbach98338222010-12-02 21:55:33 +00002411 assert(keys == NULL
2412 ? ms.pending[0].base.keys == saved_ob_item
2413 : ms.pending[0].base.keys == &keys[0]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002414 assert(ms.pending[0].len == saved_ob_size);
Daniel Stutzbach98338222010-12-02 21:55:33 +00002415 lo = ms.pending[0].base;
Tim Petersa64dc242002-08-01 02:13:36 +00002416
2417succeed:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002418 result = Py_None;
Tim Peters330f9e92002-07-19 07:05:44 +00002419fail:
Daniel Stutzbach98338222010-12-02 21:55:33 +00002420 if (keys != NULL) {
2421 for (i = 0; i < saved_ob_size; i++)
2422 Py_DECREF(keys[i]);
Benjamin Petersonef87f8c2014-03-14 21:54:31 -05002423 if (saved_ob_size >= MERGESTATE_TEMP_SIZE/2)
Victor Stinner00d7abd2020-12-01 09:56:42 +01002424 PyMem_Free(keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002425 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002426
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002427 if (self->allocated != -1 && result != NULL) {
2428 /* The user mucked with the list during the sort,
2429 * and we don't already have another error to report.
2430 */
2431 PyErr_SetString(PyExc_ValueError, "list modified during sort");
2432 result = NULL;
2433 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002435 if (reverse && saved_ob_size > 1)
2436 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002437
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002438 merge_freemem(&ms);
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002439
Daniel Stutzbach98338222010-12-02 21:55:33 +00002440keyfunc_fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002441 final_ob_item = self->ob_item;
2442 i = Py_SIZE(self);
Victor Stinner60ac6ed2020-02-07 23:18:08 +01002443 Py_SET_SIZE(self, saved_ob_size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002444 self->ob_item = saved_ob_item;
2445 self->allocated = saved_allocated;
2446 if (final_ob_item != NULL) {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002447 /* we cannot use _list_clear() for this because it does not
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002448 guarantee that the list is really empty when it returns */
2449 while (--i >= 0) {
2450 Py_XDECREF(final_ob_item[i]);
2451 }
Victor Stinner00d7abd2020-12-01 09:56:42 +01002452 PyMem_Free(final_ob_item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002453 }
2454 Py_XINCREF(result);
2455 return result;
Guido van Rossum3f236de1996-12-10 23:55:39 +00002456}
Tim Peters330f9e92002-07-19 07:05:44 +00002457#undef IFLT
Tim Peters66860f62002-08-04 17:47:26 +00002458#undef ISLT
Tim Peters330f9e92002-07-19 07:05:44 +00002459
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002460int
Fred Drakea2f55112000-07-09 15:16:51 +00002461PyList_Sort(PyObject *v)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002462{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002463 if (v == NULL || !PyList_Check(v)) {
2464 PyErr_BadInternalCall();
2465 return -1;
2466 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002467 v = list_sort_impl((PyListObject *)v, NULL, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002468 if (v == NULL)
2469 return -1;
2470 Py_DECREF(v);
2471 return 0;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002472}
2473
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002474/*[clinic input]
2475list.reverse
2476
2477Reverse *IN PLACE*.
2478[clinic start generated code]*/
2479
Guido van Rossumb86c5492001-02-12 22:06:02 +00002480static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002481list_reverse_impl(PyListObject *self)
2482/*[clinic end generated code: output=482544fc451abea9 input=eefd4c3ae1bc9887]*/
Guido van Rossumb86c5492001-02-12 22:06:02 +00002483{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002484 if (Py_SIZE(self) > 1)
2485 reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
2486 Py_RETURN_NONE;
Guido van Rossumed98d481991-03-06 13:07:53 +00002487}
2488
Guido van Rossum84c76f51990-10-30 13:32:20 +00002489int
Fred Drakea2f55112000-07-09 15:16:51 +00002490PyList_Reverse(PyObject *v)
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002491{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002492 PyListObject *self = (PyListObject *)v;
Tim Peters6063e262002-08-08 01:06:39 +00002493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002494 if (v == NULL || !PyList_Check(v)) {
2495 PyErr_BadInternalCall();
2496 return -1;
2497 }
2498 if (Py_SIZE(self) > 1)
2499 reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
2500 return 0;
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002501}
2502
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002503PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00002504PyList_AsTuple(PyObject *v)
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002505{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002506 if (v == NULL || !PyList_Check(v)) {
2507 PyErr_BadInternalCall();
2508 return NULL;
2509 }
Sergey Fedoseev234531b2019-02-25 21:59:12 +05002510 return _PyTuple_FromArray(((PyListObject *)v)->ob_item, Py_SIZE(v));
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002511}
2512
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002513/*[clinic input]
2514list.index
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002515
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002516 value: object
Serhiy Storchaka80ec8362017-03-19 19:37:40 +02002517 start: slice_index(accept={int}) = 0
2518 stop: slice_index(accept={int}, c_default="PY_SSIZE_T_MAX") = sys.maxsize
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002519 /
2520
2521Return first index of value.
2522
2523Raises ValueError if the value is not present.
2524[clinic start generated code]*/
2525
2526static PyObject *
2527list_index_impl(PyListObject *self, PyObject *value, Py_ssize_t start,
2528 Py_ssize_t stop)
Serhiy Storchaka80ec8362017-03-19 19:37:40 +02002529/*[clinic end generated code: output=ec51b88787e4e481 input=40ec5826303a0eb1]*/
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002530{
2531 Py_ssize_t i;
2532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002533 if (start < 0) {
2534 start += Py_SIZE(self);
2535 if (start < 0)
2536 start = 0;
2537 }
2538 if (stop < 0) {
2539 stop += Py_SIZE(self);
2540 if (stop < 0)
2541 stop = 0;
2542 }
2543 for (i = start; i < stop && i < Py_SIZE(self); i++) {
Zackery Spytzd9e561d2019-12-30 12:32:58 -07002544 PyObject *obj = self->ob_item[i];
2545 Py_INCREF(obj);
2546 int cmp = PyObject_RichCompareBool(obj, value, Py_EQ);
2547 Py_DECREF(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002548 if (cmp > 0)
2549 return PyLong_FromSsize_t(i);
2550 else if (cmp < 0)
2551 return NULL;
2552 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002553 PyErr_Format(PyExc_ValueError, "%R is not in list", value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002554 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002555}
2556
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002557/*[clinic input]
2558list.count
2559
2560 value: object
2561 /
2562
2563Return number of occurrences of value.
2564[clinic start generated code]*/
2565
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002566static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002567list_count(PyListObject *self, PyObject *value)
2568/*[clinic end generated code: output=b1f5d284205ae714 input=3bdc3a5e6f749565]*/
Guido van Rossume6f7d181991-10-20 20:20:40 +00002569{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002570 Py_ssize_t count = 0;
2571 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002573 for (i = 0; i < Py_SIZE(self); i++) {
Zackery Spytzd9e561d2019-12-30 12:32:58 -07002574 PyObject *obj = self->ob_item[i];
Dong-hee Na14d80d02020-01-23 02:36:54 +09002575 if (obj == value) {
2576 count++;
2577 continue;
2578 }
Zackery Spytzd9e561d2019-12-30 12:32:58 -07002579 Py_INCREF(obj);
2580 int cmp = PyObject_RichCompareBool(obj, value, Py_EQ);
2581 Py_DECREF(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002582 if (cmp > 0)
2583 count++;
2584 else if (cmp < 0)
2585 return NULL;
2586 }
2587 return PyLong_FromSsize_t(count);
Guido van Rossume6f7d181991-10-20 20:20:40 +00002588}
2589
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002590/*[clinic input]
2591list.remove
2592
2593 value: object
2594 /
2595
2596Remove first occurrence of value.
2597
2598Raises ValueError if the value is not present.
2599[clinic start generated code]*/
2600
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002601static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002602list_remove(PyListObject *self, PyObject *value)
2603/*[clinic end generated code: output=f087e1951a5e30d1 input=2dc2ba5bb2fb1f82]*/
Guido van Rossumed98d481991-03-06 13:07:53 +00002604{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002605 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002607 for (i = 0; i < Py_SIZE(self); i++) {
Zackery Spytzd9e561d2019-12-30 12:32:58 -07002608 PyObject *obj = self->ob_item[i];
2609 Py_INCREF(obj);
2610 int cmp = PyObject_RichCompareBool(obj, value, Py_EQ);
2611 Py_DECREF(obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002612 if (cmp > 0) {
2613 if (list_ass_slice(self, i, i+1,
2614 (PyObject *)NULL) == 0)
2615 Py_RETURN_NONE;
2616 return NULL;
2617 }
2618 else if (cmp < 0)
2619 return NULL;
2620 }
2621 PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
2622 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002623}
2624
Jeremy Hylton8caad492000-06-23 14:18:11 +00002625static int
2626list_traverse(PyListObject *o, visitproc visit, void *arg)
2627{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002628 Py_ssize_t i;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002630 for (i = Py_SIZE(o); --i >= 0; )
2631 Py_VISIT(o->ob_item[i]);
2632 return 0;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002633}
2634
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002635static PyObject *
2636list_richcompare(PyObject *v, PyObject *w, int op)
2637{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002638 PyListObject *vl, *wl;
2639 Py_ssize_t i;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002640
Brian Curtindfc80e32011-08-10 20:28:54 -05002641 if (!PyList_Check(v) || !PyList_Check(w))
2642 Py_RETURN_NOTIMPLEMENTED;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002643
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002644 vl = (PyListObject *)v;
2645 wl = (PyListObject *)w;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002647 if (Py_SIZE(vl) != Py_SIZE(wl) && (op == Py_EQ || op == Py_NE)) {
2648 /* Shortcut: if the lengths differ, the lists differ */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002649 if (op == Py_EQ)
stratakise8b19652017-11-02 11:32:54 +01002650 Py_RETURN_FALSE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002651 else
stratakise8b19652017-11-02 11:32:54 +01002652 Py_RETURN_TRUE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002653 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002655 /* Search for the first index where items are different */
2656 for (i = 0; i < Py_SIZE(vl) && i < Py_SIZE(wl); i++) {
Dong-hee Na2d5bf562019-12-31 10:04:22 +09002657 PyObject *vitem = vl->ob_item[i];
2658 PyObject *witem = wl->ob_item[i];
Inada Naokidfef9862019-12-31 10:58:37 +09002659 if (vitem == witem) {
2660 continue;
2661 }
Dong-hee Na2d5bf562019-12-31 10:04:22 +09002662
2663 Py_INCREF(vitem);
2664 Py_INCREF(witem);
sweeneydebe7ead62020-02-26 02:00:35 -05002665 int k = PyObject_RichCompareBool(vitem, witem, Py_EQ);
Dong-hee Na2d5bf562019-12-31 10:04:22 +09002666 Py_DECREF(vitem);
2667 Py_DECREF(witem);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002668 if (k < 0)
2669 return NULL;
2670 if (!k)
2671 break;
2672 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002673
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002674 if (i >= Py_SIZE(vl) || i >= Py_SIZE(wl)) {
2675 /* No more items to compare -- compare sizes */
stratakise8b19652017-11-02 11:32:54 +01002676 Py_RETURN_RICHCOMPARE(Py_SIZE(vl), Py_SIZE(wl), op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002677 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002678
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002679 /* We have an item that differs -- shortcuts for EQ/NE */
2680 if (op == Py_EQ) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02002681 Py_RETURN_FALSE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002682 }
2683 if (op == Py_NE) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02002684 Py_RETURN_TRUE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002685 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002686
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002687 /* Compare the final item again using the proper operator */
2688 return PyObject_RichCompare(vl->ob_item[i], wl->ob_item[i], op);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002689}
2690
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002691/*[clinic input]
2692list.__init__
2693
2694 iterable: object(c_default="NULL") = ()
2695 /
2696
2697Built-in mutable sequence.
2698
2699If no argument is given, the constructor creates a new empty list.
2700The argument must be an iterable if specified.
2701[clinic start generated code]*/
2702
Tim Peters6d6c1a32001-08-02 04:15:00 +00002703static int
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002704list___init___impl(PyListObject *self, PyObject *iterable)
2705/*[clinic end generated code: output=0f3c21379d01de48 input=b3f3fe7206af8f6b]*/
Tim Peters6d6c1a32001-08-02 04:15:00 +00002706{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002707 /* Verify list invariants established by PyType_GenericAlloc() */
2708 assert(0 <= Py_SIZE(self));
2709 assert(Py_SIZE(self) <= self->allocated || self->allocated == -1);
2710 assert(self->ob_item != NULL ||
2711 self->allocated == 0 || self->allocated == -1);
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002712
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002713 /* Empty previous contents */
2714 if (self->ob_item != NULL) {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002715 (void)_list_clear(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002716 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002717 if (iterable != NULL) {
Pablo Galindo372d7052018-10-28 20:16:26 +00002718 if (_PyObject_HasLen(iterable)) {
2719 Py_ssize_t iter_len = PyObject_Size(iterable);
2720 if (iter_len == -1) {
2721 if (!PyErr_ExceptionMatches(PyExc_TypeError)) {
2722 return -1;
2723 }
2724 PyErr_Clear();
2725 }
2726 if (iter_len > 0 && self->ob_item == NULL
2727 && list_preallocate_exact(self, iter_len)) {
2728 return -1;
2729 }
2730 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002731 PyObject *rv = list_extend(self, iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002732 if (rv == NULL)
2733 return -1;
2734 Py_DECREF(rv);
2735 }
2736 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002737}
2738
Petr Viktorince105542020-03-30 14:16:16 +02002739static PyObject *
2740list_vectorcall(PyObject *type, PyObject * const*args,
2741 size_t nargsf, PyObject *kwnames)
2742{
2743 if (!_PyArg_NoKwnames("list", kwnames)) {
2744 return NULL;
2745 }
2746 Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
2747 if (!_PyArg_CheckPositional("list", nargs, 0, 1)) {
2748 return NULL;
2749 }
2750
2751 assert(PyType_Check(type));
2752 PyObject *list = PyType_GenericAlloc((PyTypeObject *)type, 0);
2753 if (list == NULL) {
2754 return NULL;
2755 }
2756 if (nargs) {
2757 if (list___init___impl((PyListObject *)list, args[0])) {
2758 Py_DECREF(list);
2759 return NULL;
2760 }
2761 }
2762 return list;
2763}
2764
2765
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002766/*[clinic input]
2767list.__sizeof__
2768
2769Return the size of the list in memory, in bytes.
2770[clinic start generated code]*/
2771
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002772static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002773list___sizeof___impl(PyListObject *self)
2774/*[clinic end generated code: output=3417541f95f9a53e input=b8030a5d5ce8a187]*/
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002775{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002776 Py_ssize_t res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002777
Serhiy Storchaka5c4064e2015-12-19 20:05:25 +02002778 res = _PyObject_SIZE(Py_TYPE(self)) + self->allocated * sizeof(void*);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002779 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002780}
2781
Raymond Hettinger1021c442003-11-07 15:38:09 +00002782static PyObject *list_iter(PyObject *seq);
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002783static PyObject *list_subscript(PyListObject*, PyObject*);
2784
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002785static PyMethodDef list_methods[] = {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002786 {"__getitem__", (PyCFunction)list_subscript, METH_O|METH_COEXIST, "x.__getitem__(y) <==> x[y]"},
2787 LIST___REVERSED___METHODDEF
2788 LIST___SIZEOF___METHODDEF
2789 LIST_CLEAR_METHODDEF
2790 LIST_COPY_METHODDEF
2791 LIST_APPEND_METHODDEF
2792 LIST_INSERT_METHODDEF
2793 LIST_EXTEND_METHODDEF
2794 LIST_POP_METHODDEF
2795 LIST_REMOVE_METHODDEF
2796 LIST_INDEX_METHODDEF
2797 LIST_COUNT_METHODDEF
2798 LIST_REVERSE_METHODDEF
2799 LIST_SORT_METHODDEF
Guido van Rossum48b069a2020-04-07 09:50:06 -07002800 {"__class_getitem__", (PyCFunction)Py_GenericAlias, METH_O|METH_CLASS, PyDoc_STR("See PEP 585")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002801 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002802};
2803
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002804static PySequenceMethods list_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002805 (lenfunc)list_length, /* sq_length */
2806 (binaryfunc)list_concat, /* sq_concat */
2807 (ssizeargfunc)list_repeat, /* sq_repeat */
2808 (ssizeargfunc)list_item, /* sq_item */
2809 0, /* sq_slice */
2810 (ssizeobjargproc)list_ass_item, /* sq_ass_item */
2811 0, /* sq_ass_slice */
2812 (objobjproc)list_contains, /* sq_contains */
2813 (binaryfunc)list_inplace_concat, /* sq_inplace_concat */
2814 (ssizeargfunc)list_inplace_repeat, /* sq_inplace_repeat */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002815};
2816
Jeremy Hyltona4b4c3b2002-07-13 03:51:17 +00002817static PyObject *
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002818list_subscript(PyListObject* self, PyObject* item)
2819{
Victor Stinnera15e2602020-04-08 02:01:56 +02002820 if (_PyIndex_Check(item)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002821 Py_ssize_t i;
2822 i = PyNumber_AsSsize_t(item, PyExc_IndexError);
2823 if (i == -1 && PyErr_Occurred())
2824 return NULL;
2825 if (i < 0)
2826 i += PyList_GET_SIZE(self);
2827 return list_item(self, i);
2828 }
2829 else if (PySlice_Check(item)) {
HongWeipeng3c87a662019-09-08 18:15:56 +08002830 Py_ssize_t start, stop, step, slicelength, i;
2831 size_t cur;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002832 PyObject* result;
2833 PyObject* it;
2834 PyObject **src, **dest;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002835
Serhiy Storchakab879fe82017-04-08 09:53:51 +03002836 if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002837 return NULL;
2838 }
Serhiy Storchakab879fe82017-04-08 09:53:51 +03002839 slicelength = PySlice_AdjustIndices(Py_SIZE(self), &start, &stop,
2840 step);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002841
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002842 if (slicelength <= 0) {
2843 return PyList_New(0);
2844 }
2845 else if (step == 1) {
2846 return list_slice(self, start, stop);
2847 }
2848 else {
Sergey Fedoseev2fc46972018-08-11 18:12:07 +05002849 result = list_new_prealloc(slicelength);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002850 if (!result) return NULL;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002851
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002852 src = self->ob_item;
2853 dest = ((PyListObject *)result)->ob_item;
2854 for (cur = start, i = 0; i < slicelength;
Mark Dickinsonc7d93b72011-09-25 15:34:32 +01002855 cur += (size_t)step, i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002856 it = src[cur];
2857 Py_INCREF(it);
2858 dest[i] = it;
2859 }
Victor Stinner60ac6ed2020-02-07 23:18:08 +01002860 Py_SET_SIZE(result, slicelength);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002861 return result;
2862 }
2863 }
2864 else {
2865 PyErr_Format(PyExc_TypeError,
Terry Jan Reedyffff1442014-08-02 01:30:37 -04002866 "list indices must be integers or slices, not %.200s",
Victor Stinner58ac7002020-02-07 03:04:21 +01002867 Py_TYPE(item)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002868 return NULL;
2869 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002870}
2871
Tim Peters3b01a122002-07-19 02:35:45 +00002872static int
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002873list_ass_subscript(PyListObject* self, PyObject* item, PyObject* value)
2874{
Victor Stinnera15e2602020-04-08 02:01:56 +02002875 if (_PyIndex_Check(item)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002876 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
2877 if (i == -1 && PyErr_Occurred())
2878 return -1;
2879 if (i < 0)
2880 i += PyList_GET_SIZE(self);
2881 return list_ass_item(self, i, value);
2882 }
2883 else if (PySlice_Check(item)) {
2884 Py_ssize_t start, stop, step, slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002885
Serhiy Storchakab879fe82017-04-08 09:53:51 +03002886 if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002887 return -1;
2888 }
Serhiy Storchakab879fe82017-04-08 09:53:51 +03002889 slicelength = PySlice_AdjustIndices(Py_SIZE(self), &start, &stop,
2890 step);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002892 if (step == 1)
2893 return list_ass_slice(self, start, stop, value);
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002895 /* Make sure s[5:2] = [..] inserts at the right place:
2896 before 5, not before 2. */
2897 if ((step < 0 && start < stop) ||
2898 (step > 0 && start > stop))
2899 stop = start;
Thomas Woutersed03b412007-08-28 21:37:11 +00002900
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002901 if (value == NULL) {
2902 /* delete slice */
2903 PyObject **garbage;
2904 size_t cur;
2905 Py_ssize_t i;
Victor Stinner35f28032013-11-21 12:16:35 +01002906 int res;
Tim Peters3b01a122002-07-19 02:35:45 +00002907
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002908 if (slicelength <= 0)
2909 return 0;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002910
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002911 if (step < 0) {
2912 stop = start + 1;
2913 start = stop + step*(slicelength - 1) - 1;
2914 step = -step;
2915 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002916
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002917 garbage = (PyObject**)
Victor Stinner00d7abd2020-12-01 09:56:42 +01002918 PyMem_Malloc(slicelength*sizeof(PyObject*));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002919 if (!garbage) {
2920 PyErr_NoMemory();
2921 return -1;
2922 }
Tim Peters3b01a122002-07-19 02:35:45 +00002923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002924 /* drawing pictures might help understand these for
2925 loops. Basically, we memmove the parts of the
2926 list that are *not* part of the slice: step-1
2927 items for each item that is part of the slice,
2928 and then tail end of the list that was not
2929 covered by the slice */
2930 for (cur = start, i = 0;
2931 cur < (size_t)stop;
2932 cur += step, i++) {
2933 Py_ssize_t lim = step - 1;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002934
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002935 garbage[i] = PyList_GET_ITEM(self, cur);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002936
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002937 if (cur + step >= (size_t)Py_SIZE(self)) {
2938 lim = Py_SIZE(self) - cur - 1;
2939 }
Michael W. Hudson56796f62002-07-29 14:35:04 +00002940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002941 memmove(self->ob_item + cur - i,
2942 self->ob_item + cur + 1,
2943 lim * sizeof(PyObject *));
2944 }
Mark Dickinsonc7d93b72011-09-25 15:34:32 +01002945 cur = start + (size_t)slicelength * step;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002946 if (cur < (size_t)Py_SIZE(self)) {
2947 memmove(self->ob_item + cur - slicelength,
2948 self->ob_item + cur,
2949 (Py_SIZE(self) - cur) *
2950 sizeof(PyObject *));
2951 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002952
Victor Stinner60ac6ed2020-02-07 23:18:08 +01002953 Py_SET_SIZE(self, Py_SIZE(self) - slicelength);
Victor Stinner35f28032013-11-21 12:16:35 +01002954 res = list_resize(self, Py_SIZE(self));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002956 for (i = 0; i < slicelength; i++) {
2957 Py_DECREF(garbage[i]);
2958 }
Victor Stinner00d7abd2020-12-01 09:56:42 +01002959 PyMem_Free(garbage);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002960
Victor Stinner35f28032013-11-21 12:16:35 +01002961 return res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002962 }
2963 else {
2964 /* assign slice */
2965 PyObject *ins, *seq;
2966 PyObject **garbage, **seqitems, **selfitems;
HongWeipeng3c87a662019-09-08 18:15:56 +08002967 Py_ssize_t i;
2968 size_t cur;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002970 /* protect against a[::-1] = a */
2971 if (self == (PyListObject*)value) {
2972 seq = list_slice((PyListObject*)value, 0,
2973 PyList_GET_SIZE(value));
2974 }
2975 else {
2976 seq = PySequence_Fast(value,
2977 "must assign iterable "
2978 "to extended slice");
2979 }
2980 if (!seq)
2981 return -1;
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002982
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002983 if (PySequence_Fast_GET_SIZE(seq) != slicelength) {
2984 PyErr_Format(PyExc_ValueError,
2985 "attempt to assign sequence of "
2986 "size %zd to extended slice of "
2987 "size %zd",
2988 PySequence_Fast_GET_SIZE(seq),
2989 slicelength);
2990 Py_DECREF(seq);
2991 return -1;
2992 }
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002994 if (!slicelength) {
2995 Py_DECREF(seq);
2996 return 0;
2997 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002999 garbage = (PyObject**)
Victor Stinner00d7abd2020-12-01 09:56:42 +01003000 PyMem_Malloc(slicelength*sizeof(PyObject*));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003001 if (!garbage) {
3002 Py_DECREF(seq);
3003 PyErr_NoMemory();
3004 return -1;
3005 }
Tim Peters3b01a122002-07-19 02:35:45 +00003006
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003007 selfitems = self->ob_item;
3008 seqitems = PySequence_Fast_ITEMS(seq);
3009 for (cur = start, i = 0; i < slicelength;
Mark Dickinsonc7d93b72011-09-25 15:34:32 +01003010 cur += (size_t)step, i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003011 garbage[i] = selfitems[cur];
3012 ins = seqitems[i];
3013 Py_INCREF(ins);
3014 selfitems[cur] = ins;
3015 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00003016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003017 for (i = 0; i < slicelength; i++) {
3018 Py_DECREF(garbage[i]);
3019 }
Tim Peters3b01a122002-07-19 02:35:45 +00003020
Victor Stinner00d7abd2020-12-01 09:56:42 +01003021 PyMem_Free(garbage);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003022 Py_DECREF(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00003023
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003024 return 0;
3025 }
3026 }
3027 else {
3028 PyErr_Format(PyExc_TypeError,
Terry Jan Reedyffff1442014-08-02 01:30:37 -04003029 "list indices must be integers or slices, not %.200s",
Victor Stinner58ac7002020-02-07 03:04:21 +01003030 Py_TYPE(item)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003031 return -1;
3032 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00003033}
3034
3035static PyMappingMethods list_as_mapping = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003036 (lenfunc)list_length,
3037 (binaryfunc)list_subscript,
3038 (objobjargproc)list_ass_subscript
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00003039};
3040
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003041PyTypeObject PyList_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003042 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3043 "list",
3044 sizeof(PyListObject),
3045 0,
3046 (destructor)list_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003047 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003048 0, /* tp_getattr */
3049 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003050 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003051 (reprfunc)list_repr, /* tp_repr */
3052 0, /* tp_as_number */
3053 &list_as_sequence, /* tp_as_sequence */
3054 &list_as_mapping, /* tp_as_mapping */
Georg Brandl00da4e02010-10-18 07:32:48 +00003055 PyObject_HashNotImplemented, /* tp_hash */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003056 0, /* tp_call */
3057 0, /* tp_str */
3058 PyObject_GenericGetAttr, /* tp_getattro */
3059 0, /* tp_setattro */
3060 0, /* tp_as_buffer */
3061 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Brandt Bucher145bf262021-02-26 14:51:55 -08003062 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LIST_SUBCLASS |
Mark Shannon069e81a2021-04-30 09:50:28 +01003063 _Py_TPFLAGS_MATCH_SELF | Py_TPFLAGS_SEQUENCE, /* tp_flags */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02003064 list___init____doc__, /* tp_doc */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003065 (traverseproc)list_traverse, /* tp_traverse */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02003066 (inquiry)_list_clear, /* tp_clear */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003067 list_richcompare, /* tp_richcompare */
3068 0, /* tp_weaklistoffset */
3069 list_iter, /* tp_iter */
3070 0, /* tp_iternext */
3071 list_methods, /* tp_methods */
3072 0, /* tp_members */
3073 0, /* tp_getset */
3074 0, /* tp_base */
3075 0, /* tp_dict */
3076 0, /* tp_descr_get */
3077 0, /* tp_descr_set */
3078 0, /* tp_dictoffset */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02003079 (initproc)list___init__, /* tp_init */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003080 PyType_GenericAlloc, /* tp_alloc */
3081 PyType_GenericNew, /* tp_new */
3082 PyObject_GC_Del, /* tp_free */
Petr Viktorince105542020-03-30 14:16:16 +02003083 .tp_vectorcall = list_vectorcall,
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003084};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00003085
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00003086/*********************** List Iterator **************************/
3087
3088typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003089 PyObject_HEAD
Victor Stinner7660b882013-06-24 23:59:24 +02003090 Py_ssize_t it_index;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003091 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00003092} listiterobject;
3093
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003094static void listiter_dealloc(listiterobject *);
3095static int listiter_traverse(listiterobject *, visitproc, void *);
3096static PyObject *listiter_next(listiterobject *);
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303097static PyObject *listiter_len(listiterobject *, PyObject *);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003098static PyObject *listiter_reduce_general(void *_it, int forward);
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303099static PyObject *listiter_reduce(listiterobject *, PyObject *);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003100static PyObject *listiter_setstate(listiterobject *, PyObject *state);
Raymond Hettinger435bf582004-03-18 22:43:10 +00003101
Armin Rigof5b3e362006-02-11 21:32:43 +00003102PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003103PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
3104PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00003105
3106static PyMethodDef listiter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003107 {"__length_hint__", (PyCFunction)listiter_len, METH_NOARGS, length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003108 {"__reduce__", (PyCFunction)listiter_reduce, METH_NOARGS, reduce_doc},
3109 {"__setstate__", (PyCFunction)listiter_setstate, METH_O, setstate_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003110 {NULL, NULL} /* sentinel */
Raymond Hettinger435bf582004-03-18 22:43:10 +00003111};
3112
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00003113PyTypeObject PyListIter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003114 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3115 "list_iterator", /* tp_name */
3116 sizeof(listiterobject), /* tp_basicsize */
3117 0, /* tp_itemsize */
3118 /* methods */
3119 (destructor)listiter_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003120 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003121 0, /* tp_getattr */
3122 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003123 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003124 0, /* tp_repr */
3125 0, /* tp_as_number */
3126 0, /* tp_as_sequence */
3127 0, /* tp_as_mapping */
3128 0, /* tp_hash */
3129 0, /* tp_call */
3130 0, /* tp_str */
3131 PyObject_GenericGetAttr, /* tp_getattro */
3132 0, /* tp_setattro */
3133 0, /* tp_as_buffer */
3134 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3135 0, /* tp_doc */
3136 (traverseproc)listiter_traverse, /* tp_traverse */
3137 0, /* tp_clear */
3138 0, /* tp_richcompare */
3139 0, /* tp_weaklistoffset */
3140 PyObject_SelfIter, /* tp_iter */
3141 (iternextfunc)listiter_next, /* tp_iternext */
3142 listiter_methods, /* tp_methods */
3143 0, /* tp_members */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00003144};
Raymond Hettinger1021c442003-11-07 15:38:09 +00003145
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003146
3147static PyObject *
3148list_iter(PyObject *seq)
3149{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003150 listiterobject *it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003152 if (!PyList_Check(seq)) {
3153 PyErr_BadInternalCall();
3154 return NULL;
3155 }
3156 it = PyObject_GC_New(listiterobject, &PyListIter_Type);
3157 if (it == NULL)
3158 return NULL;
3159 it->it_index = 0;
3160 Py_INCREF(seq);
3161 it->it_seq = (PyListObject *)seq;
3162 _PyObject_GC_TRACK(it);
3163 return (PyObject *)it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003164}
3165
3166static void
3167listiter_dealloc(listiterobject *it)
3168{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003169 _PyObject_GC_UNTRACK(it);
3170 Py_XDECREF(it->it_seq);
3171 PyObject_GC_Del(it);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003172}
3173
3174static int
3175listiter_traverse(listiterobject *it, visitproc visit, void *arg)
3176{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003177 Py_VISIT(it->it_seq);
3178 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003179}
3180
3181static PyObject *
3182listiter_next(listiterobject *it)
3183{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003184 PyListObject *seq;
3185 PyObject *item;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003186
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003187 assert(it != NULL);
3188 seq = it->it_seq;
3189 if (seq == NULL)
3190 return NULL;
3191 assert(PyList_Check(seq));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003193 if (it->it_index < PyList_GET_SIZE(seq)) {
3194 item = PyList_GET_ITEM(seq, it->it_index);
3195 ++it->it_index;
3196 Py_INCREF(item);
3197 return item;
3198 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003200 it->it_seq = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003201 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003202 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003203}
3204
3205static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303206listiter_len(listiterobject *it, PyObject *Py_UNUSED(ignored))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003207{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003208 Py_ssize_t len;
3209 if (it->it_seq) {
3210 len = PyList_GET_SIZE(it->it_seq) - it->it_index;
3211 if (len >= 0)
3212 return PyLong_FromSsize_t(len);
3213 }
3214 return PyLong_FromLong(0);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003215}
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003216
3217static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303218listiter_reduce(listiterobject *it, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003219{
3220 return listiter_reduce_general(it, 1);
3221}
3222
3223static PyObject *
3224listiter_setstate(listiterobject *it, PyObject *state)
3225{
Victor Stinner7660b882013-06-24 23:59:24 +02003226 Py_ssize_t index = PyLong_AsSsize_t(state);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003227 if (index == -1 && PyErr_Occurred())
3228 return NULL;
3229 if (it->it_seq != NULL) {
3230 if (index < 0)
3231 index = 0;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +00003232 else if (index > PyList_GET_SIZE(it->it_seq))
3233 index = PyList_GET_SIZE(it->it_seq); /* iterator exhausted */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003234 it->it_index = index;
3235 }
3236 Py_RETURN_NONE;
3237}
3238
Raymond Hettinger1021c442003-11-07 15:38:09 +00003239/*********************** List Reverse Iterator **************************/
3240
3241typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003242 PyObject_HEAD
3243 Py_ssize_t it_index;
3244 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger1021c442003-11-07 15:38:09 +00003245} listreviterobject;
3246
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003247static void listreviter_dealloc(listreviterobject *);
3248static int listreviter_traverse(listreviterobject *, visitproc, void *);
3249static PyObject *listreviter_next(listreviterobject *);
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303250static PyObject *listreviter_len(listreviterobject *, PyObject *);
3251static PyObject *listreviter_reduce(listreviterobject *, PyObject *);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003252static PyObject *listreviter_setstate(listreviterobject *, PyObject *);
Raymond Hettingeref9bf402004-03-10 10:10:42 +00003253
Raymond Hettingerf5b64112008-12-02 21:33:45 +00003254static PyMethodDef listreviter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003255 {"__length_hint__", (PyCFunction)listreviter_len, METH_NOARGS, length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003256 {"__reduce__", (PyCFunction)listreviter_reduce, METH_NOARGS, reduce_doc},
3257 {"__setstate__", (PyCFunction)listreviter_setstate, METH_O, setstate_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003258 {NULL, NULL} /* sentinel */
Raymond Hettingeref9bf402004-03-10 10:10:42 +00003259};
3260
Raymond Hettinger1021c442003-11-07 15:38:09 +00003261PyTypeObject PyListRevIter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003262 PyVarObject_HEAD_INIT(&PyType_Type, 0)
3263 "list_reverseiterator", /* tp_name */
3264 sizeof(listreviterobject), /* tp_basicsize */
3265 0, /* tp_itemsize */
3266 /* methods */
3267 (destructor)listreviter_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003268 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003269 0, /* tp_getattr */
3270 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003271 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003272 0, /* tp_repr */
3273 0, /* tp_as_number */
3274 0, /* tp_as_sequence */
3275 0, /* tp_as_mapping */
3276 0, /* tp_hash */
3277 0, /* tp_call */
3278 0, /* tp_str */
3279 PyObject_GenericGetAttr, /* tp_getattro */
3280 0, /* tp_setattro */
3281 0, /* tp_as_buffer */
3282 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
3283 0, /* tp_doc */
3284 (traverseproc)listreviter_traverse, /* tp_traverse */
3285 0, /* tp_clear */
3286 0, /* tp_richcompare */
3287 0, /* tp_weaklistoffset */
3288 PyObject_SelfIter, /* tp_iter */
3289 (iternextfunc)listreviter_next, /* tp_iternext */
3290 listreviter_methods, /* tp_methods */
3291 0,
Raymond Hettinger1021c442003-11-07 15:38:09 +00003292};
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003293
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02003294/*[clinic input]
3295list.__reversed__
3296
3297Return a reverse iterator over the list.
3298[clinic start generated code]*/
3299
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003300static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02003301list___reversed___impl(PyListObject *self)
3302/*[clinic end generated code: output=b166f073208c888c input=eadb6e17f8a6a280]*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003303{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003304 listreviterobject *it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003306 it = PyObject_GC_New(listreviterobject, &PyListRevIter_Type);
3307 if (it == NULL)
3308 return NULL;
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02003309 assert(PyList_Check(self));
3310 it->it_index = PyList_GET_SIZE(self) - 1;
3311 Py_INCREF(self);
3312 it->it_seq = self;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003313 PyObject_GC_Track(it);
3314 return (PyObject *)it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003315}
3316
3317static void
3318listreviter_dealloc(listreviterobject *it)
3319{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003320 PyObject_GC_UnTrack(it);
3321 Py_XDECREF(it->it_seq);
3322 PyObject_GC_Del(it);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003323}
3324
3325static int
3326listreviter_traverse(listreviterobject *it, visitproc visit, void *arg)
3327{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003328 Py_VISIT(it->it_seq);
3329 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003330}
3331
3332static PyObject *
3333listreviter_next(listreviterobject *it)
3334{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003335 PyObject *item;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003336 Py_ssize_t index;
3337 PyListObject *seq;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003338
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003339 assert(it != NULL);
3340 seq = it->it_seq;
3341 if (seq == NULL) {
3342 return NULL;
3343 }
3344 assert(PyList_Check(seq));
3345
3346 index = it->it_index;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003347 if (index>=0 && index < PyList_GET_SIZE(seq)) {
3348 item = PyList_GET_ITEM(seq, index);
3349 it->it_index--;
3350 Py_INCREF(item);
3351 return item;
3352 }
3353 it->it_index = -1;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03003354 it->it_seq = NULL;
3355 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003356 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003357}
3358
Raymond Hettingerf5b64112008-12-02 21:33:45 +00003359static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303360listreviter_len(listreviterobject *it, PyObject *Py_UNUSED(ignored))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003361{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003362 Py_ssize_t len = it->it_index + 1;
3363 if (it->it_seq == NULL || PyList_GET_SIZE(it->it_seq) < len)
3364 len = 0;
3365 return PyLong_FromSsize_t(len);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003366}
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003367
3368static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303369listreviter_reduce(listreviterobject *it, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003370{
3371 return listiter_reduce_general(it, 0);
3372}
3373
3374static PyObject *
3375listreviter_setstate(listreviterobject *it, PyObject *state)
3376{
3377 Py_ssize_t index = PyLong_AsSsize_t(state);
3378 if (index == -1 && PyErr_Occurred())
3379 return NULL;
3380 if (it->it_seq != NULL) {
3381 if (index < -1)
3382 index = -1;
3383 else if (index > PyList_GET_SIZE(it->it_seq) - 1)
3384 index = PyList_GET_SIZE(it->it_seq) - 1;
3385 it->it_index = index;
3386 }
3387 Py_RETURN_NONE;
3388}
3389
3390/* common pickling support */
3391
3392static PyObject *
3393listiter_reduce_general(void *_it, int forward)
3394{
Serhiy Storchakabb86bf42018-12-11 08:28:18 +02003395 _Py_IDENTIFIER(iter);
3396 _Py_IDENTIFIER(reversed);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003397 PyObject *list;
3398
3399 /* the objects are not the same, index is of different types! */
3400 if (forward) {
3401 listiterobject *it = (listiterobject *)_it;
3402 if (it->it_seq)
Serhiy Storchakabb86bf42018-12-11 08:28:18 +02003403 return Py_BuildValue("N(O)n", _PyEval_GetBuiltinId(&PyId_iter),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003404 it->it_seq, it->it_index);
3405 } else {
3406 listreviterobject *it = (listreviterobject *)_it;
3407 if (it->it_seq)
Serhiy Storchakabb86bf42018-12-11 08:28:18 +02003408 return Py_BuildValue("N(O)n", _PyEval_GetBuiltinId(&PyId_reversed),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003409 it->it_seq, it->it_index);
3410 }
3411 /* empty iterator, create an empty list */
3412 list = PyList_New(0);
3413 if (list == NULL)
3414 return NULL;
Serhiy Storchakabb86bf42018-12-11 08:28:18 +02003415 return Py_BuildValue("N(N)", _PyEval_GetBuiltinId(&PyId_iter), list);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003416}