2 /* Tuple object implementation */
6 /* Speed optimization to avoid frequent malloc/free of small tuples */
8 #define MAXSAVESIZE 20 /* Largest tuple to save on free list */
10 #ifndef MAXSAVEDTUPLES
11 #define MAXSAVEDTUPLES 2000 /* Maximum number of tuples of each size to save */
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
];
22 int fast_tuple_allocs
;
23 int tuple_zero_allocs
;
27 PyTuple_New(register Py_ssize_t size
)
29 register PyTupleObject
*op
;
32 PyErr_BadInternalCall();
36 if (size
== 0 && free_tuples
[0]) {
42 return (PyObject
*) op
;
44 if (size
< MAXSAVESIZE
&& (op
= free_tuples
[size
]) != NULL
) {
45 free_tuples
[size
] = (PyTupleObject
*) op
->ob_item
[0];
46 num_free_tuples
[size
]--;
50 /* Inline PyObject_InitVar */
53 op
->ob_type
= &PyTuple_Type
;
55 _Py_NewReference((PyObject
*)op
);
60 Py_ssize_t nbytes
= size
* sizeof(PyObject
*);
61 /* Check for overflow */
62 if (nbytes
/ sizeof(PyObject
*) != (size_t)size
||
63 (nbytes
+= sizeof(PyTupleObject
) - sizeof(PyObject
*))
66 return PyErr_NoMemory();
68 op
= PyObject_GC_NewVar(PyTupleObject
, &PyTuple_Type
, size
);
72 for (i
=0; i
< size
; i
++)
73 op
->ob_item
[i
] = NULL
;
78 Py_INCREF(op
); /* extra INCREF so that this is never freed */
81 _PyObject_GC_TRACK(op
);
82 return (PyObject
*) op
;
86 PyTuple_Size(register PyObject
*op
)
88 if (!PyTuple_Check(op
)) {
89 PyErr_BadInternalCall();
93 return ((PyTupleObject
*)op
)->ob_size
;
97 PyTuple_GetItem(register PyObject
*op
, register Py_ssize_t i
)
99 if (!PyTuple_Check(op
)) {
100 PyErr_BadInternalCall();
103 if (i
< 0 || i
>= ((PyTupleObject
*)op
) -> ob_size
) {
104 PyErr_SetString(PyExc_IndexError
, "tuple index out of range");
107 return ((PyTupleObject
*)op
) -> ob_item
[i
];
111 PyTuple_SetItem(register PyObject
*op
, register Py_ssize_t i
, PyObject
*newitem
)
113 register PyObject
*olditem
;
114 register PyObject
**p
;
115 if (!PyTuple_Check(op
) || op
->ob_refcnt
!= 1) {
117 PyErr_BadInternalCall();
120 if (i
< 0 || i
>= ((PyTupleObject
*)op
) -> ob_size
) {
122 PyErr_SetString(PyExc_IndexError
,
123 "tuple assignment index out of range");
126 p
= ((PyTupleObject
*)op
) -> ob_item
+ i
;
134 PyTuple_Pack(Py_ssize_t n
, ...)
143 result
= PyTuple_New(n
);
146 items
= ((PyTupleObject
*)result
)->ob_item
;
147 for (i
= 0; i
< n
; i
++) {
148 o
= va_arg(vargs
, PyObject
*);
160 tupledealloc(register PyTupleObject
*op
)
162 register Py_ssize_t i
;
163 register Py_ssize_t len
= op
->ob_size
;
164 PyObject_GC_UnTrack(op
);
165 Py_TRASHCAN_SAFE_BEGIN(op
)
169 Py_XDECREF(op
->ob_item
[i
]);
171 if (len
< MAXSAVESIZE
&&
172 num_free_tuples
[len
] < MAXSAVEDTUPLES
&&
173 op
->ob_type
== &PyTuple_Type
)
175 op
->ob_item
[0] = (PyObject
*) free_tuples
[len
];
176 num_free_tuples
[len
]++;
177 free_tuples
[len
] = op
;
178 goto done
; /* return */
182 op
->ob_type
->tp_free((PyObject
*)op
);
184 Py_TRASHCAN_SAFE_END(op
)
188 tupleprint(PyTupleObject
*op
, FILE *fp
, int flags
)
192 for (i
= 0; i
< op
->ob_size
; i
++) {
195 if (PyObject_Print(op
->ob_item
[i
], fp
, 0) != 0)
198 if (op
->ob_size
== 1)
205 tuplerepr(PyTupleObject
*v
)
209 PyObject
*pieces
, *result
= NULL
;
213 return PyString_FromString("()");
215 pieces
= PyTuple_New(n
);
219 /* Do repr() on each element. */
220 for (i
= 0; i
< n
; ++i
) {
221 s
= PyObject_Repr(v
->ob_item
[i
]);
224 PyTuple_SET_ITEM(pieces
, i
, s
);
227 /* Add "()" decorations to the first and last items. */
229 s
= PyString_FromString("(");
232 temp
= PyTuple_GET_ITEM(pieces
, 0);
233 PyString_ConcatAndDel(&s
, temp
);
234 PyTuple_SET_ITEM(pieces
, 0, s
);
238 s
= PyString_FromString(n
== 1 ? ",)" : ")");
241 temp
= PyTuple_GET_ITEM(pieces
, n
-1);
242 PyString_ConcatAndDel(&temp
, s
);
243 PyTuple_SET_ITEM(pieces
, n
-1, temp
);
247 /* Paste them all together with ", " between. */
248 s
= PyString_FromString(", ");
251 result
= _PyString_Join(s
, pieces
);
259 /* The addend 82520, was selected from the range(0, 1000000) for
260 generating the greatest number of prime multipliers for tuples
263 1082527, 1165049, 1082531, 1165057, 1247581, 1330103, 1082533,
264 1330111, 1412633, 1165069, 1247599, 1495177, 1577699
268 tuplehash(PyTupleObject
*v
)
271 register Py_ssize_t len
= v
->ob_size
;
272 register PyObject
**p
;
273 long mult
= 1000003L;
277 y
= PyObject_Hash(*p
++);
281 /* the cast might truncate len; that doesn't change hash stability */
282 mult
+= (long)(82520L + len
+ len
);
291 tuplelength(PyTupleObject
*a
)
297 tuplecontains(PyTupleObject
*a
, PyObject
*el
)
302 for (i
= 0, cmp
= 0 ; cmp
== 0 && i
< a
->ob_size
; ++i
)
303 cmp
= PyObject_RichCompareBool(el
, PyTuple_GET_ITEM(a
, i
),
309 tupleitem(register PyTupleObject
*a
, register Py_ssize_t i
)
311 if (i
< 0 || i
>= a
->ob_size
) {
312 PyErr_SetString(PyExc_IndexError
, "tuple index out of range");
315 Py_INCREF(a
->ob_item
[i
]);
316 return a
->ob_item
[i
];
320 tupleslice(register PyTupleObject
*a
, register Py_ssize_t ilow
,
321 register Py_ssize_t ihigh
)
323 register PyTupleObject
*np
;
324 PyObject
**src
, **dest
;
325 register Py_ssize_t i
;
329 if (ihigh
> a
->ob_size
)
333 if (ilow
== 0 && ihigh
== a
->ob_size
&& PyTuple_CheckExact(a
)) {
335 return (PyObject
*)a
;
338 np
= (PyTupleObject
*)PyTuple_New(len
);
341 src
= a
->ob_item
+ ilow
;
343 for (i
= 0; i
< len
; i
++) {
344 PyObject
*v
= src
[i
];
348 return (PyObject
*)np
;
352 PyTuple_GetSlice(PyObject
*op
, Py_ssize_t i
, Py_ssize_t j
)
354 if (op
== NULL
|| !PyTuple_Check(op
)) {
355 PyErr_BadInternalCall();
358 return tupleslice((PyTupleObject
*)op
, i
, j
);
362 tupleconcat(register PyTupleObject
*a
, register PyObject
*bb
)
364 register Py_ssize_t size
;
365 register Py_ssize_t i
;
366 PyObject
**src
, **dest
;
368 if (!PyTuple_Check(bb
)) {
369 PyErr_Format(PyExc_TypeError
,
370 "can only concatenate tuple (not \"%.200s\") to tuple",
371 bb
->ob_type
->tp_name
);
374 #define b ((PyTupleObject *)bb)
375 size
= a
->ob_size
+ b
->ob_size
;
377 return PyErr_NoMemory();
378 np
= (PyTupleObject
*) PyTuple_New(size
);
384 for (i
= 0; i
< a
->ob_size
; i
++) {
385 PyObject
*v
= src
[i
];
390 dest
= np
->ob_item
+ a
->ob_size
;
391 for (i
= 0; i
< b
->ob_size
; i
++) {
392 PyObject
*v
= src
[i
];
396 return (PyObject
*)np
;
401 tuplerepeat(PyTupleObject
*a
, Py_ssize_t n
)
406 PyObject
**p
, **items
;
409 if (a
->ob_size
== 0 || n
== 1) {
410 if (PyTuple_CheckExact(a
)) {
411 /* Since tuples are immutable, we can return a shared
414 return (PyObject
*)a
;
417 return PyTuple_New(0);
419 size
= a
->ob_size
* n
;
420 if (size
/a
->ob_size
!= n
)
421 return PyErr_NoMemory();
422 np
= (PyTupleObject
*) PyTuple_New(size
);
427 for (i
= 0; i
< n
; i
++) {
428 for (j
= 0; j
< a
->ob_size
; j
++) {
434 return (PyObject
*) np
;
438 tupletraverse(PyTupleObject
*o
, visitproc visit
, void *arg
)
442 for (i
= o
->ob_size
; --i
>= 0; )
443 Py_VISIT(o
->ob_item
[i
]);
448 tuplerichcompare(PyObject
*v
, PyObject
*w
, int op
)
450 PyTupleObject
*vt
, *wt
;
452 Py_ssize_t vlen
, wlen
;
454 if (!PyTuple_Check(v
) || !PyTuple_Check(w
)) {
455 Py_INCREF(Py_NotImplemented
);
456 return Py_NotImplemented
;
459 vt
= (PyTupleObject
*)v
;
460 wt
= (PyTupleObject
*)w
;
465 /* Note: the corresponding code for lists has an "early out" test
466 * here when op is EQ or NE and the lengths differ. That pays there,
467 * but Tim was unable to find any real code where EQ/NE tuple
468 * compares don't have the same length, so testing for it here would
469 * have cost without benefit.
472 /* Search for the first index where items are different.
473 * Note that because tuples are immutable, it's safe to reuse
474 * vlen and wlen across the comparison calls.
476 for (i
= 0; i
< vlen
&& i
< wlen
; i
++) {
477 int k
= PyObject_RichCompareBool(vt
->ob_item
[i
],
478 wt
->ob_item
[i
], Py_EQ
);
485 if (i
>= vlen
|| i
>= wlen
) {
486 /* No more items to compare -- compare sizes */
490 case Py_LT
: cmp
= vlen
< wlen
; break;
491 case Py_LE
: cmp
= vlen
<= wlen
; break;
492 case Py_EQ
: cmp
= vlen
== wlen
; break;
493 case Py_NE
: cmp
= vlen
!= wlen
; break;
494 case Py_GT
: cmp
= vlen
> wlen
; break;
495 case Py_GE
: cmp
= vlen
>= wlen
; break;
496 default: return NULL
; /* cannot happen */
506 /* We have an item that differs -- shortcuts for EQ/NE */
516 /* Compare the final item again using the proper operator */
517 return PyObject_RichCompare(vt
->ob_item
[i
], wt
->ob_item
[i
], op
);
521 tuple_subtype_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
);
524 tuple_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
526 PyObject
*arg
= NULL
;
527 static char *kwlist
[] = {"sequence", 0};
529 if (type
!= &PyTuple_Type
)
530 return tuple_subtype_new(type
, args
, kwds
);
531 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "|O:tuple", kwlist
, &arg
))
535 return PyTuple_New(0);
537 return PySequence_Tuple(arg
);
541 tuple_subtype_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
543 PyObject
*tmp
, *newobj
, *item
;
546 assert(PyType_IsSubtype(type
, &PyTuple_Type
));
547 tmp
= tuple_new(&PyTuple_Type
, args
, kwds
);
550 assert(PyTuple_Check(tmp
));
551 newobj
= type
->tp_alloc(type
, n
= PyTuple_GET_SIZE(tmp
));
554 for (i
= 0; i
< n
; i
++) {
555 item
= PyTuple_GET_ITEM(tmp
, i
);
557 PyTuple_SET_ITEM(newobj
, i
, item
);
563 PyDoc_STRVAR(tuple_doc
,
564 "tuple() -> an empty tuple\n"
565 "tuple(sequence) -> tuple initialized from sequence's items\n"
567 "If the argument is a tuple, the return value is the same object.");
569 static PySequenceMethods tuple_as_sequence
= {
570 (lenfunc
)tuplelength
, /* sq_length */
571 (binaryfunc
)tupleconcat
, /* sq_concat */
572 (ssizeargfunc
)tuplerepeat
, /* sq_repeat */
573 (ssizeargfunc
)tupleitem
, /* sq_item */
574 (ssizessizeargfunc
)tupleslice
, /* sq_slice */
576 0, /* sq_ass_slice */
577 (objobjproc
)tuplecontains
, /* sq_contains */
580 #define HASINDEX(o) PyType_HasFeature((o)->ob_type, Py_TPFLAGS_HAVE_INDEX)
583 tuplesubscript(PyTupleObject
* self
, PyObject
* item
)
585 PyNumberMethods
*nb
= item
->ob_type
->tp_as_number
;
586 if (nb
!= NULL
&& HASINDEX(item
) && nb
->nb_index
!= NULL
) {
587 Py_ssize_t i
= nb
->nb_index(item
);
588 if (i
== -1 && PyErr_Occurred())
591 i
+= PyTuple_GET_SIZE(self
);
592 return tupleitem(self
, i
);
594 else if (PySlice_Check(item
)) {
595 Py_ssize_t start
, stop
, step
, slicelength
, cur
, i
;
598 PyObject
**src
, **dest
;
600 if (PySlice_GetIndicesEx((PySliceObject
*)item
,
601 PyTuple_GET_SIZE(self
),
602 &start
, &stop
, &step
, &slicelength
) < 0) {
606 if (slicelength
<= 0) {
607 return PyTuple_New(0);
610 result
= PyTuple_New(slicelength
);
611 if (!result
) return NULL
;
614 dest
= ((PyTupleObject
*)result
)->ob_item
;
615 for (cur
= start
, i
= 0; i
< slicelength
;
626 PyErr_SetString(PyExc_TypeError
,
627 "tuple indices must be integers");
633 tuple_getnewargs(PyTupleObject
*v
)
635 return Py_BuildValue("(N)", tupleslice(v
, 0, v
->ob_size
));
639 static PyMethodDef tuple_methods
[] = {
640 {"__getnewargs__", (PyCFunction
)tuple_getnewargs
, METH_NOARGS
},
641 {NULL
, NULL
} /* sentinel */
644 static PyMappingMethods tuple_as_mapping
= {
645 (lenfunc
)tuplelength
,
646 (binaryfunc
)tuplesubscript
,
650 static PyObject
*tuple_iter(PyObject
*seq
);
652 PyTypeObject PyTuple_Type
= {
653 PyObject_HEAD_INIT(&PyType_Type
)
656 sizeof(PyTupleObject
) - sizeof(PyObject
*),
658 (destructor
)tupledealloc
, /* tp_dealloc */
659 (printfunc
)tupleprint
, /* tp_print */
663 (reprfunc
)tuplerepr
, /* tp_repr */
664 0, /* tp_as_number */
665 &tuple_as_sequence
, /* tp_as_sequence */
666 &tuple_as_mapping
, /* tp_as_mapping */
667 (hashfunc
)tuplehash
, /* tp_hash */
670 PyObject_GenericGetAttr
, /* tp_getattro */
672 0, /* tp_as_buffer */
673 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_HAVE_GC
|
674 Py_TPFLAGS_BASETYPE
, /* tp_flags */
675 tuple_doc
, /* tp_doc */
676 (traverseproc
)tupletraverse
, /* tp_traverse */
678 tuplerichcompare
, /* tp_richcompare */
679 0, /* tp_weaklistoffset */
680 tuple_iter
, /* tp_iter */
682 tuple_methods
, /* tp_methods */
687 0, /* tp_descr_get */
688 0, /* tp_descr_set */
689 0, /* tp_dictoffset */
692 tuple_new
, /* tp_new */
693 PyObject_GC_Del
, /* tp_free */
696 /* The following function breaks the notion that tuples are immutable:
697 it changes the size of a tuple. We get away with this only if there
698 is only one module referencing the object. You can also think of it
699 as creating a new tuple object and destroying the old one, only more
700 efficiently. In any case, don't use this if the tuple may already be
701 known to some other part of the code. */
704 _PyTuple_Resize(PyObject
**pv
, Py_ssize_t newsize
)
706 register PyTupleObject
*v
;
707 register PyTupleObject
*sv
;
711 v
= (PyTupleObject
*) *pv
;
712 if (v
== NULL
|| v
->ob_type
!= &PyTuple_Type
||
713 (v
->ob_size
!= 0 && v
->ob_refcnt
!= 1)) {
716 PyErr_BadInternalCall();
719 oldsize
= v
->ob_size
;
720 if (oldsize
== newsize
)
724 /* Empty tuples are often shared, so we should never
725 resize them in-place even if we do own the only
726 (current) reference */
728 *pv
= PyTuple_New(newsize
);
729 return *pv
== NULL
? -1 : 0;
732 /* XXX UNREF/NEWREF interface should be more symmetrical */
734 _PyObject_GC_UNTRACK(v
);
735 _Py_ForgetReference((PyObject
*) v
);
736 /* DECREF items deleted by shrinkage */
737 for (i
= newsize
; i
< oldsize
; i
++) {
738 Py_XDECREF(v
->ob_item
[i
]);
739 v
->ob_item
[i
] = NULL
;
741 sv
= PyObject_GC_Resize(PyTupleObject
, v
, newsize
);
747 _Py_NewReference((PyObject
*) sv
);
748 /* Zero out items added by growing */
749 if (newsize
> oldsize
)
750 memset(&sv
->ob_item
[oldsize
], 0,
751 sizeof(*sv
->ob_item
) * (newsize
- oldsize
));
752 *pv
= (PyObject
*) sv
;
753 _PyObject_GC_TRACK(sv
);
763 Py_XDECREF(free_tuples
[0]);
764 free_tuples
[0] = NULL
;
766 for (i
= 1; i
< MAXSAVESIZE
; i
++) {
767 PyTupleObject
*p
, *q
;
769 free_tuples
[i
] = NULL
;
772 p
= (PyTupleObject
*)(p
->ob_item
[0]);
779 /*********************** Tuple Iterator **************************/
784 PyTupleObject
*it_seq
; /* Set to NULL when iterator is exhausted */
788 tupleiter_dealloc(tupleiterobject
*it
)
790 _PyObject_GC_UNTRACK(it
);
791 Py_XDECREF(it
->it_seq
);
796 tupleiter_traverse(tupleiterobject
*it
, visitproc visit
, void *arg
)
798 Py_VISIT(it
->it_seq
);
803 tupleiter_next(tupleiterobject
*it
)
812 assert(PyTuple_Check(seq
));
814 if (it
->it_index
< PyTuple_GET_SIZE(seq
)) {
815 item
= PyTuple_GET_ITEM(seq
, it
->it_index
);
827 tupleiter_len(tupleiterobject
*it
)
831 len
= PyTuple_GET_SIZE(it
->it_seq
) - it
->it_index
;
832 return PyInt_FromSsize_t(len
);
835 PyDoc_STRVAR(length_hint_doc
, "Private method returning an estimate of len(list(it)).");
837 static PyMethodDef tupleiter_methods
[] = {
838 {"__length_hint__", (PyCFunction
)tupleiter_len
, METH_NOARGS
, length_hint_doc
},
839 {NULL
, NULL
} /* sentinel */
842 PyTypeObject PyTupleIter_Type
= {
843 PyObject_HEAD_INIT(&PyType_Type
)
845 "tupleiterator", /* tp_name */
846 sizeof(tupleiterobject
), /* tp_basicsize */
849 (destructor
)tupleiter_dealloc
, /* tp_dealloc */
855 0, /* tp_as_number */
856 0, /* tp_as_sequence */
857 0, /* tp_as_mapping */
861 PyObject_GenericGetAttr
, /* tp_getattro */
863 0, /* tp_as_buffer */
864 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_HAVE_GC
,/* tp_flags */
866 (traverseproc
)tupleiter_traverse
, /* tp_traverse */
868 0, /* tp_richcompare */
869 0, /* tp_weaklistoffset */
870 PyObject_SelfIter
, /* tp_iter */
871 (iternextfunc
)tupleiter_next
, /* tp_iternext */
872 tupleiter_methods
, /* tp_methods */
877 tuple_iter(PyObject
*seq
)
881 if (!PyTuple_Check(seq
)) {
882 PyErr_BadInternalCall();
885 it
= PyObject_GC_New(tupleiterobject
, &PyTupleIter_Type
);
890 it
->it_seq
= (PyTupleObject
*)seq
;
891 _PyObject_GC_TRACK(it
);
892 return (PyObject
*)it
;