blob: e3d1910b9f8d7a532ba6184ceca00651031c1490 [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
113/* A simple freelisting scheme is used to minimize calls to the memory
Raymond Hettinger551350a2015-03-24 00:19:53 -0700114 allocator. It accommodates common use cases where new blocks are being
Raymond Hettinger82df9252013-07-07 01:43:42 -1000115 added at about the same rate as old blocks are being freed.
116 */
117
Raymond Hettingerf2b02ce2015-09-26 17:47:02 -0700118#define MAXFREEBLOCKS 16
Benjamin Petersond6313712008-07-31 16:23:04 +0000119static Py_ssize_t numfreeblocks = 0;
Guido van Rossum58da9312007-11-10 23:39:45 +0000120static block *freeblocks[MAXFREEBLOCKS];
121
Tim Peters6f853562004-10-01 01:04:50 +0000122static block *
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700123newblock(void) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000124 block *b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000125 if (numfreeblocks) {
Raymond Hettinger59cf23a2013-02-07 00:57:19 -0500126 numfreeblocks--;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000127 return freeblocks[numfreeblocks];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000128 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000129 b = PyMem_Malloc(sizeof(block));
130 if (b != NULL) {
131 return b;
132 }
133 PyErr_NoMemory();
134 return NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000135}
136
Martin v. Löwis59683e82008-06-13 07:50:45 +0000137static void
Guido van Rossum58da9312007-11-10 23:39:45 +0000138freeblock(block *b)
139{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000140 if (numfreeblocks < MAXFREEBLOCKS) {
141 freeblocks[numfreeblocks] = b;
142 numfreeblocks++;
143 } else {
144 PyMem_Free(b);
145 }
Guido van Rossum58da9312007-11-10 23:39:45 +0000146}
147
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000148static PyObject *
149deque_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
150{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000151 dequeobject *deque;
152 block *b;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000154 /* create dequeobject structure */
155 deque = (dequeobject *)type->tp_alloc(type, 0);
156 if (deque == NULL)
157 return NULL;
Tim Peters1065f752004-10-01 01:03:29 +0000158
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700159 b = newblock();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000160 if (b == NULL) {
161 Py_DECREF(deque);
162 return NULL;
163 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000164 MARK_END(b->leftlink);
165 MARK_END(b->rightlink);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000167 assert(BLOCKLEN >= 2);
Raymond Hettinger87e69122015-03-02 23:32:02 -0800168 Py_SIZE(deque) = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000169 deque->leftblock = b;
170 deque->rightblock = b;
171 deque->leftindex = CENTER + 1;
172 deque->rightindex = CENTER;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000173 deque->state = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000174 deque->maxlen = -1;
Raymond Hettinger87e69122015-03-02 23:32:02 -0800175 deque->weakreflist = NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000176
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000177 return (PyObject *)deque;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000178}
179
180static PyObject *
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000181deque_pop(dequeobject *deque, PyObject *unused)
182{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000183 PyObject *item;
184 block *prevblock;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000185
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000186 if (Py_SIZE(deque) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000187 PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
188 return NULL;
189 }
190 item = deque->rightblock->data[deque->rightindex];
191 deque->rightindex--;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000192 Py_SIZE(deque)--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000193 deque->state++;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000194
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -0700195 if (deque->rightindex < 0) {
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700196 if (Py_SIZE(deque)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000197 prevblock = deque->rightblock->leftlink;
198 assert(deque->leftblock != deque->rightblock);
199 freeblock(deque->rightblock);
Raymond Hettinger82df9252013-07-07 01:43:42 -1000200 CHECK_NOT_END(prevblock);
201 MARK_END(prevblock->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000202 deque->rightblock = prevblock;
203 deque->rightindex = BLOCKLEN - 1;
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700204 } else {
205 assert(deque->leftblock == deque->rightblock);
206 assert(deque->leftindex == deque->rightindex+1);
207 /* re-center instead of freeing a block */
208 deque->leftindex = CENTER + 1;
209 deque->rightindex = CENTER;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000210 }
211 }
212 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000213}
214
215PyDoc_STRVAR(pop_doc, "Remove and return the rightmost element.");
216
217static PyObject *
218deque_popleft(dequeobject *deque, PyObject *unused)
219{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000220 PyObject *item;
221 block *prevblock;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000222
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000223 if (Py_SIZE(deque) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000224 PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
225 return NULL;
226 }
227 assert(deque->leftblock != NULL);
228 item = deque->leftblock->data[deque->leftindex];
229 deque->leftindex++;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000230 Py_SIZE(deque)--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000231 deque->state++;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000233 if (deque->leftindex == BLOCKLEN) {
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700234 if (Py_SIZE(deque)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000235 assert(deque->leftblock != deque->rightblock);
236 prevblock = deque->leftblock->rightlink;
237 freeblock(deque->leftblock);
Raymond Hettinger82df9252013-07-07 01:43:42 -1000238 CHECK_NOT_END(prevblock);
239 MARK_END(prevblock->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000240 deque->leftblock = prevblock;
241 deque->leftindex = 0;
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700242 } else {
243 assert(deque->leftblock == deque->rightblock);
244 assert(deque->leftindex == deque->rightindex+1);
245 /* re-center instead of freeing a block */
246 deque->leftindex = CENTER + 1;
247 deque->rightindex = CENTER;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000248 }
249 }
250 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000251}
252
253PyDoc_STRVAR(popleft_doc, "Remove and return the leftmost element.");
254
Raymond Hettingerf30f5b92015-03-02 22:23:37 -0800255/* The deque's size limit is d.maxlen. The limit can be zero or positive.
256 * If there is no limit, then d.maxlen == -1.
257 *
Raymond Hettingera4b13d02015-10-15 08:05:31 -0700258 * After an item is added to a deque, we check to see if the size has
259 * grown past the limit. If it has, we get the size back down to the limit
260 * by popping an item off of the opposite end. The methods that can
261 * trigger this are append(), appendleft(), extend(), and extendleft().
Raymond Hettingerd96db092015-10-11 22:34:48 -0700262 *
263 * The macro to check whether a deque needs to be trimmed uses a single
264 * unsigned test that returns true whenever 0 <= maxlen < Py_SIZE(deque).
Raymond Hettingerf30f5b92015-03-02 22:23:37 -0800265 */
266
Raymond Hettingerd96db092015-10-11 22:34:48 -0700267#define NEEDS_TRIM(deque, maxlen) ((size_t)(maxlen) < (size_t)(Py_SIZE(deque)))
Raymond Hettingerf30f5b92015-03-02 22:23:37 -0800268
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000269static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000270deque_append(dequeobject *deque, PyObject *item)
271{
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700272 if (deque->rightindex == BLOCKLEN - 1) {
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700273 block *b = newblock();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000274 if (b == NULL)
275 return NULL;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000276 b->leftlink = deque->rightblock;
277 CHECK_END(deque->rightblock->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000278 deque->rightblock->rightlink = b;
279 deque->rightblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000280 MARK_END(b->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000281 deque->rightindex = -1;
282 }
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000283 Py_SIZE(deque)++;
Raymond Hettinger7c0b70f2015-09-26 21:11:05 -0700284 Py_INCREF(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000285 deque->rightindex++;
286 deque->rightblock->data[deque->rightindex] = item;
Raymond Hettingerd96db092015-10-11 22:34:48 -0700287 if (NEEDS_TRIM(deque, deque->maxlen)) {
Raymond Hettinger1286d142015-10-14 23:16:57 -0700288 PyObject *olditem = deque_popleft(deque, NULL);
289 Py_DECREF(olditem);
Raymond Hettinger0f43bb12015-10-20 00:03:33 -0700290 } else {
291 deque->state++;
Raymond Hettingerd96db092015-10-11 22:34:48 -0700292 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000293 Py_RETURN_NONE;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000294}
295
296PyDoc_STRVAR(append_doc, "Add an element to the right side of the deque.");
297
298static PyObject *
299deque_appendleft(dequeobject *deque, PyObject *item)
300{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000301 if (deque->leftindex == 0) {
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700302 block *b = newblock();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000303 if (b == NULL)
304 return NULL;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000305 b->rightlink = deque->leftblock;
306 CHECK_END(deque->leftblock->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000307 deque->leftblock->leftlink = b;
308 deque->leftblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000309 MARK_END(b->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000310 deque->leftindex = BLOCKLEN;
311 }
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000312 Py_SIZE(deque)++;
Raymond Hettinger7c0b70f2015-09-26 21:11:05 -0700313 Py_INCREF(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000314 deque->leftindex--;
315 deque->leftblock->data[deque->leftindex] = item;
Raymond Hettingerd96db092015-10-11 22:34:48 -0700316 if (NEEDS_TRIM(deque, deque->maxlen)) {
Raymond Hettinger1286d142015-10-14 23:16:57 -0700317 PyObject *olditem = deque_pop(deque, NULL);
318 Py_DECREF(olditem);
Raymond Hettinger0f43bb12015-10-20 00:03:33 -0700319 } else {
320 deque->state++;
Raymond Hettingerd96db092015-10-11 22:34:48 -0700321 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000322 Py_RETURN_NONE;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000323}
324
325PyDoc_STRVAR(appendleft_doc, "Add an element to the left side of the deque.");
326
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700327static PyObject*
328finalize_iterator(PyObject *it)
329{
330 if (PyErr_Occurred()) {
331 if (PyErr_ExceptionMatches(PyExc_StopIteration))
332 PyErr_Clear();
333 else {
334 Py_DECREF(it);
335 return NULL;
336 }
337 }
338 Py_DECREF(it);
339 Py_RETURN_NONE;
340}
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000342/* Run an iterator to exhaustion. Shortcut for
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000343 the extend/extendleft methods when maxlen == 0. */
344static PyObject*
345consume_iterator(PyObject *it)
346{
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700347 PyObject *(*iternext)(PyObject *);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000348 PyObject *item;
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000349
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700350 iternext = *Py_TYPE(it)->tp_iternext;
351 while ((item = iternext(it)) != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000352 Py_DECREF(item);
353 }
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700354 return finalize_iterator(it);
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000355}
356
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000357static PyObject *
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000358deque_extend(dequeobject *deque, PyObject *iterable)
359{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000360 PyObject *it, *item;
Raymond Hettinger7a845522015-09-26 01:30:51 -0700361 PyObject *(*iternext)(PyObject *);
Raymond Hettinger6b1e1132015-10-11 09:43:50 -0700362 Py_ssize_t maxlen = deque->maxlen;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000364 /* Handle case where id(deque) == id(iterable) */
365 if ((PyObject *)deque == iterable) {
366 PyObject *result;
367 PyObject *s = PySequence_List(iterable);
368 if (s == NULL)
369 return NULL;
370 result = deque_extend(deque, s);
371 Py_DECREF(s);
372 return result;
373 }
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000374
Raymond Hettingerd9c116c2013-07-09 00:13:21 -0700375 /* Space saving heuristic. Start filling from the left */
376 if (Py_SIZE(deque) == 0) {
377 assert(deque->leftblock == deque->rightblock);
378 assert(deque->leftindex == deque->rightindex+1);
379 deque->leftindex = 1;
380 deque->rightindex = 0;
381 }
382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000383 it = PyObject_GetIter(iterable);
384 if (it == NULL)
385 return NULL;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000386
Raymond Hettinger965362e2015-10-11 22:52:54 -0700387 if (maxlen == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000388 return consume_iterator(it);
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000389
Raymond Hettinger7a845522015-09-26 01:30:51 -0700390 iternext = *Py_TYPE(it)->tp_iternext;
391 while ((item = iternext(it)) != NULL) {
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700392 if (deque->rightindex == BLOCKLEN - 1) {
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700393 block *b = newblock();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000394 if (b == NULL) {
395 Py_DECREF(item);
396 Py_DECREF(it);
397 return NULL;
398 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000399 b->leftlink = deque->rightblock;
400 CHECK_END(deque->rightblock->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000401 deque->rightblock->rightlink = b;
402 deque->rightblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000403 MARK_END(b->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000404 deque->rightindex = -1;
405 }
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000406 Py_SIZE(deque)++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000407 deque->rightindex++;
408 deque->rightblock->data[deque->rightindex] = item;
Raymond Hettingerd96db092015-10-11 22:34:48 -0700409 if (NEEDS_TRIM(deque, maxlen)) {
Raymond Hettinger1286d142015-10-14 23:16:57 -0700410 PyObject *olditem = deque_popleft(deque, NULL);
411 Py_DECREF(olditem);
Raymond Hettinger0f43bb12015-10-20 00:03:33 -0700412 } else {
413 deque->state++;
Raymond Hettinger6b1e1132015-10-11 09:43:50 -0700414 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000415 }
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700416 return finalize_iterator(it);
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000417}
418
Tim Peters1065f752004-10-01 01:03:29 +0000419PyDoc_STRVAR(extend_doc,
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000420"Extend the right side of the deque with elements from the iterable");
421
422static PyObject *
423deque_extendleft(dequeobject *deque, PyObject *iterable)
424{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425 PyObject *it, *item;
Raymond Hettinger7a845522015-09-26 01:30:51 -0700426 PyObject *(*iternext)(PyObject *);
Raymond Hettinger6b1e1132015-10-11 09:43:50 -0700427 Py_ssize_t maxlen = deque->maxlen;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000428
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000429 /* Handle case where id(deque) == id(iterable) */
430 if ((PyObject *)deque == iterable) {
431 PyObject *result;
432 PyObject *s = PySequence_List(iterable);
433 if (s == NULL)
434 return NULL;
435 result = deque_extendleft(deque, s);
436 Py_DECREF(s);
437 return result;
438 }
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000439
Raymond Hettingerd9c116c2013-07-09 00:13:21 -0700440 /* Space saving heuristic. Start filling from the right */
441 if (Py_SIZE(deque) == 0) {
442 assert(deque->leftblock == deque->rightblock);
443 assert(deque->leftindex == deque->rightindex+1);
444 deque->leftindex = BLOCKLEN - 1;
445 deque->rightindex = BLOCKLEN - 2;
446 }
447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000448 it = PyObject_GetIter(iterable);
449 if (it == NULL)
450 return NULL;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000451
Raymond Hettinger965362e2015-10-11 22:52:54 -0700452 if (maxlen == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000453 return consume_iterator(it);
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000454
Raymond Hettinger7a845522015-09-26 01:30:51 -0700455 iternext = *Py_TYPE(it)->tp_iternext;
456 while ((item = iternext(it)) != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000457 if (deque->leftindex == 0) {
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700458 block *b = newblock();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000459 if (b == NULL) {
460 Py_DECREF(item);
461 Py_DECREF(it);
462 return NULL;
463 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000464 b->rightlink = deque->leftblock;
465 CHECK_END(deque->leftblock->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000466 deque->leftblock->leftlink = b;
467 deque->leftblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000468 MARK_END(b->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469 deque->leftindex = BLOCKLEN;
470 }
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000471 Py_SIZE(deque)++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 deque->leftindex--;
473 deque->leftblock->data[deque->leftindex] = item;
Raymond Hettingerd96db092015-10-11 22:34:48 -0700474 if (NEEDS_TRIM(deque, maxlen)) {
Raymond Hettinger1286d142015-10-14 23:16:57 -0700475 PyObject *olditem = deque_pop(deque, NULL);
476 Py_DECREF(olditem);
Raymond Hettinger0f43bb12015-10-20 00:03:33 -0700477 } else {
478 deque->state++;
Raymond Hettinger6b1e1132015-10-11 09:43:50 -0700479 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000480 }
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700481 return finalize_iterator(it);
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000482}
483
Tim Peters1065f752004-10-01 01:03:29 +0000484PyDoc_STRVAR(extendleft_doc,
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000485"Extend the left side of the deque with elements from the iterable");
486
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000487static PyObject *
488deque_inplace_concat(dequeobject *deque, PyObject *other)
489{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 PyObject *result;
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 result = deque_extend(deque, other);
493 if (result == NULL)
494 return result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000495 Py_INCREF(deque);
Raymond Hettinger2b2b7532015-09-05 17:05:52 -0700496 Py_DECREF(result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 return (PyObject *)deque;
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000498}
499
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700500static PyObject *
501deque_copy(PyObject *deque)
502{
503 dequeobject *old_deque = (dequeobject *)deque;
504 if (Py_TYPE(deque) == &deque_type) {
505 dequeobject *new_deque;
506 PyObject *rv;
507
508 new_deque = (dequeobject *)deque_new(&deque_type, (PyObject *)NULL, (PyObject *)NULL);
509 if (new_deque == NULL)
510 return NULL;
511 new_deque->maxlen = old_deque->maxlen;
512 /* Fast path for the deque_repeat() common case where len(deque) == 1 */
Raymond Hettinger0443ac22015-10-05 22:52:37 -0400513 if (Py_SIZE(deque) == 1) {
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700514 PyObject *item = old_deque->leftblock->data[old_deque->leftindex];
515 rv = deque_append(new_deque, item);
516 } else {
517 rv = deque_extend(new_deque, deque);
518 }
519 if (rv != NULL) {
520 Py_DECREF(rv);
521 return (PyObject *)new_deque;
522 }
523 Py_DECREF(new_deque);
524 return NULL;
525 }
526 if (old_deque->maxlen < 0)
527 return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "O", deque, NULL);
528 else
529 return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "Oi",
530 deque, old_deque->maxlen, NULL);
531}
532
533PyDoc_STRVAR(copy_doc, "Return a shallow copy of a deque.");
Raymond Hettinger41290a62015-03-31 08:12:23 -0700534
535static PyObject *
536deque_concat(dequeobject *deque, PyObject *other)
537{
Benjamin Peterson1a629212015-04-04 10:52:36 -0400538 PyObject *new_deque, *result;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700539 int rv;
540
541 rv = PyObject_IsInstance(other, (PyObject *)&deque_type);
542 if (rv <= 0) {
543 if (rv == 0) {
544 PyErr_Format(PyExc_TypeError,
545 "can only concatenate deque (not \"%.200s\") to deque",
546 other->ob_type->tp_name);
547 }
548 return NULL;
549 }
550
551 new_deque = deque_copy((PyObject *)deque);
552 if (new_deque == NULL)
553 return NULL;
Benjamin Peterson1a629212015-04-04 10:52:36 -0400554 result = deque_extend((dequeobject *)new_deque, other);
555 if (result == NULL) {
556 Py_DECREF(new_deque);
557 return NULL;
558 }
559 Py_DECREF(result);
560 return new_deque;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700561}
562
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700563static void
564deque_clear(dequeobject *deque)
565{
566 block *b;
567 block *prevblock;
568 block *leftblock;
569 Py_ssize_t leftindex;
570 Py_ssize_t n;
571 PyObject *item;
572
Raymond Hettinger38031142015-09-29 22:45:05 -0700573 if (Py_SIZE(deque) == 0)
574 return;
575
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700576 /* During the process of clearing a deque, decrefs can cause the
577 deque to mutate. To avoid fatal confusion, we have to make the
578 deque empty before clearing the blocks and never refer to
579 anything via deque->ref while clearing. (This is the same
580 technique used for clearing lists, sets, and dicts.)
581
582 Making the deque empty requires allocating a new empty block. In
583 the unlikely event that memory is full, we fall back to an
584 alternate method that doesn't require a new block. Repeating
585 pops in a while-loop is slower, possibly re-entrant (and a clever
586 adversary could cause it to never terminate).
587 */
588
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700589 b = newblock();
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700590 if (b == NULL) {
591 PyErr_Clear();
592 goto alternate_method;
593 }
594
595 /* Remember the old size, leftblock, and leftindex */
596 leftblock = deque->leftblock;
597 leftindex = deque->leftindex;
598 n = Py_SIZE(deque);
599
600 /* Set the deque to be empty using the newly allocated block */
601 MARK_END(b->leftlink);
602 MARK_END(b->rightlink);
603 Py_SIZE(deque) = 0;
604 deque->leftblock = b;
605 deque->rightblock = b;
606 deque->leftindex = CENTER + 1;
607 deque->rightindex = CENTER;
608 deque->state++;
609
610 /* Now the old size, leftblock, and leftindex are disconnected from
611 the empty deque and we can use them to decref the pointers.
612 */
613 while (n--) {
614 item = leftblock->data[leftindex];
615 Py_DECREF(item);
616 leftindex++;
617 if (leftindex == BLOCKLEN && n) {
618 CHECK_NOT_END(leftblock->rightlink);
619 prevblock = leftblock;
620 leftblock = leftblock->rightlink;
621 leftindex = 0;
622 freeblock(prevblock);
623 }
624 }
625 CHECK_END(leftblock->rightlink);
626 freeblock(leftblock);
627 return;
628
629 alternate_method:
630 while (Py_SIZE(deque)) {
631 item = deque_pop(deque, NULL);
632 assert (item != NULL);
633 Py_DECREF(item);
634 }
635}
636
637static PyObject *
638deque_clearmethod(dequeobject *deque)
639{
640 deque_clear(deque);
641 Py_RETURN_NONE;
642}
643
644PyDoc_STRVAR(clear_doc, "Remove all elements from the deque.");
Raymond Hettinger41290a62015-03-31 08:12:23 -0700645
646static PyObject *
Raymond Hettinger41290a62015-03-31 08:12:23 -0700647deque_inplace_repeat(dequeobject *deque, Py_ssize_t n)
648{
Raymond Hettingerc22eee62015-09-26 02:14:50 -0700649 Py_ssize_t i, m, size;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700650 PyObject *seq;
651 PyObject *rv;
652
653 size = Py_SIZE(deque);
654 if (size == 0 || n == 1) {
655 Py_INCREF(deque);
656 return (PyObject *)deque;
657 }
658
659 if (n <= 0) {
660 deque_clear(deque);
661 Py_INCREF(deque);
662 return (PyObject *)deque;
663 }
664
Raymond Hettinger41290a62015-03-31 08:12:23 -0700665 if (size == 1) {
666 /* common case, repeating a single element */
667 PyObject *item = deque->leftblock->data[deque->leftindex];
668
Raymond Hettingera7f630092015-10-10 23:56:02 -0400669 if (deque->maxlen >= 0 && n > deque->maxlen)
Raymond Hettinger41290a62015-03-31 08:12:23 -0700670 n = deque->maxlen;
671
Raymond Hettinger67c78b52015-09-12 11:00:20 -0400672 deque->state++;
Raymond Hettingerad262252015-09-14 01:03:04 -0400673 for (i = 0 ; i < n-1 ; ) {
Raymond Hettinger67c78b52015-09-12 11:00:20 -0400674 if (deque->rightindex == BLOCKLEN - 1) {
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700675 block *b = newblock();
Raymond Hettinger67c78b52015-09-12 11:00:20 -0400676 if (b == NULL) {
677 Py_SIZE(deque) += i;
678 return NULL;
679 }
680 b->leftlink = deque->rightblock;
681 CHECK_END(deque->rightblock->rightlink);
682 deque->rightblock->rightlink = b;
683 deque->rightblock = b;
684 MARK_END(b->rightlink);
685 deque->rightindex = -1;
686 }
Raymond Hettingerc22eee62015-09-26 02:14:50 -0700687 m = n - 1 - i;
688 if (m > BLOCKLEN - 1 - deque->rightindex)
689 m = BLOCKLEN - 1 - deque->rightindex;
690 i += m;
691 while (m--) {
Raymond Hettingerad262252015-09-14 01:03:04 -0400692 deque->rightindex++;
693 Py_INCREF(item);
694 deque->rightblock->data[deque->rightindex] = item;
695 }
Raymond Hettinger41290a62015-03-31 08:12:23 -0700696 }
Raymond Hettinger67c78b52015-09-12 11:00:20 -0400697 Py_SIZE(deque) += i;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700698 Py_INCREF(deque);
699 return (PyObject *)deque;
700 }
701
Raymond Hettinger20151f52015-10-16 22:47:29 -0700702 if ((size_t)size > PY_SSIZE_T_MAX / (size_t)n) {
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400703 return PyErr_NoMemory();
704 }
705
Raymond Hettinger41290a62015-03-31 08:12:23 -0700706 seq = PySequence_List((PyObject *)deque);
707 if (seq == NULL)
708 return seq;
709
710 for (i = 0 ; i < n-1 ; i++) {
711 rv = deque_extend(deque, seq);
712 if (rv == NULL) {
713 Py_DECREF(seq);
714 return NULL;
715 }
716 Py_DECREF(rv);
717 }
718 Py_INCREF(deque);
719 Py_DECREF(seq);
720 return (PyObject *)deque;
721}
722
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400723static PyObject *
724deque_repeat(dequeobject *deque, Py_ssize_t n)
725{
726 dequeobject *new_deque;
Raymond Hettinger95e2cc52015-09-13 02:41:18 -0400727 PyObject *rv;
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400728
729 new_deque = (dequeobject *)deque_copy((PyObject *) deque);
730 if (new_deque == NULL)
731 return NULL;
Raymond Hettinger95e2cc52015-09-13 02:41:18 -0400732 rv = deque_inplace_repeat(new_deque, n);
733 Py_DECREF(new_deque);
734 return rv;
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400735}
736
Raymond Hettinger54023152014-04-23 00:58:48 -0700737/* The rotate() method is part of the public API and is used internally
738as a primitive for other methods.
739
740Rotation by 1 or -1 is a common case, so any optimizations for high
741volume rotations should take care not to penalize the common case.
742
743Conceptually, a rotate by one is equivalent to a pop on one side and an
744append on the other. However, a pop/append pair is unnecessarily slow
Martin Panterd2ad5712015-11-02 04:20:33 +0000745because it requires an incref/decref pair for an object located randomly
Raymond Hettinger54023152014-04-23 00:58:48 -0700746in memory. It is better to just move the object pointer from one block
747to the next without changing the reference count.
748
749When moving batches of pointers, it is tempting to use memcpy() but that
750proved to be slower than a simple loop for a variety of reasons.
751Memcpy() cannot know in advance that we're copying pointers instead of
752bytes, that the source and destination are pointer aligned and
753non-overlapping, that moving just one pointer is a common case, that we
754never need to move more than BLOCKLEN pointers, and that at least one
755pointer is always moved.
756
757For high volume rotations, newblock() and freeblock() are never called
758more than once. Previously emptied blocks are immediately reused as a
759destination block. If a block is left-over at the end, it is freed.
760*/
761
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000762static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000763_deque_rotate(dequeobject *deque, Py_ssize_t n)
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000764{
Raymond Hettinger3959af92013-07-13 02:34:08 -0700765 block *b = NULL;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700766 block *leftblock = deque->leftblock;
767 block *rightblock = deque->rightblock;
768 Py_ssize_t leftindex = deque->leftindex;
769 Py_ssize_t rightindex = deque->rightindex;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000770 Py_ssize_t len=Py_SIZE(deque), halflen=len>>1;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700771 int rv = -1;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000772
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800773 if (len <= 1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000774 return 0;
775 if (n > halflen || n < -halflen) {
776 n %= len;
777 if (n > halflen)
778 n -= len;
779 else if (n < -halflen)
780 n += len;
781 }
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500782 assert(len > 1);
Raymond Hettingera4409c12013-02-04 00:08:12 -0500783 assert(-halflen <= n && n <= halflen);
Raymond Hettinger231ee4d2013-02-02 11:24:43 -0800784
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800785 deque->state++;
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500786 while (n > 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700787 if (leftindex == 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700788 if (b == NULL) {
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700789 b = newblock();
Raymond Hettinger3959af92013-07-13 02:34:08 -0700790 if (b == NULL)
791 goto done;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700792 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000793 b->rightlink = leftblock;
794 CHECK_END(leftblock->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700795 leftblock->leftlink = b;
796 leftblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000797 MARK_END(b->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700798 leftindex = BLOCKLEN;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700799 b = NULL;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800800 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700801 assert(leftindex > 0);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700802 {
803 PyObject **src, **dest;
804 Py_ssize_t m = n;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800805
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700806 if (m > rightindex + 1)
807 m = rightindex + 1;
808 if (m > leftindex)
809 m = leftindex;
810 assert (m > 0 && m <= len);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700811 rightindex -= m;
812 leftindex -= m;
Raymond Hettinger0e259f12015-02-01 22:53:41 -0800813 src = &rightblock->data[rightindex + 1];
814 dest = &leftblock->data[leftindex];
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700815 n -= m;
Raymond Hettinger840533b2013-07-13 17:03:58 -0700816 do {
Raymond Hettinger0e259f12015-02-01 22:53:41 -0800817 *(dest++) = *(src++);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700818 } while (--m);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700819 }
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -0700820 if (rightindex < 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700821 assert(leftblock != rightblock);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700822 assert(b == NULL);
Raymond Hettinger3959af92013-07-13 02:34:08 -0700823 b = rightblock;
Raymond Hettingerb97cc492013-07-21 01:51:07 -0700824 CHECK_NOT_END(rightblock->leftlink);
825 rightblock = rightblock->leftlink;
826 MARK_END(rightblock->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700827 rightindex = BLOCKLEN - 1;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800828 }
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800829 }
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500830 while (n < 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700831 if (rightindex == BLOCKLEN - 1) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700832 if (b == NULL) {
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700833 b = newblock();
Raymond Hettinger3959af92013-07-13 02:34:08 -0700834 if (b == NULL)
835 goto done;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700836 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000837 b->leftlink = rightblock;
838 CHECK_END(rightblock->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700839 rightblock->rightlink = b;
840 rightblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000841 MARK_END(b->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700842 rightindex = -1;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700843 b = NULL;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800844 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700845 assert (rightindex < BLOCKLEN - 1);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700846 {
847 PyObject **src, **dest;
848 Py_ssize_t m = -n;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800849
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700850 if (m > BLOCKLEN - leftindex)
851 m = BLOCKLEN - leftindex;
852 if (m > BLOCKLEN - 1 - rightindex)
853 m = BLOCKLEN - 1 - rightindex;
854 assert (m > 0 && m <= len);
855 src = &leftblock->data[leftindex];
856 dest = &rightblock->data[rightindex + 1];
857 leftindex += m;
858 rightindex += m;
859 n += m;
Raymond Hettinger840533b2013-07-13 17:03:58 -0700860 do {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700861 *(dest++) = *(src++);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700862 } while (--m);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700863 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700864 if (leftindex == BLOCKLEN) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700865 assert(leftblock != rightblock);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700866 assert(b == NULL);
Raymond Hettinger3959af92013-07-13 02:34:08 -0700867 b = leftblock;
Raymond Hettingerb97cc492013-07-21 01:51:07 -0700868 CHECK_NOT_END(leftblock->rightlink);
869 leftblock = leftblock->rightlink;
870 MARK_END(leftblock->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700871 leftindex = 0;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800872 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000873 }
Raymond Hettinger3959af92013-07-13 02:34:08 -0700874 rv = 0;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700875done:
Raymond Hettinger3959af92013-07-13 02:34:08 -0700876 if (b != NULL)
877 freeblock(b);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700878 deque->leftblock = leftblock;
879 deque->rightblock = rightblock;
880 deque->leftindex = leftindex;
881 deque->rightindex = rightindex;
882
883 return rv;
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000884}
885
886static PyObject *
887deque_rotate(dequeobject *deque, PyObject *args)
888{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 Py_ssize_t n=1;
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000891 if (!PyArg_ParseTuple(args, "|n:rotate", &n))
892 return NULL;
Raymond Hettinger6921c132015-03-21 02:03:40 -0700893 if (!_deque_rotate(deque, n))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 Py_RETURN_NONE;
895 return NULL;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000896}
897
Tim Peters1065f752004-10-01 01:03:29 +0000898PyDoc_STRVAR(rotate_doc,
Raymond Hettingeree33b272004-02-08 04:05:26 +0000899"Rotate the deque n steps to the right (default n=1). If n is negative, rotates left.");
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000900
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000901static PyObject *
902deque_reverse(dequeobject *deque, PyObject *unused)
903{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000904 block *leftblock = deque->leftblock;
905 block *rightblock = deque->rightblock;
906 Py_ssize_t leftindex = deque->leftindex;
907 Py_ssize_t rightindex = deque->rightindex;
Raymond Hettingercfe5b6c2015-07-20 00:25:50 -0400908 Py_ssize_t n = Py_SIZE(deque) >> 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000909 PyObject *tmp;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000910
Raymond Hettinger7a237232015-09-22 01:20:36 -0700911 while (n-- > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000912 /* Validate that pointers haven't met in the middle */
913 assert(leftblock != rightblock || leftindex < rightindex);
Raymond Hettinger82df9252013-07-07 01:43:42 -1000914 CHECK_NOT_END(leftblock);
915 CHECK_NOT_END(rightblock);
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000916
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000917 /* Swap */
918 tmp = leftblock->data[leftindex];
919 leftblock->data[leftindex] = rightblock->data[rightindex];
920 rightblock->data[rightindex] = tmp;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 /* Advance left block/index pair */
923 leftindex++;
924 if (leftindex == BLOCKLEN) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000925 leftblock = leftblock->rightlink;
926 leftindex = 0;
927 }
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000928
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000929 /* Step backwards with the right block/index pair */
930 rightindex--;
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -0700931 if (rightindex < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 rightblock = rightblock->leftlink;
933 rightindex = BLOCKLEN - 1;
934 }
935 }
936 Py_RETURN_NONE;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000937}
938
939PyDoc_STRVAR(reverse_doc,
940"D.reverse() -- reverse *IN PLACE*");
941
Raymond Hettinger44459de2010-04-03 23:20:46 +0000942static PyObject *
943deque_count(dequeobject *deque, PyObject *v)
944{
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000945 block *b = deque->leftblock;
946 Py_ssize_t index = deque->leftindex;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000947 Py_ssize_t n = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000948 Py_ssize_t count = 0;
Raymond Hettingerf9d9c792015-03-02 22:47:46 -0800949 size_t start_state = deque->state;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 PyObject *item;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 int cmp;
Raymond Hettinger44459de2010-04-03 23:20:46 +0000952
Raymond Hettinger3a1a8d02015-09-23 02:42:02 -0700953 while (n--) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000954 CHECK_NOT_END(b);
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000955 item = b->data[index];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000956 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
Raymond Hettinger2b0d6462015-09-23 19:15:44 -0700957 if (cmp < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000958 return NULL;
Raymond Hettinger2b0d6462015-09-23 19:15:44 -0700959 count += cmp;
Raymond Hettinger44459de2010-04-03 23:20:46 +0000960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000961 if (start_state != deque->state) {
962 PyErr_SetString(PyExc_RuntimeError,
963 "deque mutated during iteration");
964 return NULL;
965 }
Raymond Hettinger44459de2010-04-03 23:20:46 +0000966
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000967 /* Advance left block/index pair */
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000968 index++;
969 if (index == BLOCKLEN) {
970 b = b->rightlink;
971 index = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 }
973 }
974 return PyLong_FromSsize_t(count);
Raymond Hettinger44459de2010-04-03 23:20:46 +0000975}
976
977PyDoc_STRVAR(count_doc,
978"D.count(value) -> integer -- return number of occurrences of value");
979
Raymond Hettinger39dadf72015-03-20 16:38:56 -0700980static int
981deque_contains(dequeobject *deque, PyObject *v)
982{
983 block *b = deque->leftblock;
984 Py_ssize_t index = deque->leftindex;
985 Py_ssize_t n = Py_SIZE(deque);
Raymond Hettinger39dadf72015-03-20 16:38:56 -0700986 size_t start_state = deque->state;
987 PyObject *item;
988 int cmp;
989
Raymond Hettinger3a1a8d02015-09-23 02:42:02 -0700990 while (n--) {
Raymond Hettinger39dadf72015-03-20 16:38:56 -0700991 CHECK_NOT_END(b);
992 item = b->data[index];
993 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
994 if (cmp) {
995 return cmp;
996 }
997 if (start_state != deque->state) {
998 PyErr_SetString(PyExc_RuntimeError,
999 "deque mutated during iteration");
1000 return -1;
1001 }
1002 index++;
1003 if (index == BLOCKLEN) {
1004 b = b->rightlink;
1005 index = 0;
1006 }
1007 }
1008 return 0;
1009}
1010
Martin v. Löwis18e16552006-02-15 17:27:45 +00001011static Py_ssize_t
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001012deque_len(dequeobject *deque)
1013{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001014 return Py_SIZE(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001015}
1016
Raymond Hettinger4aec61e2005-03-18 21:20:23 +00001017static PyObject *
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001018deque_index(dequeobject *deque, PyObject *args)
1019{
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001020 Py_ssize_t i, n, start=0, stop=Py_SIZE(deque);
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001021 PyObject *v, *item;
1022 block *b = deque->leftblock;
1023 Py_ssize_t index = deque->leftindex;
1024 size_t start_state = deque->state;
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001025 int cmp;
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001026
1027 if (!PyArg_ParseTuple(args, "O|O&O&:index", &v,
1028 _PyEval_SliceIndex, &start,
1029 _PyEval_SliceIndex, &stop))
1030 return NULL;
1031 if (start < 0) {
1032 start += Py_SIZE(deque);
1033 if (start < 0)
1034 start = 0;
1035 }
1036 if (stop < 0) {
1037 stop += Py_SIZE(deque);
1038 if (stop < 0)
1039 stop = 0;
1040 }
Raymond Hettinger87674ec2015-08-26 08:08:38 -07001041 if (stop > Py_SIZE(deque))
1042 stop = Py_SIZE(deque);
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001043 if (start > stop)
1044 start = stop;
1045 assert(0 <= start && start <= stop && stop <= Py_SIZE(deque));
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001046
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001047 /* XXX Replace this loop with faster code from deque_item() */
1048 for (i=0 ; i<start ; i++) {
1049 index++;
1050 if (index == BLOCKLEN) {
1051 b = b->rightlink;
1052 index = 0;
1053 }
1054 }
1055
Raymond Hettinger4a91d212015-11-03 22:00:26 -05001056 n = stop - i + 1;
1057 while (--n) {
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001058 CHECK_NOT_END(b);
1059 item = b->data[index];
1060 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
1061 if (cmp > 0)
Raymond Hettinger4a91d212015-11-03 22:00:26 -05001062 return PyLong_FromSsize_t(stop - n);
Raymond Hettingerdf8f5b52015-11-02 07:27:40 -05001063 if (cmp < 0)
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001064 return NULL;
1065 if (start_state != deque->state) {
1066 PyErr_SetString(PyExc_RuntimeError,
1067 "deque mutated during iteration");
1068 return NULL;
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001069 }
1070 index++;
1071 if (index == BLOCKLEN) {
1072 b = b->rightlink;
1073 index = 0;
1074 }
1075 }
1076 PyErr_Format(PyExc_ValueError, "%R is not in deque", v);
1077 return NULL;
1078}
1079
1080PyDoc_STRVAR(index_doc,
1081"D.index(value, [start, [stop]]) -> integer -- return first index of value.\n"
1082"Raises ValueError if the value is not present.");
1083
Raymond Hettinger551350a2015-03-24 00:19:53 -07001084/* insert(), remove(), and delitem() are implemented in terms of
1085 rotate() for simplicity and reasonable performance near the end
1086 points. If for some reason these methods become popular, it is not
1087 hard to re-implement this using direct data movement (similar to
1088 the code used in list slice assignments) and achieve a performance
Raymond Hettingerfef9c1b2015-03-24 21:12:57 -07001089 boost (by moving each pointer only once instead of twice).
Raymond Hettinger551350a2015-03-24 00:19:53 -07001090*/
1091
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001092static PyObject *
1093deque_insert(dequeobject *deque, PyObject *args)
1094{
1095 Py_ssize_t index;
1096 Py_ssize_t n = Py_SIZE(deque);
1097 PyObject *value;
1098 PyObject *rv;
1099
1100 if (!PyArg_ParseTuple(args, "nO:insert", &index, &value))
1101 return NULL;
1102 if (index >= n)
1103 return deque_append(deque, value);
1104 if (index <= -n || index == 0)
1105 return deque_appendleft(deque, value);
1106 if (_deque_rotate(deque, -index))
1107 return NULL;
1108 if (index < 0)
1109 rv = deque_append(deque, value);
1110 else
1111 rv = deque_appendleft(deque, value);
1112 if (rv == NULL)
1113 return NULL;
1114 Py_DECREF(rv);
1115 if (_deque_rotate(deque, index))
1116 return NULL;
1117 Py_RETURN_NONE;
1118}
1119
1120PyDoc_STRVAR(insert_doc,
1121"D.insert(index, object) -- insert object before index");
1122
1123static PyObject *
Raymond Hettinger4aec61e2005-03-18 21:20:23 +00001124deque_remove(dequeobject *deque, PyObject *value)
1125{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001126 Py_ssize_t i, n=Py_SIZE(deque);
Raymond Hettinger4aec61e2005-03-18 21:20:23 +00001127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001128 for (i=0 ; i<n ; i++) {
1129 PyObject *item = deque->leftblock->data[deque->leftindex];
1130 int cmp = PyObject_RichCompareBool(item, value, Py_EQ);
Raymond Hettingerd73202c2005-03-19 00:00:51 +00001131
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001132 if (Py_SIZE(deque) != n) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001133 PyErr_SetString(PyExc_IndexError,
1134 "deque mutated during remove().");
1135 return NULL;
1136 }
1137 if (cmp > 0) {
1138 PyObject *tgt = deque_popleft(deque, NULL);
1139 assert (tgt != NULL);
Raymond Hettinger6921c132015-03-21 02:03:40 -07001140 if (_deque_rotate(deque, i))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001141 return NULL;
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001142 Py_DECREF(tgt);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001143 Py_RETURN_NONE;
1144 }
1145 else if (cmp < 0) {
1146 _deque_rotate(deque, i);
1147 return NULL;
1148 }
1149 _deque_rotate(deque, -1);
1150 }
1151 PyErr_SetString(PyExc_ValueError, "deque.remove(x): x not in deque");
1152 return NULL;
Raymond Hettinger4aec61e2005-03-18 21:20:23 +00001153}
1154
1155PyDoc_STRVAR(remove_doc,
1156"D.remove(value) -- remove first occurrence of value.");
1157
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001158static int
1159valid_index(Py_ssize_t i, Py_ssize_t limit)
1160{
Raymond Hettinger12f896c2015-07-31 12:03:20 -07001161 /* The cast to size_t lets us use just a single comparison
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001162 to check whether i is in the range: 0 <= i < limit */
1163 return (size_t) i < (size_t) limit;
1164}
1165
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001166static PyObject *
Benjamin Petersond6313712008-07-31 16:23:04 +00001167deque_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001168{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001169 block *b;
1170 PyObject *item;
1171 Py_ssize_t n, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001172
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001173 if (!valid_index(i, Py_SIZE(deque))) {
1174 PyErr_SetString(PyExc_IndexError, "deque index out of range");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001175 return NULL;
1176 }
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178 if (i == 0) {
1179 i = deque->leftindex;
1180 b = deque->leftblock;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001181 } else if (i == Py_SIZE(deque) - 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 i = deque->rightindex;
1183 b = deque->rightblock;
1184 } else {
1185 i += deque->leftindex;
Raymond Hettingerc2083082015-02-28 23:29:16 -08001186 n = (Py_ssize_t)((size_t) i / BLOCKLEN);
1187 i = (Py_ssize_t)((size_t) i % BLOCKLEN);
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001188 if (index < (Py_SIZE(deque) >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001189 b = deque->leftblock;
1190 while (n--)
1191 b = b->rightlink;
1192 } else {
Raymond Hettinger63d1ff22015-02-28 07:41:30 -08001193 n = (Py_ssize_t)(
Raymond Hettingerc2083082015-02-28 23:29:16 -08001194 ((size_t)(deque->leftindex + Py_SIZE(deque) - 1))
Raymond Hettinger63d1ff22015-02-28 07:41:30 -08001195 / BLOCKLEN - n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001196 b = deque->rightblock;
1197 while (n--)
1198 b = b->leftlink;
1199 }
1200 }
1201 item = b->data[i];
1202 Py_INCREF(item);
1203 return item;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001204}
1205
1206static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001207deque_del_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001208{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 PyObject *item;
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001210 int rv;
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001211
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001212 assert (i >= 0 && i < Py_SIZE(deque));
Raymond Hettinger6921c132015-03-21 02:03:40 -07001213 if (_deque_rotate(deque, -i))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001214 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001215 item = deque_popleft(deque, NULL);
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001216 rv = _deque_rotate(deque, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001217 assert (item != NULL);
1218 Py_DECREF(item);
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001219 return rv;
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001220}
1221
1222static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001223deque_ass_item(dequeobject *deque, Py_ssize_t i, PyObject *v)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001224{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 PyObject *old_value;
1226 block *b;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001227 Py_ssize_t n, len=Py_SIZE(deque), halflen=(len+1)>>1, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001228
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001229 if (!valid_index(i, len)) {
1230 PyErr_SetString(PyExc_IndexError, "deque index out of range");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001231 return -1;
1232 }
1233 if (v == NULL)
1234 return deque_del_item(deque, i);
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001236 i += deque->leftindex;
Raymond Hettingerc2083082015-02-28 23:29:16 -08001237 n = (Py_ssize_t)((size_t) i / BLOCKLEN);
1238 i = (Py_ssize_t)((size_t) i % BLOCKLEN);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001239 if (index <= halflen) {
1240 b = deque->leftblock;
1241 while (n--)
1242 b = b->rightlink;
1243 } else {
Raymond Hettingera473b9d2015-02-28 17:49:47 -08001244 n = (Py_ssize_t)(
Raymond Hettingerc2083082015-02-28 23:29:16 -08001245 ((size_t)(deque->leftindex + Py_SIZE(deque) - 1))
Raymond Hettingera473b9d2015-02-28 17:49:47 -08001246 / BLOCKLEN - n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001247 b = deque->rightblock;
1248 while (n--)
1249 b = b->leftlink;
1250 }
1251 Py_INCREF(v);
1252 old_value = b->data[i];
1253 b->data[i] = v;
1254 Py_DECREF(old_value);
1255 return 0;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001256}
1257
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001258static void
1259deque_dealloc(dequeobject *deque)
1260{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001261 PyObject_GC_UnTrack(deque);
1262 if (deque->weakreflist != NULL)
1263 PyObject_ClearWeakRefs((PyObject *) deque);
1264 if (deque->leftblock != NULL) {
1265 deque_clear(deque);
1266 assert(deque->leftblock != NULL);
1267 freeblock(deque->leftblock);
1268 }
1269 deque->leftblock = NULL;
1270 deque->rightblock = NULL;
1271 Py_TYPE(deque)->tp_free(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001272}
1273
1274static int
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001275deque_traverse(dequeobject *deque, visitproc visit, void *arg)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001276{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001277 block *b;
1278 PyObject *item;
1279 Py_ssize_t index;
1280 Py_ssize_t indexlo = deque->leftindex;
Raymond Hettinger1286d142015-10-14 23:16:57 -07001281 Py_ssize_t indexhigh;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001282
Raymond Hettinger5bfa8672013-07-06 11:58:09 -10001283 for (b = deque->leftblock; b != deque->rightblock; b = b->rightlink) {
1284 for (index = indexlo; index < BLOCKLEN ; index++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001285 item = b->data[index];
1286 Py_VISIT(item);
1287 }
1288 indexlo = 0;
1289 }
Raymond Hettinger1286d142015-10-14 23:16:57 -07001290 indexhigh = deque->rightindex;
1291 for (index = indexlo; index <= indexhigh; index++) {
Raymond Hettinger5bfa8672013-07-06 11:58:09 -10001292 item = b->data[index];
1293 Py_VISIT(item);
1294 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001295 return 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001296}
1297
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001298static PyObject *
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001299deque_reduce(dequeobject *deque)
1300{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001301 PyObject *dict, *result, *aslist;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001302 _Py_IDENTIFIER(__dict__);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001303
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001304 dict = _PyObject_GetAttrId((PyObject *)deque, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001305 if (dict == NULL)
1306 PyErr_Clear();
1307 aslist = PySequence_List((PyObject *)deque);
1308 if (aslist == NULL) {
1309 Py_XDECREF(dict);
1310 return NULL;
1311 }
1312 if (dict == NULL) {
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -07001313 if (deque->maxlen < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001314 result = Py_BuildValue("O(O)", Py_TYPE(deque), aslist);
1315 else
1316 result = Py_BuildValue("O(On)", Py_TYPE(deque), aslist, deque->maxlen);
1317 } else {
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -07001318 if (deque->maxlen < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001319 result = Py_BuildValue("O(OO)O", Py_TYPE(deque), aslist, Py_None, dict);
1320 else
1321 result = Py_BuildValue("O(On)O", Py_TYPE(deque), aslist, deque->maxlen, dict);
1322 }
1323 Py_XDECREF(dict);
1324 Py_DECREF(aslist);
1325 return result;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001326}
1327
1328PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
1329
1330static PyObject *
1331deque_repr(PyObject *deque)
1332{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001333 PyObject *aslist, *result;
1334 int i;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336 i = Py_ReprEnter(deque);
1337 if (i != 0) {
1338 if (i < 0)
1339 return NULL;
1340 return PyUnicode_FromString("[...]");
1341 }
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001343 aslist = PySequence_List(deque);
1344 if (aslist == NULL) {
1345 Py_ReprLeave(deque);
1346 return NULL;
1347 }
Raymond Hettingera7f630092015-10-10 23:56:02 -04001348 if (((dequeobject *)deque)->maxlen >= 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001349 result = PyUnicode_FromFormat("deque(%R, maxlen=%zd)",
1350 aslist, ((dequeobject *)deque)->maxlen);
1351 else
1352 result = PyUnicode_FromFormat("deque(%R)", aslist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001353 Py_ReprLeave(deque);
Raymond Hettinger2b2b7532015-09-05 17:05:52 -07001354 Py_DECREF(aslist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001355 return result;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001356}
1357
Raymond Hettinger738ec902004-02-29 02:15:56 +00001358static PyObject *
1359deque_richcompare(PyObject *v, PyObject *w, int op)
1360{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001361 PyObject *it1=NULL, *it2=NULL, *x, *y;
1362 Py_ssize_t vs, ws;
1363 int b, cmp=-1;
Raymond Hettinger738ec902004-02-29 02:15:56 +00001364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001365 if (!PyObject_TypeCheck(v, &deque_type) ||
1366 !PyObject_TypeCheck(w, &deque_type)) {
Brian Curtindfc80e32011-08-10 20:28:54 -05001367 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001368 }
Raymond Hettinger738ec902004-02-29 02:15:56 +00001369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001370 /* Shortcuts */
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001371 vs = Py_SIZE((dequeobject *)v);
1372 ws = Py_SIZE((dequeobject *)w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001373 if (op == Py_EQ) {
1374 if (v == w)
1375 Py_RETURN_TRUE;
1376 if (vs != ws)
1377 Py_RETURN_FALSE;
1378 }
1379 if (op == Py_NE) {
1380 if (v == w)
1381 Py_RETURN_FALSE;
1382 if (vs != ws)
1383 Py_RETURN_TRUE;
1384 }
Raymond Hettinger738ec902004-02-29 02:15:56 +00001385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001386 /* Search for the first index where items are different */
1387 it1 = PyObject_GetIter(v);
1388 if (it1 == NULL)
1389 goto done;
1390 it2 = PyObject_GetIter(w);
1391 if (it2 == NULL)
1392 goto done;
1393 for (;;) {
1394 x = PyIter_Next(it1);
1395 if (x == NULL && PyErr_Occurred())
1396 goto done;
1397 y = PyIter_Next(it2);
1398 if (x == NULL || y == NULL)
1399 break;
1400 b = PyObject_RichCompareBool(x, y, Py_EQ);
1401 if (b == 0) {
1402 cmp = PyObject_RichCompareBool(x, y, op);
1403 Py_DECREF(x);
1404 Py_DECREF(y);
1405 goto done;
1406 }
1407 Py_DECREF(x);
1408 Py_DECREF(y);
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -07001409 if (b < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 goto done;
1411 }
1412 /* We reached the end of one deque or both */
1413 Py_XDECREF(x);
1414 Py_XDECREF(y);
1415 if (PyErr_Occurred())
1416 goto done;
1417 switch (op) {
1418 case Py_LT: cmp = y != NULL; break; /* if w was longer */
1419 case Py_LE: cmp = x == NULL; break; /* if v was not longer */
1420 case Py_EQ: cmp = x == y; break; /* if we reached the end of both */
1421 case Py_NE: cmp = x != y; break; /* if one deque continues */
1422 case Py_GT: cmp = x != NULL; break; /* if v was longer */
1423 case Py_GE: cmp = y == NULL; break; /* if w was not longer */
1424 }
Tim Peters1065f752004-10-01 01:03:29 +00001425
Raymond Hettinger738ec902004-02-29 02:15:56 +00001426done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001427 Py_XDECREF(it1);
1428 Py_XDECREF(it2);
1429 if (cmp == 1)
1430 Py_RETURN_TRUE;
1431 if (cmp == 0)
1432 Py_RETURN_FALSE;
1433 return NULL;
Raymond Hettinger738ec902004-02-29 02:15:56 +00001434}
1435
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001436static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001437deque_init(dequeobject *deque, PyObject *args, PyObject *kwdargs)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001438{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001439 PyObject *iterable = NULL;
1440 PyObject *maxlenobj = NULL;
1441 Py_ssize_t maxlen = -1;
1442 char *kwlist[] = {"iterable", "maxlen", 0};
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001443
Raymond Hettinger0d309402015-09-30 23:15:02 -07001444 if (kwdargs == NULL) {
1445 if (!PyArg_UnpackTuple(args, "deque()", 0, 2, &iterable, &maxlenobj))
1446 return -1;
1447 } else {
1448 if (!PyArg_ParseTupleAndKeywords(args, kwdargs, "|OO:deque", kwlist,
1449 &iterable, &maxlenobj))
1450 return -1;
1451 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001452 if (maxlenobj != NULL && maxlenobj != Py_None) {
1453 maxlen = PyLong_AsSsize_t(maxlenobj);
1454 if (maxlen == -1 && PyErr_Occurred())
1455 return -1;
1456 if (maxlen < 0) {
1457 PyErr_SetString(PyExc_ValueError, "maxlen must be non-negative");
1458 return -1;
1459 }
1460 }
1461 deque->maxlen = maxlen;
Raymond Hettinger0d309402015-09-30 23:15:02 -07001462 if (Py_SIZE(deque) > 0)
1463 deque_clear(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001464 if (iterable != NULL) {
1465 PyObject *rv = deque_extend(deque, iterable);
1466 if (rv == NULL)
1467 return -1;
1468 Py_DECREF(rv);
1469 }
1470 return 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001471}
1472
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001473static PyObject *
Jesus Cea16e2fca2012-08-03 14:49:42 +02001474deque_sizeof(dequeobject *deque, void *unused)
1475{
1476 Py_ssize_t res;
1477 Py_ssize_t blocks;
1478
Serhiy Storchaka5c4064e2015-12-19 20:05:25 +02001479 res = _PyObject_SIZE(Py_TYPE(deque));
Raymond Hettingerbc003412015-10-14 23:33:23 -07001480 blocks = (size_t)(deque->leftindex + Py_SIZE(deque) + BLOCKLEN - 1) / BLOCKLEN;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001481 assert(deque->leftindex + Py_SIZE(deque) - 1 ==
Jesus Cea16e2fca2012-08-03 14:49:42 +02001482 (blocks - 1) * BLOCKLEN + deque->rightindex);
1483 res += blocks * sizeof(block);
1484 return PyLong_FromSsize_t(res);
1485}
1486
1487PyDoc_STRVAR(sizeof_doc,
1488"D.__sizeof__() -- size of D in memory, in bytes");
1489
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001490static int
1491deque_bool(dequeobject *deque)
1492{
1493 return Py_SIZE(deque) != 0;
1494}
1495
Jesus Cea16e2fca2012-08-03 14:49:42 +02001496static PyObject *
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001497deque_get_maxlen(dequeobject *deque)
1498{
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -07001499 if (deque->maxlen < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001500 Py_RETURN_NONE;
1501 return PyLong_FromSsize_t(deque->maxlen);
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001502}
1503
Raymond Hettinger41290a62015-03-31 08:12:23 -07001504
1505/* deque object ********************************************************/
1506
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001507static PyGetSetDef deque_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001508 {"maxlen", (getter)deque_get_maxlen, (setter)NULL,
1509 "maximum size of a deque or None if unbounded"},
1510 {0}
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001511};
1512
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001513static PySequenceMethods deque_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001514 (lenfunc)deque_len, /* sq_length */
Raymond Hettinger41290a62015-03-31 08:12:23 -07001515 (binaryfunc)deque_concat, /* sq_concat */
1516 (ssizeargfunc)deque_repeat, /* sq_repeat */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001517 (ssizeargfunc)deque_item, /* sq_item */
1518 0, /* sq_slice */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001519 (ssizeobjargproc)deque_ass_item, /* sq_ass_item */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001520 0, /* sq_ass_slice */
Raymond Hettinger39dadf72015-03-20 16:38:56 -07001521 (objobjproc)deque_contains, /* sq_contains */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001522 (binaryfunc)deque_inplace_concat, /* sq_inplace_concat */
Raymond Hettinger41290a62015-03-31 08:12:23 -07001523 (ssizeargfunc)deque_inplace_repeat, /* sq_inplace_repeat */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001524};
1525
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001526static PyNumberMethods deque_as_number = {
1527 0, /* nb_add */
1528 0, /* nb_subtract */
1529 0, /* nb_multiply */
1530 0, /* nb_remainder */
1531 0, /* nb_divmod */
1532 0, /* nb_power */
1533 0, /* nb_negative */
1534 0, /* nb_positive */
1535 0, /* nb_absolute */
1536 (inquiry)deque_bool, /* nb_bool */
1537 0, /* nb_invert */
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001538 };
1539
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001540static PyObject *deque_iter(dequeobject *deque);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001541static PyObject *deque_reviter(dequeobject *deque);
Tim Peters1065f752004-10-01 01:03:29 +00001542PyDoc_STRVAR(reversed_doc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001543 "D.__reversed__() -- return a reverse iterator over the deque");
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001544
1545static PyMethodDef deque_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001546 {"append", (PyCFunction)deque_append,
1547 METH_O, append_doc},
1548 {"appendleft", (PyCFunction)deque_appendleft,
1549 METH_O, appendleft_doc},
1550 {"clear", (PyCFunction)deque_clearmethod,
1551 METH_NOARGS, clear_doc},
1552 {"__copy__", (PyCFunction)deque_copy,
1553 METH_NOARGS, copy_doc},
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001554 {"copy", (PyCFunction)deque_copy,
1555 METH_NOARGS, copy_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001556 {"count", (PyCFunction)deque_count,
Raymond Hettinger0f6f9472015-03-21 01:42:10 -07001557 METH_O, count_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001558 {"extend", (PyCFunction)deque_extend,
1559 METH_O, extend_doc},
1560 {"extendleft", (PyCFunction)deque_extendleft,
1561 METH_O, extendleft_doc},
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001562 {"index", (PyCFunction)deque_index,
1563 METH_VARARGS, index_doc},
1564 {"insert", (PyCFunction)deque_insert,
1565 METH_VARARGS, insert_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001566 {"pop", (PyCFunction)deque_pop,
1567 METH_NOARGS, pop_doc},
1568 {"popleft", (PyCFunction)deque_popleft,
1569 METH_NOARGS, popleft_doc},
Raymond Hettinger0f6f9472015-03-21 01:42:10 -07001570 {"__reduce__", (PyCFunction)deque_reduce,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001571 METH_NOARGS, reduce_doc},
1572 {"remove", (PyCFunction)deque_remove,
1573 METH_O, remove_doc},
1574 {"__reversed__", (PyCFunction)deque_reviter,
1575 METH_NOARGS, reversed_doc},
1576 {"reverse", (PyCFunction)deque_reverse,
1577 METH_NOARGS, reverse_doc},
1578 {"rotate", (PyCFunction)deque_rotate,
Jesus Cea16e2fca2012-08-03 14:49:42 +02001579 METH_VARARGS, rotate_doc},
1580 {"__sizeof__", (PyCFunction)deque_sizeof,
1581 METH_NOARGS, sizeof_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001582 {NULL, NULL} /* sentinel */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001583};
1584
1585PyDoc_STRVAR(deque_doc,
Andrew Svetlov6a5c7c32012-10-31 11:50:40 +02001586"deque([iterable[, maxlen]]) --> deque object\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001587\n\
Raymond Hettinger41290a62015-03-31 08:12:23 -07001588A list-like sequence optimized for data accesses near its endpoints.");
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001589
Neal Norwitz87f10132004-02-29 15:40:53 +00001590static PyTypeObject deque_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001591 PyVarObject_HEAD_INIT(NULL, 0)
1592 "collections.deque", /* tp_name */
1593 sizeof(dequeobject), /* tp_basicsize */
1594 0, /* tp_itemsize */
1595 /* methods */
1596 (destructor)deque_dealloc, /* tp_dealloc */
1597 0, /* tp_print */
1598 0, /* tp_getattr */
1599 0, /* tp_setattr */
1600 0, /* tp_reserved */
1601 deque_repr, /* tp_repr */
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001602 &deque_as_number, /* tp_as_number */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001603 &deque_as_sequence, /* tp_as_sequence */
1604 0, /* tp_as_mapping */
Georg Brandlf038b322010-10-18 07:35:09 +00001605 PyObject_HashNotImplemented, /* tp_hash */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001606 0, /* tp_call */
1607 0, /* tp_str */
1608 PyObject_GenericGetAttr, /* tp_getattro */
1609 0, /* tp_setattro */
1610 0, /* tp_as_buffer */
1611 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
Georg Brandlf038b322010-10-18 07:35:09 +00001612 /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001613 deque_doc, /* tp_doc */
1614 (traverseproc)deque_traverse, /* tp_traverse */
1615 (inquiry)deque_clear, /* tp_clear */
1616 (richcmpfunc)deque_richcompare, /* tp_richcompare */
Georg Brandlf038b322010-10-18 07:35:09 +00001617 offsetof(dequeobject, weakreflist), /* tp_weaklistoffset*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001618 (getiterfunc)deque_iter, /* tp_iter */
1619 0, /* tp_iternext */
1620 deque_methods, /* tp_methods */
1621 0, /* tp_members */
Georg Brandlf038b322010-10-18 07:35:09 +00001622 deque_getset, /* tp_getset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001623 0, /* tp_base */
1624 0, /* tp_dict */
1625 0, /* tp_descr_get */
1626 0, /* tp_descr_set */
1627 0, /* tp_dictoffset */
1628 (initproc)deque_init, /* tp_init */
1629 PyType_GenericAlloc, /* tp_alloc */
1630 deque_new, /* tp_new */
1631 PyObject_GC_Del, /* tp_free */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001632};
1633
1634/*********************** Deque Iterator **************************/
1635
1636typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001637 PyObject_HEAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001638 block *b;
Raymond Hettinger87e69122015-03-02 23:32:02 -08001639 Py_ssize_t index;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001640 dequeobject *deque;
Raymond Hettingerf9d9c792015-03-02 22:47:46 -08001641 size_t state; /* state when the iterator is created */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001642 Py_ssize_t counter; /* number of items remaining for iteration */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001643} dequeiterobject;
1644
Martin v. Löwis59683e82008-06-13 07:50:45 +00001645static PyTypeObject dequeiter_type;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001646
1647static PyObject *
1648deque_iter(dequeobject *deque)
1649{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001650 dequeiterobject *it;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001652 it = PyObject_GC_New(dequeiterobject, &dequeiter_type);
1653 if (it == NULL)
1654 return NULL;
1655 it->b = deque->leftblock;
1656 it->index = deque->leftindex;
1657 Py_INCREF(deque);
1658 it->deque = deque;
1659 it->state = deque->state;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001660 it->counter = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001661 PyObject_GC_Track(it);
1662 return (PyObject *)it;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001663}
1664
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001665static int
1666dequeiter_traverse(dequeiterobject *dio, visitproc visit, void *arg)
1667{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001668 Py_VISIT(dio->deque);
1669 return 0;
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001670}
1671
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001672static void
1673dequeiter_dealloc(dequeiterobject *dio)
1674{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001675 Py_XDECREF(dio->deque);
1676 PyObject_GC_Del(dio);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001677}
1678
1679static PyObject *
1680dequeiter_next(dequeiterobject *it)
1681{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001682 PyObject *item;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001683
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001684 if (it->deque->state != it->state) {
1685 it->counter = 0;
1686 PyErr_SetString(PyExc_RuntimeError,
1687 "deque mutated during iteration");
1688 return NULL;
1689 }
1690 if (it->counter == 0)
1691 return NULL;
1692 assert (!(it->b == it->deque->rightblock &&
1693 it->index > it->deque->rightindex));
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001694
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001695 item = it->b->data[it->index];
1696 it->index++;
1697 it->counter--;
1698 if (it->index == BLOCKLEN && it->counter > 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -10001699 CHECK_NOT_END(it->b->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001700 it->b = it->b->rightlink;
1701 it->index = 0;
1702 }
1703 Py_INCREF(item);
1704 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001705}
1706
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001707static PyObject *
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001708dequeiter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1709{
1710 Py_ssize_t i, index=0;
1711 PyObject *deque;
1712 dequeiterobject *it;
1713 if (!PyArg_ParseTuple(args, "O!|n", &deque_type, &deque, &index))
1714 return NULL;
1715 assert(type == &dequeiter_type);
1716
1717 it = (dequeiterobject*)deque_iter((dequeobject *)deque);
1718 if (!it)
1719 return NULL;
1720 /* consume items from the queue */
1721 for(i=0; i<index; i++) {
1722 PyObject *item = dequeiter_next(it);
1723 if (item) {
1724 Py_DECREF(item);
1725 } else {
1726 if (it->counter) {
1727 Py_DECREF(it);
1728 return NULL;
1729 } else
1730 break;
1731 }
1732 }
1733 return (PyObject*)it;
1734}
1735
1736static PyObject *
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001737dequeiter_len(dequeiterobject *it)
1738{
Antoine Pitrou554f3342010-08-17 18:30:06 +00001739 return PyLong_FromSsize_t(it->counter);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001740}
1741
Armin Rigof5b3e362006-02-11 21:32:43 +00001742PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001743
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001744static PyObject *
1745dequeiter_reduce(dequeiterobject *it)
1746{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001747 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 +00001748}
1749
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001750static PyMethodDef dequeiter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001751 {"__length_hint__", (PyCFunction)dequeiter_len, METH_NOARGS, length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001752 {"__reduce__", (PyCFunction)dequeiter_reduce, METH_NOARGS, reduce_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001753 {NULL, NULL} /* sentinel */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001754};
1755
Martin v. Löwis59683e82008-06-13 07:50:45 +00001756static PyTypeObject dequeiter_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001757 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger87e69122015-03-02 23:32:02 -08001758 "_collections._deque_iterator", /* tp_name */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001759 sizeof(dequeiterobject), /* tp_basicsize */
1760 0, /* tp_itemsize */
1761 /* methods */
1762 (destructor)dequeiter_dealloc, /* tp_dealloc */
1763 0, /* tp_print */
1764 0, /* tp_getattr */
1765 0, /* tp_setattr */
1766 0, /* tp_reserved */
1767 0, /* tp_repr */
1768 0, /* tp_as_number */
1769 0, /* tp_as_sequence */
1770 0, /* tp_as_mapping */
1771 0, /* tp_hash */
1772 0, /* tp_call */
1773 0, /* tp_str */
1774 PyObject_GenericGetAttr, /* tp_getattro */
1775 0, /* tp_setattro */
1776 0, /* tp_as_buffer */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001777 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001778 0, /* tp_doc */
1779 (traverseproc)dequeiter_traverse, /* tp_traverse */
1780 0, /* tp_clear */
1781 0, /* tp_richcompare */
1782 0, /* tp_weaklistoffset */
1783 PyObject_SelfIter, /* tp_iter */
1784 (iternextfunc)dequeiter_next, /* tp_iternext */
1785 dequeiter_methods, /* tp_methods */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001786 0, /* tp_members */
1787 0, /* tp_getset */
1788 0, /* tp_base */
1789 0, /* tp_dict */
1790 0, /* tp_descr_get */
1791 0, /* tp_descr_set */
1792 0, /* tp_dictoffset */
1793 0, /* tp_init */
1794 0, /* tp_alloc */
1795 dequeiter_new, /* tp_new */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001796 0,
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001797};
1798
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001799/*********************** Deque Reverse Iterator **************************/
1800
Martin v. Löwis59683e82008-06-13 07:50:45 +00001801static PyTypeObject dequereviter_type;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001802
1803static PyObject *
1804deque_reviter(dequeobject *deque)
1805{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001806 dequeiterobject *it;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001808 it = PyObject_GC_New(dequeiterobject, &dequereviter_type);
1809 if (it == NULL)
1810 return NULL;
1811 it->b = deque->rightblock;
1812 it->index = deque->rightindex;
1813 Py_INCREF(deque);
1814 it->deque = deque;
1815 it->state = deque->state;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001816 it->counter = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001817 PyObject_GC_Track(it);
1818 return (PyObject *)it;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001819}
1820
1821static PyObject *
1822dequereviter_next(dequeiterobject *it)
1823{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001824 PyObject *item;
1825 if (it->counter == 0)
1826 return NULL;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001827
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001828 if (it->deque->state != it->state) {
1829 it->counter = 0;
1830 PyErr_SetString(PyExc_RuntimeError,
1831 "deque mutated during iteration");
1832 return NULL;
1833 }
1834 assert (!(it->b == it->deque->leftblock &&
1835 it->index < it->deque->leftindex));
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001836
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001837 item = it->b->data[it->index];
1838 it->index--;
1839 it->counter--;
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -07001840 if (it->index < 0 && it->counter > 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -10001841 CHECK_NOT_END(it->b->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001842 it->b = it->b->leftlink;
1843 it->index = BLOCKLEN - 1;
1844 }
1845 Py_INCREF(item);
1846 return item;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001847}
1848
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001849static PyObject *
1850dequereviter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1851{
1852 Py_ssize_t i, index=0;
1853 PyObject *deque;
1854 dequeiterobject *it;
1855 if (!PyArg_ParseTuple(args, "O!|n", &deque_type, &deque, &index))
1856 return NULL;
1857 assert(type == &dequereviter_type);
1858
1859 it = (dequeiterobject*)deque_reviter((dequeobject *)deque);
1860 if (!it)
1861 return NULL;
1862 /* consume items from the queue */
1863 for(i=0; i<index; i++) {
1864 PyObject *item = dequereviter_next(it);
1865 if (item) {
1866 Py_DECREF(item);
1867 } else {
1868 if (it->counter) {
1869 Py_DECREF(it);
1870 return NULL;
1871 } else
1872 break;
1873 }
1874 }
1875 return (PyObject*)it;
1876}
1877
Martin v. Löwis59683e82008-06-13 07:50:45 +00001878static PyTypeObject dequereviter_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001879 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger87e69122015-03-02 23:32:02 -08001880 "_collections._deque_reverse_iterator", /* tp_name */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001881 sizeof(dequeiterobject), /* tp_basicsize */
1882 0, /* tp_itemsize */
1883 /* methods */
1884 (destructor)dequeiter_dealloc, /* tp_dealloc */
1885 0, /* tp_print */
1886 0, /* tp_getattr */
1887 0, /* tp_setattr */
1888 0, /* tp_reserved */
1889 0, /* tp_repr */
1890 0, /* tp_as_number */
1891 0, /* tp_as_sequence */
1892 0, /* tp_as_mapping */
1893 0, /* tp_hash */
1894 0, /* tp_call */
1895 0, /* tp_str */
1896 PyObject_GenericGetAttr, /* tp_getattro */
1897 0, /* tp_setattro */
1898 0, /* tp_as_buffer */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001899 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001900 0, /* tp_doc */
1901 (traverseproc)dequeiter_traverse, /* tp_traverse */
1902 0, /* tp_clear */
1903 0, /* tp_richcompare */
1904 0, /* tp_weaklistoffset */
1905 PyObject_SelfIter, /* tp_iter */
1906 (iternextfunc)dequereviter_next, /* tp_iternext */
1907 dequeiter_methods, /* tp_methods */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001908 0, /* tp_members */
1909 0, /* tp_getset */
1910 0, /* tp_base */
1911 0, /* tp_dict */
1912 0, /* tp_descr_get */
1913 0, /* tp_descr_set */
1914 0, /* tp_dictoffset */
1915 0, /* tp_init */
1916 0, /* tp_alloc */
1917 dequereviter_new, /* tp_new */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001918 0,
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001919};
1920
Guido van Rossum1968ad32006-02-25 22:38:04 +00001921/* defaultdict type *********************************************************/
1922
1923typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001924 PyDictObject dict;
1925 PyObject *default_factory;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001926} defdictobject;
1927
1928static PyTypeObject defdict_type; /* Forward */
1929
1930PyDoc_STRVAR(defdict_missing_doc,
1931"__missing__(key) # Called by __getitem__ for missing key; pseudo-code:\n\
Guido van Rossumd8faa362007-04-27 19:54:29 +00001932 if self.default_factory is None: raise KeyError((key,))\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00001933 self[key] = value = self.default_factory()\n\
1934 return value\n\
1935");
1936
1937static PyObject *
1938defdict_missing(defdictobject *dd, PyObject *key)
1939{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001940 PyObject *factory = dd->default_factory;
1941 PyObject *value;
1942 if (factory == NULL || factory == Py_None) {
1943 /* XXX Call dict.__missing__(key) */
1944 PyObject *tup;
1945 tup = PyTuple_Pack(1, key);
1946 if (!tup) return NULL;
1947 PyErr_SetObject(PyExc_KeyError, tup);
1948 Py_DECREF(tup);
1949 return NULL;
1950 }
1951 value = PyEval_CallObject(factory, NULL);
1952 if (value == NULL)
1953 return value;
1954 if (PyObject_SetItem((PyObject *)dd, key, value) < 0) {
1955 Py_DECREF(value);
1956 return NULL;
1957 }
1958 return value;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001959}
1960
1961PyDoc_STRVAR(defdict_copy_doc, "D.copy() -> a shallow copy of D.");
1962
1963static PyObject *
1964defdict_copy(defdictobject *dd)
1965{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001966 /* This calls the object's class. That only works for subclasses
1967 whose class constructor has the same signature. Subclasses that
1968 define a different constructor signature must override copy().
1969 */
Raymond Hettinger54628fa2009-08-04 19:16:39 +00001970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001971 if (dd->default_factory == NULL)
1972 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd), Py_None, dd, NULL);
1973 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd),
1974 dd->default_factory, dd, NULL);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001975}
1976
1977static PyObject *
1978defdict_reduce(defdictobject *dd)
1979{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001980 /* __reduce__ must return a 5-tuple as follows:
Guido van Rossum1968ad32006-02-25 22:38:04 +00001981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001982 - factory function
1983 - tuple of args for the factory function
1984 - additional state (here None)
1985 - sequence iterator (here None)
1986 - dictionary iterator (yielding successive (key, value) pairs
Guido van Rossum1968ad32006-02-25 22:38:04 +00001987
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001988 This API is used by pickle.py and copy.py.
Guido van Rossum1968ad32006-02-25 22:38:04 +00001989
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001990 For this to be useful with pickle.py, the default_factory
1991 must be picklable; e.g., None, a built-in, or a global
1992 function in a module or package.
Guido van Rossum1968ad32006-02-25 22:38:04 +00001993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001994 Both shallow and deep copying are supported, but for deep
1995 copying, the default_factory must be deep-copyable; e.g. None,
1996 or a built-in (functions are not copyable at this time).
Guido van Rossum1968ad32006-02-25 22:38:04 +00001997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001998 This only works for subclasses as long as their constructor
1999 signature is compatible; the first argument must be the
2000 optional default_factory, defaulting to None.
2001 */
2002 PyObject *args;
2003 PyObject *items;
2004 PyObject *iter;
2005 PyObject *result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002006 _Py_IDENTIFIER(items);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002008 if (dd->default_factory == NULL || dd->default_factory == Py_None)
2009 args = PyTuple_New(0);
2010 else
2011 args = PyTuple_Pack(1, dd->default_factory);
2012 if (args == NULL)
2013 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002014 items = _PyObject_CallMethodId((PyObject *)dd, &PyId_items, "()");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002015 if (items == NULL) {
2016 Py_DECREF(args);
2017 return NULL;
2018 }
2019 iter = PyObject_GetIter(items);
2020 if (iter == NULL) {
2021 Py_DECREF(items);
2022 Py_DECREF(args);
2023 return NULL;
2024 }
2025 result = PyTuple_Pack(5, Py_TYPE(dd), args,
2026 Py_None, Py_None, iter);
2027 Py_DECREF(iter);
2028 Py_DECREF(items);
2029 Py_DECREF(args);
2030 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00002031}
2032
2033static PyMethodDef defdict_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002034 {"__missing__", (PyCFunction)defdict_missing, METH_O,
2035 defdict_missing_doc},
2036 {"copy", (PyCFunction)defdict_copy, METH_NOARGS,
2037 defdict_copy_doc},
2038 {"__copy__", (PyCFunction)defdict_copy, METH_NOARGS,
2039 defdict_copy_doc},
2040 {"__reduce__", (PyCFunction)defdict_reduce, METH_NOARGS,
2041 reduce_doc},
2042 {NULL}
Guido van Rossum1968ad32006-02-25 22:38:04 +00002043};
2044
2045static PyMemberDef defdict_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002046 {"default_factory", T_OBJECT,
2047 offsetof(defdictobject, default_factory), 0,
2048 PyDoc_STR("Factory for default value called by __missing__().")},
2049 {NULL}
Guido van Rossum1968ad32006-02-25 22:38:04 +00002050};
2051
2052static void
2053defdict_dealloc(defdictobject *dd)
2054{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002055 Py_CLEAR(dd->default_factory);
2056 PyDict_Type.tp_dealloc((PyObject *)dd);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002057}
2058
Guido van Rossum1968ad32006-02-25 22:38:04 +00002059static PyObject *
2060defdict_repr(defdictobject *dd)
2061{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002062 PyObject *baserepr;
2063 PyObject *defrepr;
2064 PyObject *result;
2065 baserepr = PyDict_Type.tp_repr((PyObject *)dd);
2066 if (baserepr == NULL)
2067 return NULL;
2068 if (dd->default_factory == NULL)
2069 defrepr = PyUnicode_FromString("None");
2070 else
2071 {
2072 int status = Py_ReprEnter(dd->default_factory);
2073 if (status != 0) {
Antoine Pitrouf5f1fe02012-02-15 02:42:46 +01002074 if (status < 0) {
2075 Py_DECREF(baserepr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002076 return NULL;
Antoine Pitrouf5f1fe02012-02-15 02:42:46 +01002077 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002078 defrepr = PyUnicode_FromString("...");
2079 }
2080 else
2081 defrepr = PyObject_Repr(dd->default_factory);
2082 Py_ReprLeave(dd->default_factory);
2083 }
2084 if (defrepr == NULL) {
2085 Py_DECREF(baserepr);
2086 return NULL;
2087 }
2088 result = PyUnicode_FromFormat("defaultdict(%U, %U)",
2089 defrepr, baserepr);
2090 Py_DECREF(defrepr);
2091 Py_DECREF(baserepr);
2092 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00002093}
2094
2095static int
2096defdict_traverse(PyObject *self, visitproc visit, void *arg)
2097{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002098 Py_VISIT(((defdictobject *)self)->default_factory);
2099 return PyDict_Type.tp_traverse(self, visit, arg);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002100}
2101
2102static int
2103defdict_tp_clear(defdictobject *dd)
2104{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002105 Py_CLEAR(dd->default_factory);
2106 return PyDict_Type.tp_clear((PyObject *)dd);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002107}
2108
2109static int
2110defdict_init(PyObject *self, PyObject *args, PyObject *kwds)
2111{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002112 defdictobject *dd = (defdictobject *)self;
2113 PyObject *olddefault = dd->default_factory;
2114 PyObject *newdefault = NULL;
2115 PyObject *newargs;
2116 int result;
2117 if (args == NULL || !PyTuple_Check(args))
2118 newargs = PyTuple_New(0);
2119 else {
2120 Py_ssize_t n = PyTuple_GET_SIZE(args);
2121 if (n > 0) {
2122 newdefault = PyTuple_GET_ITEM(args, 0);
2123 if (!PyCallable_Check(newdefault) && newdefault != Py_None) {
2124 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger239aba72015-07-20 03:09:22 -04002125 "first argument must be callable or None");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002126 return -1;
2127 }
2128 }
2129 newargs = PySequence_GetSlice(args, 1, n);
2130 }
2131 if (newargs == NULL)
2132 return -1;
2133 Py_XINCREF(newdefault);
2134 dd->default_factory = newdefault;
2135 result = PyDict_Type.tp_init(self, newargs, kwds);
2136 Py_DECREF(newargs);
2137 Py_XDECREF(olddefault);
2138 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00002139}
2140
2141PyDoc_STRVAR(defdict_doc,
Benjamin Peterson9cb33b72014-01-13 23:56:05 -05002142"defaultdict(default_factory[, ...]) --> dict with default factory\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00002143\n\
2144The default factory is called without arguments to produce\n\
2145a new value when a key is not present, in __getitem__ only.\n\
2146A defaultdict compares equal to a dict with the same items.\n\
Benjamin Peterson9cb33b72014-01-13 23:56:05 -05002147All remaining arguments are treated the same as if they were\n\
2148passed to the dict constructor, including keyword arguments.\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00002149");
2150
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002151/* See comment in xxsubtype.c */
2152#define DEFERRED_ADDRESS(ADDR) 0
2153
Guido van Rossum1968ad32006-02-25 22:38:04 +00002154static PyTypeObject defdict_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002155 PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0)
2156 "collections.defaultdict", /* tp_name */
2157 sizeof(defdictobject), /* tp_basicsize */
2158 0, /* tp_itemsize */
2159 /* methods */
2160 (destructor)defdict_dealloc, /* tp_dealloc */
2161 0, /* tp_print */
2162 0, /* tp_getattr */
2163 0, /* tp_setattr */
2164 0, /* tp_reserved */
2165 (reprfunc)defdict_repr, /* tp_repr */
2166 0, /* tp_as_number */
2167 0, /* tp_as_sequence */
2168 0, /* tp_as_mapping */
2169 0, /* tp_hash */
2170 0, /* tp_call */
2171 0, /* tp_str */
2172 PyObject_GenericGetAttr, /* tp_getattro */
2173 0, /* tp_setattro */
2174 0, /* tp_as_buffer */
2175 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
2176 /* tp_flags */
2177 defdict_doc, /* tp_doc */
2178 defdict_traverse, /* tp_traverse */
2179 (inquiry)defdict_tp_clear, /* tp_clear */
2180 0, /* tp_richcompare */
2181 0, /* tp_weaklistoffset*/
2182 0, /* tp_iter */
2183 0, /* tp_iternext */
2184 defdict_methods, /* tp_methods */
2185 defdict_members, /* tp_members */
2186 0, /* tp_getset */
2187 DEFERRED_ADDRESS(&PyDict_Type), /* tp_base */
2188 0, /* tp_dict */
2189 0, /* tp_descr_get */
2190 0, /* tp_descr_set */
2191 0, /* tp_dictoffset */
2192 defdict_init, /* tp_init */
2193 PyType_GenericAlloc, /* tp_alloc */
2194 0, /* tp_new */
2195 PyObject_GC_Del, /* tp_free */
Guido van Rossum1968ad32006-02-25 22:38:04 +00002196};
2197
Raymond Hettinger96f34102010-12-15 16:30:37 +00002198/* helper function for Counter *********************************************/
2199
2200PyDoc_STRVAR(_count_elements_doc,
2201"_count_elements(mapping, iterable) -> None\n\
2202\n\
2203Count elements in the iterable, updating the mappping");
2204
2205static PyObject *
2206_count_elements(PyObject *self, PyObject *args)
2207{
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002208 _Py_IDENTIFIER(get);
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002209 _Py_IDENTIFIER(__setitem__);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002210 PyObject *it, *iterable, *mapping, *oldval;
2211 PyObject *newval = NULL;
2212 PyObject *key = NULL;
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002213 PyObject *zero = NULL;
Raymond Hettinger96f34102010-12-15 16:30:37 +00002214 PyObject *one = NULL;
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002215 PyObject *bound_get = NULL;
2216 PyObject *mapping_get;
2217 PyObject *dict_get;
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002218 PyObject *mapping_setitem;
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002219 PyObject *dict_setitem;
Raymond Hettinger96f34102010-12-15 16:30:37 +00002220
2221 if (!PyArg_UnpackTuple(args, "_count_elements", 2, 2, &mapping, &iterable))
2222 return NULL;
2223
Raymond Hettinger96f34102010-12-15 16:30:37 +00002224 it = PyObject_GetIter(iterable);
2225 if (it == NULL)
2226 return NULL;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002227
Raymond Hettinger96f34102010-12-15 16:30:37 +00002228 one = PyLong_FromLong(1);
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002229 if (one == NULL)
2230 goto done;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002231
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002232 /* Only take the fast path when get() and __setitem__()
2233 * have not been overridden.
2234 */
2235 mapping_get = _PyType_LookupId(Py_TYPE(mapping), &PyId_get);
2236 dict_get = _PyType_LookupId(&PyDict_Type, &PyId_get);
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002237 mapping_setitem = _PyType_LookupId(Py_TYPE(mapping), &PyId___setitem__);
2238 dict_setitem = _PyType_LookupId(&PyDict_Type, &PyId___setitem__);
2239
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002240 if (mapping_get != NULL && mapping_get == dict_get &&
2241 mapping_setitem != NULL && mapping_setitem == dict_setitem) {
Raymond Hettinger426e0522011-01-03 02:12:02 +00002242 while (1) {
Raymond Hettinger507d9972014-05-18 21:32:40 +01002243 /* Fast path advantages:
2244 1. Eliminate double hashing
2245 (by re-using the same hash for both the get and set)
2246 2. Avoid argument overhead of PyObject_CallFunctionObjArgs
2247 (argument tuple creation and parsing)
2248 3. Avoid indirection through a bound method object
2249 (creates another argument tuple)
2250 4. Avoid initial increment from zero
2251 (reuse an existing one-object instead)
2252 */
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002253 Py_hash_t hash;
2254
Raymond Hettinger426e0522011-01-03 02:12:02 +00002255 key = PyIter_Next(it);
Victor Stinnera154b5c2011-04-20 23:23:52 +02002256 if (key == NULL)
2257 break;
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002258
2259 if (!PyUnicode_CheckExact(key) ||
2260 (hash = ((PyASCIIObject *) key)->hash) == -1)
2261 {
2262 hash = PyObject_Hash(key);
Raymond Hettingerda2850f2015-02-27 12:42:54 -08002263 if (hash == -1)
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002264 goto done;
2265 }
2266
2267 oldval = _PyDict_GetItem_KnownHash(mapping, key, hash);
Raymond Hettinger426e0522011-01-03 02:12:02 +00002268 if (oldval == NULL) {
Raymond Hettinger28c995d2015-08-14 02:07:41 -07002269 if (_PyDict_SetItem_KnownHash(mapping, key, one, hash) < 0)
Raymond Hettinger507d9972014-05-18 21:32:40 +01002270 goto done;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002271 } else {
2272 newval = PyNumber_Add(oldval, one);
2273 if (newval == NULL)
Raymond Hettinger507d9972014-05-18 21:32:40 +01002274 goto done;
Raymond Hettinger28c995d2015-08-14 02:07:41 -07002275 if (_PyDict_SetItem_KnownHash(mapping, key, newval, hash) < 0)
Raymond Hettinger507d9972014-05-18 21:32:40 +01002276 goto done;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002277 Py_CLEAR(newval);
2278 }
2279 Py_DECREF(key);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002280 }
Raymond Hettinger426e0522011-01-03 02:12:02 +00002281 } else {
Victor Stinnere7f516c2013-11-06 23:52:55 +01002282 bound_get = _PyObject_GetAttrId(mapping, &PyId_get);
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002283 if (bound_get == NULL)
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002284 goto done;
2285
2286 zero = PyLong_FromLong(0);
2287 if (zero == NULL)
2288 goto done;
2289
Raymond Hettinger426e0522011-01-03 02:12:02 +00002290 while (1) {
2291 key = PyIter_Next(it);
Victor Stinnera154b5c2011-04-20 23:23:52 +02002292 if (key == NULL)
2293 break;
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002294 oldval = PyObject_CallFunctionObjArgs(bound_get, key, zero, NULL);
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002295 if (oldval == NULL)
2296 break;
2297 newval = PyNumber_Add(oldval, one);
2298 Py_DECREF(oldval);
2299 if (newval == NULL)
2300 break;
Raymond Hettinger28c995d2015-08-14 02:07:41 -07002301 if (PyObject_SetItem(mapping, key, newval) < 0)
Raymond Hettinger96f34102010-12-15 16:30:37 +00002302 break;
2303 Py_CLEAR(newval);
Raymond Hettinger426e0522011-01-03 02:12:02 +00002304 Py_DECREF(key);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002305 }
Raymond Hettinger96f34102010-12-15 16:30:37 +00002306 }
Raymond Hettinger426e0522011-01-03 02:12:02 +00002307
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002308done:
Raymond Hettinger96f34102010-12-15 16:30:37 +00002309 Py_DECREF(it);
2310 Py_XDECREF(key);
2311 Py_XDECREF(newval);
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002312 Py_XDECREF(bound_get);
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002313 Py_XDECREF(zero);
2314 Py_XDECREF(one);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002315 if (PyErr_Occurred())
2316 return NULL;
2317 Py_RETURN_NONE;
2318}
2319
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002320/* module level code ********************************************************/
2321
2322PyDoc_STRVAR(module_doc,
Guido van Rossum1968ad32006-02-25 22:38:04 +00002323"High performance data structures.\n\
2324- deque: ordered collection accessible from endpoints only\n\
2325- defaultdict: dict subclass with a default value factory\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002326");
2327
Raymond Hettinger96f34102010-12-15 16:30:37 +00002328static struct PyMethodDef module_functions[] = {
2329 {"_count_elements", _count_elements, METH_VARARGS, _count_elements_doc},
2330 {NULL, NULL} /* sentinel */
2331};
Martin v. Löwis1a214512008-06-11 05:26:20 +00002332
2333static struct PyModuleDef _collectionsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002334 PyModuleDef_HEAD_INIT,
2335 "_collections",
2336 module_doc,
2337 -1,
Raymond Hettinger96f34102010-12-15 16:30:37 +00002338 module_functions,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002339 NULL,
2340 NULL,
2341 NULL,
2342 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002343};
2344
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002345PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002346PyInit__collections(void)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002347{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002348 PyObject *m;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002350 m = PyModule_Create(&_collectionsmodule);
2351 if (m == NULL)
2352 return NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002353
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002354 if (PyType_Ready(&deque_type) < 0)
2355 return NULL;
2356 Py_INCREF(&deque_type);
2357 PyModule_AddObject(m, "deque", (PyObject *)&deque_type);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002359 defdict_type.tp_base = &PyDict_Type;
2360 if (PyType_Ready(&defdict_type) < 0)
2361 return NULL;
2362 Py_INCREF(&defdict_type);
2363 PyModule_AddObject(m, "defaultdict", (PyObject *)&defdict_type);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002364
Eric Snow47db7172015-05-29 22:21:39 -06002365 Py_INCREF(&PyODict_Type);
2366 PyModule_AddObject(m, "OrderedDict", (PyObject *)&PyODict_Type);
2367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002368 if (PyType_Ready(&dequeiter_type) < 0)
2369 return NULL;
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002370 Py_INCREF(&dequeiter_type);
2371 PyModule_AddObject(m, "_deque_iterator", (PyObject *)&dequeiter_type);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002373 if (PyType_Ready(&dequereviter_type) < 0)
2374 return NULL;
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002375 Py_INCREF(&dequereviter_type);
2376 PyModule_AddObject(m, "_deque_reverse_iterator", (PyObject *)&dequereviter_type);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00002377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002378 return m;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002379}