blob: ca63f710cd8648c26d527f624a7b9d6a026c3e6a [file] [log] [blame]
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001#include "Python.h"
Victor Stinner37834132020-10-27 17:12:53 +01002#include "pycore_long.h" // _PyLong_GetZero()
Victor Stinner4a21e572020-04-15 02:35:41 +02003#include "structmember.h" // PyMemberDef
Raymond Hettinger756b3f32004-01-29 06:37:52 +00004
Raymond Hettingerc2083082015-02-28 23:29:16 -08005#ifdef STDC_HEADERS
6#include <stddef.h>
7#else
Victor Stinner4a21e572020-04-15 02:35:41 +02008#include <sys/types.h> // size_t
Raymond Hettingerc2083082015-02-28 23:29:16 -08009#endif
10
Pablo Galindo3f5fc702018-12-30 09:24:03 +000011/*[clinic input]
Raymond Hettingere9858042019-06-05 16:05:25 -070012module _collections
Pablo Galindo3f5fc702018-12-30 09:24:03 +000013class _tuplegetter "_tuplegetterobject *" "&tuplegetter_type"
14[clinic start generated code]*/
Raymond Hettingere9858042019-06-05 16:05:25 -070015/*[clinic end generated code: output=da39a3ee5e6b4b0d input=a8ece4ccad7e30ac]*/
Pablo Galindo3f5fc702018-12-30 09:24:03 +000016
17static PyTypeObject tuplegetter_type;
18#include "clinic/_collectionsmodule.c.h"
19
Raymond Hettinger756b3f32004-01-29 06:37:52 +000020/* collections module implementation of a deque() datatype
21 Written and maintained by Raymond D. Hettinger <python@rcn.com>
Raymond Hettinger756b3f32004-01-29 06:37:52 +000022*/
23
Raymond Hettinger77e8bf12004-10-01 15:25:53 +000024/* The block length may be set to any number over 1. Larger numbers
Raymond Hettinger20b0f872013-06-23 15:44:33 -070025 * reduce the number of calls to the memory allocator, give faster
Raymond Hettinger30c90742015-03-02 22:31:35 -080026 * indexing and rotation, and reduce the link to data overhead ratio.
Raymond Hettingerdaf57f22015-02-26 23:21:29 -080027 * Making the block length a power of two speeds-up the modulo
Raymond Hettinger30c90742015-03-02 22:31:35 -080028 * and division calculations in deque_item() and deque_ass_item().
Raymond Hettinger77e8bf12004-10-01 15:25:53 +000029 */
30
Raymond Hettingerdaf57f22015-02-26 23:21:29 -080031#define BLOCKLEN 64
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000032#define CENTER ((BLOCKLEN - 1) / 2)
Raymond Hettinger756b3f32004-01-29 06:37:52 +000033
Raymond Hettinger551350a2015-03-24 00:19:53 -070034/* Data for deque objects is stored in a doubly-linked list of fixed
35 * length blocks. This assures that appends or pops never move any
36 * other data elements besides the one being appended or popped.
37 *
38 * Another advantage is that it completely avoids use of realloc(),
39 * resulting in more predictable performance.
40 *
41 * Textbook implementations of doubly-linked lists store one datum
42 * per link, but that gives them a 200% memory overhead (a prev and
43 * next link for each datum) and it costs one malloc() call per data
44 * element. By using fixed-length blocks, the link to data ratio is
45 * significantly improved and there are proportionally fewer calls
46 * to malloc() and free(). The data blocks of consecutive pointers
47 * also improve cache locality.
48 *
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000049 * The list of blocks is never empty, so d.leftblock and d.rightblock
Raymond Hettinger82df9252013-07-07 01:43:42 -100050 * are never equal to NULL. The list is not circular.
51 *
52 * A deque d's first element is at d.leftblock[leftindex]
53 * and its last element is at d.rightblock[rightindex].
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000054 *
Raymond Hettinger551350a2015-03-24 00:19:53 -070055 * Unlike Python slice indices, these indices are inclusive on both
56 * ends. This makes the algorithms for left and right operations
57 * more symmetrical and it simplifies the design.
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000058 *
Raymond Hettinger551350a2015-03-24 00:19:53 -070059 * The indices, d.leftindex and d.rightindex are always in the range:
60 * 0 <= index < BLOCKLEN
61 *
62 * And their exact relationship is:
63 * (d.leftindex + d.len - 1) % BLOCKLEN == d.rightindex
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000064 *
Raymond Hettinger8dbbae22015-03-24 21:01:50 -070065 * Whenever d.leftblock == d.rightblock, then:
Raymond Hettinger551350a2015-03-24 00:19:53 -070066 * d.leftindex + d.len - 1 == d.rightindex
Thomas Wouters0e3f5912006-08-11 14:57:12 +000067 *
Raymond Hettinger551350a2015-03-24 00:19:53 -070068 * However, when d.leftblock != d.rightblock, the d.leftindex and
69 * d.rightindex become indices into distinct blocks and either may
70 * be larger than the other.
71 *
72 * Empty deques have:
73 * d.len == 0
74 * d.leftblock == d.rightblock
75 * d.leftindex == CENTER + 1
76 * d.rightindex == CENTER
77 *
78 * Checking for d.len == 0 is the intended way to see whether d is empty.
Tim Petersd8768d32004-10-01 01:32:53 +000079 */
80
Raymond Hettinger756b3f32004-01-29 06:37:52 +000081typedef struct BLOCK {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000082 struct BLOCK *leftlink;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000083 PyObject *data[BLOCKLEN];
Raymond Hettinger20b0f872013-06-23 15:44:33 -070084 struct BLOCK *rightlink;
Raymond Hettinger756b3f32004-01-29 06:37:52 +000085} block;
86
Raymond Hettinger30c90742015-03-02 22:31:35 -080087typedef struct {
88 PyObject_VAR_HEAD
89 block *leftblock;
90 block *rightblock;
Raymond Hettinger551350a2015-03-24 00:19:53 -070091 Py_ssize_t leftindex; /* 0 <= leftindex < BLOCKLEN */
92 Py_ssize_t rightindex; /* 0 <= rightindex < BLOCKLEN */
Raymond Hettingerf9d9c792015-03-02 22:47:46 -080093 size_t state; /* incremented whenever the indices move */
Raymond Hettingerd84ec222016-01-24 09:12:06 -080094 Py_ssize_t maxlen; /* maxlen is -1 for unbounded deques */
Raymond Hettinger0f6f9472015-03-21 01:42:10 -070095 PyObject *weakreflist;
Raymond Hettinger30c90742015-03-02 22:31:35 -080096} dequeobject;
97
98static PyTypeObject deque_type;
99
Raymond Hettinger82df9252013-07-07 01:43:42 -1000100/* For debug builds, add error checking to track the endpoints
101 * in the chain of links. The goal is to make sure that link
102 * assignments only take place at endpoints so that links already
103 * in use do not get overwritten.
104 *
105 * CHECK_END should happen before each assignment to a block's link field.
106 * MARK_END should happen whenever a link field becomes a new endpoint.
107 * This happens when new blocks are added or whenever an existing
108 * block is freed leaving another existing block as the new endpoint.
109 */
110
Raymond Hettinger3223dd52013-07-26 23:14:22 -0700111#ifndef NDEBUG
Raymond Hettinger82df9252013-07-07 01:43:42 -1000112#define MARK_END(link) link = NULL;
113#define CHECK_END(link) assert(link == NULL);
114#define CHECK_NOT_END(link) assert(link != NULL);
115#else
116#define MARK_END(link)
117#define CHECK_END(link)
118#define CHECK_NOT_END(link)
119#endif
120
Tim Peters6f853562004-10-01 01:04:50 +0000121static block *
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700122newblock(void) {
Raymond Hettinger32f2eda2020-06-23 06:50:15 -0700123 block *b = PyMem_Malloc(sizeof(block));
Raymond Hettinger82df9252013-07-07 01:43:42 -1000124 if (b != NULL) {
125 return b;
126 }
127 PyErr_NoMemory();
128 return NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000129}
130
Martin v. Löwis59683e82008-06-13 07:50:45 +0000131static void
Guido van Rossum58da9312007-11-10 23:39:45 +0000132freeblock(block *b)
133{
Raymond Hettinger32f2eda2020-06-23 06:50:15 -0700134 PyMem_Free(b);
Guido van Rossum58da9312007-11-10 23:39:45 +0000135}
136
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000137static PyObject *
138deque_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
139{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000140 dequeobject *deque;
141 block *b;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000143 /* create dequeobject structure */
144 deque = (dequeobject *)type->tp_alloc(type, 0);
145 if (deque == NULL)
146 return NULL;
Tim Peters1065f752004-10-01 01:03:29 +0000147
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700148 b = newblock();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000149 if (b == NULL) {
150 Py_DECREF(deque);
151 return NULL;
152 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000153 MARK_END(b->leftlink);
154 MARK_END(b->rightlink);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000155
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000156 assert(BLOCKLEN >= 2);
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100157 Py_SET_SIZE(deque, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000158 deque->leftblock = b;
159 deque->rightblock = b;
160 deque->leftindex = CENTER + 1;
161 deque->rightindex = CENTER;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000162 deque->state = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000163 deque->maxlen = -1;
Raymond Hettinger87e69122015-03-02 23:32:02 -0800164 deque->weakreflist = NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000166 return (PyObject *)deque;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000167}
168
169static PyObject *
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000170deque_pop(dequeobject *deque, PyObject *unused)
171{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000172 PyObject *item;
173 block *prevblock;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000174
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000175 if (Py_SIZE(deque) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000176 PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
177 return NULL;
178 }
179 item = deque->rightblock->data[deque->rightindex];
180 deque->rightindex--;
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100181 Py_SET_SIZE(deque, Py_SIZE(deque) - 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000182 deque->state++;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000183
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -0700184 if (deque->rightindex < 0) {
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700185 if (Py_SIZE(deque)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000186 prevblock = deque->rightblock->leftlink;
187 assert(deque->leftblock != deque->rightblock);
188 freeblock(deque->rightblock);
Raymond Hettinger82df9252013-07-07 01:43:42 -1000189 CHECK_NOT_END(prevblock);
190 MARK_END(prevblock->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000191 deque->rightblock = prevblock;
192 deque->rightindex = BLOCKLEN - 1;
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700193 } else {
194 assert(deque->leftblock == deque->rightblock);
195 assert(deque->leftindex == deque->rightindex+1);
196 /* re-center instead of freeing a block */
197 deque->leftindex = CENTER + 1;
198 deque->rightindex = CENTER;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000199 }
200 }
201 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000202}
203
204PyDoc_STRVAR(pop_doc, "Remove and return the rightmost element.");
205
206static PyObject *
207deque_popleft(dequeobject *deque, PyObject *unused)
208{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000209 PyObject *item;
210 block *prevblock;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000211
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000212 if (Py_SIZE(deque) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000213 PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
214 return NULL;
215 }
216 assert(deque->leftblock != NULL);
217 item = deque->leftblock->data[deque->leftindex];
218 deque->leftindex++;
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100219 Py_SET_SIZE(deque, Py_SIZE(deque) - 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000220 deque->state++;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000222 if (deque->leftindex == BLOCKLEN) {
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700223 if (Py_SIZE(deque)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000224 assert(deque->leftblock != deque->rightblock);
225 prevblock = deque->leftblock->rightlink;
226 freeblock(deque->leftblock);
Raymond Hettinger82df9252013-07-07 01:43:42 -1000227 CHECK_NOT_END(prevblock);
228 MARK_END(prevblock->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000229 deque->leftblock = prevblock;
230 deque->leftindex = 0;
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700231 } else {
232 assert(deque->leftblock == deque->rightblock);
233 assert(deque->leftindex == deque->rightindex+1);
234 /* re-center instead of freeing a block */
235 deque->leftindex = CENTER + 1;
236 deque->rightindex = CENTER;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000237 }
238 }
239 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000240}
241
242PyDoc_STRVAR(popleft_doc, "Remove and return the leftmost element.");
243
Raymond Hettingerf30f5b92015-03-02 22:23:37 -0800244/* The deque's size limit is d.maxlen. The limit can be zero or positive.
245 * If there is no limit, then d.maxlen == -1.
246 *
Raymond Hettingera4b13d02015-10-15 08:05:31 -0700247 * After an item is added to a deque, we check to see if the size has
248 * grown past the limit. If it has, we get the size back down to the limit
249 * by popping an item off of the opposite end. The methods that can
250 * trigger this are append(), appendleft(), extend(), and extendleft().
Raymond Hettingerd96db092015-10-11 22:34:48 -0700251 *
252 * The macro to check whether a deque needs to be trimmed uses a single
253 * unsigned test that returns true whenever 0 <= maxlen < Py_SIZE(deque).
Raymond Hettingerf30f5b92015-03-02 22:23:37 -0800254 */
255
Raymond Hettingerd96db092015-10-11 22:34:48 -0700256#define NEEDS_TRIM(deque, maxlen) ((size_t)(maxlen) < (size_t)(Py_SIZE(deque)))
Raymond Hettingerf30f5b92015-03-02 22:23:37 -0800257
Raymond Hettinger66953f02018-07-10 04:17:40 -0700258static inline int
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800259deque_append_internal(dequeobject *deque, PyObject *item, Py_ssize_t maxlen)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000260{
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700261 if (deque->rightindex == BLOCKLEN - 1) {
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700262 block *b = newblock();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000263 if (b == NULL)
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800264 return -1;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000265 b->leftlink = deque->rightblock;
266 CHECK_END(deque->rightblock->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000267 deque->rightblock->rightlink = b;
268 deque->rightblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000269 MARK_END(b->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000270 deque->rightindex = -1;
271 }
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100272 Py_SET_SIZE(deque, Py_SIZE(deque) + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000273 deque->rightindex++;
274 deque->rightblock->data[deque->rightindex] = item;
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800275 if (NEEDS_TRIM(deque, maxlen)) {
Raymond Hettinger1286d142015-10-14 23:16:57 -0700276 PyObject *olditem = deque_popleft(deque, NULL);
277 Py_DECREF(olditem);
Raymond Hettinger0f43bb12015-10-20 00:03:33 -0700278 } else {
279 deque->state++;
Raymond Hettingerd96db092015-10-11 22:34:48 -0700280 }
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800281 return 0;
282}
283
284static PyObject *
285deque_append(dequeobject *deque, PyObject *item)
286{
287 Py_INCREF(item);
288 if (deque_append_internal(deque, item, deque->maxlen) < 0)
289 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000290 Py_RETURN_NONE;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000291}
292
293PyDoc_STRVAR(append_doc, "Add an element to the right side of the deque.");
294
Raymond Hettinger66953f02018-07-10 04:17:40 -0700295static inline int
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800296deque_appendleft_internal(dequeobject *deque, PyObject *item, Py_ssize_t maxlen)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000297{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000298 if (deque->leftindex == 0) {
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700299 block *b = newblock();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000300 if (b == NULL)
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800301 return -1;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000302 b->rightlink = deque->leftblock;
303 CHECK_END(deque->leftblock->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000304 deque->leftblock->leftlink = b;
305 deque->leftblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000306 MARK_END(b->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000307 deque->leftindex = BLOCKLEN;
308 }
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100309 Py_SET_SIZE(deque, Py_SIZE(deque) + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000310 deque->leftindex--;
311 deque->leftblock->data[deque->leftindex] = item;
Raymond Hettingerd96db092015-10-11 22:34:48 -0700312 if (NEEDS_TRIM(deque, deque->maxlen)) {
Raymond Hettinger1286d142015-10-14 23:16:57 -0700313 PyObject *olditem = deque_pop(deque, NULL);
314 Py_DECREF(olditem);
Raymond Hettinger0f43bb12015-10-20 00:03:33 -0700315 } else {
316 deque->state++;
Raymond Hettingerd96db092015-10-11 22:34:48 -0700317 }
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800318 return 0;
319}
320
321static PyObject *
322deque_appendleft(dequeobject *deque, PyObject *item)
323{
324 Py_INCREF(item);
325 if (deque_appendleft_internal(deque, item, deque->maxlen) < 0)
326 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000327 Py_RETURN_NONE;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000328}
329
330PyDoc_STRVAR(appendleft_doc, "Add an element to the left side of the deque.");
331
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700332static PyObject*
333finalize_iterator(PyObject *it)
334{
335 if (PyErr_Occurred()) {
336 if (PyErr_ExceptionMatches(PyExc_StopIteration))
337 PyErr_Clear();
338 else {
339 Py_DECREF(it);
340 return NULL;
341 }
342 }
343 Py_DECREF(it);
344 Py_RETURN_NONE;
345}
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000347/* Run an iterator to exhaustion. Shortcut for
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000348 the extend/extendleft methods when maxlen == 0. */
349static PyObject*
350consume_iterator(PyObject *it)
351{
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700352 PyObject *(*iternext)(PyObject *);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000353 PyObject *item;
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000354
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700355 iternext = *Py_TYPE(it)->tp_iternext;
356 while ((item = iternext(it)) != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000357 Py_DECREF(item);
358 }
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700359 return finalize_iterator(it);
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000360}
361
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000362static PyObject *
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000363deque_extend(dequeobject *deque, PyObject *iterable)
364{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000365 PyObject *it, *item;
Raymond Hettinger7a845522015-09-26 01:30:51 -0700366 PyObject *(*iternext)(PyObject *);
Raymond Hettinger6b1e1132015-10-11 09:43:50 -0700367 Py_ssize_t maxlen = deque->maxlen;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000369 /* Handle case where id(deque) == id(iterable) */
370 if ((PyObject *)deque == iterable) {
371 PyObject *result;
372 PyObject *s = PySequence_List(iterable);
373 if (s == NULL)
374 return NULL;
375 result = deque_extend(deque, s);
376 Py_DECREF(s);
377 return result;
378 }
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000379
Raymond Hettingerd79d5b12016-03-04 09:55:07 -0800380 it = PyObject_GetIter(iterable);
381 if (it == NULL)
382 return NULL;
383
384 if (maxlen == 0)
385 return consume_iterator(it);
386
Raymond Hettingerd9c116c2013-07-09 00:13:21 -0700387 /* Space saving heuristic. Start filling from the left */
388 if (Py_SIZE(deque) == 0) {
389 assert(deque->leftblock == deque->rightblock);
390 assert(deque->leftindex == deque->rightindex+1);
391 deque->leftindex = 1;
392 deque->rightindex = 0;
393 }
394
Raymond Hettinger7a845522015-09-26 01:30:51 -0700395 iternext = *Py_TYPE(it)->tp_iternext;
396 while ((item = iternext(it)) != NULL) {
Raymond Hettinger66953f02018-07-10 04:17:40 -0700397 if (deque_append_internal(deque, item, maxlen) == -1) {
398 Py_DECREF(item);
399 Py_DECREF(it);
400 return NULL;
Raymond Hettinger6b1e1132015-10-11 09:43:50 -0700401 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000402 }
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700403 return finalize_iterator(it);
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000404}
405
Tim Peters1065f752004-10-01 01:03:29 +0000406PyDoc_STRVAR(extend_doc,
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000407"Extend the right side of the deque with elements from the iterable");
408
409static PyObject *
410deque_extendleft(dequeobject *deque, PyObject *iterable)
411{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000412 PyObject *it, *item;
Raymond Hettinger7a845522015-09-26 01:30:51 -0700413 PyObject *(*iternext)(PyObject *);
Raymond Hettinger6b1e1132015-10-11 09:43:50 -0700414 Py_ssize_t maxlen = deque->maxlen;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000415
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000416 /* Handle case where id(deque) == id(iterable) */
417 if ((PyObject *)deque == iterable) {
418 PyObject *result;
419 PyObject *s = PySequence_List(iterable);
420 if (s == NULL)
421 return NULL;
422 result = deque_extendleft(deque, s);
423 Py_DECREF(s);
424 return result;
425 }
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000426
Raymond Hettingerd79d5b12016-03-04 09:55:07 -0800427 it = PyObject_GetIter(iterable);
428 if (it == NULL)
429 return NULL;
430
431 if (maxlen == 0)
432 return consume_iterator(it);
433
Raymond Hettingerd9c116c2013-07-09 00:13:21 -0700434 /* Space saving heuristic. Start filling from the right */
435 if (Py_SIZE(deque) == 0) {
436 assert(deque->leftblock == deque->rightblock);
437 assert(deque->leftindex == deque->rightindex+1);
438 deque->leftindex = BLOCKLEN - 1;
439 deque->rightindex = BLOCKLEN - 2;
440 }
441
Raymond Hettinger7a845522015-09-26 01:30:51 -0700442 iternext = *Py_TYPE(it)->tp_iternext;
443 while ((item = iternext(it)) != NULL) {
Raymond Hettinger66953f02018-07-10 04:17:40 -0700444 if (deque_appendleft_internal(deque, item, maxlen) == -1) {
445 Py_DECREF(item);
446 Py_DECREF(it);
447 return NULL;
Raymond Hettinger6b1e1132015-10-11 09:43:50 -0700448 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000449 }
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700450 return finalize_iterator(it);
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000451}
452
Tim Peters1065f752004-10-01 01:03:29 +0000453PyDoc_STRVAR(extendleft_doc,
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000454"Extend the left side of the deque with elements from the iterable");
455
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000456static PyObject *
457deque_inplace_concat(dequeobject *deque, PyObject *other)
458{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000459 PyObject *result;
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000460
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 result = deque_extend(deque, other);
462 if (result == NULL)
463 return result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000464 Py_INCREF(deque);
Raymond Hettinger2b2b7532015-09-05 17:05:52 -0700465 Py_DECREF(result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000466 return (PyObject *)deque;
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000467}
468
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700469static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530470deque_copy(PyObject *deque, PyObject *Py_UNUSED(ignored))
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700471{
Oren Milman24bd50b2018-09-11 21:46:55 +0300472 PyObject *result;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700473 dequeobject *old_deque = (dequeobject *)deque;
Andy Lesterdffe4c02020-03-04 07:15:20 -0600474 if (Py_IS_TYPE(deque, &deque_type)) {
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700475 dequeobject *new_deque;
476 PyObject *rv;
477
478 new_deque = (dequeobject *)deque_new(&deque_type, (PyObject *)NULL, (PyObject *)NULL);
479 if (new_deque == NULL)
480 return NULL;
481 new_deque->maxlen = old_deque->maxlen;
482 /* Fast path for the deque_repeat() common case where len(deque) == 1 */
Raymond Hettinger0443ac22015-10-05 22:52:37 -0400483 if (Py_SIZE(deque) == 1) {
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700484 PyObject *item = old_deque->leftblock->data[old_deque->leftindex];
485 rv = deque_append(new_deque, item);
486 } else {
487 rv = deque_extend(new_deque, deque);
488 }
489 if (rv != NULL) {
490 Py_DECREF(rv);
491 return (PyObject *)new_deque;
492 }
493 Py_DECREF(new_deque);
494 return NULL;
495 }
496 if (old_deque->maxlen < 0)
Petr Viktorinffd97532020-02-11 17:46:57 +0100497 result = PyObject_CallOneArg((PyObject *)(Py_TYPE(deque)), deque);
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700498 else
Oren Milman24bd50b2018-09-11 21:46:55 +0300499 result = PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "Oi",
500 deque, old_deque->maxlen, NULL);
501 if (result != NULL && !PyObject_TypeCheck(result, &deque_type)) {
502 PyErr_Format(PyExc_TypeError,
503 "%.200s() must return a deque, not %.200s",
504 Py_TYPE(deque)->tp_name, Py_TYPE(result)->tp_name);
505 Py_DECREF(result);
506 return NULL;
507 }
508 return result;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700509}
510
511PyDoc_STRVAR(copy_doc, "Return a shallow copy of a deque.");
Raymond Hettinger41290a62015-03-31 08:12:23 -0700512
513static PyObject *
514deque_concat(dequeobject *deque, PyObject *other)
515{
Benjamin Peterson1a629212015-04-04 10:52:36 -0400516 PyObject *new_deque, *result;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700517 int rv;
518
519 rv = PyObject_IsInstance(other, (PyObject *)&deque_type);
520 if (rv <= 0) {
521 if (rv == 0) {
522 PyErr_Format(PyExc_TypeError,
523 "can only concatenate deque (not \"%.200s\") to deque",
Victor Stinnerdaa97562020-02-07 03:37:06 +0100524 Py_TYPE(other)->tp_name);
Raymond Hettinger41290a62015-03-31 08:12:23 -0700525 }
526 return NULL;
527 }
528
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530529 new_deque = deque_copy((PyObject *)deque, NULL);
Raymond Hettinger41290a62015-03-31 08:12:23 -0700530 if (new_deque == NULL)
531 return NULL;
Benjamin Peterson1a629212015-04-04 10:52:36 -0400532 result = deque_extend((dequeobject *)new_deque, other);
533 if (result == NULL) {
534 Py_DECREF(new_deque);
535 return NULL;
536 }
537 Py_DECREF(result);
538 return new_deque;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700539}
540
Serhiy Storchakaa5c42282018-05-31 07:34:34 +0300541static int
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700542deque_clear(dequeobject *deque)
543{
544 block *b;
545 block *prevblock;
546 block *leftblock;
547 Py_ssize_t leftindex;
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800548 Py_ssize_t n, m;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700549 PyObject *item;
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800550 PyObject **itemptr, **limit;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700551
Raymond Hettinger38031142015-09-29 22:45:05 -0700552 if (Py_SIZE(deque) == 0)
Serhiy Storchakaa5c42282018-05-31 07:34:34 +0300553 return 0;
Raymond Hettinger38031142015-09-29 22:45:05 -0700554
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700555 /* During the process of clearing a deque, decrefs can cause the
556 deque to mutate. To avoid fatal confusion, we have to make the
557 deque empty before clearing the blocks and never refer to
558 anything via deque->ref while clearing. (This is the same
559 technique used for clearing lists, sets, and dicts.)
560
561 Making the deque empty requires allocating a new empty block. In
562 the unlikely event that memory is full, we fall back to an
563 alternate method that doesn't require a new block. Repeating
564 pops in a while-loop is slower, possibly re-entrant (and a clever
565 adversary could cause it to never terminate).
566 */
567
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700568 b = newblock();
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700569 if (b == NULL) {
570 PyErr_Clear();
571 goto alternate_method;
572 }
573
574 /* Remember the old size, leftblock, and leftindex */
Raymond Hettinger6f86a332016-03-02 00:30:58 -0800575 n = Py_SIZE(deque);
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700576 leftblock = deque->leftblock;
577 leftindex = deque->leftindex;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700578
579 /* Set the deque to be empty using the newly allocated block */
580 MARK_END(b->leftlink);
581 MARK_END(b->rightlink);
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100582 Py_SET_SIZE(deque, 0);
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700583 deque->leftblock = b;
584 deque->rightblock = b;
585 deque->leftindex = CENTER + 1;
586 deque->rightindex = CENTER;
587 deque->state++;
588
589 /* Now the old size, leftblock, and leftindex are disconnected from
590 the empty deque and we can use them to decref the pointers.
591 */
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800592 m = (BLOCKLEN - leftindex > n) ? n : BLOCKLEN - leftindex;
Raymond Hettinger589106b2016-03-02 00:06:21 -0800593 itemptr = &leftblock->data[leftindex];
Raymond Hettinger6f86a332016-03-02 00:30:58 -0800594 limit = itemptr + m;
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800595 n -= m;
596 while (1) {
597 if (itemptr == limit) {
598 if (n == 0)
599 break;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700600 CHECK_NOT_END(leftblock->rightlink);
601 prevblock = leftblock;
602 leftblock = leftblock->rightlink;
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800603 m = (n > BLOCKLEN) ? BLOCKLEN : n;
Raymond Hettinger589106b2016-03-02 00:06:21 -0800604 itemptr = leftblock->data;
Raymond Hettinger6f86a332016-03-02 00:30:58 -0800605 limit = itemptr + m;
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800606 n -= m;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700607 freeblock(prevblock);
608 }
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800609 item = *(itemptr++);
610 Py_DECREF(item);
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700611 }
612 CHECK_END(leftblock->rightlink);
613 freeblock(leftblock);
Serhiy Storchakaa5c42282018-05-31 07:34:34 +0300614 return 0;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700615
616 alternate_method:
617 while (Py_SIZE(deque)) {
618 item = deque_pop(deque, NULL);
619 assert (item != NULL);
620 Py_DECREF(item);
621 }
Serhiy Storchakaa5c42282018-05-31 07:34:34 +0300622 return 0;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700623}
624
625static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530626deque_clearmethod(dequeobject *deque, PyObject *Py_UNUSED(ignored))
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700627{
628 deque_clear(deque);
629 Py_RETURN_NONE;
630}
631
632PyDoc_STRVAR(clear_doc, "Remove all elements from the deque.");
Raymond Hettinger41290a62015-03-31 08:12:23 -0700633
634static PyObject *
Raymond Hettinger41290a62015-03-31 08:12:23 -0700635deque_inplace_repeat(dequeobject *deque, Py_ssize_t n)
636{
Raymond Hettingerc22eee62015-09-26 02:14:50 -0700637 Py_ssize_t i, m, size;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700638 PyObject *seq;
639 PyObject *rv;
640
641 size = Py_SIZE(deque);
642 if (size == 0 || n == 1) {
643 Py_INCREF(deque);
644 return (PyObject *)deque;
645 }
646
647 if (n <= 0) {
648 deque_clear(deque);
649 Py_INCREF(deque);
650 return (PyObject *)deque;
651 }
652
Raymond Hettinger41290a62015-03-31 08:12:23 -0700653 if (size == 1) {
654 /* common case, repeating a single element */
655 PyObject *item = deque->leftblock->data[deque->leftindex];
656
Raymond Hettingera7f630092015-10-10 23:56:02 -0400657 if (deque->maxlen >= 0 && n > deque->maxlen)
Raymond Hettinger41290a62015-03-31 08:12:23 -0700658 n = deque->maxlen;
659
Raymond Hettinger67c78b52015-09-12 11:00:20 -0400660 deque->state++;
Raymond Hettingerad262252015-09-14 01:03:04 -0400661 for (i = 0 ; i < n-1 ; ) {
Raymond Hettinger67c78b52015-09-12 11:00:20 -0400662 if (deque->rightindex == BLOCKLEN - 1) {
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700663 block *b = newblock();
Raymond Hettinger67c78b52015-09-12 11:00:20 -0400664 if (b == NULL) {
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100665 Py_SET_SIZE(deque, Py_SIZE(deque) + i);
Raymond Hettinger67c78b52015-09-12 11:00:20 -0400666 return NULL;
667 }
668 b->leftlink = deque->rightblock;
669 CHECK_END(deque->rightblock->rightlink);
670 deque->rightblock->rightlink = b;
671 deque->rightblock = b;
672 MARK_END(b->rightlink);
673 deque->rightindex = -1;
674 }
Raymond Hettingerc22eee62015-09-26 02:14:50 -0700675 m = n - 1 - i;
676 if (m > BLOCKLEN - 1 - deque->rightindex)
677 m = BLOCKLEN - 1 - deque->rightindex;
678 i += m;
679 while (m--) {
Raymond Hettingerad262252015-09-14 01:03:04 -0400680 deque->rightindex++;
681 Py_INCREF(item);
682 deque->rightblock->data[deque->rightindex] = item;
683 }
Raymond Hettinger41290a62015-03-31 08:12:23 -0700684 }
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100685 Py_SET_SIZE(deque, Py_SIZE(deque) + i);
Raymond Hettinger41290a62015-03-31 08:12:23 -0700686 Py_INCREF(deque);
687 return (PyObject *)deque;
688 }
689
Raymond Hettinger20151f52015-10-16 22:47:29 -0700690 if ((size_t)size > PY_SSIZE_T_MAX / (size_t)n) {
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400691 return PyErr_NoMemory();
692 }
693
Raymond Hettinger41290a62015-03-31 08:12:23 -0700694 seq = PySequence_List((PyObject *)deque);
695 if (seq == NULL)
696 return seq;
697
Louie Lu357bad72017-02-24 11:59:49 +0800698 /* Reduce the number of repetitions when maxlen would be exceeded */
699 if (deque->maxlen >= 0 && n * size > deque->maxlen)
700 n = (deque->maxlen + size - 1) / size;
701
Raymond Hettinger41290a62015-03-31 08:12:23 -0700702 for (i = 0 ; i < n-1 ; i++) {
703 rv = deque_extend(deque, seq);
704 if (rv == NULL) {
705 Py_DECREF(seq);
706 return NULL;
707 }
708 Py_DECREF(rv);
709 }
710 Py_INCREF(deque);
711 Py_DECREF(seq);
712 return (PyObject *)deque;
713}
714
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400715static PyObject *
716deque_repeat(dequeobject *deque, Py_ssize_t n)
717{
718 dequeobject *new_deque;
Raymond Hettinger95e2cc52015-09-13 02:41:18 -0400719 PyObject *rv;
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400720
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530721 new_deque = (dequeobject *)deque_copy((PyObject *) deque, NULL);
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400722 if (new_deque == NULL)
723 return NULL;
Raymond Hettinger95e2cc52015-09-13 02:41:18 -0400724 rv = deque_inplace_repeat(new_deque, n);
725 Py_DECREF(new_deque);
726 return rv;
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400727}
728
Raymond Hettinger54023152014-04-23 00:58:48 -0700729/* The rotate() method is part of the public API and is used internally
730as a primitive for other methods.
731
732Rotation by 1 or -1 is a common case, so any optimizations for high
733volume rotations should take care not to penalize the common case.
734
735Conceptually, a rotate by one is equivalent to a pop on one side and an
736append on the other. However, a pop/append pair is unnecessarily slow
Martin Panterd2ad5712015-11-02 04:20:33 +0000737because it requires an incref/decref pair for an object located randomly
Raymond Hettinger54023152014-04-23 00:58:48 -0700738in memory. It is better to just move the object pointer from one block
739to the next without changing the reference count.
740
741When moving batches of pointers, it is tempting to use memcpy() but that
742proved to be slower than a simple loop for a variety of reasons.
743Memcpy() cannot know in advance that we're copying pointers instead of
744bytes, that the source and destination are pointer aligned and
745non-overlapping, that moving just one pointer is a common case, that we
746never need to move more than BLOCKLEN pointers, and that at least one
747pointer is always moved.
748
749For high volume rotations, newblock() and freeblock() are never called
750more than once. Previously emptied blocks are immediately reused as a
751destination block. If a block is left-over at the end, it is freed.
752*/
753
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000754static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000755_deque_rotate(dequeobject *deque, Py_ssize_t n)
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000756{
Raymond Hettinger3959af92013-07-13 02:34:08 -0700757 block *b = NULL;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700758 block *leftblock = deque->leftblock;
759 block *rightblock = deque->rightblock;
760 Py_ssize_t leftindex = deque->leftindex;
761 Py_ssize_t rightindex = deque->rightindex;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000762 Py_ssize_t len=Py_SIZE(deque), halflen=len>>1;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700763 int rv = -1;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000764
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800765 if (len <= 1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000766 return 0;
767 if (n > halflen || n < -halflen) {
768 n %= len;
769 if (n > halflen)
770 n -= len;
771 else if (n < -halflen)
772 n += len;
773 }
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500774 assert(len > 1);
Raymond Hettingera4409c12013-02-04 00:08:12 -0500775 assert(-halflen <= n && n <= halflen);
Raymond Hettinger231ee4d2013-02-02 11:24:43 -0800776
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800777 deque->state++;
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500778 while (n > 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700779 if (leftindex == 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700780 if (b == NULL) {
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700781 b = newblock();
Raymond Hettinger3959af92013-07-13 02:34:08 -0700782 if (b == NULL)
783 goto done;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700784 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000785 b->rightlink = leftblock;
786 CHECK_END(leftblock->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700787 leftblock->leftlink = b;
788 leftblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000789 MARK_END(b->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700790 leftindex = BLOCKLEN;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700791 b = NULL;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800792 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700793 assert(leftindex > 0);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700794 {
795 PyObject **src, **dest;
796 Py_ssize_t m = n;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800797
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700798 if (m > rightindex + 1)
799 m = rightindex + 1;
800 if (m > leftindex)
801 m = leftindex;
802 assert (m > 0 && m <= len);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700803 rightindex -= m;
804 leftindex -= m;
Raymond Hettinger0e259f12015-02-01 22:53:41 -0800805 src = &rightblock->data[rightindex + 1];
806 dest = &leftblock->data[leftindex];
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700807 n -= m;
Raymond Hettinger840533b2013-07-13 17:03:58 -0700808 do {
Raymond Hettinger0e259f12015-02-01 22:53:41 -0800809 *(dest++) = *(src++);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700810 } while (--m);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700811 }
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -0700812 if (rightindex < 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700813 assert(leftblock != rightblock);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700814 assert(b == NULL);
Raymond Hettinger3959af92013-07-13 02:34:08 -0700815 b = rightblock;
Raymond Hettingerb97cc492013-07-21 01:51:07 -0700816 CHECK_NOT_END(rightblock->leftlink);
817 rightblock = rightblock->leftlink;
818 MARK_END(rightblock->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700819 rightindex = BLOCKLEN - 1;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800820 }
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800821 }
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500822 while (n < 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700823 if (rightindex == BLOCKLEN - 1) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700824 if (b == NULL) {
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700825 b = newblock();
Raymond Hettinger3959af92013-07-13 02:34:08 -0700826 if (b == NULL)
827 goto done;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700828 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000829 b->leftlink = rightblock;
830 CHECK_END(rightblock->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700831 rightblock->rightlink = b;
832 rightblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000833 MARK_END(b->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700834 rightindex = -1;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700835 b = NULL;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800836 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700837 assert (rightindex < BLOCKLEN - 1);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700838 {
839 PyObject **src, **dest;
840 Py_ssize_t m = -n;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800841
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700842 if (m > BLOCKLEN - leftindex)
843 m = BLOCKLEN - leftindex;
844 if (m > BLOCKLEN - 1 - rightindex)
845 m = BLOCKLEN - 1 - rightindex;
846 assert (m > 0 && m <= len);
847 src = &leftblock->data[leftindex];
848 dest = &rightblock->data[rightindex + 1];
849 leftindex += m;
850 rightindex += m;
851 n += m;
Raymond Hettinger840533b2013-07-13 17:03:58 -0700852 do {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700853 *(dest++) = *(src++);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700854 } while (--m);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700855 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700856 if (leftindex == BLOCKLEN) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700857 assert(leftblock != rightblock);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700858 assert(b == NULL);
Raymond Hettinger3959af92013-07-13 02:34:08 -0700859 b = leftblock;
Raymond Hettingerb97cc492013-07-21 01:51:07 -0700860 CHECK_NOT_END(leftblock->rightlink);
861 leftblock = leftblock->rightlink;
862 MARK_END(leftblock->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700863 leftindex = 0;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800864 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000865 }
Raymond Hettinger3959af92013-07-13 02:34:08 -0700866 rv = 0;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700867done:
Raymond Hettinger3959af92013-07-13 02:34:08 -0700868 if (b != NULL)
869 freeblock(b);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700870 deque->leftblock = leftblock;
871 deque->rightblock = rightblock;
872 deque->leftindex = leftindex;
873 deque->rightindex = rightindex;
874
875 return rv;
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000876}
877
878static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +0200879deque_rotate(dequeobject *deque, PyObject *const *args, Py_ssize_t nargs)
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000880{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 Py_ssize_t n=1;
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000882
Dennis Sweeney448801d2021-03-16 00:02:25 -0400883 if (!_PyArg_CheckPositional("deque.rotate", nargs, 0, 1)) {
Victor Stinnerdd407d52017-02-06 16:06:49 +0100884 return NULL;
885 }
Dennis Sweeney448801d2021-03-16 00:02:25 -0400886 if (nargs) {
887 PyObject *index = _PyNumber_Index(args[0]);
888 if (index == NULL) {
889 return NULL;
890 }
891 n = PyLong_AsSsize_t(index);
892 Py_DECREF(index);
893 if (n == -1 && PyErr_Occurred()) {
894 return NULL;
895 }
896 }
Victor Stinnerdd407d52017-02-06 16:06:49 +0100897
Raymond Hettinger6921c132015-03-21 02:03:40 -0700898 if (!_deque_rotate(deque, n))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000899 Py_RETURN_NONE;
900 return NULL;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000901}
902
Tim Peters1065f752004-10-01 01:03:29 +0000903PyDoc_STRVAR(rotate_doc,
Raymond Hettingeree33b272004-02-08 04:05:26 +0000904"Rotate the deque n steps to the right (default n=1). If n is negative, rotates left.");
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000905
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000906static PyObject *
907deque_reverse(dequeobject *deque, PyObject *unused)
908{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000909 block *leftblock = deque->leftblock;
910 block *rightblock = deque->rightblock;
911 Py_ssize_t leftindex = deque->leftindex;
912 Py_ssize_t rightindex = deque->rightindex;
Raymond Hettingercfe5b6c2015-07-20 00:25:50 -0400913 Py_ssize_t n = Py_SIZE(deque) >> 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 PyObject *tmp;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000915
Raymond Hettingere1b02872017-09-04 16:07:06 -0700916 while (--n >= 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000917 /* Validate that pointers haven't met in the middle */
918 assert(leftblock != rightblock || leftindex < rightindex);
Raymond Hettinger82df9252013-07-07 01:43:42 -1000919 CHECK_NOT_END(leftblock);
920 CHECK_NOT_END(rightblock);
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 /* Swap */
923 tmp = leftblock->data[leftindex];
924 leftblock->data[leftindex] = rightblock->data[rightindex];
925 rightblock->data[rightindex] = tmp;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000926
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000927 /* Advance left block/index pair */
928 leftindex++;
929 if (leftindex == BLOCKLEN) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000930 leftblock = leftblock->rightlink;
931 leftindex = 0;
932 }
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000933
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 /* Step backwards with the right block/index pair */
935 rightindex--;
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -0700936 if (rightindex < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000937 rightblock = rightblock->leftlink;
938 rightindex = BLOCKLEN - 1;
939 }
940 }
941 Py_RETURN_NONE;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000942}
943
944PyDoc_STRVAR(reverse_doc,
945"D.reverse() -- reverse *IN PLACE*");
946
Raymond Hettinger44459de2010-04-03 23:20:46 +0000947static PyObject *
948deque_count(dequeobject *deque, PyObject *v)
949{
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000950 block *b = deque->leftblock;
951 Py_ssize_t index = deque->leftindex;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000952 Py_ssize_t n = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 Py_ssize_t count = 0;
Raymond Hettingerf9d9c792015-03-02 22:47:46 -0800954 size_t start_state = deque->state;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 PyObject *item;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000956 int cmp;
Raymond Hettinger44459de2010-04-03 23:20:46 +0000957
Raymond Hettingere1b02872017-09-04 16:07:06 -0700958 while (--n >= 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000959 CHECK_NOT_END(b);
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000960 item = b->data[index];
sweeneydec6dedde2020-02-09 03:16:43 -0500961 Py_INCREF(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
sweeneydec6dedde2020-02-09 03:16:43 -0500963 Py_DECREF(item);
Raymond Hettinger2b0d6462015-09-23 19:15:44 -0700964 if (cmp < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000965 return NULL;
Raymond Hettinger2b0d6462015-09-23 19:15:44 -0700966 count += cmp;
Raymond Hettinger44459de2010-04-03 23:20:46 +0000967
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000968 if (start_state != deque->state) {
969 PyErr_SetString(PyExc_RuntimeError,
970 "deque mutated during iteration");
971 return NULL;
972 }
Raymond Hettinger44459de2010-04-03 23:20:46 +0000973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 /* Advance left block/index pair */
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000975 index++;
976 if (index == BLOCKLEN) {
977 b = b->rightlink;
978 index = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 }
980 }
981 return PyLong_FromSsize_t(count);
Raymond Hettinger44459de2010-04-03 23:20:46 +0000982}
983
984PyDoc_STRVAR(count_doc,
985"D.count(value) -> integer -- return number of occurrences of value");
986
Raymond Hettinger39dadf72015-03-20 16:38:56 -0700987static int
988deque_contains(dequeobject *deque, PyObject *v)
989{
990 block *b = deque->leftblock;
991 Py_ssize_t index = deque->leftindex;
992 Py_ssize_t n = Py_SIZE(deque);
Raymond Hettinger39dadf72015-03-20 16:38:56 -0700993 size_t start_state = deque->state;
994 PyObject *item;
995 int cmp;
996
Raymond Hettingere1b02872017-09-04 16:07:06 -0700997 while (--n >= 0) {
Raymond Hettinger39dadf72015-03-20 16:38:56 -0700998 CHECK_NOT_END(b);
999 item = b->data[index];
sweeneydec6dedde2020-02-09 03:16:43 -05001000 Py_INCREF(item);
Raymond Hettinger39dadf72015-03-20 16:38:56 -07001001 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
sweeneydec6dedde2020-02-09 03:16:43 -05001002 Py_DECREF(item);
Raymond Hettinger39dadf72015-03-20 16:38:56 -07001003 if (cmp) {
1004 return cmp;
1005 }
1006 if (start_state != deque->state) {
1007 PyErr_SetString(PyExc_RuntimeError,
1008 "deque mutated during iteration");
1009 return -1;
1010 }
1011 index++;
1012 if (index == BLOCKLEN) {
1013 b = b->rightlink;
1014 index = 0;
1015 }
1016 }
1017 return 0;
1018}
1019
Martin v. Löwis18e16552006-02-15 17:27:45 +00001020static Py_ssize_t
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001021deque_len(dequeobject *deque)
1022{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001023 return Py_SIZE(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001024}
1025
Raymond Hettinger4aec61e2005-03-18 21:20:23 +00001026static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02001027deque_index(dequeobject *deque, PyObject *const *args, Py_ssize_t nargs)
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001028{
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001029 Py_ssize_t i, n, start=0, stop=Py_SIZE(deque);
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001030 PyObject *v, *item;
1031 block *b = deque->leftblock;
1032 Py_ssize_t index = deque->leftindex;
1033 size_t start_state = deque->state;
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001034 int cmp;
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001035
Victor Stinnerdd407d52017-02-06 16:06:49 +01001036 if (!_PyArg_ParseStack(args, nargs, "O|O&O&:index", &v,
Serhiy Storchakad4edfc92017-03-30 18:29:23 +03001037 _PyEval_SliceIndexNotNone, &start,
1038 _PyEval_SliceIndexNotNone, &stop)) {
Victor Stinnerdd407d52017-02-06 16:06:49 +01001039 return NULL;
1040 }
1041
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001042 if (start < 0) {
1043 start += Py_SIZE(deque);
1044 if (start < 0)
1045 start = 0;
1046 }
1047 if (stop < 0) {
1048 stop += Py_SIZE(deque);
1049 if (stop < 0)
1050 stop = 0;
1051 }
Raymond Hettinger87674ec2015-08-26 08:08:38 -07001052 if (stop > Py_SIZE(deque))
1053 stop = Py_SIZE(deque);
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001054 if (start > stop)
1055 start = stop;
1056 assert(0 <= start && start <= stop && stop <= Py_SIZE(deque));
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001057
Raymond Hettingerb46ad542018-09-21 01:46:41 -07001058 for (i=0 ; i < start - BLOCKLEN ; i += BLOCKLEN) {
1059 b = b->rightlink;
1060 }
1061 for ( ; i < start ; i++) {
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001062 index++;
1063 if (index == BLOCKLEN) {
1064 b = b->rightlink;
1065 index = 0;
1066 }
1067 }
1068
Raymond Hettingere1b02872017-09-04 16:07:06 -07001069 n = stop - i;
1070 while (--n >= 0) {
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001071 CHECK_NOT_END(b);
1072 item = b->data[index];
1073 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
1074 if (cmp > 0)
Raymond Hettingere1b02872017-09-04 16:07:06 -07001075 return PyLong_FromSsize_t(stop - n - 1);
Raymond Hettingerdf8f5b52015-11-02 07:27:40 -05001076 if (cmp < 0)
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001077 return NULL;
1078 if (start_state != deque->state) {
1079 PyErr_SetString(PyExc_RuntimeError,
1080 "deque mutated during iteration");
1081 return NULL;
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001082 }
1083 index++;
1084 if (index == BLOCKLEN) {
1085 b = b->rightlink;
1086 index = 0;
1087 }
1088 }
1089 PyErr_Format(PyExc_ValueError, "%R is not in deque", v);
1090 return NULL;
1091}
1092
1093PyDoc_STRVAR(index_doc,
1094"D.index(value, [start, [stop]]) -> integer -- return first index of value.\n"
1095"Raises ValueError if the value is not present.");
1096
Raymond Hettinger551350a2015-03-24 00:19:53 -07001097/* insert(), remove(), and delitem() are implemented in terms of
1098 rotate() for simplicity and reasonable performance near the end
1099 points. If for some reason these methods become popular, it is not
1100 hard to re-implement this using direct data movement (similar to
1101 the code used in list slice assignments) and achieve a performance
Raymond Hettingerfef9c1b2015-03-24 21:12:57 -07001102 boost (by moving each pointer only once instead of twice).
Raymond Hettinger551350a2015-03-24 00:19:53 -07001103*/
1104
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001105static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02001106deque_insert(dequeobject *deque, PyObject *const *args, Py_ssize_t nargs)
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001107{
1108 Py_ssize_t index;
1109 Py_ssize_t n = Py_SIZE(deque);
1110 PyObject *value;
1111 PyObject *rv;
1112
Victor Stinnerdd407d52017-02-06 16:06:49 +01001113 if (!_PyArg_ParseStack(args, nargs, "nO:insert", &index, &value)) {
1114 return NULL;
1115 }
1116
Raymond Hettinger37434322016-01-26 21:44:16 -08001117 if (deque->maxlen == Py_SIZE(deque)) {
Raymond Hettingera6389712016-02-01 21:21:19 -08001118 PyErr_SetString(PyExc_IndexError, "deque already at its maximum size");
1119 return NULL;
Raymond Hettinger37434322016-01-26 21:44:16 -08001120 }
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001121 if (index >= n)
1122 return deque_append(deque, value);
1123 if (index <= -n || index == 0)
1124 return deque_appendleft(deque, value);
1125 if (_deque_rotate(deque, -index))
1126 return NULL;
1127 if (index < 0)
1128 rv = deque_append(deque, value);
1129 else
1130 rv = deque_appendleft(deque, value);
1131 if (rv == NULL)
1132 return NULL;
1133 Py_DECREF(rv);
1134 if (_deque_rotate(deque, index))
1135 return NULL;
1136 Py_RETURN_NONE;
1137}
1138
1139PyDoc_STRVAR(insert_doc,
1140"D.insert(index, object) -- insert object before index");
1141
Raymond Hettinger4aec61e2005-03-18 21:20:23 +00001142PyDoc_STRVAR(remove_doc,
1143"D.remove(value) -- remove first occurrence of value.");
1144
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001145static int
1146valid_index(Py_ssize_t i, Py_ssize_t limit)
1147{
Raymond Hettinger12f896c2015-07-31 12:03:20 -07001148 /* The cast to size_t lets us use just a single comparison
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001149 to check whether i is in the range: 0 <= i < limit */
1150 return (size_t) i < (size_t) limit;
1151}
1152
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001153static PyObject *
Benjamin Petersond6313712008-07-31 16:23:04 +00001154deque_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001155{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001156 block *b;
1157 PyObject *item;
1158 Py_ssize_t n, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001159
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001160 if (!valid_index(i, Py_SIZE(deque))) {
1161 PyErr_SetString(PyExc_IndexError, "deque index out of range");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001162 return NULL;
1163 }
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001165 if (i == 0) {
1166 i = deque->leftindex;
1167 b = deque->leftblock;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001168 } else if (i == Py_SIZE(deque) - 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001169 i = deque->rightindex;
1170 b = deque->rightblock;
1171 } else {
1172 i += deque->leftindex;
Raymond Hettingerc2083082015-02-28 23:29:16 -08001173 n = (Py_ssize_t)((size_t) i / BLOCKLEN);
1174 i = (Py_ssize_t)((size_t) i % BLOCKLEN);
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001175 if (index < (Py_SIZE(deque) >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001176 b = deque->leftblock;
Raymond Hettingere1b02872017-09-04 16:07:06 -07001177 while (--n >= 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178 b = b->rightlink;
1179 } else {
Raymond Hettinger63d1ff22015-02-28 07:41:30 -08001180 n = (Py_ssize_t)(
Raymond Hettingerc2083082015-02-28 23:29:16 -08001181 ((size_t)(deque->leftindex + Py_SIZE(deque) - 1))
Raymond Hettinger63d1ff22015-02-28 07:41:30 -08001182 / BLOCKLEN - n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 b = deque->rightblock;
Raymond Hettingere1b02872017-09-04 16:07:06 -07001184 while (--n >= 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001185 b = b->leftlink;
1186 }
1187 }
1188 item = b->data[i];
1189 Py_INCREF(item);
1190 return item;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001191}
1192
1193static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001194deque_del_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001195{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001196 PyObject *item;
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001197 int rv;
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001198
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001199 assert (i >= 0 && i < Py_SIZE(deque));
Raymond Hettinger6921c132015-03-21 02:03:40 -07001200 if (_deque_rotate(deque, -i))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001201 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001202 item = deque_popleft(deque, NULL);
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001203 rv = _deque_rotate(deque, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 assert (item != NULL);
1205 Py_DECREF(item);
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001206 return rv;
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001207}
1208
Raymond Hettinger6b1ac802020-12-23 11:45:06 -08001209static PyObject *
1210deque_remove(dequeobject *deque, PyObject *value)
1211{
1212 PyObject *item;
1213 block *b = deque->leftblock;
1214 Py_ssize_t i, n = Py_SIZE(deque), index = deque->leftindex;
1215 size_t start_state = deque->state;
1216 int cmp, rv;
1217
1218 for (i = 0 ; i < n; i++) {
1219 item = b->data[index];
1220 Py_INCREF(item);
1221 cmp = PyObject_RichCompareBool(item, value, Py_EQ);
1222 Py_DECREF(item);
1223 if (cmp < 0) {
1224 return NULL;
1225 }
1226 if (start_state != deque->state) {
1227 PyErr_SetString(PyExc_IndexError,
1228 "deque mutated during iteration");
1229 return NULL;
1230 }
1231 if (cmp > 0) {
1232 break;
1233 }
1234 index++;
1235 if (index == BLOCKLEN) {
1236 b = b->rightlink;
1237 index = 0;
1238 }
1239 }
1240 if (i == n) {
1241 PyErr_Format(PyExc_ValueError, "%R is not in deque", value);
1242 return NULL;
1243 }
1244 rv = deque_del_item(deque, i);
1245 if (rv == -1) {
1246 return NULL;
1247 }
1248 Py_RETURN_NONE;
1249}
1250
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001251static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001252deque_ass_item(dequeobject *deque, Py_ssize_t i, PyObject *v)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001253{
Raymond Hettinger38418662016-02-08 20:34:49 -08001254 PyObject *old_value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001255 block *b;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001256 Py_ssize_t n, len=Py_SIZE(deque), halflen=(len+1)>>1, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001257
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001258 if (!valid_index(i, len)) {
1259 PyErr_SetString(PyExc_IndexError, "deque index out of range");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001260 return -1;
1261 }
1262 if (v == NULL)
1263 return deque_del_item(deque, i);
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001265 i += deque->leftindex;
Raymond Hettingerc2083082015-02-28 23:29:16 -08001266 n = (Py_ssize_t)((size_t) i / BLOCKLEN);
1267 i = (Py_ssize_t)((size_t) i % BLOCKLEN);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001268 if (index <= halflen) {
1269 b = deque->leftblock;
Raymond Hettingere1b02872017-09-04 16:07:06 -07001270 while (--n >= 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001271 b = b->rightlink;
1272 } else {
Raymond Hettingera473b9d2015-02-28 17:49:47 -08001273 n = (Py_ssize_t)(
Raymond Hettingerc2083082015-02-28 23:29:16 -08001274 ((size_t)(deque->leftindex + Py_SIZE(deque) - 1))
Raymond Hettingera473b9d2015-02-28 17:49:47 -08001275 / BLOCKLEN - n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001276 b = deque->rightblock;
Raymond Hettingere1b02872017-09-04 16:07:06 -07001277 while (--n >= 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001278 b = b->leftlink;
1279 }
1280 Py_INCREF(v);
Raymond Hettinger38418662016-02-08 20:34:49 -08001281 old_value = b->data[i];
1282 b->data[i] = v;
1283 Py_DECREF(old_value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001284 return 0;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001285}
1286
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001287static void
1288deque_dealloc(dequeobject *deque)
1289{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001290 PyObject_GC_UnTrack(deque);
1291 if (deque->weakreflist != NULL)
1292 PyObject_ClearWeakRefs((PyObject *) deque);
1293 if (deque->leftblock != NULL) {
1294 deque_clear(deque);
1295 assert(deque->leftblock != NULL);
1296 freeblock(deque->leftblock);
1297 }
1298 deque->leftblock = NULL;
1299 deque->rightblock = NULL;
1300 Py_TYPE(deque)->tp_free(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001301}
1302
1303static int
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001304deque_traverse(dequeobject *deque, visitproc visit, void *arg)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001305{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001306 block *b;
1307 PyObject *item;
1308 Py_ssize_t index;
1309 Py_ssize_t indexlo = deque->leftindex;
Raymond Hettinger1286d142015-10-14 23:16:57 -07001310 Py_ssize_t indexhigh;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001311
Raymond Hettinger5bfa8672013-07-06 11:58:09 -10001312 for (b = deque->leftblock; b != deque->rightblock; b = b->rightlink) {
1313 for (index = indexlo; index < BLOCKLEN ; index++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001314 item = b->data[index];
1315 Py_VISIT(item);
1316 }
1317 indexlo = 0;
1318 }
Raymond Hettinger1286d142015-10-14 23:16:57 -07001319 indexhigh = deque->rightindex;
1320 for (index = indexlo; index <= indexhigh; index++) {
Raymond Hettinger5bfa8672013-07-06 11:58:09 -10001321 item = b->data[index];
1322 Py_VISIT(item);
1323 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001324 return 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001325}
1326
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001327static PyObject *
Serhiy Storchaka81524022018-11-27 13:05:02 +02001328deque_reduce(dequeobject *deque, PyObject *Py_UNUSED(ignored))
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001329{
Serhiy Storchakaa0d416f2016-03-06 08:55:21 +02001330 PyObject *dict, *it;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001331 _Py_IDENTIFIER(__dict__);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001332
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001333 if (_PyObject_LookupAttrId((PyObject *)deque, &PyId___dict__, &dict) < 0) {
1334 return NULL;
1335 }
Serhiy Storchakaa0d416f2016-03-06 08:55:21 +02001336 if (dict == NULL) {
Serhiy Storchakaa0d416f2016-03-06 08:55:21 +02001337 dict = Py_None;
1338 Py_INCREF(dict);
1339 }
1340
1341 it = PyObject_GetIter((PyObject *)deque);
1342 if (it == NULL) {
1343 Py_DECREF(dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001344 return NULL;
1345 }
Serhiy Storchakaa0d416f2016-03-06 08:55:21 +02001346
1347 if (deque->maxlen < 0) {
1348 return Py_BuildValue("O()NN", Py_TYPE(deque), dict, it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001349 }
Serhiy Storchakaa0d416f2016-03-06 08:55:21 +02001350 else {
1351 return Py_BuildValue("O(()n)NN", Py_TYPE(deque), deque->maxlen, dict, it);
1352 }
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001353}
1354
1355PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
1356
1357static PyObject *
1358deque_repr(PyObject *deque)
1359{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001360 PyObject *aslist, *result;
1361 int i;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001363 i = Py_ReprEnter(deque);
1364 if (i != 0) {
1365 if (i < 0)
1366 return NULL;
1367 return PyUnicode_FromString("[...]");
1368 }
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001370 aslist = PySequence_List(deque);
1371 if (aslist == NULL) {
1372 Py_ReprLeave(deque);
1373 return NULL;
1374 }
Raymond Hettingera7f630092015-10-10 23:56:02 -04001375 if (((dequeobject *)deque)->maxlen >= 0)
Serhiy Storchakab3a77962017-09-21 14:24:13 +03001376 result = PyUnicode_FromFormat("%s(%R, maxlen=%zd)",
1377 _PyType_Name(Py_TYPE(deque)), aslist,
1378 ((dequeobject *)deque)->maxlen);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001379 else
Serhiy Storchakab3a77962017-09-21 14:24:13 +03001380 result = PyUnicode_FromFormat("%s(%R)",
1381 _PyType_Name(Py_TYPE(deque)), aslist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001382 Py_ReprLeave(deque);
Raymond Hettinger2b2b7532015-09-05 17:05:52 -07001383 Py_DECREF(aslist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001384 return result;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001385}
1386
Raymond Hettinger738ec902004-02-29 02:15:56 +00001387static PyObject *
1388deque_richcompare(PyObject *v, PyObject *w, int op)
1389{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001390 PyObject *it1=NULL, *it2=NULL, *x, *y;
1391 Py_ssize_t vs, ws;
1392 int b, cmp=-1;
Raymond Hettinger738ec902004-02-29 02:15:56 +00001393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001394 if (!PyObject_TypeCheck(v, &deque_type) ||
1395 !PyObject_TypeCheck(w, &deque_type)) {
Brian Curtindfc80e32011-08-10 20:28:54 -05001396 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001397 }
Raymond Hettinger738ec902004-02-29 02:15:56 +00001398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001399 /* Shortcuts */
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001400 vs = Py_SIZE((dequeobject *)v);
1401 ws = Py_SIZE((dequeobject *)w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001402 if (op == Py_EQ) {
1403 if (v == w)
1404 Py_RETURN_TRUE;
1405 if (vs != ws)
1406 Py_RETURN_FALSE;
1407 }
1408 if (op == Py_NE) {
1409 if (v == w)
1410 Py_RETURN_FALSE;
1411 if (vs != ws)
1412 Py_RETURN_TRUE;
1413 }
Raymond Hettinger738ec902004-02-29 02:15:56 +00001414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001415 /* Search for the first index where items are different */
1416 it1 = PyObject_GetIter(v);
1417 if (it1 == NULL)
1418 goto done;
1419 it2 = PyObject_GetIter(w);
1420 if (it2 == NULL)
1421 goto done;
1422 for (;;) {
1423 x = PyIter_Next(it1);
1424 if (x == NULL && PyErr_Occurred())
1425 goto done;
1426 y = PyIter_Next(it2);
1427 if (x == NULL || y == NULL)
1428 break;
1429 b = PyObject_RichCompareBool(x, y, Py_EQ);
1430 if (b == 0) {
1431 cmp = PyObject_RichCompareBool(x, y, op);
1432 Py_DECREF(x);
1433 Py_DECREF(y);
1434 goto done;
1435 }
1436 Py_DECREF(x);
1437 Py_DECREF(y);
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -07001438 if (b < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001439 goto done;
1440 }
1441 /* We reached the end of one deque or both */
1442 Py_XDECREF(x);
1443 Py_XDECREF(y);
1444 if (PyErr_Occurred())
1445 goto done;
1446 switch (op) {
1447 case Py_LT: cmp = y != NULL; break; /* if w was longer */
1448 case Py_LE: cmp = x == NULL; break; /* if v was not longer */
1449 case Py_EQ: cmp = x == y; break; /* if we reached the end of both */
1450 case Py_NE: cmp = x != y; break; /* if one deque continues */
1451 case Py_GT: cmp = x != NULL; break; /* if v was longer */
1452 case Py_GE: cmp = y == NULL; break; /* if w was not longer */
1453 }
Tim Peters1065f752004-10-01 01:03:29 +00001454
Raymond Hettinger738ec902004-02-29 02:15:56 +00001455done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001456 Py_XDECREF(it1);
1457 Py_XDECREF(it2);
1458 if (cmp == 1)
1459 Py_RETURN_TRUE;
1460 if (cmp == 0)
1461 Py_RETURN_FALSE;
1462 return NULL;
Raymond Hettinger738ec902004-02-29 02:15:56 +00001463}
1464
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001465static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001466deque_init(dequeobject *deque, PyObject *args, PyObject *kwdargs)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001467{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001468 PyObject *iterable = NULL;
1469 PyObject *maxlenobj = NULL;
1470 Py_ssize_t maxlen = -1;
1471 char *kwlist[] = {"iterable", "maxlen", 0};
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001472
Raymond Hettinger05f1b932019-01-31 22:13:43 -08001473 if (kwdargs == NULL && PyTuple_GET_SIZE(args) <= 2) {
1474 if (PyTuple_GET_SIZE(args) > 0) {
1475 iterable = PyTuple_GET_ITEM(args, 0);
1476 }
1477 if (PyTuple_GET_SIZE(args) > 1) {
1478 maxlenobj = PyTuple_GET_ITEM(args, 1);
1479 }
Raymond Hettinger0d309402015-09-30 23:15:02 -07001480 } else {
1481 if (!PyArg_ParseTupleAndKeywords(args, kwdargs, "|OO:deque", kwlist,
1482 &iterable, &maxlenobj))
1483 return -1;
1484 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001485 if (maxlenobj != NULL && maxlenobj != Py_None) {
1486 maxlen = PyLong_AsSsize_t(maxlenobj);
1487 if (maxlen == -1 && PyErr_Occurred())
1488 return -1;
1489 if (maxlen < 0) {
1490 PyErr_SetString(PyExc_ValueError, "maxlen must be non-negative");
1491 return -1;
1492 }
1493 }
1494 deque->maxlen = maxlen;
Raymond Hettinger0d309402015-09-30 23:15:02 -07001495 if (Py_SIZE(deque) > 0)
1496 deque_clear(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001497 if (iterable != NULL) {
1498 PyObject *rv = deque_extend(deque, iterable);
1499 if (rv == NULL)
1500 return -1;
1501 Py_DECREF(rv);
1502 }
1503 return 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001504}
1505
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001506static PyObject *
Jesus Cea16e2fca2012-08-03 14:49:42 +02001507deque_sizeof(dequeobject *deque, void *unused)
1508{
1509 Py_ssize_t res;
1510 Py_ssize_t blocks;
1511
Serhiy Storchaka5c4064e2015-12-19 20:05:25 +02001512 res = _PyObject_SIZE(Py_TYPE(deque));
Raymond Hettingerbc003412015-10-14 23:33:23 -07001513 blocks = (size_t)(deque->leftindex + Py_SIZE(deque) + BLOCKLEN - 1) / BLOCKLEN;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001514 assert(deque->leftindex + Py_SIZE(deque) - 1 ==
Jesus Cea16e2fca2012-08-03 14:49:42 +02001515 (blocks - 1) * BLOCKLEN + deque->rightindex);
1516 res += blocks * sizeof(block);
1517 return PyLong_FromSsize_t(res);
1518}
1519
1520PyDoc_STRVAR(sizeof_doc,
1521"D.__sizeof__() -- size of D in memory, in bytes");
1522
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001523static int
1524deque_bool(dequeobject *deque)
1525{
1526 return Py_SIZE(deque) != 0;
1527}
1528
Jesus Cea16e2fca2012-08-03 14:49:42 +02001529static PyObject *
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +02001530deque_get_maxlen(dequeobject *deque, void *Py_UNUSED(ignored))
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001531{
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -07001532 if (deque->maxlen < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001533 Py_RETURN_NONE;
1534 return PyLong_FromSsize_t(deque->maxlen);
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001535}
1536
Raymond Hettinger41290a62015-03-31 08:12:23 -07001537
1538/* deque object ********************************************************/
1539
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001540static PyGetSetDef deque_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001541 {"maxlen", (getter)deque_get_maxlen, (setter)NULL,
1542 "maximum size of a deque or None if unbounded"},
1543 {0}
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001544};
1545
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001546static PySequenceMethods deque_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001547 (lenfunc)deque_len, /* sq_length */
Raymond Hettinger41290a62015-03-31 08:12:23 -07001548 (binaryfunc)deque_concat, /* sq_concat */
1549 (ssizeargfunc)deque_repeat, /* sq_repeat */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001550 (ssizeargfunc)deque_item, /* sq_item */
1551 0, /* sq_slice */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001552 (ssizeobjargproc)deque_ass_item, /* sq_ass_item */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001553 0, /* sq_ass_slice */
Raymond Hettinger39dadf72015-03-20 16:38:56 -07001554 (objobjproc)deque_contains, /* sq_contains */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001555 (binaryfunc)deque_inplace_concat, /* sq_inplace_concat */
Raymond Hettinger41290a62015-03-31 08:12:23 -07001556 (ssizeargfunc)deque_inplace_repeat, /* sq_inplace_repeat */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001557};
1558
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001559static PyNumberMethods deque_as_number = {
1560 0, /* nb_add */
1561 0, /* nb_subtract */
1562 0, /* nb_multiply */
1563 0, /* nb_remainder */
1564 0, /* nb_divmod */
1565 0, /* nb_power */
1566 0, /* nb_negative */
1567 0, /* nb_positive */
1568 0, /* nb_absolute */
1569 (inquiry)deque_bool, /* nb_bool */
1570 0, /* nb_invert */
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001571 };
1572
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001573static PyObject *deque_iter(dequeobject *deque);
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301574static PyObject *deque_reviter(dequeobject *deque, PyObject *Py_UNUSED(ignored));
Tim Peters1065f752004-10-01 01:03:29 +00001575PyDoc_STRVAR(reversed_doc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001576 "D.__reversed__() -- return a reverse iterator over the deque");
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001577
1578static PyMethodDef deque_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001579 {"append", (PyCFunction)deque_append,
1580 METH_O, append_doc},
1581 {"appendleft", (PyCFunction)deque_appendleft,
1582 METH_O, appendleft_doc},
1583 {"clear", (PyCFunction)deque_clearmethod,
1584 METH_NOARGS, clear_doc},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301585 {"__copy__", deque_copy,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001586 METH_NOARGS, copy_doc},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301587 {"copy", deque_copy,
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001588 METH_NOARGS, copy_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001589 {"count", (PyCFunction)deque_count,
Raymond Hettinger0f6f9472015-03-21 01:42:10 -07001590 METH_O, count_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001591 {"extend", (PyCFunction)deque_extend,
1592 METH_O, extend_doc},
1593 {"extendleft", (PyCFunction)deque_extendleft,
1594 METH_O, extendleft_doc},
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001595 {"index", (PyCFunction)(void(*)(void))deque_index,
Victor Stinnerdd407d52017-02-06 16:06:49 +01001596 METH_FASTCALL, index_doc},
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001597 {"insert", (PyCFunction)(void(*)(void))deque_insert,
Victor Stinnerdd407d52017-02-06 16:06:49 +01001598 METH_FASTCALL, insert_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001599 {"pop", (PyCFunction)deque_pop,
1600 METH_NOARGS, pop_doc},
1601 {"popleft", (PyCFunction)deque_popleft,
1602 METH_NOARGS, popleft_doc},
Raymond Hettinger0f6f9472015-03-21 01:42:10 -07001603 {"__reduce__", (PyCFunction)deque_reduce,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001604 METH_NOARGS, reduce_doc},
1605 {"remove", (PyCFunction)deque_remove,
1606 METH_O, remove_doc},
1607 {"__reversed__", (PyCFunction)deque_reviter,
1608 METH_NOARGS, reversed_doc},
1609 {"reverse", (PyCFunction)deque_reverse,
1610 METH_NOARGS, reverse_doc},
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001611 {"rotate", (PyCFunction)(void(*)(void))deque_rotate,
Victor Stinnerdd407d52017-02-06 16:06:49 +01001612 METH_FASTCALL, rotate_doc},
Jesus Cea16e2fca2012-08-03 14:49:42 +02001613 {"__sizeof__", (PyCFunction)deque_sizeof,
1614 METH_NOARGS, sizeof_doc},
Guido van Rossum48b069a2020-04-07 09:50:06 -07001615 {"__class_getitem__", (PyCFunction)Py_GenericAlias,
1616 METH_O|METH_CLASS, PyDoc_STR("See PEP 585")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001617 {NULL, NULL} /* sentinel */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001618};
1619
1620PyDoc_STRVAR(deque_doc,
Andrew Svetlov6a5c7c32012-10-31 11:50:40 +02001621"deque([iterable[, maxlen]]) --> deque object\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001622\n\
Raymond Hettinger41290a62015-03-31 08:12:23 -07001623A list-like sequence optimized for data accesses near its endpoints.");
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001624
Neal Norwitz87f10132004-02-29 15:40:53 +00001625static PyTypeObject deque_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001626 PyVarObject_HEAD_INIT(NULL, 0)
1627 "collections.deque", /* tp_name */
1628 sizeof(dequeobject), /* tp_basicsize */
1629 0, /* tp_itemsize */
1630 /* methods */
1631 (destructor)deque_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001632 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001633 0, /* tp_getattr */
1634 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001635 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001636 deque_repr, /* tp_repr */
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001637 &deque_as_number, /* tp_as_number */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001638 &deque_as_sequence, /* tp_as_sequence */
1639 0, /* tp_as_mapping */
Georg Brandlf038b322010-10-18 07:35:09 +00001640 PyObject_HashNotImplemented, /* tp_hash */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001641 0, /* tp_call */
1642 0, /* tp_str */
1643 PyObject_GenericGetAttr, /* tp_getattro */
1644 0, /* tp_setattro */
1645 0, /* tp_as_buffer */
1646 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
Georg Brandlf038b322010-10-18 07:35:09 +00001647 /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001648 deque_doc, /* tp_doc */
1649 (traverseproc)deque_traverse, /* tp_traverse */
1650 (inquiry)deque_clear, /* tp_clear */
1651 (richcmpfunc)deque_richcompare, /* tp_richcompare */
Georg Brandlf038b322010-10-18 07:35:09 +00001652 offsetof(dequeobject, weakreflist), /* tp_weaklistoffset*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001653 (getiterfunc)deque_iter, /* tp_iter */
1654 0, /* tp_iternext */
1655 deque_methods, /* tp_methods */
1656 0, /* tp_members */
Georg Brandlf038b322010-10-18 07:35:09 +00001657 deque_getset, /* tp_getset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001658 0, /* tp_base */
1659 0, /* tp_dict */
1660 0, /* tp_descr_get */
1661 0, /* tp_descr_set */
1662 0, /* tp_dictoffset */
1663 (initproc)deque_init, /* tp_init */
1664 PyType_GenericAlloc, /* tp_alloc */
1665 deque_new, /* tp_new */
1666 PyObject_GC_Del, /* tp_free */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001667};
1668
1669/*********************** Deque Iterator **************************/
1670
1671typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001672 PyObject_HEAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001673 block *b;
Raymond Hettinger87e69122015-03-02 23:32:02 -08001674 Py_ssize_t index;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001675 dequeobject *deque;
Raymond Hettingerf9d9c792015-03-02 22:47:46 -08001676 size_t state; /* state when the iterator is created */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001677 Py_ssize_t counter; /* number of items remaining for iteration */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001678} dequeiterobject;
1679
Martin v. Löwis59683e82008-06-13 07:50:45 +00001680static PyTypeObject dequeiter_type;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001681
1682static PyObject *
1683deque_iter(dequeobject *deque)
1684{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001685 dequeiterobject *it;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001686
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001687 it = PyObject_GC_New(dequeiterobject, &dequeiter_type);
1688 if (it == NULL)
1689 return NULL;
1690 it->b = deque->leftblock;
1691 it->index = deque->leftindex;
1692 Py_INCREF(deque);
1693 it->deque = deque;
1694 it->state = deque->state;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001695 it->counter = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001696 PyObject_GC_Track(it);
1697 return (PyObject *)it;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001698}
1699
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001700static int
1701dequeiter_traverse(dequeiterobject *dio, visitproc visit, void *arg)
1702{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001703 Py_VISIT(dio->deque);
1704 return 0;
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001705}
1706
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001707static void
1708dequeiter_dealloc(dequeiterobject *dio)
1709{
INADA Naokia6296d32017-08-24 14:55:17 +09001710 /* bpo-31095: UnTrack is needed before calling any callbacks */
1711 PyObject_GC_UnTrack(dio);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001712 Py_XDECREF(dio->deque);
1713 PyObject_GC_Del(dio);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001714}
1715
1716static PyObject *
1717dequeiter_next(dequeiterobject *it)
1718{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001719 PyObject *item;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001720
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001721 if (it->deque->state != it->state) {
1722 it->counter = 0;
1723 PyErr_SetString(PyExc_RuntimeError,
1724 "deque mutated during iteration");
1725 return NULL;
1726 }
1727 if (it->counter == 0)
1728 return NULL;
1729 assert (!(it->b == it->deque->rightblock &&
1730 it->index > it->deque->rightindex));
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001731
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001732 item = it->b->data[it->index];
1733 it->index++;
1734 it->counter--;
1735 if (it->index == BLOCKLEN && it->counter > 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -10001736 CHECK_NOT_END(it->b->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001737 it->b = it->b->rightlink;
1738 it->index = 0;
1739 }
1740 Py_INCREF(item);
1741 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001742}
1743
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001744static PyObject *
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001745dequeiter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1746{
1747 Py_ssize_t i, index=0;
1748 PyObject *deque;
1749 dequeiterobject *it;
1750 if (!PyArg_ParseTuple(args, "O!|n", &deque_type, &deque, &index))
1751 return NULL;
1752 assert(type == &dequeiter_type);
1753
1754 it = (dequeiterobject*)deque_iter((dequeobject *)deque);
1755 if (!it)
1756 return NULL;
1757 /* consume items from the queue */
1758 for(i=0; i<index; i++) {
1759 PyObject *item = dequeiter_next(it);
1760 if (item) {
1761 Py_DECREF(item);
1762 } else {
1763 if (it->counter) {
1764 Py_DECREF(it);
1765 return NULL;
1766 } else
1767 break;
1768 }
1769 }
1770 return (PyObject*)it;
1771}
1772
1773static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301774dequeiter_len(dequeiterobject *it, PyObject *Py_UNUSED(ignored))
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001775{
Antoine Pitrou554f3342010-08-17 18:30:06 +00001776 return PyLong_FromSsize_t(it->counter);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001777}
1778
Armin Rigof5b3e362006-02-11 21:32:43 +00001779PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001780
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001781static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301782dequeiter_reduce(dequeiterobject *it, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001783{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001784 return Py_BuildValue("O(On)", Py_TYPE(it), it->deque, Py_SIZE(it->deque) - it->counter);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001785}
1786
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001787static PyMethodDef dequeiter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001788 {"__length_hint__", (PyCFunction)dequeiter_len, METH_NOARGS, length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001789 {"__reduce__", (PyCFunction)dequeiter_reduce, METH_NOARGS, reduce_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001790 {NULL, NULL} /* sentinel */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001791};
1792
Martin v. Löwis59683e82008-06-13 07:50:45 +00001793static PyTypeObject dequeiter_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001794 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger87e69122015-03-02 23:32:02 -08001795 "_collections._deque_iterator", /* tp_name */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001796 sizeof(dequeiterobject), /* tp_basicsize */
1797 0, /* tp_itemsize */
1798 /* methods */
1799 (destructor)dequeiter_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001800 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001801 0, /* tp_getattr */
1802 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001803 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001804 0, /* tp_repr */
1805 0, /* tp_as_number */
1806 0, /* tp_as_sequence */
1807 0, /* tp_as_mapping */
1808 0, /* tp_hash */
1809 0, /* tp_call */
1810 0, /* tp_str */
1811 PyObject_GenericGetAttr, /* tp_getattro */
1812 0, /* tp_setattro */
1813 0, /* tp_as_buffer */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001814 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001815 0, /* tp_doc */
1816 (traverseproc)dequeiter_traverse, /* tp_traverse */
1817 0, /* tp_clear */
1818 0, /* tp_richcompare */
1819 0, /* tp_weaklistoffset */
1820 PyObject_SelfIter, /* tp_iter */
1821 (iternextfunc)dequeiter_next, /* tp_iternext */
1822 dequeiter_methods, /* tp_methods */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001823 0, /* tp_members */
1824 0, /* tp_getset */
1825 0, /* tp_base */
1826 0, /* tp_dict */
1827 0, /* tp_descr_get */
1828 0, /* tp_descr_set */
1829 0, /* tp_dictoffset */
1830 0, /* tp_init */
1831 0, /* tp_alloc */
1832 dequeiter_new, /* tp_new */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001833 0,
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001834};
1835
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001836/*********************** Deque Reverse Iterator **************************/
1837
Martin v. Löwis59683e82008-06-13 07:50:45 +00001838static PyTypeObject dequereviter_type;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001839
1840static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301841deque_reviter(dequeobject *deque, PyObject *Py_UNUSED(ignored))
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001842{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001843 dequeiterobject *it;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001844
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001845 it = PyObject_GC_New(dequeiterobject, &dequereviter_type);
1846 if (it == NULL)
1847 return NULL;
1848 it->b = deque->rightblock;
1849 it->index = deque->rightindex;
1850 Py_INCREF(deque);
1851 it->deque = deque;
1852 it->state = deque->state;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001853 it->counter = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001854 PyObject_GC_Track(it);
1855 return (PyObject *)it;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001856}
1857
1858static PyObject *
1859dequereviter_next(dequeiterobject *it)
1860{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001861 PyObject *item;
1862 if (it->counter == 0)
1863 return NULL;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001865 if (it->deque->state != it->state) {
1866 it->counter = 0;
1867 PyErr_SetString(PyExc_RuntimeError,
1868 "deque mutated during iteration");
1869 return NULL;
1870 }
1871 assert (!(it->b == it->deque->leftblock &&
1872 it->index < it->deque->leftindex));
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001874 item = it->b->data[it->index];
1875 it->index--;
1876 it->counter--;
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -07001877 if (it->index < 0 && it->counter > 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -10001878 CHECK_NOT_END(it->b->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001879 it->b = it->b->leftlink;
1880 it->index = BLOCKLEN - 1;
1881 }
1882 Py_INCREF(item);
1883 return item;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001884}
1885
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001886static PyObject *
1887dequereviter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1888{
1889 Py_ssize_t i, index=0;
1890 PyObject *deque;
1891 dequeiterobject *it;
1892 if (!PyArg_ParseTuple(args, "O!|n", &deque_type, &deque, &index))
1893 return NULL;
1894 assert(type == &dequereviter_type);
1895
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301896 it = (dequeiterobject*)deque_reviter((dequeobject *)deque, NULL);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001897 if (!it)
1898 return NULL;
1899 /* consume items from the queue */
1900 for(i=0; i<index; i++) {
1901 PyObject *item = dequereviter_next(it);
1902 if (item) {
1903 Py_DECREF(item);
1904 } else {
1905 if (it->counter) {
1906 Py_DECREF(it);
1907 return NULL;
1908 } else
1909 break;
1910 }
1911 }
1912 return (PyObject*)it;
1913}
1914
Martin v. Löwis59683e82008-06-13 07:50:45 +00001915static PyTypeObject dequereviter_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001916 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger87e69122015-03-02 23:32:02 -08001917 "_collections._deque_reverse_iterator", /* tp_name */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001918 sizeof(dequeiterobject), /* tp_basicsize */
1919 0, /* tp_itemsize */
1920 /* methods */
1921 (destructor)dequeiter_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001922 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001923 0, /* tp_getattr */
1924 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001925 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001926 0, /* tp_repr */
1927 0, /* tp_as_number */
1928 0, /* tp_as_sequence */
1929 0, /* tp_as_mapping */
1930 0, /* tp_hash */
1931 0, /* tp_call */
1932 0, /* tp_str */
1933 PyObject_GenericGetAttr, /* tp_getattro */
1934 0, /* tp_setattro */
1935 0, /* tp_as_buffer */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001936 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001937 0, /* tp_doc */
1938 (traverseproc)dequeiter_traverse, /* tp_traverse */
1939 0, /* tp_clear */
1940 0, /* tp_richcompare */
1941 0, /* tp_weaklistoffset */
1942 PyObject_SelfIter, /* tp_iter */
1943 (iternextfunc)dequereviter_next, /* tp_iternext */
1944 dequeiter_methods, /* tp_methods */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001945 0, /* tp_members */
1946 0, /* tp_getset */
1947 0, /* tp_base */
1948 0, /* tp_dict */
1949 0, /* tp_descr_get */
1950 0, /* tp_descr_set */
1951 0, /* tp_dictoffset */
1952 0, /* tp_init */
1953 0, /* tp_alloc */
1954 dequereviter_new, /* tp_new */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001955 0,
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001956};
1957
Guido van Rossum1968ad32006-02-25 22:38:04 +00001958/* defaultdict type *********************************************************/
1959
1960typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001961 PyDictObject dict;
1962 PyObject *default_factory;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001963} defdictobject;
1964
1965static PyTypeObject defdict_type; /* Forward */
1966
1967PyDoc_STRVAR(defdict_missing_doc,
1968"__missing__(key) # Called by __getitem__ for missing key; pseudo-code:\n\
Guido van Rossumd8faa362007-04-27 19:54:29 +00001969 if self.default_factory is None: raise KeyError((key,))\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00001970 self[key] = value = self.default_factory()\n\
1971 return value\n\
1972");
1973
1974static PyObject *
1975defdict_missing(defdictobject *dd, PyObject *key)
1976{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001977 PyObject *factory = dd->default_factory;
1978 PyObject *value;
1979 if (factory == NULL || factory == Py_None) {
1980 /* XXX Call dict.__missing__(key) */
1981 PyObject *tup;
1982 tup = PyTuple_Pack(1, key);
1983 if (!tup) return NULL;
1984 PyErr_SetObject(PyExc_KeyError, tup);
1985 Py_DECREF(tup);
1986 return NULL;
1987 }
Jeroen Demeyer7f41c8e2019-07-04 12:35:31 +02001988 value = _PyObject_CallNoArg(factory);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001989 if (value == NULL)
1990 return value;
1991 if (PyObject_SetItem((PyObject *)dd, key, value) < 0) {
1992 Py_DECREF(value);
1993 return NULL;
1994 }
1995 return value;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001996}
1997
Brandt Bucher57c9d172020-03-06 09:24:08 -08001998static inline PyObject*
1999new_defdict(defdictobject *dd, PyObject *arg)
2000{
2001 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd),
2002 dd->default_factory ? dd->default_factory : Py_None, arg, NULL);
2003}
2004
Guido van Rossum1968ad32006-02-25 22:38:04 +00002005PyDoc_STRVAR(defdict_copy_doc, "D.copy() -> a shallow copy of D.");
2006
2007static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302008defdict_copy(defdictobject *dd, PyObject *Py_UNUSED(ignored))
Guido van Rossum1968ad32006-02-25 22:38:04 +00002009{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002010 /* This calls the object's class. That only works for subclasses
2011 whose class constructor has the same signature. Subclasses that
2012 define a different constructor signature must override copy().
2013 */
Brandt Bucher57c9d172020-03-06 09:24:08 -08002014 return new_defdict(dd, (PyObject*)dd);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002015}
2016
2017static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302018defdict_reduce(defdictobject *dd, PyObject *Py_UNUSED(ignored))
Guido van Rossum1968ad32006-02-25 22:38:04 +00002019{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002020 /* __reduce__ must return a 5-tuple as follows:
Guido van Rossum1968ad32006-02-25 22:38:04 +00002021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002022 - factory function
2023 - tuple of args for the factory function
2024 - additional state (here None)
2025 - sequence iterator (here None)
2026 - dictionary iterator (yielding successive (key, value) pairs
Guido van Rossum1968ad32006-02-25 22:38:04 +00002027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002028 This API is used by pickle.py and copy.py.
Guido van Rossum1968ad32006-02-25 22:38:04 +00002029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002030 For this to be useful with pickle.py, the default_factory
2031 must be picklable; e.g., None, a built-in, or a global
2032 function in a module or package.
Guido van Rossum1968ad32006-02-25 22:38:04 +00002033
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002034 Both shallow and deep copying are supported, but for deep
2035 copying, the default_factory must be deep-copyable; e.g. None,
2036 or a built-in (functions are not copyable at this time).
Guido van Rossum1968ad32006-02-25 22:38:04 +00002037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002038 This only works for subclasses as long as their constructor
2039 signature is compatible; the first argument must be the
2040 optional default_factory, defaulting to None.
2041 */
2042 PyObject *args;
2043 PyObject *items;
2044 PyObject *iter;
2045 PyObject *result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002046 _Py_IDENTIFIER(items);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002048 if (dd->default_factory == NULL || dd->default_factory == Py_None)
2049 args = PyTuple_New(0);
2050 else
2051 args = PyTuple_Pack(1, dd->default_factory);
2052 if (args == NULL)
2053 return NULL;
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002054 items = _PyObject_CallMethodIdNoArgs((PyObject *)dd, &PyId_items);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002055 if (items == NULL) {
2056 Py_DECREF(args);
2057 return NULL;
2058 }
2059 iter = PyObject_GetIter(items);
2060 if (iter == NULL) {
2061 Py_DECREF(items);
2062 Py_DECREF(args);
2063 return NULL;
2064 }
2065 result = PyTuple_Pack(5, Py_TYPE(dd), args,
2066 Py_None, Py_None, iter);
2067 Py_DECREF(iter);
2068 Py_DECREF(items);
2069 Py_DECREF(args);
2070 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00002071}
2072
2073static PyMethodDef defdict_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002074 {"__missing__", (PyCFunction)defdict_missing, METH_O,
2075 defdict_missing_doc},
2076 {"copy", (PyCFunction)defdict_copy, METH_NOARGS,
2077 defdict_copy_doc},
2078 {"__copy__", (PyCFunction)defdict_copy, METH_NOARGS,
2079 defdict_copy_doc},
2080 {"__reduce__", (PyCFunction)defdict_reduce, METH_NOARGS,
2081 reduce_doc},
Guido van Rossum48b069a2020-04-07 09:50:06 -07002082 {"__class_getitem__", (PyCFunction)Py_GenericAlias, METH_O|METH_CLASS,
2083 PyDoc_STR("See PEP 585")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002084 {NULL}
Guido van Rossum1968ad32006-02-25 22:38:04 +00002085};
2086
2087static PyMemberDef defdict_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002088 {"default_factory", T_OBJECT,
2089 offsetof(defdictobject, default_factory), 0,
2090 PyDoc_STR("Factory for default value called by __missing__().")},
2091 {NULL}
Guido van Rossum1968ad32006-02-25 22:38:04 +00002092};
2093
2094static void
2095defdict_dealloc(defdictobject *dd)
2096{
INADA Naokia6296d32017-08-24 14:55:17 +09002097 /* bpo-31095: UnTrack is needed before calling any callbacks */
2098 PyObject_GC_UnTrack(dd);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002099 Py_CLEAR(dd->default_factory);
2100 PyDict_Type.tp_dealloc((PyObject *)dd);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002101}
2102
Guido van Rossum1968ad32006-02-25 22:38:04 +00002103static PyObject *
2104defdict_repr(defdictobject *dd)
2105{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002106 PyObject *baserepr;
2107 PyObject *defrepr;
2108 PyObject *result;
2109 baserepr = PyDict_Type.tp_repr((PyObject *)dd);
2110 if (baserepr == NULL)
2111 return NULL;
2112 if (dd->default_factory == NULL)
2113 defrepr = PyUnicode_FromString("None");
2114 else
2115 {
2116 int status = Py_ReprEnter(dd->default_factory);
2117 if (status != 0) {
Antoine Pitrouf5f1fe02012-02-15 02:42:46 +01002118 if (status < 0) {
2119 Py_DECREF(baserepr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002120 return NULL;
Antoine Pitrouf5f1fe02012-02-15 02:42:46 +01002121 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002122 defrepr = PyUnicode_FromString("...");
2123 }
2124 else
2125 defrepr = PyObject_Repr(dd->default_factory);
2126 Py_ReprLeave(dd->default_factory);
2127 }
2128 if (defrepr == NULL) {
2129 Py_DECREF(baserepr);
2130 return NULL;
2131 }
Serhiy Storchakab3a77962017-09-21 14:24:13 +03002132 result = PyUnicode_FromFormat("%s(%U, %U)",
2133 _PyType_Name(Py_TYPE(dd)),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002134 defrepr, baserepr);
2135 Py_DECREF(defrepr);
2136 Py_DECREF(baserepr);
2137 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00002138}
2139
Brandt Bucher57c9d172020-03-06 09:24:08 -08002140static PyObject*
2141defdict_or(PyObject* left, PyObject* right)
2142{
Brandt Bucher57c9d172020-03-06 09:24:08 -08002143 PyObject *self, *other;
Brandt Bucher1dd37942020-03-11 21:06:46 -07002144 if (PyObject_TypeCheck(left, &defdict_type)) {
Brandt Bucher57c9d172020-03-06 09:24:08 -08002145 self = left;
2146 other = right;
2147 }
2148 else {
2149 self = right;
2150 other = left;
2151 }
2152 if (!PyDict_Check(other)) {
2153 Py_RETURN_NOTIMPLEMENTED;
2154 }
2155 // Like copy(), this calls the object's class.
2156 // Override __or__/__ror__ for subclasses with different constructors.
2157 PyObject *new = new_defdict((defdictobject*)self, left);
2158 if (!new) {
2159 return NULL;
2160 }
2161 if (PyDict_Update(new, right)) {
2162 Py_DECREF(new);
2163 return NULL;
2164 }
2165 return new;
2166}
2167
2168static PyNumberMethods defdict_as_number = {
2169 .nb_or = defdict_or,
2170};
2171
Guido van Rossum1968ad32006-02-25 22:38:04 +00002172static int
2173defdict_traverse(PyObject *self, visitproc visit, void *arg)
2174{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002175 Py_VISIT(((defdictobject *)self)->default_factory);
2176 return PyDict_Type.tp_traverse(self, visit, arg);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002177}
2178
2179static int
2180defdict_tp_clear(defdictobject *dd)
2181{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002182 Py_CLEAR(dd->default_factory);
2183 return PyDict_Type.tp_clear((PyObject *)dd);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002184}
2185
2186static int
2187defdict_init(PyObject *self, PyObject *args, PyObject *kwds)
2188{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002189 defdictobject *dd = (defdictobject *)self;
2190 PyObject *olddefault = dd->default_factory;
2191 PyObject *newdefault = NULL;
2192 PyObject *newargs;
2193 int result;
2194 if (args == NULL || !PyTuple_Check(args))
2195 newargs = PyTuple_New(0);
2196 else {
2197 Py_ssize_t n = PyTuple_GET_SIZE(args);
2198 if (n > 0) {
2199 newdefault = PyTuple_GET_ITEM(args, 0);
2200 if (!PyCallable_Check(newdefault) && newdefault != Py_None) {
2201 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger239aba72015-07-20 03:09:22 -04002202 "first argument must be callable or None");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002203 return -1;
2204 }
2205 }
2206 newargs = PySequence_GetSlice(args, 1, n);
2207 }
2208 if (newargs == NULL)
2209 return -1;
2210 Py_XINCREF(newdefault);
2211 dd->default_factory = newdefault;
2212 result = PyDict_Type.tp_init(self, newargs, kwds);
2213 Py_DECREF(newargs);
2214 Py_XDECREF(olddefault);
2215 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00002216}
2217
2218PyDoc_STRVAR(defdict_doc,
Benjamin Peterson9cb33b72014-01-13 23:56:05 -05002219"defaultdict(default_factory[, ...]) --> dict with default factory\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00002220\n\
2221The default factory is called without arguments to produce\n\
2222a new value when a key is not present, in __getitem__ only.\n\
2223A defaultdict compares equal to a dict with the same items.\n\
Benjamin Peterson9cb33b72014-01-13 23:56:05 -05002224All remaining arguments are treated the same as if they were\n\
2225passed to the dict constructor, including keyword arguments.\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00002226");
2227
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002228/* See comment in xxsubtype.c */
2229#define DEFERRED_ADDRESS(ADDR) 0
2230
Guido van Rossum1968ad32006-02-25 22:38:04 +00002231static PyTypeObject defdict_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002232 PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0)
2233 "collections.defaultdict", /* tp_name */
2234 sizeof(defdictobject), /* tp_basicsize */
2235 0, /* tp_itemsize */
2236 /* methods */
2237 (destructor)defdict_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002238 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002239 0, /* tp_getattr */
2240 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002241 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002242 (reprfunc)defdict_repr, /* tp_repr */
Brandt Bucher57c9d172020-03-06 09:24:08 -08002243 &defdict_as_number, /* tp_as_number */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002244 0, /* tp_as_sequence */
2245 0, /* tp_as_mapping */
2246 0, /* tp_hash */
2247 0, /* tp_call */
2248 0, /* tp_str */
2249 PyObject_GenericGetAttr, /* tp_getattro */
2250 0, /* tp_setattro */
2251 0, /* tp_as_buffer */
2252 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
2253 /* tp_flags */
2254 defdict_doc, /* tp_doc */
2255 defdict_traverse, /* tp_traverse */
2256 (inquiry)defdict_tp_clear, /* tp_clear */
2257 0, /* tp_richcompare */
2258 0, /* tp_weaklistoffset*/
2259 0, /* tp_iter */
2260 0, /* tp_iternext */
2261 defdict_methods, /* tp_methods */
2262 defdict_members, /* tp_members */
2263 0, /* tp_getset */
2264 DEFERRED_ADDRESS(&PyDict_Type), /* tp_base */
2265 0, /* tp_dict */
2266 0, /* tp_descr_get */
2267 0, /* tp_descr_set */
2268 0, /* tp_dictoffset */
2269 defdict_init, /* tp_init */
2270 PyType_GenericAlloc, /* tp_alloc */
2271 0, /* tp_new */
2272 PyObject_GC_Del, /* tp_free */
Guido van Rossum1968ad32006-02-25 22:38:04 +00002273};
2274
Raymond Hettinger96f34102010-12-15 16:30:37 +00002275/* helper function for Counter *********************************************/
2276
Raymond Hettingere9858042019-06-05 16:05:25 -07002277/*[clinic input]
2278_collections._count_elements
2279
2280 mapping: object
2281 iterable: object
2282 /
2283
2284Count elements in the iterable, updating the mapping
2285[clinic start generated code]*/
Raymond Hettinger96f34102010-12-15 16:30:37 +00002286
2287static PyObject *
Raymond Hettingere9858042019-06-05 16:05:25 -07002288_collections__count_elements_impl(PyObject *module, PyObject *mapping,
2289 PyObject *iterable)
2290/*[clinic end generated code: output=7e0c1789636b3d8f input=e79fad04534a0b45]*/
Raymond Hettinger96f34102010-12-15 16:30:37 +00002291{
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002292 _Py_IDENTIFIER(get);
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002293 _Py_IDENTIFIER(__setitem__);
Raymond Hettingere9858042019-06-05 16:05:25 -07002294 PyObject *it, *oldval;
Raymond Hettinger96f34102010-12-15 16:30:37 +00002295 PyObject *newval = NULL;
2296 PyObject *key = NULL;
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002297 PyObject *bound_get = NULL;
2298 PyObject *mapping_get;
2299 PyObject *dict_get;
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002300 PyObject *mapping_setitem;
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002301 PyObject *dict_setitem;
Victor Stinner35b95aa2020-10-27 22:24:33 +01002302 PyObject *one = _PyLong_GetOne(); // borrowed reference
Raymond Hettinger96f34102010-12-15 16:30:37 +00002303
Raymond Hettinger96f34102010-12-15 16:30:37 +00002304 it = PyObject_GetIter(iterable);
2305 if (it == NULL)
2306 return NULL;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002307
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002308 /* Only take the fast path when get() and __setitem__()
2309 * have not been overridden.
2310 */
2311 mapping_get = _PyType_LookupId(Py_TYPE(mapping), &PyId_get);
2312 dict_get = _PyType_LookupId(&PyDict_Type, &PyId_get);
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002313 mapping_setitem = _PyType_LookupId(Py_TYPE(mapping), &PyId___setitem__);
2314 dict_setitem = _PyType_LookupId(&PyDict_Type, &PyId___setitem__);
2315
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002316 if (mapping_get != NULL && mapping_get == dict_get &&
Oren Milman31aca4b2017-09-27 06:18:21 +03002317 mapping_setitem != NULL && mapping_setitem == dict_setitem &&
2318 PyDict_Check(mapping))
2319 {
Raymond Hettinger426e0522011-01-03 02:12:02 +00002320 while (1) {
Raymond Hettinger507d9972014-05-18 21:32:40 +01002321 /* Fast path advantages:
2322 1. Eliminate double hashing
2323 (by re-using the same hash for both the get and set)
2324 2. Avoid argument overhead of PyObject_CallFunctionObjArgs
2325 (argument tuple creation and parsing)
2326 3. Avoid indirection through a bound method object
2327 (creates another argument tuple)
2328 4. Avoid initial increment from zero
2329 (reuse an existing one-object instead)
2330 */
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002331 Py_hash_t hash;
2332
Raymond Hettinger426e0522011-01-03 02:12:02 +00002333 key = PyIter_Next(it);
Victor Stinnera154b5c2011-04-20 23:23:52 +02002334 if (key == NULL)
2335 break;
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002336
2337 if (!PyUnicode_CheckExact(key) ||
2338 (hash = ((PyASCIIObject *) key)->hash) == -1)
2339 {
2340 hash = PyObject_Hash(key);
Raymond Hettingerda2850f2015-02-27 12:42:54 -08002341 if (hash == -1)
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002342 goto done;
2343 }
2344
2345 oldval = _PyDict_GetItem_KnownHash(mapping, key, hash);
Raymond Hettinger426e0522011-01-03 02:12:02 +00002346 if (oldval == NULL) {
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02002347 if (PyErr_Occurred())
2348 goto done;
Victor Stinner35b95aa2020-10-27 22:24:33 +01002349 if (_PyDict_SetItem_KnownHash(mapping, key, one, hash) < 0)
Raymond Hettinger507d9972014-05-18 21:32:40 +01002350 goto done;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002351 } else {
Victor Stinner35b95aa2020-10-27 22:24:33 +01002352 newval = PyNumber_Add(oldval, one);
Raymond Hettinger426e0522011-01-03 02:12:02 +00002353 if (newval == NULL)
Raymond Hettinger507d9972014-05-18 21:32:40 +01002354 goto done;
Raymond Hettinger28c995d2015-08-14 02:07:41 -07002355 if (_PyDict_SetItem_KnownHash(mapping, key, newval, hash) < 0)
Raymond Hettinger507d9972014-05-18 21:32:40 +01002356 goto done;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002357 Py_CLEAR(newval);
2358 }
2359 Py_DECREF(key);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002360 }
Victor Stinner35b95aa2020-10-27 22:24:33 +01002361 }
2362 else {
Victor Stinnere7f516c2013-11-06 23:52:55 +01002363 bound_get = _PyObject_GetAttrId(mapping, &PyId_get);
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002364 if (bound_get == NULL)
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002365 goto done;
2366
Victor Stinner37834132020-10-27 17:12:53 +01002367 PyObject *zero = _PyLong_GetZero(); // borrowed reference
Raymond Hettinger426e0522011-01-03 02:12:02 +00002368 while (1) {
2369 key = PyIter_Next(it);
Victor Stinnera154b5c2011-04-20 23:23:52 +02002370 if (key == NULL)
2371 break;
Victor Stinner37834132020-10-27 17:12:53 +01002372 oldval = PyObject_CallFunctionObjArgs(bound_get, key, zero, NULL);
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002373 if (oldval == NULL)
2374 break;
Victor Stinner37834132020-10-27 17:12:53 +01002375 newval = PyNumber_Add(oldval, one);
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002376 Py_DECREF(oldval);
2377 if (newval == NULL)
2378 break;
Raymond Hettinger28c995d2015-08-14 02:07:41 -07002379 if (PyObject_SetItem(mapping, key, newval) < 0)
Raymond Hettinger96f34102010-12-15 16:30:37 +00002380 break;
2381 Py_CLEAR(newval);
Raymond Hettinger426e0522011-01-03 02:12:02 +00002382 Py_DECREF(key);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002383 }
Raymond Hettinger96f34102010-12-15 16:30:37 +00002384 }
Raymond Hettinger426e0522011-01-03 02:12:02 +00002385
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002386done:
Raymond Hettinger96f34102010-12-15 16:30:37 +00002387 Py_DECREF(it);
2388 Py_XDECREF(key);
2389 Py_XDECREF(newval);
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002390 Py_XDECREF(bound_get);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002391 if (PyErr_Occurred())
2392 return NULL;
2393 Py_RETURN_NONE;
2394}
2395
Serhiy Storchaka052b2df2018-12-31 14:15:16 +02002396/* Helper function for namedtuple() ************************************/
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002397
2398typedef struct {
2399 PyObject_HEAD
2400 Py_ssize_t index;
2401 PyObject* doc;
2402} _tuplegetterobject;
2403
2404/*[clinic input]
2405@classmethod
2406_tuplegetter.__new__ as tuplegetter_new
2407
2408 index: Py_ssize_t
2409 doc: object
2410 /
2411[clinic start generated code]*/
2412
2413static PyObject *
2414tuplegetter_new_impl(PyTypeObject *type, Py_ssize_t index, PyObject *doc)
2415/*[clinic end generated code: output=014be444ad80263f input=87c576a5bdbc0bbb]*/
2416{
2417 _tuplegetterobject* self;
2418 self = (_tuplegetterobject *)type->tp_alloc(type, 0);
2419 if (self == NULL) {
2420 return NULL;
2421 }
2422 self->index = index;
2423 Py_INCREF(doc);
2424 self->doc = doc;
2425 return (PyObject *)self;
2426}
2427
2428static PyObject *
Serhiy Storchaka052b2df2018-12-31 14:15:16 +02002429tuplegetter_descr_get(PyObject *self, PyObject *obj, PyObject *type)
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002430{
Serhiy Storchaka052b2df2018-12-31 14:15:16 +02002431 Py_ssize_t index = ((_tuplegetterobject*)self)->index;
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002432 PyObject *result;
Serhiy Storchaka052b2df2018-12-31 14:15:16 +02002433
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002434 if (obj == NULL) {
2435 Py_INCREF(self);
2436 return self;
2437 }
2438 if (!PyTuple_Check(obj)) {
2439 if (obj == Py_None) {
2440 Py_INCREF(self);
2441 return self;
2442 }
2443 PyErr_Format(PyExc_TypeError,
Serhiy Storchakad53fe5f2019-03-13 22:59:55 +02002444 "descriptor for index '%zd' for tuple subclasses "
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002445 "doesn't apply to '%s' object",
Serhiy Storchaka052b2df2018-12-31 14:15:16 +02002446 index,
Victor Stinnerdaa97562020-02-07 03:37:06 +01002447 Py_TYPE(obj)->tp_name);
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002448 return NULL;
2449 }
2450
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002451 if (!valid_index(index, PyTuple_GET_SIZE(obj))) {
2452 PyErr_SetString(PyExc_IndexError, "tuple index out of range");
2453 return NULL;
2454 }
2455
2456 result = PyTuple_GET_ITEM(obj, index);
2457 Py_INCREF(result);
2458 return result;
2459}
2460
2461static int
Serhiy Storchaka052b2df2018-12-31 14:15:16 +02002462tuplegetter_descr_set(PyObject *self, PyObject *obj, PyObject *value)
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002463{
2464 if (value == NULL) {
2465 PyErr_SetString(PyExc_AttributeError, "can't delete attribute");
2466 } else {
2467 PyErr_SetString(PyExc_AttributeError, "can't set attribute");
2468 }
2469 return -1;
2470}
2471
2472static int
2473tuplegetter_traverse(PyObject *self, visitproc visit, void *arg)
2474{
2475 _tuplegetterobject *tuplegetter = (_tuplegetterobject *)self;
2476 Py_VISIT(tuplegetter->doc);
2477 return 0;
2478}
2479
2480static int
2481tuplegetter_clear(PyObject *self)
2482{
2483 _tuplegetterobject *tuplegetter = (_tuplegetterobject *)self;
2484 Py_CLEAR(tuplegetter->doc);
2485 return 0;
2486}
2487
2488static void
2489tuplegetter_dealloc(_tuplegetterobject *self)
2490{
2491 PyObject_GC_UnTrack(self);
2492 tuplegetter_clear((PyObject*)self);
2493 Py_TYPE(self)->tp_free((PyObject*)self);
2494}
2495
Joe Jevnikf36f8922019-02-21 16:00:40 -05002496static PyObject*
Serhiy Storchakaadfffc72019-03-05 18:41:09 +02002497tuplegetter_reduce(_tuplegetterobject *self, PyObject *Py_UNUSED(ignored))
Joe Jevnikf36f8922019-02-21 16:00:40 -05002498{
2499 return Py_BuildValue("(O(nO))", (PyObject*) Py_TYPE(self), self->index, self->doc);
2500}
2501
Ammar Askara86b5222020-04-14 23:36:08 -07002502static PyObject*
2503tuplegetter_repr(_tuplegetterobject *self)
2504{
2505 return PyUnicode_FromFormat("%s(%zd, %R)",
2506 _PyType_Name(Py_TYPE(self)),
2507 self->index, self->doc);
2508}
2509
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002510
2511static PyMemberDef tuplegetter_members[] = {
2512 {"__doc__", T_OBJECT, offsetof(_tuplegetterobject, doc), 0},
2513 {0}
2514};
2515
Joe Jevnikf36f8922019-02-21 16:00:40 -05002516static PyMethodDef tuplegetter_methods[] = {
Serhiy Storchakaadfffc72019-03-05 18:41:09 +02002517 {"__reduce__", (PyCFunction)tuplegetter_reduce, METH_NOARGS, NULL},
Joe Jevnikf36f8922019-02-21 16:00:40 -05002518 {NULL},
2519};
2520
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002521static PyTypeObject tuplegetter_type = {
2522 PyVarObject_HEAD_INIT(NULL, 0)
2523 "_collections._tuplegetter", /* tp_name */
2524 sizeof(_tuplegetterobject), /* tp_basicsize */
2525 0, /* tp_itemsize */
2526 /* methods */
2527 (destructor)tuplegetter_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002528 0, /* tp_vectorcall_offset */
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002529 0, /* tp_getattr */
2530 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002531 0, /* tp_as_async */
Ammar Askara86b5222020-04-14 23:36:08 -07002532 (reprfunc)tuplegetter_repr, /* tp_repr */
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002533 0, /* tp_as_number */
2534 0, /* tp_as_sequence */
2535 0, /* tp_as_mapping */
2536 0, /* tp_hash */
2537 0, /* tp_call */
2538 0, /* tp_str */
2539 0, /* tp_getattro */
2540 0, /* tp_setattro */
2541 0, /* tp_as_buffer */
2542 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
2543 0, /* tp_doc */
2544 (traverseproc)tuplegetter_traverse, /* tp_traverse */
2545 (inquiry)tuplegetter_clear, /* tp_clear */
2546 0, /* tp_richcompare */
2547 0, /* tp_weaklistoffset */
2548 0, /* tp_iter */
2549 0, /* tp_iternext */
Joe Jevnikf36f8922019-02-21 16:00:40 -05002550 tuplegetter_methods, /* tp_methods */
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002551 tuplegetter_members, /* tp_members */
2552 0, /* tp_getset */
2553 0, /* tp_base */
2554 0, /* tp_dict */
Serhiy Storchaka052b2df2018-12-31 14:15:16 +02002555 tuplegetter_descr_get, /* tp_descr_get */
2556 tuplegetter_descr_set, /* tp_descr_set */
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002557 0, /* tp_dictoffset */
2558 0, /* tp_init */
2559 0, /* tp_alloc */
2560 tuplegetter_new, /* tp_new */
2561 0,
2562};
2563
2564
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002565/* module level code ********************************************************/
2566
Dong-hee Na77248a22020-03-20 01:16:04 +09002567PyDoc_STRVAR(collections_doc,
Guido van Rossum1968ad32006-02-25 22:38:04 +00002568"High performance data structures.\n\
2569- deque: ordered collection accessible from endpoints only\n\
2570- defaultdict: dict subclass with a default value factory\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002571");
2572
Dong-hee Na77248a22020-03-20 01:16:04 +09002573static struct PyMethodDef collections_methods[] = {
Raymond Hettingere9858042019-06-05 16:05:25 -07002574 _COLLECTIONS__COUNT_ELEMENTS_METHODDEF
Raymond Hettinger96f34102010-12-15 16:30:37 +00002575 {NULL, NULL} /* sentinel */
2576};
Martin v. Löwis1a214512008-06-11 05:26:20 +00002577
Dong-hee Na77248a22020-03-20 01:16:04 +09002578static int
2579collections_exec(PyObject *module) {
2580 PyTypeObject *typelist[] = {
2581 &deque_type,
2582 &defdict_type,
2583 &PyODict_Type,
2584 &dequeiter_type,
2585 &dequereviter_type,
Dong-hee Na05e4a292020-03-23 01:17:34 +09002586 &tuplegetter_type
Dong-hee Na77248a22020-03-20 01:16:04 +09002587 };
2588
2589 defdict_type.tp_base = &PyDict_Type;
2590
Dong-hee Na05e4a292020-03-23 01:17:34 +09002591 for (size_t i = 0; i < Py_ARRAY_LENGTH(typelist); i++) {
2592 if (PyModule_AddType(module, typelist[i]) < 0) {
Dong-hee Na77248a22020-03-20 01:16:04 +09002593 return -1;
2594 }
2595 }
2596
2597 return 0;
2598}
2599
2600static struct PyModuleDef_Slot collections_slots[] = {
2601 {Py_mod_exec, collections_exec},
2602 {0, NULL}
2603};
2604
Martin v. Löwis1a214512008-06-11 05:26:20 +00002605static struct PyModuleDef _collectionsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002606 PyModuleDef_HEAD_INIT,
2607 "_collections",
Dong-hee Na77248a22020-03-20 01:16:04 +09002608 collections_doc,
2609 0,
2610 collections_methods,
2611 collections_slots,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002612 NULL,
2613 NULL,
2614 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002615};
2616
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002617PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002618PyInit__collections(void)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002619{
Dong-hee Na77248a22020-03-20 01:16:04 +09002620 return PyModuleDef_Init(&_collectionsmodule);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002621}