Blocked revisions 73580-73582 via svnmerge
[python/dscho.git] / Modules / _collectionsmodule.c
blobf8d656cccbfa58328760b04349279f8f3ef9b379
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;
681 int i;
683 i = Py_ReprEnter(deque);
684 if (i != 0) {
685 if (i < 0)
686 return NULL;
687 return PyUnicode_FromString("[...]");
690 aslist = PySequence_List(deque);
691 if (aslist == NULL) {
692 Py_ReprLeave(deque);
693 return NULL;
695 if (((dequeobject *)deque)->maxlen != -1)
697 result = PyUnicode_FromFormat("deque(%R, maxlen=%zd)",
698 aslist, ((dequeobject *)deque)->maxlen);
699 else
700 result = PyUnicode_FromFormat("deque(%R)", aslist);
701 Py_DECREF(aslist);
702 Py_ReprLeave(deque);
703 return result;
706 static PyObject *
707 deque_richcompare(PyObject *v, PyObject *w, int op)
709 PyObject *it1=NULL, *it2=NULL, *x, *y;
710 Py_ssize_t vs, ws;
711 int b, cmp=-1;
713 if (!PyObject_TypeCheck(v, &deque_type) ||
714 !PyObject_TypeCheck(w, &deque_type)) {
715 Py_INCREF(Py_NotImplemented);
716 return Py_NotImplemented;
719 /* Shortcuts */
720 vs = ((dequeobject *)v)->len;
721 ws = ((dequeobject *)w)->len;
722 if (op == Py_EQ) {
723 if (v == w)
724 Py_RETURN_TRUE;
725 if (vs != ws)
726 Py_RETURN_FALSE;
728 if (op == Py_NE) {
729 if (v == w)
730 Py_RETURN_FALSE;
731 if (vs != ws)
732 Py_RETURN_TRUE;
735 /* Search for the first index where items are different */
736 it1 = PyObject_GetIter(v);
737 if (it1 == NULL)
738 goto done;
739 it2 = PyObject_GetIter(w);
740 if (it2 == NULL)
741 goto done;
742 for (;;) {
743 x = PyIter_Next(it1);
744 if (x == NULL && PyErr_Occurred())
745 goto done;
746 y = PyIter_Next(it2);
747 if (x == NULL || y == NULL)
748 break;
749 b = PyObject_RichCompareBool(x, y, Py_EQ);
750 if (b == 0) {
751 cmp = PyObject_RichCompareBool(x, y, op);
752 Py_DECREF(x);
753 Py_DECREF(y);
754 goto done;
756 Py_DECREF(x);
757 Py_DECREF(y);
758 if (b == -1)
759 goto done;
761 /* We reached the end of one deque or both */
762 Py_XDECREF(x);
763 Py_XDECREF(y);
764 if (PyErr_Occurred())
765 goto done;
766 switch (op) {
767 case Py_LT: cmp = y != NULL; break; /* if w was longer */
768 case Py_LE: cmp = x == NULL; break; /* if v was not longer */
769 case Py_EQ: cmp = x == y; break; /* if we reached the end of both */
770 case Py_NE: cmp = x != y; break; /* if one deque continues */
771 case Py_GT: cmp = x != NULL; break; /* if v was longer */
772 case Py_GE: cmp = y == NULL; break; /* if w was not longer */
775 done:
776 Py_XDECREF(it1);
777 Py_XDECREF(it2);
778 if (cmp == 1)
779 Py_RETURN_TRUE;
780 if (cmp == 0)
781 Py_RETURN_FALSE;
782 return NULL;
785 static int
786 deque_init(dequeobject *deque, PyObject *args, PyObject *kwdargs)
788 PyObject *iterable = NULL;
789 PyObject *maxlenobj = NULL;
790 Py_ssize_t maxlen = -1;
791 char *kwlist[] = {"iterable", "maxlen", 0};
793 if (!PyArg_ParseTupleAndKeywords(args, kwdargs, "|OO:deque", kwlist, &iterable, &maxlenobj))
794 return -1;
795 if (maxlenobj != NULL && maxlenobj != Py_None) {
796 maxlen = PyLong_AsSsize_t(maxlenobj);
797 if (maxlen == -1 && PyErr_Occurred())
798 return -1;
799 if (maxlen < 0) {
800 PyErr_SetString(PyExc_ValueError, "maxlen must be non-negative");
801 return -1;
804 deque->maxlen = maxlen;
805 deque_clear(deque);
806 if (iterable != NULL) {
807 PyObject *rv = deque_extend(deque, iterable);
808 if (rv == NULL)
809 return -1;
810 Py_DECREF(rv);
812 return 0;
815 static PyObject *
816 deque_get_maxlen(dequeobject *deque)
818 if (deque->maxlen == -1)
819 Py_RETURN_NONE;
820 return PyLong_FromSsize_t(deque->maxlen);
823 static PyGetSetDef deque_getset[] = {
824 {"maxlen", (getter)deque_get_maxlen, (setter)NULL,
825 "maximum size of a deque or None if unbounded"},
829 static PySequenceMethods deque_as_sequence = {
830 (lenfunc)deque_len, /* sq_length */
831 0, /* sq_concat */
832 0, /* sq_repeat */
833 (ssizeargfunc)deque_item, /* sq_item */
834 0, /* sq_slice */
835 (ssizeobjargproc)deque_ass_item, /* sq_ass_item */
838 /* deque object ********************************************************/
840 static PyObject *deque_iter(dequeobject *deque);
841 static PyObject *deque_reviter(dequeobject *deque);
842 PyDoc_STRVAR(reversed_doc,
843 "D.__reversed__() -- return a reverse iterator over the deque");
845 static PyMethodDef deque_methods[] = {
846 {"append", (PyCFunction)deque_append,
847 METH_O, append_doc},
848 {"appendleft", (PyCFunction)deque_appendleft,
849 METH_O, appendleft_doc},
850 {"clear", (PyCFunction)deque_clearmethod,
851 METH_NOARGS, clear_doc},
852 {"__copy__", (PyCFunction)deque_copy,
853 METH_NOARGS, copy_doc},
854 {"extend", (PyCFunction)deque_extend,
855 METH_O, extend_doc},
856 {"extendleft", (PyCFunction)deque_extendleft,
857 METH_O, extendleft_doc},
858 {"pop", (PyCFunction)deque_pop,
859 METH_NOARGS, pop_doc},
860 {"popleft", (PyCFunction)deque_popleft,
861 METH_NOARGS, popleft_doc},
862 {"__reduce__", (PyCFunction)deque_reduce,
863 METH_NOARGS, reduce_doc},
864 {"remove", (PyCFunction)deque_remove,
865 METH_O, remove_doc},
866 {"__reversed__", (PyCFunction)deque_reviter,
867 METH_NOARGS, reversed_doc},
868 {"rotate", (PyCFunction)deque_rotate,
869 METH_VARARGS, rotate_doc},
870 {NULL, NULL} /* sentinel */
873 PyDoc_STRVAR(deque_doc,
874 "deque(iterable[, maxlen]) --> deque object\n\
876 Build an ordered collection accessible from endpoints only.");
878 static PyTypeObject deque_type = {
879 PyVarObject_HEAD_INIT(NULL, 0)
880 "collections.deque", /* tp_name */
881 sizeof(dequeobject), /* tp_basicsize */
882 0, /* tp_itemsize */
883 /* methods */
884 (destructor)deque_dealloc, /* tp_dealloc */
885 0, /* tp_print */
886 0, /* tp_getattr */
887 0, /* tp_setattr */
888 0, /* tp_reserved */
889 deque_repr, /* tp_repr */
890 0, /* tp_as_number */
891 &deque_as_sequence, /* tp_as_sequence */
892 0, /* tp_as_mapping */
893 (hashfunc)PyObject_HashNotImplemented, /* tp_hash */
894 0, /* tp_call */
895 0, /* tp_str */
896 PyObject_GenericGetAttr, /* tp_getattro */
897 0, /* tp_setattro */
898 0, /* tp_as_buffer */
899 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
900 /* tp_flags */
901 deque_doc, /* tp_doc */
902 (traverseproc)deque_traverse, /* tp_traverse */
903 (inquiry)deque_clear, /* tp_clear */
904 (richcmpfunc)deque_richcompare, /* tp_richcompare */
905 offsetof(dequeobject, weakreflist), /* tp_weaklistoffset*/
906 (getiterfunc)deque_iter, /* tp_iter */
907 0, /* tp_iternext */
908 deque_methods, /* tp_methods */
909 0, /* tp_members */
910 deque_getset, /* tp_getset */
911 0, /* tp_base */
912 0, /* tp_dict */
913 0, /* tp_descr_get */
914 0, /* tp_descr_set */
915 0, /* tp_dictoffset */
916 (initproc)deque_init, /* tp_init */
917 PyType_GenericAlloc, /* tp_alloc */
918 deque_new, /* tp_new */
919 PyObject_GC_Del, /* tp_free */
922 /*********************** Deque Iterator **************************/
924 typedef struct {
925 PyObject_HEAD
926 Py_ssize_t index;
927 block *b;
928 dequeobject *deque;
929 long state; /* state when the iterator is created */
930 Py_ssize_t counter; /* number of items remaining for iteration */
931 } dequeiterobject;
933 static PyTypeObject dequeiter_type;
935 static PyObject *
936 deque_iter(dequeobject *deque)
938 dequeiterobject *it;
940 it = PyObject_GC_New(dequeiterobject, &dequeiter_type);
941 if (it == NULL)
942 return NULL;
943 it->b = deque->leftblock;
944 it->index = deque->leftindex;
945 Py_INCREF(deque);
946 it->deque = deque;
947 it->state = deque->state;
948 it->counter = deque->len;
949 PyObject_GC_Track(it);
950 return (PyObject *)it;
953 static int
954 dequeiter_traverse(dequeiterobject *dio, visitproc visit, void *arg)
956 Py_VISIT(dio->deque);
957 return 0;
960 static void
961 dequeiter_dealloc(dequeiterobject *dio)
963 Py_XDECREF(dio->deque);
964 PyObject_GC_Del(dio);
967 static PyObject *
968 dequeiter_next(dequeiterobject *it)
970 PyObject *item;
972 if (it->deque->state != it->state) {
973 it->counter = 0;
974 PyErr_SetString(PyExc_RuntimeError,
975 "deque mutated during iteration");
976 return NULL;
978 if (it->counter == 0)
979 return NULL;
980 assert (!(it->b == it->deque->rightblock &&
981 it->index > it->deque->rightindex));
983 item = it->b->data[it->index];
984 it->index++;
985 it->counter--;
986 if (it->index == BLOCKLEN && it->counter > 0) {
987 assert (it->b->rightlink != NULL);
988 it->b = it->b->rightlink;
989 it->index = 0;
991 Py_INCREF(item);
992 return item;
995 static PyObject *
996 dequeiter_len(dequeiterobject *it)
998 return PyLong_FromLong(it->counter);
1001 PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
1003 static PyMethodDef dequeiter_methods[] = {
1004 {"__length_hint__", (PyCFunction)dequeiter_len, METH_NOARGS, length_hint_doc},
1005 {NULL, NULL} /* sentinel */
1008 static PyTypeObject dequeiter_type = {
1009 PyVarObject_HEAD_INIT(NULL, 0)
1010 "deque_iterator", /* tp_name */
1011 sizeof(dequeiterobject), /* tp_basicsize */
1012 0, /* tp_itemsize */
1013 /* methods */
1014 (destructor)dequeiter_dealloc, /* tp_dealloc */
1015 0, /* tp_print */
1016 0, /* tp_getattr */
1017 0, /* tp_setattr */
1018 0, /* tp_reserved */
1019 0, /* tp_repr */
1020 0, /* tp_as_number */
1021 0, /* tp_as_sequence */
1022 0, /* tp_as_mapping */
1023 0, /* tp_hash */
1024 0, /* tp_call */
1025 0, /* tp_str */
1026 PyObject_GenericGetAttr, /* tp_getattro */
1027 0, /* tp_setattro */
1028 0, /* tp_as_buffer */
1029 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
1030 0, /* tp_doc */
1031 (traverseproc)dequeiter_traverse, /* tp_traverse */
1032 0, /* tp_clear */
1033 0, /* tp_richcompare */
1034 0, /* tp_weaklistoffset */
1035 PyObject_SelfIter, /* tp_iter */
1036 (iternextfunc)dequeiter_next, /* tp_iternext */
1037 dequeiter_methods, /* tp_methods */
1041 /*********************** Deque Reverse Iterator **************************/
1043 static PyTypeObject dequereviter_type;
1045 static PyObject *
1046 deque_reviter(dequeobject *deque)
1048 dequeiterobject *it;
1050 it = PyObject_GC_New(dequeiterobject, &dequereviter_type);
1051 if (it == NULL)
1052 return NULL;
1053 it->b = deque->rightblock;
1054 it->index = deque->rightindex;
1055 Py_INCREF(deque);
1056 it->deque = deque;
1057 it->state = deque->state;
1058 it->counter = deque->len;
1059 PyObject_GC_Track(it);
1060 return (PyObject *)it;
1063 static PyObject *
1064 dequereviter_next(dequeiterobject *it)
1066 PyObject *item;
1067 if (it->counter == 0)
1068 return NULL;
1070 if (it->deque->state != it->state) {
1071 it->counter = 0;
1072 PyErr_SetString(PyExc_RuntimeError,
1073 "deque mutated during iteration");
1074 return NULL;
1076 assert (!(it->b == it->deque->leftblock &&
1077 it->index < it->deque->leftindex));
1079 item = it->b->data[it->index];
1080 it->index--;
1081 it->counter--;
1082 if (it->index == -1 && it->counter > 0) {
1083 assert (it->b->leftlink != NULL);
1084 it->b = it->b->leftlink;
1085 it->index = BLOCKLEN - 1;
1087 Py_INCREF(item);
1088 return item;
1091 static PyTypeObject dequereviter_type = {
1092 PyVarObject_HEAD_INIT(NULL, 0)
1093 "deque_reverse_iterator", /* tp_name */
1094 sizeof(dequeiterobject), /* tp_basicsize */
1095 0, /* tp_itemsize */
1096 /* methods */
1097 (destructor)dequeiter_dealloc, /* tp_dealloc */
1098 0, /* tp_print */
1099 0, /* tp_getattr */
1100 0, /* tp_setattr */
1101 0, /* tp_reserved */
1102 0, /* tp_repr */
1103 0, /* tp_as_number */
1104 0, /* tp_as_sequence */
1105 0, /* tp_as_mapping */
1106 0, /* tp_hash */
1107 0, /* tp_call */
1108 0, /* tp_str */
1109 PyObject_GenericGetAttr, /* tp_getattro */
1110 0, /* tp_setattro */
1111 0, /* tp_as_buffer */
1112 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
1113 0, /* tp_doc */
1114 (traverseproc)dequeiter_traverse, /* tp_traverse */
1115 0, /* tp_clear */
1116 0, /* tp_richcompare */
1117 0, /* tp_weaklistoffset */
1118 PyObject_SelfIter, /* tp_iter */
1119 (iternextfunc)dequereviter_next, /* tp_iternext */
1120 dequeiter_methods, /* tp_methods */
1124 /* defaultdict type *********************************************************/
1126 typedef struct {
1127 PyDictObject dict;
1128 PyObject *default_factory;
1129 } defdictobject;
1131 static PyTypeObject defdict_type; /* Forward */
1133 PyDoc_STRVAR(defdict_missing_doc,
1134 "__missing__(key) # Called by __getitem__ for missing key; pseudo-code:\n\
1135 if self.default_factory is None: raise KeyError((key,))\n\
1136 self[key] = value = self.default_factory()\n\
1137 return value\n\
1140 static PyObject *
1141 defdict_missing(defdictobject *dd, PyObject *key)
1143 PyObject *factory = dd->default_factory;
1144 PyObject *value;
1145 if (factory == NULL || factory == Py_None) {
1146 /* XXX Call dict.__missing__(key) */
1147 PyObject *tup;
1148 tup = PyTuple_Pack(1, key);
1149 if (!tup) return NULL;
1150 PyErr_SetObject(PyExc_KeyError, tup);
1151 Py_DECREF(tup);
1152 return NULL;
1154 value = PyEval_CallObject(factory, NULL);
1155 if (value == NULL)
1156 return value;
1157 if (PyObject_SetItem((PyObject *)dd, key, value) < 0) {
1158 Py_DECREF(value);
1159 return NULL;
1161 return value;
1164 PyDoc_STRVAR(defdict_copy_doc, "D.copy() -> a shallow copy of D.");
1166 static PyObject *
1167 defdict_copy(defdictobject *dd)
1169 /* This calls the object's class. That only works for subclasses
1170 whose class constructor has the same signature. Subclasses that
1171 define a different constructor signature must override copy().
1173 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd),
1174 dd->default_factory, dd, NULL);
1177 static PyObject *
1178 defdict_reduce(defdictobject *dd)
1180 /* __reduce__ must return a 5-tuple as follows:
1182 - factory function
1183 - tuple of args for the factory function
1184 - additional state (here None)
1185 - sequence iterator (here None)
1186 - dictionary iterator (yielding successive (key, value) pairs
1188 This API is used by pickle.py and copy.py.
1190 For this to be useful with pickle.py, the default_factory
1191 must be picklable; e.g., None, a built-in, or a global
1192 function in a module or package.
1194 Both shallow and deep copying are supported, but for deep
1195 copying, the default_factory must be deep-copyable; e.g. None,
1196 or a built-in (functions are not copyable at this time).
1198 This only works for subclasses as long as their constructor
1199 signature is compatible; the first argument must be the
1200 optional default_factory, defaulting to None.
1202 PyObject *args;
1203 PyObject *items;
1204 PyObject *iter;
1205 PyObject *result;
1206 if (dd->default_factory == NULL || dd->default_factory == Py_None)
1207 args = PyTuple_New(0);
1208 else
1209 args = PyTuple_Pack(1, dd->default_factory);
1210 if (args == NULL)
1211 return NULL;
1212 items = PyObject_CallMethod((PyObject *)dd, "items", "()");
1213 if (items == NULL) {
1214 Py_DECREF(args);
1215 return NULL;
1217 iter = PyObject_GetIter(items);
1218 if (iter == NULL) {
1219 Py_DECREF(items);
1220 Py_DECREF(args);
1221 return NULL;
1223 result = PyTuple_Pack(5, Py_TYPE(dd), args,
1224 Py_None, Py_None, iter);
1225 Py_DECREF(iter);
1226 Py_DECREF(items);
1227 Py_DECREF(args);
1228 return result;
1231 static PyMethodDef defdict_methods[] = {
1232 {"__missing__", (PyCFunction)defdict_missing, METH_O,
1233 defdict_missing_doc},
1234 {"copy", (PyCFunction)defdict_copy, METH_NOARGS,
1235 defdict_copy_doc},
1236 {"__copy__", (PyCFunction)defdict_copy, METH_NOARGS,
1237 defdict_copy_doc},
1238 {"__reduce__", (PyCFunction)defdict_reduce, METH_NOARGS,
1239 reduce_doc},
1240 {NULL}
1243 static PyMemberDef defdict_members[] = {
1244 {"default_factory", T_OBJECT,
1245 offsetof(defdictobject, default_factory), 0,
1246 PyDoc_STR("Factory for default value called by __missing__().")},
1247 {NULL}
1250 static void
1251 defdict_dealloc(defdictobject *dd)
1253 Py_CLEAR(dd->default_factory);
1254 PyDict_Type.tp_dealloc((PyObject *)dd);
1257 static PyObject *
1258 defdict_repr(defdictobject *dd)
1260 PyObject *baserepr;
1261 PyObject *defrepr;
1262 PyObject *result;
1263 baserepr = PyDict_Type.tp_repr((PyObject *)dd);
1264 if (baserepr == NULL)
1265 return NULL;
1266 if (dd->default_factory == NULL)
1267 defrepr = PyUnicode_FromString("None");
1268 else
1270 int status = Py_ReprEnter(dd->default_factory);
1271 if (status != 0) {
1272 if (status < 0)
1273 return NULL;
1274 defrepr = PyUnicode_FromString("...");
1276 else
1277 defrepr = PyObject_Repr(dd->default_factory);
1278 Py_ReprLeave(dd->default_factory);
1280 if (defrepr == NULL) {
1281 Py_DECREF(baserepr);
1282 return NULL;
1284 result = PyUnicode_FromFormat("defaultdict(%U, %U)",
1285 defrepr, baserepr);
1286 Py_DECREF(defrepr);
1287 Py_DECREF(baserepr);
1288 return result;
1291 static int
1292 defdict_traverse(PyObject *self, visitproc visit, void *arg)
1294 Py_VISIT(((defdictobject *)self)->default_factory);
1295 return PyDict_Type.tp_traverse(self, visit, arg);
1298 static int
1299 defdict_tp_clear(defdictobject *dd)
1301 Py_CLEAR(dd->default_factory);
1302 return PyDict_Type.tp_clear((PyObject *)dd);
1305 static int
1306 defdict_init(PyObject *self, PyObject *args, PyObject *kwds)
1308 defdictobject *dd = (defdictobject *)self;
1309 PyObject *olddefault = dd->default_factory;
1310 PyObject *newdefault = NULL;
1311 PyObject *newargs;
1312 int result;
1313 if (args == NULL || !PyTuple_Check(args))
1314 newargs = PyTuple_New(0);
1315 else {
1316 Py_ssize_t n = PyTuple_GET_SIZE(args);
1317 if (n > 0) {
1318 newdefault = PyTuple_GET_ITEM(args, 0);
1319 if (!PyCallable_Check(newdefault)) {
1320 PyErr_SetString(PyExc_TypeError,
1321 "first argument must be callable");
1322 return -1;
1325 newargs = PySequence_GetSlice(args, 1, n);
1327 if (newargs == NULL)
1328 return -1;
1329 Py_XINCREF(newdefault);
1330 dd->default_factory = newdefault;
1331 result = PyDict_Type.tp_init(self, newargs, kwds);
1332 Py_DECREF(newargs);
1333 Py_XDECREF(olddefault);
1334 return result;
1337 PyDoc_STRVAR(defdict_doc,
1338 "defaultdict(default_factory) --> dict with default factory\n\
1340 The default factory is called without arguments to produce\n\
1341 a new value when a key is not present, in __getitem__ only.\n\
1342 A defaultdict compares equal to a dict with the same items.\n\
1345 /* See comment in xxsubtype.c */
1346 #define DEFERRED_ADDRESS(ADDR) 0
1348 static PyTypeObject defdict_type = {
1349 PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0)
1350 "collections.defaultdict", /* tp_name */
1351 sizeof(defdictobject), /* tp_basicsize */
1352 0, /* tp_itemsize */
1353 /* methods */
1354 (destructor)defdict_dealloc, /* tp_dealloc */
1355 0, /* tp_print */
1356 0, /* tp_getattr */
1357 0, /* tp_setattr */
1358 0, /* tp_reserved */
1359 (reprfunc)defdict_repr, /* tp_repr */
1360 0, /* tp_as_number */
1361 0, /* tp_as_sequence */
1362 0, /* tp_as_mapping */
1363 0, /* tp_hash */
1364 0, /* tp_call */
1365 0, /* tp_str */
1366 PyObject_GenericGetAttr, /* tp_getattro */
1367 0, /* tp_setattro */
1368 0, /* tp_as_buffer */
1369 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
1370 /* tp_flags */
1371 defdict_doc, /* tp_doc */
1372 defdict_traverse, /* tp_traverse */
1373 (inquiry)defdict_tp_clear, /* tp_clear */
1374 0, /* tp_richcompare */
1375 0, /* tp_weaklistoffset*/
1376 0, /* tp_iter */
1377 0, /* tp_iternext */
1378 defdict_methods, /* tp_methods */
1379 defdict_members, /* tp_members */
1380 0, /* tp_getset */
1381 DEFERRED_ADDRESS(&PyDict_Type), /* tp_base */
1382 0, /* tp_dict */
1383 0, /* tp_descr_get */
1384 0, /* tp_descr_set */
1385 0, /* tp_dictoffset */
1386 defdict_init, /* tp_init */
1387 PyType_GenericAlloc, /* tp_alloc */
1388 0, /* tp_new */
1389 PyObject_GC_Del, /* tp_free */
1392 /* module level code ********************************************************/
1394 PyDoc_STRVAR(module_doc,
1395 "High performance data structures.\n\
1396 - deque: ordered collection accessible from endpoints only\n\
1397 - defaultdict: dict subclass with a default value factory\n\
1401 static struct PyModuleDef _collectionsmodule = {
1402 PyModuleDef_HEAD_INIT,
1403 "_collections",
1404 module_doc,
1406 NULL,
1407 NULL,
1408 NULL,
1409 NULL,
1410 NULL
1413 PyMODINIT_FUNC
1414 PyInit__collections(void)
1416 PyObject *m;
1418 m = PyModule_Create(&_collectionsmodule);
1419 if (m == NULL)
1420 return NULL;
1422 if (PyType_Ready(&deque_type) < 0)
1423 return NULL;
1424 Py_INCREF(&deque_type);
1425 PyModule_AddObject(m, "deque", (PyObject *)&deque_type);
1427 defdict_type.tp_base = &PyDict_Type;
1428 if (PyType_Ready(&defdict_type) < 0)
1429 return NULL;
1430 Py_INCREF(&defdict_type);
1431 PyModule_AddObject(m, "defaultdict", (PyObject *)&defdict_type);
1433 if (PyType_Ready(&dequeiter_type) < 0)
1434 return NULL;
1436 if (PyType_Ready(&dequereviter_type) < 0)
1437 return NULL;
1439 return m;