blob: 65d556c5a0e5b4cb62ff79c2700a2cdc3e884252 [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
doko@ubuntu.combc731502016-05-18 01:06:01 +0200267static 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
doko@ubuntu.com17f0e612016-06-14 07:27:58 +0200304static 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 Hettinger88057172016-09-11 22:45:53 -0700406 if (deque->rightindex == BLOCKLEN - 1) {
407 block *b = newblock();
408 if (b == NULL) {
409 Py_DECREF(item);
410 Py_DECREF(it);
411 return NULL;
412 }
413 b->leftlink = deque->rightblock;
414 CHECK_END(deque->rightblock->rightlink);
415 deque->rightblock->rightlink = b;
416 deque->rightblock = b;
417 MARK_END(b->rightlink);
418 deque->rightindex = -1;
419 }
420 Py_SIZE(deque)++;
421 deque->rightindex++;
422 deque->rightblock->data[deque->rightindex] = item;
423 if (NEEDS_TRIM(deque, maxlen)) {
424 PyObject *olditem = deque_popleft(deque, NULL);
425 Py_DECREF(olditem);
426 } else {
427 deque->state++;
Raymond Hettinger6b1e1132015-10-11 09:43:50 -0700428 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000429 }
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700430 return finalize_iterator(it);
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000431}
432
Tim Peters1065f752004-10-01 01:03:29 +0000433PyDoc_STRVAR(extend_doc,
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000434"Extend the right side of the deque with elements from the iterable");
435
436static PyObject *
437deque_extendleft(dequeobject *deque, PyObject *iterable)
438{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000439 PyObject *it, *item;
Raymond Hettinger7a845522015-09-26 01:30:51 -0700440 PyObject *(*iternext)(PyObject *);
Raymond Hettinger6b1e1132015-10-11 09:43:50 -0700441 Py_ssize_t maxlen = deque->maxlen;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000443 /* Handle case where id(deque) == id(iterable) */
444 if ((PyObject *)deque == iterable) {
445 PyObject *result;
446 PyObject *s = PySequence_List(iterable);
447 if (s == NULL)
448 return NULL;
449 result = deque_extendleft(deque, s);
450 Py_DECREF(s);
451 return result;
452 }
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000453
Raymond Hettingerd79d5b12016-03-04 09:55:07 -0800454 it = PyObject_GetIter(iterable);
455 if (it == NULL)
456 return NULL;
457
458 if (maxlen == 0)
459 return consume_iterator(it);
460
Raymond Hettingerd9c116c2013-07-09 00:13:21 -0700461 /* Space saving heuristic. Start filling from the right */
462 if (Py_SIZE(deque) == 0) {
463 assert(deque->leftblock == deque->rightblock);
464 assert(deque->leftindex == deque->rightindex+1);
465 deque->leftindex = BLOCKLEN - 1;
466 deque->rightindex = BLOCKLEN - 2;
467 }
468
Raymond Hettinger7a845522015-09-26 01:30:51 -0700469 iternext = *Py_TYPE(it)->tp_iternext;
470 while ((item = iternext(it)) != NULL) {
Raymond Hettinger88057172016-09-11 22:45:53 -0700471 if (deque->leftindex == 0) {
472 block *b = newblock();
473 if (b == NULL) {
474 Py_DECREF(item);
475 Py_DECREF(it);
476 return NULL;
477 }
478 b->rightlink = deque->leftblock;
479 CHECK_END(deque->leftblock->leftlink);
480 deque->leftblock->leftlink = b;
481 deque->leftblock = b;
482 MARK_END(b->leftlink);
483 deque->leftindex = BLOCKLEN;
484 }
485 Py_SIZE(deque)++;
486 deque->leftindex--;
487 deque->leftblock->data[deque->leftindex] = item;
488 if (NEEDS_TRIM(deque, maxlen)) {
489 PyObject *olditem = deque_pop(deque, NULL);
490 Py_DECREF(olditem);
491 } else {
492 deque->state++;
Raymond Hettinger6b1e1132015-10-11 09:43:50 -0700493 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 }
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700495 return finalize_iterator(it);
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000496}
497
Tim Peters1065f752004-10-01 01:03:29 +0000498PyDoc_STRVAR(extendleft_doc,
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000499"Extend the left side of the deque with elements from the iterable");
500
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000501static PyObject *
502deque_inplace_concat(dequeobject *deque, PyObject *other)
503{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 PyObject *result;
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 result = deque_extend(deque, other);
507 if (result == NULL)
508 return result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000509 Py_INCREF(deque);
Raymond Hettinger2b2b7532015-09-05 17:05:52 -0700510 Py_DECREF(result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 return (PyObject *)deque;
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000512}
513
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700514static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530515deque_copy(PyObject *deque, PyObject *Py_UNUSED(ignored))
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700516{
517 dequeobject *old_deque = (dequeobject *)deque;
518 if (Py_TYPE(deque) == &deque_type) {
519 dequeobject *new_deque;
520 PyObject *rv;
521
522 new_deque = (dequeobject *)deque_new(&deque_type, (PyObject *)NULL, (PyObject *)NULL);
523 if (new_deque == NULL)
524 return NULL;
525 new_deque->maxlen = old_deque->maxlen;
526 /* Fast path for the deque_repeat() common case where len(deque) == 1 */
Raymond Hettinger0443ac22015-10-05 22:52:37 -0400527 if (Py_SIZE(deque) == 1) {
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700528 PyObject *item = old_deque->leftblock->data[old_deque->leftindex];
529 rv = deque_append(new_deque, item);
530 } else {
531 rv = deque_extend(new_deque, deque);
532 }
533 if (rv != NULL) {
534 Py_DECREF(rv);
535 return (PyObject *)new_deque;
536 }
537 Py_DECREF(new_deque);
538 return NULL;
539 }
540 if (old_deque->maxlen < 0)
Victor Stinner7bfb42d2016-12-05 17:04:32 +0100541 return PyObject_CallFunctionObjArgs((PyObject *)(Py_TYPE(deque)),
542 deque, NULL);
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700543 else
544 return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "Oi",
545 deque, old_deque->maxlen, NULL);
546}
547
548PyDoc_STRVAR(copy_doc, "Return a shallow copy of a deque.");
Raymond Hettinger41290a62015-03-31 08:12:23 -0700549
550static PyObject *
551deque_concat(dequeobject *deque, PyObject *other)
552{
Benjamin Peterson1a629212015-04-04 10:52:36 -0400553 PyObject *new_deque, *result;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700554 int rv;
555
556 rv = PyObject_IsInstance(other, (PyObject *)&deque_type);
557 if (rv <= 0) {
558 if (rv == 0) {
559 PyErr_Format(PyExc_TypeError,
560 "can only concatenate deque (not \"%.200s\") to deque",
561 other->ob_type->tp_name);
562 }
563 return NULL;
564 }
565
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530566 new_deque = deque_copy((PyObject *)deque, NULL);
Raymond Hettinger41290a62015-03-31 08:12:23 -0700567 if (new_deque == NULL)
568 return NULL;
Benjamin Peterson1a629212015-04-04 10:52:36 -0400569 result = deque_extend((dequeobject *)new_deque, other);
570 if (result == NULL) {
571 Py_DECREF(new_deque);
572 return NULL;
573 }
574 Py_DECREF(result);
575 return new_deque;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700576}
577
Serhiy Storchakaa5c42282018-05-31 07:34:34 +0300578static int
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700579deque_clear(dequeobject *deque)
580{
581 block *b;
582 block *prevblock;
583 block *leftblock;
584 Py_ssize_t leftindex;
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800585 Py_ssize_t n, m;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700586 PyObject *item;
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800587 PyObject **itemptr, **limit;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700588
Raymond Hettinger38031142015-09-29 22:45:05 -0700589 if (Py_SIZE(deque) == 0)
Serhiy Storchakaa5c42282018-05-31 07:34:34 +0300590 return 0;
Raymond Hettinger38031142015-09-29 22:45:05 -0700591
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700592 /* During the process of clearing a deque, decrefs can cause the
593 deque to mutate. To avoid fatal confusion, we have to make the
594 deque empty before clearing the blocks and never refer to
595 anything via deque->ref while clearing. (This is the same
596 technique used for clearing lists, sets, and dicts.)
597
598 Making the deque empty requires allocating a new empty block. In
599 the unlikely event that memory is full, we fall back to an
600 alternate method that doesn't require a new block. Repeating
601 pops in a while-loop is slower, possibly re-entrant (and a clever
602 adversary could cause it to never terminate).
603 */
604
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700605 b = newblock();
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700606 if (b == NULL) {
607 PyErr_Clear();
608 goto alternate_method;
609 }
610
611 /* Remember the old size, leftblock, and leftindex */
Raymond Hettinger6f86a332016-03-02 00:30:58 -0800612 n = Py_SIZE(deque);
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700613 leftblock = deque->leftblock;
614 leftindex = deque->leftindex;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700615
616 /* Set the deque to be empty using the newly allocated block */
617 MARK_END(b->leftlink);
618 MARK_END(b->rightlink);
619 Py_SIZE(deque) = 0;
620 deque->leftblock = b;
621 deque->rightblock = b;
622 deque->leftindex = CENTER + 1;
623 deque->rightindex = CENTER;
624 deque->state++;
625
626 /* Now the old size, leftblock, and leftindex are disconnected from
627 the empty deque and we can use them to decref the pointers.
628 */
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800629 m = (BLOCKLEN - leftindex > n) ? n : BLOCKLEN - leftindex;
Raymond Hettinger589106b2016-03-02 00:06:21 -0800630 itemptr = &leftblock->data[leftindex];
Raymond Hettinger6f86a332016-03-02 00:30:58 -0800631 limit = itemptr + m;
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800632 n -= m;
633 while (1) {
634 if (itemptr == limit) {
635 if (n == 0)
636 break;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700637 CHECK_NOT_END(leftblock->rightlink);
638 prevblock = leftblock;
639 leftblock = leftblock->rightlink;
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800640 m = (n > BLOCKLEN) ? BLOCKLEN : n;
Raymond Hettinger589106b2016-03-02 00:06:21 -0800641 itemptr = leftblock->data;
Raymond Hettinger6f86a332016-03-02 00:30:58 -0800642 limit = itemptr + m;
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800643 n -= m;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700644 freeblock(prevblock);
645 }
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800646 item = *(itemptr++);
647 Py_DECREF(item);
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700648 }
649 CHECK_END(leftblock->rightlink);
650 freeblock(leftblock);
Serhiy Storchakaa5c42282018-05-31 07:34:34 +0300651 return 0;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700652
653 alternate_method:
654 while (Py_SIZE(deque)) {
655 item = deque_pop(deque, NULL);
656 assert (item != NULL);
657 Py_DECREF(item);
658 }
Serhiy Storchakaa5c42282018-05-31 07:34:34 +0300659 return 0;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700660}
661
662static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530663deque_clearmethod(dequeobject *deque, PyObject *Py_UNUSED(ignored))
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700664{
665 deque_clear(deque);
666 Py_RETURN_NONE;
667}
668
669PyDoc_STRVAR(clear_doc, "Remove all elements from the deque.");
Raymond Hettinger41290a62015-03-31 08:12:23 -0700670
671static PyObject *
Raymond Hettinger41290a62015-03-31 08:12:23 -0700672deque_inplace_repeat(dequeobject *deque, Py_ssize_t n)
673{
Raymond Hettingerc22eee62015-09-26 02:14:50 -0700674 Py_ssize_t i, m, size;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700675 PyObject *seq;
676 PyObject *rv;
677
678 size = Py_SIZE(deque);
679 if (size == 0 || n == 1) {
680 Py_INCREF(deque);
681 return (PyObject *)deque;
682 }
683
684 if (n <= 0) {
685 deque_clear(deque);
686 Py_INCREF(deque);
687 return (PyObject *)deque;
688 }
689
Raymond Hettinger41290a62015-03-31 08:12:23 -0700690 if (size == 1) {
691 /* common case, repeating a single element */
692 PyObject *item = deque->leftblock->data[deque->leftindex];
693
Raymond Hettingera7f630092015-10-10 23:56:02 -0400694 if (deque->maxlen >= 0 && n > deque->maxlen)
Raymond Hettinger41290a62015-03-31 08:12:23 -0700695 n = deque->maxlen;
696
Raymond Hettinger67c78b52015-09-12 11:00:20 -0400697 deque->state++;
Raymond Hettingerad262252015-09-14 01:03:04 -0400698 for (i = 0 ; i < n-1 ; ) {
Raymond Hettinger67c78b52015-09-12 11:00:20 -0400699 if (deque->rightindex == BLOCKLEN - 1) {
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700700 block *b = newblock();
Raymond Hettinger67c78b52015-09-12 11:00:20 -0400701 if (b == NULL) {
702 Py_SIZE(deque) += i;
703 return NULL;
704 }
705 b->leftlink = deque->rightblock;
706 CHECK_END(deque->rightblock->rightlink);
707 deque->rightblock->rightlink = b;
708 deque->rightblock = b;
709 MARK_END(b->rightlink);
710 deque->rightindex = -1;
711 }
Raymond Hettingerc22eee62015-09-26 02:14:50 -0700712 m = n - 1 - i;
713 if (m > BLOCKLEN - 1 - deque->rightindex)
714 m = BLOCKLEN - 1 - deque->rightindex;
715 i += m;
716 while (m--) {
Raymond Hettingerad262252015-09-14 01:03:04 -0400717 deque->rightindex++;
718 Py_INCREF(item);
719 deque->rightblock->data[deque->rightindex] = item;
720 }
Raymond Hettinger41290a62015-03-31 08:12:23 -0700721 }
Raymond Hettinger67c78b52015-09-12 11:00:20 -0400722 Py_SIZE(deque) += i;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700723 Py_INCREF(deque);
724 return (PyObject *)deque;
725 }
726
Raymond Hettinger20151f52015-10-16 22:47:29 -0700727 if ((size_t)size > PY_SSIZE_T_MAX / (size_t)n) {
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400728 return PyErr_NoMemory();
729 }
730
Raymond Hettinger41290a62015-03-31 08:12:23 -0700731 seq = PySequence_List((PyObject *)deque);
732 if (seq == NULL)
733 return seq;
734
Louie Lu357bad72017-02-24 11:59:49 +0800735 /* Reduce the number of repetitions when maxlen would be exceeded */
736 if (deque->maxlen >= 0 && n * size > deque->maxlen)
737 n = (deque->maxlen + size - 1) / size;
738
Raymond Hettinger41290a62015-03-31 08:12:23 -0700739 for (i = 0 ; i < n-1 ; i++) {
740 rv = deque_extend(deque, seq);
741 if (rv == NULL) {
742 Py_DECREF(seq);
743 return NULL;
744 }
745 Py_DECREF(rv);
746 }
747 Py_INCREF(deque);
748 Py_DECREF(seq);
749 return (PyObject *)deque;
750}
751
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400752static PyObject *
753deque_repeat(dequeobject *deque, Py_ssize_t n)
754{
755 dequeobject *new_deque;
Raymond Hettinger95e2cc52015-09-13 02:41:18 -0400756 PyObject *rv;
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400757
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530758 new_deque = (dequeobject *)deque_copy((PyObject *) deque, NULL);
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400759 if (new_deque == NULL)
760 return NULL;
Raymond Hettinger95e2cc52015-09-13 02:41:18 -0400761 rv = deque_inplace_repeat(new_deque, n);
762 Py_DECREF(new_deque);
763 return rv;
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400764}
765
Raymond Hettinger54023152014-04-23 00:58:48 -0700766/* The rotate() method is part of the public API and is used internally
767as a primitive for other methods.
768
769Rotation by 1 or -1 is a common case, so any optimizations for high
770volume rotations should take care not to penalize the common case.
771
772Conceptually, a rotate by one is equivalent to a pop on one side and an
773append on the other. However, a pop/append pair is unnecessarily slow
Martin Panterd2ad5712015-11-02 04:20:33 +0000774because it requires an incref/decref pair for an object located randomly
Raymond Hettinger54023152014-04-23 00:58:48 -0700775in memory. It is better to just move the object pointer from one block
776to the next without changing the reference count.
777
778When moving batches of pointers, it is tempting to use memcpy() but that
779proved to be slower than a simple loop for a variety of reasons.
780Memcpy() cannot know in advance that we're copying pointers instead of
781bytes, that the source and destination are pointer aligned and
782non-overlapping, that moving just one pointer is a common case, that we
783never need to move more than BLOCKLEN pointers, and that at least one
784pointer is always moved.
785
786For high volume rotations, newblock() and freeblock() are never called
787more than once. Previously emptied blocks are immediately reused as a
788destination block. If a block is left-over at the end, it is freed.
789*/
790
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000791static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000792_deque_rotate(dequeobject *deque, Py_ssize_t n)
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000793{
Raymond Hettinger3959af92013-07-13 02:34:08 -0700794 block *b = NULL;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700795 block *leftblock = deque->leftblock;
796 block *rightblock = deque->rightblock;
797 Py_ssize_t leftindex = deque->leftindex;
798 Py_ssize_t rightindex = deque->rightindex;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000799 Py_ssize_t len=Py_SIZE(deque), halflen=len>>1;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700800 int rv = -1;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000801
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800802 if (len <= 1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 return 0;
804 if (n > halflen || n < -halflen) {
805 n %= len;
806 if (n > halflen)
807 n -= len;
808 else if (n < -halflen)
809 n += len;
810 }
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500811 assert(len > 1);
Raymond Hettingera4409c12013-02-04 00:08:12 -0500812 assert(-halflen <= n && n <= halflen);
Raymond Hettinger231ee4d2013-02-02 11:24:43 -0800813
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800814 deque->state++;
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500815 while (n > 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700816 if (leftindex == 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700817 if (b == NULL) {
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700818 b = newblock();
Raymond Hettinger3959af92013-07-13 02:34:08 -0700819 if (b == NULL)
820 goto done;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700821 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000822 b->rightlink = leftblock;
823 CHECK_END(leftblock->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700824 leftblock->leftlink = b;
825 leftblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000826 MARK_END(b->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700827 leftindex = BLOCKLEN;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700828 b = NULL;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800829 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700830 assert(leftindex > 0);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700831 {
832 PyObject **src, **dest;
833 Py_ssize_t m = n;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800834
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700835 if (m > rightindex + 1)
836 m = rightindex + 1;
837 if (m > leftindex)
838 m = leftindex;
839 assert (m > 0 && m <= len);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700840 rightindex -= m;
841 leftindex -= m;
Raymond Hettinger0e259f12015-02-01 22:53:41 -0800842 src = &rightblock->data[rightindex + 1];
843 dest = &leftblock->data[leftindex];
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700844 n -= m;
Raymond Hettinger840533b2013-07-13 17:03:58 -0700845 do {
Raymond Hettinger0e259f12015-02-01 22:53:41 -0800846 *(dest++) = *(src++);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700847 } while (--m);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700848 }
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -0700849 if (rightindex < 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700850 assert(leftblock != rightblock);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700851 assert(b == NULL);
Raymond Hettinger3959af92013-07-13 02:34:08 -0700852 b = rightblock;
Raymond Hettingerb97cc492013-07-21 01:51:07 -0700853 CHECK_NOT_END(rightblock->leftlink);
854 rightblock = rightblock->leftlink;
855 MARK_END(rightblock->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700856 rightindex = BLOCKLEN - 1;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800857 }
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800858 }
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500859 while (n < 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700860 if (rightindex == BLOCKLEN - 1) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700861 if (b == NULL) {
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700862 b = newblock();
Raymond Hettinger3959af92013-07-13 02:34:08 -0700863 if (b == NULL)
864 goto done;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700865 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000866 b->leftlink = rightblock;
867 CHECK_END(rightblock->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700868 rightblock->rightlink = b;
869 rightblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000870 MARK_END(b->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700871 rightindex = -1;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700872 b = NULL;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800873 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700874 assert (rightindex < BLOCKLEN - 1);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700875 {
876 PyObject **src, **dest;
877 Py_ssize_t m = -n;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800878
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700879 if (m > BLOCKLEN - leftindex)
880 m = BLOCKLEN - leftindex;
881 if (m > BLOCKLEN - 1 - rightindex)
882 m = BLOCKLEN - 1 - rightindex;
883 assert (m > 0 && m <= len);
884 src = &leftblock->data[leftindex];
885 dest = &rightblock->data[rightindex + 1];
886 leftindex += m;
887 rightindex += m;
888 n += m;
Raymond Hettinger840533b2013-07-13 17:03:58 -0700889 do {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700890 *(dest++) = *(src++);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700891 } while (--m);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700892 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700893 if (leftindex == BLOCKLEN) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700894 assert(leftblock != rightblock);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700895 assert(b == NULL);
Raymond Hettinger3959af92013-07-13 02:34:08 -0700896 b = leftblock;
Raymond Hettingerb97cc492013-07-21 01:51:07 -0700897 CHECK_NOT_END(leftblock->rightlink);
898 leftblock = leftblock->rightlink;
899 MARK_END(leftblock->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700900 leftindex = 0;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800901 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000902 }
Raymond Hettinger3959af92013-07-13 02:34:08 -0700903 rv = 0;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700904done:
Raymond Hettinger3959af92013-07-13 02:34:08 -0700905 if (b != NULL)
906 freeblock(b);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700907 deque->leftblock = leftblock;
908 deque->rightblock = rightblock;
909 deque->leftindex = leftindex;
910 deque->rightindex = rightindex;
911
912 return rv;
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000913}
914
915static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +0200916deque_rotate(dequeobject *deque, PyObject *const *args, Py_ssize_t nargs)
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000917{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 Py_ssize_t n=1;
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000919
Victor Stinnerdd407d52017-02-06 16:06:49 +0100920 if (!_PyArg_ParseStack(args, nargs, "|n:rotate", &n)) {
921 return NULL;
922 }
923
Raymond Hettinger6921c132015-03-21 02:03:40 -0700924 if (!_deque_rotate(deque, n))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000925 Py_RETURN_NONE;
926 return NULL;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000927}
928
Tim Peters1065f752004-10-01 01:03:29 +0000929PyDoc_STRVAR(rotate_doc,
Raymond Hettingeree33b272004-02-08 04:05:26 +0000930"Rotate the deque n steps to the right (default n=1). If n is negative, rotates left.");
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000931
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000932static PyObject *
933deque_reverse(dequeobject *deque, PyObject *unused)
934{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 block *leftblock = deque->leftblock;
936 block *rightblock = deque->rightblock;
937 Py_ssize_t leftindex = deque->leftindex;
938 Py_ssize_t rightindex = deque->rightindex;
Raymond Hettingercfe5b6c2015-07-20 00:25:50 -0400939 Py_ssize_t n = Py_SIZE(deque) >> 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 PyObject *tmp;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000941
Raymond Hettingere1b02872017-09-04 16:07:06 -0700942 while (--n >= 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000943 /* Validate that pointers haven't met in the middle */
944 assert(leftblock != rightblock || leftindex < rightindex);
Raymond Hettinger82df9252013-07-07 01:43:42 -1000945 CHECK_NOT_END(leftblock);
946 CHECK_NOT_END(rightblock);
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000947
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000948 /* Swap */
949 tmp = leftblock->data[leftindex];
950 leftblock->data[leftindex] = rightblock->data[rightindex];
951 rightblock->data[rightindex] = tmp;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 /* Advance left block/index pair */
954 leftindex++;
955 if (leftindex == BLOCKLEN) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000956 leftblock = leftblock->rightlink;
957 leftindex = 0;
958 }
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 /* Step backwards with the right block/index pair */
961 rightindex--;
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -0700962 if (rightindex < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000963 rightblock = rightblock->leftlink;
964 rightindex = BLOCKLEN - 1;
965 }
966 }
967 Py_RETURN_NONE;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000968}
969
970PyDoc_STRVAR(reverse_doc,
971"D.reverse() -- reverse *IN PLACE*");
972
Raymond Hettinger44459de2010-04-03 23:20:46 +0000973static PyObject *
974deque_count(dequeobject *deque, PyObject *v)
975{
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000976 block *b = deque->leftblock;
977 Py_ssize_t index = deque->leftindex;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000978 Py_ssize_t n = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 Py_ssize_t count = 0;
Raymond Hettingerf9d9c792015-03-02 22:47:46 -0800980 size_t start_state = deque->state;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000981 PyObject *item;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 int cmp;
Raymond Hettinger44459de2010-04-03 23:20:46 +0000983
Raymond Hettingere1b02872017-09-04 16:07:06 -0700984 while (--n >= 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000985 CHECK_NOT_END(b);
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000986 item = b->data[index];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
Raymond Hettinger2b0d6462015-09-23 19:15:44 -0700988 if (cmp < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000989 return NULL;
Raymond Hettinger2b0d6462015-09-23 19:15:44 -0700990 count += cmp;
Raymond Hettinger44459de2010-04-03 23:20:46 +0000991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992 if (start_state != deque->state) {
993 PyErr_SetString(PyExc_RuntimeError,
994 "deque mutated during iteration");
995 return NULL;
996 }
Raymond Hettinger44459de2010-04-03 23:20:46 +0000997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998 /* Advance left block/index pair */
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000999 index++;
1000 if (index == BLOCKLEN) {
1001 b = b->rightlink;
1002 index = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001003 }
1004 }
1005 return PyLong_FromSsize_t(count);
Raymond Hettinger44459de2010-04-03 23:20:46 +00001006}
1007
1008PyDoc_STRVAR(count_doc,
1009"D.count(value) -> integer -- return number of occurrences of value");
1010
Raymond Hettinger39dadf72015-03-20 16:38:56 -07001011static int
1012deque_contains(dequeobject *deque, PyObject *v)
1013{
1014 block *b = deque->leftblock;
1015 Py_ssize_t index = deque->leftindex;
1016 Py_ssize_t n = Py_SIZE(deque);
Raymond Hettinger39dadf72015-03-20 16:38:56 -07001017 size_t start_state = deque->state;
1018 PyObject *item;
1019 int cmp;
1020
Raymond Hettingere1b02872017-09-04 16:07:06 -07001021 while (--n >= 0) {
Raymond Hettinger39dadf72015-03-20 16:38:56 -07001022 CHECK_NOT_END(b);
1023 item = b->data[index];
1024 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
1025 if (cmp) {
1026 return cmp;
1027 }
1028 if (start_state != deque->state) {
1029 PyErr_SetString(PyExc_RuntimeError,
1030 "deque mutated during iteration");
1031 return -1;
1032 }
1033 index++;
1034 if (index == BLOCKLEN) {
1035 b = b->rightlink;
1036 index = 0;
1037 }
1038 }
1039 return 0;
1040}
1041
Martin v. Löwis18e16552006-02-15 17:27:45 +00001042static Py_ssize_t
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001043deque_len(dequeobject *deque)
1044{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001045 return Py_SIZE(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001046}
1047
Raymond Hettinger4aec61e2005-03-18 21:20:23 +00001048static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02001049deque_index(dequeobject *deque, PyObject *const *args, Py_ssize_t nargs)
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001050{
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001051 Py_ssize_t i, n, start=0, stop=Py_SIZE(deque);
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001052 PyObject *v, *item;
1053 block *b = deque->leftblock;
1054 Py_ssize_t index = deque->leftindex;
1055 size_t start_state = deque->state;
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001056 int cmp;
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001057
Victor Stinnerdd407d52017-02-06 16:06:49 +01001058 if (!_PyArg_ParseStack(args, nargs, "O|O&O&:index", &v,
Serhiy Storchakad4edfc92017-03-30 18:29:23 +03001059 _PyEval_SliceIndexNotNone, &start,
1060 _PyEval_SliceIndexNotNone, &stop)) {
Victor Stinnerdd407d52017-02-06 16:06:49 +01001061 return NULL;
1062 }
1063
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001064 if (start < 0) {
1065 start += Py_SIZE(deque);
1066 if (start < 0)
1067 start = 0;
1068 }
1069 if (stop < 0) {
1070 stop += Py_SIZE(deque);
1071 if (stop < 0)
1072 stop = 0;
1073 }
Raymond Hettinger87674ec2015-08-26 08:08:38 -07001074 if (stop > Py_SIZE(deque))
1075 stop = Py_SIZE(deque);
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001076 if (start > stop)
1077 start = stop;
1078 assert(0 <= start && start <= stop && stop <= Py_SIZE(deque));
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001079
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001080 /* XXX Replace this loop with faster code from deque_item() */
1081 for (i=0 ; i<start ; i++) {
1082 index++;
1083 if (index == BLOCKLEN) {
1084 b = b->rightlink;
1085 index = 0;
1086 }
1087 }
1088
Raymond Hettingere1b02872017-09-04 16:07:06 -07001089 n = stop - i;
1090 while (--n >= 0) {
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001091 CHECK_NOT_END(b);
1092 item = b->data[index];
1093 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
1094 if (cmp > 0)
Raymond Hettingere1b02872017-09-04 16:07:06 -07001095 return PyLong_FromSsize_t(stop - n - 1);
Raymond Hettingerdf8f5b52015-11-02 07:27:40 -05001096 if (cmp < 0)
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001097 return NULL;
1098 if (start_state != deque->state) {
1099 PyErr_SetString(PyExc_RuntimeError,
1100 "deque mutated during iteration");
1101 return NULL;
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001102 }
1103 index++;
1104 if (index == BLOCKLEN) {
1105 b = b->rightlink;
1106 index = 0;
1107 }
1108 }
1109 PyErr_Format(PyExc_ValueError, "%R is not in deque", v);
1110 return NULL;
1111}
1112
1113PyDoc_STRVAR(index_doc,
1114"D.index(value, [start, [stop]]) -> integer -- return first index of value.\n"
1115"Raises ValueError if the value is not present.");
1116
Raymond Hettinger551350a2015-03-24 00:19:53 -07001117/* insert(), remove(), and delitem() are implemented in terms of
1118 rotate() for simplicity and reasonable performance near the end
1119 points. If for some reason these methods become popular, it is not
1120 hard to re-implement this using direct data movement (similar to
1121 the code used in list slice assignments) and achieve a performance
Raymond Hettingerfef9c1b2015-03-24 21:12:57 -07001122 boost (by moving each pointer only once instead of twice).
Raymond Hettinger551350a2015-03-24 00:19:53 -07001123*/
1124
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001125static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02001126deque_insert(dequeobject *deque, PyObject *const *args, Py_ssize_t nargs)
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001127{
1128 Py_ssize_t index;
1129 Py_ssize_t n = Py_SIZE(deque);
1130 PyObject *value;
1131 PyObject *rv;
1132
Victor Stinnerdd407d52017-02-06 16:06:49 +01001133 if (!_PyArg_ParseStack(args, nargs, "nO:insert", &index, &value)) {
1134 return NULL;
1135 }
1136
Raymond Hettinger37434322016-01-26 21:44:16 -08001137 if (deque->maxlen == Py_SIZE(deque)) {
Raymond Hettingera6389712016-02-01 21:21:19 -08001138 PyErr_SetString(PyExc_IndexError, "deque already at its maximum size");
1139 return NULL;
Raymond Hettinger37434322016-01-26 21:44:16 -08001140 }
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001141 if (index >= n)
1142 return deque_append(deque, value);
1143 if (index <= -n || index == 0)
1144 return deque_appendleft(deque, value);
1145 if (_deque_rotate(deque, -index))
1146 return NULL;
1147 if (index < 0)
1148 rv = deque_append(deque, value);
1149 else
1150 rv = deque_appendleft(deque, value);
1151 if (rv == NULL)
1152 return NULL;
1153 Py_DECREF(rv);
1154 if (_deque_rotate(deque, index))
1155 return NULL;
1156 Py_RETURN_NONE;
1157}
1158
1159PyDoc_STRVAR(insert_doc,
1160"D.insert(index, object) -- insert object before index");
1161
1162static PyObject *
Raymond Hettinger4aec61e2005-03-18 21:20:23 +00001163deque_remove(dequeobject *deque, PyObject *value)
1164{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001165 Py_ssize_t i, n=Py_SIZE(deque);
Raymond Hettinger4aec61e2005-03-18 21:20:23 +00001166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001167 for (i=0 ; i<n ; i++) {
1168 PyObject *item = deque->leftblock->data[deque->leftindex];
1169 int cmp = PyObject_RichCompareBool(item, value, Py_EQ);
Raymond Hettingerd73202c2005-03-19 00:00:51 +00001170
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001171 if (Py_SIZE(deque) != n) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001172 PyErr_SetString(PyExc_IndexError,
1173 "deque mutated during remove().");
1174 return NULL;
1175 }
1176 if (cmp > 0) {
1177 PyObject *tgt = deque_popleft(deque, NULL);
1178 assert (tgt != NULL);
Raymond Hettinger6921c132015-03-21 02:03:40 -07001179 if (_deque_rotate(deque, i))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001180 return NULL;
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001181 Py_DECREF(tgt);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 Py_RETURN_NONE;
1183 }
1184 else if (cmp < 0) {
1185 _deque_rotate(deque, i);
1186 return NULL;
1187 }
1188 _deque_rotate(deque, -1);
1189 }
1190 PyErr_SetString(PyExc_ValueError, "deque.remove(x): x not in deque");
1191 return NULL;
Raymond Hettinger4aec61e2005-03-18 21:20:23 +00001192}
1193
1194PyDoc_STRVAR(remove_doc,
1195"D.remove(value) -- remove first occurrence of value.");
1196
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001197static int
1198valid_index(Py_ssize_t i, Py_ssize_t limit)
1199{
Raymond Hettinger12f896c2015-07-31 12:03:20 -07001200 /* The cast to size_t lets us use just a single comparison
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001201 to check whether i is in the range: 0 <= i < limit */
1202 return (size_t) i < (size_t) limit;
1203}
1204
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001205static PyObject *
Benjamin Petersond6313712008-07-31 16:23:04 +00001206deque_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001207{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001208 block *b;
1209 PyObject *item;
1210 Py_ssize_t n, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001211
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001212 if (!valid_index(i, Py_SIZE(deque))) {
1213 PyErr_SetString(PyExc_IndexError, "deque index out of range");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001214 return NULL;
1215 }
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001216
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001217 if (i == 0) {
1218 i = deque->leftindex;
1219 b = deque->leftblock;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001220 } else if (i == Py_SIZE(deque) - 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001221 i = deque->rightindex;
1222 b = deque->rightblock;
1223 } else {
1224 i += deque->leftindex;
Raymond Hettingerc2083082015-02-28 23:29:16 -08001225 n = (Py_ssize_t)((size_t) i / BLOCKLEN);
1226 i = (Py_ssize_t)((size_t) i % BLOCKLEN);
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001227 if (index < (Py_SIZE(deque) >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001228 b = deque->leftblock;
Raymond Hettingere1b02872017-09-04 16:07:06 -07001229 while (--n >= 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001230 b = b->rightlink;
1231 } else {
Raymond Hettinger63d1ff22015-02-28 07:41:30 -08001232 n = (Py_ssize_t)(
Raymond Hettingerc2083082015-02-28 23:29:16 -08001233 ((size_t)(deque->leftindex + Py_SIZE(deque) - 1))
Raymond Hettinger63d1ff22015-02-28 07:41:30 -08001234 / BLOCKLEN - n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001235 b = deque->rightblock;
Raymond Hettingere1b02872017-09-04 16:07:06 -07001236 while (--n >= 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001237 b = b->leftlink;
1238 }
1239 }
1240 item = b->data[i];
1241 Py_INCREF(item);
1242 return item;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001243}
1244
1245static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001246deque_del_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001247{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001248 PyObject *item;
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001249 int rv;
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001250
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001251 assert (i >= 0 && i < Py_SIZE(deque));
Raymond Hettinger6921c132015-03-21 02:03:40 -07001252 if (_deque_rotate(deque, -i))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001253 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001254 item = deque_popleft(deque, NULL);
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001255 rv = _deque_rotate(deque, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001256 assert (item != NULL);
1257 Py_DECREF(item);
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001258 return rv;
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001259}
1260
1261static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001262deque_ass_item(dequeobject *deque, Py_ssize_t i, PyObject *v)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001263{
Raymond Hettinger38418662016-02-08 20:34:49 -08001264 PyObject *old_value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001265 block *b;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001266 Py_ssize_t n, len=Py_SIZE(deque), halflen=(len+1)>>1, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001267
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001268 if (!valid_index(i, len)) {
1269 PyErr_SetString(PyExc_IndexError, "deque index out of range");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001270 return -1;
1271 }
1272 if (v == NULL)
1273 return deque_del_item(deque, i);
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001275 i += deque->leftindex;
Raymond Hettingerc2083082015-02-28 23:29:16 -08001276 n = (Py_ssize_t)((size_t) i / BLOCKLEN);
1277 i = (Py_ssize_t)((size_t) i % BLOCKLEN);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001278 if (index <= halflen) {
1279 b = deque->leftblock;
Raymond Hettingere1b02872017-09-04 16:07:06 -07001280 while (--n >= 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001281 b = b->rightlink;
1282 } else {
Raymond Hettingera473b9d2015-02-28 17:49:47 -08001283 n = (Py_ssize_t)(
Raymond Hettingerc2083082015-02-28 23:29:16 -08001284 ((size_t)(deque->leftindex + Py_SIZE(deque) - 1))
Raymond Hettingera473b9d2015-02-28 17:49:47 -08001285 / BLOCKLEN - n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001286 b = deque->rightblock;
Raymond Hettingere1b02872017-09-04 16:07:06 -07001287 while (--n >= 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001288 b = b->leftlink;
1289 }
1290 Py_INCREF(v);
Raymond Hettinger38418662016-02-08 20:34:49 -08001291 old_value = b->data[i];
1292 b->data[i] = v;
1293 Py_DECREF(old_value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001294 return 0;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001295}
1296
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001297static void
1298deque_dealloc(dequeobject *deque)
1299{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001300 PyObject_GC_UnTrack(deque);
1301 if (deque->weakreflist != NULL)
1302 PyObject_ClearWeakRefs((PyObject *) deque);
1303 if (deque->leftblock != NULL) {
1304 deque_clear(deque);
1305 assert(deque->leftblock != NULL);
1306 freeblock(deque->leftblock);
1307 }
1308 deque->leftblock = NULL;
1309 deque->rightblock = NULL;
1310 Py_TYPE(deque)->tp_free(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001311}
1312
1313static int
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001314deque_traverse(dequeobject *deque, visitproc visit, void *arg)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001315{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001316 block *b;
1317 PyObject *item;
1318 Py_ssize_t index;
1319 Py_ssize_t indexlo = deque->leftindex;
Raymond Hettinger1286d142015-10-14 23:16:57 -07001320 Py_ssize_t indexhigh;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001321
Raymond Hettinger5bfa8672013-07-06 11:58:09 -10001322 for (b = deque->leftblock; b != deque->rightblock; b = b->rightlink) {
1323 for (index = indexlo; index < BLOCKLEN ; index++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001324 item = b->data[index];
1325 Py_VISIT(item);
1326 }
1327 indexlo = 0;
1328 }
Raymond Hettinger1286d142015-10-14 23:16:57 -07001329 indexhigh = deque->rightindex;
1330 for (index = indexlo; index <= indexhigh; index++) {
Raymond Hettinger5bfa8672013-07-06 11:58:09 -10001331 item = b->data[index];
1332 Py_VISIT(item);
1333 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001334 return 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001335}
1336
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001337static PyObject *
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001338deque_reduce(dequeobject *deque)
1339{
Serhiy Storchakaa0d416f2016-03-06 08:55:21 +02001340 PyObject *dict, *it;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001341 _Py_IDENTIFIER(__dict__);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001342
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001343 if (_PyObject_LookupAttrId((PyObject *)deque, &PyId___dict__, &dict) < 0) {
1344 return NULL;
1345 }
Serhiy Storchakaa0d416f2016-03-06 08:55:21 +02001346 if (dict == NULL) {
Serhiy Storchakaa0d416f2016-03-06 08:55:21 +02001347 dict = Py_None;
1348 Py_INCREF(dict);
1349 }
1350
1351 it = PyObject_GetIter((PyObject *)deque);
1352 if (it == NULL) {
1353 Py_DECREF(dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001354 return NULL;
1355 }
Serhiy Storchakaa0d416f2016-03-06 08:55:21 +02001356
1357 if (deque->maxlen < 0) {
1358 return Py_BuildValue("O()NN", Py_TYPE(deque), dict, it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001359 }
Serhiy Storchakaa0d416f2016-03-06 08:55:21 +02001360 else {
1361 return Py_BuildValue("O(()n)NN", Py_TYPE(deque), deque->maxlen, dict, it);
1362 }
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001363}
1364
1365PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
1366
1367static PyObject *
1368deque_repr(PyObject *deque)
1369{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001370 PyObject *aslist, *result;
1371 int i;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001373 i = Py_ReprEnter(deque);
1374 if (i != 0) {
1375 if (i < 0)
1376 return NULL;
1377 return PyUnicode_FromString("[...]");
1378 }
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001380 aslist = PySequence_List(deque);
1381 if (aslist == NULL) {
1382 Py_ReprLeave(deque);
1383 return NULL;
1384 }
Raymond Hettingera7f630092015-10-10 23:56:02 -04001385 if (((dequeobject *)deque)->maxlen >= 0)
Serhiy Storchakab3a77962017-09-21 14:24:13 +03001386 result = PyUnicode_FromFormat("%s(%R, maxlen=%zd)",
1387 _PyType_Name(Py_TYPE(deque)), aslist,
1388 ((dequeobject *)deque)->maxlen);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001389 else
Serhiy Storchakab3a77962017-09-21 14:24:13 +03001390 result = PyUnicode_FromFormat("%s(%R)",
1391 _PyType_Name(Py_TYPE(deque)), aslist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001392 Py_ReprLeave(deque);
Raymond Hettinger2b2b7532015-09-05 17:05:52 -07001393 Py_DECREF(aslist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001394 return result;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001395}
1396
Raymond Hettinger738ec902004-02-29 02:15:56 +00001397static PyObject *
1398deque_richcompare(PyObject *v, PyObject *w, int op)
1399{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001400 PyObject *it1=NULL, *it2=NULL, *x, *y;
1401 Py_ssize_t vs, ws;
1402 int b, cmp=-1;
Raymond Hettinger738ec902004-02-29 02:15:56 +00001403
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001404 if (!PyObject_TypeCheck(v, &deque_type) ||
1405 !PyObject_TypeCheck(w, &deque_type)) {
Brian Curtindfc80e32011-08-10 20:28:54 -05001406 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001407 }
Raymond Hettinger738ec902004-02-29 02:15:56 +00001408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001409 /* Shortcuts */
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001410 vs = Py_SIZE((dequeobject *)v);
1411 ws = Py_SIZE((dequeobject *)w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001412 if (op == Py_EQ) {
1413 if (v == w)
1414 Py_RETURN_TRUE;
1415 if (vs != ws)
1416 Py_RETURN_FALSE;
1417 }
1418 if (op == Py_NE) {
1419 if (v == w)
1420 Py_RETURN_FALSE;
1421 if (vs != ws)
1422 Py_RETURN_TRUE;
1423 }
Raymond Hettinger738ec902004-02-29 02:15:56 +00001424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001425 /* Search for the first index where items are different */
1426 it1 = PyObject_GetIter(v);
1427 if (it1 == NULL)
1428 goto done;
1429 it2 = PyObject_GetIter(w);
1430 if (it2 == NULL)
1431 goto done;
1432 for (;;) {
1433 x = PyIter_Next(it1);
1434 if (x == NULL && PyErr_Occurred())
1435 goto done;
1436 y = PyIter_Next(it2);
1437 if (x == NULL || y == NULL)
1438 break;
1439 b = PyObject_RichCompareBool(x, y, Py_EQ);
1440 if (b == 0) {
1441 cmp = PyObject_RichCompareBool(x, y, op);
1442 Py_DECREF(x);
1443 Py_DECREF(y);
1444 goto done;
1445 }
1446 Py_DECREF(x);
1447 Py_DECREF(y);
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -07001448 if (b < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001449 goto done;
1450 }
1451 /* We reached the end of one deque or both */
1452 Py_XDECREF(x);
1453 Py_XDECREF(y);
1454 if (PyErr_Occurred())
1455 goto done;
1456 switch (op) {
1457 case Py_LT: cmp = y != NULL; break; /* if w was longer */
1458 case Py_LE: cmp = x == NULL; break; /* if v was not longer */
1459 case Py_EQ: cmp = x == y; break; /* if we reached the end of both */
1460 case Py_NE: cmp = x != y; break; /* if one deque continues */
1461 case Py_GT: cmp = x != NULL; break; /* if v was longer */
1462 case Py_GE: cmp = y == NULL; break; /* if w was not longer */
1463 }
Tim Peters1065f752004-10-01 01:03:29 +00001464
Raymond Hettinger738ec902004-02-29 02:15:56 +00001465done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001466 Py_XDECREF(it1);
1467 Py_XDECREF(it2);
1468 if (cmp == 1)
1469 Py_RETURN_TRUE;
1470 if (cmp == 0)
1471 Py_RETURN_FALSE;
1472 return NULL;
Raymond Hettinger738ec902004-02-29 02:15:56 +00001473}
1474
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001475static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001476deque_init(dequeobject *deque, PyObject *args, PyObject *kwdargs)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001477{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001478 PyObject *iterable = NULL;
1479 PyObject *maxlenobj = NULL;
1480 Py_ssize_t maxlen = -1;
1481 char *kwlist[] = {"iterable", "maxlen", 0};
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001482
Raymond Hettinger0d309402015-09-30 23:15:02 -07001483 if (kwdargs == NULL) {
1484 if (!PyArg_UnpackTuple(args, "deque()", 0, 2, &iterable, &maxlenobj))
1485 return -1;
1486 } else {
1487 if (!PyArg_ParseTupleAndKeywords(args, kwdargs, "|OO:deque", kwlist,
1488 &iterable, &maxlenobj))
1489 return -1;
1490 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001491 if (maxlenobj != NULL && maxlenobj != Py_None) {
1492 maxlen = PyLong_AsSsize_t(maxlenobj);
1493 if (maxlen == -1 && PyErr_Occurred())
1494 return -1;
1495 if (maxlen < 0) {
1496 PyErr_SetString(PyExc_ValueError, "maxlen must be non-negative");
1497 return -1;
1498 }
1499 }
1500 deque->maxlen = maxlen;
Raymond Hettinger0d309402015-09-30 23:15:02 -07001501 if (Py_SIZE(deque) > 0)
1502 deque_clear(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001503 if (iterable != NULL) {
1504 PyObject *rv = deque_extend(deque, iterable);
1505 if (rv == NULL)
1506 return -1;
1507 Py_DECREF(rv);
1508 }
1509 return 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001510}
1511
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001512static PyObject *
Jesus Cea16e2fca2012-08-03 14:49:42 +02001513deque_sizeof(dequeobject *deque, void *unused)
1514{
1515 Py_ssize_t res;
1516 Py_ssize_t blocks;
1517
Serhiy Storchaka5c4064e2015-12-19 20:05:25 +02001518 res = _PyObject_SIZE(Py_TYPE(deque));
Raymond Hettingerbc003412015-10-14 23:33:23 -07001519 blocks = (size_t)(deque->leftindex + Py_SIZE(deque) + BLOCKLEN - 1) / BLOCKLEN;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001520 assert(deque->leftindex + Py_SIZE(deque) - 1 ==
Jesus Cea16e2fca2012-08-03 14:49:42 +02001521 (blocks - 1) * BLOCKLEN + deque->rightindex);
1522 res += blocks * sizeof(block);
1523 return PyLong_FromSsize_t(res);
1524}
1525
1526PyDoc_STRVAR(sizeof_doc,
1527"D.__sizeof__() -- size of D in memory, in bytes");
1528
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001529static int
1530deque_bool(dequeobject *deque)
1531{
1532 return Py_SIZE(deque) != 0;
1533}
1534
Jesus Cea16e2fca2012-08-03 14:49:42 +02001535static PyObject *
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001536deque_get_maxlen(dequeobject *deque)
1537{
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -07001538 if (deque->maxlen < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001539 Py_RETURN_NONE;
1540 return PyLong_FromSsize_t(deque->maxlen);
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001541}
1542
Raymond Hettinger41290a62015-03-31 08:12:23 -07001543
1544/* deque object ********************************************************/
1545
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001546static PyGetSetDef deque_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001547 {"maxlen", (getter)deque_get_maxlen, (setter)NULL,
1548 "maximum size of a deque or None if unbounded"},
1549 {0}
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001550};
1551
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001552static PySequenceMethods deque_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001553 (lenfunc)deque_len, /* sq_length */
Raymond Hettinger41290a62015-03-31 08:12:23 -07001554 (binaryfunc)deque_concat, /* sq_concat */
1555 (ssizeargfunc)deque_repeat, /* sq_repeat */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001556 (ssizeargfunc)deque_item, /* sq_item */
1557 0, /* sq_slice */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001558 (ssizeobjargproc)deque_ass_item, /* sq_ass_item */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001559 0, /* sq_ass_slice */
Raymond Hettinger39dadf72015-03-20 16:38:56 -07001560 (objobjproc)deque_contains, /* sq_contains */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001561 (binaryfunc)deque_inplace_concat, /* sq_inplace_concat */
Raymond Hettinger41290a62015-03-31 08:12:23 -07001562 (ssizeargfunc)deque_inplace_repeat, /* sq_inplace_repeat */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001563};
1564
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001565static PyNumberMethods deque_as_number = {
1566 0, /* nb_add */
1567 0, /* nb_subtract */
1568 0, /* nb_multiply */
1569 0, /* nb_remainder */
1570 0, /* nb_divmod */
1571 0, /* nb_power */
1572 0, /* nb_negative */
1573 0, /* nb_positive */
1574 0, /* nb_absolute */
1575 (inquiry)deque_bool, /* nb_bool */
1576 0, /* nb_invert */
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001577 };
1578
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001579static PyObject *deque_iter(dequeobject *deque);
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301580static PyObject *deque_reviter(dequeobject *deque, PyObject *Py_UNUSED(ignored));
Tim Peters1065f752004-10-01 01:03:29 +00001581PyDoc_STRVAR(reversed_doc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001582 "D.__reversed__() -- return a reverse iterator over the deque");
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001583
1584static PyMethodDef deque_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001585 {"append", (PyCFunction)deque_append,
1586 METH_O, append_doc},
1587 {"appendleft", (PyCFunction)deque_appendleft,
1588 METH_O, appendleft_doc},
1589 {"clear", (PyCFunction)deque_clearmethod,
1590 METH_NOARGS, clear_doc},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301591 {"__copy__", deque_copy,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001592 METH_NOARGS, copy_doc},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301593 {"copy", deque_copy,
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001594 METH_NOARGS, copy_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001595 {"count", (PyCFunction)deque_count,
Raymond Hettinger0f6f9472015-03-21 01:42:10 -07001596 METH_O, count_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001597 {"extend", (PyCFunction)deque_extend,
1598 METH_O, extend_doc},
1599 {"extendleft", (PyCFunction)deque_extendleft,
1600 METH_O, extendleft_doc},
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001601 {"index", (PyCFunction)deque_index,
Victor Stinnerdd407d52017-02-06 16:06:49 +01001602 METH_FASTCALL, index_doc},
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001603 {"insert", (PyCFunction)deque_insert,
Victor Stinnerdd407d52017-02-06 16:06:49 +01001604 METH_FASTCALL, insert_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001605 {"pop", (PyCFunction)deque_pop,
1606 METH_NOARGS, pop_doc},
1607 {"popleft", (PyCFunction)deque_popleft,
1608 METH_NOARGS, popleft_doc},
Raymond Hettinger0f6f9472015-03-21 01:42:10 -07001609 {"__reduce__", (PyCFunction)deque_reduce,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001610 METH_NOARGS, reduce_doc},
1611 {"remove", (PyCFunction)deque_remove,
1612 METH_O, remove_doc},
1613 {"__reversed__", (PyCFunction)deque_reviter,
1614 METH_NOARGS, reversed_doc},
1615 {"reverse", (PyCFunction)deque_reverse,
1616 METH_NOARGS, reverse_doc},
1617 {"rotate", (PyCFunction)deque_rotate,
Victor Stinnerdd407d52017-02-06 16:06:49 +01001618 METH_FASTCALL, rotate_doc},
Jesus Cea16e2fca2012-08-03 14:49:42 +02001619 {"__sizeof__", (PyCFunction)deque_sizeof,
1620 METH_NOARGS, sizeof_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001621 {NULL, NULL} /* sentinel */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001622};
1623
1624PyDoc_STRVAR(deque_doc,
Andrew Svetlov6a5c7c32012-10-31 11:50:40 +02001625"deque([iterable[, maxlen]]) --> deque object\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001626\n\
Raymond Hettinger41290a62015-03-31 08:12:23 -07001627A list-like sequence optimized for data accesses near its endpoints.");
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001628
Neal Norwitz87f10132004-02-29 15:40:53 +00001629static PyTypeObject deque_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001630 PyVarObject_HEAD_INIT(NULL, 0)
1631 "collections.deque", /* tp_name */
1632 sizeof(dequeobject), /* tp_basicsize */
1633 0, /* tp_itemsize */
1634 /* methods */
1635 (destructor)deque_dealloc, /* tp_dealloc */
1636 0, /* tp_print */
1637 0, /* tp_getattr */
1638 0, /* tp_setattr */
1639 0, /* tp_reserved */
1640 deque_repr, /* tp_repr */
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001641 &deque_as_number, /* tp_as_number */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001642 &deque_as_sequence, /* tp_as_sequence */
1643 0, /* tp_as_mapping */
Georg Brandlf038b322010-10-18 07:35:09 +00001644 PyObject_HashNotImplemented, /* tp_hash */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001645 0, /* tp_call */
1646 0, /* tp_str */
1647 PyObject_GenericGetAttr, /* tp_getattro */
1648 0, /* tp_setattro */
1649 0, /* tp_as_buffer */
1650 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
Georg Brandlf038b322010-10-18 07:35:09 +00001651 /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001652 deque_doc, /* tp_doc */
1653 (traverseproc)deque_traverse, /* tp_traverse */
1654 (inquiry)deque_clear, /* tp_clear */
1655 (richcmpfunc)deque_richcompare, /* tp_richcompare */
Georg Brandlf038b322010-10-18 07:35:09 +00001656 offsetof(dequeobject, weakreflist), /* tp_weaklistoffset*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001657 (getiterfunc)deque_iter, /* tp_iter */
1658 0, /* tp_iternext */
1659 deque_methods, /* tp_methods */
1660 0, /* tp_members */
Georg Brandlf038b322010-10-18 07:35:09 +00001661 deque_getset, /* tp_getset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001662 0, /* tp_base */
1663 0, /* tp_dict */
1664 0, /* tp_descr_get */
1665 0, /* tp_descr_set */
1666 0, /* tp_dictoffset */
1667 (initproc)deque_init, /* tp_init */
1668 PyType_GenericAlloc, /* tp_alloc */
1669 deque_new, /* tp_new */
1670 PyObject_GC_Del, /* tp_free */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001671};
1672
1673/*********************** Deque Iterator **************************/
1674
1675typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001676 PyObject_HEAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001677 block *b;
Raymond Hettinger87e69122015-03-02 23:32:02 -08001678 Py_ssize_t index;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001679 dequeobject *deque;
Raymond Hettingerf9d9c792015-03-02 22:47:46 -08001680 size_t state; /* state when the iterator is created */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001681 Py_ssize_t counter; /* number of items remaining for iteration */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001682} dequeiterobject;
1683
Martin v. Löwis59683e82008-06-13 07:50:45 +00001684static PyTypeObject dequeiter_type;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001685
1686static PyObject *
1687deque_iter(dequeobject *deque)
1688{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001689 dequeiterobject *it;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001690
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001691 it = PyObject_GC_New(dequeiterobject, &dequeiter_type);
1692 if (it == NULL)
1693 return NULL;
1694 it->b = deque->leftblock;
1695 it->index = deque->leftindex;
1696 Py_INCREF(deque);
1697 it->deque = deque;
1698 it->state = deque->state;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001699 it->counter = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001700 PyObject_GC_Track(it);
1701 return (PyObject *)it;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001702}
1703
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001704static int
1705dequeiter_traverse(dequeiterobject *dio, visitproc visit, void *arg)
1706{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001707 Py_VISIT(dio->deque);
1708 return 0;
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001709}
1710
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001711static void
1712dequeiter_dealloc(dequeiterobject *dio)
1713{
INADA Naokia6296d32017-08-24 14:55:17 +09001714 /* bpo-31095: UnTrack is needed before calling any callbacks */
1715 PyObject_GC_UnTrack(dio);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001716 Py_XDECREF(dio->deque);
1717 PyObject_GC_Del(dio);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001718}
1719
1720static PyObject *
1721dequeiter_next(dequeiterobject *it)
1722{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001723 PyObject *item;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001725 if (it->deque->state != it->state) {
1726 it->counter = 0;
1727 PyErr_SetString(PyExc_RuntimeError,
1728 "deque mutated during iteration");
1729 return NULL;
1730 }
1731 if (it->counter == 0)
1732 return NULL;
1733 assert (!(it->b == it->deque->rightblock &&
1734 it->index > it->deque->rightindex));
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 item = it->b->data[it->index];
1737 it->index++;
1738 it->counter--;
1739 if (it->index == BLOCKLEN && it->counter > 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -10001740 CHECK_NOT_END(it->b->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001741 it->b = it->b->rightlink;
1742 it->index = 0;
1743 }
1744 Py_INCREF(item);
1745 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001746}
1747
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001748static PyObject *
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001749dequeiter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1750{
1751 Py_ssize_t i, index=0;
1752 PyObject *deque;
1753 dequeiterobject *it;
1754 if (!PyArg_ParseTuple(args, "O!|n", &deque_type, &deque, &index))
1755 return NULL;
1756 assert(type == &dequeiter_type);
1757
1758 it = (dequeiterobject*)deque_iter((dequeobject *)deque);
1759 if (!it)
1760 return NULL;
1761 /* consume items from the queue */
1762 for(i=0; i<index; i++) {
1763 PyObject *item = dequeiter_next(it);
1764 if (item) {
1765 Py_DECREF(item);
1766 } else {
1767 if (it->counter) {
1768 Py_DECREF(it);
1769 return NULL;
1770 } else
1771 break;
1772 }
1773 }
1774 return (PyObject*)it;
1775}
1776
1777static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301778dequeiter_len(dequeiterobject *it, PyObject *Py_UNUSED(ignored))
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001779{
Antoine Pitrou554f3342010-08-17 18:30:06 +00001780 return PyLong_FromSsize_t(it->counter);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001781}
1782
Armin Rigof5b3e362006-02-11 21:32:43 +00001783PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001784
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001785static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301786dequeiter_reduce(dequeiterobject *it, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001787{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001788 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 +00001789}
1790
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001791static PyMethodDef dequeiter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001792 {"__length_hint__", (PyCFunction)dequeiter_len, METH_NOARGS, length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001793 {"__reduce__", (PyCFunction)dequeiter_reduce, METH_NOARGS, reduce_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001794 {NULL, NULL} /* sentinel */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001795};
1796
Martin v. Löwis59683e82008-06-13 07:50:45 +00001797static PyTypeObject dequeiter_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001798 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger87e69122015-03-02 23:32:02 -08001799 "_collections._deque_iterator", /* tp_name */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001800 sizeof(dequeiterobject), /* tp_basicsize */
1801 0, /* tp_itemsize */
1802 /* methods */
1803 (destructor)dequeiter_dealloc, /* tp_dealloc */
1804 0, /* tp_print */
1805 0, /* tp_getattr */
1806 0, /* tp_setattr */
1807 0, /* tp_reserved */
1808 0, /* tp_repr */
1809 0, /* tp_as_number */
1810 0, /* tp_as_sequence */
1811 0, /* tp_as_mapping */
1812 0, /* tp_hash */
1813 0, /* tp_call */
1814 0, /* tp_str */
1815 PyObject_GenericGetAttr, /* tp_getattro */
1816 0, /* tp_setattro */
1817 0, /* tp_as_buffer */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001818 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001819 0, /* tp_doc */
1820 (traverseproc)dequeiter_traverse, /* tp_traverse */
1821 0, /* tp_clear */
1822 0, /* tp_richcompare */
1823 0, /* tp_weaklistoffset */
1824 PyObject_SelfIter, /* tp_iter */
1825 (iternextfunc)dequeiter_next, /* tp_iternext */
1826 dequeiter_methods, /* tp_methods */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001827 0, /* tp_members */
1828 0, /* tp_getset */
1829 0, /* tp_base */
1830 0, /* tp_dict */
1831 0, /* tp_descr_get */
1832 0, /* tp_descr_set */
1833 0, /* tp_dictoffset */
1834 0, /* tp_init */
1835 0, /* tp_alloc */
1836 dequeiter_new, /* tp_new */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001837 0,
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001838};
1839
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001840/*********************** Deque Reverse Iterator **************************/
1841
Martin v. Löwis59683e82008-06-13 07:50:45 +00001842static PyTypeObject dequereviter_type;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001843
1844static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301845deque_reviter(dequeobject *deque, PyObject *Py_UNUSED(ignored))
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001846{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001847 dequeiterobject *it;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001849 it = PyObject_GC_New(dequeiterobject, &dequereviter_type);
1850 if (it == NULL)
1851 return NULL;
1852 it->b = deque->rightblock;
1853 it->index = deque->rightindex;
1854 Py_INCREF(deque);
1855 it->deque = deque;
1856 it->state = deque->state;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001857 it->counter = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001858 PyObject_GC_Track(it);
1859 return (PyObject *)it;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001860}
1861
1862static PyObject *
1863dequereviter_next(dequeiterobject *it)
1864{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001865 PyObject *item;
1866 if (it->counter == 0)
1867 return NULL;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001868
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001869 if (it->deque->state != it->state) {
1870 it->counter = 0;
1871 PyErr_SetString(PyExc_RuntimeError,
1872 "deque mutated during iteration");
1873 return NULL;
1874 }
1875 assert (!(it->b == it->deque->leftblock &&
1876 it->index < it->deque->leftindex));
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001878 item = it->b->data[it->index];
1879 it->index--;
1880 it->counter--;
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -07001881 if (it->index < 0 && it->counter > 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -10001882 CHECK_NOT_END(it->b->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001883 it->b = it->b->leftlink;
1884 it->index = BLOCKLEN - 1;
1885 }
1886 Py_INCREF(item);
1887 return item;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001888}
1889
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001890static PyObject *
1891dequereviter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1892{
1893 Py_ssize_t i, index=0;
1894 PyObject *deque;
1895 dequeiterobject *it;
1896 if (!PyArg_ParseTuple(args, "O!|n", &deque_type, &deque, &index))
1897 return NULL;
1898 assert(type == &dequereviter_type);
1899
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301900 it = (dequeiterobject*)deque_reviter((dequeobject *)deque, NULL);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001901 if (!it)
1902 return NULL;
1903 /* consume items from the queue */
1904 for(i=0; i<index; i++) {
1905 PyObject *item = dequereviter_next(it);
1906 if (item) {
1907 Py_DECREF(item);
1908 } else {
1909 if (it->counter) {
1910 Py_DECREF(it);
1911 return NULL;
1912 } else
1913 break;
1914 }
1915 }
1916 return (PyObject*)it;
1917}
1918
Martin v. Löwis59683e82008-06-13 07:50:45 +00001919static PyTypeObject dequereviter_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001920 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger87e69122015-03-02 23:32:02 -08001921 "_collections._deque_reverse_iterator", /* tp_name */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001922 sizeof(dequeiterobject), /* tp_basicsize */
1923 0, /* tp_itemsize */
1924 /* methods */
1925 (destructor)dequeiter_dealloc, /* tp_dealloc */
1926 0, /* tp_print */
1927 0, /* tp_getattr */
1928 0, /* tp_setattr */
1929 0, /* tp_reserved */
1930 0, /* tp_repr */
1931 0, /* tp_as_number */
1932 0, /* tp_as_sequence */
1933 0, /* tp_as_mapping */
1934 0, /* tp_hash */
1935 0, /* tp_call */
1936 0, /* tp_str */
1937 PyObject_GenericGetAttr, /* tp_getattro */
1938 0, /* tp_setattro */
1939 0, /* tp_as_buffer */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001940 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001941 0, /* tp_doc */
1942 (traverseproc)dequeiter_traverse, /* tp_traverse */
1943 0, /* tp_clear */
1944 0, /* tp_richcompare */
1945 0, /* tp_weaklistoffset */
1946 PyObject_SelfIter, /* tp_iter */
1947 (iternextfunc)dequereviter_next, /* tp_iternext */
1948 dequeiter_methods, /* tp_methods */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001949 0, /* tp_members */
1950 0, /* tp_getset */
1951 0, /* tp_base */
1952 0, /* tp_dict */
1953 0, /* tp_descr_get */
1954 0, /* tp_descr_set */
1955 0, /* tp_dictoffset */
1956 0, /* tp_init */
1957 0, /* tp_alloc */
1958 dequereviter_new, /* tp_new */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001959 0,
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001960};
1961
Guido van Rossum1968ad32006-02-25 22:38:04 +00001962/* defaultdict type *********************************************************/
1963
1964typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001965 PyDictObject dict;
1966 PyObject *default_factory;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001967} defdictobject;
1968
1969static PyTypeObject defdict_type; /* Forward */
1970
1971PyDoc_STRVAR(defdict_missing_doc,
1972"__missing__(key) # Called by __getitem__ for missing key; pseudo-code:\n\
Guido van Rossumd8faa362007-04-27 19:54:29 +00001973 if self.default_factory is None: raise KeyError((key,))\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00001974 self[key] = value = self.default_factory()\n\
1975 return value\n\
1976");
1977
1978static PyObject *
1979defdict_missing(defdictobject *dd, PyObject *key)
1980{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001981 PyObject *factory = dd->default_factory;
1982 PyObject *value;
1983 if (factory == NULL || factory == Py_None) {
1984 /* XXX Call dict.__missing__(key) */
1985 PyObject *tup;
1986 tup = PyTuple_Pack(1, key);
1987 if (!tup) return NULL;
1988 PyErr_SetObject(PyExc_KeyError, tup);
1989 Py_DECREF(tup);
1990 return NULL;
1991 }
1992 value = PyEval_CallObject(factory, NULL);
1993 if (value == NULL)
1994 return value;
1995 if (PyObject_SetItem((PyObject *)dd, key, value) < 0) {
1996 Py_DECREF(value);
1997 return NULL;
1998 }
1999 return value;
Guido van Rossum1968ad32006-02-25 22:38:04 +00002000}
2001
2002PyDoc_STRVAR(defdict_copy_doc, "D.copy() -> a shallow copy of D.");
2003
2004static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302005defdict_copy(defdictobject *dd, PyObject *Py_UNUSED(ignored))
Guido van Rossum1968ad32006-02-25 22:38:04 +00002006{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002007 /* This calls the object's class. That only works for subclasses
2008 whose class constructor has the same signature. Subclasses that
2009 define a different constructor signature must override copy().
2010 */
Raymond Hettinger54628fa2009-08-04 19:16:39 +00002011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002012 if (dd->default_factory == NULL)
2013 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd), Py_None, dd, NULL);
2014 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd),
2015 dd->default_factory, dd, NULL);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002016}
2017
2018static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302019defdict_reduce(defdictobject *dd, PyObject *Py_UNUSED(ignored))
Guido van Rossum1968ad32006-02-25 22:38:04 +00002020{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002021 /* __reduce__ must return a 5-tuple as follows:
Guido van Rossum1968ad32006-02-25 22:38:04 +00002022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002023 - factory function
2024 - tuple of args for the factory function
2025 - additional state (here None)
2026 - sequence iterator (here None)
2027 - dictionary iterator (yielding successive (key, value) pairs
Guido van Rossum1968ad32006-02-25 22:38:04 +00002028
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002029 This API is used by pickle.py and copy.py.
Guido van Rossum1968ad32006-02-25 22:38:04 +00002030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002031 For this to be useful with pickle.py, the default_factory
2032 must be picklable; e.g., None, a built-in, or a global
2033 function in a module or package.
Guido van Rossum1968ad32006-02-25 22:38:04 +00002034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002035 Both shallow and deep copying are supported, but for deep
2036 copying, the default_factory must be deep-copyable; e.g. None,
2037 or a built-in (functions are not copyable at this time).
Guido van Rossum1968ad32006-02-25 22:38:04 +00002038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002039 This only works for subclasses as long as their constructor
2040 signature is compatible; the first argument must be the
2041 optional default_factory, defaulting to None.
2042 */
2043 PyObject *args;
2044 PyObject *items;
2045 PyObject *iter;
2046 PyObject *result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002047 _Py_IDENTIFIER(items);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002048
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002049 if (dd->default_factory == NULL || dd->default_factory == Py_None)
2050 args = PyTuple_New(0);
2051 else
2052 args = PyTuple_Pack(1, dd->default_factory);
2053 if (args == NULL)
2054 return NULL;
Victor Stinnerad8c83a2016-09-05 17:53:15 -07002055 items = _PyObject_CallMethodId((PyObject *)dd, &PyId_items, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002056 if (items == NULL) {
2057 Py_DECREF(args);
2058 return NULL;
2059 }
2060 iter = PyObject_GetIter(items);
2061 if (iter == NULL) {
2062 Py_DECREF(items);
2063 Py_DECREF(args);
2064 return NULL;
2065 }
2066 result = PyTuple_Pack(5, Py_TYPE(dd), args,
2067 Py_None, Py_None, iter);
2068 Py_DECREF(iter);
2069 Py_DECREF(items);
2070 Py_DECREF(args);
2071 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00002072}
2073
2074static PyMethodDef defdict_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002075 {"__missing__", (PyCFunction)defdict_missing, METH_O,
2076 defdict_missing_doc},
2077 {"copy", (PyCFunction)defdict_copy, METH_NOARGS,
2078 defdict_copy_doc},
2079 {"__copy__", (PyCFunction)defdict_copy, METH_NOARGS,
2080 defdict_copy_doc},
2081 {"__reduce__", (PyCFunction)defdict_reduce, METH_NOARGS,
2082 reduce_doc},
2083 {NULL}
Guido van Rossum1968ad32006-02-25 22:38:04 +00002084};
2085
2086static PyMemberDef defdict_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002087 {"default_factory", T_OBJECT,
2088 offsetof(defdictobject, default_factory), 0,
2089 PyDoc_STR("Factory for default value called by __missing__().")},
2090 {NULL}
Guido van Rossum1968ad32006-02-25 22:38:04 +00002091};
2092
2093static void
2094defdict_dealloc(defdictobject *dd)
2095{
INADA Naokia6296d32017-08-24 14:55:17 +09002096 /* bpo-31095: UnTrack is needed before calling any callbacks */
2097 PyObject_GC_UnTrack(dd);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002098 Py_CLEAR(dd->default_factory);
2099 PyDict_Type.tp_dealloc((PyObject *)dd);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002100}
2101
Guido van Rossum1968ad32006-02-25 22:38:04 +00002102static PyObject *
2103defdict_repr(defdictobject *dd)
2104{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002105 PyObject *baserepr;
2106 PyObject *defrepr;
2107 PyObject *result;
2108 baserepr = PyDict_Type.tp_repr((PyObject *)dd);
2109 if (baserepr == NULL)
2110 return NULL;
2111 if (dd->default_factory == NULL)
2112 defrepr = PyUnicode_FromString("None");
2113 else
2114 {
2115 int status = Py_ReprEnter(dd->default_factory);
2116 if (status != 0) {
Antoine Pitrouf5f1fe02012-02-15 02:42:46 +01002117 if (status < 0) {
2118 Py_DECREF(baserepr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002119 return NULL;
Antoine Pitrouf5f1fe02012-02-15 02:42:46 +01002120 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002121 defrepr = PyUnicode_FromString("...");
2122 }
2123 else
2124 defrepr = PyObject_Repr(dd->default_factory);
2125 Py_ReprLeave(dd->default_factory);
2126 }
2127 if (defrepr == NULL) {
2128 Py_DECREF(baserepr);
2129 return NULL;
2130 }
Serhiy Storchakab3a77962017-09-21 14:24:13 +03002131 result = PyUnicode_FromFormat("%s(%U, %U)",
2132 _PyType_Name(Py_TYPE(dd)),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002133 defrepr, baserepr);
2134 Py_DECREF(defrepr);
2135 Py_DECREF(baserepr);
2136 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00002137}
2138
2139static int
2140defdict_traverse(PyObject *self, visitproc visit, void *arg)
2141{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002142 Py_VISIT(((defdictobject *)self)->default_factory);
2143 return PyDict_Type.tp_traverse(self, visit, arg);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002144}
2145
2146static int
2147defdict_tp_clear(defdictobject *dd)
2148{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002149 Py_CLEAR(dd->default_factory);
2150 return PyDict_Type.tp_clear((PyObject *)dd);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002151}
2152
2153static int
2154defdict_init(PyObject *self, PyObject *args, PyObject *kwds)
2155{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002156 defdictobject *dd = (defdictobject *)self;
2157 PyObject *olddefault = dd->default_factory;
2158 PyObject *newdefault = NULL;
2159 PyObject *newargs;
2160 int result;
2161 if (args == NULL || !PyTuple_Check(args))
2162 newargs = PyTuple_New(0);
2163 else {
2164 Py_ssize_t n = PyTuple_GET_SIZE(args);
2165 if (n > 0) {
2166 newdefault = PyTuple_GET_ITEM(args, 0);
2167 if (!PyCallable_Check(newdefault) && newdefault != Py_None) {
2168 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger239aba72015-07-20 03:09:22 -04002169 "first argument must be callable or None");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002170 return -1;
2171 }
2172 }
2173 newargs = PySequence_GetSlice(args, 1, n);
2174 }
2175 if (newargs == NULL)
2176 return -1;
2177 Py_XINCREF(newdefault);
2178 dd->default_factory = newdefault;
2179 result = PyDict_Type.tp_init(self, newargs, kwds);
2180 Py_DECREF(newargs);
2181 Py_XDECREF(olddefault);
2182 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00002183}
2184
2185PyDoc_STRVAR(defdict_doc,
Benjamin Peterson9cb33b72014-01-13 23:56:05 -05002186"defaultdict(default_factory[, ...]) --> dict with default factory\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00002187\n\
2188The default factory is called without arguments to produce\n\
2189a new value when a key is not present, in __getitem__ only.\n\
2190A defaultdict compares equal to a dict with the same items.\n\
Benjamin Peterson9cb33b72014-01-13 23:56:05 -05002191All remaining arguments are treated the same as if they were\n\
2192passed to the dict constructor, including keyword arguments.\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00002193");
2194
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002195/* See comment in xxsubtype.c */
2196#define DEFERRED_ADDRESS(ADDR) 0
2197
Guido van Rossum1968ad32006-02-25 22:38:04 +00002198static PyTypeObject defdict_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002199 PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0)
2200 "collections.defaultdict", /* tp_name */
2201 sizeof(defdictobject), /* tp_basicsize */
2202 0, /* tp_itemsize */
2203 /* methods */
2204 (destructor)defdict_dealloc, /* tp_dealloc */
2205 0, /* tp_print */
2206 0, /* tp_getattr */
2207 0, /* tp_setattr */
2208 0, /* tp_reserved */
2209 (reprfunc)defdict_repr, /* tp_repr */
2210 0, /* tp_as_number */
2211 0, /* tp_as_sequence */
2212 0, /* tp_as_mapping */
2213 0, /* tp_hash */
2214 0, /* tp_call */
2215 0, /* tp_str */
2216 PyObject_GenericGetAttr, /* tp_getattro */
2217 0, /* tp_setattro */
2218 0, /* tp_as_buffer */
2219 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
2220 /* tp_flags */
2221 defdict_doc, /* tp_doc */
2222 defdict_traverse, /* tp_traverse */
2223 (inquiry)defdict_tp_clear, /* tp_clear */
2224 0, /* tp_richcompare */
2225 0, /* tp_weaklistoffset*/
2226 0, /* tp_iter */
2227 0, /* tp_iternext */
2228 defdict_methods, /* tp_methods */
2229 defdict_members, /* tp_members */
2230 0, /* tp_getset */
2231 DEFERRED_ADDRESS(&PyDict_Type), /* tp_base */
2232 0, /* tp_dict */
2233 0, /* tp_descr_get */
2234 0, /* tp_descr_set */
2235 0, /* tp_dictoffset */
2236 defdict_init, /* tp_init */
2237 PyType_GenericAlloc, /* tp_alloc */
2238 0, /* tp_new */
2239 PyObject_GC_Del, /* tp_free */
Guido van Rossum1968ad32006-02-25 22:38:04 +00002240};
2241
Raymond Hettinger96f34102010-12-15 16:30:37 +00002242/* helper function for Counter *********************************************/
2243
2244PyDoc_STRVAR(_count_elements_doc,
2245"_count_elements(mapping, iterable) -> None\n\
2246\n\
Raymond Hettingera24dca62017-01-12 22:25:25 -08002247Count elements in the iterable, updating the mapping");
Raymond Hettinger96f34102010-12-15 16:30:37 +00002248
2249static PyObject *
2250_count_elements(PyObject *self, PyObject *args)
2251{
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002252 _Py_IDENTIFIER(get);
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002253 _Py_IDENTIFIER(__setitem__);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002254 PyObject *it, *iterable, *mapping, *oldval;
2255 PyObject *newval = NULL;
2256 PyObject *key = NULL;
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002257 PyObject *bound_get = NULL;
2258 PyObject *mapping_get;
2259 PyObject *dict_get;
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002260 PyObject *mapping_setitem;
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002261 PyObject *dict_setitem;
Raymond Hettinger96f34102010-12-15 16:30:37 +00002262
2263 if (!PyArg_UnpackTuple(args, "_count_elements", 2, 2, &mapping, &iterable))
2264 return NULL;
2265
Raymond Hettinger96f34102010-12-15 16:30:37 +00002266 it = PyObject_GetIter(iterable);
2267 if (it == NULL)
2268 return NULL;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002269
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002270 /* Only take the fast path when get() and __setitem__()
2271 * have not been overridden.
2272 */
2273 mapping_get = _PyType_LookupId(Py_TYPE(mapping), &PyId_get);
2274 dict_get = _PyType_LookupId(&PyDict_Type, &PyId_get);
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002275 mapping_setitem = _PyType_LookupId(Py_TYPE(mapping), &PyId___setitem__);
2276 dict_setitem = _PyType_LookupId(&PyDict_Type, &PyId___setitem__);
2277
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002278 if (mapping_get != NULL && mapping_get == dict_get &&
Oren Milman31aca4b2017-09-27 06:18:21 +03002279 mapping_setitem != NULL && mapping_setitem == dict_setitem &&
2280 PyDict_Check(mapping))
2281 {
Raymond Hettinger426e0522011-01-03 02:12:02 +00002282 while (1) {
Raymond Hettinger507d9972014-05-18 21:32:40 +01002283 /* Fast path advantages:
2284 1. Eliminate double hashing
2285 (by re-using the same hash for both the get and set)
2286 2. Avoid argument overhead of PyObject_CallFunctionObjArgs
2287 (argument tuple creation and parsing)
2288 3. Avoid indirection through a bound method object
2289 (creates another argument tuple)
2290 4. Avoid initial increment from zero
2291 (reuse an existing one-object instead)
2292 */
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002293 Py_hash_t hash;
2294
Raymond Hettinger426e0522011-01-03 02:12:02 +00002295 key = PyIter_Next(it);
Victor Stinnera154b5c2011-04-20 23:23:52 +02002296 if (key == NULL)
2297 break;
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002298
2299 if (!PyUnicode_CheckExact(key) ||
2300 (hash = ((PyASCIIObject *) key)->hash) == -1)
2301 {
2302 hash = PyObject_Hash(key);
Raymond Hettingerda2850f2015-02-27 12:42:54 -08002303 if (hash == -1)
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002304 goto done;
2305 }
2306
2307 oldval = _PyDict_GetItem_KnownHash(mapping, key, hash);
Raymond Hettinger426e0522011-01-03 02:12:02 +00002308 if (oldval == NULL) {
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02002309 if (PyErr_Occurred())
2310 goto done;
Serhiy Storchakaba85d692017-03-30 09:09:41 +03002311 if (_PyDict_SetItem_KnownHash(mapping, key, _PyLong_One, hash) < 0)
Raymond Hettinger507d9972014-05-18 21:32:40 +01002312 goto done;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002313 } else {
Serhiy Storchakaba85d692017-03-30 09:09:41 +03002314 newval = PyNumber_Add(oldval, _PyLong_One);
Raymond Hettinger426e0522011-01-03 02:12:02 +00002315 if (newval == NULL)
Raymond Hettinger507d9972014-05-18 21:32:40 +01002316 goto done;
Raymond Hettinger28c995d2015-08-14 02:07:41 -07002317 if (_PyDict_SetItem_KnownHash(mapping, key, newval, hash) < 0)
Raymond Hettinger507d9972014-05-18 21:32:40 +01002318 goto done;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002319 Py_CLEAR(newval);
2320 }
2321 Py_DECREF(key);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002322 }
Raymond Hettinger426e0522011-01-03 02:12:02 +00002323 } else {
Victor Stinnere7f516c2013-11-06 23:52:55 +01002324 bound_get = _PyObject_GetAttrId(mapping, &PyId_get);
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002325 if (bound_get == NULL)
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002326 goto done;
2327
Raymond Hettinger426e0522011-01-03 02:12:02 +00002328 while (1) {
2329 key = PyIter_Next(it);
Victor Stinnera154b5c2011-04-20 23:23:52 +02002330 if (key == NULL)
2331 break;
Serhiy Storchakaba85d692017-03-30 09:09:41 +03002332 oldval = PyObject_CallFunctionObjArgs(bound_get, key, _PyLong_Zero, NULL);
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002333 if (oldval == NULL)
2334 break;
Serhiy Storchakaba85d692017-03-30 09:09:41 +03002335 newval = PyNumber_Add(oldval, _PyLong_One);
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002336 Py_DECREF(oldval);
2337 if (newval == NULL)
2338 break;
Raymond Hettinger28c995d2015-08-14 02:07:41 -07002339 if (PyObject_SetItem(mapping, key, newval) < 0)
Raymond Hettinger96f34102010-12-15 16:30:37 +00002340 break;
2341 Py_CLEAR(newval);
Raymond Hettinger426e0522011-01-03 02:12:02 +00002342 Py_DECREF(key);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002343 }
Raymond Hettinger96f34102010-12-15 16:30:37 +00002344 }
Raymond Hettinger426e0522011-01-03 02:12:02 +00002345
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002346done:
Raymond Hettinger96f34102010-12-15 16:30:37 +00002347 Py_DECREF(it);
2348 Py_XDECREF(key);
2349 Py_XDECREF(newval);
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002350 Py_XDECREF(bound_get);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002351 if (PyErr_Occurred())
2352 return NULL;
2353 Py_RETURN_NONE;
2354}
2355
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002356/* module level code ********************************************************/
2357
2358PyDoc_STRVAR(module_doc,
Guido van Rossum1968ad32006-02-25 22:38:04 +00002359"High performance data structures.\n\
2360- deque: ordered collection accessible from endpoints only\n\
2361- defaultdict: dict subclass with a default value factory\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002362");
2363
Raymond Hettinger96f34102010-12-15 16:30:37 +00002364static struct PyMethodDef module_functions[] = {
2365 {"_count_elements", _count_elements, METH_VARARGS, _count_elements_doc},
2366 {NULL, NULL} /* sentinel */
2367};
Martin v. Löwis1a214512008-06-11 05:26:20 +00002368
2369static struct PyModuleDef _collectionsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002370 PyModuleDef_HEAD_INIT,
2371 "_collections",
2372 module_doc,
2373 -1,
Raymond Hettinger96f34102010-12-15 16:30:37 +00002374 module_functions,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002375 NULL,
2376 NULL,
2377 NULL,
2378 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002379};
2380
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002381PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002382PyInit__collections(void)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002383{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002384 PyObject *m;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002386 m = PyModule_Create(&_collectionsmodule);
2387 if (m == NULL)
2388 return NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002390 if (PyType_Ready(&deque_type) < 0)
2391 return NULL;
2392 Py_INCREF(&deque_type);
2393 PyModule_AddObject(m, "deque", (PyObject *)&deque_type);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002395 defdict_type.tp_base = &PyDict_Type;
2396 if (PyType_Ready(&defdict_type) < 0)
2397 return NULL;
2398 Py_INCREF(&defdict_type);
2399 PyModule_AddObject(m, "defaultdict", (PyObject *)&defdict_type);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002400
Eric Snow47db7172015-05-29 22:21:39 -06002401 Py_INCREF(&PyODict_Type);
2402 PyModule_AddObject(m, "OrderedDict", (PyObject *)&PyODict_Type);
2403
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002404 if (PyType_Ready(&dequeiter_type) < 0)
2405 return NULL;
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002406 Py_INCREF(&dequeiter_type);
2407 PyModule_AddObject(m, "_deque_iterator", (PyObject *)&dequeiter_type);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002409 if (PyType_Ready(&dequereviter_type) < 0)
2410 return NULL;
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002411 Py_INCREF(&dequereviter_type);
2412 PyModule_AddObject(m, "_deque_reverse_iterator", (PyObject *)&dequereviter_type);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00002413
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002414 return m;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002415}