blob: 97b390539ffdb8e00e48f083af6d438275574470 [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
Tim Peters5566e962006-07-28 00:23:15 +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
Tim Peters5566e962006-07-28 00:23:15 +000025 * on both ends, algorithms for left and right operations become
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000026 * symmetrical which simplifies the design.
Tim Peters5566e962006-07-28 00:23:15 +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 *
Tim Peters5566e962006-07-28 00:23:15 +000040 * Whenever d.leftblock == d.rightblock,
Raymond Hettinger4ca4c7c2004-10-01 15:14:39 +000041 * d.leftindex + d.len - 1 == d.rightindex.
Tim Peters5566e962006-07-28 00:23:15 +000042 *
Raymond Hettinger4ca4c7c2004-10-01 15:14:39 +000043 * However, when d.leftblock != d.rightblock, d.leftindex and d.rightindex
Tim Peters5566e962006-07-28 00:23:15 +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
Raymond Hettingerd3ffd342007-11-10 01:54:03 +000054#define MAXFREEBLOCKS 10
Raymond Hettinger33fcf9d2008-07-24 00:08:18 +000055static Py_ssize_t numfreeblocks = 0;
Raymond Hettingerd3ffd342007-11-10 01:54:03 +000056static block *freeblocks[MAXFREEBLOCKS];
57
Tim Peters6f853562004-10-01 01:04:50 +000058static block *
Raymond Hettinger33fcf9d2008-07-24 00:08:18 +000059newblock(block *leftlink, block *rightlink, Py_ssize_t len) {
Raymond Hettingerc5fa9922004-10-06 17:51:54 +000060 block *b;
Raymond Hettinger33fcf9d2008-07-24 00:08:18 +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
Raymond Hettinger33fcf9d2008-07-24 00:08:18 +000066 * have PY_SSIZE_T_MAX-2 entries in total.
Raymond Hettingerc5fa9922004-10-06 17:51:54 +000067 */
Raymond Hettinger33fcf9d2008-07-24 00:08:18 +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 }
Raymond Hettingerd3ffd342007-11-10 01:54:03 +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öwis111c1802008-06-13 07:47:47 +000088static void
Raymond Hettingerd3ffd342007-11-10 01:54:03 +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;
Raymond Hettinger33fcf9d2008-07-24 00:08:18 +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
Raymond Hettingera7fc4b12007-10-05 02:47:07 +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;
Raymond Hettingera7fc4b12007-10-05 02:47:07 +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);
Raymond Hettingerd3ffd342007-11-10 01:54:03 +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 }
Neal Norwitzccc56c72006-08-13 18:13:02 +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;
Raymond Hettingerd3ffd342007-11-10 01:54:03 +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 *
Raymond Hettingera7fc4b12007-10-05 02:47:07 +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 Hettingerbac769b2009-03-10 09:31:48 +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
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000296static PyObject *
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000297deque_extend(dequeobject *deque, PyObject *iterable)
298{
299 PyObject *it, *item;
300
Raymond Hettinger0b3263b2009-12-10 06:00:33 +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 Hettingerbac769b2009-03-10 09:31:48 +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;
Raymond Hettingera7fc4b12007-10-05 02:47:07 +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 Hettinger0b3263b2009-12-10 06:00:33 +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 Hettingerbac769b2009-03-10 09:31:48 +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;
Raymond Hettingera7fc4b12007-10-05 02:47:07 +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 Hettinger0b3263b2009-12-10 06:00:33 +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{
Raymond Hettinger33fcf9d2008-07-24 00:08:18 +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{
Raymond Hettinger33fcf9d2008-07-24 00:08:18 +0000453 Py_ssize_t n=1;
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000454
Raymond Hettinger723ba302008-07-24 00:53:49 +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) {
Tim Peters5566e962006-07-28 00:23:15 +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 *
Raymond Hettinger33fcf9d2008-07-24 00:08:18 +0000523deque_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000524{
525 block *b;
526 PyObject *item;
Raymond Hettinger33fcf9d2008-07-24 00:08:18 +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);
Raymond Hettingerd3ffd342007-11-10 01:54:03 +0000640 freeblock(deque->leftblock);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000641 }
642 deque->leftblock = NULL;
643 deque->rightblock = NULL;
Christian Heimese93237d2007-12-19 02:37:44 +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;
Raymond Hettinger33fcf9d2008-07-24 00:08:18 +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) {
Raymond Hettinger33fcf9d2008-07-24 00:08:18 +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{
Raymond Hettinger68995862007-10-10 00:26:46 +0000672 if (((dequeobject *)deque)->maxlen == -1)
Christian Heimese93237d2007-12-19 02:37:44 +0000673 return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "O", deque, NULL);
Raymond Hettinger68995862007-10-10 00:26:46 +0000674 else
Christian Heimese93237d2007-12-19 02:37:44 +0000675 return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "Oi",
Raymond Hettinger68995862007-10-10 00:26:46 +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{
Raymond Hettingera7fc4b12007-10-05 02:47:07 +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__");
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000687 if (dict == NULL)
Raymond Hettinger952f8802004-11-09 07:27:35 +0000688 PyErr_Clear();
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000689 aslist = PySequence_List((PyObject *)deque);
690 if (aslist == NULL) {
Neal Norwitzc47cf7d2007-10-05 03:39:17 +0000691 Py_XDECREF(dict);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000692 return NULL;
693 }
Raymond Hettinger68995862007-10-10 00:26:46 +0000694 if (dict == NULL) {
695 if (deque->maxlen == -1)
Christian Heimese93237d2007-12-19 02:37:44 +0000696 result = Py_BuildValue("O(O)", Py_TYPE(deque), aslist);
Raymond Hettinger68995862007-10-10 00:26:46 +0000697 else
Raymond Hettinger33fcf9d2008-07-24 00:08:18 +0000698 result = Py_BuildValue("O(On)", Py_TYPE(deque), aslist, deque->maxlen);
Raymond Hettinger68995862007-10-10 00:26:46 +0000699 } else {
700 if (deque->maxlen == -1)
Christian Heimese93237d2007-12-19 02:37:44 +0000701 result = Py_BuildValue("O(OO)O", Py_TYPE(deque), aslist, Py_None, dict);
Raymond Hettinger68995862007-10-10 00:26:46 +0000702 else
Raymond Hettinger33fcf9d2008-07-24 00:08:18 +0000703 result = Py_BuildValue("O(On)O", Py_TYPE(deque), aslist, deque->maxlen, dict);
Raymond Hettinger68995862007-10-10 00:26:46 +0000704 }
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000705 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{
Raymond Hettinger556b43d2007-10-05 19:07:31 +0000715 PyObject *aslist, *result, *fmt;
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;
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000722 return PyString_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 }
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000730 if (((dequeobject *)deque)->maxlen != -1)
Amaury Forgeot d'Arc05e34492008-09-10 22:04:45 +0000731 fmt = PyString_FromFormat("deque(%%r, maxlen=%zd)",
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000732 ((dequeobject *)deque)->maxlen);
733 else
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000734 fmt = PyString_FromString("deque(%r)");
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000735 if (fmt == NULL) {
736 Py_DECREF(aslist);
737 Py_ReprLeave(deque);
738 return NULL;
739 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000740 result = PyString_Format(fmt, aslist);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000741 Py_DECREF(fmt);
742 Py_DECREF(aslist);
743 Py_ReprLeave(deque);
744 return result;
745}
746
747static int
748deque_tp_print(PyObject *deque, FILE *fp, int flags)
749{
750 PyObject *it, *item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000751 char *emit = ""; /* No separator emitted on first pass */
752 char *separator = ", ";
753 int i;
754
755 i = Py_ReprEnter(deque);
756 if (i != 0) {
757 if (i < 0)
758 return i;
Raymond Hettinger556b43d2007-10-05 19:07:31 +0000759 Py_BEGIN_ALLOW_THREADS
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000760 fputs("[...]", fp);
Raymond Hettinger556b43d2007-10-05 19:07:31 +0000761 Py_END_ALLOW_THREADS
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000762 return 0;
763 }
764
765 it = PyObject_GetIter(deque);
766 if (it == NULL)
767 return -1;
768
Raymond Hettinger556b43d2007-10-05 19:07:31 +0000769 Py_BEGIN_ALLOW_THREADS
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000770 fputs("deque([", fp);
Raymond Hettinger556b43d2007-10-05 19:07:31 +0000771 Py_END_ALLOW_THREADS
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000772 while ((item = PyIter_Next(it)) != NULL) {
Raymond Hettinger556b43d2007-10-05 19:07:31 +0000773 Py_BEGIN_ALLOW_THREADS
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000774 fputs(emit, fp);
Raymond Hettinger556b43d2007-10-05 19:07:31 +0000775 Py_END_ALLOW_THREADS
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000776 emit = separator;
777 if (PyObject_Print(item, fp, 0) != 0) {
778 Py_DECREF(item);
779 Py_DECREF(it);
780 Py_ReprLeave(deque);
781 return -1;
782 }
783 Py_DECREF(item);
784 }
785 Py_ReprLeave(deque);
786 Py_DECREF(it);
Tim Peters1065f752004-10-01 01:03:29 +0000787 if (PyErr_Occurred())
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000788 return -1;
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000789
Raymond Hettinger556b43d2007-10-05 19:07:31 +0000790 Py_BEGIN_ALLOW_THREADS
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000791 if (((dequeobject *)deque)->maxlen == -1)
792 fputs("])", fp);
793 else
Christian Heimes1cc69632008-08-22 20:10:27 +0000794 fprintf(fp, "], maxlen=%" PY_FORMAT_SIZE_T "d)", ((dequeobject *)deque)->maxlen);
Raymond Hettinger556b43d2007-10-05 19:07:31 +0000795 Py_END_ALLOW_THREADS
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000796 return 0;
797}
798
Raymond Hettinger738ec902004-02-29 02:15:56 +0000799static PyObject *
800deque_richcompare(PyObject *v, PyObject *w, int op)
801{
802 PyObject *it1=NULL, *it2=NULL, *x, *y;
Raymond Hettinger33fcf9d2008-07-24 00:08:18 +0000803 Py_ssize_t vs, ws;
804 int b, cmp=-1;
Raymond Hettinger738ec902004-02-29 02:15:56 +0000805
Tim Peters1065f752004-10-01 01:03:29 +0000806 if (!PyObject_TypeCheck(v, &deque_type) ||
Raymond Hettinger285cfcc2004-05-18 18:15:03 +0000807 !PyObject_TypeCheck(w, &deque_type)) {
Raymond Hettinger738ec902004-02-29 02:15:56 +0000808 Py_INCREF(Py_NotImplemented);
809 return Py_NotImplemented;
810 }
811
812 /* Shortcuts */
813 vs = ((dequeobject *)v)->len;
814 ws = ((dequeobject *)w)->len;
815 if (op == Py_EQ) {
816 if (v == w)
817 Py_RETURN_TRUE;
818 if (vs != ws)
819 Py_RETURN_FALSE;
820 }
821 if (op == Py_NE) {
822 if (v == w)
823 Py_RETURN_FALSE;
824 if (vs != ws)
825 Py_RETURN_TRUE;
826 }
827
828 /* Search for the first index where items are different */
829 it1 = PyObject_GetIter(v);
830 if (it1 == NULL)
831 goto done;
832 it2 = PyObject_GetIter(w);
833 if (it2 == NULL)
834 goto done;
Armin Rigo974d7572004-10-02 13:59:34 +0000835 for (;;) {
Raymond Hettinger738ec902004-02-29 02:15:56 +0000836 x = PyIter_Next(it1);
Armin Rigo974d7572004-10-02 13:59:34 +0000837 if (x == NULL && PyErr_Occurred())
Raymond Hettinger738ec902004-02-29 02:15:56 +0000838 goto done;
839 y = PyIter_Next(it2);
Armin Rigo974d7572004-10-02 13:59:34 +0000840 if (x == NULL || y == NULL)
841 break;
Raymond Hettinger738ec902004-02-29 02:15:56 +0000842 b = PyObject_RichCompareBool(x, y, Py_EQ);
843 if (b == 0) {
844 cmp = PyObject_RichCompareBool(x, y, op);
845 Py_DECREF(x);
846 Py_DECREF(y);
847 goto done;
848 }
849 Py_DECREF(x);
850 Py_DECREF(y);
851 if (b == -1)
852 goto done;
853 }
Armin Rigo974d7572004-10-02 13:59:34 +0000854 /* We reached the end of one deque or both */
855 Py_XDECREF(x);
856 Py_XDECREF(y);
857 if (PyErr_Occurred())
858 goto done;
Raymond Hettinger738ec902004-02-29 02:15:56 +0000859 switch (op) {
Armin Rigo974d7572004-10-02 13:59:34 +0000860 case Py_LT: cmp = y != NULL; break; /* if w was longer */
861 case Py_LE: cmp = x == NULL; break; /* if v was not longer */
862 case Py_EQ: cmp = x == y; break; /* if we reached the end of both */
863 case Py_NE: cmp = x != y; break; /* if one deque continues */
864 case Py_GT: cmp = x != NULL; break; /* if v was longer */
865 case Py_GE: cmp = y == NULL; break; /* if w was not longer */
Raymond Hettinger738ec902004-02-29 02:15:56 +0000866 }
Tim Peters1065f752004-10-01 01:03:29 +0000867
Raymond Hettinger738ec902004-02-29 02:15:56 +0000868done:
869 Py_XDECREF(it1);
870 Py_XDECREF(it2);
871 if (cmp == 1)
872 Py_RETURN_TRUE;
873 if (cmp == 0)
874 Py_RETURN_FALSE;
875 return NULL;
876}
877
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000878static int
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000879deque_init(dequeobject *deque, PyObject *args, PyObject *kwdargs)
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000880{
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000881 PyObject *iterable = NULL;
Raymond Hettinger68995862007-10-10 00:26:46 +0000882 PyObject *maxlenobj = NULL;
Raymond Hettinger33fcf9d2008-07-24 00:08:18 +0000883 Py_ssize_t maxlen = -1;
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000884 char *kwlist[] = {"iterable", "maxlen", 0};
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000885
Raymond Hettinger68995862007-10-10 00:26:46 +0000886 if (!PyArg_ParseTupleAndKeywords(args, kwdargs, "|OO:deque", kwlist, &iterable, &maxlenobj))
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000887 return -1;
Raymond Hettinger68995862007-10-10 00:26:46 +0000888 if (maxlenobj != NULL && maxlenobj != Py_None) {
Raymond Hettinger33fcf9d2008-07-24 00:08:18 +0000889 maxlen = PyInt_AsSsize_t(maxlenobj);
Raymond Hettinger68995862007-10-10 00:26:46 +0000890 if (maxlen == -1 && PyErr_Occurred())
891 return -1;
892 if (maxlen < 0) {
893 PyErr_SetString(PyExc_ValueError, "maxlen must be non-negative");
894 return -1;
895 }
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000896 }
897 deque->maxlen = maxlen;
Raymond Hettingeradf9ffd2007-12-13 00:08:37 +0000898 deque_clear(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000899 if (iterable != NULL) {
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000900 PyObject *rv = deque_extend(deque, iterable);
901 if (rv == NULL)
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000902 return -1;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000903 Py_DECREF(rv);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000904 }
905 return 0;
906}
907
Raymond Hettinger56411aa2009-03-10 12:50:59 +0000908static PyObject *
909deque_get_maxlen(dequeobject *deque)
910{
911 if (deque->maxlen == -1)
912 Py_RETURN_NONE;
913 return PyInt_FromSsize_t(deque->maxlen);
914}
915
916static PyGetSetDef deque_getset[] = {
917 {"maxlen", (getter)deque_get_maxlen, (setter)NULL,
918 "maximum size of a deque or None if unbounded"},
919 {0}
920};
921
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000922static PySequenceMethods deque_as_sequence = {
Martin v. Löwis18e16552006-02-15 17:27:45 +0000923 (lenfunc)deque_len, /* sq_length */
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000924 0, /* sq_concat */
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000925 0, /* sq_repeat */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000926 (ssizeargfunc)deque_item, /* sq_item */
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000927 0, /* sq_slice */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000928 (ssizeobjargproc)deque_ass_item, /* sq_ass_item */
Raymond Hettinger0b3263b2009-12-10 06:00:33 +0000929 0, /* sq_ass_slice */
930 0, /* sq_contains */
931 (binaryfunc)deque_inplace_concat, /* sq_inplace_concat */
932 0, /* sq_inplace_repeat */
933
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000934};
935
936/* deque object ********************************************************/
937
938static PyObject *deque_iter(dequeobject *deque);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +0000939static PyObject *deque_reviter(dequeobject *deque);
Tim Peters1065f752004-10-01 01:03:29 +0000940PyDoc_STRVAR(reversed_doc,
Raymond Hettinger1e5809f2004-03-18 11:04:57 +0000941 "D.__reversed__() -- return a reverse iterator over the deque");
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000942
943static PyMethodDef deque_methods[] = {
Tim Peters1065f752004-10-01 01:03:29 +0000944 {"append", (PyCFunction)deque_append,
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000945 METH_O, append_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000946 {"appendleft", (PyCFunction)deque_appendleft,
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000947 METH_O, appendleft_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000948 {"clear", (PyCFunction)deque_clearmethod,
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000949 METH_NOARGS, clear_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000950 {"__copy__", (PyCFunction)deque_copy,
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000951 METH_NOARGS, copy_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000952 {"extend", (PyCFunction)deque_extend,
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000953 METH_O, extend_doc},
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000954 {"extendleft", (PyCFunction)deque_extendleft,
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000955 METH_O, extendleft_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000956 {"pop", (PyCFunction)deque_pop,
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000957 METH_NOARGS, pop_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000958 {"popleft", (PyCFunction)deque_popleft,
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000959 METH_NOARGS, popleft_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000960 {"__reduce__", (PyCFunction)deque_reduce,
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000961 METH_NOARGS, reduce_doc},
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000962 {"remove", (PyCFunction)deque_remove,
963 METH_O, remove_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000964 {"__reversed__", (PyCFunction)deque_reviter,
Raymond Hettinger1e5809f2004-03-18 11:04:57 +0000965 METH_NOARGS, reversed_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000966 {"rotate", (PyCFunction)deque_rotate,
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000967 METH_VARARGS, rotate_doc},
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000968 {NULL, NULL} /* sentinel */
969};
970
971PyDoc_STRVAR(deque_doc,
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000972"deque(iterable[, maxlen]) --> deque object\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000973\n\
974Build an ordered collection accessible from endpoints only.");
975
Neal Norwitz87f10132004-02-29 15:40:53 +0000976static PyTypeObject deque_type = {
Martin v. Löwis68192102007-07-21 06:55:02 +0000977 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000978 "collections.deque", /* tp_name */
979 sizeof(dequeobject), /* tp_basicsize */
980 0, /* tp_itemsize */
981 /* methods */
982 (destructor)deque_dealloc, /* tp_dealloc */
Georg Brandld37ac692006-03-30 11:58:57 +0000983 deque_tp_print, /* tp_print */
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000984 0, /* tp_getattr */
985 0, /* tp_setattr */
986 0, /* tp_compare */
Georg Brandld37ac692006-03-30 11:58:57 +0000987 deque_repr, /* tp_repr */
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000988 0, /* tp_as_number */
989 &deque_as_sequence, /* tp_as_sequence */
990 0, /* tp_as_mapping */
Nick Coghlan53663a62008-07-15 14:27:37 +0000991 (hashfunc)PyObject_HashNotImplemented, /* tp_hash */
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000992 0, /* tp_call */
993 0, /* tp_str */
994 PyObject_GenericGetAttr, /* tp_getattro */
995 0, /* tp_setattro */
996 0, /* tp_as_buffer */
Raymond Hettinger691d8052004-05-30 07:26:47 +0000997 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
998 Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000999 deque_doc, /* tp_doc */
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001000 (traverseproc)deque_traverse, /* tp_traverse */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001001 (inquiry)deque_clear, /* tp_clear */
Raymond Hettinger738ec902004-02-29 02:15:56 +00001002 (richcmpfunc)deque_richcompare, /* tp_richcompare */
Raymond Hettinger691d8052004-05-30 07:26:47 +00001003 offsetof(dequeobject, weakreflist), /* tp_weaklistoffset*/
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001004 (getiterfunc)deque_iter, /* tp_iter */
1005 0, /* tp_iternext */
1006 deque_methods, /* tp_methods */
1007 0, /* tp_members */
Raymond Hettinger56411aa2009-03-10 12:50:59 +00001008 deque_getset, /* tp_getset */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001009 0, /* tp_base */
1010 0, /* tp_dict */
1011 0, /* tp_descr_get */
1012 0, /* tp_descr_set */
1013 0, /* tp_dictoffset */
1014 (initproc)deque_init, /* tp_init */
1015 PyType_GenericAlloc, /* tp_alloc */
1016 deque_new, /* tp_new */
1017 PyObject_GC_Del, /* tp_free */
1018};
1019
1020/*********************** Deque Iterator **************************/
1021
1022typedef struct {
1023 PyObject_HEAD
Raymond Hettinger33fcf9d2008-07-24 00:08:18 +00001024 Py_ssize_t index;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001025 block *b;
1026 dequeobject *deque;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001027 long state; /* state when the iterator is created */
Raymond Hettinger33fcf9d2008-07-24 00:08:18 +00001028 Py_ssize_t counter; /* number of items remaining for iteration */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001029} dequeiterobject;
1030
Martin v. Löwis111c1802008-06-13 07:47:47 +00001031static PyTypeObject dequeiter_type;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001032
1033static PyObject *
1034deque_iter(dequeobject *deque)
1035{
1036 dequeiterobject *it;
1037
Antoine Pitrouaa687902009-01-01 14:11:22 +00001038 it = PyObject_GC_New(dequeiterobject, &dequeiter_type);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001039 if (it == NULL)
1040 return NULL;
1041 it->b = deque->leftblock;
1042 it->index = deque->leftindex;
1043 Py_INCREF(deque);
1044 it->deque = deque;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001045 it->state = deque->state;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001046 it->counter = deque->len;
Amaury Forgeot d'Arc57eb0e92009-01-02 00:03:54 +00001047 PyObject_GC_Track(it);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001048 return (PyObject *)it;
1049}
1050
Antoine Pitrouaa687902009-01-01 14:11:22 +00001051static int
1052dequeiter_traverse(dequeiterobject *dio, visitproc visit, void *arg)
1053{
1054 Py_VISIT(dio->deque);
1055 return 0;
1056}
1057
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001058static void
1059dequeiter_dealloc(dequeiterobject *dio)
1060{
1061 Py_XDECREF(dio->deque);
Antoine Pitrouaa687902009-01-01 14:11:22 +00001062 PyObject_GC_Del(dio);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001063}
1064
1065static PyObject *
1066dequeiter_next(dequeiterobject *it)
1067{
1068 PyObject *item;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001069
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001070 if (it->deque->state != it->state) {
Raymond Hettinger7892b1c2004-04-12 18:10:01 +00001071 it->counter = 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001072 PyErr_SetString(PyExc_RuntimeError,
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001073 "deque mutated during iteration");
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001074 return NULL;
1075 }
Raymond Hettinger51c2f6c2007-01-08 18:09:20 +00001076 if (it->counter == 0)
1077 return NULL;
Tim Peters5566e962006-07-28 00:23:15 +00001078 assert (!(it->b == it->deque->rightblock &&
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001079 it->index > it->deque->rightindex));
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001080
1081 item = it->b->data[it->index];
1082 it->index++;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001083 it->counter--;
1084 if (it->index == BLOCKLEN && it->counter > 0) {
1085 assert (it->b->rightlink != NULL);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001086 it->b = it->b->rightlink;
1087 it->index = 0;
1088 }
1089 Py_INCREF(item);
1090 return item;
1091}
1092
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001093static PyObject *
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001094dequeiter_len(dequeiterobject *it)
1095{
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001096 return PyInt_FromLong(it->counter);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001097}
1098
Armin Rigof5b3e362006-02-11 21:32:43 +00001099PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001100
1101static PyMethodDef dequeiter_methods[] = {
Armin Rigof5b3e362006-02-11 21:32:43 +00001102 {"__length_hint__", (PyCFunction)dequeiter_len, METH_NOARGS, length_hint_doc},
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001103 {NULL, NULL} /* sentinel */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001104};
1105
Martin v. Löwis111c1802008-06-13 07:47:47 +00001106static PyTypeObject dequeiter_type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00001107 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001108 "deque_iterator", /* tp_name */
1109 sizeof(dequeiterobject), /* tp_basicsize */
1110 0, /* tp_itemsize */
1111 /* methods */
1112 (destructor)dequeiter_dealloc, /* tp_dealloc */
1113 0, /* tp_print */
1114 0, /* tp_getattr */
1115 0, /* tp_setattr */
1116 0, /* tp_compare */
1117 0, /* tp_repr */
1118 0, /* tp_as_number */
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001119 0, /* tp_as_sequence */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001120 0, /* tp_as_mapping */
1121 0, /* tp_hash */
1122 0, /* tp_call */
1123 0, /* tp_str */
1124 PyObject_GenericGetAttr, /* tp_getattro */
1125 0, /* tp_setattro */
1126 0, /* tp_as_buffer */
Antoine Pitrouaa687902009-01-01 14:11:22 +00001127 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001128 0, /* tp_doc */
Antoine Pitrouaa687902009-01-01 14:11:22 +00001129 (traverseproc)dequeiter_traverse, /* tp_traverse */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001130 0, /* tp_clear */
1131 0, /* tp_richcompare */
1132 0, /* tp_weaklistoffset */
1133 PyObject_SelfIter, /* tp_iter */
1134 (iternextfunc)dequeiter_next, /* tp_iternext */
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001135 dequeiter_methods, /* tp_methods */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001136 0,
1137};
1138
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001139/*********************** Deque Reverse Iterator **************************/
1140
Martin v. Löwis111c1802008-06-13 07:47:47 +00001141static PyTypeObject dequereviter_type;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001142
1143static PyObject *
1144deque_reviter(dequeobject *deque)
1145{
1146 dequeiterobject *it;
1147
Antoine Pitrouaa687902009-01-01 14:11:22 +00001148 it = PyObject_GC_New(dequeiterobject, &dequereviter_type);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001149 if (it == NULL)
1150 return NULL;
1151 it->b = deque->rightblock;
1152 it->index = deque->rightindex;
1153 Py_INCREF(deque);
1154 it->deque = deque;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001155 it->state = deque->state;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001156 it->counter = deque->len;
Amaury Forgeot d'Arc57eb0e92009-01-02 00:03:54 +00001157 PyObject_GC_Track(it);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001158 return (PyObject *)it;
1159}
1160
1161static PyObject *
1162dequereviter_next(dequeiterobject *it)
1163{
1164 PyObject *item;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001165 if (it->counter == 0)
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001166 return NULL;
1167
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001168 if (it->deque->state != it->state) {
Raymond Hettinger7892b1c2004-04-12 18:10:01 +00001169 it->counter = 0;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001170 PyErr_SetString(PyExc_RuntimeError,
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001171 "deque mutated during iteration");
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001172 return NULL;
1173 }
Tim Peters5566e962006-07-28 00:23:15 +00001174 assert (!(it->b == it->deque->leftblock &&
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001175 it->index < it->deque->leftindex));
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001176
1177 item = it->b->data[it->index];
1178 it->index--;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001179 it->counter--;
1180 if (it->index == -1 && it->counter > 0) {
1181 assert (it->b->leftlink != NULL);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001182 it->b = it->b->leftlink;
1183 it->index = BLOCKLEN - 1;
1184 }
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001185 Py_INCREF(item);
1186 return item;
1187}
1188
Martin v. Löwis111c1802008-06-13 07:47:47 +00001189static PyTypeObject dequereviter_type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00001190 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001191 "deque_reverse_iterator", /* tp_name */
1192 sizeof(dequeiterobject), /* tp_basicsize */
1193 0, /* tp_itemsize */
1194 /* methods */
1195 (destructor)dequeiter_dealloc, /* tp_dealloc */
1196 0, /* tp_print */
1197 0, /* tp_getattr */
1198 0, /* tp_setattr */
1199 0, /* tp_compare */
1200 0, /* tp_repr */
1201 0, /* tp_as_number */
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001202 0, /* tp_as_sequence */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001203 0, /* tp_as_mapping */
1204 0, /* tp_hash */
1205 0, /* tp_call */
1206 0, /* tp_str */
1207 PyObject_GenericGetAttr, /* tp_getattro */
1208 0, /* tp_setattro */
1209 0, /* tp_as_buffer */
Antoine Pitrouaa687902009-01-01 14:11:22 +00001210 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001211 0, /* tp_doc */
Antoine Pitrouaa687902009-01-01 14:11:22 +00001212 (traverseproc)dequeiter_traverse, /* tp_traverse */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001213 0, /* tp_clear */
1214 0, /* tp_richcompare */
1215 0, /* tp_weaklistoffset */
1216 PyObject_SelfIter, /* tp_iter */
1217 (iternextfunc)dequereviter_next, /* tp_iternext */
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001218 dequeiter_methods, /* tp_methods */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001219 0,
1220};
1221
Guido van Rossum1968ad32006-02-25 22:38:04 +00001222/* defaultdict type *********************************************************/
1223
1224typedef struct {
1225 PyDictObject dict;
1226 PyObject *default_factory;
1227} defdictobject;
1228
1229static PyTypeObject defdict_type; /* Forward */
1230
1231PyDoc_STRVAR(defdict_missing_doc,
1232"__missing__(key) # Called by __getitem__ for missing key; pseudo-code:\n\
Georg Brandlb51a57e2007-03-06 13:32:52 +00001233 if self.default_factory is None: raise KeyError((key,))\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00001234 self[key] = value = self.default_factory()\n\
1235 return value\n\
1236");
1237
1238static PyObject *
1239defdict_missing(defdictobject *dd, PyObject *key)
1240{
1241 PyObject *factory = dd->default_factory;
1242 PyObject *value;
1243 if (factory == NULL || factory == Py_None) {
1244 /* XXX Call dict.__missing__(key) */
Georg Brandlb51a57e2007-03-06 13:32:52 +00001245 PyObject *tup;
1246 tup = PyTuple_Pack(1, key);
1247 if (!tup) return NULL;
1248 PyErr_SetObject(PyExc_KeyError, tup);
1249 Py_DECREF(tup);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001250 return NULL;
1251 }
1252 value = PyEval_CallObject(factory, NULL);
1253 if (value == NULL)
1254 return value;
1255 if (PyObject_SetItem((PyObject *)dd, key, value) < 0) {
1256 Py_DECREF(value);
1257 return NULL;
1258 }
1259 return value;
1260}
1261
1262PyDoc_STRVAR(defdict_copy_doc, "D.copy() -> a shallow copy of D.");
1263
1264static PyObject *
1265defdict_copy(defdictobject *dd)
1266{
1267 /* This calls the object's class. That only works for subclasses
1268 whose class constructor has the same signature. Subclasses that
Raymond Hettingera37430a2008-02-12 19:05:36 +00001269 define a different constructor signature must override copy().
Guido van Rossum1968ad32006-02-25 22:38:04 +00001270 */
Raymond Hettinger8fdab952009-08-04 19:08:05 +00001271
1272 if (dd->default_factory == NULL)
1273 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd), Py_None, dd, NULL);
Christian Heimese93237d2007-12-19 02:37:44 +00001274 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd),
Guido van Rossum1968ad32006-02-25 22:38:04 +00001275 dd->default_factory, dd, NULL);
1276}
1277
1278static PyObject *
1279defdict_reduce(defdictobject *dd)
1280{
Tim Peters5566e962006-07-28 00:23:15 +00001281 /* __reduce__ must return a 5-tuple as follows:
Guido van Rossum1968ad32006-02-25 22:38:04 +00001282
1283 - factory function
1284 - tuple of args for the factory function
1285 - additional state (here None)
1286 - sequence iterator (here None)
1287 - dictionary iterator (yielding successive (key, value) pairs
1288
1289 This API is used by pickle.py and copy.py.
1290
1291 For this to be useful with pickle.py, the default_factory
1292 must be picklable; e.g., None, a built-in, or a global
1293 function in a module or package.
1294
1295 Both shallow and deep copying are supported, but for deep
1296 copying, the default_factory must be deep-copyable; e.g. None,
1297 or a built-in (functions are not copyable at this time).
1298
1299 This only works for subclasses as long as their constructor
1300 signature is compatible; the first argument must be the
1301 optional default_factory, defaulting to None.
1302 */
1303 PyObject *args;
1304 PyObject *items;
1305 PyObject *result;
1306 if (dd->default_factory == NULL || dd->default_factory == Py_None)
1307 args = PyTuple_New(0);
1308 else
1309 args = PyTuple_Pack(1, dd->default_factory);
1310 if (args == NULL)
1311 return NULL;
1312 items = PyObject_CallMethod((PyObject *)dd, "iteritems", "()");
1313 if (items == NULL) {
1314 Py_DECREF(args);
1315 return NULL;
1316 }
Christian Heimese93237d2007-12-19 02:37:44 +00001317 result = PyTuple_Pack(5, Py_TYPE(dd), args,
Guido van Rossum1968ad32006-02-25 22:38:04 +00001318 Py_None, Py_None, items);
Tim Peters5566e962006-07-28 00:23:15 +00001319 Py_DECREF(items);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001320 Py_DECREF(args);
1321 return result;
1322}
1323
1324static PyMethodDef defdict_methods[] = {
1325 {"__missing__", (PyCFunction)defdict_missing, METH_O,
1326 defdict_missing_doc},
Raymond Hettingera37430a2008-02-12 19:05:36 +00001327 {"copy", (PyCFunction)defdict_copy, METH_NOARGS,
Guido van Rossum1968ad32006-02-25 22:38:04 +00001328 defdict_copy_doc},
1329 {"__copy__", (PyCFunction)defdict_copy, METH_NOARGS,
1330 defdict_copy_doc},
1331 {"__reduce__", (PyCFunction)defdict_reduce, METH_NOARGS,
1332 reduce_doc},
1333 {NULL}
1334};
1335
1336static PyMemberDef defdict_members[] = {
1337 {"default_factory", T_OBJECT,
1338 offsetof(defdictobject, default_factory), 0,
1339 PyDoc_STR("Factory for default value called by __missing__().")},
1340 {NULL}
1341};
1342
1343static void
1344defdict_dealloc(defdictobject *dd)
1345{
1346 Py_CLEAR(dd->default_factory);
1347 PyDict_Type.tp_dealloc((PyObject *)dd);
1348}
1349
1350static int
1351defdict_print(defdictobject *dd, FILE *fp, int flags)
1352{
1353 int sts;
Raymond Hettinger556b43d2007-10-05 19:07:31 +00001354 Py_BEGIN_ALLOW_THREADS
Guido van Rossum1968ad32006-02-25 22:38:04 +00001355 fprintf(fp, "defaultdict(");
Raymond Hettinger556b43d2007-10-05 19:07:31 +00001356 Py_END_ALLOW_THREADS
1357 if (dd->default_factory == NULL) {
1358 Py_BEGIN_ALLOW_THREADS
Guido van Rossum1968ad32006-02-25 22:38:04 +00001359 fprintf(fp, "None");
Raymond Hettinger556b43d2007-10-05 19:07:31 +00001360 Py_END_ALLOW_THREADS
1361 } else {
Guido van Rossum1968ad32006-02-25 22:38:04 +00001362 PyObject_Print(dd->default_factory, fp, 0);
1363 }
Raymond Hettinger556b43d2007-10-05 19:07:31 +00001364 Py_BEGIN_ALLOW_THREADS
Guido van Rossum1968ad32006-02-25 22:38:04 +00001365 fprintf(fp, ", ");
Raymond Hettinger556b43d2007-10-05 19:07:31 +00001366 Py_END_ALLOW_THREADS
Guido van Rossum1968ad32006-02-25 22:38:04 +00001367 sts = PyDict_Type.tp_print((PyObject *)dd, fp, 0);
Raymond Hettinger556b43d2007-10-05 19:07:31 +00001368 Py_BEGIN_ALLOW_THREADS
Guido van Rossum1968ad32006-02-25 22:38:04 +00001369 fprintf(fp, ")");
Raymond Hettinger556b43d2007-10-05 19:07:31 +00001370 Py_END_ALLOW_THREADS
Guido van Rossum1968ad32006-02-25 22:38:04 +00001371 return sts;
1372}
1373
1374static PyObject *
1375defdict_repr(defdictobject *dd)
1376{
1377 PyObject *defrepr;
1378 PyObject *baserepr;
1379 PyObject *result;
1380 baserepr = PyDict_Type.tp_repr((PyObject *)dd);
1381 if (baserepr == NULL)
1382 return NULL;
1383 if (dd->default_factory == NULL)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001384 defrepr = PyString_FromString("None");
Guido van Rossum1968ad32006-02-25 22:38:04 +00001385 else
Amaury Forgeot d'Arcb01aa432008-02-08 00:56:02 +00001386 {
1387 int status = Py_ReprEnter(dd->default_factory);
1388 if (status != 0) {
1389 if (status < 0)
1390 return NULL;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001391 defrepr = PyString_FromString("...");
Amaury Forgeot d'Arcb01aa432008-02-08 00:56:02 +00001392 }
1393 else
1394 defrepr = PyObject_Repr(dd->default_factory);
1395 Py_ReprLeave(dd->default_factory);
1396 }
Guido van Rossum1968ad32006-02-25 22:38:04 +00001397 if (defrepr == NULL) {
1398 Py_DECREF(baserepr);
1399 return NULL;
1400 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001401 result = PyString_FromFormat("defaultdict(%s, %s)",
1402 PyString_AS_STRING(defrepr),
1403 PyString_AS_STRING(baserepr));
Guido van Rossum1968ad32006-02-25 22:38:04 +00001404 Py_DECREF(defrepr);
1405 Py_DECREF(baserepr);
1406 return result;
1407}
1408
1409static int
1410defdict_traverse(PyObject *self, visitproc visit, void *arg)
1411{
1412 Py_VISIT(((defdictobject *)self)->default_factory);
1413 return PyDict_Type.tp_traverse(self, visit, arg);
1414}
1415
1416static int
1417defdict_tp_clear(defdictobject *dd)
1418{
Thomas Woutersedf17d82006-04-15 17:28:34 +00001419 Py_CLEAR(dd->default_factory);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001420 return PyDict_Type.tp_clear((PyObject *)dd);
1421}
1422
1423static int
1424defdict_init(PyObject *self, PyObject *args, PyObject *kwds)
1425{
1426 defdictobject *dd = (defdictobject *)self;
1427 PyObject *olddefault = dd->default_factory;
1428 PyObject *newdefault = NULL;
1429 PyObject *newargs;
1430 int result;
1431 if (args == NULL || !PyTuple_Check(args))
1432 newargs = PyTuple_New(0);
1433 else {
1434 Py_ssize_t n = PyTuple_GET_SIZE(args);
Raymond Hettinger5a0217e2007-02-07 21:42:17 +00001435 if (n > 0) {
Guido van Rossum1968ad32006-02-25 22:38:04 +00001436 newdefault = PyTuple_GET_ITEM(args, 0);
Raymond Hettinger8fdab952009-08-04 19:08:05 +00001437 if (!PyCallable_Check(newdefault) && newdefault != Py_None) {
Raymond Hettinger5a0217e2007-02-07 21:42:17 +00001438 PyErr_SetString(PyExc_TypeError,
1439 "first argument must be callable");
1440 return -1;
1441 }
1442 }
Guido van Rossum1968ad32006-02-25 22:38:04 +00001443 newargs = PySequence_GetSlice(args, 1, n);
1444 }
1445 if (newargs == NULL)
1446 return -1;
1447 Py_XINCREF(newdefault);
1448 dd->default_factory = newdefault;
1449 result = PyDict_Type.tp_init(self, newargs, kwds);
1450 Py_DECREF(newargs);
1451 Py_XDECREF(olddefault);
1452 return result;
1453}
1454
1455PyDoc_STRVAR(defdict_doc,
1456"defaultdict(default_factory) --> dict with default factory\n\
1457\n\
1458The default factory is called without arguments to produce\n\
1459a new value when a key is not present, in __getitem__ only.\n\
1460A defaultdict compares equal to a dict with the same items.\n\
1461");
1462
Anthony Baxter3b8ff312006-04-04 15:05:23 +00001463/* See comment in xxsubtype.c */
1464#define DEFERRED_ADDRESS(ADDR) 0
1465
Guido van Rossum1968ad32006-02-25 22:38:04 +00001466static PyTypeObject defdict_type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00001467 PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0)
Guido van Rossum1968ad32006-02-25 22:38:04 +00001468 "collections.defaultdict", /* tp_name */
1469 sizeof(defdictobject), /* tp_basicsize */
1470 0, /* tp_itemsize */
1471 /* methods */
1472 (destructor)defdict_dealloc, /* tp_dealloc */
1473 (printfunc)defdict_print, /* tp_print */
1474 0, /* tp_getattr */
1475 0, /* tp_setattr */
1476 0, /* tp_compare */
1477 (reprfunc)defdict_repr, /* tp_repr */
1478 0, /* tp_as_number */
1479 0, /* tp_as_sequence */
1480 0, /* tp_as_mapping */
1481 0, /* tp_hash */
1482 0, /* tp_call */
1483 0, /* tp_str */
1484 PyObject_GenericGetAttr, /* tp_getattro */
1485 0, /* tp_setattro */
1486 0, /* tp_as_buffer */
1487 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
1488 Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
1489 defdict_doc, /* tp_doc */
Georg Brandld37ac692006-03-30 11:58:57 +00001490 defdict_traverse, /* tp_traverse */
Guido van Rossum1968ad32006-02-25 22:38:04 +00001491 (inquiry)defdict_tp_clear, /* tp_clear */
1492 0, /* tp_richcompare */
1493 0, /* tp_weaklistoffset*/
1494 0, /* tp_iter */
1495 0, /* tp_iternext */
1496 defdict_methods, /* tp_methods */
1497 defdict_members, /* tp_members */
1498 0, /* tp_getset */
Anthony Baxter3b8ff312006-04-04 15:05:23 +00001499 DEFERRED_ADDRESS(&PyDict_Type), /* tp_base */
Guido van Rossum1968ad32006-02-25 22:38:04 +00001500 0, /* tp_dict */
1501 0, /* tp_descr_get */
1502 0, /* tp_descr_set */
1503 0, /* tp_dictoffset */
Georg Brandld37ac692006-03-30 11:58:57 +00001504 defdict_init, /* tp_init */
Guido van Rossum1968ad32006-02-25 22:38:04 +00001505 PyType_GenericAlloc, /* tp_alloc */
1506 0, /* tp_new */
1507 PyObject_GC_Del, /* tp_free */
1508};
1509
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001510/* module level code ********************************************************/
1511
1512PyDoc_STRVAR(module_doc,
Guido van Rossum1968ad32006-02-25 22:38:04 +00001513"High performance data structures.\n\
1514- deque: ordered collection accessible from endpoints only\n\
1515- defaultdict: dict subclass with a default value factory\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001516");
1517
1518PyMODINIT_FUNC
Raymond Hettingereb979882007-02-28 18:37:52 +00001519init_collections(void)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001520{
1521 PyObject *m;
1522
Raymond Hettingereb979882007-02-28 18:37:52 +00001523 m = Py_InitModule3("_collections", NULL, module_doc);
Neal Norwitz1ac754f2006-01-19 06:09:39 +00001524 if (m == NULL)
1525 return;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001526
1527 if (PyType_Ready(&deque_type) < 0)
1528 return;
1529 Py_INCREF(&deque_type);
1530 PyModule_AddObject(m, "deque", (PyObject *)&deque_type);
1531
Anthony Baxter3b8ff312006-04-04 15:05:23 +00001532 defdict_type.tp_base = &PyDict_Type;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001533 if (PyType_Ready(&defdict_type) < 0)
1534 return;
1535 Py_INCREF(&defdict_type);
1536 PyModule_AddObject(m, "defaultdict", (PyObject *)&defdict_type);
1537
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001538 if (PyType_Ready(&dequeiter_type) < 0)
Tim Peters1065f752004-10-01 01:03:29 +00001539 return;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001540
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001541 if (PyType_Ready(&dequereviter_type) < 0)
1542 return;
1543
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001544 return;
1545}