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 /* Run an iterator to exhaustion. Shortcut for
281 the extend/extendleft methods when maxlen == 0. */
283 consume_iterator(PyObject
*it
)
287 while ((item
= PyIter_Next(it
)) != NULL
) {
291 if (PyErr_Occurred())
297 deque_extend(dequeobject
*deque
, PyObject
*iterable
)
301 it
= PyObject_GetIter(iterable
);
305 if (deque
->maxlen
== 0)
306 return consume_iterator(it
);
308 while ((item
= PyIter_Next(it
)) != NULL
) {
310 if (deque
->rightindex
== BLOCKLEN
-1) {
311 block
*b
= newblock(deque
->rightblock
, NULL
,
318 assert(deque
->rightblock
->rightlink
== NULL
);
319 deque
->rightblock
->rightlink
= b
;
320 deque
->rightblock
= b
;
321 deque
->rightindex
= -1;
325 deque
->rightblock
->data
[deque
->rightindex
] = item
;
326 TRIM(deque
, deque_popleft
);
329 if (PyErr_Occurred())
334 PyDoc_STRVAR(extend_doc
,
335 "Extend the right side of the deque with elements from the iterable");
338 deque_extendleft(dequeobject
*deque
, PyObject
*iterable
)
342 it
= PyObject_GetIter(iterable
);
346 if (deque
->maxlen
== 0)
347 return consume_iterator(it
);
349 while ((item
= PyIter_Next(it
)) != NULL
) {
351 if (deque
->leftindex
== 0) {
352 block
*b
= newblock(NULL
, deque
->leftblock
,
359 assert(deque
->leftblock
->leftlink
== NULL
);
360 deque
->leftblock
->leftlink
= b
;
361 deque
->leftblock
= b
;
362 deque
->leftindex
= BLOCKLEN
;
366 deque
->leftblock
->data
[deque
->leftindex
] = item
;
367 TRIM(deque
, deque_pop
);
370 if (PyErr_Occurred())
375 PyDoc_STRVAR(extendleft_doc
,
376 "Extend the left side of the deque with elements from the iterable");
379 _deque_rotate(dequeobject
*deque
, Py_ssize_t n
)
381 Py_ssize_t i
, len
=deque
->len
, halflen
=(len
+1)>>1;
386 if (n
> halflen
|| n
< -halflen
) {
390 else if (n
< -halflen
)
394 for (i
=0 ; i
<n
; i
++) {
395 item
= deque_pop(deque
, NULL
);
396 assert (item
!= NULL
);
397 rv
= deque_appendleft(deque
, item
);
403 for (i
=0 ; i
>n
; i
--) {
404 item
= deque_popleft(deque
, NULL
);
405 assert (item
!= NULL
);
406 rv
= deque_append(deque
, item
);
416 deque_rotate(dequeobject
*deque
, PyObject
*args
)
420 if (!PyArg_ParseTuple(args
, "|n:rotate", &n
))
422 if (_deque_rotate(deque
, n
) == 0)
427 PyDoc_STRVAR(rotate_doc
,
428 "Rotate the deque n steps to the right (default n=1). If n is negative, rotates left.");
431 deque_len(dequeobject
*deque
)
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().");
451 PyObject
*tgt
= deque_popleft(deque
, NULL
);
452 assert (tgt
!= NULL
);
454 if (_deque_rotate(deque
, i
) == -1)
459 _deque_rotate(deque
, i
);
462 _deque_rotate(deque
, -1);
464 PyErr_SetString(PyExc_ValueError
, "deque.remove(x): x not in deque");
468 PyDoc_STRVAR(remove_doc
,
469 "D.remove(value) -- remove first occurrence of value.");
472 deque_clear(dequeobject
*deque
)
477 item
= deque_pop(deque
, NULL
);
478 assert (item
!= NULL
);
481 assert(deque
->leftblock
== deque
->rightblock
&&
482 deque
->leftindex
- 1 == deque
->rightindex
&&
488 deque_item(dequeobject
*deque
, Py_ssize_t i
)
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");
501 i
= deque
->leftindex
;
502 b
= deque
->leftblock
;
503 } else if (i
== deque
->len
- 1) {
504 i
= deque
->rightindex
;
505 b
= deque
->rightblock
;
507 i
+= deque
->leftindex
;
510 if (index
< (deque
->len
>> 1)) {
511 b
= deque
->leftblock
;
515 n
= (deque
->leftindex
+ deque
->len
- 1) / BLOCKLEN
- n
;
516 b
= deque
->rightblock
;
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
534 deque_del_item(dequeobject
*deque
, Py_ssize_t i
)
538 assert (i
>= 0 && i
< deque
->len
);
539 if (_deque_rotate(deque
, -i
) == -1)
542 item
= deque_popleft(deque
, NULL
);
543 assert (item
!= NULL
);
546 return _deque_rotate(deque
, i
);
550 deque_ass_item(dequeobject
*deque
, Py_ssize_t i
, PyObject
*v
)
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");
562 return deque_del_item(deque
, i
);
564 i
+= deque
->leftindex
;
567 if (index
<= halflen
) {
568 b
= deque
->leftblock
;
572 n
= (deque
->leftindex
+ len
- 1) / BLOCKLEN
- n
;
573 b
= deque
->rightblock
;
578 old_value
= b
->data
[i
];
580 Py_DECREF(old_value
);
585 deque_clearmethod(dequeobject
*deque
)
589 rv
= deque_clear(deque
);
594 PyDoc_STRVAR(clear_doc
, "Remove all elements from the deque.");
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
) {
604 assert(deque
->leftblock
!= NULL
);
605 freeblock(deque
->leftblock
);
607 deque
->leftblock
= NULL
;
608 deque
->rightblock
= NULL
;
609 Py_TYPE(deque
)->tp_free(deque
);
613 deque_traverse(dequeobject
*deque
, visitproc visit
, void *arg
)
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
?
625 for (index
= indexlo
; index
<= indexhi
; ++index
) {
626 item
= b
->data
[index
];
635 deque_copy(PyObject
*deque
)
637 if (((dequeobject
*)deque
)->maxlen
== -1)
638 return PyObject_CallFunction((PyObject
*)(Py_TYPE(deque
)), "O", deque
, NULL
);
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.");
647 deque_reduce(dequeobject
*deque
)
649 PyObject
*dict
, *result
, *aslist
;
651 dict
= PyObject_GetAttrString((PyObject
*)deque
, "__dict__");
654 aslist
= PySequence_List((PyObject
*)deque
);
655 if (aslist
== NULL
) {
660 if (deque
->maxlen
== -1)
661 result
= Py_BuildValue("O(O)", Py_TYPE(deque
), aslist
);
663 result
= Py_BuildValue("O(On)", Py_TYPE(deque
), aslist
, deque
->maxlen
);
665 if (deque
->maxlen
== -1)
666 result
= Py_BuildValue("O(OO)O", Py_TYPE(deque
), aslist
, Py_None
, dict
);
668 result
= Py_BuildValue("O(On)O", Py_TYPE(deque
), aslist
, deque
->maxlen
, dict
);
675 PyDoc_STRVAR(reduce_doc
, "Return state information for pickling.");
678 deque_repr(PyObject
*deque
)
680 PyObject
*aslist
, *result
;
683 i
= Py_ReprEnter(deque
);
687 return PyUnicode_FromString("[...]");
690 aslist
= PySequence_List(deque
);
691 if (aslist
== NULL
) {
695 if (((dequeobject
*)deque
)->maxlen
!= -1)
697 result
= PyUnicode_FromFormat("deque(%R, maxlen=%zd)",
698 aslist
, ((dequeobject
*)deque
)->maxlen
);
700 result
= PyUnicode_FromFormat("deque(%R)", aslist
);
707 deque_richcompare(PyObject
*v
, PyObject
*w
, int op
)
709 PyObject
*it1
=NULL
, *it2
=NULL
, *x
, *y
;
713 if (!PyObject_TypeCheck(v
, &deque_type
) ||
714 !PyObject_TypeCheck(w
, &deque_type
)) {
715 Py_INCREF(Py_NotImplemented
);
716 return Py_NotImplemented
;
720 vs
= ((dequeobject
*)v
)->len
;
721 ws
= ((dequeobject
*)w
)->len
;
735 /* Search for the first index where items are different */
736 it1
= PyObject_GetIter(v
);
739 it2
= PyObject_GetIter(w
);
743 x
= PyIter_Next(it1
);
744 if (x
== NULL
&& PyErr_Occurred())
746 y
= PyIter_Next(it2
);
747 if (x
== NULL
|| y
== NULL
)
749 b
= PyObject_RichCompareBool(x
, y
, Py_EQ
);
751 cmp
= PyObject_RichCompareBool(x
, y
, op
);
761 /* We reached the end of one deque or both */
764 if (PyErr_Occurred())
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 */
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
))
795 if (maxlenobj
!= NULL
&& maxlenobj
!= Py_None
) {
796 maxlen
= PyLong_AsSsize_t(maxlenobj
);
797 if (maxlen
== -1 && PyErr_Occurred())
800 PyErr_SetString(PyExc_ValueError
, "maxlen must be non-negative");
804 deque
->maxlen
= maxlen
;
806 if (iterable
!= NULL
) {
807 PyObject
*rv
= deque_extend(deque
, iterable
);
816 deque_get_maxlen(dequeobject
*deque
)
818 if (deque
->maxlen
== -1)
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 */
833 (ssizeargfunc
)deque_item
, /* sq_item */
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
,
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
,
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
,
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 */
884 (destructor
)deque_dealloc
, /* tp_dealloc */
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 */
896 PyObject_GenericGetAttr
, /* tp_getattro */
898 0, /* tp_as_buffer */
899 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
| Py_TPFLAGS_HAVE_GC
,
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 */
908 deque_methods
, /* tp_methods */
910 deque_getset
, /* tp_getset */
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 **************************/
929 long state
; /* state when the iterator is created */
930 Py_ssize_t counter
; /* number of items remaining for iteration */
933 static PyTypeObject dequeiter_type
;
936 deque_iter(dequeobject
*deque
)
940 it
= PyObject_GC_New(dequeiterobject
, &dequeiter_type
);
943 it
->b
= deque
->leftblock
;
944 it
->index
= deque
->leftindex
;
947 it
->state
= deque
->state
;
948 it
->counter
= deque
->len
;
949 PyObject_GC_Track(it
);
950 return (PyObject
*)it
;
954 dequeiter_traverse(dequeiterobject
*dio
, visitproc visit
, void *arg
)
956 Py_VISIT(dio
->deque
);
961 dequeiter_dealloc(dequeiterobject
*dio
)
963 Py_XDECREF(dio
->deque
);
964 PyObject_GC_Del(dio
);
968 dequeiter_next(dequeiterobject
*it
)
972 if (it
->deque
->state
!= it
->state
) {
974 PyErr_SetString(PyExc_RuntimeError
,
975 "deque mutated during iteration");
978 if (it
->counter
== 0)
980 assert (!(it
->b
== it
->deque
->rightblock
&&
981 it
->index
> it
->deque
->rightindex
));
983 item
= it
->b
->data
[it
->index
];
986 if (it
->index
== BLOCKLEN
&& it
->counter
> 0) {
987 assert (it
->b
->rightlink
!= NULL
);
988 it
->b
= it
->b
->rightlink
;
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 */
1014 (destructor
)dequeiter_dealloc
, /* tp_dealloc */
1018 0, /* tp_reserved */
1020 0, /* tp_as_number */
1021 0, /* tp_as_sequence */
1022 0, /* tp_as_mapping */
1026 PyObject_GenericGetAttr
, /* tp_getattro */
1027 0, /* tp_setattro */
1028 0, /* tp_as_buffer */
1029 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_HAVE_GC
,/* tp_flags */
1031 (traverseproc
)dequeiter_traverse
, /* tp_traverse */
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
;
1046 deque_reviter(dequeobject
*deque
)
1048 dequeiterobject
*it
;
1050 it
= PyObject_GC_New(dequeiterobject
, &dequereviter_type
);
1053 it
->b
= deque
->rightblock
;
1054 it
->index
= deque
->rightindex
;
1057 it
->state
= deque
->state
;
1058 it
->counter
= deque
->len
;
1059 PyObject_GC_Track(it
);
1060 return (PyObject
*)it
;
1064 dequereviter_next(dequeiterobject
*it
)
1067 if (it
->counter
== 0)
1070 if (it
->deque
->state
!= it
->state
) {
1072 PyErr_SetString(PyExc_RuntimeError
,
1073 "deque mutated during iteration");
1076 assert (!(it
->b
== it
->deque
->leftblock
&&
1077 it
->index
< it
->deque
->leftindex
));
1079 item
= it
->b
->data
[it
->index
];
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;
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 */
1097 (destructor
)dequeiter_dealloc
, /* tp_dealloc */
1101 0, /* tp_reserved */
1103 0, /* tp_as_number */
1104 0, /* tp_as_sequence */
1105 0, /* tp_as_mapping */
1109 PyObject_GenericGetAttr
, /* tp_getattro */
1110 0, /* tp_setattro */
1111 0, /* tp_as_buffer */
1112 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_HAVE_GC
,/* tp_flags */
1114 (traverseproc
)dequeiter_traverse
, /* tp_traverse */
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 *********************************************************/
1128 PyObject
*default_factory
;
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\
1141 defdict_missing(defdictobject
*dd
, PyObject
*key
)
1143 PyObject
*factory
= dd
->default_factory
;
1145 if (factory
== NULL
|| factory
== Py_None
) {
1146 /* XXX Call dict.__missing__(key) */
1148 tup
= PyTuple_Pack(1, key
);
1149 if (!tup
) return NULL
;
1150 PyErr_SetObject(PyExc_KeyError
, tup
);
1154 value
= PyEval_CallObject(factory
, NULL
);
1157 if (PyObject_SetItem((PyObject
*)dd
, key
, value
) < 0) {
1164 PyDoc_STRVAR(defdict_copy_doc
, "D.copy() -> a shallow copy of D.");
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
);
1178 defdict_reduce(defdictobject
*dd
)
1180 /* __reduce__ must return a 5-tuple as follows:
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.
1206 if (dd
->default_factory
== NULL
|| dd
->default_factory
== Py_None
)
1207 args
= PyTuple_New(0);
1209 args
= PyTuple_Pack(1, dd
->default_factory
);
1212 items
= PyObject_CallMethod((PyObject
*)dd
, "items", "()");
1213 if (items
== NULL
) {
1217 iter
= PyObject_GetIter(items
);
1223 result
= PyTuple_Pack(5, Py_TYPE(dd
), args
,
1224 Py_None
, Py_None
, iter
);
1231 static PyMethodDef defdict_methods
[] = {
1232 {"__missing__", (PyCFunction
)defdict_missing
, METH_O
,
1233 defdict_missing_doc
},
1234 {"copy", (PyCFunction
)defdict_copy
, METH_NOARGS
,
1236 {"__copy__", (PyCFunction
)defdict_copy
, METH_NOARGS
,
1238 {"__reduce__", (PyCFunction
)defdict_reduce
, METH_NOARGS
,
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__().")},
1251 defdict_dealloc(defdictobject
*dd
)
1253 Py_CLEAR(dd
->default_factory
);
1254 PyDict_Type
.tp_dealloc((PyObject
*)dd
);
1258 defdict_repr(defdictobject
*dd
)
1263 baserepr
= PyDict_Type
.tp_repr((PyObject
*)dd
);
1264 if (baserepr
== NULL
)
1266 if (dd
->default_factory
== NULL
)
1267 defrepr
= PyUnicode_FromString("None");
1270 int status
= Py_ReprEnter(dd
->default_factory
);
1274 defrepr
= PyUnicode_FromString("...");
1277 defrepr
= PyObject_Repr(dd
->default_factory
);
1278 Py_ReprLeave(dd
->default_factory
);
1280 if (defrepr
== NULL
) {
1281 Py_DECREF(baserepr
);
1284 result
= PyUnicode_FromFormat("defaultdict(%U, %U)",
1287 Py_DECREF(baserepr
);
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
);
1299 defdict_tp_clear(defdictobject
*dd
)
1301 Py_CLEAR(dd
->default_factory
);
1302 return PyDict_Type
.tp_clear((PyObject
*)dd
);
1306 defdict_init(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
1308 defdictobject
*dd
= (defdictobject
*)self
;
1309 PyObject
*olddefault
= dd
->default_factory
;
1310 PyObject
*newdefault
= NULL
;
1313 if (args
== NULL
|| !PyTuple_Check(args
))
1314 newargs
= PyTuple_New(0);
1316 Py_ssize_t n
= PyTuple_GET_SIZE(args
);
1318 newdefault
= PyTuple_GET_ITEM(args
, 0);
1319 if (!PyCallable_Check(newdefault
)) {
1320 PyErr_SetString(PyExc_TypeError
,
1321 "first argument must be callable");
1325 newargs
= PySequence_GetSlice(args
, 1, n
);
1327 if (newargs
== NULL
)
1329 Py_XINCREF(newdefault
);
1330 dd
->default_factory
= newdefault
;
1331 result
= PyDict_Type
.tp_init(self
, newargs
, kwds
);
1333 Py_XDECREF(olddefault
);
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 */
1354 (destructor
)defdict_dealloc
, /* tp_dealloc */
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 */
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
,
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*/
1377 0, /* tp_iternext */
1378 defdict_methods
, /* tp_methods */
1379 defdict_members
, /* tp_members */
1381 DEFERRED_ADDRESS(&PyDict_Type
), /* tp_base */
1383 0, /* tp_descr_get */
1384 0, /* tp_descr_set */
1385 0, /* tp_dictoffset */
1386 defdict_init
, /* tp_init */
1387 PyType_GenericAlloc
, /* tp_alloc */
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
,
1414 PyInit__collections(void)
1418 m
= PyModule_Create(&_collectionsmodule
);
1422 if (PyType_Ready(&deque_type
) < 0)
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)
1430 Py_INCREF(&defdict_type
);
1431 PyModule_AddObject(m
, "defaultdict", (PyObject
*)&defdict_type
);
1433 if (PyType_Ready(&dequeiter_type
) < 0)
1436 if (PyType_Ready(&dequereviter_type
) < 0)