blob: 0087c63521e9baca2de73bda6deb66c7d66313fa [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 Rossumc0b618a1997-05-02 03:12:38 +000012#define ROUNDUP(n, PyTryBlock) \
13 ((((n)+(PyTryBlock)-1)/(PyTryBlock))*(PyTryBlock))
Guido van Rossuma46d51d1995-01-26 22:59:43 +000014
15static int
Fred Drakea2f55112000-07-09 15:16:51 +000016roundupsize(int n)
Guido van Rossuma46d51d1995-01-26 22:59:43 +000017{
18 if (n < 500)
19 return ROUNDUP(n, 10);
20 else
21 return ROUNDUP(n, 100);
22}
23
Guido van Rossuma27d1121997-08-25 18:36:23 +000024#define NRESIZE(var, type, nitems) PyMem_RESIZE(var, type, roundupsize(nitems))
Guido van Rossuma46d51d1995-01-26 22:59:43 +000025
Guido van Rossumc0b618a1997-05-02 03:12:38 +000026PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +000027PyList_New(int size)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000028{
29 int i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +000030 PyListObject *op;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +000031 size_t nbytes;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000032 if (size < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +000033 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000034 return NULL;
35 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +000036 nbytes = size * sizeof(PyObject *);
Guido van Rossum1e28e5e1992-08-19 16:46:30 +000037 /* Check for overflow */
Guido van Rossumc0b618a1997-05-02 03:12:38 +000038 if (nbytes / sizeof(PyObject *) != (size_t)size) {
39 return PyErr_NoMemory();
Guido van Rossum1e28e5e1992-08-19 16:46:30 +000040 }
Guido van Rossumb18618d2000-05-03 23:44:39 +000041 /* PyObject_NewVar is inlined */
Jeremy Hyltond08b4c42000-06-23 19:37:02 +000042 op = (PyListObject *) PyObject_MALLOC(sizeof(PyListObject)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +000043 + PyGC_HEAD_SIZE);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000044 if (op == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +000045 return PyErr_NoMemory();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000046 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +000047 op = (PyListObject *) PyObject_FROM_GC(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000048 if (size <= 0) {
49 op->ob_item = NULL;
50 }
51 else {
Guido van Rossumb18618d2000-05-03 23:44:39 +000052 op->ob_item = (PyObject **) PyMem_MALLOC(nbytes);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000053 if (op->ob_item == NULL) {
Vladimir Marangozov467a67e2000-07-15 03:31:31 +000054 PyObject_FREE(PyObject_AS_GC(op));
Guido van Rossumc0b618a1997-05-02 03:12:38 +000055 return PyErr_NoMemory();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000056 }
57 }
Guido van Rossumb18618d2000-05-03 23:44:39 +000058 PyObject_INIT_VAR(op, &PyList_Type, size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000059 for (i = 0; i < size; i++)
60 op->ob_item[i] = NULL;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +000061 PyObject_GC_Init(op);
Guido van Rossumc0b618a1997-05-02 03:12:38 +000062 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000063}
64
65int
Fred Drakea2f55112000-07-09 15:16:51 +000066PyList_Size(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000067{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000068 if (!PyList_Check(op)) {
69 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000070 return -1;
71 }
72 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +000073 return ((PyListObject *)op) -> ob_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000074}
75
Guido van Rossumc0b618a1997-05-02 03:12:38 +000076static PyObject *indexerr;
Guido van Rossum929f1b81996-08-09 20:51:27 +000077
Guido van Rossumc0b618a1997-05-02 03:12:38 +000078PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +000079PyList_GetItem(PyObject *op, int i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000080{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000081 if (!PyList_Check(op)) {
82 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000083 return NULL;
84 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +000085 if (i < 0 || i >= ((PyListObject *)op) -> ob_size) {
Guido van Rossum929f1b81996-08-09 20:51:27 +000086 if (indexerr == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +000087 indexerr = PyString_FromString(
88 "list index out of range");
89 PyErr_SetObject(PyExc_IndexError, indexerr);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000090 return NULL;
91 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +000092 return ((PyListObject *)op) -> ob_item[i];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000093}
94
95int
Fred Drakea2f55112000-07-09 15:16:51 +000096PyList_SetItem(register PyObject *op, register int i,
97 register PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000098{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000099 register PyObject *olditem;
100 register PyObject **p;
101 if (!PyList_Check(op)) {
102 Py_XDECREF(newitem);
103 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000104 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000105 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000106 if (i < 0 || i >= ((PyListObject *)op) -> ob_size) {
107 Py_XDECREF(newitem);
108 PyErr_SetString(PyExc_IndexError,
109 "list assignment index out of range");
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000110 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000111 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000112 p = ((PyListObject *)op) -> ob_item + i;
Guido van Rossum5fe60581995-03-09 12:12:50 +0000113 olditem = *p;
114 *p = newitem;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000115 Py_XDECREF(olditem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000116 return 0;
117}
118
119static int
Fred Drakea2f55112000-07-09 15:16:51 +0000120ins1(PyListObject *self, int where, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000121{
122 int i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000123 PyObject **items;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000124 if (v == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000125 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000126 return -1;
127 }
Trent Micka5846642000-08-13 22:47:45 +0000128 if (self->ob_size == INT_MAX) {
129 PyErr_SetString(PyExc_OverflowError,
130 "cannot add more objects to list");
131 return -1;
132 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000133 items = self->ob_item;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000134 NRESIZE(items, PyObject *, self->ob_size+1);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000135 if (items == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000136 PyErr_NoMemory();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000137 return -1;
138 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000139 if (where < 0)
140 where = 0;
141 if (where > self->ob_size)
142 where = self->ob_size;
143 for (i = self->ob_size; --i >= where; )
144 items[i+1] = items[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000145 Py_INCREF(v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000146 items[where] = v;
147 self->ob_item = items;
148 self->ob_size++;
149 return 0;
150}
151
152int
Fred Drakea2f55112000-07-09 15:16:51 +0000153PyList_Insert(PyObject *op, int where, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000154{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000155 if (!PyList_Check(op)) {
156 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000157 return -1;
158 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000159 return ins1((PyListObject *)op, where, newitem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000160}
161
162int
Fred Drakea2f55112000-07-09 15:16:51 +0000163PyList_Append(PyObject *op, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000164{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000165 if (!PyList_Check(op)) {
166 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000167 return -1;
168 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000169 return ins1((PyListObject *)op,
170 (int) ((PyListObject *)op)->ob_size, newitem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000171}
172
173/* Methods */
174
175static void
Fred Drakea2f55112000-07-09 15:16:51 +0000176list_dealloc(PyListObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000177{
178 int i;
Guido van Rossumd724b232000-03-13 16:01:29 +0000179 Py_TRASHCAN_SAFE_BEGIN(op)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000180 PyObject_GC_Fini(op);
Jack Jansen7874d1f1995-01-19 12:09:27 +0000181 if (op->ob_item != NULL) {
Guido van Rossumfa717011999-06-09 15:19:34 +0000182 /* Do it backwards, for Christian Tismer.
183 There's a simple test case where somehow this reduces
184 thrashing when a *very* large list is created and
185 immediately deleted. */
186 i = op->ob_size;
187 while (--i >= 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000188 Py_XDECREF(op->ob_item[i]);
Jack Jansen7874d1f1995-01-19 12:09:27 +0000189 }
Guido van Rossumb18618d2000-05-03 23:44:39 +0000190 PyMem_FREE(op->ob_item);
Jack Jansen7874d1f1995-01-19 12:09:27 +0000191 }
Guido van Rossum4cc6ac72000-07-01 01:00:38 +0000192 op = (PyListObject *) PyObject_AS_GC(op);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000193 PyObject_DEL(op);
Guido van Rossumd724b232000-03-13 16:01:29 +0000194 Py_TRASHCAN_SAFE_END(op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000195}
196
Guido van Rossum90933611991-06-07 16:10:43 +0000197static int
Fred Drakea2f55112000-07-09 15:16:51 +0000198list_print(PyListObject *op, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000199{
200 int i;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000201
202 i = Py_ReprEnter((PyObject*)op);
203 if (i != 0) {
204 if (i < 0)
205 return i;
206 fprintf(fp, "[...]");
207 return 0;
208 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000209 fprintf(fp, "[");
Guido van Rossum90933611991-06-07 16:10:43 +0000210 for (i = 0; i < op->ob_size; i++) {
211 if (i > 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000212 fprintf(fp, ", ");
Guido van Rossumfb376de1998-04-10 22:47:27 +0000213 if (PyObject_Print(op->ob_item[i], fp, 0) != 0) {
214 Py_ReprLeave((PyObject *)op);
Guido van Rossum90933611991-06-07 16:10:43 +0000215 return -1;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000216 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000217 }
218 fprintf(fp, "]");
Guido van Rossumfb376de1998-04-10 22:47:27 +0000219 Py_ReprLeave((PyObject *)op);
Guido van Rossum90933611991-06-07 16:10:43 +0000220 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000221}
222
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000223static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000224list_repr(PyListObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000225{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000226 PyObject *s, *comma;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000227 int i;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000228
229 i = Py_ReprEnter((PyObject*)v);
230 if (i != 0) {
231 if (i > 0)
232 return PyString_FromString("[...]");
233 return NULL;
234 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000235 s = PyString_FromString("[");
236 comma = PyString_FromString(", ");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000237 for (i = 0; i < v->ob_size && s != NULL; i++) {
238 if (i > 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000239 PyString_Concat(&s, comma);
240 PyString_ConcatAndDel(&s, PyObject_Repr(v->ob_item[i]));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000241 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000242 Py_XDECREF(comma);
243 PyString_ConcatAndDel(&s, PyString_FromString("]"));
Guido van Rossumfb376de1998-04-10 22:47:27 +0000244 Py_ReprLeave((PyObject *)v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000245 return s;
246}
247
248static int
Fred Drakea2f55112000-07-09 15:16:51 +0000249list_length(PyListObject *a)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000250{
251 return a->ob_size;
252}
253
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000254
255
256static int
Fred Drakea2f55112000-07-09 15:16:51 +0000257list_contains(PyListObject *a, PyObject *el)
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000258{
Guido van Rossum65e1cea2001-01-17 22:11:59 +0000259 int i;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000260
261 for (i = 0; i < a->ob_size; ++i) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +0000262 int cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i),
263 Py_EQ);
264 if (cmp > 0)
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000265 return 1;
Guido van Rossum65e1cea2001-01-17 22:11:59 +0000266 else if (cmp < 0)
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000267 return -1;
268 }
269 return 0;
270}
271
272
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000273static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000274list_item(PyListObject *a, int i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000275{
276 if (i < 0 || i >= a->ob_size) {
Guido van Rossum929f1b81996-08-09 20:51:27 +0000277 if (indexerr == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000278 indexerr = PyString_FromString(
279 "list index out of range");
280 PyErr_SetObject(PyExc_IndexError, indexerr);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000281 return NULL;
282 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000283 Py_INCREF(a->ob_item[i]);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000284 return a->ob_item[i];
285}
286
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000287static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000288list_slice(PyListObject *a, int ilow, int ihigh)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000289{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000290 PyListObject *np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000291 int i;
292 if (ilow < 0)
293 ilow = 0;
294 else if (ilow > a->ob_size)
295 ilow = a->ob_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000296 if (ihigh < ilow)
297 ihigh = ilow;
298 else if (ihigh > a->ob_size)
299 ihigh = a->ob_size;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000300 np = (PyListObject *) PyList_New(ihigh - ilow);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000301 if (np == NULL)
302 return NULL;
303 for (i = ilow; i < ihigh; i++) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000304 PyObject *v = a->ob_item[i];
305 Py_INCREF(v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000306 np->ob_item[i - ilow] = v;
307 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000308 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000309}
310
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000311PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000312PyList_GetSlice(PyObject *a, int ilow, int ihigh)
Guido van Rossum234f9421993-06-17 12:35:49 +0000313{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000314 if (!PyList_Check(a)) {
315 PyErr_BadInternalCall();
Guido van Rossum234f9421993-06-17 12:35:49 +0000316 return NULL;
317 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000318 return list_slice((PyListObject *)a, ilow, ihigh);
Guido van Rossum234f9421993-06-17 12:35:49 +0000319}
320
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000321static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000322list_concat(PyListObject *a, PyObject *bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000323{
324 int size;
325 int i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000326 PyListObject *np;
327 if (!PyList_Check(bb)) {
Fred Drakeb6a9ada2000-06-01 03:12:13 +0000328 PyErr_Format(PyExc_TypeError,
Fred Drake914a2ed2000-06-01 14:31:03 +0000329 "can only concatenate list (not \"%.200s\") to list",
330 bb->ob_type->tp_name);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000331 return NULL;
332 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000333#define b ((PyListObject *)bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000334 size = a->ob_size + b->ob_size;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000335 np = (PyListObject *) PyList_New(size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000336 if (np == NULL) {
Guido van Rossum90933611991-06-07 16:10:43 +0000337 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000338 }
339 for (i = 0; i < a->ob_size; i++) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000340 PyObject *v = a->ob_item[i];
341 Py_INCREF(v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000342 np->ob_item[i] = v;
343 }
344 for (i = 0; i < b->ob_size; i++) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000345 PyObject *v = b->ob_item[i];
346 Py_INCREF(v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000347 np->ob_item[i + a->ob_size] = v;
348 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000349 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000350#undef b
351}
352
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000353static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000354list_repeat(PyListObject *a, int n)
Guido van Rossumed98d481991-03-06 13:07:53 +0000355{
356 int i, j;
357 int size;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000358 PyListObject *np;
359 PyObject **p;
Guido van Rossumed98d481991-03-06 13:07:53 +0000360 if (n < 0)
361 n = 0;
362 size = a->ob_size * n;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000363 np = (PyListObject *) PyList_New(size);
Guido van Rossumed98d481991-03-06 13:07:53 +0000364 if (np == NULL)
365 return NULL;
366 p = np->ob_item;
367 for (i = 0; i < n; i++) {
368 for (j = 0; j < a->ob_size; j++) {
369 *p = a->ob_item[j];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000370 Py_INCREF(*p);
Guido van Rossumed98d481991-03-06 13:07:53 +0000371 p++;
372 }
373 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000374 return (PyObject *) np;
Guido van Rossumed98d481991-03-06 13:07:53 +0000375}
376
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000377static int
Fred Drakea2f55112000-07-09 15:16:51 +0000378list_ass_slice(PyListObject *a, int ilow, int ihigh, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000379{
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000380 /* Because [X]DECREF can recursively invoke list operations on
381 this list, we must postpone all [X]DECREF activity until
382 after the list is back in its canonical shape. Therefore
383 we must allocate an additional array, 'recycle', into which
384 we temporarily copy the items that are deleted from the
385 list. :-( */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000386 PyObject **recycle, **p;
387 PyObject **item;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000388 int n; /* Size of replacement list */
389 int d; /* Change in size */
390 int k; /* Loop index */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000391#define b ((PyListObject *)v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000392 if (v == NULL)
393 n = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000394 else if (PyList_Check(v)) {
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000395 n = b->ob_size;
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000396 if (a == b) {
397 /* Special case "a[i:j] = a" -- copy b first */
398 int ret;
399 v = list_slice(b, 0, n);
400 ret = list_ass_slice(a, ilow, ihigh, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000401 Py_DECREF(v);
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000402 return ret;
403 }
404 }
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000405 else {
Fred Drakeb6a9ada2000-06-01 03:12:13 +0000406 PyErr_Format(PyExc_TypeError,
407 "must assign list (not \"%.200s\") to slice",
408 v->ob_type->tp_name);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000409 return -1;
410 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000411 if (ilow < 0)
412 ilow = 0;
413 else if (ilow > a->ob_size)
414 ilow = a->ob_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000415 if (ihigh < ilow)
416 ihigh = ilow;
417 else if (ihigh > a->ob_size)
418 ihigh = a->ob_size;
419 item = a->ob_item;
420 d = n - (ihigh-ilow);
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000421 if (ihigh > ilow)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000422 p = recycle = PyMem_NEW(PyObject *, (ihigh-ilow));
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000423 else
424 p = recycle = NULL;
425 if (d <= 0) { /* Delete -d items; recycle ihigh-ilow items */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000426 for (k = ilow; k < ihigh; k++)
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000427 *p++ = item[k];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000428 if (d < 0) {
429 for (/*k = ihigh*/; k < a->ob_size; k++)
430 item[k+d] = item[k];
431 a->ob_size += d;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000432 NRESIZE(item, PyObject *, a->ob_size); /* Can't fail */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000433 a->ob_item = item;
434 }
435 }
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000436 else { /* Insert d items; recycle ihigh-ilow items */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000437 NRESIZE(item, PyObject *, a->ob_size + d);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000438 if (item == NULL) {
Guido van Rossumb18618d2000-05-03 23:44:39 +0000439 if (recycle != NULL)
440 PyMem_DEL(recycle);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000441 PyErr_NoMemory();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000442 return -1;
443 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000444 for (k = a->ob_size; --k >= ihigh; )
445 item[k+d] = item[k];
446 for (/*k = ihigh-1*/; k >= ilow; --k)
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000447 *p++ = item[k];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000448 a->ob_item = item;
449 a->ob_size += d;
450 }
451 for (k = 0; k < n; k++, ilow++) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000452 PyObject *w = b->ob_item[k];
453 Py_XINCREF(w);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000454 item[ilow] = w;
455 }
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000456 if (recycle) {
457 while (--p >= recycle)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000458 Py_XDECREF(*p);
459 PyMem_DEL(recycle);
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000460 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000461 return 0;
462#undef b
463}
464
Guido van Rossum234f9421993-06-17 12:35:49 +0000465int
Fred Drakea2f55112000-07-09 15:16:51 +0000466PyList_SetSlice(PyObject *a, int ilow, int ihigh, PyObject *v)
Guido van Rossum234f9421993-06-17 12:35:49 +0000467{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000468 if (!PyList_Check(a)) {
469 PyErr_BadInternalCall();
Guido van Rossum1fc238a1993-07-29 08:25:09 +0000470 return -1;
Guido van Rossum234f9421993-06-17 12:35:49 +0000471 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000472 return list_ass_slice((PyListObject *)a, ilow, ihigh, v);
Guido van Rossum234f9421993-06-17 12:35:49 +0000473}
474
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000475static PyObject *
476list_inplace_repeat(PyListObject *self, int n)
477{
478 PyObject **items;
479 int size, i, j;
480
481
482 size = PyList_GET_SIZE(self);
483 if (size == 0) {
484 Py_INCREF(self);
485 return (PyObject *)self;
486 }
487
488 items = self->ob_item;
489
490 if (n < 1) {
491 self->ob_item = NULL;
492 self->ob_size = 0;
493 for (i = 0; i < size; i++)
494 Py_XDECREF(items[i]);
495 PyMem_DEL(items);
496 Py_INCREF(self);
497 return (PyObject *)self;
498 }
499
500 NRESIZE(items, PyObject*, size*n);
501 if (items == NULL) {
502 PyErr_NoMemory();
503 goto finally;
504 }
505 self->ob_item = items;
506 for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */
507 for (j = 0; j < size; j++) {
508 PyObject *o = PyList_GET_ITEM(self, j);
509 Py_INCREF(o);
510 PyList_SET_ITEM(self, self->ob_size++, o);
511 }
512 }
513 Py_INCREF(self);
514 return (PyObject *)self;
515 finally:
516 return NULL;
517}
518
Guido van Rossum4a450d01991-04-03 19:05:18 +0000519static int
Fred Drakea2f55112000-07-09 15:16:51 +0000520list_ass_item(PyListObject *a, int i, PyObject *v)
Guido van Rossum4a450d01991-04-03 19:05:18 +0000521{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000522 PyObject *old_value;
Guido van Rossum4a450d01991-04-03 19:05:18 +0000523 if (i < 0 || i >= a->ob_size) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000524 PyErr_SetString(PyExc_IndexError,
525 "list assignment index out of range");
Guido van Rossum4a450d01991-04-03 19:05:18 +0000526 return -1;
527 }
528 if (v == NULL)
529 return list_ass_slice(a, i, i+1, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000530 Py_INCREF(v);
Guido van Rossumd7047b31995-01-02 19:07:15 +0000531 old_value = a->ob_item[i];
Guido van Rossum4a450d01991-04-03 19:05:18 +0000532 a->ob_item[i] = v;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000533 Py_DECREF(old_value);
Guido van Rossum4a450d01991-04-03 19:05:18 +0000534 return 0;
535}
536
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000537static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000538ins(PyListObject *self, int where, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000539{
540 if (ins1(self, where, v) != 0)
541 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000542 Py_INCREF(Py_None);
543 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000544}
545
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000546static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000547listinsert(PyListObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000548{
549 int i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000550 PyObject *v;
Guido van Rossumc00a9382000-02-24 21:48:29 +0000551 if (!PyArg_ParseTuple(args, "iO:insert", &i, &v))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000552 return NULL;
Guido van Rossumbf80e541993-02-08 15:49:17 +0000553 return ins(self, i, v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000554}
555
Guido van Rossumef93b872000-03-13 15:41:59 +0000556/* Define NO_STRICT_LIST_APPEND to enable multi-argument append() */
557
558#ifndef NO_STRICT_LIST_APPEND
559#define PyArg_ParseTuple_Compat1 PyArg_ParseTuple
560#else
561#define PyArg_ParseTuple_Compat1(args, format, ret) \
562( \
563 PyTuple_GET_SIZE(args) > 1 ? (*ret = args, 1) : \
564 PyTuple_GET_SIZE(args) == 1 ? (*ret = PyTuple_GET_ITEM(args, 0), 1) : \
565 PyArg_ParseTuple(args, format, ret) \
566)
567#endif
568
569
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000570static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000571listappend(PyListObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000572{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000573 PyObject *v;
Guido van Rossumef93b872000-03-13 15:41:59 +0000574 if (!PyArg_ParseTuple_Compat1(args, "O:append", &v))
Guido van Rossumbf80e541993-02-08 15:49:17 +0000575 return NULL;
576 return ins(self, (int) self->ob_size, v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000577}
578
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000579static int
580listextend_internal(PyListObject *self, PyObject *b)
Barry Warsawdedf6d61998-10-09 16:37:25 +0000581{
Barry Warsawdedf6d61998-10-09 16:37:25 +0000582 PyObject **items;
583 int selflen = PyList_GET_SIZE(self);
584 int blen;
585 register int i;
586
Jeremy Hyltondb60bb52001-01-03 22:32:16 +0000587 if (PyObject_Size(b) == 0) {
Barry Warsawdedf6d61998-10-09 16:37:25 +0000588 /* short circuit when b is empty */
Jeremy Hyltondb60bb52001-01-03 22:32:16 +0000589 Py_DECREF(b);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000590 return 0;
Jeremy Hyltondb60bb52001-01-03 22:32:16 +0000591 }
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000592
Barry Warsawdedf6d61998-10-09 16:37:25 +0000593 if (self == (PyListObject*)b) {
594 /* as in list_ass_slice() we must special case the
595 * situation: a.extend(a)
596 *
597 * XXX: I think this way ought to be faster than using
598 * list_slice() the way list_ass_slice() does.
599 */
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000600 Py_DECREF(b);
Barry Warsawdedf6d61998-10-09 16:37:25 +0000601 b = PyList_New(selflen);
602 if (!b)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000603 return -1;
Barry Warsawdedf6d61998-10-09 16:37:25 +0000604 for (i = 0; i < selflen; i++) {
605 PyObject *o = PyList_GET_ITEM(self, i);
606 Py_INCREF(o);
607 PyList_SET_ITEM(b, i, o);
608 }
609 }
Barry Warsawdedf6d61998-10-09 16:37:25 +0000610
Jeremy Hylton03657cf2000-07-12 13:05:33 +0000611 blen = PyObject_Size(b);
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000612
Barry Warsawdedf6d61998-10-09 16:37:25 +0000613 /* resize a using idiom */
614 items = self->ob_item;
615 NRESIZE(items, PyObject*, selflen + blen);
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000616 if (items == NULL) {
Barry Warsawdedf6d61998-10-09 16:37:25 +0000617 PyErr_NoMemory();
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000618 Py_DECREF(b);
619 return -1;
Barry Warsawdedf6d61998-10-09 16:37:25 +0000620 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000621
Barry Warsawdedf6d61998-10-09 16:37:25 +0000622 self->ob_item = items;
623
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000624 /* populate the end of self with b's items */
Barry Warsawdedf6d61998-10-09 16:37:25 +0000625 for (i = 0; i < blen; i++) {
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000626 PyObject *o = PySequence_Fast_GET_ITEM(b, i);
Barry Warsawdedf6d61998-10-09 16:37:25 +0000627 Py_INCREF(o);
628 PyList_SET_ITEM(self, self->ob_size++, o);
629 }
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000630 Py_DECREF(b);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000631 return 0;
Barry Warsawdedf6d61998-10-09 16:37:25 +0000632}
633
634
635static PyObject *
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000636list_inplace_concat(PyListObject *self, PyObject *other)
637{
638 other = PySequence_Fast(other, "argument to += must be a sequence");
639 if (!other)
640 return NULL;
641
642 if (listextend_internal(self, other) < 0)
643 return NULL;
644
645 Py_INCREF(self);
646 return (PyObject *)self;
647}
648
649static PyObject *
650listextend(PyListObject *self, PyObject *args)
651{
652
653 PyObject *b;
654
655 if (!PyArg_ParseTuple(args, "O:extend", &b))
656 return NULL;
657
658 b = PySequence_Fast(b, "list.extend() argument must be a sequence");
659 if (!b)
660 return NULL;
661
662 if (listextend_internal(self, b) < 0)
663 return NULL;
664
665 Py_INCREF(Py_None);
666 return Py_None;
667}
668
669static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000670listpop(PyListObject *self, PyObject *args)
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000671{
672 int i = -1;
673 PyObject *v;
Guido van Rossumc00a9382000-02-24 21:48:29 +0000674 if (!PyArg_ParseTuple(args, "|i:pop", &i))
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000675 return NULL;
676 if (self->ob_size == 0) {
677 /* Special-case most common failure cause */
678 PyErr_SetString(PyExc_IndexError, "pop from empty list");
679 return NULL;
680 }
681 if (i < 0)
682 i += self->ob_size;
683 if (i < 0 || i >= self->ob_size) {
684 PyErr_SetString(PyExc_IndexError, "pop index out of range");
685 return NULL;
686 }
687 v = self->ob_item[i];
688 Py_INCREF(v);
689 if (list_ass_slice(self, i, i+1, (PyObject *)NULL) != 0) {
690 Py_DECREF(v);
691 return NULL;
692 }
693 return v;
694}
695
Guido van Rossum3f236de1996-12-10 23:55:39 +0000696/* New quicksort implementation for arrays of object pointers.
697 Thanks to discussions with Tim Peters. */
698
699/* CMPERROR is returned by our comparison function when an error
700 occurred. This is the largest negative integer (0x80000000 on a
701 32-bit system). */
Guido van Rossum19700b61997-03-05 00:45:43 +0000702#define CMPERROR ( (int) ((unsigned int)1 << (8*sizeof(int) - 1)) )
Guido van Rossum3f236de1996-12-10 23:55:39 +0000703
704/* Comparison function. Takes care of calling a user-supplied
705 comparison function (any callable Python object). Calls the
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000706 standard comparison function, PyObject_Compare(), if the user-
707 supplied function is NULL. */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000708
709static int
Fred Drakea2f55112000-07-09 15:16:51 +0000710docompare(PyObject *x, PyObject *y, PyObject *compare)
Guido van Rossum3f236de1996-12-10 23:55:39 +0000711{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000712 PyObject *args, *res;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000713 int i;
714
Guido van Rossumc8b6df91997-05-23 00:06:51 +0000715 if (compare == NULL) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +0000716 /* NOTE: we rely on the fact here that the sorting algorithm
717 only ever checks whether k<0, i.e., whether x<y. So we
718 invoke the rich comparison function with Py_LT ('<'), and
719 return -1 when it returns true and 0 when it returns
720 false. */
721 i = PyObject_RichCompareBool(x, y, Py_LT);
722 if (i < 0)
723 return CMPERROR;
724 else
725 return -i;
Guido van Rossumc8b6df91997-05-23 00:06:51 +0000726 }
Guido van Rossum3f236de1996-12-10 23:55:39 +0000727
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000728 args = Py_BuildValue("(OO)", x, y);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000729 if (args == NULL)
730 return CMPERROR;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000731 res = PyEval_CallObject(compare, args);
732 Py_DECREF(args);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000733 if (res == NULL)
734 return CMPERROR;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000735 if (!PyInt_Check(res)) {
736 Py_DECREF(res);
737 PyErr_SetString(PyExc_TypeError,
Guido van Rossum9bcd1d71999-04-19 17:44:39 +0000738 "comparison function must return int");
Guido van Rossum3f236de1996-12-10 23:55:39 +0000739 return CMPERROR;
740 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000741 i = PyInt_AsLong(res);
742 Py_DECREF(res);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000743 if (i < 0)
744 return -1;
745 if (i > 0)
746 return 1;
747 return 0;
748}
749
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000750/* MINSIZE is the smallest array that will get a full-blown samplesort
751 treatment; smaller arrays are sorted using binary insertion. It must
752 be at least 7 for the samplesort implementation to work. Binary
753 insertion does fewer compares, but can suffer O(N**2) data movement.
754 The more expensive compares, the larger MINSIZE should be. */
755#define MINSIZE 100
756
757/* MINPARTITIONSIZE is the smallest array slice samplesort will bother to
758 partition; smaller slices are passed to binarysort. It must be at
759 least 2, and no larger than MINSIZE. Setting it higher reduces the #
760 of compares slowly, but increases the amount of data movement quickly.
761 The value here was chosen assuming a compare costs ~25x more than
762 swapping a pair of memory-resident pointers -- but under that assumption,
763 changing the value by a few dozen more or less has aggregate effect
764 under 1%. So the value is crucial, but not touchy <wink>. */
765#define MINPARTITIONSIZE 40
766
767/* MAXMERGE is the largest number of elements we'll always merge into
768 a known-to-be sorted chunk via binary insertion, regardless of the
769 size of that chunk. Given a chunk of N sorted elements, and a group
770 of K unknowns, the largest K for which it's better to do insertion
771 (than a full-blown sort) is a complicated function of N and K mostly
772 involving the expected number of compares and data moves under each
773 approach, and the relative cost of those operations on a specific
774 architecure. The fixed value here is conservative, and should be a
775 clear win regardless of architecture or N. */
776#define MAXMERGE 15
Guido van Rossum3f236de1996-12-10 23:55:39 +0000777
Guido van Rossum3f236de1996-12-10 23:55:39 +0000778/* STACKSIZE is the size of our work stack. A rough estimate is that
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000779 this allows us to sort arrays of size N where
780 N / ln(N) = MINPARTITIONSIZE * 2**STACKSIZE, so 60 is more than enough
781 for arrays of size 2**64. Because we push the biggest partition
782 first, the worst case occurs when all subarrays are always partitioned
783 exactly in two. */
784#define STACKSIZE 60
Guido van Rossum3f236de1996-12-10 23:55:39 +0000785
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000786
787#define SETK(X,Y) if ((k = docompare(X,Y,compare))==CMPERROR) goto fail
788
789/* binarysort is the best method for sorting small arrays: it does
790 few compares, but can do data movement quadratic in the number of
791 elements.
Guido van Rossum42812581998-06-17 14:15:44 +0000792 [lo, hi) is a contiguous slice of a list, and is sorted via
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000793 binary insertion.
794 On entry, must have lo <= start <= hi, and that [lo, start) is already
795 sorted (pass start == lo if you don't know!).
796 If docompare complains (returns CMPERROR) return -1, else 0.
797 Even in case of error, the output slice will be some permutation of
798 the input (nothing is lost or duplicated).
799*/
Guido van Rossum3f236de1996-12-10 23:55:39 +0000800
801static int
Fred Drakea2f55112000-07-09 15:16:51 +0000802binarysort(PyObject **lo, PyObject **hi, PyObject **start, PyObject *compare)
803 /* compare -- comparison function object, or NULL for default */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000804{
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000805 /* assert lo <= start <= hi
806 assert [lo, start) is sorted */
807 register int k;
808 register PyObject **l, **p, **r;
809 register PyObject *pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000810
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000811 if (lo == start)
812 ++start;
813 for (; start < hi; ++start) {
814 /* set l to where *start belongs */
815 l = lo;
816 r = start;
Guido van Rossuma119c0d1998-05-29 17:56:32 +0000817 pivot = *r;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000818 do {
819 p = l + ((r - l) >> 1);
820 SETK(pivot, *p);
821 if (k < 0)
822 r = p;
823 else
824 l = p + 1;
825 } while (l < r);
826 /* Pivot should go at l -- slide over to make room.
827 Caution: using memmove is much slower under MSVC 5;
828 we're not usually moving many slots. */
829 for (p = start; p > l; --p)
830 *p = *(p-1);
831 *l = pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000832 }
Guido van Rossum3f236de1996-12-10 23:55:39 +0000833 return 0;
Guido van Rossuma119c0d1998-05-29 17:56:32 +0000834
835 fail:
836 return -1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000837}
838
839/* samplesortslice is the sorting workhorse.
Guido van Rossum42812581998-06-17 14:15:44 +0000840 [lo, hi) is a contiguous slice of a list, to be sorted in place.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000841 On entry, must have lo <= hi,
842 If docompare complains (returns CMPERROR) return -1, else 0.
843 Even in case of error, the output slice will be some permutation of
844 the input (nothing is lost or duplicated).
845
846 samplesort is basically quicksort on steroids: a power of 2 close
847 to n/ln(n) is computed, and that many elements (less 1) are picked at
848 random from the array and sorted. These 2**k - 1 elements are then
849 used as preselected pivots for an equal number of quicksort
850 partitioning steps, partitioning the slice into 2**k chunks each of
851 size about ln(n). These small final chunks are then usually handled
852 by binarysort. Note that when k=1, this is roughly the same as an
853 ordinary quicksort using a random pivot, and when k=2 this is roughly
854 a median-of-3 quicksort. From that view, using k ~= lg(n/ln(n)) makes
855 this a "median of n/ln(n)" quicksort. You can also view it as a kind
856 of bucket sort, where 2**k-1 bucket boundaries are picked dynamically.
857
858 The large number of samples makes a quadratic-time case almost
859 impossible, and asymptotically drives the average-case number of
860 compares from quicksort's 2 N ln N (or 12/7 N ln N for the median-of-
861 3 variant) down to N lg N.
862
863 We also play lots of low-level tricks to cut the number of compares.
864
865 Very obscure: To avoid using extra memory, the PPs are stored in the
866 array and shuffled around as partitioning proceeds. At the start of a
867 partitioning step, we'll have 2**m-1 (for some m) PPs in sorted order,
868 adjacent (either on the left or the right!) to a chunk of X elements
869 that are to be partitioned: P X or X P. In either case we need to
870 shuffle things *in place* so that the 2**(m-1) smaller PPs are on the
871 left, followed by the PP to be used for this step (that's the middle
872 of the PPs), followed by X, followed by the 2**(m-1) larger PPs:
873 P X or X P -> Psmall pivot X Plarge
874 and the order of the PPs must not be altered. It can take a while
875 to realize this isn't trivial! It can take even longer <wink> to
876 understand why the simple code below works, using only 2**(m-1) swaps.
877 The key is that the order of the X elements isn't necessarily
878 preserved: X can end up as some cyclic permutation of its original
879 order. That's OK, because X is unsorted anyway. If the order of X
880 had to be preserved too, the simplest method I know of using O(1)
881 scratch storage requires len(X) + 2**(m-1) swaps, spread over 2 passes.
882 Since len(X) is typically several times larger than 2**(m-1), that
883 would slow things down.
884*/
885
886struct SamplesortStackNode {
887 /* Represents a slice of the array, from (& including) lo up
888 to (but excluding) hi. "extra" additional & adjacent elements
889 are pre-selected pivots (PPs), spanning [lo-extra, lo) if
890 extra > 0, or [hi, hi-extra) if extra < 0. The PPs are
891 already sorted, but nothing is known about the other elements
892 in [lo, hi). |extra| is always one less than a power of 2.
893 When extra is 0, we're out of PPs, and the slice must be
894 sorted by some other means. */
895 PyObject **lo;
896 PyObject **hi;
897 int extra;
898};
899
900/* 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 +0000901 N / ln(N) as possible. So k ~= lg(N / ln(N)). Calling libm routines
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000902 is undesirable, so cutoff values are canned in the "cutoff" table
903 below: cutoff[i] is the smallest N such that k == CUTOFFBASE + i. */
904#define CUTOFFBASE 4
Guido van Rossum3aa23fd1999-01-14 19:01:53 +0000905static long cutoff[] = {
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000906 43, /* smallest N such that k == 4 */
907 106, /* etc */
908 250,
909 576,
910 1298,
911 2885,
912 6339,
913 13805,
914 29843,
915 64116,
916 137030,
917 291554,
918 617916,
919 1305130,
920 2748295,
921 5771662,
922 12091672,
923 25276798,
924 52734615,
925 109820537,
926 228324027,
927 473977813,
928 982548444, /* smallest N such that k == 26 */
929 2034159050 /* largest N that fits in signed 32-bit; k == 27 */
930};
931
932static int
Fred Drakea2f55112000-07-09 15:16:51 +0000933samplesortslice(PyObject **lo, PyObject **hi, PyObject *compare)
934 /* compare -- comparison function object, or NULL for default */
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000935{
936 register PyObject **l, **r;
937 register PyObject *tmp, *pivot;
938 register int k;
939 int n, extra, top, extraOnRight;
940 struct SamplesortStackNode stack[STACKSIZE];
941
942 /* assert lo <= hi */
943 n = hi - lo;
944
945 /* ----------------------------------------------------------
946 * Special cases
947 * --------------------------------------------------------*/
948 if (n < 2)
949 return 0;
950
951 /* Set r to the largest value such that [lo,r) is sorted.
952 This catches the already-sorted case, the all-the-same
953 case, and the appended-a-few-elements-to-a-sorted-list case.
954 If the array is unsorted, we're very likely to get out of
955 the loop fast, so the test is cheap if it doesn't pay off.
956 */
957 /* assert lo < hi */
958 for (r = lo+1; r < hi; ++r) {
959 SETK(*r, *(r-1));
960 if (k < 0)
961 break;
962 }
963 /* [lo,r) is sorted, [r,hi) unknown. Get out cheap if there are
964 few unknowns, or few elements in total. */
965 if (hi - r <= MAXMERGE || n < MINSIZE)
Guido van Rossum42812581998-06-17 14:15:44 +0000966 return binarysort(lo, hi, r, compare);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000967
968 /* Check for the array already being reverse-sorted. Typical
969 benchmark-driven silliness <wink>. */
970 /* assert lo < hi */
971 for (r = lo+1; r < hi; ++r) {
972 SETK(*(r-1), *r);
973 if (k < 0)
974 break;
975 }
976 if (hi - r <= MAXMERGE) {
977 /* Reverse the reversed prefix, then insert the tail */
978 PyObject **originalr = r;
979 l = lo;
980 do {
981 --r;
982 tmp = *l; *l = *r; *r = tmp;
983 ++l;
984 } while (l < r);
Guido van Rossum42812581998-06-17 14:15:44 +0000985 return binarysort(lo, hi, originalr, compare);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000986 }
987
988 /* ----------------------------------------------------------
989 * Normal case setup: a large array without obvious pattern.
990 * --------------------------------------------------------*/
991
992 /* extra := a power of 2 ~= n/ln(n), less 1.
993 First find the smallest extra s.t. n < cutoff[extra] */
994 for (extra = 0;
995 extra < sizeof(cutoff) / sizeof(cutoff[0]);
996 ++extra) {
997 if (n < cutoff[extra])
998 break;
999 /* note that if we fall out of the loop, the value of
1000 extra still makes *sense*, but may be smaller than
1001 we would like (but the array has more than ~= 2**31
1002 elements in this case!) */
1003 }
1004 /* Now k == extra - 1 + CUTOFFBASE. The smallest value k can
1005 have is CUTOFFBASE-1, so
1006 assert MINSIZE >= 2**(CUTOFFBASE-1) - 1 */
1007 extra = (1 << (extra - 1 + CUTOFFBASE)) - 1;
1008 /* assert extra > 0 and n >= extra */
1009
1010 /* Swap that many values to the start of the array. The
1011 selection of elements is pseudo-random, but the same on
1012 every run (this is intentional! timing algorithm changes is
1013 a pain if timing varies across runs). */
1014 {
1015 unsigned int seed = n / extra; /* arbitrary */
1016 unsigned int i;
1017 for (i = 0; i < (unsigned)extra; ++i) {
1018 /* j := random int in [i, n) */
1019 unsigned int j;
1020 seed = seed * 69069 + 7;
1021 j = i + seed % (n - i);
1022 tmp = lo[i]; lo[i] = lo[j]; lo[j] = tmp;
1023 }
1024 }
1025
1026 /* Recursively sort the preselected pivots. */
Guido van Rossum42812581998-06-17 14:15:44 +00001027 if (samplesortslice(lo, lo + extra, compare) < 0)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001028 goto fail;
1029
1030 top = 0; /* index of available stack slot */
1031 lo += extra; /* point to first unknown */
1032 extraOnRight = 0; /* the PPs are at the left end */
1033
1034 /* ----------------------------------------------------------
1035 * Partition [lo, hi), and repeat until out of work.
1036 * --------------------------------------------------------*/
1037 for (;;) {
1038 /* assert lo <= hi, so n >= 0 */
1039 n = hi - lo;
1040
1041 /* We may not want, or may not be able, to partition:
1042 If n is small, it's quicker to insert.
1043 If extra is 0, we're out of pivots, and *must* use
1044 another method.
1045 */
1046 if (n < MINPARTITIONSIZE || extra == 0) {
1047 if (n >= MINSIZE) {
1048 /* assert extra == 0
1049 This is rare, since the average size
1050 of a final block is only about
1051 ln(original n). */
Guido van Rossum42812581998-06-17 14:15:44 +00001052 if (samplesortslice(lo, hi, compare) < 0)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001053 goto fail;
1054 }
1055 else {
1056 /* Binary insertion should be quicker,
1057 and we can take advantage of the PPs
1058 already being sorted. */
1059 if (extraOnRight && extra) {
1060 /* swap the PPs to the left end */
1061 k = extra;
1062 do {
1063 tmp = *lo;
1064 *lo = *hi;
1065 *hi = tmp;
1066 ++lo; ++hi;
1067 } while (--k);
1068 }
1069 if (binarysort(lo - extra, hi, lo,
Guido van Rossum42812581998-06-17 14:15:44 +00001070 compare) < 0)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001071 goto fail;
1072 }
1073
1074 /* Find another slice to work on. */
1075 if (--top < 0)
1076 break; /* no more -- done! */
1077 lo = stack[top].lo;
1078 hi = stack[top].hi;
1079 extra = stack[top].extra;
1080 extraOnRight = 0;
1081 if (extra < 0) {
1082 extraOnRight = 1;
1083 extra = -extra;
1084 }
1085 continue;
1086 }
1087
1088 /* Pretend the PPs are indexed 0, 1, ..., extra-1.
1089 Then our preselected pivot is at (extra-1)/2, and we
1090 want to move the PPs before that to the left end of
1091 the slice, and the PPs after that to the right end.
1092 The following section changes extra, lo, hi, and the
1093 slice such that:
1094 [lo-extra, lo) contains the smaller PPs.
1095 *lo == our PP.
1096 (lo, hi) contains the unknown elements.
1097 [hi, hi+extra) contains the larger PPs.
1098 */
1099 k = extra >>= 1; /* num PPs to move */
1100 if (extraOnRight) {
1101 /* Swap the smaller PPs to the left end.
1102 Note that this loop actually moves k+1 items:
1103 the last is our PP */
1104 do {
1105 tmp = *lo; *lo = *hi; *hi = tmp;
1106 ++lo; ++hi;
1107 } while (k--);
1108 }
1109 else {
1110 /* Swap the larger PPs to the right end. */
1111 while (k--) {
1112 --lo; --hi;
1113 tmp = *lo; *lo = *hi; *hi = tmp;
1114 }
1115 }
1116 --lo; /* *lo is now our PP */
1117 pivot = *lo;
1118
1119 /* Now an almost-ordinary quicksort partition step.
1120 Note that most of the time is spent here!
1121 Only odd thing is that we partition into < and >=,
1122 instead of the usual <= and >=. This helps when
1123 there are lots of duplicates of different values,
1124 because it eventually tends to make subfiles
1125 "pure" (all duplicates), and we special-case for
1126 duplicates later. */
1127 l = lo + 1;
1128 r = hi - 1;
1129 /* assert lo < l < r < hi (small n weeded out above) */
1130
1131 do {
1132 /* slide l right, looking for key >= pivot */
1133 do {
1134 SETK(*l, pivot);
1135 if (k < 0)
1136 ++l;
1137 else
1138 break;
1139 } while (l < r);
1140
1141 /* slide r left, looking for key < pivot */
1142 while (l < r) {
Guido van Rossum42812581998-06-17 14:15:44 +00001143 register PyObject *rval = *r--;
1144 SETK(rval, pivot);
1145 if (k < 0) {
1146 /* swap and advance */
1147 r[1] = *l;
1148 *l++ = rval;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001149 break;
Guido van Rossum42812581998-06-17 14:15:44 +00001150 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001151 }
1152
1153 } while (l < r);
1154
1155 /* assert lo < r <= l < hi
1156 assert r == l or r+1 == l
1157 everything to the left of l is < pivot, and
1158 everything to the right of r is >= pivot */
1159
1160 if (l == r) {
1161 SETK(*r, pivot);
1162 if (k < 0)
1163 ++l;
1164 else
1165 --r;
1166 }
1167 /* assert lo <= r and r+1 == l and l <= hi
1168 assert r == lo or a[r] < pivot
1169 assert a[lo] is pivot
1170 assert l == hi or a[l] >= pivot
1171 Swap the pivot into "the middle", so we can henceforth
1172 ignore it.
1173 */
1174 *lo = *r;
1175 *r = pivot;
1176
1177 /* The following is true now, & will be preserved:
1178 All in [lo,r) are < pivot
1179 All in [r,l) == pivot (& so can be ignored)
1180 All in [l,hi) are >= pivot */
1181
1182 /* Check for duplicates of the pivot. One compare is
1183 wasted if there are no duplicates, but can win big
1184 when there are.
1185 Tricky: we're sticking to "<" compares, so deduce
1186 equality indirectly. We know pivot <= *l, so they're
1187 equal iff not pivot < *l.
1188 */
1189 while (l < hi) {
1190 /* pivot <= *l known */
1191 SETK(pivot, *l);
1192 if (k < 0)
1193 break;
1194 else
1195 /* <= and not < implies == */
1196 ++l;
1197 }
1198
1199 /* assert lo <= r < l <= hi
1200 Partitions are [lo, r) and [l, hi) */
1201
1202 /* push fattest first; remember we still have extra PPs
1203 to the left of the left chunk and to the right of
1204 the right chunk! */
1205 /* assert top < STACKSIZE */
1206 if (r - lo <= hi - l) {
1207 /* second is bigger */
1208 stack[top].lo = l;
1209 stack[top].hi = hi;
1210 stack[top].extra = -extra;
1211 hi = r;
1212 extraOnRight = 0;
1213 }
1214 else {
1215 /* first is bigger */
1216 stack[top].lo = lo;
1217 stack[top].hi = r;
1218 stack[top].extra = extra;
1219 lo = l;
1220 extraOnRight = 1;
1221 }
1222 ++top;
1223
1224 } /* end of partitioning loop */
1225
1226 return 0;
1227
1228 fail:
1229 return -1;
1230}
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001231
1232#undef SETK
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001233
1234staticforward PyTypeObject immutable_list_type;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001235
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001236static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00001237listsort(PyListObject *self, PyObject *args)
Guido van Rossum3f236de1996-12-10 23:55:39 +00001238{
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001239 int err;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001240 PyObject *compare = NULL;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001241
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001242 if (args != NULL) {
Guido van Rossumc00a9382000-02-24 21:48:29 +00001243 if (!PyArg_ParseTuple(args, "|O:sort", &compare))
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001244 return NULL;
1245 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001246 self->ob_type = &immutable_list_type;
1247 err = samplesortslice(self->ob_item,
1248 self->ob_item + self->ob_size,
Guido van Rossum42812581998-06-17 14:15:44 +00001249 compare);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001250 self->ob_type = &PyList_Type;
1251 if (err < 0)
Guido van Rossum3f236de1996-12-10 23:55:39 +00001252 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001253 Py_INCREF(Py_None);
1254 return Py_None;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001255}
1256
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001257int
Fred Drakea2f55112000-07-09 15:16:51 +00001258PyList_Sort(PyObject *v)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001259{
1260 if (v == NULL || !PyList_Check(v)) {
1261 PyErr_BadInternalCall();
1262 return -1;
1263 }
1264 v = listsort((PyListObject *)v, (PyObject *)NULL);
1265 if (v == NULL)
1266 return -1;
1267 Py_DECREF(v);
1268 return 0;
1269}
1270
Guido van Rossumb86c5492001-02-12 22:06:02 +00001271static void
1272_listreverse(PyListObject *self)
Guido van Rossumed98d481991-03-06 13:07:53 +00001273{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001274 register PyObject **p, **q;
1275 register PyObject *tmp;
Guido van Rossumed98d481991-03-06 13:07:53 +00001276
Guido van Rossumed98d481991-03-06 13:07:53 +00001277 if (self->ob_size > 1) {
1278 for (p = self->ob_item, q = self->ob_item + self->ob_size - 1;
Guido van Rossumb86c5492001-02-12 22:06:02 +00001279 p < q;
1280 p++, q--)
1281 {
Guido van Rossumed98d481991-03-06 13:07:53 +00001282 tmp = *p;
1283 *p = *q;
1284 *q = tmp;
1285 }
1286 }
Guido van Rossumb86c5492001-02-12 22:06:02 +00001287}
1288
1289static PyObject *
1290listreverse(PyListObject *self, PyObject *args)
1291{
1292 if (!PyArg_ParseTuple(args, ":reverse"))
1293 return NULL;
1294 _listreverse(self);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001295 Py_INCREF(Py_None);
1296 return Py_None;
Guido van Rossumed98d481991-03-06 13:07:53 +00001297}
1298
Guido van Rossum84c76f51990-10-30 13:32:20 +00001299int
Fred Drakea2f55112000-07-09 15:16:51 +00001300PyList_Reverse(PyObject *v)
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00001301{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001302 if (v == NULL || !PyList_Check(v)) {
1303 PyErr_BadInternalCall();
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00001304 return -1;
1305 }
Guido van Rossumb86c5492001-02-12 22:06:02 +00001306 _listreverse((PyListObject *)v);
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00001307 return 0;
1308}
1309
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001310PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00001311PyList_AsTuple(PyObject *v)
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00001312{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001313 PyObject *w;
1314 PyObject **p;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00001315 int n;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001316 if (v == NULL || !PyList_Check(v)) {
1317 PyErr_BadInternalCall();
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00001318 return NULL;
1319 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001320 n = ((PyListObject *)v)->ob_size;
1321 w = PyTuple_New(n);
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00001322 if (w == NULL)
1323 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001324 p = ((PyTupleObject *)w)->ob_item;
Thomas Wouters334fb892000-07-25 12:56:38 +00001325 memcpy((void *)p,
1326 (void *)((PyListObject *)v)->ob_item,
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001327 n*sizeof(PyObject *));
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00001328 while (--n >= 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001329 Py_INCREF(*p);
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00001330 p++;
1331 }
1332 return w;
1333}
1334
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001335static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00001336listindex(PyListObject *self, PyObject *args)
Guido van Rossumed98d481991-03-06 13:07:53 +00001337{
1338 int i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001339 PyObject *v;
1340
Guido van Rossumef93b872000-03-13 15:41:59 +00001341 if (!PyArg_ParseTuple_Compat1(args, "O:index", &v))
Guido van Rossumed98d481991-03-06 13:07:53 +00001342 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00001343 for (i = 0; i < self->ob_size; i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001344 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
1345 if (cmp > 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001346 return PyInt_FromLong((long)i);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001347 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00001348 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00001349 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001350 PyErr_SetString(PyExc_ValueError, "list.index(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00001351 return NULL;
1352}
1353
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001354static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00001355listcount(PyListObject *self, PyObject *args)
Guido van Rossume6f7d181991-10-20 20:20:40 +00001356{
1357 int count = 0;
1358 int i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001359 PyObject *v;
1360
Guido van Rossumef93b872000-03-13 15:41:59 +00001361 if (!PyArg_ParseTuple_Compat1(args, "O:count", &v))
Guido van Rossume6f7d181991-10-20 20:20:40 +00001362 return NULL;
Guido van Rossume6f7d181991-10-20 20:20:40 +00001363 for (i = 0; i < self->ob_size; i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001364 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
1365 if (cmp > 0)
Guido van Rossume6f7d181991-10-20 20:20:40 +00001366 count++;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001367 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00001368 return NULL;
Guido van Rossume6f7d181991-10-20 20:20:40 +00001369 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001370 return PyInt_FromLong((long)count);
Guido van Rossume6f7d181991-10-20 20:20:40 +00001371}
1372
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001373static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00001374listremove(PyListObject *self, PyObject *args)
Guido van Rossumed98d481991-03-06 13:07:53 +00001375{
1376 int i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001377 PyObject *v;
1378
Guido van Rossumef93b872000-03-13 15:41:59 +00001379 if (!PyArg_ParseTuple_Compat1(args, "O:remove", &v))
Guido van Rossumed98d481991-03-06 13:07:53 +00001380 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00001381 for (i = 0; i < self->ob_size; i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001382 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
1383 if (cmp > 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001384 if (list_ass_slice(self, i, i+1,
1385 (PyObject *)NULL) != 0)
Guido van Rossumed98d481991-03-06 13:07:53 +00001386 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001387 Py_INCREF(Py_None);
1388 return Py_None;
Guido van Rossumed98d481991-03-06 13:07:53 +00001389 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001390 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00001391 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00001392 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001393 PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00001394 return NULL;
1395}
1396
Jeremy Hylton8caad492000-06-23 14:18:11 +00001397static int
1398list_traverse(PyListObject *o, visitproc visit, void *arg)
1399{
1400 int i, err;
1401 PyObject *x;
1402
1403 for (i = o->ob_size; --i >= 0; ) {
1404 x = o->ob_item[i];
1405 if (x != NULL) {
1406 err = visit(x, arg);
1407 if (err)
1408 return err;
1409 }
1410 }
1411 return 0;
1412}
1413
1414static int
1415list_clear(PyListObject *lp)
1416{
1417 (void) PyList_SetSlice((PyObject *)lp, 0, lp->ob_size, 0);
1418 return 0;
1419}
1420
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001421static PyObject *
1422list_richcompare(PyObject *v, PyObject *w, int op)
1423{
1424 PyListObject *vl, *wl;
1425 int i;
1426
1427 if (!PyList_Check(v) || !PyList_Check(w)) {
1428 Py_INCREF(Py_NotImplemented);
1429 return Py_NotImplemented;
1430 }
1431
1432 vl = (PyListObject *)v;
1433 wl = (PyListObject *)w;
1434
1435 if (vl->ob_size != wl->ob_size && (op == Py_EQ || op == Py_NE)) {
1436 /* Shortcut: if the lengths differ, the lists differ */
1437 PyObject *res;
1438 if (op == Py_EQ)
1439 res = Py_False;
1440 else
1441 res = Py_True;
1442 Py_INCREF(res);
1443 return res;
1444 }
1445
1446 /* Search for the first index where items are different */
1447 for (i = 0; i < vl->ob_size && i < wl->ob_size; i++) {
1448 int k = PyObject_RichCompareBool(vl->ob_item[i],
1449 wl->ob_item[i], Py_EQ);
1450 if (k < 0)
1451 return NULL;
1452 if (!k)
1453 break;
1454 }
1455
1456 if (i >= vl->ob_size || i >= wl->ob_size) {
1457 /* No more items to compare -- compare sizes */
1458 int vs = vl->ob_size;
1459 int ws = wl->ob_size;
1460 int cmp;
1461 PyObject *res;
1462 switch (op) {
1463 case Py_LT: cmp = vs < ws; break;
1464 case Py_LE: cmp = ws <= ws; break;
1465 case Py_EQ: cmp = vs == ws; break;
1466 case Py_NE: cmp = vs != ws; break;
1467 case Py_GT: cmp = vs > ws; break;
1468 case Py_GE: cmp = vs >= ws; break;
1469 default: return NULL; /* cannot happen */
1470 }
1471 if (cmp)
1472 res = Py_True;
1473 else
1474 res = Py_False;
1475 Py_INCREF(res);
1476 return res;
1477 }
1478
1479 /* We have an item that differs -- shortcuts for EQ/NE */
1480 if (op == Py_EQ) {
1481 Py_INCREF(Py_False);
1482 return Py_False;
1483 }
1484 if (op == Py_NE) {
1485 Py_INCREF(Py_True);
1486 return Py_True;
1487 }
1488
1489 /* Compare the final item again using the proper operator */
1490 return PyObject_RichCompare(vl->ob_item[i], wl->ob_item[i], op);
1491}
1492
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +00001493static char append_doc[] =
1494"L.append(object) -- append object to end";
Barry Warsawdedf6d61998-10-09 16:37:25 +00001495static char extend_doc[] =
1496"L.extend(list) -- extend list by appending list elements";
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +00001497static char insert_doc[] =
1498"L.insert(index, object) -- insert object before index";
1499static char pop_doc[] =
1500"L.pop([index]) -> item -- remove and return item at index (default last)";
1501static char remove_doc[] =
1502"L.remove(value) -- remove first occurrence of value";
1503static char index_doc[] =
1504"L.index(value) -> integer -- return index of first occurrence of value";
1505static char count_doc[] =
1506"L.count(value) -> integer -- return number of occurrences of value";
1507static char reverse_doc[] =
1508"L.reverse() -- reverse *IN PLACE*";
1509static char sort_doc[] =
1510"L.sort([cmpfunc]) -- sort *IN PLACE*; if given, cmpfunc(x, y) -> -1, 0, 1";
1511
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001512static PyMethodDef list_methods[] = {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001513 {"append", (PyCFunction)listappend, METH_VARARGS, append_doc},
1514 {"insert", (PyCFunction)listinsert, METH_VARARGS, insert_doc},
1515 {"extend", (PyCFunction)listextend, METH_VARARGS, extend_doc},
1516 {"pop", (PyCFunction)listpop, METH_VARARGS, pop_doc},
1517 {"remove", (PyCFunction)listremove, METH_VARARGS, remove_doc},
1518 {"index", (PyCFunction)listindex, METH_VARARGS, index_doc},
1519 {"count", (PyCFunction)listcount, METH_VARARGS, count_doc},
Tim Peters0e76ab22000-12-13 22:35:46 +00001520 {"reverse", (PyCFunction)listreverse, METH_VARARGS, reverse_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001521 {"sort", (PyCFunction)listsort, METH_VARARGS, sort_doc},
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001522 {NULL, NULL} /* sentinel */
1523};
1524
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001525static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00001526list_getattr(PyListObject *f, char *name)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001527{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001528 return Py_FindMethod(list_methods, (PyObject *)f, name);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001529}
1530
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001531static PySequenceMethods list_as_sequence = {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001532 (inquiry)list_length, /* sq_length */
1533 (binaryfunc)list_concat, /* sq_concat */
1534 (intargfunc)list_repeat, /* sq_repeat */
1535 (intargfunc)list_item, /* sq_item */
1536 (intintargfunc)list_slice, /* sq_slice */
1537 (intobjargproc)list_ass_item, /* sq_ass_item */
1538 (intintobjargproc)list_ass_slice, /* sq_ass_slice */
1539 (objobjproc)list_contains, /* sq_contains */
1540 (binaryfunc)list_inplace_concat, /* sq_inplace_concat */
1541 (intargfunc)list_inplace_repeat, /* sq_inplace_repeat */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001542};
1543
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001544PyTypeObject PyList_Type = {
1545 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001546 0,
1547 "list",
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001548 sizeof(PyListObject) + PyGC_HEAD_SIZE,
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001549 0,
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001550 (destructor)list_dealloc, /* tp_dealloc */
1551 (printfunc)list_print, /* tp_print */
1552 (getattrfunc)list_getattr, /* tp_getattr */
1553 0, /* tp_setattr */
1554 0, /* tp_compare */
1555 (reprfunc)list_repr, /* tp_repr */
1556 0, /* tp_as_number */
1557 &list_as_sequence, /* tp_as_sequence */
1558 0, /* tp_as_mapping */
1559 0, /* tp_hash */
1560 0, /* tp_call */
1561 0, /* tp_str */
1562 0, /* tp_getattro */
1563 0, /* tp_setattro */
1564 0, /* tp_as_buffer */
1565 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_GC, /* tp_flags */
1566 0, /* tp_doc */
1567 (traverseproc)list_traverse, /* tp_traverse */
1568 (inquiry)list_clear, /* tp_clear */
1569 list_richcompare, /* tp_richcompare */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001570};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001571
1572
1573/* During a sort, we really can't have anyone modifying the list; it could
1574 cause core dumps. Thus, we substitute a dummy type that raises an
1575 explanatory exception when a modifying operation is used. Caveat:
1576 comparisons may behave differently; but I guess it's a bad idea anyway to
1577 compare a list that's being sorted... */
1578
1579static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00001580immutable_list_op(void)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001581{
1582 PyErr_SetString(PyExc_TypeError,
1583 "a list cannot be modified while it is being sorted");
1584 return NULL;
1585}
1586
1587static PyMethodDef immutable_list_methods[] = {
1588 {"append", (PyCFunction)immutable_list_op},
1589 {"insert", (PyCFunction)immutable_list_op},
1590 {"remove", (PyCFunction)immutable_list_op},
1591 {"index", (PyCFunction)listindex},
1592 {"count", (PyCFunction)listcount},
1593 {"reverse", (PyCFunction)immutable_list_op},
1594 {"sort", (PyCFunction)immutable_list_op},
1595 {NULL, NULL} /* sentinel */
1596};
1597
1598static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00001599immutable_list_getattr(PyListObject *f, char *name)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001600{
1601 return Py_FindMethod(immutable_list_methods, (PyObject *)f, name);
1602}
1603
1604static int
Fred Drakea2f55112000-07-09 15:16:51 +00001605immutable_list_ass(void)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001606{
1607 immutable_list_op();
1608 return -1;
1609}
1610
1611static PySequenceMethods immutable_list_as_sequence = {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001612 (inquiry)list_length, /* sq_length */
1613 (binaryfunc)list_concat, /* sq_concat */
1614 (intargfunc)list_repeat, /* sq_repeat */
1615 (intargfunc)list_item, /* sq_item */
1616 (intintargfunc)list_slice, /* sq_slice */
1617 (intobjargproc)immutable_list_ass, /* sq_ass_item */
1618 (intintobjargproc)immutable_list_ass, /* sq_ass_slice */
1619 (objobjproc)list_contains, /* sq_contains */
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001620};
1621
1622static PyTypeObject immutable_list_type = {
1623 PyObject_HEAD_INIT(&PyType_Type)
1624 0,
1625 "list (immutable, during sort)",
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001626 sizeof(PyListObject) + PyGC_HEAD_SIZE,
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001627 0,
Guido van Rossum65e1cea2001-01-17 22:11:59 +00001628 0, /* Cannot happen */ /* tp_dealloc */
1629 (printfunc)list_print, /* tp_print */
1630 (getattrfunc)immutable_list_getattr, /* tp_getattr */
1631 0, /* tp_setattr */
1632 0, /* Won't be called */ /* tp_compare */
1633 (reprfunc)list_repr, /* tp_repr */
1634 0, /* tp_as_number */
1635 &immutable_list_as_sequence, /* tp_as_sequence */
1636 0, /* tp_as_mapping */
1637 0, /* tp_hash */
1638 0, /* tp_call */
1639 0, /* tp_str */
1640 0, /* tp_getattro */
1641 0, /* tp_setattro */
1642 0, /* tp_as_buffer */
1643 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_GC, /* tp_flags */
1644 0, /* tp_doc */
1645 (traverseproc)list_traverse, /* tp_traverse */
1646 0, /* tp_clear */
1647 list_richcompare, /* tp_richcompare */
1648 /* NOTE: This is *not* the standard list_type struct! */
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001649};