blob: a495e5f718f82b3de2a923a3d6878ec41dcd4898 [file] [log] [blame]
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001#include "Python.h"
Raymond Hettinger691d8052004-05-30 07:26:47 +00002#include "structmember.h"
Raymond Hettinger756b3f32004-01-29 06:37:52 +00003
Raymond Hettingerc2083082015-02-28 23:29:16 -08004#ifdef STDC_HEADERS
5#include <stddef.h>
6#else
7#include <sys/types.h> /* For size_t */
8#endif
9
Raymond Hettinger756b3f32004-01-29 06:37:52 +000010/* collections module implementation of a deque() datatype
11 Written and maintained by Raymond D. Hettinger <python@rcn.com>
Raymond Hettinger756b3f32004-01-29 06:37:52 +000012*/
13
Raymond Hettinger77e8bf12004-10-01 15:25:53 +000014/* The block length may be set to any number over 1. Larger numbers
Raymond Hettinger20b0f872013-06-23 15:44:33 -070015 * reduce the number of calls to the memory allocator, give faster
Raymond Hettinger30c90742015-03-02 22:31:35 -080016 * indexing and rotation, and reduce the link to data overhead ratio.
Raymond Hettingerdaf57f22015-02-26 23:21:29 -080017 * Making the block length a power of two speeds-up the modulo
Raymond Hettinger30c90742015-03-02 22:31:35 -080018 * and division calculations in deque_item() and deque_ass_item().
Raymond Hettinger77e8bf12004-10-01 15:25:53 +000019 */
20
Raymond Hettingerdaf57f22015-02-26 23:21:29 -080021#define BLOCKLEN 64
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000022#define CENTER ((BLOCKLEN - 1) / 2)
Raymond Hettinger756b3f32004-01-29 06:37:52 +000023
Raymond Hettinger551350a2015-03-24 00:19:53 -070024/* Data for deque objects is stored in a doubly-linked list of fixed
25 * length blocks. This assures that appends or pops never move any
26 * other data elements besides the one being appended or popped.
27 *
28 * Another advantage is that it completely avoids use of realloc(),
29 * resulting in more predictable performance.
30 *
31 * Textbook implementations of doubly-linked lists store one datum
32 * per link, but that gives them a 200% memory overhead (a prev and
33 * next link for each datum) and it costs one malloc() call per data
34 * element. By using fixed-length blocks, the link to data ratio is
35 * significantly improved and there are proportionally fewer calls
36 * to malloc() and free(). The data blocks of consecutive pointers
37 * also improve cache locality.
38 *
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000039 * The list of blocks is never empty, so d.leftblock and d.rightblock
Raymond Hettinger82df9252013-07-07 01:43:42 -100040 * are never equal to NULL. The list is not circular.
41 *
42 * A deque d's first element is at d.leftblock[leftindex]
43 * and its last element is at d.rightblock[rightindex].
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000044 *
Raymond Hettinger551350a2015-03-24 00:19:53 -070045 * Unlike Python slice indices, these indices are inclusive on both
46 * ends. This makes the algorithms for left and right operations
47 * more symmetrical and it simplifies the design.
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000048 *
Raymond Hettinger551350a2015-03-24 00:19:53 -070049 * The indices, d.leftindex and d.rightindex are always in the range:
50 * 0 <= index < BLOCKLEN
51 *
52 * And their exact relationship is:
53 * (d.leftindex + d.len - 1) % BLOCKLEN == d.rightindex
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000054 *
Raymond Hettinger8dbbae22015-03-24 21:01:50 -070055 * Whenever d.leftblock == d.rightblock, then:
Raymond Hettinger551350a2015-03-24 00:19:53 -070056 * d.leftindex + d.len - 1 == d.rightindex
Thomas Wouters0e3f5912006-08-11 14:57:12 +000057 *
Raymond Hettinger551350a2015-03-24 00:19:53 -070058 * However, when d.leftblock != d.rightblock, the d.leftindex and
59 * d.rightindex become indices into distinct blocks and either may
60 * be larger than the other.
61 *
62 * Empty deques have:
63 * d.len == 0
64 * d.leftblock == d.rightblock
65 * d.leftindex == CENTER + 1
66 * d.rightindex == CENTER
67 *
68 * Checking for d.len == 0 is the intended way to see whether d is empty.
Tim Petersd8768d32004-10-01 01:32:53 +000069 */
70
Raymond Hettinger756b3f32004-01-29 06:37:52 +000071typedef struct BLOCK {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000072 struct BLOCK *leftlink;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000073 PyObject *data[BLOCKLEN];
Raymond Hettinger20b0f872013-06-23 15:44:33 -070074 struct BLOCK *rightlink;
Raymond Hettinger756b3f32004-01-29 06:37:52 +000075} block;
76
Raymond Hettinger30c90742015-03-02 22:31:35 -080077typedef struct {
78 PyObject_VAR_HEAD
79 block *leftblock;
80 block *rightblock;
Raymond Hettinger551350a2015-03-24 00:19:53 -070081 Py_ssize_t leftindex; /* 0 <= leftindex < BLOCKLEN */
82 Py_ssize_t rightindex; /* 0 <= rightindex < BLOCKLEN */
Raymond Hettingerf9d9c792015-03-02 22:47:46 -080083 size_t state; /* incremented whenever the indices move */
Raymond Hettingerd84ec222016-01-24 09:12:06 -080084 Py_ssize_t maxlen; /* maxlen is -1 for unbounded deques */
Raymond Hettinger0f6f9472015-03-21 01:42:10 -070085 PyObject *weakreflist;
Raymond Hettinger30c90742015-03-02 22:31:35 -080086} dequeobject;
87
88static PyTypeObject deque_type;
89
Raymond Hettinger82df9252013-07-07 01:43:42 -100090/* For debug builds, add error checking to track the endpoints
91 * in the chain of links. The goal is to make sure that link
92 * assignments only take place at endpoints so that links already
93 * in use do not get overwritten.
94 *
95 * CHECK_END should happen before each assignment to a block's link field.
96 * MARK_END should happen whenever a link field becomes a new endpoint.
97 * This happens when new blocks are added or whenever an existing
98 * block is freed leaving another existing block as the new endpoint.
99 */
100
Raymond Hettinger3223dd52013-07-26 23:14:22 -0700101#ifndef NDEBUG
Raymond Hettinger82df9252013-07-07 01:43:42 -1000102#define MARK_END(link) link = NULL;
103#define CHECK_END(link) assert(link == NULL);
104#define CHECK_NOT_END(link) assert(link != NULL);
105#else
106#define MARK_END(link)
107#define CHECK_END(link)
108#define CHECK_NOT_END(link)
109#endif
110
111/* A simple freelisting scheme is used to minimize calls to the memory
Raymond Hettinger551350a2015-03-24 00:19:53 -0700112 allocator. It accommodates common use cases where new blocks are being
Raymond Hettinger82df9252013-07-07 01:43:42 -1000113 added at about the same rate as old blocks are being freed.
114 */
115
Raymond Hettingerf2b02ce2015-09-26 17:47:02 -0700116#define MAXFREEBLOCKS 16
Benjamin Petersond6313712008-07-31 16:23:04 +0000117static Py_ssize_t numfreeblocks = 0;
Guido van Rossum58da9312007-11-10 23:39:45 +0000118static block *freeblocks[MAXFREEBLOCKS];
119
Tim Peters6f853562004-10-01 01:04:50 +0000120static block *
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700121newblock(void) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000122 block *b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000123 if (numfreeblocks) {
Raymond Hettinger59cf23a2013-02-07 00:57:19 -0500124 numfreeblocks--;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000125 return freeblocks[numfreeblocks];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000126 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000127 b = PyMem_Malloc(sizeof(block));
128 if (b != NULL) {
129 return b;
130 }
131 PyErr_NoMemory();
132 return NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000133}
134
Martin v. Löwis59683e82008-06-13 07:50:45 +0000135static void
Guido van Rossum58da9312007-11-10 23:39:45 +0000136freeblock(block *b)
137{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000138 if (numfreeblocks < MAXFREEBLOCKS) {
139 freeblocks[numfreeblocks] = b;
140 numfreeblocks++;
141 } else {
142 PyMem_Free(b);
143 }
Guido van Rossum58da9312007-11-10 23:39:45 +0000144}
145
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000146static PyObject *
147deque_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
148{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000149 dequeobject *deque;
150 block *b;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000152 /* create dequeobject structure */
153 deque = (dequeobject *)type->tp_alloc(type, 0);
154 if (deque == NULL)
155 return NULL;
Tim Peters1065f752004-10-01 01:03:29 +0000156
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700157 b = newblock();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000158 if (b == NULL) {
159 Py_DECREF(deque);
160 return NULL;
161 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000162 MARK_END(b->leftlink);
163 MARK_END(b->rightlink);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000165 assert(BLOCKLEN >= 2);
Raymond Hettinger87e69122015-03-02 23:32:02 -0800166 Py_SIZE(deque) = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000167 deque->leftblock = b;
168 deque->rightblock = b;
169 deque->leftindex = CENTER + 1;
170 deque->rightindex = CENTER;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000171 deque->state = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000172 deque->maxlen = -1;
Raymond Hettinger87e69122015-03-02 23:32:02 -0800173 deque->weakreflist = NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175 return (PyObject *)deque;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000176}
177
178static PyObject *
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000179deque_pop(dequeobject *deque, PyObject *unused)
180{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000181 PyObject *item;
182 block *prevblock;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000183
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000184 if (Py_SIZE(deque) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000185 PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
186 return NULL;
187 }
188 item = deque->rightblock->data[deque->rightindex];
189 deque->rightindex--;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000190 Py_SIZE(deque)--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000191 deque->state++;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000192
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -0700193 if (deque->rightindex < 0) {
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700194 if (Py_SIZE(deque)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000195 prevblock = deque->rightblock->leftlink;
196 assert(deque->leftblock != deque->rightblock);
197 freeblock(deque->rightblock);
Raymond Hettinger82df9252013-07-07 01:43:42 -1000198 CHECK_NOT_END(prevblock);
199 MARK_END(prevblock->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000200 deque->rightblock = prevblock;
201 deque->rightindex = BLOCKLEN - 1;
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700202 } else {
203 assert(deque->leftblock == deque->rightblock);
204 assert(deque->leftindex == deque->rightindex+1);
205 /* re-center instead of freeing a block */
206 deque->leftindex = CENTER + 1;
207 deque->rightindex = CENTER;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000208 }
209 }
210 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000211}
212
213PyDoc_STRVAR(pop_doc, "Remove and return the rightmost element.");
214
215static PyObject *
216deque_popleft(dequeobject *deque, PyObject *unused)
217{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000218 PyObject *item;
219 block *prevblock;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000220
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000221 if (Py_SIZE(deque) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000222 PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
223 return NULL;
224 }
225 assert(deque->leftblock != NULL);
226 item = deque->leftblock->data[deque->leftindex];
227 deque->leftindex++;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000228 Py_SIZE(deque)--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000229 deque->state++;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000231 if (deque->leftindex == BLOCKLEN) {
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700232 if (Py_SIZE(deque)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000233 assert(deque->leftblock != deque->rightblock);
234 prevblock = deque->leftblock->rightlink;
235 freeblock(deque->leftblock);
Raymond Hettinger82df9252013-07-07 01:43:42 -1000236 CHECK_NOT_END(prevblock);
237 MARK_END(prevblock->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000238 deque->leftblock = prevblock;
239 deque->leftindex = 0;
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700240 } else {
241 assert(deque->leftblock == deque->rightblock);
242 assert(deque->leftindex == deque->rightindex+1);
243 /* re-center instead of freeing a block */
244 deque->leftindex = CENTER + 1;
245 deque->rightindex = CENTER;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000246 }
247 }
248 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000249}
250
251PyDoc_STRVAR(popleft_doc, "Remove and return the leftmost element.");
252
Raymond Hettingerf30f5b92015-03-02 22:23:37 -0800253/* The deque's size limit is d.maxlen. The limit can be zero or positive.
254 * If there is no limit, then d.maxlen == -1.
255 *
Raymond Hettingera4b13d02015-10-15 08:05:31 -0700256 * After an item is added to a deque, we check to see if the size has
257 * grown past the limit. If it has, we get the size back down to the limit
258 * by popping an item off of the opposite end. The methods that can
259 * trigger this are append(), appendleft(), extend(), and extendleft().
Raymond Hettingerd96db092015-10-11 22:34:48 -0700260 *
261 * The macro to check whether a deque needs to be trimmed uses a single
262 * unsigned test that returns true whenever 0 <= maxlen < Py_SIZE(deque).
Raymond Hettingerf30f5b92015-03-02 22:23:37 -0800263 */
264
Raymond Hettingerd96db092015-10-11 22:34:48 -0700265#define NEEDS_TRIM(deque, maxlen) ((size_t)(maxlen) < (size_t)(Py_SIZE(deque)))
Raymond Hettingerf30f5b92015-03-02 22:23:37 -0800266
Raymond Hettinger66953f02018-07-10 04:17:40 -0700267static inline int
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800268deque_append_internal(dequeobject *deque, PyObject *item, Py_ssize_t maxlen)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000269{
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700270 if (deque->rightindex == BLOCKLEN - 1) {
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700271 block *b = newblock();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000272 if (b == NULL)
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800273 return -1;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000274 b->leftlink = deque->rightblock;
275 CHECK_END(deque->rightblock->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000276 deque->rightblock->rightlink = b;
277 deque->rightblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000278 MARK_END(b->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000279 deque->rightindex = -1;
280 }
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000281 Py_SIZE(deque)++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000282 deque->rightindex++;
283 deque->rightblock->data[deque->rightindex] = item;
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800284 if (NEEDS_TRIM(deque, maxlen)) {
Raymond Hettinger1286d142015-10-14 23:16:57 -0700285 PyObject *olditem = deque_popleft(deque, NULL);
286 Py_DECREF(olditem);
Raymond Hettinger0f43bb12015-10-20 00:03:33 -0700287 } else {
288 deque->state++;
Raymond Hettingerd96db092015-10-11 22:34:48 -0700289 }
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800290 return 0;
291}
292
293static PyObject *
294deque_append(dequeobject *deque, PyObject *item)
295{
296 Py_INCREF(item);
297 if (deque_append_internal(deque, item, deque->maxlen) < 0)
298 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000299 Py_RETURN_NONE;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000300}
301
302PyDoc_STRVAR(append_doc, "Add an element to the right side of the deque.");
303
Raymond Hettinger66953f02018-07-10 04:17:40 -0700304static inline int
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800305deque_appendleft_internal(dequeobject *deque, PyObject *item, Py_ssize_t maxlen)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000306{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000307 if (deque->leftindex == 0) {
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700308 block *b = newblock();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000309 if (b == NULL)
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800310 return -1;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000311 b->rightlink = deque->leftblock;
312 CHECK_END(deque->leftblock->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000313 deque->leftblock->leftlink = b;
314 deque->leftblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000315 MARK_END(b->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000316 deque->leftindex = BLOCKLEN;
317 }
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000318 Py_SIZE(deque)++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000319 deque->leftindex--;
320 deque->leftblock->data[deque->leftindex] = item;
Raymond Hettingerd96db092015-10-11 22:34:48 -0700321 if (NEEDS_TRIM(deque, deque->maxlen)) {
Raymond Hettinger1286d142015-10-14 23:16:57 -0700322 PyObject *olditem = deque_pop(deque, NULL);
323 Py_DECREF(olditem);
Raymond Hettinger0f43bb12015-10-20 00:03:33 -0700324 } else {
325 deque->state++;
Raymond Hettingerd96db092015-10-11 22:34:48 -0700326 }
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800327 return 0;
328}
329
330static PyObject *
331deque_appendleft(dequeobject *deque, PyObject *item)
332{
333 Py_INCREF(item);
334 if (deque_appendleft_internal(deque, item, deque->maxlen) < 0)
335 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000336 Py_RETURN_NONE;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000337}
338
339PyDoc_STRVAR(appendleft_doc, "Add an element to the left side of the deque.");
340
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700341static PyObject*
342finalize_iterator(PyObject *it)
343{
344 if (PyErr_Occurred()) {
345 if (PyErr_ExceptionMatches(PyExc_StopIteration))
346 PyErr_Clear();
347 else {
348 Py_DECREF(it);
349 return NULL;
350 }
351 }
352 Py_DECREF(it);
353 Py_RETURN_NONE;
354}
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000356/* Run an iterator to exhaustion. Shortcut for
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000357 the extend/extendleft methods when maxlen == 0. */
358static PyObject*
359consume_iterator(PyObject *it)
360{
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700361 PyObject *(*iternext)(PyObject *);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000362 PyObject *item;
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000363
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700364 iternext = *Py_TYPE(it)->tp_iternext;
365 while ((item = iternext(it)) != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000366 Py_DECREF(item);
367 }
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700368 return finalize_iterator(it);
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000369}
370
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000371static PyObject *
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000372deque_extend(dequeobject *deque, PyObject *iterable)
373{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000374 PyObject *it, *item;
Raymond Hettinger7a845522015-09-26 01:30:51 -0700375 PyObject *(*iternext)(PyObject *);
Raymond Hettinger6b1e1132015-10-11 09:43:50 -0700376 Py_ssize_t maxlen = deque->maxlen;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000378 /* Handle case where id(deque) == id(iterable) */
379 if ((PyObject *)deque == iterable) {
380 PyObject *result;
381 PyObject *s = PySequence_List(iterable);
382 if (s == NULL)
383 return NULL;
384 result = deque_extend(deque, s);
385 Py_DECREF(s);
386 return result;
387 }
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000388
Raymond Hettingerd79d5b12016-03-04 09:55:07 -0800389 it = PyObject_GetIter(iterable);
390 if (it == NULL)
391 return NULL;
392
393 if (maxlen == 0)
394 return consume_iterator(it);
395
Raymond Hettingerd9c116c2013-07-09 00:13:21 -0700396 /* Space saving heuristic. Start filling from the left */
397 if (Py_SIZE(deque) == 0) {
398 assert(deque->leftblock == deque->rightblock);
399 assert(deque->leftindex == deque->rightindex+1);
400 deque->leftindex = 1;
401 deque->rightindex = 0;
402 }
403
Raymond Hettinger7a845522015-09-26 01:30:51 -0700404 iternext = *Py_TYPE(it)->tp_iternext;
405 while ((item = iternext(it)) != NULL) {
Raymond Hettinger66953f02018-07-10 04:17:40 -0700406 if (deque_append_internal(deque, item, maxlen) == -1) {
407 Py_DECREF(item);
408 Py_DECREF(it);
409 return NULL;
Raymond Hettinger6b1e1132015-10-11 09:43:50 -0700410 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 }
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700412 return finalize_iterator(it);
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000413}
414
Tim Peters1065f752004-10-01 01:03:29 +0000415PyDoc_STRVAR(extend_doc,
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000416"Extend the right side of the deque with elements from the iterable");
417
418static PyObject *
419deque_extendleft(dequeobject *deque, PyObject *iterable)
420{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 PyObject *it, *item;
Raymond Hettinger7a845522015-09-26 01:30:51 -0700422 PyObject *(*iternext)(PyObject *);
Raymond Hettinger6b1e1132015-10-11 09:43:50 -0700423 Py_ssize_t maxlen = deque->maxlen;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425 /* Handle case where id(deque) == id(iterable) */
426 if ((PyObject *)deque == iterable) {
427 PyObject *result;
428 PyObject *s = PySequence_List(iterable);
429 if (s == NULL)
430 return NULL;
431 result = deque_extendleft(deque, s);
432 Py_DECREF(s);
433 return result;
434 }
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000435
Raymond Hettingerd79d5b12016-03-04 09:55:07 -0800436 it = PyObject_GetIter(iterable);
437 if (it == NULL)
438 return NULL;
439
440 if (maxlen == 0)
441 return consume_iterator(it);
442
Raymond Hettingerd9c116c2013-07-09 00:13:21 -0700443 /* Space saving heuristic. Start filling from the right */
444 if (Py_SIZE(deque) == 0) {
445 assert(deque->leftblock == deque->rightblock);
446 assert(deque->leftindex == deque->rightindex+1);
447 deque->leftindex = BLOCKLEN - 1;
448 deque->rightindex = BLOCKLEN - 2;
449 }
450
Raymond Hettinger7a845522015-09-26 01:30:51 -0700451 iternext = *Py_TYPE(it)->tp_iternext;
452 while ((item = iternext(it)) != NULL) {
Raymond Hettinger66953f02018-07-10 04:17:40 -0700453 if (deque_appendleft_internal(deque, item, maxlen) == -1) {
454 Py_DECREF(item);
455 Py_DECREF(it);
456 return NULL;
Raymond Hettinger6b1e1132015-10-11 09:43:50 -0700457 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000458 }
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700459 return finalize_iterator(it);
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000460}
461
Tim Peters1065f752004-10-01 01:03:29 +0000462PyDoc_STRVAR(extendleft_doc,
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000463"Extend the left side of the deque with elements from the iterable");
464
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000465static PyObject *
466deque_inplace_concat(dequeobject *deque, PyObject *other)
467{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000468 PyObject *result;
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000470 result = deque_extend(deque, other);
471 if (result == NULL)
472 return result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000473 Py_INCREF(deque);
Raymond Hettinger2b2b7532015-09-05 17:05:52 -0700474 Py_DECREF(result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000475 return (PyObject *)deque;
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000476}
477
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700478static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530479deque_copy(PyObject *deque, PyObject *Py_UNUSED(ignored))
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700480{
Oren Milman24bd50b2018-09-11 21:46:55 +0300481 PyObject *result;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700482 dequeobject *old_deque = (dequeobject *)deque;
483 if (Py_TYPE(deque) == &deque_type) {
484 dequeobject *new_deque;
485 PyObject *rv;
486
487 new_deque = (dequeobject *)deque_new(&deque_type, (PyObject *)NULL, (PyObject *)NULL);
488 if (new_deque == NULL)
489 return NULL;
490 new_deque->maxlen = old_deque->maxlen;
491 /* Fast path for the deque_repeat() common case where len(deque) == 1 */
Raymond Hettinger0443ac22015-10-05 22:52:37 -0400492 if (Py_SIZE(deque) == 1) {
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700493 PyObject *item = old_deque->leftblock->data[old_deque->leftindex];
494 rv = deque_append(new_deque, item);
495 } else {
496 rv = deque_extend(new_deque, deque);
497 }
498 if (rv != NULL) {
499 Py_DECREF(rv);
500 return (PyObject *)new_deque;
501 }
502 Py_DECREF(new_deque);
503 return NULL;
504 }
505 if (old_deque->maxlen < 0)
Oren Milman24bd50b2018-09-11 21:46:55 +0300506 result = PyObject_CallFunctionObjArgs((PyObject *)(Py_TYPE(deque)),
507 deque, NULL);
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700508 else
Oren Milman24bd50b2018-09-11 21:46:55 +0300509 result = PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "Oi",
510 deque, old_deque->maxlen, NULL);
511 if (result != NULL && !PyObject_TypeCheck(result, &deque_type)) {
512 PyErr_Format(PyExc_TypeError,
513 "%.200s() must return a deque, not %.200s",
514 Py_TYPE(deque)->tp_name, Py_TYPE(result)->tp_name);
515 Py_DECREF(result);
516 return NULL;
517 }
518 return result;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700519}
520
521PyDoc_STRVAR(copy_doc, "Return a shallow copy of a deque.");
Raymond Hettinger41290a62015-03-31 08:12:23 -0700522
523static PyObject *
524deque_concat(dequeobject *deque, PyObject *other)
525{
Benjamin Peterson1a629212015-04-04 10:52:36 -0400526 PyObject *new_deque, *result;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700527 int rv;
528
529 rv = PyObject_IsInstance(other, (PyObject *)&deque_type);
530 if (rv <= 0) {
531 if (rv == 0) {
532 PyErr_Format(PyExc_TypeError,
533 "can only concatenate deque (not \"%.200s\") to deque",
534 other->ob_type->tp_name);
535 }
536 return NULL;
537 }
538
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530539 new_deque = deque_copy((PyObject *)deque, NULL);
Raymond Hettinger41290a62015-03-31 08:12:23 -0700540 if (new_deque == NULL)
541 return NULL;
Benjamin Peterson1a629212015-04-04 10:52:36 -0400542 result = deque_extend((dequeobject *)new_deque, other);
543 if (result == NULL) {
544 Py_DECREF(new_deque);
545 return NULL;
546 }
547 Py_DECREF(result);
548 return new_deque;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700549}
550
Serhiy Storchakaa5c42282018-05-31 07:34:34 +0300551static int
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700552deque_clear(dequeobject *deque)
553{
554 block *b;
555 block *prevblock;
556 block *leftblock;
557 Py_ssize_t leftindex;
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800558 Py_ssize_t n, m;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700559 PyObject *item;
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800560 PyObject **itemptr, **limit;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700561
Raymond Hettinger38031142015-09-29 22:45:05 -0700562 if (Py_SIZE(deque) == 0)
Serhiy Storchakaa5c42282018-05-31 07:34:34 +0300563 return 0;
Raymond Hettinger38031142015-09-29 22:45:05 -0700564
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700565 /* During the process of clearing a deque, decrefs can cause the
566 deque to mutate. To avoid fatal confusion, we have to make the
567 deque empty before clearing the blocks and never refer to
568 anything via deque->ref while clearing. (This is the same
569 technique used for clearing lists, sets, and dicts.)
570
571 Making the deque empty requires allocating a new empty block. In
572 the unlikely event that memory is full, we fall back to an
573 alternate method that doesn't require a new block. Repeating
574 pops in a while-loop is slower, possibly re-entrant (and a clever
575 adversary could cause it to never terminate).
576 */
577
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700578 b = newblock();
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700579 if (b == NULL) {
580 PyErr_Clear();
581 goto alternate_method;
582 }
583
584 /* Remember the old size, leftblock, and leftindex */
Raymond Hettinger6f86a332016-03-02 00:30:58 -0800585 n = Py_SIZE(deque);
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700586 leftblock = deque->leftblock;
587 leftindex = deque->leftindex;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700588
589 /* Set the deque to be empty using the newly allocated block */
590 MARK_END(b->leftlink);
591 MARK_END(b->rightlink);
592 Py_SIZE(deque) = 0;
593 deque->leftblock = b;
594 deque->rightblock = b;
595 deque->leftindex = CENTER + 1;
596 deque->rightindex = CENTER;
597 deque->state++;
598
599 /* Now the old size, leftblock, and leftindex are disconnected from
600 the empty deque and we can use them to decref the pointers.
601 */
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800602 m = (BLOCKLEN - leftindex > n) ? n : BLOCKLEN - leftindex;
Raymond Hettinger589106b2016-03-02 00:06:21 -0800603 itemptr = &leftblock->data[leftindex];
Raymond Hettinger6f86a332016-03-02 00:30:58 -0800604 limit = itemptr + m;
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800605 n -= m;
606 while (1) {
607 if (itemptr == limit) {
608 if (n == 0)
609 break;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700610 CHECK_NOT_END(leftblock->rightlink);
611 prevblock = leftblock;
612 leftblock = leftblock->rightlink;
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800613 m = (n > BLOCKLEN) ? BLOCKLEN : n;
Raymond Hettinger589106b2016-03-02 00:06:21 -0800614 itemptr = leftblock->data;
Raymond Hettinger6f86a332016-03-02 00:30:58 -0800615 limit = itemptr + m;
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800616 n -= m;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700617 freeblock(prevblock);
618 }
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800619 item = *(itemptr++);
620 Py_DECREF(item);
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700621 }
622 CHECK_END(leftblock->rightlink);
623 freeblock(leftblock);
Serhiy Storchakaa5c42282018-05-31 07:34:34 +0300624 return 0;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700625
626 alternate_method:
627 while (Py_SIZE(deque)) {
628 item = deque_pop(deque, NULL);
629 assert (item != NULL);
630 Py_DECREF(item);
631 }
Serhiy Storchakaa5c42282018-05-31 07:34:34 +0300632 return 0;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700633}
634
635static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530636deque_clearmethod(dequeobject *deque, PyObject *Py_UNUSED(ignored))
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700637{
638 deque_clear(deque);
639 Py_RETURN_NONE;
640}
641
642PyDoc_STRVAR(clear_doc, "Remove all elements from the deque.");
Raymond Hettinger41290a62015-03-31 08:12:23 -0700643
644static PyObject *
Raymond Hettinger41290a62015-03-31 08:12:23 -0700645deque_inplace_repeat(dequeobject *deque, Py_ssize_t n)
646{
Raymond Hettingerc22eee62015-09-26 02:14:50 -0700647 Py_ssize_t i, m, size;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700648 PyObject *seq;
649 PyObject *rv;
650
651 size = Py_SIZE(deque);
652 if (size == 0 || n == 1) {
653 Py_INCREF(deque);
654 return (PyObject *)deque;
655 }
656
657 if (n <= 0) {
658 deque_clear(deque);
659 Py_INCREF(deque);
660 return (PyObject *)deque;
661 }
662
Raymond Hettinger41290a62015-03-31 08:12:23 -0700663 if (size == 1) {
664 /* common case, repeating a single element */
665 PyObject *item = deque->leftblock->data[deque->leftindex];
666
Raymond Hettingera7f630092015-10-10 23:56:02 -0400667 if (deque->maxlen >= 0 && n > deque->maxlen)
Raymond Hettinger41290a62015-03-31 08:12:23 -0700668 n = deque->maxlen;
669
Raymond Hettinger67c78b52015-09-12 11:00:20 -0400670 deque->state++;
Raymond Hettingerad262252015-09-14 01:03:04 -0400671 for (i = 0 ; i < n-1 ; ) {
Raymond Hettinger67c78b52015-09-12 11:00:20 -0400672 if (deque->rightindex == BLOCKLEN - 1) {
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700673 block *b = newblock();
Raymond Hettinger67c78b52015-09-12 11:00:20 -0400674 if (b == NULL) {
675 Py_SIZE(deque) += i;
676 return NULL;
677 }
678 b->leftlink = deque->rightblock;
679 CHECK_END(deque->rightblock->rightlink);
680 deque->rightblock->rightlink = b;
681 deque->rightblock = b;
682 MARK_END(b->rightlink);
683 deque->rightindex = -1;
684 }
Raymond Hettingerc22eee62015-09-26 02:14:50 -0700685 m = n - 1 - i;
686 if (m > BLOCKLEN - 1 - deque->rightindex)
687 m = BLOCKLEN - 1 - deque->rightindex;
688 i += m;
689 while (m--) {
Raymond Hettingerad262252015-09-14 01:03:04 -0400690 deque->rightindex++;
691 Py_INCREF(item);
692 deque->rightblock->data[deque->rightindex] = item;
693 }
Raymond Hettinger41290a62015-03-31 08:12:23 -0700694 }
Raymond Hettinger67c78b52015-09-12 11:00:20 -0400695 Py_SIZE(deque) += i;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700696 Py_INCREF(deque);
697 return (PyObject *)deque;
698 }
699
Raymond Hettinger20151f52015-10-16 22:47:29 -0700700 if ((size_t)size > PY_SSIZE_T_MAX / (size_t)n) {
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400701 return PyErr_NoMemory();
702 }
703
Raymond Hettinger41290a62015-03-31 08:12:23 -0700704 seq = PySequence_List((PyObject *)deque);
705 if (seq == NULL)
706 return seq;
707
Louie Lu357bad72017-02-24 11:59:49 +0800708 /* Reduce the number of repetitions when maxlen would be exceeded */
709 if (deque->maxlen >= 0 && n * size > deque->maxlen)
710 n = (deque->maxlen + size - 1) / size;
711
Raymond Hettinger41290a62015-03-31 08:12:23 -0700712 for (i = 0 ; i < n-1 ; i++) {
713 rv = deque_extend(deque, seq);
714 if (rv == NULL) {
715 Py_DECREF(seq);
716 return NULL;
717 }
718 Py_DECREF(rv);
719 }
720 Py_INCREF(deque);
721 Py_DECREF(seq);
722 return (PyObject *)deque;
723}
724
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400725static PyObject *
726deque_repeat(dequeobject *deque, Py_ssize_t n)
727{
728 dequeobject *new_deque;
Raymond Hettinger95e2cc52015-09-13 02:41:18 -0400729 PyObject *rv;
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400730
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530731 new_deque = (dequeobject *)deque_copy((PyObject *) deque, NULL);
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400732 if (new_deque == NULL)
733 return NULL;
Raymond Hettinger95e2cc52015-09-13 02:41:18 -0400734 rv = deque_inplace_repeat(new_deque, n);
735 Py_DECREF(new_deque);
736 return rv;
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400737}
738
Raymond Hettinger54023152014-04-23 00:58:48 -0700739/* The rotate() method is part of the public API and is used internally
740as a primitive for other methods.
741
742Rotation by 1 or -1 is a common case, so any optimizations for high
743volume rotations should take care not to penalize the common case.
744
745Conceptually, a rotate by one is equivalent to a pop on one side and an
746append on the other. However, a pop/append pair is unnecessarily slow
Martin Panterd2ad5712015-11-02 04:20:33 +0000747because it requires an incref/decref pair for an object located randomly
Raymond Hettinger54023152014-04-23 00:58:48 -0700748in memory. It is better to just move the object pointer from one block
749to the next without changing the reference count.
750
751When moving batches of pointers, it is tempting to use memcpy() but that
752proved to be slower than a simple loop for a variety of reasons.
753Memcpy() cannot know in advance that we're copying pointers instead of
754bytes, that the source and destination are pointer aligned and
755non-overlapping, that moving just one pointer is a common case, that we
756never need to move more than BLOCKLEN pointers, and that at least one
757pointer is always moved.
758
759For high volume rotations, newblock() and freeblock() are never called
760more than once. Previously emptied blocks are immediately reused as a
761destination block. If a block is left-over at the end, it is freed.
762*/
763
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000764static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000765_deque_rotate(dequeobject *deque, Py_ssize_t n)
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000766{
Raymond Hettinger3959af92013-07-13 02:34:08 -0700767 block *b = NULL;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700768 block *leftblock = deque->leftblock;
769 block *rightblock = deque->rightblock;
770 Py_ssize_t leftindex = deque->leftindex;
771 Py_ssize_t rightindex = deque->rightindex;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000772 Py_ssize_t len=Py_SIZE(deque), halflen=len>>1;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700773 int rv = -1;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000774
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800775 if (len <= 1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000776 return 0;
777 if (n > halflen || n < -halflen) {
778 n %= len;
779 if (n > halflen)
780 n -= len;
781 else if (n < -halflen)
782 n += len;
783 }
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500784 assert(len > 1);
Raymond Hettingera4409c12013-02-04 00:08:12 -0500785 assert(-halflen <= n && n <= halflen);
Raymond Hettinger231ee4d2013-02-02 11:24:43 -0800786
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800787 deque->state++;
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500788 while (n > 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700789 if (leftindex == 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700790 if (b == NULL) {
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700791 b = newblock();
Raymond Hettinger3959af92013-07-13 02:34:08 -0700792 if (b == NULL)
793 goto done;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700794 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000795 b->rightlink = leftblock;
796 CHECK_END(leftblock->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700797 leftblock->leftlink = b;
798 leftblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000799 MARK_END(b->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700800 leftindex = BLOCKLEN;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700801 b = NULL;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800802 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700803 assert(leftindex > 0);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700804 {
805 PyObject **src, **dest;
806 Py_ssize_t m = n;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800807
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700808 if (m > rightindex + 1)
809 m = rightindex + 1;
810 if (m > leftindex)
811 m = leftindex;
812 assert (m > 0 && m <= len);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700813 rightindex -= m;
814 leftindex -= m;
Raymond Hettinger0e259f12015-02-01 22:53:41 -0800815 src = &rightblock->data[rightindex + 1];
816 dest = &leftblock->data[leftindex];
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700817 n -= m;
Raymond Hettinger840533b2013-07-13 17:03:58 -0700818 do {
Raymond Hettinger0e259f12015-02-01 22:53:41 -0800819 *(dest++) = *(src++);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700820 } while (--m);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700821 }
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -0700822 if (rightindex < 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700823 assert(leftblock != rightblock);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700824 assert(b == NULL);
Raymond Hettinger3959af92013-07-13 02:34:08 -0700825 b = rightblock;
Raymond Hettingerb97cc492013-07-21 01:51:07 -0700826 CHECK_NOT_END(rightblock->leftlink);
827 rightblock = rightblock->leftlink;
828 MARK_END(rightblock->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700829 rightindex = BLOCKLEN - 1;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800830 }
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800831 }
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500832 while (n < 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700833 if (rightindex == BLOCKLEN - 1) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700834 if (b == NULL) {
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700835 b = newblock();
Raymond Hettinger3959af92013-07-13 02:34:08 -0700836 if (b == NULL)
837 goto done;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700838 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000839 b->leftlink = rightblock;
840 CHECK_END(rightblock->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700841 rightblock->rightlink = b;
842 rightblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000843 MARK_END(b->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700844 rightindex = -1;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700845 b = NULL;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800846 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700847 assert (rightindex < BLOCKLEN - 1);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700848 {
849 PyObject **src, **dest;
850 Py_ssize_t m = -n;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800851
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700852 if (m > BLOCKLEN - leftindex)
853 m = BLOCKLEN - leftindex;
854 if (m > BLOCKLEN - 1 - rightindex)
855 m = BLOCKLEN - 1 - rightindex;
856 assert (m > 0 && m <= len);
857 src = &leftblock->data[leftindex];
858 dest = &rightblock->data[rightindex + 1];
859 leftindex += m;
860 rightindex += m;
861 n += m;
Raymond Hettinger840533b2013-07-13 17:03:58 -0700862 do {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700863 *(dest++) = *(src++);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700864 } while (--m);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700865 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700866 if (leftindex == BLOCKLEN) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700867 assert(leftblock != rightblock);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700868 assert(b == NULL);
Raymond Hettinger3959af92013-07-13 02:34:08 -0700869 b = leftblock;
Raymond Hettingerb97cc492013-07-21 01:51:07 -0700870 CHECK_NOT_END(leftblock->rightlink);
871 leftblock = leftblock->rightlink;
872 MARK_END(leftblock->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700873 leftindex = 0;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800874 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000875 }
Raymond Hettinger3959af92013-07-13 02:34:08 -0700876 rv = 0;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700877done:
Raymond Hettinger3959af92013-07-13 02:34:08 -0700878 if (b != NULL)
879 freeblock(b);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700880 deque->leftblock = leftblock;
881 deque->rightblock = rightblock;
882 deque->leftindex = leftindex;
883 deque->rightindex = rightindex;
884
885 return rv;
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000886}
887
888static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +0200889deque_rotate(dequeobject *deque, PyObject *const *args, Py_ssize_t nargs)
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000890{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000891 Py_ssize_t n=1;
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000892
Victor Stinnerdd407d52017-02-06 16:06:49 +0100893 if (!_PyArg_ParseStack(args, nargs, "|n:rotate", &n)) {
894 return NULL;
895 }
896
Raymond Hettinger6921c132015-03-21 02:03:40 -0700897 if (!_deque_rotate(deque, n))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000898 Py_RETURN_NONE;
899 return NULL;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000900}
901
Tim Peters1065f752004-10-01 01:03:29 +0000902PyDoc_STRVAR(rotate_doc,
Raymond Hettingeree33b272004-02-08 04:05:26 +0000903"Rotate the deque n steps to the right (default n=1). If n is negative, rotates left.");
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000904
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000905static PyObject *
906deque_reverse(dequeobject *deque, PyObject *unused)
907{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000908 block *leftblock = deque->leftblock;
909 block *rightblock = deque->rightblock;
910 Py_ssize_t leftindex = deque->leftindex;
911 Py_ssize_t rightindex = deque->rightindex;
Raymond Hettingercfe5b6c2015-07-20 00:25:50 -0400912 Py_ssize_t n = Py_SIZE(deque) >> 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 PyObject *tmp;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000914
Raymond Hettingere1b02872017-09-04 16:07:06 -0700915 while (--n >= 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 /* Validate that pointers haven't met in the middle */
917 assert(leftblock != rightblock || leftindex < rightindex);
Raymond Hettinger82df9252013-07-07 01:43:42 -1000918 CHECK_NOT_END(leftblock);
919 CHECK_NOT_END(rightblock);
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 /* Swap */
922 tmp = leftblock->data[leftindex];
923 leftblock->data[leftindex] = rightblock->data[rightindex];
924 rightblock->data[rightindex] = tmp;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000925
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 /* Advance left block/index pair */
927 leftindex++;
928 if (leftindex == BLOCKLEN) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000929 leftblock = leftblock->rightlink;
930 leftindex = 0;
931 }
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933 /* Step backwards with the right block/index pair */
934 rightindex--;
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -0700935 if (rightindex < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 rightblock = rightblock->leftlink;
937 rightindex = BLOCKLEN - 1;
938 }
939 }
940 Py_RETURN_NONE;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000941}
942
943PyDoc_STRVAR(reverse_doc,
944"D.reverse() -- reverse *IN PLACE*");
945
Raymond Hettinger44459de2010-04-03 23:20:46 +0000946static PyObject *
947deque_count(dequeobject *deque, PyObject *v)
948{
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000949 block *b = deque->leftblock;
950 Py_ssize_t index = deque->leftindex;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000951 Py_ssize_t n = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 Py_ssize_t count = 0;
Raymond Hettingerf9d9c792015-03-02 22:47:46 -0800953 size_t start_state = deque->state;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000954 PyObject *item;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 int cmp;
Raymond Hettinger44459de2010-04-03 23:20:46 +0000956
Raymond Hettingere1b02872017-09-04 16:07:06 -0700957 while (--n >= 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000958 CHECK_NOT_END(b);
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000959 item = b->data[index];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
Raymond Hettinger2b0d6462015-09-23 19:15:44 -0700961 if (cmp < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962 return NULL;
Raymond Hettinger2b0d6462015-09-23 19:15:44 -0700963 count += cmp;
Raymond Hettinger44459de2010-04-03 23:20:46 +0000964
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000965 if (start_state != deque->state) {
966 PyErr_SetString(PyExc_RuntimeError,
967 "deque mutated during iteration");
968 return NULL;
969 }
Raymond Hettinger44459de2010-04-03 23:20:46 +0000970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 /* Advance left block/index pair */
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000972 index++;
973 if (index == BLOCKLEN) {
974 b = b->rightlink;
975 index = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000976 }
977 }
978 return PyLong_FromSsize_t(count);
Raymond Hettinger44459de2010-04-03 23:20:46 +0000979}
980
981PyDoc_STRVAR(count_doc,
982"D.count(value) -> integer -- return number of occurrences of value");
983
Raymond Hettinger39dadf72015-03-20 16:38:56 -0700984static int
985deque_contains(dequeobject *deque, PyObject *v)
986{
987 block *b = deque->leftblock;
988 Py_ssize_t index = deque->leftindex;
989 Py_ssize_t n = Py_SIZE(deque);
Raymond Hettinger39dadf72015-03-20 16:38:56 -0700990 size_t start_state = deque->state;
991 PyObject *item;
992 int cmp;
993
Raymond Hettingere1b02872017-09-04 16:07:06 -0700994 while (--n >= 0) {
Raymond Hettinger39dadf72015-03-20 16:38:56 -0700995 CHECK_NOT_END(b);
996 item = b->data[index];
997 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
998 if (cmp) {
999 return cmp;
1000 }
1001 if (start_state != deque->state) {
1002 PyErr_SetString(PyExc_RuntimeError,
1003 "deque mutated during iteration");
1004 return -1;
1005 }
1006 index++;
1007 if (index == BLOCKLEN) {
1008 b = b->rightlink;
1009 index = 0;
1010 }
1011 }
1012 return 0;
1013}
1014
Martin v. Löwis18e16552006-02-15 17:27:45 +00001015static Py_ssize_t
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001016deque_len(dequeobject *deque)
1017{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001018 return Py_SIZE(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001019}
1020
Raymond Hettinger4aec61e2005-03-18 21:20:23 +00001021static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02001022deque_index(dequeobject *deque, PyObject *const *args, Py_ssize_t nargs)
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001023{
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001024 Py_ssize_t i, n, start=0, stop=Py_SIZE(deque);
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001025 PyObject *v, *item;
1026 block *b = deque->leftblock;
1027 Py_ssize_t index = deque->leftindex;
1028 size_t start_state = deque->state;
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001029 int cmp;
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001030
Victor Stinnerdd407d52017-02-06 16:06:49 +01001031 if (!_PyArg_ParseStack(args, nargs, "O|O&O&:index", &v,
Serhiy Storchakad4edfc92017-03-30 18:29:23 +03001032 _PyEval_SliceIndexNotNone, &start,
1033 _PyEval_SliceIndexNotNone, &stop)) {
Victor Stinnerdd407d52017-02-06 16:06:49 +01001034 return NULL;
1035 }
1036
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001037 if (start < 0) {
1038 start += Py_SIZE(deque);
1039 if (start < 0)
1040 start = 0;
1041 }
1042 if (stop < 0) {
1043 stop += Py_SIZE(deque);
1044 if (stop < 0)
1045 stop = 0;
1046 }
Raymond Hettinger87674ec2015-08-26 08:08:38 -07001047 if (stop > Py_SIZE(deque))
1048 stop = Py_SIZE(deque);
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001049 if (start > stop)
1050 start = stop;
1051 assert(0 <= start && start <= stop && stop <= Py_SIZE(deque));
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001052
Raymond Hettingerb46ad542018-09-21 01:46:41 -07001053 for (i=0 ; i < start - BLOCKLEN ; i += BLOCKLEN) {
1054 b = b->rightlink;
1055 }
1056 for ( ; i < start ; i++) {
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001057 index++;
1058 if (index == BLOCKLEN) {
1059 b = b->rightlink;
1060 index = 0;
1061 }
1062 }
1063
Raymond Hettingere1b02872017-09-04 16:07:06 -07001064 n = stop - i;
1065 while (--n >= 0) {
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001066 CHECK_NOT_END(b);
1067 item = b->data[index];
1068 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
1069 if (cmp > 0)
Raymond Hettingere1b02872017-09-04 16:07:06 -07001070 return PyLong_FromSsize_t(stop - n - 1);
Raymond Hettingerdf8f5b52015-11-02 07:27:40 -05001071 if (cmp < 0)
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001072 return NULL;
1073 if (start_state != deque->state) {
1074 PyErr_SetString(PyExc_RuntimeError,
1075 "deque mutated during iteration");
1076 return NULL;
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001077 }
1078 index++;
1079 if (index == BLOCKLEN) {
1080 b = b->rightlink;
1081 index = 0;
1082 }
1083 }
1084 PyErr_Format(PyExc_ValueError, "%R is not in deque", v);
1085 return NULL;
1086}
1087
1088PyDoc_STRVAR(index_doc,
1089"D.index(value, [start, [stop]]) -> integer -- return first index of value.\n"
1090"Raises ValueError if the value is not present.");
1091
Raymond Hettinger551350a2015-03-24 00:19:53 -07001092/* insert(), remove(), and delitem() are implemented in terms of
1093 rotate() for simplicity and reasonable performance near the end
1094 points. If for some reason these methods become popular, it is not
1095 hard to re-implement this using direct data movement (similar to
1096 the code used in list slice assignments) and achieve a performance
Raymond Hettingerfef9c1b2015-03-24 21:12:57 -07001097 boost (by moving each pointer only once instead of twice).
Raymond Hettinger551350a2015-03-24 00:19:53 -07001098*/
1099
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001100static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02001101deque_insert(dequeobject *deque, PyObject *const *args, Py_ssize_t nargs)
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001102{
1103 Py_ssize_t index;
1104 Py_ssize_t n = Py_SIZE(deque);
1105 PyObject *value;
1106 PyObject *rv;
1107
Victor Stinnerdd407d52017-02-06 16:06:49 +01001108 if (!_PyArg_ParseStack(args, nargs, "nO:insert", &index, &value)) {
1109 return NULL;
1110 }
1111
Raymond Hettinger37434322016-01-26 21:44:16 -08001112 if (deque->maxlen == Py_SIZE(deque)) {
Raymond Hettingera6389712016-02-01 21:21:19 -08001113 PyErr_SetString(PyExc_IndexError, "deque already at its maximum size");
1114 return NULL;
Raymond Hettinger37434322016-01-26 21:44:16 -08001115 }
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001116 if (index >= n)
1117 return deque_append(deque, value);
1118 if (index <= -n || index == 0)
1119 return deque_appendleft(deque, value);
1120 if (_deque_rotate(deque, -index))
1121 return NULL;
1122 if (index < 0)
1123 rv = deque_append(deque, value);
1124 else
1125 rv = deque_appendleft(deque, value);
1126 if (rv == NULL)
1127 return NULL;
1128 Py_DECREF(rv);
1129 if (_deque_rotate(deque, index))
1130 return NULL;
1131 Py_RETURN_NONE;
1132}
1133
1134PyDoc_STRVAR(insert_doc,
1135"D.insert(index, object) -- insert object before index");
1136
1137static PyObject *
Raymond Hettinger4aec61e2005-03-18 21:20:23 +00001138deque_remove(dequeobject *deque, PyObject *value)
1139{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001140 Py_ssize_t i, n=Py_SIZE(deque);
Raymond Hettinger4aec61e2005-03-18 21:20:23 +00001141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142 for (i=0 ; i<n ; i++) {
1143 PyObject *item = deque->leftblock->data[deque->leftindex];
1144 int cmp = PyObject_RichCompareBool(item, value, Py_EQ);
Raymond Hettingerd73202c2005-03-19 00:00:51 +00001145
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001146 if (Py_SIZE(deque) != n) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001147 PyErr_SetString(PyExc_IndexError,
1148 "deque mutated during remove().");
1149 return NULL;
1150 }
1151 if (cmp > 0) {
1152 PyObject *tgt = deque_popleft(deque, NULL);
1153 assert (tgt != NULL);
Raymond Hettinger6921c132015-03-21 02:03:40 -07001154 if (_deque_rotate(deque, i))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001155 return NULL;
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001156 Py_DECREF(tgt);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001157 Py_RETURN_NONE;
1158 }
1159 else if (cmp < 0) {
1160 _deque_rotate(deque, i);
1161 return NULL;
1162 }
1163 _deque_rotate(deque, -1);
1164 }
1165 PyErr_SetString(PyExc_ValueError, "deque.remove(x): x not in deque");
1166 return NULL;
Raymond Hettinger4aec61e2005-03-18 21:20:23 +00001167}
1168
1169PyDoc_STRVAR(remove_doc,
1170"D.remove(value) -- remove first occurrence of value.");
1171
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001172static int
1173valid_index(Py_ssize_t i, Py_ssize_t limit)
1174{
Raymond Hettinger12f896c2015-07-31 12:03:20 -07001175 /* The cast to size_t lets us use just a single comparison
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001176 to check whether i is in the range: 0 <= i < limit */
1177 return (size_t) i < (size_t) limit;
1178}
1179
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001180static PyObject *
Benjamin Petersond6313712008-07-31 16:23:04 +00001181deque_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001182{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 block *b;
1184 PyObject *item;
1185 Py_ssize_t n, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001186
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001187 if (!valid_index(i, Py_SIZE(deque))) {
1188 PyErr_SetString(PyExc_IndexError, "deque index out of range");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001189 return NULL;
1190 }
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001192 if (i == 0) {
1193 i = deque->leftindex;
1194 b = deque->leftblock;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001195 } else if (i == Py_SIZE(deque) - 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001196 i = deque->rightindex;
1197 b = deque->rightblock;
1198 } else {
1199 i += deque->leftindex;
Raymond Hettingerc2083082015-02-28 23:29:16 -08001200 n = (Py_ssize_t)((size_t) i / BLOCKLEN);
1201 i = (Py_ssize_t)((size_t) i % BLOCKLEN);
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001202 if (index < (Py_SIZE(deque) >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001203 b = deque->leftblock;
Raymond Hettingere1b02872017-09-04 16:07:06 -07001204 while (--n >= 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001205 b = b->rightlink;
1206 } else {
Raymond Hettinger63d1ff22015-02-28 07:41:30 -08001207 n = (Py_ssize_t)(
Raymond Hettingerc2083082015-02-28 23:29:16 -08001208 ((size_t)(deque->leftindex + Py_SIZE(deque) - 1))
Raymond Hettinger63d1ff22015-02-28 07:41:30 -08001209 / BLOCKLEN - n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001210 b = deque->rightblock;
Raymond Hettingere1b02872017-09-04 16:07:06 -07001211 while (--n >= 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001212 b = b->leftlink;
1213 }
1214 }
1215 item = b->data[i];
1216 Py_INCREF(item);
1217 return item;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001218}
1219
1220static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001221deque_del_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001222{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001223 PyObject *item;
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001224 int rv;
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001225
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001226 assert (i >= 0 && i < Py_SIZE(deque));
Raymond Hettinger6921c132015-03-21 02:03:40 -07001227 if (_deque_rotate(deque, -i))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001228 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 item = deque_popleft(deque, NULL);
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001230 rv = _deque_rotate(deque, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001231 assert (item != NULL);
1232 Py_DECREF(item);
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001233 return rv;
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001234}
1235
1236static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001237deque_ass_item(dequeobject *deque, Py_ssize_t i, PyObject *v)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001238{
Raymond Hettinger38418662016-02-08 20:34:49 -08001239 PyObject *old_value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001240 block *b;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001241 Py_ssize_t n, len=Py_SIZE(deque), halflen=(len+1)>>1, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001242
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001243 if (!valid_index(i, len)) {
1244 PyErr_SetString(PyExc_IndexError, "deque index out of range");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001245 return -1;
1246 }
1247 if (v == NULL)
1248 return deque_del_item(deque, i);
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001250 i += deque->leftindex;
Raymond Hettingerc2083082015-02-28 23:29:16 -08001251 n = (Py_ssize_t)((size_t) i / BLOCKLEN);
1252 i = (Py_ssize_t)((size_t) i % BLOCKLEN);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001253 if (index <= halflen) {
1254 b = deque->leftblock;
Raymond Hettingere1b02872017-09-04 16:07:06 -07001255 while (--n >= 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001256 b = b->rightlink;
1257 } else {
Raymond Hettingera473b9d2015-02-28 17:49:47 -08001258 n = (Py_ssize_t)(
Raymond Hettingerc2083082015-02-28 23:29:16 -08001259 ((size_t)(deque->leftindex + Py_SIZE(deque) - 1))
Raymond Hettingera473b9d2015-02-28 17:49:47 -08001260 / BLOCKLEN - n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001261 b = deque->rightblock;
Raymond Hettingere1b02872017-09-04 16:07:06 -07001262 while (--n >= 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 b = b->leftlink;
1264 }
1265 Py_INCREF(v);
Raymond Hettinger38418662016-02-08 20:34:49 -08001266 old_value = b->data[i];
1267 b->data[i] = v;
1268 Py_DECREF(old_value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001269 return 0;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001270}
1271
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001272static void
1273deque_dealloc(dequeobject *deque)
1274{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001275 PyObject_GC_UnTrack(deque);
1276 if (deque->weakreflist != NULL)
1277 PyObject_ClearWeakRefs((PyObject *) deque);
1278 if (deque->leftblock != NULL) {
1279 deque_clear(deque);
1280 assert(deque->leftblock != NULL);
1281 freeblock(deque->leftblock);
1282 }
1283 deque->leftblock = NULL;
1284 deque->rightblock = NULL;
1285 Py_TYPE(deque)->tp_free(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001286}
1287
1288static int
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001289deque_traverse(dequeobject *deque, visitproc visit, void *arg)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001290{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001291 block *b;
1292 PyObject *item;
1293 Py_ssize_t index;
1294 Py_ssize_t indexlo = deque->leftindex;
Raymond Hettinger1286d142015-10-14 23:16:57 -07001295 Py_ssize_t indexhigh;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001296
Raymond Hettinger5bfa8672013-07-06 11:58:09 -10001297 for (b = deque->leftblock; b != deque->rightblock; b = b->rightlink) {
1298 for (index = indexlo; index < BLOCKLEN ; index++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001299 item = b->data[index];
1300 Py_VISIT(item);
1301 }
1302 indexlo = 0;
1303 }
Raymond Hettinger1286d142015-10-14 23:16:57 -07001304 indexhigh = deque->rightindex;
1305 for (index = indexlo; index <= indexhigh; index++) {
Raymond Hettinger5bfa8672013-07-06 11:58:09 -10001306 item = b->data[index];
1307 Py_VISIT(item);
1308 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001309 return 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001310}
1311
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001312static PyObject *
Serhiy Storchaka81524022018-11-27 13:05:02 +02001313deque_reduce(dequeobject *deque, PyObject *Py_UNUSED(ignored))
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001314{
Serhiy Storchakaa0d416f2016-03-06 08:55:21 +02001315 PyObject *dict, *it;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001316 _Py_IDENTIFIER(__dict__);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001317
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001318 if (_PyObject_LookupAttrId((PyObject *)deque, &PyId___dict__, &dict) < 0) {
1319 return NULL;
1320 }
Serhiy Storchakaa0d416f2016-03-06 08:55:21 +02001321 if (dict == NULL) {
Serhiy Storchakaa0d416f2016-03-06 08:55:21 +02001322 dict = Py_None;
1323 Py_INCREF(dict);
1324 }
1325
1326 it = PyObject_GetIter((PyObject *)deque);
1327 if (it == NULL) {
1328 Py_DECREF(dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001329 return NULL;
1330 }
Serhiy Storchakaa0d416f2016-03-06 08:55:21 +02001331
1332 if (deque->maxlen < 0) {
1333 return Py_BuildValue("O()NN", Py_TYPE(deque), dict, it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001334 }
Serhiy Storchakaa0d416f2016-03-06 08:55:21 +02001335 else {
1336 return Py_BuildValue("O(()n)NN", Py_TYPE(deque), deque->maxlen, dict, it);
1337 }
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001338}
1339
1340PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
1341
1342static PyObject *
1343deque_repr(PyObject *deque)
1344{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001345 PyObject *aslist, *result;
1346 int i;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001348 i = Py_ReprEnter(deque);
1349 if (i != 0) {
1350 if (i < 0)
1351 return NULL;
1352 return PyUnicode_FromString("[...]");
1353 }
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001355 aslist = PySequence_List(deque);
1356 if (aslist == NULL) {
1357 Py_ReprLeave(deque);
1358 return NULL;
1359 }
Raymond Hettingera7f630092015-10-10 23:56:02 -04001360 if (((dequeobject *)deque)->maxlen >= 0)
Serhiy Storchakab3a77962017-09-21 14:24:13 +03001361 result = PyUnicode_FromFormat("%s(%R, maxlen=%zd)",
1362 _PyType_Name(Py_TYPE(deque)), aslist,
1363 ((dequeobject *)deque)->maxlen);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001364 else
Serhiy Storchakab3a77962017-09-21 14:24:13 +03001365 result = PyUnicode_FromFormat("%s(%R)",
1366 _PyType_Name(Py_TYPE(deque)), aslist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001367 Py_ReprLeave(deque);
Raymond Hettinger2b2b7532015-09-05 17:05:52 -07001368 Py_DECREF(aslist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001369 return result;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001370}
1371
Raymond Hettinger738ec902004-02-29 02:15:56 +00001372static PyObject *
1373deque_richcompare(PyObject *v, PyObject *w, int op)
1374{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001375 PyObject *it1=NULL, *it2=NULL, *x, *y;
1376 Py_ssize_t vs, ws;
1377 int b, cmp=-1;
Raymond Hettinger738ec902004-02-29 02:15:56 +00001378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001379 if (!PyObject_TypeCheck(v, &deque_type) ||
1380 !PyObject_TypeCheck(w, &deque_type)) {
Brian Curtindfc80e32011-08-10 20:28:54 -05001381 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001382 }
Raymond Hettinger738ec902004-02-29 02:15:56 +00001383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001384 /* Shortcuts */
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001385 vs = Py_SIZE((dequeobject *)v);
1386 ws = Py_SIZE((dequeobject *)w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001387 if (op == Py_EQ) {
1388 if (v == w)
1389 Py_RETURN_TRUE;
1390 if (vs != ws)
1391 Py_RETURN_FALSE;
1392 }
1393 if (op == Py_NE) {
1394 if (v == w)
1395 Py_RETURN_FALSE;
1396 if (vs != ws)
1397 Py_RETURN_TRUE;
1398 }
Raymond Hettinger738ec902004-02-29 02:15:56 +00001399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001400 /* Search for the first index where items are different */
1401 it1 = PyObject_GetIter(v);
1402 if (it1 == NULL)
1403 goto done;
1404 it2 = PyObject_GetIter(w);
1405 if (it2 == NULL)
1406 goto done;
1407 for (;;) {
1408 x = PyIter_Next(it1);
1409 if (x == NULL && PyErr_Occurred())
1410 goto done;
1411 y = PyIter_Next(it2);
1412 if (x == NULL || y == NULL)
1413 break;
1414 b = PyObject_RichCompareBool(x, y, Py_EQ);
1415 if (b == 0) {
1416 cmp = PyObject_RichCompareBool(x, y, op);
1417 Py_DECREF(x);
1418 Py_DECREF(y);
1419 goto done;
1420 }
1421 Py_DECREF(x);
1422 Py_DECREF(y);
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -07001423 if (b < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001424 goto done;
1425 }
1426 /* We reached the end of one deque or both */
1427 Py_XDECREF(x);
1428 Py_XDECREF(y);
1429 if (PyErr_Occurred())
1430 goto done;
1431 switch (op) {
1432 case Py_LT: cmp = y != NULL; break; /* if w was longer */
1433 case Py_LE: cmp = x == NULL; break; /* if v was not longer */
1434 case Py_EQ: cmp = x == y; break; /* if we reached the end of both */
1435 case Py_NE: cmp = x != y; break; /* if one deque continues */
1436 case Py_GT: cmp = x != NULL; break; /* if v was longer */
1437 case Py_GE: cmp = y == NULL; break; /* if w was not longer */
1438 }
Tim Peters1065f752004-10-01 01:03:29 +00001439
Raymond Hettinger738ec902004-02-29 02:15:56 +00001440done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001441 Py_XDECREF(it1);
1442 Py_XDECREF(it2);
1443 if (cmp == 1)
1444 Py_RETURN_TRUE;
1445 if (cmp == 0)
1446 Py_RETURN_FALSE;
1447 return NULL;
Raymond Hettinger738ec902004-02-29 02:15:56 +00001448}
1449
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001450static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001451deque_init(dequeobject *deque, PyObject *args, PyObject *kwdargs)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001452{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001453 PyObject *iterable = NULL;
1454 PyObject *maxlenobj = NULL;
1455 Py_ssize_t maxlen = -1;
1456 char *kwlist[] = {"iterable", "maxlen", 0};
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001457
Raymond Hettinger0d309402015-09-30 23:15:02 -07001458 if (kwdargs == NULL) {
1459 if (!PyArg_UnpackTuple(args, "deque()", 0, 2, &iterable, &maxlenobj))
1460 return -1;
1461 } else {
1462 if (!PyArg_ParseTupleAndKeywords(args, kwdargs, "|OO:deque", kwlist,
1463 &iterable, &maxlenobj))
1464 return -1;
1465 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001466 if (maxlenobj != NULL && maxlenobj != Py_None) {
1467 maxlen = PyLong_AsSsize_t(maxlenobj);
1468 if (maxlen == -1 && PyErr_Occurred())
1469 return -1;
1470 if (maxlen < 0) {
1471 PyErr_SetString(PyExc_ValueError, "maxlen must be non-negative");
1472 return -1;
1473 }
1474 }
1475 deque->maxlen = maxlen;
Raymond Hettinger0d309402015-09-30 23:15:02 -07001476 if (Py_SIZE(deque) > 0)
1477 deque_clear(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001478 if (iterable != NULL) {
1479 PyObject *rv = deque_extend(deque, iterable);
1480 if (rv == NULL)
1481 return -1;
1482 Py_DECREF(rv);
1483 }
1484 return 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001485}
1486
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001487static PyObject *
Jesus Cea16e2fca2012-08-03 14:49:42 +02001488deque_sizeof(dequeobject *deque, void *unused)
1489{
1490 Py_ssize_t res;
1491 Py_ssize_t blocks;
1492
Serhiy Storchaka5c4064e2015-12-19 20:05:25 +02001493 res = _PyObject_SIZE(Py_TYPE(deque));
Raymond Hettingerbc003412015-10-14 23:33:23 -07001494 blocks = (size_t)(deque->leftindex + Py_SIZE(deque) + BLOCKLEN - 1) / BLOCKLEN;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001495 assert(deque->leftindex + Py_SIZE(deque) - 1 ==
Jesus Cea16e2fca2012-08-03 14:49:42 +02001496 (blocks - 1) * BLOCKLEN + deque->rightindex);
1497 res += blocks * sizeof(block);
1498 return PyLong_FromSsize_t(res);
1499}
1500
1501PyDoc_STRVAR(sizeof_doc,
1502"D.__sizeof__() -- size of D in memory, in bytes");
1503
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001504static int
1505deque_bool(dequeobject *deque)
1506{
1507 return Py_SIZE(deque) != 0;
1508}
1509
Jesus Cea16e2fca2012-08-03 14:49:42 +02001510static PyObject *
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001511deque_get_maxlen(dequeobject *deque)
1512{
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -07001513 if (deque->maxlen < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001514 Py_RETURN_NONE;
1515 return PyLong_FromSsize_t(deque->maxlen);
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001516}
1517
Raymond Hettinger41290a62015-03-31 08:12:23 -07001518
1519/* deque object ********************************************************/
1520
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001521static PyGetSetDef deque_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001522 {"maxlen", (getter)deque_get_maxlen, (setter)NULL,
1523 "maximum size of a deque or None if unbounded"},
1524 {0}
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001525};
1526
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001527static PySequenceMethods deque_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001528 (lenfunc)deque_len, /* sq_length */
Raymond Hettinger41290a62015-03-31 08:12:23 -07001529 (binaryfunc)deque_concat, /* sq_concat */
1530 (ssizeargfunc)deque_repeat, /* sq_repeat */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001531 (ssizeargfunc)deque_item, /* sq_item */
1532 0, /* sq_slice */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001533 (ssizeobjargproc)deque_ass_item, /* sq_ass_item */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001534 0, /* sq_ass_slice */
Raymond Hettinger39dadf72015-03-20 16:38:56 -07001535 (objobjproc)deque_contains, /* sq_contains */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001536 (binaryfunc)deque_inplace_concat, /* sq_inplace_concat */
Raymond Hettinger41290a62015-03-31 08:12:23 -07001537 (ssizeargfunc)deque_inplace_repeat, /* sq_inplace_repeat */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001538};
1539
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001540static PyNumberMethods deque_as_number = {
1541 0, /* nb_add */
1542 0, /* nb_subtract */
1543 0, /* nb_multiply */
1544 0, /* nb_remainder */
1545 0, /* nb_divmod */
1546 0, /* nb_power */
1547 0, /* nb_negative */
1548 0, /* nb_positive */
1549 0, /* nb_absolute */
1550 (inquiry)deque_bool, /* nb_bool */
1551 0, /* nb_invert */
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001552 };
1553
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001554static PyObject *deque_iter(dequeobject *deque);
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301555static PyObject *deque_reviter(dequeobject *deque, PyObject *Py_UNUSED(ignored));
Tim Peters1065f752004-10-01 01:03:29 +00001556PyDoc_STRVAR(reversed_doc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001557 "D.__reversed__() -- return a reverse iterator over the deque");
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001558
1559static PyMethodDef deque_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001560 {"append", (PyCFunction)deque_append,
1561 METH_O, append_doc},
1562 {"appendleft", (PyCFunction)deque_appendleft,
1563 METH_O, appendleft_doc},
1564 {"clear", (PyCFunction)deque_clearmethod,
1565 METH_NOARGS, clear_doc},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301566 {"__copy__", deque_copy,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001567 METH_NOARGS, copy_doc},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301568 {"copy", deque_copy,
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001569 METH_NOARGS, copy_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001570 {"count", (PyCFunction)deque_count,
Raymond Hettinger0f6f9472015-03-21 01:42:10 -07001571 METH_O, count_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001572 {"extend", (PyCFunction)deque_extend,
1573 METH_O, extend_doc},
1574 {"extendleft", (PyCFunction)deque_extendleft,
1575 METH_O, extendleft_doc},
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001576 {"index", (PyCFunction)deque_index,
Victor Stinnerdd407d52017-02-06 16:06:49 +01001577 METH_FASTCALL, index_doc},
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001578 {"insert", (PyCFunction)deque_insert,
Victor Stinnerdd407d52017-02-06 16:06:49 +01001579 METH_FASTCALL, insert_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001580 {"pop", (PyCFunction)deque_pop,
1581 METH_NOARGS, pop_doc},
1582 {"popleft", (PyCFunction)deque_popleft,
1583 METH_NOARGS, popleft_doc},
Raymond Hettinger0f6f9472015-03-21 01:42:10 -07001584 {"__reduce__", (PyCFunction)deque_reduce,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001585 METH_NOARGS, reduce_doc},
1586 {"remove", (PyCFunction)deque_remove,
1587 METH_O, remove_doc},
1588 {"__reversed__", (PyCFunction)deque_reviter,
1589 METH_NOARGS, reversed_doc},
1590 {"reverse", (PyCFunction)deque_reverse,
1591 METH_NOARGS, reverse_doc},
1592 {"rotate", (PyCFunction)deque_rotate,
Victor Stinnerdd407d52017-02-06 16:06:49 +01001593 METH_FASTCALL, rotate_doc},
Jesus Cea16e2fca2012-08-03 14:49:42 +02001594 {"__sizeof__", (PyCFunction)deque_sizeof,
1595 METH_NOARGS, sizeof_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001596 {NULL, NULL} /* sentinel */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001597};
1598
1599PyDoc_STRVAR(deque_doc,
Andrew Svetlov6a5c7c32012-10-31 11:50:40 +02001600"deque([iterable[, maxlen]]) --> deque object\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001601\n\
Raymond Hettinger41290a62015-03-31 08:12:23 -07001602A list-like sequence optimized for data accesses near its endpoints.");
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001603
Neal Norwitz87f10132004-02-29 15:40:53 +00001604static PyTypeObject deque_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001605 PyVarObject_HEAD_INIT(NULL, 0)
1606 "collections.deque", /* tp_name */
1607 sizeof(dequeobject), /* tp_basicsize */
1608 0, /* tp_itemsize */
1609 /* methods */
1610 (destructor)deque_dealloc, /* tp_dealloc */
1611 0, /* tp_print */
1612 0, /* tp_getattr */
1613 0, /* tp_setattr */
1614 0, /* tp_reserved */
1615 deque_repr, /* tp_repr */
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001616 &deque_as_number, /* tp_as_number */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001617 &deque_as_sequence, /* tp_as_sequence */
1618 0, /* tp_as_mapping */
Georg Brandlf038b322010-10-18 07:35:09 +00001619 PyObject_HashNotImplemented, /* tp_hash */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001620 0, /* tp_call */
1621 0, /* tp_str */
1622 PyObject_GenericGetAttr, /* tp_getattro */
1623 0, /* tp_setattro */
1624 0, /* tp_as_buffer */
1625 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
Georg Brandlf038b322010-10-18 07:35:09 +00001626 /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001627 deque_doc, /* tp_doc */
1628 (traverseproc)deque_traverse, /* tp_traverse */
1629 (inquiry)deque_clear, /* tp_clear */
1630 (richcmpfunc)deque_richcompare, /* tp_richcompare */
Georg Brandlf038b322010-10-18 07:35:09 +00001631 offsetof(dequeobject, weakreflist), /* tp_weaklistoffset*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001632 (getiterfunc)deque_iter, /* tp_iter */
1633 0, /* tp_iternext */
1634 deque_methods, /* tp_methods */
1635 0, /* tp_members */
Georg Brandlf038b322010-10-18 07:35:09 +00001636 deque_getset, /* tp_getset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001637 0, /* tp_base */
1638 0, /* tp_dict */
1639 0, /* tp_descr_get */
1640 0, /* tp_descr_set */
1641 0, /* tp_dictoffset */
1642 (initproc)deque_init, /* tp_init */
1643 PyType_GenericAlloc, /* tp_alloc */
1644 deque_new, /* tp_new */
1645 PyObject_GC_Del, /* tp_free */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001646};
1647
1648/*********************** Deque Iterator **************************/
1649
1650typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001651 PyObject_HEAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001652 block *b;
Raymond Hettinger87e69122015-03-02 23:32:02 -08001653 Py_ssize_t index;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001654 dequeobject *deque;
Raymond Hettingerf9d9c792015-03-02 22:47:46 -08001655 size_t state; /* state when the iterator is created */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001656 Py_ssize_t counter; /* number of items remaining for iteration */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001657} dequeiterobject;
1658
Martin v. Löwis59683e82008-06-13 07:50:45 +00001659static PyTypeObject dequeiter_type;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001660
1661static PyObject *
1662deque_iter(dequeobject *deque)
1663{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001664 dequeiterobject *it;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001665
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001666 it = PyObject_GC_New(dequeiterobject, &dequeiter_type);
1667 if (it == NULL)
1668 return NULL;
1669 it->b = deque->leftblock;
1670 it->index = deque->leftindex;
1671 Py_INCREF(deque);
1672 it->deque = deque;
1673 it->state = deque->state;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001674 it->counter = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001675 PyObject_GC_Track(it);
1676 return (PyObject *)it;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001677}
1678
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001679static int
1680dequeiter_traverse(dequeiterobject *dio, visitproc visit, void *arg)
1681{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001682 Py_VISIT(dio->deque);
1683 return 0;
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001684}
1685
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001686static void
1687dequeiter_dealloc(dequeiterobject *dio)
1688{
INADA Naokia6296d32017-08-24 14:55:17 +09001689 /* bpo-31095: UnTrack is needed before calling any callbacks */
1690 PyObject_GC_UnTrack(dio);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001691 Py_XDECREF(dio->deque);
1692 PyObject_GC_Del(dio);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001693}
1694
1695static PyObject *
1696dequeiter_next(dequeiterobject *it)
1697{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001698 PyObject *item;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001699
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001700 if (it->deque->state != it->state) {
1701 it->counter = 0;
1702 PyErr_SetString(PyExc_RuntimeError,
1703 "deque mutated during iteration");
1704 return NULL;
1705 }
1706 if (it->counter == 0)
1707 return NULL;
1708 assert (!(it->b == it->deque->rightblock &&
1709 it->index > it->deque->rightindex));
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001710
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001711 item = it->b->data[it->index];
1712 it->index++;
1713 it->counter--;
1714 if (it->index == BLOCKLEN && it->counter > 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -10001715 CHECK_NOT_END(it->b->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001716 it->b = it->b->rightlink;
1717 it->index = 0;
1718 }
1719 Py_INCREF(item);
1720 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001721}
1722
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001723static PyObject *
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001724dequeiter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1725{
1726 Py_ssize_t i, index=0;
1727 PyObject *deque;
1728 dequeiterobject *it;
1729 if (!PyArg_ParseTuple(args, "O!|n", &deque_type, &deque, &index))
1730 return NULL;
1731 assert(type == &dequeiter_type);
1732
1733 it = (dequeiterobject*)deque_iter((dequeobject *)deque);
1734 if (!it)
1735 return NULL;
1736 /* consume items from the queue */
1737 for(i=0; i<index; i++) {
1738 PyObject *item = dequeiter_next(it);
1739 if (item) {
1740 Py_DECREF(item);
1741 } else {
1742 if (it->counter) {
1743 Py_DECREF(it);
1744 return NULL;
1745 } else
1746 break;
1747 }
1748 }
1749 return (PyObject*)it;
1750}
1751
1752static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301753dequeiter_len(dequeiterobject *it, PyObject *Py_UNUSED(ignored))
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001754{
Antoine Pitrou554f3342010-08-17 18:30:06 +00001755 return PyLong_FromSsize_t(it->counter);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001756}
1757
Armin Rigof5b3e362006-02-11 21:32:43 +00001758PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001759
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001760static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301761dequeiter_reduce(dequeiterobject *it, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001762{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001763 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 +00001764}
1765
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001766static PyMethodDef dequeiter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001767 {"__length_hint__", (PyCFunction)dequeiter_len, METH_NOARGS, length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001768 {"__reduce__", (PyCFunction)dequeiter_reduce, METH_NOARGS, reduce_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001769 {NULL, NULL} /* sentinel */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001770};
1771
Martin v. Löwis59683e82008-06-13 07:50:45 +00001772static PyTypeObject dequeiter_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001773 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger87e69122015-03-02 23:32:02 -08001774 "_collections._deque_iterator", /* tp_name */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001775 sizeof(dequeiterobject), /* tp_basicsize */
1776 0, /* tp_itemsize */
1777 /* methods */
1778 (destructor)dequeiter_dealloc, /* tp_dealloc */
1779 0, /* tp_print */
1780 0, /* tp_getattr */
1781 0, /* tp_setattr */
1782 0, /* tp_reserved */
1783 0, /* tp_repr */
1784 0, /* tp_as_number */
1785 0, /* tp_as_sequence */
1786 0, /* tp_as_mapping */
1787 0, /* tp_hash */
1788 0, /* tp_call */
1789 0, /* tp_str */
1790 PyObject_GenericGetAttr, /* tp_getattro */
1791 0, /* tp_setattro */
1792 0, /* tp_as_buffer */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001793 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001794 0, /* tp_doc */
1795 (traverseproc)dequeiter_traverse, /* tp_traverse */
1796 0, /* tp_clear */
1797 0, /* tp_richcompare */
1798 0, /* tp_weaklistoffset */
1799 PyObject_SelfIter, /* tp_iter */
1800 (iternextfunc)dequeiter_next, /* tp_iternext */
1801 dequeiter_methods, /* tp_methods */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001802 0, /* tp_members */
1803 0, /* tp_getset */
1804 0, /* tp_base */
1805 0, /* tp_dict */
1806 0, /* tp_descr_get */
1807 0, /* tp_descr_set */
1808 0, /* tp_dictoffset */
1809 0, /* tp_init */
1810 0, /* tp_alloc */
1811 dequeiter_new, /* tp_new */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001812 0,
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001813};
1814
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001815/*********************** Deque Reverse Iterator **************************/
1816
Martin v. Löwis59683e82008-06-13 07:50:45 +00001817static PyTypeObject dequereviter_type;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001818
1819static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301820deque_reviter(dequeobject *deque, PyObject *Py_UNUSED(ignored))
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001821{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001822 dequeiterobject *it;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001823
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001824 it = PyObject_GC_New(dequeiterobject, &dequereviter_type);
1825 if (it == NULL)
1826 return NULL;
1827 it->b = deque->rightblock;
1828 it->index = deque->rightindex;
1829 Py_INCREF(deque);
1830 it->deque = deque;
1831 it->state = deque->state;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001832 it->counter = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001833 PyObject_GC_Track(it);
1834 return (PyObject *)it;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001835}
1836
1837static PyObject *
1838dequereviter_next(dequeiterobject *it)
1839{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001840 PyObject *item;
1841 if (it->counter == 0)
1842 return NULL;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001843
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001844 if (it->deque->state != it->state) {
1845 it->counter = 0;
1846 PyErr_SetString(PyExc_RuntimeError,
1847 "deque mutated during iteration");
1848 return NULL;
1849 }
1850 assert (!(it->b == it->deque->leftblock &&
1851 it->index < it->deque->leftindex));
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001853 item = it->b->data[it->index];
1854 it->index--;
1855 it->counter--;
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -07001856 if (it->index < 0 && it->counter > 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -10001857 CHECK_NOT_END(it->b->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001858 it->b = it->b->leftlink;
1859 it->index = BLOCKLEN - 1;
1860 }
1861 Py_INCREF(item);
1862 return item;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001863}
1864
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001865static PyObject *
1866dequereviter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1867{
1868 Py_ssize_t i, index=0;
1869 PyObject *deque;
1870 dequeiterobject *it;
1871 if (!PyArg_ParseTuple(args, "O!|n", &deque_type, &deque, &index))
1872 return NULL;
1873 assert(type == &dequereviter_type);
1874
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301875 it = (dequeiterobject*)deque_reviter((dequeobject *)deque, NULL);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001876 if (!it)
1877 return NULL;
1878 /* consume items from the queue */
1879 for(i=0; i<index; i++) {
1880 PyObject *item = dequereviter_next(it);
1881 if (item) {
1882 Py_DECREF(item);
1883 } else {
1884 if (it->counter) {
1885 Py_DECREF(it);
1886 return NULL;
1887 } else
1888 break;
1889 }
1890 }
1891 return (PyObject*)it;
1892}
1893
Martin v. Löwis59683e82008-06-13 07:50:45 +00001894static PyTypeObject dequereviter_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001895 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger87e69122015-03-02 23:32:02 -08001896 "_collections._deque_reverse_iterator", /* tp_name */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001897 sizeof(dequeiterobject), /* tp_basicsize */
1898 0, /* tp_itemsize */
1899 /* methods */
1900 (destructor)dequeiter_dealloc, /* tp_dealloc */
1901 0, /* tp_print */
1902 0, /* tp_getattr */
1903 0, /* tp_setattr */
1904 0, /* tp_reserved */
1905 0, /* tp_repr */
1906 0, /* tp_as_number */
1907 0, /* tp_as_sequence */
1908 0, /* tp_as_mapping */
1909 0, /* tp_hash */
1910 0, /* tp_call */
1911 0, /* tp_str */
1912 PyObject_GenericGetAttr, /* tp_getattro */
1913 0, /* tp_setattro */
1914 0, /* tp_as_buffer */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001915 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001916 0, /* tp_doc */
1917 (traverseproc)dequeiter_traverse, /* tp_traverse */
1918 0, /* tp_clear */
1919 0, /* tp_richcompare */
1920 0, /* tp_weaklistoffset */
1921 PyObject_SelfIter, /* tp_iter */
1922 (iternextfunc)dequereviter_next, /* tp_iternext */
1923 dequeiter_methods, /* tp_methods */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001924 0, /* tp_members */
1925 0, /* tp_getset */
1926 0, /* tp_base */
1927 0, /* tp_dict */
1928 0, /* tp_descr_get */
1929 0, /* tp_descr_set */
1930 0, /* tp_dictoffset */
1931 0, /* tp_init */
1932 0, /* tp_alloc */
1933 dequereviter_new, /* tp_new */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001934 0,
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001935};
1936
Guido van Rossum1968ad32006-02-25 22:38:04 +00001937/* defaultdict type *********************************************************/
1938
1939typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001940 PyDictObject dict;
1941 PyObject *default_factory;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001942} defdictobject;
1943
1944static PyTypeObject defdict_type; /* Forward */
1945
1946PyDoc_STRVAR(defdict_missing_doc,
1947"__missing__(key) # Called by __getitem__ for missing key; pseudo-code:\n\
Guido van Rossumd8faa362007-04-27 19:54:29 +00001948 if self.default_factory is None: raise KeyError((key,))\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00001949 self[key] = value = self.default_factory()\n\
1950 return value\n\
1951");
1952
1953static PyObject *
1954defdict_missing(defdictobject *dd, PyObject *key)
1955{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001956 PyObject *factory = dd->default_factory;
1957 PyObject *value;
1958 if (factory == NULL || factory == Py_None) {
1959 /* XXX Call dict.__missing__(key) */
1960 PyObject *tup;
1961 tup = PyTuple_Pack(1, key);
1962 if (!tup) return NULL;
1963 PyErr_SetObject(PyExc_KeyError, tup);
1964 Py_DECREF(tup);
1965 return NULL;
1966 }
1967 value = PyEval_CallObject(factory, NULL);
1968 if (value == NULL)
1969 return value;
1970 if (PyObject_SetItem((PyObject *)dd, key, value) < 0) {
1971 Py_DECREF(value);
1972 return NULL;
1973 }
1974 return value;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001975}
1976
1977PyDoc_STRVAR(defdict_copy_doc, "D.copy() -> a shallow copy of D.");
1978
1979static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301980defdict_copy(defdictobject *dd, PyObject *Py_UNUSED(ignored))
Guido van Rossum1968ad32006-02-25 22:38:04 +00001981{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001982 /* This calls the object's class. That only works for subclasses
1983 whose class constructor has the same signature. Subclasses that
1984 define a different constructor signature must override copy().
1985 */
Raymond Hettinger54628fa2009-08-04 19:16:39 +00001986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001987 if (dd->default_factory == NULL)
1988 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd), Py_None, dd, NULL);
1989 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd),
1990 dd->default_factory, dd, NULL);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001991}
1992
1993static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301994defdict_reduce(defdictobject *dd, PyObject *Py_UNUSED(ignored))
Guido van Rossum1968ad32006-02-25 22:38:04 +00001995{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001996 /* __reduce__ must return a 5-tuple as follows:
Guido van Rossum1968ad32006-02-25 22:38:04 +00001997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001998 - factory function
1999 - tuple of args for the factory function
2000 - additional state (here None)
2001 - sequence iterator (here None)
2002 - dictionary iterator (yielding successive (key, value) pairs
Guido van Rossum1968ad32006-02-25 22:38:04 +00002003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002004 This API is used by pickle.py and copy.py.
Guido van Rossum1968ad32006-02-25 22:38:04 +00002005
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002006 For this to be useful with pickle.py, the default_factory
2007 must be picklable; e.g., None, a built-in, or a global
2008 function in a module or package.
Guido van Rossum1968ad32006-02-25 22:38:04 +00002009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002010 Both shallow and deep copying are supported, but for deep
2011 copying, the default_factory must be deep-copyable; e.g. None,
2012 or a built-in (functions are not copyable at this time).
Guido van Rossum1968ad32006-02-25 22:38:04 +00002013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002014 This only works for subclasses as long as their constructor
2015 signature is compatible; the first argument must be the
2016 optional default_factory, defaulting to None.
2017 */
2018 PyObject *args;
2019 PyObject *items;
2020 PyObject *iter;
2021 PyObject *result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002022 _Py_IDENTIFIER(items);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002023
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002024 if (dd->default_factory == NULL || dd->default_factory == Py_None)
2025 args = PyTuple_New(0);
2026 else
2027 args = PyTuple_Pack(1, dd->default_factory);
2028 if (args == NULL)
2029 return NULL;
Victor Stinnerad8c83a2016-09-05 17:53:15 -07002030 items = _PyObject_CallMethodId((PyObject *)dd, &PyId_items, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002031 if (items == NULL) {
2032 Py_DECREF(args);
2033 return NULL;
2034 }
2035 iter = PyObject_GetIter(items);
2036 if (iter == NULL) {
2037 Py_DECREF(items);
2038 Py_DECREF(args);
2039 return NULL;
2040 }
2041 result = PyTuple_Pack(5, Py_TYPE(dd), args,
2042 Py_None, Py_None, iter);
2043 Py_DECREF(iter);
2044 Py_DECREF(items);
2045 Py_DECREF(args);
2046 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00002047}
2048
2049static PyMethodDef defdict_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002050 {"__missing__", (PyCFunction)defdict_missing, METH_O,
2051 defdict_missing_doc},
2052 {"copy", (PyCFunction)defdict_copy, METH_NOARGS,
2053 defdict_copy_doc},
2054 {"__copy__", (PyCFunction)defdict_copy, METH_NOARGS,
2055 defdict_copy_doc},
2056 {"__reduce__", (PyCFunction)defdict_reduce, METH_NOARGS,
2057 reduce_doc},
2058 {NULL}
Guido van Rossum1968ad32006-02-25 22:38:04 +00002059};
2060
2061static PyMemberDef defdict_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002062 {"default_factory", T_OBJECT,
2063 offsetof(defdictobject, default_factory), 0,
2064 PyDoc_STR("Factory for default value called by __missing__().")},
2065 {NULL}
Guido van Rossum1968ad32006-02-25 22:38:04 +00002066};
2067
2068static void
2069defdict_dealloc(defdictobject *dd)
2070{
INADA Naokia6296d32017-08-24 14:55:17 +09002071 /* bpo-31095: UnTrack is needed before calling any callbacks */
2072 PyObject_GC_UnTrack(dd);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002073 Py_CLEAR(dd->default_factory);
2074 PyDict_Type.tp_dealloc((PyObject *)dd);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002075}
2076
Guido van Rossum1968ad32006-02-25 22:38:04 +00002077static PyObject *
2078defdict_repr(defdictobject *dd)
2079{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002080 PyObject *baserepr;
2081 PyObject *defrepr;
2082 PyObject *result;
2083 baserepr = PyDict_Type.tp_repr((PyObject *)dd);
2084 if (baserepr == NULL)
2085 return NULL;
2086 if (dd->default_factory == NULL)
2087 defrepr = PyUnicode_FromString("None");
2088 else
2089 {
2090 int status = Py_ReprEnter(dd->default_factory);
2091 if (status != 0) {
Antoine Pitrouf5f1fe02012-02-15 02:42:46 +01002092 if (status < 0) {
2093 Py_DECREF(baserepr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002094 return NULL;
Antoine Pitrouf5f1fe02012-02-15 02:42:46 +01002095 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002096 defrepr = PyUnicode_FromString("...");
2097 }
2098 else
2099 defrepr = PyObject_Repr(dd->default_factory);
2100 Py_ReprLeave(dd->default_factory);
2101 }
2102 if (defrepr == NULL) {
2103 Py_DECREF(baserepr);
2104 return NULL;
2105 }
Serhiy Storchakab3a77962017-09-21 14:24:13 +03002106 result = PyUnicode_FromFormat("%s(%U, %U)",
2107 _PyType_Name(Py_TYPE(dd)),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002108 defrepr, baserepr);
2109 Py_DECREF(defrepr);
2110 Py_DECREF(baserepr);
2111 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00002112}
2113
2114static int
2115defdict_traverse(PyObject *self, visitproc visit, void *arg)
2116{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002117 Py_VISIT(((defdictobject *)self)->default_factory);
2118 return PyDict_Type.tp_traverse(self, visit, arg);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002119}
2120
2121static int
2122defdict_tp_clear(defdictobject *dd)
2123{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002124 Py_CLEAR(dd->default_factory);
2125 return PyDict_Type.tp_clear((PyObject *)dd);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002126}
2127
2128static int
2129defdict_init(PyObject *self, PyObject *args, PyObject *kwds)
2130{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002131 defdictobject *dd = (defdictobject *)self;
2132 PyObject *olddefault = dd->default_factory;
2133 PyObject *newdefault = NULL;
2134 PyObject *newargs;
2135 int result;
2136 if (args == NULL || !PyTuple_Check(args))
2137 newargs = PyTuple_New(0);
2138 else {
2139 Py_ssize_t n = PyTuple_GET_SIZE(args);
2140 if (n > 0) {
2141 newdefault = PyTuple_GET_ITEM(args, 0);
2142 if (!PyCallable_Check(newdefault) && newdefault != Py_None) {
2143 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger239aba72015-07-20 03:09:22 -04002144 "first argument must be callable or None");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002145 return -1;
2146 }
2147 }
2148 newargs = PySequence_GetSlice(args, 1, n);
2149 }
2150 if (newargs == NULL)
2151 return -1;
2152 Py_XINCREF(newdefault);
2153 dd->default_factory = newdefault;
2154 result = PyDict_Type.tp_init(self, newargs, kwds);
2155 Py_DECREF(newargs);
2156 Py_XDECREF(olddefault);
2157 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00002158}
2159
2160PyDoc_STRVAR(defdict_doc,
Benjamin Peterson9cb33b72014-01-13 23:56:05 -05002161"defaultdict(default_factory[, ...]) --> dict with default factory\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00002162\n\
2163The default factory is called without arguments to produce\n\
2164a new value when a key is not present, in __getitem__ only.\n\
2165A defaultdict compares equal to a dict with the same items.\n\
Benjamin Peterson9cb33b72014-01-13 23:56:05 -05002166All remaining arguments are treated the same as if they were\n\
2167passed to the dict constructor, including keyword arguments.\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00002168");
2169
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002170/* See comment in xxsubtype.c */
2171#define DEFERRED_ADDRESS(ADDR) 0
2172
Guido van Rossum1968ad32006-02-25 22:38:04 +00002173static PyTypeObject defdict_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002174 PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0)
2175 "collections.defaultdict", /* tp_name */
2176 sizeof(defdictobject), /* tp_basicsize */
2177 0, /* tp_itemsize */
2178 /* methods */
2179 (destructor)defdict_dealloc, /* tp_dealloc */
2180 0, /* tp_print */
2181 0, /* tp_getattr */
2182 0, /* tp_setattr */
2183 0, /* tp_reserved */
2184 (reprfunc)defdict_repr, /* tp_repr */
2185 0, /* tp_as_number */
2186 0, /* tp_as_sequence */
2187 0, /* tp_as_mapping */
2188 0, /* tp_hash */
2189 0, /* tp_call */
2190 0, /* tp_str */
2191 PyObject_GenericGetAttr, /* tp_getattro */
2192 0, /* tp_setattro */
2193 0, /* tp_as_buffer */
2194 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
2195 /* tp_flags */
2196 defdict_doc, /* tp_doc */
2197 defdict_traverse, /* tp_traverse */
2198 (inquiry)defdict_tp_clear, /* tp_clear */
2199 0, /* tp_richcompare */
2200 0, /* tp_weaklistoffset*/
2201 0, /* tp_iter */
2202 0, /* tp_iternext */
2203 defdict_methods, /* tp_methods */
2204 defdict_members, /* tp_members */
2205 0, /* tp_getset */
2206 DEFERRED_ADDRESS(&PyDict_Type), /* tp_base */
2207 0, /* tp_dict */
2208 0, /* tp_descr_get */
2209 0, /* tp_descr_set */
2210 0, /* tp_dictoffset */
2211 defdict_init, /* tp_init */
2212 PyType_GenericAlloc, /* tp_alloc */
2213 0, /* tp_new */
2214 PyObject_GC_Del, /* tp_free */
Guido van Rossum1968ad32006-02-25 22:38:04 +00002215};
2216
Raymond Hettinger96f34102010-12-15 16:30:37 +00002217/* helper function for Counter *********************************************/
2218
2219PyDoc_STRVAR(_count_elements_doc,
2220"_count_elements(mapping, iterable) -> None\n\
2221\n\
Raymond Hettingera24dca62017-01-12 22:25:25 -08002222Count elements in the iterable, updating the mapping");
Raymond Hettinger96f34102010-12-15 16:30:37 +00002223
2224static PyObject *
2225_count_elements(PyObject *self, PyObject *args)
2226{
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002227 _Py_IDENTIFIER(get);
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002228 _Py_IDENTIFIER(__setitem__);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002229 PyObject *it, *iterable, *mapping, *oldval;
2230 PyObject *newval = NULL;
2231 PyObject *key = NULL;
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002232 PyObject *bound_get = NULL;
2233 PyObject *mapping_get;
2234 PyObject *dict_get;
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002235 PyObject *mapping_setitem;
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002236 PyObject *dict_setitem;
Raymond Hettinger96f34102010-12-15 16:30:37 +00002237
2238 if (!PyArg_UnpackTuple(args, "_count_elements", 2, 2, &mapping, &iterable))
2239 return NULL;
2240
Raymond Hettinger96f34102010-12-15 16:30:37 +00002241 it = PyObject_GetIter(iterable);
2242 if (it == NULL)
2243 return NULL;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002244
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002245 /* Only take the fast path when get() and __setitem__()
2246 * have not been overridden.
2247 */
2248 mapping_get = _PyType_LookupId(Py_TYPE(mapping), &PyId_get);
2249 dict_get = _PyType_LookupId(&PyDict_Type, &PyId_get);
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002250 mapping_setitem = _PyType_LookupId(Py_TYPE(mapping), &PyId___setitem__);
2251 dict_setitem = _PyType_LookupId(&PyDict_Type, &PyId___setitem__);
2252
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002253 if (mapping_get != NULL && mapping_get == dict_get &&
Oren Milman31aca4b2017-09-27 06:18:21 +03002254 mapping_setitem != NULL && mapping_setitem == dict_setitem &&
2255 PyDict_Check(mapping))
2256 {
Raymond Hettinger426e0522011-01-03 02:12:02 +00002257 while (1) {
Raymond Hettinger507d9972014-05-18 21:32:40 +01002258 /* Fast path advantages:
2259 1. Eliminate double hashing
2260 (by re-using the same hash for both the get and set)
2261 2. Avoid argument overhead of PyObject_CallFunctionObjArgs
2262 (argument tuple creation and parsing)
2263 3. Avoid indirection through a bound method object
2264 (creates another argument tuple)
2265 4. Avoid initial increment from zero
2266 (reuse an existing one-object instead)
2267 */
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002268 Py_hash_t hash;
2269
Raymond Hettinger426e0522011-01-03 02:12:02 +00002270 key = PyIter_Next(it);
Victor Stinnera154b5c2011-04-20 23:23:52 +02002271 if (key == NULL)
2272 break;
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002273
2274 if (!PyUnicode_CheckExact(key) ||
2275 (hash = ((PyASCIIObject *) key)->hash) == -1)
2276 {
2277 hash = PyObject_Hash(key);
Raymond Hettingerda2850f2015-02-27 12:42:54 -08002278 if (hash == -1)
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002279 goto done;
2280 }
2281
2282 oldval = _PyDict_GetItem_KnownHash(mapping, key, hash);
Raymond Hettinger426e0522011-01-03 02:12:02 +00002283 if (oldval == NULL) {
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02002284 if (PyErr_Occurred())
2285 goto done;
Serhiy Storchakaba85d692017-03-30 09:09:41 +03002286 if (_PyDict_SetItem_KnownHash(mapping, key, _PyLong_One, hash) < 0)
Raymond Hettinger507d9972014-05-18 21:32:40 +01002287 goto done;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002288 } else {
Serhiy Storchakaba85d692017-03-30 09:09:41 +03002289 newval = PyNumber_Add(oldval, _PyLong_One);
Raymond Hettinger426e0522011-01-03 02:12:02 +00002290 if (newval == NULL)
Raymond Hettinger507d9972014-05-18 21:32:40 +01002291 goto done;
Raymond Hettinger28c995d2015-08-14 02:07:41 -07002292 if (_PyDict_SetItem_KnownHash(mapping, key, newval, hash) < 0)
Raymond Hettinger507d9972014-05-18 21:32:40 +01002293 goto done;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002294 Py_CLEAR(newval);
2295 }
2296 Py_DECREF(key);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002297 }
Raymond Hettinger426e0522011-01-03 02:12:02 +00002298 } else {
Victor Stinnere7f516c2013-11-06 23:52:55 +01002299 bound_get = _PyObject_GetAttrId(mapping, &PyId_get);
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002300 if (bound_get == NULL)
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002301 goto done;
2302
Raymond Hettinger426e0522011-01-03 02:12:02 +00002303 while (1) {
2304 key = PyIter_Next(it);
Victor Stinnera154b5c2011-04-20 23:23:52 +02002305 if (key == NULL)
2306 break;
Serhiy Storchakaba85d692017-03-30 09:09:41 +03002307 oldval = PyObject_CallFunctionObjArgs(bound_get, key, _PyLong_Zero, NULL);
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002308 if (oldval == NULL)
2309 break;
Serhiy Storchakaba85d692017-03-30 09:09:41 +03002310 newval = PyNumber_Add(oldval, _PyLong_One);
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002311 Py_DECREF(oldval);
2312 if (newval == NULL)
2313 break;
Raymond Hettinger28c995d2015-08-14 02:07:41 -07002314 if (PyObject_SetItem(mapping, key, newval) < 0)
Raymond Hettinger96f34102010-12-15 16:30:37 +00002315 break;
2316 Py_CLEAR(newval);
Raymond Hettinger426e0522011-01-03 02:12:02 +00002317 Py_DECREF(key);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002318 }
Raymond Hettinger96f34102010-12-15 16:30:37 +00002319 }
Raymond Hettinger426e0522011-01-03 02:12:02 +00002320
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002321done:
Raymond Hettinger96f34102010-12-15 16:30:37 +00002322 Py_DECREF(it);
2323 Py_XDECREF(key);
2324 Py_XDECREF(newval);
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002325 Py_XDECREF(bound_get);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002326 if (PyErr_Occurred())
2327 return NULL;
2328 Py_RETURN_NONE;
2329}
2330
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002331/* module level code ********************************************************/
2332
2333PyDoc_STRVAR(module_doc,
Guido van Rossum1968ad32006-02-25 22:38:04 +00002334"High performance data structures.\n\
2335- deque: ordered collection accessible from endpoints only\n\
2336- defaultdict: dict subclass with a default value factory\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002337");
2338
Raymond Hettinger96f34102010-12-15 16:30:37 +00002339static struct PyMethodDef module_functions[] = {
2340 {"_count_elements", _count_elements, METH_VARARGS, _count_elements_doc},
2341 {NULL, NULL} /* sentinel */
2342};
Martin v. Löwis1a214512008-06-11 05:26:20 +00002343
2344static struct PyModuleDef _collectionsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002345 PyModuleDef_HEAD_INIT,
2346 "_collections",
2347 module_doc,
2348 -1,
Raymond Hettinger96f34102010-12-15 16:30:37 +00002349 module_functions,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002350 NULL,
2351 NULL,
2352 NULL,
2353 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002354};
2355
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002356PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002357PyInit__collections(void)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002358{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002359 PyObject *m;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002360
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002361 m = PyModule_Create(&_collectionsmodule);
2362 if (m == NULL)
2363 return NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002365 if (PyType_Ready(&deque_type) < 0)
2366 return NULL;
2367 Py_INCREF(&deque_type);
2368 PyModule_AddObject(m, "deque", (PyObject *)&deque_type);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002370 defdict_type.tp_base = &PyDict_Type;
2371 if (PyType_Ready(&defdict_type) < 0)
2372 return NULL;
2373 Py_INCREF(&defdict_type);
2374 PyModule_AddObject(m, "defaultdict", (PyObject *)&defdict_type);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002375
Eric Snow47db7172015-05-29 22:21:39 -06002376 Py_INCREF(&PyODict_Type);
2377 PyModule_AddObject(m, "OrderedDict", (PyObject *)&PyODict_Type);
2378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002379 if (PyType_Ready(&dequeiter_type) < 0)
2380 return NULL;
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002381 Py_INCREF(&dequeiter_type);
2382 PyModule_AddObject(m, "_deque_iterator", (PyObject *)&dequeiter_type);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002384 if (PyType_Ready(&dequereviter_type) < 0)
2385 return NULL;
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002386 Py_INCREF(&dequereviter_type);
2387 PyModule_AddObject(m, "_deque_reverse_iterator", (PyObject *)&dequereviter_type);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00002388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002389 return m;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002390}