blob: 52640fb0837795d43f25fe6d058e21610b16de54 [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001/***********************************************************
Guido van Rossumfd71b9e2000-06-30 23:50:40 +00002Copyright (c) 2000, BeOpen.com.
3Copyright (c) 1995-2000, Corporation for National Research Initiatives.
4Copyright (c) 1990-1995, Stichting Mathematisch Centrum.
5All rights reserved.
Guido van Rossumf70e43a1991-02-19 12:39:46 +00006
Guido van Rossumfd71b9e2000-06-30 23:50:40 +00007See the file "Misc/COPYRIGHT" for information on usage and
8redistribution of this file, and for a DISCLAIMER OF ALL WARRANTIES.
Guido van Rossumf70e43a1991-02-19 12:39:46 +00009******************************************************************/
10
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000011/* List object implementation */
12
Guido van Rossumc0b618a1997-05-02 03:12:38 +000013#include "Python.h"
14
Guido van Rossum6cd2fe01994-08-29 12:45:32 +000015#ifdef STDC_HEADERS
16#include <stddef.h>
17#else
18#include <sys/types.h> /* For size_t */
19#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000020
Guido van Rossumc0b618a1997-05-02 03:12:38 +000021#define ROUNDUP(n, PyTryBlock) \
22 ((((n)+(PyTryBlock)-1)/(PyTryBlock))*(PyTryBlock))
Guido van Rossuma46d51d1995-01-26 22:59:43 +000023
24static int
Fred Drakea2f55112000-07-09 15:16:51 +000025roundupsize(int n)
Guido van Rossuma46d51d1995-01-26 22:59:43 +000026{
27 if (n < 500)
28 return ROUNDUP(n, 10);
29 else
30 return ROUNDUP(n, 100);
31}
32
Guido van Rossuma27d1121997-08-25 18:36:23 +000033#define NRESIZE(var, type, nitems) PyMem_RESIZE(var, type, roundupsize(nitems))
Guido van Rossuma46d51d1995-01-26 22:59:43 +000034
Guido van Rossumc0b618a1997-05-02 03:12:38 +000035PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +000036PyList_New(int size)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000037{
38 int i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +000039 PyListObject *op;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +000040 size_t nbytes;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000041 if (size < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +000042 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000043 return NULL;
44 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +000045 nbytes = size * sizeof(PyObject *);
Guido van Rossum1e28e5e1992-08-19 16:46:30 +000046 /* Check for overflow */
Guido van Rossumc0b618a1997-05-02 03:12:38 +000047 if (nbytes / sizeof(PyObject *) != (size_t)size) {
48 return PyErr_NoMemory();
Guido van Rossum1e28e5e1992-08-19 16:46:30 +000049 }
Guido van Rossumb18618d2000-05-03 23:44:39 +000050 /* PyObject_NewVar is inlined */
Jeremy Hyltond08b4c42000-06-23 19:37:02 +000051 op = (PyListObject *) PyObject_MALLOC(sizeof(PyListObject)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +000052 + PyGC_HEAD_SIZE);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000053 if (op == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +000054 return PyErr_NoMemory();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000055 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +000056 op = (PyListObject *) PyObject_FROM_GC(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000057 if (size <= 0) {
58 op->ob_item = NULL;
59 }
60 else {
Guido van Rossumb18618d2000-05-03 23:44:39 +000061 op->ob_item = (PyObject **) PyMem_MALLOC(nbytes);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000062 if (op->ob_item == NULL) {
Vladimir Marangozov467a67e2000-07-15 03:31:31 +000063 PyObject_FREE(PyObject_AS_GC(op));
Guido van Rossumc0b618a1997-05-02 03:12:38 +000064 return PyErr_NoMemory();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000065 }
66 }
Guido van Rossumb18618d2000-05-03 23:44:39 +000067 PyObject_INIT_VAR(op, &PyList_Type, size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000068 for (i = 0; i < size; i++)
69 op->ob_item[i] = NULL;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +000070 PyObject_GC_Init(op);
Guido van Rossumc0b618a1997-05-02 03:12:38 +000071 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000072}
73
74int
Fred Drakea2f55112000-07-09 15:16:51 +000075PyList_Size(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000076{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000077 if (!PyList_Check(op)) {
78 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000079 return -1;
80 }
81 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +000082 return ((PyListObject *)op) -> ob_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000083}
84
Guido van Rossumc0b618a1997-05-02 03:12:38 +000085static PyObject *indexerr;
Guido van Rossum929f1b81996-08-09 20:51:27 +000086
Guido van Rossumc0b618a1997-05-02 03:12:38 +000087PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +000088PyList_GetItem(PyObject *op, int i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000089{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000090 if (!PyList_Check(op)) {
91 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000092 return NULL;
93 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +000094 if (i < 0 || i >= ((PyListObject *)op) -> ob_size) {
Guido van Rossum929f1b81996-08-09 20:51:27 +000095 if (indexerr == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +000096 indexerr = PyString_FromString(
97 "list index out of range");
98 PyErr_SetObject(PyExc_IndexError, indexerr);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000099 return NULL;
100 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000101 return ((PyListObject *)op) -> ob_item[i];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000102}
103
104int
Fred Drakea2f55112000-07-09 15:16:51 +0000105PyList_SetItem(register PyObject *op, register int i,
106 register PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000107{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000108 register PyObject *olditem;
109 register PyObject **p;
110 if (!PyList_Check(op)) {
111 Py_XDECREF(newitem);
112 PyErr_BadInternalCall();
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 if (i < 0 || i >= ((PyListObject *)op) -> ob_size) {
116 Py_XDECREF(newitem);
117 PyErr_SetString(PyExc_IndexError,
118 "list assignment index out of range");
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000119 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000120 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000121 p = ((PyListObject *)op) -> ob_item + i;
Guido van Rossum5fe60581995-03-09 12:12:50 +0000122 olditem = *p;
123 *p = newitem;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000124 Py_XDECREF(olditem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000125 return 0;
126}
127
128static int
Fred Drakea2f55112000-07-09 15:16:51 +0000129ins1(PyListObject *self, int where, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000130{
131 int i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000132 PyObject **items;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000133 if (v == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000134 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000135 return -1;
136 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000137 items = self->ob_item;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000138 NRESIZE(items, PyObject *, self->ob_size+1);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000139 if (items == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000140 PyErr_NoMemory();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000141 return -1;
142 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000143 if (where < 0)
144 where = 0;
145 if (where > self->ob_size)
146 where = self->ob_size;
147 for (i = self->ob_size; --i >= where; )
148 items[i+1] = items[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000149 Py_INCREF(v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000150 items[where] = v;
151 self->ob_item = items;
152 self->ob_size++;
153 return 0;
154}
155
156int
Fred Drakea2f55112000-07-09 15:16:51 +0000157PyList_Insert(PyObject *op, int where, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000158{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000159 if (!PyList_Check(op)) {
160 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000161 return -1;
162 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000163 return ins1((PyListObject *)op, where, newitem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000164}
165
166int
Fred Drakea2f55112000-07-09 15:16:51 +0000167PyList_Append(PyObject *op, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000168{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000169 if (!PyList_Check(op)) {
170 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000171 return -1;
172 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000173 return ins1((PyListObject *)op,
174 (int) ((PyListObject *)op)->ob_size, newitem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000175}
176
177/* Methods */
178
179static void
Fred Drakea2f55112000-07-09 15:16:51 +0000180list_dealloc(PyListObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000181{
182 int i;
Guido van Rossumd724b232000-03-13 16:01:29 +0000183 Py_TRASHCAN_SAFE_BEGIN(op)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000184 PyObject_GC_Fini(op);
Jack Jansen7874d1f1995-01-19 12:09:27 +0000185 if (op->ob_item != NULL) {
Guido van Rossumfa717011999-06-09 15:19:34 +0000186 /* Do it backwards, for Christian Tismer.
187 There's a simple test case where somehow this reduces
188 thrashing when a *very* large list is created and
189 immediately deleted. */
190 i = op->ob_size;
191 while (--i >= 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000192 Py_XDECREF(op->ob_item[i]);
Jack Jansen7874d1f1995-01-19 12:09:27 +0000193 }
Guido van Rossumb18618d2000-05-03 23:44:39 +0000194 PyMem_FREE(op->ob_item);
Jack Jansen7874d1f1995-01-19 12:09:27 +0000195 }
Guido van Rossum4cc6ac72000-07-01 01:00:38 +0000196 op = (PyListObject *) PyObject_AS_GC(op);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000197 PyObject_DEL(op);
Guido van Rossumd724b232000-03-13 16:01:29 +0000198 Py_TRASHCAN_SAFE_END(op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000199}
200
Guido van Rossum90933611991-06-07 16:10:43 +0000201static int
Fred Drakea2f55112000-07-09 15:16:51 +0000202list_print(PyListObject *op, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000203{
204 int i;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000205
206 i = Py_ReprEnter((PyObject*)op);
207 if (i != 0) {
208 if (i < 0)
209 return i;
210 fprintf(fp, "[...]");
211 return 0;
212 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000213 fprintf(fp, "[");
Guido van Rossum90933611991-06-07 16:10:43 +0000214 for (i = 0; i < op->ob_size; i++) {
215 if (i > 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000216 fprintf(fp, ", ");
Guido van Rossumfb376de1998-04-10 22:47:27 +0000217 if (PyObject_Print(op->ob_item[i], fp, 0) != 0) {
218 Py_ReprLeave((PyObject *)op);
Guido van Rossum90933611991-06-07 16:10:43 +0000219 return -1;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000220 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000221 }
222 fprintf(fp, "]");
Guido van Rossumfb376de1998-04-10 22:47:27 +0000223 Py_ReprLeave((PyObject *)op);
Guido van Rossum90933611991-06-07 16:10:43 +0000224 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000225}
226
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000227static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000228list_repr(PyListObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000229{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000230 PyObject *s, *comma;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000231 int i;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000232
233 i = Py_ReprEnter((PyObject*)v);
234 if (i != 0) {
235 if (i > 0)
236 return PyString_FromString("[...]");
237 return NULL;
238 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000239 s = PyString_FromString("[");
240 comma = PyString_FromString(", ");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000241 for (i = 0; i < v->ob_size && s != NULL; i++) {
242 if (i > 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000243 PyString_Concat(&s, comma);
244 PyString_ConcatAndDel(&s, PyObject_Repr(v->ob_item[i]));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000245 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000246 Py_XDECREF(comma);
247 PyString_ConcatAndDel(&s, PyString_FromString("]"));
Guido van Rossumfb376de1998-04-10 22:47:27 +0000248 Py_ReprLeave((PyObject *)v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000249 return s;
250}
251
252static int
Fred Drakea2f55112000-07-09 15:16:51 +0000253list_compare(PyListObject *v, PyListObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000254{
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000255 int i;
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
Guido van Rossum4a450d01991-04-03 19:05:18 +0000490static int
Fred Drakea2f55112000-07-09 15:16:51 +0000491list_ass_item(PyListObject *a, int i, PyObject *v)
Guido van Rossum4a450d01991-04-03 19:05:18 +0000492{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000493 PyObject *old_value;
Guido van Rossum4a450d01991-04-03 19:05:18 +0000494 if (i < 0 || i >= a->ob_size) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000495 PyErr_SetString(PyExc_IndexError,
496 "list assignment index out of range");
Guido van Rossum4a450d01991-04-03 19:05:18 +0000497 return -1;
498 }
499 if (v == NULL)
500 return list_ass_slice(a, i, i+1, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000501 Py_INCREF(v);
Guido van Rossumd7047b31995-01-02 19:07:15 +0000502 old_value = a->ob_item[i];
Guido van Rossum4a450d01991-04-03 19:05:18 +0000503 a->ob_item[i] = v;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000504 Py_DECREF(old_value);
Guido van Rossum4a450d01991-04-03 19:05:18 +0000505 return 0;
506}
507
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000508static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000509ins(PyListObject *self, int where, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000510{
511 if (ins1(self, where, v) != 0)
512 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000513 Py_INCREF(Py_None);
514 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000515}
516
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000517static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000518listinsert(PyListObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000519{
520 int i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000521 PyObject *v;
Guido van Rossumc00a9382000-02-24 21:48:29 +0000522 if (!PyArg_ParseTuple(args, "iO:insert", &i, &v))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000523 return NULL;
Guido van Rossumbf80e541993-02-08 15:49:17 +0000524 return ins(self, i, v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000525}
526
Guido van Rossumef93b872000-03-13 15:41:59 +0000527/* Define NO_STRICT_LIST_APPEND to enable multi-argument append() */
528
529#ifndef NO_STRICT_LIST_APPEND
530#define PyArg_ParseTuple_Compat1 PyArg_ParseTuple
531#else
532#define PyArg_ParseTuple_Compat1(args, format, ret) \
533( \
534 PyTuple_GET_SIZE(args) > 1 ? (*ret = args, 1) : \
535 PyTuple_GET_SIZE(args) == 1 ? (*ret = PyTuple_GET_ITEM(args, 0), 1) : \
536 PyArg_ParseTuple(args, format, ret) \
537)
538#endif
539
540
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000541static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000542listappend(PyListObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000543{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000544 PyObject *v;
Guido van Rossumef93b872000-03-13 15:41:59 +0000545 if (!PyArg_ParseTuple_Compat1(args, "O:append", &v))
Guido van Rossumbf80e541993-02-08 15:49:17 +0000546 return NULL;
547 return ins(self, (int) self->ob_size, v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000548}
549
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000550static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000551listextend(PyListObject *self, PyObject *args)
Barry Warsawdedf6d61998-10-09 16:37:25 +0000552{
553 PyObject *b = NULL, *res = NULL;
554 PyObject **items;
555 int selflen = PyList_GET_SIZE(self);
556 int blen;
557 register int i;
558
Guido van Rossumc00a9382000-02-24 21:48:29 +0000559 if (!PyArg_ParseTuple(args, "O:extend", &b))
Barry Warsawdedf6d61998-10-09 16:37:25 +0000560 return NULL;
561
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000562 b = PySequence_Fast(b, "list.extend() argument must be a sequence");
563 if (!b)
Barry Warsawdedf6d61998-10-09 16:37:25 +0000564 return NULL;
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000565
Jeremy Hylton03657cf2000-07-12 13:05:33 +0000566 if (PyObject_Size(b) == 0)
Barry Warsawdedf6d61998-10-09 16:37:25 +0000567 /* short circuit when b is empty */
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000568 goto ok;
569
Barry Warsawdedf6d61998-10-09 16:37:25 +0000570 if (self == (PyListObject*)b) {
571 /* as in list_ass_slice() we must special case the
572 * situation: a.extend(a)
573 *
574 * XXX: I think this way ought to be faster than using
575 * list_slice() the way list_ass_slice() does.
576 */
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000577 Py_DECREF(b);
Barry Warsawdedf6d61998-10-09 16:37:25 +0000578 b = PyList_New(selflen);
579 if (!b)
580 return NULL;
581 for (i = 0; i < selflen; i++) {
582 PyObject *o = PyList_GET_ITEM(self, i);
583 Py_INCREF(o);
584 PyList_SET_ITEM(b, i, o);
585 }
586 }
Barry Warsawdedf6d61998-10-09 16:37:25 +0000587
Jeremy Hylton03657cf2000-07-12 13:05:33 +0000588 blen = PyObject_Size(b);
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000589
Barry Warsawdedf6d61998-10-09 16:37:25 +0000590 /* resize a using idiom */
591 items = self->ob_item;
592 NRESIZE(items, PyObject*, selflen + blen);
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000593 if (items == NULL) {
Barry Warsawdedf6d61998-10-09 16:37:25 +0000594 PyErr_NoMemory();
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000595 goto failed;
Barry Warsawdedf6d61998-10-09 16:37:25 +0000596 }
597 self->ob_item = items;
598
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000599 /* populate the end of self with b's items */
Barry Warsawdedf6d61998-10-09 16:37:25 +0000600 for (i = 0; i < blen; i++) {
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000601 PyObject *o = PySequence_Fast_GET_ITEM(b, i);
Barry Warsawdedf6d61998-10-09 16:37:25 +0000602 Py_INCREF(o);
603 PyList_SET_ITEM(self, self->ob_size++, o);
604 }
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000605 ok:
Barry Warsawdedf6d61998-10-09 16:37:25 +0000606 res = Py_None;
607 Py_INCREF(res);
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000608 failed:
609 Py_DECREF(b);
Barry Warsawdedf6d61998-10-09 16:37:25 +0000610 return res;
611}
612
613
614static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000615listpop(PyListObject *self, PyObject *args)
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000616{
617 int i = -1;
618 PyObject *v;
Guido van Rossumc00a9382000-02-24 21:48:29 +0000619 if (!PyArg_ParseTuple(args, "|i:pop", &i))
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000620 return NULL;
621 if (self->ob_size == 0) {
622 /* Special-case most common failure cause */
623 PyErr_SetString(PyExc_IndexError, "pop from empty list");
624 return NULL;
625 }
626 if (i < 0)
627 i += self->ob_size;
628 if (i < 0 || i >= self->ob_size) {
629 PyErr_SetString(PyExc_IndexError, "pop index out of range");
630 return NULL;
631 }
632 v = self->ob_item[i];
633 Py_INCREF(v);
634 if (list_ass_slice(self, i, i+1, (PyObject *)NULL) != 0) {
635 Py_DECREF(v);
636 return NULL;
637 }
638 return v;
639}
640
Guido van Rossum3f236de1996-12-10 23:55:39 +0000641/* New quicksort implementation for arrays of object pointers.
642 Thanks to discussions with Tim Peters. */
643
644/* CMPERROR is returned by our comparison function when an error
645 occurred. This is the largest negative integer (0x80000000 on a
646 32-bit system). */
Guido van Rossum19700b61997-03-05 00:45:43 +0000647#define CMPERROR ( (int) ((unsigned int)1 << (8*sizeof(int) - 1)) )
Guido van Rossum3f236de1996-12-10 23:55:39 +0000648
649/* Comparison function. Takes care of calling a user-supplied
650 comparison function (any callable Python object). Calls the
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000651 standard comparison function, PyObject_Compare(), if the user-
652 supplied function is NULL. */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000653
654static int
Fred Drakea2f55112000-07-09 15:16:51 +0000655docompare(PyObject *x, PyObject *y, PyObject *compare)
Guido van Rossum3f236de1996-12-10 23:55:39 +0000656{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000657 PyObject *args, *res;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000658 int i;
659
Guido van Rossumc8b6df91997-05-23 00:06:51 +0000660 if (compare == NULL) {
661 i = PyObject_Compare(x, y);
662 if (i && PyErr_Occurred())
663 i = CMPERROR;
664 return i;
665 }
Guido van Rossum3f236de1996-12-10 23:55:39 +0000666
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000667 args = Py_BuildValue("(OO)", x, y);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000668 if (args == NULL)
669 return CMPERROR;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000670 res = PyEval_CallObject(compare, args);
671 Py_DECREF(args);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000672 if (res == NULL)
673 return CMPERROR;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000674 if (!PyInt_Check(res)) {
675 Py_DECREF(res);
676 PyErr_SetString(PyExc_TypeError,
Guido van Rossum9bcd1d71999-04-19 17:44:39 +0000677 "comparison function must return int");
Guido van Rossum3f236de1996-12-10 23:55:39 +0000678 return CMPERROR;
679 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000680 i = PyInt_AsLong(res);
681 Py_DECREF(res);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000682 if (i < 0)
683 return -1;
684 if (i > 0)
685 return 1;
686 return 0;
687}
688
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000689/* MINSIZE is the smallest array that will get a full-blown samplesort
690 treatment; smaller arrays are sorted using binary insertion. It must
691 be at least 7 for the samplesort implementation to work. Binary
692 insertion does fewer compares, but can suffer O(N**2) data movement.
693 The more expensive compares, the larger MINSIZE should be. */
694#define MINSIZE 100
695
696/* MINPARTITIONSIZE is the smallest array slice samplesort will bother to
697 partition; smaller slices are passed to binarysort. It must be at
698 least 2, and no larger than MINSIZE. Setting it higher reduces the #
699 of compares slowly, but increases the amount of data movement quickly.
700 The value here was chosen assuming a compare costs ~25x more than
701 swapping a pair of memory-resident pointers -- but under that assumption,
702 changing the value by a few dozen more or less has aggregate effect
703 under 1%. So the value is crucial, but not touchy <wink>. */
704#define MINPARTITIONSIZE 40
705
706/* MAXMERGE is the largest number of elements we'll always merge into
707 a known-to-be sorted chunk via binary insertion, regardless of the
708 size of that chunk. Given a chunk of N sorted elements, and a group
709 of K unknowns, the largest K for which it's better to do insertion
710 (than a full-blown sort) is a complicated function of N and K mostly
711 involving the expected number of compares and data moves under each
712 approach, and the relative cost of those operations on a specific
713 architecure. The fixed value here is conservative, and should be a
714 clear win regardless of architecture or N. */
715#define MAXMERGE 15
Guido van Rossum3f236de1996-12-10 23:55:39 +0000716
Guido van Rossum3f236de1996-12-10 23:55:39 +0000717/* STACKSIZE is the size of our work stack. A rough estimate is that
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000718 this allows us to sort arrays of size N where
719 N / ln(N) = MINPARTITIONSIZE * 2**STACKSIZE, so 60 is more than enough
720 for arrays of size 2**64. Because we push the biggest partition
721 first, the worst case occurs when all subarrays are always partitioned
722 exactly in two. */
723#define STACKSIZE 60
Guido van Rossum3f236de1996-12-10 23:55:39 +0000724
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000725
726#define SETK(X,Y) if ((k = docompare(X,Y,compare))==CMPERROR) goto fail
727
728/* binarysort is the best method for sorting small arrays: it does
729 few compares, but can do data movement quadratic in the number of
730 elements.
Guido van Rossum42812581998-06-17 14:15:44 +0000731 [lo, hi) is a contiguous slice of a list, and is sorted via
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000732 binary insertion.
733 On entry, must have lo <= start <= hi, and that [lo, start) is already
734 sorted (pass start == lo if you don't know!).
735 If docompare complains (returns CMPERROR) return -1, else 0.
736 Even in case of error, the output slice will be some permutation of
737 the input (nothing is lost or duplicated).
738*/
Guido van Rossum3f236de1996-12-10 23:55:39 +0000739
740static int
Fred Drakea2f55112000-07-09 15:16:51 +0000741binarysort(PyObject **lo, PyObject **hi, PyObject **start, PyObject *compare)
742 /* compare -- comparison function object, or NULL for default */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000743{
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000744 /* assert lo <= start <= hi
745 assert [lo, start) is sorted */
746 register int k;
747 register PyObject **l, **p, **r;
748 register PyObject *pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000749
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000750 if (lo == start)
751 ++start;
752 for (; start < hi; ++start) {
753 /* set l to where *start belongs */
754 l = lo;
755 r = start;
Guido van Rossuma119c0d1998-05-29 17:56:32 +0000756 pivot = *r;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000757 do {
758 p = l + ((r - l) >> 1);
759 SETK(pivot, *p);
760 if (k < 0)
761 r = p;
762 else
763 l = p + 1;
764 } while (l < r);
765 /* Pivot should go at l -- slide over to make room.
766 Caution: using memmove is much slower under MSVC 5;
767 we're not usually moving many slots. */
768 for (p = start; p > l; --p)
769 *p = *(p-1);
770 *l = pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000771 }
Guido van Rossum3f236de1996-12-10 23:55:39 +0000772 return 0;
Guido van Rossuma119c0d1998-05-29 17:56:32 +0000773
774 fail:
775 return -1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000776}
777
778/* samplesortslice is the sorting workhorse.
Guido van Rossum42812581998-06-17 14:15:44 +0000779 [lo, hi) is a contiguous slice of a list, to be sorted in place.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000780 On entry, must have lo <= hi,
781 If docompare complains (returns CMPERROR) return -1, else 0.
782 Even in case of error, the output slice will be some permutation of
783 the input (nothing is lost or duplicated).
784
785 samplesort is basically quicksort on steroids: a power of 2 close
786 to n/ln(n) is computed, and that many elements (less 1) are picked at
787 random from the array and sorted. These 2**k - 1 elements are then
788 used as preselected pivots for an equal number of quicksort
789 partitioning steps, partitioning the slice into 2**k chunks each of
790 size about ln(n). These small final chunks are then usually handled
791 by binarysort. Note that when k=1, this is roughly the same as an
792 ordinary quicksort using a random pivot, and when k=2 this is roughly
793 a median-of-3 quicksort. From that view, using k ~= lg(n/ln(n)) makes
794 this a "median of n/ln(n)" quicksort. You can also view it as a kind
795 of bucket sort, where 2**k-1 bucket boundaries are picked dynamically.
796
797 The large number of samples makes a quadratic-time case almost
798 impossible, and asymptotically drives the average-case number of
799 compares from quicksort's 2 N ln N (or 12/7 N ln N for the median-of-
800 3 variant) down to N lg N.
801
802 We also play lots of low-level tricks to cut the number of compares.
803
804 Very obscure: To avoid using extra memory, the PPs are stored in the
805 array and shuffled around as partitioning proceeds. At the start of a
806 partitioning step, we'll have 2**m-1 (for some m) PPs in sorted order,
807 adjacent (either on the left or the right!) to a chunk of X elements
808 that are to be partitioned: P X or X P. In either case we need to
809 shuffle things *in place* so that the 2**(m-1) smaller PPs are on the
810 left, followed by the PP to be used for this step (that's the middle
811 of the PPs), followed by X, followed by the 2**(m-1) larger PPs:
812 P X or X P -> Psmall pivot X Plarge
813 and the order of the PPs must not be altered. It can take a while
814 to realize this isn't trivial! It can take even longer <wink> to
815 understand why the simple code below works, using only 2**(m-1) swaps.
816 The key is that the order of the X elements isn't necessarily
817 preserved: X can end up as some cyclic permutation of its original
818 order. That's OK, because X is unsorted anyway. If the order of X
819 had to be preserved too, the simplest method I know of using O(1)
820 scratch storage requires len(X) + 2**(m-1) swaps, spread over 2 passes.
821 Since len(X) is typically several times larger than 2**(m-1), that
822 would slow things down.
823*/
824
825struct SamplesortStackNode {
826 /* Represents a slice of the array, from (& including) lo up
827 to (but excluding) hi. "extra" additional & adjacent elements
828 are pre-selected pivots (PPs), spanning [lo-extra, lo) if
829 extra > 0, or [hi, hi-extra) if extra < 0. The PPs are
830 already sorted, but nothing is known about the other elements
831 in [lo, hi). |extra| is always one less than a power of 2.
832 When extra is 0, we're out of PPs, and the slice must be
833 sorted by some other means. */
834 PyObject **lo;
835 PyObject **hi;
836 int extra;
837};
838
839/* 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 +0000840 N / ln(N) as possible. So k ~= lg(N / ln(N)). Calling libm routines
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000841 is undesirable, so cutoff values are canned in the "cutoff" table
842 below: cutoff[i] is the smallest N such that k == CUTOFFBASE + i. */
843#define CUTOFFBASE 4
Guido van Rossum3aa23fd1999-01-14 19:01:53 +0000844static long cutoff[] = {
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000845 43, /* smallest N such that k == 4 */
846 106, /* etc */
847 250,
848 576,
849 1298,
850 2885,
851 6339,
852 13805,
853 29843,
854 64116,
855 137030,
856 291554,
857 617916,
858 1305130,
859 2748295,
860 5771662,
861 12091672,
862 25276798,
863 52734615,
864 109820537,
865 228324027,
866 473977813,
867 982548444, /* smallest N such that k == 26 */
868 2034159050 /* largest N that fits in signed 32-bit; k == 27 */
869};
870
871static int
Fred Drakea2f55112000-07-09 15:16:51 +0000872samplesortslice(PyObject **lo, PyObject **hi, PyObject *compare)
873 /* compare -- comparison function object, or NULL for default */
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000874{
875 register PyObject **l, **r;
876 register PyObject *tmp, *pivot;
877 register int k;
878 int n, extra, top, extraOnRight;
879 struct SamplesortStackNode stack[STACKSIZE];
880
881 /* assert lo <= hi */
882 n = hi - lo;
883
884 /* ----------------------------------------------------------
885 * Special cases
886 * --------------------------------------------------------*/
887 if (n < 2)
888 return 0;
889
890 /* Set r to the largest value such that [lo,r) is sorted.
891 This catches the already-sorted case, the all-the-same
892 case, and the appended-a-few-elements-to-a-sorted-list case.
893 If the array is unsorted, we're very likely to get out of
894 the loop fast, so the test is cheap if it doesn't pay off.
895 */
896 /* assert lo < hi */
897 for (r = lo+1; r < hi; ++r) {
898 SETK(*r, *(r-1));
899 if (k < 0)
900 break;
901 }
902 /* [lo,r) is sorted, [r,hi) unknown. Get out cheap if there are
903 few unknowns, or few elements in total. */
904 if (hi - r <= MAXMERGE || n < MINSIZE)
Guido van Rossum42812581998-06-17 14:15:44 +0000905 return binarysort(lo, hi, r, compare);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000906
907 /* Check for the array already being reverse-sorted. Typical
908 benchmark-driven silliness <wink>. */
909 /* assert lo < hi */
910 for (r = lo+1; r < hi; ++r) {
911 SETK(*(r-1), *r);
912 if (k < 0)
913 break;
914 }
915 if (hi - r <= MAXMERGE) {
916 /* Reverse the reversed prefix, then insert the tail */
917 PyObject **originalr = r;
918 l = lo;
919 do {
920 --r;
921 tmp = *l; *l = *r; *r = tmp;
922 ++l;
923 } while (l < r);
Guido van Rossum42812581998-06-17 14:15:44 +0000924 return binarysort(lo, hi, originalr, compare);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000925 }
926
927 /* ----------------------------------------------------------
928 * Normal case setup: a large array without obvious pattern.
929 * --------------------------------------------------------*/
930
931 /* extra := a power of 2 ~= n/ln(n), less 1.
932 First find the smallest extra s.t. n < cutoff[extra] */
933 for (extra = 0;
934 extra < sizeof(cutoff) / sizeof(cutoff[0]);
935 ++extra) {
936 if (n < cutoff[extra])
937 break;
938 /* note that if we fall out of the loop, the value of
939 extra still makes *sense*, but may be smaller than
940 we would like (but the array has more than ~= 2**31
941 elements in this case!) */
942 }
943 /* Now k == extra - 1 + CUTOFFBASE. The smallest value k can
944 have is CUTOFFBASE-1, so
945 assert MINSIZE >= 2**(CUTOFFBASE-1) - 1 */
946 extra = (1 << (extra - 1 + CUTOFFBASE)) - 1;
947 /* assert extra > 0 and n >= extra */
948
949 /* Swap that many values to the start of the array. The
950 selection of elements is pseudo-random, but the same on
951 every run (this is intentional! timing algorithm changes is
952 a pain if timing varies across runs). */
953 {
954 unsigned int seed = n / extra; /* arbitrary */
955 unsigned int i;
956 for (i = 0; i < (unsigned)extra; ++i) {
957 /* j := random int in [i, n) */
958 unsigned int j;
959 seed = seed * 69069 + 7;
960 j = i + seed % (n - i);
961 tmp = lo[i]; lo[i] = lo[j]; lo[j] = tmp;
962 }
963 }
964
965 /* Recursively sort the preselected pivots. */
Guido van Rossum42812581998-06-17 14:15:44 +0000966 if (samplesortslice(lo, lo + extra, compare) < 0)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000967 goto fail;
968
969 top = 0; /* index of available stack slot */
970 lo += extra; /* point to first unknown */
971 extraOnRight = 0; /* the PPs are at the left end */
972
973 /* ----------------------------------------------------------
974 * Partition [lo, hi), and repeat until out of work.
975 * --------------------------------------------------------*/
976 for (;;) {
977 /* assert lo <= hi, so n >= 0 */
978 n = hi - lo;
979
980 /* We may not want, or may not be able, to partition:
981 If n is small, it's quicker to insert.
982 If extra is 0, we're out of pivots, and *must* use
983 another method.
984 */
985 if (n < MINPARTITIONSIZE || extra == 0) {
986 if (n >= MINSIZE) {
987 /* assert extra == 0
988 This is rare, since the average size
989 of a final block is only about
990 ln(original n). */
Guido van Rossum42812581998-06-17 14:15:44 +0000991 if (samplesortslice(lo, hi, compare) < 0)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000992 goto fail;
993 }
994 else {
995 /* Binary insertion should be quicker,
996 and we can take advantage of the PPs
997 already being sorted. */
998 if (extraOnRight && extra) {
999 /* swap the PPs to the left end */
1000 k = extra;
1001 do {
1002 tmp = *lo;
1003 *lo = *hi;
1004 *hi = tmp;
1005 ++lo; ++hi;
1006 } while (--k);
1007 }
1008 if (binarysort(lo - extra, hi, lo,
Guido van Rossum42812581998-06-17 14:15:44 +00001009 compare) < 0)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001010 goto fail;
1011 }
1012
1013 /* Find another slice to work on. */
1014 if (--top < 0)
1015 break; /* no more -- done! */
1016 lo = stack[top].lo;
1017 hi = stack[top].hi;
1018 extra = stack[top].extra;
1019 extraOnRight = 0;
1020 if (extra < 0) {
1021 extraOnRight = 1;
1022 extra = -extra;
1023 }
1024 continue;
1025 }
1026
1027 /* Pretend the PPs are indexed 0, 1, ..., extra-1.
1028 Then our preselected pivot is at (extra-1)/2, and we
1029 want to move the PPs before that to the left end of
1030 the slice, and the PPs after that to the right end.
1031 The following section changes extra, lo, hi, and the
1032 slice such that:
1033 [lo-extra, lo) contains the smaller PPs.
1034 *lo == our PP.
1035 (lo, hi) contains the unknown elements.
1036 [hi, hi+extra) contains the larger PPs.
1037 */
1038 k = extra >>= 1; /* num PPs to move */
1039 if (extraOnRight) {
1040 /* Swap the smaller PPs to the left end.
1041 Note that this loop actually moves k+1 items:
1042 the last is our PP */
1043 do {
1044 tmp = *lo; *lo = *hi; *hi = tmp;
1045 ++lo; ++hi;
1046 } while (k--);
1047 }
1048 else {
1049 /* Swap the larger PPs to the right end. */
1050 while (k--) {
1051 --lo; --hi;
1052 tmp = *lo; *lo = *hi; *hi = tmp;
1053 }
1054 }
1055 --lo; /* *lo is now our PP */
1056 pivot = *lo;
1057
1058 /* Now an almost-ordinary quicksort partition step.
1059 Note that most of the time is spent here!
1060 Only odd thing is that we partition into < and >=,
1061 instead of the usual <= and >=. This helps when
1062 there are lots of duplicates of different values,
1063 because it eventually tends to make subfiles
1064 "pure" (all duplicates), and we special-case for
1065 duplicates later. */
1066 l = lo + 1;
1067 r = hi - 1;
1068 /* assert lo < l < r < hi (small n weeded out above) */
1069
1070 do {
1071 /* slide l right, looking for key >= pivot */
1072 do {
1073 SETK(*l, pivot);
1074 if (k < 0)
1075 ++l;
1076 else
1077 break;
1078 } while (l < r);
1079
1080 /* slide r left, looking for key < pivot */
1081 while (l < r) {
Guido van Rossum42812581998-06-17 14:15:44 +00001082 register PyObject *rval = *r--;
1083 SETK(rval, pivot);
1084 if (k < 0) {
1085 /* swap and advance */
1086 r[1] = *l;
1087 *l++ = rval;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001088 break;
Guido van Rossum42812581998-06-17 14:15:44 +00001089 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001090 }
1091
1092 } while (l < r);
1093
1094 /* assert lo < r <= l < hi
1095 assert r == l or r+1 == l
1096 everything to the left of l is < pivot, and
1097 everything to the right of r is >= pivot */
1098
1099 if (l == r) {
1100 SETK(*r, pivot);
1101 if (k < 0)
1102 ++l;
1103 else
1104 --r;
1105 }
1106 /* assert lo <= r and r+1 == l and l <= hi
1107 assert r == lo or a[r] < pivot
1108 assert a[lo] is pivot
1109 assert l == hi or a[l] >= pivot
1110 Swap the pivot into "the middle", so we can henceforth
1111 ignore it.
1112 */
1113 *lo = *r;
1114 *r = pivot;
1115
1116 /* The following is true now, & will be preserved:
1117 All in [lo,r) are < pivot
1118 All in [r,l) == pivot (& so can be ignored)
1119 All in [l,hi) are >= pivot */
1120
1121 /* Check for duplicates of the pivot. One compare is
1122 wasted if there are no duplicates, but can win big
1123 when there are.
1124 Tricky: we're sticking to "<" compares, so deduce
1125 equality indirectly. We know pivot <= *l, so they're
1126 equal iff not pivot < *l.
1127 */
1128 while (l < hi) {
1129 /* pivot <= *l known */
1130 SETK(pivot, *l);
1131 if (k < 0)
1132 break;
1133 else
1134 /* <= and not < implies == */
1135 ++l;
1136 }
1137
1138 /* assert lo <= r < l <= hi
1139 Partitions are [lo, r) and [l, hi) */
1140
1141 /* push fattest first; remember we still have extra PPs
1142 to the left of the left chunk and to the right of
1143 the right chunk! */
1144 /* assert top < STACKSIZE */
1145 if (r - lo <= hi - l) {
1146 /* second is bigger */
1147 stack[top].lo = l;
1148 stack[top].hi = hi;
1149 stack[top].extra = -extra;
1150 hi = r;
1151 extraOnRight = 0;
1152 }
1153 else {
1154 /* first is bigger */
1155 stack[top].lo = lo;
1156 stack[top].hi = r;
1157 stack[top].extra = extra;
1158 lo = l;
1159 extraOnRight = 1;
1160 }
1161 ++top;
1162
1163 } /* end of partitioning loop */
1164
1165 return 0;
1166
1167 fail:
1168 return -1;
1169}
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001170
1171#undef SETK
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001172
1173staticforward PyTypeObject immutable_list_type;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001174
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001175static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00001176listsort(PyListObject *self, PyObject *args)
Guido van Rossum3f236de1996-12-10 23:55:39 +00001177{
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001178 int err;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001179 PyObject *compare = NULL;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001180
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001181 if (args != NULL) {
Guido van Rossumc00a9382000-02-24 21:48:29 +00001182 if (!PyArg_ParseTuple(args, "|O:sort", &compare))
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001183 return NULL;
1184 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001185 self->ob_type = &immutable_list_type;
1186 err = samplesortslice(self->ob_item,
1187 self->ob_item + self->ob_size,
Guido van Rossum42812581998-06-17 14:15:44 +00001188 compare);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001189 self->ob_type = &PyList_Type;
1190 if (err < 0)
Guido van Rossum3f236de1996-12-10 23:55:39 +00001191 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001192 Py_INCREF(Py_None);
1193 return Py_None;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001194}
1195
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001196int
Fred Drakea2f55112000-07-09 15:16:51 +00001197PyList_Sort(PyObject *v)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001198{
1199 if (v == NULL || !PyList_Check(v)) {
1200 PyErr_BadInternalCall();
1201 return -1;
1202 }
1203 v = listsort((PyListObject *)v, (PyObject *)NULL);
1204 if (v == NULL)
1205 return -1;
1206 Py_DECREF(v);
1207 return 0;
1208}
1209
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001210static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00001211listreverse(PyListObject *self, PyObject *args)
Guido van Rossumed98d481991-03-06 13:07:53 +00001212{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001213 register PyObject **p, **q;
1214 register PyObject *tmp;
Guido van Rossumed98d481991-03-06 13:07:53 +00001215
Guido van Rossumc00a9382000-02-24 21:48:29 +00001216 if (!PyArg_ParseTuple(args, ":reverse"))
Guido van Rossumed98d481991-03-06 13:07:53 +00001217 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00001218
1219 if (self->ob_size > 1) {
1220 for (p = self->ob_item, q = self->ob_item + self->ob_size - 1;
1221 p < q; p++, q--) {
1222 tmp = *p;
1223 *p = *q;
1224 *q = tmp;
1225 }
1226 }
1227
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001228 Py_INCREF(Py_None);
1229 return Py_None;
Guido van Rossumed98d481991-03-06 13:07:53 +00001230}
1231
Guido van Rossum84c76f51990-10-30 13:32:20 +00001232int
Fred Drakea2f55112000-07-09 15:16:51 +00001233PyList_Reverse(PyObject *v)
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00001234{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001235 if (v == NULL || !PyList_Check(v)) {
1236 PyErr_BadInternalCall();
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00001237 return -1;
1238 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001239 v = listreverse((PyListObject *)v, (PyObject *)NULL);
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00001240 if (v == NULL)
1241 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001242 Py_DECREF(v);
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00001243 return 0;
1244}
1245
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001246PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00001247PyList_AsTuple(PyObject *v)
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00001248{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001249 PyObject *w;
1250 PyObject **p;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00001251 int n;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001252 if (v == NULL || !PyList_Check(v)) {
1253 PyErr_BadInternalCall();
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00001254 return NULL;
1255 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001256 n = ((PyListObject *)v)->ob_size;
1257 w = PyTuple_New(n);
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00001258 if (w == NULL)
1259 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001260 p = ((PyTupleObject *)w)->ob_item;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00001261 memcpy((ANY *)p,
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001262 (ANY *)((PyListObject *)v)->ob_item,
1263 n*sizeof(PyObject *));
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00001264 while (--n >= 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001265 Py_INCREF(*p);
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00001266 p++;
1267 }
1268 return w;
1269}
1270
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001271static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00001272listindex(PyListObject *self, PyObject *args)
Guido van Rossumed98d481991-03-06 13:07:53 +00001273{
1274 int i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001275 PyObject *v;
1276
Guido van Rossumef93b872000-03-13 15:41:59 +00001277 if (!PyArg_ParseTuple_Compat1(args, "O:index", &v))
Guido van Rossumed98d481991-03-06 13:07:53 +00001278 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00001279 for (i = 0; i < self->ob_size; i++) {
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001280 if (PyObject_Compare(self->ob_item[i], v) == 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001281 return PyInt_FromLong((long)i);
Guido van Rossumc8b6df91997-05-23 00:06:51 +00001282 if (PyErr_Occurred())
1283 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00001284 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001285 PyErr_SetString(PyExc_ValueError, "list.index(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00001286 return NULL;
1287}
1288
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001289static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00001290listcount(PyListObject *self, PyObject *args)
Guido van Rossume6f7d181991-10-20 20:20:40 +00001291{
1292 int count = 0;
1293 int i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001294 PyObject *v;
1295
Guido van Rossumef93b872000-03-13 15:41:59 +00001296 if (!PyArg_ParseTuple_Compat1(args, "O:count", &v))
Guido van Rossume6f7d181991-10-20 20:20:40 +00001297 return NULL;
Guido van Rossume6f7d181991-10-20 20:20:40 +00001298 for (i = 0; i < self->ob_size; i++) {
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001299 if (PyObject_Compare(self->ob_item[i], v) == 0)
Guido van Rossume6f7d181991-10-20 20:20:40 +00001300 count++;
Guido van Rossumc8b6df91997-05-23 00:06:51 +00001301 if (PyErr_Occurred())
1302 return NULL;
Guido van Rossume6f7d181991-10-20 20:20:40 +00001303 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001304 return PyInt_FromLong((long)count);
Guido van Rossume6f7d181991-10-20 20:20:40 +00001305}
1306
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001307static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00001308listremove(PyListObject *self, PyObject *args)
Guido van Rossumed98d481991-03-06 13:07:53 +00001309{
1310 int i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001311 PyObject *v;
1312
Guido van Rossumef93b872000-03-13 15:41:59 +00001313 if (!PyArg_ParseTuple_Compat1(args, "O:remove", &v))
Guido van Rossumed98d481991-03-06 13:07:53 +00001314 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00001315 for (i = 0; i < self->ob_size; i++) {
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001316 if (PyObject_Compare(self->ob_item[i], v) == 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001317 if (list_ass_slice(self, i, i+1,
1318 (PyObject *)NULL) != 0)
Guido van Rossumed98d481991-03-06 13:07:53 +00001319 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001320 Py_INCREF(Py_None);
1321 return Py_None;
Guido van Rossumed98d481991-03-06 13:07:53 +00001322 }
Guido van Rossumc8b6df91997-05-23 00:06:51 +00001323 if (PyErr_Occurred())
1324 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00001325 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001326 PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00001327 return NULL;
1328}
1329
Jeremy Hylton8caad492000-06-23 14:18:11 +00001330static int
1331list_traverse(PyListObject *o, visitproc visit, void *arg)
1332{
1333 int i, err;
1334 PyObject *x;
1335
1336 for (i = o->ob_size; --i >= 0; ) {
1337 x = o->ob_item[i];
1338 if (x != NULL) {
1339 err = visit(x, arg);
1340 if (err)
1341 return err;
1342 }
1343 }
1344 return 0;
1345}
1346
1347static int
1348list_clear(PyListObject *lp)
1349{
1350 (void) PyList_SetSlice((PyObject *)lp, 0, lp->ob_size, 0);
1351 return 0;
1352}
1353
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +00001354static char append_doc[] =
1355"L.append(object) -- append object to end";
Barry Warsawdedf6d61998-10-09 16:37:25 +00001356static char extend_doc[] =
1357"L.extend(list) -- extend list by appending list elements";
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +00001358static char insert_doc[] =
1359"L.insert(index, object) -- insert object before index";
1360static char pop_doc[] =
1361"L.pop([index]) -> item -- remove and return item at index (default last)";
1362static char remove_doc[] =
1363"L.remove(value) -- remove first occurrence of value";
1364static char index_doc[] =
1365"L.index(value) -> integer -- return index of first occurrence of value";
1366static char count_doc[] =
1367"L.count(value) -> integer -- return number of occurrences of value";
1368static char reverse_doc[] =
1369"L.reverse() -- reverse *IN PLACE*";
1370static char sort_doc[] =
1371"L.sort([cmpfunc]) -- sort *IN PLACE*; if given, cmpfunc(x, y) -> -1, 0, 1";
1372
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001373static PyMethodDef list_methods[] = {
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001374 {"append", (PyCFunction)listappend, 1, append_doc},
1375 {"insert", (PyCFunction)listinsert, 1, insert_doc},
Barry Warsawdedf6d61998-10-09 16:37:25 +00001376 {"extend", (PyCFunction)listextend, 1, extend_doc},
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +00001377 {"pop", (PyCFunction)listpop, 1, pop_doc},
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001378 {"remove", (PyCFunction)listremove, 1, remove_doc},
1379 {"index", (PyCFunction)listindex, 1, index_doc},
1380 {"count", (PyCFunction)listcount, 1, count_doc},
1381 {"reverse", (PyCFunction)listreverse, 1, reverse_doc},
1382 {"sort", (PyCFunction)listsort, 1, sort_doc},
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001383 {NULL, NULL} /* sentinel */
1384};
1385
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001386static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00001387list_getattr(PyListObject *f, char *name)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001388{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001389 return Py_FindMethod(list_methods, (PyObject *)f, name);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001390}
1391
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001392static PySequenceMethods list_as_sequence = {
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00001393 (inquiry)list_length, /*sq_length*/
1394 (binaryfunc)list_concat, /*sq_concat*/
1395 (intargfunc)list_repeat, /*sq_repeat*/
1396 (intargfunc)list_item, /*sq_item*/
1397 (intintargfunc)list_slice, /*sq_slice*/
1398 (intobjargproc)list_ass_item, /*sq_ass_item*/
1399 (intintobjargproc)list_ass_slice, /*sq_ass_slice*/
Jeremy Hylton37b1a262000-04-27 21:41:03 +00001400 (objobjproc)list_contains, /*sq_contains*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001401};
1402
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001403PyTypeObject PyList_Type = {
1404 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001405 0,
1406 "list",
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001407 sizeof(PyListObject) + PyGC_HEAD_SIZE,
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001408 0,
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00001409 (destructor)list_dealloc, /*tp_dealloc*/
1410 (printfunc)list_print, /*tp_print*/
1411 (getattrfunc)list_getattr, /*tp_getattr*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001412 0, /*tp_setattr*/
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00001413 (cmpfunc)list_compare, /*tp_compare*/
1414 (reprfunc)list_repr, /*tp_repr*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001415 0, /*tp_as_number*/
1416 &list_as_sequence, /*tp_as_sequence*/
1417 0, /*tp_as_mapping*/
Fred Drake56780252000-06-15 14:50:20 +00001418 0, /*tp_hash*/
1419 0, /*tp_call*/
1420 0, /*tp_str*/
1421 0, /*tp_getattro*/
1422 0, /*tp_setattro*/
1423 0, /*tp_as_buffer*/
Jeremy Hyltond08b4c42000-06-23 19:37:02 +00001424 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_GC, /*tp_flags*/
Jeremy Hylton8caad492000-06-23 14:18:11 +00001425 0, /* tp_doc */
1426 (traverseproc)list_traverse, /* tp_traverse */
1427 (inquiry)list_clear, /* tp_clear */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001428};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001429
1430
1431/* During a sort, we really can't have anyone modifying the list; it could
1432 cause core dumps. Thus, we substitute a dummy type that raises an
1433 explanatory exception when a modifying operation is used. Caveat:
1434 comparisons may behave differently; but I guess it's a bad idea anyway to
1435 compare a list that's being sorted... */
1436
1437static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00001438immutable_list_op(void)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001439{
1440 PyErr_SetString(PyExc_TypeError,
1441 "a list cannot be modified while it is being sorted");
1442 return NULL;
1443}
1444
1445static PyMethodDef immutable_list_methods[] = {
1446 {"append", (PyCFunction)immutable_list_op},
1447 {"insert", (PyCFunction)immutable_list_op},
1448 {"remove", (PyCFunction)immutable_list_op},
1449 {"index", (PyCFunction)listindex},
1450 {"count", (PyCFunction)listcount},
1451 {"reverse", (PyCFunction)immutable_list_op},
1452 {"sort", (PyCFunction)immutable_list_op},
1453 {NULL, NULL} /* sentinel */
1454};
1455
1456static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00001457immutable_list_getattr(PyListObject *f, char *name)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001458{
1459 return Py_FindMethod(immutable_list_methods, (PyObject *)f, name);
1460}
1461
1462static int
Fred Drakea2f55112000-07-09 15:16:51 +00001463immutable_list_ass(void)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001464{
1465 immutable_list_op();
1466 return -1;
1467}
1468
1469static PySequenceMethods immutable_list_as_sequence = {
1470 (inquiry)list_length, /*sq_length*/
1471 (binaryfunc)list_concat, /*sq_concat*/
1472 (intargfunc)list_repeat, /*sq_repeat*/
1473 (intargfunc)list_item, /*sq_item*/
1474 (intintargfunc)list_slice, /*sq_slice*/
1475 (intobjargproc)immutable_list_ass, /*sq_ass_item*/
1476 (intintobjargproc)immutable_list_ass, /*sq_ass_slice*/
Fred Drake56780252000-06-15 14:50:20 +00001477 (objobjproc)list_contains, /*sq_contains*/
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001478};
1479
1480static PyTypeObject immutable_list_type = {
1481 PyObject_HEAD_INIT(&PyType_Type)
1482 0,
1483 "list (immutable, during sort)",
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001484 sizeof(PyListObject) + PyGC_HEAD_SIZE,
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001485 0,
1486 0, /*tp_dealloc*/ /* Cannot happen */
1487 (printfunc)list_print, /*tp_print*/
1488 (getattrfunc)immutable_list_getattr, /*tp_getattr*/
1489 0, /*tp_setattr*/
1490 0, /*tp_compare*/ /* Won't be called */
1491 (reprfunc)list_repr, /*tp_repr*/
1492 0, /*tp_as_number*/
1493 &immutable_list_as_sequence, /*tp_as_sequence*/
1494 0, /*tp_as_mapping*/
Fred Drake56780252000-06-15 14:50:20 +00001495 0, /*tp_hash*/
1496 0, /*tp_call*/
1497 0, /*tp_str*/
1498 0, /*tp_getattro*/
1499 0, /*tp_setattro*/
1500 0, /*tp_as_buffer*/
Jeremy Hyltond08b4c42000-06-23 19:37:02 +00001501 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_GC, /*tp_flags*/
Jeremy Hylton8caad492000-06-23 14:18:11 +00001502 0, /* tp_doc */
1503 (traverseproc)list_traverse, /* tp_traverse */
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001504};