blob: c0d0e090dfa239038544e661bfc9730f059db009 [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"
4
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00005#ifdef STDC_HEADERS
6#include <stddef.h>
7#else
8#include <sys/types.h> /* For size_t */
9#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000010
Tim Peters8d9eb102004-07-31 02:24:20 +000011/* Ensure ob_item has room for at least newsize elements, and set
12 * ob_size to newsize. If newsize > ob_size on entry, the content
13 * of the new slots at exit is undefined heap trash; it's the caller's
14 * responsiblity to overwrite them with sane values.
15 * The number of allocated elements may grow, shrink, or stay the same.
16 * Failure is impossible if newsize <= self.allocated on entry, although
17 * that partly relies on an assumption that the system realloc() never
18 * fails when passed a number of bytes <= the number of bytes last
19 * allocated (the C standard doesn't guarantee this, but it's hard to
20 * imagine a realloc implementation where it wouldn't be true).
21 * Note that self->ob_item may change, and even if newsize is less
22 * than ob_size on entry.
23 */
Guido van Rossuma46d51d1995-01-26 22:59:43 +000024static int
Martin v. Löwis18e16552006-02-15 17:27:45 +000025list_resize(PyListObject *self, Py_ssize_t newsize)
Guido van Rossuma46d51d1995-01-26 22:59:43 +000026{
Raymond Hettinger4bb95402004-02-13 11:36:39 +000027 PyObject **items;
Raymond Hettingera84f3ab2004-09-12 19:53:07 +000028 size_t new_allocated;
Martin v. Löwis18e16552006-02-15 17:27:45 +000029 Py_ssize_t allocated = self->allocated;
Tim Peters65b8b842001-05-26 05:28:40 +000030
Raymond Hettinger4bb95402004-02-13 11:36:39 +000031 /* Bypass realloc() when a previous overallocation is large enough
Raymond Hettingera84f3ab2004-09-12 19:53:07 +000032 to accommodate the newsize. If the newsize falls lower than half
33 the allocated size, then proceed with the realloc() to shrink the list.
Raymond Hettinger4bb95402004-02-13 11:36:39 +000034 */
Raymond Hettingera84f3ab2004-09-12 19:53:07 +000035 if (allocated >= newsize && newsize >= (allocated >> 1)) {
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +000036 assert(self->ob_item != NULL || newsize == 0);
Raymond Hettinger4bb95402004-02-13 11:36:39 +000037 self->ob_size = newsize;
38 return 0;
39 }
40
41 /* This over-allocates proportional to the list size, making room
Tim Peters65b8b842001-05-26 05:28:40 +000042 * for additional growth. The over-allocation is mild, but is
43 * enough to give linear-time amortized behavior over a long
44 * sequence of appends() in the presence of a poorly-performing
Raymond Hettingerab517d22004-02-14 18:34:46 +000045 * system realloc().
46 * The growth pattern is: 0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ...
Tim Peters65b8b842001-05-26 05:28:40 +000047 */
Raymond Hettingera84f3ab2004-09-12 19:53:07 +000048 new_allocated = (newsize >> 3) + (newsize < 9 ? 3 : 6) + newsize;
49 if (newsize == 0)
50 new_allocated = 0;
Raymond Hettinger4bb95402004-02-13 11:36:39 +000051 items = self->ob_item;
Raymond Hettingera84f3ab2004-09-12 19:53:07 +000052 if (new_allocated <= ((~(size_t)0) / sizeof(PyObject *)))
53 PyMem_RESIZE(items, PyObject *, new_allocated);
Raymond Hettinger4bb95402004-02-13 11:36:39 +000054 else
55 items = NULL;
56 if (items == NULL) {
57 PyErr_NoMemory();
58 return -1;
59 }
60 self->ob_item = items;
61 self->ob_size = newsize;
Raymond Hettingera84f3ab2004-09-12 19:53:07 +000062 self->allocated = new_allocated;
Raymond Hettinger4bb95402004-02-13 11:36:39 +000063 return 0;
64}
Guido van Rossuma46d51d1995-01-26 22:59:43 +000065
Raymond Hettinger0468e412004-05-05 05:37:53 +000066/* Empty list reuse scheme to save calls to malloc and free */
67#define MAXFREELISTS 80
68static PyListObject *free_lists[MAXFREELISTS];
69static int num_free_lists = 0;
70
Raymond Hettingerfb09f0e2004-10-07 03:58:07 +000071void
72PyList_Fini(void)
73{
74 PyListObject *op;
75
76 while (num_free_lists) {
77 num_free_lists--;
78 op = free_lists[num_free_lists];
79 assert(PyList_CheckExact(op));
80 PyObject_GC_Del(op);
81 }
82}
83
Guido van Rossumc0b618a1997-05-02 03:12:38 +000084PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +000085PyList_New(Py_ssize_t size)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000086{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000087 PyListObject *op;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +000088 size_t nbytes;
Tim Peters3986d4e2004-07-29 02:28:42 +000089
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000090 if (size < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +000091 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000092 return NULL;
93 }
Tim Peters7049d812004-01-18 20:31:02 +000094 nbytes = size * sizeof(PyObject *);
Guido van Rossum1e28e5e1992-08-19 16:46:30 +000095 /* Check for overflow */
Raymond Hettingerfdfe6182004-05-05 06:28:16 +000096 if (nbytes / sizeof(PyObject *) != (size_t)size)
Guido van Rossumc0b618a1997-05-02 03:12:38 +000097 return PyErr_NoMemory();
Raymond Hettinger0468e412004-05-05 05:37:53 +000098 if (num_free_lists) {
99 num_free_lists--;
100 op = free_lists[num_free_lists];
101 _Py_NewReference((PyObject *)op);
102 } else {
103 op = PyObject_GC_New(PyListObject, &PyList_Type);
104 if (op == NULL)
105 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000106 }
Raymond Hettingerfdfe6182004-05-05 06:28:16 +0000107 if (size <= 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000108 op->ob_item = NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000109 else {
Guido van Rossumb18618d2000-05-03 23:44:39 +0000110 op->ob_item = (PyObject **) PyMem_MALLOC(nbytes);
Neal Norwitza00c0b92006-06-12 02:08:41 +0000111 if (op->ob_item == NULL) {
112 Py_DECREF(op);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000113 return PyErr_NoMemory();
Neal Norwitza00c0b92006-06-12 02:08:41 +0000114 }
Tim Peters3986d4e2004-07-29 02:28:42 +0000115 memset(op->ob_item, 0, nbytes);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000116 }
Neil Schemenauere83c00e2001-08-29 23:54:21 +0000117 op->ob_size = size;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000118 op->allocated = size;
Neil Schemenauere83c00e2001-08-29 23:54:21 +0000119 _PyObject_GC_TRACK(op);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000120 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000121}
122
Martin v. Löwis18e16552006-02-15 17:27:45 +0000123Py_ssize_t
Fred Drakea2f55112000-07-09 15:16:51 +0000124PyList_Size(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000125{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000126 if (!PyList_Check(op)) {
127 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000128 return -1;
129 }
130 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000131 return ((PyListObject *)op) -> ob_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000132}
133
Raymond Hettingerfdfe6182004-05-05 06:28:16 +0000134static PyObject *indexerr = NULL;
Guido van Rossum929f1b81996-08-09 20:51:27 +0000135
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000136PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000137PyList_GetItem(PyObject *op, Py_ssize_t i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000138{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000139 if (!PyList_Check(op)) {
140 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000141 return NULL;
142 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000143 if (i < 0 || i >= ((PyListObject *)op) -> ob_size) {
Guido van Rossum929f1b81996-08-09 20:51:27 +0000144 if (indexerr == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000145 indexerr = PyString_FromString(
146 "list index out of range");
147 PyErr_SetObject(PyExc_IndexError, indexerr);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000148 return NULL;
149 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000150 return ((PyListObject *)op) -> ob_item[i];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000151}
152
153int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000154PyList_SetItem(register PyObject *op, register Py_ssize_t i,
Fred Drakea2f55112000-07-09 15:16:51 +0000155 register PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000156{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000157 register PyObject *olditem;
158 register PyObject **p;
159 if (!PyList_Check(op)) {
160 Py_XDECREF(newitem);
161 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000162 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000163 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000164 if (i < 0 || i >= ((PyListObject *)op) -> ob_size) {
165 Py_XDECREF(newitem);
166 PyErr_SetString(PyExc_IndexError,
167 "list assignment index out of range");
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000168 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000169 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000170 p = ((PyListObject *)op) -> ob_item + i;
Guido van Rossum5fe60581995-03-09 12:12:50 +0000171 olditem = *p;
172 *p = newitem;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000173 Py_XDECREF(olditem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000174 return 0;
175}
176
177static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000178ins1(PyListObject *self, Py_ssize_t where, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000179{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000180 Py_ssize_t i, n = self->ob_size;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000181 PyObject **items;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000182 if (v == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000183 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000184 return -1;
185 }
Martin v. Löwisb1ed7fa2006-04-13 07:52:27 +0000186 if (n == PY_SSIZE_T_MAX) {
Trent Micka5846642000-08-13 22:47:45 +0000187 PyErr_SetString(PyExc_OverflowError,
188 "cannot add more objects to list");
189 return -1;
190 }
Tim Petersb38e2b62004-07-29 02:29:26 +0000191
Raymond Hettingerd4ff7412004-03-15 09:01:31 +0000192 if (list_resize(self, n+1) == -1)
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000193 return -1;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000194
Guido van Rossum3a3cca52003-04-14 20:58:14 +0000195 if (where < 0) {
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000196 where += n;
Guido van Rossum3a3cca52003-04-14 20:58:14 +0000197 if (where < 0)
198 where = 0;
199 }
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000200 if (where > n)
201 where = n;
202 items = self->ob_item;
203 for (i = n; --i >= where; )
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000204 items[i+1] = items[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000205 Py_INCREF(v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000206 items[where] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000207 return 0;
208}
209
210int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000211PyList_Insert(PyObject *op, Py_ssize_t where, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000212{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000213 if (!PyList_Check(op)) {
214 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000215 return -1;
216 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000217 return ins1((PyListObject *)op, where, newitem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000218}
219
Raymond Hettinger40a03822004-04-12 13:05:09 +0000220static int
221app1(PyListObject *self, PyObject *v)
222{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000223 Py_ssize_t n = PyList_GET_SIZE(self);
Raymond Hettinger40a03822004-04-12 13:05:09 +0000224
225 assert (v != NULL);
Martin v. Löwisb1ed7fa2006-04-13 07:52:27 +0000226 if (n == PY_SSIZE_T_MAX) {
Raymond Hettinger40a03822004-04-12 13:05:09 +0000227 PyErr_SetString(PyExc_OverflowError,
228 "cannot add more objects to list");
229 return -1;
230 }
231
232 if (list_resize(self, n+1) == -1)
233 return -1;
234
235 Py_INCREF(v);
236 PyList_SET_ITEM(self, n, v);
237 return 0;
238}
239
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000240int
Fred Drakea2f55112000-07-09 15:16:51 +0000241PyList_Append(PyObject *op, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000242{
Raymond Hettingerfdfe6182004-05-05 06:28:16 +0000243 if (PyList_Check(op) && (newitem != NULL))
244 return app1((PyListObject *)op, newitem);
245 PyErr_BadInternalCall();
246 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000247}
248
249/* Methods */
250
251static void
Fred Drakea2f55112000-07-09 15:16:51 +0000252list_dealloc(PyListObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000253{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000254 Py_ssize_t i;
Guido van Rossumff413af2002-03-28 20:34:59 +0000255 PyObject_GC_UnTrack(op);
Guido van Rossumd724b232000-03-13 16:01:29 +0000256 Py_TRASHCAN_SAFE_BEGIN(op)
Jack Jansen7874d1f1995-01-19 12:09:27 +0000257 if (op->ob_item != NULL) {
Guido van Rossumfa717011999-06-09 15:19:34 +0000258 /* Do it backwards, for Christian Tismer.
259 There's a simple test case where somehow this reduces
260 thrashing when a *very* large list is created and
261 immediately deleted. */
262 i = op->ob_size;
263 while (--i >= 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000264 Py_XDECREF(op->ob_item[i]);
Jack Jansen7874d1f1995-01-19 12:09:27 +0000265 }
Guido van Rossumb18618d2000-05-03 23:44:39 +0000266 PyMem_FREE(op->ob_item);
Jack Jansen7874d1f1995-01-19 12:09:27 +0000267 }
Raymond Hettinger0468e412004-05-05 05:37:53 +0000268 if (num_free_lists < MAXFREELISTS && PyList_CheckExact(op))
269 free_lists[num_free_lists++] = op;
Tim Petersb38e2b62004-07-29 02:29:26 +0000270 else
271 op->ob_type->tp_free((PyObject *)op);
Guido van Rossumd724b232000-03-13 16:01:29 +0000272 Py_TRASHCAN_SAFE_END(op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000273}
274
Guido van Rossum90933611991-06-07 16:10:43 +0000275static int
Fred Drakea2f55112000-07-09 15:16:51 +0000276list_print(PyListObject *op, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000277{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000278 int rc;
279 Py_ssize_t i;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000280
Martin v. Löwis18e16552006-02-15 17:27:45 +0000281 rc = Py_ReprEnter((PyObject*)op);
282 if (rc != 0) {
283 if (rc < 0)
284 return rc;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000285 fprintf(fp, "[...]");
286 return 0;
287 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000288 fprintf(fp, "[");
Guido van Rossum90933611991-06-07 16:10:43 +0000289 for (i = 0; i < op->ob_size; i++) {
290 if (i > 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000291 fprintf(fp, ", ");
Guido van Rossumfb376de1998-04-10 22:47:27 +0000292 if (PyObject_Print(op->ob_item[i], fp, 0) != 0) {
293 Py_ReprLeave((PyObject *)op);
Guido van Rossum90933611991-06-07 16:10:43 +0000294 return -1;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000295 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000296 }
297 fprintf(fp, "]");
Guido van Rossumfb376de1998-04-10 22:47:27 +0000298 Py_ReprLeave((PyObject *)op);
Guido van Rossum90933611991-06-07 16:10:43 +0000299 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000300}
301
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000302static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000303list_repr(PyListObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000304{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000305 Py_ssize_t i;
Tim Petersa7259592001-06-16 05:11:17 +0000306 PyObject *s, *temp;
307 PyObject *pieces = NULL, *result = NULL;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000308
309 i = Py_ReprEnter((PyObject*)v);
310 if (i != 0) {
Tim Petersa7259592001-06-16 05:11:17 +0000311 return i > 0 ? PyString_FromString("[...]") : NULL;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000312 }
Tim Petersa7259592001-06-16 05:11:17 +0000313
314 if (v->ob_size == 0) {
315 result = PyString_FromString("[]");
316 goto Done;
317 }
318
319 pieces = PyList_New(0);
320 if (pieces == NULL)
321 goto Done;
322
323 /* Do repr() on each element. Note that this may mutate the list,
324 so must refetch the list size on each iteration. */
325 for (i = 0; i < v->ob_size; ++i) {
326 int status;
327 s = PyObject_Repr(v->ob_item[i]);
328 if (s == NULL)
329 goto Done;
330 status = PyList_Append(pieces, s);
331 Py_DECREF(s); /* append created a new ref */
332 if (status < 0)
333 goto Done;
334 }
335
336 /* Add "[]" decorations to the first and last items. */
337 assert(PyList_GET_SIZE(pieces) > 0);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000338 s = PyString_FromString("[");
Tim Petersa7259592001-06-16 05:11:17 +0000339 if (s == NULL)
340 goto Done;
341 temp = PyList_GET_ITEM(pieces, 0);
342 PyString_ConcatAndDel(&s, temp);
343 PyList_SET_ITEM(pieces, 0, s);
344 if (s == NULL)
345 goto Done;
346
347 s = PyString_FromString("]");
348 if (s == NULL)
349 goto Done;
350 temp = PyList_GET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1);
351 PyString_ConcatAndDel(&temp, s);
352 PyList_SET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1, temp);
353 if (temp == NULL)
354 goto Done;
355
356 /* Paste them all together with ", " between. */
357 s = PyString_FromString(", ");
358 if (s == NULL)
359 goto Done;
360 result = _PyString_Join(s, pieces);
Tim Peters3b01a122002-07-19 02:35:45 +0000361 Py_DECREF(s);
Tim Petersa7259592001-06-16 05:11:17 +0000362
363Done:
364 Py_XDECREF(pieces);
Guido van Rossumfb376de1998-04-10 22:47:27 +0000365 Py_ReprLeave((PyObject *)v);
Tim Petersa7259592001-06-16 05:11:17 +0000366 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000367}
368
Martin v. Löwis18e16552006-02-15 17:27:45 +0000369static Py_ssize_t
Fred Drakea2f55112000-07-09 15:16:51 +0000370list_length(PyListObject *a)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000371{
372 return a->ob_size;
373}
374
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000375static int
Fred Drakea2f55112000-07-09 15:16:51 +0000376list_contains(PyListObject *a, PyObject *el)
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000377{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000378 Py_ssize_t i;
379 int cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000380
Raymond Hettingeraae59992002-09-05 14:23:49 +0000381 for (i = 0, cmp = 0 ; cmp == 0 && i < a->ob_size; ++i)
382 cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i),
Guido van Rossum65e1cea2001-01-17 22:11:59 +0000383 Py_EQ);
Neal Norwitzbb9c5f52002-09-05 21:32:55 +0000384 return cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000385}
386
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000387static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000388list_item(PyListObject *a, Py_ssize_t i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000389{
390 if (i < 0 || i >= a->ob_size) {
Guido van Rossum929f1b81996-08-09 20:51:27 +0000391 if (indexerr == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000392 indexerr = PyString_FromString(
393 "list index out of range");
394 PyErr_SetObject(PyExc_IndexError, indexerr);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000395 return NULL;
396 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000397 Py_INCREF(a->ob_item[i]);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000398 return a->ob_item[i];
399}
400
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000401static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000402list_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000403{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000404 PyListObject *np;
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000405 PyObject **src, **dest;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000406 Py_ssize_t i, len;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000407 if (ilow < 0)
408 ilow = 0;
409 else if (ilow > a->ob_size)
410 ilow = a->ob_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000411 if (ihigh < ilow)
412 ihigh = ilow;
413 else if (ihigh > a->ob_size)
414 ihigh = a->ob_size;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000415 len = ihigh - ilow;
416 np = (PyListObject *) PyList_New(len);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000417 if (np == NULL)
418 return NULL;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000419
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000420 src = a->ob_item + ilow;
421 dest = np->ob_item;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000422 for (i = 0; i < len; i++) {
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000423 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000424 Py_INCREF(v);
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000425 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000426 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000427 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000428}
429
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000430PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000431PyList_GetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum234f9421993-06-17 12:35:49 +0000432{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000433 if (!PyList_Check(a)) {
434 PyErr_BadInternalCall();
Guido van Rossum234f9421993-06-17 12:35:49 +0000435 return NULL;
436 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000437 return list_slice((PyListObject *)a, ilow, ihigh);
Guido van Rossum234f9421993-06-17 12:35:49 +0000438}
439
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000440static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000441list_concat(PyListObject *a, PyObject *bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000442{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000443 Py_ssize_t size;
444 Py_ssize_t i;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000445 PyObject **src, **dest;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000446 PyListObject *np;
447 if (!PyList_Check(bb)) {
Fred Drakeb6a9ada2000-06-01 03:12:13 +0000448 PyErr_Format(PyExc_TypeError,
Fred Drake914a2ed2000-06-01 14:31:03 +0000449 "can only concatenate list (not \"%.200s\") to list",
450 bb->ob_type->tp_name);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000451 return NULL;
452 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000453#define b ((PyListObject *)bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000454 size = a->ob_size + b->ob_size;
Guido van Rossuma5c0e6d2002-10-11 21:05:56 +0000455 if (size < 0)
456 return PyErr_NoMemory();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000457 np = (PyListObject *) PyList_New(size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000458 if (np == NULL) {
Guido van Rossum90933611991-06-07 16:10:43 +0000459 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000460 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000461 src = a->ob_item;
462 dest = np->ob_item;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000463 for (i = 0; i < a->ob_size; i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000464 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000465 Py_INCREF(v);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000466 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000467 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000468 src = b->ob_item;
469 dest = np->ob_item + a->ob_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000470 for (i = 0; i < b->ob_size; i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000471 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000472 Py_INCREF(v);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000473 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000474 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000475 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000476#undef b
477}
478
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000479static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000480list_repeat(PyListObject *a, Py_ssize_t n)
Guido van Rossumed98d481991-03-06 13:07:53 +0000481{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000482 Py_ssize_t i, j;
483 Py_ssize_t size;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000484 PyListObject *np;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000485 PyObject **p, **items;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000486 PyObject *elem;
Guido van Rossumed98d481991-03-06 13:07:53 +0000487 if (n < 0)
488 n = 0;
489 size = a->ob_size * n;
Guido van Rossumbfa5a142002-10-11 23:39:35 +0000490 if (n && size/n != a->ob_size)
Guido van Rossuma5c0e6d2002-10-11 21:05:56 +0000491 return PyErr_NoMemory();
Guido van Rossum809123c2007-11-12 20:04:41 +0000492 if (size == 0)
493 return PyList_New(0);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000494 np = (PyListObject *) PyList_New(size);
Guido van Rossumed98d481991-03-06 13:07:53 +0000495 if (np == NULL)
496 return NULL;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000497
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000498 items = np->ob_item;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000499 if (a->ob_size == 1) {
500 elem = a->ob_item[0];
501 for (i = 0; i < n; i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000502 items[i] = elem;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000503 Py_INCREF(elem);
504 }
505 return (PyObject *) np;
506 }
Guido van Rossumed98d481991-03-06 13:07:53 +0000507 p = np->ob_item;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000508 items = a->ob_item;
Guido van Rossumed98d481991-03-06 13:07:53 +0000509 for (i = 0; i < n; i++) {
510 for (j = 0; j < a->ob_size; j++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000511 *p = items[j];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000512 Py_INCREF(*p);
Guido van Rossumed98d481991-03-06 13:07:53 +0000513 p++;
514 }
515 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000516 return (PyObject *) np;
Guido van Rossumed98d481991-03-06 13:07:53 +0000517}
518
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000519static int
Armin Rigo93677f02004-07-29 12:40:23 +0000520list_clear(PyListObject *a)
521{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000522 Py_ssize_t i;
Armin Rigo93677f02004-07-29 12:40:23 +0000523 PyObject **item = a->ob_item;
524 if (item != NULL) {
525 /* Because XDECREF can recursively invoke operations on
526 this list, we make it empty first. */
527 i = a->ob_size;
528 a->ob_size = 0;
529 a->ob_item = NULL;
530 a->allocated = 0;
531 while (--i >= 0) {
532 Py_XDECREF(item[i]);
533 }
534 PyMem_FREE(item);
535 }
536 /* Never fails; the return value can be ignored.
537 Note that there is no guarantee that the list is actually empty
538 at this point, because XDECREF may have populated it again! */
539 return 0;
540}
541
Tim Peters8fc4a912004-07-31 21:53:19 +0000542/* a[ilow:ihigh] = v if v != NULL.
543 * del a[ilow:ihigh] if v == NULL.
544 *
545 * Special speed gimmick: when v is NULL and ihigh - ilow <= 8, it's
546 * guaranteed the call cannot fail.
547 */
Armin Rigo93677f02004-07-29 12:40:23 +0000548static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000549list_ass_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000550{
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000551 /* Because [X]DECREF can recursively invoke list operations on
552 this list, we must postpone all [X]DECREF activity until
553 after the list is back in its canonical shape. Therefore
554 we must allocate an additional array, 'recycle', into which
555 we temporarily copy the items that are deleted from the
556 list. :-( */
Tim Peters73572222004-07-31 02:54:42 +0000557 PyObject *recycle_on_stack[8];
558 PyObject **recycle = recycle_on_stack; /* will allocate more if needed */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000559 PyObject **item;
Raymond Hettingerf889e102004-03-09 08:04:33 +0000560 PyObject **vitem = NULL;
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000561 PyObject *v_as_SF = NULL; /* PySequence_Fast(v) */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000562 Py_ssize_t n; /* # of elements in replacement list */
563 Py_ssize_t norig; /* # of elements in list getting replaced */
564 Py_ssize_t d; /* Change in size */
565 Py_ssize_t k;
Tim Peters8d9eb102004-07-31 02:24:20 +0000566 size_t s;
567 int result = -1; /* guilty until proved innocent */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000568#define b ((PyListObject *)v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000569 if (v == NULL)
570 n = 0;
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000571 else {
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000572 if (a == b) {
573 /* Special case "a[i:j] = a" -- copy b first */
Michael W. Hudsonda0a0672003-08-15 12:06:41 +0000574 v = list_slice(b, 0, b->ob_size);
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000575 if (v == NULL)
Tim Peters8d9eb102004-07-31 02:24:20 +0000576 return result;
577 result = list_ass_slice(a, ilow, ihigh, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000578 Py_DECREF(v);
Tim Peters8d9eb102004-07-31 02:24:20 +0000579 return result;
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000580 }
Raymond Hettingerf889e102004-03-09 08:04:33 +0000581 v_as_SF = PySequence_Fast(v, "can only assign an iterable");
Michael W. Hudsonb4f49382003-08-14 17:04:28 +0000582 if(v_as_SF == NULL)
Tim Peters8d9eb102004-07-31 02:24:20 +0000583 goto Error;
Michael W. Hudsonb4f49382003-08-14 17:04:28 +0000584 n = PySequence_Fast_GET_SIZE(v_as_SF);
Raymond Hettinger42bec932004-03-12 16:38:17 +0000585 vitem = PySequence_Fast_ITEMS(v_as_SF);
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000586 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000587 if (ilow < 0)
588 ilow = 0;
589 else if (ilow > a->ob_size)
590 ilow = a->ob_size;
Tim Peters8d9eb102004-07-31 02:24:20 +0000591
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000592 if (ihigh < ilow)
593 ihigh = ilow;
594 else if (ihigh > a->ob_size)
595 ihigh = a->ob_size;
Armin Rigo93677f02004-07-29 12:40:23 +0000596
Tim Peters8d9eb102004-07-31 02:24:20 +0000597 norig = ihigh - ilow;
598 assert(norig >= 0);
599 d = n - norig;
Armin Rigo93677f02004-07-29 12:40:23 +0000600 if (a->ob_size + d == 0) {
601 Py_XDECREF(v_as_SF);
602 return list_clear(a);
603 }
604 item = a->ob_item;
Tim Peters8d9eb102004-07-31 02:24:20 +0000605 /* recycle the items that we are about to remove */
606 s = norig * sizeof(PyObject *);
Tim Peters73572222004-07-31 02:54:42 +0000607 if (s > sizeof(recycle_on_stack)) {
Armin Rigo1dd04a02004-07-30 11:38:22 +0000608 recycle = (PyObject **)PyMem_MALLOC(s);
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000609 if (recycle == NULL) {
610 PyErr_NoMemory();
Tim Peters8d9eb102004-07-31 02:24:20 +0000611 goto Error;
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000612 }
613 }
Armin Rigo1dd04a02004-07-30 11:38:22 +0000614 memcpy(recycle, &item[ilow], s);
Tim Peters8d9eb102004-07-31 02:24:20 +0000615
Armin Rigo1dd04a02004-07-30 11:38:22 +0000616 if (d < 0) { /* Delete -d items */
617 memmove(&item[ihigh+d], &item[ihigh],
618 (a->ob_size - ihigh)*sizeof(PyObject *));
619 list_resize(a, a->ob_size + d);
620 item = a->ob_item;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000621 }
Armin Rigo1dd04a02004-07-30 11:38:22 +0000622 else if (d > 0) { /* Insert d items */
Tim Peters73572222004-07-31 02:54:42 +0000623 k = a->ob_size;
624 if (list_resize(a, k+d) < 0)
Tim Peters8d9eb102004-07-31 02:24:20 +0000625 goto Error;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000626 item = a->ob_item;
Raymond Hettingerf889e102004-03-09 08:04:33 +0000627 memmove(&item[ihigh+d], &item[ihigh],
Tim Peters73572222004-07-31 02:54:42 +0000628 (k - ihigh)*sizeof(PyObject *));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000629 }
630 for (k = 0; k < n; k++, ilow++) {
Raymond Hettingerf889e102004-03-09 08:04:33 +0000631 PyObject *w = vitem[k];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000632 Py_XINCREF(w);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000633 item[ilow] = w;
634 }
Tim Peters73572222004-07-31 02:54:42 +0000635 for (k = norig - 1; k >= 0; --k)
636 Py_XDECREF(recycle[k]);
Tim Peters8d9eb102004-07-31 02:24:20 +0000637 result = 0;
638 Error:
Tim Peters73572222004-07-31 02:54:42 +0000639 if (recycle != recycle_on_stack)
Armin Rigo1dd04a02004-07-30 11:38:22 +0000640 PyMem_FREE(recycle);
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000641 Py_XDECREF(v_as_SF);
Tim Peters8d9eb102004-07-31 02:24:20 +0000642 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000643#undef b
644}
645
Guido van Rossum234f9421993-06-17 12:35:49 +0000646int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000647PyList_SetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum234f9421993-06-17 12:35:49 +0000648{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000649 if (!PyList_Check(a)) {
650 PyErr_BadInternalCall();
Guido van Rossum1fc238a1993-07-29 08:25:09 +0000651 return -1;
Guido van Rossum234f9421993-06-17 12:35:49 +0000652 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000653 return list_ass_slice((PyListObject *)a, ilow, ihigh, v);
Guido van Rossum234f9421993-06-17 12:35:49 +0000654}
655
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000656static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000657list_inplace_repeat(PyListObject *self, Py_ssize_t n)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000658{
659 PyObject **items;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000660 Py_ssize_t size, i, j, p;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000661
662
663 size = PyList_GET_SIZE(self);
Guido van Rossum809123c2007-11-12 20:04:41 +0000664 if (size == 0 || n == 1) {
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000665 Py_INCREF(self);
666 return (PyObject *)self;
667 }
668
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000669 if (n < 1) {
Armin Rigo93677f02004-07-29 12:40:23 +0000670 (void)list_clear(self);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000671 Py_INCREF(self);
672 return (PyObject *)self;
673 }
674
Guido van Rossum809123c2007-11-12 20:04:41 +0000675 p = size*n;
676 if (p/n != size)
677 return PyErr_NoMemory();
678 if (list_resize(self, p) == -1)
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000679 return NULL;
680
681 p = size;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000682 items = self->ob_item;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000683 for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */
684 for (j = 0; j < size; j++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000685 PyObject *o = items[j];
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000686 Py_INCREF(o);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000687 items[p++] = o;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000688 }
689 }
690 Py_INCREF(self);
691 return (PyObject *)self;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000692}
693
Guido van Rossum4a450d01991-04-03 19:05:18 +0000694static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000695list_ass_item(PyListObject *a, Py_ssize_t i, PyObject *v)
Guido van Rossum4a450d01991-04-03 19:05:18 +0000696{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000697 PyObject *old_value;
Guido van Rossum4a450d01991-04-03 19:05:18 +0000698 if (i < 0 || i >= a->ob_size) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000699 PyErr_SetString(PyExc_IndexError,
700 "list assignment index out of range");
Guido van Rossum4a450d01991-04-03 19:05:18 +0000701 return -1;
702 }
703 if (v == NULL)
704 return list_ass_slice(a, i, i+1, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000705 Py_INCREF(v);
Guido van Rossumd7047b31995-01-02 19:07:15 +0000706 old_value = a->ob_item[i];
Guido van Rossum4a450d01991-04-03 19:05:18 +0000707 a->ob_item[i] = v;
Tim Peters3b01a122002-07-19 02:35:45 +0000708 Py_DECREF(old_value);
Guido van Rossum4a450d01991-04-03 19:05:18 +0000709 return 0;
710}
711
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000712static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000713listinsert(PyListObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000714{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000715 Py_ssize_t i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000716 PyObject *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000717 if (!PyArg_ParseTuple(args, "nO:insert", &i, &v))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000718 return NULL;
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +0000719 if (ins1(self, i, v) == 0)
720 Py_RETURN_NONE;
Raymond Hettinger501f02c2004-04-12 14:01:16 +0000721 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000722}
723
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000724static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000725listappend(PyListObject *self, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000726{
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +0000727 if (app1(self, v) == 0)
728 Py_RETURN_NONE;
Raymond Hettinger501f02c2004-04-12 14:01:16 +0000729 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000730}
731
Barry Warsawdedf6d61998-10-09 16:37:25 +0000732static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000733listextend(PyListObject *self, PyObject *b)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000734{
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000735 PyObject *it; /* iter(v) */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000736 Py_ssize_t m; /* size of self */
737 Py_ssize_t n; /* guess for size of b */
738 Py_ssize_t mn; /* m + n */
739 Py_ssize_t i;
Raymond Hettinger57c45422004-03-11 09:48:18 +0000740 PyObject *(*iternext)(PyObject *);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000741
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000742 /* Special cases:
Tim Petersb38e2b62004-07-29 02:29:26 +0000743 1) lists and tuples which can use PySequence_Fast ops
744 2) extending self to self requires making a copy first
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000745 */
746 if (PyList_CheckExact(b) || PyTuple_CheckExact(b) || (PyObject *)self == b) {
Armin Rigo70d172d2004-03-20 22:19:23 +0000747 PyObject **src, **dest;
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000748 b = PySequence_Fast(b, "argument must be iterable");
749 if (!b)
750 return NULL;
Armin Rigo70d172d2004-03-20 22:19:23 +0000751 n = PySequence_Fast_GET_SIZE(b);
752 if (n == 0) {
753 /* short circuit when b is empty */
754 Py_DECREF(b);
755 Py_RETURN_NONE;
756 }
757 m = self->ob_size;
758 if (list_resize(self, m + n) == -1) {
759 Py_DECREF(b);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000760 return NULL;
Armin Rigo70d172d2004-03-20 22:19:23 +0000761 }
762 /* note that we may still have self == b here for the
763 * situation a.extend(a), but the following code works
764 * in that case too. Just make sure to resize self
765 * before calling PySequence_Fast_ITEMS.
766 */
767 /* populate the end of self with b's items */
768 src = PySequence_Fast_ITEMS(b);
769 dest = self->ob_item + m;
770 for (i = 0; i < n; i++) {
771 PyObject *o = src[i];
772 Py_INCREF(o);
773 dest[i] = o;
774 }
775 Py_DECREF(b);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000776 Py_RETURN_NONE;
777 }
778
779 it = PyObject_GetIter(b);
780 if (it == NULL)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000781 return NULL;
Raymond Hettinger57c45422004-03-11 09:48:18 +0000782 iternext = *it->ob_type->tp_iternext;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000783
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000784 /* Guess a result list size. */
Armin Rigof5b3e362006-02-11 21:32:43 +0000785 n = _PyObject_LengthHint(b);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000786 if (n < 0) {
Christian Heimes03acd852007-12-05 12:51:23 +0000787 if (PyErr_Occurred()
788 && !PyErr_ExceptionMatches(PyExc_TypeError)
789 && !PyErr_ExceptionMatches(PyExc_AttributeError)) {
Raymond Hettingera710b332005-08-21 11:03:59 +0000790 Py_DECREF(it);
791 return NULL;
792 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000793 PyErr_Clear();
794 n = 8; /* arbitrary */
795 }
796 m = self->ob_size;
797 mn = m + n;
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000798 if (mn >= m) {
799 /* Make room. */
800 if (list_resize(self, mn) == -1)
801 goto error;
802 /* Make the list sane again. */
803 self->ob_size = m;
804 }
805 /* Else m + n overflowed; on the chance that n lied, and there really
806 * is enough room, ignore it. If n was telling the truth, we'll
807 * eventually run out of memory during the loop.
808 */
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000809
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000810 /* Run iterator to exhaustion. */
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000811 for (;;) {
Raymond Hettinger57c45422004-03-11 09:48:18 +0000812 PyObject *item = iternext(it);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000813 if (item == NULL) {
Raymond Hettinger57c45422004-03-11 09:48:18 +0000814 if (PyErr_Occurred()) {
815 if (PyErr_ExceptionMatches(PyExc_StopIteration))
816 PyErr_Clear();
817 else
818 goto error;
819 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000820 break;
821 }
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000822 if (self->ob_size < self->allocated) {
823 /* steals ref */
824 PyList_SET_ITEM(self, self->ob_size, item);
825 ++self->ob_size;
826 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000827 else {
Raymond Hettinger40a03822004-04-12 13:05:09 +0000828 int status = app1(self, item);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000829 Py_DECREF(item); /* append creates a new ref */
830 if (status < 0)
831 goto error;
832 }
833 }
834
835 /* Cut back result list if initial guess was too large. */
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000836 if (self->ob_size < self->allocated)
837 list_resize(self, self->ob_size); /* shrinking can't fail */
838
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000839 Py_DECREF(it);
840 Py_RETURN_NONE;
841
842 error:
843 Py_DECREF(it);
844 return NULL;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000845}
846
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000847PyObject *
848_PyList_Extend(PyListObject *self, PyObject *b)
849{
850 return listextend(self, b);
851}
852
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000853static PyObject *
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000854list_inplace_concat(PyListObject *self, PyObject *other)
855{
856 PyObject *result;
857
858 result = listextend(self, other);
859 if (result == NULL)
860 return result;
861 Py_DECREF(result);
862 Py_INCREF(self);
863 return (PyObject *)self;
864}
865
866static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000867listpop(PyListObject *self, PyObject *args)
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000868{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000869 Py_ssize_t i = -1;
Armin Rigo4b63c212006-10-04 11:44:06 +0000870 PyObject *v;
Tim Peters8fc4a912004-07-31 21:53:19 +0000871 int status;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000872
Armin Rigo4b63c212006-10-04 11:44:06 +0000873 if (!PyArg_ParseTuple(args, "|n:pop", &i))
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000874 return NULL;
Armin Rigo4b63c212006-10-04 11:44:06 +0000875
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000876 if (self->ob_size == 0) {
877 /* Special-case most common failure cause */
878 PyErr_SetString(PyExc_IndexError, "pop from empty list");
879 return NULL;
880 }
881 if (i < 0)
882 i += self->ob_size;
883 if (i < 0 || i >= self->ob_size) {
884 PyErr_SetString(PyExc_IndexError, "pop index out of range");
885 return NULL;
886 }
887 v = self->ob_item[i];
Raymond Hettingercb3e5802004-02-13 18:36:31 +0000888 if (i == self->ob_size - 1) {
Tim Peters8fc4a912004-07-31 21:53:19 +0000889 status = list_resize(self, self->ob_size - 1);
890 assert(status >= 0);
891 return v; /* and v now owns the reference the list had */
Raymond Hettingercb3e5802004-02-13 18:36:31 +0000892 }
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000893 Py_INCREF(v);
Tim Peters8fc4a912004-07-31 21:53:19 +0000894 status = list_ass_slice(self, i, i+1, (PyObject *)NULL);
895 assert(status >= 0);
896 /* Use status, so that in a release build compilers don't
897 * complain about the unused name.
898 */
Brett Cannon651dd522004-08-08 21:21:18 +0000899 (void) status;
900
901 return v;
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000902}
903
Tim Peters8e2e7ca2002-07-19 02:33:08 +0000904/* Reverse a slice of a list in place, from lo up to (exclusive) hi. */
905static void
906reverse_slice(PyObject **lo, PyObject **hi)
907{
908 assert(lo && hi);
909
910 --hi;
911 while (lo < hi) {
912 PyObject *t = *lo;
913 *lo = *hi;
914 *hi = t;
915 ++lo;
916 --hi;
917 }
918}
919
Tim Petersa64dc242002-08-01 02:13:36 +0000920/* Lots of code for an adaptive, stable, natural mergesort. There are many
921 * pieces to this algorithm; read listsort.txt for overviews and details.
922 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000923
Guido van Rossum3f236de1996-12-10 23:55:39 +0000924/* Comparison function. Takes care of calling a user-supplied
Tim Peters66860f62002-08-04 17:47:26 +0000925 * comparison function (any callable Python object), which must not be
926 * NULL (use the ISLT macro if you don't know, or call PyObject_RichCompareBool
927 * with Py_LT if you know it's NULL).
Tim Petersa64dc242002-08-01 02:13:36 +0000928 * Returns -1 on error, 1 if x < y, 0 if x >= y.
929 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000930static int
Tim Petersa8c974c2002-07-19 03:30:57 +0000931islt(PyObject *x, PyObject *y, PyObject *compare)
Guido van Rossum3f236de1996-12-10 23:55:39 +0000932{
Tim Petersf2a04732002-07-11 21:46:16 +0000933 PyObject *res;
934 PyObject *args;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000935 Py_ssize_t i;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000936
Tim Peters66860f62002-08-04 17:47:26 +0000937 assert(compare != NULL);
Tim Petersa8c974c2002-07-19 03:30:57 +0000938 /* Call the user's comparison function and translate the 3-way
939 * result into true or false (or error).
940 */
Tim Petersf2a04732002-07-11 21:46:16 +0000941 args = PyTuple_New(2);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000942 if (args == NULL)
Tim Petersa8c974c2002-07-19 03:30:57 +0000943 return -1;
Tim Petersf2a04732002-07-11 21:46:16 +0000944 Py_INCREF(x);
945 Py_INCREF(y);
946 PyTuple_SET_ITEM(args, 0, x);
947 PyTuple_SET_ITEM(args, 1, y);
Tim Peters58cf3612002-07-15 05:16:13 +0000948 res = PyObject_Call(compare, args, NULL);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000949 Py_DECREF(args);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000950 if (res == NULL)
Tim Petersa8c974c2002-07-19 03:30:57 +0000951 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000952 if (!PyInt_Check(res)) {
953 Py_DECREF(res);
954 PyErr_SetString(PyExc_TypeError,
Guido van Rossum9bcd1d71999-04-19 17:44:39 +0000955 "comparison function must return int");
Tim Petersa8c974c2002-07-19 03:30:57 +0000956 return -1;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000957 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000958 i = PyInt_AsLong(res);
959 Py_DECREF(res);
Tim Petersa8c974c2002-07-19 03:30:57 +0000960 return i < 0;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000961}
962
Tim Peters66860f62002-08-04 17:47:26 +0000963/* If COMPARE is NULL, calls PyObject_RichCompareBool with Py_LT, else calls
964 * islt. This avoids a layer of function call in the usual case, and
965 * sorting does many comparisons.
966 * Returns -1 on error, 1 if x < y, 0 if x >= y.
967 */
968#define ISLT(X, Y, COMPARE) ((COMPARE) == NULL ? \
969 PyObject_RichCompareBool(X, Y, Py_LT) : \
970 islt(X, Y, COMPARE))
971
972/* Compare X to Y via "<". Goto "fail" if the comparison raises an
Tim Petersa8c974c2002-07-19 03:30:57 +0000973 error. Else "k" is set to true iff X<Y, and an "if (k)" block is
974 started. It makes more sense in context <wink>. X and Y are PyObject*s.
975*/
Tim Peters66860f62002-08-04 17:47:26 +0000976#define IFLT(X, Y) if ((k = ISLT(X, Y, compare)) < 0) goto fail; \
Tim Petersa8c974c2002-07-19 03:30:57 +0000977 if (k)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000978
979/* binarysort is the best method for sorting small arrays: it does
980 few compares, but can do data movement quadratic in the number of
981 elements.
Guido van Rossum42812581998-06-17 14:15:44 +0000982 [lo, hi) is a contiguous slice of a list, and is sorted via
Tim Petersa8c974c2002-07-19 03:30:57 +0000983 binary insertion. This sort is stable.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000984 On entry, must have lo <= start <= hi, and that [lo, start) is already
985 sorted (pass start == lo if you don't know!).
Tim Petersa8c974c2002-07-19 03:30:57 +0000986 If islt() complains return -1, else 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000987 Even in case of error, the output slice will be some permutation of
988 the input (nothing is lost or duplicated).
989*/
Guido van Rossum3f236de1996-12-10 23:55:39 +0000990static int
Fred Drakea2f55112000-07-09 15:16:51 +0000991binarysort(PyObject **lo, PyObject **hi, PyObject **start, PyObject *compare)
992 /* compare -- comparison function object, or NULL for default */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000993{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000994 register Py_ssize_t k;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000995 register PyObject **l, **p, **r;
996 register PyObject *pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000997
Tim Petersa8c974c2002-07-19 03:30:57 +0000998 assert(lo <= start && start <= hi);
999 /* assert [lo, start) is sorted */
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001000 if (lo == start)
1001 ++start;
1002 for (; start < hi; ++start) {
1003 /* set l to where *start belongs */
1004 l = lo;
1005 r = start;
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001006 pivot = *r;
Tim Peters0fe977c2002-07-19 06:12:32 +00001007 /* Invariants:
1008 * pivot >= all in [lo, l).
1009 * pivot < all in [r, start).
1010 * The second is vacuously true at the start.
1011 */
1012 assert(l < r);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001013 do {
1014 p = l + ((r - l) >> 1);
Tim Petersa8c974c2002-07-19 03:30:57 +00001015 IFLT(pivot, *p)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001016 r = p;
1017 else
Tim Peters0fe977c2002-07-19 06:12:32 +00001018 l = p+1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001019 } while (l < r);
Tim Peters0fe977c2002-07-19 06:12:32 +00001020 assert(l == r);
1021 /* The invariants still hold, so pivot >= all in [lo, l) and
1022 pivot < all in [l, start), so pivot belongs at l. Note
1023 that if there are elements equal to pivot, l points to the
1024 first slot after them -- that's why this sort is stable.
1025 Slide over to make room.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001026 Caution: using memmove is much slower under MSVC 5;
1027 we're not usually moving many slots. */
1028 for (p = start; p > l; --p)
1029 *p = *(p-1);
1030 *l = pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001031 }
Guido van Rossum3f236de1996-12-10 23:55:39 +00001032 return 0;
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001033
1034 fail:
1035 return -1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001036}
1037
Tim Petersa64dc242002-08-01 02:13:36 +00001038/*
1039Return the length of the run beginning at lo, in the slice [lo, hi). lo < hi
1040is required on entry. "A run" is the longest ascending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001041
Tim Petersa64dc242002-08-01 02:13:36 +00001042 lo[0] <= lo[1] <= lo[2] <= ...
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001043
Tim Petersa64dc242002-08-01 02:13:36 +00001044or the longest descending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001045
Tim Petersa64dc242002-08-01 02:13:36 +00001046 lo[0] > lo[1] > lo[2] > ...
Tim Peters3b01a122002-07-19 02:35:45 +00001047
Tim Petersa64dc242002-08-01 02:13:36 +00001048Boolean *descending is set to 0 in the former case, or to 1 in the latter.
1049For its intended use in a stable mergesort, the strictness of the defn of
1050"descending" is needed so that the caller can safely reverse a descending
1051sequence without violating stability (strict > ensures there are no equal
1052elements to get out of order).
1053
1054Returns -1 in case of error.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001055*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001056static Py_ssize_t
Tim Petersa64dc242002-08-01 02:13:36 +00001057count_run(PyObject **lo, PyObject **hi, PyObject *compare, int *descending)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001058{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001059 Py_ssize_t k;
1060 Py_ssize_t n;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001061
Tim Petersa64dc242002-08-01 02:13:36 +00001062 assert(lo < hi);
1063 *descending = 0;
1064 ++lo;
1065 if (lo == hi)
1066 return 1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001067
Tim Petersa64dc242002-08-01 02:13:36 +00001068 n = 2;
1069 IFLT(*lo, *(lo-1)) {
1070 *descending = 1;
1071 for (lo = lo+1; lo < hi; ++lo, ++n) {
1072 IFLT(*lo, *(lo-1))
1073 ;
1074 else
1075 break;
1076 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001077 }
Tim Petersa64dc242002-08-01 02:13:36 +00001078 else {
1079 for (lo = lo+1; lo < hi; ++lo, ++n) {
1080 IFLT(*lo, *(lo-1))
1081 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001082 }
1083 }
1084
Tim Petersa64dc242002-08-01 02:13:36 +00001085 return n;
1086fail:
1087 return -1;
1088}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001089
Tim Petersa64dc242002-08-01 02:13:36 +00001090/*
1091Locate the proper position of key in a sorted vector; if the vector contains
1092an element equal to key, return the position immediately to the left of
1093the leftmost equal element. [gallop_right() does the same except returns
1094the position to the right of the rightmost equal element (if any).]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001095
Tim Petersa64dc242002-08-01 02:13:36 +00001096"a" is a sorted vector with n elements, starting at a[0]. n must be > 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001097
Tim Petersa64dc242002-08-01 02:13:36 +00001098"hint" is an index at which to begin the search, 0 <= hint < n. The closer
1099hint is to the final result, the faster this runs.
1100
1101The return value is the int k in 0..n such that
1102
1103 a[k-1] < key <= a[k]
1104
1105pretending that *(a-1) is minus infinity and a[n] is plus infinity. IOW,
1106key belongs at index k; or, IOW, the first k elements of a should precede
1107key, and the last n-k should follow key.
1108
1109Returns -1 on error. See listsort.txt for info on the method.
1110*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001111static Py_ssize_t
1112gallop_left(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint, PyObject *compare)
Tim Petersa64dc242002-08-01 02:13:36 +00001113{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001114 Py_ssize_t ofs;
1115 Py_ssize_t lastofs;
1116 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001117
1118 assert(key && a && n > 0 && hint >= 0 && hint < n);
1119
1120 a += hint;
1121 lastofs = 0;
1122 ofs = 1;
1123 IFLT(*a, key) {
1124 /* a[hint] < key -- gallop right, until
1125 * a[hint + lastofs] < key <= a[hint + ofs]
1126 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001127 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
Tim Petersa64dc242002-08-01 02:13:36 +00001128 while (ofs < maxofs) {
1129 IFLT(a[ofs], key) {
1130 lastofs = ofs;
1131 ofs = (ofs << 1) + 1;
1132 if (ofs <= 0) /* int overflow */
1133 ofs = maxofs;
1134 }
1135 else /* key <= a[hint + ofs] */
1136 break;
1137 }
1138 if (ofs > maxofs)
1139 ofs = maxofs;
1140 /* Translate back to offsets relative to &a[0]. */
1141 lastofs += hint;
1142 ofs += hint;
1143 }
1144 else {
1145 /* key <= a[hint] -- gallop left, until
1146 * a[hint - ofs] < key <= a[hint - lastofs]
1147 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001148 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
Tim Petersa64dc242002-08-01 02:13:36 +00001149 while (ofs < maxofs) {
1150 IFLT(*(a-ofs), key)
1151 break;
1152 /* key <= a[hint - ofs] */
1153 lastofs = ofs;
1154 ofs = (ofs << 1) + 1;
1155 if (ofs <= 0) /* int overflow */
1156 ofs = maxofs;
1157 }
1158 if (ofs > maxofs)
1159 ofs = maxofs;
1160 /* Translate back to positive offsets relative to &a[0]. */
1161 k = lastofs;
1162 lastofs = hint - ofs;
1163 ofs = hint - k;
1164 }
1165 a -= hint;
1166
1167 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1168 /* Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the
1169 * right of lastofs but no farther right than ofs. Do a binary
1170 * search, with invariant a[lastofs-1] < key <= a[ofs].
1171 */
1172 ++lastofs;
1173 while (lastofs < ofs) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001174 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001175
1176 IFLT(a[m], key)
1177 lastofs = m+1; /* a[m] < key */
1178 else
1179 ofs = m; /* key <= a[m] */
1180 }
1181 assert(lastofs == ofs); /* so a[ofs-1] < key <= a[ofs] */
1182 return ofs;
1183
1184fail:
1185 return -1;
1186}
1187
1188/*
1189Exactly like gallop_left(), except that if key already exists in a[0:n],
1190finds the position immediately to the right of the rightmost equal value.
1191
1192The return value is the int k in 0..n such that
1193
1194 a[k-1] <= key < a[k]
1195
1196or -1 if error.
1197
1198The code duplication is massive, but this is enough different given that
1199we're sticking to "<" comparisons that it's much harder to follow if
1200written as one routine with yet another "left or right?" flag.
1201*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001202static Py_ssize_t
1203gallop_right(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint, PyObject *compare)
Tim Petersa64dc242002-08-01 02:13:36 +00001204{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001205 Py_ssize_t ofs;
1206 Py_ssize_t lastofs;
1207 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001208
1209 assert(key && a && n > 0 && hint >= 0 && hint < n);
1210
1211 a += hint;
1212 lastofs = 0;
1213 ofs = 1;
1214 IFLT(key, *a) {
1215 /* key < a[hint] -- gallop left, until
1216 * a[hint - ofs] <= key < a[hint - lastofs]
1217 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001218 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
Tim Petersa64dc242002-08-01 02:13:36 +00001219 while (ofs < maxofs) {
1220 IFLT(key, *(a-ofs)) {
1221 lastofs = ofs;
1222 ofs = (ofs << 1) + 1;
1223 if (ofs <= 0) /* int overflow */
1224 ofs = maxofs;
1225 }
1226 else /* a[hint - ofs] <= key */
1227 break;
1228 }
1229 if (ofs > maxofs)
1230 ofs = maxofs;
1231 /* Translate back to positive offsets relative to &a[0]. */
1232 k = lastofs;
1233 lastofs = hint - ofs;
1234 ofs = hint - k;
1235 }
1236 else {
1237 /* a[hint] <= key -- gallop right, until
1238 * a[hint + lastofs] <= key < a[hint + ofs]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001239 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001240 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
Tim Petersa64dc242002-08-01 02:13:36 +00001241 while (ofs < maxofs) {
1242 IFLT(key, a[ofs])
1243 break;
1244 /* a[hint + ofs] <= key */
1245 lastofs = ofs;
1246 ofs = (ofs << 1) + 1;
1247 if (ofs <= 0) /* int overflow */
1248 ofs = maxofs;
1249 }
1250 if (ofs > maxofs)
1251 ofs = maxofs;
1252 /* Translate back to offsets relative to &a[0]. */
1253 lastofs += hint;
1254 ofs += hint;
1255 }
1256 a -= hint;
1257
1258 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1259 /* Now a[lastofs] <= key < a[ofs], so key belongs somewhere to the
1260 * right of lastofs but no farther right than ofs. Do a binary
1261 * search, with invariant a[lastofs-1] <= key < a[ofs].
1262 */
1263 ++lastofs;
1264 while (lastofs < ofs) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001265 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001266
1267 IFLT(key, a[m])
1268 ofs = m; /* key < a[m] */
1269 else
1270 lastofs = m+1; /* a[m] <= key */
1271 }
1272 assert(lastofs == ofs); /* so a[ofs-1] <= key < a[ofs] */
1273 return ofs;
1274
1275fail:
1276 return -1;
1277}
1278
1279/* The maximum number of entries in a MergeState's pending-runs stack.
1280 * This is enough to sort arrays of size up to about
1281 * 32 * phi ** MAX_MERGE_PENDING
1282 * where phi ~= 1.618. 85 is ridiculouslylarge enough, good for an array
1283 * with 2**64 elements.
1284 */
1285#define MAX_MERGE_PENDING 85
1286
Tim Peterse05f65a2002-08-10 05:21:15 +00001287/* When we get into galloping mode, we stay there until both runs win less
1288 * often than MIN_GALLOP consecutive times. See listsort.txt for more info.
Tim Petersa64dc242002-08-01 02:13:36 +00001289 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001290#define MIN_GALLOP 7
Tim Petersa64dc242002-08-01 02:13:36 +00001291
1292/* Avoid malloc for small temp arrays. */
1293#define MERGESTATE_TEMP_SIZE 256
1294
1295/* One MergeState exists on the stack per invocation of mergesort. It's just
1296 * a convenient way to pass state around among the helper functions.
1297 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001298struct s_slice {
1299 PyObject **base;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001300 Py_ssize_t len;
Tim Peterse05f65a2002-08-10 05:21:15 +00001301};
1302
Tim Petersa64dc242002-08-01 02:13:36 +00001303typedef struct s_MergeState {
1304 /* The user-supplied comparison function. or NULL if none given. */
1305 PyObject *compare;
1306
Tim Peterse05f65a2002-08-10 05:21:15 +00001307 /* This controls when we get *into* galloping mode. It's initialized
1308 * to MIN_GALLOP. merge_lo and merge_hi tend to nudge it higher for
1309 * random data, and lower for highly structured data.
1310 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001311 Py_ssize_t min_gallop;
Tim Peterse05f65a2002-08-10 05:21:15 +00001312
Tim Petersa64dc242002-08-01 02:13:36 +00001313 /* 'a' is temp storage to help with merges. It contains room for
1314 * alloced entries.
1315 */
1316 PyObject **a; /* may point to temparray below */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001317 Py_ssize_t alloced;
Tim Petersa64dc242002-08-01 02:13:36 +00001318
1319 /* A stack of n pending runs yet to be merged. Run #i starts at
1320 * address base[i] and extends for len[i] elements. It's always
1321 * true (so long as the indices are in bounds) that
1322 *
Tim Peterse05f65a2002-08-10 05:21:15 +00001323 * pending[i].base + pending[i].len == pending[i+1].base
Tim Petersa64dc242002-08-01 02:13:36 +00001324 *
1325 * so we could cut the storage for this, but it's a minor amount,
1326 * and keeping all the info explicit simplifies the code.
1327 */
1328 int n;
Tim Peterse05f65a2002-08-10 05:21:15 +00001329 struct s_slice pending[MAX_MERGE_PENDING];
Tim Petersa64dc242002-08-01 02:13:36 +00001330
1331 /* 'a' points to this when possible, rather than muck with malloc. */
1332 PyObject *temparray[MERGESTATE_TEMP_SIZE];
1333} MergeState;
1334
1335/* Conceptually a MergeState's constructor. */
1336static void
1337merge_init(MergeState *ms, PyObject *compare)
1338{
1339 assert(ms != NULL);
1340 ms->compare = compare;
1341 ms->a = ms->temparray;
1342 ms->alloced = MERGESTATE_TEMP_SIZE;
1343 ms->n = 0;
Tim Peterse05f65a2002-08-10 05:21:15 +00001344 ms->min_gallop = MIN_GALLOP;
Tim Petersa64dc242002-08-01 02:13:36 +00001345}
1346
1347/* Free all the temp memory owned by the MergeState. This must be called
1348 * when you're done with a MergeState, and may be called before then if
1349 * you want to free the temp memory early.
1350 */
1351static void
1352merge_freemem(MergeState *ms)
1353{
1354 assert(ms != NULL);
1355 if (ms->a != ms->temparray)
1356 PyMem_Free(ms->a);
1357 ms->a = ms->temparray;
1358 ms->alloced = MERGESTATE_TEMP_SIZE;
1359}
1360
1361/* Ensure enough temp memory for 'need' array slots is available.
1362 * Returns 0 on success and -1 if the memory can't be gotten.
1363 */
1364static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001365merge_getmem(MergeState *ms, Py_ssize_t need)
Tim Petersa64dc242002-08-01 02:13:36 +00001366{
1367 assert(ms != NULL);
1368 if (need <= ms->alloced)
1369 return 0;
1370 /* Don't realloc! That can cost cycles to copy the old data, but
1371 * we don't care what's in the block.
1372 */
1373 merge_freemem(ms);
1374 ms->a = (PyObject **)PyMem_Malloc(need * sizeof(PyObject*));
1375 if (ms->a) {
1376 ms->alloced = need;
1377 return 0;
1378 }
1379 PyErr_NoMemory();
1380 merge_freemem(ms); /* reset to sane state */
1381 return -1;
1382}
1383#define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 : \
1384 merge_getmem(MS, NEED))
1385
1386/* Merge the na elements starting at pa with the nb elements starting at pb
1387 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1388 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1389 * merge, and should have na <= nb. See listsort.txt for more info.
1390 * Return 0 if successful, -1 if error.
1391 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001392static Py_ssize_t
1393merge_lo(MergeState *ms, PyObject **pa, Py_ssize_t na,
1394 PyObject **pb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001395{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001396 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001397 PyObject *compare;
1398 PyObject **dest;
1399 int result = -1; /* guilty until proved innocent */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001400 Py_ssize_t min_gallop = ms->min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001401
1402 assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
1403 if (MERGE_GETMEM(ms, na) < 0)
1404 return -1;
1405 memcpy(ms->a, pa, na * sizeof(PyObject*));
1406 dest = pa;
1407 pa = ms->a;
1408
1409 *dest++ = *pb++;
1410 --nb;
1411 if (nb == 0)
1412 goto Succeed;
1413 if (na == 1)
1414 goto CopyB;
1415
1416 compare = ms->compare;
1417 for (;;) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001418 Py_ssize_t acount = 0; /* # of times A won in a row */
1419 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001420
1421 /* Do the straightforward thing until (if ever) one run
1422 * appears to win consistently.
1423 */
1424 for (;;) {
Tim Peterse05f65a2002-08-10 05:21:15 +00001425 assert(na > 1 && nb > 0);
Tim Peters66860f62002-08-04 17:47:26 +00001426 k = ISLT(*pb, *pa, compare);
Tim Petersa64dc242002-08-01 02:13:36 +00001427 if (k) {
1428 if (k < 0)
1429 goto Fail;
1430 *dest++ = *pb++;
1431 ++bcount;
1432 acount = 0;
1433 --nb;
1434 if (nb == 0)
1435 goto Succeed;
Tim Peterse05f65a2002-08-10 05:21:15 +00001436 if (bcount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001437 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001438 }
1439 else {
Tim Petersa64dc242002-08-01 02:13:36 +00001440 *dest++ = *pa++;
1441 ++acount;
1442 bcount = 0;
1443 --na;
1444 if (na == 1)
1445 goto CopyB;
Tim Peterse05f65a2002-08-10 05:21:15 +00001446 if (acount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001447 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001448 }
Tim Petersa64dc242002-08-01 02:13:36 +00001449 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001450
Tim Petersa64dc242002-08-01 02:13:36 +00001451 /* One run is winning so consistently that galloping may
1452 * be a huge win. So try that, and continue galloping until
1453 * (if ever) neither run appears to be winning consistently
1454 * anymore.
1455 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001456 ++min_gallop;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001457 do {
Tim Peterse05f65a2002-08-10 05:21:15 +00001458 assert(na > 1 && nb > 0);
1459 min_gallop -= min_gallop > 1;
1460 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001461 k = gallop_right(*pb, pa, na, 0, compare);
1462 acount = k;
1463 if (k) {
1464 if (k < 0)
1465 goto Fail;
1466 memcpy(dest, pa, k * sizeof(PyObject *));
1467 dest += k;
1468 pa += k;
1469 na -= k;
1470 if (na == 1)
1471 goto CopyB;
1472 /* na==0 is impossible now if the comparison
1473 * function is consistent, but we can't assume
1474 * that it is.
1475 */
1476 if (na == 0)
1477 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001478 }
Tim Petersa64dc242002-08-01 02:13:36 +00001479 *dest++ = *pb++;
1480 --nb;
1481 if (nb == 0)
1482 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001483
Tim Petersa64dc242002-08-01 02:13:36 +00001484 k = gallop_left(*pa, pb, nb, 0, compare);
1485 bcount = k;
1486 if (k) {
1487 if (k < 0)
1488 goto Fail;
1489 memmove(dest, pb, k * sizeof(PyObject *));
1490 dest += k;
1491 pb += k;
1492 nb -= k;
1493 if (nb == 0)
1494 goto Succeed;
1495 }
1496 *dest++ = *pa++;
1497 --na;
1498 if (na == 1)
1499 goto CopyB;
1500 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
Tim Peterse05f65a2002-08-10 05:21:15 +00001501 ++min_gallop; /* penalize it for leaving galloping mode */
1502 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001503 }
1504Succeed:
1505 result = 0;
1506Fail:
1507 if (na)
1508 memcpy(dest, pa, na * sizeof(PyObject*));
1509 return result;
1510CopyB:
1511 assert(na == 1 && nb > 0);
1512 /* The last element of pa belongs at the end of the merge. */
1513 memmove(dest, pb, nb * sizeof(PyObject *));
1514 dest[nb] = *pa;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001515 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001516}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001517
Tim Petersa64dc242002-08-01 02:13:36 +00001518/* Merge the na elements starting at pa with the nb elements starting at pb
1519 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1520 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1521 * merge, and should have na >= nb. See listsort.txt for more info.
1522 * Return 0 if successful, -1 if error.
1523 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001524static Py_ssize_t
1525merge_hi(MergeState *ms, PyObject **pa, Py_ssize_t na, PyObject **pb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001526{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001527 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001528 PyObject *compare;
1529 PyObject **dest;
1530 int result = -1; /* guilty until proved innocent */
1531 PyObject **basea;
1532 PyObject **baseb;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001533 Py_ssize_t min_gallop = ms->min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001534
1535 assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
1536 if (MERGE_GETMEM(ms, nb) < 0)
1537 return -1;
1538 dest = pb + nb - 1;
1539 memcpy(ms->a, pb, nb * sizeof(PyObject*));
1540 basea = pa;
1541 baseb = ms->a;
1542 pb = ms->a + nb - 1;
1543 pa += na - 1;
1544
1545 *dest-- = *pa--;
1546 --na;
1547 if (na == 0)
1548 goto Succeed;
1549 if (nb == 1)
1550 goto CopyA;
1551
1552 compare = ms->compare;
1553 for (;;) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001554 Py_ssize_t acount = 0; /* # of times A won in a row */
1555 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001556
1557 /* Do the straightforward thing until (if ever) one run
1558 * appears to win consistently.
1559 */
1560 for (;;) {
Tim Peterse05f65a2002-08-10 05:21:15 +00001561 assert(na > 0 && nb > 1);
Tim Peters66860f62002-08-04 17:47:26 +00001562 k = ISLT(*pb, *pa, compare);
Tim Petersa64dc242002-08-01 02:13:36 +00001563 if (k) {
1564 if (k < 0)
1565 goto Fail;
1566 *dest-- = *pa--;
1567 ++acount;
1568 bcount = 0;
1569 --na;
1570 if (na == 0)
1571 goto Succeed;
Tim Peterse05f65a2002-08-10 05:21:15 +00001572 if (acount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001573 break;
1574 }
1575 else {
1576 *dest-- = *pb--;
1577 ++bcount;
1578 acount = 0;
1579 --nb;
1580 if (nb == 1)
1581 goto CopyA;
Tim Peterse05f65a2002-08-10 05:21:15 +00001582 if (bcount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001583 break;
1584 }
1585 }
1586
1587 /* One run is winning so consistently that galloping may
1588 * be a huge win. So try that, and continue galloping until
1589 * (if ever) neither run appears to be winning consistently
1590 * anymore.
1591 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001592 ++min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001593 do {
Tim Peterse05f65a2002-08-10 05:21:15 +00001594 assert(na > 0 && nb > 1);
1595 min_gallop -= min_gallop > 1;
1596 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001597 k = gallop_right(*pb, basea, na, na-1, compare);
1598 if (k < 0)
1599 goto Fail;
1600 k = na - k;
1601 acount = k;
1602 if (k) {
1603 dest -= k;
1604 pa -= k;
1605 memmove(dest+1, pa+1, k * sizeof(PyObject *));
1606 na -= k;
1607 if (na == 0)
1608 goto Succeed;
1609 }
1610 *dest-- = *pb--;
1611 --nb;
1612 if (nb == 1)
1613 goto CopyA;
1614
1615 k = gallop_left(*pa, baseb, nb, nb-1, compare);
1616 if (k < 0)
1617 goto Fail;
1618 k = nb - k;
1619 bcount = k;
1620 if (k) {
1621 dest -= k;
1622 pb -= k;
1623 memcpy(dest+1, pb+1, k * sizeof(PyObject *));
1624 nb -= k;
1625 if (nb == 1)
1626 goto CopyA;
1627 /* nb==0 is impossible now if the comparison
1628 * function is consistent, but we can't assume
1629 * that it is.
1630 */
1631 if (nb == 0)
1632 goto Succeed;
1633 }
1634 *dest-- = *pa--;
1635 --na;
1636 if (na == 0)
1637 goto Succeed;
1638 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
Tim Peterse05f65a2002-08-10 05:21:15 +00001639 ++min_gallop; /* penalize it for leaving galloping mode */
1640 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001641 }
1642Succeed:
1643 result = 0;
1644Fail:
1645 if (nb)
1646 memcpy(dest-(nb-1), baseb, nb * sizeof(PyObject*));
1647 return result;
1648CopyA:
1649 assert(nb == 1 && na > 0);
1650 /* The first element of pb belongs at the front of the merge. */
1651 dest -= na;
1652 pa -= na;
1653 memmove(dest+1, pa+1, na * sizeof(PyObject *));
1654 *dest = *pb;
1655 return 0;
1656}
1657
1658/* Merge the two runs at stack indices i and i+1.
1659 * Returns 0 on success, -1 on error.
1660 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001661static Py_ssize_t
1662merge_at(MergeState *ms, Py_ssize_t i)
Tim Petersa64dc242002-08-01 02:13:36 +00001663{
1664 PyObject **pa, **pb;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001665 Py_ssize_t na, nb;
1666 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001667 PyObject *compare;
1668
1669 assert(ms != NULL);
1670 assert(ms->n >= 2);
1671 assert(i >= 0);
1672 assert(i == ms->n - 2 || i == ms->n - 3);
1673
Tim Peterse05f65a2002-08-10 05:21:15 +00001674 pa = ms->pending[i].base;
1675 na = ms->pending[i].len;
1676 pb = ms->pending[i+1].base;
1677 nb = ms->pending[i+1].len;
Tim Petersa64dc242002-08-01 02:13:36 +00001678 assert(na > 0 && nb > 0);
1679 assert(pa + na == pb);
1680
1681 /* Record the length of the combined runs; if i is the 3rd-last
1682 * run now, also slide over the last run (which isn't involved
1683 * in this merge). The current run i+1 goes away in any case.
1684 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001685 ms->pending[i].len = na + nb;
1686 if (i == ms->n - 3)
1687 ms->pending[i+1] = ms->pending[i+2];
Tim Petersa64dc242002-08-01 02:13:36 +00001688 --ms->n;
1689
1690 /* Where does b start in a? Elements in a before that can be
1691 * ignored (already in place).
1692 */
1693 compare = ms->compare;
1694 k = gallop_right(*pb, pa, na, 0, compare);
1695 if (k < 0)
1696 return -1;
1697 pa += k;
1698 na -= k;
1699 if (na == 0)
1700 return 0;
1701
1702 /* Where does a end in b? Elements in b after that can be
1703 * ignored (already in place).
1704 */
1705 nb = gallop_left(pa[na-1], pb, nb, nb-1, compare);
1706 if (nb <= 0)
1707 return nb;
1708
1709 /* Merge what remains of the runs, using a temp array with
1710 * min(na, nb) elements.
1711 */
1712 if (na <= nb)
1713 return merge_lo(ms, pa, na, pb, nb);
1714 else
1715 return merge_hi(ms, pa, na, pb, nb);
1716}
1717
1718/* Examine the stack of runs waiting to be merged, merging adjacent runs
1719 * until the stack invariants are re-established:
1720 *
1721 * 1. len[-3] > len[-2] + len[-1]
1722 * 2. len[-2] > len[-1]
1723 *
1724 * See listsort.txt for more info.
1725 *
1726 * Returns 0 on success, -1 on error.
1727 */
1728static int
1729merge_collapse(MergeState *ms)
1730{
Tim Peterse05f65a2002-08-10 05:21:15 +00001731 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001732
1733 assert(ms);
1734 while (ms->n > 1) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001735 Py_ssize_t n = ms->n - 2;
Tim Peterse05f65a2002-08-10 05:21:15 +00001736 if (n > 0 && p[n-1].len <= p[n].len + p[n+1].len) {
1737 if (p[n-1].len < p[n+1].len)
Tim Petersa64dc242002-08-01 02:13:36 +00001738 --n;
1739 if (merge_at(ms, n) < 0)
1740 return -1;
1741 }
Tim Peterse05f65a2002-08-10 05:21:15 +00001742 else if (p[n].len <= p[n+1].len) {
Tim Petersa64dc242002-08-01 02:13:36 +00001743 if (merge_at(ms, n) < 0)
1744 return -1;
1745 }
1746 else
1747 break;
1748 }
1749 return 0;
1750}
1751
1752/* Regardless of invariants, merge all runs on the stack until only one
1753 * remains. This is used at the end of the mergesort.
1754 *
1755 * Returns 0 on success, -1 on error.
1756 */
1757static int
1758merge_force_collapse(MergeState *ms)
1759{
Tim Peterse05f65a2002-08-10 05:21:15 +00001760 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001761
1762 assert(ms);
1763 while (ms->n > 1) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001764 Py_ssize_t n = ms->n - 2;
Tim Peterse05f65a2002-08-10 05:21:15 +00001765 if (n > 0 && p[n-1].len < p[n+1].len)
Tim Petersa64dc242002-08-01 02:13:36 +00001766 --n;
1767 if (merge_at(ms, n) < 0)
1768 return -1;
1769 }
1770 return 0;
1771}
1772
1773/* Compute a good value for the minimum run length; natural runs shorter
1774 * than this are boosted artificially via binary insertion.
1775 *
1776 * If n < 64, return n (it's too small to bother with fancy stuff).
1777 * Else if n is an exact power of 2, return 32.
1778 * Else return an int k, 32 <= k <= 64, such that n/k is close to, but
1779 * strictly less than, an exact power of 2.
1780 *
1781 * See listsort.txt for more info.
1782 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001783static Py_ssize_t
1784merge_compute_minrun(Py_ssize_t n)
Tim Petersa64dc242002-08-01 02:13:36 +00001785{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001786 Py_ssize_t r = 0; /* becomes 1 if any 1 bits are shifted off */
Tim Petersa64dc242002-08-01 02:13:36 +00001787
1788 assert(n >= 0);
1789 while (n >= 64) {
1790 r |= n & 1;
1791 n >>= 1;
1792 }
1793 return n + r;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001794}
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001795
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001796/* Special wrapper to support stable sorting using the decorate-sort-undecorate
Andrew M. Kuchling55be9ea2004-09-10 12:59:54 +00001797 pattern. Holds a key which is used for comparisons and the original record
Tim Petersb38e2b62004-07-29 02:29:26 +00001798 which is returned during the undecorate phase. By exposing only the key
1799 during comparisons, the underlying sort stability characteristics are left
1800 unchanged. Also, if a custom comparison function is used, it will only see
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001801 the key instead of a full record. */
1802
1803typedef struct {
1804 PyObject_HEAD
1805 PyObject *key;
1806 PyObject *value;
1807} sortwrapperobject;
1808
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001809PyDoc_STRVAR(sortwrapper_doc, "Object wrapper with a custom sort key.");
Anthony Baxter377be112006-04-11 06:54:30 +00001810static PyObject *
1811sortwrapper_richcompare(sortwrapperobject *, sortwrapperobject *, int);
1812static void
1813sortwrapper_dealloc(sortwrapperobject *);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001814
1815static PyTypeObject sortwrapper_type = {
1816 PyObject_HEAD_INIT(&PyType_Type)
1817 0, /* ob_size */
1818 "sortwrapper", /* tp_name */
1819 sizeof(sortwrapperobject), /* tp_basicsize */
1820 0, /* tp_itemsize */
1821 /* methods */
1822 (destructor)sortwrapper_dealloc, /* tp_dealloc */
1823 0, /* tp_print */
1824 0, /* tp_getattr */
1825 0, /* tp_setattr */
1826 0, /* tp_compare */
1827 0, /* tp_repr */
1828 0, /* tp_as_number */
1829 0, /* tp_as_sequence */
1830 0, /* tp_as_mapping */
1831 0, /* tp_hash */
1832 0, /* tp_call */
1833 0, /* tp_str */
1834 PyObject_GenericGetAttr, /* tp_getattro */
1835 0, /* tp_setattro */
1836 0, /* tp_as_buffer */
Tim Petersb38e2b62004-07-29 02:29:26 +00001837 Py_TPFLAGS_DEFAULT |
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001838 Py_TPFLAGS_HAVE_RICHCOMPARE, /* tp_flags */
1839 sortwrapper_doc, /* tp_doc */
1840 0, /* tp_traverse */
1841 0, /* tp_clear */
1842 (richcmpfunc)sortwrapper_richcompare, /* tp_richcompare */
1843};
1844
Anthony Baxter377be112006-04-11 06:54:30 +00001845
1846static PyObject *
1847sortwrapper_richcompare(sortwrapperobject *a, sortwrapperobject *b, int op)
1848{
1849 if (!PyObject_TypeCheck(b, &sortwrapper_type)) {
1850 PyErr_SetString(PyExc_TypeError,
1851 "expected a sortwrapperobject");
1852 return NULL;
1853 }
1854 return PyObject_RichCompare(a->key, b->key, op);
1855}
1856
1857static void
1858sortwrapper_dealloc(sortwrapperobject *so)
1859{
1860 Py_XDECREF(so->key);
1861 Py_XDECREF(so->value);
1862 PyObject_Del(so);
1863}
1864
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001865/* Returns a new reference to a sortwrapper.
1866 Consumes the references to the two underlying objects. */
1867
1868static PyObject *
1869build_sortwrapper(PyObject *key, PyObject *value)
1870{
1871 sortwrapperobject *so;
Tim Petersb38e2b62004-07-29 02:29:26 +00001872
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001873 so = PyObject_New(sortwrapperobject, &sortwrapper_type);
1874 if (so == NULL)
1875 return NULL;
1876 so->key = key;
1877 so->value = value;
1878 return (PyObject *)so;
1879}
1880
1881/* Returns a new reference to the value underlying the wrapper. */
1882static PyObject *
1883sortwrapper_getvalue(PyObject *so)
1884{
1885 PyObject *value;
1886
1887 if (!PyObject_TypeCheck(so, &sortwrapper_type)) {
Tim Petersb38e2b62004-07-29 02:29:26 +00001888 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001889 "expected a sortwrapperobject");
1890 return NULL;
1891 }
1892 value = ((sortwrapperobject *)so)->value;
1893 Py_INCREF(value);
1894 return value;
1895}
1896
1897/* Wrapper for user specified cmp functions in combination with a
1898 specified key function. Makes sure the cmp function is presented
1899 with the actual key instead of the sortwrapper */
1900
1901typedef struct {
1902 PyObject_HEAD
1903 PyObject *func;
1904} cmpwrapperobject;
1905
1906static void
1907cmpwrapper_dealloc(cmpwrapperobject *co)
1908{
1909 Py_XDECREF(co->func);
1910 PyObject_Del(co);
1911}
1912
1913static PyObject *
1914cmpwrapper_call(cmpwrapperobject *co, PyObject *args, PyObject *kwds)
1915{
1916 PyObject *x, *y, *xx, *yy;
1917
1918 if (!PyArg_UnpackTuple(args, "", 2, 2, &x, &y))
1919 return NULL;
1920 if (!PyObject_TypeCheck(x, &sortwrapper_type) ||
Raymond Hettingerae4a2992003-10-16 17:16:30 +00001921 !PyObject_TypeCheck(y, &sortwrapper_type)) {
Tim Petersb38e2b62004-07-29 02:29:26 +00001922 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001923 "expected a sortwrapperobject");
1924 return NULL;
1925 }
1926 xx = ((sortwrapperobject *)x)->key;
1927 yy = ((sortwrapperobject *)y)->key;
1928 return PyObject_CallFunctionObjArgs(co->func, xx, yy, NULL);
1929}
1930
1931PyDoc_STRVAR(cmpwrapper_doc, "cmp() wrapper for sort with custom keys.");
1932
1933static PyTypeObject cmpwrapper_type = {
1934 PyObject_HEAD_INIT(&PyType_Type)
1935 0, /* ob_size */
1936 "cmpwrapper", /* tp_name */
1937 sizeof(cmpwrapperobject), /* tp_basicsize */
1938 0, /* tp_itemsize */
1939 /* methods */
1940 (destructor)cmpwrapper_dealloc, /* tp_dealloc */
1941 0, /* tp_print */
1942 0, /* tp_getattr */
1943 0, /* tp_setattr */
1944 0, /* tp_compare */
1945 0, /* tp_repr */
1946 0, /* tp_as_number */
1947 0, /* tp_as_sequence */
1948 0, /* tp_as_mapping */
1949 0, /* tp_hash */
1950 (ternaryfunc)cmpwrapper_call, /* tp_call */
1951 0, /* tp_str */
1952 PyObject_GenericGetAttr, /* tp_getattro */
1953 0, /* tp_setattro */
1954 0, /* tp_as_buffer */
1955 Py_TPFLAGS_DEFAULT, /* tp_flags */
1956 cmpwrapper_doc, /* tp_doc */
1957};
1958
1959static PyObject *
1960build_cmpwrapper(PyObject *cmpfunc)
1961{
1962 cmpwrapperobject *co;
Tim Petersb38e2b62004-07-29 02:29:26 +00001963
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001964 co = PyObject_New(cmpwrapperobject, &cmpwrapper_type);
1965 if (co == NULL)
1966 return NULL;
1967 Py_INCREF(cmpfunc);
1968 co->func = cmpfunc;
1969 return (PyObject *)co;
1970}
1971
Tim Petersa64dc242002-08-01 02:13:36 +00001972/* An adaptive, stable, natural mergesort. See listsort.txt.
1973 * Returns Py_None on success, NULL on error. Even in case of error, the
1974 * list will be some permutation of its input state (nothing is lost or
1975 * duplicated).
1976 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001977static PyObject *
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001978listsort(PyListObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f236de1996-12-10 23:55:39 +00001979{
Tim Petersa64dc242002-08-01 02:13:36 +00001980 MergeState ms;
1981 PyObject **lo, **hi;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001982 Py_ssize_t nremaining;
1983 Py_ssize_t minrun;
1984 Py_ssize_t saved_ob_size, saved_allocated;
Tim Petersb9099c32002-11-12 22:08:10 +00001985 PyObject **saved_ob_item;
Armin Rigo93677f02004-07-29 12:40:23 +00001986 PyObject **final_ob_item;
Tim Petersa64dc242002-08-01 02:13:36 +00001987 PyObject *compare = NULL;
1988 PyObject *result = NULL; /* guilty until proved innocent */
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001989 int reverse = 0;
1990 PyObject *keyfunc = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001991 Py_ssize_t i;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001992 PyObject *key, *value, *kvpair;
Martin v. Löwis15e62742006-02-27 16:46:16 +00001993 static char *kwlist[] = {"cmp", "key", "reverse", 0};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001994
Tim Petersa64dc242002-08-01 02:13:36 +00001995 assert(self != NULL);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001996 assert (PyList_Check(self));
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001997 if (args != NULL) {
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001998 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOi:sort",
1999 kwlist, &compare, &keyfunc, &reverse))
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002000 return NULL;
2001 }
Skip Montanaro4abd5f02003-01-02 20:51:08 +00002002 if (compare == Py_None)
2003 compare = NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002004 if (keyfunc == Py_None)
2005 keyfunc = NULL;
2006 if (compare != NULL && keyfunc != NULL) {
2007 compare = build_cmpwrapper(compare);
2008 if (compare == NULL)
Hye-Shik Chang19cb1932003-12-10 07:31:08 +00002009 return NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002010 } else
2011 Py_XINCREF(compare);
2012
Tim Petersb9099c32002-11-12 22:08:10 +00002013 /* The list is temporarily made empty, so that mutations performed
2014 * by comparison functions can't affect the slice of memory we're
2015 * sorting (allowing mutations during sorting is a core-dump
2016 * factory, since ob_item may change).
2017 */
2018 saved_ob_size = self->ob_size;
2019 saved_ob_item = self->ob_item;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002020 saved_allocated = self->allocated;
Armin Rigo93677f02004-07-29 12:40:23 +00002021 self->ob_size = 0;
Tim Peters51b4ade2004-07-29 04:07:15 +00002022 self->ob_item = NULL;
Armin Rigo93677f02004-07-29 12:40:23 +00002023 self->allocated = -1; /* any operation will reset it to >= 0 */
Tim Peters330f9e92002-07-19 07:05:44 +00002024
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002025 if (keyfunc != NULL) {
2026 for (i=0 ; i < saved_ob_size ; i++) {
2027 value = saved_ob_item[i];
Tim Petersb38e2b62004-07-29 02:29:26 +00002028 key = PyObject_CallFunctionObjArgs(keyfunc, value,
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002029 NULL);
2030 if (key == NULL) {
2031 for (i=i-1 ; i>=0 ; i--) {
2032 kvpair = saved_ob_item[i];
2033 value = sortwrapper_getvalue(kvpair);
2034 saved_ob_item[i] = value;
2035 Py_DECREF(kvpair);
2036 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002037 goto dsu_fail;
2038 }
2039 kvpair = build_sortwrapper(key, value);
2040 if (kvpair == NULL)
2041 goto dsu_fail;
2042 saved_ob_item[i] = kvpair;
2043 }
2044 }
2045
2046 /* Reverse sort stability achieved by initially reversing the list,
2047 applying a stable forward sort, then reversing the final result. */
2048 if (reverse && saved_ob_size > 1)
2049 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
2050
2051 merge_init(&ms, compare);
2052
Tim Petersb9099c32002-11-12 22:08:10 +00002053 nremaining = saved_ob_size;
Tim Petersa64dc242002-08-01 02:13:36 +00002054 if (nremaining < 2)
2055 goto succeed;
Tim Peters330f9e92002-07-19 07:05:44 +00002056
Tim Petersa64dc242002-08-01 02:13:36 +00002057 /* March over the array once, left to right, finding natural runs,
2058 * and extending short natural runs to minrun elements.
2059 */
Tim Petersb9099c32002-11-12 22:08:10 +00002060 lo = saved_ob_item;
Tim Petersa64dc242002-08-01 02:13:36 +00002061 hi = lo + nremaining;
2062 minrun = merge_compute_minrun(nremaining);
2063 do {
2064 int descending;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002065 Py_ssize_t n;
Tim Peters330f9e92002-07-19 07:05:44 +00002066
Tim Petersa64dc242002-08-01 02:13:36 +00002067 /* Identify next run. */
2068 n = count_run(lo, hi, compare, &descending);
2069 if (n < 0)
2070 goto fail;
2071 if (descending)
2072 reverse_slice(lo, lo + n);
2073 /* If short, extend to min(minrun, nremaining). */
2074 if (n < minrun) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002075 const Py_ssize_t force = nremaining <= minrun ?
Tim Petersa64dc242002-08-01 02:13:36 +00002076 nremaining : minrun;
2077 if (binarysort(lo, lo + force, lo + n, compare) < 0)
2078 goto fail;
2079 n = force;
2080 }
2081 /* Push run onto pending-runs stack, and maybe merge. */
2082 assert(ms.n < MAX_MERGE_PENDING);
Tim Peterse05f65a2002-08-10 05:21:15 +00002083 ms.pending[ms.n].base = lo;
2084 ms.pending[ms.n].len = n;
Tim Petersa64dc242002-08-01 02:13:36 +00002085 ++ms.n;
2086 if (merge_collapse(&ms) < 0)
2087 goto fail;
2088 /* Advance to find next run. */
2089 lo += n;
2090 nremaining -= n;
2091 } while (nremaining);
2092 assert(lo == hi);
Tim Peters330f9e92002-07-19 07:05:44 +00002093
Tim Petersa64dc242002-08-01 02:13:36 +00002094 if (merge_force_collapse(&ms) < 0)
2095 goto fail;
2096 assert(ms.n == 1);
Tim Petersb9099c32002-11-12 22:08:10 +00002097 assert(ms.pending[0].base == saved_ob_item);
2098 assert(ms.pending[0].len == saved_ob_size);
Tim Petersa64dc242002-08-01 02:13:36 +00002099
2100succeed:
2101 result = Py_None;
Tim Peters330f9e92002-07-19 07:05:44 +00002102fail:
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002103 if (keyfunc != NULL) {
2104 for (i=0 ; i < saved_ob_size ; i++) {
2105 kvpair = saved_ob_item[i];
2106 value = sortwrapper_getvalue(kvpair);
2107 saved_ob_item[i] = value;
2108 Py_DECREF(kvpair);
2109 }
2110 }
2111
Armin Rigo93677f02004-07-29 12:40:23 +00002112 if (self->allocated != -1 && result != NULL) {
Tim Peters51b4ade2004-07-29 04:07:15 +00002113 /* The user mucked with the list during the sort,
2114 * and we don't already have another error to report.
2115 */
2116 PyErr_SetString(PyExc_ValueError, "list modified during sort");
2117 result = NULL;
Tim Petersb9099c32002-11-12 22:08:10 +00002118 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002119
2120 if (reverse && saved_ob_size > 1)
2121 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
2122
2123 merge_freemem(&ms);
2124
2125dsu_fail:
Armin Rigo93677f02004-07-29 12:40:23 +00002126 final_ob_item = self->ob_item;
2127 i = self->ob_size;
Tim Petersb9099c32002-11-12 22:08:10 +00002128 self->ob_size = saved_ob_size;
2129 self->ob_item = saved_ob_item;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002130 self->allocated = saved_allocated;
Armin Rigo93677f02004-07-29 12:40:23 +00002131 if (final_ob_item != NULL) {
2132 /* we cannot use list_clear() for this because it does not
2133 guarantee that the list is really empty when it returns */
2134 while (--i >= 0) {
2135 Py_XDECREF(final_ob_item[i]);
2136 }
2137 PyMem_FREE(final_ob_item);
2138 }
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002139 Py_XDECREF(compare);
Tim Petersa64dc242002-08-01 02:13:36 +00002140 Py_XINCREF(result);
2141 return result;
Guido van Rossum3f236de1996-12-10 23:55:39 +00002142}
Tim Peters330f9e92002-07-19 07:05:44 +00002143#undef IFLT
Tim Peters66860f62002-08-04 17:47:26 +00002144#undef ISLT
Tim Peters330f9e92002-07-19 07:05:44 +00002145
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002146int
Fred Drakea2f55112000-07-09 15:16:51 +00002147PyList_Sort(PyObject *v)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002148{
2149 if (v == NULL || !PyList_Check(v)) {
2150 PyErr_BadInternalCall();
2151 return -1;
2152 }
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002153 v = listsort((PyListObject *)v, (PyObject *)NULL, (PyObject *)NULL);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002154 if (v == NULL)
2155 return -1;
2156 Py_DECREF(v);
2157 return 0;
2158}
2159
Guido van Rossumb86c5492001-02-12 22:06:02 +00002160static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002161listreverse(PyListObject *self)
Guido van Rossumb86c5492001-02-12 22:06:02 +00002162{
Tim Peters326b4482002-07-19 04:04:16 +00002163 if (self->ob_size > 1)
2164 reverse_slice(self->ob_item, self->ob_item + self->ob_size);
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +00002165 Py_RETURN_NONE;
Guido van Rossumed98d481991-03-06 13:07:53 +00002166}
2167
Guido van Rossum84c76f51990-10-30 13:32:20 +00002168int
Fred Drakea2f55112000-07-09 15:16:51 +00002169PyList_Reverse(PyObject *v)
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002170{
Tim Peters6063e262002-08-08 01:06:39 +00002171 PyListObject *self = (PyListObject *)v;
2172
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002173 if (v == NULL || !PyList_Check(v)) {
2174 PyErr_BadInternalCall();
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002175 return -1;
2176 }
Tim Peters6063e262002-08-08 01:06:39 +00002177 if (self->ob_size > 1)
2178 reverse_slice(self->ob_item, self->ob_item + self->ob_size);
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002179 return 0;
2180}
2181
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002182PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00002183PyList_AsTuple(PyObject *v)
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002184{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002185 PyObject *w;
2186 PyObject **p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002187 Py_ssize_t n;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002188 if (v == NULL || !PyList_Check(v)) {
2189 PyErr_BadInternalCall();
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002190 return NULL;
2191 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002192 n = ((PyListObject *)v)->ob_size;
2193 w = PyTuple_New(n);
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002194 if (w == NULL)
2195 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002196 p = ((PyTupleObject *)w)->ob_item;
Thomas Wouters334fb892000-07-25 12:56:38 +00002197 memcpy((void *)p,
2198 (void *)((PyListObject *)v)->ob_item,
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002199 n*sizeof(PyObject *));
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002200 while (--n >= 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002201 Py_INCREF(*p);
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002202 p++;
2203 }
2204 return w;
2205}
2206
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002207static PyObject *
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002208listindex(PyListObject *self, PyObject *args)
Guido van Rossumed98d481991-03-06 13:07:53 +00002209{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002210 Py_ssize_t i, start=0, stop=self->ob_size;
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002211 PyObject *v;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002212
Walter Dörwalde8049bef2003-06-17 19:27:39 +00002213 if (!PyArg_ParseTuple(args, "O|O&O&:index", &v,
2214 _PyEval_SliceIndex, &start,
2215 _PyEval_SliceIndex, &stop))
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002216 return NULL;
Guido van Rossum2743d872003-06-17 14:25:14 +00002217 if (start < 0) {
2218 start += self->ob_size;
2219 if (start < 0)
2220 start = 0;
2221 }
2222 if (stop < 0) {
2223 stop += self->ob_size;
2224 if (stop < 0)
2225 stop = 0;
2226 }
Neal Norwitzf0769532004-08-13 03:18:29 +00002227 for (i = start; i < stop && i < self->ob_size; i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002228 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2229 if (cmp > 0)
Martin v. Löwis18e16552006-02-15 17:27:45 +00002230 return PyInt_FromSsize_t(i);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002231 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002232 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002233 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002234 PyErr_SetString(PyExc_ValueError, "list.index(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00002235 return NULL;
2236}
2237
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002238static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002239listcount(PyListObject *self, PyObject *v)
Guido van Rossume6f7d181991-10-20 20:20:40 +00002240{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002241 Py_ssize_t count = 0;
2242 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002243
Guido van Rossume6f7d181991-10-20 20:20:40 +00002244 for (i = 0; i < self->ob_size; i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002245 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2246 if (cmp > 0)
Guido van Rossume6f7d181991-10-20 20:20:40 +00002247 count++;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002248 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002249 return NULL;
Guido van Rossume6f7d181991-10-20 20:20:40 +00002250 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002251 return PyInt_FromSsize_t(count);
Guido van Rossume6f7d181991-10-20 20:20:40 +00002252}
2253
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002254static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002255listremove(PyListObject *self, PyObject *v)
Guido van Rossumed98d481991-03-06 13:07:53 +00002256{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002257 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002258
Guido van Rossumed98d481991-03-06 13:07:53 +00002259 for (i = 0; i < self->ob_size; i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002260 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2261 if (cmp > 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002262 if (list_ass_slice(self, i, i+1,
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +00002263 (PyObject *)NULL) == 0)
2264 Py_RETURN_NONE;
2265 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002266 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002267 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002268 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002269 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002270 PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00002271 return NULL;
2272}
2273
Jeremy Hylton8caad492000-06-23 14:18:11 +00002274static int
2275list_traverse(PyListObject *o, visitproc visit, void *arg)
2276{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002277 Py_ssize_t i;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002278
Thomas Woutersc6e55062006-04-15 21:47:09 +00002279 for (i = o->ob_size; --i >= 0; )
2280 Py_VISIT(o->ob_item[i]);
Jeremy Hylton8caad492000-06-23 14:18:11 +00002281 return 0;
2282}
2283
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002284static PyObject *
2285list_richcompare(PyObject *v, PyObject *w, int op)
2286{
2287 PyListObject *vl, *wl;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002288 Py_ssize_t i;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002289
2290 if (!PyList_Check(v) || !PyList_Check(w)) {
2291 Py_INCREF(Py_NotImplemented);
2292 return Py_NotImplemented;
2293 }
2294
2295 vl = (PyListObject *)v;
2296 wl = (PyListObject *)w;
2297
2298 if (vl->ob_size != wl->ob_size && (op == Py_EQ || op == Py_NE)) {
2299 /* Shortcut: if the lengths differ, the lists differ */
2300 PyObject *res;
2301 if (op == Py_EQ)
2302 res = Py_False;
2303 else
2304 res = Py_True;
2305 Py_INCREF(res);
2306 return res;
2307 }
2308
2309 /* Search for the first index where items are different */
2310 for (i = 0; i < vl->ob_size && i < wl->ob_size; i++) {
2311 int k = PyObject_RichCompareBool(vl->ob_item[i],
2312 wl->ob_item[i], Py_EQ);
2313 if (k < 0)
2314 return NULL;
2315 if (!k)
2316 break;
2317 }
2318
2319 if (i >= vl->ob_size || i >= wl->ob_size) {
2320 /* No more items to compare -- compare sizes */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002321 Py_ssize_t vs = vl->ob_size;
2322 Py_ssize_t ws = wl->ob_size;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002323 int cmp;
2324 PyObject *res;
2325 switch (op) {
2326 case Py_LT: cmp = vs < ws; break;
Tim Peters6ee42342001-07-06 17:45:43 +00002327 case Py_LE: cmp = vs <= ws; break;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002328 case Py_EQ: cmp = vs == ws; break;
2329 case Py_NE: cmp = vs != ws; break;
2330 case Py_GT: cmp = vs > ws; break;
2331 case Py_GE: cmp = vs >= ws; break;
2332 default: return NULL; /* cannot happen */
2333 }
2334 if (cmp)
2335 res = Py_True;
2336 else
2337 res = Py_False;
2338 Py_INCREF(res);
2339 return res;
2340 }
2341
2342 /* We have an item that differs -- shortcuts for EQ/NE */
2343 if (op == Py_EQ) {
2344 Py_INCREF(Py_False);
2345 return Py_False;
2346 }
2347 if (op == Py_NE) {
2348 Py_INCREF(Py_True);
2349 return Py_True;
2350 }
2351
2352 /* Compare the final item again using the proper operator */
2353 return PyObject_RichCompare(vl->ob_item[i], wl->ob_item[i], op);
2354}
2355
Tim Peters6d6c1a32001-08-02 04:15:00 +00002356static int
2357list_init(PyListObject *self, PyObject *args, PyObject *kw)
2358{
2359 PyObject *arg = NULL;
Martin v. Löwis15e62742006-02-27 16:46:16 +00002360 static char *kwlist[] = {"sequence", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002361
2362 if (!PyArg_ParseTupleAndKeywords(args, kw, "|O:list", kwlist, &arg))
2363 return -1;
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002364
2365 /* Verify list invariants established by PyType_GenericAlloc() */
Armin Rigoa37bbf22004-07-30 11:20:18 +00002366 assert(0 <= self->ob_size);
2367 assert(self->ob_size <= self->allocated || self->allocated == -1);
2368 assert(self->ob_item != NULL ||
2369 self->allocated == 0 || self->allocated == -1);
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002370
Raymond Hettinger90a39bf2004-02-15 03:57:00 +00002371 /* Empty previous contents */
Armin Rigo93677f02004-07-29 12:40:23 +00002372 if (self->ob_item != NULL) {
2373 (void)list_clear(self);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +00002374 }
2375 if (arg != NULL) {
2376 PyObject *rv = listextend(self, arg);
2377 if (rv == NULL)
2378 return -1;
2379 Py_DECREF(rv);
2380 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002381 return 0;
2382}
2383
Guido van Rossumdbb53d92001-12-03 16:32:18 +00002384static long
2385list_nohash(PyObject *self)
2386{
2387 PyErr_SetString(PyExc_TypeError, "list objects are unhashable");
2388 return -1;
2389}
2390
Raymond Hettinger1021c442003-11-07 15:38:09 +00002391static PyObject *list_iter(PyObject *seq);
2392static PyObject *list_reversed(PyListObject* seq, PyObject* unused);
2393
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002394PyDoc_STRVAR(getitem_doc,
2395"x.__getitem__(y) <==> x[y]");
Raymond Hettinger1021c442003-11-07 15:38:09 +00002396PyDoc_STRVAR(reversed_doc,
2397"L.__reversed__() -- return a reverse iterator over the list");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002398PyDoc_STRVAR(append_doc,
2399"L.append(object) -- append object to end");
2400PyDoc_STRVAR(extend_doc,
Raymond Hettingerf8bcfb12002-12-29 05:49:09 +00002401"L.extend(iterable) -- extend list by appending elements from the iterable");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002402PyDoc_STRVAR(insert_doc,
2403"L.insert(index, object) -- insert object before index");
2404PyDoc_STRVAR(pop_doc,
2405"L.pop([index]) -> item -- remove and return item at index (default last)");
2406PyDoc_STRVAR(remove_doc,
2407"L.remove(value) -- remove first occurrence of value");
2408PyDoc_STRVAR(index_doc,
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002409"L.index(value, [start, [stop]]) -> integer -- return first index of value");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002410PyDoc_STRVAR(count_doc,
2411"L.count(value) -> integer -- return number of occurrences of value");
2412PyDoc_STRVAR(reverse_doc,
2413"L.reverse() -- reverse *IN PLACE*");
2414PyDoc_STRVAR(sort_doc,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002415"L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;\n\
2416cmp(x, y) -> -1, 0, 1");
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +00002417
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002418static PyObject *list_subscript(PyListObject*, PyObject*);
2419
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002420static PyMethodDef list_methods[] = {
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002421 {"__getitem__", (PyCFunction)list_subscript, METH_O|METH_COEXIST, getitem_doc},
Raymond Hettinger1021c442003-11-07 15:38:09 +00002422 {"__reversed__",(PyCFunction)list_reversed, METH_NOARGS, reversed_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002423 {"append", (PyCFunction)listappend, METH_O, append_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002424 {"insert", (PyCFunction)listinsert, METH_VARARGS, insert_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002425 {"extend", (PyCFunction)listextend, METH_O, extend_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002426 {"pop", (PyCFunction)listpop, METH_VARARGS, pop_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002427 {"remove", (PyCFunction)listremove, METH_O, remove_doc},
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002428 {"index", (PyCFunction)listindex, METH_VARARGS, index_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002429 {"count", (PyCFunction)listcount, METH_O, count_doc},
2430 {"reverse", (PyCFunction)listreverse, METH_NOARGS, reverse_doc},
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002431 {"sort", (PyCFunction)listsort, METH_VARARGS | METH_KEYWORDS, sort_doc},
Tim Petersa64dc242002-08-01 02:13:36 +00002432 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002433};
2434
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002435static PySequenceMethods list_as_sequence = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002436 (lenfunc)list_length, /* sq_length */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002437 (binaryfunc)list_concat, /* sq_concat */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002438 (ssizeargfunc)list_repeat, /* sq_repeat */
2439 (ssizeargfunc)list_item, /* sq_item */
2440 (ssizessizeargfunc)list_slice, /* sq_slice */
2441 (ssizeobjargproc)list_ass_item, /* sq_ass_item */
2442 (ssizessizeobjargproc)list_ass_slice, /* sq_ass_slice */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002443 (objobjproc)list_contains, /* sq_contains */
2444 (binaryfunc)list_inplace_concat, /* sq_inplace_concat */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002445 (ssizeargfunc)list_inplace_repeat, /* sq_inplace_repeat */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002446};
2447
Neal Norwitz2c2e8272002-06-14 02:04:18 +00002448PyDoc_STRVAR(list_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002449"list() -> new list\n"
Neal Norwitz2c2e8272002-06-14 02:04:18 +00002450"list(sequence) -> new list initialized from sequence's items");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002451
Guido van Rossum38fff8c2006-03-07 18:50:55 +00002452
Jeremy Hyltona4b4c3b2002-07-13 03:51:17 +00002453static PyObject *
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002454list_subscript(PyListObject* self, PyObject* item)
2455{
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00002456 if (PyIndex_Check(item)) {
2457 Py_ssize_t i;
2458 i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002459 if (i == -1 && PyErr_Occurred())
2460 return NULL;
2461 if (i < 0)
2462 i += PyList_GET_SIZE(self);
2463 return list_item(self, i);
2464 }
2465 else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002466 Py_ssize_t start, stop, step, slicelength, cur, i;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002467 PyObject* result;
2468 PyObject* it;
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002469 PyObject **src, **dest;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002470
2471 if (PySlice_GetIndicesEx((PySliceObject*)item, self->ob_size,
2472 &start, &stop, &step, &slicelength) < 0) {
2473 return NULL;
2474 }
2475
2476 if (slicelength <= 0) {
2477 return PyList_New(0);
2478 }
2479 else {
2480 result = PyList_New(slicelength);
2481 if (!result) return NULL;
2482
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002483 src = self->ob_item;
2484 dest = ((PyListObject *)result)->ob_item;
Tim Peters3b01a122002-07-19 02:35:45 +00002485 for (cur = start, i = 0; i < slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002486 cur += step, i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002487 it = src[cur];
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002488 Py_INCREF(it);
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002489 dest[i] = it;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002490 }
Tim Peters3b01a122002-07-19 02:35:45 +00002491
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002492 return result;
2493 }
2494 }
2495 else {
2496 PyErr_SetString(PyExc_TypeError,
2497 "list indices must be integers");
2498 return NULL;
2499 }
2500}
2501
Tim Peters3b01a122002-07-19 02:35:45 +00002502static int
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002503list_ass_subscript(PyListObject* self, PyObject* item, PyObject* value)
2504{
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00002505 if (PyIndex_Check(item)) {
2506 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002507 if (i == -1 && PyErr_Occurred())
2508 return -1;
2509 if (i < 0)
2510 i += PyList_GET_SIZE(self);
2511 return list_ass_item(self, i, value);
2512 }
2513 else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002514 Py_ssize_t start, stop, step, slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002515
2516 if (PySlice_GetIndicesEx((PySliceObject*)item, self->ob_size,
2517 &start, &stop, &step, &slicelength) < 0) {
2518 return -1;
2519 }
2520
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002521 /* treat L[slice(a,b)] = v _exactly_ like L[a:b] = v */
2522 if (step == 1 && ((PySliceObject*)item)->step == Py_None)
2523 return list_ass_slice(self, start, stop, value);
2524
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002525 if (value == NULL) {
2526 /* delete slice */
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002527 PyObject **garbage;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002528 Py_ssize_t cur, i;
Tim Peters3b01a122002-07-19 02:35:45 +00002529
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002530 if (slicelength <= 0)
2531 return 0;
2532
2533 if (step < 0) {
2534 stop = start + 1;
2535 start = stop + step*(slicelength - 1) - 1;
2536 step = -step;
2537 }
2538
2539 garbage = (PyObject**)
2540 PyMem_MALLOC(slicelength*sizeof(PyObject*));
Neal Norwitzb88cfad2006-08-12 03:16:54 +00002541 if (!garbage) {
2542 PyErr_NoMemory();
2543 return -1;
2544 }
Tim Peters3b01a122002-07-19 02:35:45 +00002545
2546 /* drawing pictures might help
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002547 understand these for loops */
Guido van Rossum75a20b12002-06-11 12:22:28 +00002548 for (cur = start, i = 0;
2549 cur < stop;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002550 cur += step, i++) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002551 Py_ssize_t lim = step;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002552
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002553 garbage[i] = PyList_GET_ITEM(self, cur);
2554
Michael W. Hudson56796f62002-07-29 14:35:04 +00002555 if (cur + step >= self->ob_size) {
2556 lim = self->ob_size - cur - 1;
2557 }
2558
Tim Petersb38e2b62004-07-29 02:29:26 +00002559 memmove(self->ob_item + cur - i,
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002560 self->ob_item + cur + 1,
2561 lim * sizeof(PyObject *));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002562 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002563
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002564 for (cur = start + slicelength*step + 1;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002565 cur < self->ob_size; cur++) {
2566 PyList_SET_ITEM(self, cur - slicelength,
2567 PyList_GET_ITEM(self, cur));
2568 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002569
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002570 self->ob_size -= slicelength;
Raymond Hettingerd4ff7412004-03-15 09:01:31 +00002571 list_resize(self, self->ob_size);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002572
2573 for (i = 0; i < slicelength; i++) {
2574 Py_DECREF(garbage[i]);
2575 }
2576 PyMem_FREE(garbage);
2577
2578 return 0;
2579 }
2580 else {
2581 /* assign slice */
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002582 PyObject **garbage, *ins, *seq, **seqitems, **selfitems;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002583 Py_ssize_t cur, i;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002584
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002585 /* protect against a[::-1] = a */
Tim Peters3b01a122002-07-19 02:35:45 +00002586 if (self == (PyListObject*)value) {
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002587 seq = list_slice((PyListObject*)value, 0,
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002588 PyList_GET_SIZE(value));
Tim Peters3b01a122002-07-19 02:35:45 +00002589 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002590 else {
Tim Petersb38e2b62004-07-29 02:29:26 +00002591 seq = PySequence_Fast(value,
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002592 "must assign iterable to extended slice");
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002593 }
Neal Norwitzb88cfad2006-08-12 03:16:54 +00002594 if (!seq)
2595 return -1;
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002596
2597 if (PySequence_Fast_GET_SIZE(seq) != slicelength) {
2598 PyErr_Format(PyExc_ValueError,
Martin v. Löwis2c95cc62006-02-16 06:54:25 +00002599 "attempt to assign sequence of size %zd to extended slice of size %zd",
Martin v. Löwise0e89f72006-02-16 06:59:22 +00002600 PySequence_Fast_GET_SIZE(seq),
2601 slicelength);
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002602 Py_DECREF(seq);
2603 return -1;
2604 }
2605
2606 if (!slicelength) {
2607 Py_DECREF(seq);
2608 return 0;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002609 }
2610
2611 garbage = (PyObject**)
2612 PyMem_MALLOC(slicelength*sizeof(PyObject*));
Neal Norwitze0cf6242006-10-28 21:39:10 +00002613 if (!garbage) {
2614 Py_DECREF(seq);
2615 PyErr_NoMemory();
2616 return -1;
2617 }
Tim Peters3b01a122002-07-19 02:35:45 +00002618
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002619 selfitems = self->ob_item;
Raymond Hettinger42bec932004-03-12 16:38:17 +00002620 seqitems = PySequence_Fast_ITEMS(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002621 for (cur = start, i = 0; i < slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002622 cur += step, i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002623 garbage[i] = selfitems[cur];
2624 ins = seqitems[i];
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002625 Py_INCREF(ins);
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002626 selfitems[cur] = ins;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002627 }
2628
2629 for (i = 0; i < slicelength; i++) {
2630 Py_DECREF(garbage[i]);
2631 }
Tim Peters3b01a122002-07-19 02:35:45 +00002632
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002633 PyMem_FREE(garbage);
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002634 Py_DECREF(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002635
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002636 return 0;
2637 }
Tim Peters3b01a122002-07-19 02:35:45 +00002638 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002639 else {
Tim Peters3b01a122002-07-19 02:35:45 +00002640 PyErr_SetString(PyExc_TypeError,
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002641 "list indices must be integers");
2642 return -1;
2643 }
2644}
2645
2646static PyMappingMethods list_as_mapping = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002647 (lenfunc)list_length,
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002648 (binaryfunc)list_subscript,
2649 (objobjargproc)list_ass_subscript
2650};
2651
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002652PyTypeObject PyList_Type = {
2653 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002654 0,
2655 "list",
Neil Schemenauere83c00e2001-08-29 23:54:21 +00002656 sizeof(PyListObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002657 0,
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002658 (destructor)list_dealloc, /* tp_dealloc */
2659 (printfunc)list_print, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002660 0, /* tp_getattr */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002661 0, /* tp_setattr */
2662 0, /* tp_compare */
2663 (reprfunc)list_repr, /* tp_repr */
2664 0, /* tp_as_number */
2665 &list_as_sequence, /* tp_as_sequence */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002666 &list_as_mapping, /* tp_as_mapping */
Guido van Rossumdbb53d92001-12-03 16:32:18 +00002667 list_nohash, /* tp_hash */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002668 0, /* tp_call */
2669 0, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002670 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002671 0, /* tp_setattro */
2672 0, /* tp_as_buffer */
Neil Schemenauere83c00e2001-08-29 23:54:21 +00002673 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Tim Peters6d6c1a32001-08-02 04:15:00 +00002674 Py_TPFLAGS_BASETYPE, /* tp_flags */
2675 list_doc, /* tp_doc */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002676 (traverseproc)list_traverse, /* tp_traverse */
2677 (inquiry)list_clear, /* tp_clear */
2678 list_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002679 0, /* tp_weaklistoffset */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002680 list_iter, /* tp_iter */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002681 0, /* tp_iternext */
2682 list_methods, /* tp_methods */
2683 0, /* tp_members */
2684 0, /* tp_getset */
2685 0, /* tp_base */
2686 0, /* tp_dict */
2687 0, /* tp_descr_get */
2688 0, /* tp_descr_set */
2689 0, /* tp_dictoffset */
2690 (initproc)list_init, /* tp_init */
2691 PyType_GenericAlloc, /* tp_alloc */
2692 PyType_GenericNew, /* tp_new */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002693 PyObject_GC_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002694};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002695
2696
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002697/*********************** List Iterator **************************/
2698
2699typedef struct {
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002700 PyObject_HEAD
2701 long it_index;
Guido van Rossum86103ae2002-07-16 20:07:32 +00002702 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002703} listiterobject;
2704
Anthony Baxter377be112006-04-11 06:54:30 +00002705static PyObject *list_iter(PyObject *);
2706static void listiter_dealloc(listiterobject *);
2707static int listiter_traverse(listiterobject *, visitproc, void *);
2708static PyObject *listiter_next(listiterobject *);
2709static PyObject *listiter_len(listiterobject *);
2710
2711PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
2712
2713static PyMethodDef listiter_methods[] = {
2714 {"__length_hint__", (PyCFunction)listiter_len, METH_NOARGS, length_hint_doc},
2715 {NULL, NULL} /* sentinel */
2716};
2717
2718PyTypeObject PyListIter_Type = {
2719 PyObject_HEAD_INIT(&PyType_Type)
2720 0, /* ob_size */
2721 "listiterator", /* tp_name */
2722 sizeof(listiterobject), /* tp_basicsize */
2723 0, /* tp_itemsize */
2724 /* methods */
2725 (destructor)listiter_dealloc, /* tp_dealloc */
2726 0, /* tp_print */
2727 0, /* tp_getattr */
2728 0, /* tp_setattr */
2729 0, /* tp_compare */
2730 0, /* tp_repr */
2731 0, /* tp_as_number */
2732 0, /* tp_as_sequence */
2733 0, /* tp_as_mapping */
2734 0, /* tp_hash */
2735 0, /* tp_call */
2736 0, /* tp_str */
2737 PyObject_GenericGetAttr, /* tp_getattro */
2738 0, /* tp_setattro */
2739 0, /* tp_as_buffer */
2740 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2741 0, /* tp_doc */
2742 (traverseproc)listiter_traverse, /* tp_traverse */
2743 0, /* tp_clear */
2744 0, /* tp_richcompare */
2745 0, /* tp_weaklistoffset */
2746 PyObject_SelfIter, /* tp_iter */
2747 (iternextfunc)listiter_next, /* tp_iternext */
2748 listiter_methods, /* tp_methods */
2749 0, /* tp_members */
2750};
2751
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002752
Guido van Rossum5086e492002-07-16 15:56:52 +00002753static PyObject *
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002754list_iter(PyObject *seq)
2755{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002756 listiterobject *it;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002757
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002758 if (!PyList_Check(seq)) {
2759 PyErr_BadInternalCall();
2760 return NULL;
2761 }
2762 it = PyObject_GC_New(listiterobject, &PyListIter_Type);
2763 if (it == NULL)
2764 return NULL;
2765 it->it_index = 0;
2766 Py_INCREF(seq);
2767 it->it_seq = (PyListObject *)seq;
2768 _PyObject_GC_TRACK(it);
2769 return (PyObject *)it;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002770}
2771
2772static void
2773listiter_dealloc(listiterobject *it)
2774{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002775 _PyObject_GC_UNTRACK(it);
Guido van Rossum86103ae2002-07-16 20:07:32 +00002776 Py_XDECREF(it->it_seq);
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002777 PyObject_GC_Del(it);
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002778}
2779
2780static int
2781listiter_traverse(listiterobject *it, visitproc visit, void *arg)
2782{
Thomas Woutersc6e55062006-04-15 21:47:09 +00002783 Py_VISIT(it->it_seq);
2784 return 0;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002785}
2786
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002787static PyObject *
Tim Peters93b2cc42002-06-01 05:22:55 +00002788listiter_next(listiterobject *it)
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002789{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002790 PyListObject *seq;
2791 PyObject *item;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002792
Tim Peters93b2cc42002-06-01 05:22:55 +00002793 assert(it != NULL);
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002794 seq = it->it_seq;
Guido van Rossum86103ae2002-07-16 20:07:32 +00002795 if (seq == NULL)
2796 return NULL;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002797 assert(PyList_Check(seq));
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002798
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002799 if (it->it_index < PyList_GET_SIZE(seq)) {
Tim Peters93b2cc42002-06-01 05:22:55 +00002800 item = PyList_GET_ITEM(seq, it->it_index);
2801 ++it->it_index;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002802 Py_INCREF(item);
2803 return item;
2804 }
Guido van Rossum86103ae2002-07-16 20:07:32 +00002805
2806 Py_DECREF(seq);
2807 it->it_seq = NULL;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002808 return NULL;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002809}
2810
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002811static PyObject *
Raymond Hettinger435bf582004-03-18 22:43:10 +00002812listiter_len(listiterobject *it)
2813{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002814 Py_ssize_t len;
Raymond Hettinger40a03822004-04-12 13:05:09 +00002815 if (it->it_seq) {
2816 len = PyList_GET_SIZE(it->it_seq) - it->it_index;
2817 if (len >= 0)
Martin v. Löwis18e16552006-02-15 17:27:45 +00002818 return PyInt_FromSsize_t(len);
Raymond Hettinger40a03822004-04-12 13:05:09 +00002819 }
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002820 return PyInt_FromLong(0);
Raymond Hettinger435bf582004-03-18 22:43:10 +00002821}
Anthony Baxter377be112006-04-11 06:54:30 +00002822/*********************** List Reverse Iterator **************************/
Raymond Hettinger435bf582004-03-18 22:43:10 +00002823
Anthony Baxter377be112006-04-11 06:54:30 +00002824typedef struct {
2825 PyObject_HEAD
2826 Py_ssize_t it_index;
2827 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
2828} listreviterobject;
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002829
Anthony Baxter377be112006-04-11 06:54:30 +00002830static PyObject *list_reversed(PyListObject *, PyObject *);
2831static void listreviter_dealloc(listreviterobject *);
2832static int listreviter_traverse(listreviterobject *, visitproc, void *);
2833static PyObject *listreviter_next(listreviterobject *);
2834static Py_ssize_t listreviter_len(listreviterobject *);
2835
2836static PySequenceMethods listreviter_as_sequence = {
2837 (lenfunc)listreviter_len, /* sq_length */
2838 0, /* sq_concat */
Raymond Hettinger435bf582004-03-18 22:43:10 +00002839};
2840
Anthony Baxter377be112006-04-11 06:54:30 +00002841PyTypeObject PyListRevIter_Type = {
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002842 PyObject_HEAD_INIT(&PyType_Type)
2843 0, /* ob_size */
Anthony Baxter377be112006-04-11 06:54:30 +00002844 "listreverseiterator", /* tp_name */
2845 sizeof(listreviterobject), /* tp_basicsize */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002846 0, /* tp_itemsize */
2847 /* methods */
Anthony Baxter377be112006-04-11 06:54:30 +00002848 (destructor)listreviter_dealloc, /* tp_dealloc */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002849 0, /* tp_print */
2850 0, /* tp_getattr */
2851 0, /* tp_setattr */
2852 0, /* tp_compare */
2853 0, /* tp_repr */
2854 0, /* tp_as_number */
Anthony Baxter377be112006-04-11 06:54:30 +00002855 &listreviter_as_sequence, /* tp_as_sequence */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002856 0, /* tp_as_mapping */
2857 0, /* tp_hash */
2858 0, /* tp_call */
2859 0, /* tp_str */
2860 PyObject_GenericGetAttr, /* tp_getattro */
2861 0, /* tp_setattro */
2862 0, /* tp_as_buffer */
2863 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2864 0, /* tp_doc */
Anthony Baxter377be112006-04-11 06:54:30 +00002865 (traverseproc)listreviter_traverse, /* tp_traverse */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002866 0, /* tp_clear */
2867 0, /* tp_richcompare */
2868 0, /* tp_weaklistoffset */
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +00002869 PyObject_SelfIter, /* tp_iter */
Anthony Baxter377be112006-04-11 06:54:30 +00002870 (iternextfunc)listreviter_next, /* tp_iternext */
2871 0,
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002872};
Raymond Hettinger1021c442003-11-07 15:38:09 +00002873
Raymond Hettinger1021c442003-11-07 15:38:09 +00002874static PyObject *
2875list_reversed(PyListObject *seq, PyObject *unused)
2876{
2877 listreviterobject *it;
2878
2879 it = PyObject_GC_New(listreviterobject, &PyListRevIter_Type);
2880 if (it == NULL)
2881 return NULL;
2882 assert(PyList_Check(seq));
2883 it->it_index = PyList_GET_SIZE(seq) - 1;
2884 Py_INCREF(seq);
2885 it->it_seq = seq;
2886 PyObject_GC_Track(it);
2887 return (PyObject *)it;
2888}
2889
2890static void
2891listreviter_dealloc(listreviterobject *it)
2892{
2893 PyObject_GC_UnTrack(it);
2894 Py_XDECREF(it->it_seq);
2895 PyObject_GC_Del(it);
2896}
2897
2898static int
2899listreviter_traverse(listreviterobject *it, visitproc visit, void *arg)
2900{
Thomas Woutersc6e55062006-04-15 21:47:09 +00002901 Py_VISIT(it->it_seq);
2902 return 0;
Raymond Hettinger1021c442003-11-07 15:38:09 +00002903}
2904
2905static PyObject *
2906listreviter_next(listreviterobject *it)
2907{
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002908 PyObject *item;
Martin v. Löwiseb079f12006-02-16 14:32:27 +00002909 Py_ssize_t index = it->it_index;
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002910 PyListObject *seq = it->it_seq;
Raymond Hettinger1021c442003-11-07 15:38:09 +00002911
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002912 if (index>=0 && index < PyList_GET_SIZE(seq)) {
2913 item = PyList_GET_ITEM(seq, index);
Raymond Hettinger1021c442003-11-07 15:38:09 +00002914 it->it_index--;
2915 Py_INCREF(item);
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002916 return item;
Raymond Hettinger1021c442003-11-07 15:38:09 +00002917 }
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002918 it->it_index = -1;
2919 if (seq != NULL) {
2920 it->it_seq = NULL;
2921 Py_DECREF(seq);
2922 }
2923 return NULL;
Raymond Hettinger1021c442003-11-07 15:38:09 +00002924}
2925
Martin v. Löwis18e16552006-02-15 17:27:45 +00002926static Py_ssize_t
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002927listreviter_len(listreviterobject *it)
2928{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002929 Py_ssize_t len = it->it_index + 1;
Raymond Hettinger40a03822004-04-12 13:05:09 +00002930 if (it->it_seq == NULL || PyList_GET_SIZE(it->it_seq) < len)
2931 return 0;
2932 return len;
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002933}