blob: 1873cabc5b6b7e352565fd7618cef7d9e081e1f1 [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
301 it = PyObject_GetIter(iterable);
302 if (it == NULL)
303 return NULL;
304
Raymond Hettingerbac769b2009-03-10 09:31:48 +0000305 if (deque->maxlen == 0)
306 return consume_iterator(it);
307
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000308 while ((item = PyIter_Next(it)) != NULL) {
Raymond Hettingerd1b3d882004-10-02 00:43:13 +0000309 deque->state++;
Armin Rigo974d7572004-10-02 13:59:34 +0000310 if (deque->rightindex == BLOCKLEN-1) {
Raymond Hettingerc5fa9922004-10-06 17:51:54 +0000311 block *b = newblock(deque->rightblock, NULL,
312 deque->len);
Raymond Hettingerc058fd12004-02-07 02:45:22 +0000313 if (b == NULL) {
314 Py_DECREF(item);
315 Py_DECREF(it);
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000316 return NULL;
Raymond Hettingerc058fd12004-02-07 02:45:22 +0000317 }
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000318 assert(deque->rightblock->rightlink == NULL);
319 deque->rightblock->rightlink = b;
320 deque->rightblock = b;
Armin Rigo974d7572004-10-02 13:59:34 +0000321 deque->rightindex = -1;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000322 }
Armin Rigo974d7572004-10-02 13:59:34 +0000323 deque->len++;
324 deque->rightindex++;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000325 deque->rightblock->data[deque->rightindex] = item;
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000326 TRIM(deque, deque_popleft);
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000327 }
328 Py_DECREF(it);
Tim Peters1065f752004-10-01 01:03:29 +0000329 if (PyErr_Occurred())
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000330 return NULL;
331 Py_RETURN_NONE;
332}
333
Tim Peters1065f752004-10-01 01:03:29 +0000334PyDoc_STRVAR(extend_doc,
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000335"Extend the right side of the deque with elements from the iterable");
336
337static PyObject *
338deque_extendleft(dequeobject *deque, PyObject *iterable)
339{
340 PyObject *it, *item;
341
342 it = PyObject_GetIter(iterable);
343 if (it == NULL)
344 return NULL;
345
Raymond Hettingerbac769b2009-03-10 09:31:48 +0000346 if (deque->maxlen == 0)
347 return consume_iterator(it);
348
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000349 while ((item = PyIter_Next(it)) != NULL) {
Raymond Hettingerd1b3d882004-10-02 00:43:13 +0000350 deque->state++;
Armin Rigo974d7572004-10-02 13:59:34 +0000351 if (deque->leftindex == 0) {
Raymond Hettingerc5fa9922004-10-06 17:51:54 +0000352 block *b = newblock(NULL, deque->leftblock,
353 deque->len);
Raymond Hettingerc058fd12004-02-07 02:45:22 +0000354 if (b == NULL) {
355 Py_DECREF(item);
356 Py_DECREF(it);
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000357 return NULL;
Raymond Hettingerc058fd12004-02-07 02:45:22 +0000358 }
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000359 assert(deque->leftblock->leftlink == NULL);
360 deque->leftblock->leftlink = b;
361 deque->leftblock = b;
Armin Rigo974d7572004-10-02 13:59:34 +0000362 deque->leftindex = BLOCKLEN;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000363 }
Armin Rigo974d7572004-10-02 13:59:34 +0000364 deque->len++;
365 deque->leftindex--;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000366 deque->leftblock->data[deque->leftindex] = item;
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000367 TRIM(deque, deque_pop);
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000368 }
369 Py_DECREF(it);
Raymond Hettingera435c532004-07-09 04:10:20 +0000370 if (PyErr_Occurred())
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000371 return NULL;
372 Py_RETURN_NONE;
373}
374
Tim Peters1065f752004-10-01 01:03:29 +0000375PyDoc_STRVAR(extendleft_doc,
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000376"Extend the left side of the deque with elements from the iterable");
377
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000378static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000379_deque_rotate(dequeobject *deque, Py_ssize_t n)
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000380{
Raymond Hettinger33fcf9d2008-07-24 00:08:18 +0000381 Py_ssize_t i, len=deque->len, halflen=(len+1)>>1;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000382 PyObject *item, *rv;
383
Raymond Hettingeree33b272004-02-08 04:05:26 +0000384 if (len == 0)
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000385 return 0;
Raymond Hettingeree33b272004-02-08 04:05:26 +0000386 if (n > halflen || n < -halflen) {
387 n %= len;
388 if (n > halflen)
389 n -= len;
390 else if (n < -halflen)
391 n += len;
392 }
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000393
394 for (i=0 ; i<n ; i++) {
395 item = deque_pop(deque, NULL);
Raymond Hettingera435c532004-07-09 04:10:20 +0000396 assert (item != NULL);
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000397 rv = deque_appendleft(deque, item);
398 Py_DECREF(item);
399 if (rv == NULL)
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000400 return -1;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000401 Py_DECREF(rv);
402 }
403 for (i=0 ; i>n ; i--) {
404 item = deque_popleft(deque, NULL);
Raymond Hettingera435c532004-07-09 04:10:20 +0000405 assert (item != NULL);
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000406 rv = deque_append(deque, item);
407 Py_DECREF(item);
408 if (rv == NULL)
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000409 return -1;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000410 Py_DECREF(rv);
411 }
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000412 return 0;
413}
414
415static PyObject *
416deque_rotate(dequeobject *deque, PyObject *args)
417{
Raymond Hettinger33fcf9d2008-07-24 00:08:18 +0000418 Py_ssize_t n=1;
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000419
Raymond Hettinger723ba302008-07-24 00:53:49 +0000420 if (!PyArg_ParseTuple(args, "|n:rotate", &n))
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000421 return NULL;
422 if (_deque_rotate(deque, n) == 0)
423 Py_RETURN_NONE;
424 return NULL;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000425}
426
Tim Peters1065f752004-10-01 01:03:29 +0000427PyDoc_STRVAR(rotate_doc,
Raymond Hettingeree33b272004-02-08 04:05:26 +0000428"Rotate the deque n steps to the right (default n=1). If n is negative, rotates left.");
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000429
Martin v. Löwis18e16552006-02-15 17:27:45 +0000430static Py_ssize_t
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000431deque_len(dequeobject *deque)
432{
433 return deque->len;
434}
435
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000436static PyObject *
437deque_remove(dequeobject *deque, PyObject *value)
438{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000439 Py_ssize_t i, n=deque->len;
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000440
441 for (i=0 ; i<n ; i++) {
442 PyObject *item = deque->leftblock->data[deque->leftindex];
443 int cmp = PyObject_RichCompareBool(item, value, Py_EQ);
Raymond Hettingerd73202c2005-03-19 00:00:51 +0000444
445 if (deque->len != n) {
Tim Peters5566e962006-07-28 00:23:15 +0000446 PyErr_SetString(PyExc_IndexError,
Raymond Hettingerd73202c2005-03-19 00:00:51 +0000447 "deque mutated during remove().");
448 return NULL;
449 }
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000450 if (cmp > 0) {
Raymond Hettingerd73202c2005-03-19 00:00:51 +0000451 PyObject *tgt = deque_popleft(deque, NULL);
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000452 assert (tgt != NULL);
453 Py_DECREF(tgt);
454 if (_deque_rotate(deque, i) == -1)
455 return NULL;
456 Py_RETURN_NONE;
457 }
458 else if (cmp < 0) {
459 _deque_rotate(deque, i);
460 return NULL;
461 }
462 _deque_rotate(deque, -1);
463 }
464 PyErr_SetString(PyExc_ValueError, "deque.remove(x): x not in deque");
465 return NULL;
466}
467
468PyDoc_STRVAR(remove_doc,
469"D.remove(value) -- remove first occurrence of value.");
470
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000471static int
472deque_clear(dequeobject *deque)
473{
474 PyObject *item;
475
Raymond Hettingerd1b3d882004-10-02 00:43:13 +0000476 while (deque->len) {
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000477 item = deque_pop(deque, NULL);
Raymond Hettingera435c532004-07-09 04:10:20 +0000478 assert (item != NULL);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000479 Py_DECREF(item);
480 }
481 assert(deque->leftblock == deque->rightblock &&
Raymond Hettingerd1b3d882004-10-02 00:43:13 +0000482 deque->leftindex - 1 == deque->rightindex &&
483 deque->len == 0);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000484 return 0;
485}
486
487static PyObject *
Raymond Hettinger33fcf9d2008-07-24 00:08:18 +0000488deque_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000489{
490 block *b;
491 PyObject *item;
Raymond Hettinger33fcf9d2008-07-24 00:08:18 +0000492 Py_ssize_t n, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000493
494 if (i < 0 || i >= deque->len) {
495 PyErr_SetString(PyExc_IndexError,
496 "deque index out of range");
497 return NULL;
498 }
499
Raymond Hettinger6c79a512004-03-04 08:00:54 +0000500 if (i == 0) {
501 i = deque->leftindex;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000502 b = deque->leftblock;
Raymond Hettinger6c79a512004-03-04 08:00:54 +0000503 } else if (i == deque->len - 1) {
504 i = deque->rightindex;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000505 b = deque->rightblock;
Raymond Hettinger6c79a512004-03-04 08:00:54 +0000506 } else {
507 i += deque->leftindex;
508 n = i / BLOCKLEN;
509 i %= BLOCKLEN;
Armin Rigo974d7572004-10-02 13:59:34 +0000510 if (index < (deque->len >> 1)) {
Raymond Hettinger6c79a512004-03-04 08:00:54 +0000511 b = deque->leftblock;
512 while (n--)
513 b = b->rightlink;
514 } else {
515 n = (deque->leftindex + deque->len - 1) / BLOCKLEN - n;
516 b = deque->rightblock;
517 while (n--)
518 b = b->leftlink;
519 }
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000520 }
521 item = b->data[i];
522 Py_INCREF(item);
523 return item;
524}
525
Raymond Hettinger616f4f62004-06-26 04:42:06 +0000526/* delitem() implemented in terms of rotate for simplicity and reasonable
527 performance near the end points. If for some reason this method becomes
Tim Peters1065f752004-10-01 01:03:29 +0000528 popular, it is not hard to re-implement this using direct data movement
Raymond Hettinger616f4f62004-06-26 04:42:06 +0000529 (similar to code in list slice assignment) and achieve a two or threefold
530 performance boost.
531*/
532
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000533static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000534deque_del_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000535{
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000536 PyObject *item;
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000537
Tim Peters1065f752004-10-01 01:03:29 +0000538 assert (i >= 0 && i < deque->len);
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000539 if (_deque_rotate(deque, -i) == -1)
540 return -1;
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000541
542 item = deque_popleft(deque, NULL);
Raymond Hettingera435c532004-07-09 04:10:20 +0000543 assert (item != NULL);
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000544 Py_DECREF(item);
545
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000546 return _deque_rotate(deque, i);
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000547}
548
549static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000550deque_ass_item(dequeobject *deque, Py_ssize_t i, PyObject *v)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000551{
552 PyObject *old_value;
553 block *b;
Martin v. Löwisad0a4622006-02-16 14:30:23 +0000554 Py_ssize_t n, len=deque->len, halflen=(len+1)>>1, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000555
Raymond Hettingera435c532004-07-09 04:10:20 +0000556 if (i < 0 || i >= len) {
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000557 PyErr_SetString(PyExc_IndexError,
558 "deque index out of range");
559 return -1;
560 }
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000561 if (v == NULL)
562 return deque_del_item(deque, i);
563
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000564 i += deque->leftindex;
565 n = i / BLOCKLEN;
566 i %= BLOCKLEN;
Raymond Hettingera435c532004-07-09 04:10:20 +0000567 if (index <= halflen) {
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000568 b = deque->leftblock;
569 while (n--)
570 b = b->rightlink;
571 } else {
Raymond Hettingera435c532004-07-09 04:10:20 +0000572 n = (deque->leftindex + len - 1) / BLOCKLEN - n;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000573 b = deque->rightblock;
574 while (n--)
575 b = b->leftlink;
576 }
577 Py_INCREF(v);
578 old_value = b->data[i];
579 b->data[i] = v;
580 Py_DECREF(old_value);
581 return 0;
582}
583
584static PyObject *
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000585deque_clearmethod(dequeobject *deque)
586{
Raymond Hettingera435c532004-07-09 04:10:20 +0000587 int rv;
588
589 rv = deque_clear(deque);
590 assert (rv != -1);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000591 Py_RETURN_NONE;
592}
593
594PyDoc_STRVAR(clear_doc, "Remove all elements from the deque.");
595
596static void
597deque_dealloc(dequeobject *deque)
598{
599 PyObject_GC_UnTrack(deque);
Raymond Hettinger691d8052004-05-30 07:26:47 +0000600 if (deque->weakreflist != NULL)
601 PyObject_ClearWeakRefs((PyObject *) deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000602 if (deque->leftblock != NULL) {
Raymond Hettingere9c89e82004-07-19 00:10:24 +0000603 deque_clear(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000604 assert(deque->leftblock != NULL);
Raymond Hettingerd3ffd342007-11-10 01:54:03 +0000605 freeblock(deque->leftblock);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000606 }
607 deque->leftblock = NULL;
608 deque->rightblock = NULL;
Christian Heimese93237d2007-12-19 02:37:44 +0000609 Py_TYPE(deque)->tp_free(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000610}
611
612static int
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000613deque_traverse(dequeobject *deque, visitproc visit, void *arg)
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000614{
Tim Peters10c7e862004-10-01 02:01:04 +0000615 block *b;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000616 PyObject *item;
Raymond Hettinger33fcf9d2008-07-24 00:08:18 +0000617 Py_ssize_t index;
618 Py_ssize_t indexlo = deque->leftindex;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000619
Tim Peters10c7e862004-10-01 02:01:04 +0000620 for (b = deque->leftblock; b != NULL; b = b->rightlink) {
Raymond Hettinger33fcf9d2008-07-24 00:08:18 +0000621 const Py_ssize_t indexhi = b == deque->rightblock ?
Tim Peters10c7e862004-10-01 02:01:04 +0000622 deque->rightindex :
623 BLOCKLEN - 1;
624
625 for (index = indexlo; index <= indexhi; ++index) {
626 item = b->data[index];
627 Py_VISIT(item);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000628 }
Tim Peters10c7e862004-10-01 02:01:04 +0000629 indexlo = 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000630 }
631 return 0;
632}
633
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000634static PyObject *
635deque_copy(PyObject *deque)
636{
Raymond Hettinger68995862007-10-10 00:26:46 +0000637 if (((dequeobject *)deque)->maxlen == -1)
Christian Heimese93237d2007-12-19 02:37:44 +0000638 return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "O", deque, NULL);
Raymond Hettinger68995862007-10-10 00:26:46 +0000639 else
Christian Heimese93237d2007-12-19 02:37:44 +0000640 return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "Oi",
Raymond Hettinger68995862007-10-10 00:26:46 +0000641 deque, ((dequeobject *)deque)->maxlen, NULL);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000642}
643
644PyDoc_STRVAR(copy_doc, "Return a shallow copy of a deque.");
645
646static PyObject *
647deque_reduce(dequeobject *deque)
648{
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000649 PyObject *dict, *result, *aslist;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000650
Raymond Hettinger952f8802004-11-09 07:27:35 +0000651 dict = PyObject_GetAttrString((PyObject *)deque, "__dict__");
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000652 if (dict == NULL)
Raymond Hettinger952f8802004-11-09 07:27:35 +0000653 PyErr_Clear();
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000654 aslist = PySequence_List((PyObject *)deque);
655 if (aslist == NULL) {
Neal Norwitzc47cf7d2007-10-05 03:39:17 +0000656 Py_XDECREF(dict);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000657 return NULL;
658 }
Raymond Hettinger68995862007-10-10 00:26:46 +0000659 if (dict == NULL) {
660 if (deque->maxlen == -1)
Christian Heimese93237d2007-12-19 02:37:44 +0000661 result = Py_BuildValue("O(O)", Py_TYPE(deque), aslist);
Raymond Hettinger68995862007-10-10 00:26:46 +0000662 else
Raymond Hettinger33fcf9d2008-07-24 00:08:18 +0000663 result = Py_BuildValue("O(On)", Py_TYPE(deque), aslist, deque->maxlen);
Raymond Hettinger68995862007-10-10 00:26:46 +0000664 } else {
665 if (deque->maxlen == -1)
Christian Heimese93237d2007-12-19 02:37:44 +0000666 result = Py_BuildValue("O(OO)O", Py_TYPE(deque), aslist, Py_None, dict);
Raymond Hettinger68995862007-10-10 00:26:46 +0000667 else
Raymond Hettinger33fcf9d2008-07-24 00:08:18 +0000668 result = Py_BuildValue("O(On)O", Py_TYPE(deque), aslist, deque->maxlen, dict);
Raymond Hettinger68995862007-10-10 00:26:46 +0000669 }
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000670 Py_XDECREF(dict);
671 Py_DECREF(aslist);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000672 return result;
673}
674
675PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
676
677static PyObject *
678deque_repr(PyObject *deque)
679{
Raymond Hettinger556b43d2007-10-05 19:07:31 +0000680 PyObject *aslist, *result, *fmt;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000681 int i;
682
683 i = Py_ReprEnter(deque);
684 if (i != 0) {
685 if (i < 0)
686 return NULL;
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000687 return PyString_FromString("[...]");
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000688 }
689
690 aslist = PySequence_List(deque);
691 if (aslist == NULL) {
692 Py_ReprLeave(deque);
693 return NULL;
694 }
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000695 if (((dequeobject *)deque)->maxlen != -1)
Amaury Forgeot d'Arc05e34492008-09-10 22:04:45 +0000696 fmt = PyString_FromFormat("deque(%%r, maxlen=%zd)",
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000697 ((dequeobject *)deque)->maxlen);
698 else
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000699 fmt = PyString_FromString("deque(%r)");
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000700 if (fmt == NULL) {
701 Py_DECREF(aslist);
702 Py_ReprLeave(deque);
703 return NULL;
704 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000705 result = PyString_Format(fmt, aslist);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000706 Py_DECREF(fmt);
707 Py_DECREF(aslist);
708 Py_ReprLeave(deque);
709 return result;
710}
711
712static int
713deque_tp_print(PyObject *deque, FILE *fp, int flags)
714{
715 PyObject *it, *item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000716 char *emit = ""; /* No separator emitted on first pass */
717 char *separator = ", ";
718 int i;
719
720 i = Py_ReprEnter(deque);
721 if (i != 0) {
722 if (i < 0)
723 return i;
Raymond Hettinger556b43d2007-10-05 19:07:31 +0000724 Py_BEGIN_ALLOW_THREADS
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000725 fputs("[...]", fp);
Raymond Hettinger556b43d2007-10-05 19:07:31 +0000726 Py_END_ALLOW_THREADS
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000727 return 0;
728 }
729
730 it = PyObject_GetIter(deque);
731 if (it == NULL)
732 return -1;
733
Raymond Hettinger556b43d2007-10-05 19:07:31 +0000734 Py_BEGIN_ALLOW_THREADS
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000735 fputs("deque([", fp);
Raymond Hettinger556b43d2007-10-05 19:07:31 +0000736 Py_END_ALLOW_THREADS
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000737 while ((item = PyIter_Next(it)) != NULL) {
Raymond Hettinger556b43d2007-10-05 19:07:31 +0000738 Py_BEGIN_ALLOW_THREADS
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000739 fputs(emit, fp);
Raymond Hettinger556b43d2007-10-05 19:07:31 +0000740 Py_END_ALLOW_THREADS
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000741 emit = separator;
742 if (PyObject_Print(item, fp, 0) != 0) {
743 Py_DECREF(item);
744 Py_DECREF(it);
745 Py_ReprLeave(deque);
746 return -1;
747 }
748 Py_DECREF(item);
749 }
750 Py_ReprLeave(deque);
751 Py_DECREF(it);
Tim Peters1065f752004-10-01 01:03:29 +0000752 if (PyErr_Occurred())
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000753 return -1;
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000754
Raymond Hettinger556b43d2007-10-05 19:07:31 +0000755 Py_BEGIN_ALLOW_THREADS
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000756 if (((dequeobject *)deque)->maxlen == -1)
757 fputs("])", fp);
758 else
Christian Heimes1cc69632008-08-22 20:10:27 +0000759 fprintf(fp, "], maxlen=%" PY_FORMAT_SIZE_T "d)", ((dequeobject *)deque)->maxlen);
Raymond Hettinger556b43d2007-10-05 19:07:31 +0000760 Py_END_ALLOW_THREADS
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000761 return 0;
762}
763
Raymond Hettinger738ec902004-02-29 02:15:56 +0000764static PyObject *
765deque_richcompare(PyObject *v, PyObject *w, int op)
766{
767 PyObject *it1=NULL, *it2=NULL, *x, *y;
Raymond Hettinger33fcf9d2008-07-24 00:08:18 +0000768 Py_ssize_t vs, ws;
769 int b, cmp=-1;
Raymond Hettinger738ec902004-02-29 02:15:56 +0000770
Tim Peters1065f752004-10-01 01:03:29 +0000771 if (!PyObject_TypeCheck(v, &deque_type) ||
Raymond Hettinger285cfcc2004-05-18 18:15:03 +0000772 !PyObject_TypeCheck(w, &deque_type)) {
Raymond Hettinger738ec902004-02-29 02:15:56 +0000773 Py_INCREF(Py_NotImplemented);
774 return Py_NotImplemented;
775 }
776
777 /* Shortcuts */
778 vs = ((dequeobject *)v)->len;
779 ws = ((dequeobject *)w)->len;
780 if (op == Py_EQ) {
781 if (v == w)
782 Py_RETURN_TRUE;
783 if (vs != ws)
784 Py_RETURN_FALSE;
785 }
786 if (op == Py_NE) {
787 if (v == w)
788 Py_RETURN_FALSE;
789 if (vs != ws)
790 Py_RETURN_TRUE;
791 }
792
793 /* Search for the first index where items are different */
794 it1 = PyObject_GetIter(v);
795 if (it1 == NULL)
796 goto done;
797 it2 = PyObject_GetIter(w);
798 if (it2 == NULL)
799 goto done;
Armin Rigo974d7572004-10-02 13:59:34 +0000800 for (;;) {
Raymond Hettinger738ec902004-02-29 02:15:56 +0000801 x = PyIter_Next(it1);
Armin Rigo974d7572004-10-02 13:59:34 +0000802 if (x == NULL && PyErr_Occurred())
Raymond Hettinger738ec902004-02-29 02:15:56 +0000803 goto done;
804 y = PyIter_Next(it2);
Armin Rigo974d7572004-10-02 13:59:34 +0000805 if (x == NULL || y == NULL)
806 break;
Raymond Hettinger738ec902004-02-29 02:15:56 +0000807 b = PyObject_RichCompareBool(x, y, Py_EQ);
808 if (b == 0) {
809 cmp = PyObject_RichCompareBool(x, y, op);
810 Py_DECREF(x);
811 Py_DECREF(y);
812 goto done;
813 }
814 Py_DECREF(x);
815 Py_DECREF(y);
816 if (b == -1)
817 goto done;
818 }
Armin Rigo974d7572004-10-02 13:59:34 +0000819 /* We reached the end of one deque or both */
820 Py_XDECREF(x);
821 Py_XDECREF(y);
822 if (PyErr_Occurred())
823 goto done;
Raymond Hettinger738ec902004-02-29 02:15:56 +0000824 switch (op) {
Armin Rigo974d7572004-10-02 13:59:34 +0000825 case Py_LT: cmp = y != NULL; break; /* if w was longer */
826 case Py_LE: cmp = x == NULL; break; /* if v was not longer */
827 case Py_EQ: cmp = x == y; break; /* if we reached the end of both */
828 case Py_NE: cmp = x != y; break; /* if one deque continues */
829 case Py_GT: cmp = x != NULL; break; /* if v was longer */
830 case Py_GE: cmp = y == NULL; break; /* if w was not longer */
Raymond Hettinger738ec902004-02-29 02:15:56 +0000831 }
Tim Peters1065f752004-10-01 01:03:29 +0000832
Raymond Hettinger738ec902004-02-29 02:15:56 +0000833done:
834 Py_XDECREF(it1);
835 Py_XDECREF(it2);
836 if (cmp == 1)
837 Py_RETURN_TRUE;
838 if (cmp == 0)
839 Py_RETURN_FALSE;
840 return NULL;
841}
842
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000843static int
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000844deque_init(dequeobject *deque, PyObject *args, PyObject *kwdargs)
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000845{
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000846 PyObject *iterable = NULL;
Raymond Hettinger68995862007-10-10 00:26:46 +0000847 PyObject *maxlenobj = NULL;
Raymond Hettinger33fcf9d2008-07-24 00:08:18 +0000848 Py_ssize_t maxlen = -1;
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000849 char *kwlist[] = {"iterable", "maxlen", 0};
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000850
Raymond Hettinger68995862007-10-10 00:26:46 +0000851 if (!PyArg_ParseTupleAndKeywords(args, kwdargs, "|OO:deque", kwlist, &iterable, &maxlenobj))
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000852 return -1;
Raymond Hettinger68995862007-10-10 00:26:46 +0000853 if (maxlenobj != NULL && maxlenobj != Py_None) {
Raymond Hettinger33fcf9d2008-07-24 00:08:18 +0000854 maxlen = PyInt_AsSsize_t(maxlenobj);
Raymond Hettinger68995862007-10-10 00:26:46 +0000855 if (maxlen == -1 && PyErr_Occurred())
856 return -1;
857 if (maxlen < 0) {
858 PyErr_SetString(PyExc_ValueError, "maxlen must be non-negative");
859 return -1;
860 }
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000861 }
862 deque->maxlen = maxlen;
Raymond Hettingeradf9ffd2007-12-13 00:08:37 +0000863 deque_clear(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000864 if (iterable != NULL) {
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000865 PyObject *rv = deque_extend(deque, iterable);
866 if (rv == NULL)
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000867 return -1;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000868 Py_DECREF(rv);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000869 }
870 return 0;
871}
872
Raymond Hettinger56411aa2009-03-10 12:50:59 +0000873static PyObject *
874deque_get_maxlen(dequeobject *deque)
875{
876 if (deque->maxlen == -1)
877 Py_RETURN_NONE;
878 return PyInt_FromSsize_t(deque->maxlen);
879}
880
881static PyGetSetDef deque_getset[] = {
882 {"maxlen", (getter)deque_get_maxlen, (setter)NULL,
883 "maximum size of a deque or None if unbounded"},
884 {0}
885};
886
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000887static PySequenceMethods deque_as_sequence = {
Martin v. Löwis18e16552006-02-15 17:27:45 +0000888 (lenfunc)deque_len, /* sq_length */
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000889 0, /* sq_concat */
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000890 0, /* sq_repeat */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000891 (ssizeargfunc)deque_item, /* sq_item */
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000892 0, /* sq_slice */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000893 (ssizeobjargproc)deque_ass_item, /* sq_ass_item */
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000894};
895
896/* deque object ********************************************************/
897
898static PyObject *deque_iter(dequeobject *deque);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +0000899static PyObject *deque_reviter(dequeobject *deque);
Tim Peters1065f752004-10-01 01:03:29 +0000900PyDoc_STRVAR(reversed_doc,
Raymond Hettinger1e5809f2004-03-18 11:04:57 +0000901 "D.__reversed__() -- return a reverse iterator over the deque");
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000902
903static PyMethodDef deque_methods[] = {
Tim Peters1065f752004-10-01 01:03:29 +0000904 {"append", (PyCFunction)deque_append,
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000905 METH_O, append_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000906 {"appendleft", (PyCFunction)deque_appendleft,
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000907 METH_O, appendleft_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000908 {"clear", (PyCFunction)deque_clearmethod,
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000909 METH_NOARGS, clear_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000910 {"__copy__", (PyCFunction)deque_copy,
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000911 METH_NOARGS, copy_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000912 {"extend", (PyCFunction)deque_extend,
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000913 METH_O, extend_doc},
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000914 {"extendleft", (PyCFunction)deque_extendleft,
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000915 METH_O, extendleft_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000916 {"pop", (PyCFunction)deque_pop,
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000917 METH_NOARGS, pop_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000918 {"popleft", (PyCFunction)deque_popleft,
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000919 METH_NOARGS, popleft_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000920 {"__reduce__", (PyCFunction)deque_reduce,
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000921 METH_NOARGS, reduce_doc},
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000922 {"remove", (PyCFunction)deque_remove,
923 METH_O, remove_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000924 {"__reversed__", (PyCFunction)deque_reviter,
Raymond Hettinger1e5809f2004-03-18 11:04:57 +0000925 METH_NOARGS, reversed_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000926 {"rotate", (PyCFunction)deque_rotate,
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000927 METH_VARARGS, rotate_doc},
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000928 {NULL, NULL} /* sentinel */
929};
930
931PyDoc_STRVAR(deque_doc,
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000932"deque(iterable[, maxlen]) --> deque object\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000933\n\
934Build an ordered collection accessible from endpoints only.");
935
Neal Norwitz87f10132004-02-29 15:40:53 +0000936static PyTypeObject deque_type = {
Martin v. Löwis68192102007-07-21 06:55:02 +0000937 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000938 "collections.deque", /* tp_name */
939 sizeof(dequeobject), /* tp_basicsize */
940 0, /* tp_itemsize */
941 /* methods */
942 (destructor)deque_dealloc, /* tp_dealloc */
Georg Brandld37ac692006-03-30 11:58:57 +0000943 deque_tp_print, /* tp_print */
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000944 0, /* tp_getattr */
945 0, /* tp_setattr */
946 0, /* tp_compare */
Georg Brandld37ac692006-03-30 11:58:57 +0000947 deque_repr, /* tp_repr */
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000948 0, /* tp_as_number */
949 &deque_as_sequence, /* tp_as_sequence */
950 0, /* tp_as_mapping */
Nick Coghlan53663a62008-07-15 14:27:37 +0000951 (hashfunc)PyObject_HashNotImplemented, /* tp_hash */
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000952 0, /* tp_call */
953 0, /* tp_str */
954 PyObject_GenericGetAttr, /* tp_getattro */
955 0, /* tp_setattro */
956 0, /* tp_as_buffer */
Raymond Hettinger691d8052004-05-30 07:26:47 +0000957 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
958 Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000959 deque_doc, /* tp_doc */
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000960 (traverseproc)deque_traverse, /* tp_traverse */
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000961 (inquiry)deque_clear, /* tp_clear */
Raymond Hettinger738ec902004-02-29 02:15:56 +0000962 (richcmpfunc)deque_richcompare, /* tp_richcompare */
Raymond Hettinger691d8052004-05-30 07:26:47 +0000963 offsetof(dequeobject, weakreflist), /* tp_weaklistoffset*/
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000964 (getiterfunc)deque_iter, /* tp_iter */
965 0, /* tp_iternext */
966 deque_methods, /* tp_methods */
967 0, /* tp_members */
Raymond Hettinger56411aa2009-03-10 12:50:59 +0000968 deque_getset, /* tp_getset */
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000969 0, /* tp_base */
970 0, /* tp_dict */
971 0, /* tp_descr_get */
972 0, /* tp_descr_set */
973 0, /* tp_dictoffset */
974 (initproc)deque_init, /* tp_init */
975 PyType_GenericAlloc, /* tp_alloc */
976 deque_new, /* tp_new */
977 PyObject_GC_Del, /* tp_free */
978};
979
980/*********************** Deque Iterator **************************/
981
982typedef struct {
983 PyObject_HEAD
Raymond Hettinger33fcf9d2008-07-24 00:08:18 +0000984 Py_ssize_t index;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000985 block *b;
986 dequeobject *deque;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +0000987 long state; /* state when the iterator is created */
Raymond Hettinger33fcf9d2008-07-24 00:08:18 +0000988 Py_ssize_t counter; /* number of items remaining for iteration */
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000989} dequeiterobject;
990
Martin v. Löwis111c1802008-06-13 07:47:47 +0000991static PyTypeObject dequeiter_type;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000992
993static PyObject *
994deque_iter(dequeobject *deque)
995{
996 dequeiterobject *it;
997
Antoine Pitrouaa687902009-01-01 14:11:22 +0000998 it = PyObject_GC_New(dequeiterobject, &dequeiter_type);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000999 if (it == NULL)
1000 return NULL;
1001 it->b = deque->leftblock;
1002 it->index = deque->leftindex;
1003 Py_INCREF(deque);
1004 it->deque = deque;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001005 it->state = deque->state;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001006 it->counter = deque->len;
Amaury Forgeot d'Arc57eb0e92009-01-02 00:03:54 +00001007 PyObject_GC_Track(it);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001008 return (PyObject *)it;
1009}
1010
Antoine Pitrouaa687902009-01-01 14:11:22 +00001011static int
1012dequeiter_traverse(dequeiterobject *dio, visitproc visit, void *arg)
1013{
1014 Py_VISIT(dio->deque);
1015 return 0;
1016}
1017
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001018static void
1019dequeiter_dealloc(dequeiterobject *dio)
1020{
1021 Py_XDECREF(dio->deque);
Antoine Pitrouaa687902009-01-01 14:11:22 +00001022 PyObject_GC_Del(dio);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001023}
1024
1025static PyObject *
1026dequeiter_next(dequeiterobject *it)
1027{
1028 PyObject *item;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001029
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001030 if (it->deque->state != it->state) {
Raymond Hettinger7892b1c2004-04-12 18:10:01 +00001031 it->counter = 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001032 PyErr_SetString(PyExc_RuntimeError,
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001033 "deque mutated during iteration");
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001034 return NULL;
1035 }
Raymond Hettinger51c2f6c2007-01-08 18:09:20 +00001036 if (it->counter == 0)
1037 return NULL;
Tim Peters5566e962006-07-28 00:23:15 +00001038 assert (!(it->b == it->deque->rightblock &&
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001039 it->index > it->deque->rightindex));
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001040
1041 item = it->b->data[it->index];
1042 it->index++;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001043 it->counter--;
1044 if (it->index == BLOCKLEN && it->counter > 0) {
1045 assert (it->b->rightlink != NULL);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001046 it->b = it->b->rightlink;
1047 it->index = 0;
1048 }
1049 Py_INCREF(item);
1050 return item;
1051}
1052
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001053static PyObject *
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001054dequeiter_len(dequeiterobject *it)
1055{
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001056 return PyInt_FromLong(it->counter);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001057}
1058
Armin Rigof5b3e362006-02-11 21:32:43 +00001059PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001060
1061static PyMethodDef dequeiter_methods[] = {
Armin Rigof5b3e362006-02-11 21:32:43 +00001062 {"__length_hint__", (PyCFunction)dequeiter_len, METH_NOARGS, length_hint_doc},
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001063 {NULL, NULL} /* sentinel */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001064};
1065
Martin v. Löwis111c1802008-06-13 07:47:47 +00001066static PyTypeObject dequeiter_type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00001067 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001068 "deque_iterator", /* tp_name */
1069 sizeof(dequeiterobject), /* tp_basicsize */
1070 0, /* tp_itemsize */
1071 /* methods */
1072 (destructor)dequeiter_dealloc, /* tp_dealloc */
1073 0, /* tp_print */
1074 0, /* tp_getattr */
1075 0, /* tp_setattr */
1076 0, /* tp_compare */
1077 0, /* tp_repr */
1078 0, /* tp_as_number */
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001079 0, /* tp_as_sequence */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001080 0, /* tp_as_mapping */
1081 0, /* tp_hash */
1082 0, /* tp_call */
1083 0, /* tp_str */
1084 PyObject_GenericGetAttr, /* tp_getattro */
1085 0, /* tp_setattro */
1086 0, /* tp_as_buffer */
Antoine Pitrouaa687902009-01-01 14:11:22 +00001087 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001088 0, /* tp_doc */
Antoine Pitrouaa687902009-01-01 14:11:22 +00001089 (traverseproc)dequeiter_traverse, /* tp_traverse */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001090 0, /* tp_clear */
1091 0, /* tp_richcompare */
1092 0, /* tp_weaklistoffset */
1093 PyObject_SelfIter, /* tp_iter */
1094 (iternextfunc)dequeiter_next, /* tp_iternext */
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001095 dequeiter_methods, /* tp_methods */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001096 0,
1097};
1098
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001099/*********************** Deque Reverse Iterator **************************/
1100
Martin v. Löwis111c1802008-06-13 07:47:47 +00001101static PyTypeObject dequereviter_type;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001102
1103static PyObject *
1104deque_reviter(dequeobject *deque)
1105{
1106 dequeiterobject *it;
1107
Antoine Pitrouaa687902009-01-01 14:11:22 +00001108 it = PyObject_GC_New(dequeiterobject, &dequereviter_type);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001109 if (it == NULL)
1110 return NULL;
1111 it->b = deque->rightblock;
1112 it->index = deque->rightindex;
1113 Py_INCREF(deque);
1114 it->deque = deque;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001115 it->state = deque->state;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001116 it->counter = deque->len;
Amaury Forgeot d'Arc57eb0e92009-01-02 00:03:54 +00001117 PyObject_GC_Track(it);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001118 return (PyObject *)it;
1119}
1120
1121static PyObject *
1122dequereviter_next(dequeiterobject *it)
1123{
1124 PyObject *item;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001125 if (it->counter == 0)
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001126 return NULL;
1127
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001128 if (it->deque->state != it->state) {
Raymond Hettinger7892b1c2004-04-12 18:10:01 +00001129 it->counter = 0;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001130 PyErr_SetString(PyExc_RuntimeError,
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001131 "deque mutated during iteration");
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001132 return NULL;
1133 }
Tim Peters5566e962006-07-28 00:23:15 +00001134 assert (!(it->b == it->deque->leftblock &&
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001135 it->index < it->deque->leftindex));
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001136
1137 item = it->b->data[it->index];
1138 it->index--;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001139 it->counter--;
1140 if (it->index == -1 && it->counter > 0) {
1141 assert (it->b->leftlink != NULL);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001142 it->b = it->b->leftlink;
1143 it->index = BLOCKLEN - 1;
1144 }
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001145 Py_INCREF(item);
1146 return item;
1147}
1148
Martin v. Löwis111c1802008-06-13 07:47:47 +00001149static PyTypeObject dequereviter_type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00001150 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001151 "deque_reverse_iterator", /* tp_name */
1152 sizeof(dequeiterobject), /* tp_basicsize */
1153 0, /* tp_itemsize */
1154 /* methods */
1155 (destructor)dequeiter_dealloc, /* tp_dealloc */
1156 0, /* tp_print */
1157 0, /* tp_getattr */
1158 0, /* tp_setattr */
1159 0, /* tp_compare */
1160 0, /* tp_repr */
1161 0, /* tp_as_number */
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001162 0, /* tp_as_sequence */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001163 0, /* tp_as_mapping */
1164 0, /* tp_hash */
1165 0, /* tp_call */
1166 0, /* tp_str */
1167 PyObject_GenericGetAttr, /* tp_getattro */
1168 0, /* tp_setattro */
1169 0, /* tp_as_buffer */
Antoine Pitrouaa687902009-01-01 14:11:22 +00001170 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001171 0, /* tp_doc */
Antoine Pitrouaa687902009-01-01 14:11:22 +00001172 (traverseproc)dequeiter_traverse, /* tp_traverse */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001173 0, /* tp_clear */
1174 0, /* tp_richcompare */
1175 0, /* tp_weaklistoffset */
1176 PyObject_SelfIter, /* tp_iter */
1177 (iternextfunc)dequereviter_next, /* tp_iternext */
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001178 dequeiter_methods, /* tp_methods */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001179 0,
1180};
1181
Guido van Rossum1968ad32006-02-25 22:38:04 +00001182/* defaultdict type *********************************************************/
1183
1184typedef struct {
1185 PyDictObject dict;
1186 PyObject *default_factory;
1187} defdictobject;
1188
1189static PyTypeObject defdict_type; /* Forward */
1190
1191PyDoc_STRVAR(defdict_missing_doc,
1192"__missing__(key) # Called by __getitem__ for missing key; pseudo-code:\n\
Georg Brandlb51a57e2007-03-06 13:32:52 +00001193 if self.default_factory is None: raise KeyError((key,))\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00001194 self[key] = value = self.default_factory()\n\
1195 return value\n\
1196");
1197
1198static PyObject *
1199defdict_missing(defdictobject *dd, PyObject *key)
1200{
1201 PyObject *factory = dd->default_factory;
1202 PyObject *value;
1203 if (factory == NULL || factory == Py_None) {
1204 /* XXX Call dict.__missing__(key) */
Georg Brandlb51a57e2007-03-06 13:32:52 +00001205 PyObject *tup;
1206 tup = PyTuple_Pack(1, key);
1207 if (!tup) return NULL;
1208 PyErr_SetObject(PyExc_KeyError, tup);
1209 Py_DECREF(tup);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001210 return NULL;
1211 }
1212 value = PyEval_CallObject(factory, NULL);
1213 if (value == NULL)
1214 return value;
1215 if (PyObject_SetItem((PyObject *)dd, key, value) < 0) {
1216 Py_DECREF(value);
1217 return NULL;
1218 }
1219 return value;
1220}
1221
1222PyDoc_STRVAR(defdict_copy_doc, "D.copy() -> a shallow copy of D.");
1223
1224static PyObject *
1225defdict_copy(defdictobject *dd)
1226{
1227 /* This calls the object's class. That only works for subclasses
1228 whose class constructor has the same signature. Subclasses that
Raymond Hettingera37430a2008-02-12 19:05:36 +00001229 define a different constructor signature must override copy().
Guido van Rossum1968ad32006-02-25 22:38:04 +00001230 */
Raymond Hettinger8fdab952009-08-04 19:08:05 +00001231
1232 if (dd->default_factory == NULL)
1233 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd), Py_None, dd, NULL);
Christian Heimese93237d2007-12-19 02:37:44 +00001234 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd),
Guido van Rossum1968ad32006-02-25 22:38:04 +00001235 dd->default_factory, dd, NULL);
1236}
1237
1238static PyObject *
1239defdict_reduce(defdictobject *dd)
1240{
Tim Peters5566e962006-07-28 00:23:15 +00001241 /* __reduce__ must return a 5-tuple as follows:
Guido van Rossum1968ad32006-02-25 22:38:04 +00001242
1243 - factory function
1244 - tuple of args for the factory function
1245 - additional state (here None)
1246 - sequence iterator (here None)
1247 - dictionary iterator (yielding successive (key, value) pairs
1248
1249 This API is used by pickle.py and copy.py.
1250
1251 For this to be useful with pickle.py, the default_factory
1252 must be picklable; e.g., None, a built-in, or a global
1253 function in a module or package.
1254
1255 Both shallow and deep copying are supported, but for deep
1256 copying, the default_factory must be deep-copyable; e.g. None,
1257 or a built-in (functions are not copyable at this time).
1258
1259 This only works for subclasses as long as their constructor
1260 signature is compatible; the first argument must be the
1261 optional default_factory, defaulting to None.
1262 */
1263 PyObject *args;
1264 PyObject *items;
1265 PyObject *result;
1266 if (dd->default_factory == NULL || dd->default_factory == Py_None)
1267 args = PyTuple_New(0);
1268 else
1269 args = PyTuple_Pack(1, dd->default_factory);
1270 if (args == NULL)
1271 return NULL;
1272 items = PyObject_CallMethod((PyObject *)dd, "iteritems", "()");
1273 if (items == NULL) {
1274 Py_DECREF(args);
1275 return NULL;
1276 }
Christian Heimese93237d2007-12-19 02:37:44 +00001277 result = PyTuple_Pack(5, Py_TYPE(dd), args,
Guido van Rossum1968ad32006-02-25 22:38:04 +00001278 Py_None, Py_None, items);
Tim Peters5566e962006-07-28 00:23:15 +00001279 Py_DECREF(items);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001280 Py_DECREF(args);
1281 return result;
1282}
1283
1284static PyMethodDef defdict_methods[] = {
1285 {"__missing__", (PyCFunction)defdict_missing, METH_O,
1286 defdict_missing_doc},
Raymond Hettingera37430a2008-02-12 19:05:36 +00001287 {"copy", (PyCFunction)defdict_copy, METH_NOARGS,
Guido van Rossum1968ad32006-02-25 22:38:04 +00001288 defdict_copy_doc},
1289 {"__copy__", (PyCFunction)defdict_copy, METH_NOARGS,
1290 defdict_copy_doc},
1291 {"__reduce__", (PyCFunction)defdict_reduce, METH_NOARGS,
1292 reduce_doc},
1293 {NULL}
1294};
1295
1296static PyMemberDef defdict_members[] = {
1297 {"default_factory", T_OBJECT,
1298 offsetof(defdictobject, default_factory), 0,
1299 PyDoc_STR("Factory for default value called by __missing__().")},
1300 {NULL}
1301};
1302
1303static void
1304defdict_dealloc(defdictobject *dd)
1305{
1306 Py_CLEAR(dd->default_factory);
1307 PyDict_Type.tp_dealloc((PyObject *)dd);
1308}
1309
1310static int
1311defdict_print(defdictobject *dd, FILE *fp, int flags)
1312{
1313 int sts;
Raymond Hettinger556b43d2007-10-05 19:07:31 +00001314 Py_BEGIN_ALLOW_THREADS
Guido van Rossum1968ad32006-02-25 22:38:04 +00001315 fprintf(fp, "defaultdict(");
Raymond Hettinger556b43d2007-10-05 19:07:31 +00001316 Py_END_ALLOW_THREADS
1317 if (dd->default_factory == NULL) {
1318 Py_BEGIN_ALLOW_THREADS
Guido van Rossum1968ad32006-02-25 22:38:04 +00001319 fprintf(fp, "None");
Raymond Hettinger556b43d2007-10-05 19:07:31 +00001320 Py_END_ALLOW_THREADS
1321 } else {
Guido van Rossum1968ad32006-02-25 22:38:04 +00001322 PyObject_Print(dd->default_factory, fp, 0);
1323 }
Raymond Hettinger556b43d2007-10-05 19:07:31 +00001324 Py_BEGIN_ALLOW_THREADS
Guido van Rossum1968ad32006-02-25 22:38:04 +00001325 fprintf(fp, ", ");
Raymond Hettinger556b43d2007-10-05 19:07:31 +00001326 Py_END_ALLOW_THREADS
Guido van Rossum1968ad32006-02-25 22:38:04 +00001327 sts = PyDict_Type.tp_print((PyObject *)dd, fp, 0);
Raymond Hettinger556b43d2007-10-05 19:07:31 +00001328 Py_BEGIN_ALLOW_THREADS
Guido van Rossum1968ad32006-02-25 22:38:04 +00001329 fprintf(fp, ")");
Raymond Hettinger556b43d2007-10-05 19:07:31 +00001330 Py_END_ALLOW_THREADS
Guido van Rossum1968ad32006-02-25 22:38:04 +00001331 return sts;
1332}
1333
1334static PyObject *
1335defdict_repr(defdictobject *dd)
1336{
1337 PyObject *defrepr;
1338 PyObject *baserepr;
1339 PyObject *result;
1340 baserepr = PyDict_Type.tp_repr((PyObject *)dd);
1341 if (baserepr == NULL)
1342 return NULL;
1343 if (dd->default_factory == NULL)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001344 defrepr = PyString_FromString("None");
Guido van Rossum1968ad32006-02-25 22:38:04 +00001345 else
Amaury Forgeot d'Arcb01aa432008-02-08 00:56:02 +00001346 {
1347 int status = Py_ReprEnter(dd->default_factory);
1348 if (status != 0) {
1349 if (status < 0)
1350 return NULL;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001351 defrepr = PyString_FromString("...");
Amaury Forgeot d'Arcb01aa432008-02-08 00:56:02 +00001352 }
1353 else
1354 defrepr = PyObject_Repr(dd->default_factory);
1355 Py_ReprLeave(dd->default_factory);
1356 }
Guido van Rossum1968ad32006-02-25 22:38:04 +00001357 if (defrepr == NULL) {
1358 Py_DECREF(baserepr);
1359 return NULL;
1360 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001361 result = PyString_FromFormat("defaultdict(%s, %s)",
1362 PyString_AS_STRING(defrepr),
1363 PyString_AS_STRING(baserepr));
Guido van Rossum1968ad32006-02-25 22:38:04 +00001364 Py_DECREF(defrepr);
1365 Py_DECREF(baserepr);
1366 return result;
1367}
1368
1369static int
1370defdict_traverse(PyObject *self, visitproc visit, void *arg)
1371{
1372 Py_VISIT(((defdictobject *)self)->default_factory);
1373 return PyDict_Type.tp_traverse(self, visit, arg);
1374}
1375
1376static int
1377defdict_tp_clear(defdictobject *dd)
1378{
Thomas Woutersedf17d82006-04-15 17:28:34 +00001379 Py_CLEAR(dd->default_factory);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001380 return PyDict_Type.tp_clear((PyObject *)dd);
1381}
1382
1383static int
1384defdict_init(PyObject *self, PyObject *args, PyObject *kwds)
1385{
1386 defdictobject *dd = (defdictobject *)self;
1387 PyObject *olddefault = dd->default_factory;
1388 PyObject *newdefault = NULL;
1389 PyObject *newargs;
1390 int result;
1391 if (args == NULL || !PyTuple_Check(args))
1392 newargs = PyTuple_New(0);
1393 else {
1394 Py_ssize_t n = PyTuple_GET_SIZE(args);
Raymond Hettinger5a0217e2007-02-07 21:42:17 +00001395 if (n > 0) {
Guido van Rossum1968ad32006-02-25 22:38:04 +00001396 newdefault = PyTuple_GET_ITEM(args, 0);
Raymond Hettinger8fdab952009-08-04 19:08:05 +00001397 if (!PyCallable_Check(newdefault) && newdefault != Py_None) {
Raymond Hettinger5a0217e2007-02-07 21:42:17 +00001398 PyErr_SetString(PyExc_TypeError,
1399 "first argument must be callable");
1400 return -1;
1401 }
1402 }
Guido van Rossum1968ad32006-02-25 22:38:04 +00001403 newargs = PySequence_GetSlice(args, 1, n);
1404 }
1405 if (newargs == NULL)
1406 return -1;
1407 Py_XINCREF(newdefault);
1408 dd->default_factory = newdefault;
1409 result = PyDict_Type.tp_init(self, newargs, kwds);
1410 Py_DECREF(newargs);
1411 Py_XDECREF(olddefault);
1412 return result;
1413}
1414
1415PyDoc_STRVAR(defdict_doc,
1416"defaultdict(default_factory) --> dict with default factory\n\
1417\n\
1418The default factory is called without arguments to produce\n\
1419a new value when a key is not present, in __getitem__ only.\n\
1420A defaultdict compares equal to a dict with the same items.\n\
1421");
1422
Anthony Baxter3b8ff312006-04-04 15:05:23 +00001423/* See comment in xxsubtype.c */
1424#define DEFERRED_ADDRESS(ADDR) 0
1425
Guido van Rossum1968ad32006-02-25 22:38:04 +00001426static PyTypeObject defdict_type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00001427 PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0)
Guido van Rossum1968ad32006-02-25 22:38:04 +00001428 "collections.defaultdict", /* tp_name */
1429 sizeof(defdictobject), /* tp_basicsize */
1430 0, /* tp_itemsize */
1431 /* methods */
1432 (destructor)defdict_dealloc, /* tp_dealloc */
1433 (printfunc)defdict_print, /* tp_print */
1434 0, /* tp_getattr */
1435 0, /* tp_setattr */
1436 0, /* tp_compare */
1437 (reprfunc)defdict_repr, /* tp_repr */
1438 0, /* tp_as_number */
1439 0, /* tp_as_sequence */
1440 0, /* tp_as_mapping */
1441 0, /* tp_hash */
1442 0, /* tp_call */
1443 0, /* tp_str */
1444 PyObject_GenericGetAttr, /* tp_getattro */
1445 0, /* tp_setattro */
1446 0, /* tp_as_buffer */
1447 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
1448 Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
1449 defdict_doc, /* tp_doc */
Georg Brandld37ac692006-03-30 11:58:57 +00001450 defdict_traverse, /* tp_traverse */
Guido van Rossum1968ad32006-02-25 22:38:04 +00001451 (inquiry)defdict_tp_clear, /* tp_clear */
1452 0, /* tp_richcompare */
1453 0, /* tp_weaklistoffset*/
1454 0, /* tp_iter */
1455 0, /* tp_iternext */
1456 defdict_methods, /* tp_methods */
1457 defdict_members, /* tp_members */
1458 0, /* tp_getset */
Anthony Baxter3b8ff312006-04-04 15:05:23 +00001459 DEFERRED_ADDRESS(&PyDict_Type), /* tp_base */
Guido van Rossum1968ad32006-02-25 22:38:04 +00001460 0, /* tp_dict */
1461 0, /* tp_descr_get */
1462 0, /* tp_descr_set */
1463 0, /* tp_dictoffset */
Georg Brandld37ac692006-03-30 11:58:57 +00001464 defdict_init, /* tp_init */
Guido van Rossum1968ad32006-02-25 22:38:04 +00001465 PyType_GenericAlloc, /* tp_alloc */
1466 0, /* tp_new */
1467 PyObject_GC_Del, /* tp_free */
1468};
1469
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001470/* module level code ********************************************************/
1471
1472PyDoc_STRVAR(module_doc,
Guido van Rossum1968ad32006-02-25 22:38:04 +00001473"High performance data structures.\n\
1474- deque: ordered collection accessible from endpoints only\n\
1475- defaultdict: dict subclass with a default value factory\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001476");
1477
1478PyMODINIT_FUNC
Raymond Hettingereb979882007-02-28 18:37:52 +00001479init_collections(void)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001480{
1481 PyObject *m;
1482
Raymond Hettingereb979882007-02-28 18:37:52 +00001483 m = Py_InitModule3("_collections", NULL, module_doc);
Neal Norwitz1ac754f2006-01-19 06:09:39 +00001484 if (m == NULL)
1485 return;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001486
1487 if (PyType_Ready(&deque_type) < 0)
1488 return;
1489 Py_INCREF(&deque_type);
1490 PyModule_AddObject(m, "deque", (PyObject *)&deque_type);
1491
Anthony Baxter3b8ff312006-04-04 15:05:23 +00001492 defdict_type.tp_base = &PyDict_Type;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001493 if (PyType_Ready(&defdict_type) < 0)
1494 return;
1495 Py_INCREF(&defdict_type);
1496 PyModule_AddObject(m, "defaultdict", (PyObject *)&defdict_type);
1497
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001498 if (PyType_Ready(&dequeiter_type) < 0)
Tim Peters1065f752004-10-01 01:03:29 +00001499 return;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001500
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001501 if (PyType_Ready(&dequereviter_type) < 0)
1502 return;
1503
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001504 return;
1505}