blob: b9224754db4742bc3a249aef0a8cab5b5d36ec87 [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 Hettinger7d112df2004-11-02 02:11:35 +000017#define BLOCKLEN 62
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.
21 * This list is not circular (the leftmost block has leftlink==NULL,
22 * and the rightmost block has rightlink==NULL). A deque d's first
23 * element is at d.leftblock[leftindex] and its last element is at
24 * d.rightblock[rightindex]; note that, unlike as for Python slice
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000025 * indices, these indices are inclusive on both ends. By being inclusive
Thomas Wouters0e3f5912006-08-11 14:57:12 +000026 * on both ends, algorithms for left and right operations become
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000027 * symmetrical which simplifies the design.
Thomas Wouters0e3f5912006-08-11 14:57:12 +000028 *
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000029 * The list of blocks is never empty, so d.leftblock and d.rightblock
30 * are never equal to NULL.
31 *
32 * The indices, d.leftindex and d.rightindex are always in the range
33 * 0 <= index < BLOCKLEN.
Raymond Hettinger4ca4c7c2004-10-01 15:14:39 +000034 * Their exact relationship is:
35 * (d.leftindex + d.len - 1) % BLOCKLEN == d.rightindex.
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000036 *
37 * Empty deques have d.len == 0; d.leftblock==d.rightblock;
38 * d.leftindex == CENTER+1; and d.rightindex == CENTER.
39 * Checking for d.len == 0 is the intended way to see whether d is empty.
40 *
Thomas Wouters0e3f5912006-08-11 14:57:12 +000041 * Whenever d.leftblock == d.rightblock,
Raymond Hettinger4ca4c7c2004-10-01 15:14:39 +000042 * d.leftindex + d.len - 1 == d.rightindex.
Thomas Wouters0e3f5912006-08-11 14:57:12 +000043 *
Raymond Hettinger4ca4c7c2004-10-01 15:14:39 +000044 * However, when d.leftblock != d.rightblock, d.leftindex and d.rightindex
Thomas Wouters0e3f5912006-08-11 14:57:12 +000045 * become indices into distinct blocks and either may be larger than the
Raymond Hettinger4ca4c7c2004-10-01 15:14:39 +000046 * other.
Tim Petersd8768d32004-10-01 01:32:53 +000047 */
48
Raymond Hettinger756b3f32004-01-29 06:37:52 +000049typedef struct BLOCK {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000050 struct BLOCK *leftlink;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000051 PyObject *data[BLOCKLEN];
Raymond Hettinger20b0f872013-06-23 15:44:33 -070052 struct BLOCK *rightlink;
Raymond Hettinger756b3f32004-01-29 06:37:52 +000053} block;
54
Guido van Rossum58da9312007-11-10 23:39:45 +000055#define MAXFREEBLOCKS 10
Benjamin Petersond6313712008-07-31 16:23:04 +000056static Py_ssize_t numfreeblocks = 0;
Guido van Rossum58da9312007-11-10 23:39:45 +000057static block *freeblocks[MAXFREEBLOCKS];
58
Tim Peters6f853562004-10-01 01:04:50 +000059static block *
Benjamin Petersond6313712008-07-31 16:23:04 +000060newblock(block *leftlink, block *rightlink, Py_ssize_t len) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000061 block *b;
Raymond Hettinger20b0f872013-06-23 15:44:33 -070062 /* To prevent len from overflowing PY_SSIZE_T_MAX, we refuse to
63 * allocate new blocks if the current len is nearing overflow. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000064 if (len >= PY_SSIZE_T_MAX - 2*BLOCKLEN) {
65 PyErr_SetString(PyExc_OverflowError,
66 "cannot add more blocks to the deque");
67 return NULL;
68 }
69 if (numfreeblocks) {
Raymond Hettinger59cf23a2013-02-07 00:57:19 -050070 numfreeblocks--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000071 b = freeblocks[numfreeblocks];
72 } else {
73 b = PyMem_Malloc(sizeof(block));
74 if (b == NULL) {
75 PyErr_NoMemory();
76 return NULL;
77 }
78 }
79 b->leftlink = leftlink;
80 b->rightlink = rightlink;
81 return b;
Raymond Hettinger756b3f32004-01-29 06:37:52 +000082}
83
Martin v. Löwis59683e82008-06-13 07:50:45 +000084static void
Guido van Rossum58da9312007-11-10 23:39:45 +000085freeblock(block *b)
86{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000087 if (numfreeblocks < MAXFREEBLOCKS) {
88 freeblocks[numfreeblocks] = b;
89 numfreeblocks++;
90 } else {
91 PyMem_Free(b);
92 }
Guido van Rossum58da9312007-11-10 23:39:45 +000093}
94
Raymond Hettinger756b3f32004-01-29 06:37:52 +000095typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000096 PyObject_HEAD
97 block *leftblock;
98 block *rightblock;
99 Py_ssize_t leftindex; /* in range(BLOCKLEN) */
100 Py_ssize_t rightindex; /* in range(BLOCKLEN) */
101 Py_ssize_t len;
102 Py_ssize_t maxlen;
103 long state; /* incremented whenever the indices move */
104 PyObject *weakreflist; /* List of weak references */
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000105} dequeobject;
106
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000107/* The deque's size limit is d.maxlen. The limit can be zero or positive.
108 * If there is no limit, then d.maxlen == -1.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000109 *
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000110 * After an item is added to a deque, we check to see if the size has grown past
111 * the limit. If it has, we get the size back down to the limit by popping an
112 * item off of the opposite end. The methods that can trigger this are append(),
113 * appendleft(), extend(), and extendleft().
114 */
115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000116#define TRIM(d, popfunction) \
117 if (d->maxlen != -1 && d->len > d->maxlen) { \
118 PyObject *rv = popfunction(d, NULL); \
119 assert(rv != NULL && d->len <= d->maxlen); \
120 Py_DECREF(rv); \
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000121 }
122
Neal Norwitz87f10132004-02-29 15:40:53 +0000123static PyTypeObject deque_type;
Raymond Hettinger738ec902004-02-29 02:15:56 +0000124
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000125static PyObject *
126deque_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
127{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000128 dequeobject *deque;
129 block *b;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000131 /* create dequeobject structure */
132 deque = (dequeobject *)type->tp_alloc(type, 0);
133 if (deque == NULL)
134 return NULL;
Tim Peters1065f752004-10-01 01:03:29 +0000135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000136 b = newblock(NULL, NULL, 0);
137 if (b == NULL) {
138 Py_DECREF(deque);
139 return NULL;
140 }
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000142 assert(BLOCKLEN >= 2);
143 deque->leftblock = b;
144 deque->rightblock = b;
145 deque->leftindex = CENTER + 1;
146 deque->rightindex = CENTER;
147 deque->len = 0;
148 deque->state = 0;
149 deque->weakreflist = NULL;
150 deque->maxlen = -1;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000152 return (PyObject *)deque;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000153}
154
155static PyObject *
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000156deque_pop(dequeobject *deque, PyObject *unused)
157{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000158 PyObject *item;
159 block *prevblock;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000161 if (deque->len == 0) {
162 PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
163 return NULL;
164 }
165 item = deque->rightblock->data[deque->rightindex];
166 deque->rightindex--;
167 deque->len--;
168 deque->state++;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000169
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000170 if (deque->rightindex == -1) {
171 if (deque->len == 0) {
172 assert(deque->leftblock == deque->rightblock);
173 assert(deque->leftindex == deque->rightindex+1);
174 /* re-center instead of freeing a block */
175 deque->leftindex = CENTER + 1;
176 deque->rightindex = CENTER;
177 } else {
178 prevblock = deque->rightblock->leftlink;
179 assert(deque->leftblock != deque->rightblock);
180 freeblock(deque->rightblock);
181 prevblock->rightlink = NULL;
182 deque->rightblock = prevblock;
183 deque->rightindex = BLOCKLEN - 1;
184 }
185 }
186 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000187}
188
189PyDoc_STRVAR(pop_doc, "Remove and return the rightmost element.");
190
191static PyObject *
192deque_popleft(dequeobject *deque, PyObject *unused)
193{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000194 PyObject *item;
195 block *prevblock;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000196
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000197 if (deque->len == 0) {
198 PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
199 return NULL;
200 }
201 assert(deque->leftblock != NULL);
202 item = deque->leftblock->data[deque->leftindex];
203 deque->leftindex++;
204 deque->len--;
205 deque->state++;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000206
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000207 if (deque->leftindex == BLOCKLEN) {
208 if (deque->len == 0) {
209 assert(deque->leftblock == deque->rightblock);
210 assert(deque->leftindex == deque->rightindex+1);
211 /* re-center instead of freeing a block */
212 deque->leftindex = CENTER + 1;
213 deque->rightindex = CENTER;
214 } else {
215 assert(deque->leftblock != deque->rightblock);
216 prevblock = deque->leftblock->rightlink;
217 freeblock(deque->leftblock);
218 assert(prevblock != NULL);
219 prevblock->leftlink = NULL;
220 deque->leftblock = prevblock;
221 deque->leftindex = 0;
222 }
223 }
224 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000225}
226
227PyDoc_STRVAR(popleft_doc, "Remove and return the leftmost element.");
228
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000229static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000230deque_append(dequeobject *deque, PyObject *item)
231{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000232 deque->state++;
233 if (deque->rightindex == BLOCKLEN-1) {
234 block *b = newblock(deque->rightblock, NULL, deque->len);
235 if (b == NULL)
236 return NULL;
237 assert(deque->rightblock->rightlink == NULL);
238 deque->rightblock->rightlink = b;
239 deque->rightblock = b;
240 deque->rightindex = -1;
241 }
242 Py_INCREF(item);
243 deque->len++;
244 deque->rightindex++;
245 deque->rightblock->data[deque->rightindex] = item;
246 TRIM(deque, deque_popleft);
247 Py_RETURN_NONE;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000248}
249
250PyDoc_STRVAR(append_doc, "Add an element to the right side of the deque.");
251
252static PyObject *
253deque_appendleft(dequeobject *deque, PyObject *item)
254{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000255 deque->state++;
256 if (deque->leftindex == 0) {
257 block *b = newblock(NULL, deque->leftblock, deque->len);
258 if (b == NULL)
259 return NULL;
260 assert(deque->leftblock->leftlink == NULL);
261 deque->leftblock->leftlink = b;
262 deque->leftblock = b;
263 deque->leftindex = BLOCKLEN;
264 }
265 Py_INCREF(item);
266 deque->len++;
267 deque->leftindex--;
268 deque->leftblock->data[deque->leftindex] = item;
269 TRIM(deque, deque_pop);
270 Py_RETURN_NONE;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000271}
272
273PyDoc_STRVAR(appendleft_doc, "Add an element to the left side of the deque.");
274
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000276/* Run an iterator to exhaustion. Shortcut for
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000277 the extend/extendleft methods when maxlen == 0. */
278static PyObject*
279consume_iterator(PyObject *it)
280{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000281 PyObject *item;
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000283 while ((item = PyIter_Next(it)) != NULL) {
284 Py_DECREF(item);
285 }
286 Py_DECREF(it);
287 if (PyErr_Occurred())
288 return NULL;
289 Py_RETURN_NONE;
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000290}
291
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000292static PyObject *
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000293deque_extend(dequeobject *deque, PyObject *iterable)
294{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000295 PyObject *it, *item;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000297 /* Handle case where id(deque) == id(iterable) */
298 if ((PyObject *)deque == iterable) {
299 PyObject *result;
300 PyObject *s = PySequence_List(iterable);
301 if (s == NULL)
302 return NULL;
303 result = deque_extend(deque, s);
304 Py_DECREF(s);
305 return result;
306 }
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000308 it = PyObject_GetIter(iterable);
309 if (it == NULL)
310 return NULL;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000312 if (deque->maxlen == 0)
313 return consume_iterator(it);
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000315 while ((item = PyIter_Next(it)) != NULL) {
316 deque->state++;
317 if (deque->rightindex == BLOCKLEN-1) {
318 block *b = newblock(deque->rightblock, NULL,
319 deque->len);
320 if (b == NULL) {
321 Py_DECREF(item);
322 Py_DECREF(it);
323 return NULL;
324 }
325 assert(deque->rightblock->rightlink == NULL);
326 deque->rightblock->rightlink = b;
327 deque->rightblock = b;
328 deque->rightindex = -1;
329 }
330 deque->len++;
331 deque->rightindex++;
332 deque->rightblock->data[deque->rightindex] = item;
333 TRIM(deque, deque_popleft);
334 }
335 Py_DECREF(it);
336 if (PyErr_Occurred())
337 return NULL;
338 Py_RETURN_NONE;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000339}
340
Tim Peters1065f752004-10-01 01:03:29 +0000341PyDoc_STRVAR(extend_doc,
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000342"Extend the right side of the deque with elements from the iterable");
343
344static PyObject *
345deque_extendleft(dequeobject *deque, PyObject *iterable)
346{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000347 PyObject *it, *item;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000349 /* Handle case where id(deque) == id(iterable) */
350 if ((PyObject *)deque == iterable) {
351 PyObject *result;
352 PyObject *s = PySequence_List(iterable);
353 if (s == NULL)
354 return NULL;
355 result = deque_extendleft(deque, s);
356 Py_DECREF(s);
357 return result;
358 }
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000360 it = PyObject_GetIter(iterable);
361 if (it == NULL)
362 return NULL;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000364 if (deque->maxlen == 0)
365 return consume_iterator(it);
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000367 while ((item = PyIter_Next(it)) != NULL) {
368 deque->state++;
369 if (deque->leftindex == 0) {
370 block *b = newblock(NULL, deque->leftblock,
371 deque->len);
372 if (b == NULL) {
373 Py_DECREF(item);
374 Py_DECREF(it);
375 return NULL;
376 }
377 assert(deque->leftblock->leftlink == NULL);
378 deque->leftblock->leftlink = b;
379 deque->leftblock = b;
380 deque->leftindex = BLOCKLEN;
381 }
382 deque->len++;
383 deque->leftindex--;
384 deque->leftblock->data[deque->leftindex] = item;
385 TRIM(deque, deque_pop);
386 }
387 Py_DECREF(it);
388 if (PyErr_Occurred())
389 return NULL;
390 Py_RETURN_NONE;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000391}
392
Tim Peters1065f752004-10-01 01:03:29 +0000393PyDoc_STRVAR(extendleft_doc,
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000394"Extend the left side of the deque with elements from the iterable");
395
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000396static PyObject *
397deque_inplace_concat(dequeobject *deque, PyObject *other)
398{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000399 PyObject *result;
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000401 result = deque_extend(deque, other);
402 if (result == NULL)
403 return result;
404 Py_DECREF(result);
405 Py_INCREF(deque);
406 return (PyObject *)deque;
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000407}
408
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000409static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000410_deque_rotate(dequeobject *deque, Py_ssize_t n)
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000411{
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700412 block *leftblock = deque->leftblock;
413 block *rightblock = deque->rightblock;
414 Py_ssize_t leftindex = deque->leftindex;
415 Py_ssize_t rightindex = deque->rightindex;
416 Py_ssize_t len=deque->len, halflen=len>>1;
417 int rv = 0;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000418
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800419 if (len <= 1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 return 0;
421 if (n > halflen || n < -halflen) {
422 n %= len;
423 if (n > halflen)
424 n -= len;
425 else if (n < -halflen)
426 n += len;
427 }
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500428 assert(len > 1);
Raymond Hettingera4409c12013-02-04 00:08:12 -0500429 assert(-halflen <= n && n <= halflen);
Raymond Hettinger231ee4d2013-02-02 11:24:43 -0800430
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800431 deque->state++;
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500432 while (n > 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700433 if (leftindex == 0) {
434 block *b = newblock(NULL, leftblock, len);
435 if (b == NULL) {
436 rv = -1;
437 goto done;
438 }
439 assert(leftblock->leftlink == NULL);
440 leftblock->leftlink = b;
441 leftblock = b;
442 leftindex = BLOCKLEN;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800443 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700444 assert(leftindex > 0);
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800445
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700446 {
447 PyObject **src, **dest;
448 Py_ssize_t m = n;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800449
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700450 if (m > rightindex + 1)
451 m = rightindex + 1;
452 if (m > leftindex)
453 m = leftindex;
454 assert (m > 0 && m <= len);
455 src = &rightblock->data[rightindex];
456 dest = &leftblock->data[leftindex - 1];
457 rightindex -= m;
458 leftindex -= m;
459 n -= m;
460 while (m--)
461 *(dest--) = *(src--);
462 }
463
464 if (rightindex == -1) {
465 block *prevblock = rightblock->leftlink;
466 assert(rightblock != NULL);
467 assert(leftblock != rightblock);
468 freeblock(rightblock);
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800469 prevblock->rightlink = NULL;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700470 rightblock = prevblock;
471 rightindex = BLOCKLEN - 1;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800472 }
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800473 }
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500474 while (n < 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700475 if (rightindex == BLOCKLEN - 1) {
476 block *b = newblock(rightblock, NULL, len);
477 if (b == NULL) {
478 rv = -1;
479 goto done;
480 }
481 assert(rightblock->rightlink == NULL);
482 rightblock->rightlink = b;
483 rightblock = b;
484 rightindex = -1;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800485 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700486 assert (rightindex < BLOCKLEN - 1);
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800487
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700488 {
489 PyObject **src, **dest;
490 Py_ssize_t m = -n;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800491
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700492 if (m > BLOCKLEN - leftindex)
493 m = BLOCKLEN - leftindex;
494 if (m > BLOCKLEN - 1 - rightindex)
495 m = BLOCKLEN - 1 - rightindex;
496 assert (m > 0 && m <= len);
497 src = &leftblock->data[leftindex];
498 dest = &rightblock->data[rightindex + 1];
499 leftindex += m;
500 rightindex += m;
501 n += m;
502 while (m--)
503 *(dest++) = *(src++);
504 }
505
506 if (leftindex == BLOCKLEN) {
507 block *nextblock = leftblock->rightlink;
508 assert(leftblock != rightblock);
509 freeblock(leftblock);
Raymond Hettinger59cf23a2013-02-07 00:57:19 -0500510 assert(nextblock != NULL);
511 nextblock->leftlink = NULL;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700512 leftblock = nextblock;
513 leftindex = 0;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800514 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000515 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700516done:
517 deque->leftblock = leftblock;
518 deque->rightblock = rightblock;
519 deque->leftindex = leftindex;
520 deque->rightindex = rightindex;
521
522 return rv;
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000523}
524
525static PyObject *
526deque_rotate(dequeobject *deque, PyObject *args)
527{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000528 Py_ssize_t n=1;
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 if (!PyArg_ParseTuple(args, "|n:rotate", &n))
531 return NULL;
532 if (_deque_rotate(deque, n) == 0)
533 Py_RETURN_NONE;
534 return NULL;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000535}
536
Tim Peters1065f752004-10-01 01:03:29 +0000537PyDoc_STRVAR(rotate_doc,
Raymond Hettingeree33b272004-02-08 04:05:26 +0000538"Rotate the deque n steps to the right (default n=1). If n is negative, rotates left.");
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000539
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000540static PyObject *
541deque_reverse(dequeobject *deque, PyObject *unused)
542{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000543 block *leftblock = deque->leftblock;
544 block *rightblock = deque->rightblock;
545 Py_ssize_t leftindex = deque->leftindex;
546 Py_ssize_t rightindex = deque->rightindex;
547 Py_ssize_t n = (deque->len)/2;
548 Py_ssize_t i;
549 PyObject *tmp;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000550
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 for (i=0 ; i<n ; i++) {
552 /* Validate that pointers haven't met in the middle */
553 assert(leftblock != rightblock || leftindex < rightindex);
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 /* Swap */
556 tmp = leftblock->data[leftindex];
557 leftblock->data[leftindex] = rightblock->data[rightindex];
558 rightblock->data[rightindex] = tmp;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 /* Advance left block/index pair */
561 leftindex++;
562 if (leftindex == BLOCKLEN) {
Raymond Hettinger512d2cc2011-01-25 21:32:39 +0000563 if (leftblock->rightlink == NULL)
564 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000565 leftblock = leftblock->rightlink;
566 leftindex = 0;
567 }
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000568
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000569 /* Step backwards with the right block/index pair */
570 rightindex--;
571 if (rightindex == -1) {
Raymond Hettinger512d2cc2011-01-25 21:32:39 +0000572 if (rightblock->leftlink == NULL)
573 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000574 rightblock = rightblock->leftlink;
575 rightindex = BLOCKLEN - 1;
576 }
577 }
578 Py_RETURN_NONE;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000579}
580
581PyDoc_STRVAR(reverse_doc,
582"D.reverse() -- reverse *IN PLACE*");
583
Raymond Hettinger44459de2010-04-03 23:20:46 +0000584static PyObject *
585deque_count(dequeobject *deque, PyObject *v)
586{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000587 block *leftblock = deque->leftblock;
588 Py_ssize_t leftindex = deque->leftindex;
Raymond Hettinger512d2cc2011-01-25 21:32:39 +0000589 Py_ssize_t n = deque->len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000590 Py_ssize_t i;
591 Py_ssize_t count = 0;
592 PyObject *item;
593 long start_state = deque->state;
594 int cmp;
Raymond Hettinger44459de2010-04-03 23:20:46 +0000595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 for (i=0 ; i<n ; i++) {
597 item = leftblock->data[leftindex];
598 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
599 if (cmp > 0)
600 count++;
601 else if (cmp < 0)
602 return NULL;
Raymond Hettinger44459de2010-04-03 23:20:46 +0000603
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000604 if (start_state != deque->state) {
605 PyErr_SetString(PyExc_RuntimeError,
606 "deque mutated during iteration");
607 return NULL;
608 }
Raymond Hettinger44459de2010-04-03 23:20:46 +0000609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610 /* Advance left block/index pair */
611 leftindex++;
612 if (leftindex == BLOCKLEN) {
Raymond Hettinger512d2cc2011-01-25 21:32:39 +0000613 if (leftblock->rightlink == NULL) /* can occur when i==n-1 */
614 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 leftblock = leftblock->rightlink;
616 leftindex = 0;
617 }
618 }
619 return PyLong_FromSsize_t(count);
Raymond Hettinger44459de2010-04-03 23:20:46 +0000620}
621
622PyDoc_STRVAR(count_doc,
623"D.count(value) -> integer -- return number of occurrences of value");
624
Martin v. Löwis18e16552006-02-15 17:27:45 +0000625static Py_ssize_t
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000626deque_len(dequeobject *deque)
627{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000628 return deque->len;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000629}
630
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000631static PyObject *
632deque_remove(dequeobject *deque, PyObject *value)
633{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 Py_ssize_t i, n=deque->len;
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 for (i=0 ; i<n ; i++) {
637 PyObject *item = deque->leftblock->data[deque->leftindex];
638 int cmp = PyObject_RichCompareBool(item, value, Py_EQ);
Raymond Hettingerd73202c2005-03-19 00:00:51 +0000639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 if (deque->len != n) {
641 PyErr_SetString(PyExc_IndexError,
642 "deque mutated during remove().");
643 return NULL;
644 }
645 if (cmp > 0) {
646 PyObject *tgt = deque_popleft(deque, NULL);
647 assert (tgt != NULL);
648 Py_DECREF(tgt);
649 if (_deque_rotate(deque, i) == -1)
650 return NULL;
651 Py_RETURN_NONE;
652 }
653 else if (cmp < 0) {
654 _deque_rotate(deque, i);
655 return NULL;
656 }
657 _deque_rotate(deque, -1);
658 }
659 PyErr_SetString(PyExc_ValueError, "deque.remove(x): x not in deque");
660 return NULL;
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000661}
662
663PyDoc_STRVAR(remove_doc,
664"D.remove(value) -- remove first occurrence of value.");
665
Benjamin Peterson0e5c48a2013-01-12 21:22:18 -0500666static void
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000667deque_clear(dequeobject *deque)
668{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000669 PyObject *item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000670
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000671 while (deque->len) {
672 item = deque_pop(deque, NULL);
673 assert (item != NULL);
674 Py_DECREF(item);
675 }
676 assert(deque->leftblock == deque->rightblock &&
677 deque->leftindex - 1 == deque->rightindex &&
678 deque->len == 0);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000679}
680
681static PyObject *
Benjamin Petersond6313712008-07-31 16:23:04 +0000682deque_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000683{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000684 block *b;
685 PyObject *item;
686 Py_ssize_t n, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000687
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000688 if (i < 0 || i >= deque->len) {
689 PyErr_SetString(PyExc_IndexError,
690 "deque index out of range");
691 return NULL;
692 }
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000693
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000694 if (i == 0) {
695 i = deque->leftindex;
696 b = deque->leftblock;
697 } else if (i == deque->len - 1) {
698 i = deque->rightindex;
699 b = deque->rightblock;
700 } else {
701 i += deque->leftindex;
702 n = i / BLOCKLEN;
703 i %= BLOCKLEN;
704 if (index < (deque->len >> 1)) {
705 b = deque->leftblock;
706 while (n--)
707 b = b->rightlink;
708 } else {
709 n = (deque->leftindex + deque->len - 1) / BLOCKLEN - n;
710 b = deque->rightblock;
711 while (n--)
712 b = b->leftlink;
713 }
714 }
715 item = b->data[i];
716 Py_INCREF(item);
717 return item;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000718}
719
Raymond Hettinger616f4f62004-06-26 04:42:06 +0000720/* delitem() implemented in terms of rotate for simplicity and reasonable
721 performance near the end points. If for some reason this method becomes
Tim Peters1065f752004-10-01 01:03:29 +0000722 popular, it is not hard to re-implement this using direct data movement
Raymond Hettinger616f4f62004-06-26 04:42:06 +0000723 (similar to code in list slice assignment) and achieve a two or threefold
724 performance boost.
725*/
726
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000727static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000728deque_del_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000729{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000730 PyObject *item;
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000731
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 assert (i >= 0 && i < deque->len);
733 if (_deque_rotate(deque, -i) == -1)
734 return -1;
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 item = deque_popleft(deque, NULL);
737 assert (item != NULL);
738 Py_DECREF(item);
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000740 return _deque_rotate(deque, i);
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000741}
742
743static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000744deque_ass_item(dequeobject *deque, Py_ssize_t i, PyObject *v)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000745{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000746 PyObject *old_value;
747 block *b;
748 Py_ssize_t n, len=deque->len, halflen=(len+1)>>1, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000749
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000750 if (i < 0 || i >= len) {
751 PyErr_SetString(PyExc_IndexError,
752 "deque index out of range");
753 return -1;
754 }
755 if (v == NULL)
756 return deque_del_item(deque, i);
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 i += deque->leftindex;
759 n = i / BLOCKLEN;
760 i %= BLOCKLEN;
761 if (index <= halflen) {
762 b = deque->leftblock;
763 while (n--)
764 b = b->rightlink;
765 } else {
766 n = (deque->leftindex + len - 1) / BLOCKLEN - n;
767 b = deque->rightblock;
768 while (n--)
769 b = b->leftlink;
770 }
771 Py_INCREF(v);
772 old_value = b->data[i];
773 b->data[i] = v;
774 Py_DECREF(old_value);
775 return 0;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000776}
777
778static PyObject *
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000779deque_clearmethod(dequeobject *deque)
780{
Benjamin Peterson0e5c48a2013-01-12 21:22:18 -0500781 deque_clear(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 Py_RETURN_NONE;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000783}
784
785PyDoc_STRVAR(clear_doc, "Remove all elements from the deque.");
786
787static void
788deque_dealloc(dequeobject *deque)
789{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 PyObject_GC_UnTrack(deque);
791 if (deque->weakreflist != NULL)
792 PyObject_ClearWeakRefs((PyObject *) deque);
793 if (deque->leftblock != NULL) {
794 deque_clear(deque);
795 assert(deque->leftblock != NULL);
796 freeblock(deque->leftblock);
797 }
798 deque->leftblock = NULL;
799 deque->rightblock = NULL;
800 Py_TYPE(deque)->tp_free(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000801}
802
803static int
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000804deque_traverse(dequeobject *deque, visitproc visit, void *arg)
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000805{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000806 block *b;
807 PyObject *item;
808 Py_ssize_t index;
809 Py_ssize_t indexlo = deque->leftindex;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000811 for (b = deque->leftblock; b != NULL; b = b->rightlink) {
812 const Py_ssize_t indexhi = b == deque->rightblock ?
813 deque->rightindex :
814 BLOCKLEN - 1;
Tim Peters10c7e862004-10-01 02:01:04 +0000815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000816 for (index = indexlo; index <= indexhi; ++index) {
817 item = b->data[index];
818 Py_VISIT(item);
819 }
820 indexlo = 0;
821 }
822 return 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000823}
824
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000825static PyObject *
826deque_copy(PyObject *deque)
827{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000828 if (((dequeobject *)deque)->maxlen == -1)
829 return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "O", deque, NULL);
830 else
831 return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "Oi",
832 deque, ((dequeobject *)deque)->maxlen, NULL);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000833}
834
835PyDoc_STRVAR(copy_doc, "Return a shallow copy of a deque.");
836
837static PyObject *
838deque_reduce(dequeobject *deque)
839{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 PyObject *dict, *result, *aslist;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200841 _Py_IDENTIFIER(__dict__);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000842
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200843 dict = _PyObject_GetAttrId((PyObject *)deque, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000844 if (dict == NULL)
845 PyErr_Clear();
846 aslist = PySequence_List((PyObject *)deque);
847 if (aslist == NULL) {
848 Py_XDECREF(dict);
849 return NULL;
850 }
851 if (dict == NULL) {
852 if (deque->maxlen == -1)
853 result = Py_BuildValue("O(O)", Py_TYPE(deque), aslist);
854 else
855 result = Py_BuildValue("O(On)", Py_TYPE(deque), aslist, deque->maxlen);
856 } else {
857 if (deque->maxlen == -1)
858 result = Py_BuildValue("O(OO)O", Py_TYPE(deque), aslist, Py_None, dict);
859 else
860 result = Py_BuildValue("O(On)O", Py_TYPE(deque), aslist, deque->maxlen, dict);
861 }
862 Py_XDECREF(dict);
863 Py_DECREF(aslist);
864 return result;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000865}
866
867PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
868
869static PyObject *
870deque_repr(PyObject *deque)
871{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000872 PyObject *aslist, *result;
873 int i;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000874
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000875 i = Py_ReprEnter(deque);
876 if (i != 0) {
877 if (i < 0)
878 return NULL;
879 return PyUnicode_FromString("[...]");
880 }
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 aslist = PySequence_List(deque);
883 if (aslist == NULL) {
884 Py_ReprLeave(deque);
885 return NULL;
886 }
887 if (((dequeobject *)deque)->maxlen != -1)
Benjamin Petersona786b022008-08-25 21:05:21 +0000888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 result = PyUnicode_FromFormat("deque(%R, maxlen=%zd)",
890 aslist, ((dequeobject *)deque)->maxlen);
891 else
892 result = PyUnicode_FromFormat("deque(%R)", aslist);
893 Py_DECREF(aslist);
894 Py_ReprLeave(deque);
895 return result;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000896}
897
Raymond Hettinger738ec902004-02-29 02:15:56 +0000898static PyObject *
899deque_richcompare(PyObject *v, PyObject *w, int op)
900{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000901 PyObject *it1=NULL, *it2=NULL, *x, *y;
902 Py_ssize_t vs, ws;
903 int b, cmp=-1;
Raymond Hettinger738ec902004-02-29 02:15:56 +0000904
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000905 if (!PyObject_TypeCheck(v, &deque_type) ||
906 !PyObject_TypeCheck(w, &deque_type)) {
Brian Curtindfc80e32011-08-10 20:28:54 -0500907 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000908 }
Raymond Hettinger738ec902004-02-29 02:15:56 +0000909
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 /* Shortcuts */
911 vs = ((dequeobject *)v)->len;
912 ws = ((dequeobject *)w)->len;
913 if (op == Py_EQ) {
914 if (v == w)
915 Py_RETURN_TRUE;
916 if (vs != ws)
917 Py_RETURN_FALSE;
918 }
919 if (op == Py_NE) {
920 if (v == w)
921 Py_RETURN_FALSE;
922 if (vs != ws)
923 Py_RETURN_TRUE;
924 }
Raymond Hettinger738ec902004-02-29 02:15:56 +0000925
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 /* Search for the first index where items are different */
927 it1 = PyObject_GetIter(v);
928 if (it1 == NULL)
929 goto done;
930 it2 = PyObject_GetIter(w);
931 if (it2 == NULL)
932 goto done;
933 for (;;) {
934 x = PyIter_Next(it1);
935 if (x == NULL && PyErr_Occurred())
936 goto done;
937 y = PyIter_Next(it2);
938 if (x == NULL || y == NULL)
939 break;
940 b = PyObject_RichCompareBool(x, y, Py_EQ);
941 if (b == 0) {
942 cmp = PyObject_RichCompareBool(x, y, op);
943 Py_DECREF(x);
944 Py_DECREF(y);
945 goto done;
946 }
947 Py_DECREF(x);
948 Py_DECREF(y);
949 if (b == -1)
950 goto done;
951 }
952 /* We reached the end of one deque or both */
953 Py_XDECREF(x);
954 Py_XDECREF(y);
955 if (PyErr_Occurred())
956 goto done;
957 switch (op) {
958 case Py_LT: cmp = y != NULL; break; /* if w was longer */
959 case Py_LE: cmp = x == NULL; break; /* if v was not longer */
960 case Py_EQ: cmp = x == y; break; /* if we reached the end of both */
961 case Py_NE: cmp = x != y; break; /* if one deque continues */
962 case Py_GT: cmp = x != NULL; break; /* if v was longer */
963 case Py_GE: cmp = y == NULL; break; /* if w was not longer */
964 }
Tim Peters1065f752004-10-01 01:03:29 +0000965
Raymond Hettinger738ec902004-02-29 02:15:56 +0000966done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000967 Py_XDECREF(it1);
968 Py_XDECREF(it2);
969 if (cmp == 1)
970 Py_RETURN_TRUE;
971 if (cmp == 0)
972 Py_RETURN_FALSE;
973 return NULL;
Raymond Hettinger738ec902004-02-29 02:15:56 +0000974}
975
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000976static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000977deque_init(dequeobject *deque, PyObject *args, PyObject *kwdargs)
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000978{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 PyObject *iterable = NULL;
980 PyObject *maxlenobj = NULL;
981 Py_ssize_t maxlen = -1;
982 char *kwlist[] = {"iterable", "maxlen", 0};
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000983
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000984 if (!PyArg_ParseTupleAndKeywords(args, kwdargs, "|OO:deque", kwlist, &iterable, &maxlenobj))
985 return -1;
986 if (maxlenobj != NULL && maxlenobj != Py_None) {
987 maxlen = PyLong_AsSsize_t(maxlenobj);
988 if (maxlen == -1 && PyErr_Occurred())
989 return -1;
990 if (maxlen < 0) {
991 PyErr_SetString(PyExc_ValueError, "maxlen must be non-negative");
992 return -1;
993 }
994 }
995 deque->maxlen = maxlen;
996 deque_clear(deque);
997 if (iterable != NULL) {
998 PyObject *rv = deque_extend(deque, iterable);
999 if (rv == NULL)
1000 return -1;
1001 Py_DECREF(rv);
1002 }
1003 return 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001004}
1005
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001006static PyObject *
Jesus Cea16e2fca2012-08-03 14:49:42 +02001007deque_sizeof(dequeobject *deque, void *unused)
1008{
1009 Py_ssize_t res;
1010 Py_ssize_t blocks;
1011
1012 res = sizeof(dequeobject);
1013 blocks = (deque->leftindex + deque->len + BLOCKLEN - 1) / BLOCKLEN;
1014 assert(deque->leftindex + deque->len - 1 ==
1015 (blocks - 1) * BLOCKLEN + deque->rightindex);
1016 res += blocks * sizeof(block);
1017 return PyLong_FromSsize_t(res);
1018}
1019
1020PyDoc_STRVAR(sizeof_doc,
1021"D.__sizeof__() -- size of D in memory, in bytes");
1022
1023static PyObject *
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001024deque_get_maxlen(dequeobject *deque)
1025{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001026 if (deque->maxlen == -1)
1027 Py_RETURN_NONE;
1028 return PyLong_FromSsize_t(deque->maxlen);
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001029}
1030
1031static PyGetSetDef deque_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001032 {"maxlen", (getter)deque_get_maxlen, (setter)NULL,
1033 "maximum size of a deque or None if unbounded"},
1034 {0}
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001035};
1036
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001037static PySequenceMethods deque_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 (lenfunc)deque_len, /* sq_length */
1039 0, /* sq_concat */
1040 0, /* sq_repeat */
1041 (ssizeargfunc)deque_item, /* sq_item */
1042 0, /* sq_slice */
1043 (ssizeobjargproc)deque_ass_item, /* sq_ass_item */
1044 0, /* sq_ass_slice */
1045 0, /* sq_contains */
1046 (binaryfunc)deque_inplace_concat, /* sq_inplace_concat */
1047 0, /* sq_inplace_repeat */
Raymond Hettinger3f9afd82009-12-10 03:03:02 +00001048
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001049};
1050
1051/* deque object ********************************************************/
1052
1053static PyObject *deque_iter(dequeobject *deque);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001054static PyObject *deque_reviter(dequeobject *deque);
Tim Peters1065f752004-10-01 01:03:29 +00001055PyDoc_STRVAR(reversed_doc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001056 "D.__reversed__() -- return a reverse iterator over the deque");
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001057
1058static PyMethodDef deque_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001059 {"append", (PyCFunction)deque_append,
1060 METH_O, append_doc},
1061 {"appendleft", (PyCFunction)deque_appendleft,
1062 METH_O, appendleft_doc},
1063 {"clear", (PyCFunction)deque_clearmethod,
1064 METH_NOARGS, clear_doc},
1065 {"__copy__", (PyCFunction)deque_copy,
1066 METH_NOARGS, copy_doc},
1067 {"count", (PyCFunction)deque_count,
1068 METH_O, count_doc},
1069 {"extend", (PyCFunction)deque_extend,
1070 METH_O, extend_doc},
1071 {"extendleft", (PyCFunction)deque_extendleft,
1072 METH_O, extendleft_doc},
1073 {"pop", (PyCFunction)deque_pop,
1074 METH_NOARGS, pop_doc},
1075 {"popleft", (PyCFunction)deque_popleft,
1076 METH_NOARGS, popleft_doc},
1077 {"__reduce__", (PyCFunction)deque_reduce,
1078 METH_NOARGS, reduce_doc},
1079 {"remove", (PyCFunction)deque_remove,
1080 METH_O, remove_doc},
1081 {"__reversed__", (PyCFunction)deque_reviter,
1082 METH_NOARGS, reversed_doc},
1083 {"reverse", (PyCFunction)deque_reverse,
1084 METH_NOARGS, reverse_doc},
1085 {"rotate", (PyCFunction)deque_rotate,
Jesus Cea16e2fca2012-08-03 14:49:42 +02001086 METH_VARARGS, rotate_doc},
1087 {"__sizeof__", (PyCFunction)deque_sizeof,
1088 METH_NOARGS, sizeof_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001089 {NULL, NULL} /* sentinel */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001090};
1091
1092PyDoc_STRVAR(deque_doc,
Andrew Svetlov6a5c7c32012-10-31 11:50:40 +02001093"deque([iterable[, maxlen]]) --> deque object\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001094\n\
Raymond Hettinger49747052011-03-29 17:36:31 -07001095Build an ordered collection with optimized access from its endpoints.");
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001096
Neal Norwitz87f10132004-02-29 15:40:53 +00001097static PyTypeObject deque_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098 PyVarObject_HEAD_INIT(NULL, 0)
1099 "collections.deque", /* tp_name */
1100 sizeof(dequeobject), /* tp_basicsize */
1101 0, /* tp_itemsize */
1102 /* methods */
1103 (destructor)deque_dealloc, /* tp_dealloc */
1104 0, /* tp_print */
1105 0, /* tp_getattr */
1106 0, /* tp_setattr */
1107 0, /* tp_reserved */
1108 deque_repr, /* tp_repr */
1109 0, /* tp_as_number */
1110 &deque_as_sequence, /* tp_as_sequence */
1111 0, /* tp_as_mapping */
Georg Brandlf038b322010-10-18 07:35:09 +00001112 PyObject_HashNotImplemented, /* tp_hash */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001113 0, /* tp_call */
1114 0, /* tp_str */
1115 PyObject_GenericGetAttr, /* tp_getattro */
1116 0, /* tp_setattro */
1117 0, /* tp_as_buffer */
1118 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
Georg Brandlf038b322010-10-18 07:35:09 +00001119 /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001120 deque_doc, /* tp_doc */
1121 (traverseproc)deque_traverse, /* tp_traverse */
1122 (inquiry)deque_clear, /* tp_clear */
1123 (richcmpfunc)deque_richcompare, /* tp_richcompare */
Georg Brandlf038b322010-10-18 07:35:09 +00001124 offsetof(dequeobject, weakreflist), /* tp_weaklistoffset*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001125 (getiterfunc)deque_iter, /* tp_iter */
1126 0, /* tp_iternext */
1127 deque_methods, /* tp_methods */
1128 0, /* tp_members */
Georg Brandlf038b322010-10-18 07:35:09 +00001129 deque_getset, /* tp_getset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001130 0, /* tp_base */
1131 0, /* tp_dict */
1132 0, /* tp_descr_get */
1133 0, /* tp_descr_set */
1134 0, /* tp_dictoffset */
1135 (initproc)deque_init, /* tp_init */
1136 PyType_GenericAlloc, /* tp_alloc */
1137 deque_new, /* tp_new */
1138 PyObject_GC_Del, /* tp_free */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001139};
1140
1141/*********************** Deque Iterator **************************/
1142
1143typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001144 PyObject_HEAD
1145 Py_ssize_t index;
1146 block *b;
1147 dequeobject *deque;
1148 long state; /* state when the iterator is created */
1149 Py_ssize_t counter; /* number of items remaining for iteration */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001150} dequeiterobject;
1151
Martin v. Löwis59683e82008-06-13 07:50:45 +00001152static PyTypeObject dequeiter_type;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001153
1154static PyObject *
1155deque_iter(dequeobject *deque)
1156{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001157 dequeiterobject *it;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001158
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001159 it = PyObject_GC_New(dequeiterobject, &dequeiter_type);
1160 if (it == NULL)
1161 return NULL;
1162 it->b = deque->leftblock;
1163 it->index = deque->leftindex;
1164 Py_INCREF(deque);
1165 it->deque = deque;
1166 it->state = deque->state;
1167 it->counter = deque->len;
1168 PyObject_GC_Track(it);
1169 return (PyObject *)it;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001170}
1171
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001172static int
1173dequeiter_traverse(dequeiterobject *dio, visitproc visit, void *arg)
1174{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001175 Py_VISIT(dio->deque);
1176 return 0;
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001177}
1178
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001179static void
1180dequeiter_dealloc(dequeiterobject *dio)
1181{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 Py_XDECREF(dio->deque);
1183 PyObject_GC_Del(dio);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001184}
1185
1186static PyObject *
1187dequeiter_next(dequeiterobject *it)
1188{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001189 PyObject *item;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001191 if (it->deque->state != it->state) {
1192 it->counter = 0;
1193 PyErr_SetString(PyExc_RuntimeError,
1194 "deque mutated during iteration");
1195 return NULL;
1196 }
1197 if (it->counter == 0)
1198 return NULL;
1199 assert (!(it->b == it->deque->rightblock &&
1200 it->index > it->deque->rightindex));
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001202 item = it->b->data[it->index];
1203 it->index++;
1204 it->counter--;
1205 if (it->index == BLOCKLEN && it->counter > 0) {
1206 assert (it->b->rightlink != NULL);
1207 it->b = it->b->rightlink;
1208 it->index = 0;
1209 }
1210 Py_INCREF(item);
1211 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001212}
1213
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001214static PyObject *
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001215dequeiter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1216{
1217 Py_ssize_t i, index=0;
1218 PyObject *deque;
1219 dequeiterobject *it;
1220 if (!PyArg_ParseTuple(args, "O!|n", &deque_type, &deque, &index))
1221 return NULL;
1222 assert(type == &dequeiter_type);
1223
1224 it = (dequeiterobject*)deque_iter((dequeobject *)deque);
1225 if (!it)
1226 return NULL;
1227 /* consume items from the queue */
1228 for(i=0; i<index; i++) {
1229 PyObject *item = dequeiter_next(it);
1230 if (item) {
1231 Py_DECREF(item);
1232 } else {
1233 if (it->counter) {
1234 Py_DECREF(it);
1235 return NULL;
1236 } else
1237 break;
1238 }
1239 }
1240 return (PyObject*)it;
1241}
1242
1243static PyObject *
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001244dequeiter_len(dequeiterobject *it)
1245{
Antoine Pitrou554f3342010-08-17 18:30:06 +00001246 return PyLong_FromSsize_t(it->counter);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001247}
1248
Armin Rigof5b3e362006-02-11 21:32:43 +00001249PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001250
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001251static PyObject *
1252dequeiter_reduce(dequeiterobject *it)
1253{
1254 return Py_BuildValue("O(On)", Py_TYPE(it), it->deque, it->deque->len - it->counter);
1255}
1256
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001257static PyMethodDef dequeiter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258 {"__length_hint__", (PyCFunction)dequeiter_len, METH_NOARGS, length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001259 {"__reduce__", (PyCFunction)dequeiter_reduce, METH_NOARGS, reduce_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001260 {NULL, NULL} /* sentinel */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001261};
1262
Martin v. Löwis59683e82008-06-13 07:50:45 +00001263static PyTypeObject dequeiter_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001264 PyVarObject_HEAD_INIT(NULL, 0)
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001265 "_collections._deque_iterator", /* tp_name */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001266 sizeof(dequeiterobject), /* tp_basicsize */
1267 0, /* tp_itemsize */
1268 /* methods */
1269 (destructor)dequeiter_dealloc, /* tp_dealloc */
1270 0, /* tp_print */
1271 0, /* tp_getattr */
1272 0, /* tp_setattr */
1273 0, /* tp_reserved */
1274 0, /* tp_repr */
1275 0, /* tp_as_number */
1276 0, /* tp_as_sequence */
1277 0, /* tp_as_mapping */
1278 0, /* tp_hash */
1279 0, /* tp_call */
1280 0, /* tp_str */
1281 PyObject_GenericGetAttr, /* tp_getattro */
1282 0, /* tp_setattro */
1283 0, /* tp_as_buffer */
1284 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
1285 0, /* tp_doc */
1286 (traverseproc)dequeiter_traverse, /* tp_traverse */
1287 0, /* tp_clear */
1288 0, /* tp_richcompare */
1289 0, /* tp_weaklistoffset */
1290 PyObject_SelfIter, /* tp_iter */
1291 (iternextfunc)dequeiter_next, /* tp_iternext */
1292 dequeiter_methods, /* tp_methods */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001293 0, /* tp_members */
1294 0, /* tp_getset */
1295 0, /* tp_base */
1296 0, /* tp_dict */
1297 0, /* tp_descr_get */
1298 0, /* tp_descr_set */
1299 0, /* tp_dictoffset */
1300 0, /* tp_init */
1301 0, /* tp_alloc */
1302 dequeiter_new, /* tp_new */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001303 0,
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001304};
1305
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001306/*********************** Deque Reverse Iterator **************************/
1307
Martin v. Löwis59683e82008-06-13 07:50:45 +00001308static PyTypeObject dequereviter_type;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001309
1310static PyObject *
1311deque_reviter(dequeobject *deque)
1312{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001313 dequeiterobject *it;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001315 it = PyObject_GC_New(dequeiterobject, &dequereviter_type);
1316 if (it == NULL)
1317 return NULL;
1318 it->b = deque->rightblock;
1319 it->index = deque->rightindex;
1320 Py_INCREF(deque);
1321 it->deque = deque;
1322 it->state = deque->state;
1323 it->counter = deque->len;
1324 PyObject_GC_Track(it);
1325 return (PyObject *)it;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001326}
1327
1328static PyObject *
1329dequereviter_next(dequeiterobject *it)
1330{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001331 PyObject *item;
1332 if (it->counter == 0)
1333 return NULL;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001335 if (it->deque->state != it->state) {
1336 it->counter = 0;
1337 PyErr_SetString(PyExc_RuntimeError,
1338 "deque mutated during iteration");
1339 return NULL;
1340 }
1341 assert (!(it->b == it->deque->leftblock &&
1342 it->index < it->deque->leftindex));
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001344 item = it->b->data[it->index];
1345 it->index--;
1346 it->counter--;
1347 if (it->index == -1 && it->counter > 0) {
1348 assert (it->b->leftlink != NULL);
1349 it->b = it->b->leftlink;
1350 it->index = BLOCKLEN - 1;
1351 }
1352 Py_INCREF(item);
1353 return item;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001354}
1355
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001356static PyObject *
1357dequereviter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1358{
1359 Py_ssize_t i, index=0;
1360 PyObject *deque;
1361 dequeiterobject *it;
1362 if (!PyArg_ParseTuple(args, "O!|n", &deque_type, &deque, &index))
1363 return NULL;
1364 assert(type == &dequereviter_type);
1365
1366 it = (dequeiterobject*)deque_reviter((dequeobject *)deque);
1367 if (!it)
1368 return NULL;
1369 /* consume items from the queue */
1370 for(i=0; i<index; i++) {
1371 PyObject *item = dequereviter_next(it);
1372 if (item) {
1373 Py_DECREF(item);
1374 } else {
1375 if (it->counter) {
1376 Py_DECREF(it);
1377 return NULL;
1378 } else
1379 break;
1380 }
1381 }
1382 return (PyObject*)it;
1383}
1384
Martin v. Löwis59683e82008-06-13 07:50:45 +00001385static PyTypeObject dequereviter_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001386 PyVarObject_HEAD_INIT(NULL, 0)
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001387 "_collections._deque_reverse_iterator", /* tp_name */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001388 sizeof(dequeiterobject), /* tp_basicsize */
1389 0, /* tp_itemsize */
1390 /* methods */
1391 (destructor)dequeiter_dealloc, /* tp_dealloc */
1392 0, /* tp_print */
1393 0, /* tp_getattr */
1394 0, /* tp_setattr */
1395 0, /* tp_reserved */
1396 0, /* tp_repr */
1397 0, /* tp_as_number */
1398 0, /* tp_as_sequence */
1399 0, /* tp_as_mapping */
1400 0, /* tp_hash */
1401 0, /* tp_call */
1402 0, /* tp_str */
1403 PyObject_GenericGetAttr, /* tp_getattro */
1404 0, /* tp_setattro */
1405 0, /* tp_as_buffer */
1406 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
1407 0, /* tp_doc */
1408 (traverseproc)dequeiter_traverse, /* tp_traverse */
1409 0, /* tp_clear */
1410 0, /* tp_richcompare */
1411 0, /* tp_weaklistoffset */
1412 PyObject_SelfIter, /* tp_iter */
1413 (iternextfunc)dequereviter_next, /* tp_iternext */
1414 dequeiter_methods, /* tp_methods */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001415 0, /* tp_members */
1416 0, /* tp_getset */
1417 0, /* tp_base */
1418 0, /* tp_dict */
1419 0, /* tp_descr_get */
1420 0, /* tp_descr_set */
1421 0, /* tp_dictoffset */
1422 0, /* tp_init */
1423 0, /* tp_alloc */
1424 dequereviter_new, /* tp_new */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001425 0,
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001426};
1427
Guido van Rossum1968ad32006-02-25 22:38:04 +00001428/* defaultdict type *********************************************************/
1429
1430typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001431 PyDictObject dict;
1432 PyObject *default_factory;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001433} defdictobject;
1434
1435static PyTypeObject defdict_type; /* Forward */
1436
1437PyDoc_STRVAR(defdict_missing_doc,
1438"__missing__(key) # Called by __getitem__ for missing key; pseudo-code:\n\
Guido van Rossumd8faa362007-04-27 19:54:29 +00001439 if self.default_factory is None: raise KeyError((key,))\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00001440 self[key] = value = self.default_factory()\n\
1441 return value\n\
1442");
1443
1444static PyObject *
1445defdict_missing(defdictobject *dd, PyObject *key)
1446{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001447 PyObject *factory = dd->default_factory;
1448 PyObject *value;
1449 if (factory == NULL || factory == Py_None) {
1450 /* XXX Call dict.__missing__(key) */
1451 PyObject *tup;
1452 tup = PyTuple_Pack(1, key);
1453 if (!tup) return NULL;
1454 PyErr_SetObject(PyExc_KeyError, tup);
1455 Py_DECREF(tup);
1456 return NULL;
1457 }
1458 value = PyEval_CallObject(factory, NULL);
1459 if (value == NULL)
1460 return value;
1461 if (PyObject_SetItem((PyObject *)dd, key, value) < 0) {
1462 Py_DECREF(value);
1463 return NULL;
1464 }
1465 return value;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001466}
1467
1468PyDoc_STRVAR(defdict_copy_doc, "D.copy() -> a shallow copy of D.");
1469
1470static PyObject *
1471defdict_copy(defdictobject *dd)
1472{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001473 /* This calls the object's class. That only works for subclasses
1474 whose class constructor has the same signature. Subclasses that
1475 define a different constructor signature must override copy().
1476 */
Raymond Hettinger54628fa2009-08-04 19:16:39 +00001477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001478 if (dd->default_factory == NULL)
1479 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd), Py_None, dd, NULL);
1480 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd),
1481 dd->default_factory, dd, NULL);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001482}
1483
1484static PyObject *
1485defdict_reduce(defdictobject *dd)
1486{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001487 /* __reduce__ must return a 5-tuple as follows:
Guido van Rossum1968ad32006-02-25 22:38:04 +00001488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001489 - factory function
1490 - tuple of args for the factory function
1491 - additional state (here None)
1492 - sequence iterator (here None)
1493 - dictionary iterator (yielding successive (key, value) pairs
Guido van Rossum1968ad32006-02-25 22:38:04 +00001494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001495 This API is used by pickle.py and copy.py.
Guido van Rossum1968ad32006-02-25 22:38:04 +00001496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001497 For this to be useful with pickle.py, the default_factory
1498 must be picklable; e.g., None, a built-in, or a global
1499 function in a module or package.
Guido van Rossum1968ad32006-02-25 22:38:04 +00001500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001501 Both shallow and deep copying are supported, but for deep
1502 copying, the default_factory must be deep-copyable; e.g. None,
1503 or a built-in (functions are not copyable at this time).
Guido van Rossum1968ad32006-02-25 22:38:04 +00001504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001505 This only works for subclasses as long as their constructor
1506 signature is compatible; the first argument must be the
1507 optional default_factory, defaulting to None.
1508 */
1509 PyObject *args;
1510 PyObject *items;
1511 PyObject *iter;
1512 PyObject *result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001513 _Py_IDENTIFIER(items);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001515 if (dd->default_factory == NULL || dd->default_factory == Py_None)
1516 args = PyTuple_New(0);
1517 else
1518 args = PyTuple_Pack(1, dd->default_factory);
1519 if (args == NULL)
1520 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001521 items = _PyObject_CallMethodId((PyObject *)dd, &PyId_items, "()");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001522 if (items == NULL) {
1523 Py_DECREF(args);
1524 return NULL;
1525 }
1526 iter = PyObject_GetIter(items);
1527 if (iter == NULL) {
1528 Py_DECREF(items);
1529 Py_DECREF(args);
1530 return NULL;
1531 }
1532 result = PyTuple_Pack(5, Py_TYPE(dd), args,
1533 Py_None, Py_None, iter);
1534 Py_DECREF(iter);
1535 Py_DECREF(items);
1536 Py_DECREF(args);
1537 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001538}
1539
1540static PyMethodDef defdict_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001541 {"__missing__", (PyCFunction)defdict_missing, METH_O,
1542 defdict_missing_doc},
1543 {"copy", (PyCFunction)defdict_copy, METH_NOARGS,
1544 defdict_copy_doc},
1545 {"__copy__", (PyCFunction)defdict_copy, METH_NOARGS,
1546 defdict_copy_doc},
1547 {"__reduce__", (PyCFunction)defdict_reduce, METH_NOARGS,
1548 reduce_doc},
1549 {NULL}
Guido van Rossum1968ad32006-02-25 22:38:04 +00001550};
1551
1552static PyMemberDef defdict_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001553 {"default_factory", T_OBJECT,
1554 offsetof(defdictobject, default_factory), 0,
1555 PyDoc_STR("Factory for default value called by __missing__().")},
1556 {NULL}
Guido van Rossum1968ad32006-02-25 22:38:04 +00001557};
1558
1559static void
1560defdict_dealloc(defdictobject *dd)
1561{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001562 Py_CLEAR(dd->default_factory);
1563 PyDict_Type.tp_dealloc((PyObject *)dd);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001564}
1565
Guido van Rossum1968ad32006-02-25 22:38:04 +00001566static PyObject *
1567defdict_repr(defdictobject *dd)
1568{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001569 PyObject *baserepr;
1570 PyObject *defrepr;
1571 PyObject *result;
1572 baserepr = PyDict_Type.tp_repr((PyObject *)dd);
1573 if (baserepr == NULL)
1574 return NULL;
1575 if (dd->default_factory == NULL)
1576 defrepr = PyUnicode_FromString("None");
1577 else
1578 {
1579 int status = Py_ReprEnter(dd->default_factory);
1580 if (status != 0) {
Antoine Pitrouf5f1fe02012-02-15 02:42:46 +01001581 if (status < 0) {
1582 Py_DECREF(baserepr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001583 return NULL;
Antoine Pitrouf5f1fe02012-02-15 02:42:46 +01001584 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001585 defrepr = PyUnicode_FromString("...");
1586 }
1587 else
1588 defrepr = PyObject_Repr(dd->default_factory);
1589 Py_ReprLeave(dd->default_factory);
1590 }
1591 if (defrepr == NULL) {
1592 Py_DECREF(baserepr);
1593 return NULL;
1594 }
1595 result = PyUnicode_FromFormat("defaultdict(%U, %U)",
1596 defrepr, baserepr);
1597 Py_DECREF(defrepr);
1598 Py_DECREF(baserepr);
1599 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001600}
1601
1602static int
1603defdict_traverse(PyObject *self, visitproc visit, void *arg)
1604{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001605 Py_VISIT(((defdictobject *)self)->default_factory);
1606 return PyDict_Type.tp_traverse(self, visit, arg);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001607}
1608
1609static int
1610defdict_tp_clear(defdictobject *dd)
1611{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001612 Py_CLEAR(dd->default_factory);
1613 return PyDict_Type.tp_clear((PyObject *)dd);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001614}
1615
1616static int
1617defdict_init(PyObject *self, PyObject *args, PyObject *kwds)
1618{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001619 defdictobject *dd = (defdictobject *)self;
1620 PyObject *olddefault = dd->default_factory;
1621 PyObject *newdefault = NULL;
1622 PyObject *newargs;
1623 int result;
1624 if (args == NULL || !PyTuple_Check(args))
1625 newargs = PyTuple_New(0);
1626 else {
1627 Py_ssize_t n = PyTuple_GET_SIZE(args);
1628 if (n > 0) {
1629 newdefault = PyTuple_GET_ITEM(args, 0);
1630 if (!PyCallable_Check(newdefault) && newdefault != Py_None) {
1631 PyErr_SetString(PyExc_TypeError,
1632 "first argument must be callable");
1633 return -1;
1634 }
1635 }
1636 newargs = PySequence_GetSlice(args, 1, n);
1637 }
1638 if (newargs == NULL)
1639 return -1;
1640 Py_XINCREF(newdefault);
1641 dd->default_factory = newdefault;
1642 result = PyDict_Type.tp_init(self, newargs, kwds);
1643 Py_DECREF(newargs);
1644 Py_XDECREF(olddefault);
1645 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001646}
1647
1648PyDoc_STRVAR(defdict_doc,
1649"defaultdict(default_factory) --> dict with default factory\n\
1650\n\
1651The default factory is called without arguments to produce\n\
1652a new value when a key is not present, in __getitem__ only.\n\
1653A defaultdict compares equal to a dict with the same items.\n\
1654");
1655
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001656/* See comment in xxsubtype.c */
1657#define DEFERRED_ADDRESS(ADDR) 0
1658
Guido van Rossum1968ad32006-02-25 22:38:04 +00001659static PyTypeObject defdict_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001660 PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0)
1661 "collections.defaultdict", /* tp_name */
1662 sizeof(defdictobject), /* tp_basicsize */
1663 0, /* tp_itemsize */
1664 /* methods */
1665 (destructor)defdict_dealloc, /* tp_dealloc */
1666 0, /* tp_print */
1667 0, /* tp_getattr */
1668 0, /* tp_setattr */
1669 0, /* tp_reserved */
1670 (reprfunc)defdict_repr, /* tp_repr */
1671 0, /* tp_as_number */
1672 0, /* tp_as_sequence */
1673 0, /* tp_as_mapping */
1674 0, /* tp_hash */
1675 0, /* tp_call */
1676 0, /* tp_str */
1677 PyObject_GenericGetAttr, /* tp_getattro */
1678 0, /* tp_setattro */
1679 0, /* tp_as_buffer */
1680 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
1681 /* tp_flags */
1682 defdict_doc, /* tp_doc */
1683 defdict_traverse, /* tp_traverse */
1684 (inquiry)defdict_tp_clear, /* tp_clear */
1685 0, /* tp_richcompare */
1686 0, /* tp_weaklistoffset*/
1687 0, /* tp_iter */
1688 0, /* tp_iternext */
1689 defdict_methods, /* tp_methods */
1690 defdict_members, /* tp_members */
1691 0, /* tp_getset */
1692 DEFERRED_ADDRESS(&PyDict_Type), /* tp_base */
1693 0, /* tp_dict */
1694 0, /* tp_descr_get */
1695 0, /* tp_descr_set */
1696 0, /* tp_dictoffset */
1697 defdict_init, /* tp_init */
1698 PyType_GenericAlloc, /* tp_alloc */
1699 0, /* tp_new */
1700 PyObject_GC_Del, /* tp_free */
Guido van Rossum1968ad32006-02-25 22:38:04 +00001701};
1702
Raymond Hettinger96f34102010-12-15 16:30:37 +00001703/* helper function for Counter *********************************************/
1704
1705PyDoc_STRVAR(_count_elements_doc,
1706"_count_elements(mapping, iterable) -> None\n\
1707\n\
1708Count elements in the iterable, updating the mappping");
1709
1710static PyObject *
1711_count_elements(PyObject *self, PyObject *args)
1712{
1713 PyObject *it, *iterable, *mapping, *oldval;
1714 PyObject *newval = NULL;
1715 PyObject *key = NULL;
1716 PyObject *one = NULL;
1717
1718 if (!PyArg_UnpackTuple(args, "_count_elements", 2, 2, &mapping, &iterable))
1719 return NULL;
1720
Raymond Hettinger96f34102010-12-15 16:30:37 +00001721 it = PyObject_GetIter(iterable);
1722 if (it == NULL)
1723 return NULL;
Raymond Hettinger426e0522011-01-03 02:12:02 +00001724
Raymond Hettinger96f34102010-12-15 16:30:37 +00001725 one = PyLong_FromLong(1);
1726 if (one == NULL) {
1727 Py_DECREF(it);
1728 return NULL;
1729 }
Raymond Hettinger426e0522011-01-03 02:12:02 +00001730
1731 if (PyDict_CheckExact(mapping)) {
1732 while (1) {
1733 key = PyIter_Next(it);
Victor Stinnera154b5c2011-04-20 23:23:52 +02001734 if (key == NULL)
1735 break;
Raymond Hettinger426e0522011-01-03 02:12:02 +00001736 oldval = PyDict_GetItem(mapping, key);
1737 if (oldval == NULL) {
1738 if (PyDict_SetItem(mapping, key, one) == -1)
1739 break;
1740 } else {
1741 newval = PyNumber_Add(oldval, one);
1742 if (newval == NULL)
1743 break;
1744 if (PyDict_SetItem(mapping, key, newval) == -1)
1745 break;
1746 Py_CLEAR(newval);
1747 }
1748 Py_DECREF(key);
Raymond Hettinger96f34102010-12-15 16:30:37 +00001749 }
Raymond Hettinger426e0522011-01-03 02:12:02 +00001750 } else {
1751 while (1) {
1752 key = PyIter_Next(it);
Victor Stinnera154b5c2011-04-20 23:23:52 +02001753 if (key == NULL)
1754 break;
Raymond Hettinger426e0522011-01-03 02:12:02 +00001755 oldval = PyObject_GetItem(mapping, key);
1756 if (oldval == NULL) {
1757 if (!PyErr_Occurred() || !PyErr_ExceptionMatches(PyExc_KeyError))
1758 break;
1759 PyErr_Clear();
1760 Py_INCREF(one);
1761 newval = one;
1762 } else {
1763 newval = PyNumber_Add(oldval, one);
1764 Py_DECREF(oldval);
1765 if (newval == NULL)
1766 break;
1767 }
1768 if (PyObject_SetItem(mapping, key, newval) == -1)
Raymond Hettinger96f34102010-12-15 16:30:37 +00001769 break;
1770 Py_CLEAR(newval);
Raymond Hettinger426e0522011-01-03 02:12:02 +00001771 Py_DECREF(key);
Raymond Hettinger96f34102010-12-15 16:30:37 +00001772 }
Raymond Hettinger96f34102010-12-15 16:30:37 +00001773 }
Raymond Hettinger426e0522011-01-03 02:12:02 +00001774
Raymond Hettinger96f34102010-12-15 16:30:37 +00001775 Py_DECREF(it);
1776 Py_XDECREF(key);
1777 Py_XDECREF(newval);
1778 Py_DECREF(one);
1779 if (PyErr_Occurred())
1780 return NULL;
1781 Py_RETURN_NONE;
1782}
1783
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001784/* module level code ********************************************************/
1785
1786PyDoc_STRVAR(module_doc,
Guido van Rossum1968ad32006-02-25 22:38:04 +00001787"High performance data structures.\n\
1788- deque: ordered collection accessible from endpoints only\n\
1789- defaultdict: dict subclass with a default value factory\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001790");
1791
Raymond Hettinger96f34102010-12-15 16:30:37 +00001792static struct PyMethodDef module_functions[] = {
1793 {"_count_elements", _count_elements, METH_VARARGS, _count_elements_doc},
1794 {NULL, NULL} /* sentinel */
1795};
Martin v. Löwis1a214512008-06-11 05:26:20 +00001796
1797static struct PyModuleDef _collectionsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001798 PyModuleDef_HEAD_INIT,
1799 "_collections",
1800 module_doc,
1801 -1,
Raymond Hettinger96f34102010-12-15 16:30:37 +00001802 module_functions,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001803 NULL,
1804 NULL,
1805 NULL,
1806 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001807};
1808
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001809PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001810PyInit__collections(void)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001811{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001812 PyObject *m;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001813
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001814 m = PyModule_Create(&_collectionsmodule);
1815 if (m == NULL)
1816 return NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001817
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001818 if (PyType_Ready(&deque_type) < 0)
1819 return NULL;
1820 Py_INCREF(&deque_type);
1821 PyModule_AddObject(m, "deque", (PyObject *)&deque_type);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001823 defdict_type.tp_base = &PyDict_Type;
1824 if (PyType_Ready(&defdict_type) < 0)
1825 return NULL;
1826 Py_INCREF(&defdict_type);
1827 PyModule_AddObject(m, "defaultdict", (PyObject *)&defdict_type);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001829 if (PyType_Ready(&dequeiter_type) < 0)
1830 return NULL;
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001831 Py_INCREF(&dequeiter_type);
1832 PyModule_AddObject(m, "_deque_iterator", (PyObject *)&dequeiter_type);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001834 if (PyType_Ready(&dequereviter_type) < 0)
1835 return NULL;
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001836 Py_INCREF(&dequereviter_type);
1837 PyModule_AddObject(m, "_deque_reverse_iterator", (PyObject *)&dequereviter_type);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001838
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001839 return m;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001840}