blob: 978bd9a4bb00e53f4dff9428a8ecaa9563164825 [file] [log] [blame]
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001#include "Python.h"
Raymond Hettinger691d8052004-05-30 07:26:47 +00002#include "structmember.h"
Raymond Hettinger756b3f32004-01-29 06:37:52 +00003
4/* collections module implementation of a deque() datatype
5 Written and maintained by Raymond D. Hettinger <python@rcn.com>
6 Copyright (c) 2004 Python Software Foundation.
7 All rights reserved.
8*/
9
Raymond Hettinger77e8bf12004-10-01 15:25:53 +000010/* The block length may be set to any number over 1. Larger numbers
11 * reduce the number of calls to the memory allocator but take more
12 * memory. Ideally, BLOCKLEN should be set with an eye to the
Tim Peters5566e962006-07-28 00:23:15 +000013 * length of a cache line.
Raymond Hettinger77e8bf12004-10-01 15:25:53 +000014 */
15
Raymond Hettinger7d112df2004-11-02 02:11:35 +000016#define BLOCKLEN 62
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000017#define CENTER ((BLOCKLEN - 1) / 2)
Raymond Hettinger756b3f32004-01-29 06:37:52 +000018
Tim Petersd8768d32004-10-01 01:32:53 +000019/* A `dequeobject` is composed of a doubly-linked list of `block` nodes.
20 * This list is not circular (the leftmost block has leftlink==NULL,
21 * and the rightmost block has rightlink==NULL). A deque d's first
22 * element is at d.leftblock[leftindex] and its last element is at
23 * d.rightblock[rightindex]; note that, unlike as for Python slice
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000024 * indices, these indices are inclusive on both ends. By being inclusive
Tim Peters5566e962006-07-28 00:23:15 +000025 * on both ends, algorithms for left and right operations become
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000026 * symmetrical which simplifies the design.
Tim Peters5566e962006-07-28 00:23:15 +000027 *
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000028 * The list of blocks is never empty, so d.leftblock and d.rightblock
29 * are never equal to NULL.
30 *
31 * The indices, d.leftindex and d.rightindex are always in the range
32 * 0 <= index < BLOCKLEN.
Raymond Hettinger4ca4c7c2004-10-01 15:14:39 +000033 * Their exact relationship is:
34 * (d.leftindex + d.len - 1) % BLOCKLEN == d.rightindex.
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000035 *
36 * Empty deques have d.len == 0; d.leftblock==d.rightblock;
37 * d.leftindex == CENTER+1; and d.rightindex == CENTER.
38 * Checking for d.len == 0 is the intended way to see whether d is empty.
39 *
Tim Peters5566e962006-07-28 00:23:15 +000040 * Whenever d.leftblock == d.rightblock,
Raymond Hettinger4ca4c7c2004-10-01 15:14:39 +000041 * d.leftindex + d.len - 1 == d.rightindex.
Tim Peters5566e962006-07-28 00:23:15 +000042 *
Raymond Hettinger4ca4c7c2004-10-01 15:14:39 +000043 * However, when d.leftblock != d.rightblock, d.leftindex and d.rightindex
Tim Peters5566e962006-07-28 00:23:15 +000044 * become indices into distinct blocks and either may be larger than the
Raymond Hettinger4ca4c7c2004-10-01 15:14:39 +000045 * other.
Tim Petersd8768d32004-10-01 01:32:53 +000046 */
47
Raymond Hettinger756b3f32004-01-29 06:37:52 +000048typedef struct BLOCK {
49 struct BLOCK *leftlink;
50 struct BLOCK *rightlink;
51 PyObject *data[BLOCKLEN];
52} block;
53
Raymond Hettingerd3ffd342007-11-10 01:54:03 +000054#define MAXFREEBLOCKS 10
Raymond Hettinger33fcf9d2008-07-24 00:08:18 +000055static Py_ssize_t numfreeblocks = 0;
Raymond Hettingerd3ffd342007-11-10 01:54:03 +000056static block *freeblocks[MAXFREEBLOCKS];
57
Tim Peters6f853562004-10-01 01:04:50 +000058static block *
Raymond Hettinger33fcf9d2008-07-24 00:08:18 +000059newblock(block *leftlink, block *rightlink, Py_ssize_t len) {
Raymond Hettingerc5fa9922004-10-06 17:51:54 +000060 block *b;
Raymond Hettinger33fcf9d2008-07-24 00:08:18 +000061 /* To prevent len from overflowing PY_SSIZE_T_MAX on 64-bit machines, we
Raymond Hettingerc5fa9922004-10-06 17:51:54 +000062 * refuse to allocate new blocks if the current len is dangerously
63 * close. There is some extra margin to prevent spurious arithmetic
64 * overflows at various places. The following check ensures that
65 * the blocks allocated to the deque, in the worst case, can only
Raymond Hettinger33fcf9d2008-07-24 00:08:18 +000066 * have PY_SSIZE_T_MAX-2 entries in total.
Raymond Hettingerc5fa9922004-10-06 17:51:54 +000067 */
Raymond Hettinger33fcf9d2008-07-24 00:08:18 +000068 if (len >= PY_SSIZE_T_MAX - 2*BLOCKLEN) {
Raymond Hettingerc5fa9922004-10-06 17:51:54 +000069 PyErr_SetString(PyExc_OverflowError,
70 "cannot add more blocks to the deque");
71 return NULL;
72 }
Raymond Hettingerd3ffd342007-11-10 01:54:03 +000073 if (numfreeblocks) {
74 numfreeblocks -= 1;
75 b = freeblocks[numfreeblocks];
76 } else {
77 b = PyMem_Malloc(sizeof(block));
78 if (b == NULL) {
79 PyErr_NoMemory();
80 return NULL;
81 }
Raymond Hettinger756b3f32004-01-29 06:37:52 +000082 }
83 b->leftlink = leftlink;
84 b->rightlink = rightlink;
85 return b;
86}
87
Martin v. Löwis111c1802008-06-13 07:47:47 +000088static void
Raymond Hettingerd3ffd342007-11-10 01:54:03 +000089freeblock(block *b)
90{
91 if (numfreeblocks < MAXFREEBLOCKS) {
92 freeblocks[numfreeblocks] = b;
93 numfreeblocks++;
94 } else {
95 PyMem_Free(b);
96 }
97}
98
Raymond Hettinger756b3f32004-01-29 06:37:52 +000099typedef struct {
100 PyObject_HEAD
101 block *leftblock;
102 block *rightblock;
Raymond Hettinger33fcf9d2008-07-24 00:08:18 +0000103 Py_ssize_t leftindex; /* in range(BLOCKLEN) */
104 Py_ssize_t rightindex; /* in range(BLOCKLEN) */
105 Py_ssize_t len;
106 Py_ssize_t maxlen;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +0000107 long state; /* incremented whenever the indices move */
Raymond Hettinger691d8052004-05-30 07:26:47 +0000108 PyObject *weakreflist; /* List of weak references */
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000109} dequeobject;
110
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000111/* The deque's size limit is d.maxlen. The limit can be zero or positive.
112 * If there is no limit, then d.maxlen == -1.
113 *
114 * After an item is added to a deque, we check to see if the size has grown past
115 * the limit. If it has, we get the size back down to the limit by popping an
116 * item off of the opposite end. The methods that can trigger this are append(),
117 * appendleft(), extend(), and extendleft().
118 */
119
120#define TRIM(d, popfunction) \
121 if (d->maxlen != -1 && d->len > d->maxlen) { \
122 PyObject *rv = popfunction(d, NULL); \
123 assert(rv != NULL && d->len <= d->maxlen); \
124 Py_DECREF(rv); \
125 }
126
Neal Norwitz87f10132004-02-29 15:40:53 +0000127static PyTypeObject deque_type;
Raymond Hettinger738ec902004-02-29 02:15:56 +0000128
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000129static PyObject *
130deque_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
131{
132 dequeobject *deque;
133 block *b;
134
135 /* create dequeobject structure */
136 deque = (dequeobject *)type->tp_alloc(type, 0);
137 if (deque == NULL)
138 return NULL;
Tim Peters1065f752004-10-01 01:03:29 +0000139
Raymond Hettingerc5fa9922004-10-06 17:51:54 +0000140 b = newblock(NULL, NULL, 0);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000141 if (b == NULL) {
142 Py_DECREF(deque);
143 return NULL;
144 }
145
Raymond Hettinger61f05fb2004-10-01 06:24:12 +0000146 assert(BLOCKLEN >= 2);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000147 deque->leftblock = b;
148 deque->rightblock = b;
Raymond Hettinger61f05fb2004-10-01 06:24:12 +0000149 deque->leftindex = CENTER + 1;
150 deque->rightindex = CENTER;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000151 deque->len = 0;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +0000152 deque->state = 0;
Raymond Hettinger691d8052004-05-30 07:26:47 +0000153 deque->weakreflist = NULL;
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000154 deque->maxlen = -1;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000155
156 return (PyObject *)deque;
157}
158
159static PyObject *
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000160deque_pop(dequeobject *deque, PyObject *unused)
161{
162 PyObject *item;
163 block *prevblock;
164
165 if (deque->len == 0) {
Raymond Hettinger738ec902004-02-29 02:15:56 +0000166 PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000167 return NULL;
168 }
169 item = deque->rightblock->data[deque->rightindex];
170 deque->rightindex--;
171 deque->len--;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +0000172 deque->state++;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000173
174 if (deque->rightindex == -1) {
175 if (deque->len == 0) {
176 assert(deque->leftblock == deque->rightblock);
177 assert(deque->leftindex == deque->rightindex+1);
178 /* re-center instead of freeing a block */
Raymond Hettinger61f05fb2004-10-01 06:24:12 +0000179 deque->leftindex = CENTER + 1;
180 deque->rightindex = CENTER;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000181 } else {
182 prevblock = deque->rightblock->leftlink;
183 assert(deque->leftblock != deque->rightblock);
Raymond Hettingerd3ffd342007-11-10 01:54:03 +0000184 freeblock(deque->rightblock);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000185 prevblock->rightlink = NULL;
186 deque->rightblock = prevblock;
187 deque->rightindex = BLOCKLEN - 1;
188 }
189 }
190 return item;
191}
192
193PyDoc_STRVAR(pop_doc, "Remove and return the rightmost element.");
194
195static PyObject *
196deque_popleft(dequeobject *deque, PyObject *unused)
197{
198 PyObject *item;
199 block *prevblock;
200
201 if (deque->len == 0) {
Raymond Hettinger738ec902004-02-29 02:15:56 +0000202 PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000203 return NULL;
204 }
Neal Norwitzccc56c72006-08-13 18:13:02 +0000205 assert(deque->leftblock != NULL);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000206 item = deque->leftblock->data[deque->leftindex];
207 deque->leftindex++;
208 deque->len--;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +0000209 deque->state++;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000210
211 if (deque->leftindex == BLOCKLEN) {
212 if (deque->len == 0) {
213 assert(deque->leftblock == deque->rightblock);
214 assert(deque->leftindex == deque->rightindex+1);
215 /* re-center instead of freeing a block */
Raymond Hettinger61f05fb2004-10-01 06:24:12 +0000216 deque->leftindex = CENTER + 1;
217 deque->rightindex = CENTER;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000218 } else {
219 assert(deque->leftblock != deque->rightblock);
220 prevblock = deque->leftblock->rightlink;
Raymond Hettingerd3ffd342007-11-10 01:54:03 +0000221 freeblock(deque->leftblock);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000222 assert(prevblock != NULL);
223 prevblock->leftlink = NULL;
224 deque->leftblock = prevblock;
225 deque->leftindex = 0;
226 }
227 }
228 return item;
229}
230
231PyDoc_STRVAR(popleft_doc, "Remove and return the leftmost element.");
232
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000233static PyObject *
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000234deque_append(dequeobject *deque, PyObject *item)
235{
236 deque->state++;
237 if (deque->rightindex == BLOCKLEN-1) {
238 block *b = newblock(deque->rightblock, NULL, deque->len);
239 if (b == NULL)
240 return NULL;
241 assert(deque->rightblock->rightlink == NULL);
242 deque->rightblock->rightlink = b;
243 deque->rightblock = b;
244 deque->rightindex = -1;
245 }
246 Py_INCREF(item);
247 deque->len++;
248 deque->rightindex++;
249 deque->rightblock->data[deque->rightindex] = item;
250 TRIM(deque, deque_popleft);
251 Py_RETURN_NONE;
252}
253
254PyDoc_STRVAR(append_doc, "Add an element to the right side of the deque.");
255
256static PyObject *
257deque_appendleft(dequeobject *deque, PyObject *item)
258{
259 deque->state++;
260 if (deque->leftindex == 0) {
261 block *b = newblock(NULL, deque->leftblock, deque->len);
262 if (b == NULL)
263 return NULL;
264 assert(deque->leftblock->leftlink == NULL);
265 deque->leftblock->leftlink = b;
266 deque->leftblock = b;
267 deque->leftindex = BLOCKLEN;
268 }
269 Py_INCREF(item);
270 deque->len++;
271 deque->leftindex--;
272 deque->leftblock->data[deque->leftindex] = item;
273 TRIM(deque, deque_pop);
274 Py_RETURN_NONE;
275}
276
277PyDoc_STRVAR(appendleft_doc, "Add an element to the left side of the deque.");
278
Raymond Hettingerbac769b2009-03-10 09:31:48 +0000279
280/* Run an iterator to exhaustion. Shortcut for
281 the extend/extendleft methods when maxlen == 0. */
282static PyObject*
283consume_iterator(PyObject *it)
284{
285 PyObject *item;
286
287 while ((item = PyIter_Next(it)) != NULL) {
288 Py_DECREF(item);
289 }
290 Py_DECREF(it);
291 if (PyErr_Occurred())
292 return NULL;
293 Py_RETURN_NONE;
294}
295
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000296static PyObject *
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000297deque_extend(dequeobject *deque, PyObject *iterable)
298{
299 PyObject *it, *item;
300
Raymond Hettinger0b3263b2009-12-10 06:00:33 +0000301 /* Handle case where id(deque) == id(iterable) */
302 if ((PyObject *)deque == iterable) {
303 PyObject *result;
304 PyObject *s = PySequence_List(iterable);
305 if (s == NULL)
306 return NULL;
307 result = deque_extend(deque, s);
308 Py_DECREF(s);
309 return result;
310 }
311
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000312 it = PyObject_GetIter(iterable);
313 if (it == NULL)
314 return NULL;
315
Raymond Hettingerbac769b2009-03-10 09:31:48 +0000316 if (deque->maxlen == 0)
317 return consume_iterator(it);
318
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000319 while ((item = PyIter_Next(it)) != NULL) {
Raymond Hettingerd1b3d882004-10-02 00:43:13 +0000320 deque->state++;
Armin Rigo974d7572004-10-02 13:59:34 +0000321 if (deque->rightindex == BLOCKLEN-1) {
Raymond Hettingerc5fa9922004-10-06 17:51:54 +0000322 block *b = newblock(deque->rightblock, NULL,
323 deque->len);
Raymond Hettingerc058fd12004-02-07 02:45:22 +0000324 if (b == NULL) {
325 Py_DECREF(item);
326 Py_DECREF(it);
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000327 return NULL;
Raymond Hettingerc058fd12004-02-07 02:45:22 +0000328 }
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000329 assert(deque->rightblock->rightlink == NULL);
330 deque->rightblock->rightlink = b;
331 deque->rightblock = b;
Armin Rigo974d7572004-10-02 13:59:34 +0000332 deque->rightindex = -1;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000333 }
Armin Rigo974d7572004-10-02 13:59:34 +0000334 deque->len++;
335 deque->rightindex++;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000336 deque->rightblock->data[deque->rightindex] = item;
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000337 TRIM(deque, deque_popleft);
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000338 }
339 Py_DECREF(it);
Tim Peters1065f752004-10-01 01:03:29 +0000340 if (PyErr_Occurred())
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000341 return NULL;
342 Py_RETURN_NONE;
343}
344
Tim Peters1065f752004-10-01 01:03:29 +0000345PyDoc_STRVAR(extend_doc,
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000346"Extend the right side of the deque with elements from the iterable");
347
348static PyObject *
349deque_extendleft(dequeobject *deque, PyObject *iterable)
350{
351 PyObject *it, *item;
352
Raymond Hettinger0b3263b2009-12-10 06:00:33 +0000353 /* Handle case where id(deque) == id(iterable) */
354 if ((PyObject *)deque == iterable) {
355 PyObject *result;
356 PyObject *s = PySequence_List(iterable);
357 if (s == NULL)
358 return NULL;
359 result = deque_extendleft(deque, s);
360 Py_DECREF(s);
361 return result;
362 }
363
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000364 it = PyObject_GetIter(iterable);
365 if (it == NULL)
366 return NULL;
367
Raymond Hettingerbac769b2009-03-10 09:31:48 +0000368 if (deque->maxlen == 0)
369 return consume_iterator(it);
370
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000371 while ((item = PyIter_Next(it)) != NULL) {
Raymond Hettingerd1b3d882004-10-02 00:43:13 +0000372 deque->state++;
Armin Rigo974d7572004-10-02 13:59:34 +0000373 if (deque->leftindex == 0) {
Raymond Hettingerc5fa9922004-10-06 17:51:54 +0000374 block *b = newblock(NULL, deque->leftblock,
375 deque->len);
Raymond Hettingerc058fd12004-02-07 02:45:22 +0000376 if (b == NULL) {
377 Py_DECREF(item);
378 Py_DECREF(it);
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000379 return NULL;
Raymond Hettingerc058fd12004-02-07 02:45:22 +0000380 }
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000381 assert(deque->leftblock->leftlink == NULL);
382 deque->leftblock->leftlink = b;
383 deque->leftblock = b;
Armin Rigo974d7572004-10-02 13:59:34 +0000384 deque->leftindex = BLOCKLEN;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000385 }
Armin Rigo974d7572004-10-02 13:59:34 +0000386 deque->len++;
387 deque->leftindex--;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000388 deque->leftblock->data[deque->leftindex] = item;
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000389 TRIM(deque, deque_pop);
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000390 }
391 Py_DECREF(it);
Raymond Hettingera435c532004-07-09 04:10:20 +0000392 if (PyErr_Occurred())
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000393 return NULL;
394 Py_RETURN_NONE;
395}
396
Tim Peters1065f752004-10-01 01:03:29 +0000397PyDoc_STRVAR(extendleft_doc,
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000398"Extend the left side of the deque with elements from the iterable");
399
Raymond Hettinger0b3263b2009-12-10 06:00:33 +0000400static PyObject *
401deque_inplace_concat(dequeobject *deque, PyObject *other)
402{
403 PyObject *result;
404
405 result = deque_extend(deque, other);
406 if (result == NULL)
407 return result;
408 Py_DECREF(result);
409 Py_INCREF(deque);
410 return (PyObject *)deque;
411}
412
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000413static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000414_deque_rotate(dequeobject *deque, Py_ssize_t n)
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000415{
Raymond Hettinger33fcf9d2008-07-24 00:08:18 +0000416 Py_ssize_t i, len=deque->len, halflen=(len+1)>>1;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000417 PyObject *item, *rv;
418
Raymond Hettingeree33b272004-02-08 04:05:26 +0000419 if (len == 0)
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000420 return 0;
Raymond Hettingeree33b272004-02-08 04:05:26 +0000421 if (n > halflen || n < -halflen) {
422 n %= len;
423 if (n > halflen)
424 n -= len;
425 else if (n < -halflen)
426 n += len;
427 }
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000428
429 for (i=0 ; i<n ; i++) {
430 item = deque_pop(deque, NULL);
Raymond Hettingera435c532004-07-09 04:10:20 +0000431 assert (item != NULL);
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000432 rv = deque_appendleft(deque, item);
433 Py_DECREF(item);
434 if (rv == NULL)
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000435 return -1;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000436 Py_DECREF(rv);
437 }
438 for (i=0 ; i>n ; i--) {
439 item = deque_popleft(deque, NULL);
Raymond Hettingera435c532004-07-09 04:10:20 +0000440 assert (item != NULL);
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000441 rv = deque_append(deque, item);
442 Py_DECREF(item);
443 if (rv == NULL)
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000444 return -1;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000445 Py_DECREF(rv);
446 }
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000447 return 0;
448}
449
450static PyObject *
451deque_rotate(dequeobject *deque, PyObject *args)
452{
Raymond Hettinger33fcf9d2008-07-24 00:08:18 +0000453 Py_ssize_t n=1;
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000454
Raymond Hettinger723ba302008-07-24 00:53:49 +0000455 if (!PyArg_ParseTuple(args, "|n:rotate", &n))
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000456 return NULL;
457 if (_deque_rotate(deque, n) == 0)
458 Py_RETURN_NONE;
459 return NULL;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000460}
461
Tim Peters1065f752004-10-01 01:03:29 +0000462PyDoc_STRVAR(rotate_doc,
Raymond Hettingeree33b272004-02-08 04:05:26 +0000463"Rotate the deque n steps to the right (default n=1). If n is negative, rotates left.");
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000464
Raymond Hettingera5fd24e2009-12-10 06:42:54 +0000465static PyObject *
466deque_reverse(dequeobject *deque, PyObject *unused)
467{
468 block *leftblock = deque->leftblock;
469 block *rightblock = deque->rightblock;
470 Py_ssize_t leftindex = deque->leftindex;
471 Py_ssize_t rightindex = deque->rightindex;
472 Py_ssize_t n = (deque->len)/2;
473 Py_ssize_t i;
474 PyObject *tmp;
475
476 for (i=0 ; i<n ; i++) {
477 /* Validate that pointers haven't met in the middle */
478 assert(leftblock != rightblock || leftindex < rightindex);
479
480 /* Swap */
481 tmp = leftblock->data[leftindex];
482 leftblock->data[leftindex] = rightblock->data[rightindex];
483 rightblock->data[rightindex] = tmp;
484
485 /* Advance left block/index pair */
486 leftindex++;
487 if (leftindex == BLOCKLEN) {
488 assert (leftblock->rightlink != NULL);
489 leftblock = leftblock->rightlink;
490 leftindex = 0;
491 }
492
493 /* Step backwards with the right block/index pair */
494 rightindex--;
495 if (rightindex == -1) {
496 assert (rightblock->leftlink != NULL);
497 rightblock = rightblock->leftlink;
498 rightindex = BLOCKLEN - 1;
499 }
500 }
501 Py_RETURN_NONE;
502}
503
504PyDoc_STRVAR(reverse_doc,
505"D.reverse() -- reverse *IN PLACE*");
506
Martin v. Löwis18e16552006-02-15 17:27:45 +0000507static Py_ssize_t
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000508deque_len(dequeobject *deque)
509{
510 return deque->len;
511}
512
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000513static PyObject *
514deque_remove(dequeobject *deque, PyObject *value)
515{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000516 Py_ssize_t i, n=deque->len;
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000517
518 for (i=0 ; i<n ; i++) {
519 PyObject *item = deque->leftblock->data[deque->leftindex];
520 int cmp = PyObject_RichCompareBool(item, value, Py_EQ);
Raymond Hettingerd73202c2005-03-19 00:00:51 +0000521
522 if (deque->len != n) {
Tim Peters5566e962006-07-28 00:23:15 +0000523 PyErr_SetString(PyExc_IndexError,
Raymond Hettingerd73202c2005-03-19 00:00:51 +0000524 "deque mutated during remove().");
525 return NULL;
526 }
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000527 if (cmp > 0) {
Raymond Hettingerd73202c2005-03-19 00:00:51 +0000528 PyObject *tgt = deque_popleft(deque, NULL);
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000529 assert (tgt != NULL);
530 Py_DECREF(tgt);
531 if (_deque_rotate(deque, i) == -1)
532 return NULL;
533 Py_RETURN_NONE;
534 }
535 else if (cmp < 0) {
536 _deque_rotate(deque, i);
537 return NULL;
538 }
539 _deque_rotate(deque, -1);
540 }
541 PyErr_SetString(PyExc_ValueError, "deque.remove(x): x not in deque");
542 return NULL;
543}
544
545PyDoc_STRVAR(remove_doc,
546"D.remove(value) -- remove first occurrence of value.");
547
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000548static int
549deque_clear(dequeobject *deque)
550{
551 PyObject *item;
552
Raymond Hettingerd1b3d882004-10-02 00:43:13 +0000553 while (deque->len) {
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000554 item = deque_pop(deque, NULL);
Raymond Hettingera435c532004-07-09 04:10:20 +0000555 assert (item != NULL);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000556 Py_DECREF(item);
557 }
558 assert(deque->leftblock == deque->rightblock &&
Raymond Hettingerd1b3d882004-10-02 00:43:13 +0000559 deque->leftindex - 1 == deque->rightindex &&
560 deque->len == 0);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000561 return 0;
562}
563
564static PyObject *
Raymond Hettinger33fcf9d2008-07-24 00:08:18 +0000565deque_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000566{
567 block *b;
568 PyObject *item;
Raymond Hettinger33fcf9d2008-07-24 00:08:18 +0000569 Py_ssize_t n, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000570
571 if (i < 0 || i >= deque->len) {
572 PyErr_SetString(PyExc_IndexError,
573 "deque index out of range");
574 return NULL;
575 }
576
Raymond Hettinger6c79a512004-03-04 08:00:54 +0000577 if (i == 0) {
578 i = deque->leftindex;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000579 b = deque->leftblock;
Raymond Hettinger6c79a512004-03-04 08:00:54 +0000580 } else if (i == deque->len - 1) {
581 i = deque->rightindex;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000582 b = deque->rightblock;
Raymond Hettinger6c79a512004-03-04 08:00:54 +0000583 } else {
584 i += deque->leftindex;
585 n = i / BLOCKLEN;
586 i %= BLOCKLEN;
Armin Rigo974d7572004-10-02 13:59:34 +0000587 if (index < (deque->len >> 1)) {
Raymond Hettinger6c79a512004-03-04 08:00:54 +0000588 b = deque->leftblock;
589 while (n--)
590 b = b->rightlink;
591 } else {
592 n = (deque->leftindex + deque->len - 1) / BLOCKLEN - n;
593 b = deque->rightblock;
594 while (n--)
595 b = b->leftlink;
596 }
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000597 }
598 item = b->data[i];
599 Py_INCREF(item);
600 return item;
601}
602
Raymond Hettinger616f4f62004-06-26 04:42:06 +0000603/* delitem() implemented in terms of rotate for simplicity and reasonable
604 performance near the end points. If for some reason this method becomes
Tim Peters1065f752004-10-01 01:03:29 +0000605 popular, it is not hard to re-implement this using direct data movement
Raymond Hettinger616f4f62004-06-26 04:42:06 +0000606 (similar to code in list slice assignment) and achieve a two or threefold
607 performance boost.
608*/
609
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000610static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000611deque_del_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000612{
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000613 PyObject *item;
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000614
Tim Peters1065f752004-10-01 01:03:29 +0000615 assert (i >= 0 && i < deque->len);
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000616 if (_deque_rotate(deque, -i) == -1)
617 return -1;
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000618
619 item = deque_popleft(deque, NULL);
Raymond Hettingera435c532004-07-09 04:10:20 +0000620 assert (item != NULL);
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000621 Py_DECREF(item);
622
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000623 return _deque_rotate(deque, i);
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000624}
625
626static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000627deque_ass_item(dequeobject *deque, Py_ssize_t i, PyObject *v)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000628{
629 PyObject *old_value;
630 block *b;
Martin v. Löwisad0a4622006-02-16 14:30:23 +0000631 Py_ssize_t n, len=deque->len, halflen=(len+1)>>1, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000632
Raymond Hettingera435c532004-07-09 04:10:20 +0000633 if (i < 0 || i >= len) {
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000634 PyErr_SetString(PyExc_IndexError,
635 "deque index out of range");
636 return -1;
637 }
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000638 if (v == NULL)
639 return deque_del_item(deque, i);
640
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000641 i += deque->leftindex;
642 n = i / BLOCKLEN;
643 i %= BLOCKLEN;
Raymond Hettingera435c532004-07-09 04:10:20 +0000644 if (index <= halflen) {
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000645 b = deque->leftblock;
646 while (n--)
647 b = b->rightlink;
648 } else {
Raymond Hettingera435c532004-07-09 04:10:20 +0000649 n = (deque->leftindex + len - 1) / BLOCKLEN - n;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000650 b = deque->rightblock;
651 while (n--)
652 b = b->leftlink;
653 }
654 Py_INCREF(v);
655 old_value = b->data[i];
656 b->data[i] = v;
657 Py_DECREF(old_value);
658 return 0;
659}
660
661static PyObject *
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000662deque_clearmethod(dequeobject *deque)
663{
Raymond Hettingera435c532004-07-09 04:10:20 +0000664 int rv;
665
666 rv = deque_clear(deque);
667 assert (rv != -1);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000668 Py_RETURN_NONE;
669}
670
671PyDoc_STRVAR(clear_doc, "Remove all elements from the deque.");
672
673static void
674deque_dealloc(dequeobject *deque)
675{
676 PyObject_GC_UnTrack(deque);
Raymond Hettinger691d8052004-05-30 07:26:47 +0000677 if (deque->weakreflist != NULL)
678 PyObject_ClearWeakRefs((PyObject *) deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000679 if (deque->leftblock != NULL) {
Raymond Hettingere9c89e82004-07-19 00:10:24 +0000680 deque_clear(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000681 assert(deque->leftblock != NULL);
Raymond Hettingerd3ffd342007-11-10 01:54:03 +0000682 freeblock(deque->leftblock);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000683 }
684 deque->leftblock = NULL;
685 deque->rightblock = NULL;
Christian Heimese93237d2007-12-19 02:37:44 +0000686 Py_TYPE(deque)->tp_free(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000687}
688
689static int
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000690deque_traverse(dequeobject *deque, visitproc visit, void *arg)
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000691{
Tim Peters10c7e862004-10-01 02:01:04 +0000692 block *b;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000693 PyObject *item;
Raymond Hettinger33fcf9d2008-07-24 00:08:18 +0000694 Py_ssize_t index;
695 Py_ssize_t indexlo = deque->leftindex;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000696
Tim Peters10c7e862004-10-01 02:01:04 +0000697 for (b = deque->leftblock; b != NULL; b = b->rightlink) {
Raymond Hettinger33fcf9d2008-07-24 00:08:18 +0000698 const Py_ssize_t indexhi = b == deque->rightblock ?
Tim Peters10c7e862004-10-01 02:01:04 +0000699 deque->rightindex :
700 BLOCKLEN - 1;
701
702 for (index = indexlo; index <= indexhi; ++index) {
703 item = b->data[index];
704 Py_VISIT(item);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000705 }
Tim Peters10c7e862004-10-01 02:01:04 +0000706 indexlo = 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000707 }
708 return 0;
709}
710
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000711static PyObject *
712deque_copy(PyObject *deque)
713{
Raymond Hettinger68995862007-10-10 00:26:46 +0000714 if (((dequeobject *)deque)->maxlen == -1)
Christian Heimese93237d2007-12-19 02:37:44 +0000715 return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "O", deque, NULL);
Raymond Hettinger68995862007-10-10 00:26:46 +0000716 else
Christian Heimese93237d2007-12-19 02:37:44 +0000717 return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "Oi",
Raymond Hettinger68995862007-10-10 00:26:46 +0000718 deque, ((dequeobject *)deque)->maxlen, NULL);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000719}
720
721PyDoc_STRVAR(copy_doc, "Return a shallow copy of a deque.");
722
723static PyObject *
724deque_reduce(dequeobject *deque)
725{
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000726 PyObject *dict, *result, *aslist;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000727
Raymond Hettinger952f8802004-11-09 07:27:35 +0000728 dict = PyObject_GetAttrString((PyObject *)deque, "__dict__");
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000729 if (dict == NULL)
Raymond Hettinger952f8802004-11-09 07:27:35 +0000730 PyErr_Clear();
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000731 aslist = PySequence_List((PyObject *)deque);
732 if (aslist == NULL) {
Neal Norwitzc47cf7d2007-10-05 03:39:17 +0000733 Py_XDECREF(dict);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000734 return NULL;
735 }
Raymond Hettinger68995862007-10-10 00:26:46 +0000736 if (dict == NULL) {
737 if (deque->maxlen == -1)
Christian Heimese93237d2007-12-19 02:37:44 +0000738 result = Py_BuildValue("O(O)", Py_TYPE(deque), aslist);
Raymond Hettinger68995862007-10-10 00:26:46 +0000739 else
Raymond Hettinger33fcf9d2008-07-24 00:08:18 +0000740 result = Py_BuildValue("O(On)", Py_TYPE(deque), aslist, deque->maxlen);
Raymond Hettinger68995862007-10-10 00:26:46 +0000741 } else {
742 if (deque->maxlen == -1)
Christian Heimese93237d2007-12-19 02:37:44 +0000743 result = Py_BuildValue("O(OO)O", Py_TYPE(deque), aslist, Py_None, dict);
Raymond Hettinger68995862007-10-10 00:26:46 +0000744 else
Raymond Hettinger33fcf9d2008-07-24 00:08:18 +0000745 result = Py_BuildValue("O(On)O", Py_TYPE(deque), aslist, deque->maxlen, dict);
Raymond Hettinger68995862007-10-10 00:26:46 +0000746 }
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000747 Py_XDECREF(dict);
748 Py_DECREF(aslist);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000749 return result;
750}
751
752PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
753
754static PyObject *
755deque_repr(PyObject *deque)
756{
Raymond Hettinger556b43d2007-10-05 19:07:31 +0000757 PyObject *aslist, *result, *fmt;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000758 int i;
759
760 i = Py_ReprEnter(deque);
761 if (i != 0) {
762 if (i < 0)
763 return NULL;
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000764 return PyString_FromString("[...]");
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000765 }
766
767 aslist = PySequence_List(deque);
768 if (aslist == NULL) {
769 Py_ReprLeave(deque);
770 return NULL;
771 }
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000772 if (((dequeobject *)deque)->maxlen != -1)
Amaury Forgeot d'Arc05e34492008-09-10 22:04:45 +0000773 fmt = PyString_FromFormat("deque(%%r, maxlen=%zd)",
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000774 ((dequeobject *)deque)->maxlen);
775 else
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000776 fmt = PyString_FromString("deque(%r)");
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000777 if (fmt == NULL) {
778 Py_DECREF(aslist);
779 Py_ReprLeave(deque);
780 return NULL;
781 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000782 result = PyString_Format(fmt, aslist);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000783 Py_DECREF(fmt);
784 Py_DECREF(aslist);
785 Py_ReprLeave(deque);
786 return result;
787}
788
789static int
790deque_tp_print(PyObject *deque, FILE *fp, int flags)
791{
792 PyObject *it, *item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000793 char *emit = ""; /* No separator emitted on first pass */
794 char *separator = ", ";
795 int i;
796
797 i = Py_ReprEnter(deque);
798 if (i != 0) {
799 if (i < 0)
800 return i;
Raymond Hettinger556b43d2007-10-05 19:07:31 +0000801 Py_BEGIN_ALLOW_THREADS
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000802 fputs("[...]", fp);
Raymond Hettinger556b43d2007-10-05 19:07:31 +0000803 Py_END_ALLOW_THREADS
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000804 return 0;
805 }
806
807 it = PyObject_GetIter(deque);
808 if (it == NULL)
809 return -1;
810
Raymond Hettinger556b43d2007-10-05 19:07:31 +0000811 Py_BEGIN_ALLOW_THREADS
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000812 fputs("deque([", fp);
Raymond Hettinger556b43d2007-10-05 19:07:31 +0000813 Py_END_ALLOW_THREADS
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000814 while ((item = PyIter_Next(it)) != NULL) {
Raymond Hettinger556b43d2007-10-05 19:07:31 +0000815 Py_BEGIN_ALLOW_THREADS
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000816 fputs(emit, fp);
Raymond Hettinger556b43d2007-10-05 19:07:31 +0000817 Py_END_ALLOW_THREADS
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000818 emit = separator;
819 if (PyObject_Print(item, fp, 0) != 0) {
820 Py_DECREF(item);
821 Py_DECREF(it);
822 Py_ReprLeave(deque);
823 return -1;
824 }
825 Py_DECREF(item);
826 }
827 Py_ReprLeave(deque);
828 Py_DECREF(it);
Tim Peters1065f752004-10-01 01:03:29 +0000829 if (PyErr_Occurred())
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000830 return -1;
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000831
Raymond Hettinger556b43d2007-10-05 19:07:31 +0000832 Py_BEGIN_ALLOW_THREADS
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000833 if (((dequeobject *)deque)->maxlen == -1)
834 fputs("])", fp);
835 else
Christian Heimes1cc69632008-08-22 20:10:27 +0000836 fprintf(fp, "], maxlen=%" PY_FORMAT_SIZE_T "d)", ((dequeobject *)deque)->maxlen);
Raymond Hettinger556b43d2007-10-05 19:07:31 +0000837 Py_END_ALLOW_THREADS
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000838 return 0;
839}
840
Raymond Hettinger738ec902004-02-29 02:15:56 +0000841static PyObject *
842deque_richcompare(PyObject *v, PyObject *w, int op)
843{
844 PyObject *it1=NULL, *it2=NULL, *x, *y;
Raymond Hettinger33fcf9d2008-07-24 00:08:18 +0000845 Py_ssize_t vs, ws;
846 int b, cmp=-1;
Raymond Hettinger738ec902004-02-29 02:15:56 +0000847
Tim Peters1065f752004-10-01 01:03:29 +0000848 if (!PyObject_TypeCheck(v, &deque_type) ||
Raymond Hettinger285cfcc2004-05-18 18:15:03 +0000849 !PyObject_TypeCheck(w, &deque_type)) {
Raymond Hettinger738ec902004-02-29 02:15:56 +0000850 Py_INCREF(Py_NotImplemented);
851 return Py_NotImplemented;
852 }
853
854 /* Shortcuts */
855 vs = ((dequeobject *)v)->len;
856 ws = ((dequeobject *)w)->len;
857 if (op == Py_EQ) {
858 if (v == w)
859 Py_RETURN_TRUE;
860 if (vs != ws)
861 Py_RETURN_FALSE;
862 }
863 if (op == Py_NE) {
864 if (v == w)
865 Py_RETURN_FALSE;
866 if (vs != ws)
867 Py_RETURN_TRUE;
868 }
869
870 /* Search for the first index where items are different */
871 it1 = PyObject_GetIter(v);
872 if (it1 == NULL)
873 goto done;
874 it2 = PyObject_GetIter(w);
875 if (it2 == NULL)
876 goto done;
Armin Rigo974d7572004-10-02 13:59:34 +0000877 for (;;) {
Raymond Hettinger738ec902004-02-29 02:15:56 +0000878 x = PyIter_Next(it1);
Armin Rigo974d7572004-10-02 13:59:34 +0000879 if (x == NULL && PyErr_Occurred())
Raymond Hettinger738ec902004-02-29 02:15:56 +0000880 goto done;
881 y = PyIter_Next(it2);
Armin Rigo974d7572004-10-02 13:59:34 +0000882 if (x == NULL || y == NULL)
883 break;
Raymond Hettinger738ec902004-02-29 02:15:56 +0000884 b = PyObject_RichCompareBool(x, y, Py_EQ);
885 if (b == 0) {
886 cmp = PyObject_RichCompareBool(x, y, op);
887 Py_DECREF(x);
888 Py_DECREF(y);
889 goto done;
890 }
891 Py_DECREF(x);
892 Py_DECREF(y);
893 if (b == -1)
894 goto done;
895 }
Armin Rigo974d7572004-10-02 13:59:34 +0000896 /* We reached the end of one deque or both */
897 Py_XDECREF(x);
898 Py_XDECREF(y);
899 if (PyErr_Occurred())
900 goto done;
Raymond Hettinger738ec902004-02-29 02:15:56 +0000901 switch (op) {
Armin Rigo974d7572004-10-02 13:59:34 +0000902 case Py_LT: cmp = y != NULL; break; /* if w was longer */
903 case Py_LE: cmp = x == NULL; break; /* if v was not longer */
904 case Py_EQ: cmp = x == y; break; /* if we reached the end of both */
905 case Py_NE: cmp = x != y; break; /* if one deque continues */
906 case Py_GT: cmp = x != NULL; break; /* if v was longer */
907 case Py_GE: cmp = y == NULL; break; /* if w was not longer */
Raymond Hettinger738ec902004-02-29 02:15:56 +0000908 }
Tim Peters1065f752004-10-01 01:03:29 +0000909
Raymond Hettinger738ec902004-02-29 02:15:56 +0000910done:
911 Py_XDECREF(it1);
912 Py_XDECREF(it2);
913 if (cmp == 1)
914 Py_RETURN_TRUE;
915 if (cmp == 0)
916 Py_RETURN_FALSE;
917 return NULL;
918}
919
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000920static int
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000921deque_init(dequeobject *deque, PyObject *args, PyObject *kwdargs)
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000922{
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000923 PyObject *iterable = NULL;
Raymond Hettinger68995862007-10-10 00:26:46 +0000924 PyObject *maxlenobj = NULL;
Raymond Hettinger33fcf9d2008-07-24 00:08:18 +0000925 Py_ssize_t maxlen = -1;
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000926 char *kwlist[] = {"iterable", "maxlen", 0};
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000927
Raymond Hettinger68995862007-10-10 00:26:46 +0000928 if (!PyArg_ParseTupleAndKeywords(args, kwdargs, "|OO:deque", kwlist, &iterable, &maxlenobj))
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000929 return -1;
Raymond Hettinger68995862007-10-10 00:26:46 +0000930 if (maxlenobj != NULL && maxlenobj != Py_None) {
Raymond Hettinger33fcf9d2008-07-24 00:08:18 +0000931 maxlen = PyInt_AsSsize_t(maxlenobj);
Raymond Hettinger68995862007-10-10 00:26:46 +0000932 if (maxlen == -1 && PyErr_Occurred())
933 return -1;
934 if (maxlen < 0) {
935 PyErr_SetString(PyExc_ValueError, "maxlen must be non-negative");
936 return -1;
937 }
Raymond Hettingera7fc4b12007-10-05 02:47:07 +0000938 }
939 deque->maxlen = maxlen;
Raymond Hettingeradf9ffd2007-12-13 00:08:37 +0000940 deque_clear(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000941 if (iterable != NULL) {
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000942 PyObject *rv = deque_extend(deque, iterable);
943 if (rv == NULL)
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000944 return -1;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000945 Py_DECREF(rv);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000946 }
947 return 0;
948}
949
Raymond Hettinger56411aa2009-03-10 12:50:59 +0000950static PyObject *
951deque_get_maxlen(dequeobject *deque)
952{
953 if (deque->maxlen == -1)
954 Py_RETURN_NONE;
955 return PyInt_FromSsize_t(deque->maxlen);
956}
957
958static PyGetSetDef deque_getset[] = {
959 {"maxlen", (getter)deque_get_maxlen, (setter)NULL,
960 "maximum size of a deque or None if unbounded"},
961 {0}
962};
963
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000964static PySequenceMethods deque_as_sequence = {
Martin v. Löwis18e16552006-02-15 17:27:45 +0000965 (lenfunc)deque_len, /* sq_length */
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000966 0, /* sq_concat */
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000967 0, /* sq_repeat */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000968 (ssizeargfunc)deque_item, /* sq_item */
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000969 0, /* sq_slice */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000970 (ssizeobjargproc)deque_ass_item, /* sq_ass_item */
Raymond Hettinger0b3263b2009-12-10 06:00:33 +0000971 0, /* sq_ass_slice */
972 0, /* sq_contains */
973 (binaryfunc)deque_inplace_concat, /* sq_inplace_concat */
974 0, /* sq_inplace_repeat */
975
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000976};
977
978/* deque object ********************************************************/
979
980static PyObject *deque_iter(dequeobject *deque);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +0000981static PyObject *deque_reviter(dequeobject *deque);
Tim Peters1065f752004-10-01 01:03:29 +0000982PyDoc_STRVAR(reversed_doc,
Raymond Hettinger1e5809f2004-03-18 11:04:57 +0000983 "D.__reversed__() -- return a reverse iterator over the deque");
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000984
985static PyMethodDef deque_methods[] = {
Tim Peters1065f752004-10-01 01:03:29 +0000986 {"append", (PyCFunction)deque_append,
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000987 METH_O, append_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000988 {"appendleft", (PyCFunction)deque_appendleft,
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000989 METH_O, appendleft_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000990 {"clear", (PyCFunction)deque_clearmethod,
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000991 METH_NOARGS, clear_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000992 {"__copy__", (PyCFunction)deque_copy,
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000993 METH_NOARGS, copy_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000994 {"extend", (PyCFunction)deque_extend,
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000995 METH_O, extend_doc},
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000996 {"extendleft", (PyCFunction)deque_extendleft,
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000997 METH_O, extendleft_doc},
Tim Peters1065f752004-10-01 01:03:29 +0000998 {"pop", (PyCFunction)deque_pop,
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000999 METH_NOARGS, pop_doc},
Tim Peters1065f752004-10-01 01:03:29 +00001000 {"popleft", (PyCFunction)deque_popleft,
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001001 METH_NOARGS, popleft_doc},
Tim Peters1065f752004-10-01 01:03:29 +00001002 {"__reduce__", (PyCFunction)deque_reduce,
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001003 METH_NOARGS, reduce_doc},
Raymond Hettinger4aec61e2005-03-18 21:20:23 +00001004 {"remove", (PyCFunction)deque_remove,
1005 METH_O, remove_doc},
Tim Peters1065f752004-10-01 01:03:29 +00001006 {"__reversed__", (PyCFunction)deque_reviter,
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001007 METH_NOARGS, reversed_doc},
Raymond Hettingera5fd24e2009-12-10 06:42:54 +00001008 {"reverse", (PyCFunction)deque_reverse,
1009 METH_NOARGS, reverse_doc},
Tim Peters1065f752004-10-01 01:03:29 +00001010 {"rotate", (PyCFunction)deque_rotate,
Raymond Hettinger5c5eb862004-02-07 21:13:00 +00001011 METH_VARARGS, rotate_doc},
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001012 {NULL, NULL} /* sentinel */
1013};
1014
1015PyDoc_STRVAR(deque_doc,
Raymond Hettingera7fc4b12007-10-05 02:47:07 +00001016"deque(iterable[, maxlen]) --> deque object\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001017\n\
1018Build an ordered collection accessible from endpoints only.");
1019
Neal Norwitz87f10132004-02-29 15:40:53 +00001020static PyTypeObject deque_type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00001021 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001022 "collections.deque", /* tp_name */
1023 sizeof(dequeobject), /* tp_basicsize */
1024 0, /* tp_itemsize */
1025 /* methods */
1026 (destructor)deque_dealloc, /* tp_dealloc */
Georg Brandld37ac692006-03-30 11:58:57 +00001027 deque_tp_print, /* tp_print */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001028 0, /* tp_getattr */
1029 0, /* tp_setattr */
1030 0, /* tp_compare */
Georg Brandld37ac692006-03-30 11:58:57 +00001031 deque_repr, /* tp_repr */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001032 0, /* tp_as_number */
1033 &deque_as_sequence, /* tp_as_sequence */
1034 0, /* tp_as_mapping */
Nick Coghlan53663a62008-07-15 14:27:37 +00001035 (hashfunc)PyObject_HashNotImplemented, /* tp_hash */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001036 0, /* tp_call */
1037 0, /* tp_str */
1038 PyObject_GenericGetAttr, /* tp_getattro */
1039 0, /* tp_setattro */
1040 0, /* tp_as_buffer */
Raymond Hettinger691d8052004-05-30 07:26:47 +00001041 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
1042 Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001043 deque_doc, /* tp_doc */
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001044 (traverseproc)deque_traverse, /* tp_traverse */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001045 (inquiry)deque_clear, /* tp_clear */
Raymond Hettinger738ec902004-02-29 02:15:56 +00001046 (richcmpfunc)deque_richcompare, /* tp_richcompare */
Raymond Hettinger691d8052004-05-30 07:26:47 +00001047 offsetof(dequeobject, weakreflist), /* tp_weaklistoffset*/
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001048 (getiterfunc)deque_iter, /* tp_iter */
1049 0, /* tp_iternext */
1050 deque_methods, /* tp_methods */
1051 0, /* tp_members */
Raymond Hettinger56411aa2009-03-10 12:50:59 +00001052 deque_getset, /* tp_getset */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001053 0, /* tp_base */
1054 0, /* tp_dict */
1055 0, /* tp_descr_get */
1056 0, /* tp_descr_set */
1057 0, /* tp_dictoffset */
1058 (initproc)deque_init, /* tp_init */
1059 PyType_GenericAlloc, /* tp_alloc */
1060 deque_new, /* tp_new */
1061 PyObject_GC_Del, /* tp_free */
1062};
1063
1064/*********************** Deque Iterator **************************/
1065
1066typedef struct {
1067 PyObject_HEAD
Raymond Hettinger33fcf9d2008-07-24 00:08:18 +00001068 Py_ssize_t index;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001069 block *b;
1070 dequeobject *deque;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001071 long state; /* state when the iterator is created */
Raymond Hettinger33fcf9d2008-07-24 00:08:18 +00001072 Py_ssize_t counter; /* number of items remaining for iteration */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001073} dequeiterobject;
1074
Martin v. Löwis111c1802008-06-13 07:47:47 +00001075static PyTypeObject dequeiter_type;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001076
1077static PyObject *
1078deque_iter(dequeobject *deque)
1079{
1080 dequeiterobject *it;
1081
Antoine Pitrouaa687902009-01-01 14:11:22 +00001082 it = PyObject_GC_New(dequeiterobject, &dequeiter_type);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001083 if (it == NULL)
1084 return NULL;
1085 it->b = deque->leftblock;
1086 it->index = deque->leftindex;
1087 Py_INCREF(deque);
1088 it->deque = deque;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001089 it->state = deque->state;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001090 it->counter = deque->len;
Amaury Forgeot d'Arc57eb0e92009-01-02 00:03:54 +00001091 PyObject_GC_Track(it);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001092 return (PyObject *)it;
1093}
1094
Antoine Pitrouaa687902009-01-01 14:11:22 +00001095static int
1096dequeiter_traverse(dequeiterobject *dio, visitproc visit, void *arg)
1097{
1098 Py_VISIT(dio->deque);
1099 return 0;
1100}
1101
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001102static void
1103dequeiter_dealloc(dequeiterobject *dio)
1104{
1105 Py_XDECREF(dio->deque);
Antoine Pitrouaa687902009-01-01 14:11:22 +00001106 PyObject_GC_Del(dio);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001107}
1108
1109static PyObject *
1110dequeiter_next(dequeiterobject *it)
1111{
1112 PyObject *item;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001113
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001114 if (it->deque->state != it->state) {
Raymond Hettinger7892b1c2004-04-12 18:10:01 +00001115 it->counter = 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001116 PyErr_SetString(PyExc_RuntimeError,
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001117 "deque mutated during iteration");
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001118 return NULL;
1119 }
Raymond Hettinger51c2f6c2007-01-08 18:09:20 +00001120 if (it->counter == 0)
1121 return NULL;
Tim Peters5566e962006-07-28 00:23:15 +00001122 assert (!(it->b == it->deque->rightblock &&
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001123 it->index > it->deque->rightindex));
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001124
1125 item = it->b->data[it->index];
1126 it->index++;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001127 it->counter--;
1128 if (it->index == BLOCKLEN && it->counter > 0) {
1129 assert (it->b->rightlink != NULL);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001130 it->b = it->b->rightlink;
1131 it->index = 0;
1132 }
1133 Py_INCREF(item);
1134 return item;
1135}
1136
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001137static PyObject *
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001138dequeiter_len(dequeiterobject *it)
1139{
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001140 return PyInt_FromLong(it->counter);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001141}
1142
Armin Rigof5b3e362006-02-11 21:32:43 +00001143PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001144
1145static PyMethodDef dequeiter_methods[] = {
Armin Rigof5b3e362006-02-11 21:32:43 +00001146 {"__length_hint__", (PyCFunction)dequeiter_len, METH_NOARGS, length_hint_doc},
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001147 {NULL, NULL} /* sentinel */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001148};
1149
Martin v. Löwis111c1802008-06-13 07:47:47 +00001150static PyTypeObject dequeiter_type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00001151 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001152 "deque_iterator", /* tp_name */
1153 sizeof(dequeiterobject), /* tp_basicsize */
1154 0, /* tp_itemsize */
1155 /* methods */
1156 (destructor)dequeiter_dealloc, /* tp_dealloc */
1157 0, /* tp_print */
1158 0, /* tp_getattr */
1159 0, /* tp_setattr */
1160 0, /* tp_compare */
1161 0, /* tp_repr */
1162 0, /* tp_as_number */
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001163 0, /* tp_as_sequence */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001164 0, /* tp_as_mapping */
1165 0, /* tp_hash */
1166 0, /* tp_call */
1167 0, /* tp_str */
1168 PyObject_GenericGetAttr, /* tp_getattro */
1169 0, /* tp_setattro */
1170 0, /* tp_as_buffer */
Antoine Pitrouaa687902009-01-01 14:11:22 +00001171 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001172 0, /* tp_doc */
Antoine Pitrouaa687902009-01-01 14:11:22 +00001173 (traverseproc)dequeiter_traverse, /* tp_traverse */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001174 0, /* tp_clear */
1175 0, /* tp_richcompare */
1176 0, /* tp_weaklistoffset */
1177 PyObject_SelfIter, /* tp_iter */
1178 (iternextfunc)dequeiter_next, /* tp_iternext */
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001179 dequeiter_methods, /* tp_methods */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001180 0,
1181};
1182
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001183/*********************** Deque Reverse Iterator **************************/
1184
Martin v. Löwis111c1802008-06-13 07:47:47 +00001185static PyTypeObject dequereviter_type;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001186
1187static PyObject *
1188deque_reviter(dequeobject *deque)
1189{
1190 dequeiterobject *it;
1191
Antoine Pitrouaa687902009-01-01 14:11:22 +00001192 it = PyObject_GC_New(dequeiterobject, &dequereviter_type);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001193 if (it == NULL)
1194 return NULL;
1195 it->b = deque->rightblock;
1196 it->index = deque->rightindex;
1197 Py_INCREF(deque);
1198 it->deque = deque;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001199 it->state = deque->state;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001200 it->counter = deque->len;
Amaury Forgeot d'Arc57eb0e92009-01-02 00:03:54 +00001201 PyObject_GC_Track(it);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001202 return (PyObject *)it;
1203}
1204
1205static PyObject *
1206dequereviter_next(dequeiterobject *it)
1207{
1208 PyObject *item;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001209 if (it->counter == 0)
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001210 return NULL;
1211
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001212 if (it->deque->state != it->state) {
Raymond Hettinger7892b1c2004-04-12 18:10:01 +00001213 it->counter = 0;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001214 PyErr_SetString(PyExc_RuntimeError,
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001215 "deque mutated during iteration");
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001216 return NULL;
1217 }
Tim Peters5566e962006-07-28 00:23:15 +00001218 assert (!(it->b == it->deque->leftblock &&
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001219 it->index < it->deque->leftindex));
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001220
1221 item = it->b->data[it->index];
1222 it->index--;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001223 it->counter--;
1224 if (it->index == -1 && it->counter > 0) {
1225 assert (it->b->leftlink != NULL);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001226 it->b = it->b->leftlink;
1227 it->index = BLOCKLEN - 1;
1228 }
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001229 Py_INCREF(item);
1230 return item;
1231}
1232
Martin v. Löwis111c1802008-06-13 07:47:47 +00001233static PyTypeObject dequereviter_type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00001234 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001235 "deque_reverse_iterator", /* tp_name */
1236 sizeof(dequeiterobject), /* tp_basicsize */
1237 0, /* tp_itemsize */
1238 /* methods */
1239 (destructor)dequeiter_dealloc, /* tp_dealloc */
1240 0, /* tp_print */
1241 0, /* tp_getattr */
1242 0, /* tp_setattr */
1243 0, /* tp_compare */
1244 0, /* tp_repr */
1245 0, /* tp_as_number */
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001246 0, /* tp_as_sequence */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001247 0, /* tp_as_mapping */
1248 0, /* tp_hash */
1249 0, /* tp_call */
1250 0, /* tp_str */
1251 PyObject_GenericGetAttr, /* tp_getattro */
1252 0, /* tp_setattro */
1253 0, /* tp_as_buffer */
Antoine Pitrouaa687902009-01-01 14:11:22 +00001254 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001255 0, /* tp_doc */
Antoine Pitrouaa687902009-01-01 14:11:22 +00001256 (traverseproc)dequeiter_traverse, /* tp_traverse */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001257 0, /* tp_clear */
1258 0, /* tp_richcompare */
1259 0, /* tp_weaklistoffset */
1260 PyObject_SelfIter, /* tp_iter */
1261 (iternextfunc)dequereviter_next, /* tp_iternext */
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001262 dequeiter_methods, /* tp_methods */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001263 0,
1264};
1265
Guido van Rossum1968ad32006-02-25 22:38:04 +00001266/* defaultdict type *********************************************************/
1267
1268typedef struct {
1269 PyDictObject dict;
1270 PyObject *default_factory;
1271} defdictobject;
1272
1273static PyTypeObject defdict_type; /* Forward */
1274
1275PyDoc_STRVAR(defdict_missing_doc,
1276"__missing__(key) # Called by __getitem__ for missing key; pseudo-code:\n\
Georg Brandlb51a57e2007-03-06 13:32:52 +00001277 if self.default_factory is None: raise KeyError((key,))\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00001278 self[key] = value = self.default_factory()\n\
1279 return value\n\
1280");
1281
1282static PyObject *
1283defdict_missing(defdictobject *dd, PyObject *key)
1284{
1285 PyObject *factory = dd->default_factory;
1286 PyObject *value;
1287 if (factory == NULL || factory == Py_None) {
1288 /* XXX Call dict.__missing__(key) */
Georg Brandlb51a57e2007-03-06 13:32:52 +00001289 PyObject *tup;
1290 tup = PyTuple_Pack(1, key);
1291 if (!tup) return NULL;
1292 PyErr_SetObject(PyExc_KeyError, tup);
1293 Py_DECREF(tup);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001294 return NULL;
1295 }
1296 value = PyEval_CallObject(factory, NULL);
1297 if (value == NULL)
1298 return value;
1299 if (PyObject_SetItem((PyObject *)dd, key, value) < 0) {
1300 Py_DECREF(value);
1301 return NULL;
1302 }
1303 return value;
1304}
1305
1306PyDoc_STRVAR(defdict_copy_doc, "D.copy() -> a shallow copy of D.");
1307
1308static PyObject *
1309defdict_copy(defdictobject *dd)
1310{
1311 /* This calls the object's class. That only works for subclasses
1312 whose class constructor has the same signature. Subclasses that
Raymond Hettingera37430a2008-02-12 19:05:36 +00001313 define a different constructor signature must override copy().
Guido van Rossum1968ad32006-02-25 22:38:04 +00001314 */
Raymond Hettinger8fdab952009-08-04 19:08:05 +00001315
1316 if (dd->default_factory == NULL)
1317 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd), Py_None, dd, NULL);
Christian Heimese93237d2007-12-19 02:37:44 +00001318 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd),
Guido van Rossum1968ad32006-02-25 22:38:04 +00001319 dd->default_factory, dd, NULL);
1320}
1321
1322static PyObject *
1323defdict_reduce(defdictobject *dd)
1324{
Tim Peters5566e962006-07-28 00:23:15 +00001325 /* __reduce__ must return a 5-tuple as follows:
Guido van Rossum1968ad32006-02-25 22:38:04 +00001326
1327 - factory function
1328 - tuple of args for the factory function
1329 - additional state (here None)
1330 - sequence iterator (here None)
1331 - dictionary iterator (yielding successive (key, value) pairs
1332
1333 This API is used by pickle.py and copy.py.
1334
1335 For this to be useful with pickle.py, the default_factory
1336 must be picklable; e.g., None, a built-in, or a global
1337 function in a module or package.
1338
1339 Both shallow and deep copying are supported, but for deep
1340 copying, the default_factory must be deep-copyable; e.g. None,
1341 or a built-in (functions are not copyable at this time).
1342
1343 This only works for subclasses as long as their constructor
1344 signature is compatible; the first argument must be the
1345 optional default_factory, defaulting to None.
1346 */
1347 PyObject *args;
1348 PyObject *items;
1349 PyObject *result;
1350 if (dd->default_factory == NULL || dd->default_factory == Py_None)
1351 args = PyTuple_New(0);
1352 else
1353 args = PyTuple_Pack(1, dd->default_factory);
1354 if (args == NULL)
1355 return NULL;
1356 items = PyObject_CallMethod((PyObject *)dd, "iteritems", "()");
1357 if (items == NULL) {
1358 Py_DECREF(args);
1359 return NULL;
1360 }
Christian Heimese93237d2007-12-19 02:37:44 +00001361 result = PyTuple_Pack(5, Py_TYPE(dd), args,
Guido van Rossum1968ad32006-02-25 22:38:04 +00001362 Py_None, Py_None, items);
Tim Peters5566e962006-07-28 00:23:15 +00001363 Py_DECREF(items);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001364 Py_DECREF(args);
1365 return result;
1366}
1367
1368static PyMethodDef defdict_methods[] = {
1369 {"__missing__", (PyCFunction)defdict_missing, METH_O,
1370 defdict_missing_doc},
Raymond Hettingera37430a2008-02-12 19:05:36 +00001371 {"copy", (PyCFunction)defdict_copy, METH_NOARGS,
Guido van Rossum1968ad32006-02-25 22:38:04 +00001372 defdict_copy_doc},
1373 {"__copy__", (PyCFunction)defdict_copy, METH_NOARGS,
1374 defdict_copy_doc},
1375 {"__reduce__", (PyCFunction)defdict_reduce, METH_NOARGS,
1376 reduce_doc},
1377 {NULL}
1378};
1379
1380static PyMemberDef defdict_members[] = {
1381 {"default_factory", T_OBJECT,
1382 offsetof(defdictobject, default_factory), 0,
1383 PyDoc_STR("Factory for default value called by __missing__().")},
1384 {NULL}
1385};
1386
1387static void
1388defdict_dealloc(defdictobject *dd)
1389{
1390 Py_CLEAR(dd->default_factory);
1391 PyDict_Type.tp_dealloc((PyObject *)dd);
1392}
1393
1394static int
1395defdict_print(defdictobject *dd, FILE *fp, int flags)
1396{
1397 int sts;
Raymond Hettinger556b43d2007-10-05 19:07:31 +00001398 Py_BEGIN_ALLOW_THREADS
Guido van Rossum1968ad32006-02-25 22:38:04 +00001399 fprintf(fp, "defaultdict(");
Raymond Hettinger556b43d2007-10-05 19:07:31 +00001400 Py_END_ALLOW_THREADS
1401 if (dd->default_factory == NULL) {
1402 Py_BEGIN_ALLOW_THREADS
Guido van Rossum1968ad32006-02-25 22:38:04 +00001403 fprintf(fp, "None");
Raymond Hettinger556b43d2007-10-05 19:07:31 +00001404 Py_END_ALLOW_THREADS
1405 } else {
Guido van Rossum1968ad32006-02-25 22:38:04 +00001406 PyObject_Print(dd->default_factory, fp, 0);
1407 }
Raymond Hettinger556b43d2007-10-05 19:07:31 +00001408 Py_BEGIN_ALLOW_THREADS
Guido van Rossum1968ad32006-02-25 22:38:04 +00001409 fprintf(fp, ", ");
Raymond Hettinger556b43d2007-10-05 19:07:31 +00001410 Py_END_ALLOW_THREADS
Guido van Rossum1968ad32006-02-25 22:38:04 +00001411 sts = PyDict_Type.tp_print((PyObject *)dd, fp, 0);
Raymond Hettinger556b43d2007-10-05 19:07:31 +00001412 Py_BEGIN_ALLOW_THREADS
Guido van Rossum1968ad32006-02-25 22:38:04 +00001413 fprintf(fp, ")");
Raymond Hettinger556b43d2007-10-05 19:07:31 +00001414 Py_END_ALLOW_THREADS
Guido van Rossum1968ad32006-02-25 22:38:04 +00001415 return sts;
1416}
1417
1418static PyObject *
1419defdict_repr(defdictobject *dd)
1420{
1421 PyObject *defrepr;
1422 PyObject *baserepr;
1423 PyObject *result;
1424 baserepr = PyDict_Type.tp_repr((PyObject *)dd);
1425 if (baserepr == NULL)
1426 return NULL;
1427 if (dd->default_factory == NULL)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001428 defrepr = PyString_FromString("None");
Guido van Rossum1968ad32006-02-25 22:38:04 +00001429 else
Amaury Forgeot d'Arcb01aa432008-02-08 00:56:02 +00001430 {
1431 int status = Py_ReprEnter(dd->default_factory);
1432 if (status != 0) {
1433 if (status < 0)
1434 return NULL;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001435 defrepr = PyString_FromString("...");
Amaury Forgeot d'Arcb01aa432008-02-08 00:56:02 +00001436 }
1437 else
1438 defrepr = PyObject_Repr(dd->default_factory);
1439 Py_ReprLeave(dd->default_factory);
1440 }
Guido van Rossum1968ad32006-02-25 22:38:04 +00001441 if (defrepr == NULL) {
1442 Py_DECREF(baserepr);
1443 return NULL;
1444 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001445 result = PyString_FromFormat("defaultdict(%s, %s)",
1446 PyString_AS_STRING(defrepr),
1447 PyString_AS_STRING(baserepr));
Guido van Rossum1968ad32006-02-25 22:38:04 +00001448 Py_DECREF(defrepr);
1449 Py_DECREF(baserepr);
1450 return result;
1451}
1452
1453static int
1454defdict_traverse(PyObject *self, visitproc visit, void *arg)
1455{
1456 Py_VISIT(((defdictobject *)self)->default_factory);
1457 return PyDict_Type.tp_traverse(self, visit, arg);
1458}
1459
1460static int
1461defdict_tp_clear(defdictobject *dd)
1462{
Thomas Woutersedf17d82006-04-15 17:28:34 +00001463 Py_CLEAR(dd->default_factory);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001464 return PyDict_Type.tp_clear((PyObject *)dd);
1465}
1466
1467static int
1468defdict_init(PyObject *self, PyObject *args, PyObject *kwds)
1469{
1470 defdictobject *dd = (defdictobject *)self;
1471 PyObject *olddefault = dd->default_factory;
1472 PyObject *newdefault = NULL;
1473 PyObject *newargs;
1474 int result;
1475 if (args == NULL || !PyTuple_Check(args))
1476 newargs = PyTuple_New(0);
1477 else {
1478 Py_ssize_t n = PyTuple_GET_SIZE(args);
Raymond Hettinger5a0217e2007-02-07 21:42:17 +00001479 if (n > 0) {
Guido van Rossum1968ad32006-02-25 22:38:04 +00001480 newdefault = PyTuple_GET_ITEM(args, 0);
Raymond Hettinger8fdab952009-08-04 19:08:05 +00001481 if (!PyCallable_Check(newdefault) && newdefault != Py_None) {
Raymond Hettinger5a0217e2007-02-07 21:42:17 +00001482 PyErr_SetString(PyExc_TypeError,
1483 "first argument must be callable");
1484 return -1;
1485 }
1486 }
Guido van Rossum1968ad32006-02-25 22:38:04 +00001487 newargs = PySequence_GetSlice(args, 1, n);
1488 }
1489 if (newargs == NULL)
1490 return -1;
1491 Py_XINCREF(newdefault);
1492 dd->default_factory = newdefault;
1493 result = PyDict_Type.tp_init(self, newargs, kwds);
1494 Py_DECREF(newargs);
1495 Py_XDECREF(olddefault);
1496 return result;
1497}
1498
1499PyDoc_STRVAR(defdict_doc,
1500"defaultdict(default_factory) --> dict with default factory\n\
1501\n\
1502The default factory is called without arguments to produce\n\
1503a new value when a key is not present, in __getitem__ only.\n\
1504A defaultdict compares equal to a dict with the same items.\n\
1505");
1506
Anthony Baxter3b8ff312006-04-04 15:05:23 +00001507/* See comment in xxsubtype.c */
1508#define DEFERRED_ADDRESS(ADDR) 0
1509
Guido van Rossum1968ad32006-02-25 22:38:04 +00001510static PyTypeObject defdict_type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00001511 PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0)
Guido van Rossum1968ad32006-02-25 22:38:04 +00001512 "collections.defaultdict", /* tp_name */
1513 sizeof(defdictobject), /* tp_basicsize */
1514 0, /* tp_itemsize */
1515 /* methods */
1516 (destructor)defdict_dealloc, /* tp_dealloc */
1517 (printfunc)defdict_print, /* tp_print */
1518 0, /* tp_getattr */
1519 0, /* tp_setattr */
1520 0, /* tp_compare */
1521 (reprfunc)defdict_repr, /* tp_repr */
1522 0, /* tp_as_number */
1523 0, /* tp_as_sequence */
1524 0, /* tp_as_mapping */
1525 0, /* tp_hash */
1526 0, /* tp_call */
1527 0, /* tp_str */
1528 PyObject_GenericGetAttr, /* tp_getattro */
1529 0, /* tp_setattro */
1530 0, /* tp_as_buffer */
1531 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
1532 Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
1533 defdict_doc, /* tp_doc */
Georg Brandld37ac692006-03-30 11:58:57 +00001534 defdict_traverse, /* tp_traverse */
Guido van Rossum1968ad32006-02-25 22:38:04 +00001535 (inquiry)defdict_tp_clear, /* tp_clear */
1536 0, /* tp_richcompare */
1537 0, /* tp_weaklistoffset*/
1538 0, /* tp_iter */
1539 0, /* tp_iternext */
1540 defdict_methods, /* tp_methods */
1541 defdict_members, /* tp_members */
1542 0, /* tp_getset */
Anthony Baxter3b8ff312006-04-04 15:05:23 +00001543 DEFERRED_ADDRESS(&PyDict_Type), /* tp_base */
Guido van Rossum1968ad32006-02-25 22:38:04 +00001544 0, /* tp_dict */
1545 0, /* tp_descr_get */
1546 0, /* tp_descr_set */
1547 0, /* tp_dictoffset */
Georg Brandld37ac692006-03-30 11:58:57 +00001548 defdict_init, /* tp_init */
Guido van Rossum1968ad32006-02-25 22:38:04 +00001549 PyType_GenericAlloc, /* tp_alloc */
1550 0, /* tp_new */
1551 PyObject_GC_Del, /* tp_free */
1552};
1553
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001554/* module level code ********************************************************/
1555
1556PyDoc_STRVAR(module_doc,
Guido van Rossum1968ad32006-02-25 22:38:04 +00001557"High performance data structures.\n\
1558- deque: ordered collection accessible from endpoints only\n\
1559- defaultdict: dict subclass with a default value factory\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001560");
1561
1562PyMODINIT_FUNC
Raymond Hettingereb979882007-02-28 18:37:52 +00001563init_collections(void)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001564{
1565 PyObject *m;
1566
Raymond Hettingereb979882007-02-28 18:37:52 +00001567 m = Py_InitModule3("_collections", NULL, module_doc);
Neal Norwitz1ac754f2006-01-19 06:09:39 +00001568 if (m == NULL)
1569 return;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001570
1571 if (PyType_Ready(&deque_type) < 0)
1572 return;
1573 Py_INCREF(&deque_type);
1574 PyModule_AddObject(m, "deque", (PyObject *)&deque_type);
1575
Anthony Baxter3b8ff312006-04-04 15:05:23 +00001576 defdict_type.tp_base = &PyDict_Type;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001577 if (PyType_Ready(&defdict_type) < 0)
1578 return;
1579 Py_INCREF(&defdict_type);
1580 PyModule_AddObject(m, "defaultdict", (PyObject *)&defdict_type);
1581
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001582 if (PyType_Ready(&dequeiter_type) < 0)
Tim Peters1065f752004-10-01 01:03:29 +00001583 return;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001584
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001585 if (PyType_Ready(&dequereviter_type) < 0)
1586 return;
1587
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001588 return;
1589}