blob: 2b016eda199fc2629eb8afc30cabb097f7884298 [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 }
Trent Micka5846642000-08-13 22:47:45 +0000137 if (self->ob_size == INT_MAX) {
138 PyErr_SetString(PyExc_OverflowError,
139 "cannot add more objects to list");
140 return -1;
141 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000142 items = self->ob_item;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000143 NRESIZE(items, PyObject *, self->ob_size+1);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000144 if (items == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000145 PyErr_NoMemory();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000146 return -1;
147 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000148 if (where < 0)
149 where = 0;
150 if (where > self->ob_size)
151 where = self->ob_size;
152 for (i = self->ob_size; --i >= where; )
153 items[i+1] = items[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000154 Py_INCREF(v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000155 items[where] = v;
156 self->ob_item = items;
157 self->ob_size++;
158 return 0;
159}
160
161int
Fred Drakea2f55112000-07-09 15:16:51 +0000162PyList_Insert(PyObject *op, int where, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000163{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000164 if (!PyList_Check(op)) {
165 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000166 return -1;
167 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000168 return ins1((PyListObject *)op, where, newitem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000169}
170
171int
Fred Drakea2f55112000-07-09 15:16:51 +0000172PyList_Append(PyObject *op, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000173{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000174 if (!PyList_Check(op)) {
175 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000176 return -1;
177 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000178 return ins1((PyListObject *)op,
179 (int) ((PyListObject *)op)->ob_size, newitem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000180}
181
182/* Methods */
183
184static void
Fred Drakea2f55112000-07-09 15:16:51 +0000185list_dealloc(PyListObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000186{
187 int i;
Guido van Rossumd724b232000-03-13 16:01:29 +0000188 Py_TRASHCAN_SAFE_BEGIN(op)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000189 PyObject_GC_Fini(op);
Jack Jansen7874d1f1995-01-19 12:09:27 +0000190 if (op->ob_item != NULL) {
Guido van Rossumfa717011999-06-09 15:19:34 +0000191 /* Do it backwards, for Christian Tismer.
192 There's a simple test case where somehow this reduces
193 thrashing when a *very* large list is created and
194 immediately deleted. */
195 i = op->ob_size;
196 while (--i >= 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000197 Py_XDECREF(op->ob_item[i]);
Jack Jansen7874d1f1995-01-19 12:09:27 +0000198 }
Guido van Rossumb18618d2000-05-03 23:44:39 +0000199 PyMem_FREE(op->ob_item);
Jack Jansen7874d1f1995-01-19 12:09:27 +0000200 }
Guido van Rossum4cc6ac72000-07-01 01:00:38 +0000201 op = (PyListObject *) PyObject_AS_GC(op);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000202 PyObject_DEL(op);
Guido van Rossumd724b232000-03-13 16:01:29 +0000203 Py_TRASHCAN_SAFE_END(op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000204}
205
Guido van Rossum90933611991-06-07 16:10:43 +0000206static int
Fred Drakea2f55112000-07-09 15:16:51 +0000207list_print(PyListObject *op, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000208{
209 int i;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000210
211 i = Py_ReprEnter((PyObject*)op);
212 if (i != 0) {
213 if (i < 0)
214 return i;
215 fprintf(fp, "[...]");
216 return 0;
217 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000218 fprintf(fp, "[");
Guido van Rossum90933611991-06-07 16:10:43 +0000219 for (i = 0; i < op->ob_size; i++) {
220 if (i > 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000221 fprintf(fp, ", ");
Guido van Rossumfb376de1998-04-10 22:47:27 +0000222 if (PyObject_Print(op->ob_item[i], fp, 0) != 0) {
223 Py_ReprLeave((PyObject *)op);
Guido van Rossum90933611991-06-07 16:10:43 +0000224 return -1;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000225 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000226 }
227 fprintf(fp, "]");
Guido van Rossumfb376de1998-04-10 22:47:27 +0000228 Py_ReprLeave((PyObject *)op);
Guido van Rossum90933611991-06-07 16:10:43 +0000229 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000230}
231
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000232static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000233list_repr(PyListObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000234{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000235 PyObject *s, *comma;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000236 int i;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000237
238 i = Py_ReprEnter((PyObject*)v);
239 if (i != 0) {
240 if (i > 0)
241 return PyString_FromString("[...]");
242 return NULL;
243 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000244 s = PyString_FromString("[");
245 comma = PyString_FromString(", ");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000246 for (i = 0; i < v->ob_size && s != NULL; i++) {
247 if (i > 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000248 PyString_Concat(&s, comma);
249 PyString_ConcatAndDel(&s, PyObject_Repr(v->ob_item[i]));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000250 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000251 Py_XDECREF(comma);
252 PyString_ConcatAndDel(&s, PyString_FromString("]"));
Guido van Rossumfb376de1998-04-10 22:47:27 +0000253 Py_ReprLeave((PyObject *)v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000254 return s;
255}
256
257static int
Fred Drakea2f55112000-07-09 15:16:51 +0000258list_compare(PyListObject *v, PyListObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000259{
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000260 int i;
Guido van Rossumae621ff1998-05-28 20:18:46 +0000261 for (i = 0; i < v->ob_size && i < w->ob_size; i++) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000262 int cmp = PyObject_Compare(v->ob_item[i], w->ob_item[i]);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000263 if (cmp != 0)
264 return cmp;
265 }
266 return v->ob_size - w->ob_size;
267}
268
269static int
Fred Drakea2f55112000-07-09 15:16:51 +0000270list_length(PyListObject *a)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000271{
272 return a->ob_size;
273}
274
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000275
276
277static int
Fred Drakea2f55112000-07-09 15:16:51 +0000278list_contains(PyListObject *a, PyObject *el)
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000279{
280 int i, cmp;
281
282 for (i = 0; i < a->ob_size; ++i) {
283 cmp = PyObject_Compare(el, PyList_GET_ITEM(a, i));
284 if (cmp == 0)
285 return 1;
286 if (PyErr_Occurred())
287 return -1;
288 }
289 return 0;
290}
291
292
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000293static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000294list_item(PyListObject *a, int i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000295{
296 if (i < 0 || i >= a->ob_size) {
Guido van Rossum929f1b81996-08-09 20:51:27 +0000297 if (indexerr == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000298 indexerr = PyString_FromString(
299 "list index out of range");
300 PyErr_SetObject(PyExc_IndexError, indexerr);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000301 return NULL;
302 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000303 Py_INCREF(a->ob_item[i]);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000304 return a->ob_item[i];
305}
306
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000307static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000308list_slice(PyListObject *a, int ilow, int ihigh)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000309{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000310 PyListObject *np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000311 int i;
312 if (ilow < 0)
313 ilow = 0;
314 else if (ilow > a->ob_size)
315 ilow = a->ob_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000316 if (ihigh < ilow)
317 ihigh = ilow;
318 else if (ihigh > a->ob_size)
319 ihigh = a->ob_size;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000320 np = (PyListObject *) PyList_New(ihigh - ilow);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000321 if (np == NULL)
322 return NULL;
323 for (i = ilow; i < ihigh; i++) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000324 PyObject *v = a->ob_item[i];
325 Py_INCREF(v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000326 np->ob_item[i - ilow] = v;
327 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000328 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000329}
330
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000331PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000332PyList_GetSlice(PyObject *a, int ilow, int ihigh)
Guido van Rossum234f9421993-06-17 12:35:49 +0000333{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000334 if (!PyList_Check(a)) {
335 PyErr_BadInternalCall();
Guido van Rossum234f9421993-06-17 12:35:49 +0000336 return NULL;
337 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000338 return list_slice((PyListObject *)a, ilow, ihigh);
Guido van Rossum234f9421993-06-17 12:35:49 +0000339}
340
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000341static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000342list_concat(PyListObject *a, PyObject *bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000343{
344 int size;
345 int i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000346 PyListObject *np;
347 if (!PyList_Check(bb)) {
Fred Drakeb6a9ada2000-06-01 03:12:13 +0000348 PyErr_Format(PyExc_TypeError,
Fred Drake914a2ed2000-06-01 14:31:03 +0000349 "can only concatenate list (not \"%.200s\") to list",
350 bb->ob_type->tp_name);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000351 return NULL;
352 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000353#define b ((PyListObject *)bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000354 size = a->ob_size + b->ob_size;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000355 np = (PyListObject *) PyList_New(size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000356 if (np == NULL) {
Guido van Rossum90933611991-06-07 16:10:43 +0000357 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000358 }
359 for (i = 0; i < a->ob_size; i++) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000360 PyObject *v = a->ob_item[i];
361 Py_INCREF(v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000362 np->ob_item[i] = v;
363 }
364 for (i = 0; i < b->ob_size; i++) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000365 PyObject *v = b->ob_item[i];
366 Py_INCREF(v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000367 np->ob_item[i + a->ob_size] = v;
368 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000369 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000370#undef b
371}
372
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000373static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000374list_repeat(PyListObject *a, int n)
Guido van Rossumed98d481991-03-06 13:07:53 +0000375{
376 int i, j;
377 int size;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000378 PyListObject *np;
379 PyObject **p;
Guido van Rossumed98d481991-03-06 13:07:53 +0000380 if (n < 0)
381 n = 0;
382 size = a->ob_size * n;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000383 np = (PyListObject *) PyList_New(size);
Guido van Rossumed98d481991-03-06 13:07:53 +0000384 if (np == NULL)
385 return NULL;
386 p = np->ob_item;
387 for (i = 0; i < n; i++) {
388 for (j = 0; j < a->ob_size; j++) {
389 *p = a->ob_item[j];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000390 Py_INCREF(*p);
Guido van Rossumed98d481991-03-06 13:07:53 +0000391 p++;
392 }
393 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000394 return (PyObject *) np;
Guido van Rossumed98d481991-03-06 13:07:53 +0000395}
396
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000397static int
Fred Drakea2f55112000-07-09 15:16:51 +0000398list_ass_slice(PyListObject *a, int ilow, int ihigh, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000399{
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000400 /* Because [X]DECREF can recursively invoke list operations on
401 this list, we must postpone all [X]DECREF activity until
402 after the list is back in its canonical shape. Therefore
403 we must allocate an additional array, 'recycle', into which
404 we temporarily copy the items that are deleted from the
405 list. :-( */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000406 PyObject **recycle, **p;
407 PyObject **item;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000408 int n; /* Size of replacement list */
409 int d; /* Change in size */
410 int k; /* Loop index */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000411#define b ((PyListObject *)v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000412 if (v == NULL)
413 n = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000414 else if (PyList_Check(v)) {
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000415 n = b->ob_size;
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000416 if (a == b) {
417 /* Special case "a[i:j] = a" -- copy b first */
418 int ret;
419 v = list_slice(b, 0, n);
420 ret = list_ass_slice(a, ilow, ihigh, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000421 Py_DECREF(v);
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000422 return ret;
423 }
424 }
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000425 else {
Fred Drakeb6a9ada2000-06-01 03:12:13 +0000426 PyErr_Format(PyExc_TypeError,
427 "must assign list (not \"%.200s\") to slice",
428 v->ob_type->tp_name);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000429 return -1;
430 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000431 if (ilow < 0)
432 ilow = 0;
433 else if (ilow > a->ob_size)
434 ilow = a->ob_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000435 if (ihigh < ilow)
436 ihigh = ilow;
437 else if (ihigh > a->ob_size)
438 ihigh = a->ob_size;
439 item = a->ob_item;
440 d = n - (ihigh-ilow);
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000441 if (ihigh > ilow)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000442 p = recycle = PyMem_NEW(PyObject *, (ihigh-ilow));
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000443 else
444 p = recycle = NULL;
445 if (d <= 0) { /* Delete -d items; recycle ihigh-ilow items */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000446 for (k = ilow; k < ihigh; k++)
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000447 *p++ = item[k];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000448 if (d < 0) {
449 for (/*k = ihigh*/; k < a->ob_size; k++)
450 item[k+d] = item[k];
451 a->ob_size += d;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000452 NRESIZE(item, PyObject *, a->ob_size); /* Can't fail */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000453 a->ob_item = item;
454 }
455 }
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000456 else { /* Insert d items; recycle ihigh-ilow items */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000457 NRESIZE(item, PyObject *, a->ob_size + d);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000458 if (item == NULL) {
Guido van Rossumb18618d2000-05-03 23:44:39 +0000459 if (recycle != NULL)
460 PyMem_DEL(recycle);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000461 PyErr_NoMemory();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000462 return -1;
463 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000464 for (k = a->ob_size; --k >= ihigh; )
465 item[k+d] = item[k];
466 for (/*k = ihigh-1*/; k >= ilow; --k)
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000467 *p++ = item[k];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000468 a->ob_item = item;
469 a->ob_size += d;
470 }
471 for (k = 0; k < n; k++, ilow++) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000472 PyObject *w = b->ob_item[k];
473 Py_XINCREF(w);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000474 item[ilow] = w;
475 }
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000476 if (recycle) {
477 while (--p >= recycle)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000478 Py_XDECREF(*p);
479 PyMem_DEL(recycle);
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000480 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000481 return 0;
482#undef b
483}
484
Guido van Rossum234f9421993-06-17 12:35:49 +0000485int
Fred Drakea2f55112000-07-09 15:16:51 +0000486PyList_SetSlice(PyObject *a, int ilow, int ihigh, PyObject *v)
Guido van Rossum234f9421993-06-17 12:35:49 +0000487{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000488 if (!PyList_Check(a)) {
489 PyErr_BadInternalCall();
Guido van Rossum1fc238a1993-07-29 08:25:09 +0000490 return -1;
Guido van Rossum234f9421993-06-17 12:35:49 +0000491 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000492 return list_ass_slice((PyListObject *)a, ilow, ihigh, v);
Guido van Rossum234f9421993-06-17 12:35:49 +0000493}
494
Guido van Rossum4a450d01991-04-03 19:05:18 +0000495static int
Fred Drakea2f55112000-07-09 15:16:51 +0000496list_ass_item(PyListObject *a, int i, PyObject *v)
Guido van Rossum4a450d01991-04-03 19:05:18 +0000497{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000498 PyObject *old_value;
Guido van Rossum4a450d01991-04-03 19:05:18 +0000499 if (i < 0 || i >= a->ob_size) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000500 PyErr_SetString(PyExc_IndexError,
501 "list assignment index out of range");
Guido van Rossum4a450d01991-04-03 19:05:18 +0000502 return -1;
503 }
504 if (v == NULL)
505 return list_ass_slice(a, i, i+1, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000506 Py_INCREF(v);
Guido van Rossumd7047b31995-01-02 19:07:15 +0000507 old_value = a->ob_item[i];
Guido van Rossum4a450d01991-04-03 19:05:18 +0000508 a->ob_item[i] = v;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000509 Py_DECREF(old_value);
Guido van Rossum4a450d01991-04-03 19:05:18 +0000510 return 0;
511}
512
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000513static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000514ins(PyListObject *self, int where, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000515{
516 if (ins1(self, where, v) != 0)
517 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000518 Py_INCREF(Py_None);
519 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000520}
521
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000522static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000523listinsert(PyListObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000524{
525 int i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000526 PyObject *v;
Guido van Rossumc00a9382000-02-24 21:48:29 +0000527 if (!PyArg_ParseTuple(args, "iO:insert", &i, &v))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000528 return NULL;
Guido van Rossumbf80e541993-02-08 15:49:17 +0000529 return ins(self, i, v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000530}
531
Guido van Rossumef93b872000-03-13 15:41:59 +0000532/* Define NO_STRICT_LIST_APPEND to enable multi-argument append() */
533
534#ifndef NO_STRICT_LIST_APPEND
535#define PyArg_ParseTuple_Compat1 PyArg_ParseTuple
536#else
537#define PyArg_ParseTuple_Compat1(args, format, ret) \
538( \
539 PyTuple_GET_SIZE(args) > 1 ? (*ret = args, 1) : \
540 PyTuple_GET_SIZE(args) == 1 ? (*ret = PyTuple_GET_ITEM(args, 0), 1) : \
541 PyArg_ParseTuple(args, format, ret) \
542)
543#endif
544
545
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000546static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000547listappend(PyListObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000548{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000549 PyObject *v;
Guido van Rossumef93b872000-03-13 15:41:59 +0000550 if (!PyArg_ParseTuple_Compat1(args, "O:append", &v))
Guido van Rossumbf80e541993-02-08 15:49:17 +0000551 return NULL;
552 return ins(self, (int) self->ob_size, v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000553}
554
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000555static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000556listextend(PyListObject *self, PyObject *args)
Barry Warsawdedf6d61998-10-09 16:37:25 +0000557{
558 PyObject *b = NULL, *res = NULL;
559 PyObject **items;
560 int selflen = PyList_GET_SIZE(self);
561 int blen;
562 register int i;
563
Guido van Rossumc00a9382000-02-24 21:48:29 +0000564 if (!PyArg_ParseTuple(args, "O:extend", &b))
Barry Warsawdedf6d61998-10-09 16:37:25 +0000565 return NULL;
566
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000567 b = PySequence_Fast(b, "list.extend() argument must be a sequence");
568 if (!b)
Barry Warsawdedf6d61998-10-09 16:37:25 +0000569 return NULL;
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000570
Jeremy Hylton03657cf2000-07-12 13:05:33 +0000571 if (PyObject_Size(b) == 0)
Barry Warsawdedf6d61998-10-09 16:37:25 +0000572 /* short circuit when b is empty */
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000573 goto ok;
574
Barry Warsawdedf6d61998-10-09 16:37:25 +0000575 if (self == (PyListObject*)b) {
576 /* as in list_ass_slice() we must special case the
577 * situation: a.extend(a)
578 *
579 * XXX: I think this way ought to be faster than using
580 * list_slice() the way list_ass_slice() does.
581 */
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000582 Py_DECREF(b);
Barry Warsawdedf6d61998-10-09 16:37:25 +0000583 b = PyList_New(selflen);
584 if (!b)
585 return NULL;
586 for (i = 0; i < selflen; i++) {
587 PyObject *o = PyList_GET_ITEM(self, i);
588 Py_INCREF(o);
589 PyList_SET_ITEM(b, i, o);
590 }
591 }
Barry Warsawdedf6d61998-10-09 16:37:25 +0000592
Jeremy Hylton03657cf2000-07-12 13:05:33 +0000593 blen = PyObject_Size(b);
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000594
Barry Warsawdedf6d61998-10-09 16:37:25 +0000595 /* resize a using idiom */
596 items = self->ob_item;
597 NRESIZE(items, PyObject*, selflen + blen);
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000598 if (items == NULL) {
Barry Warsawdedf6d61998-10-09 16:37:25 +0000599 PyErr_NoMemory();
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000600 goto failed;
Barry Warsawdedf6d61998-10-09 16:37:25 +0000601 }
602 self->ob_item = items;
603
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000604 /* populate the end of self with b's items */
Barry Warsawdedf6d61998-10-09 16:37:25 +0000605 for (i = 0; i < blen; i++) {
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000606 PyObject *o = PySequence_Fast_GET_ITEM(b, i);
Barry Warsawdedf6d61998-10-09 16:37:25 +0000607 Py_INCREF(o);
608 PyList_SET_ITEM(self, self->ob_size++, o);
609 }
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000610 ok:
Barry Warsawdedf6d61998-10-09 16:37:25 +0000611 res = Py_None;
612 Py_INCREF(res);
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000613 failed:
614 Py_DECREF(b);
Barry Warsawdedf6d61998-10-09 16:37:25 +0000615 return res;
616}
617
618
619static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000620listpop(PyListObject *self, PyObject *args)
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000621{
622 int i = -1;
623 PyObject *v;
Guido van Rossumc00a9382000-02-24 21:48:29 +0000624 if (!PyArg_ParseTuple(args, "|i:pop", &i))
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000625 return NULL;
626 if (self->ob_size == 0) {
627 /* Special-case most common failure cause */
628 PyErr_SetString(PyExc_IndexError, "pop from empty list");
629 return NULL;
630 }
631 if (i < 0)
632 i += self->ob_size;
633 if (i < 0 || i >= self->ob_size) {
634 PyErr_SetString(PyExc_IndexError, "pop index out of range");
635 return NULL;
636 }
637 v = self->ob_item[i];
638 Py_INCREF(v);
639 if (list_ass_slice(self, i, i+1, (PyObject *)NULL) != 0) {
640 Py_DECREF(v);
641 return NULL;
642 }
643 return v;
644}
645
Guido van Rossum3f236de1996-12-10 23:55:39 +0000646/* New quicksort implementation for arrays of object pointers.
647 Thanks to discussions with Tim Peters. */
648
649/* CMPERROR is returned by our comparison function when an error
650 occurred. This is the largest negative integer (0x80000000 on a
651 32-bit system). */
Guido van Rossum19700b61997-03-05 00:45:43 +0000652#define CMPERROR ( (int) ((unsigned int)1 << (8*sizeof(int) - 1)) )
Guido van Rossum3f236de1996-12-10 23:55:39 +0000653
654/* Comparison function. Takes care of calling a user-supplied
655 comparison function (any callable Python object). Calls the
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000656 standard comparison function, PyObject_Compare(), if the user-
657 supplied function is NULL. */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000658
659static int
Fred Drakea2f55112000-07-09 15:16:51 +0000660docompare(PyObject *x, PyObject *y, PyObject *compare)
Guido van Rossum3f236de1996-12-10 23:55:39 +0000661{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000662 PyObject *args, *res;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000663 int i;
664
Guido van Rossumc8b6df91997-05-23 00:06:51 +0000665 if (compare == NULL) {
666 i = PyObject_Compare(x, y);
667 if (i && PyErr_Occurred())
668 i = CMPERROR;
669 return i;
670 }
Guido van Rossum3f236de1996-12-10 23:55:39 +0000671
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000672 args = Py_BuildValue("(OO)", x, y);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000673 if (args == NULL)
674 return CMPERROR;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000675 res = PyEval_CallObject(compare, args);
676 Py_DECREF(args);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000677 if (res == NULL)
678 return CMPERROR;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000679 if (!PyInt_Check(res)) {
680 Py_DECREF(res);
681 PyErr_SetString(PyExc_TypeError,
Guido van Rossum9bcd1d71999-04-19 17:44:39 +0000682 "comparison function must return int");
Guido van Rossum3f236de1996-12-10 23:55:39 +0000683 return CMPERROR;
684 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000685 i = PyInt_AsLong(res);
686 Py_DECREF(res);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000687 if (i < 0)
688 return -1;
689 if (i > 0)
690 return 1;
691 return 0;
692}
693
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000694/* MINSIZE is the smallest array that will get a full-blown samplesort
695 treatment; smaller arrays are sorted using binary insertion. It must
696 be at least 7 for the samplesort implementation to work. Binary
697 insertion does fewer compares, but can suffer O(N**2) data movement.
698 The more expensive compares, the larger MINSIZE should be. */
699#define MINSIZE 100
700
701/* MINPARTITIONSIZE is the smallest array slice samplesort will bother to
702 partition; smaller slices are passed to binarysort. It must be at
703 least 2, and no larger than MINSIZE. Setting it higher reduces the #
704 of compares slowly, but increases the amount of data movement quickly.
705 The value here was chosen assuming a compare costs ~25x more than
706 swapping a pair of memory-resident pointers -- but under that assumption,
707 changing the value by a few dozen more or less has aggregate effect
708 under 1%. So the value is crucial, but not touchy <wink>. */
709#define MINPARTITIONSIZE 40
710
711/* MAXMERGE is the largest number of elements we'll always merge into
712 a known-to-be sorted chunk via binary insertion, regardless of the
713 size of that chunk. Given a chunk of N sorted elements, and a group
714 of K unknowns, the largest K for which it's better to do insertion
715 (than a full-blown sort) is a complicated function of N and K mostly
716 involving the expected number of compares and data moves under each
717 approach, and the relative cost of those operations on a specific
718 architecure. The fixed value here is conservative, and should be a
719 clear win regardless of architecture or N. */
720#define MAXMERGE 15
Guido van Rossum3f236de1996-12-10 23:55:39 +0000721
Guido van Rossum3f236de1996-12-10 23:55:39 +0000722/* STACKSIZE is the size of our work stack. A rough estimate is that
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000723 this allows us to sort arrays of size N where
724 N / ln(N) = MINPARTITIONSIZE * 2**STACKSIZE, so 60 is more than enough
725 for arrays of size 2**64. Because we push the biggest partition
726 first, the worst case occurs when all subarrays are always partitioned
727 exactly in two. */
728#define STACKSIZE 60
Guido van Rossum3f236de1996-12-10 23:55:39 +0000729
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000730
731#define SETK(X,Y) if ((k = docompare(X,Y,compare))==CMPERROR) goto fail
732
733/* binarysort is the best method for sorting small arrays: it does
734 few compares, but can do data movement quadratic in the number of
735 elements.
Guido van Rossum42812581998-06-17 14:15:44 +0000736 [lo, hi) is a contiguous slice of a list, and is sorted via
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000737 binary insertion.
738 On entry, must have lo <= start <= hi, and that [lo, start) is already
739 sorted (pass start == lo if you don't know!).
740 If docompare complains (returns CMPERROR) return -1, else 0.
741 Even in case of error, the output slice will be some permutation of
742 the input (nothing is lost or duplicated).
743*/
Guido van Rossum3f236de1996-12-10 23:55:39 +0000744
745static int
Fred Drakea2f55112000-07-09 15:16:51 +0000746binarysort(PyObject **lo, PyObject **hi, PyObject **start, PyObject *compare)
747 /* compare -- comparison function object, or NULL for default */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000748{
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000749 /* assert lo <= start <= hi
750 assert [lo, start) is sorted */
751 register int k;
752 register PyObject **l, **p, **r;
753 register PyObject *pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000754
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000755 if (lo == start)
756 ++start;
757 for (; start < hi; ++start) {
758 /* set l to where *start belongs */
759 l = lo;
760 r = start;
Guido van Rossuma119c0d1998-05-29 17:56:32 +0000761 pivot = *r;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000762 do {
763 p = l + ((r - l) >> 1);
764 SETK(pivot, *p);
765 if (k < 0)
766 r = p;
767 else
768 l = p + 1;
769 } while (l < r);
770 /* Pivot should go at l -- slide over to make room.
771 Caution: using memmove is much slower under MSVC 5;
772 we're not usually moving many slots. */
773 for (p = start; p > l; --p)
774 *p = *(p-1);
775 *l = pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000776 }
Guido van Rossum3f236de1996-12-10 23:55:39 +0000777 return 0;
Guido van Rossuma119c0d1998-05-29 17:56:32 +0000778
779 fail:
780 return -1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000781}
782
783/* samplesortslice is the sorting workhorse.
Guido van Rossum42812581998-06-17 14:15:44 +0000784 [lo, hi) is a contiguous slice of a list, to be sorted in place.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000785 On entry, must have lo <= hi,
786 If docompare complains (returns CMPERROR) return -1, else 0.
787 Even in case of error, the output slice will be some permutation of
788 the input (nothing is lost or duplicated).
789
790 samplesort is basically quicksort on steroids: a power of 2 close
791 to n/ln(n) is computed, and that many elements (less 1) are picked at
792 random from the array and sorted. These 2**k - 1 elements are then
793 used as preselected pivots for an equal number of quicksort
794 partitioning steps, partitioning the slice into 2**k chunks each of
795 size about ln(n). These small final chunks are then usually handled
796 by binarysort. Note that when k=1, this is roughly the same as an
797 ordinary quicksort using a random pivot, and when k=2 this is roughly
798 a median-of-3 quicksort. From that view, using k ~= lg(n/ln(n)) makes
799 this a "median of n/ln(n)" quicksort. You can also view it as a kind
800 of bucket sort, where 2**k-1 bucket boundaries are picked dynamically.
801
802 The large number of samples makes a quadratic-time case almost
803 impossible, and asymptotically drives the average-case number of
804 compares from quicksort's 2 N ln N (or 12/7 N ln N for the median-of-
805 3 variant) down to N lg N.
806
807 We also play lots of low-level tricks to cut the number of compares.
808
809 Very obscure: To avoid using extra memory, the PPs are stored in the
810 array and shuffled around as partitioning proceeds. At the start of a
811 partitioning step, we'll have 2**m-1 (for some m) PPs in sorted order,
812 adjacent (either on the left or the right!) to a chunk of X elements
813 that are to be partitioned: P X or X P. In either case we need to
814 shuffle things *in place* so that the 2**(m-1) smaller PPs are on the
815 left, followed by the PP to be used for this step (that's the middle
816 of the PPs), followed by X, followed by the 2**(m-1) larger PPs:
817 P X or X P -> Psmall pivot X Plarge
818 and the order of the PPs must not be altered. It can take a while
819 to realize this isn't trivial! It can take even longer <wink> to
820 understand why the simple code below works, using only 2**(m-1) swaps.
821 The key is that the order of the X elements isn't necessarily
822 preserved: X can end up as some cyclic permutation of its original
823 order. That's OK, because X is unsorted anyway. If the order of X
824 had to be preserved too, the simplest method I know of using O(1)
825 scratch storage requires len(X) + 2**(m-1) swaps, spread over 2 passes.
826 Since len(X) is typically several times larger than 2**(m-1), that
827 would slow things down.
828*/
829
830struct SamplesortStackNode {
831 /* Represents a slice of the array, from (& including) lo up
832 to (but excluding) hi. "extra" additional & adjacent elements
833 are pre-selected pivots (PPs), spanning [lo-extra, lo) if
834 extra > 0, or [hi, hi-extra) if extra < 0. The PPs are
835 already sorted, but nothing is known about the other elements
836 in [lo, hi). |extra| is always one less than a power of 2.
837 When extra is 0, we're out of PPs, and the slice must be
838 sorted by some other means. */
839 PyObject **lo;
840 PyObject **hi;
841 int extra;
842};
843
844/* 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 +0000845 N / ln(N) as possible. So k ~= lg(N / ln(N)). Calling libm routines
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000846 is undesirable, so cutoff values are canned in the "cutoff" table
847 below: cutoff[i] is the smallest N such that k == CUTOFFBASE + i. */
848#define CUTOFFBASE 4
Guido van Rossum3aa23fd1999-01-14 19:01:53 +0000849static long cutoff[] = {
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000850 43, /* smallest N such that k == 4 */
851 106, /* etc */
852 250,
853 576,
854 1298,
855 2885,
856 6339,
857 13805,
858 29843,
859 64116,
860 137030,
861 291554,
862 617916,
863 1305130,
864 2748295,
865 5771662,
866 12091672,
867 25276798,
868 52734615,
869 109820537,
870 228324027,
871 473977813,
872 982548444, /* smallest N such that k == 26 */
873 2034159050 /* largest N that fits in signed 32-bit; k == 27 */
874};
875
876static int
Fred Drakea2f55112000-07-09 15:16:51 +0000877samplesortslice(PyObject **lo, PyObject **hi, PyObject *compare)
878 /* compare -- comparison function object, or NULL for default */
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000879{
880 register PyObject **l, **r;
881 register PyObject *tmp, *pivot;
882 register int k;
883 int n, extra, top, extraOnRight;
884 struct SamplesortStackNode stack[STACKSIZE];
885
886 /* assert lo <= hi */
887 n = hi - lo;
888
889 /* ----------------------------------------------------------
890 * Special cases
891 * --------------------------------------------------------*/
892 if (n < 2)
893 return 0;
894
895 /* Set r to the largest value such that [lo,r) is sorted.
896 This catches the already-sorted case, the all-the-same
897 case, and the appended-a-few-elements-to-a-sorted-list case.
898 If the array is unsorted, we're very likely to get out of
899 the loop fast, so the test is cheap if it doesn't pay off.
900 */
901 /* assert lo < hi */
902 for (r = lo+1; r < hi; ++r) {
903 SETK(*r, *(r-1));
904 if (k < 0)
905 break;
906 }
907 /* [lo,r) is sorted, [r,hi) unknown. Get out cheap if there are
908 few unknowns, or few elements in total. */
909 if (hi - r <= MAXMERGE || n < MINSIZE)
Guido van Rossum42812581998-06-17 14:15:44 +0000910 return binarysort(lo, hi, r, compare);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000911
912 /* Check for the array already being reverse-sorted. Typical
913 benchmark-driven silliness <wink>. */
914 /* assert lo < hi */
915 for (r = lo+1; r < hi; ++r) {
916 SETK(*(r-1), *r);
917 if (k < 0)
918 break;
919 }
920 if (hi - r <= MAXMERGE) {
921 /* Reverse the reversed prefix, then insert the tail */
922 PyObject **originalr = r;
923 l = lo;
924 do {
925 --r;
926 tmp = *l; *l = *r; *r = tmp;
927 ++l;
928 } while (l < r);
Guido van Rossum42812581998-06-17 14:15:44 +0000929 return binarysort(lo, hi, originalr, compare);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000930 }
931
932 /* ----------------------------------------------------------
933 * Normal case setup: a large array without obvious pattern.
934 * --------------------------------------------------------*/
935
936 /* extra := a power of 2 ~= n/ln(n), less 1.
937 First find the smallest extra s.t. n < cutoff[extra] */
938 for (extra = 0;
939 extra < sizeof(cutoff) / sizeof(cutoff[0]);
940 ++extra) {
941 if (n < cutoff[extra])
942 break;
943 /* note that if we fall out of the loop, the value of
944 extra still makes *sense*, but may be smaller than
945 we would like (but the array has more than ~= 2**31
946 elements in this case!) */
947 }
948 /* Now k == extra - 1 + CUTOFFBASE. The smallest value k can
949 have is CUTOFFBASE-1, so
950 assert MINSIZE >= 2**(CUTOFFBASE-1) - 1 */
951 extra = (1 << (extra - 1 + CUTOFFBASE)) - 1;
952 /* assert extra > 0 and n >= extra */
953
954 /* Swap that many values to the start of the array. The
955 selection of elements is pseudo-random, but the same on
956 every run (this is intentional! timing algorithm changes is
957 a pain if timing varies across runs). */
958 {
959 unsigned int seed = n / extra; /* arbitrary */
960 unsigned int i;
961 for (i = 0; i < (unsigned)extra; ++i) {
962 /* j := random int in [i, n) */
963 unsigned int j;
964 seed = seed * 69069 + 7;
965 j = i + seed % (n - i);
966 tmp = lo[i]; lo[i] = lo[j]; lo[j] = tmp;
967 }
968 }
969
970 /* Recursively sort the preselected pivots. */
Guido van Rossum42812581998-06-17 14:15:44 +0000971 if (samplesortslice(lo, lo + extra, compare) < 0)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000972 goto fail;
973
974 top = 0; /* index of available stack slot */
975 lo += extra; /* point to first unknown */
976 extraOnRight = 0; /* the PPs are at the left end */
977
978 /* ----------------------------------------------------------
979 * Partition [lo, hi), and repeat until out of work.
980 * --------------------------------------------------------*/
981 for (;;) {
982 /* assert lo <= hi, so n >= 0 */
983 n = hi - lo;
984
985 /* We may not want, or may not be able, to partition:
986 If n is small, it's quicker to insert.
987 If extra is 0, we're out of pivots, and *must* use
988 another method.
989 */
990 if (n < MINPARTITIONSIZE || extra == 0) {
991 if (n >= MINSIZE) {
992 /* assert extra == 0
993 This is rare, since the average size
994 of a final block is only about
995 ln(original n). */
Guido van Rossum42812581998-06-17 14:15:44 +0000996 if (samplesortslice(lo, hi, compare) < 0)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000997 goto fail;
998 }
999 else {
1000 /* Binary insertion should be quicker,
1001 and we can take advantage of the PPs
1002 already being sorted. */
1003 if (extraOnRight && extra) {
1004 /* swap the PPs to the left end */
1005 k = extra;
1006 do {
1007 tmp = *lo;
1008 *lo = *hi;
1009 *hi = tmp;
1010 ++lo; ++hi;
1011 } while (--k);
1012 }
1013 if (binarysort(lo - extra, hi, lo,
Guido van Rossum42812581998-06-17 14:15:44 +00001014 compare) < 0)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001015 goto fail;
1016 }
1017
1018 /* Find another slice to work on. */
1019 if (--top < 0)
1020 break; /* no more -- done! */
1021 lo = stack[top].lo;
1022 hi = stack[top].hi;
1023 extra = stack[top].extra;
1024 extraOnRight = 0;
1025 if (extra < 0) {
1026 extraOnRight = 1;
1027 extra = -extra;
1028 }
1029 continue;
1030 }
1031
1032 /* Pretend the PPs are indexed 0, 1, ..., extra-1.
1033 Then our preselected pivot is at (extra-1)/2, and we
1034 want to move the PPs before that to the left end of
1035 the slice, and the PPs after that to the right end.
1036 The following section changes extra, lo, hi, and the
1037 slice such that:
1038 [lo-extra, lo) contains the smaller PPs.
1039 *lo == our PP.
1040 (lo, hi) contains the unknown elements.
1041 [hi, hi+extra) contains the larger PPs.
1042 */
1043 k = extra >>= 1; /* num PPs to move */
1044 if (extraOnRight) {
1045 /* Swap the smaller PPs to the left end.
1046 Note that this loop actually moves k+1 items:
1047 the last is our PP */
1048 do {
1049 tmp = *lo; *lo = *hi; *hi = tmp;
1050 ++lo; ++hi;
1051 } while (k--);
1052 }
1053 else {
1054 /* Swap the larger PPs to the right end. */
1055 while (k--) {
1056 --lo; --hi;
1057 tmp = *lo; *lo = *hi; *hi = tmp;
1058 }
1059 }
1060 --lo; /* *lo is now our PP */
1061 pivot = *lo;
1062
1063 /* Now an almost-ordinary quicksort partition step.
1064 Note that most of the time is spent here!
1065 Only odd thing is that we partition into < and >=,
1066 instead of the usual <= and >=. This helps when
1067 there are lots of duplicates of different values,
1068 because it eventually tends to make subfiles
1069 "pure" (all duplicates), and we special-case for
1070 duplicates later. */
1071 l = lo + 1;
1072 r = hi - 1;
1073 /* assert lo < l < r < hi (small n weeded out above) */
1074
1075 do {
1076 /* slide l right, looking for key >= pivot */
1077 do {
1078 SETK(*l, pivot);
1079 if (k < 0)
1080 ++l;
1081 else
1082 break;
1083 } while (l < r);
1084
1085 /* slide r left, looking for key < pivot */
1086 while (l < r) {
Guido van Rossum42812581998-06-17 14:15:44 +00001087 register PyObject *rval = *r--;
1088 SETK(rval, pivot);
1089 if (k < 0) {
1090 /* swap and advance */
1091 r[1] = *l;
1092 *l++ = rval;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001093 break;
Guido van Rossum42812581998-06-17 14:15:44 +00001094 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001095 }
1096
1097 } while (l < r);
1098
1099 /* assert lo < r <= l < hi
1100 assert r == l or r+1 == l
1101 everything to the left of l is < pivot, and
1102 everything to the right of r is >= pivot */
1103
1104 if (l == r) {
1105 SETK(*r, pivot);
1106 if (k < 0)
1107 ++l;
1108 else
1109 --r;
1110 }
1111 /* assert lo <= r and r+1 == l and l <= hi
1112 assert r == lo or a[r] < pivot
1113 assert a[lo] is pivot
1114 assert l == hi or a[l] >= pivot
1115 Swap the pivot into "the middle", so we can henceforth
1116 ignore it.
1117 */
1118 *lo = *r;
1119 *r = pivot;
1120
1121 /* The following is true now, & will be preserved:
1122 All in [lo,r) are < pivot
1123 All in [r,l) == pivot (& so can be ignored)
1124 All in [l,hi) are >= pivot */
1125
1126 /* Check for duplicates of the pivot. One compare is
1127 wasted if there are no duplicates, but can win big
1128 when there are.
1129 Tricky: we're sticking to "<" compares, so deduce
1130 equality indirectly. We know pivot <= *l, so they're
1131 equal iff not pivot < *l.
1132 */
1133 while (l < hi) {
1134 /* pivot <= *l known */
1135 SETK(pivot, *l);
1136 if (k < 0)
1137 break;
1138 else
1139 /* <= and not < implies == */
1140 ++l;
1141 }
1142
1143 /* assert lo <= r < l <= hi
1144 Partitions are [lo, r) and [l, hi) */
1145
1146 /* push fattest first; remember we still have extra PPs
1147 to the left of the left chunk and to the right of
1148 the right chunk! */
1149 /* assert top < STACKSIZE */
1150 if (r - lo <= hi - l) {
1151 /* second is bigger */
1152 stack[top].lo = l;
1153 stack[top].hi = hi;
1154 stack[top].extra = -extra;
1155 hi = r;
1156 extraOnRight = 0;
1157 }
1158 else {
1159 /* first is bigger */
1160 stack[top].lo = lo;
1161 stack[top].hi = r;
1162 stack[top].extra = extra;
1163 lo = l;
1164 extraOnRight = 1;
1165 }
1166 ++top;
1167
1168 } /* end of partitioning loop */
1169
1170 return 0;
1171
1172 fail:
1173 return -1;
1174}
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001175
1176#undef SETK
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001177
1178staticforward PyTypeObject immutable_list_type;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001179
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001180static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00001181listsort(PyListObject *self, PyObject *args)
Guido van Rossum3f236de1996-12-10 23:55:39 +00001182{
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001183 int err;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001184 PyObject *compare = NULL;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001185
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001186 if (args != NULL) {
Guido van Rossumc00a9382000-02-24 21:48:29 +00001187 if (!PyArg_ParseTuple(args, "|O:sort", &compare))
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001188 return NULL;
1189 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001190 self->ob_type = &immutable_list_type;
1191 err = samplesortslice(self->ob_item,
1192 self->ob_item + self->ob_size,
Guido van Rossum42812581998-06-17 14:15:44 +00001193 compare);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001194 self->ob_type = &PyList_Type;
1195 if (err < 0)
Guido van Rossum3f236de1996-12-10 23:55:39 +00001196 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001197 Py_INCREF(Py_None);
1198 return Py_None;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001199}
1200
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001201int
Fred Drakea2f55112000-07-09 15:16:51 +00001202PyList_Sort(PyObject *v)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001203{
1204 if (v == NULL || !PyList_Check(v)) {
1205 PyErr_BadInternalCall();
1206 return -1;
1207 }
1208 v = listsort((PyListObject *)v, (PyObject *)NULL);
1209 if (v == NULL)
1210 return -1;
1211 Py_DECREF(v);
1212 return 0;
1213}
1214
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001215static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00001216listreverse(PyListObject *self, PyObject *args)
Guido van Rossumed98d481991-03-06 13:07:53 +00001217{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001218 register PyObject **p, **q;
1219 register PyObject *tmp;
Guido van Rossumed98d481991-03-06 13:07:53 +00001220
Guido van Rossumc00a9382000-02-24 21:48:29 +00001221 if (!PyArg_ParseTuple(args, ":reverse"))
Guido van Rossumed98d481991-03-06 13:07:53 +00001222 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00001223
1224 if (self->ob_size > 1) {
1225 for (p = self->ob_item, q = self->ob_item + self->ob_size - 1;
1226 p < q; p++, q--) {
1227 tmp = *p;
1228 *p = *q;
1229 *q = tmp;
1230 }
1231 }
1232
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001233 Py_INCREF(Py_None);
1234 return Py_None;
Guido van Rossumed98d481991-03-06 13:07:53 +00001235}
1236
Guido van Rossum84c76f51990-10-30 13:32:20 +00001237int
Fred Drakea2f55112000-07-09 15:16:51 +00001238PyList_Reverse(PyObject *v)
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00001239{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001240 if (v == NULL || !PyList_Check(v)) {
1241 PyErr_BadInternalCall();
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00001242 return -1;
1243 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001244 v = listreverse((PyListObject *)v, (PyObject *)NULL);
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00001245 if (v == NULL)
1246 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001247 Py_DECREF(v);
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00001248 return 0;
1249}
1250
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001251PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00001252PyList_AsTuple(PyObject *v)
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00001253{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001254 PyObject *w;
1255 PyObject **p;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00001256 int n;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001257 if (v == NULL || !PyList_Check(v)) {
1258 PyErr_BadInternalCall();
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00001259 return NULL;
1260 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001261 n = ((PyListObject *)v)->ob_size;
1262 w = PyTuple_New(n);
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00001263 if (w == NULL)
1264 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001265 p = ((PyTupleObject *)w)->ob_item;
Thomas Wouters334fb892000-07-25 12:56:38 +00001266 memcpy((void *)p,
1267 (void *)((PyListObject *)v)->ob_item,
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001268 n*sizeof(PyObject *));
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00001269 while (--n >= 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001270 Py_INCREF(*p);
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00001271 p++;
1272 }
1273 return w;
1274}
1275
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001276static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00001277listindex(PyListObject *self, PyObject *args)
Guido van Rossumed98d481991-03-06 13:07:53 +00001278{
1279 int i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001280 PyObject *v;
1281
Guido van Rossumef93b872000-03-13 15:41:59 +00001282 if (!PyArg_ParseTuple_Compat1(args, "O:index", &v))
Guido van Rossumed98d481991-03-06 13:07:53 +00001283 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00001284 for (i = 0; i < self->ob_size; i++) {
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001285 if (PyObject_Compare(self->ob_item[i], v) == 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001286 return PyInt_FromLong((long)i);
Guido van Rossumc8b6df91997-05-23 00:06:51 +00001287 if (PyErr_Occurred())
1288 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00001289 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001290 PyErr_SetString(PyExc_ValueError, "list.index(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00001291 return NULL;
1292}
1293
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001294static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00001295listcount(PyListObject *self, PyObject *args)
Guido van Rossume6f7d181991-10-20 20:20:40 +00001296{
1297 int count = 0;
1298 int i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001299 PyObject *v;
1300
Guido van Rossumef93b872000-03-13 15:41:59 +00001301 if (!PyArg_ParseTuple_Compat1(args, "O:count", &v))
Guido van Rossume6f7d181991-10-20 20:20:40 +00001302 return NULL;
Guido van Rossume6f7d181991-10-20 20:20:40 +00001303 for (i = 0; i < self->ob_size; i++) {
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001304 if (PyObject_Compare(self->ob_item[i], v) == 0)
Guido van Rossume6f7d181991-10-20 20:20:40 +00001305 count++;
Guido van Rossumc8b6df91997-05-23 00:06:51 +00001306 if (PyErr_Occurred())
1307 return NULL;
Guido van Rossume6f7d181991-10-20 20:20:40 +00001308 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001309 return PyInt_FromLong((long)count);
Guido van Rossume6f7d181991-10-20 20:20:40 +00001310}
1311
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001312static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00001313listremove(PyListObject *self, PyObject *args)
Guido van Rossumed98d481991-03-06 13:07:53 +00001314{
1315 int i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001316 PyObject *v;
1317
Guido van Rossumef93b872000-03-13 15:41:59 +00001318 if (!PyArg_ParseTuple_Compat1(args, "O:remove", &v))
Guido van Rossumed98d481991-03-06 13:07:53 +00001319 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00001320 for (i = 0; i < self->ob_size; i++) {
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001321 if (PyObject_Compare(self->ob_item[i], v) == 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001322 if (list_ass_slice(self, i, i+1,
1323 (PyObject *)NULL) != 0)
Guido van Rossumed98d481991-03-06 13:07:53 +00001324 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001325 Py_INCREF(Py_None);
1326 return Py_None;
Guido van Rossumed98d481991-03-06 13:07:53 +00001327 }
Guido van Rossumc8b6df91997-05-23 00:06:51 +00001328 if (PyErr_Occurred())
1329 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00001330 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001331 PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00001332 return NULL;
1333}
1334
Jeremy Hylton8caad492000-06-23 14:18:11 +00001335static int
1336list_traverse(PyListObject *o, visitproc visit, void *arg)
1337{
1338 int i, err;
1339 PyObject *x;
1340
1341 for (i = o->ob_size; --i >= 0; ) {
1342 x = o->ob_item[i];
1343 if (x != NULL) {
1344 err = visit(x, arg);
1345 if (err)
1346 return err;
1347 }
1348 }
1349 return 0;
1350}
1351
1352static int
1353list_clear(PyListObject *lp)
1354{
1355 (void) PyList_SetSlice((PyObject *)lp, 0, lp->ob_size, 0);
1356 return 0;
1357}
1358
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +00001359static char append_doc[] =
1360"L.append(object) -- append object to end";
Barry Warsawdedf6d61998-10-09 16:37:25 +00001361static char extend_doc[] =
1362"L.extend(list) -- extend list by appending list elements";
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +00001363static char insert_doc[] =
1364"L.insert(index, object) -- insert object before index";
1365static char pop_doc[] =
1366"L.pop([index]) -> item -- remove and return item at index (default last)";
1367static char remove_doc[] =
1368"L.remove(value) -- remove first occurrence of value";
1369static char index_doc[] =
1370"L.index(value) -> integer -- return index of first occurrence of value";
1371static char count_doc[] =
1372"L.count(value) -> integer -- return number of occurrences of value";
1373static char reverse_doc[] =
1374"L.reverse() -- reverse *IN PLACE*";
1375static char sort_doc[] =
1376"L.sort([cmpfunc]) -- sort *IN PLACE*; if given, cmpfunc(x, y) -> -1, 0, 1";
1377
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001378static PyMethodDef list_methods[] = {
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001379 {"append", (PyCFunction)listappend, 1, append_doc},
1380 {"insert", (PyCFunction)listinsert, 1, insert_doc},
Barry Warsawdedf6d61998-10-09 16:37:25 +00001381 {"extend", (PyCFunction)listextend, 1, extend_doc},
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +00001382 {"pop", (PyCFunction)listpop, 1, pop_doc},
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001383 {"remove", (PyCFunction)listremove, 1, remove_doc},
1384 {"index", (PyCFunction)listindex, 1, index_doc},
1385 {"count", (PyCFunction)listcount, 1, count_doc},
1386 {"reverse", (PyCFunction)listreverse, 1, reverse_doc},
1387 {"sort", (PyCFunction)listsort, 1, sort_doc},
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001388 {NULL, NULL} /* sentinel */
1389};
1390
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001391static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00001392list_getattr(PyListObject *f, char *name)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001393{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001394 return Py_FindMethod(list_methods, (PyObject *)f, name);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001395}
1396
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001397static PySequenceMethods list_as_sequence = {
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00001398 (inquiry)list_length, /*sq_length*/
1399 (binaryfunc)list_concat, /*sq_concat*/
1400 (intargfunc)list_repeat, /*sq_repeat*/
1401 (intargfunc)list_item, /*sq_item*/
1402 (intintargfunc)list_slice, /*sq_slice*/
1403 (intobjargproc)list_ass_item, /*sq_ass_item*/
1404 (intintobjargproc)list_ass_slice, /*sq_ass_slice*/
Jeremy Hylton37b1a262000-04-27 21:41:03 +00001405 (objobjproc)list_contains, /*sq_contains*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001406};
1407
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001408PyTypeObject PyList_Type = {
1409 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001410 0,
1411 "list",
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001412 sizeof(PyListObject) + PyGC_HEAD_SIZE,
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001413 0,
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00001414 (destructor)list_dealloc, /*tp_dealloc*/
1415 (printfunc)list_print, /*tp_print*/
1416 (getattrfunc)list_getattr, /*tp_getattr*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001417 0, /*tp_setattr*/
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00001418 (cmpfunc)list_compare, /*tp_compare*/
1419 (reprfunc)list_repr, /*tp_repr*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001420 0, /*tp_as_number*/
1421 &list_as_sequence, /*tp_as_sequence*/
1422 0, /*tp_as_mapping*/
Fred Drake56780252000-06-15 14:50:20 +00001423 0, /*tp_hash*/
1424 0, /*tp_call*/
1425 0, /*tp_str*/
1426 0, /*tp_getattro*/
1427 0, /*tp_setattro*/
1428 0, /*tp_as_buffer*/
Jeremy Hyltond08b4c42000-06-23 19:37:02 +00001429 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_GC, /*tp_flags*/
Jeremy Hylton8caad492000-06-23 14:18:11 +00001430 0, /* tp_doc */
1431 (traverseproc)list_traverse, /* tp_traverse */
1432 (inquiry)list_clear, /* tp_clear */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001433};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001434
1435
1436/* During a sort, we really can't have anyone modifying the list; it could
1437 cause core dumps. Thus, we substitute a dummy type that raises an
1438 explanatory exception when a modifying operation is used. Caveat:
1439 comparisons may behave differently; but I guess it's a bad idea anyway to
1440 compare a list that's being sorted... */
1441
1442static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00001443immutable_list_op(void)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001444{
1445 PyErr_SetString(PyExc_TypeError,
1446 "a list cannot be modified while it is being sorted");
1447 return NULL;
1448}
1449
1450static PyMethodDef immutable_list_methods[] = {
1451 {"append", (PyCFunction)immutable_list_op},
1452 {"insert", (PyCFunction)immutable_list_op},
1453 {"remove", (PyCFunction)immutable_list_op},
1454 {"index", (PyCFunction)listindex},
1455 {"count", (PyCFunction)listcount},
1456 {"reverse", (PyCFunction)immutable_list_op},
1457 {"sort", (PyCFunction)immutable_list_op},
1458 {NULL, NULL} /* sentinel */
1459};
1460
1461static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00001462immutable_list_getattr(PyListObject *f, char *name)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001463{
1464 return Py_FindMethod(immutable_list_methods, (PyObject *)f, name);
1465}
1466
1467static int
Fred Drakea2f55112000-07-09 15:16:51 +00001468immutable_list_ass(void)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001469{
1470 immutable_list_op();
1471 return -1;
1472}
1473
1474static PySequenceMethods immutable_list_as_sequence = {
1475 (inquiry)list_length, /*sq_length*/
1476 (binaryfunc)list_concat, /*sq_concat*/
1477 (intargfunc)list_repeat, /*sq_repeat*/
1478 (intargfunc)list_item, /*sq_item*/
1479 (intintargfunc)list_slice, /*sq_slice*/
1480 (intobjargproc)immutable_list_ass, /*sq_ass_item*/
1481 (intintobjargproc)immutable_list_ass, /*sq_ass_slice*/
Fred Drake56780252000-06-15 14:50:20 +00001482 (objobjproc)list_contains, /*sq_contains*/
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001483};
1484
1485static PyTypeObject immutable_list_type = {
1486 PyObject_HEAD_INIT(&PyType_Type)
1487 0,
1488 "list (immutable, during sort)",
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001489 sizeof(PyListObject) + PyGC_HEAD_SIZE,
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001490 0,
1491 0, /*tp_dealloc*/ /* Cannot happen */
1492 (printfunc)list_print, /*tp_print*/
1493 (getattrfunc)immutable_list_getattr, /*tp_getattr*/
1494 0, /*tp_setattr*/
1495 0, /*tp_compare*/ /* Won't be called */
1496 (reprfunc)list_repr, /*tp_repr*/
1497 0, /*tp_as_number*/
1498 &immutable_list_as_sequence, /*tp_as_sequence*/
1499 0, /*tp_as_mapping*/
Fred Drake56780252000-06-15 14:50:20 +00001500 0, /*tp_hash*/
1501 0, /*tp_call*/
1502 0, /*tp_str*/
1503 0, /*tp_getattro*/
1504 0, /*tp_setattro*/
1505 0, /*tp_as_buffer*/
Jeremy Hyltond08b4c42000-06-23 19:37:02 +00001506 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_GC, /*tp_flags*/
Jeremy Hylton8caad492000-06-23 14:18:11 +00001507 0, /* tp_doc */
1508 (traverseproc)list_traverse, /* tp_traverse */
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001509};