blob: cef92c0b81499d3c549df45f12c0013be43caf77 [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().
Raymond Hettingerd96db092015-10-11 22:34:48 -0700279 *
280 * The macro to check whether a deque needs to be trimmed uses a single
281 * unsigned test that returns true whenever 0 <= maxlen < Py_SIZE(deque).
Raymond Hettingerf30f5b92015-03-02 22:23:37 -0800282 */
283
Raymond Hettingerd96db092015-10-11 22:34:48 -0700284#define NEEDS_TRIM(deque, maxlen) ((size_t)(maxlen) < (size_t)(Py_SIZE(deque)))
Raymond Hettingerf30f5b92015-03-02 22:23:37 -0800285
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000286static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000287deque_append(dequeobject *deque, PyObject *item)
288{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000289 deque->state++;
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700290 if (deque->rightindex == BLOCKLEN - 1) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000291 block *b = newblock(Py_SIZE(deque));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000292 if (b == NULL)
293 return NULL;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000294 b->leftlink = deque->rightblock;
295 CHECK_END(deque->rightblock->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000296 deque->rightblock->rightlink = b;
297 deque->rightblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000298 MARK_END(b->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000299 deque->rightindex = -1;
300 }
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000301 Py_SIZE(deque)++;
Raymond Hettinger7c0b70f2015-09-26 21:11:05 -0700302 Py_INCREF(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000303 deque->rightindex++;
304 deque->rightblock->data[deque->rightindex] = item;
Raymond Hettingerd96db092015-10-11 22:34:48 -0700305 if (NEEDS_TRIM(deque, deque->maxlen)) {
306 PyObject *rv = deque_popleft(deque, NULL);
307 Py_DECREF(rv);
308 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000309 Py_RETURN_NONE;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000310}
311
312PyDoc_STRVAR(append_doc, "Add an element to the right side of the deque.");
313
314static PyObject *
315deque_appendleft(dequeobject *deque, PyObject *item)
316{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000317 deque->state++;
318 if (deque->leftindex == 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000319 block *b = newblock(Py_SIZE(deque));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000320 if (b == NULL)
321 return NULL;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000322 b->rightlink = deque->leftblock;
323 CHECK_END(deque->leftblock->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000324 deque->leftblock->leftlink = b;
325 deque->leftblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000326 MARK_END(b->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000327 deque->leftindex = BLOCKLEN;
328 }
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000329 Py_SIZE(deque)++;
Raymond Hettinger7c0b70f2015-09-26 21:11:05 -0700330 Py_INCREF(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000331 deque->leftindex--;
332 deque->leftblock->data[deque->leftindex] = item;
Raymond Hettingerd96db092015-10-11 22:34:48 -0700333 if (NEEDS_TRIM(deque, deque->maxlen)) {
334 PyObject *rv = deque_pop(deque, NULL);
335 Py_DECREF(rv);
336 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000337 Py_RETURN_NONE;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000338}
339
340PyDoc_STRVAR(appendleft_doc, "Add an element to the left side of the deque.");
341
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700342static PyObject*
343finalize_iterator(PyObject *it)
344{
345 if (PyErr_Occurred()) {
346 if (PyErr_ExceptionMatches(PyExc_StopIteration))
347 PyErr_Clear();
348 else {
349 Py_DECREF(it);
350 return NULL;
351 }
352 }
353 Py_DECREF(it);
354 Py_RETURN_NONE;
355}
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000357/* Run an iterator to exhaustion. Shortcut for
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000358 the extend/extendleft methods when maxlen == 0. */
359static PyObject*
360consume_iterator(PyObject *it)
361{
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700362 PyObject *(*iternext)(PyObject *);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000363 PyObject *item;
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000364
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700365 iternext = *Py_TYPE(it)->tp_iternext;
366 while ((item = iternext(it)) != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000367 Py_DECREF(item);
368 }
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700369 return finalize_iterator(it);
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000370}
371
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000372static PyObject *
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000373deque_extend(dequeobject *deque, PyObject *iterable)
374{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 PyObject *it, *item;
Raymond Hettinger7a845522015-09-26 01:30:51 -0700376 PyObject *(*iternext)(PyObject *);
Raymond Hettinger6b1e1132015-10-11 09:43:50 -0700377 Py_ssize_t maxlen = deque->maxlen;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000379 /* Handle case where id(deque) == id(iterable) */
380 if ((PyObject *)deque == iterable) {
381 PyObject *result;
382 PyObject *s = PySequence_List(iterable);
383 if (s == NULL)
384 return NULL;
385 result = deque_extend(deque, s);
386 Py_DECREF(s);
387 return result;
388 }
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000389
Raymond Hettingerd9c116c2013-07-09 00:13:21 -0700390 /* Space saving heuristic. Start filling from the left */
391 if (Py_SIZE(deque) == 0) {
392 assert(deque->leftblock == deque->rightblock);
393 assert(deque->leftindex == deque->rightindex+1);
394 deque->leftindex = 1;
395 deque->rightindex = 0;
396 }
397
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000398 it = PyObject_GetIter(iterable);
399 if (it == NULL)
400 return NULL;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000401
Raymond Hettinger965362e2015-10-11 22:52:54 -0700402 if (maxlen == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000403 return consume_iterator(it);
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000404
Raymond Hettinger7a845522015-09-26 01:30:51 -0700405 iternext = *Py_TYPE(it)->tp_iternext;
406 while ((item = iternext(it)) != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000407 deque->state++;
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700408 if (deque->rightindex == BLOCKLEN - 1) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000409 block *b = newblock(Py_SIZE(deque));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000410 if (b == NULL) {
411 Py_DECREF(item);
412 Py_DECREF(it);
413 return NULL;
414 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000415 b->leftlink = deque->rightblock;
416 CHECK_END(deque->rightblock->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 deque->rightblock->rightlink = b;
418 deque->rightblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000419 MARK_END(b->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 deque->rightindex = -1;
421 }
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000422 Py_SIZE(deque)++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000423 deque->rightindex++;
424 deque->rightblock->data[deque->rightindex] = item;
Raymond Hettingerd96db092015-10-11 22:34:48 -0700425 if (NEEDS_TRIM(deque, maxlen)) {
Raymond Hettinger6b1e1132015-10-11 09:43:50 -0700426 PyObject *rv = deque_popleft(deque, NULL);
427 Py_DECREF(rv);
428 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000429 }
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700430 return finalize_iterator(it);
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000431}
432
Tim Peters1065f752004-10-01 01:03:29 +0000433PyDoc_STRVAR(extend_doc,
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000434"Extend the right side of the deque with elements from the iterable");
435
436static PyObject *
437deque_extendleft(dequeobject *deque, PyObject *iterable)
438{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000439 PyObject *it, *item;
Raymond Hettinger7a845522015-09-26 01:30:51 -0700440 PyObject *(*iternext)(PyObject *);
Raymond Hettinger6b1e1132015-10-11 09:43:50 -0700441 Py_ssize_t maxlen = deque->maxlen;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000443 /* Handle case where id(deque) == id(iterable) */
444 if ((PyObject *)deque == iterable) {
445 PyObject *result;
446 PyObject *s = PySequence_List(iterable);
447 if (s == NULL)
448 return NULL;
449 result = deque_extendleft(deque, s);
450 Py_DECREF(s);
451 return result;
452 }
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000453
Raymond Hettingerd9c116c2013-07-09 00:13:21 -0700454 /* Space saving heuristic. Start filling from the right */
455 if (Py_SIZE(deque) == 0) {
456 assert(deque->leftblock == deque->rightblock);
457 assert(deque->leftindex == deque->rightindex+1);
458 deque->leftindex = BLOCKLEN - 1;
459 deque->rightindex = BLOCKLEN - 2;
460 }
461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000462 it = PyObject_GetIter(iterable);
463 if (it == NULL)
464 return NULL;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000465
Raymond Hettinger965362e2015-10-11 22:52:54 -0700466 if (maxlen == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000467 return consume_iterator(it);
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000468
Raymond Hettinger7a845522015-09-26 01:30:51 -0700469 iternext = *Py_TYPE(it)->tp_iternext;
470 while ((item = iternext(it)) != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 deque->state++;
472 if (deque->leftindex == 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000473 block *b = newblock(Py_SIZE(deque));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 if (b == NULL) {
475 Py_DECREF(item);
476 Py_DECREF(it);
477 return NULL;
478 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000479 b->rightlink = deque->leftblock;
480 CHECK_END(deque->leftblock->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000481 deque->leftblock->leftlink = b;
482 deque->leftblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000483 MARK_END(b->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 deque->leftindex = BLOCKLEN;
485 }
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000486 Py_SIZE(deque)++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000487 deque->leftindex--;
488 deque->leftblock->data[deque->leftindex] = item;
Raymond Hettingerd96db092015-10-11 22:34:48 -0700489 if (NEEDS_TRIM(deque, maxlen)) {
Raymond Hettinger6b1e1132015-10-11 09:43:50 -0700490 PyObject *rv = deque_pop(deque, NULL);
491 Py_DECREF(rv);
492 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 }
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700494 return finalize_iterator(it);
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000495}
496
Tim Peters1065f752004-10-01 01:03:29 +0000497PyDoc_STRVAR(extendleft_doc,
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000498"Extend the left side of the deque with elements from the iterable");
499
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000500static PyObject *
501deque_inplace_concat(dequeobject *deque, PyObject *other)
502{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000503 PyObject *result;
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000505 result = deque_extend(deque, other);
506 if (result == NULL)
507 return result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 Py_INCREF(deque);
Raymond Hettinger2b2b7532015-09-05 17:05:52 -0700509 Py_DECREF(result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 return (PyObject *)deque;
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000511}
512
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700513static PyObject *
514deque_copy(PyObject *deque)
515{
516 dequeobject *old_deque = (dequeobject *)deque;
517 if (Py_TYPE(deque) == &deque_type) {
518 dequeobject *new_deque;
519 PyObject *rv;
520
521 new_deque = (dequeobject *)deque_new(&deque_type, (PyObject *)NULL, (PyObject *)NULL);
522 if (new_deque == NULL)
523 return NULL;
524 new_deque->maxlen = old_deque->maxlen;
525 /* Fast path for the deque_repeat() common case where len(deque) == 1 */
Raymond Hettinger0443ac22015-10-05 22:52:37 -0400526 if (Py_SIZE(deque) == 1) {
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700527 PyObject *item = old_deque->leftblock->data[old_deque->leftindex];
528 rv = deque_append(new_deque, item);
529 } else {
530 rv = deque_extend(new_deque, deque);
531 }
532 if (rv != NULL) {
533 Py_DECREF(rv);
534 return (PyObject *)new_deque;
535 }
536 Py_DECREF(new_deque);
537 return NULL;
538 }
539 if (old_deque->maxlen < 0)
540 return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "O", deque, NULL);
541 else
542 return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "Oi",
543 deque, old_deque->maxlen, NULL);
544}
545
546PyDoc_STRVAR(copy_doc, "Return a shallow copy of a deque.");
Raymond Hettinger41290a62015-03-31 08:12:23 -0700547
548static PyObject *
549deque_concat(dequeobject *deque, PyObject *other)
550{
Benjamin Peterson1a629212015-04-04 10:52:36 -0400551 PyObject *new_deque, *result;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700552 int rv;
553
554 rv = PyObject_IsInstance(other, (PyObject *)&deque_type);
555 if (rv <= 0) {
556 if (rv == 0) {
557 PyErr_Format(PyExc_TypeError,
558 "can only concatenate deque (not \"%.200s\") to deque",
559 other->ob_type->tp_name);
560 }
561 return NULL;
562 }
563
564 new_deque = deque_copy((PyObject *)deque);
565 if (new_deque == NULL)
566 return NULL;
Benjamin Peterson1a629212015-04-04 10:52:36 -0400567 result = deque_extend((dequeobject *)new_deque, other);
568 if (result == NULL) {
569 Py_DECREF(new_deque);
570 return NULL;
571 }
572 Py_DECREF(result);
573 return new_deque;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700574}
575
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700576static void
577deque_clear(dequeobject *deque)
578{
579 block *b;
580 block *prevblock;
581 block *leftblock;
582 Py_ssize_t leftindex;
583 Py_ssize_t n;
584 PyObject *item;
585
Raymond Hettinger38031142015-09-29 22:45:05 -0700586 if (Py_SIZE(deque) == 0)
587 return;
588
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700589 /* During the process of clearing a deque, decrefs can cause the
590 deque to mutate. To avoid fatal confusion, we have to make the
591 deque empty before clearing the blocks and never refer to
592 anything via deque->ref while clearing. (This is the same
593 technique used for clearing lists, sets, and dicts.)
594
595 Making the deque empty requires allocating a new empty block. In
596 the unlikely event that memory is full, we fall back to an
597 alternate method that doesn't require a new block. Repeating
598 pops in a while-loop is slower, possibly re-entrant (and a clever
599 adversary could cause it to never terminate).
600 */
601
602 b = newblock(0);
603 if (b == NULL) {
604 PyErr_Clear();
605 goto alternate_method;
606 }
607
608 /* Remember the old size, leftblock, and leftindex */
609 leftblock = deque->leftblock;
610 leftindex = deque->leftindex;
611 n = Py_SIZE(deque);
612
613 /* Set the deque to be empty using the newly allocated block */
614 MARK_END(b->leftlink);
615 MARK_END(b->rightlink);
616 Py_SIZE(deque) = 0;
617 deque->leftblock = b;
618 deque->rightblock = b;
619 deque->leftindex = CENTER + 1;
620 deque->rightindex = CENTER;
621 deque->state++;
622
623 /* Now the old size, leftblock, and leftindex are disconnected from
624 the empty deque and we can use them to decref the pointers.
625 */
626 while (n--) {
627 item = leftblock->data[leftindex];
628 Py_DECREF(item);
629 leftindex++;
630 if (leftindex == BLOCKLEN && n) {
631 CHECK_NOT_END(leftblock->rightlink);
632 prevblock = leftblock;
633 leftblock = leftblock->rightlink;
634 leftindex = 0;
635 freeblock(prevblock);
636 }
637 }
638 CHECK_END(leftblock->rightlink);
639 freeblock(leftblock);
640 return;
641
642 alternate_method:
643 while (Py_SIZE(deque)) {
644 item = deque_pop(deque, NULL);
645 assert (item != NULL);
646 Py_DECREF(item);
647 }
648}
649
650static PyObject *
651deque_clearmethod(dequeobject *deque)
652{
653 deque_clear(deque);
654 Py_RETURN_NONE;
655}
656
657PyDoc_STRVAR(clear_doc, "Remove all elements from the deque.");
Raymond Hettinger41290a62015-03-31 08:12:23 -0700658
659static PyObject *
Raymond Hettinger41290a62015-03-31 08:12:23 -0700660deque_inplace_repeat(dequeobject *deque, Py_ssize_t n)
661{
Raymond Hettingerc22eee62015-09-26 02:14:50 -0700662 Py_ssize_t i, m, size;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700663 PyObject *seq;
664 PyObject *rv;
665
666 size = Py_SIZE(deque);
667 if (size == 0 || n == 1) {
668 Py_INCREF(deque);
669 return (PyObject *)deque;
670 }
671
672 if (n <= 0) {
673 deque_clear(deque);
674 Py_INCREF(deque);
675 return (PyObject *)deque;
676 }
677
Raymond Hettinger41290a62015-03-31 08:12:23 -0700678 if (size == 1) {
679 /* common case, repeating a single element */
680 PyObject *item = deque->leftblock->data[deque->leftindex];
681
Raymond Hettingera7f630092015-10-10 23:56:02 -0400682 if (deque->maxlen >= 0 && n > deque->maxlen)
Raymond Hettinger41290a62015-03-31 08:12:23 -0700683 n = deque->maxlen;
684
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400685 if (n > MAX_DEQUE_LEN)
686 return PyErr_NoMemory();
687
Raymond Hettinger67c78b52015-09-12 11:00:20 -0400688 deque->state++;
Raymond Hettingerad262252015-09-14 01:03:04 -0400689 for (i = 0 ; i < n-1 ; ) {
Raymond Hettinger67c78b52015-09-12 11:00:20 -0400690 if (deque->rightindex == BLOCKLEN - 1) {
691 block *b = newblock(Py_SIZE(deque) + i);
692 if (b == NULL) {
693 Py_SIZE(deque) += i;
694 return NULL;
695 }
696 b->leftlink = deque->rightblock;
697 CHECK_END(deque->rightblock->rightlink);
698 deque->rightblock->rightlink = b;
699 deque->rightblock = b;
700 MARK_END(b->rightlink);
701 deque->rightindex = -1;
702 }
Raymond Hettingerc22eee62015-09-26 02:14:50 -0700703 m = n - 1 - i;
704 if (m > BLOCKLEN - 1 - deque->rightindex)
705 m = BLOCKLEN - 1 - deque->rightindex;
706 i += m;
707 while (m--) {
Raymond Hettingerad262252015-09-14 01:03:04 -0400708 deque->rightindex++;
709 Py_INCREF(item);
710 deque->rightblock->data[deque->rightindex] = item;
711 }
Raymond Hettinger41290a62015-03-31 08:12:23 -0700712 }
Raymond Hettinger67c78b52015-09-12 11:00:20 -0400713 Py_SIZE(deque) += i;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700714 Py_INCREF(deque);
715 return (PyObject *)deque;
716 }
717
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400718 if ((size_t)size > MAX_DEQUE_LEN / (size_t)n) {
719 return PyErr_NoMemory();
720 }
721
Raymond Hettinger41290a62015-03-31 08:12:23 -0700722 seq = PySequence_List((PyObject *)deque);
723 if (seq == NULL)
724 return seq;
725
726 for (i = 0 ; i < n-1 ; i++) {
727 rv = deque_extend(deque, seq);
728 if (rv == NULL) {
729 Py_DECREF(seq);
730 return NULL;
731 }
732 Py_DECREF(rv);
733 }
734 Py_INCREF(deque);
735 Py_DECREF(seq);
736 return (PyObject *)deque;
737}
738
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400739static PyObject *
740deque_repeat(dequeobject *deque, Py_ssize_t n)
741{
742 dequeobject *new_deque;
Raymond Hettinger95e2cc52015-09-13 02:41:18 -0400743 PyObject *rv;
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400744
745 new_deque = (dequeobject *)deque_copy((PyObject *) deque);
746 if (new_deque == NULL)
747 return NULL;
Raymond Hettinger95e2cc52015-09-13 02:41:18 -0400748 rv = deque_inplace_repeat(new_deque, n);
749 Py_DECREF(new_deque);
750 return rv;
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400751}
752
Raymond Hettinger54023152014-04-23 00:58:48 -0700753/* The rotate() method is part of the public API and is used internally
754as a primitive for other methods.
755
756Rotation by 1 or -1 is a common case, so any optimizations for high
757volume rotations should take care not to penalize the common case.
758
759Conceptually, a rotate by one is equivalent to a pop on one side and an
760append on the other. However, a pop/append pair is unnecessarily slow
761because it requires a incref/decref pair for an object located randomly
762in memory. It is better to just move the object pointer from one block
763to the next without changing the reference count.
764
765When moving batches of pointers, it is tempting to use memcpy() but that
766proved to be slower than a simple loop for a variety of reasons.
767Memcpy() cannot know in advance that we're copying pointers instead of
768bytes, that the source and destination are pointer aligned and
769non-overlapping, that moving just one pointer is a common case, that we
770never need to move more than BLOCKLEN pointers, and that at least one
771pointer is always moved.
772
773For high volume rotations, newblock() and freeblock() are never called
774more than once. Previously emptied blocks are immediately reused as a
775destination block. If a block is left-over at the end, it is freed.
776*/
777
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000778static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000779_deque_rotate(dequeobject *deque, Py_ssize_t n)
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000780{
Raymond Hettinger3959af92013-07-13 02:34:08 -0700781 block *b = NULL;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700782 block *leftblock = deque->leftblock;
783 block *rightblock = deque->rightblock;
784 Py_ssize_t leftindex = deque->leftindex;
785 Py_ssize_t rightindex = deque->rightindex;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000786 Py_ssize_t len=Py_SIZE(deque), halflen=len>>1;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700787 int rv = -1;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000788
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800789 if (len <= 1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 return 0;
791 if (n > halflen || n < -halflen) {
792 n %= len;
793 if (n > halflen)
794 n -= len;
795 else if (n < -halflen)
796 n += len;
797 }
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500798 assert(len > 1);
Raymond Hettingera4409c12013-02-04 00:08:12 -0500799 assert(-halflen <= n && n <= halflen);
Raymond Hettinger231ee4d2013-02-02 11:24:43 -0800800
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800801 deque->state++;
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500802 while (n > 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700803 if (leftindex == 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700804 if (b == NULL) {
Raymond Hettinger3959af92013-07-13 02:34:08 -0700805 b = newblock(len);
806 if (b == NULL)
807 goto done;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700808 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000809 b->rightlink = leftblock;
810 CHECK_END(leftblock->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700811 leftblock->leftlink = b;
812 leftblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000813 MARK_END(b->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700814 leftindex = BLOCKLEN;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700815 b = NULL;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800816 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700817 assert(leftindex > 0);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700818 {
819 PyObject **src, **dest;
820 Py_ssize_t m = n;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800821
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700822 if (m > rightindex + 1)
823 m = rightindex + 1;
824 if (m > leftindex)
825 m = leftindex;
826 assert (m > 0 && m <= len);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700827 rightindex -= m;
828 leftindex -= m;
Raymond Hettinger0e259f12015-02-01 22:53:41 -0800829 src = &rightblock->data[rightindex + 1];
830 dest = &leftblock->data[leftindex];
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700831 n -= m;
Raymond Hettinger840533b2013-07-13 17:03:58 -0700832 do {
Raymond Hettinger0e259f12015-02-01 22:53:41 -0800833 *(dest++) = *(src++);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700834 } while (--m);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700835 }
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -0700836 if (rightindex < 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700837 assert(leftblock != rightblock);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700838 assert(b == NULL);
Raymond Hettinger3959af92013-07-13 02:34:08 -0700839 b = rightblock;
Raymond Hettingerb97cc492013-07-21 01:51:07 -0700840 CHECK_NOT_END(rightblock->leftlink);
841 rightblock = rightblock->leftlink;
842 MARK_END(rightblock->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700843 rightindex = BLOCKLEN - 1;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800844 }
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800845 }
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500846 while (n < 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700847 if (rightindex == BLOCKLEN - 1) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700848 if (b == NULL) {
Raymond Hettinger3959af92013-07-13 02:34:08 -0700849 b = newblock(len);
850 if (b == NULL)
851 goto done;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700852 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000853 b->leftlink = rightblock;
854 CHECK_END(rightblock->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700855 rightblock->rightlink = b;
856 rightblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000857 MARK_END(b->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700858 rightindex = -1;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700859 b = NULL;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800860 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700861 assert (rightindex < BLOCKLEN - 1);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700862 {
863 PyObject **src, **dest;
864 Py_ssize_t m = -n;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800865
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700866 if (m > BLOCKLEN - leftindex)
867 m = BLOCKLEN - leftindex;
868 if (m > BLOCKLEN - 1 - rightindex)
869 m = BLOCKLEN - 1 - rightindex;
870 assert (m > 0 && m <= len);
871 src = &leftblock->data[leftindex];
872 dest = &rightblock->data[rightindex + 1];
873 leftindex += m;
874 rightindex += m;
875 n += m;
Raymond Hettinger840533b2013-07-13 17:03:58 -0700876 do {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700877 *(dest++) = *(src++);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700878 } while (--m);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700879 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700880 if (leftindex == BLOCKLEN) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700881 assert(leftblock != rightblock);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700882 assert(b == NULL);
Raymond Hettinger3959af92013-07-13 02:34:08 -0700883 b = leftblock;
Raymond Hettingerb97cc492013-07-21 01:51:07 -0700884 CHECK_NOT_END(leftblock->rightlink);
885 leftblock = leftblock->rightlink;
886 MARK_END(leftblock->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700887 leftindex = 0;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800888 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 }
Raymond Hettinger3959af92013-07-13 02:34:08 -0700890 rv = 0;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700891done:
Raymond Hettinger3959af92013-07-13 02:34:08 -0700892 if (b != NULL)
893 freeblock(b);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700894 deque->leftblock = leftblock;
895 deque->rightblock = rightblock;
896 deque->leftindex = leftindex;
897 deque->rightindex = rightindex;
898
899 return rv;
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000900}
901
902static PyObject *
903deque_rotate(dequeobject *deque, PyObject *args)
904{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000905 Py_ssize_t n=1;
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 if (!PyArg_ParseTuple(args, "|n:rotate", &n))
908 return NULL;
Raymond Hettinger6921c132015-03-21 02:03:40 -0700909 if (!_deque_rotate(deque, n))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 Py_RETURN_NONE;
911 return NULL;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000912}
913
Tim Peters1065f752004-10-01 01:03:29 +0000914PyDoc_STRVAR(rotate_doc,
Raymond Hettingeree33b272004-02-08 04:05:26 +0000915"Rotate the deque n steps to the right (default n=1). If n is negative, rotates left.");
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000916
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000917static PyObject *
918deque_reverse(dequeobject *deque, PyObject *unused)
919{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 block *leftblock = deque->leftblock;
921 block *rightblock = deque->rightblock;
922 Py_ssize_t leftindex = deque->leftindex;
923 Py_ssize_t rightindex = deque->rightindex;
Raymond Hettingercfe5b6c2015-07-20 00:25:50 -0400924 Py_ssize_t n = Py_SIZE(deque) >> 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000925 PyObject *tmp;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000926
Raymond Hettinger7a237232015-09-22 01:20:36 -0700927 while (n-- > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 /* Validate that pointers haven't met in the middle */
929 assert(leftblock != rightblock || leftindex < rightindex);
Raymond Hettinger82df9252013-07-07 01:43:42 -1000930 CHECK_NOT_END(leftblock);
931 CHECK_NOT_END(rightblock);
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933 /* Swap */
934 tmp = leftblock->data[leftindex];
935 leftblock->data[leftindex] = rightblock->data[rightindex];
936 rightblock->data[rightindex] = tmp;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 /* Advance left block/index pair */
939 leftindex++;
940 if (leftindex == BLOCKLEN) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 leftblock = leftblock->rightlink;
942 leftindex = 0;
943 }
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000945 /* Step backwards with the right block/index pair */
946 rightindex--;
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -0700947 if (rightindex < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000948 rightblock = rightblock->leftlink;
949 rightindex = BLOCKLEN - 1;
950 }
951 }
952 Py_RETURN_NONE;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000953}
954
955PyDoc_STRVAR(reverse_doc,
956"D.reverse() -- reverse *IN PLACE*");
957
Raymond Hettinger44459de2010-04-03 23:20:46 +0000958static PyObject *
959deque_count(dequeobject *deque, PyObject *v)
960{
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000961 block *b = deque->leftblock;
962 Py_ssize_t index = deque->leftindex;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000963 Py_ssize_t n = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000964 Py_ssize_t count = 0;
Raymond Hettingerf9d9c792015-03-02 22:47:46 -0800965 size_t start_state = deque->state;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 PyObject *item;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000967 int cmp;
Raymond Hettinger44459de2010-04-03 23:20:46 +0000968
Raymond Hettinger3a1a8d02015-09-23 02:42:02 -0700969 while (n--) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000970 CHECK_NOT_END(b);
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000971 item = b->data[index];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
Raymond Hettinger2b0d6462015-09-23 19:15:44 -0700973 if (cmp < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 return NULL;
Raymond Hettinger2b0d6462015-09-23 19:15:44 -0700975 count += cmp;
Raymond Hettinger44459de2010-04-03 23:20:46 +0000976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000977 if (start_state != deque->state) {
978 PyErr_SetString(PyExc_RuntimeError,
979 "deque mutated during iteration");
980 return NULL;
981 }
Raymond Hettinger44459de2010-04-03 23:20:46 +0000982
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000983 /* Advance left block/index pair */
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000984 index++;
985 if (index == BLOCKLEN) {
986 b = b->rightlink;
987 index = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000988 }
989 }
990 return PyLong_FromSsize_t(count);
Raymond Hettinger44459de2010-04-03 23:20:46 +0000991}
992
993PyDoc_STRVAR(count_doc,
994"D.count(value) -> integer -- return number of occurrences of value");
995
Raymond Hettinger39dadf72015-03-20 16:38:56 -0700996static int
997deque_contains(dequeobject *deque, PyObject *v)
998{
999 block *b = deque->leftblock;
1000 Py_ssize_t index = deque->leftindex;
1001 Py_ssize_t n = Py_SIZE(deque);
Raymond Hettinger39dadf72015-03-20 16:38:56 -07001002 size_t start_state = deque->state;
1003 PyObject *item;
1004 int cmp;
1005
Raymond Hettinger3a1a8d02015-09-23 02:42:02 -07001006 while (n--) {
Raymond Hettinger39dadf72015-03-20 16:38:56 -07001007 CHECK_NOT_END(b);
1008 item = b->data[index];
1009 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
1010 if (cmp) {
1011 return cmp;
1012 }
1013 if (start_state != deque->state) {
1014 PyErr_SetString(PyExc_RuntimeError,
1015 "deque mutated during iteration");
1016 return -1;
1017 }
1018 index++;
1019 if (index == BLOCKLEN) {
1020 b = b->rightlink;
1021 index = 0;
1022 }
1023 }
1024 return 0;
1025}
1026
Martin v. Löwis18e16552006-02-15 17:27:45 +00001027static Py_ssize_t
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001028deque_len(dequeobject *deque)
1029{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001030 return Py_SIZE(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001031}
1032
Raymond Hettinger4aec61e2005-03-18 21:20:23 +00001033static PyObject *
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001034deque_index(dequeobject *deque, PyObject *args)
1035{
1036 Py_ssize_t i, start=0, stop=Py_SIZE(deque);
1037 PyObject *v, *item;
1038 block *b = deque->leftblock;
1039 Py_ssize_t index = deque->leftindex;
1040 size_t start_state = deque->state;
1041
1042 if (!PyArg_ParseTuple(args, "O|O&O&:index", &v,
1043 _PyEval_SliceIndex, &start,
1044 _PyEval_SliceIndex, &stop))
1045 return NULL;
1046 if (start < 0) {
1047 start += Py_SIZE(deque);
1048 if (start < 0)
1049 start = 0;
1050 }
1051 if (stop < 0) {
1052 stop += Py_SIZE(deque);
1053 if (stop < 0)
1054 stop = 0;
1055 }
Raymond Hettinger87674ec2015-08-26 08:08:38 -07001056 if (stop > Py_SIZE(deque))
1057 stop = Py_SIZE(deque);
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001058
1059 for (i=0 ; i<stop ; i++) {
1060 if (i >= start) {
1061 int cmp;
1062 CHECK_NOT_END(b);
1063 item = b->data[index];
1064 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
1065 if (cmp > 0)
1066 return PyLong_FromSsize_t(i);
1067 else if (cmp < 0)
1068 return NULL;
1069 if (start_state != deque->state) {
1070 PyErr_SetString(PyExc_RuntimeError,
1071 "deque mutated during iteration");
1072 return NULL;
1073 }
1074 }
1075 index++;
1076 if (index == BLOCKLEN) {
1077 b = b->rightlink;
1078 index = 0;
1079 }
1080 }
1081 PyErr_Format(PyExc_ValueError, "%R is not in deque", v);
1082 return NULL;
1083}
1084
1085PyDoc_STRVAR(index_doc,
1086"D.index(value, [start, [stop]]) -> integer -- return first index of value.\n"
1087"Raises ValueError if the value is not present.");
1088
Raymond Hettinger551350a2015-03-24 00:19:53 -07001089/* insert(), remove(), and delitem() are implemented in terms of
1090 rotate() for simplicity and reasonable performance near the end
1091 points. If for some reason these methods become popular, it is not
1092 hard to re-implement this using direct data movement (similar to
1093 the code used in list slice assignments) and achieve a performance
Raymond Hettingerfef9c1b2015-03-24 21:12:57 -07001094 boost (by moving each pointer only once instead of twice).
Raymond Hettinger551350a2015-03-24 00:19:53 -07001095*/
1096
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001097static PyObject *
1098deque_insert(dequeobject *deque, PyObject *args)
1099{
1100 Py_ssize_t index;
1101 Py_ssize_t n = Py_SIZE(deque);
1102 PyObject *value;
1103 PyObject *rv;
1104
1105 if (!PyArg_ParseTuple(args, "nO:insert", &index, &value))
1106 return NULL;
1107 if (index >= n)
1108 return deque_append(deque, value);
1109 if (index <= -n || index == 0)
1110 return deque_appendleft(deque, value);
1111 if (_deque_rotate(deque, -index))
1112 return NULL;
1113 if (index < 0)
1114 rv = deque_append(deque, value);
1115 else
1116 rv = deque_appendleft(deque, value);
1117 if (rv == NULL)
1118 return NULL;
1119 Py_DECREF(rv);
1120 if (_deque_rotate(deque, index))
1121 return NULL;
1122 Py_RETURN_NONE;
1123}
1124
1125PyDoc_STRVAR(insert_doc,
1126"D.insert(index, object) -- insert object before index");
1127
1128static PyObject *
Raymond Hettinger4aec61e2005-03-18 21:20:23 +00001129deque_remove(dequeobject *deque, PyObject *value)
1130{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001131 Py_ssize_t i, n=Py_SIZE(deque);
Raymond Hettinger4aec61e2005-03-18 21:20:23 +00001132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001133 for (i=0 ; i<n ; i++) {
1134 PyObject *item = deque->leftblock->data[deque->leftindex];
1135 int cmp = PyObject_RichCompareBool(item, value, Py_EQ);
Raymond Hettingerd73202c2005-03-19 00:00:51 +00001136
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001137 if (Py_SIZE(deque) != n) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001138 PyErr_SetString(PyExc_IndexError,
1139 "deque mutated during remove().");
1140 return NULL;
1141 }
1142 if (cmp > 0) {
1143 PyObject *tgt = deque_popleft(deque, NULL);
1144 assert (tgt != NULL);
Raymond Hettinger6921c132015-03-21 02:03:40 -07001145 if (_deque_rotate(deque, i))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001146 return NULL;
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001147 Py_DECREF(tgt);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001148 Py_RETURN_NONE;
1149 }
1150 else if (cmp < 0) {
1151 _deque_rotate(deque, i);
1152 return NULL;
1153 }
1154 _deque_rotate(deque, -1);
1155 }
1156 PyErr_SetString(PyExc_ValueError, "deque.remove(x): x not in deque");
1157 return NULL;
Raymond Hettinger4aec61e2005-03-18 21:20:23 +00001158}
1159
1160PyDoc_STRVAR(remove_doc,
1161"D.remove(value) -- remove first occurrence of value.");
1162
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001163static int
1164valid_index(Py_ssize_t i, Py_ssize_t limit)
1165{
Raymond Hettinger12f896c2015-07-31 12:03:20 -07001166 /* The cast to size_t lets us use just a single comparison
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001167 to check whether i is in the range: 0 <= i < limit */
1168 return (size_t) i < (size_t) limit;
1169}
1170
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001171static PyObject *
Benjamin Petersond6313712008-07-31 16:23:04 +00001172deque_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001173{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001174 block *b;
1175 PyObject *item;
1176 Py_ssize_t n, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001177
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001178 if (!valid_index(i, Py_SIZE(deque))) {
1179 PyErr_SetString(PyExc_IndexError, "deque index out of range");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001180 return NULL;
1181 }
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001182
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 if (i == 0) {
1184 i = deque->leftindex;
1185 b = deque->leftblock;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001186 } else if (i == Py_SIZE(deque) - 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001187 i = deque->rightindex;
1188 b = deque->rightblock;
1189 } else {
1190 i += deque->leftindex;
Raymond Hettingerc2083082015-02-28 23:29:16 -08001191 n = (Py_ssize_t)((size_t) i / BLOCKLEN);
1192 i = (Py_ssize_t)((size_t) i % BLOCKLEN);
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001193 if (index < (Py_SIZE(deque) >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 b = deque->leftblock;
1195 while (n--)
1196 b = b->rightlink;
1197 } else {
Raymond Hettinger63d1ff22015-02-28 07:41:30 -08001198 n = (Py_ssize_t)(
Raymond Hettingerc2083082015-02-28 23:29:16 -08001199 ((size_t)(deque->leftindex + Py_SIZE(deque) - 1))
Raymond Hettinger63d1ff22015-02-28 07:41:30 -08001200 / BLOCKLEN - n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001201 b = deque->rightblock;
1202 while (n--)
1203 b = b->leftlink;
1204 }
1205 }
1206 item = b->data[i];
1207 Py_INCREF(item);
1208 return item;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001209}
1210
1211static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001212deque_del_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001213{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001214 PyObject *item;
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001215 int rv;
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001216
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001217 assert (i >= 0 && i < Py_SIZE(deque));
Raymond Hettinger6921c132015-03-21 02:03:40 -07001218 if (_deque_rotate(deque, -i))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001219 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001220 item = deque_popleft(deque, NULL);
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001221 rv = _deque_rotate(deque, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001222 assert (item != NULL);
1223 Py_DECREF(item);
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001224 return rv;
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001225}
1226
1227static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001228deque_ass_item(dequeobject *deque, Py_ssize_t i, PyObject *v)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001229{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001230 PyObject *old_value;
1231 block *b;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001232 Py_ssize_t n, len=Py_SIZE(deque), halflen=(len+1)>>1, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001233
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001234 if (!valid_index(i, len)) {
1235 PyErr_SetString(PyExc_IndexError, "deque index out of range");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001236 return -1;
1237 }
1238 if (v == NULL)
1239 return deque_del_item(deque, i);
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001241 i += deque->leftindex;
Raymond Hettingerc2083082015-02-28 23:29:16 -08001242 n = (Py_ssize_t)((size_t) i / BLOCKLEN);
1243 i = (Py_ssize_t)((size_t) i % BLOCKLEN);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001244 if (index <= halflen) {
1245 b = deque->leftblock;
1246 while (n--)
1247 b = b->rightlink;
1248 } else {
Raymond Hettingera473b9d2015-02-28 17:49:47 -08001249 n = (Py_ssize_t)(
Raymond Hettingerc2083082015-02-28 23:29:16 -08001250 ((size_t)(deque->leftindex + Py_SIZE(deque) - 1))
Raymond Hettingera473b9d2015-02-28 17:49:47 -08001251 / BLOCKLEN - n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001252 b = deque->rightblock;
1253 while (n--)
1254 b = b->leftlink;
1255 }
1256 Py_INCREF(v);
1257 old_value = b->data[i];
1258 b->data[i] = v;
1259 Py_DECREF(old_value);
1260 return 0;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001261}
1262
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001263static void
1264deque_dealloc(dequeobject *deque)
1265{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001266 PyObject_GC_UnTrack(deque);
1267 if (deque->weakreflist != NULL)
1268 PyObject_ClearWeakRefs((PyObject *) deque);
1269 if (deque->leftblock != NULL) {
1270 deque_clear(deque);
1271 assert(deque->leftblock != NULL);
1272 freeblock(deque->leftblock);
1273 }
1274 deque->leftblock = NULL;
1275 deque->rightblock = NULL;
1276 Py_TYPE(deque)->tp_free(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001277}
1278
1279static int
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001280deque_traverse(dequeobject *deque, visitproc visit, void *arg)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001281{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001282 block *b;
1283 PyObject *item;
1284 Py_ssize_t index;
1285 Py_ssize_t indexlo = deque->leftindex;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001286
Raymond Hettinger5bfa8672013-07-06 11:58:09 -10001287 for (b = deque->leftblock; b != deque->rightblock; b = b->rightlink) {
1288 for (index = indexlo; index < BLOCKLEN ; index++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001289 item = b->data[index];
1290 Py_VISIT(item);
1291 }
1292 indexlo = 0;
1293 }
Raymond Hettinger5bfa8672013-07-06 11:58:09 -10001294 for (index = indexlo; index <= deque->rightindex; index++) {
1295 item = b->data[index];
1296 Py_VISIT(item);
1297 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001298 return 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001299}
1300
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001301static PyObject *
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001302deque_reduce(dequeobject *deque)
1303{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001304 PyObject *dict, *result, *aslist;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001305 _Py_IDENTIFIER(__dict__);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001306
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001307 dict = _PyObject_GetAttrId((PyObject *)deque, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001308 if (dict == NULL)
1309 PyErr_Clear();
1310 aslist = PySequence_List((PyObject *)deque);
1311 if (aslist == NULL) {
1312 Py_XDECREF(dict);
1313 return NULL;
1314 }
1315 if (dict == NULL) {
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -07001316 if (deque->maxlen < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001317 result = Py_BuildValue("O(O)", Py_TYPE(deque), aslist);
1318 else
1319 result = Py_BuildValue("O(On)", Py_TYPE(deque), aslist, deque->maxlen);
1320 } else {
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -07001321 if (deque->maxlen < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001322 result = Py_BuildValue("O(OO)O", Py_TYPE(deque), aslist, Py_None, dict);
1323 else
1324 result = Py_BuildValue("O(On)O", Py_TYPE(deque), aslist, deque->maxlen, dict);
1325 }
1326 Py_XDECREF(dict);
1327 Py_DECREF(aslist);
1328 return result;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001329}
1330
1331PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
1332
1333static PyObject *
1334deque_repr(PyObject *deque)
1335{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336 PyObject *aslist, *result;
1337 int i;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001339 i = Py_ReprEnter(deque);
1340 if (i != 0) {
1341 if (i < 0)
1342 return NULL;
1343 return PyUnicode_FromString("[...]");
1344 }
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001346 aslist = PySequence_List(deque);
1347 if (aslist == NULL) {
1348 Py_ReprLeave(deque);
1349 return NULL;
1350 }
Raymond Hettingera7f630092015-10-10 23:56:02 -04001351 if (((dequeobject *)deque)->maxlen >= 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001352 result = PyUnicode_FromFormat("deque(%R, maxlen=%zd)",
1353 aslist, ((dequeobject *)deque)->maxlen);
1354 else
1355 result = PyUnicode_FromFormat("deque(%R)", aslist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001356 Py_ReprLeave(deque);
Raymond Hettinger2b2b7532015-09-05 17:05:52 -07001357 Py_DECREF(aslist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001358 return result;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001359}
1360
Raymond Hettinger738ec902004-02-29 02:15:56 +00001361static PyObject *
1362deque_richcompare(PyObject *v, PyObject *w, int op)
1363{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001364 PyObject *it1=NULL, *it2=NULL, *x, *y;
1365 Py_ssize_t vs, ws;
1366 int b, cmp=-1;
Raymond Hettinger738ec902004-02-29 02:15:56 +00001367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001368 if (!PyObject_TypeCheck(v, &deque_type) ||
1369 !PyObject_TypeCheck(w, &deque_type)) {
Brian Curtindfc80e32011-08-10 20:28:54 -05001370 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001371 }
Raymond Hettinger738ec902004-02-29 02:15:56 +00001372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001373 /* Shortcuts */
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001374 vs = Py_SIZE((dequeobject *)v);
1375 ws = Py_SIZE((dequeobject *)w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001376 if (op == Py_EQ) {
1377 if (v == w)
1378 Py_RETURN_TRUE;
1379 if (vs != ws)
1380 Py_RETURN_FALSE;
1381 }
1382 if (op == Py_NE) {
1383 if (v == w)
1384 Py_RETURN_FALSE;
1385 if (vs != ws)
1386 Py_RETURN_TRUE;
1387 }
Raymond Hettinger738ec902004-02-29 02:15:56 +00001388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001389 /* Search for the first index where items are different */
1390 it1 = PyObject_GetIter(v);
1391 if (it1 == NULL)
1392 goto done;
1393 it2 = PyObject_GetIter(w);
1394 if (it2 == NULL)
1395 goto done;
1396 for (;;) {
1397 x = PyIter_Next(it1);
1398 if (x == NULL && PyErr_Occurred())
1399 goto done;
1400 y = PyIter_Next(it2);
1401 if (x == NULL || y == NULL)
1402 break;
1403 b = PyObject_RichCompareBool(x, y, Py_EQ);
1404 if (b == 0) {
1405 cmp = PyObject_RichCompareBool(x, y, op);
1406 Py_DECREF(x);
1407 Py_DECREF(y);
1408 goto done;
1409 }
1410 Py_DECREF(x);
1411 Py_DECREF(y);
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -07001412 if (b < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001413 goto done;
1414 }
1415 /* We reached the end of one deque or both */
1416 Py_XDECREF(x);
1417 Py_XDECREF(y);
1418 if (PyErr_Occurred())
1419 goto done;
1420 switch (op) {
1421 case Py_LT: cmp = y != NULL; break; /* if w was longer */
1422 case Py_LE: cmp = x == NULL; break; /* if v was not longer */
1423 case Py_EQ: cmp = x == y; break; /* if we reached the end of both */
1424 case Py_NE: cmp = x != y; break; /* if one deque continues */
1425 case Py_GT: cmp = x != NULL; break; /* if v was longer */
1426 case Py_GE: cmp = y == NULL; break; /* if w was not longer */
1427 }
Tim Peters1065f752004-10-01 01:03:29 +00001428
Raymond Hettinger738ec902004-02-29 02:15:56 +00001429done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001430 Py_XDECREF(it1);
1431 Py_XDECREF(it2);
1432 if (cmp == 1)
1433 Py_RETURN_TRUE;
1434 if (cmp == 0)
1435 Py_RETURN_FALSE;
1436 return NULL;
Raymond Hettinger738ec902004-02-29 02:15:56 +00001437}
1438
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001439static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001440deque_init(dequeobject *deque, PyObject *args, PyObject *kwdargs)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001441{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001442 PyObject *iterable = NULL;
1443 PyObject *maxlenobj = NULL;
1444 Py_ssize_t maxlen = -1;
1445 char *kwlist[] = {"iterable", "maxlen", 0};
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001446
Raymond Hettinger0d309402015-09-30 23:15:02 -07001447 if (kwdargs == NULL) {
1448 if (!PyArg_UnpackTuple(args, "deque()", 0, 2, &iterable, &maxlenobj))
1449 return -1;
1450 } else {
1451 if (!PyArg_ParseTupleAndKeywords(args, kwdargs, "|OO:deque", kwlist,
1452 &iterable, &maxlenobj))
1453 return -1;
1454 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001455 if (maxlenobj != NULL && maxlenobj != Py_None) {
1456 maxlen = PyLong_AsSsize_t(maxlenobj);
1457 if (maxlen == -1 && PyErr_Occurred())
1458 return -1;
1459 if (maxlen < 0) {
1460 PyErr_SetString(PyExc_ValueError, "maxlen must be non-negative");
1461 return -1;
1462 }
1463 }
1464 deque->maxlen = maxlen;
Raymond Hettinger0d309402015-09-30 23:15:02 -07001465 if (Py_SIZE(deque) > 0)
1466 deque_clear(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001467 if (iterable != NULL) {
1468 PyObject *rv = deque_extend(deque, iterable);
1469 if (rv == NULL)
1470 return -1;
1471 Py_DECREF(rv);
1472 }
1473 return 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001474}
1475
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001476static PyObject *
Jesus Cea16e2fca2012-08-03 14:49:42 +02001477deque_sizeof(dequeobject *deque, void *unused)
1478{
1479 Py_ssize_t res;
1480 Py_ssize_t blocks;
1481
1482 res = sizeof(dequeobject);
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001483 blocks = (deque->leftindex + Py_SIZE(deque) + BLOCKLEN - 1) / BLOCKLEN;
1484 assert(deque->leftindex + Py_SIZE(deque) - 1 ==
Jesus Cea16e2fca2012-08-03 14:49:42 +02001485 (blocks - 1) * BLOCKLEN + deque->rightindex);
1486 res += blocks * sizeof(block);
1487 return PyLong_FromSsize_t(res);
1488}
1489
1490PyDoc_STRVAR(sizeof_doc,
1491"D.__sizeof__() -- size of D in memory, in bytes");
1492
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001493static int
1494deque_bool(dequeobject *deque)
1495{
1496 return Py_SIZE(deque) != 0;
1497}
1498
Jesus Cea16e2fca2012-08-03 14:49:42 +02001499static PyObject *
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001500deque_get_maxlen(dequeobject *deque)
1501{
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -07001502 if (deque->maxlen < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001503 Py_RETURN_NONE;
1504 return PyLong_FromSsize_t(deque->maxlen);
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001505}
1506
Raymond Hettinger41290a62015-03-31 08:12:23 -07001507
1508/* deque object ********************************************************/
1509
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001510static PyGetSetDef deque_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001511 {"maxlen", (getter)deque_get_maxlen, (setter)NULL,
1512 "maximum size of a deque or None if unbounded"},
1513 {0}
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001514};
1515
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001516static PySequenceMethods deque_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001517 (lenfunc)deque_len, /* sq_length */
Raymond Hettinger41290a62015-03-31 08:12:23 -07001518 (binaryfunc)deque_concat, /* sq_concat */
1519 (ssizeargfunc)deque_repeat, /* sq_repeat */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001520 (ssizeargfunc)deque_item, /* sq_item */
1521 0, /* sq_slice */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001522 (ssizeobjargproc)deque_ass_item, /* sq_ass_item */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001523 0, /* sq_ass_slice */
Raymond Hettinger39dadf72015-03-20 16:38:56 -07001524 (objobjproc)deque_contains, /* sq_contains */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001525 (binaryfunc)deque_inplace_concat, /* sq_inplace_concat */
Raymond Hettinger41290a62015-03-31 08:12:23 -07001526 (ssizeargfunc)deque_inplace_repeat, /* sq_inplace_repeat */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001527};
1528
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001529static PyNumberMethods deque_as_number = {
1530 0, /* nb_add */
1531 0, /* nb_subtract */
1532 0, /* nb_multiply */
1533 0, /* nb_remainder */
1534 0, /* nb_divmod */
1535 0, /* nb_power */
1536 0, /* nb_negative */
1537 0, /* nb_positive */
1538 0, /* nb_absolute */
1539 (inquiry)deque_bool, /* nb_bool */
1540 0, /* nb_invert */
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001541 };
1542
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001543static PyObject *deque_iter(dequeobject *deque);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001544static PyObject *deque_reviter(dequeobject *deque);
Tim Peters1065f752004-10-01 01:03:29 +00001545PyDoc_STRVAR(reversed_doc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001546 "D.__reversed__() -- return a reverse iterator over the deque");
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001547
1548static PyMethodDef deque_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001549 {"append", (PyCFunction)deque_append,
1550 METH_O, append_doc},
1551 {"appendleft", (PyCFunction)deque_appendleft,
1552 METH_O, appendleft_doc},
1553 {"clear", (PyCFunction)deque_clearmethod,
1554 METH_NOARGS, clear_doc},
1555 {"__copy__", (PyCFunction)deque_copy,
1556 METH_NOARGS, copy_doc},
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001557 {"copy", (PyCFunction)deque_copy,
1558 METH_NOARGS, copy_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001559 {"count", (PyCFunction)deque_count,
Raymond Hettinger0f6f9472015-03-21 01:42:10 -07001560 METH_O, count_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001561 {"extend", (PyCFunction)deque_extend,
1562 METH_O, extend_doc},
1563 {"extendleft", (PyCFunction)deque_extendleft,
1564 METH_O, extendleft_doc},
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001565 {"index", (PyCFunction)deque_index,
1566 METH_VARARGS, index_doc},
1567 {"insert", (PyCFunction)deque_insert,
1568 METH_VARARGS, insert_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001569 {"pop", (PyCFunction)deque_pop,
1570 METH_NOARGS, pop_doc},
1571 {"popleft", (PyCFunction)deque_popleft,
1572 METH_NOARGS, popleft_doc},
Raymond Hettinger0f6f9472015-03-21 01:42:10 -07001573 {"__reduce__", (PyCFunction)deque_reduce,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001574 METH_NOARGS, reduce_doc},
1575 {"remove", (PyCFunction)deque_remove,
1576 METH_O, remove_doc},
1577 {"__reversed__", (PyCFunction)deque_reviter,
1578 METH_NOARGS, reversed_doc},
1579 {"reverse", (PyCFunction)deque_reverse,
1580 METH_NOARGS, reverse_doc},
1581 {"rotate", (PyCFunction)deque_rotate,
Jesus Cea16e2fca2012-08-03 14:49:42 +02001582 METH_VARARGS, rotate_doc},
1583 {"__sizeof__", (PyCFunction)deque_sizeof,
1584 METH_NOARGS, sizeof_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001585 {NULL, NULL} /* sentinel */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001586};
1587
1588PyDoc_STRVAR(deque_doc,
Andrew Svetlov6a5c7c32012-10-31 11:50:40 +02001589"deque([iterable[, maxlen]]) --> deque object\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001590\n\
Raymond Hettinger41290a62015-03-31 08:12:23 -07001591A list-like sequence optimized for data accesses near its endpoints.");
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001592
Neal Norwitz87f10132004-02-29 15:40:53 +00001593static PyTypeObject deque_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001594 PyVarObject_HEAD_INIT(NULL, 0)
1595 "collections.deque", /* tp_name */
1596 sizeof(dequeobject), /* tp_basicsize */
1597 0, /* tp_itemsize */
1598 /* methods */
1599 (destructor)deque_dealloc, /* tp_dealloc */
1600 0, /* tp_print */
1601 0, /* tp_getattr */
1602 0, /* tp_setattr */
1603 0, /* tp_reserved */
1604 deque_repr, /* tp_repr */
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001605 &deque_as_number, /* tp_as_number */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001606 &deque_as_sequence, /* tp_as_sequence */
1607 0, /* tp_as_mapping */
Georg Brandlf038b322010-10-18 07:35:09 +00001608 PyObject_HashNotImplemented, /* tp_hash */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001609 0, /* tp_call */
1610 0, /* tp_str */
1611 PyObject_GenericGetAttr, /* tp_getattro */
1612 0, /* tp_setattro */
1613 0, /* tp_as_buffer */
1614 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
Georg Brandlf038b322010-10-18 07:35:09 +00001615 /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001616 deque_doc, /* tp_doc */
1617 (traverseproc)deque_traverse, /* tp_traverse */
1618 (inquiry)deque_clear, /* tp_clear */
1619 (richcmpfunc)deque_richcompare, /* tp_richcompare */
Georg Brandlf038b322010-10-18 07:35:09 +00001620 offsetof(dequeobject, weakreflist), /* tp_weaklistoffset*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001621 (getiterfunc)deque_iter, /* tp_iter */
1622 0, /* tp_iternext */
1623 deque_methods, /* tp_methods */
1624 0, /* tp_members */
Georg Brandlf038b322010-10-18 07:35:09 +00001625 deque_getset, /* tp_getset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001626 0, /* tp_base */
1627 0, /* tp_dict */
1628 0, /* tp_descr_get */
1629 0, /* tp_descr_set */
1630 0, /* tp_dictoffset */
1631 (initproc)deque_init, /* tp_init */
1632 PyType_GenericAlloc, /* tp_alloc */
1633 deque_new, /* tp_new */
1634 PyObject_GC_Del, /* tp_free */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001635};
1636
1637/*********************** Deque Iterator **************************/
1638
1639typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001640 PyObject_HEAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001641 block *b;
Raymond Hettinger87e69122015-03-02 23:32:02 -08001642 Py_ssize_t index;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001643 dequeobject *deque;
Raymond Hettingerf9d9c792015-03-02 22:47:46 -08001644 size_t state; /* state when the iterator is created */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001645 Py_ssize_t counter; /* number of items remaining for iteration */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001646} dequeiterobject;
1647
Martin v. Löwis59683e82008-06-13 07:50:45 +00001648static PyTypeObject dequeiter_type;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001649
1650static PyObject *
1651deque_iter(dequeobject *deque)
1652{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001653 dequeiterobject *it;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001655 it = PyObject_GC_New(dequeiterobject, &dequeiter_type);
1656 if (it == NULL)
1657 return NULL;
1658 it->b = deque->leftblock;
1659 it->index = deque->leftindex;
1660 Py_INCREF(deque);
1661 it->deque = deque;
1662 it->state = deque->state;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001663 it->counter = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001664 PyObject_GC_Track(it);
1665 return (PyObject *)it;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001666}
1667
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001668static int
1669dequeiter_traverse(dequeiterobject *dio, visitproc visit, void *arg)
1670{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001671 Py_VISIT(dio->deque);
1672 return 0;
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001673}
1674
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001675static void
1676dequeiter_dealloc(dequeiterobject *dio)
1677{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001678 Py_XDECREF(dio->deque);
1679 PyObject_GC_Del(dio);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001680}
1681
1682static PyObject *
1683dequeiter_next(dequeiterobject *it)
1684{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001685 PyObject *item;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001686
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001687 if (it->deque->state != it->state) {
1688 it->counter = 0;
1689 PyErr_SetString(PyExc_RuntimeError,
1690 "deque mutated during iteration");
1691 return NULL;
1692 }
1693 if (it->counter == 0)
1694 return NULL;
1695 assert (!(it->b == it->deque->rightblock &&
1696 it->index > it->deque->rightindex));
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001697
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001698 item = it->b->data[it->index];
1699 it->index++;
1700 it->counter--;
1701 if (it->index == BLOCKLEN && it->counter > 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -10001702 CHECK_NOT_END(it->b->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001703 it->b = it->b->rightlink;
1704 it->index = 0;
1705 }
1706 Py_INCREF(item);
1707 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001708}
1709
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001710static PyObject *
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001711dequeiter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1712{
1713 Py_ssize_t i, index=0;
1714 PyObject *deque;
1715 dequeiterobject *it;
1716 if (!PyArg_ParseTuple(args, "O!|n", &deque_type, &deque, &index))
1717 return NULL;
1718 assert(type == &dequeiter_type);
1719
1720 it = (dequeiterobject*)deque_iter((dequeobject *)deque);
1721 if (!it)
1722 return NULL;
1723 /* consume items from the queue */
1724 for(i=0; i<index; i++) {
1725 PyObject *item = dequeiter_next(it);
1726 if (item) {
1727 Py_DECREF(item);
1728 } else {
1729 if (it->counter) {
1730 Py_DECREF(it);
1731 return NULL;
1732 } else
1733 break;
1734 }
1735 }
1736 return (PyObject*)it;
1737}
1738
1739static PyObject *
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001740dequeiter_len(dequeiterobject *it)
1741{
Antoine Pitrou554f3342010-08-17 18:30:06 +00001742 return PyLong_FromSsize_t(it->counter);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001743}
1744
Armin Rigof5b3e362006-02-11 21:32:43 +00001745PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001746
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001747static PyObject *
1748dequeiter_reduce(dequeiterobject *it)
1749{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001750 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 +00001751}
1752
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001753static PyMethodDef dequeiter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001754 {"__length_hint__", (PyCFunction)dequeiter_len, METH_NOARGS, length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001755 {"__reduce__", (PyCFunction)dequeiter_reduce, METH_NOARGS, reduce_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001756 {NULL, NULL} /* sentinel */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001757};
1758
Martin v. Löwis59683e82008-06-13 07:50:45 +00001759static PyTypeObject dequeiter_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001760 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger87e69122015-03-02 23:32:02 -08001761 "_collections._deque_iterator", /* tp_name */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001762 sizeof(dequeiterobject), /* tp_basicsize */
1763 0, /* tp_itemsize */
1764 /* methods */
1765 (destructor)dequeiter_dealloc, /* tp_dealloc */
1766 0, /* tp_print */
1767 0, /* tp_getattr */
1768 0, /* tp_setattr */
1769 0, /* tp_reserved */
1770 0, /* tp_repr */
1771 0, /* tp_as_number */
1772 0, /* tp_as_sequence */
1773 0, /* tp_as_mapping */
1774 0, /* tp_hash */
1775 0, /* tp_call */
1776 0, /* tp_str */
1777 PyObject_GenericGetAttr, /* tp_getattro */
1778 0, /* tp_setattro */
1779 0, /* tp_as_buffer */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001780 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001781 0, /* tp_doc */
1782 (traverseproc)dequeiter_traverse, /* tp_traverse */
1783 0, /* tp_clear */
1784 0, /* tp_richcompare */
1785 0, /* tp_weaklistoffset */
1786 PyObject_SelfIter, /* tp_iter */
1787 (iternextfunc)dequeiter_next, /* tp_iternext */
1788 dequeiter_methods, /* tp_methods */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001789 0, /* tp_members */
1790 0, /* tp_getset */
1791 0, /* tp_base */
1792 0, /* tp_dict */
1793 0, /* tp_descr_get */
1794 0, /* tp_descr_set */
1795 0, /* tp_dictoffset */
1796 0, /* tp_init */
1797 0, /* tp_alloc */
1798 dequeiter_new, /* tp_new */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001799 0,
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001800};
1801
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001802/*********************** Deque Reverse Iterator **************************/
1803
Martin v. Löwis59683e82008-06-13 07:50:45 +00001804static PyTypeObject dequereviter_type;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001805
1806static PyObject *
1807deque_reviter(dequeobject *deque)
1808{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001809 dequeiterobject *it;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001811 it = PyObject_GC_New(dequeiterobject, &dequereviter_type);
1812 if (it == NULL)
1813 return NULL;
1814 it->b = deque->rightblock;
1815 it->index = deque->rightindex;
1816 Py_INCREF(deque);
1817 it->deque = deque;
1818 it->state = deque->state;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001819 it->counter = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001820 PyObject_GC_Track(it);
1821 return (PyObject *)it;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001822}
1823
1824static PyObject *
1825dequereviter_next(dequeiterobject *it)
1826{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001827 PyObject *item;
1828 if (it->counter == 0)
1829 return NULL;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001830
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001831 if (it->deque->state != it->state) {
1832 it->counter = 0;
1833 PyErr_SetString(PyExc_RuntimeError,
1834 "deque mutated during iteration");
1835 return NULL;
1836 }
1837 assert (!(it->b == it->deque->leftblock &&
1838 it->index < it->deque->leftindex));
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001839
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001840 item = it->b->data[it->index];
1841 it->index--;
1842 it->counter--;
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -07001843 if (it->index < 0 && it->counter > 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -10001844 CHECK_NOT_END(it->b->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001845 it->b = it->b->leftlink;
1846 it->index = BLOCKLEN - 1;
1847 }
1848 Py_INCREF(item);
1849 return item;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001850}
1851
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001852static PyObject *
1853dequereviter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1854{
1855 Py_ssize_t i, index=0;
1856 PyObject *deque;
1857 dequeiterobject *it;
1858 if (!PyArg_ParseTuple(args, "O!|n", &deque_type, &deque, &index))
1859 return NULL;
1860 assert(type == &dequereviter_type);
1861
1862 it = (dequeiterobject*)deque_reviter((dequeobject *)deque);
1863 if (!it)
1864 return NULL;
1865 /* consume items from the queue */
1866 for(i=0; i<index; i++) {
1867 PyObject *item = dequereviter_next(it);
1868 if (item) {
1869 Py_DECREF(item);
1870 } else {
1871 if (it->counter) {
1872 Py_DECREF(it);
1873 return NULL;
1874 } else
1875 break;
1876 }
1877 }
1878 return (PyObject*)it;
1879}
1880
Martin v. Löwis59683e82008-06-13 07:50:45 +00001881static PyTypeObject dequereviter_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001882 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger87e69122015-03-02 23:32:02 -08001883 "_collections._deque_reverse_iterator", /* tp_name */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001884 sizeof(dequeiterobject), /* tp_basicsize */
1885 0, /* tp_itemsize */
1886 /* methods */
1887 (destructor)dequeiter_dealloc, /* tp_dealloc */
1888 0, /* tp_print */
1889 0, /* tp_getattr */
1890 0, /* tp_setattr */
1891 0, /* tp_reserved */
1892 0, /* tp_repr */
1893 0, /* tp_as_number */
1894 0, /* tp_as_sequence */
1895 0, /* tp_as_mapping */
1896 0, /* tp_hash */
1897 0, /* tp_call */
1898 0, /* tp_str */
1899 PyObject_GenericGetAttr, /* tp_getattro */
1900 0, /* tp_setattro */
1901 0, /* tp_as_buffer */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001902 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001903 0, /* tp_doc */
1904 (traverseproc)dequeiter_traverse, /* tp_traverse */
1905 0, /* tp_clear */
1906 0, /* tp_richcompare */
1907 0, /* tp_weaklistoffset */
1908 PyObject_SelfIter, /* tp_iter */
1909 (iternextfunc)dequereviter_next, /* tp_iternext */
1910 dequeiter_methods, /* tp_methods */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001911 0, /* tp_members */
1912 0, /* tp_getset */
1913 0, /* tp_base */
1914 0, /* tp_dict */
1915 0, /* tp_descr_get */
1916 0, /* tp_descr_set */
1917 0, /* tp_dictoffset */
1918 0, /* tp_init */
1919 0, /* tp_alloc */
1920 dequereviter_new, /* tp_new */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001921 0,
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001922};
1923
Guido van Rossum1968ad32006-02-25 22:38:04 +00001924/* defaultdict type *********************************************************/
1925
1926typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001927 PyDictObject dict;
1928 PyObject *default_factory;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001929} defdictobject;
1930
1931static PyTypeObject defdict_type; /* Forward */
1932
1933PyDoc_STRVAR(defdict_missing_doc,
1934"__missing__(key) # Called by __getitem__ for missing key; pseudo-code:\n\
Guido van Rossumd8faa362007-04-27 19:54:29 +00001935 if self.default_factory is None: raise KeyError((key,))\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00001936 self[key] = value = self.default_factory()\n\
1937 return value\n\
1938");
1939
1940static PyObject *
1941defdict_missing(defdictobject *dd, PyObject *key)
1942{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001943 PyObject *factory = dd->default_factory;
1944 PyObject *value;
1945 if (factory == NULL || factory == Py_None) {
1946 /* XXX Call dict.__missing__(key) */
1947 PyObject *tup;
1948 tup = PyTuple_Pack(1, key);
1949 if (!tup) return NULL;
1950 PyErr_SetObject(PyExc_KeyError, tup);
1951 Py_DECREF(tup);
1952 return NULL;
1953 }
1954 value = PyEval_CallObject(factory, NULL);
1955 if (value == NULL)
1956 return value;
1957 if (PyObject_SetItem((PyObject *)dd, key, value) < 0) {
1958 Py_DECREF(value);
1959 return NULL;
1960 }
1961 return value;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001962}
1963
1964PyDoc_STRVAR(defdict_copy_doc, "D.copy() -> a shallow copy of D.");
1965
1966static PyObject *
1967defdict_copy(defdictobject *dd)
1968{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001969 /* This calls the object's class. That only works for subclasses
1970 whose class constructor has the same signature. Subclasses that
1971 define a different constructor signature must override copy().
1972 */
Raymond Hettinger54628fa2009-08-04 19:16:39 +00001973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001974 if (dd->default_factory == NULL)
1975 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd), Py_None, dd, NULL);
1976 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd),
1977 dd->default_factory, dd, NULL);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001978}
1979
1980static PyObject *
1981defdict_reduce(defdictobject *dd)
1982{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001983 /* __reduce__ must return a 5-tuple as follows:
Guido van Rossum1968ad32006-02-25 22:38:04 +00001984
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001985 - factory function
1986 - tuple of args for the factory function
1987 - additional state (here None)
1988 - sequence iterator (here None)
1989 - dictionary iterator (yielding successive (key, value) pairs
Guido van Rossum1968ad32006-02-25 22:38:04 +00001990
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001991 This API is used by pickle.py and copy.py.
Guido van Rossum1968ad32006-02-25 22:38:04 +00001992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001993 For this to be useful with pickle.py, the default_factory
1994 must be picklable; e.g., None, a built-in, or a global
1995 function in a module or package.
Guido van Rossum1968ad32006-02-25 22:38:04 +00001996
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001997 Both shallow and deep copying are supported, but for deep
1998 copying, the default_factory must be deep-copyable; e.g. None,
1999 or a built-in (functions are not copyable at this time).
Guido van Rossum1968ad32006-02-25 22:38:04 +00002000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002001 This only works for subclasses as long as their constructor
2002 signature is compatible; the first argument must be the
2003 optional default_factory, defaulting to None.
2004 */
2005 PyObject *args;
2006 PyObject *items;
2007 PyObject *iter;
2008 PyObject *result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002009 _Py_IDENTIFIER(items);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002011 if (dd->default_factory == NULL || dd->default_factory == Py_None)
2012 args = PyTuple_New(0);
2013 else
2014 args = PyTuple_Pack(1, dd->default_factory);
2015 if (args == NULL)
2016 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002017 items = _PyObject_CallMethodId((PyObject *)dd, &PyId_items, "()");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002018 if (items == NULL) {
2019 Py_DECREF(args);
2020 return NULL;
2021 }
2022 iter = PyObject_GetIter(items);
2023 if (iter == NULL) {
2024 Py_DECREF(items);
2025 Py_DECREF(args);
2026 return NULL;
2027 }
2028 result = PyTuple_Pack(5, Py_TYPE(dd), args,
2029 Py_None, Py_None, iter);
2030 Py_DECREF(iter);
2031 Py_DECREF(items);
2032 Py_DECREF(args);
2033 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00002034}
2035
2036static PyMethodDef defdict_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002037 {"__missing__", (PyCFunction)defdict_missing, METH_O,
2038 defdict_missing_doc},
2039 {"copy", (PyCFunction)defdict_copy, METH_NOARGS,
2040 defdict_copy_doc},
2041 {"__copy__", (PyCFunction)defdict_copy, METH_NOARGS,
2042 defdict_copy_doc},
2043 {"__reduce__", (PyCFunction)defdict_reduce, METH_NOARGS,
2044 reduce_doc},
2045 {NULL}
Guido van Rossum1968ad32006-02-25 22:38:04 +00002046};
2047
2048static PyMemberDef defdict_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002049 {"default_factory", T_OBJECT,
2050 offsetof(defdictobject, default_factory), 0,
2051 PyDoc_STR("Factory for default value called by __missing__().")},
2052 {NULL}
Guido van Rossum1968ad32006-02-25 22:38:04 +00002053};
2054
2055static void
2056defdict_dealloc(defdictobject *dd)
2057{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002058 Py_CLEAR(dd->default_factory);
2059 PyDict_Type.tp_dealloc((PyObject *)dd);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002060}
2061
Guido van Rossum1968ad32006-02-25 22:38:04 +00002062static PyObject *
2063defdict_repr(defdictobject *dd)
2064{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002065 PyObject *baserepr;
2066 PyObject *defrepr;
2067 PyObject *result;
2068 baserepr = PyDict_Type.tp_repr((PyObject *)dd);
2069 if (baserepr == NULL)
2070 return NULL;
2071 if (dd->default_factory == NULL)
2072 defrepr = PyUnicode_FromString("None");
2073 else
2074 {
2075 int status = Py_ReprEnter(dd->default_factory);
2076 if (status != 0) {
Antoine Pitrouf5f1fe02012-02-15 02:42:46 +01002077 if (status < 0) {
2078 Py_DECREF(baserepr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002079 return NULL;
Antoine Pitrouf5f1fe02012-02-15 02:42:46 +01002080 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002081 defrepr = PyUnicode_FromString("...");
2082 }
2083 else
2084 defrepr = PyObject_Repr(dd->default_factory);
2085 Py_ReprLeave(dd->default_factory);
2086 }
2087 if (defrepr == NULL) {
2088 Py_DECREF(baserepr);
2089 return NULL;
2090 }
2091 result = PyUnicode_FromFormat("defaultdict(%U, %U)",
2092 defrepr, baserepr);
2093 Py_DECREF(defrepr);
2094 Py_DECREF(baserepr);
2095 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00002096}
2097
2098static int
2099defdict_traverse(PyObject *self, visitproc visit, void *arg)
2100{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002101 Py_VISIT(((defdictobject *)self)->default_factory);
2102 return PyDict_Type.tp_traverse(self, visit, arg);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002103}
2104
2105static int
2106defdict_tp_clear(defdictobject *dd)
2107{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002108 Py_CLEAR(dd->default_factory);
2109 return PyDict_Type.tp_clear((PyObject *)dd);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002110}
2111
2112static int
2113defdict_init(PyObject *self, PyObject *args, PyObject *kwds)
2114{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002115 defdictobject *dd = (defdictobject *)self;
2116 PyObject *olddefault = dd->default_factory;
2117 PyObject *newdefault = NULL;
2118 PyObject *newargs;
2119 int result;
2120 if (args == NULL || !PyTuple_Check(args))
2121 newargs = PyTuple_New(0);
2122 else {
2123 Py_ssize_t n = PyTuple_GET_SIZE(args);
2124 if (n > 0) {
2125 newdefault = PyTuple_GET_ITEM(args, 0);
2126 if (!PyCallable_Check(newdefault) && newdefault != Py_None) {
2127 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger239aba72015-07-20 03:09:22 -04002128 "first argument must be callable or None");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002129 return -1;
2130 }
2131 }
2132 newargs = PySequence_GetSlice(args, 1, n);
2133 }
2134 if (newargs == NULL)
2135 return -1;
2136 Py_XINCREF(newdefault);
2137 dd->default_factory = newdefault;
2138 result = PyDict_Type.tp_init(self, newargs, kwds);
2139 Py_DECREF(newargs);
2140 Py_XDECREF(olddefault);
2141 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00002142}
2143
2144PyDoc_STRVAR(defdict_doc,
Benjamin Peterson9cb33b72014-01-13 23:56:05 -05002145"defaultdict(default_factory[, ...]) --> dict with default factory\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00002146\n\
2147The default factory is called without arguments to produce\n\
2148a new value when a key is not present, in __getitem__ only.\n\
2149A defaultdict compares equal to a dict with the same items.\n\
Benjamin Peterson9cb33b72014-01-13 23:56:05 -05002150All remaining arguments are treated the same as if they were\n\
2151passed to the dict constructor, including keyword arguments.\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00002152");
2153
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002154/* See comment in xxsubtype.c */
2155#define DEFERRED_ADDRESS(ADDR) 0
2156
Guido van Rossum1968ad32006-02-25 22:38:04 +00002157static PyTypeObject defdict_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002158 PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0)
2159 "collections.defaultdict", /* tp_name */
2160 sizeof(defdictobject), /* tp_basicsize */
2161 0, /* tp_itemsize */
2162 /* methods */
2163 (destructor)defdict_dealloc, /* tp_dealloc */
2164 0, /* tp_print */
2165 0, /* tp_getattr */
2166 0, /* tp_setattr */
2167 0, /* tp_reserved */
2168 (reprfunc)defdict_repr, /* tp_repr */
2169 0, /* tp_as_number */
2170 0, /* tp_as_sequence */
2171 0, /* tp_as_mapping */
2172 0, /* tp_hash */
2173 0, /* tp_call */
2174 0, /* tp_str */
2175 PyObject_GenericGetAttr, /* tp_getattro */
2176 0, /* tp_setattro */
2177 0, /* tp_as_buffer */
2178 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
2179 /* tp_flags */
2180 defdict_doc, /* tp_doc */
2181 defdict_traverse, /* tp_traverse */
2182 (inquiry)defdict_tp_clear, /* tp_clear */
2183 0, /* tp_richcompare */
2184 0, /* tp_weaklistoffset*/
2185 0, /* tp_iter */
2186 0, /* tp_iternext */
2187 defdict_methods, /* tp_methods */
2188 defdict_members, /* tp_members */
2189 0, /* tp_getset */
2190 DEFERRED_ADDRESS(&PyDict_Type), /* tp_base */
2191 0, /* tp_dict */
2192 0, /* tp_descr_get */
2193 0, /* tp_descr_set */
2194 0, /* tp_dictoffset */
2195 defdict_init, /* tp_init */
2196 PyType_GenericAlloc, /* tp_alloc */
2197 0, /* tp_new */
2198 PyObject_GC_Del, /* tp_free */
Guido van Rossum1968ad32006-02-25 22:38:04 +00002199};
2200
Raymond Hettinger96f34102010-12-15 16:30:37 +00002201/* helper function for Counter *********************************************/
2202
2203PyDoc_STRVAR(_count_elements_doc,
2204"_count_elements(mapping, iterable) -> None\n\
2205\n\
2206Count elements in the iterable, updating the mappping");
2207
2208static PyObject *
2209_count_elements(PyObject *self, PyObject *args)
2210{
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002211 _Py_IDENTIFIER(get);
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002212 _Py_IDENTIFIER(__setitem__);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002213 PyObject *it, *iterable, *mapping, *oldval;
2214 PyObject *newval = NULL;
2215 PyObject *key = NULL;
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002216 PyObject *zero = NULL;
Raymond Hettinger96f34102010-12-15 16:30:37 +00002217 PyObject *one = NULL;
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002218 PyObject *bound_get = NULL;
2219 PyObject *mapping_get;
2220 PyObject *dict_get;
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002221 PyObject *mapping_setitem;
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002222 PyObject *dict_setitem;
Raymond Hettinger96f34102010-12-15 16:30:37 +00002223
2224 if (!PyArg_UnpackTuple(args, "_count_elements", 2, 2, &mapping, &iterable))
2225 return NULL;
2226
Raymond Hettinger96f34102010-12-15 16:30:37 +00002227 it = PyObject_GetIter(iterable);
2228 if (it == NULL)
2229 return NULL;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002230
Raymond Hettinger96f34102010-12-15 16:30:37 +00002231 one = PyLong_FromLong(1);
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002232 if (one == NULL)
2233 goto done;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002234
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002235 /* Only take the fast path when get() and __setitem__()
2236 * have not been overridden.
2237 */
2238 mapping_get = _PyType_LookupId(Py_TYPE(mapping), &PyId_get);
2239 dict_get = _PyType_LookupId(&PyDict_Type, &PyId_get);
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002240 mapping_setitem = _PyType_LookupId(Py_TYPE(mapping), &PyId___setitem__);
2241 dict_setitem = _PyType_LookupId(&PyDict_Type, &PyId___setitem__);
2242
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002243 if (mapping_get != NULL && mapping_get == dict_get &&
2244 mapping_setitem != NULL && mapping_setitem == dict_setitem) {
Raymond Hettinger426e0522011-01-03 02:12:02 +00002245 while (1) {
Raymond Hettinger507d9972014-05-18 21:32:40 +01002246 /* Fast path advantages:
2247 1. Eliminate double hashing
2248 (by re-using the same hash for both the get and set)
2249 2. Avoid argument overhead of PyObject_CallFunctionObjArgs
2250 (argument tuple creation and parsing)
2251 3. Avoid indirection through a bound method object
2252 (creates another argument tuple)
2253 4. Avoid initial increment from zero
2254 (reuse an existing one-object instead)
2255 */
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002256 Py_hash_t hash;
2257
Raymond Hettinger426e0522011-01-03 02:12:02 +00002258 key = PyIter_Next(it);
Victor Stinnera154b5c2011-04-20 23:23:52 +02002259 if (key == NULL)
2260 break;
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002261
2262 if (!PyUnicode_CheckExact(key) ||
2263 (hash = ((PyASCIIObject *) key)->hash) == -1)
2264 {
2265 hash = PyObject_Hash(key);
Raymond Hettingerda2850f2015-02-27 12:42:54 -08002266 if (hash == -1)
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002267 goto done;
2268 }
2269
2270 oldval = _PyDict_GetItem_KnownHash(mapping, key, hash);
Raymond Hettinger426e0522011-01-03 02:12:02 +00002271 if (oldval == NULL) {
Raymond Hettinger28c995d2015-08-14 02:07:41 -07002272 if (_PyDict_SetItem_KnownHash(mapping, key, one, hash) < 0)
Raymond Hettinger507d9972014-05-18 21:32:40 +01002273 goto done;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002274 } else {
2275 newval = PyNumber_Add(oldval, one);
2276 if (newval == NULL)
Raymond Hettinger507d9972014-05-18 21:32:40 +01002277 goto done;
Raymond Hettinger28c995d2015-08-14 02:07:41 -07002278 if (_PyDict_SetItem_KnownHash(mapping, key, newval, hash) < 0)
Raymond Hettinger507d9972014-05-18 21:32:40 +01002279 goto done;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002280 Py_CLEAR(newval);
2281 }
2282 Py_DECREF(key);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002283 }
Raymond Hettinger426e0522011-01-03 02:12:02 +00002284 } else {
Victor Stinnere7f516c2013-11-06 23:52:55 +01002285 bound_get = _PyObject_GetAttrId(mapping, &PyId_get);
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002286 if (bound_get == NULL)
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002287 goto done;
2288
2289 zero = PyLong_FromLong(0);
2290 if (zero == NULL)
2291 goto done;
2292
Raymond Hettinger426e0522011-01-03 02:12:02 +00002293 while (1) {
2294 key = PyIter_Next(it);
Victor Stinnera154b5c2011-04-20 23:23:52 +02002295 if (key == NULL)
2296 break;
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002297 oldval = PyObject_CallFunctionObjArgs(bound_get, key, zero, NULL);
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002298 if (oldval == NULL)
2299 break;
2300 newval = PyNumber_Add(oldval, one);
2301 Py_DECREF(oldval);
2302 if (newval == NULL)
2303 break;
Raymond Hettinger28c995d2015-08-14 02:07:41 -07002304 if (PyObject_SetItem(mapping, key, newval) < 0)
Raymond Hettinger96f34102010-12-15 16:30:37 +00002305 break;
2306 Py_CLEAR(newval);
Raymond Hettinger426e0522011-01-03 02:12:02 +00002307 Py_DECREF(key);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002308 }
Raymond Hettinger96f34102010-12-15 16:30:37 +00002309 }
Raymond Hettinger426e0522011-01-03 02:12:02 +00002310
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002311done:
Raymond Hettinger96f34102010-12-15 16:30:37 +00002312 Py_DECREF(it);
2313 Py_XDECREF(key);
2314 Py_XDECREF(newval);
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002315 Py_XDECREF(bound_get);
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002316 Py_XDECREF(zero);
2317 Py_XDECREF(one);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002318 if (PyErr_Occurred())
2319 return NULL;
2320 Py_RETURN_NONE;
2321}
2322
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002323/* module level code ********************************************************/
2324
2325PyDoc_STRVAR(module_doc,
Guido van Rossum1968ad32006-02-25 22:38:04 +00002326"High performance data structures.\n\
2327- deque: ordered collection accessible from endpoints only\n\
2328- defaultdict: dict subclass with a default value factory\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002329");
2330
Raymond Hettinger96f34102010-12-15 16:30:37 +00002331static struct PyMethodDef module_functions[] = {
2332 {"_count_elements", _count_elements, METH_VARARGS, _count_elements_doc},
2333 {NULL, NULL} /* sentinel */
2334};
Martin v. Löwis1a214512008-06-11 05:26:20 +00002335
2336static struct PyModuleDef _collectionsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002337 PyModuleDef_HEAD_INIT,
2338 "_collections",
2339 module_doc,
2340 -1,
Raymond Hettinger96f34102010-12-15 16:30:37 +00002341 module_functions,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002342 NULL,
2343 NULL,
2344 NULL,
2345 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002346};
2347
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002348PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002349PyInit__collections(void)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002350{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002351 PyObject *m;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002353 m = PyModule_Create(&_collectionsmodule);
2354 if (m == NULL)
2355 return NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002357 if (PyType_Ready(&deque_type) < 0)
2358 return NULL;
2359 Py_INCREF(&deque_type);
2360 PyModule_AddObject(m, "deque", (PyObject *)&deque_type);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002362 defdict_type.tp_base = &PyDict_Type;
2363 if (PyType_Ready(&defdict_type) < 0)
2364 return NULL;
2365 Py_INCREF(&defdict_type);
2366 PyModule_AddObject(m, "defaultdict", (PyObject *)&defdict_type);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002367
Eric Snow47db7172015-05-29 22:21:39 -06002368 Py_INCREF(&PyODict_Type);
2369 PyModule_AddObject(m, "OrderedDict", (PyObject *)&PyODict_Type);
2370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002371 if (PyType_Ready(&dequeiter_type) < 0)
2372 return NULL;
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002373 Py_INCREF(&dequeiter_type);
2374 PyModule_AddObject(m, "_deque_iterator", (PyObject *)&dequeiter_type);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002376 if (PyType_Ready(&dequereviter_type) < 0)
2377 return NULL;
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002378 Py_INCREF(&dequereviter_type);
2379 PyModule_AddObject(m, "_deque_reverse_iterator", (PyObject *)&dequereviter_type);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00002380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002381 return m;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002382}