blob: 8766d86dd3ef37118412a43038e03209d0f0d3cc [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 Hettinger756b3f32004-01-29 06:37:52 +000012*/
13
Raymond Hettinger77e8bf12004-10-01 15:25:53 +000014/* The block length may be set to any number over 1. Larger numbers
Raymond Hettinger20b0f872013-06-23 15:44:33 -070015 * reduce the number of calls to the memory allocator, give faster
Raymond Hettinger30c90742015-03-02 22:31:35 -080016 * indexing and rotation, and reduce the link to data overhead ratio.
Raymond Hettingerdaf57f22015-02-26 23:21:29 -080017 * Making the block length a power of two speeds-up the modulo
Raymond Hettinger30c90742015-03-02 22:31:35 -080018 * and division calculations in deque_item() and deque_ass_item().
Raymond Hettinger77e8bf12004-10-01 15:25:53 +000019 */
20
Raymond Hettingerdaf57f22015-02-26 23:21:29 -080021#define BLOCKLEN 64
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000022#define CENTER ((BLOCKLEN - 1) / 2)
Raymond Hettinger756b3f32004-01-29 06:37:52 +000023
Raymond Hettinger551350a2015-03-24 00:19:53 -070024/* Data for deque objects is stored in a doubly-linked list of fixed
25 * length blocks. This assures that appends or pops never move any
26 * other data elements besides the one being appended or popped.
27 *
28 * Another advantage is that it completely avoids use of realloc(),
29 * resulting in more predictable performance.
30 *
31 * Textbook implementations of doubly-linked lists store one datum
32 * per link, but that gives them a 200% memory overhead (a prev and
33 * next link for each datum) and it costs one malloc() call per data
34 * element. By using fixed-length blocks, the link to data ratio is
35 * significantly improved and there are proportionally fewer calls
36 * to malloc() and free(). The data blocks of consecutive pointers
37 * also improve cache locality.
38 *
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000039 * The list of blocks is never empty, so d.leftblock and d.rightblock
Raymond Hettinger82df9252013-07-07 01:43:42 -100040 * are never equal to NULL. The list is not circular.
41 *
42 * A deque d's first element is at d.leftblock[leftindex]
43 * and its last element is at d.rightblock[rightindex].
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000044 *
Raymond Hettinger551350a2015-03-24 00:19:53 -070045 * Unlike Python slice indices, these indices are inclusive on both
46 * ends. This makes the algorithms for left and right operations
47 * more symmetrical and it simplifies the design.
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000048 *
Raymond Hettinger551350a2015-03-24 00:19:53 -070049 * The indices, d.leftindex and d.rightindex are always in the range:
50 * 0 <= index < BLOCKLEN
51 *
52 * And their exact relationship is:
53 * (d.leftindex + d.len - 1) % BLOCKLEN == d.rightindex
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000054 *
Raymond Hettinger8dbbae22015-03-24 21:01:50 -070055 * Whenever d.leftblock == d.rightblock, then:
Raymond Hettinger551350a2015-03-24 00:19:53 -070056 * d.leftindex + d.len - 1 == d.rightindex
Thomas Wouters0e3f5912006-08-11 14:57:12 +000057 *
Raymond Hettinger551350a2015-03-24 00:19:53 -070058 * However, when d.leftblock != d.rightblock, the d.leftindex and
59 * d.rightindex become indices into distinct blocks and either may
60 * be larger than the other.
61 *
62 * Empty deques have:
63 * d.len == 0
64 * d.leftblock == d.rightblock
65 * d.leftindex == CENTER + 1
66 * d.rightindex == CENTER
67 *
68 * Checking for d.len == 0 is the intended way to see whether d is empty.
Tim Petersd8768d32004-10-01 01:32:53 +000069 */
70
Raymond Hettinger756b3f32004-01-29 06:37:52 +000071typedef struct BLOCK {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000072 struct BLOCK *leftlink;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000073 PyObject *data[BLOCKLEN];
Raymond Hettinger20b0f872013-06-23 15:44:33 -070074 struct BLOCK *rightlink;
Raymond Hettinger756b3f32004-01-29 06:37:52 +000075} block;
76
Raymond Hettinger30c90742015-03-02 22:31:35 -080077typedef struct {
78 PyObject_VAR_HEAD
79 block *leftblock;
80 block *rightblock;
Raymond Hettinger551350a2015-03-24 00:19:53 -070081 Py_ssize_t leftindex; /* 0 <= leftindex < BLOCKLEN */
82 Py_ssize_t rightindex; /* 0 <= rightindex < BLOCKLEN */
Raymond Hettingerf9d9c792015-03-02 22:47:46 -080083 size_t state; /* incremented whenever the indices move */
Raymond Hettingerd84ec222016-01-24 09:12:06 -080084 Py_ssize_t maxlen; /* maxlen is -1 for unbounded deques */
Raymond Hettinger0f6f9472015-03-21 01:42:10 -070085 PyObject *weakreflist;
Raymond Hettinger30c90742015-03-02 22:31:35 -080086} dequeobject;
87
88static PyTypeObject deque_type;
89
Raymond Hettinger82df9252013-07-07 01:43:42 -100090/* For debug builds, add error checking to track the endpoints
91 * in the chain of links. The goal is to make sure that link
92 * assignments only take place at endpoints so that links already
93 * in use do not get overwritten.
94 *
95 * CHECK_END should happen before each assignment to a block's link field.
96 * MARK_END should happen whenever a link field becomes a new endpoint.
97 * This happens when new blocks are added or whenever an existing
98 * block is freed leaving another existing block as the new endpoint.
99 */
100
Raymond Hettinger3223dd52013-07-26 23:14:22 -0700101#ifndef NDEBUG
Raymond Hettinger82df9252013-07-07 01:43:42 -1000102#define MARK_END(link) link = NULL;
103#define CHECK_END(link) assert(link == NULL);
104#define CHECK_NOT_END(link) assert(link != NULL);
105#else
106#define MARK_END(link)
107#define CHECK_END(link)
108#define CHECK_NOT_END(link)
109#endif
110
111/* A simple freelisting scheme is used to minimize calls to the memory
Raymond Hettinger551350a2015-03-24 00:19:53 -0700112 allocator. It accommodates common use cases where new blocks are being
Raymond Hettinger82df9252013-07-07 01:43:42 -1000113 added at about the same rate as old blocks are being freed.
114 */
115
Raymond Hettingerf2b02ce2015-09-26 17:47:02 -0700116#define MAXFREEBLOCKS 16
Benjamin Petersond6313712008-07-31 16:23:04 +0000117static Py_ssize_t numfreeblocks = 0;
Guido van Rossum58da9312007-11-10 23:39:45 +0000118static block *freeblocks[MAXFREEBLOCKS];
119
Tim Peters6f853562004-10-01 01:04:50 +0000120static block *
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700121newblock(void) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000122 block *b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000123 if (numfreeblocks) {
Raymond Hettinger59cf23a2013-02-07 00:57:19 -0500124 numfreeblocks--;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000125 return freeblocks[numfreeblocks];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000126 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000127 b = PyMem_Malloc(sizeof(block));
128 if (b != NULL) {
129 return b;
130 }
131 PyErr_NoMemory();
132 return NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000133}
134
Martin v. Löwis59683e82008-06-13 07:50:45 +0000135static void
Guido van Rossum58da9312007-11-10 23:39:45 +0000136freeblock(block *b)
137{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000138 if (numfreeblocks < MAXFREEBLOCKS) {
139 freeblocks[numfreeblocks] = b;
140 numfreeblocks++;
141 } else {
142 PyMem_Free(b);
143 }
Guido van Rossum58da9312007-11-10 23:39:45 +0000144}
145
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000146static PyObject *
147deque_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
148{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000149 dequeobject *deque;
150 block *b;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000152 /* create dequeobject structure */
153 deque = (dequeobject *)type->tp_alloc(type, 0);
154 if (deque == NULL)
155 return NULL;
Tim Peters1065f752004-10-01 01:03:29 +0000156
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700157 b = newblock();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000158 if (b == NULL) {
159 Py_DECREF(deque);
160 return NULL;
161 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000162 MARK_END(b->leftlink);
163 MARK_END(b->rightlink);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000165 assert(BLOCKLEN >= 2);
Raymond Hettinger87e69122015-03-02 23:32:02 -0800166 Py_SIZE(deque) = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000167 deque->leftblock = b;
168 deque->rightblock = b;
169 deque->leftindex = CENTER + 1;
170 deque->rightindex = CENTER;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000171 deque->state = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000172 deque->maxlen = -1;
Raymond Hettinger87e69122015-03-02 23:32:02 -0800173 deque->weakreflist = NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175 return (PyObject *)deque;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000176}
177
178static PyObject *
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000179deque_pop(dequeobject *deque, PyObject *unused)
180{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000181 PyObject *item;
182 block *prevblock;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000183
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000184 if (Py_SIZE(deque) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000185 PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
186 return NULL;
187 }
188 item = deque->rightblock->data[deque->rightindex];
189 deque->rightindex--;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000190 Py_SIZE(deque)--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000191 deque->state++;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000192
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -0700193 if (deque->rightindex < 0) {
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700194 if (Py_SIZE(deque)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000195 prevblock = deque->rightblock->leftlink;
196 assert(deque->leftblock != deque->rightblock);
197 freeblock(deque->rightblock);
Raymond Hettinger82df9252013-07-07 01:43:42 -1000198 CHECK_NOT_END(prevblock);
199 MARK_END(prevblock->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000200 deque->rightblock = prevblock;
201 deque->rightindex = BLOCKLEN - 1;
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700202 } else {
203 assert(deque->leftblock == deque->rightblock);
204 assert(deque->leftindex == deque->rightindex+1);
205 /* re-center instead of freeing a block */
206 deque->leftindex = CENTER + 1;
207 deque->rightindex = CENTER;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000208 }
209 }
210 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000211}
212
213PyDoc_STRVAR(pop_doc, "Remove and return the rightmost element.");
214
215static PyObject *
216deque_popleft(dequeobject *deque, PyObject *unused)
217{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000218 PyObject *item;
219 block *prevblock;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000220
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000221 if (Py_SIZE(deque) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000222 PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
223 return NULL;
224 }
225 assert(deque->leftblock != NULL);
226 item = deque->leftblock->data[deque->leftindex];
227 deque->leftindex++;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000228 Py_SIZE(deque)--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000229 deque->state++;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000231 if (deque->leftindex == BLOCKLEN) {
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700232 if (Py_SIZE(deque)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000233 assert(deque->leftblock != deque->rightblock);
234 prevblock = deque->leftblock->rightlink;
235 freeblock(deque->leftblock);
Raymond Hettinger82df9252013-07-07 01:43:42 -1000236 CHECK_NOT_END(prevblock);
237 MARK_END(prevblock->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000238 deque->leftblock = prevblock;
239 deque->leftindex = 0;
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700240 } else {
241 assert(deque->leftblock == deque->rightblock);
242 assert(deque->leftindex == deque->rightindex+1);
243 /* re-center instead of freeing a block */
244 deque->leftindex = CENTER + 1;
245 deque->rightindex = CENTER;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000246 }
247 }
248 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000249}
250
251PyDoc_STRVAR(popleft_doc, "Remove and return the leftmost element.");
252
Raymond Hettingerf30f5b92015-03-02 22:23:37 -0800253/* The deque's size limit is d.maxlen. The limit can be zero or positive.
254 * If there is no limit, then d.maxlen == -1.
255 *
Raymond Hettingera4b13d02015-10-15 08:05:31 -0700256 * After an item is added to a deque, we check to see if the size has
257 * grown past the limit. If it has, we get the size back down to the limit
258 * by popping an item off of the opposite end. The methods that can
259 * trigger this are append(), appendleft(), extend(), and extendleft().
Raymond Hettingerd96db092015-10-11 22:34:48 -0700260 *
261 * The macro to check whether a deque needs to be trimmed uses a single
262 * unsigned test that returns true whenever 0 <= maxlen < Py_SIZE(deque).
Raymond Hettingerf30f5b92015-03-02 22:23:37 -0800263 */
264
Raymond Hettingerd96db092015-10-11 22:34:48 -0700265#define NEEDS_TRIM(deque, maxlen) ((size_t)(maxlen) < (size_t)(Py_SIZE(deque)))
Raymond Hettingerf30f5b92015-03-02 22:23:37 -0800266
doko@ubuntu.combc731502016-05-18 01:06:01 +0200267static int
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800268deque_append_internal(dequeobject *deque, PyObject *item, Py_ssize_t maxlen)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000269{
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700270 if (deque->rightindex == BLOCKLEN - 1) {
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700271 block *b = newblock();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000272 if (b == NULL)
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800273 return -1;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000274 b->leftlink = deque->rightblock;
275 CHECK_END(deque->rightblock->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000276 deque->rightblock->rightlink = b;
277 deque->rightblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000278 MARK_END(b->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000279 deque->rightindex = -1;
280 }
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000281 Py_SIZE(deque)++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000282 deque->rightindex++;
283 deque->rightblock->data[deque->rightindex] = item;
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800284 if (NEEDS_TRIM(deque, maxlen)) {
Raymond Hettinger1286d142015-10-14 23:16:57 -0700285 PyObject *olditem = deque_popleft(deque, NULL);
286 Py_DECREF(olditem);
Raymond Hettinger0f43bb12015-10-20 00:03:33 -0700287 } else {
288 deque->state++;
Raymond Hettingerd96db092015-10-11 22:34:48 -0700289 }
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800290 return 0;
291}
292
293static PyObject *
294deque_append(dequeobject *deque, PyObject *item)
295{
296 Py_INCREF(item);
297 if (deque_append_internal(deque, item, deque->maxlen) < 0)
298 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000299 Py_RETURN_NONE;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000300}
301
302PyDoc_STRVAR(append_doc, "Add an element to the right side of the deque.");
303
doko@ubuntu.com17f0e612016-06-14 07:27:58 +0200304static int
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800305deque_appendleft_internal(dequeobject *deque, PyObject *item, Py_ssize_t maxlen)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000306{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000307 if (deque->leftindex == 0) {
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700308 block *b = newblock();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000309 if (b == NULL)
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800310 return -1;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000311 b->rightlink = deque->leftblock;
312 CHECK_END(deque->leftblock->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000313 deque->leftblock->leftlink = b;
314 deque->leftblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000315 MARK_END(b->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000316 deque->leftindex = BLOCKLEN;
317 }
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000318 Py_SIZE(deque)++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000319 deque->leftindex--;
320 deque->leftblock->data[deque->leftindex] = item;
Raymond Hettingerd96db092015-10-11 22:34:48 -0700321 if (NEEDS_TRIM(deque, deque->maxlen)) {
Raymond Hettinger1286d142015-10-14 23:16:57 -0700322 PyObject *olditem = deque_pop(deque, NULL);
323 Py_DECREF(olditem);
Raymond Hettinger0f43bb12015-10-20 00:03:33 -0700324 } else {
325 deque->state++;
Raymond Hettingerd96db092015-10-11 22:34:48 -0700326 }
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800327 return 0;
328}
329
330static PyObject *
331deque_appendleft(dequeobject *deque, PyObject *item)
332{
333 Py_INCREF(item);
334 if (deque_appendleft_internal(deque, item, deque->maxlen) < 0)
335 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000336 Py_RETURN_NONE;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000337}
338
339PyDoc_STRVAR(appendleft_doc, "Add an element to the left side of the deque.");
340
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700341static PyObject*
342finalize_iterator(PyObject *it)
343{
344 if (PyErr_Occurred()) {
345 if (PyErr_ExceptionMatches(PyExc_StopIteration))
346 PyErr_Clear();
347 else {
348 Py_DECREF(it);
349 return NULL;
350 }
351 }
352 Py_DECREF(it);
353 Py_RETURN_NONE;
354}
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000356/* Run an iterator to exhaustion. Shortcut for
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000357 the extend/extendleft methods when maxlen == 0. */
358static PyObject*
359consume_iterator(PyObject *it)
360{
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700361 PyObject *(*iternext)(PyObject *);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000362 PyObject *item;
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000363
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700364 iternext = *Py_TYPE(it)->tp_iternext;
365 while ((item = iternext(it)) != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000366 Py_DECREF(item);
367 }
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700368 return finalize_iterator(it);
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000369}
370
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000371static PyObject *
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000372deque_extend(dequeobject *deque, PyObject *iterable)
373{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000374 PyObject *it, *item;
Raymond Hettinger7a845522015-09-26 01:30:51 -0700375 PyObject *(*iternext)(PyObject *);
Raymond Hettinger6b1e1132015-10-11 09:43:50 -0700376 Py_ssize_t maxlen = deque->maxlen;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000378 /* Handle case where id(deque) == id(iterable) */
379 if ((PyObject *)deque == iterable) {
380 PyObject *result;
381 PyObject *s = PySequence_List(iterable);
382 if (s == NULL)
383 return NULL;
384 result = deque_extend(deque, s);
385 Py_DECREF(s);
386 return result;
387 }
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000388
Raymond Hettingerd79d5b12016-03-04 09:55:07 -0800389 it = PyObject_GetIter(iterable);
390 if (it == NULL)
391 return NULL;
392
393 if (maxlen == 0)
394 return consume_iterator(it);
395
Raymond Hettingerd9c116c2013-07-09 00:13:21 -0700396 /* Space saving heuristic. Start filling from the left */
397 if (Py_SIZE(deque) == 0) {
398 assert(deque->leftblock == deque->rightblock);
399 assert(deque->leftindex == deque->rightindex+1);
400 deque->leftindex = 1;
401 deque->rightindex = 0;
402 }
403
Raymond Hettinger7a845522015-09-26 01:30:51 -0700404 iternext = *Py_TYPE(it)->tp_iternext;
405 while ((item = iternext(it)) != NULL) {
Raymond Hettinger88057172016-09-11 22:45:53 -0700406 if (deque->rightindex == BLOCKLEN - 1) {
407 block *b = newblock();
408 if (b == NULL) {
409 Py_DECREF(item);
410 Py_DECREF(it);
411 return NULL;
412 }
413 b->leftlink = deque->rightblock;
414 CHECK_END(deque->rightblock->rightlink);
415 deque->rightblock->rightlink = b;
416 deque->rightblock = b;
417 MARK_END(b->rightlink);
418 deque->rightindex = -1;
419 }
420 Py_SIZE(deque)++;
421 deque->rightindex++;
422 deque->rightblock->data[deque->rightindex] = item;
423 if (NEEDS_TRIM(deque, maxlen)) {
424 PyObject *olditem = deque_popleft(deque, NULL);
425 Py_DECREF(olditem);
426 } else {
427 deque->state++;
Raymond Hettinger6b1e1132015-10-11 09:43:50 -0700428 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000429 }
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700430 return finalize_iterator(it);
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000431}
432
Tim Peters1065f752004-10-01 01:03:29 +0000433PyDoc_STRVAR(extend_doc,
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000434"Extend the right side of the deque with elements from the iterable");
435
436static PyObject *
437deque_extendleft(dequeobject *deque, PyObject *iterable)
438{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000439 PyObject *it, *item;
Raymond Hettinger7a845522015-09-26 01:30:51 -0700440 PyObject *(*iternext)(PyObject *);
Raymond Hettinger6b1e1132015-10-11 09:43:50 -0700441 Py_ssize_t maxlen = deque->maxlen;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000443 /* Handle case where id(deque) == id(iterable) */
444 if ((PyObject *)deque == iterable) {
445 PyObject *result;
446 PyObject *s = PySequence_List(iterable);
447 if (s == NULL)
448 return NULL;
449 result = deque_extendleft(deque, s);
450 Py_DECREF(s);
451 return result;
452 }
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000453
Raymond Hettingerd79d5b12016-03-04 09:55:07 -0800454 it = PyObject_GetIter(iterable);
455 if (it == NULL)
456 return NULL;
457
458 if (maxlen == 0)
459 return consume_iterator(it);
460
Raymond Hettingerd9c116c2013-07-09 00:13:21 -0700461 /* Space saving heuristic. Start filling from the right */
462 if (Py_SIZE(deque) == 0) {
463 assert(deque->leftblock == deque->rightblock);
464 assert(deque->leftindex == deque->rightindex+1);
465 deque->leftindex = BLOCKLEN - 1;
466 deque->rightindex = BLOCKLEN - 2;
467 }
468
Raymond Hettinger7a845522015-09-26 01:30:51 -0700469 iternext = *Py_TYPE(it)->tp_iternext;
470 while ((item = iternext(it)) != NULL) {
Raymond Hettinger88057172016-09-11 22:45:53 -0700471 if (deque->leftindex == 0) {
472 block *b = newblock();
473 if (b == NULL) {
474 Py_DECREF(item);
475 Py_DECREF(it);
476 return NULL;
477 }
478 b->rightlink = deque->leftblock;
479 CHECK_END(deque->leftblock->leftlink);
480 deque->leftblock->leftlink = b;
481 deque->leftblock = b;
482 MARK_END(b->leftlink);
483 deque->leftindex = BLOCKLEN;
484 }
485 Py_SIZE(deque)++;
486 deque->leftindex--;
487 deque->leftblock->data[deque->leftindex] = item;
488 if (NEEDS_TRIM(deque, maxlen)) {
489 PyObject *olditem = deque_pop(deque, NULL);
490 Py_DECREF(olditem);
491 } else {
492 deque->state++;
Raymond Hettinger6b1e1132015-10-11 09:43:50 -0700493 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 }
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700495 return finalize_iterator(it);
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000496}
497
Tim Peters1065f752004-10-01 01:03:29 +0000498PyDoc_STRVAR(extendleft_doc,
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000499"Extend the left side of the deque with elements from the iterable");
500
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000501static PyObject *
502deque_inplace_concat(dequeobject *deque, PyObject *other)
503{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 PyObject *result;
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 result = deque_extend(deque, other);
507 if (result == NULL)
508 return result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000509 Py_INCREF(deque);
Raymond Hettinger2b2b7532015-09-05 17:05:52 -0700510 Py_DECREF(result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 return (PyObject *)deque;
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000512}
513
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700514static PyObject *
515deque_copy(PyObject *deque)
516{
517 dequeobject *old_deque = (dequeobject *)deque;
518 if (Py_TYPE(deque) == &deque_type) {
519 dequeobject *new_deque;
520 PyObject *rv;
521
522 new_deque = (dequeobject *)deque_new(&deque_type, (PyObject *)NULL, (PyObject *)NULL);
523 if (new_deque == NULL)
524 return NULL;
525 new_deque->maxlen = old_deque->maxlen;
526 /* Fast path for the deque_repeat() common case where len(deque) == 1 */
Raymond Hettinger0443ac22015-10-05 22:52:37 -0400527 if (Py_SIZE(deque) == 1) {
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700528 PyObject *item = old_deque->leftblock->data[old_deque->leftindex];
529 rv = deque_append(new_deque, item);
530 } else {
531 rv = deque_extend(new_deque, deque);
532 }
533 if (rv != NULL) {
534 Py_DECREF(rv);
535 return (PyObject *)new_deque;
536 }
537 Py_DECREF(new_deque);
538 return NULL;
539 }
540 if (old_deque->maxlen < 0)
Victor Stinner7bfb42d2016-12-05 17:04:32 +0100541 return PyObject_CallFunctionObjArgs((PyObject *)(Py_TYPE(deque)),
542 deque, NULL);
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700543 else
544 return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "Oi",
545 deque, old_deque->maxlen, NULL);
546}
547
548PyDoc_STRVAR(copy_doc, "Return a shallow copy of a deque.");
Raymond Hettinger41290a62015-03-31 08:12:23 -0700549
550static PyObject *
551deque_concat(dequeobject *deque, PyObject *other)
552{
Benjamin Peterson1a629212015-04-04 10:52:36 -0400553 PyObject *new_deque, *result;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700554 int rv;
555
556 rv = PyObject_IsInstance(other, (PyObject *)&deque_type);
557 if (rv <= 0) {
558 if (rv == 0) {
559 PyErr_Format(PyExc_TypeError,
560 "can only concatenate deque (not \"%.200s\") to deque",
561 other->ob_type->tp_name);
562 }
563 return NULL;
564 }
565
566 new_deque = deque_copy((PyObject *)deque);
567 if (new_deque == NULL)
568 return NULL;
Benjamin Peterson1a629212015-04-04 10:52:36 -0400569 result = deque_extend((dequeobject *)new_deque, other);
570 if (result == NULL) {
571 Py_DECREF(new_deque);
572 return NULL;
573 }
574 Py_DECREF(result);
575 return new_deque;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700576}
577
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700578static void
579deque_clear(dequeobject *deque)
580{
581 block *b;
582 block *prevblock;
583 block *leftblock;
584 Py_ssize_t leftindex;
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800585 Py_ssize_t n, m;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700586 PyObject *item;
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800587 PyObject **itemptr, **limit;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700588
Raymond Hettinger38031142015-09-29 22:45:05 -0700589 if (Py_SIZE(deque) == 0)
590 return;
591
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700592 /* During the process of clearing a deque, decrefs can cause the
593 deque to mutate. To avoid fatal confusion, we have to make the
594 deque empty before clearing the blocks and never refer to
595 anything via deque->ref while clearing. (This is the same
596 technique used for clearing lists, sets, and dicts.)
597
598 Making the deque empty requires allocating a new empty block. In
599 the unlikely event that memory is full, we fall back to an
600 alternate method that doesn't require a new block. Repeating
601 pops in a while-loop is slower, possibly re-entrant (and a clever
602 adversary could cause it to never terminate).
603 */
604
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700605 b = newblock();
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700606 if (b == NULL) {
607 PyErr_Clear();
608 goto alternate_method;
609 }
610
611 /* Remember the old size, leftblock, and leftindex */
Raymond Hettinger6f86a332016-03-02 00:30:58 -0800612 n = Py_SIZE(deque);
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700613 leftblock = deque->leftblock;
614 leftindex = deque->leftindex;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700615
616 /* Set the deque to be empty using the newly allocated block */
617 MARK_END(b->leftlink);
618 MARK_END(b->rightlink);
619 Py_SIZE(deque) = 0;
620 deque->leftblock = b;
621 deque->rightblock = b;
622 deque->leftindex = CENTER + 1;
623 deque->rightindex = CENTER;
624 deque->state++;
625
626 /* Now the old size, leftblock, and leftindex are disconnected from
627 the empty deque and we can use them to decref the pointers.
628 */
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800629 m = (BLOCKLEN - leftindex > n) ? n : BLOCKLEN - leftindex;
Raymond Hettinger589106b2016-03-02 00:06:21 -0800630 itemptr = &leftblock->data[leftindex];
Raymond Hettinger6f86a332016-03-02 00:30:58 -0800631 limit = itemptr + m;
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800632 n -= m;
633 while (1) {
634 if (itemptr == limit) {
635 if (n == 0)
636 break;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700637 CHECK_NOT_END(leftblock->rightlink);
638 prevblock = leftblock;
639 leftblock = leftblock->rightlink;
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800640 m = (n > BLOCKLEN) ? BLOCKLEN : n;
Raymond Hettinger589106b2016-03-02 00:06:21 -0800641 itemptr = leftblock->data;
Raymond Hettinger6f86a332016-03-02 00:30:58 -0800642 limit = itemptr + m;
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800643 n -= m;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700644 freeblock(prevblock);
645 }
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800646 item = *(itemptr++);
647 Py_DECREF(item);
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700648 }
649 CHECK_END(leftblock->rightlink);
650 freeblock(leftblock);
651 return;
652
653 alternate_method:
654 while (Py_SIZE(deque)) {
655 item = deque_pop(deque, NULL);
656 assert (item != NULL);
657 Py_DECREF(item);
658 }
659}
660
661static PyObject *
662deque_clearmethod(dequeobject *deque)
663{
664 deque_clear(deque);
665 Py_RETURN_NONE;
666}
667
668PyDoc_STRVAR(clear_doc, "Remove all elements from the deque.");
Raymond Hettinger41290a62015-03-31 08:12:23 -0700669
670static PyObject *
Raymond Hettinger41290a62015-03-31 08:12:23 -0700671deque_inplace_repeat(dequeobject *deque, Py_ssize_t n)
672{
Raymond Hettingerc22eee62015-09-26 02:14:50 -0700673 Py_ssize_t i, m, size;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700674 PyObject *seq;
675 PyObject *rv;
676
677 size = Py_SIZE(deque);
678 if (size == 0 || n == 1) {
679 Py_INCREF(deque);
680 return (PyObject *)deque;
681 }
682
683 if (n <= 0) {
684 deque_clear(deque);
685 Py_INCREF(deque);
686 return (PyObject *)deque;
687 }
688
Raymond Hettinger41290a62015-03-31 08:12:23 -0700689 if (size == 1) {
690 /* common case, repeating a single element */
691 PyObject *item = deque->leftblock->data[deque->leftindex];
692
Raymond Hettingera7f630092015-10-10 23:56:02 -0400693 if (deque->maxlen >= 0 && n > deque->maxlen)
Raymond Hettinger41290a62015-03-31 08:12:23 -0700694 n = deque->maxlen;
695
Raymond Hettinger67c78b52015-09-12 11:00:20 -0400696 deque->state++;
Raymond Hettingerad262252015-09-14 01:03:04 -0400697 for (i = 0 ; i < n-1 ; ) {
Raymond Hettinger67c78b52015-09-12 11:00:20 -0400698 if (deque->rightindex == BLOCKLEN - 1) {
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700699 block *b = newblock();
Raymond Hettinger67c78b52015-09-12 11:00:20 -0400700 if (b == NULL) {
701 Py_SIZE(deque) += i;
702 return NULL;
703 }
704 b->leftlink = deque->rightblock;
705 CHECK_END(deque->rightblock->rightlink);
706 deque->rightblock->rightlink = b;
707 deque->rightblock = b;
708 MARK_END(b->rightlink);
709 deque->rightindex = -1;
710 }
Raymond Hettingerc22eee62015-09-26 02:14:50 -0700711 m = n - 1 - i;
712 if (m > BLOCKLEN - 1 - deque->rightindex)
713 m = BLOCKLEN - 1 - deque->rightindex;
714 i += m;
715 while (m--) {
Raymond Hettingerad262252015-09-14 01:03:04 -0400716 deque->rightindex++;
717 Py_INCREF(item);
718 deque->rightblock->data[deque->rightindex] = item;
719 }
Raymond Hettinger41290a62015-03-31 08:12:23 -0700720 }
Raymond Hettinger67c78b52015-09-12 11:00:20 -0400721 Py_SIZE(deque) += i;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700722 Py_INCREF(deque);
723 return (PyObject *)deque;
724 }
725
Raymond Hettinger20151f52015-10-16 22:47:29 -0700726 if ((size_t)size > PY_SSIZE_T_MAX / (size_t)n) {
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400727 return PyErr_NoMemory();
728 }
729
Raymond Hettinger41290a62015-03-31 08:12:23 -0700730 seq = PySequence_List((PyObject *)deque);
731 if (seq == NULL)
732 return seq;
733
Louie Lu357bad72017-02-24 11:59:49 +0800734 /* Reduce the number of repetitions when maxlen would be exceeded */
735 if (deque->maxlen >= 0 && n * size > deque->maxlen)
736 n = (deque->maxlen + size - 1) / size;
737
Raymond Hettinger41290a62015-03-31 08:12:23 -0700738 for (i = 0 ; i < n-1 ; i++) {
739 rv = deque_extend(deque, seq);
740 if (rv == NULL) {
741 Py_DECREF(seq);
742 return NULL;
743 }
744 Py_DECREF(rv);
745 }
746 Py_INCREF(deque);
747 Py_DECREF(seq);
748 return (PyObject *)deque;
749}
750
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400751static PyObject *
752deque_repeat(dequeobject *deque, Py_ssize_t n)
753{
754 dequeobject *new_deque;
Raymond Hettinger95e2cc52015-09-13 02:41:18 -0400755 PyObject *rv;
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400756
757 new_deque = (dequeobject *)deque_copy((PyObject *) deque);
758 if (new_deque == NULL)
759 return NULL;
Raymond Hettinger95e2cc52015-09-13 02:41:18 -0400760 rv = deque_inplace_repeat(new_deque, n);
761 Py_DECREF(new_deque);
762 return rv;
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400763}
764
Raymond Hettinger54023152014-04-23 00:58:48 -0700765/* The rotate() method is part of the public API and is used internally
766as a primitive for other methods.
767
768Rotation by 1 or -1 is a common case, so any optimizations for high
769volume rotations should take care not to penalize the common case.
770
771Conceptually, a rotate by one is equivalent to a pop on one side and an
772append on the other. However, a pop/append pair is unnecessarily slow
Martin Panterd2ad5712015-11-02 04:20:33 +0000773because it requires an incref/decref pair for an object located randomly
Raymond Hettinger54023152014-04-23 00:58:48 -0700774in memory. It is better to just move the object pointer from one block
775to the next without changing the reference count.
776
777When moving batches of pointers, it is tempting to use memcpy() but that
778proved to be slower than a simple loop for a variety of reasons.
779Memcpy() cannot know in advance that we're copying pointers instead of
780bytes, that the source and destination are pointer aligned and
781non-overlapping, that moving just one pointer is a common case, that we
782never need to move more than BLOCKLEN pointers, and that at least one
783pointer is always moved.
784
785For high volume rotations, newblock() and freeblock() are never called
786more than once. Previously emptied blocks are immediately reused as a
787destination block. If a block is left-over at the end, it is freed.
788*/
789
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000790static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000791_deque_rotate(dequeobject *deque, Py_ssize_t n)
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000792{
Raymond Hettinger3959af92013-07-13 02:34:08 -0700793 block *b = NULL;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700794 block *leftblock = deque->leftblock;
795 block *rightblock = deque->rightblock;
796 Py_ssize_t leftindex = deque->leftindex;
797 Py_ssize_t rightindex = deque->rightindex;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000798 Py_ssize_t len=Py_SIZE(deque), halflen=len>>1;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700799 int rv = -1;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000800
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800801 if (len <= 1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000802 return 0;
803 if (n > halflen || n < -halflen) {
804 n %= len;
805 if (n > halflen)
806 n -= len;
807 else if (n < -halflen)
808 n += len;
809 }
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500810 assert(len > 1);
Raymond Hettingera4409c12013-02-04 00:08:12 -0500811 assert(-halflen <= n && n <= halflen);
Raymond Hettinger231ee4d2013-02-02 11:24:43 -0800812
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800813 deque->state++;
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500814 while (n > 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700815 if (leftindex == 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700816 if (b == NULL) {
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700817 b = newblock();
Raymond Hettinger3959af92013-07-13 02:34:08 -0700818 if (b == NULL)
819 goto done;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700820 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000821 b->rightlink = leftblock;
822 CHECK_END(leftblock->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700823 leftblock->leftlink = b;
824 leftblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000825 MARK_END(b->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700826 leftindex = BLOCKLEN;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700827 b = NULL;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800828 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700829 assert(leftindex > 0);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700830 {
831 PyObject **src, **dest;
832 Py_ssize_t m = n;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800833
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700834 if (m > rightindex + 1)
835 m = rightindex + 1;
836 if (m > leftindex)
837 m = leftindex;
838 assert (m > 0 && m <= len);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700839 rightindex -= m;
840 leftindex -= m;
Raymond Hettinger0e259f12015-02-01 22:53:41 -0800841 src = &rightblock->data[rightindex + 1];
842 dest = &leftblock->data[leftindex];
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700843 n -= m;
Raymond Hettinger840533b2013-07-13 17:03:58 -0700844 do {
Raymond Hettinger0e259f12015-02-01 22:53:41 -0800845 *(dest++) = *(src++);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700846 } while (--m);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700847 }
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -0700848 if (rightindex < 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700849 assert(leftblock != rightblock);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700850 assert(b == NULL);
Raymond Hettinger3959af92013-07-13 02:34:08 -0700851 b = rightblock;
Raymond Hettingerb97cc492013-07-21 01:51:07 -0700852 CHECK_NOT_END(rightblock->leftlink);
853 rightblock = rightblock->leftlink;
854 MARK_END(rightblock->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700855 rightindex = BLOCKLEN - 1;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800856 }
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800857 }
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500858 while (n < 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700859 if (rightindex == BLOCKLEN - 1) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700860 if (b == NULL) {
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700861 b = newblock();
Raymond Hettinger3959af92013-07-13 02:34:08 -0700862 if (b == NULL)
863 goto done;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700864 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000865 b->leftlink = rightblock;
866 CHECK_END(rightblock->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700867 rightblock->rightlink = b;
868 rightblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000869 MARK_END(b->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700870 rightindex = -1;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700871 b = NULL;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800872 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700873 assert (rightindex < BLOCKLEN - 1);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700874 {
875 PyObject **src, **dest;
876 Py_ssize_t m = -n;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800877
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700878 if (m > BLOCKLEN - leftindex)
879 m = BLOCKLEN - leftindex;
880 if (m > BLOCKLEN - 1 - rightindex)
881 m = BLOCKLEN - 1 - rightindex;
882 assert (m > 0 && m <= len);
883 src = &leftblock->data[leftindex];
884 dest = &rightblock->data[rightindex + 1];
885 leftindex += m;
886 rightindex += m;
887 n += m;
Raymond Hettinger840533b2013-07-13 17:03:58 -0700888 do {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700889 *(dest++) = *(src++);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700890 } while (--m);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700891 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700892 if (leftindex == BLOCKLEN) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700893 assert(leftblock != rightblock);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700894 assert(b == NULL);
Raymond Hettinger3959af92013-07-13 02:34:08 -0700895 b = leftblock;
Raymond Hettingerb97cc492013-07-21 01:51:07 -0700896 CHECK_NOT_END(leftblock->rightlink);
897 leftblock = leftblock->rightlink;
898 MARK_END(leftblock->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700899 leftindex = 0;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800900 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000901 }
Raymond Hettinger3959af92013-07-13 02:34:08 -0700902 rv = 0;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700903done:
Raymond Hettinger3959af92013-07-13 02:34:08 -0700904 if (b != NULL)
905 freeblock(b);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700906 deque->leftblock = leftblock;
907 deque->rightblock = rightblock;
908 deque->leftindex = leftindex;
909 deque->rightindex = rightindex;
910
911 return rv;
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000912}
913
914static PyObject *
Serhiy Storchaka6969eaf2017-07-03 21:20:15 +0300915deque_rotate(dequeobject *deque, PyObject **args, Py_ssize_t nargs)
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000916{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000917 Py_ssize_t n=1;
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000918
Victor Stinnerdd407d52017-02-06 16:06:49 +0100919 if (!_PyArg_ParseStack(args, nargs, "|n:rotate", &n)) {
920 return NULL;
921 }
922
Raymond Hettinger6921c132015-03-21 02:03:40 -0700923 if (!_deque_rotate(deque, n))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 Py_RETURN_NONE;
925 return NULL;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000926}
927
Tim Peters1065f752004-10-01 01:03:29 +0000928PyDoc_STRVAR(rotate_doc,
Raymond Hettingeree33b272004-02-08 04:05:26 +0000929"Rotate the deque n steps to the right (default n=1). If n is negative, rotates left.");
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000930
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000931static PyObject *
932deque_reverse(dequeobject *deque, PyObject *unused)
933{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 block *leftblock = deque->leftblock;
935 block *rightblock = deque->rightblock;
936 Py_ssize_t leftindex = deque->leftindex;
937 Py_ssize_t rightindex = deque->rightindex;
Raymond Hettingercfe5b6c2015-07-20 00:25:50 -0400938 Py_ssize_t n = Py_SIZE(deque) >> 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 PyObject *tmp;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000940
Raymond Hettingere1b02872017-09-04 16:07:06 -0700941 while (--n >= 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 /* Validate that pointers haven't met in the middle */
943 assert(leftblock != rightblock || leftindex < rightindex);
Raymond Hettinger82df9252013-07-07 01:43:42 -1000944 CHECK_NOT_END(leftblock);
945 CHECK_NOT_END(rightblock);
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 /* Swap */
948 tmp = leftblock->data[leftindex];
949 leftblock->data[leftindex] = rightblock->data[rightindex];
950 rightblock->data[rightindex] = tmp;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000951
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 /* Advance left block/index pair */
953 leftindex++;
954 if (leftindex == BLOCKLEN) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 leftblock = leftblock->rightlink;
956 leftindex = 0;
957 }
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000958
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 /* Step backwards with the right block/index pair */
960 rightindex--;
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -0700961 if (rightindex < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962 rightblock = rightblock->leftlink;
963 rightindex = BLOCKLEN - 1;
964 }
965 }
966 Py_RETURN_NONE;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000967}
968
969PyDoc_STRVAR(reverse_doc,
970"D.reverse() -- reverse *IN PLACE*");
971
Raymond Hettinger44459de2010-04-03 23:20:46 +0000972static PyObject *
973deque_count(dequeobject *deque, PyObject *v)
974{
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000975 block *b = deque->leftblock;
976 Py_ssize_t index = deque->leftindex;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000977 Py_ssize_t n = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 Py_ssize_t count = 0;
Raymond Hettingerf9d9c792015-03-02 22:47:46 -0800979 size_t start_state = deque->state;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000980 PyObject *item;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000981 int cmp;
Raymond Hettinger44459de2010-04-03 23:20:46 +0000982
Raymond Hettingere1b02872017-09-04 16:07:06 -0700983 while (--n >= 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000984 CHECK_NOT_END(b);
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000985 item = b->data[index];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
Raymond Hettinger2b0d6462015-09-23 19:15:44 -0700987 if (cmp < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000988 return NULL;
Raymond Hettinger2b0d6462015-09-23 19:15:44 -0700989 count += cmp;
Raymond Hettinger44459de2010-04-03 23:20:46 +0000990
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 if (start_state != deque->state) {
992 PyErr_SetString(PyExc_RuntimeError,
993 "deque mutated during iteration");
994 return NULL;
995 }
Raymond Hettinger44459de2010-04-03 23:20:46 +0000996
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 /* Advance left block/index pair */
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000998 index++;
999 if (index == BLOCKLEN) {
1000 b = b->rightlink;
1001 index = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 }
1003 }
1004 return PyLong_FromSsize_t(count);
Raymond Hettinger44459de2010-04-03 23:20:46 +00001005}
1006
1007PyDoc_STRVAR(count_doc,
1008"D.count(value) -> integer -- return number of occurrences of value");
1009
Raymond Hettinger39dadf72015-03-20 16:38:56 -07001010static int
1011deque_contains(dequeobject *deque, PyObject *v)
1012{
1013 block *b = deque->leftblock;
1014 Py_ssize_t index = deque->leftindex;
1015 Py_ssize_t n = Py_SIZE(deque);
Raymond Hettinger39dadf72015-03-20 16:38:56 -07001016 size_t start_state = deque->state;
1017 PyObject *item;
1018 int cmp;
1019
Raymond Hettingere1b02872017-09-04 16:07:06 -07001020 while (--n >= 0) {
Raymond Hettinger39dadf72015-03-20 16:38:56 -07001021 CHECK_NOT_END(b);
1022 item = b->data[index];
1023 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
1024 if (cmp) {
1025 return cmp;
1026 }
1027 if (start_state != deque->state) {
1028 PyErr_SetString(PyExc_RuntimeError,
1029 "deque mutated during iteration");
1030 return -1;
1031 }
1032 index++;
1033 if (index == BLOCKLEN) {
1034 b = b->rightlink;
1035 index = 0;
1036 }
1037 }
1038 return 0;
1039}
1040
Martin v. Löwis18e16552006-02-15 17:27:45 +00001041static Py_ssize_t
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001042deque_len(dequeobject *deque)
1043{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001044 return Py_SIZE(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001045}
1046
Raymond Hettinger4aec61e2005-03-18 21:20:23 +00001047static PyObject *
Serhiy Storchaka6969eaf2017-07-03 21:20:15 +03001048deque_index(dequeobject *deque, PyObject **args, Py_ssize_t nargs)
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001049{
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001050 Py_ssize_t i, n, start=0, stop=Py_SIZE(deque);
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001051 PyObject *v, *item;
1052 block *b = deque->leftblock;
1053 Py_ssize_t index = deque->leftindex;
1054 size_t start_state = deque->state;
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001055 int cmp;
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001056
Victor Stinnerdd407d52017-02-06 16:06:49 +01001057 if (!_PyArg_ParseStack(args, nargs, "O|O&O&:index", &v,
Serhiy Storchakad4edfc92017-03-30 18:29:23 +03001058 _PyEval_SliceIndexNotNone, &start,
1059 _PyEval_SliceIndexNotNone, &stop)) {
Victor Stinnerdd407d52017-02-06 16:06:49 +01001060 return NULL;
1061 }
1062
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001063 if (start < 0) {
1064 start += Py_SIZE(deque);
1065 if (start < 0)
1066 start = 0;
1067 }
1068 if (stop < 0) {
1069 stop += Py_SIZE(deque);
1070 if (stop < 0)
1071 stop = 0;
1072 }
Raymond Hettinger87674ec2015-08-26 08:08:38 -07001073 if (stop > Py_SIZE(deque))
1074 stop = Py_SIZE(deque);
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001075 if (start > stop)
1076 start = stop;
1077 assert(0 <= start && start <= stop && stop <= Py_SIZE(deque));
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001078
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001079 /* XXX Replace this loop with faster code from deque_item() */
1080 for (i=0 ; i<start ; i++) {
1081 index++;
1082 if (index == BLOCKLEN) {
1083 b = b->rightlink;
1084 index = 0;
1085 }
1086 }
1087
Raymond Hettingere1b02872017-09-04 16:07:06 -07001088 n = stop - i;
1089 while (--n >= 0) {
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001090 CHECK_NOT_END(b);
1091 item = b->data[index];
1092 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
1093 if (cmp > 0)
Raymond Hettingere1b02872017-09-04 16:07:06 -07001094 return PyLong_FromSsize_t(stop - n - 1);
Raymond Hettingerdf8f5b52015-11-02 07:27:40 -05001095 if (cmp < 0)
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001096 return NULL;
1097 if (start_state != deque->state) {
1098 PyErr_SetString(PyExc_RuntimeError,
1099 "deque mutated during iteration");
1100 return NULL;
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001101 }
1102 index++;
1103 if (index == BLOCKLEN) {
1104 b = b->rightlink;
1105 index = 0;
1106 }
1107 }
1108 PyErr_Format(PyExc_ValueError, "%R is not in deque", v);
1109 return NULL;
1110}
1111
1112PyDoc_STRVAR(index_doc,
1113"D.index(value, [start, [stop]]) -> integer -- return first index of value.\n"
1114"Raises ValueError if the value is not present.");
1115
Raymond Hettinger551350a2015-03-24 00:19:53 -07001116/* insert(), remove(), and delitem() are implemented in terms of
1117 rotate() for simplicity and reasonable performance near the end
1118 points. If for some reason these methods become popular, it is not
1119 hard to re-implement this using direct data movement (similar to
1120 the code used in list slice assignments) and achieve a performance
Raymond Hettingerfef9c1b2015-03-24 21:12:57 -07001121 boost (by moving each pointer only once instead of twice).
Raymond Hettinger551350a2015-03-24 00:19:53 -07001122*/
1123
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001124static PyObject *
Serhiy Storchaka6969eaf2017-07-03 21:20:15 +03001125deque_insert(dequeobject *deque, PyObject **args, Py_ssize_t nargs)
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001126{
1127 Py_ssize_t index;
1128 Py_ssize_t n = Py_SIZE(deque);
1129 PyObject *value;
1130 PyObject *rv;
1131
Victor Stinnerdd407d52017-02-06 16:06:49 +01001132 if (!_PyArg_ParseStack(args, nargs, "nO:insert", &index, &value)) {
1133 return NULL;
1134 }
1135
Raymond Hettinger37434322016-01-26 21:44:16 -08001136 if (deque->maxlen == Py_SIZE(deque)) {
Raymond Hettingera6389712016-02-01 21:21:19 -08001137 PyErr_SetString(PyExc_IndexError, "deque already at its maximum size");
1138 return NULL;
Raymond Hettinger37434322016-01-26 21:44:16 -08001139 }
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001140 if (index >= n)
1141 return deque_append(deque, value);
1142 if (index <= -n || index == 0)
1143 return deque_appendleft(deque, value);
1144 if (_deque_rotate(deque, -index))
1145 return NULL;
1146 if (index < 0)
1147 rv = deque_append(deque, value);
1148 else
1149 rv = deque_appendleft(deque, value);
1150 if (rv == NULL)
1151 return NULL;
1152 Py_DECREF(rv);
1153 if (_deque_rotate(deque, index))
1154 return NULL;
1155 Py_RETURN_NONE;
1156}
1157
1158PyDoc_STRVAR(insert_doc,
1159"D.insert(index, object) -- insert object before index");
1160
1161static PyObject *
Raymond Hettinger4aec61e2005-03-18 21:20:23 +00001162deque_remove(dequeobject *deque, PyObject *value)
1163{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001164 Py_ssize_t i, n=Py_SIZE(deque);
Raymond Hettinger4aec61e2005-03-18 21:20:23 +00001165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 for (i=0 ; i<n ; i++) {
1167 PyObject *item = deque->leftblock->data[deque->leftindex];
1168 int cmp = PyObject_RichCompareBool(item, value, Py_EQ);
Raymond Hettingerd73202c2005-03-19 00:00:51 +00001169
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001170 if (Py_SIZE(deque) != n) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001171 PyErr_SetString(PyExc_IndexError,
1172 "deque mutated during remove().");
1173 return NULL;
1174 }
1175 if (cmp > 0) {
1176 PyObject *tgt = deque_popleft(deque, NULL);
1177 assert (tgt != NULL);
Raymond Hettinger6921c132015-03-21 02:03:40 -07001178 if (_deque_rotate(deque, i))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001179 return NULL;
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001180 Py_DECREF(tgt);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001181 Py_RETURN_NONE;
1182 }
1183 else if (cmp < 0) {
1184 _deque_rotate(deque, i);
1185 return NULL;
1186 }
1187 _deque_rotate(deque, -1);
1188 }
1189 PyErr_SetString(PyExc_ValueError, "deque.remove(x): x not in deque");
1190 return NULL;
Raymond Hettinger4aec61e2005-03-18 21:20:23 +00001191}
1192
1193PyDoc_STRVAR(remove_doc,
1194"D.remove(value) -- remove first occurrence of value.");
1195
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001196static int
1197valid_index(Py_ssize_t i, Py_ssize_t limit)
1198{
Raymond Hettinger12f896c2015-07-31 12:03:20 -07001199 /* The cast to size_t lets us use just a single comparison
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001200 to check whether i is in the range: 0 <= i < limit */
1201 return (size_t) i < (size_t) limit;
1202}
1203
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001204static PyObject *
Benjamin Petersond6313712008-07-31 16:23:04 +00001205deque_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001206{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001207 block *b;
1208 PyObject *item;
1209 Py_ssize_t n, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001210
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001211 if (!valid_index(i, Py_SIZE(deque))) {
1212 PyErr_SetString(PyExc_IndexError, "deque index out of range");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 return NULL;
1214 }
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001216 if (i == 0) {
1217 i = deque->leftindex;
1218 b = deque->leftblock;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001219 } else if (i == Py_SIZE(deque) - 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001220 i = deque->rightindex;
1221 b = deque->rightblock;
1222 } else {
1223 i += deque->leftindex;
Raymond Hettingerc2083082015-02-28 23:29:16 -08001224 n = (Py_ssize_t)((size_t) i / BLOCKLEN);
1225 i = (Py_ssize_t)((size_t) i % BLOCKLEN);
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001226 if (index < (Py_SIZE(deque) >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001227 b = deque->leftblock;
Raymond Hettingere1b02872017-09-04 16:07:06 -07001228 while (--n >= 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 b = b->rightlink;
1230 } else {
Raymond Hettinger63d1ff22015-02-28 07:41:30 -08001231 n = (Py_ssize_t)(
Raymond Hettingerc2083082015-02-28 23:29:16 -08001232 ((size_t)(deque->leftindex + Py_SIZE(deque) - 1))
Raymond Hettinger63d1ff22015-02-28 07:41:30 -08001233 / BLOCKLEN - n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 b = deque->rightblock;
Raymond Hettingere1b02872017-09-04 16:07:06 -07001235 while (--n >= 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001236 b = b->leftlink;
1237 }
1238 }
1239 item = b->data[i];
1240 Py_INCREF(item);
1241 return item;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001242}
1243
1244static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001245deque_del_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001246{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001247 PyObject *item;
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001248 int rv;
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001249
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001250 assert (i >= 0 && i < Py_SIZE(deque));
Raymond Hettinger6921c132015-03-21 02:03:40 -07001251 if (_deque_rotate(deque, -i))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001252 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001253 item = deque_popleft(deque, NULL);
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001254 rv = _deque_rotate(deque, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001255 assert (item != NULL);
1256 Py_DECREF(item);
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001257 return rv;
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001258}
1259
1260static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001261deque_ass_item(dequeobject *deque, Py_ssize_t i, PyObject *v)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001262{
Raymond Hettinger38418662016-02-08 20:34:49 -08001263 PyObject *old_value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001264 block *b;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001265 Py_ssize_t n, len=Py_SIZE(deque), halflen=(len+1)>>1, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001266
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001267 if (!valid_index(i, len)) {
1268 PyErr_SetString(PyExc_IndexError, "deque index out of range");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001269 return -1;
1270 }
1271 if (v == NULL)
1272 return deque_del_item(deque, i);
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001274 i += deque->leftindex;
Raymond Hettingerc2083082015-02-28 23:29:16 -08001275 n = (Py_ssize_t)((size_t) i / BLOCKLEN);
1276 i = (Py_ssize_t)((size_t) i % BLOCKLEN);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001277 if (index <= halflen) {
1278 b = deque->leftblock;
Raymond Hettingere1b02872017-09-04 16:07:06 -07001279 while (--n >= 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001280 b = b->rightlink;
1281 } else {
Raymond Hettingera473b9d2015-02-28 17:49:47 -08001282 n = (Py_ssize_t)(
Raymond Hettingerc2083082015-02-28 23:29:16 -08001283 ((size_t)(deque->leftindex + Py_SIZE(deque) - 1))
Raymond Hettingera473b9d2015-02-28 17:49:47 -08001284 / BLOCKLEN - n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001285 b = deque->rightblock;
Raymond Hettingere1b02872017-09-04 16:07:06 -07001286 while (--n >= 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001287 b = b->leftlink;
1288 }
1289 Py_INCREF(v);
Raymond Hettinger38418662016-02-08 20:34:49 -08001290 old_value = b->data[i];
1291 b->data[i] = v;
1292 Py_DECREF(old_value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001293 return 0;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001294}
1295
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001296static void
1297deque_dealloc(dequeobject *deque)
1298{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001299 PyObject_GC_UnTrack(deque);
1300 if (deque->weakreflist != NULL)
1301 PyObject_ClearWeakRefs((PyObject *) deque);
1302 if (deque->leftblock != NULL) {
1303 deque_clear(deque);
1304 assert(deque->leftblock != NULL);
1305 freeblock(deque->leftblock);
1306 }
1307 deque->leftblock = NULL;
1308 deque->rightblock = NULL;
1309 Py_TYPE(deque)->tp_free(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001310}
1311
1312static int
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001313deque_traverse(dequeobject *deque, visitproc visit, void *arg)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001314{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001315 block *b;
1316 PyObject *item;
1317 Py_ssize_t index;
1318 Py_ssize_t indexlo = deque->leftindex;
Raymond Hettinger1286d142015-10-14 23:16:57 -07001319 Py_ssize_t indexhigh;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001320
Raymond Hettinger5bfa8672013-07-06 11:58:09 -10001321 for (b = deque->leftblock; b != deque->rightblock; b = b->rightlink) {
1322 for (index = indexlo; index < BLOCKLEN ; index++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001323 item = b->data[index];
1324 Py_VISIT(item);
1325 }
1326 indexlo = 0;
1327 }
Raymond Hettinger1286d142015-10-14 23:16:57 -07001328 indexhigh = deque->rightindex;
1329 for (index = indexlo; index <= indexhigh; index++) {
Raymond Hettinger5bfa8672013-07-06 11:58:09 -10001330 item = b->data[index];
1331 Py_VISIT(item);
1332 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001333 return 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001334}
1335
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001336static PyObject *
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001337deque_reduce(dequeobject *deque)
1338{
Serhiy Storchakaa0d416f2016-03-06 08:55:21 +02001339 PyObject *dict, *it;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001340 _Py_IDENTIFIER(__dict__);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001341
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001342 dict = _PyObject_GetAttrId((PyObject *)deque, &PyId___dict__);
Serhiy Storchakaa0d416f2016-03-06 08:55:21 +02001343 if (dict == NULL) {
1344 if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
1345 return NULL;
1346 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001347 PyErr_Clear();
Serhiy Storchakaa0d416f2016-03-06 08:55:21 +02001348 dict = Py_None;
1349 Py_INCREF(dict);
1350 }
1351
1352 it = PyObject_GetIter((PyObject *)deque);
1353 if (it == NULL) {
1354 Py_DECREF(dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001355 return NULL;
1356 }
Serhiy Storchakaa0d416f2016-03-06 08:55:21 +02001357
1358 if (deque->maxlen < 0) {
1359 return Py_BuildValue("O()NN", Py_TYPE(deque), dict, it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001360 }
Serhiy Storchakaa0d416f2016-03-06 08:55:21 +02001361 else {
1362 return Py_BuildValue("O(()n)NN", Py_TYPE(deque), deque->maxlen, dict, it);
1363 }
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001364}
1365
1366PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
1367
1368static PyObject *
1369deque_repr(PyObject *deque)
1370{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001371 PyObject *aslist, *result;
1372 int i;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001374 i = Py_ReprEnter(deque);
1375 if (i != 0) {
1376 if (i < 0)
1377 return NULL;
1378 return PyUnicode_FromString("[...]");
1379 }
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001381 aslist = PySequence_List(deque);
1382 if (aslist == NULL) {
1383 Py_ReprLeave(deque);
1384 return NULL;
1385 }
Raymond Hettingera7f630092015-10-10 23:56:02 -04001386 if (((dequeobject *)deque)->maxlen >= 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001387 result = PyUnicode_FromFormat("deque(%R, maxlen=%zd)",
1388 aslist, ((dequeobject *)deque)->maxlen);
1389 else
1390 result = PyUnicode_FromFormat("deque(%R)", aslist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001391 Py_ReprLeave(deque);
Raymond Hettinger2b2b7532015-09-05 17:05:52 -07001392 Py_DECREF(aslist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001393 return result;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001394}
1395
Raymond Hettinger738ec902004-02-29 02:15:56 +00001396static PyObject *
1397deque_richcompare(PyObject *v, PyObject *w, int op)
1398{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001399 PyObject *it1=NULL, *it2=NULL, *x, *y;
1400 Py_ssize_t vs, ws;
1401 int b, cmp=-1;
Raymond Hettinger738ec902004-02-29 02:15:56 +00001402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001403 if (!PyObject_TypeCheck(v, &deque_type) ||
1404 !PyObject_TypeCheck(w, &deque_type)) {
Brian Curtindfc80e32011-08-10 20:28:54 -05001405 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001406 }
Raymond Hettinger738ec902004-02-29 02:15:56 +00001407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001408 /* Shortcuts */
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001409 vs = Py_SIZE((dequeobject *)v);
1410 ws = Py_SIZE((dequeobject *)w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001411 if (op == Py_EQ) {
1412 if (v == w)
1413 Py_RETURN_TRUE;
1414 if (vs != ws)
1415 Py_RETURN_FALSE;
1416 }
1417 if (op == Py_NE) {
1418 if (v == w)
1419 Py_RETURN_FALSE;
1420 if (vs != ws)
1421 Py_RETURN_TRUE;
1422 }
Raymond Hettinger738ec902004-02-29 02:15:56 +00001423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001424 /* Search for the first index where items are different */
1425 it1 = PyObject_GetIter(v);
1426 if (it1 == NULL)
1427 goto done;
1428 it2 = PyObject_GetIter(w);
1429 if (it2 == NULL)
1430 goto done;
1431 for (;;) {
1432 x = PyIter_Next(it1);
1433 if (x == NULL && PyErr_Occurred())
1434 goto done;
1435 y = PyIter_Next(it2);
1436 if (x == NULL || y == NULL)
1437 break;
1438 b = PyObject_RichCompareBool(x, y, Py_EQ);
1439 if (b == 0) {
1440 cmp = PyObject_RichCompareBool(x, y, op);
1441 Py_DECREF(x);
1442 Py_DECREF(y);
1443 goto done;
1444 }
1445 Py_DECREF(x);
1446 Py_DECREF(y);
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -07001447 if (b < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001448 goto done;
1449 }
1450 /* We reached the end of one deque or both */
1451 Py_XDECREF(x);
1452 Py_XDECREF(y);
1453 if (PyErr_Occurred())
1454 goto done;
1455 switch (op) {
1456 case Py_LT: cmp = y != NULL; break; /* if w was longer */
1457 case Py_LE: cmp = x == NULL; break; /* if v was not longer */
1458 case Py_EQ: cmp = x == y; break; /* if we reached the end of both */
1459 case Py_NE: cmp = x != y; break; /* if one deque continues */
1460 case Py_GT: cmp = x != NULL; break; /* if v was longer */
1461 case Py_GE: cmp = y == NULL; break; /* if w was not longer */
1462 }
Tim Peters1065f752004-10-01 01:03:29 +00001463
Raymond Hettinger738ec902004-02-29 02:15:56 +00001464done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001465 Py_XDECREF(it1);
1466 Py_XDECREF(it2);
1467 if (cmp == 1)
1468 Py_RETURN_TRUE;
1469 if (cmp == 0)
1470 Py_RETURN_FALSE;
1471 return NULL;
Raymond Hettinger738ec902004-02-29 02:15:56 +00001472}
1473
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001474static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001475deque_init(dequeobject *deque, PyObject *args, PyObject *kwdargs)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001476{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001477 PyObject *iterable = NULL;
1478 PyObject *maxlenobj = NULL;
1479 Py_ssize_t maxlen = -1;
1480 char *kwlist[] = {"iterable", "maxlen", 0};
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001481
Raymond Hettinger0d309402015-09-30 23:15:02 -07001482 if (kwdargs == NULL) {
1483 if (!PyArg_UnpackTuple(args, "deque()", 0, 2, &iterable, &maxlenobj))
1484 return -1;
1485 } else {
1486 if (!PyArg_ParseTupleAndKeywords(args, kwdargs, "|OO:deque", kwlist,
1487 &iterable, &maxlenobj))
1488 return -1;
1489 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001490 if (maxlenobj != NULL && maxlenobj != Py_None) {
1491 maxlen = PyLong_AsSsize_t(maxlenobj);
1492 if (maxlen == -1 && PyErr_Occurred())
1493 return -1;
1494 if (maxlen < 0) {
1495 PyErr_SetString(PyExc_ValueError, "maxlen must be non-negative");
1496 return -1;
1497 }
1498 }
1499 deque->maxlen = maxlen;
Raymond Hettinger0d309402015-09-30 23:15:02 -07001500 if (Py_SIZE(deque) > 0)
1501 deque_clear(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001502 if (iterable != NULL) {
1503 PyObject *rv = deque_extend(deque, iterable);
1504 if (rv == NULL)
1505 return -1;
1506 Py_DECREF(rv);
1507 }
1508 return 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001509}
1510
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001511static PyObject *
Jesus Cea16e2fca2012-08-03 14:49:42 +02001512deque_sizeof(dequeobject *deque, void *unused)
1513{
1514 Py_ssize_t res;
1515 Py_ssize_t blocks;
1516
Serhiy Storchaka5c4064e2015-12-19 20:05:25 +02001517 res = _PyObject_SIZE(Py_TYPE(deque));
Raymond Hettingerbc003412015-10-14 23:33:23 -07001518 blocks = (size_t)(deque->leftindex + Py_SIZE(deque) + BLOCKLEN - 1) / BLOCKLEN;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001519 assert(deque->leftindex + Py_SIZE(deque) - 1 ==
Jesus Cea16e2fca2012-08-03 14:49:42 +02001520 (blocks - 1) * BLOCKLEN + deque->rightindex);
1521 res += blocks * sizeof(block);
1522 return PyLong_FromSsize_t(res);
1523}
1524
1525PyDoc_STRVAR(sizeof_doc,
1526"D.__sizeof__() -- size of D in memory, in bytes");
1527
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001528static int
1529deque_bool(dequeobject *deque)
1530{
1531 return Py_SIZE(deque) != 0;
1532}
1533
Jesus Cea16e2fca2012-08-03 14:49:42 +02001534static PyObject *
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001535deque_get_maxlen(dequeobject *deque)
1536{
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -07001537 if (deque->maxlen < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001538 Py_RETURN_NONE;
1539 return PyLong_FromSsize_t(deque->maxlen);
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001540}
1541
Raymond Hettinger41290a62015-03-31 08:12:23 -07001542
1543/* deque object ********************************************************/
1544
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001545static PyGetSetDef deque_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001546 {"maxlen", (getter)deque_get_maxlen, (setter)NULL,
1547 "maximum size of a deque or None if unbounded"},
1548 {0}
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001549};
1550
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001551static PySequenceMethods deque_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001552 (lenfunc)deque_len, /* sq_length */
Raymond Hettinger41290a62015-03-31 08:12:23 -07001553 (binaryfunc)deque_concat, /* sq_concat */
1554 (ssizeargfunc)deque_repeat, /* sq_repeat */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001555 (ssizeargfunc)deque_item, /* sq_item */
1556 0, /* sq_slice */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001557 (ssizeobjargproc)deque_ass_item, /* sq_ass_item */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001558 0, /* sq_ass_slice */
Raymond Hettinger39dadf72015-03-20 16:38:56 -07001559 (objobjproc)deque_contains, /* sq_contains */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001560 (binaryfunc)deque_inplace_concat, /* sq_inplace_concat */
Raymond Hettinger41290a62015-03-31 08:12:23 -07001561 (ssizeargfunc)deque_inplace_repeat, /* sq_inplace_repeat */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001562};
1563
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001564static PyNumberMethods deque_as_number = {
1565 0, /* nb_add */
1566 0, /* nb_subtract */
1567 0, /* nb_multiply */
1568 0, /* nb_remainder */
1569 0, /* nb_divmod */
1570 0, /* nb_power */
1571 0, /* nb_negative */
1572 0, /* nb_positive */
1573 0, /* nb_absolute */
1574 (inquiry)deque_bool, /* nb_bool */
1575 0, /* nb_invert */
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001576 };
1577
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001578static PyObject *deque_iter(dequeobject *deque);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001579static PyObject *deque_reviter(dequeobject *deque);
Tim Peters1065f752004-10-01 01:03:29 +00001580PyDoc_STRVAR(reversed_doc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001581 "D.__reversed__() -- return a reverse iterator over the deque");
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001582
1583static PyMethodDef deque_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001584 {"append", (PyCFunction)deque_append,
1585 METH_O, append_doc},
1586 {"appendleft", (PyCFunction)deque_appendleft,
1587 METH_O, appendleft_doc},
1588 {"clear", (PyCFunction)deque_clearmethod,
1589 METH_NOARGS, clear_doc},
1590 {"__copy__", (PyCFunction)deque_copy,
1591 METH_NOARGS, copy_doc},
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001592 {"copy", (PyCFunction)deque_copy,
1593 METH_NOARGS, copy_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001594 {"count", (PyCFunction)deque_count,
Raymond Hettinger0f6f9472015-03-21 01:42:10 -07001595 METH_O, count_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001596 {"extend", (PyCFunction)deque_extend,
1597 METH_O, extend_doc},
1598 {"extendleft", (PyCFunction)deque_extendleft,
1599 METH_O, extendleft_doc},
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001600 {"index", (PyCFunction)deque_index,
Victor Stinnerdd407d52017-02-06 16:06:49 +01001601 METH_FASTCALL, index_doc},
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001602 {"insert", (PyCFunction)deque_insert,
Victor Stinnerdd407d52017-02-06 16:06:49 +01001603 METH_FASTCALL, insert_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001604 {"pop", (PyCFunction)deque_pop,
1605 METH_NOARGS, pop_doc},
1606 {"popleft", (PyCFunction)deque_popleft,
1607 METH_NOARGS, popleft_doc},
Raymond Hettinger0f6f9472015-03-21 01:42:10 -07001608 {"__reduce__", (PyCFunction)deque_reduce,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001609 METH_NOARGS, reduce_doc},
1610 {"remove", (PyCFunction)deque_remove,
1611 METH_O, remove_doc},
1612 {"__reversed__", (PyCFunction)deque_reviter,
1613 METH_NOARGS, reversed_doc},
1614 {"reverse", (PyCFunction)deque_reverse,
1615 METH_NOARGS, reverse_doc},
1616 {"rotate", (PyCFunction)deque_rotate,
Victor Stinnerdd407d52017-02-06 16:06:49 +01001617 METH_FASTCALL, rotate_doc},
Jesus Cea16e2fca2012-08-03 14:49:42 +02001618 {"__sizeof__", (PyCFunction)deque_sizeof,
1619 METH_NOARGS, sizeof_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001620 {NULL, NULL} /* sentinel */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001621};
1622
1623PyDoc_STRVAR(deque_doc,
Andrew Svetlov6a5c7c32012-10-31 11:50:40 +02001624"deque([iterable[, maxlen]]) --> deque object\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001625\n\
Raymond Hettinger41290a62015-03-31 08:12:23 -07001626A list-like sequence optimized for data accesses near its endpoints.");
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001627
Neal Norwitz87f10132004-02-29 15:40:53 +00001628static PyTypeObject deque_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001629 PyVarObject_HEAD_INIT(NULL, 0)
1630 "collections.deque", /* tp_name */
1631 sizeof(dequeobject), /* tp_basicsize */
1632 0, /* tp_itemsize */
1633 /* methods */
1634 (destructor)deque_dealloc, /* tp_dealloc */
1635 0, /* tp_print */
1636 0, /* tp_getattr */
1637 0, /* tp_setattr */
1638 0, /* tp_reserved */
1639 deque_repr, /* tp_repr */
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001640 &deque_as_number, /* tp_as_number */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001641 &deque_as_sequence, /* tp_as_sequence */
1642 0, /* tp_as_mapping */
Georg Brandlf038b322010-10-18 07:35:09 +00001643 PyObject_HashNotImplemented, /* tp_hash */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001644 0, /* tp_call */
1645 0, /* tp_str */
1646 PyObject_GenericGetAttr, /* tp_getattro */
1647 0, /* tp_setattro */
1648 0, /* tp_as_buffer */
1649 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
Georg Brandlf038b322010-10-18 07:35:09 +00001650 /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001651 deque_doc, /* tp_doc */
1652 (traverseproc)deque_traverse, /* tp_traverse */
1653 (inquiry)deque_clear, /* tp_clear */
1654 (richcmpfunc)deque_richcompare, /* tp_richcompare */
Georg Brandlf038b322010-10-18 07:35:09 +00001655 offsetof(dequeobject, weakreflist), /* tp_weaklistoffset*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001656 (getiterfunc)deque_iter, /* tp_iter */
1657 0, /* tp_iternext */
1658 deque_methods, /* tp_methods */
1659 0, /* tp_members */
Georg Brandlf038b322010-10-18 07:35:09 +00001660 deque_getset, /* tp_getset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001661 0, /* tp_base */
1662 0, /* tp_dict */
1663 0, /* tp_descr_get */
1664 0, /* tp_descr_set */
1665 0, /* tp_dictoffset */
1666 (initproc)deque_init, /* tp_init */
1667 PyType_GenericAlloc, /* tp_alloc */
1668 deque_new, /* tp_new */
1669 PyObject_GC_Del, /* tp_free */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001670};
1671
1672/*********************** Deque Iterator **************************/
1673
1674typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001675 PyObject_HEAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001676 block *b;
Raymond Hettinger87e69122015-03-02 23:32:02 -08001677 Py_ssize_t index;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001678 dequeobject *deque;
Raymond Hettingerf9d9c792015-03-02 22:47:46 -08001679 size_t state; /* state when the iterator is created */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001680 Py_ssize_t counter; /* number of items remaining for iteration */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001681} dequeiterobject;
1682
Martin v. Löwis59683e82008-06-13 07:50:45 +00001683static PyTypeObject dequeiter_type;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001684
1685static PyObject *
1686deque_iter(dequeobject *deque)
1687{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001688 dequeiterobject *it;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001689
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001690 it = PyObject_GC_New(dequeiterobject, &dequeiter_type);
1691 if (it == NULL)
1692 return NULL;
1693 it->b = deque->leftblock;
1694 it->index = deque->leftindex;
1695 Py_INCREF(deque);
1696 it->deque = deque;
1697 it->state = deque->state;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001698 it->counter = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001699 PyObject_GC_Track(it);
1700 return (PyObject *)it;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001701}
1702
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001703static int
1704dequeiter_traverse(dequeiterobject *dio, visitproc visit, void *arg)
1705{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001706 Py_VISIT(dio->deque);
1707 return 0;
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001708}
1709
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001710static void
1711dequeiter_dealloc(dequeiterobject *dio)
1712{
INADA Naokia6296d32017-08-24 14:55:17 +09001713 /* bpo-31095: UnTrack is needed before calling any callbacks */
1714 PyObject_GC_UnTrack(dio);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001715 Py_XDECREF(dio->deque);
1716 PyObject_GC_Del(dio);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001717}
1718
1719static PyObject *
1720dequeiter_next(dequeiterobject *it)
1721{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001722 PyObject *item;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001723
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001724 if (it->deque->state != it->state) {
1725 it->counter = 0;
1726 PyErr_SetString(PyExc_RuntimeError,
1727 "deque mutated during iteration");
1728 return NULL;
1729 }
1730 if (it->counter == 0)
1731 return NULL;
1732 assert (!(it->b == it->deque->rightblock &&
1733 it->index > it->deque->rightindex));
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001734
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001735 item = it->b->data[it->index];
1736 it->index++;
1737 it->counter--;
1738 if (it->index == BLOCKLEN && it->counter > 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -10001739 CHECK_NOT_END(it->b->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001740 it->b = it->b->rightlink;
1741 it->index = 0;
1742 }
1743 Py_INCREF(item);
1744 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001745}
1746
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001747static PyObject *
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001748dequeiter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1749{
1750 Py_ssize_t i, index=0;
1751 PyObject *deque;
1752 dequeiterobject *it;
1753 if (!PyArg_ParseTuple(args, "O!|n", &deque_type, &deque, &index))
1754 return NULL;
1755 assert(type == &dequeiter_type);
1756
1757 it = (dequeiterobject*)deque_iter((dequeobject *)deque);
1758 if (!it)
1759 return NULL;
1760 /* consume items from the queue */
1761 for(i=0; i<index; i++) {
1762 PyObject *item = dequeiter_next(it);
1763 if (item) {
1764 Py_DECREF(item);
1765 } else {
1766 if (it->counter) {
1767 Py_DECREF(it);
1768 return NULL;
1769 } else
1770 break;
1771 }
1772 }
1773 return (PyObject*)it;
1774}
1775
1776static PyObject *
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001777dequeiter_len(dequeiterobject *it)
1778{
Antoine Pitrou554f3342010-08-17 18:30:06 +00001779 return PyLong_FromSsize_t(it->counter);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001780}
1781
Armin Rigof5b3e362006-02-11 21:32:43 +00001782PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001783
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001784static PyObject *
1785dequeiter_reduce(dequeiterobject *it)
1786{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001787 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 +00001788}
1789
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001790static PyMethodDef dequeiter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001791 {"__length_hint__", (PyCFunction)dequeiter_len, METH_NOARGS, length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001792 {"__reduce__", (PyCFunction)dequeiter_reduce, METH_NOARGS, reduce_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001793 {NULL, NULL} /* sentinel */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001794};
1795
Martin v. Löwis59683e82008-06-13 07:50:45 +00001796static PyTypeObject dequeiter_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001797 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger87e69122015-03-02 23:32:02 -08001798 "_collections._deque_iterator", /* tp_name */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001799 sizeof(dequeiterobject), /* tp_basicsize */
1800 0, /* tp_itemsize */
1801 /* methods */
1802 (destructor)dequeiter_dealloc, /* tp_dealloc */
1803 0, /* tp_print */
1804 0, /* tp_getattr */
1805 0, /* tp_setattr */
1806 0, /* tp_reserved */
1807 0, /* tp_repr */
1808 0, /* tp_as_number */
1809 0, /* tp_as_sequence */
1810 0, /* tp_as_mapping */
1811 0, /* tp_hash */
1812 0, /* tp_call */
1813 0, /* tp_str */
1814 PyObject_GenericGetAttr, /* tp_getattro */
1815 0, /* tp_setattro */
1816 0, /* tp_as_buffer */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001817 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001818 0, /* tp_doc */
1819 (traverseproc)dequeiter_traverse, /* tp_traverse */
1820 0, /* tp_clear */
1821 0, /* tp_richcompare */
1822 0, /* tp_weaklistoffset */
1823 PyObject_SelfIter, /* tp_iter */
1824 (iternextfunc)dequeiter_next, /* tp_iternext */
1825 dequeiter_methods, /* tp_methods */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001826 0, /* tp_members */
1827 0, /* tp_getset */
1828 0, /* tp_base */
1829 0, /* tp_dict */
1830 0, /* tp_descr_get */
1831 0, /* tp_descr_set */
1832 0, /* tp_dictoffset */
1833 0, /* tp_init */
1834 0, /* tp_alloc */
1835 dequeiter_new, /* tp_new */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001836 0,
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001837};
1838
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001839/*********************** Deque Reverse Iterator **************************/
1840
Martin v. Löwis59683e82008-06-13 07:50:45 +00001841static PyTypeObject dequereviter_type;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001842
1843static PyObject *
1844deque_reviter(dequeobject *deque)
1845{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001846 dequeiterobject *it;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001847
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001848 it = PyObject_GC_New(dequeiterobject, &dequereviter_type);
1849 if (it == NULL)
1850 return NULL;
1851 it->b = deque->rightblock;
1852 it->index = deque->rightindex;
1853 Py_INCREF(deque);
1854 it->deque = deque;
1855 it->state = deque->state;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001856 it->counter = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001857 PyObject_GC_Track(it);
1858 return (PyObject *)it;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001859}
1860
1861static PyObject *
1862dequereviter_next(dequeiterobject *it)
1863{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001864 PyObject *item;
1865 if (it->counter == 0)
1866 return NULL;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001868 if (it->deque->state != it->state) {
1869 it->counter = 0;
1870 PyErr_SetString(PyExc_RuntimeError,
1871 "deque mutated during iteration");
1872 return NULL;
1873 }
1874 assert (!(it->b == it->deque->leftblock &&
1875 it->index < it->deque->leftindex));
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001877 item = it->b->data[it->index];
1878 it->index--;
1879 it->counter--;
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -07001880 if (it->index < 0 && it->counter > 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -10001881 CHECK_NOT_END(it->b->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001882 it->b = it->b->leftlink;
1883 it->index = BLOCKLEN - 1;
1884 }
1885 Py_INCREF(item);
1886 return item;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001887}
1888
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001889static PyObject *
1890dequereviter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1891{
1892 Py_ssize_t i, index=0;
1893 PyObject *deque;
1894 dequeiterobject *it;
1895 if (!PyArg_ParseTuple(args, "O!|n", &deque_type, &deque, &index))
1896 return NULL;
1897 assert(type == &dequereviter_type);
1898
1899 it = (dequeiterobject*)deque_reviter((dequeobject *)deque);
1900 if (!it)
1901 return NULL;
1902 /* consume items from the queue */
1903 for(i=0; i<index; i++) {
1904 PyObject *item = dequereviter_next(it);
1905 if (item) {
1906 Py_DECREF(item);
1907 } else {
1908 if (it->counter) {
1909 Py_DECREF(it);
1910 return NULL;
1911 } else
1912 break;
1913 }
1914 }
1915 return (PyObject*)it;
1916}
1917
Martin v. Löwis59683e82008-06-13 07:50:45 +00001918static PyTypeObject dequereviter_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001919 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger87e69122015-03-02 23:32:02 -08001920 "_collections._deque_reverse_iterator", /* tp_name */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001921 sizeof(dequeiterobject), /* tp_basicsize */
1922 0, /* tp_itemsize */
1923 /* methods */
1924 (destructor)dequeiter_dealloc, /* tp_dealloc */
1925 0, /* tp_print */
1926 0, /* tp_getattr */
1927 0, /* tp_setattr */
1928 0, /* tp_reserved */
1929 0, /* tp_repr */
1930 0, /* tp_as_number */
1931 0, /* tp_as_sequence */
1932 0, /* tp_as_mapping */
1933 0, /* tp_hash */
1934 0, /* tp_call */
1935 0, /* tp_str */
1936 PyObject_GenericGetAttr, /* tp_getattro */
1937 0, /* tp_setattro */
1938 0, /* tp_as_buffer */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001939 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001940 0, /* tp_doc */
1941 (traverseproc)dequeiter_traverse, /* tp_traverse */
1942 0, /* tp_clear */
1943 0, /* tp_richcompare */
1944 0, /* tp_weaklistoffset */
1945 PyObject_SelfIter, /* tp_iter */
1946 (iternextfunc)dequereviter_next, /* tp_iternext */
1947 dequeiter_methods, /* tp_methods */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001948 0, /* tp_members */
1949 0, /* tp_getset */
1950 0, /* tp_base */
1951 0, /* tp_dict */
1952 0, /* tp_descr_get */
1953 0, /* tp_descr_set */
1954 0, /* tp_dictoffset */
1955 0, /* tp_init */
1956 0, /* tp_alloc */
1957 dequereviter_new, /* tp_new */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001958 0,
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001959};
1960
Guido van Rossum1968ad32006-02-25 22:38:04 +00001961/* defaultdict type *********************************************************/
1962
1963typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001964 PyDictObject dict;
1965 PyObject *default_factory;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001966} defdictobject;
1967
1968static PyTypeObject defdict_type; /* Forward */
1969
1970PyDoc_STRVAR(defdict_missing_doc,
1971"__missing__(key) # Called by __getitem__ for missing key; pseudo-code:\n\
Guido van Rossumd8faa362007-04-27 19:54:29 +00001972 if self.default_factory is None: raise KeyError((key,))\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00001973 self[key] = value = self.default_factory()\n\
1974 return value\n\
1975");
1976
1977static PyObject *
1978defdict_missing(defdictobject *dd, PyObject *key)
1979{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001980 PyObject *factory = dd->default_factory;
1981 PyObject *value;
1982 if (factory == NULL || factory == Py_None) {
1983 /* XXX Call dict.__missing__(key) */
1984 PyObject *tup;
1985 tup = PyTuple_Pack(1, key);
1986 if (!tup) return NULL;
1987 PyErr_SetObject(PyExc_KeyError, tup);
1988 Py_DECREF(tup);
1989 return NULL;
1990 }
1991 value = PyEval_CallObject(factory, NULL);
1992 if (value == NULL)
1993 return value;
1994 if (PyObject_SetItem((PyObject *)dd, key, value) < 0) {
1995 Py_DECREF(value);
1996 return NULL;
1997 }
1998 return value;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001999}
2000
2001PyDoc_STRVAR(defdict_copy_doc, "D.copy() -> a shallow copy of D.");
2002
2003static PyObject *
2004defdict_copy(defdictobject *dd)
2005{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002006 /* This calls the object's class. That only works for subclasses
2007 whose class constructor has the same signature. Subclasses that
2008 define a different constructor signature must override copy().
2009 */
Raymond Hettinger54628fa2009-08-04 19:16:39 +00002010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002011 if (dd->default_factory == NULL)
2012 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd), Py_None, dd, NULL);
2013 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd),
2014 dd->default_factory, dd, NULL);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002015}
2016
2017static PyObject *
2018defdict_reduce(defdictobject *dd)
2019{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002020 /* __reduce__ must return a 5-tuple as follows:
Guido van Rossum1968ad32006-02-25 22:38:04 +00002021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002022 - factory function
2023 - tuple of args for the factory function
2024 - additional state (here None)
2025 - sequence iterator (here None)
2026 - dictionary iterator (yielding successive (key, value) pairs
Guido van Rossum1968ad32006-02-25 22:38:04 +00002027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002028 This API is used by pickle.py and copy.py.
Guido van Rossum1968ad32006-02-25 22:38:04 +00002029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002030 For this to be useful with pickle.py, the default_factory
2031 must be picklable; e.g., None, a built-in, or a global
2032 function in a module or package.
Guido van Rossum1968ad32006-02-25 22:38:04 +00002033
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002034 Both shallow and deep copying are supported, but for deep
2035 copying, the default_factory must be deep-copyable; e.g. None,
2036 or a built-in (functions are not copyable at this time).
Guido van Rossum1968ad32006-02-25 22:38:04 +00002037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002038 This only works for subclasses as long as their constructor
2039 signature is compatible; the first argument must be the
2040 optional default_factory, defaulting to None.
2041 */
2042 PyObject *args;
2043 PyObject *items;
2044 PyObject *iter;
2045 PyObject *result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002046 _Py_IDENTIFIER(items);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002048 if (dd->default_factory == NULL || dd->default_factory == Py_None)
2049 args = PyTuple_New(0);
2050 else
2051 args = PyTuple_Pack(1, dd->default_factory);
2052 if (args == NULL)
2053 return NULL;
Victor Stinnerad8c83a2016-09-05 17:53:15 -07002054 items = _PyObject_CallMethodId((PyObject *)dd, &PyId_items, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002055 if (items == NULL) {
2056 Py_DECREF(args);
2057 return NULL;
2058 }
2059 iter = PyObject_GetIter(items);
2060 if (iter == NULL) {
2061 Py_DECREF(items);
2062 Py_DECREF(args);
2063 return NULL;
2064 }
2065 result = PyTuple_Pack(5, Py_TYPE(dd), args,
2066 Py_None, Py_None, iter);
2067 Py_DECREF(iter);
2068 Py_DECREF(items);
2069 Py_DECREF(args);
2070 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00002071}
2072
2073static PyMethodDef defdict_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002074 {"__missing__", (PyCFunction)defdict_missing, METH_O,
2075 defdict_missing_doc},
2076 {"copy", (PyCFunction)defdict_copy, METH_NOARGS,
2077 defdict_copy_doc},
2078 {"__copy__", (PyCFunction)defdict_copy, METH_NOARGS,
2079 defdict_copy_doc},
2080 {"__reduce__", (PyCFunction)defdict_reduce, METH_NOARGS,
2081 reduce_doc},
2082 {NULL}
Guido van Rossum1968ad32006-02-25 22:38:04 +00002083};
2084
2085static PyMemberDef defdict_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002086 {"default_factory", T_OBJECT,
2087 offsetof(defdictobject, default_factory), 0,
2088 PyDoc_STR("Factory for default value called by __missing__().")},
2089 {NULL}
Guido van Rossum1968ad32006-02-25 22:38:04 +00002090};
2091
2092static void
2093defdict_dealloc(defdictobject *dd)
2094{
INADA Naokia6296d32017-08-24 14:55:17 +09002095 /* bpo-31095: UnTrack is needed before calling any callbacks */
2096 PyObject_GC_UnTrack(dd);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002097 Py_CLEAR(dd->default_factory);
2098 PyDict_Type.tp_dealloc((PyObject *)dd);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002099}
2100
Guido van Rossum1968ad32006-02-25 22:38:04 +00002101static PyObject *
2102defdict_repr(defdictobject *dd)
2103{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002104 PyObject *baserepr;
2105 PyObject *defrepr;
2106 PyObject *result;
2107 baserepr = PyDict_Type.tp_repr((PyObject *)dd);
2108 if (baserepr == NULL)
2109 return NULL;
2110 if (dd->default_factory == NULL)
2111 defrepr = PyUnicode_FromString("None");
2112 else
2113 {
2114 int status = Py_ReprEnter(dd->default_factory);
2115 if (status != 0) {
Antoine Pitrouf5f1fe02012-02-15 02:42:46 +01002116 if (status < 0) {
2117 Py_DECREF(baserepr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002118 return NULL;
Antoine Pitrouf5f1fe02012-02-15 02:42:46 +01002119 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002120 defrepr = PyUnicode_FromString("...");
2121 }
2122 else
2123 defrepr = PyObject_Repr(dd->default_factory);
2124 Py_ReprLeave(dd->default_factory);
2125 }
2126 if (defrepr == NULL) {
2127 Py_DECREF(baserepr);
2128 return NULL;
2129 }
2130 result = PyUnicode_FromFormat("defaultdict(%U, %U)",
2131 defrepr, baserepr);
2132 Py_DECREF(defrepr);
2133 Py_DECREF(baserepr);
2134 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00002135}
2136
2137static int
2138defdict_traverse(PyObject *self, visitproc visit, void *arg)
2139{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002140 Py_VISIT(((defdictobject *)self)->default_factory);
2141 return PyDict_Type.tp_traverse(self, visit, arg);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002142}
2143
2144static int
2145defdict_tp_clear(defdictobject *dd)
2146{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002147 Py_CLEAR(dd->default_factory);
2148 return PyDict_Type.tp_clear((PyObject *)dd);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002149}
2150
2151static int
2152defdict_init(PyObject *self, PyObject *args, PyObject *kwds)
2153{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002154 defdictobject *dd = (defdictobject *)self;
2155 PyObject *olddefault = dd->default_factory;
2156 PyObject *newdefault = NULL;
2157 PyObject *newargs;
2158 int result;
2159 if (args == NULL || !PyTuple_Check(args))
2160 newargs = PyTuple_New(0);
2161 else {
2162 Py_ssize_t n = PyTuple_GET_SIZE(args);
2163 if (n > 0) {
2164 newdefault = PyTuple_GET_ITEM(args, 0);
2165 if (!PyCallable_Check(newdefault) && newdefault != Py_None) {
2166 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger239aba72015-07-20 03:09:22 -04002167 "first argument must be callable or None");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002168 return -1;
2169 }
2170 }
2171 newargs = PySequence_GetSlice(args, 1, n);
2172 }
2173 if (newargs == NULL)
2174 return -1;
2175 Py_XINCREF(newdefault);
2176 dd->default_factory = newdefault;
2177 result = PyDict_Type.tp_init(self, newargs, kwds);
2178 Py_DECREF(newargs);
2179 Py_XDECREF(olddefault);
2180 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00002181}
2182
2183PyDoc_STRVAR(defdict_doc,
Benjamin Peterson9cb33b72014-01-13 23:56:05 -05002184"defaultdict(default_factory[, ...]) --> dict with default factory\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00002185\n\
2186The default factory is called without arguments to produce\n\
2187a new value when a key is not present, in __getitem__ only.\n\
2188A defaultdict compares equal to a dict with the same items.\n\
Benjamin Peterson9cb33b72014-01-13 23:56:05 -05002189All remaining arguments are treated the same as if they were\n\
2190passed to the dict constructor, including keyword arguments.\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00002191");
2192
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002193/* See comment in xxsubtype.c */
2194#define DEFERRED_ADDRESS(ADDR) 0
2195
Guido van Rossum1968ad32006-02-25 22:38:04 +00002196static PyTypeObject defdict_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002197 PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0)
2198 "collections.defaultdict", /* tp_name */
2199 sizeof(defdictobject), /* tp_basicsize */
2200 0, /* tp_itemsize */
2201 /* methods */
2202 (destructor)defdict_dealloc, /* tp_dealloc */
2203 0, /* tp_print */
2204 0, /* tp_getattr */
2205 0, /* tp_setattr */
2206 0, /* tp_reserved */
2207 (reprfunc)defdict_repr, /* tp_repr */
2208 0, /* tp_as_number */
2209 0, /* tp_as_sequence */
2210 0, /* tp_as_mapping */
2211 0, /* tp_hash */
2212 0, /* tp_call */
2213 0, /* tp_str */
2214 PyObject_GenericGetAttr, /* tp_getattro */
2215 0, /* tp_setattro */
2216 0, /* tp_as_buffer */
2217 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
2218 /* tp_flags */
2219 defdict_doc, /* tp_doc */
2220 defdict_traverse, /* tp_traverse */
2221 (inquiry)defdict_tp_clear, /* tp_clear */
2222 0, /* tp_richcompare */
2223 0, /* tp_weaklistoffset*/
2224 0, /* tp_iter */
2225 0, /* tp_iternext */
2226 defdict_methods, /* tp_methods */
2227 defdict_members, /* tp_members */
2228 0, /* tp_getset */
2229 DEFERRED_ADDRESS(&PyDict_Type), /* tp_base */
2230 0, /* tp_dict */
2231 0, /* tp_descr_get */
2232 0, /* tp_descr_set */
2233 0, /* tp_dictoffset */
2234 defdict_init, /* tp_init */
2235 PyType_GenericAlloc, /* tp_alloc */
2236 0, /* tp_new */
2237 PyObject_GC_Del, /* tp_free */
Guido van Rossum1968ad32006-02-25 22:38:04 +00002238};
2239
Raymond Hettinger96f34102010-12-15 16:30:37 +00002240/* helper function for Counter *********************************************/
2241
2242PyDoc_STRVAR(_count_elements_doc,
2243"_count_elements(mapping, iterable) -> None\n\
2244\n\
Raymond Hettingera24dca62017-01-12 22:25:25 -08002245Count elements in the iterable, updating the mapping");
Raymond Hettinger96f34102010-12-15 16:30:37 +00002246
2247static PyObject *
2248_count_elements(PyObject *self, PyObject *args)
2249{
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002250 _Py_IDENTIFIER(get);
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002251 _Py_IDENTIFIER(__setitem__);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002252 PyObject *it, *iterable, *mapping, *oldval;
2253 PyObject *newval = NULL;
2254 PyObject *key = NULL;
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002255 PyObject *bound_get = NULL;
2256 PyObject *mapping_get;
2257 PyObject *dict_get;
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002258 PyObject *mapping_setitem;
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002259 PyObject *dict_setitem;
Raymond Hettinger96f34102010-12-15 16:30:37 +00002260
2261 if (!PyArg_UnpackTuple(args, "_count_elements", 2, 2, &mapping, &iterable))
2262 return NULL;
2263
Raymond Hettinger96f34102010-12-15 16:30:37 +00002264 it = PyObject_GetIter(iterable);
2265 if (it == NULL)
2266 return NULL;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002267
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002268 /* Only take the fast path when get() and __setitem__()
2269 * have not been overridden.
2270 */
2271 mapping_get = _PyType_LookupId(Py_TYPE(mapping), &PyId_get);
2272 dict_get = _PyType_LookupId(&PyDict_Type, &PyId_get);
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002273 mapping_setitem = _PyType_LookupId(Py_TYPE(mapping), &PyId___setitem__);
2274 dict_setitem = _PyType_LookupId(&PyDict_Type, &PyId___setitem__);
2275
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002276 if (mapping_get != NULL && mapping_get == dict_get &&
2277 mapping_setitem != NULL && mapping_setitem == dict_setitem) {
Raymond Hettinger426e0522011-01-03 02:12:02 +00002278 while (1) {
Raymond Hettinger507d9972014-05-18 21:32:40 +01002279 /* Fast path advantages:
2280 1. Eliminate double hashing
2281 (by re-using the same hash for both the get and set)
2282 2. Avoid argument overhead of PyObject_CallFunctionObjArgs
2283 (argument tuple creation and parsing)
2284 3. Avoid indirection through a bound method object
2285 (creates another argument tuple)
2286 4. Avoid initial increment from zero
2287 (reuse an existing one-object instead)
2288 */
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002289 Py_hash_t hash;
2290
Raymond Hettinger426e0522011-01-03 02:12:02 +00002291 key = PyIter_Next(it);
Victor Stinnera154b5c2011-04-20 23:23:52 +02002292 if (key == NULL)
2293 break;
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002294
2295 if (!PyUnicode_CheckExact(key) ||
2296 (hash = ((PyASCIIObject *) key)->hash) == -1)
2297 {
2298 hash = PyObject_Hash(key);
Raymond Hettingerda2850f2015-02-27 12:42:54 -08002299 if (hash == -1)
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002300 goto done;
2301 }
2302
2303 oldval = _PyDict_GetItem_KnownHash(mapping, key, hash);
Raymond Hettinger426e0522011-01-03 02:12:02 +00002304 if (oldval == NULL) {
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02002305 if (PyErr_Occurred())
2306 goto done;
Serhiy Storchakaba85d692017-03-30 09:09:41 +03002307 if (_PyDict_SetItem_KnownHash(mapping, key, _PyLong_One, hash) < 0)
Raymond Hettinger507d9972014-05-18 21:32:40 +01002308 goto done;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002309 } else {
Serhiy Storchakaba85d692017-03-30 09:09:41 +03002310 newval = PyNumber_Add(oldval, _PyLong_One);
Raymond Hettinger426e0522011-01-03 02:12:02 +00002311 if (newval == NULL)
Raymond Hettinger507d9972014-05-18 21:32:40 +01002312 goto done;
Raymond Hettinger28c995d2015-08-14 02:07:41 -07002313 if (_PyDict_SetItem_KnownHash(mapping, key, newval, hash) < 0)
Raymond Hettinger507d9972014-05-18 21:32:40 +01002314 goto done;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002315 Py_CLEAR(newval);
2316 }
2317 Py_DECREF(key);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002318 }
Raymond Hettinger426e0522011-01-03 02:12:02 +00002319 } else {
Victor Stinnere7f516c2013-11-06 23:52:55 +01002320 bound_get = _PyObject_GetAttrId(mapping, &PyId_get);
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002321 if (bound_get == NULL)
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002322 goto done;
2323
Raymond Hettinger426e0522011-01-03 02:12:02 +00002324 while (1) {
2325 key = PyIter_Next(it);
Victor Stinnera154b5c2011-04-20 23:23:52 +02002326 if (key == NULL)
2327 break;
Serhiy Storchakaba85d692017-03-30 09:09:41 +03002328 oldval = PyObject_CallFunctionObjArgs(bound_get, key, _PyLong_Zero, NULL);
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002329 if (oldval == NULL)
2330 break;
Serhiy Storchakaba85d692017-03-30 09:09:41 +03002331 newval = PyNumber_Add(oldval, _PyLong_One);
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002332 Py_DECREF(oldval);
2333 if (newval == NULL)
2334 break;
Raymond Hettinger28c995d2015-08-14 02:07:41 -07002335 if (PyObject_SetItem(mapping, key, newval) < 0)
Raymond Hettinger96f34102010-12-15 16:30:37 +00002336 break;
2337 Py_CLEAR(newval);
Raymond Hettinger426e0522011-01-03 02:12:02 +00002338 Py_DECREF(key);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002339 }
Raymond Hettinger96f34102010-12-15 16:30:37 +00002340 }
Raymond Hettinger426e0522011-01-03 02:12:02 +00002341
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002342done:
Raymond Hettinger96f34102010-12-15 16:30:37 +00002343 Py_DECREF(it);
2344 Py_XDECREF(key);
2345 Py_XDECREF(newval);
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002346 Py_XDECREF(bound_get);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002347 if (PyErr_Occurred())
2348 return NULL;
2349 Py_RETURN_NONE;
2350}
2351
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002352/* module level code ********************************************************/
2353
2354PyDoc_STRVAR(module_doc,
Guido van Rossum1968ad32006-02-25 22:38:04 +00002355"High performance data structures.\n\
2356- deque: ordered collection accessible from endpoints only\n\
2357- defaultdict: dict subclass with a default value factory\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002358");
2359
Raymond Hettinger96f34102010-12-15 16:30:37 +00002360static struct PyMethodDef module_functions[] = {
2361 {"_count_elements", _count_elements, METH_VARARGS, _count_elements_doc},
2362 {NULL, NULL} /* sentinel */
2363};
Martin v. Löwis1a214512008-06-11 05:26:20 +00002364
2365static struct PyModuleDef _collectionsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002366 PyModuleDef_HEAD_INIT,
2367 "_collections",
2368 module_doc,
2369 -1,
Raymond Hettinger96f34102010-12-15 16:30:37 +00002370 module_functions,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002371 NULL,
2372 NULL,
2373 NULL,
2374 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002375};
2376
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002377PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002378PyInit__collections(void)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002379{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002380 PyObject *m;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002382 m = PyModule_Create(&_collectionsmodule);
2383 if (m == NULL)
2384 return NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002386 if (PyType_Ready(&deque_type) < 0)
2387 return NULL;
2388 Py_INCREF(&deque_type);
2389 PyModule_AddObject(m, "deque", (PyObject *)&deque_type);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002391 defdict_type.tp_base = &PyDict_Type;
2392 if (PyType_Ready(&defdict_type) < 0)
2393 return NULL;
2394 Py_INCREF(&defdict_type);
2395 PyModule_AddObject(m, "defaultdict", (PyObject *)&defdict_type);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002396
Eric Snow47db7172015-05-29 22:21:39 -06002397 Py_INCREF(&PyODict_Type);
2398 PyModule_AddObject(m, "OrderedDict", (PyObject *)&PyODict_Type);
2399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002400 if (PyType_Ready(&dequeiter_type) < 0)
2401 return NULL;
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002402 Py_INCREF(&dequeiter_type);
2403 PyModule_AddObject(m, "_deque_iterator", (PyObject *)&dequeiter_type);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002405 if (PyType_Ready(&dequereviter_type) < 0)
2406 return NULL;
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002407 Py_INCREF(&dequereviter_type);
2408 PyModule_AddObject(m, "_deque_reverse_iterator", (PyObject *)&dequereviter_type);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00002409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002410 return m;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002411}