blob: 7d3d48f9412c760a0f2eb23695d5be07928c757b [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
Guido van Rossuma46d51d1995-01-26 22:59:43 +000011static int
Fred Drakea2f55112000-07-09 15:16:51 +000012roundupsize(int n)
Guido van Rossuma46d51d1995-01-26 22:59:43 +000013{
Tim Peters65b8b842001-05-26 05:28:40 +000014 unsigned int nbits = 0;
15 unsigned int n2 = (unsigned int)n >> 5;
16
Tim Peters3b01a122002-07-19 02:35:45 +000017 /* Round up:
Tim Peters65b8b842001-05-26 05:28:40 +000018 * If n < 256, to a multiple of 8.
19 * If n < 2048, to a multiple of 64.
20 * If n < 16384, to a multiple of 512.
21 * If n < 131072, to a multiple of 4096.
22 * If n < 1048576, to a multiple of 32768.
23 * If n < 8388608, to a multiple of 262144.
24 * If n < 67108864, to a multiple of 2097152.
25 * If n < 536870912, to a multiple of 16777216.
26 * ...
27 * If n < 2**(5+3*i), to a multiple of 2**(3*i).
28 *
29 * This over-allocates proportional to the list size, making room
30 * for additional growth. The over-allocation is mild, but is
31 * enough to give linear-time amortized behavior over a long
32 * sequence of appends() in the presence of a poorly-performing
33 * system realloc() (which is a reality, e.g., across all flavors
34 * of Windows, with Win9x behavior being particularly bad -- and
35 * we've still got address space fragmentation problems on Win9x
36 * even with this scheme, although it requires much longer lists to
37 * provoke them than it used to).
38 */
39 do {
40 n2 >>= 3;
41 nbits += 3;
42 } while (n2);
43 return ((n >> nbits) + 1) << nbits;
44 }
Guido van Rossuma46d51d1995-01-26 22:59:43 +000045
Neal Norwitzd4e5be52002-05-22 23:19:17 +000046#define NRESIZE(var, type, nitems) \
47do { \
48 size_t _new_size = roundupsize(nitems); \
49 if (_new_size <= ((~(size_t)0) / sizeof(type))) \
50 PyMem_RESIZE(var, type, _new_size); \
51 else \
52 var = NULL; \
53} while (0)
Guido van Rossuma46d51d1995-01-26 22:59:43 +000054
Guido van Rossumc0b618a1997-05-02 03:12:38 +000055PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +000056PyList_New(int size)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000057{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000058 PyListObject *op;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +000059 size_t nbytes;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000060 if (size < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +000061 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000062 return NULL;
63 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +000064 nbytes = size * sizeof(PyObject *);
Guido van Rossum1e28e5e1992-08-19 16:46:30 +000065 /* Check for overflow */
Guido van Rossumc0b618a1997-05-02 03:12:38 +000066 if (nbytes / sizeof(PyObject *) != (size_t)size) {
67 return PyErr_NoMemory();
Guido van Rossum1e28e5e1992-08-19 16:46:30 +000068 }
Neil Schemenauere83c00e2001-08-29 23:54:21 +000069 op = PyObject_GC_New(PyListObject, &PyList_Type);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000070 if (op == NULL) {
Neil Schemenauere83c00e2001-08-29 23:54:21 +000071 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000072 }
73 if (size <= 0) {
74 op->ob_item = NULL;
75 }
76 else {
Guido van Rossumb18618d2000-05-03 23:44:39 +000077 op->ob_item = (PyObject **) PyMem_MALLOC(nbytes);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000078 if (op->ob_item == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +000079 return PyErr_NoMemory();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000080 }
Neal Norwitz35fc7602002-06-13 21:11:11 +000081 memset(op->ob_item, 0, sizeof(*op->ob_item) * size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000082 }
Neil Schemenauere83c00e2001-08-29 23:54:21 +000083 op->ob_size = size;
Neil Schemenauere83c00e2001-08-29 23:54:21 +000084 _PyObject_GC_TRACK(op);
Guido van Rossumc0b618a1997-05-02 03:12:38 +000085 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000086}
87
88int
Fred Drakea2f55112000-07-09 15:16:51 +000089PyList_Size(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000090{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000091 if (!PyList_Check(op)) {
92 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000093 return -1;
94 }
95 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +000096 return ((PyListObject *)op) -> ob_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000097}
98
Guido van Rossumc0b618a1997-05-02 03:12:38 +000099static PyObject *indexerr;
Guido van Rossum929f1b81996-08-09 20:51:27 +0000100
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000101PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000102PyList_GetItem(PyObject *op, int i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000103{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000104 if (!PyList_Check(op)) {
105 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000106 return NULL;
107 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000108 if (i < 0 || i >= ((PyListObject *)op) -> ob_size) {
Guido van Rossum929f1b81996-08-09 20:51:27 +0000109 if (indexerr == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000110 indexerr = PyString_FromString(
111 "list index out of range");
112 PyErr_SetObject(PyExc_IndexError, indexerr);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000113 return NULL;
114 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000115 return ((PyListObject *)op) -> ob_item[i];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000116}
117
118int
Fred Drakea2f55112000-07-09 15:16:51 +0000119PyList_SetItem(register PyObject *op, register int i,
120 register PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000121{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000122 register PyObject *olditem;
123 register PyObject **p;
124 if (!PyList_Check(op)) {
125 Py_XDECREF(newitem);
126 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000127 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000128 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000129 if (i < 0 || i >= ((PyListObject *)op) -> ob_size) {
130 Py_XDECREF(newitem);
131 PyErr_SetString(PyExc_IndexError,
132 "list assignment index out of range");
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000133 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000134 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000135 p = ((PyListObject *)op) -> ob_item + i;
Guido van Rossum5fe60581995-03-09 12:12:50 +0000136 olditem = *p;
137 *p = newitem;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000138 Py_XDECREF(olditem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000139 return 0;
140}
141
142static int
Fred Drakea2f55112000-07-09 15:16:51 +0000143ins1(PyListObject *self, int where, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000144{
145 int i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000146 PyObject **items;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000147 if (v == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000148 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000149 return -1;
150 }
Trent Micka5846642000-08-13 22:47:45 +0000151 if (self->ob_size == INT_MAX) {
152 PyErr_SetString(PyExc_OverflowError,
153 "cannot add more objects to list");
154 return -1;
155 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000156 items = self->ob_item;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000157 NRESIZE(items, PyObject *, self->ob_size+1);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000158 if (items == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000159 PyErr_NoMemory();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000160 return -1;
161 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000162 if (where < 0)
163 where = 0;
164 if (where > self->ob_size)
165 where = self->ob_size;
166 for (i = self->ob_size; --i >= where; )
167 items[i+1] = items[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000168 Py_INCREF(v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000169 items[where] = v;
170 self->ob_item = items;
171 self->ob_size++;
172 return 0;
173}
174
175int
Fred Drakea2f55112000-07-09 15:16:51 +0000176PyList_Insert(PyObject *op, int where, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000177{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000178 if (!PyList_Check(op)) {
179 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000180 return -1;
181 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000182 return ins1((PyListObject *)op, where, newitem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000183}
184
185int
Fred Drakea2f55112000-07-09 15:16:51 +0000186PyList_Append(PyObject *op, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000187{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000188 if (!PyList_Check(op)) {
189 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000190 return -1;
191 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000192 return ins1((PyListObject *)op,
193 (int) ((PyListObject *)op)->ob_size, newitem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000194}
195
196/* Methods */
197
198static void
Fred Drakea2f55112000-07-09 15:16:51 +0000199list_dealloc(PyListObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000200{
201 int i;
Guido van Rossumff413af2002-03-28 20:34:59 +0000202 PyObject_GC_UnTrack(op);
Guido van Rossumd724b232000-03-13 16:01:29 +0000203 Py_TRASHCAN_SAFE_BEGIN(op)
Jack Jansen7874d1f1995-01-19 12:09:27 +0000204 if (op->ob_item != NULL) {
Guido van Rossumfa717011999-06-09 15:19:34 +0000205 /* Do it backwards, for Christian Tismer.
206 There's a simple test case where somehow this reduces
207 thrashing when a *very* large list is created and
208 immediately deleted. */
209 i = op->ob_size;
210 while (--i >= 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000211 Py_XDECREF(op->ob_item[i]);
Jack Jansen7874d1f1995-01-19 12:09:27 +0000212 }
Guido van Rossumb18618d2000-05-03 23:44:39 +0000213 PyMem_FREE(op->ob_item);
Jack Jansen7874d1f1995-01-19 12:09:27 +0000214 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000215 op->ob_type->tp_free((PyObject *)op);
Guido van Rossumd724b232000-03-13 16:01:29 +0000216 Py_TRASHCAN_SAFE_END(op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000217}
218
Guido van Rossum90933611991-06-07 16:10:43 +0000219static int
Fred Drakea2f55112000-07-09 15:16:51 +0000220list_print(PyListObject *op, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000221{
222 int i;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000223
224 i = Py_ReprEnter((PyObject*)op);
225 if (i != 0) {
226 if (i < 0)
227 return i;
228 fprintf(fp, "[...]");
229 return 0;
230 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000231 fprintf(fp, "[");
Guido van Rossum90933611991-06-07 16:10:43 +0000232 for (i = 0; i < op->ob_size; i++) {
233 if (i > 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000234 fprintf(fp, ", ");
Guido van Rossumfb376de1998-04-10 22:47:27 +0000235 if (PyObject_Print(op->ob_item[i], fp, 0) != 0) {
236 Py_ReprLeave((PyObject *)op);
Guido van Rossum90933611991-06-07 16:10:43 +0000237 return -1;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000238 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000239 }
240 fprintf(fp, "]");
Guido van Rossumfb376de1998-04-10 22:47:27 +0000241 Py_ReprLeave((PyObject *)op);
Guido van Rossum90933611991-06-07 16:10:43 +0000242 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000243}
244
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000245static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000246list_repr(PyListObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000247{
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000248 int i;
Tim Petersa7259592001-06-16 05:11:17 +0000249 PyObject *s, *temp;
250 PyObject *pieces = NULL, *result = NULL;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000251
252 i = Py_ReprEnter((PyObject*)v);
253 if (i != 0) {
Tim Petersa7259592001-06-16 05:11:17 +0000254 return i > 0 ? PyString_FromString("[...]") : NULL;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000255 }
Tim Petersa7259592001-06-16 05:11:17 +0000256
257 if (v->ob_size == 0) {
258 result = PyString_FromString("[]");
259 goto Done;
260 }
261
262 pieces = PyList_New(0);
263 if (pieces == NULL)
264 goto Done;
265
266 /* Do repr() on each element. Note that this may mutate the list,
267 so must refetch the list size on each iteration. */
268 for (i = 0; i < v->ob_size; ++i) {
269 int status;
270 s = PyObject_Repr(v->ob_item[i]);
271 if (s == NULL)
272 goto Done;
273 status = PyList_Append(pieces, s);
274 Py_DECREF(s); /* append created a new ref */
275 if (status < 0)
276 goto Done;
277 }
278
279 /* Add "[]" decorations to the first and last items. */
280 assert(PyList_GET_SIZE(pieces) > 0);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000281 s = PyString_FromString("[");
Tim Petersa7259592001-06-16 05:11:17 +0000282 if (s == NULL)
283 goto Done;
284 temp = PyList_GET_ITEM(pieces, 0);
285 PyString_ConcatAndDel(&s, temp);
286 PyList_SET_ITEM(pieces, 0, s);
287 if (s == NULL)
288 goto Done;
289
290 s = PyString_FromString("]");
291 if (s == NULL)
292 goto Done;
293 temp = PyList_GET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1);
294 PyString_ConcatAndDel(&temp, s);
295 PyList_SET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1, temp);
296 if (temp == NULL)
297 goto Done;
298
299 /* Paste them all together with ", " between. */
300 s = PyString_FromString(", ");
301 if (s == NULL)
302 goto Done;
303 result = _PyString_Join(s, pieces);
Tim Peters3b01a122002-07-19 02:35:45 +0000304 Py_DECREF(s);
Tim Petersa7259592001-06-16 05:11:17 +0000305
306Done:
307 Py_XDECREF(pieces);
Guido van Rossumfb376de1998-04-10 22:47:27 +0000308 Py_ReprLeave((PyObject *)v);
Tim Petersa7259592001-06-16 05:11:17 +0000309 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000310}
311
312static int
Fred Drakea2f55112000-07-09 15:16:51 +0000313list_length(PyListObject *a)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000314{
315 return a->ob_size;
316}
317
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000318
319
320static int
Fred Drakea2f55112000-07-09 15:16:51 +0000321list_contains(PyListObject *a, PyObject *el)
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000322{
Guido van Rossum65e1cea2001-01-17 22:11:59 +0000323 int i;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000324
325 for (i = 0; i < a->ob_size; ++i) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +0000326 int cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i),
327 Py_EQ);
328 if (cmp > 0)
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000329 return 1;
Guido van Rossum65e1cea2001-01-17 22:11:59 +0000330 else if (cmp < 0)
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000331 return -1;
332 }
333 return 0;
334}
335
336
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000337static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000338list_item(PyListObject *a, int i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000339{
340 if (i < 0 || i >= a->ob_size) {
Guido van Rossum929f1b81996-08-09 20:51:27 +0000341 if (indexerr == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000342 indexerr = PyString_FromString(
343 "list index out of range");
344 PyErr_SetObject(PyExc_IndexError, indexerr);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000345 return NULL;
346 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000347 Py_INCREF(a->ob_item[i]);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000348 return a->ob_item[i];
349}
350
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000351static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000352list_slice(PyListObject *a, int ilow, int ihigh)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000353{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000354 PyListObject *np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000355 int i;
356 if (ilow < 0)
357 ilow = 0;
358 else if (ilow > a->ob_size)
359 ilow = a->ob_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000360 if (ihigh < ilow)
361 ihigh = ilow;
362 else if (ihigh > a->ob_size)
363 ihigh = a->ob_size;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000364 np = (PyListObject *) PyList_New(ihigh - ilow);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000365 if (np == NULL)
366 return NULL;
367 for (i = ilow; i < ihigh; i++) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000368 PyObject *v = a->ob_item[i];
369 Py_INCREF(v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000370 np->ob_item[i - ilow] = v;
371 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000372 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000373}
374
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000375PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000376PyList_GetSlice(PyObject *a, int ilow, int ihigh)
Guido van Rossum234f9421993-06-17 12:35:49 +0000377{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000378 if (!PyList_Check(a)) {
379 PyErr_BadInternalCall();
Guido van Rossum234f9421993-06-17 12:35:49 +0000380 return NULL;
381 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000382 return list_slice((PyListObject *)a, ilow, ihigh);
Guido van Rossum234f9421993-06-17 12:35:49 +0000383}
384
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000385static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000386list_concat(PyListObject *a, PyObject *bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000387{
388 int size;
389 int i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000390 PyListObject *np;
391 if (!PyList_Check(bb)) {
Fred Drakeb6a9ada2000-06-01 03:12:13 +0000392 PyErr_Format(PyExc_TypeError,
Fred Drake914a2ed2000-06-01 14:31:03 +0000393 "can only concatenate list (not \"%.200s\") to list",
394 bb->ob_type->tp_name);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000395 return NULL;
396 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000397#define b ((PyListObject *)bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000398 size = a->ob_size + b->ob_size;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000399 np = (PyListObject *) PyList_New(size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000400 if (np == NULL) {
Guido van Rossum90933611991-06-07 16:10:43 +0000401 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000402 }
403 for (i = 0; i < a->ob_size; i++) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000404 PyObject *v = a->ob_item[i];
405 Py_INCREF(v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000406 np->ob_item[i] = v;
407 }
408 for (i = 0; i < b->ob_size; i++) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000409 PyObject *v = b->ob_item[i];
410 Py_INCREF(v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000411 np->ob_item[i + a->ob_size] = v;
412 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000413 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000414#undef b
415}
416
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000417static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000418list_repeat(PyListObject *a, int n)
Guido van Rossumed98d481991-03-06 13:07:53 +0000419{
420 int i, j;
421 int size;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000422 PyListObject *np;
423 PyObject **p;
Guido van Rossumed98d481991-03-06 13:07:53 +0000424 if (n < 0)
425 n = 0;
426 size = a->ob_size * n;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000427 np = (PyListObject *) PyList_New(size);
Guido van Rossumed98d481991-03-06 13:07:53 +0000428 if (np == NULL)
429 return NULL;
430 p = np->ob_item;
431 for (i = 0; i < n; i++) {
432 for (j = 0; j < a->ob_size; j++) {
433 *p = a->ob_item[j];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000434 Py_INCREF(*p);
Guido van Rossumed98d481991-03-06 13:07:53 +0000435 p++;
436 }
437 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000438 return (PyObject *) np;
Guido van Rossumed98d481991-03-06 13:07:53 +0000439}
440
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000441static int
Fred Drakea2f55112000-07-09 15:16:51 +0000442list_ass_slice(PyListObject *a, int ilow, int ihigh, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000443{
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000444 /* Because [X]DECREF can recursively invoke list operations on
445 this list, we must postpone all [X]DECREF activity until
446 after the list is back in its canonical shape. Therefore
447 we must allocate an additional array, 'recycle', into which
448 we temporarily copy the items that are deleted from the
449 list. :-( */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000450 PyObject **recycle, **p;
451 PyObject **item;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000452 int n; /* Size of replacement list */
453 int d; /* Change in size */
454 int k; /* Loop index */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000455#define b ((PyListObject *)v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000456 if (v == NULL)
457 n = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000458 else if (PyList_Check(v)) {
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000459 n = b->ob_size;
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000460 if (a == b) {
461 /* Special case "a[i:j] = a" -- copy b first */
462 int ret;
463 v = list_slice(b, 0, n);
464 ret = list_ass_slice(a, ilow, ihigh, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000465 Py_DECREF(v);
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000466 return ret;
467 }
468 }
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000469 else {
Fred Drakeb6a9ada2000-06-01 03:12:13 +0000470 PyErr_Format(PyExc_TypeError,
471 "must assign list (not \"%.200s\") to slice",
472 v->ob_type->tp_name);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000473 return -1;
474 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000475 if (ilow < 0)
476 ilow = 0;
477 else if (ilow > a->ob_size)
478 ilow = a->ob_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000479 if (ihigh < ilow)
480 ihigh = ilow;
481 else if (ihigh > a->ob_size)
482 ihigh = a->ob_size;
483 item = a->ob_item;
484 d = n - (ihigh-ilow);
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000485 if (ihigh > ilow)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000486 p = recycle = PyMem_NEW(PyObject *, (ihigh-ilow));
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000487 else
488 p = recycle = NULL;
489 if (d <= 0) { /* Delete -d items; recycle ihigh-ilow items */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000490 for (k = ilow; k < ihigh; k++)
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000491 *p++ = item[k];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000492 if (d < 0) {
493 for (/*k = ihigh*/; k < a->ob_size; k++)
494 item[k+d] = item[k];
495 a->ob_size += d;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000496 NRESIZE(item, PyObject *, a->ob_size); /* Can't fail */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000497 a->ob_item = item;
498 }
499 }
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000500 else { /* Insert d items; recycle ihigh-ilow items */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000501 NRESIZE(item, PyObject *, a->ob_size + d);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000502 if (item == NULL) {
Guido van Rossumb18618d2000-05-03 23:44:39 +0000503 if (recycle != NULL)
504 PyMem_DEL(recycle);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000505 PyErr_NoMemory();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000506 return -1;
507 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000508 for (k = a->ob_size; --k >= ihigh; )
509 item[k+d] = item[k];
510 for (/*k = ihigh-1*/; k >= ilow; --k)
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000511 *p++ = item[k];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000512 a->ob_item = item;
513 a->ob_size += d;
514 }
515 for (k = 0; k < n; k++, ilow++) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000516 PyObject *w = b->ob_item[k];
517 Py_XINCREF(w);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000518 item[ilow] = w;
519 }
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000520 if (recycle) {
521 while (--p >= recycle)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000522 Py_XDECREF(*p);
523 PyMem_DEL(recycle);
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000524 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000525 if (a->ob_size == 0 && a->ob_item != NULL) {
526 PyMem_FREE(a->ob_item);
527 a->ob_item = NULL;
528 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000529 return 0;
530#undef b
531}
532
Guido van Rossum234f9421993-06-17 12:35:49 +0000533int
Fred Drakea2f55112000-07-09 15:16:51 +0000534PyList_SetSlice(PyObject *a, int ilow, int ihigh, PyObject *v)
Guido van Rossum234f9421993-06-17 12:35:49 +0000535{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000536 if (!PyList_Check(a)) {
537 PyErr_BadInternalCall();
Guido van Rossum1fc238a1993-07-29 08:25:09 +0000538 return -1;
Guido van Rossum234f9421993-06-17 12:35:49 +0000539 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000540 return list_ass_slice((PyListObject *)a, ilow, ihigh, v);
Guido van Rossum234f9421993-06-17 12:35:49 +0000541}
542
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000543static PyObject *
544list_inplace_repeat(PyListObject *self, int n)
545{
546 PyObject **items;
547 int size, i, j;
548
549
550 size = PyList_GET_SIZE(self);
551 if (size == 0) {
552 Py_INCREF(self);
553 return (PyObject *)self;
554 }
555
556 items = self->ob_item;
557
558 if (n < 1) {
559 self->ob_item = NULL;
560 self->ob_size = 0;
561 for (i = 0; i < size; i++)
562 Py_XDECREF(items[i]);
563 PyMem_DEL(items);
564 Py_INCREF(self);
565 return (PyObject *)self;
566 }
567
568 NRESIZE(items, PyObject*, size*n);
569 if (items == NULL) {
570 PyErr_NoMemory();
571 goto finally;
572 }
573 self->ob_item = items;
574 for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */
575 for (j = 0; j < size; j++) {
576 PyObject *o = PyList_GET_ITEM(self, j);
577 Py_INCREF(o);
578 PyList_SET_ITEM(self, self->ob_size++, o);
579 }
580 }
581 Py_INCREF(self);
582 return (PyObject *)self;
583 finally:
584 return NULL;
585}
586
Guido van Rossum4a450d01991-04-03 19:05:18 +0000587static int
Fred Drakea2f55112000-07-09 15:16:51 +0000588list_ass_item(PyListObject *a, int i, PyObject *v)
Guido van Rossum4a450d01991-04-03 19:05:18 +0000589{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000590 PyObject *old_value;
Guido van Rossum4a450d01991-04-03 19:05:18 +0000591 if (i < 0 || i >= a->ob_size) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000592 PyErr_SetString(PyExc_IndexError,
593 "list assignment index out of range");
Guido van Rossum4a450d01991-04-03 19:05:18 +0000594 return -1;
595 }
596 if (v == NULL)
597 return list_ass_slice(a, i, i+1, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000598 Py_INCREF(v);
Guido van Rossumd7047b31995-01-02 19:07:15 +0000599 old_value = a->ob_item[i];
Guido van Rossum4a450d01991-04-03 19:05:18 +0000600 a->ob_item[i] = v;
Tim Peters3b01a122002-07-19 02:35:45 +0000601 Py_DECREF(old_value);
Guido van Rossum4a450d01991-04-03 19:05:18 +0000602 return 0;
603}
604
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000605static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000606ins(PyListObject *self, int where, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000607{
608 if (ins1(self, where, v) != 0)
609 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000610 Py_INCREF(Py_None);
611 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000612}
613
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000614static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000615listinsert(PyListObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000616{
617 int i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000618 PyObject *v;
Guido van Rossumc00a9382000-02-24 21:48:29 +0000619 if (!PyArg_ParseTuple(args, "iO:insert", &i, &v))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000620 return NULL;
Guido van Rossumbf80e541993-02-08 15:49:17 +0000621 return ins(self, i, v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000622}
623
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000624static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000625listappend(PyListObject *self, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000626{
Guido van Rossumbf80e541993-02-08 15:49:17 +0000627 return ins(self, (int) self->ob_size, v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000628}
629
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000630static int
631listextend_internal(PyListObject *self, PyObject *b)
Barry Warsawdedf6d61998-10-09 16:37:25 +0000632{
Barry Warsawdedf6d61998-10-09 16:37:25 +0000633 PyObject **items;
634 int selflen = PyList_GET_SIZE(self);
635 int blen;
636 register int i;
637
Jeremy Hyltondb60bb52001-01-03 22:32:16 +0000638 if (PyObject_Size(b) == 0) {
Barry Warsawdedf6d61998-10-09 16:37:25 +0000639 /* short circuit when b is empty */
Jeremy Hyltondb60bb52001-01-03 22:32:16 +0000640 Py_DECREF(b);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000641 return 0;
Jeremy Hyltondb60bb52001-01-03 22:32:16 +0000642 }
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000643
Barry Warsawdedf6d61998-10-09 16:37:25 +0000644 if (self == (PyListObject*)b) {
645 /* as in list_ass_slice() we must special case the
646 * situation: a.extend(a)
647 *
648 * XXX: I think this way ought to be faster than using
649 * list_slice() the way list_ass_slice() does.
650 */
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000651 Py_DECREF(b);
Barry Warsawdedf6d61998-10-09 16:37:25 +0000652 b = PyList_New(selflen);
653 if (!b)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000654 return -1;
Barry Warsawdedf6d61998-10-09 16:37:25 +0000655 for (i = 0; i < selflen; i++) {
656 PyObject *o = PyList_GET_ITEM(self, i);
657 Py_INCREF(o);
658 PyList_SET_ITEM(b, i, o);
659 }
660 }
Barry Warsawdedf6d61998-10-09 16:37:25 +0000661
Jeremy Hylton03657cf2000-07-12 13:05:33 +0000662 blen = PyObject_Size(b);
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000663
Barry Warsawdedf6d61998-10-09 16:37:25 +0000664 /* resize a using idiom */
665 items = self->ob_item;
666 NRESIZE(items, PyObject*, selflen + blen);
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000667 if (items == NULL) {
Barry Warsawdedf6d61998-10-09 16:37:25 +0000668 PyErr_NoMemory();
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000669 Py_DECREF(b);
670 return -1;
Barry Warsawdedf6d61998-10-09 16:37:25 +0000671 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000672
Barry Warsawdedf6d61998-10-09 16:37:25 +0000673 self->ob_item = items;
674
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000675 /* populate the end of self with b's items */
Barry Warsawdedf6d61998-10-09 16:37:25 +0000676 for (i = 0; i < blen; i++) {
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000677 PyObject *o = PySequence_Fast_GET_ITEM(b, i);
Barry Warsawdedf6d61998-10-09 16:37:25 +0000678 Py_INCREF(o);
679 PyList_SET_ITEM(self, self->ob_size++, o);
680 }
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000681 Py_DECREF(b);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000682 return 0;
Barry Warsawdedf6d61998-10-09 16:37:25 +0000683}
684
685
686static PyObject *
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000687list_inplace_concat(PyListObject *self, PyObject *other)
688{
Tim Peters1af03e92001-05-26 19:37:54 +0000689 other = PySequence_Fast(other, "argument to += must be iterable");
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000690 if (!other)
691 return NULL;
692
693 if (listextend_internal(self, other) < 0)
694 return NULL;
695
696 Py_INCREF(self);
697 return (PyObject *)self;
698}
699
700static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000701listextend(PyListObject *self, PyObject *b)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000702{
703
Tim Peters1af03e92001-05-26 19:37:54 +0000704 b = PySequence_Fast(b, "list.extend() argument must be iterable");
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000705 if (!b)
706 return NULL;
707
708 if (listextend_internal(self, b) < 0)
709 return NULL;
710
711 Py_INCREF(Py_None);
712 return Py_None;
713}
714
715static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000716listpop(PyListObject *self, PyObject *args)
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000717{
718 int i = -1;
719 PyObject *v;
Guido van Rossumc00a9382000-02-24 21:48:29 +0000720 if (!PyArg_ParseTuple(args, "|i:pop", &i))
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000721 return NULL;
722 if (self->ob_size == 0) {
723 /* Special-case most common failure cause */
724 PyErr_SetString(PyExc_IndexError, "pop from empty list");
725 return NULL;
726 }
727 if (i < 0)
728 i += self->ob_size;
729 if (i < 0 || i >= self->ob_size) {
730 PyErr_SetString(PyExc_IndexError, "pop index out of range");
731 return NULL;
732 }
733 v = self->ob_item[i];
734 Py_INCREF(v);
735 if (list_ass_slice(self, i, i+1, (PyObject *)NULL) != 0) {
736 Py_DECREF(v);
737 return NULL;
738 }
739 return v;
740}
741
Tim Peters8e2e7ca2002-07-19 02:33:08 +0000742/* Reverse a slice of a list in place, from lo up to (exclusive) hi. */
743static void
744reverse_slice(PyObject **lo, PyObject **hi)
745{
746 assert(lo && hi);
747
748 --hi;
749 while (lo < hi) {
750 PyObject *t = *lo;
751 *lo = *hi;
752 *hi = t;
753 ++lo;
754 --hi;
755 }
756}
757
Guido van Rossum3f236de1996-12-10 23:55:39 +0000758/* New quicksort implementation for arrays of object pointers.
759 Thanks to discussions with Tim Peters. */
760
Guido van Rossum3f236de1996-12-10 23:55:39 +0000761/* Comparison function. Takes care of calling a user-supplied
762 comparison function (any callable Python object). Calls the
Tim Petersa8c974c2002-07-19 03:30:57 +0000763 standard comparison function, PyObject_RichCompareBool(), if the user-
764 supplied function is NULL.
765 Returns <0 on error, >0 if x < y, 0 if x >= y. */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000766
767static int
Tim Petersa8c974c2002-07-19 03:30:57 +0000768islt(PyObject *x, PyObject *y, PyObject *compare)
Guido van Rossum3f236de1996-12-10 23:55:39 +0000769{
Tim Petersf2a04732002-07-11 21:46:16 +0000770 PyObject *res;
771 PyObject *args;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000772 int i;
773
Tim Petersa8c974c2002-07-19 03:30:57 +0000774 if (compare == NULL)
775 return PyObject_RichCompareBool(x, y, Py_LT);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000776
Tim Petersa8c974c2002-07-19 03:30:57 +0000777 /* Call the user's comparison function and translate the 3-way
778 * result into true or false (or error).
779 */
Tim Petersf2a04732002-07-11 21:46:16 +0000780 args = PyTuple_New(2);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000781 if (args == NULL)
Tim Petersa8c974c2002-07-19 03:30:57 +0000782 return -1;
Tim Petersf2a04732002-07-11 21:46:16 +0000783 Py_INCREF(x);
784 Py_INCREF(y);
785 PyTuple_SET_ITEM(args, 0, x);
786 PyTuple_SET_ITEM(args, 1, y);
Tim Peters58cf3612002-07-15 05:16:13 +0000787 res = PyObject_Call(compare, args, NULL);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000788 Py_DECREF(args);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000789 if (res == NULL)
Tim Petersa8c974c2002-07-19 03:30:57 +0000790 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000791 if (!PyInt_Check(res)) {
792 Py_DECREF(res);
793 PyErr_SetString(PyExc_TypeError,
Guido van Rossum9bcd1d71999-04-19 17:44:39 +0000794 "comparison function must return int");
Tim Petersa8c974c2002-07-19 03:30:57 +0000795 return -1;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000796 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000797 i = PyInt_AsLong(res);
798 Py_DECREF(res);
Tim Petersa8c974c2002-07-19 03:30:57 +0000799 return i < 0;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000800}
801
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000802/* MINSIZE is the smallest array that will get a full-blown samplesort
803 treatment; smaller arrays are sorted using binary insertion. It must
804 be at least 7 for the samplesort implementation to work. Binary
805 insertion does fewer compares, but can suffer O(N**2) data movement.
806 The more expensive compares, the larger MINSIZE should be. */
807#define MINSIZE 100
808
809/* MINPARTITIONSIZE is the smallest array slice samplesort will bother to
810 partition; smaller slices are passed to binarysort. It must be at
811 least 2, and no larger than MINSIZE. Setting it higher reduces the #
812 of compares slowly, but increases the amount of data movement quickly.
813 The value here was chosen assuming a compare costs ~25x more than
814 swapping a pair of memory-resident pointers -- but under that assumption,
815 changing the value by a few dozen more or less has aggregate effect
816 under 1%. So the value is crucial, but not touchy <wink>. */
817#define MINPARTITIONSIZE 40
818
819/* MAXMERGE is the largest number of elements we'll always merge into
820 a known-to-be sorted chunk via binary insertion, regardless of the
821 size of that chunk. Given a chunk of N sorted elements, and a group
822 of K unknowns, the largest K for which it's better to do insertion
823 (than a full-blown sort) is a complicated function of N and K mostly
824 involving the expected number of compares and data moves under each
825 approach, and the relative cost of those operations on a specific
826 architecure. The fixed value here is conservative, and should be a
827 clear win regardless of architecture or N. */
828#define MAXMERGE 15
Guido van Rossum3f236de1996-12-10 23:55:39 +0000829
Guido van Rossum3f236de1996-12-10 23:55:39 +0000830/* STACKSIZE is the size of our work stack. A rough estimate is that
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000831 this allows us to sort arrays of size N where
832 N / ln(N) = MINPARTITIONSIZE * 2**STACKSIZE, so 60 is more than enough
833 for arrays of size 2**64. Because we push the biggest partition
834 first, the worst case occurs when all subarrays are always partitioned
835 exactly in two. */
836#define STACKSIZE 60
Guido van Rossum3f236de1996-12-10 23:55:39 +0000837
Tim Petersa8c974c2002-07-19 03:30:57 +0000838/* Compare X to Y via islt(). Goto "fail" if the comparison raises an
839 error. Else "k" is set to true iff X<Y, and an "if (k)" block is
840 started. It makes more sense in context <wink>. X and Y are PyObject*s.
841*/
842#define IFLT(X, Y) if ((k = islt(X, Y, compare)) < 0) goto fail; \
843 if (k)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000844
845/* binarysort is the best method for sorting small arrays: it does
846 few compares, but can do data movement quadratic in the number of
847 elements.
Guido van Rossum42812581998-06-17 14:15:44 +0000848 [lo, hi) is a contiguous slice of a list, and is sorted via
Tim Petersa8c974c2002-07-19 03:30:57 +0000849 binary insertion. This sort is stable.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000850 On entry, must have lo <= start <= hi, and that [lo, start) is already
851 sorted (pass start == lo if you don't know!).
Tim Petersa8c974c2002-07-19 03:30:57 +0000852 If islt() complains return -1, else 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000853 Even in case of error, the output slice will be some permutation of
854 the input (nothing is lost or duplicated).
855*/
Guido van Rossum3f236de1996-12-10 23:55:39 +0000856
857static int
Fred Drakea2f55112000-07-09 15:16:51 +0000858binarysort(PyObject **lo, PyObject **hi, PyObject **start, PyObject *compare)
859 /* compare -- comparison function object, or NULL for default */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000860{
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000861 register int k;
862 register PyObject **l, **p, **r;
863 register PyObject *pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000864
Tim Petersa8c974c2002-07-19 03:30:57 +0000865 assert(lo <= start && start <= hi);
866 /* assert [lo, start) is sorted */
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000867 if (lo == start)
868 ++start;
869 for (; start < hi; ++start) {
870 /* set l to where *start belongs */
871 l = lo;
872 r = start;
Guido van Rossuma119c0d1998-05-29 17:56:32 +0000873 pivot = *r;
Tim Peters0fe977c2002-07-19 06:12:32 +0000874 /* Invariants:
875 * pivot >= all in [lo, l).
876 * pivot < all in [r, start).
877 * The second is vacuously true at the start.
878 */
879 assert(l < r);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000880 do {
881 p = l + ((r - l) >> 1);
Tim Petersa8c974c2002-07-19 03:30:57 +0000882 IFLT(pivot, *p)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000883 r = p;
884 else
Tim Peters0fe977c2002-07-19 06:12:32 +0000885 l = p+1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000886 } while (l < r);
Tim Peters0fe977c2002-07-19 06:12:32 +0000887 assert(l == r);
888 /* The invariants still hold, so pivot >= all in [lo, l) and
889 pivot < all in [l, start), so pivot belongs at l. Note
890 that if there are elements equal to pivot, l points to the
891 first slot after them -- that's why this sort is stable.
892 Slide over to make room.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000893 Caution: using memmove is much slower under MSVC 5;
894 we're not usually moving many slots. */
895 for (p = start; p > l; --p)
896 *p = *(p-1);
897 *l = pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000898 }
Guido van Rossum3f236de1996-12-10 23:55:39 +0000899 return 0;
Guido van Rossuma119c0d1998-05-29 17:56:32 +0000900
901 fail:
902 return -1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000903}
904
905/* samplesortslice is the sorting workhorse.
Guido van Rossum42812581998-06-17 14:15:44 +0000906 [lo, hi) is a contiguous slice of a list, to be sorted in place.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000907 On entry, must have lo <= hi,
Tim Petersa8c974c2002-07-19 03:30:57 +0000908 If islt() complains return -1, else 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000909 Even in case of error, the output slice will be some permutation of
910 the input (nothing is lost or duplicated).
911
912 samplesort is basically quicksort on steroids: a power of 2 close
913 to n/ln(n) is computed, and that many elements (less 1) are picked at
914 random from the array and sorted. These 2**k - 1 elements are then
915 used as preselected pivots for an equal number of quicksort
916 partitioning steps, partitioning the slice into 2**k chunks each of
917 size about ln(n). These small final chunks are then usually handled
918 by binarysort. Note that when k=1, this is roughly the same as an
919 ordinary quicksort using a random pivot, and when k=2 this is roughly
920 a median-of-3 quicksort. From that view, using k ~= lg(n/ln(n)) makes
921 this a "median of n/ln(n)" quicksort. You can also view it as a kind
922 of bucket sort, where 2**k-1 bucket boundaries are picked dynamically.
923
924 The large number of samples makes a quadratic-time case almost
925 impossible, and asymptotically drives the average-case number of
926 compares from quicksort's 2 N ln N (or 12/7 N ln N for the median-of-
927 3 variant) down to N lg N.
928
929 We also play lots of low-level tricks to cut the number of compares.
Tim Peters3b01a122002-07-19 02:35:45 +0000930
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000931 Very obscure: To avoid using extra memory, the PPs are stored in the
932 array and shuffled around as partitioning proceeds. At the start of a
933 partitioning step, we'll have 2**m-1 (for some m) PPs in sorted order,
934 adjacent (either on the left or the right!) to a chunk of X elements
935 that are to be partitioned: P X or X P. In either case we need to
936 shuffle things *in place* so that the 2**(m-1) smaller PPs are on the
937 left, followed by the PP to be used for this step (that's the middle
938 of the PPs), followed by X, followed by the 2**(m-1) larger PPs:
939 P X or X P -> Psmall pivot X Plarge
940 and the order of the PPs must not be altered. It can take a while
941 to realize this isn't trivial! It can take even longer <wink> to
942 understand why the simple code below works, using only 2**(m-1) swaps.
943 The key is that the order of the X elements isn't necessarily
944 preserved: X can end up as some cyclic permutation of its original
945 order. That's OK, because X is unsorted anyway. If the order of X
946 had to be preserved too, the simplest method I know of using O(1)
947 scratch storage requires len(X) + 2**(m-1) swaps, spread over 2 passes.
948 Since len(X) is typically several times larger than 2**(m-1), that
949 would slow things down.
950*/
951
952struct SamplesortStackNode {
953 /* Represents a slice of the array, from (& including) lo up
954 to (but excluding) hi. "extra" additional & adjacent elements
955 are pre-selected pivots (PPs), spanning [lo-extra, lo) if
956 extra > 0, or [hi, hi-extra) if extra < 0. The PPs are
957 already sorted, but nothing is known about the other elements
958 in [lo, hi). |extra| is always one less than a power of 2.
959 When extra is 0, we're out of PPs, and the slice must be
960 sorted by some other means. */
961 PyObject **lo;
962 PyObject **hi;
963 int extra;
964};
965
966/* 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 +0000967 N / ln(N) as possible. So k ~= lg(N / ln(N)). Calling libm routines
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000968 is undesirable, so cutoff values are canned in the "cutoff" table
969 below: cutoff[i] is the smallest N such that k == CUTOFFBASE + i. */
970#define CUTOFFBASE 4
Guido van Rossum3aa23fd1999-01-14 19:01:53 +0000971static long cutoff[] = {
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000972 43, /* smallest N such that k == 4 */
973 106, /* etc */
974 250,
975 576,
976 1298,
977 2885,
978 6339,
979 13805,
980 29843,
981 64116,
982 137030,
983 291554,
984 617916,
985 1305130,
986 2748295,
987 5771662,
988 12091672,
989 25276798,
990 52734615,
991 109820537,
992 228324027,
993 473977813,
994 982548444, /* smallest N such that k == 26 */
995 2034159050 /* largest N that fits in signed 32-bit; k == 27 */
996};
997
998static int
Fred Drakea2f55112000-07-09 15:16:51 +0000999samplesortslice(PyObject **lo, PyObject **hi, PyObject *compare)
1000 /* compare -- comparison function object, or NULL for default */
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001001{
1002 register PyObject **l, **r;
1003 register PyObject *tmp, *pivot;
1004 register int k;
1005 int n, extra, top, extraOnRight;
1006 struct SamplesortStackNode stack[STACKSIZE];
1007
Tim Peters330f9e92002-07-19 07:05:44 +00001008 assert(lo <= hi);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001009 n = hi - lo;
Tim Peters330f9e92002-07-19 07:05:44 +00001010 if (n < MINSIZE)
1011 return binarysort(lo, hi, lo, compare);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001012
1013 /* ----------------------------------------------------------
1014 * Normal case setup: a large array without obvious pattern.
1015 * --------------------------------------------------------*/
1016
1017 /* extra := a power of 2 ~= n/ln(n), less 1.
1018 First find the smallest extra s.t. n < cutoff[extra] */
1019 for (extra = 0;
1020 extra < sizeof(cutoff) / sizeof(cutoff[0]);
1021 ++extra) {
1022 if (n < cutoff[extra])
1023 break;
1024 /* note that if we fall out of the loop, the value of
1025 extra still makes *sense*, but may be smaller than
1026 we would like (but the array has more than ~= 2**31
Tim Peters3b01a122002-07-19 02:35:45 +00001027 elements in this case!) */
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001028 }
1029 /* Now k == extra - 1 + CUTOFFBASE. The smallest value k can
1030 have is CUTOFFBASE-1, so
1031 assert MINSIZE >= 2**(CUTOFFBASE-1) - 1 */
1032 extra = (1 << (extra - 1 + CUTOFFBASE)) - 1;
1033 /* assert extra > 0 and n >= extra */
1034
1035 /* Swap that many values to the start of the array. The
1036 selection of elements is pseudo-random, but the same on
1037 every run (this is intentional! timing algorithm changes is
1038 a pain if timing varies across runs). */
1039 {
1040 unsigned int seed = n / extra; /* arbitrary */
1041 unsigned int i;
1042 for (i = 0; i < (unsigned)extra; ++i) {
1043 /* j := random int in [i, n) */
1044 unsigned int j;
1045 seed = seed * 69069 + 7;
1046 j = i + seed % (n - i);
1047 tmp = lo[i]; lo[i] = lo[j]; lo[j] = tmp;
1048 }
1049 }
1050
1051 /* Recursively sort the preselected pivots. */
Guido van Rossum42812581998-06-17 14:15:44 +00001052 if (samplesortslice(lo, lo + extra, compare) < 0)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001053 goto fail;
1054
1055 top = 0; /* index of available stack slot */
1056 lo += extra; /* point to first unknown */
1057 extraOnRight = 0; /* the PPs are at the left end */
1058
1059 /* ----------------------------------------------------------
1060 * Partition [lo, hi), and repeat until out of work.
1061 * --------------------------------------------------------*/
1062 for (;;) {
Tim Peters330f9e92002-07-19 07:05:44 +00001063 assert(lo <= hi);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001064 n = hi - lo;
1065
1066 /* We may not want, or may not be able, to partition:
1067 If n is small, it's quicker to insert.
1068 If extra is 0, we're out of pivots, and *must* use
1069 another method.
1070 */
1071 if (n < MINPARTITIONSIZE || extra == 0) {
1072 if (n >= MINSIZE) {
Tim Peters330f9e92002-07-19 07:05:44 +00001073 assert(extra == 0);
1074 /* This is rare, since the average size
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001075 of a final block is only about
1076 ln(original n). */
Guido van Rossum42812581998-06-17 14:15:44 +00001077 if (samplesortslice(lo, hi, compare) < 0)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001078 goto fail;
1079 }
1080 else {
1081 /* Binary insertion should be quicker,
1082 and we can take advantage of the PPs
1083 already being sorted. */
1084 if (extraOnRight && extra) {
1085 /* swap the PPs to the left end */
1086 k = extra;
1087 do {
1088 tmp = *lo;
1089 *lo = *hi;
1090 *hi = tmp;
1091 ++lo; ++hi;
1092 } while (--k);
1093 }
1094 if (binarysort(lo - extra, hi, lo,
Guido van Rossum42812581998-06-17 14:15:44 +00001095 compare) < 0)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001096 goto fail;
1097 }
1098
1099 /* Find another slice to work on. */
1100 if (--top < 0)
1101 break; /* no more -- done! */
1102 lo = stack[top].lo;
1103 hi = stack[top].hi;
1104 extra = stack[top].extra;
1105 extraOnRight = 0;
1106 if (extra < 0) {
1107 extraOnRight = 1;
1108 extra = -extra;
1109 }
1110 continue;
1111 }
1112
1113 /* Pretend the PPs are indexed 0, 1, ..., extra-1.
1114 Then our preselected pivot is at (extra-1)/2, and we
1115 want to move the PPs before that to the left end of
1116 the slice, and the PPs after that to the right end.
1117 The following section changes extra, lo, hi, and the
1118 slice such that:
1119 [lo-extra, lo) contains the smaller PPs.
1120 *lo == our PP.
1121 (lo, hi) contains the unknown elements.
1122 [hi, hi+extra) contains the larger PPs.
1123 */
Tim Peters3b01a122002-07-19 02:35:45 +00001124 k = extra >>= 1; /* num PPs to move */
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001125 if (extraOnRight) {
1126 /* Swap the smaller PPs to the left end.
1127 Note that this loop actually moves k+1 items:
1128 the last is our PP */
1129 do {
1130 tmp = *lo; *lo = *hi; *hi = tmp;
1131 ++lo; ++hi;
1132 } while (k--);
1133 }
1134 else {
1135 /* Swap the larger PPs to the right end. */
1136 while (k--) {
1137 --lo; --hi;
1138 tmp = *lo; *lo = *hi; *hi = tmp;
1139 }
1140 }
1141 --lo; /* *lo is now our PP */
1142 pivot = *lo;
1143
1144 /* Now an almost-ordinary quicksort partition step.
1145 Note that most of the time is spent here!
1146 Only odd thing is that we partition into < and >=,
1147 instead of the usual <= and >=. This helps when
1148 there are lots of duplicates of different values,
1149 because it eventually tends to make subfiles
1150 "pure" (all duplicates), and we special-case for
1151 duplicates later. */
1152 l = lo + 1;
1153 r = hi - 1;
Tim Peters330f9e92002-07-19 07:05:44 +00001154 assert(lo < l && l < r && r < hi);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001155
1156 do {
1157 /* slide l right, looking for key >= pivot */
1158 do {
Tim Petersa8c974c2002-07-19 03:30:57 +00001159 IFLT(*l, pivot)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001160 ++l;
1161 else
1162 break;
1163 } while (l < r);
1164
1165 /* slide r left, looking for key < pivot */
1166 while (l < r) {
Guido van Rossum42812581998-06-17 14:15:44 +00001167 register PyObject *rval = *r--;
Tim Petersa8c974c2002-07-19 03:30:57 +00001168 IFLT(rval, pivot) {
Guido van Rossum42812581998-06-17 14:15:44 +00001169 /* swap and advance */
1170 r[1] = *l;
1171 *l++ = rval;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001172 break;
Guido van Rossum42812581998-06-17 14:15:44 +00001173 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001174 }
1175
1176 } while (l < r);
1177
Tim Peters330f9e92002-07-19 07:05:44 +00001178 assert(lo < r && r <= l && l < hi);
1179 /* everything to the left of l is < pivot, and
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001180 everything to the right of r is >= pivot */
1181
1182 if (l == r) {
Tim Petersa8c974c2002-07-19 03:30:57 +00001183 IFLT(*r, pivot)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001184 ++l;
1185 else
1186 --r;
1187 }
Tim Peters330f9e92002-07-19 07:05:44 +00001188 assert(lo <= r && r+1 == l && l <= hi);
1189 /* assert r == lo or a[r] < pivot */
1190 assert(*lo == pivot);
1191 /* assert l == hi or a[l] >= pivot */
1192 /* Swap the pivot into "the middle", so we can henceforth
1193 ignore it. */
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001194 *lo = *r;
1195 *r = pivot;
1196
1197 /* The following is true now, & will be preserved:
1198 All in [lo,r) are < pivot
1199 All in [r,l) == pivot (& so can be ignored)
1200 All in [l,hi) are >= pivot */
1201
1202 /* Check for duplicates of the pivot. One compare is
1203 wasted if there are no duplicates, but can win big
1204 when there are.
1205 Tricky: we're sticking to "<" compares, so deduce
1206 equality indirectly. We know pivot <= *l, so they're
1207 equal iff not pivot < *l.
1208 */
1209 while (l < hi) {
1210 /* pivot <= *l known */
Tim Petersa8c974c2002-07-19 03:30:57 +00001211 IFLT(pivot, *l)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001212 break;
1213 else
1214 /* <= and not < implies == */
1215 ++l;
1216 }
1217
Tim Peters330f9e92002-07-19 07:05:44 +00001218 assert(lo <= r && r < l && l <= hi);
1219 /* Partitions are [lo, r) and [l, hi)
1220 :ush fattest first; remember we still have extra PPs
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001221 to the left of the left chunk and to the right of
1222 the right chunk! */
Tim Peters330f9e92002-07-19 07:05:44 +00001223 assert(top < STACKSIZE);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001224 if (r - lo <= hi - l) {
1225 /* second is bigger */
1226 stack[top].lo = l;
1227 stack[top].hi = hi;
1228 stack[top].extra = -extra;
1229 hi = r;
1230 extraOnRight = 0;
1231 }
1232 else {
1233 /* first is bigger */
1234 stack[top].lo = lo;
1235 stack[top].hi = r;
1236 stack[top].extra = extra;
1237 lo = l;
1238 extraOnRight = 1;
1239 }
1240 ++top;
1241
1242 } /* end of partitioning loop */
1243
1244 return 0;
1245
1246 fail:
1247 return -1;
1248}
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001249
Jeremy Hylton938ace62002-07-17 16:30:39 +00001250static PyTypeObject immutable_list_type;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001251
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001252static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00001253listsort(PyListObject *self, PyObject *args)
Guido van Rossum3f236de1996-12-10 23:55:39 +00001254{
Tim Peters330f9e92002-07-19 07:05:44 +00001255 int k;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001256 PyObject *compare = NULL;
Tim Peters330f9e92002-07-19 07:05:44 +00001257 PyObject **hi, **p;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001258 PyTypeObject *savetype;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001259
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001260 if (args != NULL) {
Guido van Rossumc00a9382000-02-24 21:48:29 +00001261 if (!PyArg_ParseTuple(args, "|O:sort", &compare))
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001262 return NULL;
1263 }
Tim Peters330f9e92002-07-19 07:05:44 +00001264
Tim Peters6d6c1a32001-08-02 04:15:00 +00001265 savetype = self->ob_type;
Tim Peters330f9e92002-07-19 07:05:44 +00001266 if (self->ob_size < 2) {
1267 k = 0;
1268 goto done;
1269 }
1270
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001271 self->ob_type = &immutable_list_type;
Tim Peters330f9e92002-07-19 07:05:44 +00001272 hi = self->ob_item + self->ob_size;
1273
1274 /* Set p to the largest value such that [lo, p) is sorted.
1275 This catches the already-sorted case, the all-the-same
1276 case, and the appended-a-few-elements-to-a-sorted-list case.
1277 If the array is unsorted, we're very likely to get out of
1278 the loop fast, so the test is cheap if it doesn't pay off.
1279 */
1280 for (p = self->ob_item + 1; p < hi; ++p) {
1281 IFLT(*p, *(p-1))
1282 break;
1283 }
1284 /* [lo, p) is sorted, [p, hi) unknown. Get out cheap if there are
1285 few unknowns, or few elements in total. */
1286 if (hi - p <= MAXMERGE || self->ob_size < MINSIZE) {
1287 k = binarysort(self->ob_item, hi, p, compare);
1288 goto done;
1289 }
1290
1291 /* Check for the array already being reverse-sorted, or that with
1292 a few elements tacked on to the end. */
1293 for (p = self->ob_item + 1; p < hi; ++p) {
1294 IFLT(*(p-1), *p)
1295 break;
1296 }
1297 /* [lo, p) is reverse-sorted, [p, hi) unknown. */
1298 if (hi - p <= MAXMERGE) {
1299 /* Reverse the reversed prefix, then insert the tail */
1300 reverse_slice(self->ob_item, p);
1301 k = binarysort(self->ob_item, hi, p, compare);
1302 goto done;
1303 }
1304
1305 /* A large array without obvious pattern. */
1306 k = samplesortslice(self->ob_item, hi, compare);
1307
1308done: /* The IFLT macro requires a label named "fail". */;
1309fail:
1310 self->ob_type = savetype;
1311 if (k >= 0) {
1312 Py_INCREF(Py_None);
1313 return Py_None;
1314 }
1315 else
Guido van Rossum3f236de1996-12-10 23:55:39 +00001316 return NULL;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001317}
1318
Tim Peters330f9e92002-07-19 07:05:44 +00001319#undef IFLT
1320
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001321int
Fred Drakea2f55112000-07-09 15:16:51 +00001322PyList_Sort(PyObject *v)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001323{
1324 if (v == NULL || !PyList_Check(v)) {
1325 PyErr_BadInternalCall();
1326 return -1;
1327 }
1328 v = listsort((PyListObject *)v, (PyObject *)NULL);
1329 if (v == NULL)
1330 return -1;
1331 Py_DECREF(v);
1332 return 0;
1333}
1334
Guido van Rossumb86c5492001-02-12 22:06:02 +00001335static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001336listreverse(PyListObject *self)
Guido van Rossumb86c5492001-02-12 22:06:02 +00001337{
Tim Peters326b4482002-07-19 04:04:16 +00001338 if (self->ob_size > 1)
1339 reverse_slice(self->ob_item, self->ob_item + self->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001340 Py_INCREF(Py_None);
1341 return Py_None;
Guido van Rossumed98d481991-03-06 13:07:53 +00001342}
1343
Guido van Rossum84c76f51990-10-30 13:32:20 +00001344int
Fred Drakea2f55112000-07-09 15:16:51 +00001345PyList_Reverse(PyObject *v)
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00001346{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001347 if (v == NULL || !PyList_Check(v)) {
1348 PyErr_BadInternalCall();
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00001349 return -1;
1350 }
Tim Peters8e2e7ca2002-07-19 02:33:08 +00001351 listreverse((PyListObject *)v);
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00001352 return 0;
1353}
1354
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001355PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00001356PyList_AsTuple(PyObject *v)
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00001357{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001358 PyObject *w;
1359 PyObject **p;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00001360 int n;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001361 if (v == NULL || !PyList_Check(v)) {
1362 PyErr_BadInternalCall();
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00001363 return NULL;
1364 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001365 n = ((PyListObject *)v)->ob_size;
1366 w = PyTuple_New(n);
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00001367 if (w == NULL)
1368 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001369 p = ((PyTupleObject *)w)->ob_item;
Thomas Wouters334fb892000-07-25 12:56:38 +00001370 memcpy((void *)p,
1371 (void *)((PyListObject *)v)->ob_item,
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001372 n*sizeof(PyObject *));
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00001373 while (--n >= 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001374 Py_INCREF(*p);
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00001375 p++;
1376 }
1377 return w;
1378}
1379
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001380static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001381listindex(PyListObject *self, PyObject *v)
Guido van Rossumed98d481991-03-06 13:07:53 +00001382{
1383 int i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001384
Guido van Rossumed98d481991-03-06 13:07:53 +00001385 for (i = 0; i < self->ob_size; i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001386 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
1387 if (cmp > 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001388 return PyInt_FromLong((long)i);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001389 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00001390 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00001391 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001392 PyErr_SetString(PyExc_ValueError, "list.index(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00001393 return NULL;
1394}
1395
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001396static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001397listcount(PyListObject *self, PyObject *v)
Guido van Rossume6f7d181991-10-20 20:20:40 +00001398{
1399 int count = 0;
1400 int i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001401
Guido van Rossume6f7d181991-10-20 20:20:40 +00001402 for (i = 0; i < self->ob_size; i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001403 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
1404 if (cmp > 0)
Guido van Rossume6f7d181991-10-20 20:20:40 +00001405 count++;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001406 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00001407 return NULL;
Guido van Rossume6f7d181991-10-20 20:20:40 +00001408 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001409 return PyInt_FromLong((long)count);
Guido van Rossume6f7d181991-10-20 20:20:40 +00001410}
1411
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001412static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001413listremove(PyListObject *self, PyObject *v)
Guido van Rossumed98d481991-03-06 13:07:53 +00001414{
1415 int i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001416
Guido van Rossumed98d481991-03-06 13:07:53 +00001417 for (i = 0; i < self->ob_size; i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001418 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
1419 if (cmp > 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001420 if (list_ass_slice(self, i, i+1,
1421 (PyObject *)NULL) != 0)
Guido van Rossumed98d481991-03-06 13:07:53 +00001422 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001423 Py_INCREF(Py_None);
1424 return Py_None;
Guido van Rossumed98d481991-03-06 13:07:53 +00001425 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001426 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00001427 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00001428 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001429 PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00001430 return NULL;
1431}
1432
Jeremy Hylton8caad492000-06-23 14:18:11 +00001433static int
1434list_traverse(PyListObject *o, visitproc visit, void *arg)
1435{
1436 int i, err;
1437 PyObject *x;
1438
1439 for (i = o->ob_size; --i >= 0; ) {
1440 x = o->ob_item[i];
1441 if (x != NULL) {
1442 err = visit(x, arg);
1443 if (err)
1444 return err;
1445 }
1446 }
1447 return 0;
1448}
1449
1450static int
1451list_clear(PyListObject *lp)
1452{
1453 (void) PyList_SetSlice((PyObject *)lp, 0, lp->ob_size, 0);
1454 return 0;
1455}
1456
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001457static PyObject *
1458list_richcompare(PyObject *v, PyObject *w, int op)
1459{
1460 PyListObject *vl, *wl;
1461 int i;
1462
1463 if (!PyList_Check(v) || !PyList_Check(w)) {
1464 Py_INCREF(Py_NotImplemented);
1465 return Py_NotImplemented;
1466 }
1467
1468 vl = (PyListObject *)v;
1469 wl = (PyListObject *)w;
1470
1471 if (vl->ob_size != wl->ob_size && (op == Py_EQ || op == Py_NE)) {
1472 /* Shortcut: if the lengths differ, the lists differ */
1473 PyObject *res;
1474 if (op == Py_EQ)
1475 res = Py_False;
1476 else
1477 res = Py_True;
1478 Py_INCREF(res);
1479 return res;
1480 }
1481
1482 /* Search for the first index where items are different */
1483 for (i = 0; i < vl->ob_size && i < wl->ob_size; i++) {
1484 int k = PyObject_RichCompareBool(vl->ob_item[i],
1485 wl->ob_item[i], Py_EQ);
1486 if (k < 0)
1487 return NULL;
1488 if (!k)
1489 break;
1490 }
1491
1492 if (i >= vl->ob_size || i >= wl->ob_size) {
1493 /* No more items to compare -- compare sizes */
1494 int vs = vl->ob_size;
1495 int ws = wl->ob_size;
1496 int cmp;
1497 PyObject *res;
1498 switch (op) {
1499 case Py_LT: cmp = vs < ws; break;
Tim Peters6ee42342001-07-06 17:45:43 +00001500 case Py_LE: cmp = vs <= ws; break;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001501 case Py_EQ: cmp = vs == ws; break;
1502 case Py_NE: cmp = vs != ws; break;
1503 case Py_GT: cmp = vs > ws; break;
1504 case Py_GE: cmp = vs >= ws; break;
1505 default: return NULL; /* cannot happen */
1506 }
1507 if (cmp)
1508 res = Py_True;
1509 else
1510 res = Py_False;
1511 Py_INCREF(res);
1512 return res;
1513 }
1514
1515 /* We have an item that differs -- shortcuts for EQ/NE */
1516 if (op == Py_EQ) {
1517 Py_INCREF(Py_False);
1518 return Py_False;
1519 }
1520 if (op == Py_NE) {
1521 Py_INCREF(Py_True);
1522 return Py_True;
1523 }
1524
1525 /* Compare the final item again using the proper operator */
1526 return PyObject_RichCompare(vl->ob_item[i], wl->ob_item[i], op);
1527}
1528
Tim Peters6d6c1a32001-08-02 04:15:00 +00001529/* Adapted from newer code by Tim */
1530static int
1531list_fill(PyListObject *result, PyObject *v)
1532{
1533 PyObject *it; /* iter(v) */
1534 int n; /* guess for result list size */
1535 int i;
1536
1537 n = result->ob_size;
1538
1539 /* Special-case list(a_list), for speed. */
1540 if (PyList_Check(v)) {
1541 if (v == (PyObject *)result)
1542 return 0; /* source is destination, we're done */
1543 return list_ass_slice(result, 0, n, v);
1544 }
1545
1546 /* Empty previous contents */
1547 if (n != 0) {
1548 if (list_ass_slice(result, 0, n, (PyObject *)NULL) != 0)
1549 return -1;
1550 }
1551
1552 /* Get iterator. There may be some low-level efficiency to be gained
1553 * by caching the tp_iternext slot instead of using PyIter_Next()
1554 * later, but premature optimization is the root etc.
1555 */
1556 it = PyObject_GetIter(v);
1557 if (it == NULL)
1558 return -1;
1559
1560 /* Guess a result list size. */
1561 n = -1; /* unknown */
1562 if (PySequence_Check(v) &&
1563 v->ob_type->tp_as_sequence->sq_length) {
1564 n = PySequence_Size(v);
1565 if (n < 0)
1566 PyErr_Clear();
1567 }
1568 if (n < 0)
1569 n = 8; /* arbitrary */
1570 NRESIZE(result->ob_item, PyObject*, n);
Neal Norwitzd4e5be52002-05-22 23:19:17 +00001571 if (result->ob_item == NULL) {
1572 PyErr_NoMemory();
Tim Peters6d6c1a32001-08-02 04:15:00 +00001573 goto error;
Neal Norwitzd4e5be52002-05-22 23:19:17 +00001574 }
Neal Norwitz35fc7602002-06-13 21:11:11 +00001575 memset(result->ob_item, 0, sizeof(*result->ob_item) * n);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001576 result->ob_size = n;
1577
1578 /* Run iterator to exhaustion. */
1579 for (i = 0; ; i++) {
1580 PyObject *item = PyIter_Next(it);
1581 if (item == NULL) {
1582 if (PyErr_Occurred())
1583 goto error;
1584 break;
1585 }
1586 if (i < n)
1587 PyList_SET_ITEM(result, i, item); /* steals ref */
1588 else {
1589 int status = ins1(result, result->ob_size, item);
1590 Py_DECREF(item); /* append creates a new ref */
1591 if (status < 0)
1592 goto error;
1593 }
1594 }
1595
1596 /* Cut back result list if initial guess was too large. */
1597 if (i < n && result != NULL) {
1598 if (list_ass_slice(result, i, n, (PyObject *)NULL) != 0)
1599 goto error;
1600 }
1601 Py_DECREF(it);
1602 return 0;
1603
1604 error:
1605 Py_DECREF(it);
1606 return -1;
1607}
1608
1609static int
1610list_init(PyListObject *self, PyObject *args, PyObject *kw)
1611{
1612 PyObject *arg = NULL;
1613 static char *kwlist[] = {"sequence", 0};
1614
1615 if (!PyArg_ParseTupleAndKeywords(args, kw, "|O:list", kwlist, &arg))
1616 return -1;
1617 if (arg != NULL)
1618 return list_fill(self, arg);
1619 if (self->ob_size > 0)
1620 return list_ass_slice(self, 0, self->ob_size, (PyObject*)NULL);
1621 return 0;
1622}
1623
Guido van Rossumdbb53d92001-12-03 16:32:18 +00001624static long
1625list_nohash(PyObject *self)
1626{
1627 PyErr_SetString(PyExc_TypeError, "list objects are unhashable");
1628 return -1;
1629}
1630
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001631PyDoc_STRVAR(append_doc,
1632"L.append(object) -- append object to end");
1633PyDoc_STRVAR(extend_doc,
1634"L.extend(list) -- extend list by appending list elements");
1635PyDoc_STRVAR(insert_doc,
1636"L.insert(index, object) -- insert object before index");
1637PyDoc_STRVAR(pop_doc,
1638"L.pop([index]) -> item -- remove and return item at index (default last)");
1639PyDoc_STRVAR(remove_doc,
1640"L.remove(value) -- remove first occurrence of value");
1641PyDoc_STRVAR(index_doc,
1642"L.index(value) -> integer -- return index of first occurrence of value");
1643PyDoc_STRVAR(count_doc,
1644"L.count(value) -> integer -- return number of occurrences of value");
1645PyDoc_STRVAR(reverse_doc,
1646"L.reverse() -- reverse *IN PLACE*");
1647PyDoc_STRVAR(sort_doc,
1648"L.sort([cmpfunc]) -- sort *IN PLACE*; if given, cmpfunc(x, y) -> -1, 0, 1");
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +00001649
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001650static PyMethodDef list_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001651 {"append", (PyCFunction)listappend, METH_O, append_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001652 {"insert", (PyCFunction)listinsert, METH_VARARGS, insert_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001653 {"extend", (PyCFunction)listextend, METH_O, extend_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001654 {"pop", (PyCFunction)listpop, METH_VARARGS, pop_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001655 {"remove", (PyCFunction)listremove, METH_O, remove_doc},
1656 {"index", (PyCFunction)listindex, METH_O, index_doc},
1657 {"count", (PyCFunction)listcount, METH_O, count_doc},
1658 {"reverse", (PyCFunction)listreverse, METH_NOARGS, reverse_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001659 {"sort", (PyCFunction)listsort, METH_VARARGS, sort_doc},
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001660 {NULL, NULL} /* sentinel */
1661};
1662
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001663static PySequenceMethods list_as_sequence = {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001664 (inquiry)list_length, /* sq_length */
1665 (binaryfunc)list_concat, /* sq_concat */
1666 (intargfunc)list_repeat, /* sq_repeat */
1667 (intargfunc)list_item, /* sq_item */
1668 (intintargfunc)list_slice, /* sq_slice */
1669 (intobjargproc)list_ass_item, /* sq_ass_item */
1670 (intintobjargproc)list_ass_slice, /* sq_ass_slice */
1671 (objobjproc)list_contains, /* sq_contains */
1672 (binaryfunc)list_inplace_concat, /* sq_inplace_concat */
1673 (intargfunc)list_inplace_repeat, /* sq_inplace_repeat */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001674};
1675
Neal Norwitz2c2e8272002-06-14 02:04:18 +00001676PyDoc_STRVAR(list_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001677"list() -> new list\n"
Neal Norwitz2c2e8272002-06-14 02:04:18 +00001678"list(sequence) -> new list initialized from sequence's items");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001679
Jeremy Hyltona4b4c3b2002-07-13 03:51:17 +00001680static PyObject *list_iter(PyObject *seq);
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00001681
Jeremy Hyltona4b4c3b2002-07-13 03:51:17 +00001682static PyObject *
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00001683list_subscript(PyListObject* self, PyObject* item)
1684{
1685 if (PyInt_Check(item)) {
1686 long i = PyInt_AS_LONG(item);
1687 if (i < 0)
1688 i += PyList_GET_SIZE(self);
1689 return list_item(self, i);
1690 }
1691 else if (PyLong_Check(item)) {
1692 long i = PyLong_AsLong(item);
1693 if (i == -1 && PyErr_Occurred())
1694 return NULL;
1695 if (i < 0)
1696 i += PyList_GET_SIZE(self);
1697 return list_item(self, i);
1698 }
1699 else if (PySlice_Check(item)) {
1700 int start, stop, step, slicelength, cur, i;
1701 PyObject* result;
1702 PyObject* it;
1703
1704 if (PySlice_GetIndicesEx((PySliceObject*)item, self->ob_size,
1705 &start, &stop, &step, &slicelength) < 0) {
1706 return NULL;
1707 }
1708
1709 if (slicelength <= 0) {
1710 return PyList_New(0);
1711 }
1712 else {
1713 result = PyList_New(slicelength);
1714 if (!result) return NULL;
1715
Tim Peters3b01a122002-07-19 02:35:45 +00001716 for (cur = start, i = 0; i < slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00001717 cur += step, i++) {
1718 it = PyList_GET_ITEM(self, cur);
1719 Py_INCREF(it);
1720 PyList_SET_ITEM(result, i, it);
1721 }
Tim Peters3b01a122002-07-19 02:35:45 +00001722
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00001723 return result;
1724 }
1725 }
1726 else {
1727 PyErr_SetString(PyExc_TypeError,
1728 "list indices must be integers");
1729 return NULL;
1730 }
1731}
1732
Tim Peters3b01a122002-07-19 02:35:45 +00001733static int
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00001734list_ass_subscript(PyListObject* self, PyObject* item, PyObject* value)
1735{
1736 if (PyInt_Check(item)) {
1737 long i = PyInt_AS_LONG(item);
1738 if (i < 0)
1739 i += PyList_GET_SIZE(self);
1740 return list_ass_item(self, i, value);
1741 }
1742 else if (PyLong_Check(item)) {
1743 long i = PyLong_AsLong(item);
1744 if (i == -1 && PyErr_Occurred())
1745 return -1;
1746 if (i < 0)
1747 i += PyList_GET_SIZE(self);
1748 return list_ass_item(self, i, value);
1749 }
1750 else if (PySlice_Check(item)) {
1751 int start, stop, step, slicelength;
1752
1753 if (PySlice_GetIndicesEx((PySliceObject*)item, self->ob_size,
1754 &start, &stop, &step, &slicelength) < 0) {
1755 return -1;
1756 }
1757
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00001758 /* treat L[slice(a,b)] = v _exactly_ like L[a:b] = v */
1759 if (step == 1 && ((PySliceObject*)item)->step == Py_None)
1760 return list_ass_slice(self, start, stop, value);
1761
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00001762 if (value == NULL) {
1763 /* delete slice */
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00001764 PyObject **garbage, **it;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00001765 int cur, i, j;
Tim Peters3b01a122002-07-19 02:35:45 +00001766
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00001767 if (slicelength <= 0)
1768 return 0;
1769
1770 if (step < 0) {
1771 stop = start + 1;
1772 start = stop + step*(slicelength - 1) - 1;
1773 step = -step;
1774 }
1775
1776 garbage = (PyObject**)
1777 PyMem_MALLOC(slicelength*sizeof(PyObject*));
Tim Peters3b01a122002-07-19 02:35:45 +00001778
1779 /* drawing pictures might help
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00001780 understand these for loops */
Guido van Rossum75a20b12002-06-11 12:22:28 +00001781 for (cur = start, i = 0;
1782 cur < stop;
1783 cur += step, i++)
1784 {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00001785 garbage[i] = PyList_GET_ITEM(self, cur);
1786
1787 for (j = 0; j < step; j++) {
Tim Peters3b01a122002-07-19 02:35:45 +00001788 PyList_SET_ITEM(self, cur + j - i,
Guido van Rossum75a20b12002-06-11 12:22:28 +00001789 PyList_GET_ITEM(self,
1790 cur + j + 1));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00001791 }
1792 }
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00001793 for (cur = start + slicelength*step + 1;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00001794 cur < self->ob_size; cur++) {
1795 PyList_SET_ITEM(self, cur - slicelength,
1796 PyList_GET_ITEM(self, cur));
1797 }
1798 self->ob_size -= slicelength;
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00001799 it = self->ob_item;
1800 NRESIZE(it, PyObject*, self->ob_size);
1801 self->ob_item = it;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00001802
1803 for (i = 0; i < slicelength; i++) {
1804 Py_DECREF(garbage[i]);
1805 }
1806 PyMem_FREE(garbage);
1807
1808 return 0;
1809 }
1810 else {
1811 /* assign slice */
1812 PyObject **garbage, *ins;
1813 int cur, i;
1814
1815 if (!PyList_Check(value)) {
1816 PyErr_Format(PyExc_TypeError,
1817 "must assign list (not \"%.200s\") to slice",
1818 value->ob_type->tp_name);
1819 return -1;
1820 }
1821
1822 if (PyList_GET_SIZE(value) != slicelength) {
1823 PyErr_Format(PyExc_ValueError,
1824 "attempt to assign list of size %d to extended slice of size %d",
1825 PyList_Size(value), slicelength);
1826 return -1;
1827 }
1828
1829 if (!slicelength)
1830 return 0;
1831
1832 /* protect against a[::-1] = a */
Tim Peters3b01a122002-07-19 02:35:45 +00001833 if (self == (PyListObject*)value) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00001834 value = list_slice((PyListObject*)value, 0,
1835 PyList_GET_SIZE(value));
Tim Peters3b01a122002-07-19 02:35:45 +00001836 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00001837 else {
1838 Py_INCREF(value);
1839 }
1840
1841 garbage = (PyObject**)
1842 PyMem_MALLOC(slicelength*sizeof(PyObject*));
Tim Peters3b01a122002-07-19 02:35:45 +00001843
1844 for (cur = start, i = 0; i < slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00001845 cur += step, i++) {
1846 garbage[i] = PyList_GET_ITEM(self, cur);
Tim Peters3b01a122002-07-19 02:35:45 +00001847
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00001848 ins = PyList_GET_ITEM(value, i);
1849 Py_INCREF(ins);
1850 PyList_SET_ITEM(self, cur, ins);
1851 }
1852
1853 for (i = 0; i < slicelength; i++) {
1854 Py_DECREF(garbage[i]);
1855 }
Tim Peters3b01a122002-07-19 02:35:45 +00001856
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00001857 PyMem_FREE(garbage);
1858 Py_DECREF(value);
Tim Peters3b01a122002-07-19 02:35:45 +00001859
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00001860 return 0;
1861 }
Tim Peters3b01a122002-07-19 02:35:45 +00001862 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00001863 else {
Tim Peters3b01a122002-07-19 02:35:45 +00001864 PyErr_SetString(PyExc_TypeError,
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00001865 "list indices must be integers");
1866 return -1;
1867 }
1868}
1869
1870static PyMappingMethods list_as_mapping = {
1871 (inquiry)list_length,
1872 (binaryfunc)list_subscript,
1873 (objobjargproc)list_ass_subscript
1874};
1875
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001876PyTypeObject PyList_Type = {
1877 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001878 0,
1879 "list",
Neil Schemenauere83c00e2001-08-29 23:54:21 +00001880 sizeof(PyListObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001881 0,
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001882 (destructor)list_dealloc, /* tp_dealloc */
1883 (printfunc)list_print, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001884 0, /* tp_getattr */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001885 0, /* tp_setattr */
1886 0, /* tp_compare */
1887 (reprfunc)list_repr, /* tp_repr */
1888 0, /* tp_as_number */
1889 &list_as_sequence, /* tp_as_sequence */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00001890 &list_as_mapping, /* tp_as_mapping */
Guido van Rossumdbb53d92001-12-03 16:32:18 +00001891 list_nohash, /* tp_hash */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001892 0, /* tp_call */
1893 0, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001894 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001895 0, /* tp_setattro */
1896 0, /* tp_as_buffer */
Neil Schemenauere83c00e2001-08-29 23:54:21 +00001897 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Tim Peters6d6c1a32001-08-02 04:15:00 +00001898 Py_TPFLAGS_BASETYPE, /* tp_flags */
1899 list_doc, /* tp_doc */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001900 (traverseproc)list_traverse, /* tp_traverse */
1901 (inquiry)list_clear, /* tp_clear */
1902 list_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001903 0, /* tp_weaklistoffset */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00001904 list_iter, /* tp_iter */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001905 0, /* tp_iternext */
1906 list_methods, /* tp_methods */
1907 0, /* tp_members */
1908 0, /* tp_getset */
1909 0, /* tp_base */
1910 0, /* tp_dict */
1911 0, /* tp_descr_get */
1912 0, /* tp_descr_set */
1913 0, /* tp_dictoffset */
1914 (initproc)list_init, /* tp_init */
1915 PyType_GenericAlloc, /* tp_alloc */
1916 PyType_GenericNew, /* tp_new */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00001917 PyObject_GC_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001918};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001919
1920
1921/* During a sort, we really can't have anyone modifying the list; it could
1922 cause core dumps. Thus, we substitute a dummy type that raises an
1923 explanatory exception when a modifying operation is used. Caveat:
1924 comparisons may behave differently; but I guess it's a bad idea anyway to
1925 compare a list that's being sorted... */
1926
1927static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00001928immutable_list_op(void)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001929{
1930 PyErr_SetString(PyExc_TypeError,
1931 "a list cannot be modified while it is being sorted");
1932 return NULL;
1933}
1934
1935static PyMethodDef immutable_list_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001936 {"append", (PyCFunction)immutable_list_op, METH_VARARGS},
1937 {"insert", (PyCFunction)immutable_list_op, METH_VARARGS},
Tim Peters52e07172001-08-30 06:15:32 +00001938 {"extend", (PyCFunction)immutable_list_op, METH_O},
1939 {"pop", (PyCFunction)immutable_list_op, METH_VARARGS},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001940 {"remove", (PyCFunction)immutable_list_op, METH_VARARGS},
1941 {"index", (PyCFunction)listindex, METH_O},
1942 {"count", (PyCFunction)listcount, METH_O},
1943 {"reverse", (PyCFunction)immutable_list_op, METH_VARARGS},
1944 {"sort", (PyCFunction)immutable_list_op, METH_VARARGS},
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001945 {NULL, NULL} /* sentinel */
1946};
1947
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001948static int
Fred Drakea2f55112000-07-09 15:16:51 +00001949immutable_list_ass(void)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001950{
1951 immutable_list_op();
1952 return -1;
1953}
1954
1955static PySequenceMethods immutable_list_as_sequence = {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001956 (inquiry)list_length, /* sq_length */
1957 (binaryfunc)list_concat, /* sq_concat */
1958 (intargfunc)list_repeat, /* sq_repeat */
1959 (intargfunc)list_item, /* sq_item */
1960 (intintargfunc)list_slice, /* sq_slice */
1961 (intobjargproc)immutable_list_ass, /* sq_ass_item */
1962 (intintobjargproc)immutable_list_ass, /* sq_ass_slice */
1963 (objobjproc)list_contains, /* sq_contains */
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001964};
1965
1966static PyTypeObject immutable_list_type = {
1967 PyObject_HEAD_INIT(&PyType_Type)
1968 0,
1969 "list (immutable, during sort)",
Neil Schemenauere83c00e2001-08-29 23:54:21 +00001970 sizeof(PyListObject),
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001971 0,
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001972 0, /* Cannot happen */ /* tp_dealloc */
1973 (printfunc)list_print, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001974 0, /* tp_getattr */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001975 0, /* tp_setattr */
1976 0, /* Won't be called */ /* tp_compare */
1977 (reprfunc)list_repr, /* tp_repr */
1978 0, /* tp_as_number */
1979 &immutable_list_as_sequence, /* tp_as_sequence */
1980 0, /* tp_as_mapping */
Guido van Rossumdbb53d92001-12-03 16:32:18 +00001981 list_nohash, /* tp_hash */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001982 0, /* tp_call */
1983 0, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001984 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001985 0, /* tp_setattro */
1986 0, /* tp_as_buffer */
Neil Schemenauere83c00e2001-08-29 23:54:21 +00001987 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001988 list_doc, /* tp_doc */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001989 (traverseproc)list_traverse, /* tp_traverse */
1990 0, /* tp_clear */
1991 list_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001992 0, /* tp_weaklistoffset */
1993 0, /* tp_iter */
1994 0, /* tp_iternext */
1995 immutable_list_methods, /* tp_methods */
1996 0, /* tp_members */
1997 0, /* tp_getset */
1998 0, /* tp_base */
1999 0, /* tp_dict */
2000 0, /* tp_descr_get */
2001 0, /* tp_descr_set */
2002 0, /* tp_init */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002003 /* NOTE: This is *not* the standard list_type struct! */
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002004};
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002005
2006
2007/*********************** List Iterator **************************/
2008
2009typedef struct {
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002010 PyObject_HEAD
2011 long it_index;
Guido van Rossum86103ae2002-07-16 20:07:32 +00002012 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002013} listiterobject;
2014
2015PyTypeObject PyListIter_Type;
2016
Guido van Rossum5086e492002-07-16 15:56:52 +00002017static PyObject *
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002018list_iter(PyObject *seq)
2019{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002020 listiterobject *it;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002021
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002022 if (!PyList_Check(seq)) {
2023 PyErr_BadInternalCall();
2024 return NULL;
2025 }
2026 it = PyObject_GC_New(listiterobject, &PyListIter_Type);
2027 if (it == NULL)
2028 return NULL;
2029 it->it_index = 0;
2030 Py_INCREF(seq);
2031 it->it_seq = (PyListObject *)seq;
2032 _PyObject_GC_TRACK(it);
2033 return (PyObject *)it;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002034}
2035
2036static void
2037listiter_dealloc(listiterobject *it)
2038{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002039 _PyObject_GC_UNTRACK(it);
Guido van Rossum86103ae2002-07-16 20:07:32 +00002040 Py_XDECREF(it->it_seq);
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002041 PyObject_GC_Del(it);
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002042}
2043
2044static int
2045listiter_traverse(listiterobject *it, visitproc visit, void *arg)
2046{
Guido van Rossum86103ae2002-07-16 20:07:32 +00002047 if (it->it_seq == NULL)
2048 return 0;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002049 return visit((PyObject *)it->it_seq, arg);
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002050}
2051
2052
2053static PyObject *
2054listiter_getiter(PyObject *it)
2055{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002056 Py_INCREF(it);
2057 return it;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002058}
2059
2060static PyObject *
Tim Peters93b2cc42002-06-01 05:22:55 +00002061listiter_next(listiterobject *it)
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002062{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002063 PyListObject *seq;
2064 PyObject *item;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002065
Tim Peters93b2cc42002-06-01 05:22:55 +00002066 assert(it != NULL);
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002067 seq = it->it_seq;
Guido van Rossum86103ae2002-07-16 20:07:32 +00002068 if (seq == NULL)
2069 return NULL;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002070 assert(PyList_Check(seq));
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002071
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002072 if (it->it_index < PyList_GET_SIZE(seq)) {
Tim Peters93b2cc42002-06-01 05:22:55 +00002073 item = PyList_GET_ITEM(seq, it->it_index);
2074 ++it->it_index;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002075 Py_INCREF(item);
2076 return item;
2077 }
Guido van Rossum86103ae2002-07-16 20:07:32 +00002078
2079 Py_DECREF(seq);
2080 it->it_seq = NULL;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002081 return NULL;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002082}
2083
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002084PyTypeObject PyListIter_Type = {
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002085 PyObject_HEAD_INIT(&PyType_Type)
2086 0, /* ob_size */
2087 "listiterator", /* tp_name */
2088 sizeof(listiterobject), /* tp_basicsize */
2089 0, /* tp_itemsize */
2090 /* methods */
2091 (destructor)listiter_dealloc, /* tp_dealloc */
2092 0, /* tp_print */
2093 0, /* tp_getattr */
2094 0, /* tp_setattr */
2095 0, /* tp_compare */
2096 0, /* tp_repr */
2097 0, /* tp_as_number */
2098 0, /* tp_as_sequence */
2099 0, /* tp_as_mapping */
2100 0, /* tp_hash */
2101 0, /* tp_call */
2102 0, /* tp_str */
2103 PyObject_GenericGetAttr, /* tp_getattro */
2104 0, /* tp_setattro */
2105 0, /* tp_as_buffer */
2106 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2107 0, /* tp_doc */
2108 (traverseproc)listiter_traverse, /* tp_traverse */
2109 0, /* tp_clear */
2110 0, /* tp_richcompare */
2111 0, /* tp_weaklistoffset */
2112 (getiterfunc)listiter_getiter, /* tp_iter */
2113 (iternextfunc)listiter_next, /* tp_iternext */
Guido van Rossum86103ae2002-07-16 20:07:32 +00002114 0, /* tp_methods */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002115 0, /* tp_members */
2116 0, /* tp_getset */
2117 0, /* tp_base */
2118 0, /* tp_dict */
2119 0, /* tp_descr_get */
2120 0, /* tp_descr_set */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002121};