More configure fixes: avoid sh 'integer argument expected' error when 'long long...
[python.git] / Modules / _collectionsmodule.c
blob978bd9a4bb00e53f4dff9428a8ecaa9563164825
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 /* Handle case where id(deque) == id(iterable) */
302 if ((PyObject *)deque == iterable) {
303 PyObject *result;
304 PyObject *s = PySequence_List(iterable);
305 if (s == NULL)
306 return NULL;
307 result = deque_extend(deque, s);
308 Py_DECREF(s);
309 return result;
312 it = PyObject_GetIter(iterable);
313 if (it == NULL)
314 return NULL;
316 if (deque->maxlen == 0)
317 return consume_iterator(it);
319 while ((item = PyIter_Next(it)) != NULL) {
320 deque->state++;
321 if (deque->rightindex == BLOCKLEN-1) {
322 block *b = newblock(deque->rightblock, NULL,
323 deque->len);
324 if (b == NULL) {
325 Py_DECREF(item);
326 Py_DECREF(it);
327 return NULL;
329 assert(deque->rightblock->rightlink == NULL);
330 deque->rightblock->rightlink = b;
331 deque->rightblock = b;
332 deque->rightindex = -1;
334 deque->len++;
335 deque->rightindex++;
336 deque->rightblock->data[deque->rightindex] = item;
337 TRIM(deque, deque_popleft);
339 Py_DECREF(it);
340 if (PyErr_Occurred())
341 return NULL;
342 Py_RETURN_NONE;
345 PyDoc_STRVAR(extend_doc,
346 "Extend the right side of the deque with elements from the iterable");
348 static PyObject *
349 deque_extendleft(dequeobject *deque, PyObject *iterable)
351 PyObject *it, *item;
353 /* Handle case where id(deque) == id(iterable) */
354 if ((PyObject *)deque == iterable) {
355 PyObject *result;
356 PyObject *s = PySequence_List(iterable);
357 if (s == NULL)
358 return NULL;
359 result = deque_extendleft(deque, s);
360 Py_DECREF(s);
361 return result;
364 it = PyObject_GetIter(iterable);
365 if (it == NULL)
366 return NULL;
368 if (deque->maxlen == 0)
369 return consume_iterator(it);
371 while ((item = PyIter_Next(it)) != NULL) {
372 deque->state++;
373 if (deque->leftindex == 0) {
374 block *b = newblock(NULL, deque->leftblock,
375 deque->len);
376 if (b == NULL) {
377 Py_DECREF(item);
378 Py_DECREF(it);
379 return NULL;
381 assert(deque->leftblock->leftlink == NULL);
382 deque->leftblock->leftlink = b;
383 deque->leftblock = b;
384 deque->leftindex = BLOCKLEN;
386 deque->len++;
387 deque->leftindex--;
388 deque->leftblock->data[deque->leftindex] = item;
389 TRIM(deque, deque_pop);
391 Py_DECREF(it);
392 if (PyErr_Occurred())
393 return NULL;
394 Py_RETURN_NONE;
397 PyDoc_STRVAR(extendleft_doc,
398 "Extend the left side of the deque with elements from the iterable");
400 static PyObject *
401 deque_inplace_concat(dequeobject *deque, PyObject *other)
403 PyObject *result;
405 result = deque_extend(deque, other);
406 if (result == NULL)
407 return result;
408 Py_DECREF(result);
409 Py_INCREF(deque);
410 return (PyObject *)deque;
413 static int
414 _deque_rotate(dequeobject *deque, Py_ssize_t n)
416 Py_ssize_t i, len=deque->len, halflen=(len+1)>>1;
417 PyObject *item, *rv;
419 if (len == 0)
420 return 0;
421 if (n > halflen || n < -halflen) {
422 n %= len;
423 if (n > halflen)
424 n -= len;
425 else if (n < -halflen)
426 n += len;
429 for (i=0 ; i<n ; i++) {
430 item = deque_pop(deque, NULL);
431 assert (item != NULL);
432 rv = deque_appendleft(deque, item);
433 Py_DECREF(item);
434 if (rv == NULL)
435 return -1;
436 Py_DECREF(rv);
438 for (i=0 ; i>n ; i--) {
439 item = deque_popleft(deque, NULL);
440 assert (item != NULL);
441 rv = deque_append(deque, item);
442 Py_DECREF(item);
443 if (rv == NULL)
444 return -1;
445 Py_DECREF(rv);
447 return 0;
450 static PyObject *
451 deque_rotate(dequeobject *deque, PyObject *args)
453 Py_ssize_t n=1;
455 if (!PyArg_ParseTuple(args, "|n:rotate", &n))
456 return NULL;
457 if (_deque_rotate(deque, n) == 0)
458 Py_RETURN_NONE;
459 return NULL;
462 PyDoc_STRVAR(rotate_doc,
463 "Rotate the deque n steps to the right (default n=1). If n is negative, rotates left.");
465 static PyObject *
466 deque_reverse(dequeobject *deque, PyObject *unused)
468 block *leftblock = deque->leftblock;
469 block *rightblock = deque->rightblock;
470 Py_ssize_t leftindex = deque->leftindex;
471 Py_ssize_t rightindex = deque->rightindex;
472 Py_ssize_t n = (deque->len)/2;
473 Py_ssize_t i;
474 PyObject *tmp;
476 for (i=0 ; i<n ; i++) {
477 /* Validate that pointers haven't met in the middle */
478 assert(leftblock != rightblock || leftindex < rightindex);
480 /* Swap */
481 tmp = leftblock->data[leftindex];
482 leftblock->data[leftindex] = rightblock->data[rightindex];
483 rightblock->data[rightindex] = tmp;
485 /* Advance left block/index pair */
486 leftindex++;
487 if (leftindex == BLOCKLEN) {
488 assert (leftblock->rightlink != NULL);
489 leftblock = leftblock->rightlink;
490 leftindex = 0;
493 /* Step backwards with the right block/index pair */
494 rightindex--;
495 if (rightindex == -1) {
496 assert (rightblock->leftlink != NULL);
497 rightblock = rightblock->leftlink;
498 rightindex = BLOCKLEN - 1;
501 Py_RETURN_NONE;
504 PyDoc_STRVAR(reverse_doc,
505 "D.reverse() -- reverse *IN PLACE*");
507 static Py_ssize_t
508 deque_len(dequeobject *deque)
510 return deque->len;
513 static PyObject *
514 deque_remove(dequeobject *deque, PyObject *value)
516 Py_ssize_t i, n=deque->len;
518 for (i=0 ; i<n ; i++) {
519 PyObject *item = deque->leftblock->data[deque->leftindex];
520 int cmp = PyObject_RichCompareBool(item, value, Py_EQ);
522 if (deque->len != n) {
523 PyErr_SetString(PyExc_IndexError,
524 "deque mutated during remove().");
525 return NULL;
527 if (cmp > 0) {
528 PyObject *tgt = deque_popleft(deque, NULL);
529 assert (tgt != NULL);
530 Py_DECREF(tgt);
531 if (_deque_rotate(deque, i) == -1)
532 return NULL;
533 Py_RETURN_NONE;
535 else if (cmp < 0) {
536 _deque_rotate(deque, i);
537 return NULL;
539 _deque_rotate(deque, -1);
541 PyErr_SetString(PyExc_ValueError, "deque.remove(x): x not in deque");
542 return NULL;
545 PyDoc_STRVAR(remove_doc,
546 "D.remove(value) -- remove first occurrence of value.");
548 static int
549 deque_clear(dequeobject *deque)
551 PyObject *item;
553 while (deque->len) {
554 item = deque_pop(deque, NULL);
555 assert (item != NULL);
556 Py_DECREF(item);
558 assert(deque->leftblock == deque->rightblock &&
559 deque->leftindex - 1 == deque->rightindex &&
560 deque->len == 0);
561 return 0;
564 static PyObject *
565 deque_item(dequeobject *deque, Py_ssize_t i)
567 block *b;
568 PyObject *item;
569 Py_ssize_t n, index=i;
571 if (i < 0 || i >= deque->len) {
572 PyErr_SetString(PyExc_IndexError,
573 "deque index out of range");
574 return NULL;
577 if (i == 0) {
578 i = deque->leftindex;
579 b = deque->leftblock;
580 } else if (i == deque->len - 1) {
581 i = deque->rightindex;
582 b = deque->rightblock;
583 } else {
584 i += deque->leftindex;
585 n = i / BLOCKLEN;
586 i %= BLOCKLEN;
587 if (index < (deque->len >> 1)) {
588 b = deque->leftblock;
589 while (n--)
590 b = b->rightlink;
591 } else {
592 n = (deque->leftindex + deque->len - 1) / BLOCKLEN - n;
593 b = deque->rightblock;
594 while (n--)
595 b = b->leftlink;
598 item = b->data[i];
599 Py_INCREF(item);
600 return item;
603 /* delitem() implemented in terms of rotate for simplicity and reasonable
604 performance near the end points. If for some reason this method becomes
605 popular, it is not hard to re-implement this using direct data movement
606 (similar to code in list slice assignment) and achieve a two or threefold
607 performance boost.
610 static int
611 deque_del_item(dequeobject *deque, Py_ssize_t i)
613 PyObject *item;
615 assert (i >= 0 && i < deque->len);
616 if (_deque_rotate(deque, -i) == -1)
617 return -1;
619 item = deque_popleft(deque, NULL);
620 assert (item != NULL);
621 Py_DECREF(item);
623 return _deque_rotate(deque, i);
626 static int
627 deque_ass_item(dequeobject *deque, Py_ssize_t i, PyObject *v)
629 PyObject *old_value;
630 block *b;
631 Py_ssize_t n, len=deque->len, halflen=(len+1)>>1, index=i;
633 if (i < 0 || i >= len) {
634 PyErr_SetString(PyExc_IndexError,
635 "deque index out of range");
636 return -1;
638 if (v == NULL)
639 return deque_del_item(deque, i);
641 i += deque->leftindex;
642 n = i / BLOCKLEN;
643 i %= BLOCKLEN;
644 if (index <= halflen) {
645 b = deque->leftblock;
646 while (n--)
647 b = b->rightlink;
648 } else {
649 n = (deque->leftindex + len - 1) / BLOCKLEN - n;
650 b = deque->rightblock;
651 while (n--)
652 b = b->leftlink;
654 Py_INCREF(v);
655 old_value = b->data[i];
656 b->data[i] = v;
657 Py_DECREF(old_value);
658 return 0;
661 static PyObject *
662 deque_clearmethod(dequeobject *deque)
664 int rv;
666 rv = deque_clear(deque);
667 assert (rv != -1);
668 Py_RETURN_NONE;
671 PyDoc_STRVAR(clear_doc, "Remove all elements from the deque.");
673 static void
674 deque_dealloc(dequeobject *deque)
676 PyObject_GC_UnTrack(deque);
677 if (deque->weakreflist != NULL)
678 PyObject_ClearWeakRefs((PyObject *) deque);
679 if (deque->leftblock != NULL) {
680 deque_clear(deque);
681 assert(deque->leftblock != NULL);
682 freeblock(deque->leftblock);
684 deque->leftblock = NULL;
685 deque->rightblock = NULL;
686 Py_TYPE(deque)->tp_free(deque);
689 static int
690 deque_traverse(dequeobject *deque, visitproc visit, void *arg)
692 block *b;
693 PyObject *item;
694 Py_ssize_t index;
695 Py_ssize_t indexlo = deque->leftindex;
697 for (b = deque->leftblock; b != NULL; b = b->rightlink) {
698 const Py_ssize_t indexhi = b == deque->rightblock ?
699 deque->rightindex :
700 BLOCKLEN - 1;
702 for (index = indexlo; index <= indexhi; ++index) {
703 item = b->data[index];
704 Py_VISIT(item);
706 indexlo = 0;
708 return 0;
711 static PyObject *
712 deque_copy(PyObject *deque)
714 if (((dequeobject *)deque)->maxlen == -1)
715 return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "O", deque, NULL);
716 else
717 return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "Oi",
718 deque, ((dequeobject *)deque)->maxlen, NULL);
721 PyDoc_STRVAR(copy_doc, "Return a shallow copy of a deque.");
723 static PyObject *
724 deque_reduce(dequeobject *deque)
726 PyObject *dict, *result, *aslist;
728 dict = PyObject_GetAttrString((PyObject *)deque, "__dict__");
729 if (dict == NULL)
730 PyErr_Clear();
731 aslist = PySequence_List((PyObject *)deque);
732 if (aslist == NULL) {
733 Py_XDECREF(dict);
734 return NULL;
736 if (dict == NULL) {
737 if (deque->maxlen == -1)
738 result = Py_BuildValue("O(O)", Py_TYPE(deque), aslist);
739 else
740 result = Py_BuildValue("O(On)", Py_TYPE(deque), aslist, deque->maxlen);
741 } else {
742 if (deque->maxlen == -1)
743 result = Py_BuildValue("O(OO)O", Py_TYPE(deque), aslist, Py_None, dict);
744 else
745 result = Py_BuildValue("O(On)O", Py_TYPE(deque), aslist, deque->maxlen, dict);
747 Py_XDECREF(dict);
748 Py_DECREF(aslist);
749 return result;
752 PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
754 static PyObject *
755 deque_repr(PyObject *deque)
757 PyObject *aslist, *result, *fmt;
758 int i;
760 i = Py_ReprEnter(deque);
761 if (i != 0) {
762 if (i < 0)
763 return NULL;
764 return PyString_FromString("[...]");
767 aslist = PySequence_List(deque);
768 if (aslist == NULL) {
769 Py_ReprLeave(deque);
770 return NULL;
772 if (((dequeobject *)deque)->maxlen != -1)
773 fmt = PyString_FromFormat("deque(%%r, maxlen=%zd)",
774 ((dequeobject *)deque)->maxlen);
775 else
776 fmt = PyString_FromString("deque(%r)");
777 if (fmt == NULL) {
778 Py_DECREF(aslist);
779 Py_ReprLeave(deque);
780 return NULL;
782 result = PyString_Format(fmt, aslist);
783 Py_DECREF(fmt);
784 Py_DECREF(aslist);
785 Py_ReprLeave(deque);
786 return result;
789 static int
790 deque_tp_print(PyObject *deque, FILE *fp, int flags)
792 PyObject *it, *item;
793 char *emit = ""; /* No separator emitted on first pass */
794 char *separator = ", ";
795 int i;
797 i = Py_ReprEnter(deque);
798 if (i != 0) {
799 if (i < 0)
800 return i;
801 Py_BEGIN_ALLOW_THREADS
802 fputs("[...]", fp);
803 Py_END_ALLOW_THREADS
804 return 0;
807 it = PyObject_GetIter(deque);
808 if (it == NULL)
809 return -1;
811 Py_BEGIN_ALLOW_THREADS
812 fputs("deque([", fp);
813 Py_END_ALLOW_THREADS
814 while ((item = PyIter_Next(it)) != NULL) {
815 Py_BEGIN_ALLOW_THREADS
816 fputs(emit, fp);
817 Py_END_ALLOW_THREADS
818 emit = separator;
819 if (PyObject_Print(item, fp, 0) != 0) {
820 Py_DECREF(item);
821 Py_DECREF(it);
822 Py_ReprLeave(deque);
823 return -1;
825 Py_DECREF(item);
827 Py_ReprLeave(deque);
828 Py_DECREF(it);
829 if (PyErr_Occurred())
830 return -1;
832 Py_BEGIN_ALLOW_THREADS
833 if (((dequeobject *)deque)->maxlen == -1)
834 fputs("])", fp);
835 else
836 fprintf(fp, "], maxlen=%" PY_FORMAT_SIZE_T "d)", ((dequeobject *)deque)->maxlen);
837 Py_END_ALLOW_THREADS
838 return 0;
841 static PyObject *
842 deque_richcompare(PyObject *v, PyObject *w, int op)
844 PyObject *it1=NULL, *it2=NULL, *x, *y;
845 Py_ssize_t vs, ws;
846 int b, cmp=-1;
848 if (!PyObject_TypeCheck(v, &deque_type) ||
849 !PyObject_TypeCheck(w, &deque_type)) {
850 Py_INCREF(Py_NotImplemented);
851 return Py_NotImplemented;
854 /* Shortcuts */
855 vs = ((dequeobject *)v)->len;
856 ws = ((dequeobject *)w)->len;
857 if (op == Py_EQ) {
858 if (v == w)
859 Py_RETURN_TRUE;
860 if (vs != ws)
861 Py_RETURN_FALSE;
863 if (op == Py_NE) {
864 if (v == w)
865 Py_RETURN_FALSE;
866 if (vs != ws)
867 Py_RETURN_TRUE;
870 /* Search for the first index where items are different */
871 it1 = PyObject_GetIter(v);
872 if (it1 == NULL)
873 goto done;
874 it2 = PyObject_GetIter(w);
875 if (it2 == NULL)
876 goto done;
877 for (;;) {
878 x = PyIter_Next(it1);
879 if (x == NULL && PyErr_Occurred())
880 goto done;
881 y = PyIter_Next(it2);
882 if (x == NULL || y == NULL)
883 break;
884 b = PyObject_RichCompareBool(x, y, Py_EQ);
885 if (b == 0) {
886 cmp = PyObject_RichCompareBool(x, y, op);
887 Py_DECREF(x);
888 Py_DECREF(y);
889 goto done;
891 Py_DECREF(x);
892 Py_DECREF(y);
893 if (b == -1)
894 goto done;
896 /* We reached the end of one deque or both */
897 Py_XDECREF(x);
898 Py_XDECREF(y);
899 if (PyErr_Occurred())
900 goto done;
901 switch (op) {
902 case Py_LT: cmp = y != NULL; break; /* if w was longer */
903 case Py_LE: cmp = x == NULL; break; /* if v was not longer */
904 case Py_EQ: cmp = x == y; break; /* if we reached the end of both */
905 case Py_NE: cmp = x != y; break; /* if one deque continues */
906 case Py_GT: cmp = x != NULL; break; /* if v was longer */
907 case Py_GE: cmp = y == NULL; break; /* if w was not longer */
910 done:
911 Py_XDECREF(it1);
912 Py_XDECREF(it2);
913 if (cmp == 1)
914 Py_RETURN_TRUE;
915 if (cmp == 0)
916 Py_RETURN_FALSE;
917 return NULL;
920 static int
921 deque_init(dequeobject *deque, PyObject *args, PyObject *kwdargs)
923 PyObject *iterable = NULL;
924 PyObject *maxlenobj = NULL;
925 Py_ssize_t maxlen = -1;
926 char *kwlist[] = {"iterable", "maxlen", 0};
928 if (!PyArg_ParseTupleAndKeywords(args, kwdargs, "|OO:deque", kwlist, &iterable, &maxlenobj))
929 return -1;
930 if (maxlenobj != NULL && maxlenobj != Py_None) {
931 maxlen = PyInt_AsSsize_t(maxlenobj);
932 if (maxlen == -1 && PyErr_Occurred())
933 return -1;
934 if (maxlen < 0) {
935 PyErr_SetString(PyExc_ValueError, "maxlen must be non-negative");
936 return -1;
939 deque->maxlen = maxlen;
940 deque_clear(deque);
941 if (iterable != NULL) {
942 PyObject *rv = deque_extend(deque, iterable);
943 if (rv == NULL)
944 return -1;
945 Py_DECREF(rv);
947 return 0;
950 static PyObject *
951 deque_get_maxlen(dequeobject *deque)
953 if (deque->maxlen == -1)
954 Py_RETURN_NONE;
955 return PyInt_FromSsize_t(deque->maxlen);
958 static PyGetSetDef deque_getset[] = {
959 {"maxlen", (getter)deque_get_maxlen, (setter)NULL,
960 "maximum size of a deque or None if unbounded"},
964 static PySequenceMethods deque_as_sequence = {
965 (lenfunc)deque_len, /* sq_length */
966 0, /* sq_concat */
967 0, /* sq_repeat */
968 (ssizeargfunc)deque_item, /* sq_item */
969 0, /* sq_slice */
970 (ssizeobjargproc)deque_ass_item, /* sq_ass_item */
971 0, /* sq_ass_slice */
972 0, /* sq_contains */
973 (binaryfunc)deque_inplace_concat, /* sq_inplace_concat */
974 0, /* sq_inplace_repeat */
978 /* deque object ********************************************************/
980 static PyObject *deque_iter(dequeobject *deque);
981 static PyObject *deque_reviter(dequeobject *deque);
982 PyDoc_STRVAR(reversed_doc,
983 "D.__reversed__() -- return a reverse iterator over the deque");
985 static PyMethodDef deque_methods[] = {
986 {"append", (PyCFunction)deque_append,
987 METH_O, append_doc},
988 {"appendleft", (PyCFunction)deque_appendleft,
989 METH_O, appendleft_doc},
990 {"clear", (PyCFunction)deque_clearmethod,
991 METH_NOARGS, clear_doc},
992 {"__copy__", (PyCFunction)deque_copy,
993 METH_NOARGS, copy_doc},
994 {"extend", (PyCFunction)deque_extend,
995 METH_O, extend_doc},
996 {"extendleft", (PyCFunction)deque_extendleft,
997 METH_O, extendleft_doc},
998 {"pop", (PyCFunction)deque_pop,
999 METH_NOARGS, pop_doc},
1000 {"popleft", (PyCFunction)deque_popleft,
1001 METH_NOARGS, popleft_doc},
1002 {"__reduce__", (PyCFunction)deque_reduce,
1003 METH_NOARGS, reduce_doc},
1004 {"remove", (PyCFunction)deque_remove,
1005 METH_O, remove_doc},
1006 {"__reversed__", (PyCFunction)deque_reviter,
1007 METH_NOARGS, reversed_doc},
1008 {"reverse", (PyCFunction)deque_reverse,
1009 METH_NOARGS, reverse_doc},
1010 {"rotate", (PyCFunction)deque_rotate,
1011 METH_VARARGS, rotate_doc},
1012 {NULL, NULL} /* sentinel */
1015 PyDoc_STRVAR(deque_doc,
1016 "deque(iterable[, maxlen]) --> deque object\n\
1018 Build an ordered collection accessible from endpoints only.");
1020 static PyTypeObject deque_type = {
1021 PyVarObject_HEAD_INIT(NULL, 0)
1022 "collections.deque", /* tp_name */
1023 sizeof(dequeobject), /* tp_basicsize */
1024 0, /* tp_itemsize */
1025 /* methods */
1026 (destructor)deque_dealloc, /* tp_dealloc */
1027 deque_tp_print, /* tp_print */
1028 0, /* tp_getattr */
1029 0, /* tp_setattr */
1030 0, /* tp_compare */
1031 deque_repr, /* tp_repr */
1032 0, /* tp_as_number */
1033 &deque_as_sequence, /* tp_as_sequence */
1034 0, /* tp_as_mapping */
1035 (hashfunc)PyObject_HashNotImplemented, /* tp_hash */
1036 0, /* tp_call */
1037 0, /* tp_str */
1038 PyObject_GenericGetAttr, /* tp_getattro */
1039 0, /* tp_setattro */
1040 0, /* tp_as_buffer */
1041 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
1042 Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
1043 deque_doc, /* tp_doc */
1044 (traverseproc)deque_traverse, /* tp_traverse */
1045 (inquiry)deque_clear, /* tp_clear */
1046 (richcmpfunc)deque_richcompare, /* tp_richcompare */
1047 offsetof(dequeobject, weakreflist), /* tp_weaklistoffset*/
1048 (getiterfunc)deque_iter, /* tp_iter */
1049 0, /* tp_iternext */
1050 deque_methods, /* tp_methods */
1051 0, /* tp_members */
1052 deque_getset, /* tp_getset */
1053 0, /* tp_base */
1054 0, /* tp_dict */
1055 0, /* tp_descr_get */
1056 0, /* tp_descr_set */
1057 0, /* tp_dictoffset */
1058 (initproc)deque_init, /* tp_init */
1059 PyType_GenericAlloc, /* tp_alloc */
1060 deque_new, /* tp_new */
1061 PyObject_GC_Del, /* tp_free */
1064 /*********************** Deque Iterator **************************/
1066 typedef struct {
1067 PyObject_HEAD
1068 Py_ssize_t index;
1069 block *b;
1070 dequeobject *deque;
1071 long state; /* state when the iterator is created */
1072 Py_ssize_t counter; /* number of items remaining for iteration */
1073 } dequeiterobject;
1075 static PyTypeObject dequeiter_type;
1077 static PyObject *
1078 deque_iter(dequeobject *deque)
1080 dequeiterobject *it;
1082 it = PyObject_GC_New(dequeiterobject, &dequeiter_type);
1083 if (it == NULL)
1084 return NULL;
1085 it->b = deque->leftblock;
1086 it->index = deque->leftindex;
1087 Py_INCREF(deque);
1088 it->deque = deque;
1089 it->state = deque->state;
1090 it->counter = deque->len;
1091 PyObject_GC_Track(it);
1092 return (PyObject *)it;
1095 static int
1096 dequeiter_traverse(dequeiterobject *dio, visitproc visit, void *arg)
1098 Py_VISIT(dio->deque);
1099 return 0;
1102 static void
1103 dequeiter_dealloc(dequeiterobject *dio)
1105 Py_XDECREF(dio->deque);
1106 PyObject_GC_Del(dio);
1109 static PyObject *
1110 dequeiter_next(dequeiterobject *it)
1112 PyObject *item;
1114 if (it->deque->state != it->state) {
1115 it->counter = 0;
1116 PyErr_SetString(PyExc_RuntimeError,
1117 "deque mutated during iteration");
1118 return NULL;
1120 if (it->counter == 0)
1121 return NULL;
1122 assert (!(it->b == it->deque->rightblock &&
1123 it->index > it->deque->rightindex));
1125 item = it->b->data[it->index];
1126 it->index++;
1127 it->counter--;
1128 if (it->index == BLOCKLEN && it->counter > 0) {
1129 assert (it->b->rightlink != NULL);
1130 it->b = it->b->rightlink;
1131 it->index = 0;
1133 Py_INCREF(item);
1134 return item;
1137 static PyObject *
1138 dequeiter_len(dequeiterobject *it)
1140 return PyInt_FromLong(it->counter);
1143 PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
1145 static PyMethodDef dequeiter_methods[] = {
1146 {"__length_hint__", (PyCFunction)dequeiter_len, METH_NOARGS, length_hint_doc},
1147 {NULL, NULL} /* sentinel */
1150 static PyTypeObject dequeiter_type = {
1151 PyVarObject_HEAD_INIT(NULL, 0)
1152 "deque_iterator", /* tp_name */
1153 sizeof(dequeiterobject), /* tp_basicsize */
1154 0, /* tp_itemsize */
1155 /* methods */
1156 (destructor)dequeiter_dealloc, /* tp_dealloc */
1157 0, /* tp_print */
1158 0, /* tp_getattr */
1159 0, /* tp_setattr */
1160 0, /* tp_compare */
1161 0, /* tp_repr */
1162 0, /* tp_as_number */
1163 0, /* tp_as_sequence */
1164 0, /* tp_as_mapping */
1165 0, /* tp_hash */
1166 0, /* tp_call */
1167 0, /* tp_str */
1168 PyObject_GenericGetAttr, /* tp_getattro */
1169 0, /* tp_setattro */
1170 0, /* tp_as_buffer */
1171 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
1172 0, /* tp_doc */
1173 (traverseproc)dequeiter_traverse, /* tp_traverse */
1174 0, /* tp_clear */
1175 0, /* tp_richcompare */
1176 0, /* tp_weaklistoffset */
1177 PyObject_SelfIter, /* tp_iter */
1178 (iternextfunc)dequeiter_next, /* tp_iternext */
1179 dequeiter_methods, /* tp_methods */
1183 /*********************** Deque Reverse Iterator **************************/
1185 static PyTypeObject dequereviter_type;
1187 static PyObject *
1188 deque_reviter(dequeobject *deque)
1190 dequeiterobject *it;
1192 it = PyObject_GC_New(dequeiterobject, &dequereviter_type);
1193 if (it == NULL)
1194 return NULL;
1195 it->b = deque->rightblock;
1196 it->index = deque->rightindex;
1197 Py_INCREF(deque);
1198 it->deque = deque;
1199 it->state = deque->state;
1200 it->counter = deque->len;
1201 PyObject_GC_Track(it);
1202 return (PyObject *)it;
1205 static PyObject *
1206 dequereviter_next(dequeiterobject *it)
1208 PyObject *item;
1209 if (it->counter == 0)
1210 return NULL;
1212 if (it->deque->state != it->state) {
1213 it->counter = 0;
1214 PyErr_SetString(PyExc_RuntimeError,
1215 "deque mutated during iteration");
1216 return NULL;
1218 assert (!(it->b == it->deque->leftblock &&
1219 it->index < it->deque->leftindex));
1221 item = it->b->data[it->index];
1222 it->index--;
1223 it->counter--;
1224 if (it->index == -1 && it->counter > 0) {
1225 assert (it->b->leftlink != NULL);
1226 it->b = it->b->leftlink;
1227 it->index = BLOCKLEN - 1;
1229 Py_INCREF(item);
1230 return item;
1233 static PyTypeObject dequereviter_type = {
1234 PyVarObject_HEAD_INIT(NULL, 0)
1235 "deque_reverse_iterator", /* tp_name */
1236 sizeof(dequeiterobject), /* tp_basicsize */
1237 0, /* tp_itemsize */
1238 /* methods */
1239 (destructor)dequeiter_dealloc, /* tp_dealloc */
1240 0, /* tp_print */
1241 0, /* tp_getattr */
1242 0, /* tp_setattr */
1243 0, /* tp_compare */
1244 0, /* tp_repr */
1245 0, /* tp_as_number */
1246 0, /* tp_as_sequence */
1247 0, /* tp_as_mapping */
1248 0, /* tp_hash */
1249 0, /* tp_call */
1250 0, /* tp_str */
1251 PyObject_GenericGetAttr, /* tp_getattro */
1252 0, /* tp_setattro */
1253 0, /* tp_as_buffer */
1254 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
1255 0, /* tp_doc */
1256 (traverseproc)dequeiter_traverse, /* tp_traverse */
1257 0, /* tp_clear */
1258 0, /* tp_richcompare */
1259 0, /* tp_weaklistoffset */
1260 PyObject_SelfIter, /* tp_iter */
1261 (iternextfunc)dequereviter_next, /* tp_iternext */
1262 dequeiter_methods, /* tp_methods */
1266 /* defaultdict type *********************************************************/
1268 typedef struct {
1269 PyDictObject dict;
1270 PyObject *default_factory;
1271 } defdictobject;
1273 static PyTypeObject defdict_type; /* Forward */
1275 PyDoc_STRVAR(defdict_missing_doc,
1276 "__missing__(key) # Called by __getitem__ for missing key; pseudo-code:\n\
1277 if self.default_factory is None: raise KeyError((key,))\n\
1278 self[key] = value = self.default_factory()\n\
1279 return value\n\
1282 static PyObject *
1283 defdict_missing(defdictobject *dd, PyObject *key)
1285 PyObject *factory = dd->default_factory;
1286 PyObject *value;
1287 if (factory == NULL || factory == Py_None) {
1288 /* XXX Call dict.__missing__(key) */
1289 PyObject *tup;
1290 tup = PyTuple_Pack(1, key);
1291 if (!tup) return NULL;
1292 PyErr_SetObject(PyExc_KeyError, tup);
1293 Py_DECREF(tup);
1294 return NULL;
1296 value = PyEval_CallObject(factory, NULL);
1297 if (value == NULL)
1298 return value;
1299 if (PyObject_SetItem((PyObject *)dd, key, value) < 0) {
1300 Py_DECREF(value);
1301 return NULL;
1303 return value;
1306 PyDoc_STRVAR(defdict_copy_doc, "D.copy() -> a shallow copy of D.");
1308 static PyObject *
1309 defdict_copy(defdictobject *dd)
1311 /* This calls the object's class. That only works for subclasses
1312 whose class constructor has the same signature. Subclasses that
1313 define a different constructor signature must override copy().
1316 if (dd->default_factory == NULL)
1317 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd), Py_None, dd, NULL);
1318 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd),
1319 dd->default_factory, dd, NULL);
1322 static PyObject *
1323 defdict_reduce(defdictobject *dd)
1325 /* __reduce__ must return a 5-tuple as follows:
1327 - factory function
1328 - tuple of args for the factory function
1329 - additional state (here None)
1330 - sequence iterator (here None)
1331 - dictionary iterator (yielding successive (key, value) pairs
1333 This API is used by pickle.py and copy.py.
1335 For this to be useful with pickle.py, the default_factory
1336 must be picklable; e.g., None, a built-in, or a global
1337 function in a module or package.
1339 Both shallow and deep copying are supported, but for deep
1340 copying, the default_factory must be deep-copyable; e.g. None,
1341 or a built-in (functions are not copyable at this time).
1343 This only works for subclasses as long as their constructor
1344 signature is compatible; the first argument must be the
1345 optional default_factory, defaulting to None.
1347 PyObject *args;
1348 PyObject *items;
1349 PyObject *result;
1350 if (dd->default_factory == NULL || dd->default_factory == Py_None)
1351 args = PyTuple_New(0);
1352 else
1353 args = PyTuple_Pack(1, dd->default_factory);
1354 if (args == NULL)
1355 return NULL;
1356 items = PyObject_CallMethod((PyObject *)dd, "iteritems", "()");
1357 if (items == NULL) {
1358 Py_DECREF(args);
1359 return NULL;
1361 result = PyTuple_Pack(5, Py_TYPE(dd), args,
1362 Py_None, Py_None, items);
1363 Py_DECREF(items);
1364 Py_DECREF(args);
1365 return result;
1368 static PyMethodDef defdict_methods[] = {
1369 {"__missing__", (PyCFunction)defdict_missing, METH_O,
1370 defdict_missing_doc},
1371 {"copy", (PyCFunction)defdict_copy, METH_NOARGS,
1372 defdict_copy_doc},
1373 {"__copy__", (PyCFunction)defdict_copy, METH_NOARGS,
1374 defdict_copy_doc},
1375 {"__reduce__", (PyCFunction)defdict_reduce, METH_NOARGS,
1376 reduce_doc},
1377 {NULL}
1380 static PyMemberDef defdict_members[] = {
1381 {"default_factory", T_OBJECT,
1382 offsetof(defdictobject, default_factory), 0,
1383 PyDoc_STR("Factory for default value called by __missing__().")},
1384 {NULL}
1387 static void
1388 defdict_dealloc(defdictobject *dd)
1390 Py_CLEAR(dd->default_factory);
1391 PyDict_Type.tp_dealloc((PyObject *)dd);
1394 static int
1395 defdict_print(defdictobject *dd, FILE *fp, int flags)
1397 int sts;
1398 Py_BEGIN_ALLOW_THREADS
1399 fprintf(fp, "defaultdict(");
1400 Py_END_ALLOW_THREADS
1401 if (dd->default_factory == NULL) {
1402 Py_BEGIN_ALLOW_THREADS
1403 fprintf(fp, "None");
1404 Py_END_ALLOW_THREADS
1405 } else {
1406 PyObject_Print(dd->default_factory, fp, 0);
1408 Py_BEGIN_ALLOW_THREADS
1409 fprintf(fp, ", ");
1410 Py_END_ALLOW_THREADS
1411 sts = PyDict_Type.tp_print((PyObject *)dd, fp, 0);
1412 Py_BEGIN_ALLOW_THREADS
1413 fprintf(fp, ")");
1414 Py_END_ALLOW_THREADS
1415 return sts;
1418 static PyObject *
1419 defdict_repr(defdictobject *dd)
1421 PyObject *defrepr;
1422 PyObject *baserepr;
1423 PyObject *result;
1424 baserepr = PyDict_Type.tp_repr((PyObject *)dd);
1425 if (baserepr == NULL)
1426 return NULL;
1427 if (dd->default_factory == NULL)
1428 defrepr = PyString_FromString("None");
1429 else
1431 int status = Py_ReprEnter(dd->default_factory);
1432 if (status != 0) {
1433 if (status < 0)
1434 return NULL;
1435 defrepr = PyString_FromString("...");
1437 else
1438 defrepr = PyObject_Repr(dd->default_factory);
1439 Py_ReprLeave(dd->default_factory);
1441 if (defrepr == NULL) {
1442 Py_DECREF(baserepr);
1443 return NULL;
1445 result = PyString_FromFormat("defaultdict(%s, %s)",
1446 PyString_AS_STRING(defrepr),
1447 PyString_AS_STRING(baserepr));
1448 Py_DECREF(defrepr);
1449 Py_DECREF(baserepr);
1450 return result;
1453 static int
1454 defdict_traverse(PyObject *self, visitproc visit, void *arg)
1456 Py_VISIT(((defdictobject *)self)->default_factory);
1457 return PyDict_Type.tp_traverse(self, visit, arg);
1460 static int
1461 defdict_tp_clear(defdictobject *dd)
1463 Py_CLEAR(dd->default_factory);
1464 return PyDict_Type.tp_clear((PyObject *)dd);
1467 static int
1468 defdict_init(PyObject *self, PyObject *args, PyObject *kwds)
1470 defdictobject *dd = (defdictobject *)self;
1471 PyObject *olddefault = dd->default_factory;
1472 PyObject *newdefault = NULL;
1473 PyObject *newargs;
1474 int result;
1475 if (args == NULL || !PyTuple_Check(args))
1476 newargs = PyTuple_New(0);
1477 else {
1478 Py_ssize_t n = PyTuple_GET_SIZE(args);
1479 if (n > 0) {
1480 newdefault = PyTuple_GET_ITEM(args, 0);
1481 if (!PyCallable_Check(newdefault) && newdefault != Py_None) {
1482 PyErr_SetString(PyExc_TypeError,
1483 "first argument must be callable");
1484 return -1;
1487 newargs = PySequence_GetSlice(args, 1, n);
1489 if (newargs == NULL)
1490 return -1;
1491 Py_XINCREF(newdefault);
1492 dd->default_factory = newdefault;
1493 result = PyDict_Type.tp_init(self, newargs, kwds);
1494 Py_DECREF(newargs);
1495 Py_XDECREF(olddefault);
1496 return result;
1499 PyDoc_STRVAR(defdict_doc,
1500 "defaultdict(default_factory) --> dict with default factory\n\
1502 The default factory is called without arguments to produce\n\
1503 a new value when a key is not present, in __getitem__ only.\n\
1504 A defaultdict compares equal to a dict with the same items.\n\
1507 /* See comment in xxsubtype.c */
1508 #define DEFERRED_ADDRESS(ADDR) 0
1510 static PyTypeObject defdict_type = {
1511 PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0)
1512 "collections.defaultdict", /* tp_name */
1513 sizeof(defdictobject), /* tp_basicsize */
1514 0, /* tp_itemsize */
1515 /* methods */
1516 (destructor)defdict_dealloc, /* tp_dealloc */
1517 (printfunc)defdict_print, /* tp_print */
1518 0, /* tp_getattr */
1519 0, /* tp_setattr */
1520 0, /* tp_compare */
1521 (reprfunc)defdict_repr, /* tp_repr */
1522 0, /* tp_as_number */
1523 0, /* tp_as_sequence */
1524 0, /* tp_as_mapping */
1525 0, /* tp_hash */
1526 0, /* tp_call */
1527 0, /* tp_str */
1528 PyObject_GenericGetAttr, /* tp_getattro */
1529 0, /* tp_setattro */
1530 0, /* tp_as_buffer */
1531 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
1532 Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
1533 defdict_doc, /* tp_doc */
1534 defdict_traverse, /* tp_traverse */
1535 (inquiry)defdict_tp_clear, /* tp_clear */
1536 0, /* tp_richcompare */
1537 0, /* tp_weaklistoffset*/
1538 0, /* tp_iter */
1539 0, /* tp_iternext */
1540 defdict_methods, /* tp_methods */
1541 defdict_members, /* tp_members */
1542 0, /* tp_getset */
1543 DEFERRED_ADDRESS(&PyDict_Type), /* tp_base */
1544 0, /* tp_dict */
1545 0, /* tp_descr_get */
1546 0, /* tp_descr_set */
1547 0, /* tp_dictoffset */
1548 defdict_init, /* tp_init */
1549 PyType_GenericAlloc, /* tp_alloc */
1550 0, /* tp_new */
1551 PyObject_GC_Del, /* tp_free */
1554 /* module level code ********************************************************/
1556 PyDoc_STRVAR(module_doc,
1557 "High performance data structures.\n\
1558 - deque: ordered collection accessible from endpoints only\n\
1559 - defaultdict: dict subclass with a default value factory\n\
1562 PyMODINIT_FUNC
1563 init_collections(void)
1565 PyObject *m;
1567 m = Py_InitModule3("_collections", NULL, module_doc);
1568 if (m == NULL)
1569 return;
1571 if (PyType_Ready(&deque_type) < 0)
1572 return;
1573 Py_INCREF(&deque_type);
1574 PyModule_AddObject(m, "deque", (PyObject *)&deque_type);
1576 defdict_type.tp_base = &PyDict_Type;
1577 if (PyType_Ready(&defdict_type) < 0)
1578 return;
1579 Py_INCREF(&defdict_type);
1580 PyModule_AddObject(m, "defaultdict", (PyObject *)&defdict_type);
1582 if (PyType_Ready(&dequeiter_type) < 0)
1583 return;
1585 if (PyType_Ready(&dequereviter_type) < 0)
1586 return;
1588 return;