blob: c5690ef09ef815a4e2d382f3da06c23b0f7dbd04 [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>
6 Copyright (c) 2004 Python Software Foundation.
7 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
Benjamin Peterson227f0fa2013-06-25 11:34:48 -070011 * reduce the number of calls to the memory allocator, give faster
12 * indexing and rotation, and reduce the link::data overhead ratio.
Raymond Hettinger662908b2013-07-28 02:34:42 -070013 *
14 * Ideally, the block length will be set to two less than some
15 * multiple of the cache-line length (so that the full block
16 * including the leftlink and rightlink will fit neatly into
17 * cache lines).
Raymond Hettinger77e8bf12004-10-01 15:25:53 +000018 */
19
Raymond Hettinger662908b2013-07-28 02:34:42 -070020#define BLOCKLEN 62
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000021#define CENTER ((BLOCKLEN - 1) / 2)
Raymond Hettinger756b3f32004-01-29 06:37:52 +000022
Tim Petersd8768d32004-10-01 01:32:53 +000023/* A `dequeobject` is composed of a doubly-linked list of `block` nodes.
24 * This list is not circular (the leftmost block has leftlink==NULL,
25 * and the rightmost block has rightlink==NULL). A deque d's first
26 * element is at d.leftblock[leftindex] and its last element is at
27 * d.rightblock[rightindex]; note that, unlike as for Python slice
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000028 * indices, these indices are inclusive on both ends. By being inclusive
Tim Peters5566e962006-07-28 00:23:15 +000029 * on both ends, algorithms for left and right operations become
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000030 * symmetrical which simplifies the design.
Tim Peters5566e962006-07-28 00:23:15 +000031 *
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000032 * The list of blocks is never empty, so d.leftblock and d.rightblock
33 * are never equal to NULL.
34 *
35 * The indices, d.leftindex and d.rightindex are always in the range
36 * 0 <= index < BLOCKLEN.
Raymond Hettinger4ca4c7c2004-10-01 15:14:39 +000037 * Their exact relationship is:
38 * (d.leftindex + d.len - 1) % BLOCKLEN == d.rightindex.
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000039 *
40 * Empty deques have d.len == 0; d.leftblock==d.rightblock;
41 * d.leftindex == CENTER+1; and d.rightindex == CENTER.
42 * Checking for d.len == 0 is the intended way to see whether d is empty.
43 *
Tim Peters5566e962006-07-28 00:23:15 +000044 * Whenever d.leftblock == d.rightblock,
Raymond Hettinger4ca4c7c2004-10-01 15:14:39 +000045 * d.leftindex + d.len - 1 == d.rightindex.
Tim Peters5566e962006-07-28 00:23:15 +000046 *
Raymond Hettinger4ca4c7c2004-10-01 15:14:39 +000047 * However, when d.leftblock != d.rightblock, d.leftindex and d.rightindex
Tim Peters5566e962006-07-28 00:23:15 +000048 * become indices into distinct blocks and either may be larger than the
Raymond Hettinger4ca4c7c2004-10-01 15:14:39 +000049 * other.
Tim Petersd8768d32004-10-01 01:32:53 +000050 */
51
Raymond Hettinger756b3f32004-01-29 06:37:52 +000052typedef struct BLOCK {
Benjamin Peterson3968e292013-06-25 11:26:20 -070053 PyObject *data[BLOCKLEN];
Benjamin Peterson73d6aca2013-06-25 11:35:44 -070054 struct BLOCK *rightlink;
Raymond Hettinger90180c12013-07-16 01:59:30 -070055 struct BLOCK *leftlink;
Raymond Hettinger756b3f32004-01-29 06:37:52 +000056} block;
57
Raymond Hettingerd3ffd342007-11-10 01:54:03 +000058#define MAXFREEBLOCKS 10
Raymond Hettinger33fcf9d2008-07-24 00:08:18 +000059static Py_ssize_t numfreeblocks = 0;
Raymond Hettingerd3ffd342007-11-10 01:54:03 +000060static block *freeblocks[MAXFREEBLOCKS];
61
Tim Peters6f853562004-10-01 01:04:50 +000062static block *
Raymond Hettinger33fcf9d2008-07-24 00:08:18 +000063newblock(block *leftlink, block *rightlink, Py_ssize_t len) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +000064 block *b;
Benjamin Peterson227f0fa2013-06-25 11:34:48 -070065 /* To prevent len from overflowing PY_SSIZE_T_MAX on 32-bit machines, we
66 * refuse to allocate new blocks if the current len is nearing overflow. */
Antoine Pitrouc83ea132010-05-09 14:46:46 +000067 if (len >= PY_SSIZE_T_MAX - 2*BLOCKLEN) {
68 PyErr_SetString(PyExc_OverflowError,
69 "cannot add more blocks to the deque");
70 return NULL;
71 }
72 if (numfreeblocks) {
73 numfreeblocks -= 1;
74 b = freeblocks[numfreeblocks];
75 } else {
76 b = PyMem_Malloc(sizeof(block));
77 if (b == NULL) {
78 PyErr_NoMemory();
79 return NULL;
80 }
81 }
82 b->leftlink = leftlink;
83 b->rightlink = rightlink;
84 return b;
Raymond Hettinger756b3f32004-01-29 06:37:52 +000085}
86
Martin v. Löwis111c1802008-06-13 07:47:47 +000087static void
Raymond Hettingerd3ffd342007-11-10 01:54:03 +000088freeblock(block *b)
89{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000090 if (numfreeblocks < MAXFREEBLOCKS) {
91 freeblocks[numfreeblocks] = b;
92 numfreeblocks++;
93 } else {
94 PyMem_Free(b);
95 }
Raymond Hettingerd3ffd342007-11-10 01:54:03 +000096}
97
Raymond Hettinger756b3f32004-01-29 06:37:52 +000098typedef struct {
Antoine Pitrouc83ea132010-05-09 14:46:46 +000099 PyObject_HEAD
100 block *leftblock;
101 block *rightblock;
102 Py_ssize_t leftindex; /* in range(BLOCKLEN) */
103 Py_ssize_t rightindex; /* in range(BLOCKLEN) */
104 Py_ssize_t len;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000105 long state; /* incremented whenever the indices move */
Raymond Hettingerb77ed2c2013-07-16 02:34:19 -0700106 Py_ssize_t maxlen;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000107 PyObject *weakreflist; /* List of weak references */
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000108} dequeobject;
109
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000110/* The deque's size limit is d.maxlen. The limit can be zero or positive.
111 * If there is no limit, then d.maxlen == -1.
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000112 *
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000113 * After an item is added to a deque, we check to see if the size has grown past
114 * the limit. If it has, we get the size back down to the limit by popping an
115 * item off of the opposite end. The methods that can trigger this are append(),
116 * appendleft(), extend(), and extendleft().
117 */
118
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000119#define TRIM(d, popfunction) \
120 if (d->maxlen != -1 && d->len > d->maxlen) { \
121 PyObject *rv = popfunction(d, NULL); \
122 assert(rv != NULL && d->len <= d->maxlen); \
123 Py_DECREF(rv); \
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000124 }
125
Neal Norwitz87f10132004-02-29 15:40:53 +0000126static PyTypeObject deque_type;
Raymond Hettinger738ec902004-02-29 02:15:56 +0000127
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000128static PyObject *
129deque_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
130{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000131 dequeobject *deque;
132 block *b;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000133
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000134 /* create dequeobject structure */
135 deque = (dequeobject *)type->tp_alloc(type, 0);
136 if (deque == NULL)
137 return NULL;
Tim Peters1065f752004-10-01 01:03:29 +0000138
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000139 b = newblock(NULL, NULL, 0);
140 if (b == NULL) {
141 Py_DECREF(deque);
142 return NULL;
143 }
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000144
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000145 assert(BLOCKLEN >= 2);
146 deque->leftblock = b;
147 deque->rightblock = b;
148 deque->leftindex = CENTER + 1;
149 deque->rightindex = CENTER;
150 deque->len = 0;
151 deque->state = 0;
152 deque->weakreflist = NULL;
153 deque->maxlen = -1;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000154
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000155 return (PyObject *)deque;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000156}
157
158static PyObject *
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000159deque_pop(dequeobject *deque, PyObject *unused)
160{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000161 PyObject *item;
162 block *prevblock;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000163
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000164 if (deque->len == 0) {
165 PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
166 return NULL;
167 }
168 item = deque->rightblock->data[deque->rightindex];
169 deque->rightindex--;
170 deque->len--;
171 deque->state++;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000172
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000173 if (deque->rightindex == -1) {
174 if (deque->len == 0) {
175 assert(deque->leftblock == deque->rightblock);
176 assert(deque->leftindex == deque->rightindex+1);
177 /* re-center instead of freeing a block */
178 deque->leftindex = CENTER + 1;
179 deque->rightindex = CENTER;
180 } else {
181 prevblock = deque->rightblock->leftlink;
182 assert(deque->leftblock != deque->rightblock);
183 freeblock(deque->rightblock);
184 prevblock->rightlink = NULL;
185 deque->rightblock = prevblock;
186 deque->rightindex = BLOCKLEN - 1;
187 }
188 }
189 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000190}
191
192PyDoc_STRVAR(pop_doc, "Remove and return the rightmost element.");
193
194static PyObject *
195deque_popleft(dequeobject *deque, PyObject *unused)
196{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000197 PyObject *item;
198 block *prevblock;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000199
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000200 if (deque->len == 0) {
201 PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
202 return NULL;
203 }
204 assert(deque->leftblock != NULL);
205 item = deque->leftblock->data[deque->leftindex];
206 deque->leftindex++;
207 deque->len--;
208 deque->state++;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000209
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000210 if (deque->leftindex == BLOCKLEN) {
211 if (deque->len == 0) {
212 assert(deque->leftblock == deque->rightblock);
213 assert(deque->leftindex == deque->rightindex+1);
214 /* re-center instead of freeing a block */
215 deque->leftindex = CENTER + 1;
216 deque->rightindex = CENTER;
217 } else {
218 assert(deque->leftblock != deque->rightblock);
219 prevblock = deque->leftblock->rightlink;
220 freeblock(deque->leftblock);
221 assert(prevblock != NULL);
222 prevblock->leftlink = NULL;
223 deque->leftblock = prevblock;
224 deque->leftindex = 0;
225 }
226 }
227 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000228}
229
230PyDoc_STRVAR(popleft_doc, "Remove and return the leftmost element.");
231
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000232static PyObject *
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000233deque_append(dequeobject *deque, PyObject *item)
234{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000235 deque->state++;
236 if (deque->rightindex == BLOCKLEN-1) {
237 block *b = newblock(deque->rightblock, NULL, deque->len);
238 if (b == NULL)
239 return NULL;
240 assert(deque->rightblock->rightlink == NULL);
241 deque->rightblock->rightlink = b;
242 deque->rightblock = b;
243 deque->rightindex = -1;
244 }
245 Py_INCREF(item);
246 deque->len++;
247 deque->rightindex++;
248 deque->rightblock->data[deque->rightindex] = item;
249 TRIM(deque, deque_popleft);
250 Py_RETURN_NONE;
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000251}
252
253PyDoc_STRVAR(append_doc, "Add an element to the right side of the deque.");
254
255static PyObject *
256deque_appendleft(dequeobject *deque, PyObject *item)
257{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000258 deque->state++;
259 if (deque->leftindex == 0) {
260 block *b = newblock(NULL, deque->leftblock, deque->len);
261 if (b == NULL)
262 return NULL;
263 assert(deque->leftblock->leftlink == NULL);
264 deque->leftblock->leftlink = b;
265 deque->leftblock = b;
266 deque->leftindex = BLOCKLEN;
267 }
268 Py_INCREF(item);
269 deque->len++;
270 deque->leftindex--;
271 deque->leftblock->data[deque->leftindex] = item;
272 TRIM(deque, deque_pop);
273 Py_RETURN_NONE;
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000274}
275
276PyDoc_STRVAR(appendleft_doc, "Add an element to the left side of the deque.");
277
Raymond Hettingerbac769b2009-03-10 09:31:48 +0000278
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000279/* Run an iterator to exhaustion. Shortcut for
Raymond Hettingerbac769b2009-03-10 09:31:48 +0000280 the extend/extendleft methods when maxlen == 0. */
281static PyObject*
282consume_iterator(PyObject *it)
283{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000284 PyObject *item;
Raymond Hettingerbac769b2009-03-10 09:31:48 +0000285
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000286 while ((item = PyIter_Next(it)) != NULL) {
287 Py_DECREF(item);
288 }
289 Py_DECREF(it);
290 if (PyErr_Occurred())
291 return NULL;
292 Py_RETURN_NONE;
Raymond Hettingerbac769b2009-03-10 09:31:48 +0000293}
294
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000295static PyObject *
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000296deque_extend(dequeobject *deque, PyObject *iterable)
297{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000298 PyObject *it, *item;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000299
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000300 /* Handle case where id(deque) == id(iterable) */
301 if ((PyObject *)deque == iterable) {
302 PyObject *result;
303 PyObject *s = PySequence_List(iterable);
304 if (s == NULL)
305 return NULL;
306 result = deque_extend(deque, s);
307 Py_DECREF(s);
308 return result;
309 }
Raymond Hettinger0b3263b2009-12-10 06:00:33 +0000310
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000311 it = PyObject_GetIter(iterable);
312 if (it == NULL)
313 return NULL;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000314
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000315 if (deque->maxlen == 0)
316 return consume_iterator(it);
Raymond Hettingerbac769b2009-03-10 09:31:48 +0000317
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000318 while ((item = PyIter_Next(it)) != NULL) {
319 deque->state++;
320 if (deque->rightindex == BLOCKLEN-1) {
321 block *b = newblock(deque->rightblock, NULL,
322 deque->len);
323 if (b == NULL) {
324 Py_DECREF(item);
325 Py_DECREF(it);
326 return NULL;
327 }
328 assert(deque->rightblock->rightlink == NULL);
329 deque->rightblock->rightlink = b;
330 deque->rightblock = b;
331 deque->rightindex = -1;
332 }
333 deque->len++;
334 deque->rightindex++;
335 deque->rightblock->data[deque->rightindex] = item;
336 TRIM(deque, deque_popleft);
337 }
338 Py_DECREF(it);
339 if (PyErr_Occurred())
340 return NULL;
341 Py_RETURN_NONE;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000342}
343
Tim Peters1065f752004-10-01 01:03:29 +0000344PyDoc_STRVAR(extend_doc,
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000345"Extend the right side of the deque with elements from the iterable");
346
347static PyObject *
348deque_extendleft(dequeobject *deque, PyObject *iterable)
349{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000350 PyObject *it, *item;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000351
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000352 /* Handle case where id(deque) == id(iterable) */
353 if ((PyObject *)deque == iterable) {
354 PyObject *result;
355 PyObject *s = PySequence_List(iterable);
356 if (s == NULL)
357 return NULL;
358 result = deque_extendleft(deque, s);
359 Py_DECREF(s);
360 return result;
361 }
Raymond Hettinger0b3263b2009-12-10 06:00:33 +0000362
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000363 it = PyObject_GetIter(iterable);
364 if (it == NULL)
365 return NULL;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000366
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000367 if (deque->maxlen == 0)
368 return consume_iterator(it);
Raymond Hettingerbac769b2009-03-10 09:31:48 +0000369
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000370 while ((item = PyIter_Next(it)) != NULL) {
371 deque->state++;
372 if (deque->leftindex == 0) {
373 block *b = newblock(NULL, deque->leftblock,
374 deque->len);
375 if (b == NULL) {
376 Py_DECREF(item);
377 Py_DECREF(it);
378 return NULL;
379 }
380 assert(deque->leftblock->leftlink == NULL);
381 deque->leftblock->leftlink = b;
382 deque->leftblock = b;
383 deque->leftindex = BLOCKLEN;
384 }
385 deque->len++;
386 deque->leftindex--;
387 deque->leftblock->data[deque->leftindex] = item;
388 TRIM(deque, deque_pop);
389 }
390 Py_DECREF(it);
391 if (PyErr_Occurred())
392 return NULL;
393 Py_RETURN_NONE;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000394}
395
Tim Peters1065f752004-10-01 01:03:29 +0000396PyDoc_STRVAR(extendleft_doc,
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000397"Extend the left side of the deque with elements from the iterable");
398
Raymond Hettinger0b3263b2009-12-10 06:00:33 +0000399static PyObject *
400deque_inplace_concat(dequeobject *deque, PyObject *other)
401{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000402 PyObject *result;
Raymond Hettinger0b3263b2009-12-10 06:00:33 +0000403
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000404 result = deque_extend(deque, other);
405 if (result == NULL)
406 return result;
407 Py_DECREF(result);
408 Py_INCREF(deque);
409 return (PyObject *)deque;
Raymond Hettinger0b3263b2009-12-10 06:00:33 +0000410}
411
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000412static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000413_deque_rotate(dequeobject *deque, Py_ssize_t n)
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000414{
Raymond Hettinger6688bdb2013-02-09 18:55:44 -0500415 Py_ssize_t m, len=deque->len, halflen=len>>1;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000416
Raymond Hettinger2cdb6432013-01-12 00:05:00 -0800417 if (len <= 1)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000418 return 0;
419 if (n > halflen || n < -halflen) {
420 n %= len;
421 if (n > halflen)
422 n -= len;
423 else if (n < -halflen)
424 n += len;
425 }
Raymond Hettinger6688bdb2013-02-09 18:55:44 -0500426 assert(len > 1);
427 assert(-halflen <= n && n <= halflen);
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000428
Raymond Hettinger2cdb6432013-01-12 00:05:00 -0800429 deque->state++;
Raymond Hettinger6688bdb2013-02-09 18:55:44 -0500430 while (n > 0) {
Raymond Hettinger2cdb6432013-01-12 00:05:00 -0800431 if (deque->leftindex == 0) {
Raymond Hettinger6688bdb2013-02-09 18:55:44 -0500432 block *b = newblock(NULL, deque->leftblock, len);
Raymond Hettinger42645322013-02-02 10:23:37 -0800433 if (b == NULL)
Raymond Hettinger2cdb6432013-01-12 00:05:00 -0800434 return -1;
Raymond Hettinger42645322013-02-02 10:23:37 -0800435 assert(deque->leftblock->leftlink == NULL);
436 deque->leftblock->leftlink = b;
437 deque->leftblock = b;
Raymond Hettinger2cdb6432013-01-12 00:05:00 -0800438 deque->leftindex = BLOCKLEN;
439 }
Raymond Hettinger42645322013-02-02 10:23:37 -0800440 assert(deque->leftindex > 0);
441
Raymond Hettinger6688bdb2013-02-09 18:55:44 -0500442 m = n;
Raymond Hettinger42645322013-02-02 10:23:37 -0800443 if (m > deque->rightindex + 1)
444 m = deque->rightindex + 1;
445 if (m > deque->leftindex)
446 m = deque->leftindex;
Raymond Hettinger6688bdb2013-02-09 18:55:44 -0500447 assert (m > 0 && m <= len);
Raymond Hettinger42645322013-02-02 10:23:37 -0800448 memcpy(&deque->leftblock->data[deque->leftindex - m],
Raymond Hettinger6688bdb2013-02-09 18:55:44 -0500449 &deque->rightblock->data[deque->rightindex + 1 - m],
Raymond Hettinger42645322013-02-02 10:23:37 -0800450 m * sizeof(PyObject *));
451 deque->rightindex -= m;
452 deque->leftindex -= m;
Raymond Hettinger6688bdb2013-02-09 18:55:44 -0500453 n -= m;
Raymond Hettinger42645322013-02-02 10:23:37 -0800454
455 if (deque->rightindex == -1) {
Raymond Hettinger6688bdb2013-02-09 18:55:44 -0500456 block *prevblock = deque->rightblock->leftlink;
Raymond Hettinger42645322013-02-02 10:23:37 -0800457 assert(deque->rightblock != NULL);
Raymond Hettinger42645322013-02-02 10:23:37 -0800458 assert(deque->leftblock != deque->rightblock);
459 freeblock(deque->rightblock);
460 prevblock->rightlink = NULL;
461 deque->rightblock = prevblock;
462 deque->rightindex = BLOCKLEN - 1;
Raymond Hettinger2cdb6432013-01-12 00:05:00 -0800463 }
Raymond Hettinger42645322013-02-02 10:23:37 -0800464 }
Raymond Hettinger6688bdb2013-02-09 18:55:44 -0500465 while (n < 0) {
Raymond Hettinger42645322013-02-02 10:23:37 -0800466 if (deque->rightindex == BLOCKLEN - 1) {
Raymond Hettinger6688bdb2013-02-09 18:55:44 -0500467 block *b = newblock(deque->rightblock, NULL, len);
Raymond Hettinger42645322013-02-02 10:23:37 -0800468 if (b == NULL)
Raymond Hettinger2cdb6432013-01-12 00:05:00 -0800469 return -1;
Raymond Hettinger42645322013-02-02 10:23:37 -0800470 assert(deque->rightblock->rightlink == NULL);
471 deque->rightblock->rightlink = b;
472 deque->rightblock = b;
Raymond Hettinger2cdb6432013-01-12 00:05:00 -0800473 deque->rightindex = -1;
474 }
Raymond Hettinger42645322013-02-02 10:23:37 -0800475 assert (deque->rightindex < BLOCKLEN - 1);
476
Raymond Hettinger6688bdb2013-02-09 18:55:44 -0500477 m = -n;
Raymond Hettinger42645322013-02-02 10:23:37 -0800478 if (m > BLOCKLEN - deque->leftindex)
479 m = BLOCKLEN - deque->leftindex;
480 if (m > BLOCKLEN - 1 - deque->rightindex)
481 m = BLOCKLEN - 1 - deque->rightindex;
Raymond Hettinger6688bdb2013-02-09 18:55:44 -0500482 assert (m > 0 && m <= len);
Raymond Hettinger42645322013-02-02 10:23:37 -0800483 memcpy(&deque->rightblock->data[deque->rightindex + 1],
484 &deque->leftblock->data[deque->leftindex],
485 m * sizeof(PyObject *));
486 deque->leftindex += m;
487 deque->rightindex += m;
Raymond Hettinger6688bdb2013-02-09 18:55:44 -0500488 n += m;
Raymond Hettinger42645322013-02-02 10:23:37 -0800489
490 if (deque->leftindex == BLOCKLEN) {
Raymond Hettinger6688bdb2013-02-09 18:55:44 -0500491 block *nextblock = deque->leftblock->rightlink;
Raymond Hettinger42645322013-02-02 10:23:37 -0800492 assert(deque->leftblock != deque->rightblock);
Raymond Hettinger42645322013-02-02 10:23:37 -0800493 freeblock(deque->leftblock);
Raymond Hettinger6688bdb2013-02-09 18:55:44 -0500494 assert(nextblock != NULL);
495 nextblock->leftlink = NULL;
496 deque->leftblock = nextblock;
Raymond Hettinger42645322013-02-02 10:23:37 -0800497 deque->leftindex = 0;
498 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000499 }
500 return 0;
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000501}
502
503static PyObject *
504deque_rotate(dequeobject *deque, PyObject *args)
505{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000506 Py_ssize_t n=1;
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000507
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000508 if (!PyArg_ParseTuple(args, "|n:rotate", &n))
509 return NULL;
510 if (_deque_rotate(deque, n) == 0)
511 Py_RETURN_NONE;
512 return NULL;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000513}
514
Tim Peters1065f752004-10-01 01:03:29 +0000515PyDoc_STRVAR(rotate_doc,
Raymond Hettingeree33b272004-02-08 04:05:26 +0000516"Rotate the deque n steps to the right (default n=1). If n is negative, rotates left.");
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000517
Raymond Hettingera5fd24e2009-12-10 06:42:54 +0000518static PyObject *
519deque_reverse(dequeobject *deque, PyObject *unused)
520{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000521 block *leftblock = deque->leftblock;
522 block *rightblock = deque->rightblock;
523 Py_ssize_t leftindex = deque->leftindex;
524 Py_ssize_t rightindex = deque->rightindex;
525 Py_ssize_t n = (deque->len)/2;
526 Py_ssize_t i;
527 PyObject *tmp;
Raymond Hettingera5fd24e2009-12-10 06:42:54 +0000528
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000529 for (i=0 ; i<n ; i++) {
530 /* Validate that pointers haven't met in the middle */
531 assert(leftblock != rightblock || leftindex < rightindex);
Raymond Hettingera5fd24e2009-12-10 06:42:54 +0000532
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000533 /* Swap */
534 tmp = leftblock->data[leftindex];
535 leftblock->data[leftindex] = rightblock->data[rightindex];
536 rightblock->data[rightindex] = tmp;
Raymond Hettingera5fd24e2009-12-10 06:42:54 +0000537
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000538 /* Advance left block/index pair */
539 leftindex++;
540 if (leftindex == BLOCKLEN) {
Raymond Hettinger57a86892011-01-25 21:43:29 +0000541 if (leftblock->rightlink == NULL)
542 break;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000543 leftblock = leftblock->rightlink;
544 leftindex = 0;
545 }
Raymond Hettingera5fd24e2009-12-10 06:42:54 +0000546
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000547 /* Step backwards with the right block/index pair */
548 rightindex--;
549 if (rightindex == -1) {
Raymond Hettinger57a86892011-01-25 21:43:29 +0000550 if (rightblock->leftlink == NULL)
551 break;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000552 rightblock = rightblock->leftlink;
553 rightindex = BLOCKLEN - 1;
554 }
555 }
556 Py_RETURN_NONE;
Raymond Hettingera5fd24e2009-12-10 06:42:54 +0000557}
558
559PyDoc_STRVAR(reverse_doc,
560"D.reverse() -- reverse *IN PLACE*");
561
Raymond Hettinger5f516ed2010-04-03 18:10:37 +0000562static PyObject *
563deque_count(dequeobject *deque, PyObject *v)
564{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000565 block *leftblock = deque->leftblock;
566 Py_ssize_t leftindex = deque->leftindex;
Raymond Hettinger57a86892011-01-25 21:43:29 +0000567 Py_ssize_t n = deque->len;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000568 Py_ssize_t i;
569 Py_ssize_t count = 0;
570 PyObject *item;
571 long start_state = deque->state;
572 int cmp;
Raymond Hettinger5f516ed2010-04-03 18:10:37 +0000573
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000574 for (i=0 ; i<n ; i++) {
575 item = leftblock->data[leftindex];
576 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
577 if (cmp > 0)
578 count++;
579 else if (cmp < 0)
580 return NULL;
Raymond Hettinger5f516ed2010-04-03 18:10:37 +0000581
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000582 if (start_state != deque->state) {
583 PyErr_SetString(PyExc_RuntimeError,
584 "deque mutated during iteration");
585 return NULL;
586 }
Raymond Hettinger5f516ed2010-04-03 18:10:37 +0000587
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000588 /* Advance left block/index pair */
589 leftindex++;
590 if (leftindex == BLOCKLEN) {
Raymond Hettinger57a86892011-01-25 21:43:29 +0000591 if (leftblock->rightlink == NULL) /* can occur when i==n-1 */
592 break;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000593 leftblock = leftblock->rightlink;
594 leftindex = 0;
595 }
596 }
597 return PyInt_FromSsize_t(count);
Raymond Hettinger5f516ed2010-04-03 18:10:37 +0000598}
599
600PyDoc_STRVAR(count_doc,
601"D.count(value) -> integer -- return number of occurrences of value");
602
Martin v. Löwis18e16552006-02-15 17:27:45 +0000603static Py_ssize_t
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000604deque_len(dequeobject *deque)
605{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000606 return deque->len;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000607}
608
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000609static PyObject *
610deque_remove(dequeobject *deque, PyObject *value)
611{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000612 Py_ssize_t i, n=deque->len;
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000613
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000614 for (i=0 ; i<n ; i++) {
615 PyObject *item = deque->leftblock->data[deque->leftindex];
616 int cmp = PyObject_RichCompareBool(item, value, Py_EQ);
Raymond Hettingerd73202c2005-03-19 00:00:51 +0000617
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000618 if (deque->len != n) {
619 PyErr_SetString(PyExc_IndexError,
620 "deque mutated during remove().");
621 return NULL;
622 }
623 if (cmp > 0) {
624 PyObject *tgt = deque_popleft(deque, NULL);
625 assert (tgt != NULL);
Raymond Hettinger79f2c5b2015-05-02 10:53:27 -0700626 if (_deque_rotate(deque, i))
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000627 return NULL;
Raymond Hettinger79f2c5b2015-05-02 10:53:27 -0700628 Py_DECREF(tgt);
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000629 Py_RETURN_NONE;
630 }
631 else if (cmp < 0) {
632 _deque_rotate(deque, i);
633 return NULL;
634 }
635 _deque_rotate(deque, -1);
636 }
637 PyErr_SetString(PyExc_ValueError, "deque.remove(x): x not in deque");
638 return NULL;
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000639}
640
641PyDoc_STRVAR(remove_doc,
642"D.remove(value) -- remove first occurrence of value.");
643
Benjamin Peterson40056de2013-01-12 21:22:18 -0500644static void
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000645deque_clear(dequeobject *deque)
646{
Raymond Hettingerd2a40732015-09-26 00:52:57 -0700647 block *b;
648 block *prevblock;
649 block *leftblock;
650 Py_ssize_t leftindex;
651 Py_ssize_t n;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000652 PyObject *item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000653
Raymond Hettingere9044272015-10-06 23:12:02 -0400654 if (Py_SIZE(deque) == 0)
655 return;
656
Raymond Hettingerd2a40732015-09-26 00:52:57 -0700657 /* During the process of clearing a deque, decrefs can cause the
658 deque to mutate. To avoid fatal confusion, we have to make the
659 deque empty before clearing the blocks and never refer to
660 anything via deque->ref while clearing. (This is the same
661 technique used for clearing lists, sets, and dicts.)
662
663 Making the deque empty requires allocating a new empty block. In
664 the unlikely event that memory is full, we fall back to an
665 alternate method that doesn't require a new block. Repeating
666 pops in a while-loop is slower, possibly re-entrant (and a clever
667 adversary could cause it to never terminate).
668 */
669
670 b = newblock(NULL, NULL, 0);
671 if (b == NULL) {
672 PyErr_Clear();
673 goto alternate_method;
674 }
675
676 /* Remember the old size, leftblock, and leftindex */
677 leftblock = deque->leftblock;
678 leftindex = deque->leftindex;
679 n = deque->len;
680
681 /* Set the deque to be empty using the newly allocated block */
682 deque->len = 0;
683 deque->leftblock = b;
684 deque->rightblock = b;
685 deque->leftindex = CENTER + 1;
686 deque->rightindex = CENTER;
687 deque->state++;
688
689 /* Now the old size, leftblock, and leftindex are disconnected from
690 the empty deque and we can use them to decref the pointers.
691 */
692 while (n--) {
693 item = leftblock->data[leftindex];
694 Py_DECREF(item);
695 leftindex++;
696 if (leftindex == BLOCKLEN && n) {
697 assert(leftblock->rightlink != NULL);
698 prevblock = leftblock;
699 leftblock = leftblock->rightlink;
700 leftindex = 0;
701 freeblock(prevblock);
702 }
703 }
704 assert(leftblock->rightlink == NULL);
705 freeblock(leftblock);
706 return;
707
708 alternate_method:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000709 while (deque->len) {
710 item = deque_pop(deque, NULL);
711 assert (item != NULL);
712 Py_DECREF(item);
713 }
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000714}
715
716static PyObject *
Raymond Hettinger33fcf9d2008-07-24 00:08:18 +0000717deque_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000718{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000719 block *b;
720 PyObject *item;
721 Py_ssize_t n, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000722
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000723 if (i < 0 || i >= deque->len) {
724 PyErr_SetString(PyExc_IndexError,
725 "deque index out of range");
726 return NULL;
727 }
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000728
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000729 if (i == 0) {
730 i = deque->leftindex;
731 b = deque->leftblock;
732 } else if (i == deque->len - 1) {
733 i = deque->rightindex;
734 b = deque->rightblock;
735 } else {
736 i += deque->leftindex;
737 n = i / BLOCKLEN;
738 i %= BLOCKLEN;
739 if (index < (deque->len >> 1)) {
740 b = deque->leftblock;
741 while (n--)
742 b = b->rightlink;
743 } else {
744 n = (deque->leftindex + deque->len - 1) / BLOCKLEN - n;
745 b = deque->rightblock;
746 while (n--)
747 b = b->leftlink;
748 }
749 }
750 item = b->data[i];
751 Py_INCREF(item);
752 return item;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000753}
754
Raymond Hettinger616f4f62004-06-26 04:42:06 +0000755/* delitem() implemented in terms of rotate for simplicity and reasonable
756 performance near the end points. If for some reason this method becomes
Tim Peters1065f752004-10-01 01:03:29 +0000757 popular, it is not hard to re-implement this using direct data movement
Raymond Hettinger616f4f62004-06-26 04:42:06 +0000758 (similar to code in list slice assignment) and achieve a two or threefold
759 performance boost.
760*/
761
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000762static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000763deque_del_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000764{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000765 PyObject *item;
Raymond Hettinger79f2c5b2015-05-02 10:53:27 -0700766 int rv;
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000767
Benjamin Peterson5863a392015-05-15 12:19:18 -0400768 assert (i >= 0 && i < deque->len);
Raymond Hettinger79f2c5b2015-05-02 10:53:27 -0700769 if (_deque_rotate(deque, -i))
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000770 return -1;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000771 item = deque_popleft(deque, NULL);
Raymond Hettinger79f2c5b2015-05-02 10:53:27 -0700772 rv = _deque_rotate(deque, i);
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000773 assert (item != NULL);
774 Py_DECREF(item);
Raymond Hettinger79f2c5b2015-05-02 10:53:27 -0700775 return rv;
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000776}
777
778static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000779deque_ass_item(dequeobject *deque, Py_ssize_t i, PyObject *v)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000780{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000781 PyObject *old_value;
782 block *b;
783 Py_ssize_t n, len=deque->len, halflen=(len+1)>>1, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000784
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000785 if (i < 0 || i >= len) {
786 PyErr_SetString(PyExc_IndexError,
787 "deque index out of range");
788 return -1;
789 }
790 if (v == NULL)
791 return deque_del_item(deque, i);
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000792
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000793 i += deque->leftindex;
794 n = i / BLOCKLEN;
795 i %= BLOCKLEN;
796 if (index <= halflen) {
797 b = deque->leftblock;
798 while (n--)
799 b = b->rightlink;
800 } else {
801 n = (deque->leftindex + len - 1) / BLOCKLEN - n;
802 b = deque->rightblock;
803 while (n--)
804 b = b->leftlink;
805 }
806 Py_INCREF(v);
807 old_value = b->data[i];
808 b->data[i] = v;
809 Py_DECREF(old_value);
810 return 0;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000811}
812
813static PyObject *
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000814deque_clearmethod(dequeobject *deque)
815{
Benjamin Peterson40056de2013-01-12 21:22:18 -0500816 deque_clear(deque);
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000817 Py_RETURN_NONE;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000818}
819
820PyDoc_STRVAR(clear_doc, "Remove all elements from the deque.");
821
822static void
823deque_dealloc(dequeobject *deque)
824{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000825 PyObject_GC_UnTrack(deque);
826 if (deque->weakreflist != NULL)
827 PyObject_ClearWeakRefs((PyObject *) deque);
828 if (deque->leftblock != NULL) {
829 deque_clear(deque);
830 assert(deque->leftblock != NULL);
831 freeblock(deque->leftblock);
832 }
833 deque->leftblock = NULL;
834 deque->rightblock = NULL;
835 Py_TYPE(deque)->tp_free(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000836}
837
838static int
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000839deque_traverse(dequeobject *deque, visitproc visit, void *arg)
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000840{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000841 block *b;
842 PyObject *item;
843 Py_ssize_t index;
844 Py_ssize_t indexlo = deque->leftindex;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000845
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000846 for (b = deque->leftblock; b != NULL; b = b->rightlink) {
847 const Py_ssize_t indexhi = b == deque->rightblock ?
848 deque->rightindex :
849 BLOCKLEN - 1;
Tim Peters10c7e862004-10-01 02:01:04 +0000850
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000851 for (index = indexlo; index <= indexhi; ++index) {
852 item = b->data[index];
853 Py_VISIT(item);
854 }
855 indexlo = 0;
856 }
857 return 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000858}
859
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000860static PyObject *
861deque_copy(PyObject *deque)
862{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000863 if (((dequeobject *)deque)->maxlen == -1)
864 return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "O", deque, NULL);
865 else
866 return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "Oi",
867 deque, ((dequeobject *)deque)->maxlen, NULL);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000868}
869
870PyDoc_STRVAR(copy_doc, "Return a shallow copy of a deque.");
871
872static PyObject *
873deque_reduce(dequeobject *deque)
874{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000875 PyObject *dict, *result, *aslist;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000876
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000877 dict = PyObject_GetAttrString((PyObject *)deque, "__dict__");
878 if (dict == NULL)
879 PyErr_Clear();
880 aslist = PySequence_List((PyObject *)deque);
881 if (aslist == NULL) {
882 Py_XDECREF(dict);
883 return NULL;
884 }
885 if (dict == NULL) {
886 if (deque->maxlen == -1)
887 result = Py_BuildValue("O(O)", Py_TYPE(deque), aslist);
888 else
889 result = Py_BuildValue("O(On)", Py_TYPE(deque), aslist, deque->maxlen);
890 } else {
891 if (deque->maxlen == -1)
892 result = Py_BuildValue("O(OO)O", Py_TYPE(deque), aslist, Py_None, dict);
893 else
894 result = Py_BuildValue("O(On)O", Py_TYPE(deque), aslist, deque->maxlen, dict);
895 }
896 Py_XDECREF(dict);
897 Py_DECREF(aslist);
898 return result;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000899}
900
901PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
902
903static PyObject *
904deque_repr(PyObject *deque)
905{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000906 PyObject *aslist, *result, *fmt;
907 int i;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000908
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000909 i = Py_ReprEnter(deque);
910 if (i != 0) {
911 if (i < 0)
912 return NULL;
913 return PyString_FromString("[...]");
914 }
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000915
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000916 aslist = PySequence_List(deque);
917 if (aslist == NULL) {
918 Py_ReprLeave(deque);
919 return NULL;
920 }
921 if (((dequeobject *)deque)->maxlen != -1)
922 fmt = PyString_FromFormat("deque(%%r, maxlen=%zd)",
923 ((dequeobject *)deque)->maxlen);
924 else
925 fmt = PyString_FromString("deque(%r)");
926 if (fmt == NULL) {
927 Py_DECREF(aslist);
928 Py_ReprLeave(deque);
929 return NULL;
930 }
931 result = PyString_Format(fmt, aslist);
932 Py_DECREF(fmt);
933 Py_DECREF(aslist);
934 Py_ReprLeave(deque);
935 return result;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000936}
937
938static int
939deque_tp_print(PyObject *deque, FILE *fp, int flags)
940{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000941 PyObject *it, *item;
942 char *emit = ""; /* No separator emitted on first pass */
943 char *separator = ", ";
944 int i;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000945
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000946 i = Py_ReprEnter(deque);
947 if (i != 0) {
948 if (i < 0)
949 return i;
950 Py_BEGIN_ALLOW_THREADS
951 fputs("[...]", fp);
952 Py_END_ALLOW_THREADS
953 return 0;
954 }
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000955
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000956 it = PyObject_GetIter(deque);
957 if (it == NULL)
958 return -1;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000959
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000960 Py_BEGIN_ALLOW_THREADS
961 fputs("deque([", fp);
962 Py_END_ALLOW_THREADS
963 while ((item = PyIter_Next(it)) != NULL) {
964 Py_BEGIN_ALLOW_THREADS
965 fputs(emit, fp);
966 Py_END_ALLOW_THREADS
967 emit = separator;
968 if (PyObject_Print(item, fp, 0) != 0) {
969 Py_DECREF(item);
970 Py_DECREF(it);
971 Py_ReprLeave(deque);
972 return -1;
973 }
974 Py_DECREF(item);
975 }
976 Py_ReprLeave(deque);
977 Py_DECREF(it);
978 if (PyErr_Occurred())
979 return -1;
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000980
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000981 Py_BEGIN_ALLOW_THREADS
982 if (((dequeobject *)deque)->maxlen == -1)
983 fputs("])", fp);
984 else
985 fprintf(fp, "], maxlen=%" PY_FORMAT_SIZE_T "d)", ((dequeobject *)deque)->maxlen);
986 Py_END_ALLOW_THREADS
987 return 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000988}
989
Raymond Hettinger738ec902004-02-29 02:15:56 +0000990static PyObject *
991deque_richcompare(PyObject *v, PyObject *w, int op)
992{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000993 PyObject *it1=NULL, *it2=NULL, *x, *y;
994 Py_ssize_t vs, ws;
995 int b, cmp=-1;
Raymond Hettinger738ec902004-02-29 02:15:56 +0000996
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000997 if (!PyObject_TypeCheck(v, &deque_type) ||
998 !PyObject_TypeCheck(w, &deque_type)) {
999 Py_INCREF(Py_NotImplemented);
1000 return Py_NotImplemented;
1001 }
Raymond Hettinger738ec902004-02-29 02:15:56 +00001002
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001003 /* Shortcuts */
1004 vs = ((dequeobject *)v)->len;
1005 ws = ((dequeobject *)w)->len;
1006 if (op == Py_EQ) {
1007 if (v == w)
1008 Py_RETURN_TRUE;
1009 if (vs != ws)
1010 Py_RETURN_FALSE;
1011 }
1012 if (op == Py_NE) {
1013 if (v == w)
1014 Py_RETURN_FALSE;
1015 if (vs != ws)
1016 Py_RETURN_TRUE;
1017 }
Raymond Hettinger738ec902004-02-29 02:15:56 +00001018
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001019 /* Search for the first index where items are different */
1020 it1 = PyObject_GetIter(v);
1021 if (it1 == NULL)
1022 goto done;
1023 it2 = PyObject_GetIter(w);
1024 if (it2 == NULL)
1025 goto done;
1026 for (;;) {
1027 x = PyIter_Next(it1);
1028 if (x == NULL && PyErr_Occurred())
1029 goto done;
1030 y = PyIter_Next(it2);
1031 if (x == NULL || y == NULL)
1032 break;
1033 b = PyObject_RichCompareBool(x, y, Py_EQ);
1034 if (b == 0) {
1035 cmp = PyObject_RichCompareBool(x, y, op);
1036 Py_DECREF(x);
1037 Py_DECREF(y);
1038 goto done;
1039 }
1040 Py_DECREF(x);
1041 Py_DECREF(y);
1042 if (b == -1)
1043 goto done;
1044 }
1045 /* We reached the end of one deque or both */
1046 Py_XDECREF(x);
1047 Py_XDECREF(y);
1048 if (PyErr_Occurred())
1049 goto done;
1050 switch (op) {
1051 case Py_LT: cmp = y != NULL; break; /* if w was longer */
1052 case Py_LE: cmp = x == NULL; break; /* if v was not longer */
1053 case Py_EQ: cmp = x == y; break; /* if we reached the end of both */
1054 case Py_NE: cmp = x != y; break; /* if one deque continues */
1055 case Py_GT: cmp = x != NULL; break; /* if v was longer */
1056 case Py_GE: cmp = y == NULL; break; /* if w was not longer */
1057 }
Tim Peters1065f752004-10-01 01:03:29 +00001058
Raymond Hettinger738ec902004-02-29 02:15:56 +00001059done:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001060 Py_XDECREF(it1);
1061 Py_XDECREF(it2);
1062 if (cmp == 1)
1063 Py_RETURN_TRUE;
1064 if (cmp == 0)
1065 Py_RETURN_FALSE;
1066 return NULL;
Raymond Hettinger738ec902004-02-29 02:15:56 +00001067}
1068
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001069static int
Raymond Hettingera7fc4b12007-10-05 02:47:07 +00001070deque_init(dequeobject *deque, PyObject *args, PyObject *kwdargs)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001071{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001072 PyObject *iterable = NULL;
1073 PyObject *maxlenobj = NULL;
1074 Py_ssize_t maxlen = -1;
1075 char *kwlist[] = {"iterable", "maxlen", 0};
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001076
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001077 if (!PyArg_ParseTupleAndKeywords(args, kwdargs, "|OO:deque", kwlist, &iterable, &maxlenobj))
1078 return -1;
1079 if (maxlenobj != NULL && maxlenobj != Py_None) {
1080 maxlen = PyInt_AsSsize_t(maxlenobj);
1081 if (maxlen == -1 && PyErr_Occurred())
1082 return -1;
1083 if (maxlen < 0) {
1084 PyErr_SetString(PyExc_ValueError, "maxlen must be non-negative");
1085 return -1;
1086 }
1087 }
1088 deque->maxlen = maxlen;
Raymond Hettingere9044272015-10-06 23:12:02 -04001089 if (Py_SIZE(deque) > 0)
1090 deque_clear(deque);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001091 if (iterable != NULL) {
1092 PyObject *rv = deque_extend(deque, iterable);
1093 if (rv == NULL)
1094 return -1;
1095 Py_DECREF(rv);
1096 }
1097 return 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001098}
1099
Raymond Hettinger56411aa2009-03-10 12:50:59 +00001100static PyObject *
Jesus Cead4e58dc2012-08-03 14:48:23 +02001101deque_sizeof(dequeobject *deque, void *unused)
1102{
1103 Py_ssize_t res;
1104 Py_ssize_t blocks;
1105
1106 res = sizeof(dequeobject);
1107 blocks = (deque->leftindex + deque->len + BLOCKLEN - 1) / BLOCKLEN;
1108 assert(deque->leftindex + deque->len - 1 ==
1109 (blocks - 1) * BLOCKLEN + deque->rightindex);
1110 res += blocks * sizeof(block);
1111 return PyLong_FromSsize_t(res);
1112}
1113
1114PyDoc_STRVAR(sizeof_doc,
1115"D.__sizeof__() -- size of D in memory, in bytes");
1116
1117static PyObject *
Raymond Hettinger56411aa2009-03-10 12:50:59 +00001118deque_get_maxlen(dequeobject *deque)
1119{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001120 if (deque->maxlen == -1)
1121 Py_RETURN_NONE;
1122 return PyInt_FromSsize_t(deque->maxlen);
Raymond Hettinger56411aa2009-03-10 12:50:59 +00001123}
1124
1125static PyGetSetDef deque_getset[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001126 {"maxlen", (getter)deque_get_maxlen, (setter)NULL,
1127 "maximum size of a deque or None if unbounded"},
1128 {0}
Raymond Hettinger56411aa2009-03-10 12:50:59 +00001129};
1130
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001131static PySequenceMethods deque_as_sequence = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001132 (lenfunc)deque_len, /* sq_length */
1133 0, /* sq_concat */
1134 0, /* sq_repeat */
1135 (ssizeargfunc)deque_item, /* sq_item */
1136 0, /* sq_slice */
1137 (ssizeobjargproc)deque_ass_item, /* sq_ass_item */
1138 0, /* sq_ass_slice */
1139 0, /* sq_contains */
1140 (binaryfunc)deque_inplace_concat, /* sq_inplace_concat */
1141 0, /* sq_inplace_repeat */
Raymond Hettinger0b3263b2009-12-10 06:00:33 +00001142
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001143};
1144
1145/* deque object ********************************************************/
1146
1147static PyObject *deque_iter(dequeobject *deque);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001148static PyObject *deque_reviter(dequeobject *deque);
Tim Peters1065f752004-10-01 01:03:29 +00001149PyDoc_STRVAR(reversed_doc,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001150 "D.__reversed__() -- return a reverse iterator over the deque");
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001151
1152static PyMethodDef deque_methods[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001153 {"append", (PyCFunction)deque_append,
1154 METH_O, append_doc},
1155 {"appendleft", (PyCFunction)deque_appendleft,
1156 METH_O, appendleft_doc},
1157 {"clear", (PyCFunction)deque_clearmethod,
1158 METH_NOARGS, clear_doc},
1159 {"__copy__", (PyCFunction)deque_copy,
1160 METH_NOARGS, copy_doc},
1161 {"count", (PyCFunction)deque_count,
1162 METH_O, count_doc},
1163 {"extend", (PyCFunction)deque_extend,
1164 METH_O, extend_doc},
1165 {"extendleft", (PyCFunction)deque_extendleft,
1166 METH_O, extendleft_doc},
1167 {"pop", (PyCFunction)deque_pop,
1168 METH_NOARGS, pop_doc},
1169 {"popleft", (PyCFunction)deque_popleft,
1170 METH_NOARGS, popleft_doc},
1171 {"__reduce__", (PyCFunction)deque_reduce,
1172 METH_NOARGS, reduce_doc},
1173 {"remove", (PyCFunction)deque_remove,
1174 METH_O, remove_doc},
1175 {"__reversed__", (PyCFunction)deque_reviter,
1176 METH_NOARGS, reversed_doc},
1177 {"reverse", (PyCFunction)deque_reverse,
1178 METH_NOARGS, reverse_doc},
1179 {"rotate", (PyCFunction)deque_rotate,
Jesus Cead4e58dc2012-08-03 14:48:23 +02001180 METH_VARARGS, rotate_doc},
1181 {"__sizeof__", (PyCFunction)deque_sizeof,
1182 METH_NOARGS, sizeof_doc},
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001183 {NULL, NULL} /* sentinel */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001184};
1185
1186PyDoc_STRVAR(deque_doc,
Andrew Svetlov227f59b2012-10-31 11:50:00 +02001187"deque([iterable[, maxlen]]) --> deque object\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001188\n\
Raymond Hettingerdb9d64b2011-03-29 17:28:25 -07001189Build an ordered collection with optimized access from its endpoints.");
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001190
Neal Norwitz87f10132004-02-29 15:40:53 +00001191static PyTypeObject deque_type = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001192 PyVarObject_HEAD_INIT(NULL, 0)
1193 "collections.deque", /* tp_name */
1194 sizeof(dequeobject), /* tp_basicsize */
1195 0, /* tp_itemsize */
1196 /* methods */
1197 (destructor)deque_dealloc, /* tp_dealloc */
1198 deque_tp_print, /* tp_print */
1199 0, /* tp_getattr */
1200 0, /* tp_setattr */
1201 0, /* tp_compare */
1202 deque_repr, /* tp_repr */
1203 0, /* tp_as_number */
1204 &deque_as_sequence, /* tp_as_sequence */
1205 0, /* tp_as_mapping */
1206 (hashfunc)PyObject_HashNotImplemented, /* tp_hash */
1207 0, /* tp_call */
1208 0, /* tp_str */
1209 PyObject_GenericGetAttr, /* tp_getattro */
1210 0, /* tp_setattro */
1211 0, /* tp_as_buffer */
1212 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
1213 Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
1214 deque_doc, /* tp_doc */
1215 (traverseproc)deque_traverse, /* tp_traverse */
1216 (inquiry)deque_clear, /* tp_clear */
1217 (richcmpfunc)deque_richcompare, /* tp_richcompare */
1218 offsetof(dequeobject, weakreflist), /* tp_weaklistoffset*/
1219 (getiterfunc)deque_iter, /* tp_iter */
1220 0, /* tp_iternext */
1221 deque_methods, /* tp_methods */
1222 0, /* tp_members */
1223 deque_getset, /* tp_getset */
1224 0, /* tp_base */
1225 0, /* tp_dict */
1226 0, /* tp_descr_get */
1227 0, /* tp_descr_set */
1228 0, /* tp_dictoffset */
1229 (initproc)deque_init, /* tp_init */
1230 PyType_GenericAlloc, /* tp_alloc */
1231 deque_new, /* tp_new */
1232 PyObject_GC_Del, /* tp_free */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001233};
1234
1235/*********************** Deque Iterator **************************/
1236
1237typedef struct {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001238 PyObject_HEAD
1239 Py_ssize_t index;
1240 block *b;
1241 dequeobject *deque;
1242 long state; /* state when the iterator is created */
1243 Py_ssize_t counter; /* number of items remaining for iteration */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001244} dequeiterobject;
1245
Martin v. Löwis111c1802008-06-13 07:47:47 +00001246static PyTypeObject dequeiter_type;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001247
1248static PyObject *
1249deque_iter(dequeobject *deque)
1250{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001251 dequeiterobject *it;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001252
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001253 it = PyObject_GC_New(dequeiterobject, &dequeiter_type);
1254 if (it == NULL)
1255 return NULL;
1256 it->b = deque->leftblock;
1257 it->index = deque->leftindex;
1258 Py_INCREF(deque);
1259 it->deque = deque;
1260 it->state = deque->state;
1261 it->counter = deque->len;
1262 PyObject_GC_Track(it);
1263 return (PyObject *)it;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001264}
1265
Antoine Pitrouaa687902009-01-01 14:11:22 +00001266static int
1267dequeiter_traverse(dequeiterobject *dio, visitproc visit, void *arg)
1268{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001269 Py_VISIT(dio->deque);
1270 return 0;
Antoine Pitrouaa687902009-01-01 14:11:22 +00001271}
1272
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001273static void
1274dequeiter_dealloc(dequeiterobject *dio)
1275{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001276 Py_XDECREF(dio->deque);
1277 PyObject_GC_Del(dio);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001278}
1279
1280static PyObject *
1281dequeiter_next(dequeiterobject *it)
1282{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001283 PyObject *item;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001284
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001285 if (it->deque->state != it->state) {
1286 it->counter = 0;
1287 PyErr_SetString(PyExc_RuntimeError,
1288 "deque mutated during iteration");
1289 return NULL;
1290 }
1291 if (it->counter == 0)
1292 return NULL;
1293 assert (!(it->b == it->deque->rightblock &&
1294 it->index > it->deque->rightindex));
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001295
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001296 item = it->b->data[it->index];
1297 it->index++;
1298 it->counter--;
1299 if (it->index == BLOCKLEN && it->counter > 0) {
1300 assert (it->b->rightlink != NULL);
1301 it->b = it->b->rightlink;
1302 it->index = 0;
1303 }
1304 Py_INCREF(item);
1305 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001306}
1307
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001308static PyObject *
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001309dequeiter_len(dequeiterobject *it)
1310{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001311 return PyInt_FromLong(it->counter);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001312}
1313
Armin Rigof5b3e362006-02-11 21:32:43 +00001314PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001315
1316static PyMethodDef dequeiter_methods[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001317 {"__length_hint__", (PyCFunction)dequeiter_len, METH_NOARGS, length_hint_doc},
1318 {NULL, NULL} /* sentinel */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001319};
1320
Martin v. Löwis111c1802008-06-13 07:47:47 +00001321static PyTypeObject dequeiter_type = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001322 PyVarObject_HEAD_INIT(NULL, 0)
1323 "deque_iterator", /* tp_name */
1324 sizeof(dequeiterobject), /* tp_basicsize */
1325 0, /* tp_itemsize */
1326 /* methods */
1327 (destructor)dequeiter_dealloc, /* tp_dealloc */
1328 0, /* tp_print */
1329 0, /* tp_getattr */
1330 0, /* tp_setattr */
1331 0, /* tp_compare */
1332 0, /* tp_repr */
1333 0, /* tp_as_number */
1334 0, /* tp_as_sequence */
1335 0, /* tp_as_mapping */
1336 0, /* tp_hash */
1337 0, /* tp_call */
1338 0, /* tp_str */
1339 PyObject_GenericGetAttr, /* tp_getattro */
1340 0, /* tp_setattro */
1341 0, /* tp_as_buffer */
1342 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
1343 0, /* tp_doc */
1344 (traverseproc)dequeiter_traverse, /* tp_traverse */
1345 0, /* tp_clear */
1346 0, /* tp_richcompare */
1347 0, /* tp_weaklistoffset */
1348 PyObject_SelfIter, /* tp_iter */
1349 (iternextfunc)dequeiter_next, /* tp_iternext */
1350 dequeiter_methods, /* tp_methods */
1351 0,
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001352};
1353
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001354/*********************** Deque Reverse Iterator **************************/
1355
Martin v. Löwis111c1802008-06-13 07:47:47 +00001356static PyTypeObject dequereviter_type;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001357
1358static PyObject *
1359deque_reviter(dequeobject *deque)
1360{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001361 dequeiterobject *it;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001362
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001363 it = PyObject_GC_New(dequeiterobject, &dequereviter_type);
1364 if (it == NULL)
1365 return NULL;
1366 it->b = deque->rightblock;
1367 it->index = deque->rightindex;
1368 Py_INCREF(deque);
1369 it->deque = deque;
1370 it->state = deque->state;
1371 it->counter = deque->len;
1372 PyObject_GC_Track(it);
1373 return (PyObject *)it;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001374}
1375
1376static PyObject *
1377dequereviter_next(dequeiterobject *it)
1378{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001379 PyObject *item;
1380 if (it->counter == 0)
1381 return NULL;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001382
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001383 if (it->deque->state != it->state) {
1384 it->counter = 0;
1385 PyErr_SetString(PyExc_RuntimeError,
1386 "deque mutated during iteration");
1387 return NULL;
1388 }
1389 assert (!(it->b == it->deque->leftblock &&
1390 it->index < it->deque->leftindex));
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001391
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001392 item = it->b->data[it->index];
1393 it->index--;
1394 it->counter--;
1395 if (it->index == -1 && it->counter > 0) {
1396 assert (it->b->leftlink != NULL);
1397 it->b = it->b->leftlink;
1398 it->index = BLOCKLEN - 1;
1399 }
1400 Py_INCREF(item);
1401 return item;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001402}
1403
Martin v. Löwis111c1802008-06-13 07:47:47 +00001404static PyTypeObject dequereviter_type = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001405 PyVarObject_HEAD_INIT(NULL, 0)
1406 "deque_reverse_iterator", /* tp_name */
1407 sizeof(dequeiterobject), /* tp_basicsize */
1408 0, /* tp_itemsize */
1409 /* methods */
1410 (destructor)dequeiter_dealloc, /* tp_dealloc */
1411 0, /* tp_print */
1412 0, /* tp_getattr */
1413 0, /* tp_setattr */
1414 0, /* tp_compare */
1415 0, /* tp_repr */
1416 0, /* tp_as_number */
1417 0, /* tp_as_sequence */
1418 0, /* tp_as_mapping */
1419 0, /* tp_hash */
1420 0, /* tp_call */
1421 0, /* tp_str */
1422 PyObject_GenericGetAttr, /* tp_getattro */
1423 0, /* tp_setattro */
1424 0, /* tp_as_buffer */
1425 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
1426 0, /* tp_doc */
1427 (traverseproc)dequeiter_traverse, /* tp_traverse */
1428 0, /* tp_clear */
1429 0, /* tp_richcompare */
1430 0, /* tp_weaklistoffset */
1431 PyObject_SelfIter, /* tp_iter */
1432 (iternextfunc)dequereviter_next, /* tp_iternext */
1433 dequeiter_methods, /* tp_methods */
1434 0,
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001435};
1436
Guido van Rossum1968ad32006-02-25 22:38:04 +00001437/* defaultdict type *********************************************************/
1438
1439typedef struct {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001440 PyDictObject dict;
1441 PyObject *default_factory;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001442} defdictobject;
1443
1444static PyTypeObject defdict_type; /* Forward */
1445
1446PyDoc_STRVAR(defdict_missing_doc,
1447"__missing__(key) # Called by __getitem__ for missing key; pseudo-code:\n\
Georg Brandlb51a57e2007-03-06 13:32:52 +00001448 if self.default_factory is None: raise KeyError((key,))\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00001449 self[key] = value = self.default_factory()\n\
1450 return value\n\
1451");
1452
1453static PyObject *
1454defdict_missing(defdictobject *dd, PyObject *key)
1455{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001456 PyObject *factory = dd->default_factory;
1457 PyObject *value;
1458 if (factory == NULL || factory == Py_None) {
1459 /* XXX Call dict.__missing__(key) */
1460 PyObject *tup;
1461 tup = PyTuple_Pack(1, key);
1462 if (!tup) return NULL;
1463 PyErr_SetObject(PyExc_KeyError, tup);
1464 Py_DECREF(tup);
1465 return NULL;
1466 }
1467 value = PyEval_CallObject(factory, NULL);
1468 if (value == NULL)
1469 return value;
1470 if (PyObject_SetItem((PyObject *)dd, key, value) < 0) {
1471 Py_DECREF(value);
1472 return NULL;
1473 }
1474 return value;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001475}
1476
1477PyDoc_STRVAR(defdict_copy_doc, "D.copy() -> a shallow copy of D.");
1478
1479static PyObject *
1480defdict_copy(defdictobject *dd)
1481{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001482 /* This calls the object's class. That only works for subclasses
1483 whose class constructor has the same signature. Subclasses that
1484 define a different constructor signature must override copy().
1485 */
Raymond Hettinger8fdab952009-08-04 19:08:05 +00001486
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001487 if (dd->default_factory == NULL)
1488 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd), Py_None, dd, NULL);
1489 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd),
1490 dd->default_factory, dd, NULL);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001491}
1492
1493static PyObject *
1494defdict_reduce(defdictobject *dd)
1495{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001496 /* __reduce__ must return a 5-tuple as follows:
Guido van Rossum1968ad32006-02-25 22:38:04 +00001497
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001498 - factory function
1499 - tuple of args for the factory function
1500 - additional state (here None)
1501 - sequence iterator (here None)
1502 - dictionary iterator (yielding successive (key, value) pairs
Guido van Rossum1968ad32006-02-25 22:38:04 +00001503
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001504 This API is used by pickle.py and copy.py.
Guido van Rossum1968ad32006-02-25 22:38:04 +00001505
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001506 For this to be useful with pickle.py, the default_factory
1507 must be picklable; e.g., None, a built-in, or a global
1508 function in a module or package.
Guido van Rossum1968ad32006-02-25 22:38:04 +00001509
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001510 Both shallow and deep copying are supported, but for deep
1511 copying, the default_factory must be deep-copyable; e.g. None,
1512 or a built-in (functions are not copyable at this time).
Guido van Rossum1968ad32006-02-25 22:38:04 +00001513
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001514 This only works for subclasses as long as their constructor
1515 signature is compatible; the first argument must be the
1516 optional default_factory, defaulting to None.
1517 */
1518 PyObject *args;
1519 PyObject *items;
1520 PyObject *result;
1521 if (dd->default_factory == NULL || dd->default_factory == Py_None)
1522 args = PyTuple_New(0);
1523 else
1524 args = PyTuple_Pack(1, dd->default_factory);
1525 if (args == NULL)
1526 return NULL;
1527 items = PyObject_CallMethod((PyObject *)dd, "iteritems", "()");
1528 if (items == NULL) {
1529 Py_DECREF(args);
1530 return NULL;
1531 }
1532 result = PyTuple_Pack(5, Py_TYPE(dd), args,
1533 Py_None, Py_None, items);
1534 Py_DECREF(items);
1535 Py_DECREF(args);
1536 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001537}
1538
1539static PyMethodDef defdict_methods[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001540 {"__missing__", (PyCFunction)defdict_missing, METH_O,
1541 defdict_missing_doc},
1542 {"copy", (PyCFunction)defdict_copy, METH_NOARGS,
1543 defdict_copy_doc},
1544 {"__copy__", (PyCFunction)defdict_copy, METH_NOARGS,
1545 defdict_copy_doc},
1546 {"__reduce__", (PyCFunction)defdict_reduce, METH_NOARGS,
1547 reduce_doc},
1548 {NULL}
Guido van Rossum1968ad32006-02-25 22:38:04 +00001549};
1550
1551static PyMemberDef defdict_members[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001552 {"default_factory", T_OBJECT,
1553 offsetof(defdictobject, default_factory), 0,
1554 PyDoc_STR("Factory for default value called by __missing__().")},
1555 {NULL}
Guido van Rossum1968ad32006-02-25 22:38:04 +00001556};
1557
1558static void
1559defdict_dealloc(defdictobject *dd)
1560{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001561 Py_CLEAR(dd->default_factory);
1562 PyDict_Type.tp_dealloc((PyObject *)dd);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001563}
1564
1565static int
1566defdict_print(defdictobject *dd, FILE *fp, int flags)
1567{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001568 int sts;
1569 Py_BEGIN_ALLOW_THREADS
1570 fprintf(fp, "defaultdict(");
1571 Py_END_ALLOW_THREADS
1572 if (dd->default_factory == NULL) {
1573 Py_BEGIN_ALLOW_THREADS
1574 fprintf(fp, "None");
1575 Py_END_ALLOW_THREADS
1576 } else {
1577 PyObject_Print(dd->default_factory, fp, 0);
1578 }
1579 Py_BEGIN_ALLOW_THREADS
1580 fprintf(fp, ", ");
1581 Py_END_ALLOW_THREADS
1582 sts = PyDict_Type.tp_print((PyObject *)dd, fp, 0);
1583 Py_BEGIN_ALLOW_THREADS
1584 fprintf(fp, ")");
1585 Py_END_ALLOW_THREADS
1586 return sts;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001587}
1588
1589static PyObject *
1590defdict_repr(defdictobject *dd)
1591{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001592 PyObject *defrepr;
1593 PyObject *baserepr;
1594 PyObject *result;
1595 baserepr = PyDict_Type.tp_repr((PyObject *)dd);
1596 if (baserepr == NULL)
1597 return NULL;
1598 if (dd->default_factory == NULL)
1599 defrepr = PyString_FromString("None");
1600 else
1601 {
1602 int status = Py_ReprEnter(dd->default_factory);
1603 if (status != 0) {
Antoine Pitrouc39cd782012-02-15 02:42:46 +01001604 if (status < 0) {
1605 Py_DECREF(baserepr);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001606 return NULL;
Antoine Pitrouc39cd782012-02-15 02:42:46 +01001607 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001608 defrepr = PyString_FromString("...");
1609 }
1610 else
1611 defrepr = PyObject_Repr(dd->default_factory);
1612 Py_ReprLeave(dd->default_factory);
1613 }
1614 if (defrepr == NULL) {
1615 Py_DECREF(baserepr);
1616 return NULL;
1617 }
1618 result = PyString_FromFormat("defaultdict(%s, %s)",
1619 PyString_AS_STRING(defrepr),
1620 PyString_AS_STRING(baserepr));
1621 Py_DECREF(defrepr);
1622 Py_DECREF(baserepr);
1623 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001624}
1625
1626static int
1627defdict_traverse(PyObject *self, visitproc visit, void *arg)
1628{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001629 Py_VISIT(((defdictobject *)self)->default_factory);
1630 return PyDict_Type.tp_traverse(self, visit, arg);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001631}
1632
1633static int
1634defdict_tp_clear(defdictobject *dd)
1635{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001636 Py_CLEAR(dd->default_factory);
1637 return PyDict_Type.tp_clear((PyObject *)dd);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001638}
1639
1640static int
1641defdict_init(PyObject *self, PyObject *args, PyObject *kwds)
1642{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001643 defdictobject *dd = (defdictobject *)self;
1644 PyObject *olddefault = dd->default_factory;
1645 PyObject *newdefault = NULL;
1646 PyObject *newargs;
1647 int result;
1648 if (args == NULL || !PyTuple_Check(args))
1649 newargs = PyTuple_New(0);
1650 else {
1651 Py_ssize_t n = PyTuple_GET_SIZE(args);
1652 if (n > 0) {
1653 newdefault = PyTuple_GET_ITEM(args, 0);
1654 if (!PyCallable_Check(newdefault) && newdefault != Py_None) {
1655 PyErr_SetString(PyExc_TypeError,
Raymond Hettingerfe13eac2015-07-20 03:08:09 -04001656 "first argument must be callable or None");
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001657 return -1;
1658 }
1659 }
1660 newargs = PySequence_GetSlice(args, 1, n);
1661 }
1662 if (newargs == NULL)
1663 return -1;
1664 Py_XINCREF(newdefault);
1665 dd->default_factory = newdefault;
1666 result = PyDict_Type.tp_init(self, newargs, kwds);
1667 Py_DECREF(newargs);
1668 Py_XDECREF(olddefault);
1669 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001670}
1671
1672PyDoc_STRVAR(defdict_doc,
Benjamin Peterson06e486c2014-01-13 23:56:05 -05001673"defaultdict(default_factory[, ...]) --> dict with default factory\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00001674\n\
1675The default factory is called without arguments to produce\n\
1676a new value when a key is not present, in __getitem__ only.\n\
1677A defaultdict compares equal to a dict with the same items.\n\
Benjamin Peterson06e486c2014-01-13 23:56:05 -05001678All remaining arguments are treated the same as if they were\n\
1679passed to the dict constructor, including keyword arguments.\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00001680");
1681
Anthony Baxter3b8ff312006-04-04 15:05:23 +00001682/* See comment in xxsubtype.c */
1683#define DEFERRED_ADDRESS(ADDR) 0
1684
Guido van Rossum1968ad32006-02-25 22:38:04 +00001685static PyTypeObject defdict_type = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001686 PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0)
1687 "collections.defaultdict", /* tp_name */
1688 sizeof(defdictobject), /* tp_basicsize */
1689 0, /* tp_itemsize */
1690 /* methods */
1691 (destructor)defdict_dealloc, /* tp_dealloc */
1692 (printfunc)defdict_print, /* tp_print */
1693 0, /* tp_getattr */
1694 0, /* tp_setattr */
1695 0, /* tp_compare */
1696 (reprfunc)defdict_repr, /* tp_repr */
1697 0, /* tp_as_number */
1698 0, /* tp_as_sequence */
1699 0, /* tp_as_mapping */
1700 0, /* tp_hash */
1701 0, /* tp_call */
1702 0, /* tp_str */
1703 PyObject_GenericGetAttr, /* tp_getattro */
1704 0, /* tp_setattro */
1705 0, /* tp_as_buffer */
1706 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
1707 Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
1708 defdict_doc, /* tp_doc */
1709 defdict_traverse, /* tp_traverse */
1710 (inquiry)defdict_tp_clear, /* tp_clear */
1711 0, /* tp_richcompare */
1712 0, /* tp_weaklistoffset*/
1713 0, /* tp_iter */
1714 0, /* tp_iternext */
1715 defdict_methods, /* tp_methods */
1716 defdict_members, /* tp_members */
1717 0, /* tp_getset */
1718 DEFERRED_ADDRESS(&PyDict_Type), /* tp_base */
1719 0, /* tp_dict */
1720 0, /* tp_descr_get */
1721 0, /* tp_descr_set */
1722 0, /* tp_dictoffset */
1723 defdict_init, /* tp_init */
1724 PyType_GenericAlloc, /* tp_alloc */
1725 0, /* tp_new */
1726 PyObject_GC_Del, /* tp_free */
Guido van Rossum1968ad32006-02-25 22:38:04 +00001727};
1728
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001729/* module level code ********************************************************/
1730
1731PyDoc_STRVAR(module_doc,
Guido van Rossum1968ad32006-02-25 22:38:04 +00001732"High performance data structures.\n\
1733- deque: ordered collection accessible from endpoints only\n\
1734- defaultdict: dict subclass with a default value factory\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001735");
1736
1737PyMODINIT_FUNC
Raymond Hettingereb979882007-02-28 18:37:52 +00001738init_collections(void)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001739{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001740 PyObject *m;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001741
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001742 m = Py_InitModule3("_collections", NULL, module_doc);
1743 if (m == NULL)
1744 return;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001745
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001746 if (PyType_Ready(&deque_type) < 0)
1747 return;
1748 Py_INCREF(&deque_type);
1749 PyModule_AddObject(m, "deque", (PyObject *)&deque_type);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001750
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001751 defdict_type.tp_base = &PyDict_Type;
1752 if (PyType_Ready(&defdict_type) < 0)
1753 return;
1754 Py_INCREF(&defdict_type);
1755 PyModule_AddObject(m, "defaultdict", (PyObject *)&defdict_type);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001756
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001757 if (PyType_Ready(&dequeiter_type) < 0)
1758 return;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001759
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001760 if (PyType_Ready(&dequereviter_type) < 0)
1761 return;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001762
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001763 return;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001764}