blob: fa0f004989f073e9bb61548522a9900357a5a6d3 [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
11 * reduce the number of calls to the memory allocator but take more
12 * memory. Ideally, BLOCKLEN should be set with an eye to the
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013 * length of a cache line.
Raymond Hettinger77e8bf12004-10-01 15:25:53 +000014 */
15
Raymond Hettinger7d112df2004-11-02 02:11:35 +000016#define BLOCKLEN 62
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000017#define CENTER ((BLOCKLEN - 1) / 2)
Raymond Hettinger756b3f32004-01-29 06:37:52 +000018
Tim Petersd8768d32004-10-01 01:32:53 +000019/* A `dequeobject` is composed of a doubly-linked list of `block` nodes.
20 * This list is not circular (the leftmost block has leftlink==NULL,
21 * and the rightmost block has rightlink==NULL). A deque d's first
22 * element is at d.leftblock[leftindex] and its last element is at
23 * d.rightblock[rightindex]; note that, unlike as for Python slice
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000024 * indices, these indices are inclusive on both ends. By being inclusive
Thomas Wouters0e3f5912006-08-11 14:57:12 +000025 * on both ends, algorithms for left and right operations become
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000026 * symmetrical which simplifies the design.
Thomas Wouters0e3f5912006-08-11 14:57:12 +000027 *
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000028 * The list of blocks is never empty, so d.leftblock and d.rightblock
29 * are never equal to NULL.
30 *
31 * The indices, d.leftindex and d.rightindex are always in the range
32 * 0 <= index < BLOCKLEN.
Raymond Hettinger4ca4c7c2004-10-01 15:14:39 +000033 * Their exact relationship is:
34 * (d.leftindex + d.len - 1) % BLOCKLEN == d.rightindex.
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000035 *
36 * Empty deques have d.len == 0; d.leftblock==d.rightblock;
37 * d.leftindex == CENTER+1; and d.rightindex == CENTER.
38 * Checking for d.len == 0 is the intended way to see whether d is empty.
39 *
Thomas Wouters0e3f5912006-08-11 14:57:12 +000040 * Whenever d.leftblock == d.rightblock,
Raymond Hettinger4ca4c7c2004-10-01 15:14:39 +000041 * d.leftindex + d.len - 1 == d.rightindex.
Thomas Wouters0e3f5912006-08-11 14:57:12 +000042 *
Raymond Hettinger4ca4c7c2004-10-01 15:14:39 +000043 * However, when d.leftblock != d.rightblock, d.leftindex and d.rightindex
Thomas Wouters0e3f5912006-08-11 14:57:12 +000044 * become indices into distinct blocks and either may be larger than the
Raymond Hettinger4ca4c7c2004-10-01 15:14:39 +000045 * other.
Tim Petersd8768d32004-10-01 01:32:53 +000046 */
47
Raymond Hettinger756b3f32004-01-29 06:37:52 +000048typedef struct BLOCK {
49 struct BLOCK *leftlink;
50 struct BLOCK *rightlink;
51 PyObject *data[BLOCKLEN];
52} block;
53
Guido van Rossum58da9312007-11-10 23:39:45 +000054#define MAXFREEBLOCKS 10
Benjamin Petersond6313712008-07-31 16:23:04 +000055static Py_ssize_t numfreeblocks = 0;
Guido van Rossum58da9312007-11-10 23:39:45 +000056static block *freeblocks[MAXFREEBLOCKS];
57
Tim Peters6f853562004-10-01 01:04:50 +000058static block *
Benjamin Petersond6313712008-07-31 16:23:04 +000059newblock(block *leftlink, block *rightlink, Py_ssize_t len) {
Raymond Hettingerc5fa9922004-10-06 17:51:54 +000060 block *b;
Benjamin Petersond6313712008-07-31 16:23:04 +000061 /* To prevent len from overflowing PY_SSIZE_T_MAX on 64-bit machines, we
Raymond Hettingerc5fa9922004-10-06 17:51:54 +000062 * refuse to allocate new blocks if the current len is dangerously
63 * close. There is some extra margin to prevent spurious arithmetic
64 * overflows at various places. The following check ensures that
65 * the blocks allocated to the deque, in the worst case, can only
Benjamin Petersond6313712008-07-31 16:23:04 +000066 * have PY_SSIZE_T_MAX-2 entries in total.
Raymond Hettingerc5fa9922004-10-06 17:51:54 +000067 */
Benjamin Petersond6313712008-07-31 16:23:04 +000068 if (len >= PY_SSIZE_T_MAX - 2*BLOCKLEN) {
Raymond Hettingerc5fa9922004-10-06 17:51:54 +000069 PyErr_SetString(PyExc_OverflowError,
70 "cannot add more blocks to the deque");
71 return NULL;
72 }
Guido van Rossum58da9312007-11-10 23:39:45 +000073 if (numfreeblocks) {
74 numfreeblocks -= 1;
75 b = freeblocks[numfreeblocks];
76 } else {
77 b = PyMem_Malloc(sizeof(block));
78 if (b == NULL) {
79 PyErr_NoMemory();
80 return NULL;
81 }
Raymond Hettinger756b3f32004-01-29 06:37:52 +000082 }
83 b->leftlink = leftlink;
84 b->rightlink = rightlink;
85 return b;
86}
87
Martin v. Löwis59683e82008-06-13 07:50:45 +000088static void
Guido van Rossum58da9312007-11-10 23:39:45 +000089freeblock(block *b)
90{
91 if (numfreeblocks < MAXFREEBLOCKS) {
92 freeblocks[numfreeblocks] = b;
93 numfreeblocks++;
94 } else {
95 PyMem_Free(b);
96 }
97}
98
Raymond Hettinger756b3f32004-01-29 06:37:52 +000099typedef struct {
100 PyObject_HEAD
101 block *leftblock;
102 block *rightblock;
Benjamin Petersond6313712008-07-31 16:23:04 +0000103 Py_ssize_t leftindex; /* in range(BLOCKLEN) */
104 Py_ssize_t rightindex; /* in range(BLOCKLEN) */
105 Py_ssize_t len;
106 Py_ssize_t maxlen;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +0000107 long state; /* incremented whenever the indices move */
Raymond Hettinger691d8052004-05-30 07:26:47 +0000108 PyObject *weakreflist; /* List of weak references */
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000109} dequeobject;
110
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000111/* The deque's size limit is d.maxlen. The limit can be zero or positive.
112 * If there is no limit, then d.maxlen == -1.
113 *
114 * After an item is added to a deque, we check to see if the size has grown past
115 * the limit. If it has, we get the size back down to the limit by popping an
116 * item off of the opposite end. The methods that can trigger this are append(),
117 * appendleft(), extend(), and extendleft().
118 */
119
120#define TRIM(d, popfunction) \
121 if (d->maxlen != -1 && d->len > d->maxlen) { \
122 PyObject *rv = popfunction(d, NULL); \
123 assert(rv != NULL && d->len <= d->maxlen); \
124 Py_DECREF(rv); \
125 }
126
Neal Norwitz87f10132004-02-29 15:40:53 +0000127static PyTypeObject deque_type;
Raymond Hettinger738ec902004-02-29 02:15:56 +0000128
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000129static PyObject *
130deque_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
131{
132 dequeobject *deque;
133 block *b;
134
135 /* create dequeobject structure */
136 deque = (dequeobject *)type->tp_alloc(type, 0);
137 if (deque == NULL)
138 return NULL;
Tim Peters1065f752004-10-01 01:03:29 +0000139
Raymond Hettingerc5fa9922004-10-06 17:51:54 +0000140 b = newblock(NULL, NULL, 0);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000141 if (b == NULL) {
142 Py_DECREF(deque);
143 return NULL;
144 }
145
Raymond Hettinger61f05fb2004-10-01 06:24:12 +0000146 assert(BLOCKLEN >= 2);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000147 deque->leftblock = b;
148 deque->rightblock = b;
Raymond Hettinger61f05fb2004-10-01 06:24:12 +0000149 deque->leftindex = CENTER + 1;
150 deque->rightindex = CENTER;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000151 deque->len = 0;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +0000152 deque->state = 0;
Raymond Hettinger691d8052004-05-30 07:26:47 +0000153 deque->weakreflist = NULL;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000154 deque->maxlen = -1;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000155
156 return (PyObject *)deque;
157}
158
159static PyObject *
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000160deque_pop(dequeobject *deque, PyObject *unused)
161{
162 PyObject *item;
163 block *prevblock;
164
165 if (deque->len == 0) {
Raymond Hettinger738ec902004-02-29 02:15:56 +0000166 PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000167 return NULL;
168 }
169 item = deque->rightblock->data[deque->rightindex];
170 deque->rightindex--;
171 deque->len--;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +0000172 deque->state++;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000173
174 if (deque->rightindex == -1) {
175 if (deque->len == 0) {
176 assert(deque->leftblock == deque->rightblock);
177 assert(deque->leftindex == deque->rightindex+1);
178 /* re-center instead of freeing a block */
Raymond Hettinger61f05fb2004-10-01 06:24:12 +0000179 deque->leftindex = CENTER + 1;
180 deque->rightindex = CENTER;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000181 } else {
182 prevblock = deque->rightblock->leftlink;
183 assert(deque->leftblock != deque->rightblock);
Guido van Rossum58da9312007-11-10 23:39:45 +0000184 freeblock(deque->rightblock);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000185 prevblock->rightlink = NULL;
186 deque->rightblock = prevblock;
187 deque->rightindex = BLOCKLEN - 1;
188 }
189 }
190 return item;
191}
192
193PyDoc_STRVAR(pop_doc, "Remove and return the rightmost element.");
194
195static PyObject *
196deque_popleft(dequeobject *deque, PyObject *unused)
197{
198 PyObject *item;
199 block *prevblock;
200
201 if (deque->len == 0) {
Raymond Hettinger738ec902004-02-29 02:15:56 +0000202 PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000203 return NULL;
204 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000205 assert(deque->leftblock != NULL);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000206 item = deque->leftblock->data[deque->leftindex];
207 deque->leftindex++;
208 deque->len--;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +0000209 deque->state++;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000210
211 if (deque->leftindex == BLOCKLEN) {
212 if (deque->len == 0) {
213 assert(deque->leftblock == deque->rightblock);
214 assert(deque->leftindex == deque->rightindex+1);
215 /* re-center instead of freeing a block */
Raymond Hettinger61f05fb2004-10-01 06:24:12 +0000216 deque->leftindex = CENTER + 1;
217 deque->rightindex = CENTER;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000218 } else {
219 assert(deque->leftblock != deque->rightblock);
220 prevblock = deque->leftblock->rightlink;
Guido van Rossum58da9312007-11-10 23:39:45 +0000221 freeblock(deque->leftblock);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000222 assert(prevblock != NULL);
223 prevblock->leftlink = NULL;
224 deque->leftblock = prevblock;
225 deque->leftindex = 0;
226 }
227 }
228 return item;
229}
230
231PyDoc_STRVAR(popleft_doc, "Remove and return the leftmost element.");
232
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000233static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000234deque_append(dequeobject *deque, PyObject *item)
235{
236 deque->state++;
237 if (deque->rightindex == BLOCKLEN-1) {
238 block *b = newblock(deque->rightblock, NULL, deque->len);
239 if (b == NULL)
240 return NULL;
241 assert(deque->rightblock->rightlink == NULL);
242 deque->rightblock->rightlink = b;
243 deque->rightblock = b;
244 deque->rightindex = -1;
245 }
246 Py_INCREF(item);
247 deque->len++;
248 deque->rightindex++;
249 deque->rightblock->data[deque->rightindex] = item;
250 TRIM(deque, deque_popleft);
251 Py_RETURN_NONE;
252}
253
254PyDoc_STRVAR(append_doc, "Add an element to the right side of the deque.");
255
256static PyObject *
257deque_appendleft(dequeobject *deque, PyObject *item)
258{
259 deque->state++;
260 if (deque->leftindex == 0) {
261 block *b = newblock(NULL, deque->leftblock, deque->len);
262 if (b == NULL)
263 return NULL;
264 assert(deque->leftblock->leftlink == NULL);
265 deque->leftblock->leftlink = b;
266 deque->leftblock = b;
267 deque->leftindex = BLOCKLEN;
268 }
269 Py_INCREF(item);
270 deque->len++;
271 deque->leftindex--;
272 deque->leftblock->data[deque->leftindex] = item;
273 TRIM(deque, deque_pop);
274 Py_RETURN_NONE;
275}
276
277PyDoc_STRVAR(appendleft_doc, "Add an element to the left side of the deque.");
278
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000279
280/* Run an iterator to exhaustion. Shortcut for
281 the extend/extendleft methods when maxlen == 0. */
282static PyObject*
283consume_iterator(PyObject *it)
284{
285 PyObject *item;
286
287 while ((item = PyIter_Next(it)) != NULL) {
288 Py_DECREF(item);
289 }
290 Py_DECREF(it);
291 if (PyErr_Occurred())
292 return NULL;
293 Py_RETURN_NONE;
294}
295
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000296static PyObject *
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000297deque_extend(dequeobject *deque, PyObject *iterable)
298{
299 PyObject *it, *item;
300
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000301 /* Handle case where id(deque) == id(iterable) */
302 if ((PyObject *)deque == iterable) {
303 PyObject *result;
304 PyObject *s = PySequence_List(iterable);
305 if (s == NULL)
306 return NULL;
307 result = deque_extend(deque, s);
308 Py_DECREF(s);
309 return result;
310 }
311
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000312 it = PyObject_GetIter(iterable);
313 if (it == NULL)
314 return NULL;
315
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000316 if (deque->maxlen == 0)
317 return consume_iterator(it);
318
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000319 while ((item = PyIter_Next(it)) != NULL) {
Raymond Hettingerd1b3d882004-10-02 00:43:13 +0000320 deque->state++;
Armin Rigo974d7572004-10-02 13:59:34 +0000321 if (deque->rightindex == BLOCKLEN-1) {
Raymond Hettingerc5fa9922004-10-06 17:51:54 +0000322 block *b = newblock(deque->rightblock, NULL,
323 deque->len);
Raymond Hettingerc058fd12004-02-07 02:45:22 +0000324 if (b == NULL) {
325 Py_DECREF(item);
326 Py_DECREF(it);
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000327 return NULL;
Raymond Hettingerc058fd12004-02-07 02:45:22 +0000328 }
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000329 assert(deque->rightblock->rightlink == NULL);
330 deque->rightblock->rightlink = b;
331 deque->rightblock = b;
Armin Rigo974d7572004-10-02 13:59:34 +0000332 deque->rightindex = -1;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000333 }
Armin Rigo974d7572004-10-02 13:59:34 +0000334 deque->len++;
335 deque->rightindex++;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000336 deque->rightblock->data[deque->rightindex] = item;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000337 TRIM(deque, deque_popleft);
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000338 }
339 Py_DECREF(it);
Tim Peters1065f752004-10-01 01:03:29 +0000340 if (PyErr_Occurred())
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000341 return NULL;
342 Py_RETURN_NONE;
343}
344
Tim Peters1065f752004-10-01 01:03:29 +0000345PyDoc_STRVAR(extend_doc,
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000346"Extend the right side of the deque with elements from the iterable");
347
348static PyObject *
349deque_extendleft(dequeobject *deque, PyObject *iterable)
350{
351 PyObject *it, *item;
352
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000353 /* Handle case where id(deque) == id(iterable) */
354 if ((PyObject *)deque == iterable) {
355 PyObject *result;
356 PyObject *s = PySequence_List(iterable);
357 if (s == NULL)
358 return NULL;
359 result = deque_extendleft(deque, s);
360 Py_DECREF(s);
361 return result;
362 }
363
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000364 it = PyObject_GetIter(iterable);
365 if (it == NULL)
366 return NULL;
367
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000368 if (deque->maxlen == 0)
369 return consume_iterator(it);
370
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000371 while ((item = PyIter_Next(it)) != NULL) {
Raymond Hettingerd1b3d882004-10-02 00:43:13 +0000372 deque->state++;
Armin Rigo974d7572004-10-02 13:59:34 +0000373 if (deque->leftindex == 0) {
Raymond Hettingerc5fa9922004-10-06 17:51:54 +0000374 block *b = newblock(NULL, deque->leftblock,
375 deque->len);
Raymond Hettingerc058fd12004-02-07 02:45:22 +0000376 if (b == NULL) {
377 Py_DECREF(item);
378 Py_DECREF(it);
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000379 return NULL;
Raymond Hettingerc058fd12004-02-07 02:45:22 +0000380 }
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000381 assert(deque->leftblock->leftlink == NULL);
382 deque->leftblock->leftlink = b;
383 deque->leftblock = b;
Armin Rigo974d7572004-10-02 13:59:34 +0000384 deque->leftindex = BLOCKLEN;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000385 }
Armin Rigo974d7572004-10-02 13:59:34 +0000386 deque->len++;
387 deque->leftindex--;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000388 deque->leftblock->data[deque->leftindex] = item;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000389 TRIM(deque, deque_pop);
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000390 }
391 Py_DECREF(it);
Raymond Hettingera435c532004-07-09 04:10:20 +0000392 if (PyErr_Occurred())
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000393 return NULL;
394 Py_RETURN_NONE;
395}
396
Tim Peters1065f752004-10-01 01:03:29 +0000397PyDoc_STRVAR(extendleft_doc,
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000398"Extend the left side of the deque with elements from the iterable");
399
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000400static PyObject *
401deque_inplace_concat(dequeobject *deque, PyObject *other)
402{
403 PyObject *result;
404
405 result = deque_extend(deque, other);
406 if (result == NULL)
407 return result;
408 Py_DECREF(result);
409 Py_INCREF(deque);
410 return (PyObject *)deque;
411}
412
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000413static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000414_deque_rotate(dequeobject *deque, Py_ssize_t n)
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000415{
Benjamin Petersond6313712008-07-31 16:23:04 +0000416 Py_ssize_t i, len=deque->len, halflen=(len+1)>>1;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000417 PyObject *item, *rv;
418
Raymond Hettingeree33b272004-02-08 04:05:26 +0000419 if (len == 0)
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000420 return 0;
Raymond Hettingeree33b272004-02-08 04:05:26 +0000421 if (n > halflen || n < -halflen) {
422 n %= len;
423 if (n > halflen)
424 n -= len;
425 else if (n < -halflen)
426 n += len;
427 }
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000428
429 for (i=0 ; i<n ; i++) {
430 item = deque_pop(deque, NULL);
Raymond Hettingera435c532004-07-09 04:10:20 +0000431 assert (item != NULL);
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000432 rv = deque_appendleft(deque, item);
433 Py_DECREF(item);
434 if (rv == NULL)
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000435 return -1;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000436 Py_DECREF(rv);
437 }
438 for (i=0 ; i>n ; i--) {
439 item = deque_popleft(deque, NULL);
Raymond Hettingera435c532004-07-09 04:10:20 +0000440 assert (item != NULL);
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000441 rv = deque_append(deque, item);
442 Py_DECREF(item);
443 if (rv == NULL)
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000444 return -1;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000445 Py_DECREF(rv);
446 }
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000447 return 0;
448}
449
450static PyObject *
451deque_rotate(dequeobject *deque, PyObject *args)
452{
Benjamin Petersond6313712008-07-31 16:23:04 +0000453 Py_ssize_t n=1;
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000454
Benjamin Petersond6313712008-07-31 16:23:04 +0000455 if (!PyArg_ParseTuple(args, "|n:rotate", &n))
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000456 return NULL;
457 if (_deque_rotate(deque, n) == 0)
458 Py_RETURN_NONE;
459 return NULL;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000460}
461
Tim Peters1065f752004-10-01 01:03:29 +0000462PyDoc_STRVAR(rotate_doc,
Raymond Hettingeree33b272004-02-08 04:05:26 +0000463"Rotate the deque n steps to the right (default n=1). If n is negative, rotates left.");
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000464
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000465static PyObject *
466deque_reverse(dequeobject *deque, PyObject *unused)
467{
468 block *leftblock = deque->leftblock;
469 block *rightblock = deque->rightblock;
470 Py_ssize_t leftindex = deque->leftindex;
471 Py_ssize_t rightindex = deque->rightindex;
472 Py_ssize_t n = (deque->len)/2;
473 Py_ssize_t i;
474 PyObject *tmp;
475
476 for (i=0 ; i<n ; i++) {
477 /* Validate that pointers haven't met in the middle */
478 assert(leftblock != rightblock || leftindex < rightindex);
479
480 /* Swap */
481 tmp = leftblock->data[leftindex];
482 leftblock->data[leftindex] = rightblock->data[rightindex];
483 rightblock->data[rightindex] = tmp;
484
485 /* Advance left block/index pair */
486 leftindex++;
487 if (leftindex == BLOCKLEN) {
488 assert (leftblock->rightlink != NULL);
489 leftblock = leftblock->rightlink;
490 leftindex = 0;
491 }
492
493 /* Step backwards with the right block/index pair */
494 rightindex--;
495 if (rightindex == -1) {
496 assert (rightblock->leftlink != NULL);
497 rightblock = rightblock->leftlink;
498 rightindex = BLOCKLEN - 1;
499 }
500 }
501 Py_RETURN_NONE;
502}
503
504PyDoc_STRVAR(reverse_doc,
505"D.reverse() -- reverse *IN PLACE*");
506
Raymond Hettinger44459de2010-04-03 23:20:46 +0000507static PyObject *
508deque_count(dequeobject *deque, PyObject *v)
509{
510 block *leftblock = deque->leftblock;
511 Py_ssize_t leftindex = deque->leftindex;
512 Py_ssize_t n = (deque->len);
513 Py_ssize_t i;
514 Py_ssize_t count = 0;
515 PyObject *item;
516 long start_state = deque->state;
517 int cmp;
518
519 for (i=0 ; i<n ; i++) {
520 item = leftblock->data[leftindex];
521 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
522 if (cmp > 0)
523 count++;
524 else if (cmp < 0)
525 return NULL;
526
527 if (start_state != deque->state) {
528 PyErr_SetString(PyExc_RuntimeError,
529 "deque mutated during iteration");
530 return NULL;
531 }
532
533 /* Advance left block/index pair */
534 leftindex++;
535 if (leftindex == BLOCKLEN) {
536 assert (leftblock->rightlink != NULL);
537 leftblock = leftblock->rightlink;
538 leftindex = 0;
539 }
540 }
541 return PyLong_FromSsize_t(count);
542}
543
544PyDoc_STRVAR(count_doc,
545"D.count(value) -> integer -- return number of occurrences of value");
546
Martin v. Löwis18e16552006-02-15 17:27:45 +0000547static Py_ssize_t
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000548deque_len(dequeobject *deque)
549{
550 return deque->len;
551}
552
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000553static PyObject *
554deque_remove(dequeobject *deque, PyObject *value)
555{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000556 Py_ssize_t i, n=deque->len;
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000557
558 for (i=0 ; i<n ; i++) {
559 PyObject *item = deque->leftblock->data[deque->leftindex];
560 int cmp = PyObject_RichCompareBool(item, value, Py_EQ);
Raymond Hettingerd73202c2005-03-19 00:00:51 +0000561
562 if (deque->len != n) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000563 PyErr_SetString(PyExc_IndexError,
Raymond Hettingerd73202c2005-03-19 00:00:51 +0000564 "deque mutated during remove().");
565 return NULL;
566 }
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000567 if (cmp > 0) {
Raymond Hettingerd73202c2005-03-19 00:00:51 +0000568 PyObject *tgt = deque_popleft(deque, NULL);
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000569 assert (tgt != NULL);
570 Py_DECREF(tgt);
571 if (_deque_rotate(deque, i) == -1)
572 return NULL;
573 Py_RETURN_NONE;
574 }
575 else if (cmp < 0) {
576 _deque_rotate(deque, i);
577 return NULL;
578 }
579 _deque_rotate(deque, -1);
580 }
581 PyErr_SetString(PyExc_ValueError, "deque.remove(x): x not in deque");
582 return NULL;
583}
584
585PyDoc_STRVAR(remove_doc,
586"D.remove(value) -- remove first occurrence of value.");
587
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000588static int
589deque_clear(dequeobject *deque)
590{
591 PyObject *item;
592
Raymond Hettingerd1b3d882004-10-02 00:43:13 +0000593 while (deque->len) {
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000594 item = deque_pop(deque, NULL);
Raymond Hettingera435c532004-07-09 04:10:20 +0000595 assert (item != NULL);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000596 Py_DECREF(item);
597 }
598 assert(deque->leftblock == deque->rightblock &&
Raymond Hettingerd1b3d882004-10-02 00:43:13 +0000599 deque->leftindex - 1 == deque->rightindex &&
600 deque->len == 0);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000601 return 0;
602}
603
604static PyObject *
Benjamin Petersond6313712008-07-31 16:23:04 +0000605deque_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000606{
607 block *b;
608 PyObject *item;
Benjamin Petersond6313712008-07-31 16:23:04 +0000609 Py_ssize_t n, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000610
611 if (i < 0 || i >= deque->len) {
612 PyErr_SetString(PyExc_IndexError,
613 "deque index out of range");
614 return NULL;
615 }
616
Raymond Hettinger6c79a512004-03-04 08:00:54 +0000617 if (i == 0) {
618 i = deque->leftindex;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000619 b = deque->leftblock;
Raymond Hettinger6c79a512004-03-04 08:00:54 +0000620 } else if (i == deque->len - 1) {
621 i = deque->rightindex;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000622 b = deque->rightblock;
Raymond Hettinger6c79a512004-03-04 08:00:54 +0000623 } else {
624 i += deque->leftindex;
625 n = i / BLOCKLEN;
626 i %= BLOCKLEN;
Armin Rigo974d7572004-10-02 13:59:34 +0000627 if (index < (deque->len >> 1)) {
Raymond Hettinger6c79a512004-03-04 08:00:54 +0000628 b = deque->leftblock;
629 while (n--)
630 b = b->rightlink;
631 } else {
632 n = (deque->leftindex + deque->len - 1) / BLOCKLEN - n;
633 b = deque->rightblock;
634 while (n--)
635 b = b->leftlink;
636 }
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000637 }
638 item = b->data[i];
639 Py_INCREF(item);
640 return item;
641}
642
Raymond Hettinger616f4f62004-06-26 04:42:06 +0000643/* delitem() implemented in terms of rotate for simplicity and reasonable
644 performance near the end points. If for some reason this method becomes
Tim Peters1065f752004-10-01 01:03:29 +0000645 popular, it is not hard to re-implement this using direct data movement
Raymond Hettinger616f4f62004-06-26 04:42:06 +0000646 (similar to code in list slice assignment) and achieve a two or threefold
647 performance boost.
648*/
649
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000650static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000651deque_del_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000652{
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000653 PyObject *item;
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000654
Tim Peters1065f752004-10-01 01:03:29 +0000655 assert (i >= 0 && i < deque->len);
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000656 if (_deque_rotate(deque, -i) == -1)
657 return -1;
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000658
659 item = deque_popleft(deque, NULL);
Raymond Hettingera435c532004-07-09 04:10:20 +0000660 assert (item != NULL);
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000661 Py_DECREF(item);
662
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000663 return _deque_rotate(deque, i);
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000664}
665
666static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000667deque_ass_item(dequeobject *deque, Py_ssize_t i, PyObject *v)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000668{
669 PyObject *old_value;
670 block *b;
Martin v. Löwisad0a4622006-02-16 14:30:23 +0000671 Py_ssize_t n, len=deque->len, halflen=(len+1)>>1, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000672
Raymond Hettingera435c532004-07-09 04:10:20 +0000673 if (i < 0 || i >= len) {
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000674 PyErr_SetString(PyExc_IndexError,
675 "deque index out of range");
676 return -1;
677 }
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000678 if (v == NULL)
679 return deque_del_item(deque, i);
680
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000681 i += deque->leftindex;
682 n = i / BLOCKLEN;
683 i %= BLOCKLEN;
Raymond Hettingera435c532004-07-09 04:10:20 +0000684 if (index <= halflen) {
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000685 b = deque->leftblock;
686 while (n--)
687 b = b->rightlink;
688 } else {
Raymond Hettingera435c532004-07-09 04:10:20 +0000689 n = (deque->leftindex + len - 1) / BLOCKLEN - n;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000690 b = deque->rightblock;
691 while (n--)
692 b = b->leftlink;
693 }
694 Py_INCREF(v);
695 old_value = b->data[i];
696 b->data[i] = v;
697 Py_DECREF(old_value);
698 return 0;
699}
700
701static PyObject *
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000702deque_clearmethod(dequeobject *deque)
703{
Raymond Hettingera435c532004-07-09 04:10:20 +0000704 int rv;
705
706 rv = deque_clear(deque);
707 assert (rv != -1);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000708 Py_RETURN_NONE;
709}
710
711PyDoc_STRVAR(clear_doc, "Remove all elements from the deque.");
712
713static void
714deque_dealloc(dequeobject *deque)
715{
716 PyObject_GC_UnTrack(deque);
Raymond Hettinger691d8052004-05-30 07:26:47 +0000717 if (deque->weakreflist != NULL)
718 PyObject_ClearWeakRefs((PyObject *) deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000719 if (deque->leftblock != NULL) {
Raymond Hettingere9c89e82004-07-19 00:10:24 +0000720 deque_clear(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000721 assert(deque->leftblock != NULL);
Guido van Rossum58da9312007-11-10 23:39:45 +0000722 freeblock(deque->leftblock);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000723 }
724 deque->leftblock = NULL;
725 deque->rightblock = NULL;
Christian Heimes90aa7642007-12-19 02:45:37 +0000726 Py_TYPE(deque)->tp_free(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000727}
728
729static int
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000730deque_traverse(dequeobject *deque, visitproc visit, void *arg)
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000731{
Tim Peters10c7e862004-10-01 02:01:04 +0000732 block *b;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000733 PyObject *item;
Benjamin Petersond6313712008-07-31 16:23:04 +0000734 Py_ssize_t index;
735 Py_ssize_t indexlo = deque->leftindex;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000736
Tim Peters10c7e862004-10-01 02:01:04 +0000737 for (b = deque->leftblock; b != NULL; b = b->rightlink) {
Benjamin Petersond6313712008-07-31 16:23:04 +0000738 const Py_ssize_t indexhi = b == deque->rightblock ?
Tim Peters10c7e862004-10-01 02:01:04 +0000739 deque->rightindex :
740 BLOCKLEN - 1;
741
742 for (index = indexlo; index <= indexhi; ++index) {
743 item = b->data[index];
744 Py_VISIT(item);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000745 }
Tim Peters10c7e862004-10-01 02:01:04 +0000746 indexlo = 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000747 }
748 return 0;
749}
750
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000751static PyObject *
752deque_copy(PyObject *deque)
753{
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000754 if (((dequeobject *)deque)->maxlen == -1)
Christian Heimes90aa7642007-12-19 02:45:37 +0000755 return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "O", deque, NULL);
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000756 else
Christian Heimes90aa7642007-12-19 02:45:37 +0000757 return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "Oi",
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000758 deque, ((dequeobject *)deque)->maxlen, NULL);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000759}
760
761PyDoc_STRVAR(copy_doc, "Return a shallow copy of a deque.");
762
763static PyObject *
764deque_reduce(dequeobject *deque)
765{
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000766 PyObject *dict, *result, *aslist;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000767
Raymond Hettinger952f8802004-11-09 07:27:35 +0000768 dict = PyObject_GetAttrString((PyObject *)deque, "__dict__");
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000769 if (dict == NULL)
Raymond Hettinger952f8802004-11-09 07:27:35 +0000770 PyErr_Clear();
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000771 aslist = PySequence_List((PyObject *)deque);
772 if (aslist == NULL) {
773 Py_XDECREF(dict);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000774 return NULL;
775 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000776 if (dict == NULL) {
777 if (deque->maxlen == -1)
Christian Heimes90aa7642007-12-19 02:45:37 +0000778 result = Py_BuildValue("O(O)", Py_TYPE(deque), aslist);
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000779 else
Benjamin Petersond6313712008-07-31 16:23:04 +0000780 result = Py_BuildValue("O(On)", Py_TYPE(deque), aslist, deque->maxlen);
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000781 } else {
782 if (deque->maxlen == -1)
Christian Heimes90aa7642007-12-19 02:45:37 +0000783 result = Py_BuildValue("O(OO)O", Py_TYPE(deque), aslist, Py_None, dict);
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000784 else
Benjamin Petersond6313712008-07-31 16:23:04 +0000785 result = Py_BuildValue("O(On)O", Py_TYPE(deque), aslist, deque->maxlen, dict);
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000786 }
787 Py_XDECREF(dict);
788 Py_DECREF(aslist);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000789 return result;
790}
791
792PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
793
794static PyObject *
795deque_repr(PyObject *deque)
796{
Walter Dörwald1ab83302007-05-18 17:15:44 +0000797 PyObject *aslist, *result;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000798 int i;
799
800 i = Py_ReprEnter(deque);
801 if (i != 0) {
802 if (i < 0)
803 return NULL;
Walter Dörwald1ab83302007-05-18 17:15:44 +0000804 return PyUnicode_FromString("[...]");
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000805 }
806
807 aslist = PySequence_List(deque);
808 if (aslist == NULL) {
809 Py_ReprLeave(deque);
810 return NULL;
811 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000812 if (((dequeobject *)deque)->maxlen != -1)
Benjamin Petersona786b022008-08-25 21:05:21 +0000813
Amaury Forgeot d'Arc245c70b2008-09-10 22:24:24 +0000814 result = PyUnicode_FromFormat("deque(%R, maxlen=%zd)",
Benjamin Petersona786b022008-08-25 21:05:21 +0000815 aslist, ((dequeobject *)deque)->maxlen);
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000816 else
817 result = PyUnicode_FromFormat("deque(%R)", aslist);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000818 Py_DECREF(aslist);
819 Py_ReprLeave(deque);
820 return result;
821}
822
Raymond Hettinger738ec902004-02-29 02:15:56 +0000823static PyObject *
824deque_richcompare(PyObject *v, PyObject *w, int op)
825{
826 PyObject *it1=NULL, *it2=NULL, *x, *y;
Benjamin Petersond6313712008-07-31 16:23:04 +0000827 Py_ssize_t vs, ws;
828 int b, cmp=-1;
Raymond Hettinger738ec902004-02-29 02:15:56 +0000829
Tim Peters1065f752004-10-01 01:03:29 +0000830 if (!PyObject_TypeCheck(v, &deque_type) ||
Raymond Hettinger285cfcc2004-05-18 18:15:03 +0000831 !PyObject_TypeCheck(w, &deque_type)) {
Raymond Hettinger738ec902004-02-29 02:15:56 +0000832 Py_INCREF(Py_NotImplemented);
833 return Py_NotImplemented;
834 }
835
836 /* Shortcuts */
837 vs = ((dequeobject *)v)->len;
838 ws = ((dequeobject *)w)->len;
839 if (op == Py_EQ) {
840 if (v == w)
841 Py_RETURN_TRUE;
842 if (vs != ws)
843 Py_RETURN_FALSE;
844 }
845 if (op == Py_NE) {
846 if (v == w)
847 Py_RETURN_FALSE;
848 if (vs != ws)
849 Py_RETURN_TRUE;
850 }
851
852 /* Search for the first index where items are different */
853 it1 = PyObject_GetIter(v);
854 if (it1 == NULL)
855 goto done;
856 it2 = PyObject_GetIter(w);
857 if (it2 == NULL)
858 goto done;
Armin Rigo974d7572004-10-02 13:59:34 +0000859 for (;;) {
Raymond Hettinger738ec902004-02-29 02:15:56 +0000860 x = PyIter_Next(it1);
Armin Rigo974d7572004-10-02 13:59:34 +0000861 if (x == NULL && PyErr_Occurred())
Raymond Hettinger738ec902004-02-29 02:15:56 +0000862 goto done;
863 y = PyIter_Next(it2);
Armin Rigo974d7572004-10-02 13:59:34 +0000864 if (x == NULL || y == NULL)
865 break;
Raymond Hettinger738ec902004-02-29 02:15:56 +0000866 b = PyObject_RichCompareBool(x, y, Py_EQ);
867 if (b == 0) {
868 cmp = PyObject_RichCompareBool(x, y, op);
869 Py_DECREF(x);
870 Py_DECREF(y);
871 goto done;
872 }
873 Py_DECREF(x);
874 Py_DECREF(y);
875 if (b == -1)
876 goto done;
877 }
Armin Rigo974d7572004-10-02 13:59:34 +0000878 /* We reached the end of one deque or both */
879 Py_XDECREF(x);
880 Py_XDECREF(y);
881 if (PyErr_Occurred())
882 goto done;
Raymond Hettinger738ec902004-02-29 02:15:56 +0000883 switch (op) {
Armin Rigo974d7572004-10-02 13:59:34 +0000884 case Py_LT: cmp = y != NULL; break; /* if w was longer */
885 case Py_LE: cmp = x == NULL; break; /* if v was not longer */
886 case Py_EQ: cmp = x == y; break; /* if we reached the end of both */
887 case Py_NE: cmp = x != y; break; /* if one deque continues */
888 case Py_GT: cmp = x != NULL; break; /* if v was longer */
889 case Py_GE: cmp = y == NULL; break; /* if w was not longer */
Raymond Hettinger738ec902004-02-29 02:15:56 +0000890 }
Tim Peters1065f752004-10-01 01:03:29 +0000891
Raymond Hettinger738ec902004-02-29 02:15:56 +0000892done:
893 Py_XDECREF(it1);
894 Py_XDECREF(it2);
895 if (cmp == 1)
896 Py_RETURN_TRUE;
897 if (cmp == 0)
898 Py_RETURN_FALSE;
899 return NULL;
900}
901
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000902static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000903deque_init(dequeobject *deque, PyObject *args, PyObject *kwdargs)
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000904{
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000905 PyObject *iterable = NULL;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000906 PyObject *maxlenobj = NULL;
Benjamin Petersond6313712008-07-31 16:23:04 +0000907 Py_ssize_t maxlen = -1;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000908 char *kwlist[] = {"iterable", "maxlen", 0};
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000909
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000910 if (!PyArg_ParseTupleAndKeywords(args, kwdargs, "|OO:deque", kwlist, &iterable, &maxlenobj))
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000911 return -1;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000912 if (maxlenobj != NULL && maxlenobj != Py_None) {
Benjamin Petersond6313712008-07-31 16:23:04 +0000913 maxlen = PyLong_AsSsize_t(maxlenobj);
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000914 if (maxlen == -1 && PyErr_Occurred())
915 return -1;
916 if (maxlen < 0) {
917 PyErr_SetString(PyExc_ValueError, "maxlen must be non-negative");
918 return -1;
919 }
920 }
921 deque->maxlen = maxlen;
Christian Heimes38053212007-12-14 01:24:44 +0000922 deque_clear(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000923 if (iterable != NULL) {
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000924 PyObject *rv = deque_extend(deque, iterable);
925 if (rv == NULL)
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000926 return -1;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000927 Py_DECREF(rv);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000928 }
929 return 0;
930}
931
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +0000932static PyObject *
933deque_get_maxlen(dequeobject *deque)
934{
935 if (deque->maxlen == -1)
936 Py_RETURN_NONE;
937 return PyLong_FromSsize_t(deque->maxlen);
938}
939
940static PyGetSetDef deque_getset[] = {
941 {"maxlen", (getter)deque_get_maxlen, (setter)NULL,
942 "maximum size of a deque or None if unbounded"},
943 {0}
944};
945
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000946static PySequenceMethods deque_as_sequence = {
Martin v. Löwis18e16552006-02-15 17:27:45 +0000947 (lenfunc)deque_len, /* sq_length */
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000948 0, /* sq_concat */
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000949 0, /* sq_repeat */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000950 (ssizeargfunc)deque_item, /* sq_item */
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000951 0, /* sq_slice */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000952 (ssizeobjargproc)deque_ass_item, /* sq_ass_item */
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000953 0, /* sq_ass_slice */
954 0, /* sq_contains */
955 (binaryfunc)deque_inplace_concat, /* sq_inplace_concat */
956 0, /* sq_inplace_repeat */
957
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000958};
959
960/* deque object ********************************************************/
961
962static PyObject *deque_iter(dequeobject *deque);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +0000963static PyObject *deque_reviter(dequeobject *deque);
Tim Peters1065f752004-10-01 01:03:29 +0000964PyDoc_STRVAR(reversed_doc,
Raymond Hettinger1e5809f2004-03-18 11:04:57 +0000965 "D.__reversed__() -- return a reverse iterator over the deque");
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000966
967static PyMethodDef deque_methods[] = {
Tim Peters1065f752004-10-01 01:03:29 +0000968 {"append", (PyCFunction)deque_append,
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000969 METH_O, append_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000970 {"appendleft", (PyCFunction)deque_appendleft,
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000971 METH_O, appendleft_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000972 {"clear", (PyCFunction)deque_clearmethod,
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000973 METH_NOARGS, clear_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000974 {"__copy__", (PyCFunction)deque_copy,
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000975 METH_NOARGS, copy_doc},
Raymond Hettinger44459de2010-04-03 23:20:46 +0000976 {"count", (PyCFunction)deque_count,
977 METH_O, count_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000978 {"extend", (PyCFunction)deque_extend,
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000979 METH_O, extend_doc},
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000980 {"extendleft", (PyCFunction)deque_extendleft,
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000981 METH_O, extendleft_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000982 {"pop", (PyCFunction)deque_pop,
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000983 METH_NOARGS, pop_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000984 {"popleft", (PyCFunction)deque_popleft,
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000985 METH_NOARGS, popleft_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000986 {"__reduce__", (PyCFunction)deque_reduce,
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000987 METH_NOARGS, reduce_doc},
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000988 {"remove", (PyCFunction)deque_remove,
989 METH_O, remove_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000990 {"__reversed__", (PyCFunction)deque_reviter,
Raymond Hettinger1e5809f2004-03-18 11:04:57 +0000991 METH_NOARGS, reversed_doc},
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000992 {"reverse", (PyCFunction)deque_reverse,
993 METH_NOARGS, reverse_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000994 {"rotate", (PyCFunction)deque_rotate,
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000995 METH_VARARGS, rotate_doc},
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000996 {NULL, NULL} /* sentinel */
997};
998
999PyDoc_STRVAR(deque_doc,
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001000"deque(iterable[, maxlen]) --> deque object\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001001\n\
1002Build an ordered collection accessible from endpoints only.");
1003
Neal Norwitz87f10132004-02-29 15:40:53 +00001004static PyTypeObject deque_type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001005 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001006 "collections.deque", /* tp_name */
1007 sizeof(dequeobject), /* tp_basicsize */
1008 0, /* tp_itemsize */
1009 /* methods */
1010 (destructor)deque_dealloc, /* tp_dealloc */
Guido van Rossum346f1a82007-08-07 19:58:47 +00001011 0, /* tp_print */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001012 0, /* tp_getattr */
1013 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00001014 0, /* tp_reserved */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001015 deque_repr, /* tp_repr */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001016 0, /* tp_as_number */
1017 &deque_as_sequence, /* tp_as_sequence */
1018 0, /* tp_as_mapping */
Nick Coghland1abd252008-07-15 15:46:38 +00001019 (hashfunc)PyObject_HashNotImplemented, /* tp_hash */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001020 0, /* tp_call */
1021 0, /* tp_str */
1022 PyObject_GenericGetAttr, /* tp_getattro */
1023 0, /* tp_setattro */
1024 0, /* tp_as_buffer */
Guido van Rossumd8faa362007-04-27 19:54:29 +00001025 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
1026 /* tp_flags */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001027 deque_doc, /* tp_doc */
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001028 (traverseproc)deque_traverse, /* tp_traverse */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001029 (inquiry)deque_clear, /* tp_clear */
Raymond Hettinger738ec902004-02-29 02:15:56 +00001030 (richcmpfunc)deque_richcompare, /* tp_richcompare */
Raymond Hettinger691d8052004-05-30 07:26:47 +00001031 offsetof(dequeobject, weakreflist), /* tp_weaklistoffset*/
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001032 (getiterfunc)deque_iter, /* tp_iter */
1033 0, /* tp_iternext */
1034 deque_methods, /* tp_methods */
1035 0, /* tp_members */
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001036 deque_getset, /* tp_getset */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001037 0, /* tp_base */
1038 0, /* tp_dict */
1039 0, /* tp_descr_get */
1040 0, /* tp_descr_set */
1041 0, /* tp_dictoffset */
1042 (initproc)deque_init, /* tp_init */
1043 PyType_GenericAlloc, /* tp_alloc */
1044 deque_new, /* tp_new */
1045 PyObject_GC_Del, /* tp_free */
1046};
1047
1048/*********************** Deque Iterator **************************/
1049
1050typedef struct {
1051 PyObject_HEAD
Benjamin Petersond6313712008-07-31 16:23:04 +00001052 Py_ssize_t index;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001053 block *b;
1054 dequeobject *deque;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001055 long state; /* state when the iterator is created */
Benjamin Petersond6313712008-07-31 16:23:04 +00001056 Py_ssize_t counter; /* number of items remaining for iteration */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001057} dequeiterobject;
1058
Martin v. Löwis59683e82008-06-13 07:50:45 +00001059static PyTypeObject dequeiter_type;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001060
1061static PyObject *
1062deque_iter(dequeobject *deque)
1063{
1064 dequeiterobject *it;
1065
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001066 it = PyObject_GC_New(dequeiterobject, &dequeiter_type);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001067 if (it == NULL)
1068 return NULL;
1069 it->b = deque->leftblock;
1070 it->index = deque->leftindex;
1071 Py_INCREF(deque);
1072 it->deque = deque;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001073 it->state = deque->state;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001074 it->counter = deque->len;
Georg Brandlb1441c72009-01-03 22:33:39 +00001075 PyObject_GC_Track(it);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001076 return (PyObject *)it;
1077}
1078
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001079static int
1080dequeiter_traverse(dequeiterobject *dio, visitproc visit, void *arg)
1081{
1082 Py_VISIT(dio->deque);
1083 return 0;
1084}
1085
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001086static void
1087dequeiter_dealloc(dequeiterobject *dio)
1088{
1089 Py_XDECREF(dio->deque);
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001090 PyObject_GC_Del(dio);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001091}
1092
1093static PyObject *
1094dequeiter_next(dequeiterobject *it)
1095{
1096 PyObject *item;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001097
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001098 if (it->deque->state != it->state) {
Raymond Hettinger7892b1c2004-04-12 18:10:01 +00001099 it->counter = 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001100 PyErr_SetString(PyExc_RuntimeError,
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001101 "deque mutated during iteration");
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001102 return NULL;
1103 }
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001104 if (it->counter == 0)
1105 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001106 assert (!(it->b == it->deque->rightblock &&
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001107 it->index > it->deque->rightindex));
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001108
1109 item = it->b->data[it->index];
1110 it->index++;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001111 it->counter--;
1112 if (it->index == BLOCKLEN && it->counter > 0) {
1113 assert (it->b->rightlink != NULL);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001114 it->b = it->b->rightlink;
1115 it->index = 0;
1116 }
1117 Py_INCREF(item);
1118 return item;
1119}
1120
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001121static PyObject *
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001122dequeiter_len(dequeiterobject *it)
1123{
Christian Heimes217cfd12007-12-02 14:31:20 +00001124 return PyLong_FromLong(it->counter);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001125}
1126
Armin Rigof5b3e362006-02-11 21:32:43 +00001127PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001128
1129static PyMethodDef dequeiter_methods[] = {
Armin Rigof5b3e362006-02-11 21:32:43 +00001130 {"__length_hint__", (PyCFunction)dequeiter_len, METH_NOARGS, length_hint_doc},
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001131 {NULL, NULL} /* sentinel */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001132};
1133
Martin v. Löwis59683e82008-06-13 07:50:45 +00001134static PyTypeObject dequeiter_type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001135 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001136 "deque_iterator", /* tp_name */
1137 sizeof(dequeiterobject), /* tp_basicsize */
1138 0, /* tp_itemsize */
1139 /* methods */
1140 (destructor)dequeiter_dealloc, /* tp_dealloc */
1141 0, /* tp_print */
1142 0, /* tp_getattr */
1143 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00001144 0, /* tp_reserved */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001145 0, /* tp_repr */
1146 0, /* tp_as_number */
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001147 0, /* tp_as_sequence */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001148 0, /* tp_as_mapping */
1149 0, /* tp_hash */
1150 0, /* tp_call */
1151 0, /* tp_str */
1152 PyObject_GenericGetAttr, /* tp_getattro */
1153 0, /* tp_setattro */
1154 0, /* tp_as_buffer */
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001155 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001156 0, /* tp_doc */
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001157 (traverseproc)dequeiter_traverse, /* tp_traverse */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001158 0, /* tp_clear */
1159 0, /* tp_richcompare */
1160 0, /* tp_weaklistoffset */
1161 PyObject_SelfIter, /* tp_iter */
1162 (iternextfunc)dequeiter_next, /* tp_iternext */
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001163 dequeiter_methods, /* tp_methods */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001164 0,
1165};
1166
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001167/*********************** Deque Reverse Iterator **************************/
1168
Martin v. Löwis59683e82008-06-13 07:50:45 +00001169static PyTypeObject dequereviter_type;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001170
1171static PyObject *
1172deque_reviter(dequeobject *deque)
1173{
1174 dequeiterobject *it;
1175
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001176 it = PyObject_GC_New(dequeiterobject, &dequereviter_type);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001177 if (it == NULL)
1178 return NULL;
1179 it->b = deque->rightblock;
1180 it->index = deque->rightindex;
1181 Py_INCREF(deque);
1182 it->deque = deque;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001183 it->state = deque->state;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001184 it->counter = deque->len;
Georg Brandlb1441c72009-01-03 22:33:39 +00001185 PyObject_GC_Track(it);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001186 return (PyObject *)it;
1187}
1188
1189static PyObject *
1190dequereviter_next(dequeiterobject *it)
1191{
1192 PyObject *item;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001193 if (it->counter == 0)
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001194 return NULL;
1195
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001196 if (it->deque->state != it->state) {
Raymond Hettinger7892b1c2004-04-12 18:10:01 +00001197 it->counter = 0;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001198 PyErr_SetString(PyExc_RuntimeError,
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001199 "deque mutated during iteration");
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001200 return NULL;
1201 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001202 assert (!(it->b == it->deque->leftblock &&
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001203 it->index < it->deque->leftindex));
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001204
1205 item = it->b->data[it->index];
1206 it->index--;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001207 it->counter--;
1208 if (it->index == -1 && it->counter > 0) {
1209 assert (it->b->leftlink != NULL);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001210 it->b = it->b->leftlink;
1211 it->index = BLOCKLEN - 1;
1212 }
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001213 Py_INCREF(item);
1214 return item;
1215}
1216
Martin v. Löwis59683e82008-06-13 07:50:45 +00001217static PyTypeObject dequereviter_type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001218 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001219 "deque_reverse_iterator", /* tp_name */
1220 sizeof(dequeiterobject), /* tp_basicsize */
1221 0, /* tp_itemsize */
1222 /* methods */
1223 (destructor)dequeiter_dealloc, /* tp_dealloc */
1224 0, /* tp_print */
1225 0, /* tp_getattr */
1226 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00001227 0, /* tp_reserved */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001228 0, /* tp_repr */
1229 0, /* tp_as_number */
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001230 0, /* tp_as_sequence */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001231 0, /* tp_as_mapping */
1232 0, /* tp_hash */
1233 0, /* tp_call */
1234 0, /* tp_str */
1235 PyObject_GenericGetAttr, /* tp_getattro */
1236 0, /* tp_setattro */
1237 0, /* tp_as_buffer */
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001238 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001239 0, /* tp_doc */
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001240 (traverseproc)dequeiter_traverse, /* tp_traverse */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001241 0, /* tp_clear */
1242 0, /* tp_richcompare */
1243 0, /* tp_weaklistoffset */
1244 PyObject_SelfIter, /* tp_iter */
1245 (iternextfunc)dequereviter_next, /* tp_iternext */
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001246 dequeiter_methods, /* tp_methods */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001247 0,
1248};
1249
Guido van Rossum1968ad32006-02-25 22:38:04 +00001250/* defaultdict type *********************************************************/
1251
1252typedef struct {
1253 PyDictObject dict;
1254 PyObject *default_factory;
1255} defdictobject;
1256
1257static PyTypeObject defdict_type; /* Forward */
1258
1259PyDoc_STRVAR(defdict_missing_doc,
1260"__missing__(key) # Called by __getitem__ for missing key; pseudo-code:\n\
Guido van Rossumd8faa362007-04-27 19:54:29 +00001261 if self.default_factory is None: raise KeyError((key,))\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00001262 self[key] = value = self.default_factory()\n\
1263 return value\n\
1264");
1265
1266static PyObject *
1267defdict_missing(defdictobject *dd, PyObject *key)
1268{
1269 PyObject *factory = dd->default_factory;
1270 PyObject *value;
1271 if (factory == NULL || factory == Py_None) {
1272 /* XXX Call dict.__missing__(key) */
Guido van Rossumd8faa362007-04-27 19:54:29 +00001273 PyObject *tup;
1274 tup = PyTuple_Pack(1, key);
1275 if (!tup) return NULL;
1276 PyErr_SetObject(PyExc_KeyError, tup);
1277 Py_DECREF(tup);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001278 return NULL;
1279 }
1280 value = PyEval_CallObject(factory, NULL);
1281 if (value == NULL)
1282 return value;
1283 if (PyObject_SetItem((PyObject *)dd, key, value) < 0) {
1284 Py_DECREF(value);
1285 return NULL;
1286 }
1287 return value;
1288}
1289
1290PyDoc_STRVAR(defdict_copy_doc, "D.copy() -> a shallow copy of D.");
1291
1292static PyObject *
1293defdict_copy(defdictobject *dd)
1294{
1295 /* This calls the object's class. That only works for subclasses
1296 whose class constructor has the same signature. Subclasses that
Christian Heimes0bd4e112008-02-12 22:59:25 +00001297 define a different constructor signature must override copy().
Guido van Rossum1968ad32006-02-25 22:38:04 +00001298 */
Raymond Hettinger54628fa2009-08-04 19:16:39 +00001299
1300 if (dd->default_factory == NULL)
1301 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd), Py_None, dd, NULL);
Christian Heimes90aa7642007-12-19 02:45:37 +00001302 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd),
Guido van Rossum1968ad32006-02-25 22:38:04 +00001303 dd->default_factory, dd, NULL);
1304}
1305
1306static PyObject *
1307defdict_reduce(defdictobject *dd)
1308{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001309 /* __reduce__ must return a 5-tuple as follows:
Guido van Rossum1968ad32006-02-25 22:38:04 +00001310
1311 - factory function
1312 - tuple of args for the factory function
1313 - additional state (here None)
1314 - sequence iterator (here None)
1315 - dictionary iterator (yielding successive (key, value) pairs
1316
1317 This API is used by pickle.py and copy.py.
1318
1319 For this to be useful with pickle.py, the default_factory
1320 must be picklable; e.g., None, a built-in, or a global
1321 function in a module or package.
1322
1323 Both shallow and deep copying are supported, but for deep
1324 copying, the default_factory must be deep-copyable; e.g. None,
1325 or a built-in (functions are not copyable at this time).
1326
1327 This only works for subclasses as long as their constructor
1328 signature is compatible; the first argument must be the
1329 optional default_factory, defaulting to None.
1330 */
1331 PyObject *args;
1332 PyObject *items;
Amaury Forgeot d'Arcf43ee812008-10-30 20:58:42 +00001333 PyObject *iter;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001334 PyObject *result;
1335 if (dd->default_factory == NULL || dd->default_factory == Py_None)
1336 args = PyTuple_New(0);
1337 else
1338 args = PyTuple_Pack(1, dd->default_factory);
1339 if (args == NULL)
1340 return NULL;
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001341 items = PyObject_CallMethod((PyObject *)dd, "items", "()");
Guido van Rossum1968ad32006-02-25 22:38:04 +00001342 if (items == NULL) {
1343 Py_DECREF(args);
1344 return NULL;
1345 }
Amaury Forgeot d'Arcf43ee812008-10-30 20:58:42 +00001346 iter = PyObject_GetIter(items);
1347 if (iter == NULL) {
1348 Py_DECREF(items);
1349 Py_DECREF(args);
1350 return NULL;
1351 }
Christian Heimes90aa7642007-12-19 02:45:37 +00001352 result = PyTuple_Pack(5, Py_TYPE(dd), args,
Amaury Forgeot d'Arcf43ee812008-10-30 20:58:42 +00001353 Py_None, Py_None, iter);
1354 Py_DECREF(iter);
Guido van Rossumd8faa362007-04-27 19:54:29 +00001355 Py_DECREF(items);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001356 Py_DECREF(args);
1357 return result;
1358}
1359
1360static PyMethodDef defdict_methods[] = {
1361 {"__missing__", (PyCFunction)defdict_missing, METH_O,
1362 defdict_missing_doc},
Christian Heimes3feef612008-02-11 06:19:17 +00001363 {"copy", (PyCFunction)defdict_copy, METH_NOARGS,
1364 defdict_copy_doc},
Guido van Rossum1968ad32006-02-25 22:38:04 +00001365 {"__copy__", (PyCFunction)defdict_copy, METH_NOARGS,
1366 defdict_copy_doc},
1367 {"__reduce__", (PyCFunction)defdict_reduce, METH_NOARGS,
1368 reduce_doc},
1369 {NULL}
1370};
1371
1372static PyMemberDef defdict_members[] = {
1373 {"default_factory", T_OBJECT,
1374 offsetof(defdictobject, default_factory), 0,
1375 PyDoc_STR("Factory for default value called by __missing__().")},
1376 {NULL}
1377};
1378
1379static void
1380defdict_dealloc(defdictobject *dd)
1381{
1382 Py_CLEAR(dd->default_factory);
1383 PyDict_Type.tp_dealloc((PyObject *)dd);
1384}
1385
Guido van Rossum1968ad32006-02-25 22:38:04 +00001386static PyObject *
1387defdict_repr(defdictobject *dd)
1388{
Guido van Rossum1968ad32006-02-25 22:38:04 +00001389 PyObject *baserepr;
Christian Heimes77c02eb2008-02-09 02:18:51 +00001390 PyObject *defrepr;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001391 PyObject *result;
1392 baserepr = PyDict_Type.tp_repr((PyObject *)dd);
1393 if (baserepr == NULL)
1394 return NULL;
1395 if (dd->default_factory == NULL)
Christian Heimes77c02eb2008-02-09 02:18:51 +00001396 defrepr = PyUnicode_FromString("None");
Guido van Rossum1968ad32006-02-25 22:38:04 +00001397 else
Christian Heimes77c02eb2008-02-09 02:18:51 +00001398 {
1399 int status = Py_ReprEnter(dd->default_factory);
1400 if (status != 0) {
1401 if (status < 0)
1402 return NULL;
1403 defrepr = PyUnicode_FromString("...");
1404 }
1405 else
1406 defrepr = PyObject_Repr(dd->default_factory);
1407 Py_ReprLeave(dd->default_factory);
1408 }
1409 if (defrepr == NULL) {
1410 Py_DECREF(baserepr);
1411 return NULL;
1412 }
1413 result = PyUnicode_FromFormat("defaultdict(%U, %U)",
1414 defrepr, baserepr);
1415 Py_DECREF(defrepr);
Walter Dörwald7569dfe2007-05-19 21:49:49 +00001416 Py_DECREF(baserepr);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001417 return result;
1418}
1419
1420static int
1421defdict_traverse(PyObject *self, visitproc visit, void *arg)
1422{
1423 Py_VISIT(((defdictobject *)self)->default_factory);
1424 return PyDict_Type.tp_traverse(self, visit, arg);
1425}
1426
1427static int
1428defdict_tp_clear(defdictobject *dd)
1429{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001430 Py_CLEAR(dd->default_factory);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001431 return PyDict_Type.tp_clear((PyObject *)dd);
1432}
1433
1434static int
1435defdict_init(PyObject *self, PyObject *args, PyObject *kwds)
1436{
1437 defdictobject *dd = (defdictobject *)self;
1438 PyObject *olddefault = dd->default_factory;
1439 PyObject *newdefault = NULL;
1440 PyObject *newargs;
1441 int result;
1442 if (args == NULL || !PyTuple_Check(args))
1443 newargs = PyTuple_New(0);
1444 else {
1445 Py_ssize_t n = PyTuple_GET_SIZE(args);
Thomas Wouterscf297e42007-02-23 15:07:44 +00001446 if (n > 0) {
Guido van Rossum1968ad32006-02-25 22:38:04 +00001447 newdefault = PyTuple_GET_ITEM(args, 0);
Raymond Hettinger54628fa2009-08-04 19:16:39 +00001448 if (!PyCallable_Check(newdefault) && newdefault != Py_None) {
Thomas Wouterscf297e42007-02-23 15:07:44 +00001449 PyErr_SetString(PyExc_TypeError,
1450 "first argument must be callable");
1451 return -1;
1452 }
1453 }
Guido van Rossum1968ad32006-02-25 22:38:04 +00001454 newargs = PySequence_GetSlice(args, 1, n);
1455 }
1456 if (newargs == NULL)
1457 return -1;
1458 Py_XINCREF(newdefault);
1459 dd->default_factory = newdefault;
1460 result = PyDict_Type.tp_init(self, newargs, kwds);
1461 Py_DECREF(newargs);
1462 Py_XDECREF(olddefault);
1463 return result;
1464}
1465
1466PyDoc_STRVAR(defdict_doc,
1467"defaultdict(default_factory) --> dict with default factory\n\
1468\n\
1469The default factory is called without arguments to produce\n\
1470a new value when a key is not present, in __getitem__ only.\n\
1471A defaultdict compares equal to a dict with the same items.\n\
1472");
1473
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001474/* See comment in xxsubtype.c */
1475#define DEFERRED_ADDRESS(ADDR) 0
1476
Guido van Rossum1968ad32006-02-25 22:38:04 +00001477static PyTypeObject defdict_type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001478 PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0)
Guido van Rossum1968ad32006-02-25 22:38:04 +00001479 "collections.defaultdict", /* tp_name */
1480 sizeof(defdictobject), /* tp_basicsize */
1481 0, /* tp_itemsize */
1482 /* methods */
1483 (destructor)defdict_dealloc, /* tp_dealloc */
Guido van Rossum346f1a82007-08-07 19:58:47 +00001484 0, /* tp_print */
Guido van Rossum1968ad32006-02-25 22:38:04 +00001485 0, /* tp_getattr */
1486 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00001487 0, /* tp_reserved */
Guido van Rossum1968ad32006-02-25 22:38:04 +00001488 (reprfunc)defdict_repr, /* tp_repr */
1489 0, /* tp_as_number */
1490 0, /* tp_as_sequence */
1491 0, /* tp_as_mapping */
1492 0, /* tp_hash */
1493 0, /* tp_call */
1494 0, /* tp_str */
1495 PyObject_GenericGetAttr, /* tp_getattro */
1496 0, /* tp_setattro */
1497 0, /* tp_as_buffer */
Guido van Rossumd8faa362007-04-27 19:54:29 +00001498 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
1499 /* tp_flags */
Guido van Rossum1968ad32006-02-25 22:38:04 +00001500 defdict_doc, /* tp_doc */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001501 defdict_traverse, /* tp_traverse */
Guido van Rossum1968ad32006-02-25 22:38:04 +00001502 (inquiry)defdict_tp_clear, /* tp_clear */
1503 0, /* tp_richcompare */
1504 0, /* tp_weaklistoffset*/
1505 0, /* tp_iter */
1506 0, /* tp_iternext */
1507 defdict_methods, /* tp_methods */
1508 defdict_members, /* tp_members */
1509 0, /* tp_getset */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001510 DEFERRED_ADDRESS(&PyDict_Type), /* tp_base */
Guido van Rossum1968ad32006-02-25 22:38:04 +00001511 0, /* tp_dict */
1512 0, /* tp_descr_get */
1513 0, /* tp_descr_set */
1514 0, /* tp_dictoffset */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001515 defdict_init, /* tp_init */
Guido van Rossum1968ad32006-02-25 22:38:04 +00001516 PyType_GenericAlloc, /* tp_alloc */
1517 0, /* tp_new */
1518 PyObject_GC_Del, /* tp_free */
1519};
1520
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001521/* module level code ********************************************************/
1522
1523PyDoc_STRVAR(module_doc,
Guido van Rossum1968ad32006-02-25 22:38:04 +00001524"High performance data structures.\n\
1525- deque: ordered collection accessible from endpoints only\n\
1526- defaultdict: dict subclass with a default value factory\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001527");
1528
Martin v. Löwis1a214512008-06-11 05:26:20 +00001529
1530static struct PyModuleDef _collectionsmodule = {
1531 PyModuleDef_HEAD_INIT,
1532 "_collections",
1533 module_doc,
1534 -1,
1535 NULL,
1536 NULL,
1537 NULL,
1538 NULL,
1539 NULL
1540};
1541
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001542PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001543PyInit__collections(void)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001544{
1545 PyObject *m;
1546
Martin v. Löwis1a214512008-06-11 05:26:20 +00001547 m = PyModule_Create(&_collectionsmodule);
Neal Norwitz1ac754f2006-01-19 06:09:39 +00001548 if (m == NULL)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001549 return NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001550
1551 if (PyType_Ready(&deque_type) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001552 return NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001553 Py_INCREF(&deque_type);
1554 PyModule_AddObject(m, "deque", (PyObject *)&deque_type);
1555
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001556 defdict_type.tp_base = &PyDict_Type;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001557 if (PyType_Ready(&defdict_type) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001558 return NULL;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001559 Py_INCREF(&defdict_type);
1560 PyModule_AddObject(m, "defaultdict", (PyObject *)&defdict_type);
1561
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001562 if (PyType_Ready(&dequeiter_type) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001563 return NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001564
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001565 if (PyType_Ready(&dequereviter_type) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001566 return NULL;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001567
Martin v. Löwis1a214512008-06-11 05:26:20 +00001568 return m;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001569}