blob: ee17f4f28c5ebd5118df03ff2b3c1e796ca35875 [file] [log] [blame]
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001#include "Python.h"
Raymond Hettinger691d8052004-05-30 07:26:47 +00002#include "structmember.h"
Raymond Hettinger756b3f32004-01-29 06:37:52 +00003
4/* collections module implementation of a deque() datatype
5 Written and maintained by Raymond D. Hettinger <python@rcn.com>
6 Copyright (c) 2004 Python Software Foundation.
7 All rights reserved.
8*/
9
Raymond Hettinger77e8bf12004-10-01 15:25:53 +000010/* The block length may be set to any number over 1. Larger numbers
11 * reduce the number of calls to the memory allocator but take more
12 * memory. Ideally, BLOCKLEN should be set with an eye to the
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013 * length of a cache line.
Raymond Hettinger77e8bf12004-10-01 15:25:53 +000014 */
15
Raymond Hettinger7d112df2004-11-02 02:11:35 +000016#define BLOCKLEN 62
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000017#define CENTER ((BLOCKLEN - 1) / 2)
Raymond Hettinger756b3f32004-01-29 06:37:52 +000018
Tim Petersd8768d32004-10-01 01:32:53 +000019/* A `dequeobject` is composed of a doubly-linked list of `block` nodes.
20 * This list is not circular (the leftmost block has leftlink==NULL,
21 * and the rightmost block has rightlink==NULL). A deque d's first
22 * element is at d.leftblock[leftindex] and its last element is at
23 * d.rightblock[rightindex]; note that, unlike as for Python slice
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000024 * indices, these indices are inclusive on both ends. By being inclusive
Thomas Wouters0e3f5912006-08-11 14:57:12 +000025 * on both ends, algorithms for left and right operations become
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000026 * symmetrical which simplifies the design.
Thomas Wouters0e3f5912006-08-11 14:57:12 +000027 *
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000028 * The list of blocks is never empty, so d.leftblock and d.rightblock
29 * are never equal to NULL.
30 *
31 * The indices, d.leftindex and d.rightindex are always in the range
32 * 0 <= index < BLOCKLEN.
Raymond Hettinger4ca4c7c2004-10-01 15:14:39 +000033 * Their exact relationship is:
34 * (d.leftindex + d.len - 1) % BLOCKLEN == d.rightindex.
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000035 *
36 * Empty deques have d.len == 0; d.leftblock==d.rightblock;
37 * d.leftindex == CENTER+1; and d.rightindex == CENTER.
38 * Checking for d.len == 0 is the intended way to see whether d is empty.
39 *
Thomas Wouters0e3f5912006-08-11 14:57:12 +000040 * Whenever d.leftblock == d.rightblock,
Raymond Hettinger4ca4c7c2004-10-01 15:14:39 +000041 * d.leftindex + d.len - 1 == d.rightindex.
Thomas Wouters0e3f5912006-08-11 14:57:12 +000042 *
Raymond Hettinger4ca4c7c2004-10-01 15:14:39 +000043 * However, when d.leftblock != d.rightblock, d.leftindex and d.rightindex
Thomas Wouters0e3f5912006-08-11 14:57:12 +000044 * become indices into distinct blocks and either may be larger than the
Raymond Hettinger4ca4c7c2004-10-01 15:14:39 +000045 * other.
Tim Petersd8768d32004-10-01 01:32:53 +000046 */
47
Raymond Hettinger756b3f32004-01-29 06:37:52 +000048typedef struct BLOCK {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000049 struct BLOCK *leftlink;
50 struct BLOCK *rightlink;
51 PyObject *data[BLOCKLEN];
Raymond Hettinger756b3f32004-01-29 06:37:52 +000052} block;
53
Guido van Rossum58da9312007-11-10 23:39:45 +000054#define MAXFREEBLOCKS 10
Benjamin Petersond6313712008-07-31 16:23:04 +000055static Py_ssize_t numfreeblocks = 0;
Guido van Rossum58da9312007-11-10 23:39:45 +000056static block *freeblocks[MAXFREEBLOCKS];
57
Tim Peters6f853562004-10-01 01:04:50 +000058static block *
Benjamin Petersond6313712008-07-31 16:23:04 +000059newblock(block *leftlink, block *rightlink, Py_ssize_t len) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000060 block *b;
61 /* To prevent len from overflowing PY_SSIZE_T_MAX on 64-bit machines, we
62 * 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
66 * have PY_SSIZE_T_MAX-2 entries in total.
67 */
68 if (len >= PY_SSIZE_T_MAX - 2*BLOCKLEN) {
69 PyErr_SetString(PyExc_OverflowError,
70 "cannot add more blocks to the deque");
71 return NULL;
72 }
73 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 }
82 }
83 b->leftlink = leftlink;
84 b->rightlink = rightlink;
85 return b;
Raymond Hettinger756b3f32004-01-29 06:37:52 +000086}
87
Martin v. Löwis59683e82008-06-13 07:50:45 +000088static void
Guido van Rossum58da9312007-11-10 23:39:45 +000089freeblock(block *b)
90{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000091 if (numfreeblocks < MAXFREEBLOCKS) {
92 freeblocks[numfreeblocks] = b;
93 numfreeblocks++;
94 } else {
95 PyMem_Free(b);
96 }
Guido van Rossum58da9312007-11-10 23:39:45 +000097}
98
Raymond Hettinger756b3f32004-01-29 06:37:52 +000099typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000100 PyObject_HEAD
101 block *leftblock;
102 block *rightblock;
103 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;
107 long state; /* incremented whenever the indices move */
108 PyObject *weakreflist; /* List of weak references */
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000109} dequeobject;
110
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000111/* The deque's size limit is d.maxlen. The limit can be zero or positive.
112 * If there is no limit, then d.maxlen == -1.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000113 *
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000114 * 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
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000120#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); \
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000125 }
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{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000132 dequeobject *deque;
133 block *b;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000135 /* 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
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000140 b = newblock(NULL, NULL, 0);
141 if (b == NULL) {
142 Py_DECREF(deque);
143 return NULL;
144 }
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000145
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000146 assert(BLOCKLEN >= 2);
147 deque->leftblock = b;
148 deque->rightblock = b;
149 deque->leftindex = CENTER + 1;
150 deque->rightindex = CENTER;
151 deque->len = 0;
152 deque->state = 0;
153 deque->weakreflist = NULL;
154 deque->maxlen = -1;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000155
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000156 return (PyObject *)deque;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000157}
158
159static PyObject *
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000160deque_pop(dequeobject *deque, PyObject *unused)
161{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000162 PyObject *item;
163 block *prevblock;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000165 if (deque->len == 0) {
166 PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
167 return NULL;
168 }
169 item = deque->rightblock->data[deque->rightindex];
170 deque->rightindex--;
171 deque->len--;
172 deque->state++;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000174 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 */
179 deque->leftindex = CENTER + 1;
180 deque->rightindex = CENTER;
181 } else {
182 prevblock = deque->rightblock->leftlink;
183 assert(deque->leftblock != deque->rightblock);
184 freeblock(deque->rightblock);
185 prevblock->rightlink = NULL;
186 deque->rightblock = prevblock;
187 deque->rightindex = BLOCKLEN - 1;
188 }
189 }
190 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000191}
192
193PyDoc_STRVAR(pop_doc, "Remove and return the rightmost element.");
194
195static PyObject *
196deque_popleft(dequeobject *deque, PyObject *unused)
197{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000198 PyObject *item;
199 block *prevblock;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000201 if (deque->len == 0) {
202 PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
203 return NULL;
204 }
205 assert(deque->leftblock != NULL);
206 item = deque->leftblock->data[deque->leftindex];
207 deque->leftindex++;
208 deque->len--;
209 deque->state++;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000211 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 */
216 deque->leftindex = CENTER + 1;
217 deque->rightindex = CENTER;
218 } else {
219 assert(deque->leftblock != deque->rightblock);
220 prevblock = deque->leftblock->rightlink;
221 freeblock(deque->leftblock);
222 assert(prevblock != NULL);
223 prevblock->leftlink = NULL;
224 deque->leftblock = prevblock;
225 deque->leftindex = 0;
226 }
227 }
228 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000229}
230
231PyDoc_STRVAR(popleft_doc, "Remove and return the leftmost element.");
232
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000233static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000234deque_append(dequeobject *deque, PyObject *item)
235{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000236 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;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000252}
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{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000259 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;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000275}
276
277PyDoc_STRVAR(appendleft_doc, "Add an element to the left side of the deque.");
278
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280/* Run an iterator to exhaustion. Shortcut for
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000281 the extend/extendleft methods when maxlen == 0. */
282static PyObject*
283consume_iterator(PyObject *it)
284{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000285 PyObject *item;
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000287 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;
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000294}
295
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000296static PyObject *
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000297deque_extend(dequeobject *deque, PyObject *iterable)
298{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000299 PyObject *it, *item;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +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 }
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000312 it = PyObject_GetIter(iterable);
313 if (it == NULL)
314 return NULL;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000316 if (deque->maxlen == 0)
317 return consume_iterator(it);
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000318
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000319 while ((item = PyIter_Next(it)) != NULL) {
320 deque->state++;
321 if (deque->rightindex == BLOCKLEN-1) {
322 block *b = newblock(deque->rightblock, NULL,
323 deque->len);
324 if (b == NULL) {
325 Py_DECREF(item);
326 Py_DECREF(it);
327 return NULL;
328 }
329 assert(deque->rightblock->rightlink == NULL);
330 deque->rightblock->rightlink = b;
331 deque->rightblock = b;
332 deque->rightindex = -1;
333 }
334 deque->len++;
335 deque->rightindex++;
336 deque->rightblock->data[deque->rightindex] = item;
337 TRIM(deque, deque_popleft);
338 }
339 Py_DECREF(it);
340 if (PyErr_Occurred())
341 return NULL;
342 Py_RETURN_NONE;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000343}
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{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000351 PyObject *it, *item;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +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 }
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000364 it = PyObject_GetIter(iterable);
365 if (it == NULL)
366 return NULL;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000368 if (deque->maxlen == 0)
369 return consume_iterator(it);
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000371 while ((item = PyIter_Next(it)) != NULL) {
372 deque->state++;
373 if (deque->leftindex == 0) {
374 block *b = newblock(NULL, deque->leftblock,
375 deque->len);
376 if (b == NULL) {
377 Py_DECREF(item);
378 Py_DECREF(it);
379 return NULL;
380 }
381 assert(deque->leftblock->leftlink == NULL);
382 deque->leftblock->leftlink = b;
383 deque->leftblock = b;
384 deque->leftindex = BLOCKLEN;
385 }
386 deque->len++;
387 deque->leftindex--;
388 deque->leftblock->data[deque->leftindex] = item;
389 TRIM(deque, deque_pop);
390 }
391 Py_DECREF(it);
392 if (PyErr_Occurred())
393 return NULL;
394 Py_RETURN_NONE;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000395}
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 Hettinger3f9afd82009-12-10 03:03:02 +0000400static PyObject *
401deque_inplace_concat(dequeobject *deque, PyObject *other)
402{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000403 PyObject *result;
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000405 result = deque_extend(deque, other);
406 if (result == NULL)
407 return result;
408 Py_DECREF(result);
409 Py_INCREF(deque);
410 return (PyObject *)deque;
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000411}
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{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000416 Py_ssize_t i, len=deque->len, halflen=(len+1)>>1;
417 PyObject *item, *rv;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000418
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000419 if (len == 0)
420 return 0;
421 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
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000429 for (i=0 ; i<n ; i++) {
430 item = deque_pop(deque, NULL);
431 assert (item != NULL);
432 rv = deque_appendleft(deque, item);
433 Py_DECREF(item);
434 if (rv == NULL)
435 return -1;
436 Py_DECREF(rv);
437 }
438 for (i=0 ; i>n ; i--) {
439 item = deque_popleft(deque, NULL);
440 assert (item != NULL);
441 rv = deque_append(deque, item);
442 Py_DECREF(item);
443 if (rv == NULL)
444 return -1;
445 Py_DECREF(rv);
446 }
447 return 0;
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000448}
449
450static PyObject *
451deque_rotate(dequeobject *deque, PyObject *args)
452{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000453 Py_ssize_t n=1;
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000454
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000455 if (!PyArg_ParseTuple(args, "|n:rotate", &n))
456 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 Hettingere5fdedb2009-12-10 00:47:21 +0000465static PyObject *
466deque_reverse(dequeobject *deque, PyObject *unused)
467{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000468 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;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 for (i=0 ; i<n ; i++) {
477 /* Validate that pointers haven't met in the middle */
478 assert(leftblock != rightblock || leftindex < rightindex);
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000479
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000480 /* Swap */
481 tmp = leftblock->data[leftindex];
482 leftblock->data[leftindex] = rightblock->data[rightindex];
483 rightblock->data[rightindex] = tmp;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 /* Advance left block/index pair */
486 leftindex++;
487 if (leftindex == BLOCKLEN) {
Raymond Hettinger512d2cc2011-01-25 21:32:39 +0000488 if (leftblock->rightlink == NULL)
489 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 leftblock = leftblock->rightlink;
491 leftindex = 0;
492 }
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 /* Step backwards with the right block/index pair */
495 rightindex--;
496 if (rightindex == -1) {
Raymond Hettinger512d2cc2011-01-25 21:32:39 +0000497 if (rightblock->leftlink == NULL)
498 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000499 rightblock = rightblock->leftlink;
500 rightindex = BLOCKLEN - 1;
501 }
502 }
503 Py_RETURN_NONE;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000504}
505
506PyDoc_STRVAR(reverse_doc,
507"D.reverse() -- reverse *IN PLACE*");
508
Raymond Hettinger44459de2010-04-03 23:20:46 +0000509static PyObject *
510deque_count(dequeobject *deque, PyObject *v)
511{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 block *leftblock = deque->leftblock;
513 Py_ssize_t leftindex = deque->leftindex;
Raymond Hettinger512d2cc2011-01-25 21:32:39 +0000514 Py_ssize_t n = deque->len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000515 Py_ssize_t i;
516 Py_ssize_t count = 0;
517 PyObject *item;
518 long start_state = deque->state;
519 int cmp;
Raymond Hettinger44459de2010-04-03 23:20:46 +0000520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 for (i=0 ; i<n ; i++) {
522 item = leftblock->data[leftindex];
523 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
524 if (cmp > 0)
525 count++;
526 else if (cmp < 0)
527 return NULL;
Raymond Hettinger44459de2010-04-03 23:20:46 +0000528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000529 if (start_state != deque->state) {
530 PyErr_SetString(PyExc_RuntimeError,
531 "deque mutated during iteration");
532 return NULL;
533 }
Raymond Hettinger44459de2010-04-03 23:20:46 +0000534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 /* Advance left block/index pair */
536 leftindex++;
537 if (leftindex == BLOCKLEN) {
Raymond Hettinger512d2cc2011-01-25 21:32:39 +0000538 if (leftblock->rightlink == NULL) /* can occur when i==n-1 */
539 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000540 leftblock = leftblock->rightlink;
541 leftindex = 0;
542 }
543 }
544 return PyLong_FromSsize_t(count);
Raymond Hettinger44459de2010-04-03 23:20:46 +0000545}
546
547PyDoc_STRVAR(count_doc,
548"D.count(value) -> integer -- return number of occurrences of value");
549
Martin v. Löwis18e16552006-02-15 17:27:45 +0000550static Py_ssize_t
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000551deque_len(dequeobject *deque)
552{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000553 return deque->len;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000554}
555
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000556static PyObject *
557deque_remove(dequeobject *deque, PyObject *value)
558{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 Py_ssize_t i, n=deque->len;
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561 for (i=0 ; i<n ; i++) {
562 PyObject *item = deque->leftblock->data[deque->leftindex];
563 int cmp = PyObject_RichCompareBool(item, value, Py_EQ);
Raymond Hettingerd73202c2005-03-19 00:00:51 +0000564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000565 if (deque->len != n) {
566 PyErr_SetString(PyExc_IndexError,
567 "deque mutated during remove().");
568 return NULL;
569 }
570 if (cmp > 0) {
571 PyObject *tgt = deque_popleft(deque, NULL);
572 assert (tgt != NULL);
573 Py_DECREF(tgt);
574 if (_deque_rotate(deque, i) == -1)
575 return NULL;
576 Py_RETURN_NONE;
577 }
578 else if (cmp < 0) {
579 _deque_rotate(deque, i);
580 return NULL;
581 }
582 _deque_rotate(deque, -1);
583 }
584 PyErr_SetString(PyExc_ValueError, "deque.remove(x): x not in deque");
585 return NULL;
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000586}
587
588PyDoc_STRVAR(remove_doc,
589"D.remove(value) -- remove first occurrence of value.");
590
Benjamin Peterson0e5c48a2013-01-12 21:22:18 -0500591static void
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000592deque_clear(dequeobject *deque)
593{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 PyObject *item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 while (deque->len) {
597 item = deque_pop(deque, NULL);
598 assert (item != NULL);
599 Py_DECREF(item);
600 }
601 assert(deque->leftblock == deque->rightblock &&
602 deque->leftindex - 1 == deque->rightindex &&
603 deque->len == 0);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000604}
605
606static PyObject *
Benjamin Petersond6313712008-07-31 16:23:04 +0000607deque_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000608{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 block *b;
610 PyObject *item;
611 Py_ssize_t n, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000613 if (i < 0 || i >= deque->len) {
614 PyErr_SetString(PyExc_IndexError,
615 "deque index out of range");
616 return NULL;
617 }
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 if (i == 0) {
620 i = deque->leftindex;
621 b = deque->leftblock;
622 } else if (i == deque->len - 1) {
623 i = deque->rightindex;
624 b = deque->rightblock;
625 } else {
626 i += deque->leftindex;
627 n = i / BLOCKLEN;
628 i %= BLOCKLEN;
629 if (index < (deque->len >> 1)) {
630 b = deque->leftblock;
631 while (n--)
632 b = b->rightlink;
633 } else {
634 n = (deque->leftindex + deque->len - 1) / BLOCKLEN - n;
635 b = deque->rightblock;
636 while (n--)
637 b = b->leftlink;
638 }
639 }
640 item = b->data[i];
641 Py_INCREF(item);
642 return item;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000643}
644
Raymond Hettinger616f4f62004-06-26 04:42:06 +0000645/* delitem() implemented in terms of rotate for simplicity and reasonable
646 performance near the end points. If for some reason this method becomes
Tim Peters1065f752004-10-01 01:03:29 +0000647 popular, it is not hard to re-implement this using direct data movement
Raymond Hettinger616f4f62004-06-26 04:42:06 +0000648 (similar to code in list slice assignment) and achieve a two or threefold
649 performance boost.
650*/
651
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000652static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000653deque_del_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000654{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000655 PyObject *item;
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000657 assert (i >= 0 && i < deque->len);
658 if (_deque_rotate(deque, -i) == -1)
659 return -1;
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000660
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 item = deque_popleft(deque, NULL);
662 assert (item != NULL);
663 Py_DECREF(item);
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000664
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000665 return _deque_rotate(deque, i);
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000666}
667
668static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000669deque_ass_item(dequeobject *deque, Py_ssize_t i, PyObject *v)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000670{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000671 PyObject *old_value;
672 block *b;
673 Py_ssize_t n, len=deque->len, halflen=(len+1)>>1, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000674
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000675 if (i < 0 || i >= len) {
676 PyErr_SetString(PyExc_IndexError,
677 "deque index out of range");
678 return -1;
679 }
680 if (v == NULL)
681 return deque_del_item(deque, i);
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000682
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000683 i += deque->leftindex;
684 n = i / BLOCKLEN;
685 i %= BLOCKLEN;
686 if (index <= halflen) {
687 b = deque->leftblock;
688 while (n--)
689 b = b->rightlink;
690 } else {
691 n = (deque->leftindex + len - 1) / BLOCKLEN - n;
692 b = deque->rightblock;
693 while (n--)
694 b = b->leftlink;
695 }
696 Py_INCREF(v);
697 old_value = b->data[i];
698 b->data[i] = v;
699 Py_DECREF(old_value);
700 return 0;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000701}
702
703static PyObject *
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000704deque_clearmethod(dequeobject *deque)
705{
Benjamin Peterson0e5c48a2013-01-12 21:22:18 -0500706 deque_clear(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000707 Py_RETURN_NONE;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000708}
709
710PyDoc_STRVAR(clear_doc, "Remove all elements from the deque.");
711
712static void
713deque_dealloc(dequeobject *deque)
714{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 PyObject_GC_UnTrack(deque);
716 if (deque->weakreflist != NULL)
717 PyObject_ClearWeakRefs((PyObject *) deque);
718 if (deque->leftblock != NULL) {
719 deque_clear(deque);
720 assert(deque->leftblock != NULL);
721 freeblock(deque->leftblock);
722 }
723 deque->leftblock = NULL;
724 deque->rightblock = NULL;
725 Py_TYPE(deque)->tp_free(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000726}
727
728static int
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000729deque_traverse(dequeobject *deque, visitproc visit, void *arg)
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000730{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000731 block *b;
732 PyObject *item;
733 Py_ssize_t index;
734 Py_ssize_t indexlo = deque->leftindex;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 for (b = deque->leftblock; b != NULL; b = b->rightlink) {
737 const Py_ssize_t indexhi = b == deque->rightblock ?
738 deque->rightindex :
739 BLOCKLEN - 1;
Tim Peters10c7e862004-10-01 02:01:04 +0000740
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000741 for (index = indexlo; index <= indexhi; ++index) {
742 item = b->data[index];
743 Py_VISIT(item);
744 }
745 indexlo = 0;
746 }
747 return 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000748}
749
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000750static PyObject *
751deque_copy(PyObject *deque)
752{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000753 if (((dequeobject *)deque)->maxlen == -1)
754 return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "O", deque, NULL);
755 else
756 return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "Oi",
757 deque, ((dequeobject *)deque)->maxlen, NULL);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000758}
759
760PyDoc_STRVAR(copy_doc, "Return a shallow copy of a deque.");
761
762static PyObject *
763deque_reduce(dequeobject *deque)
764{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000765 PyObject *dict, *result, *aslist;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200766 _Py_IDENTIFIER(__dict__);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000767
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200768 dict = _PyObject_GetAttrId((PyObject *)deque, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000769 if (dict == NULL)
770 PyErr_Clear();
771 aslist = PySequence_List((PyObject *)deque);
772 if (aslist == NULL) {
773 Py_XDECREF(dict);
774 return NULL;
775 }
776 if (dict == NULL) {
777 if (deque->maxlen == -1)
778 result = Py_BuildValue("O(O)", Py_TYPE(deque), aslist);
779 else
780 result = Py_BuildValue("O(On)", Py_TYPE(deque), aslist, deque->maxlen);
781 } else {
782 if (deque->maxlen == -1)
783 result = Py_BuildValue("O(OO)O", Py_TYPE(deque), aslist, Py_None, dict);
784 else
785 result = Py_BuildValue("O(On)O", Py_TYPE(deque), aslist, deque->maxlen, dict);
786 }
787 Py_XDECREF(dict);
788 Py_DECREF(aslist);
789 return result;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000790}
791
792PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
793
794static PyObject *
795deque_repr(PyObject *deque)
796{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000797 PyObject *aslist, *result;
798 int i;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000799
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000800 i = Py_ReprEnter(deque);
801 if (i != 0) {
802 if (i < 0)
803 return NULL;
804 return PyUnicode_FromString("[...]");
805 }
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000807 aslist = PySequence_List(deque);
808 if (aslist == NULL) {
809 Py_ReprLeave(deque);
810 return NULL;
811 }
812 if (((dequeobject *)deque)->maxlen != -1)
Benjamin Petersona786b022008-08-25 21:05:21 +0000813
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000814 result = PyUnicode_FromFormat("deque(%R, maxlen=%zd)",
815 aslist, ((dequeobject *)deque)->maxlen);
816 else
817 result = PyUnicode_FromFormat("deque(%R)", aslist);
818 Py_DECREF(aslist);
819 Py_ReprLeave(deque);
820 return result;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000821}
822
Raymond Hettinger738ec902004-02-29 02:15:56 +0000823static PyObject *
824deque_richcompare(PyObject *v, PyObject *w, int op)
825{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000826 PyObject *it1=NULL, *it2=NULL, *x, *y;
827 Py_ssize_t vs, ws;
828 int b, cmp=-1;
Raymond Hettinger738ec902004-02-29 02:15:56 +0000829
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 if (!PyObject_TypeCheck(v, &deque_type) ||
831 !PyObject_TypeCheck(w, &deque_type)) {
Brian Curtindfc80e32011-08-10 20:28:54 -0500832 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000833 }
Raymond Hettinger738ec902004-02-29 02:15:56 +0000834
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 /* Shortcuts */
836 vs = ((dequeobject *)v)->len;
837 ws = ((dequeobject *)w)->len;
838 if (op == Py_EQ) {
839 if (v == w)
840 Py_RETURN_TRUE;
841 if (vs != ws)
842 Py_RETURN_FALSE;
843 }
844 if (op == Py_NE) {
845 if (v == w)
846 Py_RETURN_FALSE;
847 if (vs != ws)
848 Py_RETURN_TRUE;
849 }
Raymond Hettinger738ec902004-02-29 02:15:56 +0000850
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000851 /* Search for the first index where items are different */
852 it1 = PyObject_GetIter(v);
853 if (it1 == NULL)
854 goto done;
855 it2 = PyObject_GetIter(w);
856 if (it2 == NULL)
857 goto done;
858 for (;;) {
859 x = PyIter_Next(it1);
860 if (x == NULL && PyErr_Occurred())
861 goto done;
862 y = PyIter_Next(it2);
863 if (x == NULL || y == NULL)
864 break;
865 b = PyObject_RichCompareBool(x, y, Py_EQ);
866 if (b == 0) {
867 cmp = PyObject_RichCompareBool(x, y, op);
868 Py_DECREF(x);
869 Py_DECREF(y);
870 goto done;
871 }
872 Py_DECREF(x);
873 Py_DECREF(y);
874 if (b == -1)
875 goto done;
876 }
877 /* We reached the end of one deque or both */
878 Py_XDECREF(x);
879 Py_XDECREF(y);
880 if (PyErr_Occurred())
881 goto done;
882 switch (op) {
883 case Py_LT: cmp = y != NULL; break; /* if w was longer */
884 case Py_LE: cmp = x == NULL; break; /* if v was not longer */
885 case Py_EQ: cmp = x == y; break; /* if we reached the end of both */
886 case Py_NE: cmp = x != y; break; /* if one deque continues */
887 case Py_GT: cmp = x != NULL; break; /* if v was longer */
888 case Py_GE: cmp = y == NULL; break; /* if w was not longer */
889 }
Tim Peters1065f752004-10-01 01:03:29 +0000890
Raymond Hettinger738ec902004-02-29 02:15:56 +0000891done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000892 Py_XDECREF(it1);
893 Py_XDECREF(it2);
894 if (cmp == 1)
895 Py_RETURN_TRUE;
896 if (cmp == 0)
897 Py_RETURN_FALSE;
898 return NULL;
Raymond Hettinger738ec902004-02-29 02:15:56 +0000899}
900
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000901static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000902deque_init(dequeobject *deque, PyObject *args, PyObject *kwdargs)
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000903{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000904 PyObject *iterable = NULL;
905 PyObject *maxlenobj = NULL;
906 Py_ssize_t maxlen = -1;
907 char *kwlist[] = {"iterable", "maxlen", 0};
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000908
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000909 if (!PyArg_ParseTupleAndKeywords(args, kwdargs, "|OO:deque", kwlist, &iterable, &maxlenobj))
910 return -1;
911 if (maxlenobj != NULL && maxlenobj != Py_None) {
912 maxlen = PyLong_AsSsize_t(maxlenobj);
913 if (maxlen == -1 && PyErr_Occurred())
914 return -1;
915 if (maxlen < 0) {
916 PyErr_SetString(PyExc_ValueError, "maxlen must be non-negative");
917 return -1;
918 }
919 }
920 deque->maxlen = maxlen;
921 deque_clear(deque);
922 if (iterable != NULL) {
923 PyObject *rv = deque_extend(deque, iterable);
924 if (rv == NULL)
925 return -1;
926 Py_DECREF(rv);
927 }
928 return 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000929}
930
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +0000931static PyObject *
Jesus Cea16e2fca2012-08-03 14:49:42 +0200932deque_sizeof(dequeobject *deque, void *unused)
933{
934 Py_ssize_t res;
935 Py_ssize_t blocks;
936
937 res = sizeof(dequeobject);
938 blocks = (deque->leftindex + deque->len + BLOCKLEN - 1) / BLOCKLEN;
939 assert(deque->leftindex + deque->len - 1 ==
940 (blocks - 1) * BLOCKLEN + deque->rightindex);
941 res += blocks * sizeof(block);
942 return PyLong_FromSsize_t(res);
943}
944
945PyDoc_STRVAR(sizeof_doc,
946"D.__sizeof__() -- size of D in memory, in bytes");
947
948static PyObject *
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +0000949deque_get_maxlen(dequeobject *deque)
950{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 if (deque->maxlen == -1)
952 Py_RETURN_NONE;
953 return PyLong_FromSsize_t(deque->maxlen);
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +0000954}
955
956static PyGetSetDef deque_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000957 {"maxlen", (getter)deque_get_maxlen, (setter)NULL,
958 "maximum size of a deque or None if unbounded"},
959 {0}
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +0000960};
961
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000962static PySequenceMethods deque_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000963 (lenfunc)deque_len, /* sq_length */
964 0, /* sq_concat */
965 0, /* sq_repeat */
966 (ssizeargfunc)deque_item, /* sq_item */
967 0, /* sq_slice */
968 (ssizeobjargproc)deque_ass_item, /* sq_ass_item */
969 0, /* sq_ass_slice */
970 0, /* sq_contains */
971 (binaryfunc)deque_inplace_concat, /* sq_inplace_concat */
972 0, /* sq_inplace_repeat */
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000973
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000974};
975
976/* deque object ********************************************************/
977
978static PyObject *deque_iter(dequeobject *deque);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +0000979static PyObject *deque_reviter(dequeobject *deque);
Tim Peters1065f752004-10-01 01:03:29 +0000980PyDoc_STRVAR(reversed_doc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000981 "D.__reversed__() -- return a reverse iterator over the deque");
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000982
983static PyMethodDef deque_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000984 {"append", (PyCFunction)deque_append,
985 METH_O, append_doc},
986 {"appendleft", (PyCFunction)deque_appendleft,
987 METH_O, appendleft_doc},
988 {"clear", (PyCFunction)deque_clearmethod,
989 METH_NOARGS, clear_doc},
990 {"__copy__", (PyCFunction)deque_copy,
991 METH_NOARGS, copy_doc},
992 {"count", (PyCFunction)deque_count,
993 METH_O, count_doc},
994 {"extend", (PyCFunction)deque_extend,
995 METH_O, extend_doc},
996 {"extendleft", (PyCFunction)deque_extendleft,
997 METH_O, extendleft_doc},
998 {"pop", (PyCFunction)deque_pop,
999 METH_NOARGS, pop_doc},
1000 {"popleft", (PyCFunction)deque_popleft,
1001 METH_NOARGS, popleft_doc},
1002 {"__reduce__", (PyCFunction)deque_reduce,
1003 METH_NOARGS, reduce_doc},
1004 {"remove", (PyCFunction)deque_remove,
1005 METH_O, remove_doc},
1006 {"__reversed__", (PyCFunction)deque_reviter,
1007 METH_NOARGS, reversed_doc},
1008 {"reverse", (PyCFunction)deque_reverse,
1009 METH_NOARGS, reverse_doc},
1010 {"rotate", (PyCFunction)deque_rotate,
Jesus Cea16e2fca2012-08-03 14:49:42 +02001011 METH_VARARGS, rotate_doc},
1012 {"__sizeof__", (PyCFunction)deque_sizeof,
1013 METH_NOARGS, sizeof_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 {NULL, NULL} /* sentinel */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001015};
1016
1017PyDoc_STRVAR(deque_doc,
Andrew Svetlov6a5c7c32012-10-31 11:50:40 +02001018"deque([iterable[, maxlen]]) --> deque object\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001019\n\
Raymond Hettinger49747052011-03-29 17:36:31 -07001020Build an ordered collection with optimized access from its endpoints.");
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001021
Neal Norwitz87f10132004-02-29 15:40:53 +00001022static PyTypeObject deque_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001023 PyVarObject_HEAD_INIT(NULL, 0)
1024 "collections.deque", /* tp_name */
1025 sizeof(dequeobject), /* tp_basicsize */
1026 0, /* tp_itemsize */
1027 /* methods */
1028 (destructor)deque_dealloc, /* tp_dealloc */
1029 0, /* tp_print */
1030 0, /* tp_getattr */
1031 0, /* tp_setattr */
1032 0, /* tp_reserved */
1033 deque_repr, /* tp_repr */
1034 0, /* tp_as_number */
1035 &deque_as_sequence, /* tp_as_sequence */
1036 0, /* tp_as_mapping */
Georg Brandlf038b322010-10-18 07:35:09 +00001037 PyObject_HashNotImplemented, /* tp_hash */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 0, /* tp_call */
1039 0, /* tp_str */
1040 PyObject_GenericGetAttr, /* tp_getattro */
1041 0, /* tp_setattro */
1042 0, /* tp_as_buffer */
1043 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
Georg Brandlf038b322010-10-18 07:35:09 +00001044 /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001045 deque_doc, /* tp_doc */
1046 (traverseproc)deque_traverse, /* tp_traverse */
1047 (inquiry)deque_clear, /* tp_clear */
1048 (richcmpfunc)deque_richcompare, /* tp_richcompare */
Georg Brandlf038b322010-10-18 07:35:09 +00001049 offsetof(dequeobject, weakreflist), /* tp_weaklistoffset*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 (getiterfunc)deque_iter, /* tp_iter */
1051 0, /* tp_iternext */
1052 deque_methods, /* tp_methods */
1053 0, /* tp_members */
Georg Brandlf038b322010-10-18 07:35:09 +00001054 deque_getset, /* tp_getset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055 0, /* tp_base */
1056 0, /* tp_dict */
1057 0, /* tp_descr_get */
1058 0, /* tp_descr_set */
1059 0, /* tp_dictoffset */
1060 (initproc)deque_init, /* tp_init */
1061 PyType_GenericAlloc, /* tp_alloc */
1062 deque_new, /* tp_new */
1063 PyObject_GC_Del, /* tp_free */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001064};
1065
1066/*********************** Deque Iterator **************************/
1067
1068typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001069 PyObject_HEAD
1070 Py_ssize_t index;
1071 block *b;
1072 dequeobject *deque;
1073 long state; /* state when the iterator is created */
1074 Py_ssize_t counter; /* number of items remaining for iteration */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001075} dequeiterobject;
1076
Martin v. Löwis59683e82008-06-13 07:50:45 +00001077static PyTypeObject dequeiter_type;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001078
1079static PyObject *
1080deque_iter(dequeobject *deque)
1081{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 dequeiterobject *it;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001083
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 it = PyObject_GC_New(dequeiterobject, &dequeiter_type);
1085 if (it == NULL)
1086 return NULL;
1087 it->b = deque->leftblock;
1088 it->index = deque->leftindex;
1089 Py_INCREF(deque);
1090 it->deque = deque;
1091 it->state = deque->state;
1092 it->counter = deque->len;
1093 PyObject_GC_Track(it);
1094 return (PyObject *)it;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001095}
1096
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001097static int
1098dequeiter_traverse(dequeiterobject *dio, visitproc visit, void *arg)
1099{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001100 Py_VISIT(dio->deque);
1101 return 0;
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001102}
1103
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001104static void
1105dequeiter_dealloc(dequeiterobject *dio)
1106{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001107 Py_XDECREF(dio->deque);
1108 PyObject_GC_Del(dio);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001109}
1110
1111static PyObject *
1112dequeiter_next(dequeiterobject *it)
1113{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001114 PyObject *item;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001116 if (it->deque->state != it->state) {
1117 it->counter = 0;
1118 PyErr_SetString(PyExc_RuntimeError,
1119 "deque mutated during iteration");
1120 return NULL;
1121 }
1122 if (it->counter == 0)
1123 return NULL;
1124 assert (!(it->b == it->deque->rightblock &&
1125 it->index > it->deque->rightindex));
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001127 item = it->b->data[it->index];
1128 it->index++;
1129 it->counter--;
1130 if (it->index == BLOCKLEN && it->counter > 0) {
1131 assert (it->b->rightlink != NULL);
1132 it->b = it->b->rightlink;
1133 it->index = 0;
1134 }
1135 Py_INCREF(item);
1136 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001137}
1138
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001139static PyObject *
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001140dequeiter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1141{
1142 Py_ssize_t i, index=0;
1143 PyObject *deque;
1144 dequeiterobject *it;
1145 if (!PyArg_ParseTuple(args, "O!|n", &deque_type, &deque, &index))
1146 return NULL;
1147 assert(type == &dequeiter_type);
1148
1149 it = (dequeiterobject*)deque_iter((dequeobject *)deque);
1150 if (!it)
1151 return NULL;
1152 /* consume items from the queue */
1153 for(i=0; i<index; i++) {
1154 PyObject *item = dequeiter_next(it);
1155 if (item) {
1156 Py_DECREF(item);
1157 } else {
1158 if (it->counter) {
1159 Py_DECREF(it);
1160 return NULL;
1161 } else
1162 break;
1163 }
1164 }
1165 return (PyObject*)it;
1166}
1167
1168static PyObject *
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001169dequeiter_len(dequeiterobject *it)
1170{
Antoine Pitrou554f3342010-08-17 18:30:06 +00001171 return PyLong_FromSsize_t(it->counter);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001172}
1173
Armin Rigof5b3e362006-02-11 21:32:43 +00001174PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001175
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001176static PyObject *
1177dequeiter_reduce(dequeiterobject *it)
1178{
1179 return Py_BuildValue("O(On)", Py_TYPE(it), it->deque, it->deque->len - it->counter);
1180}
1181
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001182static PyMethodDef dequeiter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 {"__length_hint__", (PyCFunction)dequeiter_len, METH_NOARGS, length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001184 {"__reduce__", (PyCFunction)dequeiter_reduce, METH_NOARGS, reduce_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001185 {NULL, NULL} /* sentinel */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001186};
1187
Martin v. Löwis59683e82008-06-13 07:50:45 +00001188static PyTypeObject dequeiter_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001189 PyVarObject_HEAD_INIT(NULL, 0)
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001190 "_collections._deque_iterator", /* tp_name */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001191 sizeof(dequeiterobject), /* tp_basicsize */
1192 0, /* tp_itemsize */
1193 /* methods */
1194 (destructor)dequeiter_dealloc, /* tp_dealloc */
1195 0, /* tp_print */
1196 0, /* tp_getattr */
1197 0, /* tp_setattr */
1198 0, /* tp_reserved */
1199 0, /* tp_repr */
1200 0, /* tp_as_number */
1201 0, /* tp_as_sequence */
1202 0, /* tp_as_mapping */
1203 0, /* tp_hash */
1204 0, /* tp_call */
1205 0, /* tp_str */
1206 PyObject_GenericGetAttr, /* tp_getattro */
1207 0, /* tp_setattro */
1208 0, /* tp_as_buffer */
1209 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
1210 0, /* tp_doc */
1211 (traverseproc)dequeiter_traverse, /* tp_traverse */
1212 0, /* tp_clear */
1213 0, /* tp_richcompare */
1214 0, /* tp_weaklistoffset */
1215 PyObject_SelfIter, /* tp_iter */
1216 (iternextfunc)dequeiter_next, /* tp_iternext */
1217 dequeiter_methods, /* tp_methods */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001218 0, /* tp_members */
1219 0, /* tp_getset */
1220 0, /* tp_base */
1221 0, /* tp_dict */
1222 0, /* tp_descr_get */
1223 0, /* tp_descr_set */
1224 0, /* tp_dictoffset */
1225 0, /* tp_init */
1226 0, /* tp_alloc */
1227 dequeiter_new, /* tp_new */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001228 0,
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001229};
1230
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001231/*********************** Deque Reverse Iterator **************************/
1232
Martin v. Löwis59683e82008-06-13 07:50:45 +00001233static PyTypeObject dequereviter_type;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001234
1235static PyObject *
1236deque_reviter(dequeobject *deque)
1237{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001238 dequeiterobject *it;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001240 it = PyObject_GC_New(dequeiterobject, &dequereviter_type);
1241 if (it == NULL)
1242 return NULL;
1243 it->b = deque->rightblock;
1244 it->index = deque->rightindex;
1245 Py_INCREF(deque);
1246 it->deque = deque;
1247 it->state = deque->state;
1248 it->counter = deque->len;
1249 PyObject_GC_Track(it);
1250 return (PyObject *)it;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001251}
1252
1253static PyObject *
1254dequereviter_next(dequeiterobject *it)
1255{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001256 PyObject *item;
1257 if (it->counter == 0)
1258 return NULL;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001260 if (it->deque->state != it->state) {
1261 it->counter = 0;
1262 PyErr_SetString(PyExc_RuntimeError,
1263 "deque mutated during iteration");
1264 return NULL;
1265 }
1266 assert (!(it->b == it->deque->leftblock &&
1267 it->index < it->deque->leftindex));
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001269 item = it->b->data[it->index];
1270 it->index--;
1271 it->counter--;
1272 if (it->index == -1 && it->counter > 0) {
1273 assert (it->b->leftlink != NULL);
1274 it->b = it->b->leftlink;
1275 it->index = BLOCKLEN - 1;
1276 }
1277 Py_INCREF(item);
1278 return item;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001279}
1280
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001281static PyObject *
1282dequereviter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1283{
1284 Py_ssize_t i, index=0;
1285 PyObject *deque;
1286 dequeiterobject *it;
1287 if (!PyArg_ParseTuple(args, "O!|n", &deque_type, &deque, &index))
1288 return NULL;
1289 assert(type == &dequereviter_type);
1290
1291 it = (dequeiterobject*)deque_reviter((dequeobject *)deque);
1292 if (!it)
1293 return NULL;
1294 /* consume items from the queue */
1295 for(i=0; i<index; i++) {
1296 PyObject *item = dequereviter_next(it);
1297 if (item) {
1298 Py_DECREF(item);
1299 } else {
1300 if (it->counter) {
1301 Py_DECREF(it);
1302 return NULL;
1303 } else
1304 break;
1305 }
1306 }
1307 return (PyObject*)it;
1308}
1309
Martin v. Löwis59683e82008-06-13 07:50:45 +00001310static PyTypeObject dequereviter_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001311 PyVarObject_HEAD_INIT(NULL, 0)
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001312 "_collections._deque_reverse_iterator", /* tp_name */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001313 sizeof(dequeiterobject), /* tp_basicsize */
1314 0, /* tp_itemsize */
1315 /* methods */
1316 (destructor)dequeiter_dealloc, /* tp_dealloc */
1317 0, /* tp_print */
1318 0, /* tp_getattr */
1319 0, /* tp_setattr */
1320 0, /* tp_reserved */
1321 0, /* tp_repr */
1322 0, /* tp_as_number */
1323 0, /* tp_as_sequence */
1324 0, /* tp_as_mapping */
1325 0, /* tp_hash */
1326 0, /* tp_call */
1327 0, /* tp_str */
1328 PyObject_GenericGetAttr, /* tp_getattro */
1329 0, /* tp_setattro */
1330 0, /* tp_as_buffer */
1331 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
1332 0, /* tp_doc */
1333 (traverseproc)dequeiter_traverse, /* tp_traverse */
1334 0, /* tp_clear */
1335 0, /* tp_richcompare */
1336 0, /* tp_weaklistoffset */
1337 PyObject_SelfIter, /* tp_iter */
1338 (iternextfunc)dequereviter_next, /* tp_iternext */
1339 dequeiter_methods, /* tp_methods */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001340 0, /* tp_members */
1341 0, /* tp_getset */
1342 0, /* tp_base */
1343 0, /* tp_dict */
1344 0, /* tp_descr_get */
1345 0, /* tp_descr_set */
1346 0, /* tp_dictoffset */
1347 0, /* tp_init */
1348 0, /* tp_alloc */
1349 dequereviter_new, /* tp_new */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001350 0,
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001351};
1352
Guido van Rossum1968ad32006-02-25 22:38:04 +00001353/* defaultdict type *********************************************************/
1354
1355typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001356 PyDictObject dict;
1357 PyObject *default_factory;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001358} defdictobject;
1359
1360static PyTypeObject defdict_type; /* Forward */
1361
1362PyDoc_STRVAR(defdict_missing_doc,
1363"__missing__(key) # Called by __getitem__ for missing key; pseudo-code:\n\
Guido van Rossumd8faa362007-04-27 19:54:29 +00001364 if self.default_factory is None: raise KeyError((key,))\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00001365 self[key] = value = self.default_factory()\n\
1366 return value\n\
1367");
1368
1369static PyObject *
1370defdict_missing(defdictobject *dd, PyObject *key)
1371{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001372 PyObject *factory = dd->default_factory;
1373 PyObject *value;
1374 if (factory == NULL || factory == Py_None) {
1375 /* XXX Call dict.__missing__(key) */
1376 PyObject *tup;
1377 tup = PyTuple_Pack(1, key);
1378 if (!tup) return NULL;
1379 PyErr_SetObject(PyExc_KeyError, tup);
1380 Py_DECREF(tup);
1381 return NULL;
1382 }
1383 value = PyEval_CallObject(factory, NULL);
1384 if (value == NULL)
1385 return value;
1386 if (PyObject_SetItem((PyObject *)dd, key, value) < 0) {
1387 Py_DECREF(value);
1388 return NULL;
1389 }
1390 return value;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001391}
1392
1393PyDoc_STRVAR(defdict_copy_doc, "D.copy() -> a shallow copy of D.");
1394
1395static PyObject *
1396defdict_copy(defdictobject *dd)
1397{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001398 /* This calls the object's class. That only works for subclasses
1399 whose class constructor has the same signature. Subclasses that
1400 define a different constructor signature must override copy().
1401 */
Raymond Hettinger54628fa2009-08-04 19:16:39 +00001402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001403 if (dd->default_factory == NULL)
1404 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd), Py_None, dd, NULL);
1405 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd),
1406 dd->default_factory, dd, NULL);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001407}
1408
1409static PyObject *
1410defdict_reduce(defdictobject *dd)
1411{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001412 /* __reduce__ must return a 5-tuple as follows:
Guido van Rossum1968ad32006-02-25 22:38:04 +00001413
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001414 - factory function
1415 - tuple of args for the factory function
1416 - additional state (here None)
1417 - sequence iterator (here None)
1418 - dictionary iterator (yielding successive (key, value) pairs
Guido van Rossum1968ad32006-02-25 22:38:04 +00001419
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001420 This API is used by pickle.py and copy.py.
Guido van Rossum1968ad32006-02-25 22:38:04 +00001421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001422 For this to be useful with pickle.py, the default_factory
1423 must be picklable; e.g., None, a built-in, or a global
1424 function in a module or package.
Guido van Rossum1968ad32006-02-25 22:38:04 +00001425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001426 Both shallow and deep copying are supported, but for deep
1427 copying, the default_factory must be deep-copyable; e.g. None,
1428 or a built-in (functions are not copyable at this time).
Guido van Rossum1968ad32006-02-25 22:38:04 +00001429
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001430 This only works for subclasses as long as their constructor
1431 signature is compatible; the first argument must be the
1432 optional default_factory, defaulting to None.
1433 */
1434 PyObject *args;
1435 PyObject *items;
1436 PyObject *iter;
1437 PyObject *result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001438 _Py_IDENTIFIER(items);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001440 if (dd->default_factory == NULL || dd->default_factory == Py_None)
1441 args = PyTuple_New(0);
1442 else
1443 args = PyTuple_Pack(1, dd->default_factory);
1444 if (args == NULL)
1445 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001446 items = _PyObject_CallMethodId((PyObject *)dd, &PyId_items, "()");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001447 if (items == NULL) {
1448 Py_DECREF(args);
1449 return NULL;
1450 }
1451 iter = PyObject_GetIter(items);
1452 if (iter == NULL) {
1453 Py_DECREF(items);
1454 Py_DECREF(args);
1455 return NULL;
1456 }
1457 result = PyTuple_Pack(5, Py_TYPE(dd), args,
1458 Py_None, Py_None, iter);
1459 Py_DECREF(iter);
1460 Py_DECREF(items);
1461 Py_DECREF(args);
1462 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001463}
1464
1465static PyMethodDef defdict_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001466 {"__missing__", (PyCFunction)defdict_missing, METH_O,
1467 defdict_missing_doc},
1468 {"copy", (PyCFunction)defdict_copy, METH_NOARGS,
1469 defdict_copy_doc},
1470 {"__copy__", (PyCFunction)defdict_copy, METH_NOARGS,
1471 defdict_copy_doc},
1472 {"__reduce__", (PyCFunction)defdict_reduce, METH_NOARGS,
1473 reduce_doc},
1474 {NULL}
Guido van Rossum1968ad32006-02-25 22:38:04 +00001475};
1476
1477static PyMemberDef defdict_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001478 {"default_factory", T_OBJECT,
1479 offsetof(defdictobject, default_factory), 0,
1480 PyDoc_STR("Factory for default value called by __missing__().")},
1481 {NULL}
Guido van Rossum1968ad32006-02-25 22:38:04 +00001482};
1483
1484static void
1485defdict_dealloc(defdictobject *dd)
1486{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001487 Py_CLEAR(dd->default_factory);
1488 PyDict_Type.tp_dealloc((PyObject *)dd);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001489}
1490
Guido van Rossum1968ad32006-02-25 22:38:04 +00001491static PyObject *
1492defdict_repr(defdictobject *dd)
1493{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001494 PyObject *baserepr;
1495 PyObject *defrepr;
1496 PyObject *result;
1497 baserepr = PyDict_Type.tp_repr((PyObject *)dd);
1498 if (baserepr == NULL)
1499 return NULL;
1500 if (dd->default_factory == NULL)
1501 defrepr = PyUnicode_FromString("None");
1502 else
1503 {
1504 int status = Py_ReprEnter(dd->default_factory);
1505 if (status != 0) {
Antoine Pitrouf5f1fe02012-02-15 02:42:46 +01001506 if (status < 0) {
1507 Py_DECREF(baserepr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001508 return NULL;
Antoine Pitrouf5f1fe02012-02-15 02:42:46 +01001509 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001510 defrepr = PyUnicode_FromString("...");
1511 }
1512 else
1513 defrepr = PyObject_Repr(dd->default_factory);
1514 Py_ReprLeave(dd->default_factory);
1515 }
1516 if (defrepr == NULL) {
1517 Py_DECREF(baserepr);
1518 return NULL;
1519 }
1520 result = PyUnicode_FromFormat("defaultdict(%U, %U)",
1521 defrepr, baserepr);
1522 Py_DECREF(defrepr);
1523 Py_DECREF(baserepr);
1524 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001525}
1526
1527static int
1528defdict_traverse(PyObject *self, visitproc visit, void *arg)
1529{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001530 Py_VISIT(((defdictobject *)self)->default_factory);
1531 return PyDict_Type.tp_traverse(self, visit, arg);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001532}
1533
1534static int
1535defdict_tp_clear(defdictobject *dd)
1536{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001537 Py_CLEAR(dd->default_factory);
1538 return PyDict_Type.tp_clear((PyObject *)dd);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001539}
1540
1541static int
1542defdict_init(PyObject *self, PyObject *args, PyObject *kwds)
1543{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001544 defdictobject *dd = (defdictobject *)self;
1545 PyObject *olddefault = dd->default_factory;
1546 PyObject *newdefault = NULL;
1547 PyObject *newargs;
1548 int result;
1549 if (args == NULL || !PyTuple_Check(args))
1550 newargs = PyTuple_New(0);
1551 else {
1552 Py_ssize_t n = PyTuple_GET_SIZE(args);
1553 if (n > 0) {
1554 newdefault = PyTuple_GET_ITEM(args, 0);
1555 if (!PyCallable_Check(newdefault) && newdefault != Py_None) {
1556 PyErr_SetString(PyExc_TypeError,
1557 "first argument must be callable");
1558 return -1;
1559 }
1560 }
1561 newargs = PySequence_GetSlice(args, 1, n);
1562 }
1563 if (newargs == NULL)
1564 return -1;
1565 Py_XINCREF(newdefault);
1566 dd->default_factory = newdefault;
1567 result = PyDict_Type.tp_init(self, newargs, kwds);
1568 Py_DECREF(newargs);
1569 Py_XDECREF(olddefault);
1570 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001571}
1572
1573PyDoc_STRVAR(defdict_doc,
1574"defaultdict(default_factory) --> dict with default factory\n\
1575\n\
1576The default factory is called without arguments to produce\n\
1577a new value when a key is not present, in __getitem__ only.\n\
1578A defaultdict compares equal to a dict with the same items.\n\
1579");
1580
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001581/* See comment in xxsubtype.c */
1582#define DEFERRED_ADDRESS(ADDR) 0
1583
Guido van Rossum1968ad32006-02-25 22:38:04 +00001584static PyTypeObject defdict_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001585 PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0)
1586 "collections.defaultdict", /* tp_name */
1587 sizeof(defdictobject), /* tp_basicsize */
1588 0, /* tp_itemsize */
1589 /* methods */
1590 (destructor)defdict_dealloc, /* tp_dealloc */
1591 0, /* tp_print */
1592 0, /* tp_getattr */
1593 0, /* tp_setattr */
1594 0, /* tp_reserved */
1595 (reprfunc)defdict_repr, /* tp_repr */
1596 0, /* tp_as_number */
1597 0, /* tp_as_sequence */
1598 0, /* tp_as_mapping */
1599 0, /* tp_hash */
1600 0, /* tp_call */
1601 0, /* tp_str */
1602 PyObject_GenericGetAttr, /* tp_getattro */
1603 0, /* tp_setattro */
1604 0, /* tp_as_buffer */
1605 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
1606 /* tp_flags */
1607 defdict_doc, /* tp_doc */
1608 defdict_traverse, /* tp_traverse */
1609 (inquiry)defdict_tp_clear, /* tp_clear */
1610 0, /* tp_richcompare */
1611 0, /* tp_weaklistoffset*/
1612 0, /* tp_iter */
1613 0, /* tp_iternext */
1614 defdict_methods, /* tp_methods */
1615 defdict_members, /* tp_members */
1616 0, /* tp_getset */
1617 DEFERRED_ADDRESS(&PyDict_Type), /* tp_base */
1618 0, /* tp_dict */
1619 0, /* tp_descr_get */
1620 0, /* tp_descr_set */
1621 0, /* tp_dictoffset */
1622 defdict_init, /* tp_init */
1623 PyType_GenericAlloc, /* tp_alloc */
1624 0, /* tp_new */
1625 PyObject_GC_Del, /* tp_free */
Guido van Rossum1968ad32006-02-25 22:38:04 +00001626};
1627
Raymond Hettinger96f34102010-12-15 16:30:37 +00001628/* helper function for Counter *********************************************/
1629
1630PyDoc_STRVAR(_count_elements_doc,
1631"_count_elements(mapping, iterable) -> None\n\
1632\n\
1633Count elements in the iterable, updating the mappping");
1634
1635static PyObject *
1636_count_elements(PyObject *self, PyObject *args)
1637{
1638 PyObject *it, *iterable, *mapping, *oldval;
1639 PyObject *newval = NULL;
1640 PyObject *key = NULL;
1641 PyObject *one = NULL;
1642
1643 if (!PyArg_UnpackTuple(args, "_count_elements", 2, 2, &mapping, &iterable))
1644 return NULL;
1645
Raymond Hettinger96f34102010-12-15 16:30:37 +00001646 it = PyObject_GetIter(iterable);
1647 if (it == NULL)
1648 return NULL;
Raymond Hettinger426e0522011-01-03 02:12:02 +00001649
Raymond Hettinger96f34102010-12-15 16:30:37 +00001650 one = PyLong_FromLong(1);
1651 if (one == NULL) {
1652 Py_DECREF(it);
1653 return NULL;
1654 }
Raymond Hettinger426e0522011-01-03 02:12:02 +00001655
1656 if (PyDict_CheckExact(mapping)) {
1657 while (1) {
1658 key = PyIter_Next(it);
Victor Stinnera154b5c2011-04-20 23:23:52 +02001659 if (key == NULL)
1660 break;
Raymond Hettinger426e0522011-01-03 02:12:02 +00001661 oldval = PyDict_GetItem(mapping, key);
1662 if (oldval == NULL) {
1663 if (PyDict_SetItem(mapping, key, one) == -1)
1664 break;
1665 } else {
1666 newval = PyNumber_Add(oldval, one);
1667 if (newval == NULL)
1668 break;
1669 if (PyDict_SetItem(mapping, key, newval) == -1)
1670 break;
1671 Py_CLEAR(newval);
1672 }
1673 Py_DECREF(key);
Raymond Hettinger96f34102010-12-15 16:30:37 +00001674 }
Raymond Hettinger426e0522011-01-03 02:12:02 +00001675 } else {
1676 while (1) {
1677 key = PyIter_Next(it);
Victor Stinnera154b5c2011-04-20 23:23:52 +02001678 if (key == NULL)
1679 break;
Raymond Hettinger426e0522011-01-03 02:12:02 +00001680 oldval = PyObject_GetItem(mapping, key);
1681 if (oldval == NULL) {
1682 if (!PyErr_Occurred() || !PyErr_ExceptionMatches(PyExc_KeyError))
1683 break;
1684 PyErr_Clear();
1685 Py_INCREF(one);
1686 newval = one;
1687 } else {
1688 newval = PyNumber_Add(oldval, one);
1689 Py_DECREF(oldval);
1690 if (newval == NULL)
1691 break;
1692 }
1693 if (PyObject_SetItem(mapping, key, newval) == -1)
Raymond Hettinger96f34102010-12-15 16:30:37 +00001694 break;
1695 Py_CLEAR(newval);
Raymond Hettinger426e0522011-01-03 02:12:02 +00001696 Py_DECREF(key);
Raymond Hettinger96f34102010-12-15 16:30:37 +00001697 }
Raymond Hettinger96f34102010-12-15 16:30:37 +00001698 }
Raymond Hettinger426e0522011-01-03 02:12:02 +00001699
Raymond Hettinger96f34102010-12-15 16:30:37 +00001700 Py_DECREF(it);
1701 Py_XDECREF(key);
1702 Py_XDECREF(newval);
1703 Py_DECREF(one);
1704 if (PyErr_Occurred())
1705 return NULL;
1706 Py_RETURN_NONE;
1707}
1708
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001709/* module level code ********************************************************/
1710
1711PyDoc_STRVAR(module_doc,
Guido van Rossum1968ad32006-02-25 22:38:04 +00001712"High performance data structures.\n\
1713- deque: ordered collection accessible from endpoints only\n\
1714- defaultdict: dict subclass with a default value factory\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001715");
1716
Raymond Hettinger96f34102010-12-15 16:30:37 +00001717static struct PyMethodDef module_functions[] = {
1718 {"_count_elements", _count_elements, METH_VARARGS, _count_elements_doc},
1719 {NULL, NULL} /* sentinel */
1720};
Martin v. Löwis1a214512008-06-11 05:26:20 +00001721
1722static struct PyModuleDef _collectionsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001723 PyModuleDef_HEAD_INIT,
1724 "_collections",
1725 module_doc,
1726 -1,
Raymond Hettinger96f34102010-12-15 16:30:37 +00001727 module_functions,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001728 NULL,
1729 NULL,
1730 NULL,
1731 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001732};
1733
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001734PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001735PyInit__collections(void)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001736{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001737 PyObject *m;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001739 m = PyModule_Create(&_collectionsmodule);
1740 if (m == NULL)
1741 return NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001742
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001743 if (PyType_Ready(&deque_type) < 0)
1744 return NULL;
1745 Py_INCREF(&deque_type);
1746 PyModule_AddObject(m, "deque", (PyObject *)&deque_type);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001747
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001748 defdict_type.tp_base = &PyDict_Type;
1749 if (PyType_Ready(&defdict_type) < 0)
1750 return NULL;
1751 Py_INCREF(&defdict_type);
1752 PyModule_AddObject(m, "defaultdict", (PyObject *)&defdict_type);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001754 if (PyType_Ready(&dequeiter_type) < 0)
1755 return NULL;
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001756 Py_INCREF(&dequeiter_type);
1757 PyModule_AddObject(m, "_deque_iterator", (PyObject *)&dequeiter_type);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001759 if (PyType_Ready(&dequereviter_type) < 0)
1760 return NULL;
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001761 Py_INCREF(&dequereviter_type);
1762 PyModule_AddObject(m, "_deque_reverse_iterator", (PyObject *)&dequereviter_type);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001763
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001764 return m;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001765}