blob: c2892c67ee6d15c632fd65b8291e55c644fb35f3 [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* List object implementation */
3
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004#include "Python.h"
5
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00006#ifdef STDC_HEADERS
7#include <stddef.h>
8#else
9#include <sys/types.h> /* For size_t */
10#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000011
Guido van Rossuma46d51d1995-01-26 22:59:43 +000012static int
Fred Drakea2f55112000-07-09 15:16:51 +000013roundupsize(int n)
Guido van Rossuma46d51d1995-01-26 22:59:43 +000014{
Tim Peters65b8b842001-05-26 05:28:40 +000015 unsigned int nbits = 0;
16 unsigned int n2 = (unsigned int)n >> 5;
17
18 /* Round up:
19 * If n < 256, to a multiple of 8.
20 * If n < 2048, to a multiple of 64.
21 * If n < 16384, to a multiple of 512.
22 * If n < 131072, to a multiple of 4096.
23 * If n < 1048576, to a multiple of 32768.
24 * If n < 8388608, to a multiple of 262144.
25 * If n < 67108864, to a multiple of 2097152.
26 * If n < 536870912, to a multiple of 16777216.
27 * ...
28 * If n < 2**(5+3*i), to a multiple of 2**(3*i).
29 *
30 * This over-allocates proportional to the list size, making room
31 * for additional growth. The over-allocation is mild, but is
32 * enough to give linear-time amortized behavior over a long
33 * sequence of appends() in the presence of a poorly-performing
34 * system realloc() (which is a reality, e.g., across all flavors
35 * of Windows, with Win9x behavior being particularly bad -- and
36 * we've still got address space fragmentation problems on Win9x
37 * even with this scheme, although it requires much longer lists to
38 * provoke them than it used to).
39 */
40 do {
41 n2 >>= 3;
42 nbits += 3;
43 } while (n2);
44 return ((n >> nbits) + 1) << nbits;
45 }
Guido van Rossuma46d51d1995-01-26 22:59:43 +000046
Neal Norwitzd4e5be52002-05-22 23:19:17 +000047#define NRESIZE(var, type, nitems) \
48do { \
49 size_t _new_size = roundupsize(nitems); \
50 if (_new_size <= ((~(size_t)0) / sizeof(type))) \
51 PyMem_RESIZE(var, type, _new_size); \
52 else \
53 var = NULL; \
54} while (0)
Guido van Rossuma46d51d1995-01-26 22:59:43 +000055
Guido van Rossumc0b618a1997-05-02 03:12:38 +000056PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +000057PyList_New(int size)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000058{
59 int i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +000060 PyListObject *op;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +000061 size_t nbytes;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000062 if (size < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +000063 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000064 return NULL;
65 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +000066 nbytes = size * sizeof(PyObject *);
Guido van Rossum1e28e5e1992-08-19 16:46:30 +000067 /* Check for overflow */
Guido van Rossumc0b618a1997-05-02 03:12:38 +000068 if (nbytes / sizeof(PyObject *) != (size_t)size) {
69 return PyErr_NoMemory();
Guido van Rossum1e28e5e1992-08-19 16:46:30 +000070 }
Neil Schemenauere83c00e2001-08-29 23:54:21 +000071 op = PyObject_GC_New(PyListObject, &PyList_Type);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000072 if (op == NULL) {
Neil Schemenauere83c00e2001-08-29 23:54:21 +000073 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000074 }
75 if (size <= 0) {
76 op->ob_item = NULL;
77 }
78 else {
Guido van Rossumb18618d2000-05-03 23:44:39 +000079 op->ob_item = (PyObject **) PyMem_MALLOC(nbytes);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000080 if (op->ob_item == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +000081 return PyErr_NoMemory();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000082 }
83 }
Neil Schemenauere83c00e2001-08-29 23:54:21 +000084 op->ob_size = size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000085 for (i = 0; i < size; i++)
86 op->ob_item[i] = NULL;
Neil Schemenauere83c00e2001-08-29 23:54:21 +000087 _PyObject_GC_TRACK(op);
Guido van Rossumc0b618a1997-05-02 03:12:38 +000088 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000089}
90
91int
Fred Drakea2f55112000-07-09 15:16:51 +000092PyList_Size(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000093{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000094 if (!PyList_Check(op)) {
95 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000096 return -1;
97 }
98 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +000099 return ((PyListObject *)op) -> ob_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000100}
101
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000102static PyObject *indexerr;
Guido van Rossum929f1b81996-08-09 20:51:27 +0000103
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000104PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000105PyList_GetItem(PyObject *op, int i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000106{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000107 if (!PyList_Check(op)) {
108 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000109 return NULL;
110 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000111 if (i < 0 || i >= ((PyListObject *)op) -> ob_size) {
Guido van Rossum929f1b81996-08-09 20:51:27 +0000112 if (indexerr == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000113 indexerr = PyString_FromString(
114 "list index out of range");
115 PyErr_SetObject(PyExc_IndexError, indexerr);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000116 return NULL;
117 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000118 return ((PyListObject *)op) -> ob_item[i];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000119}
120
121int
Fred Drakea2f55112000-07-09 15:16:51 +0000122PyList_SetItem(register PyObject *op, register int i,
123 register PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000124{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000125 register PyObject *olditem;
126 register PyObject **p;
127 if (!PyList_Check(op)) {
128 Py_XDECREF(newitem);
129 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000130 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000131 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000132 if (i < 0 || i >= ((PyListObject *)op) -> ob_size) {
133 Py_XDECREF(newitem);
134 PyErr_SetString(PyExc_IndexError,
135 "list assignment index out of range");
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000136 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000137 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000138 p = ((PyListObject *)op) -> ob_item + i;
Guido van Rossum5fe60581995-03-09 12:12:50 +0000139 olditem = *p;
140 *p = newitem;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000141 Py_XDECREF(olditem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000142 return 0;
143}
144
145static int
Fred Drakea2f55112000-07-09 15:16:51 +0000146ins1(PyListObject *self, int where, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000147{
148 int i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000149 PyObject **items;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000150 if (v == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000151 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000152 return -1;
153 }
Trent Micka5846642000-08-13 22:47:45 +0000154 if (self->ob_size == INT_MAX) {
155 PyErr_SetString(PyExc_OverflowError,
156 "cannot add more objects to list");
157 return -1;
158 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000159 items = self->ob_item;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000160 NRESIZE(items, PyObject *, self->ob_size+1);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000161 if (items == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000162 PyErr_NoMemory();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000163 return -1;
164 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000165 if (where < 0)
166 where = 0;
167 if (where > self->ob_size)
168 where = self->ob_size;
169 for (i = self->ob_size; --i >= where; )
170 items[i+1] = items[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000171 Py_INCREF(v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000172 items[where] = v;
173 self->ob_item = items;
174 self->ob_size++;
175 return 0;
176}
177
178int
Fred Drakea2f55112000-07-09 15:16:51 +0000179PyList_Insert(PyObject *op, int where, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000180{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000181 if (!PyList_Check(op)) {
182 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000183 return -1;
184 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000185 return ins1((PyListObject *)op, where, newitem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000186}
187
188int
Fred Drakea2f55112000-07-09 15:16:51 +0000189PyList_Append(PyObject *op, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000190{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000191 if (!PyList_Check(op)) {
192 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000193 return -1;
194 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000195 return ins1((PyListObject *)op,
196 (int) ((PyListObject *)op)->ob_size, newitem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000197}
198
199/* Methods */
200
201static void
Fred Drakea2f55112000-07-09 15:16:51 +0000202list_dealloc(PyListObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000203{
204 int i;
Guido van Rossumff413af2002-03-28 20:34:59 +0000205 PyObject_GC_UnTrack(op);
Guido van Rossumd724b232000-03-13 16:01:29 +0000206 Py_TRASHCAN_SAFE_BEGIN(op)
Jack Jansen7874d1f1995-01-19 12:09:27 +0000207 if (op->ob_item != NULL) {
Guido van Rossumfa717011999-06-09 15:19:34 +0000208 /* Do it backwards, for Christian Tismer.
209 There's a simple test case where somehow this reduces
210 thrashing when a *very* large list is created and
211 immediately deleted. */
212 i = op->ob_size;
213 while (--i >= 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000214 Py_XDECREF(op->ob_item[i]);
Jack Jansen7874d1f1995-01-19 12:09:27 +0000215 }
Guido van Rossumb18618d2000-05-03 23:44:39 +0000216 PyMem_FREE(op->ob_item);
Jack Jansen7874d1f1995-01-19 12:09:27 +0000217 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000218 op->ob_type->tp_free((PyObject *)op);
Guido van Rossumd724b232000-03-13 16:01:29 +0000219 Py_TRASHCAN_SAFE_END(op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000220}
221
Guido van Rossum90933611991-06-07 16:10:43 +0000222static int
Fred Drakea2f55112000-07-09 15:16:51 +0000223list_print(PyListObject *op, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000224{
225 int i;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000226
227 i = Py_ReprEnter((PyObject*)op);
228 if (i != 0) {
229 if (i < 0)
230 return i;
231 fprintf(fp, "[...]");
232 return 0;
233 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000234 fprintf(fp, "[");
Guido van Rossum90933611991-06-07 16:10:43 +0000235 for (i = 0; i < op->ob_size; i++) {
236 if (i > 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000237 fprintf(fp, ", ");
Guido van Rossumfb376de1998-04-10 22:47:27 +0000238 if (PyObject_Print(op->ob_item[i], fp, 0) != 0) {
239 Py_ReprLeave((PyObject *)op);
Guido van Rossum90933611991-06-07 16:10:43 +0000240 return -1;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000241 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000242 }
243 fprintf(fp, "]");
Guido van Rossumfb376de1998-04-10 22:47:27 +0000244 Py_ReprLeave((PyObject *)op);
Guido van Rossum90933611991-06-07 16:10:43 +0000245 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000246}
247
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000248static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000249list_repr(PyListObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000250{
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000251 int i;
Tim Petersa7259592001-06-16 05:11:17 +0000252 PyObject *s, *temp;
253 PyObject *pieces = NULL, *result = NULL;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000254
255 i = Py_ReprEnter((PyObject*)v);
256 if (i != 0) {
Tim Petersa7259592001-06-16 05:11:17 +0000257 return i > 0 ? PyString_FromString("[...]") : NULL;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000258 }
Tim Petersa7259592001-06-16 05:11:17 +0000259
260 if (v->ob_size == 0) {
261 result = PyString_FromString("[]");
262 goto Done;
263 }
264
265 pieces = PyList_New(0);
266 if (pieces == NULL)
267 goto Done;
268
269 /* Do repr() on each element. Note that this may mutate the list,
270 so must refetch the list size on each iteration. */
271 for (i = 0; i < v->ob_size; ++i) {
272 int status;
273 s = PyObject_Repr(v->ob_item[i]);
274 if (s == NULL)
275 goto Done;
276 status = PyList_Append(pieces, s);
277 Py_DECREF(s); /* append created a new ref */
278 if (status < 0)
279 goto Done;
280 }
281
282 /* Add "[]" decorations to the first and last items. */
283 assert(PyList_GET_SIZE(pieces) > 0);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000284 s = PyString_FromString("[");
Tim Petersa7259592001-06-16 05:11:17 +0000285 if (s == NULL)
286 goto Done;
287 temp = PyList_GET_ITEM(pieces, 0);
288 PyString_ConcatAndDel(&s, temp);
289 PyList_SET_ITEM(pieces, 0, s);
290 if (s == NULL)
291 goto Done;
292
293 s = PyString_FromString("]");
294 if (s == NULL)
295 goto Done;
296 temp = PyList_GET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1);
297 PyString_ConcatAndDel(&temp, s);
298 PyList_SET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1, temp);
299 if (temp == NULL)
300 goto Done;
301
302 /* Paste them all together with ", " between. */
303 s = PyString_FromString(", ");
304 if (s == NULL)
305 goto Done;
306 result = _PyString_Join(s, pieces);
307 Py_DECREF(s);
308
309Done:
310 Py_XDECREF(pieces);
Guido van Rossumfb376de1998-04-10 22:47:27 +0000311 Py_ReprLeave((PyObject *)v);
Tim Petersa7259592001-06-16 05:11:17 +0000312 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000313}
314
315static int
Fred Drakea2f55112000-07-09 15:16:51 +0000316list_length(PyListObject *a)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000317{
318 return a->ob_size;
319}
320
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000321
322
323static int
Fred Drakea2f55112000-07-09 15:16:51 +0000324list_contains(PyListObject *a, PyObject *el)
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000325{
Guido van Rossum65e1cea2001-01-17 22:11:59 +0000326 int i;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000327
328 for (i = 0; i < a->ob_size; ++i) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +0000329 int cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i),
330 Py_EQ);
331 if (cmp > 0)
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000332 return 1;
Guido van Rossum65e1cea2001-01-17 22:11:59 +0000333 else if (cmp < 0)
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000334 return -1;
335 }
336 return 0;
337}
338
339
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000340static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000341list_item(PyListObject *a, int i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000342{
343 if (i < 0 || i >= a->ob_size) {
Guido van Rossum929f1b81996-08-09 20:51:27 +0000344 if (indexerr == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000345 indexerr = PyString_FromString(
346 "list index out of range");
347 PyErr_SetObject(PyExc_IndexError, indexerr);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000348 return NULL;
349 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000350 Py_INCREF(a->ob_item[i]);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000351 return a->ob_item[i];
352}
353
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000354static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000355list_slice(PyListObject *a, int ilow, int ihigh)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000356{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000357 PyListObject *np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000358 int i;
359 if (ilow < 0)
360 ilow = 0;
361 else if (ilow > a->ob_size)
362 ilow = a->ob_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000363 if (ihigh < ilow)
364 ihigh = ilow;
365 else if (ihigh > a->ob_size)
366 ihigh = a->ob_size;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000367 np = (PyListObject *) PyList_New(ihigh - ilow);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000368 if (np == NULL)
369 return NULL;
370 for (i = ilow; i < ihigh; i++) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000371 PyObject *v = a->ob_item[i];
372 Py_INCREF(v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000373 np->ob_item[i - ilow] = v;
374 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000375 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000376}
377
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000378PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000379PyList_GetSlice(PyObject *a, int ilow, int ihigh)
Guido van Rossum234f9421993-06-17 12:35:49 +0000380{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000381 if (!PyList_Check(a)) {
382 PyErr_BadInternalCall();
Guido van Rossum234f9421993-06-17 12:35:49 +0000383 return NULL;
384 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000385 return list_slice((PyListObject *)a, ilow, ihigh);
Guido van Rossum234f9421993-06-17 12:35:49 +0000386}
387
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000388static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000389list_concat(PyListObject *a, PyObject *bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000390{
391 int size;
392 int i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000393 PyListObject *np;
394 if (!PyList_Check(bb)) {
Fred Drakeb6a9ada2000-06-01 03:12:13 +0000395 PyErr_Format(PyExc_TypeError,
Fred Drake914a2ed2000-06-01 14:31:03 +0000396 "can only concatenate list (not \"%.200s\") to list",
397 bb->ob_type->tp_name);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000398 return NULL;
399 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000400#define b ((PyListObject *)bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000401 size = a->ob_size + b->ob_size;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000402 np = (PyListObject *) PyList_New(size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000403 if (np == NULL) {
Guido van Rossum90933611991-06-07 16:10:43 +0000404 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000405 }
406 for (i = 0; i < a->ob_size; i++) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000407 PyObject *v = a->ob_item[i];
408 Py_INCREF(v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000409 np->ob_item[i] = v;
410 }
411 for (i = 0; i < b->ob_size; i++) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000412 PyObject *v = b->ob_item[i];
413 Py_INCREF(v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000414 np->ob_item[i + a->ob_size] = v;
415 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000416 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000417#undef b
418}
419
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000420static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000421list_repeat(PyListObject *a, int n)
Guido van Rossumed98d481991-03-06 13:07:53 +0000422{
423 int i, j;
424 int size;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000425 PyListObject *np;
426 PyObject **p;
Guido van Rossumed98d481991-03-06 13:07:53 +0000427 if (n < 0)
428 n = 0;
429 size = a->ob_size * n;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000430 np = (PyListObject *) PyList_New(size);
Guido van Rossumed98d481991-03-06 13:07:53 +0000431 if (np == NULL)
432 return NULL;
433 p = np->ob_item;
434 for (i = 0; i < n; i++) {
435 for (j = 0; j < a->ob_size; j++) {
436 *p = a->ob_item[j];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000437 Py_INCREF(*p);
Guido van Rossumed98d481991-03-06 13:07:53 +0000438 p++;
439 }
440 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000441 return (PyObject *) np;
Guido van Rossumed98d481991-03-06 13:07:53 +0000442}
443
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000444static int
Fred Drakea2f55112000-07-09 15:16:51 +0000445list_ass_slice(PyListObject *a, int ilow, int ihigh, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000446{
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000447 /* Because [X]DECREF can recursively invoke list operations on
448 this list, we must postpone all [X]DECREF activity until
449 after the list is back in its canonical shape. Therefore
450 we must allocate an additional array, 'recycle', into which
451 we temporarily copy the items that are deleted from the
452 list. :-( */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000453 PyObject **recycle, **p;
454 PyObject **item;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000455 int n; /* Size of replacement list */
456 int d; /* Change in size */
457 int k; /* Loop index */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000458#define b ((PyListObject *)v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000459 if (v == NULL)
460 n = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000461 else if (PyList_Check(v)) {
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000462 n = b->ob_size;
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000463 if (a == b) {
464 /* Special case "a[i:j] = a" -- copy b first */
465 int ret;
466 v = list_slice(b, 0, n);
467 ret = list_ass_slice(a, ilow, ihigh, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000468 Py_DECREF(v);
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000469 return ret;
470 }
471 }
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000472 else {
Fred Drakeb6a9ada2000-06-01 03:12:13 +0000473 PyErr_Format(PyExc_TypeError,
474 "must assign list (not \"%.200s\") to slice",
475 v->ob_type->tp_name);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000476 return -1;
477 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000478 if (ilow < 0)
479 ilow = 0;
480 else if (ilow > a->ob_size)
481 ilow = a->ob_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000482 if (ihigh < ilow)
483 ihigh = ilow;
484 else if (ihigh > a->ob_size)
485 ihigh = a->ob_size;
486 item = a->ob_item;
487 d = n - (ihigh-ilow);
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000488 if (ihigh > ilow)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000489 p = recycle = PyMem_NEW(PyObject *, (ihigh-ilow));
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000490 else
491 p = recycle = NULL;
492 if (d <= 0) { /* Delete -d items; recycle ihigh-ilow items */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000493 for (k = ilow; k < ihigh; k++)
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000494 *p++ = item[k];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000495 if (d < 0) {
496 for (/*k = ihigh*/; k < a->ob_size; k++)
497 item[k+d] = item[k];
498 a->ob_size += d;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000499 NRESIZE(item, PyObject *, a->ob_size); /* Can't fail */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000500 a->ob_item = item;
501 }
502 }
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000503 else { /* Insert d items; recycle ihigh-ilow items */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000504 NRESIZE(item, PyObject *, a->ob_size + d);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000505 if (item == NULL) {
Guido van Rossumb18618d2000-05-03 23:44:39 +0000506 if (recycle != NULL)
507 PyMem_DEL(recycle);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000508 PyErr_NoMemory();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000509 return -1;
510 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000511 for (k = a->ob_size; --k >= ihigh; )
512 item[k+d] = item[k];
513 for (/*k = ihigh-1*/; k >= ilow; --k)
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000514 *p++ = item[k];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000515 a->ob_item = item;
516 a->ob_size += d;
517 }
518 for (k = 0; k < n; k++, ilow++) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000519 PyObject *w = b->ob_item[k];
520 Py_XINCREF(w);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000521 item[ilow] = w;
522 }
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000523 if (recycle) {
524 while (--p >= recycle)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000525 Py_XDECREF(*p);
526 PyMem_DEL(recycle);
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000527 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000528 if (a->ob_size == 0 && a->ob_item != NULL) {
529 PyMem_FREE(a->ob_item);
530 a->ob_item = NULL;
531 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000532 return 0;
533#undef b
534}
535
Guido van Rossum234f9421993-06-17 12:35:49 +0000536int
Fred Drakea2f55112000-07-09 15:16:51 +0000537PyList_SetSlice(PyObject *a, int ilow, int ihigh, PyObject *v)
Guido van Rossum234f9421993-06-17 12:35:49 +0000538{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000539 if (!PyList_Check(a)) {
540 PyErr_BadInternalCall();
Guido van Rossum1fc238a1993-07-29 08:25:09 +0000541 return -1;
Guido van Rossum234f9421993-06-17 12:35:49 +0000542 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000543 return list_ass_slice((PyListObject *)a, ilow, ihigh, v);
Guido van Rossum234f9421993-06-17 12:35:49 +0000544}
545
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000546static PyObject *
547list_inplace_repeat(PyListObject *self, int n)
548{
549 PyObject **items;
550 int size, i, j;
551
552
553 size = PyList_GET_SIZE(self);
554 if (size == 0) {
555 Py_INCREF(self);
556 return (PyObject *)self;
557 }
558
559 items = self->ob_item;
560
561 if (n < 1) {
562 self->ob_item = NULL;
563 self->ob_size = 0;
564 for (i = 0; i < size; i++)
565 Py_XDECREF(items[i]);
566 PyMem_DEL(items);
567 Py_INCREF(self);
568 return (PyObject *)self;
569 }
570
571 NRESIZE(items, PyObject*, size*n);
572 if (items == NULL) {
573 PyErr_NoMemory();
574 goto finally;
575 }
576 self->ob_item = items;
577 for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */
578 for (j = 0; j < size; j++) {
579 PyObject *o = PyList_GET_ITEM(self, j);
580 Py_INCREF(o);
581 PyList_SET_ITEM(self, self->ob_size++, o);
582 }
583 }
584 Py_INCREF(self);
585 return (PyObject *)self;
586 finally:
587 return NULL;
588}
589
Guido van Rossum4a450d01991-04-03 19:05:18 +0000590static int
Fred Drakea2f55112000-07-09 15:16:51 +0000591list_ass_item(PyListObject *a, int i, PyObject *v)
Guido van Rossum4a450d01991-04-03 19:05:18 +0000592{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000593 PyObject *old_value;
Guido van Rossum4a450d01991-04-03 19:05:18 +0000594 if (i < 0 || i >= a->ob_size) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000595 PyErr_SetString(PyExc_IndexError,
596 "list assignment index out of range");
Guido van Rossum4a450d01991-04-03 19:05:18 +0000597 return -1;
598 }
599 if (v == NULL)
600 return list_ass_slice(a, i, i+1, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000601 Py_INCREF(v);
Guido van Rossumd7047b31995-01-02 19:07:15 +0000602 old_value = a->ob_item[i];
Guido van Rossum4a450d01991-04-03 19:05:18 +0000603 a->ob_item[i] = v;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000604 Py_DECREF(old_value);
Guido van Rossum4a450d01991-04-03 19:05:18 +0000605 return 0;
606}
607
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000608static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000609ins(PyListObject *self, int where, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000610{
611 if (ins1(self, where, v) != 0)
612 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000613 Py_INCREF(Py_None);
614 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000615}
616
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000617static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000618listinsert(PyListObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000619{
620 int i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000621 PyObject *v;
Guido van Rossumc00a9382000-02-24 21:48:29 +0000622 if (!PyArg_ParseTuple(args, "iO:insert", &i, &v))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000623 return NULL;
Guido van Rossumbf80e541993-02-08 15:49:17 +0000624 return ins(self, i, v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000625}
626
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000627static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000628listappend(PyListObject *self, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000629{
Guido van Rossumbf80e541993-02-08 15:49:17 +0000630 return ins(self, (int) self->ob_size, v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000631}
632
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000633static int
634listextend_internal(PyListObject *self, PyObject *b)
Barry Warsawdedf6d61998-10-09 16:37:25 +0000635{
Barry Warsawdedf6d61998-10-09 16:37:25 +0000636 PyObject **items;
637 int selflen = PyList_GET_SIZE(self);
638 int blen;
639 register int i;
640
Jeremy Hyltondb60bb52001-01-03 22:32:16 +0000641 if (PyObject_Size(b) == 0) {
Barry Warsawdedf6d61998-10-09 16:37:25 +0000642 /* short circuit when b is empty */
Jeremy Hyltondb60bb52001-01-03 22:32:16 +0000643 Py_DECREF(b);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000644 return 0;
Jeremy Hyltondb60bb52001-01-03 22:32:16 +0000645 }
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000646
Barry Warsawdedf6d61998-10-09 16:37:25 +0000647 if (self == (PyListObject*)b) {
648 /* as in list_ass_slice() we must special case the
649 * situation: a.extend(a)
650 *
651 * XXX: I think this way ought to be faster than using
652 * list_slice() the way list_ass_slice() does.
653 */
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000654 Py_DECREF(b);
Barry Warsawdedf6d61998-10-09 16:37:25 +0000655 b = PyList_New(selflen);
656 if (!b)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000657 return -1;
Barry Warsawdedf6d61998-10-09 16:37:25 +0000658 for (i = 0; i < selflen; i++) {
659 PyObject *o = PyList_GET_ITEM(self, i);
660 Py_INCREF(o);
661 PyList_SET_ITEM(b, i, o);
662 }
663 }
Barry Warsawdedf6d61998-10-09 16:37:25 +0000664
Jeremy Hylton03657cf2000-07-12 13:05:33 +0000665 blen = PyObject_Size(b);
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000666
Barry Warsawdedf6d61998-10-09 16:37:25 +0000667 /* resize a using idiom */
668 items = self->ob_item;
669 NRESIZE(items, PyObject*, selflen + blen);
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000670 if (items == NULL) {
Barry Warsawdedf6d61998-10-09 16:37:25 +0000671 PyErr_NoMemory();
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000672 Py_DECREF(b);
673 return -1;
Barry Warsawdedf6d61998-10-09 16:37:25 +0000674 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000675
Barry Warsawdedf6d61998-10-09 16:37:25 +0000676 self->ob_item = items;
677
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000678 /* populate the end of self with b's items */
Barry Warsawdedf6d61998-10-09 16:37:25 +0000679 for (i = 0; i < blen; i++) {
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000680 PyObject *o = PySequence_Fast_GET_ITEM(b, i);
Barry Warsawdedf6d61998-10-09 16:37:25 +0000681 Py_INCREF(o);
682 PyList_SET_ITEM(self, self->ob_size++, o);
683 }
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000684 Py_DECREF(b);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000685 return 0;
Barry Warsawdedf6d61998-10-09 16:37:25 +0000686}
687
688
689static PyObject *
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000690list_inplace_concat(PyListObject *self, PyObject *other)
691{
Tim Peters1af03e92001-05-26 19:37:54 +0000692 other = PySequence_Fast(other, "argument to += must be iterable");
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000693 if (!other)
694 return NULL;
695
696 if (listextend_internal(self, other) < 0)
697 return NULL;
698
699 Py_INCREF(self);
700 return (PyObject *)self;
701}
702
703static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000704listextend(PyListObject *self, PyObject *b)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000705{
706
Tim Peters1af03e92001-05-26 19:37:54 +0000707 b = PySequence_Fast(b, "list.extend() argument must be iterable");
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000708 if (!b)
709 return NULL;
710
711 if (listextend_internal(self, b) < 0)
712 return NULL;
713
714 Py_INCREF(Py_None);
715 return Py_None;
716}
717
718static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000719listpop(PyListObject *self, PyObject *args)
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000720{
721 int i = -1;
722 PyObject *v;
Guido van Rossumc00a9382000-02-24 21:48:29 +0000723 if (!PyArg_ParseTuple(args, "|i:pop", &i))
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000724 return NULL;
725 if (self->ob_size == 0) {
726 /* Special-case most common failure cause */
727 PyErr_SetString(PyExc_IndexError, "pop from empty list");
728 return NULL;
729 }
730 if (i < 0)
731 i += self->ob_size;
732 if (i < 0 || i >= self->ob_size) {
733 PyErr_SetString(PyExc_IndexError, "pop index out of range");
734 return NULL;
735 }
736 v = self->ob_item[i];
737 Py_INCREF(v);
738 if (list_ass_slice(self, i, i+1, (PyObject *)NULL) != 0) {
739 Py_DECREF(v);
740 return NULL;
741 }
742 return v;
743}
744
Guido van Rossum3f236de1996-12-10 23:55:39 +0000745/* New quicksort implementation for arrays of object pointers.
746 Thanks to discussions with Tim Peters. */
747
748/* CMPERROR is returned by our comparison function when an error
749 occurred. This is the largest negative integer (0x80000000 on a
750 32-bit system). */
Guido van Rossum19700b61997-03-05 00:45:43 +0000751#define CMPERROR ( (int) ((unsigned int)1 << (8*sizeof(int) - 1)) )
Guido van Rossum3f236de1996-12-10 23:55:39 +0000752
753/* Comparison function. Takes care of calling a user-supplied
754 comparison function (any callable Python object). Calls the
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000755 standard comparison function, PyObject_Compare(), if the user-
756 supplied function is NULL. */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000757
758static int
Fred Drakea2f55112000-07-09 15:16:51 +0000759docompare(PyObject *x, PyObject *y, PyObject *compare)
Guido van Rossum3f236de1996-12-10 23:55:39 +0000760{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000761 PyObject *args, *res;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000762 int i;
763
Guido van Rossumc8b6df91997-05-23 00:06:51 +0000764 if (compare == NULL) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +0000765 /* NOTE: we rely on the fact here that the sorting algorithm
766 only ever checks whether k<0, i.e., whether x<y. So we
767 invoke the rich comparison function with Py_LT ('<'), and
768 return -1 when it returns true and 0 when it returns
769 false. */
770 i = PyObject_RichCompareBool(x, y, Py_LT);
771 if (i < 0)
772 return CMPERROR;
773 else
774 return -i;
Guido van Rossumc8b6df91997-05-23 00:06:51 +0000775 }
Guido van Rossum3f236de1996-12-10 23:55:39 +0000776
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000777 args = Py_BuildValue("(OO)", x, y);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000778 if (args == NULL)
779 return CMPERROR;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000780 res = PyEval_CallObject(compare, args);
781 Py_DECREF(args);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000782 if (res == NULL)
783 return CMPERROR;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000784 if (!PyInt_Check(res)) {
785 Py_DECREF(res);
786 PyErr_SetString(PyExc_TypeError,
Guido van Rossum9bcd1d71999-04-19 17:44:39 +0000787 "comparison function must return int");
Guido van Rossum3f236de1996-12-10 23:55:39 +0000788 return CMPERROR;
789 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000790 i = PyInt_AsLong(res);
791 Py_DECREF(res);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000792 if (i < 0)
793 return -1;
794 if (i > 0)
795 return 1;
796 return 0;
797}
798
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000799/* MINSIZE is the smallest array that will get a full-blown samplesort
800 treatment; smaller arrays are sorted using binary insertion. It must
801 be at least 7 for the samplesort implementation to work. Binary
802 insertion does fewer compares, but can suffer O(N**2) data movement.
803 The more expensive compares, the larger MINSIZE should be. */
804#define MINSIZE 100
805
806/* MINPARTITIONSIZE is the smallest array slice samplesort will bother to
807 partition; smaller slices are passed to binarysort. It must be at
808 least 2, and no larger than MINSIZE. Setting it higher reduces the #
809 of compares slowly, but increases the amount of data movement quickly.
810 The value here was chosen assuming a compare costs ~25x more than
811 swapping a pair of memory-resident pointers -- but under that assumption,
812 changing the value by a few dozen more or less has aggregate effect
813 under 1%. So the value is crucial, but not touchy <wink>. */
814#define MINPARTITIONSIZE 40
815
816/* MAXMERGE is the largest number of elements we'll always merge into
817 a known-to-be sorted chunk via binary insertion, regardless of the
818 size of that chunk. Given a chunk of N sorted elements, and a group
819 of K unknowns, the largest K for which it's better to do insertion
820 (than a full-blown sort) is a complicated function of N and K mostly
821 involving the expected number of compares and data moves under each
822 approach, and the relative cost of those operations on a specific
823 architecure. The fixed value here is conservative, and should be a
824 clear win regardless of architecture or N. */
825#define MAXMERGE 15
Guido van Rossum3f236de1996-12-10 23:55:39 +0000826
Guido van Rossum3f236de1996-12-10 23:55:39 +0000827/* STACKSIZE is the size of our work stack. A rough estimate is that
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000828 this allows us to sort arrays of size N where
829 N / ln(N) = MINPARTITIONSIZE * 2**STACKSIZE, so 60 is more than enough
830 for arrays of size 2**64. Because we push the biggest partition
831 first, the worst case occurs when all subarrays are always partitioned
832 exactly in two. */
833#define STACKSIZE 60
Guido van Rossum3f236de1996-12-10 23:55:39 +0000834
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000835
836#define SETK(X,Y) if ((k = docompare(X,Y,compare))==CMPERROR) goto fail
837
838/* binarysort is the best method for sorting small arrays: it does
839 few compares, but can do data movement quadratic in the number of
840 elements.
Guido van Rossum42812581998-06-17 14:15:44 +0000841 [lo, hi) is a contiguous slice of a list, and is sorted via
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000842 binary insertion.
843 On entry, must have lo <= start <= hi, and that [lo, start) is already
844 sorted (pass start == lo if you don't know!).
845 If docompare complains (returns CMPERROR) return -1, else 0.
846 Even in case of error, the output slice will be some permutation of
847 the input (nothing is lost or duplicated).
848*/
Guido van Rossum3f236de1996-12-10 23:55:39 +0000849
850static int
Fred Drakea2f55112000-07-09 15:16:51 +0000851binarysort(PyObject **lo, PyObject **hi, PyObject **start, PyObject *compare)
852 /* compare -- comparison function object, or NULL for default */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000853{
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000854 /* assert lo <= start <= hi
855 assert [lo, start) is sorted */
856 register int k;
857 register PyObject **l, **p, **r;
858 register PyObject *pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000859
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000860 if (lo == start)
861 ++start;
862 for (; start < hi; ++start) {
863 /* set l to where *start belongs */
864 l = lo;
865 r = start;
Guido van Rossuma119c0d1998-05-29 17:56:32 +0000866 pivot = *r;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000867 do {
868 p = l + ((r - l) >> 1);
869 SETK(pivot, *p);
870 if (k < 0)
871 r = p;
872 else
873 l = p + 1;
874 } while (l < r);
875 /* Pivot should go at l -- slide over to make room.
876 Caution: using memmove is much slower under MSVC 5;
877 we're not usually moving many slots. */
878 for (p = start; p > l; --p)
879 *p = *(p-1);
880 *l = pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000881 }
Guido van Rossum3f236de1996-12-10 23:55:39 +0000882 return 0;
Guido van Rossuma119c0d1998-05-29 17:56:32 +0000883
884 fail:
885 return -1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000886}
887
888/* samplesortslice is the sorting workhorse.
Guido van Rossum42812581998-06-17 14:15:44 +0000889 [lo, hi) is a contiguous slice of a list, to be sorted in place.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000890 On entry, must have lo <= hi,
891 If docompare complains (returns CMPERROR) return -1, else 0.
892 Even in case of error, the output slice will be some permutation of
893 the input (nothing is lost or duplicated).
894
895 samplesort is basically quicksort on steroids: a power of 2 close
896 to n/ln(n) is computed, and that many elements (less 1) are picked at
897 random from the array and sorted. These 2**k - 1 elements are then
898 used as preselected pivots for an equal number of quicksort
899 partitioning steps, partitioning the slice into 2**k chunks each of
900 size about ln(n). These small final chunks are then usually handled
901 by binarysort. Note that when k=1, this is roughly the same as an
902 ordinary quicksort using a random pivot, and when k=2 this is roughly
903 a median-of-3 quicksort. From that view, using k ~= lg(n/ln(n)) makes
904 this a "median of n/ln(n)" quicksort. You can also view it as a kind
905 of bucket sort, where 2**k-1 bucket boundaries are picked dynamically.
906
907 The large number of samples makes a quadratic-time case almost
908 impossible, and asymptotically drives the average-case number of
909 compares from quicksort's 2 N ln N (or 12/7 N ln N for the median-of-
910 3 variant) down to N lg N.
911
912 We also play lots of low-level tricks to cut the number of compares.
913
914 Very obscure: To avoid using extra memory, the PPs are stored in the
915 array and shuffled around as partitioning proceeds. At the start of a
916 partitioning step, we'll have 2**m-1 (for some m) PPs in sorted order,
917 adjacent (either on the left or the right!) to a chunk of X elements
918 that are to be partitioned: P X or X P. In either case we need to
919 shuffle things *in place* so that the 2**(m-1) smaller PPs are on the
920 left, followed by the PP to be used for this step (that's the middle
921 of the PPs), followed by X, followed by the 2**(m-1) larger PPs:
922 P X or X P -> Psmall pivot X Plarge
923 and the order of the PPs must not be altered. It can take a while
924 to realize this isn't trivial! It can take even longer <wink> to
925 understand why the simple code below works, using only 2**(m-1) swaps.
926 The key is that the order of the X elements isn't necessarily
927 preserved: X can end up as some cyclic permutation of its original
928 order. That's OK, because X is unsorted anyway. If the order of X
929 had to be preserved too, the simplest method I know of using O(1)
930 scratch storage requires len(X) + 2**(m-1) swaps, spread over 2 passes.
931 Since len(X) is typically several times larger than 2**(m-1), that
932 would slow things down.
933*/
934
935struct SamplesortStackNode {
936 /* Represents a slice of the array, from (& including) lo up
937 to (but excluding) hi. "extra" additional & adjacent elements
938 are pre-selected pivots (PPs), spanning [lo-extra, lo) if
939 extra > 0, or [hi, hi-extra) if extra < 0. The PPs are
940 already sorted, but nothing is known about the other elements
941 in [lo, hi). |extra| is always one less than a power of 2.
942 When extra is 0, we're out of PPs, and the slice must be
943 sorted by some other means. */
944 PyObject **lo;
945 PyObject **hi;
946 int extra;
947};
948
949/* The number of PPs we want is 2**k - 1, where 2**k is as close to
Guido van Rossum42812581998-06-17 14:15:44 +0000950 N / ln(N) as possible. So k ~= lg(N / ln(N)). Calling libm routines
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000951 is undesirable, so cutoff values are canned in the "cutoff" table
952 below: cutoff[i] is the smallest N such that k == CUTOFFBASE + i. */
953#define CUTOFFBASE 4
Guido van Rossum3aa23fd1999-01-14 19:01:53 +0000954static long cutoff[] = {
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000955 43, /* smallest N such that k == 4 */
956 106, /* etc */
957 250,
958 576,
959 1298,
960 2885,
961 6339,
962 13805,
963 29843,
964 64116,
965 137030,
966 291554,
967 617916,
968 1305130,
969 2748295,
970 5771662,
971 12091672,
972 25276798,
973 52734615,
974 109820537,
975 228324027,
976 473977813,
977 982548444, /* smallest N such that k == 26 */
978 2034159050 /* largest N that fits in signed 32-bit; k == 27 */
979};
980
981static int
Fred Drakea2f55112000-07-09 15:16:51 +0000982samplesortslice(PyObject **lo, PyObject **hi, PyObject *compare)
983 /* compare -- comparison function object, or NULL for default */
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000984{
985 register PyObject **l, **r;
986 register PyObject *tmp, *pivot;
987 register int k;
988 int n, extra, top, extraOnRight;
989 struct SamplesortStackNode stack[STACKSIZE];
990
991 /* assert lo <= hi */
992 n = hi - lo;
993
994 /* ----------------------------------------------------------
995 * Special cases
996 * --------------------------------------------------------*/
997 if (n < 2)
998 return 0;
999
1000 /* Set r to the largest value such that [lo,r) is sorted.
1001 This catches the already-sorted case, the all-the-same
1002 case, and the appended-a-few-elements-to-a-sorted-list case.
1003 If the array is unsorted, we're very likely to get out of
1004 the loop fast, so the test is cheap if it doesn't pay off.
1005 */
1006 /* assert lo < hi */
1007 for (r = lo+1; r < hi; ++r) {
1008 SETK(*r, *(r-1));
1009 if (k < 0)
1010 break;
1011 }
1012 /* [lo,r) is sorted, [r,hi) unknown. Get out cheap if there are
1013 few unknowns, or few elements in total. */
1014 if (hi - r <= MAXMERGE || n < MINSIZE)
Guido van Rossum42812581998-06-17 14:15:44 +00001015 return binarysort(lo, hi, r, compare);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001016
1017 /* Check for the array already being reverse-sorted. Typical
1018 benchmark-driven silliness <wink>. */
1019 /* assert lo < hi */
1020 for (r = lo+1; r < hi; ++r) {
1021 SETK(*(r-1), *r);
1022 if (k < 0)
1023 break;
1024 }
1025 if (hi - r <= MAXMERGE) {
1026 /* Reverse the reversed prefix, then insert the tail */
1027 PyObject **originalr = r;
1028 l = lo;
1029 do {
1030 --r;
1031 tmp = *l; *l = *r; *r = tmp;
1032 ++l;
1033 } while (l < r);
Guido van Rossum42812581998-06-17 14:15:44 +00001034 return binarysort(lo, hi, originalr, compare);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001035 }
1036
1037 /* ----------------------------------------------------------
1038 * Normal case setup: a large array without obvious pattern.
1039 * --------------------------------------------------------*/
1040
1041 /* extra := a power of 2 ~= n/ln(n), less 1.
1042 First find the smallest extra s.t. n < cutoff[extra] */
1043 for (extra = 0;
1044 extra < sizeof(cutoff) / sizeof(cutoff[0]);
1045 ++extra) {
1046 if (n < cutoff[extra])
1047 break;
1048 /* note that if we fall out of the loop, the value of
1049 extra still makes *sense*, but may be smaller than
1050 we would like (but the array has more than ~= 2**31
1051 elements in this case!) */
1052 }
1053 /* Now k == extra - 1 + CUTOFFBASE. The smallest value k can
1054 have is CUTOFFBASE-1, so
1055 assert MINSIZE >= 2**(CUTOFFBASE-1) - 1 */
1056 extra = (1 << (extra - 1 + CUTOFFBASE)) - 1;
1057 /* assert extra > 0 and n >= extra */
1058
1059 /* Swap that many values to the start of the array. The
1060 selection of elements is pseudo-random, but the same on
1061 every run (this is intentional! timing algorithm changes is
1062 a pain if timing varies across runs). */
1063 {
1064 unsigned int seed = n / extra; /* arbitrary */
1065 unsigned int i;
1066 for (i = 0; i < (unsigned)extra; ++i) {
1067 /* j := random int in [i, n) */
1068 unsigned int j;
1069 seed = seed * 69069 + 7;
1070 j = i + seed % (n - i);
1071 tmp = lo[i]; lo[i] = lo[j]; lo[j] = tmp;
1072 }
1073 }
1074
1075 /* Recursively sort the preselected pivots. */
Guido van Rossum42812581998-06-17 14:15:44 +00001076 if (samplesortslice(lo, lo + extra, compare) < 0)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001077 goto fail;
1078
1079 top = 0; /* index of available stack slot */
1080 lo += extra; /* point to first unknown */
1081 extraOnRight = 0; /* the PPs are at the left end */
1082
1083 /* ----------------------------------------------------------
1084 * Partition [lo, hi), and repeat until out of work.
1085 * --------------------------------------------------------*/
1086 for (;;) {
1087 /* assert lo <= hi, so n >= 0 */
1088 n = hi - lo;
1089
1090 /* We may not want, or may not be able, to partition:
1091 If n is small, it's quicker to insert.
1092 If extra is 0, we're out of pivots, and *must* use
1093 another method.
1094 */
1095 if (n < MINPARTITIONSIZE || extra == 0) {
1096 if (n >= MINSIZE) {
1097 /* assert extra == 0
1098 This is rare, since the average size
1099 of a final block is only about
1100 ln(original n). */
Guido van Rossum42812581998-06-17 14:15:44 +00001101 if (samplesortslice(lo, hi, compare) < 0)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001102 goto fail;
1103 }
1104 else {
1105 /* Binary insertion should be quicker,
1106 and we can take advantage of the PPs
1107 already being sorted. */
1108 if (extraOnRight && extra) {
1109 /* swap the PPs to the left end */
1110 k = extra;
1111 do {
1112 tmp = *lo;
1113 *lo = *hi;
1114 *hi = tmp;
1115 ++lo; ++hi;
1116 } while (--k);
1117 }
1118 if (binarysort(lo - extra, hi, lo,
Guido van Rossum42812581998-06-17 14:15:44 +00001119 compare) < 0)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001120 goto fail;
1121 }
1122
1123 /* Find another slice to work on. */
1124 if (--top < 0)
1125 break; /* no more -- done! */
1126 lo = stack[top].lo;
1127 hi = stack[top].hi;
1128 extra = stack[top].extra;
1129 extraOnRight = 0;
1130 if (extra < 0) {
1131 extraOnRight = 1;
1132 extra = -extra;
1133 }
1134 continue;
1135 }
1136
1137 /* Pretend the PPs are indexed 0, 1, ..., extra-1.
1138 Then our preselected pivot is at (extra-1)/2, and we
1139 want to move the PPs before that to the left end of
1140 the slice, and the PPs after that to the right end.
1141 The following section changes extra, lo, hi, and the
1142 slice such that:
1143 [lo-extra, lo) contains the smaller PPs.
1144 *lo == our PP.
1145 (lo, hi) contains the unknown elements.
1146 [hi, hi+extra) contains the larger PPs.
1147 */
1148 k = extra >>= 1; /* num PPs to move */
1149 if (extraOnRight) {
1150 /* Swap the smaller PPs to the left end.
1151 Note that this loop actually moves k+1 items:
1152 the last is our PP */
1153 do {
1154 tmp = *lo; *lo = *hi; *hi = tmp;
1155 ++lo; ++hi;
1156 } while (k--);
1157 }
1158 else {
1159 /* Swap the larger PPs to the right end. */
1160 while (k--) {
1161 --lo; --hi;
1162 tmp = *lo; *lo = *hi; *hi = tmp;
1163 }
1164 }
1165 --lo; /* *lo is now our PP */
1166 pivot = *lo;
1167
1168 /* Now an almost-ordinary quicksort partition step.
1169 Note that most of the time is spent here!
1170 Only odd thing is that we partition into < and >=,
1171 instead of the usual <= and >=. This helps when
1172 there are lots of duplicates of different values,
1173 because it eventually tends to make subfiles
1174 "pure" (all duplicates), and we special-case for
1175 duplicates later. */
1176 l = lo + 1;
1177 r = hi - 1;
1178 /* assert lo < l < r < hi (small n weeded out above) */
1179
1180 do {
1181 /* slide l right, looking for key >= pivot */
1182 do {
1183 SETK(*l, pivot);
1184 if (k < 0)
1185 ++l;
1186 else
1187 break;
1188 } while (l < r);
1189
1190 /* slide r left, looking for key < pivot */
1191 while (l < r) {
Guido van Rossum42812581998-06-17 14:15:44 +00001192 register PyObject *rval = *r--;
1193 SETK(rval, pivot);
1194 if (k < 0) {
1195 /* swap and advance */
1196 r[1] = *l;
1197 *l++ = rval;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001198 break;
Guido van Rossum42812581998-06-17 14:15:44 +00001199 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001200 }
1201
1202 } while (l < r);
1203
1204 /* assert lo < r <= l < hi
1205 assert r == l or r+1 == l
1206 everything to the left of l is < pivot, and
1207 everything to the right of r is >= pivot */
1208
1209 if (l == r) {
1210 SETK(*r, pivot);
1211 if (k < 0)
1212 ++l;
1213 else
1214 --r;
1215 }
1216 /* assert lo <= r and r+1 == l and l <= hi
1217 assert r == lo or a[r] < pivot
1218 assert a[lo] is pivot
1219 assert l == hi or a[l] >= pivot
1220 Swap the pivot into "the middle", so we can henceforth
1221 ignore it.
1222 */
1223 *lo = *r;
1224 *r = pivot;
1225
1226 /* The following is true now, & will be preserved:
1227 All in [lo,r) are < pivot
1228 All in [r,l) == pivot (& so can be ignored)
1229 All in [l,hi) are >= pivot */
1230
1231 /* Check for duplicates of the pivot. One compare is
1232 wasted if there are no duplicates, but can win big
1233 when there are.
1234 Tricky: we're sticking to "<" compares, so deduce
1235 equality indirectly. We know pivot <= *l, so they're
1236 equal iff not pivot < *l.
1237 */
1238 while (l < hi) {
1239 /* pivot <= *l known */
1240 SETK(pivot, *l);
1241 if (k < 0)
1242 break;
1243 else
1244 /* <= and not < implies == */
1245 ++l;
1246 }
1247
1248 /* assert lo <= r < l <= hi
1249 Partitions are [lo, r) and [l, hi) */
1250
1251 /* push fattest first; remember we still have extra PPs
1252 to the left of the left chunk and to the right of
1253 the right chunk! */
1254 /* assert top < STACKSIZE */
1255 if (r - lo <= hi - l) {
1256 /* second is bigger */
1257 stack[top].lo = l;
1258 stack[top].hi = hi;
1259 stack[top].extra = -extra;
1260 hi = r;
1261 extraOnRight = 0;
1262 }
1263 else {
1264 /* first is bigger */
1265 stack[top].lo = lo;
1266 stack[top].hi = r;
1267 stack[top].extra = extra;
1268 lo = l;
1269 extraOnRight = 1;
1270 }
1271 ++top;
1272
1273 } /* end of partitioning loop */
1274
1275 return 0;
1276
1277 fail:
1278 return -1;
1279}
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001280
1281#undef SETK
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001282
1283staticforward PyTypeObject immutable_list_type;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001284
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001285static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00001286listsort(PyListObject *self, PyObject *args)
Guido van Rossum3f236de1996-12-10 23:55:39 +00001287{
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001288 int err;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001289 PyObject *compare = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001290 PyTypeObject *savetype;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001291
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001292 if (args != NULL) {
Guido van Rossumc00a9382000-02-24 21:48:29 +00001293 if (!PyArg_ParseTuple(args, "|O:sort", &compare))
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001294 return NULL;
1295 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001296 savetype = self->ob_type;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001297 self->ob_type = &immutable_list_type;
1298 err = samplesortslice(self->ob_item,
1299 self->ob_item + self->ob_size,
Guido van Rossum42812581998-06-17 14:15:44 +00001300 compare);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001301 self->ob_type = savetype;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001302 if (err < 0)
Guido van Rossum3f236de1996-12-10 23:55:39 +00001303 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001304 Py_INCREF(Py_None);
1305 return Py_None;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001306}
1307
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001308int
Fred Drakea2f55112000-07-09 15:16:51 +00001309PyList_Sort(PyObject *v)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001310{
1311 if (v == NULL || !PyList_Check(v)) {
1312 PyErr_BadInternalCall();
1313 return -1;
1314 }
1315 v = listsort((PyListObject *)v, (PyObject *)NULL);
1316 if (v == NULL)
1317 return -1;
1318 Py_DECREF(v);
1319 return 0;
1320}
1321
Guido van Rossumb86c5492001-02-12 22:06:02 +00001322static void
1323_listreverse(PyListObject *self)
Guido van Rossumed98d481991-03-06 13:07:53 +00001324{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001325 register PyObject **p, **q;
1326 register PyObject *tmp;
Guido van Rossumed98d481991-03-06 13:07:53 +00001327
Guido van Rossumed98d481991-03-06 13:07:53 +00001328 if (self->ob_size > 1) {
1329 for (p = self->ob_item, q = self->ob_item + self->ob_size - 1;
Guido van Rossumb86c5492001-02-12 22:06:02 +00001330 p < q;
1331 p++, q--)
1332 {
Guido van Rossumed98d481991-03-06 13:07:53 +00001333 tmp = *p;
1334 *p = *q;
1335 *q = tmp;
1336 }
1337 }
Guido van Rossumb86c5492001-02-12 22:06:02 +00001338}
1339
1340static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001341listreverse(PyListObject *self)
Guido van Rossumb86c5492001-02-12 22:06:02 +00001342{
Guido van Rossumb86c5492001-02-12 22:06:02 +00001343 _listreverse(self);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001344 Py_INCREF(Py_None);
1345 return Py_None;
Guido van Rossumed98d481991-03-06 13:07:53 +00001346}
1347
Guido van Rossum84c76f51990-10-30 13:32:20 +00001348int
Fred Drakea2f55112000-07-09 15:16:51 +00001349PyList_Reverse(PyObject *v)
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00001350{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001351 if (v == NULL || !PyList_Check(v)) {
1352 PyErr_BadInternalCall();
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00001353 return -1;
1354 }
Guido van Rossumb86c5492001-02-12 22:06:02 +00001355 _listreverse((PyListObject *)v);
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00001356 return 0;
1357}
1358
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001359PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00001360PyList_AsTuple(PyObject *v)
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00001361{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001362 PyObject *w;
1363 PyObject **p;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00001364 int n;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001365 if (v == NULL || !PyList_Check(v)) {
1366 PyErr_BadInternalCall();
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00001367 return NULL;
1368 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001369 n = ((PyListObject *)v)->ob_size;
1370 w = PyTuple_New(n);
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00001371 if (w == NULL)
1372 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001373 p = ((PyTupleObject *)w)->ob_item;
Thomas Wouters334fb892000-07-25 12:56:38 +00001374 memcpy((void *)p,
1375 (void *)((PyListObject *)v)->ob_item,
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001376 n*sizeof(PyObject *));
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00001377 while (--n >= 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001378 Py_INCREF(*p);
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00001379 p++;
1380 }
1381 return w;
1382}
1383
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001384static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001385listindex(PyListObject *self, PyObject *v)
Guido van Rossumed98d481991-03-06 13:07:53 +00001386{
1387 int i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001388
Guido van Rossumed98d481991-03-06 13:07:53 +00001389 for (i = 0; i < self->ob_size; i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001390 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
1391 if (cmp > 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001392 return PyInt_FromLong((long)i);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001393 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00001394 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00001395 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001396 PyErr_SetString(PyExc_ValueError, "list.index(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00001397 return NULL;
1398}
1399
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001400static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001401listcount(PyListObject *self, PyObject *v)
Guido van Rossume6f7d181991-10-20 20:20:40 +00001402{
1403 int count = 0;
1404 int i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001405
Guido van Rossume6f7d181991-10-20 20:20:40 +00001406 for (i = 0; i < self->ob_size; i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001407 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
1408 if (cmp > 0)
Guido van Rossume6f7d181991-10-20 20:20:40 +00001409 count++;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001410 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00001411 return NULL;
Guido van Rossume6f7d181991-10-20 20:20:40 +00001412 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001413 return PyInt_FromLong((long)count);
Guido van Rossume6f7d181991-10-20 20:20:40 +00001414}
1415
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001416static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001417listremove(PyListObject *self, PyObject *v)
Guido van Rossumed98d481991-03-06 13:07:53 +00001418{
1419 int i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001420
Guido van Rossumed98d481991-03-06 13:07:53 +00001421 for (i = 0; i < self->ob_size; i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001422 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
1423 if (cmp > 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001424 if (list_ass_slice(self, i, i+1,
1425 (PyObject *)NULL) != 0)
Guido van Rossumed98d481991-03-06 13:07:53 +00001426 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001427 Py_INCREF(Py_None);
1428 return Py_None;
Guido van Rossumed98d481991-03-06 13:07:53 +00001429 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001430 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00001431 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00001432 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001433 PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00001434 return NULL;
1435}
1436
Jeremy Hylton8caad492000-06-23 14:18:11 +00001437static int
1438list_traverse(PyListObject *o, visitproc visit, void *arg)
1439{
1440 int i, err;
1441 PyObject *x;
1442
1443 for (i = o->ob_size; --i >= 0; ) {
1444 x = o->ob_item[i];
1445 if (x != NULL) {
1446 err = visit(x, arg);
1447 if (err)
1448 return err;
1449 }
1450 }
1451 return 0;
1452}
1453
1454static int
1455list_clear(PyListObject *lp)
1456{
1457 (void) PyList_SetSlice((PyObject *)lp, 0, lp->ob_size, 0);
1458 return 0;
1459}
1460
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001461static PyObject *
1462list_richcompare(PyObject *v, PyObject *w, int op)
1463{
1464 PyListObject *vl, *wl;
1465 int i;
1466
1467 if (!PyList_Check(v) || !PyList_Check(w)) {
1468 Py_INCREF(Py_NotImplemented);
1469 return Py_NotImplemented;
1470 }
1471
1472 vl = (PyListObject *)v;
1473 wl = (PyListObject *)w;
1474
1475 if (vl->ob_size != wl->ob_size && (op == Py_EQ || op == Py_NE)) {
1476 /* Shortcut: if the lengths differ, the lists differ */
1477 PyObject *res;
1478 if (op == Py_EQ)
1479 res = Py_False;
1480 else
1481 res = Py_True;
1482 Py_INCREF(res);
1483 return res;
1484 }
1485
1486 /* Search for the first index where items are different */
1487 for (i = 0; i < vl->ob_size && i < wl->ob_size; i++) {
1488 int k = PyObject_RichCompareBool(vl->ob_item[i],
1489 wl->ob_item[i], Py_EQ);
1490 if (k < 0)
1491 return NULL;
1492 if (!k)
1493 break;
1494 }
1495
1496 if (i >= vl->ob_size || i >= wl->ob_size) {
1497 /* No more items to compare -- compare sizes */
1498 int vs = vl->ob_size;
1499 int ws = wl->ob_size;
1500 int cmp;
1501 PyObject *res;
1502 switch (op) {
1503 case Py_LT: cmp = vs < ws; break;
Tim Peters6ee42342001-07-06 17:45:43 +00001504 case Py_LE: cmp = vs <= ws; break;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001505 case Py_EQ: cmp = vs == ws; break;
1506 case Py_NE: cmp = vs != ws; break;
1507 case Py_GT: cmp = vs > ws; break;
1508 case Py_GE: cmp = vs >= ws; break;
1509 default: return NULL; /* cannot happen */
1510 }
1511 if (cmp)
1512 res = Py_True;
1513 else
1514 res = Py_False;
1515 Py_INCREF(res);
1516 return res;
1517 }
1518
1519 /* We have an item that differs -- shortcuts for EQ/NE */
1520 if (op == Py_EQ) {
1521 Py_INCREF(Py_False);
1522 return Py_False;
1523 }
1524 if (op == Py_NE) {
1525 Py_INCREF(Py_True);
1526 return Py_True;
1527 }
1528
1529 /* Compare the final item again using the proper operator */
1530 return PyObject_RichCompare(vl->ob_item[i], wl->ob_item[i], op);
1531}
1532
Tim Peters6d6c1a32001-08-02 04:15:00 +00001533/* Adapted from newer code by Tim */
1534static int
1535list_fill(PyListObject *result, PyObject *v)
1536{
1537 PyObject *it; /* iter(v) */
1538 int n; /* guess for result list size */
1539 int i;
1540
1541 n = result->ob_size;
1542
1543 /* Special-case list(a_list), for speed. */
1544 if (PyList_Check(v)) {
1545 if (v == (PyObject *)result)
1546 return 0; /* source is destination, we're done */
1547 return list_ass_slice(result, 0, n, v);
1548 }
1549
1550 /* Empty previous contents */
1551 if (n != 0) {
1552 if (list_ass_slice(result, 0, n, (PyObject *)NULL) != 0)
1553 return -1;
1554 }
1555
1556 /* Get iterator. There may be some low-level efficiency to be gained
1557 * by caching the tp_iternext slot instead of using PyIter_Next()
1558 * later, but premature optimization is the root etc.
1559 */
1560 it = PyObject_GetIter(v);
1561 if (it == NULL)
1562 return -1;
1563
1564 /* Guess a result list size. */
1565 n = -1; /* unknown */
1566 if (PySequence_Check(v) &&
1567 v->ob_type->tp_as_sequence->sq_length) {
1568 n = PySequence_Size(v);
1569 if (n < 0)
1570 PyErr_Clear();
1571 }
1572 if (n < 0)
1573 n = 8; /* arbitrary */
1574 NRESIZE(result->ob_item, PyObject*, n);
Neal Norwitzd4e5be52002-05-22 23:19:17 +00001575 if (result->ob_item == NULL) {
1576 PyErr_NoMemory();
Tim Peters6d6c1a32001-08-02 04:15:00 +00001577 goto error;
Neal Norwitzd4e5be52002-05-22 23:19:17 +00001578 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001579 for (i = 0; i < n; i++)
1580 result->ob_item[i] = NULL;
1581 result->ob_size = n;
1582
1583 /* Run iterator to exhaustion. */
1584 for (i = 0; ; i++) {
1585 PyObject *item = PyIter_Next(it);
1586 if (item == NULL) {
1587 if (PyErr_Occurred())
1588 goto error;
1589 break;
1590 }
1591 if (i < n)
1592 PyList_SET_ITEM(result, i, item); /* steals ref */
1593 else {
1594 int status = ins1(result, result->ob_size, item);
1595 Py_DECREF(item); /* append creates a new ref */
1596 if (status < 0)
1597 goto error;
1598 }
1599 }
1600
1601 /* Cut back result list if initial guess was too large. */
1602 if (i < n && result != NULL) {
1603 if (list_ass_slice(result, i, n, (PyObject *)NULL) != 0)
1604 goto error;
1605 }
1606 Py_DECREF(it);
1607 return 0;
1608
1609 error:
1610 Py_DECREF(it);
1611 return -1;
1612}
1613
1614static int
1615list_init(PyListObject *self, PyObject *args, PyObject *kw)
1616{
1617 PyObject *arg = NULL;
1618 static char *kwlist[] = {"sequence", 0};
1619
1620 if (!PyArg_ParseTupleAndKeywords(args, kw, "|O:list", kwlist, &arg))
1621 return -1;
1622 if (arg != NULL)
1623 return list_fill(self, arg);
1624 if (self->ob_size > 0)
1625 return list_ass_slice(self, 0, self->ob_size, (PyObject*)NULL);
1626 return 0;
1627}
1628
Guido van Rossumdbb53d92001-12-03 16:32:18 +00001629static long
1630list_nohash(PyObject *self)
1631{
1632 PyErr_SetString(PyExc_TypeError, "list objects are unhashable");
1633 return -1;
1634}
1635
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +00001636static char append_doc[] =
1637"L.append(object) -- append object to end";
Barry Warsawdedf6d61998-10-09 16:37:25 +00001638static char extend_doc[] =
1639"L.extend(list) -- extend list by appending list elements";
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +00001640static char insert_doc[] =
1641"L.insert(index, object) -- insert object before index";
1642static char pop_doc[] =
1643"L.pop([index]) -> item -- remove and return item at index (default last)";
1644static char remove_doc[] =
1645"L.remove(value) -- remove first occurrence of value";
1646static char index_doc[] =
1647"L.index(value) -> integer -- return index of first occurrence of value";
1648static char count_doc[] =
1649"L.count(value) -> integer -- return number of occurrences of value";
1650static char reverse_doc[] =
1651"L.reverse() -- reverse *IN PLACE*";
1652static char sort_doc[] =
1653"L.sort([cmpfunc]) -- sort *IN PLACE*; if given, cmpfunc(x, y) -> -1, 0, 1";
1654
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001655static PyMethodDef list_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001656 {"append", (PyCFunction)listappend, METH_O, append_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001657 {"insert", (PyCFunction)listinsert, METH_VARARGS, insert_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001658 {"extend", (PyCFunction)listextend, METH_O, extend_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001659 {"pop", (PyCFunction)listpop, METH_VARARGS, pop_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001660 {"remove", (PyCFunction)listremove, METH_O, remove_doc},
1661 {"index", (PyCFunction)listindex, METH_O, index_doc},
1662 {"count", (PyCFunction)listcount, METH_O, count_doc},
1663 {"reverse", (PyCFunction)listreverse, METH_NOARGS, reverse_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001664 {"sort", (PyCFunction)listsort, METH_VARARGS, sort_doc},
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001665 {NULL, NULL} /* sentinel */
1666};
1667
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001668static PySequenceMethods list_as_sequence = {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001669 (inquiry)list_length, /* sq_length */
1670 (binaryfunc)list_concat, /* sq_concat */
1671 (intargfunc)list_repeat, /* sq_repeat */
1672 (intargfunc)list_item, /* sq_item */
1673 (intintargfunc)list_slice, /* sq_slice */
1674 (intobjargproc)list_ass_item, /* sq_ass_item */
1675 (intintobjargproc)list_ass_slice, /* sq_ass_slice */
1676 (objobjproc)list_contains, /* sq_contains */
1677 (binaryfunc)list_inplace_concat, /* sq_inplace_concat */
1678 (intargfunc)list_inplace_repeat, /* sq_inplace_repeat */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001679};
1680
Tim Peters6d6c1a32001-08-02 04:15:00 +00001681static char list_doc[] =
1682"list() -> new list\n"
1683"list(sequence) -> new list initialized from sequence's items";
1684
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00001685staticforward PyObject * list_iter(PyObject *seq);
1686
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001687PyTypeObject PyList_Type = {
1688 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001689 0,
1690 "list",
Neil Schemenauere83c00e2001-08-29 23:54:21 +00001691 sizeof(PyListObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001692 0,
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001693 (destructor)list_dealloc, /* tp_dealloc */
1694 (printfunc)list_print, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001695 0, /* tp_getattr */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001696 0, /* tp_setattr */
1697 0, /* tp_compare */
1698 (reprfunc)list_repr, /* tp_repr */
1699 0, /* tp_as_number */
1700 &list_as_sequence, /* tp_as_sequence */
1701 0, /* tp_as_mapping */
Guido van Rossumdbb53d92001-12-03 16:32:18 +00001702 list_nohash, /* tp_hash */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001703 0, /* tp_call */
1704 0, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001705 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001706 0, /* tp_setattro */
1707 0, /* tp_as_buffer */
Neil Schemenauere83c00e2001-08-29 23:54:21 +00001708 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Tim Peters6d6c1a32001-08-02 04:15:00 +00001709 Py_TPFLAGS_BASETYPE, /* tp_flags */
1710 list_doc, /* tp_doc */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001711 (traverseproc)list_traverse, /* tp_traverse */
1712 (inquiry)list_clear, /* tp_clear */
1713 list_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001714 0, /* tp_weaklistoffset */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00001715 list_iter, /* tp_iter */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001716 0, /* tp_iternext */
1717 list_methods, /* tp_methods */
1718 0, /* tp_members */
1719 0, /* tp_getset */
1720 0, /* tp_base */
1721 0, /* tp_dict */
1722 0, /* tp_descr_get */
1723 0, /* tp_descr_set */
1724 0, /* tp_dictoffset */
1725 (initproc)list_init, /* tp_init */
1726 PyType_GenericAlloc, /* tp_alloc */
1727 PyType_GenericNew, /* tp_new */
Neil Schemenauer99b5d282002-04-12 02:44:22 +00001728 PyObject_GC_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001729};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001730
1731
1732/* During a sort, we really can't have anyone modifying the list; it could
1733 cause core dumps. Thus, we substitute a dummy type that raises an
1734 explanatory exception when a modifying operation is used. Caveat:
1735 comparisons may behave differently; but I guess it's a bad idea anyway to
1736 compare a list that's being sorted... */
1737
1738static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00001739immutable_list_op(void)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001740{
1741 PyErr_SetString(PyExc_TypeError,
1742 "a list cannot be modified while it is being sorted");
1743 return NULL;
1744}
1745
1746static PyMethodDef immutable_list_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001747 {"append", (PyCFunction)immutable_list_op, METH_VARARGS},
1748 {"insert", (PyCFunction)immutable_list_op, METH_VARARGS},
Tim Peters52e07172001-08-30 06:15:32 +00001749 {"extend", (PyCFunction)immutable_list_op, METH_O},
1750 {"pop", (PyCFunction)immutable_list_op, METH_VARARGS},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001751 {"remove", (PyCFunction)immutable_list_op, METH_VARARGS},
1752 {"index", (PyCFunction)listindex, METH_O},
1753 {"count", (PyCFunction)listcount, METH_O},
1754 {"reverse", (PyCFunction)immutable_list_op, METH_VARARGS},
1755 {"sort", (PyCFunction)immutable_list_op, METH_VARARGS},
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001756 {NULL, NULL} /* sentinel */
1757};
1758
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001759static int
Fred Drakea2f55112000-07-09 15:16:51 +00001760immutable_list_ass(void)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001761{
1762 immutable_list_op();
1763 return -1;
1764}
1765
1766static PySequenceMethods immutable_list_as_sequence = {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001767 (inquiry)list_length, /* sq_length */
1768 (binaryfunc)list_concat, /* sq_concat */
1769 (intargfunc)list_repeat, /* sq_repeat */
1770 (intargfunc)list_item, /* sq_item */
1771 (intintargfunc)list_slice, /* sq_slice */
1772 (intobjargproc)immutable_list_ass, /* sq_ass_item */
1773 (intintobjargproc)immutable_list_ass, /* sq_ass_slice */
1774 (objobjproc)list_contains, /* sq_contains */
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001775};
1776
1777static PyTypeObject immutable_list_type = {
1778 PyObject_HEAD_INIT(&PyType_Type)
1779 0,
1780 "list (immutable, during sort)",
Neil Schemenauere83c00e2001-08-29 23:54:21 +00001781 sizeof(PyListObject),
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001782 0,
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001783 0, /* Cannot happen */ /* tp_dealloc */
1784 (printfunc)list_print, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001785 0, /* tp_getattr */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001786 0, /* tp_setattr */
1787 0, /* Won't be called */ /* tp_compare */
1788 (reprfunc)list_repr, /* tp_repr */
1789 0, /* tp_as_number */
1790 &immutable_list_as_sequence, /* tp_as_sequence */
1791 0, /* tp_as_mapping */
Guido van Rossumdbb53d92001-12-03 16:32:18 +00001792 list_nohash, /* tp_hash */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001793 0, /* tp_call */
1794 0, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001795 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001796 0, /* tp_setattro */
1797 0, /* tp_as_buffer */
Neil Schemenauere83c00e2001-08-29 23:54:21 +00001798 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001799 list_doc, /* tp_doc */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001800 (traverseproc)list_traverse, /* tp_traverse */
1801 0, /* tp_clear */
1802 list_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001803 0, /* tp_weaklistoffset */
1804 0, /* tp_iter */
1805 0, /* tp_iternext */
1806 immutable_list_methods, /* tp_methods */
1807 0, /* tp_members */
1808 0, /* tp_getset */
1809 0, /* tp_base */
1810 0, /* tp_dict */
1811 0, /* tp_descr_get */
1812 0, /* tp_descr_set */
1813 0, /* tp_init */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001814 /* NOTE: This is *not* the standard list_type struct! */
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001815};
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00001816
1817
1818/*********************** List Iterator **************************/
1819
1820typedef struct {
1821 PyObject_HEAD
1822 long it_index;
1823 PyObject *it_seq;
1824} listiterobject;
1825
1826PyTypeObject PyListIter_Type;
1827
1828PyObject *
1829list_iter(PyObject *seq)
1830{
1831 listiterobject *it;
1832
1833 if (!PyList_Check(seq)) {
1834 PyErr_BadInternalCall();
1835 return NULL;
1836 }
1837 it = PyObject_GC_New(listiterobject, &PyListIter_Type);
1838 if (it == NULL)
1839 return NULL;
1840 it->it_index = 0;
1841 Py_INCREF(seq);
1842 it->it_seq = seq;
1843 _PyObject_GC_TRACK(it);
1844 return (PyObject *)it;
1845}
1846
1847static void
1848listiter_dealloc(listiterobject *it)
1849{
1850 _PyObject_GC_UNTRACK(it);
1851 Py_DECREF(it->it_seq);
1852 PyObject_GC_Del(it);
1853}
1854
1855static int
1856listiter_traverse(listiterobject *it, visitproc visit, void *arg)
1857{
1858 return visit(it->it_seq, arg);
1859}
1860
1861
1862static PyObject *
1863listiter_getiter(PyObject *it)
1864{
1865 Py_INCREF(it);
1866 return it;
1867}
1868
1869static PyObject *
1870listiter_next(PyObject *it)
1871{
1872 PyObject *seq;
1873 PyObject *item;
1874
1875 assert(PyList_Check(it));
1876 seq = ((listiterobject *)it)->it_seq;
1877
1878 if (((listiterobject *)it)->it_index < PyList_GET_SIZE(seq)) {
1879 item = ((PyListObject *)(seq))->ob_item[((listiterobject *)it)->it_index++];
1880 Py_INCREF(item);
1881 return item;
1882 }
1883 return NULL;
1884}
1885
1886static PyMethodDef listiter_methods[] = {
1887 {"next", (PyCFunction)listiter_next, METH_NOARGS,
1888 "it.next() -- get the next value, or raise StopIteration"},
1889 {NULL, NULL} /* sentinel */
1890};
1891
1892PyTypeObject PyListIter_Type = {
1893 PyObject_HEAD_INIT(&PyType_Type)
1894 0, /* ob_size */
1895 "listiterator", /* tp_name */
1896 sizeof(listiterobject), /* tp_basicsize */
1897 0, /* tp_itemsize */
1898 /* methods */
1899 (destructor)listiter_dealloc, /* tp_dealloc */
1900 0, /* tp_print */
1901 0, /* tp_getattr */
1902 0, /* tp_setattr */
1903 0, /* tp_compare */
1904 0, /* tp_repr */
1905 0, /* tp_as_number */
1906 0, /* tp_as_sequence */
1907 0, /* tp_as_mapping */
1908 0, /* tp_hash */
1909 0, /* tp_call */
1910 0, /* tp_str */
1911 PyObject_GenericGetAttr, /* tp_getattro */
1912 0, /* tp_setattro */
1913 0, /* tp_as_buffer */
1914 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
1915 0, /* tp_doc */
1916 (traverseproc)listiter_traverse, /* tp_traverse */
1917 0, /* tp_clear */
1918 0, /* tp_richcompare */
1919 0, /* tp_weaklistoffset */
1920 (getiterfunc)listiter_getiter, /* tp_iter */
1921 (iternextfunc)listiter_next, /* tp_iternext */
1922 listiter_methods, /* tp_methods */
1923 0, /* tp_members */
1924 0, /* tp_getset */
1925 0, /* tp_base */
1926 0, /* tp_dict */
1927 0, /* tp_descr_get */
1928 0, /* tp_descr_set */
1929};
1930