blob: 8b01a7fad01a2619e4ff38f646bfa1cf6d2e52b7 [file] [log] [blame]
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001#include "Python.h"
Victor Stinner37834132020-10-27 17:12:53 +01002#include "pycore_long.h" // _PyLong_GetZero()
Victor Stinner4a21e572020-04-15 02:35:41 +02003#include "structmember.h" // PyMemberDef
Raymond Hettinger756b3f32004-01-29 06:37:52 +00004
Raymond Hettingerc2083082015-02-28 23:29:16 -08005#ifdef STDC_HEADERS
6#include <stddef.h>
7#else
Victor Stinner4a21e572020-04-15 02:35:41 +02008#include <sys/types.h> // size_t
Raymond Hettingerc2083082015-02-28 23:29:16 -08009#endif
10
Pablo Galindo3f5fc702018-12-30 09:24:03 +000011/*[clinic input]
Raymond Hettingere9858042019-06-05 16:05:25 -070012module _collections
Pablo Galindo3f5fc702018-12-30 09:24:03 +000013class _tuplegetter "_tuplegetterobject *" "&tuplegetter_type"
14[clinic start generated code]*/
Raymond Hettingere9858042019-06-05 16:05:25 -070015/*[clinic end generated code: output=da39a3ee5e6b4b0d input=a8ece4ccad7e30ac]*/
Pablo Galindo3f5fc702018-12-30 09:24:03 +000016
17static PyTypeObject tuplegetter_type;
18#include "clinic/_collectionsmodule.c.h"
19
Raymond Hettinger756b3f32004-01-29 06:37:52 +000020/* collections module implementation of a deque() datatype
21 Written and maintained by Raymond D. Hettinger <python@rcn.com>
Raymond Hettinger756b3f32004-01-29 06:37:52 +000022*/
23
Raymond Hettinger77e8bf12004-10-01 15:25:53 +000024/* The block length may be set to any number over 1. Larger numbers
Raymond Hettinger20b0f872013-06-23 15:44:33 -070025 * reduce the number of calls to the memory allocator, give faster
Raymond Hettinger30c90742015-03-02 22:31:35 -080026 * indexing and rotation, and reduce the link to data overhead ratio.
Raymond Hettingerdaf57f22015-02-26 23:21:29 -080027 * Making the block length a power of two speeds-up the modulo
Raymond Hettinger30c90742015-03-02 22:31:35 -080028 * and division calculations in deque_item() and deque_ass_item().
Raymond Hettinger77e8bf12004-10-01 15:25:53 +000029 */
30
Raymond Hettingerdaf57f22015-02-26 23:21:29 -080031#define BLOCKLEN 64
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000032#define CENTER ((BLOCKLEN - 1) / 2)
Raymond Hettinger756b3f32004-01-29 06:37:52 +000033
Raymond Hettinger551350a2015-03-24 00:19:53 -070034/* Data for deque objects is stored in a doubly-linked list of fixed
35 * length blocks. This assures that appends or pops never move any
36 * other data elements besides the one being appended or popped.
37 *
38 * Another advantage is that it completely avoids use of realloc(),
39 * resulting in more predictable performance.
40 *
41 * Textbook implementations of doubly-linked lists store one datum
42 * per link, but that gives them a 200% memory overhead (a prev and
43 * next link for each datum) and it costs one malloc() call per data
44 * element. By using fixed-length blocks, the link to data ratio is
45 * significantly improved and there are proportionally fewer calls
46 * to malloc() and free(). The data blocks of consecutive pointers
47 * also improve cache locality.
48 *
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000049 * The list of blocks is never empty, so d.leftblock and d.rightblock
Raymond Hettinger82df9252013-07-07 01:43:42 -100050 * are never equal to NULL. The list is not circular.
51 *
52 * A deque d's first element is at d.leftblock[leftindex]
53 * and its last element is at d.rightblock[rightindex].
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000054 *
Raymond Hettinger551350a2015-03-24 00:19:53 -070055 * Unlike Python slice indices, these indices are inclusive on both
56 * ends. This makes the algorithms for left and right operations
57 * more symmetrical and it simplifies the design.
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000058 *
Raymond Hettinger551350a2015-03-24 00:19:53 -070059 * The indices, d.leftindex and d.rightindex are always in the range:
60 * 0 <= index < BLOCKLEN
61 *
62 * And their exact relationship is:
63 * (d.leftindex + d.len - 1) % BLOCKLEN == d.rightindex
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000064 *
Raymond Hettinger8dbbae22015-03-24 21:01:50 -070065 * Whenever d.leftblock == d.rightblock, then:
Raymond Hettinger551350a2015-03-24 00:19:53 -070066 * d.leftindex + d.len - 1 == d.rightindex
Thomas Wouters0e3f5912006-08-11 14:57:12 +000067 *
Raymond Hettinger551350a2015-03-24 00:19:53 -070068 * However, when d.leftblock != d.rightblock, the d.leftindex and
69 * d.rightindex become indices into distinct blocks and either may
70 * be larger than the other.
71 *
72 * Empty deques have:
73 * d.len == 0
74 * d.leftblock == d.rightblock
75 * d.leftindex == CENTER + 1
76 * d.rightindex == CENTER
77 *
78 * Checking for d.len == 0 is the intended way to see whether d is empty.
Tim Petersd8768d32004-10-01 01:32:53 +000079 */
80
Raymond Hettinger756b3f32004-01-29 06:37:52 +000081typedef struct BLOCK {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000082 struct BLOCK *leftlink;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000083 PyObject *data[BLOCKLEN];
Raymond Hettinger20b0f872013-06-23 15:44:33 -070084 struct BLOCK *rightlink;
Raymond Hettinger756b3f32004-01-29 06:37:52 +000085} block;
86
Raymond Hettinger30c90742015-03-02 22:31:35 -080087typedef struct {
88 PyObject_VAR_HEAD
89 block *leftblock;
90 block *rightblock;
Raymond Hettinger551350a2015-03-24 00:19:53 -070091 Py_ssize_t leftindex; /* 0 <= leftindex < BLOCKLEN */
92 Py_ssize_t rightindex; /* 0 <= rightindex < BLOCKLEN */
Raymond Hettingerf9d9c792015-03-02 22:47:46 -080093 size_t state; /* incremented whenever the indices move */
Raymond Hettingerd84ec222016-01-24 09:12:06 -080094 Py_ssize_t maxlen; /* maxlen is -1 for unbounded deques */
Raymond Hettinger0f6f9472015-03-21 01:42:10 -070095 PyObject *weakreflist;
Raymond Hettinger30c90742015-03-02 22:31:35 -080096} dequeobject;
97
98static PyTypeObject deque_type;
99
Raymond Hettinger82df9252013-07-07 01:43:42 -1000100/* For debug builds, add error checking to track the endpoints
101 * in the chain of links. The goal is to make sure that link
102 * assignments only take place at endpoints so that links already
103 * in use do not get overwritten.
104 *
105 * CHECK_END should happen before each assignment to a block's link field.
106 * MARK_END should happen whenever a link field becomes a new endpoint.
107 * This happens when new blocks are added or whenever an existing
108 * block is freed leaving another existing block as the new endpoint.
109 */
110
Raymond Hettinger3223dd52013-07-26 23:14:22 -0700111#ifndef NDEBUG
Raymond Hettinger82df9252013-07-07 01:43:42 -1000112#define MARK_END(link) link = NULL;
113#define CHECK_END(link) assert(link == NULL);
114#define CHECK_NOT_END(link) assert(link != NULL);
115#else
116#define MARK_END(link)
117#define CHECK_END(link)
118#define CHECK_NOT_END(link)
119#endif
120
Raymond Hettinger3bb19872021-03-25 13:32:23 -0700121/* A simple freelisting scheme is used to minimize calls to the memory
122 allocator. It accommodates common use cases where new blocks are being
123 added at about the same rate as old blocks are being freed.
124 */
125
126#define MAXFREEBLOCKS 16
127static Py_ssize_t numfreeblocks = 0;
128static block *freeblocks[MAXFREEBLOCKS];
129
Tim Peters6f853562004-10-01 01:04:50 +0000130static block *
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700131newblock(void) {
Raymond Hettinger3bb19872021-03-25 13:32:23 -0700132 block *b;
133 if (numfreeblocks) {
134 numfreeblocks--;
135 return freeblocks[numfreeblocks];
136 }
137 b = PyMem_Malloc(sizeof(block));
Raymond Hettinger82df9252013-07-07 01:43:42 -1000138 if (b != NULL) {
139 return b;
140 }
141 PyErr_NoMemory();
142 return NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000143}
144
Martin v. Löwis59683e82008-06-13 07:50:45 +0000145static void
Guido van Rossum58da9312007-11-10 23:39:45 +0000146freeblock(block *b)
147{
Raymond Hettinger3bb19872021-03-25 13:32:23 -0700148 if (numfreeblocks < MAXFREEBLOCKS) {
149 freeblocks[numfreeblocks] = b;
150 numfreeblocks++;
151 } else {
152 PyMem_Free(b);
153 }
Guido van Rossum58da9312007-11-10 23:39:45 +0000154}
155
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000156static PyObject *
157deque_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
158{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000159 dequeobject *deque;
160 block *b;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000161
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000162 /* create dequeobject structure */
163 deque = (dequeobject *)type->tp_alloc(type, 0);
164 if (deque == NULL)
165 return NULL;
Tim Peters1065f752004-10-01 01:03:29 +0000166
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700167 b = newblock();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000168 if (b == NULL) {
169 Py_DECREF(deque);
170 return NULL;
171 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000172 MARK_END(b->leftlink);
173 MARK_END(b->rightlink);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175 assert(BLOCKLEN >= 2);
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100176 Py_SET_SIZE(deque, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000177 deque->leftblock = b;
178 deque->rightblock = b;
179 deque->leftindex = CENTER + 1;
180 deque->rightindex = CENTER;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000181 deque->state = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000182 deque->maxlen = -1;
Raymond Hettinger87e69122015-03-02 23:32:02 -0800183 deque->weakreflist = NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000184
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000185 return (PyObject *)deque;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000186}
187
188static PyObject *
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000189deque_pop(dequeobject *deque, PyObject *unused)
190{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000191 PyObject *item;
192 block *prevblock;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000193
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000194 if (Py_SIZE(deque) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000195 PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
196 return NULL;
197 }
198 item = deque->rightblock->data[deque->rightindex];
199 deque->rightindex--;
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100200 Py_SET_SIZE(deque, Py_SIZE(deque) - 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000201 deque->state++;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000202
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -0700203 if (deque->rightindex < 0) {
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700204 if (Py_SIZE(deque)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000205 prevblock = deque->rightblock->leftlink;
206 assert(deque->leftblock != deque->rightblock);
207 freeblock(deque->rightblock);
Raymond Hettinger82df9252013-07-07 01:43:42 -1000208 CHECK_NOT_END(prevblock);
209 MARK_END(prevblock->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000210 deque->rightblock = prevblock;
211 deque->rightindex = BLOCKLEN - 1;
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700212 } else {
213 assert(deque->leftblock == deque->rightblock);
214 assert(deque->leftindex == deque->rightindex+1);
215 /* re-center instead of freeing a block */
216 deque->leftindex = CENTER + 1;
217 deque->rightindex = CENTER;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000218 }
219 }
220 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000221}
222
223PyDoc_STRVAR(pop_doc, "Remove and return the rightmost element.");
224
225static PyObject *
226deque_popleft(dequeobject *deque, PyObject *unused)
227{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000228 PyObject *item;
229 block *prevblock;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000230
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000231 if (Py_SIZE(deque) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000232 PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
233 return NULL;
234 }
235 assert(deque->leftblock != NULL);
236 item = deque->leftblock->data[deque->leftindex];
237 deque->leftindex++;
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100238 Py_SET_SIZE(deque, Py_SIZE(deque) - 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000239 deque->state++;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000241 if (deque->leftindex == BLOCKLEN) {
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700242 if (Py_SIZE(deque)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000243 assert(deque->leftblock != deque->rightblock);
244 prevblock = deque->leftblock->rightlink;
245 freeblock(deque->leftblock);
Raymond Hettinger82df9252013-07-07 01:43:42 -1000246 CHECK_NOT_END(prevblock);
247 MARK_END(prevblock->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000248 deque->leftblock = prevblock;
249 deque->leftindex = 0;
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700250 } else {
251 assert(deque->leftblock == deque->rightblock);
252 assert(deque->leftindex == deque->rightindex+1);
253 /* re-center instead of freeing a block */
254 deque->leftindex = CENTER + 1;
255 deque->rightindex = CENTER;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000256 }
257 }
258 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000259}
260
261PyDoc_STRVAR(popleft_doc, "Remove and return the leftmost element.");
262
Raymond Hettingerf30f5b92015-03-02 22:23:37 -0800263/* The deque's size limit is d.maxlen. The limit can be zero or positive.
264 * If there is no limit, then d.maxlen == -1.
265 *
Raymond Hettingera4b13d02015-10-15 08:05:31 -0700266 * After an item is added to a deque, we check to see if the size has
267 * grown past the limit. If it has, we get the size back down to the limit
268 * by popping an item off of the opposite end. The methods that can
269 * trigger this are append(), appendleft(), extend(), and extendleft().
Raymond Hettingerd96db092015-10-11 22:34:48 -0700270 *
271 * The macro to check whether a deque needs to be trimmed uses a single
272 * unsigned test that returns true whenever 0 <= maxlen < Py_SIZE(deque).
Raymond Hettingerf30f5b92015-03-02 22:23:37 -0800273 */
274
Raymond Hettingerd96db092015-10-11 22:34:48 -0700275#define NEEDS_TRIM(deque, maxlen) ((size_t)(maxlen) < (size_t)(Py_SIZE(deque)))
Raymond Hettingerf30f5b92015-03-02 22:23:37 -0800276
Raymond Hettinger66953f02018-07-10 04:17:40 -0700277static inline int
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800278deque_append_internal(dequeobject *deque, PyObject *item, Py_ssize_t maxlen)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000279{
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700280 if (deque->rightindex == BLOCKLEN - 1) {
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700281 block *b = newblock();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000282 if (b == NULL)
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800283 return -1;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000284 b->leftlink = deque->rightblock;
285 CHECK_END(deque->rightblock->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 deque->rightblock->rightlink = b;
287 deque->rightblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000288 MARK_END(b->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000289 deque->rightindex = -1;
290 }
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100291 Py_SET_SIZE(deque, Py_SIZE(deque) + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000292 deque->rightindex++;
293 deque->rightblock->data[deque->rightindex] = item;
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800294 if (NEEDS_TRIM(deque, maxlen)) {
Raymond Hettinger1286d142015-10-14 23:16:57 -0700295 PyObject *olditem = deque_popleft(deque, NULL);
296 Py_DECREF(olditem);
Raymond Hettinger0f43bb12015-10-20 00:03:33 -0700297 } else {
298 deque->state++;
Raymond Hettingerd96db092015-10-11 22:34:48 -0700299 }
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800300 return 0;
301}
302
303static PyObject *
304deque_append(dequeobject *deque, PyObject *item)
305{
306 Py_INCREF(item);
307 if (deque_append_internal(deque, item, deque->maxlen) < 0)
308 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000309 Py_RETURN_NONE;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000310}
311
312PyDoc_STRVAR(append_doc, "Add an element to the right side of the deque.");
313
Raymond Hettinger66953f02018-07-10 04:17:40 -0700314static inline int
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800315deque_appendleft_internal(dequeobject *deque, PyObject *item, Py_ssize_t maxlen)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000316{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000317 if (deque->leftindex == 0) {
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700318 block *b = newblock();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000319 if (b == NULL)
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800320 return -1;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000321 b->rightlink = deque->leftblock;
322 CHECK_END(deque->leftblock->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000323 deque->leftblock->leftlink = b;
324 deque->leftblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000325 MARK_END(b->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000326 deque->leftindex = BLOCKLEN;
327 }
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100328 Py_SET_SIZE(deque, Py_SIZE(deque) + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000329 deque->leftindex--;
330 deque->leftblock->data[deque->leftindex] = item;
Raymond Hettingerd96db092015-10-11 22:34:48 -0700331 if (NEEDS_TRIM(deque, deque->maxlen)) {
Raymond Hettinger1286d142015-10-14 23:16:57 -0700332 PyObject *olditem = deque_pop(deque, NULL);
333 Py_DECREF(olditem);
Raymond Hettinger0f43bb12015-10-20 00:03:33 -0700334 } else {
335 deque->state++;
Raymond Hettingerd96db092015-10-11 22:34:48 -0700336 }
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800337 return 0;
338}
339
340static PyObject *
341deque_appendleft(dequeobject *deque, PyObject *item)
342{
343 Py_INCREF(item);
344 if (deque_appendleft_internal(deque, item, deque->maxlen) < 0)
345 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000346 Py_RETURN_NONE;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000347}
348
349PyDoc_STRVAR(appendleft_doc, "Add an element to the left side of the deque.");
350
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700351static PyObject*
352finalize_iterator(PyObject *it)
353{
354 if (PyErr_Occurred()) {
355 if (PyErr_ExceptionMatches(PyExc_StopIteration))
356 PyErr_Clear();
357 else {
358 Py_DECREF(it);
359 return NULL;
360 }
361 }
362 Py_DECREF(it);
363 Py_RETURN_NONE;
364}
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000366/* Run an iterator to exhaustion. Shortcut for
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000367 the extend/extendleft methods when maxlen == 0. */
368static PyObject*
369consume_iterator(PyObject *it)
370{
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700371 PyObject *(*iternext)(PyObject *);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000372 PyObject *item;
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000373
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700374 iternext = *Py_TYPE(it)->tp_iternext;
375 while ((item = iternext(it)) != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000376 Py_DECREF(item);
377 }
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700378 return finalize_iterator(it);
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000379}
380
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000381static PyObject *
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000382deque_extend(dequeobject *deque, PyObject *iterable)
383{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000384 PyObject *it, *item;
Raymond Hettinger7a845522015-09-26 01:30:51 -0700385 PyObject *(*iternext)(PyObject *);
Raymond Hettinger6b1e1132015-10-11 09:43:50 -0700386 Py_ssize_t maxlen = deque->maxlen;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000388 /* Handle case where id(deque) == id(iterable) */
389 if ((PyObject *)deque == iterable) {
390 PyObject *result;
391 PyObject *s = PySequence_List(iterable);
392 if (s == NULL)
393 return NULL;
394 result = deque_extend(deque, s);
395 Py_DECREF(s);
396 return result;
397 }
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000398
Raymond Hettingerd79d5b12016-03-04 09:55:07 -0800399 it = PyObject_GetIter(iterable);
400 if (it == NULL)
401 return NULL;
402
403 if (maxlen == 0)
404 return consume_iterator(it);
405
Raymond Hettingerd9c116c2013-07-09 00:13:21 -0700406 /* Space saving heuristic. Start filling from the left */
407 if (Py_SIZE(deque) == 0) {
408 assert(deque->leftblock == deque->rightblock);
409 assert(deque->leftindex == deque->rightindex+1);
410 deque->leftindex = 1;
411 deque->rightindex = 0;
412 }
413
Raymond Hettinger7a845522015-09-26 01:30:51 -0700414 iternext = *Py_TYPE(it)->tp_iternext;
415 while ((item = iternext(it)) != NULL) {
Raymond Hettinger66953f02018-07-10 04:17:40 -0700416 if (deque_append_internal(deque, item, maxlen) == -1) {
417 Py_DECREF(item);
418 Py_DECREF(it);
419 return NULL;
Raymond Hettinger6b1e1132015-10-11 09:43:50 -0700420 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 }
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700422 return finalize_iterator(it);
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000423}
424
Tim Peters1065f752004-10-01 01:03:29 +0000425PyDoc_STRVAR(extend_doc,
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000426"Extend the right side of the deque with elements from the iterable");
427
428static PyObject *
429deque_extendleft(dequeobject *deque, PyObject *iterable)
430{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 PyObject *it, *item;
Raymond Hettinger7a845522015-09-26 01:30:51 -0700432 PyObject *(*iternext)(PyObject *);
Raymond Hettinger6b1e1132015-10-11 09:43:50 -0700433 Py_ssize_t maxlen = deque->maxlen;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435 /* Handle case where id(deque) == id(iterable) */
436 if ((PyObject *)deque == iterable) {
437 PyObject *result;
438 PyObject *s = PySequence_List(iterable);
439 if (s == NULL)
440 return NULL;
441 result = deque_extendleft(deque, s);
442 Py_DECREF(s);
443 return result;
444 }
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000445
Raymond Hettingerd79d5b12016-03-04 09:55:07 -0800446 it = PyObject_GetIter(iterable);
447 if (it == NULL)
448 return NULL;
449
450 if (maxlen == 0)
451 return consume_iterator(it);
452
Raymond Hettingerd9c116c2013-07-09 00:13:21 -0700453 /* Space saving heuristic. Start filling from the right */
454 if (Py_SIZE(deque) == 0) {
455 assert(deque->leftblock == deque->rightblock);
456 assert(deque->leftindex == deque->rightindex+1);
457 deque->leftindex = BLOCKLEN - 1;
458 deque->rightindex = BLOCKLEN - 2;
459 }
460
Raymond Hettinger7a845522015-09-26 01:30:51 -0700461 iternext = *Py_TYPE(it)->tp_iternext;
462 while ((item = iternext(it)) != NULL) {
Raymond Hettinger66953f02018-07-10 04:17:40 -0700463 if (deque_appendleft_internal(deque, item, maxlen) == -1) {
464 Py_DECREF(item);
465 Py_DECREF(it);
466 return NULL;
Raymond Hettinger6b1e1132015-10-11 09:43:50 -0700467 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000468 }
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700469 return finalize_iterator(it);
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000470}
471
Tim Peters1065f752004-10-01 01:03:29 +0000472PyDoc_STRVAR(extendleft_doc,
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000473"Extend the left side of the deque with elements from the iterable");
474
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000475static PyObject *
476deque_inplace_concat(dequeobject *deque, PyObject *other)
477{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 PyObject *result;
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000479
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000480 result = deque_extend(deque, other);
481 if (result == NULL)
482 return result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 Py_INCREF(deque);
Raymond Hettinger2b2b7532015-09-05 17:05:52 -0700484 Py_DECREF(result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 return (PyObject *)deque;
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000486}
487
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700488static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530489deque_copy(PyObject *deque, PyObject *Py_UNUSED(ignored))
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700490{
Oren Milman24bd50b2018-09-11 21:46:55 +0300491 PyObject *result;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700492 dequeobject *old_deque = (dequeobject *)deque;
Andy Lesterdffe4c02020-03-04 07:15:20 -0600493 if (Py_IS_TYPE(deque, &deque_type)) {
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700494 dequeobject *new_deque;
495 PyObject *rv;
496
497 new_deque = (dequeobject *)deque_new(&deque_type, (PyObject *)NULL, (PyObject *)NULL);
498 if (new_deque == NULL)
499 return NULL;
500 new_deque->maxlen = old_deque->maxlen;
501 /* Fast path for the deque_repeat() common case where len(deque) == 1 */
Raymond Hettinger0443ac22015-10-05 22:52:37 -0400502 if (Py_SIZE(deque) == 1) {
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700503 PyObject *item = old_deque->leftblock->data[old_deque->leftindex];
504 rv = deque_append(new_deque, item);
505 } else {
506 rv = deque_extend(new_deque, deque);
507 }
508 if (rv != NULL) {
509 Py_DECREF(rv);
510 return (PyObject *)new_deque;
511 }
512 Py_DECREF(new_deque);
513 return NULL;
514 }
515 if (old_deque->maxlen < 0)
Petr Viktorinffd97532020-02-11 17:46:57 +0100516 result = PyObject_CallOneArg((PyObject *)(Py_TYPE(deque)), deque);
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700517 else
Oren Milman24bd50b2018-09-11 21:46:55 +0300518 result = PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "Oi",
519 deque, old_deque->maxlen, NULL);
520 if (result != NULL && !PyObject_TypeCheck(result, &deque_type)) {
521 PyErr_Format(PyExc_TypeError,
522 "%.200s() must return a deque, not %.200s",
523 Py_TYPE(deque)->tp_name, Py_TYPE(result)->tp_name);
524 Py_DECREF(result);
525 return NULL;
526 }
527 return result;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700528}
529
530PyDoc_STRVAR(copy_doc, "Return a shallow copy of a deque.");
Raymond Hettinger41290a62015-03-31 08:12:23 -0700531
532static PyObject *
533deque_concat(dequeobject *deque, PyObject *other)
534{
Benjamin Peterson1a629212015-04-04 10:52:36 -0400535 PyObject *new_deque, *result;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700536 int rv;
537
538 rv = PyObject_IsInstance(other, (PyObject *)&deque_type);
539 if (rv <= 0) {
540 if (rv == 0) {
541 PyErr_Format(PyExc_TypeError,
542 "can only concatenate deque (not \"%.200s\") to deque",
Victor Stinnerdaa97562020-02-07 03:37:06 +0100543 Py_TYPE(other)->tp_name);
Raymond Hettinger41290a62015-03-31 08:12:23 -0700544 }
545 return NULL;
546 }
547
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530548 new_deque = deque_copy((PyObject *)deque, NULL);
Raymond Hettinger41290a62015-03-31 08:12:23 -0700549 if (new_deque == NULL)
550 return NULL;
Benjamin Peterson1a629212015-04-04 10:52:36 -0400551 result = deque_extend((dequeobject *)new_deque, other);
552 if (result == NULL) {
553 Py_DECREF(new_deque);
554 return NULL;
555 }
556 Py_DECREF(result);
557 return new_deque;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700558}
559
Serhiy Storchakaa5c42282018-05-31 07:34:34 +0300560static int
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700561deque_clear(dequeobject *deque)
562{
563 block *b;
564 block *prevblock;
565 block *leftblock;
566 Py_ssize_t leftindex;
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800567 Py_ssize_t n, m;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700568 PyObject *item;
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800569 PyObject **itemptr, **limit;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700570
Raymond Hettinger38031142015-09-29 22:45:05 -0700571 if (Py_SIZE(deque) == 0)
Serhiy Storchakaa5c42282018-05-31 07:34:34 +0300572 return 0;
Raymond Hettinger38031142015-09-29 22:45:05 -0700573
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700574 /* During the process of clearing a deque, decrefs can cause the
575 deque to mutate. To avoid fatal confusion, we have to make the
576 deque empty before clearing the blocks and never refer to
577 anything via deque->ref while clearing. (This is the same
578 technique used for clearing lists, sets, and dicts.)
579
580 Making the deque empty requires allocating a new empty block. In
581 the unlikely event that memory is full, we fall back to an
582 alternate method that doesn't require a new block. Repeating
583 pops in a while-loop is slower, possibly re-entrant (and a clever
584 adversary could cause it to never terminate).
585 */
586
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700587 b = newblock();
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700588 if (b == NULL) {
589 PyErr_Clear();
590 goto alternate_method;
591 }
592
593 /* Remember the old size, leftblock, and leftindex */
Raymond Hettinger6f86a332016-03-02 00:30:58 -0800594 n = Py_SIZE(deque);
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700595 leftblock = deque->leftblock;
596 leftindex = deque->leftindex;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700597
598 /* Set the deque to be empty using the newly allocated block */
599 MARK_END(b->leftlink);
600 MARK_END(b->rightlink);
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100601 Py_SET_SIZE(deque, 0);
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700602 deque->leftblock = b;
603 deque->rightblock = b;
604 deque->leftindex = CENTER + 1;
605 deque->rightindex = CENTER;
606 deque->state++;
607
608 /* Now the old size, leftblock, and leftindex are disconnected from
609 the empty deque and we can use them to decref the pointers.
610 */
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800611 m = (BLOCKLEN - leftindex > n) ? n : BLOCKLEN - leftindex;
Raymond Hettinger589106b2016-03-02 00:06:21 -0800612 itemptr = &leftblock->data[leftindex];
Raymond Hettinger6f86a332016-03-02 00:30:58 -0800613 limit = itemptr + m;
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800614 n -= m;
615 while (1) {
616 if (itemptr == limit) {
617 if (n == 0)
618 break;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700619 CHECK_NOT_END(leftblock->rightlink);
620 prevblock = leftblock;
621 leftblock = leftblock->rightlink;
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800622 m = (n > BLOCKLEN) ? BLOCKLEN : n;
Raymond Hettinger589106b2016-03-02 00:06:21 -0800623 itemptr = leftblock->data;
Raymond Hettinger6f86a332016-03-02 00:30:58 -0800624 limit = itemptr + m;
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800625 n -= m;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700626 freeblock(prevblock);
627 }
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800628 item = *(itemptr++);
629 Py_DECREF(item);
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700630 }
631 CHECK_END(leftblock->rightlink);
632 freeblock(leftblock);
Serhiy Storchakaa5c42282018-05-31 07:34:34 +0300633 return 0;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700634
635 alternate_method:
636 while (Py_SIZE(deque)) {
637 item = deque_pop(deque, NULL);
638 assert (item != NULL);
639 Py_DECREF(item);
640 }
Serhiy Storchakaa5c42282018-05-31 07:34:34 +0300641 return 0;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700642}
643
644static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530645deque_clearmethod(dequeobject *deque, PyObject *Py_UNUSED(ignored))
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700646{
647 deque_clear(deque);
648 Py_RETURN_NONE;
649}
650
651PyDoc_STRVAR(clear_doc, "Remove all elements from the deque.");
Raymond Hettinger41290a62015-03-31 08:12:23 -0700652
653static PyObject *
Raymond Hettinger41290a62015-03-31 08:12:23 -0700654deque_inplace_repeat(dequeobject *deque, Py_ssize_t n)
655{
Raymond Hettingerc22eee62015-09-26 02:14:50 -0700656 Py_ssize_t i, m, size;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700657 PyObject *seq;
658 PyObject *rv;
659
660 size = Py_SIZE(deque);
661 if (size == 0 || n == 1) {
662 Py_INCREF(deque);
663 return (PyObject *)deque;
664 }
665
666 if (n <= 0) {
667 deque_clear(deque);
668 Py_INCREF(deque);
669 return (PyObject *)deque;
670 }
671
Raymond Hettinger41290a62015-03-31 08:12:23 -0700672 if (size == 1) {
673 /* common case, repeating a single element */
674 PyObject *item = deque->leftblock->data[deque->leftindex];
675
Raymond Hettingera7f630092015-10-10 23:56:02 -0400676 if (deque->maxlen >= 0 && n > deque->maxlen)
Raymond Hettinger41290a62015-03-31 08:12:23 -0700677 n = deque->maxlen;
678
Raymond Hettinger67c78b52015-09-12 11:00:20 -0400679 deque->state++;
Raymond Hettingerad262252015-09-14 01:03:04 -0400680 for (i = 0 ; i < n-1 ; ) {
Raymond Hettinger67c78b52015-09-12 11:00:20 -0400681 if (deque->rightindex == BLOCKLEN - 1) {
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700682 block *b = newblock();
Raymond Hettinger67c78b52015-09-12 11:00:20 -0400683 if (b == NULL) {
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100684 Py_SET_SIZE(deque, Py_SIZE(deque) + i);
Raymond Hettinger67c78b52015-09-12 11:00:20 -0400685 return NULL;
686 }
687 b->leftlink = deque->rightblock;
688 CHECK_END(deque->rightblock->rightlink);
689 deque->rightblock->rightlink = b;
690 deque->rightblock = b;
691 MARK_END(b->rightlink);
692 deque->rightindex = -1;
693 }
Raymond Hettingerc22eee62015-09-26 02:14:50 -0700694 m = n - 1 - i;
695 if (m > BLOCKLEN - 1 - deque->rightindex)
696 m = BLOCKLEN - 1 - deque->rightindex;
697 i += m;
698 while (m--) {
Raymond Hettingerad262252015-09-14 01:03:04 -0400699 deque->rightindex++;
700 Py_INCREF(item);
701 deque->rightblock->data[deque->rightindex] = item;
702 }
Raymond Hettinger41290a62015-03-31 08:12:23 -0700703 }
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100704 Py_SET_SIZE(deque, Py_SIZE(deque) + i);
Raymond Hettinger41290a62015-03-31 08:12:23 -0700705 Py_INCREF(deque);
706 return (PyObject *)deque;
707 }
708
Raymond Hettinger20151f52015-10-16 22:47:29 -0700709 if ((size_t)size > PY_SSIZE_T_MAX / (size_t)n) {
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400710 return PyErr_NoMemory();
711 }
712
Raymond Hettinger41290a62015-03-31 08:12:23 -0700713 seq = PySequence_List((PyObject *)deque);
714 if (seq == NULL)
715 return seq;
716
Louie Lu357bad72017-02-24 11:59:49 +0800717 /* Reduce the number of repetitions when maxlen would be exceeded */
718 if (deque->maxlen >= 0 && n * size > deque->maxlen)
719 n = (deque->maxlen + size - 1) / size;
720
Raymond Hettinger41290a62015-03-31 08:12:23 -0700721 for (i = 0 ; i < n-1 ; i++) {
722 rv = deque_extend(deque, seq);
723 if (rv == NULL) {
724 Py_DECREF(seq);
725 return NULL;
726 }
727 Py_DECREF(rv);
728 }
729 Py_INCREF(deque);
730 Py_DECREF(seq);
731 return (PyObject *)deque;
732}
733
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400734static PyObject *
735deque_repeat(dequeobject *deque, Py_ssize_t n)
736{
737 dequeobject *new_deque;
Raymond Hettinger95e2cc52015-09-13 02:41:18 -0400738 PyObject *rv;
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400739
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530740 new_deque = (dequeobject *)deque_copy((PyObject *) deque, NULL);
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400741 if (new_deque == NULL)
742 return NULL;
Raymond Hettinger95e2cc52015-09-13 02:41:18 -0400743 rv = deque_inplace_repeat(new_deque, n);
744 Py_DECREF(new_deque);
745 return rv;
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400746}
747
Raymond Hettinger54023152014-04-23 00:58:48 -0700748/* The rotate() method is part of the public API and is used internally
749as a primitive for other methods.
750
751Rotation by 1 or -1 is a common case, so any optimizations for high
752volume rotations should take care not to penalize the common case.
753
754Conceptually, a rotate by one is equivalent to a pop on one side and an
755append on the other. However, a pop/append pair is unnecessarily slow
Martin Panterd2ad5712015-11-02 04:20:33 +0000756because it requires an incref/decref pair for an object located randomly
Raymond Hettinger54023152014-04-23 00:58:48 -0700757in memory. It is better to just move the object pointer from one block
758to the next without changing the reference count.
759
760When moving batches of pointers, it is tempting to use memcpy() but that
761proved to be slower than a simple loop for a variety of reasons.
762Memcpy() cannot know in advance that we're copying pointers instead of
763bytes, that the source and destination are pointer aligned and
764non-overlapping, that moving just one pointer is a common case, that we
765never need to move more than BLOCKLEN pointers, and that at least one
766pointer is always moved.
767
768For high volume rotations, newblock() and freeblock() are never called
769more than once. Previously emptied blocks are immediately reused as a
770destination block. If a block is left-over at the end, it is freed.
771*/
772
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000773static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000774_deque_rotate(dequeobject *deque, Py_ssize_t n)
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000775{
Raymond Hettinger3959af92013-07-13 02:34:08 -0700776 block *b = NULL;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700777 block *leftblock = deque->leftblock;
778 block *rightblock = deque->rightblock;
779 Py_ssize_t leftindex = deque->leftindex;
780 Py_ssize_t rightindex = deque->rightindex;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000781 Py_ssize_t len=Py_SIZE(deque), halflen=len>>1;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700782 int rv = -1;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000783
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800784 if (len <= 1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000785 return 0;
786 if (n > halflen || n < -halflen) {
787 n %= len;
788 if (n > halflen)
789 n -= len;
790 else if (n < -halflen)
791 n += len;
792 }
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500793 assert(len > 1);
Raymond Hettingera4409c12013-02-04 00:08:12 -0500794 assert(-halflen <= n && n <= halflen);
Raymond Hettinger231ee4d2013-02-02 11:24:43 -0800795
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800796 deque->state++;
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500797 while (n > 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700798 if (leftindex == 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700799 if (b == NULL) {
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700800 b = newblock();
Raymond Hettinger3959af92013-07-13 02:34:08 -0700801 if (b == NULL)
802 goto done;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700803 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000804 b->rightlink = leftblock;
805 CHECK_END(leftblock->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700806 leftblock->leftlink = b;
807 leftblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000808 MARK_END(b->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700809 leftindex = BLOCKLEN;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700810 b = NULL;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800811 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700812 assert(leftindex > 0);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700813 {
814 PyObject **src, **dest;
815 Py_ssize_t m = n;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800816
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700817 if (m > rightindex + 1)
818 m = rightindex + 1;
819 if (m > leftindex)
820 m = leftindex;
821 assert (m > 0 && m <= len);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700822 rightindex -= m;
823 leftindex -= m;
Raymond Hettinger0e259f12015-02-01 22:53:41 -0800824 src = &rightblock->data[rightindex + 1];
825 dest = &leftblock->data[leftindex];
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700826 n -= m;
Raymond Hettinger840533b2013-07-13 17:03:58 -0700827 do {
Raymond Hettinger0e259f12015-02-01 22:53:41 -0800828 *(dest++) = *(src++);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700829 } while (--m);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700830 }
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -0700831 if (rightindex < 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700832 assert(leftblock != rightblock);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700833 assert(b == NULL);
Raymond Hettinger3959af92013-07-13 02:34:08 -0700834 b = rightblock;
Raymond Hettingerb97cc492013-07-21 01:51:07 -0700835 CHECK_NOT_END(rightblock->leftlink);
836 rightblock = rightblock->leftlink;
837 MARK_END(rightblock->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700838 rightindex = BLOCKLEN - 1;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800839 }
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800840 }
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500841 while (n < 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700842 if (rightindex == BLOCKLEN - 1) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700843 if (b == NULL) {
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700844 b = newblock();
Raymond Hettinger3959af92013-07-13 02:34:08 -0700845 if (b == NULL)
846 goto done;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700847 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000848 b->leftlink = rightblock;
849 CHECK_END(rightblock->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700850 rightblock->rightlink = b;
851 rightblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000852 MARK_END(b->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700853 rightindex = -1;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700854 b = NULL;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800855 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700856 assert (rightindex < BLOCKLEN - 1);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700857 {
858 PyObject **src, **dest;
859 Py_ssize_t m = -n;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800860
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700861 if (m > BLOCKLEN - leftindex)
862 m = BLOCKLEN - leftindex;
863 if (m > BLOCKLEN - 1 - rightindex)
864 m = BLOCKLEN - 1 - rightindex;
865 assert (m > 0 && m <= len);
866 src = &leftblock->data[leftindex];
867 dest = &rightblock->data[rightindex + 1];
868 leftindex += m;
869 rightindex += m;
870 n += m;
Raymond Hettinger840533b2013-07-13 17:03:58 -0700871 do {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700872 *(dest++) = *(src++);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700873 } while (--m);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700874 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700875 if (leftindex == BLOCKLEN) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700876 assert(leftblock != rightblock);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700877 assert(b == NULL);
Raymond Hettinger3959af92013-07-13 02:34:08 -0700878 b = leftblock;
Raymond Hettingerb97cc492013-07-21 01:51:07 -0700879 CHECK_NOT_END(leftblock->rightlink);
880 leftblock = leftblock->rightlink;
881 MARK_END(leftblock->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700882 leftindex = 0;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800883 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000884 }
Raymond Hettinger3959af92013-07-13 02:34:08 -0700885 rv = 0;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700886done:
Raymond Hettinger3959af92013-07-13 02:34:08 -0700887 if (b != NULL)
888 freeblock(b);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700889 deque->leftblock = leftblock;
890 deque->rightblock = rightblock;
891 deque->leftindex = leftindex;
892 deque->rightindex = rightindex;
893
894 return rv;
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000895}
896
897static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +0200898deque_rotate(dequeobject *deque, PyObject *const *args, Py_ssize_t nargs)
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000899{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000900 Py_ssize_t n=1;
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000901
Dennis Sweeney448801d2021-03-16 00:02:25 -0400902 if (!_PyArg_CheckPositional("deque.rotate", nargs, 0, 1)) {
Victor Stinnerdd407d52017-02-06 16:06:49 +0100903 return NULL;
904 }
Dennis Sweeney448801d2021-03-16 00:02:25 -0400905 if (nargs) {
906 PyObject *index = _PyNumber_Index(args[0]);
907 if (index == NULL) {
908 return NULL;
909 }
910 n = PyLong_AsSsize_t(index);
911 Py_DECREF(index);
912 if (n == -1 && PyErr_Occurred()) {
913 return NULL;
914 }
915 }
Victor Stinnerdd407d52017-02-06 16:06:49 +0100916
Raymond Hettinger6921c132015-03-21 02:03:40 -0700917 if (!_deque_rotate(deque, n))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 Py_RETURN_NONE;
919 return NULL;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000920}
921
Tim Peters1065f752004-10-01 01:03:29 +0000922PyDoc_STRVAR(rotate_doc,
Raymond Hettingeree33b272004-02-08 04:05:26 +0000923"Rotate the deque n steps to the right (default n=1). If n is negative, rotates left.");
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000924
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000925static PyObject *
926deque_reverse(dequeobject *deque, PyObject *unused)
927{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 block *leftblock = deque->leftblock;
929 block *rightblock = deque->rightblock;
930 Py_ssize_t leftindex = deque->leftindex;
931 Py_ssize_t rightindex = deque->rightindex;
Raymond Hettingercfe5b6c2015-07-20 00:25:50 -0400932 Py_ssize_t n = Py_SIZE(deque) >> 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933 PyObject *tmp;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000934
Raymond Hettingere1b02872017-09-04 16:07:06 -0700935 while (--n >= 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 /* Validate that pointers haven't met in the middle */
937 assert(leftblock != rightblock || leftindex < rightindex);
Raymond Hettinger82df9252013-07-07 01:43:42 -1000938 CHECK_NOT_END(leftblock);
939 CHECK_NOT_END(rightblock);
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 /* Swap */
942 tmp = leftblock->data[leftindex];
943 leftblock->data[leftindex] = rightblock->data[rightindex];
944 rightblock->data[rightindex] = tmp;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000945
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 /* Advance left block/index pair */
947 leftindex++;
948 if (leftindex == BLOCKLEN) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 leftblock = leftblock->rightlink;
950 leftindex = 0;
951 }
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 /* Step backwards with the right block/index pair */
954 rightindex--;
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -0700955 if (rightindex < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000956 rightblock = rightblock->leftlink;
957 rightindex = BLOCKLEN - 1;
958 }
959 }
960 Py_RETURN_NONE;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000961}
962
963PyDoc_STRVAR(reverse_doc,
964"D.reverse() -- reverse *IN PLACE*");
965
Raymond Hettinger44459de2010-04-03 23:20:46 +0000966static PyObject *
967deque_count(dequeobject *deque, PyObject *v)
968{
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000969 block *b = deque->leftblock;
970 Py_ssize_t index = deque->leftindex;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000971 Py_ssize_t n = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 Py_ssize_t count = 0;
Raymond Hettingerf9d9c792015-03-02 22:47:46 -0800973 size_t start_state = deque->state;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 PyObject *item;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000975 int cmp;
Raymond Hettinger44459de2010-04-03 23:20:46 +0000976
Raymond Hettingere1b02872017-09-04 16:07:06 -0700977 while (--n >= 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000978 CHECK_NOT_END(b);
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000979 item = b->data[index];
sweeneydec6dedde2020-02-09 03:16:43 -0500980 Py_INCREF(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000981 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
sweeneydec6dedde2020-02-09 03:16:43 -0500982 Py_DECREF(item);
Raymond Hettinger2b0d6462015-09-23 19:15:44 -0700983 if (cmp < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000984 return NULL;
Raymond Hettinger2b0d6462015-09-23 19:15:44 -0700985 count += cmp;
Raymond Hettinger44459de2010-04-03 23:20:46 +0000986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 if (start_state != deque->state) {
988 PyErr_SetString(PyExc_RuntimeError,
989 "deque mutated during iteration");
990 return NULL;
991 }
Raymond Hettinger44459de2010-04-03 23:20:46 +0000992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 /* Advance left block/index pair */
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000994 index++;
995 if (index == BLOCKLEN) {
996 b = b->rightlink;
997 index = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998 }
999 }
1000 return PyLong_FromSsize_t(count);
Raymond Hettinger44459de2010-04-03 23:20:46 +00001001}
1002
1003PyDoc_STRVAR(count_doc,
1004"D.count(value) -> integer -- return number of occurrences of value");
1005
Raymond Hettinger39dadf72015-03-20 16:38:56 -07001006static int
1007deque_contains(dequeobject *deque, PyObject *v)
1008{
1009 block *b = deque->leftblock;
1010 Py_ssize_t index = deque->leftindex;
1011 Py_ssize_t n = Py_SIZE(deque);
Raymond Hettinger39dadf72015-03-20 16:38:56 -07001012 size_t start_state = deque->state;
1013 PyObject *item;
1014 int cmp;
1015
Raymond Hettingere1b02872017-09-04 16:07:06 -07001016 while (--n >= 0) {
Raymond Hettinger39dadf72015-03-20 16:38:56 -07001017 CHECK_NOT_END(b);
1018 item = b->data[index];
sweeneydec6dedde2020-02-09 03:16:43 -05001019 Py_INCREF(item);
Raymond Hettinger39dadf72015-03-20 16:38:56 -07001020 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
sweeneydec6dedde2020-02-09 03:16:43 -05001021 Py_DECREF(item);
Raymond Hettinger39dadf72015-03-20 16:38:56 -07001022 if (cmp) {
1023 return cmp;
1024 }
1025 if (start_state != deque->state) {
1026 PyErr_SetString(PyExc_RuntimeError,
1027 "deque mutated during iteration");
1028 return -1;
1029 }
1030 index++;
1031 if (index == BLOCKLEN) {
1032 b = b->rightlink;
1033 index = 0;
1034 }
1035 }
1036 return 0;
1037}
1038
Martin v. Löwis18e16552006-02-15 17:27:45 +00001039static Py_ssize_t
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001040deque_len(dequeobject *deque)
1041{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001042 return Py_SIZE(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001043}
1044
Raymond Hettinger4aec61e2005-03-18 21:20:23 +00001045static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02001046deque_index(dequeobject *deque, PyObject *const *args, Py_ssize_t nargs)
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001047{
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001048 Py_ssize_t i, n, start=0, stop=Py_SIZE(deque);
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001049 PyObject *v, *item;
1050 block *b = deque->leftblock;
1051 Py_ssize_t index = deque->leftindex;
1052 size_t start_state = deque->state;
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001053 int cmp;
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001054
Victor Stinnerdd407d52017-02-06 16:06:49 +01001055 if (!_PyArg_ParseStack(args, nargs, "O|O&O&:index", &v,
Serhiy Storchakad4edfc92017-03-30 18:29:23 +03001056 _PyEval_SliceIndexNotNone, &start,
1057 _PyEval_SliceIndexNotNone, &stop)) {
Victor Stinnerdd407d52017-02-06 16:06:49 +01001058 return NULL;
1059 }
1060
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001061 if (start < 0) {
1062 start += Py_SIZE(deque);
1063 if (start < 0)
1064 start = 0;
1065 }
1066 if (stop < 0) {
1067 stop += Py_SIZE(deque);
1068 if (stop < 0)
1069 stop = 0;
1070 }
Raymond Hettinger87674ec2015-08-26 08:08:38 -07001071 if (stop > Py_SIZE(deque))
1072 stop = Py_SIZE(deque);
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001073 if (start > stop)
1074 start = stop;
1075 assert(0 <= start && start <= stop && stop <= Py_SIZE(deque));
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001076
Raymond Hettingerb46ad542018-09-21 01:46:41 -07001077 for (i=0 ; i < start - BLOCKLEN ; i += BLOCKLEN) {
1078 b = b->rightlink;
1079 }
1080 for ( ; i < start ; i++) {
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001081 index++;
1082 if (index == BLOCKLEN) {
1083 b = b->rightlink;
1084 index = 0;
1085 }
1086 }
1087
Raymond Hettingere1b02872017-09-04 16:07:06 -07001088 n = stop - i;
1089 while (--n >= 0) {
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001090 CHECK_NOT_END(b);
1091 item = b->data[index];
1092 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
1093 if (cmp > 0)
Raymond Hettingere1b02872017-09-04 16:07:06 -07001094 return PyLong_FromSsize_t(stop - n - 1);
Raymond Hettingerdf8f5b52015-11-02 07:27:40 -05001095 if (cmp < 0)
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001096 return NULL;
1097 if (start_state != deque->state) {
1098 PyErr_SetString(PyExc_RuntimeError,
1099 "deque mutated during iteration");
1100 return NULL;
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001101 }
1102 index++;
1103 if (index == BLOCKLEN) {
1104 b = b->rightlink;
1105 index = 0;
1106 }
1107 }
1108 PyErr_Format(PyExc_ValueError, "%R is not in deque", v);
1109 return NULL;
1110}
1111
1112PyDoc_STRVAR(index_doc,
1113"D.index(value, [start, [stop]]) -> integer -- return first index of value.\n"
1114"Raises ValueError if the value is not present.");
1115
Raymond Hettinger551350a2015-03-24 00:19:53 -07001116/* insert(), remove(), and delitem() are implemented in terms of
1117 rotate() for simplicity and reasonable performance near the end
1118 points. If for some reason these methods become popular, it is not
1119 hard to re-implement this using direct data movement (similar to
1120 the code used in list slice assignments) and achieve a performance
Raymond Hettingerfef9c1b2015-03-24 21:12:57 -07001121 boost (by moving each pointer only once instead of twice).
Raymond Hettinger551350a2015-03-24 00:19:53 -07001122*/
1123
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001124static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02001125deque_insert(dequeobject *deque, PyObject *const *args, Py_ssize_t nargs)
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001126{
1127 Py_ssize_t index;
1128 Py_ssize_t n = Py_SIZE(deque);
1129 PyObject *value;
1130 PyObject *rv;
1131
Victor Stinnerdd407d52017-02-06 16:06:49 +01001132 if (!_PyArg_ParseStack(args, nargs, "nO:insert", &index, &value)) {
1133 return NULL;
1134 }
1135
Raymond Hettinger37434322016-01-26 21:44:16 -08001136 if (deque->maxlen == Py_SIZE(deque)) {
Raymond Hettingera6389712016-02-01 21:21:19 -08001137 PyErr_SetString(PyExc_IndexError, "deque already at its maximum size");
1138 return NULL;
Raymond Hettinger37434322016-01-26 21:44:16 -08001139 }
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001140 if (index >= n)
1141 return deque_append(deque, value);
1142 if (index <= -n || index == 0)
1143 return deque_appendleft(deque, value);
1144 if (_deque_rotate(deque, -index))
1145 return NULL;
1146 if (index < 0)
1147 rv = deque_append(deque, value);
1148 else
1149 rv = deque_appendleft(deque, value);
1150 if (rv == NULL)
1151 return NULL;
1152 Py_DECREF(rv);
1153 if (_deque_rotate(deque, index))
1154 return NULL;
1155 Py_RETURN_NONE;
1156}
1157
1158PyDoc_STRVAR(insert_doc,
1159"D.insert(index, object) -- insert object before index");
1160
Raymond Hettinger4aec61e2005-03-18 21:20:23 +00001161PyDoc_STRVAR(remove_doc,
1162"D.remove(value) -- remove first occurrence of value.");
1163
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001164static int
1165valid_index(Py_ssize_t i, Py_ssize_t limit)
1166{
Raymond Hettinger12f896c2015-07-31 12:03:20 -07001167 /* The cast to size_t lets us use just a single comparison
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001168 to check whether i is in the range: 0 <= i < limit */
1169 return (size_t) i < (size_t) limit;
1170}
1171
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001172static PyObject *
Benjamin Petersond6313712008-07-31 16:23:04 +00001173deque_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001174{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001175 block *b;
1176 PyObject *item;
1177 Py_ssize_t n, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001178
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001179 if (!valid_index(i, Py_SIZE(deque))) {
1180 PyErr_SetString(PyExc_IndexError, "deque index out of range");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001181 return NULL;
1182 }
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001184 if (i == 0) {
1185 i = deque->leftindex;
1186 b = deque->leftblock;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001187 } else if (i == Py_SIZE(deque) - 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 i = deque->rightindex;
1189 b = deque->rightblock;
1190 } else {
1191 i += deque->leftindex;
Raymond Hettingerc2083082015-02-28 23:29:16 -08001192 n = (Py_ssize_t)((size_t) i / BLOCKLEN);
1193 i = (Py_ssize_t)((size_t) i % BLOCKLEN);
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001194 if (index < (Py_SIZE(deque) >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 b = deque->leftblock;
Raymond Hettingere1b02872017-09-04 16:07:06 -07001196 while (--n >= 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001197 b = b->rightlink;
1198 } else {
Raymond Hettinger63d1ff22015-02-28 07:41:30 -08001199 n = (Py_ssize_t)(
Raymond Hettingerc2083082015-02-28 23:29:16 -08001200 ((size_t)(deque->leftindex + Py_SIZE(deque) - 1))
Raymond Hettinger63d1ff22015-02-28 07:41:30 -08001201 / BLOCKLEN - n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001202 b = deque->rightblock;
Raymond Hettingere1b02872017-09-04 16:07:06 -07001203 while (--n >= 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 b = b->leftlink;
1205 }
1206 }
1207 item = b->data[i];
1208 Py_INCREF(item);
1209 return item;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001210}
1211
1212static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001213deque_del_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001214{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001215 PyObject *item;
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001216 int rv;
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001217
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001218 assert (i >= 0 && i < Py_SIZE(deque));
Raymond Hettinger6921c132015-03-21 02:03:40 -07001219 if (_deque_rotate(deque, -i))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001220 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001221 item = deque_popleft(deque, NULL);
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001222 rv = _deque_rotate(deque, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001223 assert (item != NULL);
1224 Py_DECREF(item);
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001225 return rv;
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001226}
1227
Raymond Hettinger6b1ac802020-12-23 11:45:06 -08001228static PyObject *
1229deque_remove(dequeobject *deque, PyObject *value)
1230{
1231 PyObject *item;
1232 block *b = deque->leftblock;
1233 Py_ssize_t i, n = Py_SIZE(deque), index = deque->leftindex;
1234 size_t start_state = deque->state;
1235 int cmp, rv;
1236
1237 for (i = 0 ; i < n; i++) {
1238 item = b->data[index];
1239 Py_INCREF(item);
1240 cmp = PyObject_RichCompareBool(item, value, Py_EQ);
1241 Py_DECREF(item);
1242 if (cmp < 0) {
1243 return NULL;
1244 }
1245 if (start_state != deque->state) {
1246 PyErr_SetString(PyExc_IndexError,
1247 "deque mutated during iteration");
1248 return NULL;
1249 }
1250 if (cmp > 0) {
1251 break;
1252 }
1253 index++;
1254 if (index == BLOCKLEN) {
1255 b = b->rightlink;
1256 index = 0;
1257 }
1258 }
1259 if (i == n) {
1260 PyErr_Format(PyExc_ValueError, "%R is not in deque", value);
1261 return NULL;
1262 }
1263 rv = deque_del_item(deque, i);
1264 if (rv == -1) {
1265 return NULL;
1266 }
1267 Py_RETURN_NONE;
1268}
1269
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001270static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001271deque_ass_item(dequeobject *deque, Py_ssize_t i, PyObject *v)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001272{
Raymond Hettinger38418662016-02-08 20:34:49 -08001273 PyObject *old_value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001274 block *b;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001275 Py_ssize_t n, len=Py_SIZE(deque), halflen=(len+1)>>1, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001276
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001277 if (!valid_index(i, len)) {
1278 PyErr_SetString(PyExc_IndexError, "deque index out of range");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001279 return -1;
1280 }
1281 if (v == NULL)
1282 return deque_del_item(deque, i);
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001284 i += deque->leftindex;
Raymond Hettingerc2083082015-02-28 23:29:16 -08001285 n = (Py_ssize_t)((size_t) i / BLOCKLEN);
1286 i = (Py_ssize_t)((size_t) i % BLOCKLEN);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001287 if (index <= halflen) {
1288 b = deque->leftblock;
Raymond Hettingere1b02872017-09-04 16:07:06 -07001289 while (--n >= 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001290 b = b->rightlink;
1291 } else {
Raymond Hettingera473b9d2015-02-28 17:49:47 -08001292 n = (Py_ssize_t)(
Raymond Hettingerc2083082015-02-28 23:29:16 -08001293 ((size_t)(deque->leftindex + Py_SIZE(deque) - 1))
Raymond Hettingera473b9d2015-02-28 17:49:47 -08001294 / BLOCKLEN - n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001295 b = deque->rightblock;
Raymond Hettingere1b02872017-09-04 16:07:06 -07001296 while (--n >= 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001297 b = b->leftlink;
1298 }
1299 Py_INCREF(v);
Raymond Hettinger38418662016-02-08 20:34:49 -08001300 old_value = b->data[i];
1301 b->data[i] = v;
1302 Py_DECREF(old_value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001303 return 0;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001304}
1305
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001306static void
1307deque_dealloc(dequeobject *deque)
1308{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001309 PyObject_GC_UnTrack(deque);
1310 if (deque->weakreflist != NULL)
1311 PyObject_ClearWeakRefs((PyObject *) deque);
1312 if (deque->leftblock != NULL) {
1313 deque_clear(deque);
1314 assert(deque->leftblock != NULL);
1315 freeblock(deque->leftblock);
1316 }
1317 deque->leftblock = NULL;
1318 deque->rightblock = NULL;
1319 Py_TYPE(deque)->tp_free(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001320}
1321
1322static int
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001323deque_traverse(dequeobject *deque, visitproc visit, void *arg)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001324{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001325 block *b;
1326 PyObject *item;
1327 Py_ssize_t index;
1328 Py_ssize_t indexlo = deque->leftindex;
Raymond Hettinger1286d142015-10-14 23:16:57 -07001329 Py_ssize_t indexhigh;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001330
Raymond Hettinger5bfa8672013-07-06 11:58:09 -10001331 for (b = deque->leftblock; b != deque->rightblock; b = b->rightlink) {
1332 for (index = indexlo; index < BLOCKLEN ; index++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001333 item = b->data[index];
1334 Py_VISIT(item);
1335 }
1336 indexlo = 0;
1337 }
Raymond Hettinger1286d142015-10-14 23:16:57 -07001338 indexhigh = deque->rightindex;
1339 for (index = indexlo; index <= indexhigh; index++) {
Raymond Hettinger5bfa8672013-07-06 11:58:09 -10001340 item = b->data[index];
1341 Py_VISIT(item);
1342 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001343 return 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001344}
1345
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001346static PyObject *
Serhiy Storchaka81524022018-11-27 13:05:02 +02001347deque_reduce(dequeobject *deque, PyObject *Py_UNUSED(ignored))
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001348{
Serhiy Storchakaa0d416f2016-03-06 08:55:21 +02001349 PyObject *dict, *it;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001350 _Py_IDENTIFIER(__dict__);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001351
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001352 if (_PyObject_LookupAttrId((PyObject *)deque, &PyId___dict__, &dict) < 0) {
1353 return NULL;
1354 }
Serhiy Storchakaa0d416f2016-03-06 08:55:21 +02001355 if (dict == NULL) {
Serhiy Storchakaa0d416f2016-03-06 08:55:21 +02001356 dict = Py_None;
1357 Py_INCREF(dict);
1358 }
1359
1360 it = PyObject_GetIter((PyObject *)deque);
1361 if (it == NULL) {
1362 Py_DECREF(dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001363 return NULL;
1364 }
Serhiy Storchakaa0d416f2016-03-06 08:55:21 +02001365
1366 if (deque->maxlen < 0) {
1367 return Py_BuildValue("O()NN", Py_TYPE(deque), dict, it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001368 }
Serhiy Storchakaa0d416f2016-03-06 08:55:21 +02001369 else {
1370 return Py_BuildValue("O(()n)NN", Py_TYPE(deque), deque->maxlen, dict, it);
1371 }
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001372}
1373
1374PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
1375
1376static PyObject *
1377deque_repr(PyObject *deque)
1378{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001379 PyObject *aslist, *result;
1380 int i;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001382 i = Py_ReprEnter(deque);
1383 if (i != 0) {
1384 if (i < 0)
1385 return NULL;
1386 return PyUnicode_FromString("[...]");
1387 }
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001389 aslist = PySequence_List(deque);
1390 if (aslist == NULL) {
1391 Py_ReprLeave(deque);
1392 return NULL;
1393 }
Raymond Hettingera7f630092015-10-10 23:56:02 -04001394 if (((dequeobject *)deque)->maxlen >= 0)
Serhiy Storchakab3a77962017-09-21 14:24:13 +03001395 result = PyUnicode_FromFormat("%s(%R, maxlen=%zd)",
1396 _PyType_Name(Py_TYPE(deque)), aslist,
1397 ((dequeobject *)deque)->maxlen);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001398 else
Serhiy Storchakab3a77962017-09-21 14:24:13 +03001399 result = PyUnicode_FromFormat("%s(%R)",
1400 _PyType_Name(Py_TYPE(deque)), aslist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001401 Py_ReprLeave(deque);
Raymond Hettinger2b2b7532015-09-05 17:05:52 -07001402 Py_DECREF(aslist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001403 return result;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001404}
1405
Raymond Hettinger738ec902004-02-29 02:15:56 +00001406static PyObject *
1407deque_richcompare(PyObject *v, PyObject *w, int op)
1408{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001409 PyObject *it1=NULL, *it2=NULL, *x, *y;
1410 Py_ssize_t vs, ws;
1411 int b, cmp=-1;
Raymond Hettinger738ec902004-02-29 02:15:56 +00001412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001413 if (!PyObject_TypeCheck(v, &deque_type) ||
1414 !PyObject_TypeCheck(w, &deque_type)) {
Brian Curtindfc80e32011-08-10 20:28:54 -05001415 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001416 }
Raymond Hettinger738ec902004-02-29 02:15:56 +00001417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001418 /* Shortcuts */
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001419 vs = Py_SIZE((dequeobject *)v);
1420 ws = Py_SIZE((dequeobject *)w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001421 if (op == Py_EQ) {
1422 if (v == w)
1423 Py_RETURN_TRUE;
1424 if (vs != ws)
1425 Py_RETURN_FALSE;
1426 }
1427 if (op == Py_NE) {
1428 if (v == w)
1429 Py_RETURN_FALSE;
1430 if (vs != ws)
1431 Py_RETURN_TRUE;
1432 }
Raymond Hettinger738ec902004-02-29 02:15:56 +00001433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001434 /* Search for the first index where items are different */
1435 it1 = PyObject_GetIter(v);
1436 if (it1 == NULL)
1437 goto done;
1438 it2 = PyObject_GetIter(w);
1439 if (it2 == NULL)
1440 goto done;
1441 for (;;) {
1442 x = PyIter_Next(it1);
1443 if (x == NULL && PyErr_Occurred())
1444 goto done;
1445 y = PyIter_Next(it2);
1446 if (x == NULL || y == NULL)
1447 break;
1448 b = PyObject_RichCompareBool(x, y, Py_EQ);
1449 if (b == 0) {
1450 cmp = PyObject_RichCompareBool(x, y, op);
1451 Py_DECREF(x);
1452 Py_DECREF(y);
1453 goto done;
1454 }
1455 Py_DECREF(x);
1456 Py_DECREF(y);
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -07001457 if (b < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001458 goto done;
1459 }
1460 /* We reached the end of one deque or both */
1461 Py_XDECREF(x);
1462 Py_XDECREF(y);
1463 if (PyErr_Occurred())
1464 goto done;
1465 switch (op) {
1466 case Py_LT: cmp = y != NULL; break; /* if w was longer */
1467 case Py_LE: cmp = x == NULL; break; /* if v was not longer */
1468 case Py_EQ: cmp = x == y; break; /* if we reached the end of both */
1469 case Py_NE: cmp = x != y; break; /* if one deque continues */
1470 case Py_GT: cmp = x != NULL; break; /* if v was longer */
1471 case Py_GE: cmp = y == NULL; break; /* if w was not longer */
1472 }
Tim Peters1065f752004-10-01 01:03:29 +00001473
Raymond Hettinger738ec902004-02-29 02:15:56 +00001474done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001475 Py_XDECREF(it1);
1476 Py_XDECREF(it2);
1477 if (cmp == 1)
1478 Py_RETURN_TRUE;
1479 if (cmp == 0)
1480 Py_RETURN_FALSE;
1481 return NULL;
Raymond Hettinger738ec902004-02-29 02:15:56 +00001482}
1483
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001484static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001485deque_init(dequeobject *deque, PyObject *args, PyObject *kwdargs)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001486{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001487 PyObject *iterable = NULL;
1488 PyObject *maxlenobj = NULL;
1489 Py_ssize_t maxlen = -1;
1490 char *kwlist[] = {"iterable", "maxlen", 0};
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001491
Raymond Hettinger05f1b932019-01-31 22:13:43 -08001492 if (kwdargs == NULL && PyTuple_GET_SIZE(args) <= 2) {
1493 if (PyTuple_GET_SIZE(args) > 0) {
1494 iterable = PyTuple_GET_ITEM(args, 0);
1495 }
1496 if (PyTuple_GET_SIZE(args) > 1) {
1497 maxlenobj = PyTuple_GET_ITEM(args, 1);
1498 }
Raymond Hettinger0d309402015-09-30 23:15:02 -07001499 } else {
1500 if (!PyArg_ParseTupleAndKeywords(args, kwdargs, "|OO:deque", kwlist,
1501 &iterable, &maxlenobj))
1502 return -1;
1503 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001504 if (maxlenobj != NULL && maxlenobj != Py_None) {
1505 maxlen = PyLong_AsSsize_t(maxlenobj);
1506 if (maxlen == -1 && PyErr_Occurred())
1507 return -1;
1508 if (maxlen < 0) {
1509 PyErr_SetString(PyExc_ValueError, "maxlen must be non-negative");
1510 return -1;
1511 }
1512 }
1513 deque->maxlen = maxlen;
Raymond Hettinger0d309402015-09-30 23:15:02 -07001514 if (Py_SIZE(deque) > 0)
1515 deque_clear(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001516 if (iterable != NULL) {
1517 PyObject *rv = deque_extend(deque, iterable);
1518 if (rv == NULL)
1519 return -1;
1520 Py_DECREF(rv);
1521 }
1522 return 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001523}
1524
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001525static PyObject *
Jesus Cea16e2fca2012-08-03 14:49:42 +02001526deque_sizeof(dequeobject *deque, void *unused)
1527{
1528 Py_ssize_t res;
1529 Py_ssize_t blocks;
1530
Serhiy Storchaka5c4064e2015-12-19 20:05:25 +02001531 res = _PyObject_SIZE(Py_TYPE(deque));
Raymond Hettingerbc003412015-10-14 23:33:23 -07001532 blocks = (size_t)(deque->leftindex + Py_SIZE(deque) + BLOCKLEN - 1) / BLOCKLEN;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001533 assert(deque->leftindex + Py_SIZE(deque) - 1 ==
Jesus Cea16e2fca2012-08-03 14:49:42 +02001534 (blocks - 1) * BLOCKLEN + deque->rightindex);
1535 res += blocks * sizeof(block);
1536 return PyLong_FromSsize_t(res);
1537}
1538
1539PyDoc_STRVAR(sizeof_doc,
1540"D.__sizeof__() -- size of D in memory, in bytes");
1541
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001542static int
1543deque_bool(dequeobject *deque)
1544{
1545 return Py_SIZE(deque) != 0;
1546}
1547
Jesus Cea16e2fca2012-08-03 14:49:42 +02001548static PyObject *
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +02001549deque_get_maxlen(dequeobject *deque, void *Py_UNUSED(ignored))
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001550{
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -07001551 if (deque->maxlen < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001552 Py_RETURN_NONE;
1553 return PyLong_FromSsize_t(deque->maxlen);
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001554}
1555
Raymond Hettinger41290a62015-03-31 08:12:23 -07001556
1557/* deque object ********************************************************/
1558
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001559static PyGetSetDef deque_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001560 {"maxlen", (getter)deque_get_maxlen, (setter)NULL,
1561 "maximum size of a deque or None if unbounded"},
1562 {0}
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001563};
1564
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001565static PySequenceMethods deque_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001566 (lenfunc)deque_len, /* sq_length */
Raymond Hettinger41290a62015-03-31 08:12:23 -07001567 (binaryfunc)deque_concat, /* sq_concat */
1568 (ssizeargfunc)deque_repeat, /* sq_repeat */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001569 (ssizeargfunc)deque_item, /* sq_item */
1570 0, /* sq_slice */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001571 (ssizeobjargproc)deque_ass_item, /* sq_ass_item */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001572 0, /* sq_ass_slice */
Raymond Hettinger39dadf72015-03-20 16:38:56 -07001573 (objobjproc)deque_contains, /* sq_contains */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001574 (binaryfunc)deque_inplace_concat, /* sq_inplace_concat */
Raymond Hettinger41290a62015-03-31 08:12:23 -07001575 (ssizeargfunc)deque_inplace_repeat, /* sq_inplace_repeat */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001576};
1577
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001578static PyNumberMethods deque_as_number = {
1579 0, /* nb_add */
1580 0, /* nb_subtract */
1581 0, /* nb_multiply */
1582 0, /* nb_remainder */
1583 0, /* nb_divmod */
1584 0, /* nb_power */
1585 0, /* nb_negative */
1586 0, /* nb_positive */
1587 0, /* nb_absolute */
1588 (inquiry)deque_bool, /* nb_bool */
1589 0, /* nb_invert */
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001590 };
1591
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001592static PyObject *deque_iter(dequeobject *deque);
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301593static PyObject *deque_reviter(dequeobject *deque, PyObject *Py_UNUSED(ignored));
Tim Peters1065f752004-10-01 01:03:29 +00001594PyDoc_STRVAR(reversed_doc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001595 "D.__reversed__() -- return a reverse iterator over the deque");
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001596
1597static PyMethodDef deque_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001598 {"append", (PyCFunction)deque_append,
1599 METH_O, append_doc},
1600 {"appendleft", (PyCFunction)deque_appendleft,
1601 METH_O, appendleft_doc},
1602 {"clear", (PyCFunction)deque_clearmethod,
1603 METH_NOARGS, clear_doc},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301604 {"__copy__", deque_copy,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001605 METH_NOARGS, copy_doc},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301606 {"copy", deque_copy,
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001607 METH_NOARGS, copy_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001608 {"count", (PyCFunction)deque_count,
Raymond Hettinger0f6f9472015-03-21 01:42:10 -07001609 METH_O, count_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001610 {"extend", (PyCFunction)deque_extend,
1611 METH_O, extend_doc},
1612 {"extendleft", (PyCFunction)deque_extendleft,
1613 METH_O, extendleft_doc},
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001614 {"index", (PyCFunction)(void(*)(void))deque_index,
Victor Stinnerdd407d52017-02-06 16:06:49 +01001615 METH_FASTCALL, index_doc},
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001616 {"insert", (PyCFunction)(void(*)(void))deque_insert,
Victor Stinnerdd407d52017-02-06 16:06:49 +01001617 METH_FASTCALL, insert_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001618 {"pop", (PyCFunction)deque_pop,
1619 METH_NOARGS, pop_doc},
1620 {"popleft", (PyCFunction)deque_popleft,
1621 METH_NOARGS, popleft_doc},
Raymond Hettinger0f6f9472015-03-21 01:42:10 -07001622 {"__reduce__", (PyCFunction)deque_reduce,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001623 METH_NOARGS, reduce_doc},
1624 {"remove", (PyCFunction)deque_remove,
1625 METH_O, remove_doc},
1626 {"__reversed__", (PyCFunction)deque_reviter,
1627 METH_NOARGS, reversed_doc},
1628 {"reverse", (PyCFunction)deque_reverse,
1629 METH_NOARGS, reverse_doc},
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001630 {"rotate", (PyCFunction)(void(*)(void))deque_rotate,
Victor Stinnerdd407d52017-02-06 16:06:49 +01001631 METH_FASTCALL, rotate_doc},
Jesus Cea16e2fca2012-08-03 14:49:42 +02001632 {"__sizeof__", (PyCFunction)deque_sizeof,
1633 METH_NOARGS, sizeof_doc},
Guido van Rossum48b069a2020-04-07 09:50:06 -07001634 {"__class_getitem__", (PyCFunction)Py_GenericAlias,
1635 METH_O|METH_CLASS, PyDoc_STR("See PEP 585")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001636 {NULL, NULL} /* sentinel */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001637};
1638
1639PyDoc_STRVAR(deque_doc,
Andrew Svetlov6a5c7c32012-10-31 11:50:40 +02001640"deque([iterable[, maxlen]]) --> deque object\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001641\n\
Raymond Hettinger41290a62015-03-31 08:12:23 -07001642A list-like sequence optimized for data accesses near its endpoints.");
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001643
Neal Norwitz87f10132004-02-29 15:40:53 +00001644static PyTypeObject deque_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001645 PyVarObject_HEAD_INIT(NULL, 0)
1646 "collections.deque", /* tp_name */
1647 sizeof(dequeobject), /* tp_basicsize */
1648 0, /* tp_itemsize */
1649 /* methods */
1650 (destructor)deque_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001651 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001652 0, /* tp_getattr */
1653 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001654 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001655 deque_repr, /* tp_repr */
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001656 &deque_as_number, /* tp_as_number */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001657 &deque_as_sequence, /* tp_as_sequence */
1658 0, /* tp_as_mapping */
Georg Brandlf038b322010-10-18 07:35:09 +00001659 PyObject_HashNotImplemented, /* tp_hash */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001660 0, /* tp_call */
1661 0, /* tp_str */
1662 PyObject_GenericGetAttr, /* tp_getattro */
1663 0, /* tp_setattro */
1664 0, /* tp_as_buffer */
1665 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
Georg Brandlf038b322010-10-18 07:35:09 +00001666 /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001667 deque_doc, /* tp_doc */
1668 (traverseproc)deque_traverse, /* tp_traverse */
1669 (inquiry)deque_clear, /* tp_clear */
1670 (richcmpfunc)deque_richcompare, /* tp_richcompare */
Georg Brandlf038b322010-10-18 07:35:09 +00001671 offsetof(dequeobject, weakreflist), /* tp_weaklistoffset*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001672 (getiterfunc)deque_iter, /* tp_iter */
1673 0, /* tp_iternext */
1674 deque_methods, /* tp_methods */
1675 0, /* tp_members */
Georg Brandlf038b322010-10-18 07:35:09 +00001676 deque_getset, /* tp_getset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001677 0, /* tp_base */
1678 0, /* tp_dict */
1679 0, /* tp_descr_get */
1680 0, /* tp_descr_set */
1681 0, /* tp_dictoffset */
1682 (initproc)deque_init, /* tp_init */
1683 PyType_GenericAlloc, /* tp_alloc */
1684 deque_new, /* tp_new */
1685 PyObject_GC_Del, /* tp_free */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001686};
1687
1688/*********************** Deque Iterator **************************/
1689
1690typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001691 PyObject_HEAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001692 block *b;
Raymond Hettinger87e69122015-03-02 23:32:02 -08001693 Py_ssize_t index;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001694 dequeobject *deque;
Raymond Hettingerf9d9c792015-03-02 22:47:46 -08001695 size_t state; /* state when the iterator is created */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001696 Py_ssize_t counter; /* number of items remaining for iteration */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001697} dequeiterobject;
1698
Martin v. Löwis59683e82008-06-13 07:50:45 +00001699static PyTypeObject dequeiter_type;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001700
1701static PyObject *
1702deque_iter(dequeobject *deque)
1703{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001704 dequeiterobject *it;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001706 it = PyObject_GC_New(dequeiterobject, &dequeiter_type);
1707 if (it == NULL)
1708 return NULL;
1709 it->b = deque->leftblock;
1710 it->index = deque->leftindex;
1711 Py_INCREF(deque);
1712 it->deque = deque;
1713 it->state = deque->state;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001714 it->counter = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001715 PyObject_GC_Track(it);
1716 return (PyObject *)it;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001717}
1718
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001719static int
1720dequeiter_traverse(dequeiterobject *dio, visitproc visit, void *arg)
1721{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001722 Py_VISIT(dio->deque);
1723 return 0;
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001724}
1725
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001726static void
1727dequeiter_dealloc(dequeiterobject *dio)
1728{
INADA Naokia6296d32017-08-24 14:55:17 +09001729 /* bpo-31095: UnTrack is needed before calling any callbacks */
1730 PyObject_GC_UnTrack(dio);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001731 Py_XDECREF(dio->deque);
1732 PyObject_GC_Del(dio);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001733}
1734
1735static PyObject *
1736dequeiter_next(dequeiterobject *it)
1737{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001738 PyObject *item;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001740 if (it->deque->state != it->state) {
1741 it->counter = 0;
1742 PyErr_SetString(PyExc_RuntimeError,
1743 "deque mutated during iteration");
1744 return NULL;
1745 }
1746 if (it->counter == 0)
1747 return NULL;
1748 assert (!(it->b == it->deque->rightblock &&
1749 it->index > it->deque->rightindex));
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001750
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001751 item = it->b->data[it->index];
1752 it->index++;
1753 it->counter--;
1754 if (it->index == BLOCKLEN && it->counter > 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -10001755 CHECK_NOT_END(it->b->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001756 it->b = it->b->rightlink;
1757 it->index = 0;
1758 }
1759 Py_INCREF(item);
1760 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001761}
1762
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001763static PyObject *
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001764dequeiter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1765{
1766 Py_ssize_t i, index=0;
1767 PyObject *deque;
1768 dequeiterobject *it;
1769 if (!PyArg_ParseTuple(args, "O!|n", &deque_type, &deque, &index))
1770 return NULL;
1771 assert(type == &dequeiter_type);
1772
1773 it = (dequeiterobject*)deque_iter((dequeobject *)deque);
1774 if (!it)
1775 return NULL;
1776 /* consume items from the queue */
1777 for(i=0; i<index; i++) {
1778 PyObject *item = dequeiter_next(it);
1779 if (item) {
1780 Py_DECREF(item);
1781 } else {
1782 if (it->counter) {
1783 Py_DECREF(it);
1784 return NULL;
1785 } else
1786 break;
1787 }
1788 }
1789 return (PyObject*)it;
1790}
1791
1792static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301793dequeiter_len(dequeiterobject *it, PyObject *Py_UNUSED(ignored))
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001794{
Antoine Pitrou554f3342010-08-17 18:30:06 +00001795 return PyLong_FromSsize_t(it->counter);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001796}
1797
Armin Rigof5b3e362006-02-11 21:32:43 +00001798PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001799
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001800static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301801dequeiter_reduce(dequeiterobject *it, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001802{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001803 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 +00001804}
1805
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001806static PyMethodDef dequeiter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001807 {"__length_hint__", (PyCFunction)dequeiter_len, METH_NOARGS, length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001808 {"__reduce__", (PyCFunction)dequeiter_reduce, METH_NOARGS, reduce_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001809 {NULL, NULL} /* sentinel */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001810};
1811
Martin v. Löwis59683e82008-06-13 07:50:45 +00001812static PyTypeObject dequeiter_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001813 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger87e69122015-03-02 23:32:02 -08001814 "_collections._deque_iterator", /* tp_name */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001815 sizeof(dequeiterobject), /* tp_basicsize */
1816 0, /* tp_itemsize */
1817 /* methods */
1818 (destructor)dequeiter_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001819 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001820 0, /* tp_getattr */
1821 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001822 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001823 0, /* tp_repr */
1824 0, /* tp_as_number */
1825 0, /* tp_as_sequence */
1826 0, /* tp_as_mapping */
1827 0, /* tp_hash */
1828 0, /* tp_call */
1829 0, /* tp_str */
1830 PyObject_GenericGetAttr, /* tp_getattro */
1831 0, /* tp_setattro */
1832 0, /* tp_as_buffer */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001833 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001834 0, /* tp_doc */
1835 (traverseproc)dequeiter_traverse, /* tp_traverse */
1836 0, /* tp_clear */
1837 0, /* tp_richcompare */
1838 0, /* tp_weaklistoffset */
1839 PyObject_SelfIter, /* tp_iter */
1840 (iternextfunc)dequeiter_next, /* tp_iternext */
1841 dequeiter_methods, /* tp_methods */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001842 0, /* tp_members */
1843 0, /* tp_getset */
1844 0, /* tp_base */
1845 0, /* tp_dict */
1846 0, /* tp_descr_get */
1847 0, /* tp_descr_set */
1848 0, /* tp_dictoffset */
1849 0, /* tp_init */
1850 0, /* tp_alloc */
1851 dequeiter_new, /* tp_new */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001852 0,
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001853};
1854
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001855/*********************** Deque Reverse Iterator **************************/
1856
Martin v. Löwis59683e82008-06-13 07:50:45 +00001857static PyTypeObject dequereviter_type;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001858
1859static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301860deque_reviter(dequeobject *deque, PyObject *Py_UNUSED(ignored))
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001861{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001862 dequeiterobject *it;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001864 it = PyObject_GC_New(dequeiterobject, &dequereviter_type);
1865 if (it == NULL)
1866 return NULL;
1867 it->b = deque->rightblock;
1868 it->index = deque->rightindex;
1869 Py_INCREF(deque);
1870 it->deque = deque;
1871 it->state = deque->state;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001872 it->counter = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001873 PyObject_GC_Track(it);
1874 return (PyObject *)it;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001875}
1876
1877static PyObject *
1878dequereviter_next(dequeiterobject *it)
1879{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001880 PyObject *item;
1881 if (it->counter == 0)
1882 return NULL;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001884 if (it->deque->state != it->state) {
1885 it->counter = 0;
1886 PyErr_SetString(PyExc_RuntimeError,
1887 "deque mutated during iteration");
1888 return NULL;
1889 }
1890 assert (!(it->b == it->deque->leftblock &&
1891 it->index < it->deque->leftindex));
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001893 item = it->b->data[it->index];
1894 it->index--;
1895 it->counter--;
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -07001896 if (it->index < 0 && it->counter > 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -10001897 CHECK_NOT_END(it->b->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001898 it->b = it->b->leftlink;
1899 it->index = BLOCKLEN - 1;
1900 }
1901 Py_INCREF(item);
1902 return item;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001903}
1904
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001905static PyObject *
1906dequereviter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1907{
1908 Py_ssize_t i, index=0;
1909 PyObject *deque;
1910 dequeiterobject *it;
1911 if (!PyArg_ParseTuple(args, "O!|n", &deque_type, &deque, &index))
1912 return NULL;
1913 assert(type == &dequereviter_type);
1914
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301915 it = (dequeiterobject*)deque_reviter((dequeobject *)deque, NULL);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001916 if (!it)
1917 return NULL;
1918 /* consume items from the queue */
1919 for(i=0; i<index; i++) {
1920 PyObject *item = dequereviter_next(it);
1921 if (item) {
1922 Py_DECREF(item);
1923 } else {
1924 if (it->counter) {
1925 Py_DECREF(it);
1926 return NULL;
1927 } else
1928 break;
1929 }
1930 }
1931 return (PyObject*)it;
1932}
1933
Martin v. Löwis59683e82008-06-13 07:50:45 +00001934static PyTypeObject dequereviter_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001935 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger87e69122015-03-02 23:32:02 -08001936 "_collections._deque_reverse_iterator", /* tp_name */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001937 sizeof(dequeiterobject), /* tp_basicsize */
1938 0, /* tp_itemsize */
1939 /* methods */
1940 (destructor)dequeiter_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001941 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001942 0, /* tp_getattr */
1943 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001944 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001945 0, /* tp_repr */
1946 0, /* tp_as_number */
1947 0, /* tp_as_sequence */
1948 0, /* tp_as_mapping */
1949 0, /* tp_hash */
1950 0, /* tp_call */
1951 0, /* tp_str */
1952 PyObject_GenericGetAttr, /* tp_getattro */
1953 0, /* tp_setattro */
1954 0, /* tp_as_buffer */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001955 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001956 0, /* tp_doc */
1957 (traverseproc)dequeiter_traverse, /* tp_traverse */
1958 0, /* tp_clear */
1959 0, /* tp_richcompare */
1960 0, /* tp_weaklistoffset */
1961 PyObject_SelfIter, /* tp_iter */
1962 (iternextfunc)dequereviter_next, /* tp_iternext */
1963 dequeiter_methods, /* tp_methods */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001964 0, /* tp_members */
1965 0, /* tp_getset */
1966 0, /* tp_base */
1967 0, /* tp_dict */
1968 0, /* tp_descr_get */
1969 0, /* tp_descr_set */
1970 0, /* tp_dictoffset */
1971 0, /* tp_init */
1972 0, /* tp_alloc */
1973 dequereviter_new, /* tp_new */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001974 0,
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001975};
1976
Guido van Rossum1968ad32006-02-25 22:38:04 +00001977/* defaultdict type *********************************************************/
1978
1979typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001980 PyDictObject dict;
1981 PyObject *default_factory;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001982} defdictobject;
1983
1984static PyTypeObject defdict_type; /* Forward */
1985
1986PyDoc_STRVAR(defdict_missing_doc,
1987"__missing__(key) # Called by __getitem__ for missing key; pseudo-code:\n\
Guido van Rossumd8faa362007-04-27 19:54:29 +00001988 if self.default_factory is None: raise KeyError((key,))\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00001989 self[key] = value = self.default_factory()\n\
1990 return value\n\
1991");
1992
1993static PyObject *
1994defdict_missing(defdictobject *dd, PyObject *key)
1995{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001996 PyObject *factory = dd->default_factory;
1997 PyObject *value;
1998 if (factory == NULL || factory == Py_None) {
1999 /* XXX Call dict.__missing__(key) */
2000 PyObject *tup;
2001 tup = PyTuple_Pack(1, key);
2002 if (!tup) return NULL;
2003 PyErr_SetObject(PyExc_KeyError, tup);
2004 Py_DECREF(tup);
2005 return NULL;
2006 }
Jeroen Demeyer7f41c8e2019-07-04 12:35:31 +02002007 value = _PyObject_CallNoArg(factory);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002008 if (value == NULL)
2009 return value;
2010 if (PyObject_SetItem((PyObject *)dd, key, value) < 0) {
2011 Py_DECREF(value);
2012 return NULL;
2013 }
2014 return value;
Guido van Rossum1968ad32006-02-25 22:38:04 +00002015}
2016
Brandt Bucher57c9d172020-03-06 09:24:08 -08002017static inline PyObject*
2018new_defdict(defdictobject *dd, PyObject *arg)
2019{
2020 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd),
2021 dd->default_factory ? dd->default_factory : Py_None, arg, NULL);
2022}
2023
Guido van Rossum1968ad32006-02-25 22:38:04 +00002024PyDoc_STRVAR(defdict_copy_doc, "D.copy() -> a shallow copy of D.");
2025
2026static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302027defdict_copy(defdictobject *dd, PyObject *Py_UNUSED(ignored))
Guido van Rossum1968ad32006-02-25 22:38:04 +00002028{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002029 /* This calls the object's class. That only works for subclasses
2030 whose class constructor has the same signature. Subclasses that
2031 define a different constructor signature must override copy().
2032 */
Brandt Bucher57c9d172020-03-06 09:24:08 -08002033 return new_defdict(dd, (PyObject*)dd);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002034}
2035
2036static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302037defdict_reduce(defdictobject *dd, PyObject *Py_UNUSED(ignored))
Guido van Rossum1968ad32006-02-25 22:38:04 +00002038{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002039 /* __reduce__ must return a 5-tuple as follows:
Guido van Rossum1968ad32006-02-25 22:38:04 +00002040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002041 - factory function
2042 - tuple of args for the factory function
2043 - additional state (here None)
2044 - sequence iterator (here None)
2045 - dictionary iterator (yielding successive (key, value) pairs
Guido van Rossum1968ad32006-02-25 22:38:04 +00002046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002047 This API is used by pickle.py and copy.py.
Guido van Rossum1968ad32006-02-25 22:38:04 +00002048
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002049 For this to be useful with pickle.py, the default_factory
2050 must be picklable; e.g., None, a built-in, or a global
2051 function in a module or package.
Guido van Rossum1968ad32006-02-25 22:38:04 +00002052
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002053 Both shallow and deep copying are supported, but for deep
2054 copying, the default_factory must be deep-copyable; e.g. None,
2055 or a built-in (functions are not copyable at this time).
Guido van Rossum1968ad32006-02-25 22:38:04 +00002056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002057 This only works for subclasses as long as their constructor
2058 signature is compatible; the first argument must be the
2059 optional default_factory, defaulting to None.
2060 */
2061 PyObject *args;
2062 PyObject *items;
2063 PyObject *iter;
2064 PyObject *result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002065 _Py_IDENTIFIER(items);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002067 if (dd->default_factory == NULL || dd->default_factory == Py_None)
2068 args = PyTuple_New(0);
2069 else
2070 args = PyTuple_Pack(1, dd->default_factory);
2071 if (args == NULL)
2072 return NULL;
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002073 items = _PyObject_CallMethodIdNoArgs((PyObject *)dd, &PyId_items);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002074 if (items == NULL) {
2075 Py_DECREF(args);
2076 return NULL;
2077 }
2078 iter = PyObject_GetIter(items);
2079 if (iter == NULL) {
2080 Py_DECREF(items);
2081 Py_DECREF(args);
2082 return NULL;
2083 }
2084 result = PyTuple_Pack(5, Py_TYPE(dd), args,
2085 Py_None, Py_None, iter);
2086 Py_DECREF(iter);
2087 Py_DECREF(items);
2088 Py_DECREF(args);
2089 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00002090}
2091
2092static PyMethodDef defdict_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002093 {"__missing__", (PyCFunction)defdict_missing, METH_O,
2094 defdict_missing_doc},
2095 {"copy", (PyCFunction)defdict_copy, METH_NOARGS,
2096 defdict_copy_doc},
2097 {"__copy__", (PyCFunction)defdict_copy, METH_NOARGS,
2098 defdict_copy_doc},
2099 {"__reduce__", (PyCFunction)defdict_reduce, METH_NOARGS,
2100 reduce_doc},
Guido van Rossum48b069a2020-04-07 09:50:06 -07002101 {"__class_getitem__", (PyCFunction)Py_GenericAlias, METH_O|METH_CLASS,
2102 PyDoc_STR("See PEP 585")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002103 {NULL}
Guido van Rossum1968ad32006-02-25 22:38:04 +00002104};
2105
2106static PyMemberDef defdict_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002107 {"default_factory", T_OBJECT,
2108 offsetof(defdictobject, default_factory), 0,
2109 PyDoc_STR("Factory for default value called by __missing__().")},
2110 {NULL}
Guido van Rossum1968ad32006-02-25 22:38:04 +00002111};
2112
2113static void
2114defdict_dealloc(defdictobject *dd)
2115{
INADA Naokia6296d32017-08-24 14:55:17 +09002116 /* bpo-31095: UnTrack is needed before calling any callbacks */
2117 PyObject_GC_UnTrack(dd);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002118 Py_CLEAR(dd->default_factory);
2119 PyDict_Type.tp_dealloc((PyObject *)dd);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002120}
2121
Guido van Rossum1968ad32006-02-25 22:38:04 +00002122static PyObject *
2123defdict_repr(defdictobject *dd)
2124{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002125 PyObject *baserepr;
2126 PyObject *defrepr;
2127 PyObject *result;
2128 baserepr = PyDict_Type.tp_repr((PyObject *)dd);
2129 if (baserepr == NULL)
2130 return NULL;
2131 if (dd->default_factory == NULL)
2132 defrepr = PyUnicode_FromString("None");
2133 else
2134 {
2135 int status = Py_ReprEnter(dd->default_factory);
2136 if (status != 0) {
Antoine Pitrouf5f1fe02012-02-15 02:42:46 +01002137 if (status < 0) {
2138 Py_DECREF(baserepr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002139 return NULL;
Antoine Pitrouf5f1fe02012-02-15 02:42:46 +01002140 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 defrepr = PyUnicode_FromString("...");
2142 }
2143 else
2144 defrepr = PyObject_Repr(dd->default_factory);
2145 Py_ReprLeave(dd->default_factory);
2146 }
2147 if (defrepr == NULL) {
2148 Py_DECREF(baserepr);
2149 return NULL;
2150 }
Serhiy Storchakab3a77962017-09-21 14:24:13 +03002151 result = PyUnicode_FromFormat("%s(%U, %U)",
2152 _PyType_Name(Py_TYPE(dd)),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002153 defrepr, baserepr);
2154 Py_DECREF(defrepr);
2155 Py_DECREF(baserepr);
2156 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00002157}
2158
Brandt Bucher57c9d172020-03-06 09:24:08 -08002159static PyObject*
2160defdict_or(PyObject* left, PyObject* right)
2161{
Brandt Bucher57c9d172020-03-06 09:24:08 -08002162 PyObject *self, *other;
Brandt Bucher1dd37942020-03-11 21:06:46 -07002163 if (PyObject_TypeCheck(left, &defdict_type)) {
Brandt Bucher57c9d172020-03-06 09:24:08 -08002164 self = left;
2165 other = right;
2166 }
2167 else {
2168 self = right;
2169 other = left;
2170 }
2171 if (!PyDict_Check(other)) {
2172 Py_RETURN_NOTIMPLEMENTED;
2173 }
2174 // Like copy(), this calls the object's class.
2175 // Override __or__/__ror__ for subclasses with different constructors.
2176 PyObject *new = new_defdict((defdictobject*)self, left);
2177 if (!new) {
2178 return NULL;
2179 }
2180 if (PyDict_Update(new, right)) {
2181 Py_DECREF(new);
2182 return NULL;
2183 }
2184 return new;
2185}
2186
2187static PyNumberMethods defdict_as_number = {
2188 .nb_or = defdict_or,
2189};
2190
Guido van Rossum1968ad32006-02-25 22:38:04 +00002191static int
2192defdict_traverse(PyObject *self, visitproc visit, void *arg)
2193{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002194 Py_VISIT(((defdictobject *)self)->default_factory);
2195 return PyDict_Type.tp_traverse(self, visit, arg);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002196}
2197
2198static int
2199defdict_tp_clear(defdictobject *dd)
2200{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002201 Py_CLEAR(dd->default_factory);
2202 return PyDict_Type.tp_clear((PyObject *)dd);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002203}
2204
2205static int
2206defdict_init(PyObject *self, PyObject *args, PyObject *kwds)
2207{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002208 defdictobject *dd = (defdictobject *)self;
2209 PyObject *olddefault = dd->default_factory;
2210 PyObject *newdefault = NULL;
2211 PyObject *newargs;
2212 int result;
2213 if (args == NULL || !PyTuple_Check(args))
2214 newargs = PyTuple_New(0);
2215 else {
2216 Py_ssize_t n = PyTuple_GET_SIZE(args);
2217 if (n > 0) {
2218 newdefault = PyTuple_GET_ITEM(args, 0);
2219 if (!PyCallable_Check(newdefault) && newdefault != Py_None) {
2220 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger239aba72015-07-20 03:09:22 -04002221 "first argument must be callable or None");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002222 return -1;
2223 }
2224 }
2225 newargs = PySequence_GetSlice(args, 1, n);
2226 }
2227 if (newargs == NULL)
2228 return -1;
2229 Py_XINCREF(newdefault);
2230 dd->default_factory = newdefault;
2231 result = PyDict_Type.tp_init(self, newargs, kwds);
2232 Py_DECREF(newargs);
2233 Py_XDECREF(olddefault);
2234 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00002235}
2236
2237PyDoc_STRVAR(defdict_doc,
Benjamin Peterson9cb33b72014-01-13 23:56:05 -05002238"defaultdict(default_factory[, ...]) --> dict with default factory\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00002239\n\
2240The default factory is called without arguments to produce\n\
2241a new value when a key is not present, in __getitem__ only.\n\
2242A defaultdict compares equal to a dict with the same items.\n\
Benjamin Peterson9cb33b72014-01-13 23:56:05 -05002243All remaining arguments are treated the same as if they were\n\
2244passed to the dict constructor, including keyword arguments.\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00002245");
2246
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002247/* See comment in xxsubtype.c */
2248#define DEFERRED_ADDRESS(ADDR) 0
2249
Guido van Rossum1968ad32006-02-25 22:38:04 +00002250static PyTypeObject defdict_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002251 PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0)
2252 "collections.defaultdict", /* tp_name */
2253 sizeof(defdictobject), /* tp_basicsize */
2254 0, /* tp_itemsize */
2255 /* methods */
2256 (destructor)defdict_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002257 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002258 0, /* tp_getattr */
2259 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002260 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002261 (reprfunc)defdict_repr, /* tp_repr */
Brandt Bucher57c9d172020-03-06 09:24:08 -08002262 &defdict_as_number, /* tp_as_number */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002263 0, /* tp_as_sequence */
2264 0, /* tp_as_mapping */
2265 0, /* tp_hash */
2266 0, /* tp_call */
2267 0, /* tp_str */
2268 PyObject_GenericGetAttr, /* tp_getattro */
2269 0, /* tp_setattro */
2270 0, /* tp_as_buffer */
2271 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
2272 /* tp_flags */
2273 defdict_doc, /* tp_doc */
2274 defdict_traverse, /* tp_traverse */
2275 (inquiry)defdict_tp_clear, /* tp_clear */
2276 0, /* tp_richcompare */
2277 0, /* tp_weaklistoffset*/
2278 0, /* tp_iter */
2279 0, /* tp_iternext */
2280 defdict_methods, /* tp_methods */
2281 defdict_members, /* tp_members */
2282 0, /* tp_getset */
2283 DEFERRED_ADDRESS(&PyDict_Type), /* tp_base */
2284 0, /* tp_dict */
2285 0, /* tp_descr_get */
2286 0, /* tp_descr_set */
2287 0, /* tp_dictoffset */
2288 defdict_init, /* tp_init */
2289 PyType_GenericAlloc, /* tp_alloc */
2290 0, /* tp_new */
2291 PyObject_GC_Del, /* tp_free */
Guido van Rossum1968ad32006-02-25 22:38:04 +00002292};
2293
Raymond Hettinger96f34102010-12-15 16:30:37 +00002294/* helper function for Counter *********************************************/
2295
Raymond Hettingere9858042019-06-05 16:05:25 -07002296/*[clinic input]
2297_collections._count_elements
2298
2299 mapping: object
2300 iterable: object
2301 /
2302
2303Count elements in the iterable, updating the mapping
2304[clinic start generated code]*/
Raymond Hettinger96f34102010-12-15 16:30:37 +00002305
2306static PyObject *
Raymond Hettingere9858042019-06-05 16:05:25 -07002307_collections__count_elements_impl(PyObject *module, PyObject *mapping,
2308 PyObject *iterable)
2309/*[clinic end generated code: output=7e0c1789636b3d8f input=e79fad04534a0b45]*/
Raymond Hettinger96f34102010-12-15 16:30:37 +00002310{
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002311 _Py_IDENTIFIER(get);
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002312 _Py_IDENTIFIER(__setitem__);
Raymond Hettingere9858042019-06-05 16:05:25 -07002313 PyObject *it, *oldval;
Raymond Hettinger96f34102010-12-15 16:30:37 +00002314 PyObject *newval = NULL;
2315 PyObject *key = NULL;
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002316 PyObject *bound_get = NULL;
2317 PyObject *mapping_get;
2318 PyObject *dict_get;
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002319 PyObject *mapping_setitem;
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002320 PyObject *dict_setitem;
Victor Stinner35b95aa2020-10-27 22:24:33 +01002321 PyObject *one = _PyLong_GetOne(); // borrowed reference
Raymond Hettinger96f34102010-12-15 16:30:37 +00002322
Raymond Hettinger96f34102010-12-15 16:30:37 +00002323 it = PyObject_GetIter(iterable);
2324 if (it == NULL)
2325 return NULL;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002326
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002327 /* Only take the fast path when get() and __setitem__()
2328 * have not been overridden.
2329 */
2330 mapping_get = _PyType_LookupId(Py_TYPE(mapping), &PyId_get);
2331 dict_get = _PyType_LookupId(&PyDict_Type, &PyId_get);
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002332 mapping_setitem = _PyType_LookupId(Py_TYPE(mapping), &PyId___setitem__);
2333 dict_setitem = _PyType_LookupId(&PyDict_Type, &PyId___setitem__);
2334
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002335 if (mapping_get != NULL && mapping_get == dict_get &&
Oren Milman31aca4b2017-09-27 06:18:21 +03002336 mapping_setitem != NULL && mapping_setitem == dict_setitem &&
2337 PyDict_Check(mapping))
2338 {
Raymond Hettinger426e0522011-01-03 02:12:02 +00002339 while (1) {
Raymond Hettinger507d9972014-05-18 21:32:40 +01002340 /* Fast path advantages:
2341 1. Eliminate double hashing
2342 (by re-using the same hash for both the get and set)
2343 2. Avoid argument overhead of PyObject_CallFunctionObjArgs
2344 (argument tuple creation and parsing)
2345 3. Avoid indirection through a bound method object
2346 (creates another argument tuple)
2347 4. Avoid initial increment from zero
2348 (reuse an existing one-object instead)
2349 */
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002350 Py_hash_t hash;
2351
Raymond Hettinger426e0522011-01-03 02:12:02 +00002352 key = PyIter_Next(it);
Victor Stinnera154b5c2011-04-20 23:23:52 +02002353 if (key == NULL)
2354 break;
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002355
2356 if (!PyUnicode_CheckExact(key) ||
2357 (hash = ((PyASCIIObject *) key)->hash) == -1)
2358 {
2359 hash = PyObject_Hash(key);
Raymond Hettingerda2850f2015-02-27 12:42:54 -08002360 if (hash == -1)
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002361 goto done;
2362 }
2363
2364 oldval = _PyDict_GetItem_KnownHash(mapping, key, hash);
Raymond Hettinger426e0522011-01-03 02:12:02 +00002365 if (oldval == NULL) {
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02002366 if (PyErr_Occurred())
2367 goto done;
Victor Stinner35b95aa2020-10-27 22:24:33 +01002368 if (_PyDict_SetItem_KnownHash(mapping, key, one, hash) < 0)
Raymond Hettinger507d9972014-05-18 21:32:40 +01002369 goto done;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002370 } else {
Victor Stinner35b95aa2020-10-27 22:24:33 +01002371 newval = PyNumber_Add(oldval, one);
Raymond Hettinger426e0522011-01-03 02:12:02 +00002372 if (newval == NULL)
Raymond Hettinger507d9972014-05-18 21:32:40 +01002373 goto done;
Raymond Hettinger28c995d2015-08-14 02:07:41 -07002374 if (_PyDict_SetItem_KnownHash(mapping, key, newval, hash) < 0)
Raymond Hettinger507d9972014-05-18 21:32:40 +01002375 goto done;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002376 Py_CLEAR(newval);
2377 }
2378 Py_DECREF(key);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002379 }
Victor Stinner35b95aa2020-10-27 22:24:33 +01002380 }
2381 else {
Victor Stinnere7f516c2013-11-06 23:52:55 +01002382 bound_get = _PyObject_GetAttrId(mapping, &PyId_get);
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002383 if (bound_get == NULL)
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002384 goto done;
2385
Victor Stinner37834132020-10-27 17:12:53 +01002386 PyObject *zero = _PyLong_GetZero(); // borrowed reference
Raymond Hettinger426e0522011-01-03 02:12:02 +00002387 while (1) {
2388 key = PyIter_Next(it);
Victor Stinnera154b5c2011-04-20 23:23:52 +02002389 if (key == NULL)
2390 break;
Victor Stinner37834132020-10-27 17:12:53 +01002391 oldval = PyObject_CallFunctionObjArgs(bound_get, key, zero, NULL);
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002392 if (oldval == NULL)
2393 break;
Victor Stinner37834132020-10-27 17:12:53 +01002394 newval = PyNumber_Add(oldval, one);
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002395 Py_DECREF(oldval);
2396 if (newval == NULL)
2397 break;
Raymond Hettinger28c995d2015-08-14 02:07:41 -07002398 if (PyObject_SetItem(mapping, key, newval) < 0)
Raymond Hettinger96f34102010-12-15 16:30:37 +00002399 break;
2400 Py_CLEAR(newval);
Raymond Hettinger426e0522011-01-03 02:12:02 +00002401 Py_DECREF(key);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002402 }
Raymond Hettinger96f34102010-12-15 16:30:37 +00002403 }
Raymond Hettinger426e0522011-01-03 02:12:02 +00002404
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002405done:
Raymond Hettinger96f34102010-12-15 16:30:37 +00002406 Py_DECREF(it);
2407 Py_XDECREF(key);
2408 Py_XDECREF(newval);
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002409 Py_XDECREF(bound_get);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002410 if (PyErr_Occurred())
2411 return NULL;
2412 Py_RETURN_NONE;
2413}
2414
Serhiy Storchaka052b2df2018-12-31 14:15:16 +02002415/* Helper function for namedtuple() ************************************/
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002416
2417typedef struct {
2418 PyObject_HEAD
2419 Py_ssize_t index;
2420 PyObject* doc;
2421} _tuplegetterobject;
2422
2423/*[clinic input]
2424@classmethod
2425_tuplegetter.__new__ as tuplegetter_new
2426
2427 index: Py_ssize_t
2428 doc: object
2429 /
2430[clinic start generated code]*/
2431
2432static PyObject *
2433tuplegetter_new_impl(PyTypeObject *type, Py_ssize_t index, PyObject *doc)
2434/*[clinic end generated code: output=014be444ad80263f input=87c576a5bdbc0bbb]*/
2435{
2436 _tuplegetterobject* self;
2437 self = (_tuplegetterobject *)type->tp_alloc(type, 0);
2438 if (self == NULL) {
2439 return NULL;
2440 }
2441 self->index = index;
2442 Py_INCREF(doc);
2443 self->doc = doc;
2444 return (PyObject *)self;
2445}
2446
2447static PyObject *
Serhiy Storchaka052b2df2018-12-31 14:15:16 +02002448tuplegetter_descr_get(PyObject *self, PyObject *obj, PyObject *type)
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002449{
Serhiy Storchaka052b2df2018-12-31 14:15:16 +02002450 Py_ssize_t index = ((_tuplegetterobject*)self)->index;
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002451 PyObject *result;
Serhiy Storchaka052b2df2018-12-31 14:15:16 +02002452
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002453 if (obj == NULL) {
2454 Py_INCREF(self);
2455 return self;
2456 }
2457 if (!PyTuple_Check(obj)) {
2458 if (obj == Py_None) {
2459 Py_INCREF(self);
2460 return self;
2461 }
2462 PyErr_Format(PyExc_TypeError,
Serhiy Storchakad53fe5f2019-03-13 22:59:55 +02002463 "descriptor for index '%zd' for tuple subclasses "
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002464 "doesn't apply to '%s' object",
Serhiy Storchaka052b2df2018-12-31 14:15:16 +02002465 index,
Victor Stinnerdaa97562020-02-07 03:37:06 +01002466 Py_TYPE(obj)->tp_name);
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002467 return NULL;
2468 }
2469
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002470 if (!valid_index(index, PyTuple_GET_SIZE(obj))) {
2471 PyErr_SetString(PyExc_IndexError, "tuple index out of range");
2472 return NULL;
2473 }
2474
2475 result = PyTuple_GET_ITEM(obj, index);
2476 Py_INCREF(result);
2477 return result;
2478}
2479
2480static int
Serhiy Storchaka052b2df2018-12-31 14:15:16 +02002481tuplegetter_descr_set(PyObject *self, PyObject *obj, PyObject *value)
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002482{
2483 if (value == NULL) {
2484 PyErr_SetString(PyExc_AttributeError, "can't delete attribute");
2485 } else {
2486 PyErr_SetString(PyExc_AttributeError, "can't set attribute");
2487 }
2488 return -1;
2489}
2490
2491static int
2492tuplegetter_traverse(PyObject *self, visitproc visit, void *arg)
2493{
2494 _tuplegetterobject *tuplegetter = (_tuplegetterobject *)self;
2495 Py_VISIT(tuplegetter->doc);
2496 return 0;
2497}
2498
2499static int
2500tuplegetter_clear(PyObject *self)
2501{
2502 _tuplegetterobject *tuplegetter = (_tuplegetterobject *)self;
2503 Py_CLEAR(tuplegetter->doc);
2504 return 0;
2505}
2506
2507static void
2508tuplegetter_dealloc(_tuplegetterobject *self)
2509{
2510 PyObject_GC_UnTrack(self);
2511 tuplegetter_clear((PyObject*)self);
2512 Py_TYPE(self)->tp_free((PyObject*)self);
2513}
2514
Joe Jevnikf36f8922019-02-21 16:00:40 -05002515static PyObject*
Serhiy Storchakaadfffc72019-03-05 18:41:09 +02002516tuplegetter_reduce(_tuplegetterobject *self, PyObject *Py_UNUSED(ignored))
Joe Jevnikf36f8922019-02-21 16:00:40 -05002517{
2518 return Py_BuildValue("(O(nO))", (PyObject*) Py_TYPE(self), self->index, self->doc);
2519}
2520
Ammar Askara86b5222020-04-14 23:36:08 -07002521static PyObject*
2522tuplegetter_repr(_tuplegetterobject *self)
2523{
2524 return PyUnicode_FromFormat("%s(%zd, %R)",
2525 _PyType_Name(Py_TYPE(self)),
2526 self->index, self->doc);
2527}
2528
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002529
2530static PyMemberDef tuplegetter_members[] = {
2531 {"__doc__", T_OBJECT, offsetof(_tuplegetterobject, doc), 0},
2532 {0}
2533};
2534
Joe Jevnikf36f8922019-02-21 16:00:40 -05002535static PyMethodDef tuplegetter_methods[] = {
Serhiy Storchakaadfffc72019-03-05 18:41:09 +02002536 {"__reduce__", (PyCFunction)tuplegetter_reduce, METH_NOARGS, NULL},
Joe Jevnikf36f8922019-02-21 16:00:40 -05002537 {NULL},
2538};
2539
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002540static PyTypeObject tuplegetter_type = {
2541 PyVarObject_HEAD_INIT(NULL, 0)
2542 "_collections._tuplegetter", /* tp_name */
2543 sizeof(_tuplegetterobject), /* tp_basicsize */
2544 0, /* tp_itemsize */
2545 /* methods */
2546 (destructor)tuplegetter_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002547 0, /* tp_vectorcall_offset */
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002548 0, /* tp_getattr */
2549 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002550 0, /* tp_as_async */
Ammar Askara86b5222020-04-14 23:36:08 -07002551 (reprfunc)tuplegetter_repr, /* tp_repr */
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002552 0, /* tp_as_number */
2553 0, /* tp_as_sequence */
2554 0, /* tp_as_mapping */
2555 0, /* tp_hash */
2556 0, /* tp_call */
2557 0, /* tp_str */
2558 0, /* tp_getattro */
2559 0, /* tp_setattro */
2560 0, /* tp_as_buffer */
2561 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
2562 0, /* tp_doc */
2563 (traverseproc)tuplegetter_traverse, /* tp_traverse */
2564 (inquiry)tuplegetter_clear, /* tp_clear */
2565 0, /* tp_richcompare */
2566 0, /* tp_weaklistoffset */
2567 0, /* tp_iter */
2568 0, /* tp_iternext */
Joe Jevnikf36f8922019-02-21 16:00:40 -05002569 tuplegetter_methods, /* tp_methods */
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002570 tuplegetter_members, /* tp_members */
2571 0, /* tp_getset */
2572 0, /* tp_base */
2573 0, /* tp_dict */
Serhiy Storchaka052b2df2018-12-31 14:15:16 +02002574 tuplegetter_descr_get, /* tp_descr_get */
2575 tuplegetter_descr_set, /* tp_descr_set */
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002576 0, /* tp_dictoffset */
2577 0, /* tp_init */
2578 0, /* tp_alloc */
2579 tuplegetter_new, /* tp_new */
2580 0,
2581};
2582
2583
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002584/* module level code ********************************************************/
2585
Dong-hee Na77248a22020-03-20 01:16:04 +09002586PyDoc_STRVAR(collections_doc,
Guido van Rossum1968ad32006-02-25 22:38:04 +00002587"High performance data structures.\n\
2588- deque: ordered collection accessible from endpoints only\n\
2589- defaultdict: dict subclass with a default value factory\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002590");
2591
Dong-hee Na77248a22020-03-20 01:16:04 +09002592static struct PyMethodDef collections_methods[] = {
Raymond Hettingere9858042019-06-05 16:05:25 -07002593 _COLLECTIONS__COUNT_ELEMENTS_METHODDEF
Raymond Hettinger96f34102010-12-15 16:30:37 +00002594 {NULL, NULL} /* sentinel */
2595};
Martin v. Löwis1a214512008-06-11 05:26:20 +00002596
Dong-hee Na77248a22020-03-20 01:16:04 +09002597static int
2598collections_exec(PyObject *module) {
2599 PyTypeObject *typelist[] = {
2600 &deque_type,
2601 &defdict_type,
2602 &PyODict_Type,
2603 &dequeiter_type,
2604 &dequereviter_type,
Dong-hee Na05e4a292020-03-23 01:17:34 +09002605 &tuplegetter_type
Dong-hee Na77248a22020-03-20 01:16:04 +09002606 };
2607
2608 defdict_type.tp_base = &PyDict_Type;
2609
Dong-hee Na05e4a292020-03-23 01:17:34 +09002610 for (size_t i = 0; i < Py_ARRAY_LENGTH(typelist); i++) {
2611 if (PyModule_AddType(module, typelist[i]) < 0) {
Dong-hee Na77248a22020-03-20 01:16:04 +09002612 return -1;
2613 }
2614 }
2615
2616 return 0;
2617}
2618
2619static struct PyModuleDef_Slot collections_slots[] = {
2620 {Py_mod_exec, collections_exec},
2621 {0, NULL}
2622};
2623
Martin v. Löwis1a214512008-06-11 05:26:20 +00002624static struct PyModuleDef _collectionsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002625 PyModuleDef_HEAD_INIT,
2626 "_collections",
Dong-hee Na77248a22020-03-20 01:16:04 +09002627 collections_doc,
2628 0,
2629 collections_methods,
2630 collections_slots,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002631 NULL,
2632 NULL,
2633 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002634};
2635
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002636PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002637PyInit__collections(void)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002638{
Dong-hee Na77248a22020-03-20 01:16:04 +09002639 return PyModuleDef_Init(&_collectionsmodule);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002640}