Use full package paths in imports.
[python/dscho.git] / Objects / tupleobject.c
blobadd9cac639c20cad91fe9b4341419a1f146fb3a7
2 /* Tuple object implementation */
4 #include "Python.h"
6 /* Speed optimization to avoid frequent malloc/free of small tuples */
7 #ifndef MAXSAVESIZE
8 #define MAXSAVESIZE 20 /* Largest tuple to save on free list */
9 #endif
10 #ifndef MAXSAVEDTUPLES
11 #define MAXSAVEDTUPLES 2000 /* Maximum number of tuples of each size to save */
12 #endif
14 #if MAXSAVESIZE > 0
15 /* Entries 1 up to MAXSAVESIZE are free lists, entry 0 is the empty
16 tuple () of which at most one instance will be allocated.
18 static PyTupleObject *free_tuples[MAXSAVESIZE];
19 static int num_free_tuples[MAXSAVESIZE];
20 #endif
21 #ifdef COUNT_ALLOCS
22 int fast_tuple_allocs;
23 int tuple_zero_allocs;
24 #endif
26 PyObject *
27 PyTuple_New(register int size)
29 register PyTupleObject *op;
30 if (size < 0) {
31 PyErr_BadInternalCall();
32 return NULL;
34 #if MAXSAVESIZE > 0
35 if (size == 0 && free_tuples[0]) {
36 op = free_tuples[0];
37 Py_INCREF(op);
38 #ifdef COUNT_ALLOCS
39 tuple_zero_allocs++;
40 #endif
41 return (PyObject *) op;
43 if (0 < size && size < MAXSAVESIZE &&
44 (op = free_tuples[size]) != NULL)
46 free_tuples[size] = (PyTupleObject *) op->ob_item[0];
47 num_free_tuples[size]--;
48 #ifdef COUNT_ALLOCS
49 fast_tuple_allocs++;
50 #endif
51 /* PyObject_InitVar is inlined */
52 #ifdef Py_TRACE_REFS
53 op->ob_size = size;
54 op->ob_type = &PyTuple_Type;
55 #endif
56 _Py_NewReference((PyObject *)op);
58 else
59 #endif
61 int nbytes = size * sizeof(PyObject *);
62 /* Check for overflow */
63 if (nbytes / sizeof(PyObject *) != (size_t)size ||
64 (nbytes += sizeof(PyTupleObject) - sizeof(PyObject *))
65 <= 0)
67 return PyErr_NoMemory();
69 op = PyObject_GC_NewVar(PyTupleObject, &PyTuple_Type, size);
70 if (op == NULL)
71 return NULL;
73 memset(op->ob_item, 0, sizeof(*op->ob_item) * size);
74 #if MAXSAVESIZE > 0
75 if (size == 0) {
76 free_tuples[0] = op;
77 ++num_free_tuples[0];
78 Py_INCREF(op); /* extra INCREF so that this is never freed */
80 #endif
81 _PyObject_GC_TRACK(op);
82 return (PyObject *) op;
85 int
86 PyTuple_Size(register PyObject *op)
88 if (!PyTuple_Check(op)) {
89 PyErr_BadInternalCall();
90 return -1;
92 else
93 return ((PyTupleObject *)op)->ob_size;
96 PyObject *
97 PyTuple_GetItem(register PyObject *op, register int i)
99 if (!PyTuple_Check(op)) {
100 PyErr_BadInternalCall();
101 return NULL;
103 if (i < 0 || i >= ((PyTupleObject *)op) -> ob_size) {
104 PyErr_SetString(PyExc_IndexError, "tuple index out of range");
105 return NULL;
107 return ((PyTupleObject *)op) -> ob_item[i];
111 PyTuple_SetItem(register PyObject *op, register int i, PyObject *newitem)
113 register PyObject *olditem;
114 register PyObject **p;
115 if (!PyTuple_Check(op) || op->ob_refcnt != 1) {
116 Py_XDECREF(newitem);
117 PyErr_BadInternalCall();
118 return -1;
120 if (i < 0 || i >= ((PyTupleObject *)op) -> ob_size) {
121 Py_XDECREF(newitem);
122 PyErr_SetString(PyExc_IndexError,
123 "tuple assignment index out of range");
124 return -1;
126 p = ((PyTupleObject *)op) -> ob_item + i;
127 olditem = *p;
128 *p = newitem;
129 Py_XDECREF(olditem);
130 return 0;
133 /* Methods */
135 static void
136 tupledealloc(register PyTupleObject *op)
138 register int i;
139 register int len = op->ob_size;
140 PyObject_GC_UnTrack(op);
141 Py_TRASHCAN_SAFE_BEGIN(op)
142 if (len > 0) {
143 i = len;
144 while (--i >= 0)
145 Py_XDECREF(op->ob_item[i]);
146 #if MAXSAVESIZE > 0
147 if (len < MAXSAVESIZE &&
148 num_free_tuples[len] < MAXSAVEDTUPLES &&
149 op->ob_type == &PyTuple_Type)
151 op->ob_item[0] = (PyObject *) free_tuples[len];
152 num_free_tuples[len]++;
153 free_tuples[len] = op;
154 goto done; /* return */
156 #endif
158 op->ob_type->tp_free((PyObject *)op);
159 done:
160 Py_TRASHCAN_SAFE_END(op)
163 static int
164 tupleprint(PyTupleObject *op, FILE *fp, int flags)
166 int i;
167 fprintf(fp, "(");
168 for (i = 0; i < op->ob_size; i++) {
169 if (i > 0)
170 fprintf(fp, ", ");
171 if (PyObject_Print(op->ob_item[i], fp, 0) != 0)
172 return -1;
174 if (op->ob_size == 1)
175 fprintf(fp, ",");
176 fprintf(fp, ")");
177 return 0;
180 static PyObject *
181 tuplerepr(PyTupleObject *v)
183 int i, n;
184 PyObject *s, *temp;
185 PyObject *pieces, *result = NULL;
187 n = v->ob_size;
188 if (n == 0)
189 return PyString_FromString("()");
191 pieces = PyTuple_New(n);
192 if (pieces == NULL)
193 return NULL;
195 /* Do repr() on each element. */
196 for (i = 0; i < n; ++i) {
197 s = PyObject_Repr(v->ob_item[i]);
198 if (s == NULL)
199 goto Done;
200 PyTuple_SET_ITEM(pieces, i, s);
203 /* Add "()" decorations to the first and last items. */
204 assert(n > 0);
205 s = PyString_FromString("(");
206 if (s == NULL)
207 goto Done;
208 temp = PyTuple_GET_ITEM(pieces, 0);
209 PyString_ConcatAndDel(&s, temp);
210 PyTuple_SET_ITEM(pieces, 0, s);
211 if (s == NULL)
212 goto Done;
214 s = PyString_FromString(n == 1 ? ",)" : ")");
215 if (s == NULL)
216 goto Done;
217 temp = PyTuple_GET_ITEM(pieces, n-1);
218 PyString_ConcatAndDel(&temp, s);
219 PyTuple_SET_ITEM(pieces, n-1, temp);
220 if (temp == NULL)
221 goto Done;
223 /* Paste them all together with ", " between. */
224 s = PyString_FromString(", ");
225 if (s == NULL)
226 goto Done;
227 result = _PyString_Join(s, pieces);
228 Py_DECREF(s);
230 Done:
231 Py_DECREF(pieces);
232 return result;
235 static long
236 tuplehash(PyTupleObject *v)
238 register long x, y;
239 register int len = v->ob_size;
240 register PyObject **p;
241 x = 0x345678L;
242 p = v->ob_item;
243 while (--len >= 0) {
244 y = PyObject_Hash(*p++);
245 if (y == -1)
246 return -1;
247 x = (1000003*x) ^ y;
249 x ^= v->ob_size;
250 if (x == -1)
251 x = -2;
252 return x;
255 static int
256 tuplelength(PyTupleObject *a)
258 return a->ob_size;
261 static int
262 tuplecontains(PyTupleObject *a, PyObject *el)
264 int i, cmp;
266 for (i = 0; i < a->ob_size; ++i) {
267 cmp = PyObject_RichCompareBool(el, PyTuple_GET_ITEM(a, i),
268 Py_EQ);
269 if (cmp > 0)
270 return 1;
271 else if (cmp < 0)
272 return -1;
274 return 0;
277 static PyObject *
278 tupleitem(register PyTupleObject *a, register int i)
280 if (i < 0 || i >= a->ob_size) {
281 PyErr_SetString(PyExc_IndexError, "tuple index out of range");
282 return NULL;
284 Py_INCREF(a->ob_item[i]);
285 return a->ob_item[i];
288 static PyObject *
289 tupleslice(register PyTupleObject *a, register int ilow, register int ihigh)
291 register PyTupleObject *np;
292 register int i;
293 if (ilow < 0)
294 ilow = 0;
295 if (ihigh > a->ob_size)
296 ihigh = a->ob_size;
297 if (ihigh < ilow)
298 ihigh = ilow;
299 if (ilow == 0 && ihigh == a->ob_size && PyTuple_CheckExact(a)) {
300 Py_INCREF(a);
301 return (PyObject *)a;
303 np = (PyTupleObject *)PyTuple_New(ihigh - ilow);
304 if (np == NULL)
305 return NULL;
306 for (i = ilow; i < ihigh; i++) {
307 PyObject *v = a->ob_item[i];
308 Py_INCREF(v);
309 np->ob_item[i - ilow] = v;
311 return (PyObject *)np;
314 PyObject *
315 PyTuple_GetSlice(PyObject *op, int i, int j)
317 if (op == NULL || !PyTuple_Check(op)) {
318 PyErr_BadInternalCall();
319 return NULL;
321 return tupleslice((PyTupleObject *)op, i, j);
324 static PyObject *
325 tupleconcat(register PyTupleObject *a, register PyObject *bb)
327 register int size;
328 register int i;
329 PyTupleObject *np;
330 if (!PyTuple_Check(bb)) {
331 PyErr_Format(PyExc_TypeError,
332 "can only concatenate tuple (not \"%.200s\") to tuple",
333 bb->ob_type->tp_name);
334 return NULL;
336 #define b ((PyTupleObject *)bb)
337 size = a->ob_size + b->ob_size;
338 np = (PyTupleObject *) PyTuple_New(size);
339 if (np == NULL) {
340 return NULL;
342 for (i = 0; i < a->ob_size; i++) {
343 PyObject *v = a->ob_item[i];
344 Py_INCREF(v);
345 np->ob_item[i] = v;
347 for (i = 0; i < b->ob_size; i++) {
348 PyObject *v = b->ob_item[i];
349 Py_INCREF(v);
350 np->ob_item[i + a->ob_size] = v;
352 return (PyObject *)np;
353 #undef b
356 static PyObject *
357 tuplerepeat(PyTupleObject *a, int n)
359 int i, j;
360 int size;
361 PyTupleObject *np;
362 PyObject **p;
363 if (n < 0)
364 n = 0;
365 if (a->ob_size == 0 || n == 1) {
366 if (PyTuple_CheckExact(a)) {
367 /* Since tuples are immutable, we can return a shared
368 copy in this case */
369 Py_INCREF(a);
370 return (PyObject *)a;
372 if (a->ob_size == 0)
373 return PyTuple_New(0);
375 size = a->ob_size * n;
376 if (size/a->ob_size != n)
377 return PyErr_NoMemory();
378 np = (PyTupleObject *) PyTuple_New(size);
379 if (np == NULL)
380 return NULL;
381 p = np->ob_item;
382 for (i = 0; i < n; i++) {
383 for (j = 0; j < a->ob_size; j++) {
384 *p = a->ob_item[j];
385 Py_INCREF(*p);
386 p++;
389 return (PyObject *) np;
392 static int
393 tupletraverse(PyTupleObject *o, visitproc visit, void *arg)
395 int i, err;
396 PyObject *x;
398 for (i = o->ob_size; --i >= 0; ) {
399 x = o->ob_item[i];
400 if (x != NULL) {
401 err = visit(x, arg);
402 if (err)
403 return err;
406 return 0;
409 static PyObject *
410 tuplerichcompare(PyObject *v, PyObject *w, int op)
412 PyTupleObject *vt, *wt;
413 int i;
414 int vlen, wlen;
416 if (!PyTuple_Check(v) || !PyTuple_Check(w)) {
417 Py_INCREF(Py_NotImplemented);
418 return Py_NotImplemented;
421 vt = (PyTupleObject *)v;
422 wt = (PyTupleObject *)w;
424 vlen = vt->ob_size;
425 wlen = wt->ob_size;
427 /* Note: the corresponding code for lists has an "early out" test
428 * here when op is EQ or NE and the lengths differ. That pays there,
429 * but Tim was unable to find any real code where EQ/NE tuple
430 * compares don't have the same length, so testing for it here would
431 * have cost without benefit.
434 /* Search for the first index where items are different.
435 * Note that because tuples are immutable, it's safe to reuse
436 * vlen and wlen across the comparison calls.
438 for (i = 0; i < vlen && i < wlen; i++) {
439 int k = PyObject_RichCompareBool(vt->ob_item[i],
440 wt->ob_item[i], Py_EQ);
441 if (k < 0)
442 return NULL;
443 if (!k)
444 break;
447 if (i >= vlen || i >= wlen) {
448 /* No more items to compare -- compare sizes */
449 int cmp;
450 PyObject *res;
451 switch (op) {
452 case Py_LT: cmp = vlen < wlen; break;
453 case Py_LE: cmp = vlen <= wlen; break;
454 case Py_EQ: cmp = vlen == wlen; break;
455 case Py_NE: cmp = vlen != wlen; break;
456 case Py_GT: cmp = vlen > wlen; break;
457 case Py_GE: cmp = vlen >= wlen; break;
458 default: return NULL; /* cannot happen */
460 if (cmp)
461 res = Py_True;
462 else
463 res = Py_False;
464 Py_INCREF(res);
465 return res;
468 /* We have an item that differs -- shortcuts for EQ/NE */
469 if (op == Py_EQ) {
470 Py_INCREF(Py_False);
471 return Py_False;
473 if (op == Py_NE) {
474 Py_INCREF(Py_True);
475 return Py_True;
478 /* Compare the final item again using the proper operator */
479 return PyObject_RichCompare(vt->ob_item[i], wt->ob_item[i], op);
482 static PyObject *
483 tuple_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
485 static PyObject *
486 tuple_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
488 PyObject *arg = NULL;
489 static char *kwlist[] = {"sequence", 0};
491 if (type != &PyTuple_Type)
492 return tuple_subtype_new(type, args, kwds);
493 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:tuple", kwlist, &arg))
494 return NULL;
496 if (arg == NULL)
497 return PyTuple_New(0);
498 else
499 return PySequence_Tuple(arg);
502 static PyObject *
503 tuple_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
505 PyObject *tmp, *new, *item;
506 int i, n;
508 assert(PyType_IsSubtype(type, &PyTuple_Type));
509 tmp = tuple_new(&PyTuple_Type, args, kwds);
510 if (tmp == NULL)
511 return NULL;
512 assert(PyTuple_Check(tmp));
513 new = type->tp_alloc(type, n = PyTuple_GET_SIZE(tmp));
514 if (new == NULL)
515 return NULL;
516 for (i = 0; i < n; i++) {
517 item = PyTuple_GET_ITEM(tmp, i);
518 Py_INCREF(item);
519 PyTuple_SET_ITEM(new, i, item);
521 Py_DECREF(tmp);
522 return new;
525 PyDoc_STRVAR(tuple_doc,
526 "tuple() -> an empty tuple\n"
527 "tuple(sequence) -> tuple initialized from sequence's items\n"
528 "\n"
529 "If the argument is a tuple, the return value is the same object.");
531 static PySequenceMethods tuple_as_sequence = {
532 (inquiry)tuplelength, /* sq_length */
533 (binaryfunc)tupleconcat, /* sq_concat */
534 (intargfunc)tuplerepeat, /* sq_repeat */
535 (intargfunc)tupleitem, /* sq_item */
536 (intintargfunc)tupleslice, /* sq_slice */
537 0, /* sq_ass_item */
538 0, /* sq_ass_slice */
539 (objobjproc)tuplecontains, /* sq_contains */
542 static PyObject*
543 tuplesubscript(PyTupleObject* self, PyObject* item)
545 if (PyInt_Check(item)) {
546 long i = PyInt_AS_LONG(item);
547 if (i < 0)
548 i += PyTuple_GET_SIZE(self);
549 return tupleitem(self, i);
551 else if (PyLong_Check(item)) {
552 long i = PyLong_AsLong(item);
553 if (i == -1 && PyErr_Occurred())
554 return NULL;
555 if (i < 0)
556 i += PyTuple_GET_SIZE(self);
557 return tupleitem(self, i);
559 else if (PySlice_Check(item)) {
560 int start, stop, step, slicelength, cur, i;
561 PyObject* result;
562 PyObject* it;
564 if (PySlice_GetIndicesEx((PySliceObject*)item,
565 PyTuple_GET_SIZE(self),
566 &start, &stop, &step, &slicelength) < 0) {
567 return NULL;
570 if (slicelength <= 0) {
571 return PyTuple_New(0);
573 else {
574 result = PyTuple_New(slicelength);
576 for (cur = start, i = 0; i < slicelength;
577 cur += step, i++) {
578 it = PyTuple_GET_ITEM(self, cur);
579 Py_INCREF(it);
580 PyTuple_SET_ITEM(result, i, it);
583 return result;
586 else {
587 PyErr_SetString(PyExc_TypeError,
588 "tuple indices must be integers");
589 return NULL;
593 static PyMappingMethods tuple_as_mapping = {
594 (inquiry)tuplelength,
595 (binaryfunc)tuplesubscript,
599 PyTypeObject PyTuple_Type = {
600 PyObject_HEAD_INIT(&PyType_Type)
602 "tuple",
603 sizeof(PyTupleObject) - sizeof(PyObject *),
604 sizeof(PyObject *),
605 (destructor)tupledealloc, /* tp_dealloc */
606 (printfunc)tupleprint, /* tp_print */
607 0, /* tp_getattr */
608 0, /* tp_setattr */
609 0, /* tp_compare */
610 (reprfunc)tuplerepr, /* tp_repr */
611 0, /* tp_as_number */
612 &tuple_as_sequence, /* tp_as_sequence */
613 &tuple_as_mapping, /* tp_as_mapping */
614 (hashfunc)tuplehash, /* tp_hash */
615 0, /* tp_call */
616 0, /* tp_str */
617 PyObject_GenericGetAttr, /* tp_getattro */
618 0, /* tp_setattro */
619 0, /* tp_as_buffer */
620 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
621 Py_TPFLAGS_BASETYPE, /* tp_flags */
622 tuple_doc, /* tp_doc */
623 (traverseproc)tupletraverse, /* tp_traverse */
624 0, /* tp_clear */
625 tuplerichcompare, /* tp_richcompare */
626 0, /* tp_weaklistoffset */
627 0, /* tp_iter */
628 0, /* tp_iternext */
629 0, /* tp_methods */
630 0, /* tp_members */
631 0, /* tp_getset */
632 0, /* tp_base */
633 0, /* tp_dict */
634 0, /* tp_descr_get */
635 0, /* tp_descr_set */
636 0, /* tp_dictoffset */
637 0, /* tp_init */
638 0, /* tp_alloc */
639 tuple_new, /* tp_new */
640 PyObject_GC_Del, /* tp_free */
643 /* The following function breaks the notion that tuples are immutable:
644 it changes the size of a tuple. We get away with this only if there
645 is only one module referencing the object. You can also think of it
646 as creating a new tuple object and destroying the old one, only more
647 efficiently. In any case, don't use this if the tuple may already be
648 known to some other part of the code. */
651 _PyTuple_Resize(PyObject **pv, int newsize)
653 register PyTupleObject *v;
654 register PyTupleObject *sv;
655 int i;
656 int oldsize;
658 v = (PyTupleObject *) *pv;
659 if (v == NULL || v->ob_type != &PyTuple_Type ||
660 (v->ob_size != 0 && v->ob_refcnt != 1)) {
661 *pv = 0;
662 Py_XDECREF(v);
663 PyErr_BadInternalCall();
664 return -1;
666 oldsize = v->ob_size;
667 if (oldsize == newsize)
668 return 0;
670 if (oldsize == 0) {
671 /* Empty tuples are often shared, so we should never
672 resize them in-place even if we do own the only
673 (current) reference */
674 Py_DECREF(v);
675 *pv = PyTuple_New(newsize);
676 return *pv == NULL ? -1 : 0;
679 /* XXX UNREF/NEWREF interface should be more symmetrical */
680 _Py_DEC_REFTOTAL;
681 _PyObject_GC_UNTRACK(v);
682 _Py_ForgetReference((PyObject *) v);
683 /* DECREF items deleted by shrinkage */
684 for (i = newsize; i < oldsize; i++) {
685 Py_XDECREF(v->ob_item[i]);
686 v->ob_item[i] = NULL;
688 sv = PyObject_GC_Resize(PyTupleObject, v, newsize);
689 if (sv == NULL) {
690 *pv = NULL;
691 PyObject_GC_Del(v);
692 return -1;
694 _Py_NewReference((PyObject *) sv);
695 /* Zero out items added by growing */
696 if (newsize > oldsize)
697 memset(&sv->ob_item[oldsize], 0,
698 sizeof(*sv->ob_item) * (newsize - oldsize));
699 *pv = (PyObject *) sv;
700 _PyObject_GC_TRACK(sv);
701 return 0;
704 void
705 PyTuple_Fini(void)
707 #if MAXSAVESIZE > 0
708 int i;
710 Py_XDECREF(free_tuples[0]);
711 free_tuples[0] = NULL;
713 for (i = 1; i < MAXSAVESIZE; i++) {
714 PyTupleObject *p, *q;
715 p = free_tuples[i];
716 free_tuples[i] = NULL;
717 while (p) {
718 q = p;
719 p = (PyTupleObject *)(p->ob_item[0]);
720 PyObject_GC_Del(q);
723 #endif