blob: 5d5fc912a15c46c9285f0178ac713ad6707a074d [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.
13 * If the block length is a power-of-two, we also get faster
14 * division/modulo computations during indexing.
Raymond Hettinger77e8bf12004-10-01 15:25:53 +000015 */
16
Raymond Hettingerde68e0c2013-07-05 18:05:29 -100017#define BLOCKLEN 64
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000018#define CENTER ((BLOCKLEN - 1) / 2)
Raymond Hettinger756b3f32004-01-29 06:37:52 +000019
Tim Petersd8768d32004-10-01 01:32:53 +000020/* A `dequeobject` is composed of a doubly-linked list of `block` nodes.
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000021 * The list of blocks is never empty, so d.leftblock and d.rightblock
Raymond Hettinger82df9252013-07-07 01:43:42 -100022 * are never equal to NULL. The list is not circular.
23 *
24 * A deque d's first element is at d.leftblock[leftindex]
25 * and its last element is at d.rightblock[rightindex].
26 * Unlike Python slice indices, these indices are inclusive
27 * on both ends. This makes the algorithms for left and
28 * right operations more symmetrical and simplifies the design.
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000029 *
30 * The indices, d.leftindex and d.rightindex are always in the range
31 * 0 <= index < BLOCKLEN.
Raymond Hettinger4ca4c7c2004-10-01 15:14:39 +000032 * Their exact relationship is:
33 * (d.leftindex + d.len - 1) % BLOCKLEN == d.rightindex.
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000034 *
35 * Empty deques have d.len == 0; d.leftblock==d.rightblock;
36 * d.leftindex == CENTER+1; and d.rightindex == CENTER.
37 * Checking for d.len == 0 is the intended way to see whether d is empty.
38 *
Thomas Wouters0e3f5912006-08-11 14:57:12 +000039 * Whenever d.leftblock == d.rightblock,
Raymond Hettinger4ca4c7c2004-10-01 15:14:39 +000040 * d.leftindex + d.len - 1 == d.rightindex.
Thomas Wouters0e3f5912006-08-11 14:57:12 +000041 *
Raymond Hettinger4ca4c7c2004-10-01 15:14:39 +000042 * However, when d.leftblock != d.rightblock, d.leftindex and d.rightindex
Thomas Wouters0e3f5912006-08-11 14:57:12 +000043 * become indices into distinct blocks and either may be larger than the
Raymond Hettinger4ca4c7c2004-10-01 15:14:39 +000044 * other.
Tim Petersd8768d32004-10-01 01:32:53 +000045 */
46
Raymond Hettinger756b3f32004-01-29 06:37:52 +000047typedef struct BLOCK {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000048 struct BLOCK *leftlink;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000049 PyObject *data[BLOCKLEN];
Raymond Hettinger20b0f872013-06-23 15:44:33 -070050 struct BLOCK *rightlink;
Raymond Hettinger756b3f32004-01-29 06:37:52 +000051} block;
52
Raymond Hettinger82df9252013-07-07 01:43:42 -100053/* For debug builds, add error checking to track the endpoints
54 * in the chain of links. The goal is to make sure that link
55 * assignments only take place at endpoints so that links already
56 * in use do not get overwritten.
57 *
58 * CHECK_END should happen before each assignment to a block's link field.
59 * MARK_END should happen whenever a link field becomes a new endpoint.
60 * This happens when new blocks are added or whenever an existing
61 * block is freed leaving another existing block as the new endpoint.
62 */
63
Raymond Hettingerb3855292013-07-07 02:07:23 -100064#ifdef Py_DEBUG
Raymond Hettinger82df9252013-07-07 01:43:42 -100065#define MARK_END(link) link = NULL;
66#define CHECK_END(link) assert(link == NULL);
67#define CHECK_NOT_END(link) assert(link != NULL);
68#else
69#define MARK_END(link)
70#define CHECK_END(link)
71#define CHECK_NOT_END(link)
72#endif
73
74/* A simple freelisting scheme is used to minimize calls to the memory
75 allocator. It accomodates common use cases where new blocks are being
76 added at about the same rate as old blocks are being freed.
77 */
78
Guido van Rossum58da9312007-11-10 23:39:45 +000079#define MAXFREEBLOCKS 10
Benjamin Petersond6313712008-07-31 16:23:04 +000080static Py_ssize_t numfreeblocks = 0;
Guido van Rossum58da9312007-11-10 23:39:45 +000081static block *freeblocks[MAXFREEBLOCKS];
82
Tim Peters6f853562004-10-01 01:04:50 +000083static block *
Raymond Hettinger82df9252013-07-07 01:43:42 -100084newblock(Py_ssize_t len) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000085 block *b;
Raymond Hettinger20b0f872013-06-23 15:44:33 -070086 /* To prevent len from overflowing PY_SSIZE_T_MAX, we refuse to
87 * allocate new blocks if the current len is nearing overflow. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000088 if (len >= PY_SSIZE_T_MAX - 2*BLOCKLEN) {
89 PyErr_SetString(PyExc_OverflowError,
90 "cannot add more blocks to the deque");
91 return NULL;
92 }
93 if (numfreeblocks) {
Raymond Hettinger59cf23a2013-02-07 00:57:19 -050094 numfreeblocks--;
Raymond Hettinger82df9252013-07-07 01:43:42 -100095 return freeblocks[numfreeblocks];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000096 }
Raymond Hettinger82df9252013-07-07 01:43:42 -100097 b = PyMem_Malloc(sizeof(block));
98 if (b != NULL) {
99 return b;
100 }
101 PyErr_NoMemory();
102 return NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000103}
104
Martin v. Löwis59683e82008-06-13 07:50:45 +0000105static void
Guido van Rossum58da9312007-11-10 23:39:45 +0000106freeblock(block *b)
107{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000108 if (numfreeblocks < MAXFREEBLOCKS) {
109 freeblocks[numfreeblocks] = b;
110 numfreeblocks++;
111 } else {
112 PyMem_Free(b);
113 }
Guido van Rossum58da9312007-11-10 23:39:45 +0000114}
115
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000116typedef struct {
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000117 PyObject_VAR_HEAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000118 block *leftblock;
119 block *rightblock;
120 Py_ssize_t leftindex; /* in range(BLOCKLEN) */
121 Py_ssize_t rightindex; /* in range(BLOCKLEN) */
Raymond Hettinger90dea4c2013-07-13 22:30:25 -0700122 long state; /* incremented whenever the indices move */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000123 Py_ssize_t maxlen;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000124 PyObject *weakreflist; /* List of weak references */
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000125} dequeobject;
126
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000127/* The deque's size limit is d.maxlen. The limit can be zero or positive.
128 * If there is no limit, then d.maxlen == -1.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000129 *
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000130 * After an item is added to a deque, we check to see if the size has grown past
131 * the limit. If it has, we get the size back down to the limit by popping an
132 * item off of the opposite end. The methods that can trigger this are append(),
133 * appendleft(), extend(), and extendleft().
134 */
135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000136#define TRIM(d, popfunction) \
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000137 if (d->maxlen != -1 && Py_SIZE(d) > d->maxlen) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000138 PyObject *rv = popfunction(d, NULL); \
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000139 assert(rv != NULL && Py_SIZE(d) <= d->maxlen); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000140 Py_DECREF(rv); \
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000141 }
142
Neal Norwitz87f10132004-02-29 15:40:53 +0000143static PyTypeObject deque_type;
Raymond Hettinger738ec902004-02-29 02:15:56 +0000144
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000145static PyObject *
146deque_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
147{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000148 dequeobject *deque;
149 block *b;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000150
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000151 /* create dequeobject structure */
152 deque = (dequeobject *)type->tp_alloc(type, 0);
153 if (deque == NULL)
154 return NULL;
Tim Peters1065f752004-10-01 01:03:29 +0000155
Raymond Hettinger82df9252013-07-07 01:43:42 -1000156 b = newblock(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000157 if (b == NULL) {
158 Py_DECREF(deque);
159 return NULL;
160 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000161 MARK_END(b->leftlink);
162 MARK_END(b->rightlink);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000164 assert(BLOCKLEN >= 2);
165 deque->leftblock = b;
166 deque->rightblock = b;
167 deque->leftindex = CENTER + 1;
168 deque->rightindex = CENTER;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000169 Py_SIZE(deque) = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000170 deque->state = 0;
171 deque->weakreflist = NULL;
172 deque->maxlen = -1;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000174 return (PyObject *)deque;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000175}
176
177static PyObject *
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000178deque_pop(dequeobject *deque, PyObject *unused)
179{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000180 PyObject *item;
181 block *prevblock;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000182
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000183 if (Py_SIZE(deque) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000184 PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
185 return NULL;
186 }
187 item = deque->rightblock->data[deque->rightindex];
188 deque->rightindex--;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000189 Py_SIZE(deque)--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000190 deque->state++;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000192 if (deque->rightindex == -1) {
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000193 if (Py_SIZE(deque) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000194 assert(deque->leftblock == deque->rightblock);
195 assert(deque->leftindex == deque->rightindex+1);
196 /* re-center instead of freeing a block */
197 deque->leftindex = CENTER + 1;
198 deque->rightindex = CENTER;
199 } else {
200 prevblock = deque->rightblock->leftlink;
201 assert(deque->leftblock != deque->rightblock);
202 freeblock(deque->rightblock);
Raymond Hettinger82df9252013-07-07 01:43:42 -1000203 CHECK_NOT_END(prevblock);
204 MARK_END(prevblock->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000205 deque->rightblock = prevblock;
206 deque->rightindex = BLOCKLEN - 1;
207 }
208 }
209 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000210}
211
212PyDoc_STRVAR(pop_doc, "Remove and return the rightmost element.");
213
214static PyObject *
215deque_popleft(dequeobject *deque, PyObject *unused)
216{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000217 PyObject *item;
218 block *prevblock;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000219
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000220 if (Py_SIZE(deque) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000221 PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
222 return NULL;
223 }
224 assert(deque->leftblock != NULL);
225 item = deque->leftblock->data[deque->leftindex];
226 deque->leftindex++;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000227 Py_SIZE(deque)--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000228 deque->state++;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000230 if (deque->leftindex == BLOCKLEN) {
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000231 if (Py_SIZE(deque) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000232 assert(deque->leftblock == deque->rightblock);
233 assert(deque->leftindex == deque->rightindex+1);
234 /* re-center instead of freeing a block */
235 deque->leftindex = CENTER + 1;
236 deque->rightindex = CENTER;
237 } else {
238 assert(deque->leftblock != deque->rightblock);
239 prevblock = deque->leftblock->rightlink;
240 freeblock(deque->leftblock);
Raymond Hettinger82df9252013-07-07 01:43:42 -1000241 CHECK_NOT_END(prevblock);
242 MARK_END(prevblock->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000243 deque->leftblock = prevblock;
244 deque->leftindex = 0;
245 }
246 }
247 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000248}
249
250PyDoc_STRVAR(popleft_doc, "Remove and return the leftmost element.");
251
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000252static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000253deque_append(dequeobject *deque, PyObject *item)
254{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000255 deque->state++;
256 if (deque->rightindex == BLOCKLEN-1) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000257 block *b = newblock(Py_SIZE(deque));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000258 if (b == NULL)
259 return NULL;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000260 b->leftlink = deque->rightblock;
261 CHECK_END(deque->rightblock->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000262 deque->rightblock->rightlink = b;
263 deque->rightblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000264 MARK_END(b->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000265 deque->rightindex = -1;
266 }
267 Py_INCREF(item);
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000268 Py_SIZE(deque)++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000269 deque->rightindex++;
270 deque->rightblock->data[deque->rightindex] = item;
271 TRIM(deque, deque_popleft);
272 Py_RETURN_NONE;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000273}
274
275PyDoc_STRVAR(append_doc, "Add an element to the right side of the deque.");
276
277static PyObject *
278deque_appendleft(dequeobject *deque, PyObject *item)
279{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 deque->state++;
281 if (deque->leftindex == 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000282 block *b = newblock(Py_SIZE(deque));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000283 if (b == NULL)
284 return NULL;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000285 b->rightlink = deque->leftblock;
286 CHECK_END(deque->leftblock->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000287 deque->leftblock->leftlink = b;
288 deque->leftblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000289 MARK_END(b->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000290 deque->leftindex = BLOCKLEN;
291 }
292 Py_INCREF(item);
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000293 Py_SIZE(deque)++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000294 deque->leftindex--;
295 deque->leftblock->data[deque->leftindex] = item;
296 TRIM(deque, deque_pop);
297 Py_RETURN_NONE;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000298}
299
300PyDoc_STRVAR(appendleft_doc, "Add an element to the left side of the deque.");
301
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000303/* Run an iterator to exhaustion. Shortcut for
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000304 the extend/extendleft methods when maxlen == 0. */
305static PyObject*
306consume_iterator(PyObject *it)
307{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000308 PyObject *item;
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000310 while ((item = PyIter_Next(it)) != NULL) {
311 Py_DECREF(item);
312 }
313 Py_DECREF(it);
314 if (PyErr_Occurred())
315 return NULL;
316 Py_RETURN_NONE;
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000317}
318
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000319static PyObject *
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000320deque_extend(dequeobject *deque, PyObject *iterable)
321{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000322 PyObject *it, *item;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000324 /* Handle case where id(deque) == id(iterable) */
325 if ((PyObject *)deque == iterable) {
326 PyObject *result;
327 PyObject *s = PySequence_List(iterable);
328 if (s == NULL)
329 return NULL;
330 result = deque_extend(deque, s);
331 Py_DECREF(s);
332 return result;
333 }
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000334
Raymond Hettingerd9c116c2013-07-09 00:13:21 -0700335 /* Space saving heuristic. Start filling from the left */
336 if (Py_SIZE(deque) == 0) {
337 assert(deque->leftblock == deque->rightblock);
338 assert(deque->leftindex == deque->rightindex+1);
339 deque->leftindex = 1;
340 deque->rightindex = 0;
341 }
342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000343 it = PyObject_GetIter(iterable);
344 if (it == NULL)
345 return NULL;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000347 if (deque->maxlen == 0)
348 return consume_iterator(it);
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000350 while ((item = PyIter_Next(it)) != NULL) {
351 deque->state++;
352 if (deque->rightindex == BLOCKLEN-1) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000353 block *b = newblock(Py_SIZE(deque));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000354 if (b == NULL) {
355 Py_DECREF(item);
356 Py_DECREF(it);
357 return NULL;
358 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000359 b->leftlink = deque->rightblock;
360 CHECK_END(deque->rightblock->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000361 deque->rightblock->rightlink = b;
362 deque->rightblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000363 MARK_END(b->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000364 deque->rightindex = -1;
365 }
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000366 Py_SIZE(deque)++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000367 deque->rightindex++;
368 deque->rightblock->data[deque->rightindex] = item;
369 TRIM(deque, deque_popleft);
370 }
371 Py_DECREF(it);
372 if (PyErr_Occurred())
373 return NULL;
374 Py_RETURN_NONE;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000375}
376
Tim Peters1065f752004-10-01 01:03:29 +0000377PyDoc_STRVAR(extend_doc,
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000378"Extend the right side of the deque with elements from the iterable");
379
380static PyObject *
381deque_extendleft(dequeobject *deque, PyObject *iterable)
382{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000383 PyObject *it, *item;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000385 /* Handle case where id(deque) == id(iterable) */
386 if ((PyObject *)deque == iterable) {
387 PyObject *result;
388 PyObject *s = PySequence_List(iterable);
389 if (s == NULL)
390 return NULL;
391 result = deque_extendleft(deque, s);
392 Py_DECREF(s);
393 return result;
394 }
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000395
Raymond Hettingerd9c116c2013-07-09 00:13:21 -0700396 /* Space saving heuristic. Start filling from the right */
397 if (Py_SIZE(deque) == 0) {
398 assert(deque->leftblock == deque->rightblock);
399 assert(deque->leftindex == deque->rightindex+1);
400 deque->leftindex = BLOCKLEN - 1;
401 deque->rightindex = BLOCKLEN - 2;
402 }
403
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000404 it = PyObject_GetIter(iterable);
405 if (it == NULL)
406 return NULL;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000408 if (deque->maxlen == 0)
409 return consume_iterator(it);
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 while ((item = PyIter_Next(it)) != NULL) {
412 deque->state++;
413 if (deque->leftindex == 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000414 block *b = newblock(Py_SIZE(deque));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000415 if (b == NULL) {
416 Py_DECREF(item);
417 Py_DECREF(it);
418 return NULL;
419 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000420 b->rightlink = deque->leftblock;
421 CHECK_END(deque->leftblock->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000422 deque->leftblock->leftlink = b;
423 deque->leftblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000424 MARK_END(b->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425 deque->leftindex = BLOCKLEN;
426 }
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000427 Py_SIZE(deque)++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000428 deque->leftindex--;
429 deque->leftblock->data[deque->leftindex] = item;
430 TRIM(deque, deque_pop);
431 }
432 Py_DECREF(it);
433 if (PyErr_Occurred())
434 return NULL;
435 Py_RETURN_NONE;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000436}
437
Tim Peters1065f752004-10-01 01:03:29 +0000438PyDoc_STRVAR(extendleft_doc,
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000439"Extend the left side of the deque with elements from the iterable");
440
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000441static PyObject *
442deque_inplace_concat(dequeobject *deque, PyObject *other)
443{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000444 PyObject *result;
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000445
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000446 result = deque_extend(deque, other);
447 if (result == NULL)
448 return result;
449 Py_DECREF(result);
450 Py_INCREF(deque);
451 return (PyObject *)deque;
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000452}
453
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000454static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000455_deque_rotate(dequeobject *deque, Py_ssize_t n)
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000456{
Raymond Hettinger3959af92013-07-13 02:34:08 -0700457 block *b = NULL;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700458 block *leftblock = deque->leftblock;
459 block *rightblock = deque->rightblock;
460 Py_ssize_t leftindex = deque->leftindex;
461 Py_ssize_t rightindex = deque->rightindex;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000462 Py_ssize_t len=Py_SIZE(deque), halflen=len>>1;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700463 int rv = -1;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000464
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800465 if (len <= 1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000466 return 0;
467 if (n > halflen || n < -halflen) {
468 n %= len;
469 if (n > halflen)
470 n -= len;
471 else if (n < -halflen)
472 n += len;
473 }
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500474 assert(len > 1);
Raymond Hettingera4409c12013-02-04 00:08:12 -0500475 assert(-halflen <= n && n <= halflen);
Raymond Hettinger231ee4d2013-02-02 11:24:43 -0800476
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800477 deque->state++;
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500478 while (n > 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700479 if (leftindex == 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700480 if (b == NULL) {
Raymond Hettinger3959af92013-07-13 02:34:08 -0700481 b = newblock(len);
482 if (b == NULL)
483 goto done;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700484 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000485 b->rightlink = leftblock;
486 CHECK_END(leftblock->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700487 leftblock->leftlink = b;
488 leftblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000489 MARK_END(b->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700490 leftindex = BLOCKLEN;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700491 b = NULL;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800492 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700493 assert(leftindex > 0);
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800494
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700495 {
496 PyObject **src, **dest;
497 Py_ssize_t m = n;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800498
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700499 if (m > rightindex + 1)
500 m = rightindex + 1;
501 if (m > leftindex)
502 m = leftindex;
503 assert (m > 0 && m <= len);
504 src = &rightblock->data[rightindex];
505 dest = &leftblock->data[leftindex - 1];
506 rightindex -= m;
507 leftindex -= m;
508 n -= m;
Raymond Hettinger840533b2013-07-13 17:03:58 -0700509 do {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700510 *(dest--) = *(src--);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700511 } while (--m);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700512 }
513
514 if (rightindex == -1) {
515 block *prevblock = rightblock->leftlink;
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 Hettinger82df9252013-07-07 01:43:42 -1000519 CHECK_NOT_END(prevblock);
520 MARK_END(prevblock->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700521 rightblock = prevblock;
522 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 Hettinger21777ac2013-02-02 09:56:08 -0800541
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700542 {
543 PyObject **src, **dest;
544 Py_ssize_t m = -n;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800545
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700546 if (m > BLOCKLEN - leftindex)
547 m = BLOCKLEN - leftindex;
548 if (m > BLOCKLEN - 1 - rightindex)
549 m = BLOCKLEN - 1 - rightindex;
550 assert (m > 0 && m <= len);
551 src = &leftblock->data[leftindex];
552 dest = &rightblock->data[rightindex + 1];
553 leftindex += m;
554 rightindex += m;
555 n += m;
Raymond Hettinger840533b2013-07-13 17:03:58 -0700556 do {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700557 *(dest++) = *(src++);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700558 } while (--m);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700559 }
560
561 if (leftindex == BLOCKLEN) {
562 block *nextblock = leftblock->rightlink;
563 assert(leftblock != rightblock);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700564 assert(b == NULL);
Raymond Hettinger3959af92013-07-13 02:34:08 -0700565 b = leftblock;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000566 CHECK_NOT_END(nextblock);
567 MARK_END(nextblock->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700568 leftblock = nextblock;
569 leftindex = 0;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800570 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000571 }
Raymond Hettinger3959af92013-07-13 02:34:08 -0700572 rv = 0;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700573done:
Raymond Hettinger3959af92013-07-13 02:34:08 -0700574 if (b != NULL)
575 freeblock(b);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700576 deque->leftblock = leftblock;
577 deque->rightblock = rightblock;
578 deque->leftindex = leftindex;
579 deque->rightindex = rightindex;
580
581 return rv;
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000582}
583
584static PyObject *
585deque_rotate(dequeobject *deque, PyObject *args)
586{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000587 Py_ssize_t n=1;
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 if (!PyArg_ParseTuple(args, "|n:rotate", &n))
590 return NULL;
591 if (_deque_rotate(deque, n) == 0)
592 Py_RETURN_NONE;
593 return NULL;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000594}
595
Tim Peters1065f752004-10-01 01:03:29 +0000596PyDoc_STRVAR(rotate_doc,
Raymond Hettingeree33b272004-02-08 04:05:26 +0000597"Rotate the deque n steps to the right (default n=1). If n is negative, rotates left.");
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000598
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000599static PyObject *
600deque_reverse(dequeobject *deque, PyObject *unused)
601{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000602 block *leftblock = deque->leftblock;
603 block *rightblock = deque->rightblock;
604 Py_ssize_t leftindex = deque->leftindex;
605 Py_ssize_t rightindex = deque->rightindex;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000606 Py_ssize_t n = (Py_SIZE(deque))/2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607 Py_ssize_t i;
608 PyObject *tmp;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610 for (i=0 ; i<n ; i++) {
611 /* Validate that pointers haven't met in the middle */
612 assert(leftblock != rightblock || leftindex < rightindex);
Raymond Hettinger82df9252013-07-07 01:43:42 -1000613 CHECK_NOT_END(leftblock);
614 CHECK_NOT_END(rightblock);
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000615
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000616 /* Swap */
617 tmp = leftblock->data[leftindex];
618 leftblock->data[leftindex] = rightblock->data[rightindex];
619 rightblock->data[rightindex] = tmp;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621 /* Advance left block/index pair */
622 leftindex++;
623 if (leftindex == BLOCKLEN) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000624 leftblock = leftblock->rightlink;
625 leftindex = 0;
626 }
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000628 /* Step backwards with the right block/index pair */
629 rightindex--;
630 if (rightindex == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000631 rightblock = rightblock->leftlink;
632 rightindex = BLOCKLEN - 1;
633 }
634 }
635 Py_RETURN_NONE;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000636}
637
638PyDoc_STRVAR(reverse_doc,
639"D.reverse() -- reverse *IN PLACE*");
640
Raymond Hettinger44459de2010-04-03 23:20:46 +0000641static PyObject *
642deque_count(dequeobject *deque, PyObject *v)
643{
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000644 block *b = deque->leftblock;
645 Py_ssize_t index = deque->leftindex;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000646 Py_ssize_t n = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 Py_ssize_t i;
648 Py_ssize_t count = 0;
649 PyObject *item;
650 long start_state = deque->state;
651 int cmp;
Raymond Hettinger44459de2010-04-03 23:20:46 +0000652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000653 for (i=0 ; i<n ; i++) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000654 CHECK_NOT_END(b);
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000655 item = b->data[index];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000656 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
657 if (cmp > 0)
658 count++;
659 else if (cmp < 0)
660 return NULL;
Raymond Hettinger44459de2010-04-03 23:20:46 +0000661
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000662 if (start_state != deque->state) {
663 PyErr_SetString(PyExc_RuntimeError,
664 "deque mutated during iteration");
665 return NULL;
666 }
Raymond Hettinger44459de2010-04-03 23:20:46 +0000667
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 /* Advance left block/index pair */
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000669 index++;
670 if (index == BLOCKLEN) {
671 b = b->rightlink;
672 index = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000673 }
674 }
675 return PyLong_FromSsize_t(count);
Raymond Hettinger44459de2010-04-03 23:20:46 +0000676}
677
678PyDoc_STRVAR(count_doc,
679"D.count(value) -> integer -- return number of occurrences of value");
680
Martin v. Löwis18e16552006-02-15 17:27:45 +0000681static Py_ssize_t
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000682deque_len(dequeobject *deque)
683{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000684 return Py_SIZE(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000685}
686
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000687static PyObject *
688deque_remove(dequeobject *deque, PyObject *value)
689{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000690 Py_ssize_t i, n=Py_SIZE(deque);
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000691
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000692 for (i=0 ; i<n ; i++) {
693 PyObject *item = deque->leftblock->data[deque->leftindex];
694 int cmp = PyObject_RichCompareBool(item, value, Py_EQ);
Raymond Hettingerd73202c2005-03-19 00:00:51 +0000695
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000696 if (Py_SIZE(deque) != n) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000697 PyErr_SetString(PyExc_IndexError,
698 "deque mutated during remove().");
699 return NULL;
700 }
701 if (cmp > 0) {
702 PyObject *tgt = deque_popleft(deque, NULL);
703 assert (tgt != NULL);
704 Py_DECREF(tgt);
705 if (_deque_rotate(deque, i) == -1)
706 return NULL;
707 Py_RETURN_NONE;
708 }
709 else if (cmp < 0) {
710 _deque_rotate(deque, i);
711 return NULL;
712 }
713 _deque_rotate(deque, -1);
714 }
715 PyErr_SetString(PyExc_ValueError, "deque.remove(x): x not in deque");
716 return NULL;
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000717}
718
719PyDoc_STRVAR(remove_doc,
720"D.remove(value) -- remove first occurrence of value.");
721
Benjamin Peterson0e5c48a2013-01-12 21:22:18 -0500722static void
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000723deque_clear(dequeobject *deque)
724{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000725 PyObject *item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000726
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000727 while (Py_SIZE(deque)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000728 item = deque_pop(deque, NULL);
729 assert (item != NULL);
730 Py_DECREF(item);
731 }
732 assert(deque->leftblock == deque->rightblock &&
733 deque->leftindex - 1 == deque->rightindex &&
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000734 Py_SIZE(deque) == 0);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000735}
736
737static PyObject *
Benjamin Petersond6313712008-07-31 16:23:04 +0000738deque_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000739{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000740 block *b;
741 PyObject *item;
742 Py_ssize_t n, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000743
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000744 if (i < 0 || i >= Py_SIZE(deque)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000745 PyErr_SetString(PyExc_IndexError,
746 "deque index out of range");
747 return NULL;
748 }
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000749
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000750 if (i == 0) {
751 i = deque->leftindex;
752 b = deque->leftblock;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000753 } else if (i == Py_SIZE(deque) - 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000754 i = deque->rightindex;
755 b = deque->rightblock;
756 } else {
757 i += deque->leftindex;
758 n = i / BLOCKLEN;
759 i %= BLOCKLEN;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000760 if (index < (Py_SIZE(deque) >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000761 b = deque->leftblock;
762 while (n--)
763 b = b->rightlink;
764 } else {
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000765 n = (deque->leftindex + Py_SIZE(deque) - 1) / BLOCKLEN - n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000766 b = deque->rightblock;
767 while (n--)
768 b = b->leftlink;
769 }
770 }
771 item = b->data[i];
772 Py_INCREF(item);
773 return item;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000774}
775
Raymond Hettinger616f4f62004-06-26 04:42:06 +0000776/* delitem() implemented in terms of rotate for simplicity and reasonable
777 performance near the end points. If for some reason this method becomes
Tim Peters1065f752004-10-01 01:03:29 +0000778 popular, it is not hard to re-implement this using direct data movement
Raymond Hettinger616f4f62004-06-26 04:42:06 +0000779 (similar to code in list slice assignment) and achieve a two or threefold
780 performance boost.
781*/
782
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000783static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000784deque_del_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000785{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000786 PyObject *item;
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000787
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000788 assert (i >= 0 && i < Py_SIZE(deque));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 if (_deque_rotate(deque, -i) == -1)
790 return -1;
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000792 item = deque_popleft(deque, NULL);
793 assert (item != NULL);
794 Py_DECREF(item);
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 return _deque_rotate(deque, i);
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000797}
798
799static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000800deque_ass_item(dequeobject *deque, Py_ssize_t i, PyObject *v)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000801{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000802 PyObject *old_value;
803 block *b;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000804 Py_ssize_t n, len=Py_SIZE(deque), halflen=(len+1)>>1, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000805
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000806 if (i < 0 || i >= len) {
807 PyErr_SetString(PyExc_IndexError,
808 "deque index out of range");
809 return -1;
810 }
811 if (v == NULL)
812 return deque_del_item(deque, i);
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000813
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000814 i += deque->leftindex;
815 n = i / BLOCKLEN;
816 i %= BLOCKLEN;
817 if (index <= halflen) {
818 b = deque->leftblock;
819 while (n--)
820 b = b->rightlink;
821 } else {
822 n = (deque->leftindex + len - 1) / BLOCKLEN - n;
823 b = deque->rightblock;
824 while (n--)
825 b = b->leftlink;
826 }
827 Py_INCREF(v);
828 old_value = b->data[i];
829 b->data[i] = v;
830 Py_DECREF(old_value);
831 return 0;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000832}
833
834static PyObject *
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000835deque_clearmethod(dequeobject *deque)
836{
Benjamin Peterson0e5c48a2013-01-12 21:22:18 -0500837 deque_clear(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 Py_RETURN_NONE;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000839}
840
841PyDoc_STRVAR(clear_doc, "Remove all elements from the deque.");
842
843static void
844deque_dealloc(dequeobject *deque)
845{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000846 PyObject_GC_UnTrack(deque);
847 if (deque->weakreflist != NULL)
848 PyObject_ClearWeakRefs((PyObject *) deque);
849 if (deque->leftblock != NULL) {
850 deque_clear(deque);
851 assert(deque->leftblock != NULL);
852 freeblock(deque->leftblock);
853 }
854 deque->leftblock = NULL;
855 deque->rightblock = NULL;
856 Py_TYPE(deque)->tp_free(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000857}
858
859static int
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000860deque_traverse(dequeobject *deque, visitproc visit, void *arg)
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000861{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 block *b;
863 PyObject *item;
864 Py_ssize_t index;
865 Py_ssize_t indexlo = deque->leftindex;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000866
Raymond Hettinger5bfa8672013-07-06 11:58:09 -1000867 for (b = deque->leftblock; b != deque->rightblock; b = b->rightlink) {
868 for (index = indexlo; index < BLOCKLEN ; index++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000869 item = b->data[index];
870 Py_VISIT(item);
871 }
872 indexlo = 0;
873 }
Raymond Hettinger5bfa8672013-07-06 11:58:09 -1000874 for (index = indexlo; index <= deque->rightindex; index++) {
875 item = b->data[index];
876 Py_VISIT(item);
877 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000878 return 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000879}
880
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000881static PyObject *
882deque_copy(PyObject *deque)
883{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000884 if (((dequeobject *)deque)->maxlen == -1)
885 return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "O", deque, NULL);
886 else
887 return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "Oi",
888 deque, ((dequeobject *)deque)->maxlen, NULL);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000889}
890
891PyDoc_STRVAR(copy_doc, "Return a shallow copy of a deque.");
892
893static PyObject *
894deque_reduce(dequeobject *deque)
895{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 PyObject *dict, *result, *aslist;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200897 _Py_IDENTIFIER(__dict__);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000898
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200899 dict = _PyObject_GetAttrId((PyObject *)deque, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000900 if (dict == NULL)
901 PyErr_Clear();
902 aslist = PySequence_List((PyObject *)deque);
903 if (aslist == NULL) {
904 Py_XDECREF(dict);
905 return NULL;
906 }
907 if (dict == NULL) {
908 if (deque->maxlen == -1)
909 result = Py_BuildValue("O(O)", Py_TYPE(deque), aslist);
910 else
911 result = Py_BuildValue("O(On)", Py_TYPE(deque), aslist, deque->maxlen);
912 } else {
913 if (deque->maxlen == -1)
914 result = Py_BuildValue("O(OO)O", Py_TYPE(deque), aslist, Py_None, dict);
915 else
916 result = Py_BuildValue("O(On)O", Py_TYPE(deque), aslist, deque->maxlen, dict);
917 }
918 Py_XDECREF(dict);
919 Py_DECREF(aslist);
920 return result;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000921}
922
923PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
924
925static PyObject *
926deque_repr(PyObject *deque)
927{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 PyObject *aslist, *result;
929 int i;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 i = Py_ReprEnter(deque);
932 if (i != 0) {
933 if (i < 0)
934 return NULL;
935 return PyUnicode_FromString("[...]");
936 }
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 aslist = PySequence_List(deque);
939 if (aslist == NULL) {
940 Py_ReprLeave(deque);
941 return NULL;
942 }
943 if (((dequeobject *)deque)->maxlen != -1)
Benjamin Petersona786b022008-08-25 21:05:21 +0000944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000945 result = PyUnicode_FromFormat("deque(%R, maxlen=%zd)",
946 aslist, ((dequeobject *)deque)->maxlen);
947 else
948 result = PyUnicode_FromFormat("deque(%R)", aslist);
949 Py_DECREF(aslist);
950 Py_ReprLeave(deque);
951 return result;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000952}
953
Raymond Hettinger738ec902004-02-29 02:15:56 +0000954static PyObject *
955deque_richcompare(PyObject *v, PyObject *w, int op)
956{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000957 PyObject *it1=NULL, *it2=NULL, *x, *y;
958 Py_ssize_t vs, ws;
959 int b, cmp=-1;
Raymond Hettinger738ec902004-02-29 02:15:56 +0000960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000961 if (!PyObject_TypeCheck(v, &deque_type) ||
962 !PyObject_TypeCheck(w, &deque_type)) {
Brian Curtindfc80e32011-08-10 20:28:54 -0500963 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000964 }
Raymond Hettinger738ec902004-02-29 02:15:56 +0000965
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 /* Shortcuts */
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000967 vs = Py_SIZE((dequeobject *)v);
968 ws = Py_SIZE((dequeobject *)w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 if (op == Py_EQ) {
970 if (v == w)
971 Py_RETURN_TRUE;
972 if (vs != ws)
973 Py_RETURN_FALSE;
974 }
975 if (op == Py_NE) {
976 if (v == w)
977 Py_RETURN_FALSE;
978 if (vs != ws)
979 Py_RETURN_TRUE;
980 }
Raymond Hettinger738ec902004-02-29 02:15:56 +0000981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 /* Search for the first index where items are different */
983 it1 = PyObject_GetIter(v);
984 if (it1 == NULL)
985 goto done;
986 it2 = PyObject_GetIter(w);
987 if (it2 == NULL)
988 goto done;
989 for (;;) {
990 x = PyIter_Next(it1);
991 if (x == NULL && PyErr_Occurred())
992 goto done;
993 y = PyIter_Next(it2);
994 if (x == NULL || y == NULL)
995 break;
996 b = PyObject_RichCompareBool(x, y, Py_EQ);
997 if (b == 0) {
998 cmp = PyObject_RichCompareBool(x, y, op);
999 Py_DECREF(x);
1000 Py_DECREF(y);
1001 goto done;
1002 }
1003 Py_DECREF(x);
1004 Py_DECREF(y);
1005 if (b == -1)
1006 goto done;
1007 }
1008 /* We reached the end of one deque or both */
1009 Py_XDECREF(x);
1010 Py_XDECREF(y);
1011 if (PyErr_Occurred())
1012 goto done;
1013 switch (op) {
1014 case Py_LT: cmp = y != NULL; break; /* if w was longer */
1015 case Py_LE: cmp = x == NULL; break; /* if v was not longer */
1016 case Py_EQ: cmp = x == y; break; /* if we reached the end of both */
1017 case Py_NE: cmp = x != y; break; /* if one deque continues */
1018 case Py_GT: cmp = x != NULL; break; /* if v was longer */
1019 case Py_GE: cmp = y == NULL; break; /* if w was not longer */
1020 }
Tim Peters1065f752004-10-01 01:03:29 +00001021
Raymond Hettinger738ec902004-02-29 02:15:56 +00001022done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001023 Py_XDECREF(it1);
1024 Py_XDECREF(it2);
1025 if (cmp == 1)
1026 Py_RETURN_TRUE;
1027 if (cmp == 0)
1028 Py_RETURN_FALSE;
1029 return NULL;
Raymond Hettinger738ec902004-02-29 02:15:56 +00001030}
1031
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001032static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001033deque_init(dequeobject *deque, PyObject *args, PyObject *kwdargs)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001034{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001035 PyObject *iterable = NULL;
1036 PyObject *maxlenobj = NULL;
1037 Py_ssize_t maxlen = -1;
1038 char *kwlist[] = {"iterable", "maxlen", 0};
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 if (!PyArg_ParseTupleAndKeywords(args, kwdargs, "|OO:deque", kwlist, &iterable, &maxlenobj))
1041 return -1;
1042 if (maxlenobj != NULL && maxlenobj != Py_None) {
1043 maxlen = PyLong_AsSsize_t(maxlenobj);
1044 if (maxlen == -1 && PyErr_Occurred())
1045 return -1;
1046 if (maxlen < 0) {
1047 PyErr_SetString(PyExc_ValueError, "maxlen must be non-negative");
1048 return -1;
1049 }
1050 }
1051 deque->maxlen = maxlen;
1052 deque_clear(deque);
1053 if (iterable != NULL) {
1054 PyObject *rv = deque_extend(deque, iterable);
1055 if (rv == NULL)
1056 return -1;
1057 Py_DECREF(rv);
1058 }
1059 return 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001060}
1061
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001062static PyObject *
Jesus Cea16e2fca2012-08-03 14:49:42 +02001063deque_sizeof(dequeobject *deque, void *unused)
1064{
1065 Py_ssize_t res;
1066 Py_ssize_t blocks;
1067
1068 res = sizeof(dequeobject);
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001069 blocks = (deque->leftindex + Py_SIZE(deque) + BLOCKLEN - 1) / BLOCKLEN;
1070 assert(deque->leftindex + Py_SIZE(deque) - 1 ==
Jesus Cea16e2fca2012-08-03 14:49:42 +02001071 (blocks - 1) * BLOCKLEN + deque->rightindex);
1072 res += blocks * sizeof(block);
1073 return PyLong_FromSsize_t(res);
1074}
1075
1076PyDoc_STRVAR(sizeof_doc,
1077"D.__sizeof__() -- size of D in memory, in bytes");
1078
1079static PyObject *
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001080deque_get_maxlen(dequeobject *deque)
1081{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 if (deque->maxlen == -1)
1083 Py_RETURN_NONE;
1084 return PyLong_FromSsize_t(deque->maxlen);
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001085}
1086
1087static PyGetSetDef deque_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001088 {"maxlen", (getter)deque_get_maxlen, (setter)NULL,
1089 "maximum size of a deque or None if unbounded"},
1090 {0}
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001091};
1092
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001093static PySequenceMethods deque_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001094 (lenfunc)deque_len, /* sq_length */
1095 0, /* sq_concat */
1096 0, /* sq_repeat */
1097 (ssizeargfunc)deque_item, /* sq_item */
1098 0, /* sq_slice */
1099 (ssizeobjargproc)deque_ass_item, /* sq_ass_item */
1100 0, /* sq_ass_slice */
1101 0, /* sq_contains */
1102 (binaryfunc)deque_inplace_concat, /* sq_inplace_concat */
1103 0, /* sq_inplace_repeat */
Raymond Hettinger3f9afd82009-12-10 03:03:02 +00001104
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001105};
1106
1107/* deque object ********************************************************/
1108
1109static PyObject *deque_iter(dequeobject *deque);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001110static PyObject *deque_reviter(dequeobject *deque);
Tim Peters1065f752004-10-01 01:03:29 +00001111PyDoc_STRVAR(reversed_doc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001112 "D.__reversed__() -- return a reverse iterator over the deque");
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001113
1114static PyMethodDef deque_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 {"append", (PyCFunction)deque_append,
1116 METH_O, append_doc},
1117 {"appendleft", (PyCFunction)deque_appendleft,
1118 METH_O, appendleft_doc},
1119 {"clear", (PyCFunction)deque_clearmethod,
1120 METH_NOARGS, clear_doc},
1121 {"__copy__", (PyCFunction)deque_copy,
1122 METH_NOARGS, copy_doc},
1123 {"count", (PyCFunction)deque_count,
1124 METH_O, count_doc},
1125 {"extend", (PyCFunction)deque_extend,
1126 METH_O, extend_doc},
1127 {"extendleft", (PyCFunction)deque_extendleft,
1128 METH_O, extendleft_doc},
1129 {"pop", (PyCFunction)deque_pop,
1130 METH_NOARGS, pop_doc},
1131 {"popleft", (PyCFunction)deque_popleft,
1132 METH_NOARGS, popleft_doc},
1133 {"__reduce__", (PyCFunction)deque_reduce,
1134 METH_NOARGS, reduce_doc},
1135 {"remove", (PyCFunction)deque_remove,
1136 METH_O, remove_doc},
1137 {"__reversed__", (PyCFunction)deque_reviter,
1138 METH_NOARGS, reversed_doc},
1139 {"reverse", (PyCFunction)deque_reverse,
1140 METH_NOARGS, reverse_doc},
1141 {"rotate", (PyCFunction)deque_rotate,
Jesus Cea16e2fca2012-08-03 14:49:42 +02001142 METH_VARARGS, rotate_doc},
1143 {"__sizeof__", (PyCFunction)deque_sizeof,
1144 METH_NOARGS, sizeof_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001145 {NULL, NULL} /* sentinel */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001146};
1147
1148PyDoc_STRVAR(deque_doc,
Andrew Svetlov6a5c7c32012-10-31 11:50:40 +02001149"deque([iterable[, maxlen]]) --> deque object\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001150\n\
Raymond Hettinger49747052011-03-29 17:36:31 -07001151Build an ordered collection with optimized access from its endpoints.");
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001152
Neal Norwitz87f10132004-02-29 15:40:53 +00001153static PyTypeObject deque_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001154 PyVarObject_HEAD_INIT(NULL, 0)
1155 "collections.deque", /* tp_name */
1156 sizeof(dequeobject), /* tp_basicsize */
1157 0, /* tp_itemsize */
1158 /* methods */
1159 (destructor)deque_dealloc, /* tp_dealloc */
1160 0, /* tp_print */
1161 0, /* tp_getattr */
1162 0, /* tp_setattr */
1163 0, /* tp_reserved */
1164 deque_repr, /* tp_repr */
1165 0, /* tp_as_number */
1166 &deque_as_sequence, /* tp_as_sequence */
1167 0, /* tp_as_mapping */
Georg Brandlf038b322010-10-18 07:35:09 +00001168 PyObject_HashNotImplemented, /* tp_hash */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001169 0, /* tp_call */
1170 0, /* tp_str */
1171 PyObject_GenericGetAttr, /* tp_getattro */
1172 0, /* tp_setattro */
1173 0, /* tp_as_buffer */
1174 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
Georg Brandlf038b322010-10-18 07:35:09 +00001175 /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001176 deque_doc, /* tp_doc */
1177 (traverseproc)deque_traverse, /* tp_traverse */
1178 (inquiry)deque_clear, /* tp_clear */
1179 (richcmpfunc)deque_richcompare, /* tp_richcompare */
Georg Brandlf038b322010-10-18 07:35:09 +00001180 offsetof(dequeobject, weakreflist), /* tp_weaklistoffset*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001181 (getiterfunc)deque_iter, /* tp_iter */
1182 0, /* tp_iternext */
1183 deque_methods, /* tp_methods */
1184 0, /* tp_members */
Georg Brandlf038b322010-10-18 07:35:09 +00001185 deque_getset, /* tp_getset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001186 0, /* tp_base */
1187 0, /* tp_dict */
1188 0, /* tp_descr_get */
1189 0, /* tp_descr_set */
1190 0, /* tp_dictoffset */
1191 (initproc)deque_init, /* tp_init */
1192 PyType_GenericAlloc, /* tp_alloc */
1193 deque_new, /* tp_new */
1194 PyObject_GC_Del, /* tp_free */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001195};
1196
1197/*********************** Deque Iterator **************************/
1198
1199typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001200 PyObject_HEAD
1201 Py_ssize_t index;
1202 block *b;
1203 dequeobject *deque;
1204 long state; /* state when the iterator is created */
1205 Py_ssize_t counter; /* number of items remaining for iteration */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001206} dequeiterobject;
1207
Martin v. Löwis59683e82008-06-13 07:50:45 +00001208static PyTypeObject dequeiter_type;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001209
1210static PyObject *
1211deque_iter(dequeobject *deque)
1212{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 dequeiterobject *it;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001214
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001215 it = PyObject_GC_New(dequeiterobject, &dequeiter_type);
1216 if (it == NULL)
1217 return NULL;
1218 it->b = deque->leftblock;
1219 it->index = deque->leftindex;
1220 Py_INCREF(deque);
1221 it->deque = deque;
1222 it->state = deque->state;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001223 it->counter = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001224 PyObject_GC_Track(it);
1225 return (PyObject *)it;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001226}
1227
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001228static int
1229dequeiter_traverse(dequeiterobject *dio, visitproc visit, void *arg)
1230{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001231 Py_VISIT(dio->deque);
1232 return 0;
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001233}
1234
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001235static void
1236dequeiter_dealloc(dequeiterobject *dio)
1237{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001238 Py_XDECREF(dio->deque);
1239 PyObject_GC_Del(dio);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001240}
1241
1242static PyObject *
1243dequeiter_next(dequeiterobject *it)
1244{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001245 PyObject *item;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001247 if (it->deque->state != it->state) {
1248 it->counter = 0;
1249 PyErr_SetString(PyExc_RuntimeError,
1250 "deque mutated during iteration");
1251 return NULL;
1252 }
1253 if (it->counter == 0)
1254 return NULL;
1255 assert (!(it->b == it->deque->rightblock &&
1256 it->index > it->deque->rightindex));
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258 item = it->b->data[it->index];
1259 it->index++;
1260 it->counter--;
1261 if (it->index == BLOCKLEN && it->counter > 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -10001262 CHECK_NOT_END(it->b->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 it->b = it->b->rightlink;
1264 it->index = 0;
1265 }
1266 Py_INCREF(item);
1267 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001268}
1269
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001270static PyObject *
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001271dequeiter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1272{
1273 Py_ssize_t i, index=0;
1274 PyObject *deque;
1275 dequeiterobject *it;
1276 if (!PyArg_ParseTuple(args, "O!|n", &deque_type, &deque, &index))
1277 return NULL;
1278 assert(type == &dequeiter_type);
1279
1280 it = (dequeiterobject*)deque_iter((dequeobject *)deque);
1281 if (!it)
1282 return NULL;
1283 /* consume items from the queue */
1284 for(i=0; i<index; i++) {
1285 PyObject *item = dequeiter_next(it);
1286 if (item) {
1287 Py_DECREF(item);
1288 } else {
1289 if (it->counter) {
1290 Py_DECREF(it);
1291 return NULL;
1292 } else
1293 break;
1294 }
1295 }
1296 return (PyObject*)it;
1297}
1298
1299static PyObject *
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001300dequeiter_len(dequeiterobject *it)
1301{
Antoine Pitrou554f3342010-08-17 18:30:06 +00001302 return PyLong_FromSsize_t(it->counter);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001303}
1304
Armin Rigof5b3e362006-02-11 21:32:43 +00001305PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001306
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001307static PyObject *
1308dequeiter_reduce(dequeiterobject *it)
1309{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001310 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 +00001311}
1312
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001313static PyMethodDef dequeiter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001314 {"__length_hint__", (PyCFunction)dequeiter_len, METH_NOARGS, length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001315 {"__reduce__", (PyCFunction)dequeiter_reduce, METH_NOARGS, reduce_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001316 {NULL, NULL} /* sentinel */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001317};
1318
Martin v. Löwis59683e82008-06-13 07:50:45 +00001319static PyTypeObject dequeiter_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001320 PyVarObject_HEAD_INIT(NULL, 0)
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001321 "_collections._deque_iterator", /* tp_name */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001322 sizeof(dequeiterobject), /* tp_basicsize */
1323 0, /* tp_itemsize */
1324 /* methods */
1325 (destructor)dequeiter_dealloc, /* tp_dealloc */
1326 0, /* tp_print */
1327 0, /* tp_getattr */
1328 0, /* tp_setattr */
1329 0, /* tp_reserved */
1330 0, /* tp_repr */
1331 0, /* tp_as_number */
1332 0, /* tp_as_sequence */
1333 0, /* tp_as_mapping */
1334 0, /* tp_hash */
1335 0, /* tp_call */
1336 0, /* tp_str */
1337 PyObject_GenericGetAttr, /* tp_getattro */
1338 0, /* tp_setattro */
1339 0, /* tp_as_buffer */
1340 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
1341 0, /* tp_doc */
1342 (traverseproc)dequeiter_traverse, /* tp_traverse */
1343 0, /* tp_clear */
1344 0, /* tp_richcompare */
1345 0, /* tp_weaklistoffset */
1346 PyObject_SelfIter, /* tp_iter */
1347 (iternextfunc)dequeiter_next, /* tp_iternext */
1348 dequeiter_methods, /* tp_methods */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001349 0, /* tp_members */
1350 0, /* tp_getset */
1351 0, /* tp_base */
1352 0, /* tp_dict */
1353 0, /* tp_descr_get */
1354 0, /* tp_descr_set */
1355 0, /* tp_dictoffset */
1356 0, /* tp_init */
1357 0, /* tp_alloc */
1358 dequeiter_new, /* tp_new */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001359 0,
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001360};
1361
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001362/*********************** Deque Reverse Iterator **************************/
1363
Martin v. Löwis59683e82008-06-13 07:50:45 +00001364static PyTypeObject dequereviter_type;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001365
1366static PyObject *
1367deque_reviter(dequeobject *deque)
1368{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001369 dequeiterobject *it;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001371 it = PyObject_GC_New(dequeiterobject, &dequereviter_type);
1372 if (it == NULL)
1373 return NULL;
1374 it->b = deque->rightblock;
1375 it->index = deque->rightindex;
1376 Py_INCREF(deque);
1377 it->deque = deque;
1378 it->state = deque->state;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001379 it->counter = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001380 PyObject_GC_Track(it);
1381 return (PyObject *)it;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001382}
1383
1384static PyObject *
1385dequereviter_next(dequeiterobject *it)
1386{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001387 PyObject *item;
1388 if (it->counter == 0)
1389 return NULL;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001391 if (it->deque->state != it->state) {
1392 it->counter = 0;
1393 PyErr_SetString(PyExc_RuntimeError,
1394 "deque mutated during iteration");
1395 return NULL;
1396 }
1397 assert (!(it->b == it->deque->leftblock &&
1398 it->index < it->deque->leftindex));
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001400 item = it->b->data[it->index];
1401 it->index--;
1402 it->counter--;
1403 if (it->index == -1 && it->counter > 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -10001404 CHECK_NOT_END(it->b->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001405 it->b = it->b->leftlink;
1406 it->index = BLOCKLEN - 1;
1407 }
1408 Py_INCREF(item);
1409 return item;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001410}
1411
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001412static PyObject *
1413dequereviter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1414{
1415 Py_ssize_t i, index=0;
1416 PyObject *deque;
1417 dequeiterobject *it;
1418 if (!PyArg_ParseTuple(args, "O!|n", &deque_type, &deque, &index))
1419 return NULL;
1420 assert(type == &dequereviter_type);
1421
1422 it = (dequeiterobject*)deque_reviter((dequeobject *)deque);
1423 if (!it)
1424 return NULL;
1425 /* consume items from the queue */
1426 for(i=0; i<index; i++) {
1427 PyObject *item = dequereviter_next(it);
1428 if (item) {
1429 Py_DECREF(item);
1430 } else {
1431 if (it->counter) {
1432 Py_DECREF(it);
1433 return NULL;
1434 } else
1435 break;
1436 }
1437 }
1438 return (PyObject*)it;
1439}
1440
Martin v. Löwis59683e82008-06-13 07:50:45 +00001441static PyTypeObject dequereviter_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001442 PyVarObject_HEAD_INIT(NULL, 0)
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001443 "_collections._deque_reverse_iterator", /* tp_name */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001444 sizeof(dequeiterobject), /* tp_basicsize */
1445 0, /* tp_itemsize */
1446 /* methods */
1447 (destructor)dequeiter_dealloc, /* tp_dealloc */
1448 0, /* tp_print */
1449 0, /* tp_getattr */
1450 0, /* tp_setattr */
1451 0, /* tp_reserved */
1452 0, /* tp_repr */
1453 0, /* tp_as_number */
1454 0, /* tp_as_sequence */
1455 0, /* tp_as_mapping */
1456 0, /* tp_hash */
1457 0, /* tp_call */
1458 0, /* tp_str */
1459 PyObject_GenericGetAttr, /* tp_getattro */
1460 0, /* tp_setattro */
1461 0, /* tp_as_buffer */
1462 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
1463 0, /* tp_doc */
1464 (traverseproc)dequeiter_traverse, /* tp_traverse */
1465 0, /* tp_clear */
1466 0, /* tp_richcompare */
1467 0, /* tp_weaklistoffset */
1468 PyObject_SelfIter, /* tp_iter */
1469 (iternextfunc)dequereviter_next, /* tp_iternext */
1470 dequeiter_methods, /* tp_methods */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001471 0, /* tp_members */
1472 0, /* tp_getset */
1473 0, /* tp_base */
1474 0, /* tp_dict */
1475 0, /* tp_descr_get */
1476 0, /* tp_descr_set */
1477 0, /* tp_dictoffset */
1478 0, /* tp_init */
1479 0, /* tp_alloc */
1480 dequereviter_new, /* tp_new */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001481 0,
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001482};
1483
Guido van Rossum1968ad32006-02-25 22:38:04 +00001484/* defaultdict type *********************************************************/
1485
1486typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001487 PyDictObject dict;
1488 PyObject *default_factory;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001489} defdictobject;
1490
1491static PyTypeObject defdict_type; /* Forward */
1492
1493PyDoc_STRVAR(defdict_missing_doc,
1494"__missing__(key) # Called by __getitem__ for missing key; pseudo-code:\n\
Guido van Rossumd8faa362007-04-27 19:54:29 +00001495 if self.default_factory is None: raise KeyError((key,))\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00001496 self[key] = value = self.default_factory()\n\
1497 return value\n\
1498");
1499
1500static PyObject *
1501defdict_missing(defdictobject *dd, PyObject *key)
1502{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001503 PyObject *factory = dd->default_factory;
1504 PyObject *value;
1505 if (factory == NULL || factory == Py_None) {
1506 /* XXX Call dict.__missing__(key) */
1507 PyObject *tup;
1508 tup = PyTuple_Pack(1, key);
1509 if (!tup) return NULL;
1510 PyErr_SetObject(PyExc_KeyError, tup);
1511 Py_DECREF(tup);
1512 return NULL;
1513 }
1514 value = PyEval_CallObject(factory, NULL);
1515 if (value == NULL)
1516 return value;
1517 if (PyObject_SetItem((PyObject *)dd, key, value) < 0) {
1518 Py_DECREF(value);
1519 return NULL;
1520 }
1521 return value;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001522}
1523
1524PyDoc_STRVAR(defdict_copy_doc, "D.copy() -> a shallow copy of D.");
1525
1526static PyObject *
1527defdict_copy(defdictobject *dd)
1528{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001529 /* This calls the object's class. That only works for subclasses
1530 whose class constructor has the same signature. Subclasses that
1531 define a different constructor signature must override copy().
1532 */
Raymond Hettinger54628fa2009-08-04 19:16:39 +00001533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001534 if (dd->default_factory == NULL)
1535 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd), Py_None, dd, NULL);
1536 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd),
1537 dd->default_factory, dd, NULL);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001538}
1539
1540static PyObject *
1541defdict_reduce(defdictobject *dd)
1542{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001543 /* __reduce__ must return a 5-tuple as follows:
Guido van Rossum1968ad32006-02-25 22:38:04 +00001544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001545 - factory function
1546 - tuple of args for the factory function
1547 - additional state (here None)
1548 - sequence iterator (here None)
1549 - dictionary iterator (yielding successive (key, value) pairs
Guido van Rossum1968ad32006-02-25 22:38:04 +00001550
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001551 This API is used by pickle.py and copy.py.
Guido van Rossum1968ad32006-02-25 22:38:04 +00001552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001553 For this to be useful with pickle.py, the default_factory
1554 must be picklable; e.g., None, a built-in, or a global
1555 function in a module or package.
Guido van Rossum1968ad32006-02-25 22:38:04 +00001556
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001557 Both shallow and deep copying are supported, but for deep
1558 copying, the default_factory must be deep-copyable; e.g. None,
1559 or a built-in (functions are not copyable at this time).
Guido van Rossum1968ad32006-02-25 22:38:04 +00001560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001561 This only works for subclasses as long as their constructor
1562 signature is compatible; the first argument must be the
1563 optional default_factory, defaulting to None.
1564 */
1565 PyObject *args;
1566 PyObject *items;
1567 PyObject *iter;
1568 PyObject *result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001569 _Py_IDENTIFIER(items);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001571 if (dd->default_factory == NULL || dd->default_factory == Py_None)
1572 args = PyTuple_New(0);
1573 else
1574 args = PyTuple_Pack(1, dd->default_factory);
1575 if (args == NULL)
1576 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001577 items = _PyObject_CallMethodId((PyObject *)dd, &PyId_items, "()");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001578 if (items == NULL) {
1579 Py_DECREF(args);
1580 return NULL;
1581 }
1582 iter = PyObject_GetIter(items);
1583 if (iter == NULL) {
1584 Py_DECREF(items);
1585 Py_DECREF(args);
1586 return NULL;
1587 }
1588 result = PyTuple_Pack(5, Py_TYPE(dd), args,
1589 Py_None, Py_None, iter);
1590 Py_DECREF(iter);
1591 Py_DECREF(items);
1592 Py_DECREF(args);
1593 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001594}
1595
1596static PyMethodDef defdict_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001597 {"__missing__", (PyCFunction)defdict_missing, METH_O,
1598 defdict_missing_doc},
1599 {"copy", (PyCFunction)defdict_copy, METH_NOARGS,
1600 defdict_copy_doc},
1601 {"__copy__", (PyCFunction)defdict_copy, METH_NOARGS,
1602 defdict_copy_doc},
1603 {"__reduce__", (PyCFunction)defdict_reduce, METH_NOARGS,
1604 reduce_doc},
1605 {NULL}
Guido van Rossum1968ad32006-02-25 22:38:04 +00001606};
1607
1608static PyMemberDef defdict_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001609 {"default_factory", T_OBJECT,
1610 offsetof(defdictobject, default_factory), 0,
1611 PyDoc_STR("Factory for default value called by __missing__().")},
1612 {NULL}
Guido van Rossum1968ad32006-02-25 22:38:04 +00001613};
1614
1615static void
1616defdict_dealloc(defdictobject *dd)
1617{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001618 Py_CLEAR(dd->default_factory);
1619 PyDict_Type.tp_dealloc((PyObject *)dd);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001620}
1621
Guido van Rossum1968ad32006-02-25 22:38:04 +00001622static PyObject *
1623defdict_repr(defdictobject *dd)
1624{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001625 PyObject *baserepr;
1626 PyObject *defrepr;
1627 PyObject *result;
1628 baserepr = PyDict_Type.tp_repr((PyObject *)dd);
1629 if (baserepr == NULL)
1630 return NULL;
1631 if (dd->default_factory == NULL)
1632 defrepr = PyUnicode_FromString("None");
1633 else
1634 {
1635 int status = Py_ReprEnter(dd->default_factory);
1636 if (status != 0) {
Antoine Pitrouf5f1fe02012-02-15 02:42:46 +01001637 if (status < 0) {
1638 Py_DECREF(baserepr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001639 return NULL;
Antoine Pitrouf5f1fe02012-02-15 02:42:46 +01001640 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001641 defrepr = PyUnicode_FromString("...");
1642 }
1643 else
1644 defrepr = PyObject_Repr(dd->default_factory);
1645 Py_ReprLeave(dd->default_factory);
1646 }
1647 if (defrepr == NULL) {
1648 Py_DECREF(baserepr);
1649 return NULL;
1650 }
1651 result = PyUnicode_FromFormat("defaultdict(%U, %U)",
1652 defrepr, baserepr);
1653 Py_DECREF(defrepr);
1654 Py_DECREF(baserepr);
1655 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001656}
1657
1658static int
1659defdict_traverse(PyObject *self, visitproc visit, void *arg)
1660{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001661 Py_VISIT(((defdictobject *)self)->default_factory);
1662 return PyDict_Type.tp_traverse(self, visit, arg);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001663}
1664
1665static int
1666defdict_tp_clear(defdictobject *dd)
1667{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001668 Py_CLEAR(dd->default_factory);
1669 return PyDict_Type.tp_clear((PyObject *)dd);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001670}
1671
1672static int
1673defdict_init(PyObject *self, PyObject *args, PyObject *kwds)
1674{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001675 defdictobject *dd = (defdictobject *)self;
1676 PyObject *olddefault = dd->default_factory;
1677 PyObject *newdefault = NULL;
1678 PyObject *newargs;
1679 int result;
1680 if (args == NULL || !PyTuple_Check(args))
1681 newargs = PyTuple_New(0);
1682 else {
1683 Py_ssize_t n = PyTuple_GET_SIZE(args);
1684 if (n > 0) {
1685 newdefault = PyTuple_GET_ITEM(args, 0);
1686 if (!PyCallable_Check(newdefault) && newdefault != Py_None) {
1687 PyErr_SetString(PyExc_TypeError,
1688 "first argument must be callable");
1689 return -1;
1690 }
1691 }
1692 newargs = PySequence_GetSlice(args, 1, n);
1693 }
1694 if (newargs == NULL)
1695 return -1;
1696 Py_XINCREF(newdefault);
1697 dd->default_factory = newdefault;
1698 result = PyDict_Type.tp_init(self, newargs, kwds);
1699 Py_DECREF(newargs);
1700 Py_XDECREF(olddefault);
1701 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001702}
1703
1704PyDoc_STRVAR(defdict_doc,
1705"defaultdict(default_factory) --> dict with default factory\n\
1706\n\
1707The default factory is called without arguments to produce\n\
1708a new value when a key is not present, in __getitem__ only.\n\
1709A defaultdict compares equal to a dict with the same items.\n\
1710");
1711
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001712/* See comment in xxsubtype.c */
1713#define DEFERRED_ADDRESS(ADDR) 0
1714
Guido van Rossum1968ad32006-02-25 22:38:04 +00001715static PyTypeObject defdict_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001716 PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0)
1717 "collections.defaultdict", /* tp_name */
1718 sizeof(defdictobject), /* tp_basicsize */
1719 0, /* tp_itemsize */
1720 /* methods */
1721 (destructor)defdict_dealloc, /* tp_dealloc */
1722 0, /* tp_print */
1723 0, /* tp_getattr */
1724 0, /* tp_setattr */
1725 0, /* tp_reserved */
1726 (reprfunc)defdict_repr, /* tp_repr */
1727 0, /* tp_as_number */
1728 0, /* tp_as_sequence */
1729 0, /* tp_as_mapping */
1730 0, /* tp_hash */
1731 0, /* tp_call */
1732 0, /* tp_str */
1733 PyObject_GenericGetAttr, /* tp_getattro */
1734 0, /* tp_setattro */
1735 0, /* tp_as_buffer */
1736 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
1737 /* tp_flags */
1738 defdict_doc, /* tp_doc */
1739 defdict_traverse, /* tp_traverse */
1740 (inquiry)defdict_tp_clear, /* tp_clear */
1741 0, /* tp_richcompare */
1742 0, /* tp_weaklistoffset*/
1743 0, /* tp_iter */
1744 0, /* tp_iternext */
1745 defdict_methods, /* tp_methods */
1746 defdict_members, /* tp_members */
1747 0, /* tp_getset */
1748 DEFERRED_ADDRESS(&PyDict_Type), /* tp_base */
1749 0, /* tp_dict */
1750 0, /* tp_descr_get */
1751 0, /* tp_descr_set */
1752 0, /* tp_dictoffset */
1753 defdict_init, /* tp_init */
1754 PyType_GenericAlloc, /* tp_alloc */
1755 0, /* tp_new */
1756 PyObject_GC_Del, /* tp_free */
Guido van Rossum1968ad32006-02-25 22:38:04 +00001757};
1758
Raymond Hettinger96f34102010-12-15 16:30:37 +00001759/* helper function for Counter *********************************************/
1760
1761PyDoc_STRVAR(_count_elements_doc,
1762"_count_elements(mapping, iterable) -> None\n\
1763\n\
1764Count elements in the iterable, updating the mappping");
1765
1766static PyObject *
1767_count_elements(PyObject *self, PyObject *args)
1768{
1769 PyObject *it, *iterable, *mapping, *oldval;
1770 PyObject *newval = NULL;
1771 PyObject *key = NULL;
1772 PyObject *one = NULL;
1773
1774 if (!PyArg_UnpackTuple(args, "_count_elements", 2, 2, &mapping, &iterable))
1775 return NULL;
1776
Raymond Hettinger96f34102010-12-15 16:30:37 +00001777 it = PyObject_GetIter(iterable);
1778 if (it == NULL)
1779 return NULL;
Raymond Hettinger426e0522011-01-03 02:12:02 +00001780
Raymond Hettinger96f34102010-12-15 16:30:37 +00001781 one = PyLong_FromLong(1);
1782 if (one == NULL) {
1783 Py_DECREF(it);
1784 return NULL;
1785 }
Raymond Hettinger426e0522011-01-03 02:12:02 +00001786
1787 if (PyDict_CheckExact(mapping)) {
1788 while (1) {
1789 key = PyIter_Next(it);
Victor Stinnera154b5c2011-04-20 23:23:52 +02001790 if (key == NULL)
1791 break;
Raymond Hettinger426e0522011-01-03 02:12:02 +00001792 oldval = PyDict_GetItem(mapping, key);
1793 if (oldval == NULL) {
1794 if (PyDict_SetItem(mapping, key, one) == -1)
1795 break;
1796 } else {
1797 newval = PyNumber_Add(oldval, one);
1798 if (newval == NULL)
1799 break;
1800 if (PyDict_SetItem(mapping, key, newval) == -1)
1801 break;
1802 Py_CLEAR(newval);
1803 }
1804 Py_DECREF(key);
Raymond Hettinger96f34102010-12-15 16:30:37 +00001805 }
Raymond Hettinger426e0522011-01-03 02:12:02 +00001806 } else {
1807 while (1) {
1808 key = PyIter_Next(it);
Victor Stinnera154b5c2011-04-20 23:23:52 +02001809 if (key == NULL)
1810 break;
Raymond Hettinger426e0522011-01-03 02:12:02 +00001811 oldval = PyObject_GetItem(mapping, key);
1812 if (oldval == NULL) {
1813 if (!PyErr_Occurred() || !PyErr_ExceptionMatches(PyExc_KeyError))
1814 break;
1815 PyErr_Clear();
1816 Py_INCREF(one);
1817 newval = one;
1818 } else {
1819 newval = PyNumber_Add(oldval, one);
1820 Py_DECREF(oldval);
1821 if (newval == NULL)
1822 break;
1823 }
1824 if (PyObject_SetItem(mapping, key, newval) == -1)
Raymond Hettinger96f34102010-12-15 16:30:37 +00001825 break;
1826 Py_CLEAR(newval);
Raymond Hettinger426e0522011-01-03 02:12:02 +00001827 Py_DECREF(key);
Raymond Hettinger96f34102010-12-15 16:30:37 +00001828 }
Raymond Hettinger96f34102010-12-15 16:30:37 +00001829 }
Raymond Hettinger426e0522011-01-03 02:12:02 +00001830
Raymond Hettinger96f34102010-12-15 16:30:37 +00001831 Py_DECREF(it);
1832 Py_XDECREF(key);
1833 Py_XDECREF(newval);
1834 Py_DECREF(one);
1835 if (PyErr_Occurred())
1836 return NULL;
1837 Py_RETURN_NONE;
1838}
1839
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001840/* module level code ********************************************************/
1841
1842PyDoc_STRVAR(module_doc,
Guido van Rossum1968ad32006-02-25 22:38:04 +00001843"High performance data structures.\n\
1844- deque: ordered collection accessible from endpoints only\n\
1845- defaultdict: dict subclass with a default value factory\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001846");
1847
Raymond Hettinger96f34102010-12-15 16:30:37 +00001848static struct PyMethodDef module_functions[] = {
1849 {"_count_elements", _count_elements, METH_VARARGS, _count_elements_doc},
1850 {NULL, NULL} /* sentinel */
1851};
Martin v. Löwis1a214512008-06-11 05:26:20 +00001852
1853static struct PyModuleDef _collectionsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001854 PyModuleDef_HEAD_INIT,
1855 "_collections",
1856 module_doc,
1857 -1,
Raymond Hettinger96f34102010-12-15 16:30:37 +00001858 module_functions,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001859 NULL,
1860 NULL,
1861 NULL,
1862 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001863};
1864
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001865PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001866PyInit__collections(void)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001867{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001868 PyObject *m;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001870 m = PyModule_Create(&_collectionsmodule);
1871 if (m == NULL)
1872 return NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001874 if (PyType_Ready(&deque_type) < 0)
1875 return NULL;
1876 Py_INCREF(&deque_type);
1877 PyModule_AddObject(m, "deque", (PyObject *)&deque_type);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001879 defdict_type.tp_base = &PyDict_Type;
1880 if (PyType_Ready(&defdict_type) < 0)
1881 return NULL;
1882 Py_INCREF(&defdict_type);
1883 PyModule_AddObject(m, "defaultdict", (PyObject *)&defdict_type);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001885 if (PyType_Ready(&dequeiter_type) < 0)
1886 return NULL;
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001887 Py_INCREF(&dequeiter_type);
1888 PyModule_AddObject(m, "_deque_iterator", (PyObject *)&dequeiter_type);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001890 if (PyType_Ready(&dequereviter_type) < 0)
1891 return NULL;
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001892 Py_INCREF(&dequereviter_type);
1893 PyModule_AddObject(m, "_deque_reverse_iterator", (PyObject *)&dequereviter_type);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001895 return m;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001896}