blob: 3410dfec07f8593b58599adc682a1647a2d5eb0d [file] [log] [blame]
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001#include "Python.h"
Raymond Hettinger691d8052004-05-30 07:26:47 +00002#include "structmember.h"
Raymond Hettinger756b3f32004-01-29 06:37:52 +00003
Raymond Hettingerc2083082015-02-28 23:29:16 -08004#ifdef STDC_HEADERS
5#include <stddef.h>
6#else
7#include <sys/types.h> /* For size_t */
8#endif
9
Raymond Hettinger756b3f32004-01-29 06:37:52 +000010/* collections module implementation of a deque() datatype
11 Written and maintained by Raymond D. Hettinger <python@rcn.com>
Raymond Hettinger756b3f32004-01-29 06:37:52 +000012*/
13
Raymond Hettinger77e8bf12004-10-01 15:25:53 +000014/* The block length may be set to any number over 1. Larger numbers
Raymond Hettinger20b0f872013-06-23 15:44:33 -070015 * reduce the number of calls to the memory allocator, give faster
Raymond Hettinger30c90742015-03-02 22:31:35 -080016 * indexing and rotation, and reduce the link to data overhead ratio.
Raymond Hettingerdaf57f22015-02-26 23:21:29 -080017 * Making the block length a power of two speeds-up the modulo
Raymond Hettinger30c90742015-03-02 22:31:35 -080018 * and division calculations in deque_item() and deque_ass_item().
Raymond Hettinger77e8bf12004-10-01 15:25:53 +000019 */
20
Raymond Hettingerdaf57f22015-02-26 23:21:29 -080021#define BLOCKLEN 64
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000022#define CENTER ((BLOCKLEN - 1) / 2)
Raymond Hettinger756b3f32004-01-29 06:37:52 +000023
Raymond Hettinger551350a2015-03-24 00:19:53 -070024/* Data for deque objects is stored in a doubly-linked list of fixed
25 * length blocks. This assures that appends or pops never move any
26 * other data elements besides the one being appended or popped.
27 *
28 * Another advantage is that it completely avoids use of realloc(),
29 * resulting in more predictable performance.
30 *
31 * Textbook implementations of doubly-linked lists store one datum
32 * per link, but that gives them a 200% memory overhead (a prev and
33 * next link for each datum) and it costs one malloc() call per data
34 * element. By using fixed-length blocks, the link to data ratio is
35 * significantly improved and there are proportionally fewer calls
36 * to malloc() and free(). The data blocks of consecutive pointers
37 * also improve cache locality.
38 *
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000039 * The list of blocks is never empty, so d.leftblock and d.rightblock
Raymond Hettinger82df9252013-07-07 01:43:42 -100040 * are never equal to NULL. The list is not circular.
41 *
42 * A deque d's first element is at d.leftblock[leftindex]
43 * and its last element is at d.rightblock[rightindex].
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000044 *
Raymond Hettinger551350a2015-03-24 00:19:53 -070045 * Unlike Python slice indices, these indices are inclusive on both
46 * ends. This makes the algorithms for left and right operations
47 * more symmetrical and it simplifies the design.
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000048 *
Raymond Hettinger551350a2015-03-24 00:19:53 -070049 * The indices, d.leftindex and d.rightindex are always in the range:
50 * 0 <= index < BLOCKLEN
51 *
52 * And their exact relationship is:
53 * (d.leftindex + d.len - 1) % BLOCKLEN == d.rightindex
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000054 *
Raymond Hettinger8dbbae22015-03-24 21:01:50 -070055 * Whenever d.leftblock == d.rightblock, then:
Raymond Hettinger551350a2015-03-24 00:19:53 -070056 * d.leftindex + d.len - 1 == d.rightindex
Thomas Wouters0e3f5912006-08-11 14:57:12 +000057 *
Raymond Hettinger551350a2015-03-24 00:19:53 -070058 * However, when d.leftblock != d.rightblock, the d.leftindex and
59 * d.rightindex become indices into distinct blocks and either may
60 * be larger than the other.
61 *
62 * Empty deques have:
63 * d.len == 0
64 * d.leftblock == d.rightblock
65 * d.leftindex == CENTER + 1
66 * d.rightindex == CENTER
67 *
68 * Checking for d.len == 0 is the intended way to see whether d is empty.
Tim Petersd8768d32004-10-01 01:32:53 +000069 */
70
Raymond Hettinger756b3f32004-01-29 06:37:52 +000071typedef struct BLOCK {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000072 struct BLOCK *leftlink;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000073 PyObject *data[BLOCKLEN];
Raymond Hettinger20b0f872013-06-23 15:44:33 -070074 struct BLOCK *rightlink;
Raymond Hettinger756b3f32004-01-29 06:37:52 +000075} block;
76
Raymond Hettinger30c90742015-03-02 22:31:35 -080077typedef struct {
78 PyObject_VAR_HEAD
79 block *leftblock;
80 block *rightblock;
Raymond Hettinger551350a2015-03-24 00:19:53 -070081 Py_ssize_t leftindex; /* 0 <= leftindex < BLOCKLEN */
82 Py_ssize_t rightindex; /* 0 <= rightindex < BLOCKLEN */
Raymond Hettingerf9d9c792015-03-02 22:47:46 -080083 size_t state; /* incremented whenever the indices move */
Raymond Hettingerd84ec222016-01-24 09:12:06 -080084 Py_ssize_t maxlen; /* maxlen is -1 for unbounded deques */
Raymond Hettinger0f6f9472015-03-21 01:42:10 -070085 PyObject *weakreflist;
Raymond Hettinger30c90742015-03-02 22:31:35 -080086} dequeobject;
87
88static PyTypeObject deque_type;
89
Raymond Hettinger82df9252013-07-07 01:43:42 -100090/* For debug builds, add error checking to track the endpoints
91 * in the chain of links. The goal is to make sure that link
92 * assignments only take place at endpoints so that links already
93 * in use do not get overwritten.
94 *
95 * CHECK_END should happen before each assignment to a block's link field.
96 * MARK_END should happen whenever a link field becomes a new endpoint.
97 * This happens when new blocks are added or whenever an existing
98 * block is freed leaving another existing block as the new endpoint.
99 */
100
Raymond Hettinger3223dd52013-07-26 23:14:22 -0700101#ifndef NDEBUG
Raymond Hettinger82df9252013-07-07 01:43:42 -1000102#define MARK_END(link) link = NULL;
103#define CHECK_END(link) assert(link == NULL);
104#define CHECK_NOT_END(link) assert(link != NULL);
105#else
106#define MARK_END(link)
107#define CHECK_END(link)
108#define CHECK_NOT_END(link)
109#endif
110
111/* A simple freelisting scheme is used to minimize calls to the memory
Raymond Hettinger551350a2015-03-24 00:19:53 -0700112 allocator. It accommodates common use cases where new blocks are being
Raymond Hettinger82df9252013-07-07 01:43:42 -1000113 added at about the same rate as old blocks are being freed.
114 */
115
Raymond Hettingerf2b02ce2015-09-26 17:47:02 -0700116#define MAXFREEBLOCKS 16
Benjamin Petersond6313712008-07-31 16:23:04 +0000117static Py_ssize_t numfreeblocks = 0;
Guido van Rossum58da9312007-11-10 23:39:45 +0000118static block *freeblocks[MAXFREEBLOCKS];
119
Tim Peters6f853562004-10-01 01:04:50 +0000120static block *
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700121newblock(void) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000122 block *b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000123 if (numfreeblocks) {
Raymond Hettinger59cf23a2013-02-07 00:57:19 -0500124 numfreeblocks--;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000125 return freeblocks[numfreeblocks];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000126 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000127 b = PyMem_Malloc(sizeof(block));
128 if (b != NULL) {
129 return b;
130 }
131 PyErr_NoMemory();
132 return NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000133}
134
Martin v. Löwis59683e82008-06-13 07:50:45 +0000135static void
Guido van Rossum58da9312007-11-10 23:39:45 +0000136freeblock(block *b)
137{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000138 if (numfreeblocks < MAXFREEBLOCKS) {
139 freeblocks[numfreeblocks] = b;
140 numfreeblocks++;
141 } else {
142 PyMem_Free(b);
143 }
Guido van Rossum58da9312007-11-10 23:39:45 +0000144}
145
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000146static PyObject *
147deque_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
148{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000149 dequeobject *deque;
150 block *b;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000152 /* create dequeobject structure */
153 deque = (dequeobject *)type->tp_alloc(type, 0);
154 if (deque == NULL)
155 return NULL;
Tim Peters1065f752004-10-01 01:03:29 +0000156
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700157 b = newblock();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000158 if (b == NULL) {
159 Py_DECREF(deque);
160 return NULL;
161 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000162 MARK_END(b->leftlink);
163 MARK_END(b->rightlink);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000165 assert(BLOCKLEN >= 2);
Raymond Hettinger87e69122015-03-02 23:32:02 -0800166 Py_SIZE(deque) = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000167 deque->leftblock = b;
168 deque->rightblock = b;
169 deque->leftindex = CENTER + 1;
170 deque->rightindex = CENTER;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000171 deque->state = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000172 deque->maxlen = -1;
Raymond Hettinger87e69122015-03-02 23:32:02 -0800173 deque->weakreflist = NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175 return (PyObject *)deque;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000176}
177
178static PyObject *
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000179deque_pop(dequeobject *deque, PyObject *unused)
180{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000181 PyObject *item;
182 block *prevblock;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000183
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000184 if (Py_SIZE(deque) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000185 PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
186 return NULL;
187 }
188 item = deque->rightblock->data[deque->rightindex];
189 deque->rightindex--;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000190 Py_SIZE(deque)--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000191 deque->state++;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000192
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -0700193 if (deque->rightindex < 0) {
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700194 if (Py_SIZE(deque)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000195 prevblock = deque->rightblock->leftlink;
196 assert(deque->leftblock != deque->rightblock);
197 freeblock(deque->rightblock);
Raymond Hettinger82df9252013-07-07 01:43:42 -1000198 CHECK_NOT_END(prevblock);
199 MARK_END(prevblock->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000200 deque->rightblock = prevblock;
201 deque->rightindex = BLOCKLEN - 1;
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700202 } else {
203 assert(deque->leftblock == deque->rightblock);
204 assert(deque->leftindex == deque->rightindex+1);
205 /* re-center instead of freeing a block */
206 deque->leftindex = CENTER + 1;
207 deque->rightindex = CENTER;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000208 }
209 }
210 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000211}
212
213PyDoc_STRVAR(pop_doc, "Remove and return the rightmost element.");
214
215static PyObject *
216deque_popleft(dequeobject *deque, PyObject *unused)
217{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000218 PyObject *item;
219 block *prevblock;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000220
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000221 if (Py_SIZE(deque) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000222 PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
223 return NULL;
224 }
225 assert(deque->leftblock != NULL);
226 item = deque->leftblock->data[deque->leftindex];
227 deque->leftindex++;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000228 Py_SIZE(deque)--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000229 deque->state++;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000231 if (deque->leftindex == BLOCKLEN) {
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700232 if (Py_SIZE(deque)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000233 assert(deque->leftblock != deque->rightblock);
234 prevblock = deque->leftblock->rightlink;
235 freeblock(deque->leftblock);
Raymond Hettinger82df9252013-07-07 01:43:42 -1000236 CHECK_NOT_END(prevblock);
237 MARK_END(prevblock->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000238 deque->leftblock = prevblock;
239 deque->leftindex = 0;
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700240 } else {
241 assert(deque->leftblock == deque->rightblock);
242 assert(deque->leftindex == deque->rightindex+1);
243 /* re-center instead of freeing a block */
244 deque->leftindex = CENTER + 1;
245 deque->rightindex = CENTER;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000246 }
247 }
248 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000249}
250
251PyDoc_STRVAR(popleft_doc, "Remove and return the leftmost element.");
252
Raymond Hettingerf30f5b92015-03-02 22:23:37 -0800253/* The deque's size limit is d.maxlen. The limit can be zero or positive.
254 * If there is no limit, then d.maxlen == -1.
255 *
Raymond Hettingera4b13d02015-10-15 08:05:31 -0700256 * After an item is added to a deque, we check to see if the size has
257 * grown past the limit. If it has, we get the size back down to the limit
258 * by popping an item off of the opposite end. The methods that can
259 * trigger this are append(), appendleft(), extend(), and extendleft().
Raymond Hettingerd96db092015-10-11 22:34:48 -0700260 *
261 * The macro to check whether a deque needs to be trimmed uses a single
262 * unsigned test that returns true whenever 0 <= maxlen < Py_SIZE(deque).
Raymond Hettingerf30f5b92015-03-02 22:23:37 -0800263 */
264
Raymond Hettingerd96db092015-10-11 22:34:48 -0700265#define NEEDS_TRIM(deque, maxlen) ((size_t)(maxlen) < (size_t)(Py_SIZE(deque)))
Raymond Hettingerf30f5b92015-03-02 22:23:37 -0800266
doko@ubuntu.combc731502016-05-18 01:06:01 +0200267static int
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800268deque_append_internal(dequeobject *deque, PyObject *item, Py_ssize_t maxlen)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000269{
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700270 if (deque->rightindex == BLOCKLEN - 1) {
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700271 block *b = newblock();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000272 if (b == NULL)
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800273 return -1;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000274 b->leftlink = deque->rightblock;
275 CHECK_END(deque->rightblock->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000276 deque->rightblock->rightlink = b;
277 deque->rightblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000278 MARK_END(b->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000279 deque->rightindex = -1;
280 }
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000281 Py_SIZE(deque)++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000282 deque->rightindex++;
283 deque->rightblock->data[deque->rightindex] = item;
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800284 if (NEEDS_TRIM(deque, maxlen)) {
Raymond Hettinger1286d142015-10-14 23:16:57 -0700285 PyObject *olditem = deque_popleft(deque, NULL);
286 Py_DECREF(olditem);
Raymond Hettinger0f43bb12015-10-20 00:03:33 -0700287 } else {
288 deque->state++;
Raymond Hettingerd96db092015-10-11 22:34:48 -0700289 }
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800290 return 0;
291}
292
293static PyObject *
294deque_append(dequeobject *deque, PyObject *item)
295{
296 Py_INCREF(item);
297 if (deque_append_internal(deque, item, deque->maxlen) < 0)
298 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000299 Py_RETURN_NONE;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000300}
301
302PyDoc_STRVAR(append_doc, "Add an element to the right side of the deque.");
303
doko@ubuntu.com17f0e612016-06-14 07:27:58 +0200304static int
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800305deque_appendleft_internal(dequeobject *deque, PyObject *item, Py_ssize_t maxlen)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000306{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000307 if (deque->leftindex == 0) {
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700308 block *b = newblock();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000309 if (b == NULL)
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800310 return -1;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000311 b->rightlink = deque->leftblock;
312 CHECK_END(deque->leftblock->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000313 deque->leftblock->leftlink = b;
314 deque->leftblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000315 MARK_END(b->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000316 deque->leftindex = BLOCKLEN;
317 }
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000318 Py_SIZE(deque)++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000319 deque->leftindex--;
320 deque->leftblock->data[deque->leftindex] = item;
Raymond Hettingerd96db092015-10-11 22:34:48 -0700321 if (NEEDS_TRIM(deque, deque->maxlen)) {
Raymond Hettinger1286d142015-10-14 23:16:57 -0700322 PyObject *olditem = deque_pop(deque, NULL);
323 Py_DECREF(olditem);
Raymond Hettinger0f43bb12015-10-20 00:03:33 -0700324 } else {
325 deque->state++;
Raymond Hettingerd96db092015-10-11 22:34:48 -0700326 }
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800327 return 0;
328}
329
330static PyObject *
331deque_appendleft(dequeobject *deque, PyObject *item)
332{
333 Py_INCREF(item);
334 if (deque_appendleft_internal(deque, item, deque->maxlen) < 0)
335 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000336 Py_RETURN_NONE;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000337}
338
339PyDoc_STRVAR(appendleft_doc, "Add an element to the left side of the deque.");
340
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700341static PyObject*
342finalize_iterator(PyObject *it)
343{
344 if (PyErr_Occurred()) {
345 if (PyErr_ExceptionMatches(PyExc_StopIteration))
346 PyErr_Clear();
347 else {
348 Py_DECREF(it);
349 return NULL;
350 }
351 }
352 Py_DECREF(it);
353 Py_RETURN_NONE;
354}
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000356/* Run an iterator to exhaustion. Shortcut for
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000357 the extend/extendleft methods when maxlen == 0. */
358static PyObject*
359consume_iterator(PyObject *it)
360{
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700361 PyObject *(*iternext)(PyObject *);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000362 PyObject *item;
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000363
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700364 iternext = *Py_TYPE(it)->tp_iternext;
365 while ((item = iternext(it)) != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000366 Py_DECREF(item);
367 }
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700368 return finalize_iterator(it);
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000369}
370
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000371static PyObject *
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000372deque_extend(dequeobject *deque, PyObject *iterable)
373{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000374 PyObject *it, *item;
Raymond Hettinger7a845522015-09-26 01:30:51 -0700375 PyObject *(*iternext)(PyObject *);
Raymond Hettinger6b1e1132015-10-11 09:43:50 -0700376 Py_ssize_t maxlen = deque->maxlen;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000378 /* Handle case where id(deque) == id(iterable) */
379 if ((PyObject *)deque == iterable) {
380 PyObject *result;
381 PyObject *s = PySequence_List(iterable);
382 if (s == NULL)
383 return NULL;
384 result = deque_extend(deque, s);
385 Py_DECREF(s);
386 return result;
387 }
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000388
Raymond Hettingerd79d5b12016-03-04 09:55:07 -0800389 it = PyObject_GetIter(iterable);
390 if (it == NULL)
391 return NULL;
392
393 if (maxlen == 0)
394 return consume_iterator(it);
395
Raymond Hettingerd9c116c2013-07-09 00:13:21 -0700396 /* Space saving heuristic. Start filling from the left */
397 if (Py_SIZE(deque) == 0) {
398 assert(deque->leftblock == deque->rightblock);
399 assert(deque->leftindex == deque->rightindex+1);
400 deque->leftindex = 1;
401 deque->rightindex = 0;
402 }
403
Raymond Hettinger7a845522015-09-26 01:30:51 -0700404 iternext = *Py_TYPE(it)->tp_iternext;
405 while ((item = iternext(it)) != NULL) {
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800406 if (deque_append_internal(deque, item, maxlen) < 0) {
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 Hettingerd84ec222016-01-24 09:12:06 -0800453 if (deque_appendleft_internal(deque, item, maxlen) < 0) {
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 *
479deque_copy(PyObject *deque)
480{
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)
505 return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "O", deque, NULL);
506 else
507 return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "Oi",
508 deque, old_deque->maxlen, NULL);
509}
510
511PyDoc_STRVAR(copy_doc, "Return a shallow copy of a deque.");
Raymond Hettinger41290a62015-03-31 08:12:23 -0700512
513static PyObject *
514deque_concat(dequeobject *deque, PyObject *other)
515{
Benjamin Peterson1a629212015-04-04 10:52:36 -0400516 PyObject *new_deque, *result;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700517 int rv;
518
519 rv = PyObject_IsInstance(other, (PyObject *)&deque_type);
520 if (rv <= 0) {
521 if (rv == 0) {
522 PyErr_Format(PyExc_TypeError,
523 "can only concatenate deque (not \"%.200s\") to deque",
524 other->ob_type->tp_name);
525 }
526 return NULL;
527 }
528
529 new_deque = deque_copy((PyObject *)deque);
530 if (new_deque == NULL)
531 return NULL;
Benjamin Peterson1a629212015-04-04 10:52:36 -0400532 result = deque_extend((dequeobject *)new_deque, other);
533 if (result == NULL) {
534 Py_DECREF(new_deque);
535 return NULL;
536 }
537 Py_DECREF(result);
538 return new_deque;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700539}
540
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700541static void
542deque_clear(dequeobject *deque)
543{
544 block *b;
545 block *prevblock;
546 block *leftblock;
547 Py_ssize_t leftindex;
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800548 Py_ssize_t n, m;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700549 PyObject *item;
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800550 PyObject **itemptr, **limit;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700551
Raymond Hettinger38031142015-09-29 22:45:05 -0700552 if (Py_SIZE(deque) == 0)
553 return;
554
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700555 /* During the process of clearing a deque, decrefs can cause the
556 deque to mutate. To avoid fatal confusion, we have to make the
557 deque empty before clearing the blocks and never refer to
558 anything via deque->ref while clearing. (This is the same
559 technique used for clearing lists, sets, and dicts.)
560
561 Making the deque empty requires allocating a new empty block. In
562 the unlikely event that memory is full, we fall back to an
563 alternate method that doesn't require a new block. Repeating
564 pops in a while-loop is slower, possibly re-entrant (and a clever
565 adversary could cause it to never terminate).
566 */
567
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700568 b = newblock();
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700569 if (b == NULL) {
570 PyErr_Clear();
571 goto alternate_method;
572 }
573
574 /* Remember the old size, leftblock, and leftindex */
Raymond Hettinger6f86a332016-03-02 00:30:58 -0800575 n = Py_SIZE(deque);
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700576 leftblock = deque->leftblock;
577 leftindex = deque->leftindex;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700578
579 /* Set the deque to be empty using the newly allocated block */
580 MARK_END(b->leftlink);
581 MARK_END(b->rightlink);
582 Py_SIZE(deque) = 0;
583 deque->leftblock = b;
584 deque->rightblock = b;
585 deque->leftindex = CENTER + 1;
586 deque->rightindex = CENTER;
587 deque->state++;
588
589 /* Now the old size, leftblock, and leftindex are disconnected from
590 the empty deque and we can use them to decref the pointers.
591 */
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800592 m = (BLOCKLEN - leftindex > n) ? n : BLOCKLEN - leftindex;
Raymond Hettinger589106b2016-03-02 00:06:21 -0800593 itemptr = &leftblock->data[leftindex];
Raymond Hettinger6f86a332016-03-02 00:30:58 -0800594 limit = itemptr + m;
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800595 n -= m;
596 while (1) {
597 if (itemptr == limit) {
598 if (n == 0)
599 break;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700600 CHECK_NOT_END(leftblock->rightlink);
601 prevblock = leftblock;
602 leftblock = leftblock->rightlink;
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800603 m = (n > BLOCKLEN) ? BLOCKLEN : n;
Raymond Hettinger589106b2016-03-02 00:06:21 -0800604 itemptr = leftblock->data;
Raymond Hettinger6f86a332016-03-02 00:30:58 -0800605 limit = itemptr + m;
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800606 n -= m;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700607 freeblock(prevblock);
608 }
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800609 item = *(itemptr++);
610 Py_DECREF(item);
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700611 }
612 CHECK_END(leftblock->rightlink);
613 freeblock(leftblock);
614 return;
615
616 alternate_method:
617 while (Py_SIZE(deque)) {
618 item = deque_pop(deque, NULL);
619 assert (item != NULL);
620 Py_DECREF(item);
621 }
622}
623
624static PyObject *
625deque_clearmethod(dequeobject *deque)
626{
627 deque_clear(deque);
628 Py_RETURN_NONE;
629}
630
631PyDoc_STRVAR(clear_doc, "Remove all elements from the deque.");
Raymond Hettinger41290a62015-03-31 08:12:23 -0700632
633static PyObject *
Raymond Hettinger41290a62015-03-31 08:12:23 -0700634deque_inplace_repeat(dequeobject *deque, Py_ssize_t n)
635{
Raymond Hettingerc22eee62015-09-26 02:14:50 -0700636 Py_ssize_t i, m, size;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700637 PyObject *seq;
638 PyObject *rv;
639
640 size = Py_SIZE(deque);
641 if (size == 0 || n == 1) {
642 Py_INCREF(deque);
643 return (PyObject *)deque;
644 }
645
646 if (n <= 0) {
647 deque_clear(deque);
648 Py_INCREF(deque);
649 return (PyObject *)deque;
650 }
651
Raymond Hettinger41290a62015-03-31 08:12:23 -0700652 if (size == 1) {
653 /* common case, repeating a single element */
654 PyObject *item = deque->leftblock->data[deque->leftindex];
655
Raymond Hettingera7f630092015-10-10 23:56:02 -0400656 if (deque->maxlen >= 0 && n > deque->maxlen)
Raymond Hettinger41290a62015-03-31 08:12:23 -0700657 n = deque->maxlen;
658
Raymond Hettinger67c78b52015-09-12 11:00:20 -0400659 deque->state++;
Raymond Hettingerad262252015-09-14 01:03:04 -0400660 for (i = 0 ; i < n-1 ; ) {
Raymond Hettinger67c78b52015-09-12 11:00:20 -0400661 if (deque->rightindex == BLOCKLEN - 1) {
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700662 block *b = newblock();
Raymond Hettinger67c78b52015-09-12 11:00:20 -0400663 if (b == NULL) {
664 Py_SIZE(deque) += i;
665 return NULL;
666 }
667 b->leftlink = deque->rightblock;
668 CHECK_END(deque->rightblock->rightlink);
669 deque->rightblock->rightlink = b;
670 deque->rightblock = b;
671 MARK_END(b->rightlink);
672 deque->rightindex = -1;
673 }
Raymond Hettingerc22eee62015-09-26 02:14:50 -0700674 m = n - 1 - i;
675 if (m > BLOCKLEN - 1 - deque->rightindex)
676 m = BLOCKLEN - 1 - deque->rightindex;
677 i += m;
678 while (m--) {
Raymond Hettingerad262252015-09-14 01:03:04 -0400679 deque->rightindex++;
680 Py_INCREF(item);
681 deque->rightblock->data[deque->rightindex] = item;
682 }
Raymond Hettinger41290a62015-03-31 08:12:23 -0700683 }
Raymond Hettinger67c78b52015-09-12 11:00:20 -0400684 Py_SIZE(deque) += i;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700685 Py_INCREF(deque);
686 return (PyObject *)deque;
687 }
688
Raymond Hettinger20151f52015-10-16 22:47:29 -0700689 if ((size_t)size > PY_SSIZE_T_MAX / (size_t)n) {
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400690 return PyErr_NoMemory();
691 }
692
Raymond Hettinger41290a62015-03-31 08:12:23 -0700693 seq = PySequence_List((PyObject *)deque);
694 if (seq == NULL)
695 return seq;
696
697 for (i = 0 ; i < n-1 ; i++) {
698 rv = deque_extend(deque, seq);
699 if (rv == NULL) {
700 Py_DECREF(seq);
701 return NULL;
702 }
703 Py_DECREF(rv);
704 }
705 Py_INCREF(deque);
706 Py_DECREF(seq);
707 return (PyObject *)deque;
708}
709
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400710static PyObject *
711deque_repeat(dequeobject *deque, Py_ssize_t n)
712{
713 dequeobject *new_deque;
Raymond Hettinger95e2cc52015-09-13 02:41:18 -0400714 PyObject *rv;
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400715
716 new_deque = (dequeobject *)deque_copy((PyObject *) deque);
717 if (new_deque == NULL)
718 return NULL;
Raymond Hettinger95e2cc52015-09-13 02:41:18 -0400719 rv = deque_inplace_repeat(new_deque, n);
720 Py_DECREF(new_deque);
721 return rv;
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400722}
723
Raymond Hettinger54023152014-04-23 00:58:48 -0700724/* The rotate() method is part of the public API and is used internally
725as a primitive for other methods.
726
727Rotation by 1 or -1 is a common case, so any optimizations for high
728volume rotations should take care not to penalize the common case.
729
730Conceptually, a rotate by one is equivalent to a pop on one side and an
731append on the other. However, a pop/append pair is unnecessarily slow
Martin Panterd2ad5712015-11-02 04:20:33 +0000732because it requires an incref/decref pair for an object located randomly
Raymond Hettinger54023152014-04-23 00:58:48 -0700733in memory. It is better to just move the object pointer from one block
734to the next without changing the reference count.
735
736When moving batches of pointers, it is tempting to use memcpy() but that
737proved to be slower than a simple loop for a variety of reasons.
738Memcpy() cannot know in advance that we're copying pointers instead of
739bytes, that the source and destination are pointer aligned and
740non-overlapping, that moving just one pointer is a common case, that we
741never need to move more than BLOCKLEN pointers, and that at least one
742pointer is always moved.
743
744For high volume rotations, newblock() and freeblock() are never called
745more than once. Previously emptied blocks are immediately reused as a
746destination block. If a block is left-over at the end, it is freed.
747*/
748
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000749static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000750_deque_rotate(dequeobject *deque, Py_ssize_t n)
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000751{
Raymond Hettinger3959af92013-07-13 02:34:08 -0700752 block *b = NULL;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700753 block *leftblock = deque->leftblock;
754 block *rightblock = deque->rightblock;
755 Py_ssize_t leftindex = deque->leftindex;
756 Py_ssize_t rightindex = deque->rightindex;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000757 Py_ssize_t len=Py_SIZE(deque), halflen=len>>1;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700758 int rv = -1;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000759
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800760 if (len <= 1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000761 return 0;
762 if (n > halflen || n < -halflen) {
763 n %= len;
764 if (n > halflen)
765 n -= len;
766 else if (n < -halflen)
767 n += len;
768 }
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500769 assert(len > 1);
Raymond Hettingera4409c12013-02-04 00:08:12 -0500770 assert(-halflen <= n && n <= halflen);
Raymond Hettinger231ee4d2013-02-02 11:24:43 -0800771
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800772 deque->state++;
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500773 while (n > 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700774 if (leftindex == 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700775 if (b == NULL) {
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700776 b = newblock();
Raymond Hettinger3959af92013-07-13 02:34:08 -0700777 if (b == NULL)
778 goto done;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700779 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000780 b->rightlink = leftblock;
781 CHECK_END(leftblock->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700782 leftblock->leftlink = b;
783 leftblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000784 MARK_END(b->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700785 leftindex = BLOCKLEN;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700786 b = NULL;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800787 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700788 assert(leftindex > 0);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700789 {
790 PyObject **src, **dest;
791 Py_ssize_t m = n;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800792
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700793 if (m > rightindex + 1)
794 m = rightindex + 1;
795 if (m > leftindex)
796 m = leftindex;
797 assert (m > 0 && m <= len);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700798 rightindex -= m;
799 leftindex -= m;
Raymond Hettinger0e259f12015-02-01 22:53:41 -0800800 src = &rightblock->data[rightindex + 1];
801 dest = &leftblock->data[leftindex];
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700802 n -= m;
Raymond Hettinger840533b2013-07-13 17:03:58 -0700803 do {
Raymond Hettinger0e259f12015-02-01 22:53:41 -0800804 *(dest++) = *(src++);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700805 } while (--m);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700806 }
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -0700807 if (rightindex < 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700808 assert(leftblock != rightblock);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700809 assert(b == NULL);
Raymond Hettinger3959af92013-07-13 02:34:08 -0700810 b = rightblock;
Raymond Hettingerb97cc492013-07-21 01:51:07 -0700811 CHECK_NOT_END(rightblock->leftlink);
812 rightblock = rightblock->leftlink;
813 MARK_END(rightblock->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700814 rightindex = BLOCKLEN - 1;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800815 }
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800816 }
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500817 while (n < 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700818 if (rightindex == BLOCKLEN - 1) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700819 if (b == NULL) {
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700820 b = newblock();
Raymond Hettinger3959af92013-07-13 02:34:08 -0700821 if (b == NULL)
822 goto done;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700823 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000824 b->leftlink = rightblock;
825 CHECK_END(rightblock->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700826 rightblock->rightlink = b;
827 rightblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000828 MARK_END(b->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700829 rightindex = -1;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700830 b = NULL;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800831 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700832 assert (rightindex < BLOCKLEN - 1);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700833 {
834 PyObject **src, **dest;
835 Py_ssize_t m = -n;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800836
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700837 if (m > BLOCKLEN - leftindex)
838 m = BLOCKLEN - leftindex;
839 if (m > BLOCKLEN - 1 - rightindex)
840 m = BLOCKLEN - 1 - rightindex;
841 assert (m > 0 && m <= len);
842 src = &leftblock->data[leftindex];
843 dest = &rightblock->data[rightindex + 1];
844 leftindex += m;
845 rightindex += m;
846 n += m;
Raymond Hettinger840533b2013-07-13 17:03:58 -0700847 do {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700848 *(dest++) = *(src++);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700849 } while (--m);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700850 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700851 if (leftindex == BLOCKLEN) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700852 assert(leftblock != rightblock);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700853 assert(b == NULL);
Raymond Hettinger3959af92013-07-13 02:34:08 -0700854 b = leftblock;
Raymond Hettingerb97cc492013-07-21 01:51:07 -0700855 CHECK_NOT_END(leftblock->rightlink);
856 leftblock = leftblock->rightlink;
857 MARK_END(leftblock->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700858 leftindex = 0;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800859 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000860 }
Raymond Hettinger3959af92013-07-13 02:34:08 -0700861 rv = 0;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700862done:
Raymond Hettinger3959af92013-07-13 02:34:08 -0700863 if (b != NULL)
864 freeblock(b);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700865 deque->leftblock = leftblock;
866 deque->rightblock = rightblock;
867 deque->leftindex = leftindex;
868 deque->rightindex = rightindex;
869
870 return rv;
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000871}
872
873static PyObject *
874deque_rotate(dequeobject *deque, PyObject *args)
875{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000876 Py_ssize_t n=1;
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000878 if (!PyArg_ParseTuple(args, "|n:rotate", &n))
879 return NULL;
Raymond Hettinger6921c132015-03-21 02:03:40 -0700880 if (!_deque_rotate(deque, n))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 Py_RETURN_NONE;
882 return NULL;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000883}
884
Tim Peters1065f752004-10-01 01:03:29 +0000885PyDoc_STRVAR(rotate_doc,
Raymond Hettingeree33b272004-02-08 04:05:26 +0000886"Rotate the deque n steps to the right (default n=1). If n is negative, rotates left.");
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000887
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000888static PyObject *
889deque_reverse(dequeobject *deque, PyObject *unused)
890{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000891 block *leftblock = deque->leftblock;
892 block *rightblock = deque->rightblock;
893 Py_ssize_t leftindex = deque->leftindex;
894 Py_ssize_t rightindex = deque->rightindex;
Raymond Hettingercfe5b6c2015-07-20 00:25:50 -0400895 Py_ssize_t n = Py_SIZE(deque) >> 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 PyObject *tmp;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000897
Raymond Hettinger306d6b12016-01-24 12:40:42 -0800898 n++;
899 while (--n) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000900 /* Validate that pointers haven't met in the middle */
901 assert(leftblock != rightblock || leftindex < rightindex);
Raymond Hettinger82df9252013-07-07 01:43:42 -1000902 CHECK_NOT_END(leftblock);
903 CHECK_NOT_END(rightblock);
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000904
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000905 /* Swap */
906 tmp = leftblock->data[leftindex];
907 leftblock->data[leftindex] = rightblock->data[rightindex];
908 rightblock->data[rightindex] = tmp;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000909
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 /* Advance left block/index pair */
911 leftindex++;
912 if (leftindex == BLOCKLEN) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 leftblock = leftblock->rightlink;
914 leftindex = 0;
915 }
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000916
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000917 /* Step backwards with the right block/index pair */
918 rightindex--;
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -0700919 if (rightindex < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 rightblock = rightblock->leftlink;
921 rightindex = BLOCKLEN - 1;
922 }
923 }
924 Py_RETURN_NONE;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000925}
926
927PyDoc_STRVAR(reverse_doc,
928"D.reverse() -- reverse *IN PLACE*");
929
Raymond Hettinger44459de2010-04-03 23:20:46 +0000930static PyObject *
931deque_count(dequeobject *deque, PyObject *v)
932{
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000933 block *b = deque->leftblock;
934 Py_ssize_t index = deque->leftindex;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000935 Py_ssize_t n = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 Py_ssize_t count = 0;
Raymond Hettingerf9d9c792015-03-02 22:47:46 -0800937 size_t start_state = deque->state;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 PyObject *item;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 int cmp;
Raymond Hettinger44459de2010-04-03 23:20:46 +0000940
Raymond Hettinger165eee22016-01-24 11:32:07 -0800941 n++;
942 while (--n) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000943 CHECK_NOT_END(b);
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000944 item = b->data[index];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000945 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
Raymond Hettinger2b0d6462015-09-23 19:15:44 -0700946 if (cmp < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 return NULL;
Raymond Hettinger2b0d6462015-09-23 19:15:44 -0700948 count += cmp;
Raymond Hettinger44459de2010-04-03 23:20:46 +0000949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 if (start_state != deque->state) {
951 PyErr_SetString(PyExc_RuntimeError,
952 "deque mutated during iteration");
953 return NULL;
954 }
Raymond Hettinger44459de2010-04-03 23:20:46 +0000955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000956 /* Advance left block/index pair */
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000957 index++;
958 if (index == BLOCKLEN) {
959 b = b->rightlink;
960 index = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000961 }
962 }
963 return PyLong_FromSsize_t(count);
Raymond Hettinger44459de2010-04-03 23:20:46 +0000964}
965
966PyDoc_STRVAR(count_doc,
967"D.count(value) -> integer -- return number of occurrences of value");
968
Raymond Hettinger39dadf72015-03-20 16:38:56 -0700969static int
970deque_contains(dequeobject *deque, PyObject *v)
971{
972 block *b = deque->leftblock;
973 Py_ssize_t index = deque->leftindex;
974 Py_ssize_t n = Py_SIZE(deque);
Raymond Hettinger39dadf72015-03-20 16:38:56 -0700975 size_t start_state = deque->state;
976 PyObject *item;
977 int cmp;
978
Raymond Hettinger165eee22016-01-24 11:32:07 -0800979 n++;
980 while (--n) {
Raymond Hettinger39dadf72015-03-20 16:38:56 -0700981 CHECK_NOT_END(b);
982 item = b->data[index];
983 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
984 if (cmp) {
985 return cmp;
986 }
987 if (start_state != deque->state) {
988 PyErr_SetString(PyExc_RuntimeError,
989 "deque mutated during iteration");
990 return -1;
991 }
992 index++;
993 if (index == BLOCKLEN) {
994 b = b->rightlink;
995 index = 0;
996 }
997 }
998 return 0;
999}
1000
Martin v. Löwis18e16552006-02-15 17:27:45 +00001001static Py_ssize_t
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001002deque_len(dequeobject *deque)
1003{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001004 return Py_SIZE(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001005}
1006
Raymond Hettinger4aec61e2005-03-18 21:20:23 +00001007static PyObject *
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001008deque_index(dequeobject *deque, PyObject *args)
1009{
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001010 Py_ssize_t i, n, start=0, stop=Py_SIZE(deque);
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001011 PyObject *v, *item;
1012 block *b = deque->leftblock;
1013 Py_ssize_t index = deque->leftindex;
1014 size_t start_state = deque->state;
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001015 int cmp;
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001016
1017 if (!PyArg_ParseTuple(args, "O|O&O&:index", &v,
1018 _PyEval_SliceIndex, &start,
1019 _PyEval_SliceIndex, &stop))
1020 return NULL;
1021 if (start < 0) {
1022 start += Py_SIZE(deque);
1023 if (start < 0)
1024 start = 0;
1025 }
1026 if (stop < 0) {
1027 stop += Py_SIZE(deque);
1028 if (stop < 0)
1029 stop = 0;
1030 }
Raymond Hettinger87674ec2015-08-26 08:08:38 -07001031 if (stop > Py_SIZE(deque))
1032 stop = Py_SIZE(deque);
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001033 if (start > stop)
1034 start = stop;
1035 assert(0 <= start && start <= stop && stop <= Py_SIZE(deque));
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001036
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001037 /* XXX Replace this loop with faster code from deque_item() */
1038 for (i=0 ; i<start ; i++) {
1039 index++;
1040 if (index == BLOCKLEN) {
1041 b = b->rightlink;
1042 index = 0;
1043 }
1044 }
1045
Raymond Hettinger4a91d212015-11-03 22:00:26 -05001046 n = stop - i + 1;
1047 while (--n) {
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001048 CHECK_NOT_END(b);
1049 item = b->data[index];
1050 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
1051 if (cmp > 0)
Raymond Hettinger4a91d212015-11-03 22:00:26 -05001052 return PyLong_FromSsize_t(stop - n);
Raymond Hettingerdf8f5b52015-11-02 07:27:40 -05001053 if (cmp < 0)
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001054 return NULL;
1055 if (start_state != deque->state) {
1056 PyErr_SetString(PyExc_RuntimeError,
1057 "deque mutated during iteration");
1058 return NULL;
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001059 }
1060 index++;
1061 if (index == BLOCKLEN) {
1062 b = b->rightlink;
1063 index = 0;
1064 }
1065 }
1066 PyErr_Format(PyExc_ValueError, "%R is not in deque", v);
1067 return NULL;
1068}
1069
1070PyDoc_STRVAR(index_doc,
1071"D.index(value, [start, [stop]]) -> integer -- return first index of value.\n"
1072"Raises ValueError if the value is not present.");
1073
Raymond Hettinger551350a2015-03-24 00:19:53 -07001074/* insert(), remove(), and delitem() are implemented in terms of
1075 rotate() for simplicity and reasonable performance near the end
1076 points. If for some reason these methods become popular, it is not
1077 hard to re-implement this using direct data movement (similar to
1078 the code used in list slice assignments) and achieve a performance
Raymond Hettingerfef9c1b2015-03-24 21:12:57 -07001079 boost (by moving each pointer only once instead of twice).
Raymond Hettinger551350a2015-03-24 00:19:53 -07001080*/
1081
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001082static PyObject *
1083deque_insert(dequeobject *deque, PyObject *args)
1084{
1085 Py_ssize_t index;
1086 Py_ssize_t n = Py_SIZE(deque);
1087 PyObject *value;
1088 PyObject *rv;
1089
1090 if (!PyArg_ParseTuple(args, "nO:insert", &index, &value))
1091 return NULL;
Raymond Hettinger37434322016-01-26 21:44:16 -08001092 if (deque->maxlen == Py_SIZE(deque)) {
Raymond Hettingera6389712016-02-01 21:21:19 -08001093 PyErr_SetString(PyExc_IndexError, "deque already at its maximum size");
1094 return NULL;
Raymond Hettinger37434322016-01-26 21:44:16 -08001095 }
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001096 if (index >= n)
1097 return deque_append(deque, value);
1098 if (index <= -n || index == 0)
1099 return deque_appendleft(deque, value);
1100 if (_deque_rotate(deque, -index))
1101 return NULL;
1102 if (index < 0)
1103 rv = deque_append(deque, value);
1104 else
1105 rv = deque_appendleft(deque, value);
1106 if (rv == NULL)
1107 return NULL;
1108 Py_DECREF(rv);
1109 if (_deque_rotate(deque, index))
1110 return NULL;
1111 Py_RETURN_NONE;
1112}
1113
1114PyDoc_STRVAR(insert_doc,
1115"D.insert(index, object) -- insert object before index");
1116
1117static PyObject *
Raymond Hettinger4aec61e2005-03-18 21:20:23 +00001118deque_remove(dequeobject *deque, PyObject *value)
1119{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001120 Py_ssize_t i, n=Py_SIZE(deque);
Raymond Hettinger4aec61e2005-03-18 21:20:23 +00001121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001122 for (i=0 ; i<n ; i++) {
1123 PyObject *item = deque->leftblock->data[deque->leftindex];
1124 int cmp = PyObject_RichCompareBool(item, value, Py_EQ);
Raymond Hettingerd73202c2005-03-19 00:00:51 +00001125
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001126 if (Py_SIZE(deque) != n) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001127 PyErr_SetString(PyExc_IndexError,
1128 "deque mutated during remove().");
1129 return NULL;
1130 }
1131 if (cmp > 0) {
1132 PyObject *tgt = deque_popleft(deque, NULL);
1133 assert (tgt != NULL);
Raymond Hettinger6921c132015-03-21 02:03:40 -07001134 if (_deque_rotate(deque, i))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001135 return NULL;
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001136 Py_DECREF(tgt);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001137 Py_RETURN_NONE;
1138 }
1139 else if (cmp < 0) {
1140 _deque_rotate(deque, i);
1141 return NULL;
1142 }
1143 _deque_rotate(deque, -1);
1144 }
1145 PyErr_SetString(PyExc_ValueError, "deque.remove(x): x not in deque");
1146 return NULL;
Raymond Hettinger4aec61e2005-03-18 21:20:23 +00001147}
1148
1149PyDoc_STRVAR(remove_doc,
1150"D.remove(value) -- remove first occurrence of value.");
1151
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001152static int
1153valid_index(Py_ssize_t i, Py_ssize_t limit)
1154{
Raymond Hettinger12f896c2015-07-31 12:03:20 -07001155 /* The cast to size_t lets us use just a single comparison
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001156 to check whether i is in the range: 0 <= i < limit */
1157 return (size_t) i < (size_t) limit;
1158}
1159
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001160static PyObject *
Benjamin Petersond6313712008-07-31 16:23:04 +00001161deque_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001162{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001163 block *b;
1164 PyObject *item;
1165 Py_ssize_t n, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001166
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001167 if (!valid_index(i, Py_SIZE(deque))) {
1168 PyErr_SetString(PyExc_IndexError, "deque index out of range");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001169 return NULL;
1170 }
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001171
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001172 if (i == 0) {
1173 i = deque->leftindex;
1174 b = deque->leftblock;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001175 } else if (i == Py_SIZE(deque) - 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001176 i = deque->rightindex;
1177 b = deque->rightblock;
1178 } else {
1179 i += deque->leftindex;
Raymond Hettingerc2083082015-02-28 23:29:16 -08001180 n = (Py_ssize_t)((size_t) i / BLOCKLEN);
1181 i = (Py_ssize_t)((size_t) i % BLOCKLEN);
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001182 if (index < (Py_SIZE(deque) >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 b = deque->leftblock;
Raymond Hettingerd84ec222016-01-24 09:12:06 -08001184 n++;
1185 while (--n)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001186 b = b->rightlink;
1187 } else {
Raymond Hettinger63d1ff22015-02-28 07:41:30 -08001188 n = (Py_ssize_t)(
Raymond Hettingerc2083082015-02-28 23:29:16 -08001189 ((size_t)(deque->leftindex + Py_SIZE(deque) - 1))
Raymond Hettinger63d1ff22015-02-28 07:41:30 -08001190 / BLOCKLEN - n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001191 b = deque->rightblock;
Raymond Hettingerd84ec222016-01-24 09:12:06 -08001192 n++;
1193 while (--n)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 b = b->leftlink;
1195 }
1196 }
1197 item = b->data[i];
1198 Py_INCREF(item);
1199 return item;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001200}
1201
1202static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001203deque_del_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001204{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001205 PyObject *item;
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001206 int rv;
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001207
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001208 assert (i >= 0 && i < Py_SIZE(deque));
Raymond Hettinger6921c132015-03-21 02:03:40 -07001209 if (_deque_rotate(deque, -i))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001210 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001211 item = deque_popleft(deque, NULL);
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001212 rv = _deque_rotate(deque, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 assert (item != NULL);
1214 Py_DECREF(item);
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001215 return rv;
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001216}
1217
1218static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001219deque_ass_item(dequeobject *deque, Py_ssize_t i, PyObject *v)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001220{
Raymond Hettinger38418662016-02-08 20:34:49 -08001221 PyObject *old_value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001222 block *b;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001223 Py_ssize_t n, len=Py_SIZE(deque), halflen=(len+1)>>1, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001224
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001225 if (!valid_index(i, len)) {
1226 PyErr_SetString(PyExc_IndexError, "deque index out of range");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001227 return -1;
1228 }
1229 if (v == NULL)
1230 return deque_del_item(deque, i);
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001232 i += deque->leftindex;
Raymond Hettingerc2083082015-02-28 23:29:16 -08001233 n = (Py_ssize_t)((size_t) i / BLOCKLEN);
1234 i = (Py_ssize_t)((size_t) i % BLOCKLEN);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001235 if (index <= halflen) {
1236 b = deque->leftblock;
Raymond Hettingerd84ec222016-01-24 09:12:06 -08001237 n++;
1238 while (--n)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001239 b = b->rightlink;
1240 } else {
Raymond Hettingera473b9d2015-02-28 17:49:47 -08001241 n = (Py_ssize_t)(
Raymond Hettingerc2083082015-02-28 23:29:16 -08001242 ((size_t)(deque->leftindex + Py_SIZE(deque) - 1))
Raymond Hettingera473b9d2015-02-28 17:49:47 -08001243 / BLOCKLEN - n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001244 b = deque->rightblock;
Raymond Hettingerd84ec222016-01-24 09:12:06 -08001245 n++;
1246 while (--n)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001247 b = b->leftlink;
1248 }
1249 Py_INCREF(v);
Raymond Hettinger38418662016-02-08 20:34:49 -08001250 old_value = b->data[i];
1251 b->data[i] = v;
1252 Py_DECREF(old_value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001253 return 0;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001254}
1255
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001256static void
1257deque_dealloc(dequeobject *deque)
1258{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001259 PyObject_GC_UnTrack(deque);
1260 if (deque->weakreflist != NULL)
1261 PyObject_ClearWeakRefs((PyObject *) deque);
1262 if (deque->leftblock != NULL) {
1263 deque_clear(deque);
1264 assert(deque->leftblock != NULL);
1265 freeblock(deque->leftblock);
1266 }
1267 deque->leftblock = NULL;
1268 deque->rightblock = NULL;
1269 Py_TYPE(deque)->tp_free(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001270}
1271
1272static int
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001273deque_traverse(dequeobject *deque, visitproc visit, void *arg)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001274{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001275 block *b;
1276 PyObject *item;
1277 Py_ssize_t index;
1278 Py_ssize_t indexlo = deque->leftindex;
Raymond Hettinger1286d142015-10-14 23:16:57 -07001279 Py_ssize_t indexhigh;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001280
Raymond Hettinger5bfa8672013-07-06 11:58:09 -10001281 for (b = deque->leftblock; b != deque->rightblock; b = b->rightlink) {
1282 for (index = indexlo; index < BLOCKLEN ; index++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001283 item = b->data[index];
1284 Py_VISIT(item);
1285 }
1286 indexlo = 0;
1287 }
Raymond Hettinger1286d142015-10-14 23:16:57 -07001288 indexhigh = deque->rightindex;
1289 for (index = indexlo; index <= indexhigh; index++) {
Raymond Hettinger5bfa8672013-07-06 11:58:09 -10001290 item = b->data[index];
1291 Py_VISIT(item);
1292 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001293 return 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001294}
1295
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001296static PyObject *
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001297deque_reduce(dequeobject *deque)
1298{
Serhiy Storchakaa0d416f2016-03-06 08:55:21 +02001299 PyObject *dict, *it;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001300 _Py_IDENTIFIER(__dict__);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001301
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001302 dict = _PyObject_GetAttrId((PyObject *)deque, &PyId___dict__);
Serhiy Storchakaa0d416f2016-03-06 08:55:21 +02001303 if (dict == NULL) {
1304 if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
1305 return NULL;
1306 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001307 PyErr_Clear();
Serhiy Storchakaa0d416f2016-03-06 08:55:21 +02001308 dict = Py_None;
1309 Py_INCREF(dict);
1310 }
1311
1312 it = PyObject_GetIter((PyObject *)deque);
1313 if (it == NULL) {
1314 Py_DECREF(dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001315 return NULL;
1316 }
Serhiy Storchakaa0d416f2016-03-06 08:55:21 +02001317
1318 if (deque->maxlen < 0) {
1319 return Py_BuildValue("O()NN", Py_TYPE(deque), dict, it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001320 }
Serhiy Storchakaa0d416f2016-03-06 08:55:21 +02001321 else {
1322 return Py_BuildValue("O(()n)NN", Py_TYPE(deque), deque->maxlen, dict, it);
1323 }
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001324}
1325
1326PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
1327
1328static PyObject *
1329deque_repr(PyObject *deque)
1330{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001331 PyObject *aslist, *result;
1332 int i;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001334 i = Py_ReprEnter(deque);
1335 if (i != 0) {
1336 if (i < 0)
1337 return NULL;
1338 return PyUnicode_FromString("[...]");
1339 }
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001341 aslist = PySequence_List(deque);
1342 if (aslist == NULL) {
1343 Py_ReprLeave(deque);
1344 return NULL;
1345 }
Raymond Hettingera7f630092015-10-10 23:56:02 -04001346 if (((dequeobject *)deque)->maxlen >= 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001347 result = PyUnicode_FromFormat("deque(%R, maxlen=%zd)",
1348 aslist, ((dequeobject *)deque)->maxlen);
1349 else
1350 result = PyUnicode_FromFormat("deque(%R)", aslist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001351 Py_ReprLeave(deque);
Raymond Hettinger2b2b7532015-09-05 17:05:52 -07001352 Py_DECREF(aslist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001353 return result;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001354}
1355
Raymond Hettinger738ec902004-02-29 02:15:56 +00001356static PyObject *
1357deque_richcompare(PyObject *v, PyObject *w, int op)
1358{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001359 PyObject *it1=NULL, *it2=NULL, *x, *y;
1360 Py_ssize_t vs, ws;
1361 int b, cmp=-1;
Raymond Hettinger738ec902004-02-29 02:15:56 +00001362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001363 if (!PyObject_TypeCheck(v, &deque_type) ||
1364 !PyObject_TypeCheck(w, &deque_type)) {
Brian Curtindfc80e32011-08-10 20:28:54 -05001365 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001366 }
Raymond Hettinger738ec902004-02-29 02:15:56 +00001367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001368 /* Shortcuts */
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001369 vs = Py_SIZE((dequeobject *)v);
1370 ws = Py_SIZE((dequeobject *)w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001371 if (op == Py_EQ) {
1372 if (v == w)
1373 Py_RETURN_TRUE;
1374 if (vs != ws)
1375 Py_RETURN_FALSE;
1376 }
1377 if (op == Py_NE) {
1378 if (v == w)
1379 Py_RETURN_FALSE;
1380 if (vs != ws)
1381 Py_RETURN_TRUE;
1382 }
Raymond Hettinger738ec902004-02-29 02:15:56 +00001383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001384 /* Search for the first index where items are different */
1385 it1 = PyObject_GetIter(v);
1386 if (it1 == NULL)
1387 goto done;
1388 it2 = PyObject_GetIter(w);
1389 if (it2 == NULL)
1390 goto done;
1391 for (;;) {
1392 x = PyIter_Next(it1);
1393 if (x == NULL && PyErr_Occurred())
1394 goto done;
1395 y = PyIter_Next(it2);
1396 if (x == NULL || y == NULL)
1397 break;
1398 b = PyObject_RichCompareBool(x, y, Py_EQ);
1399 if (b == 0) {
1400 cmp = PyObject_RichCompareBool(x, y, op);
1401 Py_DECREF(x);
1402 Py_DECREF(y);
1403 goto done;
1404 }
1405 Py_DECREF(x);
1406 Py_DECREF(y);
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -07001407 if (b < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001408 goto done;
1409 }
1410 /* We reached the end of one deque or both */
1411 Py_XDECREF(x);
1412 Py_XDECREF(y);
1413 if (PyErr_Occurred())
1414 goto done;
1415 switch (op) {
1416 case Py_LT: cmp = y != NULL; break; /* if w was longer */
1417 case Py_LE: cmp = x == NULL; break; /* if v was not longer */
1418 case Py_EQ: cmp = x == y; break; /* if we reached the end of both */
1419 case Py_NE: cmp = x != y; break; /* if one deque continues */
1420 case Py_GT: cmp = x != NULL; break; /* if v was longer */
1421 case Py_GE: cmp = y == NULL; break; /* if w was not longer */
1422 }
Tim Peters1065f752004-10-01 01:03:29 +00001423
Raymond Hettinger738ec902004-02-29 02:15:56 +00001424done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001425 Py_XDECREF(it1);
1426 Py_XDECREF(it2);
1427 if (cmp == 1)
1428 Py_RETURN_TRUE;
1429 if (cmp == 0)
1430 Py_RETURN_FALSE;
1431 return NULL;
Raymond Hettinger738ec902004-02-29 02:15:56 +00001432}
1433
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001434static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001435deque_init(dequeobject *deque, PyObject *args, PyObject *kwdargs)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001436{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001437 PyObject *iterable = NULL;
1438 PyObject *maxlenobj = NULL;
1439 Py_ssize_t maxlen = -1;
1440 char *kwlist[] = {"iterable", "maxlen", 0};
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001441
Raymond Hettinger0d309402015-09-30 23:15:02 -07001442 if (kwdargs == NULL) {
1443 if (!PyArg_UnpackTuple(args, "deque()", 0, 2, &iterable, &maxlenobj))
1444 return -1;
1445 } else {
1446 if (!PyArg_ParseTupleAndKeywords(args, kwdargs, "|OO:deque", kwlist,
1447 &iterable, &maxlenobj))
1448 return -1;
1449 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001450 if (maxlenobj != NULL && maxlenobj != Py_None) {
1451 maxlen = PyLong_AsSsize_t(maxlenobj);
1452 if (maxlen == -1 && PyErr_Occurred())
1453 return -1;
1454 if (maxlen < 0) {
1455 PyErr_SetString(PyExc_ValueError, "maxlen must be non-negative");
1456 return -1;
1457 }
1458 }
1459 deque->maxlen = maxlen;
Raymond Hettinger0d309402015-09-30 23:15:02 -07001460 if (Py_SIZE(deque) > 0)
1461 deque_clear(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001462 if (iterable != NULL) {
1463 PyObject *rv = deque_extend(deque, iterable);
1464 if (rv == NULL)
1465 return -1;
1466 Py_DECREF(rv);
1467 }
1468 return 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001469}
1470
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001471static PyObject *
Jesus Cea16e2fca2012-08-03 14:49:42 +02001472deque_sizeof(dequeobject *deque, void *unused)
1473{
1474 Py_ssize_t res;
1475 Py_ssize_t blocks;
1476
Serhiy Storchaka5c4064e2015-12-19 20:05:25 +02001477 res = _PyObject_SIZE(Py_TYPE(deque));
Raymond Hettingerbc003412015-10-14 23:33:23 -07001478 blocks = (size_t)(deque->leftindex + Py_SIZE(deque) + BLOCKLEN - 1) / BLOCKLEN;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001479 assert(deque->leftindex + Py_SIZE(deque) - 1 ==
Jesus Cea16e2fca2012-08-03 14:49:42 +02001480 (blocks - 1) * BLOCKLEN + deque->rightindex);
1481 res += blocks * sizeof(block);
1482 return PyLong_FromSsize_t(res);
1483}
1484
1485PyDoc_STRVAR(sizeof_doc,
1486"D.__sizeof__() -- size of D in memory, in bytes");
1487
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001488static int
1489deque_bool(dequeobject *deque)
1490{
1491 return Py_SIZE(deque) != 0;
1492}
1493
Jesus Cea16e2fca2012-08-03 14:49:42 +02001494static PyObject *
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001495deque_get_maxlen(dequeobject *deque)
1496{
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -07001497 if (deque->maxlen < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001498 Py_RETURN_NONE;
1499 return PyLong_FromSsize_t(deque->maxlen);
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001500}
1501
Raymond Hettinger41290a62015-03-31 08:12:23 -07001502
1503/* deque object ********************************************************/
1504
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001505static PyGetSetDef deque_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001506 {"maxlen", (getter)deque_get_maxlen, (setter)NULL,
1507 "maximum size of a deque or None if unbounded"},
1508 {0}
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001509};
1510
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001511static PySequenceMethods deque_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001512 (lenfunc)deque_len, /* sq_length */
Raymond Hettinger41290a62015-03-31 08:12:23 -07001513 (binaryfunc)deque_concat, /* sq_concat */
1514 (ssizeargfunc)deque_repeat, /* sq_repeat */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001515 (ssizeargfunc)deque_item, /* sq_item */
1516 0, /* sq_slice */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001517 (ssizeobjargproc)deque_ass_item, /* sq_ass_item */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001518 0, /* sq_ass_slice */
Raymond Hettinger39dadf72015-03-20 16:38:56 -07001519 (objobjproc)deque_contains, /* sq_contains */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001520 (binaryfunc)deque_inplace_concat, /* sq_inplace_concat */
Raymond Hettinger41290a62015-03-31 08:12:23 -07001521 (ssizeargfunc)deque_inplace_repeat, /* sq_inplace_repeat */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001522};
1523
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001524static PyNumberMethods deque_as_number = {
1525 0, /* nb_add */
1526 0, /* nb_subtract */
1527 0, /* nb_multiply */
1528 0, /* nb_remainder */
1529 0, /* nb_divmod */
1530 0, /* nb_power */
1531 0, /* nb_negative */
1532 0, /* nb_positive */
1533 0, /* nb_absolute */
1534 (inquiry)deque_bool, /* nb_bool */
1535 0, /* nb_invert */
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001536 };
1537
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001538static PyObject *deque_iter(dequeobject *deque);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001539static PyObject *deque_reviter(dequeobject *deque);
Tim Peters1065f752004-10-01 01:03:29 +00001540PyDoc_STRVAR(reversed_doc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001541 "D.__reversed__() -- return a reverse iterator over the deque");
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001542
1543static PyMethodDef deque_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001544 {"append", (PyCFunction)deque_append,
1545 METH_O, append_doc},
1546 {"appendleft", (PyCFunction)deque_appendleft,
1547 METH_O, appendleft_doc},
1548 {"clear", (PyCFunction)deque_clearmethod,
1549 METH_NOARGS, clear_doc},
1550 {"__copy__", (PyCFunction)deque_copy,
1551 METH_NOARGS, copy_doc},
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001552 {"copy", (PyCFunction)deque_copy,
1553 METH_NOARGS, copy_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001554 {"count", (PyCFunction)deque_count,
Raymond Hettinger0f6f9472015-03-21 01:42:10 -07001555 METH_O, count_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001556 {"extend", (PyCFunction)deque_extend,
1557 METH_O, extend_doc},
1558 {"extendleft", (PyCFunction)deque_extendleft,
1559 METH_O, extendleft_doc},
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001560 {"index", (PyCFunction)deque_index,
1561 METH_VARARGS, index_doc},
1562 {"insert", (PyCFunction)deque_insert,
1563 METH_VARARGS, insert_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001564 {"pop", (PyCFunction)deque_pop,
1565 METH_NOARGS, pop_doc},
1566 {"popleft", (PyCFunction)deque_popleft,
1567 METH_NOARGS, popleft_doc},
Raymond Hettinger0f6f9472015-03-21 01:42:10 -07001568 {"__reduce__", (PyCFunction)deque_reduce,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001569 METH_NOARGS, reduce_doc},
1570 {"remove", (PyCFunction)deque_remove,
1571 METH_O, remove_doc},
1572 {"__reversed__", (PyCFunction)deque_reviter,
1573 METH_NOARGS, reversed_doc},
1574 {"reverse", (PyCFunction)deque_reverse,
1575 METH_NOARGS, reverse_doc},
1576 {"rotate", (PyCFunction)deque_rotate,
Jesus Cea16e2fca2012-08-03 14:49:42 +02001577 METH_VARARGS, rotate_doc},
1578 {"__sizeof__", (PyCFunction)deque_sizeof,
1579 METH_NOARGS, sizeof_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001580 {NULL, NULL} /* sentinel */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001581};
1582
1583PyDoc_STRVAR(deque_doc,
Andrew Svetlov6a5c7c32012-10-31 11:50:40 +02001584"deque([iterable[, maxlen]]) --> deque object\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001585\n\
Raymond Hettinger41290a62015-03-31 08:12:23 -07001586A list-like sequence optimized for data accesses near its endpoints.");
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001587
Neal Norwitz87f10132004-02-29 15:40:53 +00001588static PyTypeObject deque_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001589 PyVarObject_HEAD_INIT(NULL, 0)
1590 "collections.deque", /* tp_name */
1591 sizeof(dequeobject), /* tp_basicsize */
1592 0, /* tp_itemsize */
1593 /* methods */
1594 (destructor)deque_dealloc, /* tp_dealloc */
1595 0, /* tp_print */
1596 0, /* tp_getattr */
1597 0, /* tp_setattr */
1598 0, /* tp_reserved */
1599 deque_repr, /* tp_repr */
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001600 &deque_as_number, /* tp_as_number */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001601 &deque_as_sequence, /* tp_as_sequence */
1602 0, /* tp_as_mapping */
Georg Brandlf038b322010-10-18 07:35:09 +00001603 PyObject_HashNotImplemented, /* tp_hash */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001604 0, /* tp_call */
1605 0, /* tp_str */
1606 PyObject_GenericGetAttr, /* tp_getattro */
1607 0, /* tp_setattro */
1608 0, /* tp_as_buffer */
1609 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
Georg Brandlf038b322010-10-18 07:35:09 +00001610 /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001611 deque_doc, /* tp_doc */
1612 (traverseproc)deque_traverse, /* tp_traverse */
1613 (inquiry)deque_clear, /* tp_clear */
1614 (richcmpfunc)deque_richcompare, /* tp_richcompare */
Georg Brandlf038b322010-10-18 07:35:09 +00001615 offsetof(dequeobject, weakreflist), /* tp_weaklistoffset*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001616 (getiterfunc)deque_iter, /* tp_iter */
1617 0, /* tp_iternext */
1618 deque_methods, /* tp_methods */
1619 0, /* tp_members */
Georg Brandlf038b322010-10-18 07:35:09 +00001620 deque_getset, /* tp_getset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001621 0, /* tp_base */
1622 0, /* tp_dict */
1623 0, /* tp_descr_get */
1624 0, /* tp_descr_set */
1625 0, /* tp_dictoffset */
1626 (initproc)deque_init, /* tp_init */
1627 PyType_GenericAlloc, /* tp_alloc */
1628 deque_new, /* tp_new */
1629 PyObject_GC_Del, /* tp_free */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001630};
1631
1632/*********************** Deque Iterator **************************/
1633
1634typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001635 PyObject_HEAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001636 block *b;
Raymond Hettinger87e69122015-03-02 23:32:02 -08001637 Py_ssize_t index;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001638 dequeobject *deque;
Raymond Hettingerf9d9c792015-03-02 22:47:46 -08001639 size_t state; /* state when the iterator is created */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001640 Py_ssize_t counter; /* number of items remaining for iteration */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001641} dequeiterobject;
1642
Martin v. Löwis59683e82008-06-13 07:50:45 +00001643static PyTypeObject dequeiter_type;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001644
1645static PyObject *
1646deque_iter(dequeobject *deque)
1647{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001648 dequeiterobject *it;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001649
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001650 it = PyObject_GC_New(dequeiterobject, &dequeiter_type);
1651 if (it == NULL)
1652 return NULL;
1653 it->b = deque->leftblock;
1654 it->index = deque->leftindex;
1655 Py_INCREF(deque);
1656 it->deque = deque;
1657 it->state = deque->state;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001658 it->counter = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001659 PyObject_GC_Track(it);
1660 return (PyObject *)it;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001661}
1662
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001663static int
1664dequeiter_traverse(dequeiterobject *dio, visitproc visit, void *arg)
1665{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001666 Py_VISIT(dio->deque);
1667 return 0;
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001668}
1669
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001670static void
1671dequeiter_dealloc(dequeiterobject *dio)
1672{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001673 Py_XDECREF(dio->deque);
1674 PyObject_GC_Del(dio);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001675}
1676
1677static PyObject *
1678dequeiter_next(dequeiterobject *it)
1679{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001680 PyObject *item;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001681
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001682 if (it->deque->state != it->state) {
1683 it->counter = 0;
1684 PyErr_SetString(PyExc_RuntimeError,
1685 "deque mutated during iteration");
1686 return NULL;
1687 }
1688 if (it->counter == 0)
1689 return NULL;
1690 assert (!(it->b == it->deque->rightblock &&
1691 it->index > it->deque->rightindex));
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001692
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001693 item = it->b->data[it->index];
1694 it->index++;
1695 it->counter--;
1696 if (it->index == BLOCKLEN && it->counter > 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -10001697 CHECK_NOT_END(it->b->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001698 it->b = it->b->rightlink;
1699 it->index = 0;
1700 }
1701 Py_INCREF(item);
1702 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001703}
1704
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001705static PyObject *
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001706dequeiter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1707{
1708 Py_ssize_t i, index=0;
1709 PyObject *deque;
1710 dequeiterobject *it;
1711 if (!PyArg_ParseTuple(args, "O!|n", &deque_type, &deque, &index))
1712 return NULL;
1713 assert(type == &dequeiter_type);
1714
1715 it = (dequeiterobject*)deque_iter((dequeobject *)deque);
1716 if (!it)
1717 return NULL;
1718 /* consume items from the queue */
1719 for(i=0; i<index; i++) {
1720 PyObject *item = dequeiter_next(it);
1721 if (item) {
1722 Py_DECREF(item);
1723 } else {
1724 if (it->counter) {
1725 Py_DECREF(it);
1726 return NULL;
1727 } else
1728 break;
1729 }
1730 }
1731 return (PyObject*)it;
1732}
1733
1734static PyObject *
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001735dequeiter_len(dequeiterobject *it)
1736{
Antoine Pitrou554f3342010-08-17 18:30:06 +00001737 return PyLong_FromSsize_t(it->counter);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001738}
1739
Armin Rigof5b3e362006-02-11 21:32:43 +00001740PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001741
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001742static PyObject *
1743dequeiter_reduce(dequeiterobject *it)
1744{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001745 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 +00001746}
1747
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001748static PyMethodDef dequeiter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001749 {"__length_hint__", (PyCFunction)dequeiter_len, METH_NOARGS, length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001750 {"__reduce__", (PyCFunction)dequeiter_reduce, METH_NOARGS, reduce_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001751 {NULL, NULL} /* sentinel */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001752};
1753
Martin v. Löwis59683e82008-06-13 07:50:45 +00001754static PyTypeObject dequeiter_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001755 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger87e69122015-03-02 23:32:02 -08001756 "_collections._deque_iterator", /* tp_name */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001757 sizeof(dequeiterobject), /* tp_basicsize */
1758 0, /* tp_itemsize */
1759 /* methods */
1760 (destructor)dequeiter_dealloc, /* tp_dealloc */
1761 0, /* tp_print */
1762 0, /* tp_getattr */
1763 0, /* tp_setattr */
1764 0, /* tp_reserved */
1765 0, /* tp_repr */
1766 0, /* tp_as_number */
1767 0, /* tp_as_sequence */
1768 0, /* tp_as_mapping */
1769 0, /* tp_hash */
1770 0, /* tp_call */
1771 0, /* tp_str */
1772 PyObject_GenericGetAttr, /* tp_getattro */
1773 0, /* tp_setattro */
1774 0, /* tp_as_buffer */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001775 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001776 0, /* tp_doc */
1777 (traverseproc)dequeiter_traverse, /* tp_traverse */
1778 0, /* tp_clear */
1779 0, /* tp_richcompare */
1780 0, /* tp_weaklistoffset */
1781 PyObject_SelfIter, /* tp_iter */
1782 (iternextfunc)dequeiter_next, /* tp_iternext */
1783 dequeiter_methods, /* tp_methods */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001784 0, /* tp_members */
1785 0, /* tp_getset */
1786 0, /* tp_base */
1787 0, /* tp_dict */
1788 0, /* tp_descr_get */
1789 0, /* tp_descr_set */
1790 0, /* tp_dictoffset */
1791 0, /* tp_init */
1792 0, /* tp_alloc */
1793 dequeiter_new, /* tp_new */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001794 0,
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001795};
1796
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001797/*********************** Deque Reverse Iterator **************************/
1798
Martin v. Löwis59683e82008-06-13 07:50:45 +00001799static PyTypeObject dequereviter_type;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001800
1801static PyObject *
1802deque_reviter(dequeobject *deque)
1803{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001804 dequeiterobject *it;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001805
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001806 it = PyObject_GC_New(dequeiterobject, &dequereviter_type);
1807 if (it == NULL)
1808 return NULL;
1809 it->b = deque->rightblock;
1810 it->index = deque->rightindex;
1811 Py_INCREF(deque);
1812 it->deque = deque;
1813 it->state = deque->state;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001814 it->counter = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001815 PyObject_GC_Track(it);
1816 return (PyObject *)it;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001817}
1818
1819static PyObject *
1820dequereviter_next(dequeiterobject *it)
1821{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001822 PyObject *item;
1823 if (it->counter == 0)
1824 return NULL;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001825
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001826 if (it->deque->state != it->state) {
1827 it->counter = 0;
1828 PyErr_SetString(PyExc_RuntimeError,
1829 "deque mutated during iteration");
1830 return NULL;
1831 }
1832 assert (!(it->b == it->deque->leftblock &&
1833 it->index < it->deque->leftindex));
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001834
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001835 item = it->b->data[it->index];
1836 it->index--;
1837 it->counter--;
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -07001838 if (it->index < 0 && it->counter > 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -10001839 CHECK_NOT_END(it->b->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001840 it->b = it->b->leftlink;
1841 it->index = BLOCKLEN - 1;
1842 }
1843 Py_INCREF(item);
1844 return item;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001845}
1846
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001847static PyObject *
1848dequereviter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1849{
1850 Py_ssize_t i, index=0;
1851 PyObject *deque;
1852 dequeiterobject *it;
1853 if (!PyArg_ParseTuple(args, "O!|n", &deque_type, &deque, &index))
1854 return NULL;
1855 assert(type == &dequereviter_type);
1856
1857 it = (dequeiterobject*)deque_reviter((dequeobject *)deque);
1858 if (!it)
1859 return NULL;
1860 /* consume items from the queue */
1861 for(i=0; i<index; i++) {
1862 PyObject *item = dequereviter_next(it);
1863 if (item) {
1864 Py_DECREF(item);
1865 } else {
1866 if (it->counter) {
1867 Py_DECREF(it);
1868 return NULL;
1869 } else
1870 break;
1871 }
1872 }
1873 return (PyObject*)it;
1874}
1875
Martin v. Löwis59683e82008-06-13 07:50:45 +00001876static PyTypeObject dequereviter_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001877 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger87e69122015-03-02 23:32:02 -08001878 "_collections._deque_reverse_iterator", /* tp_name */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001879 sizeof(dequeiterobject), /* tp_basicsize */
1880 0, /* tp_itemsize */
1881 /* methods */
1882 (destructor)dequeiter_dealloc, /* tp_dealloc */
1883 0, /* tp_print */
1884 0, /* tp_getattr */
1885 0, /* tp_setattr */
1886 0, /* tp_reserved */
1887 0, /* tp_repr */
1888 0, /* tp_as_number */
1889 0, /* tp_as_sequence */
1890 0, /* tp_as_mapping */
1891 0, /* tp_hash */
1892 0, /* tp_call */
1893 0, /* tp_str */
1894 PyObject_GenericGetAttr, /* tp_getattro */
1895 0, /* tp_setattro */
1896 0, /* tp_as_buffer */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001897 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001898 0, /* tp_doc */
1899 (traverseproc)dequeiter_traverse, /* tp_traverse */
1900 0, /* tp_clear */
1901 0, /* tp_richcompare */
1902 0, /* tp_weaklistoffset */
1903 PyObject_SelfIter, /* tp_iter */
1904 (iternextfunc)dequereviter_next, /* tp_iternext */
1905 dequeiter_methods, /* tp_methods */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001906 0, /* tp_members */
1907 0, /* tp_getset */
1908 0, /* tp_base */
1909 0, /* tp_dict */
1910 0, /* tp_descr_get */
1911 0, /* tp_descr_set */
1912 0, /* tp_dictoffset */
1913 0, /* tp_init */
1914 0, /* tp_alloc */
1915 dequereviter_new, /* tp_new */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001916 0,
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001917};
1918
Guido van Rossum1968ad32006-02-25 22:38:04 +00001919/* defaultdict type *********************************************************/
1920
1921typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001922 PyDictObject dict;
1923 PyObject *default_factory;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001924} defdictobject;
1925
1926static PyTypeObject defdict_type; /* Forward */
1927
1928PyDoc_STRVAR(defdict_missing_doc,
1929"__missing__(key) # Called by __getitem__ for missing key; pseudo-code:\n\
Guido van Rossumd8faa362007-04-27 19:54:29 +00001930 if self.default_factory is None: raise KeyError((key,))\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00001931 self[key] = value = self.default_factory()\n\
1932 return value\n\
1933");
1934
1935static PyObject *
1936defdict_missing(defdictobject *dd, PyObject *key)
1937{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001938 PyObject *factory = dd->default_factory;
1939 PyObject *value;
1940 if (factory == NULL || factory == Py_None) {
1941 /* XXX Call dict.__missing__(key) */
1942 PyObject *tup;
1943 tup = PyTuple_Pack(1, key);
1944 if (!tup) return NULL;
1945 PyErr_SetObject(PyExc_KeyError, tup);
1946 Py_DECREF(tup);
1947 return NULL;
1948 }
1949 value = PyEval_CallObject(factory, NULL);
1950 if (value == NULL)
1951 return value;
1952 if (PyObject_SetItem((PyObject *)dd, key, value) < 0) {
1953 Py_DECREF(value);
1954 return NULL;
1955 }
1956 return value;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001957}
1958
1959PyDoc_STRVAR(defdict_copy_doc, "D.copy() -> a shallow copy of D.");
1960
1961static PyObject *
1962defdict_copy(defdictobject *dd)
1963{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001964 /* This calls the object's class. That only works for subclasses
1965 whose class constructor has the same signature. Subclasses that
1966 define a different constructor signature must override copy().
1967 */
Raymond Hettinger54628fa2009-08-04 19:16:39 +00001968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001969 if (dd->default_factory == NULL)
1970 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd), Py_None, dd, NULL);
1971 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd),
1972 dd->default_factory, dd, NULL);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001973}
1974
1975static PyObject *
1976defdict_reduce(defdictobject *dd)
1977{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001978 /* __reduce__ must return a 5-tuple as follows:
Guido van Rossum1968ad32006-02-25 22:38:04 +00001979
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001980 - factory function
1981 - tuple of args for the factory function
1982 - additional state (here None)
1983 - sequence iterator (here None)
1984 - dictionary iterator (yielding successive (key, value) pairs
Guido van Rossum1968ad32006-02-25 22:38:04 +00001985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001986 This API is used by pickle.py and copy.py.
Guido van Rossum1968ad32006-02-25 22:38:04 +00001987
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001988 For this to be useful with pickle.py, the default_factory
1989 must be picklable; e.g., None, a built-in, or a global
1990 function in a module or package.
Guido van Rossum1968ad32006-02-25 22:38:04 +00001991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001992 Both shallow and deep copying are supported, but for deep
1993 copying, the default_factory must be deep-copyable; e.g. None,
1994 or a built-in (functions are not copyable at this time).
Guido van Rossum1968ad32006-02-25 22:38:04 +00001995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001996 This only works for subclasses as long as their constructor
1997 signature is compatible; the first argument must be the
1998 optional default_factory, defaulting to None.
1999 */
2000 PyObject *args;
2001 PyObject *items;
2002 PyObject *iter;
2003 PyObject *result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002004 _Py_IDENTIFIER(items);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002005
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002006 if (dd->default_factory == NULL || dd->default_factory == Py_None)
2007 args = PyTuple_New(0);
2008 else
2009 args = PyTuple_Pack(1, dd->default_factory);
2010 if (args == NULL)
2011 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002012 items = _PyObject_CallMethodId((PyObject *)dd, &PyId_items, "()");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002013 if (items == NULL) {
2014 Py_DECREF(args);
2015 return NULL;
2016 }
2017 iter = PyObject_GetIter(items);
2018 if (iter == NULL) {
2019 Py_DECREF(items);
2020 Py_DECREF(args);
2021 return NULL;
2022 }
2023 result = PyTuple_Pack(5, Py_TYPE(dd), args,
2024 Py_None, Py_None, iter);
2025 Py_DECREF(iter);
2026 Py_DECREF(items);
2027 Py_DECREF(args);
2028 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00002029}
2030
2031static PyMethodDef defdict_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002032 {"__missing__", (PyCFunction)defdict_missing, METH_O,
2033 defdict_missing_doc},
2034 {"copy", (PyCFunction)defdict_copy, METH_NOARGS,
2035 defdict_copy_doc},
2036 {"__copy__", (PyCFunction)defdict_copy, METH_NOARGS,
2037 defdict_copy_doc},
2038 {"__reduce__", (PyCFunction)defdict_reduce, METH_NOARGS,
2039 reduce_doc},
2040 {NULL}
Guido van Rossum1968ad32006-02-25 22:38:04 +00002041};
2042
2043static PyMemberDef defdict_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002044 {"default_factory", T_OBJECT,
2045 offsetof(defdictobject, default_factory), 0,
2046 PyDoc_STR("Factory for default value called by __missing__().")},
2047 {NULL}
Guido van Rossum1968ad32006-02-25 22:38:04 +00002048};
2049
2050static void
2051defdict_dealloc(defdictobject *dd)
2052{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002053 Py_CLEAR(dd->default_factory);
2054 PyDict_Type.tp_dealloc((PyObject *)dd);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002055}
2056
Guido van Rossum1968ad32006-02-25 22:38:04 +00002057static PyObject *
2058defdict_repr(defdictobject *dd)
2059{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002060 PyObject *baserepr;
2061 PyObject *defrepr;
2062 PyObject *result;
2063 baserepr = PyDict_Type.tp_repr((PyObject *)dd);
2064 if (baserepr == NULL)
2065 return NULL;
2066 if (dd->default_factory == NULL)
2067 defrepr = PyUnicode_FromString("None");
2068 else
2069 {
2070 int status = Py_ReprEnter(dd->default_factory);
2071 if (status != 0) {
Antoine Pitrouf5f1fe02012-02-15 02:42:46 +01002072 if (status < 0) {
2073 Py_DECREF(baserepr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002074 return NULL;
Antoine Pitrouf5f1fe02012-02-15 02:42:46 +01002075 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002076 defrepr = PyUnicode_FromString("...");
2077 }
2078 else
2079 defrepr = PyObject_Repr(dd->default_factory);
2080 Py_ReprLeave(dd->default_factory);
2081 }
2082 if (defrepr == NULL) {
2083 Py_DECREF(baserepr);
2084 return NULL;
2085 }
2086 result = PyUnicode_FromFormat("defaultdict(%U, %U)",
2087 defrepr, baserepr);
2088 Py_DECREF(defrepr);
2089 Py_DECREF(baserepr);
2090 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00002091}
2092
2093static int
2094defdict_traverse(PyObject *self, visitproc visit, void *arg)
2095{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002096 Py_VISIT(((defdictobject *)self)->default_factory);
2097 return PyDict_Type.tp_traverse(self, visit, arg);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002098}
2099
2100static int
2101defdict_tp_clear(defdictobject *dd)
2102{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002103 Py_CLEAR(dd->default_factory);
2104 return PyDict_Type.tp_clear((PyObject *)dd);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002105}
2106
2107static int
2108defdict_init(PyObject *self, PyObject *args, PyObject *kwds)
2109{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002110 defdictobject *dd = (defdictobject *)self;
2111 PyObject *olddefault = dd->default_factory;
2112 PyObject *newdefault = NULL;
2113 PyObject *newargs;
2114 int result;
2115 if (args == NULL || !PyTuple_Check(args))
2116 newargs = PyTuple_New(0);
2117 else {
2118 Py_ssize_t n = PyTuple_GET_SIZE(args);
2119 if (n > 0) {
2120 newdefault = PyTuple_GET_ITEM(args, 0);
2121 if (!PyCallable_Check(newdefault) && newdefault != Py_None) {
2122 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger239aba72015-07-20 03:09:22 -04002123 "first argument must be callable or None");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002124 return -1;
2125 }
2126 }
2127 newargs = PySequence_GetSlice(args, 1, n);
2128 }
2129 if (newargs == NULL)
2130 return -1;
2131 Py_XINCREF(newdefault);
2132 dd->default_factory = newdefault;
2133 result = PyDict_Type.tp_init(self, newargs, kwds);
2134 Py_DECREF(newargs);
2135 Py_XDECREF(olddefault);
2136 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00002137}
2138
2139PyDoc_STRVAR(defdict_doc,
Benjamin Peterson9cb33b72014-01-13 23:56:05 -05002140"defaultdict(default_factory[, ...]) --> dict with default factory\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00002141\n\
2142The default factory is called without arguments to produce\n\
2143a new value when a key is not present, in __getitem__ only.\n\
2144A defaultdict compares equal to a dict with the same items.\n\
Benjamin Peterson9cb33b72014-01-13 23:56:05 -05002145All remaining arguments are treated the same as if they were\n\
2146passed to the dict constructor, including keyword arguments.\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00002147");
2148
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002149/* See comment in xxsubtype.c */
2150#define DEFERRED_ADDRESS(ADDR) 0
2151
Guido van Rossum1968ad32006-02-25 22:38:04 +00002152static PyTypeObject defdict_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002153 PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0)
2154 "collections.defaultdict", /* tp_name */
2155 sizeof(defdictobject), /* tp_basicsize */
2156 0, /* tp_itemsize */
2157 /* methods */
2158 (destructor)defdict_dealloc, /* tp_dealloc */
2159 0, /* tp_print */
2160 0, /* tp_getattr */
2161 0, /* tp_setattr */
2162 0, /* tp_reserved */
2163 (reprfunc)defdict_repr, /* tp_repr */
2164 0, /* tp_as_number */
2165 0, /* tp_as_sequence */
2166 0, /* tp_as_mapping */
2167 0, /* tp_hash */
2168 0, /* tp_call */
2169 0, /* tp_str */
2170 PyObject_GenericGetAttr, /* tp_getattro */
2171 0, /* tp_setattro */
2172 0, /* tp_as_buffer */
2173 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
2174 /* tp_flags */
2175 defdict_doc, /* tp_doc */
2176 defdict_traverse, /* tp_traverse */
2177 (inquiry)defdict_tp_clear, /* tp_clear */
2178 0, /* tp_richcompare */
2179 0, /* tp_weaklistoffset*/
2180 0, /* tp_iter */
2181 0, /* tp_iternext */
2182 defdict_methods, /* tp_methods */
2183 defdict_members, /* tp_members */
2184 0, /* tp_getset */
2185 DEFERRED_ADDRESS(&PyDict_Type), /* tp_base */
2186 0, /* tp_dict */
2187 0, /* tp_descr_get */
2188 0, /* tp_descr_set */
2189 0, /* tp_dictoffset */
2190 defdict_init, /* tp_init */
2191 PyType_GenericAlloc, /* tp_alloc */
2192 0, /* tp_new */
2193 PyObject_GC_Del, /* tp_free */
Guido van Rossum1968ad32006-02-25 22:38:04 +00002194};
2195
Raymond Hettinger96f34102010-12-15 16:30:37 +00002196/* helper function for Counter *********************************************/
2197
2198PyDoc_STRVAR(_count_elements_doc,
2199"_count_elements(mapping, iterable) -> None\n\
2200\n\
2201Count elements in the iterable, updating the mappping");
2202
2203static PyObject *
2204_count_elements(PyObject *self, PyObject *args)
2205{
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002206 _Py_IDENTIFIER(get);
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002207 _Py_IDENTIFIER(__setitem__);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002208 PyObject *it, *iterable, *mapping, *oldval;
2209 PyObject *newval = NULL;
2210 PyObject *key = NULL;
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002211 PyObject *zero = NULL;
Raymond Hettinger96f34102010-12-15 16:30:37 +00002212 PyObject *one = NULL;
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002213 PyObject *bound_get = NULL;
2214 PyObject *mapping_get;
2215 PyObject *dict_get;
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002216 PyObject *mapping_setitem;
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002217 PyObject *dict_setitem;
Raymond Hettinger96f34102010-12-15 16:30:37 +00002218
2219 if (!PyArg_UnpackTuple(args, "_count_elements", 2, 2, &mapping, &iterable))
2220 return NULL;
2221
Raymond Hettinger96f34102010-12-15 16:30:37 +00002222 it = PyObject_GetIter(iterable);
2223 if (it == NULL)
2224 return NULL;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002225
Raymond Hettinger96f34102010-12-15 16:30:37 +00002226 one = PyLong_FromLong(1);
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002227 if (one == NULL)
2228 goto done;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002229
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002230 /* Only take the fast path when get() and __setitem__()
2231 * have not been overridden.
2232 */
2233 mapping_get = _PyType_LookupId(Py_TYPE(mapping), &PyId_get);
2234 dict_get = _PyType_LookupId(&PyDict_Type, &PyId_get);
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002235 mapping_setitem = _PyType_LookupId(Py_TYPE(mapping), &PyId___setitem__);
2236 dict_setitem = _PyType_LookupId(&PyDict_Type, &PyId___setitem__);
2237
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002238 if (mapping_get != NULL && mapping_get == dict_get &&
2239 mapping_setitem != NULL && mapping_setitem == dict_setitem) {
Raymond Hettinger426e0522011-01-03 02:12:02 +00002240 while (1) {
Raymond Hettinger507d9972014-05-18 21:32:40 +01002241 /* Fast path advantages:
2242 1. Eliminate double hashing
2243 (by re-using the same hash for both the get and set)
2244 2. Avoid argument overhead of PyObject_CallFunctionObjArgs
2245 (argument tuple creation and parsing)
2246 3. Avoid indirection through a bound method object
2247 (creates another argument tuple)
2248 4. Avoid initial increment from zero
2249 (reuse an existing one-object instead)
2250 */
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002251 Py_hash_t hash;
2252
Raymond Hettinger426e0522011-01-03 02:12:02 +00002253 key = PyIter_Next(it);
Victor Stinnera154b5c2011-04-20 23:23:52 +02002254 if (key == NULL)
2255 break;
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002256
2257 if (!PyUnicode_CheckExact(key) ||
2258 (hash = ((PyASCIIObject *) key)->hash) == -1)
2259 {
2260 hash = PyObject_Hash(key);
Raymond Hettingerda2850f2015-02-27 12:42:54 -08002261 if (hash == -1)
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002262 goto done;
2263 }
2264
2265 oldval = _PyDict_GetItem_KnownHash(mapping, key, hash);
Raymond Hettinger426e0522011-01-03 02:12:02 +00002266 if (oldval == NULL) {
Raymond Hettinger28c995d2015-08-14 02:07:41 -07002267 if (_PyDict_SetItem_KnownHash(mapping, key, one, hash) < 0)
Raymond Hettinger507d9972014-05-18 21:32:40 +01002268 goto done;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002269 } else {
2270 newval = PyNumber_Add(oldval, one);
2271 if (newval == NULL)
Raymond Hettinger507d9972014-05-18 21:32:40 +01002272 goto done;
Raymond Hettinger28c995d2015-08-14 02:07:41 -07002273 if (_PyDict_SetItem_KnownHash(mapping, key, newval, hash) < 0)
Raymond Hettinger507d9972014-05-18 21:32:40 +01002274 goto done;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002275 Py_CLEAR(newval);
2276 }
2277 Py_DECREF(key);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002278 }
Raymond Hettinger426e0522011-01-03 02:12:02 +00002279 } else {
Victor Stinnere7f516c2013-11-06 23:52:55 +01002280 bound_get = _PyObject_GetAttrId(mapping, &PyId_get);
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002281 if (bound_get == NULL)
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002282 goto done;
2283
2284 zero = PyLong_FromLong(0);
2285 if (zero == NULL)
2286 goto done;
2287
Raymond Hettinger426e0522011-01-03 02:12:02 +00002288 while (1) {
2289 key = PyIter_Next(it);
Victor Stinnera154b5c2011-04-20 23:23:52 +02002290 if (key == NULL)
2291 break;
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002292 oldval = PyObject_CallFunctionObjArgs(bound_get, key, zero, NULL);
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002293 if (oldval == NULL)
2294 break;
2295 newval = PyNumber_Add(oldval, one);
2296 Py_DECREF(oldval);
2297 if (newval == NULL)
2298 break;
Raymond Hettinger28c995d2015-08-14 02:07:41 -07002299 if (PyObject_SetItem(mapping, key, newval) < 0)
Raymond Hettinger96f34102010-12-15 16:30:37 +00002300 break;
2301 Py_CLEAR(newval);
Raymond Hettinger426e0522011-01-03 02:12:02 +00002302 Py_DECREF(key);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002303 }
Raymond Hettinger96f34102010-12-15 16:30:37 +00002304 }
Raymond Hettinger426e0522011-01-03 02:12:02 +00002305
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002306done:
Raymond Hettinger96f34102010-12-15 16:30:37 +00002307 Py_DECREF(it);
2308 Py_XDECREF(key);
2309 Py_XDECREF(newval);
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002310 Py_XDECREF(bound_get);
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002311 Py_XDECREF(zero);
2312 Py_XDECREF(one);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002313 if (PyErr_Occurred())
2314 return NULL;
2315 Py_RETURN_NONE;
2316}
2317
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002318/* module level code ********************************************************/
2319
2320PyDoc_STRVAR(module_doc,
Guido van Rossum1968ad32006-02-25 22:38:04 +00002321"High performance data structures.\n\
2322- deque: ordered collection accessible from endpoints only\n\
2323- defaultdict: dict subclass with a default value factory\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002324");
2325
Raymond Hettinger96f34102010-12-15 16:30:37 +00002326static struct PyMethodDef module_functions[] = {
2327 {"_count_elements", _count_elements, METH_VARARGS, _count_elements_doc},
2328 {NULL, NULL} /* sentinel */
2329};
Martin v. Löwis1a214512008-06-11 05:26:20 +00002330
2331static struct PyModuleDef _collectionsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002332 PyModuleDef_HEAD_INIT,
2333 "_collections",
2334 module_doc,
2335 -1,
Raymond Hettinger96f34102010-12-15 16:30:37 +00002336 module_functions,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002337 NULL,
2338 NULL,
2339 NULL,
2340 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002341};
2342
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002343PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002344PyInit__collections(void)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002345{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002346 PyObject *m;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002348 m = PyModule_Create(&_collectionsmodule);
2349 if (m == NULL)
2350 return NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002352 if (PyType_Ready(&deque_type) < 0)
2353 return NULL;
2354 Py_INCREF(&deque_type);
2355 PyModule_AddObject(m, "deque", (PyObject *)&deque_type);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002357 defdict_type.tp_base = &PyDict_Type;
2358 if (PyType_Ready(&defdict_type) < 0)
2359 return NULL;
2360 Py_INCREF(&defdict_type);
2361 PyModule_AddObject(m, "defaultdict", (PyObject *)&defdict_type);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002362
Eric Snow47db7172015-05-29 22:21:39 -06002363 Py_INCREF(&PyODict_Type);
2364 PyModule_AddObject(m, "OrderedDict", (PyObject *)&PyODict_Type);
2365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002366 if (PyType_Ready(&dequeiter_type) < 0)
2367 return NULL;
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002368 Py_INCREF(&dequeiter_type);
2369 PyModule_AddObject(m, "_deque_iterator", (PyObject *)&dequeiter_type);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002371 if (PyType_Ready(&dequereviter_type) < 0)
2372 return NULL;
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002373 Py_INCREF(&dequereviter_type);
2374 PyModule_AddObject(m, "_deque_reverse_iterator", (PyObject *)&dequereviter_type);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00002375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002376 return m;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002377}