blob: c1aa9a30bcd72737ec1a54a382263526791a7f0c [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
4/* collections module implementation of a deque() datatype
5 Written and maintained by Raymond D. Hettinger <python@rcn.com>
Raymond Hettingera4409c12013-02-04 00:08:12 -05006 Copyright (c) 2004-2013 Python Software Foundation.
Raymond Hettinger756b3f32004-01-29 06:37:52 +00007 All rights reserved.
8*/
9
Raymond Hettinger77e8bf12004-10-01 15:25:53 +000010/* The block length may be set to any number over 1. Larger numbers
Raymond Hettinger20b0f872013-06-23 15:44:33 -070011 * reduce the number of calls to the memory allocator, give faster
12 * indexing and rotation, and reduce the link::data overhead ratio.
Raymond Hettinger77578202013-07-28 02:39:49 -070013 *
14 * Ideally, the block length will be set to two less than some
15 * multiple of the cache-line length (so that the full block
16 * including the leftlink and rightlink will fit neatly into
17 * cache lines).
Raymond Hettinger77e8bf12004-10-01 15:25:53 +000018 */
19
Raymond Hettinger77578202013-07-28 02:39:49 -070020#define BLOCKLEN 62
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000021#define CENTER ((BLOCKLEN - 1) / 2)
Raymond Hettinger756b3f32004-01-29 06:37:52 +000022
Tim Petersd8768d32004-10-01 01:32:53 +000023/* A `dequeobject` is composed of a doubly-linked list of `block` nodes.
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000024 * The list of blocks is never empty, so d.leftblock and d.rightblock
Raymond Hettinger82df9252013-07-07 01:43:42 -100025 * are never equal to NULL. The list is not circular.
26 *
27 * A deque d's first element is at d.leftblock[leftindex]
28 * and its last element is at d.rightblock[rightindex].
29 * Unlike Python slice indices, these indices are inclusive
30 * on both ends. This makes the algorithms for left and
31 * right operations more symmetrical and simplifies the design.
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000032 *
33 * The indices, d.leftindex and d.rightindex are always in the range
34 * 0 <= index < BLOCKLEN.
Raymond Hettinger4ca4c7c2004-10-01 15:14:39 +000035 * Their exact relationship is:
36 * (d.leftindex + d.len - 1) % BLOCKLEN == d.rightindex.
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000037 *
38 * Empty deques have d.len == 0; d.leftblock==d.rightblock;
39 * d.leftindex == CENTER+1; and d.rightindex == CENTER.
40 * Checking for d.len == 0 is the intended way to see whether d is empty.
41 *
Thomas Wouters0e3f5912006-08-11 14:57:12 +000042 * Whenever d.leftblock == d.rightblock,
Raymond Hettinger4ca4c7c2004-10-01 15:14:39 +000043 * d.leftindex + d.len - 1 == d.rightindex.
Thomas Wouters0e3f5912006-08-11 14:57:12 +000044 *
Raymond Hettinger4ca4c7c2004-10-01 15:14:39 +000045 * However, when d.leftblock != d.rightblock, d.leftindex and d.rightindex
Thomas Wouters0e3f5912006-08-11 14:57:12 +000046 * become indices into distinct blocks and either may be larger than the
Raymond Hettinger4ca4c7c2004-10-01 15:14:39 +000047 * other.
Tim Petersd8768d32004-10-01 01:32:53 +000048 */
49
Raymond Hettinger756b3f32004-01-29 06:37:52 +000050typedef struct BLOCK {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000051 struct BLOCK *leftlink;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000052 PyObject *data[BLOCKLEN];
Raymond Hettinger20b0f872013-06-23 15:44:33 -070053 struct BLOCK *rightlink;
Raymond Hettinger756b3f32004-01-29 06:37:52 +000054} block;
55
Raymond Hettinger82df9252013-07-07 01:43:42 -100056/* For debug builds, add error checking to track the endpoints
57 * in the chain of links. The goal is to make sure that link
58 * assignments only take place at endpoints so that links already
59 * in use do not get overwritten.
60 *
61 * CHECK_END should happen before each assignment to a block's link field.
62 * MARK_END should happen whenever a link field becomes a new endpoint.
63 * This happens when new blocks are added or whenever an existing
64 * block is freed leaving another existing block as the new endpoint.
65 */
66
Raymond Hettinger3223dd52013-07-26 23:14:22 -070067#ifndef NDEBUG
Raymond Hettinger82df9252013-07-07 01:43:42 -100068#define MARK_END(link) link = NULL;
69#define CHECK_END(link) assert(link == NULL);
70#define CHECK_NOT_END(link) assert(link != NULL);
71#else
72#define MARK_END(link)
73#define CHECK_END(link)
74#define CHECK_NOT_END(link)
75#endif
76
77/* A simple freelisting scheme is used to minimize calls to the memory
78 allocator. It accomodates common use cases where new blocks are being
79 added at about the same rate as old blocks are being freed.
80 */
81
Guido van Rossum58da9312007-11-10 23:39:45 +000082#define MAXFREEBLOCKS 10
Benjamin Petersond6313712008-07-31 16:23:04 +000083static Py_ssize_t numfreeblocks = 0;
Guido van Rossum58da9312007-11-10 23:39:45 +000084static block *freeblocks[MAXFREEBLOCKS];
85
Tim Peters6f853562004-10-01 01:04:50 +000086static block *
Raymond Hettinger82df9252013-07-07 01:43:42 -100087newblock(Py_ssize_t len) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000088 block *b;
Raymond Hettinger20b0f872013-06-23 15:44:33 -070089 /* To prevent len from overflowing PY_SSIZE_T_MAX, we refuse to
90 * allocate new blocks if the current len is nearing overflow. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000091 if (len >= PY_SSIZE_T_MAX - 2*BLOCKLEN) {
92 PyErr_SetString(PyExc_OverflowError,
93 "cannot add more blocks to the deque");
94 return NULL;
95 }
96 if (numfreeblocks) {
Raymond Hettinger59cf23a2013-02-07 00:57:19 -050097 numfreeblocks--;
Raymond Hettinger82df9252013-07-07 01:43:42 -100098 return freeblocks[numfreeblocks];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000099 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000100 b = PyMem_Malloc(sizeof(block));
101 if (b != NULL) {
102 return b;
103 }
104 PyErr_NoMemory();
105 return NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000106}
107
Martin v. Löwis59683e82008-06-13 07:50:45 +0000108static void
Guido van Rossum58da9312007-11-10 23:39:45 +0000109freeblock(block *b)
110{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000111 if (numfreeblocks < MAXFREEBLOCKS) {
112 freeblocks[numfreeblocks] = b;
113 numfreeblocks++;
114 } else {
115 PyMem_Free(b);
116 }
Guido van Rossum58da9312007-11-10 23:39:45 +0000117}
118
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000119typedef struct {
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000120 PyObject_VAR_HEAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000121 block *leftblock;
122 block *rightblock;
123 Py_ssize_t leftindex; /* in range(BLOCKLEN) */
124 Py_ssize_t rightindex; /* in range(BLOCKLEN) */
Raymond Hettinger90dea4c2013-07-13 22:30:25 -0700125 long state; /* incremented whenever the indices move */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000126 Py_ssize_t maxlen;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000127 PyObject *weakreflist; /* List of weak references */
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000128} dequeobject;
129
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000130/* The deque's size limit is d.maxlen. The limit can be zero or positive.
131 * If there is no limit, then d.maxlen == -1.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000132 *
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000133 * After an item is added to a deque, we check to see if the size has grown past
134 * the limit. If it has, we get the size back down to the limit by popping an
135 * item off of the opposite end. The methods that can trigger this are append(),
136 * appendleft(), extend(), and extendleft().
137 */
138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000139#define TRIM(d, popfunction) \
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000140 if (d->maxlen != -1 && Py_SIZE(d) > d->maxlen) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000141 PyObject *rv = popfunction(d, NULL); \
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000142 assert(rv != NULL && Py_SIZE(d) <= d->maxlen); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000143 Py_DECREF(rv); \
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000144 }
145
Neal Norwitz87f10132004-02-29 15:40:53 +0000146static PyTypeObject deque_type;
Raymond Hettinger738ec902004-02-29 02:15:56 +0000147
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000148static PyObject *
149deque_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
150{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000151 dequeobject *deque;
152 block *b;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000154 /* create dequeobject structure */
155 deque = (dequeobject *)type->tp_alloc(type, 0);
156 if (deque == NULL)
157 return NULL;
Tim Peters1065f752004-10-01 01:03:29 +0000158
Raymond Hettinger82df9252013-07-07 01:43:42 -1000159 b = newblock(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000160 if (b == NULL) {
161 Py_DECREF(deque);
162 return NULL;
163 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000164 MARK_END(b->leftlink);
165 MARK_END(b->rightlink);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000167 assert(BLOCKLEN >= 2);
168 deque->leftblock = b;
169 deque->rightblock = b;
170 deque->leftindex = CENTER + 1;
171 deque->rightindex = CENTER;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000172 Py_SIZE(deque) = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000173 deque->state = 0;
174 deque->weakreflist = NULL;
175 deque->maxlen = -1;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000176
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000177 return (PyObject *)deque;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000178}
179
180static PyObject *
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000181deque_pop(dequeobject *deque, PyObject *unused)
182{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000183 PyObject *item;
184 block *prevblock;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000185
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000186 if (Py_SIZE(deque) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000187 PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
188 return NULL;
189 }
190 item = deque->rightblock->data[deque->rightindex];
191 deque->rightindex--;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000192 Py_SIZE(deque)--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000193 deque->state++;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000195 if (deque->rightindex == -1) {
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000196 if (Py_SIZE(deque) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000197 assert(deque->leftblock == deque->rightblock);
198 assert(deque->leftindex == deque->rightindex+1);
199 /* re-center instead of freeing a block */
200 deque->leftindex = CENTER + 1;
201 deque->rightindex = CENTER;
202 } else {
203 prevblock = deque->rightblock->leftlink;
204 assert(deque->leftblock != deque->rightblock);
205 freeblock(deque->rightblock);
Raymond Hettinger82df9252013-07-07 01:43:42 -1000206 CHECK_NOT_END(prevblock);
207 MARK_END(prevblock->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000208 deque->rightblock = prevblock;
209 deque->rightindex = BLOCKLEN - 1;
210 }
211 }
212 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000213}
214
215PyDoc_STRVAR(pop_doc, "Remove and return the rightmost element.");
216
217static PyObject *
218deque_popleft(dequeobject *deque, PyObject *unused)
219{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000220 PyObject *item;
221 block *prevblock;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000222
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000223 if (Py_SIZE(deque) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000224 PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
225 return NULL;
226 }
227 assert(deque->leftblock != NULL);
228 item = deque->leftblock->data[deque->leftindex];
229 deque->leftindex++;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000230 Py_SIZE(deque)--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000231 deque->state++;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000233 if (deque->leftindex == BLOCKLEN) {
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000234 if (Py_SIZE(deque) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000235 assert(deque->leftblock == deque->rightblock);
236 assert(deque->leftindex == deque->rightindex+1);
237 /* re-center instead of freeing a block */
238 deque->leftindex = CENTER + 1;
239 deque->rightindex = CENTER;
240 } else {
241 assert(deque->leftblock != deque->rightblock);
242 prevblock = deque->leftblock->rightlink;
243 freeblock(deque->leftblock);
Raymond Hettinger82df9252013-07-07 01:43:42 -1000244 CHECK_NOT_END(prevblock);
245 MARK_END(prevblock->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000246 deque->leftblock = prevblock;
247 deque->leftindex = 0;
248 }
249 }
250 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000251}
252
253PyDoc_STRVAR(popleft_doc, "Remove and return the leftmost element.");
254
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000255static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000256deque_append(dequeobject *deque, PyObject *item)
257{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000258 deque->state++;
259 if (deque->rightindex == BLOCKLEN-1) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000260 block *b = newblock(Py_SIZE(deque));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000261 if (b == NULL)
262 return NULL;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000263 b->leftlink = deque->rightblock;
264 CHECK_END(deque->rightblock->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000265 deque->rightblock->rightlink = b;
266 deque->rightblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000267 MARK_END(b->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000268 deque->rightindex = -1;
269 }
270 Py_INCREF(item);
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000271 Py_SIZE(deque)++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000272 deque->rightindex++;
273 deque->rightblock->data[deque->rightindex] = item;
274 TRIM(deque, deque_popleft);
275 Py_RETURN_NONE;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000276}
277
278PyDoc_STRVAR(append_doc, "Add an element to the right side of the deque.");
279
280static PyObject *
281deque_appendleft(dequeobject *deque, PyObject *item)
282{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000283 deque->state++;
284 if (deque->leftindex == 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000285 block *b = newblock(Py_SIZE(deque));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 if (b == NULL)
287 return NULL;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000288 b->rightlink = deque->leftblock;
289 CHECK_END(deque->leftblock->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000290 deque->leftblock->leftlink = b;
291 deque->leftblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000292 MARK_END(b->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000293 deque->leftindex = BLOCKLEN;
294 }
295 Py_INCREF(item);
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000296 Py_SIZE(deque)++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000297 deque->leftindex--;
298 deque->leftblock->data[deque->leftindex] = item;
299 TRIM(deque, deque_pop);
300 Py_RETURN_NONE;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000301}
302
303PyDoc_STRVAR(appendleft_doc, "Add an element to the left side of the deque.");
304
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000306/* Run an iterator to exhaustion. Shortcut for
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000307 the extend/extendleft methods when maxlen == 0. */
308static PyObject*
309consume_iterator(PyObject *it)
310{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000311 PyObject *item;
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000313 while ((item = PyIter_Next(it)) != NULL) {
314 Py_DECREF(item);
315 }
316 Py_DECREF(it);
317 if (PyErr_Occurred())
318 return NULL;
319 Py_RETURN_NONE;
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000320}
321
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000322static PyObject *
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000323deque_extend(dequeobject *deque, PyObject *iterable)
324{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000325 PyObject *it, *item;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000327 /* Handle case where id(deque) == id(iterable) */
328 if ((PyObject *)deque == iterable) {
329 PyObject *result;
330 PyObject *s = PySequence_List(iterable);
331 if (s == NULL)
332 return NULL;
333 result = deque_extend(deque, s);
334 Py_DECREF(s);
335 return result;
336 }
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000337
Raymond Hettingerd9c116c2013-07-09 00:13:21 -0700338 /* Space saving heuristic. Start filling from the left */
339 if (Py_SIZE(deque) == 0) {
340 assert(deque->leftblock == deque->rightblock);
341 assert(deque->leftindex == deque->rightindex+1);
342 deque->leftindex = 1;
343 deque->rightindex = 0;
344 }
345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000346 it = PyObject_GetIter(iterable);
347 if (it == NULL)
348 return NULL;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000350 if (deque->maxlen == 0)
351 return consume_iterator(it);
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000353 while ((item = PyIter_Next(it)) != NULL) {
354 deque->state++;
355 if (deque->rightindex == BLOCKLEN-1) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000356 block *b = newblock(Py_SIZE(deque));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000357 if (b == NULL) {
358 Py_DECREF(item);
359 Py_DECREF(it);
360 return NULL;
361 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000362 b->leftlink = deque->rightblock;
363 CHECK_END(deque->rightblock->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000364 deque->rightblock->rightlink = b;
365 deque->rightblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000366 MARK_END(b->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000367 deque->rightindex = -1;
368 }
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000369 Py_SIZE(deque)++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000370 deque->rightindex++;
371 deque->rightblock->data[deque->rightindex] = item;
372 TRIM(deque, deque_popleft);
373 }
374 Py_DECREF(it);
375 if (PyErr_Occurred())
376 return NULL;
377 Py_RETURN_NONE;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000378}
379
Tim Peters1065f752004-10-01 01:03:29 +0000380PyDoc_STRVAR(extend_doc,
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000381"Extend the right side of the deque with elements from the iterable");
382
383static PyObject *
384deque_extendleft(dequeobject *deque, PyObject *iterable)
385{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000386 PyObject *it, *item;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000388 /* Handle case where id(deque) == id(iterable) */
389 if ((PyObject *)deque == iterable) {
390 PyObject *result;
391 PyObject *s = PySequence_List(iterable);
392 if (s == NULL)
393 return NULL;
394 result = deque_extendleft(deque, s);
395 Py_DECREF(s);
396 return result;
397 }
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000398
Raymond Hettingerd9c116c2013-07-09 00:13:21 -0700399 /* Space saving heuristic. Start filling from the right */
400 if (Py_SIZE(deque) == 0) {
401 assert(deque->leftblock == deque->rightblock);
402 assert(deque->leftindex == deque->rightindex+1);
403 deque->leftindex = BLOCKLEN - 1;
404 deque->rightindex = BLOCKLEN - 2;
405 }
406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000407 it = PyObject_GetIter(iterable);
408 if (it == NULL)
409 return NULL;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 if (deque->maxlen == 0)
412 return consume_iterator(it);
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000413
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000414 while ((item = PyIter_Next(it)) != NULL) {
415 deque->state++;
416 if (deque->leftindex == 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000417 block *b = newblock(Py_SIZE(deque));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000418 if (b == NULL) {
419 Py_DECREF(item);
420 Py_DECREF(it);
421 return NULL;
422 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000423 b->rightlink = deque->leftblock;
424 CHECK_END(deque->leftblock->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425 deque->leftblock->leftlink = b;
426 deque->leftblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000427 MARK_END(b->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000428 deque->leftindex = BLOCKLEN;
429 }
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000430 Py_SIZE(deque)++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 deque->leftindex--;
432 deque->leftblock->data[deque->leftindex] = item;
433 TRIM(deque, deque_pop);
434 }
435 Py_DECREF(it);
436 if (PyErr_Occurred())
437 return NULL;
438 Py_RETURN_NONE;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000439}
440
Tim Peters1065f752004-10-01 01:03:29 +0000441PyDoc_STRVAR(extendleft_doc,
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000442"Extend the left side of the deque with elements from the iterable");
443
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000444static PyObject *
445deque_inplace_concat(dequeobject *deque, PyObject *other)
446{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000447 PyObject *result;
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000449 result = deque_extend(deque, other);
450 if (result == NULL)
451 return result;
452 Py_DECREF(result);
453 Py_INCREF(deque);
454 return (PyObject *)deque;
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000455}
456
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000457static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000458_deque_rotate(dequeobject *deque, Py_ssize_t n)
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000459{
Raymond Hettinger3959af92013-07-13 02:34:08 -0700460 block *b = NULL;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700461 block *leftblock = deque->leftblock;
462 block *rightblock = deque->rightblock;
463 Py_ssize_t leftindex = deque->leftindex;
464 Py_ssize_t rightindex = deque->rightindex;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000465 Py_ssize_t len=Py_SIZE(deque), halflen=len>>1;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700466 int rv = -1;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000467
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800468 if (len <= 1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469 return 0;
470 if (n > halflen || n < -halflen) {
471 n %= len;
472 if (n > halflen)
473 n -= len;
474 else if (n < -halflen)
475 n += len;
476 }
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500477 assert(len > 1);
Raymond Hettingera4409c12013-02-04 00:08:12 -0500478 assert(-halflen <= n && n <= halflen);
Raymond Hettinger231ee4d2013-02-02 11:24:43 -0800479
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800480 deque->state++;
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500481 while (n > 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700482 if (leftindex == 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700483 if (b == NULL) {
Raymond Hettinger3959af92013-07-13 02:34:08 -0700484 b = newblock(len);
485 if (b == NULL)
486 goto done;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700487 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000488 b->rightlink = leftblock;
489 CHECK_END(leftblock->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700490 leftblock->leftlink = b;
491 leftblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000492 MARK_END(b->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700493 leftindex = BLOCKLEN;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700494 b = NULL;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800495 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700496 assert(leftindex > 0);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700497 {
498 PyObject **src, **dest;
499 Py_ssize_t m = n;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800500
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700501 if (m > rightindex + 1)
502 m = rightindex + 1;
503 if (m > leftindex)
504 m = leftindex;
505 assert (m > 0 && m <= len);
506 src = &rightblock->data[rightindex];
507 dest = &leftblock->data[leftindex - 1];
508 rightindex -= m;
509 leftindex -= m;
510 n -= m;
Raymond Hettinger840533b2013-07-13 17:03:58 -0700511 do {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700512 *(dest--) = *(src--);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700513 } while (--m);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700514 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700515 if (rightindex == -1) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700516 assert(leftblock != rightblock);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700517 assert(b == NULL);
Raymond Hettinger3959af92013-07-13 02:34:08 -0700518 b = rightblock;
Raymond Hettingerb97cc492013-07-21 01:51:07 -0700519 CHECK_NOT_END(rightblock->leftlink);
520 rightblock = rightblock->leftlink;
521 MARK_END(rightblock->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700522 rightindex = BLOCKLEN - 1;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800523 }
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800524 }
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500525 while (n < 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700526 if (rightindex == BLOCKLEN - 1) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700527 if (b == NULL) {
Raymond Hettinger3959af92013-07-13 02:34:08 -0700528 b = newblock(len);
529 if (b == NULL)
530 goto done;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700531 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000532 b->leftlink = rightblock;
533 CHECK_END(rightblock->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700534 rightblock->rightlink = b;
535 rightblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000536 MARK_END(b->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700537 rightindex = -1;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700538 b = NULL;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800539 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700540 assert (rightindex < BLOCKLEN - 1);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700541 {
542 PyObject **src, **dest;
543 Py_ssize_t m = -n;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800544
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700545 if (m > BLOCKLEN - leftindex)
546 m = BLOCKLEN - leftindex;
547 if (m > BLOCKLEN - 1 - rightindex)
548 m = BLOCKLEN - 1 - rightindex;
549 assert (m > 0 && m <= len);
550 src = &leftblock->data[leftindex];
551 dest = &rightblock->data[rightindex + 1];
552 leftindex += m;
553 rightindex += m;
554 n += m;
Raymond Hettinger840533b2013-07-13 17:03:58 -0700555 do {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700556 *(dest++) = *(src++);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700557 } while (--m);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700558 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700559 if (leftindex == BLOCKLEN) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700560 assert(leftblock != rightblock);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700561 assert(b == NULL);
Raymond Hettinger3959af92013-07-13 02:34:08 -0700562 b = leftblock;
Raymond Hettingerb97cc492013-07-21 01:51:07 -0700563 CHECK_NOT_END(leftblock->rightlink);
564 leftblock = leftblock->rightlink;
565 MARK_END(leftblock->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700566 leftindex = 0;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800567 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000568 }
Raymond Hettinger3959af92013-07-13 02:34:08 -0700569 rv = 0;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700570done:
Raymond Hettinger3959af92013-07-13 02:34:08 -0700571 if (b != NULL)
572 freeblock(b);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700573 deque->leftblock = leftblock;
574 deque->rightblock = rightblock;
575 deque->leftindex = leftindex;
576 deque->rightindex = rightindex;
577
578 return rv;
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000579}
580
581static PyObject *
582deque_rotate(dequeobject *deque, PyObject *args)
583{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000584 Py_ssize_t n=1;
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000586 if (!PyArg_ParseTuple(args, "|n:rotate", &n))
587 return NULL;
588 if (_deque_rotate(deque, n) == 0)
589 Py_RETURN_NONE;
590 return NULL;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000591}
592
Tim Peters1065f752004-10-01 01:03:29 +0000593PyDoc_STRVAR(rotate_doc,
Raymond Hettingeree33b272004-02-08 04:05:26 +0000594"Rotate the deque n steps to the right (default n=1). If n is negative, rotates left.");
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000595
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000596static PyObject *
597deque_reverse(dequeobject *deque, PyObject *unused)
598{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000599 block *leftblock = deque->leftblock;
600 block *rightblock = deque->rightblock;
601 Py_ssize_t leftindex = deque->leftindex;
602 Py_ssize_t rightindex = deque->rightindex;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000603 Py_ssize_t n = (Py_SIZE(deque))/2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000604 Py_ssize_t i;
605 PyObject *tmp;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607 for (i=0 ; i<n ; i++) {
608 /* Validate that pointers haven't met in the middle */
609 assert(leftblock != rightblock || leftindex < rightindex);
Raymond Hettinger82df9252013-07-07 01:43:42 -1000610 CHECK_NOT_END(leftblock);
611 CHECK_NOT_END(rightblock);
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000613 /* Swap */
614 tmp = leftblock->data[leftindex];
615 leftblock->data[leftindex] = rightblock->data[rightindex];
616 rightblock->data[rightindex] = tmp;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000618 /* Advance left block/index pair */
619 leftindex++;
620 if (leftindex == BLOCKLEN) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621 leftblock = leftblock->rightlink;
622 leftindex = 0;
623 }
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000624
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000625 /* Step backwards with the right block/index pair */
626 rightindex--;
627 if (rightindex == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000628 rightblock = rightblock->leftlink;
629 rightindex = BLOCKLEN - 1;
630 }
631 }
632 Py_RETURN_NONE;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000633}
634
635PyDoc_STRVAR(reverse_doc,
636"D.reverse() -- reverse *IN PLACE*");
637
Raymond Hettinger44459de2010-04-03 23:20:46 +0000638static PyObject *
639deque_count(dequeobject *deque, PyObject *v)
640{
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000641 block *b = deque->leftblock;
642 Py_ssize_t index = deque->leftindex;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000643 Py_ssize_t n = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 Py_ssize_t i;
645 Py_ssize_t count = 0;
646 PyObject *item;
647 long start_state = deque->state;
648 int cmp;
Raymond Hettinger44459de2010-04-03 23:20:46 +0000649
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 for (i=0 ; i<n ; i++) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000651 CHECK_NOT_END(b);
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000652 item = b->data[index];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000653 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
654 if (cmp > 0)
655 count++;
656 else if (cmp < 0)
657 return NULL;
Raymond Hettinger44459de2010-04-03 23:20:46 +0000658
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000659 if (start_state != deque->state) {
660 PyErr_SetString(PyExc_RuntimeError,
661 "deque mutated during iteration");
662 return NULL;
663 }
Raymond Hettinger44459de2010-04-03 23:20:46 +0000664
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000665 /* Advance left block/index pair */
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000666 index++;
667 if (index == BLOCKLEN) {
668 b = b->rightlink;
669 index = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 }
671 }
672 return PyLong_FromSsize_t(count);
Raymond Hettinger44459de2010-04-03 23:20:46 +0000673}
674
675PyDoc_STRVAR(count_doc,
676"D.count(value) -> integer -- return number of occurrences of value");
677
Martin v. Löwis18e16552006-02-15 17:27:45 +0000678static Py_ssize_t
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000679deque_len(dequeobject *deque)
680{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000681 return Py_SIZE(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000682}
683
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000684static PyObject *
685deque_remove(dequeobject *deque, PyObject *value)
686{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000687 Py_ssize_t i, n=Py_SIZE(deque);
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000688
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000689 for (i=0 ; i<n ; i++) {
690 PyObject *item = deque->leftblock->data[deque->leftindex];
691 int cmp = PyObject_RichCompareBool(item, value, Py_EQ);
Raymond Hettingerd73202c2005-03-19 00:00:51 +0000692
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000693 if (Py_SIZE(deque) != n) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000694 PyErr_SetString(PyExc_IndexError,
695 "deque mutated during remove().");
696 return NULL;
697 }
698 if (cmp > 0) {
699 PyObject *tgt = deque_popleft(deque, NULL);
700 assert (tgt != NULL);
701 Py_DECREF(tgt);
702 if (_deque_rotate(deque, i) == -1)
703 return NULL;
704 Py_RETURN_NONE;
705 }
706 else if (cmp < 0) {
707 _deque_rotate(deque, i);
708 return NULL;
709 }
710 _deque_rotate(deque, -1);
711 }
712 PyErr_SetString(PyExc_ValueError, "deque.remove(x): x not in deque");
713 return NULL;
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000714}
715
716PyDoc_STRVAR(remove_doc,
717"D.remove(value) -- remove first occurrence of value.");
718
Benjamin Peterson0e5c48a2013-01-12 21:22:18 -0500719static void
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000720deque_clear(dequeobject *deque)
721{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000722 PyObject *item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000723
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000724 while (Py_SIZE(deque)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000725 item = deque_pop(deque, NULL);
726 assert (item != NULL);
727 Py_DECREF(item);
728 }
729 assert(deque->leftblock == deque->rightblock &&
730 deque->leftindex - 1 == deque->rightindex &&
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000731 Py_SIZE(deque) == 0);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000732}
733
734static PyObject *
Benjamin Petersond6313712008-07-31 16:23:04 +0000735deque_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000736{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000737 block *b;
738 PyObject *item;
739 Py_ssize_t n, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000740
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000741 if (i < 0 || i >= Py_SIZE(deque)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000742 PyErr_SetString(PyExc_IndexError,
743 "deque index out of range");
744 return NULL;
745 }
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000746
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000747 if (i == 0) {
748 i = deque->leftindex;
749 b = deque->leftblock;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000750 } else if (i == Py_SIZE(deque) - 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000751 i = deque->rightindex;
752 b = deque->rightblock;
753 } else {
754 i += deque->leftindex;
755 n = i / BLOCKLEN;
756 i %= BLOCKLEN;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000757 if (index < (Py_SIZE(deque) >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 b = deque->leftblock;
759 while (n--)
760 b = b->rightlink;
761 } else {
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000762 n = (deque->leftindex + Py_SIZE(deque) - 1) / BLOCKLEN - n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000763 b = deque->rightblock;
764 while (n--)
765 b = b->leftlink;
766 }
767 }
768 item = b->data[i];
769 Py_INCREF(item);
770 return item;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000771}
772
Raymond Hettinger616f4f62004-06-26 04:42:06 +0000773/* delitem() implemented in terms of rotate for simplicity and reasonable
774 performance near the end points. If for some reason this method becomes
Tim Peters1065f752004-10-01 01:03:29 +0000775 popular, it is not hard to re-implement this using direct data movement
Raymond Hettinger616f4f62004-06-26 04:42:06 +0000776 (similar to code in list slice assignment) and achieve a two or threefold
777 performance boost.
778*/
779
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000780static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000781deque_del_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000782{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000783 PyObject *item;
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000784
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000785 assert (i >= 0 && i < Py_SIZE(deque));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000786 if (_deque_rotate(deque, -i) == -1)
787 return -1;
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 item = deque_popleft(deque, NULL);
790 assert (item != NULL);
791 Py_DECREF(item);
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000792
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000793 return _deque_rotate(deque, i);
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000794}
795
796static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000797deque_ass_item(dequeobject *deque, Py_ssize_t i, PyObject *v)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000798{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000799 PyObject *old_value;
800 block *b;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000801 Py_ssize_t n, len=Py_SIZE(deque), halflen=(len+1)>>1, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000802
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 if (i < 0 || i >= len) {
804 PyErr_SetString(PyExc_IndexError,
805 "deque index out of range");
806 return -1;
807 }
808 if (v == NULL)
809 return deque_del_item(deque, i);
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000811 i += deque->leftindex;
812 n = i / BLOCKLEN;
813 i %= BLOCKLEN;
814 if (index <= halflen) {
815 b = deque->leftblock;
816 while (n--)
817 b = b->rightlink;
818 } else {
819 n = (deque->leftindex + len - 1) / BLOCKLEN - n;
820 b = deque->rightblock;
821 while (n--)
822 b = b->leftlink;
823 }
824 Py_INCREF(v);
825 old_value = b->data[i];
826 b->data[i] = v;
827 Py_DECREF(old_value);
828 return 0;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000829}
830
831static PyObject *
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000832deque_clearmethod(dequeobject *deque)
833{
Benjamin Peterson0e5c48a2013-01-12 21:22:18 -0500834 deque_clear(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 Py_RETURN_NONE;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000836}
837
838PyDoc_STRVAR(clear_doc, "Remove all elements from the deque.");
839
840static void
841deque_dealloc(dequeobject *deque)
842{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000843 PyObject_GC_UnTrack(deque);
844 if (deque->weakreflist != NULL)
845 PyObject_ClearWeakRefs((PyObject *) deque);
846 if (deque->leftblock != NULL) {
847 deque_clear(deque);
848 assert(deque->leftblock != NULL);
849 freeblock(deque->leftblock);
850 }
851 deque->leftblock = NULL;
852 deque->rightblock = NULL;
853 Py_TYPE(deque)->tp_free(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000854}
855
856static int
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000857deque_traverse(dequeobject *deque, visitproc visit, void *arg)
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000858{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 block *b;
860 PyObject *item;
861 Py_ssize_t index;
862 Py_ssize_t indexlo = deque->leftindex;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000863
Raymond Hettinger5bfa8672013-07-06 11:58:09 -1000864 for (b = deque->leftblock; b != deque->rightblock; b = b->rightlink) {
865 for (index = indexlo; index < BLOCKLEN ; index++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 item = b->data[index];
867 Py_VISIT(item);
868 }
869 indexlo = 0;
870 }
Raymond Hettinger5bfa8672013-07-06 11:58:09 -1000871 for (index = indexlo; index <= deque->rightindex; index++) {
872 item = b->data[index];
873 Py_VISIT(item);
874 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000875 return 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000876}
877
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000878static PyObject *
879deque_copy(PyObject *deque)
880{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 if (((dequeobject *)deque)->maxlen == -1)
882 return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "O", deque, NULL);
883 else
884 return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "Oi",
885 deque, ((dequeobject *)deque)->maxlen, NULL);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000886}
887
888PyDoc_STRVAR(copy_doc, "Return a shallow copy of a deque.");
889
890static PyObject *
891deque_reduce(dequeobject *deque)
892{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000893 PyObject *dict, *result, *aslist;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200894 _Py_IDENTIFIER(__dict__);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000895
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200896 dict = _PyObject_GetAttrId((PyObject *)deque, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000897 if (dict == NULL)
898 PyErr_Clear();
899 aslist = PySequence_List((PyObject *)deque);
900 if (aslist == NULL) {
901 Py_XDECREF(dict);
902 return NULL;
903 }
904 if (dict == NULL) {
905 if (deque->maxlen == -1)
906 result = Py_BuildValue("O(O)", Py_TYPE(deque), aslist);
907 else
908 result = Py_BuildValue("O(On)", Py_TYPE(deque), aslist, deque->maxlen);
909 } else {
910 if (deque->maxlen == -1)
911 result = Py_BuildValue("O(OO)O", Py_TYPE(deque), aslist, Py_None, dict);
912 else
913 result = Py_BuildValue("O(On)O", Py_TYPE(deque), aslist, deque->maxlen, dict);
914 }
915 Py_XDECREF(dict);
916 Py_DECREF(aslist);
917 return result;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000918}
919
920PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
921
922static PyObject *
923deque_repr(PyObject *deque)
924{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000925 PyObject *aslist, *result;
926 int i;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 i = Py_ReprEnter(deque);
929 if (i != 0) {
930 if (i < 0)
931 return NULL;
932 return PyUnicode_FromString("[...]");
933 }
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000934
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 aslist = PySequence_List(deque);
936 if (aslist == NULL) {
937 Py_ReprLeave(deque);
938 return NULL;
939 }
940 if (((dequeobject *)deque)->maxlen != -1)
Benjamin Petersona786b022008-08-25 21:05:21 +0000941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 result = PyUnicode_FromFormat("deque(%R, maxlen=%zd)",
943 aslist, ((dequeobject *)deque)->maxlen);
944 else
945 result = PyUnicode_FromFormat("deque(%R)", aslist);
946 Py_DECREF(aslist);
947 Py_ReprLeave(deque);
948 return result;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000949}
950
Raymond Hettinger738ec902004-02-29 02:15:56 +0000951static PyObject *
952deque_richcompare(PyObject *v, PyObject *w, int op)
953{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000954 PyObject *it1=NULL, *it2=NULL, *x, *y;
955 Py_ssize_t vs, ws;
956 int b, cmp=-1;
Raymond Hettinger738ec902004-02-29 02:15:56 +0000957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000958 if (!PyObject_TypeCheck(v, &deque_type) ||
959 !PyObject_TypeCheck(w, &deque_type)) {
Brian Curtindfc80e32011-08-10 20:28:54 -0500960 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000961 }
Raymond Hettinger738ec902004-02-29 02:15:56 +0000962
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000963 /* Shortcuts */
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000964 vs = Py_SIZE((dequeobject *)v);
965 ws = Py_SIZE((dequeobject *)w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 if (op == Py_EQ) {
967 if (v == w)
968 Py_RETURN_TRUE;
969 if (vs != ws)
970 Py_RETURN_FALSE;
971 }
972 if (op == Py_NE) {
973 if (v == w)
974 Py_RETURN_FALSE;
975 if (vs != ws)
976 Py_RETURN_TRUE;
977 }
Raymond Hettinger738ec902004-02-29 02:15:56 +0000978
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 /* Search for the first index where items are different */
980 it1 = PyObject_GetIter(v);
981 if (it1 == NULL)
982 goto done;
983 it2 = PyObject_GetIter(w);
984 if (it2 == NULL)
985 goto done;
986 for (;;) {
987 x = PyIter_Next(it1);
988 if (x == NULL && PyErr_Occurred())
989 goto done;
990 y = PyIter_Next(it2);
991 if (x == NULL || y == NULL)
992 break;
993 b = PyObject_RichCompareBool(x, y, Py_EQ);
994 if (b == 0) {
995 cmp = PyObject_RichCompareBool(x, y, op);
996 Py_DECREF(x);
997 Py_DECREF(y);
998 goto done;
999 }
1000 Py_DECREF(x);
1001 Py_DECREF(y);
1002 if (b == -1)
1003 goto done;
1004 }
1005 /* We reached the end of one deque or both */
1006 Py_XDECREF(x);
1007 Py_XDECREF(y);
1008 if (PyErr_Occurred())
1009 goto done;
1010 switch (op) {
1011 case Py_LT: cmp = y != NULL; break; /* if w was longer */
1012 case Py_LE: cmp = x == NULL; break; /* if v was not longer */
1013 case Py_EQ: cmp = x == y; break; /* if we reached the end of both */
1014 case Py_NE: cmp = x != y; break; /* if one deque continues */
1015 case Py_GT: cmp = x != NULL; break; /* if v was longer */
1016 case Py_GE: cmp = y == NULL; break; /* if w was not longer */
1017 }
Tim Peters1065f752004-10-01 01:03:29 +00001018
Raymond Hettinger738ec902004-02-29 02:15:56 +00001019done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 Py_XDECREF(it1);
1021 Py_XDECREF(it2);
1022 if (cmp == 1)
1023 Py_RETURN_TRUE;
1024 if (cmp == 0)
1025 Py_RETURN_FALSE;
1026 return NULL;
Raymond Hettinger738ec902004-02-29 02:15:56 +00001027}
1028
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001029static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001030deque_init(dequeobject *deque, PyObject *args, PyObject *kwdargs)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001031{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001032 PyObject *iterable = NULL;
1033 PyObject *maxlenobj = NULL;
1034 Py_ssize_t maxlen = -1;
1035 char *kwlist[] = {"iterable", "maxlen", 0};
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001037 if (!PyArg_ParseTupleAndKeywords(args, kwdargs, "|OO:deque", kwlist, &iterable, &maxlenobj))
1038 return -1;
1039 if (maxlenobj != NULL && maxlenobj != Py_None) {
1040 maxlen = PyLong_AsSsize_t(maxlenobj);
1041 if (maxlen == -1 && PyErr_Occurred())
1042 return -1;
1043 if (maxlen < 0) {
1044 PyErr_SetString(PyExc_ValueError, "maxlen must be non-negative");
1045 return -1;
1046 }
1047 }
1048 deque->maxlen = maxlen;
1049 deque_clear(deque);
1050 if (iterable != NULL) {
1051 PyObject *rv = deque_extend(deque, iterable);
1052 if (rv == NULL)
1053 return -1;
1054 Py_DECREF(rv);
1055 }
1056 return 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001057}
1058
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001059static PyObject *
Jesus Cea16e2fca2012-08-03 14:49:42 +02001060deque_sizeof(dequeobject *deque, void *unused)
1061{
1062 Py_ssize_t res;
1063 Py_ssize_t blocks;
1064
1065 res = sizeof(dequeobject);
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001066 blocks = (deque->leftindex + Py_SIZE(deque) + BLOCKLEN - 1) / BLOCKLEN;
1067 assert(deque->leftindex + Py_SIZE(deque) - 1 ==
Jesus Cea16e2fca2012-08-03 14:49:42 +02001068 (blocks - 1) * BLOCKLEN + deque->rightindex);
1069 res += blocks * sizeof(block);
1070 return PyLong_FromSsize_t(res);
1071}
1072
1073PyDoc_STRVAR(sizeof_doc,
1074"D.__sizeof__() -- size of D in memory, in bytes");
1075
1076static PyObject *
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001077deque_get_maxlen(dequeobject *deque)
1078{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001079 if (deque->maxlen == -1)
1080 Py_RETURN_NONE;
1081 return PyLong_FromSsize_t(deque->maxlen);
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001082}
1083
1084static PyGetSetDef deque_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001085 {"maxlen", (getter)deque_get_maxlen, (setter)NULL,
1086 "maximum size of a deque or None if unbounded"},
1087 {0}
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001088};
1089
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001090static PySequenceMethods deque_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 (lenfunc)deque_len, /* sq_length */
1092 0, /* sq_concat */
1093 0, /* sq_repeat */
1094 (ssizeargfunc)deque_item, /* sq_item */
1095 0, /* sq_slice */
1096 (ssizeobjargproc)deque_ass_item, /* sq_ass_item */
1097 0, /* sq_ass_slice */
1098 0, /* sq_contains */
1099 (binaryfunc)deque_inplace_concat, /* sq_inplace_concat */
1100 0, /* sq_inplace_repeat */
Raymond Hettinger3f9afd82009-12-10 03:03:02 +00001101
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001102};
1103
1104/* deque object ********************************************************/
1105
1106static PyObject *deque_iter(dequeobject *deque);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001107static PyObject *deque_reviter(dequeobject *deque);
Tim Peters1065f752004-10-01 01:03:29 +00001108PyDoc_STRVAR(reversed_doc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001109 "D.__reversed__() -- return a reverse iterator over the deque");
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001110
1111static PyMethodDef deque_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001112 {"append", (PyCFunction)deque_append,
1113 METH_O, append_doc},
1114 {"appendleft", (PyCFunction)deque_appendleft,
1115 METH_O, appendleft_doc},
1116 {"clear", (PyCFunction)deque_clearmethod,
1117 METH_NOARGS, clear_doc},
1118 {"__copy__", (PyCFunction)deque_copy,
1119 METH_NOARGS, copy_doc},
1120 {"count", (PyCFunction)deque_count,
1121 METH_O, count_doc},
1122 {"extend", (PyCFunction)deque_extend,
1123 METH_O, extend_doc},
1124 {"extendleft", (PyCFunction)deque_extendleft,
1125 METH_O, extendleft_doc},
1126 {"pop", (PyCFunction)deque_pop,
1127 METH_NOARGS, pop_doc},
1128 {"popleft", (PyCFunction)deque_popleft,
1129 METH_NOARGS, popleft_doc},
1130 {"__reduce__", (PyCFunction)deque_reduce,
1131 METH_NOARGS, reduce_doc},
1132 {"remove", (PyCFunction)deque_remove,
1133 METH_O, remove_doc},
1134 {"__reversed__", (PyCFunction)deque_reviter,
1135 METH_NOARGS, reversed_doc},
1136 {"reverse", (PyCFunction)deque_reverse,
1137 METH_NOARGS, reverse_doc},
1138 {"rotate", (PyCFunction)deque_rotate,
Jesus Cea16e2fca2012-08-03 14:49:42 +02001139 METH_VARARGS, rotate_doc},
1140 {"__sizeof__", (PyCFunction)deque_sizeof,
1141 METH_NOARGS, sizeof_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142 {NULL, NULL} /* sentinel */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001143};
1144
1145PyDoc_STRVAR(deque_doc,
Andrew Svetlov6a5c7c32012-10-31 11:50:40 +02001146"deque([iterable[, maxlen]]) --> deque object\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001147\n\
Raymond Hettinger49747052011-03-29 17:36:31 -07001148Build an ordered collection with optimized access from its endpoints.");
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001149
Neal Norwitz87f10132004-02-29 15:40:53 +00001150static PyTypeObject deque_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001151 PyVarObject_HEAD_INIT(NULL, 0)
1152 "collections.deque", /* tp_name */
1153 sizeof(dequeobject), /* tp_basicsize */
1154 0, /* tp_itemsize */
1155 /* methods */
1156 (destructor)deque_dealloc, /* tp_dealloc */
1157 0, /* tp_print */
1158 0, /* tp_getattr */
1159 0, /* tp_setattr */
1160 0, /* tp_reserved */
1161 deque_repr, /* tp_repr */
1162 0, /* tp_as_number */
1163 &deque_as_sequence, /* tp_as_sequence */
1164 0, /* tp_as_mapping */
Georg Brandlf038b322010-10-18 07:35:09 +00001165 PyObject_HashNotImplemented, /* tp_hash */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 0, /* tp_call */
1167 0, /* tp_str */
1168 PyObject_GenericGetAttr, /* tp_getattro */
1169 0, /* tp_setattro */
1170 0, /* tp_as_buffer */
1171 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
Georg Brandlf038b322010-10-18 07:35:09 +00001172 /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001173 deque_doc, /* tp_doc */
1174 (traverseproc)deque_traverse, /* tp_traverse */
1175 (inquiry)deque_clear, /* tp_clear */
1176 (richcmpfunc)deque_richcompare, /* tp_richcompare */
Georg Brandlf038b322010-10-18 07:35:09 +00001177 offsetof(dequeobject, weakreflist), /* tp_weaklistoffset*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178 (getiterfunc)deque_iter, /* tp_iter */
1179 0, /* tp_iternext */
1180 deque_methods, /* tp_methods */
1181 0, /* tp_members */
Georg Brandlf038b322010-10-18 07:35:09 +00001182 deque_getset, /* tp_getset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 0, /* tp_base */
1184 0, /* tp_dict */
1185 0, /* tp_descr_get */
1186 0, /* tp_descr_set */
1187 0, /* tp_dictoffset */
1188 (initproc)deque_init, /* tp_init */
1189 PyType_GenericAlloc, /* tp_alloc */
1190 deque_new, /* tp_new */
1191 PyObject_GC_Del, /* tp_free */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001192};
1193
1194/*********************** Deque Iterator **************************/
1195
1196typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001197 PyObject_HEAD
1198 Py_ssize_t index;
1199 block *b;
1200 dequeobject *deque;
1201 long state; /* state when the iterator is created */
1202 Py_ssize_t counter; /* number of items remaining for iteration */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001203} dequeiterobject;
1204
Martin v. Löwis59683e82008-06-13 07:50:45 +00001205static PyTypeObject dequeiter_type;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001206
1207static PyObject *
1208deque_iter(dequeobject *deque)
1209{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001210 dequeiterobject *it;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001212 it = PyObject_GC_New(dequeiterobject, &dequeiter_type);
1213 if (it == NULL)
1214 return NULL;
1215 it->b = deque->leftblock;
1216 it->index = deque->leftindex;
1217 Py_INCREF(deque);
1218 it->deque = deque;
1219 it->state = deque->state;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001220 it->counter = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001221 PyObject_GC_Track(it);
1222 return (PyObject *)it;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001223}
1224
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001225static int
1226dequeiter_traverse(dequeiterobject *dio, visitproc visit, void *arg)
1227{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001228 Py_VISIT(dio->deque);
1229 return 0;
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001230}
1231
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001232static void
1233dequeiter_dealloc(dequeiterobject *dio)
1234{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001235 Py_XDECREF(dio->deque);
1236 PyObject_GC_Del(dio);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001237}
1238
1239static PyObject *
1240dequeiter_next(dequeiterobject *it)
1241{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001242 PyObject *item;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001244 if (it->deque->state != it->state) {
1245 it->counter = 0;
1246 PyErr_SetString(PyExc_RuntimeError,
1247 "deque mutated during iteration");
1248 return NULL;
1249 }
1250 if (it->counter == 0)
1251 return NULL;
1252 assert (!(it->b == it->deque->rightblock &&
1253 it->index > it->deque->rightindex));
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001255 item = it->b->data[it->index];
1256 it->index++;
1257 it->counter--;
1258 if (it->index == BLOCKLEN && it->counter > 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -10001259 CHECK_NOT_END(it->b->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001260 it->b = it->b->rightlink;
1261 it->index = 0;
1262 }
1263 Py_INCREF(item);
1264 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001265}
1266
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001267static PyObject *
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001268dequeiter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1269{
1270 Py_ssize_t i, index=0;
1271 PyObject *deque;
1272 dequeiterobject *it;
1273 if (!PyArg_ParseTuple(args, "O!|n", &deque_type, &deque, &index))
1274 return NULL;
1275 assert(type == &dequeiter_type);
1276
1277 it = (dequeiterobject*)deque_iter((dequeobject *)deque);
1278 if (!it)
1279 return NULL;
1280 /* consume items from the queue */
1281 for(i=0; i<index; i++) {
1282 PyObject *item = dequeiter_next(it);
1283 if (item) {
1284 Py_DECREF(item);
1285 } else {
1286 if (it->counter) {
1287 Py_DECREF(it);
1288 return NULL;
1289 } else
1290 break;
1291 }
1292 }
1293 return (PyObject*)it;
1294}
1295
1296static PyObject *
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001297dequeiter_len(dequeiterobject *it)
1298{
Antoine Pitrou554f3342010-08-17 18:30:06 +00001299 return PyLong_FromSsize_t(it->counter);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001300}
1301
Armin Rigof5b3e362006-02-11 21:32:43 +00001302PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001303
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001304static PyObject *
1305dequeiter_reduce(dequeiterobject *it)
1306{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001307 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 +00001308}
1309
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001310static PyMethodDef dequeiter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001311 {"__length_hint__", (PyCFunction)dequeiter_len, METH_NOARGS, length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001312 {"__reduce__", (PyCFunction)dequeiter_reduce, METH_NOARGS, reduce_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001313 {NULL, NULL} /* sentinel */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001314};
1315
Martin v. Löwis59683e82008-06-13 07:50:45 +00001316static PyTypeObject dequeiter_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001317 PyVarObject_HEAD_INIT(NULL, 0)
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001318 "_collections._deque_iterator", /* tp_name */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001319 sizeof(dequeiterobject), /* tp_basicsize */
1320 0, /* tp_itemsize */
1321 /* methods */
1322 (destructor)dequeiter_dealloc, /* tp_dealloc */
1323 0, /* tp_print */
1324 0, /* tp_getattr */
1325 0, /* tp_setattr */
1326 0, /* tp_reserved */
1327 0, /* tp_repr */
1328 0, /* tp_as_number */
1329 0, /* tp_as_sequence */
1330 0, /* tp_as_mapping */
1331 0, /* tp_hash */
1332 0, /* tp_call */
1333 0, /* tp_str */
1334 PyObject_GenericGetAttr, /* tp_getattro */
1335 0, /* tp_setattro */
1336 0, /* tp_as_buffer */
1337 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
1338 0, /* tp_doc */
1339 (traverseproc)dequeiter_traverse, /* tp_traverse */
1340 0, /* tp_clear */
1341 0, /* tp_richcompare */
1342 0, /* tp_weaklistoffset */
1343 PyObject_SelfIter, /* tp_iter */
1344 (iternextfunc)dequeiter_next, /* tp_iternext */
1345 dequeiter_methods, /* tp_methods */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001346 0, /* tp_members */
1347 0, /* tp_getset */
1348 0, /* tp_base */
1349 0, /* tp_dict */
1350 0, /* tp_descr_get */
1351 0, /* tp_descr_set */
1352 0, /* tp_dictoffset */
1353 0, /* tp_init */
1354 0, /* tp_alloc */
1355 dequeiter_new, /* tp_new */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001356 0,
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001357};
1358
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001359/*********************** Deque Reverse Iterator **************************/
1360
Martin v. Löwis59683e82008-06-13 07:50:45 +00001361static PyTypeObject dequereviter_type;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001362
1363static PyObject *
1364deque_reviter(dequeobject *deque)
1365{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001366 dequeiterobject *it;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001368 it = PyObject_GC_New(dequeiterobject, &dequereviter_type);
1369 if (it == NULL)
1370 return NULL;
1371 it->b = deque->rightblock;
1372 it->index = deque->rightindex;
1373 Py_INCREF(deque);
1374 it->deque = deque;
1375 it->state = deque->state;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001376 it->counter = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001377 PyObject_GC_Track(it);
1378 return (PyObject *)it;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001379}
1380
1381static PyObject *
1382dequereviter_next(dequeiterobject *it)
1383{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001384 PyObject *item;
1385 if (it->counter == 0)
1386 return NULL;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001388 if (it->deque->state != it->state) {
1389 it->counter = 0;
1390 PyErr_SetString(PyExc_RuntimeError,
1391 "deque mutated during iteration");
1392 return NULL;
1393 }
1394 assert (!(it->b == it->deque->leftblock &&
1395 it->index < it->deque->leftindex));
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001396
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001397 item = it->b->data[it->index];
1398 it->index--;
1399 it->counter--;
1400 if (it->index == -1 && it->counter > 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -10001401 CHECK_NOT_END(it->b->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001402 it->b = it->b->leftlink;
1403 it->index = BLOCKLEN - 1;
1404 }
1405 Py_INCREF(item);
1406 return item;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001407}
1408
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001409static PyObject *
1410dequereviter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1411{
1412 Py_ssize_t i, index=0;
1413 PyObject *deque;
1414 dequeiterobject *it;
1415 if (!PyArg_ParseTuple(args, "O!|n", &deque_type, &deque, &index))
1416 return NULL;
1417 assert(type == &dequereviter_type);
1418
1419 it = (dequeiterobject*)deque_reviter((dequeobject *)deque);
1420 if (!it)
1421 return NULL;
1422 /* consume items from the queue */
1423 for(i=0; i<index; i++) {
1424 PyObject *item = dequereviter_next(it);
1425 if (item) {
1426 Py_DECREF(item);
1427 } else {
1428 if (it->counter) {
1429 Py_DECREF(it);
1430 return NULL;
1431 } else
1432 break;
1433 }
1434 }
1435 return (PyObject*)it;
1436}
1437
Martin v. Löwis59683e82008-06-13 07:50:45 +00001438static PyTypeObject dequereviter_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001439 PyVarObject_HEAD_INIT(NULL, 0)
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001440 "_collections._deque_reverse_iterator", /* tp_name */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001441 sizeof(dequeiterobject), /* tp_basicsize */
1442 0, /* tp_itemsize */
1443 /* methods */
1444 (destructor)dequeiter_dealloc, /* tp_dealloc */
1445 0, /* tp_print */
1446 0, /* tp_getattr */
1447 0, /* tp_setattr */
1448 0, /* tp_reserved */
1449 0, /* tp_repr */
1450 0, /* tp_as_number */
1451 0, /* tp_as_sequence */
1452 0, /* tp_as_mapping */
1453 0, /* tp_hash */
1454 0, /* tp_call */
1455 0, /* tp_str */
1456 PyObject_GenericGetAttr, /* tp_getattro */
1457 0, /* tp_setattro */
1458 0, /* tp_as_buffer */
1459 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
1460 0, /* tp_doc */
1461 (traverseproc)dequeiter_traverse, /* tp_traverse */
1462 0, /* tp_clear */
1463 0, /* tp_richcompare */
1464 0, /* tp_weaklistoffset */
1465 PyObject_SelfIter, /* tp_iter */
1466 (iternextfunc)dequereviter_next, /* tp_iternext */
1467 dequeiter_methods, /* tp_methods */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001468 0, /* tp_members */
1469 0, /* tp_getset */
1470 0, /* tp_base */
1471 0, /* tp_dict */
1472 0, /* tp_descr_get */
1473 0, /* tp_descr_set */
1474 0, /* tp_dictoffset */
1475 0, /* tp_init */
1476 0, /* tp_alloc */
1477 dequereviter_new, /* tp_new */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001478 0,
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001479};
1480
Guido van Rossum1968ad32006-02-25 22:38:04 +00001481/* defaultdict type *********************************************************/
1482
1483typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001484 PyDictObject dict;
1485 PyObject *default_factory;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001486} defdictobject;
1487
1488static PyTypeObject defdict_type; /* Forward */
1489
1490PyDoc_STRVAR(defdict_missing_doc,
1491"__missing__(key) # Called by __getitem__ for missing key; pseudo-code:\n\
Guido van Rossumd8faa362007-04-27 19:54:29 +00001492 if self.default_factory is None: raise KeyError((key,))\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00001493 self[key] = value = self.default_factory()\n\
1494 return value\n\
1495");
1496
1497static PyObject *
1498defdict_missing(defdictobject *dd, PyObject *key)
1499{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001500 PyObject *factory = dd->default_factory;
1501 PyObject *value;
1502 if (factory == NULL || factory == Py_None) {
1503 /* XXX Call dict.__missing__(key) */
1504 PyObject *tup;
1505 tup = PyTuple_Pack(1, key);
1506 if (!tup) return NULL;
1507 PyErr_SetObject(PyExc_KeyError, tup);
1508 Py_DECREF(tup);
1509 return NULL;
1510 }
1511 value = PyEval_CallObject(factory, NULL);
1512 if (value == NULL)
1513 return value;
1514 if (PyObject_SetItem((PyObject *)dd, key, value) < 0) {
1515 Py_DECREF(value);
1516 return NULL;
1517 }
1518 return value;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001519}
1520
1521PyDoc_STRVAR(defdict_copy_doc, "D.copy() -> a shallow copy of D.");
1522
1523static PyObject *
1524defdict_copy(defdictobject *dd)
1525{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001526 /* This calls the object's class. That only works for subclasses
1527 whose class constructor has the same signature. Subclasses that
1528 define a different constructor signature must override copy().
1529 */
Raymond Hettinger54628fa2009-08-04 19:16:39 +00001530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001531 if (dd->default_factory == NULL)
1532 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd), Py_None, dd, NULL);
1533 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd),
1534 dd->default_factory, dd, NULL);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001535}
1536
1537static PyObject *
1538defdict_reduce(defdictobject *dd)
1539{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001540 /* __reduce__ must return a 5-tuple as follows:
Guido van Rossum1968ad32006-02-25 22:38:04 +00001541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001542 - factory function
1543 - tuple of args for the factory function
1544 - additional state (here None)
1545 - sequence iterator (here None)
1546 - dictionary iterator (yielding successive (key, value) pairs
Guido van Rossum1968ad32006-02-25 22:38:04 +00001547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001548 This API is used by pickle.py and copy.py.
Guido van Rossum1968ad32006-02-25 22:38:04 +00001549
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001550 For this to be useful with pickle.py, the default_factory
1551 must be picklable; e.g., None, a built-in, or a global
1552 function in a module or package.
Guido van Rossum1968ad32006-02-25 22:38:04 +00001553
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001554 Both shallow and deep copying are supported, but for deep
1555 copying, the default_factory must be deep-copyable; e.g. None,
1556 or a built-in (functions are not copyable at this time).
Guido van Rossum1968ad32006-02-25 22:38:04 +00001557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001558 This only works for subclasses as long as their constructor
1559 signature is compatible; the first argument must be the
1560 optional default_factory, defaulting to None.
1561 */
1562 PyObject *args;
1563 PyObject *items;
1564 PyObject *iter;
1565 PyObject *result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001566 _Py_IDENTIFIER(items);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001568 if (dd->default_factory == NULL || dd->default_factory == Py_None)
1569 args = PyTuple_New(0);
1570 else
1571 args = PyTuple_Pack(1, dd->default_factory);
1572 if (args == NULL)
1573 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001574 items = _PyObject_CallMethodId((PyObject *)dd, &PyId_items, "()");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001575 if (items == NULL) {
1576 Py_DECREF(args);
1577 return NULL;
1578 }
1579 iter = PyObject_GetIter(items);
1580 if (iter == NULL) {
1581 Py_DECREF(items);
1582 Py_DECREF(args);
1583 return NULL;
1584 }
1585 result = PyTuple_Pack(5, Py_TYPE(dd), args,
1586 Py_None, Py_None, iter);
1587 Py_DECREF(iter);
1588 Py_DECREF(items);
1589 Py_DECREF(args);
1590 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001591}
1592
1593static PyMethodDef defdict_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001594 {"__missing__", (PyCFunction)defdict_missing, METH_O,
1595 defdict_missing_doc},
1596 {"copy", (PyCFunction)defdict_copy, METH_NOARGS,
1597 defdict_copy_doc},
1598 {"__copy__", (PyCFunction)defdict_copy, METH_NOARGS,
1599 defdict_copy_doc},
1600 {"__reduce__", (PyCFunction)defdict_reduce, METH_NOARGS,
1601 reduce_doc},
1602 {NULL}
Guido van Rossum1968ad32006-02-25 22:38:04 +00001603};
1604
1605static PyMemberDef defdict_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001606 {"default_factory", T_OBJECT,
1607 offsetof(defdictobject, default_factory), 0,
1608 PyDoc_STR("Factory for default value called by __missing__().")},
1609 {NULL}
Guido van Rossum1968ad32006-02-25 22:38:04 +00001610};
1611
1612static void
1613defdict_dealloc(defdictobject *dd)
1614{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001615 Py_CLEAR(dd->default_factory);
1616 PyDict_Type.tp_dealloc((PyObject *)dd);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001617}
1618
Guido van Rossum1968ad32006-02-25 22:38:04 +00001619static PyObject *
1620defdict_repr(defdictobject *dd)
1621{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001622 PyObject *baserepr;
1623 PyObject *defrepr;
1624 PyObject *result;
1625 baserepr = PyDict_Type.tp_repr((PyObject *)dd);
1626 if (baserepr == NULL)
1627 return NULL;
1628 if (dd->default_factory == NULL)
1629 defrepr = PyUnicode_FromString("None");
1630 else
1631 {
1632 int status = Py_ReprEnter(dd->default_factory);
1633 if (status != 0) {
Antoine Pitrouf5f1fe02012-02-15 02:42:46 +01001634 if (status < 0) {
1635 Py_DECREF(baserepr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001636 return NULL;
Antoine Pitrouf5f1fe02012-02-15 02:42:46 +01001637 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001638 defrepr = PyUnicode_FromString("...");
1639 }
1640 else
1641 defrepr = PyObject_Repr(dd->default_factory);
1642 Py_ReprLeave(dd->default_factory);
1643 }
1644 if (defrepr == NULL) {
1645 Py_DECREF(baserepr);
1646 return NULL;
1647 }
1648 result = PyUnicode_FromFormat("defaultdict(%U, %U)",
1649 defrepr, baserepr);
1650 Py_DECREF(defrepr);
1651 Py_DECREF(baserepr);
1652 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001653}
1654
1655static int
1656defdict_traverse(PyObject *self, visitproc visit, void *arg)
1657{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001658 Py_VISIT(((defdictobject *)self)->default_factory);
1659 return PyDict_Type.tp_traverse(self, visit, arg);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001660}
1661
1662static int
1663defdict_tp_clear(defdictobject *dd)
1664{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001665 Py_CLEAR(dd->default_factory);
1666 return PyDict_Type.tp_clear((PyObject *)dd);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001667}
1668
1669static int
1670defdict_init(PyObject *self, PyObject *args, PyObject *kwds)
1671{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001672 defdictobject *dd = (defdictobject *)self;
1673 PyObject *olddefault = dd->default_factory;
1674 PyObject *newdefault = NULL;
1675 PyObject *newargs;
1676 int result;
1677 if (args == NULL || !PyTuple_Check(args))
1678 newargs = PyTuple_New(0);
1679 else {
1680 Py_ssize_t n = PyTuple_GET_SIZE(args);
1681 if (n > 0) {
1682 newdefault = PyTuple_GET_ITEM(args, 0);
1683 if (!PyCallable_Check(newdefault) && newdefault != Py_None) {
1684 PyErr_SetString(PyExc_TypeError,
1685 "first argument must be callable");
1686 return -1;
1687 }
1688 }
1689 newargs = PySequence_GetSlice(args, 1, n);
1690 }
1691 if (newargs == NULL)
1692 return -1;
1693 Py_XINCREF(newdefault);
1694 dd->default_factory = newdefault;
1695 result = PyDict_Type.tp_init(self, newargs, kwds);
1696 Py_DECREF(newargs);
1697 Py_XDECREF(olddefault);
1698 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001699}
1700
1701PyDoc_STRVAR(defdict_doc,
Benjamin Peterson9cb33b72014-01-13 23:56:05 -05001702"defaultdict(default_factory[, ...]) --> dict with default factory\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00001703\n\
1704The default factory is called without arguments to produce\n\
1705a new value when a key is not present, in __getitem__ only.\n\
1706A defaultdict compares equal to a dict with the same items.\n\
Benjamin Peterson9cb33b72014-01-13 23:56:05 -05001707All remaining arguments are treated the same as if they were\n\
1708passed to the dict constructor, including keyword arguments.\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00001709");
1710
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001711/* See comment in xxsubtype.c */
1712#define DEFERRED_ADDRESS(ADDR) 0
1713
Guido van Rossum1968ad32006-02-25 22:38:04 +00001714static PyTypeObject defdict_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001715 PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0)
1716 "collections.defaultdict", /* tp_name */
1717 sizeof(defdictobject), /* tp_basicsize */
1718 0, /* tp_itemsize */
1719 /* methods */
1720 (destructor)defdict_dealloc, /* tp_dealloc */
1721 0, /* tp_print */
1722 0, /* tp_getattr */
1723 0, /* tp_setattr */
1724 0, /* tp_reserved */
1725 (reprfunc)defdict_repr, /* tp_repr */
1726 0, /* tp_as_number */
1727 0, /* tp_as_sequence */
1728 0, /* tp_as_mapping */
1729 0, /* tp_hash */
1730 0, /* tp_call */
1731 0, /* tp_str */
1732 PyObject_GenericGetAttr, /* tp_getattro */
1733 0, /* tp_setattro */
1734 0, /* tp_as_buffer */
1735 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
1736 /* tp_flags */
1737 defdict_doc, /* tp_doc */
1738 defdict_traverse, /* tp_traverse */
1739 (inquiry)defdict_tp_clear, /* tp_clear */
1740 0, /* tp_richcompare */
1741 0, /* tp_weaklistoffset*/
1742 0, /* tp_iter */
1743 0, /* tp_iternext */
1744 defdict_methods, /* tp_methods */
1745 defdict_members, /* tp_members */
1746 0, /* tp_getset */
1747 DEFERRED_ADDRESS(&PyDict_Type), /* tp_base */
1748 0, /* tp_dict */
1749 0, /* tp_descr_get */
1750 0, /* tp_descr_set */
1751 0, /* tp_dictoffset */
1752 defdict_init, /* tp_init */
1753 PyType_GenericAlloc, /* tp_alloc */
1754 0, /* tp_new */
1755 PyObject_GC_Del, /* tp_free */
Guido van Rossum1968ad32006-02-25 22:38:04 +00001756};
1757
Raymond Hettinger96f34102010-12-15 16:30:37 +00001758/* helper function for Counter *********************************************/
1759
1760PyDoc_STRVAR(_count_elements_doc,
1761"_count_elements(mapping, iterable) -> None\n\
1762\n\
1763Count elements in the iterable, updating the mappping");
1764
1765static PyObject *
1766_count_elements(PyObject *self, PyObject *args)
1767{
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07001768 _Py_IDENTIFIER(get);
Raymond Hettinger2ff21902013-10-01 00:55:43 -07001769 _Py_IDENTIFIER(__setitem__);
Raymond Hettinger96f34102010-12-15 16:30:37 +00001770 PyObject *it, *iterable, *mapping, *oldval;
1771 PyObject *newval = NULL;
1772 PyObject *key = NULL;
Raymond Hettinger224c87d2013-10-01 21:36:09 -07001773 PyObject *zero = NULL;
Raymond Hettinger96f34102010-12-15 16:30:37 +00001774 PyObject *one = NULL;
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07001775 PyObject *bound_get = NULL;
1776 PyObject *mapping_get;
1777 PyObject *dict_get;
Raymond Hettinger2ff21902013-10-01 00:55:43 -07001778 PyObject *mapping_setitem;
Raymond Hettinger2ff21902013-10-01 00:55:43 -07001779 PyObject *dict_setitem;
Raymond Hettinger96f34102010-12-15 16:30:37 +00001780
1781 if (!PyArg_UnpackTuple(args, "_count_elements", 2, 2, &mapping, &iterable))
1782 return NULL;
1783
Raymond Hettinger96f34102010-12-15 16:30:37 +00001784 it = PyObject_GetIter(iterable);
1785 if (it == NULL)
1786 return NULL;
Raymond Hettinger426e0522011-01-03 02:12:02 +00001787
Raymond Hettinger96f34102010-12-15 16:30:37 +00001788 one = PyLong_FromLong(1);
Raymond Hettinger224c87d2013-10-01 21:36:09 -07001789 if (one == NULL)
1790 goto done;
Raymond Hettinger426e0522011-01-03 02:12:02 +00001791
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07001792 /* Only take the fast path when get() and __setitem__()
1793 * have not been overridden.
1794 */
1795 mapping_get = _PyType_LookupId(Py_TYPE(mapping), &PyId_get);
1796 dict_get = _PyType_LookupId(&PyDict_Type, &PyId_get);
Raymond Hettinger2ff21902013-10-01 00:55:43 -07001797 mapping_setitem = _PyType_LookupId(Py_TYPE(mapping), &PyId___setitem__);
1798 dict_setitem = _PyType_LookupId(&PyDict_Type, &PyId___setitem__);
1799
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07001800 if (mapping_get != NULL && mapping_get == dict_get &&
1801 mapping_setitem != NULL && mapping_setitem == dict_setitem) {
Raymond Hettinger426e0522011-01-03 02:12:02 +00001802 while (1) {
1803 key = PyIter_Next(it);
Victor Stinnera154b5c2011-04-20 23:23:52 +02001804 if (key == NULL)
1805 break;
Raymond Hettinger426e0522011-01-03 02:12:02 +00001806 oldval = PyDict_GetItem(mapping, key);
1807 if (oldval == NULL) {
1808 if (PyDict_SetItem(mapping, key, one) == -1)
1809 break;
1810 } else {
1811 newval = PyNumber_Add(oldval, one);
1812 if (newval == NULL)
1813 break;
1814 if (PyDict_SetItem(mapping, key, newval) == -1)
1815 break;
1816 Py_CLEAR(newval);
1817 }
1818 Py_DECREF(key);
Raymond Hettinger96f34102010-12-15 16:30:37 +00001819 }
Raymond Hettinger426e0522011-01-03 02:12:02 +00001820 } else {
Victor Stinnere7f516c2013-11-06 23:52:55 +01001821 bound_get = _PyObject_GetAttrId(mapping, &PyId_get);
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07001822 if (bound_get == NULL)
Raymond Hettinger224c87d2013-10-01 21:36:09 -07001823 goto done;
1824
1825 zero = PyLong_FromLong(0);
1826 if (zero == NULL)
1827 goto done;
1828
Raymond Hettinger426e0522011-01-03 02:12:02 +00001829 while (1) {
1830 key = PyIter_Next(it);
Victor Stinnera154b5c2011-04-20 23:23:52 +02001831 if (key == NULL)
1832 break;
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07001833 oldval = PyObject_CallFunctionObjArgs(bound_get, key, zero, NULL);
Raymond Hettinger224c87d2013-10-01 21:36:09 -07001834 if (oldval == NULL)
1835 break;
1836 newval = PyNumber_Add(oldval, one);
1837 Py_DECREF(oldval);
1838 if (newval == NULL)
1839 break;
Raymond Hettinger426e0522011-01-03 02:12:02 +00001840 if (PyObject_SetItem(mapping, key, newval) == -1)
Raymond Hettinger96f34102010-12-15 16:30:37 +00001841 break;
1842 Py_CLEAR(newval);
Raymond Hettinger426e0522011-01-03 02:12:02 +00001843 Py_DECREF(key);
Raymond Hettinger96f34102010-12-15 16:30:37 +00001844 }
Raymond Hettinger96f34102010-12-15 16:30:37 +00001845 }
Raymond Hettinger426e0522011-01-03 02:12:02 +00001846
Raymond Hettinger224c87d2013-10-01 21:36:09 -07001847done:
Raymond Hettinger96f34102010-12-15 16:30:37 +00001848 Py_DECREF(it);
1849 Py_XDECREF(key);
1850 Py_XDECREF(newval);
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07001851 Py_XDECREF(bound_get);
Raymond Hettinger224c87d2013-10-01 21:36:09 -07001852 Py_XDECREF(zero);
1853 Py_XDECREF(one);
Raymond Hettinger96f34102010-12-15 16:30:37 +00001854 if (PyErr_Occurred())
1855 return NULL;
1856 Py_RETURN_NONE;
1857}
1858
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001859/* module level code ********************************************************/
1860
1861PyDoc_STRVAR(module_doc,
Guido van Rossum1968ad32006-02-25 22:38:04 +00001862"High performance data structures.\n\
1863- deque: ordered collection accessible from endpoints only\n\
1864- defaultdict: dict subclass with a default value factory\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001865");
1866
Raymond Hettinger96f34102010-12-15 16:30:37 +00001867static struct PyMethodDef module_functions[] = {
1868 {"_count_elements", _count_elements, METH_VARARGS, _count_elements_doc},
1869 {NULL, NULL} /* sentinel */
1870};
Martin v. Löwis1a214512008-06-11 05:26:20 +00001871
1872static struct PyModuleDef _collectionsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001873 PyModuleDef_HEAD_INIT,
1874 "_collections",
1875 module_doc,
1876 -1,
Raymond Hettinger96f34102010-12-15 16:30:37 +00001877 module_functions,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001878 NULL,
1879 NULL,
1880 NULL,
1881 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001882};
1883
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001884PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001885PyInit__collections(void)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001886{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001887 PyObject *m;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001889 m = PyModule_Create(&_collectionsmodule);
1890 if (m == NULL)
1891 return NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001893 if (PyType_Ready(&deque_type) < 0)
1894 return NULL;
1895 Py_INCREF(&deque_type);
1896 PyModule_AddObject(m, "deque", (PyObject *)&deque_type);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001898 defdict_type.tp_base = &PyDict_Type;
1899 if (PyType_Ready(&defdict_type) < 0)
1900 return NULL;
1901 Py_INCREF(&defdict_type);
1902 PyModule_AddObject(m, "defaultdict", (PyObject *)&defdict_type);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001904 if (PyType_Ready(&dequeiter_type) < 0)
1905 return NULL;
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001906 Py_INCREF(&dequeiter_type);
1907 PyModule_AddObject(m, "_deque_iterator", (PyObject *)&dequeiter_type);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001908
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001909 if (PyType_Ready(&dequereviter_type) < 0)
1910 return NULL;
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001911 Py_INCREF(&dequereviter_type);
1912 PyModule_AddObject(m, "_deque_reverse_iterator", (PyObject *)&dequereviter_type);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001914 return m;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001915}