blob: d20c839ae3332735e166af9691341969546ac6eb [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 Hettinger64eaa202009-12-10 05:36:11 +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 Hettinger64eaa202009-12-10 05:36:11 +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 Hettinger64eaa202009-12-10 05:36:11 +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
Martin v. Löwis18e16552006-02-15 17:27:45 +0000465static Py_ssize_t
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000466deque_len(dequeobject *deque)
467{
468 return deque->len;
469}
470
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000471static PyObject *
472deque_remove(dequeobject *deque, PyObject *value)
473{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000474 Py_ssize_t i, n=deque->len;
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000475
476 for (i=0 ; i<n ; i++) {
477 PyObject *item = deque->leftblock->data[deque->leftindex];
478 int cmp = PyObject_RichCompareBool(item, value, Py_EQ);
Raymond Hettingerd73202c2005-03-19 00:00:51 +0000479
480 if (deque->len != n) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000481 PyErr_SetString(PyExc_IndexError,
Raymond Hettingerd73202c2005-03-19 00:00:51 +0000482 "deque mutated during remove().");
483 return NULL;
484 }
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000485 if (cmp > 0) {
Raymond Hettingerd73202c2005-03-19 00:00:51 +0000486 PyObject *tgt = deque_popleft(deque, NULL);
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000487 assert (tgt != NULL);
488 Py_DECREF(tgt);
489 if (_deque_rotate(deque, i) == -1)
490 return NULL;
491 Py_RETURN_NONE;
492 }
493 else if (cmp < 0) {
494 _deque_rotate(deque, i);
495 return NULL;
496 }
497 _deque_rotate(deque, -1);
498 }
499 PyErr_SetString(PyExc_ValueError, "deque.remove(x): x not in deque");
500 return NULL;
501}
502
503PyDoc_STRVAR(remove_doc,
504"D.remove(value) -- remove first occurrence of value.");
505
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000506static int
507deque_clear(dequeobject *deque)
508{
509 PyObject *item;
510
Raymond Hettingerd1b3d882004-10-02 00:43:13 +0000511 while (deque->len) {
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000512 item = deque_pop(deque, NULL);
Raymond Hettingera435c532004-07-09 04:10:20 +0000513 assert (item != NULL);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000514 Py_DECREF(item);
515 }
516 assert(deque->leftblock == deque->rightblock &&
Raymond Hettingerd1b3d882004-10-02 00:43:13 +0000517 deque->leftindex - 1 == deque->rightindex &&
518 deque->len == 0);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000519 return 0;
520}
521
522static PyObject *
Benjamin Petersond6313712008-07-31 16:23:04 +0000523deque_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000524{
525 block *b;
526 PyObject *item;
Benjamin Petersond6313712008-07-31 16:23:04 +0000527 Py_ssize_t n, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000528
529 if (i < 0 || i >= deque->len) {
530 PyErr_SetString(PyExc_IndexError,
531 "deque index out of range");
532 return NULL;
533 }
534
Raymond Hettinger6c79a512004-03-04 08:00:54 +0000535 if (i == 0) {
536 i = deque->leftindex;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000537 b = deque->leftblock;
Raymond Hettinger6c79a512004-03-04 08:00:54 +0000538 } else if (i == deque->len - 1) {
539 i = deque->rightindex;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000540 b = deque->rightblock;
Raymond Hettinger6c79a512004-03-04 08:00:54 +0000541 } else {
542 i += deque->leftindex;
543 n = i / BLOCKLEN;
544 i %= BLOCKLEN;
Armin Rigo974d7572004-10-02 13:59:34 +0000545 if (index < (deque->len >> 1)) {
Raymond Hettinger6c79a512004-03-04 08:00:54 +0000546 b = deque->leftblock;
547 while (n--)
548 b = b->rightlink;
549 } else {
550 n = (deque->leftindex + deque->len - 1) / BLOCKLEN - n;
551 b = deque->rightblock;
552 while (n--)
553 b = b->leftlink;
554 }
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000555 }
556 item = b->data[i];
557 Py_INCREF(item);
558 return item;
559}
560
Raymond Hettinger616f4f62004-06-26 04:42:06 +0000561/* delitem() implemented in terms of rotate for simplicity and reasonable
562 performance near the end points. If for some reason this method becomes
Tim Peters1065f752004-10-01 01:03:29 +0000563 popular, it is not hard to re-implement this using direct data movement
Raymond Hettinger616f4f62004-06-26 04:42:06 +0000564 (similar to code in list slice assignment) and achieve a two or threefold
565 performance boost.
566*/
567
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000568static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000569deque_del_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000570{
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000571 PyObject *item;
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000572
Tim Peters1065f752004-10-01 01:03:29 +0000573 assert (i >= 0 && i < deque->len);
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000574 if (_deque_rotate(deque, -i) == -1)
575 return -1;
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000576
577 item = deque_popleft(deque, NULL);
Raymond Hettingera435c532004-07-09 04:10:20 +0000578 assert (item != NULL);
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000579 Py_DECREF(item);
580
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000581 return _deque_rotate(deque, i);
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000582}
583
584static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000585deque_ass_item(dequeobject *deque, Py_ssize_t i, PyObject *v)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000586{
587 PyObject *old_value;
588 block *b;
Martin v. Löwisad0a4622006-02-16 14:30:23 +0000589 Py_ssize_t n, len=deque->len, halflen=(len+1)>>1, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000590
Raymond Hettingera435c532004-07-09 04:10:20 +0000591 if (i < 0 || i >= len) {
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000592 PyErr_SetString(PyExc_IndexError,
593 "deque index out of range");
594 return -1;
595 }
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000596 if (v == NULL)
597 return deque_del_item(deque, i);
598
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000599 i += deque->leftindex;
600 n = i / BLOCKLEN;
601 i %= BLOCKLEN;
Raymond Hettingera435c532004-07-09 04:10:20 +0000602 if (index <= halflen) {
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000603 b = deque->leftblock;
604 while (n--)
605 b = b->rightlink;
606 } else {
Raymond Hettingera435c532004-07-09 04:10:20 +0000607 n = (deque->leftindex + len - 1) / BLOCKLEN - n;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000608 b = deque->rightblock;
609 while (n--)
610 b = b->leftlink;
611 }
612 Py_INCREF(v);
613 old_value = b->data[i];
614 b->data[i] = v;
615 Py_DECREF(old_value);
616 return 0;
617}
618
619static PyObject *
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000620deque_clearmethod(dequeobject *deque)
621{
Raymond Hettingera435c532004-07-09 04:10:20 +0000622 int rv;
623
624 rv = deque_clear(deque);
625 assert (rv != -1);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000626 Py_RETURN_NONE;
627}
628
629PyDoc_STRVAR(clear_doc, "Remove all elements from the deque.");
630
631static void
632deque_dealloc(dequeobject *deque)
633{
634 PyObject_GC_UnTrack(deque);
Raymond Hettinger691d8052004-05-30 07:26:47 +0000635 if (deque->weakreflist != NULL)
636 PyObject_ClearWeakRefs((PyObject *) deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000637 if (deque->leftblock != NULL) {
Raymond Hettingere9c89e82004-07-19 00:10:24 +0000638 deque_clear(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000639 assert(deque->leftblock != NULL);
Guido van Rossum58da9312007-11-10 23:39:45 +0000640 freeblock(deque->leftblock);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000641 }
642 deque->leftblock = NULL;
643 deque->rightblock = NULL;
Christian Heimes90aa7642007-12-19 02:45:37 +0000644 Py_TYPE(deque)->tp_free(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000645}
646
647static int
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000648deque_traverse(dequeobject *deque, visitproc visit, void *arg)
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000649{
Tim Peters10c7e862004-10-01 02:01:04 +0000650 block *b;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000651 PyObject *item;
Benjamin Petersond6313712008-07-31 16:23:04 +0000652 Py_ssize_t index;
653 Py_ssize_t indexlo = deque->leftindex;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000654
Tim Peters10c7e862004-10-01 02:01:04 +0000655 for (b = deque->leftblock; b != NULL; b = b->rightlink) {
Benjamin Petersond6313712008-07-31 16:23:04 +0000656 const Py_ssize_t indexhi = b == deque->rightblock ?
Tim Peters10c7e862004-10-01 02:01:04 +0000657 deque->rightindex :
658 BLOCKLEN - 1;
659
660 for (index = indexlo; index <= indexhi; ++index) {
661 item = b->data[index];
662 Py_VISIT(item);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000663 }
Tim Peters10c7e862004-10-01 02:01:04 +0000664 indexlo = 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000665 }
666 return 0;
667}
668
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000669static PyObject *
670deque_copy(PyObject *deque)
671{
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000672 if (((dequeobject *)deque)->maxlen == -1)
Christian Heimes90aa7642007-12-19 02:45:37 +0000673 return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "O", deque, NULL);
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000674 else
Christian Heimes90aa7642007-12-19 02:45:37 +0000675 return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "Oi",
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000676 deque, ((dequeobject *)deque)->maxlen, NULL);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000677}
678
679PyDoc_STRVAR(copy_doc, "Return a shallow copy of a deque.");
680
681static PyObject *
682deque_reduce(dequeobject *deque)
683{
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000684 PyObject *dict, *result, *aslist;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000685
Raymond Hettinger952f8802004-11-09 07:27:35 +0000686 dict = PyObject_GetAttrString((PyObject *)deque, "__dict__");
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000687 if (dict == NULL)
Raymond Hettinger952f8802004-11-09 07:27:35 +0000688 PyErr_Clear();
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000689 aslist = PySequence_List((PyObject *)deque);
690 if (aslist == NULL) {
691 Py_XDECREF(dict);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000692 return NULL;
693 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000694 if (dict == NULL) {
695 if (deque->maxlen == -1)
Christian Heimes90aa7642007-12-19 02:45:37 +0000696 result = Py_BuildValue("O(O)", Py_TYPE(deque), aslist);
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000697 else
Benjamin Petersond6313712008-07-31 16:23:04 +0000698 result = Py_BuildValue("O(On)", Py_TYPE(deque), aslist, deque->maxlen);
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000699 } else {
700 if (deque->maxlen == -1)
Christian Heimes90aa7642007-12-19 02:45:37 +0000701 result = Py_BuildValue("O(OO)O", Py_TYPE(deque), aslist, Py_None, dict);
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000702 else
Benjamin Petersond6313712008-07-31 16:23:04 +0000703 result = Py_BuildValue("O(On)O", Py_TYPE(deque), aslist, deque->maxlen, dict);
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000704 }
705 Py_XDECREF(dict);
706 Py_DECREF(aslist);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000707 return result;
708}
709
710PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
711
712static PyObject *
713deque_repr(PyObject *deque)
714{
Walter Dörwald1ab83302007-05-18 17:15:44 +0000715 PyObject *aslist, *result;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000716 int i;
717
718 i = Py_ReprEnter(deque);
719 if (i != 0) {
720 if (i < 0)
721 return NULL;
Walter Dörwald1ab83302007-05-18 17:15:44 +0000722 return PyUnicode_FromString("[...]");
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000723 }
724
725 aslist = PySequence_List(deque);
726 if (aslist == NULL) {
727 Py_ReprLeave(deque);
728 return NULL;
729 }
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000730 if (((dequeobject *)deque)->maxlen != -1)
Benjamin Petersona786b022008-08-25 21:05:21 +0000731
Amaury Forgeot d'Arc245c70b2008-09-10 22:24:24 +0000732 result = PyUnicode_FromFormat("deque(%R, maxlen=%zd)",
Benjamin Petersona786b022008-08-25 21:05:21 +0000733 aslist, ((dequeobject *)deque)->maxlen);
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000734 else
735 result = PyUnicode_FromFormat("deque(%R)", aslist);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000736 Py_DECREF(aslist);
737 Py_ReprLeave(deque);
738 return result;
739}
740
Raymond Hettinger738ec902004-02-29 02:15:56 +0000741static PyObject *
742deque_richcompare(PyObject *v, PyObject *w, int op)
743{
744 PyObject *it1=NULL, *it2=NULL, *x, *y;
Benjamin Petersond6313712008-07-31 16:23:04 +0000745 Py_ssize_t vs, ws;
746 int b, cmp=-1;
Raymond Hettinger738ec902004-02-29 02:15:56 +0000747
Tim Peters1065f752004-10-01 01:03:29 +0000748 if (!PyObject_TypeCheck(v, &deque_type) ||
Raymond Hettinger285cfcc2004-05-18 18:15:03 +0000749 !PyObject_TypeCheck(w, &deque_type)) {
Raymond Hettinger738ec902004-02-29 02:15:56 +0000750 Py_INCREF(Py_NotImplemented);
751 return Py_NotImplemented;
752 }
753
754 /* Shortcuts */
755 vs = ((dequeobject *)v)->len;
756 ws = ((dequeobject *)w)->len;
757 if (op == Py_EQ) {
758 if (v == w)
759 Py_RETURN_TRUE;
760 if (vs != ws)
761 Py_RETURN_FALSE;
762 }
763 if (op == Py_NE) {
764 if (v == w)
765 Py_RETURN_FALSE;
766 if (vs != ws)
767 Py_RETURN_TRUE;
768 }
769
770 /* Search for the first index where items are different */
771 it1 = PyObject_GetIter(v);
772 if (it1 == NULL)
773 goto done;
774 it2 = PyObject_GetIter(w);
775 if (it2 == NULL)
776 goto done;
Armin Rigo974d7572004-10-02 13:59:34 +0000777 for (;;) {
Raymond Hettinger738ec902004-02-29 02:15:56 +0000778 x = PyIter_Next(it1);
Armin Rigo974d7572004-10-02 13:59:34 +0000779 if (x == NULL && PyErr_Occurred())
Raymond Hettinger738ec902004-02-29 02:15:56 +0000780 goto done;
781 y = PyIter_Next(it2);
Armin Rigo974d7572004-10-02 13:59:34 +0000782 if (x == NULL || y == NULL)
783 break;
Raymond Hettinger738ec902004-02-29 02:15:56 +0000784 b = PyObject_RichCompareBool(x, y, Py_EQ);
785 if (b == 0) {
786 cmp = PyObject_RichCompareBool(x, y, op);
787 Py_DECREF(x);
788 Py_DECREF(y);
789 goto done;
790 }
791 Py_DECREF(x);
792 Py_DECREF(y);
793 if (b == -1)
794 goto done;
795 }
Armin Rigo974d7572004-10-02 13:59:34 +0000796 /* We reached the end of one deque or both */
797 Py_XDECREF(x);
798 Py_XDECREF(y);
799 if (PyErr_Occurred())
800 goto done;
Raymond Hettinger738ec902004-02-29 02:15:56 +0000801 switch (op) {
Armin Rigo974d7572004-10-02 13:59:34 +0000802 case Py_LT: cmp = y != NULL; break; /* if w was longer */
803 case Py_LE: cmp = x == NULL; break; /* if v was not longer */
804 case Py_EQ: cmp = x == y; break; /* if we reached the end of both */
805 case Py_NE: cmp = x != y; break; /* if one deque continues */
806 case Py_GT: cmp = x != NULL; break; /* if v was longer */
807 case Py_GE: cmp = y == NULL; break; /* if w was not longer */
Raymond Hettinger738ec902004-02-29 02:15:56 +0000808 }
Tim Peters1065f752004-10-01 01:03:29 +0000809
Raymond Hettinger738ec902004-02-29 02:15:56 +0000810done:
811 Py_XDECREF(it1);
812 Py_XDECREF(it2);
813 if (cmp == 1)
814 Py_RETURN_TRUE;
815 if (cmp == 0)
816 Py_RETURN_FALSE;
817 return NULL;
818}
819
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000820static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000821deque_init(dequeobject *deque, PyObject *args, PyObject *kwdargs)
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000822{
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000823 PyObject *iterable = NULL;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000824 PyObject *maxlenobj = NULL;
Benjamin Petersond6313712008-07-31 16:23:04 +0000825 Py_ssize_t maxlen = -1;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000826 char *kwlist[] = {"iterable", "maxlen", 0};
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000827
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000828 if (!PyArg_ParseTupleAndKeywords(args, kwdargs, "|OO:deque", kwlist, &iterable, &maxlenobj))
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000829 return -1;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000830 if (maxlenobj != NULL && maxlenobj != Py_None) {
Benjamin Petersond6313712008-07-31 16:23:04 +0000831 maxlen = PyLong_AsSsize_t(maxlenobj);
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000832 if (maxlen == -1 && PyErr_Occurred())
833 return -1;
834 if (maxlen < 0) {
835 PyErr_SetString(PyExc_ValueError, "maxlen must be non-negative");
836 return -1;
837 }
838 }
839 deque->maxlen = maxlen;
Christian Heimes38053212007-12-14 01:24:44 +0000840 deque_clear(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000841 if (iterable != NULL) {
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000842 PyObject *rv = deque_extend(deque, iterable);
843 if (rv == NULL)
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000844 return -1;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000845 Py_DECREF(rv);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000846 }
847 return 0;
848}
849
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +0000850static PyObject *
851deque_get_maxlen(dequeobject *deque)
852{
853 if (deque->maxlen == -1)
854 Py_RETURN_NONE;
855 return PyLong_FromSsize_t(deque->maxlen);
856}
857
858static PyGetSetDef deque_getset[] = {
859 {"maxlen", (getter)deque_get_maxlen, (setter)NULL,
860 "maximum size of a deque or None if unbounded"},
861 {0}
862};
863
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000864static PySequenceMethods deque_as_sequence = {
Martin v. Löwis18e16552006-02-15 17:27:45 +0000865 (lenfunc)deque_len, /* sq_length */
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000866 0, /* sq_concat */
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000867 0, /* sq_repeat */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000868 (ssizeargfunc)deque_item, /* sq_item */
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000869 0, /* sq_slice */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000870 (ssizeobjargproc)deque_ass_item, /* sq_ass_item */
Raymond Hettinger64eaa202009-12-10 05:36:11 +0000871 0, /* sq_ass_slice */
872 0, /* sq_contains */
873 (binaryfunc)deque_inplace_concat, /* sq_inplace_concat */
874 0, /* sq_inplace_repeat */
875
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000876};
877
878/* deque object ********************************************************/
879
880static PyObject *deque_iter(dequeobject *deque);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +0000881static PyObject *deque_reviter(dequeobject *deque);
Tim Peters1065f752004-10-01 01:03:29 +0000882PyDoc_STRVAR(reversed_doc,
Raymond Hettinger1e5809f2004-03-18 11:04:57 +0000883 "D.__reversed__() -- return a reverse iterator over the deque");
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000884
885static PyMethodDef deque_methods[] = {
Tim Peters1065f752004-10-01 01:03:29 +0000886 {"append", (PyCFunction)deque_append,
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000887 METH_O, append_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000888 {"appendleft", (PyCFunction)deque_appendleft,
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000889 METH_O, appendleft_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000890 {"clear", (PyCFunction)deque_clearmethod,
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000891 METH_NOARGS, clear_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000892 {"__copy__", (PyCFunction)deque_copy,
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000893 METH_NOARGS, copy_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000894 {"extend", (PyCFunction)deque_extend,
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000895 METH_O, extend_doc},
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000896 {"extendleft", (PyCFunction)deque_extendleft,
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000897 METH_O, extendleft_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000898 {"pop", (PyCFunction)deque_pop,
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000899 METH_NOARGS, pop_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000900 {"popleft", (PyCFunction)deque_popleft,
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000901 METH_NOARGS, popleft_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000902 {"__reduce__", (PyCFunction)deque_reduce,
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000903 METH_NOARGS, reduce_doc},
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000904 {"remove", (PyCFunction)deque_remove,
905 METH_O, remove_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000906 {"__reversed__", (PyCFunction)deque_reviter,
Raymond Hettinger1e5809f2004-03-18 11:04:57 +0000907 METH_NOARGS, reversed_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000908 {"rotate", (PyCFunction)deque_rotate,
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000909 METH_VARARGS, rotate_doc},
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000910 {NULL, NULL} /* sentinel */
911};
912
913PyDoc_STRVAR(deque_doc,
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000914"deque(iterable[, maxlen]) --> deque object\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000915\n\
916Build an ordered collection accessible from endpoints only.");
917
Neal Norwitz87f10132004-02-29 15:40:53 +0000918static PyTypeObject deque_type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000919 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000920 "collections.deque", /* tp_name */
921 sizeof(dequeobject), /* tp_basicsize */
922 0, /* tp_itemsize */
923 /* methods */
924 (destructor)deque_dealloc, /* tp_dealloc */
Guido van Rossum346f1a82007-08-07 19:58:47 +0000925 0, /* tp_print */
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000926 0, /* tp_getattr */
927 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +0000928 0, /* tp_reserved */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000929 deque_repr, /* tp_repr */
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000930 0, /* tp_as_number */
931 &deque_as_sequence, /* tp_as_sequence */
932 0, /* tp_as_mapping */
Nick Coghland1abd252008-07-15 15:46:38 +0000933 (hashfunc)PyObject_HashNotImplemented, /* tp_hash */
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000934 0, /* tp_call */
935 0, /* tp_str */
936 PyObject_GenericGetAttr, /* tp_getattro */
937 0, /* tp_setattro */
938 0, /* tp_as_buffer */
Guido van Rossumd8faa362007-04-27 19:54:29 +0000939 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
940 /* tp_flags */
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000941 deque_doc, /* tp_doc */
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000942 (traverseproc)deque_traverse, /* tp_traverse */
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000943 (inquiry)deque_clear, /* tp_clear */
Raymond Hettinger738ec902004-02-29 02:15:56 +0000944 (richcmpfunc)deque_richcompare, /* tp_richcompare */
Raymond Hettinger691d8052004-05-30 07:26:47 +0000945 offsetof(dequeobject, weakreflist), /* tp_weaklistoffset*/
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000946 (getiterfunc)deque_iter, /* tp_iter */
947 0, /* tp_iternext */
948 deque_methods, /* tp_methods */
949 0, /* tp_members */
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +0000950 deque_getset, /* tp_getset */
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000951 0, /* tp_base */
952 0, /* tp_dict */
953 0, /* tp_descr_get */
954 0, /* tp_descr_set */
955 0, /* tp_dictoffset */
956 (initproc)deque_init, /* tp_init */
957 PyType_GenericAlloc, /* tp_alloc */
958 deque_new, /* tp_new */
959 PyObject_GC_Del, /* tp_free */
960};
961
962/*********************** Deque Iterator **************************/
963
964typedef struct {
965 PyObject_HEAD
Benjamin Petersond6313712008-07-31 16:23:04 +0000966 Py_ssize_t index;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000967 block *b;
968 dequeobject *deque;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +0000969 long state; /* state when the iterator is created */
Benjamin Petersond6313712008-07-31 16:23:04 +0000970 Py_ssize_t counter; /* number of items remaining for iteration */
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000971} dequeiterobject;
972
Martin v. Löwis59683e82008-06-13 07:50:45 +0000973static PyTypeObject dequeiter_type;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000974
975static PyObject *
976deque_iter(dequeobject *deque)
977{
978 dequeiterobject *it;
979
Antoine Pitrou7ddda782009-01-01 15:35:33 +0000980 it = PyObject_GC_New(dequeiterobject, &dequeiter_type);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000981 if (it == NULL)
982 return NULL;
983 it->b = deque->leftblock;
984 it->index = deque->leftindex;
985 Py_INCREF(deque);
986 it->deque = deque;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +0000987 it->state = deque->state;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +0000988 it->counter = deque->len;
Georg Brandlb1441c72009-01-03 22:33:39 +0000989 PyObject_GC_Track(it);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000990 return (PyObject *)it;
991}
992
Antoine Pitrou7ddda782009-01-01 15:35:33 +0000993static int
994dequeiter_traverse(dequeiterobject *dio, visitproc visit, void *arg)
995{
996 Py_VISIT(dio->deque);
997 return 0;
998}
999
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001000static void
1001dequeiter_dealloc(dequeiterobject *dio)
1002{
1003 Py_XDECREF(dio->deque);
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001004 PyObject_GC_Del(dio);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001005}
1006
1007static PyObject *
1008dequeiter_next(dequeiterobject *it)
1009{
1010 PyObject *item;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001011
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001012 if (it->deque->state != it->state) {
Raymond Hettinger7892b1c2004-04-12 18:10:01 +00001013 it->counter = 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001014 PyErr_SetString(PyExc_RuntimeError,
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001015 "deque mutated during iteration");
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001016 return NULL;
1017 }
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001018 if (it->counter == 0)
1019 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001020 assert (!(it->b == it->deque->rightblock &&
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001021 it->index > it->deque->rightindex));
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001022
1023 item = it->b->data[it->index];
1024 it->index++;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001025 it->counter--;
1026 if (it->index == BLOCKLEN && it->counter > 0) {
1027 assert (it->b->rightlink != NULL);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001028 it->b = it->b->rightlink;
1029 it->index = 0;
1030 }
1031 Py_INCREF(item);
1032 return item;
1033}
1034
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001035static PyObject *
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001036dequeiter_len(dequeiterobject *it)
1037{
Christian Heimes217cfd12007-12-02 14:31:20 +00001038 return PyLong_FromLong(it->counter);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001039}
1040
Armin Rigof5b3e362006-02-11 21:32:43 +00001041PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001042
1043static PyMethodDef dequeiter_methods[] = {
Armin Rigof5b3e362006-02-11 21:32:43 +00001044 {"__length_hint__", (PyCFunction)dequeiter_len, METH_NOARGS, length_hint_doc},
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001045 {NULL, NULL} /* sentinel */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001046};
1047
Martin v. Löwis59683e82008-06-13 07:50:45 +00001048static PyTypeObject dequeiter_type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001049 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001050 "deque_iterator", /* tp_name */
1051 sizeof(dequeiterobject), /* tp_basicsize */
1052 0, /* tp_itemsize */
1053 /* methods */
1054 (destructor)dequeiter_dealloc, /* tp_dealloc */
1055 0, /* tp_print */
1056 0, /* tp_getattr */
1057 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00001058 0, /* tp_reserved */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001059 0, /* tp_repr */
1060 0, /* tp_as_number */
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001061 0, /* tp_as_sequence */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001062 0, /* tp_as_mapping */
1063 0, /* tp_hash */
1064 0, /* tp_call */
1065 0, /* tp_str */
1066 PyObject_GenericGetAttr, /* tp_getattro */
1067 0, /* tp_setattro */
1068 0, /* tp_as_buffer */
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001069 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001070 0, /* tp_doc */
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001071 (traverseproc)dequeiter_traverse, /* tp_traverse */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001072 0, /* tp_clear */
1073 0, /* tp_richcompare */
1074 0, /* tp_weaklistoffset */
1075 PyObject_SelfIter, /* tp_iter */
1076 (iternextfunc)dequeiter_next, /* tp_iternext */
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001077 dequeiter_methods, /* tp_methods */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001078 0,
1079};
1080
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001081/*********************** Deque Reverse Iterator **************************/
1082
Martin v. Löwis59683e82008-06-13 07:50:45 +00001083static PyTypeObject dequereviter_type;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001084
1085static PyObject *
1086deque_reviter(dequeobject *deque)
1087{
1088 dequeiterobject *it;
1089
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001090 it = PyObject_GC_New(dequeiterobject, &dequereviter_type);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001091 if (it == NULL)
1092 return NULL;
1093 it->b = deque->rightblock;
1094 it->index = deque->rightindex;
1095 Py_INCREF(deque);
1096 it->deque = deque;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001097 it->state = deque->state;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001098 it->counter = deque->len;
Georg Brandlb1441c72009-01-03 22:33:39 +00001099 PyObject_GC_Track(it);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001100 return (PyObject *)it;
1101}
1102
1103static PyObject *
1104dequereviter_next(dequeiterobject *it)
1105{
1106 PyObject *item;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001107 if (it->counter == 0)
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001108 return NULL;
1109
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001110 if (it->deque->state != it->state) {
Raymond Hettinger7892b1c2004-04-12 18:10:01 +00001111 it->counter = 0;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001112 PyErr_SetString(PyExc_RuntimeError,
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001113 "deque mutated during iteration");
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001114 return NULL;
1115 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001116 assert (!(it->b == it->deque->leftblock &&
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001117 it->index < it->deque->leftindex));
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001118
1119 item = it->b->data[it->index];
1120 it->index--;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001121 it->counter--;
1122 if (it->index == -1 && it->counter > 0) {
1123 assert (it->b->leftlink != NULL);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001124 it->b = it->b->leftlink;
1125 it->index = BLOCKLEN - 1;
1126 }
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001127 Py_INCREF(item);
1128 return item;
1129}
1130
Martin v. Löwis59683e82008-06-13 07:50:45 +00001131static PyTypeObject dequereviter_type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001132 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001133 "deque_reverse_iterator", /* tp_name */
1134 sizeof(dequeiterobject), /* tp_basicsize */
1135 0, /* tp_itemsize */
1136 /* methods */
1137 (destructor)dequeiter_dealloc, /* tp_dealloc */
1138 0, /* tp_print */
1139 0, /* tp_getattr */
1140 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00001141 0, /* tp_reserved */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001142 0, /* tp_repr */
1143 0, /* tp_as_number */
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001144 0, /* tp_as_sequence */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001145 0, /* tp_as_mapping */
1146 0, /* tp_hash */
1147 0, /* tp_call */
1148 0, /* tp_str */
1149 PyObject_GenericGetAttr, /* tp_getattro */
1150 0, /* tp_setattro */
1151 0, /* tp_as_buffer */
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001152 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001153 0, /* tp_doc */
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001154 (traverseproc)dequeiter_traverse, /* tp_traverse */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001155 0, /* tp_clear */
1156 0, /* tp_richcompare */
1157 0, /* tp_weaklistoffset */
1158 PyObject_SelfIter, /* tp_iter */
1159 (iternextfunc)dequereviter_next, /* tp_iternext */
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001160 dequeiter_methods, /* tp_methods */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001161 0,
1162};
1163
Guido van Rossum1968ad32006-02-25 22:38:04 +00001164/* defaultdict type *********************************************************/
1165
1166typedef struct {
1167 PyDictObject dict;
1168 PyObject *default_factory;
1169} defdictobject;
1170
1171static PyTypeObject defdict_type; /* Forward */
1172
1173PyDoc_STRVAR(defdict_missing_doc,
1174"__missing__(key) # Called by __getitem__ for missing key; pseudo-code:\n\
Guido van Rossumd8faa362007-04-27 19:54:29 +00001175 if self.default_factory is None: raise KeyError((key,))\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00001176 self[key] = value = self.default_factory()\n\
1177 return value\n\
1178");
1179
1180static PyObject *
1181defdict_missing(defdictobject *dd, PyObject *key)
1182{
1183 PyObject *factory = dd->default_factory;
1184 PyObject *value;
1185 if (factory == NULL || factory == Py_None) {
1186 /* XXX Call dict.__missing__(key) */
Guido van Rossumd8faa362007-04-27 19:54:29 +00001187 PyObject *tup;
1188 tup = PyTuple_Pack(1, key);
1189 if (!tup) return NULL;
1190 PyErr_SetObject(PyExc_KeyError, tup);
1191 Py_DECREF(tup);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001192 return NULL;
1193 }
1194 value = PyEval_CallObject(factory, NULL);
1195 if (value == NULL)
1196 return value;
1197 if (PyObject_SetItem((PyObject *)dd, key, value) < 0) {
1198 Py_DECREF(value);
1199 return NULL;
1200 }
1201 return value;
1202}
1203
1204PyDoc_STRVAR(defdict_copy_doc, "D.copy() -> a shallow copy of D.");
1205
1206static PyObject *
1207defdict_copy(defdictobject *dd)
1208{
1209 /* This calls the object's class. That only works for subclasses
1210 whose class constructor has the same signature. Subclasses that
Christian Heimes0bd4e112008-02-12 22:59:25 +00001211 define a different constructor signature must override copy().
Guido van Rossum1968ad32006-02-25 22:38:04 +00001212 */
Raymond Hettinger99a13ee2009-08-04 19:13:37 +00001213
1214 if (dd->default_factory == NULL)
1215 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd), Py_None, dd, NULL);
Christian Heimes90aa7642007-12-19 02:45:37 +00001216 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd),
Guido van Rossum1968ad32006-02-25 22:38:04 +00001217 dd->default_factory, dd, NULL);
1218}
1219
1220static PyObject *
1221defdict_reduce(defdictobject *dd)
1222{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001223 /* __reduce__ must return a 5-tuple as follows:
Guido van Rossum1968ad32006-02-25 22:38:04 +00001224
1225 - factory function
1226 - tuple of args for the factory function
1227 - additional state (here None)
1228 - sequence iterator (here None)
1229 - dictionary iterator (yielding successive (key, value) pairs
1230
1231 This API is used by pickle.py and copy.py.
1232
1233 For this to be useful with pickle.py, the default_factory
1234 must be picklable; e.g., None, a built-in, or a global
1235 function in a module or package.
1236
1237 Both shallow and deep copying are supported, but for deep
1238 copying, the default_factory must be deep-copyable; e.g. None,
1239 or a built-in (functions are not copyable at this time).
1240
1241 This only works for subclasses as long as their constructor
1242 signature is compatible; the first argument must be the
1243 optional default_factory, defaulting to None.
1244 */
1245 PyObject *args;
1246 PyObject *items;
Amaury Forgeot d'Arcf43ee812008-10-30 20:58:42 +00001247 PyObject *iter;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001248 PyObject *result;
1249 if (dd->default_factory == NULL || dd->default_factory == Py_None)
1250 args = PyTuple_New(0);
1251 else
1252 args = PyTuple_Pack(1, dd->default_factory);
1253 if (args == NULL)
1254 return NULL;
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001255 items = PyObject_CallMethod((PyObject *)dd, "items", "()");
Guido van Rossum1968ad32006-02-25 22:38:04 +00001256 if (items == NULL) {
1257 Py_DECREF(args);
1258 return NULL;
1259 }
Amaury Forgeot d'Arcf43ee812008-10-30 20:58:42 +00001260 iter = PyObject_GetIter(items);
1261 if (iter == NULL) {
1262 Py_DECREF(items);
1263 Py_DECREF(args);
1264 return NULL;
1265 }
Christian Heimes90aa7642007-12-19 02:45:37 +00001266 result = PyTuple_Pack(5, Py_TYPE(dd), args,
Amaury Forgeot d'Arcf43ee812008-10-30 20:58:42 +00001267 Py_None, Py_None, iter);
1268 Py_DECREF(iter);
Guido van Rossumd8faa362007-04-27 19:54:29 +00001269 Py_DECREF(items);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001270 Py_DECREF(args);
1271 return result;
1272}
1273
1274static PyMethodDef defdict_methods[] = {
1275 {"__missing__", (PyCFunction)defdict_missing, METH_O,
1276 defdict_missing_doc},
Christian Heimes3feef612008-02-11 06:19:17 +00001277 {"copy", (PyCFunction)defdict_copy, METH_NOARGS,
1278 defdict_copy_doc},
Guido van Rossum1968ad32006-02-25 22:38:04 +00001279 {"__copy__", (PyCFunction)defdict_copy, METH_NOARGS,
1280 defdict_copy_doc},
1281 {"__reduce__", (PyCFunction)defdict_reduce, METH_NOARGS,
1282 reduce_doc},
1283 {NULL}
1284};
1285
1286static PyMemberDef defdict_members[] = {
1287 {"default_factory", T_OBJECT,
1288 offsetof(defdictobject, default_factory), 0,
1289 PyDoc_STR("Factory for default value called by __missing__().")},
1290 {NULL}
1291};
1292
1293static void
1294defdict_dealloc(defdictobject *dd)
1295{
1296 Py_CLEAR(dd->default_factory);
1297 PyDict_Type.tp_dealloc((PyObject *)dd);
1298}
1299
Guido van Rossum1968ad32006-02-25 22:38:04 +00001300static PyObject *
1301defdict_repr(defdictobject *dd)
1302{
Guido van Rossum1968ad32006-02-25 22:38:04 +00001303 PyObject *baserepr;
Christian Heimes77c02eb2008-02-09 02:18:51 +00001304 PyObject *defrepr;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001305 PyObject *result;
1306 baserepr = PyDict_Type.tp_repr((PyObject *)dd);
1307 if (baserepr == NULL)
1308 return NULL;
1309 if (dd->default_factory == NULL)
Christian Heimes77c02eb2008-02-09 02:18:51 +00001310 defrepr = PyUnicode_FromString("None");
Guido van Rossum1968ad32006-02-25 22:38:04 +00001311 else
Christian Heimes77c02eb2008-02-09 02:18:51 +00001312 {
1313 int status = Py_ReprEnter(dd->default_factory);
1314 if (status != 0) {
1315 if (status < 0)
1316 return NULL;
1317 defrepr = PyUnicode_FromString("...");
1318 }
1319 else
1320 defrepr = PyObject_Repr(dd->default_factory);
1321 Py_ReprLeave(dd->default_factory);
1322 }
1323 if (defrepr == NULL) {
1324 Py_DECREF(baserepr);
1325 return NULL;
1326 }
1327 result = PyUnicode_FromFormat("defaultdict(%U, %U)",
1328 defrepr, baserepr);
1329 Py_DECREF(defrepr);
Walter Dörwald7569dfe2007-05-19 21:49:49 +00001330 Py_DECREF(baserepr);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001331 return result;
1332}
1333
1334static int
1335defdict_traverse(PyObject *self, visitproc visit, void *arg)
1336{
1337 Py_VISIT(((defdictobject *)self)->default_factory);
1338 return PyDict_Type.tp_traverse(self, visit, arg);
1339}
1340
1341static int
1342defdict_tp_clear(defdictobject *dd)
1343{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001344 Py_CLEAR(dd->default_factory);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001345 return PyDict_Type.tp_clear((PyObject *)dd);
1346}
1347
1348static int
1349defdict_init(PyObject *self, PyObject *args, PyObject *kwds)
1350{
1351 defdictobject *dd = (defdictobject *)self;
1352 PyObject *olddefault = dd->default_factory;
1353 PyObject *newdefault = NULL;
1354 PyObject *newargs;
1355 int result;
1356 if (args == NULL || !PyTuple_Check(args))
1357 newargs = PyTuple_New(0);
1358 else {
1359 Py_ssize_t n = PyTuple_GET_SIZE(args);
Thomas Wouterscf297e42007-02-23 15:07:44 +00001360 if (n > 0) {
Guido van Rossum1968ad32006-02-25 22:38:04 +00001361 newdefault = PyTuple_GET_ITEM(args, 0);
Raymond Hettinger99a13ee2009-08-04 19:13:37 +00001362 if (!PyCallable_Check(newdefault) && newdefault != Py_None) {
Thomas Wouterscf297e42007-02-23 15:07:44 +00001363 PyErr_SetString(PyExc_TypeError,
1364 "first argument must be callable");
1365 return -1;
1366 }
1367 }
Guido van Rossum1968ad32006-02-25 22:38:04 +00001368 newargs = PySequence_GetSlice(args, 1, n);
1369 }
1370 if (newargs == NULL)
1371 return -1;
1372 Py_XINCREF(newdefault);
1373 dd->default_factory = newdefault;
1374 result = PyDict_Type.tp_init(self, newargs, kwds);
1375 Py_DECREF(newargs);
1376 Py_XDECREF(olddefault);
1377 return result;
1378}
1379
1380PyDoc_STRVAR(defdict_doc,
1381"defaultdict(default_factory) --> dict with default factory\n\
1382\n\
1383The default factory is called without arguments to produce\n\
1384a new value when a key is not present, in __getitem__ only.\n\
1385A defaultdict compares equal to a dict with the same items.\n\
1386");
1387
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001388/* See comment in xxsubtype.c */
1389#define DEFERRED_ADDRESS(ADDR) 0
1390
Guido van Rossum1968ad32006-02-25 22:38:04 +00001391static PyTypeObject defdict_type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001392 PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0)
Guido van Rossum1968ad32006-02-25 22:38:04 +00001393 "collections.defaultdict", /* tp_name */
1394 sizeof(defdictobject), /* tp_basicsize */
1395 0, /* tp_itemsize */
1396 /* methods */
1397 (destructor)defdict_dealloc, /* tp_dealloc */
Guido van Rossum346f1a82007-08-07 19:58:47 +00001398 0, /* tp_print */
Guido van Rossum1968ad32006-02-25 22:38:04 +00001399 0, /* tp_getattr */
1400 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00001401 0, /* tp_reserved */
Guido van Rossum1968ad32006-02-25 22:38:04 +00001402 (reprfunc)defdict_repr, /* tp_repr */
1403 0, /* tp_as_number */
1404 0, /* tp_as_sequence */
1405 0, /* tp_as_mapping */
1406 0, /* tp_hash */
1407 0, /* tp_call */
1408 0, /* tp_str */
1409 PyObject_GenericGetAttr, /* tp_getattro */
1410 0, /* tp_setattro */
1411 0, /* tp_as_buffer */
Guido van Rossumd8faa362007-04-27 19:54:29 +00001412 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
1413 /* tp_flags */
Guido van Rossum1968ad32006-02-25 22:38:04 +00001414 defdict_doc, /* tp_doc */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001415 defdict_traverse, /* tp_traverse */
Guido van Rossum1968ad32006-02-25 22:38:04 +00001416 (inquiry)defdict_tp_clear, /* tp_clear */
1417 0, /* tp_richcompare */
1418 0, /* tp_weaklistoffset*/
1419 0, /* tp_iter */
1420 0, /* tp_iternext */
1421 defdict_methods, /* tp_methods */
1422 defdict_members, /* tp_members */
1423 0, /* tp_getset */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001424 DEFERRED_ADDRESS(&PyDict_Type), /* tp_base */
Guido van Rossum1968ad32006-02-25 22:38:04 +00001425 0, /* tp_dict */
1426 0, /* tp_descr_get */
1427 0, /* tp_descr_set */
1428 0, /* tp_dictoffset */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001429 defdict_init, /* tp_init */
Guido van Rossum1968ad32006-02-25 22:38:04 +00001430 PyType_GenericAlloc, /* tp_alloc */
1431 0, /* tp_new */
1432 PyObject_GC_Del, /* tp_free */
1433};
1434
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001435/* module level code ********************************************************/
1436
1437PyDoc_STRVAR(module_doc,
Guido van Rossum1968ad32006-02-25 22:38:04 +00001438"High performance data structures.\n\
1439- deque: ordered collection accessible from endpoints only\n\
1440- defaultdict: dict subclass with a default value factory\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001441");
1442
Martin v. Löwis1a214512008-06-11 05:26:20 +00001443
1444static struct PyModuleDef _collectionsmodule = {
1445 PyModuleDef_HEAD_INIT,
1446 "_collections",
1447 module_doc,
1448 -1,
1449 NULL,
1450 NULL,
1451 NULL,
1452 NULL,
1453 NULL
1454};
1455
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001456PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001457PyInit__collections(void)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001458{
1459 PyObject *m;
1460
Martin v. Löwis1a214512008-06-11 05:26:20 +00001461 m = PyModule_Create(&_collectionsmodule);
Neal Norwitz1ac754f2006-01-19 06:09:39 +00001462 if (m == NULL)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001463 return NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001464
1465 if (PyType_Ready(&deque_type) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001466 return NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001467 Py_INCREF(&deque_type);
1468 PyModule_AddObject(m, "deque", (PyObject *)&deque_type);
1469
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001470 defdict_type.tp_base = &PyDict_Type;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001471 if (PyType_Ready(&defdict_type) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001472 return NULL;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001473 Py_INCREF(&defdict_type);
1474 PyModule_AddObject(m, "defaultdict", (PyObject *)&defdict_type);
1475
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001476 if (PyType_Ready(&dequeiter_type) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001477 return NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001478
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001479 if (PyType_Ready(&dequereviter_type) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001480 return NULL;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001481
Martin v. Löwis1a214512008-06-11 05:26:20 +00001482 return m;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001483}