blob: 6a5358494ff5638ce169660660be0d5b432c077c [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 block *b;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001226 Py_ssize_t n, len=Py_SIZE(deque), halflen=(len+1)>>1, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001227
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001228 if (!valid_index(i, len)) {
1229 PyErr_SetString(PyExc_IndexError, "deque index out of range");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001230 return -1;
1231 }
1232 if (v == NULL)
1233 return deque_del_item(deque, i);
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001235 i += deque->leftindex;
Raymond Hettingerc2083082015-02-28 23:29:16 -08001236 n = (Py_ssize_t)((size_t) i / BLOCKLEN);
1237 i = (Py_ssize_t)((size_t) i % BLOCKLEN);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001238 if (index <= halflen) {
1239 b = deque->leftblock;
1240 while (n--)
1241 b = b->rightlink;
1242 } else {
Raymond Hettingera473b9d2015-02-28 17:49:47 -08001243 n = (Py_ssize_t)(
Raymond Hettingerc2083082015-02-28 23:29:16 -08001244 ((size_t)(deque->leftindex + Py_SIZE(deque) - 1))
Raymond Hettingera473b9d2015-02-28 17:49:47 -08001245 / BLOCKLEN - n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001246 b = deque->rightblock;
1247 while (n--)
1248 b = b->leftlink;
1249 }
1250 Py_INCREF(v);
Serhiy Storchaka1ed017a2015-12-27 15:51:32 +02001251 Py_SETREF(b->data[i], v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001252 return 0;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001253}
1254
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001255static void
1256deque_dealloc(dequeobject *deque)
1257{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258 PyObject_GC_UnTrack(deque);
1259 if (deque->weakreflist != NULL)
1260 PyObject_ClearWeakRefs((PyObject *) deque);
1261 if (deque->leftblock != NULL) {
1262 deque_clear(deque);
1263 assert(deque->leftblock != NULL);
1264 freeblock(deque->leftblock);
1265 }
1266 deque->leftblock = NULL;
1267 deque->rightblock = NULL;
1268 Py_TYPE(deque)->tp_free(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001269}
1270
1271static int
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001272deque_traverse(dequeobject *deque, visitproc visit, void *arg)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001273{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001274 block *b;
1275 PyObject *item;
1276 Py_ssize_t index;
1277 Py_ssize_t indexlo = deque->leftindex;
Raymond Hettinger1286d142015-10-14 23:16:57 -07001278 Py_ssize_t indexhigh;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001279
Raymond Hettinger5bfa8672013-07-06 11:58:09 -10001280 for (b = deque->leftblock; b != deque->rightblock; b = b->rightlink) {
1281 for (index = indexlo; index < BLOCKLEN ; index++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001282 item = b->data[index];
1283 Py_VISIT(item);
1284 }
1285 indexlo = 0;
1286 }
Raymond Hettinger1286d142015-10-14 23:16:57 -07001287 indexhigh = deque->rightindex;
1288 for (index = indexlo; index <= indexhigh; index++) {
Raymond Hettinger5bfa8672013-07-06 11:58:09 -10001289 item = b->data[index];
1290 Py_VISIT(item);
1291 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001292 return 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001293}
1294
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001295static PyObject *
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001296deque_reduce(dequeobject *deque)
1297{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001298 PyObject *dict, *result, *aslist;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001299 _Py_IDENTIFIER(__dict__);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001300
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001301 dict = _PyObject_GetAttrId((PyObject *)deque, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001302 if (dict == NULL)
1303 PyErr_Clear();
1304 aslist = PySequence_List((PyObject *)deque);
1305 if (aslist == NULL) {
1306 Py_XDECREF(dict);
1307 return NULL;
1308 }
1309 if (dict == NULL) {
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -07001310 if (deque->maxlen < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001311 result = Py_BuildValue("O(O)", Py_TYPE(deque), aslist);
1312 else
1313 result = Py_BuildValue("O(On)", Py_TYPE(deque), aslist, deque->maxlen);
1314 } else {
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -07001315 if (deque->maxlen < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001316 result = Py_BuildValue("O(OO)O", Py_TYPE(deque), aslist, Py_None, dict);
1317 else
1318 result = Py_BuildValue("O(On)O", Py_TYPE(deque), aslist, deque->maxlen, dict);
1319 }
1320 Py_XDECREF(dict);
1321 Py_DECREF(aslist);
1322 return result;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001323}
1324
1325PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
1326
1327static PyObject *
1328deque_repr(PyObject *deque)
1329{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001330 PyObject *aslist, *result;
1331 int i;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001333 i = Py_ReprEnter(deque);
1334 if (i != 0) {
1335 if (i < 0)
1336 return NULL;
1337 return PyUnicode_FromString("[...]");
1338 }
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001340 aslist = PySequence_List(deque);
1341 if (aslist == NULL) {
1342 Py_ReprLeave(deque);
1343 return NULL;
1344 }
Raymond Hettingera7f630092015-10-10 23:56:02 -04001345 if (((dequeobject *)deque)->maxlen >= 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001346 result = PyUnicode_FromFormat("deque(%R, maxlen=%zd)",
1347 aslist, ((dequeobject *)deque)->maxlen);
1348 else
1349 result = PyUnicode_FromFormat("deque(%R)", aslist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001350 Py_ReprLeave(deque);
Raymond Hettinger2b2b7532015-09-05 17:05:52 -07001351 Py_DECREF(aslist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001352 return result;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001353}
1354
Raymond Hettinger738ec902004-02-29 02:15:56 +00001355static PyObject *
1356deque_richcompare(PyObject *v, PyObject *w, int op)
1357{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001358 PyObject *it1=NULL, *it2=NULL, *x, *y;
1359 Py_ssize_t vs, ws;
1360 int b, cmp=-1;
Raymond Hettinger738ec902004-02-29 02:15:56 +00001361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001362 if (!PyObject_TypeCheck(v, &deque_type) ||
1363 !PyObject_TypeCheck(w, &deque_type)) {
Brian Curtindfc80e32011-08-10 20:28:54 -05001364 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001365 }
Raymond Hettinger738ec902004-02-29 02:15:56 +00001366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001367 /* Shortcuts */
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001368 vs = Py_SIZE((dequeobject *)v);
1369 ws = Py_SIZE((dequeobject *)w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001370 if (op == Py_EQ) {
1371 if (v == w)
1372 Py_RETURN_TRUE;
1373 if (vs != ws)
1374 Py_RETURN_FALSE;
1375 }
1376 if (op == Py_NE) {
1377 if (v == w)
1378 Py_RETURN_FALSE;
1379 if (vs != ws)
1380 Py_RETURN_TRUE;
1381 }
Raymond Hettinger738ec902004-02-29 02:15:56 +00001382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001383 /* Search for the first index where items are different */
1384 it1 = PyObject_GetIter(v);
1385 if (it1 == NULL)
1386 goto done;
1387 it2 = PyObject_GetIter(w);
1388 if (it2 == NULL)
1389 goto done;
1390 for (;;) {
1391 x = PyIter_Next(it1);
1392 if (x == NULL && PyErr_Occurred())
1393 goto done;
1394 y = PyIter_Next(it2);
1395 if (x == NULL || y == NULL)
1396 break;
1397 b = PyObject_RichCompareBool(x, y, Py_EQ);
1398 if (b == 0) {
1399 cmp = PyObject_RichCompareBool(x, y, op);
1400 Py_DECREF(x);
1401 Py_DECREF(y);
1402 goto done;
1403 }
1404 Py_DECREF(x);
1405 Py_DECREF(y);
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -07001406 if (b < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001407 goto done;
1408 }
1409 /* We reached the end of one deque or both */
1410 Py_XDECREF(x);
1411 Py_XDECREF(y);
1412 if (PyErr_Occurred())
1413 goto done;
1414 switch (op) {
1415 case Py_LT: cmp = y != NULL; break; /* if w was longer */
1416 case Py_LE: cmp = x == NULL; break; /* if v was not longer */
1417 case Py_EQ: cmp = x == y; break; /* if we reached the end of both */
1418 case Py_NE: cmp = x != y; break; /* if one deque continues */
1419 case Py_GT: cmp = x != NULL; break; /* if v was longer */
1420 case Py_GE: cmp = y == NULL; break; /* if w was not longer */
1421 }
Tim Peters1065f752004-10-01 01:03:29 +00001422
Raymond Hettinger738ec902004-02-29 02:15:56 +00001423done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001424 Py_XDECREF(it1);
1425 Py_XDECREF(it2);
1426 if (cmp == 1)
1427 Py_RETURN_TRUE;
1428 if (cmp == 0)
1429 Py_RETURN_FALSE;
1430 return NULL;
Raymond Hettinger738ec902004-02-29 02:15:56 +00001431}
1432
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001433static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001434deque_init(dequeobject *deque, PyObject *args, PyObject *kwdargs)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001435{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001436 PyObject *iterable = NULL;
1437 PyObject *maxlenobj = NULL;
1438 Py_ssize_t maxlen = -1;
1439 char *kwlist[] = {"iterable", "maxlen", 0};
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001440
Raymond Hettinger0d309402015-09-30 23:15:02 -07001441 if (kwdargs == NULL) {
1442 if (!PyArg_UnpackTuple(args, "deque()", 0, 2, &iterable, &maxlenobj))
1443 return -1;
1444 } else {
1445 if (!PyArg_ParseTupleAndKeywords(args, kwdargs, "|OO:deque", kwlist,
1446 &iterable, &maxlenobj))
1447 return -1;
1448 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001449 if (maxlenobj != NULL && maxlenobj != Py_None) {
1450 maxlen = PyLong_AsSsize_t(maxlenobj);
1451 if (maxlen == -1 && PyErr_Occurred())
1452 return -1;
1453 if (maxlen < 0) {
1454 PyErr_SetString(PyExc_ValueError, "maxlen must be non-negative");
1455 return -1;
1456 }
1457 }
1458 deque->maxlen = maxlen;
Raymond Hettinger0d309402015-09-30 23:15:02 -07001459 if (Py_SIZE(deque) > 0)
1460 deque_clear(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001461 if (iterable != NULL) {
1462 PyObject *rv = deque_extend(deque, iterable);
1463 if (rv == NULL)
1464 return -1;
1465 Py_DECREF(rv);
1466 }
1467 return 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001468}
1469
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001470static PyObject *
Jesus Cea16e2fca2012-08-03 14:49:42 +02001471deque_sizeof(dequeobject *deque, void *unused)
1472{
1473 Py_ssize_t res;
1474 Py_ssize_t blocks;
1475
Serhiy Storchaka5c4064e2015-12-19 20:05:25 +02001476 res = _PyObject_SIZE(Py_TYPE(deque));
Raymond Hettingerbc003412015-10-14 23:33:23 -07001477 blocks = (size_t)(deque->leftindex + Py_SIZE(deque) + BLOCKLEN - 1) / BLOCKLEN;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001478 assert(deque->leftindex + Py_SIZE(deque) - 1 ==
Jesus Cea16e2fca2012-08-03 14:49:42 +02001479 (blocks - 1) * BLOCKLEN + deque->rightindex);
1480 res += blocks * sizeof(block);
1481 return PyLong_FromSsize_t(res);
1482}
1483
1484PyDoc_STRVAR(sizeof_doc,
1485"D.__sizeof__() -- size of D in memory, in bytes");
1486
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001487static int
1488deque_bool(dequeobject *deque)
1489{
1490 return Py_SIZE(deque) != 0;
1491}
1492
Jesus Cea16e2fca2012-08-03 14:49:42 +02001493static PyObject *
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001494deque_get_maxlen(dequeobject *deque)
1495{
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -07001496 if (deque->maxlen < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001497 Py_RETURN_NONE;
1498 return PyLong_FromSsize_t(deque->maxlen);
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001499}
1500
Raymond Hettinger41290a62015-03-31 08:12:23 -07001501
1502/* deque object ********************************************************/
1503
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001504static PyGetSetDef deque_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001505 {"maxlen", (getter)deque_get_maxlen, (setter)NULL,
1506 "maximum size of a deque or None if unbounded"},
1507 {0}
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001508};
1509
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001510static PySequenceMethods deque_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001511 (lenfunc)deque_len, /* sq_length */
Raymond Hettinger41290a62015-03-31 08:12:23 -07001512 (binaryfunc)deque_concat, /* sq_concat */
1513 (ssizeargfunc)deque_repeat, /* sq_repeat */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001514 (ssizeargfunc)deque_item, /* sq_item */
1515 0, /* sq_slice */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001516 (ssizeobjargproc)deque_ass_item, /* sq_ass_item */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001517 0, /* sq_ass_slice */
Raymond Hettinger39dadf72015-03-20 16:38:56 -07001518 (objobjproc)deque_contains, /* sq_contains */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001519 (binaryfunc)deque_inplace_concat, /* sq_inplace_concat */
Raymond Hettinger41290a62015-03-31 08:12:23 -07001520 (ssizeargfunc)deque_inplace_repeat, /* sq_inplace_repeat */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001521};
1522
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001523static PyNumberMethods deque_as_number = {
1524 0, /* nb_add */
1525 0, /* nb_subtract */
1526 0, /* nb_multiply */
1527 0, /* nb_remainder */
1528 0, /* nb_divmod */
1529 0, /* nb_power */
1530 0, /* nb_negative */
1531 0, /* nb_positive */
1532 0, /* nb_absolute */
1533 (inquiry)deque_bool, /* nb_bool */
1534 0, /* nb_invert */
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001535 };
1536
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001537static PyObject *deque_iter(dequeobject *deque);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001538static PyObject *deque_reviter(dequeobject *deque);
Tim Peters1065f752004-10-01 01:03:29 +00001539PyDoc_STRVAR(reversed_doc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001540 "D.__reversed__() -- return a reverse iterator over the deque");
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001541
1542static PyMethodDef deque_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001543 {"append", (PyCFunction)deque_append,
1544 METH_O, append_doc},
1545 {"appendleft", (PyCFunction)deque_appendleft,
1546 METH_O, appendleft_doc},
1547 {"clear", (PyCFunction)deque_clearmethod,
1548 METH_NOARGS, clear_doc},
1549 {"__copy__", (PyCFunction)deque_copy,
1550 METH_NOARGS, copy_doc},
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001551 {"copy", (PyCFunction)deque_copy,
1552 METH_NOARGS, copy_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001553 {"count", (PyCFunction)deque_count,
Raymond Hettinger0f6f9472015-03-21 01:42:10 -07001554 METH_O, count_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001555 {"extend", (PyCFunction)deque_extend,
1556 METH_O, extend_doc},
1557 {"extendleft", (PyCFunction)deque_extendleft,
1558 METH_O, extendleft_doc},
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001559 {"index", (PyCFunction)deque_index,
1560 METH_VARARGS, index_doc},
1561 {"insert", (PyCFunction)deque_insert,
1562 METH_VARARGS, insert_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001563 {"pop", (PyCFunction)deque_pop,
1564 METH_NOARGS, pop_doc},
1565 {"popleft", (PyCFunction)deque_popleft,
1566 METH_NOARGS, popleft_doc},
Raymond Hettinger0f6f9472015-03-21 01:42:10 -07001567 {"__reduce__", (PyCFunction)deque_reduce,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001568 METH_NOARGS, reduce_doc},
1569 {"remove", (PyCFunction)deque_remove,
1570 METH_O, remove_doc},
1571 {"__reversed__", (PyCFunction)deque_reviter,
1572 METH_NOARGS, reversed_doc},
1573 {"reverse", (PyCFunction)deque_reverse,
1574 METH_NOARGS, reverse_doc},
1575 {"rotate", (PyCFunction)deque_rotate,
Jesus Cea16e2fca2012-08-03 14:49:42 +02001576 METH_VARARGS, rotate_doc},
1577 {"__sizeof__", (PyCFunction)deque_sizeof,
1578 METH_NOARGS, sizeof_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001579 {NULL, NULL} /* sentinel */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001580};
1581
1582PyDoc_STRVAR(deque_doc,
Andrew Svetlov6a5c7c32012-10-31 11:50:40 +02001583"deque([iterable[, maxlen]]) --> deque object\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001584\n\
Raymond Hettinger41290a62015-03-31 08:12:23 -07001585A list-like sequence optimized for data accesses near its endpoints.");
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001586
Neal Norwitz87f10132004-02-29 15:40:53 +00001587static PyTypeObject deque_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001588 PyVarObject_HEAD_INIT(NULL, 0)
1589 "collections.deque", /* tp_name */
1590 sizeof(dequeobject), /* tp_basicsize */
1591 0, /* tp_itemsize */
1592 /* methods */
1593 (destructor)deque_dealloc, /* tp_dealloc */
1594 0, /* tp_print */
1595 0, /* tp_getattr */
1596 0, /* tp_setattr */
1597 0, /* tp_reserved */
1598 deque_repr, /* tp_repr */
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001599 &deque_as_number, /* tp_as_number */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001600 &deque_as_sequence, /* tp_as_sequence */
1601 0, /* tp_as_mapping */
Georg Brandlf038b322010-10-18 07:35:09 +00001602 PyObject_HashNotImplemented, /* tp_hash */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001603 0, /* tp_call */
1604 0, /* tp_str */
1605 PyObject_GenericGetAttr, /* tp_getattro */
1606 0, /* tp_setattro */
1607 0, /* tp_as_buffer */
1608 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
Georg Brandlf038b322010-10-18 07:35:09 +00001609 /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001610 deque_doc, /* tp_doc */
1611 (traverseproc)deque_traverse, /* tp_traverse */
1612 (inquiry)deque_clear, /* tp_clear */
1613 (richcmpfunc)deque_richcompare, /* tp_richcompare */
Georg Brandlf038b322010-10-18 07:35:09 +00001614 offsetof(dequeobject, weakreflist), /* tp_weaklistoffset*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001615 (getiterfunc)deque_iter, /* tp_iter */
1616 0, /* tp_iternext */
1617 deque_methods, /* tp_methods */
1618 0, /* tp_members */
Georg Brandlf038b322010-10-18 07:35:09 +00001619 deque_getset, /* tp_getset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001620 0, /* tp_base */
1621 0, /* tp_dict */
1622 0, /* tp_descr_get */
1623 0, /* tp_descr_set */
1624 0, /* tp_dictoffset */
1625 (initproc)deque_init, /* tp_init */
1626 PyType_GenericAlloc, /* tp_alloc */
1627 deque_new, /* tp_new */
1628 PyObject_GC_Del, /* tp_free */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001629};
1630
1631/*********************** Deque Iterator **************************/
1632
1633typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001634 PyObject_HEAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001635 block *b;
Raymond Hettinger87e69122015-03-02 23:32:02 -08001636 Py_ssize_t index;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001637 dequeobject *deque;
Raymond Hettingerf9d9c792015-03-02 22:47:46 -08001638 size_t state; /* state when the iterator is created */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001639 Py_ssize_t counter; /* number of items remaining for iteration */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001640} dequeiterobject;
1641
Martin v. Löwis59683e82008-06-13 07:50:45 +00001642static PyTypeObject dequeiter_type;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001643
1644static PyObject *
1645deque_iter(dequeobject *deque)
1646{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001647 dequeiterobject *it;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001649 it = PyObject_GC_New(dequeiterobject, &dequeiter_type);
1650 if (it == NULL)
1651 return NULL;
1652 it->b = deque->leftblock;
1653 it->index = deque->leftindex;
1654 Py_INCREF(deque);
1655 it->deque = deque;
1656 it->state = deque->state;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001657 it->counter = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001658 PyObject_GC_Track(it);
1659 return (PyObject *)it;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001660}
1661
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001662static int
1663dequeiter_traverse(dequeiterobject *dio, visitproc visit, void *arg)
1664{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001665 Py_VISIT(dio->deque);
1666 return 0;
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001667}
1668
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001669static void
1670dequeiter_dealloc(dequeiterobject *dio)
1671{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001672 Py_XDECREF(dio->deque);
1673 PyObject_GC_Del(dio);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001674}
1675
1676static PyObject *
1677dequeiter_next(dequeiterobject *it)
1678{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001679 PyObject *item;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001680
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001681 if (it->deque->state != it->state) {
1682 it->counter = 0;
1683 PyErr_SetString(PyExc_RuntimeError,
1684 "deque mutated during iteration");
1685 return NULL;
1686 }
1687 if (it->counter == 0)
1688 return NULL;
1689 assert (!(it->b == it->deque->rightblock &&
1690 it->index > it->deque->rightindex));
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001691
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001692 item = it->b->data[it->index];
1693 it->index++;
1694 it->counter--;
1695 if (it->index == BLOCKLEN && it->counter > 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -10001696 CHECK_NOT_END(it->b->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001697 it->b = it->b->rightlink;
1698 it->index = 0;
1699 }
1700 Py_INCREF(item);
1701 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001702}
1703
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001704static PyObject *
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001705dequeiter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1706{
1707 Py_ssize_t i, index=0;
1708 PyObject *deque;
1709 dequeiterobject *it;
1710 if (!PyArg_ParseTuple(args, "O!|n", &deque_type, &deque, &index))
1711 return NULL;
1712 assert(type == &dequeiter_type);
1713
1714 it = (dequeiterobject*)deque_iter((dequeobject *)deque);
1715 if (!it)
1716 return NULL;
1717 /* consume items from the queue */
1718 for(i=0; i<index; i++) {
1719 PyObject *item = dequeiter_next(it);
1720 if (item) {
1721 Py_DECREF(item);
1722 } else {
1723 if (it->counter) {
1724 Py_DECREF(it);
1725 return NULL;
1726 } else
1727 break;
1728 }
1729 }
1730 return (PyObject*)it;
1731}
1732
1733static PyObject *
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001734dequeiter_len(dequeiterobject *it)
1735{
Antoine Pitrou554f3342010-08-17 18:30:06 +00001736 return PyLong_FromSsize_t(it->counter);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001737}
1738
Armin Rigof5b3e362006-02-11 21:32:43 +00001739PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001740
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001741static PyObject *
1742dequeiter_reduce(dequeiterobject *it)
1743{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001744 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 +00001745}
1746
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001747static PyMethodDef dequeiter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001748 {"__length_hint__", (PyCFunction)dequeiter_len, METH_NOARGS, length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001749 {"__reduce__", (PyCFunction)dequeiter_reduce, METH_NOARGS, reduce_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001750 {NULL, NULL} /* sentinel */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001751};
1752
Martin v. Löwis59683e82008-06-13 07:50:45 +00001753static PyTypeObject dequeiter_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001754 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger87e69122015-03-02 23:32:02 -08001755 "_collections._deque_iterator", /* tp_name */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001756 sizeof(dequeiterobject), /* tp_basicsize */
1757 0, /* tp_itemsize */
1758 /* methods */
1759 (destructor)dequeiter_dealloc, /* tp_dealloc */
1760 0, /* tp_print */
1761 0, /* tp_getattr */
1762 0, /* tp_setattr */
1763 0, /* tp_reserved */
1764 0, /* tp_repr */
1765 0, /* tp_as_number */
1766 0, /* tp_as_sequence */
1767 0, /* tp_as_mapping */
1768 0, /* tp_hash */
1769 0, /* tp_call */
1770 0, /* tp_str */
1771 PyObject_GenericGetAttr, /* tp_getattro */
1772 0, /* tp_setattro */
1773 0, /* tp_as_buffer */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001774 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001775 0, /* tp_doc */
1776 (traverseproc)dequeiter_traverse, /* tp_traverse */
1777 0, /* tp_clear */
1778 0, /* tp_richcompare */
1779 0, /* tp_weaklistoffset */
1780 PyObject_SelfIter, /* tp_iter */
1781 (iternextfunc)dequeiter_next, /* tp_iternext */
1782 dequeiter_methods, /* tp_methods */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001783 0, /* tp_members */
1784 0, /* tp_getset */
1785 0, /* tp_base */
1786 0, /* tp_dict */
1787 0, /* tp_descr_get */
1788 0, /* tp_descr_set */
1789 0, /* tp_dictoffset */
1790 0, /* tp_init */
1791 0, /* tp_alloc */
1792 dequeiter_new, /* tp_new */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001793 0,
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001794};
1795
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001796/*********************** Deque Reverse Iterator **************************/
1797
Martin v. Löwis59683e82008-06-13 07:50:45 +00001798static PyTypeObject dequereviter_type;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001799
1800static PyObject *
1801deque_reviter(dequeobject *deque)
1802{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001803 dequeiterobject *it;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001804
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001805 it = PyObject_GC_New(dequeiterobject, &dequereviter_type);
1806 if (it == NULL)
1807 return NULL;
1808 it->b = deque->rightblock;
1809 it->index = deque->rightindex;
1810 Py_INCREF(deque);
1811 it->deque = deque;
1812 it->state = deque->state;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001813 it->counter = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001814 PyObject_GC_Track(it);
1815 return (PyObject *)it;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001816}
1817
1818static PyObject *
1819dequereviter_next(dequeiterobject *it)
1820{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001821 PyObject *item;
1822 if (it->counter == 0)
1823 return NULL;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001824
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001825 if (it->deque->state != it->state) {
1826 it->counter = 0;
1827 PyErr_SetString(PyExc_RuntimeError,
1828 "deque mutated during iteration");
1829 return NULL;
1830 }
1831 assert (!(it->b == it->deque->leftblock &&
1832 it->index < it->deque->leftindex));
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001834 item = it->b->data[it->index];
1835 it->index--;
1836 it->counter--;
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -07001837 if (it->index < 0 && it->counter > 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -10001838 CHECK_NOT_END(it->b->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001839 it->b = it->b->leftlink;
1840 it->index = BLOCKLEN - 1;
1841 }
1842 Py_INCREF(item);
1843 return item;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001844}
1845
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001846static PyObject *
1847dequereviter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1848{
1849 Py_ssize_t i, index=0;
1850 PyObject *deque;
1851 dequeiterobject *it;
1852 if (!PyArg_ParseTuple(args, "O!|n", &deque_type, &deque, &index))
1853 return NULL;
1854 assert(type == &dequereviter_type);
1855
1856 it = (dequeiterobject*)deque_reviter((dequeobject *)deque);
1857 if (!it)
1858 return NULL;
1859 /* consume items from the queue */
1860 for(i=0; i<index; i++) {
1861 PyObject *item = dequereviter_next(it);
1862 if (item) {
1863 Py_DECREF(item);
1864 } else {
1865 if (it->counter) {
1866 Py_DECREF(it);
1867 return NULL;
1868 } else
1869 break;
1870 }
1871 }
1872 return (PyObject*)it;
1873}
1874
Martin v. Löwis59683e82008-06-13 07:50:45 +00001875static PyTypeObject dequereviter_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001876 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger87e69122015-03-02 23:32:02 -08001877 "_collections._deque_reverse_iterator", /* tp_name */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001878 sizeof(dequeiterobject), /* tp_basicsize */
1879 0, /* tp_itemsize */
1880 /* methods */
1881 (destructor)dequeiter_dealloc, /* tp_dealloc */
1882 0, /* tp_print */
1883 0, /* tp_getattr */
1884 0, /* tp_setattr */
1885 0, /* tp_reserved */
1886 0, /* tp_repr */
1887 0, /* tp_as_number */
1888 0, /* tp_as_sequence */
1889 0, /* tp_as_mapping */
1890 0, /* tp_hash */
1891 0, /* tp_call */
1892 0, /* tp_str */
1893 PyObject_GenericGetAttr, /* tp_getattro */
1894 0, /* tp_setattro */
1895 0, /* tp_as_buffer */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001896 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001897 0, /* tp_doc */
1898 (traverseproc)dequeiter_traverse, /* tp_traverse */
1899 0, /* tp_clear */
1900 0, /* tp_richcompare */
1901 0, /* tp_weaklistoffset */
1902 PyObject_SelfIter, /* tp_iter */
1903 (iternextfunc)dequereviter_next, /* tp_iternext */
1904 dequeiter_methods, /* tp_methods */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001905 0, /* tp_members */
1906 0, /* tp_getset */
1907 0, /* tp_base */
1908 0, /* tp_dict */
1909 0, /* tp_descr_get */
1910 0, /* tp_descr_set */
1911 0, /* tp_dictoffset */
1912 0, /* tp_init */
1913 0, /* tp_alloc */
1914 dequereviter_new, /* tp_new */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001915 0,
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001916};
1917
Guido van Rossum1968ad32006-02-25 22:38:04 +00001918/* defaultdict type *********************************************************/
1919
1920typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001921 PyDictObject dict;
1922 PyObject *default_factory;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001923} defdictobject;
1924
1925static PyTypeObject defdict_type; /* Forward */
1926
1927PyDoc_STRVAR(defdict_missing_doc,
1928"__missing__(key) # Called by __getitem__ for missing key; pseudo-code:\n\
Guido van Rossumd8faa362007-04-27 19:54:29 +00001929 if self.default_factory is None: raise KeyError((key,))\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00001930 self[key] = value = self.default_factory()\n\
1931 return value\n\
1932");
1933
1934static PyObject *
1935defdict_missing(defdictobject *dd, PyObject *key)
1936{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001937 PyObject *factory = dd->default_factory;
1938 PyObject *value;
1939 if (factory == NULL || factory == Py_None) {
1940 /* XXX Call dict.__missing__(key) */
1941 PyObject *tup;
1942 tup = PyTuple_Pack(1, key);
1943 if (!tup) return NULL;
1944 PyErr_SetObject(PyExc_KeyError, tup);
1945 Py_DECREF(tup);
1946 return NULL;
1947 }
1948 value = PyEval_CallObject(factory, NULL);
1949 if (value == NULL)
1950 return value;
1951 if (PyObject_SetItem((PyObject *)dd, key, value) < 0) {
1952 Py_DECREF(value);
1953 return NULL;
1954 }
1955 return value;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001956}
1957
1958PyDoc_STRVAR(defdict_copy_doc, "D.copy() -> a shallow copy of D.");
1959
1960static PyObject *
1961defdict_copy(defdictobject *dd)
1962{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001963 /* This calls the object's class. That only works for subclasses
1964 whose class constructor has the same signature. Subclasses that
1965 define a different constructor signature must override copy().
1966 */
Raymond Hettinger54628fa2009-08-04 19:16:39 +00001967
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001968 if (dd->default_factory == NULL)
1969 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd), Py_None, dd, NULL);
1970 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd),
1971 dd->default_factory, dd, NULL);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001972}
1973
1974static PyObject *
1975defdict_reduce(defdictobject *dd)
1976{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001977 /* __reduce__ must return a 5-tuple as follows:
Guido van Rossum1968ad32006-02-25 22:38:04 +00001978
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001979 - factory function
1980 - tuple of args for the factory function
1981 - additional state (here None)
1982 - sequence iterator (here None)
1983 - dictionary iterator (yielding successive (key, value) pairs
Guido van Rossum1968ad32006-02-25 22:38:04 +00001984
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001985 This API is used by pickle.py and copy.py.
Guido van Rossum1968ad32006-02-25 22:38:04 +00001986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001987 For this to be useful with pickle.py, the default_factory
1988 must be picklable; e.g., None, a built-in, or a global
1989 function in a module or package.
Guido van Rossum1968ad32006-02-25 22:38:04 +00001990
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001991 Both shallow and deep copying are supported, but for deep
1992 copying, the default_factory must be deep-copyable; e.g. None,
1993 or a built-in (functions are not copyable at this time).
Guido van Rossum1968ad32006-02-25 22:38:04 +00001994
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001995 This only works for subclasses as long as their constructor
1996 signature is compatible; the first argument must be the
1997 optional default_factory, defaulting to None.
1998 */
1999 PyObject *args;
2000 PyObject *items;
2001 PyObject *iter;
2002 PyObject *result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002003 _Py_IDENTIFIER(items);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002004
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002005 if (dd->default_factory == NULL || dd->default_factory == Py_None)
2006 args = PyTuple_New(0);
2007 else
2008 args = PyTuple_Pack(1, dd->default_factory);
2009 if (args == NULL)
2010 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002011 items = _PyObject_CallMethodId((PyObject *)dd, &PyId_items, "()");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002012 if (items == NULL) {
2013 Py_DECREF(args);
2014 return NULL;
2015 }
2016 iter = PyObject_GetIter(items);
2017 if (iter == NULL) {
2018 Py_DECREF(items);
2019 Py_DECREF(args);
2020 return NULL;
2021 }
2022 result = PyTuple_Pack(5, Py_TYPE(dd), args,
2023 Py_None, Py_None, iter);
2024 Py_DECREF(iter);
2025 Py_DECREF(items);
2026 Py_DECREF(args);
2027 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00002028}
2029
2030static PyMethodDef defdict_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002031 {"__missing__", (PyCFunction)defdict_missing, METH_O,
2032 defdict_missing_doc},
2033 {"copy", (PyCFunction)defdict_copy, METH_NOARGS,
2034 defdict_copy_doc},
2035 {"__copy__", (PyCFunction)defdict_copy, METH_NOARGS,
2036 defdict_copy_doc},
2037 {"__reduce__", (PyCFunction)defdict_reduce, METH_NOARGS,
2038 reduce_doc},
2039 {NULL}
Guido van Rossum1968ad32006-02-25 22:38:04 +00002040};
2041
2042static PyMemberDef defdict_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002043 {"default_factory", T_OBJECT,
2044 offsetof(defdictobject, default_factory), 0,
2045 PyDoc_STR("Factory for default value called by __missing__().")},
2046 {NULL}
Guido van Rossum1968ad32006-02-25 22:38:04 +00002047};
2048
2049static void
2050defdict_dealloc(defdictobject *dd)
2051{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002052 Py_CLEAR(dd->default_factory);
2053 PyDict_Type.tp_dealloc((PyObject *)dd);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002054}
2055
Guido van Rossum1968ad32006-02-25 22:38:04 +00002056static PyObject *
2057defdict_repr(defdictobject *dd)
2058{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002059 PyObject *baserepr;
2060 PyObject *defrepr;
2061 PyObject *result;
2062 baserepr = PyDict_Type.tp_repr((PyObject *)dd);
2063 if (baserepr == NULL)
2064 return NULL;
2065 if (dd->default_factory == NULL)
2066 defrepr = PyUnicode_FromString("None");
2067 else
2068 {
2069 int status = Py_ReprEnter(dd->default_factory);
2070 if (status != 0) {
Antoine Pitrouf5f1fe02012-02-15 02:42:46 +01002071 if (status < 0) {
2072 Py_DECREF(baserepr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002073 return NULL;
Antoine Pitrouf5f1fe02012-02-15 02:42:46 +01002074 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002075 defrepr = PyUnicode_FromString("...");
2076 }
2077 else
2078 defrepr = PyObject_Repr(dd->default_factory);
2079 Py_ReprLeave(dd->default_factory);
2080 }
2081 if (defrepr == NULL) {
2082 Py_DECREF(baserepr);
2083 return NULL;
2084 }
2085 result = PyUnicode_FromFormat("defaultdict(%U, %U)",
2086 defrepr, baserepr);
2087 Py_DECREF(defrepr);
2088 Py_DECREF(baserepr);
2089 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00002090}
2091
2092static int
2093defdict_traverse(PyObject *self, visitproc visit, void *arg)
2094{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002095 Py_VISIT(((defdictobject *)self)->default_factory);
2096 return PyDict_Type.tp_traverse(self, visit, arg);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002097}
2098
2099static int
2100defdict_tp_clear(defdictobject *dd)
2101{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002102 Py_CLEAR(dd->default_factory);
2103 return PyDict_Type.tp_clear((PyObject *)dd);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002104}
2105
2106static int
2107defdict_init(PyObject *self, PyObject *args, PyObject *kwds)
2108{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002109 defdictobject *dd = (defdictobject *)self;
2110 PyObject *olddefault = dd->default_factory;
2111 PyObject *newdefault = NULL;
2112 PyObject *newargs;
2113 int result;
2114 if (args == NULL || !PyTuple_Check(args))
2115 newargs = PyTuple_New(0);
2116 else {
2117 Py_ssize_t n = PyTuple_GET_SIZE(args);
2118 if (n > 0) {
2119 newdefault = PyTuple_GET_ITEM(args, 0);
2120 if (!PyCallable_Check(newdefault) && newdefault != Py_None) {
2121 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger239aba72015-07-20 03:09:22 -04002122 "first argument must be callable or None");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002123 return -1;
2124 }
2125 }
2126 newargs = PySequence_GetSlice(args, 1, n);
2127 }
2128 if (newargs == NULL)
2129 return -1;
2130 Py_XINCREF(newdefault);
2131 dd->default_factory = newdefault;
2132 result = PyDict_Type.tp_init(self, newargs, kwds);
2133 Py_DECREF(newargs);
2134 Py_XDECREF(olddefault);
2135 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00002136}
2137
2138PyDoc_STRVAR(defdict_doc,
Benjamin Peterson9cb33b72014-01-13 23:56:05 -05002139"defaultdict(default_factory[, ...]) --> dict with default factory\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00002140\n\
2141The default factory is called without arguments to produce\n\
2142a new value when a key is not present, in __getitem__ only.\n\
2143A defaultdict compares equal to a dict with the same items.\n\
Benjamin Peterson9cb33b72014-01-13 23:56:05 -05002144All remaining arguments are treated the same as if they were\n\
2145passed to the dict constructor, including keyword arguments.\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00002146");
2147
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002148/* See comment in xxsubtype.c */
2149#define DEFERRED_ADDRESS(ADDR) 0
2150
Guido van Rossum1968ad32006-02-25 22:38:04 +00002151static PyTypeObject defdict_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002152 PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0)
2153 "collections.defaultdict", /* tp_name */
2154 sizeof(defdictobject), /* tp_basicsize */
2155 0, /* tp_itemsize */
2156 /* methods */
2157 (destructor)defdict_dealloc, /* tp_dealloc */
2158 0, /* tp_print */
2159 0, /* tp_getattr */
2160 0, /* tp_setattr */
2161 0, /* tp_reserved */
2162 (reprfunc)defdict_repr, /* tp_repr */
2163 0, /* tp_as_number */
2164 0, /* tp_as_sequence */
2165 0, /* tp_as_mapping */
2166 0, /* tp_hash */
2167 0, /* tp_call */
2168 0, /* tp_str */
2169 PyObject_GenericGetAttr, /* tp_getattro */
2170 0, /* tp_setattro */
2171 0, /* tp_as_buffer */
2172 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
2173 /* tp_flags */
2174 defdict_doc, /* tp_doc */
2175 defdict_traverse, /* tp_traverse */
2176 (inquiry)defdict_tp_clear, /* tp_clear */
2177 0, /* tp_richcompare */
2178 0, /* tp_weaklistoffset*/
2179 0, /* tp_iter */
2180 0, /* tp_iternext */
2181 defdict_methods, /* tp_methods */
2182 defdict_members, /* tp_members */
2183 0, /* tp_getset */
2184 DEFERRED_ADDRESS(&PyDict_Type), /* tp_base */
2185 0, /* tp_dict */
2186 0, /* tp_descr_get */
2187 0, /* tp_descr_set */
2188 0, /* tp_dictoffset */
2189 defdict_init, /* tp_init */
2190 PyType_GenericAlloc, /* tp_alloc */
2191 0, /* tp_new */
2192 PyObject_GC_Del, /* tp_free */
Guido van Rossum1968ad32006-02-25 22:38:04 +00002193};
2194
Raymond Hettinger96f34102010-12-15 16:30:37 +00002195/* helper function for Counter *********************************************/
2196
2197PyDoc_STRVAR(_count_elements_doc,
2198"_count_elements(mapping, iterable) -> None\n\
2199\n\
2200Count elements in the iterable, updating the mappping");
2201
2202static PyObject *
2203_count_elements(PyObject *self, PyObject *args)
2204{
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002205 _Py_IDENTIFIER(get);
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002206 _Py_IDENTIFIER(__setitem__);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002207 PyObject *it, *iterable, *mapping, *oldval;
2208 PyObject *newval = NULL;
2209 PyObject *key = NULL;
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002210 PyObject *zero = NULL;
Raymond Hettinger96f34102010-12-15 16:30:37 +00002211 PyObject *one = NULL;
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002212 PyObject *bound_get = NULL;
2213 PyObject *mapping_get;
2214 PyObject *dict_get;
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002215 PyObject *mapping_setitem;
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002216 PyObject *dict_setitem;
Raymond Hettinger96f34102010-12-15 16:30:37 +00002217
2218 if (!PyArg_UnpackTuple(args, "_count_elements", 2, 2, &mapping, &iterable))
2219 return NULL;
2220
Raymond Hettinger96f34102010-12-15 16:30:37 +00002221 it = PyObject_GetIter(iterable);
2222 if (it == NULL)
2223 return NULL;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002224
Raymond Hettinger96f34102010-12-15 16:30:37 +00002225 one = PyLong_FromLong(1);
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002226 if (one == NULL)
2227 goto done;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002228
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002229 /* Only take the fast path when get() and __setitem__()
2230 * have not been overridden.
2231 */
2232 mapping_get = _PyType_LookupId(Py_TYPE(mapping), &PyId_get);
2233 dict_get = _PyType_LookupId(&PyDict_Type, &PyId_get);
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002234 mapping_setitem = _PyType_LookupId(Py_TYPE(mapping), &PyId___setitem__);
2235 dict_setitem = _PyType_LookupId(&PyDict_Type, &PyId___setitem__);
2236
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002237 if (mapping_get != NULL && mapping_get == dict_get &&
2238 mapping_setitem != NULL && mapping_setitem == dict_setitem) {
Raymond Hettinger426e0522011-01-03 02:12:02 +00002239 while (1) {
Raymond Hettinger507d9972014-05-18 21:32:40 +01002240 /* Fast path advantages:
2241 1. Eliminate double hashing
2242 (by re-using the same hash for both the get and set)
2243 2. Avoid argument overhead of PyObject_CallFunctionObjArgs
2244 (argument tuple creation and parsing)
2245 3. Avoid indirection through a bound method object
2246 (creates another argument tuple)
2247 4. Avoid initial increment from zero
2248 (reuse an existing one-object instead)
2249 */
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002250 Py_hash_t hash;
2251
Raymond Hettinger426e0522011-01-03 02:12:02 +00002252 key = PyIter_Next(it);
Victor Stinnera154b5c2011-04-20 23:23:52 +02002253 if (key == NULL)
2254 break;
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002255
2256 if (!PyUnicode_CheckExact(key) ||
2257 (hash = ((PyASCIIObject *) key)->hash) == -1)
2258 {
2259 hash = PyObject_Hash(key);
Raymond Hettingerda2850f2015-02-27 12:42:54 -08002260 if (hash == -1)
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002261 goto done;
2262 }
2263
2264 oldval = _PyDict_GetItem_KnownHash(mapping, key, hash);
Raymond Hettinger426e0522011-01-03 02:12:02 +00002265 if (oldval == NULL) {
Raymond Hettinger28c995d2015-08-14 02:07:41 -07002266 if (_PyDict_SetItem_KnownHash(mapping, key, one, hash) < 0)
Raymond Hettinger507d9972014-05-18 21:32:40 +01002267 goto done;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002268 } else {
2269 newval = PyNumber_Add(oldval, one);
2270 if (newval == NULL)
Raymond Hettinger507d9972014-05-18 21:32:40 +01002271 goto done;
Raymond Hettinger28c995d2015-08-14 02:07:41 -07002272 if (_PyDict_SetItem_KnownHash(mapping, key, newval, hash) < 0)
Raymond Hettinger507d9972014-05-18 21:32:40 +01002273 goto done;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002274 Py_CLEAR(newval);
2275 }
2276 Py_DECREF(key);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002277 }
Raymond Hettinger426e0522011-01-03 02:12:02 +00002278 } else {
Victor Stinnere7f516c2013-11-06 23:52:55 +01002279 bound_get = _PyObject_GetAttrId(mapping, &PyId_get);
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002280 if (bound_get == NULL)
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002281 goto done;
2282
2283 zero = PyLong_FromLong(0);
2284 if (zero == NULL)
2285 goto done;
2286
Raymond Hettinger426e0522011-01-03 02:12:02 +00002287 while (1) {
2288 key = PyIter_Next(it);
Victor Stinnera154b5c2011-04-20 23:23:52 +02002289 if (key == NULL)
2290 break;
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002291 oldval = PyObject_CallFunctionObjArgs(bound_get, key, zero, NULL);
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002292 if (oldval == NULL)
2293 break;
2294 newval = PyNumber_Add(oldval, one);
2295 Py_DECREF(oldval);
2296 if (newval == NULL)
2297 break;
Raymond Hettinger28c995d2015-08-14 02:07:41 -07002298 if (PyObject_SetItem(mapping, key, newval) < 0)
Raymond Hettinger96f34102010-12-15 16:30:37 +00002299 break;
2300 Py_CLEAR(newval);
Raymond Hettinger426e0522011-01-03 02:12:02 +00002301 Py_DECREF(key);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002302 }
Raymond Hettinger96f34102010-12-15 16:30:37 +00002303 }
Raymond Hettinger426e0522011-01-03 02:12:02 +00002304
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002305done:
Raymond Hettinger96f34102010-12-15 16:30:37 +00002306 Py_DECREF(it);
2307 Py_XDECREF(key);
2308 Py_XDECREF(newval);
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002309 Py_XDECREF(bound_get);
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002310 Py_XDECREF(zero);
2311 Py_XDECREF(one);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002312 if (PyErr_Occurred())
2313 return NULL;
2314 Py_RETURN_NONE;
2315}
2316
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002317/* module level code ********************************************************/
2318
2319PyDoc_STRVAR(module_doc,
Guido van Rossum1968ad32006-02-25 22:38:04 +00002320"High performance data structures.\n\
2321- deque: ordered collection accessible from endpoints only\n\
2322- defaultdict: dict subclass with a default value factory\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002323");
2324
Raymond Hettinger96f34102010-12-15 16:30:37 +00002325static struct PyMethodDef module_functions[] = {
2326 {"_count_elements", _count_elements, METH_VARARGS, _count_elements_doc},
2327 {NULL, NULL} /* sentinel */
2328};
Martin v. Löwis1a214512008-06-11 05:26:20 +00002329
2330static struct PyModuleDef _collectionsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002331 PyModuleDef_HEAD_INIT,
2332 "_collections",
2333 module_doc,
2334 -1,
Raymond Hettinger96f34102010-12-15 16:30:37 +00002335 module_functions,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002336 NULL,
2337 NULL,
2338 NULL,
2339 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002340};
2341
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002342PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002343PyInit__collections(void)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002344{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002345 PyObject *m;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002347 m = PyModule_Create(&_collectionsmodule);
2348 if (m == NULL)
2349 return NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002351 if (PyType_Ready(&deque_type) < 0)
2352 return NULL;
2353 Py_INCREF(&deque_type);
2354 PyModule_AddObject(m, "deque", (PyObject *)&deque_type);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002356 defdict_type.tp_base = &PyDict_Type;
2357 if (PyType_Ready(&defdict_type) < 0)
2358 return NULL;
2359 Py_INCREF(&defdict_type);
2360 PyModule_AddObject(m, "defaultdict", (PyObject *)&defdict_type);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002361
Eric Snow47db7172015-05-29 22:21:39 -06002362 Py_INCREF(&PyODict_Type);
2363 PyModule_AddObject(m, "OrderedDict", (PyObject *)&PyODict_Type);
2364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002365 if (PyType_Ready(&dequeiter_type) < 0)
2366 return NULL;
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002367 Py_INCREF(&dequeiter_type);
2368 PyModule_AddObject(m, "_deque_iterator", (PyObject *)&dequeiter_type);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002370 if (PyType_Ready(&dequereviter_type) < 0)
2371 return NULL;
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002372 Py_INCREF(&dequereviter_type);
2373 PyModule_AddObject(m, "_deque_reverse_iterator", (PyObject *)&dequereviter_type);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00002374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002375 return m;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002376}