blob: 721a4f2ded0fa03a77e5161191536d88b7307489 [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
Jack Jansene9791602000-08-22 21:51:22 +000020#ifdef HAVE_LIMITS_H
21#include <limits.h>
22#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000023
Guido van Rossumc0b618a1997-05-02 03:12:38 +000024#define ROUNDUP(n, PyTryBlock) \
25 ((((n)+(PyTryBlock)-1)/(PyTryBlock))*(PyTryBlock))
Guido van Rossuma46d51d1995-01-26 22:59:43 +000026
27static int
Fred Drakea2f55112000-07-09 15:16:51 +000028roundupsize(int n)
Guido van Rossuma46d51d1995-01-26 22:59:43 +000029{
30 if (n < 500)
31 return ROUNDUP(n, 10);
32 else
33 return ROUNDUP(n, 100);
34}
35
Guido van Rossuma27d1121997-08-25 18:36:23 +000036#define NRESIZE(var, type, nitems) PyMem_RESIZE(var, type, roundupsize(nitems))
Guido van Rossuma46d51d1995-01-26 22:59:43 +000037
Guido van Rossumc0b618a1997-05-02 03:12:38 +000038PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +000039PyList_New(int size)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000040{
41 int i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +000042 PyListObject *op;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +000043 size_t nbytes;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000044 if (size < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +000045 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000046 return NULL;
47 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +000048 nbytes = size * sizeof(PyObject *);
Guido van Rossum1e28e5e1992-08-19 16:46:30 +000049 /* Check for overflow */
Guido van Rossumc0b618a1997-05-02 03:12:38 +000050 if (nbytes / sizeof(PyObject *) != (size_t)size) {
51 return PyErr_NoMemory();
Guido van Rossum1e28e5e1992-08-19 16:46:30 +000052 }
Guido van Rossumb18618d2000-05-03 23:44:39 +000053 /* PyObject_NewVar is inlined */
Jeremy Hyltond08b4c42000-06-23 19:37:02 +000054 op = (PyListObject *) PyObject_MALLOC(sizeof(PyListObject)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +000055 + PyGC_HEAD_SIZE);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000056 if (op == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +000057 return PyErr_NoMemory();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000058 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +000059 op = (PyListObject *) PyObject_FROM_GC(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000060 if (size <= 0) {
61 op->ob_item = NULL;
62 }
63 else {
Guido van Rossumb18618d2000-05-03 23:44:39 +000064 op->ob_item = (PyObject **) PyMem_MALLOC(nbytes);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000065 if (op->ob_item == NULL) {
Vladimir Marangozov467a67e2000-07-15 03:31:31 +000066 PyObject_FREE(PyObject_AS_GC(op));
Guido van Rossumc0b618a1997-05-02 03:12:38 +000067 return PyErr_NoMemory();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000068 }
69 }
Guido van Rossumb18618d2000-05-03 23:44:39 +000070 PyObject_INIT_VAR(op, &PyList_Type, size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000071 for (i = 0; i < size; i++)
72 op->ob_item[i] = NULL;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +000073 PyObject_GC_Init(op);
Guido van Rossumc0b618a1997-05-02 03:12:38 +000074 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000075}
76
77int
Fred Drakea2f55112000-07-09 15:16:51 +000078PyList_Size(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000079{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000080 if (!PyList_Check(op)) {
81 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000082 return -1;
83 }
84 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +000085 return ((PyListObject *)op) -> ob_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000086}
87
Guido van Rossumc0b618a1997-05-02 03:12:38 +000088static PyObject *indexerr;
Guido van Rossum929f1b81996-08-09 20:51:27 +000089
Guido van Rossumc0b618a1997-05-02 03:12:38 +000090PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +000091PyList_GetItem(PyObject *op, int i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000092{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000093 if (!PyList_Check(op)) {
94 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000095 return NULL;
96 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +000097 if (i < 0 || i >= ((PyListObject *)op) -> ob_size) {
Guido van Rossum929f1b81996-08-09 20:51:27 +000098 if (indexerr == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +000099 indexerr = PyString_FromString(
100 "list index out of range");
101 PyErr_SetObject(PyExc_IndexError, indexerr);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000102 return NULL;
103 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000104 return ((PyListObject *)op) -> ob_item[i];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000105}
106
107int
Fred Drakea2f55112000-07-09 15:16:51 +0000108PyList_SetItem(register PyObject *op, register int i,
109 register PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000110{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000111 register PyObject *olditem;
112 register PyObject **p;
113 if (!PyList_Check(op)) {
114 Py_XDECREF(newitem);
115 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000116 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000117 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000118 if (i < 0 || i >= ((PyListObject *)op) -> ob_size) {
119 Py_XDECREF(newitem);
120 PyErr_SetString(PyExc_IndexError,
121 "list assignment index out of range");
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000122 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000123 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000124 p = ((PyListObject *)op) -> ob_item + i;
Guido van Rossum5fe60581995-03-09 12:12:50 +0000125 olditem = *p;
126 *p = newitem;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000127 Py_XDECREF(olditem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000128 return 0;
129}
130
131static int
Fred Drakea2f55112000-07-09 15:16:51 +0000132ins1(PyListObject *self, int where, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000133{
134 int i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000135 PyObject **items;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000136 if (v == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000137 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000138 return -1;
139 }
Trent Micka5846642000-08-13 22:47:45 +0000140 if (self->ob_size == INT_MAX) {
141 PyErr_SetString(PyExc_OverflowError,
142 "cannot add more objects to list");
143 return -1;
144 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000145 items = self->ob_item;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000146 NRESIZE(items, PyObject *, self->ob_size+1);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000147 if (items == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000148 PyErr_NoMemory();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000149 return -1;
150 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000151 if (where < 0)
152 where = 0;
153 if (where > self->ob_size)
154 where = self->ob_size;
155 for (i = self->ob_size; --i >= where; )
156 items[i+1] = items[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000157 Py_INCREF(v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000158 items[where] = v;
159 self->ob_item = items;
160 self->ob_size++;
161 return 0;
162}
163
164int
Fred Drakea2f55112000-07-09 15:16:51 +0000165PyList_Insert(PyObject *op, int where, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000166{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000167 if (!PyList_Check(op)) {
168 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000169 return -1;
170 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000171 return ins1((PyListObject *)op, where, newitem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000172}
173
174int
Fred Drakea2f55112000-07-09 15:16:51 +0000175PyList_Append(PyObject *op, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000176{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000177 if (!PyList_Check(op)) {
178 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000179 return -1;
180 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000181 return ins1((PyListObject *)op,
182 (int) ((PyListObject *)op)->ob_size, newitem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000183}
184
185/* Methods */
186
187static void
Fred Drakea2f55112000-07-09 15:16:51 +0000188list_dealloc(PyListObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000189{
190 int i;
Guido van Rossumd724b232000-03-13 16:01:29 +0000191 Py_TRASHCAN_SAFE_BEGIN(op)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000192 PyObject_GC_Fini(op);
Jack Jansen7874d1f1995-01-19 12:09:27 +0000193 if (op->ob_item != NULL) {
Guido van Rossumfa717011999-06-09 15:19:34 +0000194 /* Do it backwards, for Christian Tismer.
195 There's a simple test case where somehow this reduces
196 thrashing when a *very* large list is created and
197 immediately deleted. */
198 i = op->ob_size;
199 while (--i >= 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000200 Py_XDECREF(op->ob_item[i]);
Jack Jansen7874d1f1995-01-19 12:09:27 +0000201 }
Guido van Rossumb18618d2000-05-03 23:44:39 +0000202 PyMem_FREE(op->ob_item);
Jack Jansen7874d1f1995-01-19 12:09:27 +0000203 }
Guido van Rossum4cc6ac72000-07-01 01:00:38 +0000204 op = (PyListObject *) PyObject_AS_GC(op);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000205 PyObject_DEL(op);
Guido van Rossumd724b232000-03-13 16:01:29 +0000206 Py_TRASHCAN_SAFE_END(op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000207}
208
Guido van Rossum90933611991-06-07 16:10:43 +0000209static int
Fred Drakea2f55112000-07-09 15:16:51 +0000210list_print(PyListObject *op, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000211{
212 int i;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000213
214 i = Py_ReprEnter((PyObject*)op);
215 if (i != 0) {
216 if (i < 0)
217 return i;
218 fprintf(fp, "[...]");
219 return 0;
220 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000221 fprintf(fp, "[");
Guido van Rossum90933611991-06-07 16:10:43 +0000222 for (i = 0; i < op->ob_size; i++) {
223 if (i > 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000224 fprintf(fp, ", ");
Guido van Rossumfb376de1998-04-10 22:47:27 +0000225 if (PyObject_Print(op->ob_item[i], fp, 0) != 0) {
226 Py_ReprLeave((PyObject *)op);
Guido van Rossum90933611991-06-07 16:10:43 +0000227 return -1;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000228 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000229 }
230 fprintf(fp, "]");
Guido van Rossumfb376de1998-04-10 22:47:27 +0000231 Py_ReprLeave((PyObject *)op);
Guido van Rossum90933611991-06-07 16:10:43 +0000232 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000233}
234
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000235static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000236list_repr(PyListObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000237{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000238 PyObject *s, *comma;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000239 int i;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000240
241 i = Py_ReprEnter((PyObject*)v);
242 if (i != 0) {
243 if (i > 0)
244 return PyString_FromString("[...]");
245 return NULL;
246 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000247 s = PyString_FromString("[");
248 comma = PyString_FromString(", ");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000249 for (i = 0; i < v->ob_size && s != NULL; i++) {
250 if (i > 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000251 PyString_Concat(&s, comma);
252 PyString_ConcatAndDel(&s, PyObject_Repr(v->ob_item[i]));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000253 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000254 Py_XDECREF(comma);
255 PyString_ConcatAndDel(&s, PyString_FromString("]"));
Guido van Rossumfb376de1998-04-10 22:47:27 +0000256 Py_ReprLeave((PyObject *)v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000257 return s;
258}
259
260static int
Fred Drakea2f55112000-07-09 15:16:51 +0000261list_compare(PyListObject *v, PyListObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000262{
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000263 int i;
Jack Jansene9791602000-08-22 21:51:22 +0000264
Guido van Rossumae621ff1998-05-28 20:18:46 +0000265 for (i = 0; i < v->ob_size && i < w->ob_size; i++) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000266 int cmp = PyObject_Compare(v->ob_item[i], w->ob_item[i]);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000267 if (cmp != 0)
268 return cmp;
269 }
270 return v->ob_size - w->ob_size;
271}
272
273static int
Fred Drakea2f55112000-07-09 15:16:51 +0000274list_length(PyListObject *a)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000275{
276 return a->ob_size;
277}
278
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000279
280
281static int
Fred Drakea2f55112000-07-09 15:16:51 +0000282list_contains(PyListObject *a, PyObject *el)
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000283{
284 int i, cmp;
285
286 for (i = 0; i < a->ob_size; ++i) {
287 cmp = PyObject_Compare(el, PyList_GET_ITEM(a, i));
288 if (cmp == 0)
289 return 1;
290 if (PyErr_Occurred())
291 return -1;
292 }
293 return 0;
294}
295
296
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000297static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000298list_item(PyListObject *a, int i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000299{
300 if (i < 0 || i >= a->ob_size) {
Guido van Rossum929f1b81996-08-09 20:51:27 +0000301 if (indexerr == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000302 indexerr = PyString_FromString(
303 "list index out of range");
304 PyErr_SetObject(PyExc_IndexError, indexerr);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000305 return NULL;
306 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000307 Py_INCREF(a->ob_item[i]);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000308 return a->ob_item[i];
309}
310
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000311static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000312list_slice(PyListObject *a, int ilow, int ihigh)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000313{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000314 PyListObject *np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000315 int i;
316 if (ilow < 0)
317 ilow = 0;
318 else if (ilow > a->ob_size)
319 ilow = a->ob_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000320 if (ihigh < ilow)
321 ihigh = ilow;
322 else if (ihigh > a->ob_size)
323 ihigh = a->ob_size;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000324 np = (PyListObject *) PyList_New(ihigh - ilow);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000325 if (np == NULL)
326 return NULL;
327 for (i = ilow; i < ihigh; i++) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000328 PyObject *v = a->ob_item[i];
329 Py_INCREF(v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000330 np->ob_item[i - ilow] = v;
331 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000332 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000333}
334
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000335PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000336PyList_GetSlice(PyObject *a, int ilow, int ihigh)
Guido van Rossum234f9421993-06-17 12:35:49 +0000337{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000338 if (!PyList_Check(a)) {
339 PyErr_BadInternalCall();
Guido van Rossum234f9421993-06-17 12:35:49 +0000340 return NULL;
341 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000342 return list_slice((PyListObject *)a, ilow, ihigh);
Guido van Rossum234f9421993-06-17 12:35:49 +0000343}
344
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000345static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000346list_concat(PyListObject *a, PyObject *bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000347{
348 int size;
349 int i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000350 PyListObject *np;
351 if (!PyList_Check(bb)) {
Fred Drakeb6a9ada2000-06-01 03:12:13 +0000352 PyErr_Format(PyExc_TypeError,
Fred Drake914a2ed2000-06-01 14:31:03 +0000353 "can only concatenate list (not \"%.200s\") to list",
354 bb->ob_type->tp_name);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000355 return NULL;
356 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000357#define b ((PyListObject *)bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000358 size = a->ob_size + b->ob_size;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000359 np = (PyListObject *) PyList_New(size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000360 if (np == NULL) {
Guido van Rossum90933611991-06-07 16:10:43 +0000361 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000362 }
363 for (i = 0; i < a->ob_size; i++) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000364 PyObject *v = a->ob_item[i];
365 Py_INCREF(v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000366 np->ob_item[i] = v;
367 }
368 for (i = 0; i < b->ob_size; i++) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000369 PyObject *v = b->ob_item[i];
370 Py_INCREF(v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000371 np->ob_item[i + a->ob_size] = v;
372 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000373 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000374#undef b
375}
376
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000377static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000378list_repeat(PyListObject *a, int n)
Guido van Rossumed98d481991-03-06 13:07:53 +0000379{
380 int i, j;
381 int size;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000382 PyListObject *np;
383 PyObject **p;
Guido van Rossumed98d481991-03-06 13:07:53 +0000384 if (n < 0)
385 n = 0;
386 size = a->ob_size * n;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000387 np = (PyListObject *) PyList_New(size);
Guido van Rossumed98d481991-03-06 13:07:53 +0000388 if (np == NULL)
389 return NULL;
390 p = np->ob_item;
391 for (i = 0; i < n; i++) {
392 for (j = 0; j < a->ob_size; j++) {
393 *p = a->ob_item[j];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000394 Py_INCREF(*p);
Guido van Rossumed98d481991-03-06 13:07:53 +0000395 p++;
396 }
397 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000398 return (PyObject *) np;
Guido van Rossumed98d481991-03-06 13:07:53 +0000399}
400
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000401static int
Fred Drakea2f55112000-07-09 15:16:51 +0000402list_ass_slice(PyListObject *a, int ilow, int ihigh, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000403{
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000404 /* Because [X]DECREF can recursively invoke list operations on
405 this list, we must postpone all [X]DECREF activity until
406 after the list is back in its canonical shape. Therefore
407 we must allocate an additional array, 'recycle', into which
408 we temporarily copy the items that are deleted from the
409 list. :-( */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000410 PyObject **recycle, **p;
411 PyObject **item;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000412 int n; /* Size of replacement list */
413 int d; /* Change in size */
414 int k; /* Loop index */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000415#define b ((PyListObject *)v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000416 if (v == NULL)
417 n = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000418 else if (PyList_Check(v)) {
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000419 n = b->ob_size;
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000420 if (a == b) {
421 /* Special case "a[i:j] = a" -- copy b first */
422 int ret;
423 v = list_slice(b, 0, n);
424 ret = list_ass_slice(a, ilow, ihigh, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000425 Py_DECREF(v);
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000426 return ret;
427 }
428 }
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000429 else {
Fred Drakeb6a9ada2000-06-01 03:12:13 +0000430 PyErr_Format(PyExc_TypeError,
431 "must assign list (not \"%.200s\") to slice",
432 v->ob_type->tp_name);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000433 return -1;
434 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000435 if (ilow < 0)
436 ilow = 0;
437 else if (ilow > a->ob_size)
438 ilow = a->ob_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000439 if (ihigh < ilow)
440 ihigh = ilow;
441 else if (ihigh > a->ob_size)
442 ihigh = a->ob_size;
443 item = a->ob_item;
444 d = n - (ihigh-ilow);
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000445 if (ihigh > ilow)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000446 p = recycle = PyMem_NEW(PyObject *, (ihigh-ilow));
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000447 else
448 p = recycle = NULL;
449 if (d <= 0) { /* Delete -d items; recycle ihigh-ilow items */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000450 for (k = ilow; k < ihigh; k++)
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000451 *p++ = item[k];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000452 if (d < 0) {
453 for (/*k = ihigh*/; k < a->ob_size; k++)
454 item[k+d] = item[k];
455 a->ob_size += d;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000456 NRESIZE(item, PyObject *, a->ob_size); /* Can't fail */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000457 a->ob_item = item;
458 }
459 }
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000460 else { /* Insert d items; recycle ihigh-ilow items */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000461 NRESIZE(item, PyObject *, a->ob_size + d);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000462 if (item == NULL) {
Guido van Rossumb18618d2000-05-03 23:44:39 +0000463 if (recycle != NULL)
464 PyMem_DEL(recycle);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000465 PyErr_NoMemory();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000466 return -1;
467 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000468 for (k = a->ob_size; --k >= ihigh; )
469 item[k+d] = item[k];
470 for (/*k = ihigh-1*/; k >= ilow; --k)
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000471 *p++ = item[k];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000472 a->ob_item = item;
473 a->ob_size += d;
474 }
475 for (k = 0; k < n; k++, ilow++) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000476 PyObject *w = b->ob_item[k];
477 Py_XINCREF(w);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000478 item[ilow] = w;
479 }
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000480 if (recycle) {
481 while (--p >= recycle)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000482 Py_XDECREF(*p);
483 PyMem_DEL(recycle);
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000484 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000485 return 0;
486#undef b
487}
488
Guido van Rossum234f9421993-06-17 12:35:49 +0000489int
Fred Drakea2f55112000-07-09 15:16:51 +0000490PyList_SetSlice(PyObject *a, int ilow, int ihigh, PyObject *v)
Guido van Rossum234f9421993-06-17 12:35:49 +0000491{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000492 if (!PyList_Check(a)) {
493 PyErr_BadInternalCall();
Guido van Rossum1fc238a1993-07-29 08:25:09 +0000494 return -1;
Guido van Rossum234f9421993-06-17 12:35:49 +0000495 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000496 return list_ass_slice((PyListObject *)a, ilow, ihigh, v);
Guido van Rossum234f9421993-06-17 12:35:49 +0000497}
498
Guido van Rossum4a450d01991-04-03 19:05:18 +0000499static int
Fred Drakea2f55112000-07-09 15:16:51 +0000500list_ass_item(PyListObject *a, int i, PyObject *v)
Guido van Rossum4a450d01991-04-03 19:05:18 +0000501{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000502 PyObject *old_value;
Guido van Rossum4a450d01991-04-03 19:05:18 +0000503 if (i < 0 || i >= a->ob_size) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000504 PyErr_SetString(PyExc_IndexError,
505 "list assignment index out of range");
Guido van Rossum4a450d01991-04-03 19:05:18 +0000506 return -1;
507 }
508 if (v == NULL)
509 return list_ass_slice(a, i, i+1, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000510 Py_INCREF(v);
Guido van Rossumd7047b31995-01-02 19:07:15 +0000511 old_value = a->ob_item[i];
Guido van Rossum4a450d01991-04-03 19:05:18 +0000512 a->ob_item[i] = v;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000513 Py_DECREF(old_value);
Guido van Rossum4a450d01991-04-03 19:05:18 +0000514 return 0;
515}
516
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000517static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000518ins(PyListObject *self, int where, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000519{
520 if (ins1(self, where, v) != 0)
521 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000522 Py_INCREF(Py_None);
523 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000524}
525
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000526static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000527listinsert(PyListObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000528{
529 int i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000530 PyObject *v;
Guido van Rossumc00a9382000-02-24 21:48:29 +0000531 if (!PyArg_ParseTuple(args, "iO:insert", &i, &v))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000532 return NULL;
Guido van Rossumbf80e541993-02-08 15:49:17 +0000533 return ins(self, i, v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000534}
535
Guido van Rossumef93b872000-03-13 15:41:59 +0000536/* Define NO_STRICT_LIST_APPEND to enable multi-argument append() */
537
538#ifndef NO_STRICT_LIST_APPEND
539#define PyArg_ParseTuple_Compat1 PyArg_ParseTuple
540#else
541#define PyArg_ParseTuple_Compat1(args, format, ret) \
542( \
543 PyTuple_GET_SIZE(args) > 1 ? (*ret = args, 1) : \
544 PyTuple_GET_SIZE(args) == 1 ? (*ret = PyTuple_GET_ITEM(args, 0), 1) : \
545 PyArg_ParseTuple(args, format, ret) \
546)
547#endif
548
549
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000550static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000551listappend(PyListObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000552{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000553 PyObject *v;
Guido van Rossumef93b872000-03-13 15:41:59 +0000554 if (!PyArg_ParseTuple_Compat1(args, "O:append", &v))
Guido van Rossumbf80e541993-02-08 15:49:17 +0000555 return NULL;
556 return ins(self, (int) self->ob_size, v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000557}
558
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000559static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000560listextend(PyListObject *self, PyObject *args)
Barry Warsawdedf6d61998-10-09 16:37:25 +0000561{
562 PyObject *b = NULL, *res = NULL;
563 PyObject **items;
564 int selflen = PyList_GET_SIZE(self);
565 int blen;
566 register int i;
567
Guido van Rossumc00a9382000-02-24 21:48:29 +0000568 if (!PyArg_ParseTuple(args, "O:extend", &b))
Barry Warsawdedf6d61998-10-09 16:37:25 +0000569 return NULL;
570
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000571 b = PySequence_Fast(b, "list.extend() argument must be a sequence");
572 if (!b)
Barry Warsawdedf6d61998-10-09 16:37:25 +0000573 return NULL;
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000574
Jeremy Hylton03657cf2000-07-12 13:05:33 +0000575 if (PyObject_Size(b) == 0)
Barry Warsawdedf6d61998-10-09 16:37:25 +0000576 /* short circuit when b is empty */
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000577 goto ok;
578
Barry Warsawdedf6d61998-10-09 16:37:25 +0000579 if (self == (PyListObject*)b) {
580 /* as in list_ass_slice() we must special case the
581 * situation: a.extend(a)
582 *
583 * XXX: I think this way ought to be faster than using
584 * list_slice() the way list_ass_slice() does.
585 */
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000586 Py_DECREF(b);
Barry Warsawdedf6d61998-10-09 16:37:25 +0000587 b = PyList_New(selflen);
588 if (!b)
589 return NULL;
590 for (i = 0; i < selflen; i++) {
591 PyObject *o = PyList_GET_ITEM(self, i);
592 Py_INCREF(o);
593 PyList_SET_ITEM(b, i, o);
594 }
595 }
Barry Warsawdedf6d61998-10-09 16:37:25 +0000596
Jeremy Hylton03657cf2000-07-12 13:05:33 +0000597 blen = PyObject_Size(b);
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000598
Barry Warsawdedf6d61998-10-09 16:37:25 +0000599 /* resize a using idiom */
600 items = self->ob_item;
601 NRESIZE(items, PyObject*, selflen + blen);
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000602 if (items == NULL) {
Barry Warsawdedf6d61998-10-09 16:37:25 +0000603 PyErr_NoMemory();
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000604 goto failed;
Barry Warsawdedf6d61998-10-09 16:37:25 +0000605 }
606 self->ob_item = items;
607
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000608 /* populate the end of self with b's items */
Barry Warsawdedf6d61998-10-09 16:37:25 +0000609 for (i = 0; i < blen; i++) {
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000610 PyObject *o = PySequence_Fast_GET_ITEM(b, i);
Barry Warsawdedf6d61998-10-09 16:37:25 +0000611 Py_INCREF(o);
612 PyList_SET_ITEM(self, self->ob_size++, o);
613 }
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000614 ok:
Barry Warsawdedf6d61998-10-09 16:37:25 +0000615 res = Py_None;
616 Py_INCREF(res);
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000617 failed:
618 Py_DECREF(b);
Barry Warsawdedf6d61998-10-09 16:37:25 +0000619 return res;
620}
621
622
623static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000624listpop(PyListObject *self, PyObject *args)
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000625{
626 int i = -1;
627 PyObject *v;
Guido van Rossumc00a9382000-02-24 21:48:29 +0000628 if (!PyArg_ParseTuple(args, "|i:pop", &i))
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000629 return NULL;
630 if (self->ob_size == 0) {
631 /* Special-case most common failure cause */
632 PyErr_SetString(PyExc_IndexError, "pop from empty list");
633 return NULL;
634 }
635 if (i < 0)
636 i += self->ob_size;
637 if (i < 0 || i >= self->ob_size) {
638 PyErr_SetString(PyExc_IndexError, "pop index out of range");
639 return NULL;
640 }
641 v = self->ob_item[i];
642 Py_INCREF(v);
643 if (list_ass_slice(self, i, i+1, (PyObject *)NULL) != 0) {
644 Py_DECREF(v);
645 return NULL;
646 }
647 return v;
648}
649
Guido van Rossum3f236de1996-12-10 23:55:39 +0000650/* New quicksort implementation for arrays of object pointers.
651 Thanks to discussions with Tim Peters. */
652
653/* CMPERROR is returned by our comparison function when an error
654 occurred. This is the largest negative integer (0x80000000 on a
655 32-bit system). */
Guido van Rossum19700b61997-03-05 00:45:43 +0000656#define CMPERROR ( (int) ((unsigned int)1 << (8*sizeof(int) - 1)) )
Guido van Rossum3f236de1996-12-10 23:55:39 +0000657
658/* Comparison function. Takes care of calling a user-supplied
659 comparison function (any callable Python object). Calls the
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000660 standard comparison function, PyObject_Compare(), if the user-
661 supplied function is NULL. */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000662
663static int
Fred Drakea2f55112000-07-09 15:16:51 +0000664docompare(PyObject *x, PyObject *y, PyObject *compare)
Guido van Rossum3f236de1996-12-10 23:55:39 +0000665{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000666 PyObject *args, *res;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000667 int i;
668
Guido van Rossumc8b6df91997-05-23 00:06:51 +0000669 if (compare == NULL) {
670 i = PyObject_Compare(x, y);
671 if (i && PyErr_Occurred())
672 i = CMPERROR;
673 return i;
674 }
Guido van Rossum3f236de1996-12-10 23:55:39 +0000675
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000676 args = Py_BuildValue("(OO)", x, y);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000677 if (args == NULL)
678 return CMPERROR;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000679 res = PyEval_CallObject(compare, args);
680 Py_DECREF(args);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000681 if (res == NULL)
682 return CMPERROR;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000683 if (!PyInt_Check(res)) {
684 Py_DECREF(res);
685 PyErr_SetString(PyExc_TypeError,
Guido van Rossum9bcd1d71999-04-19 17:44:39 +0000686 "comparison function must return int");
Guido van Rossum3f236de1996-12-10 23:55:39 +0000687 return CMPERROR;
688 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000689 i = PyInt_AsLong(res);
690 Py_DECREF(res);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000691 if (i < 0)
692 return -1;
693 if (i > 0)
694 return 1;
695 return 0;
696}
697
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000698/* MINSIZE is the smallest array that will get a full-blown samplesort
699 treatment; smaller arrays are sorted using binary insertion. It must
700 be at least 7 for the samplesort implementation to work. Binary
701 insertion does fewer compares, but can suffer O(N**2) data movement.
702 The more expensive compares, the larger MINSIZE should be. */
703#define MINSIZE 100
704
705/* MINPARTITIONSIZE is the smallest array slice samplesort will bother to
706 partition; smaller slices are passed to binarysort. It must be at
707 least 2, and no larger than MINSIZE. Setting it higher reduces the #
708 of compares slowly, but increases the amount of data movement quickly.
709 The value here was chosen assuming a compare costs ~25x more than
710 swapping a pair of memory-resident pointers -- but under that assumption,
711 changing the value by a few dozen more or less has aggregate effect
712 under 1%. So the value is crucial, but not touchy <wink>. */
713#define MINPARTITIONSIZE 40
714
715/* MAXMERGE is the largest number of elements we'll always merge into
716 a known-to-be sorted chunk via binary insertion, regardless of the
717 size of that chunk. Given a chunk of N sorted elements, and a group
718 of K unknowns, the largest K for which it's better to do insertion
719 (than a full-blown sort) is a complicated function of N and K mostly
720 involving the expected number of compares and data moves under each
721 approach, and the relative cost of those operations on a specific
722 architecure. The fixed value here is conservative, and should be a
723 clear win regardless of architecture or N. */
724#define MAXMERGE 15
Guido van Rossum3f236de1996-12-10 23:55:39 +0000725
Guido van Rossum3f236de1996-12-10 23:55:39 +0000726/* STACKSIZE is the size of our work stack. A rough estimate is that
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000727 this allows us to sort arrays of size N where
728 N / ln(N) = MINPARTITIONSIZE * 2**STACKSIZE, so 60 is more than enough
729 for arrays of size 2**64. Because we push the biggest partition
730 first, the worst case occurs when all subarrays are always partitioned
731 exactly in two. */
732#define STACKSIZE 60
Guido van Rossum3f236de1996-12-10 23:55:39 +0000733
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000734
735#define SETK(X,Y) if ((k = docompare(X,Y,compare))==CMPERROR) goto fail
736
737/* binarysort is the best method for sorting small arrays: it does
738 few compares, but can do data movement quadratic in the number of
739 elements.
Guido van Rossum42812581998-06-17 14:15:44 +0000740 [lo, hi) is a contiguous slice of a list, and is sorted via
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000741 binary insertion.
742 On entry, must have lo <= start <= hi, and that [lo, start) is already
743 sorted (pass start == lo if you don't know!).
744 If docompare complains (returns CMPERROR) return -1, else 0.
745 Even in case of error, the output slice will be some permutation of
746 the input (nothing is lost or duplicated).
747*/
Guido van Rossum3f236de1996-12-10 23:55:39 +0000748
749static int
Fred Drakea2f55112000-07-09 15:16:51 +0000750binarysort(PyObject **lo, PyObject **hi, PyObject **start, PyObject *compare)
751 /* compare -- comparison function object, or NULL for default */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000752{
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000753 /* assert lo <= start <= hi
754 assert [lo, start) is sorted */
755 register int k;
756 register PyObject **l, **p, **r;
757 register PyObject *pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000758
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000759 if (lo == start)
760 ++start;
761 for (; start < hi; ++start) {
762 /* set l to where *start belongs */
763 l = lo;
764 r = start;
Guido van Rossuma119c0d1998-05-29 17:56:32 +0000765 pivot = *r;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000766 do {
767 p = l + ((r - l) >> 1);
768 SETK(pivot, *p);
769 if (k < 0)
770 r = p;
771 else
772 l = p + 1;
773 } while (l < r);
774 /* Pivot should go at l -- slide over to make room.
775 Caution: using memmove is much slower under MSVC 5;
776 we're not usually moving many slots. */
777 for (p = start; p > l; --p)
778 *p = *(p-1);
779 *l = pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000780 }
Guido van Rossum3f236de1996-12-10 23:55:39 +0000781 return 0;
Guido van Rossuma119c0d1998-05-29 17:56:32 +0000782
783 fail:
784 return -1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000785}
786
787/* samplesortslice is the sorting workhorse.
Guido van Rossum42812581998-06-17 14:15:44 +0000788 [lo, hi) is a contiguous slice of a list, to be sorted in place.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000789 On entry, must have lo <= hi,
790 If docompare complains (returns CMPERROR) return -1, else 0.
791 Even in case of error, the output slice will be some permutation of
792 the input (nothing is lost or duplicated).
793
794 samplesort is basically quicksort on steroids: a power of 2 close
795 to n/ln(n) is computed, and that many elements (less 1) are picked at
796 random from the array and sorted. These 2**k - 1 elements are then
797 used as preselected pivots for an equal number of quicksort
798 partitioning steps, partitioning the slice into 2**k chunks each of
799 size about ln(n). These small final chunks are then usually handled
800 by binarysort. Note that when k=1, this is roughly the same as an
801 ordinary quicksort using a random pivot, and when k=2 this is roughly
802 a median-of-3 quicksort. From that view, using k ~= lg(n/ln(n)) makes
803 this a "median of n/ln(n)" quicksort. You can also view it as a kind
804 of bucket sort, where 2**k-1 bucket boundaries are picked dynamically.
805
806 The large number of samples makes a quadratic-time case almost
807 impossible, and asymptotically drives the average-case number of
808 compares from quicksort's 2 N ln N (or 12/7 N ln N for the median-of-
809 3 variant) down to N lg N.
810
811 We also play lots of low-level tricks to cut the number of compares.
812
813 Very obscure: To avoid using extra memory, the PPs are stored in the
814 array and shuffled around as partitioning proceeds. At the start of a
815 partitioning step, we'll have 2**m-1 (for some m) PPs in sorted order,
816 adjacent (either on the left or the right!) to a chunk of X elements
817 that are to be partitioned: P X or X P. In either case we need to
818 shuffle things *in place* so that the 2**(m-1) smaller PPs are on the
819 left, followed by the PP to be used for this step (that's the middle
820 of the PPs), followed by X, followed by the 2**(m-1) larger PPs:
821 P X or X P -> Psmall pivot X Plarge
822 and the order of the PPs must not be altered. It can take a while
823 to realize this isn't trivial! It can take even longer <wink> to
824 understand why the simple code below works, using only 2**(m-1) swaps.
825 The key is that the order of the X elements isn't necessarily
826 preserved: X can end up as some cyclic permutation of its original
827 order. That's OK, because X is unsorted anyway. If the order of X
828 had to be preserved too, the simplest method I know of using O(1)
829 scratch storage requires len(X) + 2**(m-1) swaps, spread over 2 passes.
830 Since len(X) is typically several times larger than 2**(m-1), that
831 would slow things down.
832*/
833
834struct SamplesortStackNode {
835 /* Represents a slice of the array, from (& including) lo up
836 to (but excluding) hi. "extra" additional & adjacent elements
837 are pre-selected pivots (PPs), spanning [lo-extra, lo) if
838 extra > 0, or [hi, hi-extra) if extra < 0. The PPs are
839 already sorted, but nothing is known about the other elements
840 in [lo, hi). |extra| is always one less than a power of 2.
841 When extra is 0, we're out of PPs, and the slice must be
842 sorted by some other means. */
843 PyObject **lo;
844 PyObject **hi;
845 int extra;
846};
847
848/* 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 +0000849 N / ln(N) as possible. So k ~= lg(N / ln(N)). Calling libm routines
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000850 is undesirable, so cutoff values are canned in the "cutoff" table
851 below: cutoff[i] is the smallest N such that k == CUTOFFBASE + i. */
852#define CUTOFFBASE 4
Guido van Rossum3aa23fd1999-01-14 19:01:53 +0000853static long cutoff[] = {
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000854 43, /* smallest N such that k == 4 */
855 106, /* etc */
856 250,
857 576,
858 1298,
859 2885,
860 6339,
861 13805,
862 29843,
863 64116,
864 137030,
865 291554,
866 617916,
867 1305130,
868 2748295,
869 5771662,
870 12091672,
871 25276798,
872 52734615,
873 109820537,
874 228324027,
875 473977813,
876 982548444, /* smallest N such that k == 26 */
877 2034159050 /* largest N that fits in signed 32-bit; k == 27 */
878};
879
880static int
Fred Drakea2f55112000-07-09 15:16:51 +0000881samplesortslice(PyObject **lo, PyObject **hi, PyObject *compare)
882 /* compare -- comparison function object, or NULL for default */
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000883{
884 register PyObject **l, **r;
885 register PyObject *tmp, *pivot;
886 register int k;
887 int n, extra, top, extraOnRight;
888 struct SamplesortStackNode stack[STACKSIZE];
889
890 /* assert lo <= hi */
891 n = hi - lo;
892
893 /* ----------------------------------------------------------
894 * Special cases
895 * --------------------------------------------------------*/
896 if (n < 2)
897 return 0;
898
899 /* Set r to the largest value such that [lo,r) is sorted.
900 This catches the already-sorted case, the all-the-same
901 case, and the appended-a-few-elements-to-a-sorted-list case.
902 If the array is unsorted, we're very likely to get out of
903 the loop fast, so the test is cheap if it doesn't pay off.
904 */
905 /* assert lo < hi */
906 for (r = lo+1; r < hi; ++r) {
907 SETK(*r, *(r-1));
908 if (k < 0)
909 break;
910 }
911 /* [lo,r) is sorted, [r,hi) unknown. Get out cheap if there are
912 few unknowns, or few elements in total. */
913 if (hi - r <= MAXMERGE || n < MINSIZE)
Guido van Rossum42812581998-06-17 14:15:44 +0000914 return binarysort(lo, hi, r, compare);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000915
916 /* Check for the array already being reverse-sorted. Typical
917 benchmark-driven silliness <wink>. */
918 /* assert lo < hi */
919 for (r = lo+1; r < hi; ++r) {
920 SETK(*(r-1), *r);
921 if (k < 0)
922 break;
923 }
924 if (hi - r <= MAXMERGE) {
925 /* Reverse the reversed prefix, then insert the tail */
926 PyObject **originalr = r;
927 l = lo;
928 do {
929 --r;
930 tmp = *l; *l = *r; *r = tmp;
931 ++l;
932 } while (l < r);
Guido van Rossum42812581998-06-17 14:15:44 +0000933 return binarysort(lo, hi, originalr, compare);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000934 }
935
936 /* ----------------------------------------------------------
937 * Normal case setup: a large array without obvious pattern.
938 * --------------------------------------------------------*/
939
940 /* extra := a power of 2 ~= n/ln(n), less 1.
941 First find the smallest extra s.t. n < cutoff[extra] */
942 for (extra = 0;
943 extra < sizeof(cutoff) / sizeof(cutoff[0]);
944 ++extra) {
945 if (n < cutoff[extra])
946 break;
947 /* note that if we fall out of the loop, the value of
948 extra still makes *sense*, but may be smaller than
949 we would like (but the array has more than ~= 2**31
950 elements in this case!) */
951 }
952 /* Now k == extra - 1 + CUTOFFBASE. The smallest value k can
953 have is CUTOFFBASE-1, so
954 assert MINSIZE >= 2**(CUTOFFBASE-1) - 1 */
955 extra = (1 << (extra - 1 + CUTOFFBASE)) - 1;
956 /* assert extra > 0 and n >= extra */
957
958 /* Swap that many values to the start of the array. The
959 selection of elements is pseudo-random, but the same on
960 every run (this is intentional! timing algorithm changes is
961 a pain if timing varies across runs). */
962 {
963 unsigned int seed = n / extra; /* arbitrary */
964 unsigned int i;
965 for (i = 0; i < (unsigned)extra; ++i) {
966 /* j := random int in [i, n) */
967 unsigned int j;
968 seed = seed * 69069 + 7;
969 j = i + seed % (n - i);
970 tmp = lo[i]; lo[i] = lo[j]; lo[j] = tmp;
971 }
972 }
973
974 /* Recursively sort the preselected pivots. */
Guido van Rossum42812581998-06-17 14:15:44 +0000975 if (samplesortslice(lo, lo + extra, compare) < 0)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000976 goto fail;
977
978 top = 0; /* index of available stack slot */
979 lo += extra; /* point to first unknown */
980 extraOnRight = 0; /* the PPs are at the left end */
981
982 /* ----------------------------------------------------------
983 * Partition [lo, hi), and repeat until out of work.
984 * --------------------------------------------------------*/
985 for (;;) {
986 /* assert lo <= hi, so n >= 0 */
987 n = hi - lo;
988
989 /* We may not want, or may not be able, to partition:
990 If n is small, it's quicker to insert.
991 If extra is 0, we're out of pivots, and *must* use
992 another method.
993 */
994 if (n < MINPARTITIONSIZE || extra == 0) {
995 if (n >= MINSIZE) {
996 /* assert extra == 0
997 This is rare, since the average size
998 of a final block is only about
999 ln(original n). */
Guido van Rossum42812581998-06-17 14:15:44 +00001000 if (samplesortslice(lo, hi, compare) < 0)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001001 goto fail;
1002 }
1003 else {
1004 /* Binary insertion should be quicker,
1005 and we can take advantage of the PPs
1006 already being sorted. */
1007 if (extraOnRight && extra) {
1008 /* swap the PPs to the left end */
1009 k = extra;
1010 do {
1011 tmp = *lo;
1012 *lo = *hi;
1013 *hi = tmp;
1014 ++lo; ++hi;
1015 } while (--k);
1016 }
1017 if (binarysort(lo - extra, hi, lo,
Guido van Rossum42812581998-06-17 14:15:44 +00001018 compare) < 0)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001019 goto fail;
1020 }
1021
1022 /* Find another slice to work on. */
1023 if (--top < 0)
1024 break; /* no more -- done! */
1025 lo = stack[top].lo;
1026 hi = stack[top].hi;
1027 extra = stack[top].extra;
1028 extraOnRight = 0;
1029 if (extra < 0) {
1030 extraOnRight = 1;
1031 extra = -extra;
1032 }
1033 continue;
1034 }
1035
1036 /* Pretend the PPs are indexed 0, 1, ..., extra-1.
1037 Then our preselected pivot is at (extra-1)/2, and we
1038 want to move the PPs before that to the left end of
1039 the slice, and the PPs after that to the right end.
1040 The following section changes extra, lo, hi, and the
1041 slice such that:
1042 [lo-extra, lo) contains the smaller PPs.
1043 *lo == our PP.
1044 (lo, hi) contains the unknown elements.
1045 [hi, hi+extra) contains the larger PPs.
1046 */
1047 k = extra >>= 1; /* num PPs to move */
1048 if (extraOnRight) {
1049 /* Swap the smaller PPs to the left end.
1050 Note that this loop actually moves k+1 items:
1051 the last is our PP */
1052 do {
1053 tmp = *lo; *lo = *hi; *hi = tmp;
1054 ++lo; ++hi;
1055 } while (k--);
1056 }
1057 else {
1058 /* Swap the larger PPs to the right end. */
1059 while (k--) {
1060 --lo; --hi;
1061 tmp = *lo; *lo = *hi; *hi = tmp;
1062 }
1063 }
1064 --lo; /* *lo is now our PP */
1065 pivot = *lo;
1066
1067 /* Now an almost-ordinary quicksort partition step.
1068 Note that most of the time is spent here!
1069 Only odd thing is that we partition into < and >=,
1070 instead of the usual <= and >=. This helps when
1071 there are lots of duplicates of different values,
1072 because it eventually tends to make subfiles
1073 "pure" (all duplicates), and we special-case for
1074 duplicates later. */
1075 l = lo + 1;
1076 r = hi - 1;
1077 /* assert lo < l < r < hi (small n weeded out above) */
1078
1079 do {
1080 /* slide l right, looking for key >= pivot */
1081 do {
1082 SETK(*l, pivot);
1083 if (k < 0)
1084 ++l;
1085 else
1086 break;
1087 } while (l < r);
1088
1089 /* slide r left, looking for key < pivot */
1090 while (l < r) {
Guido van Rossum42812581998-06-17 14:15:44 +00001091 register PyObject *rval = *r--;
1092 SETK(rval, pivot);
1093 if (k < 0) {
1094 /* swap and advance */
1095 r[1] = *l;
1096 *l++ = rval;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001097 break;
Guido van Rossum42812581998-06-17 14:15:44 +00001098 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001099 }
1100
1101 } while (l < r);
1102
1103 /* assert lo < r <= l < hi
1104 assert r == l or r+1 == l
1105 everything to the left of l is < pivot, and
1106 everything to the right of r is >= pivot */
1107
1108 if (l == r) {
1109 SETK(*r, pivot);
1110 if (k < 0)
1111 ++l;
1112 else
1113 --r;
1114 }
1115 /* assert lo <= r and r+1 == l and l <= hi
1116 assert r == lo or a[r] < pivot
1117 assert a[lo] is pivot
1118 assert l == hi or a[l] >= pivot
1119 Swap the pivot into "the middle", so we can henceforth
1120 ignore it.
1121 */
1122 *lo = *r;
1123 *r = pivot;
1124
1125 /* The following is true now, & will be preserved:
1126 All in [lo,r) are < pivot
1127 All in [r,l) == pivot (& so can be ignored)
1128 All in [l,hi) are >= pivot */
1129
1130 /* Check for duplicates of the pivot. One compare is
1131 wasted if there are no duplicates, but can win big
1132 when there are.
1133 Tricky: we're sticking to "<" compares, so deduce
1134 equality indirectly. We know pivot <= *l, so they're
1135 equal iff not pivot < *l.
1136 */
1137 while (l < hi) {
1138 /* pivot <= *l known */
1139 SETK(pivot, *l);
1140 if (k < 0)
1141 break;
1142 else
1143 /* <= and not < implies == */
1144 ++l;
1145 }
1146
1147 /* assert lo <= r < l <= hi
1148 Partitions are [lo, r) and [l, hi) */
1149
1150 /* push fattest first; remember we still have extra PPs
1151 to the left of the left chunk and to the right of
1152 the right chunk! */
1153 /* assert top < STACKSIZE */
1154 if (r - lo <= hi - l) {
1155 /* second is bigger */
1156 stack[top].lo = l;
1157 stack[top].hi = hi;
1158 stack[top].extra = -extra;
1159 hi = r;
1160 extraOnRight = 0;
1161 }
1162 else {
1163 /* first is bigger */
1164 stack[top].lo = lo;
1165 stack[top].hi = r;
1166 stack[top].extra = extra;
1167 lo = l;
1168 extraOnRight = 1;
1169 }
1170 ++top;
1171
1172 } /* end of partitioning loop */
1173
1174 return 0;
1175
1176 fail:
1177 return -1;
1178}
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001179
1180#undef SETK
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001181
1182staticforward PyTypeObject immutable_list_type;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001183
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001184static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00001185listsort(PyListObject *self, PyObject *args)
Guido van Rossum3f236de1996-12-10 23:55:39 +00001186{
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001187 int err;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001188 PyObject *compare = NULL;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001189
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001190 if (args != NULL) {
Guido van Rossumc00a9382000-02-24 21:48:29 +00001191 if (!PyArg_ParseTuple(args, "|O:sort", &compare))
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001192 return NULL;
1193 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001194 self->ob_type = &immutable_list_type;
1195 err = samplesortslice(self->ob_item,
1196 self->ob_item + self->ob_size,
Guido van Rossum42812581998-06-17 14:15:44 +00001197 compare);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001198 self->ob_type = &PyList_Type;
1199 if (err < 0)
Guido van Rossum3f236de1996-12-10 23:55:39 +00001200 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001201 Py_INCREF(Py_None);
1202 return Py_None;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001203}
1204
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001205int
Fred Drakea2f55112000-07-09 15:16:51 +00001206PyList_Sort(PyObject *v)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001207{
1208 if (v == NULL || !PyList_Check(v)) {
1209 PyErr_BadInternalCall();
1210 return -1;
1211 }
1212 v = listsort((PyListObject *)v, (PyObject *)NULL);
1213 if (v == NULL)
1214 return -1;
1215 Py_DECREF(v);
1216 return 0;
1217}
1218
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001219static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00001220listreverse(PyListObject *self, PyObject *args)
Guido van Rossumed98d481991-03-06 13:07:53 +00001221{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001222 register PyObject **p, **q;
1223 register PyObject *tmp;
Guido van Rossumed98d481991-03-06 13:07:53 +00001224
Guido van Rossumc00a9382000-02-24 21:48:29 +00001225 if (!PyArg_ParseTuple(args, ":reverse"))
Guido van Rossumed98d481991-03-06 13:07:53 +00001226 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00001227
1228 if (self->ob_size > 1) {
1229 for (p = self->ob_item, q = self->ob_item + self->ob_size - 1;
1230 p < q; p++, q--) {
1231 tmp = *p;
1232 *p = *q;
1233 *q = tmp;
1234 }
1235 }
1236
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001237 Py_INCREF(Py_None);
1238 return Py_None;
Guido van Rossumed98d481991-03-06 13:07:53 +00001239}
1240
Guido van Rossum84c76f51990-10-30 13:32:20 +00001241int
Fred Drakea2f55112000-07-09 15:16:51 +00001242PyList_Reverse(PyObject *v)
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00001243{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001244 if (v == NULL || !PyList_Check(v)) {
1245 PyErr_BadInternalCall();
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00001246 return -1;
1247 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001248 v = listreverse((PyListObject *)v, (PyObject *)NULL);
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00001249 if (v == NULL)
1250 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001251 Py_DECREF(v);
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00001252 return 0;
1253}
1254
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001255PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00001256PyList_AsTuple(PyObject *v)
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00001257{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001258 PyObject *w;
1259 PyObject **p;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00001260 int n;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001261 if (v == NULL || !PyList_Check(v)) {
1262 PyErr_BadInternalCall();
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00001263 return NULL;
1264 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001265 n = ((PyListObject *)v)->ob_size;
1266 w = PyTuple_New(n);
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00001267 if (w == NULL)
1268 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001269 p = ((PyTupleObject *)w)->ob_item;
Thomas Wouters334fb892000-07-25 12:56:38 +00001270 memcpy((void *)p,
1271 (void *)((PyListObject *)v)->ob_item,
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001272 n*sizeof(PyObject *));
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00001273 while (--n >= 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001274 Py_INCREF(*p);
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00001275 p++;
1276 }
1277 return w;
1278}
1279
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001280static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00001281listindex(PyListObject *self, PyObject *args)
Guido van Rossumed98d481991-03-06 13:07:53 +00001282{
1283 int i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001284 PyObject *v;
1285
Guido van Rossumef93b872000-03-13 15:41:59 +00001286 if (!PyArg_ParseTuple_Compat1(args, "O:index", &v))
Guido van Rossumed98d481991-03-06 13:07:53 +00001287 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00001288 for (i = 0; i < self->ob_size; i++) {
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001289 if (PyObject_Compare(self->ob_item[i], v) == 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001290 return PyInt_FromLong((long)i);
Guido van Rossumc8b6df91997-05-23 00:06:51 +00001291 if (PyErr_Occurred())
1292 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00001293 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001294 PyErr_SetString(PyExc_ValueError, "list.index(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00001295 return NULL;
1296}
1297
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001298static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00001299listcount(PyListObject *self, PyObject *args)
Guido van Rossume6f7d181991-10-20 20:20:40 +00001300{
1301 int count = 0;
1302 int i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001303 PyObject *v;
1304
Guido van Rossumef93b872000-03-13 15:41:59 +00001305 if (!PyArg_ParseTuple_Compat1(args, "O:count", &v))
Guido van Rossume6f7d181991-10-20 20:20:40 +00001306 return NULL;
Guido van Rossume6f7d181991-10-20 20:20:40 +00001307 for (i = 0; i < self->ob_size; i++) {
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001308 if (PyObject_Compare(self->ob_item[i], v) == 0)
Guido van Rossume6f7d181991-10-20 20:20:40 +00001309 count++;
Guido van Rossumc8b6df91997-05-23 00:06:51 +00001310 if (PyErr_Occurred())
1311 return NULL;
Guido van Rossume6f7d181991-10-20 20:20:40 +00001312 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001313 return PyInt_FromLong((long)count);
Guido van Rossume6f7d181991-10-20 20:20:40 +00001314}
1315
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001316static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00001317listremove(PyListObject *self, PyObject *args)
Guido van Rossumed98d481991-03-06 13:07:53 +00001318{
1319 int i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001320 PyObject *v;
1321
Guido van Rossumef93b872000-03-13 15:41:59 +00001322 if (!PyArg_ParseTuple_Compat1(args, "O:remove", &v))
Guido van Rossumed98d481991-03-06 13:07:53 +00001323 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00001324 for (i = 0; i < self->ob_size; i++) {
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001325 if (PyObject_Compare(self->ob_item[i], v) == 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001326 if (list_ass_slice(self, i, i+1,
1327 (PyObject *)NULL) != 0)
Guido van Rossumed98d481991-03-06 13:07:53 +00001328 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001329 Py_INCREF(Py_None);
1330 return Py_None;
Guido van Rossumed98d481991-03-06 13:07:53 +00001331 }
Guido van Rossumc8b6df91997-05-23 00:06:51 +00001332 if (PyErr_Occurred())
1333 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00001334 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001335 PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00001336 return NULL;
1337}
1338
Jeremy Hylton8caad492000-06-23 14:18:11 +00001339static int
1340list_traverse(PyListObject *o, visitproc visit, void *arg)
1341{
1342 int i, err;
1343 PyObject *x;
1344
1345 for (i = o->ob_size; --i >= 0; ) {
1346 x = o->ob_item[i];
1347 if (x != NULL) {
1348 err = visit(x, arg);
1349 if (err)
1350 return err;
1351 }
1352 }
1353 return 0;
1354}
1355
1356static int
1357list_clear(PyListObject *lp)
1358{
1359 (void) PyList_SetSlice((PyObject *)lp, 0, lp->ob_size, 0);
1360 return 0;
1361}
1362
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +00001363static char append_doc[] =
1364"L.append(object) -- append object to end";
Barry Warsawdedf6d61998-10-09 16:37:25 +00001365static char extend_doc[] =
1366"L.extend(list) -- extend list by appending list elements";
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +00001367static char insert_doc[] =
1368"L.insert(index, object) -- insert object before index";
1369static char pop_doc[] =
1370"L.pop([index]) -> item -- remove and return item at index (default last)";
1371static char remove_doc[] =
1372"L.remove(value) -- remove first occurrence of value";
1373static char index_doc[] =
1374"L.index(value) -> integer -- return index of first occurrence of value";
1375static char count_doc[] =
1376"L.count(value) -> integer -- return number of occurrences of value";
1377static char reverse_doc[] =
1378"L.reverse() -- reverse *IN PLACE*";
1379static char sort_doc[] =
1380"L.sort([cmpfunc]) -- sort *IN PLACE*; if given, cmpfunc(x, y) -> -1, 0, 1";
1381
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001382static PyMethodDef list_methods[] = {
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001383 {"append", (PyCFunction)listappend, 1, append_doc},
1384 {"insert", (PyCFunction)listinsert, 1, insert_doc},
Barry Warsawdedf6d61998-10-09 16:37:25 +00001385 {"extend", (PyCFunction)listextend, 1, extend_doc},
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +00001386 {"pop", (PyCFunction)listpop, 1, pop_doc},
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001387 {"remove", (PyCFunction)listremove, 1, remove_doc},
1388 {"index", (PyCFunction)listindex, 1, index_doc},
1389 {"count", (PyCFunction)listcount, 1, count_doc},
1390 {"reverse", (PyCFunction)listreverse, 1, reverse_doc},
1391 {"sort", (PyCFunction)listsort, 1, sort_doc},
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001392 {NULL, NULL} /* sentinel */
1393};
1394
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001395static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00001396list_getattr(PyListObject *f, char *name)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001397{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001398 return Py_FindMethod(list_methods, (PyObject *)f, name);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001399}
1400
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001401static PySequenceMethods list_as_sequence = {
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00001402 (inquiry)list_length, /*sq_length*/
1403 (binaryfunc)list_concat, /*sq_concat*/
1404 (intargfunc)list_repeat, /*sq_repeat*/
1405 (intargfunc)list_item, /*sq_item*/
1406 (intintargfunc)list_slice, /*sq_slice*/
1407 (intobjargproc)list_ass_item, /*sq_ass_item*/
1408 (intintobjargproc)list_ass_slice, /*sq_ass_slice*/
Jeremy Hylton37b1a262000-04-27 21:41:03 +00001409 (objobjproc)list_contains, /*sq_contains*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001410};
1411
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001412PyTypeObject PyList_Type = {
1413 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001414 0,
1415 "list",
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001416 sizeof(PyListObject) + PyGC_HEAD_SIZE,
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001417 0,
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00001418 (destructor)list_dealloc, /*tp_dealloc*/
1419 (printfunc)list_print, /*tp_print*/
1420 (getattrfunc)list_getattr, /*tp_getattr*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001421 0, /*tp_setattr*/
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00001422 (cmpfunc)list_compare, /*tp_compare*/
1423 (reprfunc)list_repr, /*tp_repr*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001424 0, /*tp_as_number*/
1425 &list_as_sequence, /*tp_as_sequence*/
1426 0, /*tp_as_mapping*/
Fred Drake56780252000-06-15 14:50:20 +00001427 0, /*tp_hash*/
1428 0, /*tp_call*/
1429 0, /*tp_str*/
1430 0, /*tp_getattro*/
1431 0, /*tp_setattro*/
1432 0, /*tp_as_buffer*/
Jeremy Hyltond08b4c42000-06-23 19:37:02 +00001433 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_GC, /*tp_flags*/
Jeremy Hylton8caad492000-06-23 14:18:11 +00001434 0, /* tp_doc */
1435 (traverseproc)list_traverse, /* tp_traverse */
1436 (inquiry)list_clear, /* tp_clear */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001437};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001438
1439
1440/* During a sort, we really can't have anyone modifying the list; it could
1441 cause core dumps. Thus, we substitute a dummy type that raises an
1442 explanatory exception when a modifying operation is used. Caveat:
1443 comparisons may behave differently; but I guess it's a bad idea anyway to
1444 compare a list that's being sorted... */
1445
1446static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00001447immutable_list_op(void)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001448{
1449 PyErr_SetString(PyExc_TypeError,
1450 "a list cannot be modified while it is being sorted");
1451 return NULL;
1452}
1453
1454static PyMethodDef immutable_list_methods[] = {
1455 {"append", (PyCFunction)immutable_list_op},
1456 {"insert", (PyCFunction)immutable_list_op},
1457 {"remove", (PyCFunction)immutable_list_op},
1458 {"index", (PyCFunction)listindex},
1459 {"count", (PyCFunction)listcount},
1460 {"reverse", (PyCFunction)immutable_list_op},
1461 {"sort", (PyCFunction)immutable_list_op},
1462 {NULL, NULL} /* sentinel */
1463};
1464
1465static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00001466immutable_list_getattr(PyListObject *f, char *name)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001467{
1468 return Py_FindMethod(immutable_list_methods, (PyObject *)f, name);
1469}
1470
1471static int
Fred Drakea2f55112000-07-09 15:16:51 +00001472immutable_list_ass(void)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001473{
1474 immutable_list_op();
1475 return -1;
1476}
1477
1478static PySequenceMethods immutable_list_as_sequence = {
1479 (inquiry)list_length, /*sq_length*/
1480 (binaryfunc)list_concat, /*sq_concat*/
1481 (intargfunc)list_repeat, /*sq_repeat*/
1482 (intargfunc)list_item, /*sq_item*/
1483 (intintargfunc)list_slice, /*sq_slice*/
1484 (intobjargproc)immutable_list_ass, /*sq_ass_item*/
1485 (intintobjargproc)immutable_list_ass, /*sq_ass_slice*/
Fred Drake56780252000-06-15 14:50:20 +00001486 (objobjproc)list_contains, /*sq_contains*/
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001487};
1488
1489static PyTypeObject immutable_list_type = {
1490 PyObject_HEAD_INIT(&PyType_Type)
1491 0,
1492 "list (immutable, during sort)",
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001493 sizeof(PyListObject) + PyGC_HEAD_SIZE,
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001494 0,
1495 0, /*tp_dealloc*/ /* Cannot happen */
1496 (printfunc)list_print, /*tp_print*/
1497 (getattrfunc)immutable_list_getattr, /*tp_getattr*/
1498 0, /*tp_setattr*/
1499 0, /*tp_compare*/ /* Won't be called */
1500 (reprfunc)list_repr, /*tp_repr*/
1501 0, /*tp_as_number*/
1502 &immutable_list_as_sequence, /*tp_as_sequence*/
1503 0, /*tp_as_mapping*/
Fred Drake56780252000-06-15 14:50:20 +00001504 0, /*tp_hash*/
1505 0, /*tp_call*/
1506 0, /*tp_str*/
1507 0, /*tp_getattro*/
1508 0, /*tp_setattro*/
1509 0, /*tp_as_buffer*/
Jeremy Hyltond08b4c42000-06-23 19:37:02 +00001510 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_GC, /*tp_flags*/
Jeremy Hylton8caad492000-06-23 14:18:11 +00001511 0, /* tp_doc */
1512 (traverseproc)list_traverse, /* tp_traverse */
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001513};