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
, *fmt
;
683 i
= Py_ReprEnter(deque
);
687 return PyString_FromString("[...]");
690 aslist
= PySequence_List(deque
);
691 if (aslist
== NULL
) {
695 if (((dequeobject
*)deque
)->maxlen
!= -1)
696 fmt
= PyString_FromFormat("deque(%%r, maxlen=%zd)",
697 ((dequeobject
*)deque
)->maxlen
);
699 fmt
= PyString_FromString("deque(%r)");
705 result
= PyString_Format(fmt
, aslist
);
713 deque_tp_print(PyObject
*deque
, FILE *fp
, int flags
)
716 char *emit
= ""; /* No separator emitted on first pass */
717 char *separator
= ", ";
720 i
= Py_ReprEnter(deque
);
724 Py_BEGIN_ALLOW_THREADS
730 it
= PyObject_GetIter(deque
);
734 Py_BEGIN_ALLOW_THREADS
735 fputs("deque([", fp
);
737 while ((item
= PyIter_Next(it
)) != NULL
) {
738 Py_BEGIN_ALLOW_THREADS
742 if (PyObject_Print(item
, fp
, 0) != 0) {
752 if (PyErr_Occurred())
755 Py_BEGIN_ALLOW_THREADS
756 if (((dequeobject
*)deque
)->maxlen
== -1)
759 fprintf(fp
, "], maxlen=%" PY_FORMAT_SIZE_T
"d)", ((dequeobject
*)deque
)->maxlen
);
765 deque_richcompare(PyObject
*v
, PyObject
*w
, int op
)
767 PyObject
*it1
=NULL
, *it2
=NULL
, *x
, *y
;
771 if (!PyObject_TypeCheck(v
, &deque_type
) ||
772 !PyObject_TypeCheck(w
, &deque_type
)) {
773 Py_INCREF(Py_NotImplemented
);
774 return Py_NotImplemented
;
778 vs
= ((dequeobject
*)v
)->len
;
779 ws
= ((dequeobject
*)w
)->len
;
793 /* Search for the first index where items are different */
794 it1
= PyObject_GetIter(v
);
797 it2
= PyObject_GetIter(w
);
801 x
= PyIter_Next(it1
);
802 if (x
== NULL
&& PyErr_Occurred())
804 y
= PyIter_Next(it2
);
805 if (x
== NULL
|| y
== NULL
)
807 b
= PyObject_RichCompareBool(x
, y
, Py_EQ
);
809 cmp
= PyObject_RichCompareBool(x
, y
, op
);
819 /* We reached the end of one deque or both */
822 if (PyErr_Occurred())
825 case Py_LT
: cmp
= y
!= NULL
; break; /* if w was longer */
826 case Py_LE
: cmp
= x
== NULL
; break; /* if v was not longer */
827 case Py_EQ
: cmp
= x
== y
; break; /* if we reached the end of both */
828 case Py_NE
: cmp
= x
!= y
; break; /* if one deque continues */
829 case Py_GT
: cmp
= x
!= NULL
; break; /* if v was longer */
830 case Py_GE
: cmp
= y
== NULL
; break; /* if w was not longer */
844 deque_init(dequeobject
*deque
, PyObject
*args
, PyObject
*kwdargs
)
846 PyObject
*iterable
= NULL
;
847 PyObject
*maxlenobj
= NULL
;
848 Py_ssize_t maxlen
= -1;
849 char *kwlist
[] = {"iterable", "maxlen", 0};
851 if (!PyArg_ParseTupleAndKeywords(args
, kwdargs
, "|OO:deque", kwlist
, &iterable
, &maxlenobj
))
853 if (maxlenobj
!= NULL
&& maxlenobj
!= Py_None
) {
854 maxlen
= PyInt_AsSsize_t(maxlenobj
);
855 if (maxlen
== -1 && PyErr_Occurred())
858 PyErr_SetString(PyExc_ValueError
, "maxlen must be non-negative");
862 deque
->maxlen
= maxlen
;
864 if (iterable
!= NULL
) {
865 PyObject
*rv
= deque_extend(deque
, iterable
);
874 deque_get_maxlen(dequeobject
*deque
)
876 if (deque
->maxlen
== -1)
878 return PyInt_FromSsize_t(deque
->maxlen
);
881 static PyGetSetDef deque_getset
[] = {
882 {"maxlen", (getter
)deque_get_maxlen
, (setter
)NULL
,
883 "maximum size of a deque or None if unbounded"},
887 static PySequenceMethods deque_as_sequence
= {
888 (lenfunc
)deque_len
, /* sq_length */
891 (ssizeargfunc
)deque_item
, /* sq_item */
893 (ssizeobjargproc
)deque_ass_item
, /* sq_ass_item */
896 /* deque object ********************************************************/
898 static PyObject
*deque_iter(dequeobject
*deque
);
899 static PyObject
*deque_reviter(dequeobject
*deque
);
900 PyDoc_STRVAR(reversed_doc
,
901 "D.__reversed__() -- return a reverse iterator over the deque");
903 static PyMethodDef deque_methods
[] = {
904 {"append", (PyCFunction
)deque_append
,
906 {"appendleft", (PyCFunction
)deque_appendleft
,
907 METH_O
, appendleft_doc
},
908 {"clear", (PyCFunction
)deque_clearmethod
,
909 METH_NOARGS
, clear_doc
},
910 {"__copy__", (PyCFunction
)deque_copy
,
911 METH_NOARGS
, copy_doc
},
912 {"extend", (PyCFunction
)deque_extend
,
914 {"extendleft", (PyCFunction
)deque_extendleft
,
915 METH_O
, extendleft_doc
},
916 {"pop", (PyCFunction
)deque_pop
,
917 METH_NOARGS
, pop_doc
},
918 {"popleft", (PyCFunction
)deque_popleft
,
919 METH_NOARGS
, popleft_doc
},
920 {"__reduce__", (PyCFunction
)deque_reduce
,
921 METH_NOARGS
, reduce_doc
},
922 {"remove", (PyCFunction
)deque_remove
,
924 {"__reversed__", (PyCFunction
)deque_reviter
,
925 METH_NOARGS
, reversed_doc
},
926 {"rotate", (PyCFunction
)deque_rotate
,
927 METH_VARARGS
, rotate_doc
},
928 {NULL
, NULL
} /* sentinel */
931 PyDoc_STRVAR(deque_doc
,
932 "deque(iterable[, maxlen]) --> deque object\n\
934 Build an ordered collection accessible from endpoints only.");
936 static PyTypeObject deque_type
= {
937 PyVarObject_HEAD_INIT(NULL
, 0)
938 "collections.deque", /* tp_name */
939 sizeof(dequeobject
), /* tp_basicsize */
942 (destructor
)deque_dealloc
, /* tp_dealloc */
943 deque_tp_print
, /* tp_print */
947 deque_repr
, /* tp_repr */
948 0, /* tp_as_number */
949 &deque_as_sequence
, /* tp_as_sequence */
950 0, /* tp_as_mapping */
951 (hashfunc
)PyObject_HashNotImplemented
, /* tp_hash */
954 PyObject_GenericGetAttr
, /* tp_getattro */
956 0, /* tp_as_buffer */
957 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
| Py_TPFLAGS_HAVE_GC
|
958 Py_TPFLAGS_HAVE_WEAKREFS
, /* tp_flags */
959 deque_doc
, /* tp_doc */
960 (traverseproc
)deque_traverse
, /* tp_traverse */
961 (inquiry
)deque_clear
, /* tp_clear */
962 (richcmpfunc
)deque_richcompare
, /* tp_richcompare */
963 offsetof(dequeobject
, weakreflist
), /* tp_weaklistoffset*/
964 (getiterfunc
)deque_iter
, /* tp_iter */
966 deque_methods
, /* tp_methods */
968 deque_getset
, /* tp_getset */
971 0, /* tp_descr_get */
972 0, /* tp_descr_set */
973 0, /* tp_dictoffset */
974 (initproc
)deque_init
, /* tp_init */
975 PyType_GenericAlloc
, /* tp_alloc */
976 deque_new
, /* tp_new */
977 PyObject_GC_Del
, /* tp_free */
980 /*********************** Deque Iterator **************************/
987 long state
; /* state when the iterator is created */
988 Py_ssize_t counter
; /* number of items remaining for iteration */
991 static PyTypeObject dequeiter_type
;
994 deque_iter(dequeobject
*deque
)
998 it
= PyObject_GC_New(dequeiterobject
, &dequeiter_type
);
1001 it
->b
= deque
->leftblock
;
1002 it
->index
= deque
->leftindex
;
1005 it
->state
= deque
->state
;
1006 it
->counter
= deque
->len
;
1007 PyObject_GC_Track(it
);
1008 return (PyObject
*)it
;
1012 dequeiter_traverse(dequeiterobject
*dio
, visitproc visit
, void *arg
)
1014 Py_VISIT(dio
->deque
);
1019 dequeiter_dealloc(dequeiterobject
*dio
)
1021 Py_XDECREF(dio
->deque
);
1022 PyObject_GC_Del(dio
);
1026 dequeiter_next(dequeiterobject
*it
)
1030 if (it
->deque
->state
!= it
->state
) {
1032 PyErr_SetString(PyExc_RuntimeError
,
1033 "deque mutated during iteration");
1036 if (it
->counter
== 0)
1038 assert (!(it
->b
== it
->deque
->rightblock
&&
1039 it
->index
> it
->deque
->rightindex
));
1041 item
= it
->b
->data
[it
->index
];
1044 if (it
->index
== BLOCKLEN
&& it
->counter
> 0) {
1045 assert (it
->b
->rightlink
!= NULL
);
1046 it
->b
= it
->b
->rightlink
;
1054 dequeiter_len(dequeiterobject
*it
)
1056 return PyInt_FromLong(it
->counter
);
1059 PyDoc_STRVAR(length_hint_doc
, "Private method returning an estimate of len(list(it)).");
1061 static PyMethodDef dequeiter_methods
[] = {
1062 {"__length_hint__", (PyCFunction
)dequeiter_len
, METH_NOARGS
, length_hint_doc
},
1063 {NULL
, NULL
} /* sentinel */
1066 static PyTypeObject dequeiter_type
= {
1067 PyVarObject_HEAD_INIT(NULL
, 0)
1068 "deque_iterator", /* tp_name */
1069 sizeof(dequeiterobject
), /* tp_basicsize */
1070 0, /* tp_itemsize */
1072 (destructor
)dequeiter_dealloc
, /* tp_dealloc */
1078 0, /* tp_as_number */
1079 0, /* tp_as_sequence */
1080 0, /* tp_as_mapping */
1084 PyObject_GenericGetAttr
, /* tp_getattro */
1085 0, /* tp_setattro */
1086 0, /* tp_as_buffer */
1087 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_HAVE_GC
,/* tp_flags */
1089 (traverseproc
)dequeiter_traverse
, /* tp_traverse */
1091 0, /* tp_richcompare */
1092 0, /* tp_weaklistoffset */
1093 PyObject_SelfIter
, /* tp_iter */
1094 (iternextfunc
)dequeiter_next
, /* tp_iternext */
1095 dequeiter_methods
, /* tp_methods */
1099 /*********************** Deque Reverse Iterator **************************/
1101 static PyTypeObject dequereviter_type
;
1104 deque_reviter(dequeobject
*deque
)
1106 dequeiterobject
*it
;
1108 it
= PyObject_GC_New(dequeiterobject
, &dequereviter_type
);
1111 it
->b
= deque
->rightblock
;
1112 it
->index
= deque
->rightindex
;
1115 it
->state
= deque
->state
;
1116 it
->counter
= deque
->len
;
1117 PyObject_GC_Track(it
);
1118 return (PyObject
*)it
;
1122 dequereviter_next(dequeiterobject
*it
)
1125 if (it
->counter
== 0)
1128 if (it
->deque
->state
!= it
->state
) {
1130 PyErr_SetString(PyExc_RuntimeError
,
1131 "deque mutated during iteration");
1134 assert (!(it
->b
== it
->deque
->leftblock
&&
1135 it
->index
< it
->deque
->leftindex
));
1137 item
= it
->b
->data
[it
->index
];
1140 if (it
->index
== -1 && it
->counter
> 0) {
1141 assert (it
->b
->leftlink
!= NULL
);
1142 it
->b
= it
->b
->leftlink
;
1143 it
->index
= BLOCKLEN
- 1;
1149 static PyTypeObject dequereviter_type
= {
1150 PyVarObject_HEAD_INIT(NULL
, 0)
1151 "deque_reverse_iterator", /* tp_name */
1152 sizeof(dequeiterobject
), /* tp_basicsize */
1153 0, /* tp_itemsize */
1155 (destructor
)dequeiter_dealloc
, /* tp_dealloc */
1161 0, /* tp_as_number */
1162 0, /* tp_as_sequence */
1163 0, /* tp_as_mapping */
1167 PyObject_GenericGetAttr
, /* tp_getattro */
1168 0, /* tp_setattro */
1169 0, /* tp_as_buffer */
1170 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_HAVE_GC
,/* tp_flags */
1172 (traverseproc
)dequeiter_traverse
, /* tp_traverse */
1174 0, /* tp_richcompare */
1175 0, /* tp_weaklistoffset */
1176 PyObject_SelfIter
, /* tp_iter */
1177 (iternextfunc
)dequereviter_next
, /* tp_iternext */
1178 dequeiter_methods
, /* tp_methods */
1182 /* defaultdict type *********************************************************/
1186 PyObject
*default_factory
;
1189 static PyTypeObject defdict_type
; /* Forward */
1191 PyDoc_STRVAR(defdict_missing_doc
,
1192 "__missing__(key) # Called by __getitem__ for missing key; pseudo-code:\n\
1193 if self.default_factory is None: raise KeyError((key,))\n\
1194 self[key] = value = self.default_factory()\n\
1199 defdict_missing(defdictobject
*dd
, PyObject
*key
)
1201 PyObject
*factory
= dd
->default_factory
;
1203 if (factory
== NULL
|| factory
== Py_None
) {
1204 /* XXX Call dict.__missing__(key) */
1206 tup
= PyTuple_Pack(1, key
);
1207 if (!tup
) return NULL
;
1208 PyErr_SetObject(PyExc_KeyError
, tup
);
1212 value
= PyEval_CallObject(factory
, NULL
);
1215 if (PyObject_SetItem((PyObject
*)dd
, key
, value
) < 0) {
1222 PyDoc_STRVAR(defdict_copy_doc
, "D.copy() -> a shallow copy of D.");
1225 defdict_copy(defdictobject
*dd
)
1227 /* This calls the object's class. That only works for subclasses
1228 whose class constructor has the same signature. Subclasses that
1229 define a different constructor signature must override copy().
1232 if (dd
->default_factory
== NULL
)
1233 return PyObject_CallFunctionObjArgs((PyObject
*)Py_TYPE(dd
), Py_None
, dd
, NULL
);
1234 return PyObject_CallFunctionObjArgs((PyObject
*)Py_TYPE(dd
),
1235 dd
->default_factory
, dd
, NULL
);
1239 defdict_reduce(defdictobject
*dd
)
1241 /* __reduce__ must return a 5-tuple as follows:
1244 - tuple of args for the factory function
1245 - additional state (here None)
1246 - sequence iterator (here None)
1247 - dictionary iterator (yielding successive (key, value) pairs
1249 This API is used by pickle.py and copy.py.
1251 For this to be useful with pickle.py, the default_factory
1252 must be picklable; e.g., None, a built-in, or a global
1253 function in a module or package.
1255 Both shallow and deep copying are supported, but for deep
1256 copying, the default_factory must be deep-copyable; e.g. None,
1257 or a built-in (functions are not copyable at this time).
1259 This only works for subclasses as long as their constructor
1260 signature is compatible; the first argument must be the
1261 optional default_factory, defaulting to None.
1266 if (dd
->default_factory
== NULL
|| dd
->default_factory
== Py_None
)
1267 args
= PyTuple_New(0);
1269 args
= PyTuple_Pack(1, dd
->default_factory
);
1272 items
= PyObject_CallMethod((PyObject
*)dd
, "iteritems", "()");
1273 if (items
== NULL
) {
1277 result
= PyTuple_Pack(5, Py_TYPE(dd
), args
,
1278 Py_None
, Py_None
, items
);
1284 static PyMethodDef defdict_methods
[] = {
1285 {"__missing__", (PyCFunction
)defdict_missing
, METH_O
,
1286 defdict_missing_doc
},
1287 {"copy", (PyCFunction
)defdict_copy
, METH_NOARGS
,
1289 {"__copy__", (PyCFunction
)defdict_copy
, METH_NOARGS
,
1291 {"__reduce__", (PyCFunction
)defdict_reduce
, METH_NOARGS
,
1296 static PyMemberDef defdict_members
[] = {
1297 {"default_factory", T_OBJECT
,
1298 offsetof(defdictobject
, default_factory
), 0,
1299 PyDoc_STR("Factory for default value called by __missing__().")},
1304 defdict_dealloc(defdictobject
*dd
)
1306 Py_CLEAR(dd
->default_factory
);
1307 PyDict_Type
.tp_dealloc((PyObject
*)dd
);
1311 defdict_print(defdictobject
*dd
, FILE *fp
, int flags
)
1314 Py_BEGIN_ALLOW_THREADS
1315 fprintf(fp
, "defaultdict(");
1316 Py_END_ALLOW_THREADS
1317 if (dd
->default_factory
== NULL
) {
1318 Py_BEGIN_ALLOW_THREADS
1319 fprintf(fp
, "None");
1320 Py_END_ALLOW_THREADS
1322 PyObject_Print(dd
->default_factory
, fp
, 0);
1324 Py_BEGIN_ALLOW_THREADS
1326 Py_END_ALLOW_THREADS
1327 sts
= PyDict_Type
.tp_print((PyObject
*)dd
, fp
, 0);
1328 Py_BEGIN_ALLOW_THREADS
1330 Py_END_ALLOW_THREADS
1335 defdict_repr(defdictobject
*dd
)
1340 baserepr
= PyDict_Type
.tp_repr((PyObject
*)dd
);
1341 if (baserepr
== NULL
)
1343 if (dd
->default_factory
== NULL
)
1344 defrepr
= PyString_FromString("None");
1347 int status
= Py_ReprEnter(dd
->default_factory
);
1351 defrepr
= PyString_FromString("...");
1354 defrepr
= PyObject_Repr(dd
->default_factory
);
1355 Py_ReprLeave(dd
->default_factory
);
1357 if (defrepr
== NULL
) {
1358 Py_DECREF(baserepr
);
1361 result
= PyString_FromFormat("defaultdict(%s, %s)",
1362 PyString_AS_STRING(defrepr
),
1363 PyString_AS_STRING(baserepr
));
1365 Py_DECREF(baserepr
);
1370 defdict_traverse(PyObject
*self
, visitproc visit
, void *arg
)
1372 Py_VISIT(((defdictobject
*)self
)->default_factory
);
1373 return PyDict_Type
.tp_traverse(self
, visit
, arg
);
1377 defdict_tp_clear(defdictobject
*dd
)
1379 Py_CLEAR(dd
->default_factory
);
1380 return PyDict_Type
.tp_clear((PyObject
*)dd
);
1384 defdict_init(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
1386 defdictobject
*dd
= (defdictobject
*)self
;
1387 PyObject
*olddefault
= dd
->default_factory
;
1388 PyObject
*newdefault
= NULL
;
1391 if (args
== NULL
|| !PyTuple_Check(args
))
1392 newargs
= PyTuple_New(0);
1394 Py_ssize_t n
= PyTuple_GET_SIZE(args
);
1396 newdefault
= PyTuple_GET_ITEM(args
, 0);
1397 if (!PyCallable_Check(newdefault
) && newdefault
!= Py_None
) {
1398 PyErr_SetString(PyExc_TypeError
,
1399 "first argument must be callable");
1403 newargs
= PySequence_GetSlice(args
, 1, n
);
1405 if (newargs
== NULL
)
1407 Py_XINCREF(newdefault
);
1408 dd
->default_factory
= newdefault
;
1409 result
= PyDict_Type
.tp_init(self
, newargs
, kwds
);
1411 Py_XDECREF(olddefault
);
1415 PyDoc_STRVAR(defdict_doc
,
1416 "defaultdict(default_factory) --> dict with default factory\n\
1418 The default factory is called without arguments to produce\n\
1419 a new value when a key is not present, in __getitem__ only.\n\
1420 A defaultdict compares equal to a dict with the same items.\n\
1423 /* See comment in xxsubtype.c */
1424 #define DEFERRED_ADDRESS(ADDR) 0
1426 static PyTypeObject defdict_type
= {
1427 PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type
), 0)
1428 "collections.defaultdict", /* tp_name */
1429 sizeof(defdictobject
), /* tp_basicsize */
1430 0, /* tp_itemsize */
1432 (destructor
)defdict_dealloc
, /* tp_dealloc */
1433 (printfunc
)defdict_print
, /* tp_print */
1437 (reprfunc
)defdict_repr
, /* tp_repr */
1438 0, /* tp_as_number */
1439 0, /* tp_as_sequence */
1440 0, /* tp_as_mapping */
1444 PyObject_GenericGetAttr
, /* tp_getattro */
1445 0, /* tp_setattro */
1446 0, /* tp_as_buffer */
1447 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
| Py_TPFLAGS_HAVE_GC
|
1448 Py_TPFLAGS_HAVE_WEAKREFS
, /* tp_flags */
1449 defdict_doc
, /* tp_doc */
1450 defdict_traverse
, /* tp_traverse */
1451 (inquiry
)defdict_tp_clear
, /* tp_clear */
1452 0, /* tp_richcompare */
1453 0, /* tp_weaklistoffset*/
1455 0, /* tp_iternext */
1456 defdict_methods
, /* tp_methods */
1457 defdict_members
, /* tp_members */
1459 DEFERRED_ADDRESS(&PyDict_Type
), /* tp_base */
1461 0, /* tp_descr_get */
1462 0, /* tp_descr_set */
1463 0, /* tp_dictoffset */
1464 defdict_init
, /* tp_init */
1465 PyType_GenericAlloc
, /* tp_alloc */
1467 PyObject_GC_Del
, /* tp_free */
1470 /* module level code ********************************************************/
1472 PyDoc_STRVAR(module_doc
,
1473 "High performance data structures.\n\
1474 - deque: ordered collection accessible from endpoints only\n\
1475 - defaultdict: dict subclass with a default value factory\n\
1479 init_collections(void)
1483 m
= Py_InitModule3("_collections", NULL
, module_doc
);
1487 if (PyType_Ready(&deque_type
) < 0)
1489 Py_INCREF(&deque_type
);
1490 PyModule_AddObject(m
, "deque", (PyObject
*)&deque_type
);
1492 defdict_type
.tp_base
= &PyDict_Type
;
1493 if (PyType_Ready(&defdict_type
) < 0)
1495 Py_INCREF(&defdict_type
);
1496 PyModule_AddObject(m
, "defaultdict", (PyObject
*)&defdict_type
);
1498 if (PyType_Ready(&dequeiter_type
) < 0)
1501 if (PyType_Ready(&dequereviter_type
) < 0)