blob: 00198ff3eb7ddbcecced6392e554a43dd13b2538 [file] [log] [blame]
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001#include "Python.h"
Victor Stinner4a21e572020-04-15 02:35:41 +02002#include "structmember.h" // PyMemberDef
Raymond Hettinger756b3f32004-01-29 06:37:52 +00003
Raymond Hettingerc2083082015-02-28 23:29:16 -08004#ifdef STDC_HEADERS
5#include <stddef.h>
6#else
Victor Stinner4a21e572020-04-15 02:35:41 +02007#include <sys/types.h> // size_t
Raymond Hettingerc2083082015-02-28 23:29:16 -08008#endif
9
Pablo Galindo3f5fc702018-12-30 09:24:03 +000010/*[clinic input]
Raymond Hettingere9858042019-06-05 16:05:25 -070011module _collections
Pablo Galindo3f5fc702018-12-30 09:24:03 +000012class _tuplegetter "_tuplegetterobject *" "&tuplegetter_type"
13[clinic start generated code]*/
Raymond Hettingere9858042019-06-05 16:05:25 -070014/*[clinic end generated code: output=da39a3ee5e6b4b0d input=a8ece4ccad7e30ac]*/
Pablo Galindo3f5fc702018-12-30 09:24:03 +000015
16static PyTypeObject tuplegetter_type;
17#include "clinic/_collectionsmodule.c.h"
18
Raymond Hettinger756b3f32004-01-29 06:37:52 +000019/* collections module implementation of a deque() datatype
20 Written and maintained by Raymond D. Hettinger <python@rcn.com>
Raymond Hettinger756b3f32004-01-29 06:37:52 +000021*/
22
Raymond Hettinger77e8bf12004-10-01 15:25:53 +000023/* The block length may be set to any number over 1. Larger numbers
Raymond Hettinger20b0f872013-06-23 15:44:33 -070024 * reduce the number of calls to the memory allocator, give faster
Raymond Hettinger30c90742015-03-02 22:31:35 -080025 * indexing and rotation, and reduce the link to data overhead ratio.
Raymond Hettingerdaf57f22015-02-26 23:21:29 -080026 * Making the block length a power of two speeds-up the modulo
Raymond Hettinger30c90742015-03-02 22:31:35 -080027 * and division calculations in deque_item() and deque_ass_item().
Raymond Hettinger77e8bf12004-10-01 15:25:53 +000028 */
29
Raymond Hettingerdaf57f22015-02-26 23:21:29 -080030#define BLOCKLEN 64
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000031#define CENTER ((BLOCKLEN - 1) / 2)
Raymond Hettinger756b3f32004-01-29 06:37:52 +000032
Raymond Hettinger551350a2015-03-24 00:19:53 -070033/* Data for deque objects is stored in a doubly-linked list of fixed
34 * length blocks. This assures that appends or pops never move any
35 * other data elements besides the one being appended or popped.
36 *
37 * Another advantage is that it completely avoids use of realloc(),
38 * resulting in more predictable performance.
39 *
40 * Textbook implementations of doubly-linked lists store one datum
41 * per link, but that gives them a 200% memory overhead (a prev and
42 * next link for each datum) and it costs one malloc() call per data
43 * element. By using fixed-length blocks, the link to data ratio is
44 * significantly improved and there are proportionally fewer calls
45 * to malloc() and free(). The data blocks of consecutive pointers
46 * also improve cache locality.
47 *
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000048 * The list of blocks is never empty, so d.leftblock and d.rightblock
Raymond Hettinger82df9252013-07-07 01:43:42 -100049 * are never equal to NULL. The list is not circular.
50 *
51 * A deque d's first element is at d.leftblock[leftindex]
52 * and its last element is at d.rightblock[rightindex].
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000053 *
Raymond Hettinger551350a2015-03-24 00:19:53 -070054 * Unlike Python slice indices, these indices are inclusive on both
55 * ends. This makes the algorithms for left and right operations
56 * more symmetrical and it simplifies the design.
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000057 *
Raymond Hettinger551350a2015-03-24 00:19:53 -070058 * The indices, d.leftindex and d.rightindex are always in the range:
59 * 0 <= index < BLOCKLEN
60 *
61 * And their exact relationship is:
62 * (d.leftindex + d.len - 1) % BLOCKLEN == d.rightindex
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000063 *
Raymond Hettinger8dbbae22015-03-24 21:01:50 -070064 * Whenever d.leftblock == d.rightblock, then:
Raymond Hettinger551350a2015-03-24 00:19:53 -070065 * d.leftindex + d.len - 1 == d.rightindex
Thomas Wouters0e3f5912006-08-11 14:57:12 +000066 *
Raymond Hettinger551350a2015-03-24 00:19:53 -070067 * However, when d.leftblock != d.rightblock, the d.leftindex and
68 * d.rightindex become indices into distinct blocks and either may
69 * be larger than the other.
70 *
71 * Empty deques have:
72 * d.len == 0
73 * d.leftblock == d.rightblock
74 * d.leftindex == CENTER + 1
75 * d.rightindex == CENTER
76 *
77 * Checking for d.len == 0 is the intended way to see whether d is empty.
Tim Petersd8768d32004-10-01 01:32:53 +000078 */
79
Raymond Hettinger756b3f32004-01-29 06:37:52 +000080typedef struct BLOCK {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000081 struct BLOCK *leftlink;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000082 PyObject *data[BLOCKLEN];
Raymond Hettinger20b0f872013-06-23 15:44:33 -070083 struct BLOCK *rightlink;
Raymond Hettinger756b3f32004-01-29 06:37:52 +000084} block;
85
Raymond Hettinger30c90742015-03-02 22:31:35 -080086typedef struct {
87 PyObject_VAR_HEAD
88 block *leftblock;
89 block *rightblock;
Raymond Hettinger551350a2015-03-24 00:19:53 -070090 Py_ssize_t leftindex; /* 0 <= leftindex < BLOCKLEN */
91 Py_ssize_t rightindex; /* 0 <= rightindex < BLOCKLEN */
Raymond Hettingerf9d9c792015-03-02 22:47:46 -080092 size_t state; /* incremented whenever the indices move */
Raymond Hettingerd84ec222016-01-24 09:12:06 -080093 Py_ssize_t maxlen; /* maxlen is -1 for unbounded deques */
Raymond Hettinger0f6f9472015-03-21 01:42:10 -070094 PyObject *weakreflist;
Raymond Hettinger30c90742015-03-02 22:31:35 -080095} dequeobject;
96
97static PyTypeObject deque_type;
98
Raymond Hettinger82df9252013-07-07 01:43:42 -100099/* For debug builds, add error checking to track the endpoints
100 * in the chain of links. The goal is to make sure that link
101 * assignments only take place at endpoints so that links already
102 * in use do not get overwritten.
103 *
104 * CHECK_END should happen before each assignment to a block's link field.
105 * MARK_END should happen whenever a link field becomes a new endpoint.
106 * This happens when new blocks are added or whenever an existing
107 * block is freed leaving another existing block as the new endpoint.
108 */
109
Raymond Hettinger3223dd52013-07-26 23:14:22 -0700110#ifndef NDEBUG
Raymond Hettinger82df9252013-07-07 01:43:42 -1000111#define MARK_END(link) link = NULL;
112#define CHECK_END(link) assert(link == NULL);
113#define CHECK_NOT_END(link) assert(link != NULL);
114#else
115#define MARK_END(link)
116#define CHECK_END(link)
117#define CHECK_NOT_END(link)
118#endif
119
Tim Peters6f853562004-10-01 01:04:50 +0000120static block *
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700121newblock(void) {
Raymond Hettinger32f2eda2020-06-23 06:50:15 -0700122 block *b = PyMem_Malloc(sizeof(block));
Raymond Hettinger82df9252013-07-07 01:43:42 -1000123 if (b != NULL) {
124 return b;
125 }
126 PyErr_NoMemory();
127 return NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000128}
129
Martin v. Löwis59683e82008-06-13 07:50:45 +0000130static void
Guido van Rossum58da9312007-11-10 23:39:45 +0000131freeblock(block *b)
132{
Raymond Hettinger32f2eda2020-06-23 06:50:15 -0700133 PyMem_Free(b);
Guido van Rossum58da9312007-11-10 23:39:45 +0000134}
135
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000136static PyObject *
137deque_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
138{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000139 dequeobject *deque;
140 block *b;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000142 /* create dequeobject structure */
143 deque = (dequeobject *)type->tp_alloc(type, 0);
144 if (deque == NULL)
145 return NULL;
Tim Peters1065f752004-10-01 01:03:29 +0000146
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700147 b = newblock();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000148 if (b == NULL) {
149 Py_DECREF(deque);
150 return NULL;
151 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000152 MARK_END(b->leftlink);
153 MARK_END(b->rightlink);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000154
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000155 assert(BLOCKLEN >= 2);
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100156 Py_SET_SIZE(deque, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000157 deque->leftblock = b;
158 deque->rightblock = b;
159 deque->leftindex = CENTER + 1;
160 deque->rightindex = CENTER;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000161 deque->state = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000162 deque->maxlen = -1;
Raymond Hettinger87e69122015-03-02 23:32:02 -0800163 deque->weakreflist = NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000165 return (PyObject *)deque;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000166}
167
168static PyObject *
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000169deque_pop(dequeobject *deque, PyObject *unused)
170{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000171 PyObject *item;
172 block *prevblock;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000173
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000174 if (Py_SIZE(deque) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175 PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
176 return NULL;
177 }
178 item = deque->rightblock->data[deque->rightindex];
179 deque->rightindex--;
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100180 Py_SET_SIZE(deque, Py_SIZE(deque) - 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000181 deque->state++;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000182
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -0700183 if (deque->rightindex < 0) {
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700184 if (Py_SIZE(deque)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000185 prevblock = deque->rightblock->leftlink;
186 assert(deque->leftblock != deque->rightblock);
187 freeblock(deque->rightblock);
Raymond Hettinger82df9252013-07-07 01:43:42 -1000188 CHECK_NOT_END(prevblock);
189 MARK_END(prevblock->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000190 deque->rightblock = prevblock;
191 deque->rightindex = BLOCKLEN - 1;
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700192 } else {
193 assert(deque->leftblock == deque->rightblock);
194 assert(deque->leftindex == deque->rightindex+1);
195 /* re-center instead of freeing a block */
196 deque->leftindex = CENTER + 1;
197 deque->rightindex = CENTER;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000198 }
199 }
200 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000201}
202
203PyDoc_STRVAR(pop_doc, "Remove and return the rightmost element.");
204
205static PyObject *
206deque_popleft(dequeobject *deque, PyObject *unused)
207{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000208 PyObject *item;
209 block *prevblock;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000210
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000211 if (Py_SIZE(deque) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000212 PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
213 return NULL;
214 }
215 assert(deque->leftblock != NULL);
216 item = deque->leftblock->data[deque->leftindex];
217 deque->leftindex++;
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100218 Py_SET_SIZE(deque, Py_SIZE(deque) - 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000219 deque->state++;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000221 if (deque->leftindex == BLOCKLEN) {
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700222 if (Py_SIZE(deque)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000223 assert(deque->leftblock != deque->rightblock);
224 prevblock = deque->leftblock->rightlink;
225 freeblock(deque->leftblock);
Raymond Hettinger82df9252013-07-07 01:43:42 -1000226 CHECK_NOT_END(prevblock);
227 MARK_END(prevblock->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000228 deque->leftblock = prevblock;
229 deque->leftindex = 0;
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700230 } else {
231 assert(deque->leftblock == deque->rightblock);
232 assert(deque->leftindex == deque->rightindex+1);
233 /* re-center instead of freeing a block */
234 deque->leftindex = CENTER + 1;
235 deque->rightindex = CENTER;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000236 }
237 }
238 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000239}
240
241PyDoc_STRVAR(popleft_doc, "Remove and return the leftmost element.");
242
Raymond Hettingerf30f5b92015-03-02 22:23:37 -0800243/* The deque's size limit is d.maxlen. The limit can be zero or positive.
244 * If there is no limit, then d.maxlen == -1.
245 *
Raymond Hettingera4b13d02015-10-15 08:05:31 -0700246 * After an item is added to a deque, we check to see if the size has
247 * grown past the limit. If it has, we get the size back down to the limit
248 * by popping an item off of the opposite end. The methods that can
249 * trigger this are append(), appendleft(), extend(), and extendleft().
Raymond Hettingerd96db092015-10-11 22:34:48 -0700250 *
251 * The macro to check whether a deque needs to be trimmed uses a single
252 * unsigned test that returns true whenever 0 <= maxlen < Py_SIZE(deque).
Raymond Hettingerf30f5b92015-03-02 22:23:37 -0800253 */
254
Raymond Hettingerd96db092015-10-11 22:34:48 -0700255#define NEEDS_TRIM(deque, maxlen) ((size_t)(maxlen) < (size_t)(Py_SIZE(deque)))
Raymond Hettingerf30f5b92015-03-02 22:23:37 -0800256
Raymond Hettinger66953f02018-07-10 04:17:40 -0700257static inline int
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800258deque_append_internal(dequeobject *deque, PyObject *item, Py_ssize_t maxlen)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000259{
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700260 if (deque->rightindex == BLOCKLEN - 1) {
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700261 block *b = newblock();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000262 if (b == NULL)
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800263 return -1;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000264 b->leftlink = deque->rightblock;
265 CHECK_END(deque->rightblock->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000266 deque->rightblock->rightlink = b;
267 deque->rightblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000268 MARK_END(b->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000269 deque->rightindex = -1;
270 }
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100271 Py_SET_SIZE(deque, Py_SIZE(deque) + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000272 deque->rightindex++;
273 deque->rightblock->data[deque->rightindex] = item;
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800274 if (NEEDS_TRIM(deque, maxlen)) {
Raymond Hettinger1286d142015-10-14 23:16:57 -0700275 PyObject *olditem = deque_popleft(deque, NULL);
276 Py_DECREF(olditem);
Raymond Hettinger0f43bb12015-10-20 00:03:33 -0700277 } else {
278 deque->state++;
Raymond Hettingerd96db092015-10-11 22:34:48 -0700279 }
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800280 return 0;
281}
282
283static PyObject *
284deque_append(dequeobject *deque, PyObject *item)
285{
286 Py_INCREF(item);
287 if (deque_append_internal(deque, item, deque->maxlen) < 0)
288 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000289 Py_RETURN_NONE;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000290}
291
292PyDoc_STRVAR(append_doc, "Add an element to the right side of the deque.");
293
Raymond Hettinger66953f02018-07-10 04:17:40 -0700294static inline int
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800295deque_appendleft_internal(dequeobject *deque, PyObject *item, Py_ssize_t maxlen)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000296{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000297 if (deque->leftindex == 0) {
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700298 block *b = newblock();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000299 if (b == NULL)
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800300 return -1;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000301 b->rightlink = deque->leftblock;
302 CHECK_END(deque->leftblock->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000303 deque->leftblock->leftlink = b;
304 deque->leftblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000305 MARK_END(b->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000306 deque->leftindex = BLOCKLEN;
307 }
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100308 Py_SET_SIZE(deque, Py_SIZE(deque) + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000309 deque->leftindex--;
310 deque->leftblock->data[deque->leftindex] = item;
Raymond Hettingerd96db092015-10-11 22:34:48 -0700311 if (NEEDS_TRIM(deque, deque->maxlen)) {
Raymond Hettinger1286d142015-10-14 23:16:57 -0700312 PyObject *olditem = deque_pop(deque, NULL);
313 Py_DECREF(olditem);
Raymond Hettinger0f43bb12015-10-20 00:03:33 -0700314 } else {
315 deque->state++;
Raymond Hettingerd96db092015-10-11 22:34:48 -0700316 }
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800317 return 0;
318}
319
320static PyObject *
321deque_appendleft(dequeobject *deque, PyObject *item)
322{
323 Py_INCREF(item);
324 if (deque_appendleft_internal(deque, item, deque->maxlen) < 0)
325 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000326 Py_RETURN_NONE;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000327}
328
329PyDoc_STRVAR(appendleft_doc, "Add an element to the left side of the deque.");
330
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700331static PyObject*
332finalize_iterator(PyObject *it)
333{
334 if (PyErr_Occurred()) {
335 if (PyErr_ExceptionMatches(PyExc_StopIteration))
336 PyErr_Clear();
337 else {
338 Py_DECREF(it);
339 return NULL;
340 }
341 }
342 Py_DECREF(it);
343 Py_RETURN_NONE;
344}
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000346/* Run an iterator to exhaustion. Shortcut for
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000347 the extend/extendleft methods when maxlen == 0. */
348static PyObject*
349consume_iterator(PyObject *it)
350{
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700351 PyObject *(*iternext)(PyObject *);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000352 PyObject *item;
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000353
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700354 iternext = *Py_TYPE(it)->tp_iternext;
355 while ((item = iternext(it)) != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000356 Py_DECREF(item);
357 }
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700358 return finalize_iterator(it);
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000359}
360
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000361static PyObject *
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000362deque_extend(dequeobject *deque, PyObject *iterable)
363{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000364 PyObject *it, *item;
Raymond Hettinger7a845522015-09-26 01:30:51 -0700365 PyObject *(*iternext)(PyObject *);
Raymond Hettinger6b1e1132015-10-11 09:43:50 -0700366 Py_ssize_t maxlen = deque->maxlen;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000368 /* Handle case where id(deque) == id(iterable) */
369 if ((PyObject *)deque == iterable) {
370 PyObject *result;
371 PyObject *s = PySequence_List(iterable);
372 if (s == NULL)
373 return NULL;
374 result = deque_extend(deque, s);
375 Py_DECREF(s);
376 return result;
377 }
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000378
Raymond Hettingerd79d5b12016-03-04 09:55:07 -0800379 it = PyObject_GetIter(iterable);
380 if (it == NULL)
381 return NULL;
382
383 if (maxlen == 0)
384 return consume_iterator(it);
385
Raymond Hettingerd9c116c2013-07-09 00:13:21 -0700386 /* Space saving heuristic. Start filling from the left */
387 if (Py_SIZE(deque) == 0) {
388 assert(deque->leftblock == deque->rightblock);
389 assert(deque->leftindex == deque->rightindex+1);
390 deque->leftindex = 1;
391 deque->rightindex = 0;
392 }
393
Raymond Hettinger7a845522015-09-26 01:30:51 -0700394 iternext = *Py_TYPE(it)->tp_iternext;
395 while ((item = iternext(it)) != NULL) {
Raymond Hettinger66953f02018-07-10 04:17:40 -0700396 if (deque_append_internal(deque, item, maxlen) == -1) {
397 Py_DECREF(item);
398 Py_DECREF(it);
399 return NULL;
Raymond Hettinger6b1e1132015-10-11 09:43:50 -0700400 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000401 }
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700402 return finalize_iterator(it);
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000403}
404
Tim Peters1065f752004-10-01 01:03:29 +0000405PyDoc_STRVAR(extend_doc,
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000406"Extend the right side of the deque with elements from the iterable");
407
408static PyObject *
409deque_extendleft(dequeobject *deque, PyObject *iterable)
410{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 PyObject *it, *item;
Raymond Hettinger7a845522015-09-26 01:30:51 -0700412 PyObject *(*iternext)(PyObject *);
Raymond Hettinger6b1e1132015-10-11 09:43:50 -0700413 Py_ssize_t maxlen = deque->maxlen;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000415 /* Handle case where id(deque) == id(iterable) */
416 if ((PyObject *)deque == iterable) {
417 PyObject *result;
418 PyObject *s = PySequence_List(iterable);
419 if (s == NULL)
420 return NULL;
421 result = deque_extendleft(deque, s);
422 Py_DECREF(s);
423 return result;
424 }
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000425
Raymond Hettingerd79d5b12016-03-04 09:55:07 -0800426 it = PyObject_GetIter(iterable);
427 if (it == NULL)
428 return NULL;
429
430 if (maxlen == 0)
431 return consume_iterator(it);
432
Raymond Hettingerd9c116c2013-07-09 00:13:21 -0700433 /* Space saving heuristic. Start filling from the right */
434 if (Py_SIZE(deque) == 0) {
435 assert(deque->leftblock == deque->rightblock);
436 assert(deque->leftindex == deque->rightindex+1);
437 deque->leftindex = BLOCKLEN - 1;
438 deque->rightindex = BLOCKLEN - 2;
439 }
440
Raymond Hettinger7a845522015-09-26 01:30:51 -0700441 iternext = *Py_TYPE(it)->tp_iternext;
442 while ((item = iternext(it)) != NULL) {
Raymond Hettinger66953f02018-07-10 04:17:40 -0700443 if (deque_appendleft_internal(deque, item, maxlen) == -1) {
444 Py_DECREF(item);
445 Py_DECREF(it);
446 return NULL;
Raymond Hettinger6b1e1132015-10-11 09:43:50 -0700447 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000448 }
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700449 return finalize_iterator(it);
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000450}
451
Tim Peters1065f752004-10-01 01:03:29 +0000452PyDoc_STRVAR(extendleft_doc,
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000453"Extend the left side of the deque with elements from the iterable");
454
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000455static PyObject *
456deque_inplace_concat(dequeobject *deque, PyObject *other)
457{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000458 PyObject *result;
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 result = deque_extend(deque, other);
461 if (result == NULL)
462 return result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000463 Py_INCREF(deque);
Raymond Hettinger2b2b7532015-09-05 17:05:52 -0700464 Py_DECREF(result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000465 return (PyObject *)deque;
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000466}
467
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700468static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530469deque_copy(PyObject *deque, PyObject *Py_UNUSED(ignored))
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700470{
Oren Milman24bd50b2018-09-11 21:46:55 +0300471 PyObject *result;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700472 dequeobject *old_deque = (dequeobject *)deque;
Andy Lesterdffe4c02020-03-04 07:15:20 -0600473 if (Py_IS_TYPE(deque, &deque_type)) {
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700474 dequeobject *new_deque;
475 PyObject *rv;
476
477 new_deque = (dequeobject *)deque_new(&deque_type, (PyObject *)NULL, (PyObject *)NULL);
478 if (new_deque == NULL)
479 return NULL;
480 new_deque->maxlen = old_deque->maxlen;
481 /* Fast path for the deque_repeat() common case where len(deque) == 1 */
Raymond Hettinger0443ac22015-10-05 22:52:37 -0400482 if (Py_SIZE(deque) == 1) {
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700483 PyObject *item = old_deque->leftblock->data[old_deque->leftindex];
484 rv = deque_append(new_deque, item);
485 } else {
486 rv = deque_extend(new_deque, deque);
487 }
488 if (rv != NULL) {
489 Py_DECREF(rv);
490 return (PyObject *)new_deque;
491 }
492 Py_DECREF(new_deque);
493 return NULL;
494 }
495 if (old_deque->maxlen < 0)
Petr Viktorinffd97532020-02-11 17:46:57 +0100496 result = PyObject_CallOneArg((PyObject *)(Py_TYPE(deque)), deque);
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700497 else
Oren Milman24bd50b2018-09-11 21:46:55 +0300498 result = PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "Oi",
499 deque, old_deque->maxlen, NULL);
500 if (result != NULL && !PyObject_TypeCheck(result, &deque_type)) {
501 PyErr_Format(PyExc_TypeError,
502 "%.200s() must return a deque, not %.200s",
503 Py_TYPE(deque)->tp_name, Py_TYPE(result)->tp_name);
504 Py_DECREF(result);
505 return NULL;
506 }
507 return result;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700508}
509
510PyDoc_STRVAR(copy_doc, "Return a shallow copy of a deque.");
Raymond Hettinger41290a62015-03-31 08:12:23 -0700511
512static PyObject *
513deque_concat(dequeobject *deque, PyObject *other)
514{
Benjamin Peterson1a629212015-04-04 10:52:36 -0400515 PyObject *new_deque, *result;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700516 int rv;
517
518 rv = PyObject_IsInstance(other, (PyObject *)&deque_type);
519 if (rv <= 0) {
520 if (rv == 0) {
521 PyErr_Format(PyExc_TypeError,
522 "can only concatenate deque (not \"%.200s\") to deque",
Victor Stinnerdaa97562020-02-07 03:37:06 +0100523 Py_TYPE(other)->tp_name);
Raymond Hettinger41290a62015-03-31 08:12:23 -0700524 }
525 return NULL;
526 }
527
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530528 new_deque = deque_copy((PyObject *)deque, NULL);
Raymond Hettinger41290a62015-03-31 08:12:23 -0700529 if (new_deque == NULL)
530 return NULL;
Benjamin Peterson1a629212015-04-04 10:52:36 -0400531 result = deque_extend((dequeobject *)new_deque, other);
532 if (result == NULL) {
533 Py_DECREF(new_deque);
534 return NULL;
535 }
536 Py_DECREF(result);
537 return new_deque;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700538}
539
Serhiy Storchakaa5c42282018-05-31 07:34:34 +0300540static int
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700541deque_clear(dequeobject *deque)
542{
543 block *b;
544 block *prevblock;
545 block *leftblock;
546 Py_ssize_t leftindex;
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800547 Py_ssize_t n, m;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700548 PyObject *item;
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800549 PyObject **itemptr, **limit;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700550
Raymond Hettinger38031142015-09-29 22:45:05 -0700551 if (Py_SIZE(deque) == 0)
Serhiy Storchakaa5c42282018-05-31 07:34:34 +0300552 return 0;
Raymond Hettinger38031142015-09-29 22:45:05 -0700553
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700554 /* During the process of clearing a deque, decrefs can cause the
555 deque to mutate. To avoid fatal confusion, we have to make the
556 deque empty before clearing the blocks and never refer to
557 anything via deque->ref while clearing. (This is the same
558 technique used for clearing lists, sets, and dicts.)
559
560 Making the deque empty requires allocating a new empty block. In
561 the unlikely event that memory is full, we fall back to an
562 alternate method that doesn't require a new block. Repeating
563 pops in a while-loop is slower, possibly re-entrant (and a clever
564 adversary could cause it to never terminate).
565 */
566
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700567 b = newblock();
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700568 if (b == NULL) {
569 PyErr_Clear();
570 goto alternate_method;
571 }
572
573 /* Remember the old size, leftblock, and leftindex */
Raymond Hettinger6f86a332016-03-02 00:30:58 -0800574 n = Py_SIZE(deque);
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700575 leftblock = deque->leftblock;
576 leftindex = deque->leftindex;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700577
578 /* Set the deque to be empty using the newly allocated block */
579 MARK_END(b->leftlink);
580 MARK_END(b->rightlink);
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100581 Py_SET_SIZE(deque, 0);
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700582 deque->leftblock = b;
583 deque->rightblock = b;
584 deque->leftindex = CENTER + 1;
585 deque->rightindex = CENTER;
586 deque->state++;
587
588 /* Now the old size, leftblock, and leftindex are disconnected from
589 the empty deque and we can use them to decref the pointers.
590 */
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800591 m = (BLOCKLEN - leftindex > n) ? n : BLOCKLEN - leftindex;
Raymond Hettinger589106b2016-03-02 00:06:21 -0800592 itemptr = &leftblock->data[leftindex];
Raymond Hettinger6f86a332016-03-02 00:30:58 -0800593 limit = itemptr + m;
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800594 n -= m;
595 while (1) {
596 if (itemptr == limit) {
597 if (n == 0)
598 break;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700599 CHECK_NOT_END(leftblock->rightlink);
600 prevblock = leftblock;
601 leftblock = leftblock->rightlink;
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800602 m = (n > BLOCKLEN) ? BLOCKLEN : n;
Raymond Hettinger589106b2016-03-02 00:06:21 -0800603 itemptr = leftblock->data;
Raymond Hettinger6f86a332016-03-02 00:30:58 -0800604 limit = itemptr + m;
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800605 n -= m;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700606 freeblock(prevblock);
607 }
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800608 item = *(itemptr++);
609 Py_DECREF(item);
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700610 }
611 CHECK_END(leftblock->rightlink);
612 freeblock(leftblock);
Serhiy Storchakaa5c42282018-05-31 07:34:34 +0300613 return 0;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700614
615 alternate_method:
616 while (Py_SIZE(deque)) {
617 item = deque_pop(deque, NULL);
618 assert (item != NULL);
619 Py_DECREF(item);
620 }
Serhiy Storchakaa5c42282018-05-31 07:34:34 +0300621 return 0;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700622}
623
624static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530625deque_clearmethod(dequeobject *deque, PyObject *Py_UNUSED(ignored))
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700626{
627 deque_clear(deque);
628 Py_RETURN_NONE;
629}
630
631PyDoc_STRVAR(clear_doc, "Remove all elements from the deque.");
Raymond Hettinger41290a62015-03-31 08:12:23 -0700632
633static PyObject *
Raymond Hettinger41290a62015-03-31 08:12:23 -0700634deque_inplace_repeat(dequeobject *deque, Py_ssize_t n)
635{
Raymond Hettingerc22eee62015-09-26 02:14:50 -0700636 Py_ssize_t i, m, size;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700637 PyObject *seq;
638 PyObject *rv;
639
640 size = Py_SIZE(deque);
641 if (size == 0 || n == 1) {
642 Py_INCREF(deque);
643 return (PyObject *)deque;
644 }
645
646 if (n <= 0) {
647 deque_clear(deque);
648 Py_INCREF(deque);
649 return (PyObject *)deque;
650 }
651
Raymond Hettinger41290a62015-03-31 08:12:23 -0700652 if (size == 1) {
653 /* common case, repeating a single element */
654 PyObject *item = deque->leftblock->data[deque->leftindex];
655
Raymond Hettingera7f630092015-10-10 23:56:02 -0400656 if (deque->maxlen >= 0 && n > deque->maxlen)
Raymond Hettinger41290a62015-03-31 08:12:23 -0700657 n = deque->maxlen;
658
Raymond Hettinger67c78b52015-09-12 11:00:20 -0400659 deque->state++;
Raymond Hettingerad262252015-09-14 01:03:04 -0400660 for (i = 0 ; i < n-1 ; ) {
Raymond Hettinger67c78b52015-09-12 11:00:20 -0400661 if (deque->rightindex == BLOCKLEN - 1) {
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700662 block *b = newblock();
Raymond Hettinger67c78b52015-09-12 11:00:20 -0400663 if (b == NULL) {
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100664 Py_SET_SIZE(deque, Py_SIZE(deque) + i);
Raymond Hettinger67c78b52015-09-12 11:00:20 -0400665 return NULL;
666 }
667 b->leftlink = deque->rightblock;
668 CHECK_END(deque->rightblock->rightlink);
669 deque->rightblock->rightlink = b;
670 deque->rightblock = b;
671 MARK_END(b->rightlink);
672 deque->rightindex = -1;
673 }
Raymond Hettingerc22eee62015-09-26 02:14:50 -0700674 m = n - 1 - i;
675 if (m > BLOCKLEN - 1 - deque->rightindex)
676 m = BLOCKLEN - 1 - deque->rightindex;
677 i += m;
678 while (m--) {
Raymond Hettingerad262252015-09-14 01:03:04 -0400679 deque->rightindex++;
680 Py_INCREF(item);
681 deque->rightblock->data[deque->rightindex] = item;
682 }
Raymond Hettinger41290a62015-03-31 08:12:23 -0700683 }
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100684 Py_SET_SIZE(deque, Py_SIZE(deque) + i);
Raymond Hettinger41290a62015-03-31 08:12:23 -0700685 Py_INCREF(deque);
686 return (PyObject *)deque;
687 }
688
Raymond Hettinger20151f52015-10-16 22:47:29 -0700689 if ((size_t)size > PY_SSIZE_T_MAX / (size_t)n) {
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400690 return PyErr_NoMemory();
691 }
692
Raymond Hettinger41290a62015-03-31 08:12:23 -0700693 seq = PySequence_List((PyObject *)deque);
694 if (seq == NULL)
695 return seq;
696
Louie Lu357bad72017-02-24 11:59:49 +0800697 /* Reduce the number of repetitions when maxlen would be exceeded */
698 if (deque->maxlen >= 0 && n * size > deque->maxlen)
699 n = (deque->maxlen + size - 1) / size;
700
Raymond Hettinger41290a62015-03-31 08:12:23 -0700701 for (i = 0 ; i < n-1 ; i++) {
702 rv = deque_extend(deque, seq);
703 if (rv == NULL) {
704 Py_DECREF(seq);
705 return NULL;
706 }
707 Py_DECREF(rv);
708 }
709 Py_INCREF(deque);
710 Py_DECREF(seq);
711 return (PyObject *)deque;
712}
713
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400714static PyObject *
715deque_repeat(dequeobject *deque, Py_ssize_t n)
716{
717 dequeobject *new_deque;
Raymond Hettinger95e2cc52015-09-13 02:41:18 -0400718 PyObject *rv;
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400719
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530720 new_deque = (dequeobject *)deque_copy((PyObject *) deque, NULL);
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400721 if (new_deque == NULL)
722 return NULL;
Raymond Hettinger95e2cc52015-09-13 02:41:18 -0400723 rv = deque_inplace_repeat(new_deque, n);
724 Py_DECREF(new_deque);
725 return rv;
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400726}
727
Raymond Hettinger54023152014-04-23 00:58:48 -0700728/* The rotate() method is part of the public API and is used internally
729as a primitive for other methods.
730
731Rotation by 1 or -1 is a common case, so any optimizations for high
732volume rotations should take care not to penalize the common case.
733
734Conceptually, a rotate by one is equivalent to a pop on one side and an
735append on the other. However, a pop/append pair is unnecessarily slow
Martin Panterd2ad5712015-11-02 04:20:33 +0000736because it requires an incref/decref pair for an object located randomly
Raymond Hettinger54023152014-04-23 00:58:48 -0700737in memory. It is better to just move the object pointer from one block
738to the next without changing the reference count.
739
740When moving batches of pointers, it is tempting to use memcpy() but that
741proved to be slower than a simple loop for a variety of reasons.
742Memcpy() cannot know in advance that we're copying pointers instead of
743bytes, that the source and destination are pointer aligned and
744non-overlapping, that moving just one pointer is a common case, that we
745never need to move more than BLOCKLEN pointers, and that at least one
746pointer is always moved.
747
748For high volume rotations, newblock() and freeblock() are never called
749more than once. Previously emptied blocks are immediately reused as a
750destination block. If a block is left-over at the end, it is freed.
751*/
752
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000753static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000754_deque_rotate(dequeobject *deque, Py_ssize_t n)
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000755{
Raymond Hettinger3959af92013-07-13 02:34:08 -0700756 block *b = NULL;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700757 block *leftblock = deque->leftblock;
758 block *rightblock = deque->rightblock;
759 Py_ssize_t leftindex = deque->leftindex;
760 Py_ssize_t rightindex = deque->rightindex;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000761 Py_ssize_t len=Py_SIZE(deque), halflen=len>>1;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700762 int rv = -1;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000763
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800764 if (len <= 1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000765 return 0;
766 if (n > halflen || n < -halflen) {
767 n %= len;
768 if (n > halflen)
769 n -= len;
770 else if (n < -halflen)
771 n += len;
772 }
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500773 assert(len > 1);
Raymond Hettingera4409c12013-02-04 00:08:12 -0500774 assert(-halflen <= n && n <= halflen);
Raymond Hettinger231ee4d2013-02-02 11:24:43 -0800775
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800776 deque->state++;
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500777 while (n > 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700778 if (leftindex == 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700779 if (b == NULL) {
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700780 b = newblock();
Raymond Hettinger3959af92013-07-13 02:34:08 -0700781 if (b == NULL)
782 goto done;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700783 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000784 b->rightlink = leftblock;
785 CHECK_END(leftblock->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700786 leftblock->leftlink = b;
787 leftblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000788 MARK_END(b->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700789 leftindex = BLOCKLEN;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700790 b = NULL;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800791 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700792 assert(leftindex > 0);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700793 {
794 PyObject **src, **dest;
795 Py_ssize_t m = n;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800796
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700797 if (m > rightindex + 1)
798 m = rightindex + 1;
799 if (m > leftindex)
800 m = leftindex;
801 assert (m > 0 && m <= len);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700802 rightindex -= m;
803 leftindex -= m;
Raymond Hettinger0e259f12015-02-01 22:53:41 -0800804 src = &rightblock->data[rightindex + 1];
805 dest = &leftblock->data[leftindex];
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700806 n -= m;
Raymond Hettinger840533b2013-07-13 17:03:58 -0700807 do {
Raymond Hettinger0e259f12015-02-01 22:53:41 -0800808 *(dest++) = *(src++);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700809 } while (--m);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700810 }
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -0700811 if (rightindex < 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700812 assert(leftblock != rightblock);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700813 assert(b == NULL);
Raymond Hettinger3959af92013-07-13 02:34:08 -0700814 b = rightblock;
Raymond Hettingerb97cc492013-07-21 01:51:07 -0700815 CHECK_NOT_END(rightblock->leftlink);
816 rightblock = rightblock->leftlink;
817 MARK_END(rightblock->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700818 rightindex = BLOCKLEN - 1;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800819 }
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800820 }
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500821 while (n < 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700822 if (rightindex == BLOCKLEN - 1) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700823 if (b == NULL) {
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700824 b = newblock();
Raymond Hettinger3959af92013-07-13 02:34:08 -0700825 if (b == NULL)
826 goto done;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700827 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000828 b->leftlink = rightblock;
829 CHECK_END(rightblock->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700830 rightblock->rightlink = b;
831 rightblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000832 MARK_END(b->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700833 rightindex = -1;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700834 b = NULL;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800835 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700836 assert (rightindex < BLOCKLEN - 1);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700837 {
838 PyObject **src, **dest;
839 Py_ssize_t m = -n;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800840
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700841 if (m > BLOCKLEN - leftindex)
842 m = BLOCKLEN - leftindex;
843 if (m > BLOCKLEN - 1 - rightindex)
844 m = BLOCKLEN - 1 - rightindex;
845 assert (m > 0 && m <= len);
846 src = &leftblock->data[leftindex];
847 dest = &rightblock->data[rightindex + 1];
848 leftindex += m;
849 rightindex += m;
850 n += m;
Raymond Hettinger840533b2013-07-13 17:03:58 -0700851 do {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700852 *(dest++) = *(src++);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700853 } while (--m);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700854 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700855 if (leftindex == BLOCKLEN) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700856 assert(leftblock != rightblock);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700857 assert(b == NULL);
Raymond Hettinger3959af92013-07-13 02:34:08 -0700858 b = leftblock;
Raymond Hettingerb97cc492013-07-21 01:51:07 -0700859 CHECK_NOT_END(leftblock->rightlink);
860 leftblock = leftblock->rightlink;
861 MARK_END(leftblock->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700862 leftindex = 0;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800863 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 }
Raymond Hettinger3959af92013-07-13 02:34:08 -0700865 rv = 0;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700866done:
Raymond Hettinger3959af92013-07-13 02:34:08 -0700867 if (b != NULL)
868 freeblock(b);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700869 deque->leftblock = leftblock;
870 deque->rightblock = rightblock;
871 deque->leftindex = leftindex;
872 deque->rightindex = rightindex;
873
874 return rv;
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000875}
876
877static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +0200878deque_rotate(dequeobject *deque, PyObject *const *args, Py_ssize_t nargs)
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000879{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 Py_ssize_t n=1;
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000881
Victor Stinnerdd407d52017-02-06 16:06:49 +0100882 if (!_PyArg_ParseStack(args, nargs, "|n:rotate", &n)) {
883 return NULL;
884 }
885
Raymond Hettinger6921c132015-03-21 02:03:40 -0700886 if (!_deque_rotate(deque, n))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000887 Py_RETURN_NONE;
888 return NULL;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000889}
890
Tim Peters1065f752004-10-01 01:03:29 +0000891PyDoc_STRVAR(rotate_doc,
Raymond Hettingeree33b272004-02-08 04:05:26 +0000892"Rotate the deque n steps to the right (default n=1). If n is negative, rotates left.");
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000893
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000894static PyObject *
895deque_reverse(dequeobject *deque, PyObject *unused)
896{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000897 block *leftblock = deque->leftblock;
898 block *rightblock = deque->rightblock;
899 Py_ssize_t leftindex = deque->leftindex;
900 Py_ssize_t rightindex = deque->rightindex;
Raymond Hettingercfe5b6c2015-07-20 00:25:50 -0400901 Py_ssize_t n = Py_SIZE(deque) >> 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000902 PyObject *tmp;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000903
Raymond Hettingere1b02872017-09-04 16:07:06 -0700904 while (--n >= 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000905 /* Validate that pointers haven't met in the middle */
906 assert(leftblock != rightblock || leftindex < rightindex);
Raymond Hettinger82df9252013-07-07 01:43:42 -1000907 CHECK_NOT_END(leftblock);
908 CHECK_NOT_END(rightblock);
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000909
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 /* Swap */
911 tmp = leftblock->data[leftindex];
912 leftblock->data[leftindex] = rightblock->data[rightindex];
913 rightblock->data[rightindex] = tmp;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000914
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000915 /* Advance left block/index pair */
916 leftindex++;
917 if (leftindex == BLOCKLEN) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 leftblock = leftblock->rightlink;
919 leftindex = 0;
920 }
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 /* Step backwards with the right block/index pair */
923 rightindex--;
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -0700924 if (rightindex < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000925 rightblock = rightblock->leftlink;
926 rightindex = BLOCKLEN - 1;
927 }
928 }
929 Py_RETURN_NONE;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000930}
931
932PyDoc_STRVAR(reverse_doc,
933"D.reverse() -- reverse *IN PLACE*");
934
Raymond Hettinger44459de2010-04-03 23:20:46 +0000935static PyObject *
936deque_count(dequeobject *deque, PyObject *v)
937{
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000938 block *b = deque->leftblock;
939 Py_ssize_t index = deque->leftindex;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000940 Py_ssize_t n = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 Py_ssize_t count = 0;
Raymond Hettingerf9d9c792015-03-02 22:47:46 -0800942 size_t start_state = deque->state;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000943 PyObject *item;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000944 int cmp;
Raymond Hettinger44459de2010-04-03 23:20:46 +0000945
Raymond Hettingere1b02872017-09-04 16:07:06 -0700946 while (--n >= 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000947 CHECK_NOT_END(b);
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000948 item = b->data[index];
sweeneydec6dedde2020-02-09 03:16:43 -0500949 Py_INCREF(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
sweeneydec6dedde2020-02-09 03:16:43 -0500951 Py_DECREF(item);
Raymond Hettinger2b0d6462015-09-23 19:15:44 -0700952 if (cmp < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 return NULL;
Raymond Hettinger2b0d6462015-09-23 19:15:44 -0700954 count += cmp;
Raymond Hettinger44459de2010-04-03 23:20:46 +0000955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000956 if (start_state != deque->state) {
957 PyErr_SetString(PyExc_RuntimeError,
958 "deque mutated during iteration");
959 return NULL;
960 }
Raymond Hettinger44459de2010-04-03 23:20:46 +0000961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962 /* Advance left block/index pair */
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000963 index++;
964 if (index == BLOCKLEN) {
965 b = b->rightlink;
966 index = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000967 }
968 }
969 return PyLong_FromSsize_t(count);
Raymond Hettinger44459de2010-04-03 23:20:46 +0000970}
971
972PyDoc_STRVAR(count_doc,
973"D.count(value) -> integer -- return number of occurrences of value");
974
Raymond Hettinger39dadf72015-03-20 16:38:56 -0700975static int
976deque_contains(dequeobject *deque, PyObject *v)
977{
978 block *b = deque->leftblock;
979 Py_ssize_t index = deque->leftindex;
980 Py_ssize_t n = Py_SIZE(deque);
Raymond Hettinger39dadf72015-03-20 16:38:56 -0700981 size_t start_state = deque->state;
982 PyObject *item;
983 int cmp;
984
Raymond Hettingere1b02872017-09-04 16:07:06 -0700985 while (--n >= 0) {
Raymond Hettinger39dadf72015-03-20 16:38:56 -0700986 CHECK_NOT_END(b);
987 item = b->data[index];
sweeneydec6dedde2020-02-09 03:16:43 -0500988 Py_INCREF(item);
Raymond Hettinger39dadf72015-03-20 16:38:56 -0700989 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
sweeneydec6dedde2020-02-09 03:16:43 -0500990 Py_DECREF(item);
Raymond Hettinger39dadf72015-03-20 16:38:56 -0700991 if (cmp) {
992 return cmp;
993 }
994 if (start_state != deque->state) {
995 PyErr_SetString(PyExc_RuntimeError,
996 "deque mutated during iteration");
997 return -1;
998 }
999 index++;
1000 if (index == BLOCKLEN) {
1001 b = b->rightlink;
1002 index = 0;
1003 }
1004 }
1005 return 0;
1006}
1007
Martin v. Löwis18e16552006-02-15 17:27:45 +00001008static Py_ssize_t
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001009deque_len(dequeobject *deque)
1010{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001011 return Py_SIZE(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001012}
1013
Raymond Hettinger4aec61e2005-03-18 21:20:23 +00001014static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02001015deque_index(dequeobject *deque, PyObject *const *args, Py_ssize_t nargs)
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001016{
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001017 Py_ssize_t i, n, start=0, stop=Py_SIZE(deque);
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001018 PyObject *v, *item;
1019 block *b = deque->leftblock;
1020 Py_ssize_t index = deque->leftindex;
1021 size_t start_state = deque->state;
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001022 int cmp;
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001023
Victor Stinnerdd407d52017-02-06 16:06:49 +01001024 if (!_PyArg_ParseStack(args, nargs, "O|O&O&:index", &v,
Serhiy Storchakad4edfc92017-03-30 18:29:23 +03001025 _PyEval_SliceIndexNotNone, &start,
1026 _PyEval_SliceIndexNotNone, &stop)) {
Victor Stinnerdd407d52017-02-06 16:06:49 +01001027 return NULL;
1028 }
1029
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001030 if (start < 0) {
1031 start += Py_SIZE(deque);
1032 if (start < 0)
1033 start = 0;
1034 }
1035 if (stop < 0) {
1036 stop += Py_SIZE(deque);
1037 if (stop < 0)
1038 stop = 0;
1039 }
Raymond Hettinger87674ec2015-08-26 08:08:38 -07001040 if (stop > Py_SIZE(deque))
1041 stop = Py_SIZE(deque);
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001042 if (start > stop)
1043 start = stop;
1044 assert(0 <= start && start <= stop && stop <= Py_SIZE(deque));
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001045
Raymond Hettingerb46ad542018-09-21 01:46:41 -07001046 for (i=0 ; i < start - BLOCKLEN ; i += BLOCKLEN) {
1047 b = b->rightlink;
1048 }
1049 for ( ; i < start ; i++) {
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001050 index++;
1051 if (index == BLOCKLEN) {
1052 b = b->rightlink;
1053 index = 0;
1054 }
1055 }
1056
Raymond Hettingere1b02872017-09-04 16:07:06 -07001057 n = stop - i;
1058 while (--n >= 0) {
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001059 CHECK_NOT_END(b);
1060 item = b->data[index];
1061 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
1062 if (cmp > 0)
Raymond Hettingere1b02872017-09-04 16:07:06 -07001063 return PyLong_FromSsize_t(stop - n - 1);
Raymond Hettingerdf8f5b52015-11-02 07:27:40 -05001064 if (cmp < 0)
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001065 return NULL;
1066 if (start_state != deque->state) {
1067 PyErr_SetString(PyExc_RuntimeError,
1068 "deque mutated during iteration");
1069 return NULL;
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001070 }
1071 index++;
1072 if (index == BLOCKLEN) {
1073 b = b->rightlink;
1074 index = 0;
1075 }
1076 }
1077 PyErr_Format(PyExc_ValueError, "%R is not in deque", v);
1078 return NULL;
1079}
1080
1081PyDoc_STRVAR(index_doc,
1082"D.index(value, [start, [stop]]) -> integer -- return first index of value.\n"
1083"Raises ValueError if the value is not present.");
1084
Raymond Hettinger551350a2015-03-24 00:19:53 -07001085/* insert(), remove(), and delitem() are implemented in terms of
1086 rotate() for simplicity and reasonable performance near the end
1087 points. If for some reason these methods become popular, it is not
1088 hard to re-implement this using direct data movement (similar to
1089 the code used in list slice assignments) and achieve a performance
Raymond Hettingerfef9c1b2015-03-24 21:12:57 -07001090 boost (by moving each pointer only once instead of twice).
Raymond Hettinger551350a2015-03-24 00:19:53 -07001091*/
1092
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001093static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02001094deque_insert(dequeobject *deque, PyObject *const *args, Py_ssize_t nargs)
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001095{
1096 Py_ssize_t index;
1097 Py_ssize_t n = Py_SIZE(deque);
1098 PyObject *value;
1099 PyObject *rv;
1100
Victor Stinnerdd407d52017-02-06 16:06:49 +01001101 if (!_PyArg_ParseStack(args, nargs, "nO:insert", &index, &value)) {
1102 return NULL;
1103 }
1104
Raymond Hettinger37434322016-01-26 21:44:16 -08001105 if (deque->maxlen == Py_SIZE(deque)) {
Raymond Hettingera6389712016-02-01 21:21:19 -08001106 PyErr_SetString(PyExc_IndexError, "deque already at its maximum size");
1107 return NULL;
Raymond Hettinger37434322016-01-26 21:44:16 -08001108 }
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001109 if (index >= n)
1110 return deque_append(deque, value);
1111 if (index <= -n || index == 0)
1112 return deque_appendleft(deque, value);
1113 if (_deque_rotate(deque, -index))
1114 return NULL;
1115 if (index < 0)
1116 rv = deque_append(deque, value);
1117 else
1118 rv = deque_appendleft(deque, value);
1119 if (rv == NULL)
1120 return NULL;
1121 Py_DECREF(rv);
1122 if (_deque_rotate(deque, index))
1123 return NULL;
1124 Py_RETURN_NONE;
1125}
1126
1127PyDoc_STRVAR(insert_doc,
1128"D.insert(index, object) -- insert object before index");
1129
1130static PyObject *
Raymond Hettinger4aec61e2005-03-18 21:20:23 +00001131deque_remove(dequeobject *deque, PyObject *value)
1132{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001133 Py_ssize_t i, n=Py_SIZE(deque);
Raymond Hettinger4aec61e2005-03-18 21:20:23 +00001134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001135 for (i=0 ; i<n ; i++) {
1136 PyObject *item = deque->leftblock->data[deque->leftindex];
1137 int cmp = PyObject_RichCompareBool(item, value, Py_EQ);
Raymond Hettingerd73202c2005-03-19 00:00:51 +00001138
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001139 if (Py_SIZE(deque) != n) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001140 PyErr_SetString(PyExc_IndexError,
1141 "deque mutated during remove().");
1142 return NULL;
1143 }
1144 if (cmp > 0) {
1145 PyObject *tgt = deque_popleft(deque, NULL);
1146 assert (tgt != NULL);
Raymond Hettinger6921c132015-03-21 02:03:40 -07001147 if (_deque_rotate(deque, i))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001148 return NULL;
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001149 Py_DECREF(tgt);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001150 Py_RETURN_NONE;
1151 }
1152 else if (cmp < 0) {
1153 _deque_rotate(deque, i);
1154 return NULL;
1155 }
1156 _deque_rotate(deque, -1);
1157 }
1158 PyErr_SetString(PyExc_ValueError, "deque.remove(x): x not in deque");
1159 return NULL;
Raymond Hettinger4aec61e2005-03-18 21:20:23 +00001160}
1161
1162PyDoc_STRVAR(remove_doc,
1163"D.remove(value) -- remove first occurrence of value.");
1164
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001165static int
1166valid_index(Py_ssize_t i, Py_ssize_t limit)
1167{
Raymond Hettinger12f896c2015-07-31 12:03:20 -07001168 /* The cast to size_t lets us use just a single comparison
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001169 to check whether i is in the range: 0 <= i < limit */
1170 return (size_t) i < (size_t) limit;
1171}
1172
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001173static PyObject *
Benjamin Petersond6313712008-07-31 16:23:04 +00001174deque_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001175{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001176 block *b;
1177 PyObject *item;
1178 Py_ssize_t n, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001179
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001180 if (!valid_index(i, Py_SIZE(deque))) {
1181 PyErr_SetString(PyExc_IndexError, "deque index out of range");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 return NULL;
1183 }
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001184
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001185 if (i == 0) {
1186 i = deque->leftindex;
1187 b = deque->leftblock;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001188 } else if (i == Py_SIZE(deque) - 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001189 i = deque->rightindex;
1190 b = deque->rightblock;
1191 } else {
1192 i += deque->leftindex;
Raymond Hettingerc2083082015-02-28 23:29:16 -08001193 n = (Py_ssize_t)((size_t) i / BLOCKLEN);
1194 i = (Py_ssize_t)((size_t) i % BLOCKLEN);
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001195 if (index < (Py_SIZE(deque) >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001196 b = deque->leftblock;
Raymond Hettingere1b02872017-09-04 16:07:06 -07001197 while (--n >= 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001198 b = b->rightlink;
1199 } else {
Raymond Hettinger63d1ff22015-02-28 07:41:30 -08001200 n = (Py_ssize_t)(
Raymond Hettingerc2083082015-02-28 23:29:16 -08001201 ((size_t)(deque->leftindex + Py_SIZE(deque) - 1))
Raymond Hettinger63d1ff22015-02-28 07:41:30 -08001202 / BLOCKLEN - n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001203 b = deque->rightblock;
Raymond Hettingere1b02872017-09-04 16:07:06 -07001204 while (--n >= 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001205 b = b->leftlink;
1206 }
1207 }
1208 item = b->data[i];
1209 Py_INCREF(item);
1210 return item;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001211}
1212
1213static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001214deque_del_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001215{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001216 PyObject *item;
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001217 int rv;
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001218
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001219 assert (i >= 0 && i < Py_SIZE(deque));
Raymond Hettinger6921c132015-03-21 02:03:40 -07001220 if (_deque_rotate(deque, -i))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001221 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001222 item = deque_popleft(deque, NULL);
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001223 rv = _deque_rotate(deque, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001224 assert (item != NULL);
1225 Py_DECREF(item);
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001226 return rv;
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001227}
1228
1229static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001230deque_ass_item(dequeobject *deque, Py_ssize_t i, PyObject *v)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001231{
Raymond Hettinger38418662016-02-08 20:34:49 -08001232 PyObject *old_value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001233 block *b;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001234 Py_ssize_t n, len=Py_SIZE(deque), halflen=(len+1)>>1, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001235
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001236 if (!valid_index(i, len)) {
1237 PyErr_SetString(PyExc_IndexError, "deque index out of range");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001238 return -1;
1239 }
1240 if (v == NULL)
1241 return deque_del_item(deque, i);
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001243 i += deque->leftindex;
Raymond Hettingerc2083082015-02-28 23:29:16 -08001244 n = (Py_ssize_t)((size_t) i / BLOCKLEN);
1245 i = (Py_ssize_t)((size_t) i % BLOCKLEN);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001246 if (index <= halflen) {
1247 b = deque->leftblock;
Raymond Hettingere1b02872017-09-04 16:07:06 -07001248 while (--n >= 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001249 b = b->rightlink;
1250 } else {
Raymond Hettingera473b9d2015-02-28 17:49:47 -08001251 n = (Py_ssize_t)(
Raymond Hettingerc2083082015-02-28 23:29:16 -08001252 ((size_t)(deque->leftindex + Py_SIZE(deque) - 1))
Raymond Hettingera473b9d2015-02-28 17:49:47 -08001253 / BLOCKLEN - n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001254 b = deque->rightblock;
Raymond Hettingere1b02872017-09-04 16:07:06 -07001255 while (--n >= 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001256 b = b->leftlink;
1257 }
1258 Py_INCREF(v);
Raymond Hettinger38418662016-02-08 20:34:49 -08001259 old_value = b->data[i];
1260 b->data[i] = v;
1261 Py_DECREF(old_value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001262 return 0;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001263}
1264
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001265static void
1266deque_dealloc(dequeobject *deque)
1267{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001268 PyObject_GC_UnTrack(deque);
1269 if (deque->weakreflist != NULL)
1270 PyObject_ClearWeakRefs((PyObject *) deque);
1271 if (deque->leftblock != NULL) {
1272 deque_clear(deque);
1273 assert(deque->leftblock != NULL);
1274 freeblock(deque->leftblock);
1275 }
1276 deque->leftblock = NULL;
1277 deque->rightblock = NULL;
1278 Py_TYPE(deque)->tp_free(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001279}
1280
1281static int
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001282deque_traverse(dequeobject *deque, visitproc visit, void *arg)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001283{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001284 block *b;
1285 PyObject *item;
1286 Py_ssize_t index;
1287 Py_ssize_t indexlo = deque->leftindex;
Raymond Hettinger1286d142015-10-14 23:16:57 -07001288 Py_ssize_t indexhigh;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001289
Raymond Hettinger5bfa8672013-07-06 11:58:09 -10001290 for (b = deque->leftblock; b != deque->rightblock; b = b->rightlink) {
1291 for (index = indexlo; index < BLOCKLEN ; index++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001292 item = b->data[index];
1293 Py_VISIT(item);
1294 }
1295 indexlo = 0;
1296 }
Raymond Hettinger1286d142015-10-14 23:16:57 -07001297 indexhigh = deque->rightindex;
1298 for (index = indexlo; index <= indexhigh; index++) {
Raymond Hettinger5bfa8672013-07-06 11:58:09 -10001299 item = b->data[index];
1300 Py_VISIT(item);
1301 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001302 return 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001303}
1304
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001305static PyObject *
Serhiy Storchaka81524022018-11-27 13:05:02 +02001306deque_reduce(dequeobject *deque, PyObject *Py_UNUSED(ignored))
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001307{
Serhiy Storchakaa0d416f2016-03-06 08:55:21 +02001308 PyObject *dict, *it;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001309 _Py_IDENTIFIER(__dict__);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001310
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001311 if (_PyObject_LookupAttrId((PyObject *)deque, &PyId___dict__, &dict) < 0) {
1312 return NULL;
1313 }
Serhiy Storchakaa0d416f2016-03-06 08:55:21 +02001314 if (dict == NULL) {
Serhiy Storchakaa0d416f2016-03-06 08:55:21 +02001315 dict = Py_None;
1316 Py_INCREF(dict);
1317 }
1318
1319 it = PyObject_GetIter((PyObject *)deque);
1320 if (it == NULL) {
1321 Py_DECREF(dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001322 return NULL;
1323 }
Serhiy Storchakaa0d416f2016-03-06 08:55:21 +02001324
1325 if (deque->maxlen < 0) {
1326 return Py_BuildValue("O()NN", Py_TYPE(deque), dict, it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001327 }
Serhiy Storchakaa0d416f2016-03-06 08:55:21 +02001328 else {
1329 return Py_BuildValue("O(()n)NN", Py_TYPE(deque), deque->maxlen, dict, it);
1330 }
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001331}
1332
1333PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
1334
1335static PyObject *
1336deque_repr(PyObject *deque)
1337{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001338 PyObject *aslist, *result;
1339 int i;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001341 i = Py_ReprEnter(deque);
1342 if (i != 0) {
1343 if (i < 0)
1344 return NULL;
1345 return PyUnicode_FromString("[...]");
1346 }
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001348 aslist = PySequence_List(deque);
1349 if (aslist == NULL) {
1350 Py_ReprLeave(deque);
1351 return NULL;
1352 }
Raymond Hettingera7f630092015-10-10 23:56:02 -04001353 if (((dequeobject *)deque)->maxlen >= 0)
Serhiy Storchakab3a77962017-09-21 14:24:13 +03001354 result = PyUnicode_FromFormat("%s(%R, maxlen=%zd)",
1355 _PyType_Name(Py_TYPE(deque)), aslist,
1356 ((dequeobject *)deque)->maxlen);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001357 else
Serhiy Storchakab3a77962017-09-21 14:24:13 +03001358 result = PyUnicode_FromFormat("%s(%R)",
1359 _PyType_Name(Py_TYPE(deque)), aslist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001360 Py_ReprLeave(deque);
Raymond Hettinger2b2b7532015-09-05 17:05:52 -07001361 Py_DECREF(aslist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001362 return result;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001363}
1364
Raymond Hettinger738ec902004-02-29 02:15:56 +00001365static PyObject *
1366deque_richcompare(PyObject *v, PyObject *w, int op)
1367{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001368 PyObject *it1=NULL, *it2=NULL, *x, *y;
1369 Py_ssize_t vs, ws;
1370 int b, cmp=-1;
Raymond Hettinger738ec902004-02-29 02:15:56 +00001371
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001372 if (!PyObject_TypeCheck(v, &deque_type) ||
1373 !PyObject_TypeCheck(w, &deque_type)) {
Brian Curtindfc80e32011-08-10 20:28:54 -05001374 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001375 }
Raymond Hettinger738ec902004-02-29 02:15:56 +00001376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001377 /* Shortcuts */
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001378 vs = Py_SIZE((dequeobject *)v);
1379 ws = Py_SIZE((dequeobject *)w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001380 if (op == Py_EQ) {
1381 if (v == w)
1382 Py_RETURN_TRUE;
1383 if (vs != ws)
1384 Py_RETURN_FALSE;
1385 }
1386 if (op == Py_NE) {
1387 if (v == w)
1388 Py_RETURN_FALSE;
1389 if (vs != ws)
1390 Py_RETURN_TRUE;
1391 }
Raymond Hettinger738ec902004-02-29 02:15:56 +00001392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001393 /* Search for the first index where items are different */
1394 it1 = PyObject_GetIter(v);
1395 if (it1 == NULL)
1396 goto done;
1397 it2 = PyObject_GetIter(w);
1398 if (it2 == NULL)
1399 goto done;
1400 for (;;) {
1401 x = PyIter_Next(it1);
1402 if (x == NULL && PyErr_Occurred())
1403 goto done;
1404 y = PyIter_Next(it2);
1405 if (x == NULL || y == NULL)
1406 break;
1407 b = PyObject_RichCompareBool(x, y, Py_EQ);
1408 if (b == 0) {
1409 cmp = PyObject_RichCompareBool(x, y, op);
1410 Py_DECREF(x);
1411 Py_DECREF(y);
1412 goto done;
1413 }
1414 Py_DECREF(x);
1415 Py_DECREF(y);
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -07001416 if (b < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001417 goto done;
1418 }
1419 /* We reached the end of one deque or both */
1420 Py_XDECREF(x);
1421 Py_XDECREF(y);
1422 if (PyErr_Occurred())
1423 goto done;
1424 switch (op) {
1425 case Py_LT: cmp = y != NULL; break; /* if w was longer */
1426 case Py_LE: cmp = x == NULL; break; /* if v was not longer */
1427 case Py_EQ: cmp = x == y; break; /* if we reached the end of both */
1428 case Py_NE: cmp = x != y; break; /* if one deque continues */
1429 case Py_GT: cmp = x != NULL; break; /* if v was longer */
1430 case Py_GE: cmp = y == NULL; break; /* if w was not longer */
1431 }
Tim Peters1065f752004-10-01 01:03:29 +00001432
Raymond Hettinger738ec902004-02-29 02:15:56 +00001433done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001434 Py_XDECREF(it1);
1435 Py_XDECREF(it2);
1436 if (cmp == 1)
1437 Py_RETURN_TRUE;
1438 if (cmp == 0)
1439 Py_RETURN_FALSE;
1440 return NULL;
Raymond Hettinger738ec902004-02-29 02:15:56 +00001441}
1442
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001443static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001444deque_init(dequeobject *deque, PyObject *args, PyObject *kwdargs)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001445{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001446 PyObject *iterable = NULL;
1447 PyObject *maxlenobj = NULL;
1448 Py_ssize_t maxlen = -1;
1449 char *kwlist[] = {"iterable", "maxlen", 0};
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001450
Raymond Hettinger05f1b932019-01-31 22:13:43 -08001451 if (kwdargs == NULL && PyTuple_GET_SIZE(args) <= 2) {
1452 if (PyTuple_GET_SIZE(args) > 0) {
1453 iterable = PyTuple_GET_ITEM(args, 0);
1454 }
1455 if (PyTuple_GET_SIZE(args) > 1) {
1456 maxlenobj = PyTuple_GET_ITEM(args, 1);
1457 }
Raymond Hettinger0d309402015-09-30 23:15:02 -07001458 } else {
1459 if (!PyArg_ParseTupleAndKeywords(args, kwdargs, "|OO:deque", kwlist,
1460 &iterable, &maxlenobj))
1461 return -1;
1462 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001463 if (maxlenobj != NULL && maxlenobj != Py_None) {
1464 maxlen = PyLong_AsSsize_t(maxlenobj);
1465 if (maxlen == -1 && PyErr_Occurred())
1466 return -1;
1467 if (maxlen < 0) {
1468 PyErr_SetString(PyExc_ValueError, "maxlen must be non-negative");
1469 return -1;
1470 }
1471 }
1472 deque->maxlen = maxlen;
Raymond Hettinger0d309402015-09-30 23:15:02 -07001473 if (Py_SIZE(deque) > 0)
1474 deque_clear(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001475 if (iterable != NULL) {
1476 PyObject *rv = deque_extend(deque, iterable);
1477 if (rv == NULL)
1478 return -1;
1479 Py_DECREF(rv);
1480 }
1481 return 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001482}
1483
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001484static PyObject *
Jesus Cea16e2fca2012-08-03 14:49:42 +02001485deque_sizeof(dequeobject *deque, void *unused)
1486{
1487 Py_ssize_t res;
1488 Py_ssize_t blocks;
1489
Serhiy Storchaka5c4064e2015-12-19 20:05:25 +02001490 res = _PyObject_SIZE(Py_TYPE(deque));
Raymond Hettingerbc003412015-10-14 23:33:23 -07001491 blocks = (size_t)(deque->leftindex + Py_SIZE(deque) + BLOCKLEN - 1) / BLOCKLEN;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001492 assert(deque->leftindex + Py_SIZE(deque) - 1 ==
Jesus Cea16e2fca2012-08-03 14:49:42 +02001493 (blocks - 1) * BLOCKLEN + deque->rightindex);
1494 res += blocks * sizeof(block);
1495 return PyLong_FromSsize_t(res);
1496}
1497
1498PyDoc_STRVAR(sizeof_doc,
1499"D.__sizeof__() -- size of D in memory, in bytes");
1500
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001501static int
1502deque_bool(dequeobject *deque)
1503{
1504 return Py_SIZE(deque) != 0;
1505}
1506
Jesus Cea16e2fca2012-08-03 14:49:42 +02001507static PyObject *
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +02001508deque_get_maxlen(dequeobject *deque, void *Py_UNUSED(ignored))
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001509{
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -07001510 if (deque->maxlen < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001511 Py_RETURN_NONE;
1512 return PyLong_FromSsize_t(deque->maxlen);
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001513}
1514
Raymond Hettinger41290a62015-03-31 08:12:23 -07001515
1516/* deque object ********************************************************/
1517
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001518static PyGetSetDef deque_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001519 {"maxlen", (getter)deque_get_maxlen, (setter)NULL,
1520 "maximum size of a deque or None if unbounded"},
1521 {0}
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001522};
1523
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001524static PySequenceMethods deque_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001525 (lenfunc)deque_len, /* sq_length */
Raymond Hettinger41290a62015-03-31 08:12:23 -07001526 (binaryfunc)deque_concat, /* sq_concat */
1527 (ssizeargfunc)deque_repeat, /* sq_repeat */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001528 (ssizeargfunc)deque_item, /* sq_item */
1529 0, /* sq_slice */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001530 (ssizeobjargproc)deque_ass_item, /* sq_ass_item */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001531 0, /* sq_ass_slice */
Raymond Hettinger39dadf72015-03-20 16:38:56 -07001532 (objobjproc)deque_contains, /* sq_contains */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001533 (binaryfunc)deque_inplace_concat, /* sq_inplace_concat */
Raymond Hettinger41290a62015-03-31 08:12:23 -07001534 (ssizeargfunc)deque_inplace_repeat, /* sq_inplace_repeat */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001535};
1536
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001537static PyNumberMethods deque_as_number = {
1538 0, /* nb_add */
1539 0, /* nb_subtract */
1540 0, /* nb_multiply */
1541 0, /* nb_remainder */
1542 0, /* nb_divmod */
1543 0, /* nb_power */
1544 0, /* nb_negative */
1545 0, /* nb_positive */
1546 0, /* nb_absolute */
1547 (inquiry)deque_bool, /* nb_bool */
1548 0, /* nb_invert */
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001549 };
1550
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001551static PyObject *deque_iter(dequeobject *deque);
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301552static PyObject *deque_reviter(dequeobject *deque, PyObject *Py_UNUSED(ignored));
Tim Peters1065f752004-10-01 01:03:29 +00001553PyDoc_STRVAR(reversed_doc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001554 "D.__reversed__() -- return a reverse iterator over the deque");
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001555
1556static PyMethodDef deque_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001557 {"append", (PyCFunction)deque_append,
1558 METH_O, append_doc},
1559 {"appendleft", (PyCFunction)deque_appendleft,
1560 METH_O, appendleft_doc},
1561 {"clear", (PyCFunction)deque_clearmethod,
1562 METH_NOARGS, clear_doc},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301563 {"__copy__", deque_copy,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001564 METH_NOARGS, copy_doc},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301565 {"copy", deque_copy,
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001566 METH_NOARGS, copy_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001567 {"count", (PyCFunction)deque_count,
Raymond Hettinger0f6f9472015-03-21 01:42:10 -07001568 METH_O, count_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001569 {"extend", (PyCFunction)deque_extend,
1570 METH_O, extend_doc},
1571 {"extendleft", (PyCFunction)deque_extendleft,
1572 METH_O, extendleft_doc},
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001573 {"index", (PyCFunction)(void(*)(void))deque_index,
Victor Stinnerdd407d52017-02-06 16:06:49 +01001574 METH_FASTCALL, index_doc},
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001575 {"insert", (PyCFunction)(void(*)(void))deque_insert,
Victor Stinnerdd407d52017-02-06 16:06:49 +01001576 METH_FASTCALL, insert_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001577 {"pop", (PyCFunction)deque_pop,
1578 METH_NOARGS, pop_doc},
1579 {"popleft", (PyCFunction)deque_popleft,
1580 METH_NOARGS, popleft_doc},
Raymond Hettinger0f6f9472015-03-21 01:42:10 -07001581 {"__reduce__", (PyCFunction)deque_reduce,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001582 METH_NOARGS, reduce_doc},
1583 {"remove", (PyCFunction)deque_remove,
1584 METH_O, remove_doc},
1585 {"__reversed__", (PyCFunction)deque_reviter,
1586 METH_NOARGS, reversed_doc},
1587 {"reverse", (PyCFunction)deque_reverse,
1588 METH_NOARGS, reverse_doc},
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001589 {"rotate", (PyCFunction)(void(*)(void))deque_rotate,
Victor Stinnerdd407d52017-02-06 16:06:49 +01001590 METH_FASTCALL, rotate_doc},
Jesus Cea16e2fca2012-08-03 14:49:42 +02001591 {"__sizeof__", (PyCFunction)deque_sizeof,
1592 METH_NOARGS, sizeof_doc},
Guido van Rossum48b069a2020-04-07 09:50:06 -07001593 {"__class_getitem__", (PyCFunction)Py_GenericAlias,
1594 METH_O|METH_CLASS, PyDoc_STR("See PEP 585")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001595 {NULL, NULL} /* sentinel */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001596};
1597
1598PyDoc_STRVAR(deque_doc,
Andrew Svetlov6a5c7c32012-10-31 11:50:40 +02001599"deque([iterable[, maxlen]]) --> deque object\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001600\n\
Raymond Hettinger41290a62015-03-31 08:12:23 -07001601A list-like sequence optimized for data accesses near its endpoints.");
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001602
Neal Norwitz87f10132004-02-29 15:40:53 +00001603static PyTypeObject deque_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001604 PyVarObject_HEAD_INIT(NULL, 0)
1605 "collections.deque", /* tp_name */
1606 sizeof(dequeobject), /* tp_basicsize */
1607 0, /* tp_itemsize */
1608 /* methods */
1609 (destructor)deque_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001610 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001611 0, /* tp_getattr */
1612 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001613 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001614 deque_repr, /* tp_repr */
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001615 &deque_as_number, /* tp_as_number */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001616 &deque_as_sequence, /* tp_as_sequence */
1617 0, /* tp_as_mapping */
Georg Brandlf038b322010-10-18 07:35:09 +00001618 PyObject_HashNotImplemented, /* tp_hash */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001619 0, /* tp_call */
1620 0, /* tp_str */
1621 PyObject_GenericGetAttr, /* tp_getattro */
1622 0, /* tp_setattro */
1623 0, /* tp_as_buffer */
1624 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
Georg Brandlf038b322010-10-18 07:35:09 +00001625 /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001626 deque_doc, /* tp_doc */
1627 (traverseproc)deque_traverse, /* tp_traverse */
1628 (inquiry)deque_clear, /* tp_clear */
1629 (richcmpfunc)deque_richcompare, /* tp_richcompare */
Georg Brandlf038b322010-10-18 07:35:09 +00001630 offsetof(dequeobject, weakreflist), /* tp_weaklistoffset*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001631 (getiterfunc)deque_iter, /* tp_iter */
1632 0, /* tp_iternext */
1633 deque_methods, /* tp_methods */
1634 0, /* tp_members */
Georg Brandlf038b322010-10-18 07:35:09 +00001635 deque_getset, /* tp_getset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001636 0, /* tp_base */
1637 0, /* tp_dict */
1638 0, /* tp_descr_get */
1639 0, /* tp_descr_set */
1640 0, /* tp_dictoffset */
1641 (initproc)deque_init, /* tp_init */
1642 PyType_GenericAlloc, /* tp_alloc */
1643 deque_new, /* tp_new */
1644 PyObject_GC_Del, /* tp_free */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001645};
1646
1647/*********************** Deque Iterator **************************/
1648
1649typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001650 PyObject_HEAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001651 block *b;
Raymond Hettinger87e69122015-03-02 23:32:02 -08001652 Py_ssize_t index;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001653 dequeobject *deque;
Raymond Hettingerf9d9c792015-03-02 22:47:46 -08001654 size_t state; /* state when the iterator is created */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001655 Py_ssize_t counter; /* number of items remaining for iteration */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001656} dequeiterobject;
1657
Martin v. Löwis59683e82008-06-13 07:50:45 +00001658static PyTypeObject dequeiter_type;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001659
1660static PyObject *
1661deque_iter(dequeobject *deque)
1662{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001663 dequeiterobject *it;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001664
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001665 it = PyObject_GC_New(dequeiterobject, &dequeiter_type);
1666 if (it == NULL)
1667 return NULL;
1668 it->b = deque->leftblock;
1669 it->index = deque->leftindex;
1670 Py_INCREF(deque);
1671 it->deque = deque;
1672 it->state = deque->state;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001673 it->counter = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001674 PyObject_GC_Track(it);
1675 return (PyObject *)it;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001676}
1677
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001678static int
1679dequeiter_traverse(dequeiterobject *dio, visitproc visit, void *arg)
1680{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001681 Py_VISIT(dio->deque);
1682 return 0;
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001683}
1684
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001685static void
1686dequeiter_dealloc(dequeiterobject *dio)
1687{
INADA Naokia6296d32017-08-24 14:55:17 +09001688 /* bpo-31095: UnTrack is needed before calling any callbacks */
1689 PyObject_GC_UnTrack(dio);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001690 Py_XDECREF(dio->deque);
1691 PyObject_GC_Del(dio);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001692}
1693
1694static PyObject *
1695dequeiter_next(dequeiterobject *it)
1696{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001697 PyObject *item;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001698
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001699 if (it->deque->state != it->state) {
1700 it->counter = 0;
1701 PyErr_SetString(PyExc_RuntimeError,
1702 "deque mutated during iteration");
1703 return NULL;
1704 }
1705 if (it->counter == 0)
1706 return NULL;
1707 assert (!(it->b == it->deque->rightblock &&
1708 it->index > it->deque->rightindex));
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001709
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001710 item = it->b->data[it->index];
1711 it->index++;
1712 it->counter--;
1713 if (it->index == BLOCKLEN && it->counter > 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -10001714 CHECK_NOT_END(it->b->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001715 it->b = it->b->rightlink;
1716 it->index = 0;
1717 }
1718 Py_INCREF(item);
1719 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001720}
1721
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001722static PyObject *
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001723dequeiter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1724{
1725 Py_ssize_t i, index=0;
1726 PyObject *deque;
1727 dequeiterobject *it;
1728 if (!PyArg_ParseTuple(args, "O!|n", &deque_type, &deque, &index))
1729 return NULL;
1730 assert(type == &dequeiter_type);
1731
1732 it = (dequeiterobject*)deque_iter((dequeobject *)deque);
1733 if (!it)
1734 return NULL;
1735 /* consume items from the queue */
1736 for(i=0; i<index; i++) {
1737 PyObject *item = dequeiter_next(it);
1738 if (item) {
1739 Py_DECREF(item);
1740 } else {
1741 if (it->counter) {
1742 Py_DECREF(it);
1743 return NULL;
1744 } else
1745 break;
1746 }
1747 }
1748 return (PyObject*)it;
1749}
1750
1751static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301752dequeiter_len(dequeiterobject *it, PyObject *Py_UNUSED(ignored))
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001753{
Antoine Pitrou554f3342010-08-17 18:30:06 +00001754 return PyLong_FromSsize_t(it->counter);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001755}
1756
Armin Rigof5b3e362006-02-11 21:32:43 +00001757PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001758
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001759static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301760dequeiter_reduce(dequeiterobject *it, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001761{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001762 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 +00001763}
1764
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001765static PyMethodDef dequeiter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001766 {"__length_hint__", (PyCFunction)dequeiter_len, METH_NOARGS, length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001767 {"__reduce__", (PyCFunction)dequeiter_reduce, METH_NOARGS, reduce_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001768 {NULL, NULL} /* sentinel */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001769};
1770
Martin v. Löwis59683e82008-06-13 07:50:45 +00001771static PyTypeObject dequeiter_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001772 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger87e69122015-03-02 23:32:02 -08001773 "_collections._deque_iterator", /* tp_name */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001774 sizeof(dequeiterobject), /* tp_basicsize */
1775 0, /* tp_itemsize */
1776 /* methods */
1777 (destructor)dequeiter_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001778 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001779 0, /* tp_getattr */
1780 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001781 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001782 0, /* tp_repr */
1783 0, /* tp_as_number */
1784 0, /* tp_as_sequence */
1785 0, /* tp_as_mapping */
1786 0, /* tp_hash */
1787 0, /* tp_call */
1788 0, /* tp_str */
1789 PyObject_GenericGetAttr, /* tp_getattro */
1790 0, /* tp_setattro */
1791 0, /* tp_as_buffer */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001792 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001793 0, /* tp_doc */
1794 (traverseproc)dequeiter_traverse, /* tp_traverse */
1795 0, /* tp_clear */
1796 0, /* tp_richcompare */
1797 0, /* tp_weaklistoffset */
1798 PyObject_SelfIter, /* tp_iter */
1799 (iternextfunc)dequeiter_next, /* tp_iternext */
1800 dequeiter_methods, /* tp_methods */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001801 0, /* tp_members */
1802 0, /* tp_getset */
1803 0, /* tp_base */
1804 0, /* tp_dict */
1805 0, /* tp_descr_get */
1806 0, /* tp_descr_set */
1807 0, /* tp_dictoffset */
1808 0, /* tp_init */
1809 0, /* tp_alloc */
1810 dequeiter_new, /* tp_new */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001811 0,
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001812};
1813
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001814/*********************** Deque Reverse Iterator **************************/
1815
Martin v. Löwis59683e82008-06-13 07:50:45 +00001816static PyTypeObject dequereviter_type;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001817
1818static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301819deque_reviter(dequeobject *deque, PyObject *Py_UNUSED(ignored))
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001820{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001821 dequeiterobject *it;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001823 it = PyObject_GC_New(dequeiterobject, &dequereviter_type);
1824 if (it == NULL)
1825 return NULL;
1826 it->b = deque->rightblock;
1827 it->index = deque->rightindex;
1828 Py_INCREF(deque);
1829 it->deque = deque;
1830 it->state = deque->state;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001831 it->counter = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001832 PyObject_GC_Track(it);
1833 return (PyObject *)it;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001834}
1835
1836static PyObject *
1837dequereviter_next(dequeiterobject *it)
1838{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001839 PyObject *item;
1840 if (it->counter == 0)
1841 return NULL;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001842
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001843 if (it->deque->state != it->state) {
1844 it->counter = 0;
1845 PyErr_SetString(PyExc_RuntimeError,
1846 "deque mutated during iteration");
1847 return NULL;
1848 }
1849 assert (!(it->b == it->deque->leftblock &&
1850 it->index < it->deque->leftindex));
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001851
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001852 item = it->b->data[it->index];
1853 it->index--;
1854 it->counter--;
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -07001855 if (it->index < 0 && it->counter > 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -10001856 CHECK_NOT_END(it->b->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001857 it->b = it->b->leftlink;
1858 it->index = BLOCKLEN - 1;
1859 }
1860 Py_INCREF(item);
1861 return item;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001862}
1863
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001864static PyObject *
1865dequereviter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1866{
1867 Py_ssize_t i, index=0;
1868 PyObject *deque;
1869 dequeiterobject *it;
1870 if (!PyArg_ParseTuple(args, "O!|n", &deque_type, &deque, &index))
1871 return NULL;
1872 assert(type == &dequereviter_type);
1873
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301874 it = (dequeiterobject*)deque_reviter((dequeobject *)deque, NULL);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001875 if (!it)
1876 return NULL;
1877 /* consume items from the queue */
1878 for(i=0; i<index; i++) {
1879 PyObject *item = dequereviter_next(it);
1880 if (item) {
1881 Py_DECREF(item);
1882 } else {
1883 if (it->counter) {
1884 Py_DECREF(it);
1885 return NULL;
1886 } else
1887 break;
1888 }
1889 }
1890 return (PyObject*)it;
1891}
1892
Martin v. Löwis59683e82008-06-13 07:50:45 +00001893static PyTypeObject dequereviter_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001894 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger87e69122015-03-02 23:32:02 -08001895 "_collections._deque_reverse_iterator", /* tp_name */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001896 sizeof(dequeiterobject), /* tp_basicsize */
1897 0, /* tp_itemsize */
1898 /* methods */
1899 (destructor)dequeiter_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001900 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001901 0, /* tp_getattr */
1902 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001903 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001904 0, /* tp_repr */
1905 0, /* tp_as_number */
1906 0, /* tp_as_sequence */
1907 0, /* tp_as_mapping */
1908 0, /* tp_hash */
1909 0, /* tp_call */
1910 0, /* tp_str */
1911 PyObject_GenericGetAttr, /* tp_getattro */
1912 0, /* tp_setattro */
1913 0, /* tp_as_buffer */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001914 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001915 0, /* tp_doc */
1916 (traverseproc)dequeiter_traverse, /* tp_traverse */
1917 0, /* tp_clear */
1918 0, /* tp_richcompare */
1919 0, /* tp_weaklistoffset */
1920 PyObject_SelfIter, /* tp_iter */
1921 (iternextfunc)dequereviter_next, /* tp_iternext */
1922 dequeiter_methods, /* tp_methods */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001923 0, /* tp_members */
1924 0, /* tp_getset */
1925 0, /* tp_base */
1926 0, /* tp_dict */
1927 0, /* tp_descr_get */
1928 0, /* tp_descr_set */
1929 0, /* tp_dictoffset */
1930 0, /* tp_init */
1931 0, /* tp_alloc */
1932 dequereviter_new, /* tp_new */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001933 0,
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001934};
1935
Guido van Rossum1968ad32006-02-25 22:38:04 +00001936/* defaultdict type *********************************************************/
1937
1938typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001939 PyDictObject dict;
1940 PyObject *default_factory;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001941} defdictobject;
1942
1943static PyTypeObject defdict_type; /* Forward */
1944
1945PyDoc_STRVAR(defdict_missing_doc,
1946"__missing__(key) # Called by __getitem__ for missing key; pseudo-code:\n\
Guido van Rossumd8faa362007-04-27 19:54:29 +00001947 if self.default_factory is None: raise KeyError((key,))\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00001948 self[key] = value = self.default_factory()\n\
1949 return value\n\
1950");
1951
1952static PyObject *
1953defdict_missing(defdictobject *dd, PyObject *key)
1954{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001955 PyObject *factory = dd->default_factory;
1956 PyObject *value;
1957 if (factory == NULL || factory == Py_None) {
1958 /* XXX Call dict.__missing__(key) */
1959 PyObject *tup;
1960 tup = PyTuple_Pack(1, key);
1961 if (!tup) return NULL;
1962 PyErr_SetObject(PyExc_KeyError, tup);
1963 Py_DECREF(tup);
1964 return NULL;
1965 }
Jeroen Demeyer7f41c8e2019-07-04 12:35:31 +02001966 value = _PyObject_CallNoArg(factory);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001967 if (value == NULL)
1968 return value;
1969 if (PyObject_SetItem((PyObject *)dd, key, value) < 0) {
1970 Py_DECREF(value);
1971 return NULL;
1972 }
1973 return value;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001974}
1975
Brandt Bucher57c9d172020-03-06 09:24:08 -08001976static inline PyObject*
1977new_defdict(defdictobject *dd, PyObject *arg)
1978{
1979 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd),
1980 dd->default_factory ? dd->default_factory : Py_None, arg, NULL);
1981}
1982
Guido van Rossum1968ad32006-02-25 22:38:04 +00001983PyDoc_STRVAR(defdict_copy_doc, "D.copy() -> a shallow copy of D.");
1984
1985static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301986defdict_copy(defdictobject *dd, PyObject *Py_UNUSED(ignored))
Guido van Rossum1968ad32006-02-25 22:38:04 +00001987{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001988 /* This calls the object's class. That only works for subclasses
1989 whose class constructor has the same signature. Subclasses that
1990 define a different constructor signature must override copy().
1991 */
Brandt Bucher57c9d172020-03-06 09:24:08 -08001992 return new_defdict(dd, (PyObject*)dd);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001993}
1994
1995static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301996defdict_reduce(defdictobject *dd, PyObject *Py_UNUSED(ignored))
Guido van Rossum1968ad32006-02-25 22:38:04 +00001997{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001998 /* __reduce__ must return a 5-tuple as follows:
Guido van Rossum1968ad32006-02-25 22:38:04 +00001999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002000 - factory function
2001 - tuple of args for the factory function
2002 - additional state (here None)
2003 - sequence iterator (here None)
2004 - dictionary iterator (yielding successive (key, value) pairs
Guido van Rossum1968ad32006-02-25 22:38:04 +00002005
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002006 This API is used by pickle.py and copy.py.
Guido van Rossum1968ad32006-02-25 22:38:04 +00002007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002008 For this to be useful with pickle.py, the default_factory
2009 must be picklable; e.g., None, a built-in, or a global
2010 function in a module or package.
Guido van Rossum1968ad32006-02-25 22:38:04 +00002011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002012 Both shallow and deep copying are supported, but for deep
2013 copying, the default_factory must be deep-copyable; e.g. None,
2014 or a built-in (functions are not copyable at this time).
Guido van Rossum1968ad32006-02-25 22:38:04 +00002015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002016 This only works for subclasses as long as their constructor
2017 signature is compatible; the first argument must be the
2018 optional default_factory, defaulting to None.
2019 */
2020 PyObject *args;
2021 PyObject *items;
2022 PyObject *iter;
2023 PyObject *result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002024 _Py_IDENTIFIER(items);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002025
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002026 if (dd->default_factory == NULL || dd->default_factory == Py_None)
2027 args = PyTuple_New(0);
2028 else
2029 args = PyTuple_Pack(1, dd->default_factory);
2030 if (args == NULL)
2031 return NULL;
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002032 items = _PyObject_CallMethodIdNoArgs((PyObject *)dd, &PyId_items);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002033 if (items == NULL) {
2034 Py_DECREF(args);
2035 return NULL;
2036 }
2037 iter = PyObject_GetIter(items);
2038 if (iter == NULL) {
2039 Py_DECREF(items);
2040 Py_DECREF(args);
2041 return NULL;
2042 }
2043 result = PyTuple_Pack(5, Py_TYPE(dd), args,
2044 Py_None, Py_None, iter);
2045 Py_DECREF(iter);
2046 Py_DECREF(items);
2047 Py_DECREF(args);
2048 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00002049}
2050
2051static PyMethodDef defdict_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002052 {"__missing__", (PyCFunction)defdict_missing, METH_O,
2053 defdict_missing_doc},
2054 {"copy", (PyCFunction)defdict_copy, METH_NOARGS,
2055 defdict_copy_doc},
2056 {"__copy__", (PyCFunction)defdict_copy, METH_NOARGS,
2057 defdict_copy_doc},
2058 {"__reduce__", (PyCFunction)defdict_reduce, METH_NOARGS,
2059 reduce_doc},
Guido van Rossum48b069a2020-04-07 09:50:06 -07002060 {"__class_getitem__", (PyCFunction)Py_GenericAlias, METH_O|METH_CLASS,
2061 PyDoc_STR("See PEP 585")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002062 {NULL}
Guido van Rossum1968ad32006-02-25 22:38:04 +00002063};
2064
2065static PyMemberDef defdict_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002066 {"default_factory", T_OBJECT,
2067 offsetof(defdictobject, default_factory), 0,
2068 PyDoc_STR("Factory for default value called by __missing__().")},
2069 {NULL}
Guido van Rossum1968ad32006-02-25 22:38:04 +00002070};
2071
2072static void
2073defdict_dealloc(defdictobject *dd)
2074{
INADA Naokia6296d32017-08-24 14:55:17 +09002075 /* bpo-31095: UnTrack is needed before calling any callbacks */
2076 PyObject_GC_UnTrack(dd);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002077 Py_CLEAR(dd->default_factory);
2078 PyDict_Type.tp_dealloc((PyObject *)dd);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002079}
2080
Guido van Rossum1968ad32006-02-25 22:38:04 +00002081static PyObject *
2082defdict_repr(defdictobject *dd)
2083{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002084 PyObject *baserepr;
2085 PyObject *defrepr;
2086 PyObject *result;
2087 baserepr = PyDict_Type.tp_repr((PyObject *)dd);
2088 if (baserepr == NULL)
2089 return NULL;
2090 if (dd->default_factory == NULL)
2091 defrepr = PyUnicode_FromString("None");
2092 else
2093 {
2094 int status = Py_ReprEnter(dd->default_factory);
2095 if (status != 0) {
Antoine Pitrouf5f1fe02012-02-15 02:42:46 +01002096 if (status < 0) {
2097 Py_DECREF(baserepr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002098 return NULL;
Antoine Pitrouf5f1fe02012-02-15 02:42:46 +01002099 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002100 defrepr = PyUnicode_FromString("...");
2101 }
2102 else
2103 defrepr = PyObject_Repr(dd->default_factory);
2104 Py_ReprLeave(dd->default_factory);
2105 }
2106 if (defrepr == NULL) {
2107 Py_DECREF(baserepr);
2108 return NULL;
2109 }
Serhiy Storchakab3a77962017-09-21 14:24:13 +03002110 result = PyUnicode_FromFormat("%s(%U, %U)",
2111 _PyType_Name(Py_TYPE(dd)),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002112 defrepr, baserepr);
2113 Py_DECREF(defrepr);
2114 Py_DECREF(baserepr);
2115 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00002116}
2117
Brandt Bucher57c9d172020-03-06 09:24:08 -08002118static PyObject*
2119defdict_or(PyObject* left, PyObject* right)
2120{
Brandt Bucher57c9d172020-03-06 09:24:08 -08002121 PyObject *self, *other;
Brandt Bucher1dd37942020-03-11 21:06:46 -07002122 if (PyObject_TypeCheck(left, &defdict_type)) {
Brandt Bucher57c9d172020-03-06 09:24:08 -08002123 self = left;
2124 other = right;
2125 }
2126 else {
2127 self = right;
2128 other = left;
2129 }
2130 if (!PyDict_Check(other)) {
2131 Py_RETURN_NOTIMPLEMENTED;
2132 }
2133 // Like copy(), this calls the object's class.
2134 // Override __or__/__ror__ for subclasses with different constructors.
2135 PyObject *new = new_defdict((defdictobject*)self, left);
2136 if (!new) {
2137 return NULL;
2138 }
2139 if (PyDict_Update(new, right)) {
2140 Py_DECREF(new);
2141 return NULL;
2142 }
2143 return new;
2144}
2145
2146static PyNumberMethods defdict_as_number = {
2147 .nb_or = defdict_or,
2148};
2149
Guido van Rossum1968ad32006-02-25 22:38:04 +00002150static int
2151defdict_traverse(PyObject *self, visitproc visit, void *arg)
2152{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002153 Py_VISIT(((defdictobject *)self)->default_factory);
2154 return PyDict_Type.tp_traverse(self, visit, arg);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002155}
2156
2157static int
2158defdict_tp_clear(defdictobject *dd)
2159{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002160 Py_CLEAR(dd->default_factory);
2161 return PyDict_Type.tp_clear((PyObject *)dd);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002162}
2163
2164static int
2165defdict_init(PyObject *self, PyObject *args, PyObject *kwds)
2166{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002167 defdictobject *dd = (defdictobject *)self;
2168 PyObject *olddefault = dd->default_factory;
2169 PyObject *newdefault = NULL;
2170 PyObject *newargs;
2171 int result;
2172 if (args == NULL || !PyTuple_Check(args))
2173 newargs = PyTuple_New(0);
2174 else {
2175 Py_ssize_t n = PyTuple_GET_SIZE(args);
2176 if (n > 0) {
2177 newdefault = PyTuple_GET_ITEM(args, 0);
2178 if (!PyCallable_Check(newdefault) && newdefault != Py_None) {
2179 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger239aba72015-07-20 03:09:22 -04002180 "first argument must be callable or None");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002181 return -1;
2182 }
2183 }
2184 newargs = PySequence_GetSlice(args, 1, n);
2185 }
2186 if (newargs == NULL)
2187 return -1;
2188 Py_XINCREF(newdefault);
2189 dd->default_factory = newdefault;
2190 result = PyDict_Type.tp_init(self, newargs, kwds);
2191 Py_DECREF(newargs);
2192 Py_XDECREF(olddefault);
2193 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00002194}
2195
2196PyDoc_STRVAR(defdict_doc,
Benjamin Peterson9cb33b72014-01-13 23:56:05 -05002197"defaultdict(default_factory[, ...]) --> dict with default factory\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00002198\n\
2199The default factory is called without arguments to produce\n\
2200a new value when a key is not present, in __getitem__ only.\n\
2201A defaultdict compares equal to a dict with the same items.\n\
Benjamin Peterson9cb33b72014-01-13 23:56:05 -05002202All remaining arguments are treated the same as if they were\n\
2203passed to the dict constructor, including keyword arguments.\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00002204");
2205
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002206/* See comment in xxsubtype.c */
2207#define DEFERRED_ADDRESS(ADDR) 0
2208
Guido van Rossum1968ad32006-02-25 22:38:04 +00002209static PyTypeObject defdict_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002210 PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0)
2211 "collections.defaultdict", /* tp_name */
2212 sizeof(defdictobject), /* tp_basicsize */
2213 0, /* tp_itemsize */
2214 /* methods */
2215 (destructor)defdict_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002216 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002217 0, /* tp_getattr */
2218 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002219 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002220 (reprfunc)defdict_repr, /* tp_repr */
Brandt Bucher57c9d172020-03-06 09:24:08 -08002221 &defdict_as_number, /* tp_as_number */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002222 0, /* tp_as_sequence */
2223 0, /* tp_as_mapping */
2224 0, /* tp_hash */
2225 0, /* tp_call */
2226 0, /* tp_str */
2227 PyObject_GenericGetAttr, /* tp_getattro */
2228 0, /* tp_setattro */
2229 0, /* tp_as_buffer */
2230 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
2231 /* tp_flags */
2232 defdict_doc, /* tp_doc */
2233 defdict_traverse, /* tp_traverse */
2234 (inquiry)defdict_tp_clear, /* tp_clear */
2235 0, /* tp_richcompare */
2236 0, /* tp_weaklistoffset*/
2237 0, /* tp_iter */
2238 0, /* tp_iternext */
2239 defdict_methods, /* tp_methods */
2240 defdict_members, /* tp_members */
2241 0, /* tp_getset */
2242 DEFERRED_ADDRESS(&PyDict_Type), /* tp_base */
2243 0, /* tp_dict */
2244 0, /* tp_descr_get */
2245 0, /* tp_descr_set */
2246 0, /* tp_dictoffset */
2247 defdict_init, /* tp_init */
2248 PyType_GenericAlloc, /* tp_alloc */
2249 0, /* tp_new */
2250 PyObject_GC_Del, /* tp_free */
Guido van Rossum1968ad32006-02-25 22:38:04 +00002251};
2252
Raymond Hettinger96f34102010-12-15 16:30:37 +00002253/* helper function for Counter *********************************************/
2254
Raymond Hettingere9858042019-06-05 16:05:25 -07002255/*[clinic input]
2256_collections._count_elements
2257
2258 mapping: object
2259 iterable: object
2260 /
2261
2262Count elements in the iterable, updating the mapping
2263[clinic start generated code]*/
Raymond Hettinger96f34102010-12-15 16:30:37 +00002264
2265static PyObject *
Raymond Hettingere9858042019-06-05 16:05:25 -07002266_collections__count_elements_impl(PyObject *module, PyObject *mapping,
2267 PyObject *iterable)
2268/*[clinic end generated code: output=7e0c1789636b3d8f input=e79fad04534a0b45]*/
Raymond Hettinger96f34102010-12-15 16:30:37 +00002269{
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002270 _Py_IDENTIFIER(get);
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002271 _Py_IDENTIFIER(__setitem__);
Raymond Hettingere9858042019-06-05 16:05:25 -07002272 PyObject *it, *oldval;
Raymond Hettinger96f34102010-12-15 16:30:37 +00002273 PyObject *newval = NULL;
2274 PyObject *key = NULL;
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002275 PyObject *bound_get = NULL;
2276 PyObject *mapping_get;
2277 PyObject *dict_get;
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002278 PyObject *mapping_setitem;
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002279 PyObject *dict_setitem;
Raymond Hettinger96f34102010-12-15 16:30:37 +00002280
Raymond Hettinger96f34102010-12-15 16:30:37 +00002281 it = PyObject_GetIter(iterable);
2282 if (it == NULL)
2283 return NULL;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002284
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002285 /* Only take the fast path when get() and __setitem__()
2286 * have not been overridden.
2287 */
2288 mapping_get = _PyType_LookupId(Py_TYPE(mapping), &PyId_get);
2289 dict_get = _PyType_LookupId(&PyDict_Type, &PyId_get);
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002290 mapping_setitem = _PyType_LookupId(Py_TYPE(mapping), &PyId___setitem__);
2291 dict_setitem = _PyType_LookupId(&PyDict_Type, &PyId___setitem__);
2292
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002293 if (mapping_get != NULL && mapping_get == dict_get &&
Oren Milman31aca4b2017-09-27 06:18:21 +03002294 mapping_setitem != NULL && mapping_setitem == dict_setitem &&
2295 PyDict_Check(mapping))
2296 {
Raymond Hettinger426e0522011-01-03 02:12:02 +00002297 while (1) {
Raymond Hettinger507d9972014-05-18 21:32:40 +01002298 /* Fast path advantages:
2299 1. Eliminate double hashing
2300 (by re-using the same hash for both the get and set)
2301 2. Avoid argument overhead of PyObject_CallFunctionObjArgs
2302 (argument tuple creation and parsing)
2303 3. Avoid indirection through a bound method object
2304 (creates another argument tuple)
2305 4. Avoid initial increment from zero
2306 (reuse an existing one-object instead)
2307 */
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002308 Py_hash_t hash;
2309
Raymond Hettinger426e0522011-01-03 02:12:02 +00002310 key = PyIter_Next(it);
Victor Stinnera154b5c2011-04-20 23:23:52 +02002311 if (key == NULL)
2312 break;
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002313
2314 if (!PyUnicode_CheckExact(key) ||
2315 (hash = ((PyASCIIObject *) key)->hash) == -1)
2316 {
2317 hash = PyObject_Hash(key);
Raymond Hettingerda2850f2015-02-27 12:42:54 -08002318 if (hash == -1)
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002319 goto done;
2320 }
2321
2322 oldval = _PyDict_GetItem_KnownHash(mapping, key, hash);
Raymond Hettinger426e0522011-01-03 02:12:02 +00002323 if (oldval == NULL) {
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02002324 if (PyErr_Occurred())
2325 goto done;
Serhiy Storchakaba85d692017-03-30 09:09:41 +03002326 if (_PyDict_SetItem_KnownHash(mapping, key, _PyLong_One, hash) < 0)
Raymond Hettinger507d9972014-05-18 21:32:40 +01002327 goto done;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002328 } else {
Serhiy Storchakaba85d692017-03-30 09:09:41 +03002329 newval = PyNumber_Add(oldval, _PyLong_One);
Raymond Hettinger426e0522011-01-03 02:12:02 +00002330 if (newval == NULL)
Raymond Hettinger507d9972014-05-18 21:32:40 +01002331 goto done;
Raymond Hettinger28c995d2015-08-14 02:07:41 -07002332 if (_PyDict_SetItem_KnownHash(mapping, key, newval, hash) < 0)
Raymond Hettinger507d9972014-05-18 21:32:40 +01002333 goto done;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002334 Py_CLEAR(newval);
2335 }
2336 Py_DECREF(key);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002337 }
Raymond Hettinger426e0522011-01-03 02:12:02 +00002338 } else {
Victor Stinnere7f516c2013-11-06 23:52:55 +01002339 bound_get = _PyObject_GetAttrId(mapping, &PyId_get);
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002340 if (bound_get == NULL)
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002341 goto done;
2342
Raymond Hettinger426e0522011-01-03 02:12:02 +00002343 while (1) {
2344 key = PyIter_Next(it);
Victor Stinnera154b5c2011-04-20 23:23:52 +02002345 if (key == NULL)
2346 break;
Serhiy Storchakaba85d692017-03-30 09:09:41 +03002347 oldval = PyObject_CallFunctionObjArgs(bound_get, key, _PyLong_Zero, NULL);
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002348 if (oldval == NULL)
2349 break;
Serhiy Storchakaba85d692017-03-30 09:09:41 +03002350 newval = PyNumber_Add(oldval, _PyLong_One);
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002351 Py_DECREF(oldval);
2352 if (newval == NULL)
2353 break;
Raymond Hettinger28c995d2015-08-14 02:07:41 -07002354 if (PyObject_SetItem(mapping, key, newval) < 0)
Raymond Hettinger96f34102010-12-15 16:30:37 +00002355 break;
2356 Py_CLEAR(newval);
Raymond Hettinger426e0522011-01-03 02:12:02 +00002357 Py_DECREF(key);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002358 }
Raymond Hettinger96f34102010-12-15 16:30:37 +00002359 }
Raymond Hettinger426e0522011-01-03 02:12:02 +00002360
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002361done:
Raymond Hettinger96f34102010-12-15 16:30:37 +00002362 Py_DECREF(it);
2363 Py_XDECREF(key);
2364 Py_XDECREF(newval);
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002365 Py_XDECREF(bound_get);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002366 if (PyErr_Occurred())
2367 return NULL;
2368 Py_RETURN_NONE;
2369}
2370
Serhiy Storchaka052b2df2018-12-31 14:15:16 +02002371/* Helper function for namedtuple() ************************************/
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002372
2373typedef struct {
2374 PyObject_HEAD
2375 Py_ssize_t index;
2376 PyObject* doc;
2377} _tuplegetterobject;
2378
2379/*[clinic input]
2380@classmethod
2381_tuplegetter.__new__ as tuplegetter_new
2382
2383 index: Py_ssize_t
2384 doc: object
2385 /
2386[clinic start generated code]*/
2387
2388static PyObject *
2389tuplegetter_new_impl(PyTypeObject *type, Py_ssize_t index, PyObject *doc)
2390/*[clinic end generated code: output=014be444ad80263f input=87c576a5bdbc0bbb]*/
2391{
2392 _tuplegetterobject* self;
2393 self = (_tuplegetterobject *)type->tp_alloc(type, 0);
2394 if (self == NULL) {
2395 return NULL;
2396 }
2397 self->index = index;
2398 Py_INCREF(doc);
2399 self->doc = doc;
2400 return (PyObject *)self;
2401}
2402
2403static PyObject *
Serhiy Storchaka052b2df2018-12-31 14:15:16 +02002404tuplegetter_descr_get(PyObject *self, PyObject *obj, PyObject *type)
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002405{
Serhiy Storchaka052b2df2018-12-31 14:15:16 +02002406 Py_ssize_t index = ((_tuplegetterobject*)self)->index;
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002407 PyObject *result;
Serhiy Storchaka052b2df2018-12-31 14:15:16 +02002408
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002409 if (obj == NULL) {
2410 Py_INCREF(self);
2411 return self;
2412 }
2413 if (!PyTuple_Check(obj)) {
2414 if (obj == Py_None) {
2415 Py_INCREF(self);
2416 return self;
2417 }
2418 PyErr_Format(PyExc_TypeError,
Serhiy Storchakad53fe5f2019-03-13 22:59:55 +02002419 "descriptor for index '%zd' for tuple subclasses "
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002420 "doesn't apply to '%s' object",
Serhiy Storchaka052b2df2018-12-31 14:15:16 +02002421 index,
Victor Stinnerdaa97562020-02-07 03:37:06 +01002422 Py_TYPE(obj)->tp_name);
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002423 return NULL;
2424 }
2425
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002426 if (!valid_index(index, PyTuple_GET_SIZE(obj))) {
2427 PyErr_SetString(PyExc_IndexError, "tuple index out of range");
2428 return NULL;
2429 }
2430
2431 result = PyTuple_GET_ITEM(obj, index);
2432 Py_INCREF(result);
2433 return result;
2434}
2435
2436static int
Serhiy Storchaka052b2df2018-12-31 14:15:16 +02002437tuplegetter_descr_set(PyObject *self, PyObject *obj, PyObject *value)
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002438{
2439 if (value == NULL) {
2440 PyErr_SetString(PyExc_AttributeError, "can't delete attribute");
2441 } else {
2442 PyErr_SetString(PyExc_AttributeError, "can't set attribute");
2443 }
2444 return -1;
2445}
2446
2447static int
2448tuplegetter_traverse(PyObject *self, visitproc visit, void *arg)
2449{
2450 _tuplegetterobject *tuplegetter = (_tuplegetterobject *)self;
2451 Py_VISIT(tuplegetter->doc);
2452 return 0;
2453}
2454
2455static int
2456tuplegetter_clear(PyObject *self)
2457{
2458 _tuplegetterobject *tuplegetter = (_tuplegetterobject *)self;
2459 Py_CLEAR(tuplegetter->doc);
2460 return 0;
2461}
2462
2463static void
2464tuplegetter_dealloc(_tuplegetterobject *self)
2465{
2466 PyObject_GC_UnTrack(self);
2467 tuplegetter_clear((PyObject*)self);
2468 Py_TYPE(self)->tp_free((PyObject*)self);
2469}
2470
Joe Jevnikf36f8922019-02-21 16:00:40 -05002471static PyObject*
Serhiy Storchakaadfffc72019-03-05 18:41:09 +02002472tuplegetter_reduce(_tuplegetterobject *self, PyObject *Py_UNUSED(ignored))
Joe Jevnikf36f8922019-02-21 16:00:40 -05002473{
2474 return Py_BuildValue("(O(nO))", (PyObject*) Py_TYPE(self), self->index, self->doc);
2475}
2476
Ammar Askara86b5222020-04-14 23:36:08 -07002477static PyObject*
2478tuplegetter_repr(_tuplegetterobject *self)
2479{
2480 return PyUnicode_FromFormat("%s(%zd, %R)",
2481 _PyType_Name(Py_TYPE(self)),
2482 self->index, self->doc);
2483}
2484
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002485
2486static PyMemberDef tuplegetter_members[] = {
2487 {"__doc__", T_OBJECT, offsetof(_tuplegetterobject, doc), 0},
2488 {0}
2489};
2490
Joe Jevnikf36f8922019-02-21 16:00:40 -05002491static PyMethodDef tuplegetter_methods[] = {
Serhiy Storchakaadfffc72019-03-05 18:41:09 +02002492 {"__reduce__", (PyCFunction)tuplegetter_reduce, METH_NOARGS, NULL},
Joe Jevnikf36f8922019-02-21 16:00:40 -05002493 {NULL},
2494};
2495
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002496static PyTypeObject tuplegetter_type = {
2497 PyVarObject_HEAD_INIT(NULL, 0)
2498 "_collections._tuplegetter", /* tp_name */
2499 sizeof(_tuplegetterobject), /* tp_basicsize */
2500 0, /* tp_itemsize */
2501 /* methods */
2502 (destructor)tuplegetter_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002503 0, /* tp_vectorcall_offset */
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002504 0, /* tp_getattr */
2505 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002506 0, /* tp_as_async */
Ammar Askara86b5222020-04-14 23:36:08 -07002507 (reprfunc)tuplegetter_repr, /* tp_repr */
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002508 0, /* tp_as_number */
2509 0, /* tp_as_sequence */
2510 0, /* tp_as_mapping */
2511 0, /* tp_hash */
2512 0, /* tp_call */
2513 0, /* tp_str */
2514 0, /* tp_getattro */
2515 0, /* tp_setattro */
2516 0, /* tp_as_buffer */
2517 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
2518 0, /* tp_doc */
2519 (traverseproc)tuplegetter_traverse, /* tp_traverse */
2520 (inquiry)tuplegetter_clear, /* tp_clear */
2521 0, /* tp_richcompare */
2522 0, /* tp_weaklistoffset */
2523 0, /* tp_iter */
2524 0, /* tp_iternext */
Joe Jevnikf36f8922019-02-21 16:00:40 -05002525 tuplegetter_methods, /* tp_methods */
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002526 tuplegetter_members, /* tp_members */
2527 0, /* tp_getset */
2528 0, /* tp_base */
2529 0, /* tp_dict */
Serhiy Storchaka052b2df2018-12-31 14:15:16 +02002530 tuplegetter_descr_get, /* tp_descr_get */
2531 tuplegetter_descr_set, /* tp_descr_set */
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002532 0, /* tp_dictoffset */
2533 0, /* tp_init */
2534 0, /* tp_alloc */
2535 tuplegetter_new, /* tp_new */
2536 0,
2537};
2538
2539
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002540/* module level code ********************************************************/
2541
Dong-hee Na77248a22020-03-20 01:16:04 +09002542PyDoc_STRVAR(collections_doc,
Guido van Rossum1968ad32006-02-25 22:38:04 +00002543"High performance data structures.\n\
2544- deque: ordered collection accessible from endpoints only\n\
2545- defaultdict: dict subclass with a default value factory\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002546");
2547
Dong-hee Na77248a22020-03-20 01:16:04 +09002548static struct PyMethodDef collections_methods[] = {
Raymond Hettingere9858042019-06-05 16:05:25 -07002549 _COLLECTIONS__COUNT_ELEMENTS_METHODDEF
Raymond Hettinger96f34102010-12-15 16:30:37 +00002550 {NULL, NULL} /* sentinel */
2551};
Martin v. Löwis1a214512008-06-11 05:26:20 +00002552
Dong-hee Na77248a22020-03-20 01:16:04 +09002553static int
2554collections_exec(PyObject *module) {
2555 PyTypeObject *typelist[] = {
2556 &deque_type,
2557 &defdict_type,
2558 &PyODict_Type,
2559 &dequeiter_type,
2560 &dequereviter_type,
Dong-hee Na05e4a292020-03-23 01:17:34 +09002561 &tuplegetter_type
Dong-hee Na77248a22020-03-20 01:16:04 +09002562 };
2563
2564 defdict_type.tp_base = &PyDict_Type;
2565
Dong-hee Na05e4a292020-03-23 01:17:34 +09002566 for (size_t i = 0; i < Py_ARRAY_LENGTH(typelist); i++) {
2567 if (PyModule_AddType(module, typelist[i]) < 0) {
Dong-hee Na77248a22020-03-20 01:16:04 +09002568 return -1;
2569 }
2570 }
2571
2572 return 0;
2573}
2574
2575static struct PyModuleDef_Slot collections_slots[] = {
2576 {Py_mod_exec, collections_exec},
2577 {0, NULL}
2578};
2579
Martin v. Löwis1a214512008-06-11 05:26:20 +00002580static struct PyModuleDef _collectionsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002581 PyModuleDef_HEAD_INIT,
2582 "_collections",
Dong-hee Na77248a22020-03-20 01:16:04 +09002583 collections_doc,
2584 0,
2585 collections_methods,
2586 collections_slots,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002587 NULL,
2588 NULL,
2589 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002590};
2591
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002592PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002593PyInit__collections(void)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002594{
Dong-hee Na77248a22020-03-20 01:16:04 +09002595 return PyModuleDef_Init(&_collectionsmodule);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002596}