Manual py3k backport: [svn r74158] Issue #6218: Make io.BytesIO and io.StringIO pickl...
[python.git] / Modules / _collectionsmodule.c
blob1873cabc5b6b7e352565fd7618cef7d9e081e1f1
1 #include "Python.h"
2 #include "structmember.h"
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 */
10 /* 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
13 * length of a cache line.
16 #define BLOCKLEN 62
17 #define CENTER ((BLOCKLEN - 1) / 2)
19 /* 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
24 * indices, these indices are inclusive on both ends. By being inclusive
25 * on both ends, algorithms for left and right operations become
26 * symmetrical which simplifies the design.
28 * The list of blocks is never empty, so d.leftblock and d.rightblock
29 * are never equal to NULL.
31 * The indices, d.leftindex and d.rightindex are always in the range
32 * 0 <= index < BLOCKLEN.
33 * Their exact relationship is:
34 * (d.leftindex + d.len - 1) % BLOCKLEN == d.rightindex.
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.
40 * Whenever d.leftblock == d.rightblock,
41 * d.leftindex + d.len - 1 == d.rightindex.
43 * However, when d.leftblock != d.rightblock, d.leftindex and d.rightindex
44 * become indices into distinct blocks and either may be larger than the
45 * other.
48 typedef struct BLOCK {
49 struct BLOCK *leftlink;
50 struct BLOCK *rightlink;
51 PyObject *data[BLOCKLEN];
52 } block;
54 #define MAXFREEBLOCKS 10
55 static Py_ssize_t numfreeblocks = 0;
56 static block *freeblocks[MAXFREEBLOCKS];
58 static block *
59 newblock(block *leftlink, block *rightlink, Py_ssize_t len) {
60 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.
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;
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;
83 b->leftlink = leftlink;
84 b->rightlink = rightlink;
85 return b;
88 static void
89 freeblock(block *b)
91 if (numfreeblocks < MAXFREEBLOCKS) {
92 freeblocks[numfreeblocks] = b;
93 numfreeblocks++;
94 } else {
95 PyMem_Free(b);
99 typedef struct {
100 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 */
109 } dequeobject;
111 /* 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.
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().
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); \
127 static PyTypeObject deque_type;
129 static PyObject *
130 deque_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
132 dequeobject *deque;
133 block *b;
135 /* create dequeobject structure */
136 deque = (dequeobject *)type->tp_alloc(type, 0);
137 if (deque == NULL)
138 return NULL;
140 b = newblock(NULL, NULL, 0);
141 if (b == NULL) {
142 Py_DECREF(deque);
143 return NULL;
146 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;
156 return (PyObject *)deque;
159 static PyObject *
160 deque_pop(dequeobject *deque, PyObject *unused)
162 PyObject *item;
163 block *prevblock;
165 if (deque->len == 0) {
166 PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
167 return NULL;
169 item = deque->rightblock->data[deque->rightindex];
170 deque->rightindex--;
171 deque->len--;
172 deque->state++;
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 */
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;
190 return item;
193 PyDoc_STRVAR(pop_doc, "Remove and return the rightmost element.");
195 static PyObject *
196 deque_popleft(dequeobject *deque, PyObject *unused)
198 PyObject *item;
199 block *prevblock;
201 if (deque->len == 0) {
202 PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
203 return NULL;
205 assert(deque->leftblock != NULL);
206 item = deque->leftblock->data[deque->leftindex];
207 deque->leftindex++;
208 deque->len--;
209 deque->state++;
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 */
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;
228 return item;
231 PyDoc_STRVAR(popleft_doc, "Remove and return the leftmost element.");
233 static PyObject *
234 deque_append(dequeobject *deque, PyObject *item)
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;
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;
254 PyDoc_STRVAR(append_doc, "Add an element to the right side of the deque.");
256 static PyObject *
257 deque_appendleft(dequeobject *deque, PyObject *item)
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;
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;
277 PyDoc_STRVAR(appendleft_doc, "Add an element to the left side of the deque.");
280 /* Run an iterator to exhaustion. Shortcut for
281 the extend/extendleft methods when maxlen == 0. */
282 static PyObject*
283 consume_iterator(PyObject *it)
285 PyObject *item;
287 while ((item = PyIter_Next(it)) != NULL) {
288 Py_DECREF(item);
290 Py_DECREF(it);
291 if (PyErr_Occurred())
292 return NULL;
293 Py_RETURN_NONE;
296 static PyObject *
297 deque_extend(dequeobject *deque, PyObject *iterable)
299 PyObject *it, *item;
301 it = PyObject_GetIter(iterable);
302 if (it == NULL)
303 return NULL;
305 if (deque->maxlen == 0)
306 return consume_iterator(it);
308 while ((item = PyIter_Next(it)) != NULL) {
309 deque->state++;
310 if (deque->rightindex == BLOCKLEN-1) {
311 block *b = newblock(deque->rightblock, NULL,
312 deque->len);
313 if (b == NULL) {
314 Py_DECREF(item);
315 Py_DECREF(it);
316 return NULL;
318 assert(deque->rightblock->rightlink == NULL);
319 deque->rightblock->rightlink = b;
320 deque->rightblock = b;
321 deque->rightindex = -1;
323 deque->len++;
324 deque->rightindex++;
325 deque->rightblock->data[deque->rightindex] = item;
326 TRIM(deque, deque_popleft);
328 Py_DECREF(it);
329 if (PyErr_Occurred())
330 return NULL;
331 Py_RETURN_NONE;
334 PyDoc_STRVAR(extend_doc,
335 "Extend the right side of the deque with elements from the iterable");
337 static PyObject *
338 deque_extendleft(dequeobject *deque, PyObject *iterable)
340 PyObject *it, *item;
342 it = PyObject_GetIter(iterable);
343 if (it == NULL)
344 return NULL;
346 if (deque->maxlen == 0)
347 return consume_iterator(it);
349 while ((item = PyIter_Next(it)) != NULL) {
350 deque->state++;
351 if (deque->leftindex == 0) {
352 block *b = newblock(NULL, deque->leftblock,
353 deque->len);
354 if (b == NULL) {
355 Py_DECREF(item);
356 Py_DECREF(it);
357 return NULL;
359 assert(deque->leftblock->leftlink == NULL);
360 deque->leftblock->leftlink = b;
361 deque->leftblock = b;
362 deque->leftindex = BLOCKLEN;
364 deque->len++;
365 deque->leftindex--;
366 deque->leftblock->data[deque->leftindex] = item;
367 TRIM(deque, deque_pop);
369 Py_DECREF(it);
370 if (PyErr_Occurred())
371 return NULL;
372 Py_RETURN_NONE;
375 PyDoc_STRVAR(extendleft_doc,
376 "Extend the left side of the deque with elements from the iterable");
378 static int
379 _deque_rotate(dequeobject *deque, Py_ssize_t n)
381 Py_ssize_t i, len=deque->len, halflen=(len+1)>>1;
382 PyObject *item, *rv;
384 if (len == 0)
385 return 0;
386 if (n > halflen || n < -halflen) {
387 n %= len;
388 if (n > halflen)
389 n -= len;
390 else if (n < -halflen)
391 n += len;
394 for (i=0 ; i<n ; i++) {
395 item = deque_pop(deque, NULL);
396 assert (item != NULL);
397 rv = deque_appendleft(deque, item);
398 Py_DECREF(item);
399 if (rv == NULL)
400 return -1;
401 Py_DECREF(rv);
403 for (i=0 ; i>n ; i--) {
404 item = deque_popleft(deque, NULL);
405 assert (item != NULL);
406 rv = deque_append(deque, item);
407 Py_DECREF(item);
408 if (rv == NULL)
409 return -1;
410 Py_DECREF(rv);
412 return 0;
415 static PyObject *
416 deque_rotate(dequeobject *deque, PyObject *args)
418 Py_ssize_t n=1;
420 if (!PyArg_ParseTuple(args, "|n:rotate", &n))
421 return NULL;
422 if (_deque_rotate(deque, n) == 0)
423 Py_RETURN_NONE;
424 return NULL;
427 PyDoc_STRVAR(rotate_doc,
428 "Rotate the deque n steps to the right (default n=1). If n is negative, rotates left.");
430 static Py_ssize_t
431 deque_len(dequeobject *deque)
433 return deque->len;
436 static PyObject *
437 deque_remove(dequeobject *deque, PyObject *value)
439 Py_ssize_t i, n=deque->len;
441 for (i=0 ; i<n ; i++) {
442 PyObject *item = deque->leftblock->data[deque->leftindex];
443 int cmp = PyObject_RichCompareBool(item, value, Py_EQ);
445 if (deque->len != n) {
446 PyErr_SetString(PyExc_IndexError,
447 "deque mutated during remove().");
448 return NULL;
450 if (cmp > 0) {
451 PyObject *tgt = deque_popleft(deque, NULL);
452 assert (tgt != NULL);
453 Py_DECREF(tgt);
454 if (_deque_rotate(deque, i) == -1)
455 return NULL;
456 Py_RETURN_NONE;
458 else if (cmp < 0) {
459 _deque_rotate(deque, i);
460 return NULL;
462 _deque_rotate(deque, -1);
464 PyErr_SetString(PyExc_ValueError, "deque.remove(x): x not in deque");
465 return NULL;
468 PyDoc_STRVAR(remove_doc,
469 "D.remove(value) -- remove first occurrence of value.");
471 static int
472 deque_clear(dequeobject *deque)
474 PyObject *item;
476 while (deque->len) {
477 item = deque_pop(deque, NULL);
478 assert (item != NULL);
479 Py_DECREF(item);
481 assert(deque->leftblock == deque->rightblock &&
482 deque->leftindex - 1 == deque->rightindex &&
483 deque->len == 0);
484 return 0;
487 static PyObject *
488 deque_item(dequeobject *deque, Py_ssize_t i)
490 block *b;
491 PyObject *item;
492 Py_ssize_t n, index=i;
494 if (i < 0 || i >= deque->len) {
495 PyErr_SetString(PyExc_IndexError,
496 "deque index out of range");
497 return NULL;
500 if (i == 0) {
501 i = deque->leftindex;
502 b = deque->leftblock;
503 } else if (i == deque->len - 1) {
504 i = deque->rightindex;
505 b = deque->rightblock;
506 } else {
507 i += deque->leftindex;
508 n = i / BLOCKLEN;
509 i %= BLOCKLEN;
510 if (index < (deque->len >> 1)) {
511 b = deque->leftblock;
512 while (n--)
513 b = b->rightlink;
514 } else {
515 n = (deque->leftindex + deque->len - 1) / BLOCKLEN - n;
516 b = deque->rightblock;
517 while (n--)
518 b = b->leftlink;
521 item = b->data[i];
522 Py_INCREF(item);
523 return item;
526 /* delitem() implemented in terms of rotate for simplicity and reasonable
527 performance near the end points. If for some reason this method becomes
528 popular, it is not hard to re-implement this using direct data movement
529 (similar to code in list slice assignment) and achieve a two or threefold
530 performance boost.
533 static int
534 deque_del_item(dequeobject *deque, Py_ssize_t i)
536 PyObject *item;
538 assert (i >= 0 && i < deque->len);
539 if (_deque_rotate(deque, -i) == -1)
540 return -1;
542 item = deque_popleft(deque, NULL);
543 assert (item != NULL);
544 Py_DECREF(item);
546 return _deque_rotate(deque, i);
549 static int
550 deque_ass_item(dequeobject *deque, Py_ssize_t i, PyObject *v)
552 PyObject *old_value;
553 block *b;
554 Py_ssize_t n, len=deque->len, halflen=(len+1)>>1, index=i;
556 if (i < 0 || i >= len) {
557 PyErr_SetString(PyExc_IndexError,
558 "deque index out of range");
559 return -1;
561 if (v == NULL)
562 return deque_del_item(deque, i);
564 i += deque->leftindex;
565 n = i / BLOCKLEN;
566 i %= BLOCKLEN;
567 if (index <= halflen) {
568 b = deque->leftblock;
569 while (n--)
570 b = b->rightlink;
571 } else {
572 n = (deque->leftindex + len - 1) / BLOCKLEN - n;
573 b = deque->rightblock;
574 while (n--)
575 b = b->leftlink;
577 Py_INCREF(v);
578 old_value = b->data[i];
579 b->data[i] = v;
580 Py_DECREF(old_value);
581 return 0;
584 static PyObject *
585 deque_clearmethod(dequeobject *deque)
587 int rv;
589 rv = deque_clear(deque);
590 assert (rv != -1);
591 Py_RETURN_NONE;
594 PyDoc_STRVAR(clear_doc, "Remove all elements from the deque.");
596 static void
597 deque_dealloc(dequeobject *deque)
599 PyObject_GC_UnTrack(deque);
600 if (deque->weakreflist != NULL)
601 PyObject_ClearWeakRefs((PyObject *) deque);
602 if (deque->leftblock != NULL) {
603 deque_clear(deque);
604 assert(deque->leftblock != NULL);
605 freeblock(deque->leftblock);
607 deque->leftblock = NULL;
608 deque->rightblock = NULL;
609 Py_TYPE(deque)->tp_free(deque);
612 static int
613 deque_traverse(dequeobject *deque, visitproc visit, void *arg)
615 block *b;
616 PyObject *item;
617 Py_ssize_t index;
618 Py_ssize_t indexlo = deque->leftindex;
620 for (b = deque->leftblock; b != NULL; b = b->rightlink) {
621 const Py_ssize_t indexhi = b == deque->rightblock ?
622 deque->rightindex :
623 BLOCKLEN - 1;
625 for (index = indexlo; index <= indexhi; ++index) {
626 item = b->data[index];
627 Py_VISIT(item);
629 indexlo = 0;
631 return 0;
634 static PyObject *
635 deque_copy(PyObject *deque)
637 if (((dequeobject *)deque)->maxlen == -1)
638 return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "O", deque, NULL);
639 else
640 return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "Oi",
641 deque, ((dequeobject *)deque)->maxlen, NULL);
644 PyDoc_STRVAR(copy_doc, "Return a shallow copy of a deque.");
646 static PyObject *
647 deque_reduce(dequeobject *deque)
649 PyObject *dict, *result, *aslist;
651 dict = PyObject_GetAttrString((PyObject *)deque, "__dict__");
652 if (dict == NULL)
653 PyErr_Clear();
654 aslist = PySequence_List((PyObject *)deque);
655 if (aslist == NULL) {
656 Py_XDECREF(dict);
657 return NULL;
659 if (dict == NULL) {
660 if (deque->maxlen == -1)
661 result = Py_BuildValue("O(O)", Py_TYPE(deque), aslist);
662 else
663 result = Py_BuildValue("O(On)", Py_TYPE(deque), aslist, deque->maxlen);
664 } else {
665 if (deque->maxlen == -1)
666 result = Py_BuildValue("O(OO)O", Py_TYPE(deque), aslist, Py_None, dict);
667 else
668 result = Py_BuildValue("O(On)O", Py_TYPE(deque), aslist, deque->maxlen, dict);
670 Py_XDECREF(dict);
671 Py_DECREF(aslist);
672 return result;
675 PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
677 static PyObject *
678 deque_repr(PyObject *deque)
680 PyObject *aslist, *result, *fmt;
681 int i;
683 i = Py_ReprEnter(deque);
684 if (i != 0) {
685 if (i < 0)
686 return NULL;
687 return PyString_FromString("[...]");
690 aslist = PySequence_List(deque);
691 if (aslist == NULL) {
692 Py_ReprLeave(deque);
693 return NULL;
695 if (((dequeobject *)deque)->maxlen != -1)
696 fmt = PyString_FromFormat("deque(%%r, maxlen=%zd)",
697 ((dequeobject *)deque)->maxlen);
698 else
699 fmt = PyString_FromString("deque(%r)");
700 if (fmt == NULL) {
701 Py_DECREF(aslist);
702 Py_ReprLeave(deque);
703 return NULL;
705 result = PyString_Format(fmt, aslist);
706 Py_DECREF(fmt);
707 Py_DECREF(aslist);
708 Py_ReprLeave(deque);
709 return result;
712 static int
713 deque_tp_print(PyObject *deque, FILE *fp, int flags)
715 PyObject *it, *item;
716 char *emit = ""; /* No separator emitted on first pass */
717 char *separator = ", ";
718 int i;
720 i = Py_ReprEnter(deque);
721 if (i != 0) {
722 if (i < 0)
723 return i;
724 Py_BEGIN_ALLOW_THREADS
725 fputs("[...]", fp);
726 Py_END_ALLOW_THREADS
727 return 0;
730 it = PyObject_GetIter(deque);
731 if (it == NULL)
732 return -1;
734 Py_BEGIN_ALLOW_THREADS
735 fputs("deque([", fp);
736 Py_END_ALLOW_THREADS
737 while ((item = PyIter_Next(it)) != NULL) {
738 Py_BEGIN_ALLOW_THREADS
739 fputs(emit, fp);
740 Py_END_ALLOW_THREADS
741 emit = separator;
742 if (PyObject_Print(item, fp, 0) != 0) {
743 Py_DECREF(item);
744 Py_DECREF(it);
745 Py_ReprLeave(deque);
746 return -1;
748 Py_DECREF(item);
750 Py_ReprLeave(deque);
751 Py_DECREF(it);
752 if (PyErr_Occurred())
753 return -1;
755 Py_BEGIN_ALLOW_THREADS
756 if (((dequeobject *)deque)->maxlen == -1)
757 fputs("])", fp);
758 else
759 fprintf(fp, "], maxlen=%" PY_FORMAT_SIZE_T "d)", ((dequeobject *)deque)->maxlen);
760 Py_END_ALLOW_THREADS
761 return 0;
764 static PyObject *
765 deque_richcompare(PyObject *v, PyObject *w, int op)
767 PyObject *it1=NULL, *it2=NULL, *x, *y;
768 Py_ssize_t vs, ws;
769 int b, cmp=-1;
771 if (!PyObject_TypeCheck(v, &deque_type) ||
772 !PyObject_TypeCheck(w, &deque_type)) {
773 Py_INCREF(Py_NotImplemented);
774 return Py_NotImplemented;
777 /* Shortcuts */
778 vs = ((dequeobject *)v)->len;
779 ws = ((dequeobject *)w)->len;
780 if (op == Py_EQ) {
781 if (v == w)
782 Py_RETURN_TRUE;
783 if (vs != ws)
784 Py_RETURN_FALSE;
786 if (op == Py_NE) {
787 if (v == w)
788 Py_RETURN_FALSE;
789 if (vs != ws)
790 Py_RETURN_TRUE;
793 /* Search for the first index where items are different */
794 it1 = PyObject_GetIter(v);
795 if (it1 == NULL)
796 goto done;
797 it2 = PyObject_GetIter(w);
798 if (it2 == NULL)
799 goto done;
800 for (;;) {
801 x = PyIter_Next(it1);
802 if (x == NULL && PyErr_Occurred())
803 goto done;
804 y = PyIter_Next(it2);
805 if (x == NULL || y == NULL)
806 break;
807 b = PyObject_RichCompareBool(x, y, Py_EQ);
808 if (b == 0) {
809 cmp = PyObject_RichCompareBool(x, y, op);
810 Py_DECREF(x);
811 Py_DECREF(y);
812 goto done;
814 Py_DECREF(x);
815 Py_DECREF(y);
816 if (b == -1)
817 goto done;
819 /* We reached the end of one deque or both */
820 Py_XDECREF(x);
821 Py_XDECREF(y);
822 if (PyErr_Occurred())
823 goto done;
824 switch (op) {
825 case Py_LT: cmp = y != NULL; break; /* if w was longer */
826 case Py_LE: cmp = x == NULL; break; /* if v was not longer */
827 case Py_EQ: cmp = x == y; break; /* if we reached the end of both */
828 case Py_NE: cmp = x != y; break; /* if one deque continues */
829 case Py_GT: cmp = x != NULL; break; /* if v was longer */
830 case Py_GE: cmp = y == NULL; break; /* if w was not longer */
833 done:
834 Py_XDECREF(it1);
835 Py_XDECREF(it2);
836 if (cmp == 1)
837 Py_RETURN_TRUE;
838 if (cmp == 0)
839 Py_RETURN_FALSE;
840 return NULL;
843 static int
844 deque_init(dequeobject *deque, PyObject *args, PyObject *kwdargs)
846 PyObject *iterable = NULL;
847 PyObject *maxlenobj = NULL;
848 Py_ssize_t maxlen = -1;
849 char *kwlist[] = {"iterable", "maxlen", 0};
851 if (!PyArg_ParseTupleAndKeywords(args, kwdargs, "|OO:deque", kwlist, &iterable, &maxlenobj))
852 return -1;
853 if (maxlenobj != NULL && maxlenobj != Py_None) {
854 maxlen = PyInt_AsSsize_t(maxlenobj);
855 if (maxlen == -1 && PyErr_Occurred())
856 return -1;
857 if (maxlen < 0) {
858 PyErr_SetString(PyExc_ValueError, "maxlen must be non-negative");
859 return -1;
862 deque->maxlen = maxlen;
863 deque_clear(deque);
864 if (iterable != NULL) {
865 PyObject *rv = deque_extend(deque, iterable);
866 if (rv == NULL)
867 return -1;
868 Py_DECREF(rv);
870 return 0;
873 static PyObject *
874 deque_get_maxlen(dequeobject *deque)
876 if (deque->maxlen == -1)
877 Py_RETURN_NONE;
878 return PyInt_FromSsize_t(deque->maxlen);
881 static PyGetSetDef deque_getset[] = {
882 {"maxlen", (getter)deque_get_maxlen, (setter)NULL,
883 "maximum size of a deque or None if unbounded"},
887 static PySequenceMethods deque_as_sequence = {
888 (lenfunc)deque_len, /* sq_length */
889 0, /* sq_concat */
890 0, /* sq_repeat */
891 (ssizeargfunc)deque_item, /* sq_item */
892 0, /* sq_slice */
893 (ssizeobjargproc)deque_ass_item, /* sq_ass_item */
896 /* deque object ********************************************************/
898 static PyObject *deque_iter(dequeobject *deque);
899 static PyObject *deque_reviter(dequeobject *deque);
900 PyDoc_STRVAR(reversed_doc,
901 "D.__reversed__() -- return a reverse iterator over the deque");
903 static PyMethodDef deque_methods[] = {
904 {"append", (PyCFunction)deque_append,
905 METH_O, append_doc},
906 {"appendleft", (PyCFunction)deque_appendleft,
907 METH_O, appendleft_doc},
908 {"clear", (PyCFunction)deque_clearmethod,
909 METH_NOARGS, clear_doc},
910 {"__copy__", (PyCFunction)deque_copy,
911 METH_NOARGS, copy_doc},
912 {"extend", (PyCFunction)deque_extend,
913 METH_O, extend_doc},
914 {"extendleft", (PyCFunction)deque_extendleft,
915 METH_O, extendleft_doc},
916 {"pop", (PyCFunction)deque_pop,
917 METH_NOARGS, pop_doc},
918 {"popleft", (PyCFunction)deque_popleft,
919 METH_NOARGS, popleft_doc},
920 {"__reduce__", (PyCFunction)deque_reduce,
921 METH_NOARGS, reduce_doc},
922 {"remove", (PyCFunction)deque_remove,
923 METH_O, remove_doc},
924 {"__reversed__", (PyCFunction)deque_reviter,
925 METH_NOARGS, reversed_doc},
926 {"rotate", (PyCFunction)deque_rotate,
927 METH_VARARGS, rotate_doc},
928 {NULL, NULL} /* sentinel */
931 PyDoc_STRVAR(deque_doc,
932 "deque(iterable[, maxlen]) --> deque object\n\
934 Build an ordered collection accessible from endpoints only.");
936 static PyTypeObject deque_type = {
937 PyVarObject_HEAD_INIT(NULL, 0)
938 "collections.deque", /* tp_name */
939 sizeof(dequeobject), /* tp_basicsize */
940 0, /* tp_itemsize */
941 /* methods */
942 (destructor)deque_dealloc, /* tp_dealloc */
943 deque_tp_print, /* tp_print */
944 0, /* tp_getattr */
945 0, /* tp_setattr */
946 0, /* tp_compare */
947 deque_repr, /* tp_repr */
948 0, /* tp_as_number */
949 &deque_as_sequence, /* tp_as_sequence */
950 0, /* tp_as_mapping */
951 (hashfunc)PyObject_HashNotImplemented, /* tp_hash */
952 0, /* tp_call */
953 0, /* tp_str */
954 PyObject_GenericGetAttr, /* tp_getattro */
955 0, /* tp_setattro */
956 0, /* tp_as_buffer */
957 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
958 Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
959 deque_doc, /* tp_doc */
960 (traverseproc)deque_traverse, /* tp_traverse */
961 (inquiry)deque_clear, /* tp_clear */
962 (richcmpfunc)deque_richcompare, /* tp_richcompare */
963 offsetof(dequeobject, weakreflist), /* tp_weaklistoffset*/
964 (getiterfunc)deque_iter, /* tp_iter */
965 0, /* tp_iternext */
966 deque_methods, /* tp_methods */
967 0, /* tp_members */
968 deque_getset, /* tp_getset */
969 0, /* tp_base */
970 0, /* tp_dict */
971 0, /* tp_descr_get */
972 0, /* tp_descr_set */
973 0, /* tp_dictoffset */
974 (initproc)deque_init, /* tp_init */
975 PyType_GenericAlloc, /* tp_alloc */
976 deque_new, /* tp_new */
977 PyObject_GC_Del, /* tp_free */
980 /*********************** Deque Iterator **************************/
982 typedef struct {
983 PyObject_HEAD
984 Py_ssize_t index;
985 block *b;
986 dequeobject *deque;
987 long state; /* state when the iterator is created */
988 Py_ssize_t counter; /* number of items remaining for iteration */
989 } dequeiterobject;
991 static PyTypeObject dequeiter_type;
993 static PyObject *
994 deque_iter(dequeobject *deque)
996 dequeiterobject *it;
998 it = PyObject_GC_New(dequeiterobject, &dequeiter_type);
999 if (it == NULL)
1000 return NULL;
1001 it->b = deque->leftblock;
1002 it->index = deque->leftindex;
1003 Py_INCREF(deque);
1004 it->deque = deque;
1005 it->state = deque->state;
1006 it->counter = deque->len;
1007 PyObject_GC_Track(it);
1008 return (PyObject *)it;
1011 static int
1012 dequeiter_traverse(dequeiterobject *dio, visitproc visit, void *arg)
1014 Py_VISIT(dio->deque);
1015 return 0;
1018 static void
1019 dequeiter_dealloc(dequeiterobject *dio)
1021 Py_XDECREF(dio->deque);
1022 PyObject_GC_Del(dio);
1025 static PyObject *
1026 dequeiter_next(dequeiterobject *it)
1028 PyObject *item;
1030 if (it->deque->state != it->state) {
1031 it->counter = 0;
1032 PyErr_SetString(PyExc_RuntimeError,
1033 "deque mutated during iteration");
1034 return NULL;
1036 if (it->counter == 0)
1037 return NULL;
1038 assert (!(it->b == it->deque->rightblock &&
1039 it->index > it->deque->rightindex));
1041 item = it->b->data[it->index];
1042 it->index++;
1043 it->counter--;
1044 if (it->index == BLOCKLEN && it->counter > 0) {
1045 assert (it->b->rightlink != NULL);
1046 it->b = it->b->rightlink;
1047 it->index = 0;
1049 Py_INCREF(item);
1050 return item;
1053 static PyObject *
1054 dequeiter_len(dequeiterobject *it)
1056 return PyInt_FromLong(it->counter);
1059 PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
1061 static PyMethodDef dequeiter_methods[] = {
1062 {"__length_hint__", (PyCFunction)dequeiter_len, METH_NOARGS, length_hint_doc},
1063 {NULL, NULL} /* sentinel */
1066 static PyTypeObject dequeiter_type = {
1067 PyVarObject_HEAD_INIT(NULL, 0)
1068 "deque_iterator", /* tp_name */
1069 sizeof(dequeiterobject), /* tp_basicsize */
1070 0, /* tp_itemsize */
1071 /* methods */
1072 (destructor)dequeiter_dealloc, /* tp_dealloc */
1073 0, /* tp_print */
1074 0, /* tp_getattr */
1075 0, /* tp_setattr */
1076 0, /* tp_compare */
1077 0, /* tp_repr */
1078 0, /* tp_as_number */
1079 0, /* tp_as_sequence */
1080 0, /* tp_as_mapping */
1081 0, /* tp_hash */
1082 0, /* tp_call */
1083 0, /* tp_str */
1084 PyObject_GenericGetAttr, /* tp_getattro */
1085 0, /* tp_setattro */
1086 0, /* tp_as_buffer */
1087 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
1088 0, /* tp_doc */
1089 (traverseproc)dequeiter_traverse, /* tp_traverse */
1090 0, /* tp_clear */
1091 0, /* tp_richcompare */
1092 0, /* tp_weaklistoffset */
1093 PyObject_SelfIter, /* tp_iter */
1094 (iternextfunc)dequeiter_next, /* tp_iternext */
1095 dequeiter_methods, /* tp_methods */
1099 /*********************** Deque Reverse Iterator **************************/
1101 static PyTypeObject dequereviter_type;
1103 static PyObject *
1104 deque_reviter(dequeobject *deque)
1106 dequeiterobject *it;
1108 it = PyObject_GC_New(dequeiterobject, &dequereviter_type);
1109 if (it == NULL)
1110 return NULL;
1111 it->b = deque->rightblock;
1112 it->index = deque->rightindex;
1113 Py_INCREF(deque);
1114 it->deque = deque;
1115 it->state = deque->state;
1116 it->counter = deque->len;
1117 PyObject_GC_Track(it);
1118 return (PyObject *)it;
1121 static PyObject *
1122 dequereviter_next(dequeiterobject *it)
1124 PyObject *item;
1125 if (it->counter == 0)
1126 return NULL;
1128 if (it->deque->state != it->state) {
1129 it->counter = 0;
1130 PyErr_SetString(PyExc_RuntimeError,
1131 "deque mutated during iteration");
1132 return NULL;
1134 assert (!(it->b == it->deque->leftblock &&
1135 it->index < it->deque->leftindex));
1137 item = it->b->data[it->index];
1138 it->index--;
1139 it->counter--;
1140 if (it->index == -1 && it->counter > 0) {
1141 assert (it->b->leftlink != NULL);
1142 it->b = it->b->leftlink;
1143 it->index = BLOCKLEN - 1;
1145 Py_INCREF(item);
1146 return item;
1149 static PyTypeObject dequereviter_type = {
1150 PyVarObject_HEAD_INIT(NULL, 0)
1151 "deque_reverse_iterator", /* tp_name */
1152 sizeof(dequeiterobject), /* tp_basicsize */
1153 0, /* tp_itemsize */
1154 /* methods */
1155 (destructor)dequeiter_dealloc, /* tp_dealloc */
1156 0, /* tp_print */
1157 0, /* tp_getattr */
1158 0, /* tp_setattr */
1159 0, /* tp_compare */
1160 0, /* tp_repr */
1161 0, /* tp_as_number */
1162 0, /* tp_as_sequence */
1163 0, /* tp_as_mapping */
1164 0, /* tp_hash */
1165 0, /* tp_call */
1166 0, /* tp_str */
1167 PyObject_GenericGetAttr, /* tp_getattro */
1168 0, /* tp_setattro */
1169 0, /* tp_as_buffer */
1170 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
1171 0, /* tp_doc */
1172 (traverseproc)dequeiter_traverse, /* tp_traverse */
1173 0, /* tp_clear */
1174 0, /* tp_richcompare */
1175 0, /* tp_weaklistoffset */
1176 PyObject_SelfIter, /* tp_iter */
1177 (iternextfunc)dequereviter_next, /* tp_iternext */
1178 dequeiter_methods, /* tp_methods */
1182 /* defaultdict type *********************************************************/
1184 typedef struct {
1185 PyDictObject dict;
1186 PyObject *default_factory;
1187 } defdictobject;
1189 static PyTypeObject defdict_type; /* Forward */
1191 PyDoc_STRVAR(defdict_missing_doc,
1192 "__missing__(key) # Called by __getitem__ for missing key; pseudo-code:\n\
1193 if self.default_factory is None: raise KeyError((key,))\n\
1194 self[key] = value = self.default_factory()\n\
1195 return value\n\
1198 static PyObject *
1199 defdict_missing(defdictobject *dd, PyObject *key)
1201 PyObject *factory = dd->default_factory;
1202 PyObject *value;
1203 if (factory == NULL || factory == Py_None) {
1204 /* XXX Call dict.__missing__(key) */
1205 PyObject *tup;
1206 tup = PyTuple_Pack(1, key);
1207 if (!tup) return NULL;
1208 PyErr_SetObject(PyExc_KeyError, tup);
1209 Py_DECREF(tup);
1210 return NULL;
1212 value = PyEval_CallObject(factory, NULL);
1213 if (value == NULL)
1214 return value;
1215 if (PyObject_SetItem((PyObject *)dd, key, value) < 0) {
1216 Py_DECREF(value);
1217 return NULL;
1219 return value;
1222 PyDoc_STRVAR(defdict_copy_doc, "D.copy() -> a shallow copy of D.");
1224 static PyObject *
1225 defdict_copy(defdictobject *dd)
1227 /* This calls the object's class. That only works for subclasses
1228 whose class constructor has the same signature. Subclasses that
1229 define a different constructor signature must override copy().
1232 if (dd->default_factory == NULL)
1233 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd), Py_None, dd, NULL);
1234 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd),
1235 dd->default_factory, dd, NULL);
1238 static PyObject *
1239 defdict_reduce(defdictobject *dd)
1241 /* __reduce__ must return a 5-tuple as follows:
1243 - factory function
1244 - tuple of args for the factory function
1245 - additional state (here None)
1246 - sequence iterator (here None)
1247 - dictionary iterator (yielding successive (key, value) pairs
1249 This API is used by pickle.py and copy.py.
1251 For this to be useful with pickle.py, the default_factory
1252 must be picklable; e.g., None, a built-in, or a global
1253 function in a module or package.
1255 Both shallow and deep copying are supported, but for deep
1256 copying, the default_factory must be deep-copyable; e.g. None,
1257 or a built-in (functions are not copyable at this time).
1259 This only works for subclasses as long as their constructor
1260 signature is compatible; the first argument must be the
1261 optional default_factory, defaulting to None.
1263 PyObject *args;
1264 PyObject *items;
1265 PyObject *result;
1266 if (dd->default_factory == NULL || dd->default_factory == Py_None)
1267 args = PyTuple_New(0);
1268 else
1269 args = PyTuple_Pack(1, dd->default_factory);
1270 if (args == NULL)
1271 return NULL;
1272 items = PyObject_CallMethod((PyObject *)dd, "iteritems", "()");
1273 if (items == NULL) {
1274 Py_DECREF(args);
1275 return NULL;
1277 result = PyTuple_Pack(5, Py_TYPE(dd), args,
1278 Py_None, Py_None, items);
1279 Py_DECREF(items);
1280 Py_DECREF(args);
1281 return result;
1284 static PyMethodDef defdict_methods[] = {
1285 {"__missing__", (PyCFunction)defdict_missing, METH_O,
1286 defdict_missing_doc},
1287 {"copy", (PyCFunction)defdict_copy, METH_NOARGS,
1288 defdict_copy_doc},
1289 {"__copy__", (PyCFunction)defdict_copy, METH_NOARGS,
1290 defdict_copy_doc},
1291 {"__reduce__", (PyCFunction)defdict_reduce, METH_NOARGS,
1292 reduce_doc},
1293 {NULL}
1296 static PyMemberDef defdict_members[] = {
1297 {"default_factory", T_OBJECT,
1298 offsetof(defdictobject, default_factory), 0,
1299 PyDoc_STR("Factory for default value called by __missing__().")},
1300 {NULL}
1303 static void
1304 defdict_dealloc(defdictobject *dd)
1306 Py_CLEAR(dd->default_factory);
1307 PyDict_Type.tp_dealloc((PyObject *)dd);
1310 static int
1311 defdict_print(defdictobject *dd, FILE *fp, int flags)
1313 int sts;
1314 Py_BEGIN_ALLOW_THREADS
1315 fprintf(fp, "defaultdict(");
1316 Py_END_ALLOW_THREADS
1317 if (dd->default_factory == NULL) {
1318 Py_BEGIN_ALLOW_THREADS
1319 fprintf(fp, "None");
1320 Py_END_ALLOW_THREADS
1321 } else {
1322 PyObject_Print(dd->default_factory, fp, 0);
1324 Py_BEGIN_ALLOW_THREADS
1325 fprintf(fp, ", ");
1326 Py_END_ALLOW_THREADS
1327 sts = PyDict_Type.tp_print((PyObject *)dd, fp, 0);
1328 Py_BEGIN_ALLOW_THREADS
1329 fprintf(fp, ")");
1330 Py_END_ALLOW_THREADS
1331 return sts;
1334 static PyObject *
1335 defdict_repr(defdictobject *dd)
1337 PyObject *defrepr;
1338 PyObject *baserepr;
1339 PyObject *result;
1340 baserepr = PyDict_Type.tp_repr((PyObject *)dd);
1341 if (baserepr == NULL)
1342 return NULL;
1343 if (dd->default_factory == NULL)
1344 defrepr = PyString_FromString("None");
1345 else
1347 int status = Py_ReprEnter(dd->default_factory);
1348 if (status != 0) {
1349 if (status < 0)
1350 return NULL;
1351 defrepr = PyString_FromString("...");
1353 else
1354 defrepr = PyObject_Repr(dd->default_factory);
1355 Py_ReprLeave(dd->default_factory);
1357 if (defrepr == NULL) {
1358 Py_DECREF(baserepr);
1359 return NULL;
1361 result = PyString_FromFormat("defaultdict(%s, %s)",
1362 PyString_AS_STRING(defrepr),
1363 PyString_AS_STRING(baserepr));
1364 Py_DECREF(defrepr);
1365 Py_DECREF(baserepr);
1366 return result;
1369 static int
1370 defdict_traverse(PyObject *self, visitproc visit, void *arg)
1372 Py_VISIT(((defdictobject *)self)->default_factory);
1373 return PyDict_Type.tp_traverse(self, visit, arg);
1376 static int
1377 defdict_tp_clear(defdictobject *dd)
1379 Py_CLEAR(dd->default_factory);
1380 return PyDict_Type.tp_clear((PyObject *)dd);
1383 static int
1384 defdict_init(PyObject *self, PyObject *args, PyObject *kwds)
1386 defdictobject *dd = (defdictobject *)self;
1387 PyObject *olddefault = dd->default_factory;
1388 PyObject *newdefault = NULL;
1389 PyObject *newargs;
1390 int result;
1391 if (args == NULL || !PyTuple_Check(args))
1392 newargs = PyTuple_New(0);
1393 else {
1394 Py_ssize_t n = PyTuple_GET_SIZE(args);
1395 if (n > 0) {
1396 newdefault = PyTuple_GET_ITEM(args, 0);
1397 if (!PyCallable_Check(newdefault) && newdefault != Py_None) {
1398 PyErr_SetString(PyExc_TypeError,
1399 "first argument must be callable");
1400 return -1;
1403 newargs = PySequence_GetSlice(args, 1, n);
1405 if (newargs == NULL)
1406 return -1;
1407 Py_XINCREF(newdefault);
1408 dd->default_factory = newdefault;
1409 result = PyDict_Type.tp_init(self, newargs, kwds);
1410 Py_DECREF(newargs);
1411 Py_XDECREF(olddefault);
1412 return result;
1415 PyDoc_STRVAR(defdict_doc,
1416 "defaultdict(default_factory) --> dict with default factory\n\
1418 The default factory is called without arguments to produce\n\
1419 a new value when a key is not present, in __getitem__ only.\n\
1420 A defaultdict compares equal to a dict with the same items.\n\
1423 /* See comment in xxsubtype.c */
1424 #define DEFERRED_ADDRESS(ADDR) 0
1426 static PyTypeObject defdict_type = {
1427 PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0)
1428 "collections.defaultdict", /* tp_name */
1429 sizeof(defdictobject), /* tp_basicsize */
1430 0, /* tp_itemsize */
1431 /* methods */
1432 (destructor)defdict_dealloc, /* tp_dealloc */
1433 (printfunc)defdict_print, /* tp_print */
1434 0, /* tp_getattr */
1435 0, /* tp_setattr */
1436 0, /* tp_compare */
1437 (reprfunc)defdict_repr, /* tp_repr */
1438 0, /* tp_as_number */
1439 0, /* tp_as_sequence */
1440 0, /* tp_as_mapping */
1441 0, /* tp_hash */
1442 0, /* tp_call */
1443 0, /* tp_str */
1444 PyObject_GenericGetAttr, /* tp_getattro */
1445 0, /* tp_setattro */
1446 0, /* tp_as_buffer */
1447 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
1448 Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
1449 defdict_doc, /* tp_doc */
1450 defdict_traverse, /* tp_traverse */
1451 (inquiry)defdict_tp_clear, /* tp_clear */
1452 0, /* tp_richcompare */
1453 0, /* tp_weaklistoffset*/
1454 0, /* tp_iter */
1455 0, /* tp_iternext */
1456 defdict_methods, /* tp_methods */
1457 defdict_members, /* tp_members */
1458 0, /* tp_getset */
1459 DEFERRED_ADDRESS(&PyDict_Type), /* tp_base */
1460 0, /* tp_dict */
1461 0, /* tp_descr_get */
1462 0, /* tp_descr_set */
1463 0, /* tp_dictoffset */
1464 defdict_init, /* tp_init */
1465 PyType_GenericAlloc, /* tp_alloc */
1466 0, /* tp_new */
1467 PyObject_GC_Del, /* tp_free */
1470 /* module level code ********************************************************/
1472 PyDoc_STRVAR(module_doc,
1473 "High performance data structures.\n\
1474 - deque: ordered collection accessible from endpoints only\n\
1475 - defaultdict: dict subclass with a default value factory\n\
1478 PyMODINIT_FUNC
1479 init_collections(void)
1481 PyObject *m;
1483 m = Py_InitModule3("_collections", NULL, module_doc);
1484 if (m == NULL)
1485 return;
1487 if (PyType_Ready(&deque_type) < 0)
1488 return;
1489 Py_INCREF(&deque_type);
1490 PyModule_AddObject(m, "deque", (PyObject *)&deque_type);
1492 defdict_type.tp_base = &PyDict_Type;
1493 if (PyType_Ready(&defdict_type) < 0)
1494 return;
1495 Py_INCREF(&defdict_type);
1496 PyModule_AddObject(m, "defaultdict", (PyObject *)&defdict_type);
1498 if (PyType_Ready(&dequeiter_type) < 0)
1499 return;
1501 if (PyType_Ready(&dequereviter_type) < 0)
1502 return;
1504 return;