blob: ffb2a8066d94243da08391a0ee1c9bbd1ad59a22 [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
Martin v. Löwis18e16552006-02-15 17:27:45 +0000507static Py_ssize_t
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000508deque_len(dequeobject *deque)
509{
510 return deque->len;
511}
512
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000513static PyObject *
514deque_remove(dequeobject *deque, PyObject *value)
515{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000516 Py_ssize_t i, n=deque->len;
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000517
518 for (i=0 ; i<n ; i++) {
519 PyObject *item = deque->leftblock->data[deque->leftindex];
520 int cmp = PyObject_RichCompareBool(item, value, Py_EQ);
Raymond Hettingerd73202c2005-03-19 00:00:51 +0000521
522 if (deque->len != n) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000523 PyErr_SetString(PyExc_IndexError,
Raymond Hettingerd73202c2005-03-19 00:00:51 +0000524 "deque mutated during remove().");
525 return NULL;
526 }
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000527 if (cmp > 0) {
Raymond Hettingerd73202c2005-03-19 00:00:51 +0000528 PyObject *tgt = deque_popleft(deque, NULL);
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000529 assert (tgt != NULL);
530 Py_DECREF(tgt);
531 if (_deque_rotate(deque, i) == -1)
532 return NULL;
533 Py_RETURN_NONE;
534 }
535 else if (cmp < 0) {
536 _deque_rotate(deque, i);
537 return NULL;
538 }
539 _deque_rotate(deque, -1);
540 }
541 PyErr_SetString(PyExc_ValueError, "deque.remove(x): x not in deque");
542 return NULL;
543}
544
545PyDoc_STRVAR(remove_doc,
546"D.remove(value) -- remove first occurrence of value.");
547
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000548static int
549deque_clear(dequeobject *deque)
550{
551 PyObject *item;
552
Raymond Hettingerd1b3d882004-10-02 00:43:13 +0000553 while (deque->len) {
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000554 item = deque_pop(deque, NULL);
Raymond Hettingera435c532004-07-09 04:10:20 +0000555 assert (item != NULL);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000556 Py_DECREF(item);
557 }
558 assert(deque->leftblock == deque->rightblock &&
Raymond Hettingerd1b3d882004-10-02 00:43:13 +0000559 deque->leftindex - 1 == deque->rightindex &&
560 deque->len == 0);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000561 return 0;
562}
563
564static PyObject *
Benjamin Petersond6313712008-07-31 16:23:04 +0000565deque_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000566{
567 block *b;
568 PyObject *item;
Benjamin Petersond6313712008-07-31 16:23:04 +0000569 Py_ssize_t n, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000570
571 if (i < 0 || i >= deque->len) {
572 PyErr_SetString(PyExc_IndexError,
573 "deque index out of range");
574 return NULL;
575 }
576
Raymond Hettinger6c79a512004-03-04 08:00:54 +0000577 if (i == 0) {
578 i = deque->leftindex;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000579 b = deque->leftblock;
Raymond Hettinger6c79a512004-03-04 08:00:54 +0000580 } else if (i == deque->len - 1) {
581 i = deque->rightindex;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000582 b = deque->rightblock;
Raymond Hettinger6c79a512004-03-04 08:00:54 +0000583 } else {
584 i += deque->leftindex;
585 n = i / BLOCKLEN;
586 i %= BLOCKLEN;
Armin Rigo974d7572004-10-02 13:59:34 +0000587 if (index < (deque->len >> 1)) {
Raymond Hettinger6c79a512004-03-04 08:00:54 +0000588 b = deque->leftblock;
589 while (n--)
590 b = b->rightlink;
591 } else {
592 n = (deque->leftindex + deque->len - 1) / BLOCKLEN - n;
593 b = deque->rightblock;
594 while (n--)
595 b = b->leftlink;
596 }
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000597 }
598 item = b->data[i];
599 Py_INCREF(item);
600 return item;
601}
602
Raymond Hettinger616f4f62004-06-26 04:42:06 +0000603/* delitem() implemented in terms of rotate for simplicity and reasonable
604 performance near the end points. If for some reason this method becomes
Tim Peters1065f752004-10-01 01:03:29 +0000605 popular, it is not hard to re-implement this using direct data movement
Raymond Hettinger616f4f62004-06-26 04:42:06 +0000606 (similar to code in list slice assignment) and achieve a two or threefold
607 performance boost.
608*/
609
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000610static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000611deque_del_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000612{
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000613 PyObject *item;
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000614
Tim Peters1065f752004-10-01 01:03:29 +0000615 assert (i >= 0 && i < deque->len);
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000616 if (_deque_rotate(deque, -i) == -1)
617 return -1;
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000618
619 item = deque_popleft(deque, NULL);
Raymond Hettingera435c532004-07-09 04:10:20 +0000620 assert (item != NULL);
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000621 Py_DECREF(item);
622
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000623 return _deque_rotate(deque, i);
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000624}
625
626static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000627deque_ass_item(dequeobject *deque, Py_ssize_t i, PyObject *v)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000628{
629 PyObject *old_value;
630 block *b;
Martin v. Löwisad0a4622006-02-16 14:30:23 +0000631 Py_ssize_t n, len=deque->len, halflen=(len+1)>>1, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000632
Raymond Hettingera435c532004-07-09 04:10:20 +0000633 if (i < 0 || i >= len) {
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000634 PyErr_SetString(PyExc_IndexError,
635 "deque index out of range");
636 return -1;
637 }
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000638 if (v == NULL)
639 return deque_del_item(deque, i);
640
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000641 i += deque->leftindex;
642 n = i / BLOCKLEN;
643 i %= BLOCKLEN;
Raymond Hettingera435c532004-07-09 04:10:20 +0000644 if (index <= halflen) {
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000645 b = deque->leftblock;
646 while (n--)
647 b = b->rightlink;
648 } else {
Raymond Hettingera435c532004-07-09 04:10:20 +0000649 n = (deque->leftindex + len - 1) / BLOCKLEN - n;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000650 b = deque->rightblock;
651 while (n--)
652 b = b->leftlink;
653 }
654 Py_INCREF(v);
655 old_value = b->data[i];
656 b->data[i] = v;
657 Py_DECREF(old_value);
658 return 0;
659}
660
661static PyObject *
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000662deque_clearmethod(dequeobject *deque)
663{
Raymond Hettingera435c532004-07-09 04:10:20 +0000664 int rv;
665
666 rv = deque_clear(deque);
667 assert (rv != -1);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000668 Py_RETURN_NONE;
669}
670
671PyDoc_STRVAR(clear_doc, "Remove all elements from the deque.");
672
673static void
674deque_dealloc(dequeobject *deque)
675{
676 PyObject_GC_UnTrack(deque);
Raymond Hettinger691d8052004-05-30 07:26:47 +0000677 if (deque->weakreflist != NULL)
678 PyObject_ClearWeakRefs((PyObject *) deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000679 if (deque->leftblock != NULL) {
Raymond Hettingere9c89e82004-07-19 00:10:24 +0000680 deque_clear(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000681 assert(deque->leftblock != NULL);
Guido van Rossum58da9312007-11-10 23:39:45 +0000682 freeblock(deque->leftblock);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000683 }
684 deque->leftblock = NULL;
685 deque->rightblock = NULL;
Christian Heimes90aa7642007-12-19 02:45:37 +0000686 Py_TYPE(deque)->tp_free(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000687}
688
689static int
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000690deque_traverse(dequeobject *deque, visitproc visit, void *arg)
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000691{
Tim Peters10c7e862004-10-01 02:01:04 +0000692 block *b;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000693 PyObject *item;
Benjamin Petersond6313712008-07-31 16:23:04 +0000694 Py_ssize_t index;
695 Py_ssize_t indexlo = deque->leftindex;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000696
Tim Peters10c7e862004-10-01 02:01:04 +0000697 for (b = deque->leftblock; b != NULL; b = b->rightlink) {
Benjamin Petersond6313712008-07-31 16:23:04 +0000698 const Py_ssize_t indexhi = b == deque->rightblock ?
Tim Peters10c7e862004-10-01 02:01:04 +0000699 deque->rightindex :
700 BLOCKLEN - 1;
701
702 for (index = indexlo; index <= indexhi; ++index) {
703 item = b->data[index];
704 Py_VISIT(item);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000705 }
Tim Peters10c7e862004-10-01 02:01:04 +0000706 indexlo = 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000707 }
708 return 0;
709}
710
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000711static PyObject *
712deque_copy(PyObject *deque)
713{
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000714 if (((dequeobject *)deque)->maxlen == -1)
Christian Heimes90aa7642007-12-19 02:45:37 +0000715 return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "O", deque, NULL);
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000716 else
Christian Heimes90aa7642007-12-19 02:45:37 +0000717 return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "Oi",
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000718 deque, ((dequeobject *)deque)->maxlen, NULL);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000719}
720
721PyDoc_STRVAR(copy_doc, "Return a shallow copy of a deque.");
722
723static PyObject *
724deque_reduce(dequeobject *deque)
725{
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000726 PyObject *dict, *result, *aslist;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000727
Raymond Hettinger952f8802004-11-09 07:27:35 +0000728 dict = PyObject_GetAttrString((PyObject *)deque, "__dict__");
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000729 if (dict == NULL)
Raymond Hettinger952f8802004-11-09 07:27:35 +0000730 PyErr_Clear();
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000731 aslist = PySequence_List((PyObject *)deque);
732 if (aslist == NULL) {
733 Py_XDECREF(dict);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000734 return NULL;
735 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000736 if (dict == NULL) {
737 if (deque->maxlen == -1)
Christian Heimes90aa7642007-12-19 02:45:37 +0000738 result = Py_BuildValue("O(O)", Py_TYPE(deque), aslist);
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000739 else
Benjamin Petersond6313712008-07-31 16:23:04 +0000740 result = Py_BuildValue("O(On)", Py_TYPE(deque), aslist, deque->maxlen);
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000741 } else {
742 if (deque->maxlen == -1)
Christian Heimes90aa7642007-12-19 02:45:37 +0000743 result = Py_BuildValue("O(OO)O", Py_TYPE(deque), aslist, Py_None, dict);
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000744 else
Benjamin Petersond6313712008-07-31 16:23:04 +0000745 result = Py_BuildValue("O(On)O", Py_TYPE(deque), aslist, deque->maxlen, dict);
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000746 }
747 Py_XDECREF(dict);
748 Py_DECREF(aslist);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000749 return result;
750}
751
752PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
753
754static PyObject *
755deque_repr(PyObject *deque)
756{
Walter Dörwald1ab83302007-05-18 17:15:44 +0000757 PyObject *aslist, *result;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000758 int i;
759
760 i = Py_ReprEnter(deque);
761 if (i != 0) {
762 if (i < 0)
763 return NULL;
Walter Dörwald1ab83302007-05-18 17:15:44 +0000764 return PyUnicode_FromString("[...]");
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000765 }
766
767 aslist = PySequence_List(deque);
768 if (aslist == NULL) {
769 Py_ReprLeave(deque);
770 return NULL;
771 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000772 if (((dequeobject *)deque)->maxlen != -1)
Benjamin Petersona786b022008-08-25 21:05:21 +0000773
Amaury Forgeot d'Arc245c70b2008-09-10 22:24:24 +0000774 result = PyUnicode_FromFormat("deque(%R, maxlen=%zd)",
Benjamin Petersona786b022008-08-25 21:05:21 +0000775 aslist, ((dequeobject *)deque)->maxlen);
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000776 else
777 result = PyUnicode_FromFormat("deque(%R)", aslist);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000778 Py_DECREF(aslist);
779 Py_ReprLeave(deque);
780 return result;
781}
782
Raymond Hettinger738ec902004-02-29 02:15:56 +0000783static PyObject *
784deque_richcompare(PyObject *v, PyObject *w, int op)
785{
786 PyObject *it1=NULL, *it2=NULL, *x, *y;
Benjamin Petersond6313712008-07-31 16:23:04 +0000787 Py_ssize_t vs, ws;
788 int b, cmp=-1;
Raymond Hettinger738ec902004-02-29 02:15:56 +0000789
Tim Peters1065f752004-10-01 01:03:29 +0000790 if (!PyObject_TypeCheck(v, &deque_type) ||
Raymond Hettinger285cfcc2004-05-18 18:15:03 +0000791 !PyObject_TypeCheck(w, &deque_type)) {
Raymond Hettinger738ec902004-02-29 02:15:56 +0000792 Py_INCREF(Py_NotImplemented);
793 return Py_NotImplemented;
794 }
795
796 /* Shortcuts */
797 vs = ((dequeobject *)v)->len;
798 ws = ((dequeobject *)w)->len;
799 if (op == Py_EQ) {
800 if (v == w)
801 Py_RETURN_TRUE;
802 if (vs != ws)
803 Py_RETURN_FALSE;
804 }
805 if (op == Py_NE) {
806 if (v == w)
807 Py_RETURN_FALSE;
808 if (vs != ws)
809 Py_RETURN_TRUE;
810 }
811
812 /* Search for the first index where items are different */
813 it1 = PyObject_GetIter(v);
814 if (it1 == NULL)
815 goto done;
816 it2 = PyObject_GetIter(w);
817 if (it2 == NULL)
818 goto done;
Armin Rigo974d7572004-10-02 13:59:34 +0000819 for (;;) {
Raymond Hettinger738ec902004-02-29 02:15:56 +0000820 x = PyIter_Next(it1);
Armin Rigo974d7572004-10-02 13:59:34 +0000821 if (x == NULL && PyErr_Occurred())
Raymond Hettinger738ec902004-02-29 02:15:56 +0000822 goto done;
823 y = PyIter_Next(it2);
Armin Rigo974d7572004-10-02 13:59:34 +0000824 if (x == NULL || y == NULL)
825 break;
Raymond Hettinger738ec902004-02-29 02:15:56 +0000826 b = PyObject_RichCompareBool(x, y, Py_EQ);
827 if (b == 0) {
828 cmp = PyObject_RichCompareBool(x, y, op);
829 Py_DECREF(x);
830 Py_DECREF(y);
831 goto done;
832 }
833 Py_DECREF(x);
834 Py_DECREF(y);
835 if (b == -1)
836 goto done;
837 }
Armin Rigo974d7572004-10-02 13:59:34 +0000838 /* We reached the end of one deque or both */
839 Py_XDECREF(x);
840 Py_XDECREF(y);
841 if (PyErr_Occurred())
842 goto done;
Raymond Hettinger738ec902004-02-29 02:15:56 +0000843 switch (op) {
Armin Rigo974d7572004-10-02 13:59:34 +0000844 case Py_LT: cmp = y != NULL; break; /* if w was longer */
845 case Py_LE: cmp = x == NULL; break; /* if v was not longer */
846 case Py_EQ: cmp = x == y; break; /* if we reached the end of both */
847 case Py_NE: cmp = x != y; break; /* if one deque continues */
848 case Py_GT: cmp = x != NULL; break; /* if v was longer */
849 case Py_GE: cmp = y == NULL; break; /* if w was not longer */
Raymond Hettinger738ec902004-02-29 02:15:56 +0000850 }
Tim Peters1065f752004-10-01 01:03:29 +0000851
Raymond Hettinger738ec902004-02-29 02:15:56 +0000852done:
853 Py_XDECREF(it1);
854 Py_XDECREF(it2);
855 if (cmp == 1)
856 Py_RETURN_TRUE;
857 if (cmp == 0)
858 Py_RETURN_FALSE;
859 return NULL;
860}
861
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000862static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000863deque_init(dequeobject *deque, PyObject *args, PyObject *kwdargs)
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000864{
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000865 PyObject *iterable = NULL;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000866 PyObject *maxlenobj = NULL;
Benjamin Petersond6313712008-07-31 16:23:04 +0000867 Py_ssize_t maxlen = -1;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000868 char *kwlist[] = {"iterable", "maxlen", 0};
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000869
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000870 if (!PyArg_ParseTupleAndKeywords(args, kwdargs, "|OO:deque", kwlist, &iterable, &maxlenobj))
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000871 return -1;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000872 if (maxlenobj != NULL && maxlenobj != Py_None) {
Benjamin Petersond6313712008-07-31 16:23:04 +0000873 maxlen = PyLong_AsSsize_t(maxlenobj);
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000874 if (maxlen == -1 && PyErr_Occurred())
875 return -1;
876 if (maxlen < 0) {
877 PyErr_SetString(PyExc_ValueError, "maxlen must be non-negative");
878 return -1;
879 }
880 }
881 deque->maxlen = maxlen;
Christian Heimes38053212007-12-14 01:24:44 +0000882 deque_clear(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000883 if (iterable != NULL) {
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000884 PyObject *rv = deque_extend(deque, iterable);
885 if (rv == NULL)
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000886 return -1;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000887 Py_DECREF(rv);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000888 }
889 return 0;
890}
891
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +0000892static PyObject *
893deque_get_maxlen(dequeobject *deque)
894{
895 if (deque->maxlen == -1)
896 Py_RETURN_NONE;
897 return PyLong_FromSsize_t(deque->maxlen);
898}
899
900static PyGetSetDef deque_getset[] = {
901 {"maxlen", (getter)deque_get_maxlen, (setter)NULL,
902 "maximum size of a deque or None if unbounded"},
903 {0}
904};
905
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000906static PySequenceMethods deque_as_sequence = {
Martin v. Löwis18e16552006-02-15 17:27:45 +0000907 (lenfunc)deque_len, /* sq_length */
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000908 0, /* sq_concat */
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000909 0, /* sq_repeat */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000910 (ssizeargfunc)deque_item, /* sq_item */
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000911 0, /* sq_slice */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000912 (ssizeobjargproc)deque_ass_item, /* sq_ass_item */
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000913 0, /* sq_ass_slice */
914 0, /* sq_contains */
915 (binaryfunc)deque_inplace_concat, /* sq_inplace_concat */
916 0, /* sq_inplace_repeat */
917
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000918};
919
920/* deque object ********************************************************/
921
922static PyObject *deque_iter(dequeobject *deque);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +0000923static PyObject *deque_reviter(dequeobject *deque);
Tim Peters1065f752004-10-01 01:03:29 +0000924PyDoc_STRVAR(reversed_doc,
Raymond Hettinger1e5809f2004-03-18 11:04:57 +0000925 "D.__reversed__() -- return a reverse iterator over the deque");
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000926
927static PyMethodDef deque_methods[] = {
Tim Peters1065f752004-10-01 01:03:29 +0000928 {"append", (PyCFunction)deque_append,
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000929 METH_O, append_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000930 {"appendleft", (PyCFunction)deque_appendleft,
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000931 METH_O, appendleft_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000932 {"clear", (PyCFunction)deque_clearmethod,
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000933 METH_NOARGS, clear_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000934 {"__copy__", (PyCFunction)deque_copy,
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000935 METH_NOARGS, copy_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000936 {"extend", (PyCFunction)deque_extend,
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000937 METH_O, extend_doc},
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000938 {"extendleft", (PyCFunction)deque_extendleft,
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000939 METH_O, extendleft_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000940 {"pop", (PyCFunction)deque_pop,
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000941 METH_NOARGS, pop_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000942 {"popleft", (PyCFunction)deque_popleft,
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000943 METH_NOARGS, popleft_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000944 {"__reduce__", (PyCFunction)deque_reduce,
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000945 METH_NOARGS, reduce_doc},
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000946 {"remove", (PyCFunction)deque_remove,
947 METH_O, remove_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000948 {"__reversed__", (PyCFunction)deque_reviter,
Raymond Hettinger1e5809f2004-03-18 11:04:57 +0000949 METH_NOARGS, reversed_doc},
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000950 {"reverse", (PyCFunction)deque_reverse,
951 METH_NOARGS, reverse_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000952 {"rotate", (PyCFunction)deque_rotate,
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000953 METH_VARARGS, rotate_doc},
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000954 {NULL, NULL} /* sentinel */
955};
956
957PyDoc_STRVAR(deque_doc,
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000958"deque(iterable[, maxlen]) --> deque object\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000959\n\
960Build an ordered collection accessible from endpoints only.");
961
Neal Norwitz87f10132004-02-29 15:40:53 +0000962static PyTypeObject deque_type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000963 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000964 "collections.deque", /* tp_name */
965 sizeof(dequeobject), /* tp_basicsize */
966 0, /* tp_itemsize */
967 /* methods */
968 (destructor)deque_dealloc, /* tp_dealloc */
Guido van Rossum346f1a82007-08-07 19:58:47 +0000969 0, /* tp_print */
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000970 0, /* tp_getattr */
971 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +0000972 0, /* tp_reserved */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000973 deque_repr, /* tp_repr */
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000974 0, /* tp_as_number */
975 &deque_as_sequence, /* tp_as_sequence */
976 0, /* tp_as_mapping */
Nick Coghland1abd252008-07-15 15:46:38 +0000977 (hashfunc)PyObject_HashNotImplemented, /* tp_hash */
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000978 0, /* tp_call */
979 0, /* tp_str */
980 PyObject_GenericGetAttr, /* tp_getattro */
981 0, /* tp_setattro */
982 0, /* tp_as_buffer */
Guido van Rossumd8faa362007-04-27 19:54:29 +0000983 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
984 /* tp_flags */
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000985 deque_doc, /* tp_doc */
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000986 (traverseproc)deque_traverse, /* tp_traverse */
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000987 (inquiry)deque_clear, /* tp_clear */
Raymond Hettinger738ec902004-02-29 02:15:56 +0000988 (richcmpfunc)deque_richcompare, /* tp_richcompare */
Raymond Hettinger691d8052004-05-30 07:26:47 +0000989 offsetof(dequeobject, weakreflist), /* tp_weaklistoffset*/
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000990 (getiterfunc)deque_iter, /* tp_iter */
991 0, /* tp_iternext */
992 deque_methods, /* tp_methods */
993 0, /* tp_members */
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +0000994 deque_getset, /* tp_getset */
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000995 0, /* tp_base */
996 0, /* tp_dict */
997 0, /* tp_descr_get */
998 0, /* tp_descr_set */
999 0, /* tp_dictoffset */
1000 (initproc)deque_init, /* tp_init */
1001 PyType_GenericAlloc, /* tp_alloc */
1002 deque_new, /* tp_new */
1003 PyObject_GC_Del, /* tp_free */
1004};
1005
1006/*********************** Deque Iterator **************************/
1007
1008typedef struct {
1009 PyObject_HEAD
Benjamin Petersond6313712008-07-31 16:23:04 +00001010 Py_ssize_t index;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001011 block *b;
1012 dequeobject *deque;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001013 long state; /* state when the iterator is created */
Benjamin Petersond6313712008-07-31 16:23:04 +00001014 Py_ssize_t counter; /* number of items remaining for iteration */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001015} dequeiterobject;
1016
Martin v. Löwis59683e82008-06-13 07:50:45 +00001017static PyTypeObject dequeiter_type;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001018
1019static PyObject *
1020deque_iter(dequeobject *deque)
1021{
1022 dequeiterobject *it;
1023
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001024 it = PyObject_GC_New(dequeiterobject, &dequeiter_type);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001025 if (it == NULL)
1026 return NULL;
1027 it->b = deque->leftblock;
1028 it->index = deque->leftindex;
1029 Py_INCREF(deque);
1030 it->deque = deque;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001031 it->state = deque->state;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001032 it->counter = deque->len;
Georg Brandlb1441c72009-01-03 22:33:39 +00001033 PyObject_GC_Track(it);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001034 return (PyObject *)it;
1035}
1036
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001037static int
1038dequeiter_traverse(dequeiterobject *dio, visitproc visit, void *arg)
1039{
1040 Py_VISIT(dio->deque);
1041 return 0;
1042}
1043
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001044static void
1045dequeiter_dealloc(dequeiterobject *dio)
1046{
1047 Py_XDECREF(dio->deque);
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001048 PyObject_GC_Del(dio);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001049}
1050
1051static PyObject *
1052dequeiter_next(dequeiterobject *it)
1053{
1054 PyObject *item;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001055
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001056 if (it->deque->state != it->state) {
Raymond Hettinger7892b1c2004-04-12 18:10:01 +00001057 it->counter = 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001058 PyErr_SetString(PyExc_RuntimeError,
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001059 "deque mutated during iteration");
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001060 return NULL;
1061 }
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001062 if (it->counter == 0)
1063 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001064 assert (!(it->b == it->deque->rightblock &&
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001065 it->index > it->deque->rightindex));
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001066
1067 item = it->b->data[it->index];
1068 it->index++;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001069 it->counter--;
1070 if (it->index == BLOCKLEN && it->counter > 0) {
1071 assert (it->b->rightlink != NULL);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001072 it->b = it->b->rightlink;
1073 it->index = 0;
1074 }
1075 Py_INCREF(item);
1076 return item;
1077}
1078
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001079static PyObject *
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001080dequeiter_len(dequeiterobject *it)
1081{
Christian Heimes217cfd12007-12-02 14:31:20 +00001082 return PyLong_FromLong(it->counter);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001083}
1084
Armin Rigof5b3e362006-02-11 21:32:43 +00001085PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001086
1087static PyMethodDef dequeiter_methods[] = {
Armin Rigof5b3e362006-02-11 21:32:43 +00001088 {"__length_hint__", (PyCFunction)dequeiter_len, METH_NOARGS, length_hint_doc},
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001089 {NULL, NULL} /* sentinel */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001090};
1091
Martin v. Löwis59683e82008-06-13 07:50:45 +00001092static PyTypeObject dequeiter_type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001093 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001094 "deque_iterator", /* tp_name */
1095 sizeof(dequeiterobject), /* tp_basicsize */
1096 0, /* tp_itemsize */
1097 /* methods */
1098 (destructor)dequeiter_dealloc, /* tp_dealloc */
1099 0, /* tp_print */
1100 0, /* tp_getattr */
1101 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00001102 0, /* tp_reserved */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001103 0, /* tp_repr */
1104 0, /* tp_as_number */
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001105 0, /* tp_as_sequence */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001106 0, /* tp_as_mapping */
1107 0, /* tp_hash */
1108 0, /* tp_call */
1109 0, /* tp_str */
1110 PyObject_GenericGetAttr, /* tp_getattro */
1111 0, /* tp_setattro */
1112 0, /* tp_as_buffer */
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001113 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001114 0, /* tp_doc */
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001115 (traverseproc)dequeiter_traverse, /* tp_traverse */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001116 0, /* tp_clear */
1117 0, /* tp_richcompare */
1118 0, /* tp_weaklistoffset */
1119 PyObject_SelfIter, /* tp_iter */
1120 (iternextfunc)dequeiter_next, /* tp_iternext */
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001121 dequeiter_methods, /* tp_methods */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001122 0,
1123};
1124
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001125/*********************** Deque Reverse Iterator **************************/
1126
Martin v. Löwis59683e82008-06-13 07:50:45 +00001127static PyTypeObject dequereviter_type;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001128
1129static PyObject *
1130deque_reviter(dequeobject *deque)
1131{
1132 dequeiterobject *it;
1133
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001134 it = PyObject_GC_New(dequeiterobject, &dequereviter_type);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001135 if (it == NULL)
1136 return NULL;
1137 it->b = deque->rightblock;
1138 it->index = deque->rightindex;
1139 Py_INCREF(deque);
1140 it->deque = deque;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001141 it->state = deque->state;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001142 it->counter = deque->len;
Georg Brandlb1441c72009-01-03 22:33:39 +00001143 PyObject_GC_Track(it);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001144 return (PyObject *)it;
1145}
1146
1147static PyObject *
1148dequereviter_next(dequeiterobject *it)
1149{
1150 PyObject *item;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001151 if (it->counter == 0)
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001152 return NULL;
1153
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001154 if (it->deque->state != it->state) {
Raymond Hettinger7892b1c2004-04-12 18:10:01 +00001155 it->counter = 0;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001156 PyErr_SetString(PyExc_RuntimeError,
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001157 "deque mutated during iteration");
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001158 return NULL;
1159 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001160 assert (!(it->b == it->deque->leftblock &&
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001161 it->index < it->deque->leftindex));
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001162
1163 item = it->b->data[it->index];
1164 it->index--;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001165 it->counter--;
1166 if (it->index == -1 && it->counter > 0) {
1167 assert (it->b->leftlink != NULL);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001168 it->b = it->b->leftlink;
1169 it->index = BLOCKLEN - 1;
1170 }
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001171 Py_INCREF(item);
1172 return item;
1173}
1174
Martin v. Löwis59683e82008-06-13 07:50:45 +00001175static PyTypeObject dequereviter_type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001176 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001177 "deque_reverse_iterator", /* tp_name */
1178 sizeof(dequeiterobject), /* tp_basicsize */
1179 0, /* tp_itemsize */
1180 /* methods */
1181 (destructor)dequeiter_dealloc, /* tp_dealloc */
1182 0, /* tp_print */
1183 0, /* tp_getattr */
1184 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00001185 0, /* tp_reserved */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001186 0, /* tp_repr */
1187 0, /* tp_as_number */
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001188 0, /* tp_as_sequence */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001189 0, /* tp_as_mapping */
1190 0, /* tp_hash */
1191 0, /* tp_call */
1192 0, /* tp_str */
1193 PyObject_GenericGetAttr, /* tp_getattro */
1194 0, /* tp_setattro */
1195 0, /* tp_as_buffer */
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001196 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001197 0, /* tp_doc */
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001198 (traverseproc)dequeiter_traverse, /* tp_traverse */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001199 0, /* tp_clear */
1200 0, /* tp_richcompare */
1201 0, /* tp_weaklistoffset */
1202 PyObject_SelfIter, /* tp_iter */
1203 (iternextfunc)dequereviter_next, /* tp_iternext */
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001204 dequeiter_methods, /* tp_methods */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001205 0,
1206};
1207
Guido van Rossum1968ad32006-02-25 22:38:04 +00001208/* defaultdict type *********************************************************/
1209
1210typedef struct {
1211 PyDictObject dict;
1212 PyObject *default_factory;
1213} defdictobject;
1214
1215static PyTypeObject defdict_type; /* Forward */
1216
1217PyDoc_STRVAR(defdict_missing_doc,
1218"__missing__(key) # Called by __getitem__ for missing key; pseudo-code:\n\
Guido van Rossumd8faa362007-04-27 19:54:29 +00001219 if self.default_factory is None: raise KeyError((key,))\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00001220 self[key] = value = self.default_factory()\n\
1221 return value\n\
1222");
1223
1224static PyObject *
1225defdict_missing(defdictobject *dd, PyObject *key)
1226{
1227 PyObject *factory = dd->default_factory;
1228 PyObject *value;
1229 if (factory == NULL || factory == Py_None) {
1230 /* XXX Call dict.__missing__(key) */
Guido van Rossumd8faa362007-04-27 19:54:29 +00001231 PyObject *tup;
1232 tup = PyTuple_Pack(1, key);
1233 if (!tup) return NULL;
1234 PyErr_SetObject(PyExc_KeyError, tup);
1235 Py_DECREF(tup);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001236 return NULL;
1237 }
1238 value = PyEval_CallObject(factory, NULL);
1239 if (value == NULL)
1240 return value;
1241 if (PyObject_SetItem((PyObject *)dd, key, value) < 0) {
1242 Py_DECREF(value);
1243 return NULL;
1244 }
1245 return value;
1246}
1247
1248PyDoc_STRVAR(defdict_copy_doc, "D.copy() -> a shallow copy of D.");
1249
1250static PyObject *
1251defdict_copy(defdictobject *dd)
1252{
1253 /* This calls the object's class. That only works for subclasses
1254 whose class constructor has the same signature. Subclasses that
Christian Heimes0bd4e112008-02-12 22:59:25 +00001255 define a different constructor signature must override copy().
Guido van Rossum1968ad32006-02-25 22:38:04 +00001256 */
Raymond Hettinger54628fa2009-08-04 19:16:39 +00001257
1258 if (dd->default_factory == NULL)
1259 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd), Py_None, dd, NULL);
Christian Heimes90aa7642007-12-19 02:45:37 +00001260 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd),
Guido van Rossum1968ad32006-02-25 22:38:04 +00001261 dd->default_factory, dd, NULL);
1262}
1263
1264static PyObject *
1265defdict_reduce(defdictobject *dd)
1266{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001267 /* __reduce__ must return a 5-tuple as follows:
Guido van Rossum1968ad32006-02-25 22:38:04 +00001268
1269 - factory function
1270 - tuple of args for the factory function
1271 - additional state (here None)
1272 - sequence iterator (here None)
1273 - dictionary iterator (yielding successive (key, value) pairs
1274
1275 This API is used by pickle.py and copy.py.
1276
1277 For this to be useful with pickle.py, the default_factory
1278 must be picklable; e.g., None, a built-in, or a global
1279 function in a module or package.
1280
1281 Both shallow and deep copying are supported, but for deep
1282 copying, the default_factory must be deep-copyable; e.g. None,
1283 or a built-in (functions are not copyable at this time).
1284
1285 This only works for subclasses as long as their constructor
1286 signature is compatible; the first argument must be the
1287 optional default_factory, defaulting to None.
1288 */
1289 PyObject *args;
1290 PyObject *items;
Amaury Forgeot d'Arcf43ee812008-10-30 20:58:42 +00001291 PyObject *iter;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001292 PyObject *result;
1293 if (dd->default_factory == NULL || dd->default_factory == Py_None)
1294 args = PyTuple_New(0);
1295 else
1296 args = PyTuple_Pack(1, dd->default_factory);
1297 if (args == NULL)
1298 return NULL;
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001299 items = PyObject_CallMethod((PyObject *)dd, "items", "()");
Guido van Rossum1968ad32006-02-25 22:38:04 +00001300 if (items == NULL) {
1301 Py_DECREF(args);
1302 return NULL;
1303 }
Amaury Forgeot d'Arcf43ee812008-10-30 20:58:42 +00001304 iter = PyObject_GetIter(items);
1305 if (iter == NULL) {
1306 Py_DECREF(items);
1307 Py_DECREF(args);
1308 return NULL;
1309 }
Christian Heimes90aa7642007-12-19 02:45:37 +00001310 result = PyTuple_Pack(5, Py_TYPE(dd), args,
Amaury Forgeot d'Arcf43ee812008-10-30 20:58:42 +00001311 Py_None, Py_None, iter);
1312 Py_DECREF(iter);
Guido van Rossumd8faa362007-04-27 19:54:29 +00001313 Py_DECREF(items);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001314 Py_DECREF(args);
1315 return result;
1316}
1317
1318static PyMethodDef defdict_methods[] = {
1319 {"__missing__", (PyCFunction)defdict_missing, METH_O,
1320 defdict_missing_doc},
Christian Heimes3feef612008-02-11 06:19:17 +00001321 {"copy", (PyCFunction)defdict_copy, METH_NOARGS,
1322 defdict_copy_doc},
Guido van Rossum1968ad32006-02-25 22:38:04 +00001323 {"__copy__", (PyCFunction)defdict_copy, METH_NOARGS,
1324 defdict_copy_doc},
1325 {"__reduce__", (PyCFunction)defdict_reduce, METH_NOARGS,
1326 reduce_doc},
1327 {NULL}
1328};
1329
1330static PyMemberDef defdict_members[] = {
1331 {"default_factory", T_OBJECT,
1332 offsetof(defdictobject, default_factory), 0,
1333 PyDoc_STR("Factory for default value called by __missing__().")},
1334 {NULL}
1335};
1336
1337static void
1338defdict_dealloc(defdictobject *dd)
1339{
1340 Py_CLEAR(dd->default_factory);
1341 PyDict_Type.tp_dealloc((PyObject *)dd);
1342}
1343
Guido van Rossum1968ad32006-02-25 22:38:04 +00001344static PyObject *
1345defdict_repr(defdictobject *dd)
1346{
Guido van Rossum1968ad32006-02-25 22:38:04 +00001347 PyObject *baserepr;
Christian Heimes77c02eb2008-02-09 02:18:51 +00001348 PyObject *defrepr;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001349 PyObject *result;
1350 baserepr = PyDict_Type.tp_repr((PyObject *)dd);
1351 if (baserepr == NULL)
1352 return NULL;
1353 if (dd->default_factory == NULL)
Christian Heimes77c02eb2008-02-09 02:18:51 +00001354 defrepr = PyUnicode_FromString("None");
Guido van Rossum1968ad32006-02-25 22:38:04 +00001355 else
Christian Heimes77c02eb2008-02-09 02:18:51 +00001356 {
1357 int status = Py_ReprEnter(dd->default_factory);
1358 if (status != 0) {
1359 if (status < 0)
1360 return NULL;
1361 defrepr = PyUnicode_FromString("...");
1362 }
1363 else
1364 defrepr = PyObject_Repr(dd->default_factory);
1365 Py_ReprLeave(dd->default_factory);
1366 }
1367 if (defrepr == NULL) {
1368 Py_DECREF(baserepr);
1369 return NULL;
1370 }
1371 result = PyUnicode_FromFormat("defaultdict(%U, %U)",
1372 defrepr, baserepr);
1373 Py_DECREF(defrepr);
Walter Dörwald7569dfe2007-05-19 21:49:49 +00001374 Py_DECREF(baserepr);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001375 return result;
1376}
1377
1378static int
1379defdict_traverse(PyObject *self, visitproc visit, void *arg)
1380{
1381 Py_VISIT(((defdictobject *)self)->default_factory);
1382 return PyDict_Type.tp_traverse(self, visit, arg);
1383}
1384
1385static int
1386defdict_tp_clear(defdictobject *dd)
1387{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001388 Py_CLEAR(dd->default_factory);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001389 return PyDict_Type.tp_clear((PyObject *)dd);
1390}
1391
1392static int
1393defdict_init(PyObject *self, PyObject *args, PyObject *kwds)
1394{
1395 defdictobject *dd = (defdictobject *)self;
1396 PyObject *olddefault = dd->default_factory;
1397 PyObject *newdefault = NULL;
1398 PyObject *newargs;
1399 int result;
1400 if (args == NULL || !PyTuple_Check(args))
1401 newargs = PyTuple_New(0);
1402 else {
1403 Py_ssize_t n = PyTuple_GET_SIZE(args);
Thomas Wouterscf297e42007-02-23 15:07:44 +00001404 if (n > 0) {
Guido van Rossum1968ad32006-02-25 22:38:04 +00001405 newdefault = PyTuple_GET_ITEM(args, 0);
Raymond Hettinger54628fa2009-08-04 19:16:39 +00001406 if (!PyCallable_Check(newdefault) && newdefault != Py_None) {
Thomas Wouterscf297e42007-02-23 15:07:44 +00001407 PyErr_SetString(PyExc_TypeError,
1408 "first argument must be callable");
1409 return -1;
1410 }
1411 }
Guido van Rossum1968ad32006-02-25 22:38:04 +00001412 newargs = PySequence_GetSlice(args, 1, n);
1413 }
1414 if (newargs == NULL)
1415 return -1;
1416 Py_XINCREF(newdefault);
1417 dd->default_factory = newdefault;
1418 result = PyDict_Type.tp_init(self, newargs, kwds);
1419 Py_DECREF(newargs);
1420 Py_XDECREF(olddefault);
1421 return result;
1422}
1423
1424PyDoc_STRVAR(defdict_doc,
1425"defaultdict(default_factory) --> dict with default factory\n\
1426\n\
1427The default factory is called without arguments to produce\n\
1428a new value when a key is not present, in __getitem__ only.\n\
1429A defaultdict compares equal to a dict with the same items.\n\
1430");
1431
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001432/* See comment in xxsubtype.c */
1433#define DEFERRED_ADDRESS(ADDR) 0
1434
Guido van Rossum1968ad32006-02-25 22:38:04 +00001435static PyTypeObject defdict_type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001436 PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0)
Guido van Rossum1968ad32006-02-25 22:38:04 +00001437 "collections.defaultdict", /* tp_name */
1438 sizeof(defdictobject), /* tp_basicsize */
1439 0, /* tp_itemsize */
1440 /* methods */
1441 (destructor)defdict_dealloc, /* tp_dealloc */
Guido van Rossum346f1a82007-08-07 19:58:47 +00001442 0, /* tp_print */
Guido van Rossum1968ad32006-02-25 22:38:04 +00001443 0, /* tp_getattr */
1444 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00001445 0, /* tp_reserved */
Guido van Rossum1968ad32006-02-25 22:38:04 +00001446 (reprfunc)defdict_repr, /* tp_repr */
1447 0, /* tp_as_number */
1448 0, /* tp_as_sequence */
1449 0, /* tp_as_mapping */
1450 0, /* tp_hash */
1451 0, /* tp_call */
1452 0, /* tp_str */
1453 PyObject_GenericGetAttr, /* tp_getattro */
1454 0, /* tp_setattro */
1455 0, /* tp_as_buffer */
Guido van Rossumd8faa362007-04-27 19:54:29 +00001456 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
1457 /* tp_flags */
Guido van Rossum1968ad32006-02-25 22:38:04 +00001458 defdict_doc, /* tp_doc */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001459 defdict_traverse, /* tp_traverse */
Guido van Rossum1968ad32006-02-25 22:38:04 +00001460 (inquiry)defdict_tp_clear, /* tp_clear */
1461 0, /* tp_richcompare */
1462 0, /* tp_weaklistoffset*/
1463 0, /* tp_iter */
1464 0, /* tp_iternext */
1465 defdict_methods, /* tp_methods */
1466 defdict_members, /* tp_members */
1467 0, /* tp_getset */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001468 DEFERRED_ADDRESS(&PyDict_Type), /* tp_base */
Guido van Rossum1968ad32006-02-25 22:38:04 +00001469 0, /* tp_dict */
1470 0, /* tp_descr_get */
1471 0, /* tp_descr_set */
1472 0, /* tp_dictoffset */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001473 defdict_init, /* tp_init */
Guido van Rossum1968ad32006-02-25 22:38:04 +00001474 PyType_GenericAlloc, /* tp_alloc */
1475 0, /* tp_new */
1476 PyObject_GC_Del, /* tp_free */
1477};
1478
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001479/* module level code ********************************************************/
1480
1481PyDoc_STRVAR(module_doc,
Guido van Rossum1968ad32006-02-25 22:38:04 +00001482"High performance data structures.\n\
1483- deque: ordered collection accessible from endpoints only\n\
1484- defaultdict: dict subclass with a default value factory\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001485");
1486
Martin v. Löwis1a214512008-06-11 05:26:20 +00001487
1488static struct PyModuleDef _collectionsmodule = {
1489 PyModuleDef_HEAD_INIT,
1490 "_collections",
1491 module_doc,
1492 -1,
1493 NULL,
1494 NULL,
1495 NULL,
1496 NULL,
1497 NULL
1498};
1499
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001500PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001501PyInit__collections(void)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001502{
1503 PyObject *m;
1504
Martin v. Löwis1a214512008-06-11 05:26:20 +00001505 m = PyModule_Create(&_collectionsmodule);
Neal Norwitz1ac754f2006-01-19 06:09:39 +00001506 if (m == NULL)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001507 return NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001508
1509 if (PyType_Ready(&deque_type) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001510 return NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001511 Py_INCREF(&deque_type);
1512 PyModule_AddObject(m, "deque", (PyObject *)&deque_type);
1513
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001514 defdict_type.tp_base = &PyDict_Type;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001515 if (PyType_Ready(&defdict_type) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001516 return NULL;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001517 Py_INCREF(&defdict_type);
1518 PyModule_AddObject(m, "defaultdict", (PyObject *)&defdict_type);
1519
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001520 if (PyType_Ready(&dequeiter_type) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001521 return NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001522
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001523 if (PyType_Ready(&dequereviter_type) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001524 return NULL;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001525
Martin v. Löwis1a214512008-06-11 05:26:20 +00001526 return m;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001527}