blob: c0448577140220d3f77020b71bda814f787e6721 [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{
481 dequeobject *old_deque = (dequeobject *)deque;
482 if (Py_TYPE(deque) == &deque_type) {
483 dequeobject *new_deque;
484 PyObject *rv;
485
486 new_deque = (dequeobject *)deque_new(&deque_type, (PyObject *)NULL, (PyObject *)NULL);
487 if (new_deque == NULL)
488 return NULL;
489 new_deque->maxlen = old_deque->maxlen;
490 /* Fast path for the deque_repeat() common case where len(deque) == 1 */
Raymond Hettinger0443ac22015-10-05 22:52:37 -0400491 if (Py_SIZE(deque) == 1) {
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700492 PyObject *item = old_deque->leftblock->data[old_deque->leftindex];
493 rv = deque_append(new_deque, item);
494 } else {
495 rv = deque_extend(new_deque, deque);
496 }
497 if (rv != NULL) {
498 Py_DECREF(rv);
499 return (PyObject *)new_deque;
500 }
501 Py_DECREF(new_deque);
502 return NULL;
503 }
504 if (old_deque->maxlen < 0)
Victor Stinner7bfb42d2016-12-05 17:04:32 +0100505 return PyObject_CallFunctionObjArgs((PyObject *)(Py_TYPE(deque)),
506 deque, NULL);
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700507 else
508 return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "Oi",
509 deque, old_deque->maxlen, NULL);
510}
511
512PyDoc_STRVAR(copy_doc, "Return a shallow copy of a deque.");
Raymond Hettinger41290a62015-03-31 08:12:23 -0700513
514static PyObject *
515deque_concat(dequeobject *deque, PyObject *other)
516{
Benjamin Peterson1a629212015-04-04 10:52:36 -0400517 PyObject *new_deque, *result;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700518 int rv;
519
520 rv = PyObject_IsInstance(other, (PyObject *)&deque_type);
521 if (rv <= 0) {
522 if (rv == 0) {
523 PyErr_Format(PyExc_TypeError,
524 "can only concatenate deque (not \"%.200s\") to deque",
525 other->ob_type->tp_name);
526 }
527 return NULL;
528 }
529
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530530 new_deque = deque_copy((PyObject *)deque, NULL);
Raymond Hettinger41290a62015-03-31 08:12:23 -0700531 if (new_deque == NULL)
532 return NULL;
Benjamin Peterson1a629212015-04-04 10:52:36 -0400533 result = deque_extend((dequeobject *)new_deque, other);
534 if (result == NULL) {
535 Py_DECREF(new_deque);
536 return NULL;
537 }
538 Py_DECREF(result);
539 return new_deque;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700540}
541
Serhiy Storchakaa5c42282018-05-31 07:34:34 +0300542static int
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700543deque_clear(dequeobject *deque)
544{
545 block *b;
546 block *prevblock;
547 block *leftblock;
548 Py_ssize_t leftindex;
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800549 Py_ssize_t n, m;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700550 PyObject *item;
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800551 PyObject **itemptr, **limit;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700552
Raymond Hettinger38031142015-09-29 22:45:05 -0700553 if (Py_SIZE(deque) == 0)
Serhiy Storchakaa5c42282018-05-31 07:34:34 +0300554 return 0;
Raymond Hettinger38031142015-09-29 22:45:05 -0700555
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700556 /* During the process of clearing a deque, decrefs can cause the
557 deque to mutate. To avoid fatal confusion, we have to make the
558 deque empty before clearing the blocks and never refer to
559 anything via deque->ref while clearing. (This is the same
560 technique used for clearing lists, sets, and dicts.)
561
562 Making the deque empty requires allocating a new empty block. In
563 the unlikely event that memory is full, we fall back to an
564 alternate method that doesn't require a new block. Repeating
565 pops in a while-loop is slower, possibly re-entrant (and a clever
566 adversary could cause it to never terminate).
567 */
568
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700569 b = newblock();
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700570 if (b == NULL) {
571 PyErr_Clear();
572 goto alternate_method;
573 }
574
575 /* Remember the old size, leftblock, and leftindex */
Raymond Hettinger6f86a332016-03-02 00:30:58 -0800576 n = Py_SIZE(deque);
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700577 leftblock = deque->leftblock;
578 leftindex = deque->leftindex;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700579
580 /* Set the deque to be empty using the newly allocated block */
581 MARK_END(b->leftlink);
582 MARK_END(b->rightlink);
583 Py_SIZE(deque) = 0;
584 deque->leftblock = b;
585 deque->rightblock = b;
586 deque->leftindex = CENTER + 1;
587 deque->rightindex = CENTER;
588 deque->state++;
589
590 /* Now the old size, leftblock, and leftindex are disconnected from
591 the empty deque and we can use them to decref the pointers.
592 */
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800593 m = (BLOCKLEN - leftindex > n) ? n : BLOCKLEN - leftindex;
Raymond Hettinger589106b2016-03-02 00:06:21 -0800594 itemptr = &leftblock->data[leftindex];
Raymond Hettinger6f86a332016-03-02 00:30:58 -0800595 limit = itemptr + m;
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800596 n -= m;
597 while (1) {
598 if (itemptr == limit) {
599 if (n == 0)
600 break;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700601 CHECK_NOT_END(leftblock->rightlink);
602 prevblock = leftblock;
603 leftblock = leftblock->rightlink;
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800604 m = (n > BLOCKLEN) ? BLOCKLEN : n;
Raymond Hettinger589106b2016-03-02 00:06:21 -0800605 itemptr = leftblock->data;
Raymond Hettinger6f86a332016-03-02 00:30:58 -0800606 limit = itemptr + m;
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800607 n -= m;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700608 freeblock(prevblock);
609 }
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800610 item = *(itemptr++);
611 Py_DECREF(item);
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700612 }
613 CHECK_END(leftblock->rightlink);
614 freeblock(leftblock);
Serhiy Storchakaa5c42282018-05-31 07:34:34 +0300615 return 0;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700616
617 alternate_method:
618 while (Py_SIZE(deque)) {
619 item = deque_pop(deque, NULL);
620 assert (item != NULL);
621 Py_DECREF(item);
622 }
Serhiy Storchakaa5c42282018-05-31 07:34:34 +0300623 return 0;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700624}
625
626static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530627deque_clearmethod(dequeobject *deque, PyObject *Py_UNUSED(ignored))
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700628{
629 deque_clear(deque);
630 Py_RETURN_NONE;
631}
632
633PyDoc_STRVAR(clear_doc, "Remove all elements from the deque.");
Raymond Hettinger41290a62015-03-31 08:12:23 -0700634
635static PyObject *
Raymond Hettinger41290a62015-03-31 08:12:23 -0700636deque_inplace_repeat(dequeobject *deque, Py_ssize_t n)
637{
Raymond Hettingerc22eee62015-09-26 02:14:50 -0700638 Py_ssize_t i, m, size;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700639 PyObject *seq;
640 PyObject *rv;
641
642 size = Py_SIZE(deque);
643 if (size == 0 || n == 1) {
644 Py_INCREF(deque);
645 return (PyObject *)deque;
646 }
647
648 if (n <= 0) {
649 deque_clear(deque);
650 Py_INCREF(deque);
651 return (PyObject *)deque;
652 }
653
Raymond Hettinger41290a62015-03-31 08:12:23 -0700654 if (size == 1) {
655 /* common case, repeating a single element */
656 PyObject *item = deque->leftblock->data[deque->leftindex];
657
Raymond Hettingera7f630092015-10-10 23:56:02 -0400658 if (deque->maxlen >= 0 && n > deque->maxlen)
Raymond Hettinger41290a62015-03-31 08:12:23 -0700659 n = deque->maxlen;
660
Raymond Hettinger67c78b52015-09-12 11:00:20 -0400661 deque->state++;
Raymond Hettingerad262252015-09-14 01:03:04 -0400662 for (i = 0 ; i < n-1 ; ) {
Raymond Hettinger67c78b52015-09-12 11:00:20 -0400663 if (deque->rightindex == BLOCKLEN - 1) {
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700664 block *b = newblock();
Raymond Hettinger67c78b52015-09-12 11:00:20 -0400665 if (b == NULL) {
666 Py_SIZE(deque) += i;
667 return NULL;
668 }
669 b->leftlink = deque->rightblock;
670 CHECK_END(deque->rightblock->rightlink);
671 deque->rightblock->rightlink = b;
672 deque->rightblock = b;
673 MARK_END(b->rightlink);
674 deque->rightindex = -1;
675 }
Raymond Hettingerc22eee62015-09-26 02:14:50 -0700676 m = n - 1 - i;
677 if (m > BLOCKLEN - 1 - deque->rightindex)
678 m = BLOCKLEN - 1 - deque->rightindex;
679 i += m;
680 while (m--) {
Raymond Hettingerad262252015-09-14 01:03:04 -0400681 deque->rightindex++;
682 Py_INCREF(item);
683 deque->rightblock->data[deque->rightindex] = item;
684 }
Raymond Hettinger41290a62015-03-31 08:12:23 -0700685 }
Raymond Hettinger67c78b52015-09-12 11:00:20 -0400686 Py_SIZE(deque) += i;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700687 Py_INCREF(deque);
688 return (PyObject *)deque;
689 }
690
Raymond Hettinger20151f52015-10-16 22:47:29 -0700691 if ((size_t)size > PY_SSIZE_T_MAX / (size_t)n) {
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400692 return PyErr_NoMemory();
693 }
694
Raymond Hettinger41290a62015-03-31 08:12:23 -0700695 seq = PySequence_List((PyObject *)deque);
696 if (seq == NULL)
697 return seq;
698
Louie Lu357bad72017-02-24 11:59:49 +0800699 /* Reduce the number of repetitions when maxlen would be exceeded */
700 if (deque->maxlen >= 0 && n * size > deque->maxlen)
701 n = (deque->maxlen + size - 1) / size;
702
Raymond Hettinger41290a62015-03-31 08:12:23 -0700703 for (i = 0 ; i < n-1 ; i++) {
704 rv = deque_extend(deque, seq);
705 if (rv == NULL) {
706 Py_DECREF(seq);
707 return NULL;
708 }
709 Py_DECREF(rv);
710 }
711 Py_INCREF(deque);
712 Py_DECREF(seq);
713 return (PyObject *)deque;
714}
715
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400716static PyObject *
717deque_repeat(dequeobject *deque, Py_ssize_t n)
718{
719 dequeobject *new_deque;
Raymond Hettinger95e2cc52015-09-13 02:41:18 -0400720 PyObject *rv;
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400721
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530722 new_deque = (dequeobject *)deque_copy((PyObject *) deque, NULL);
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400723 if (new_deque == NULL)
724 return NULL;
Raymond Hettinger95e2cc52015-09-13 02:41:18 -0400725 rv = deque_inplace_repeat(new_deque, n);
726 Py_DECREF(new_deque);
727 return rv;
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400728}
729
Raymond Hettinger54023152014-04-23 00:58:48 -0700730/* The rotate() method is part of the public API and is used internally
731as a primitive for other methods.
732
733Rotation by 1 or -1 is a common case, so any optimizations for high
734volume rotations should take care not to penalize the common case.
735
736Conceptually, a rotate by one is equivalent to a pop on one side and an
737append on the other. However, a pop/append pair is unnecessarily slow
Martin Panterd2ad5712015-11-02 04:20:33 +0000738because it requires an incref/decref pair for an object located randomly
Raymond Hettinger54023152014-04-23 00:58:48 -0700739in memory. It is better to just move the object pointer from one block
740to the next without changing the reference count.
741
742When moving batches of pointers, it is tempting to use memcpy() but that
743proved to be slower than a simple loop for a variety of reasons.
744Memcpy() cannot know in advance that we're copying pointers instead of
745bytes, that the source and destination are pointer aligned and
746non-overlapping, that moving just one pointer is a common case, that we
747never need to move more than BLOCKLEN pointers, and that at least one
748pointer is always moved.
749
750For high volume rotations, newblock() and freeblock() are never called
751more than once. Previously emptied blocks are immediately reused as a
752destination block. If a block is left-over at the end, it is freed.
753*/
754
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000755static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000756_deque_rotate(dequeobject *deque, Py_ssize_t n)
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000757{
Raymond Hettinger3959af92013-07-13 02:34:08 -0700758 block *b = NULL;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700759 block *leftblock = deque->leftblock;
760 block *rightblock = deque->rightblock;
761 Py_ssize_t leftindex = deque->leftindex;
762 Py_ssize_t rightindex = deque->rightindex;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000763 Py_ssize_t len=Py_SIZE(deque), halflen=len>>1;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700764 int rv = -1;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000765
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800766 if (len <= 1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000767 return 0;
768 if (n > halflen || n < -halflen) {
769 n %= len;
770 if (n > halflen)
771 n -= len;
772 else if (n < -halflen)
773 n += len;
774 }
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500775 assert(len > 1);
Raymond Hettingera4409c12013-02-04 00:08:12 -0500776 assert(-halflen <= n && n <= halflen);
Raymond Hettinger231ee4d2013-02-02 11:24:43 -0800777
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800778 deque->state++;
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500779 while (n > 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700780 if (leftindex == 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700781 if (b == NULL) {
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700782 b = newblock();
Raymond Hettinger3959af92013-07-13 02:34:08 -0700783 if (b == NULL)
784 goto done;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700785 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000786 b->rightlink = leftblock;
787 CHECK_END(leftblock->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700788 leftblock->leftlink = b;
789 leftblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000790 MARK_END(b->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700791 leftindex = BLOCKLEN;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700792 b = NULL;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800793 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700794 assert(leftindex > 0);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700795 {
796 PyObject **src, **dest;
797 Py_ssize_t m = n;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800798
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700799 if (m > rightindex + 1)
800 m = rightindex + 1;
801 if (m > leftindex)
802 m = leftindex;
803 assert (m > 0 && m <= len);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700804 rightindex -= m;
805 leftindex -= m;
Raymond Hettinger0e259f12015-02-01 22:53:41 -0800806 src = &rightblock->data[rightindex + 1];
807 dest = &leftblock->data[leftindex];
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700808 n -= m;
Raymond Hettinger840533b2013-07-13 17:03:58 -0700809 do {
Raymond Hettinger0e259f12015-02-01 22:53:41 -0800810 *(dest++) = *(src++);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700811 } while (--m);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700812 }
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -0700813 if (rightindex < 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700814 assert(leftblock != rightblock);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700815 assert(b == NULL);
Raymond Hettinger3959af92013-07-13 02:34:08 -0700816 b = rightblock;
Raymond Hettingerb97cc492013-07-21 01:51:07 -0700817 CHECK_NOT_END(rightblock->leftlink);
818 rightblock = rightblock->leftlink;
819 MARK_END(rightblock->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700820 rightindex = BLOCKLEN - 1;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800821 }
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800822 }
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500823 while (n < 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700824 if (rightindex == BLOCKLEN - 1) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700825 if (b == NULL) {
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700826 b = newblock();
Raymond Hettinger3959af92013-07-13 02:34:08 -0700827 if (b == NULL)
828 goto done;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700829 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000830 b->leftlink = rightblock;
831 CHECK_END(rightblock->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700832 rightblock->rightlink = b;
833 rightblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000834 MARK_END(b->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700835 rightindex = -1;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700836 b = NULL;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800837 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700838 assert (rightindex < BLOCKLEN - 1);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700839 {
840 PyObject **src, **dest;
841 Py_ssize_t m = -n;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800842
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700843 if (m > BLOCKLEN - leftindex)
844 m = BLOCKLEN - leftindex;
845 if (m > BLOCKLEN - 1 - rightindex)
846 m = BLOCKLEN - 1 - rightindex;
847 assert (m > 0 && m <= len);
848 src = &leftblock->data[leftindex];
849 dest = &rightblock->data[rightindex + 1];
850 leftindex += m;
851 rightindex += m;
852 n += m;
Raymond Hettinger840533b2013-07-13 17:03:58 -0700853 do {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700854 *(dest++) = *(src++);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700855 } while (--m);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700856 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700857 if (leftindex == BLOCKLEN) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700858 assert(leftblock != rightblock);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700859 assert(b == NULL);
Raymond Hettinger3959af92013-07-13 02:34:08 -0700860 b = leftblock;
Raymond Hettingerb97cc492013-07-21 01:51:07 -0700861 CHECK_NOT_END(leftblock->rightlink);
862 leftblock = leftblock->rightlink;
863 MARK_END(leftblock->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700864 leftindex = 0;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800865 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 }
Raymond Hettinger3959af92013-07-13 02:34:08 -0700867 rv = 0;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700868done:
Raymond Hettinger3959af92013-07-13 02:34:08 -0700869 if (b != NULL)
870 freeblock(b);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700871 deque->leftblock = leftblock;
872 deque->rightblock = rightblock;
873 deque->leftindex = leftindex;
874 deque->rightindex = rightindex;
875
876 return rv;
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000877}
878
879static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +0200880deque_rotate(dequeobject *deque, PyObject *const *args, Py_ssize_t nargs)
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000881{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 Py_ssize_t n=1;
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000883
Victor Stinnerdd407d52017-02-06 16:06:49 +0100884 if (!_PyArg_ParseStack(args, nargs, "|n:rotate", &n)) {
885 return NULL;
886 }
887
Raymond Hettinger6921c132015-03-21 02:03:40 -0700888 if (!_deque_rotate(deque, n))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 Py_RETURN_NONE;
890 return NULL;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000891}
892
Tim Peters1065f752004-10-01 01:03:29 +0000893PyDoc_STRVAR(rotate_doc,
Raymond Hettingeree33b272004-02-08 04:05:26 +0000894"Rotate the deque n steps to the right (default n=1). If n is negative, rotates left.");
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000895
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000896static PyObject *
897deque_reverse(dequeobject *deque, PyObject *unused)
898{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000899 block *leftblock = deque->leftblock;
900 block *rightblock = deque->rightblock;
901 Py_ssize_t leftindex = deque->leftindex;
902 Py_ssize_t rightindex = deque->rightindex;
Raymond Hettingercfe5b6c2015-07-20 00:25:50 -0400903 Py_ssize_t n = Py_SIZE(deque) >> 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000904 PyObject *tmp;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000905
Raymond Hettingere1b02872017-09-04 16:07:06 -0700906 while (--n >= 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 /* Validate that pointers haven't met in the middle */
908 assert(leftblock != rightblock || leftindex < rightindex);
Raymond Hettinger82df9252013-07-07 01:43:42 -1000909 CHECK_NOT_END(leftblock);
910 CHECK_NOT_END(rightblock);
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000911
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000912 /* Swap */
913 tmp = leftblock->data[leftindex];
914 leftblock->data[leftindex] = rightblock->data[rightindex];
915 rightblock->data[rightindex] = tmp;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000916
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000917 /* Advance left block/index pair */
918 leftindex++;
919 if (leftindex == BLOCKLEN) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 leftblock = leftblock->rightlink;
921 leftindex = 0;
922 }
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 /* Step backwards with the right block/index pair */
925 rightindex--;
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -0700926 if (rightindex < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000927 rightblock = rightblock->leftlink;
928 rightindex = BLOCKLEN - 1;
929 }
930 }
931 Py_RETURN_NONE;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000932}
933
934PyDoc_STRVAR(reverse_doc,
935"D.reverse() -- reverse *IN PLACE*");
936
Raymond Hettinger44459de2010-04-03 23:20:46 +0000937static PyObject *
938deque_count(dequeobject *deque, PyObject *v)
939{
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000940 block *b = deque->leftblock;
941 Py_ssize_t index = deque->leftindex;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000942 Py_ssize_t n = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000943 Py_ssize_t count = 0;
Raymond Hettingerf9d9c792015-03-02 22:47:46 -0800944 size_t start_state = deque->state;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000945 PyObject *item;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 int cmp;
Raymond Hettinger44459de2010-04-03 23:20:46 +0000947
Raymond Hettingere1b02872017-09-04 16:07:06 -0700948 while (--n >= 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000949 CHECK_NOT_END(b);
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000950 item = b->data[index];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
Raymond Hettinger2b0d6462015-09-23 19:15:44 -0700952 if (cmp < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 return NULL;
Raymond Hettinger2b0d6462015-09-23 19:15:44 -0700954 count += cmp;
Raymond Hettinger44459de2010-04-03 23:20:46 +0000955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000956 if (start_state != deque->state) {
957 PyErr_SetString(PyExc_RuntimeError,
958 "deque mutated during iteration");
959 return NULL;
960 }
Raymond Hettinger44459de2010-04-03 23:20:46 +0000961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962 /* Advance left block/index pair */
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000963 index++;
964 if (index == BLOCKLEN) {
965 b = b->rightlink;
966 index = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000967 }
968 }
969 return PyLong_FromSsize_t(count);
Raymond Hettinger44459de2010-04-03 23:20:46 +0000970}
971
972PyDoc_STRVAR(count_doc,
973"D.count(value) -> integer -- return number of occurrences of value");
974
Raymond Hettinger39dadf72015-03-20 16:38:56 -0700975static int
976deque_contains(dequeobject *deque, PyObject *v)
977{
978 block *b = deque->leftblock;
979 Py_ssize_t index = deque->leftindex;
980 Py_ssize_t n = Py_SIZE(deque);
Raymond Hettinger39dadf72015-03-20 16:38:56 -0700981 size_t start_state = deque->state;
982 PyObject *item;
983 int cmp;
984
Raymond Hettingere1b02872017-09-04 16:07:06 -0700985 while (--n >= 0) {
Raymond Hettinger39dadf72015-03-20 16:38:56 -0700986 CHECK_NOT_END(b);
987 item = b->data[index];
988 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
989 if (cmp) {
990 return cmp;
991 }
992 if (start_state != deque->state) {
993 PyErr_SetString(PyExc_RuntimeError,
994 "deque mutated during iteration");
995 return -1;
996 }
997 index++;
998 if (index == BLOCKLEN) {
999 b = b->rightlink;
1000 index = 0;
1001 }
1002 }
1003 return 0;
1004}
1005
Martin v. Löwis18e16552006-02-15 17:27:45 +00001006static Py_ssize_t
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001007deque_len(dequeobject *deque)
1008{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001009 return Py_SIZE(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001010}
1011
Raymond Hettinger4aec61e2005-03-18 21:20:23 +00001012static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02001013deque_index(dequeobject *deque, PyObject *const *args, Py_ssize_t nargs)
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001014{
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001015 Py_ssize_t i, n, start=0, stop=Py_SIZE(deque);
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001016 PyObject *v, *item;
1017 block *b = deque->leftblock;
1018 Py_ssize_t index = deque->leftindex;
1019 size_t start_state = deque->state;
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001020 int cmp;
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001021
Victor Stinnerdd407d52017-02-06 16:06:49 +01001022 if (!_PyArg_ParseStack(args, nargs, "O|O&O&:index", &v,
Serhiy Storchakad4edfc92017-03-30 18:29:23 +03001023 _PyEval_SliceIndexNotNone, &start,
1024 _PyEval_SliceIndexNotNone, &stop)) {
Victor Stinnerdd407d52017-02-06 16:06:49 +01001025 return NULL;
1026 }
1027
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001028 if (start < 0) {
1029 start += Py_SIZE(deque);
1030 if (start < 0)
1031 start = 0;
1032 }
1033 if (stop < 0) {
1034 stop += Py_SIZE(deque);
1035 if (stop < 0)
1036 stop = 0;
1037 }
Raymond Hettinger87674ec2015-08-26 08:08:38 -07001038 if (stop > Py_SIZE(deque))
1039 stop = Py_SIZE(deque);
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001040 if (start > stop)
1041 start = stop;
1042 assert(0 <= start && start <= stop && stop <= Py_SIZE(deque));
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001043
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001044 /* XXX Replace this loop with faster code from deque_item() */
1045 for (i=0 ; i<start ; i++) {
1046 index++;
1047 if (index == BLOCKLEN) {
1048 b = b->rightlink;
1049 index = 0;
1050 }
1051 }
1052
Raymond Hettingere1b02872017-09-04 16:07:06 -07001053 n = stop - i;
1054 while (--n >= 0) {
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001055 CHECK_NOT_END(b);
1056 item = b->data[index];
1057 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
1058 if (cmp > 0)
Raymond Hettingere1b02872017-09-04 16:07:06 -07001059 return PyLong_FromSsize_t(stop - n - 1);
Raymond Hettingerdf8f5b52015-11-02 07:27:40 -05001060 if (cmp < 0)
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001061 return NULL;
1062 if (start_state != deque->state) {
1063 PyErr_SetString(PyExc_RuntimeError,
1064 "deque mutated during iteration");
1065 return NULL;
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001066 }
1067 index++;
1068 if (index == BLOCKLEN) {
1069 b = b->rightlink;
1070 index = 0;
1071 }
1072 }
1073 PyErr_Format(PyExc_ValueError, "%R is not in deque", v);
1074 return NULL;
1075}
1076
1077PyDoc_STRVAR(index_doc,
1078"D.index(value, [start, [stop]]) -> integer -- return first index of value.\n"
1079"Raises ValueError if the value is not present.");
1080
Raymond Hettinger551350a2015-03-24 00:19:53 -07001081/* insert(), remove(), and delitem() are implemented in terms of
1082 rotate() for simplicity and reasonable performance near the end
1083 points. If for some reason these methods become popular, it is not
1084 hard to re-implement this using direct data movement (similar to
1085 the code used in list slice assignments) and achieve a performance
Raymond Hettingerfef9c1b2015-03-24 21:12:57 -07001086 boost (by moving each pointer only once instead of twice).
Raymond Hettinger551350a2015-03-24 00:19:53 -07001087*/
1088
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001089static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02001090deque_insert(dequeobject *deque, PyObject *const *args, Py_ssize_t nargs)
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001091{
1092 Py_ssize_t index;
1093 Py_ssize_t n = Py_SIZE(deque);
1094 PyObject *value;
1095 PyObject *rv;
1096
Victor Stinnerdd407d52017-02-06 16:06:49 +01001097 if (!_PyArg_ParseStack(args, nargs, "nO:insert", &index, &value)) {
1098 return NULL;
1099 }
1100
Raymond Hettinger37434322016-01-26 21:44:16 -08001101 if (deque->maxlen == Py_SIZE(deque)) {
Raymond Hettingera6389712016-02-01 21:21:19 -08001102 PyErr_SetString(PyExc_IndexError, "deque already at its maximum size");
1103 return NULL;
Raymond Hettinger37434322016-01-26 21:44:16 -08001104 }
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001105 if (index >= n)
1106 return deque_append(deque, value);
1107 if (index <= -n || index == 0)
1108 return deque_appendleft(deque, value);
1109 if (_deque_rotate(deque, -index))
1110 return NULL;
1111 if (index < 0)
1112 rv = deque_append(deque, value);
1113 else
1114 rv = deque_appendleft(deque, value);
1115 if (rv == NULL)
1116 return NULL;
1117 Py_DECREF(rv);
1118 if (_deque_rotate(deque, index))
1119 return NULL;
1120 Py_RETURN_NONE;
1121}
1122
1123PyDoc_STRVAR(insert_doc,
1124"D.insert(index, object) -- insert object before index");
1125
1126static PyObject *
Raymond Hettinger4aec61e2005-03-18 21:20:23 +00001127deque_remove(dequeobject *deque, PyObject *value)
1128{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001129 Py_ssize_t i, n=Py_SIZE(deque);
Raymond Hettinger4aec61e2005-03-18 21:20:23 +00001130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001131 for (i=0 ; i<n ; i++) {
1132 PyObject *item = deque->leftblock->data[deque->leftindex];
1133 int cmp = PyObject_RichCompareBool(item, value, Py_EQ);
Raymond Hettingerd73202c2005-03-19 00:00:51 +00001134
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001135 if (Py_SIZE(deque) != n) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136 PyErr_SetString(PyExc_IndexError,
1137 "deque mutated during remove().");
1138 return NULL;
1139 }
1140 if (cmp > 0) {
1141 PyObject *tgt = deque_popleft(deque, NULL);
1142 assert (tgt != NULL);
Raymond Hettinger6921c132015-03-21 02:03:40 -07001143 if (_deque_rotate(deque, i))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001144 return NULL;
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001145 Py_DECREF(tgt);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001146 Py_RETURN_NONE;
1147 }
1148 else if (cmp < 0) {
1149 _deque_rotate(deque, i);
1150 return NULL;
1151 }
1152 _deque_rotate(deque, -1);
1153 }
1154 PyErr_SetString(PyExc_ValueError, "deque.remove(x): x not in deque");
1155 return NULL;
Raymond Hettinger4aec61e2005-03-18 21:20:23 +00001156}
1157
1158PyDoc_STRVAR(remove_doc,
1159"D.remove(value) -- remove first occurrence of value.");
1160
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001161static int
1162valid_index(Py_ssize_t i, Py_ssize_t limit)
1163{
Raymond Hettinger12f896c2015-07-31 12:03:20 -07001164 /* The cast to size_t lets us use just a single comparison
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001165 to check whether i is in the range: 0 <= i < limit */
1166 return (size_t) i < (size_t) limit;
1167}
1168
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001169static PyObject *
Benjamin Petersond6313712008-07-31 16:23:04 +00001170deque_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001171{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001172 block *b;
1173 PyObject *item;
1174 Py_ssize_t n, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001175
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001176 if (!valid_index(i, Py_SIZE(deque))) {
1177 PyErr_SetString(PyExc_IndexError, "deque index out of range");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178 return NULL;
1179 }
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001180
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001181 if (i == 0) {
1182 i = deque->leftindex;
1183 b = deque->leftblock;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001184 } else if (i == Py_SIZE(deque) - 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001185 i = deque->rightindex;
1186 b = deque->rightblock;
1187 } else {
1188 i += deque->leftindex;
Raymond Hettingerc2083082015-02-28 23:29:16 -08001189 n = (Py_ssize_t)((size_t) i / BLOCKLEN);
1190 i = (Py_ssize_t)((size_t) i % BLOCKLEN);
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001191 if (index < (Py_SIZE(deque) >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001192 b = deque->leftblock;
Raymond Hettingere1b02872017-09-04 16:07:06 -07001193 while (--n >= 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 b = b->rightlink;
1195 } else {
Raymond Hettinger63d1ff22015-02-28 07:41:30 -08001196 n = (Py_ssize_t)(
Raymond Hettingerc2083082015-02-28 23:29:16 -08001197 ((size_t)(deque->leftindex + Py_SIZE(deque) - 1))
Raymond Hettinger63d1ff22015-02-28 07:41:30 -08001198 / BLOCKLEN - n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001199 b = deque->rightblock;
Raymond Hettingere1b02872017-09-04 16:07:06 -07001200 while (--n >= 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001201 b = b->leftlink;
1202 }
1203 }
1204 item = b->data[i];
1205 Py_INCREF(item);
1206 return item;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001207}
1208
1209static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001210deque_del_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001211{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001212 PyObject *item;
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001213 int rv;
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001214
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001215 assert (i >= 0 && i < Py_SIZE(deque));
Raymond Hettinger6921c132015-03-21 02:03:40 -07001216 if (_deque_rotate(deque, -i))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001217 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001218 item = deque_popleft(deque, NULL);
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001219 rv = _deque_rotate(deque, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001220 assert (item != NULL);
1221 Py_DECREF(item);
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001222 return rv;
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001223}
1224
1225static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001226deque_ass_item(dequeobject *deque, Py_ssize_t i, PyObject *v)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001227{
Raymond Hettinger38418662016-02-08 20:34:49 -08001228 PyObject *old_value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 block *b;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001230 Py_ssize_t n, len=Py_SIZE(deque), halflen=(len+1)>>1, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001231
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001232 if (!valid_index(i, len)) {
1233 PyErr_SetString(PyExc_IndexError, "deque index out of range");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 return -1;
1235 }
1236 if (v == NULL)
1237 return deque_del_item(deque, i);
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001239 i += deque->leftindex;
Raymond Hettingerc2083082015-02-28 23:29:16 -08001240 n = (Py_ssize_t)((size_t) i / BLOCKLEN);
1241 i = (Py_ssize_t)((size_t) i % BLOCKLEN);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001242 if (index <= halflen) {
1243 b = deque->leftblock;
Raymond Hettingere1b02872017-09-04 16:07:06 -07001244 while (--n >= 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001245 b = b->rightlink;
1246 } else {
Raymond Hettingera473b9d2015-02-28 17:49:47 -08001247 n = (Py_ssize_t)(
Raymond Hettingerc2083082015-02-28 23:29:16 -08001248 ((size_t)(deque->leftindex + Py_SIZE(deque) - 1))
Raymond Hettingera473b9d2015-02-28 17:49:47 -08001249 / BLOCKLEN - n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001250 b = deque->rightblock;
Raymond Hettingere1b02872017-09-04 16:07:06 -07001251 while (--n >= 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001252 b = b->leftlink;
1253 }
1254 Py_INCREF(v);
Raymond Hettinger38418662016-02-08 20:34:49 -08001255 old_value = b->data[i];
1256 b->data[i] = v;
1257 Py_DECREF(old_value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258 return 0;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001259}
1260
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001261static void
1262deque_dealloc(dequeobject *deque)
1263{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001264 PyObject_GC_UnTrack(deque);
1265 if (deque->weakreflist != NULL)
1266 PyObject_ClearWeakRefs((PyObject *) deque);
1267 if (deque->leftblock != NULL) {
1268 deque_clear(deque);
1269 assert(deque->leftblock != NULL);
1270 freeblock(deque->leftblock);
1271 }
1272 deque->leftblock = NULL;
1273 deque->rightblock = NULL;
1274 Py_TYPE(deque)->tp_free(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001275}
1276
1277static int
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001278deque_traverse(dequeobject *deque, visitproc visit, void *arg)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001279{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001280 block *b;
1281 PyObject *item;
1282 Py_ssize_t index;
1283 Py_ssize_t indexlo = deque->leftindex;
Raymond Hettinger1286d142015-10-14 23:16:57 -07001284 Py_ssize_t indexhigh;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001285
Raymond Hettinger5bfa8672013-07-06 11:58:09 -10001286 for (b = deque->leftblock; b != deque->rightblock; b = b->rightlink) {
1287 for (index = indexlo; index < BLOCKLEN ; index++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001288 item = b->data[index];
1289 Py_VISIT(item);
1290 }
1291 indexlo = 0;
1292 }
Raymond Hettinger1286d142015-10-14 23:16:57 -07001293 indexhigh = deque->rightindex;
1294 for (index = indexlo; index <= indexhigh; index++) {
Raymond Hettinger5bfa8672013-07-06 11:58:09 -10001295 item = b->data[index];
1296 Py_VISIT(item);
1297 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001298 return 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001299}
1300
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001301static PyObject *
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001302deque_reduce(dequeobject *deque)
1303{
Serhiy Storchakaa0d416f2016-03-06 08:55:21 +02001304 PyObject *dict, *it;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001305 _Py_IDENTIFIER(__dict__);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001306
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001307 if (_PyObject_LookupAttrId((PyObject *)deque, &PyId___dict__, &dict) < 0) {
1308 return NULL;
1309 }
Serhiy Storchakaa0d416f2016-03-06 08:55:21 +02001310 if (dict == NULL) {
Serhiy Storchakaa0d416f2016-03-06 08:55:21 +02001311 dict = Py_None;
1312 Py_INCREF(dict);
1313 }
1314
1315 it = PyObject_GetIter((PyObject *)deque);
1316 if (it == NULL) {
1317 Py_DECREF(dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001318 return NULL;
1319 }
Serhiy Storchakaa0d416f2016-03-06 08:55:21 +02001320
1321 if (deque->maxlen < 0) {
1322 return Py_BuildValue("O()NN", Py_TYPE(deque), dict, it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001323 }
Serhiy Storchakaa0d416f2016-03-06 08:55:21 +02001324 else {
1325 return Py_BuildValue("O(()n)NN", Py_TYPE(deque), deque->maxlen, dict, it);
1326 }
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001327}
1328
1329PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
1330
1331static PyObject *
1332deque_repr(PyObject *deque)
1333{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001334 PyObject *aslist, *result;
1335 int i;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001337 i = Py_ReprEnter(deque);
1338 if (i != 0) {
1339 if (i < 0)
1340 return NULL;
1341 return PyUnicode_FromString("[...]");
1342 }
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001344 aslist = PySequence_List(deque);
1345 if (aslist == NULL) {
1346 Py_ReprLeave(deque);
1347 return NULL;
1348 }
Raymond Hettingera7f630092015-10-10 23:56:02 -04001349 if (((dequeobject *)deque)->maxlen >= 0)
Serhiy Storchakab3a77962017-09-21 14:24:13 +03001350 result = PyUnicode_FromFormat("%s(%R, maxlen=%zd)",
1351 _PyType_Name(Py_TYPE(deque)), aslist,
1352 ((dequeobject *)deque)->maxlen);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001353 else
Serhiy Storchakab3a77962017-09-21 14:24:13 +03001354 result = PyUnicode_FromFormat("%s(%R)",
1355 _PyType_Name(Py_TYPE(deque)), aslist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001356 Py_ReprLeave(deque);
Raymond Hettinger2b2b7532015-09-05 17:05:52 -07001357 Py_DECREF(aslist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001358 return result;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001359}
1360
Raymond Hettinger738ec902004-02-29 02:15:56 +00001361static PyObject *
1362deque_richcompare(PyObject *v, PyObject *w, int op)
1363{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001364 PyObject *it1=NULL, *it2=NULL, *x, *y;
1365 Py_ssize_t vs, ws;
1366 int b, cmp=-1;
Raymond Hettinger738ec902004-02-29 02:15:56 +00001367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001368 if (!PyObject_TypeCheck(v, &deque_type) ||
1369 !PyObject_TypeCheck(w, &deque_type)) {
Brian Curtindfc80e32011-08-10 20:28:54 -05001370 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001371 }
Raymond Hettinger738ec902004-02-29 02:15:56 +00001372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001373 /* Shortcuts */
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001374 vs = Py_SIZE((dequeobject *)v);
1375 ws = Py_SIZE((dequeobject *)w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001376 if (op == Py_EQ) {
1377 if (v == w)
1378 Py_RETURN_TRUE;
1379 if (vs != ws)
1380 Py_RETURN_FALSE;
1381 }
1382 if (op == Py_NE) {
1383 if (v == w)
1384 Py_RETURN_FALSE;
1385 if (vs != ws)
1386 Py_RETURN_TRUE;
1387 }
Raymond Hettinger738ec902004-02-29 02:15:56 +00001388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001389 /* Search for the first index where items are different */
1390 it1 = PyObject_GetIter(v);
1391 if (it1 == NULL)
1392 goto done;
1393 it2 = PyObject_GetIter(w);
1394 if (it2 == NULL)
1395 goto done;
1396 for (;;) {
1397 x = PyIter_Next(it1);
1398 if (x == NULL && PyErr_Occurred())
1399 goto done;
1400 y = PyIter_Next(it2);
1401 if (x == NULL || y == NULL)
1402 break;
1403 b = PyObject_RichCompareBool(x, y, Py_EQ);
1404 if (b == 0) {
1405 cmp = PyObject_RichCompareBool(x, y, op);
1406 Py_DECREF(x);
1407 Py_DECREF(y);
1408 goto done;
1409 }
1410 Py_DECREF(x);
1411 Py_DECREF(y);
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -07001412 if (b < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001413 goto done;
1414 }
1415 /* We reached the end of one deque or both */
1416 Py_XDECREF(x);
1417 Py_XDECREF(y);
1418 if (PyErr_Occurred())
1419 goto done;
1420 switch (op) {
1421 case Py_LT: cmp = y != NULL; break; /* if w was longer */
1422 case Py_LE: cmp = x == NULL; break; /* if v was not longer */
1423 case Py_EQ: cmp = x == y; break; /* if we reached the end of both */
1424 case Py_NE: cmp = x != y; break; /* if one deque continues */
1425 case Py_GT: cmp = x != NULL; break; /* if v was longer */
1426 case Py_GE: cmp = y == NULL; break; /* if w was not longer */
1427 }
Tim Peters1065f752004-10-01 01:03:29 +00001428
Raymond Hettinger738ec902004-02-29 02:15:56 +00001429done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001430 Py_XDECREF(it1);
1431 Py_XDECREF(it2);
1432 if (cmp == 1)
1433 Py_RETURN_TRUE;
1434 if (cmp == 0)
1435 Py_RETURN_FALSE;
1436 return NULL;
Raymond Hettinger738ec902004-02-29 02:15:56 +00001437}
1438
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001439static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001440deque_init(dequeobject *deque, PyObject *args, PyObject *kwdargs)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001441{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001442 PyObject *iterable = NULL;
1443 PyObject *maxlenobj = NULL;
1444 Py_ssize_t maxlen = -1;
1445 char *kwlist[] = {"iterable", "maxlen", 0};
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001446
Raymond Hettinger0d309402015-09-30 23:15:02 -07001447 if (kwdargs == NULL) {
1448 if (!PyArg_UnpackTuple(args, "deque()", 0, 2, &iterable, &maxlenobj))
1449 return -1;
1450 } else {
1451 if (!PyArg_ParseTupleAndKeywords(args, kwdargs, "|OO:deque", kwlist,
1452 &iterable, &maxlenobj))
1453 return -1;
1454 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001455 if (maxlenobj != NULL && maxlenobj != Py_None) {
1456 maxlen = PyLong_AsSsize_t(maxlenobj);
1457 if (maxlen == -1 && PyErr_Occurred())
1458 return -1;
1459 if (maxlen < 0) {
1460 PyErr_SetString(PyExc_ValueError, "maxlen must be non-negative");
1461 return -1;
1462 }
1463 }
1464 deque->maxlen = maxlen;
Raymond Hettinger0d309402015-09-30 23:15:02 -07001465 if (Py_SIZE(deque) > 0)
1466 deque_clear(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001467 if (iterable != NULL) {
1468 PyObject *rv = deque_extend(deque, iterable);
1469 if (rv == NULL)
1470 return -1;
1471 Py_DECREF(rv);
1472 }
1473 return 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001474}
1475
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001476static PyObject *
Jesus Cea16e2fca2012-08-03 14:49:42 +02001477deque_sizeof(dequeobject *deque, void *unused)
1478{
1479 Py_ssize_t res;
1480 Py_ssize_t blocks;
1481
Serhiy Storchaka5c4064e2015-12-19 20:05:25 +02001482 res = _PyObject_SIZE(Py_TYPE(deque));
Raymond Hettingerbc003412015-10-14 23:33:23 -07001483 blocks = (size_t)(deque->leftindex + Py_SIZE(deque) + BLOCKLEN - 1) / BLOCKLEN;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001484 assert(deque->leftindex + Py_SIZE(deque) - 1 ==
Jesus Cea16e2fca2012-08-03 14:49:42 +02001485 (blocks - 1) * BLOCKLEN + deque->rightindex);
1486 res += blocks * sizeof(block);
1487 return PyLong_FromSsize_t(res);
1488}
1489
1490PyDoc_STRVAR(sizeof_doc,
1491"D.__sizeof__() -- size of D in memory, in bytes");
1492
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001493static int
1494deque_bool(dequeobject *deque)
1495{
1496 return Py_SIZE(deque) != 0;
1497}
1498
Jesus Cea16e2fca2012-08-03 14:49:42 +02001499static PyObject *
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001500deque_get_maxlen(dequeobject *deque)
1501{
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -07001502 if (deque->maxlen < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001503 Py_RETURN_NONE;
1504 return PyLong_FromSsize_t(deque->maxlen);
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001505}
1506
Raymond Hettinger41290a62015-03-31 08:12:23 -07001507
1508/* deque object ********************************************************/
1509
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001510static PyGetSetDef deque_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001511 {"maxlen", (getter)deque_get_maxlen, (setter)NULL,
1512 "maximum size of a deque or None if unbounded"},
1513 {0}
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001514};
1515
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001516static PySequenceMethods deque_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001517 (lenfunc)deque_len, /* sq_length */
Raymond Hettinger41290a62015-03-31 08:12:23 -07001518 (binaryfunc)deque_concat, /* sq_concat */
1519 (ssizeargfunc)deque_repeat, /* sq_repeat */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001520 (ssizeargfunc)deque_item, /* sq_item */
1521 0, /* sq_slice */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001522 (ssizeobjargproc)deque_ass_item, /* sq_ass_item */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001523 0, /* sq_ass_slice */
Raymond Hettinger39dadf72015-03-20 16:38:56 -07001524 (objobjproc)deque_contains, /* sq_contains */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001525 (binaryfunc)deque_inplace_concat, /* sq_inplace_concat */
Raymond Hettinger41290a62015-03-31 08:12:23 -07001526 (ssizeargfunc)deque_inplace_repeat, /* sq_inplace_repeat */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001527};
1528
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001529static PyNumberMethods deque_as_number = {
1530 0, /* nb_add */
1531 0, /* nb_subtract */
1532 0, /* nb_multiply */
1533 0, /* nb_remainder */
1534 0, /* nb_divmod */
1535 0, /* nb_power */
1536 0, /* nb_negative */
1537 0, /* nb_positive */
1538 0, /* nb_absolute */
1539 (inquiry)deque_bool, /* nb_bool */
1540 0, /* nb_invert */
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001541 };
1542
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001543static PyObject *deque_iter(dequeobject *deque);
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301544static PyObject *deque_reviter(dequeobject *deque, PyObject *Py_UNUSED(ignored));
Tim Peters1065f752004-10-01 01:03:29 +00001545PyDoc_STRVAR(reversed_doc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001546 "D.__reversed__() -- return a reverse iterator over the deque");
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001547
1548static PyMethodDef deque_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001549 {"append", (PyCFunction)deque_append,
1550 METH_O, append_doc},
1551 {"appendleft", (PyCFunction)deque_appendleft,
1552 METH_O, appendleft_doc},
1553 {"clear", (PyCFunction)deque_clearmethod,
1554 METH_NOARGS, clear_doc},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301555 {"__copy__", deque_copy,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001556 METH_NOARGS, copy_doc},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301557 {"copy", deque_copy,
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001558 METH_NOARGS, copy_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001559 {"count", (PyCFunction)deque_count,
Raymond Hettinger0f6f9472015-03-21 01:42:10 -07001560 METH_O, count_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001561 {"extend", (PyCFunction)deque_extend,
1562 METH_O, extend_doc},
1563 {"extendleft", (PyCFunction)deque_extendleft,
1564 METH_O, extendleft_doc},
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001565 {"index", (PyCFunction)deque_index,
Victor Stinnerdd407d52017-02-06 16:06:49 +01001566 METH_FASTCALL, index_doc},
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001567 {"insert", (PyCFunction)deque_insert,
Victor Stinnerdd407d52017-02-06 16:06:49 +01001568 METH_FASTCALL, insert_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001569 {"pop", (PyCFunction)deque_pop,
1570 METH_NOARGS, pop_doc},
1571 {"popleft", (PyCFunction)deque_popleft,
1572 METH_NOARGS, popleft_doc},
Raymond Hettinger0f6f9472015-03-21 01:42:10 -07001573 {"__reduce__", (PyCFunction)deque_reduce,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001574 METH_NOARGS, reduce_doc},
1575 {"remove", (PyCFunction)deque_remove,
1576 METH_O, remove_doc},
1577 {"__reversed__", (PyCFunction)deque_reviter,
1578 METH_NOARGS, reversed_doc},
1579 {"reverse", (PyCFunction)deque_reverse,
1580 METH_NOARGS, reverse_doc},
1581 {"rotate", (PyCFunction)deque_rotate,
Victor Stinnerdd407d52017-02-06 16:06:49 +01001582 METH_FASTCALL, rotate_doc},
Jesus Cea16e2fca2012-08-03 14:49:42 +02001583 {"__sizeof__", (PyCFunction)deque_sizeof,
1584 METH_NOARGS, sizeof_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001585 {NULL, NULL} /* sentinel */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001586};
1587
1588PyDoc_STRVAR(deque_doc,
Andrew Svetlov6a5c7c32012-10-31 11:50:40 +02001589"deque([iterable[, maxlen]]) --> deque object\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001590\n\
Raymond Hettinger41290a62015-03-31 08:12:23 -07001591A list-like sequence optimized for data accesses near its endpoints.");
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001592
Neal Norwitz87f10132004-02-29 15:40:53 +00001593static PyTypeObject deque_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001594 PyVarObject_HEAD_INIT(NULL, 0)
1595 "collections.deque", /* tp_name */
1596 sizeof(dequeobject), /* tp_basicsize */
1597 0, /* tp_itemsize */
1598 /* methods */
1599 (destructor)deque_dealloc, /* tp_dealloc */
1600 0, /* tp_print */
1601 0, /* tp_getattr */
1602 0, /* tp_setattr */
1603 0, /* tp_reserved */
1604 deque_repr, /* tp_repr */
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001605 &deque_as_number, /* tp_as_number */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001606 &deque_as_sequence, /* tp_as_sequence */
1607 0, /* tp_as_mapping */
Georg Brandlf038b322010-10-18 07:35:09 +00001608 PyObject_HashNotImplemented, /* tp_hash */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001609 0, /* tp_call */
1610 0, /* tp_str */
1611 PyObject_GenericGetAttr, /* tp_getattro */
1612 0, /* tp_setattro */
1613 0, /* tp_as_buffer */
1614 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
Georg Brandlf038b322010-10-18 07:35:09 +00001615 /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001616 deque_doc, /* tp_doc */
1617 (traverseproc)deque_traverse, /* tp_traverse */
1618 (inquiry)deque_clear, /* tp_clear */
1619 (richcmpfunc)deque_richcompare, /* tp_richcompare */
Georg Brandlf038b322010-10-18 07:35:09 +00001620 offsetof(dequeobject, weakreflist), /* tp_weaklistoffset*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001621 (getiterfunc)deque_iter, /* tp_iter */
1622 0, /* tp_iternext */
1623 deque_methods, /* tp_methods */
1624 0, /* tp_members */
Georg Brandlf038b322010-10-18 07:35:09 +00001625 deque_getset, /* tp_getset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001626 0, /* tp_base */
1627 0, /* tp_dict */
1628 0, /* tp_descr_get */
1629 0, /* tp_descr_set */
1630 0, /* tp_dictoffset */
1631 (initproc)deque_init, /* tp_init */
1632 PyType_GenericAlloc, /* tp_alloc */
1633 deque_new, /* tp_new */
1634 PyObject_GC_Del, /* tp_free */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001635};
1636
1637/*********************** Deque Iterator **************************/
1638
1639typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001640 PyObject_HEAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001641 block *b;
Raymond Hettinger87e69122015-03-02 23:32:02 -08001642 Py_ssize_t index;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001643 dequeobject *deque;
Raymond Hettingerf9d9c792015-03-02 22:47:46 -08001644 size_t state; /* state when the iterator is created */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001645 Py_ssize_t counter; /* number of items remaining for iteration */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001646} dequeiterobject;
1647
Martin v. Löwis59683e82008-06-13 07:50:45 +00001648static PyTypeObject dequeiter_type;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001649
1650static PyObject *
1651deque_iter(dequeobject *deque)
1652{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001653 dequeiterobject *it;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001655 it = PyObject_GC_New(dequeiterobject, &dequeiter_type);
1656 if (it == NULL)
1657 return NULL;
1658 it->b = deque->leftblock;
1659 it->index = deque->leftindex;
1660 Py_INCREF(deque);
1661 it->deque = deque;
1662 it->state = deque->state;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001663 it->counter = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001664 PyObject_GC_Track(it);
1665 return (PyObject *)it;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001666}
1667
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001668static int
1669dequeiter_traverse(dequeiterobject *dio, visitproc visit, void *arg)
1670{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001671 Py_VISIT(dio->deque);
1672 return 0;
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001673}
1674
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001675static void
1676dequeiter_dealloc(dequeiterobject *dio)
1677{
INADA Naokia6296d32017-08-24 14:55:17 +09001678 /* bpo-31095: UnTrack is needed before calling any callbacks */
1679 PyObject_GC_UnTrack(dio);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001680 Py_XDECREF(dio->deque);
1681 PyObject_GC_Del(dio);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001682}
1683
1684static PyObject *
1685dequeiter_next(dequeiterobject *it)
1686{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001687 PyObject *item;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001688
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001689 if (it->deque->state != it->state) {
1690 it->counter = 0;
1691 PyErr_SetString(PyExc_RuntimeError,
1692 "deque mutated during iteration");
1693 return NULL;
1694 }
1695 if (it->counter == 0)
1696 return NULL;
1697 assert (!(it->b == it->deque->rightblock &&
1698 it->index > it->deque->rightindex));
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001699
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001700 item = it->b->data[it->index];
1701 it->index++;
1702 it->counter--;
1703 if (it->index == BLOCKLEN && it->counter > 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -10001704 CHECK_NOT_END(it->b->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001705 it->b = it->b->rightlink;
1706 it->index = 0;
1707 }
1708 Py_INCREF(item);
1709 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001710}
1711
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001712static PyObject *
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001713dequeiter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1714{
1715 Py_ssize_t i, index=0;
1716 PyObject *deque;
1717 dequeiterobject *it;
1718 if (!PyArg_ParseTuple(args, "O!|n", &deque_type, &deque, &index))
1719 return NULL;
1720 assert(type == &dequeiter_type);
1721
1722 it = (dequeiterobject*)deque_iter((dequeobject *)deque);
1723 if (!it)
1724 return NULL;
1725 /* consume items from the queue */
1726 for(i=0; i<index; i++) {
1727 PyObject *item = dequeiter_next(it);
1728 if (item) {
1729 Py_DECREF(item);
1730 } else {
1731 if (it->counter) {
1732 Py_DECREF(it);
1733 return NULL;
1734 } else
1735 break;
1736 }
1737 }
1738 return (PyObject*)it;
1739}
1740
1741static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301742dequeiter_len(dequeiterobject *it, PyObject *Py_UNUSED(ignored))
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001743{
Antoine Pitrou554f3342010-08-17 18:30:06 +00001744 return PyLong_FromSsize_t(it->counter);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001745}
1746
Armin Rigof5b3e362006-02-11 21:32:43 +00001747PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001748
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001749static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301750dequeiter_reduce(dequeiterobject *it, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001751{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001752 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 +00001753}
1754
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001755static PyMethodDef dequeiter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001756 {"__length_hint__", (PyCFunction)dequeiter_len, METH_NOARGS, length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001757 {"__reduce__", (PyCFunction)dequeiter_reduce, METH_NOARGS, reduce_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001758 {NULL, NULL} /* sentinel */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001759};
1760
Martin v. Löwis59683e82008-06-13 07:50:45 +00001761static PyTypeObject dequeiter_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001762 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger87e69122015-03-02 23:32:02 -08001763 "_collections._deque_iterator", /* tp_name */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001764 sizeof(dequeiterobject), /* tp_basicsize */
1765 0, /* tp_itemsize */
1766 /* methods */
1767 (destructor)dequeiter_dealloc, /* tp_dealloc */
1768 0, /* tp_print */
1769 0, /* tp_getattr */
1770 0, /* tp_setattr */
1771 0, /* tp_reserved */
1772 0, /* tp_repr */
1773 0, /* tp_as_number */
1774 0, /* tp_as_sequence */
1775 0, /* tp_as_mapping */
1776 0, /* tp_hash */
1777 0, /* tp_call */
1778 0, /* tp_str */
1779 PyObject_GenericGetAttr, /* tp_getattro */
1780 0, /* tp_setattro */
1781 0, /* tp_as_buffer */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001782 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001783 0, /* tp_doc */
1784 (traverseproc)dequeiter_traverse, /* tp_traverse */
1785 0, /* tp_clear */
1786 0, /* tp_richcompare */
1787 0, /* tp_weaklistoffset */
1788 PyObject_SelfIter, /* tp_iter */
1789 (iternextfunc)dequeiter_next, /* tp_iternext */
1790 dequeiter_methods, /* tp_methods */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001791 0, /* tp_members */
1792 0, /* tp_getset */
1793 0, /* tp_base */
1794 0, /* tp_dict */
1795 0, /* tp_descr_get */
1796 0, /* tp_descr_set */
1797 0, /* tp_dictoffset */
1798 0, /* tp_init */
1799 0, /* tp_alloc */
1800 dequeiter_new, /* tp_new */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001801 0,
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001802};
1803
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001804/*********************** Deque Reverse Iterator **************************/
1805
Martin v. Löwis59683e82008-06-13 07:50:45 +00001806static PyTypeObject dequereviter_type;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001807
1808static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301809deque_reviter(dequeobject *deque, PyObject *Py_UNUSED(ignored))
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001810{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001811 dequeiterobject *it;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001812
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001813 it = PyObject_GC_New(dequeiterobject, &dequereviter_type);
1814 if (it == NULL)
1815 return NULL;
1816 it->b = deque->rightblock;
1817 it->index = deque->rightindex;
1818 Py_INCREF(deque);
1819 it->deque = deque;
1820 it->state = deque->state;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001821 it->counter = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001822 PyObject_GC_Track(it);
1823 return (PyObject *)it;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001824}
1825
1826static PyObject *
1827dequereviter_next(dequeiterobject *it)
1828{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001829 PyObject *item;
1830 if (it->counter == 0)
1831 return NULL;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001832
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001833 if (it->deque->state != it->state) {
1834 it->counter = 0;
1835 PyErr_SetString(PyExc_RuntimeError,
1836 "deque mutated during iteration");
1837 return NULL;
1838 }
1839 assert (!(it->b == it->deque->leftblock &&
1840 it->index < it->deque->leftindex));
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001841
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001842 item = it->b->data[it->index];
1843 it->index--;
1844 it->counter--;
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -07001845 if (it->index < 0 && it->counter > 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -10001846 CHECK_NOT_END(it->b->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001847 it->b = it->b->leftlink;
1848 it->index = BLOCKLEN - 1;
1849 }
1850 Py_INCREF(item);
1851 return item;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001852}
1853
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001854static PyObject *
1855dequereviter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1856{
1857 Py_ssize_t i, index=0;
1858 PyObject *deque;
1859 dequeiterobject *it;
1860 if (!PyArg_ParseTuple(args, "O!|n", &deque_type, &deque, &index))
1861 return NULL;
1862 assert(type == &dequereviter_type);
1863
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301864 it = (dequeiterobject*)deque_reviter((dequeobject *)deque, NULL);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001865 if (!it)
1866 return NULL;
1867 /* consume items from the queue */
1868 for(i=0; i<index; i++) {
1869 PyObject *item = dequereviter_next(it);
1870 if (item) {
1871 Py_DECREF(item);
1872 } else {
1873 if (it->counter) {
1874 Py_DECREF(it);
1875 return NULL;
1876 } else
1877 break;
1878 }
1879 }
1880 return (PyObject*)it;
1881}
1882
Martin v. Löwis59683e82008-06-13 07:50:45 +00001883static PyTypeObject dequereviter_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001884 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger87e69122015-03-02 23:32:02 -08001885 "_collections._deque_reverse_iterator", /* tp_name */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001886 sizeof(dequeiterobject), /* tp_basicsize */
1887 0, /* tp_itemsize */
1888 /* methods */
1889 (destructor)dequeiter_dealloc, /* tp_dealloc */
1890 0, /* tp_print */
1891 0, /* tp_getattr */
1892 0, /* tp_setattr */
1893 0, /* tp_reserved */
1894 0, /* tp_repr */
1895 0, /* tp_as_number */
1896 0, /* tp_as_sequence */
1897 0, /* tp_as_mapping */
1898 0, /* tp_hash */
1899 0, /* tp_call */
1900 0, /* tp_str */
1901 PyObject_GenericGetAttr, /* tp_getattro */
1902 0, /* tp_setattro */
1903 0, /* tp_as_buffer */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001904 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001905 0, /* tp_doc */
1906 (traverseproc)dequeiter_traverse, /* tp_traverse */
1907 0, /* tp_clear */
1908 0, /* tp_richcompare */
1909 0, /* tp_weaklistoffset */
1910 PyObject_SelfIter, /* tp_iter */
1911 (iternextfunc)dequereviter_next, /* tp_iternext */
1912 dequeiter_methods, /* tp_methods */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001913 0, /* tp_members */
1914 0, /* tp_getset */
1915 0, /* tp_base */
1916 0, /* tp_dict */
1917 0, /* tp_descr_get */
1918 0, /* tp_descr_set */
1919 0, /* tp_dictoffset */
1920 0, /* tp_init */
1921 0, /* tp_alloc */
1922 dequereviter_new, /* tp_new */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001923 0,
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001924};
1925
Guido van Rossum1968ad32006-02-25 22:38:04 +00001926/* defaultdict type *********************************************************/
1927
1928typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001929 PyDictObject dict;
1930 PyObject *default_factory;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001931} defdictobject;
1932
1933static PyTypeObject defdict_type; /* Forward */
1934
1935PyDoc_STRVAR(defdict_missing_doc,
1936"__missing__(key) # Called by __getitem__ for missing key; pseudo-code:\n\
Guido van Rossumd8faa362007-04-27 19:54:29 +00001937 if self.default_factory is None: raise KeyError((key,))\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00001938 self[key] = value = self.default_factory()\n\
1939 return value\n\
1940");
1941
1942static PyObject *
1943defdict_missing(defdictobject *dd, PyObject *key)
1944{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001945 PyObject *factory = dd->default_factory;
1946 PyObject *value;
1947 if (factory == NULL || factory == Py_None) {
1948 /* XXX Call dict.__missing__(key) */
1949 PyObject *tup;
1950 tup = PyTuple_Pack(1, key);
1951 if (!tup) return NULL;
1952 PyErr_SetObject(PyExc_KeyError, tup);
1953 Py_DECREF(tup);
1954 return NULL;
1955 }
1956 value = PyEval_CallObject(factory, NULL);
1957 if (value == NULL)
1958 return value;
1959 if (PyObject_SetItem((PyObject *)dd, key, value) < 0) {
1960 Py_DECREF(value);
1961 return NULL;
1962 }
1963 return value;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001964}
1965
1966PyDoc_STRVAR(defdict_copy_doc, "D.copy() -> a shallow copy of D.");
1967
1968static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301969defdict_copy(defdictobject *dd, PyObject *Py_UNUSED(ignored))
Guido van Rossum1968ad32006-02-25 22:38:04 +00001970{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001971 /* This calls the object's class. That only works for subclasses
1972 whose class constructor has the same signature. Subclasses that
1973 define a different constructor signature must override copy().
1974 */
Raymond Hettinger54628fa2009-08-04 19:16:39 +00001975
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001976 if (dd->default_factory == NULL)
1977 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd), Py_None, dd, NULL);
1978 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd),
1979 dd->default_factory, dd, NULL);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001980}
1981
1982static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301983defdict_reduce(defdictobject *dd, PyObject *Py_UNUSED(ignored))
Guido van Rossum1968ad32006-02-25 22:38:04 +00001984{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001985 /* __reduce__ must return a 5-tuple as follows:
Guido van Rossum1968ad32006-02-25 22:38:04 +00001986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001987 - factory function
1988 - tuple of args for the factory function
1989 - additional state (here None)
1990 - sequence iterator (here None)
1991 - dictionary iterator (yielding successive (key, value) pairs
Guido van Rossum1968ad32006-02-25 22:38:04 +00001992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001993 This API is used by pickle.py and copy.py.
Guido van Rossum1968ad32006-02-25 22:38:04 +00001994
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001995 For this to be useful with pickle.py, the default_factory
1996 must be picklable; e.g., None, a built-in, or a global
1997 function in a module or package.
Guido van Rossum1968ad32006-02-25 22:38:04 +00001998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001999 Both shallow and deep copying are supported, but for deep
2000 copying, the default_factory must be deep-copyable; e.g. None,
2001 or a built-in (functions are not copyable at this time).
Guido van Rossum1968ad32006-02-25 22:38:04 +00002002
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002003 This only works for subclasses as long as their constructor
2004 signature is compatible; the first argument must be the
2005 optional default_factory, defaulting to None.
2006 */
2007 PyObject *args;
2008 PyObject *items;
2009 PyObject *iter;
2010 PyObject *result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002011 _Py_IDENTIFIER(items);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002013 if (dd->default_factory == NULL || dd->default_factory == Py_None)
2014 args = PyTuple_New(0);
2015 else
2016 args = PyTuple_Pack(1, dd->default_factory);
2017 if (args == NULL)
2018 return NULL;
Victor Stinnerad8c83a2016-09-05 17:53:15 -07002019 items = _PyObject_CallMethodId((PyObject *)dd, &PyId_items, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002020 if (items == NULL) {
2021 Py_DECREF(args);
2022 return NULL;
2023 }
2024 iter = PyObject_GetIter(items);
2025 if (iter == NULL) {
2026 Py_DECREF(items);
2027 Py_DECREF(args);
2028 return NULL;
2029 }
2030 result = PyTuple_Pack(5, Py_TYPE(dd), args,
2031 Py_None, Py_None, iter);
2032 Py_DECREF(iter);
2033 Py_DECREF(items);
2034 Py_DECREF(args);
2035 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00002036}
2037
2038static PyMethodDef defdict_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002039 {"__missing__", (PyCFunction)defdict_missing, METH_O,
2040 defdict_missing_doc},
2041 {"copy", (PyCFunction)defdict_copy, METH_NOARGS,
2042 defdict_copy_doc},
2043 {"__copy__", (PyCFunction)defdict_copy, METH_NOARGS,
2044 defdict_copy_doc},
2045 {"__reduce__", (PyCFunction)defdict_reduce, METH_NOARGS,
2046 reduce_doc},
2047 {NULL}
Guido van Rossum1968ad32006-02-25 22:38:04 +00002048};
2049
2050static PyMemberDef defdict_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002051 {"default_factory", T_OBJECT,
2052 offsetof(defdictobject, default_factory), 0,
2053 PyDoc_STR("Factory for default value called by __missing__().")},
2054 {NULL}
Guido van Rossum1968ad32006-02-25 22:38:04 +00002055};
2056
2057static void
2058defdict_dealloc(defdictobject *dd)
2059{
INADA Naokia6296d32017-08-24 14:55:17 +09002060 /* bpo-31095: UnTrack is needed before calling any callbacks */
2061 PyObject_GC_UnTrack(dd);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002062 Py_CLEAR(dd->default_factory);
2063 PyDict_Type.tp_dealloc((PyObject *)dd);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002064}
2065
Guido van Rossum1968ad32006-02-25 22:38:04 +00002066static PyObject *
2067defdict_repr(defdictobject *dd)
2068{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002069 PyObject *baserepr;
2070 PyObject *defrepr;
2071 PyObject *result;
2072 baserepr = PyDict_Type.tp_repr((PyObject *)dd);
2073 if (baserepr == NULL)
2074 return NULL;
2075 if (dd->default_factory == NULL)
2076 defrepr = PyUnicode_FromString("None");
2077 else
2078 {
2079 int status = Py_ReprEnter(dd->default_factory);
2080 if (status != 0) {
Antoine Pitrouf5f1fe02012-02-15 02:42:46 +01002081 if (status < 0) {
2082 Py_DECREF(baserepr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002083 return NULL;
Antoine Pitrouf5f1fe02012-02-15 02:42:46 +01002084 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002085 defrepr = PyUnicode_FromString("...");
2086 }
2087 else
2088 defrepr = PyObject_Repr(dd->default_factory);
2089 Py_ReprLeave(dd->default_factory);
2090 }
2091 if (defrepr == NULL) {
2092 Py_DECREF(baserepr);
2093 return NULL;
2094 }
Serhiy Storchakab3a77962017-09-21 14:24:13 +03002095 result = PyUnicode_FromFormat("%s(%U, %U)",
2096 _PyType_Name(Py_TYPE(dd)),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002097 defrepr, baserepr);
2098 Py_DECREF(defrepr);
2099 Py_DECREF(baserepr);
2100 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00002101}
2102
2103static int
2104defdict_traverse(PyObject *self, visitproc visit, void *arg)
2105{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002106 Py_VISIT(((defdictobject *)self)->default_factory);
2107 return PyDict_Type.tp_traverse(self, visit, arg);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002108}
2109
2110static int
2111defdict_tp_clear(defdictobject *dd)
2112{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002113 Py_CLEAR(dd->default_factory);
2114 return PyDict_Type.tp_clear((PyObject *)dd);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002115}
2116
2117static int
2118defdict_init(PyObject *self, PyObject *args, PyObject *kwds)
2119{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002120 defdictobject *dd = (defdictobject *)self;
2121 PyObject *olddefault = dd->default_factory;
2122 PyObject *newdefault = NULL;
2123 PyObject *newargs;
2124 int result;
2125 if (args == NULL || !PyTuple_Check(args))
2126 newargs = PyTuple_New(0);
2127 else {
2128 Py_ssize_t n = PyTuple_GET_SIZE(args);
2129 if (n > 0) {
2130 newdefault = PyTuple_GET_ITEM(args, 0);
2131 if (!PyCallable_Check(newdefault) && newdefault != Py_None) {
2132 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger239aba72015-07-20 03:09:22 -04002133 "first argument must be callable or None");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002134 return -1;
2135 }
2136 }
2137 newargs = PySequence_GetSlice(args, 1, n);
2138 }
2139 if (newargs == NULL)
2140 return -1;
2141 Py_XINCREF(newdefault);
2142 dd->default_factory = newdefault;
2143 result = PyDict_Type.tp_init(self, newargs, kwds);
2144 Py_DECREF(newargs);
2145 Py_XDECREF(olddefault);
2146 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00002147}
2148
2149PyDoc_STRVAR(defdict_doc,
Benjamin Peterson9cb33b72014-01-13 23:56:05 -05002150"defaultdict(default_factory[, ...]) --> dict with default factory\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00002151\n\
2152The default factory is called without arguments to produce\n\
2153a new value when a key is not present, in __getitem__ only.\n\
2154A defaultdict compares equal to a dict with the same items.\n\
Benjamin Peterson9cb33b72014-01-13 23:56:05 -05002155All remaining arguments are treated the same as if they were\n\
2156passed to the dict constructor, including keyword arguments.\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00002157");
2158
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002159/* See comment in xxsubtype.c */
2160#define DEFERRED_ADDRESS(ADDR) 0
2161
Guido van Rossum1968ad32006-02-25 22:38:04 +00002162static PyTypeObject defdict_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002163 PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0)
2164 "collections.defaultdict", /* tp_name */
2165 sizeof(defdictobject), /* tp_basicsize */
2166 0, /* tp_itemsize */
2167 /* methods */
2168 (destructor)defdict_dealloc, /* tp_dealloc */
2169 0, /* tp_print */
2170 0, /* tp_getattr */
2171 0, /* tp_setattr */
2172 0, /* tp_reserved */
2173 (reprfunc)defdict_repr, /* tp_repr */
2174 0, /* tp_as_number */
2175 0, /* tp_as_sequence */
2176 0, /* tp_as_mapping */
2177 0, /* tp_hash */
2178 0, /* tp_call */
2179 0, /* tp_str */
2180 PyObject_GenericGetAttr, /* tp_getattro */
2181 0, /* tp_setattro */
2182 0, /* tp_as_buffer */
2183 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
2184 /* tp_flags */
2185 defdict_doc, /* tp_doc */
2186 defdict_traverse, /* tp_traverse */
2187 (inquiry)defdict_tp_clear, /* tp_clear */
2188 0, /* tp_richcompare */
2189 0, /* tp_weaklistoffset*/
2190 0, /* tp_iter */
2191 0, /* tp_iternext */
2192 defdict_methods, /* tp_methods */
2193 defdict_members, /* tp_members */
2194 0, /* tp_getset */
2195 DEFERRED_ADDRESS(&PyDict_Type), /* tp_base */
2196 0, /* tp_dict */
2197 0, /* tp_descr_get */
2198 0, /* tp_descr_set */
2199 0, /* tp_dictoffset */
2200 defdict_init, /* tp_init */
2201 PyType_GenericAlloc, /* tp_alloc */
2202 0, /* tp_new */
2203 PyObject_GC_Del, /* tp_free */
Guido van Rossum1968ad32006-02-25 22:38:04 +00002204};
2205
Raymond Hettinger96f34102010-12-15 16:30:37 +00002206/* helper function for Counter *********************************************/
2207
2208PyDoc_STRVAR(_count_elements_doc,
2209"_count_elements(mapping, iterable) -> None\n\
2210\n\
Raymond Hettingera24dca62017-01-12 22:25:25 -08002211Count elements in the iterable, updating the mapping");
Raymond Hettinger96f34102010-12-15 16:30:37 +00002212
2213static PyObject *
2214_count_elements(PyObject *self, PyObject *args)
2215{
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002216 _Py_IDENTIFIER(get);
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002217 _Py_IDENTIFIER(__setitem__);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002218 PyObject *it, *iterable, *mapping, *oldval;
2219 PyObject *newval = NULL;
2220 PyObject *key = NULL;
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002221 PyObject *bound_get = NULL;
2222 PyObject *mapping_get;
2223 PyObject *dict_get;
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002224 PyObject *mapping_setitem;
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002225 PyObject *dict_setitem;
Raymond Hettinger96f34102010-12-15 16:30:37 +00002226
2227 if (!PyArg_UnpackTuple(args, "_count_elements", 2, 2, &mapping, &iterable))
2228 return NULL;
2229
Raymond Hettinger96f34102010-12-15 16:30:37 +00002230 it = PyObject_GetIter(iterable);
2231 if (it == NULL)
2232 return NULL;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002233
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002234 /* Only take the fast path when get() and __setitem__()
2235 * have not been overridden.
2236 */
2237 mapping_get = _PyType_LookupId(Py_TYPE(mapping), &PyId_get);
2238 dict_get = _PyType_LookupId(&PyDict_Type, &PyId_get);
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002239 mapping_setitem = _PyType_LookupId(Py_TYPE(mapping), &PyId___setitem__);
2240 dict_setitem = _PyType_LookupId(&PyDict_Type, &PyId___setitem__);
2241
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002242 if (mapping_get != NULL && mapping_get == dict_get &&
Oren Milman31aca4b2017-09-27 06:18:21 +03002243 mapping_setitem != NULL && mapping_setitem == dict_setitem &&
2244 PyDict_Check(mapping))
2245 {
Raymond Hettinger426e0522011-01-03 02:12:02 +00002246 while (1) {
Raymond Hettinger507d9972014-05-18 21:32:40 +01002247 /* Fast path advantages:
2248 1. Eliminate double hashing
2249 (by re-using the same hash for both the get and set)
2250 2. Avoid argument overhead of PyObject_CallFunctionObjArgs
2251 (argument tuple creation and parsing)
2252 3. Avoid indirection through a bound method object
2253 (creates another argument tuple)
2254 4. Avoid initial increment from zero
2255 (reuse an existing one-object instead)
2256 */
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002257 Py_hash_t hash;
2258
Raymond Hettinger426e0522011-01-03 02:12:02 +00002259 key = PyIter_Next(it);
Victor Stinnera154b5c2011-04-20 23:23:52 +02002260 if (key == NULL)
2261 break;
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002262
2263 if (!PyUnicode_CheckExact(key) ||
2264 (hash = ((PyASCIIObject *) key)->hash) == -1)
2265 {
2266 hash = PyObject_Hash(key);
Raymond Hettingerda2850f2015-02-27 12:42:54 -08002267 if (hash == -1)
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002268 goto done;
2269 }
2270
2271 oldval = _PyDict_GetItem_KnownHash(mapping, key, hash);
Raymond Hettinger426e0522011-01-03 02:12:02 +00002272 if (oldval == NULL) {
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02002273 if (PyErr_Occurred())
2274 goto done;
Serhiy Storchakaba85d692017-03-30 09:09:41 +03002275 if (_PyDict_SetItem_KnownHash(mapping, key, _PyLong_One, hash) < 0)
Raymond Hettinger507d9972014-05-18 21:32:40 +01002276 goto done;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002277 } else {
Serhiy Storchakaba85d692017-03-30 09:09:41 +03002278 newval = PyNumber_Add(oldval, _PyLong_One);
Raymond Hettinger426e0522011-01-03 02:12:02 +00002279 if (newval == NULL)
Raymond Hettinger507d9972014-05-18 21:32:40 +01002280 goto done;
Raymond Hettinger28c995d2015-08-14 02:07:41 -07002281 if (_PyDict_SetItem_KnownHash(mapping, key, newval, hash) < 0)
Raymond Hettinger507d9972014-05-18 21:32:40 +01002282 goto done;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002283 Py_CLEAR(newval);
2284 }
2285 Py_DECREF(key);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002286 }
Raymond Hettinger426e0522011-01-03 02:12:02 +00002287 } else {
Victor Stinnere7f516c2013-11-06 23:52:55 +01002288 bound_get = _PyObject_GetAttrId(mapping, &PyId_get);
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002289 if (bound_get == NULL)
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002290 goto done;
2291
Raymond Hettinger426e0522011-01-03 02:12:02 +00002292 while (1) {
2293 key = PyIter_Next(it);
Victor Stinnera154b5c2011-04-20 23:23:52 +02002294 if (key == NULL)
2295 break;
Serhiy Storchakaba85d692017-03-30 09:09:41 +03002296 oldval = PyObject_CallFunctionObjArgs(bound_get, key, _PyLong_Zero, NULL);
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002297 if (oldval == NULL)
2298 break;
Serhiy Storchakaba85d692017-03-30 09:09:41 +03002299 newval = PyNumber_Add(oldval, _PyLong_One);
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002300 Py_DECREF(oldval);
2301 if (newval == NULL)
2302 break;
Raymond Hettinger28c995d2015-08-14 02:07:41 -07002303 if (PyObject_SetItem(mapping, key, newval) < 0)
Raymond Hettinger96f34102010-12-15 16:30:37 +00002304 break;
2305 Py_CLEAR(newval);
Raymond Hettinger426e0522011-01-03 02:12:02 +00002306 Py_DECREF(key);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002307 }
Raymond Hettinger96f34102010-12-15 16:30:37 +00002308 }
Raymond Hettinger426e0522011-01-03 02:12:02 +00002309
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002310done:
Raymond Hettinger96f34102010-12-15 16:30:37 +00002311 Py_DECREF(it);
2312 Py_XDECREF(key);
2313 Py_XDECREF(newval);
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002314 Py_XDECREF(bound_get);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002315 if (PyErr_Occurred())
2316 return NULL;
2317 Py_RETURN_NONE;
2318}
2319
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002320/* module level code ********************************************************/
2321
2322PyDoc_STRVAR(module_doc,
Guido van Rossum1968ad32006-02-25 22:38:04 +00002323"High performance data structures.\n\
2324- deque: ordered collection accessible from endpoints only\n\
2325- defaultdict: dict subclass with a default value factory\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002326");
2327
Raymond Hettinger96f34102010-12-15 16:30:37 +00002328static struct PyMethodDef module_functions[] = {
2329 {"_count_elements", _count_elements, METH_VARARGS, _count_elements_doc},
2330 {NULL, NULL} /* sentinel */
2331};
Martin v. Löwis1a214512008-06-11 05:26:20 +00002332
2333static struct PyModuleDef _collectionsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002334 PyModuleDef_HEAD_INIT,
2335 "_collections",
2336 module_doc,
2337 -1,
Raymond Hettinger96f34102010-12-15 16:30:37 +00002338 module_functions,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002339 NULL,
2340 NULL,
2341 NULL,
2342 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002343};
2344
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002345PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002346PyInit__collections(void)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002347{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002348 PyObject *m;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002350 m = PyModule_Create(&_collectionsmodule);
2351 if (m == NULL)
2352 return NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002353
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002354 if (PyType_Ready(&deque_type) < 0)
2355 return NULL;
2356 Py_INCREF(&deque_type);
2357 PyModule_AddObject(m, "deque", (PyObject *)&deque_type);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002359 defdict_type.tp_base = &PyDict_Type;
2360 if (PyType_Ready(&defdict_type) < 0)
2361 return NULL;
2362 Py_INCREF(&defdict_type);
2363 PyModule_AddObject(m, "defaultdict", (PyObject *)&defdict_type);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002364
Eric Snow47db7172015-05-29 22:21:39 -06002365 Py_INCREF(&PyODict_Type);
2366 PyModule_AddObject(m, "OrderedDict", (PyObject *)&PyODict_Type);
2367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002368 if (PyType_Ready(&dequeiter_type) < 0)
2369 return NULL;
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002370 Py_INCREF(&dequeiter_type);
2371 PyModule_AddObject(m, "_deque_iterator", (PyObject *)&dequeiter_type);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002373 if (PyType_Ready(&dequereviter_type) < 0)
2374 return NULL;
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002375 Py_INCREF(&dequereviter_type);
2376 PyModule_AddObject(m, "_deque_reverse_iterator", (PyObject *)&dequereviter_type);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00002377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002378 return m;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002379}