blob: 42cfe6b34beb929a8b06450584a23af54a1589e1 [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
279static PyObject *
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000280deque_extend(dequeobject *deque, PyObject *iterable)
281{
282 PyObject *it, *item;
283
Raymond Hettinger287bef42009-12-10 05:56:49 +0000284 /* Handle case where id(deque) == id(iterable) */
285 if ((PyObject *)deque == iterable) {
286 PyObject *result;
287 PyObject *s = PySequence_List(iterable);
288 if (s == NULL)
289 return NULL;
290 result = deque_extend(deque, s);
291 Py_DECREF(s);
292 return result;
293 }
294
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000295 it = PyObject_GetIter(iterable);
296 if (it == NULL)
297 return NULL;
298
299 while ((item = PyIter_Next(it)) != NULL) {
Raymond Hettingerd1b3d882004-10-02 00:43:13 +0000300 deque->state++;
Armin Rigo974d7572004-10-02 13:59:34 +0000301 if (deque->rightindex == BLOCKLEN-1) {
Raymond Hettingerc5fa9922004-10-06 17:51:54 +0000302 block *b = newblock(deque->rightblock, NULL,
303 deque->len);
Raymond Hettingerc058fd12004-02-07 02:45:22 +0000304 if (b == NULL) {
305 Py_DECREF(item);
306 Py_DECREF(it);
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000307 return NULL;
Raymond Hettingerc058fd12004-02-07 02:45:22 +0000308 }
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000309 assert(deque->rightblock->rightlink == NULL);
310 deque->rightblock->rightlink = b;
311 deque->rightblock = b;
Armin Rigo974d7572004-10-02 13:59:34 +0000312 deque->rightindex = -1;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000313 }
Armin Rigo974d7572004-10-02 13:59:34 +0000314 deque->len++;
315 deque->rightindex++;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000316 deque->rightblock->data[deque->rightindex] = item;
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000317 TRIM(deque, deque_popleft);
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000318 }
319 Py_DECREF(it);
Tim Peters1065f752004-10-01 01:03:29 +0000320 if (PyErr_Occurred())
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000321 return NULL;
322 Py_RETURN_NONE;
323}
324
Tim Peters1065f752004-10-01 01:03:29 +0000325PyDoc_STRVAR(extend_doc,
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000326"Extend the right side of the deque with elements from the iterable");
327
328static PyObject *
329deque_extendleft(dequeobject *deque, PyObject *iterable)
330{
331 PyObject *it, *item;
332
Raymond Hettinger287bef42009-12-10 05:56:49 +0000333 /* Handle case where id(deque) == id(iterable) */
334 if ((PyObject *)deque == iterable) {
335 PyObject *result;
336 PyObject *s = PySequence_List(iterable);
337 if (s == NULL)
338 return NULL;
339 result = deque_extendleft(deque, s);
340 Py_DECREF(s);
341 return result;
342 }
343
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000344 it = PyObject_GetIter(iterable);
345 if (it == NULL)
346 return NULL;
347
348 while ((item = PyIter_Next(it)) != NULL) {
Raymond Hettingerd1b3d882004-10-02 00:43:13 +0000349 deque->state++;
Armin Rigo974d7572004-10-02 13:59:34 +0000350 if (deque->leftindex == 0) {
Raymond Hettingerc5fa9922004-10-06 17:51:54 +0000351 block *b = newblock(NULL, deque->leftblock,
352 deque->len);
Raymond Hettingerc058fd12004-02-07 02:45:22 +0000353 if (b == NULL) {
354 Py_DECREF(item);
355 Py_DECREF(it);
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000356 return NULL;
Raymond Hettingerc058fd12004-02-07 02:45:22 +0000357 }
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000358 assert(deque->leftblock->leftlink == NULL);
359 deque->leftblock->leftlink = b;
360 deque->leftblock = b;
Armin Rigo974d7572004-10-02 13:59:34 +0000361 deque->leftindex = BLOCKLEN;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000362 }
Armin Rigo974d7572004-10-02 13:59:34 +0000363 deque->len++;
364 deque->leftindex--;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000365 deque->leftblock->data[deque->leftindex] = item;
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000366 TRIM(deque, deque_pop);
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000367 }
368 Py_DECREF(it);
Raymond Hettingera435c532004-07-09 04:10:20 +0000369 if (PyErr_Occurred())
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000370 return NULL;
371 Py_RETURN_NONE;
372}
373
Tim Peters1065f752004-10-01 01:03:29 +0000374PyDoc_STRVAR(extendleft_doc,
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000375"Extend the left side of the deque with elements from the iterable");
376
Raymond Hettinger287bef42009-12-10 05:56:49 +0000377static PyObject *
378deque_inplace_concat(dequeobject *deque, PyObject *other)
379{
380 PyObject *result;
381
382 result = deque_extend(deque, other);
383 if (result == NULL)
384 return result;
385 Py_DECREF(result);
386 Py_INCREF(deque);
387 return (PyObject *)deque;
388}
389
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000390static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000391_deque_rotate(dequeobject *deque, Py_ssize_t n)
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000392{
Raymond Hettinger33fcf9d2008-07-24 00:08:18 +0000393 Py_ssize_t i, len=deque->len, halflen=(len+1)>>1;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000394 PyObject *item, *rv;
395
Raymond Hettingeree33b272004-02-08 04:05:26 +0000396 if (len == 0)
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000397 return 0;
Raymond Hettingeree33b272004-02-08 04:05:26 +0000398 if (n > halflen || n < -halflen) {
399 n %= len;
400 if (n > halflen)
401 n -= len;
402 else if (n < -halflen)
403 n += len;
404 }
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000405
406 for (i=0 ; i<n ; i++) {
407 item = deque_pop(deque, NULL);
Raymond Hettingera435c532004-07-09 04:10:20 +0000408 assert (item != NULL);
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000409 rv = deque_appendleft(deque, item);
410 Py_DECREF(item);
411 if (rv == NULL)
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000412 return -1;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000413 Py_DECREF(rv);
414 }
415 for (i=0 ; i>n ; i--) {
416 item = deque_popleft(deque, NULL);
Raymond Hettingera435c532004-07-09 04:10:20 +0000417 assert (item != NULL);
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000418 rv = deque_append(deque, item);
419 Py_DECREF(item);
420 if (rv == NULL)
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000421 return -1;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000422 Py_DECREF(rv);
423 }
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000424 return 0;
425}
426
427static PyObject *
428deque_rotate(dequeobject *deque, PyObject *args)
429{
Raymond Hettinger33fcf9d2008-07-24 00:08:18 +0000430 Py_ssize_t n=1;
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000431
Raymond Hettinger723ba302008-07-24 00:53:49 +0000432 if (!PyArg_ParseTuple(args, "|n:rotate", &n))
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000433 return NULL;
434 if (_deque_rotate(deque, n) == 0)
435 Py_RETURN_NONE;
436 return NULL;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000437}
438
Tim Peters1065f752004-10-01 01:03:29 +0000439PyDoc_STRVAR(rotate_doc,
Raymond Hettingeree33b272004-02-08 04:05:26 +0000440"Rotate the deque n steps to the right (default n=1). If n is negative, rotates left.");
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000441
Martin v. Löwis18e16552006-02-15 17:27:45 +0000442static Py_ssize_t
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000443deque_len(dequeobject *deque)
444{
445 return deque->len;
446}
447
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000448static PyObject *
449deque_remove(dequeobject *deque, PyObject *value)
450{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000451 Py_ssize_t i, n=deque->len;
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000452
453 for (i=0 ; i<n ; i++) {
454 PyObject *item = deque->leftblock->data[deque->leftindex];
455 int cmp = PyObject_RichCompareBool(item, value, Py_EQ);
Raymond Hettingerd73202c2005-03-19 00:00:51 +0000456
457 if (deque->len != n) {
Tim Peters5566e962006-07-28 00:23:15 +0000458 PyErr_SetString(PyExc_IndexError,
Raymond Hettingerd73202c2005-03-19 00:00:51 +0000459 "deque mutated during remove().");
460 return NULL;
461 }
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000462 if (cmp > 0) {
Raymond Hettingerd73202c2005-03-19 00:00:51 +0000463 PyObject *tgt = deque_popleft(deque, NULL);
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000464 assert (tgt != NULL);
465 Py_DECREF(tgt);
466 if (_deque_rotate(deque, i) == -1)
467 return NULL;
468 Py_RETURN_NONE;
469 }
470 else if (cmp < 0) {
471 _deque_rotate(deque, i);
472 return NULL;
473 }
474 _deque_rotate(deque, -1);
475 }
476 PyErr_SetString(PyExc_ValueError, "deque.remove(x): x not in deque");
477 return NULL;
478}
479
480PyDoc_STRVAR(remove_doc,
481"D.remove(value) -- remove first occurrence of value.");
482
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000483static int
484deque_clear(dequeobject *deque)
485{
486 PyObject *item;
487
Raymond Hettingerd1b3d882004-10-02 00:43:13 +0000488 while (deque->len) {
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000489 item = deque_pop(deque, NULL);
Raymond Hettingera435c532004-07-09 04:10:20 +0000490 assert (item != NULL);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000491 Py_DECREF(item);
492 }
493 assert(deque->leftblock == deque->rightblock &&
Raymond Hettingerd1b3d882004-10-02 00:43:13 +0000494 deque->leftindex - 1 == deque->rightindex &&
495 deque->len == 0);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000496 return 0;
497}
498
499static PyObject *
Raymond Hettinger33fcf9d2008-07-24 00:08:18 +0000500deque_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000501{
502 block *b;
503 PyObject *item;
Raymond Hettinger33fcf9d2008-07-24 00:08:18 +0000504 Py_ssize_t n, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000505
506 if (i < 0 || i >= deque->len) {
507 PyErr_SetString(PyExc_IndexError,
508 "deque index out of range");
509 return NULL;
510 }
511
Raymond Hettinger6c79a512004-03-04 08:00:54 +0000512 if (i == 0) {
513 i = deque->leftindex;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000514 b = deque->leftblock;
Raymond Hettinger6c79a512004-03-04 08:00:54 +0000515 } else if (i == deque->len - 1) {
516 i = deque->rightindex;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000517 b = deque->rightblock;
Raymond Hettinger6c79a512004-03-04 08:00:54 +0000518 } else {
519 i += deque->leftindex;
520 n = i / BLOCKLEN;
521 i %= BLOCKLEN;
Armin Rigo974d7572004-10-02 13:59:34 +0000522 if (index < (deque->len >> 1)) {
Raymond Hettinger6c79a512004-03-04 08:00:54 +0000523 b = deque->leftblock;
524 while (n--)
525 b = b->rightlink;
526 } else {
527 n = (deque->leftindex + deque->len - 1) / BLOCKLEN - n;
528 b = deque->rightblock;
529 while (n--)
530 b = b->leftlink;
531 }
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000532 }
533 item = b->data[i];
534 Py_INCREF(item);
535 return item;
536}
537
Raymond Hettinger616f4f62004-06-26 04:42:06 +0000538/* delitem() implemented in terms of rotate for simplicity and reasonable
539 performance near the end points. If for some reason this method becomes
Tim Peters1065f752004-10-01 01:03:29 +0000540 popular, it is not hard to re-implement this using direct data movement
Raymond Hettinger616f4f62004-06-26 04:42:06 +0000541 (similar to code in list slice assignment) and achieve a two or threefold
542 performance boost.
543*/
544
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000545static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000546deque_del_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000547{
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000548 PyObject *item;
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000549
Tim Peters1065f752004-10-01 01:03:29 +0000550 assert (i >= 0 && i < deque->len);
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000551 if (_deque_rotate(deque, -i) == -1)
552 return -1;
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000553
554 item = deque_popleft(deque, NULL);
Raymond Hettingera435c532004-07-09 04:10:20 +0000555 assert (item != NULL);
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000556 Py_DECREF(item);
557
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000558 return _deque_rotate(deque, i);
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000559}
560
561static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000562deque_ass_item(dequeobject *deque, Py_ssize_t i, PyObject *v)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000563{
564 PyObject *old_value;
565 block *b;
Martin v. Löwisad0a4622006-02-16 14:30:23 +0000566 Py_ssize_t n, len=deque->len, halflen=(len+1)>>1, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000567
Raymond Hettingera435c532004-07-09 04:10:20 +0000568 if (i < 0 || i >= len) {
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000569 PyErr_SetString(PyExc_IndexError,
570 "deque index out of range");
571 return -1;
572 }
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000573 if (v == NULL)
574 return deque_del_item(deque, i);
575
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000576 i += deque->leftindex;
577 n = i / BLOCKLEN;
578 i %= BLOCKLEN;
Raymond Hettingera435c532004-07-09 04:10:20 +0000579 if (index <= halflen) {
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000580 b = deque->leftblock;
581 while (n--)
582 b = b->rightlink;
583 } else {
Raymond Hettingera435c532004-07-09 04:10:20 +0000584 n = (deque->leftindex + len - 1) / BLOCKLEN - n;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000585 b = deque->rightblock;
586 while (n--)
587 b = b->leftlink;
588 }
589 Py_INCREF(v);
590 old_value = b->data[i];
591 b->data[i] = v;
592 Py_DECREF(old_value);
593 return 0;
594}
595
596static PyObject *
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000597deque_clearmethod(dequeobject *deque)
598{
Raymond Hettingera435c532004-07-09 04:10:20 +0000599 int rv;
600
601 rv = deque_clear(deque);
602 assert (rv != -1);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000603 Py_RETURN_NONE;
604}
605
606PyDoc_STRVAR(clear_doc, "Remove all elements from the deque.");
607
608static void
609deque_dealloc(dequeobject *deque)
610{
611 PyObject_GC_UnTrack(deque);
Raymond Hettinger691d8052004-05-30 07:26:47 +0000612 if (deque->weakreflist != NULL)
613 PyObject_ClearWeakRefs((PyObject *) deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000614 if (deque->leftblock != NULL) {
Raymond Hettingere9c89e82004-07-19 00:10:24 +0000615 deque_clear(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000616 assert(deque->leftblock != NULL);
Raymond Hettingerd3ffd342007-11-10 01:54:03 +0000617 freeblock(deque->leftblock);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000618 }
619 deque->leftblock = NULL;
620 deque->rightblock = NULL;
Christian Heimese93237d2007-12-19 02:37:44 +0000621 Py_TYPE(deque)->tp_free(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000622}
623
624static int
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000625deque_traverse(dequeobject *deque, visitproc visit, void *arg)
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000626{
Tim Peters10c7e862004-10-01 02:01:04 +0000627 block *b;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000628 PyObject *item;
Raymond Hettinger33fcf9d2008-07-24 00:08:18 +0000629 Py_ssize_t index;
630 Py_ssize_t indexlo = deque->leftindex;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000631
Tim Peters10c7e862004-10-01 02:01:04 +0000632 for (b = deque->leftblock; b != NULL; b = b->rightlink) {
Raymond Hettinger33fcf9d2008-07-24 00:08:18 +0000633 const Py_ssize_t indexhi = b == deque->rightblock ?
Tim Peters10c7e862004-10-01 02:01:04 +0000634 deque->rightindex :
635 BLOCKLEN - 1;
636
637 for (index = indexlo; index <= indexhi; ++index) {
638 item = b->data[index];
639 Py_VISIT(item);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000640 }
Tim Peters10c7e862004-10-01 02:01:04 +0000641 indexlo = 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000642 }
643 return 0;
644}
645
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000646static PyObject *
647deque_copy(PyObject *deque)
648{
Raymond Hettinger68995862007-10-10 00:26:46 +0000649 if (((dequeobject *)deque)->maxlen == -1)
Christian Heimese93237d2007-12-19 02:37:44 +0000650 return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "O", deque, NULL);
Raymond Hettinger68995862007-10-10 00:26:46 +0000651 else
Christian Heimese93237d2007-12-19 02:37:44 +0000652 return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "Oi",
Raymond Hettinger68995862007-10-10 00:26:46 +0000653 deque, ((dequeobject *)deque)->maxlen, NULL);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000654}
655
656PyDoc_STRVAR(copy_doc, "Return a shallow copy of a deque.");
657
658static PyObject *
659deque_reduce(dequeobject *deque)
660{
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000661 PyObject *dict, *result, *aslist;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000662
Raymond Hettinger952f8802004-11-09 07:27:35 +0000663 dict = PyObject_GetAttrString((PyObject *)deque, "__dict__");
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000664 if (dict == NULL)
Raymond Hettinger952f8802004-11-09 07:27:35 +0000665 PyErr_Clear();
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000666 aslist = PySequence_List((PyObject *)deque);
667 if (aslist == NULL) {
Neal Norwitzc47cf7d2007-10-05 03:39:17 +0000668 Py_XDECREF(dict);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000669 return NULL;
670 }
Raymond Hettinger68995862007-10-10 00:26:46 +0000671 if (dict == NULL) {
672 if (deque->maxlen == -1)
Christian Heimese93237d2007-12-19 02:37:44 +0000673 result = Py_BuildValue("O(O)", Py_TYPE(deque), aslist);
Raymond Hettinger68995862007-10-10 00:26:46 +0000674 else
Raymond Hettinger33fcf9d2008-07-24 00:08:18 +0000675 result = Py_BuildValue("O(On)", Py_TYPE(deque), aslist, deque->maxlen);
Raymond Hettinger68995862007-10-10 00:26:46 +0000676 } else {
677 if (deque->maxlen == -1)
Christian Heimese93237d2007-12-19 02:37:44 +0000678 result = Py_BuildValue("O(OO)O", Py_TYPE(deque), aslist, Py_None, dict);
Raymond Hettinger68995862007-10-10 00:26:46 +0000679 else
Raymond Hettinger33fcf9d2008-07-24 00:08:18 +0000680 result = Py_BuildValue("O(On)O", Py_TYPE(deque), aslist, deque->maxlen, dict);
Raymond Hettinger68995862007-10-10 00:26:46 +0000681 }
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000682 Py_XDECREF(dict);
683 Py_DECREF(aslist);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000684 return result;
685}
686
687PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
688
689static PyObject *
690deque_repr(PyObject *deque)
691{
Raymond Hettinger556b43d2007-10-05 19:07:31 +0000692 PyObject *aslist, *result, *fmt;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000693 int i;
694
695 i = Py_ReprEnter(deque);
696 if (i != 0) {
697 if (i < 0)
698 return NULL;
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000699 return PyString_FromString("[...]");
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000700 }
701
702 aslist = PySequence_List(deque);
703 if (aslist == NULL) {
704 Py_ReprLeave(deque);
705 return NULL;
706 }
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000707 if (((dequeobject *)deque)->maxlen != -1)
Amaury Forgeot d'Arc05e34492008-09-10 22:04:45 +0000708 fmt = PyString_FromFormat("deque(%%r, maxlen=%zd)",
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000709 ((dequeobject *)deque)->maxlen);
710 else
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000711 fmt = PyString_FromString("deque(%r)");
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000712 if (fmt == NULL) {
713 Py_DECREF(aslist);
714 Py_ReprLeave(deque);
715 return NULL;
716 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000717 result = PyString_Format(fmt, aslist);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000718 Py_DECREF(fmt);
719 Py_DECREF(aslist);
720 Py_ReprLeave(deque);
721 return result;
722}
723
724static int
725deque_tp_print(PyObject *deque, FILE *fp, int flags)
726{
727 PyObject *it, *item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000728 char *emit = ""; /* No separator emitted on first pass */
729 char *separator = ", ";
730 int i;
731
732 i = Py_ReprEnter(deque);
733 if (i != 0) {
734 if (i < 0)
735 return i;
Raymond Hettinger556b43d2007-10-05 19:07:31 +0000736 Py_BEGIN_ALLOW_THREADS
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000737 fputs("[...]", fp);
Raymond Hettinger556b43d2007-10-05 19:07:31 +0000738 Py_END_ALLOW_THREADS
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000739 return 0;
740 }
741
742 it = PyObject_GetIter(deque);
743 if (it == NULL)
744 return -1;
745
Raymond Hettinger556b43d2007-10-05 19:07:31 +0000746 Py_BEGIN_ALLOW_THREADS
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000747 fputs("deque([", fp);
Raymond Hettinger556b43d2007-10-05 19:07:31 +0000748 Py_END_ALLOW_THREADS
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000749 while ((item = PyIter_Next(it)) != NULL) {
Raymond Hettinger556b43d2007-10-05 19:07:31 +0000750 Py_BEGIN_ALLOW_THREADS
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000751 fputs(emit, fp);
Raymond Hettinger556b43d2007-10-05 19:07:31 +0000752 Py_END_ALLOW_THREADS
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000753 emit = separator;
754 if (PyObject_Print(item, fp, 0) != 0) {
755 Py_DECREF(item);
756 Py_DECREF(it);
757 Py_ReprLeave(deque);
758 return -1;
759 }
760 Py_DECREF(item);
761 }
762 Py_ReprLeave(deque);
763 Py_DECREF(it);
Tim Peters1065f752004-10-01 01:03:29 +0000764 if (PyErr_Occurred())
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000765 return -1;
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000766
Raymond Hettinger556b43d2007-10-05 19:07:31 +0000767 Py_BEGIN_ALLOW_THREADS
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000768 if (((dequeobject *)deque)->maxlen == -1)
769 fputs("])", fp);
770 else
Christian Heimes1cc69632008-08-22 20:10:27 +0000771 fprintf(fp, "], maxlen=%" PY_FORMAT_SIZE_T "d)", ((dequeobject *)deque)->maxlen);
Raymond Hettinger556b43d2007-10-05 19:07:31 +0000772 Py_END_ALLOW_THREADS
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000773 return 0;
774}
775
Raymond Hettinger738ec902004-02-29 02:15:56 +0000776static PyObject *
777deque_richcompare(PyObject *v, PyObject *w, int op)
778{
779 PyObject *it1=NULL, *it2=NULL, *x, *y;
Raymond Hettinger33fcf9d2008-07-24 00:08:18 +0000780 Py_ssize_t vs, ws;
781 int b, cmp=-1;
Raymond Hettinger738ec902004-02-29 02:15:56 +0000782
Tim Peters1065f752004-10-01 01:03:29 +0000783 if (!PyObject_TypeCheck(v, &deque_type) ||
Raymond Hettinger285cfcc2004-05-18 18:15:03 +0000784 !PyObject_TypeCheck(w, &deque_type)) {
Raymond Hettinger738ec902004-02-29 02:15:56 +0000785 Py_INCREF(Py_NotImplemented);
786 return Py_NotImplemented;
787 }
788
789 /* Shortcuts */
790 vs = ((dequeobject *)v)->len;
791 ws = ((dequeobject *)w)->len;
792 if (op == Py_EQ) {
793 if (v == w)
794 Py_RETURN_TRUE;
795 if (vs != ws)
796 Py_RETURN_FALSE;
797 }
798 if (op == Py_NE) {
799 if (v == w)
800 Py_RETURN_FALSE;
801 if (vs != ws)
802 Py_RETURN_TRUE;
803 }
804
805 /* Search for the first index where items are different */
806 it1 = PyObject_GetIter(v);
807 if (it1 == NULL)
808 goto done;
809 it2 = PyObject_GetIter(w);
810 if (it2 == NULL)
811 goto done;
Armin Rigo974d7572004-10-02 13:59:34 +0000812 for (;;) {
Raymond Hettinger738ec902004-02-29 02:15:56 +0000813 x = PyIter_Next(it1);
Armin Rigo974d7572004-10-02 13:59:34 +0000814 if (x == NULL && PyErr_Occurred())
Raymond Hettinger738ec902004-02-29 02:15:56 +0000815 goto done;
816 y = PyIter_Next(it2);
Armin Rigo974d7572004-10-02 13:59:34 +0000817 if (x == NULL || y == NULL)
818 break;
Raymond Hettinger738ec902004-02-29 02:15:56 +0000819 b = PyObject_RichCompareBool(x, y, Py_EQ);
820 if (b == 0) {
821 cmp = PyObject_RichCompareBool(x, y, op);
822 Py_DECREF(x);
823 Py_DECREF(y);
824 goto done;
825 }
826 Py_DECREF(x);
827 Py_DECREF(y);
828 if (b == -1)
829 goto done;
830 }
Armin Rigo974d7572004-10-02 13:59:34 +0000831 /* We reached the end of one deque or both */
832 Py_XDECREF(x);
833 Py_XDECREF(y);
834 if (PyErr_Occurred())
835 goto done;
Raymond Hettinger738ec902004-02-29 02:15:56 +0000836 switch (op) {
Armin Rigo974d7572004-10-02 13:59:34 +0000837 case Py_LT: cmp = y != NULL; break; /* if w was longer */
838 case Py_LE: cmp = x == NULL; break; /* if v was not longer */
839 case Py_EQ: cmp = x == y; break; /* if we reached the end of both */
840 case Py_NE: cmp = x != y; break; /* if one deque continues */
841 case Py_GT: cmp = x != NULL; break; /* if v was longer */
842 case Py_GE: cmp = y == NULL; break; /* if w was not longer */
Raymond Hettinger738ec902004-02-29 02:15:56 +0000843 }
Tim Peters1065f752004-10-01 01:03:29 +0000844
Raymond Hettinger738ec902004-02-29 02:15:56 +0000845done:
846 Py_XDECREF(it1);
847 Py_XDECREF(it2);
848 if (cmp == 1)
849 Py_RETURN_TRUE;
850 if (cmp == 0)
851 Py_RETURN_FALSE;
852 return NULL;
853}
854
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000855static int
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000856deque_init(dequeobject *deque, PyObject *args, PyObject *kwdargs)
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000857{
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000858 PyObject *iterable = NULL;
Raymond Hettinger68995862007-10-10 00:26:46 +0000859 PyObject *maxlenobj = NULL;
Raymond Hettinger33fcf9d2008-07-24 00:08:18 +0000860 Py_ssize_t maxlen = -1;
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000861 char *kwlist[] = {"iterable", "maxlen", 0};
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000862
Raymond Hettinger68995862007-10-10 00:26:46 +0000863 if (!PyArg_ParseTupleAndKeywords(args, kwdargs, "|OO:deque", kwlist, &iterable, &maxlenobj))
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000864 return -1;
Raymond Hettinger68995862007-10-10 00:26:46 +0000865 if (maxlenobj != NULL && maxlenobj != Py_None) {
Raymond Hettinger33fcf9d2008-07-24 00:08:18 +0000866 maxlen = PyInt_AsSsize_t(maxlenobj);
Raymond Hettinger68995862007-10-10 00:26:46 +0000867 if (maxlen == -1 && PyErr_Occurred())
868 return -1;
869 if (maxlen < 0) {
870 PyErr_SetString(PyExc_ValueError, "maxlen must be non-negative");
871 return -1;
872 }
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000873 }
874 deque->maxlen = maxlen;
Raymond Hettingeradf9ffd2007-12-13 00:08:37 +0000875 deque_clear(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000876 if (iterable != NULL) {
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000877 PyObject *rv = deque_extend(deque, iterable);
878 if (rv == NULL)
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000879 return -1;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000880 Py_DECREF(rv);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000881 }
882 return 0;
883}
884
885static PySequenceMethods deque_as_sequence = {
Martin v. Löwis18e16552006-02-15 17:27:45 +0000886 (lenfunc)deque_len, /* sq_length */
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000887 0, /* sq_concat */
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000888 0, /* sq_repeat */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000889 (ssizeargfunc)deque_item, /* sq_item */
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000890 0, /* sq_slice */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000891 (ssizeobjargproc)deque_ass_item, /* sq_ass_item */
Raymond Hettinger287bef42009-12-10 05:56:49 +0000892 0, /* sq_ass_slice */
893 0, /* sq_contains */
894 (binaryfunc)deque_inplace_concat, /* sq_inplace_concat */
895 0, /* sq_inplace_repeat */
896
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000897};
898
899/* deque object ********************************************************/
900
901static PyObject *deque_iter(dequeobject *deque);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +0000902static PyObject *deque_reviter(dequeobject *deque);
Tim Peters1065f752004-10-01 01:03:29 +0000903PyDoc_STRVAR(reversed_doc,
Raymond Hettinger1e5809f2004-03-18 11:04:57 +0000904 "D.__reversed__() -- return a reverse iterator over the deque");
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000905
906static PyMethodDef deque_methods[] = {
Tim Peters1065f752004-10-01 01:03:29 +0000907 {"append", (PyCFunction)deque_append,
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000908 METH_O, append_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000909 {"appendleft", (PyCFunction)deque_appendleft,
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000910 METH_O, appendleft_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000911 {"clear", (PyCFunction)deque_clearmethod,
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000912 METH_NOARGS, clear_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000913 {"__copy__", (PyCFunction)deque_copy,
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000914 METH_NOARGS, copy_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000915 {"extend", (PyCFunction)deque_extend,
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000916 METH_O, extend_doc},
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000917 {"extendleft", (PyCFunction)deque_extendleft,
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000918 METH_O, extendleft_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000919 {"pop", (PyCFunction)deque_pop,
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000920 METH_NOARGS, pop_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000921 {"popleft", (PyCFunction)deque_popleft,
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000922 METH_NOARGS, popleft_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000923 {"__reduce__", (PyCFunction)deque_reduce,
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000924 METH_NOARGS, reduce_doc},
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000925 {"remove", (PyCFunction)deque_remove,
926 METH_O, remove_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000927 {"__reversed__", (PyCFunction)deque_reviter,
Raymond Hettinger1e5809f2004-03-18 11:04:57 +0000928 METH_NOARGS, reversed_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000929 {"rotate", (PyCFunction)deque_rotate,
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000930 METH_VARARGS, rotate_doc},
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000931 {NULL, NULL} /* sentinel */
932};
933
934PyDoc_STRVAR(deque_doc,
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000935"deque(iterable[, maxlen]) --> deque object\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000936\n\
937Build an ordered collection accessible from endpoints only.");
938
Neal Norwitz87f10132004-02-29 15:40:53 +0000939static PyTypeObject deque_type = {
Martin v. Löwis68192102007-07-21 06:55:02 +0000940 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000941 "collections.deque", /* tp_name */
942 sizeof(dequeobject), /* tp_basicsize */
943 0, /* tp_itemsize */
944 /* methods */
945 (destructor)deque_dealloc, /* tp_dealloc */
Georg Brandld37ac692006-03-30 11:58:57 +0000946 deque_tp_print, /* tp_print */
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000947 0, /* tp_getattr */
948 0, /* tp_setattr */
949 0, /* tp_compare */
Georg Brandld37ac692006-03-30 11:58:57 +0000950 deque_repr, /* tp_repr */
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000951 0, /* tp_as_number */
952 &deque_as_sequence, /* tp_as_sequence */
953 0, /* tp_as_mapping */
Nick Coghlan53663a62008-07-15 14:27:37 +0000954 (hashfunc)PyObject_HashNotImplemented, /* tp_hash */
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000955 0, /* tp_call */
956 0, /* tp_str */
957 PyObject_GenericGetAttr, /* tp_getattro */
958 0, /* tp_setattro */
959 0, /* tp_as_buffer */
Raymond Hettinger691d8052004-05-30 07:26:47 +0000960 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
961 Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000962 deque_doc, /* tp_doc */
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000963 (traverseproc)deque_traverse, /* tp_traverse */
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000964 (inquiry)deque_clear, /* tp_clear */
Raymond Hettinger738ec902004-02-29 02:15:56 +0000965 (richcmpfunc)deque_richcompare, /* tp_richcompare */
Raymond Hettinger691d8052004-05-30 07:26:47 +0000966 offsetof(dequeobject, weakreflist), /* tp_weaklistoffset*/
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000967 (getiterfunc)deque_iter, /* tp_iter */
968 0, /* tp_iternext */
969 deque_methods, /* tp_methods */
970 0, /* tp_members */
971 0, /* tp_getset */
972 0, /* tp_base */
973 0, /* tp_dict */
974 0, /* tp_descr_get */
975 0, /* tp_descr_set */
976 0, /* tp_dictoffset */
977 (initproc)deque_init, /* tp_init */
978 PyType_GenericAlloc, /* tp_alloc */
979 deque_new, /* tp_new */
980 PyObject_GC_Del, /* tp_free */
981};
982
983/*********************** Deque Iterator **************************/
984
985typedef struct {
986 PyObject_HEAD
Raymond Hettinger33fcf9d2008-07-24 00:08:18 +0000987 Py_ssize_t index;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000988 block *b;
989 dequeobject *deque;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +0000990 long state; /* state when the iterator is created */
Raymond Hettinger33fcf9d2008-07-24 00:08:18 +0000991 Py_ssize_t counter; /* number of items remaining for iteration */
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000992} dequeiterobject;
993
Martin v. Löwis111c1802008-06-13 07:47:47 +0000994static PyTypeObject dequeiter_type;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000995
996static PyObject *
997deque_iter(dequeobject *deque)
998{
999 dequeiterobject *it;
1000
Georg Brandl47fe9812009-01-01 15:46:10 +00001001 it = PyObject_GC_New(dequeiterobject, &dequeiter_type);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001002 if (it == NULL)
1003 return NULL;
1004 it->b = deque->leftblock;
1005 it->index = deque->leftindex;
1006 Py_INCREF(deque);
1007 it->deque = deque;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001008 it->state = deque->state;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001009 it->counter = deque->len;
Georg Brandl734373c2009-01-03 21:55:17 +00001010 PyObject_GC_Track(it);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001011 return (PyObject *)it;
1012}
1013
Georg Brandl47fe9812009-01-01 15:46:10 +00001014static int
1015dequeiter_traverse(dequeiterobject *dio, visitproc visit, void *arg)
1016{
1017 Py_VISIT(dio->deque);
1018 return 0;
1019}
1020
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001021static void
1022dequeiter_dealloc(dequeiterobject *dio)
1023{
1024 Py_XDECREF(dio->deque);
Georg Brandl47fe9812009-01-01 15:46:10 +00001025 PyObject_GC_Del(dio);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001026}
1027
1028static PyObject *
1029dequeiter_next(dequeiterobject *it)
1030{
1031 PyObject *item;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001032
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001033 if (it->deque->state != it->state) {
Raymond Hettinger7892b1c2004-04-12 18:10:01 +00001034 it->counter = 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001035 PyErr_SetString(PyExc_RuntimeError,
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001036 "deque mutated during iteration");
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001037 return NULL;
1038 }
Raymond Hettinger51c2f6c2007-01-08 18:09:20 +00001039 if (it->counter == 0)
1040 return NULL;
Tim Peters5566e962006-07-28 00:23:15 +00001041 assert (!(it->b == it->deque->rightblock &&
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001042 it->index > it->deque->rightindex));
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001043
1044 item = it->b->data[it->index];
1045 it->index++;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001046 it->counter--;
1047 if (it->index == BLOCKLEN && it->counter > 0) {
1048 assert (it->b->rightlink != NULL);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001049 it->b = it->b->rightlink;
1050 it->index = 0;
1051 }
1052 Py_INCREF(item);
1053 return item;
1054}
1055
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001056static PyObject *
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001057dequeiter_len(dequeiterobject *it)
1058{
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001059 return PyInt_FromLong(it->counter);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001060}
1061
Armin Rigof5b3e362006-02-11 21:32:43 +00001062PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001063
1064static PyMethodDef dequeiter_methods[] = {
Armin Rigof5b3e362006-02-11 21:32:43 +00001065 {"__length_hint__", (PyCFunction)dequeiter_len, METH_NOARGS, length_hint_doc},
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001066 {NULL, NULL} /* sentinel */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001067};
1068
Martin v. Löwis111c1802008-06-13 07:47:47 +00001069static PyTypeObject dequeiter_type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00001070 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001071 "deque_iterator", /* tp_name */
1072 sizeof(dequeiterobject), /* tp_basicsize */
1073 0, /* tp_itemsize */
1074 /* methods */
1075 (destructor)dequeiter_dealloc, /* tp_dealloc */
1076 0, /* tp_print */
1077 0, /* tp_getattr */
1078 0, /* tp_setattr */
1079 0, /* tp_compare */
1080 0, /* tp_repr */
1081 0, /* tp_as_number */
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001082 0, /* tp_as_sequence */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001083 0, /* tp_as_mapping */
1084 0, /* tp_hash */
1085 0, /* tp_call */
1086 0, /* tp_str */
1087 PyObject_GenericGetAttr, /* tp_getattro */
1088 0, /* tp_setattro */
1089 0, /* tp_as_buffer */
Georg Brandl47fe9812009-01-01 15:46:10 +00001090 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001091 0, /* tp_doc */
Georg Brandl47fe9812009-01-01 15:46:10 +00001092 (traverseproc)dequeiter_traverse, /* tp_traverse */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001093 0, /* tp_clear */
1094 0, /* tp_richcompare */
1095 0, /* tp_weaklistoffset */
1096 PyObject_SelfIter, /* tp_iter */
1097 (iternextfunc)dequeiter_next, /* tp_iternext */
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001098 dequeiter_methods, /* tp_methods */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001099 0,
1100};
1101
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001102/*********************** Deque Reverse Iterator **************************/
1103
Martin v. Löwis111c1802008-06-13 07:47:47 +00001104static PyTypeObject dequereviter_type;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001105
1106static PyObject *
1107deque_reviter(dequeobject *deque)
1108{
1109 dequeiterobject *it;
1110
Georg Brandl47fe9812009-01-01 15:46:10 +00001111 it = PyObject_GC_New(dequeiterobject, &dequereviter_type);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001112 if (it == NULL)
1113 return NULL;
1114 it->b = deque->rightblock;
1115 it->index = deque->rightindex;
1116 Py_INCREF(deque);
1117 it->deque = deque;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001118 it->state = deque->state;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001119 it->counter = deque->len;
Georg Brandl734373c2009-01-03 21:55:17 +00001120 PyObject_GC_Track(it);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001121 return (PyObject *)it;
1122}
1123
1124static PyObject *
1125dequereviter_next(dequeiterobject *it)
1126{
1127 PyObject *item;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001128 if (it->counter == 0)
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001129 return NULL;
1130
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001131 if (it->deque->state != it->state) {
Raymond Hettinger7892b1c2004-04-12 18:10:01 +00001132 it->counter = 0;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001133 PyErr_SetString(PyExc_RuntimeError,
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001134 "deque mutated during iteration");
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001135 return NULL;
1136 }
Tim Peters5566e962006-07-28 00:23:15 +00001137 assert (!(it->b == it->deque->leftblock &&
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001138 it->index < it->deque->leftindex));
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001139
1140 item = it->b->data[it->index];
1141 it->index--;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001142 it->counter--;
1143 if (it->index == -1 && it->counter > 0) {
1144 assert (it->b->leftlink != NULL);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001145 it->b = it->b->leftlink;
1146 it->index = BLOCKLEN - 1;
1147 }
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001148 Py_INCREF(item);
1149 return item;
1150}
1151
Martin v. Löwis111c1802008-06-13 07:47:47 +00001152static PyTypeObject dequereviter_type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00001153 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001154 "deque_reverse_iterator", /* tp_name */
1155 sizeof(dequeiterobject), /* tp_basicsize */
1156 0, /* tp_itemsize */
1157 /* methods */
1158 (destructor)dequeiter_dealloc, /* tp_dealloc */
1159 0, /* tp_print */
1160 0, /* tp_getattr */
1161 0, /* tp_setattr */
1162 0, /* tp_compare */
1163 0, /* tp_repr */
1164 0, /* tp_as_number */
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001165 0, /* tp_as_sequence */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001166 0, /* tp_as_mapping */
1167 0, /* tp_hash */
1168 0, /* tp_call */
1169 0, /* tp_str */
1170 PyObject_GenericGetAttr, /* tp_getattro */
1171 0, /* tp_setattro */
1172 0, /* tp_as_buffer */
Georg Brandl47fe9812009-01-01 15:46:10 +00001173 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001174 0, /* tp_doc */
Georg Brandl47fe9812009-01-01 15:46:10 +00001175 (traverseproc)dequeiter_traverse, /* tp_traverse */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001176 0, /* tp_clear */
1177 0, /* tp_richcompare */
1178 0, /* tp_weaklistoffset */
1179 PyObject_SelfIter, /* tp_iter */
1180 (iternextfunc)dequereviter_next, /* tp_iternext */
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001181 dequeiter_methods, /* tp_methods */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001182 0,
1183};
1184
Guido van Rossum1968ad32006-02-25 22:38:04 +00001185/* defaultdict type *********************************************************/
1186
1187typedef struct {
1188 PyDictObject dict;
1189 PyObject *default_factory;
1190} defdictobject;
1191
1192static PyTypeObject defdict_type; /* Forward */
1193
1194PyDoc_STRVAR(defdict_missing_doc,
1195"__missing__(key) # Called by __getitem__ for missing key; pseudo-code:\n\
Georg Brandlb51a57e2007-03-06 13:32:52 +00001196 if self.default_factory is None: raise KeyError((key,))\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00001197 self[key] = value = self.default_factory()\n\
1198 return value\n\
1199");
1200
1201static PyObject *
1202defdict_missing(defdictobject *dd, PyObject *key)
1203{
1204 PyObject *factory = dd->default_factory;
1205 PyObject *value;
1206 if (factory == NULL || factory == Py_None) {
1207 /* XXX Call dict.__missing__(key) */
Georg Brandlb51a57e2007-03-06 13:32:52 +00001208 PyObject *tup;
1209 tup = PyTuple_Pack(1, key);
1210 if (!tup) return NULL;
1211 PyErr_SetObject(PyExc_KeyError, tup);
1212 Py_DECREF(tup);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001213 return NULL;
1214 }
1215 value = PyEval_CallObject(factory, NULL);
1216 if (value == NULL)
1217 return value;
1218 if (PyObject_SetItem((PyObject *)dd, key, value) < 0) {
1219 Py_DECREF(value);
1220 return NULL;
1221 }
1222 return value;
1223}
1224
1225PyDoc_STRVAR(defdict_copy_doc, "D.copy() -> a shallow copy of D.");
1226
1227static PyObject *
1228defdict_copy(defdictobject *dd)
1229{
1230 /* This calls the object's class. That only works for subclasses
1231 whose class constructor has the same signature. Subclasses that
Raymond Hettingera37430a2008-02-12 19:05:36 +00001232 define a different constructor signature must override copy().
Guido van Rossum1968ad32006-02-25 22:38:04 +00001233 */
Raymond Hettingerd6119ef2009-08-04 18:49:26 +00001234
1235 if (dd->default_factory == NULL)
1236 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd), Py_None, dd, NULL);
Christian Heimese93237d2007-12-19 02:37:44 +00001237 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd),
Guido van Rossum1968ad32006-02-25 22:38:04 +00001238 dd->default_factory, dd, NULL);
1239}
1240
1241static PyObject *
1242defdict_reduce(defdictobject *dd)
1243{
Tim Peters5566e962006-07-28 00:23:15 +00001244 /* __reduce__ must return a 5-tuple as follows:
Guido van Rossum1968ad32006-02-25 22:38:04 +00001245
1246 - factory function
1247 - tuple of args for the factory function
1248 - additional state (here None)
1249 - sequence iterator (here None)
1250 - dictionary iterator (yielding successive (key, value) pairs
1251
1252 This API is used by pickle.py and copy.py.
1253
1254 For this to be useful with pickle.py, the default_factory
1255 must be picklable; e.g., None, a built-in, or a global
1256 function in a module or package.
1257
1258 Both shallow and deep copying are supported, but for deep
1259 copying, the default_factory must be deep-copyable; e.g. None,
1260 or a built-in (functions are not copyable at this time).
1261
1262 This only works for subclasses as long as their constructor
1263 signature is compatible; the first argument must be the
1264 optional default_factory, defaulting to None.
1265 */
1266 PyObject *args;
1267 PyObject *items;
1268 PyObject *result;
1269 if (dd->default_factory == NULL || dd->default_factory == Py_None)
1270 args = PyTuple_New(0);
1271 else
1272 args = PyTuple_Pack(1, dd->default_factory);
1273 if (args == NULL)
1274 return NULL;
1275 items = PyObject_CallMethod((PyObject *)dd, "iteritems", "()");
1276 if (items == NULL) {
1277 Py_DECREF(args);
1278 return NULL;
1279 }
Christian Heimese93237d2007-12-19 02:37:44 +00001280 result = PyTuple_Pack(5, Py_TYPE(dd), args,
Guido van Rossum1968ad32006-02-25 22:38:04 +00001281 Py_None, Py_None, items);
Tim Peters5566e962006-07-28 00:23:15 +00001282 Py_DECREF(items);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001283 Py_DECREF(args);
1284 return result;
1285}
1286
1287static PyMethodDef defdict_methods[] = {
1288 {"__missing__", (PyCFunction)defdict_missing, METH_O,
1289 defdict_missing_doc},
Raymond Hettingera37430a2008-02-12 19:05:36 +00001290 {"copy", (PyCFunction)defdict_copy, METH_NOARGS,
Guido van Rossum1968ad32006-02-25 22:38:04 +00001291 defdict_copy_doc},
1292 {"__copy__", (PyCFunction)defdict_copy, METH_NOARGS,
1293 defdict_copy_doc},
1294 {"__reduce__", (PyCFunction)defdict_reduce, METH_NOARGS,
1295 reduce_doc},
1296 {NULL}
1297};
1298
1299static PyMemberDef defdict_members[] = {
1300 {"default_factory", T_OBJECT,
1301 offsetof(defdictobject, default_factory), 0,
1302 PyDoc_STR("Factory for default value called by __missing__().")},
1303 {NULL}
1304};
1305
1306static void
1307defdict_dealloc(defdictobject *dd)
1308{
1309 Py_CLEAR(dd->default_factory);
1310 PyDict_Type.tp_dealloc((PyObject *)dd);
1311}
1312
1313static int
1314defdict_print(defdictobject *dd, FILE *fp, int flags)
1315{
1316 int sts;
Raymond Hettinger556b43d2007-10-05 19:07:31 +00001317 Py_BEGIN_ALLOW_THREADS
Guido van Rossum1968ad32006-02-25 22:38:04 +00001318 fprintf(fp, "defaultdict(");
Raymond Hettinger556b43d2007-10-05 19:07:31 +00001319 Py_END_ALLOW_THREADS
1320 if (dd->default_factory == NULL) {
1321 Py_BEGIN_ALLOW_THREADS
Guido van Rossum1968ad32006-02-25 22:38:04 +00001322 fprintf(fp, "None");
Raymond Hettinger556b43d2007-10-05 19:07:31 +00001323 Py_END_ALLOW_THREADS
1324 } else {
Guido van Rossum1968ad32006-02-25 22:38:04 +00001325 PyObject_Print(dd->default_factory, fp, 0);
1326 }
Raymond Hettinger556b43d2007-10-05 19:07:31 +00001327 Py_BEGIN_ALLOW_THREADS
Guido van Rossum1968ad32006-02-25 22:38:04 +00001328 fprintf(fp, ", ");
Raymond Hettinger556b43d2007-10-05 19:07:31 +00001329 Py_END_ALLOW_THREADS
Guido van Rossum1968ad32006-02-25 22:38:04 +00001330 sts = PyDict_Type.tp_print((PyObject *)dd, fp, 0);
Raymond Hettinger556b43d2007-10-05 19:07:31 +00001331 Py_BEGIN_ALLOW_THREADS
Guido van Rossum1968ad32006-02-25 22:38:04 +00001332 fprintf(fp, ")");
Raymond Hettinger556b43d2007-10-05 19:07:31 +00001333 Py_END_ALLOW_THREADS
Guido van Rossum1968ad32006-02-25 22:38:04 +00001334 return sts;
1335}
1336
1337static PyObject *
1338defdict_repr(defdictobject *dd)
1339{
1340 PyObject *defrepr;
1341 PyObject *baserepr;
1342 PyObject *result;
1343 baserepr = PyDict_Type.tp_repr((PyObject *)dd);
1344 if (baserepr == NULL)
1345 return NULL;
1346 if (dd->default_factory == NULL)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001347 defrepr = PyString_FromString("None");
Guido van Rossum1968ad32006-02-25 22:38:04 +00001348 else
Amaury Forgeot d'Arcb01aa432008-02-08 00:56:02 +00001349 {
1350 int status = Py_ReprEnter(dd->default_factory);
1351 if (status != 0) {
1352 if (status < 0)
1353 return NULL;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001354 defrepr = PyString_FromString("...");
Amaury Forgeot d'Arcb01aa432008-02-08 00:56:02 +00001355 }
1356 else
1357 defrepr = PyObject_Repr(dd->default_factory);
1358 Py_ReprLeave(dd->default_factory);
1359 }
Guido van Rossum1968ad32006-02-25 22:38:04 +00001360 if (defrepr == NULL) {
1361 Py_DECREF(baserepr);
1362 return NULL;
1363 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001364 result = PyString_FromFormat("defaultdict(%s, %s)",
1365 PyString_AS_STRING(defrepr),
1366 PyString_AS_STRING(baserepr));
Guido van Rossum1968ad32006-02-25 22:38:04 +00001367 Py_DECREF(defrepr);
1368 Py_DECREF(baserepr);
1369 return result;
1370}
1371
1372static int
1373defdict_traverse(PyObject *self, visitproc visit, void *arg)
1374{
1375 Py_VISIT(((defdictobject *)self)->default_factory);
1376 return PyDict_Type.tp_traverse(self, visit, arg);
1377}
1378
1379static int
1380defdict_tp_clear(defdictobject *dd)
1381{
Thomas Woutersedf17d82006-04-15 17:28:34 +00001382 Py_CLEAR(dd->default_factory);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001383 return PyDict_Type.tp_clear((PyObject *)dd);
1384}
1385
1386static int
1387defdict_init(PyObject *self, PyObject *args, PyObject *kwds)
1388{
1389 defdictobject *dd = (defdictobject *)self;
1390 PyObject *olddefault = dd->default_factory;
1391 PyObject *newdefault = NULL;
1392 PyObject *newargs;
1393 int result;
1394 if (args == NULL || !PyTuple_Check(args))
1395 newargs = PyTuple_New(0);
1396 else {
1397 Py_ssize_t n = PyTuple_GET_SIZE(args);
Raymond Hettinger5a0217e2007-02-07 21:42:17 +00001398 if (n > 0) {
Guido van Rossum1968ad32006-02-25 22:38:04 +00001399 newdefault = PyTuple_GET_ITEM(args, 0);
Raymond Hettingerd6119ef2009-08-04 18:49:26 +00001400 if (!PyCallable_Check(newdefault) && newdefault != Py_None) {
Raymond Hettinger5a0217e2007-02-07 21:42:17 +00001401 PyErr_SetString(PyExc_TypeError,
1402 "first argument must be callable");
1403 return -1;
1404 }
1405 }
Guido van Rossum1968ad32006-02-25 22:38:04 +00001406 newargs = PySequence_GetSlice(args, 1, n);
1407 }
1408 if (newargs == NULL)
1409 return -1;
1410 Py_XINCREF(newdefault);
1411 dd->default_factory = newdefault;
1412 result = PyDict_Type.tp_init(self, newargs, kwds);
1413 Py_DECREF(newargs);
1414 Py_XDECREF(olddefault);
1415 return result;
1416}
1417
1418PyDoc_STRVAR(defdict_doc,
1419"defaultdict(default_factory) --> dict with default factory\n\
1420\n\
1421The default factory is called without arguments to produce\n\
1422a new value when a key is not present, in __getitem__ only.\n\
1423A defaultdict compares equal to a dict with the same items.\n\
1424");
1425
Anthony Baxter3b8ff312006-04-04 15:05:23 +00001426/* See comment in xxsubtype.c */
1427#define DEFERRED_ADDRESS(ADDR) 0
1428
Guido van Rossum1968ad32006-02-25 22:38:04 +00001429static PyTypeObject defdict_type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00001430 PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0)
Guido van Rossum1968ad32006-02-25 22:38:04 +00001431 "collections.defaultdict", /* tp_name */
1432 sizeof(defdictobject), /* tp_basicsize */
1433 0, /* tp_itemsize */
1434 /* methods */
1435 (destructor)defdict_dealloc, /* tp_dealloc */
1436 (printfunc)defdict_print, /* tp_print */
1437 0, /* tp_getattr */
1438 0, /* tp_setattr */
1439 0, /* tp_compare */
1440 (reprfunc)defdict_repr, /* tp_repr */
1441 0, /* tp_as_number */
1442 0, /* tp_as_sequence */
1443 0, /* tp_as_mapping */
1444 0, /* tp_hash */
1445 0, /* tp_call */
1446 0, /* tp_str */
1447 PyObject_GenericGetAttr, /* tp_getattro */
1448 0, /* tp_setattro */
1449 0, /* tp_as_buffer */
1450 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
1451 Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
1452 defdict_doc, /* tp_doc */
Georg Brandld37ac692006-03-30 11:58:57 +00001453 defdict_traverse, /* tp_traverse */
Guido van Rossum1968ad32006-02-25 22:38:04 +00001454 (inquiry)defdict_tp_clear, /* tp_clear */
1455 0, /* tp_richcompare */
1456 0, /* tp_weaklistoffset*/
1457 0, /* tp_iter */
1458 0, /* tp_iternext */
1459 defdict_methods, /* tp_methods */
1460 defdict_members, /* tp_members */
1461 0, /* tp_getset */
Anthony Baxter3b8ff312006-04-04 15:05:23 +00001462 DEFERRED_ADDRESS(&PyDict_Type), /* tp_base */
Guido van Rossum1968ad32006-02-25 22:38:04 +00001463 0, /* tp_dict */
1464 0, /* tp_descr_get */
1465 0, /* tp_descr_set */
1466 0, /* tp_dictoffset */
Georg Brandld37ac692006-03-30 11:58:57 +00001467 defdict_init, /* tp_init */
Guido van Rossum1968ad32006-02-25 22:38:04 +00001468 PyType_GenericAlloc, /* tp_alloc */
1469 0, /* tp_new */
1470 PyObject_GC_Del, /* tp_free */
1471};
1472
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001473/* module level code ********************************************************/
1474
1475PyDoc_STRVAR(module_doc,
Guido van Rossum1968ad32006-02-25 22:38:04 +00001476"High performance data structures.\n\
1477- deque: ordered collection accessible from endpoints only\n\
1478- defaultdict: dict subclass with a default value factory\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001479");
1480
1481PyMODINIT_FUNC
Raymond Hettingereb979882007-02-28 18:37:52 +00001482init_collections(void)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001483{
1484 PyObject *m;
1485
Raymond Hettingereb979882007-02-28 18:37:52 +00001486 m = Py_InitModule3("_collections", NULL, module_doc);
Neal Norwitz1ac754f2006-01-19 06:09:39 +00001487 if (m == NULL)
1488 return;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001489
1490 if (PyType_Ready(&deque_type) < 0)
1491 return;
1492 Py_INCREF(&deque_type);
1493 PyModule_AddObject(m, "deque", (PyObject *)&deque_type);
1494
Anthony Baxter3b8ff312006-04-04 15:05:23 +00001495 defdict_type.tp_base = &PyDict_Type;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001496 if (PyType_Ready(&defdict_type) < 0)
1497 return;
1498 Py_INCREF(&defdict_type);
1499 PyModule_AddObject(m, "defaultdict", (PyObject *)&defdict_type);
1500
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001501 if (PyType_Ready(&dequeiter_type) < 0)
Tim Peters1065f752004-10-01 01:03:29 +00001502 return;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001503
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001504 if (PyType_Ready(&dequereviter_type) < 0)
1505 return;
1506
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001507 return;
1508}