blob: 9c8701af904ab98aca875b6cf20ee938b98d32cf [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 */
Mark Shannon069e81a2021-04-30 09:50:28 +01001665 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
1666 Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_SEQUENCE,
Georg Brandlf038b322010-10-18 07:35:09 +00001667 /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001668 deque_doc, /* tp_doc */
1669 (traverseproc)deque_traverse, /* tp_traverse */
1670 (inquiry)deque_clear, /* tp_clear */
1671 (richcmpfunc)deque_richcompare, /* tp_richcompare */
Georg Brandlf038b322010-10-18 07:35:09 +00001672 offsetof(dequeobject, weakreflist), /* tp_weaklistoffset*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001673 (getiterfunc)deque_iter, /* tp_iter */
1674 0, /* tp_iternext */
1675 deque_methods, /* tp_methods */
1676 0, /* tp_members */
Georg Brandlf038b322010-10-18 07:35:09 +00001677 deque_getset, /* tp_getset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001678 0, /* tp_base */
1679 0, /* tp_dict */
1680 0, /* tp_descr_get */
1681 0, /* tp_descr_set */
1682 0, /* tp_dictoffset */
1683 (initproc)deque_init, /* tp_init */
1684 PyType_GenericAlloc, /* tp_alloc */
1685 deque_new, /* tp_new */
1686 PyObject_GC_Del, /* tp_free */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001687};
1688
1689/*********************** Deque Iterator **************************/
1690
1691typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001692 PyObject_HEAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001693 block *b;
Raymond Hettinger87e69122015-03-02 23:32:02 -08001694 Py_ssize_t index;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001695 dequeobject *deque;
Raymond Hettingerf9d9c792015-03-02 22:47:46 -08001696 size_t state; /* state when the iterator is created */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001697 Py_ssize_t counter; /* number of items remaining for iteration */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001698} dequeiterobject;
1699
Martin v. Löwis59683e82008-06-13 07:50:45 +00001700static PyTypeObject dequeiter_type;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001701
1702static PyObject *
1703deque_iter(dequeobject *deque)
1704{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001705 dequeiterobject *it;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001707 it = PyObject_GC_New(dequeiterobject, &dequeiter_type);
1708 if (it == NULL)
1709 return NULL;
1710 it->b = deque->leftblock;
1711 it->index = deque->leftindex;
1712 Py_INCREF(deque);
1713 it->deque = deque;
1714 it->state = deque->state;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001715 it->counter = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001716 PyObject_GC_Track(it);
1717 return (PyObject *)it;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001718}
1719
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001720static int
1721dequeiter_traverse(dequeiterobject *dio, visitproc visit, void *arg)
1722{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001723 Py_VISIT(dio->deque);
1724 return 0;
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001725}
1726
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001727static void
1728dequeiter_dealloc(dequeiterobject *dio)
1729{
INADA Naokia6296d32017-08-24 14:55:17 +09001730 /* bpo-31095: UnTrack is needed before calling any callbacks */
1731 PyObject_GC_UnTrack(dio);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001732 Py_XDECREF(dio->deque);
1733 PyObject_GC_Del(dio);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001734}
1735
1736static PyObject *
1737dequeiter_next(dequeiterobject *it)
1738{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001739 PyObject *item;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001740
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001741 if (it->deque->state != it->state) {
1742 it->counter = 0;
1743 PyErr_SetString(PyExc_RuntimeError,
1744 "deque mutated during iteration");
1745 return NULL;
1746 }
1747 if (it->counter == 0)
1748 return NULL;
1749 assert (!(it->b == it->deque->rightblock &&
1750 it->index > it->deque->rightindex));
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001751
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001752 item = it->b->data[it->index];
1753 it->index++;
1754 it->counter--;
1755 if (it->index == BLOCKLEN && it->counter > 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -10001756 CHECK_NOT_END(it->b->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001757 it->b = it->b->rightlink;
1758 it->index = 0;
1759 }
1760 Py_INCREF(item);
1761 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001762}
1763
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001764static PyObject *
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001765dequeiter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1766{
1767 Py_ssize_t i, index=0;
1768 PyObject *deque;
1769 dequeiterobject *it;
1770 if (!PyArg_ParseTuple(args, "O!|n", &deque_type, &deque, &index))
1771 return NULL;
1772 assert(type == &dequeiter_type);
1773
1774 it = (dequeiterobject*)deque_iter((dequeobject *)deque);
1775 if (!it)
1776 return NULL;
1777 /* consume items from the queue */
1778 for(i=0; i<index; i++) {
1779 PyObject *item = dequeiter_next(it);
1780 if (item) {
1781 Py_DECREF(item);
1782 } else {
1783 if (it->counter) {
1784 Py_DECREF(it);
1785 return NULL;
1786 } else
1787 break;
1788 }
1789 }
1790 return (PyObject*)it;
1791}
1792
1793static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301794dequeiter_len(dequeiterobject *it, PyObject *Py_UNUSED(ignored))
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001795{
Antoine Pitrou554f3342010-08-17 18:30:06 +00001796 return PyLong_FromSsize_t(it->counter);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001797}
1798
Armin Rigof5b3e362006-02-11 21:32:43 +00001799PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001800
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001801static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301802dequeiter_reduce(dequeiterobject *it, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001803{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001804 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 +00001805}
1806
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001807static PyMethodDef dequeiter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001808 {"__length_hint__", (PyCFunction)dequeiter_len, METH_NOARGS, length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001809 {"__reduce__", (PyCFunction)dequeiter_reduce, METH_NOARGS, reduce_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001810 {NULL, NULL} /* sentinel */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001811};
1812
Martin v. Löwis59683e82008-06-13 07:50:45 +00001813static PyTypeObject dequeiter_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001814 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger87e69122015-03-02 23:32:02 -08001815 "_collections._deque_iterator", /* tp_name */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001816 sizeof(dequeiterobject), /* tp_basicsize */
1817 0, /* tp_itemsize */
1818 /* methods */
1819 (destructor)dequeiter_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001820 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001821 0, /* tp_getattr */
1822 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001823 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001824 0, /* tp_repr */
1825 0, /* tp_as_number */
1826 0, /* tp_as_sequence */
1827 0, /* tp_as_mapping */
1828 0, /* tp_hash */
1829 0, /* tp_call */
1830 0, /* tp_str */
1831 PyObject_GenericGetAttr, /* tp_getattro */
1832 0, /* tp_setattro */
1833 0, /* tp_as_buffer */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001834 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001835 0, /* tp_doc */
1836 (traverseproc)dequeiter_traverse, /* tp_traverse */
1837 0, /* tp_clear */
1838 0, /* tp_richcompare */
1839 0, /* tp_weaklistoffset */
1840 PyObject_SelfIter, /* tp_iter */
1841 (iternextfunc)dequeiter_next, /* tp_iternext */
1842 dequeiter_methods, /* tp_methods */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001843 0, /* tp_members */
1844 0, /* tp_getset */
1845 0, /* tp_base */
1846 0, /* tp_dict */
1847 0, /* tp_descr_get */
1848 0, /* tp_descr_set */
1849 0, /* tp_dictoffset */
1850 0, /* tp_init */
1851 0, /* tp_alloc */
1852 dequeiter_new, /* tp_new */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001853 0,
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001854};
1855
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001856/*********************** Deque Reverse Iterator **************************/
1857
Martin v. Löwis59683e82008-06-13 07:50:45 +00001858static PyTypeObject dequereviter_type;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001859
1860static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301861deque_reviter(dequeobject *deque, PyObject *Py_UNUSED(ignored))
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001862{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001863 dequeiterobject *it;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001865 it = PyObject_GC_New(dequeiterobject, &dequereviter_type);
1866 if (it == NULL)
1867 return NULL;
1868 it->b = deque->rightblock;
1869 it->index = deque->rightindex;
1870 Py_INCREF(deque);
1871 it->deque = deque;
1872 it->state = deque->state;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001873 it->counter = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001874 PyObject_GC_Track(it);
1875 return (PyObject *)it;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001876}
1877
1878static PyObject *
1879dequereviter_next(dequeiterobject *it)
1880{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001881 PyObject *item;
1882 if (it->counter == 0)
1883 return NULL;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001885 if (it->deque->state != it->state) {
1886 it->counter = 0;
1887 PyErr_SetString(PyExc_RuntimeError,
1888 "deque mutated during iteration");
1889 return NULL;
1890 }
1891 assert (!(it->b == it->deque->leftblock &&
1892 it->index < it->deque->leftindex));
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001894 item = it->b->data[it->index];
1895 it->index--;
1896 it->counter--;
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -07001897 if (it->index < 0 && it->counter > 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -10001898 CHECK_NOT_END(it->b->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001899 it->b = it->b->leftlink;
1900 it->index = BLOCKLEN - 1;
1901 }
1902 Py_INCREF(item);
1903 return item;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001904}
1905
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001906static PyObject *
1907dequereviter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1908{
1909 Py_ssize_t i, index=0;
1910 PyObject *deque;
1911 dequeiterobject *it;
1912 if (!PyArg_ParseTuple(args, "O!|n", &deque_type, &deque, &index))
1913 return NULL;
1914 assert(type == &dequereviter_type);
1915
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301916 it = (dequeiterobject*)deque_reviter((dequeobject *)deque, NULL);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001917 if (!it)
1918 return NULL;
1919 /* consume items from the queue */
1920 for(i=0; i<index; i++) {
1921 PyObject *item = dequereviter_next(it);
1922 if (item) {
1923 Py_DECREF(item);
1924 } else {
1925 if (it->counter) {
1926 Py_DECREF(it);
1927 return NULL;
1928 } else
1929 break;
1930 }
1931 }
1932 return (PyObject*)it;
1933}
1934
Martin v. Löwis59683e82008-06-13 07:50:45 +00001935static PyTypeObject dequereviter_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001936 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger87e69122015-03-02 23:32:02 -08001937 "_collections._deque_reverse_iterator", /* tp_name */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001938 sizeof(dequeiterobject), /* tp_basicsize */
1939 0, /* tp_itemsize */
1940 /* methods */
1941 (destructor)dequeiter_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001942 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001943 0, /* tp_getattr */
1944 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001945 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001946 0, /* tp_repr */
1947 0, /* tp_as_number */
1948 0, /* tp_as_sequence */
1949 0, /* tp_as_mapping */
1950 0, /* tp_hash */
1951 0, /* tp_call */
1952 0, /* tp_str */
1953 PyObject_GenericGetAttr, /* tp_getattro */
1954 0, /* tp_setattro */
1955 0, /* tp_as_buffer */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001956 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001957 0, /* tp_doc */
1958 (traverseproc)dequeiter_traverse, /* tp_traverse */
1959 0, /* tp_clear */
1960 0, /* tp_richcompare */
1961 0, /* tp_weaklistoffset */
1962 PyObject_SelfIter, /* tp_iter */
1963 (iternextfunc)dequereviter_next, /* tp_iternext */
1964 dequeiter_methods, /* tp_methods */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001965 0, /* tp_members */
1966 0, /* tp_getset */
1967 0, /* tp_base */
1968 0, /* tp_dict */
1969 0, /* tp_descr_get */
1970 0, /* tp_descr_set */
1971 0, /* tp_dictoffset */
1972 0, /* tp_init */
1973 0, /* tp_alloc */
1974 dequereviter_new, /* tp_new */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001975 0,
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001976};
1977
Guido van Rossum1968ad32006-02-25 22:38:04 +00001978/* defaultdict type *********************************************************/
1979
1980typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001981 PyDictObject dict;
1982 PyObject *default_factory;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001983} defdictobject;
1984
1985static PyTypeObject defdict_type; /* Forward */
1986
1987PyDoc_STRVAR(defdict_missing_doc,
1988"__missing__(key) # Called by __getitem__ for missing key; pseudo-code:\n\
Guido van Rossumd8faa362007-04-27 19:54:29 +00001989 if self.default_factory is None: raise KeyError((key,))\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00001990 self[key] = value = self.default_factory()\n\
1991 return value\n\
1992");
1993
1994static PyObject *
1995defdict_missing(defdictobject *dd, PyObject *key)
1996{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001997 PyObject *factory = dd->default_factory;
1998 PyObject *value;
1999 if (factory == NULL || factory == Py_None) {
2000 /* XXX Call dict.__missing__(key) */
2001 PyObject *tup;
2002 tup = PyTuple_Pack(1, key);
2003 if (!tup) return NULL;
2004 PyErr_SetObject(PyExc_KeyError, tup);
2005 Py_DECREF(tup);
2006 return NULL;
2007 }
Jeroen Demeyer7f41c8e2019-07-04 12:35:31 +02002008 value = _PyObject_CallNoArg(factory);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002009 if (value == NULL)
2010 return value;
2011 if (PyObject_SetItem((PyObject *)dd, key, value) < 0) {
2012 Py_DECREF(value);
2013 return NULL;
2014 }
2015 return value;
Guido van Rossum1968ad32006-02-25 22:38:04 +00002016}
2017
Brandt Bucher57c9d172020-03-06 09:24:08 -08002018static inline PyObject*
2019new_defdict(defdictobject *dd, PyObject *arg)
2020{
2021 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd),
2022 dd->default_factory ? dd->default_factory : Py_None, arg, NULL);
2023}
2024
Guido van Rossum1968ad32006-02-25 22:38:04 +00002025PyDoc_STRVAR(defdict_copy_doc, "D.copy() -> a shallow copy of D.");
2026
2027static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302028defdict_copy(defdictobject *dd, PyObject *Py_UNUSED(ignored))
Guido van Rossum1968ad32006-02-25 22:38:04 +00002029{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002030 /* This calls the object's class. That only works for subclasses
2031 whose class constructor has the same signature. Subclasses that
2032 define a different constructor signature must override copy().
2033 */
Brandt Bucher57c9d172020-03-06 09:24:08 -08002034 return new_defdict(dd, (PyObject*)dd);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002035}
2036
2037static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302038defdict_reduce(defdictobject *dd, PyObject *Py_UNUSED(ignored))
Guido van Rossum1968ad32006-02-25 22:38:04 +00002039{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002040 /* __reduce__ must return a 5-tuple as follows:
Guido van Rossum1968ad32006-02-25 22:38:04 +00002041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002042 - factory function
2043 - tuple of args for the factory function
2044 - additional state (here None)
2045 - sequence iterator (here None)
2046 - dictionary iterator (yielding successive (key, value) pairs
Guido van Rossum1968ad32006-02-25 22:38:04 +00002047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002048 This API is used by pickle.py and copy.py.
Guido van Rossum1968ad32006-02-25 22:38:04 +00002049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002050 For this to be useful with pickle.py, the default_factory
2051 must be picklable; e.g., None, a built-in, or a global
2052 function in a module or package.
Guido van Rossum1968ad32006-02-25 22:38:04 +00002053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002054 Both shallow and deep copying are supported, but for deep
2055 copying, the default_factory must be deep-copyable; e.g. None,
2056 or a built-in (functions are not copyable at this time).
Guido van Rossum1968ad32006-02-25 22:38:04 +00002057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002058 This only works for subclasses as long as their constructor
2059 signature is compatible; the first argument must be the
2060 optional default_factory, defaulting to None.
2061 */
2062 PyObject *args;
2063 PyObject *items;
2064 PyObject *iter;
2065 PyObject *result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002066 _Py_IDENTIFIER(items);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002068 if (dd->default_factory == NULL || dd->default_factory == Py_None)
2069 args = PyTuple_New(0);
2070 else
2071 args = PyTuple_Pack(1, dd->default_factory);
2072 if (args == NULL)
2073 return NULL;
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002074 items = _PyObject_CallMethodIdNoArgs((PyObject *)dd, &PyId_items);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002075 if (items == NULL) {
2076 Py_DECREF(args);
2077 return NULL;
2078 }
2079 iter = PyObject_GetIter(items);
2080 if (iter == NULL) {
2081 Py_DECREF(items);
2082 Py_DECREF(args);
2083 return NULL;
2084 }
2085 result = PyTuple_Pack(5, Py_TYPE(dd), args,
2086 Py_None, Py_None, iter);
2087 Py_DECREF(iter);
2088 Py_DECREF(items);
2089 Py_DECREF(args);
2090 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00002091}
2092
2093static PyMethodDef defdict_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002094 {"__missing__", (PyCFunction)defdict_missing, METH_O,
2095 defdict_missing_doc},
2096 {"copy", (PyCFunction)defdict_copy, METH_NOARGS,
2097 defdict_copy_doc},
2098 {"__copy__", (PyCFunction)defdict_copy, METH_NOARGS,
2099 defdict_copy_doc},
2100 {"__reduce__", (PyCFunction)defdict_reduce, METH_NOARGS,
2101 reduce_doc},
Guido van Rossum48b069a2020-04-07 09:50:06 -07002102 {"__class_getitem__", (PyCFunction)Py_GenericAlias, METH_O|METH_CLASS,
2103 PyDoc_STR("See PEP 585")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002104 {NULL}
Guido van Rossum1968ad32006-02-25 22:38:04 +00002105};
2106
2107static PyMemberDef defdict_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002108 {"default_factory", T_OBJECT,
2109 offsetof(defdictobject, default_factory), 0,
2110 PyDoc_STR("Factory for default value called by __missing__().")},
2111 {NULL}
Guido van Rossum1968ad32006-02-25 22:38:04 +00002112};
2113
2114static void
2115defdict_dealloc(defdictobject *dd)
2116{
INADA Naokia6296d32017-08-24 14:55:17 +09002117 /* bpo-31095: UnTrack is needed before calling any callbacks */
2118 PyObject_GC_UnTrack(dd);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002119 Py_CLEAR(dd->default_factory);
2120 PyDict_Type.tp_dealloc((PyObject *)dd);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002121}
2122
Guido van Rossum1968ad32006-02-25 22:38:04 +00002123static PyObject *
2124defdict_repr(defdictobject *dd)
2125{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002126 PyObject *baserepr;
2127 PyObject *defrepr;
2128 PyObject *result;
2129 baserepr = PyDict_Type.tp_repr((PyObject *)dd);
2130 if (baserepr == NULL)
2131 return NULL;
2132 if (dd->default_factory == NULL)
2133 defrepr = PyUnicode_FromString("None");
2134 else
2135 {
2136 int status = Py_ReprEnter(dd->default_factory);
2137 if (status != 0) {
Antoine Pitrouf5f1fe02012-02-15 02:42:46 +01002138 if (status < 0) {
2139 Py_DECREF(baserepr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002140 return NULL;
Antoine Pitrouf5f1fe02012-02-15 02:42:46 +01002141 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002142 defrepr = PyUnicode_FromString("...");
2143 }
2144 else
2145 defrepr = PyObject_Repr(dd->default_factory);
2146 Py_ReprLeave(dd->default_factory);
2147 }
2148 if (defrepr == NULL) {
2149 Py_DECREF(baserepr);
2150 return NULL;
2151 }
Serhiy Storchakab3a77962017-09-21 14:24:13 +03002152 result = PyUnicode_FromFormat("%s(%U, %U)",
2153 _PyType_Name(Py_TYPE(dd)),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002154 defrepr, baserepr);
2155 Py_DECREF(defrepr);
2156 Py_DECREF(baserepr);
2157 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00002158}
2159
Brandt Bucher57c9d172020-03-06 09:24:08 -08002160static PyObject*
2161defdict_or(PyObject* left, PyObject* right)
2162{
Brandt Bucher57c9d172020-03-06 09:24:08 -08002163 PyObject *self, *other;
Brandt Bucher1dd37942020-03-11 21:06:46 -07002164 if (PyObject_TypeCheck(left, &defdict_type)) {
Brandt Bucher57c9d172020-03-06 09:24:08 -08002165 self = left;
2166 other = right;
2167 }
2168 else {
2169 self = right;
2170 other = left;
2171 }
2172 if (!PyDict_Check(other)) {
2173 Py_RETURN_NOTIMPLEMENTED;
2174 }
2175 // Like copy(), this calls the object's class.
2176 // Override __or__/__ror__ for subclasses with different constructors.
2177 PyObject *new = new_defdict((defdictobject*)self, left);
2178 if (!new) {
2179 return NULL;
2180 }
2181 if (PyDict_Update(new, right)) {
2182 Py_DECREF(new);
2183 return NULL;
2184 }
2185 return new;
2186}
2187
2188static PyNumberMethods defdict_as_number = {
2189 .nb_or = defdict_or,
2190};
2191
Guido van Rossum1968ad32006-02-25 22:38:04 +00002192static int
2193defdict_traverse(PyObject *self, visitproc visit, void *arg)
2194{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002195 Py_VISIT(((defdictobject *)self)->default_factory);
2196 return PyDict_Type.tp_traverse(self, visit, arg);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002197}
2198
2199static int
2200defdict_tp_clear(defdictobject *dd)
2201{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002202 Py_CLEAR(dd->default_factory);
2203 return PyDict_Type.tp_clear((PyObject *)dd);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002204}
2205
2206static int
2207defdict_init(PyObject *self, PyObject *args, PyObject *kwds)
2208{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002209 defdictobject *dd = (defdictobject *)self;
2210 PyObject *olddefault = dd->default_factory;
2211 PyObject *newdefault = NULL;
2212 PyObject *newargs;
2213 int result;
2214 if (args == NULL || !PyTuple_Check(args))
2215 newargs = PyTuple_New(0);
2216 else {
2217 Py_ssize_t n = PyTuple_GET_SIZE(args);
2218 if (n > 0) {
2219 newdefault = PyTuple_GET_ITEM(args, 0);
2220 if (!PyCallable_Check(newdefault) && newdefault != Py_None) {
2221 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger239aba72015-07-20 03:09:22 -04002222 "first argument must be callable or None");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002223 return -1;
2224 }
2225 }
2226 newargs = PySequence_GetSlice(args, 1, n);
2227 }
2228 if (newargs == NULL)
2229 return -1;
2230 Py_XINCREF(newdefault);
2231 dd->default_factory = newdefault;
2232 result = PyDict_Type.tp_init(self, newargs, kwds);
2233 Py_DECREF(newargs);
2234 Py_XDECREF(olddefault);
2235 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00002236}
2237
2238PyDoc_STRVAR(defdict_doc,
Benjamin Peterson9cb33b72014-01-13 23:56:05 -05002239"defaultdict(default_factory[, ...]) --> dict with default factory\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00002240\n\
2241The default factory is called without arguments to produce\n\
2242a new value when a key is not present, in __getitem__ only.\n\
2243A defaultdict compares equal to a dict with the same items.\n\
Benjamin Peterson9cb33b72014-01-13 23:56:05 -05002244All remaining arguments are treated the same as if they were\n\
2245passed to the dict constructor, including keyword arguments.\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00002246");
2247
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002248/* See comment in xxsubtype.c */
2249#define DEFERRED_ADDRESS(ADDR) 0
2250
Guido van Rossum1968ad32006-02-25 22:38:04 +00002251static PyTypeObject defdict_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002252 PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0)
2253 "collections.defaultdict", /* tp_name */
2254 sizeof(defdictobject), /* tp_basicsize */
2255 0, /* tp_itemsize */
2256 /* methods */
2257 (destructor)defdict_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002258 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002259 0, /* tp_getattr */
2260 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002261 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002262 (reprfunc)defdict_repr, /* tp_repr */
Brandt Bucher57c9d172020-03-06 09:24:08 -08002263 &defdict_as_number, /* tp_as_number */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002264 0, /* tp_as_sequence */
2265 0, /* tp_as_mapping */
2266 0, /* tp_hash */
2267 0, /* tp_call */
2268 0, /* tp_str */
2269 PyObject_GenericGetAttr, /* tp_getattro */
2270 0, /* tp_setattro */
2271 0, /* tp_as_buffer */
2272 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
2273 /* tp_flags */
2274 defdict_doc, /* tp_doc */
2275 defdict_traverse, /* tp_traverse */
2276 (inquiry)defdict_tp_clear, /* tp_clear */
2277 0, /* tp_richcompare */
2278 0, /* tp_weaklistoffset*/
2279 0, /* tp_iter */
2280 0, /* tp_iternext */
2281 defdict_methods, /* tp_methods */
2282 defdict_members, /* tp_members */
2283 0, /* tp_getset */
2284 DEFERRED_ADDRESS(&PyDict_Type), /* tp_base */
2285 0, /* tp_dict */
2286 0, /* tp_descr_get */
2287 0, /* tp_descr_set */
2288 0, /* tp_dictoffset */
2289 defdict_init, /* tp_init */
2290 PyType_GenericAlloc, /* tp_alloc */
2291 0, /* tp_new */
2292 PyObject_GC_Del, /* tp_free */
Guido van Rossum1968ad32006-02-25 22:38:04 +00002293};
2294
Raymond Hettinger96f34102010-12-15 16:30:37 +00002295/* helper function for Counter *********************************************/
2296
Raymond Hettingere9858042019-06-05 16:05:25 -07002297/*[clinic input]
2298_collections._count_elements
2299
2300 mapping: object
2301 iterable: object
2302 /
2303
2304Count elements in the iterable, updating the mapping
2305[clinic start generated code]*/
Raymond Hettinger96f34102010-12-15 16:30:37 +00002306
2307static PyObject *
Raymond Hettingere9858042019-06-05 16:05:25 -07002308_collections__count_elements_impl(PyObject *module, PyObject *mapping,
2309 PyObject *iterable)
2310/*[clinic end generated code: output=7e0c1789636b3d8f input=e79fad04534a0b45]*/
Raymond Hettinger96f34102010-12-15 16:30:37 +00002311{
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002312 _Py_IDENTIFIER(get);
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002313 _Py_IDENTIFIER(__setitem__);
Raymond Hettingere9858042019-06-05 16:05:25 -07002314 PyObject *it, *oldval;
Raymond Hettinger96f34102010-12-15 16:30:37 +00002315 PyObject *newval = NULL;
2316 PyObject *key = NULL;
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002317 PyObject *bound_get = NULL;
2318 PyObject *mapping_get;
2319 PyObject *dict_get;
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002320 PyObject *mapping_setitem;
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002321 PyObject *dict_setitem;
Victor Stinner35b95aa2020-10-27 22:24:33 +01002322 PyObject *one = _PyLong_GetOne(); // borrowed reference
Raymond Hettinger96f34102010-12-15 16:30:37 +00002323
Raymond Hettinger96f34102010-12-15 16:30:37 +00002324 it = PyObject_GetIter(iterable);
2325 if (it == NULL)
2326 return NULL;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002327
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002328 /* Only take the fast path when get() and __setitem__()
2329 * have not been overridden.
2330 */
2331 mapping_get = _PyType_LookupId(Py_TYPE(mapping), &PyId_get);
2332 dict_get = _PyType_LookupId(&PyDict_Type, &PyId_get);
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002333 mapping_setitem = _PyType_LookupId(Py_TYPE(mapping), &PyId___setitem__);
2334 dict_setitem = _PyType_LookupId(&PyDict_Type, &PyId___setitem__);
2335
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002336 if (mapping_get != NULL && mapping_get == dict_get &&
Oren Milman31aca4b2017-09-27 06:18:21 +03002337 mapping_setitem != NULL && mapping_setitem == dict_setitem &&
2338 PyDict_Check(mapping))
2339 {
Raymond Hettinger426e0522011-01-03 02:12:02 +00002340 while (1) {
Raymond Hettinger507d9972014-05-18 21:32:40 +01002341 /* Fast path advantages:
2342 1. Eliminate double hashing
2343 (by re-using the same hash for both the get and set)
2344 2. Avoid argument overhead of PyObject_CallFunctionObjArgs
2345 (argument tuple creation and parsing)
2346 3. Avoid indirection through a bound method object
2347 (creates another argument tuple)
2348 4. Avoid initial increment from zero
2349 (reuse an existing one-object instead)
2350 */
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002351 Py_hash_t hash;
2352
Raymond Hettinger426e0522011-01-03 02:12:02 +00002353 key = PyIter_Next(it);
Victor Stinnera154b5c2011-04-20 23:23:52 +02002354 if (key == NULL)
2355 break;
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002356
2357 if (!PyUnicode_CheckExact(key) ||
2358 (hash = ((PyASCIIObject *) key)->hash) == -1)
2359 {
2360 hash = PyObject_Hash(key);
Raymond Hettingerda2850f2015-02-27 12:42:54 -08002361 if (hash == -1)
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002362 goto done;
2363 }
2364
2365 oldval = _PyDict_GetItem_KnownHash(mapping, key, hash);
Raymond Hettinger426e0522011-01-03 02:12:02 +00002366 if (oldval == NULL) {
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02002367 if (PyErr_Occurred())
2368 goto done;
Victor Stinner35b95aa2020-10-27 22:24:33 +01002369 if (_PyDict_SetItem_KnownHash(mapping, key, one, hash) < 0)
Raymond Hettinger507d9972014-05-18 21:32:40 +01002370 goto done;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002371 } else {
Victor Stinner35b95aa2020-10-27 22:24:33 +01002372 newval = PyNumber_Add(oldval, one);
Raymond Hettinger426e0522011-01-03 02:12:02 +00002373 if (newval == NULL)
Raymond Hettinger507d9972014-05-18 21:32:40 +01002374 goto done;
Raymond Hettinger28c995d2015-08-14 02:07:41 -07002375 if (_PyDict_SetItem_KnownHash(mapping, key, newval, hash) < 0)
Raymond Hettinger507d9972014-05-18 21:32:40 +01002376 goto done;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002377 Py_CLEAR(newval);
2378 }
2379 Py_DECREF(key);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002380 }
Victor Stinner35b95aa2020-10-27 22:24:33 +01002381 }
2382 else {
Victor Stinnere7f516c2013-11-06 23:52:55 +01002383 bound_get = _PyObject_GetAttrId(mapping, &PyId_get);
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002384 if (bound_get == NULL)
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002385 goto done;
2386
Victor Stinner37834132020-10-27 17:12:53 +01002387 PyObject *zero = _PyLong_GetZero(); // borrowed reference
Raymond Hettinger426e0522011-01-03 02:12:02 +00002388 while (1) {
2389 key = PyIter_Next(it);
Victor Stinnera154b5c2011-04-20 23:23:52 +02002390 if (key == NULL)
2391 break;
Victor Stinner37834132020-10-27 17:12:53 +01002392 oldval = PyObject_CallFunctionObjArgs(bound_get, key, zero, NULL);
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002393 if (oldval == NULL)
2394 break;
Victor Stinner37834132020-10-27 17:12:53 +01002395 newval = PyNumber_Add(oldval, one);
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002396 Py_DECREF(oldval);
2397 if (newval == NULL)
2398 break;
Raymond Hettinger28c995d2015-08-14 02:07:41 -07002399 if (PyObject_SetItem(mapping, key, newval) < 0)
Raymond Hettinger96f34102010-12-15 16:30:37 +00002400 break;
2401 Py_CLEAR(newval);
Raymond Hettinger426e0522011-01-03 02:12:02 +00002402 Py_DECREF(key);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002403 }
Raymond Hettinger96f34102010-12-15 16:30:37 +00002404 }
Raymond Hettinger426e0522011-01-03 02:12:02 +00002405
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002406done:
Raymond Hettinger96f34102010-12-15 16:30:37 +00002407 Py_DECREF(it);
2408 Py_XDECREF(key);
2409 Py_XDECREF(newval);
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002410 Py_XDECREF(bound_get);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002411 if (PyErr_Occurred())
2412 return NULL;
2413 Py_RETURN_NONE;
2414}
2415
Serhiy Storchaka052b2df2018-12-31 14:15:16 +02002416/* Helper function for namedtuple() ************************************/
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002417
2418typedef struct {
2419 PyObject_HEAD
2420 Py_ssize_t index;
2421 PyObject* doc;
2422} _tuplegetterobject;
2423
2424/*[clinic input]
2425@classmethod
2426_tuplegetter.__new__ as tuplegetter_new
2427
2428 index: Py_ssize_t
2429 doc: object
2430 /
2431[clinic start generated code]*/
2432
2433static PyObject *
2434tuplegetter_new_impl(PyTypeObject *type, Py_ssize_t index, PyObject *doc)
2435/*[clinic end generated code: output=014be444ad80263f input=87c576a5bdbc0bbb]*/
2436{
2437 _tuplegetterobject* self;
2438 self = (_tuplegetterobject *)type->tp_alloc(type, 0);
2439 if (self == NULL) {
2440 return NULL;
2441 }
2442 self->index = index;
2443 Py_INCREF(doc);
2444 self->doc = doc;
2445 return (PyObject *)self;
2446}
2447
2448static PyObject *
Serhiy Storchaka052b2df2018-12-31 14:15:16 +02002449tuplegetter_descr_get(PyObject *self, PyObject *obj, PyObject *type)
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002450{
Serhiy Storchaka052b2df2018-12-31 14:15:16 +02002451 Py_ssize_t index = ((_tuplegetterobject*)self)->index;
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002452 PyObject *result;
Serhiy Storchaka052b2df2018-12-31 14:15:16 +02002453
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002454 if (obj == NULL) {
2455 Py_INCREF(self);
2456 return self;
2457 }
2458 if (!PyTuple_Check(obj)) {
2459 if (obj == Py_None) {
2460 Py_INCREF(self);
2461 return self;
2462 }
2463 PyErr_Format(PyExc_TypeError,
Serhiy Storchakad53fe5f2019-03-13 22:59:55 +02002464 "descriptor for index '%zd' for tuple subclasses "
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002465 "doesn't apply to '%s' object",
Serhiy Storchaka052b2df2018-12-31 14:15:16 +02002466 index,
Victor Stinnerdaa97562020-02-07 03:37:06 +01002467 Py_TYPE(obj)->tp_name);
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002468 return NULL;
2469 }
2470
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002471 if (!valid_index(index, PyTuple_GET_SIZE(obj))) {
2472 PyErr_SetString(PyExc_IndexError, "tuple index out of range");
2473 return NULL;
2474 }
2475
2476 result = PyTuple_GET_ITEM(obj, index);
2477 Py_INCREF(result);
2478 return result;
2479}
2480
2481static int
Serhiy Storchaka052b2df2018-12-31 14:15:16 +02002482tuplegetter_descr_set(PyObject *self, PyObject *obj, PyObject *value)
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002483{
2484 if (value == NULL) {
2485 PyErr_SetString(PyExc_AttributeError, "can't delete attribute");
2486 } else {
2487 PyErr_SetString(PyExc_AttributeError, "can't set attribute");
2488 }
2489 return -1;
2490}
2491
2492static int
2493tuplegetter_traverse(PyObject *self, visitproc visit, void *arg)
2494{
2495 _tuplegetterobject *tuplegetter = (_tuplegetterobject *)self;
2496 Py_VISIT(tuplegetter->doc);
2497 return 0;
2498}
2499
2500static int
2501tuplegetter_clear(PyObject *self)
2502{
2503 _tuplegetterobject *tuplegetter = (_tuplegetterobject *)self;
2504 Py_CLEAR(tuplegetter->doc);
2505 return 0;
2506}
2507
2508static void
2509tuplegetter_dealloc(_tuplegetterobject *self)
2510{
2511 PyObject_GC_UnTrack(self);
2512 tuplegetter_clear((PyObject*)self);
2513 Py_TYPE(self)->tp_free((PyObject*)self);
2514}
2515
Joe Jevnikf36f8922019-02-21 16:00:40 -05002516static PyObject*
Serhiy Storchakaadfffc72019-03-05 18:41:09 +02002517tuplegetter_reduce(_tuplegetterobject *self, PyObject *Py_UNUSED(ignored))
Joe Jevnikf36f8922019-02-21 16:00:40 -05002518{
2519 return Py_BuildValue("(O(nO))", (PyObject*) Py_TYPE(self), self->index, self->doc);
2520}
2521
Ammar Askara86b5222020-04-14 23:36:08 -07002522static PyObject*
2523tuplegetter_repr(_tuplegetterobject *self)
2524{
2525 return PyUnicode_FromFormat("%s(%zd, %R)",
2526 _PyType_Name(Py_TYPE(self)),
2527 self->index, self->doc);
2528}
2529
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002530
2531static PyMemberDef tuplegetter_members[] = {
2532 {"__doc__", T_OBJECT, offsetof(_tuplegetterobject, doc), 0},
2533 {0}
2534};
2535
Joe Jevnikf36f8922019-02-21 16:00:40 -05002536static PyMethodDef tuplegetter_methods[] = {
Serhiy Storchakaadfffc72019-03-05 18:41:09 +02002537 {"__reduce__", (PyCFunction)tuplegetter_reduce, METH_NOARGS, NULL},
Joe Jevnikf36f8922019-02-21 16:00:40 -05002538 {NULL},
2539};
2540
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002541static PyTypeObject tuplegetter_type = {
2542 PyVarObject_HEAD_INIT(NULL, 0)
2543 "_collections._tuplegetter", /* tp_name */
2544 sizeof(_tuplegetterobject), /* tp_basicsize */
2545 0, /* tp_itemsize */
2546 /* methods */
2547 (destructor)tuplegetter_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002548 0, /* tp_vectorcall_offset */
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002549 0, /* tp_getattr */
2550 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002551 0, /* tp_as_async */
Ammar Askara86b5222020-04-14 23:36:08 -07002552 (reprfunc)tuplegetter_repr, /* tp_repr */
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002553 0, /* tp_as_number */
2554 0, /* tp_as_sequence */
2555 0, /* tp_as_mapping */
2556 0, /* tp_hash */
2557 0, /* tp_call */
2558 0, /* tp_str */
2559 0, /* tp_getattro */
2560 0, /* tp_setattro */
2561 0, /* tp_as_buffer */
2562 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
2563 0, /* tp_doc */
2564 (traverseproc)tuplegetter_traverse, /* tp_traverse */
2565 (inquiry)tuplegetter_clear, /* tp_clear */
2566 0, /* tp_richcompare */
2567 0, /* tp_weaklistoffset */
2568 0, /* tp_iter */
2569 0, /* tp_iternext */
Joe Jevnikf36f8922019-02-21 16:00:40 -05002570 tuplegetter_methods, /* tp_methods */
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002571 tuplegetter_members, /* tp_members */
2572 0, /* tp_getset */
2573 0, /* tp_base */
2574 0, /* tp_dict */
Serhiy Storchaka052b2df2018-12-31 14:15:16 +02002575 tuplegetter_descr_get, /* tp_descr_get */
2576 tuplegetter_descr_set, /* tp_descr_set */
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002577 0, /* tp_dictoffset */
2578 0, /* tp_init */
2579 0, /* tp_alloc */
2580 tuplegetter_new, /* tp_new */
2581 0,
2582};
2583
2584
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002585/* module level code ********************************************************/
2586
Dong-hee Na77248a22020-03-20 01:16:04 +09002587PyDoc_STRVAR(collections_doc,
Guido van Rossum1968ad32006-02-25 22:38:04 +00002588"High performance data structures.\n\
2589- deque: ordered collection accessible from endpoints only\n\
2590- defaultdict: dict subclass with a default value factory\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002591");
2592
Dong-hee Na77248a22020-03-20 01:16:04 +09002593static struct PyMethodDef collections_methods[] = {
Raymond Hettingere9858042019-06-05 16:05:25 -07002594 _COLLECTIONS__COUNT_ELEMENTS_METHODDEF
Raymond Hettinger96f34102010-12-15 16:30:37 +00002595 {NULL, NULL} /* sentinel */
2596};
Martin v. Löwis1a214512008-06-11 05:26:20 +00002597
Dong-hee Na77248a22020-03-20 01:16:04 +09002598static int
2599collections_exec(PyObject *module) {
2600 PyTypeObject *typelist[] = {
2601 &deque_type,
2602 &defdict_type,
2603 &PyODict_Type,
2604 &dequeiter_type,
2605 &dequereviter_type,
Dong-hee Na05e4a292020-03-23 01:17:34 +09002606 &tuplegetter_type
Dong-hee Na77248a22020-03-20 01:16:04 +09002607 };
2608
2609 defdict_type.tp_base = &PyDict_Type;
2610
Dong-hee Na05e4a292020-03-23 01:17:34 +09002611 for (size_t i = 0; i < Py_ARRAY_LENGTH(typelist); i++) {
2612 if (PyModule_AddType(module, typelist[i]) < 0) {
Dong-hee Na77248a22020-03-20 01:16:04 +09002613 return -1;
2614 }
2615 }
2616
2617 return 0;
2618}
2619
2620static struct PyModuleDef_Slot collections_slots[] = {
2621 {Py_mod_exec, collections_exec},
2622 {0, NULL}
2623};
2624
Martin v. Löwis1a214512008-06-11 05:26:20 +00002625static struct PyModuleDef _collectionsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002626 PyModuleDef_HEAD_INIT,
2627 "_collections",
Dong-hee Na77248a22020-03-20 01:16:04 +09002628 collections_doc,
2629 0,
2630 collections_methods,
2631 collections_slots,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002632 NULL,
2633 NULL,
2634 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002635};
2636
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002637PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002638PyInit__collections(void)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002639{
Dong-hee Na77248a22020-03-20 01:16:04 +09002640 return PyModuleDef_Init(&_collectionsmodule);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002641}