listobject.c 51.6 KB
Newer Older
Guido van Rossum's avatar
Guido van Rossum committed
1 2
/* List object implementation */

3 4
#include "Python.h"

5 6 7 8 9
#ifdef STDC_HEADERS
#include <stddef.h>
#else
#include <sys/types.h>		/* For size_t */
#endif
Guido van Rossum's avatar
Guido van Rossum committed
10

11
static int
Fred Drake's avatar
Fred Drake committed
12
roundupsize(int n)
13
{
14 15 16
	unsigned int nbits = 0;
	unsigned int n2 = (unsigned int)n >> 5;

Tim Peters's avatar
Tim Peters committed
17
	/* Round up:
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
	 * If n <       256, to a multiple of        8.
	 * If n <      2048, to a multiple of       64.
	 * If n <     16384, to a multiple of      512.
	 * If n <    131072, to a multiple of     4096.
	 * If n <   1048576, to a multiple of    32768.
	 * If n <   8388608, to a multiple of   262144.
	 * If n <  67108864, to a multiple of  2097152.
	 * If n < 536870912, to a multiple of 16777216.
	 * ...
	 * If n < 2**(5+3*i), to a multiple of 2**(3*i).
	 *
	 * This over-allocates proportional to the list size, making room
	 * for additional growth.  The over-allocation is mild, but is
	 * enough to give linear-time amortized behavior over a long
	 * sequence of appends() in the presence of a poorly-performing
	 * system realloc() (which is a reality, e.g., across all flavors
	 * of Windows, with Win9x behavior being particularly bad -- and
	 * we've still got address space fragmentation problems on Win9x
	 * even with this scheme, although it requires much longer lists to
	 * provoke them than it used to).
	 */
	do {
		n2 >>= 3;
		nbits += 3;
	} while (n2);
	return ((n >> nbits) + 1) << nbits;
 }
45

46 47 48 49 50 51 52 53
#define NRESIZE(var, type, nitems)				\
do {								\
	size_t _new_size = roundupsize(nitems);			\
	if (_new_size <= ((~(size_t)0) / sizeof(type)))		\
		PyMem_RESIZE(var, type, _new_size);		\
	else							\
		var = NULL;					\
} while (0)
54

55
PyObject *
Fred Drake's avatar
Fred Drake committed
56
PyList_New(int size)
Guido van Rossum's avatar
Guido van Rossum committed
57
{
58
	PyListObject *op;
59
	size_t nbytes;
Guido van Rossum's avatar
Guido van Rossum committed
60
	if (size < 0) {
61
		PyErr_BadInternalCall();
Guido van Rossum's avatar
Guido van Rossum committed
62 63
		return NULL;
	}
64
	nbytes = size * sizeof(PyObject *);
65
	/* Check for overflow */
66 67
	if (nbytes / sizeof(PyObject *) != (size_t)size) {
		return PyErr_NoMemory();
68
	}
Neil Schemenauer's avatar
Neil Schemenauer committed
69
	op = PyObject_GC_New(PyListObject, &PyList_Type);
Guido van Rossum's avatar
Guido van Rossum committed
70
	if (op == NULL) {
Neil Schemenauer's avatar
Neil Schemenauer committed
71
		return NULL;
Guido van Rossum's avatar
Guido van Rossum committed
72 73 74 75 76
	}
	if (size <= 0) {
		op->ob_item = NULL;
	}
	else {
77
		op->ob_item = (PyObject **) PyMem_MALLOC(nbytes);
Guido van Rossum's avatar
Guido van Rossum committed
78
		if (op->ob_item == NULL) {
79
			return PyErr_NoMemory();
Guido van Rossum's avatar
Guido van Rossum committed
80
		}
Neal Norwitz's avatar
Neal Norwitz committed
81
		memset(op->ob_item, 0, sizeof(*op->ob_item) * size);
Guido van Rossum's avatar
Guido van Rossum committed
82
	}
Neil Schemenauer's avatar
Neil Schemenauer committed
83 84
	op->ob_size = size;
	_PyObject_GC_TRACK(op);
85
	return (PyObject *) op;
Guido van Rossum's avatar
Guido van Rossum committed
86 87 88
}

int
Fred Drake's avatar
Fred Drake committed
89
PyList_Size(PyObject *op)
Guido van Rossum's avatar
Guido van Rossum committed
90
{
91 92
	if (!PyList_Check(op)) {
		PyErr_BadInternalCall();
Guido van Rossum's avatar
Guido van Rossum committed
93 94 95
		return -1;
	}
	else
96
		return ((PyListObject *)op) -> ob_size;
Guido van Rossum's avatar
Guido van Rossum committed
97 98
}

99
static PyObject *indexerr;
100

101
PyObject *
Fred Drake's avatar
Fred Drake committed
102
PyList_GetItem(PyObject *op, int i)
Guido van Rossum's avatar
Guido van Rossum committed
103
{
104 105
	if (!PyList_Check(op)) {
		PyErr_BadInternalCall();
Guido van Rossum's avatar
Guido van Rossum committed
106 107
		return NULL;
	}
108
	if (i < 0 || i >= ((PyListObject *)op) -> ob_size) {
109
		if (indexerr == NULL)
110 111 112
			indexerr = PyString_FromString(
				"list index out of range");
		PyErr_SetObject(PyExc_IndexError, indexerr);
Guido van Rossum's avatar
Guido van Rossum committed
113 114
		return NULL;
	}
115
	return ((PyListObject *)op) -> ob_item[i];
Guido van Rossum's avatar
Guido van Rossum committed
116 117 118
}

int
Fred Drake's avatar
Fred Drake committed
119 120
PyList_SetItem(register PyObject *op, register int i,
               register PyObject *newitem)
Guido van Rossum's avatar
Guido van Rossum committed
121
{
122 123 124 125 126
	register PyObject *olditem;
	register PyObject **p;
	if (!PyList_Check(op)) {
		Py_XDECREF(newitem);
		PyErr_BadInternalCall();
Guido van Rossum's avatar
Guido van Rossum committed
127
		return -1;
Guido van Rossum's avatar
Guido van Rossum committed
128
	}
129 130 131 132
	if (i < 0 || i >= ((PyListObject *)op) -> ob_size) {
		Py_XDECREF(newitem);
		PyErr_SetString(PyExc_IndexError,
				"list assignment index out of range");
Guido van Rossum's avatar
Guido van Rossum committed
133
		return -1;
Guido van Rossum's avatar
Guido van Rossum committed
134
	}
135
	p = ((PyListObject *)op) -> ob_item + i;
136 137
	olditem = *p;
	*p = newitem;
138
	Py_XDECREF(olditem);
Guido van Rossum's avatar
Guido van Rossum committed
139 140 141 142
	return 0;
}

static int
Fred Drake's avatar
Fred Drake committed
143
ins1(PyListObject *self, int where, PyObject *v)
Guido van Rossum's avatar
Guido van Rossum committed
144 145
{
	int i;
146
	PyObject **items;
Guido van Rossum's avatar
Guido van Rossum committed
147
	if (v == NULL) {
148
		PyErr_BadInternalCall();
Guido van Rossum's avatar
Guido van Rossum committed
149 150
		return -1;
	}
151 152 153 154 155
	if (self->ob_size == INT_MAX) {
		PyErr_SetString(PyExc_OverflowError,
			"cannot add more objects to list");
		return -1;
	}
Guido van Rossum's avatar
Guido van Rossum committed
156
	items = self->ob_item;
157
	NRESIZE(items, PyObject *, self->ob_size+1);
Guido van Rossum's avatar
Guido van Rossum committed
158
	if (items == NULL) {
159
		PyErr_NoMemory();
Guido van Rossum's avatar
Guido van Rossum committed
160 161
		return -1;
	}
Guido van Rossum's avatar
Guido van Rossum committed
162 163 164 165 166 167
	if (where < 0)
		where = 0;
	if (where > self->ob_size)
		where = self->ob_size;
	for (i = self->ob_size; --i >= where; )
		items[i+1] = items[i];
168
	Py_INCREF(v);
Guido van Rossum's avatar
Guido van Rossum committed
169 170 171 172 173 174 175
	items[where] = v;
	self->ob_item = items;
	self->ob_size++;
	return 0;
}

int
Fred Drake's avatar
Fred Drake committed
176
PyList_Insert(PyObject *op, int where, PyObject *newitem)
Guido van Rossum's avatar
Guido van Rossum committed
177
{
178 179
	if (!PyList_Check(op)) {
		PyErr_BadInternalCall();
Guido van Rossum's avatar
Guido van Rossum committed
180 181
		return -1;
	}
182
	return ins1((PyListObject *)op, where, newitem);
Guido van Rossum's avatar
Guido van Rossum committed
183 184 185
}

int
Fred Drake's avatar
Fred Drake committed
186
PyList_Append(PyObject *op, PyObject *newitem)
Guido van Rossum's avatar
Guido van Rossum committed
187
{
188 189
	if (!PyList_Check(op)) {
		PyErr_BadInternalCall();
Guido van Rossum's avatar
Guido van Rossum committed
190 191
		return -1;
	}
192 193
	return ins1((PyListObject *)op,
		(int) ((PyListObject *)op)->ob_size, newitem);
Guido van Rossum's avatar
Guido van Rossum committed
194 195 196 197 198
}

/* Methods */

static void
Fred Drake's avatar
Fred Drake committed
199
list_dealloc(PyListObject *op)
Guido van Rossum's avatar
Guido van Rossum committed
200 201
{
	int i;
202
	PyObject_GC_UnTrack(op);
203
	Py_TRASHCAN_SAFE_BEGIN(op)
204
	if (op->ob_item != NULL) {
205 206 207 208 209 210
		/* Do it backwards, for Christian Tismer.
		   There's a simple test case where somehow this reduces
		   thrashing when a *very* large list is created and
		   immediately deleted. */
		i = op->ob_size;
		while (--i >= 0) {
211
			Py_XDECREF(op->ob_item[i]);
212
		}
213
		PyMem_FREE(op->ob_item);
214
	}
215
	op->ob_type->tp_free((PyObject *)op);
216
	Py_TRASHCAN_SAFE_END(op)
Guido van Rossum's avatar
Guido van Rossum committed
217 218
}

219
static int
Fred Drake's avatar
Fred Drake committed
220
list_print(PyListObject *op, FILE *fp, int flags)
Guido van Rossum's avatar
Guido van Rossum committed
221 222
{
	int i;
223 224 225 226 227 228 229 230

	i = Py_ReprEnter((PyObject*)op);
	if (i != 0) {
		if (i < 0)
			return i;
		fprintf(fp, "[...]");
		return 0;
	}
Guido van Rossum's avatar
Guido van Rossum committed
231
	fprintf(fp, "[");
232 233
	for (i = 0; i < op->ob_size; i++) {
		if (i > 0)
Guido van Rossum's avatar
Guido van Rossum committed
234
			fprintf(fp, ", ");
235 236
		if (PyObject_Print(op->ob_item[i], fp, 0) != 0) {
			Py_ReprLeave((PyObject *)op);
237
			return -1;
238
		}
Guido van Rossum's avatar
Guido van Rossum committed
239 240
	}
	fprintf(fp, "]");
241
	Py_ReprLeave((PyObject *)op);
242
	return 0;
Guido van Rossum's avatar
Guido van Rossum committed
243 244
}

245
static PyObject *
Fred Drake's avatar
Fred Drake committed
246
list_repr(PyListObject *v)
Guido van Rossum's avatar
Guido van Rossum committed
247 248
{
	int i;
249 250
	PyObject *s, *temp;
	PyObject *pieces = NULL, *result = NULL;
251 252 253

	i = Py_ReprEnter((PyObject*)v);
	if (i != 0) {
254
		return i > 0 ? PyString_FromString("[...]") : NULL;
255
	}
256 257 258 259

	if (v->ob_size == 0) {
		result = PyString_FromString("[]");
		goto Done;
Guido van Rossum's avatar
Guido van Rossum committed
260
	}
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303

	pieces = PyList_New(0);
	if (pieces == NULL)
		goto Done;

	/* Do repr() on each element.  Note that this may mutate the list,
	   so must refetch the list size on each iteration. */
	for (i = 0; i < v->ob_size; ++i) {
		int status;
		s = PyObject_Repr(v->ob_item[i]);
		if (s == NULL)
			goto Done;
		status = PyList_Append(pieces, s);
		Py_DECREF(s);  /* append created a new ref */
		if (status < 0)
			goto Done;
	}

	/* Add "[]" decorations to the first and last items. */
	assert(PyList_GET_SIZE(pieces) > 0);
	s = PyString_FromString("[");
	if (s == NULL)
		goto Done;
	temp = PyList_GET_ITEM(pieces, 0);
	PyString_ConcatAndDel(&s, temp);
	PyList_SET_ITEM(pieces, 0, s);
	if (s == NULL)
		goto Done;

	s = PyString_FromString("]");
	if (s == NULL)
		goto Done;
	temp = PyList_GET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1);
	PyString_ConcatAndDel(&temp, s);
	PyList_SET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1, temp);
	if (temp == NULL)
		goto Done;

	/* Paste them all together with ", " between. */
	s = PyString_FromString(", ");
	if (s == NULL)
		goto Done;
	result = _PyString_Join(s, pieces);
Tim Peters's avatar
Tim Peters committed
304
	Py_DECREF(s);
305 306 307

Done:
	Py_XDECREF(pieces);
308
	Py_ReprLeave((PyObject *)v);
309
	return result;
Guido van Rossum's avatar
Guido van Rossum committed
310 311 312
}

static int
Fred Drake's avatar
Fred Drake committed
313
list_length(PyListObject *a)
Guido van Rossum's avatar
Guido van Rossum committed
314 315 316 317
{
	return a->ob_size;
}

318 319 320


static int
Fred Drake's avatar
Fred Drake committed
321
list_contains(PyListObject *a, PyObject *el)
322
{
323
	int i;
324 325

	for (i = 0; i < a->ob_size; ++i) {
326 327 328
		int cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i),
						   Py_EQ);
		if (cmp > 0)
329
			return 1;
330
		else if (cmp < 0)
331 332 333 334 335 336
			return -1;
	}
	return 0;
}


337
static PyObject *
Fred Drake's avatar
Fred Drake committed
338
list_item(PyListObject *a, int i)
Guido van Rossum's avatar
Guido van Rossum committed
339 340
{
	if (i < 0 || i >= a->ob_size) {
341
		if (indexerr == NULL)
342 343 344
			indexerr = PyString_FromString(
				"list index out of range");
		PyErr_SetObject(PyExc_IndexError, indexerr);
Guido van Rossum's avatar
Guido van Rossum committed
345 346
		return NULL;
	}
347
	Py_INCREF(a->ob_item[i]);
Guido van Rossum's avatar
Guido van Rossum committed
348 349 350
	return a->ob_item[i];
}

351
static PyObject *
Fred Drake's avatar
Fred Drake committed
352
list_slice(PyListObject *a, int ilow, int ihigh)
Guido van Rossum's avatar
Guido van Rossum committed
353
{
354
	PyListObject *np;
Guido van Rossum's avatar
Guido van Rossum committed
355 356 357 358 359 360 361 362 363
	int i;
	if (ilow < 0)
		ilow = 0;
	else if (ilow > a->ob_size)
		ilow = a->ob_size;
	if (ihigh < ilow)
		ihigh = ilow;
	else if (ihigh > a->ob_size)
		ihigh = a->ob_size;
364
	np = (PyListObject *) PyList_New(ihigh - ilow);
Guido van Rossum's avatar
Guido van Rossum committed
365 366 367
	if (np == NULL)
		return NULL;
	for (i = ilow; i < ihigh; i++) {
368 369
		PyObject *v = a->ob_item[i];
		Py_INCREF(v);
Guido van Rossum's avatar
Guido van Rossum committed
370 371
		np->ob_item[i - ilow] = v;
	}
372
	return (PyObject *)np;
Guido van Rossum's avatar
Guido van Rossum committed
373 374
}

375
PyObject *
Fred Drake's avatar
Fred Drake committed
376
PyList_GetSlice(PyObject *a, int ilow, int ihigh)
377
{
378 379
	if (!PyList_Check(a)) {
		PyErr_BadInternalCall();
380 381
		return NULL;
	}
382
	return list_slice((PyListObject *)a, ilow, ihigh);
383 384
}

385
static PyObject *
Fred Drake's avatar
Fred Drake committed
386
list_concat(PyListObject *a, PyObject *bb)
Guido van Rossum's avatar
Guido van Rossum committed
387 388 389
{
	int size;
	int i;
390 391
	PyListObject *np;
	if (!PyList_Check(bb)) {
Fred Drake's avatar
Fred Drake committed
392
		PyErr_Format(PyExc_TypeError,
393 394
			  "can only concatenate list (not \"%.200s\") to list",
			  bb->ob_type->tp_name);
Guido van Rossum's avatar
Guido van Rossum committed
395 396
		return NULL;
	}
397
#define b ((PyListObject *)bb)
Guido van Rossum's avatar
Guido van Rossum committed
398
	size = a->ob_size + b->ob_size;
399
	np = (PyListObject *) PyList_New(size);
Guido van Rossum's avatar
Guido van Rossum committed
400
	if (np == NULL) {
401
		return NULL;
Guido van Rossum's avatar
Guido van Rossum committed
402 403
	}
	for (i = 0; i < a->ob_size; i++) {
404 405
		PyObject *v = a->ob_item[i];
		Py_INCREF(v);
Guido van Rossum's avatar
Guido van Rossum committed
406 407 408
		np->ob_item[i] = v;
	}
	for (i = 0; i < b->ob_size; i++) {
409 410
		PyObject *v = b->ob_item[i];
		Py_INCREF(v);
Guido van Rossum's avatar
Guido van Rossum committed
411 412
		np->ob_item[i + a->ob_size] = v;
	}
413
	return (PyObject *)np;
Guido van Rossum's avatar
Guido van Rossum committed
414 415 416
#undef b
}

417
static PyObject *
Fred Drake's avatar
Fred Drake committed
418
list_repeat(PyListObject *a, int n)
419 420 421
{
	int i, j;
	int size;
422 423
	PyListObject *np;
	PyObject **p;
424 425 426
	if (n < 0)
		n = 0;
	size = a->ob_size * n;
427
	np = (PyListObject *) PyList_New(size);
428 429 430 431 432 433
	if (np == NULL)
		return NULL;
	p = np->ob_item;
	for (i = 0; i < n; i++) {
		for (j = 0; j < a->ob_size; j++) {
			*p = a->ob_item[j];
434
			Py_INCREF(*p);
435 436 437
			p++;
		}
	}
438
	return (PyObject *) np;
439 440
}

Guido van Rossum's avatar
Guido van Rossum committed
441
static int
Fred Drake's avatar
Fred Drake committed
442
list_ass_slice(PyListObject *a, int ilow, int ihigh, PyObject *v)
Guido van Rossum's avatar
Guido van Rossum committed
443
{
444 445 446 447 448 449
	/* Because [X]DECREF can recursively invoke list operations on
	   this list, we must postpone all [X]DECREF activity until
	   after the list is back in its canonical shape.  Therefore
	   we must allocate an additional array, 'recycle', into which
	   we temporarily copy the items that are deleted from the
	   list. :-( */
450 451
	PyObject **recycle, **p;
	PyObject **item;
Guido van Rossum's avatar
Guido van Rossum committed
452 453 454
	int n; /* Size of replacement list */
	int d; /* Change in size */
	int k; /* Loop index */
455
#define b ((PyListObject *)v)
Guido van Rossum's avatar
Guido van Rossum committed
456 457
	if (v == NULL)
		n = 0;
458
	else if (PyList_Check(v)) {
Guido van Rossum's avatar
Guido van Rossum committed
459
		n = b->ob_size;
460 461 462 463 464
		if (a == b) {
			/* Special case "a[i:j] = a" -- copy b first */
			int ret;
			v = list_slice(b, 0, n);
			ret = list_ass_slice(a, ilow, ihigh, v);
465
			Py_DECREF(v);
466 467 468
			return ret;
		}
	}
Guido van Rossum's avatar
Guido van Rossum committed
469
	else {
Fred Drake's avatar
Fred Drake committed
470 471 472
		PyErr_Format(PyExc_TypeError,
			     "must assign list (not \"%.200s\") to slice",
			     v->ob_type->tp_name);
Guido van Rossum's avatar
Guido van Rossum committed
473 474
		return -1;
	}
Guido van Rossum's avatar
Guido van Rossum committed
475 476 477 478 479 480 481 482 483 484
	if (ilow < 0)
		ilow = 0;
	else if (ilow > a->ob_size)
		ilow = a->ob_size;
	if (ihigh < ilow)
		ihigh = ilow;
	else if (ihigh > a->ob_size)
		ihigh = a->ob_size;
	item = a->ob_item;
	d = n - (ihigh-ilow);
485
	if (ihigh > ilow)
486
		p = recycle = PyMem_NEW(PyObject *, (ihigh-ilow));
487 488 489
	else
		p = recycle = NULL;
	if (d <= 0) { /* Delete -d items; recycle ihigh-ilow items */
Guido van Rossum's avatar
Guido van Rossum committed
490
		for (k = ilow; k < ihigh; k++)
491
			*p++ = item[k];
Guido van Rossum's avatar
Guido van Rossum committed
492 493 494 495
		if (d < 0) {
			for (/*k = ihigh*/; k < a->ob_size; k++)
				item[k+d] = item[k];
			a->ob_size += d;
496
			NRESIZE(item, PyObject *, a->ob_size); /* Can't fail */
Guido van Rossum's avatar
Guido van Rossum committed
497 498 499
			a->ob_item = item;
		}
	}
500
	else { /* Insert d items; recycle ihigh-ilow items */
501
		NRESIZE(item, PyObject *, a->ob_size + d);
Guido van Rossum's avatar
Guido van Rossum committed
502
		if (item == NULL) {
503 504
			if (recycle != NULL)
				PyMem_DEL(recycle);
505
			PyErr_NoMemory();
Guido van Rossum's avatar
Guido van Rossum committed
506 507
			return -1;
		}
Guido van Rossum's avatar
Guido van Rossum committed
508 509 510
		for (k = a->ob_size; --k >= ihigh; )
			item[k+d] = item[k];
		for (/*k = ihigh-1*/; k >= ilow; --k)
511
			*p++ = item[k];
Guido van Rossum's avatar
Guido van Rossum committed
512 513 514 515
		a->ob_item = item;
		a->ob_size += d;
	}
	for (k = 0; k < n; k++, ilow++) {
516 517
		PyObject *w = b->ob_item[k];
		Py_XINCREF(w);
Guido van Rossum's avatar
Guido van Rossum committed
518 519
		item[ilow] = w;
	}
520 521
	if (recycle) {
		while (--p >= recycle)
522 523
			Py_XDECREF(*p);
		PyMem_DEL(recycle);
524
	}
525 526 527 528
	if (a->ob_size == 0 && a->ob_item != NULL) {
		PyMem_FREE(a->ob_item);
		a->ob_item = NULL;
	}
Guido van Rossum's avatar
Guido van Rossum committed
529 530 531 532
	return 0;
#undef b
}

533
int
Fred Drake's avatar
Fred Drake committed
534
PyList_SetSlice(PyObject *a, int ilow, int ihigh, PyObject *v)
535
{
536 537
	if (!PyList_Check(a)) {
		PyErr_BadInternalCall();
538
		return -1;
539
	}
540
	return list_ass_slice((PyListObject *)a, ilow, ihigh, v);
541 542
}

543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586
static PyObject *
list_inplace_repeat(PyListObject *self, int n)
{
	PyObject **items;
	int size, i, j;


	size = PyList_GET_SIZE(self);
	if (size == 0) {
		Py_INCREF(self);
		return (PyObject *)self;
	}

	items = self->ob_item;

	if (n < 1) {
		self->ob_item = NULL;
		self->ob_size = 0;
		for (i = 0; i < size; i++)
			Py_XDECREF(items[i]);
		PyMem_DEL(items);
		Py_INCREF(self);
		return (PyObject *)self;
	}

	NRESIZE(items, PyObject*, size*n);
	if (items == NULL) {
		PyErr_NoMemory();
		goto finally;
	}
	self->ob_item = items;
	for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */
		for (j = 0; j < size; j++) {
			PyObject *o = PyList_GET_ITEM(self, j);
			Py_INCREF(o);
			PyList_SET_ITEM(self, self->ob_size++, o);
		}
	}
	Py_INCREF(self);
	return (PyObject *)self;
  finally:
  	return NULL;
}

587
static int
Fred Drake's avatar
Fred Drake committed
588
list_ass_item(PyListObject *a, int i, PyObject *v)
589
{
590
	PyObject *old_value;
591
	if (i < 0 || i >= a->ob_size) {
592 593
		PyErr_SetString(PyExc_IndexError,
				"list assignment index out of range");
594 595 596 597
		return -1;
	}
	if (v == NULL)
		return list_ass_slice(a, i, i+1, v);
598
	Py_INCREF(v);
599
	old_value = a->ob_item[i];
600
	a->ob_item[i] = v;
Tim Peters's avatar
Tim Peters committed
601
	Py_DECREF(old_value);
602 603 604
	return 0;
}

605
static PyObject *
Fred Drake's avatar
Fred Drake committed
606
ins(PyListObject *self, int where, PyObject *v)
Guido van Rossum's avatar
Guido van Rossum committed
607 608 609
{
	if (ins1(self, where, v) != 0)
		return NULL;
610 611
	Py_INCREF(Py_None);
	return Py_None;
Guido van Rossum's avatar
Guido van Rossum committed
612 613
}

614
static PyObject *
Fred Drake's avatar
Fred Drake committed
615
listinsert(PyListObject *self, PyObject *args)
Guido van Rossum's avatar
Guido van Rossum committed
616 617
{
	int i;
618
	PyObject *v;
619
	if (!PyArg_ParseTuple(args, "iO:insert", &i, &v))
Guido van Rossum's avatar
Guido van Rossum committed
620
		return NULL;
621
	return ins(self, i, v);
Guido van Rossum's avatar
Guido van Rossum committed
622 623
}

624
static PyObject *
625
listappend(PyListObject *self, PyObject *v)
Guido van Rossum's avatar
Guido van Rossum committed
626
{
627
	return ins(self, (int) self->ob_size, v);
Guido van Rossum's avatar
Guido van Rossum committed
628 629
}

630 631
static int
listextend_internal(PyListObject *self, PyObject *b)
632 633 634 635 636 637
{
	PyObject **items;
	int selflen = PyList_GET_SIZE(self);
	int blen;
	register int i;

Jeremy Hylton's avatar
Jeremy Hylton committed
638
	if (PyObject_Size(b) == 0) {
639
		/* short circuit when b is empty */
Jeremy Hylton's avatar
Jeremy Hylton committed
640
		Py_DECREF(b);
641
		return 0;
Jeremy Hylton's avatar
Jeremy Hylton committed
642
	}
Andrew M. Kuchling's avatar
Andrew M. Kuchling committed
643

644 645 646 647 648 649 650
	if (self == (PyListObject*)b) {
		/* as in list_ass_slice() we must special case the
		 * situation: a.extend(a)
		 *
		 * XXX: I think this way ought to be faster than using
		 * list_slice() the way list_ass_slice() does.
		 */
Andrew M. Kuchling's avatar
Andrew M. Kuchling committed
651
		Py_DECREF(b);
652 653
		b = PyList_New(selflen);
		if (!b)
654
			return -1;
655 656 657 658 659 660 661
		for (i = 0; i < selflen; i++) {
			PyObject *o = PyList_GET_ITEM(self, i);
			Py_INCREF(o);
			PyList_SET_ITEM(b, i, o);
		}
	}

662
	blen = PyObject_Size(b);
Andrew M. Kuchling's avatar
Andrew M. Kuchling committed
663

664 665 666
	/* resize a using idiom */
	items = self->ob_item;
	NRESIZE(items, PyObject*, selflen + blen);
Andrew M. Kuchling's avatar
Andrew M. Kuchling committed
667
	if (items == NULL) {
668
		PyErr_NoMemory();
669 670
		Py_DECREF(b);
		return -1;
671
	}
672

673 674
	self->ob_item = items;

Andrew M. Kuchling's avatar
Andrew M. Kuchling committed
675
	/* populate the end of self with b's items */
676
	for (i = 0; i < blen; i++) {
Andrew M. Kuchling's avatar
Andrew M. Kuchling committed
677
		PyObject *o = PySequence_Fast_GET_ITEM(b, i);
678 679 680
		Py_INCREF(o);
		PyList_SET_ITEM(self, self->ob_size++, o);
	}
Andrew M. Kuchling's avatar
Andrew M. Kuchling committed
681
	Py_DECREF(b);
682 683 684 685 686 687 688
	return 0;
}


static PyObject *
list_inplace_concat(PyListObject *self, PyObject *other)
{
689
	other = PySequence_Fast(other, "argument to += must be iterable");
690 691 692 693 694 695 696 697
	if (!other)
		return NULL;

	if (listextend_internal(self, other) < 0)
		return NULL;

	Py_INCREF(self);
	return (PyObject *)self;
698 699
}

700
static PyObject *
701
listextend(PyListObject *self, PyObject *b)
702 703
{

704
	b = PySequence_Fast(b, "list.extend() argument must be iterable");
705 706 707 708 709 710 711 712 713
	if (!b)
		return NULL;

	if (listextend_internal(self, b) < 0)
		return NULL;

	Py_INCREF(Py_None);
	return Py_None;
}
714

715
static PyObject *
Fred Drake's avatar
Fred Drake committed
716
listpop(PyListObject *self, PyObject *args)
717 718 719
{
	int i = -1;
	PyObject *v;
720
	if (!PyArg_ParseTuple(args, "|i:pop", &i))
721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741
		return NULL;
	if (self->ob_size == 0) {
		/* Special-case most common failure cause */
		PyErr_SetString(PyExc_IndexError, "pop from empty list");
		return NULL;
	}
	if (i < 0)
		i += self->ob_size;
	if (i < 0 || i >= self->ob_size) {
		PyErr_SetString(PyExc_IndexError, "pop index out of range");
		return NULL;
	}
	v = self->ob_item[i];
	Py_INCREF(v);
	if (list_ass_slice(self, i, i+1, (PyObject *)NULL) != 0) {
		Py_DECREF(v);
		return NULL;
	}
	return v;
}

742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757
/* Reverse a slice of a list in place, from lo up to (exclusive) hi. */
static void
reverse_slice(PyObject **lo, PyObject **hi)
{
	assert(lo && hi);

	--hi;
	while (lo < hi) {
		PyObject *t = *lo;
		*lo = *hi;
		*hi = t;
		++lo;
		--hi;
	}
}

758 759 760 761 762
/* New quicksort implementation for arrays of object pointers.
   Thanks to discussions with Tim Peters. */

/* Comparison function.  Takes care of calling a user-supplied
   comparison function (any callable Python object).  Calls the
763 764 765
   standard comparison function, PyObject_RichCompareBool(), if the user-
   supplied function is NULL.
   Returns <0 on error, >0 if x < y, 0 if x >= y. */
766 767

static int
768
islt(PyObject *x, PyObject *y, PyObject *compare)
769
{
770 771
	PyObject *res;
	PyObject *args;
772 773
	int i;

774 775
	if (compare == NULL)
		return PyObject_RichCompareBool(x, y, Py_LT);
776

777 778 779
	/* Call the user's comparison function and translate the 3-way
	 * result into true or false (or error).
	 */
780
	args = PyTuple_New(2);
781
	if (args == NULL)
782
		return -1;
783 784 785 786
	Py_INCREF(x);
	Py_INCREF(y);
	PyTuple_SET_ITEM(args, 0, x);
	PyTuple_SET_ITEM(args, 1, y);
787
	res = PyObject_Call(compare, args, NULL);
788
	Py_DECREF(args);
789
	if (res == NULL)
790
		return -1;
791 792 793
	if (!PyInt_Check(res)) {
		Py_DECREF(res);
		PyErr_SetString(PyExc_TypeError,
794
				"comparison function must return int");
795
		return -1;
796
	}
797 798
	i = PyInt_AsLong(res);
	Py_DECREF(res);
799
	return i < 0;
800 801
}

802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828
/* MINSIZE is the smallest array that will get a full-blown samplesort
   treatment; smaller arrays are sorted using binary insertion.  It must
   be at least 7 for the samplesort implementation to work.  Binary
   insertion does fewer compares, but can suffer O(N**2) data movement.
   The more expensive compares, the larger MINSIZE should be. */
#define MINSIZE 100

/* MINPARTITIONSIZE is the smallest array slice samplesort will bother to
   partition; smaller slices are passed to binarysort.  It must be at
   least 2, and no larger than MINSIZE.  Setting it higher reduces the #
   of compares slowly, but increases the amount of data movement quickly.
   The value here was chosen assuming a compare costs ~25x more than
   swapping a pair of memory-resident pointers -- but under that assumption,
   changing the value by a few dozen more or less has aggregate effect
   under 1%.  So the value is crucial, but not touchy <wink>. */
#define MINPARTITIONSIZE 40

/* MAXMERGE is the largest number of elements we'll always merge into
   a known-to-be sorted chunk via binary insertion, regardless of the
   size of that chunk.  Given a chunk of N sorted elements, and a group
   of K unknowns, the largest K for which it's better to do insertion
   (than a full-blown sort) is a complicated function of N and K mostly
   involving the expected number of compares and data moves under each
   approach, and the relative cost of those operations on a specific
   architecure.  The fixed value here is conservative, and should be a
   clear win regardless of architecture or N. */
#define MAXMERGE 15
829 830

/* STACKSIZE is the size of our work stack.  A rough estimate is that
831 832 833 834 835 836 837
   this allows us to sort arrays of size N where
   N / ln(N) = MINPARTITIONSIZE * 2**STACKSIZE, so 60 is more than enough
   for arrays of size 2**64.  Because we push the biggest partition
   first, the worst case occurs when all subarrays are always partitioned
   exactly in two. */
#define STACKSIZE 60

838 839 840 841 842 843
/* Compare X to Y via islt().  Goto "fail" if the comparison raises an
   error.  Else "k" is set to true iff X<Y, and an "if (k)" block is
   started.  It makes more sense in context <wink>.  X and Y are PyObject*s.
*/
#define IFLT(X, Y) if ((k = islt(X, Y, compare)) < 0) goto fail;  \
		   if (k)
844 845 846 847

/* binarysort is the best method for sorting small arrays: it does
   few compares, but can do data movement quadratic in the number of
   elements.
848
   [lo, hi) is a contiguous slice of a list, and is sorted via
849
   binary insertion.  This sort is stable.
850 851
   On entry, must have lo <= start <= hi, and that [lo, start) is already
   sorted (pass start == lo if you don't know!).
852
   If islt() complains return -1, else 0.
853 854 855 856 857
   Even in case of error, the output slice will be some permutation of
   the input (nothing is lost or duplicated).
*/

static int
Fred Drake's avatar
Fred Drake committed
858 859
binarysort(PyObject **lo, PyObject **hi, PyObject **start, PyObject *compare)
     /* compare -- comparison function object, or NULL for default */
860 861 862 863 864
{
	register int k;
	register PyObject **l, **p, **r;
	register PyObject *pivot;

865 866
	assert(lo <= start && start <= hi);
	/* assert [lo, start) is sorted */
867 868 869 870 871 872 873
	if (lo == start)
		++start;
	for (; start < hi; ++start) {
		/* set l to where *start belongs */
		l = lo;
		r = start;
		pivot = *r;
874 875 876 877 878 879
		/* Invariants:
		 * pivot >= all in [lo, l).
		 * pivot  < all in [r, start).
		 * The second is vacuously true at the start.
		 */
		assert(l < r);
880 881
		do {
			p = l + ((r - l) >> 1);
882
			IFLT(pivot, *p)
883 884
				r = p;
			else
885
				l = p+1;
886
		} while (l < r);
887 888 889 890 891 892
		assert(l == r);
		/* The invariants still hold, so pivot >= all in [lo, l) and
		   pivot < all in [l, start), so pivot belongs at l.  Note
		   that if there are elements equal to pivot, l points to the
		   first slot after them -- that's why this sort is stable.
		   Slide over to make room.
893 894 895 896 897 898 899
		   Caution: using memmove is much slower under MSVC 5;
		   we're not usually moving many slots. */
		for (p = start; p > l; --p)
			*p = *(p-1);
		*l = pivot;
	}
	return 0;
900

901 902 903 904 905
 fail:
	return -1;
}

/* samplesortslice is the sorting workhorse.
906
   [lo, hi) is a contiguous slice of a list, to be sorted in place.
907
   On entry, must have lo <= hi,
908
   If islt() complains return -1, else 0.
909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929
   Even in case of error, the output slice will be some permutation of
   the input (nothing is lost or duplicated).

   samplesort is basically quicksort on steroids:  a power of 2 close
   to n/ln(n) is computed, and that many elements (less 1) are picked at
   random from the array and sorted.  These 2**k - 1 elements are then
   used as preselected pivots for an equal number of quicksort
   partitioning steps, partitioning the slice into 2**k chunks each of
   size about ln(n).  These small final chunks are then usually handled
   by binarysort.  Note that when k=1, this is roughly the same as an
   ordinary quicksort using a random pivot, and when k=2 this is roughly
   a median-of-3 quicksort.  From that view, using k ~= lg(n/ln(n)) makes
   this a "median of n/ln(n)" quicksort.  You can also view it as a kind
   of bucket sort, where 2**k-1 bucket boundaries are picked dynamically.

   The large number of samples makes a quadratic-time case almost
   impossible, and asymptotically drives the average-case number of
   compares from quicksort's 2 N ln N (or 12/7 N ln N for the median-of-
   3 variant) down to N lg N.

   We also play lots of low-level tricks to cut the number of compares.
Tim Peters's avatar
Tim Peters committed
930

931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966
   Very obscure:  To avoid using extra memory, the PPs are stored in the
   array and shuffled around as partitioning proceeds.  At the start of a
   partitioning step, we'll have 2**m-1 (for some m) PPs in sorted order,
   adjacent (either on the left or the right!) to a chunk of X elements
   that are to be partitioned: P X or X P.  In either case we need to
   shuffle things *in place* so that the 2**(m-1) smaller PPs are on the
   left, followed by the PP to be used for this step (that's the middle
   of the PPs), followed by X, followed by the 2**(m-1) larger PPs:
       P X or X P -> Psmall pivot X Plarge
   and the order of the PPs must not be altered.  It can take a while
   to realize this isn't trivial!  It can take even longer <wink> to
   understand why the simple code below works, using only 2**(m-1) swaps.
   The key is that the order of the X elements isn't necessarily
   preserved:  X can end up as some cyclic permutation of its original
   order.  That's OK, because X is unsorted anyway.  If the order of X
   had to be preserved too, the simplest method I know of using O(1)
   scratch storage requires len(X) + 2**(m-1) swaps, spread over 2 passes.
   Since len(X) is typically several times larger than 2**(m-1), that
   would slow things down.
*/

struct SamplesortStackNode {
	/* Represents a slice of the array, from (& including) lo up
	   to (but excluding) hi.  "extra" additional & adjacent elements
	   are pre-selected pivots (PPs), spanning [lo-extra, lo) if
	   extra > 0, or [hi, hi-extra) if extra < 0.  The PPs are
	   already sorted, but nothing is known about the other elements
	   in [lo, hi). |extra| is always one less than a power of 2.
	   When extra is 0, we're out of PPs, and the slice must be
	   sorted by some other means. */
	PyObject **lo;
	PyObject **hi;
	int extra;
};

/* The number of PPs we want is 2**k - 1, where 2**k is as close to
967
   N / ln(N) as possible.  So k ~= lg(N / ln(N)).  Calling libm routines
968 969 970
   is undesirable, so cutoff values are canned in the "cutoff" table
   below:  cutoff[i] is the smallest N such that k == CUTOFFBASE + i. */
#define CUTOFFBASE 4
971
static long cutoff[] = {
972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996
	43,        /* smallest N such that k == 4 */
	106,       /* etc */
	250,
	576,
	1298,
	2885,
	6339,
	13805,
	29843,
	64116,
	137030,
	291554,
	617916,
	1305130,
	2748295,
	5771662,
	12091672,
	25276798,
	52734615,
	109820537,
	228324027,
	473977813,
	982548444,   /* smallest N such that k == 26 */
	2034159050   /* largest N that fits in signed 32-bit; k == 27 */
};
997 998

static int
Fred Drake's avatar
Fred Drake committed
999 1000
samplesortslice(PyObject **lo, PyObject **hi, PyObject *compare)
     /* compare -- comparison function object, or NULL for default */
1001
{
1002
	register PyObject **l, **r;
1003
	register PyObject *tmp, *pivot;
1004 1005 1006 1007
	register int k;
	int n, extra, top, extraOnRight;
	struct SamplesortStackNode stack[STACKSIZE];

1008
	assert(lo <= hi);
1009
	n = hi - lo;
1010 1011
	if (n < MINSIZE)
		return binarysort(lo, hi, lo, compare);
1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026

	/* ----------------------------------------------------------
	 * Normal case setup: a large array without obvious pattern.
	 * --------------------------------------------------------*/

	/* extra := a power of 2 ~= n/ln(n), less 1.
	   First find the smallest extra s.t. n < cutoff[extra] */
	for (extra = 0;
	     extra < sizeof(cutoff) / sizeof(cutoff[0]);
	     ++extra) {
		if (n < cutoff[extra])
			break;
		/* note that if we fall out of the loop, the value of
		   extra still makes *sense*, but may be smaller than
		   we would like (but the array has more than ~= 2**31
Tim Peters's avatar
Tim Peters committed
1027
		   elements in this case!) */
1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051
	}
	/* Now k == extra - 1 + CUTOFFBASE.  The smallest value k can
	   have is CUTOFFBASE-1, so
	   assert MINSIZE >= 2**(CUTOFFBASE-1) - 1 */
	extra = (1 << (extra - 1 + CUTOFFBASE)) - 1;
	/* assert extra > 0 and n >= extra */

	/* Swap that many values to the start of the array.  The
	   selection of elements is pseudo-random, but the same on
	   every run (this is intentional! timing algorithm changes is
	   a pain if timing varies across runs).  */
	{
		unsigned int seed = n / extra;  /* arbitrary */
		unsigned int i;
		for (i = 0; i < (unsigned)extra; ++i) {
			/* j := random int in [i, n) */
			unsigned int j;
			seed = seed * 69069 + 7;
			j = i + seed % (n - i);
			tmp = lo[i]; lo[i] = lo[j]; lo[j] = tmp;
		}
	}

	/* Recursively sort the preselected pivots. */
1052
	if (samplesortslice(lo, lo + extra, compare) < 0)
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062
		goto fail;

	top = 0;          /* index of available stack slot */
	lo += extra;      /* point to first unknown */
	extraOnRight = 0; /* the PPs are at the left end */

	/* ----------------------------------------------------------
	 * Partition [lo, hi), and repeat until out of work.
	 * --------------------------------------------------------*/
	for (;;) {
1063
		assert(lo <= hi);
1064
		n = hi - lo;
Guido van Rossum's avatar
Guido van Rossum committed
1065

1066 1067 1068 1069 1070 1071 1072
		/* We may not want, or may not be able, to partition:
		   If n is small, it's quicker to insert.
		   If extra is 0, we're out of pivots, and *must* use
		   another method.
		*/
		if (n < MINPARTITIONSIZE || extra == 0) {
			if (n >= MINSIZE) {
1073 1074
				assert(extra == 0);
				/* This is rare, since the average size
1075 1076
				   of a final block is only about
				   ln(original n). */
1077
				if (samplesortslice(lo, hi, compare) < 0)
1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094
					goto fail;
			}
			else {
				/* Binary insertion should be quicker,
				   and we can take advantage of the PPs
				   already being sorted. */
				if (extraOnRight && extra) {
					/* swap the PPs to the left end */
					k = extra;
					do {
						tmp = *lo;
						*lo = *hi;
						*hi = tmp;
						++lo; ++hi;
					} while (--k);
				}
				if (binarysort(lo - extra, hi, lo,
1095
					       compare) < 0)
1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108
					goto fail;
			}

			/* Find another slice to work on. */
			if (--top < 0)
				break;   /* no more -- done! */
			lo = stack[top].lo;
			hi = stack[top].hi;
			extra = stack[top].extra;
			extraOnRight = 0;
			if (extra < 0) {
				extraOnRight = 1;
				extra = -extra;
Guido van Rossum's avatar
Guido van Rossum committed
1109
			}
1110
			continue;
Guido van Rossum's avatar
Guido van Rossum committed
1111
		}
1112

1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123
		/* Pretend the PPs are indexed 0, 1, ..., extra-1.
		   Then our preselected pivot is at (extra-1)/2, and we
		   want to move the PPs before that to the left end of
		   the slice, and the PPs after that to the right end.
		   The following section changes extra, lo, hi, and the
		   slice such that:
		   [lo-extra, lo) contains the smaller PPs.
		   *lo == our PP.
		   (lo, hi) contains the unknown elements.
		   [hi, hi+extra) contains the larger PPs.
		*/
Tim Peters's avatar
Tim Peters committed
1124
		k = extra >>= 1;  /* num PPs to move */
1125 1126 1127 1128 1129 1130 1131 1132
		if (extraOnRight) {
			/* Swap the smaller PPs to the left end.
			   Note that this loop actually moves k+1 items:
			   the last is our PP */
			do {
				tmp = *lo; *lo = *hi; *hi = tmp;
				++lo; ++hi;
			} while (k--);
1133
		}
1134 1135 1136 1137 1138
		else {
			/* Swap the larger PPs to the right end. */
			while (k--) {
				--lo; --hi;
				tmp = *lo; *lo = *hi; *hi = tmp;
1139 1140
			}
		}
1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153
		--lo;   /* *lo is now our PP */
		pivot = *lo;

		/* Now an almost-ordinary quicksort partition step.
		   Note that most of the time is spent here!
		   Only odd thing is that we partition into < and >=,
		   instead of the usual <= and >=.  This helps when
		   there are lots of duplicates of different values,
		   because it eventually tends to make subfiles
		   "pure" (all duplicates), and we special-case for
		   duplicates later. */
		l = lo + 1;
		r = hi - 1;
1154
		assert(lo < l && l < r && r < hi);
1155 1156 1157 1158

		do {
			/* slide l right, looking for key >= pivot */
			do {
1159
				IFLT(*l, pivot)
1160 1161
					++l;
				else
1162
					break;
1163 1164 1165 1166
			} while (l < r);

			/* slide r left, looking for key < pivot */
			while (l < r) {
1167
				register PyObject *rval = *r--;
1168
				IFLT(rval, pivot) {
1169 1170 1171
					/* swap and advance */
					r[1] = *l;
					*l++ = rval;
1172
					break;
1173
				}
1174 1175
			}

1176
		} while (l < r);
Guido van Rossum's avatar
Guido van Rossum committed
1177

1178 1179
		assert(lo < r && r <= l && l < hi);
		/* everything to the left of l is < pivot, and
1180
		   everything to the right of r is >= pivot */
Guido van Rossum's avatar
Guido van Rossum committed
1181

1182
		if (l == r) {
1183
			IFLT(*r, pivot)
1184 1185 1186 1187
				++l;
			else
				--r;
		}
1188 1189 1190 1191 1192 1193
		assert(lo <= r && r+1 == l && l <= hi);
		/* assert r == lo or a[r] < pivot */
		assert(*lo == pivot);
		/* assert l == hi or a[l] >= pivot */
		/* Swap the pivot into "the middle", so we can henceforth
		   ignore it. */
1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210
		*lo = *r;
		*r = pivot;

		/* The following is true now, & will be preserved:
		   All in [lo,r) are < pivot
		   All in [r,l) == pivot (& so can be ignored)
		   All in [l,hi) are >= pivot */

		/* Check for duplicates of the pivot.  One compare is
		   wasted if there are no duplicates, but can win big
		   when there are.
		   Tricky: we're sticking to "<" compares, so deduce
		   equality indirectly.  We know pivot <= *l, so they're
		   equal iff not pivot < *l.
		*/
		while (l < hi) {
			/* pivot <= *l known */
1211
			IFLT(pivot, *l)
1212 1213
				break;
			else
Guido van Rossum's avatar
Guido van Rossum committed
1214
				/* <= and not < implies == */
1215 1216
				++l;
		}
Guido van Rossum's avatar
Guido van Rossum committed
1217

1218 1219 1220
		assert(lo <= r && r < l && l <= hi);
		/* Partitions are [lo, r) and [l, hi)
		   :ush fattest first; remember we still have extra PPs
1221 1222
		   to the left of the left chunk and to the right of
		   the right chunk! */
1223
		assert(top < STACKSIZE);
1224 1225 1226 1227 1228 1229 1230
		if (r - lo <= hi - l) {
			/* second is bigger */
			stack[top].lo = l;
			stack[top].hi = hi;
			stack[top].extra = -extra;
			hi = r;
			extraOnRight = 0;
1231
		}
1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242
		else {
			/* first is bigger */
			stack[top].lo = lo;
			stack[top].hi = r;
			stack[top].extra = extra;
			lo = l;
			extraOnRight = 1;
		}
		++top;

	}   /* end of partitioning loop */
1243

1244
	return 0;
1245 1246 1247

 fail:
	return -1;
1248
}
1249

Jeremy Hylton's avatar
Jeremy Hylton committed
1250
static PyTypeObject immutable_list_type;
1251

1252
static PyObject *
Fred Drake's avatar
Fred Drake committed
1253
listsort(PyListObject *self, PyObject *args)
1254
{
1255
	int k;
1256
	PyObject *compare = NULL;
1257
	PyObject **hi, **p;
1258
	PyTypeObject *savetype;
1259

1260
	if (args != NULL) {
1261
		if (!PyArg_ParseTuple(args, "|O:sort", &compare))
1262 1263
			return NULL;
	}
1264

1265
	savetype = self->ob_type;
1266 1267 1268 1269 1270
	if (self->ob_size < 2) {
		k = 0;
		goto done;
	}

1271
	self->ob_type = &immutable_list_type;
1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315
	hi = self->ob_item + self->ob_size;

	/* Set p to the largest value such that [lo, p) is sorted.
	   This catches the already-sorted case, the all-the-same
	   case, and the appended-a-few-elements-to-a-sorted-list case.
	   If the array is unsorted, we're very likely to get out of
	   the loop fast, so the test is cheap if it doesn't pay off.
	*/
	for (p = self->ob_item + 1; p < hi; ++p) {
		IFLT(*p, *(p-1))
			break;
	}
	/* [lo, p) is sorted, [p, hi) unknown.  Get out cheap if there are
	   few unknowns, or few elements in total. */
	if (hi - p <= MAXMERGE || self->ob_size < MINSIZE) {
		k = binarysort(self->ob_item, hi, p, compare);
		goto done;
	}

	/* Check for the array already being reverse-sorted, or that with
	   a few elements tacked on to the end. */
	for (p = self->ob_item + 1; p < hi; ++p) {
		IFLT(*(p-1), *p)
			break;
	}
	/* [lo, p) is reverse-sorted, [p, hi) unknown. */
	if (hi - p <= MAXMERGE) {
		/* Reverse the reversed prefix, then insert the tail */
		reverse_slice(self->ob_item, p);
		k = binarysort(self->ob_item, hi, p, compare);
		goto done;
	}

	/* A large array without obvious pattern. */
	k = samplesortslice(self->ob_item, hi, compare);

done: /* The IFLT macro requires a label named "fail". */;
fail:
 	self->ob_type = savetype;
	if (k >= 0) {
		Py_INCREF(Py_None);
		return Py_None;
	}
	else
1316 1317 1318
		return NULL;
}

1319 1320
#undef IFLT

1321
int
Fred Drake's avatar
Fred Drake committed
1322
PyList_Sort(PyObject *v)
1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334
{
	if (v == NULL || !PyList_Check(v)) {
		PyErr_BadInternalCall();
		return -1;
	}
	v = listsort((PyListObject *)v, (PyObject *)NULL);
	if (v == NULL)
		return -1;
	Py_DECREF(v);
	return 0;
}

1335
static PyObject *
1336
listreverse(PyListObject *self)
1337
{
1338 1339
	if (self->ob_size > 1)
		reverse_slice(self->ob_item, self->ob_item + self->ob_size);
1340 1341
	Py_INCREF(Py_None);
	return Py_None;
1342 1343
}

1344
int
Fred Drake's avatar
Fred Drake committed
1345
PyList_Reverse(PyObject *v)
1346
{
1347 1348
	if (v == NULL || !PyList_Check(v)) {
		PyErr_BadInternalCall();
1349 1350
		return -1;
	}
1351
	listreverse((PyListObject *)v);
1352 1353 1354
	return 0;
}

1355
PyObject *
Fred Drake's avatar
Fred Drake committed
1356
PyList_AsTuple(PyObject *v)
1357
{
1358 1359
	PyObject *w;
	PyObject **p;
1360
	int n;
1361 1362
	if (v == NULL || !PyList_Check(v)) {
		PyErr_BadInternalCall();
1363 1364
		return NULL;
	}
1365 1366
	n = ((PyListObject *)v)->ob_size;
	w = PyTuple_New(n);
1367 1368
	if (w == NULL)
		return NULL;
1369
	p = ((PyTupleObject *)w)->ob_item;
1370 1371
	memcpy((void *)p,
	       (void *)((PyListObject *)v)->ob_item,
1372
	       n*sizeof(PyObject *));
1373
	while (--n >= 0) {
1374
		Py_INCREF(*p);
1375 1376 1377 1378 1379
		p++;
	}
	return w;
}

1380
static PyObject *
1381
listindex(PyListObject *self, PyObject *v)
1382 1383
{
	int i;
1384

1385
	for (i = 0; i < self->ob_size; i++) {
1386 1387
		int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
		if (cmp > 0)
1388
			return PyInt_FromLong((long)i);
1389
		else if (cmp < 0)
1390
			return NULL;
1391
	}
1392
	PyErr_SetString(PyExc_ValueError, "list.index(x): x not in list");
1393 1394 1395
	return NULL;
}

1396
static PyObject *
1397
listcount(PyListObject *self, PyObject *v)
Guido van Rossum's avatar
Guido van Rossum committed
1398 1399 1400
{
	int count = 0;
	int i;
1401

Guido van Rossum's avatar
Guido van Rossum committed
1402
	for (i = 0; i < self->ob_size; i++) {
1403 1404
		int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
		if (cmp > 0)
Guido van Rossum's avatar
Guido van Rossum committed
1405
			count++;
1406
		else if (cmp < 0)
1407
			return NULL;
Guido van Rossum's avatar
Guido van Rossum committed
1408
	}
1409
	return PyInt_FromLong((long)count);
Guido van Rossum's avatar
Guido van Rossum committed
1410 1411
}

1412
static PyObject *
1413
listremove(PyListObject *self, PyObject *v)
1414 1415
{
	int i;
1416

1417
	for (i = 0; i < self->ob_size; i++) {
1418 1419
		int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
		if (cmp > 0) {
1420 1421
			if (list_ass_slice(self, i, i+1,
					   (PyObject *)NULL) != 0)
1422
				return NULL;
1423 1424
			Py_INCREF(Py_None);
			return Py_None;
1425
		}
1426
		else if (cmp < 0)
1427
			return NULL;
1428
	}
1429
	PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
1430 1431 1432
	return NULL;
}

1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456
static int
list_traverse(PyListObject *o, visitproc visit, void *arg)
{
	int i, err;
	PyObject *x;

	for (i = o->ob_size; --i >= 0; ) {
		x = o->ob_item[i];
		if (x != NULL) {
			err = visit(x, arg);
			if (err)
				return err;
		}
	}
	return 0;
}

static int
list_clear(PyListObject *lp)
{
	(void) PyList_SetSlice((PyObject *)lp, 0, lp->ob_size, 0);
	return 0;
}

1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499
static PyObject *
list_richcompare(PyObject *v, PyObject *w, int op)
{
	PyListObject *vl, *wl;
	int i;

	if (!PyList_Check(v) || !PyList_Check(w)) {
		Py_INCREF(Py_NotImplemented);
		return Py_NotImplemented;
	}

	vl = (PyListObject *)v;
	wl = (PyListObject *)w;

	if (vl->ob_size != wl->ob_size && (op == Py_EQ || op == Py_NE)) {
		/* Shortcut: if the lengths differ, the lists differ */
		PyObject *res;
		if (op == Py_EQ)
			res = Py_False;
		else
			res = Py_True;
		Py_INCREF(res);
		return res;
	}

	/* Search for the first index where items are different */
	for (i = 0; i < vl->ob_size && i < wl->ob_size; i++) {
		int k = PyObject_RichCompareBool(vl->ob_item[i],
						 wl->ob_item[i], Py_EQ);
		if (k < 0)
			return NULL;
		if (!k)
			break;
	}

	if (i >= vl->ob_size || i >= wl->ob_size) {
		/* No more items to compare -- compare sizes */
		int vs = vl->ob_size;
		int ws = wl->ob_size;
		int cmp;
		PyObject *res;
		switch (op) {
		case Py_LT: cmp = vs <  ws; break;
1500
		case Py_LE: cmp = vs <= ws; break;
1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528
		case Py_EQ: cmp = vs == ws; break;
		case Py_NE: cmp = vs != ws; break;
		case Py_GT: cmp = vs >  ws; break;
		case Py_GE: cmp = vs >= ws; break;
		default: return NULL; /* cannot happen */
		}
		if (cmp)
			res = Py_True;
		else
			res = Py_False;
		Py_INCREF(res);
		return res;
	}

	/* We have an item that differs -- shortcuts for EQ/NE */
	if (op == Py_EQ) {
		Py_INCREF(Py_False);
		return Py_False;
	}
	if (op == Py_NE) {
		Py_INCREF(Py_True);
		return Py_True;
	}

	/* Compare the final item again using the proper operator */
	return PyObject_RichCompare(vl->ob_item[i], wl->ob_item[i], op);
}

1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570
/* Adapted from newer code by Tim */
static int
list_fill(PyListObject *result, PyObject *v)
{
	PyObject *it;      /* iter(v) */
	int n;		   /* guess for result list size */
	int i;

	n = result->ob_size;

	/* Special-case list(a_list), for speed. */
	if (PyList_Check(v)) {
		if (v == (PyObject *)result)
			return 0; /* source is destination, we're done */
		return list_ass_slice(result, 0, n, v);
	}

	/* Empty previous contents */
	if (n != 0) {
		if (list_ass_slice(result, 0, n, (PyObject *)NULL) != 0)
			return -1;
	}

	/* Get iterator.  There may be some low-level efficiency to be gained
	 * by caching the tp_iternext slot instead of using PyIter_Next()
	 * later, but premature optimization is the root etc.
	 */
	it = PyObject_GetIter(v);
	if (it == NULL)
		return -1;

	/* Guess a result list size. */
	n = -1;	 /* unknown */
	if (PySequence_Check(v) &&
	    v->ob_type->tp_as_sequence->sq_length) {
		n = PySequence_Size(v);
		if (n < 0)
			PyErr_Clear();
	}
	if (n < 0)
		n = 8;	/* arbitrary */
	NRESIZE(result->ob_item, PyObject*, n);
1571 1572
	if (result->ob_item == NULL) {
		PyErr_NoMemory();
1573
		goto error;
1574
	}
Neal Norwitz's avatar
Neal Norwitz committed
1575
	memset(result->ob_item, 0, sizeof(*result->ob_item) * n);
1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623
	result->ob_size = n;

	/* Run iterator to exhaustion. */
	for (i = 0; ; i++) {
		PyObject *item = PyIter_Next(it);
		if (item == NULL) {
			if (PyErr_Occurred())
				goto error;
			break;
		}
		if (i < n)
			PyList_SET_ITEM(result, i, item); /* steals ref */
		else {
			int status = ins1(result, result->ob_size, item);
			Py_DECREF(item);  /* append creates a new ref */
			if (status < 0)
				goto error;
		}
	}

	/* Cut back result list if initial guess was too large. */
	if (i < n && result != NULL) {
		if (list_ass_slice(result, i, n, (PyObject *)NULL) != 0)
			goto error;
	}
	Py_DECREF(it);
	return 0;

  error:
	Py_DECREF(it);
	return -1;
}

static int
list_init(PyListObject *self, PyObject *args, PyObject *kw)
{
	PyObject *arg = NULL;
	static char *kwlist[] = {"sequence", 0};

	if (!PyArg_ParseTupleAndKeywords(args, kw, "|O:list", kwlist, &arg))
		return -1;
	if (arg != NULL)
		return list_fill(self, arg);
	if (self->ob_size > 0)
		return list_ass_slice(self, 0, self->ob_size, (PyObject*)NULL);
	return 0;
}

1624 1625 1626 1627 1628 1629 1630
static long
list_nohash(PyObject *self)
{
	PyErr_SetString(PyExc_TypeError, "list objects are unhashable");
	return -1;
}

1631 1632 1633
PyDoc_STRVAR(append_doc,
"L.append(object) -- append object to end");
PyDoc_STRVAR(extend_doc,
1634
"L.extend(sequence) -- extend list by appending sequence elements");
1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648
PyDoc_STRVAR(insert_doc,
"L.insert(index, object) -- insert object before index");
PyDoc_STRVAR(pop_doc,
"L.pop([index]) -> item -- remove and return item at index (default last)");
PyDoc_STRVAR(remove_doc,
"L.remove(value) -- remove first occurrence of value");
PyDoc_STRVAR(index_doc,
"L.index(value) -> integer -- return index of first occurrence of value");
PyDoc_STRVAR(count_doc,
"L.count(value) -> integer -- return number of occurrences of value");
PyDoc_STRVAR(reverse_doc,
"L.reverse() -- reverse *IN PLACE*");
PyDoc_STRVAR(sort_doc,
"L.sort([cmpfunc]) -- sort *IN PLACE*; if given, cmpfunc(x, y) -> -1, 0, 1");
1649

1650
static PyMethodDef list_methods[] = {
1651
	{"append",	(PyCFunction)listappend,  METH_O, append_doc},
1652
	{"insert",	(PyCFunction)listinsert,  METH_VARARGS, insert_doc},
1653
	{"extend",      (PyCFunction)listextend,  METH_O, extend_doc},
1654
	{"pop",		(PyCFunction)listpop, 	  METH_VARARGS, pop_doc},
1655 1656 1657 1658
	{"remove",	(PyCFunction)listremove,  METH_O, remove_doc},
	{"index",	(PyCFunction)listindex,   METH_O, index_doc},
	{"count",	(PyCFunction)listcount,   METH_O, count_doc},
	{"reverse",	(PyCFunction)listreverse, METH_NOARGS, reverse_doc},
1659
	{"sort",	(PyCFunction)listsort, 	  METH_VARARGS, sort_doc},
Guido van Rossum's avatar
Guido van Rossum committed
1660 1661 1662
	{NULL,		NULL}		/* sentinel */
};

1663
static PySequenceMethods list_as_sequence = {
1664 1665 1666 1667 1668 1669 1670 1671 1672 1673
	(inquiry)list_length,			/* sq_length */
	(binaryfunc)list_concat,		/* sq_concat */
	(intargfunc)list_repeat,		/* sq_repeat */
	(intargfunc)list_item,			/* sq_item */
	(intintargfunc)list_slice,		/* sq_slice */
	(intobjargproc)list_ass_item,		/* sq_ass_item */
	(intintobjargproc)list_ass_slice,	/* sq_ass_slice */
	(objobjproc)list_contains,		/* sq_contains */
	(binaryfunc)list_inplace_concat,	/* sq_inplace_concat */
	(intargfunc)list_inplace_repeat,	/* sq_inplace_repeat */
Guido van Rossum's avatar
Guido van Rossum committed
1674 1675
};

1676
PyDoc_STRVAR(list_doc,
1677
"list() -> new list\n"
1678
"list(sequence) -> new list initialized from sequence's items");
1679

1680
static PyObject *list_iter(PyObject *seq);
1681

1682
static PyObject *
1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715
list_subscript(PyListObject* self, PyObject* item)
{
	if (PyInt_Check(item)) {
		long i = PyInt_AS_LONG(item);
		if (i < 0)
			i += PyList_GET_SIZE(self);
		return list_item(self, i);
	}
	else if (PyLong_Check(item)) {
		long i = PyLong_AsLong(item);
		if (i == -1 && PyErr_Occurred())
			return NULL;
		if (i < 0)
			i += PyList_GET_SIZE(self);
		return list_item(self, i);
	}
	else if (PySlice_Check(item)) {
		int start, stop, step, slicelength, cur, i;
		PyObject* result;
		PyObject* it;

		if (PySlice_GetIndicesEx((PySliceObject*)item, self->ob_size,
				 &start, &stop, &step, &slicelength) < 0) {
			return NULL;
		}

		if (slicelength <= 0) {
			return PyList_New(0);
		}
		else {
			result = PyList_New(slicelength);
			if (!result) return NULL;

Tim Peters's avatar
Tim Peters committed
1716
			for (cur = start, i = 0; i < slicelength;
1717 1718 1719 1720 1721
			     cur += step, i++) {
				it = PyList_GET_ITEM(self, cur);
				Py_INCREF(it);
				PyList_SET_ITEM(result, i, it);
			}
Tim Peters's avatar
Tim Peters committed
1722

1723 1724 1725 1726 1727 1728 1729 1730 1731 1732
			return result;
		}
	}
	else {
		PyErr_SetString(PyExc_TypeError,
				"list indices must be integers");
		return NULL;
	}
}

Tim Peters's avatar
Tim Peters committed
1733
static int
1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757
list_ass_subscript(PyListObject* self, PyObject* item, PyObject* value)
{
	if (PyInt_Check(item)) {
		long i = PyInt_AS_LONG(item);
		if (i < 0)
			i += PyList_GET_SIZE(self);
		return list_ass_item(self, i, value);
	}
	else if (PyLong_Check(item)) {
		long i = PyLong_AsLong(item);
		if (i == -1 && PyErr_Occurred())
			return -1;
		if (i < 0)
			i += PyList_GET_SIZE(self);
		return list_ass_item(self, i, value);
	}
	else if (PySlice_Check(item)) {
		int start, stop, step, slicelength;

		if (PySlice_GetIndicesEx((PySliceObject*)item, self->ob_size,
				 &start, &stop, &step, &slicelength) < 0) {
			return -1;
		}

Michael W. Hudson's avatar
Michael W. Hudson committed
1758 1759 1760 1761
		/* treat L[slice(a,b)] = v _exactly_ like L[a:b] = v */
		if (step == 1 && ((PySliceObject*)item)->step == Py_None)
			return list_ass_slice(self, start, stop, value);

1762 1763
		if (value == NULL) {
			/* delete slice */
Michael W. Hudson's avatar
Michael W. Hudson committed
1764
			PyObject **garbage, **it;
1765
			int cur, i, j;
Tim Peters's avatar
Tim Peters committed
1766

1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777
			if (slicelength <= 0)
				return 0;

			if (step < 0) {
				stop = start + 1;
				start = stop + step*(slicelength - 1) - 1;
				step = -step;
			}

			garbage = (PyObject**)
				PyMem_MALLOC(slicelength*sizeof(PyObject*));
Tim Peters's avatar
Tim Peters committed
1778 1779

			/* drawing pictures might help
1780
			   understand these for loops */
Guido van Rossum's avatar
Guido van Rossum committed
1781 1782 1783 1784
			for (cur = start, i = 0;
			     cur < stop;
			     cur += step, i++)
			{
1785 1786 1787
				garbage[i] = PyList_GET_ITEM(self, cur);

				for (j = 0; j < step; j++) {
Tim Peters's avatar
Tim Peters committed
1788
					PyList_SET_ITEM(self, cur + j - i,
Guido van Rossum's avatar
Guido van Rossum committed
1789 1790
						PyList_GET_ITEM(self,
								cur + j + 1));
1791 1792
				}
			}
Michael W. Hudson's avatar
Michael W. Hudson committed
1793
			for (cur = start + slicelength*step + 1;
1794 1795 1796 1797 1798
			     cur < self->ob_size; cur++) {
				PyList_SET_ITEM(self, cur - slicelength,
						PyList_GET_ITEM(self, cur));
			}
			self->ob_size -= slicelength;
Michael W. Hudson's avatar
Michael W. Hudson committed
1799 1800 1801
			it = self->ob_item;
			NRESIZE(it, PyObject*, self->ob_size);
			self->ob_item = it;
1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832

			for (i = 0; i < slicelength; i++) {
				Py_DECREF(garbage[i]);
			}
			PyMem_FREE(garbage);

			return 0;
		}
		else {
			/* assign slice */
			PyObject **garbage, *ins;
			int cur, i;

			if (!PyList_Check(value)) {
				PyErr_Format(PyExc_TypeError,
			     "must assign list (not \"%.200s\") to slice",
					     value->ob_type->tp_name);
				return -1;
			}

			if (PyList_GET_SIZE(value) != slicelength) {
				PyErr_Format(PyExc_ValueError,
            "attempt to assign list of size %d to extended slice of size %d",
					     PyList_Size(value), slicelength);
				return -1;
			}

			if (!slicelength)
				return 0;

			/* protect against a[::-1] = a */
Tim Peters's avatar
Tim Peters committed
1833
			if (self == (PyListObject*)value) {
1834 1835
				value = list_slice((PyListObject*)value, 0,
						   PyList_GET_SIZE(value));
Tim Peters's avatar
Tim Peters committed
1836
			}
1837 1838 1839 1840 1841 1842
			else {
				Py_INCREF(value);
			}

			garbage = (PyObject**)
				PyMem_MALLOC(slicelength*sizeof(PyObject*));
Tim Peters's avatar
Tim Peters committed
1843 1844

			for (cur = start, i = 0; i < slicelength;
1845 1846
			     cur += step, i++) {
				garbage[i] = PyList_GET_ITEM(self, cur);
Tim Peters's avatar
Tim Peters committed
1847

1848 1849 1850 1851 1852 1853 1854 1855
				ins = PyList_GET_ITEM(value, i);
				Py_INCREF(ins);
				PyList_SET_ITEM(self, cur, ins);
			}

			for (i = 0; i < slicelength; i++) {
				Py_DECREF(garbage[i]);
			}
Tim Peters's avatar
Tim Peters committed
1856

1857 1858
			PyMem_FREE(garbage);
			Py_DECREF(value);
Tim Peters's avatar
Tim Peters committed
1859

1860 1861
			return 0;
		}
Tim Peters's avatar
Tim Peters committed
1862
	}
1863
	else {
Tim Peters's avatar
Tim Peters committed
1864
		PyErr_SetString(PyExc_TypeError,
1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875
				"list indices must be integers");
		return -1;
	}
}

static PyMappingMethods list_as_mapping = {
	(inquiry)list_length,
	(binaryfunc)list_subscript,
	(objobjargproc)list_ass_subscript
};

1876 1877
PyTypeObject PyList_Type = {
	PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum's avatar
Guido van Rossum committed
1878 1879
	0,
	"list",
Neil Schemenauer's avatar
Neil Schemenauer committed
1880
	sizeof(PyListObject),
Guido van Rossum's avatar
Guido van Rossum committed
1881
	0,
1882 1883
	(destructor)list_dealloc,		/* tp_dealloc */
	(printfunc)list_print,			/* tp_print */
1884
	0,					/* tp_getattr */
1885 1886 1887 1888 1889
	0,					/* tp_setattr */
	0,					/* tp_compare */
	(reprfunc)list_repr,			/* tp_repr */
	0,					/* tp_as_number */
	&list_as_sequence,			/* tp_as_sequence */
1890
	&list_as_mapping,			/* tp_as_mapping */
1891
	list_nohash,				/* tp_hash */
1892 1893
	0,					/* tp_call */
	0,					/* tp_str */
1894
	PyObject_GenericGetAttr,		/* tp_getattro */
1895 1896
	0,					/* tp_setattro */
	0,					/* tp_as_buffer */
Neil Schemenauer's avatar
Neil Schemenauer committed
1897
	Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1898 1899
		Py_TPFLAGS_BASETYPE,		/* tp_flags */
 	list_doc,				/* tp_doc */
1900 1901 1902
 	(traverseproc)list_traverse,		/* tp_traverse */
 	(inquiry)list_clear,			/* tp_clear */
	list_richcompare,			/* tp_richcompare */
1903
	0,					/* tp_weaklistoffset */
1904
	list_iter,				/* tp_iter */
1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916
	0,					/* tp_iternext */
	list_methods,				/* tp_methods */
	0,					/* tp_members */
	0,					/* tp_getset */
	0,					/* tp_base */
	0,					/* tp_dict */
	0,					/* tp_descr_get */
	0,					/* tp_descr_set */
	0,					/* tp_dictoffset */
	(initproc)list_init,			/* tp_init */
	PyType_GenericAlloc,			/* tp_alloc */
	PyType_GenericNew,			/* tp_new */
Guido van Rossum's avatar
Guido van Rossum committed
1917
	PyObject_GC_Del,			/* tp_free */
Guido van Rossum's avatar
Guido van Rossum committed
1918
};
1919 1920 1921 1922 1923 1924 1925 1926 1927


/* During a sort, we really can't have anyone modifying the list; it could
   cause core dumps.  Thus, we substitute a dummy type that raises an
   explanatory exception when a modifying operation is used.  Caveat:
   comparisons may behave differently; but I guess it's a bad idea anyway to
   compare a list that's being sorted... */

static PyObject *
Fred Drake's avatar
Fred Drake committed
1928
immutable_list_op(void)
1929 1930 1931 1932 1933 1934 1935
{
	PyErr_SetString(PyExc_TypeError,
			"a list cannot be modified while it is being sorted");
	return NULL;
}

static PyMethodDef immutable_list_methods[] = {
1936 1937
	{"append",	(PyCFunction)immutable_list_op, METH_VARARGS},
	{"insert",	(PyCFunction)immutable_list_op, METH_VARARGS},
1938 1939
	{"extend",      (PyCFunction)immutable_list_op,  METH_O},
	{"pop",		(PyCFunction)immutable_list_op, METH_VARARGS},
1940 1941 1942 1943 1944
	{"remove",	(PyCFunction)immutable_list_op, METH_VARARGS},
	{"index",	(PyCFunction)listindex,         METH_O},
	{"count",	(PyCFunction)listcount,         METH_O},
	{"reverse",	(PyCFunction)immutable_list_op, METH_VARARGS},
	{"sort",	(PyCFunction)immutable_list_op, METH_VARARGS},
1945 1946 1947 1948
	{NULL,		NULL}		/* sentinel */
};

static int
Fred Drake's avatar
Fred Drake committed
1949
immutable_list_ass(void)
1950 1951 1952 1953 1954 1955
{
	immutable_list_op();
	return -1;
}

static PySequenceMethods immutable_list_as_sequence = {
1956 1957 1958 1959 1960 1961 1962 1963
	(inquiry)list_length,			/* sq_length */
	(binaryfunc)list_concat,		/* sq_concat */
	(intargfunc)list_repeat,		/* sq_repeat */
	(intargfunc)list_item,			/* sq_item */
	(intintargfunc)list_slice,		/* sq_slice */
	(intobjargproc)immutable_list_ass,	/* sq_ass_item */
	(intintobjargproc)immutable_list_ass,	/* sq_ass_slice */
	(objobjproc)list_contains,		/* sq_contains */
1964 1965 1966 1967 1968 1969
};

static PyTypeObject immutable_list_type = {
	PyObject_HEAD_INIT(&PyType_Type)
	0,
	"list (immutable, during sort)",
Neil Schemenauer's avatar
Neil Schemenauer committed
1970
	sizeof(PyListObject),
1971
	0,
1972 1973
	0, /* Cannot happen */			/* tp_dealloc */
	(printfunc)list_print,			/* tp_print */
1974
	0,					/* tp_getattr */
1975 1976 1977 1978 1979 1980
	0,					/* tp_setattr */
	0, /* Won't be called */		/* tp_compare */
	(reprfunc)list_repr,			/* tp_repr */
	0,					/* tp_as_number */
	&immutable_list_as_sequence,		/* tp_as_sequence */
	0,					/* tp_as_mapping */
1981
	list_nohash,				/* tp_hash */
1982 1983
	0,					/* tp_call */
	0,					/* tp_str */
1984
	PyObject_GenericGetAttr,		/* tp_getattro */
1985 1986
	0,					/* tp_setattro */
	0,					/* tp_as_buffer */
Neil Schemenauer's avatar
Neil Schemenauer committed
1987
	Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
1988
 	list_doc,				/* tp_doc */
1989 1990 1991
 	(traverseproc)list_traverse,		/* tp_traverse */
	0,					/* tp_clear */
	list_richcompare,			/* tp_richcompare */
1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002
	0,					/* tp_weaklistoffset */
	0,					/* tp_iter */
	0,					/* tp_iternext */
	immutable_list_methods,			/* tp_methods */
	0,					/* tp_members */
	0,					/* tp_getset */
	0,					/* tp_base */
	0,					/* tp_dict */
	0,					/* tp_descr_get */
	0,					/* tp_descr_set */
	0,					/* tp_init */
2003
	/* NOTE: This is *not* the standard list_type struct! */
2004
};
2005 2006 2007 2008 2009


/*********************** List Iterator **************************/

typedef struct {
Guido van Rossum's avatar
Guido van Rossum committed
2010 2011
	PyObject_HEAD
	long it_index;
2012
	PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
2013 2014 2015 2016
} listiterobject;

PyTypeObject PyListIter_Type;

2017
static PyObject *
2018 2019
list_iter(PyObject *seq)
{
Guido van Rossum's avatar
Guido van Rossum committed
2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033
	listiterobject *it;

	if (!PyList_Check(seq)) {
		PyErr_BadInternalCall();
		return NULL;
	}
	it = PyObject_GC_New(listiterobject, &PyListIter_Type);
	if (it == NULL)
		return NULL;
	it->it_index = 0;
	Py_INCREF(seq);
	it->it_seq = (PyListObject *)seq;
	_PyObject_GC_TRACK(it);
	return (PyObject *)it;
2034 2035 2036 2037 2038
}

static void
listiter_dealloc(listiterobject *it)
{
Guido van Rossum's avatar
Guido van Rossum committed
2039
	_PyObject_GC_UNTRACK(it);
2040
	Py_XDECREF(it->it_seq);
Guido van Rossum's avatar
Guido van Rossum committed
2041
	PyObject_GC_Del(it);
2042 2043 2044 2045 2046
}

static int
listiter_traverse(listiterobject *it, visitproc visit, void *arg)
{
2047 2048
	if (it->it_seq == NULL)
		return 0;
Guido van Rossum's avatar
Guido van Rossum committed
2049
	return visit((PyObject *)it->it_seq, arg);
2050 2051 2052 2053 2054 2055
}


static PyObject *
listiter_getiter(PyObject *it)
{
Guido van Rossum's avatar
Guido van Rossum committed
2056 2057
	Py_INCREF(it);
	return it;
2058 2059 2060
}

static PyObject *
2061
listiter_next(listiterobject *it)
2062
{
Guido van Rossum's avatar
Guido van Rossum committed
2063 2064
	PyListObject *seq;
	PyObject *item;
2065

2066
	assert(it != NULL);
Guido van Rossum's avatar
Guido van Rossum committed
2067
	seq = it->it_seq;
2068 2069
	if (seq == NULL)
		return NULL;
Guido van Rossum's avatar
Guido van Rossum committed
2070
	assert(PyList_Check(seq));
2071

Guido van Rossum's avatar
Guido van Rossum committed
2072
	if (it->it_index < PyList_GET_SIZE(seq)) {
2073 2074
		item = PyList_GET_ITEM(seq, it->it_index);
		++it->it_index;
Guido van Rossum's avatar
Guido van Rossum committed
2075 2076 2077
		Py_INCREF(item);
		return item;
	}
2078 2079 2080

	Py_DECREF(seq);
	it->it_seq = NULL;
Guido van Rossum's avatar
Guido van Rossum committed
2081
	return NULL;
2082 2083 2084
}

PyTypeObject PyListIter_Type = {
Guido van Rossum's avatar
Guido van Rossum committed
2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113
	PyObject_HEAD_INIT(&PyType_Type)
	0,					/* ob_size */
	"listiterator",				/* tp_name */
	sizeof(listiterobject),			/* tp_basicsize */
	0,					/* tp_itemsize */
	/* methods */
	(destructor)listiter_dealloc,		/* tp_dealloc */
	0,					/* tp_print */
	0,					/* tp_getattr */
	0,					/* tp_setattr */
	0,					/* tp_compare */
	0,					/* tp_repr */
	0,					/* tp_as_number */
	0,					/* tp_as_sequence */
	0,					/* tp_as_mapping */
	0,					/* tp_hash */
	0,					/* tp_call */
	0,					/* tp_str */
	PyObject_GenericGetAttr,		/* tp_getattro */
	0,					/* tp_setattro */
	0,					/* tp_as_buffer */
	Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
	0,					/* tp_doc */
	(traverseproc)listiter_traverse,	/* tp_traverse */
	0,					/* tp_clear */
	0,					/* tp_richcompare */
	0,					/* tp_weaklistoffset */
	(getiterfunc)listiter_getiter,		/* tp_iter */
	(iternextfunc)listiter_next,		/* tp_iternext */
2114
	0,					/* tp_methods */
Guido van Rossum's avatar
Guido van Rossum committed
2115 2116 2117 2118 2119 2120
	0,					/* tp_members */
	0,					/* tp_getset */
	0,					/* tp_base */
	0,					/* tp_dict */
	0,					/* tp_descr_get */
	0,					/* tp_descr_set */
2121
};