blob: ac81680e1bd7101945bbea82e3756a5832660b58 [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 Hettinger30c90742015-03-02 22:31:35 -080084 Py_ssize_t maxlen;
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
Raymond Hettinger41290a62015-03-31 08:12:23 -0700111/* To prevent len from overflowing PY_SSIZE_T_MAX, we refuse to
112 allocate new blocks if the current len is nearing overflow.
113*/
114
115#define MAX_DEQUE_LEN (PY_SSIZE_T_MAX - 3*BLOCKLEN)
116
Raymond Hettinger82df9252013-07-07 01:43:42 -1000117/* A simple freelisting scheme is used to minimize calls to the memory
Raymond Hettinger551350a2015-03-24 00:19:53 -0700118 allocator. It accommodates common use cases where new blocks are being
Raymond Hettinger82df9252013-07-07 01:43:42 -1000119 added at about the same rate as old blocks are being freed.
120 */
121
Guido van Rossum58da9312007-11-10 23:39:45 +0000122#define MAXFREEBLOCKS 10
Benjamin Petersond6313712008-07-31 16:23:04 +0000123static Py_ssize_t numfreeblocks = 0;
Guido van Rossum58da9312007-11-10 23:39:45 +0000124static block *freeblocks[MAXFREEBLOCKS];
125
Tim Peters6f853562004-10-01 01:04:50 +0000126static block *
Raymond Hettinger82df9252013-07-07 01:43:42 -1000127newblock(Py_ssize_t len) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000128 block *b;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700129 if (len >= MAX_DEQUE_LEN) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000130 PyErr_SetString(PyExc_OverflowError,
131 "cannot add more blocks to the deque");
132 return NULL;
133 }
134 if (numfreeblocks) {
Raymond Hettinger59cf23a2013-02-07 00:57:19 -0500135 numfreeblocks--;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000136 return freeblocks[numfreeblocks];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000137 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000138 b = PyMem_Malloc(sizeof(block));
139 if (b != NULL) {
140 return b;
141 }
142 PyErr_NoMemory();
143 return NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000144}
145
Martin v. Löwis59683e82008-06-13 07:50:45 +0000146static void
Guido van Rossum58da9312007-11-10 23:39:45 +0000147freeblock(block *b)
148{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000149 if (numfreeblocks < MAXFREEBLOCKS) {
150 freeblocks[numfreeblocks] = b;
151 numfreeblocks++;
152 } else {
153 PyMem_Free(b);
154 }
Guido van Rossum58da9312007-11-10 23:39:45 +0000155}
156
Raymond Hettingerda2850f2015-02-27 12:42:54 -0800157/* XXX Todo:
Raymond Hettinger54023152014-04-23 00:58:48 -0700158 If aligned memory allocations become available, make the
159 deque object 64 byte aligned so that all of the fields
160 can be retrieved or updated in a single cache line.
161*/
162
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000163static PyObject *
164deque_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
165{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000166 dequeobject *deque;
167 block *b;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000169 /* create dequeobject structure */
170 deque = (dequeobject *)type->tp_alloc(type, 0);
171 if (deque == NULL)
172 return NULL;
Tim Peters1065f752004-10-01 01:03:29 +0000173
Raymond Hettinger82df9252013-07-07 01:43:42 -1000174 b = newblock(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175 if (b == NULL) {
176 Py_DECREF(deque);
177 return NULL;
178 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000179 MARK_END(b->leftlink);
180 MARK_END(b->rightlink);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000182 assert(BLOCKLEN >= 2);
Raymond Hettinger87e69122015-03-02 23:32:02 -0800183 Py_SIZE(deque) = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000184 deque->leftblock = b;
185 deque->rightblock = b;
186 deque->leftindex = CENTER + 1;
187 deque->rightindex = CENTER;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000188 deque->state = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000189 deque->maxlen = -1;
Raymond Hettinger87e69122015-03-02 23:32:02 -0800190 deque->weakreflist = NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000192 return (PyObject *)deque;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000193}
194
195static PyObject *
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000196deque_pop(dequeobject *deque, PyObject *unused)
197{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000198 PyObject *item;
199 block *prevblock;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000200
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000201 if (Py_SIZE(deque) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000202 PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
203 return NULL;
204 }
205 item = deque->rightblock->data[deque->rightindex];
206 deque->rightindex--;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000207 Py_SIZE(deque)--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000208 deque->state++;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000210 if (deque->rightindex == -1) {
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700211 if (Py_SIZE(deque)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000212 prevblock = deque->rightblock->leftlink;
213 assert(deque->leftblock != deque->rightblock);
214 freeblock(deque->rightblock);
Raymond Hettinger82df9252013-07-07 01:43:42 -1000215 CHECK_NOT_END(prevblock);
216 MARK_END(prevblock->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000217 deque->rightblock = prevblock;
218 deque->rightindex = BLOCKLEN - 1;
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700219 } else {
220 assert(deque->leftblock == deque->rightblock);
221 assert(deque->leftindex == deque->rightindex+1);
222 /* re-center instead of freeing a block */
223 deque->leftindex = CENTER + 1;
224 deque->rightindex = CENTER;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000225 }
226 }
227 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000228}
229
230PyDoc_STRVAR(pop_doc, "Remove and return the rightmost element.");
231
232static PyObject *
233deque_popleft(dequeobject *deque, PyObject *unused)
234{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000235 PyObject *item;
236 block *prevblock;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000237
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000238 if (Py_SIZE(deque) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000239 PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
240 return NULL;
241 }
242 assert(deque->leftblock != NULL);
243 item = deque->leftblock->data[deque->leftindex];
244 deque->leftindex++;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000245 Py_SIZE(deque)--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000246 deque->state++;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000248 if (deque->leftindex == BLOCKLEN) {
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700249 if (Py_SIZE(deque)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000250 assert(deque->leftblock != deque->rightblock);
251 prevblock = deque->leftblock->rightlink;
252 freeblock(deque->leftblock);
Raymond Hettinger82df9252013-07-07 01:43:42 -1000253 CHECK_NOT_END(prevblock);
254 MARK_END(prevblock->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000255 deque->leftblock = prevblock;
256 deque->leftindex = 0;
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700257 } else {
258 assert(deque->leftblock == deque->rightblock);
259 assert(deque->leftindex == deque->rightindex+1);
260 /* re-center instead of freeing a block */
261 deque->leftindex = CENTER + 1;
262 deque->rightindex = CENTER;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000263 }
264 }
265 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000266}
267
268PyDoc_STRVAR(popleft_doc, "Remove and return the leftmost element.");
269
Raymond Hettingerf30f5b92015-03-02 22:23:37 -0800270/* The deque's size limit is d.maxlen. The limit can be zero or positive.
271 * If there is no limit, then d.maxlen == -1.
272 *
273 * After an item is added to a deque, we check to see if the size has grown past
274 * the limit. If it has, we get the size back down to the limit by popping an
275 * item off of the opposite end. The methods that can trigger this are append(),
276 * appendleft(), extend(), and extendleft().
277 */
278
279static void
280deque_trim_right(dequeobject *deque)
281{
282 if (deque->maxlen != -1 && Py_SIZE(deque) > deque->maxlen) {
283 PyObject *rv = deque_pop(deque, NULL);
284 assert(rv != NULL);
285 assert(Py_SIZE(deque) <= deque->maxlen);
286 Py_DECREF(rv);
287 }
288}
289
290static void
291deque_trim_left(dequeobject *deque)
292{
293 if (deque->maxlen != -1 && Py_SIZE(deque) > deque->maxlen) {
294 PyObject *rv = deque_popleft(deque, NULL);
295 assert(rv != NULL);
296 assert(Py_SIZE(deque) <= deque->maxlen);
297 Py_DECREF(rv);
298 }
299}
300
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000301static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000302deque_append(dequeobject *deque, PyObject *item)
303{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000304 deque->state++;
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700305 if (deque->rightindex == BLOCKLEN - 1) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000306 block *b = newblock(Py_SIZE(deque));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000307 if (b == NULL)
308 return NULL;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000309 b->leftlink = deque->rightblock;
310 CHECK_END(deque->rightblock->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000311 deque->rightblock->rightlink = b;
312 deque->rightblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000313 MARK_END(b->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000314 deque->rightindex = -1;
315 }
316 Py_INCREF(item);
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000317 Py_SIZE(deque)++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000318 deque->rightindex++;
319 deque->rightblock->data[deque->rightindex] = item;
Raymond Hettingerf30f5b92015-03-02 22:23:37 -0800320 deque_trim_left(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000321 Py_RETURN_NONE;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000322}
323
324PyDoc_STRVAR(append_doc, "Add an element to the right side of the deque.");
325
326static PyObject *
327deque_appendleft(dequeobject *deque, PyObject *item)
328{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000329 deque->state++;
330 if (deque->leftindex == 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000331 block *b = newblock(Py_SIZE(deque));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000332 if (b == NULL)
333 return NULL;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000334 b->rightlink = deque->leftblock;
335 CHECK_END(deque->leftblock->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000336 deque->leftblock->leftlink = b;
337 deque->leftblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000338 MARK_END(b->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000339 deque->leftindex = BLOCKLEN;
340 }
341 Py_INCREF(item);
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000342 Py_SIZE(deque)++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000343 deque->leftindex--;
344 deque->leftblock->data[deque->leftindex] = item;
Raymond Hettingerf30f5b92015-03-02 22:23:37 -0800345 deque_trim_right(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000346 Py_RETURN_NONE;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000347}
348
349PyDoc_STRVAR(appendleft_doc, "Add an element to the left side of the deque.");
350
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000352/* Run an iterator to exhaustion. Shortcut for
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000353 the extend/extendleft methods when maxlen == 0. */
354static PyObject*
355consume_iterator(PyObject *it)
356{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000357 PyObject *item;
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000359 while ((item = PyIter_Next(it)) != NULL) {
360 Py_DECREF(item);
361 }
362 Py_DECREF(it);
363 if (PyErr_Occurred())
364 return NULL;
365 Py_RETURN_NONE;
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000366}
367
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000368static PyObject *
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000369deque_extend(dequeobject *deque, PyObject *iterable)
370{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000371 PyObject *it, *item;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000373 /* Handle case where id(deque) == id(iterable) */
374 if ((PyObject *)deque == iterable) {
375 PyObject *result;
376 PyObject *s = PySequence_List(iterable);
377 if (s == NULL)
378 return NULL;
379 result = deque_extend(deque, s);
380 Py_DECREF(s);
381 return result;
382 }
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000383
Raymond Hettingerd9c116c2013-07-09 00:13:21 -0700384 /* Space saving heuristic. Start filling from the left */
385 if (Py_SIZE(deque) == 0) {
386 assert(deque->leftblock == deque->rightblock);
387 assert(deque->leftindex == deque->rightindex+1);
388 deque->leftindex = 1;
389 deque->rightindex = 0;
390 }
391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000392 it = PyObject_GetIter(iterable);
393 if (it == NULL)
394 return NULL;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000396 if (deque->maxlen == 0)
397 return consume_iterator(it);
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000399 while ((item = PyIter_Next(it)) != NULL) {
400 deque->state++;
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700401 if (deque->rightindex == BLOCKLEN - 1) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000402 block *b = newblock(Py_SIZE(deque));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000403 if (b == NULL) {
404 Py_DECREF(item);
405 Py_DECREF(it);
406 return NULL;
407 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000408 b->leftlink = deque->rightblock;
409 CHECK_END(deque->rightblock->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000410 deque->rightblock->rightlink = b;
411 deque->rightblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000412 MARK_END(b->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000413 deque->rightindex = -1;
414 }
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000415 Py_SIZE(deque)++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000416 deque->rightindex++;
417 deque->rightblock->data[deque->rightindex] = item;
Raymond Hettingerf30f5b92015-03-02 22:23:37 -0800418 deque_trim_left(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000419 }
Raymond Hettinger2b2b7532015-09-05 17:05:52 -0700420 if (PyErr_Occurred()) {
421 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000422 return NULL;
Raymond Hettinger2b2b7532015-09-05 17:05:52 -0700423 }
424 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425 Py_RETURN_NONE;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000426}
427
Tim Peters1065f752004-10-01 01:03:29 +0000428PyDoc_STRVAR(extend_doc,
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000429"Extend the right side of the deque with elements from the iterable");
430
431static PyObject *
432deque_extendleft(dequeobject *deque, PyObject *iterable)
433{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000434 PyObject *it, *item;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000436 /* Handle case where id(deque) == id(iterable) */
437 if ((PyObject *)deque == iterable) {
438 PyObject *result;
439 PyObject *s = PySequence_List(iterable);
440 if (s == NULL)
441 return NULL;
442 result = deque_extendleft(deque, s);
443 Py_DECREF(s);
444 return result;
445 }
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000446
Raymond Hettingerd9c116c2013-07-09 00:13:21 -0700447 /* Space saving heuristic. Start filling from the right */
448 if (Py_SIZE(deque) == 0) {
449 assert(deque->leftblock == deque->rightblock);
450 assert(deque->leftindex == deque->rightindex+1);
451 deque->leftindex = BLOCKLEN - 1;
452 deque->rightindex = BLOCKLEN - 2;
453 }
454
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000455 it = PyObject_GetIter(iterable);
456 if (it == NULL)
457 return NULL;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000458
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000459 if (deque->maxlen == 0)
460 return consume_iterator(it);
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000462 while ((item = PyIter_Next(it)) != NULL) {
463 deque->state++;
464 if (deque->leftindex == 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000465 block *b = newblock(Py_SIZE(deque));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000466 if (b == NULL) {
467 Py_DECREF(item);
468 Py_DECREF(it);
469 return NULL;
470 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000471 b->rightlink = deque->leftblock;
472 CHECK_END(deque->leftblock->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000473 deque->leftblock->leftlink = b;
474 deque->leftblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000475 MARK_END(b->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 deque->leftindex = BLOCKLEN;
477 }
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000478 Py_SIZE(deque)++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 deque->leftindex--;
480 deque->leftblock->data[deque->leftindex] = item;
Raymond Hettingerf30f5b92015-03-02 22:23:37 -0800481 deque_trim_right(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 }
Raymond Hettinger2b2b7532015-09-05 17:05:52 -0700483 if (PyErr_Occurred()) {
484 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 return NULL;
Raymond Hettinger2b2b7532015-09-05 17:05:52 -0700486 }
487 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 Py_RETURN_NONE;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000489}
490
Tim Peters1065f752004-10-01 01:03:29 +0000491PyDoc_STRVAR(extendleft_doc,
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000492"Extend the left side of the deque with elements from the iterable");
493
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000494static PyObject *
495deque_inplace_concat(dequeobject *deque, PyObject *other)
496{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 PyObject *result;
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000499 result = deque_extend(deque, other);
500 if (result == NULL)
501 return result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 Py_INCREF(deque);
Raymond Hettinger2b2b7532015-09-05 17:05:52 -0700503 Py_DECREF(result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 return (PyObject *)deque;
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000505}
506
Raymond Hettinger41290a62015-03-31 08:12:23 -0700507static PyObject *deque_copy(PyObject *deque);
508
509static PyObject *
510deque_concat(dequeobject *deque, PyObject *other)
511{
Benjamin Peterson1a629212015-04-04 10:52:36 -0400512 PyObject *new_deque, *result;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700513 int rv;
514
515 rv = PyObject_IsInstance(other, (PyObject *)&deque_type);
516 if (rv <= 0) {
517 if (rv == 0) {
518 PyErr_Format(PyExc_TypeError,
519 "can only concatenate deque (not \"%.200s\") to deque",
520 other->ob_type->tp_name);
521 }
522 return NULL;
523 }
524
525 new_deque = deque_copy((PyObject *)deque);
526 if (new_deque == NULL)
527 return NULL;
Benjamin Peterson1a629212015-04-04 10:52:36 -0400528 result = deque_extend((dequeobject *)new_deque, other);
529 if (result == NULL) {
530 Py_DECREF(new_deque);
531 return NULL;
532 }
533 Py_DECREF(result);
534 return new_deque;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700535}
536
537static void deque_clear(dequeobject *deque);
538
539static PyObject *
540deque_repeat(dequeobject *deque, Py_ssize_t n)
541{
542 dequeobject *new_deque;
543 PyObject *result;
544
545 /* XXX add a special case for when maxlen is defined */
546 if (n < 0)
547 n = 0;
548 else if (n > 0 && Py_SIZE(deque) > MAX_DEQUE_LEN / n)
549 return PyErr_NoMemory();
550
551 new_deque = (dequeobject *)deque_new(&deque_type, (PyObject *)NULL, (PyObject *)NULL);
552 new_deque->maxlen = deque->maxlen;
553
554 for ( ; n ; n--) {
555 result = deque_extend(new_deque, (PyObject *)deque);
556 if (result == NULL) {
557 Py_DECREF(new_deque);
558 return NULL;
559 }
560 Py_DECREF(result);
561 }
562 return (PyObject *)new_deque;
563}
564
565static PyObject *
566deque_inplace_repeat(dequeobject *deque, Py_ssize_t n)
567{
568 Py_ssize_t i, size;
569 PyObject *seq;
570 PyObject *rv;
571
572 size = Py_SIZE(deque);
573 if (size == 0 || n == 1) {
574 Py_INCREF(deque);
575 return (PyObject *)deque;
576 }
577
578 if (n <= 0) {
579 deque_clear(deque);
580 Py_INCREF(deque);
581 return (PyObject *)deque;
582 }
583
584 if (size > MAX_DEQUE_LEN / n) {
585 return PyErr_NoMemory();
586 }
587
588 if (size == 1) {
589 /* common case, repeating a single element */
590 PyObject *item = deque->leftblock->data[deque->leftindex];
591
592 if (deque->maxlen != -1 && n > deque->maxlen)
593 n = deque->maxlen;
594
595 for (i = 0 ; i < n-1 ; i++) {
596 rv = deque_append(deque, item);
597 if (rv == NULL)
598 return NULL;
599 Py_DECREF(rv);
600 }
601 Py_INCREF(deque);
602 return (PyObject *)deque;
603 }
604
605 seq = PySequence_List((PyObject *)deque);
606 if (seq == NULL)
607 return seq;
608
609 for (i = 0 ; i < n-1 ; i++) {
610 rv = deque_extend(deque, seq);
611 if (rv == NULL) {
612 Py_DECREF(seq);
613 return NULL;
614 }
615 Py_DECREF(rv);
616 }
617 Py_INCREF(deque);
618 Py_DECREF(seq);
619 return (PyObject *)deque;
620}
621
Raymond Hettinger54023152014-04-23 00:58:48 -0700622/* The rotate() method is part of the public API and is used internally
623as a primitive for other methods.
624
625Rotation by 1 or -1 is a common case, so any optimizations for high
626volume rotations should take care not to penalize the common case.
627
628Conceptually, a rotate by one is equivalent to a pop on one side and an
629append on the other. However, a pop/append pair is unnecessarily slow
Martin Panterd2ad5712015-11-02 04:20:33 +0000630because it requires an incref/decref pair for an object located randomly
Raymond Hettinger54023152014-04-23 00:58:48 -0700631in memory. It is better to just move the object pointer from one block
632to the next without changing the reference count.
633
634When moving batches of pointers, it is tempting to use memcpy() but that
635proved to be slower than a simple loop for a variety of reasons.
636Memcpy() cannot know in advance that we're copying pointers instead of
637bytes, that the source and destination are pointer aligned and
638non-overlapping, that moving just one pointer is a common case, that we
639never need to move more than BLOCKLEN pointers, and that at least one
640pointer is always moved.
641
642For high volume rotations, newblock() and freeblock() are never called
643more than once. Previously emptied blocks are immediately reused as a
644destination block. If a block is left-over at the end, it is freed.
645*/
646
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000647static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000648_deque_rotate(dequeobject *deque, Py_ssize_t n)
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000649{
Raymond Hettinger3959af92013-07-13 02:34:08 -0700650 block *b = NULL;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700651 block *leftblock = deque->leftblock;
652 block *rightblock = deque->rightblock;
653 Py_ssize_t leftindex = deque->leftindex;
654 Py_ssize_t rightindex = deque->rightindex;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000655 Py_ssize_t len=Py_SIZE(deque), halflen=len>>1;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700656 int rv = -1;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000657
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800658 if (len <= 1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000659 return 0;
660 if (n > halflen || n < -halflen) {
661 n %= len;
662 if (n > halflen)
663 n -= len;
664 else if (n < -halflen)
665 n += len;
666 }
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500667 assert(len > 1);
Raymond Hettingera4409c12013-02-04 00:08:12 -0500668 assert(-halflen <= n && n <= halflen);
Raymond Hettinger231ee4d2013-02-02 11:24:43 -0800669
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800670 deque->state++;
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500671 while (n > 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700672 if (leftindex == 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700673 if (b == NULL) {
Raymond Hettinger3959af92013-07-13 02:34:08 -0700674 b = newblock(len);
675 if (b == NULL)
676 goto done;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700677 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000678 b->rightlink = leftblock;
679 CHECK_END(leftblock->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700680 leftblock->leftlink = b;
681 leftblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000682 MARK_END(b->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700683 leftindex = BLOCKLEN;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700684 b = NULL;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800685 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700686 assert(leftindex > 0);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700687 {
688 PyObject **src, **dest;
689 Py_ssize_t m = n;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800690
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700691 if (m > rightindex + 1)
692 m = rightindex + 1;
693 if (m > leftindex)
694 m = leftindex;
695 assert (m > 0 && m <= len);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700696 rightindex -= m;
697 leftindex -= m;
Raymond Hettinger0e259f12015-02-01 22:53:41 -0800698 src = &rightblock->data[rightindex + 1];
699 dest = &leftblock->data[leftindex];
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700700 n -= m;
Raymond Hettinger840533b2013-07-13 17:03:58 -0700701 do {
Raymond Hettinger0e259f12015-02-01 22:53:41 -0800702 *(dest++) = *(src++);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700703 } while (--m);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700704 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700705 if (rightindex == -1) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700706 assert(leftblock != rightblock);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700707 assert(b == NULL);
Raymond Hettinger3959af92013-07-13 02:34:08 -0700708 b = rightblock;
Raymond Hettingerb97cc492013-07-21 01:51:07 -0700709 CHECK_NOT_END(rightblock->leftlink);
710 rightblock = rightblock->leftlink;
711 MARK_END(rightblock->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700712 rightindex = BLOCKLEN - 1;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800713 }
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800714 }
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500715 while (n < 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700716 if (rightindex == BLOCKLEN - 1) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700717 if (b == NULL) {
Raymond Hettinger3959af92013-07-13 02:34:08 -0700718 b = newblock(len);
719 if (b == NULL)
720 goto done;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700721 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000722 b->leftlink = rightblock;
723 CHECK_END(rightblock->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700724 rightblock->rightlink = b;
725 rightblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000726 MARK_END(b->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700727 rightindex = -1;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700728 b = NULL;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800729 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700730 assert (rightindex < BLOCKLEN - 1);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700731 {
732 PyObject **src, **dest;
733 Py_ssize_t m = -n;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800734
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700735 if (m > BLOCKLEN - leftindex)
736 m = BLOCKLEN - leftindex;
737 if (m > BLOCKLEN - 1 - rightindex)
738 m = BLOCKLEN - 1 - rightindex;
739 assert (m > 0 && m <= len);
740 src = &leftblock->data[leftindex];
741 dest = &rightblock->data[rightindex + 1];
742 leftindex += m;
743 rightindex += m;
744 n += m;
Raymond Hettinger840533b2013-07-13 17:03:58 -0700745 do {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700746 *(dest++) = *(src++);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700747 } while (--m);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700748 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700749 if (leftindex == BLOCKLEN) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700750 assert(leftblock != rightblock);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700751 assert(b == NULL);
Raymond Hettinger3959af92013-07-13 02:34:08 -0700752 b = leftblock;
Raymond Hettingerb97cc492013-07-21 01:51:07 -0700753 CHECK_NOT_END(leftblock->rightlink);
754 leftblock = leftblock->rightlink;
755 MARK_END(leftblock->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700756 leftindex = 0;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800757 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 }
Raymond Hettinger3959af92013-07-13 02:34:08 -0700759 rv = 0;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700760done:
Raymond Hettinger3959af92013-07-13 02:34:08 -0700761 if (b != NULL)
762 freeblock(b);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700763 deque->leftblock = leftblock;
764 deque->rightblock = rightblock;
765 deque->leftindex = leftindex;
766 deque->rightindex = rightindex;
767
768 return rv;
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000769}
770
771static PyObject *
772deque_rotate(dequeobject *deque, PyObject *args)
773{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000774 Py_ssize_t n=1;
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000775
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000776 if (!PyArg_ParseTuple(args, "|n:rotate", &n))
777 return NULL;
Raymond Hettinger6921c132015-03-21 02:03:40 -0700778 if (!_deque_rotate(deque, n))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 Py_RETURN_NONE;
780 return NULL;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000781}
782
Tim Peters1065f752004-10-01 01:03:29 +0000783PyDoc_STRVAR(rotate_doc,
Raymond Hettingeree33b272004-02-08 04:05:26 +0000784"Rotate the deque n steps to the right (default n=1). If n is negative, rotates left.");
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000785
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000786static PyObject *
787deque_reverse(dequeobject *deque, PyObject *unused)
788{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 block *leftblock = deque->leftblock;
790 block *rightblock = deque->rightblock;
791 Py_ssize_t leftindex = deque->leftindex;
792 Py_ssize_t rightindex = deque->rightindex;
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700793 Py_ssize_t n = Py_SIZE(deque) / 2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000794 Py_ssize_t i;
795 PyObject *tmp;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000796
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000797 for (i=0 ; i<n ; i++) {
798 /* Validate that pointers haven't met in the middle */
799 assert(leftblock != rightblock || leftindex < rightindex);
Raymond Hettinger82df9252013-07-07 01:43:42 -1000800 CHECK_NOT_END(leftblock);
801 CHECK_NOT_END(rightblock);
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000802
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 /* Swap */
804 tmp = leftblock->data[leftindex];
805 leftblock->data[leftindex] = rightblock->data[rightindex];
806 rightblock->data[rightindex] = tmp;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 /* Advance left block/index pair */
809 leftindex++;
810 if (leftindex == BLOCKLEN) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000811 leftblock = leftblock->rightlink;
812 leftindex = 0;
813 }
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000814
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000815 /* Step backwards with the right block/index pair */
816 rightindex--;
817 if (rightindex == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000818 rightblock = rightblock->leftlink;
819 rightindex = BLOCKLEN - 1;
820 }
821 }
822 Py_RETURN_NONE;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000823}
824
825PyDoc_STRVAR(reverse_doc,
826"D.reverse() -- reverse *IN PLACE*");
827
Raymond Hettinger44459de2010-04-03 23:20:46 +0000828static PyObject *
829deque_count(dequeobject *deque, PyObject *v)
830{
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000831 block *b = deque->leftblock;
832 Py_ssize_t index = deque->leftindex;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000833 Py_ssize_t n = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000834 Py_ssize_t i;
835 Py_ssize_t count = 0;
Raymond Hettingerf9d9c792015-03-02 22:47:46 -0800836 size_t start_state = deque->state;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000837 PyObject *item;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 int cmp;
Raymond Hettinger44459de2010-04-03 23:20:46 +0000839
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 for (i=0 ; i<n ; i++) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000841 CHECK_NOT_END(b);
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000842 item = b->data[index];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000843 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
844 if (cmp > 0)
845 count++;
846 else if (cmp < 0)
847 return NULL;
Raymond Hettinger44459de2010-04-03 23:20:46 +0000848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 if (start_state != deque->state) {
850 PyErr_SetString(PyExc_RuntimeError,
851 "deque mutated during iteration");
852 return NULL;
853 }
Raymond Hettinger44459de2010-04-03 23:20:46 +0000854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 /* Advance left block/index pair */
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000856 index++;
857 if (index == BLOCKLEN) {
858 b = b->rightlink;
859 index = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000860 }
861 }
862 return PyLong_FromSsize_t(count);
Raymond Hettinger44459de2010-04-03 23:20:46 +0000863}
864
865PyDoc_STRVAR(count_doc,
866"D.count(value) -> integer -- return number of occurrences of value");
867
Raymond Hettinger39dadf72015-03-20 16:38:56 -0700868static int
869deque_contains(dequeobject *deque, PyObject *v)
870{
871 block *b = deque->leftblock;
872 Py_ssize_t index = deque->leftindex;
873 Py_ssize_t n = Py_SIZE(deque);
874 Py_ssize_t i;
875 size_t start_state = deque->state;
876 PyObject *item;
877 int cmp;
878
879 for (i=0 ; i<n ; i++) {
880 CHECK_NOT_END(b);
881 item = b->data[index];
882 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
883 if (cmp) {
884 return cmp;
885 }
886 if (start_state != deque->state) {
887 PyErr_SetString(PyExc_RuntimeError,
888 "deque mutated during iteration");
889 return -1;
890 }
891 index++;
892 if (index == BLOCKLEN) {
893 b = b->rightlink;
894 index = 0;
895 }
896 }
897 return 0;
898}
899
Martin v. Löwis18e16552006-02-15 17:27:45 +0000900static Py_ssize_t
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000901deque_len(dequeobject *deque)
902{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000903 return Py_SIZE(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000904}
905
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000906static PyObject *
Raymond Hettinger32ea1652015-03-21 01:37:37 -0700907deque_index(dequeobject *deque, PyObject *args)
908{
909 Py_ssize_t i, start=0, stop=Py_SIZE(deque);
910 PyObject *v, *item;
911 block *b = deque->leftblock;
912 Py_ssize_t index = deque->leftindex;
913 size_t start_state = deque->state;
914
915 if (!PyArg_ParseTuple(args, "O|O&O&:index", &v,
916 _PyEval_SliceIndex, &start,
917 _PyEval_SliceIndex, &stop))
918 return NULL;
919 if (start < 0) {
920 start += Py_SIZE(deque);
921 if (start < 0)
922 start = 0;
923 }
924 if (stop < 0) {
925 stop += Py_SIZE(deque);
926 if (stop < 0)
927 stop = 0;
928 }
Raymond Hettinger87674ec2015-08-26 08:08:38 -0700929 if (stop > Py_SIZE(deque))
930 stop = Py_SIZE(deque);
Raymond Hettinger32ea1652015-03-21 01:37:37 -0700931
932 for (i=0 ; i<stop ; i++) {
933 if (i >= start) {
934 int cmp;
935 CHECK_NOT_END(b);
936 item = b->data[index];
937 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
938 if (cmp > 0)
939 return PyLong_FromSsize_t(i);
940 else if (cmp < 0)
941 return NULL;
942 if (start_state != deque->state) {
943 PyErr_SetString(PyExc_RuntimeError,
944 "deque mutated during iteration");
945 return NULL;
946 }
947 }
948 index++;
949 if (index == BLOCKLEN) {
950 b = b->rightlink;
951 index = 0;
952 }
953 }
954 PyErr_Format(PyExc_ValueError, "%R is not in deque", v);
955 return NULL;
956}
957
958PyDoc_STRVAR(index_doc,
959"D.index(value, [start, [stop]]) -> integer -- return first index of value.\n"
960"Raises ValueError if the value is not present.");
961
Raymond Hettinger551350a2015-03-24 00:19:53 -0700962/* insert(), remove(), and delitem() are implemented in terms of
963 rotate() for simplicity and reasonable performance near the end
964 points. If for some reason these methods become popular, it is not
965 hard to re-implement this using direct data movement (similar to
966 the code used in list slice assignments) and achieve a performance
Raymond Hettingerfef9c1b2015-03-24 21:12:57 -0700967 boost (by moving each pointer only once instead of twice).
Raymond Hettinger551350a2015-03-24 00:19:53 -0700968*/
969
Raymond Hettinger32ea1652015-03-21 01:37:37 -0700970static PyObject *
971deque_insert(dequeobject *deque, PyObject *args)
972{
973 Py_ssize_t index;
974 Py_ssize_t n = Py_SIZE(deque);
975 PyObject *value;
976 PyObject *rv;
977
978 if (!PyArg_ParseTuple(args, "nO:insert", &index, &value))
979 return NULL;
Raymond Hettinger37434322016-01-26 21:44:16 -0800980 if (deque->maxlen == Py_SIZE(deque)) {
Raymond Hettingerb00da572016-02-01 21:19:22 -0800981 PyErr_SetString(PyExc_IndexError, "deque already at its maximum size");
982 return NULL;
Raymond Hettinger37434322016-01-26 21:44:16 -0800983 }
Raymond Hettinger32ea1652015-03-21 01:37:37 -0700984 if (index >= n)
985 return deque_append(deque, value);
986 if (index <= -n || index == 0)
987 return deque_appendleft(deque, value);
988 if (_deque_rotate(deque, -index))
989 return NULL;
990 if (index < 0)
991 rv = deque_append(deque, value);
992 else
993 rv = deque_appendleft(deque, value);
994 if (rv == NULL)
995 return NULL;
996 Py_DECREF(rv);
997 if (_deque_rotate(deque, index))
998 return NULL;
999 Py_RETURN_NONE;
1000}
1001
1002PyDoc_STRVAR(insert_doc,
1003"D.insert(index, object) -- insert object before index");
1004
1005static PyObject *
Raymond Hettinger4aec61e2005-03-18 21:20:23 +00001006deque_remove(dequeobject *deque, PyObject *value)
1007{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001008 Py_ssize_t i, n=Py_SIZE(deque);
Raymond Hettinger4aec61e2005-03-18 21:20:23 +00001009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001010 for (i=0 ; i<n ; i++) {
1011 PyObject *item = deque->leftblock->data[deque->leftindex];
1012 int cmp = PyObject_RichCompareBool(item, value, Py_EQ);
Raymond Hettingerd73202c2005-03-19 00:00:51 +00001013
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001014 if (Py_SIZE(deque) != n) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 PyErr_SetString(PyExc_IndexError,
1016 "deque mutated during remove().");
1017 return NULL;
1018 }
1019 if (cmp > 0) {
1020 PyObject *tgt = deque_popleft(deque, NULL);
1021 assert (tgt != NULL);
Raymond Hettinger6921c132015-03-21 02:03:40 -07001022 if (_deque_rotate(deque, i))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001023 return NULL;
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001024 Py_DECREF(tgt);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001025 Py_RETURN_NONE;
1026 }
1027 else if (cmp < 0) {
1028 _deque_rotate(deque, i);
1029 return NULL;
1030 }
1031 _deque_rotate(deque, -1);
1032 }
1033 PyErr_SetString(PyExc_ValueError, "deque.remove(x): x not in deque");
1034 return NULL;
Raymond Hettinger4aec61e2005-03-18 21:20:23 +00001035}
1036
1037PyDoc_STRVAR(remove_doc,
1038"D.remove(value) -- remove first occurrence of value.");
1039
Benjamin Peterson0e5c48a2013-01-12 21:22:18 -05001040static void
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001041deque_clear(dequeobject *deque)
1042{
Raymond Hettingerbf49fee2015-09-26 00:14:59 -07001043 block *b;
1044 block *prevblock;
1045 block *leftblock;
1046 Py_ssize_t leftindex;
1047 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 PyObject *item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001049
Raymond Hettinger848f2b52015-10-06 23:06:17 -04001050 if (Py_SIZE(deque) == 0)
1051 return;
1052
Raymond Hettingerbf49fee2015-09-26 00:14:59 -07001053 /* During the process of clearing a deque, decrefs can cause the
1054 deque to mutate. To avoid fatal confusion, we have to make the
1055 deque empty before clearing the blocks and never refer to
1056 anything via deque->ref while clearing. (This is the same
1057 technique used for clearing lists, sets, and dicts.)
1058
1059 Making the deque empty requires allocating a new empty block. In
1060 the unlikely event that memory is full, we fall back to an
1061 alternate method that doesn't require a new block. Repeating
1062 pops in a while-loop is slower, possibly re-entrant (and a clever
1063 adversary could cause it to never terminate).
1064 */
1065
1066 b = newblock(0);
1067 if (b == NULL) {
1068 PyErr_Clear();
1069 goto alternate_method;
1070 }
1071
1072 /* Remember the old size, leftblock, and leftindex */
1073 leftblock = deque->leftblock;
1074 leftindex = deque->leftindex;
1075 n = Py_SIZE(deque);
1076
1077 /* Set the deque to be empty using the newly allocated block */
1078 MARK_END(b->leftlink);
1079 MARK_END(b->rightlink);
1080 Py_SIZE(deque) = 0;
1081 deque->leftblock = b;
1082 deque->rightblock = b;
1083 deque->leftindex = CENTER + 1;
1084 deque->rightindex = CENTER;
1085 deque->state++;
1086
1087 /* Now the old size, leftblock, and leftindex are disconnected from
1088 the empty deque and we can use them to decref the pointers.
1089 */
1090 while (n--) {
1091 item = leftblock->data[leftindex];
1092 Py_DECREF(item);
1093 leftindex++;
1094 if (leftindex == BLOCKLEN && n) {
1095 CHECK_NOT_END(leftblock->rightlink);
1096 prevblock = leftblock;
1097 leftblock = leftblock->rightlink;
1098 leftindex = 0;
1099 freeblock(prevblock);
1100 }
1101 }
1102 CHECK_END(leftblock->rightlink);
1103 freeblock(leftblock);
1104 return;
1105
1106 alternate_method:
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001107 while (Py_SIZE(deque)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001108 item = deque_pop(deque, NULL);
1109 assert (item != NULL);
1110 Py_DECREF(item);
1111 }
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001112}
1113
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001114static int
1115valid_index(Py_ssize_t i, Py_ssize_t limit)
1116{
1117 /* The cast to size_t let us use just a single comparison
1118 to check whether i is in the range: 0 <= i < limit */
1119 return (size_t) i < (size_t) limit;
1120}
1121
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001122static PyObject *
Benjamin Petersond6313712008-07-31 16:23:04 +00001123deque_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001124{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001125 block *b;
1126 PyObject *item;
1127 Py_ssize_t n, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001128
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001129 if (!valid_index(i, Py_SIZE(deque))) {
1130 PyErr_SetString(PyExc_IndexError, "deque index out of range");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001131 return NULL;
1132 }
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001133
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001134 if (i == 0) {
1135 i = deque->leftindex;
1136 b = deque->leftblock;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001137 } else if (i == Py_SIZE(deque) - 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001138 i = deque->rightindex;
1139 b = deque->rightblock;
1140 } else {
1141 i += deque->leftindex;
Raymond Hettingerc2083082015-02-28 23:29:16 -08001142 n = (Py_ssize_t)((size_t) i / BLOCKLEN);
1143 i = (Py_ssize_t)((size_t) i % BLOCKLEN);
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001144 if (index < (Py_SIZE(deque) >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001145 b = deque->leftblock;
1146 while (n--)
1147 b = b->rightlink;
1148 } else {
Raymond Hettinger63d1ff22015-02-28 07:41:30 -08001149 n = (Py_ssize_t)(
Raymond Hettingerc2083082015-02-28 23:29:16 -08001150 ((size_t)(deque->leftindex + Py_SIZE(deque) - 1))
Raymond Hettinger63d1ff22015-02-28 07:41:30 -08001151 / BLOCKLEN - n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001152 b = deque->rightblock;
1153 while (n--)
1154 b = b->leftlink;
1155 }
1156 }
1157 item = b->data[i];
1158 Py_INCREF(item);
1159 return item;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001160}
1161
1162static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001163deque_del_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001164{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001165 PyObject *item;
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001166 int rv;
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001167
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001168 assert (i >= 0 && i < Py_SIZE(deque));
Raymond Hettinger6921c132015-03-21 02:03:40 -07001169 if (_deque_rotate(deque, -i))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001170 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001171 item = deque_popleft(deque, NULL);
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001172 rv = _deque_rotate(deque, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001173 assert (item != NULL);
1174 Py_DECREF(item);
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001175 return rv;
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001176}
1177
1178static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001179deque_ass_item(dequeobject *deque, Py_ssize_t i, PyObject *v)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001180{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001181 PyObject *old_value;
1182 block *b;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001183 Py_ssize_t n, len=Py_SIZE(deque), halflen=(len+1)>>1, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001184
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001185 if (!valid_index(i, len)) {
1186 PyErr_SetString(PyExc_IndexError, "deque index out of range");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001187 return -1;
1188 }
1189 if (v == NULL)
1190 return deque_del_item(deque, i);
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001192 i += deque->leftindex;
Raymond Hettingerc2083082015-02-28 23:29:16 -08001193 n = (Py_ssize_t)((size_t) i / BLOCKLEN);
1194 i = (Py_ssize_t)((size_t) i % BLOCKLEN);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 if (index <= halflen) {
1196 b = deque->leftblock;
1197 while (n--)
1198 b = b->rightlink;
1199 } else {
Raymond Hettingera473b9d2015-02-28 17:49:47 -08001200 n = (Py_ssize_t)(
Raymond Hettingerc2083082015-02-28 23:29:16 -08001201 ((size_t)(deque->leftindex + Py_SIZE(deque) - 1))
Raymond Hettingera473b9d2015-02-28 17:49:47 -08001202 / BLOCKLEN - n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001203 b = deque->rightblock;
1204 while (n--)
1205 b = b->leftlink;
1206 }
1207 Py_INCREF(v);
1208 old_value = b->data[i];
1209 b->data[i] = v;
1210 Py_DECREF(old_value);
1211 return 0;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001212}
1213
1214static PyObject *
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001215deque_clearmethod(dequeobject *deque)
1216{
Benjamin Peterson0e5c48a2013-01-12 21:22:18 -05001217 deque_clear(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001218 Py_RETURN_NONE;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001219}
1220
1221PyDoc_STRVAR(clear_doc, "Remove all elements from the deque.");
1222
1223static void
1224deque_dealloc(dequeobject *deque)
1225{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001226 PyObject_GC_UnTrack(deque);
1227 if (deque->weakreflist != NULL)
1228 PyObject_ClearWeakRefs((PyObject *) deque);
1229 if (deque->leftblock != NULL) {
1230 deque_clear(deque);
1231 assert(deque->leftblock != NULL);
1232 freeblock(deque->leftblock);
1233 }
1234 deque->leftblock = NULL;
1235 deque->rightblock = NULL;
1236 Py_TYPE(deque)->tp_free(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001237}
1238
1239static int
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001240deque_traverse(dequeobject *deque, visitproc visit, void *arg)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001241{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001242 block *b;
1243 PyObject *item;
1244 Py_ssize_t index;
1245 Py_ssize_t indexlo = deque->leftindex;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001246
Raymond Hettinger5bfa8672013-07-06 11:58:09 -10001247 for (b = deque->leftblock; b != deque->rightblock; b = b->rightlink) {
1248 for (index = indexlo; index < BLOCKLEN ; index++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001249 item = b->data[index];
1250 Py_VISIT(item);
1251 }
1252 indexlo = 0;
1253 }
Raymond Hettinger5bfa8672013-07-06 11:58:09 -10001254 for (index = indexlo; index <= deque->rightindex; index++) {
1255 item = b->data[index];
1256 Py_VISIT(item);
1257 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258 return 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001259}
1260
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001261static PyObject *
1262deque_copy(PyObject *deque)
1263{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001264 if (((dequeobject *)deque)->maxlen == -1)
1265 return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "O", deque, NULL);
1266 else
1267 return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "Oi",
1268 deque, ((dequeobject *)deque)->maxlen, NULL);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001269}
1270
1271PyDoc_STRVAR(copy_doc, "Return a shallow copy of a deque.");
1272
1273static PyObject *
1274deque_reduce(dequeobject *deque)
1275{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001276 PyObject *dict, *result, *aslist;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001277 _Py_IDENTIFIER(__dict__);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001278
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001279 dict = _PyObject_GetAttrId((PyObject *)deque, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001280 if (dict == NULL)
1281 PyErr_Clear();
1282 aslist = PySequence_List((PyObject *)deque);
1283 if (aslist == NULL) {
1284 Py_XDECREF(dict);
1285 return NULL;
1286 }
1287 if (dict == NULL) {
1288 if (deque->maxlen == -1)
1289 result = Py_BuildValue("O(O)", Py_TYPE(deque), aslist);
1290 else
1291 result = Py_BuildValue("O(On)", Py_TYPE(deque), aslist, deque->maxlen);
1292 } else {
1293 if (deque->maxlen == -1)
1294 result = Py_BuildValue("O(OO)O", Py_TYPE(deque), aslist, Py_None, dict);
1295 else
1296 result = Py_BuildValue("O(On)O", Py_TYPE(deque), aslist, deque->maxlen, dict);
1297 }
1298 Py_XDECREF(dict);
1299 Py_DECREF(aslist);
1300 return result;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001301}
1302
1303PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
1304
1305static PyObject *
1306deque_repr(PyObject *deque)
1307{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001308 PyObject *aslist, *result;
1309 int i;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001311 i = Py_ReprEnter(deque);
1312 if (i != 0) {
1313 if (i < 0)
1314 return NULL;
1315 return PyUnicode_FromString("[...]");
1316 }
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001318 aslist = PySequence_List(deque);
1319 if (aslist == NULL) {
1320 Py_ReprLeave(deque);
1321 return NULL;
1322 }
1323 if (((dequeobject *)deque)->maxlen != -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001324 result = PyUnicode_FromFormat("deque(%R, maxlen=%zd)",
1325 aslist, ((dequeobject *)deque)->maxlen);
1326 else
1327 result = PyUnicode_FromFormat("deque(%R)", aslist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001328 Py_ReprLeave(deque);
Raymond Hettinger2b2b7532015-09-05 17:05:52 -07001329 Py_DECREF(aslist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001330 return result;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001331}
1332
Raymond Hettinger738ec902004-02-29 02:15:56 +00001333static PyObject *
1334deque_richcompare(PyObject *v, PyObject *w, int op)
1335{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336 PyObject *it1=NULL, *it2=NULL, *x, *y;
1337 Py_ssize_t vs, ws;
1338 int b, cmp=-1;
Raymond Hettinger738ec902004-02-29 02:15:56 +00001339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001340 if (!PyObject_TypeCheck(v, &deque_type) ||
1341 !PyObject_TypeCheck(w, &deque_type)) {
Brian Curtindfc80e32011-08-10 20:28:54 -05001342 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001343 }
Raymond Hettinger738ec902004-02-29 02:15:56 +00001344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001345 /* Shortcuts */
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001346 vs = Py_SIZE((dequeobject *)v);
1347 ws = Py_SIZE((dequeobject *)w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001348 if (op == Py_EQ) {
1349 if (v == w)
1350 Py_RETURN_TRUE;
1351 if (vs != ws)
1352 Py_RETURN_FALSE;
1353 }
1354 if (op == Py_NE) {
1355 if (v == w)
1356 Py_RETURN_FALSE;
1357 if (vs != ws)
1358 Py_RETURN_TRUE;
1359 }
Raymond Hettinger738ec902004-02-29 02:15:56 +00001360
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001361 /* Search for the first index where items are different */
1362 it1 = PyObject_GetIter(v);
1363 if (it1 == NULL)
1364 goto done;
1365 it2 = PyObject_GetIter(w);
1366 if (it2 == NULL)
1367 goto done;
1368 for (;;) {
1369 x = PyIter_Next(it1);
1370 if (x == NULL && PyErr_Occurred())
1371 goto done;
1372 y = PyIter_Next(it2);
1373 if (x == NULL || y == NULL)
1374 break;
1375 b = PyObject_RichCompareBool(x, y, Py_EQ);
1376 if (b == 0) {
1377 cmp = PyObject_RichCompareBool(x, y, op);
1378 Py_DECREF(x);
1379 Py_DECREF(y);
1380 goto done;
1381 }
1382 Py_DECREF(x);
1383 Py_DECREF(y);
1384 if (b == -1)
1385 goto done;
1386 }
1387 /* We reached the end of one deque or both */
1388 Py_XDECREF(x);
1389 Py_XDECREF(y);
1390 if (PyErr_Occurred())
1391 goto done;
1392 switch (op) {
1393 case Py_LT: cmp = y != NULL; break; /* if w was longer */
1394 case Py_LE: cmp = x == NULL; break; /* if v was not longer */
1395 case Py_EQ: cmp = x == y; break; /* if we reached the end of both */
1396 case Py_NE: cmp = x != y; break; /* if one deque continues */
1397 case Py_GT: cmp = x != NULL; break; /* if v was longer */
1398 case Py_GE: cmp = y == NULL; break; /* if w was not longer */
1399 }
Tim Peters1065f752004-10-01 01:03:29 +00001400
Raymond Hettinger738ec902004-02-29 02:15:56 +00001401done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001402 Py_XDECREF(it1);
1403 Py_XDECREF(it2);
1404 if (cmp == 1)
1405 Py_RETURN_TRUE;
1406 if (cmp == 0)
1407 Py_RETURN_FALSE;
1408 return NULL;
Raymond Hettinger738ec902004-02-29 02:15:56 +00001409}
1410
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001411static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001412deque_init(dequeobject *deque, PyObject *args, PyObject *kwdargs)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001413{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001414 PyObject *iterable = NULL;
1415 PyObject *maxlenobj = NULL;
1416 Py_ssize_t maxlen = -1;
1417 char *kwlist[] = {"iterable", "maxlen", 0};
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001418
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001419 if (!PyArg_ParseTupleAndKeywords(args, kwdargs, "|OO:deque", kwlist, &iterable, &maxlenobj))
1420 return -1;
1421 if (maxlenobj != NULL && maxlenobj != Py_None) {
1422 maxlen = PyLong_AsSsize_t(maxlenobj);
1423 if (maxlen == -1 && PyErr_Occurred())
1424 return -1;
1425 if (maxlen < 0) {
1426 PyErr_SetString(PyExc_ValueError, "maxlen must be non-negative");
1427 return -1;
1428 }
1429 }
1430 deque->maxlen = maxlen;
Raymond Hettinger848f2b52015-10-06 23:06:17 -04001431 if (Py_SIZE(deque) > 0)
1432 deque_clear(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001433 if (iterable != NULL) {
1434 PyObject *rv = deque_extend(deque, iterable);
1435 if (rv == NULL)
1436 return -1;
1437 Py_DECREF(rv);
1438 }
1439 return 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001440}
1441
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001442static PyObject *
Jesus Cea16e2fca2012-08-03 14:49:42 +02001443deque_sizeof(dequeobject *deque, void *unused)
1444{
1445 Py_ssize_t res;
1446 Py_ssize_t blocks;
1447
Serhiy Storchaka5c4064e2015-12-19 20:05:25 +02001448 res = _PyObject_SIZE(Py_TYPE(deque));
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001449 blocks = (deque->leftindex + Py_SIZE(deque) + BLOCKLEN - 1) / BLOCKLEN;
1450 assert(deque->leftindex + Py_SIZE(deque) - 1 ==
Jesus Cea16e2fca2012-08-03 14:49:42 +02001451 (blocks - 1) * BLOCKLEN + deque->rightindex);
1452 res += blocks * sizeof(block);
1453 return PyLong_FromSsize_t(res);
1454}
1455
1456PyDoc_STRVAR(sizeof_doc,
1457"D.__sizeof__() -- size of D in memory, in bytes");
1458
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001459static int
1460deque_bool(dequeobject *deque)
1461{
1462 return Py_SIZE(deque) != 0;
1463}
1464
Jesus Cea16e2fca2012-08-03 14:49:42 +02001465static PyObject *
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001466deque_get_maxlen(dequeobject *deque)
1467{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001468 if (deque->maxlen == -1)
1469 Py_RETURN_NONE;
1470 return PyLong_FromSsize_t(deque->maxlen);
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001471}
1472
Raymond Hettinger41290a62015-03-31 08:12:23 -07001473
1474/* deque object ********************************************************/
1475
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001476static PyGetSetDef deque_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001477 {"maxlen", (getter)deque_get_maxlen, (setter)NULL,
1478 "maximum size of a deque or None if unbounded"},
1479 {0}
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001480};
1481
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001482static PySequenceMethods deque_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001483 (lenfunc)deque_len, /* sq_length */
Raymond Hettinger41290a62015-03-31 08:12:23 -07001484 (binaryfunc)deque_concat, /* sq_concat */
1485 (ssizeargfunc)deque_repeat, /* sq_repeat */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001486 (ssizeargfunc)deque_item, /* sq_item */
1487 0, /* sq_slice */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001488 (ssizeobjargproc)deque_ass_item, /* sq_ass_item */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001489 0, /* sq_ass_slice */
Raymond Hettinger39dadf72015-03-20 16:38:56 -07001490 (objobjproc)deque_contains, /* sq_contains */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001491 (binaryfunc)deque_inplace_concat, /* sq_inplace_concat */
Raymond Hettinger41290a62015-03-31 08:12:23 -07001492 (ssizeargfunc)deque_inplace_repeat, /* sq_inplace_repeat */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001493};
1494
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001495static PyNumberMethods deque_as_number = {
1496 0, /* nb_add */
1497 0, /* nb_subtract */
1498 0, /* nb_multiply */
1499 0, /* nb_remainder */
1500 0, /* nb_divmod */
1501 0, /* nb_power */
1502 0, /* nb_negative */
1503 0, /* nb_positive */
1504 0, /* nb_absolute */
1505 (inquiry)deque_bool, /* nb_bool */
1506 0, /* nb_invert */
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001507 };
1508
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001509static PyObject *deque_iter(dequeobject *deque);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001510static PyObject *deque_reviter(dequeobject *deque);
Tim Peters1065f752004-10-01 01:03:29 +00001511PyDoc_STRVAR(reversed_doc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001512 "D.__reversed__() -- return a reverse iterator over the deque");
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001513
1514static PyMethodDef deque_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001515 {"append", (PyCFunction)deque_append,
1516 METH_O, append_doc},
1517 {"appendleft", (PyCFunction)deque_appendleft,
1518 METH_O, appendleft_doc},
1519 {"clear", (PyCFunction)deque_clearmethod,
1520 METH_NOARGS, clear_doc},
1521 {"__copy__", (PyCFunction)deque_copy,
1522 METH_NOARGS, copy_doc},
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001523 {"copy", (PyCFunction)deque_copy,
1524 METH_NOARGS, copy_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001525 {"count", (PyCFunction)deque_count,
Raymond Hettinger0f6f9472015-03-21 01:42:10 -07001526 METH_O, count_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001527 {"extend", (PyCFunction)deque_extend,
1528 METH_O, extend_doc},
1529 {"extendleft", (PyCFunction)deque_extendleft,
1530 METH_O, extendleft_doc},
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001531 {"index", (PyCFunction)deque_index,
1532 METH_VARARGS, index_doc},
1533 {"insert", (PyCFunction)deque_insert,
1534 METH_VARARGS, insert_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001535 {"pop", (PyCFunction)deque_pop,
1536 METH_NOARGS, pop_doc},
1537 {"popleft", (PyCFunction)deque_popleft,
1538 METH_NOARGS, popleft_doc},
Raymond Hettinger0f6f9472015-03-21 01:42:10 -07001539 {"__reduce__", (PyCFunction)deque_reduce,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001540 METH_NOARGS, reduce_doc},
1541 {"remove", (PyCFunction)deque_remove,
1542 METH_O, remove_doc},
1543 {"__reversed__", (PyCFunction)deque_reviter,
1544 METH_NOARGS, reversed_doc},
1545 {"reverse", (PyCFunction)deque_reverse,
1546 METH_NOARGS, reverse_doc},
1547 {"rotate", (PyCFunction)deque_rotate,
Jesus Cea16e2fca2012-08-03 14:49:42 +02001548 METH_VARARGS, rotate_doc},
1549 {"__sizeof__", (PyCFunction)deque_sizeof,
1550 METH_NOARGS, sizeof_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001551 {NULL, NULL} /* sentinel */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001552};
1553
1554PyDoc_STRVAR(deque_doc,
Andrew Svetlov6a5c7c32012-10-31 11:50:40 +02001555"deque([iterable[, maxlen]]) --> deque object\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001556\n\
Raymond Hettinger41290a62015-03-31 08:12:23 -07001557A list-like sequence optimized for data accesses near its endpoints.");
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001558
Neal Norwitz87f10132004-02-29 15:40:53 +00001559static PyTypeObject deque_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001560 PyVarObject_HEAD_INIT(NULL, 0)
1561 "collections.deque", /* tp_name */
1562 sizeof(dequeobject), /* tp_basicsize */
1563 0, /* tp_itemsize */
1564 /* methods */
1565 (destructor)deque_dealloc, /* tp_dealloc */
1566 0, /* tp_print */
1567 0, /* tp_getattr */
1568 0, /* tp_setattr */
1569 0, /* tp_reserved */
1570 deque_repr, /* tp_repr */
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001571 &deque_as_number, /* tp_as_number */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001572 &deque_as_sequence, /* tp_as_sequence */
1573 0, /* tp_as_mapping */
Georg Brandlf038b322010-10-18 07:35:09 +00001574 PyObject_HashNotImplemented, /* tp_hash */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001575 0, /* tp_call */
1576 0, /* tp_str */
1577 PyObject_GenericGetAttr, /* tp_getattro */
1578 0, /* tp_setattro */
1579 0, /* tp_as_buffer */
1580 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
Georg Brandlf038b322010-10-18 07:35:09 +00001581 /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001582 deque_doc, /* tp_doc */
1583 (traverseproc)deque_traverse, /* tp_traverse */
1584 (inquiry)deque_clear, /* tp_clear */
1585 (richcmpfunc)deque_richcompare, /* tp_richcompare */
Georg Brandlf038b322010-10-18 07:35:09 +00001586 offsetof(dequeobject, weakreflist), /* tp_weaklistoffset*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001587 (getiterfunc)deque_iter, /* tp_iter */
1588 0, /* tp_iternext */
1589 deque_methods, /* tp_methods */
1590 0, /* tp_members */
Georg Brandlf038b322010-10-18 07:35:09 +00001591 deque_getset, /* tp_getset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001592 0, /* tp_base */
1593 0, /* tp_dict */
1594 0, /* tp_descr_get */
1595 0, /* tp_descr_set */
1596 0, /* tp_dictoffset */
1597 (initproc)deque_init, /* tp_init */
1598 PyType_GenericAlloc, /* tp_alloc */
1599 deque_new, /* tp_new */
1600 PyObject_GC_Del, /* tp_free */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001601};
1602
1603/*********************** Deque Iterator **************************/
1604
1605typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001606 PyObject_HEAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001607 block *b;
Raymond Hettinger87e69122015-03-02 23:32:02 -08001608 Py_ssize_t index;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001609 dequeobject *deque;
Raymond Hettingerf9d9c792015-03-02 22:47:46 -08001610 size_t state; /* state when the iterator is created */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001611 Py_ssize_t counter; /* number of items remaining for iteration */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001612} dequeiterobject;
1613
Martin v. Löwis59683e82008-06-13 07:50:45 +00001614static PyTypeObject dequeiter_type;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001615
1616static PyObject *
1617deque_iter(dequeobject *deque)
1618{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001619 dequeiterobject *it;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001621 it = PyObject_GC_New(dequeiterobject, &dequeiter_type);
1622 if (it == NULL)
1623 return NULL;
1624 it->b = deque->leftblock;
1625 it->index = deque->leftindex;
1626 Py_INCREF(deque);
1627 it->deque = deque;
1628 it->state = deque->state;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001629 it->counter = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001630 PyObject_GC_Track(it);
1631 return (PyObject *)it;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001632}
1633
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001634static int
1635dequeiter_traverse(dequeiterobject *dio, visitproc visit, void *arg)
1636{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001637 Py_VISIT(dio->deque);
1638 return 0;
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001639}
1640
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001641static void
1642dequeiter_dealloc(dequeiterobject *dio)
1643{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001644 Py_XDECREF(dio->deque);
1645 PyObject_GC_Del(dio);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001646}
1647
1648static PyObject *
1649dequeiter_next(dequeiterobject *it)
1650{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001651 PyObject *item;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001653 if (it->deque->state != it->state) {
1654 it->counter = 0;
1655 PyErr_SetString(PyExc_RuntimeError,
1656 "deque mutated during iteration");
1657 return NULL;
1658 }
1659 if (it->counter == 0)
1660 return NULL;
1661 assert (!(it->b == it->deque->rightblock &&
1662 it->index > it->deque->rightindex));
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001663
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001664 item = it->b->data[it->index];
1665 it->index++;
1666 it->counter--;
1667 if (it->index == BLOCKLEN && it->counter > 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -10001668 CHECK_NOT_END(it->b->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001669 it->b = it->b->rightlink;
1670 it->index = 0;
1671 }
1672 Py_INCREF(item);
1673 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001674}
1675
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001676static PyObject *
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001677dequeiter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1678{
1679 Py_ssize_t i, index=0;
1680 PyObject *deque;
1681 dequeiterobject *it;
1682 if (!PyArg_ParseTuple(args, "O!|n", &deque_type, &deque, &index))
1683 return NULL;
1684 assert(type == &dequeiter_type);
1685
1686 it = (dequeiterobject*)deque_iter((dequeobject *)deque);
1687 if (!it)
1688 return NULL;
1689 /* consume items from the queue */
1690 for(i=0; i<index; i++) {
1691 PyObject *item = dequeiter_next(it);
1692 if (item) {
1693 Py_DECREF(item);
1694 } else {
1695 if (it->counter) {
1696 Py_DECREF(it);
1697 return NULL;
1698 } else
1699 break;
1700 }
1701 }
1702 return (PyObject*)it;
1703}
1704
1705static PyObject *
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001706dequeiter_len(dequeiterobject *it)
1707{
Antoine Pitrou554f3342010-08-17 18:30:06 +00001708 return PyLong_FromSsize_t(it->counter);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001709}
1710
Armin Rigof5b3e362006-02-11 21:32:43 +00001711PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001712
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001713static PyObject *
1714dequeiter_reduce(dequeiterobject *it)
1715{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001716 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 +00001717}
1718
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001719static PyMethodDef dequeiter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001720 {"__length_hint__", (PyCFunction)dequeiter_len, METH_NOARGS, length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001721 {"__reduce__", (PyCFunction)dequeiter_reduce, METH_NOARGS, reduce_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001722 {NULL, NULL} /* sentinel */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001723};
1724
Martin v. Löwis59683e82008-06-13 07:50:45 +00001725static PyTypeObject dequeiter_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001726 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger87e69122015-03-02 23:32:02 -08001727 "_collections._deque_iterator", /* tp_name */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001728 sizeof(dequeiterobject), /* tp_basicsize */
1729 0, /* tp_itemsize */
1730 /* methods */
1731 (destructor)dequeiter_dealloc, /* tp_dealloc */
1732 0, /* tp_print */
1733 0, /* tp_getattr */
1734 0, /* tp_setattr */
1735 0, /* tp_reserved */
1736 0, /* tp_repr */
1737 0, /* tp_as_number */
1738 0, /* tp_as_sequence */
1739 0, /* tp_as_mapping */
1740 0, /* tp_hash */
1741 0, /* tp_call */
1742 0, /* tp_str */
1743 PyObject_GenericGetAttr, /* tp_getattro */
1744 0, /* tp_setattro */
1745 0, /* tp_as_buffer */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001746 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001747 0, /* tp_doc */
1748 (traverseproc)dequeiter_traverse, /* tp_traverse */
1749 0, /* tp_clear */
1750 0, /* tp_richcompare */
1751 0, /* tp_weaklistoffset */
1752 PyObject_SelfIter, /* tp_iter */
1753 (iternextfunc)dequeiter_next, /* tp_iternext */
1754 dequeiter_methods, /* tp_methods */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001755 0, /* tp_members */
1756 0, /* tp_getset */
1757 0, /* tp_base */
1758 0, /* tp_dict */
1759 0, /* tp_descr_get */
1760 0, /* tp_descr_set */
1761 0, /* tp_dictoffset */
1762 0, /* tp_init */
1763 0, /* tp_alloc */
1764 dequeiter_new, /* tp_new */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001765 0,
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001766};
1767
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001768/*********************** Deque Reverse Iterator **************************/
1769
Martin v. Löwis59683e82008-06-13 07:50:45 +00001770static PyTypeObject dequereviter_type;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001771
1772static PyObject *
1773deque_reviter(dequeobject *deque)
1774{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001775 dequeiterobject *it;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001777 it = PyObject_GC_New(dequeiterobject, &dequereviter_type);
1778 if (it == NULL)
1779 return NULL;
1780 it->b = deque->rightblock;
1781 it->index = deque->rightindex;
1782 Py_INCREF(deque);
1783 it->deque = deque;
1784 it->state = deque->state;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001785 it->counter = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001786 PyObject_GC_Track(it);
1787 return (PyObject *)it;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001788}
1789
1790static PyObject *
1791dequereviter_next(dequeiterobject *it)
1792{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001793 PyObject *item;
1794 if (it->counter == 0)
1795 return NULL;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001796
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001797 if (it->deque->state != it->state) {
1798 it->counter = 0;
1799 PyErr_SetString(PyExc_RuntimeError,
1800 "deque mutated during iteration");
1801 return NULL;
1802 }
1803 assert (!(it->b == it->deque->leftblock &&
1804 it->index < it->deque->leftindex));
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001805
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001806 item = it->b->data[it->index];
1807 it->index--;
1808 it->counter--;
1809 if (it->index == -1 && it->counter > 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -10001810 CHECK_NOT_END(it->b->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001811 it->b = it->b->leftlink;
1812 it->index = BLOCKLEN - 1;
1813 }
1814 Py_INCREF(item);
1815 return item;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001816}
1817
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001818static PyObject *
1819dequereviter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1820{
1821 Py_ssize_t i, index=0;
1822 PyObject *deque;
1823 dequeiterobject *it;
1824 if (!PyArg_ParseTuple(args, "O!|n", &deque_type, &deque, &index))
1825 return NULL;
1826 assert(type == &dequereviter_type);
1827
1828 it = (dequeiterobject*)deque_reviter((dequeobject *)deque);
1829 if (!it)
1830 return NULL;
1831 /* consume items from the queue */
1832 for(i=0; i<index; i++) {
1833 PyObject *item = dequereviter_next(it);
1834 if (item) {
1835 Py_DECREF(item);
1836 } else {
1837 if (it->counter) {
1838 Py_DECREF(it);
1839 return NULL;
1840 } else
1841 break;
1842 }
1843 }
1844 return (PyObject*)it;
1845}
1846
Martin v. Löwis59683e82008-06-13 07:50:45 +00001847static PyTypeObject dequereviter_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001848 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger87e69122015-03-02 23:32:02 -08001849 "_collections._deque_reverse_iterator", /* tp_name */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001850 sizeof(dequeiterobject), /* tp_basicsize */
1851 0, /* tp_itemsize */
1852 /* methods */
1853 (destructor)dequeiter_dealloc, /* tp_dealloc */
1854 0, /* tp_print */
1855 0, /* tp_getattr */
1856 0, /* tp_setattr */
1857 0, /* tp_reserved */
1858 0, /* tp_repr */
1859 0, /* tp_as_number */
1860 0, /* tp_as_sequence */
1861 0, /* tp_as_mapping */
1862 0, /* tp_hash */
1863 0, /* tp_call */
1864 0, /* tp_str */
1865 PyObject_GenericGetAttr, /* tp_getattro */
1866 0, /* tp_setattro */
1867 0, /* tp_as_buffer */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001868 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001869 0, /* tp_doc */
1870 (traverseproc)dequeiter_traverse, /* tp_traverse */
1871 0, /* tp_clear */
1872 0, /* tp_richcompare */
1873 0, /* tp_weaklistoffset */
1874 PyObject_SelfIter, /* tp_iter */
1875 (iternextfunc)dequereviter_next, /* tp_iternext */
1876 dequeiter_methods, /* tp_methods */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001877 0, /* tp_members */
1878 0, /* tp_getset */
1879 0, /* tp_base */
1880 0, /* tp_dict */
1881 0, /* tp_descr_get */
1882 0, /* tp_descr_set */
1883 0, /* tp_dictoffset */
1884 0, /* tp_init */
1885 0, /* tp_alloc */
1886 dequereviter_new, /* tp_new */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001887 0,
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001888};
1889
Guido van Rossum1968ad32006-02-25 22:38:04 +00001890/* defaultdict type *********************************************************/
1891
1892typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001893 PyDictObject dict;
1894 PyObject *default_factory;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001895} defdictobject;
1896
1897static PyTypeObject defdict_type; /* Forward */
1898
1899PyDoc_STRVAR(defdict_missing_doc,
1900"__missing__(key) # Called by __getitem__ for missing key; pseudo-code:\n\
Guido van Rossumd8faa362007-04-27 19:54:29 +00001901 if self.default_factory is None: raise KeyError((key,))\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00001902 self[key] = value = self.default_factory()\n\
1903 return value\n\
1904");
1905
1906static PyObject *
1907defdict_missing(defdictobject *dd, PyObject *key)
1908{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001909 PyObject *factory = dd->default_factory;
1910 PyObject *value;
1911 if (factory == NULL || factory == Py_None) {
1912 /* XXX Call dict.__missing__(key) */
1913 PyObject *tup;
1914 tup = PyTuple_Pack(1, key);
1915 if (!tup) return NULL;
1916 PyErr_SetObject(PyExc_KeyError, tup);
1917 Py_DECREF(tup);
1918 return NULL;
1919 }
1920 value = PyEval_CallObject(factory, NULL);
1921 if (value == NULL)
1922 return value;
1923 if (PyObject_SetItem((PyObject *)dd, key, value) < 0) {
1924 Py_DECREF(value);
1925 return NULL;
1926 }
1927 return value;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001928}
1929
1930PyDoc_STRVAR(defdict_copy_doc, "D.copy() -> a shallow copy of D.");
1931
1932static PyObject *
1933defdict_copy(defdictobject *dd)
1934{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001935 /* This calls the object's class. That only works for subclasses
1936 whose class constructor has the same signature. Subclasses that
1937 define a different constructor signature must override copy().
1938 */
Raymond Hettinger54628fa2009-08-04 19:16:39 +00001939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001940 if (dd->default_factory == NULL)
1941 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd), Py_None, dd, NULL);
1942 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd),
1943 dd->default_factory, dd, NULL);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001944}
1945
1946static PyObject *
1947defdict_reduce(defdictobject *dd)
1948{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001949 /* __reduce__ must return a 5-tuple as follows:
Guido van Rossum1968ad32006-02-25 22:38:04 +00001950
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001951 - factory function
1952 - tuple of args for the factory function
1953 - additional state (here None)
1954 - sequence iterator (here None)
1955 - dictionary iterator (yielding successive (key, value) pairs
Guido van Rossum1968ad32006-02-25 22:38:04 +00001956
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001957 This API is used by pickle.py and copy.py.
Guido van Rossum1968ad32006-02-25 22:38:04 +00001958
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001959 For this to be useful with pickle.py, the default_factory
1960 must be picklable; e.g., None, a built-in, or a global
1961 function in a module or package.
Guido van Rossum1968ad32006-02-25 22:38:04 +00001962
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001963 Both shallow and deep copying are supported, but for deep
1964 copying, the default_factory must be deep-copyable; e.g. None,
1965 or a built-in (functions are not copyable at this time).
Guido van Rossum1968ad32006-02-25 22:38:04 +00001966
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001967 This only works for subclasses as long as their constructor
1968 signature is compatible; the first argument must be the
1969 optional default_factory, defaulting to None.
1970 */
1971 PyObject *args;
1972 PyObject *items;
1973 PyObject *iter;
1974 PyObject *result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001975 _Py_IDENTIFIER(items);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001977 if (dd->default_factory == NULL || dd->default_factory == Py_None)
1978 args = PyTuple_New(0);
1979 else
1980 args = PyTuple_Pack(1, dd->default_factory);
1981 if (args == NULL)
1982 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001983 items = _PyObject_CallMethodId((PyObject *)dd, &PyId_items, "()");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001984 if (items == NULL) {
1985 Py_DECREF(args);
1986 return NULL;
1987 }
1988 iter = PyObject_GetIter(items);
1989 if (iter == NULL) {
1990 Py_DECREF(items);
1991 Py_DECREF(args);
1992 return NULL;
1993 }
1994 result = PyTuple_Pack(5, Py_TYPE(dd), args,
1995 Py_None, Py_None, iter);
1996 Py_DECREF(iter);
1997 Py_DECREF(items);
1998 Py_DECREF(args);
1999 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00002000}
2001
2002static PyMethodDef defdict_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002003 {"__missing__", (PyCFunction)defdict_missing, METH_O,
2004 defdict_missing_doc},
2005 {"copy", (PyCFunction)defdict_copy, METH_NOARGS,
2006 defdict_copy_doc},
2007 {"__copy__", (PyCFunction)defdict_copy, METH_NOARGS,
2008 defdict_copy_doc},
2009 {"__reduce__", (PyCFunction)defdict_reduce, METH_NOARGS,
2010 reduce_doc},
2011 {NULL}
Guido van Rossum1968ad32006-02-25 22:38:04 +00002012};
2013
2014static PyMemberDef defdict_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002015 {"default_factory", T_OBJECT,
2016 offsetof(defdictobject, default_factory), 0,
2017 PyDoc_STR("Factory for default value called by __missing__().")},
2018 {NULL}
Guido van Rossum1968ad32006-02-25 22:38:04 +00002019};
2020
2021static void
2022defdict_dealloc(defdictobject *dd)
2023{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002024 Py_CLEAR(dd->default_factory);
2025 PyDict_Type.tp_dealloc((PyObject *)dd);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002026}
2027
Guido van Rossum1968ad32006-02-25 22:38:04 +00002028static PyObject *
2029defdict_repr(defdictobject *dd)
2030{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002031 PyObject *baserepr;
2032 PyObject *defrepr;
2033 PyObject *result;
2034 baserepr = PyDict_Type.tp_repr((PyObject *)dd);
2035 if (baserepr == NULL)
2036 return NULL;
2037 if (dd->default_factory == NULL)
2038 defrepr = PyUnicode_FromString("None");
2039 else
2040 {
2041 int status = Py_ReprEnter(dd->default_factory);
2042 if (status != 0) {
Antoine Pitrouf5f1fe02012-02-15 02:42:46 +01002043 if (status < 0) {
2044 Py_DECREF(baserepr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002045 return NULL;
Antoine Pitrouf5f1fe02012-02-15 02:42:46 +01002046 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002047 defrepr = PyUnicode_FromString("...");
2048 }
2049 else
2050 defrepr = PyObject_Repr(dd->default_factory);
2051 Py_ReprLeave(dd->default_factory);
2052 }
2053 if (defrepr == NULL) {
2054 Py_DECREF(baserepr);
2055 return NULL;
2056 }
2057 result = PyUnicode_FromFormat("defaultdict(%U, %U)",
2058 defrepr, baserepr);
2059 Py_DECREF(defrepr);
2060 Py_DECREF(baserepr);
2061 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00002062}
2063
2064static int
2065defdict_traverse(PyObject *self, visitproc visit, void *arg)
2066{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002067 Py_VISIT(((defdictobject *)self)->default_factory);
2068 return PyDict_Type.tp_traverse(self, visit, arg);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002069}
2070
2071static int
2072defdict_tp_clear(defdictobject *dd)
2073{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002074 Py_CLEAR(dd->default_factory);
2075 return PyDict_Type.tp_clear((PyObject *)dd);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002076}
2077
2078static int
2079defdict_init(PyObject *self, PyObject *args, PyObject *kwds)
2080{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002081 defdictobject *dd = (defdictobject *)self;
2082 PyObject *olddefault = dd->default_factory;
2083 PyObject *newdefault = NULL;
2084 PyObject *newargs;
2085 int result;
2086 if (args == NULL || !PyTuple_Check(args))
2087 newargs = PyTuple_New(0);
2088 else {
2089 Py_ssize_t n = PyTuple_GET_SIZE(args);
2090 if (n > 0) {
2091 newdefault = PyTuple_GET_ITEM(args, 0);
2092 if (!PyCallable_Check(newdefault) && newdefault != Py_None) {
2093 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger239aba72015-07-20 03:09:22 -04002094 "first argument must be callable or None");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002095 return -1;
2096 }
2097 }
2098 newargs = PySequence_GetSlice(args, 1, n);
2099 }
2100 if (newargs == NULL)
2101 return -1;
2102 Py_XINCREF(newdefault);
2103 dd->default_factory = newdefault;
2104 result = PyDict_Type.tp_init(self, newargs, kwds);
2105 Py_DECREF(newargs);
2106 Py_XDECREF(olddefault);
2107 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00002108}
2109
2110PyDoc_STRVAR(defdict_doc,
Benjamin Peterson9cb33b72014-01-13 23:56:05 -05002111"defaultdict(default_factory[, ...]) --> dict with default factory\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00002112\n\
2113The default factory is called without arguments to produce\n\
2114a new value when a key is not present, in __getitem__ only.\n\
2115A defaultdict compares equal to a dict with the same items.\n\
Benjamin Peterson9cb33b72014-01-13 23:56:05 -05002116All remaining arguments are treated the same as if they were\n\
2117passed to the dict constructor, including keyword arguments.\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00002118");
2119
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002120/* See comment in xxsubtype.c */
2121#define DEFERRED_ADDRESS(ADDR) 0
2122
Guido van Rossum1968ad32006-02-25 22:38:04 +00002123static PyTypeObject defdict_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002124 PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0)
2125 "collections.defaultdict", /* tp_name */
2126 sizeof(defdictobject), /* tp_basicsize */
2127 0, /* tp_itemsize */
2128 /* methods */
2129 (destructor)defdict_dealloc, /* tp_dealloc */
2130 0, /* tp_print */
2131 0, /* tp_getattr */
2132 0, /* tp_setattr */
2133 0, /* tp_reserved */
2134 (reprfunc)defdict_repr, /* tp_repr */
2135 0, /* tp_as_number */
2136 0, /* tp_as_sequence */
2137 0, /* tp_as_mapping */
2138 0, /* tp_hash */
2139 0, /* tp_call */
2140 0, /* tp_str */
2141 PyObject_GenericGetAttr, /* tp_getattro */
2142 0, /* tp_setattro */
2143 0, /* tp_as_buffer */
2144 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
2145 /* tp_flags */
2146 defdict_doc, /* tp_doc */
2147 defdict_traverse, /* tp_traverse */
2148 (inquiry)defdict_tp_clear, /* tp_clear */
2149 0, /* tp_richcompare */
2150 0, /* tp_weaklistoffset*/
2151 0, /* tp_iter */
2152 0, /* tp_iternext */
2153 defdict_methods, /* tp_methods */
2154 defdict_members, /* tp_members */
2155 0, /* tp_getset */
2156 DEFERRED_ADDRESS(&PyDict_Type), /* tp_base */
2157 0, /* tp_dict */
2158 0, /* tp_descr_get */
2159 0, /* tp_descr_set */
2160 0, /* tp_dictoffset */
2161 defdict_init, /* tp_init */
2162 PyType_GenericAlloc, /* tp_alloc */
2163 0, /* tp_new */
2164 PyObject_GC_Del, /* tp_free */
Guido van Rossum1968ad32006-02-25 22:38:04 +00002165};
2166
Raymond Hettinger96f34102010-12-15 16:30:37 +00002167/* helper function for Counter *********************************************/
2168
2169PyDoc_STRVAR(_count_elements_doc,
2170"_count_elements(mapping, iterable) -> None\n\
2171\n\
Martin Panter536d70e2017-01-14 08:23:08 +00002172Count elements in the iterable, updating the mapping");
Raymond Hettinger96f34102010-12-15 16:30:37 +00002173
2174static PyObject *
2175_count_elements(PyObject *self, PyObject *args)
2176{
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002177 _Py_IDENTIFIER(get);
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002178 _Py_IDENTIFIER(__setitem__);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002179 PyObject *it, *iterable, *mapping, *oldval;
2180 PyObject *newval = NULL;
2181 PyObject *key = NULL;
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002182 PyObject *zero = NULL;
Raymond Hettinger96f34102010-12-15 16:30:37 +00002183 PyObject *one = NULL;
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002184 PyObject *bound_get = NULL;
2185 PyObject *mapping_get;
2186 PyObject *dict_get;
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002187 PyObject *mapping_setitem;
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002188 PyObject *dict_setitem;
Raymond Hettinger96f34102010-12-15 16:30:37 +00002189
2190 if (!PyArg_UnpackTuple(args, "_count_elements", 2, 2, &mapping, &iterable))
2191 return NULL;
2192
Raymond Hettinger96f34102010-12-15 16:30:37 +00002193 it = PyObject_GetIter(iterable);
2194 if (it == NULL)
2195 return NULL;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002196
Raymond Hettinger96f34102010-12-15 16:30:37 +00002197 one = PyLong_FromLong(1);
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002198 if (one == NULL)
2199 goto done;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002200
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002201 /* Only take the fast path when get() and __setitem__()
2202 * have not been overridden.
2203 */
2204 mapping_get = _PyType_LookupId(Py_TYPE(mapping), &PyId_get);
2205 dict_get = _PyType_LookupId(&PyDict_Type, &PyId_get);
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002206 mapping_setitem = _PyType_LookupId(Py_TYPE(mapping), &PyId___setitem__);
2207 dict_setitem = _PyType_LookupId(&PyDict_Type, &PyId___setitem__);
2208
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002209 if (mapping_get != NULL && mapping_get == dict_get &&
2210 mapping_setitem != NULL && mapping_setitem == dict_setitem) {
Raymond Hettinger426e0522011-01-03 02:12:02 +00002211 while (1) {
Raymond Hettinger507d9972014-05-18 21:32:40 +01002212 /* Fast path advantages:
2213 1. Eliminate double hashing
2214 (by re-using the same hash for both the get and set)
2215 2. Avoid argument overhead of PyObject_CallFunctionObjArgs
2216 (argument tuple creation and parsing)
2217 3. Avoid indirection through a bound method object
2218 (creates another argument tuple)
2219 4. Avoid initial increment from zero
2220 (reuse an existing one-object instead)
2221 */
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002222 Py_hash_t hash;
2223
Raymond Hettinger426e0522011-01-03 02:12:02 +00002224 key = PyIter_Next(it);
Victor Stinnera154b5c2011-04-20 23:23:52 +02002225 if (key == NULL)
2226 break;
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002227
2228 if (!PyUnicode_CheckExact(key) ||
2229 (hash = ((PyASCIIObject *) key)->hash) == -1)
2230 {
2231 hash = PyObject_Hash(key);
Raymond Hettingerda2850f2015-02-27 12:42:54 -08002232 if (hash == -1)
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002233 goto done;
2234 }
2235
2236 oldval = _PyDict_GetItem_KnownHash(mapping, key, hash);
Raymond Hettinger426e0522011-01-03 02:12:02 +00002237 if (oldval == NULL) {
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002238 if (_PyDict_SetItem_KnownHash(mapping, key, one, hash) == -1)
Raymond Hettinger507d9972014-05-18 21:32:40 +01002239 goto done;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002240 } else {
2241 newval = PyNumber_Add(oldval, one);
2242 if (newval == NULL)
Raymond Hettinger507d9972014-05-18 21:32:40 +01002243 goto done;
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002244 if (_PyDict_SetItem_KnownHash(mapping, key, newval, hash) == -1)
Raymond Hettinger507d9972014-05-18 21:32:40 +01002245 goto done;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002246 Py_CLEAR(newval);
2247 }
2248 Py_DECREF(key);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002249 }
Raymond Hettinger426e0522011-01-03 02:12:02 +00002250 } else {
Victor Stinnere7f516c2013-11-06 23:52:55 +01002251 bound_get = _PyObject_GetAttrId(mapping, &PyId_get);
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002252 if (bound_get == NULL)
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002253 goto done;
2254
2255 zero = PyLong_FromLong(0);
2256 if (zero == NULL)
2257 goto done;
2258
Raymond Hettinger426e0522011-01-03 02:12:02 +00002259 while (1) {
2260 key = PyIter_Next(it);
Victor Stinnera154b5c2011-04-20 23:23:52 +02002261 if (key == NULL)
2262 break;
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002263 oldval = PyObject_CallFunctionObjArgs(bound_get, key, zero, NULL);
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002264 if (oldval == NULL)
2265 break;
2266 newval = PyNumber_Add(oldval, one);
2267 Py_DECREF(oldval);
2268 if (newval == NULL)
2269 break;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002270 if (PyObject_SetItem(mapping, key, newval) == -1)
Raymond Hettinger96f34102010-12-15 16:30:37 +00002271 break;
2272 Py_CLEAR(newval);
Raymond Hettinger426e0522011-01-03 02:12:02 +00002273 Py_DECREF(key);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002274 }
Raymond Hettinger96f34102010-12-15 16:30:37 +00002275 }
Raymond Hettinger426e0522011-01-03 02:12:02 +00002276
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002277done:
Raymond Hettinger96f34102010-12-15 16:30:37 +00002278 Py_DECREF(it);
2279 Py_XDECREF(key);
2280 Py_XDECREF(newval);
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002281 Py_XDECREF(bound_get);
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002282 Py_XDECREF(zero);
2283 Py_XDECREF(one);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002284 if (PyErr_Occurred())
2285 return NULL;
2286 Py_RETURN_NONE;
2287}
2288
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002289/* module level code ********************************************************/
2290
2291PyDoc_STRVAR(module_doc,
Guido van Rossum1968ad32006-02-25 22:38:04 +00002292"High performance data structures.\n\
2293- deque: ordered collection accessible from endpoints only\n\
2294- defaultdict: dict subclass with a default value factory\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002295");
2296
Raymond Hettinger96f34102010-12-15 16:30:37 +00002297static struct PyMethodDef module_functions[] = {
2298 {"_count_elements", _count_elements, METH_VARARGS, _count_elements_doc},
2299 {NULL, NULL} /* sentinel */
2300};
Martin v. Löwis1a214512008-06-11 05:26:20 +00002301
2302static struct PyModuleDef _collectionsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002303 PyModuleDef_HEAD_INIT,
2304 "_collections",
2305 module_doc,
2306 -1,
Raymond Hettinger96f34102010-12-15 16:30:37 +00002307 module_functions,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002308 NULL,
2309 NULL,
2310 NULL,
2311 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002312};
2313
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002314PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002315PyInit__collections(void)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002316{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002317 PyObject *m;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002318
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002319 m = PyModule_Create(&_collectionsmodule);
2320 if (m == NULL)
2321 return NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002323 if (PyType_Ready(&deque_type) < 0)
2324 return NULL;
2325 Py_INCREF(&deque_type);
2326 PyModule_AddObject(m, "deque", (PyObject *)&deque_type);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002328 defdict_type.tp_base = &PyDict_Type;
2329 if (PyType_Ready(&defdict_type) < 0)
2330 return NULL;
2331 Py_INCREF(&defdict_type);
2332 PyModule_AddObject(m, "defaultdict", (PyObject *)&defdict_type);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002333
Eric Snow96c6af92015-05-29 22:21:39 -06002334 Py_INCREF(&PyODict_Type);
2335 PyModule_AddObject(m, "OrderedDict", (PyObject *)&PyODict_Type);
2336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002337 if (PyType_Ready(&dequeiter_type) < 0)
2338 return NULL;
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002339 Py_INCREF(&dequeiter_type);
2340 PyModule_AddObject(m, "_deque_iterator", (PyObject *)&dequeiter_type);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002342 if (PyType_Ready(&dequereviter_type) < 0)
2343 return NULL;
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002344 Py_INCREF(&dequereviter_type);
2345 PyModule_AddObject(m, "_deque_reverse_iterator", (PyObject *)&dequereviter_type);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00002346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002347 return m;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002348}