blob: 59b1912a803edef1cdd663f4cbff3079edb55c9e [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_compare(PyListObject *v, PyListObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000250{
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000251 int i;
Jack Jansene9791602000-08-22 21:51:22 +0000252
Guido van Rossumae621ff1998-05-28 20:18:46 +0000253 for (i = 0; i < v->ob_size && i < w->ob_size; i++) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000254 int cmp = PyObject_Compare(v->ob_item[i], w->ob_item[i]);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000255 if (cmp != 0)
256 return cmp;
257 }
258 return v->ob_size - w->ob_size;
259}
260
261static int
Fred Drakea2f55112000-07-09 15:16:51 +0000262list_length(PyListObject *a)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000263{
264 return a->ob_size;
265}
266
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000267
268
269static int
Fred Drakea2f55112000-07-09 15:16:51 +0000270list_contains(PyListObject *a, PyObject *el)
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000271{
272 int i, cmp;
273
274 for (i = 0; i < a->ob_size; ++i) {
275 cmp = PyObject_Compare(el, PyList_GET_ITEM(a, i));
276 if (cmp == 0)
277 return 1;
278 if (PyErr_Occurred())
279 return -1;
280 }
281 return 0;
282}
283
284
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000285static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000286list_item(PyListObject *a, int i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000287{
288 if (i < 0 || i >= a->ob_size) {
Guido van Rossum929f1b81996-08-09 20:51:27 +0000289 if (indexerr == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000290 indexerr = PyString_FromString(
291 "list index out of range");
292 PyErr_SetObject(PyExc_IndexError, indexerr);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000293 return NULL;
294 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000295 Py_INCREF(a->ob_item[i]);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000296 return a->ob_item[i];
297}
298
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000299static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000300list_slice(PyListObject *a, int ilow, int ihigh)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000301{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000302 PyListObject *np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000303 int i;
304 if (ilow < 0)
305 ilow = 0;
306 else if (ilow > a->ob_size)
307 ilow = a->ob_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000308 if (ihigh < ilow)
309 ihigh = ilow;
310 else if (ihigh > a->ob_size)
311 ihigh = a->ob_size;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000312 np = (PyListObject *) PyList_New(ihigh - ilow);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000313 if (np == NULL)
314 return NULL;
315 for (i = ilow; i < ihigh; i++) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000316 PyObject *v = a->ob_item[i];
317 Py_INCREF(v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000318 np->ob_item[i - ilow] = v;
319 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000320 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000321}
322
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000323PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000324PyList_GetSlice(PyObject *a, int ilow, int ihigh)
Guido van Rossum234f9421993-06-17 12:35:49 +0000325{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000326 if (!PyList_Check(a)) {
327 PyErr_BadInternalCall();
Guido van Rossum234f9421993-06-17 12:35:49 +0000328 return NULL;
329 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000330 return list_slice((PyListObject *)a, ilow, ihigh);
Guido van Rossum234f9421993-06-17 12:35:49 +0000331}
332
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000333static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000334list_concat(PyListObject *a, PyObject *bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000335{
336 int size;
337 int i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000338 PyListObject *np;
339 if (!PyList_Check(bb)) {
Fred Drakeb6a9ada2000-06-01 03:12:13 +0000340 PyErr_Format(PyExc_TypeError,
Fred Drake914a2ed2000-06-01 14:31:03 +0000341 "can only concatenate list (not \"%.200s\") to list",
342 bb->ob_type->tp_name);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000343 return NULL;
344 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000345#define b ((PyListObject *)bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000346 size = a->ob_size + b->ob_size;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000347 np = (PyListObject *) PyList_New(size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000348 if (np == NULL) {
Guido van Rossum90933611991-06-07 16:10:43 +0000349 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000350 }
351 for (i = 0; i < a->ob_size; i++) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000352 PyObject *v = a->ob_item[i];
353 Py_INCREF(v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000354 np->ob_item[i] = v;
355 }
356 for (i = 0; i < b->ob_size; i++) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000357 PyObject *v = b->ob_item[i];
358 Py_INCREF(v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000359 np->ob_item[i + a->ob_size] = v;
360 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000361 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000362#undef b
363}
364
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000365static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000366list_repeat(PyListObject *a, int n)
Guido van Rossumed98d481991-03-06 13:07:53 +0000367{
368 int i, j;
369 int size;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000370 PyListObject *np;
371 PyObject **p;
Guido van Rossumed98d481991-03-06 13:07:53 +0000372 if (n < 0)
373 n = 0;
374 size = a->ob_size * n;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000375 np = (PyListObject *) PyList_New(size);
Guido van Rossumed98d481991-03-06 13:07:53 +0000376 if (np == NULL)
377 return NULL;
378 p = np->ob_item;
379 for (i = 0; i < n; i++) {
380 for (j = 0; j < a->ob_size; j++) {
381 *p = a->ob_item[j];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000382 Py_INCREF(*p);
Guido van Rossumed98d481991-03-06 13:07:53 +0000383 p++;
384 }
385 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000386 return (PyObject *) np;
Guido van Rossumed98d481991-03-06 13:07:53 +0000387}
388
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000389static int
Fred Drakea2f55112000-07-09 15:16:51 +0000390list_ass_slice(PyListObject *a, int ilow, int ihigh, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000391{
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000392 /* Because [X]DECREF can recursively invoke list operations on
393 this list, we must postpone all [X]DECREF activity until
394 after the list is back in its canonical shape. Therefore
395 we must allocate an additional array, 'recycle', into which
396 we temporarily copy the items that are deleted from the
397 list. :-( */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000398 PyObject **recycle, **p;
399 PyObject **item;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000400 int n; /* Size of replacement list */
401 int d; /* Change in size */
402 int k; /* Loop index */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000403#define b ((PyListObject *)v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000404 if (v == NULL)
405 n = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000406 else if (PyList_Check(v)) {
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000407 n = b->ob_size;
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000408 if (a == b) {
409 /* Special case "a[i:j] = a" -- copy b first */
410 int ret;
411 v = list_slice(b, 0, n);
412 ret = list_ass_slice(a, ilow, ihigh, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000413 Py_DECREF(v);
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000414 return ret;
415 }
416 }
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000417 else {
Fred Drakeb6a9ada2000-06-01 03:12:13 +0000418 PyErr_Format(PyExc_TypeError,
419 "must assign list (not \"%.200s\") to slice",
420 v->ob_type->tp_name);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000421 return -1;
422 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000423 if (ilow < 0)
424 ilow = 0;
425 else if (ilow > a->ob_size)
426 ilow = a->ob_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000427 if (ihigh < ilow)
428 ihigh = ilow;
429 else if (ihigh > a->ob_size)
430 ihigh = a->ob_size;
431 item = a->ob_item;
432 d = n - (ihigh-ilow);
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000433 if (ihigh > ilow)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000434 p = recycle = PyMem_NEW(PyObject *, (ihigh-ilow));
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000435 else
436 p = recycle = NULL;
437 if (d <= 0) { /* Delete -d items; recycle ihigh-ilow items */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000438 for (k = ilow; k < ihigh; k++)
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000439 *p++ = item[k];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000440 if (d < 0) {
441 for (/*k = ihigh*/; k < a->ob_size; k++)
442 item[k+d] = item[k];
443 a->ob_size += d;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000444 NRESIZE(item, PyObject *, a->ob_size); /* Can't fail */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000445 a->ob_item = item;
446 }
447 }
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000448 else { /* Insert d items; recycle ihigh-ilow items */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000449 NRESIZE(item, PyObject *, a->ob_size + d);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000450 if (item == NULL) {
Guido van Rossumb18618d2000-05-03 23:44:39 +0000451 if (recycle != NULL)
452 PyMem_DEL(recycle);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000453 PyErr_NoMemory();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000454 return -1;
455 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000456 for (k = a->ob_size; --k >= ihigh; )
457 item[k+d] = item[k];
458 for (/*k = ihigh-1*/; k >= ilow; --k)
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000459 *p++ = item[k];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000460 a->ob_item = item;
461 a->ob_size += d;
462 }
463 for (k = 0; k < n; k++, ilow++) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000464 PyObject *w = b->ob_item[k];
465 Py_XINCREF(w);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000466 item[ilow] = w;
467 }
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000468 if (recycle) {
469 while (--p >= recycle)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000470 Py_XDECREF(*p);
471 PyMem_DEL(recycle);
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000472 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000473 return 0;
474#undef b
475}
476
Guido van Rossum234f9421993-06-17 12:35:49 +0000477int
Fred Drakea2f55112000-07-09 15:16:51 +0000478PyList_SetSlice(PyObject *a, int ilow, int ihigh, PyObject *v)
Guido van Rossum234f9421993-06-17 12:35:49 +0000479{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000480 if (!PyList_Check(a)) {
481 PyErr_BadInternalCall();
Guido van Rossum1fc238a1993-07-29 08:25:09 +0000482 return -1;
Guido van Rossum234f9421993-06-17 12:35:49 +0000483 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000484 return list_ass_slice((PyListObject *)a, ilow, ihigh, v);
Guido van Rossum234f9421993-06-17 12:35:49 +0000485}
486
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000487static PyObject *
488list_inplace_repeat(PyListObject *self, int n)
489{
490 PyObject **items;
491 int size, i, j;
492
493
494 size = PyList_GET_SIZE(self);
495 if (size == 0) {
496 Py_INCREF(self);
497 return (PyObject *)self;
498 }
499
500 items = self->ob_item;
501
502 if (n < 1) {
503 self->ob_item = NULL;
504 self->ob_size = 0;
505 for (i = 0; i < size; i++)
506 Py_XDECREF(items[i]);
507 PyMem_DEL(items);
508 Py_INCREF(self);
509 return (PyObject *)self;
510 }
511
512 NRESIZE(items, PyObject*, size*n);
513 if (items == NULL) {
514 PyErr_NoMemory();
515 goto finally;
516 }
517 self->ob_item = items;
518 for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */
519 for (j = 0; j < size; j++) {
520 PyObject *o = PyList_GET_ITEM(self, j);
521 Py_INCREF(o);
522 PyList_SET_ITEM(self, self->ob_size++, o);
523 }
524 }
525 Py_INCREF(self);
526 return (PyObject *)self;
527 finally:
528 return NULL;
529}
530
Guido van Rossum4a450d01991-04-03 19:05:18 +0000531static int
Fred Drakea2f55112000-07-09 15:16:51 +0000532list_ass_item(PyListObject *a, int i, PyObject *v)
Guido van Rossum4a450d01991-04-03 19:05:18 +0000533{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000534 PyObject *old_value;
Guido van Rossum4a450d01991-04-03 19:05:18 +0000535 if (i < 0 || i >= a->ob_size) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000536 PyErr_SetString(PyExc_IndexError,
537 "list assignment index out of range");
Guido van Rossum4a450d01991-04-03 19:05:18 +0000538 return -1;
539 }
540 if (v == NULL)
541 return list_ass_slice(a, i, i+1, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000542 Py_INCREF(v);
Guido van Rossumd7047b31995-01-02 19:07:15 +0000543 old_value = a->ob_item[i];
Guido van Rossum4a450d01991-04-03 19:05:18 +0000544 a->ob_item[i] = v;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000545 Py_DECREF(old_value);
Guido van Rossum4a450d01991-04-03 19:05:18 +0000546 return 0;
547}
548
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000549static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000550ins(PyListObject *self, int where, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000551{
552 if (ins1(self, where, v) != 0)
553 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000554 Py_INCREF(Py_None);
555 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000556}
557
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000558static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000559listinsert(PyListObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000560{
561 int i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000562 PyObject *v;
Guido van Rossumc00a9382000-02-24 21:48:29 +0000563 if (!PyArg_ParseTuple(args, "iO:insert", &i, &v))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000564 return NULL;
Guido van Rossumbf80e541993-02-08 15:49:17 +0000565 return ins(self, i, v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000566}
567
Guido van Rossumef93b872000-03-13 15:41:59 +0000568/* Define NO_STRICT_LIST_APPEND to enable multi-argument append() */
569
570#ifndef NO_STRICT_LIST_APPEND
571#define PyArg_ParseTuple_Compat1 PyArg_ParseTuple
572#else
573#define PyArg_ParseTuple_Compat1(args, format, ret) \
574( \
575 PyTuple_GET_SIZE(args) > 1 ? (*ret = args, 1) : \
576 PyTuple_GET_SIZE(args) == 1 ? (*ret = PyTuple_GET_ITEM(args, 0), 1) : \
577 PyArg_ParseTuple(args, format, ret) \
578)
579#endif
580
581
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000582static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000583listappend(PyListObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000584{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000585 PyObject *v;
Guido van Rossumef93b872000-03-13 15:41:59 +0000586 if (!PyArg_ParseTuple_Compat1(args, "O:append", &v))
Guido van Rossumbf80e541993-02-08 15:49:17 +0000587 return NULL;
588 return ins(self, (int) self->ob_size, v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000589}
590
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000591static int
592listextend_internal(PyListObject *self, PyObject *b)
Barry Warsawdedf6d61998-10-09 16:37:25 +0000593{
Barry Warsawdedf6d61998-10-09 16:37:25 +0000594 PyObject **items;
595 int selflen = PyList_GET_SIZE(self);
596 int blen;
597 register int i;
598
Jeremy Hyltondb60bb52001-01-03 22:32:16 +0000599 if (PyObject_Size(b) == 0) {
Barry Warsawdedf6d61998-10-09 16:37:25 +0000600 /* short circuit when b is empty */
Jeremy Hyltondb60bb52001-01-03 22:32:16 +0000601 Py_DECREF(b);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000602 return 0;
Jeremy Hyltondb60bb52001-01-03 22:32:16 +0000603 }
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000604
Barry Warsawdedf6d61998-10-09 16:37:25 +0000605 if (self == (PyListObject*)b) {
606 /* as in list_ass_slice() we must special case the
607 * situation: a.extend(a)
608 *
609 * XXX: I think this way ought to be faster than using
610 * list_slice() the way list_ass_slice() does.
611 */
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000612 Py_DECREF(b);
Barry Warsawdedf6d61998-10-09 16:37:25 +0000613 b = PyList_New(selflen);
614 if (!b)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000615 return -1;
Barry Warsawdedf6d61998-10-09 16:37:25 +0000616 for (i = 0; i < selflen; i++) {
617 PyObject *o = PyList_GET_ITEM(self, i);
618 Py_INCREF(o);
619 PyList_SET_ITEM(b, i, o);
620 }
621 }
Barry Warsawdedf6d61998-10-09 16:37:25 +0000622
Jeremy Hylton03657cf2000-07-12 13:05:33 +0000623 blen = PyObject_Size(b);
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000624
Barry Warsawdedf6d61998-10-09 16:37:25 +0000625 /* resize a using idiom */
626 items = self->ob_item;
627 NRESIZE(items, PyObject*, selflen + blen);
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000628 if (items == NULL) {
Barry Warsawdedf6d61998-10-09 16:37:25 +0000629 PyErr_NoMemory();
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000630 Py_DECREF(b);
631 return -1;
Barry Warsawdedf6d61998-10-09 16:37:25 +0000632 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000633
Barry Warsawdedf6d61998-10-09 16:37:25 +0000634 self->ob_item = items;
635
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000636 /* populate the end of self with b's items */
Barry Warsawdedf6d61998-10-09 16:37:25 +0000637 for (i = 0; i < blen; i++) {
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000638 PyObject *o = PySequence_Fast_GET_ITEM(b, i);
Barry Warsawdedf6d61998-10-09 16:37:25 +0000639 Py_INCREF(o);
640 PyList_SET_ITEM(self, self->ob_size++, o);
641 }
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000642 Py_DECREF(b);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000643 return 0;
Barry Warsawdedf6d61998-10-09 16:37:25 +0000644}
645
646
647static PyObject *
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000648list_inplace_concat(PyListObject *self, PyObject *other)
649{
650 other = PySequence_Fast(other, "argument to += must be a sequence");
651 if (!other)
652 return NULL;
653
654 if (listextend_internal(self, other) < 0)
655 return NULL;
656
657 Py_INCREF(self);
658 return (PyObject *)self;
659}
660
661static PyObject *
662listextend(PyListObject *self, PyObject *args)
663{
664
665 PyObject *b;
666
667 if (!PyArg_ParseTuple(args, "O:extend", &b))
668 return NULL;
669
670 b = PySequence_Fast(b, "list.extend() argument must be a sequence");
671 if (!b)
672 return NULL;
673
674 if (listextend_internal(self, b) < 0)
675 return NULL;
676
677 Py_INCREF(Py_None);
678 return Py_None;
679}
680
681static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000682listpop(PyListObject *self, PyObject *args)
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000683{
684 int i = -1;
685 PyObject *v;
Guido van Rossumc00a9382000-02-24 21:48:29 +0000686 if (!PyArg_ParseTuple(args, "|i:pop", &i))
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000687 return NULL;
688 if (self->ob_size == 0) {
689 /* Special-case most common failure cause */
690 PyErr_SetString(PyExc_IndexError, "pop from empty list");
691 return NULL;
692 }
693 if (i < 0)
694 i += self->ob_size;
695 if (i < 0 || i >= self->ob_size) {
696 PyErr_SetString(PyExc_IndexError, "pop index out of range");
697 return NULL;
698 }
699 v = self->ob_item[i];
700 Py_INCREF(v);
701 if (list_ass_slice(self, i, i+1, (PyObject *)NULL) != 0) {
702 Py_DECREF(v);
703 return NULL;
704 }
705 return v;
706}
707
Guido van Rossum3f236de1996-12-10 23:55:39 +0000708/* New quicksort implementation for arrays of object pointers.
709 Thanks to discussions with Tim Peters. */
710
711/* CMPERROR is returned by our comparison function when an error
712 occurred. This is the largest negative integer (0x80000000 on a
713 32-bit system). */
Guido van Rossum19700b61997-03-05 00:45:43 +0000714#define CMPERROR ( (int) ((unsigned int)1 << (8*sizeof(int) - 1)) )
Guido van Rossum3f236de1996-12-10 23:55:39 +0000715
716/* Comparison function. Takes care of calling a user-supplied
717 comparison function (any callable Python object). Calls the
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000718 standard comparison function, PyObject_Compare(), if the user-
719 supplied function is NULL. */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000720
721static int
Fred Drakea2f55112000-07-09 15:16:51 +0000722docompare(PyObject *x, PyObject *y, PyObject *compare)
Guido van Rossum3f236de1996-12-10 23:55:39 +0000723{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000724 PyObject *args, *res;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000725 int i;
726
Guido van Rossumc8b6df91997-05-23 00:06:51 +0000727 if (compare == NULL) {
728 i = PyObject_Compare(x, y);
729 if (i && PyErr_Occurred())
730 i = CMPERROR;
731 return i;
732 }
Guido van Rossum3f236de1996-12-10 23:55:39 +0000733
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000734 args = Py_BuildValue("(OO)", x, y);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000735 if (args == NULL)
736 return CMPERROR;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000737 res = PyEval_CallObject(compare, args);
738 Py_DECREF(args);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000739 if (res == NULL)
740 return CMPERROR;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000741 if (!PyInt_Check(res)) {
742 Py_DECREF(res);
743 PyErr_SetString(PyExc_TypeError,
Guido van Rossum9bcd1d71999-04-19 17:44:39 +0000744 "comparison function must return int");
Guido van Rossum3f236de1996-12-10 23:55:39 +0000745 return CMPERROR;
746 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000747 i = PyInt_AsLong(res);
748 Py_DECREF(res);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000749 if (i < 0)
750 return -1;
751 if (i > 0)
752 return 1;
753 return 0;
754}
755
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000756/* MINSIZE is the smallest array that will get a full-blown samplesort
757 treatment; smaller arrays are sorted using binary insertion. It must
758 be at least 7 for the samplesort implementation to work. Binary
759 insertion does fewer compares, but can suffer O(N**2) data movement.
760 The more expensive compares, the larger MINSIZE should be. */
761#define MINSIZE 100
762
763/* MINPARTITIONSIZE is the smallest array slice samplesort will bother to
764 partition; smaller slices are passed to binarysort. It must be at
765 least 2, and no larger than MINSIZE. Setting it higher reduces the #
766 of compares slowly, but increases the amount of data movement quickly.
767 The value here was chosen assuming a compare costs ~25x more than
768 swapping a pair of memory-resident pointers -- but under that assumption,
769 changing the value by a few dozen more or less has aggregate effect
770 under 1%. So the value is crucial, but not touchy <wink>. */
771#define MINPARTITIONSIZE 40
772
773/* MAXMERGE is the largest number of elements we'll always merge into
774 a known-to-be sorted chunk via binary insertion, regardless of the
775 size of that chunk. Given a chunk of N sorted elements, and a group
776 of K unknowns, the largest K for which it's better to do insertion
777 (than a full-blown sort) is a complicated function of N and K mostly
778 involving the expected number of compares and data moves under each
779 approach, and the relative cost of those operations on a specific
780 architecure. The fixed value here is conservative, and should be a
781 clear win regardless of architecture or N. */
782#define MAXMERGE 15
Guido van Rossum3f236de1996-12-10 23:55:39 +0000783
Guido van Rossum3f236de1996-12-10 23:55:39 +0000784/* STACKSIZE is the size of our work stack. A rough estimate is that
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000785 this allows us to sort arrays of size N where
786 N / ln(N) = MINPARTITIONSIZE * 2**STACKSIZE, so 60 is more than enough
787 for arrays of size 2**64. Because we push the biggest partition
788 first, the worst case occurs when all subarrays are always partitioned
789 exactly in two. */
790#define STACKSIZE 60
Guido van Rossum3f236de1996-12-10 23:55:39 +0000791
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000792
793#define SETK(X,Y) if ((k = docompare(X,Y,compare))==CMPERROR) goto fail
794
795/* binarysort is the best method for sorting small arrays: it does
796 few compares, but can do data movement quadratic in the number of
797 elements.
Guido van Rossum42812581998-06-17 14:15:44 +0000798 [lo, hi) is a contiguous slice of a list, and is sorted via
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000799 binary insertion.
800 On entry, must have lo <= start <= hi, and that [lo, start) is already
801 sorted (pass start == lo if you don't know!).
802 If docompare complains (returns CMPERROR) return -1, else 0.
803 Even in case of error, the output slice will be some permutation of
804 the input (nothing is lost or duplicated).
805*/
Guido van Rossum3f236de1996-12-10 23:55:39 +0000806
807static int
Fred Drakea2f55112000-07-09 15:16:51 +0000808binarysort(PyObject **lo, PyObject **hi, PyObject **start, PyObject *compare)
809 /* compare -- comparison function object, or NULL for default */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000810{
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000811 /* assert lo <= start <= hi
812 assert [lo, start) is sorted */
813 register int k;
814 register PyObject **l, **p, **r;
815 register PyObject *pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000816
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000817 if (lo == start)
818 ++start;
819 for (; start < hi; ++start) {
820 /* set l to where *start belongs */
821 l = lo;
822 r = start;
Guido van Rossuma119c0d1998-05-29 17:56:32 +0000823 pivot = *r;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000824 do {
825 p = l + ((r - l) >> 1);
826 SETK(pivot, *p);
827 if (k < 0)
828 r = p;
829 else
830 l = p + 1;
831 } while (l < r);
832 /* Pivot should go at l -- slide over to make room.
833 Caution: using memmove is much slower under MSVC 5;
834 we're not usually moving many slots. */
835 for (p = start; p > l; --p)
836 *p = *(p-1);
837 *l = pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000838 }
Guido van Rossum3f236de1996-12-10 23:55:39 +0000839 return 0;
Guido van Rossuma119c0d1998-05-29 17:56:32 +0000840
841 fail:
842 return -1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000843}
844
845/* samplesortslice is the sorting workhorse.
Guido van Rossum42812581998-06-17 14:15:44 +0000846 [lo, hi) is a contiguous slice of a list, to be sorted in place.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000847 On entry, must have lo <= hi,
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
852 samplesort is basically quicksort on steroids: a power of 2 close
853 to n/ln(n) is computed, and that many elements (less 1) are picked at
854 random from the array and sorted. These 2**k - 1 elements are then
855 used as preselected pivots for an equal number of quicksort
856 partitioning steps, partitioning the slice into 2**k chunks each of
857 size about ln(n). These small final chunks are then usually handled
858 by binarysort. Note that when k=1, this is roughly the same as an
859 ordinary quicksort using a random pivot, and when k=2 this is roughly
860 a median-of-3 quicksort. From that view, using k ~= lg(n/ln(n)) makes
861 this a "median of n/ln(n)" quicksort. You can also view it as a kind
862 of bucket sort, where 2**k-1 bucket boundaries are picked dynamically.
863
864 The large number of samples makes a quadratic-time case almost
865 impossible, and asymptotically drives the average-case number of
866 compares from quicksort's 2 N ln N (or 12/7 N ln N for the median-of-
867 3 variant) down to N lg N.
868
869 We also play lots of low-level tricks to cut the number of compares.
870
871 Very obscure: To avoid using extra memory, the PPs are stored in the
872 array and shuffled around as partitioning proceeds. At the start of a
873 partitioning step, we'll have 2**m-1 (for some m) PPs in sorted order,
874 adjacent (either on the left or the right!) to a chunk of X elements
875 that are to be partitioned: P X or X P. In either case we need to
876 shuffle things *in place* so that the 2**(m-1) smaller PPs are on the
877 left, followed by the PP to be used for this step (that's the middle
878 of the PPs), followed by X, followed by the 2**(m-1) larger PPs:
879 P X or X P -> Psmall pivot X Plarge
880 and the order of the PPs must not be altered. It can take a while
881 to realize this isn't trivial! It can take even longer <wink> to
882 understand why the simple code below works, using only 2**(m-1) swaps.
883 The key is that the order of the X elements isn't necessarily
884 preserved: X can end up as some cyclic permutation of its original
885 order. That's OK, because X is unsorted anyway. If the order of X
886 had to be preserved too, the simplest method I know of using O(1)
887 scratch storage requires len(X) + 2**(m-1) swaps, spread over 2 passes.
888 Since len(X) is typically several times larger than 2**(m-1), that
889 would slow things down.
890*/
891
892struct SamplesortStackNode {
893 /* Represents a slice of the array, from (& including) lo up
894 to (but excluding) hi. "extra" additional & adjacent elements
895 are pre-selected pivots (PPs), spanning [lo-extra, lo) if
896 extra > 0, or [hi, hi-extra) if extra < 0. The PPs are
897 already sorted, but nothing is known about the other elements
898 in [lo, hi). |extra| is always one less than a power of 2.
899 When extra is 0, we're out of PPs, and the slice must be
900 sorted by some other means. */
901 PyObject **lo;
902 PyObject **hi;
903 int extra;
904};
905
906/* 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 +0000907 N / ln(N) as possible. So k ~= lg(N / ln(N)). Calling libm routines
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000908 is undesirable, so cutoff values are canned in the "cutoff" table
909 below: cutoff[i] is the smallest N such that k == CUTOFFBASE + i. */
910#define CUTOFFBASE 4
Guido van Rossum3aa23fd1999-01-14 19:01:53 +0000911static long cutoff[] = {
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000912 43, /* smallest N such that k == 4 */
913 106, /* etc */
914 250,
915 576,
916 1298,
917 2885,
918 6339,
919 13805,
920 29843,
921 64116,
922 137030,
923 291554,
924 617916,
925 1305130,
926 2748295,
927 5771662,
928 12091672,
929 25276798,
930 52734615,
931 109820537,
932 228324027,
933 473977813,
934 982548444, /* smallest N such that k == 26 */
935 2034159050 /* largest N that fits in signed 32-bit; k == 27 */
936};
937
938static int
Fred Drakea2f55112000-07-09 15:16:51 +0000939samplesortslice(PyObject **lo, PyObject **hi, PyObject *compare)
940 /* compare -- comparison function object, or NULL for default */
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000941{
942 register PyObject **l, **r;
943 register PyObject *tmp, *pivot;
944 register int k;
945 int n, extra, top, extraOnRight;
946 struct SamplesortStackNode stack[STACKSIZE];
947
948 /* assert lo <= hi */
949 n = hi - lo;
950
951 /* ----------------------------------------------------------
952 * Special cases
953 * --------------------------------------------------------*/
954 if (n < 2)
955 return 0;
956
957 /* Set r to the largest value such that [lo,r) is sorted.
958 This catches the already-sorted case, the all-the-same
959 case, and the appended-a-few-elements-to-a-sorted-list case.
960 If the array is unsorted, we're very likely to get out of
961 the loop fast, so the test is cheap if it doesn't pay off.
962 */
963 /* assert lo < hi */
964 for (r = lo+1; r < hi; ++r) {
965 SETK(*r, *(r-1));
966 if (k < 0)
967 break;
968 }
969 /* [lo,r) is sorted, [r,hi) unknown. Get out cheap if there are
970 few unknowns, or few elements in total. */
971 if (hi - r <= MAXMERGE || n < MINSIZE)
Guido van Rossum42812581998-06-17 14:15:44 +0000972 return binarysort(lo, hi, r, compare);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000973
974 /* Check for the array already being reverse-sorted. Typical
975 benchmark-driven silliness <wink>. */
976 /* assert lo < hi */
977 for (r = lo+1; r < hi; ++r) {
978 SETK(*(r-1), *r);
979 if (k < 0)
980 break;
981 }
982 if (hi - r <= MAXMERGE) {
983 /* Reverse the reversed prefix, then insert the tail */
984 PyObject **originalr = r;
985 l = lo;
986 do {
987 --r;
988 tmp = *l; *l = *r; *r = tmp;
989 ++l;
990 } while (l < r);
Guido van Rossum42812581998-06-17 14:15:44 +0000991 return binarysort(lo, hi, originalr, compare);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000992 }
993
994 /* ----------------------------------------------------------
995 * Normal case setup: a large array without obvious pattern.
996 * --------------------------------------------------------*/
997
998 /* extra := a power of 2 ~= n/ln(n), less 1.
999 First find the smallest extra s.t. n < cutoff[extra] */
1000 for (extra = 0;
1001 extra < sizeof(cutoff) / sizeof(cutoff[0]);
1002 ++extra) {
1003 if (n < cutoff[extra])
1004 break;
1005 /* note that if we fall out of the loop, the value of
1006 extra still makes *sense*, but may be smaller than
1007 we would like (but the array has more than ~= 2**31
1008 elements in this case!) */
1009 }
1010 /* Now k == extra - 1 + CUTOFFBASE. The smallest value k can
1011 have is CUTOFFBASE-1, so
1012 assert MINSIZE >= 2**(CUTOFFBASE-1) - 1 */
1013 extra = (1 << (extra - 1 + CUTOFFBASE)) - 1;
1014 /* assert extra > 0 and n >= extra */
1015
1016 /* Swap that many values to the start of the array. The
1017 selection of elements is pseudo-random, but the same on
1018 every run (this is intentional! timing algorithm changes is
1019 a pain if timing varies across runs). */
1020 {
1021 unsigned int seed = n / extra; /* arbitrary */
1022 unsigned int i;
1023 for (i = 0; i < (unsigned)extra; ++i) {
1024 /* j := random int in [i, n) */
1025 unsigned int j;
1026 seed = seed * 69069 + 7;
1027 j = i + seed % (n - i);
1028 tmp = lo[i]; lo[i] = lo[j]; lo[j] = tmp;
1029 }
1030 }
1031
1032 /* Recursively sort the preselected pivots. */
Guido van Rossum42812581998-06-17 14:15:44 +00001033 if (samplesortslice(lo, lo + extra, compare) < 0)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001034 goto fail;
1035
1036 top = 0; /* index of available stack slot */
1037 lo += extra; /* point to first unknown */
1038 extraOnRight = 0; /* the PPs are at the left end */
1039
1040 /* ----------------------------------------------------------
1041 * Partition [lo, hi), and repeat until out of work.
1042 * --------------------------------------------------------*/
1043 for (;;) {
1044 /* assert lo <= hi, so n >= 0 */
1045 n = hi - lo;
1046
1047 /* We may not want, or may not be able, to partition:
1048 If n is small, it's quicker to insert.
1049 If extra is 0, we're out of pivots, and *must* use
1050 another method.
1051 */
1052 if (n < MINPARTITIONSIZE || extra == 0) {
1053 if (n >= MINSIZE) {
1054 /* assert extra == 0
1055 This is rare, since the average size
1056 of a final block is only about
1057 ln(original n). */
Guido van Rossum42812581998-06-17 14:15:44 +00001058 if (samplesortslice(lo, hi, compare) < 0)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001059 goto fail;
1060 }
1061 else {
1062 /* Binary insertion should be quicker,
1063 and we can take advantage of the PPs
1064 already being sorted. */
1065 if (extraOnRight && extra) {
1066 /* swap the PPs to the left end */
1067 k = extra;
1068 do {
1069 tmp = *lo;
1070 *lo = *hi;
1071 *hi = tmp;
1072 ++lo; ++hi;
1073 } while (--k);
1074 }
1075 if (binarysort(lo - extra, hi, lo,
Guido van Rossum42812581998-06-17 14:15:44 +00001076 compare) < 0)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001077 goto fail;
1078 }
1079
1080 /* Find another slice to work on. */
1081 if (--top < 0)
1082 break; /* no more -- done! */
1083 lo = stack[top].lo;
1084 hi = stack[top].hi;
1085 extra = stack[top].extra;
1086 extraOnRight = 0;
1087 if (extra < 0) {
1088 extraOnRight = 1;
1089 extra = -extra;
1090 }
1091 continue;
1092 }
1093
1094 /* Pretend the PPs are indexed 0, 1, ..., extra-1.
1095 Then our preselected pivot is at (extra-1)/2, and we
1096 want to move the PPs before that to the left end of
1097 the slice, and the PPs after that to the right end.
1098 The following section changes extra, lo, hi, and the
1099 slice such that:
1100 [lo-extra, lo) contains the smaller PPs.
1101 *lo == our PP.
1102 (lo, hi) contains the unknown elements.
1103 [hi, hi+extra) contains the larger PPs.
1104 */
1105 k = extra >>= 1; /* num PPs to move */
1106 if (extraOnRight) {
1107 /* Swap the smaller PPs to the left end.
1108 Note that this loop actually moves k+1 items:
1109 the last is our PP */
1110 do {
1111 tmp = *lo; *lo = *hi; *hi = tmp;
1112 ++lo; ++hi;
1113 } while (k--);
1114 }
1115 else {
1116 /* Swap the larger PPs to the right end. */
1117 while (k--) {
1118 --lo; --hi;
1119 tmp = *lo; *lo = *hi; *hi = tmp;
1120 }
1121 }
1122 --lo; /* *lo is now our PP */
1123 pivot = *lo;
1124
1125 /* Now an almost-ordinary quicksort partition step.
1126 Note that most of the time is spent here!
1127 Only odd thing is that we partition into < and >=,
1128 instead of the usual <= and >=. This helps when
1129 there are lots of duplicates of different values,
1130 because it eventually tends to make subfiles
1131 "pure" (all duplicates), and we special-case for
1132 duplicates later. */
1133 l = lo + 1;
1134 r = hi - 1;
1135 /* assert lo < l < r < hi (small n weeded out above) */
1136
1137 do {
1138 /* slide l right, looking for key >= pivot */
1139 do {
1140 SETK(*l, pivot);
1141 if (k < 0)
1142 ++l;
1143 else
1144 break;
1145 } while (l < r);
1146
1147 /* slide r left, looking for key < pivot */
1148 while (l < r) {
Guido van Rossum42812581998-06-17 14:15:44 +00001149 register PyObject *rval = *r--;
1150 SETK(rval, pivot);
1151 if (k < 0) {
1152 /* swap and advance */
1153 r[1] = *l;
1154 *l++ = rval;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001155 break;
Guido van Rossum42812581998-06-17 14:15:44 +00001156 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001157 }
1158
1159 } while (l < r);
1160
1161 /* assert lo < r <= l < hi
1162 assert r == l or r+1 == l
1163 everything to the left of l is < pivot, and
1164 everything to the right of r is >= pivot */
1165
1166 if (l == r) {
1167 SETK(*r, pivot);
1168 if (k < 0)
1169 ++l;
1170 else
1171 --r;
1172 }
1173 /* assert lo <= r and r+1 == l and l <= hi
1174 assert r == lo or a[r] < pivot
1175 assert a[lo] is pivot
1176 assert l == hi or a[l] >= pivot
1177 Swap the pivot into "the middle", so we can henceforth
1178 ignore it.
1179 */
1180 *lo = *r;
1181 *r = pivot;
1182
1183 /* The following is true now, & will be preserved:
1184 All in [lo,r) are < pivot
1185 All in [r,l) == pivot (& so can be ignored)
1186 All in [l,hi) are >= pivot */
1187
1188 /* Check for duplicates of the pivot. One compare is
1189 wasted if there are no duplicates, but can win big
1190 when there are.
1191 Tricky: we're sticking to "<" compares, so deduce
1192 equality indirectly. We know pivot <= *l, so they're
1193 equal iff not pivot < *l.
1194 */
1195 while (l < hi) {
1196 /* pivot <= *l known */
1197 SETK(pivot, *l);
1198 if (k < 0)
1199 break;
1200 else
1201 /* <= and not < implies == */
1202 ++l;
1203 }
1204
1205 /* assert lo <= r < l <= hi
1206 Partitions are [lo, r) and [l, hi) */
1207
1208 /* push fattest first; remember we still have extra PPs
1209 to the left of the left chunk and to the right of
1210 the right chunk! */
1211 /* assert top < STACKSIZE */
1212 if (r - lo <= hi - l) {
1213 /* second is bigger */
1214 stack[top].lo = l;
1215 stack[top].hi = hi;
1216 stack[top].extra = -extra;
1217 hi = r;
1218 extraOnRight = 0;
1219 }
1220 else {
1221 /* first is bigger */
1222 stack[top].lo = lo;
1223 stack[top].hi = r;
1224 stack[top].extra = extra;
1225 lo = l;
1226 extraOnRight = 1;
1227 }
1228 ++top;
1229
1230 } /* end of partitioning loop */
1231
1232 return 0;
1233
1234 fail:
1235 return -1;
1236}
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001237
1238#undef SETK
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001239
1240staticforward PyTypeObject immutable_list_type;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001241
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001242static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00001243listsort(PyListObject *self, PyObject *args)
Guido van Rossum3f236de1996-12-10 23:55:39 +00001244{
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001245 int err;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001246 PyObject *compare = NULL;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001247
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001248 if (args != NULL) {
Guido van Rossumc00a9382000-02-24 21:48:29 +00001249 if (!PyArg_ParseTuple(args, "|O:sort", &compare))
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001250 return NULL;
1251 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001252 self->ob_type = &immutable_list_type;
1253 err = samplesortslice(self->ob_item,
1254 self->ob_item + self->ob_size,
Guido van Rossum42812581998-06-17 14:15:44 +00001255 compare);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001256 self->ob_type = &PyList_Type;
1257 if (err < 0)
Guido van Rossum3f236de1996-12-10 23:55:39 +00001258 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001259 Py_INCREF(Py_None);
1260 return Py_None;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001261}
1262
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001263int
Fred Drakea2f55112000-07-09 15:16:51 +00001264PyList_Sort(PyObject *v)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001265{
1266 if (v == NULL || !PyList_Check(v)) {
1267 PyErr_BadInternalCall();
1268 return -1;
1269 }
1270 v = listsort((PyListObject *)v, (PyObject *)NULL);
1271 if (v == NULL)
1272 return -1;
1273 Py_DECREF(v);
1274 return 0;
1275}
1276
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001277static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00001278listreverse(PyListObject *self, PyObject *args)
Guido van Rossumed98d481991-03-06 13:07:53 +00001279{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001280 register PyObject **p, **q;
1281 register PyObject *tmp;
Guido van Rossumed98d481991-03-06 13:07:53 +00001282
Guido van Rossumc00a9382000-02-24 21:48:29 +00001283 if (!PyArg_ParseTuple(args, ":reverse"))
Guido van Rossumed98d481991-03-06 13:07:53 +00001284 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00001285
1286 if (self->ob_size > 1) {
1287 for (p = self->ob_item, q = self->ob_item + self->ob_size - 1;
1288 p < q; p++, q--) {
1289 tmp = *p;
1290 *p = *q;
1291 *q = tmp;
1292 }
1293 }
1294
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 Rossumc0b618a1997-05-02 03:12:38 +00001306 v = listreverse((PyListObject *)v, (PyObject *)NULL);
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00001307 if (v == NULL)
1308 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001309 Py_DECREF(v);
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00001310 return 0;
1311}
1312
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001313PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00001314PyList_AsTuple(PyObject *v)
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00001315{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001316 PyObject *w;
1317 PyObject **p;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00001318 int n;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001319 if (v == NULL || !PyList_Check(v)) {
1320 PyErr_BadInternalCall();
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00001321 return NULL;
1322 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001323 n = ((PyListObject *)v)->ob_size;
1324 w = PyTuple_New(n);
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00001325 if (w == NULL)
1326 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001327 p = ((PyTupleObject *)w)->ob_item;
Thomas Wouters334fb892000-07-25 12:56:38 +00001328 memcpy((void *)p,
1329 (void *)((PyListObject *)v)->ob_item,
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001330 n*sizeof(PyObject *));
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00001331 while (--n >= 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001332 Py_INCREF(*p);
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00001333 p++;
1334 }
1335 return w;
1336}
1337
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001338static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00001339listindex(PyListObject *self, PyObject *args)
Guido van Rossumed98d481991-03-06 13:07:53 +00001340{
1341 int i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001342 PyObject *v;
1343
Guido van Rossumef93b872000-03-13 15:41:59 +00001344 if (!PyArg_ParseTuple_Compat1(args, "O:index", &v))
Guido van Rossumed98d481991-03-06 13:07:53 +00001345 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00001346 for (i = 0; i < self->ob_size; i++) {
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001347 if (PyObject_Compare(self->ob_item[i], v) == 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001348 return PyInt_FromLong((long)i);
Guido van Rossumc8b6df91997-05-23 00:06:51 +00001349 if (PyErr_Occurred())
1350 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00001351 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001352 PyErr_SetString(PyExc_ValueError, "list.index(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00001353 return NULL;
1354}
1355
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001356static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00001357listcount(PyListObject *self, PyObject *args)
Guido van Rossume6f7d181991-10-20 20:20:40 +00001358{
1359 int count = 0;
1360 int i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001361 PyObject *v;
1362
Guido van Rossumef93b872000-03-13 15:41:59 +00001363 if (!PyArg_ParseTuple_Compat1(args, "O:count", &v))
Guido van Rossume6f7d181991-10-20 20:20:40 +00001364 return NULL;
Guido van Rossume6f7d181991-10-20 20:20:40 +00001365 for (i = 0; i < self->ob_size; i++) {
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001366 if (PyObject_Compare(self->ob_item[i], v) == 0)
Guido van Rossume6f7d181991-10-20 20:20:40 +00001367 count++;
Guido van Rossumc8b6df91997-05-23 00:06:51 +00001368 if (PyErr_Occurred())
1369 return NULL;
Guido van Rossume6f7d181991-10-20 20:20:40 +00001370 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001371 return PyInt_FromLong((long)count);
Guido van Rossume6f7d181991-10-20 20:20:40 +00001372}
1373
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001374static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00001375listremove(PyListObject *self, PyObject *args)
Guido van Rossumed98d481991-03-06 13:07:53 +00001376{
1377 int i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001378 PyObject *v;
1379
Guido van Rossumef93b872000-03-13 15:41:59 +00001380 if (!PyArg_ParseTuple_Compat1(args, "O:remove", &v))
Guido van Rossumed98d481991-03-06 13:07:53 +00001381 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00001382 for (i = 0; i < self->ob_size; i++) {
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001383 if (PyObject_Compare(self->ob_item[i], v) == 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 Rossumc8b6df91997-05-23 00:06:51 +00001390 if (PyErr_Occurred())
1391 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 Rossum3dd7f3f1998-06-30 15:36:32 +00001421static char append_doc[] =
1422"L.append(object) -- append object to end";
Barry Warsawdedf6d61998-10-09 16:37:25 +00001423static char extend_doc[] =
1424"L.extend(list) -- extend list by appending list elements";
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +00001425static char insert_doc[] =
1426"L.insert(index, object) -- insert object before index";
1427static char pop_doc[] =
1428"L.pop([index]) -> item -- remove and return item at index (default last)";
1429static char remove_doc[] =
1430"L.remove(value) -- remove first occurrence of value";
1431static char index_doc[] =
1432"L.index(value) -> integer -- return index of first occurrence of value";
1433static char count_doc[] =
1434"L.count(value) -> integer -- return number of occurrences of value";
1435static char reverse_doc[] =
1436"L.reverse() -- reverse *IN PLACE*";
1437static char sort_doc[] =
1438"L.sort([cmpfunc]) -- sort *IN PLACE*; if given, cmpfunc(x, y) -> -1, 0, 1";
1439
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001440static PyMethodDef list_methods[] = {
Tim Peters0e76ab22000-12-13 22:35:46 +00001441 {"append", (PyCFunction)listappend, METH_VARARGS, append_doc},
1442 {"insert", (PyCFunction)listinsert, METH_VARARGS, insert_doc},
1443 {"extend", (PyCFunction)listextend, METH_VARARGS, extend_doc},
1444 {"pop", (PyCFunction)listpop, METH_VARARGS, pop_doc},
1445 {"remove", (PyCFunction)listremove, METH_VARARGS, remove_doc},
1446 {"index", (PyCFunction)listindex, METH_VARARGS, index_doc},
1447 {"count", (PyCFunction)listcount, METH_VARARGS, count_doc},
1448 {"reverse", (PyCFunction)listreverse, METH_VARARGS, reverse_doc},
1449 {"sort", (PyCFunction)listsort, METH_VARARGS, sort_doc},
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001450 {NULL, NULL} /* sentinel */
1451};
1452
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001453static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00001454list_getattr(PyListObject *f, char *name)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001455{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001456 return Py_FindMethod(list_methods, (PyObject *)f, name);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001457}
1458
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001459static PySequenceMethods list_as_sequence = {
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00001460 (inquiry)list_length, /*sq_length*/
1461 (binaryfunc)list_concat, /*sq_concat*/
1462 (intargfunc)list_repeat, /*sq_repeat*/
1463 (intargfunc)list_item, /*sq_item*/
1464 (intintargfunc)list_slice, /*sq_slice*/
1465 (intobjargproc)list_ass_item, /*sq_ass_item*/
1466 (intintobjargproc)list_ass_slice, /*sq_ass_slice*/
Jeremy Hylton37b1a262000-04-27 21:41:03 +00001467 (objobjproc)list_contains, /*sq_contains*/
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001468 (binaryfunc)list_inplace_concat, /*sq_inplace_concat*/
1469 (intargfunc)list_inplace_repeat, /*sq_inplace_repeat*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001470};
1471
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001472PyTypeObject PyList_Type = {
1473 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001474 0,
1475 "list",
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001476 sizeof(PyListObject) + PyGC_HEAD_SIZE,
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001477 0,
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00001478 (destructor)list_dealloc, /*tp_dealloc*/
1479 (printfunc)list_print, /*tp_print*/
1480 (getattrfunc)list_getattr, /*tp_getattr*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001481 0, /*tp_setattr*/
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00001482 (cmpfunc)list_compare, /*tp_compare*/
1483 (reprfunc)list_repr, /*tp_repr*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001484 0, /*tp_as_number*/
1485 &list_as_sequence, /*tp_as_sequence*/
1486 0, /*tp_as_mapping*/
Fred Drake56780252000-06-15 14:50:20 +00001487 0, /*tp_hash*/
1488 0, /*tp_call*/
1489 0, /*tp_str*/
1490 0, /*tp_getattro*/
1491 0, /*tp_setattro*/
1492 0, /*tp_as_buffer*/
Jeremy Hyltond08b4c42000-06-23 19:37:02 +00001493 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_GC, /*tp_flags*/
Jeremy Hylton8caad492000-06-23 14:18:11 +00001494 0, /* tp_doc */
1495 (traverseproc)list_traverse, /* tp_traverse */
1496 (inquiry)list_clear, /* tp_clear */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001497};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001498
1499
1500/* During a sort, we really can't have anyone modifying the list; it could
1501 cause core dumps. Thus, we substitute a dummy type that raises an
1502 explanatory exception when a modifying operation is used. Caveat:
1503 comparisons may behave differently; but I guess it's a bad idea anyway to
1504 compare a list that's being sorted... */
1505
1506static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00001507immutable_list_op(void)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001508{
1509 PyErr_SetString(PyExc_TypeError,
1510 "a list cannot be modified while it is being sorted");
1511 return NULL;
1512}
1513
1514static PyMethodDef immutable_list_methods[] = {
1515 {"append", (PyCFunction)immutable_list_op},
1516 {"insert", (PyCFunction)immutable_list_op},
1517 {"remove", (PyCFunction)immutable_list_op},
1518 {"index", (PyCFunction)listindex},
1519 {"count", (PyCFunction)listcount},
1520 {"reverse", (PyCFunction)immutable_list_op},
1521 {"sort", (PyCFunction)immutable_list_op},
1522 {NULL, NULL} /* sentinel */
1523};
1524
1525static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00001526immutable_list_getattr(PyListObject *f, char *name)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001527{
1528 return Py_FindMethod(immutable_list_methods, (PyObject *)f, name);
1529}
1530
1531static int
Fred Drakea2f55112000-07-09 15:16:51 +00001532immutable_list_ass(void)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001533{
1534 immutable_list_op();
1535 return -1;
1536}
1537
1538static PySequenceMethods immutable_list_as_sequence = {
1539 (inquiry)list_length, /*sq_length*/
1540 (binaryfunc)list_concat, /*sq_concat*/
1541 (intargfunc)list_repeat, /*sq_repeat*/
1542 (intargfunc)list_item, /*sq_item*/
1543 (intintargfunc)list_slice, /*sq_slice*/
1544 (intobjargproc)immutable_list_ass, /*sq_ass_item*/
1545 (intintobjargproc)immutable_list_ass, /*sq_ass_slice*/
Fred Drake56780252000-06-15 14:50:20 +00001546 (objobjproc)list_contains, /*sq_contains*/
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001547};
1548
1549static PyTypeObject immutable_list_type = {
1550 PyObject_HEAD_INIT(&PyType_Type)
1551 0,
1552 "list (immutable, during sort)",
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001553 sizeof(PyListObject) + PyGC_HEAD_SIZE,
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001554 0,
1555 0, /*tp_dealloc*/ /* Cannot happen */
1556 (printfunc)list_print, /*tp_print*/
1557 (getattrfunc)immutable_list_getattr, /*tp_getattr*/
1558 0, /*tp_setattr*/
1559 0, /*tp_compare*/ /* Won't be called */
1560 (reprfunc)list_repr, /*tp_repr*/
1561 0, /*tp_as_number*/
1562 &immutable_list_as_sequence, /*tp_as_sequence*/
1563 0, /*tp_as_mapping*/
Fred Drake56780252000-06-15 14:50:20 +00001564 0, /*tp_hash*/
1565 0, /*tp_call*/
1566 0, /*tp_str*/
1567 0, /*tp_getattro*/
1568 0, /*tp_setattro*/
1569 0, /*tp_as_buffer*/
Jeremy Hyltond08b4c42000-06-23 19:37:02 +00001570 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_GC, /*tp_flags*/
Jeremy Hylton8caad492000-06-23 14:18:11 +00001571 0, /* tp_doc */
1572 (traverseproc)list_traverse, /* tp_traverse */
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001573};