blob: 935b4348a8ff8bb978861698a31f234d3e1b71da [file] [log] [blame]
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001#include "Python.h"
Raymond Hettinger691d8052004-05-30 07:26:47 +00002#include "structmember.h"
Raymond Hettinger756b3f32004-01-29 06:37:52 +00003
Raymond Hettingerc2083082015-02-28 23:29:16 -08004#ifdef STDC_HEADERS
5#include <stddef.h>
6#else
7#include <sys/types.h> /* For size_t */
8#endif
9
Raymond Hettinger756b3f32004-01-29 06:37:52 +000010/* collections module implementation of a deque() datatype
11 Written and maintained by Raymond D. Hettinger <python@rcn.com>
Raymond Hettinger756b3f32004-01-29 06:37:52 +000012*/
13
Raymond Hettinger77e8bf12004-10-01 15:25:53 +000014/* The block length may be set to any number over 1. Larger numbers
Raymond Hettinger20b0f872013-06-23 15:44:33 -070015 * reduce the number of calls to the memory allocator, give faster
Raymond Hettinger30c90742015-03-02 22:31:35 -080016 * indexing and rotation, and reduce the link to data overhead ratio.
Raymond Hettingerdaf57f22015-02-26 23:21:29 -080017 * Making the block length a power of two speeds-up the modulo
Raymond Hettinger30c90742015-03-02 22:31:35 -080018 * and division calculations in deque_item() and deque_ass_item().
Raymond Hettinger77e8bf12004-10-01 15:25:53 +000019 */
20
Raymond Hettingerdaf57f22015-02-26 23:21:29 -080021#define BLOCKLEN 64
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000022#define CENTER ((BLOCKLEN - 1) / 2)
Raymond Hettinger756b3f32004-01-29 06:37:52 +000023
Raymond Hettinger551350a2015-03-24 00:19:53 -070024/* Data for deque objects is stored in a doubly-linked list of fixed
25 * length blocks. This assures that appends or pops never move any
26 * other data elements besides the one being appended or popped.
27 *
28 * Another advantage is that it completely avoids use of realloc(),
29 * resulting in more predictable performance.
30 *
31 * Textbook implementations of doubly-linked lists store one datum
32 * per link, but that gives them a 200% memory overhead (a prev and
33 * next link for each datum) and it costs one malloc() call per data
34 * element. By using fixed-length blocks, the link to data ratio is
35 * significantly improved and there are proportionally fewer calls
36 * to malloc() and free(). The data blocks of consecutive pointers
37 * also improve cache locality.
38 *
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000039 * The list of blocks is never empty, so d.leftblock and d.rightblock
Raymond Hettinger82df9252013-07-07 01:43:42 -100040 * are never equal to NULL. The list is not circular.
41 *
42 * A deque d's first element is at d.leftblock[leftindex]
43 * and its last element is at d.rightblock[rightindex].
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000044 *
Raymond Hettinger551350a2015-03-24 00:19:53 -070045 * Unlike Python slice indices, these indices are inclusive on both
46 * ends. This makes the algorithms for left and right operations
47 * more symmetrical and it simplifies the design.
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000048 *
Raymond Hettinger551350a2015-03-24 00:19:53 -070049 * The indices, d.leftindex and d.rightindex are always in the range:
50 * 0 <= index < BLOCKLEN
51 *
52 * And their exact relationship is:
53 * (d.leftindex + d.len - 1) % BLOCKLEN == d.rightindex
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000054 *
Raymond Hettinger8dbbae22015-03-24 21:01:50 -070055 * Whenever d.leftblock == d.rightblock, then:
Raymond Hettinger551350a2015-03-24 00:19:53 -070056 * d.leftindex + d.len - 1 == d.rightindex
Thomas Wouters0e3f5912006-08-11 14:57:12 +000057 *
Raymond Hettinger551350a2015-03-24 00:19:53 -070058 * However, when d.leftblock != d.rightblock, the d.leftindex and
59 * d.rightindex become indices into distinct blocks and either may
60 * be larger than the other.
61 *
62 * Empty deques have:
63 * d.len == 0
64 * d.leftblock == d.rightblock
65 * d.leftindex == CENTER + 1
66 * d.rightindex == CENTER
67 *
68 * Checking for d.len == 0 is the intended way to see whether d is empty.
Tim Petersd8768d32004-10-01 01:32:53 +000069 */
70
Raymond Hettinger756b3f32004-01-29 06:37:52 +000071typedef struct BLOCK {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000072 struct BLOCK *leftlink;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000073 PyObject *data[BLOCKLEN];
Raymond Hettinger20b0f872013-06-23 15:44:33 -070074 struct BLOCK *rightlink;
Raymond Hettinger756b3f32004-01-29 06:37:52 +000075} block;
76
Raymond Hettinger30c90742015-03-02 22:31:35 -080077typedef struct {
78 PyObject_VAR_HEAD
79 block *leftblock;
80 block *rightblock;
Raymond Hettinger551350a2015-03-24 00:19:53 -070081 Py_ssize_t leftindex; /* 0 <= leftindex < BLOCKLEN */
82 Py_ssize_t rightindex; /* 0 <= rightindex < BLOCKLEN */
Raymond Hettingerf9d9c792015-03-02 22:47:46 -080083 size_t state; /* incremented whenever the indices move */
Raymond Hettingerd84ec222016-01-24 09:12:06 -080084 Py_ssize_t maxlen; /* maxlen is -1 for unbounded deques */
Raymond Hettinger0f6f9472015-03-21 01:42:10 -070085 PyObject *weakreflist;
Raymond Hettinger30c90742015-03-02 22:31:35 -080086} dequeobject;
87
88static PyTypeObject deque_type;
89
Raymond Hettinger82df9252013-07-07 01:43:42 -100090/* For debug builds, add error checking to track the endpoints
91 * in the chain of links. The goal is to make sure that link
92 * assignments only take place at endpoints so that links already
93 * in use do not get overwritten.
94 *
95 * CHECK_END should happen before each assignment to a block's link field.
96 * MARK_END should happen whenever a link field becomes a new endpoint.
97 * This happens when new blocks are added or whenever an existing
98 * block is freed leaving another existing block as the new endpoint.
99 */
100
Raymond Hettinger3223dd52013-07-26 23:14:22 -0700101#ifndef NDEBUG
Raymond Hettinger82df9252013-07-07 01:43:42 -1000102#define MARK_END(link) link = NULL;
103#define CHECK_END(link) assert(link == NULL);
104#define CHECK_NOT_END(link) assert(link != NULL);
105#else
106#define MARK_END(link)
107#define CHECK_END(link)
108#define CHECK_NOT_END(link)
109#endif
110
111/* A simple freelisting scheme is used to minimize calls to the memory
Raymond Hettinger551350a2015-03-24 00:19:53 -0700112 allocator. It accommodates common use cases where new blocks are being
Raymond Hettinger82df9252013-07-07 01:43:42 -1000113 added at about the same rate as old blocks are being freed.
114 */
115
Raymond Hettingerf2b02ce2015-09-26 17:47:02 -0700116#define MAXFREEBLOCKS 16
Benjamin Petersond6313712008-07-31 16:23:04 +0000117static Py_ssize_t numfreeblocks = 0;
Guido van Rossum58da9312007-11-10 23:39:45 +0000118static block *freeblocks[MAXFREEBLOCKS];
119
Tim Peters6f853562004-10-01 01:04:50 +0000120static block *
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700121newblock(void) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000122 block *b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000123 if (numfreeblocks) {
Raymond Hettinger59cf23a2013-02-07 00:57:19 -0500124 numfreeblocks--;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000125 return freeblocks[numfreeblocks];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000126 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000127 b = PyMem_Malloc(sizeof(block));
128 if (b != NULL) {
129 return b;
130 }
131 PyErr_NoMemory();
132 return NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000133}
134
Martin v. Löwis59683e82008-06-13 07:50:45 +0000135static void
Guido van Rossum58da9312007-11-10 23:39:45 +0000136freeblock(block *b)
137{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000138 if (numfreeblocks < MAXFREEBLOCKS) {
139 freeblocks[numfreeblocks] = b;
140 numfreeblocks++;
141 } else {
142 PyMem_Free(b);
143 }
Guido van Rossum58da9312007-11-10 23:39:45 +0000144}
145
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000146static PyObject *
147deque_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
148{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000149 dequeobject *deque;
150 block *b;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000152 /* create dequeobject structure */
153 deque = (dequeobject *)type->tp_alloc(type, 0);
154 if (deque == NULL)
155 return NULL;
Tim Peters1065f752004-10-01 01:03:29 +0000156
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700157 b = newblock();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000158 if (b == NULL) {
159 Py_DECREF(deque);
160 return NULL;
161 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000162 MARK_END(b->leftlink);
163 MARK_END(b->rightlink);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000165 assert(BLOCKLEN >= 2);
Raymond Hettinger87e69122015-03-02 23:32:02 -0800166 Py_SIZE(deque) = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000167 deque->leftblock = b;
168 deque->rightblock = b;
169 deque->leftindex = CENTER + 1;
170 deque->rightindex = CENTER;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000171 deque->state = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000172 deque->maxlen = -1;
Raymond Hettinger87e69122015-03-02 23:32:02 -0800173 deque->weakreflist = NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175 return (PyObject *)deque;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000176}
177
178static PyObject *
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000179deque_pop(dequeobject *deque, PyObject *unused)
180{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000181 PyObject *item;
182 block *prevblock;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000183
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000184 if (Py_SIZE(deque) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000185 PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
186 return NULL;
187 }
188 item = deque->rightblock->data[deque->rightindex];
189 deque->rightindex--;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000190 Py_SIZE(deque)--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000191 deque->state++;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000192
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -0700193 if (deque->rightindex < 0) {
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700194 if (Py_SIZE(deque)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000195 prevblock = deque->rightblock->leftlink;
196 assert(deque->leftblock != deque->rightblock);
197 freeblock(deque->rightblock);
Raymond Hettinger82df9252013-07-07 01:43:42 -1000198 CHECK_NOT_END(prevblock);
199 MARK_END(prevblock->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000200 deque->rightblock = prevblock;
201 deque->rightindex = BLOCKLEN - 1;
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700202 } else {
203 assert(deque->leftblock == deque->rightblock);
204 assert(deque->leftindex == deque->rightindex+1);
205 /* re-center instead of freeing a block */
206 deque->leftindex = CENTER + 1;
207 deque->rightindex = CENTER;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000208 }
209 }
210 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000211}
212
213PyDoc_STRVAR(pop_doc, "Remove and return the rightmost element.");
214
215static PyObject *
216deque_popleft(dequeobject *deque, PyObject *unused)
217{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000218 PyObject *item;
219 block *prevblock;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000220
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000221 if (Py_SIZE(deque) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000222 PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
223 return NULL;
224 }
225 assert(deque->leftblock != NULL);
226 item = deque->leftblock->data[deque->leftindex];
227 deque->leftindex++;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000228 Py_SIZE(deque)--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000229 deque->state++;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000231 if (deque->leftindex == BLOCKLEN) {
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700232 if (Py_SIZE(deque)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000233 assert(deque->leftblock != deque->rightblock);
234 prevblock = deque->leftblock->rightlink;
235 freeblock(deque->leftblock);
Raymond Hettinger82df9252013-07-07 01:43:42 -1000236 CHECK_NOT_END(prevblock);
237 MARK_END(prevblock->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000238 deque->leftblock = prevblock;
239 deque->leftindex = 0;
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700240 } else {
241 assert(deque->leftblock == deque->rightblock);
242 assert(deque->leftindex == deque->rightindex+1);
243 /* re-center instead of freeing a block */
244 deque->leftindex = CENTER + 1;
245 deque->rightindex = CENTER;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000246 }
247 }
248 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000249}
250
251PyDoc_STRVAR(popleft_doc, "Remove and return the leftmost element.");
252
Raymond Hettingerf30f5b92015-03-02 22:23:37 -0800253/* The deque's size limit is d.maxlen. The limit can be zero or positive.
254 * If there is no limit, then d.maxlen == -1.
255 *
Raymond Hettingera4b13d02015-10-15 08:05:31 -0700256 * After an item is added to a deque, we check to see if the size has
257 * grown past the limit. If it has, we get the size back down to the limit
258 * by popping an item off of the opposite end. The methods that can
259 * trigger this are append(), appendleft(), extend(), and extendleft().
Raymond Hettingerd96db092015-10-11 22:34:48 -0700260 *
261 * The macro to check whether a deque needs to be trimmed uses a single
262 * unsigned test that returns true whenever 0 <= maxlen < Py_SIZE(deque).
Raymond Hettingerf30f5b92015-03-02 22:23:37 -0800263 */
264
Raymond Hettingerd96db092015-10-11 22:34:48 -0700265#define NEEDS_TRIM(deque, maxlen) ((size_t)(maxlen) < (size_t)(Py_SIZE(deque)))
Raymond Hettingerf30f5b92015-03-02 22:23:37 -0800266
Raymond Hettinger66953f02018-07-10 04:17:40 -0700267static inline int
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800268deque_append_internal(dequeobject *deque, PyObject *item, Py_ssize_t maxlen)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000269{
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700270 if (deque->rightindex == BLOCKLEN - 1) {
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700271 block *b = newblock();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000272 if (b == NULL)
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800273 return -1;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000274 b->leftlink = deque->rightblock;
275 CHECK_END(deque->rightblock->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000276 deque->rightblock->rightlink = b;
277 deque->rightblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000278 MARK_END(b->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000279 deque->rightindex = -1;
280 }
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000281 Py_SIZE(deque)++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000282 deque->rightindex++;
283 deque->rightblock->data[deque->rightindex] = item;
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800284 if (NEEDS_TRIM(deque, maxlen)) {
Raymond Hettinger1286d142015-10-14 23:16:57 -0700285 PyObject *olditem = deque_popleft(deque, NULL);
286 Py_DECREF(olditem);
Raymond Hettinger0f43bb12015-10-20 00:03:33 -0700287 } else {
288 deque->state++;
Raymond Hettingerd96db092015-10-11 22:34:48 -0700289 }
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800290 return 0;
291}
292
293static PyObject *
294deque_append(dequeobject *deque, PyObject *item)
295{
296 Py_INCREF(item);
297 if (deque_append_internal(deque, item, deque->maxlen) < 0)
298 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000299 Py_RETURN_NONE;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000300}
301
302PyDoc_STRVAR(append_doc, "Add an element to the right side of the deque.");
303
Raymond Hettinger66953f02018-07-10 04:17:40 -0700304static inline int
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800305deque_appendleft_internal(dequeobject *deque, PyObject *item, Py_ssize_t maxlen)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000306{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000307 if (deque->leftindex == 0) {
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700308 block *b = newblock();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000309 if (b == NULL)
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800310 return -1;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000311 b->rightlink = deque->leftblock;
312 CHECK_END(deque->leftblock->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000313 deque->leftblock->leftlink = b;
314 deque->leftblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000315 MARK_END(b->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000316 deque->leftindex = BLOCKLEN;
317 }
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000318 Py_SIZE(deque)++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000319 deque->leftindex--;
320 deque->leftblock->data[deque->leftindex] = item;
Raymond Hettingerd96db092015-10-11 22:34:48 -0700321 if (NEEDS_TRIM(deque, deque->maxlen)) {
Raymond Hettinger1286d142015-10-14 23:16:57 -0700322 PyObject *olditem = deque_pop(deque, NULL);
323 Py_DECREF(olditem);
Raymond Hettinger0f43bb12015-10-20 00:03:33 -0700324 } else {
325 deque->state++;
Raymond Hettingerd96db092015-10-11 22:34:48 -0700326 }
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800327 return 0;
328}
329
330static PyObject *
331deque_appendleft(dequeobject *deque, PyObject *item)
332{
333 Py_INCREF(item);
334 if (deque_appendleft_internal(deque, item, deque->maxlen) < 0)
335 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000336 Py_RETURN_NONE;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000337}
338
339PyDoc_STRVAR(appendleft_doc, "Add an element to the left side of the deque.");
340
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700341static PyObject*
342finalize_iterator(PyObject *it)
343{
344 if (PyErr_Occurred()) {
345 if (PyErr_ExceptionMatches(PyExc_StopIteration))
346 PyErr_Clear();
347 else {
348 Py_DECREF(it);
349 return NULL;
350 }
351 }
352 Py_DECREF(it);
353 Py_RETURN_NONE;
354}
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000356/* Run an iterator to exhaustion. Shortcut for
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000357 the extend/extendleft methods when maxlen == 0. */
358static PyObject*
359consume_iterator(PyObject *it)
360{
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700361 PyObject *(*iternext)(PyObject *);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000362 PyObject *item;
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000363
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700364 iternext = *Py_TYPE(it)->tp_iternext;
365 while ((item = iternext(it)) != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000366 Py_DECREF(item);
367 }
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700368 return finalize_iterator(it);
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000369}
370
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000371static PyObject *
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000372deque_extend(dequeobject *deque, PyObject *iterable)
373{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000374 PyObject *it, *item;
Raymond Hettinger7a845522015-09-26 01:30:51 -0700375 PyObject *(*iternext)(PyObject *);
Raymond Hettinger6b1e1132015-10-11 09:43:50 -0700376 Py_ssize_t maxlen = deque->maxlen;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000378 /* Handle case where id(deque) == id(iterable) */
379 if ((PyObject *)deque == iterable) {
380 PyObject *result;
381 PyObject *s = PySequence_List(iterable);
382 if (s == NULL)
383 return NULL;
384 result = deque_extend(deque, s);
385 Py_DECREF(s);
386 return result;
387 }
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000388
Raymond Hettingerd79d5b12016-03-04 09:55:07 -0800389 it = PyObject_GetIter(iterable);
390 if (it == NULL)
391 return NULL;
392
393 if (maxlen == 0)
394 return consume_iterator(it);
395
Raymond Hettingerd9c116c2013-07-09 00:13:21 -0700396 /* Space saving heuristic. Start filling from the left */
397 if (Py_SIZE(deque) == 0) {
398 assert(deque->leftblock == deque->rightblock);
399 assert(deque->leftindex == deque->rightindex+1);
400 deque->leftindex = 1;
401 deque->rightindex = 0;
402 }
403
Raymond Hettinger7a845522015-09-26 01:30:51 -0700404 iternext = *Py_TYPE(it)->tp_iternext;
405 while ((item = iternext(it)) != NULL) {
Raymond Hettinger66953f02018-07-10 04:17:40 -0700406 if (deque_append_internal(deque, item, maxlen) == -1) {
407 Py_DECREF(item);
408 Py_DECREF(it);
409 return NULL;
Raymond Hettinger6b1e1132015-10-11 09:43:50 -0700410 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 }
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700412 return finalize_iterator(it);
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000413}
414
Tim Peters1065f752004-10-01 01:03:29 +0000415PyDoc_STRVAR(extend_doc,
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000416"Extend the right side of the deque with elements from the iterable");
417
418static PyObject *
419deque_extendleft(dequeobject *deque, PyObject *iterable)
420{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 PyObject *it, *item;
Raymond Hettinger7a845522015-09-26 01:30:51 -0700422 PyObject *(*iternext)(PyObject *);
Raymond Hettinger6b1e1132015-10-11 09:43:50 -0700423 Py_ssize_t maxlen = deque->maxlen;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425 /* Handle case where id(deque) == id(iterable) */
426 if ((PyObject *)deque == iterable) {
427 PyObject *result;
428 PyObject *s = PySequence_List(iterable);
429 if (s == NULL)
430 return NULL;
431 result = deque_extendleft(deque, s);
432 Py_DECREF(s);
433 return result;
434 }
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000435
Raymond Hettingerd79d5b12016-03-04 09:55:07 -0800436 it = PyObject_GetIter(iterable);
437 if (it == NULL)
438 return NULL;
439
440 if (maxlen == 0)
441 return consume_iterator(it);
442
Raymond Hettingerd9c116c2013-07-09 00:13:21 -0700443 /* Space saving heuristic. Start filling from the right */
444 if (Py_SIZE(deque) == 0) {
445 assert(deque->leftblock == deque->rightblock);
446 assert(deque->leftindex == deque->rightindex+1);
447 deque->leftindex = BLOCKLEN - 1;
448 deque->rightindex = BLOCKLEN - 2;
449 }
450
Raymond Hettinger7a845522015-09-26 01:30:51 -0700451 iternext = *Py_TYPE(it)->tp_iternext;
452 while ((item = iternext(it)) != NULL) {
Raymond Hettinger66953f02018-07-10 04:17:40 -0700453 if (deque_appendleft_internal(deque, item, maxlen) == -1) {
454 Py_DECREF(item);
455 Py_DECREF(it);
456 return NULL;
Raymond Hettinger6b1e1132015-10-11 09:43:50 -0700457 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000458 }
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700459 return finalize_iterator(it);
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000460}
461
Tim Peters1065f752004-10-01 01:03:29 +0000462PyDoc_STRVAR(extendleft_doc,
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000463"Extend the left side of the deque with elements from the iterable");
464
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000465static PyObject *
466deque_inplace_concat(dequeobject *deque, PyObject *other)
467{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000468 PyObject *result;
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000470 result = deque_extend(deque, other);
471 if (result == NULL)
472 return result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000473 Py_INCREF(deque);
Raymond Hettinger2b2b7532015-09-05 17:05:52 -0700474 Py_DECREF(result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000475 return (PyObject *)deque;
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000476}
477
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700478static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530479deque_copy(PyObject *deque, PyObject *Py_UNUSED(ignored))
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700480{
Oren Milman24bd50b2018-09-11 21:46:55 +0300481 PyObject *result;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700482 dequeobject *old_deque = (dequeobject *)deque;
483 if (Py_TYPE(deque) == &deque_type) {
484 dequeobject *new_deque;
485 PyObject *rv;
486
487 new_deque = (dequeobject *)deque_new(&deque_type, (PyObject *)NULL, (PyObject *)NULL);
488 if (new_deque == NULL)
489 return NULL;
490 new_deque->maxlen = old_deque->maxlen;
491 /* Fast path for the deque_repeat() common case where len(deque) == 1 */
Raymond Hettinger0443ac22015-10-05 22:52:37 -0400492 if (Py_SIZE(deque) == 1) {
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700493 PyObject *item = old_deque->leftblock->data[old_deque->leftindex];
494 rv = deque_append(new_deque, item);
495 } else {
496 rv = deque_extend(new_deque, deque);
497 }
498 if (rv != NULL) {
499 Py_DECREF(rv);
500 return (PyObject *)new_deque;
501 }
502 Py_DECREF(new_deque);
503 return NULL;
504 }
505 if (old_deque->maxlen < 0)
Oren Milman24bd50b2018-09-11 21:46:55 +0300506 result = PyObject_CallFunctionObjArgs((PyObject *)(Py_TYPE(deque)),
507 deque, NULL);
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700508 else
Oren Milman24bd50b2018-09-11 21:46:55 +0300509 result = PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "Oi",
510 deque, old_deque->maxlen, NULL);
511 if (result != NULL && !PyObject_TypeCheck(result, &deque_type)) {
512 PyErr_Format(PyExc_TypeError,
513 "%.200s() must return a deque, not %.200s",
514 Py_TYPE(deque)->tp_name, Py_TYPE(result)->tp_name);
515 Py_DECREF(result);
516 return NULL;
517 }
518 return result;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700519}
520
521PyDoc_STRVAR(copy_doc, "Return a shallow copy of a deque.");
Raymond Hettinger41290a62015-03-31 08:12:23 -0700522
523static PyObject *
524deque_concat(dequeobject *deque, PyObject *other)
525{
Benjamin Peterson1a629212015-04-04 10:52:36 -0400526 PyObject *new_deque, *result;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700527 int rv;
528
529 rv = PyObject_IsInstance(other, (PyObject *)&deque_type);
530 if (rv <= 0) {
531 if (rv == 0) {
532 PyErr_Format(PyExc_TypeError,
533 "can only concatenate deque (not \"%.200s\") to deque",
534 other->ob_type->tp_name);
535 }
536 return NULL;
537 }
538
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530539 new_deque = deque_copy((PyObject *)deque, NULL);
Raymond Hettinger41290a62015-03-31 08:12:23 -0700540 if (new_deque == NULL)
541 return NULL;
Benjamin Peterson1a629212015-04-04 10:52:36 -0400542 result = deque_extend((dequeobject *)new_deque, other);
543 if (result == NULL) {
544 Py_DECREF(new_deque);
545 return NULL;
546 }
547 Py_DECREF(result);
548 return new_deque;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700549}
550
Serhiy Storchakaa5c42282018-05-31 07:34:34 +0300551static int
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700552deque_clear(dequeobject *deque)
553{
554 block *b;
555 block *prevblock;
556 block *leftblock;
557 Py_ssize_t leftindex;
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800558 Py_ssize_t n, m;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700559 PyObject *item;
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800560 PyObject **itemptr, **limit;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700561
Raymond Hettinger38031142015-09-29 22:45:05 -0700562 if (Py_SIZE(deque) == 0)
Serhiy Storchakaa5c42282018-05-31 07:34:34 +0300563 return 0;
Raymond Hettinger38031142015-09-29 22:45:05 -0700564
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700565 /* During the process of clearing a deque, decrefs can cause the
566 deque to mutate. To avoid fatal confusion, we have to make the
567 deque empty before clearing the blocks and never refer to
568 anything via deque->ref while clearing. (This is the same
569 technique used for clearing lists, sets, and dicts.)
570
571 Making the deque empty requires allocating a new empty block. In
572 the unlikely event that memory is full, we fall back to an
573 alternate method that doesn't require a new block. Repeating
574 pops in a while-loop is slower, possibly re-entrant (and a clever
575 adversary could cause it to never terminate).
576 */
577
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700578 b = newblock();
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700579 if (b == NULL) {
580 PyErr_Clear();
581 goto alternate_method;
582 }
583
584 /* Remember the old size, leftblock, and leftindex */
Raymond Hettinger6f86a332016-03-02 00:30:58 -0800585 n = Py_SIZE(deque);
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700586 leftblock = deque->leftblock;
587 leftindex = deque->leftindex;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700588
589 /* Set the deque to be empty using the newly allocated block */
590 MARK_END(b->leftlink);
591 MARK_END(b->rightlink);
592 Py_SIZE(deque) = 0;
593 deque->leftblock = b;
594 deque->rightblock = b;
595 deque->leftindex = CENTER + 1;
596 deque->rightindex = CENTER;
597 deque->state++;
598
599 /* Now the old size, leftblock, and leftindex are disconnected from
600 the empty deque and we can use them to decref the pointers.
601 */
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800602 m = (BLOCKLEN - leftindex > n) ? n : BLOCKLEN - leftindex;
Raymond Hettinger589106b2016-03-02 00:06:21 -0800603 itemptr = &leftblock->data[leftindex];
Raymond Hettinger6f86a332016-03-02 00:30:58 -0800604 limit = itemptr + m;
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800605 n -= m;
606 while (1) {
607 if (itemptr == limit) {
608 if (n == 0)
609 break;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700610 CHECK_NOT_END(leftblock->rightlink);
611 prevblock = leftblock;
612 leftblock = leftblock->rightlink;
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800613 m = (n > BLOCKLEN) ? BLOCKLEN : n;
Raymond Hettinger589106b2016-03-02 00:06:21 -0800614 itemptr = leftblock->data;
Raymond Hettinger6f86a332016-03-02 00:30:58 -0800615 limit = itemptr + m;
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800616 n -= m;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700617 freeblock(prevblock);
618 }
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800619 item = *(itemptr++);
620 Py_DECREF(item);
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700621 }
622 CHECK_END(leftblock->rightlink);
623 freeblock(leftblock);
Serhiy Storchakaa5c42282018-05-31 07:34:34 +0300624 return 0;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700625
626 alternate_method:
627 while (Py_SIZE(deque)) {
628 item = deque_pop(deque, NULL);
629 assert (item != NULL);
630 Py_DECREF(item);
631 }
Serhiy Storchakaa5c42282018-05-31 07:34:34 +0300632 return 0;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700633}
634
635static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530636deque_clearmethod(dequeobject *deque, PyObject *Py_UNUSED(ignored))
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700637{
638 deque_clear(deque);
639 Py_RETURN_NONE;
640}
641
642PyDoc_STRVAR(clear_doc, "Remove all elements from the deque.");
Raymond Hettinger41290a62015-03-31 08:12:23 -0700643
644static PyObject *
Raymond Hettinger41290a62015-03-31 08:12:23 -0700645deque_inplace_repeat(dequeobject *deque, Py_ssize_t n)
646{
Raymond Hettingerc22eee62015-09-26 02:14:50 -0700647 Py_ssize_t i, m, size;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700648 PyObject *seq;
649 PyObject *rv;
650
651 size = Py_SIZE(deque);
652 if (size == 0 || n == 1) {
653 Py_INCREF(deque);
654 return (PyObject *)deque;
655 }
656
657 if (n <= 0) {
658 deque_clear(deque);
659 Py_INCREF(deque);
660 return (PyObject *)deque;
661 }
662
Raymond Hettinger41290a62015-03-31 08:12:23 -0700663 if (size == 1) {
664 /* common case, repeating a single element */
665 PyObject *item = deque->leftblock->data[deque->leftindex];
666
Raymond Hettingera7f630092015-10-10 23:56:02 -0400667 if (deque->maxlen >= 0 && n > deque->maxlen)
Raymond Hettinger41290a62015-03-31 08:12:23 -0700668 n = deque->maxlen;
669
Raymond Hettinger67c78b52015-09-12 11:00:20 -0400670 deque->state++;
Raymond Hettingerad262252015-09-14 01:03:04 -0400671 for (i = 0 ; i < n-1 ; ) {
Raymond Hettinger67c78b52015-09-12 11:00:20 -0400672 if (deque->rightindex == BLOCKLEN - 1) {
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700673 block *b = newblock();
Raymond Hettinger67c78b52015-09-12 11:00:20 -0400674 if (b == NULL) {
675 Py_SIZE(deque) += i;
676 return NULL;
677 }
678 b->leftlink = deque->rightblock;
679 CHECK_END(deque->rightblock->rightlink);
680 deque->rightblock->rightlink = b;
681 deque->rightblock = b;
682 MARK_END(b->rightlink);
683 deque->rightindex = -1;
684 }
Raymond Hettingerc22eee62015-09-26 02:14:50 -0700685 m = n - 1 - i;
686 if (m > BLOCKLEN - 1 - deque->rightindex)
687 m = BLOCKLEN - 1 - deque->rightindex;
688 i += m;
689 while (m--) {
Raymond Hettingerad262252015-09-14 01:03:04 -0400690 deque->rightindex++;
691 Py_INCREF(item);
692 deque->rightblock->data[deque->rightindex] = item;
693 }
Raymond Hettinger41290a62015-03-31 08:12:23 -0700694 }
Raymond Hettinger67c78b52015-09-12 11:00:20 -0400695 Py_SIZE(deque) += i;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700696 Py_INCREF(deque);
697 return (PyObject *)deque;
698 }
699
Raymond Hettinger20151f52015-10-16 22:47:29 -0700700 if ((size_t)size > PY_SSIZE_T_MAX / (size_t)n) {
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400701 return PyErr_NoMemory();
702 }
703
Raymond Hettinger41290a62015-03-31 08:12:23 -0700704 seq = PySequence_List((PyObject *)deque);
705 if (seq == NULL)
706 return seq;
707
Louie Lu357bad72017-02-24 11:59:49 +0800708 /* Reduce the number of repetitions when maxlen would be exceeded */
709 if (deque->maxlen >= 0 && n * size > deque->maxlen)
710 n = (deque->maxlen + size - 1) / size;
711
Raymond Hettinger41290a62015-03-31 08:12:23 -0700712 for (i = 0 ; i < n-1 ; i++) {
713 rv = deque_extend(deque, seq);
714 if (rv == NULL) {
715 Py_DECREF(seq);
716 return NULL;
717 }
718 Py_DECREF(rv);
719 }
720 Py_INCREF(deque);
721 Py_DECREF(seq);
722 return (PyObject *)deque;
723}
724
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400725static PyObject *
726deque_repeat(dequeobject *deque, Py_ssize_t n)
727{
728 dequeobject *new_deque;
Raymond Hettinger95e2cc52015-09-13 02:41:18 -0400729 PyObject *rv;
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400730
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530731 new_deque = (dequeobject *)deque_copy((PyObject *) deque, NULL);
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400732 if (new_deque == NULL)
733 return NULL;
Raymond Hettinger95e2cc52015-09-13 02:41:18 -0400734 rv = deque_inplace_repeat(new_deque, n);
735 Py_DECREF(new_deque);
736 return rv;
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400737}
738
Raymond Hettinger54023152014-04-23 00:58:48 -0700739/* The rotate() method is part of the public API and is used internally
740as a primitive for other methods.
741
742Rotation by 1 or -1 is a common case, so any optimizations for high
743volume rotations should take care not to penalize the common case.
744
745Conceptually, a rotate by one is equivalent to a pop on one side and an
746append on the other. However, a pop/append pair is unnecessarily slow
Martin Panterd2ad5712015-11-02 04:20:33 +0000747because it requires an incref/decref pair for an object located randomly
Raymond Hettinger54023152014-04-23 00:58:48 -0700748in memory. It is better to just move the object pointer from one block
749to the next without changing the reference count.
750
751When moving batches of pointers, it is tempting to use memcpy() but that
752proved to be slower than a simple loop for a variety of reasons.
753Memcpy() cannot know in advance that we're copying pointers instead of
754bytes, that the source and destination are pointer aligned and
755non-overlapping, that moving just one pointer is a common case, that we
756never need to move more than BLOCKLEN pointers, and that at least one
757pointer is always moved.
758
759For high volume rotations, newblock() and freeblock() are never called
760more than once. Previously emptied blocks are immediately reused as a
761destination block. If a block is left-over at the end, it is freed.
762*/
763
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000764static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000765_deque_rotate(dequeobject *deque, Py_ssize_t n)
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000766{
Raymond Hettinger3959af92013-07-13 02:34:08 -0700767 block *b = NULL;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700768 block *leftblock = deque->leftblock;
769 block *rightblock = deque->rightblock;
770 Py_ssize_t leftindex = deque->leftindex;
771 Py_ssize_t rightindex = deque->rightindex;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000772 Py_ssize_t len=Py_SIZE(deque), halflen=len>>1;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700773 int rv = -1;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000774
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800775 if (len <= 1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000776 return 0;
777 if (n > halflen || n < -halflen) {
778 n %= len;
779 if (n > halflen)
780 n -= len;
781 else if (n < -halflen)
782 n += len;
783 }
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500784 assert(len > 1);
Raymond Hettingera4409c12013-02-04 00:08:12 -0500785 assert(-halflen <= n && n <= halflen);
Raymond Hettinger231ee4d2013-02-02 11:24:43 -0800786
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800787 deque->state++;
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500788 while (n > 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700789 if (leftindex == 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700790 if (b == NULL) {
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700791 b = newblock();
Raymond Hettinger3959af92013-07-13 02:34:08 -0700792 if (b == NULL)
793 goto done;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700794 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000795 b->rightlink = leftblock;
796 CHECK_END(leftblock->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700797 leftblock->leftlink = b;
798 leftblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000799 MARK_END(b->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700800 leftindex = BLOCKLEN;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700801 b = NULL;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800802 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700803 assert(leftindex > 0);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700804 {
805 PyObject **src, **dest;
806 Py_ssize_t m = n;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800807
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700808 if (m > rightindex + 1)
809 m = rightindex + 1;
810 if (m > leftindex)
811 m = leftindex;
812 assert (m > 0 && m <= len);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700813 rightindex -= m;
814 leftindex -= m;
Raymond Hettinger0e259f12015-02-01 22:53:41 -0800815 src = &rightblock->data[rightindex + 1];
816 dest = &leftblock->data[leftindex];
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700817 n -= m;
Raymond Hettinger840533b2013-07-13 17:03:58 -0700818 do {
Raymond Hettinger0e259f12015-02-01 22:53:41 -0800819 *(dest++) = *(src++);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700820 } while (--m);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700821 }
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -0700822 if (rightindex < 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700823 assert(leftblock != rightblock);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700824 assert(b == NULL);
Raymond Hettinger3959af92013-07-13 02:34:08 -0700825 b = rightblock;
Raymond Hettingerb97cc492013-07-21 01:51:07 -0700826 CHECK_NOT_END(rightblock->leftlink);
827 rightblock = rightblock->leftlink;
828 MARK_END(rightblock->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700829 rightindex = BLOCKLEN - 1;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800830 }
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800831 }
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500832 while (n < 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700833 if (rightindex == BLOCKLEN - 1) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700834 if (b == NULL) {
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700835 b = newblock();
Raymond Hettinger3959af92013-07-13 02:34:08 -0700836 if (b == NULL)
837 goto done;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700838 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000839 b->leftlink = rightblock;
840 CHECK_END(rightblock->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700841 rightblock->rightlink = b;
842 rightblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000843 MARK_END(b->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700844 rightindex = -1;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700845 b = NULL;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800846 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700847 assert (rightindex < BLOCKLEN - 1);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700848 {
849 PyObject **src, **dest;
850 Py_ssize_t m = -n;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800851
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700852 if (m > BLOCKLEN - leftindex)
853 m = BLOCKLEN - leftindex;
854 if (m > BLOCKLEN - 1 - rightindex)
855 m = BLOCKLEN - 1 - rightindex;
856 assert (m > 0 && m <= len);
857 src = &leftblock->data[leftindex];
858 dest = &rightblock->data[rightindex + 1];
859 leftindex += m;
860 rightindex += m;
861 n += m;
Raymond Hettinger840533b2013-07-13 17:03:58 -0700862 do {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700863 *(dest++) = *(src++);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700864 } while (--m);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700865 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700866 if (leftindex == BLOCKLEN) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700867 assert(leftblock != rightblock);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700868 assert(b == NULL);
Raymond Hettinger3959af92013-07-13 02:34:08 -0700869 b = leftblock;
Raymond Hettingerb97cc492013-07-21 01:51:07 -0700870 CHECK_NOT_END(leftblock->rightlink);
871 leftblock = leftblock->rightlink;
872 MARK_END(leftblock->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700873 leftindex = 0;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800874 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000875 }
Raymond Hettinger3959af92013-07-13 02:34:08 -0700876 rv = 0;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700877done:
Raymond Hettinger3959af92013-07-13 02:34:08 -0700878 if (b != NULL)
879 freeblock(b);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700880 deque->leftblock = leftblock;
881 deque->rightblock = rightblock;
882 deque->leftindex = leftindex;
883 deque->rightindex = rightindex;
884
885 return rv;
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000886}
887
888static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +0200889deque_rotate(dequeobject *deque, PyObject *const *args, Py_ssize_t nargs)
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000890{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000891 Py_ssize_t n=1;
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000892
Victor Stinnerdd407d52017-02-06 16:06:49 +0100893 if (!_PyArg_ParseStack(args, nargs, "|n:rotate", &n)) {
894 return NULL;
895 }
896
Raymond Hettinger6921c132015-03-21 02:03:40 -0700897 if (!_deque_rotate(deque, n))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000898 Py_RETURN_NONE;
899 return NULL;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000900}
901
Tim Peters1065f752004-10-01 01:03:29 +0000902PyDoc_STRVAR(rotate_doc,
Raymond Hettingeree33b272004-02-08 04:05:26 +0000903"Rotate the deque n steps to the right (default n=1). If n is negative, rotates left.");
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000904
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000905static PyObject *
906deque_reverse(dequeobject *deque, PyObject *unused)
907{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000908 block *leftblock = deque->leftblock;
909 block *rightblock = deque->rightblock;
910 Py_ssize_t leftindex = deque->leftindex;
911 Py_ssize_t rightindex = deque->rightindex;
Raymond Hettingercfe5b6c2015-07-20 00:25:50 -0400912 Py_ssize_t n = Py_SIZE(deque) >> 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 PyObject *tmp;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000914
Raymond Hettingere1b02872017-09-04 16:07:06 -0700915 while (--n >= 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 /* Validate that pointers haven't met in the middle */
917 assert(leftblock != rightblock || leftindex < rightindex);
Raymond Hettinger82df9252013-07-07 01:43:42 -1000918 CHECK_NOT_END(leftblock);
919 CHECK_NOT_END(rightblock);
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 /* Swap */
922 tmp = leftblock->data[leftindex];
923 leftblock->data[leftindex] = rightblock->data[rightindex];
924 rightblock->data[rightindex] = tmp;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000925
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 /* Advance left block/index pair */
927 leftindex++;
928 if (leftindex == BLOCKLEN) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000929 leftblock = leftblock->rightlink;
930 leftindex = 0;
931 }
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933 /* Step backwards with the right block/index pair */
934 rightindex--;
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -0700935 if (rightindex < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 rightblock = rightblock->leftlink;
937 rightindex = BLOCKLEN - 1;
938 }
939 }
940 Py_RETURN_NONE;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000941}
942
943PyDoc_STRVAR(reverse_doc,
944"D.reverse() -- reverse *IN PLACE*");
945
Raymond Hettinger44459de2010-04-03 23:20:46 +0000946static PyObject *
947deque_count(dequeobject *deque, PyObject *v)
948{
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000949 block *b = deque->leftblock;
950 Py_ssize_t index = deque->leftindex;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000951 Py_ssize_t n = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 Py_ssize_t count = 0;
Raymond Hettingerf9d9c792015-03-02 22:47:46 -0800953 size_t start_state = deque->state;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000954 PyObject *item;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 int cmp;
Raymond Hettinger44459de2010-04-03 23:20:46 +0000956
Raymond Hettingere1b02872017-09-04 16:07:06 -0700957 while (--n >= 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000958 CHECK_NOT_END(b);
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000959 item = b->data[index];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
Raymond Hettinger2b0d6462015-09-23 19:15:44 -0700961 if (cmp < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962 return NULL;
Raymond Hettinger2b0d6462015-09-23 19:15:44 -0700963 count += cmp;
Raymond Hettinger44459de2010-04-03 23:20:46 +0000964
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000965 if (start_state != deque->state) {
966 PyErr_SetString(PyExc_RuntimeError,
967 "deque mutated during iteration");
968 return NULL;
969 }
Raymond Hettinger44459de2010-04-03 23:20:46 +0000970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 /* Advance left block/index pair */
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000972 index++;
973 if (index == BLOCKLEN) {
974 b = b->rightlink;
975 index = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000976 }
977 }
978 return PyLong_FromSsize_t(count);
Raymond Hettinger44459de2010-04-03 23:20:46 +0000979}
980
981PyDoc_STRVAR(count_doc,
982"D.count(value) -> integer -- return number of occurrences of value");
983
Raymond Hettinger39dadf72015-03-20 16:38:56 -0700984static int
985deque_contains(dequeobject *deque, PyObject *v)
986{
987 block *b = deque->leftblock;
988 Py_ssize_t index = deque->leftindex;
989 Py_ssize_t n = Py_SIZE(deque);
Raymond Hettinger39dadf72015-03-20 16:38:56 -0700990 size_t start_state = deque->state;
991 PyObject *item;
992 int cmp;
993
Raymond Hettingere1b02872017-09-04 16:07:06 -0700994 while (--n >= 0) {
Raymond Hettinger39dadf72015-03-20 16:38:56 -0700995 CHECK_NOT_END(b);
996 item = b->data[index];
997 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
998 if (cmp) {
999 return cmp;
1000 }
1001 if (start_state != deque->state) {
1002 PyErr_SetString(PyExc_RuntimeError,
1003 "deque mutated during iteration");
1004 return -1;
1005 }
1006 index++;
1007 if (index == BLOCKLEN) {
1008 b = b->rightlink;
1009 index = 0;
1010 }
1011 }
1012 return 0;
1013}
1014
Martin v. Löwis18e16552006-02-15 17:27:45 +00001015static Py_ssize_t
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001016deque_len(dequeobject *deque)
1017{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001018 return Py_SIZE(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001019}
1020
Raymond Hettinger4aec61e2005-03-18 21:20:23 +00001021static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02001022deque_index(dequeobject *deque, PyObject *const *args, Py_ssize_t nargs)
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001023{
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001024 Py_ssize_t i, n, start=0, stop=Py_SIZE(deque);
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001025 PyObject *v, *item;
1026 block *b = deque->leftblock;
1027 Py_ssize_t index = deque->leftindex;
1028 size_t start_state = deque->state;
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001029 int cmp;
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001030
Victor Stinnerdd407d52017-02-06 16:06:49 +01001031 if (!_PyArg_ParseStack(args, nargs, "O|O&O&:index", &v,
Serhiy Storchakad4edfc92017-03-30 18:29:23 +03001032 _PyEval_SliceIndexNotNone, &start,
1033 _PyEval_SliceIndexNotNone, &stop)) {
Victor Stinnerdd407d52017-02-06 16:06:49 +01001034 return NULL;
1035 }
1036
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001037 if (start < 0) {
1038 start += Py_SIZE(deque);
1039 if (start < 0)
1040 start = 0;
1041 }
1042 if (stop < 0) {
1043 stop += Py_SIZE(deque);
1044 if (stop < 0)
1045 stop = 0;
1046 }
Raymond Hettinger87674ec2015-08-26 08:08:38 -07001047 if (stop > Py_SIZE(deque))
1048 stop = Py_SIZE(deque);
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001049 if (start > stop)
1050 start = stop;
1051 assert(0 <= start && start <= stop && stop <= Py_SIZE(deque));
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001052
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001053 /* XXX Replace this loop with faster code from deque_item() */
1054 for (i=0 ; i<start ; i++) {
1055 index++;
1056 if (index == BLOCKLEN) {
1057 b = b->rightlink;
1058 index = 0;
1059 }
1060 }
1061
Raymond Hettingere1b02872017-09-04 16:07:06 -07001062 n = stop - i;
1063 while (--n >= 0) {
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001064 CHECK_NOT_END(b);
1065 item = b->data[index];
1066 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
1067 if (cmp > 0)
Raymond Hettingere1b02872017-09-04 16:07:06 -07001068 return PyLong_FromSsize_t(stop - n - 1);
Raymond Hettingerdf8f5b52015-11-02 07:27:40 -05001069 if (cmp < 0)
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001070 return NULL;
1071 if (start_state != deque->state) {
1072 PyErr_SetString(PyExc_RuntimeError,
1073 "deque mutated during iteration");
1074 return NULL;
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001075 }
1076 index++;
1077 if (index == BLOCKLEN) {
1078 b = b->rightlink;
1079 index = 0;
1080 }
1081 }
1082 PyErr_Format(PyExc_ValueError, "%R is not in deque", v);
1083 return NULL;
1084}
1085
1086PyDoc_STRVAR(index_doc,
1087"D.index(value, [start, [stop]]) -> integer -- return first index of value.\n"
1088"Raises ValueError if the value is not present.");
1089
Raymond Hettinger551350a2015-03-24 00:19:53 -07001090/* insert(), remove(), and delitem() are implemented in terms of
1091 rotate() for simplicity and reasonable performance near the end
1092 points. If for some reason these methods become popular, it is not
1093 hard to re-implement this using direct data movement (similar to
1094 the code used in list slice assignments) and achieve a performance
Raymond Hettingerfef9c1b2015-03-24 21:12:57 -07001095 boost (by moving each pointer only once instead of twice).
Raymond Hettinger551350a2015-03-24 00:19:53 -07001096*/
1097
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001098static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02001099deque_insert(dequeobject *deque, PyObject *const *args, Py_ssize_t nargs)
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001100{
1101 Py_ssize_t index;
1102 Py_ssize_t n = Py_SIZE(deque);
1103 PyObject *value;
1104 PyObject *rv;
1105
Victor Stinnerdd407d52017-02-06 16:06:49 +01001106 if (!_PyArg_ParseStack(args, nargs, "nO:insert", &index, &value)) {
1107 return NULL;
1108 }
1109
Raymond Hettinger37434322016-01-26 21:44:16 -08001110 if (deque->maxlen == Py_SIZE(deque)) {
Raymond Hettingera6389712016-02-01 21:21:19 -08001111 PyErr_SetString(PyExc_IndexError, "deque already at its maximum size");
1112 return NULL;
Raymond Hettinger37434322016-01-26 21:44:16 -08001113 }
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001114 if (index >= n)
1115 return deque_append(deque, value);
1116 if (index <= -n || index == 0)
1117 return deque_appendleft(deque, value);
1118 if (_deque_rotate(deque, -index))
1119 return NULL;
1120 if (index < 0)
1121 rv = deque_append(deque, value);
1122 else
1123 rv = deque_appendleft(deque, value);
1124 if (rv == NULL)
1125 return NULL;
1126 Py_DECREF(rv);
1127 if (_deque_rotate(deque, index))
1128 return NULL;
1129 Py_RETURN_NONE;
1130}
1131
1132PyDoc_STRVAR(insert_doc,
1133"D.insert(index, object) -- insert object before index");
1134
1135static PyObject *
Raymond Hettinger4aec61e2005-03-18 21:20:23 +00001136deque_remove(dequeobject *deque, PyObject *value)
1137{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001138 Py_ssize_t i, n=Py_SIZE(deque);
Raymond Hettinger4aec61e2005-03-18 21:20:23 +00001139
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001140 for (i=0 ; i<n ; i++) {
1141 PyObject *item = deque->leftblock->data[deque->leftindex];
1142 int cmp = PyObject_RichCompareBool(item, value, Py_EQ);
Raymond Hettingerd73202c2005-03-19 00:00:51 +00001143
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001144 if (Py_SIZE(deque) != n) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001145 PyErr_SetString(PyExc_IndexError,
1146 "deque mutated during remove().");
1147 return NULL;
1148 }
1149 if (cmp > 0) {
1150 PyObject *tgt = deque_popleft(deque, NULL);
1151 assert (tgt != NULL);
Raymond Hettinger6921c132015-03-21 02:03:40 -07001152 if (_deque_rotate(deque, i))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001153 return NULL;
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001154 Py_DECREF(tgt);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001155 Py_RETURN_NONE;
1156 }
1157 else if (cmp < 0) {
1158 _deque_rotate(deque, i);
1159 return NULL;
1160 }
1161 _deque_rotate(deque, -1);
1162 }
1163 PyErr_SetString(PyExc_ValueError, "deque.remove(x): x not in deque");
1164 return NULL;
Raymond Hettinger4aec61e2005-03-18 21:20:23 +00001165}
1166
1167PyDoc_STRVAR(remove_doc,
1168"D.remove(value) -- remove first occurrence of value.");
1169
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001170static int
1171valid_index(Py_ssize_t i, Py_ssize_t limit)
1172{
Raymond Hettinger12f896c2015-07-31 12:03:20 -07001173 /* The cast to size_t lets us use just a single comparison
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001174 to check whether i is in the range: 0 <= i < limit */
1175 return (size_t) i < (size_t) limit;
1176}
1177
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001178static PyObject *
Benjamin Petersond6313712008-07-31 16:23:04 +00001179deque_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001180{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001181 block *b;
1182 PyObject *item;
1183 Py_ssize_t n, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001184
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001185 if (!valid_index(i, Py_SIZE(deque))) {
1186 PyErr_SetString(PyExc_IndexError, "deque index out of range");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001187 return NULL;
1188 }
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001189
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001190 if (i == 0) {
1191 i = deque->leftindex;
1192 b = deque->leftblock;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001193 } else if (i == Py_SIZE(deque) - 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 i = deque->rightindex;
1195 b = deque->rightblock;
1196 } else {
1197 i += deque->leftindex;
Raymond Hettingerc2083082015-02-28 23:29:16 -08001198 n = (Py_ssize_t)((size_t) i / BLOCKLEN);
1199 i = (Py_ssize_t)((size_t) i % BLOCKLEN);
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001200 if (index < (Py_SIZE(deque) >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001201 b = deque->leftblock;
Raymond Hettingere1b02872017-09-04 16:07:06 -07001202 while (--n >= 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001203 b = b->rightlink;
1204 } else {
Raymond Hettinger63d1ff22015-02-28 07:41:30 -08001205 n = (Py_ssize_t)(
Raymond Hettingerc2083082015-02-28 23:29:16 -08001206 ((size_t)(deque->leftindex + Py_SIZE(deque) - 1))
Raymond Hettinger63d1ff22015-02-28 07:41:30 -08001207 / BLOCKLEN - n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001208 b = deque->rightblock;
Raymond Hettingere1b02872017-09-04 16:07:06 -07001209 while (--n >= 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001210 b = b->leftlink;
1211 }
1212 }
1213 item = b->data[i];
1214 Py_INCREF(item);
1215 return item;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001216}
1217
1218static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001219deque_del_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001220{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001221 PyObject *item;
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001222 int rv;
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001223
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001224 assert (i >= 0 && i < Py_SIZE(deque));
Raymond Hettinger6921c132015-03-21 02:03:40 -07001225 if (_deque_rotate(deque, -i))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001226 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001227 item = deque_popleft(deque, NULL);
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001228 rv = _deque_rotate(deque, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 assert (item != NULL);
1230 Py_DECREF(item);
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001231 return rv;
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001232}
1233
1234static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001235deque_ass_item(dequeobject *deque, Py_ssize_t i, PyObject *v)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001236{
Raymond Hettinger38418662016-02-08 20:34:49 -08001237 PyObject *old_value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001238 block *b;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001239 Py_ssize_t n, len=Py_SIZE(deque), halflen=(len+1)>>1, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001240
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001241 if (!valid_index(i, len)) {
1242 PyErr_SetString(PyExc_IndexError, "deque index out of range");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001243 return -1;
1244 }
1245 if (v == NULL)
1246 return deque_del_item(deque, i);
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001248 i += deque->leftindex;
Raymond Hettingerc2083082015-02-28 23:29:16 -08001249 n = (Py_ssize_t)((size_t) i / BLOCKLEN);
1250 i = (Py_ssize_t)((size_t) i % BLOCKLEN);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001251 if (index <= halflen) {
1252 b = deque->leftblock;
Raymond Hettingere1b02872017-09-04 16:07:06 -07001253 while (--n >= 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001254 b = b->rightlink;
1255 } else {
Raymond Hettingera473b9d2015-02-28 17:49:47 -08001256 n = (Py_ssize_t)(
Raymond Hettingerc2083082015-02-28 23:29:16 -08001257 ((size_t)(deque->leftindex + Py_SIZE(deque) - 1))
Raymond Hettingera473b9d2015-02-28 17:49:47 -08001258 / BLOCKLEN - n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001259 b = deque->rightblock;
Raymond Hettingere1b02872017-09-04 16:07:06 -07001260 while (--n >= 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001261 b = b->leftlink;
1262 }
1263 Py_INCREF(v);
Raymond Hettinger38418662016-02-08 20:34:49 -08001264 old_value = b->data[i];
1265 b->data[i] = v;
1266 Py_DECREF(old_value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001267 return 0;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001268}
1269
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001270static void
1271deque_dealloc(dequeobject *deque)
1272{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001273 PyObject_GC_UnTrack(deque);
1274 if (deque->weakreflist != NULL)
1275 PyObject_ClearWeakRefs((PyObject *) deque);
1276 if (deque->leftblock != NULL) {
1277 deque_clear(deque);
1278 assert(deque->leftblock != NULL);
1279 freeblock(deque->leftblock);
1280 }
1281 deque->leftblock = NULL;
1282 deque->rightblock = NULL;
1283 Py_TYPE(deque)->tp_free(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001284}
1285
1286static int
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001287deque_traverse(dequeobject *deque, visitproc visit, void *arg)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001288{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001289 block *b;
1290 PyObject *item;
1291 Py_ssize_t index;
1292 Py_ssize_t indexlo = deque->leftindex;
Raymond Hettinger1286d142015-10-14 23:16:57 -07001293 Py_ssize_t indexhigh;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001294
Raymond Hettinger5bfa8672013-07-06 11:58:09 -10001295 for (b = deque->leftblock; b != deque->rightblock; b = b->rightlink) {
1296 for (index = indexlo; index < BLOCKLEN ; index++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001297 item = b->data[index];
1298 Py_VISIT(item);
1299 }
1300 indexlo = 0;
1301 }
Raymond Hettinger1286d142015-10-14 23:16:57 -07001302 indexhigh = deque->rightindex;
1303 for (index = indexlo; index <= indexhigh; index++) {
Raymond Hettinger5bfa8672013-07-06 11:58:09 -10001304 item = b->data[index];
1305 Py_VISIT(item);
1306 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001307 return 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001308}
1309
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001310static PyObject *
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001311deque_reduce(dequeobject *deque)
1312{
Serhiy Storchakaa0d416f2016-03-06 08:55:21 +02001313 PyObject *dict, *it;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001314 _Py_IDENTIFIER(__dict__);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001315
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001316 if (_PyObject_LookupAttrId((PyObject *)deque, &PyId___dict__, &dict) < 0) {
1317 return NULL;
1318 }
Serhiy Storchakaa0d416f2016-03-06 08:55:21 +02001319 if (dict == NULL) {
Serhiy Storchakaa0d416f2016-03-06 08:55:21 +02001320 dict = Py_None;
1321 Py_INCREF(dict);
1322 }
1323
1324 it = PyObject_GetIter((PyObject *)deque);
1325 if (it == NULL) {
1326 Py_DECREF(dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001327 return NULL;
1328 }
Serhiy Storchakaa0d416f2016-03-06 08:55:21 +02001329
1330 if (deque->maxlen < 0) {
1331 return Py_BuildValue("O()NN", Py_TYPE(deque), dict, it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001332 }
Serhiy Storchakaa0d416f2016-03-06 08:55:21 +02001333 else {
1334 return Py_BuildValue("O(()n)NN", Py_TYPE(deque), deque->maxlen, dict, it);
1335 }
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001336}
1337
1338PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
1339
1340static PyObject *
1341deque_repr(PyObject *deque)
1342{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001343 PyObject *aslist, *result;
1344 int i;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001346 i = Py_ReprEnter(deque);
1347 if (i != 0) {
1348 if (i < 0)
1349 return NULL;
1350 return PyUnicode_FromString("[...]");
1351 }
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001353 aslist = PySequence_List(deque);
1354 if (aslist == NULL) {
1355 Py_ReprLeave(deque);
1356 return NULL;
1357 }
Raymond Hettingera7f630092015-10-10 23:56:02 -04001358 if (((dequeobject *)deque)->maxlen >= 0)
Serhiy Storchakab3a77962017-09-21 14:24:13 +03001359 result = PyUnicode_FromFormat("%s(%R, maxlen=%zd)",
1360 _PyType_Name(Py_TYPE(deque)), aslist,
1361 ((dequeobject *)deque)->maxlen);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001362 else
Serhiy Storchakab3a77962017-09-21 14:24:13 +03001363 result = PyUnicode_FromFormat("%s(%R)",
1364 _PyType_Name(Py_TYPE(deque)), aslist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001365 Py_ReprLeave(deque);
Raymond Hettinger2b2b7532015-09-05 17:05:52 -07001366 Py_DECREF(aslist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001367 return result;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001368}
1369
Raymond Hettinger738ec902004-02-29 02:15:56 +00001370static PyObject *
1371deque_richcompare(PyObject *v, PyObject *w, int op)
1372{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001373 PyObject *it1=NULL, *it2=NULL, *x, *y;
1374 Py_ssize_t vs, ws;
1375 int b, cmp=-1;
Raymond Hettinger738ec902004-02-29 02:15:56 +00001376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001377 if (!PyObject_TypeCheck(v, &deque_type) ||
1378 !PyObject_TypeCheck(w, &deque_type)) {
Brian Curtindfc80e32011-08-10 20:28:54 -05001379 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001380 }
Raymond Hettinger738ec902004-02-29 02:15:56 +00001381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001382 /* Shortcuts */
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001383 vs = Py_SIZE((dequeobject *)v);
1384 ws = Py_SIZE((dequeobject *)w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001385 if (op == Py_EQ) {
1386 if (v == w)
1387 Py_RETURN_TRUE;
1388 if (vs != ws)
1389 Py_RETURN_FALSE;
1390 }
1391 if (op == Py_NE) {
1392 if (v == w)
1393 Py_RETURN_FALSE;
1394 if (vs != ws)
1395 Py_RETURN_TRUE;
1396 }
Raymond Hettinger738ec902004-02-29 02:15:56 +00001397
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001398 /* Search for the first index where items are different */
1399 it1 = PyObject_GetIter(v);
1400 if (it1 == NULL)
1401 goto done;
1402 it2 = PyObject_GetIter(w);
1403 if (it2 == NULL)
1404 goto done;
1405 for (;;) {
1406 x = PyIter_Next(it1);
1407 if (x == NULL && PyErr_Occurred())
1408 goto done;
1409 y = PyIter_Next(it2);
1410 if (x == NULL || y == NULL)
1411 break;
1412 b = PyObject_RichCompareBool(x, y, Py_EQ);
1413 if (b == 0) {
1414 cmp = PyObject_RichCompareBool(x, y, op);
1415 Py_DECREF(x);
1416 Py_DECREF(y);
1417 goto done;
1418 }
1419 Py_DECREF(x);
1420 Py_DECREF(y);
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -07001421 if (b < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001422 goto done;
1423 }
1424 /* We reached the end of one deque or both */
1425 Py_XDECREF(x);
1426 Py_XDECREF(y);
1427 if (PyErr_Occurred())
1428 goto done;
1429 switch (op) {
1430 case Py_LT: cmp = y != NULL; break; /* if w was longer */
1431 case Py_LE: cmp = x == NULL; break; /* if v was not longer */
1432 case Py_EQ: cmp = x == y; break; /* if we reached the end of both */
1433 case Py_NE: cmp = x != y; break; /* if one deque continues */
1434 case Py_GT: cmp = x != NULL; break; /* if v was longer */
1435 case Py_GE: cmp = y == NULL; break; /* if w was not longer */
1436 }
Tim Peters1065f752004-10-01 01:03:29 +00001437
Raymond Hettinger738ec902004-02-29 02:15:56 +00001438done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001439 Py_XDECREF(it1);
1440 Py_XDECREF(it2);
1441 if (cmp == 1)
1442 Py_RETURN_TRUE;
1443 if (cmp == 0)
1444 Py_RETURN_FALSE;
1445 return NULL;
Raymond Hettinger738ec902004-02-29 02:15:56 +00001446}
1447
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001448static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001449deque_init(dequeobject *deque, PyObject *args, PyObject *kwdargs)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001450{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001451 PyObject *iterable = NULL;
1452 PyObject *maxlenobj = NULL;
1453 Py_ssize_t maxlen = -1;
1454 char *kwlist[] = {"iterable", "maxlen", 0};
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001455
Raymond Hettinger0d309402015-09-30 23:15:02 -07001456 if (kwdargs == NULL) {
1457 if (!PyArg_UnpackTuple(args, "deque()", 0, 2, &iterable, &maxlenobj))
1458 return -1;
1459 } else {
1460 if (!PyArg_ParseTupleAndKeywords(args, kwdargs, "|OO:deque", kwlist,
1461 &iterable, &maxlenobj))
1462 return -1;
1463 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001464 if (maxlenobj != NULL && maxlenobj != Py_None) {
1465 maxlen = PyLong_AsSsize_t(maxlenobj);
1466 if (maxlen == -1 && PyErr_Occurred())
1467 return -1;
1468 if (maxlen < 0) {
1469 PyErr_SetString(PyExc_ValueError, "maxlen must be non-negative");
1470 return -1;
1471 }
1472 }
1473 deque->maxlen = maxlen;
Raymond Hettinger0d309402015-09-30 23:15:02 -07001474 if (Py_SIZE(deque) > 0)
1475 deque_clear(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001476 if (iterable != NULL) {
1477 PyObject *rv = deque_extend(deque, iterable);
1478 if (rv == NULL)
1479 return -1;
1480 Py_DECREF(rv);
1481 }
1482 return 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001483}
1484
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001485static PyObject *
Jesus Cea16e2fca2012-08-03 14:49:42 +02001486deque_sizeof(dequeobject *deque, void *unused)
1487{
1488 Py_ssize_t res;
1489 Py_ssize_t blocks;
1490
Serhiy Storchaka5c4064e2015-12-19 20:05:25 +02001491 res = _PyObject_SIZE(Py_TYPE(deque));
Raymond Hettingerbc003412015-10-14 23:33:23 -07001492 blocks = (size_t)(deque->leftindex + Py_SIZE(deque) + BLOCKLEN - 1) / BLOCKLEN;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001493 assert(deque->leftindex + Py_SIZE(deque) - 1 ==
Jesus Cea16e2fca2012-08-03 14:49:42 +02001494 (blocks - 1) * BLOCKLEN + deque->rightindex);
1495 res += blocks * sizeof(block);
1496 return PyLong_FromSsize_t(res);
1497}
1498
1499PyDoc_STRVAR(sizeof_doc,
1500"D.__sizeof__() -- size of D in memory, in bytes");
1501
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001502static int
1503deque_bool(dequeobject *deque)
1504{
1505 return Py_SIZE(deque) != 0;
1506}
1507
Jesus Cea16e2fca2012-08-03 14:49:42 +02001508static PyObject *
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001509deque_get_maxlen(dequeobject *deque)
1510{
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -07001511 if (deque->maxlen < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001512 Py_RETURN_NONE;
1513 return PyLong_FromSsize_t(deque->maxlen);
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001514}
1515
Raymond Hettinger41290a62015-03-31 08:12:23 -07001516
1517/* deque object ********************************************************/
1518
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001519static PyGetSetDef deque_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001520 {"maxlen", (getter)deque_get_maxlen, (setter)NULL,
1521 "maximum size of a deque or None if unbounded"},
1522 {0}
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001523};
1524
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001525static PySequenceMethods deque_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001526 (lenfunc)deque_len, /* sq_length */
Raymond Hettinger41290a62015-03-31 08:12:23 -07001527 (binaryfunc)deque_concat, /* sq_concat */
1528 (ssizeargfunc)deque_repeat, /* sq_repeat */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001529 (ssizeargfunc)deque_item, /* sq_item */
1530 0, /* sq_slice */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001531 (ssizeobjargproc)deque_ass_item, /* sq_ass_item */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001532 0, /* sq_ass_slice */
Raymond Hettinger39dadf72015-03-20 16:38:56 -07001533 (objobjproc)deque_contains, /* sq_contains */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001534 (binaryfunc)deque_inplace_concat, /* sq_inplace_concat */
Raymond Hettinger41290a62015-03-31 08:12:23 -07001535 (ssizeargfunc)deque_inplace_repeat, /* sq_inplace_repeat */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001536};
1537
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001538static PyNumberMethods deque_as_number = {
1539 0, /* nb_add */
1540 0, /* nb_subtract */
1541 0, /* nb_multiply */
1542 0, /* nb_remainder */
1543 0, /* nb_divmod */
1544 0, /* nb_power */
1545 0, /* nb_negative */
1546 0, /* nb_positive */
1547 0, /* nb_absolute */
1548 (inquiry)deque_bool, /* nb_bool */
1549 0, /* nb_invert */
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001550 };
1551
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001552static PyObject *deque_iter(dequeobject *deque);
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301553static PyObject *deque_reviter(dequeobject *deque, PyObject *Py_UNUSED(ignored));
Tim Peters1065f752004-10-01 01:03:29 +00001554PyDoc_STRVAR(reversed_doc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001555 "D.__reversed__() -- return a reverse iterator over the deque");
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001556
1557static PyMethodDef deque_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001558 {"append", (PyCFunction)deque_append,
1559 METH_O, append_doc},
1560 {"appendleft", (PyCFunction)deque_appendleft,
1561 METH_O, appendleft_doc},
1562 {"clear", (PyCFunction)deque_clearmethod,
1563 METH_NOARGS, clear_doc},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301564 {"__copy__", deque_copy,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001565 METH_NOARGS, copy_doc},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301566 {"copy", deque_copy,
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001567 METH_NOARGS, copy_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001568 {"count", (PyCFunction)deque_count,
Raymond Hettinger0f6f9472015-03-21 01:42:10 -07001569 METH_O, count_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001570 {"extend", (PyCFunction)deque_extend,
1571 METH_O, extend_doc},
1572 {"extendleft", (PyCFunction)deque_extendleft,
1573 METH_O, extendleft_doc},
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001574 {"index", (PyCFunction)deque_index,
Victor Stinnerdd407d52017-02-06 16:06:49 +01001575 METH_FASTCALL, index_doc},
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001576 {"insert", (PyCFunction)deque_insert,
Victor Stinnerdd407d52017-02-06 16:06:49 +01001577 METH_FASTCALL, insert_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001578 {"pop", (PyCFunction)deque_pop,
1579 METH_NOARGS, pop_doc},
1580 {"popleft", (PyCFunction)deque_popleft,
1581 METH_NOARGS, popleft_doc},
Raymond Hettinger0f6f9472015-03-21 01:42:10 -07001582 {"__reduce__", (PyCFunction)deque_reduce,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001583 METH_NOARGS, reduce_doc},
1584 {"remove", (PyCFunction)deque_remove,
1585 METH_O, remove_doc},
1586 {"__reversed__", (PyCFunction)deque_reviter,
1587 METH_NOARGS, reversed_doc},
1588 {"reverse", (PyCFunction)deque_reverse,
1589 METH_NOARGS, reverse_doc},
1590 {"rotate", (PyCFunction)deque_rotate,
Victor Stinnerdd407d52017-02-06 16:06:49 +01001591 METH_FASTCALL, rotate_doc},
Jesus Cea16e2fca2012-08-03 14:49:42 +02001592 {"__sizeof__", (PyCFunction)deque_sizeof,
1593 METH_NOARGS, sizeof_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001594 {NULL, NULL} /* sentinel */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001595};
1596
1597PyDoc_STRVAR(deque_doc,
Andrew Svetlov6a5c7c32012-10-31 11:50:40 +02001598"deque([iterable[, maxlen]]) --> deque object\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001599\n\
Raymond Hettinger41290a62015-03-31 08:12:23 -07001600A list-like sequence optimized for data accesses near its endpoints.");
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001601
Neal Norwitz87f10132004-02-29 15:40:53 +00001602static PyTypeObject deque_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001603 PyVarObject_HEAD_INIT(NULL, 0)
1604 "collections.deque", /* tp_name */
1605 sizeof(dequeobject), /* tp_basicsize */
1606 0, /* tp_itemsize */
1607 /* methods */
1608 (destructor)deque_dealloc, /* tp_dealloc */
1609 0, /* tp_print */
1610 0, /* tp_getattr */
1611 0, /* tp_setattr */
1612 0, /* tp_reserved */
1613 deque_repr, /* tp_repr */
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001614 &deque_as_number, /* tp_as_number */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001615 &deque_as_sequence, /* tp_as_sequence */
1616 0, /* tp_as_mapping */
Georg Brandlf038b322010-10-18 07:35:09 +00001617 PyObject_HashNotImplemented, /* tp_hash */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001618 0, /* tp_call */
1619 0, /* tp_str */
1620 PyObject_GenericGetAttr, /* tp_getattro */
1621 0, /* tp_setattro */
1622 0, /* tp_as_buffer */
1623 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
Georg Brandlf038b322010-10-18 07:35:09 +00001624 /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001625 deque_doc, /* tp_doc */
1626 (traverseproc)deque_traverse, /* tp_traverse */
1627 (inquiry)deque_clear, /* tp_clear */
1628 (richcmpfunc)deque_richcompare, /* tp_richcompare */
Georg Brandlf038b322010-10-18 07:35:09 +00001629 offsetof(dequeobject, weakreflist), /* tp_weaklistoffset*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001630 (getiterfunc)deque_iter, /* tp_iter */
1631 0, /* tp_iternext */
1632 deque_methods, /* tp_methods */
1633 0, /* tp_members */
Georg Brandlf038b322010-10-18 07:35:09 +00001634 deque_getset, /* tp_getset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001635 0, /* tp_base */
1636 0, /* tp_dict */
1637 0, /* tp_descr_get */
1638 0, /* tp_descr_set */
1639 0, /* tp_dictoffset */
1640 (initproc)deque_init, /* tp_init */
1641 PyType_GenericAlloc, /* tp_alloc */
1642 deque_new, /* tp_new */
1643 PyObject_GC_Del, /* tp_free */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001644};
1645
1646/*********************** Deque Iterator **************************/
1647
1648typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001649 PyObject_HEAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001650 block *b;
Raymond Hettinger87e69122015-03-02 23:32:02 -08001651 Py_ssize_t index;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001652 dequeobject *deque;
Raymond Hettingerf9d9c792015-03-02 22:47:46 -08001653 size_t state; /* state when the iterator is created */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001654 Py_ssize_t counter; /* number of items remaining for iteration */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001655} dequeiterobject;
1656
Martin v. Löwis59683e82008-06-13 07:50:45 +00001657static PyTypeObject dequeiter_type;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001658
1659static PyObject *
1660deque_iter(dequeobject *deque)
1661{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001662 dequeiterobject *it;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001663
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001664 it = PyObject_GC_New(dequeiterobject, &dequeiter_type);
1665 if (it == NULL)
1666 return NULL;
1667 it->b = deque->leftblock;
1668 it->index = deque->leftindex;
1669 Py_INCREF(deque);
1670 it->deque = deque;
1671 it->state = deque->state;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001672 it->counter = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001673 PyObject_GC_Track(it);
1674 return (PyObject *)it;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001675}
1676
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001677static int
1678dequeiter_traverse(dequeiterobject *dio, visitproc visit, void *arg)
1679{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001680 Py_VISIT(dio->deque);
1681 return 0;
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001682}
1683
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001684static void
1685dequeiter_dealloc(dequeiterobject *dio)
1686{
INADA Naokia6296d32017-08-24 14:55:17 +09001687 /* bpo-31095: UnTrack is needed before calling any callbacks */
1688 PyObject_GC_UnTrack(dio);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001689 Py_XDECREF(dio->deque);
1690 PyObject_GC_Del(dio);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001691}
1692
1693static PyObject *
1694dequeiter_next(dequeiterobject *it)
1695{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001696 PyObject *item;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001697
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001698 if (it->deque->state != it->state) {
1699 it->counter = 0;
1700 PyErr_SetString(PyExc_RuntimeError,
1701 "deque mutated during iteration");
1702 return NULL;
1703 }
1704 if (it->counter == 0)
1705 return NULL;
1706 assert (!(it->b == it->deque->rightblock &&
1707 it->index > it->deque->rightindex));
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001709 item = it->b->data[it->index];
1710 it->index++;
1711 it->counter--;
1712 if (it->index == BLOCKLEN && it->counter > 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -10001713 CHECK_NOT_END(it->b->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001714 it->b = it->b->rightlink;
1715 it->index = 0;
1716 }
1717 Py_INCREF(item);
1718 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001719}
1720
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001721static PyObject *
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001722dequeiter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1723{
1724 Py_ssize_t i, index=0;
1725 PyObject *deque;
1726 dequeiterobject *it;
1727 if (!PyArg_ParseTuple(args, "O!|n", &deque_type, &deque, &index))
1728 return NULL;
1729 assert(type == &dequeiter_type);
1730
1731 it = (dequeiterobject*)deque_iter((dequeobject *)deque);
1732 if (!it)
1733 return NULL;
1734 /* consume items from the queue */
1735 for(i=0; i<index; i++) {
1736 PyObject *item = dequeiter_next(it);
1737 if (item) {
1738 Py_DECREF(item);
1739 } else {
1740 if (it->counter) {
1741 Py_DECREF(it);
1742 return NULL;
1743 } else
1744 break;
1745 }
1746 }
1747 return (PyObject*)it;
1748}
1749
1750static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301751dequeiter_len(dequeiterobject *it, PyObject *Py_UNUSED(ignored))
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001752{
Antoine Pitrou554f3342010-08-17 18:30:06 +00001753 return PyLong_FromSsize_t(it->counter);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001754}
1755
Armin Rigof5b3e362006-02-11 21:32:43 +00001756PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001757
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001758static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301759dequeiter_reduce(dequeiterobject *it, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001760{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001761 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 +00001762}
1763
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001764static PyMethodDef dequeiter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001765 {"__length_hint__", (PyCFunction)dequeiter_len, METH_NOARGS, length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001766 {"__reduce__", (PyCFunction)dequeiter_reduce, METH_NOARGS, reduce_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001767 {NULL, NULL} /* sentinel */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001768};
1769
Martin v. Löwis59683e82008-06-13 07:50:45 +00001770static PyTypeObject dequeiter_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001771 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger87e69122015-03-02 23:32:02 -08001772 "_collections._deque_iterator", /* tp_name */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001773 sizeof(dequeiterobject), /* tp_basicsize */
1774 0, /* tp_itemsize */
1775 /* methods */
1776 (destructor)dequeiter_dealloc, /* tp_dealloc */
1777 0, /* tp_print */
1778 0, /* tp_getattr */
1779 0, /* tp_setattr */
1780 0, /* tp_reserved */
1781 0, /* tp_repr */
1782 0, /* tp_as_number */
1783 0, /* tp_as_sequence */
1784 0, /* tp_as_mapping */
1785 0, /* tp_hash */
1786 0, /* tp_call */
1787 0, /* tp_str */
1788 PyObject_GenericGetAttr, /* tp_getattro */
1789 0, /* tp_setattro */
1790 0, /* tp_as_buffer */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001791 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001792 0, /* tp_doc */
1793 (traverseproc)dequeiter_traverse, /* tp_traverse */
1794 0, /* tp_clear */
1795 0, /* tp_richcompare */
1796 0, /* tp_weaklistoffset */
1797 PyObject_SelfIter, /* tp_iter */
1798 (iternextfunc)dequeiter_next, /* tp_iternext */
1799 dequeiter_methods, /* tp_methods */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001800 0, /* tp_members */
1801 0, /* tp_getset */
1802 0, /* tp_base */
1803 0, /* tp_dict */
1804 0, /* tp_descr_get */
1805 0, /* tp_descr_set */
1806 0, /* tp_dictoffset */
1807 0, /* tp_init */
1808 0, /* tp_alloc */
1809 dequeiter_new, /* tp_new */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001810 0,
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001811};
1812
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001813/*********************** Deque Reverse Iterator **************************/
1814
Martin v. Löwis59683e82008-06-13 07:50:45 +00001815static PyTypeObject dequereviter_type;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001816
1817static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301818deque_reviter(dequeobject *deque, PyObject *Py_UNUSED(ignored))
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001819{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001820 dequeiterobject *it;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001821
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001822 it = PyObject_GC_New(dequeiterobject, &dequereviter_type);
1823 if (it == NULL)
1824 return NULL;
1825 it->b = deque->rightblock;
1826 it->index = deque->rightindex;
1827 Py_INCREF(deque);
1828 it->deque = deque;
1829 it->state = deque->state;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001830 it->counter = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001831 PyObject_GC_Track(it);
1832 return (PyObject *)it;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001833}
1834
1835static PyObject *
1836dequereviter_next(dequeiterobject *it)
1837{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001838 PyObject *item;
1839 if (it->counter == 0)
1840 return NULL;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001841
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001842 if (it->deque->state != it->state) {
1843 it->counter = 0;
1844 PyErr_SetString(PyExc_RuntimeError,
1845 "deque mutated during iteration");
1846 return NULL;
1847 }
1848 assert (!(it->b == it->deque->leftblock &&
1849 it->index < it->deque->leftindex));
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001850
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001851 item = it->b->data[it->index];
1852 it->index--;
1853 it->counter--;
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -07001854 if (it->index < 0 && it->counter > 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -10001855 CHECK_NOT_END(it->b->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001856 it->b = it->b->leftlink;
1857 it->index = BLOCKLEN - 1;
1858 }
1859 Py_INCREF(item);
1860 return item;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001861}
1862
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001863static PyObject *
1864dequereviter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1865{
1866 Py_ssize_t i, index=0;
1867 PyObject *deque;
1868 dequeiterobject *it;
1869 if (!PyArg_ParseTuple(args, "O!|n", &deque_type, &deque, &index))
1870 return NULL;
1871 assert(type == &dequereviter_type);
1872
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301873 it = (dequeiterobject*)deque_reviter((dequeobject *)deque, NULL);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001874 if (!it)
1875 return NULL;
1876 /* consume items from the queue */
1877 for(i=0; i<index; i++) {
1878 PyObject *item = dequereviter_next(it);
1879 if (item) {
1880 Py_DECREF(item);
1881 } else {
1882 if (it->counter) {
1883 Py_DECREF(it);
1884 return NULL;
1885 } else
1886 break;
1887 }
1888 }
1889 return (PyObject*)it;
1890}
1891
Martin v. Löwis59683e82008-06-13 07:50:45 +00001892static PyTypeObject dequereviter_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001893 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger87e69122015-03-02 23:32:02 -08001894 "_collections._deque_reverse_iterator", /* tp_name */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001895 sizeof(dequeiterobject), /* tp_basicsize */
1896 0, /* tp_itemsize */
1897 /* methods */
1898 (destructor)dequeiter_dealloc, /* tp_dealloc */
1899 0, /* tp_print */
1900 0, /* tp_getattr */
1901 0, /* tp_setattr */
1902 0, /* tp_reserved */
1903 0, /* tp_repr */
1904 0, /* tp_as_number */
1905 0, /* tp_as_sequence */
1906 0, /* tp_as_mapping */
1907 0, /* tp_hash */
1908 0, /* tp_call */
1909 0, /* tp_str */
1910 PyObject_GenericGetAttr, /* tp_getattro */
1911 0, /* tp_setattro */
1912 0, /* tp_as_buffer */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001913 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001914 0, /* tp_doc */
1915 (traverseproc)dequeiter_traverse, /* tp_traverse */
1916 0, /* tp_clear */
1917 0, /* tp_richcompare */
1918 0, /* tp_weaklistoffset */
1919 PyObject_SelfIter, /* tp_iter */
1920 (iternextfunc)dequereviter_next, /* tp_iternext */
1921 dequeiter_methods, /* tp_methods */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001922 0, /* tp_members */
1923 0, /* tp_getset */
1924 0, /* tp_base */
1925 0, /* tp_dict */
1926 0, /* tp_descr_get */
1927 0, /* tp_descr_set */
1928 0, /* tp_dictoffset */
1929 0, /* tp_init */
1930 0, /* tp_alloc */
1931 dequereviter_new, /* tp_new */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001932 0,
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001933};
1934
Guido van Rossum1968ad32006-02-25 22:38:04 +00001935/* defaultdict type *********************************************************/
1936
1937typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001938 PyDictObject dict;
1939 PyObject *default_factory;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001940} defdictobject;
1941
1942static PyTypeObject defdict_type; /* Forward */
1943
1944PyDoc_STRVAR(defdict_missing_doc,
1945"__missing__(key) # Called by __getitem__ for missing key; pseudo-code:\n\
Guido van Rossumd8faa362007-04-27 19:54:29 +00001946 if self.default_factory is None: raise KeyError((key,))\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00001947 self[key] = value = self.default_factory()\n\
1948 return value\n\
1949");
1950
1951static PyObject *
1952defdict_missing(defdictobject *dd, PyObject *key)
1953{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001954 PyObject *factory = dd->default_factory;
1955 PyObject *value;
1956 if (factory == NULL || factory == Py_None) {
1957 /* XXX Call dict.__missing__(key) */
1958 PyObject *tup;
1959 tup = PyTuple_Pack(1, key);
1960 if (!tup) return NULL;
1961 PyErr_SetObject(PyExc_KeyError, tup);
1962 Py_DECREF(tup);
1963 return NULL;
1964 }
1965 value = PyEval_CallObject(factory, NULL);
1966 if (value == NULL)
1967 return value;
1968 if (PyObject_SetItem((PyObject *)dd, key, value) < 0) {
1969 Py_DECREF(value);
1970 return NULL;
1971 }
1972 return value;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001973}
1974
1975PyDoc_STRVAR(defdict_copy_doc, "D.copy() -> a shallow copy of D.");
1976
1977static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301978defdict_copy(defdictobject *dd, PyObject *Py_UNUSED(ignored))
Guido van Rossum1968ad32006-02-25 22:38:04 +00001979{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001980 /* This calls the object's class. That only works for subclasses
1981 whose class constructor has the same signature. Subclasses that
1982 define a different constructor signature must override copy().
1983 */
Raymond Hettinger54628fa2009-08-04 19:16:39 +00001984
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001985 if (dd->default_factory == NULL)
1986 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd), Py_None, dd, NULL);
1987 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd),
1988 dd->default_factory, dd, NULL);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001989}
1990
1991static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301992defdict_reduce(defdictobject *dd, PyObject *Py_UNUSED(ignored))
Guido van Rossum1968ad32006-02-25 22:38:04 +00001993{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001994 /* __reduce__ must return a 5-tuple as follows:
Guido van Rossum1968ad32006-02-25 22:38:04 +00001995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001996 - factory function
1997 - tuple of args for the factory function
1998 - additional state (here None)
1999 - sequence iterator (here None)
2000 - dictionary iterator (yielding successive (key, value) pairs
Guido van Rossum1968ad32006-02-25 22:38:04 +00002001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002002 This API is used by pickle.py and copy.py.
Guido van Rossum1968ad32006-02-25 22:38:04 +00002003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002004 For this to be useful with pickle.py, the default_factory
2005 must be picklable; e.g., None, a built-in, or a global
2006 function in a module or package.
Guido van Rossum1968ad32006-02-25 22:38:04 +00002007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002008 Both shallow and deep copying are supported, but for deep
2009 copying, the default_factory must be deep-copyable; e.g. None,
2010 or a built-in (functions are not copyable at this time).
Guido van Rossum1968ad32006-02-25 22:38:04 +00002011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002012 This only works for subclasses as long as their constructor
2013 signature is compatible; the first argument must be the
2014 optional default_factory, defaulting to None.
2015 */
2016 PyObject *args;
2017 PyObject *items;
2018 PyObject *iter;
2019 PyObject *result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002020 _Py_IDENTIFIER(items);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002022 if (dd->default_factory == NULL || dd->default_factory == Py_None)
2023 args = PyTuple_New(0);
2024 else
2025 args = PyTuple_Pack(1, dd->default_factory);
2026 if (args == NULL)
2027 return NULL;
Victor Stinnerad8c83a2016-09-05 17:53:15 -07002028 items = _PyObject_CallMethodId((PyObject *)dd, &PyId_items, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002029 if (items == NULL) {
2030 Py_DECREF(args);
2031 return NULL;
2032 }
2033 iter = PyObject_GetIter(items);
2034 if (iter == NULL) {
2035 Py_DECREF(items);
2036 Py_DECREF(args);
2037 return NULL;
2038 }
2039 result = PyTuple_Pack(5, Py_TYPE(dd), args,
2040 Py_None, Py_None, iter);
2041 Py_DECREF(iter);
2042 Py_DECREF(items);
2043 Py_DECREF(args);
2044 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00002045}
2046
2047static PyMethodDef defdict_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002048 {"__missing__", (PyCFunction)defdict_missing, METH_O,
2049 defdict_missing_doc},
2050 {"copy", (PyCFunction)defdict_copy, METH_NOARGS,
2051 defdict_copy_doc},
2052 {"__copy__", (PyCFunction)defdict_copy, METH_NOARGS,
2053 defdict_copy_doc},
2054 {"__reduce__", (PyCFunction)defdict_reduce, METH_NOARGS,
2055 reduce_doc},
2056 {NULL}
Guido van Rossum1968ad32006-02-25 22:38:04 +00002057};
2058
2059static PyMemberDef defdict_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002060 {"default_factory", T_OBJECT,
2061 offsetof(defdictobject, default_factory), 0,
2062 PyDoc_STR("Factory for default value called by __missing__().")},
2063 {NULL}
Guido van Rossum1968ad32006-02-25 22:38:04 +00002064};
2065
2066static void
2067defdict_dealloc(defdictobject *dd)
2068{
INADA Naokia6296d32017-08-24 14:55:17 +09002069 /* bpo-31095: UnTrack is needed before calling any callbacks */
2070 PyObject_GC_UnTrack(dd);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002071 Py_CLEAR(dd->default_factory);
2072 PyDict_Type.tp_dealloc((PyObject *)dd);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002073}
2074
Guido van Rossum1968ad32006-02-25 22:38:04 +00002075static PyObject *
2076defdict_repr(defdictobject *dd)
2077{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002078 PyObject *baserepr;
2079 PyObject *defrepr;
2080 PyObject *result;
2081 baserepr = PyDict_Type.tp_repr((PyObject *)dd);
2082 if (baserepr == NULL)
2083 return NULL;
2084 if (dd->default_factory == NULL)
2085 defrepr = PyUnicode_FromString("None");
2086 else
2087 {
2088 int status = Py_ReprEnter(dd->default_factory);
2089 if (status != 0) {
Antoine Pitrouf5f1fe02012-02-15 02:42:46 +01002090 if (status < 0) {
2091 Py_DECREF(baserepr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002092 return NULL;
Antoine Pitrouf5f1fe02012-02-15 02:42:46 +01002093 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002094 defrepr = PyUnicode_FromString("...");
2095 }
2096 else
2097 defrepr = PyObject_Repr(dd->default_factory);
2098 Py_ReprLeave(dd->default_factory);
2099 }
2100 if (defrepr == NULL) {
2101 Py_DECREF(baserepr);
2102 return NULL;
2103 }
Serhiy Storchakab3a77962017-09-21 14:24:13 +03002104 result = PyUnicode_FromFormat("%s(%U, %U)",
2105 _PyType_Name(Py_TYPE(dd)),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002106 defrepr, baserepr);
2107 Py_DECREF(defrepr);
2108 Py_DECREF(baserepr);
2109 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00002110}
2111
2112static int
2113defdict_traverse(PyObject *self, visitproc visit, void *arg)
2114{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002115 Py_VISIT(((defdictobject *)self)->default_factory);
2116 return PyDict_Type.tp_traverse(self, visit, arg);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002117}
2118
2119static int
2120defdict_tp_clear(defdictobject *dd)
2121{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002122 Py_CLEAR(dd->default_factory);
2123 return PyDict_Type.tp_clear((PyObject *)dd);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002124}
2125
2126static int
2127defdict_init(PyObject *self, PyObject *args, PyObject *kwds)
2128{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002129 defdictobject *dd = (defdictobject *)self;
2130 PyObject *olddefault = dd->default_factory;
2131 PyObject *newdefault = NULL;
2132 PyObject *newargs;
2133 int result;
2134 if (args == NULL || !PyTuple_Check(args))
2135 newargs = PyTuple_New(0);
2136 else {
2137 Py_ssize_t n = PyTuple_GET_SIZE(args);
2138 if (n > 0) {
2139 newdefault = PyTuple_GET_ITEM(args, 0);
2140 if (!PyCallable_Check(newdefault) && newdefault != Py_None) {
2141 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger239aba72015-07-20 03:09:22 -04002142 "first argument must be callable or None");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002143 return -1;
2144 }
2145 }
2146 newargs = PySequence_GetSlice(args, 1, n);
2147 }
2148 if (newargs == NULL)
2149 return -1;
2150 Py_XINCREF(newdefault);
2151 dd->default_factory = newdefault;
2152 result = PyDict_Type.tp_init(self, newargs, kwds);
2153 Py_DECREF(newargs);
2154 Py_XDECREF(olddefault);
2155 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00002156}
2157
2158PyDoc_STRVAR(defdict_doc,
Benjamin Peterson9cb33b72014-01-13 23:56:05 -05002159"defaultdict(default_factory[, ...]) --> dict with default factory\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00002160\n\
2161The default factory is called without arguments to produce\n\
2162a new value when a key is not present, in __getitem__ only.\n\
2163A defaultdict compares equal to a dict with the same items.\n\
Benjamin Peterson9cb33b72014-01-13 23:56:05 -05002164All remaining arguments are treated the same as if they were\n\
2165passed to the dict constructor, including keyword arguments.\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00002166");
2167
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002168/* See comment in xxsubtype.c */
2169#define DEFERRED_ADDRESS(ADDR) 0
2170
Guido van Rossum1968ad32006-02-25 22:38:04 +00002171static PyTypeObject defdict_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002172 PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0)
2173 "collections.defaultdict", /* tp_name */
2174 sizeof(defdictobject), /* tp_basicsize */
2175 0, /* tp_itemsize */
2176 /* methods */
2177 (destructor)defdict_dealloc, /* tp_dealloc */
2178 0, /* tp_print */
2179 0, /* tp_getattr */
2180 0, /* tp_setattr */
2181 0, /* tp_reserved */
2182 (reprfunc)defdict_repr, /* tp_repr */
2183 0, /* tp_as_number */
2184 0, /* tp_as_sequence */
2185 0, /* tp_as_mapping */
2186 0, /* tp_hash */
2187 0, /* tp_call */
2188 0, /* tp_str */
2189 PyObject_GenericGetAttr, /* tp_getattro */
2190 0, /* tp_setattro */
2191 0, /* tp_as_buffer */
2192 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
2193 /* tp_flags */
2194 defdict_doc, /* tp_doc */
2195 defdict_traverse, /* tp_traverse */
2196 (inquiry)defdict_tp_clear, /* tp_clear */
2197 0, /* tp_richcompare */
2198 0, /* tp_weaklistoffset*/
2199 0, /* tp_iter */
2200 0, /* tp_iternext */
2201 defdict_methods, /* tp_methods */
2202 defdict_members, /* tp_members */
2203 0, /* tp_getset */
2204 DEFERRED_ADDRESS(&PyDict_Type), /* tp_base */
2205 0, /* tp_dict */
2206 0, /* tp_descr_get */
2207 0, /* tp_descr_set */
2208 0, /* tp_dictoffset */
2209 defdict_init, /* tp_init */
2210 PyType_GenericAlloc, /* tp_alloc */
2211 0, /* tp_new */
2212 PyObject_GC_Del, /* tp_free */
Guido van Rossum1968ad32006-02-25 22:38:04 +00002213};
2214
Raymond Hettinger96f34102010-12-15 16:30:37 +00002215/* helper function for Counter *********************************************/
2216
2217PyDoc_STRVAR(_count_elements_doc,
2218"_count_elements(mapping, iterable) -> None\n\
2219\n\
Raymond Hettingera24dca62017-01-12 22:25:25 -08002220Count elements in the iterable, updating the mapping");
Raymond Hettinger96f34102010-12-15 16:30:37 +00002221
2222static PyObject *
2223_count_elements(PyObject *self, PyObject *args)
2224{
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002225 _Py_IDENTIFIER(get);
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002226 _Py_IDENTIFIER(__setitem__);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002227 PyObject *it, *iterable, *mapping, *oldval;
2228 PyObject *newval = NULL;
2229 PyObject *key = NULL;
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002230 PyObject *bound_get = NULL;
2231 PyObject *mapping_get;
2232 PyObject *dict_get;
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002233 PyObject *mapping_setitem;
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002234 PyObject *dict_setitem;
Raymond Hettinger96f34102010-12-15 16:30:37 +00002235
2236 if (!PyArg_UnpackTuple(args, "_count_elements", 2, 2, &mapping, &iterable))
2237 return NULL;
2238
Raymond Hettinger96f34102010-12-15 16:30:37 +00002239 it = PyObject_GetIter(iterable);
2240 if (it == NULL)
2241 return NULL;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002242
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002243 /* Only take the fast path when get() and __setitem__()
2244 * have not been overridden.
2245 */
2246 mapping_get = _PyType_LookupId(Py_TYPE(mapping), &PyId_get);
2247 dict_get = _PyType_LookupId(&PyDict_Type, &PyId_get);
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002248 mapping_setitem = _PyType_LookupId(Py_TYPE(mapping), &PyId___setitem__);
2249 dict_setitem = _PyType_LookupId(&PyDict_Type, &PyId___setitem__);
2250
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002251 if (mapping_get != NULL && mapping_get == dict_get &&
Oren Milman31aca4b2017-09-27 06:18:21 +03002252 mapping_setitem != NULL && mapping_setitem == dict_setitem &&
2253 PyDict_Check(mapping))
2254 {
Raymond Hettinger426e0522011-01-03 02:12:02 +00002255 while (1) {
Raymond Hettinger507d9972014-05-18 21:32:40 +01002256 /* Fast path advantages:
2257 1. Eliminate double hashing
2258 (by re-using the same hash for both the get and set)
2259 2. Avoid argument overhead of PyObject_CallFunctionObjArgs
2260 (argument tuple creation and parsing)
2261 3. Avoid indirection through a bound method object
2262 (creates another argument tuple)
2263 4. Avoid initial increment from zero
2264 (reuse an existing one-object instead)
2265 */
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002266 Py_hash_t hash;
2267
Raymond Hettinger426e0522011-01-03 02:12:02 +00002268 key = PyIter_Next(it);
Victor Stinnera154b5c2011-04-20 23:23:52 +02002269 if (key == NULL)
2270 break;
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002271
2272 if (!PyUnicode_CheckExact(key) ||
2273 (hash = ((PyASCIIObject *) key)->hash) == -1)
2274 {
2275 hash = PyObject_Hash(key);
Raymond Hettingerda2850f2015-02-27 12:42:54 -08002276 if (hash == -1)
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002277 goto done;
2278 }
2279
2280 oldval = _PyDict_GetItem_KnownHash(mapping, key, hash);
Raymond Hettinger426e0522011-01-03 02:12:02 +00002281 if (oldval == NULL) {
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02002282 if (PyErr_Occurred())
2283 goto done;
Serhiy Storchakaba85d692017-03-30 09:09:41 +03002284 if (_PyDict_SetItem_KnownHash(mapping, key, _PyLong_One, hash) < 0)
Raymond Hettinger507d9972014-05-18 21:32:40 +01002285 goto done;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002286 } else {
Serhiy Storchakaba85d692017-03-30 09:09:41 +03002287 newval = PyNumber_Add(oldval, _PyLong_One);
Raymond Hettinger426e0522011-01-03 02:12:02 +00002288 if (newval == NULL)
Raymond Hettinger507d9972014-05-18 21:32:40 +01002289 goto done;
Raymond Hettinger28c995d2015-08-14 02:07:41 -07002290 if (_PyDict_SetItem_KnownHash(mapping, key, newval, hash) < 0)
Raymond Hettinger507d9972014-05-18 21:32:40 +01002291 goto done;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002292 Py_CLEAR(newval);
2293 }
2294 Py_DECREF(key);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002295 }
Raymond Hettinger426e0522011-01-03 02:12:02 +00002296 } else {
Victor Stinnere7f516c2013-11-06 23:52:55 +01002297 bound_get = _PyObject_GetAttrId(mapping, &PyId_get);
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002298 if (bound_get == NULL)
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002299 goto done;
2300
Raymond Hettinger426e0522011-01-03 02:12:02 +00002301 while (1) {
2302 key = PyIter_Next(it);
Victor Stinnera154b5c2011-04-20 23:23:52 +02002303 if (key == NULL)
2304 break;
Serhiy Storchakaba85d692017-03-30 09:09:41 +03002305 oldval = PyObject_CallFunctionObjArgs(bound_get, key, _PyLong_Zero, NULL);
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002306 if (oldval == NULL)
2307 break;
Serhiy Storchakaba85d692017-03-30 09:09:41 +03002308 newval = PyNumber_Add(oldval, _PyLong_One);
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002309 Py_DECREF(oldval);
2310 if (newval == NULL)
2311 break;
Raymond Hettinger28c995d2015-08-14 02:07:41 -07002312 if (PyObject_SetItem(mapping, key, newval) < 0)
Raymond Hettinger96f34102010-12-15 16:30:37 +00002313 break;
2314 Py_CLEAR(newval);
Raymond Hettinger426e0522011-01-03 02:12:02 +00002315 Py_DECREF(key);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002316 }
Raymond Hettinger96f34102010-12-15 16:30:37 +00002317 }
Raymond Hettinger426e0522011-01-03 02:12:02 +00002318
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002319done:
Raymond Hettinger96f34102010-12-15 16:30:37 +00002320 Py_DECREF(it);
2321 Py_XDECREF(key);
2322 Py_XDECREF(newval);
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002323 Py_XDECREF(bound_get);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002324 if (PyErr_Occurred())
2325 return NULL;
2326 Py_RETURN_NONE;
2327}
2328
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002329/* module level code ********************************************************/
2330
2331PyDoc_STRVAR(module_doc,
Guido van Rossum1968ad32006-02-25 22:38:04 +00002332"High performance data structures.\n\
2333- deque: ordered collection accessible from endpoints only\n\
2334- defaultdict: dict subclass with a default value factory\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002335");
2336
Raymond Hettinger96f34102010-12-15 16:30:37 +00002337static struct PyMethodDef module_functions[] = {
2338 {"_count_elements", _count_elements, METH_VARARGS, _count_elements_doc},
2339 {NULL, NULL} /* sentinel */
2340};
Martin v. Löwis1a214512008-06-11 05:26:20 +00002341
2342static struct PyModuleDef _collectionsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002343 PyModuleDef_HEAD_INIT,
2344 "_collections",
2345 module_doc,
2346 -1,
Raymond Hettinger96f34102010-12-15 16:30:37 +00002347 module_functions,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002348 NULL,
2349 NULL,
2350 NULL,
2351 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002352};
2353
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002354PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002355PyInit__collections(void)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002356{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002357 PyObject *m;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002359 m = PyModule_Create(&_collectionsmodule);
2360 if (m == NULL)
2361 return NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002363 if (PyType_Ready(&deque_type) < 0)
2364 return NULL;
2365 Py_INCREF(&deque_type);
2366 PyModule_AddObject(m, "deque", (PyObject *)&deque_type);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002368 defdict_type.tp_base = &PyDict_Type;
2369 if (PyType_Ready(&defdict_type) < 0)
2370 return NULL;
2371 Py_INCREF(&defdict_type);
2372 PyModule_AddObject(m, "defaultdict", (PyObject *)&defdict_type);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002373
Eric Snow47db7172015-05-29 22:21:39 -06002374 Py_INCREF(&PyODict_Type);
2375 PyModule_AddObject(m, "OrderedDict", (PyObject *)&PyODict_Type);
2376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002377 if (PyType_Ready(&dequeiter_type) < 0)
2378 return NULL;
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002379 Py_INCREF(&dequeiter_type);
2380 PyModule_AddObject(m, "_deque_iterator", (PyObject *)&dequeiter_type);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002382 if (PyType_Ready(&dequereviter_type) < 0)
2383 return NULL;
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002384 Py_INCREF(&dequereviter_type);
2385 PyModule_AddObject(m, "_deque_reverse_iterator", (PyObject *)&dequereviter_type);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00002386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002387 return m;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002388}