blob: 8cd22d77edfdfe2a072fac95cffa87eff629b580 [file] [log] [blame]
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001#include "Python.h"
Raymond Hettinger691d8052004-05-30 07:26:47 +00002#include "structmember.h"
Raymond Hettinger756b3f32004-01-29 06:37:52 +00003
Raymond Hettingerc2083082015-02-28 23:29:16 -08004#ifdef STDC_HEADERS
5#include <stddef.h>
6#else
7#include <sys/types.h> /* For size_t */
8#endif
9
Raymond Hettinger756b3f32004-01-29 06:37:52 +000010/* collections module implementation of a deque() datatype
11 Written and maintained by Raymond D. Hettinger <python@rcn.com>
Raymond Hettingereb6b5542015-02-10 22:37:22 -060012 Copyright (c) 2004-2015 Python Software Foundation.
Raymond Hettinger756b3f32004-01-29 06:37:52 +000013 All rights reserved.
14*/
15
Raymond Hettinger77e8bf12004-10-01 15:25:53 +000016/* The block length may be set to any number over 1. Larger numbers
Raymond Hettinger20b0f872013-06-23 15:44:33 -070017 * reduce the number of calls to the memory allocator, give faster
Raymond Hettinger30c90742015-03-02 22:31:35 -080018 * indexing and rotation, and reduce the link to data overhead ratio.
Raymond Hettingerdaf57f22015-02-26 23:21:29 -080019 * Making the block length a power of two speeds-up the modulo
Raymond Hettinger30c90742015-03-02 22:31:35 -080020 * and division calculations in deque_item() and deque_ass_item().
Raymond Hettinger77e8bf12004-10-01 15:25:53 +000021 */
22
Raymond Hettingerdaf57f22015-02-26 23:21:29 -080023#define BLOCKLEN 64
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000024#define CENTER ((BLOCKLEN - 1) / 2)
Raymond Hettinger756b3f32004-01-29 06:37:52 +000025
Raymond Hettinger551350a2015-03-24 00:19:53 -070026/* Data for deque objects is stored in a doubly-linked list of fixed
27 * length blocks. This assures that appends or pops never move any
28 * other data elements besides the one being appended or popped.
29 *
30 * Another advantage is that it completely avoids use of realloc(),
31 * resulting in more predictable performance.
32 *
33 * Textbook implementations of doubly-linked lists store one datum
34 * per link, but that gives them a 200% memory overhead (a prev and
35 * next link for each datum) and it costs one malloc() call per data
36 * element. By using fixed-length blocks, the link to data ratio is
37 * significantly improved and there are proportionally fewer calls
38 * to malloc() and free(). The data blocks of consecutive pointers
39 * also improve cache locality.
40 *
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000041 * The list of blocks is never empty, so d.leftblock and d.rightblock
Raymond Hettinger82df9252013-07-07 01:43:42 -100042 * are never equal to NULL. The list is not circular.
43 *
44 * A deque d's first element is at d.leftblock[leftindex]
45 * and its last element is at d.rightblock[rightindex].
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000046 *
Raymond Hettinger551350a2015-03-24 00:19:53 -070047 * Unlike Python slice indices, these indices are inclusive on both
48 * ends. This makes the algorithms for left and right operations
49 * more symmetrical and it simplifies the design.
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000050 *
Raymond Hettinger551350a2015-03-24 00:19:53 -070051 * The indices, d.leftindex and d.rightindex are always in the range:
52 * 0 <= index < BLOCKLEN
53 *
54 * And their exact relationship is:
55 * (d.leftindex + d.len - 1) % BLOCKLEN == d.rightindex
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000056 *
Raymond Hettinger8dbbae22015-03-24 21:01:50 -070057 * Whenever d.leftblock == d.rightblock, then:
Raymond Hettinger551350a2015-03-24 00:19:53 -070058 * d.leftindex + d.len - 1 == d.rightindex
Thomas Wouters0e3f5912006-08-11 14:57:12 +000059 *
Raymond Hettinger551350a2015-03-24 00:19:53 -070060 * However, when d.leftblock != d.rightblock, the d.leftindex and
61 * d.rightindex become indices into distinct blocks and either may
62 * be larger than the other.
63 *
64 * Empty deques have:
65 * d.len == 0
66 * d.leftblock == d.rightblock
67 * d.leftindex == CENTER + 1
68 * d.rightindex == CENTER
69 *
70 * Checking for d.len == 0 is the intended way to see whether d is empty.
Tim Petersd8768d32004-10-01 01:32:53 +000071 */
72
Raymond Hettinger756b3f32004-01-29 06:37:52 +000073typedef struct BLOCK {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000074 struct BLOCK *leftlink;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000075 PyObject *data[BLOCKLEN];
Raymond Hettinger20b0f872013-06-23 15:44:33 -070076 struct BLOCK *rightlink;
Raymond Hettinger756b3f32004-01-29 06:37:52 +000077} block;
78
Raymond Hettinger30c90742015-03-02 22:31:35 -080079typedef struct {
80 PyObject_VAR_HEAD
81 block *leftblock;
82 block *rightblock;
Raymond Hettinger551350a2015-03-24 00:19:53 -070083 Py_ssize_t leftindex; /* 0 <= leftindex < BLOCKLEN */
84 Py_ssize_t rightindex; /* 0 <= rightindex < BLOCKLEN */
Raymond Hettingerf9d9c792015-03-02 22:47:46 -080085 size_t state; /* incremented whenever the indices move */
Raymond Hettinger30c90742015-03-02 22:31:35 -080086 Py_ssize_t maxlen;
Raymond Hettinger0f6f9472015-03-21 01:42:10 -070087 PyObject *weakreflist;
Raymond Hettinger30c90742015-03-02 22:31:35 -080088} dequeobject;
89
90static PyTypeObject deque_type;
91
Raymond Hettinger82df9252013-07-07 01:43:42 -100092/* For debug builds, add error checking to track the endpoints
93 * in the chain of links. The goal is to make sure that link
94 * assignments only take place at endpoints so that links already
95 * in use do not get overwritten.
96 *
97 * CHECK_END should happen before each assignment to a block's link field.
98 * MARK_END should happen whenever a link field becomes a new endpoint.
99 * This happens when new blocks are added or whenever an existing
100 * block is freed leaving another existing block as the new endpoint.
101 */
102
Raymond Hettinger3223dd52013-07-26 23:14:22 -0700103#ifndef NDEBUG
Raymond Hettinger82df9252013-07-07 01:43:42 -1000104#define MARK_END(link) link = NULL;
105#define CHECK_END(link) assert(link == NULL);
106#define CHECK_NOT_END(link) assert(link != NULL);
107#else
108#define MARK_END(link)
109#define CHECK_END(link)
110#define CHECK_NOT_END(link)
111#endif
112
Raymond Hettinger41290a62015-03-31 08:12:23 -0700113/* To prevent len from overflowing PY_SSIZE_T_MAX, we refuse to
114 allocate new blocks if the current len is nearing overflow.
115*/
116
117#define MAX_DEQUE_LEN (PY_SSIZE_T_MAX - 3*BLOCKLEN)
118
Raymond Hettinger82df9252013-07-07 01:43:42 -1000119/* A simple freelisting scheme is used to minimize calls to the memory
Raymond Hettinger551350a2015-03-24 00:19:53 -0700120 allocator. It accommodates common use cases where new blocks are being
Raymond Hettinger82df9252013-07-07 01:43:42 -1000121 added at about the same rate as old blocks are being freed.
122 */
123
Raymond Hettingerf2b02ce2015-09-26 17:47:02 -0700124#define MAXFREEBLOCKS 16
Benjamin Petersond6313712008-07-31 16:23:04 +0000125static Py_ssize_t numfreeblocks = 0;
Guido van Rossum58da9312007-11-10 23:39:45 +0000126static block *freeblocks[MAXFREEBLOCKS];
127
Tim Peters6f853562004-10-01 01:04:50 +0000128static block *
Raymond Hettinger82df9252013-07-07 01:43:42 -1000129newblock(Py_ssize_t len) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000130 block *b;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700131 if (len >= MAX_DEQUE_LEN) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000132 PyErr_SetString(PyExc_OverflowError,
133 "cannot add more blocks to the deque");
134 return NULL;
135 }
136 if (numfreeblocks) {
Raymond Hettinger59cf23a2013-02-07 00:57:19 -0500137 numfreeblocks--;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000138 return freeblocks[numfreeblocks];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000139 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000140 b = PyMem_Malloc(sizeof(block));
141 if (b != NULL) {
142 return b;
143 }
144 PyErr_NoMemory();
145 return NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000146}
147
Martin v. Löwis59683e82008-06-13 07:50:45 +0000148static void
Guido van Rossum58da9312007-11-10 23:39:45 +0000149freeblock(block *b)
150{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000151 if (numfreeblocks < MAXFREEBLOCKS) {
152 freeblocks[numfreeblocks] = b;
153 numfreeblocks++;
154 } else {
155 PyMem_Free(b);
156 }
Guido van Rossum58da9312007-11-10 23:39:45 +0000157}
158
Raymond Hettingerda2850f2015-02-27 12:42:54 -0800159/* XXX Todo:
Raymond Hettinger54023152014-04-23 00:58:48 -0700160 If aligned memory allocations become available, make the
161 deque object 64 byte aligned so that all of the fields
162 can be retrieved or updated in a single cache line.
163*/
164
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000165static PyObject *
166deque_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
167{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000168 dequeobject *deque;
169 block *b;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000171 /* create dequeobject structure */
172 deque = (dequeobject *)type->tp_alloc(type, 0);
173 if (deque == NULL)
174 return NULL;
Tim Peters1065f752004-10-01 01:03:29 +0000175
Raymond Hettinger82df9252013-07-07 01:43:42 -1000176 b = newblock(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000177 if (b == NULL) {
178 Py_DECREF(deque);
179 return NULL;
180 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000181 MARK_END(b->leftlink);
182 MARK_END(b->rightlink);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000184 assert(BLOCKLEN >= 2);
Raymond Hettinger87e69122015-03-02 23:32:02 -0800185 Py_SIZE(deque) = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000186 deque->leftblock = b;
187 deque->rightblock = b;
188 deque->leftindex = CENTER + 1;
189 deque->rightindex = CENTER;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000190 deque->state = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000191 deque->maxlen = -1;
Raymond Hettinger87e69122015-03-02 23:32:02 -0800192 deque->weakreflist = NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000194 return (PyObject *)deque;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000195}
196
197static PyObject *
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000198deque_pop(dequeobject *deque, PyObject *unused)
199{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000200 PyObject *item;
201 block *prevblock;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000202
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000203 if (Py_SIZE(deque) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000204 PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
205 return NULL;
206 }
207 item = deque->rightblock->data[deque->rightindex];
208 deque->rightindex--;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000209 Py_SIZE(deque)--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000210 deque->state++;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000211
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -0700212 if (deque->rightindex < 0) {
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700213 if (Py_SIZE(deque)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000214 prevblock = deque->rightblock->leftlink;
215 assert(deque->leftblock != deque->rightblock);
216 freeblock(deque->rightblock);
Raymond Hettinger82df9252013-07-07 01:43:42 -1000217 CHECK_NOT_END(prevblock);
218 MARK_END(prevblock->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000219 deque->rightblock = prevblock;
220 deque->rightindex = BLOCKLEN - 1;
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700221 } else {
222 assert(deque->leftblock == deque->rightblock);
223 assert(deque->leftindex == deque->rightindex+1);
224 /* re-center instead of freeing a block */
225 deque->leftindex = CENTER + 1;
226 deque->rightindex = CENTER;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000227 }
228 }
229 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000230}
231
232PyDoc_STRVAR(pop_doc, "Remove and return the rightmost element.");
233
234static PyObject *
235deque_popleft(dequeobject *deque, PyObject *unused)
236{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000237 PyObject *item;
238 block *prevblock;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000239
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000240 if (Py_SIZE(deque) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000241 PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
242 return NULL;
243 }
244 assert(deque->leftblock != NULL);
245 item = deque->leftblock->data[deque->leftindex];
246 deque->leftindex++;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000247 Py_SIZE(deque)--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000248 deque->state++;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000250 if (deque->leftindex == BLOCKLEN) {
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700251 if (Py_SIZE(deque)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000252 assert(deque->leftblock != deque->rightblock);
253 prevblock = deque->leftblock->rightlink;
254 freeblock(deque->leftblock);
Raymond Hettinger82df9252013-07-07 01:43:42 -1000255 CHECK_NOT_END(prevblock);
256 MARK_END(prevblock->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000257 deque->leftblock = prevblock;
258 deque->leftindex = 0;
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700259 } else {
260 assert(deque->leftblock == deque->rightblock);
261 assert(deque->leftindex == deque->rightindex+1);
262 /* re-center instead of freeing a block */
263 deque->leftindex = CENTER + 1;
264 deque->rightindex = CENTER;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000265 }
266 }
267 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000268}
269
270PyDoc_STRVAR(popleft_doc, "Remove and return the leftmost element.");
271
Raymond Hettingerf30f5b92015-03-02 22:23:37 -0800272/* The deque's size limit is d.maxlen. The limit can be zero or positive.
273 * If there is no limit, then d.maxlen == -1.
274 *
275 * After an item is added to a deque, we check to see if the size has grown past
276 * the limit. If it has, we get the size back down to the limit by popping an
277 * item off of the opposite end. The methods that can trigger this are append(),
278 * appendleft(), extend(), and extendleft().
279 */
280
281static void
282deque_trim_right(dequeobject *deque)
283{
Raymond Hettingera7f630092015-10-10 23:56:02 -0400284 if (deque->maxlen >= 0 && Py_SIZE(deque) > deque->maxlen) {
Raymond Hettingerf30f5b92015-03-02 22:23:37 -0800285 PyObject *rv = deque_pop(deque, NULL);
286 assert(rv != NULL);
287 assert(Py_SIZE(deque) <= deque->maxlen);
288 Py_DECREF(rv);
289 }
290}
291
292static void
293deque_trim_left(dequeobject *deque)
294{
Raymond Hettingera7f630092015-10-10 23:56:02 -0400295 if (deque->maxlen >= 0 && Py_SIZE(deque) > deque->maxlen) {
Raymond Hettingerf30f5b92015-03-02 22:23:37 -0800296 PyObject *rv = deque_popleft(deque, NULL);
297 assert(rv != NULL);
298 assert(Py_SIZE(deque) <= deque->maxlen);
299 Py_DECREF(rv);
300 }
301}
302
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000303static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000304deque_append(dequeobject *deque, PyObject *item)
305{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000306 deque->state++;
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700307 if (deque->rightindex == BLOCKLEN - 1) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000308 block *b = newblock(Py_SIZE(deque));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000309 if (b == NULL)
310 return NULL;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000311 b->leftlink = deque->rightblock;
312 CHECK_END(deque->rightblock->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000313 deque->rightblock->rightlink = b;
314 deque->rightblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000315 MARK_END(b->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000316 deque->rightindex = -1;
317 }
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000318 Py_SIZE(deque)++;
Raymond Hettinger7c0b70f2015-09-26 21:11:05 -0700319 Py_INCREF(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000320 deque->rightindex++;
321 deque->rightblock->data[deque->rightindex] = item;
Raymond Hettingerf30f5b92015-03-02 22:23:37 -0800322 deque_trim_left(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000323 Py_RETURN_NONE;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000324}
325
326PyDoc_STRVAR(append_doc, "Add an element to the right side of the deque.");
327
328static PyObject *
329deque_appendleft(dequeobject *deque, PyObject *item)
330{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000331 deque->state++;
332 if (deque->leftindex == 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000333 block *b = newblock(Py_SIZE(deque));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000334 if (b == NULL)
335 return NULL;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000336 b->rightlink = deque->leftblock;
337 CHECK_END(deque->leftblock->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000338 deque->leftblock->leftlink = b;
339 deque->leftblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000340 MARK_END(b->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000341 deque->leftindex = BLOCKLEN;
342 }
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000343 Py_SIZE(deque)++;
Raymond Hettinger7c0b70f2015-09-26 21:11:05 -0700344 Py_INCREF(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000345 deque->leftindex--;
346 deque->leftblock->data[deque->leftindex] = item;
Raymond Hettingerf30f5b92015-03-02 22:23:37 -0800347 deque_trim_right(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000348 Py_RETURN_NONE;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000349}
350
351PyDoc_STRVAR(appendleft_doc, "Add an element to the left side of the deque.");
352
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700353static PyObject*
354finalize_iterator(PyObject *it)
355{
356 if (PyErr_Occurred()) {
357 if (PyErr_ExceptionMatches(PyExc_StopIteration))
358 PyErr_Clear();
359 else {
360 Py_DECREF(it);
361 return NULL;
362 }
363 }
364 Py_DECREF(it);
365 Py_RETURN_NONE;
366}
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000368/* Run an iterator to exhaustion. Shortcut for
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000369 the extend/extendleft methods when maxlen == 0. */
370static PyObject*
371consume_iterator(PyObject *it)
372{
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700373 PyObject *(*iternext)(PyObject *);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000374 PyObject *item;
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000375
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700376 iternext = *Py_TYPE(it)->tp_iternext;
377 while ((item = iternext(it)) != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000378 Py_DECREF(item);
379 }
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700380 return finalize_iterator(it);
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000381}
382
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000383static PyObject *
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000384deque_extend(dequeobject *deque, PyObject *iterable)
385{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000386 PyObject *it, *item;
Raymond Hettinger7a845522015-09-26 01:30:51 -0700387 PyObject *(*iternext)(PyObject *);
Raymond Hettinger6b1e1132015-10-11 09:43:50 -0700388 Py_ssize_t maxlen = deque->maxlen;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000390 /* Handle case where id(deque) == id(iterable) */
391 if ((PyObject *)deque == iterable) {
392 PyObject *result;
393 PyObject *s = PySequence_List(iterable);
394 if (s == NULL)
395 return NULL;
396 result = deque_extend(deque, s);
397 Py_DECREF(s);
398 return result;
399 }
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000400
Raymond Hettingerd9c116c2013-07-09 00:13:21 -0700401 /* Space saving heuristic. Start filling from the left */
402 if (Py_SIZE(deque) == 0) {
403 assert(deque->leftblock == deque->rightblock);
404 assert(deque->leftindex == deque->rightindex+1);
405 deque->leftindex = 1;
406 deque->rightindex = 0;
407 }
408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000409 it = PyObject_GetIter(iterable);
410 if (it == NULL)
411 return NULL;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000413 if (deque->maxlen == 0)
414 return consume_iterator(it);
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000415
Raymond Hettinger7a845522015-09-26 01:30:51 -0700416 iternext = *Py_TYPE(it)->tp_iternext;
417 while ((item = iternext(it)) != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000418 deque->state++;
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700419 if (deque->rightindex == BLOCKLEN - 1) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000420 block *b = newblock(Py_SIZE(deque));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 if (b == NULL) {
422 Py_DECREF(item);
423 Py_DECREF(it);
424 return NULL;
425 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000426 b->leftlink = deque->rightblock;
427 CHECK_END(deque->rightblock->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000428 deque->rightblock->rightlink = b;
429 deque->rightblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000430 MARK_END(b->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 deque->rightindex = -1;
432 }
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000433 Py_SIZE(deque)++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000434 deque->rightindex++;
435 deque->rightblock->data[deque->rightindex] = item;
Raymond Hettinger6b1e1132015-10-11 09:43:50 -0700436 if (maxlen >= 0 && Py_SIZE(deque) > maxlen) {
437 PyObject *rv = deque_popleft(deque, NULL);
438 Py_DECREF(rv);
439 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000440 }
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700441 return finalize_iterator(it);
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000442}
443
Tim Peters1065f752004-10-01 01:03:29 +0000444PyDoc_STRVAR(extend_doc,
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000445"Extend the right side of the deque with elements from the iterable");
446
447static PyObject *
448deque_extendleft(dequeobject *deque, PyObject *iterable)
449{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000450 PyObject *it, *item;
Raymond Hettinger7a845522015-09-26 01:30:51 -0700451 PyObject *(*iternext)(PyObject *);
Raymond Hettinger6b1e1132015-10-11 09:43:50 -0700452 Py_ssize_t maxlen = deque->maxlen;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000454 /* Handle case where id(deque) == id(iterable) */
455 if ((PyObject *)deque == iterable) {
456 PyObject *result;
457 PyObject *s = PySequence_List(iterable);
458 if (s == NULL)
459 return NULL;
460 result = deque_extendleft(deque, s);
461 Py_DECREF(s);
462 return result;
463 }
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000464
Raymond Hettingerd9c116c2013-07-09 00:13:21 -0700465 /* Space saving heuristic. Start filling from the right */
466 if (Py_SIZE(deque) == 0) {
467 assert(deque->leftblock == deque->rightblock);
468 assert(deque->leftindex == deque->rightindex+1);
469 deque->leftindex = BLOCKLEN - 1;
470 deque->rightindex = BLOCKLEN - 2;
471 }
472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000473 it = PyObject_GetIter(iterable);
474 if (it == NULL)
475 return NULL;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000476
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 if (deque->maxlen == 0)
478 return consume_iterator(it);
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000479
Raymond Hettinger7a845522015-09-26 01:30:51 -0700480 iternext = *Py_TYPE(it)->tp_iternext;
481 while ((item = iternext(it)) != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 deque->state++;
483 if (deque->leftindex == 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000484 block *b = newblock(Py_SIZE(deque));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 if (b == NULL) {
486 Py_DECREF(item);
487 Py_DECREF(it);
488 return NULL;
489 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000490 b->rightlink = deque->leftblock;
491 CHECK_END(deque->leftblock->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 deque->leftblock->leftlink = b;
493 deque->leftblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000494 MARK_END(b->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000495 deque->leftindex = BLOCKLEN;
496 }
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000497 Py_SIZE(deque)++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000498 deque->leftindex--;
499 deque->leftblock->data[deque->leftindex] = item;
Raymond Hettinger6b1e1132015-10-11 09:43:50 -0700500 if (maxlen >= 0 && Py_SIZE(deque) > maxlen) {
501 PyObject *rv = deque_pop(deque, NULL);
502 Py_DECREF(rv);
503 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 }
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700505 return finalize_iterator(it);
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000506}
507
Tim Peters1065f752004-10-01 01:03:29 +0000508PyDoc_STRVAR(extendleft_doc,
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000509"Extend the left side of the deque with elements from the iterable");
510
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000511static PyObject *
512deque_inplace_concat(dequeobject *deque, PyObject *other)
513{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000514 PyObject *result;
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 result = deque_extend(deque, other);
517 if (result == NULL)
518 return result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 Py_INCREF(deque);
Raymond Hettinger2b2b7532015-09-05 17:05:52 -0700520 Py_DECREF(result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 return (PyObject *)deque;
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000522}
523
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700524static PyObject *
525deque_copy(PyObject *deque)
526{
527 dequeobject *old_deque = (dequeobject *)deque;
528 if (Py_TYPE(deque) == &deque_type) {
529 dequeobject *new_deque;
530 PyObject *rv;
531
532 new_deque = (dequeobject *)deque_new(&deque_type, (PyObject *)NULL, (PyObject *)NULL);
533 if (new_deque == NULL)
534 return NULL;
535 new_deque->maxlen = old_deque->maxlen;
536 /* Fast path for the deque_repeat() common case where len(deque) == 1 */
Raymond Hettinger0443ac22015-10-05 22:52:37 -0400537 if (Py_SIZE(deque) == 1) {
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700538 PyObject *item = old_deque->leftblock->data[old_deque->leftindex];
539 rv = deque_append(new_deque, item);
540 } else {
541 rv = deque_extend(new_deque, deque);
542 }
543 if (rv != NULL) {
544 Py_DECREF(rv);
545 return (PyObject *)new_deque;
546 }
547 Py_DECREF(new_deque);
548 return NULL;
549 }
550 if (old_deque->maxlen < 0)
551 return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "O", deque, NULL);
552 else
553 return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "Oi",
554 deque, old_deque->maxlen, NULL);
555}
556
557PyDoc_STRVAR(copy_doc, "Return a shallow copy of a deque.");
Raymond Hettinger41290a62015-03-31 08:12:23 -0700558
559static PyObject *
560deque_concat(dequeobject *deque, PyObject *other)
561{
Benjamin Peterson1a629212015-04-04 10:52:36 -0400562 PyObject *new_deque, *result;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700563 int rv;
564
565 rv = PyObject_IsInstance(other, (PyObject *)&deque_type);
566 if (rv <= 0) {
567 if (rv == 0) {
568 PyErr_Format(PyExc_TypeError,
569 "can only concatenate deque (not \"%.200s\") to deque",
570 other->ob_type->tp_name);
571 }
572 return NULL;
573 }
574
575 new_deque = deque_copy((PyObject *)deque);
576 if (new_deque == NULL)
577 return NULL;
Benjamin Peterson1a629212015-04-04 10:52:36 -0400578 result = deque_extend((dequeobject *)new_deque, other);
579 if (result == NULL) {
580 Py_DECREF(new_deque);
581 return NULL;
582 }
583 Py_DECREF(result);
584 return new_deque;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700585}
586
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700587static void
588deque_clear(dequeobject *deque)
589{
590 block *b;
591 block *prevblock;
592 block *leftblock;
593 Py_ssize_t leftindex;
594 Py_ssize_t n;
595 PyObject *item;
596
Raymond Hettinger38031142015-09-29 22:45:05 -0700597 if (Py_SIZE(deque) == 0)
598 return;
599
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700600 /* During the process of clearing a deque, decrefs can cause the
601 deque to mutate. To avoid fatal confusion, we have to make the
602 deque empty before clearing the blocks and never refer to
603 anything via deque->ref while clearing. (This is the same
604 technique used for clearing lists, sets, and dicts.)
605
606 Making the deque empty requires allocating a new empty block. In
607 the unlikely event that memory is full, we fall back to an
608 alternate method that doesn't require a new block. Repeating
609 pops in a while-loop is slower, possibly re-entrant (and a clever
610 adversary could cause it to never terminate).
611 */
612
613 b = newblock(0);
614 if (b == NULL) {
615 PyErr_Clear();
616 goto alternate_method;
617 }
618
619 /* Remember the old size, leftblock, and leftindex */
620 leftblock = deque->leftblock;
621 leftindex = deque->leftindex;
622 n = Py_SIZE(deque);
623
624 /* Set the deque to be empty using the newly allocated block */
625 MARK_END(b->leftlink);
626 MARK_END(b->rightlink);
627 Py_SIZE(deque) = 0;
628 deque->leftblock = b;
629 deque->rightblock = b;
630 deque->leftindex = CENTER + 1;
631 deque->rightindex = CENTER;
632 deque->state++;
633
634 /* Now the old size, leftblock, and leftindex are disconnected from
635 the empty deque and we can use them to decref the pointers.
636 */
637 while (n--) {
638 item = leftblock->data[leftindex];
639 Py_DECREF(item);
640 leftindex++;
641 if (leftindex == BLOCKLEN && n) {
642 CHECK_NOT_END(leftblock->rightlink);
643 prevblock = leftblock;
644 leftblock = leftblock->rightlink;
645 leftindex = 0;
646 freeblock(prevblock);
647 }
648 }
649 CHECK_END(leftblock->rightlink);
650 freeblock(leftblock);
651 return;
652
653 alternate_method:
654 while (Py_SIZE(deque)) {
655 item = deque_pop(deque, NULL);
656 assert (item != NULL);
657 Py_DECREF(item);
658 }
659}
660
661static PyObject *
662deque_clearmethod(dequeobject *deque)
663{
664 deque_clear(deque);
665 Py_RETURN_NONE;
666}
667
668PyDoc_STRVAR(clear_doc, "Remove all elements from the deque.");
Raymond Hettinger41290a62015-03-31 08:12:23 -0700669
670static PyObject *
Raymond Hettinger41290a62015-03-31 08:12:23 -0700671deque_inplace_repeat(dequeobject *deque, Py_ssize_t n)
672{
Raymond Hettingerc22eee62015-09-26 02:14:50 -0700673 Py_ssize_t i, m, size;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700674 PyObject *seq;
675 PyObject *rv;
676
677 size = Py_SIZE(deque);
678 if (size == 0 || n == 1) {
679 Py_INCREF(deque);
680 return (PyObject *)deque;
681 }
682
683 if (n <= 0) {
684 deque_clear(deque);
685 Py_INCREF(deque);
686 return (PyObject *)deque;
687 }
688
Raymond Hettinger41290a62015-03-31 08:12:23 -0700689 if (size == 1) {
690 /* common case, repeating a single element */
691 PyObject *item = deque->leftblock->data[deque->leftindex];
692
Raymond Hettingera7f630092015-10-10 23:56:02 -0400693 if (deque->maxlen >= 0 && n > deque->maxlen)
Raymond Hettinger41290a62015-03-31 08:12:23 -0700694 n = deque->maxlen;
695
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400696 if (n > MAX_DEQUE_LEN)
697 return PyErr_NoMemory();
698
Raymond Hettinger67c78b52015-09-12 11:00:20 -0400699 deque->state++;
Raymond Hettingerad262252015-09-14 01:03:04 -0400700 for (i = 0 ; i < n-1 ; ) {
Raymond Hettinger67c78b52015-09-12 11:00:20 -0400701 if (deque->rightindex == BLOCKLEN - 1) {
702 block *b = newblock(Py_SIZE(deque) + i);
703 if (b == NULL) {
704 Py_SIZE(deque) += i;
705 return NULL;
706 }
707 b->leftlink = deque->rightblock;
708 CHECK_END(deque->rightblock->rightlink);
709 deque->rightblock->rightlink = b;
710 deque->rightblock = b;
711 MARK_END(b->rightlink);
712 deque->rightindex = -1;
713 }
Raymond Hettingerc22eee62015-09-26 02:14:50 -0700714 m = n - 1 - i;
715 if (m > BLOCKLEN - 1 - deque->rightindex)
716 m = BLOCKLEN - 1 - deque->rightindex;
717 i += m;
718 while (m--) {
Raymond Hettingerad262252015-09-14 01:03:04 -0400719 deque->rightindex++;
720 Py_INCREF(item);
721 deque->rightblock->data[deque->rightindex] = item;
722 }
Raymond Hettinger41290a62015-03-31 08:12:23 -0700723 }
Raymond Hettinger67c78b52015-09-12 11:00:20 -0400724 Py_SIZE(deque) += i;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700725 Py_INCREF(deque);
726 return (PyObject *)deque;
727 }
728
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400729 if ((size_t)size > MAX_DEQUE_LEN / (size_t)n) {
730 return PyErr_NoMemory();
731 }
732
Raymond Hettinger41290a62015-03-31 08:12:23 -0700733 seq = PySequence_List((PyObject *)deque);
734 if (seq == NULL)
735 return seq;
736
737 for (i = 0 ; i < n-1 ; i++) {
738 rv = deque_extend(deque, seq);
739 if (rv == NULL) {
740 Py_DECREF(seq);
741 return NULL;
742 }
743 Py_DECREF(rv);
744 }
745 Py_INCREF(deque);
746 Py_DECREF(seq);
747 return (PyObject *)deque;
748}
749
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400750static PyObject *
751deque_repeat(dequeobject *deque, Py_ssize_t n)
752{
753 dequeobject *new_deque;
Raymond Hettinger95e2cc52015-09-13 02:41:18 -0400754 PyObject *rv;
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400755
756 new_deque = (dequeobject *)deque_copy((PyObject *) deque);
757 if (new_deque == NULL)
758 return NULL;
Raymond Hettinger95e2cc52015-09-13 02:41:18 -0400759 rv = deque_inplace_repeat(new_deque, n);
760 Py_DECREF(new_deque);
761 return rv;
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400762}
763
Raymond Hettinger54023152014-04-23 00:58:48 -0700764/* The rotate() method is part of the public API and is used internally
765as a primitive for other methods.
766
767Rotation by 1 or -1 is a common case, so any optimizations for high
768volume rotations should take care not to penalize the common case.
769
770Conceptually, a rotate by one is equivalent to a pop on one side and an
771append on the other. However, a pop/append pair is unnecessarily slow
772because it requires a incref/decref pair for an object located randomly
773in memory. It is better to just move the object pointer from one block
774to the next without changing the reference count.
775
776When moving batches of pointers, it is tempting to use memcpy() but that
777proved to be slower than a simple loop for a variety of reasons.
778Memcpy() cannot know in advance that we're copying pointers instead of
779bytes, that the source and destination are pointer aligned and
780non-overlapping, that moving just one pointer is a common case, that we
781never need to move more than BLOCKLEN pointers, and that at least one
782pointer is always moved.
783
784For high volume rotations, newblock() and freeblock() are never called
785more than once. Previously emptied blocks are immediately reused as a
786destination block. If a block is left-over at the end, it is freed.
787*/
788
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000789static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000790_deque_rotate(dequeobject *deque, Py_ssize_t n)
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000791{
Raymond Hettinger3959af92013-07-13 02:34:08 -0700792 block *b = NULL;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700793 block *leftblock = deque->leftblock;
794 block *rightblock = deque->rightblock;
795 Py_ssize_t leftindex = deque->leftindex;
796 Py_ssize_t rightindex = deque->rightindex;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000797 Py_ssize_t len=Py_SIZE(deque), halflen=len>>1;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700798 int rv = -1;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000799
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800800 if (len <= 1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000801 return 0;
802 if (n > halflen || n < -halflen) {
803 n %= len;
804 if (n > halflen)
805 n -= len;
806 else if (n < -halflen)
807 n += len;
808 }
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500809 assert(len > 1);
Raymond Hettingera4409c12013-02-04 00:08:12 -0500810 assert(-halflen <= n && n <= halflen);
Raymond Hettinger231ee4d2013-02-02 11:24:43 -0800811
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800812 deque->state++;
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500813 while (n > 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700814 if (leftindex == 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700815 if (b == NULL) {
Raymond Hettinger3959af92013-07-13 02:34:08 -0700816 b = newblock(len);
817 if (b == NULL)
818 goto done;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700819 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000820 b->rightlink = leftblock;
821 CHECK_END(leftblock->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700822 leftblock->leftlink = b;
823 leftblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000824 MARK_END(b->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700825 leftindex = BLOCKLEN;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700826 b = NULL;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800827 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700828 assert(leftindex > 0);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700829 {
830 PyObject **src, **dest;
831 Py_ssize_t m = n;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800832
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700833 if (m > rightindex + 1)
834 m = rightindex + 1;
835 if (m > leftindex)
836 m = leftindex;
837 assert (m > 0 && m <= len);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700838 rightindex -= m;
839 leftindex -= m;
Raymond Hettinger0e259f12015-02-01 22:53:41 -0800840 src = &rightblock->data[rightindex + 1];
841 dest = &leftblock->data[leftindex];
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700842 n -= m;
Raymond Hettinger840533b2013-07-13 17:03:58 -0700843 do {
Raymond Hettinger0e259f12015-02-01 22:53:41 -0800844 *(dest++) = *(src++);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700845 } while (--m);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700846 }
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -0700847 if (rightindex < 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700848 assert(leftblock != rightblock);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700849 assert(b == NULL);
Raymond Hettinger3959af92013-07-13 02:34:08 -0700850 b = rightblock;
Raymond Hettingerb97cc492013-07-21 01:51:07 -0700851 CHECK_NOT_END(rightblock->leftlink);
852 rightblock = rightblock->leftlink;
853 MARK_END(rightblock->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700854 rightindex = BLOCKLEN - 1;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800855 }
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800856 }
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500857 while (n < 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700858 if (rightindex == BLOCKLEN - 1) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700859 if (b == NULL) {
Raymond Hettinger3959af92013-07-13 02:34:08 -0700860 b = newblock(len);
861 if (b == NULL)
862 goto done;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700863 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000864 b->leftlink = rightblock;
865 CHECK_END(rightblock->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700866 rightblock->rightlink = b;
867 rightblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000868 MARK_END(b->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700869 rightindex = -1;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700870 b = NULL;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800871 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700872 assert (rightindex < BLOCKLEN - 1);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700873 {
874 PyObject **src, **dest;
875 Py_ssize_t m = -n;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800876
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700877 if (m > BLOCKLEN - leftindex)
878 m = BLOCKLEN - leftindex;
879 if (m > BLOCKLEN - 1 - rightindex)
880 m = BLOCKLEN - 1 - rightindex;
881 assert (m > 0 && m <= len);
882 src = &leftblock->data[leftindex];
883 dest = &rightblock->data[rightindex + 1];
884 leftindex += m;
885 rightindex += m;
886 n += m;
Raymond Hettinger840533b2013-07-13 17:03:58 -0700887 do {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700888 *(dest++) = *(src++);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700889 } while (--m);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700890 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700891 if (leftindex == BLOCKLEN) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700892 assert(leftblock != rightblock);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700893 assert(b == NULL);
Raymond Hettinger3959af92013-07-13 02:34:08 -0700894 b = leftblock;
Raymond Hettingerb97cc492013-07-21 01:51:07 -0700895 CHECK_NOT_END(leftblock->rightlink);
896 leftblock = leftblock->rightlink;
897 MARK_END(leftblock->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700898 leftindex = 0;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800899 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000900 }
Raymond Hettinger3959af92013-07-13 02:34:08 -0700901 rv = 0;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700902done:
Raymond Hettinger3959af92013-07-13 02:34:08 -0700903 if (b != NULL)
904 freeblock(b);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700905 deque->leftblock = leftblock;
906 deque->rightblock = rightblock;
907 deque->leftindex = leftindex;
908 deque->rightindex = rightindex;
909
910 return rv;
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000911}
912
913static PyObject *
914deque_rotate(dequeobject *deque, PyObject *args)
915{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 Py_ssize_t n=1;
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 if (!PyArg_ParseTuple(args, "|n:rotate", &n))
919 return NULL;
Raymond Hettinger6921c132015-03-21 02:03:40 -0700920 if (!_deque_rotate(deque, n))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 Py_RETURN_NONE;
922 return NULL;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000923}
924
Tim Peters1065f752004-10-01 01:03:29 +0000925PyDoc_STRVAR(rotate_doc,
Raymond Hettingeree33b272004-02-08 04:05:26 +0000926"Rotate the deque n steps to the right (default n=1). If n is negative, rotates left.");
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000927
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000928static PyObject *
929deque_reverse(dequeobject *deque, PyObject *unused)
930{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 block *leftblock = deque->leftblock;
932 block *rightblock = deque->rightblock;
933 Py_ssize_t leftindex = deque->leftindex;
934 Py_ssize_t rightindex = deque->rightindex;
Raymond Hettingercfe5b6c2015-07-20 00:25:50 -0400935 Py_ssize_t n = Py_SIZE(deque) >> 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 PyObject *tmp;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000937
Raymond Hettinger7a237232015-09-22 01:20:36 -0700938 while (n-- > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 /* Validate that pointers haven't met in the middle */
940 assert(leftblock != rightblock || leftindex < rightindex);
Raymond Hettinger82df9252013-07-07 01:43:42 -1000941 CHECK_NOT_END(leftblock);
942 CHECK_NOT_END(rightblock);
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000943
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000944 /* Swap */
945 tmp = leftblock->data[leftindex];
946 leftblock->data[leftindex] = rightblock->data[rightindex];
947 rightblock->data[rightindex] = tmp;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 /* Advance left block/index pair */
950 leftindex++;
951 if (leftindex == BLOCKLEN) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 leftblock = leftblock->rightlink;
953 leftindex = 0;
954 }
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000956 /* Step backwards with the right block/index pair */
957 rightindex--;
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -0700958 if (rightindex < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 rightblock = rightblock->leftlink;
960 rightindex = BLOCKLEN - 1;
961 }
962 }
963 Py_RETURN_NONE;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000964}
965
966PyDoc_STRVAR(reverse_doc,
967"D.reverse() -- reverse *IN PLACE*");
968
Raymond Hettinger44459de2010-04-03 23:20:46 +0000969static PyObject *
970deque_count(dequeobject *deque, PyObject *v)
971{
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000972 block *b = deque->leftblock;
973 Py_ssize_t index = deque->leftindex;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000974 Py_ssize_t n = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000975 Py_ssize_t count = 0;
Raymond Hettingerf9d9c792015-03-02 22:47:46 -0800976 size_t start_state = deque->state;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000977 PyObject *item;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 int cmp;
Raymond Hettinger44459de2010-04-03 23:20:46 +0000979
Raymond Hettinger3a1a8d02015-09-23 02:42:02 -0700980 while (n--) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000981 CHECK_NOT_END(b);
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000982 item = b->data[index];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000983 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
Raymond Hettinger2b0d6462015-09-23 19:15:44 -0700984 if (cmp < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000985 return NULL;
Raymond Hettinger2b0d6462015-09-23 19:15:44 -0700986 count += cmp;
Raymond Hettinger44459de2010-04-03 23:20:46 +0000987
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000988 if (start_state != deque->state) {
989 PyErr_SetString(PyExc_RuntimeError,
990 "deque mutated during iteration");
991 return NULL;
992 }
Raymond Hettinger44459de2010-04-03 23:20:46 +0000993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000994 /* Advance left block/index pair */
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000995 index++;
996 if (index == BLOCKLEN) {
997 b = b->rightlink;
998 index = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 }
1000 }
1001 return PyLong_FromSsize_t(count);
Raymond Hettinger44459de2010-04-03 23:20:46 +00001002}
1003
1004PyDoc_STRVAR(count_doc,
1005"D.count(value) -> integer -- return number of occurrences of value");
1006
Raymond Hettinger39dadf72015-03-20 16:38:56 -07001007static int
1008deque_contains(dequeobject *deque, PyObject *v)
1009{
1010 block *b = deque->leftblock;
1011 Py_ssize_t index = deque->leftindex;
1012 Py_ssize_t n = Py_SIZE(deque);
Raymond Hettinger39dadf72015-03-20 16:38:56 -07001013 size_t start_state = deque->state;
1014 PyObject *item;
1015 int cmp;
1016
Raymond Hettinger3a1a8d02015-09-23 02:42:02 -07001017 while (n--) {
Raymond Hettinger39dadf72015-03-20 16:38:56 -07001018 CHECK_NOT_END(b);
1019 item = b->data[index];
1020 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
1021 if (cmp) {
1022 return cmp;
1023 }
1024 if (start_state != deque->state) {
1025 PyErr_SetString(PyExc_RuntimeError,
1026 "deque mutated during iteration");
1027 return -1;
1028 }
1029 index++;
1030 if (index == BLOCKLEN) {
1031 b = b->rightlink;
1032 index = 0;
1033 }
1034 }
1035 return 0;
1036}
1037
Martin v. Löwis18e16552006-02-15 17:27:45 +00001038static Py_ssize_t
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001039deque_len(dequeobject *deque)
1040{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001041 return Py_SIZE(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001042}
1043
Raymond Hettinger4aec61e2005-03-18 21:20:23 +00001044static PyObject *
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001045deque_index(dequeobject *deque, PyObject *args)
1046{
1047 Py_ssize_t i, start=0, stop=Py_SIZE(deque);
1048 PyObject *v, *item;
1049 block *b = deque->leftblock;
1050 Py_ssize_t index = deque->leftindex;
1051 size_t start_state = deque->state;
1052
1053 if (!PyArg_ParseTuple(args, "O|O&O&:index", &v,
1054 _PyEval_SliceIndex, &start,
1055 _PyEval_SliceIndex, &stop))
1056 return NULL;
1057 if (start < 0) {
1058 start += Py_SIZE(deque);
1059 if (start < 0)
1060 start = 0;
1061 }
1062 if (stop < 0) {
1063 stop += Py_SIZE(deque);
1064 if (stop < 0)
1065 stop = 0;
1066 }
Raymond Hettinger87674ec2015-08-26 08:08:38 -07001067 if (stop > Py_SIZE(deque))
1068 stop = Py_SIZE(deque);
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001069
1070 for (i=0 ; i<stop ; i++) {
1071 if (i >= start) {
1072 int cmp;
1073 CHECK_NOT_END(b);
1074 item = b->data[index];
1075 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
1076 if (cmp > 0)
1077 return PyLong_FromSsize_t(i);
1078 else if (cmp < 0)
1079 return NULL;
1080 if (start_state != deque->state) {
1081 PyErr_SetString(PyExc_RuntimeError,
1082 "deque mutated during iteration");
1083 return NULL;
1084 }
1085 }
1086 index++;
1087 if (index == BLOCKLEN) {
1088 b = b->rightlink;
1089 index = 0;
1090 }
1091 }
1092 PyErr_Format(PyExc_ValueError, "%R is not in deque", v);
1093 return NULL;
1094}
1095
1096PyDoc_STRVAR(index_doc,
1097"D.index(value, [start, [stop]]) -> integer -- return first index of value.\n"
1098"Raises ValueError if the value is not present.");
1099
Raymond Hettinger551350a2015-03-24 00:19:53 -07001100/* insert(), remove(), and delitem() are implemented in terms of
1101 rotate() for simplicity and reasonable performance near the end
1102 points. If for some reason these methods become popular, it is not
1103 hard to re-implement this using direct data movement (similar to
1104 the code used in list slice assignments) and achieve a performance
Raymond Hettingerfef9c1b2015-03-24 21:12:57 -07001105 boost (by moving each pointer only once instead of twice).
Raymond Hettinger551350a2015-03-24 00:19:53 -07001106*/
1107
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001108static PyObject *
1109deque_insert(dequeobject *deque, PyObject *args)
1110{
1111 Py_ssize_t index;
1112 Py_ssize_t n = Py_SIZE(deque);
1113 PyObject *value;
1114 PyObject *rv;
1115
1116 if (!PyArg_ParseTuple(args, "nO:insert", &index, &value))
1117 return NULL;
1118 if (index >= n)
1119 return deque_append(deque, value);
1120 if (index <= -n || index == 0)
1121 return deque_appendleft(deque, value);
1122 if (_deque_rotate(deque, -index))
1123 return NULL;
1124 if (index < 0)
1125 rv = deque_append(deque, value);
1126 else
1127 rv = deque_appendleft(deque, value);
1128 if (rv == NULL)
1129 return NULL;
1130 Py_DECREF(rv);
1131 if (_deque_rotate(deque, index))
1132 return NULL;
1133 Py_RETURN_NONE;
1134}
1135
1136PyDoc_STRVAR(insert_doc,
1137"D.insert(index, object) -- insert object before index");
1138
1139static PyObject *
Raymond Hettinger4aec61e2005-03-18 21:20:23 +00001140deque_remove(dequeobject *deque, PyObject *value)
1141{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001142 Py_ssize_t i, n=Py_SIZE(deque);
Raymond Hettinger4aec61e2005-03-18 21:20:23 +00001143
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001144 for (i=0 ; i<n ; i++) {
1145 PyObject *item = deque->leftblock->data[deque->leftindex];
1146 int cmp = PyObject_RichCompareBool(item, value, Py_EQ);
Raymond Hettingerd73202c2005-03-19 00:00:51 +00001147
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001148 if (Py_SIZE(deque) != n) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001149 PyErr_SetString(PyExc_IndexError,
1150 "deque mutated during remove().");
1151 return NULL;
1152 }
1153 if (cmp > 0) {
1154 PyObject *tgt = deque_popleft(deque, NULL);
1155 assert (tgt != NULL);
Raymond Hettinger6921c132015-03-21 02:03:40 -07001156 if (_deque_rotate(deque, i))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001157 return NULL;
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001158 Py_DECREF(tgt);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001159 Py_RETURN_NONE;
1160 }
1161 else if (cmp < 0) {
1162 _deque_rotate(deque, i);
1163 return NULL;
1164 }
1165 _deque_rotate(deque, -1);
1166 }
1167 PyErr_SetString(PyExc_ValueError, "deque.remove(x): x not in deque");
1168 return NULL;
Raymond Hettinger4aec61e2005-03-18 21:20:23 +00001169}
1170
1171PyDoc_STRVAR(remove_doc,
1172"D.remove(value) -- remove first occurrence of value.");
1173
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001174static int
1175valid_index(Py_ssize_t i, Py_ssize_t limit)
1176{
Raymond Hettinger12f896c2015-07-31 12:03:20 -07001177 /* The cast to size_t lets us use just a single comparison
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001178 to check whether i is in the range: 0 <= i < limit */
1179 return (size_t) i < (size_t) limit;
1180}
1181
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001182static PyObject *
Benjamin Petersond6313712008-07-31 16:23:04 +00001183deque_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001184{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001185 block *b;
1186 PyObject *item;
1187 Py_ssize_t n, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001188
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001189 if (!valid_index(i, Py_SIZE(deque))) {
1190 PyErr_SetString(PyExc_IndexError, "deque index out of range");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001191 return NULL;
1192 }
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 if (i == 0) {
1195 i = deque->leftindex;
1196 b = deque->leftblock;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001197 } else if (i == Py_SIZE(deque) - 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001198 i = deque->rightindex;
1199 b = deque->rightblock;
1200 } else {
1201 i += deque->leftindex;
Raymond Hettingerc2083082015-02-28 23:29:16 -08001202 n = (Py_ssize_t)((size_t) i / BLOCKLEN);
1203 i = (Py_ssize_t)((size_t) i % BLOCKLEN);
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001204 if (index < (Py_SIZE(deque) >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001205 b = deque->leftblock;
1206 while (n--)
1207 b = b->rightlink;
1208 } else {
Raymond Hettinger63d1ff22015-02-28 07:41:30 -08001209 n = (Py_ssize_t)(
Raymond Hettingerc2083082015-02-28 23:29:16 -08001210 ((size_t)(deque->leftindex + Py_SIZE(deque) - 1))
Raymond Hettinger63d1ff22015-02-28 07:41:30 -08001211 / BLOCKLEN - n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001212 b = deque->rightblock;
1213 while (n--)
1214 b = b->leftlink;
1215 }
1216 }
1217 item = b->data[i];
1218 Py_INCREF(item);
1219 return item;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001220}
1221
1222static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001223deque_del_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001224{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 PyObject *item;
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001226 int rv;
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001227
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001228 assert (i >= 0 && i < Py_SIZE(deque));
Raymond Hettinger6921c132015-03-21 02:03:40 -07001229 if (_deque_rotate(deque, -i))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001230 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001231 item = deque_popleft(deque, NULL);
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001232 rv = _deque_rotate(deque, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001233 assert (item != NULL);
1234 Py_DECREF(item);
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001235 return rv;
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001236}
1237
1238static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001239deque_ass_item(dequeobject *deque, Py_ssize_t i, PyObject *v)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001240{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001241 PyObject *old_value;
1242 block *b;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001243 Py_ssize_t n, len=Py_SIZE(deque), halflen=(len+1)>>1, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001244
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001245 if (!valid_index(i, len)) {
1246 PyErr_SetString(PyExc_IndexError, "deque index out of range");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001247 return -1;
1248 }
1249 if (v == NULL)
1250 return deque_del_item(deque, i);
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001252 i += deque->leftindex;
Raymond Hettingerc2083082015-02-28 23:29:16 -08001253 n = (Py_ssize_t)((size_t) i / BLOCKLEN);
1254 i = (Py_ssize_t)((size_t) i % BLOCKLEN);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001255 if (index <= halflen) {
1256 b = deque->leftblock;
1257 while (n--)
1258 b = b->rightlink;
1259 } else {
Raymond Hettingera473b9d2015-02-28 17:49:47 -08001260 n = (Py_ssize_t)(
Raymond Hettingerc2083082015-02-28 23:29:16 -08001261 ((size_t)(deque->leftindex + Py_SIZE(deque) - 1))
Raymond Hettingera473b9d2015-02-28 17:49:47 -08001262 / BLOCKLEN - n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 b = deque->rightblock;
1264 while (n--)
1265 b = b->leftlink;
1266 }
1267 Py_INCREF(v);
1268 old_value = b->data[i];
1269 b->data[i] = v;
1270 Py_DECREF(old_value);
1271 return 0;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001272}
1273
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001274static void
1275deque_dealloc(dequeobject *deque)
1276{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001277 PyObject_GC_UnTrack(deque);
1278 if (deque->weakreflist != NULL)
1279 PyObject_ClearWeakRefs((PyObject *) deque);
1280 if (deque->leftblock != NULL) {
1281 deque_clear(deque);
1282 assert(deque->leftblock != NULL);
1283 freeblock(deque->leftblock);
1284 }
1285 deque->leftblock = NULL;
1286 deque->rightblock = NULL;
1287 Py_TYPE(deque)->tp_free(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001288}
1289
1290static int
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001291deque_traverse(dequeobject *deque, visitproc visit, void *arg)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001292{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001293 block *b;
1294 PyObject *item;
1295 Py_ssize_t index;
1296 Py_ssize_t indexlo = deque->leftindex;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001297
Raymond Hettinger5bfa8672013-07-06 11:58:09 -10001298 for (b = deque->leftblock; b != deque->rightblock; b = b->rightlink) {
1299 for (index = indexlo; index < BLOCKLEN ; index++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001300 item = b->data[index];
1301 Py_VISIT(item);
1302 }
1303 indexlo = 0;
1304 }
Raymond Hettinger5bfa8672013-07-06 11:58:09 -10001305 for (index = indexlo; index <= deque->rightindex; index++) {
1306 item = b->data[index];
1307 Py_VISIT(item);
1308 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001309 return 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001310}
1311
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001312static PyObject *
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001313deque_reduce(dequeobject *deque)
1314{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001315 PyObject *dict, *result, *aslist;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001316 _Py_IDENTIFIER(__dict__);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001317
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001318 dict = _PyObject_GetAttrId((PyObject *)deque, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001319 if (dict == NULL)
1320 PyErr_Clear();
1321 aslist = PySequence_List((PyObject *)deque);
1322 if (aslist == NULL) {
1323 Py_XDECREF(dict);
1324 return NULL;
1325 }
1326 if (dict == NULL) {
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -07001327 if (deque->maxlen < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001328 result = Py_BuildValue("O(O)", Py_TYPE(deque), aslist);
1329 else
1330 result = Py_BuildValue("O(On)", Py_TYPE(deque), aslist, deque->maxlen);
1331 } else {
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -07001332 if (deque->maxlen < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001333 result = Py_BuildValue("O(OO)O", Py_TYPE(deque), aslist, Py_None, dict);
1334 else
1335 result = Py_BuildValue("O(On)O", Py_TYPE(deque), aslist, deque->maxlen, dict);
1336 }
1337 Py_XDECREF(dict);
1338 Py_DECREF(aslist);
1339 return result;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001340}
1341
1342PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
1343
1344static PyObject *
1345deque_repr(PyObject *deque)
1346{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001347 PyObject *aslist, *result;
1348 int i;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001350 i = Py_ReprEnter(deque);
1351 if (i != 0) {
1352 if (i < 0)
1353 return NULL;
1354 return PyUnicode_FromString("[...]");
1355 }
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001357 aslist = PySequence_List(deque);
1358 if (aslist == NULL) {
1359 Py_ReprLeave(deque);
1360 return NULL;
1361 }
Raymond Hettingera7f630092015-10-10 23:56:02 -04001362 if (((dequeobject *)deque)->maxlen >= 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001363 result = PyUnicode_FromFormat("deque(%R, maxlen=%zd)",
1364 aslist, ((dequeobject *)deque)->maxlen);
1365 else
1366 result = PyUnicode_FromFormat("deque(%R)", aslist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001367 Py_ReprLeave(deque);
Raymond Hettinger2b2b7532015-09-05 17:05:52 -07001368 Py_DECREF(aslist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001369 return result;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001370}
1371
Raymond Hettinger738ec902004-02-29 02:15:56 +00001372static PyObject *
1373deque_richcompare(PyObject *v, PyObject *w, int op)
1374{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001375 PyObject *it1=NULL, *it2=NULL, *x, *y;
1376 Py_ssize_t vs, ws;
1377 int b, cmp=-1;
Raymond Hettinger738ec902004-02-29 02:15:56 +00001378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001379 if (!PyObject_TypeCheck(v, &deque_type) ||
1380 !PyObject_TypeCheck(w, &deque_type)) {
Brian Curtindfc80e32011-08-10 20:28:54 -05001381 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001382 }
Raymond Hettinger738ec902004-02-29 02:15:56 +00001383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001384 /* Shortcuts */
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001385 vs = Py_SIZE((dequeobject *)v);
1386 ws = Py_SIZE((dequeobject *)w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001387 if (op == Py_EQ) {
1388 if (v == w)
1389 Py_RETURN_TRUE;
1390 if (vs != ws)
1391 Py_RETURN_FALSE;
1392 }
1393 if (op == Py_NE) {
1394 if (v == w)
1395 Py_RETURN_FALSE;
1396 if (vs != ws)
1397 Py_RETURN_TRUE;
1398 }
Raymond Hettinger738ec902004-02-29 02:15:56 +00001399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001400 /* Search for the first index where items are different */
1401 it1 = PyObject_GetIter(v);
1402 if (it1 == NULL)
1403 goto done;
1404 it2 = PyObject_GetIter(w);
1405 if (it2 == NULL)
1406 goto done;
1407 for (;;) {
1408 x = PyIter_Next(it1);
1409 if (x == NULL && PyErr_Occurred())
1410 goto done;
1411 y = PyIter_Next(it2);
1412 if (x == NULL || y == NULL)
1413 break;
1414 b = PyObject_RichCompareBool(x, y, Py_EQ);
1415 if (b == 0) {
1416 cmp = PyObject_RichCompareBool(x, y, op);
1417 Py_DECREF(x);
1418 Py_DECREF(y);
1419 goto done;
1420 }
1421 Py_DECREF(x);
1422 Py_DECREF(y);
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -07001423 if (b < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001424 goto done;
1425 }
1426 /* We reached the end of one deque or both */
1427 Py_XDECREF(x);
1428 Py_XDECREF(y);
1429 if (PyErr_Occurred())
1430 goto done;
1431 switch (op) {
1432 case Py_LT: cmp = y != NULL; break; /* if w was longer */
1433 case Py_LE: cmp = x == NULL; break; /* if v was not longer */
1434 case Py_EQ: cmp = x == y; break; /* if we reached the end of both */
1435 case Py_NE: cmp = x != y; break; /* if one deque continues */
1436 case Py_GT: cmp = x != NULL; break; /* if v was longer */
1437 case Py_GE: cmp = y == NULL; break; /* if w was not longer */
1438 }
Tim Peters1065f752004-10-01 01:03:29 +00001439
Raymond Hettinger738ec902004-02-29 02:15:56 +00001440done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001441 Py_XDECREF(it1);
1442 Py_XDECREF(it2);
1443 if (cmp == 1)
1444 Py_RETURN_TRUE;
1445 if (cmp == 0)
1446 Py_RETURN_FALSE;
1447 return NULL;
Raymond Hettinger738ec902004-02-29 02:15:56 +00001448}
1449
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001450static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001451deque_init(dequeobject *deque, PyObject *args, PyObject *kwdargs)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001452{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001453 PyObject *iterable = NULL;
1454 PyObject *maxlenobj = NULL;
1455 Py_ssize_t maxlen = -1;
1456 char *kwlist[] = {"iterable", "maxlen", 0};
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001457
Raymond Hettinger0d309402015-09-30 23:15:02 -07001458 if (kwdargs == NULL) {
1459 if (!PyArg_UnpackTuple(args, "deque()", 0, 2, &iterable, &maxlenobj))
1460 return -1;
1461 } else {
1462 if (!PyArg_ParseTupleAndKeywords(args, kwdargs, "|OO:deque", kwlist,
1463 &iterable, &maxlenobj))
1464 return -1;
1465 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001466 if (maxlenobj != NULL && maxlenobj != Py_None) {
1467 maxlen = PyLong_AsSsize_t(maxlenobj);
1468 if (maxlen == -1 && PyErr_Occurred())
1469 return -1;
1470 if (maxlen < 0) {
1471 PyErr_SetString(PyExc_ValueError, "maxlen must be non-negative");
1472 return -1;
1473 }
1474 }
1475 deque->maxlen = maxlen;
Raymond Hettinger0d309402015-09-30 23:15:02 -07001476 if (Py_SIZE(deque) > 0)
1477 deque_clear(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001478 if (iterable != NULL) {
1479 PyObject *rv = deque_extend(deque, iterable);
1480 if (rv == NULL)
1481 return -1;
1482 Py_DECREF(rv);
1483 }
1484 return 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001485}
1486
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001487static PyObject *
Jesus Cea16e2fca2012-08-03 14:49:42 +02001488deque_sizeof(dequeobject *deque, void *unused)
1489{
1490 Py_ssize_t res;
1491 Py_ssize_t blocks;
1492
1493 res = sizeof(dequeobject);
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001494 blocks = (deque->leftindex + Py_SIZE(deque) + BLOCKLEN - 1) / BLOCKLEN;
1495 assert(deque->leftindex + Py_SIZE(deque) - 1 ==
Jesus Cea16e2fca2012-08-03 14:49:42 +02001496 (blocks - 1) * BLOCKLEN + deque->rightindex);
1497 res += blocks * sizeof(block);
1498 return PyLong_FromSsize_t(res);
1499}
1500
1501PyDoc_STRVAR(sizeof_doc,
1502"D.__sizeof__() -- size of D in memory, in bytes");
1503
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001504static int
1505deque_bool(dequeobject *deque)
1506{
1507 return Py_SIZE(deque) != 0;
1508}
1509
Jesus Cea16e2fca2012-08-03 14:49:42 +02001510static PyObject *
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001511deque_get_maxlen(dequeobject *deque)
1512{
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -07001513 if (deque->maxlen < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001514 Py_RETURN_NONE;
1515 return PyLong_FromSsize_t(deque->maxlen);
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001516}
1517
Raymond Hettinger41290a62015-03-31 08:12:23 -07001518
1519/* deque object ********************************************************/
1520
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001521static PyGetSetDef deque_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001522 {"maxlen", (getter)deque_get_maxlen, (setter)NULL,
1523 "maximum size of a deque or None if unbounded"},
1524 {0}
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001525};
1526
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001527static PySequenceMethods deque_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001528 (lenfunc)deque_len, /* sq_length */
Raymond Hettinger41290a62015-03-31 08:12:23 -07001529 (binaryfunc)deque_concat, /* sq_concat */
1530 (ssizeargfunc)deque_repeat, /* sq_repeat */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001531 (ssizeargfunc)deque_item, /* sq_item */
1532 0, /* sq_slice */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001533 (ssizeobjargproc)deque_ass_item, /* sq_ass_item */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001534 0, /* sq_ass_slice */
Raymond Hettinger39dadf72015-03-20 16:38:56 -07001535 (objobjproc)deque_contains, /* sq_contains */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001536 (binaryfunc)deque_inplace_concat, /* sq_inplace_concat */
Raymond Hettinger41290a62015-03-31 08:12:23 -07001537 (ssizeargfunc)deque_inplace_repeat, /* sq_inplace_repeat */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001538};
1539
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001540static PyNumberMethods deque_as_number = {
1541 0, /* nb_add */
1542 0, /* nb_subtract */
1543 0, /* nb_multiply */
1544 0, /* nb_remainder */
1545 0, /* nb_divmod */
1546 0, /* nb_power */
1547 0, /* nb_negative */
1548 0, /* nb_positive */
1549 0, /* nb_absolute */
1550 (inquiry)deque_bool, /* nb_bool */
1551 0, /* nb_invert */
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001552 };
1553
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001554static PyObject *deque_iter(dequeobject *deque);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001555static PyObject *deque_reviter(dequeobject *deque);
Tim Peters1065f752004-10-01 01:03:29 +00001556PyDoc_STRVAR(reversed_doc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001557 "D.__reversed__() -- return a reverse iterator over the deque");
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001558
1559static PyMethodDef deque_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001560 {"append", (PyCFunction)deque_append,
1561 METH_O, append_doc},
1562 {"appendleft", (PyCFunction)deque_appendleft,
1563 METH_O, appendleft_doc},
1564 {"clear", (PyCFunction)deque_clearmethod,
1565 METH_NOARGS, clear_doc},
1566 {"__copy__", (PyCFunction)deque_copy,
1567 METH_NOARGS, copy_doc},
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001568 {"copy", (PyCFunction)deque_copy,
1569 METH_NOARGS, copy_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001570 {"count", (PyCFunction)deque_count,
Raymond Hettinger0f6f9472015-03-21 01:42:10 -07001571 METH_O, count_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001572 {"extend", (PyCFunction)deque_extend,
1573 METH_O, extend_doc},
1574 {"extendleft", (PyCFunction)deque_extendleft,
1575 METH_O, extendleft_doc},
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001576 {"index", (PyCFunction)deque_index,
1577 METH_VARARGS, index_doc},
1578 {"insert", (PyCFunction)deque_insert,
1579 METH_VARARGS, insert_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001580 {"pop", (PyCFunction)deque_pop,
1581 METH_NOARGS, pop_doc},
1582 {"popleft", (PyCFunction)deque_popleft,
1583 METH_NOARGS, popleft_doc},
Raymond Hettinger0f6f9472015-03-21 01:42:10 -07001584 {"__reduce__", (PyCFunction)deque_reduce,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001585 METH_NOARGS, reduce_doc},
1586 {"remove", (PyCFunction)deque_remove,
1587 METH_O, remove_doc},
1588 {"__reversed__", (PyCFunction)deque_reviter,
1589 METH_NOARGS, reversed_doc},
1590 {"reverse", (PyCFunction)deque_reverse,
1591 METH_NOARGS, reverse_doc},
1592 {"rotate", (PyCFunction)deque_rotate,
Jesus Cea16e2fca2012-08-03 14:49:42 +02001593 METH_VARARGS, rotate_doc},
1594 {"__sizeof__", (PyCFunction)deque_sizeof,
1595 METH_NOARGS, sizeof_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001596 {NULL, NULL} /* sentinel */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001597};
1598
1599PyDoc_STRVAR(deque_doc,
Andrew Svetlov6a5c7c32012-10-31 11:50:40 +02001600"deque([iterable[, maxlen]]) --> deque object\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001601\n\
Raymond Hettinger41290a62015-03-31 08:12:23 -07001602A list-like sequence optimized for data accesses near its endpoints.");
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001603
Neal Norwitz87f10132004-02-29 15:40:53 +00001604static PyTypeObject deque_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001605 PyVarObject_HEAD_INIT(NULL, 0)
1606 "collections.deque", /* tp_name */
1607 sizeof(dequeobject), /* tp_basicsize */
1608 0, /* tp_itemsize */
1609 /* methods */
1610 (destructor)deque_dealloc, /* tp_dealloc */
1611 0, /* tp_print */
1612 0, /* tp_getattr */
1613 0, /* tp_setattr */
1614 0, /* tp_reserved */
1615 deque_repr, /* tp_repr */
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001616 &deque_as_number, /* tp_as_number */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001617 &deque_as_sequence, /* tp_as_sequence */
1618 0, /* tp_as_mapping */
Georg Brandlf038b322010-10-18 07:35:09 +00001619 PyObject_HashNotImplemented, /* tp_hash */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001620 0, /* tp_call */
1621 0, /* tp_str */
1622 PyObject_GenericGetAttr, /* tp_getattro */
1623 0, /* tp_setattro */
1624 0, /* tp_as_buffer */
1625 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
Georg Brandlf038b322010-10-18 07:35:09 +00001626 /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001627 deque_doc, /* tp_doc */
1628 (traverseproc)deque_traverse, /* tp_traverse */
1629 (inquiry)deque_clear, /* tp_clear */
1630 (richcmpfunc)deque_richcompare, /* tp_richcompare */
Georg Brandlf038b322010-10-18 07:35:09 +00001631 offsetof(dequeobject, weakreflist), /* tp_weaklistoffset*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001632 (getiterfunc)deque_iter, /* tp_iter */
1633 0, /* tp_iternext */
1634 deque_methods, /* tp_methods */
1635 0, /* tp_members */
Georg Brandlf038b322010-10-18 07:35:09 +00001636 deque_getset, /* tp_getset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001637 0, /* tp_base */
1638 0, /* tp_dict */
1639 0, /* tp_descr_get */
1640 0, /* tp_descr_set */
1641 0, /* tp_dictoffset */
1642 (initproc)deque_init, /* tp_init */
1643 PyType_GenericAlloc, /* tp_alloc */
1644 deque_new, /* tp_new */
1645 PyObject_GC_Del, /* tp_free */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001646};
1647
1648/*********************** Deque Iterator **************************/
1649
1650typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001651 PyObject_HEAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001652 block *b;
Raymond Hettinger87e69122015-03-02 23:32:02 -08001653 Py_ssize_t index;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001654 dequeobject *deque;
Raymond Hettingerf9d9c792015-03-02 22:47:46 -08001655 size_t state; /* state when the iterator is created */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001656 Py_ssize_t counter; /* number of items remaining for iteration */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001657} dequeiterobject;
1658
Martin v. Löwis59683e82008-06-13 07:50:45 +00001659static PyTypeObject dequeiter_type;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001660
1661static PyObject *
1662deque_iter(dequeobject *deque)
1663{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001664 dequeiterobject *it;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001665
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001666 it = PyObject_GC_New(dequeiterobject, &dequeiter_type);
1667 if (it == NULL)
1668 return NULL;
1669 it->b = deque->leftblock;
1670 it->index = deque->leftindex;
1671 Py_INCREF(deque);
1672 it->deque = deque;
1673 it->state = deque->state;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001674 it->counter = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001675 PyObject_GC_Track(it);
1676 return (PyObject *)it;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001677}
1678
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001679static int
1680dequeiter_traverse(dequeiterobject *dio, visitproc visit, void *arg)
1681{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001682 Py_VISIT(dio->deque);
1683 return 0;
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001684}
1685
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001686static void
1687dequeiter_dealloc(dequeiterobject *dio)
1688{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001689 Py_XDECREF(dio->deque);
1690 PyObject_GC_Del(dio);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001691}
1692
1693static PyObject *
1694dequeiter_next(dequeiterobject *it)
1695{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001696 PyObject *item;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001697
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001698 if (it->deque->state != it->state) {
1699 it->counter = 0;
1700 PyErr_SetString(PyExc_RuntimeError,
1701 "deque mutated during iteration");
1702 return NULL;
1703 }
1704 if (it->counter == 0)
1705 return NULL;
1706 assert (!(it->b == it->deque->rightblock &&
1707 it->index > it->deque->rightindex));
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001709 item = it->b->data[it->index];
1710 it->index++;
1711 it->counter--;
1712 if (it->index == BLOCKLEN && it->counter > 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -10001713 CHECK_NOT_END(it->b->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001714 it->b = it->b->rightlink;
1715 it->index = 0;
1716 }
1717 Py_INCREF(item);
1718 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001719}
1720
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001721static PyObject *
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001722dequeiter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1723{
1724 Py_ssize_t i, index=0;
1725 PyObject *deque;
1726 dequeiterobject *it;
1727 if (!PyArg_ParseTuple(args, "O!|n", &deque_type, &deque, &index))
1728 return NULL;
1729 assert(type == &dequeiter_type);
1730
1731 it = (dequeiterobject*)deque_iter((dequeobject *)deque);
1732 if (!it)
1733 return NULL;
1734 /* consume items from the queue */
1735 for(i=0; i<index; i++) {
1736 PyObject *item = dequeiter_next(it);
1737 if (item) {
1738 Py_DECREF(item);
1739 } else {
1740 if (it->counter) {
1741 Py_DECREF(it);
1742 return NULL;
1743 } else
1744 break;
1745 }
1746 }
1747 return (PyObject*)it;
1748}
1749
1750static PyObject *
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001751dequeiter_len(dequeiterobject *it)
1752{
Antoine Pitrou554f3342010-08-17 18:30:06 +00001753 return PyLong_FromSsize_t(it->counter);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001754}
1755
Armin Rigof5b3e362006-02-11 21:32:43 +00001756PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001757
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001758static PyObject *
1759dequeiter_reduce(dequeiterobject *it)
1760{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001761 return Py_BuildValue("O(On)", Py_TYPE(it), it->deque, Py_SIZE(it->deque) - it->counter);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001762}
1763
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001764static PyMethodDef dequeiter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001765 {"__length_hint__", (PyCFunction)dequeiter_len, METH_NOARGS, length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001766 {"__reduce__", (PyCFunction)dequeiter_reduce, METH_NOARGS, reduce_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001767 {NULL, NULL} /* sentinel */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001768};
1769
Martin v. Löwis59683e82008-06-13 07:50:45 +00001770static PyTypeObject dequeiter_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001771 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger87e69122015-03-02 23:32:02 -08001772 "_collections._deque_iterator", /* tp_name */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001773 sizeof(dequeiterobject), /* tp_basicsize */
1774 0, /* tp_itemsize */
1775 /* methods */
1776 (destructor)dequeiter_dealloc, /* tp_dealloc */
1777 0, /* tp_print */
1778 0, /* tp_getattr */
1779 0, /* tp_setattr */
1780 0, /* tp_reserved */
1781 0, /* tp_repr */
1782 0, /* tp_as_number */
1783 0, /* tp_as_sequence */
1784 0, /* tp_as_mapping */
1785 0, /* tp_hash */
1786 0, /* tp_call */
1787 0, /* tp_str */
1788 PyObject_GenericGetAttr, /* tp_getattro */
1789 0, /* tp_setattro */
1790 0, /* tp_as_buffer */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001791 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001792 0, /* tp_doc */
1793 (traverseproc)dequeiter_traverse, /* tp_traverse */
1794 0, /* tp_clear */
1795 0, /* tp_richcompare */
1796 0, /* tp_weaklistoffset */
1797 PyObject_SelfIter, /* tp_iter */
1798 (iternextfunc)dequeiter_next, /* tp_iternext */
1799 dequeiter_methods, /* tp_methods */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001800 0, /* tp_members */
1801 0, /* tp_getset */
1802 0, /* tp_base */
1803 0, /* tp_dict */
1804 0, /* tp_descr_get */
1805 0, /* tp_descr_set */
1806 0, /* tp_dictoffset */
1807 0, /* tp_init */
1808 0, /* tp_alloc */
1809 dequeiter_new, /* tp_new */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001810 0,
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001811};
1812
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001813/*********************** Deque Reverse Iterator **************************/
1814
Martin v. Löwis59683e82008-06-13 07:50:45 +00001815static PyTypeObject dequereviter_type;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001816
1817static PyObject *
1818deque_reviter(dequeobject *deque)
1819{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001820 dequeiterobject *it;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001821
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001822 it = PyObject_GC_New(dequeiterobject, &dequereviter_type);
1823 if (it == NULL)
1824 return NULL;
1825 it->b = deque->rightblock;
1826 it->index = deque->rightindex;
1827 Py_INCREF(deque);
1828 it->deque = deque;
1829 it->state = deque->state;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001830 it->counter = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001831 PyObject_GC_Track(it);
1832 return (PyObject *)it;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001833}
1834
1835static PyObject *
1836dequereviter_next(dequeiterobject *it)
1837{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001838 PyObject *item;
1839 if (it->counter == 0)
1840 return NULL;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001841
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001842 if (it->deque->state != it->state) {
1843 it->counter = 0;
1844 PyErr_SetString(PyExc_RuntimeError,
1845 "deque mutated during iteration");
1846 return NULL;
1847 }
1848 assert (!(it->b == it->deque->leftblock &&
1849 it->index < it->deque->leftindex));
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001850
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001851 item = it->b->data[it->index];
1852 it->index--;
1853 it->counter--;
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -07001854 if (it->index < 0 && it->counter > 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -10001855 CHECK_NOT_END(it->b->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001856 it->b = it->b->leftlink;
1857 it->index = BLOCKLEN - 1;
1858 }
1859 Py_INCREF(item);
1860 return item;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001861}
1862
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001863static PyObject *
1864dequereviter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1865{
1866 Py_ssize_t i, index=0;
1867 PyObject *deque;
1868 dequeiterobject *it;
1869 if (!PyArg_ParseTuple(args, "O!|n", &deque_type, &deque, &index))
1870 return NULL;
1871 assert(type == &dequereviter_type);
1872
1873 it = (dequeiterobject*)deque_reviter((dequeobject *)deque);
1874 if (!it)
1875 return NULL;
1876 /* consume items from the queue */
1877 for(i=0; i<index; i++) {
1878 PyObject *item = dequereviter_next(it);
1879 if (item) {
1880 Py_DECREF(item);
1881 } else {
1882 if (it->counter) {
1883 Py_DECREF(it);
1884 return NULL;
1885 } else
1886 break;
1887 }
1888 }
1889 return (PyObject*)it;
1890}
1891
Martin v. Löwis59683e82008-06-13 07:50:45 +00001892static PyTypeObject dequereviter_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001893 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger87e69122015-03-02 23:32:02 -08001894 "_collections._deque_reverse_iterator", /* tp_name */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001895 sizeof(dequeiterobject), /* tp_basicsize */
1896 0, /* tp_itemsize */
1897 /* methods */
1898 (destructor)dequeiter_dealloc, /* tp_dealloc */
1899 0, /* tp_print */
1900 0, /* tp_getattr */
1901 0, /* tp_setattr */
1902 0, /* tp_reserved */
1903 0, /* tp_repr */
1904 0, /* tp_as_number */
1905 0, /* tp_as_sequence */
1906 0, /* tp_as_mapping */
1907 0, /* tp_hash */
1908 0, /* tp_call */
1909 0, /* tp_str */
1910 PyObject_GenericGetAttr, /* tp_getattro */
1911 0, /* tp_setattro */
1912 0, /* tp_as_buffer */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001913 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001914 0, /* tp_doc */
1915 (traverseproc)dequeiter_traverse, /* tp_traverse */
1916 0, /* tp_clear */
1917 0, /* tp_richcompare */
1918 0, /* tp_weaklistoffset */
1919 PyObject_SelfIter, /* tp_iter */
1920 (iternextfunc)dequereviter_next, /* tp_iternext */
1921 dequeiter_methods, /* tp_methods */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001922 0, /* tp_members */
1923 0, /* tp_getset */
1924 0, /* tp_base */
1925 0, /* tp_dict */
1926 0, /* tp_descr_get */
1927 0, /* tp_descr_set */
1928 0, /* tp_dictoffset */
1929 0, /* tp_init */
1930 0, /* tp_alloc */
1931 dequereviter_new, /* tp_new */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001932 0,
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001933};
1934
Guido van Rossum1968ad32006-02-25 22:38:04 +00001935/* defaultdict type *********************************************************/
1936
1937typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001938 PyDictObject dict;
1939 PyObject *default_factory;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001940} defdictobject;
1941
1942static PyTypeObject defdict_type; /* Forward */
1943
1944PyDoc_STRVAR(defdict_missing_doc,
1945"__missing__(key) # Called by __getitem__ for missing key; pseudo-code:\n\
Guido van Rossumd8faa362007-04-27 19:54:29 +00001946 if self.default_factory is None: raise KeyError((key,))\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00001947 self[key] = value = self.default_factory()\n\
1948 return value\n\
1949");
1950
1951static PyObject *
1952defdict_missing(defdictobject *dd, PyObject *key)
1953{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001954 PyObject *factory = dd->default_factory;
1955 PyObject *value;
1956 if (factory == NULL || factory == Py_None) {
1957 /* XXX Call dict.__missing__(key) */
1958 PyObject *tup;
1959 tup = PyTuple_Pack(1, key);
1960 if (!tup) return NULL;
1961 PyErr_SetObject(PyExc_KeyError, tup);
1962 Py_DECREF(tup);
1963 return NULL;
1964 }
1965 value = PyEval_CallObject(factory, NULL);
1966 if (value == NULL)
1967 return value;
1968 if (PyObject_SetItem((PyObject *)dd, key, value) < 0) {
1969 Py_DECREF(value);
1970 return NULL;
1971 }
1972 return value;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001973}
1974
1975PyDoc_STRVAR(defdict_copy_doc, "D.copy() -> a shallow copy of D.");
1976
1977static PyObject *
1978defdict_copy(defdictobject *dd)
1979{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001980 /* This calls the object's class. That only works for subclasses
1981 whose class constructor has the same signature. Subclasses that
1982 define a different constructor signature must override copy().
1983 */
Raymond Hettinger54628fa2009-08-04 19:16:39 +00001984
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001985 if (dd->default_factory == NULL)
1986 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd), Py_None, dd, NULL);
1987 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd),
1988 dd->default_factory, dd, NULL);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001989}
1990
1991static PyObject *
1992defdict_reduce(defdictobject *dd)
1993{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001994 /* __reduce__ must return a 5-tuple as follows:
Guido van Rossum1968ad32006-02-25 22:38:04 +00001995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001996 - factory function
1997 - tuple of args for the factory function
1998 - additional state (here None)
1999 - sequence iterator (here None)
2000 - dictionary iterator (yielding successive (key, value) pairs
Guido van Rossum1968ad32006-02-25 22:38:04 +00002001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002002 This API is used by pickle.py and copy.py.
Guido van Rossum1968ad32006-02-25 22:38:04 +00002003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002004 For this to be useful with pickle.py, the default_factory
2005 must be picklable; e.g., None, a built-in, or a global
2006 function in a module or package.
Guido van Rossum1968ad32006-02-25 22:38:04 +00002007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002008 Both shallow and deep copying are supported, but for deep
2009 copying, the default_factory must be deep-copyable; e.g. None,
2010 or a built-in (functions are not copyable at this time).
Guido van Rossum1968ad32006-02-25 22:38:04 +00002011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002012 This only works for subclasses as long as their constructor
2013 signature is compatible; the first argument must be the
2014 optional default_factory, defaulting to None.
2015 */
2016 PyObject *args;
2017 PyObject *items;
2018 PyObject *iter;
2019 PyObject *result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002020 _Py_IDENTIFIER(items);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002022 if (dd->default_factory == NULL || dd->default_factory == Py_None)
2023 args = PyTuple_New(0);
2024 else
2025 args = PyTuple_Pack(1, dd->default_factory);
2026 if (args == NULL)
2027 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002028 items = _PyObject_CallMethodId((PyObject *)dd, &PyId_items, "()");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002029 if (items == NULL) {
2030 Py_DECREF(args);
2031 return NULL;
2032 }
2033 iter = PyObject_GetIter(items);
2034 if (iter == NULL) {
2035 Py_DECREF(items);
2036 Py_DECREF(args);
2037 return NULL;
2038 }
2039 result = PyTuple_Pack(5, Py_TYPE(dd), args,
2040 Py_None, Py_None, iter);
2041 Py_DECREF(iter);
2042 Py_DECREF(items);
2043 Py_DECREF(args);
2044 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00002045}
2046
2047static PyMethodDef defdict_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002048 {"__missing__", (PyCFunction)defdict_missing, METH_O,
2049 defdict_missing_doc},
2050 {"copy", (PyCFunction)defdict_copy, METH_NOARGS,
2051 defdict_copy_doc},
2052 {"__copy__", (PyCFunction)defdict_copy, METH_NOARGS,
2053 defdict_copy_doc},
2054 {"__reduce__", (PyCFunction)defdict_reduce, METH_NOARGS,
2055 reduce_doc},
2056 {NULL}
Guido van Rossum1968ad32006-02-25 22:38:04 +00002057};
2058
2059static PyMemberDef defdict_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002060 {"default_factory", T_OBJECT,
2061 offsetof(defdictobject, default_factory), 0,
2062 PyDoc_STR("Factory for default value called by __missing__().")},
2063 {NULL}
Guido van Rossum1968ad32006-02-25 22:38:04 +00002064};
2065
2066static void
2067defdict_dealloc(defdictobject *dd)
2068{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002069 Py_CLEAR(dd->default_factory);
2070 PyDict_Type.tp_dealloc((PyObject *)dd);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002071}
2072
Guido van Rossum1968ad32006-02-25 22:38:04 +00002073static PyObject *
2074defdict_repr(defdictobject *dd)
2075{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002076 PyObject *baserepr;
2077 PyObject *defrepr;
2078 PyObject *result;
2079 baserepr = PyDict_Type.tp_repr((PyObject *)dd);
2080 if (baserepr == NULL)
2081 return NULL;
2082 if (dd->default_factory == NULL)
2083 defrepr = PyUnicode_FromString("None");
2084 else
2085 {
2086 int status = Py_ReprEnter(dd->default_factory);
2087 if (status != 0) {
Antoine Pitrouf5f1fe02012-02-15 02:42:46 +01002088 if (status < 0) {
2089 Py_DECREF(baserepr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002090 return NULL;
Antoine Pitrouf5f1fe02012-02-15 02:42:46 +01002091 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002092 defrepr = PyUnicode_FromString("...");
2093 }
2094 else
2095 defrepr = PyObject_Repr(dd->default_factory);
2096 Py_ReprLeave(dd->default_factory);
2097 }
2098 if (defrepr == NULL) {
2099 Py_DECREF(baserepr);
2100 return NULL;
2101 }
2102 result = PyUnicode_FromFormat("defaultdict(%U, %U)",
2103 defrepr, baserepr);
2104 Py_DECREF(defrepr);
2105 Py_DECREF(baserepr);
2106 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00002107}
2108
2109static int
2110defdict_traverse(PyObject *self, visitproc visit, void *arg)
2111{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002112 Py_VISIT(((defdictobject *)self)->default_factory);
2113 return PyDict_Type.tp_traverse(self, visit, arg);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002114}
2115
2116static int
2117defdict_tp_clear(defdictobject *dd)
2118{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002119 Py_CLEAR(dd->default_factory);
2120 return PyDict_Type.tp_clear((PyObject *)dd);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002121}
2122
2123static int
2124defdict_init(PyObject *self, PyObject *args, PyObject *kwds)
2125{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002126 defdictobject *dd = (defdictobject *)self;
2127 PyObject *olddefault = dd->default_factory;
2128 PyObject *newdefault = NULL;
2129 PyObject *newargs;
2130 int result;
2131 if (args == NULL || !PyTuple_Check(args))
2132 newargs = PyTuple_New(0);
2133 else {
2134 Py_ssize_t n = PyTuple_GET_SIZE(args);
2135 if (n > 0) {
2136 newdefault = PyTuple_GET_ITEM(args, 0);
2137 if (!PyCallable_Check(newdefault) && newdefault != Py_None) {
2138 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger239aba72015-07-20 03:09:22 -04002139 "first argument must be callable or None");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002140 return -1;
2141 }
2142 }
2143 newargs = PySequence_GetSlice(args, 1, n);
2144 }
2145 if (newargs == NULL)
2146 return -1;
2147 Py_XINCREF(newdefault);
2148 dd->default_factory = newdefault;
2149 result = PyDict_Type.tp_init(self, newargs, kwds);
2150 Py_DECREF(newargs);
2151 Py_XDECREF(olddefault);
2152 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00002153}
2154
2155PyDoc_STRVAR(defdict_doc,
Benjamin Peterson9cb33b72014-01-13 23:56:05 -05002156"defaultdict(default_factory[, ...]) --> dict with default factory\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00002157\n\
2158The default factory is called without arguments to produce\n\
2159a new value when a key is not present, in __getitem__ only.\n\
2160A defaultdict compares equal to a dict with the same items.\n\
Benjamin Peterson9cb33b72014-01-13 23:56:05 -05002161All remaining arguments are treated the same as if they were\n\
2162passed to the dict constructor, including keyword arguments.\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00002163");
2164
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002165/* See comment in xxsubtype.c */
2166#define DEFERRED_ADDRESS(ADDR) 0
2167
Guido van Rossum1968ad32006-02-25 22:38:04 +00002168static PyTypeObject defdict_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002169 PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0)
2170 "collections.defaultdict", /* tp_name */
2171 sizeof(defdictobject), /* tp_basicsize */
2172 0, /* tp_itemsize */
2173 /* methods */
2174 (destructor)defdict_dealloc, /* tp_dealloc */
2175 0, /* tp_print */
2176 0, /* tp_getattr */
2177 0, /* tp_setattr */
2178 0, /* tp_reserved */
2179 (reprfunc)defdict_repr, /* tp_repr */
2180 0, /* tp_as_number */
2181 0, /* tp_as_sequence */
2182 0, /* tp_as_mapping */
2183 0, /* tp_hash */
2184 0, /* tp_call */
2185 0, /* tp_str */
2186 PyObject_GenericGetAttr, /* tp_getattro */
2187 0, /* tp_setattro */
2188 0, /* tp_as_buffer */
2189 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
2190 /* tp_flags */
2191 defdict_doc, /* tp_doc */
2192 defdict_traverse, /* tp_traverse */
2193 (inquiry)defdict_tp_clear, /* tp_clear */
2194 0, /* tp_richcompare */
2195 0, /* tp_weaklistoffset*/
2196 0, /* tp_iter */
2197 0, /* tp_iternext */
2198 defdict_methods, /* tp_methods */
2199 defdict_members, /* tp_members */
2200 0, /* tp_getset */
2201 DEFERRED_ADDRESS(&PyDict_Type), /* tp_base */
2202 0, /* tp_dict */
2203 0, /* tp_descr_get */
2204 0, /* tp_descr_set */
2205 0, /* tp_dictoffset */
2206 defdict_init, /* tp_init */
2207 PyType_GenericAlloc, /* tp_alloc */
2208 0, /* tp_new */
2209 PyObject_GC_Del, /* tp_free */
Guido van Rossum1968ad32006-02-25 22:38:04 +00002210};
2211
Raymond Hettinger96f34102010-12-15 16:30:37 +00002212/* helper function for Counter *********************************************/
2213
2214PyDoc_STRVAR(_count_elements_doc,
2215"_count_elements(mapping, iterable) -> None\n\
2216\n\
2217Count elements in the iterable, updating the mappping");
2218
2219static PyObject *
2220_count_elements(PyObject *self, PyObject *args)
2221{
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002222 _Py_IDENTIFIER(get);
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002223 _Py_IDENTIFIER(__setitem__);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002224 PyObject *it, *iterable, *mapping, *oldval;
2225 PyObject *newval = NULL;
2226 PyObject *key = NULL;
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002227 PyObject *zero = NULL;
Raymond Hettinger96f34102010-12-15 16:30:37 +00002228 PyObject *one = NULL;
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002229 PyObject *bound_get = NULL;
2230 PyObject *mapping_get;
2231 PyObject *dict_get;
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002232 PyObject *mapping_setitem;
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002233 PyObject *dict_setitem;
Raymond Hettinger96f34102010-12-15 16:30:37 +00002234
2235 if (!PyArg_UnpackTuple(args, "_count_elements", 2, 2, &mapping, &iterable))
2236 return NULL;
2237
Raymond Hettinger96f34102010-12-15 16:30:37 +00002238 it = PyObject_GetIter(iterable);
2239 if (it == NULL)
2240 return NULL;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002241
Raymond Hettinger96f34102010-12-15 16:30:37 +00002242 one = PyLong_FromLong(1);
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002243 if (one == NULL)
2244 goto done;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002245
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002246 /* Only take the fast path when get() and __setitem__()
2247 * have not been overridden.
2248 */
2249 mapping_get = _PyType_LookupId(Py_TYPE(mapping), &PyId_get);
2250 dict_get = _PyType_LookupId(&PyDict_Type, &PyId_get);
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002251 mapping_setitem = _PyType_LookupId(Py_TYPE(mapping), &PyId___setitem__);
2252 dict_setitem = _PyType_LookupId(&PyDict_Type, &PyId___setitem__);
2253
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002254 if (mapping_get != NULL && mapping_get == dict_get &&
2255 mapping_setitem != NULL && mapping_setitem == dict_setitem) {
Raymond Hettinger426e0522011-01-03 02:12:02 +00002256 while (1) {
Raymond Hettinger507d9972014-05-18 21:32:40 +01002257 /* Fast path advantages:
2258 1. Eliminate double hashing
2259 (by re-using the same hash for both the get and set)
2260 2. Avoid argument overhead of PyObject_CallFunctionObjArgs
2261 (argument tuple creation and parsing)
2262 3. Avoid indirection through a bound method object
2263 (creates another argument tuple)
2264 4. Avoid initial increment from zero
2265 (reuse an existing one-object instead)
2266 */
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002267 Py_hash_t hash;
2268
Raymond Hettinger426e0522011-01-03 02:12:02 +00002269 key = PyIter_Next(it);
Victor Stinnera154b5c2011-04-20 23:23:52 +02002270 if (key == NULL)
2271 break;
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002272
2273 if (!PyUnicode_CheckExact(key) ||
2274 (hash = ((PyASCIIObject *) key)->hash) == -1)
2275 {
2276 hash = PyObject_Hash(key);
Raymond Hettingerda2850f2015-02-27 12:42:54 -08002277 if (hash == -1)
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002278 goto done;
2279 }
2280
2281 oldval = _PyDict_GetItem_KnownHash(mapping, key, hash);
Raymond Hettinger426e0522011-01-03 02:12:02 +00002282 if (oldval == NULL) {
Raymond Hettinger28c995d2015-08-14 02:07:41 -07002283 if (_PyDict_SetItem_KnownHash(mapping, key, one, hash) < 0)
Raymond Hettinger507d9972014-05-18 21:32:40 +01002284 goto done;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002285 } else {
2286 newval = PyNumber_Add(oldval, one);
2287 if (newval == NULL)
Raymond Hettinger507d9972014-05-18 21:32:40 +01002288 goto done;
Raymond Hettinger28c995d2015-08-14 02:07:41 -07002289 if (_PyDict_SetItem_KnownHash(mapping, key, newval, hash) < 0)
Raymond Hettinger507d9972014-05-18 21:32:40 +01002290 goto done;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002291 Py_CLEAR(newval);
2292 }
2293 Py_DECREF(key);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002294 }
Raymond Hettinger426e0522011-01-03 02:12:02 +00002295 } else {
Victor Stinnere7f516c2013-11-06 23:52:55 +01002296 bound_get = _PyObject_GetAttrId(mapping, &PyId_get);
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002297 if (bound_get == NULL)
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002298 goto done;
2299
2300 zero = PyLong_FromLong(0);
2301 if (zero == NULL)
2302 goto done;
2303
Raymond Hettinger426e0522011-01-03 02:12:02 +00002304 while (1) {
2305 key = PyIter_Next(it);
Victor Stinnera154b5c2011-04-20 23:23:52 +02002306 if (key == NULL)
2307 break;
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002308 oldval = PyObject_CallFunctionObjArgs(bound_get, key, zero, NULL);
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002309 if (oldval == NULL)
2310 break;
2311 newval = PyNumber_Add(oldval, one);
2312 Py_DECREF(oldval);
2313 if (newval == NULL)
2314 break;
Raymond Hettinger28c995d2015-08-14 02:07:41 -07002315 if (PyObject_SetItem(mapping, key, newval) < 0)
Raymond Hettinger96f34102010-12-15 16:30:37 +00002316 break;
2317 Py_CLEAR(newval);
Raymond Hettinger426e0522011-01-03 02:12:02 +00002318 Py_DECREF(key);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002319 }
Raymond Hettinger96f34102010-12-15 16:30:37 +00002320 }
Raymond Hettinger426e0522011-01-03 02:12:02 +00002321
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002322done:
Raymond Hettinger96f34102010-12-15 16:30:37 +00002323 Py_DECREF(it);
2324 Py_XDECREF(key);
2325 Py_XDECREF(newval);
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002326 Py_XDECREF(bound_get);
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002327 Py_XDECREF(zero);
2328 Py_XDECREF(one);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002329 if (PyErr_Occurred())
2330 return NULL;
2331 Py_RETURN_NONE;
2332}
2333
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002334/* module level code ********************************************************/
2335
2336PyDoc_STRVAR(module_doc,
Guido van Rossum1968ad32006-02-25 22:38:04 +00002337"High performance data structures.\n\
2338- deque: ordered collection accessible from endpoints only\n\
2339- defaultdict: dict subclass with a default value factory\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002340");
2341
Raymond Hettinger96f34102010-12-15 16:30:37 +00002342static struct PyMethodDef module_functions[] = {
2343 {"_count_elements", _count_elements, METH_VARARGS, _count_elements_doc},
2344 {NULL, NULL} /* sentinel */
2345};
Martin v. Löwis1a214512008-06-11 05:26:20 +00002346
2347static struct PyModuleDef _collectionsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002348 PyModuleDef_HEAD_INIT,
2349 "_collections",
2350 module_doc,
2351 -1,
Raymond Hettinger96f34102010-12-15 16:30:37 +00002352 module_functions,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002353 NULL,
2354 NULL,
2355 NULL,
2356 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002357};
2358
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002359PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002360PyInit__collections(void)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002361{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002362 PyObject *m;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002364 m = PyModule_Create(&_collectionsmodule);
2365 if (m == NULL)
2366 return NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002368 if (PyType_Ready(&deque_type) < 0)
2369 return NULL;
2370 Py_INCREF(&deque_type);
2371 PyModule_AddObject(m, "deque", (PyObject *)&deque_type);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002373 defdict_type.tp_base = &PyDict_Type;
2374 if (PyType_Ready(&defdict_type) < 0)
2375 return NULL;
2376 Py_INCREF(&defdict_type);
2377 PyModule_AddObject(m, "defaultdict", (PyObject *)&defdict_type);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002378
Eric Snow47db7172015-05-29 22:21:39 -06002379 Py_INCREF(&PyODict_Type);
2380 PyModule_AddObject(m, "OrderedDict", (PyObject *)&PyODict_Type);
2381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002382 if (PyType_Ready(&dequeiter_type) < 0)
2383 return NULL;
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002384 Py_INCREF(&dequeiter_type);
2385 PyModule_AddObject(m, "_deque_iterator", (PyObject *)&dequeiter_type);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002387 if (PyType_Ready(&dequereviter_type) < 0)
2388 return NULL;
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002389 Py_INCREF(&dequereviter_type);
2390 PyModule_AddObject(m, "_deque_reverse_iterator", (PyObject *)&dequereviter_type);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00002391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002392 return m;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002393}