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.
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.
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
48 typedef struct BLOCK
{
49 struct BLOCK
*leftlink
;
50 struct BLOCK
*rightlink
;
51 PyObject
*data
[BLOCKLEN
];
54 #define MAXFREEBLOCKS 10
55 static Py_ssize_t numfreeblocks
= 0;
56 static block
*freeblocks
[MAXFREEBLOCKS
];
59 newblock(block
*leftlink
, block
*rightlink
, Py_ssize_t len
) {
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");
75 b
= freeblocks
[numfreeblocks
];
77 b
= PyMem_Malloc(sizeof(block
));
83 b
->leftlink
= leftlink
;
84 b
->rightlink
= rightlink
;
91 if (numfreeblocks
< MAXFREEBLOCKS
) {
92 freeblocks
[numfreeblocks
] = b
;
103 Py_ssize_t leftindex
; /* in range(BLOCKLEN) */
104 Py_ssize_t rightindex
; /* in range(BLOCKLEN) */
107 long state
; /* incremented whenever the indices move */
108 PyObject
*weakreflist
; /* List of weak references */
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); \
127 static PyTypeObject deque_type
;
130 deque_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
135 /* create dequeobject structure */
136 deque
= (dequeobject
*)type
->tp_alloc(type
, 0);
140 b
= newblock(NULL
, NULL
, 0);
146 assert(BLOCKLEN
>= 2);
147 deque
->leftblock
= b
;
148 deque
->rightblock
= b
;
149 deque
->leftindex
= CENTER
+ 1;
150 deque
->rightindex
= CENTER
;
153 deque
->weakreflist
= NULL
;
156 return (PyObject
*)deque
;
160 deque_pop(dequeobject
*deque
, PyObject
*unused
)
165 if (deque
->len
== 0) {
166 PyErr_SetString(PyExc_IndexError
, "pop from an empty deque");
169 item
= deque
->rightblock
->data
[deque
->rightindex
];
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
;
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;
193 PyDoc_STRVAR(pop_doc
, "Remove and return the rightmost element.");
196 deque_popleft(dequeobject
*deque
, PyObject
*unused
)
201 if (deque
->len
== 0) {
202 PyErr_SetString(PyExc_IndexError
, "pop from an empty deque");
205 assert(deque
->leftblock
!= NULL
);
206 item
= deque
->leftblock
->data
[deque
->leftindex
];
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
;
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;
231 PyDoc_STRVAR(popleft_doc
, "Remove and return the leftmost element.");
234 deque_append(dequeobject
*deque
, PyObject
*item
)
237 if (deque
->rightindex
== BLOCKLEN
-1) {
238 block
*b
= newblock(deque
->rightblock
, NULL
, deque
->len
);
241 assert(deque
->rightblock
->rightlink
== NULL
);
242 deque
->rightblock
->rightlink
= b
;
243 deque
->rightblock
= b
;
244 deque
->rightindex
= -1;
249 deque
->rightblock
->data
[deque
->rightindex
] = item
;
250 TRIM(deque
, deque_popleft
);
254 PyDoc_STRVAR(append_doc
, "Add an element to the right side of the deque.");
257 deque_appendleft(dequeobject
*deque
, PyObject
*item
)
260 if (deque
->leftindex
== 0) {
261 block
*b
= newblock(NULL
, deque
->leftblock
, deque
->len
);
264 assert(deque
->leftblock
->leftlink
== NULL
);
265 deque
->leftblock
->leftlink
= b
;
266 deque
->leftblock
= b
;
267 deque
->leftindex
= BLOCKLEN
;
272 deque
->leftblock
->data
[deque
->leftindex
] = item
;
273 TRIM(deque
, deque_pop
);
277 PyDoc_STRVAR(appendleft_doc
, "Add an element to the left side of the deque.");
280 deque_extend(dequeobject
*deque
, PyObject
*iterable
)
284 it
= PyObject_GetIter(iterable
);
288 while ((item
= PyIter_Next(it
)) != NULL
) {
290 if (deque
->rightindex
== BLOCKLEN
-1) {
291 block
*b
= newblock(deque
->rightblock
, NULL
,
298 assert(deque
->rightblock
->rightlink
== NULL
);
299 deque
->rightblock
->rightlink
= b
;
300 deque
->rightblock
= b
;
301 deque
->rightindex
= -1;
305 deque
->rightblock
->data
[deque
->rightindex
] = item
;
306 TRIM(deque
, deque_popleft
);
309 if (PyErr_Occurred())
314 PyDoc_STRVAR(extend_doc
,
315 "Extend the right side of the deque with elements from the iterable");
318 deque_extendleft(dequeobject
*deque
, PyObject
*iterable
)
322 it
= PyObject_GetIter(iterable
);
326 while ((item
= PyIter_Next(it
)) != NULL
) {
328 if (deque
->leftindex
== 0) {
329 block
*b
= newblock(NULL
, deque
->leftblock
,
336 assert(deque
->leftblock
->leftlink
== NULL
);
337 deque
->leftblock
->leftlink
= b
;
338 deque
->leftblock
= b
;
339 deque
->leftindex
= BLOCKLEN
;
343 deque
->leftblock
->data
[deque
->leftindex
] = item
;
344 TRIM(deque
, deque_pop
);
347 if (PyErr_Occurred())
352 PyDoc_STRVAR(extendleft_doc
,
353 "Extend the left side of the deque with elements from the iterable");
356 _deque_rotate(dequeobject
*deque
, Py_ssize_t n
)
358 Py_ssize_t i
, len
=deque
->len
, halflen
=(len
+1)>>1;
363 if (n
> halflen
|| n
< -halflen
) {
367 else if (n
< -halflen
)
371 for (i
=0 ; i
<n
; i
++) {
372 item
= deque_pop(deque
, NULL
);
373 assert (item
!= NULL
);
374 rv
= deque_appendleft(deque
, item
);
380 for (i
=0 ; i
>n
; i
--) {
381 item
= deque_popleft(deque
, NULL
);
382 assert (item
!= NULL
);
383 rv
= deque_append(deque
, item
);
393 deque_rotate(dequeobject
*deque
, PyObject
*args
)
397 if (!PyArg_ParseTuple(args
, "|n:rotate", &n
))
399 if (_deque_rotate(deque
, n
) == 0)
404 PyDoc_STRVAR(rotate_doc
,
405 "Rotate the deque n steps to the right (default n=1). If n is negative, rotates left.");
408 deque_len(dequeobject
*deque
)
414 deque_remove(dequeobject
*deque
, PyObject
*value
)
416 Py_ssize_t i
, n
=deque
->len
;
418 for (i
=0 ; i
<n
; i
++) {
419 PyObject
*item
= deque
->leftblock
->data
[deque
->leftindex
];
420 int cmp
= PyObject_RichCompareBool(item
, value
, Py_EQ
);
422 if (deque
->len
!= n
) {
423 PyErr_SetString(PyExc_IndexError
,
424 "deque mutated during remove().");
428 PyObject
*tgt
= deque_popleft(deque
, NULL
);
429 assert (tgt
!= NULL
);
431 if (_deque_rotate(deque
, i
) == -1)
436 _deque_rotate(deque
, i
);
439 _deque_rotate(deque
, -1);
441 PyErr_SetString(PyExc_ValueError
, "deque.remove(x): x not in deque");
445 PyDoc_STRVAR(remove_doc
,
446 "D.remove(value) -- remove first occurrence of value.");
449 deque_clear(dequeobject
*deque
)
454 item
= deque_pop(deque
, NULL
);
455 assert (item
!= NULL
);
458 assert(deque
->leftblock
== deque
->rightblock
&&
459 deque
->leftindex
- 1 == deque
->rightindex
&&
465 deque_item(dequeobject
*deque
, Py_ssize_t i
)
469 Py_ssize_t n
, index
=i
;
471 if (i
< 0 || i
>= deque
->len
) {
472 PyErr_SetString(PyExc_IndexError
,
473 "deque index out of range");
478 i
= deque
->leftindex
;
479 b
= deque
->leftblock
;
480 } else if (i
== deque
->len
- 1) {
481 i
= deque
->rightindex
;
482 b
= deque
->rightblock
;
484 i
+= deque
->leftindex
;
487 if (index
< (deque
->len
>> 1)) {
488 b
= deque
->leftblock
;
492 n
= (deque
->leftindex
+ deque
->len
- 1) / BLOCKLEN
- n
;
493 b
= deque
->rightblock
;
503 /* delitem() implemented in terms of rotate for simplicity and reasonable
504 performance near the end points. If for some reason this method becomes
505 popular, it is not hard to re-implement this using direct data movement
506 (similar to code in list slice assignment) and achieve a two or threefold
511 deque_del_item(dequeobject
*deque
, Py_ssize_t i
)
515 assert (i
>= 0 && i
< deque
->len
);
516 if (_deque_rotate(deque
, -i
) == -1)
519 item
= deque_popleft(deque
, NULL
);
520 assert (item
!= NULL
);
523 return _deque_rotate(deque
, i
);
527 deque_ass_item(dequeobject
*deque
, Py_ssize_t i
, PyObject
*v
)
531 Py_ssize_t n
, len
=deque
->len
, halflen
=(len
+1)>>1, index
=i
;
533 if (i
< 0 || i
>= len
) {
534 PyErr_SetString(PyExc_IndexError
,
535 "deque index out of range");
539 return deque_del_item(deque
, i
);
541 i
+= deque
->leftindex
;
544 if (index
<= halflen
) {
545 b
= deque
->leftblock
;
549 n
= (deque
->leftindex
+ len
- 1) / BLOCKLEN
- n
;
550 b
= deque
->rightblock
;
555 old_value
= b
->data
[i
];
557 Py_DECREF(old_value
);
562 deque_clearmethod(dequeobject
*deque
)
566 rv
= deque_clear(deque
);
571 PyDoc_STRVAR(clear_doc
, "Remove all elements from the deque.");
574 deque_dealloc(dequeobject
*deque
)
576 PyObject_GC_UnTrack(deque
);
577 if (deque
->weakreflist
!= NULL
)
578 PyObject_ClearWeakRefs((PyObject
*) deque
);
579 if (deque
->leftblock
!= NULL
) {
581 assert(deque
->leftblock
!= NULL
);
582 freeblock(deque
->leftblock
);
584 deque
->leftblock
= NULL
;
585 deque
->rightblock
= NULL
;
586 Py_TYPE(deque
)->tp_free(deque
);
590 deque_traverse(dequeobject
*deque
, visitproc visit
, void *arg
)
595 Py_ssize_t indexlo
= deque
->leftindex
;
597 for (b
= deque
->leftblock
; b
!= NULL
; b
= b
->rightlink
) {
598 const Py_ssize_t indexhi
= b
== deque
->rightblock
?
602 for (index
= indexlo
; index
<= indexhi
; ++index
) {
603 item
= b
->data
[index
];
612 deque_copy(PyObject
*deque
)
614 if (((dequeobject
*)deque
)->maxlen
== -1)
615 return PyObject_CallFunction((PyObject
*)(Py_TYPE(deque
)), "O", deque
, NULL
);
617 return PyObject_CallFunction((PyObject
*)(Py_TYPE(deque
)), "Oi",
618 deque
, ((dequeobject
*)deque
)->maxlen
, NULL
);
621 PyDoc_STRVAR(copy_doc
, "Return a shallow copy of a deque.");
624 deque_reduce(dequeobject
*deque
)
626 PyObject
*dict
, *result
, *aslist
;
628 dict
= PyObject_GetAttrString((PyObject
*)deque
, "__dict__");
631 aslist
= PySequence_List((PyObject
*)deque
);
632 if (aslist
== NULL
) {
637 if (deque
->maxlen
== -1)
638 result
= Py_BuildValue("O(O)", Py_TYPE(deque
), aslist
);
640 result
= Py_BuildValue("O(On)", Py_TYPE(deque
), aslist
, deque
->maxlen
);
642 if (deque
->maxlen
== -1)
643 result
= Py_BuildValue("O(OO)O", Py_TYPE(deque
), aslist
, Py_None
, dict
);
645 result
= Py_BuildValue("O(On)O", Py_TYPE(deque
), aslist
, deque
->maxlen
, dict
);
652 PyDoc_STRVAR(reduce_doc
, "Return state information for pickling.");
655 deque_repr(PyObject
*deque
)
657 PyObject
*aslist
, *result
, *fmt
;
660 i
= Py_ReprEnter(deque
);
664 return PyString_FromString("[...]");
667 aslist
= PySequence_List(deque
);
668 if (aslist
== NULL
) {
672 if (((dequeobject
*)deque
)->maxlen
!= -1)
673 fmt
= PyString_FromFormat("deque(%%r, maxlen=%i)",
674 ((dequeobject
*)deque
)->maxlen
);
676 fmt
= PyString_FromString("deque(%r)");
682 result
= PyString_Format(fmt
, aslist
);
690 deque_tp_print(PyObject
*deque
, FILE *fp
, int flags
)
693 char *emit
= ""; /* No separator emitted on first pass */
694 char *separator
= ", ";
697 i
= Py_ReprEnter(deque
);
701 Py_BEGIN_ALLOW_THREADS
707 it
= PyObject_GetIter(deque
);
711 Py_BEGIN_ALLOW_THREADS
712 fputs("deque([", fp
);
714 while ((item
= PyIter_Next(it
)) != NULL
) {
715 Py_BEGIN_ALLOW_THREADS
719 if (PyObject_Print(item
, fp
, 0) != 0) {
729 if (PyErr_Occurred())
732 Py_BEGIN_ALLOW_THREADS
733 if (((dequeobject
*)deque
)->maxlen
== -1)
736 fprintf(fp
, "], maxlen=%d)", ((dequeobject
*)deque
)->maxlen
);
742 deque_richcompare(PyObject
*v
, PyObject
*w
, int op
)
744 PyObject
*it1
=NULL
, *it2
=NULL
, *x
, *y
;
748 if (!PyObject_TypeCheck(v
, &deque_type
) ||
749 !PyObject_TypeCheck(w
, &deque_type
)) {
750 Py_INCREF(Py_NotImplemented
);
751 return Py_NotImplemented
;
755 vs
= ((dequeobject
*)v
)->len
;
756 ws
= ((dequeobject
*)w
)->len
;
770 /* Search for the first index where items are different */
771 it1
= PyObject_GetIter(v
);
774 it2
= PyObject_GetIter(w
);
778 x
= PyIter_Next(it1
);
779 if (x
== NULL
&& PyErr_Occurred())
781 y
= PyIter_Next(it2
);
782 if (x
== NULL
|| y
== NULL
)
784 b
= PyObject_RichCompareBool(x
, y
, Py_EQ
);
786 cmp
= PyObject_RichCompareBool(x
, y
, op
);
796 /* We reached the end of one deque or both */
799 if (PyErr_Occurred())
802 case Py_LT
: cmp
= y
!= NULL
; break; /* if w was longer */
803 case Py_LE
: cmp
= x
== NULL
; break; /* if v was not longer */
804 case Py_EQ
: cmp
= x
== y
; break; /* if we reached the end of both */
805 case Py_NE
: cmp
= x
!= y
; break; /* if one deque continues */
806 case Py_GT
: cmp
= x
!= NULL
; break; /* if v was longer */
807 case Py_GE
: cmp
= y
== NULL
; break; /* if w was not longer */
821 deque_init(dequeobject
*deque
, PyObject
*args
, PyObject
*kwdargs
)
823 PyObject
*iterable
= NULL
;
824 PyObject
*maxlenobj
= NULL
;
825 Py_ssize_t maxlen
= -1;
826 char *kwlist
[] = {"iterable", "maxlen", 0};
828 if (!PyArg_ParseTupleAndKeywords(args
, kwdargs
, "|OO:deque", kwlist
, &iterable
, &maxlenobj
))
830 if (maxlenobj
!= NULL
&& maxlenobj
!= Py_None
) {
831 maxlen
= PyInt_AsSsize_t(maxlenobj
);
832 if (maxlen
== -1 && PyErr_Occurred())
835 PyErr_SetString(PyExc_ValueError
, "maxlen must be non-negative");
839 deque
->maxlen
= maxlen
;
841 if (iterable
!= NULL
) {
842 PyObject
*rv
= deque_extend(deque
, iterable
);
850 static PySequenceMethods deque_as_sequence
= {
851 (lenfunc
)deque_len
, /* sq_length */
854 (ssizeargfunc
)deque_item
, /* sq_item */
856 (ssizeobjargproc
)deque_ass_item
, /* sq_ass_item */
859 /* deque object ********************************************************/
861 static PyObject
*deque_iter(dequeobject
*deque
);
862 static PyObject
*deque_reviter(dequeobject
*deque
);
863 PyDoc_STRVAR(reversed_doc
,
864 "D.__reversed__() -- return a reverse iterator over the deque");
866 static PyMethodDef deque_methods
[] = {
867 {"append", (PyCFunction
)deque_append
,
869 {"appendleft", (PyCFunction
)deque_appendleft
,
870 METH_O
, appendleft_doc
},
871 {"clear", (PyCFunction
)deque_clearmethod
,
872 METH_NOARGS
, clear_doc
},
873 {"__copy__", (PyCFunction
)deque_copy
,
874 METH_NOARGS
, copy_doc
},
875 {"extend", (PyCFunction
)deque_extend
,
877 {"extendleft", (PyCFunction
)deque_extendleft
,
878 METH_O
, extendleft_doc
},
879 {"pop", (PyCFunction
)deque_pop
,
880 METH_NOARGS
, pop_doc
},
881 {"popleft", (PyCFunction
)deque_popleft
,
882 METH_NOARGS
, popleft_doc
},
883 {"__reduce__", (PyCFunction
)deque_reduce
,
884 METH_NOARGS
, reduce_doc
},
885 {"remove", (PyCFunction
)deque_remove
,
887 {"__reversed__", (PyCFunction
)deque_reviter
,
888 METH_NOARGS
, reversed_doc
},
889 {"rotate", (PyCFunction
)deque_rotate
,
890 METH_VARARGS
, rotate_doc
},
891 {NULL
, NULL
} /* sentinel */
894 PyDoc_STRVAR(deque_doc
,
895 "deque(iterable[, maxlen]) --> deque object\n\
897 Build an ordered collection accessible from endpoints only.");
899 static PyTypeObject deque_type
= {
900 PyVarObject_HEAD_INIT(NULL
, 0)
901 "collections.deque", /* tp_name */
902 sizeof(dequeobject
), /* tp_basicsize */
905 (destructor
)deque_dealloc
, /* tp_dealloc */
906 deque_tp_print
, /* tp_print */
910 deque_repr
, /* tp_repr */
911 0, /* tp_as_number */
912 &deque_as_sequence
, /* tp_as_sequence */
913 0, /* tp_as_mapping */
914 (hashfunc
)PyObject_HashNotImplemented
, /* tp_hash */
917 PyObject_GenericGetAttr
, /* tp_getattro */
919 0, /* tp_as_buffer */
920 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
| Py_TPFLAGS_HAVE_GC
|
921 Py_TPFLAGS_HAVE_WEAKREFS
, /* tp_flags */
922 deque_doc
, /* tp_doc */
923 (traverseproc
)deque_traverse
, /* tp_traverse */
924 (inquiry
)deque_clear
, /* tp_clear */
925 (richcmpfunc
)deque_richcompare
, /* tp_richcompare */
926 offsetof(dequeobject
, weakreflist
), /* tp_weaklistoffset*/
927 (getiterfunc
)deque_iter
, /* tp_iter */
929 deque_methods
, /* tp_methods */
934 0, /* tp_descr_get */
935 0, /* tp_descr_set */
936 0, /* tp_dictoffset */
937 (initproc
)deque_init
, /* tp_init */
938 PyType_GenericAlloc
, /* tp_alloc */
939 deque_new
, /* tp_new */
940 PyObject_GC_Del
, /* tp_free */
943 /*********************** Deque Iterator **************************/
950 long state
; /* state when the iterator is created */
951 Py_ssize_t counter
; /* number of items remaining for iteration */
954 static PyTypeObject dequeiter_type
;
957 deque_iter(dequeobject
*deque
)
961 it
= PyObject_New(dequeiterobject
, &dequeiter_type
);
964 it
->b
= deque
->leftblock
;
965 it
->index
= deque
->leftindex
;
968 it
->state
= deque
->state
;
969 it
->counter
= deque
->len
;
970 return (PyObject
*)it
;
974 dequeiter_dealloc(dequeiterobject
*dio
)
976 Py_XDECREF(dio
->deque
);
977 Py_TYPE(dio
)->tp_free(dio
);
981 dequeiter_next(dequeiterobject
*it
)
985 if (it
->deque
->state
!= it
->state
) {
987 PyErr_SetString(PyExc_RuntimeError
,
988 "deque mutated during iteration");
991 if (it
->counter
== 0)
993 assert (!(it
->b
== it
->deque
->rightblock
&&
994 it
->index
> it
->deque
->rightindex
));
996 item
= it
->b
->data
[it
->index
];
999 if (it
->index
== BLOCKLEN
&& it
->counter
> 0) {
1000 assert (it
->b
->rightlink
!= NULL
);
1001 it
->b
= it
->b
->rightlink
;
1009 dequeiter_len(dequeiterobject
*it
)
1011 return PyInt_FromLong(it
->counter
);
1014 PyDoc_STRVAR(length_hint_doc
, "Private method returning an estimate of len(list(it)).");
1016 static PyMethodDef dequeiter_methods
[] = {
1017 {"__length_hint__", (PyCFunction
)dequeiter_len
, METH_NOARGS
, length_hint_doc
},
1018 {NULL
, NULL
} /* sentinel */
1021 static PyTypeObject dequeiter_type
= {
1022 PyVarObject_HEAD_INIT(NULL
, 0)
1023 "deque_iterator", /* tp_name */
1024 sizeof(dequeiterobject
), /* tp_basicsize */
1025 0, /* tp_itemsize */
1027 (destructor
)dequeiter_dealloc
, /* tp_dealloc */
1033 0, /* tp_as_number */
1034 0, /* tp_as_sequence */
1035 0, /* tp_as_mapping */
1039 PyObject_GenericGetAttr
, /* tp_getattro */
1040 0, /* tp_setattro */
1041 0, /* tp_as_buffer */
1042 Py_TPFLAGS_DEFAULT
, /* tp_flags */
1044 0, /* tp_traverse */
1046 0, /* tp_richcompare */
1047 0, /* tp_weaklistoffset */
1048 PyObject_SelfIter
, /* tp_iter */
1049 (iternextfunc
)dequeiter_next
, /* tp_iternext */
1050 dequeiter_methods
, /* tp_methods */
1054 /*********************** Deque Reverse Iterator **************************/
1056 static PyTypeObject dequereviter_type
;
1059 deque_reviter(dequeobject
*deque
)
1061 dequeiterobject
*it
;
1063 it
= PyObject_New(dequeiterobject
, &dequereviter_type
);
1066 it
->b
= deque
->rightblock
;
1067 it
->index
= deque
->rightindex
;
1070 it
->state
= deque
->state
;
1071 it
->counter
= deque
->len
;
1072 return (PyObject
*)it
;
1076 dequereviter_next(dequeiterobject
*it
)
1079 if (it
->counter
== 0)
1082 if (it
->deque
->state
!= it
->state
) {
1084 PyErr_SetString(PyExc_RuntimeError
,
1085 "deque mutated during iteration");
1088 assert (!(it
->b
== it
->deque
->leftblock
&&
1089 it
->index
< it
->deque
->leftindex
));
1091 item
= it
->b
->data
[it
->index
];
1094 if (it
->index
== -1 && it
->counter
> 0) {
1095 assert (it
->b
->leftlink
!= NULL
);
1096 it
->b
= it
->b
->leftlink
;
1097 it
->index
= BLOCKLEN
- 1;
1103 static PyTypeObject dequereviter_type
= {
1104 PyVarObject_HEAD_INIT(NULL
, 0)
1105 "deque_reverse_iterator", /* tp_name */
1106 sizeof(dequeiterobject
), /* tp_basicsize */
1107 0, /* tp_itemsize */
1109 (destructor
)dequeiter_dealloc
, /* tp_dealloc */
1115 0, /* tp_as_number */
1116 0, /* tp_as_sequence */
1117 0, /* tp_as_mapping */
1121 PyObject_GenericGetAttr
, /* tp_getattro */
1122 0, /* tp_setattro */
1123 0, /* tp_as_buffer */
1124 Py_TPFLAGS_DEFAULT
, /* tp_flags */
1126 0, /* tp_traverse */
1128 0, /* tp_richcompare */
1129 0, /* tp_weaklistoffset */
1130 PyObject_SelfIter
, /* tp_iter */
1131 (iternextfunc
)dequereviter_next
, /* tp_iternext */
1132 dequeiter_methods
, /* tp_methods */
1136 /* defaultdict type *********************************************************/
1140 PyObject
*default_factory
;
1143 static PyTypeObject defdict_type
; /* Forward */
1145 PyDoc_STRVAR(defdict_missing_doc
,
1146 "__missing__(key) # Called by __getitem__ for missing key; pseudo-code:\n\
1147 if self.default_factory is None: raise KeyError((key,))\n\
1148 self[key] = value = self.default_factory()\n\
1153 defdict_missing(defdictobject
*dd
, PyObject
*key
)
1155 PyObject
*factory
= dd
->default_factory
;
1157 if (factory
== NULL
|| factory
== Py_None
) {
1158 /* XXX Call dict.__missing__(key) */
1160 tup
= PyTuple_Pack(1, key
);
1161 if (!tup
) return NULL
;
1162 PyErr_SetObject(PyExc_KeyError
, tup
);
1166 value
= PyEval_CallObject(factory
, NULL
);
1169 if (PyObject_SetItem((PyObject
*)dd
, key
, value
) < 0) {
1176 PyDoc_STRVAR(defdict_copy_doc
, "D.copy() -> a shallow copy of D.");
1179 defdict_copy(defdictobject
*dd
)
1181 /* This calls the object's class. That only works for subclasses
1182 whose class constructor has the same signature. Subclasses that
1183 define a different constructor signature must override copy().
1185 return PyObject_CallFunctionObjArgs((PyObject
*)Py_TYPE(dd
),
1186 dd
->default_factory
, dd
, NULL
);
1190 defdict_reduce(defdictobject
*dd
)
1192 /* __reduce__ must return a 5-tuple as follows:
1195 - tuple of args for the factory function
1196 - additional state (here None)
1197 - sequence iterator (here None)
1198 - dictionary iterator (yielding successive (key, value) pairs
1200 This API is used by pickle.py and copy.py.
1202 For this to be useful with pickle.py, the default_factory
1203 must be picklable; e.g., None, a built-in, or a global
1204 function in a module or package.
1206 Both shallow and deep copying are supported, but for deep
1207 copying, the default_factory must be deep-copyable; e.g. None,
1208 or a built-in (functions are not copyable at this time).
1210 This only works for subclasses as long as their constructor
1211 signature is compatible; the first argument must be the
1212 optional default_factory, defaulting to None.
1217 if (dd
->default_factory
== NULL
|| dd
->default_factory
== Py_None
)
1218 args
= PyTuple_New(0);
1220 args
= PyTuple_Pack(1, dd
->default_factory
);
1223 items
= PyObject_CallMethod((PyObject
*)dd
, "iteritems", "()");
1224 if (items
== NULL
) {
1228 result
= PyTuple_Pack(5, Py_TYPE(dd
), args
,
1229 Py_None
, Py_None
, items
);
1235 static PyMethodDef defdict_methods
[] = {
1236 {"__missing__", (PyCFunction
)defdict_missing
, METH_O
,
1237 defdict_missing_doc
},
1238 {"copy", (PyCFunction
)defdict_copy
, METH_NOARGS
,
1240 {"__copy__", (PyCFunction
)defdict_copy
, METH_NOARGS
,
1242 {"__reduce__", (PyCFunction
)defdict_reduce
, METH_NOARGS
,
1247 static PyMemberDef defdict_members
[] = {
1248 {"default_factory", T_OBJECT
,
1249 offsetof(defdictobject
, default_factory
), 0,
1250 PyDoc_STR("Factory for default value called by __missing__().")},
1255 defdict_dealloc(defdictobject
*dd
)
1257 Py_CLEAR(dd
->default_factory
);
1258 PyDict_Type
.tp_dealloc((PyObject
*)dd
);
1262 defdict_print(defdictobject
*dd
, FILE *fp
, int flags
)
1265 Py_BEGIN_ALLOW_THREADS
1266 fprintf(fp
, "defaultdict(");
1267 Py_END_ALLOW_THREADS
1268 if (dd
->default_factory
== NULL
) {
1269 Py_BEGIN_ALLOW_THREADS
1270 fprintf(fp
, "None");
1271 Py_END_ALLOW_THREADS
1273 PyObject_Print(dd
->default_factory
, fp
, 0);
1275 Py_BEGIN_ALLOW_THREADS
1277 Py_END_ALLOW_THREADS
1278 sts
= PyDict_Type
.tp_print((PyObject
*)dd
, fp
, 0);
1279 Py_BEGIN_ALLOW_THREADS
1281 Py_END_ALLOW_THREADS
1286 defdict_repr(defdictobject
*dd
)
1291 baserepr
= PyDict_Type
.tp_repr((PyObject
*)dd
);
1292 if (baserepr
== NULL
)
1294 if (dd
->default_factory
== NULL
)
1295 defrepr
= PyString_FromString("None");
1298 int status
= Py_ReprEnter(dd
->default_factory
);
1302 defrepr
= PyString_FromString("...");
1305 defrepr
= PyObject_Repr(dd
->default_factory
);
1306 Py_ReprLeave(dd
->default_factory
);
1308 if (defrepr
== NULL
) {
1309 Py_DECREF(baserepr
);
1312 result
= PyString_FromFormat("defaultdict(%s, %s)",
1313 PyString_AS_STRING(defrepr
),
1314 PyString_AS_STRING(baserepr
));
1316 Py_DECREF(baserepr
);
1321 defdict_traverse(PyObject
*self
, visitproc visit
, void *arg
)
1323 Py_VISIT(((defdictobject
*)self
)->default_factory
);
1324 return PyDict_Type
.tp_traverse(self
, visit
, arg
);
1328 defdict_tp_clear(defdictobject
*dd
)
1330 Py_CLEAR(dd
->default_factory
);
1331 return PyDict_Type
.tp_clear((PyObject
*)dd
);
1335 defdict_init(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
1337 defdictobject
*dd
= (defdictobject
*)self
;
1338 PyObject
*olddefault
= dd
->default_factory
;
1339 PyObject
*newdefault
= NULL
;
1342 if (args
== NULL
|| !PyTuple_Check(args
))
1343 newargs
= PyTuple_New(0);
1345 Py_ssize_t n
= PyTuple_GET_SIZE(args
);
1347 newdefault
= PyTuple_GET_ITEM(args
, 0);
1348 if (!PyCallable_Check(newdefault
)) {
1349 PyErr_SetString(PyExc_TypeError
,
1350 "first argument must be callable");
1354 newargs
= PySequence_GetSlice(args
, 1, n
);
1356 if (newargs
== NULL
)
1358 Py_XINCREF(newdefault
);
1359 dd
->default_factory
= newdefault
;
1360 result
= PyDict_Type
.tp_init(self
, newargs
, kwds
);
1362 Py_XDECREF(olddefault
);
1366 PyDoc_STRVAR(defdict_doc
,
1367 "defaultdict(default_factory) --> dict with default factory\n\
1369 The default factory is called without arguments to produce\n\
1370 a new value when a key is not present, in __getitem__ only.\n\
1371 A defaultdict compares equal to a dict with the same items.\n\
1374 /* See comment in xxsubtype.c */
1375 #define DEFERRED_ADDRESS(ADDR) 0
1377 static PyTypeObject defdict_type
= {
1378 PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type
), 0)
1379 "collections.defaultdict", /* tp_name */
1380 sizeof(defdictobject
), /* tp_basicsize */
1381 0, /* tp_itemsize */
1383 (destructor
)defdict_dealloc
, /* tp_dealloc */
1384 (printfunc
)defdict_print
, /* tp_print */
1388 (reprfunc
)defdict_repr
, /* tp_repr */
1389 0, /* tp_as_number */
1390 0, /* tp_as_sequence */
1391 0, /* tp_as_mapping */
1395 PyObject_GenericGetAttr
, /* tp_getattro */
1396 0, /* tp_setattro */
1397 0, /* tp_as_buffer */
1398 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
| Py_TPFLAGS_HAVE_GC
|
1399 Py_TPFLAGS_HAVE_WEAKREFS
, /* tp_flags */
1400 defdict_doc
, /* tp_doc */
1401 defdict_traverse
, /* tp_traverse */
1402 (inquiry
)defdict_tp_clear
, /* tp_clear */
1403 0, /* tp_richcompare */
1404 0, /* tp_weaklistoffset*/
1406 0, /* tp_iternext */
1407 defdict_methods
, /* tp_methods */
1408 defdict_members
, /* tp_members */
1410 DEFERRED_ADDRESS(&PyDict_Type
), /* tp_base */
1412 0, /* tp_descr_get */
1413 0, /* tp_descr_set */
1414 0, /* tp_dictoffset */
1415 defdict_init
, /* tp_init */
1416 PyType_GenericAlloc
, /* tp_alloc */
1418 PyObject_GC_Del
, /* tp_free */
1421 /* module level code ********************************************************/
1423 PyDoc_STRVAR(module_doc
,
1424 "High performance data structures.\n\
1425 - deque: ordered collection accessible from endpoints only\n\
1426 - defaultdict: dict subclass with a default value factory\n\
1430 init_collections(void)
1434 m
= Py_InitModule3("_collections", NULL
, module_doc
);
1438 if (PyType_Ready(&deque_type
) < 0)
1440 Py_INCREF(&deque_type
);
1441 PyModule_AddObject(m
, "deque", (PyObject
*)&deque_type
);
1443 defdict_type
.tp_base
= &PyDict_Type
;
1444 if (PyType_Ready(&defdict_type
) < 0)
1446 Py_INCREF(&defdict_type
);
1447 PyModule_AddObject(m
, "defaultdict", (PyObject
*)&defdict_type
);
1449 if (PyType_Ready(&dequeiter_type
) < 0)
1452 if (PyType_Ready(&dequereviter_type
) < 0)