blob: aa3cf5c06e41df2436801df6ddf0997cb2c1dac1 [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 Hettingerd2a40732015-09-26 00:52:57 -0700654 /* During the process of clearing a deque, decrefs can cause the
655 deque to mutate. To avoid fatal confusion, we have to make the
656 deque empty before clearing the blocks and never refer to
657 anything via deque->ref while clearing. (This is the same
658 technique used for clearing lists, sets, and dicts.)
659
660 Making the deque empty requires allocating a new empty block. In
661 the unlikely event that memory is full, we fall back to an
662 alternate method that doesn't require a new block. Repeating
663 pops in a while-loop is slower, possibly re-entrant (and a clever
664 adversary could cause it to never terminate).
665 */
666
667 b = newblock(NULL, NULL, 0);
668 if (b == NULL) {
669 PyErr_Clear();
670 goto alternate_method;
671 }
672
673 /* Remember the old size, leftblock, and leftindex */
674 leftblock = deque->leftblock;
675 leftindex = deque->leftindex;
676 n = deque->len;
677
678 /* Set the deque to be empty using the newly allocated block */
679 deque->len = 0;
680 deque->leftblock = b;
681 deque->rightblock = b;
682 deque->leftindex = CENTER + 1;
683 deque->rightindex = CENTER;
684 deque->state++;
685
686 /* Now the old size, leftblock, and leftindex are disconnected from
687 the empty deque and we can use them to decref the pointers.
688 */
689 while (n--) {
690 item = leftblock->data[leftindex];
691 Py_DECREF(item);
692 leftindex++;
693 if (leftindex == BLOCKLEN && n) {
694 assert(leftblock->rightlink != NULL);
695 prevblock = leftblock;
696 leftblock = leftblock->rightlink;
697 leftindex = 0;
698 freeblock(prevblock);
699 }
700 }
701 assert(leftblock->rightlink == NULL);
702 freeblock(leftblock);
703 return;
704
705 alternate_method:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000706 while (deque->len) {
707 item = deque_pop(deque, NULL);
708 assert (item != NULL);
709 Py_DECREF(item);
710 }
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000711}
712
713static PyObject *
Raymond Hettinger33fcf9d2008-07-24 00:08:18 +0000714deque_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000715{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000716 block *b;
717 PyObject *item;
718 Py_ssize_t n, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000719
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000720 if (i < 0 || i >= deque->len) {
721 PyErr_SetString(PyExc_IndexError,
722 "deque index out of range");
723 return NULL;
724 }
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000725
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000726 if (i == 0) {
727 i = deque->leftindex;
728 b = deque->leftblock;
729 } else if (i == deque->len - 1) {
730 i = deque->rightindex;
731 b = deque->rightblock;
732 } else {
733 i += deque->leftindex;
734 n = i / BLOCKLEN;
735 i %= BLOCKLEN;
736 if (index < (deque->len >> 1)) {
737 b = deque->leftblock;
738 while (n--)
739 b = b->rightlink;
740 } else {
741 n = (deque->leftindex + deque->len - 1) / BLOCKLEN - n;
742 b = deque->rightblock;
743 while (n--)
744 b = b->leftlink;
745 }
746 }
747 item = b->data[i];
748 Py_INCREF(item);
749 return item;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000750}
751
Raymond Hettinger616f4f62004-06-26 04:42:06 +0000752/* delitem() implemented in terms of rotate for simplicity and reasonable
753 performance near the end points. If for some reason this method becomes
Tim Peters1065f752004-10-01 01:03:29 +0000754 popular, it is not hard to re-implement this using direct data movement
Raymond Hettinger616f4f62004-06-26 04:42:06 +0000755 (similar to code in list slice assignment) and achieve a two or threefold
756 performance boost.
757*/
758
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000759static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000760deque_del_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000761{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000762 PyObject *item;
Raymond Hettinger79f2c5b2015-05-02 10:53:27 -0700763 int rv;
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000764
Benjamin Peterson5863a392015-05-15 12:19:18 -0400765 assert (i >= 0 && i < deque->len);
Raymond Hettinger79f2c5b2015-05-02 10:53:27 -0700766 if (_deque_rotate(deque, -i))
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000767 return -1;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000768 item = deque_popleft(deque, NULL);
Raymond Hettinger79f2c5b2015-05-02 10:53:27 -0700769 rv = _deque_rotate(deque, i);
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000770 assert (item != NULL);
771 Py_DECREF(item);
Raymond Hettinger79f2c5b2015-05-02 10:53:27 -0700772 return rv;
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000773}
774
775static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000776deque_ass_item(dequeobject *deque, Py_ssize_t i, PyObject *v)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000777{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000778 PyObject *old_value;
779 block *b;
780 Py_ssize_t n, len=deque->len, halflen=(len+1)>>1, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000781
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000782 if (i < 0 || i >= len) {
783 PyErr_SetString(PyExc_IndexError,
784 "deque index out of range");
785 return -1;
786 }
787 if (v == NULL)
788 return deque_del_item(deque, i);
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000789
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000790 i += deque->leftindex;
791 n = i / BLOCKLEN;
792 i %= BLOCKLEN;
793 if (index <= halflen) {
794 b = deque->leftblock;
795 while (n--)
796 b = b->rightlink;
797 } else {
798 n = (deque->leftindex + len - 1) / BLOCKLEN - n;
799 b = deque->rightblock;
800 while (n--)
801 b = b->leftlink;
802 }
803 Py_INCREF(v);
804 old_value = b->data[i];
805 b->data[i] = v;
806 Py_DECREF(old_value);
807 return 0;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000808}
809
810static PyObject *
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000811deque_clearmethod(dequeobject *deque)
812{
Benjamin Peterson40056de2013-01-12 21:22:18 -0500813 deque_clear(deque);
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000814 Py_RETURN_NONE;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000815}
816
817PyDoc_STRVAR(clear_doc, "Remove all elements from the deque.");
818
819static void
820deque_dealloc(dequeobject *deque)
821{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000822 PyObject_GC_UnTrack(deque);
823 if (deque->weakreflist != NULL)
824 PyObject_ClearWeakRefs((PyObject *) deque);
825 if (deque->leftblock != NULL) {
826 deque_clear(deque);
827 assert(deque->leftblock != NULL);
828 freeblock(deque->leftblock);
829 }
830 deque->leftblock = NULL;
831 deque->rightblock = NULL;
832 Py_TYPE(deque)->tp_free(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000833}
834
835static int
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000836deque_traverse(dequeobject *deque, visitproc visit, void *arg)
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000837{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000838 block *b;
839 PyObject *item;
840 Py_ssize_t index;
841 Py_ssize_t indexlo = deque->leftindex;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000842
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000843 for (b = deque->leftblock; b != NULL; b = b->rightlink) {
844 const Py_ssize_t indexhi = b == deque->rightblock ?
845 deque->rightindex :
846 BLOCKLEN - 1;
Tim Peters10c7e862004-10-01 02:01:04 +0000847
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000848 for (index = indexlo; index <= indexhi; ++index) {
849 item = b->data[index];
850 Py_VISIT(item);
851 }
852 indexlo = 0;
853 }
854 return 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000855}
856
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000857static PyObject *
858deque_copy(PyObject *deque)
859{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000860 if (((dequeobject *)deque)->maxlen == -1)
861 return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "O", deque, NULL);
862 else
863 return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "Oi",
864 deque, ((dequeobject *)deque)->maxlen, NULL);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000865}
866
867PyDoc_STRVAR(copy_doc, "Return a shallow copy of a deque.");
868
869static PyObject *
870deque_reduce(dequeobject *deque)
871{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000872 PyObject *dict, *result, *aslist;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000873
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000874 dict = PyObject_GetAttrString((PyObject *)deque, "__dict__");
875 if (dict == NULL)
876 PyErr_Clear();
877 aslist = PySequence_List((PyObject *)deque);
878 if (aslist == NULL) {
879 Py_XDECREF(dict);
880 return NULL;
881 }
882 if (dict == NULL) {
883 if (deque->maxlen == -1)
884 result = Py_BuildValue("O(O)", Py_TYPE(deque), aslist);
885 else
886 result = Py_BuildValue("O(On)", Py_TYPE(deque), aslist, deque->maxlen);
887 } else {
888 if (deque->maxlen == -1)
889 result = Py_BuildValue("O(OO)O", Py_TYPE(deque), aslist, Py_None, dict);
890 else
891 result = Py_BuildValue("O(On)O", Py_TYPE(deque), aslist, deque->maxlen, dict);
892 }
893 Py_XDECREF(dict);
894 Py_DECREF(aslist);
895 return result;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000896}
897
898PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
899
900static PyObject *
901deque_repr(PyObject *deque)
902{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000903 PyObject *aslist, *result, *fmt;
904 int i;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000905
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000906 i = Py_ReprEnter(deque);
907 if (i != 0) {
908 if (i < 0)
909 return NULL;
910 return PyString_FromString("[...]");
911 }
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000912
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000913 aslist = PySequence_List(deque);
914 if (aslist == NULL) {
915 Py_ReprLeave(deque);
916 return NULL;
917 }
918 if (((dequeobject *)deque)->maxlen != -1)
919 fmt = PyString_FromFormat("deque(%%r, maxlen=%zd)",
920 ((dequeobject *)deque)->maxlen);
921 else
922 fmt = PyString_FromString("deque(%r)");
923 if (fmt == NULL) {
924 Py_DECREF(aslist);
925 Py_ReprLeave(deque);
926 return NULL;
927 }
928 result = PyString_Format(fmt, aslist);
929 Py_DECREF(fmt);
930 Py_DECREF(aslist);
931 Py_ReprLeave(deque);
932 return result;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000933}
934
935static int
936deque_tp_print(PyObject *deque, FILE *fp, int flags)
937{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000938 PyObject *it, *item;
939 char *emit = ""; /* No separator emitted on first pass */
940 char *separator = ", ";
941 int i;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000942
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000943 i = Py_ReprEnter(deque);
944 if (i != 0) {
945 if (i < 0)
946 return i;
947 Py_BEGIN_ALLOW_THREADS
948 fputs("[...]", fp);
949 Py_END_ALLOW_THREADS
950 return 0;
951 }
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000952
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000953 it = PyObject_GetIter(deque);
954 if (it == NULL)
955 return -1;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000956
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000957 Py_BEGIN_ALLOW_THREADS
958 fputs("deque([", fp);
959 Py_END_ALLOW_THREADS
960 while ((item = PyIter_Next(it)) != NULL) {
961 Py_BEGIN_ALLOW_THREADS
962 fputs(emit, fp);
963 Py_END_ALLOW_THREADS
964 emit = separator;
965 if (PyObject_Print(item, fp, 0) != 0) {
966 Py_DECREF(item);
967 Py_DECREF(it);
968 Py_ReprLeave(deque);
969 return -1;
970 }
971 Py_DECREF(item);
972 }
973 Py_ReprLeave(deque);
974 Py_DECREF(it);
975 if (PyErr_Occurred())
976 return -1;
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000977
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000978 Py_BEGIN_ALLOW_THREADS
979 if (((dequeobject *)deque)->maxlen == -1)
980 fputs("])", fp);
981 else
982 fprintf(fp, "], maxlen=%" PY_FORMAT_SIZE_T "d)", ((dequeobject *)deque)->maxlen);
983 Py_END_ALLOW_THREADS
984 return 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000985}
986
Raymond Hettinger738ec902004-02-29 02:15:56 +0000987static PyObject *
988deque_richcompare(PyObject *v, PyObject *w, int op)
989{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000990 PyObject *it1=NULL, *it2=NULL, *x, *y;
991 Py_ssize_t vs, ws;
992 int b, cmp=-1;
Raymond Hettinger738ec902004-02-29 02:15:56 +0000993
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000994 if (!PyObject_TypeCheck(v, &deque_type) ||
995 !PyObject_TypeCheck(w, &deque_type)) {
996 Py_INCREF(Py_NotImplemented);
997 return Py_NotImplemented;
998 }
Raymond Hettinger738ec902004-02-29 02:15:56 +0000999
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001000 /* Shortcuts */
1001 vs = ((dequeobject *)v)->len;
1002 ws = ((dequeobject *)w)->len;
1003 if (op == Py_EQ) {
1004 if (v == w)
1005 Py_RETURN_TRUE;
1006 if (vs != ws)
1007 Py_RETURN_FALSE;
1008 }
1009 if (op == Py_NE) {
1010 if (v == w)
1011 Py_RETURN_FALSE;
1012 if (vs != ws)
1013 Py_RETURN_TRUE;
1014 }
Raymond Hettinger738ec902004-02-29 02:15:56 +00001015
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001016 /* Search for the first index where items are different */
1017 it1 = PyObject_GetIter(v);
1018 if (it1 == NULL)
1019 goto done;
1020 it2 = PyObject_GetIter(w);
1021 if (it2 == NULL)
1022 goto done;
1023 for (;;) {
1024 x = PyIter_Next(it1);
1025 if (x == NULL && PyErr_Occurred())
1026 goto done;
1027 y = PyIter_Next(it2);
1028 if (x == NULL || y == NULL)
1029 break;
1030 b = PyObject_RichCompareBool(x, y, Py_EQ);
1031 if (b == 0) {
1032 cmp = PyObject_RichCompareBool(x, y, op);
1033 Py_DECREF(x);
1034 Py_DECREF(y);
1035 goto done;
1036 }
1037 Py_DECREF(x);
1038 Py_DECREF(y);
1039 if (b == -1)
1040 goto done;
1041 }
1042 /* We reached the end of one deque or both */
1043 Py_XDECREF(x);
1044 Py_XDECREF(y);
1045 if (PyErr_Occurred())
1046 goto done;
1047 switch (op) {
1048 case Py_LT: cmp = y != NULL; break; /* if w was longer */
1049 case Py_LE: cmp = x == NULL; break; /* if v was not longer */
1050 case Py_EQ: cmp = x == y; break; /* if we reached the end of both */
1051 case Py_NE: cmp = x != y; break; /* if one deque continues */
1052 case Py_GT: cmp = x != NULL; break; /* if v was longer */
1053 case Py_GE: cmp = y == NULL; break; /* if w was not longer */
1054 }
Tim Peters1065f752004-10-01 01:03:29 +00001055
Raymond Hettinger738ec902004-02-29 02:15:56 +00001056done:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001057 Py_XDECREF(it1);
1058 Py_XDECREF(it2);
1059 if (cmp == 1)
1060 Py_RETURN_TRUE;
1061 if (cmp == 0)
1062 Py_RETURN_FALSE;
1063 return NULL;
Raymond Hettinger738ec902004-02-29 02:15:56 +00001064}
1065
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001066static int
Raymond Hettingera7fc4b12007-10-05 02:47:07 +00001067deque_init(dequeobject *deque, PyObject *args, PyObject *kwdargs)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001068{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001069 PyObject *iterable = NULL;
1070 PyObject *maxlenobj = NULL;
1071 Py_ssize_t maxlen = -1;
1072 char *kwlist[] = {"iterable", "maxlen", 0};
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001073
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001074 if (!PyArg_ParseTupleAndKeywords(args, kwdargs, "|OO:deque", kwlist, &iterable, &maxlenobj))
1075 return -1;
1076 if (maxlenobj != NULL && maxlenobj != Py_None) {
1077 maxlen = PyInt_AsSsize_t(maxlenobj);
1078 if (maxlen == -1 && PyErr_Occurred())
1079 return -1;
1080 if (maxlen < 0) {
1081 PyErr_SetString(PyExc_ValueError, "maxlen must be non-negative");
1082 return -1;
1083 }
1084 }
1085 deque->maxlen = maxlen;
1086 deque_clear(deque);
1087 if (iterable != NULL) {
1088 PyObject *rv = deque_extend(deque, iterable);
1089 if (rv == NULL)
1090 return -1;
1091 Py_DECREF(rv);
1092 }
1093 return 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001094}
1095
Raymond Hettinger56411aa2009-03-10 12:50:59 +00001096static PyObject *
Jesus Cead4e58dc2012-08-03 14:48:23 +02001097deque_sizeof(dequeobject *deque, void *unused)
1098{
1099 Py_ssize_t res;
1100 Py_ssize_t blocks;
1101
1102 res = sizeof(dequeobject);
1103 blocks = (deque->leftindex + deque->len + BLOCKLEN - 1) / BLOCKLEN;
1104 assert(deque->leftindex + deque->len - 1 ==
1105 (blocks - 1) * BLOCKLEN + deque->rightindex);
1106 res += blocks * sizeof(block);
1107 return PyLong_FromSsize_t(res);
1108}
1109
1110PyDoc_STRVAR(sizeof_doc,
1111"D.__sizeof__() -- size of D in memory, in bytes");
1112
1113static PyObject *
Raymond Hettinger56411aa2009-03-10 12:50:59 +00001114deque_get_maxlen(dequeobject *deque)
1115{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001116 if (deque->maxlen == -1)
1117 Py_RETURN_NONE;
1118 return PyInt_FromSsize_t(deque->maxlen);
Raymond Hettinger56411aa2009-03-10 12:50:59 +00001119}
1120
1121static PyGetSetDef deque_getset[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001122 {"maxlen", (getter)deque_get_maxlen, (setter)NULL,
1123 "maximum size of a deque or None if unbounded"},
1124 {0}
Raymond Hettinger56411aa2009-03-10 12:50:59 +00001125};
1126
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001127static PySequenceMethods deque_as_sequence = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001128 (lenfunc)deque_len, /* sq_length */
1129 0, /* sq_concat */
1130 0, /* sq_repeat */
1131 (ssizeargfunc)deque_item, /* sq_item */
1132 0, /* sq_slice */
1133 (ssizeobjargproc)deque_ass_item, /* sq_ass_item */
1134 0, /* sq_ass_slice */
1135 0, /* sq_contains */
1136 (binaryfunc)deque_inplace_concat, /* sq_inplace_concat */
1137 0, /* sq_inplace_repeat */
Raymond Hettinger0b3263b2009-12-10 06:00:33 +00001138
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001139};
1140
1141/* deque object ********************************************************/
1142
1143static PyObject *deque_iter(dequeobject *deque);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001144static PyObject *deque_reviter(dequeobject *deque);
Tim Peters1065f752004-10-01 01:03:29 +00001145PyDoc_STRVAR(reversed_doc,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001146 "D.__reversed__() -- return a reverse iterator over the deque");
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001147
1148static PyMethodDef deque_methods[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001149 {"append", (PyCFunction)deque_append,
1150 METH_O, append_doc},
1151 {"appendleft", (PyCFunction)deque_appendleft,
1152 METH_O, appendleft_doc},
1153 {"clear", (PyCFunction)deque_clearmethod,
1154 METH_NOARGS, clear_doc},
1155 {"__copy__", (PyCFunction)deque_copy,
1156 METH_NOARGS, copy_doc},
1157 {"count", (PyCFunction)deque_count,
1158 METH_O, count_doc},
1159 {"extend", (PyCFunction)deque_extend,
1160 METH_O, extend_doc},
1161 {"extendleft", (PyCFunction)deque_extendleft,
1162 METH_O, extendleft_doc},
1163 {"pop", (PyCFunction)deque_pop,
1164 METH_NOARGS, pop_doc},
1165 {"popleft", (PyCFunction)deque_popleft,
1166 METH_NOARGS, popleft_doc},
1167 {"__reduce__", (PyCFunction)deque_reduce,
1168 METH_NOARGS, reduce_doc},
1169 {"remove", (PyCFunction)deque_remove,
1170 METH_O, remove_doc},
1171 {"__reversed__", (PyCFunction)deque_reviter,
1172 METH_NOARGS, reversed_doc},
1173 {"reverse", (PyCFunction)deque_reverse,
1174 METH_NOARGS, reverse_doc},
1175 {"rotate", (PyCFunction)deque_rotate,
Jesus Cead4e58dc2012-08-03 14:48:23 +02001176 METH_VARARGS, rotate_doc},
1177 {"__sizeof__", (PyCFunction)deque_sizeof,
1178 METH_NOARGS, sizeof_doc},
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001179 {NULL, NULL} /* sentinel */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001180};
1181
1182PyDoc_STRVAR(deque_doc,
Andrew Svetlov227f59b2012-10-31 11:50:00 +02001183"deque([iterable[, maxlen]]) --> deque object\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001184\n\
Raymond Hettingerdb9d64b2011-03-29 17:28:25 -07001185Build an ordered collection with optimized access from its endpoints.");
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001186
Neal Norwitz87f10132004-02-29 15:40:53 +00001187static PyTypeObject deque_type = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001188 PyVarObject_HEAD_INIT(NULL, 0)
1189 "collections.deque", /* tp_name */
1190 sizeof(dequeobject), /* tp_basicsize */
1191 0, /* tp_itemsize */
1192 /* methods */
1193 (destructor)deque_dealloc, /* tp_dealloc */
1194 deque_tp_print, /* tp_print */
1195 0, /* tp_getattr */
1196 0, /* tp_setattr */
1197 0, /* tp_compare */
1198 deque_repr, /* tp_repr */
1199 0, /* tp_as_number */
1200 &deque_as_sequence, /* tp_as_sequence */
1201 0, /* tp_as_mapping */
1202 (hashfunc)PyObject_HashNotImplemented, /* tp_hash */
1203 0, /* tp_call */
1204 0, /* tp_str */
1205 PyObject_GenericGetAttr, /* tp_getattro */
1206 0, /* tp_setattro */
1207 0, /* tp_as_buffer */
1208 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
1209 Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
1210 deque_doc, /* tp_doc */
1211 (traverseproc)deque_traverse, /* tp_traverse */
1212 (inquiry)deque_clear, /* tp_clear */
1213 (richcmpfunc)deque_richcompare, /* tp_richcompare */
1214 offsetof(dequeobject, weakreflist), /* tp_weaklistoffset*/
1215 (getiterfunc)deque_iter, /* tp_iter */
1216 0, /* tp_iternext */
1217 deque_methods, /* tp_methods */
1218 0, /* tp_members */
1219 deque_getset, /* tp_getset */
1220 0, /* tp_base */
1221 0, /* tp_dict */
1222 0, /* tp_descr_get */
1223 0, /* tp_descr_set */
1224 0, /* tp_dictoffset */
1225 (initproc)deque_init, /* tp_init */
1226 PyType_GenericAlloc, /* tp_alloc */
1227 deque_new, /* tp_new */
1228 PyObject_GC_Del, /* tp_free */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001229};
1230
1231/*********************** Deque Iterator **************************/
1232
1233typedef struct {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001234 PyObject_HEAD
1235 Py_ssize_t index;
1236 block *b;
1237 dequeobject *deque;
1238 long state; /* state when the iterator is created */
1239 Py_ssize_t counter; /* number of items remaining for iteration */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001240} dequeiterobject;
1241
Martin v. Löwis111c1802008-06-13 07:47:47 +00001242static PyTypeObject dequeiter_type;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001243
1244static PyObject *
1245deque_iter(dequeobject *deque)
1246{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001247 dequeiterobject *it;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001248
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001249 it = PyObject_GC_New(dequeiterobject, &dequeiter_type);
1250 if (it == NULL)
1251 return NULL;
1252 it->b = deque->leftblock;
1253 it->index = deque->leftindex;
1254 Py_INCREF(deque);
1255 it->deque = deque;
1256 it->state = deque->state;
1257 it->counter = deque->len;
1258 PyObject_GC_Track(it);
1259 return (PyObject *)it;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001260}
1261
Antoine Pitrouaa687902009-01-01 14:11:22 +00001262static int
1263dequeiter_traverse(dequeiterobject *dio, visitproc visit, void *arg)
1264{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001265 Py_VISIT(dio->deque);
1266 return 0;
Antoine Pitrouaa687902009-01-01 14:11:22 +00001267}
1268
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001269static void
1270dequeiter_dealloc(dequeiterobject *dio)
1271{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001272 Py_XDECREF(dio->deque);
1273 PyObject_GC_Del(dio);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001274}
1275
1276static PyObject *
1277dequeiter_next(dequeiterobject *it)
1278{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001279 PyObject *item;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001280
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001281 if (it->deque->state != it->state) {
1282 it->counter = 0;
1283 PyErr_SetString(PyExc_RuntimeError,
1284 "deque mutated during iteration");
1285 return NULL;
1286 }
1287 if (it->counter == 0)
1288 return NULL;
1289 assert (!(it->b == it->deque->rightblock &&
1290 it->index > it->deque->rightindex));
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001291
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001292 item = it->b->data[it->index];
1293 it->index++;
1294 it->counter--;
1295 if (it->index == BLOCKLEN && it->counter > 0) {
1296 assert (it->b->rightlink != NULL);
1297 it->b = it->b->rightlink;
1298 it->index = 0;
1299 }
1300 Py_INCREF(item);
1301 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001302}
1303
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001304static PyObject *
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001305dequeiter_len(dequeiterobject *it)
1306{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001307 return PyInt_FromLong(it->counter);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001308}
1309
Armin Rigof5b3e362006-02-11 21:32:43 +00001310PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001311
1312static PyMethodDef dequeiter_methods[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001313 {"__length_hint__", (PyCFunction)dequeiter_len, METH_NOARGS, length_hint_doc},
1314 {NULL, NULL} /* sentinel */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001315};
1316
Martin v. Löwis111c1802008-06-13 07:47:47 +00001317static PyTypeObject dequeiter_type = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001318 PyVarObject_HEAD_INIT(NULL, 0)
1319 "deque_iterator", /* tp_name */
1320 sizeof(dequeiterobject), /* tp_basicsize */
1321 0, /* tp_itemsize */
1322 /* methods */
1323 (destructor)dequeiter_dealloc, /* tp_dealloc */
1324 0, /* tp_print */
1325 0, /* tp_getattr */
1326 0, /* tp_setattr */
1327 0, /* tp_compare */
1328 0, /* tp_repr */
1329 0, /* tp_as_number */
1330 0, /* tp_as_sequence */
1331 0, /* tp_as_mapping */
1332 0, /* tp_hash */
1333 0, /* tp_call */
1334 0, /* tp_str */
1335 PyObject_GenericGetAttr, /* tp_getattro */
1336 0, /* tp_setattro */
1337 0, /* tp_as_buffer */
1338 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
1339 0, /* tp_doc */
1340 (traverseproc)dequeiter_traverse, /* tp_traverse */
1341 0, /* tp_clear */
1342 0, /* tp_richcompare */
1343 0, /* tp_weaklistoffset */
1344 PyObject_SelfIter, /* tp_iter */
1345 (iternextfunc)dequeiter_next, /* tp_iternext */
1346 dequeiter_methods, /* tp_methods */
1347 0,
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001348};
1349
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001350/*********************** Deque Reverse Iterator **************************/
1351
Martin v. Löwis111c1802008-06-13 07:47:47 +00001352static PyTypeObject dequereviter_type;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001353
1354static PyObject *
1355deque_reviter(dequeobject *deque)
1356{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001357 dequeiterobject *it;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001358
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001359 it = PyObject_GC_New(dequeiterobject, &dequereviter_type);
1360 if (it == NULL)
1361 return NULL;
1362 it->b = deque->rightblock;
1363 it->index = deque->rightindex;
1364 Py_INCREF(deque);
1365 it->deque = deque;
1366 it->state = deque->state;
1367 it->counter = deque->len;
1368 PyObject_GC_Track(it);
1369 return (PyObject *)it;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001370}
1371
1372static PyObject *
1373dequereviter_next(dequeiterobject *it)
1374{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001375 PyObject *item;
1376 if (it->counter == 0)
1377 return NULL;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001378
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001379 if (it->deque->state != it->state) {
1380 it->counter = 0;
1381 PyErr_SetString(PyExc_RuntimeError,
1382 "deque mutated during iteration");
1383 return NULL;
1384 }
1385 assert (!(it->b == it->deque->leftblock &&
1386 it->index < it->deque->leftindex));
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001387
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001388 item = it->b->data[it->index];
1389 it->index--;
1390 it->counter--;
1391 if (it->index == -1 && it->counter > 0) {
1392 assert (it->b->leftlink != NULL);
1393 it->b = it->b->leftlink;
1394 it->index = BLOCKLEN - 1;
1395 }
1396 Py_INCREF(item);
1397 return item;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001398}
1399
Martin v. Löwis111c1802008-06-13 07:47:47 +00001400static PyTypeObject dequereviter_type = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001401 PyVarObject_HEAD_INIT(NULL, 0)
1402 "deque_reverse_iterator", /* tp_name */
1403 sizeof(dequeiterobject), /* tp_basicsize */
1404 0, /* tp_itemsize */
1405 /* methods */
1406 (destructor)dequeiter_dealloc, /* tp_dealloc */
1407 0, /* tp_print */
1408 0, /* tp_getattr */
1409 0, /* tp_setattr */
1410 0, /* tp_compare */
1411 0, /* tp_repr */
1412 0, /* tp_as_number */
1413 0, /* tp_as_sequence */
1414 0, /* tp_as_mapping */
1415 0, /* tp_hash */
1416 0, /* tp_call */
1417 0, /* tp_str */
1418 PyObject_GenericGetAttr, /* tp_getattro */
1419 0, /* tp_setattro */
1420 0, /* tp_as_buffer */
1421 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
1422 0, /* tp_doc */
1423 (traverseproc)dequeiter_traverse, /* tp_traverse */
1424 0, /* tp_clear */
1425 0, /* tp_richcompare */
1426 0, /* tp_weaklistoffset */
1427 PyObject_SelfIter, /* tp_iter */
1428 (iternextfunc)dequereviter_next, /* tp_iternext */
1429 dequeiter_methods, /* tp_methods */
1430 0,
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001431};
1432
Guido van Rossum1968ad32006-02-25 22:38:04 +00001433/* defaultdict type *********************************************************/
1434
1435typedef struct {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001436 PyDictObject dict;
1437 PyObject *default_factory;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001438} defdictobject;
1439
1440static PyTypeObject defdict_type; /* Forward */
1441
1442PyDoc_STRVAR(defdict_missing_doc,
1443"__missing__(key) # Called by __getitem__ for missing key; pseudo-code:\n\
Georg Brandlb51a57e2007-03-06 13:32:52 +00001444 if self.default_factory is None: raise KeyError((key,))\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00001445 self[key] = value = self.default_factory()\n\
1446 return value\n\
1447");
1448
1449static PyObject *
1450defdict_missing(defdictobject *dd, PyObject *key)
1451{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001452 PyObject *factory = dd->default_factory;
1453 PyObject *value;
1454 if (factory == NULL || factory == Py_None) {
1455 /* XXX Call dict.__missing__(key) */
1456 PyObject *tup;
1457 tup = PyTuple_Pack(1, key);
1458 if (!tup) return NULL;
1459 PyErr_SetObject(PyExc_KeyError, tup);
1460 Py_DECREF(tup);
1461 return NULL;
1462 }
1463 value = PyEval_CallObject(factory, NULL);
1464 if (value == NULL)
1465 return value;
1466 if (PyObject_SetItem((PyObject *)dd, key, value) < 0) {
1467 Py_DECREF(value);
1468 return NULL;
1469 }
1470 return value;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001471}
1472
1473PyDoc_STRVAR(defdict_copy_doc, "D.copy() -> a shallow copy of D.");
1474
1475static PyObject *
1476defdict_copy(defdictobject *dd)
1477{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001478 /* This calls the object's class. That only works for subclasses
1479 whose class constructor has the same signature. Subclasses that
1480 define a different constructor signature must override copy().
1481 */
Raymond Hettinger8fdab952009-08-04 19:08:05 +00001482
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001483 if (dd->default_factory == NULL)
1484 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd), Py_None, dd, NULL);
1485 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd),
1486 dd->default_factory, dd, NULL);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001487}
1488
1489static PyObject *
1490defdict_reduce(defdictobject *dd)
1491{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001492 /* __reduce__ must return a 5-tuple as follows:
Guido van Rossum1968ad32006-02-25 22:38:04 +00001493
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001494 - factory function
1495 - tuple of args for the factory function
1496 - additional state (here None)
1497 - sequence iterator (here None)
1498 - dictionary iterator (yielding successive (key, value) pairs
Guido van Rossum1968ad32006-02-25 22:38:04 +00001499
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001500 This API is used by pickle.py and copy.py.
Guido van Rossum1968ad32006-02-25 22:38:04 +00001501
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001502 For this to be useful with pickle.py, the default_factory
1503 must be picklable; e.g., None, a built-in, or a global
1504 function in a module or package.
Guido van Rossum1968ad32006-02-25 22:38:04 +00001505
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001506 Both shallow and deep copying are supported, but for deep
1507 copying, the default_factory must be deep-copyable; e.g. None,
1508 or a built-in (functions are not copyable at this time).
Guido van Rossum1968ad32006-02-25 22:38:04 +00001509
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001510 This only works for subclasses as long as their constructor
1511 signature is compatible; the first argument must be the
1512 optional default_factory, defaulting to None.
1513 */
1514 PyObject *args;
1515 PyObject *items;
1516 PyObject *result;
1517 if (dd->default_factory == NULL || dd->default_factory == Py_None)
1518 args = PyTuple_New(0);
1519 else
1520 args = PyTuple_Pack(1, dd->default_factory);
1521 if (args == NULL)
1522 return NULL;
1523 items = PyObject_CallMethod((PyObject *)dd, "iteritems", "()");
1524 if (items == NULL) {
1525 Py_DECREF(args);
1526 return NULL;
1527 }
1528 result = PyTuple_Pack(5, Py_TYPE(dd), args,
1529 Py_None, Py_None, items);
1530 Py_DECREF(items);
1531 Py_DECREF(args);
1532 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001533}
1534
1535static PyMethodDef defdict_methods[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001536 {"__missing__", (PyCFunction)defdict_missing, METH_O,
1537 defdict_missing_doc},
1538 {"copy", (PyCFunction)defdict_copy, METH_NOARGS,
1539 defdict_copy_doc},
1540 {"__copy__", (PyCFunction)defdict_copy, METH_NOARGS,
1541 defdict_copy_doc},
1542 {"__reduce__", (PyCFunction)defdict_reduce, METH_NOARGS,
1543 reduce_doc},
1544 {NULL}
Guido van Rossum1968ad32006-02-25 22:38:04 +00001545};
1546
1547static PyMemberDef defdict_members[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001548 {"default_factory", T_OBJECT,
1549 offsetof(defdictobject, default_factory), 0,
1550 PyDoc_STR("Factory for default value called by __missing__().")},
1551 {NULL}
Guido van Rossum1968ad32006-02-25 22:38:04 +00001552};
1553
1554static void
1555defdict_dealloc(defdictobject *dd)
1556{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001557 Py_CLEAR(dd->default_factory);
1558 PyDict_Type.tp_dealloc((PyObject *)dd);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001559}
1560
1561static int
1562defdict_print(defdictobject *dd, FILE *fp, int flags)
1563{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001564 int sts;
1565 Py_BEGIN_ALLOW_THREADS
1566 fprintf(fp, "defaultdict(");
1567 Py_END_ALLOW_THREADS
1568 if (dd->default_factory == NULL) {
1569 Py_BEGIN_ALLOW_THREADS
1570 fprintf(fp, "None");
1571 Py_END_ALLOW_THREADS
1572 } else {
1573 PyObject_Print(dd->default_factory, fp, 0);
1574 }
1575 Py_BEGIN_ALLOW_THREADS
1576 fprintf(fp, ", ");
1577 Py_END_ALLOW_THREADS
1578 sts = PyDict_Type.tp_print((PyObject *)dd, fp, 0);
1579 Py_BEGIN_ALLOW_THREADS
1580 fprintf(fp, ")");
1581 Py_END_ALLOW_THREADS
1582 return sts;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001583}
1584
1585static PyObject *
1586defdict_repr(defdictobject *dd)
1587{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001588 PyObject *defrepr;
1589 PyObject *baserepr;
1590 PyObject *result;
1591 baserepr = PyDict_Type.tp_repr((PyObject *)dd);
1592 if (baserepr == NULL)
1593 return NULL;
1594 if (dd->default_factory == NULL)
1595 defrepr = PyString_FromString("None");
1596 else
1597 {
1598 int status = Py_ReprEnter(dd->default_factory);
1599 if (status != 0) {
Antoine Pitrouc39cd782012-02-15 02:42:46 +01001600 if (status < 0) {
1601 Py_DECREF(baserepr);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001602 return NULL;
Antoine Pitrouc39cd782012-02-15 02:42:46 +01001603 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001604 defrepr = PyString_FromString("...");
1605 }
1606 else
1607 defrepr = PyObject_Repr(dd->default_factory);
1608 Py_ReprLeave(dd->default_factory);
1609 }
1610 if (defrepr == NULL) {
1611 Py_DECREF(baserepr);
1612 return NULL;
1613 }
1614 result = PyString_FromFormat("defaultdict(%s, %s)",
1615 PyString_AS_STRING(defrepr),
1616 PyString_AS_STRING(baserepr));
1617 Py_DECREF(defrepr);
1618 Py_DECREF(baserepr);
1619 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001620}
1621
1622static int
1623defdict_traverse(PyObject *self, visitproc visit, void *arg)
1624{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001625 Py_VISIT(((defdictobject *)self)->default_factory);
1626 return PyDict_Type.tp_traverse(self, visit, arg);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001627}
1628
1629static int
1630defdict_tp_clear(defdictobject *dd)
1631{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001632 Py_CLEAR(dd->default_factory);
1633 return PyDict_Type.tp_clear((PyObject *)dd);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001634}
1635
1636static int
1637defdict_init(PyObject *self, PyObject *args, PyObject *kwds)
1638{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001639 defdictobject *dd = (defdictobject *)self;
1640 PyObject *olddefault = dd->default_factory;
1641 PyObject *newdefault = NULL;
1642 PyObject *newargs;
1643 int result;
1644 if (args == NULL || !PyTuple_Check(args))
1645 newargs = PyTuple_New(0);
1646 else {
1647 Py_ssize_t n = PyTuple_GET_SIZE(args);
1648 if (n > 0) {
1649 newdefault = PyTuple_GET_ITEM(args, 0);
1650 if (!PyCallable_Check(newdefault) && newdefault != Py_None) {
1651 PyErr_SetString(PyExc_TypeError,
Raymond Hettingerfe13eac2015-07-20 03:08:09 -04001652 "first argument must be callable or None");
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001653 return -1;
1654 }
1655 }
1656 newargs = PySequence_GetSlice(args, 1, n);
1657 }
1658 if (newargs == NULL)
1659 return -1;
1660 Py_XINCREF(newdefault);
1661 dd->default_factory = newdefault;
1662 result = PyDict_Type.tp_init(self, newargs, kwds);
1663 Py_DECREF(newargs);
1664 Py_XDECREF(olddefault);
1665 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001666}
1667
1668PyDoc_STRVAR(defdict_doc,
Benjamin Peterson06e486c2014-01-13 23:56:05 -05001669"defaultdict(default_factory[, ...]) --> dict with default factory\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00001670\n\
1671The default factory is called without arguments to produce\n\
1672a new value when a key is not present, in __getitem__ only.\n\
1673A defaultdict compares equal to a dict with the same items.\n\
Benjamin Peterson06e486c2014-01-13 23:56:05 -05001674All remaining arguments are treated the same as if they were\n\
1675passed to the dict constructor, including keyword arguments.\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00001676");
1677
Anthony Baxter3b8ff312006-04-04 15:05:23 +00001678/* See comment in xxsubtype.c */
1679#define DEFERRED_ADDRESS(ADDR) 0
1680
Guido van Rossum1968ad32006-02-25 22:38:04 +00001681static PyTypeObject defdict_type = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001682 PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0)
1683 "collections.defaultdict", /* tp_name */
1684 sizeof(defdictobject), /* tp_basicsize */
1685 0, /* tp_itemsize */
1686 /* methods */
1687 (destructor)defdict_dealloc, /* tp_dealloc */
1688 (printfunc)defdict_print, /* tp_print */
1689 0, /* tp_getattr */
1690 0, /* tp_setattr */
1691 0, /* tp_compare */
1692 (reprfunc)defdict_repr, /* tp_repr */
1693 0, /* tp_as_number */
1694 0, /* tp_as_sequence */
1695 0, /* tp_as_mapping */
1696 0, /* tp_hash */
1697 0, /* tp_call */
1698 0, /* tp_str */
1699 PyObject_GenericGetAttr, /* tp_getattro */
1700 0, /* tp_setattro */
1701 0, /* tp_as_buffer */
1702 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
1703 Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
1704 defdict_doc, /* tp_doc */
1705 defdict_traverse, /* tp_traverse */
1706 (inquiry)defdict_tp_clear, /* tp_clear */
1707 0, /* tp_richcompare */
1708 0, /* tp_weaklistoffset*/
1709 0, /* tp_iter */
1710 0, /* tp_iternext */
1711 defdict_methods, /* tp_methods */
1712 defdict_members, /* tp_members */
1713 0, /* tp_getset */
1714 DEFERRED_ADDRESS(&PyDict_Type), /* tp_base */
1715 0, /* tp_dict */
1716 0, /* tp_descr_get */
1717 0, /* tp_descr_set */
1718 0, /* tp_dictoffset */
1719 defdict_init, /* tp_init */
1720 PyType_GenericAlloc, /* tp_alloc */
1721 0, /* tp_new */
1722 PyObject_GC_Del, /* tp_free */
Guido van Rossum1968ad32006-02-25 22:38:04 +00001723};
1724
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001725/* module level code ********************************************************/
1726
1727PyDoc_STRVAR(module_doc,
Guido van Rossum1968ad32006-02-25 22:38:04 +00001728"High performance data structures.\n\
1729- deque: ordered collection accessible from endpoints only\n\
1730- defaultdict: dict subclass with a default value factory\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001731");
1732
1733PyMODINIT_FUNC
Raymond Hettingereb979882007-02-28 18:37:52 +00001734init_collections(void)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001735{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001736 PyObject *m;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001737
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001738 m = Py_InitModule3("_collections", NULL, module_doc);
1739 if (m == NULL)
1740 return;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001741
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001742 if (PyType_Ready(&deque_type) < 0)
1743 return;
1744 Py_INCREF(&deque_type);
1745 PyModule_AddObject(m, "deque", (PyObject *)&deque_type);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001746
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001747 defdict_type.tp_base = &PyDict_Type;
1748 if (PyType_Ready(&defdict_type) < 0)
1749 return;
1750 Py_INCREF(&defdict_type);
1751 PyModule_AddObject(m, "defaultdict", (PyObject *)&defdict_type);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001752
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001753 if (PyType_Ready(&dequeiter_type) < 0)
1754 return;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001755
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001756 if (PyType_Ready(&dequereviter_type) < 0)
1757 return;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001758
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001759 return;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001760}