blob: 3ff1d1fc7e37201466e9c39e51ba57dfd0e726b2 [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 Hettinger20b0f872013-06-23 15:44:33 -0700494 {
495 PyObject **src, **dest;
496 Py_ssize_t m = n;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800497
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700498 if (m > rightindex + 1)
499 m = rightindex + 1;
500 if (m > leftindex)
501 m = leftindex;
502 assert (m > 0 && m <= len);
503 src = &rightblock->data[rightindex];
504 dest = &leftblock->data[leftindex - 1];
505 rightindex -= m;
506 leftindex -= m;
507 n -= m;
Raymond Hettinger840533b2013-07-13 17:03:58 -0700508 do {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700509 *(dest--) = *(src--);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700510 } while (--m);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700511 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700512 if (rightindex == -1) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700513 assert(leftblock != rightblock);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700514 assert(b == NULL);
Raymond Hettinger3959af92013-07-13 02:34:08 -0700515 b = rightblock;
Raymond Hettingerb97cc492013-07-21 01:51:07 -0700516 CHECK_NOT_END(rightblock->leftlink);
517 rightblock = rightblock->leftlink;
518 MARK_END(rightblock->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700519 rightindex = BLOCKLEN - 1;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800520 }
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800521 }
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500522 while (n < 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700523 if (rightindex == BLOCKLEN - 1) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700524 if (b == NULL) {
Raymond Hettinger3959af92013-07-13 02:34:08 -0700525 b = newblock(len);
526 if (b == NULL)
527 goto done;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700528 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000529 b->leftlink = rightblock;
530 CHECK_END(rightblock->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700531 rightblock->rightlink = b;
532 rightblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000533 MARK_END(b->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700534 rightindex = -1;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700535 b = NULL;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800536 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700537 assert (rightindex < BLOCKLEN - 1);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700538 {
539 PyObject **src, **dest;
540 Py_ssize_t m = -n;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800541
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700542 if (m > BLOCKLEN - leftindex)
543 m = BLOCKLEN - leftindex;
544 if (m > BLOCKLEN - 1 - rightindex)
545 m = BLOCKLEN - 1 - rightindex;
546 assert (m > 0 && m <= len);
547 src = &leftblock->data[leftindex];
548 dest = &rightblock->data[rightindex + 1];
549 leftindex += m;
550 rightindex += m;
551 n += m;
Raymond Hettinger840533b2013-07-13 17:03:58 -0700552 do {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700553 *(dest++) = *(src++);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700554 } while (--m);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700555 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700556 if (leftindex == BLOCKLEN) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700557 assert(leftblock != rightblock);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700558 assert(b == NULL);
Raymond Hettinger3959af92013-07-13 02:34:08 -0700559 b = leftblock;
Raymond Hettingerb97cc492013-07-21 01:51:07 -0700560 CHECK_NOT_END(leftblock->rightlink);
561 leftblock = leftblock->rightlink;
562 MARK_END(leftblock->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700563 leftindex = 0;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800564 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000565 }
Raymond Hettinger3959af92013-07-13 02:34:08 -0700566 rv = 0;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700567done:
Raymond Hettinger3959af92013-07-13 02:34:08 -0700568 if (b != NULL)
569 freeblock(b);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700570 deque->leftblock = leftblock;
571 deque->rightblock = rightblock;
572 deque->leftindex = leftindex;
573 deque->rightindex = rightindex;
574
575 return rv;
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000576}
577
578static PyObject *
579deque_rotate(dequeobject *deque, PyObject *args)
580{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000581 Py_ssize_t n=1;
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000583 if (!PyArg_ParseTuple(args, "|n:rotate", &n))
584 return NULL;
585 if (_deque_rotate(deque, n) == 0)
586 Py_RETURN_NONE;
587 return NULL;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000588}
589
Tim Peters1065f752004-10-01 01:03:29 +0000590PyDoc_STRVAR(rotate_doc,
Raymond Hettingeree33b272004-02-08 04:05:26 +0000591"Rotate the deque n steps to the right (default n=1). If n is negative, rotates left.");
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000592
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000593static PyObject *
594deque_reverse(dequeobject *deque, PyObject *unused)
595{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 block *leftblock = deque->leftblock;
597 block *rightblock = deque->rightblock;
598 Py_ssize_t leftindex = deque->leftindex;
599 Py_ssize_t rightindex = deque->rightindex;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000600 Py_ssize_t n = (Py_SIZE(deque))/2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000601 Py_ssize_t i;
602 PyObject *tmp;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000603
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000604 for (i=0 ; i<n ; i++) {
605 /* Validate that pointers haven't met in the middle */
606 assert(leftblock != rightblock || leftindex < rightindex);
Raymond Hettinger82df9252013-07-07 01:43:42 -1000607 CHECK_NOT_END(leftblock);
608 CHECK_NOT_END(rightblock);
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610 /* Swap */
611 tmp = leftblock->data[leftindex];
612 leftblock->data[leftindex] = rightblock->data[rightindex];
613 rightblock->data[rightindex] = tmp;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000614
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 /* Advance left block/index pair */
616 leftindex++;
617 if (leftindex == BLOCKLEN) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000618 leftblock = leftblock->rightlink;
619 leftindex = 0;
620 }
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 /* Step backwards with the right block/index pair */
623 rightindex--;
624 if (rightindex == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000625 rightblock = rightblock->leftlink;
626 rightindex = BLOCKLEN - 1;
627 }
628 }
629 Py_RETURN_NONE;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000630}
631
632PyDoc_STRVAR(reverse_doc,
633"D.reverse() -- reverse *IN PLACE*");
634
Raymond Hettinger44459de2010-04-03 23:20:46 +0000635static PyObject *
636deque_count(dequeobject *deque, PyObject *v)
637{
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000638 block *b = deque->leftblock;
639 Py_ssize_t index = deque->leftindex;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000640 Py_ssize_t n = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 Py_ssize_t i;
642 Py_ssize_t count = 0;
643 PyObject *item;
644 long start_state = deque->state;
645 int cmp;
Raymond Hettinger44459de2010-04-03 23:20:46 +0000646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 for (i=0 ; i<n ; i++) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000648 CHECK_NOT_END(b);
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000649 item = b->data[index];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
651 if (cmp > 0)
652 count++;
653 else if (cmp < 0)
654 return NULL;
Raymond Hettinger44459de2010-04-03 23:20:46 +0000655
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000656 if (start_state != deque->state) {
657 PyErr_SetString(PyExc_RuntimeError,
658 "deque mutated during iteration");
659 return NULL;
660 }
Raymond Hettinger44459de2010-04-03 23:20:46 +0000661
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000662 /* Advance left block/index pair */
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000663 index++;
664 if (index == BLOCKLEN) {
665 b = b->rightlink;
666 index = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000667 }
668 }
669 return PyLong_FromSsize_t(count);
Raymond Hettinger44459de2010-04-03 23:20:46 +0000670}
671
672PyDoc_STRVAR(count_doc,
673"D.count(value) -> integer -- return number of occurrences of value");
674
Martin v. Löwis18e16552006-02-15 17:27:45 +0000675static Py_ssize_t
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000676deque_len(dequeobject *deque)
677{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000678 return Py_SIZE(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000679}
680
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000681static PyObject *
682deque_remove(dequeobject *deque, PyObject *value)
683{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000684 Py_ssize_t i, n=Py_SIZE(deque);
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000685
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000686 for (i=0 ; i<n ; i++) {
687 PyObject *item = deque->leftblock->data[deque->leftindex];
688 int cmp = PyObject_RichCompareBool(item, value, Py_EQ);
Raymond Hettingerd73202c2005-03-19 00:00:51 +0000689
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000690 if (Py_SIZE(deque) != n) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000691 PyErr_SetString(PyExc_IndexError,
692 "deque mutated during remove().");
693 return NULL;
694 }
695 if (cmp > 0) {
696 PyObject *tgt = deque_popleft(deque, NULL);
697 assert (tgt != NULL);
698 Py_DECREF(tgt);
699 if (_deque_rotate(deque, i) == -1)
700 return NULL;
701 Py_RETURN_NONE;
702 }
703 else if (cmp < 0) {
704 _deque_rotate(deque, i);
705 return NULL;
706 }
707 _deque_rotate(deque, -1);
708 }
709 PyErr_SetString(PyExc_ValueError, "deque.remove(x): x not in deque");
710 return NULL;
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000711}
712
713PyDoc_STRVAR(remove_doc,
714"D.remove(value) -- remove first occurrence of value.");
715
Benjamin Peterson0e5c48a2013-01-12 21:22:18 -0500716static void
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000717deque_clear(dequeobject *deque)
718{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000719 PyObject *item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000720
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000721 while (Py_SIZE(deque)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000722 item = deque_pop(deque, NULL);
723 assert (item != NULL);
724 Py_DECREF(item);
725 }
726 assert(deque->leftblock == deque->rightblock &&
727 deque->leftindex - 1 == deque->rightindex &&
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000728 Py_SIZE(deque) == 0);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000729}
730
731static PyObject *
Benjamin Petersond6313712008-07-31 16:23:04 +0000732deque_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000733{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000734 block *b;
735 PyObject *item;
736 Py_ssize_t n, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000737
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000738 if (i < 0 || i >= Py_SIZE(deque)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 PyErr_SetString(PyExc_IndexError,
740 "deque index out of range");
741 return NULL;
742 }
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000744 if (i == 0) {
745 i = deque->leftindex;
746 b = deque->leftblock;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000747 } else if (i == Py_SIZE(deque) - 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000748 i = deque->rightindex;
749 b = deque->rightblock;
750 } else {
751 i += deque->leftindex;
752 n = i / BLOCKLEN;
753 i %= BLOCKLEN;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000754 if (index < (Py_SIZE(deque) >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000755 b = deque->leftblock;
756 while (n--)
757 b = b->rightlink;
758 } else {
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000759 n = (deque->leftindex + Py_SIZE(deque) - 1) / BLOCKLEN - n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000760 b = deque->rightblock;
761 while (n--)
762 b = b->leftlink;
763 }
764 }
765 item = b->data[i];
766 Py_INCREF(item);
767 return item;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000768}
769
Raymond Hettinger616f4f62004-06-26 04:42:06 +0000770/* delitem() implemented in terms of rotate for simplicity and reasonable
771 performance near the end points. If for some reason this method becomes
Tim Peters1065f752004-10-01 01:03:29 +0000772 popular, it is not hard to re-implement this using direct data movement
Raymond Hettinger616f4f62004-06-26 04:42:06 +0000773 (similar to code in list slice assignment) and achieve a two or threefold
774 performance boost.
775*/
776
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000777static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000778deque_del_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000779{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000780 PyObject *item;
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000781
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000782 assert (i >= 0 && i < Py_SIZE(deque));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000783 if (_deque_rotate(deque, -i) == -1)
784 return -1;
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000785
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000786 item = deque_popleft(deque, NULL);
787 assert (item != NULL);
788 Py_DECREF(item);
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 return _deque_rotate(deque, i);
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000791}
792
793static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000794deque_ass_item(dequeobject *deque, Py_ssize_t i, PyObject *v)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000795{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 PyObject *old_value;
797 block *b;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000798 Py_ssize_t n, len=Py_SIZE(deque), halflen=(len+1)>>1, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000799
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000800 if (i < 0 || i >= len) {
801 PyErr_SetString(PyExc_IndexError,
802 "deque index out of range");
803 return -1;
804 }
805 if (v == NULL)
806 return deque_del_item(deque, i);
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 i += deque->leftindex;
809 n = i / BLOCKLEN;
810 i %= BLOCKLEN;
811 if (index <= halflen) {
812 b = deque->leftblock;
813 while (n--)
814 b = b->rightlink;
815 } else {
816 n = (deque->leftindex + len - 1) / BLOCKLEN - n;
817 b = deque->rightblock;
818 while (n--)
819 b = b->leftlink;
820 }
821 Py_INCREF(v);
822 old_value = b->data[i];
823 b->data[i] = v;
824 Py_DECREF(old_value);
825 return 0;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000826}
827
828static PyObject *
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000829deque_clearmethod(dequeobject *deque)
830{
Benjamin Peterson0e5c48a2013-01-12 21:22:18 -0500831 deque_clear(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000832 Py_RETURN_NONE;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000833}
834
835PyDoc_STRVAR(clear_doc, "Remove all elements from the deque.");
836
837static void
838deque_dealloc(dequeobject *deque)
839{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 PyObject_GC_UnTrack(deque);
841 if (deque->weakreflist != NULL)
842 PyObject_ClearWeakRefs((PyObject *) deque);
843 if (deque->leftblock != NULL) {
844 deque_clear(deque);
845 assert(deque->leftblock != NULL);
846 freeblock(deque->leftblock);
847 }
848 deque->leftblock = NULL;
849 deque->rightblock = NULL;
850 Py_TYPE(deque)->tp_free(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000851}
852
853static int
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000854deque_traverse(dequeobject *deque, visitproc visit, void *arg)
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000855{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000856 block *b;
857 PyObject *item;
858 Py_ssize_t index;
859 Py_ssize_t indexlo = deque->leftindex;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000860
Raymond Hettinger5bfa8672013-07-06 11:58:09 -1000861 for (b = deque->leftblock; b != deque->rightblock; b = b->rightlink) {
862 for (index = indexlo; index < BLOCKLEN ; index++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000863 item = b->data[index];
864 Py_VISIT(item);
865 }
866 indexlo = 0;
867 }
Raymond Hettinger5bfa8672013-07-06 11:58:09 -1000868 for (index = indexlo; index <= deque->rightindex; index++) {
869 item = b->data[index];
870 Py_VISIT(item);
871 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000872 return 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000873}
874
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000875static PyObject *
876deque_copy(PyObject *deque)
877{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000878 if (((dequeobject *)deque)->maxlen == -1)
879 return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "O", deque, NULL);
880 else
881 return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "Oi",
882 deque, ((dequeobject *)deque)->maxlen, NULL);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000883}
884
885PyDoc_STRVAR(copy_doc, "Return a shallow copy of a deque.");
886
887static PyObject *
888deque_reduce(dequeobject *deque)
889{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000890 PyObject *dict, *result, *aslist;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200891 _Py_IDENTIFIER(__dict__);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000892
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200893 dict = _PyObject_GetAttrId((PyObject *)deque, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 if (dict == NULL)
895 PyErr_Clear();
896 aslist = PySequence_List((PyObject *)deque);
897 if (aslist == NULL) {
898 Py_XDECREF(dict);
899 return NULL;
900 }
901 if (dict == NULL) {
902 if (deque->maxlen == -1)
903 result = Py_BuildValue("O(O)", Py_TYPE(deque), aslist);
904 else
905 result = Py_BuildValue("O(On)", Py_TYPE(deque), aslist, deque->maxlen);
906 } else {
907 if (deque->maxlen == -1)
908 result = Py_BuildValue("O(OO)O", Py_TYPE(deque), aslist, Py_None, dict);
909 else
910 result = Py_BuildValue("O(On)O", Py_TYPE(deque), aslist, deque->maxlen, dict);
911 }
912 Py_XDECREF(dict);
913 Py_DECREF(aslist);
914 return result;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000915}
916
917PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
918
919static PyObject *
920deque_repr(PyObject *deque)
921{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 PyObject *aslist, *result;
923 int i;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000925 i = Py_ReprEnter(deque);
926 if (i != 0) {
927 if (i < 0)
928 return NULL;
929 return PyUnicode_FromString("[...]");
930 }
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 aslist = PySequence_List(deque);
933 if (aslist == NULL) {
934 Py_ReprLeave(deque);
935 return NULL;
936 }
937 if (((dequeobject *)deque)->maxlen != -1)
Benjamin Petersona786b022008-08-25 21:05:21 +0000938
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 result = PyUnicode_FromFormat("deque(%R, maxlen=%zd)",
940 aslist, ((dequeobject *)deque)->maxlen);
941 else
942 result = PyUnicode_FromFormat("deque(%R)", aslist);
943 Py_DECREF(aslist);
944 Py_ReprLeave(deque);
945 return result;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000946}
947
Raymond Hettinger738ec902004-02-29 02:15:56 +0000948static PyObject *
949deque_richcompare(PyObject *v, PyObject *w, int op)
950{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 PyObject *it1=NULL, *it2=NULL, *x, *y;
952 Py_ssize_t vs, ws;
953 int b, cmp=-1;
Raymond Hettinger738ec902004-02-29 02:15:56 +0000954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 if (!PyObject_TypeCheck(v, &deque_type) ||
956 !PyObject_TypeCheck(w, &deque_type)) {
Brian Curtindfc80e32011-08-10 20:28:54 -0500957 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000958 }
Raymond Hettinger738ec902004-02-29 02:15:56 +0000959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 /* Shortcuts */
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000961 vs = Py_SIZE((dequeobject *)v);
962 ws = Py_SIZE((dequeobject *)w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000963 if (op == Py_EQ) {
964 if (v == w)
965 Py_RETURN_TRUE;
966 if (vs != ws)
967 Py_RETURN_FALSE;
968 }
969 if (op == Py_NE) {
970 if (v == w)
971 Py_RETURN_FALSE;
972 if (vs != ws)
973 Py_RETURN_TRUE;
974 }
Raymond Hettinger738ec902004-02-29 02:15:56 +0000975
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000976 /* Search for the first index where items are different */
977 it1 = PyObject_GetIter(v);
978 if (it1 == NULL)
979 goto done;
980 it2 = PyObject_GetIter(w);
981 if (it2 == NULL)
982 goto done;
983 for (;;) {
984 x = PyIter_Next(it1);
985 if (x == NULL && PyErr_Occurred())
986 goto done;
987 y = PyIter_Next(it2);
988 if (x == NULL || y == NULL)
989 break;
990 b = PyObject_RichCompareBool(x, y, Py_EQ);
991 if (b == 0) {
992 cmp = PyObject_RichCompareBool(x, y, op);
993 Py_DECREF(x);
994 Py_DECREF(y);
995 goto done;
996 }
997 Py_DECREF(x);
998 Py_DECREF(y);
999 if (b == -1)
1000 goto done;
1001 }
1002 /* We reached the end of one deque or both */
1003 Py_XDECREF(x);
1004 Py_XDECREF(y);
1005 if (PyErr_Occurred())
1006 goto done;
1007 switch (op) {
1008 case Py_LT: cmp = y != NULL; break; /* if w was longer */
1009 case Py_LE: cmp = x == NULL; break; /* if v was not longer */
1010 case Py_EQ: cmp = x == y; break; /* if we reached the end of both */
1011 case Py_NE: cmp = x != y; break; /* if one deque continues */
1012 case Py_GT: cmp = x != NULL; break; /* if v was longer */
1013 case Py_GE: cmp = y == NULL; break; /* if w was not longer */
1014 }
Tim Peters1065f752004-10-01 01:03:29 +00001015
Raymond Hettinger738ec902004-02-29 02:15:56 +00001016done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 Py_XDECREF(it1);
1018 Py_XDECREF(it2);
1019 if (cmp == 1)
1020 Py_RETURN_TRUE;
1021 if (cmp == 0)
1022 Py_RETURN_FALSE;
1023 return NULL;
Raymond Hettinger738ec902004-02-29 02:15:56 +00001024}
1025
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001026static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001027deque_init(dequeobject *deque, PyObject *args, PyObject *kwdargs)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001028{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 PyObject *iterable = NULL;
1030 PyObject *maxlenobj = NULL;
1031 Py_ssize_t maxlen = -1;
1032 char *kwlist[] = {"iterable", "maxlen", 0};
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001033
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001034 if (!PyArg_ParseTupleAndKeywords(args, kwdargs, "|OO:deque", kwlist, &iterable, &maxlenobj))
1035 return -1;
1036 if (maxlenobj != NULL && maxlenobj != Py_None) {
1037 maxlen = PyLong_AsSsize_t(maxlenobj);
1038 if (maxlen == -1 && PyErr_Occurred())
1039 return -1;
1040 if (maxlen < 0) {
1041 PyErr_SetString(PyExc_ValueError, "maxlen must be non-negative");
1042 return -1;
1043 }
1044 }
1045 deque->maxlen = maxlen;
1046 deque_clear(deque);
1047 if (iterable != NULL) {
1048 PyObject *rv = deque_extend(deque, iterable);
1049 if (rv == NULL)
1050 return -1;
1051 Py_DECREF(rv);
1052 }
1053 return 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001054}
1055
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001056static PyObject *
Jesus Cea16e2fca2012-08-03 14:49:42 +02001057deque_sizeof(dequeobject *deque, void *unused)
1058{
1059 Py_ssize_t res;
1060 Py_ssize_t blocks;
1061
1062 res = sizeof(dequeobject);
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001063 blocks = (deque->leftindex + Py_SIZE(deque) + BLOCKLEN - 1) / BLOCKLEN;
1064 assert(deque->leftindex + Py_SIZE(deque) - 1 ==
Jesus Cea16e2fca2012-08-03 14:49:42 +02001065 (blocks - 1) * BLOCKLEN + deque->rightindex);
1066 res += blocks * sizeof(block);
1067 return PyLong_FromSsize_t(res);
1068}
1069
1070PyDoc_STRVAR(sizeof_doc,
1071"D.__sizeof__() -- size of D in memory, in bytes");
1072
1073static PyObject *
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001074deque_get_maxlen(dequeobject *deque)
1075{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001076 if (deque->maxlen == -1)
1077 Py_RETURN_NONE;
1078 return PyLong_FromSsize_t(deque->maxlen);
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001079}
1080
1081static PyGetSetDef deque_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 {"maxlen", (getter)deque_get_maxlen, (setter)NULL,
1083 "maximum size of a deque or None if unbounded"},
1084 {0}
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001085};
1086
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001087static PySequenceMethods deque_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001088 (lenfunc)deque_len, /* sq_length */
1089 0, /* sq_concat */
1090 0, /* sq_repeat */
1091 (ssizeargfunc)deque_item, /* sq_item */
1092 0, /* sq_slice */
1093 (ssizeobjargproc)deque_ass_item, /* sq_ass_item */
1094 0, /* sq_ass_slice */
1095 0, /* sq_contains */
1096 (binaryfunc)deque_inplace_concat, /* sq_inplace_concat */
1097 0, /* sq_inplace_repeat */
Raymond Hettinger3f9afd82009-12-10 03:03:02 +00001098
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001099};
1100
1101/* deque object ********************************************************/
1102
1103static PyObject *deque_iter(dequeobject *deque);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001104static PyObject *deque_reviter(dequeobject *deque);
Tim Peters1065f752004-10-01 01:03:29 +00001105PyDoc_STRVAR(reversed_doc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 "D.__reversed__() -- return a reverse iterator over the deque");
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001107
1108static PyMethodDef deque_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001109 {"append", (PyCFunction)deque_append,
1110 METH_O, append_doc},
1111 {"appendleft", (PyCFunction)deque_appendleft,
1112 METH_O, appendleft_doc},
1113 {"clear", (PyCFunction)deque_clearmethod,
1114 METH_NOARGS, clear_doc},
1115 {"__copy__", (PyCFunction)deque_copy,
1116 METH_NOARGS, copy_doc},
1117 {"count", (PyCFunction)deque_count,
1118 METH_O, count_doc},
1119 {"extend", (PyCFunction)deque_extend,
1120 METH_O, extend_doc},
1121 {"extendleft", (PyCFunction)deque_extendleft,
1122 METH_O, extendleft_doc},
1123 {"pop", (PyCFunction)deque_pop,
1124 METH_NOARGS, pop_doc},
1125 {"popleft", (PyCFunction)deque_popleft,
1126 METH_NOARGS, popleft_doc},
1127 {"__reduce__", (PyCFunction)deque_reduce,
1128 METH_NOARGS, reduce_doc},
1129 {"remove", (PyCFunction)deque_remove,
1130 METH_O, remove_doc},
1131 {"__reversed__", (PyCFunction)deque_reviter,
1132 METH_NOARGS, reversed_doc},
1133 {"reverse", (PyCFunction)deque_reverse,
1134 METH_NOARGS, reverse_doc},
1135 {"rotate", (PyCFunction)deque_rotate,
Jesus Cea16e2fca2012-08-03 14:49:42 +02001136 METH_VARARGS, rotate_doc},
1137 {"__sizeof__", (PyCFunction)deque_sizeof,
1138 METH_NOARGS, sizeof_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001139 {NULL, NULL} /* sentinel */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001140};
1141
1142PyDoc_STRVAR(deque_doc,
Andrew Svetlov6a5c7c32012-10-31 11:50:40 +02001143"deque([iterable[, maxlen]]) --> deque object\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001144\n\
Raymond Hettinger49747052011-03-29 17:36:31 -07001145Build an ordered collection with optimized access from its endpoints.");
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001146
Neal Norwitz87f10132004-02-29 15:40:53 +00001147static PyTypeObject deque_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001148 PyVarObject_HEAD_INIT(NULL, 0)
1149 "collections.deque", /* tp_name */
1150 sizeof(dequeobject), /* tp_basicsize */
1151 0, /* tp_itemsize */
1152 /* methods */
1153 (destructor)deque_dealloc, /* tp_dealloc */
1154 0, /* tp_print */
1155 0, /* tp_getattr */
1156 0, /* tp_setattr */
1157 0, /* tp_reserved */
1158 deque_repr, /* tp_repr */
1159 0, /* tp_as_number */
1160 &deque_as_sequence, /* tp_as_sequence */
1161 0, /* tp_as_mapping */
Georg Brandlf038b322010-10-18 07:35:09 +00001162 PyObject_HashNotImplemented, /* tp_hash */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001163 0, /* tp_call */
1164 0, /* tp_str */
1165 PyObject_GenericGetAttr, /* tp_getattro */
1166 0, /* tp_setattro */
1167 0, /* tp_as_buffer */
1168 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
Georg Brandlf038b322010-10-18 07:35:09 +00001169 /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001170 deque_doc, /* tp_doc */
1171 (traverseproc)deque_traverse, /* tp_traverse */
1172 (inquiry)deque_clear, /* tp_clear */
1173 (richcmpfunc)deque_richcompare, /* tp_richcompare */
Georg Brandlf038b322010-10-18 07:35:09 +00001174 offsetof(dequeobject, weakreflist), /* tp_weaklistoffset*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001175 (getiterfunc)deque_iter, /* tp_iter */
1176 0, /* tp_iternext */
1177 deque_methods, /* tp_methods */
1178 0, /* tp_members */
Georg Brandlf038b322010-10-18 07:35:09 +00001179 deque_getset, /* tp_getset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001180 0, /* tp_base */
1181 0, /* tp_dict */
1182 0, /* tp_descr_get */
1183 0, /* tp_descr_set */
1184 0, /* tp_dictoffset */
1185 (initproc)deque_init, /* tp_init */
1186 PyType_GenericAlloc, /* tp_alloc */
1187 deque_new, /* tp_new */
1188 PyObject_GC_Del, /* tp_free */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001189};
1190
1191/*********************** Deque Iterator **************************/
1192
1193typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 PyObject_HEAD
1195 Py_ssize_t index;
1196 block *b;
1197 dequeobject *deque;
1198 long state; /* state when the iterator is created */
1199 Py_ssize_t counter; /* number of items remaining for iteration */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001200} dequeiterobject;
1201
Martin v. Löwis59683e82008-06-13 07:50:45 +00001202static PyTypeObject dequeiter_type;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001203
1204static PyObject *
1205deque_iter(dequeobject *deque)
1206{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001207 dequeiterobject *it;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 it = PyObject_GC_New(dequeiterobject, &dequeiter_type);
1210 if (it == NULL)
1211 return NULL;
1212 it->b = deque->leftblock;
1213 it->index = deque->leftindex;
1214 Py_INCREF(deque);
1215 it->deque = deque;
1216 it->state = deque->state;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001217 it->counter = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001218 PyObject_GC_Track(it);
1219 return (PyObject *)it;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001220}
1221
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001222static int
1223dequeiter_traverse(dequeiterobject *dio, visitproc visit, void *arg)
1224{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 Py_VISIT(dio->deque);
1226 return 0;
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001227}
1228
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001229static void
1230dequeiter_dealloc(dequeiterobject *dio)
1231{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001232 Py_XDECREF(dio->deque);
1233 PyObject_GC_Del(dio);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001234}
1235
1236static PyObject *
1237dequeiter_next(dequeiterobject *it)
1238{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001239 PyObject *item;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001241 if (it->deque->state != it->state) {
1242 it->counter = 0;
1243 PyErr_SetString(PyExc_RuntimeError,
1244 "deque mutated during iteration");
1245 return NULL;
1246 }
1247 if (it->counter == 0)
1248 return NULL;
1249 assert (!(it->b == it->deque->rightblock &&
1250 it->index > it->deque->rightindex));
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001252 item = it->b->data[it->index];
1253 it->index++;
1254 it->counter--;
1255 if (it->index == BLOCKLEN && it->counter > 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -10001256 CHECK_NOT_END(it->b->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001257 it->b = it->b->rightlink;
1258 it->index = 0;
1259 }
1260 Py_INCREF(item);
1261 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001262}
1263
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001264static PyObject *
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001265dequeiter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1266{
1267 Py_ssize_t i, index=0;
1268 PyObject *deque;
1269 dequeiterobject *it;
1270 if (!PyArg_ParseTuple(args, "O!|n", &deque_type, &deque, &index))
1271 return NULL;
1272 assert(type == &dequeiter_type);
1273
1274 it = (dequeiterobject*)deque_iter((dequeobject *)deque);
1275 if (!it)
1276 return NULL;
1277 /* consume items from the queue */
1278 for(i=0; i<index; i++) {
1279 PyObject *item = dequeiter_next(it);
1280 if (item) {
1281 Py_DECREF(item);
1282 } else {
1283 if (it->counter) {
1284 Py_DECREF(it);
1285 return NULL;
1286 } else
1287 break;
1288 }
1289 }
1290 return (PyObject*)it;
1291}
1292
1293static PyObject *
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001294dequeiter_len(dequeiterobject *it)
1295{
Antoine Pitrou554f3342010-08-17 18:30:06 +00001296 return PyLong_FromSsize_t(it->counter);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001297}
1298
Armin Rigof5b3e362006-02-11 21:32:43 +00001299PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001300
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001301static PyObject *
1302dequeiter_reduce(dequeiterobject *it)
1303{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001304 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 +00001305}
1306
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001307static PyMethodDef dequeiter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001308 {"__length_hint__", (PyCFunction)dequeiter_len, METH_NOARGS, length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001309 {"__reduce__", (PyCFunction)dequeiter_reduce, METH_NOARGS, reduce_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001310 {NULL, NULL} /* sentinel */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001311};
1312
Martin v. Löwis59683e82008-06-13 07:50:45 +00001313static PyTypeObject dequeiter_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001314 PyVarObject_HEAD_INIT(NULL, 0)
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001315 "_collections._deque_iterator", /* tp_name */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001316 sizeof(dequeiterobject), /* tp_basicsize */
1317 0, /* tp_itemsize */
1318 /* methods */
1319 (destructor)dequeiter_dealloc, /* tp_dealloc */
1320 0, /* tp_print */
1321 0, /* tp_getattr */
1322 0, /* tp_setattr */
1323 0, /* tp_reserved */
1324 0, /* tp_repr */
1325 0, /* tp_as_number */
1326 0, /* tp_as_sequence */
1327 0, /* tp_as_mapping */
1328 0, /* tp_hash */
1329 0, /* tp_call */
1330 0, /* tp_str */
1331 PyObject_GenericGetAttr, /* tp_getattro */
1332 0, /* tp_setattro */
1333 0, /* tp_as_buffer */
1334 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
1335 0, /* tp_doc */
1336 (traverseproc)dequeiter_traverse, /* tp_traverse */
1337 0, /* tp_clear */
1338 0, /* tp_richcompare */
1339 0, /* tp_weaklistoffset */
1340 PyObject_SelfIter, /* tp_iter */
1341 (iternextfunc)dequeiter_next, /* tp_iternext */
1342 dequeiter_methods, /* tp_methods */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001343 0, /* tp_members */
1344 0, /* tp_getset */
1345 0, /* tp_base */
1346 0, /* tp_dict */
1347 0, /* tp_descr_get */
1348 0, /* tp_descr_set */
1349 0, /* tp_dictoffset */
1350 0, /* tp_init */
1351 0, /* tp_alloc */
1352 dequeiter_new, /* tp_new */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001353 0,
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001354};
1355
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001356/*********************** Deque Reverse Iterator **************************/
1357
Martin v. Löwis59683e82008-06-13 07:50:45 +00001358static PyTypeObject dequereviter_type;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001359
1360static PyObject *
1361deque_reviter(dequeobject *deque)
1362{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001363 dequeiterobject *it;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001365 it = PyObject_GC_New(dequeiterobject, &dequereviter_type);
1366 if (it == NULL)
1367 return NULL;
1368 it->b = deque->rightblock;
1369 it->index = deque->rightindex;
1370 Py_INCREF(deque);
1371 it->deque = deque;
1372 it->state = deque->state;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001373 it->counter = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001374 PyObject_GC_Track(it);
1375 return (PyObject *)it;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001376}
1377
1378static PyObject *
1379dequereviter_next(dequeiterobject *it)
1380{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001381 PyObject *item;
1382 if (it->counter == 0)
1383 return NULL;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001385 if (it->deque->state != it->state) {
1386 it->counter = 0;
1387 PyErr_SetString(PyExc_RuntimeError,
1388 "deque mutated during iteration");
1389 return NULL;
1390 }
1391 assert (!(it->b == it->deque->leftblock &&
1392 it->index < it->deque->leftindex));
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001394 item = it->b->data[it->index];
1395 it->index--;
1396 it->counter--;
1397 if (it->index == -1 && it->counter > 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -10001398 CHECK_NOT_END(it->b->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001399 it->b = it->b->leftlink;
1400 it->index = BLOCKLEN - 1;
1401 }
1402 Py_INCREF(item);
1403 return item;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001404}
1405
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001406static PyObject *
1407dequereviter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1408{
1409 Py_ssize_t i, index=0;
1410 PyObject *deque;
1411 dequeiterobject *it;
1412 if (!PyArg_ParseTuple(args, "O!|n", &deque_type, &deque, &index))
1413 return NULL;
1414 assert(type == &dequereviter_type);
1415
1416 it = (dequeiterobject*)deque_reviter((dequeobject *)deque);
1417 if (!it)
1418 return NULL;
1419 /* consume items from the queue */
1420 for(i=0; i<index; i++) {
1421 PyObject *item = dequereviter_next(it);
1422 if (item) {
1423 Py_DECREF(item);
1424 } else {
1425 if (it->counter) {
1426 Py_DECREF(it);
1427 return NULL;
1428 } else
1429 break;
1430 }
1431 }
1432 return (PyObject*)it;
1433}
1434
Martin v. Löwis59683e82008-06-13 07:50:45 +00001435static PyTypeObject dequereviter_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001436 PyVarObject_HEAD_INIT(NULL, 0)
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001437 "_collections._deque_reverse_iterator", /* tp_name */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001438 sizeof(dequeiterobject), /* tp_basicsize */
1439 0, /* tp_itemsize */
1440 /* methods */
1441 (destructor)dequeiter_dealloc, /* tp_dealloc */
1442 0, /* tp_print */
1443 0, /* tp_getattr */
1444 0, /* tp_setattr */
1445 0, /* tp_reserved */
1446 0, /* tp_repr */
1447 0, /* tp_as_number */
1448 0, /* tp_as_sequence */
1449 0, /* tp_as_mapping */
1450 0, /* tp_hash */
1451 0, /* tp_call */
1452 0, /* tp_str */
1453 PyObject_GenericGetAttr, /* tp_getattro */
1454 0, /* tp_setattro */
1455 0, /* tp_as_buffer */
1456 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
1457 0, /* tp_doc */
1458 (traverseproc)dequeiter_traverse, /* tp_traverse */
1459 0, /* tp_clear */
1460 0, /* tp_richcompare */
1461 0, /* tp_weaklistoffset */
1462 PyObject_SelfIter, /* tp_iter */
1463 (iternextfunc)dequereviter_next, /* tp_iternext */
1464 dequeiter_methods, /* tp_methods */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001465 0, /* tp_members */
1466 0, /* tp_getset */
1467 0, /* tp_base */
1468 0, /* tp_dict */
1469 0, /* tp_descr_get */
1470 0, /* tp_descr_set */
1471 0, /* tp_dictoffset */
1472 0, /* tp_init */
1473 0, /* tp_alloc */
1474 dequereviter_new, /* tp_new */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001475 0,
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001476};
1477
Guido van Rossum1968ad32006-02-25 22:38:04 +00001478/* defaultdict type *********************************************************/
1479
1480typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001481 PyDictObject dict;
1482 PyObject *default_factory;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001483} defdictobject;
1484
1485static PyTypeObject defdict_type; /* Forward */
1486
1487PyDoc_STRVAR(defdict_missing_doc,
1488"__missing__(key) # Called by __getitem__ for missing key; pseudo-code:\n\
Guido van Rossumd8faa362007-04-27 19:54:29 +00001489 if self.default_factory is None: raise KeyError((key,))\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00001490 self[key] = value = self.default_factory()\n\
1491 return value\n\
1492");
1493
1494static PyObject *
1495defdict_missing(defdictobject *dd, PyObject *key)
1496{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001497 PyObject *factory = dd->default_factory;
1498 PyObject *value;
1499 if (factory == NULL || factory == Py_None) {
1500 /* XXX Call dict.__missing__(key) */
1501 PyObject *tup;
1502 tup = PyTuple_Pack(1, key);
1503 if (!tup) return NULL;
1504 PyErr_SetObject(PyExc_KeyError, tup);
1505 Py_DECREF(tup);
1506 return NULL;
1507 }
1508 value = PyEval_CallObject(factory, NULL);
1509 if (value == NULL)
1510 return value;
1511 if (PyObject_SetItem((PyObject *)dd, key, value) < 0) {
1512 Py_DECREF(value);
1513 return NULL;
1514 }
1515 return value;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001516}
1517
1518PyDoc_STRVAR(defdict_copy_doc, "D.copy() -> a shallow copy of D.");
1519
1520static PyObject *
1521defdict_copy(defdictobject *dd)
1522{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001523 /* This calls the object's class. That only works for subclasses
1524 whose class constructor has the same signature. Subclasses that
1525 define a different constructor signature must override copy().
1526 */
Raymond Hettinger54628fa2009-08-04 19:16:39 +00001527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001528 if (dd->default_factory == NULL)
1529 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd), Py_None, dd, NULL);
1530 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd),
1531 dd->default_factory, dd, NULL);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001532}
1533
1534static PyObject *
1535defdict_reduce(defdictobject *dd)
1536{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001537 /* __reduce__ must return a 5-tuple as follows:
Guido van Rossum1968ad32006-02-25 22:38:04 +00001538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001539 - factory function
1540 - tuple of args for the factory function
1541 - additional state (here None)
1542 - sequence iterator (here None)
1543 - dictionary iterator (yielding successive (key, value) pairs
Guido van Rossum1968ad32006-02-25 22:38:04 +00001544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001545 This API is used by pickle.py and copy.py.
Guido van Rossum1968ad32006-02-25 22:38:04 +00001546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001547 For this to be useful with pickle.py, the default_factory
1548 must be picklable; e.g., None, a built-in, or a global
1549 function in a module or package.
Guido van Rossum1968ad32006-02-25 22:38:04 +00001550
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001551 Both shallow and deep copying are supported, but for deep
1552 copying, the default_factory must be deep-copyable; e.g. None,
1553 or a built-in (functions are not copyable at this time).
Guido van Rossum1968ad32006-02-25 22:38:04 +00001554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001555 This only works for subclasses as long as their constructor
1556 signature is compatible; the first argument must be the
1557 optional default_factory, defaulting to None.
1558 */
1559 PyObject *args;
1560 PyObject *items;
1561 PyObject *iter;
1562 PyObject *result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001563 _Py_IDENTIFIER(items);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001565 if (dd->default_factory == NULL || dd->default_factory == Py_None)
1566 args = PyTuple_New(0);
1567 else
1568 args = PyTuple_Pack(1, dd->default_factory);
1569 if (args == NULL)
1570 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001571 items = _PyObject_CallMethodId((PyObject *)dd, &PyId_items, "()");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001572 if (items == NULL) {
1573 Py_DECREF(args);
1574 return NULL;
1575 }
1576 iter = PyObject_GetIter(items);
1577 if (iter == NULL) {
1578 Py_DECREF(items);
1579 Py_DECREF(args);
1580 return NULL;
1581 }
1582 result = PyTuple_Pack(5, Py_TYPE(dd), args,
1583 Py_None, Py_None, iter);
1584 Py_DECREF(iter);
1585 Py_DECREF(items);
1586 Py_DECREF(args);
1587 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001588}
1589
1590static PyMethodDef defdict_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001591 {"__missing__", (PyCFunction)defdict_missing, METH_O,
1592 defdict_missing_doc},
1593 {"copy", (PyCFunction)defdict_copy, METH_NOARGS,
1594 defdict_copy_doc},
1595 {"__copy__", (PyCFunction)defdict_copy, METH_NOARGS,
1596 defdict_copy_doc},
1597 {"__reduce__", (PyCFunction)defdict_reduce, METH_NOARGS,
1598 reduce_doc},
1599 {NULL}
Guido van Rossum1968ad32006-02-25 22:38:04 +00001600};
1601
1602static PyMemberDef defdict_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001603 {"default_factory", T_OBJECT,
1604 offsetof(defdictobject, default_factory), 0,
1605 PyDoc_STR("Factory for default value called by __missing__().")},
1606 {NULL}
Guido van Rossum1968ad32006-02-25 22:38:04 +00001607};
1608
1609static void
1610defdict_dealloc(defdictobject *dd)
1611{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001612 Py_CLEAR(dd->default_factory);
1613 PyDict_Type.tp_dealloc((PyObject *)dd);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001614}
1615
Guido van Rossum1968ad32006-02-25 22:38:04 +00001616static PyObject *
1617defdict_repr(defdictobject *dd)
1618{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001619 PyObject *baserepr;
1620 PyObject *defrepr;
1621 PyObject *result;
1622 baserepr = PyDict_Type.tp_repr((PyObject *)dd);
1623 if (baserepr == NULL)
1624 return NULL;
1625 if (dd->default_factory == NULL)
1626 defrepr = PyUnicode_FromString("None");
1627 else
1628 {
1629 int status = Py_ReprEnter(dd->default_factory);
1630 if (status != 0) {
Antoine Pitrouf5f1fe02012-02-15 02:42:46 +01001631 if (status < 0) {
1632 Py_DECREF(baserepr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001633 return NULL;
Antoine Pitrouf5f1fe02012-02-15 02:42:46 +01001634 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001635 defrepr = PyUnicode_FromString("...");
1636 }
1637 else
1638 defrepr = PyObject_Repr(dd->default_factory);
1639 Py_ReprLeave(dd->default_factory);
1640 }
1641 if (defrepr == NULL) {
1642 Py_DECREF(baserepr);
1643 return NULL;
1644 }
1645 result = PyUnicode_FromFormat("defaultdict(%U, %U)",
1646 defrepr, baserepr);
1647 Py_DECREF(defrepr);
1648 Py_DECREF(baserepr);
1649 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001650}
1651
1652static int
1653defdict_traverse(PyObject *self, visitproc visit, void *arg)
1654{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001655 Py_VISIT(((defdictobject *)self)->default_factory);
1656 return PyDict_Type.tp_traverse(self, visit, arg);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001657}
1658
1659static int
1660defdict_tp_clear(defdictobject *dd)
1661{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001662 Py_CLEAR(dd->default_factory);
1663 return PyDict_Type.tp_clear((PyObject *)dd);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001664}
1665
1666static int
1667defdict_init(PyObject *self, PyObject *args, PyObject *kwds)
1668{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001669 defdictobject *dd = (defdictobject *)self;
1670 PyObject *olddefault = dd->default_factory;
1671 PyObject *newdefault = NULL;
1672 PyObject *newargs;
1673 int result;
1674 if (args == NULL || !PyTuple_Check(args))
1675 newargs = PyTuple_New(0);
1676 else {
1677 Py_ssize_t n = PyTuple_GET_SIZE(args);
1678 if (n > 0) {
1679 newdefault = PyTuple_GET_ITEM(args, 0);
1680 if (!PyCallable_Check(newdefault) && newdefault != Py_None) {
1681 PyErr_SetString(PyExc_TypeError,
1682 "first argument must be callable");
1683 return -1;
1684 }
1685 }
1686 newargs = PySequence_GetSlice(args, 1, n);
1687 }
1688 if (newargs == NULL)
1689 return -1;
1690 Py_XINCREF(newdefault);
1691 dd->default_factory = newdefault;
1692 result = PyDict_Type.tp_init(self, newargs, kwds);
1693 Py_DECREF(newargs);
1694 Py_XDECREF(olddefault);
1695 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001696}
1697
1698PyDoc_STRVAR(defdict_doc,
1699"defaultdict(default_factory) --> dict with default factory\n\
1700\n\
1701The default factory is called without arguments to produce\n\
1702a new value when a key is not present, in __getitem__ only.\n\
1703A defaultdict compares equal to a dict with the same items.\n\
1704");
1705
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001706/* See comment in xxsubtype.c */
1707#define DEFERRED_ADDRESS(ADDR) 0
1708
Guido van Rossum1968ad32006-02-25 22:38:04 +00001709static PyTypeObject defdict_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001710 PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0)
1711 "collections.defaultdict", /* tp_name */
1712 sizeof(defdictobject), /* tp_basicsize */
1713 0, /* tp_itemsize */
1714 /* methods */
1715 (destructor)defdict_dealloc, /* tp_dealloc */
1716 0, /* tp_print */
1717 0, /* tp_getattr */
1718 0, /* tp_setattr */
1719 0, /* tp_reserved */
1720 (reprfunc)defdict_repr, /* tp_repr */
1721 0, /* tp_as_number */
1722 0, /* tp_as_sequence */
1723 0, /* tp_as_mapping */
1724 0, /* tp_hash */
1725 0, /* tp_call */
1726 0, /* tp_str */
1727 PyObject_GenericGetAttr, /* tp_getattro */
1728 0, /* tp_setattro */
1729 0, /* tp_as_buffer */
1730 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
1731 /* tp_flags */
1732 defdict_doc, /* tp_doc */
1733 defdict_traverse, /* tp_traverse */
1734 (inquiry)defdict_tp_clear, /* tp_clear */
1735 0, /* tp_richcompare */
1736 0, /* tp_weaklistoffset*/
1737 0, /* tp_iter */
1738 0, /* tp_iternext */
1739 defdict_methods, /* tp_methods */
1740 defdict_members, /* tp_members */
1741 0, /* tp_getset */
1742 DEFERRED_ADDRESS(&PyDict_Type), /* tp_base */
1743 0, /* tp_dict */
1744 0, /* tp_descr_get */
1745 0, /* tp_descr_set */
1746 0, /* tp_dictoffset */
1747 defdict_init, /* tp_init */
1748 PyType_GenericAlloc, /* tp_alloc */
1749 0, /* tp_new */
1750 PyObject_GC_Del, /* tp_free */
Guido van Rossum1968ad32006-02-25 22:38:04 +00001751};
1752
Raymond Hettinger96f34102010-12-15 16:30:37 +00001753/* helper function for Counter *********************************************/
1754
1755PyDoc_STRVAR(_count_elements_doc,
1756"_count_elements(mapping, iterable) -> None\n\
1757\n\
1758Count elements in the iterable, updating the mappping");
1759
1760static PyObject *
1761_count_elements(PyObject *self, PyObject *args)
1762{
1763 PyObject *it, *iterable, *mapping, *oldval;
1764 PyObject *newval = NULL;
1765 PyObject *key = NULL;
1766 PyObject *one = NULL;
1767
1768 if (!PyArg_UnpackTuple(args, "_count_elements", 2, 2, &mapping, &iterable))
1769 return NULL;
1770
Raymond Hettinger96f34102010-12-15 16:30:37 +00001771 it = PyObject_GetIter(iterable);
1772 if (it == NULL)
1773 return NULL;
Raymond Hettinger426e0522011-01-03 02:12:02 +00001774
Raymond Hettinger96f34102010-12-15 16:30:37 +00001775 one = PyLong_FromLong(1);
1776 if (one == NULL) {
1777 Py_DECREF(it);
1778 return NULL;
1779 }
Raymond Hettinger426e0522011-01-03 02:12:02 +00001780
1781 if (PyDict_CheckExact(mapping)) {
1782 while (1) {
1783 key = PyIter_Next(it);
Victor Stinnera154b5c2011-04-20 23:23:52 +02001784 if (key == NULL)
1785 break;
Raymond Hettinger426e0522011-01-03 02:12:02 +00001786 oldval = PyDict_GetItem(mapping, key);
1787 if (oldval == NULL) {
1788 if (PyDict_SetItem(mapping, key, one) == -1)
1789 break;
1790 } else {
1791 newval = PyNumber_Add(oldval, one);
1792 if (newval == NULL)
1793 break;
1794 if (PyDict_SetItem(mapping, key, newval) == -1)
1795 break;
1796 Py_CLEAR(newval);
1797 }
1798 Py_DECREF(key);
Raymond Hettinger96f34102010-12-15 16:30:37 +00001799 }
Raymond Hettinger426e0522011-01-03 02:12:02 +00001800 } else {
1801 while (1) {
1802 key = PyIter_Next(it);
Victor Stinnera154b5c2011-04-20 23:23:52 +02001803 if (key == NULL)
1804 break;
Raymond Hettinger426e0522011-01-03 02:12:02 +00001805 oldval = PyObject_GetItem(mapping, key);
1806 if (oldval == NULL) {
1807 if (!PyErr_Occurred() || !PyErr_ExceptionMatches(PyExc_KeyError))
1808 break;
1809 PyErr_Clear();
1810 Py_INCREF(one);
1811 newval = one;
1812 } else {
1813 newval = PyNumber_Add(oldval, one);
1814 Py_DECREF(oldval);
1815 if (newval == NULL)
1816 break;
1817 }
1818 if (PyObject_SetItem(mapping, key, newval) == -1)
Raymond Hettinger96f34102010-12-15 16:30:37 +00001819 break;
1820 Py_CLEAR(newval);
Raymond Hettinger426e0522011-01-03 02:12:02 +00001821 Py_DECREF(key);
Raymond Hettinger96f34102010-12-15 16:30:37 +00001822 }
Raymond Hettinger96f34102010-12-15 16:30:37 +00001823 }
Raymond Hettinger426e0522011-01-03 02:12:02 +00001824
Raymond Hettinger96f34102010-12-15 16:30:37 +00001825 Py_DECREF(it);
1826 Py_XDECREF(key);
1827 Py_XDECREF(newval);
1828 Py_DECREF(one);
1829 if (PyErr_Occurred())
1830 return NULL;
1831 Py_RETURN_NONE;
1832}
1833
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001834/* module level code ********************************************************/
1835
1836PyDoc_STRVAR(module_doc,
Guido van Rossum1968ad32006-02-25 22:38:04 +00001837"High performance data structures.\n\
1838- deque: ordered collection accessible from endpoints only\n\
1839- defaultdict: dict subclass with a default value factory\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001840");
1841
Raymond Hettinger96f34102010-12-15 16:30:37 +00001842static struct PyMethodDef module_functions[] = {
1843 {"_count_elements", _count_elements, METH_VARARGS, _count_elements_doc},
1844 {NULL, NULL} /* sentinel */
1845};
Martin v. Löwis1a214512008-06-11 05:26:20 +00001846
1847static struct PyModuleDef _collectionsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001848 PyModuleDef_HEAD_INIT,
1849 "_collections",
1850 module_doc,
1851 -1,
Raymond Hettinger96f34102010-12-15 16:30:37 +00001852 module_functions,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001853 NULL,
1854 NULL,
1855 NULL,
1856 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001857};
1858
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001859PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001860PyInit__collections(void)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001861{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001862 PyObject *m;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001864 m = PyModule_Create(&_collectionsmodule);
1865 if (m == NULL)
1866 return NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001868 if (PyType_Ready(&deque_type) < 0)
1869 return NULL;
1870 Py_INCREF(&deque_type);
1871 PyModule_AddObject(m, "deque", (PyObject *)&deque_type);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001873 defdict_type.tp_base = &PyDict_Type;
1874 if (PyType_Ready(&defdict_type) < 0)
1875 return NULL;
1876 Py_INCREF(&defdict_type);
1877 PyModule_AddObject(m, "defaultdict", (PyObject *)&defdict_type);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001879 if (PyType_Ready(&dequeiter_type) < 0)
1880 return NULL;
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001881 Py_INCREF(&dequeiter_type);
1882 PyModule_AddObject(m, "_deque_iterator", (PyObject *)&dequeiter_type);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001884 if (PyType_Ready(&dequereviter_type) < 0)
1885 return NULL;
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001886 Py_INCREF(&dequereviter_type);
1887 PyModule_AddObject(m, "_deque_reverse_iterator", (PyObject *)&dequereviter_type);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001889 return m;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001890}