blob: dd2d5806dd3bb701aa3291b7fb3ae6d013e731e1 [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{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000059 PyListObject *op;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +000060 size_t nbytes;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000061 if (size < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +000062 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000063 return NULL;
64 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +000065 nbytes = size * sizeof(PyObject *);
Guido van Rossum1e28e5e1992-08-19 16:46:30 +000066 /* Check for overflow */
Guido van Rossumc0b618a1997-05-02 03:12:38 +000067 if (nbytes / sizeof(PyObject *) != (size_t)size) {
68 return PyErr_NoMemory();
Guido van Rossum1e28e5e1992-08-19 16:46:30 +000069 }
Neil Schemenauere83c00e2001-08-29 23:54:21 +000070 op = PyObject_GC_New(PyListObject, &PyList_Type);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000071 if (op == NULL) {
Neil Schemenauere83c00e2001-08-29 23:54:21 +000072 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000073 }
74 if (size <= 0) {
75 op->ob_item = NULL;
76 }
77 else {
Guido van Rossumb18618d2000-05-03 23:44:39 +000078 op->ob_item = (PyObject **) PyMem_MALLOC(nbytes);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000079 if (op->ob_item == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +000080 return PyErr_NoMemory();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000081 }
Neal Norwitz35fc7602002-06-13 21:11:11 +000082 memset(op->ob_item, 0, sizeof(*op->ob_item) * size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000083 }
Neil Schemenauere83c00e2001-08-29 23:54:21 +000084 op->ob_size = size;
Neil Schemenauere83c00e2001-08-29 23:54:21 +000085 _PyObject_GC_TRACK(op);
Guido van Rossumc0b618a1997-05-02 03:12:38 +000086 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000087}
88
89int
Fred Drakea2f55112000-07-09 15:16:51 +000090PyList_Size(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000091{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000092 if (!PyList_Check(op)) {
93 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000094 return -1;
95 }
96 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +000097 return ((PyListObject *)op) -> ob_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000098}
99
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000100static PyObject *indexerr;
Guido van Rossum929f1b81996-08-09 20:51:27 +0000101
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000102PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000103PyList_GetItem(PyObject *op, int i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000104{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000105 if (!PyList_Check(op)) {
106 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000107 return NULL;
108 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000109 if (i < 0 || i >= ((PyListObject *)op) -> ob_size) {
Guido van Rossum929f1b81996-08-09 20:51:27 +0000110 if (indexerr == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000111 indexerr = PyString_FromString(
112 "list index out of range");
113 PyErr_SetObject(PyExc_IndexError, indexerr);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000114 return NULL;
115 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000116 return ((PyListObject *)op) -> ob_item[i];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000117}
118
119int
Fred Drakea2f55112000-07-09 15:16:51 +0000120PyList_SetItem(register PyObject *op, register int i,
121 register PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000122{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000123 register PyObject *olditem;
124 register PyObject **p;
125 if (!PyList_Check(op)) {
126 Py_XDECREF(newitem);
127 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000128 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000129 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000130 if (i < 0 || i >= ((PyListObject *)op) -> ob_size) {
131 Py_XDECREF(newitem);
132 PyErr_SetString(PyExc_IndexError,
133 "list assignment index out of range");
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000134 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000135 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000136 p = ((PyListObject *)op) -> ob_item + i;
Guido van Rossum5fe60581995-03-09 12:12:50 +0000137 olditem = *p;
138 *p = newitem;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000139 Py_XDECREF(olditem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000140 return 0;
141}
142
143static int
Fred Drakea2f55112000-07-09 15:16:51 +0000144ins1(PyListObject *self, int where, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000145{
146 int i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000147 PyObject **items;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000148 if (v == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000149 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000150 return -1;
151 }
Trent Micka5846642000-08-13 22:47:45 +0000152 if (self->ob_size == INT_MAX) {
153 PyErr_SetString(PyExc_OverflowError,
154 "cannot add more objects to list");
155 return -1;
156 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000157 items = self->ob_item;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000158 NRESIZE(items, PyObject *, self->ob_size+1);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000159 if (items == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000160 PyErr_NoMemory();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000161 return -1;
162 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000163 if (where < 0)
164 where = 0;
165 if (where > self->ob_size)
166 where = self->ob_size;
167 for (i = self->ob_size; --i >= where; )
168 items[i+1] = items[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000169 Py_INCREF(v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000170 items[where] = v;
171 self->ob_item = items;
172 self->ob_size++;
173 return 0;
174}
175
176int
Fred Drakea2f55112000-07-09 15:16:51 +0000177PyList_Insert(PyObject *op, int where, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000178{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000179 if (!PyList_Check(op)) {
180 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000181 return -1;
182 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000183 return ins1((PyListObject *)op, where, newitem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000184}
185
186int
Fred Drakea2f55112000-07-09 15:16:51 +0000187PyList_Append(PyObject *op, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000188{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000189 if (!PyList_Check(op)) {
190 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000191 return -1;
192 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000193 return ins1((PyListObject *)op,
194 (int) ((PyListObject *)op)->ob_size, newitem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000195}
196
197/* Methods */
198
199static void
Fred Drakea2f55112000-07-09 15:16:51 +0000200list_dealloc(PyListObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000201{
202 int i;
Guido van Rossumff413af2002-03-28 20:34:59 +0000203 PyObject_GC_UnTrack(op);
Guido van Rossumd724b232000-03-13 16:01:29 +0000204 Py_TRASHCAN_SAFE_BEGIN(op)
Jack Jansen7874d1f1995-01-19 12:09:27 +0000205 if (op->ob_item != NULL) {
Guido van Rossumfa717011999-06-09 15:19:34 +0000206 /* Do it backwards, for Christian Tismer.
207 There's a simple test case where somehow this reduces
208 thrashing when a *very* large list is created and
209 immediately deleted. */
210 i = op->ob_size;
211 while (--i >= 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000212 Py_XDECREF(op->ob_item[i]);
Jack Jansen7874d1f1995-01-19 12:09:27 +0000213 }
Guido van Rossumb18618d2000-05-03 23:44:39 +0000214 PyMem_FREE(op->ob_item);
Jack Jansen7874d1f1995-01-19 12:09:27 +0000215 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000216 op->ob_type->tp_free((PyObject *)op);
Guido van Rossumd724b232000-03-13 16:01:29 +0000217 Py_TRASHCAN_SAFE_END(op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000218}
219
Guido van Rossum90933611991-06-07 16:10:43 +0000220static int
Fred Drakea2f55112000-07-09 15:16:51 +0000221list_print(PyListObject *op, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000222{
223 int i;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000224
225 i = Py_ReprEnter((PyObject*)op);
226 if (i != 0) {
227 if (i < 0)
228 return i;
229 fprintf(fp, "[...]");
230 return 0;
231 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000232 fprintf(fp, "[");
Guido van Rossum90933611991-06-07 16:10:43 +0000233 for (i = 0; i < op->ob_size; i++) {
234 if (i > 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000235 fprintf(fp, ", ");
Guido van Rossumfb376de1998-04-10 22:47:27 +0000236 if (PyObject_Print(op->ob_item[i], fp, 0) != 0) {
237 Py_ReprLeave((PyObject *)op);
Guido van Rossum90933611991-06-07 16:10:43 +0000238 return -1;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000239 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000240 }
241 fprintf(fp, "]");
Guido van Rossumfb376de1998-04-10 22:47:27 +0000242 Py_ReprLeave((PyObject *)op);
Guido van Rossum90933611991-06-07 16:10:43 +0000243 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000244}
245
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000246static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000247list_repr(PyListObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000248{
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000249 int i;
Tim Petersa7259592001-06-16 05:11:17 +0000250 PyObject *s, *temp;
251 PyObject *pieces = NULL, *result = NULL;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000252
253 i = Py_ReprEnter((PyObject*)v);
254 if (i != 0) {
Tim Petersa7259592001-06-16 05:11:17 +0000255 return i > 0 ? PyString_FromString("[...]") : NULL;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000256 }
Tim Petersa7259592001-06-16 05:11:17 +0000257
258 if (v->ob_size == 0) {
259 result = PyString_FromString("[]");
260 goto Done;
261 }
262
263 pieces = PyList_New(0);
264 if (pieces == NULL)
265 goto Done;
266
267 /* Do repr() on each element. Note that this may mutate the list,
268 so must refetch the list size on each iteration. */
269 for (i = 0; i < v->ob_size; ++i) {
270 int status;
271 s = PyObject_Repr(v->ob_item[i]);
272 if (s == NULL)
273 goto Done;
274 status = PyList_Append(pieces, s);
275 Py_DECREF(s); /* append created a new ref */
276 if (status < 0)
277 goto Done;
278 }
279
280 /* Add "[]" decorations to the first and last items. */
281 assert(PyList_GET_SIZE(pieces) > 0);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000282 s = PyString_FromString("[");
Tim Petersa7259592001-06-16 05:11:17 +0000283 if (s == NULL)
284 goto Done;
285 temp = PyList_GET_ITEM(pieces, 0);
286 PyString_ConcatAndDel(&s, temp);
287 PyList_SET_ITEM(pieces, 0, s);
288 if (s == NULL)
289 goto Done;
290
291 s = PyString_FromString("]");
292 if (s == NULL)
293 goto Done;
294 temp = PyList_GET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1);
295 PyString_ConcatAndDel(&temp, s);
296 PyList_SET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1, temp);
297 if (temp == NULL)
298 goto Done;
299
300 /* Paste them all together with ", " between. */
301 s = PyString_FromString(", ");
302 if (s == NULL)
303 goto Done;
304 result = _PyString_Join(s, pieces);
305 Py_DECREF(s);
306
307Done:
308 Py_XDECREF(pieces);
Guido van Rossumfb376de1998-04-10 22:47:27 +0000309 Py_ReprLeave((PyObject *)v);
Tim Petersa7259592001-06-16 05:11:17 +0000310 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000311}
312
313static int
Fred Drakea2f55112000-07-09 15:16:51 +0000314list_length(PyListObject *a)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000315{
316 return a->ob_size;
317}
318
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000319
320
321static int
Fred Drakea2f55112000-07-09 15:16:51 +0000322list_contains(PyListObject *a, PyObject *el)
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000323{
Guido van Rossum65e1cea2001-01-17 22:11:59 +0000324 int i;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000325
326 for (i = 0; i < a->ob_size; ++i) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +0000327 int cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i),
328 Py_EQ);
329 if (cmp > 0)
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000330 return 1;
Guido van Rossum65e1cea2001-01-17 22:11:59 +0000331 else if (cmp < 0)
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000332 return -1;
333 }
334 return 0;
335}
336
337
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000338static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000339list_item(PyListObject *a, int i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000340{
341 if (i < 0 || i >= a->ob_size) {
Guido van Rossum929f1b81996-08-09 20:51:27 +0000342 if (indexerr == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000343 indexerr = PyString_FromString(
344 "list index out of range");
345 PyErr_SetObject(PyExc_IndexError, indexerr);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000346 return NULL;
347 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000348 Py_INCREF(a->ob_item[i]);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000349 return a->ob_item[i];
350}
351
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000352static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000353list_slice(PyListObject *a, int ilow, int ihigh)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000354{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000355 PyListObject *np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000356 int i;
357 if (ilow < 0)
358 ilow = 0;
359 else if (ilow > a->ob_size)
360 ilow = a->ob_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000361 if (ihigh < ilow)
362 ihigh = ilow;
363 else if (ihigh > a->ob_size)
364 ihigh = a->ob_size;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000365 np = (PyListObject *) PyList_New(ihigh - ilow);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000366 if (np == NULL)
367 return NULL;
368 for (i = ilow; i < ihigh; i++) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000369 PyObject *v = a->ob_item[i];
370 Py_INCREF(v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000371 np->ob_item[i - ilow] = v;
372 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000373 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000374}
375
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000376PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000377PyList_GetSlice(PyObject *a, int ilow, int ihigh)
Guido van Rossum234f9421993-06-17 12:35:49 +0000378{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000379 if (!PyList_Check(a)) {
380 PyErr_BadInternalCall();
Guido van Rossum234f9421993-06-17 12:35:49 +0000381 return NULL;
382 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000383 return list_slice((PyListObject *)a, ilow, ihigh);
Guido van Rossum234f9421993-06-17 12:35:49 +0000384}
385
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000386static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000387list_concat(PyListObject *a, PyObject *bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000388{
389 int size;
390 int i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000391 PyListObject *np;
392 if (!PyList_Check(bb)) {
Fred Drakeb6a9ada2000-06-01 03:12:13 +0000393 PyErr_Format(PyExc_TypeError,
Fred Drake914a2ed2000-06-01 14:31:03 +0000394 "can only concatenate list (not \"%.200s\") to list",
395 bb->ob_type->tp_name);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000396 return NULL;
397 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000398#define b ((PyListObject *)bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000399 size = a->ob_size + b->ob_size;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000400 np = (PyListObject *) PyList_New(size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000401 if (np == NULL) {
Guido van Rossum90933611991-06-07 16:10:43 +0000402 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000403 }
404 for (i = 0; i < a->ob_size; i++) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000405 PyObject *v = a->ob_item[i];
406 Py_INCREF(v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000407 np->ob_item[i] = v;
408 }
409 for (i = 0; i < b->ob_size; i++) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000410 PyObject *v = b->ob_item[i];
411 Py_INCREF(v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000412 np->ob_item[i + a->ob_size] = v;
413 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000414 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000415#undef b
416}
417
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000418static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000419list_repeat(PyListObject *a, int n)
Guido van Rossumed98d481991-03-06 13:07:53 +0000420{
421 int i, j;
422 int size;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000423 PyListObject *np;
424 PyObject **p;
Guido van Rossumed98d481991-03-06 13:07:53 +0000425 if (n < 0)
426 n = 0;
427 size = a->ob_size * n;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000428 np = (PyListObject *) PyList_New(size);
Guido van Rossumed98d481991-03-06 13:07:53 +0000429 if (np == NULL)
430 return NULL;
431 p = np->ob_item;
432 for (i = 0; i < n; i++) {
433 for (j = 0; j < a->ob_size; j++) {
434 *p = a->ob_item[j];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000435 Py_INCREF(*p);
Guido van Rossumed98d481991-03-06 13:07:53 +0000436 p++;
437 }
438 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000439 return (PyObject *) np;
Guido van Rossumed98d481991-03-06 13:07:53 +0000440}
441
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000442static int
Fred Drakea2f55112000-07-09 15:16:51 +0000443list_ass_slice(PyListObject *a, int ilow, int ihigh, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000444{
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000445 /* Because [X]DECREF can recursively invoke list operations on
446 this list, we must postpone all [X]DECREF activity until
447 after the list is back in its canonical shape. Therefore
448 we must allocate an additional array, 'recycle', into which
449 we temporarily copy the items that are deleted from the
450 list. :-( */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000451 PyObject **recycle, **p;
452 PyObject **item;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000453 int n; /* Size of replacement list */
454 int d; /* Change in size */
455 int k; /* Loop index */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000456#define b ((PyListObject *)v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000457 if (v == NULL)
458 n = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000459 else if (PyList_Check(v)) {
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000460 n = b->ob_size;
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000461 if (a == b) {
462 /* Special case "a[i:j] = a" -- copy b first */
463 int ret;
464 v = list_slice(b, 0, n);
465 ret = list_ass_slice(a, ilow, ihigh, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000466 Py_DECREF(v);
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000467 return ret;
468 }
469 }
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000470 else {
Fred Drakeb6a9ada2000-06-01 03:12:13 +0000471 PyErr_Format(PyExc_TypeError,
472 "must assign list (not \"%.200s\") to slice",
473 v->ob_type->tp_name);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000474 return -1;
475 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000476 if (ilow < 0)
477 ilow = 0;
478 else if (ilow > a->ob_size)
479 ilow = a->ob_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000480 if (ihigh < ilow)
481 ihigh = ilow;
482 else if (ihigh > a->ob_size)
483 ihigh = a->ob_size;
484 item = a->ob_item;
485 d = n - (ihigh-ilow);
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000486 if (ihigh > ilow)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000487 p = recycle = PyMem_NEW(PyObject *, (ihigh-ilow));
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000488 else
489 p = recycle = NULL;
490 if (d <= 0) { /* Delete -d items; recycle ihigh-ilow items */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000491 for (k = ilow; k < ihigh; k++)
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000492 *p++ = item[k];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000493 if (d < 0) {
494 for (/*k = ihigh*/; k < a->ob_size; k++)
495 item[k+d] = item[k];
496 a->ob_size += d;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000497 NRESIZE(item, PyObject *, a->ob_size); /* Can't fail */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000498 a->ob_item = item;
499 }
500 }
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000501 else { /* Insert d items; recycle ihigh-ilow items */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000502 NRESIZE(item, PyObject *, a->ob_size + d);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000503 if (item == NULL) {
Guido van Rossumb18618d2000-05-03 23:44:39 +0000504 if (recycle != NULL)
505 PyMem_DEL(recycle);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000506 PyErr_NoMemory();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000507 return -1;
508 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000509 for (k = a->ob_size; --k >= ihigh; )
510 item[k+d] = item[k];
511 for (/*k = ihigh-1*/; k >= ilow; --k)
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000512 *p++ = item[k];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000513 a->ob_item = item;
514 a->ob_size += d;
515 }
516 for (k = 0; k < n; k++, ilow++) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000517 PyObject *w = b->ob_item[k];
518 Py_XINCREF(w);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000519 item[ilow] = w;
520 }
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000521 if (recycle) {
522 while (--p >= recycle)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000523 Py_XDECREF(*p);
524 PyMem_DEL(recycle);
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000525 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000526 if (a->ob_size == 0 && a->ob_item != NULL) {
527 PyMem_FREE(a->ob_item);
528 a->ob_item = NULL;
529 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000530 return 0;
531#undef b
532}
533
Guido van Rossum234f9421993-06-17 12:35:49 +0000534int
Fred Drakea2f55112000-07-09 15:16:51 +0000535PyList_SetSlice(PyObject *a, int ilow, int ihigh, PyObject *v)
Guido van Rossum234f9421993-06-17 12:35:49 +0000536{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000537 if (!PyList_Check(a)) {
538 PyErr_BadInternalCall();
Guido van Rossum1fc238a1993-07-29 08:25:09 +0000539 return -1;
Guido van Rossum234f9421993-06-17 12:35:49 +0000540 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000541 return list_ass_slice((PyListObject *)a, ilow, ihigh, v);
Guido van Rossum234f9421993-06-17 12:35:49 +0000542}
543
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000544static PyObject *
545list_inplace_repeat(PyListObject *self, int n)
546{
547 PyObject **items;
548 int size, i, j;
549
550
551 size = PyList_GET_SIZE(self);
552 if (size == 0) {
553 Py_INCREF(self);
554 return (PyObject *)self;
555 }
556
557 items = self->ob_item;
558
559 if (n < 1) {
560 self->ob_item = NULL;
561 self->ob_size = 0;
562 for (i = 0; i < size; i++)
563 Py_XDECREF(items[i]);
564 PyMem_DEL(items);
565 Py_INCREF(self);
566 return (PyObject *)self;
567 }
568
569 NRESIZE(items, PyObject*, size*n);
570 if (items == NULL) {
571 PyErr_NoMemory();
572 goto finally;
573 }
574 self->ob_item = items;
575 for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */
576 for (j = 0; j < size; j++) {
577 PyObject *o = PyList_GET_ITEM(self, j);
578 Py_INCREF(o);
579 PyList_SET_ITEM(self, self->ob_size++, o);
580 }
581 }
582 Py_INCREF(self);
583 return (PyObject *)self;
584 finally:
585 return NULL;
586}
587
Guido van Rossum4a450d01991-04-03 19:05:18 +0000588static int
Fred Drakea2f55112000-07-09 15:16:51 +0000589list_ass_item(PyListObject *a, int i, PyObject *v)
Guido van Rossum4a450d01991-04-03 19:05:18 +0000590{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000591 PyObject *old_value;
Guido van Rossum4a450d01991-04-03 19:05:18 +0000592 if (i < 0 || i >= a->ob_size) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000593 PyErr_SetString(PyExc_IndexError,
594 "list assignment index out of range");
Guido van Rossum4a450d01991-04-03 19:05:18 +0000595 return -1;
596 }
597 if (v == NULL)
598 return list_ass_slice(a, i, i+1, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000599 Py_INCREF(v);
Guido van Rossumd7047b31995-01-02 19:07:15 +0000600 old_value = a->ob_item[i];
Guido van Rossum4a450d01991-04-03 19:05:18 +0000601 a->ob_item[i] = v;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000602 Py_DECREF(old_value);
Guido van Rossum4a450d01991-04-03 19:05:18 +0000603 return 0;
604}
605
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000606static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000607ins(PyListObject *self, int where, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000608{
609 if (ins1(self, where, v) != 0)
610 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000611 Py_INCREF(Py_None);
612 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000613}
614
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000615static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000616listinsert(PyListObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000617{
618 int i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000619 PyObject *v;
Guido van Rossumc00a9382000-02-24 21:48:29 +0000620 if (!PyArg_ParseTuple(args, "iO:insert", &i, &v))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000621 return NULL;
Guido van Rossumbf80e541993-02-08 15:49:17 +0000622 return ins(self, i, v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000623}
624
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000625static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000626listappend(PyListObject *self, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000627{
Guido van Rossumbf80e541993-02-08 15:49:17 +0000628 return ins(self, (int) self->ob_size, v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000629}
630
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000631static int
632listextend_internal(PyListObject *self, PyObject *b)
Barry Warsawdedf6d61998-10-09 16:37:25 +0000633{
Barry Warsawdedf6d61998-10-09 16:37:25 +0000634 PyObject **items;
635 int selflen = PyList_GET_SIZE(self);
636 int blen;
637 register int i;
638
Jeremy Hyltondb60bb52001-01-03 22:32:16 +0000639 if (PyObject_Size(b) == 0) {
Barry Warsawdedf6d61998-10-09 16:37:25 +0000640 /* short circuit when b is empty */
Jeremy Hyltondb60bb52001-01-03 22:32:16 +0000641 Py_DECREF(b);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000642 return 0;
Jeremy Hyltondb60bb52001-01-03 22:32:16 +0000643 }
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000644
Barry Warsawdedf6d61998-10-09 16:37:25 +0000645 if (self == (PyListObject*)b) {
646 /* as in list_ass_slice() we must special case the
647 * situation: a.extend(a)
648 *
649 * XXX: I think this way ought to be faster than using
650 * list_slice() the way list_ass_slice() does.
651 */
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000652 Py_DECREF(b);
Barry Warsawdedf6d61998-10-09 16:37:25 +0000653 b = PyList_New(selflen);
654 if (!b)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000655 return -1;
Barry Warsawdedf6d61998-10-09 16:37:25 +0000656 for (i = 0; i < selflen; i++) {
657 PyObject *o = PyList_GET_ITEM(self, i);
658 Py_INCREF(o);
659 PyList_SET_ITEM(b, i, o);
660 }
661 }
Barry Warsawdedf6d61998-10-09 16:37:25 +0000662
Jeremy Hylton03657cf2000-07-12 13:05:33 +0000663 blen = PyObject_Size(b);
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000664
Barry Warsawdedf6d61998-10-09 16:37:25 +0000665 /* resize a using idiom */
666 items = self->ob_item;
667 NRESIZE(items, PyObject*, selflen + blen);
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000668 if (items == NULL) {
Barry Warsawdedf6d61998-10-09 16:37:25 +0000669 PyErr_NoMemory();
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000670 Py_DECREF(b);
671 return -1;
Barry Warsawdedf6d61998-10-09 16:37:25 +0000672 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000673
Barry Warsawdedf6d61998-10-09 16:37:25 +0000674 self->ob_item = items;
675
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000676 /* populate the end of self with b's items */
Barry Warsawdedf6d61998-10-09 16:37:25 +0000677 for (i = 0; i < blen; i++) {
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000678 PyObject *o = PySequence_Fast_GET_ITEM(b, i);
Barry Warsawdedf6d61998-10-09 16:37:25 +0000679 Py_INCREF(o);
680 PyList_SET_ITEM(self, self->ob_size++, o);
681 }
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000682 Py_DECREF(b);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000683 return 0;
Barry Warsawdedf6d61998-10-09 16:37:25 +0000684}
685
686
687static PyObject *
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000688list_inplace_concat(PyListObject *self, PyObject *other)
689{
Tim Peters1af03e92001-05-26 19:37:54 +0000690 other = PySequence_Fast(other, "argument to += must be iterable");
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000691 if (!other)
692 return NULL;
693
694 if (listextend_internal(self, other) < 0)
695 return NULL;
696
697 Py_INCREF(self);
698 return (PyObject *)self;
699}
700
701static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000702listextend(PyListObject *self, PyObject *b)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000703{
704
Tim Peters1af03e92001-05-26 19:37:54 +0000705 b = PySequence_Fast(b, "list.extend() argument must be iterable");
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000706 if (!b)
707 return NULL;
708
709 if (listextend_internal(self, b) < 0)
710 return NULL;
711
712 Py_INCREF(Py_None);
713 return Py_None;
714}
715
716static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000717listpop(PyListObject *self, PyObject *args)
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000718{
719 int i = -1;
720 PyObject *v;
Guido van Rossumc00a9382000-02-24 21:48:29 +0000721 if (!PyArg_ParseTuple(args, "|i:pop", &i))
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000722 return NULL;
723 if (self->ob_size == 0) {
724 /* Special-case most common failure cause */
725 PyErr_SetString(PyExc_IndexError, "pop from empty list");
726 return NULL;
727 }
728 if (i < 0)
729 i += self->ob_size;
730 if (i < 0 || i >= self->ob_size) {
731 PyErr_SetString(PyExc_IndexError, "pop index out of range");
732 return NULL;
733 }
734 v = self->ob_item[i];
735 Py_INCREF(v);
736 if (list_ass_slice(self, i, i+1, (PyObject *)NULL) != 0) {
737 Py_DECREF(v);
738 return NULL;
739 }
740 return v;
741}
742
Guido van Rossum3f236de1996-12-10 23:55:39 +0000743/* New quicksort implementation for arrays of object pointers.
744 Thanks to discussions with Tim Peters. */
745
746/* CMPERROR is returned by our comparison function when an error
747 occurred. This is the largest negative integer (0x80000000 on a
748 32-bit system). */
Guido van Rossum19700b61997-03-05 00:45:43 +0000749#define CMPERROR ( (int) ((unsigned int)1 << (8*sizeof(int) - 1)) )
Guido van Rossum3f236de1996-12-10 23:55:39 +0000750
751/* Comparison function. Takes care of calling a user-supplied
752 comparison function (any callable Python object). Calls the
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000753 standard comparison function, PyObject_Compare(), if the user-
754 supplied function is NULL. */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000755
756static int
Fred Drakea2f55112000-07-09 15:16:51 +0000757docompare(PyObject *x, PyObject *y, PyObject *compare)
Guido van Rossum3f236de1996-12-10 23:55:39 +0000758{
Tim Petersf2a04732002-07-11 21:46:16 +0000759 PyObject *res;
760 PyObject *args;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000761 int i;
762
Guido van Rossumc8b6df91997-05-23 00:06:51 +0000763 if (compare == NULL) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +0000764 /* NOTE: we rely on the fact here that the sorting algorithm
765 only ever checks whether k<0, i.e., whether x<y. So we
766 invoke the rich comparison function with Py_LT ('<'), and
767 return -1 when it returns true and 0 when it returns
768 false. */
769 i = PyObject_RichCompareBool(x, y, Py_LT);
770 if (i < 0)
771 return CMPERROR;
772 else
773 return -i;
Guido van Rossumc8b6df91997-05-23 00:06:51 +0000774 }
Guido van Rossum3f236de1996-12-10 23:55:39 +0000775
Tim Petersf2a04732002-07-11 21:46:16 +0000776 args = PyTuple_New(2);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000777 if (args == NULL)
778 return CMPERROR;
Tim Petersf2a04732002-07-11 21:46:16 +0000779 Py_INCREF(x);
780 Py_INCREF(y);
781 PyTuple_SET_ITEM(args, 0, x);
782 PyTuple_SET_ITEM(args, 1, y);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000783 res = PyEval_CallObject(compare, args);
784 Py_DECREF(args);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000785 if (res == NULL)
786 return CMPERROR;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000787 if (!PyInt_Check(res)) {
788 Py_DECREF(res);
789 PyErr_SetString(PyExc_TypeError,
Guido van Rossum9bcd1d71999-04-19 17:44:39 +0000790 "comparison function must return int");
Guido van Rossum3f236de1996-12-10 23:55:39 +0000791 return CMPERROR;
792 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000793 i = PyInt_AsLong(res);
794 Py_DECREF(res);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000795 if (i < 0)
796 return -1;
797 if (i > 0)
798 return 1;
799 return 0;
800}
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
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000838
839#define SETK(X,Y) if ((k = docompare(X,Y,compare))==CMPERROR) goto fail
840
841/* binarysort is the best method for sorting small arrays: it does
842 few compares, but can do data movement quadratic in the number of
843 elements.
Guido van Rossum42812581998-06-17 14:15:44 +0000844 [lo, hi) is a contiguous slice of a list, and is sorted via
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000845 binary insertion.
846 On entry, must have lo <= start <= hi, and that [lo, start) is already
847 sorted (pass start == lo if you don't know!).
848 If docompare complains (returns CMPERROR) return -1, else 0.
849 Even in case of error, the output slice will be some permutation of
850 the input (nothing is lost or duplicated).
851*/
Guido van Rossum3f236de1996-12-10 23:55:39 +0000852
853static int
Fred Drakea2f55112000-07-09 15:16:51 +0000854binarysort(PyObject **lo, PyObject **hi, PyObject **start, PyObject *compare)
855 /* compare -- comparison function object, or NULL for default */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000856{
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000857 /* assert lo <= start <= hi
858 assert [lo, start) is sorted */
859 register int k;
860 register PyObject **l, **p, **r;
861 register PyObject *pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000862
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000863 if (lo == start)
864 ++start;
865 for (; start < hi; ++start) {
866 /* set l to where *start belongs */
867 l = lo;
868 r = start;
Guido van Rossuma119c0d1998-05-29 17:56:32 +0000869 pivot = *r;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000870 do {
871 p = l + ((r - l) >> 1);
872 SETK(pivot, *p);
873 if (k < 0)
874 r = p;
875 else
876 l = p + 1;
877 } while (l < r);
878 /* Pivot should go at l -- slide over to make room.
879 Caution: using memmove is much slower under MSVC 5;
880 we're not usually moving many slots. */
881 for (p = start; p > l; --p)
882 *p = *(p-1);
883 *l = pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000884 }
Guido van Rossum3f236de1996-12-10 23:55:39 +0000885 return 0;
Guido van Rossuma119c0d1998-05-29 17:56:32 +0000886
887 fail:
888 return -1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000889}
890
891/* samplesortslice is the sorting workhorse.
Guido van Rossum42812581998-06-17 14:15:44 +0000892 [lo, hi) is a contiguous slice of a list, to be sorted in place.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000893 On entry, must have lo <= hi,
894 If docompare complains (returns CMPERROR) return -1, else 0.
895 Even in case of error, the output slice will be some permutation of
896 the input (nothing is lost or duplicated).
897
898 samplesort is basically quicksort on steroids: a power of 2 close
899 to n/ln(n) is computed, and that many elements (less 1) are picked at
900 random from the array and sorted. These 2**k - 1 elements are then
901 used as preselected pivots for an equal number of quicksort
902 partitioning steps, partitioning the slice into 2**k chunks each of
903 size about ln(n). These small final chunks are then usually handled
904 by binarysort. Note that when k=1, this is roughly the same as an
905 ordinary quicksort using a random pivot, and when k=2 this is roughly
906 a median-of-3 quicksort. From that view, using k ~= lg(n/ln(n)) makes
907 this a "median of n/ln(n)" quicksort. You can also view it as a kind
908 of bucket sort, where 2**k-1 bucket boundaries are picked dynamically.
909
910 The large number of samples makes a quadratic-time case almost
911 impossible, and asymptotically drives the average-case number of
912 compares from quicksort's 2 N ln N (or 12/7 N ln N for the median-of-
913 3 variant) down to N lg N.
914
915 We also play lots of low-level tricks to cut the number of compares.
916
917 Very obscure: To avoid using extra memory, the PPs are stored in the
918 array and shuffled around as partitioning proceeds. At the start of a
919 partitioning step, we'll have 2**m-1 (for some m) PPs in sorted order,
920 adjacent (either on the left or the right!) to a chunk of X elements
921 that are to be partitioned: P X or X P. In either case we need to
922 shuffle things *in place* so that the 2**(m-1) smaller PPs are on the
923 left, followed by the PP to be used for this step (that's the middle
924 of the PPs), followed by X, followed by the 2**(m-1) larger PPs:
925 P X or X P -> Psmall pivot X Plarge
926 and the order of the PPs must not be altered. It can take a while
927 to realize this isn't trivial! It can take even longer <wink> to
928 understand why the simple code below works, using only 2**(m-1) swaps.
929 The key is that the order of the X elements isn't necessarily
930 preserved: X can end up as some cyclic permutation of its original
931 order. That's OK, because X is unsorted anyway. If the order of X
932 had to be preserved too, the simplest method I know of using O(1)
933 scratch storage requires len(X) + 2**(m-1) swaps, spread over 2 passes.
934 Since len(X) is typically several times larger than 2**(m-1), that
935 would slow things down.
936*/
937
938struct SamplesortStackNode {
939 /* Represents a slice of the array, from (& including) lo up
940 to (but excluding) hi. "extra" additional & adjacent elements
941 are pre-selected pivots (PPs), spanning [lo-extra, lo) if
942 extra > 0, or [hi, hi-extra) if extra < 0. The PPs are
943 already sorted, but nothing is known about the other elements
944 in [lo, hi). |extra| is always one less than a power of 2.
945 When extra is 0, we're out of PPs, and the slice must be
946 sorted by some other means. */
947 PyObject **lo;
948 PyObject **hi;
949 int extra;
950};
951
952/* 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 +0000953 N / ln(N) as possible. So k ~= lg(N / ln(N)). Calling libm routines
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000954 is undesirable, so cutoff values are canned in the "cutoff" table
955 below: cutoff[i] is the smallest N such that k == CUTOFFBASE + i. */
956#define CUTOFFBASE 4
Guido van Rossum3aa23fd1999-01-14 19:01:53 +0000957static long cutoff[] = {
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000958 43, /* smallest N such that k == 4 */
959 106, /* etc */
960 250,
961 576,
962 1298,
963 2885,
964 6339,
965 13805,
966 29843,
967 64116,
968 137030,
969 291554,
970 617916,
971 1305130,
972 2748295,
973 5771662,
974 12091672,
975 25276798,
976 52734615,
977 109820537,
978 228324027,
979 473977813,
980 982548444, /* smallest N such that k == 26 */
981 2034159050 /* largest N that fits in signed 32-bit; k == 27 */
982};
983
984static int
Fred Drakea2f55112000-07-09 15:16:51 +0000985samplesortslice(PyObject **lo, PyObject **hi, PyObject *compare)
986 /* compare -- comparison function object, or NULL for default */
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000987{
988 register PyObject **l, **r;
989 register PyObject *tmp, *pivot;
990 register int k;
991 int n, extra, top, extraOnRight;
992 struct SamplesortStackNode stack[STACKSIZE];
993
994 /* assert lo <= hi */
995 n = hi - lo;
996
997 /* ----------------------------------------------------------
998 * Special cases
999 * --------------------------------------------------------*/
1000 if (n < 2)
1001 return 0;
1002
1003 /* Set r to the largest value such that [lo,r) is sorted.
1004 This catches the already-sorted case, the all-the-same
1005 case, and the appended-a-few-elements-to-a-sorted-list case.
1006 If the array is unsorted, we're very likely to get out of
1007 the loop fast, so the test is cheap if it doesn't pay off.
1008 */
1009 /* assert lo < hi */
1010 for (r = lo+1; r < hi; ++r) {
1011 SETK(*r, *(r-1));
1012 if (k < 0)
1013 break;
1014 }
1015 /* [lo,r) is sorted, [r,hi) unknown. Get out cheap if there are
1016 few unknowns, or few elements in total. */
1017 if (hi - r <= MAXMERGE || n < MINSIZE)
Guido van Rossum42812581998-06-17 14:15:44 +00001018 return binarysort(lo, hi, r, compare);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001019
1020 /* Check for the array already being reverse-sorted. Typical
1021 benchmark-driven silliness <wink>. */
1022 /* assert lo < hi */
1023 for (r = lo+1; r < hi; ++r) {
1024 SETK(*(r-1), *r);
1025 if (k < 0)
1026 break;
1027 }
1028 if (hi - r <= MAXMERGE) {
1029 /* Reverse the reversed prefix, then insert the tail */
1030 PyObject **originalr = r;
1031 l = lo;
1032 do {
1033 --r;
1034 tmp = *l; *l = *r; *r = tmp;
1035 ++l;
1036 } while (l < r);
Guido van Rossum42812581998-06-17 14:15:44 +00001037 return binarysort(lo, hi, originalr, compare);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001038 }
1039
1040 /* ----------------------------------------------------------
1041 * Normal case setup: a large array without obvious pattern.
1042 * --------------------------------------------------------*/
1043
1044 /* extra := a power of 2 ~= n/ln(n), less 1.
1045 First find the smallest extra s.t. n < cutoff[extra] */
1046 for (extra = 0;
1047 extra < sizeof(cutoff) / sizeof(cutoff[0]);
1048 ++extra) {
1049 if (n < cutoff[extra])
1050 break;
1051 /* note that if we fall out of the loop, the value of
1052 extra still makes *sense*, but may be smaller than
1053 we would like (but the array has more than ~= 2**31
1054 elements in this case!) */
1055 }
1056 /* Now k == extra - 1 + CUTOFFBASE. The smallest value k can
1057 have is CUTOFFBASE-1, so
1058 assert MINSIZE >= 2**(CUTOFFBASE-1) - 1 */
1059 extra = (1 << (extra - 1 + CUTOFFBASE)) - 1;
1060 /* assert extra > 0 and n >= extra */
1061
1062 /* Swap that many values to the start of the array. The
1063 selection of elements is pseudo-random, but the same on
1064 every run (this is intentional! timing algorithm changes is
1065 a pain if timing varies across runs). */
1066 {
1067 unsigned int seed = n / extra; /* arbitrary */
1068 unsigned int i;
1069 for (i = 0; i < (unsigned)extra; ++i) {
1070 /* j := random int in [i, n) */
1071 unsigned int j;
1072 seed = seed * 69069 + 7;
1073 j = i + seed % (n - i);
1074 tmp = lo[i]; lo[i] = lo[j]; lo[j] = tmp;
1075 }
1076 }
1077
1078 /* Recursively sort the preselected pivots. */
Guido van Rossum42812581998-06-17 14:15:44 +00001079 if (samplesortslice(lo, lo + extra, compare) < 0)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001080 goto fail;
1081
1082 top = 0; /* index of available stack slot */
1083 lo += extra; /* point to first unknown */
1084 extraOnRight = 0; /* the PPs are at the left end */
1085
1086 /* ----------------------------------------------------------
1087 * Partition [lo, hi), and repeat until out of work.
1088 * --------------------------------------------------------*/
1089 for (;;) {
1090 /* assert lo <= hi, so n >= 0 */
1091 n = hi - lo;
1092
1093 /* We may not want, or may not be able, to partition:
1094 If n is small, it's quicker to insert.
1095 If extra is 0, we're out of pivots, and *must* use
1096 another method.
1097 */
1098 if (n < MINPARTITIONSIZE || extra == 0) {
1099 if (n >= MINSIZE) {
1100 /* assert extra == 0
1101 This is rare, since the average size
1102 of a final block is only about
1103 ln(original n). */
Guido van Rossum42812581998-06-17 14:15:44 +00001104 if (samplesortslice(lo, hi, compare) < 0)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001105 goto fail;
1106 }
1107 else {
1108 /* Binary insertion should be quicker,
1109 and we can take advantage of the PPs
1110 already being sorted. */
1111 if (extraOnRight && extra) {
1112 /* swap the PPs to the left end */
1113 k = extra;
1114 do {
1115 tmp = *lo;
1116 *lo = *hi;
1117 *hi = tmp;
1118 ++lo; ++hi;
1119 } while (--k);
1120 }
1121 if (binarysort(lo - extra, hi, lo,
Guido van Rossum42812581998-06-17 14:15:44 +00001122 compare) < 0)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001123 goto fail;
1124 }
1125
1126 /* Find another slice to work on. */
1127 if (--top < 0)
1128 break; /* no more -- done! */
1129 lo = stack[top].lo;
1130 hi = stack[top].hi;
1131 extra = stack[top].extra;
1132 extraOnRight = 0;
1133 if (extra < 0) {
1134 extraOnRight = 1;
1135 extra = -extra;
1136 }
1137 continue;
1138 }
1139
1140 /* Pretend the PPs are indexed 0, 1, ..., extra-1.
1141 Then our preselected pivot is at (extra-1)/2, and we
1142 want to move the PPs before that to the left end of
1143 the slice, and the PPs after that to the right end.
1144 The following section changes extra, lo, hi, and the
1145 slice such that:
1146 [lo-extra, lo) contains the smaller PPs.
1147 *lo == our PP.
1148 (lo, hi) contains the unknown elements.
1149 [hi, hi+extra) contains the larger PPs.
1150 */
1151 k = extra >>= 1; /* num PPs to move */
1152 if (extraOnRight) {
1153 /* Swap the smaller PPs to the left end.
1154 Note that this loop actually moves k+1 items:
1155 the last is our PP */
1156 do {
1157 tmp = *lo; *lo = *hi; *hi = tmp;
1158 ++lo; ++hi;
1159 } while (k--);
1160 }
1161 else {
1162 /* Swap the larger PPs to the right end. */
1163 while (k--) {
1164 --lo; --hi;
1165 tmp = *lo; *lo = *hi; *hi = tmp;
1166 }
1167 }
1168 --lo; /* *lo is now our PP */
1169 pivot = *lo;
1170
1171 /* Now an almost-ordinary quicksort partition step.
1172 Note that most of the time is spent here!
1173 Only odd thing is that we partition into < and >=,
1174 instead of the usual <= and >=. This helps when
1175 there are lots of duplicates of different values,
1176 because it eventually tends to make subfiles
1177 "pure" (all duplicates), and we special-case for
1178 duplicates later. */
1179 l = lo + 1;
1180 r = hi - 1;
1181 /* assert lo < l < r < hi (small n weeded out above) */
1182
1183 do {
1184 /* slide l right, looking for key >= pivot */
1185 do {
1186 SETK(*l, pivot);
1187 if (k < 0)
1188 ++l;
1189 else
1190 break;
1191 } while (l < r);
1192
1193 /* slide r left, looking for key < pivot */
1194 while (l < r) {
Guido van Rossum42812581998-06-17 14:15:44 +00001195 register PyObject *rval = *r--;
1196 SETK(rval, pivot);
1197 if (k < 0) {
1198 /* swap and advance */
1199 r[1] = *l;
1200 *l++ = rval;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001201 break;
Guido van Rossum42812581998-06-17 14:15:44 +00001202 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001203 }
1204
1205 } while (l < r);
1206
1207 /* assert lo < r <= l < hi
1208 assert r == l or r+1 == l
1209 everything to the left of l is < pivot, and
1210 everything to the right of r is >= pivot */
1211
1212 if (l == r) {
1213 SETK(*r, pivot);
1214 if (k < 0)
1215 ++l;
1216 else
1217 --r;
1218 }
1219 /* assert lo <= r and r+1 == l and l <= hi
1220 assert r == lo or a[r] < pivot
1221 assert a[lo] is pivot
1222 assert l == hi or a[l] >= pivot
1223 Swap the pivot into "the middle", so we can henceforth
1224 ignore it.
1225 */
1226 *lo = *r;
1227 *r = pivot;
1228
1229 /* The following is true now, & will be preserved:
1230 All in [lo,r) are < pivot
1231 All in [r,l) == pivot (& so can be ignored)
1232 All in [l,hi) are >= pivot */
1233
1234 /* Check for duplicates of the pivot. One compare is
1235 wasted if there are no duplicates, but can win big
1236 when there are.
1237 Tricky: we're sticking to "<" compares, so deduce
1238 equality indirectly. We know pivot <= *l, so they're
1239 equal iff not pivot < *l.
1240 */
1241 while (l < hi) {
1242 /* pivot <= *l known */
1243 SETK(pivot, *l);
1244 if (k < 0)
1245 break;
1246 else
1247 /* <= and not < implies == */
1248 ++l;
1249 }
1250
1251 /* assert lo <= r < l <= hi
1252 Partitions are [lo, r) and [l, hi) */
1253
1254 /* push fattest first; remember we still have extra PPs
1255 to the left of the left chunk and to the right of
1256 the right chunk! */
1257 /* assert top < STACKSIZE */
1258 if (r - lo <= hi - l) {
1259 /* second is bigger */
1260 stack[top].lo = l;
1261 stack[top].hi = hi;
1262 stack[top].extra = -extra;
1263 hi = r;
1264 extraOnRight = 0;
1265 }
1266 else {
1267 /* first is bigger */
1268 stack[top].lo = lo;
1269 stack[top].hi = r;
1270 stack[top].extra = extra;
1271 lo = l;
1272 extraOnRight = 1;
1273 }
1274 ++top;
1275
1276 } /* end of partitioning loop */
1277
1278 return 0;
1279
1280 fail:
1281 return -1;
1282}
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001283
1284#undef SETK
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001285
1286staticforward PyTypeObject immutable_list_type;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001287
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001288static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00001289listsort(PyListObject *self, PyObject *args)
Guido van Rossum3f236de1996-12-10 23:55:39 +00001290{
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001291 int err;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001292 PyObject *compare = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001293 PyTypeObject *savetype;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001294
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001295 if (args != NULL) {
Guido van Rossumc00a9382000-02-24 21:48:29 +00001296 if (!PyArg_ParseTuple(args, "|O:sort", &compare))
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001297 return NULL;
1298 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001299 savetype = self->ob_type;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001300 self->ob_type = &immutable_list_type;
1301 err = samplesortslice(self->ob_item,
1302 self->ob_item + self->ob_size,
Guido van Rossum42812581998-06-17 14:15:44 +00001303 compare);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001304 self->ob_type = savetype;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001305 if (err < 0)
Guido van Rossum3f236de1996-12-10 23:55:39 +00001306 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001307 Py_INCREF(Py_None);
1308 return Py_None;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001309}
1310
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001311int
Fred Drakea2f55112000-07-09 15:16:51 +00001312PyList_Sort(PyObject *v)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001313{
1314 if (v == NULL || !PyList_Check(v)) {
1315 PyErr_BadInternalCall();
1316 return -1;
1317 }
1318 v = listsort((PyListObject *)v, (PyObject *)NULL);
1319 if (v == NULL)
1320 return -1;
1321 Py_DECREF(v);
1322 return 0;
1323}
1324
Guido van Rossumb86c5492001-02-12 22:06:02 +00001325static void
1326_listreverse(PyListObject *self)
Guido van Rossumed98d481991-03-06 13:07:53 +00001327{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001328 register PyObject **p, **q;
1329 register PyObject *tmp;
Guido van Rossumed98d481991-03-06 13:07:53 +00001330
Guido van Rossumed98d481991-03-06 13:07:53 +00001331 if (self->ob_size > 1) {
1332 for (p = self->ob_item, q = self->ob_item + self->ob_size - 1;
Guido van Rossumb86c5492001-02-12 22:06:02 +00001333 p < q;
1334 p++, q--)
1335 {
Guido van Rossumed98d481991-03-06 13:07:53 +00001336 tmp = *p;
1337 *p = *q;
1338 *q = tmp;
1339 }
1340 }
Guido van Rossumb86c5492001-02-12 22:06:02 +00001341}
1342
1343static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001344listreverse(PyListObject *self)
Guido van Rossumb86c5492001-02-12 22:06:02 +00001345{
Guido van Rossumb86c5492001-02-12 22:06:02 +00001346 _listreverse(self);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001347 Py_INCREF(Py_None);
1348 return Py_None;
Guido van Rossumed98d481991-03-06 13:07:53 +00001349}
1350
Guido van Rossum84c76f51990-10-30 13:32:20 +00001351int
Fred Drakea2f55112000-07-09 15:16:51 +00001352PyList_Reverse(PyObject *v)
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00001353{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001354 if (v == NULL || !PyList_Check(v)) {
1355 PyErr_BadInternalCall();
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00001356 return -1;
1357 }
Guido van Rossumb86c5492001-02-12 22:06:02 +00001358 _listreverse((PyListObject *)v);
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00001359 return 0;
1360}
1361
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001362PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00001363PyList_AsTuple(PyObject *v)
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00001364{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001365 PyObject *w;
1366 PyObject **p;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00001367 int n;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001368 if (v == NULL || !PyList_Check(v)) {
1369 PyErr_BadInternalCall();
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00001370 return NULL;
1371 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001372 n = ((PyListObject *)v)->ob_size;
1373 w = PyTuple_New(n);
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00001374 if (w == NULL)
1375 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001376 p = ((PyTupleObject *)w)->ob_item;
Thomas Wouters334fb892000-07-25 12:56:38 +00001377 memcpy((void *)p,
1378 (void *)((PyListObject *)v)->ob_item,
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001379 n*sizeof(PyObject *));
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00001380 while (--n >= 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001381 Py_INCREF(*p);
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00001382 p++;
1383 }
1384 return w;
1385}
1386
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001387static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001388listindex(PyListObject *self, PyObject *v)
Guido van Rossumed98d481991-03-06 13:07:53 +00001389{
1390 int i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001391
Guido van Rossumed98d481991-03-06 13:07:53 +00001392 for (i = 0; i < self->ob_size; i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001393 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
1394 if (cmp > 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001395 return PyInt_FromLong((long)i);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001396 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00001397 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00001398 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001399 PyErr_SetString(PyExc_ValueError, "list.index(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00001400 return NULL;
1401}
1402
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001403static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001404listcount(PyListObject *self, PyObject *v)
Guido van Rossume6f7d181991-10-20 20:20:40 +00001405{
1406 int count = 0;
1407 int i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001408
Guido van Rossume6f7d181991-10-20 20:20:40 +00001409 for (i = 0; i < self->ob_size; i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001410 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
1411 if (cmp > 0)
Guido van Rossume6f7d181991-10-20 20:20:40 +00001412 count++;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001413 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00001414 return NULL;
Guido van Rossume6f7d181991-10-20 20:20:40 +00001415 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001416 return PyInt_FromLong((long)count);
Guido van Rossume6f7d181991-10-20 20:20:40 +00001417}
1418
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001419static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001420listremove(PyListObject *self, PyObject *v)
Guido van Rossumed98d481991-03-06 13:07:53 +00001421{
1422 int i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001423
Guido van Rossumed98d481991-03-06 13:07:53 +00001424 for (i = 0; i < self->ob_size; i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001425 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
1426 if (cmp > 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001427 if (list_ass_slice(self, i, i+1,
1428 (PyObject *)NULL) != 0)
Guido van Rossumed98d481991-03-06 13:07:53 +00001429 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001430 Py_INCREF(Py_None);
1431 return Py_None;
Guido van Rossumed98d481991-03-06 13:07:53 +00001432 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001433 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00001434 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00001435 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001436 PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00001437 return NULL;
1438}
1439
Jeremy Hylton8caad492000-06-23 14:18:11 +00001440static int
1441list_traverse(PyListObject *o, visitproc visit, void *arg)
1442{
1443 int i, err;
1444 PyObject *x;
1445
1446 for (i = o->ob_size; --i >= 0; ) {
1447 x = o->ob_item[i];
1448 if (x != NULL) {
1449 err = visit(x, arg);
1450 if (err)
1451 return err;
1452 }
1453 }
1454 return 0;
1455}
1456
1457static int
1458list_clear(PyListObject *lp)
1459{
1460 (void) PyList_SetSlice((PyObject *)lp, 0, lp->ob_size, 0);
1461 return 0;
1462}
1463
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001464static PyObject *
1465list_richcompare(PyObject *v, PyObject *w, int op)
1466{
1467 PyListObject *vl, *wl;
1468 int i;
1469
1470 if (!PyList_Check(v) || !PyList_Check(w)) {
1471 Py_INCREF(Py_NotImplemented);
1472 return Py_NotImplemented;
1473 }
1474
1475 vl = (PyListObject *)v;
1476 wl = (PyListObject *)w;
1477
1478 if (vl->ob_size != wl->ob_size && (op == Py_EQ || op == Py_NE)) {
1479 /* Shortcut: if the lengths differ, the lists differ */
1480 PyObject *res;
1481 if (op == Py_EQ)
1482 res = Py_False;
1483 else
1484 res = Py_True;
1485 Py_INCREF(res);
1486 return res;
1487 }
1488
1489 /* Search for the first index where items are different */
1490 for (i = 0; i < vl->ob_size && i < wl->ob_size; i++) {
1491 int k = PyObject_RichCompareBool(vl->ob_item[i],
1492 wl->ob_item[i], Py_EQ);
1493 if (k < 0)
1494 return NULL;
1495 if (!k)
1496 break;
1497 }
1498
1499 if (i >= vl->ob_size || i >= wl->ob_size) {
1500 /* No more items to compare -- compare sizes */
1501 int vs = vl->ob_size;
1502 int ws = wl->ob_size;
1503 int cmp;
1504 PyObject *res;
1505 switch (op) {
1506 case Py_LT: cmp = vs < ws; break;
Tim Peters6ee42342001-07-06 17:45:43 +00001507 case Py_LE: cmp = vs <= ws; break;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001508 case Py_EQ: cmp = vs == ws; break;
1509 case Py_NE: cmp = vs != ws; break;
1510 case Py_GT: cmp = vs > ws; break;
1511 case Py_GE: cmp = vs >= ws; break;
1512 default: return NULL; /* cannot happen */
1513 }
1514 if (cmp)
1515 res = Py_True;
1516 else
1517 res = Py_False;
1518 Py_INCREF(res);
1519 return res;
1520 }
1521
1522 /* We have an item that differs -- shortcuts for EQ/NE */
1523 if (op == Py_EQ) {
1524 Py_INCREF(Py_False);
1525 return Py_False;
1526 }
1527 if (op == Py_NE) {
1528 Py_INCREF(Py_True);
1529 return Py_True;
1530 }
1531
1532 /* Compare the final item again using the proper operator */
1533 return PyObject_RichCompare(vl->ob_item[i], wl->ob_item[i], op);
1534}
1535
Tim Peters6d6c1a32001-08-02 04:15:00 +00001536/* Adapted from newer code by Tim */
1537static int
1538list_fill(PyListObject *result, PyObject *v)
1539{
1540 PyObject *it; /* iter(v) */
1541 int n; /* guess for result list size */
1542 int i;
1543
1544 n = result->ob_size;
1545
1546 /* Special-case list(a_list), for speed. */
1547 if (PyList_Check(v)) {
1548 if (v == (PyObject *)result)
1549 return 0; /* source is destination, we're done */
1550 return list_ass_slice(result, 0, n, v);
1551 }
1552
1553 /* Empty previous contents */
1554 if (n != 0) {
1555 if (list_ass_slice(result, 0, n, (PyObject *)NULL) != 0)
1556 return -1;
1557 }
1558
1559 /* Get iterator. There may be some low-level efficiency to be gained
1560 * by caching the tp_iternext slot instead of using PyIter_Next()
1561 * later, but premature optimization is the root etc.
1562 */
1563 it = PyObject_GetIter(v);
1564 if (it == NULL)
1565 return -1;
1566
1567 /* Guess a result list size. */
1568 n = -1; /* unknown */
1569 if (PySequence_Check(v) &&
1570 v->ob_type->tp_as_sequence->sq_length) {
1571 n = PySequence_Size(v);
1572 if (n < 0)
1573 PyErr_Clear();
1574 }
1575 if (n < 0)
1576 n = 8; /* arbitrary */
1577 NRESIZE(result->ob_item, PyObject*, n);
Neal Norwitzd4e5be52002-05-22 23:19:17 +00001578 if (result->ob_item == NULL) {
1579 PyErr_NoMemory();
Tim Peters6d6c1a32001-08-02 04:15:00 +00001580 goto error;
Neal Norwitzd4e5be52002-05-22 23:19:17 +00001581 }
Neal Norwitz35fc7602002-06-13 21:11:11 +00001582 memset(result->ob_item, 0, sizeof(*result->ob_item) * n);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001583 result->ob_size = n;
1584
1585 /* Run iterator to exhaustion. */
1586 for (i = 0; ; i++) {
1587 PyObject *item = PyIter_Next(it);
1588 if (item == NULL) {
1589 if (PyErr_Occurred())
1590 goto error;
1591 break;
1592 }
1593 if (i < n)
1594 PyList_SET_ITEM(result, i, item); /* steals ref */
1595 else {
1596 int status = ins1(result, result->ob_size, item);
1597 Py_DECREF(item); /* append creates a new ref */
1598 if (status < 0)
1599 goto error;
1600 }
1601 }
1602
1603 /* Cut back result list if initial guess was too large. */
1604 if (i < n && result != NULL) {
1605 if (list_ass_slice(result, i, n, (PyObject *)NULL) != 0)
1606 goto error;
1607 }
1608 Py_DECREF(it);
1609 return 0;
1610
1611 error:
1612 Py_DECREF(it);
1613 return -1;
1614}
1615
1616static int
1617list_init(PyListObject *self, PyObject *args, PyObject *kw)
1618{
1619 PyObject *arg = NULL;
1620 static char *kwlist[] = {"sequence", 0};
1621
1622 if (!PyArg_ParseTupleAndKeywords(args, kw, "|O:list", kwlist, &arg))
1623 return -1;
1624 if (arg != NULL)
1625 return list_fill(self, arg);
1626 if (self->ob_size > 0)
1627 return list_ass_slice(self, 0, self->ob_size, (PyObject*)NULL);
1628 return 0;
1629}
1630
Guido van Rossumdbb53d92001-12-03 16:32:18 +00001631static long
1632list_nohash(PyObject *self)
1633{
1634 PyErr_SetString(PyExc_TypeError, "list objects are unhashable");
1635 return -1;
1636}
1637
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001638PyDoc_STRVAR(append_doc,
1639"L.append(object) -- append object to end");
1640PyDoc_STRVAR(extend_doc,
1641"L.extend(list) -- extend list by appending list elements");
1642PyDoc_STRVAR(insert_doc,
1643"L.insert(index, object) -- insert object before index");
1644PyDoc_STRVAR(pop_doc,
1645"L.pop([index]) -> item -- remove and return item at index (default last)");
1646PyDoc_STRVAR(remove_doc,
1647"L.remove(value) -- remove first occurrence of value");
1648PyDoc_STRVAR(index_doc,
1649"L.index(value) -> integer -- return index of first occurrence of value");
1650PyDoc_STRVAR(count_doc,
1651"L.count(value) -> integer -- return number of occurrences of value");
1652PyDoc_STRVAR(reverse_doc,
1653"L.reverse() -- reverse *IN PLACE*");
1654PyDoc_STRVAR(sort_doc,
1655"L.sort([cmpfunc]) -- sort *IN PLACE*; if given, cmpfunc(x, y) -> -1, 0, 1");
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +00001656
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001657static PyMethodDef list_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001658 {"append", (PyCFunction)listappend, METH_O, append_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001659 {"insert", (PyCFunction)listinsert, METH_VARARGS, insert_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001660 {"extend", (PyCFunction)listextend, METH_O, extend_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001661 {"pop", (PyCFunction)listpop, METH_VARARGS, pop_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001662 {"remove", (PyCFunction)listremove, METH_O, remove_doc},
1663 {"index", (PyCFunction)listindex, METH_O, index_doc},
1664 {"count", (PyCFunction)listcount, METH_O, count_doc},
1665 {"reverse", (PyCFunction)listreverse, METH_NOARGS, reverse_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001666 {"sort", (PyCFunction)listsort, METH_VARARGS, sort_doc},
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001667 {NULL, NULL} /* sentinel */
1668};
1669
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001670static PySequenceMethods list_as_sequence = {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001671 (inquiry)list_length, /* sq_length */
1672 (binaryfunc)list_concat, /* sq_concat */
1673 (intargfunc)list_repeat, /* sq_repeat */
1674 (intargfunc)list_item, /* sq_item */
1675 (intintargfunc)list_slice, /* sq_slice */
1676 (intobjargproc)list_ass_item, /* sq_ass_item */
1677 (intintobjargproc)list_ass_slice, /* sq_ass_slice */
1678 (objobjproc)list_contains, /* sq_contains */
1679 (binaryfunc)list_inplace_concat, /* sq_inplace_concat */
1680 (intargfunc)list_inplace_repeat, /* sq_inplace_repeat */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001681};
1682
Neal Norwitz2c2e8272002-06-14 02:04:18 +00001683PyDoc_STRVAR(list_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001684"list() -> new list\n"
Neal Norwitz2c2e8272002-06-14 02:04:18 +00001685"list(sequence) -> new list initialized from sequence's items");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001686
Jeremy Hyltona4b4c3b2002-07-13 03:51:17 +00001687static PyObject *list_iter(PyObject *seq);
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00001688
Jeremy Hyltona4b4c3b2002-07-13 03:51:17 +00001689static PyObject *
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00001690list_subscript(PyListObject* self, PyObject* item)
1691{
1692 if (PyInt_Check(item)) {
1693 long i = PyInt_AS_LONG(item);
1694 if (i < 0)
1695 i += PyList_GET_SIZE(self);
1696 return list_item(self, i);
1697 }
1698 else if (PyLong_Check(item)) {
1699 long i = PyLong_AsLong(item);
1700 if (i == -1 && PyErr_Occurred())
1701 return NULL;
1702 if (i < 0)
1703 i += PyList_GET_SIZE(self);
1704 return list_item(self, i);
1705 }
1706 else if (PySlice_Check(item)) {
1707 int start, stop, step, slicelength, cur, i;
1708 PyObject* result;
1709 PyObject* it;
1710
1711 if (PySlice_GetIndicesEx((PySliceObject*)item, self->ob_size,
1712 &start, &stop, &step, &slicelength) < 0) {
1713 return NULL;
1714 }
1715
1716 if (slicelength <= 0) {
1717 return PyList_New(0);
1718 }
1719 else {
1720 result = PyList_New(slicelength);
1721 if (!result) return NULL;
1722
1723 for (cur = start, i = 0; i < slicelength;
1724 cur += step, i++) {
1725 it = PyList_GET_ITEM(self, cur);
1726 Py_INCREF(it);
1727 PyList_SET_ITEM(result, i, it);
1728 }
1729
1730 return result;
1731 }
1732 }
1733 else {
1734 PyErr_SetString(PyExc_TypeError,
1735 "list indices must be integers");
1736 return NULL;
1737 }
1738}
1739
1740static int
1741list_ass_subscript(PyListObject* self, PyObject* item, PyObject* value)
1742{
1743 if (PyInt_Check(item)) {
1744 long i = PyInt_AS_LONG(item);
1745 if (i < 0)
1746 i += PyList_GET_SIZE(self);
1747 return list_ass_item(self, i, value);
1748 }
1749 else if (PyLong_Check(item)) {
1750 long i = PyLong_AsLong(item);
1751 if (i == -1 && PyErr_Occurred())
1752 return -1;
1753 if (i < 0)
1754 i += PyList_GET_SIZE(self);
1755 return list_ass_item(self, i, value);
1756 }
1757 else if (PySlice_Check(item)) {
1758 int start, stop, step, slicelength;
1759
1760 if (PySlice_GetIndicesEx((PySliceObject*)item, self->ob_size,
1761 &start, &stop, &step, &slicelength) < 0) {
1762 return -1;
1763 }
1764
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00001765 /* treat L[slice(a,b)] = v _exactly_ like L[a:b] = v */
1766 if (step == 1 && ((PySliceObject*)item)->step == Py_None)
1767 return list_ass_slice(self, start, stop, value);
1768
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00001769 if (value == NULL) {
1770 /* delete slice */
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00001771 PyObject **garbage, **it;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00001772 int cur, i, j;
1773
1774 if (slicelength <= 0)
1775 return 0;
1776
1777 if (step < 0) {
1778 stop = start + 1;
1779 start = stop + step*(slicelength - 1) - 1;
1780 step = -step;
1781 }
1782
1783 garbage = (PyObject**)
1784 PyMem_MALLOC(slicelength*sizeof(PyObject*));
1785
1786 /* drawing pictures might help
1787 understand these for loops */
Guido van Rossum75a20b12002-06-11 12:22:28 +00001788 for (cur = start, i = 0;
1789 cur < stop;
1790 cur += step, i++)
1791 {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00001792 garbage[i] = PyList_GET_ITEM(self, cur);
1793
1794 for (j = 0; j < step; j++) {
1795 PyList_SET_ITEM(self, cur + j - i,
Guido van Rossum75a20b12002-06-11 12:22:28 +00001796 PyList_GET_ITEM(self,
1797 cur + j + 1));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00001798 }
1799 }
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00001800 for (cur = start + slicelength*step + 1;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00001801 cur < self->ob_size; cur++) {
1802 PyList_SET_ITEM(self, cur - slicelength,
1803 PyList_GET_ITEM(self, cur));
1804 }
1805 self->ob_size -= slicelength;
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00001806 it = self->ob_item;
1807 NRESIZE(it, PyObject*, self->ob_size);
1808 self->ob_item = it;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00001809
1810 for (i = 0; i < slicelength; i++) {
1811 Py_DECREF(garbage[i]);
1812 }
1813 PyMem_FREE(garbage);
1814
1815 return 0;
1816 }
1817 else {
1818 /* assign slice */
1819 PyObject **garbage, *ins;
1820 int cur, i;
1821
1822 if (!PyList_Check(value)) {
1823 PyErr_Format(PyExc_TypeError,
1824 "must assign list (not \"%.200s\") to slice",
1825 value->ob_type->tp_name);
1826 return -1;
1827 }
1828
1829 if (PyList_GET_SIZE(value) != slicelength) {
1830 PyErr_Format(PyExc_ValueError,
1831 "attempt to assign list of size %d to extended slice of size %d",
1832 PyList_Size(value), slicelength);
1833 return -1;
1834 }
1835
1836 if (!slicelength)
1837 return 0;
1838
1839 /* protect against a[::-1] = a */
1840 if (self == (PyListObject*)value) {
1841 value = list_slice((PyListObject*)value, 0,
1842 PyList_GET_SIZE(value));
1843 }
1844 else {
1845 Py_INCREF(value);
1846 }
1847
1848 garbage = (PyObject**)
1849 PyMem_MALLOC(slicelength*sizeof(PyObject*));
1850
1851 for (cur = start, i = 0; i < slicelength;
1852 cur += step, i++) {
1853 garbage[i] = PyList_GET_ITEM(self, cur);
1854
1855 ins = PyList_GET_ITEM(value, i);
1856 Py_INCREF(ins);
1857 PyList_SET_ITEM(self, cur, ins);
1858 }
1859
1860 for (i = 0; i < slicelength; i++) {
1861 Py_DECREF(garbage[i]);
1862 }
1863
1864 PyMem_FREE(garbage);
1865 Py_DECREF(value);
1866
1867 return 0;
1868 }
1869 }
1870 else {
1871 PyErr_SetString(PyExc_TypeError,
1872 "list indices must be integers");
1873 return -1;
1874 }
1875}
1876
1877static PyMappingMethods list_as_mapping = {
1878 (inquiry)list_length,
1879 (binaryfunc)list_subscript,
1880 (objobjargproc)list_ass_subscript
1881};
1882
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001883PyTypeObject PyList_Type = {
1884 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001885 0,
1886 "list",
Neil Schemenauere83c00e2001-08-29 23:54:21 +00001887 sizeof(PyListObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001888 0,
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001889 (destructor)list_dealloc, /* tp_dealloc */
1890 (printfunc)list_print, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001891 0, /* tp_getattr */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001892 0, /* tp_setattr */
1893 0, /* tp_compare */
1894 (reprfunc)list_repr, /* tp_repr */
1895 0, /* tp_as_number */
1896 &list_as_sequence, /* tp_as_sequence */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00001897 &list_as_mapping, /* tp_as_mapping */
Guido van Rossumdbb53d92001-12-03 16:32:18 +00001898 list_nohash, /* tp_hash */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001899 0, /* tp_call */
1900 0, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001901 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001902 0, /* tp_setattro */
1903 0, /* tp_as_buffer */
Neil Schemenauere83c00e2001-08-29 23:54:21 +00001904 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Tim Peters6d6c1a32001-08-02 04:15:00 +00001905 Py_TPFLAGS_BASETYPE, /* tp_flags */
1906 list_doc, /* tp_doc */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001907 (traverseproc)list_traverse, /* tp_traverse */
1908 (inquiry)list_clear, /* tp_clear */
1909 list_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001910 0, /* tp_weaklistoffset */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00001911 list_iter, /* tp_iter */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001912 0, /* tp_iternext */
1913 list_methods, /* tp_methods */
1914 0, /* tp_members */
1915 0, /* tp_getset */
1916 0, /* tp_base */
1917 0, /* tp_dict */
1918 0, /* tp_descr_get */
1919 0, /* tp_descr_set */
1920 0, /* tp_dictoffset */
1921 (initproc)list_init, /* tp_init */
1922 PyType_GenericAlloc, /* tp_alloc */
1923 PyType_GenericNew, /* tp_new */
Neil Schemenauer99b5d282002-04-12 02:44:22 +00001924 PyObject_GC_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001925};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001926
1927
1928/* During a sort, we really can't have anyone modifying the list; it could
1929 cause core dumps. Thus, we substitute a dummy type that raises an
1930 explanatory exception when a modifying operation is used. Caveat:
1931 comparisons may behave differently; but I guess it's a bad idea anyway to
1932 compare a list that's being sorted... */
1933
1934static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00001935immutable_list_op(void)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001936{
1937 PyErr_SetString(PyExc_TypeError,
1938 "a list cannot be modified while it is being sorted");
1939 return NULL;
1940}
1941
1942static PyMethodDef immutable_list_methods[] = {
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001943 {"append", (PyCFunction)immutable_list_op, METH_VARARGS},
1944 {"insert", (PyCFunction)immutable_list_op, METH_VARARGS},
Tim Peters52e07172001-08-30 06:15:32 +00001945 {"extend", (PyCFunction)immutable_list_op, METH_O},
1946 {"pop", (PyCFunction)immutable_list_op, METH_VARARGS},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001947 {"remove", (PyCFunction)immutable_list_op, METH_VARARGS},
1948 {"index", (PyCFunction)listindex, METH_O},
1949 {"count", (PyCFunction)listcount, METH_O},
1950 {"reverse", (PyCFunction)immutable_list_op, METH_VARARGS},
1951 {"sort", (PyCFunction)immutable_list_op, METH_VARARGS},
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001952 {NULL, NULL} /* sentinel */
1953};
1954
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001955static int
Fred Drakea2f55112000-07-09 15:16:51 +00001956immutable_list_ass(void)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001957{
1958 immutable_list_op();
1959 return -1;
1960}
1961
1962static PySequenceMethods immutable_list_as_sequence = {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001963 (inquiry)list_length, /* sq_length */
1964 (binaryfunc)list_concat, /* sq_concat */
1965 (intargfunc)list_repeat, /* sq_repeat */
1966 (intargfunc)list_item, /* sq_item */
1967 (intintargfunc)list_slice, /* sq_slice */
1968 (intobjargproc)immutable_list_ass, /* sq_ass_item */
1969 (intintobjargproc)immutable_list_ass, /* sq_ass_slice */
1970 (objobjproc)list_contains, /* sq_contains */
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001971};
1972
1973static PyTypeObject immutable_list_type = {
1974 PyObject_HEAD_INIT(&PyType_Type)
1975 0,
1976 "list (immutable, during sort)",
Neil Schemenauere83c00e2001-08-29 23:54:21 +00001977 sizeof(PyListObject),
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001978 0,
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001979 0, /* Cannot happen */ /* tp_dealloc */
1980 (printfunc)list_print, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001981 0, /* tp_getattr */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001982 0, /* tp_setattr */
1983 0, /* Won't be called */ /* tp_compare */
1984 (reprfunc)list_repr, /* tp_repr */
1985 0, /* tp_as_number */
1986 &immutable_list_as_sequence, /* tp_as_sequence */
1987 0, /* tp_as_mapping */
Guido van Rossumdbb53d92001-12-03 16:32:18 +00001988 list_nohash, /* tp_hash */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001989 0, /* tp_call */
1990 0, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001991 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001992 0, /* tp_setattro */
1993 0, /* tp_as_buffer */
Neil Schemenauere83c00e2001-08-29 23:54:21 +00001994 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001995 list_doc, /* tp_doc */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001996 (traverseproc)list_traverse, /* tp_traverse */
1997 0, /* tp_clear */
1998 list_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001999 0, /* tp_weaklistoffset */
2000 0, /* tp_iter */
2001 0, /* tp_iternext */
2002 immutable_list_methods, /* tp_methods */
2003 0, /* tp_members */
2004 0, /* tp_getset */
2005 0, /* tp_base */
2006 0, /* tp_dict */
2007 0, /* tp_descr_get */
2008 0, /* tp_descr_set */
2009 0, /* tp_init */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002010 /* NOTE: This is *not* the standard list_type struct! */
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002011};
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002012
2013
2014/*********************** List Iterator **************************/
2015
2016typedef struct {
2017 PyObject_HEAD
Tim Peters93b2cc42002-06-01 05:22:55 +00002018 long it_index;
2019 PyListObject *it_seq;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002020} listiterobject;
2021
2022PyTypeObject PyListIter_Type;
2023
2024PyObject *
2025list_iter(PyObject *seq)
2026{
2027 listiterobject *it;
2028
2029 if (!PyList_Check(seq)) {
2030 PyErr_BadInternalCall();
2031 return NULL;
2032 }
2033 it = PyObject_GC_New(listiterobject, &PyListIter_Type);
2034 if (it == NULL)
2035 return NULL;
2036 it->it_index = 0;
2037 Py_INCREF(seq);
Tim Peters93b2cc42002-06-01 05:22:55 +00002038 it->it_seq = (PyListObject *)seq;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002039 _PyObject_GC_TRACK(it);
2040 return (PyObject *)it;
2041}
2042
2043static void
2044listiter_dealloc(listiterobject *it)
2045{
2046 _PyObject_GC_UNTRACK(it);
2047 Py_DECREF(it->it_seq);
2048 PyObject_GC_Del(it);
2049}
2050
2051static int
2052listiter_traverse(listiterobject *it, visitproc visit, void *arg)
2053{
Tim Peters93b2cc42002-06-01 05:22:55 +00002054 return visit((PyObject *)it->it_seq, arg);
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002055}
2056
2057
2058static PyObject *
2059listiter_getiter(PyObject *it)
2060{
2061 Py_INCREF(it);
2062 return it;
2063}
2064
2065static PyObject *
Tim Peters93b2cc42002-06-01 05:22:55 +00002066listiter_next(listiterobject *it)
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002067{
Tim Peters93b2cc42002-06-01 05:22:55 +00002068 PyListObject *seq;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002069 PyObject *item;
2070
Tim Peters93b2cc42002-06-01 05:22:55 +00002071 assert(it != NULL);
2072 seq = it->it_seq;
2073 assert(PyList_Check(seq));
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002074
Tim Peters93b2cc42002-06-01 05:22:55 +00002075 if (it->it_index < PyList_GET_SIZE(seq)) {
2076 item = PyList_GET_ITEM(seq, it->it_index);
2077 ++it->it_index;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002078 Py_INCREF(item);
2079 return item;
2080 }
2081 return NULL;
2082}
2083
2084static PyMethodDef listiter_methods[] = {
2085 {"next", (PyCFunction)listiter_next, METH_NOARGS,
2086 "it.next() -- get the next value, or raise StopIteration"},
2087 {NULL, NULL} /* sentinel */
2088};
2089
2090PyTypeObject PyListIter_Type = {
2091 PyObject_HEAD_INIT(&PyType_Type)
2092 0, /* ob_size */
2093 "listiterator", /* tp_name */
2094 sizeof(listiterobject), /* tp_basicsize */
2095 0, /* tp_itemsize */
2096 /* methods */
2097 (destructor)listiter_dealloc, /* tp_dealloc */
2098 0, /* tp_print */
2099 0, /* tp_getattr */
2100 0, /* tp_setattr */
2101 0, /* tp_compare */
2102 0, /* tp_repr */
2103 0, /* tp_as_number */
2104 0, /* tp_as_sequence */
2105 0, /* tp_as_mapping */
2106 0, /* tp_hash */
2107 0, /* tp_call */
2108 0, /* tp_str */
2109 PyObject_GenericGetAttr, /* tp_getattro */
2110 0, /* tp_setattro */
2111 0, /* tp_as_buffer */
2112 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2113 0, /* tp_doc */
2114 (traverseproc)listiter_traverse, /* tp_traverse */
2115 0, /* tp_clear */
2116 0, /* tp_richcompare */
2117 0, /* tp_weaklistoffset */
2118 (getiterfunc)listiter_getiter, /* tp_iter */
2119 (iternextfunc)listiter_next, /* tp_iternext */
2120 listiter_methods, /* tp_methods */
2121 0, /* tp_members */
2122 0, /* tp_getset */
2123 0, /* tp_base */
2124 0, /* tp_dict */
2125 0, /* tp_descr_get */
2126 0, /* tp_descr_set */
2127};
2128