blob: 3d02b5f9a2bb54e732564e3956fddd49bf1fe58a [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
Jack Jansene9791602000-08-22 21:51:22 +000011#ifdef HAVE_LIMITS_H
12#include <limits.h>
13#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000014
Guido van Rossumc0b618a1997-05-02 03:12:38 +000015#define ROUNDUP(n, PyTryBlock) \
16 ((((n)+(PyTryBlock)-1)/(PyTryBlock))*(PyTryBlock))
Guido van Rossuma46d51d1995-01-26 22:59:43 +000017
18static int
Fred Drakea2f55112000-07-09 15:16:51 +000019roundupsize(int n)
Guido van Rossuma46d51d1995-01-26 22:59:43 +000020{
21 if (n < 500)
22 return ROUNDUP(n, 10);
23 else
24 return ROUNDUP(n, 100);
25}
26
Guido van Rossuma27d1121997-08-25 18:36:23 +000027#define NRESIZE(var, type, nitems) PyMem_RESIZE(var, type, roundupsize(nitems))
Guido van Rossuma46d51d1995-01-26 22:59:43 +000028
Guido van Rossumc0b618a1997-05-02 03:12:38 +000029PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +000030PyList_New(int size)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000031{
32 int i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +000033 PyListObject *op;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +000034 size_t nbytes;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000035 if (size < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +000036 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000037 return NULL;
38 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +000039 nbytes = size * sizeof(PyObject *);
Guido van Rossum1e28e5e1992-08-19 16:46:30 +000040 /* Check for overflow */
Guido van Rossumc0b618a1997-05-02 03:12:38 +000041 if (nbytes / sizeof(PyObject *) != (size_t)size) {
42 return PyErr_NoMemory();
Guido van Rossum1e28e5e1992-08-19 16:46:30 +000043 }
Guido van Rossumb18618d2000-05-03 23:44:39 +000044 /* PyObject_NewVar is inlined */
Jeremy Hyltond08b4c42000-06-23 19:37:02 +000045 op = (PyListObject *) PyObject_MALLOC(sizeof(PyListObject)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +000046 + PyGC_HEAD_SIZE);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000047 if (op == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +000048 return PyErr_NoMemory();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000049 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +000050 op = (PyListObject *) PyObject_FROM_GC(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000051 if (size <= 0) {
52 op->ob_item = NULL;
53 }
54 else {
Guido van Rossumb18618d2000-05-03 23:44:39 +000055 op->ob_item = (PyObject **) PyMem_MALLOC(nbytes);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000056 if (op->ob_item == NULL) {
Vladimir Marangozov467a67e2000-07-15 03:31:31 +000057 PyObject_FREE(PyObject_AS_GC(op));
Guido van Rossumc0b618a1997-05-02 03:12:38 +000058 return PyErr_NoMemory();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000059 }
60 }
Guido van Rossumb18618d2000-05-03 23:44:39 +000061 PyObject_INIT_VAR(op, &PyList_Type, size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000062 for (i = 0; i < size; i++)
63 op->ob_item[i] = NULL;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +000064 PyObject_GC_Init(op);
Guido van Rossumc0b618a1997-05-02 03:12:38 +000065 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000066}
67
68int
Fred Drakea2f55112000-07-09 15:16:51 +000069PyList_Size(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000070{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000071 if (!PyList_Check(op)) {
72 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000073 return -1;
74 }
75 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +000076 return ((PyListObject *)op) -> ob_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000077}
78
Guido van Rossumc0b618a1997-05-02 03:12:38 +000079static PyObject *indexerr;
Guido van Rossum929f1b81996-08-09 20:51:27 +000080
Guido van Rossumc0b618a1997-05-02 03:12:38 +000081PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +000082PyList_GetItem(PyObject *op, int i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000083{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000084 if (!PyList_Check(op)) {
85 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000086 return NULL;
87 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +000088 if (i < 0 || i >= ((PyListObject *)op) -> ob_size) {
Guido van Rossum929f1b81996-08-09 20:51:27 +000089 if (indexerr == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +000090 indexerr = PyString_FromString(
91 "list index out of range");
92 PyErr_SetObject(PyExc_IndexError, indexerr);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000093 return NULL;
94 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +000095 return ((PyListObject *)op) -> ob_item[i];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000096}
97
98int
Fred Drakea2f55112000-07-09 15:16:51 +000099PyList_SetItem(register PyObject *op, register int i,
100 register PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000101{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000102 register PyObject *olditem;
103 register PyObject **p;
104 if (!PyList_Check(op)) {
105 Py_XDECREF(newitem);
106 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000107 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000108 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000109 if (i < 0 || i >= ((PyListObject *)op) -> ob_size) {
110 Py_XDECREF(newitem);
111 PyErr_SetString(PyExc_IndexError,
112 "list assignment index out of range");
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000113 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000114 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000115 p = ((PyListObject *)op) -> ob_item + i;
Guido van Rossum5fe60581995-03-09 12:12:50 +0000116 olditem = *p;
117 *p = newitem;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000118 Py_XDECREF(olditem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000119 return 0;
120}
121
122static int
Fred Drakea2f55112000-07-09 15:16:51 +0000123ins1(PyListObject *self, int where, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000124{
125 int i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000126 PyObject **items;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000127 if (v == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000128 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000129 return -1;
130 }
Trent Micka5846642000-08-13 22:47:45 +0000131 if (self->ob_size == INT_MAX) {
132 PyErr_SetString(PyExc_OverflowError,
133 "cannot add more objects to list");
134 return -1;
135 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000136 items = self->ob_item;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000137 NRESIZE(items, PyObject *, self->ob_size+1);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000138 if (items == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000139 PyErr_NoMemory();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000140 return -1;
141 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000142 if (where < 0)
143 where = 0;
144 if (where > self->ob_size)
145 where = self->ob_size;
146 for (i = self->ob_size; --i >= where; )
147 items[i+1] = items[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000148 Py_INCREF(v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000149 items[where] = v;
150 self->ob_item = items;
151 self->ob_size++;
152 return 0;
153}
154
155int
Fred Drakea2f55112000-07-09 15:16:51 +0000156PyList_Insert(PyObject *op, int where, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000157{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000158 if (!PyList_Check(op)) {
159 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000160 return -1;
161 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000162 return ins1((PyListObject *)op, where, newitem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000163}
164
165int
Fred Drakea2f55112000-07-09 15:16:51 +0000166PyList_Append(PyObject *op, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000167{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000168 if (!PyList_Check(op)) {
169 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000170 return -1;
171 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000172 return ins1((PyListObject *)op,
173 (int) ((PyListObject *)op)->ob_size, newitem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000174}
175
176/* Methods */
177
178static void
Fred Drakea2f55112000-07-09 15:16:51 +0000179list_dealloc(PyListObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000180{
181 int i;
Guido van Rossumd724b232000-03-13 16:01:29 +0000182 Py_TRASHCAN_SAFE_BEGIN(op)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000183 PyObject_GC_Fini(op);
Jack Jansen7874d1f1995-01-19 12:09:27 +0000184 if (op->ob_item != NULL) {
Guido van Rossumfa717011999-06-09 15:19:34 +0000185 /* Do it backwards, for Christian Tismer.
186 There's a simple test case where somehow this reduces
187 thrashing when a *very* large list is created and
188 immediately deleted. */
189 i = op->ob_size;
190 while (--i >= 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000191 Py_XDECREF(op->ob_item[i]);
Jack Jansen7874d1f1995-01-19 12:09:27 +0000192 }
Guido van Rossumb18618d2000-05-03 23:44:39 +0000193 PyMem_FREE(op->ob_item);
Jack Jansen7874d1f1995-01-19 12:09:27 +0000194 }
Guido van Rossum4cc6ac72000-07-01 01:00:38 +0000195 op = (PyListObject *) PyObject_AS_GC(op);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000196 PyObject_DEL(op);
Guido van Rossumd724b232000-03-13 16:01:29 +0000197 Py_TRASHCAN_SAFE_END(op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000198}
199
Guido van Rossum90933611991-06-07 16:10:43 +0000200static int
Fred Drakea2f55112000-07-09 15:16:51 +0000201list_print(PyListObject *op, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000202{
203 int i;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000204
205 i = Py_ReprEnter((PyObject*)op);
206 if (i != 0) {
207 if (i < 0)
208 return i;
209 fprintf(fp, "[...]");
210 return 0;
211 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000212 fprintf(fp, "[");
Guido van Rossum90933611991-06-07 16:10:43 +0000213 for (i = 0; i < op->ob_size; i++) {
214 if (i > 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000215 fprintf(fp, ", ");
Guido van Rossumfb376de1998-04-10 22:47:27 +0000216 if (PyObject_Print(op->ob_item[i], fp, 0) != 0) {
217 Py_ReprLeave((PyObject *)op);
Guido van Rossum90933611991-06-07 16:10:43 +0000218 return -1;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000219 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000220 }
221 fprintf(fp, "]");
Guido van Rossumfb376de1998-04-10 22:47:27 +0000222 Py_ReprLeave((PyObject *)op);
Guido van Rossum90933611991-06-07 16:10:43 +0000223 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000224}
225
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000226static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000227list_repr(PyListObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000228{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000229 PyObject *s, *comma;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000230 int i;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000231
232 i = Py_ReprEnter((PyObject*)v);
233 if (i != 0) {
234 if (i > 0)
235 return PyString_FromString("[...]");
236 return NULL;
237 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000238 s = PyString_FromString("[");
239 comma = PyString_FromString(", ");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000240 for (i = 0; i < v->ob_size && s != NULL; i++) {
241 if (i > 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000242 PyString_Concat(&s, comma);
243 PyString_ConcatAndDel(&s, PyObject_Repr(v->ob_item[i]));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000244 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000245 Py_XDECREF(comma);
246 PyString_ConcatAndDel(&s, PyString_FromString("]"));
Guido van Rossumfb376de1998-04-10 22:47:27 +0000247 Py_ReprLeave((PyObject *)v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000248 return s;
249}
250
251static int
Fred Drakea2f55112000-07-09 15:16:51 +0000252list_compare(PyListObject *v, PyListObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000253{
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000254 int i;
Jack Jansene9791602000-08-22 21:51:22 +0000255
Guido van Rossumae621ff1998-05-28 20:18:46 +0000256 for (i = 0; i < v->ob_size && i < w->ob_size; i++) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000257 int cmp = PyObject_Compare(v->ob_item[i], w->ob_item[i]);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000258 if (cmp != 0)
259 return cmp;
260 }
261 return v->ob_size - w->ob_size;
262}
263
264static int
Fred Drakea2f55112000-07-09 15:16:51 +0000265list_length(PyListObject *a)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000266{
267 return a->ob_size;
268}
269
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000270
271
272static int
Fred Drakea2f55112000-07-09 15:16:51 +0000273list_contains(PyListObject *a, PyObject *el)
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000274{
275 int i, cmp;
276
277 for (i = 0; i < a->ob_size; ++i) {
278 cmp = PyObject_Compare(el, PyList_GET_ITEM(a, i));
279 if (cmp == 0)
280 return 1;
281 if (PyErr_Occurred())
282 return -1;
283 }
284 return 0;
285}
286
287
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000288static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000289list_item(PyListObject *a, int i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000290{
291 if (i < 0 || i >= a->ob_size) {
Guido van Rossum929f1b81996-08-09 20:51:27 +0000292 if (indexerr == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000293 indexerr = PyString_FromString(
294 "list index out of range");
295 PyErr_SetObject(PyExc_IndexError, indexerr);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000296 return NULL;
297 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000298 Py_INCREF(a->ob_item[i]);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000299 return a->ob_item[i];
300}
301
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000302static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000303list_slice(PyListObject *a, int ilow, int ihigh)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000304{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000305 PyListObject *np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000306 int i;
307 if (ilow < 0)
308 ilow = 0;
309 else if (ilow > a->ob_size)
310 ilow = a->ob_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000311 if (ihigh < ilow)
312 ihigh = ilow;
313 else if (ihigh > a->ob_size)
314 ihigh = a->ob_size;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000315 np = (PyListObject *) PyList_New(ihigh - ilow);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000316 if (np == NULL)
317 return NULL;
318 for (i = ilow; i < ihigh; i++) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000319 PyObject *v = a->ob_item[i];
320 Py_INCREF(v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000321 np->ob_item[i - ilow] = v;
322 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000323 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000324}
325
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000326PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000327PyList_GetSlice(PyObject *a, int ilow, int ihigh)
Guido van Rossum234f9421993-06-17 12:35:49 +0000328{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000329 if (!PyList_Check(a)) {
330 PyErr_BadInternalCall();
Guido van Rossum234f9421993-06-17 12:35:49 +0000331 return NULL;
332 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000333 return list_slice((PyListObject *)a, ilow, ihigh);
Guido van Rossum234f9421993-06-17 12:35:49 +0000334}
335
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000336static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000337list_concat(PyListObject *a, PyObject *bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000338{
339 int size;
340 int i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000341 PyListObject *np;
342 if (!PyList_Check(bb)) {
Fred Drakeb6a9ada2000-06-01 03:12:13 +0000343 PyErr_Format(PyExc_TypeError,
Fred Drake914a2ed2000-06-01 14:31:03 +0000344 "can only concatenate list (not \"%.200s\") to list",
345 bb->ob_type->tp_name);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000346 return NULL;
347 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000348#define b ((PyListObject *)bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000349 size = a->ob_size + b->ob_size;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000350 np = (PyListObject *) PyList_New(size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000351 if (np == NULL) {
Guido van Rossum90933611991-06-07 16:10:43 +0000352 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000353 }
354 for (i = 0; i < a->ob_size; i++) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000355 PyObject *v = a->ob_item[i];
356 Py_INCREF(v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000357 np->ob_item[i] = v;
358 }
359 for (i = 0; i < b->ob_size; i++) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000360 PyObject *v = b->ob_item[i];
361 Py_INCREF(v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000362 np->ob_item[i + a->ob_size] = v;
363 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000364 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000365#undef b
366}
367
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000368static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000369list_repeat(PyListObject *a, int n)
Guido van Rossumed98d481991-03-06 13:07:53 +0000370{
371 int i, j;
372 int size;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000373 PyListObject *np;
374 PyObject **p;
Guido van Rossumed98d481991-03-06 13:07:53 +0000375 if (n < 0)
376 n = 0;
377 size = a->ob_size * n;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000378 np = (PyListObject *) PyList_New(size);
Guido van Rossumed98d481991-03-06 13:07:53 +0000379 if (np == NULL)
380 return NULL;
381 p = np->ob_item;
382 for (i = 0; i < n; i++) {
383 for (j = 0; j < a->ob_size; j++) {
384 *p = a->ob_item[j];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000385 Py_INCREF(*p);
Guido van Rossumed98d481991-03-06 13:07:53 +0000386 p++;
387 }
388 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000389 return (PyObject *) np;
Guido van Rossumed98d481991-03-06 13:07:53 +0000390}
391
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000392static int
Fred Drakea2f55112000-07-09 15:16:51 +0000393list_ass_slice(PyListObject *a, int ilow, int ihigh, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000394{
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000395 /* Because [X]DECREF can recursively invoke list operations on
396 this list, we must postpone all [X]DECREF activity until
397 after the list is back in its canonical shape. Therefore
398 we must allocate an additional array, 'recycle', into which
399 we temporarily copy the items that are deleted from the
400 list. :-( */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000401 PyObject **recycle, **p;
402 PyObject **item;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000403 int n; /* Size of replacement list */
404 int d; /* Change in size */
405 int k; /* Loop index */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000406#define b ((PyListObject *)v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000407 if (v == NULL)
408 n = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000409 else if (PyList_Check(v)) {
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000410 n = b->ob_size;
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000411 if (a == b) {
412 /* Special case "a[i:j] = a" -- copy b first */
413 int ret;
414 v = list_slice(b, 0, n);
415 ret = list_ass_slice(a, ilow, ihigh, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000416 Py_DECREF(v);
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000417 return ret;
418 }
419 }
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000420 else {
Fred Drakeb6a9ada2000-06-01 03:12:13 +0000421 PyErr_Format(PyExc_TypeError,
422 "must assign list (not \"%.200s\") to slice",
423 v->ob_type->tp_name);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000424 return -1;
425 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000426 if (ilow < 0)
427 ilow = 0;
428 else if (ilow > a->ob_size)
429 ilow = a->ob_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000430 if (ihigh < ilow)
431 ihigh = ilow;
432 else if (ihigh > a->ob_size)
433 ihigh = a->ob_size;
434 item = a->ob_item;
435 d = n - (ihigh-ilow);
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000436 if (ihigh > ilow)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000437 p = recycle = PyMem_NEW(PyObject *, (ihigh-ilow));
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000438 else
439 p = recycle = NULL;
440 if (d <= 0) { /* Delete -d items; recycle ihigh-ilow items */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000441 for (k = ilow; k < ihigh; k++)
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000442 *p++ = item[k];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000443 if (d < 0) {
444 for (/*k = ihigh*/; k < a->ob_size; k++)
445 item[k+d] = item[k];
446 a->ob_size += d;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000447 NRESIZE(item, PyObject *, a->ob_size); /* Can't fail */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000448 a->ob_item = item;
449 }
450 }
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000451 else { /* Insert d items; recycle ihigh-ilow items */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000452 NRESIZE(item, PyObject *, a->ob_size + d);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000453 if (item == NULL) {
Guido van Rossumb18618d2000-05-03 23:44:39 +0000454 if (recycle != NULL)
455 PyMem_DEL(recycle);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000456 PyErr_NoMemory();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000457 return -1;
458 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000459 for (k = a->ob_size; --k >= ihigh; )
460 item[k+d] = item[k];
461 for (/*k = ihigh-1*/; k >= ilow; --k)
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000462 *p++ = item[k];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000463 a->ob_item = item;
464 a->ob_size += d;
465 }
466 for (k = 0; k < n; k++, ilow++) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000467 PyObject *w = b->ob_item[k];
468 Py_XINCREF(w);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000469 item[ilow] = w;
470 }
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000471 if (recycle) {
472 while (--p >= recycle)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000473 Py_XDECREF(*p);
474 PyMem_DEL(recycle);
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000475 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000476 return 0;
477#undef b
478}
479
Guido van Rossum234f9421993-06-17 12:35:49 +0000480int
Fred Drakea2f55112000-07-09 15:16:51 +0000481PyList_SetSlice(PyObject *a, int ilow, int ihigh, PyObject *v)
Guido van Rossum234f9421993-06-17 12:35:49 +0000482{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000483 if (!PyList_Check(a)) {
484 PyErr_BadInternalCall();
Guido van Rossum1fc238a1993-07-29 08:25:09 +0000485 return -1;
Guido van Rossum234f9421993-06-17 12:35:49 +0000486 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000487 return list_ass_slice((PyListObject *)a, ilow, ihigh, v);
Guido van Rossum234f9421993-06-17 12:35:49 +0000488}
489
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000490static PyObject *
491list_inplace_repeat(PyListObject *self, int n)
492{
493 PyObject **items;
494 int size, i, j;
495
496
497 size = PyList_GET_SIZE(self);
498 if (size == 0) {
499 Py_INCREF(self);
500 return (PyObject *)self;
501 }
502
503 items = self->ob_item;
504
505 if (n < 1) {
506 self->ob_item = NULL;
507 self->ob_size = 0;
508 for (i = 0; i < size; i++)
509 Py_XDECREF(items[i]);
510 PyMem_DEL(items);
511 Py_INCREF(self);
512 return (PyObject *)self;
513 }
514
515 NRESIZE(items, PyObject*, size*n);
516 if (items == NULL) {
517 PyErr_NoMemory();
518 goto finally;
519 }
520 self->ob_item = items;
521 for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */
522 for (j = 0; j < size; j++) {
523 PyObject *o = PyList_GET_ITEM(self, j);
524 Py_INCREF(o);
525 PyList_SET_ITEM(self, self->ob_size++, o);
526 }
527 }
528 Py_INCREF(self);
529 return (PyObject *)self;
530 finally:
531 return NULL;
532}
533
Guido van Rossum4a450d01991-04-03 19:05:18 +0000534static int
Fred Drakea2f55112000-07-09 15:16:51 +0000535list_ass_item(PyListObject *a, int i, PyObject *v)
Guido van Rossum4a450d01991-04-03 19:05:18 +0000536{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000537 PyObject *old_value;
Guido van Rossum4a450d01991-04-03 19:05:18 +0000538 if (i < 0 || i >= a->ob_size) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000539 PyErr_SetString(PyExc_IndexError,
540 "list assignment index out of range");
Guido van Rossum4a450d01991-04-03 19:05:18 +0000541 return -1;
542 }
543 if (v == NULL)
544 return list_ass_slice(a, i, i+1, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000545 Py_INCREF(v);
Guido van Rossumd7047b31995-01-02 19:07:15 +0000546 old_value = a->ob_item[i];
Guido van Rossum4a450d01991-04-03 19:05:18 +0000547 a->ob_item[i] = v;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000548 Py_DECREF(old_value);
Guido van Rossum4a450d01991-04-03 19:05:18 +0000549 return 0;
550}
551
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000552static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000553ins(PyListObject *self, int where, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000554{
555 if (ins1(self, where, v) != 0)
556 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000557 Py_INCREF(Py_None);
558 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000559}
560
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000561static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000562listinsert(PyListObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000563{
564 int i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000565 PyObject *v;
Guido van Rossumc00a9382000-02-24 21:48:29 +0000566 if (!PyArg_ParseTuple(args, "iO:insert", &i, &v))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000567 return NULL;
Guido van Rossumbf80e541993-02-08 15:49:17 +0000568 return ins(self, i, v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000569}
570
Guido van Rossumef93b872000-03-13 15:41:59 +0000571/* Define NO_STRICT_LIST_APPEND to enable multi-argument append() */
572
573#ifndef NO_STRICT_LIST_APPEND
574#define PyArg_ParseTuple_Compat1 PyArg_ParseTuple
575#else
576#define PyArg_ParseTuple_Compat1(args, format, ret) \
577( \
578 PyTuple_GET_SIZE(args) > 1 ? (*ret = args, 1) : \
579 PyTuple_GET_SIZE(args) == 1 ? (*ret = PyTuple_GET_ITEM(args, 0), 1) : \
580 PyArg_ParseTuple(args, format, ret) \
581)
582#endif
583
584
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000585static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000586listappend(PyListObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000587{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000588 PyObject *v;
Guido van Rossumef93b872000-03-13 15:41:59 +0000589 if (!PyArg_ParseTuple_Compat1(args, "O:append", &v))
Guido van Rossumbf80e541993-02-08 15:49:17 +0000590 return NULL;
591 return ins(self, (int) self->ob_size, v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000592}
593
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000594static int
595listextend_internal(PyListObject *self, PyObject *b)
Barry Warsawdedf6d61998-10-09 16:37:25 +0000596{
Barry Warsawdedf6d61998-10-09 16:37:25 +0000597 PyObject **items;
598 int selflen = PyList_GET_SIZE(self);
599 int blen;
600 register int i;
601
Jeremy Hylton03657cf2000-07-12 13:05:33 +0000602 if (PyObject_Size(b) == 0)
Barry Warsawdedf6d61998-10-09 16:37:25 +0000603 /* short circuit when b is empty */
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000604 return 0;
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000605
Barry Warsawdedf6d61998-10-09 16:37:25 +0000606 if (self == (PyListObject*)b) {
607 /* as in list_ass_slice() we must special case the
608 * situation: a.extend(a)
609 *
610 * XXX: I think this way ought to be faster than using
611 * list_slice() the way list_ass_slice() does.
612 */
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000613 Py_DECREF(b);
Barry Warsawdedf6d61998-10-09 16:37:25 +0000614 b = PyList_New(selflen);
615 if (!b)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000616 return -1;
Barry Warsawdedf6d61998-10-09 16:37:25 +0000617 for (i = 0; i < selflen; i++) {
618 PyObject *o = PyList_GET_ITEM(self, i);
619 Py_INCREF(o);
620 PyList_SET_ITEM(b, i, o);
621 }
622 }
Barry Warsawdedf6d61998-10-09 16:37:25 +0000623
Jeremy Hylton03657cf2000-07-12 13:05:33 +0000624 blen = PyObject_Size(b);
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000625
Barry Warsawdedf6d61998-10-09 16:37:25 +0000626 /* resize a using idiom */
627 items = self->ob_item;
628 NRESIZE(items, PyObject*, selflen + blen);
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000629 if (items == NULL) {
Barry Warsawdedf6d61998-10-09 16:37:25 +0000630 PyErr_NoMemory();
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000631 Py_DECREF(b);
632 return -1;
Barry Warsawdedf6d61998-10-09 16:37:25 +0000633 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000634
Barry Warsawdedf6d61998-10-09 16:37:25 +0000635 self->ob_item = items;
636
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000637 /* populate the end of self with b's items */
Barry Warsawdedf6d61998-10-09 16:37:25 +0000638 for (i = 0; i < blen; i++) {
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000639 PyObject *o = PySequence_Fast_GET_ITEM(b, i);
Barry Warsawdedf6d61998-10-09 16:37:25 +0000640 Py_INCREF(o);
641 PyList_SET_ITEM(self, self->ob_size++, o);
642 }
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000643 Py_DECREF(b);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000644 return 0;
Barry Warsawdedf6d61998-10-09 16:37:25 +0000645}
646
647
648static PyObject *
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000649list_inplace_concat(PyListObject *self, PyObject *other)
650{
651 other = PySequence_Fast(other, "argument to += must be a sequence");
652 if (!other)
653 return NULL;
654
655 if (listextend_internal(self, other) < 0)
656 return NULL;
657
658 Py_INCREF(self);
659 return (PyObject *)self;
660}
661
662static PyObject *
663listextend(PyListObject *self, PyObject *args)
664{
665
666 PyObject *b;
667
668 if (!PyArg_ParseTuple(args, "O:extend", &b))
669 return NULL;
670
671 b = PySequence_Fast(b, "list.extend() argument must be a sequence");
672 if (!b)
673 return NULL;
674
675 if (listextend_internal(self, b) < 0)
676 return NULL;
677
678 Py_INCREF(Py_None);
679 return Py_None;
680}
681
682static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000683listpop(PyListObject *self, PyObject *args)
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000684{
685 int i = -1;
686 PyObject *v;
Guido van Rossumc00a9382000-02-24 21:48:29 +0000687 if (!PyArg_ParseTuple(args, "|i:pop", &i))
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000688 return NULL;
689 if (self->ob_size == 0) {
690 /* Special-case most common failure cause */
691 PyErr_SetString(PyExc_IndexError, "pop from empty list");
692 return NULL;
693 }
694 if (i < 0)
695 i += self->ob_size;
696 if (i < 0 || i >= self->ob_size) {
697 PyErr_SetString(PyExc_IndexError, "pop index out of range");
698 return NULL;
699 }
700 v = self->ob_item[i];
701 Py_INCREF(v);
702 if (list_ass_slice(self, i, i+1, (PyObject *)NULL) != 0) {
703 Py_DECREF(v);
704 return NULL;
705 }
706 return v;
707}
708
Guido van Rossum3f236de1996-12-10 23:55:39 +0000709/* New quicksort implementation for arrays of object pointers.
710 Thanks to discussions with Tim Peters. */
711
712/* CMPERROR is returned by our comparison function when an error
713 occurred. This is the largest negative integer (0x80000000 on a
714 32-bit system). */
Guido van Rossum19700b61997-03-05 00:45:43 +0000715#define CMPERROR ( (int) ((unsigned int)1 << (8*sizeof(int) - 1)) )
Guido van Rossum3f236de1996-12-10 23:55:39 +0000716
717/* Comparison function. Takes care of calling a user-supplied
718 comparison function (any callable Python object). Calls the
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000719 standard comparison function, PyObject_Compare(), if the user-
720 supplied function is NULL. */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000721
722static int
Fred Drakea2f55112000-07-09 15:16:51 +0000723docompare(PyObject *x, PyObject *y, PyObject *compare)
Guido van Rossum3f236de1996-12-10 23:55:39 +0000724{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000725 PyObject *args, *res;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000726 int i;
727
Guido van Rossumc8b6df91997-05-23 00:06:51 +0000728 if (compare == NULL) {
729 i = PyObject_Compare(x, y);
730 if (i && PyErr_Occurred())
731 i = CMPERROR;
732 return i;
733 }
Guido van Rossum3f236de1996-12-10 23:55:39 +0000734
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000735 args = Py_BuildValue("(OO)", x, y);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000736 if (args == NULL)
737 return CMPERROR;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000738 res = PyEval_CallObject(compare, args);
739 Py_DECREF(args);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000740 if (res == NULL)
741 return CMPERROR;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000742 if (!PyInt_Check(res)) {
743 Py_DECREF(res);
744 PyErr_SetString(PyExc_TypeError,
Guido van Rossum9bcd1d71999-04-19 17:44:39 +0000745 "comparison function must return int");
Guido van Rossum3f236de1996-12-10 23:55:39 +0000746 return CMPERROR;
747 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000748 i = PyInt_AsLong(res);
749 Py_DECREF(res);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000750 if (i < 0)
751 return -1;
752 if (i > 0)
753 return 1;
754 return 0;
755}
756
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000757/* MINSIZE is the smallest array that will get a full-blown samplesort
758 treatment; smaller arrays are sorted using binary insertion. It must
759 be at least 7 for the samplesort implementation to work. Binary
760 insertion does fewer compares, but can suffer O(N**2) data movement.
761 The more expensive compares, the larger MINSIZE should be. */
762#define MINSIZE 100
763
764/* MINPARTITIONSIZE is the smallest array slice samplesort will bother to
765 partition; smaller slices are passed to binarysort. It must be at
766 least 2, and no larger than MINSIZE. Setting it higher reduces the #
767 of compares slowly, but increases the amount of data movement quickly.
768 The value here was chosen assuming a compare costs ~25x more than
769 swapping a pair of memory-resident pointers -- but under that assumption,
770 changing the value by a few dozen more or less has aggregate effect
771 under 1%. So the value is crucial, but not touchy <wink>. */
772#define MINPARTITIONSIZE 40
773
774/* MAXMERGE is the largest number of elements we'll always merge into
775 a known-to-be sorted chunk via binary insertion, regardless of the
776 size of that chunk. Given a chunk of N sorted elements, and a group
777 of K unknowns, the largest K for which it's better to do insertion
778 (than a full-blown sort) is a complicated function of N and K mostly
779 involving the expected number of compares and data moves under each
780 approach, and the relative cost of those operations on a specific
781 architecure. The fixed value here is conservative, and should be a
782 clear win regardless of architecture or N. */
783#define MAXMERGE 15
Guido van Rossum3f236de1996-12-10 23:55:39 +0000784
Guido van Rossum3f236de1996-12-10 23:55:39 +0000785/* STACKSIZE is the size of our work stack. A rough estimate is that
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000786 this allows us to sort arrays of size N where
787 N / ln(N) = MINPARTITIONSIZE * 2**STACKSIZE, so 60 is more than enough
788 for arrays of size 2**64. Because we push the biggest partition
789 first, the worst case occurs when all subarrays are always partitioned
790 exactly in two. */
791#define STACKSIZE 60
Guido van Rossum3f236de1996-12-10 23:55:39 +0000792
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000793
794#define SETK(X,Y) if ((k = docompare(X,Y,compare))==CMPERROR) goto fail
795
796/* binarysort is the best method for sorting small arrays: it does
797 few compares, but can do data movement quadratic in the number of
798 elements.
Guido van Rossum42812581998-06-17 14:15:44 +0000799 [lo, hi) is a contiguous slice of a list, and is sorted via
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000800 binary insertion.
801 On entry, must have lo <= start <= hi, and that [lo, start) is already
802 sorted (pass start == lo if you don't know!).
803 If docompare complains (returns CMPERROR) return -1, else 0.
804 Even in case of error, the output slice will be some permutation of
805 the input (nothing is lost or duplicated).
806*/
Guido van Rossum3f236de1996-12-10 23:55:39 +0000807
808static int
Fred Drakea2f55112000-07-09 15:16:51 +0000809binarysort(PyObject **lo, PyObject **hi, PyObject **start, PyObject *compare)
810 /* compare -- comparison function object, or NULL for default */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000811{
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000812 /* assert lo <= start <= hi
813 assert [lo, start) is sorted */
814 register int k;
815 register PyObject **l, **p, **r;
816 register PyObject *pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000817
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000818 if (lo == start)
819 ++start;
820 for (; start < hi; ++start) {
821 /* set l to where *start belongs */
822 l = lo;
823 r = start;
Guido van Rossuma119c0d1998-05-29 17:56:32 +0000824 pivot = *r;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000825 do {
826 p = l + ((r - l) >> 1);
827 SETK(pivot, *p);
828 if (k < 0)
829 r = p;
830 else
831 l = p + 1;
832 } while (l < r);
833 /* Pivot should go at l -- slide over to make room.
834 Caution: using memmove is much slower under MSVC 5;
835 we're not usually moving many slots. */
836 for (p = start; p > l; --p)
837 *p = *(p-1);
838 *l = pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000839 }
Guido van Rossum3f236de1996-12-10 23:55:39 +0000840 return 0;
Guido van Rossuma119c0d1998-05-29 17:56:32 +0000841
842 fail:
843 return -1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000844}
845
846/* samplesortslice is the sorting workhorse.
Guido van Rossum42812581998-06-17 14:15:44 +0000847 [lo, hi) is a contiguous slice of a list, to be sorted in place.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000848 On entry, must have lo <= hi,
849 If docompare complains (returns CMPERROR) return -1, else 0.
850 Even in case of error, the output slice will be some permutation of
851 the input (nothing is lost or duplicated).
852
853 samplesort is basically quicksort on steroids: a power of 2 close
854 to n/ln(n) is computed, and that many elements (less 1) are picked at
855 random from the array and sorted. These 2**k - 1 elements are then
856 used as preselected pivots for an equal number of quicksort
857 partitioning steps, partitioning the slice into 2**k chunks each of
858 size about ln(n). These small final chunks are then usually handled
859 by binarysort. Note that when k=1, this is roughly the same as an
860 ordinary quicksort using a random pivot, and when k=2 this is roughly
861 a median-of-3 quicksort. From that view, using k ~= lg(n/ln(n)) makes
862 this a "median of n/ln(n)" quicksort. You can also view it as a kind
863 of bucket sort, where 2**k-1 bucket boundaries are picked dynamically.
864
865 The large number of samples makes a quadratic-time case almost
866 impossible, and asymptotically drives the average-case number of
867 compares from quicksort's 2 N ln N (or 12/7 N ln N for the median-of-
868 3 variant) down to N lg N.
869
870 We also play lots of low-level tricks to cut the number of compares.
871
872 Very obscure: To avoid using extra memory, the PPs are stored in the
873 array and shuffled around as partitioning proceeds. At the start of a
874 partitioning step, we'll have 2**m-1 (for some m) PPs in sorted order,
875 adjacent (either on the left or the right!) to a chunk of X elements
876 that are to be partitioned: P X or X P. In either case we need to
877 shuffle things *in place* so that the 2**(m-1) smaller PPs are on the
878 left, followed by the PP to be used for this step (that's the middle
879 of the PPs), followed by X, followed by the 2**(m-1) larger PPs:
880 P X or X P -> Psmall pivot X Plarge
881 and the order of the PPs must not be altered. It can take a while
882 to realize this isn't trivial! It can take even longer <wink> to
883 understand why the simple code below works, using only 2**(m-1) swaps.
884 The key is that the order of the X elements isn't necessarily
885 preserved: X can end up as some cyclic permutation of its original
886 order. That's OK, because X is unsorted anyway. If the order of X
887 had to be preserved too, the simplest method I know of using O(1)
888 scratch storage requires len(X) + 2**(m-1) swaps, spread over 2 passes.
889 Since len(X) is typically several times larger than 2**(m-1), that
890 would slow things down.
891*/
892
893struct SamplesortStackNode {
894 /* Represents a slice of the array, from (& including) lo up
895 to (but excluding) hi. "extra" additional & adjacent elements
896 are pre-selected pivots (PPs), spanning [lo-extra, lo) if
897 extra > 0, or [hi, hi-extra) if extra < 0. The PPs are
898 already sorted, but nothing is known about the other elements
899 in [lo, hi). |extra| is always one less than a power of 2.
900 When extra is 0, we're out of PPs, and the slice must be
901 sorted by some other means. */
902 PyObject **lo;
903 PyObject **hi;
904 int extra;
905};
906
907/* 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 +0000908 N / ln(N) as possible. So k ~= lg(N / ln(N)). Calling libm routines
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000909 is undesirable, so cutoff values are canned in the "cutoff" table
910 below: cutoff[i] is the smallest N such that k == CUTOFFBASE + i. */
911#define CUTOFFBASE 4
Guido van Rossum3aa23fd1999-01-14 19:01:53 +0000912static long cutoff[] = {
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000913 43, /* smallest N such that k == 4 */
914 106, /* etc */
915 250,
916 576,
917 1298,
918 2885,
919 6339,
920 13805,
921 29843,
922 64116,
923 137030,
924 291554,
925 617916,
926 1305130,
927 2748295,
928 5771662,
929 12091672,
930 25276798,
931 52734615,
932 109820537,
933 228324027,
934 473977813,
935 982548444, /* smallest N such that k == 26 */
936 2034159050 /* largest N that fits in signed 32-bit; k == 27 */
937};
938
939static int
Fred Drakea2f55112000-07-09 15:16:51 +0000940samplesortslice(PyObject **lo, PyObject **hi, PyObject *compare)
941 /* compare -- comparison function object, or NULL for default */
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000942{
943 register PyObject **l, **r;
944 register PyObject *tmp, *pivot;
945 register int k;
946 int n, extra, top, extraOnRight;
947 struct SamplesortStackNode stack[STACKSIZE];
948
949 /* assert lo <= hi */
950 n = hi - lo;
951
952 /* ----------------------------------------------------------
953 * Special cases
954 * --------------------------------------------------------*/
955 if (n < 2)
956 return 0;
957
958 /* Set r to the largest value such that [lo,r) is sorted.
959 This catches the already-sorted case, the all-the-same
960 case, and the appended-a-few-elements-to-a-sorted-list case.
961 If the array is unsorted, we're very likely to get out of
962 the loop fast, so the test is cheap if it doesn't pay off.
963 */
964 /* assert lo < hi */
965 for (r = lo+1; r < hi; ++r) {
966 SETK(*r, *(r-1));
967 if (k < 0)
968 break;
969 }
970 /* [lo,r) is sorted, [r,hi) unknown. Get out cheap if there are
971 few unknowns, or few elements in total. */
972 if (hi - r <= MAXMERGE || n < MINSIZE)
Guido van Rossum42812581998-06-17 14:15:44 +0000973 return binarysort(lo, hi, r, compare);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000974
975 /* Check for the array already being reverse-sorted. Typical
976 benchmark-driven silliness <wink>. */
977 /* assert lo < hi */
978 for (r = lo+1; r < hi; ++r) {
979 SETK(*(r-1), *r);
980 if (k < 0)
981 break;
982 }
983 if (hi - r <= MAXMERGE) {
984 /* Reverse the reversed prefix, then insert the tail */
985 PyObject **originalr = r;
986 l = lo;
987 do {
988 --r;
989 tmp = *l; *l = *r; *r = tmp;
990 ++l;
991 } while (l < r);
Guido van Rossum42812581998-06-17 14:15:44 +0000992 return binarysort(lo, hi, originalr, compare);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000993 }
994
995 /* ----------------------------------------------------------
996 * Normal case setup: a large array without obvious pattern.
997 * --------------------------------------------------------*/
998
999 /* extra := a power of 2 ~= n/ln(n), less 1.
1000 First find the smallest extra s.t. n < cutoff[extra] */
1001 for (extra = 0;
1002 extra < sizeof(cutoff) / sizeof(cutoff[0]);
1003 ++extra) {
1004 if (n < cutoff[extra])
1005 break;
1006 /* note that if we fall out of the loop, the value of
1007 extra still makes *sense*, but may be smaller than
1008 we would like (but the array has more than ~= 2**31
1009 elements in this case!) */
1010 }
1011 /* Now k == extra - 1 + CUTOFFBASE. The smallest value k can
1012 have is CUTOFFBASE-1, so
1013 assert MINSIZE >= 2**(CUTOFFBASE-1) - 1 */
1014 extra = (1 << (extra - 1 + CUTOFFBASE)) - 1;
1015 /* assert extra > 0 and n >= extra */
1016
1017 /* Swap that many values to the start of the array. The
1018 selection of elements is pseudo-random, but the same on
1019 every run (this is intentional! timing algorithm changes is
1020 a pain if timing varies across runs). */
1021 {
1022 unsigned int seed = n / extra; /* arbitrary */
1023 unsigned int i;
1024 for (i = 0; i < (unsigned)extra; ++i) {
1025 /* j := random int in [i, n) */
1026 unsigned int j;
1027 seed = seed * 69069 + 7;
1028 j = i + seed % (n - i);
1029 tmp = lo[i]; lo[i] = lo[j]; lo[j] = tmp;
1030 }
1031 }
1032
1033 /* Recursively sort the preselected pivots. */
Guido van Rossum42812581998-06-17 14:15:44 +00001034 if (samplesortslice(lo, lo + extra, compare) < 0)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001035 goto fail;
1036
1037 top = 0; /* index of available stack slot */
1038 lo += extra; /* point to first unknown */
1039 extraOnRight = 0; /* the PPs are at the left end */
1040
1041 /* ----------------------------------------------------------
1042 * Partition [lo, hi), and repeat until out of work.
1043 * --------------------------------------------------------*/
1044 for (;;) {
1045 /* assert lo <= hi, so n >= 0 */
1046 n = hi - lo;
1047
1048 /* We may not want, or may not be able, to partition:
1049 If n is small, it's quicker to insert.
1050 If extra is 0, we're out of pivots, and *must* use
1051 another method.
1052 */
1053 if (n < MINPARTITIONSIZE || extra == 0) {
1054 if (n >= MINSIZE) {
1055 /* assert extra == 0
1056 This is rare, since the average size
1057 of a final block is only about
1058 ln(original n). */
Guido van Rossum42812581998-06-17 14:15:44 +00001059 if (samplesortslice(lo, hi, compare) < 0)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001060 goto fail;
1061 }
1062 else {
1063 /* Binary insertion should be quicker,
1064 and we can take advantage of the PPs
1065 already being sorted. */
1066 if (extraOnRight && extra) {
1067 /* swap the PPs to the left end */
1068 k = extra;
1069 do {
1070 tmp = *lo;
1071 *lo = *hi;
1072 *hi = tmp;
1073 ++lo; ++hi;
1074 } while (--k);
1075 }
1076 if (binarysort(lo - extra, hi, lo,
Guido van Rossum42812581998-06-17 14:15:44 +00001077 compare) < 0)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001078 goto fail;
1079 }
1080
1081 /* Find another slice to work on. */
1082 if (--top < 0)
1083 break; /* no more -- done! */
1084 lo = stack[top].lo;
1085 hi = stack[top].hi;
1086 extra = stack[top].extra;
1087 extraOnRight = 0;
1088 if (extra < 0) {
1089 extraOnRight = 1;
1090 extra = -extra;
1091 }
1092 continue;
1093 }
1094
1095 /* Pretend the PPs are indexed 0, 1, ..., extra-1.
1096 Then our preselected pivot is at (extra-1)/2, and we
1097 want to move the PPs before that to the left end of
1098 the slice, and the PPs after that to the right end.
1099 The following section changes extra, lo, hi, and the
1100 slice such that:
1101 [lo-extra, lo) contains the smaller PPs.
1102 *lo == our PP.
1103 (lo, hi) contains the unknown elements.
1104 [hi, hi+extra) contains the larger PPs.
1105 */
1106 k = extra >>= 1; /* num PPs to move */
1107 if (extraOnRight) {
1108 /* Swap the smaller PPs to the left end.
1109 Note that this loop actually moves k+1 items:
1110 the last is our PP */
1111 do {
1112 tmp = *lo; *lo = *hi; *hi = tmp;
1113 ++lo; ++hi;
1114 } while (k--);
1115 }
1116 else {
1117 /* Swap the larger PPs to the right end. */
1118 while (k--) {
1119 --lo; --hi;
1120 tmp = *lo; *lo = *hi; *hi = tmp;
1121 }
1122 }
1123 --lo; /* *lo is now our PP */
1124 pivot = *lo;
1125
1126 /* Now an almost-ordinary quicksort partition step.
1127 Note that most of the time is spent here!
1128 Only odd thing is that we partition into < and >=,
1129 instead of the usual <= and >=. This helps when
1130 there are lots of duplicates of different values,
1131 because it eventually tends to make subfiles
1132 "pure" (all duplicates), and we special-case for
1133 duplicates later. */
1134 l = lo + 1;
1135 r = hi - 1;
1136 /* assert lo < l < r < hi (small n weeded out above) */
1137
1138 do {
1139 /* slide l right, looking for key >= pivot */
1140 do {
1141 SETK(*l, pivot);
1142 if (k < 0)
1143 ++l;
1144 else
1145 break;
1146 } while (l < r);
1147
1148 /* slide r left, looking for key < pivot */
1149 while (l < r) {
Guido van Rossum42812581998-06-17 14:15:44 +00001150 register PyObject *rval = *r--;
1151 SETK(rval, pivot);
1152 if (k < 0) {
1153 /* swap and advance */
1154 r[1] = *l;
1155 *l++ = rval;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001156 break;
Guido van Rossum42812581998-06-17 14:15:44 +00001157 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001158 }
1159
1160 } while (l < r);
1161
1162 /* assert lo < r <= l < hi
1163 assert r == l or r+1 == l
1164 everything to the left of l is < pivot, and
1165 everything to the right of r is >= pivot */
1166
1167 if (l == r) {
1168 SETK(*r, pivot);
1169 if (k < 0)
1170 ++l;
1171 else
1172 --r;
1173 }
1174 /* assert lo <= r and r+1 == l and l <= hi
1175 assert r == lo or a[r] < pivot
1176 assert a[lo] is pivot
1177 assert l == hi or a[l] >= pivot
1178 Swap the pivot into "the middle", so we can henceforth
1179 ignore it.
1180 */
1181 *lo = *r;
1182 *r = pivot;
1183
1184 /* The following is true now, & will be preserved:
1185 All in [lo,r) are < pivot
1186 All in [r,l) == pivot (& so can be ignored)
1187 All in [l,hi) are >= pivot */
1188
1189 /* Check for duplicates of the pivot. One compare is
1190 wasted if there are no duplicates, but can win big
1191 when there are.
1192 Tricky: we're sticking to "<" compares, so deduce
1193 equality indirectly. We know pivot <= *l, so they're
1194 equal iff not pivot < *l.
1195 */
1196 while (l < hi) {
1197 /* pivot <= *l known */
1198 SETK(pivot, *l);
1199 if (k < 0)
1200 break;
1201 else
1202 /* <= and not < implies == */
1203 ++l;
1204 }
1205
1206 /* assert lo <= r < l <= hi
1207 Partitions are [lo, r) and [l, hi) */
1208
1209 /* push fattest first; remember we still have extra PPs
1210 to the left of the left chunk and to the right of
1211 the right chunk! */
1212 /* assert top < STACKSIZE */
1213 if (r - lo <= hi - l) {
1214 /* second is bigger */
1215 stack[top].lo = l;
1216 stack[top].hi = hi;
1217 stack[top].extra = -extra;
1218 hi = r;
1219 extraOnRight = 0;
1220 }
1221 else {
1222 /* first is bigger */
1223 stack[top].lo = lo;
1224 stack[top].hi = r;
1225 stack[top].extra = extra;
1226 lo = l;
1227 extraOnRight = 1;
1228 }
1229 ++top;
1230
1231 } /* end of partitioning loop */
1232
1233 return 0;
1234
1235 fail:
1236 return -1;
1237}
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001238
1239#undef SETK
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001240
1241staticforward PyTypeObject immutable_list_type;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001242
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001243static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00001244listsort(PyListObject *self, PyObject *args)
Guido van Rossum3f236de1996-12-10 23:55:39 +00001245{
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001246 int err;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001247 PyObject *compare = NULL;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001248
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001249 if (args != NULL) {
Guido van Rossumc00a9382000-02-24 21:48:29 +00001250 if (!PyArg_ParseTuple(args, "|O:sort", &compare))
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001251 return NULL;
1252 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001253 self->ob_type = &immutable_list_type;
1254 err = samplesortslice(self->ob_item,
1255 self->ob_item + self->ob_size,
Guido van Rossum42812581998-06-17 14:15:44 +00001256 compare);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001257 self->ob_type = &PyList_Type;
1258 if (err < 0)
Guido van Rossum3f236de1996-12-10 23:55:39 +00001259 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001260 Py_INCREF(Py_None);
1261 return Py_None;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001262}
1263
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001264int
Fred Drakea2f55112000-07-09 15:16:51 +00001265PyList_Sort(PyObject *v)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001266{
1267 if (v == NULL || !PyList_Check(v)) {
1268 PyErr_BadInternalCall();
1269 return -1;
1270 }
1271 v = listsort((PyListObject *)v, (PyObject *)NULL);
1272 if (v == NULL)
1273 return -1;
1274 Py_DECREF(v);
1275 return 0;
1276}
1277
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001278static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00001279listreverse(PyListObject *self, PyObject *args)
Guido van Rossumed98d481991-03-06 13:07:53 +00001280{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001281 register PyObject **p, **q;
1282 register PyObject *tmp;
Guido van Rossumed98d481991-03-06 13:07:53 +00001283
Guido van Rossumc00a9382000-02-24 21:48:29 +00001284 if (!PyArg_ParseTuple(args, ":reverse"))
Guido van Rossumed98d481991-03-06 13:07:53 +00001285 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00001286
1287 if (self->ob_size > 1) {
1288 for (p = self->ob_item, q = self->ob_item + self->ob_size - 1;
1289 p < q; p++, q--) {
1290 tmp = *p;
1291 *p = *q;
1292 *q = tmp;
1293 }
1294 }
1295
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001296 Py_INCREF(Py_None);
1297 return Py_None;
Guido van Rossumed98d481991-03-06 13:07:53 +00001298}
1299
Guido van Rossum84c76f51990-10-30 13:32:20 +00001300int
Fred Drakea2f55112000-07-09 15:16:51 +00001301PyList_Reverse(PyObject *v)
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00001302{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001303 if (v == NULL || !PyList_Check(v)) {
1304 PyErr_BadInternalCall();
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00001305 return -1;
1306 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001307 v = listreverse((PyListObject *)v, (PyObject *)NULL);
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00001308 if (v == NULL)
1309 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001310 Py_DECREF(v);
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00001311 return 0;
1312}
1313
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001314PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00001315PyList_AsTuple(PyObject *v)
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00001316{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001317 PyObject *w;
1318 PyObject **p;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00001319 int n;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001320 if (v == NULL || !PyList_Check(v)) {
1321 PyErr_BadInternalCall();
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00001322 return NULL;
1323 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001324 n = ((PyListObject *)v)->ob_size;
1325 w = PyTuple_New(n);
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00001326 if (w == NULL)
1327 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001328 p = ((PyTupleObject *)w)->ob_item;
Thomas Wouters334fb892000-07-25 12:56:38 +00001329 memcpy((void *)p,
1330 (void *)((PyListObject *)v)->ob_item,
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001331 n*sizeof(PyObject *));
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00001332 while (--n >= 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001333 Py_INCREF(*p);
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00001334 p++;
1335 }
1336 return w;
1337}
1338
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001339static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00001340listindex(PyListObject *self, PyObject *args)
Guido van Rossumed98d481991-03-06 13:07:53 +00001341{
1342 int i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001343 PyObject *v;
1344
Guido van Rossumef93b872000-03-13 15:41:59 +00001345 if (!PyArg_ParseTuple_Compat1(args, "O:index", &v))
Guido van Rossumed98d481991-03-06 13:07:53 +00001346 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00001347 for (i = 0; i < self->ob_size; i++) {
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001348 if (PyObject_Compare(self->ob_item[i], v) == 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001349 return PyInt_FromLong((long)i);
Guido van Rossumc8b6df91997-05-23 00:06:51 +00001350 if (PyErr_Occurred())
1351 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00001352 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001353 PyErr_SetString(PyExc_ValueError, "list.index(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00001354 return NULL;
1355}
1356
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001357static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00001358listcount(PyListObject *self, PyObject *args)
Guido van Rossume6f7d181991-10-20 20:20:40 +00001359{
1360 int count = 0;
1361 int i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001362 PyObject *v;
1363
Guido van Rossumef93b872000-03-13 15:41:59 +00001364 if (!PyArg_ParseTuple_Compat1(args, "O:count", &v))
Guido van Rossume6f7d181991-10-20 20:20:40 +00001365 return NULL;
Guido van Rossume6f7d181991-10-20 20:20:40 +00001366 for (i = 0; i < self->ob_size; i++) {
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001367 if (PyObject_Compare(self->ob_item[i], v) == 0)
Guido van Rossume6f7d181991-10-20 20:20:40 +00001368 count++;
Guido van Rossumc8b6df91997-05-23 00:06:51 +00001369 if (PyErr_Occurred())
1370 return NULL;
Guido van Rossume6f7d181991-10-20 20:20:40 +00001371 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001372 return PyInt_FromLong((long)count);
Guido van Rossume6f7d181991-10-20 20:20:40 +00001373}
1374
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001375static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00001376listremove(PyListObject *self, PyObject *args)
Guido van Rossumed98d481991-03-06 13:07:53 +00001377{
1378 int i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001379 PyObject *v;
1380
Guido van Rossumef93b872000-03-13 15:41:59 +00001381 if (!PyArg_ParseTuple_Compat1(args, "O:remove", &v))
Guido van Rossumed98d481991-03-06 13:07:53 +00001382 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00001383 for (i = 0; i < self->ob_size; i++) {
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001384 if (PyObject_Compare(self->ob_item[i], v) == 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001385 if (list_ass_slice(self, i, i+1,
1386 (PyObject *)NULL) != 0)
Guido van Rossumed98d481991-03-06 13:07:53 +00001387 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001388 Py_INCREF(Py_None);
1389 return Py_None;
Guido van Rossumed98d481991-03-06 13:07:53 +00001390 }
Guido van Rossumc8b6df91997-05-23 00:06:51 +00001391 if (PyErr_Occurred())
1392 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00001393 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001394 PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00001395 return NULL;
1396}
1397
Jeremy Hylton8caad492000-06-23 14:18:11 +00001398static int
1399list_traverse(PyListObject *o, visitproc visit, void *arg)
1400{
1401 int i, err;
1402 PyObject *x;
1403
1404 for (i = o->ob_size; --i >= 0; ) {
1405 x = o->ob_item[i];
1406 if (x != NULL) {
1407 err = visit(x, arg);
1408 if (err)
1409 return err;
1410 }
1411 }
1412 return 0;
1413}
1414
1415static int
1416list_clear(PyListObject *lp)
1417{
1418 (void) PyList_SetSlice((PyObject *)lp, 0, lp->ob_size, 0);
1419 return 0;
1420}
1421
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +00001422static char append_doc[] =
1423"L.append(object) -- append object to end";
Barry Warsawdedf6d61998-10-09 16:37:25 +00001424static char extend_doc[] =
1425"L.extend(list) -- extend list by appending list elements";
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +00001426static char insert_doc[] =
1427"L.insert(index, object) -- insert object before index";
1428static char pop_doc[] =
1429"L.pop([index]) -> item -- remove and return item at index (default last)";
1430static char remove_doc[] =
1431"L.remove(value) -- remove first occurrence of value";
1432static char index_doc[] =
1433"L.index(value) -> integer -- return index of first occurrence of value";
1434static char count_doc[] =
1435"L.count(value) -> integer -- return number of occurrences of value";
1436static char reverse_doc[] =
1437"L.reverse() -- reverse *IN PLACE*";
1438static char sort_doc[] =
1439"L.sort([cmpfunc]) -- sort *IN PLACE*; if given, cmpfunc(x, y) -> -1, 0, 1";
1440
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001441static PyMethodDef list_methods[] = {
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001442 {"append", (PyCFunction)listappend, 1, append_doc},
1443 {"insert", (PyCFunction)listinsert, 1, insert_doc},
Barry Warsawdedf6d61998-10-09 16:37:25 +00001444 {"extend", (PyCFunction)listextend, 1, extend_doc},
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +00001445 {"pop", (PyCFunction)listpop, 1, pop_doc},
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001446 {"remove", (PyCFunction)listremove, 1, remove_doc},
1447 {"index", (PyCFunction)listindex, 1, index_doc},
1448 {"count", (PyCFunction)listcount, 1, count_doc},
1449 {"reverse", (PyCFunction)listreverse, 1, reverse_doc},
1450 {"sort", (PyCFunction)listsort, 1, sort_doc},
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001451 {NULL, NULL} /* sentinel */
1452};
1453
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001454static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00001455list_getattr(PyListObject *f, char *name)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001456{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001457 return Py_FindMethod(list_methods, (PyObject *)f, name);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001458}
1459
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001460static PySequenceMethods list_as_sequence = {
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00001461 (inquiry)list_length, /*sq_length*/
1462 (binaryfunc)list_concat, /*sq_concat*/
1463 (intargfunc)list_repeat, /*sq_repeat*/
1464 (intargfunc)list_item, /*sq_item*/
1465 (intintargfunc)list_slice, /*sq_slice*/
1466 (intobjargproc)list_ass_item, /*sq_ass_item*/
1467 (intintobjargproc)list_ass_slice, /*sq_ass_slice*/
Jeremy Hylton37b1a262000-04-27 21:41:03 +00001468 (objobjproc)list_contains, /*sq_contains*/
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001469 (binaryfunc)list_inplace_concat, /*sq_inplace_concat*/
1470 (intargfunc)list_inplace_repeat, /*sq_inplace_repeat*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001471};
1472
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001473PyTypeObject PyList_Type = {
1474 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001475 0,
1476 "list",
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001477 sizeof(PyListObject) + PyGC_HEAD_SIZE,
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001478 0,
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00001479 (destructor)list_dealloc, /*tp_dealloc*/
1480 (printfunc)list_print, /*tp_print*/
1481 (getattrfunc)list_getattr, /*tp_getattr*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001482 0, /*tp_setattr*/
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00001483 (cmpfunc)list_compare, /*tp_compare*/
1484 (reprfunc)list_repr, /*tp_repr*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001485 0, /*tp_as_number*/
1486 &list_as_sequence, /*tp_as_sequence*/
1487 0, /*tp_as_mapping*/
Fred Drake56780252000-06-15 14:50:20 +00001488 0, /*tp_hash*/
1489 0, /*tp_call*/
1490 0, /*tp_str*/
1491 0, /*tp_getattro*/
1492 0, /*tp_setattro*/
1493 0, /*tp_as_buffer*/
Jeremy Hyltond08b4c42000-06-23 19:37:02 +00001494 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_GC, /*tp_flags*/
Jeremy Hylton8caad492000-06-23 14:18:11 +00001495 0, /* tp_doc */
1496 (traverseproc)list_traverse, /* tp_traverse */
1497 (inquiry)list_clear, /* tp_clear */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001498};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001499
1500
1501/* During a sort, we really can't have anyone modifying the list; it could
1502 cause core dumps. Thus, we substitute a dummy type that raises an
1503 explanatory exception when a modifying operation is used. Caveat:
1504 comparisons may behave differently; but I guess it's a bad idea anyway to
1505 compare a list that's being sorted... */
1506
1507static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00001508immutable_list_op(void)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001509{
1510 PyErr_SetString(PyExc_TypeError,
1511 "a list cannot be modified while it is being sorted");
1512 return NULL;
1513}
1514
1515static PyMethodDef immutable_list_methods[] = {
1516 {"append", (PyCFunction)immutable_list_op},
1517 {"insert", (PyCFunction)immutable_list_op},
1518 {"remove", (PyCFunction)immutable_list_op},
1519 {"index", (PyCFunction)listindex},
1520 {"count", (PyCFunction)listcount},
1521 {"reverse", (PyCFunction)immutable_list_op},
1522 {"sort", (PyCFunction)immutable_list_op},
1523 {NULL, NULL} /* sentinel */
1524};
1525
1526static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00001527immutable_list_getattr(PyListObject *f, char *name)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001528{
1529 return Py_FindMethod(immutable_list_methods, (PyObject *)f, name);
1530}
1531
1532static int
Fred Drakea2f55112000-07-09 15:16:51 +00001533immutable_list_ass(void)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001534{
1535 immutable_list_op();
1536 return -1;
1537}
1538
1539static PySequenceMethods immutable_list_as_sequence = {
1540 (inquiry)list_length, /*sq_length*/
1541 (binaryfunc)list_concat, /*sq_concat*/
1542 (intargfunc)list_repeat, /*sq_repeat*/
1543 (intargfunc)list_item, /*sq_item*/
1544 (intintargfunc)list_slice, /*sq_slice*/
1545 (intobjargproc)immutable_list_ass, /*sq_ass_item*/
1546 (intintobjargproc)immutable_list_ass, /*sq_ass_slice*/
Fred Drake56780252000-06-15 14:50:20 +00001547 (objobjproc)list_contains, /*sq_contains*/
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001548};
1549
1550static PyTypeObject immutable_list_type = {
1551 PyObject_HEAD_INIT(&PyType_Type)
1552 0,
1553 "list (immutable, during sort)",
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001554 sizeof(PyListObject) + PyGC_HEAD_SIZE,
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001555 0,
1556 0, /*tp_dealloc*/ /* Cannot happen */
1557 (printfunc)list_print, /*tp_print*/
1558 (getattrfunc)immutable_list_getattr, /*tp_getattr*/
1559 0, /*tp_setattr*/
1560 0, /*tp_compare*/ /* Won't be called */
1561 (reprfunc)list_repr, /*tp_repr*/
1562 0, /*tp_as_number*/
1563 &immutable_list_as_sequence, /*tp_as_sequence*/
1564 0, /*tp_as_mapping*/
Fred Drake56780252000-06-15 14:50:20 +00001565 0, /*tp_hash*/
1566 0, /*tp_call*/
1567 0, /*tp_str*/
1568 0, /*tp_getattro*/
1569 0, /*tp_setattro*/
1570 0, /*tp_as_buffer*/
Jeremy Hyltond08b4c42000-06-23 19:37:02 +00001571 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_GC, /*tp_flags*/
Jeremy Hylton8caad492000-06-23 14:18:11 +00001572 0, /* tp_doc */
1573 (traverseproc)list_traverse, /* tp_traverse */
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001574};