blob: c0b59c009a2e944bf5707785901b7872e3acb6f5 [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* Tuple object implementation */
3
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004#include "Python.h"
Victor Stinnera15e2602020-04-08 02:01:56 +02005#include "pycore_abstract.h" // _PyIndex_Check()
Victor Stinnere281f7d2018-11-01 02:30:36 +01006#include "pycore_accu.h"
Victor Stinnere5014be2020-04-14 17:52:15 +02007#include "pycore_gc.h" // _PyObject_GC_IS_TRACKED()
8#include "pycore_object.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00009
Serhiy Storchaka0b561592017-03-19 08:47:58 +020010/*[clinic input]
11class tuple "PyTupleObject *" "&PyTuple_Type"
12[clinic start generated code]*/
13/*[clinic end generated code: output=da39a3ee5e6b4b0d input=f051ba3cfdf9a189]*/
14
15#include "clinic/tupleobject.c.h"
16
Guido van Rossum5ce78f82000-04-21 21:15:05 +000017/* Speed optimization to avoid frequent malloc/free of small tuples */
Christian Heimes2202f872008-02-06 14:31:34 +000018#ifndef PyTuple_MAXSAVESIZE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000019#define PyTuple_MAXSAVESIZE 20 /* Largest tuple to save on free list */
Guido van Rossum5ce78f82000-04-21 21:15:05 +000020#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000021#ifndef PyTuple_MAXFREELIST
Christian Heimes2202f872008-02-06 14:31:34 +000022#define PyTuple_MAXFREELIST 2000 /* Maximum number of tuples of each size to save */
Sjoerd Mullender842d2cc1993-10-15 16:18:48 +000023#endif
24
Victor Stinnerb4b53862020-05-05 19:55:29 +020025/* bpo-40521: tuple free lists are shared by all interpreters. */
26#ifdef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
27# undef PyTuple_MAXSAVESIZE
28# define PyTuple_MAXSAVESIZE 0
29#endif
30
Christian Heimes2202f872008-02-06 14:31:34 +000031#if PyTuple_MAXSAVESIZE > 0
32/* Entries 1 up to PyTuple_MAXSAVESIZE are free lists, entry 0 is the empty
Sjoerd Mullender842d2cc1993-10-15 16:18:48 +000033 tuple () of which at most one instance will be allocated.
34*/
Christian Heimes2202f872008-02-06 14:31:34 +000035static PyTupleObject *free_list[PyTuple_MAXSAVESIZE];
36static int numfree[PyTuple_MAXSAVESIZE];
Sjoerd Mullender842d2cc1993-10-15 16:18:48 +000037#endif
Antoine Pitrou3a652b12009-03-23 18:52:06 +000038
Sergey Fedoseev4fa10dd2019-08-14 19:10:33 +050039static inline void
40tuple_gc_track(PyTupleObject *op)
41{
Sergey Fedoseev4fa10dd2019-08-14 19:10:33 +050042 _PyObject_GC_TRACK(op);
43}
44
David Malcolm49526f42012-06-22 14:55:41 -040045/* Print summary info about the state of the optimized allocator */
46void
47_PyTuple_DebugMallocStats(FILE *out)
48{
49#if PyTuple_MAXSAVESIZE > 0
50 int i;
51 char buf[128];
52 for (i = 1; i < PyTuple_MAXSAVESIZE; i++) {
53 PyOS_snprintf(buf, sizeof(buf),
54 "free %d-sized PyTupleObject", i);
55 _PyDebugAllocatorStats(out,
56 buf,
57 numfree[i], _PyObject_VAR_SIZE(&PyTuple_Type, i));
58 }
59#endif
60}
Antoine Pitrou3a652b12009-03-23 18:52:06 +000061
Sergey Fedoseev4fa10dd2019-08-14 19:10:33 +050062/* Allocate an uninitialized tuple object. Before making it public following
63 steps must be done:
64 - initialize its items
65 - call tuple_gc_track() on it
66 Because the empty tuple is always reused and it's already tracked by GC,
67 this function must not be called with size == 0 (unless from PyTuple_New()
68 which wraps this function).
69*/
70static PyTupleObject *
71tuple_alloc(Py_ssize_t size)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000072{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020073 PyTupleObject *op;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000074 if (size < 0) {
75 PyErr_BadInternalCall();
76 return NULL;
77 }
Christian Heimes2202f872008-02-06 14:31:34 +000078#if PyTuple_MAXSAVESIZE > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000079 if (size < PyTuple_MAXSAVESIZE && (op = free_list[size]) != NULL) {
Sergey Fedoseev4fa10dd2019-08-14 19:10:33 +050080 assert(size != 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000081 free_list[size] = (PyTupleObject *) op->ob_item[0];
82 numfree[size]--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000083 /* Inline PyObject_InitVar */
Guido van Rossum68055ce1998-12-11 14:56:38 +000084#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000085 Py_SIZE(op) = size;
86 Py_TYPE(op) = &PyTuple_Type;
Guido van Rossum68055ce1998-12-11 14:56:38 +000087#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000088 _Py_NewReference((PyObject *)op);
89 }
90 else
Sjoerd Mullender842d2cc1993-10-15 16:18:48 +000091#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000092 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000093 /* Check for overflow */
Sergey Fedoseev755d4ef2019-09-10 01:40:58 +050094 if ((size_t)size > ((size_t)PY_SSIZE_T_MAX - (sizeof(PyTupleObject) -
95 sizeof(PyObject *))) / sizeof(PyObject *)) {
Sergey Fedoseev4fa10dd2019-08-14 19:10:33 +050096 return (PyTupleObject *)PyErr_NoMemory();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000097 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000098 op = PyObject_GC_NewVar(PyTupleObject, &PyTuple_Type, size);
99 if (op == NULL)
100 return NULL;
101 }
Sergey Fedoseev4fa10dd2019-08-14 19:10:33 +0500102 return op;
103}
104
105PyObject *
106PyTuple_New(Py_ssize_t size)
107{
108 PyTupleObject *op;
109#if PyTuple_MAXSAVESIZE > 0
110 if (size == 0 && free_list[0]) {
111 op = free_list[0];
112 Py_INCREF(op);
Sergey Fedoseev4fa10dd2019-08-14 19:10:33 +0500113 return (PyObject *) op;
114 }
115#endif
116 op = tuple_alloc(size);
Zackery Spytz60bd1f82019-09-04 07:58:05 -0600117 if (op == NULL) {
118 return NULL;
119 }
Sergey Fedoseev4fa10dd2019-08-14 19:10:33 +0500120 for (Py_ssize_t i = 0; i < size; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000121 op->ob_item[i] = NULL;
Sergey Fedoseev4fa10dd2019-08-14 19:10:33 +0500122 }
Christian Heimes2202f872008-02-06 14:31:34 +0000123#if PyTuple_MAXSAVESIZE > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000124 if (size == 0) {
125 free_list[0] = op;
126 ++numfree[0];
127 Py_INCREF(op); /* extra INCREF so that this is never freed */
128 }
Sjoerd Mullender842d2cc1993-10-15 16:18:48 +0000129#endif
Sergey Fedoseev4fa10dd2019-08-14 19:10:33 +0500130 tuple_gc_track(op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000131 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000132}
133
Martin v. Löwis18e16552006-02-15 17:27:45 +0000134Py_ssize_t
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200135PyTuple_Size(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000136{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000137 if (!PyTuple_Check(op)) {
138 PyErr_BadInternalCall();
139 return -1;
140 }
141 else
142 return Py_SIZE(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000143}
144
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000145PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200146PyTuple_GetItem(PyObject *op, Py_ssize_t i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000147{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000148 if (!PyTuple_Check(op)) {
149 PyErr_BadInternalCall();
150 return NULL;
151 }
152 if (i < 0 || i >= Py_SIZE(op)) {
153 PyErr_SetString(PyExc_IndexError, "tuple index out of range");
154 return NULL;
155 }
156 return ((PyTupleObject *)op) -> ob_item[i];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000157}
158
159int
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200160PyTuple_SetItem(PyObject *op, Py_ssize_t i, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000161{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200162 PyObject **p;
Victor Stinnera93c51e2020-02-07 00:38:59 +0100163 if (!PyTuple_Check(op) || Py_REFCNT(op) != 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000164 Py_XDECREF(newitem);
165 PyErr_BadInternalCall();
166 return -1;
167 }
168 if (i < 0 || i >= Py_SIZE(op)) {
169 Py_XDECREF(newitem);
170 PyErr_SetString(PyExc_IndexError,
171 "tuple assignment index out of range");
172 return -1;
173 }
174 p = ((PyTupleObject *)op) -> ob_item + i;
Serhiy Storchakaec397562016-04-06 09:50:03 +0300175 Py_XSETREF(*p, newitem);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000176 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000177}
178
Antoine Pitrou3a652b12009-03-23 18:52:06 +0000179void
180_PyTuple_MaybeUntrack(PyObject *op)
181{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000182 PyTupleObject *t;
183 Py_ssize_t i, n;
184
185 if (!PyTuple_CheckExact(op) || !_PyObject_GC_IS_TRACKED(op))
186 return;
187 t = (PyTupleObject *) op;
188 n = Py_SIZE(t);
189 for (i = 0; i < n; i++) {
190 PyObject *elt = PyTuple_GET_ITEM(t, i);
191 /* Tuple with NULL elements aren't
192 fully constructed, don't untrack
193 them yet. */
194 if (!elt ||
195 _PyObject_GC_MAY_BE_TRACKED(elt))
196 return;
197 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000198 _PyObject_GC_UNTRACK(op);
Antoine Pitrou3a652b12009-03-23 18:52:06 +0000199}
200
Raymond Hettingercb2da432003-10-12 18:24:34 +0000201PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000202PyTuple_Pack(Py_ssize_t n, ...)
Raymond Hettingercb2da432003-10-12 18:24:34 +0000203{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000204 Py_ssize_t i;
205 PyObject *o;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000206 PyObject **items;
207 va_list vargs;
Raymond Hettingercb2da432003-10-12 18:24:34 +0000208
Sergey Fedoseev4fa10dd2019-08-14 19:10:33 +0500209 if (n == 0) {
210 return PyTuple_New(0);
211 }
212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000213 va_start(vargs, n);
Sergey Fedoseev4fa10dd2019-08-14 19:10:33 +0500214 PyTupleObject *result = tuple_alloc(n);
Christian Heimesd5a88042012-09-10 02:54:51 +0200215 if (result == NULL) {
216 va_end(vargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000217 return NULL;
Christian Heimesd5a88042012-09-10 02:54:51 +0200218 }
Sergey Fedoseev4fa10dd2019-08-14 19:10:33 +0500219 items = result->ob_item;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000220 for (i = 0; i < n; i++) {
221 o = va_arg(vargs, PyObject *);
222 Py_INCREF(o);
223 items[i] = o;
224 }
225 va_end(vargs);
Sergey Fedoseev4fa10dd2019-08-14 19:10:33 +0500226 tuple_gc_track(result);
227 return (PyObject *)result;
Raymond Hettingercb2da432003-10-12 18:24:34 +0000228}
229
230
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000231/* Methods */
232
233static void
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200234tupledealloc(PyTupleObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000235{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200236 Py_ssize_t i;
237 Py_ssize_t len = Py_SIZE(op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000238 PyObject_GC_UnTrack(op);
Jeroen Demeyer351c6742019-05-10 19:21:11 +0200239 Py_TRASHCAN_BEGIN(op, tupledealloc)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000240 if (len > 0) {
241 i = len;
242 while (--i >= 0)
243 Py_XDECREF(op->ob_item[i]);
Christian Heimes2202f872008-02-06 14:31:34 +0000244#if PyTuple_MAXSAVESIZE > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 if (len < PyTuple_MAXSAVESIZE &&
246 numfree[len] < PyTuple_MAXFREELIST &&
Andy Lesterdffe4c02020-03-04 07:15:20 -0600247 Py_IS_TYPE(op, &PyTuple_Type))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000248 {
249 op->ob_item[0] = (PyObject *) free_list[len];
250 numfree[len]++;
251 free_list[len] = op;
252 goto done; /* return */
253 }
Sjoerd Mullender842d2cc1993-10-15 16:18:48 +0000254#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000255 }
256 Py_TYPE(op)->tp_free((PyObject *)op);
Victor Stinnerb4b53862020-05-05 19:55:29 +0200257#if PyTuple_MAXSAVESIZE > 0
Guido van Rossumd724b232000-03-13 16:01:29 +0000258done:
Victor Stinnerb4b53862020-05-05 19:55:29 +0200259#endif
Jeroen Demeyer351c6742019-05-10 19:21:11 +0200260 Py_TRASHCAN_END
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000261}
262
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000263static PyObject *
Fred Drakeba096332000-07-09 07:04:36 +0000264tuplerepr(PyTupleObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000265{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000266 Py_ssize_t i, n;
Victor Stinner88a9cd92013-11-19 12:59:46 +0100267 _PyUnicodeWriter writer;
Tim Petersa7259592001-06-16 05:11:17 +0000268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000269 n = Py_SIZE(v);
270 if (n == 0)
271 return PyUnicode_FromString("()");
Tim Petersa7259592001-06-16 05:11:17 +0000272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000273 /* While not mutable, it is still possible to end up with a cycle in a
274 tuple through an object that stores itself within a tuple (and thus
275 infinitely asks for the repr of itself). This should only be
276 possible within a type. */
277 i = Py_ReprEnter((PyObject *)v);
278 if (i != 0) {
279 return i > 0 ? PyUnicode_FromString("(...)") : NULL;
280 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000281
Victor Stinner88a9cd92013-11-19 12:59:46 +0100282 _PyUnicodeWriter_Init(&writer);
283 writer.overallocate = 1;
284 if (Py_SIZE(v) > 1) {
285 /* "(" + "1" + ", 2" * (len - 1) + ")" */
286 writer.min_length = 1 + 1 + (2 + 1) * (Py_SIZE(v) - 1) + 1;
287 }
288 else {
289 /* "(1,)" */
290 writer.min_length = 4;
291 }
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200292
Victor Stinner88a9cd92013-11-19 12:59:46 +0100293 if (_PyUnicodeWriter_WriteChar(&writer, '(') < 0)
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200294 goto error;
Tim Petersa7259592001-06-16 05:11:17 +0000295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000296 /* Do repr() on each element. */
297 for (i = 0; i < n; ++i) {
Victor Stinner88a9cd92013-11-19 12:59:46 +0100298 PyObject *s;
299
300 if (i > 0) {
301 if (_PyUnicodeWriter_WriteASCIIString(&writer, ", ", 2) < 0)
302 goto error;
303 }
304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000305 s = PyObject_Repr(v->ob_item[i]);
Victor Stinner88a9cd92013-11-19 12:59:46 +0100306 if (s == NULL)
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200307 goto error;
Victor Stinner88a9cd92013-11-19 12:59:46 +0100308
309 if (_PyUnicodeWriter_WriteStr(&writer, s) < 0) {
310 Py_DECREF(s);
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200311 goto error;
Victor Stinner88a9cd92013-11-19 12:59:46 +0100312 }
313 Py_DECREF(s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000314 }
Victor Stinner88a9cd92013-11-19 12:59:46 +0100315
316 writer.overallocate = 0;
317 if (n > 1) {
318 if (_PyUnicodeWriter_WriteChar(&writer, ')') < 0)
319 goto error;
320 }
321 else {
322 if (_PyUnicodeWriter_WriteASCIIString(&writer, ",)", 2) < 0)
323 goto error;
324 }
Tim Petersa7259592001-06-16 05:11:17 +0000325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000326 Py_ReprLeave((PyObject *)v);
Victor Stinner88a9cd92013-11-19 12:59:46 +0100327 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200328
329error:
Victor Stinner88a9cd92013-11-19 12:59:46 +0100330 _PyUnicodeWriter_Dealloc(&writer);
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200331 Py_ReprLeave((PyObject *)v);
332 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000333}
334
Raymond Hettinger4ec44e82004-06-04 06:35:20 +0000335
jdemeyeraeb1be52018-10-28 02:06:38 +0200336/* Hash for tuples. This is a slightly simplified version of the xxHash
337 non-cryptographic hash:
338 - we do not use any parallellism, there is only 1 accumulator.
339 - we drop the final mixing since this is just a permutation of the
340 output space: it does not help against collisions.
341 - at the end, we mangle the length with a single constant.
342 For the xxHash specification, see
343 https://github.com/Cyan4973/xxHash/blob/master/doc/xxhash_spec.md
Christian Heimes34bdeb52013-01-07 21:24:18 +0100344
jdemeyeraeb1be52018-10-28 02:06:38 +0200345 Below are the official constants from the xxHash specification. Optimizing
346 compilers should emit a single "rotate" instruction for the
347 _PyHASH_XXROTATE() expansion. If that doesn't happen for some important
348 platform, the macro could be changed to expand to a platform-specific rotate
349 spelling instead.
Raymond Hettinger4ec44e82004-06-04 06:35:20 +0000350*/
jdemeyeraeb1be52018-10-28 02:06:38 +0200351#if SIZEOF_PY_UHASH_T > 4
352#define _PyHASH_XXPRIME_1 ((Py_uhash_t)11400714785074694791ULL)
353#define _PyHASH_XXPRIME_2 ((Py_uhash_t)14029467366897019727ULL)
354#define _PyHASH_XXPRIME_5 ((Py_uhash_t)2870177450012600261ULL)
355#define _PyHASH_XXROTATE(x) ((x << 31) | (x >> 33)) /* Rotate left 31 bits */
356#else
357#define _PyHASH_XXPRIME_1 ((Py_uhash_t)2654435761UL)
358#define _PyHASH_XXPRIME_2 ((Py_uhash_t)2246822519UL)
359#define _PyHASH_XXPRIME_5 ((Py_uhash_t)374761393UL)
360#define _PyHASH_XXROTATE(x) ((x << 13) | (x >> 19)) /* Rotate left 13 bits */
361#endif
Raymond Hettinger4ec44e82004-06-04 06:35:20 +0000362
jdemeyeraeb1be52018-10-28 02:06:38 +0200363/* Tests have shown that it's not worth to cache the hash value, see
364 https://bugs.python.org/issue9685 */
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000365static Py_hash_t
Fred Drakeba096332000-07-09 07:04:36 +0000366tuplehash(PyTupleObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000367{
jdemeyeraeb1be52018-10-28 02:06:38 +0200368 Py_ssize_t i, len = Py_SIZE(v);
369 PyObject **item = v->ob_item;
370
371 Py_uhash_t acc = _PyHASH_XXPRIME_5;
372 for (i = 0; i < len; i++) {
373 Py_uhash_t lane = PyObject_Hash(item[i]);
374 if (lane == (Py_uhash_t)-1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 return -1;
jdemeyeraeb1be52018-10-28 02:06:38 +0200376 }
377 acc += lane * _PyHASH_XXPRIME_2;
378 acc = _PyHASH_XXROTATE(acc);
379 acc *= _PyHASH_XXPRIME_1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000380 }
jdemeyeraeb1be52018-10-28 02:06:38 +0200381
382 /* Add input length, mangled to keep the historical value of hash(()). */
383 acc += len ^ (_PyHASH_XXPRIME_5 ^ 3527539UL);
384
385 if (acc == (Py_uhash_t)-1) {
386 return 1546275796;
387 }
388 return acc;
Guido van Rossum9bfef441993-03-29 10:43:31 +0000389}
390
Martin v. Löwis18e16552006-02-15 17:27:45 +0000391static Py_ssize_t
Fred Drakeba096332000-07-09 07:04:36 +0000392tuplelength(PyTupleObject *a)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000393{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000394 return Py_SIZE(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000395}
396
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000397static int
Fred Drakeba096332000-07-09 07:04:36 +0000398tuplecontains(PyTupleObject *a, PyObject *el)
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000399{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000400 Py_ssize_t i;
401 int cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000403 for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(a); ++i)
Serhiy Storchaka18b711c2019-08-04 14:12:48 +0300404 cmp = PyObject_RichCompareBool(PyTuple_GET_ITEM(a, i), el, Py_EQ);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000405 return cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000406}
407
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000408static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200409tupleitem(PyTupleObject *a, Py_ssize_t i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000410{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 if (i < 0 || i >= Py_SIZE(a)) {
412 PyErr_SetString(PyExc_IndexError, "tuple index out of range");
413 return NULL;
414 }
415 Py_INCREF(a->ob_item[i]);
416 return a->ob_item[i];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000417}
418
Sergey Fedoseev234531b2019-02-25 21:59:12 +0500419PyObject *
420_PyTuple_FromArray(PyObject *const *src, Py_ssize_t n)
421{
Sergey Fedoseev4fa10dd2019-08-14 19:10:33 +0500422 if (n == 0) {
423 return PyTuple_New(0);
424 }
425
426 PyTupleObject *tuple = tuple_alloc(n);
Sergey Fedoseev234531b2019-02-25 21:59:12 +0500427 if (tuple == NULL) {
428 return NULL;
429 }
430 PyObject **dst = tuple->ob_item;
431 for (Py_ssize_t i = 0; i < n; i++) {
432 PyObject *item = src[i];
433 Py_INCREF(item);
434 dst[i] = item;
435 }
Sergey Fedoseev4fa10dd2019-08-14 19:10:33 +0500436 tuple_gc_track(tuple);
Sergey Fedoseev234531b2019-02-25 21:59:12 +0500437 return (PyObject *)tuple;
438}
439
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000440static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200441tupleslice(PyTupleObject *a, Py_ssize_t ilow,
442 Py_ssize_t ihigh)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000443{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000444 if (ilow < 0)
445 ilow = 0;
446 if (ihigh > Py_SIZE(a))
447 ihigh = Py_SIZE(a);
448 if (ihigh < ilow)
449 ihigh = ilow;
450 if (ilow == 0 && ihigh == Py_SIZE(a) && PyTuple_CheckExact(a)) {
451 Py_INCREF(a);
452 return (PyObject *)a;
453 }
Sergey Fedoseev234531b2019-02-25 21:59:12 +0500454 return _PyTuple_FromArray(a->ob_item + ilow, ihigh - ilow);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000455}
456
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000457PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000458PyTuple_GetSlice(PyObject *op, Py_ssize_t i, Py_ssize_t j)
Guido van Rossum7c36ad71992-01-14 18:45:33 +0000459{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 if (op == NULL || !PyTuple_Check(op)) {
461 PyErr_BadInternalCall();
462 return NULL;
463 }
464 return tupleslice((PyTupleObject *)op, i, j);
Guido van Rossum7c36ad71992-01-14 18:45:33 +0000465}
466
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000467static PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200468tupleconcat(PyTupleObject *a, PyObject *bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000469{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200470 Py_ssize_t size;
471 Py_ssize_t i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 PyObject **src, **dest;
473 PyTupleObject *np;
Serhiy Storchaka98e80c22017-03-06 23:39:35 +0200474 if (Py_SIZE(a) == 0 && PyTuple_CheckExact(bb)) {
475 Py_INCREF(bb);
476 return bb;
477 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 if (!PyTuple_Check(bb)) {
479 PyErr_Format(PyExc_TypeError,
480 "can only concatenate tuple (not \"%.200s\") to tuple",
481 Py_TYPE(bb)->tp_name);
482 return NULL;
483 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000484#define b ((PyTupleObject *)bb)
Serhiy Storchaka98e80c22017-03-06 23:39:35 +0200485 if (Py_SIZE(b) == 0 && PyTuple_CheckExact(a)) {
486 Py_INCREF(a);
487 return (PyObject *)a;
488 }
Martin Panterb93d8632016-07-25 02:39:20 +0000489 if (Py_SIZE(a) > PY_SSIZE_T_MAX - Py_SIZE(b))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 return PyErr_NoMemory();
Martin Panterb93d8632016-07-25 02:39:20 +0000491 size = Py_SIZE(a) + Py_SIZE(b);
Sergey Fedoseev4fa10dd2019-08-14 19:10:33 +0500492 if (size == 0) {
493 return PyTuple_New(0);
494 }
495
496 np = tuple_alloc(size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 if (np == NULL) {
498 return NULL;
499 }
500 src = a->ob_item;
501 dest = np->ob_item;
502 for (i = 0; i < Py_SIZE(a); i++) {
503 PyObject *v = src[i];
504 Py_INCREF(v);
505 dest[i] = v;
506 }
507 src = b->ob_item;
508 dest = np->ob_item + Py_SIZE(a);
509 for (i = 0; i < Py_SIZE(b); i++) {
510 PyObject *v = src[i];
511 Py_INCREF(v);
512 dest[i] = v;
513 }
Sergey Fedoseev4fa10dd2019-08-14 19:10:33 +0500514 tuple_gc_track(np);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000515 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000516#undef b
517}
518
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000519static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000520tuplerepeat(PyTupleObject *a, Py_ssize_t n)
Guido van Rossumb8393da1991-06-04 19:35:24 +0000521{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000522 Py_ssize_t i, j;
523 Py_ssize_t size;
524 PyTupleObject *np;
525 PyObject **p, **items;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 if (Py_SIZE(a) == 0 || n == 1) {
527 if (PyTuple_CheckExact(a)) {
528 /* Since tuples are immutable, we can return a shared
529 copy in this case */
530 Py_INCREF(a);
531 return (PyObject *)a;
532 }
Sergey Fedoseev4fa10dd2019-08-14 19:10:33 +0500533 }
534 if (Py_SIZE(a) == 0 || n <= 0) {
535 return PyTuple_New(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000536 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +0100537 if (n > PY_SSIZE_T_MAX / Py_SIZE(a))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +0100539 size = Py_SIZE(a) * n;
Sergey Fedoseev4fa10dd2019-08-14 19:10:33 +0500540 np = tuple_alloc(size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000541 if (np == NULL)
542 return NULL;
543 p = np->ob_item;
544 items = a->ob_item;
545 for (i = 0; i < n; i++) {
546 for (j = 0; j < Py_SIZE(a); j++) {
547 *p = items[j];
548 Py_INCREF(*p);
549 p++;
550 }
551 }
Sergey Fedoseev4fa10dd2019-08-14 19:10:33 +0500552 tuple_gc_track(np);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000553 return (PyObject *) np;
Guido van Rossumb8393da1991-06-04 19:35:24 +0000554}
555
Serhiy Storchaka0b561592017-03-19 08:47:58 +0200556/*[clinic input]
557tuple.index
Raymond Hettinger65baa342008-02-07 00:41:02 +0000558
Serhiy Storchaka0b561592017-03-19 08:47:58 +0200559 value: object
Serhiy Storchakad4edfc92017-03-30 18:29:23 +0300560 start: slice_index(accept={int}) = 0
561 stop: slice_index(accept={int}, c_default="PY_SSIZE_T_MAX") = sys.maxsize
Serhiy Storchaka0b561592017-03-19 08:47:58 +0200562 /
563
564Return first index of value.
565
566Raises ValueError if the value is not present.
567[clinic start generated code]*/
568
569static PyObject *
570tuple_index_impl(PyTupleObject *self, PyObject *value, Py_ssize_t start,
571 Py_ssize_t stop)
Serhiy Storchakad4edfc92017-03-30 18:29:23 +0300572/*[clinic end generated code: output=07b6f9f3cb5c33eb input=fb39e9874a21fe3f]*/
Serhiy Storchaka0b561592017-03-19 08:47:58 +0200573{
574 Py_ssize_t i;
575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000576 if (start < 0) {
577 start += Py_SIZE(self);
578 if (start < 0)
579 start = 0;
580 }
581 if (stop < 0) {
582 stop += Py_SIZE(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000583 }
Serhiy Storchaka0b561592017-03-19 08:47:58 +0200584 else if (stop > Py_SIZE(self)) {
585 stop = Py_SIZE(self);
586 }
587 for (i = start; i < stop; i++) {
588 int cmp = PyObject_RichCompareBool(self->ob_item[i], value, Py_EQ);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 if (cmp > 0)
590 return PyLong_FromSsize_t(i);
591 else if (cmp < 0)
592 return NULL;
593 }
594 PyErr_SetString(PyExc_ValueError, "tuple.index(x): x not in tuple");
595 return NULL;
Raymond Hettinger65baa342008-02-07 00:41:02 +0000596}
597
Serhiy Storchaka0b561592017-03-19 08:47:58 +0200598/*[clinic input]
599tuple.count
600
601 value: object
602 /
603
604Return number of occurrences of value.
605[clinic start generated code]*/
606
Raymond Hettinger65baa342008-02-07 00:41:02 +0000607static PyObject *
Serhiy Storchaka0b561592017-03-19 08:47:58 +0200608tuple_count(PyTupleObject *self, PyObject *value)
609/*[clinic end generated code: output=aa927affc5a97605 input=531721aff65bd772]*/
Raymond Hettinger65baa342008-02-07 00:41:02 +0000610{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 Py_ssize_t count = 0;
612 Py_ssize_t i;
Raymond Hettinger65baa342008-02-07 00:41:02 +0000613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000614 for (i = 0; i < Py_SIZE(self); i++) {
Serhiy Storchaka0b561592017-03-19 08:47:58 +0200615 int cmp = PyObject_RichCompareBool(self->ob_item[i], value, Py_EQ);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000616 if (cmp > 0)
617 count++;
618 else if (cmp < 0)
619 return NULL;
620 }
621 return PyLong_FromSsize_t(count);
Raymond Hettinger65baa342008-02-07 00:41:02 +0000622}
623
Jeremy Hylton8caad492000-06-23 14:18:11 +0000624static int
625tupletraverse(PyTupleObject *o, visitproc visit, void *arg)
626{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 Py_ssize_t i;
Jeremy Hylton8caad492000-06-23 14:18:11 +0000628
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000629 for (i = Py_SIZE(o); --i >= 0; )
630 Py_VISIT(o->ob_item[i]);
631 return 0;
Jeremy Hylton8caad492000-06-23 14:18:11 +0000632}
633
Guido van Rossumf77bc622001-01-18 00:00:53 +0000634static PyObject *
635tuplerichcompare(PyObject *v, PyObject *w, int op)
636{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000637 PyTupleObject *vt, *wt;
638 Py_ssize_t i;
639 Py_ssize_t vlen, wlen;
Guido van Rossumf77bc622001-01-18 00:00:53 +0000640
Brian Curtindfc80e32011-08-10 20:28:54 -0500641 if (!PyTuple_Check(v) || !PyTuple_Check(w))
642 Py_RETURN_NOTIMPLEMENTED;
Guido van Rossumf77bc622001-01-18 00:00:53 +0000643
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 vt = (PyTupleObject *)v;
645 wt = (PyTupleObject *)w;
Guido van Rossumf77bc622001-01-18 00:00:53 +0000646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 vlen = Py_SIZE(vt);
648 wlen = Py_SIZE(wt);
Guido van Rossumf77bc622001-01-18 00:00:53 +0000649
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 /* Note: the corresponding code for lists has an "early out" test
651 * here when op is EQ or NE and the lengths differ. That pays there,
652 * but Tim was unable to find any real code where EQ/NE tuple
653 * compares don't have the same length, so testing for it here would
654 * have cost without benefit.
655 */
Tim Petersd7ed3bf2001-05-15 20:12:59 +0000656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000657 /* Search for the first index where items are different.
658 * Note that because tuples are immutable, it's safe to reuse
659 * vlen and wlen across the comparison calls.
660 */
661 for (i = 0; i < vlen && i < wlen; i++) {
662 int k = PyObject_RichCompareBool(vt->ob_item[i],
663 wt->ob_item[i], Py_EQ);
664 if (k < 0)
665 return NULL;
666 if (!k)
667 break;
668 }
Guido van Rossumf77bc622001-01-18 00:00:53 +0000669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 if (i >= vlen || i >= wlen) {
671 /* No more items to compare -- compare sizes */
stratakise8b19652017-11-02 11:32:54 +0100672 Py_RETURN_RICHCOMPARE(vlen, wlen, op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000673 }
Guido van Rossumf77bc622001-01-18 00:00:53 +0000674
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000675 /* We have an item that differs -- shortcuts for EQ/NE */
676 if (op == Py_EQ) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200677 Py_RETURN_FALSE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000678 }
679 if (op == Py_NE) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200680 Py_RETURN_TRUE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000681 }
Guido van Rossumf77bc622001-01-18 00:00:53 +0000682
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000683 /* Compare the final item again using the proper operator */
684 return PyObject_RichCompare(vt->ob_item[i], wt->ob_item[i], op);
Guido van Rossumf77bc622001-01-18 00:00:53 +0000685}
686
Jeremy Hylton938ace62002-07-17 16:30:39 +0000687static PyObject *
Serhiy Storchaka0b561592017-03-19 08:47:58 +0200688tuple_subtype_new(PyTypeObject *type, PyObject *iterable);
689
690/*[clinic input]
691@classmethod
692tuple.__new__ as tuple_new
693 iterable: object(c_default="NULL") = ()
694 /
695
696Built-in immutable sequence.
697
698If no argument is given, the constructor returns an empty tuple.
699If iterable is specified the tuple is initialized from iterable's items.
700
701If the argument is a tuple, the return value is the same object.
702[clinic start generated code]*/
Guido van Rossumae960af2001-08-30 03:11:59 +0000703
Tim Peters6d6c1a32001-08-02 04:15:00 +0000704static PyObject *
Serhiy Storchaka0b561592017-03-19 08:47:58 +0200705tuple_new_impl(PyTypeObject *type, PyObject *iterable)
706/*[clinic end generated code: output=4546d9f0d469bce7 input=86963bcde633b5a2]*/
Tim Peters6d6c1a32001-08-02 04:15:00 +0000707{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708 if (type != &PyTuple_Type)
Serhiy Storchaka0b561592017-03-19 08:47:58 +0200709 return tuple_subtype_new(type, iterable);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000710
Serhiy Storchaka0b561592017-03-19 08:47:58 +0200711 if (iterable == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000712 return PyTuple_New(0);
713 else
Serhiy Storchaka0b561592017-03-19 08:47:58 +0200714 return PySequence_Tuple(iterable);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000715}
716
Guido van Rossumae960af2001-08-30 03:11:59 +0000717static PyObject *
Dong-hee Na9ee88cd2020-03-13 22:57:00 +0900718tuple_vectorcall(PyObject *type, PyObject * const*args,
719 size_t nargsf, PyObject *kwnames)
720{
Dong-hee Na87ec86c2020-03-16 23:06:20 +0900721 if (!_PyArg_NoKwnames("tuple", kwnames)) {
Dong-hee Na9ee88cd2020-03-13 22:57:00 +0900722 return NULL;
723 }
Dong-hee Nac98f87f2020-03-16 23:04:14 +0900724
Dong-hee Na9ee88cd2020-03-13 22:57:00 +0900725 Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
Dong-hee Nac98f87f2020-03-16 23:04:14 +0900726 if (!_PyArg_CheckPositional("tuple", nargs, 0, 1)) {
Dong-hee Na9ee88cd2020-03-13 22:57:00 +0900727 return NULL;
728 }
729
730 if (nargs) {
731 return tuple_new_impl((PyTypeObject *)type, args[0]);
732 }
733 return PyTuple_New(0);
734}
735
736static PyObject *
Serhiy Storchaka0b561592017-03-19 08:47:58 +0200737tuple_subtype_new(PyTypeObject *type, PyObject *iterable)
Guido van Rossumae960af2001-08-30 03:11:59 +0000738{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 PyObject *tmp, *newobj, *item;
740 Py_ssize_t i, n;
Guido van Rossumae960af2001-08-30 03:11:59 +0000741
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000742 assert(PyType_IsSubtype(type, &PyTuple_Type));
Serhiy Storchaka0b561592017-03-19 08:47:58 +0200743 tmp = tuple_new_impl(&PyTuple_Type, iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000744 if (tmp == NULL)
745 return NULL;
746 assert(PyTuple_Check(tmp));
747 newobj = type->tp_alloc(type, n = PyTuple_GET_SIZE(tmp));
Hai Shic81609e2020-03-16 03:37:49 +0800748 if (newobj == NULL) {
749 Py_DECREF(tmp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000750 return NULL;
Hai Shic81609e2020-03-16 03:37:49 +0800751 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000752 for (i = 0; i < n; i++) {
753 item = PyTuple_GET_ITEM(tmp, i);
754 Py_INCREF(item);
755 PyTuple_SET_ITEM(newobj, i, item);
756 }
757 Py_DECREF(tmp);
758 return newobj;
Guido van Rossumae960af2001-08-30 03:11:59 +0000759}
760
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000761static PySequenceMethods tuple_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000762 (lenfunc)tuplelength, /* sq_length */
763 (binaryfunc)tupleconcat, /* sq_concat */
764 (ssizeargfunc)tuplerepeat, /* sq_repeat */
765 (ssizeargfunc)tupleitem, /* sq_item */
766 0, /* sq_slice */
767 0, /* sq_ass_item */
768 0, /* sq_ass_slice */
769 (objobjproc)tuplecontains, /* sq_contains */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000770};
771
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +0000772static PyObject*
773tuplesubscript(PyTupleObject* self, PyObject* item)
774{
Victor Stinnera15e2602020-04-08 02:01:56 +0200775 if (_PyIndex_Check(item)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000776 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
777 if (i == -1 && PyErr_Occurred())
778 return NULL;
779 if (i < 0)
780 i += PyTuple_GET_SIZE(self);
781 return tupleitem(self, i);
782 }
783 else if (PySlice_Check(item)) {
Zackery Spytz14514d92019-05-17 01:13:03 -0600784 Py_ssize_t start, stop, step, slicelength, i;
785 size_t cur;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000786 PyObject* it;
787 PyObject **src, **dest;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +0000788
Serhiy Storchakab879fe82017-04-08 09:53:51 +0300789 if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 return NULL;
791 }
Serhiy Storchakab879fe82017-04-08 09:53:51 +0300792 slicelength = PySlice_AdjustIndices(PyTuple_GET_SIZE(self), &start,
793 &stop, step);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +0000794
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000795 if (slicelength <= 0) {
796 return PyTuple_New(0);
797 }
798 else if (start == 0 && step == 1 &&
799 slicelength == PyTuple_GET_SIZE(self) &&
800 PyTuple_CheckExact(self)) {
801 Py_INCREF(self);
802 return (PyObject *)self;
803 }
804 else {
Sergey Fedoseev4fa10dd2019-08-14 19:10:33 +0500805 PyTupleObject* result = tuple_alloc(slicelength);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000806 if (!result) return NULL;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +0000807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 src = self->ob_item;
Sergey Fedoseev4fa10dd2019-08-14 19:10:33 +0500809 dest = result->ob_item;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000810 for (cur = start, i = 0; i < slicelength;
811 cur += step, i++) {
812 it = src[cur];
813 Py_INCREF(it);
814 dest[i] = it;
815 }
816
Sergey Fedoseev4fa10dd2019-08-14 19:10:33 +0500817 tuple_gc_track(result);
818 return (PyObject *)result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000819 }
820 }
821 else {
822 PyErr_Format(PyExc_TypeError,
Terry Jan Reedyffff1442014-08-02 01:30:37 -0400823 "tuple indices must be integers or slices, not %.200s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000824 Py_TYPE(item)->tp_name);
825 return NULL;
826 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +0000827}
828
Serhiy Storchaka0b561592017-03-19 08:47:58 +0200829/*[clinic input]
830tuple.__getnewargs__
831[clinic start generated code]*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000832
Serhiy Storchaka0b561592017-03-19 08:47:58 +0200833static PyObject *
834tuple___getnewargs___impl(PyTupleObject *self)
835/*[clinic end generated code: output=25e06e3ee56027e2 input=1aeb4b286a21639a]*/
836{
837 return Py_BuildValue("(N)", tupleslice(self, 0, Py_SIZE(self)));
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000838}
839
840static PyMethodDef tuple_methods[] = {
Serhiy Storchaka0b561592017-03-19 08:47:58 +0200841 TUPLE___GETNEWARGS___METHODDEF
842 TUPLE_INDEX_METHODDEF
843 TUPLE_COUNT_METHODDEF
Guido van Rossum48b069a2020-04-07 09:50:06 -0700844 {"__class_getitem__", (PyCFunction)Py_GenericAlias, METH_O|METH_CLASS, PyDoc_STR("See PEP 585")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000845 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000846};
847
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +0000848static PyMappingMethods tuple_as_mapping = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 (lenfunc)tuplelength,
850 (binaryfunc)tuplesubscript,
851 0
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +0000852};
853
Raymond Hettinger48923c52002-08-09 01:30:17 +0000854static PyObject *tuple_iter(PyObject *seq);
855
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000856PyTypeObject PyTuple_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000857 PyVarObject_HEAD_INIT(&PyType_Type, 0)
858 "tuple",
859 sizeof(PyTupleObject) - sizeof(PyObject *),
860 sizeof(PyObject *),
861 (destructor)tupledealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200862 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000863 0, /* tp_getattr */
864 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +0200865 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 (reprfunc)tuplerepr, /* tp_repr */
867 0, /* tp_as_number */
868 &tuple_as_sequence, /* tp_as_sequence */
869 &tuple_as_mapping, /* tp_as_mapping */
870 (hashfunc)tuplehash, /* tp_hash */
871 0, /* tp_call */
872 0, /* tp_str */
873 PyObject_GenericGetAttr, /* tp_getattro */
874 0, /* tp_setattro */
875 0, /* tp_as_buffer */
876 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
877 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TUPLE_SUBCLASS, /* tp_flags */
Serhiy Storchaka0b561592017-03-19 08:47:58 +0200878 tuple_new__doc__, /* tp_doc */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000879 (traverseproc)tupletraverse, /* tp_traverse */
880 0, /* tp_clear */
881 tuplerichcompare, /* tp_richcompare */
882 0, /* tp_weaklistoffset */
883 tuple_iter, /* tp_iter */
884 0, /* tp_iternext */
885 tuple_methods, /* tp_methods */
886 0, /* tp_members */
887 0, /* tp_getset */
888 0, /* tp_base */
889 0, /* tp_dict */
890 0, /* tp_descr_get */
891 0, /* tp_descr_set */
892 0, /* tp_dictoffset */
893 0, /* tp_init */
894 0, /* tp_alloc */
895 tuple_new, /* tp_new */
896 PyObject_GC_Del, /* tp_free */
Dong-hee Na9ee88cd2020-03-13 22:57:00 +0900897 .tp_vectorcall = tuple_vectorcall,
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000898};
Guido van Rossum12d12c51993-10-26 17:58:25 +0000899
900/* The following function breaks the notion that tuples are immutable:
901 it changes the size of a tuple. We get away with this only if there
902 is only one module referencing the object. You can also think of it
Neil Schemenauer08b53e62000-10-05 19:36:49 +0000903 as creating a new tuple object and destroying the old one, only more
904 efficiently. In any case, don't use this if the tuple may already be
Tim Peters4324aa32001-05-28 22:30:08 +0000905 known to some other part of the code. */
Guido van Rossum12d12c51993-10-26 17:58:25 +0000906
907int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000908_PyTuple_Resize(PyObject **pv, Py_ssize_t newsize)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000909{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200910 PyTupleObject *v;
911 PyTupleObject *sv;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000912 Py_ssize_t i;
913 Py_ssize_t oldsize;
Sjoerd Mullender615194a1993-11-01 13:46:50 +0000914
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000915 v = (PyTupleObject *) *pv;
Andy Lester55728702020-03-06 16:53:17 -0600916 if (v == NULL || !Py_IS_TYPE(v, &PyTuple_Type) ||
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000917 (Py_SIZE(v) != 0 && Py_REFCNT(v) != 1)) {
918 *pv = 0;
919 Py_XDECREF(v);
920 PyErr_BadInternalCall();
921 return -1;
922 }
923 oldsize = Py_SIZE(v);
924 if (oldsize == newsize)
925 return 0;
Neil Schemenauer08b53e62000-10-05 19:36:49 +0000926
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000927 if (oldsize == 0) {
928 /* Empty tuples are often shared, so we should never
929 resize them in-place even if we do own the only
930 (current) reference */
931 Py_DECREF(v);
932 *pv = PyTuple_New(newsize);
933 return *pv == NULL ? -1 : 0;
934 }
Thomas Wouters6a922372001-05-28 13:11:02 +0000935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 /* XXX UNREF/NEWREF interface should be more symmetrical */
Victor Stinner49932fe2020-02-03 17:55:05 +0100937#ifdef Py_REF_DEBUG
938 _Py_RefTotal--;
939#endif
940 if (_PyObject_GC_IS_TRACKED(v)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 _PyObject_GC_UNTRACK(v);
Victor Stinner49932fe2020-02-03 17:55:05 +0100942 }
943#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000944 _Py_ForgetReference((PyObject *) v);
Victor Stinner49932fe2020-02-03 17:55:05 +0100945#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 /* DECREF items deleted by shrinkage */
947 for (i = newsize; i < oldsize; i++) {
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200948 Py_CLEAR(v->ob_item[i]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 }
950 sv = PyObject_GC_Resize(PyTupleObject, v, newsize);
951 if (sv == NULL) {
952 *pv = NULL;
953 PyObject_GC_Del(v);
954 return -1;
955 }
956 _Py_NewReference((PyObject *) sv);
957 /* Zero out items added by growing */
958 if (newsize > oldsize)
959 memset(&sv->ob_item[oldsize], 0,
960 sizeof(*sv->ob_item) * (newsize - oldsize));
961 *pv = (PyObject *) sv;
962 _PyObject_GC_TRACK(sv);
963 return 0;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000964}
Guido van Rossumfbbd57e1997-08-05 02:16:08 +0000965
Victor Stinnerae00a5a2020-04-29 02:29:20 +0200966void
967_PyTuple_ClearFreeList(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +0000968{
Christian Heimes2202f872008-02-06 14:31:34 +0000969#if PyTuple_MAXSAVESIZE > 0
Victor Stinnerae00a5a2020-04-29 02:29:20 +0200970 for (Py_ssize_t i = 1; i < PyTuple_MAXSAVESIZE; i++) {
971 PyTupleObject *p = free_list[i];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 free_list[i] = NULL;
973 numfree[i] = 0;
974 while (p) {
Victor Stinnerae00a5a2020-04-29 02:29:20 +0200975 PyTupleObject *q = p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000976 p = (PyTupleObject *)(p->ob_item[0]);
977 PyObject_GC_Del(q);
978 }
979 }
Victor Stinnerae00a5a2020-04-29 02:29:20 +0200980 // the empty tuple singleton is only cleared by _PyTuple_Fini()
Guido van Rossumfbbd57e1997-08-05 02:16:08 +0000981#endif
Christian Heimesa156e092008-02-16 07:38:31 +0000982}
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000983
Christian Heimesa156e092008-02-16 07:38:31 +0000984void
Victor Stinnerbed48172019-08-27 00:12:32 +0200985_PyTuple_Fini(void)
Christian Heimesa156e092008-02-16 07:38:31 +0000986{
987#if PyTuple_MAXSAVESIZE > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000988 /* empty tuples are used all over the place and applications may
989 * rely on the fact that an empty tuple is a singleton. */
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200990 Py_CLEAR(free_list[0]);
Christian Heimesa156e092008-02-16 07:38:31 +0000991
Victor Stinnerae00a5a2020-04-29 02:29:20 +0200992 _PyTuple_ClearFreeList();
Christian Heimesa156e092008-02-16 07:38:31 +0000993#endif
Guido van Rossumfbbd57e1997-08-05 02:16:08 +0000994}
Raymond Hettinger48923c52002-08-09 01:30:17 +0000995
996/*********************** Tuple Iterator **************************/
997
998typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 PyObject_HEAD
Victor Stinnera2d56982013-06-05 00:11:34 +02001000 Py_ssize_t it_index;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001001 PyTupleObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger48923c52002-08-09 01:30:17 +00001002} tupleiterobject;
1003
Raymond Hettinger48923c52002-08-09 01:30:17 +00001004static void
1005tupleiter_dealloc(tupleiterobject *it)
1006{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007 _PyObject_GC_UNTRACK(it);
1008 Py_XDECREF(it->it_seq);
1009 PyObject_GC_Del(it);
Raymond Hettinger48923c52002-08-09 01:30:17 +00001010}
1011
1012static int
1013tupleiter_traverse(tupleiterobject *it, visitproc visit, void *arg)
1014{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 Py_VISIT(it->it_seq);
1016 return 0;
Raymond Hettinger48923c52002-08-09 01:30:17 +00001017}
1018
Raymond Hettinger48923c52002-08-09 01:30:17 +00001019static PyObject *
1020tupleiter_next(tupleiterobject *it)
1021{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001022 PyTupleObject *seq;
1023 PyObject *item;
Raymond Hettinger48923c52002-08-09 01:30:17 +00001024
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001025 assert(it != NULL);
1026 seq = it->it_seq;
1027 if (seq == NULL)
1028 return NULL;
1029 assert(PyTuple_Check(seq));
Raymond Hettinger48923c52002-08-09 01:30:17 +00001030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 if (it->it_index < PyTuple_GET_SIZE(seq)) {
1032 item = PyTuple_GET_ITEM(seq, it->it_index);
1033 ++it->it_index;
1034 Py_INCREF(item);
1035 return item;
1036 }
Raymond Hettinger48923c52002-08-09 01:30:17 +00001037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 it->it_seq = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03001039 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 return NULL;
Raymond Hettinger48923c52002-08-09 01:30:17 +00001041}
1042
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001043static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301044tupleiter_len(tupleiterobject *it, PyObject *Py_UNUSED(ignored))
Raymond Hettinger435bf582004-03-18 22:43:10 +00001045{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 Py_ssize_t len = 0;
1047 if (it->it_seq)
1048 len = PyTuple_GET_SIZE(it->it_seq) - it->it_index;
1049 return PyLong_FromSsize_t(len);
Raymond Hettinger435bf582004-03-18 22:43:10 +00001050}
1051
Armin Rigof5b3e362006-02-11 21:32:43 +00001052PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001053
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001054static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301055tupleiter_reduce(tupleiterobject *it, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001056{
Serhiy Storchakabb86bf42018-12-11 08:28:18 +02001057 _Py_IDENTIFIER(iter);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001058 if (it->it_seq)
Serhiy Storchakabb86bf42018-12-11 08:28:18 +02001059 return Py_BuildValue("N(O)n", _PyEval_GetBuiltinId(&PyId_iter),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001060 it->it_seq, it->it_index);
1061 else
Serhiy Storchakabb86bf42018-12-11 08:28:18 +02001062 return Py_BuildValue("N(())", _PyEval_GetBuiltinId(&PyId_iter));
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001063}
1064
1065static PyObject *
1066tupleiter_setstate(tupleiterobject *it, PyObject *state)
1067{
Victor Stinner7660b882013-06-24 23:59:24 +02001068 Py_ssize_t index = PyLong_AsSsize_t(state);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001069 if (index == -1 && PyErr_Occurred())
1070 return NULL;
1071 if (it->it_seq != NULL) {
1072 if (index < 0)
1073 index = 0;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +00001074 else if (index > PyTuple_GET_SIZE(it->it_seq))
1075 index = PyTuple_GET_SIZE(it->it_seq); /* exhausted iterator */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001076 it->it_index = index;
1077 }
1078 Py_RETURN_NONE;
1079}
1080
1081PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
1082PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
1083
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001084static PyMethodDef tupleiter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001085 {"__length_hint__", (PyCFunction)tupleiter_len, METH_NOARGS, length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001086 {"__reduce__", (PyCFunction)tupleiter_reduce, METH_NOARGS, reduce_doc},
1087 {"__setstate__", (PyCFunction)tupleiter_setstate, METH_O, setstate_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001088 {NULL, NULL} /* sentinel */
Raymond Hettinger435bf582004-03-18 22:43:10 +00001089};
1090
Raymond Hettinger48923c52002-08-09 01:30:17 +00001091PyTypeObject PyTupleIter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001092 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1093 "tuple_iterator", /* tp_name */
1094 sizeof(tupleiterobject), /* tp_basicsize */
1095 0, /* tp_itemsize */
1096 /* methods */
1097 (destructor)tupleiter_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001098 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001099 0, /* tp_getattr */
1100 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001101 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001102 0, /* tp_repr */
1103 0, /* tp_as_number */
1104 0, /* tp_as_sequence */
1105 0, /* tp_as_mapping */
1106 0, /* tp_hash */
1107 0, /* tp_call */
1108 0, /* tp_str */
1109 PyObject_GenericGetAttr, /* tp_getattro */
1110 0, /* tp_setattro */
1111 0, /* tp_as_buffer */
1112 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
1113 0, /* tp_doc */
1114 (traverseproc)tupleiter_traverse, /* tp_traverse */
1115 0, /* tp_clear */
1116 0, /* tp_richcompare */
1117 0, /* tp_weaklistoffset */
1118 PyObject_SelfIter, /* tp_iter */
1119 (iternextfunc)tupleiter_next, /* tp_iternext */
1120 tupleiter_methods, /* tp_methods */
1121 0,
Raymond Hettinger48923c52002-08-09 01:30:17 +00001122};
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001123
1124static PyObject *
1125tuple_iter(PyObject *seq)
1126{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001127 tupleiterobject *it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001129 if (!PyTuple_Check(seq)) {
1130 PyErr_BadInternalCall();
1131 return NULL;
1132 }
1133 it = PyObject_GC_New(tupleiterobject, &PyTupleIter_Type);
1134 if (it == NULL)
1135 return NULL;
1136 it->it_index = 0;
1137 Py_INCREF(seq);
1138 it->it_seq = (PyTupleObject *)seq;
1139 _PyObject_GC_TRACK(it);
1140 return (PyObject *)it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001141}