blob: 2b70b2ba0605f2b553e9907c26dd568ca4b2dd5a [file] [log] [blame]
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001#include "Python.h"
Raymond Hettinger691d8052004-05-30 07:26:47 +00002#include "structmember.h"
Raymond Hettinger756b3f32004-01-29 06:37:52 +00003
Raymond Hettingerc2083082015-02-28 23:29:16 -08004#ifdef STDC_HEADERS
5#include <stddef.h>
6#else
7#include <sys/types.h> /* For size_t */
8#endif
9
Raymond Hettinger756b3f32004-01-29 06:37:52 +000010/* collections module implementation of a deque() datatype
11 Written and maintained by Raymond D. Hettinger <python@rcn.com>
Raymond Hettingereb6b5542015-02-10 22:37:22 -060012 Copyright (c) 2004-2015 Python Software Foundation.
Raymond Hettinger756b3f32004-01-29 06:37:52 +000013 All rights reserved.
14*/
15
Raymond Hettinger77e8bf12004-10-01 15:25:53 +000016/* The block length may be set to any number over 1. Larger numbers
Raymond Hettinger20b0f872013-06-23 15:44:33 -070017 * reduce the number of calls to the memory allocator, give faster
Raymond Hettinger30c90742015-03-02 22:31:35 -080018 * indexing and rotation, and reduce the link to data overhead ratio.
Raymond Hettingerdaf57f22015-02-26 23:21:29 -080019 * Making the block length a power of two speeds-up the modulo
Raymond Hettinger30c90742015-03-02 22:31:35 -080020 * and division calculations in deque_item() and deque_ass_item().
Raymond Hettinger77e8bf12004-10-01 15:25:53 +000021 */
22
Raymond Hettingerdaf57f22015-02-26 23:21:29 -080023#define BLOCKLEN 64
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000024#define CENTER ((BLOCKLEN - 1) / 2)
Raymond Hettinger756b3f32004-01-29 06:37:52 +000025
Raymond Hettinger551350a2015-03-24 00:19:53 -070026/* Data for deque objects is stored in a doubly-linked list of fixed
27 * length blocks. This assures that appends or pops never move any
28 * other data elements besides the one being appended or popped.
29 *
30 * Another advantage is that it completely avoids use of realloc(),
31 * resulting in more predictable performance.
32 *
33 * Textbook implementations of doubly-linked lists store one datum
34 * per link, but that gives them a 200% memory overhead (a prev and
35 * next link for each datum) and it costs one malloc() call per data
36 * element. By using fixed-length blocks, the link to data ratio is
37 * significantly improved and there are proportionally fewer calls
38 * to malloc() and free(). The data blocks of consecutive pointers
39 * also improve cache locality.
40 *
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000041 * The list of blocks is never empty, so d.leftblock and d.rightblock
Raymond Hettinger82df9252013-07-07 01:43:42 -100042 * are never equal to NULL. The list is not circular.
43 *
44 * A deque d's first element is at d.leftblock[leftindex]
45 * and its last element is at d.rightblock[rightindex].
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000046 *
Raymond Hettinger551350a2015-03-24 00:19:53 -070047 * Unlike Python slice indices, these indices are inclusive on both
48 * ends. This makes the algorithms for left and right operations
49 * more symmetrical and it simplifies the design.
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000050 *
Raymond Hettinger551350a2015-03-24 00:19:53 -070051 * The indices, d.leftindex and d.rightindex are always in the range:
52 * 0 <= index < BLOCKLEN
53 *
54 * And their exact relationship is:
55 * (d.leftindex + d.len - 1) % BLOCKLEN == d.rightindex
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000056 *
Raymond Hettinger8dbbae22015-03-24 21:01:50 -070057 * Whenever d.leftblock == d.rightblock, then:
Raymond Hettinger551350a2015-03-24 00:19:53 -070058 * d.leftindex + d.len - 1 == d.rightindex
Thomas Wouters0e3f5912006-08-11 14:57:12 +000059 *
Raymond Hettinger551350a2015-03-24 00:19:53 -070060 * However, when d.leftblock != d.rightblock, the d.leftindex and
61 * d.rightindex become indices into distinct blocks and either may
62 * be larger than the other.
63 *
64 * Empty deques have:
65 * d.len == 0
66 * d.leftblock == d.rightblock
67 * d.leftindex == CENTER + 1
68 * d.rightindex == CENTER
69 *
70 * Checking for d.len == 0 is the intended way to see whether d is empty.
Tim Petersd8768d32004-10-01 01:32:53 +000071 */
72
Raymond Hettinger756b3f32004-01-29 06:37:52 +000073typedef struct BLOCK {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000074 struct BLOCK *leftlink;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000075 PyObject *data[BLOCKLEN];
Raymond Hettinger20b0f872013-06-23 15:44:33 -070076 struct BLOCK *rightlink;
Raymond Hettinger756b3f32004-01-29 06:37:52 +000077} block;
78
Raymond Hettinger30c90742015-03-02 22:31:35 -080079typedef struct {
80 PyObject_VAR_HEAD
81 block *leftblock;
82 block *rightblock;
Raymond Hettinger551350a2015-03-24 00:19:53 -070083 Py_ssize_t leftindex; /* 0 <= leftindex < BLOCKLEN */
84 Py_ssize_t rightindex; /* 0 <= rightindex < BLOCKLEN */
Raymond Hettingerf9d9c792015-03-02 22:47:46 -080085 size_t state; /* incremented whenever the indices move */
Raymond Hettinger30c90742015-03-02 22:31:35 -080086 Py_ssize_t maxlen;
Raymond Hettinger0f6f9472015-03-21 01:42:10 -070087 PyObject *weakreflist;
Raymond Hettinger30c90742015-03-02 22:31:35 -080088} dequeobject;
89
90static PyTypeObject deque_type;
91
Raymond Hettinger82df9252013-07-07 01:43:42 -100092/* For debug builds, add error checking to track the endpoints
93 * in the chain of links. The goal is to make sure that link
94 * assignments only take place at endpoints so that links already
95 * in use do not get overwritten.
96 *
97 * CHECK_END should happen before each assignment to a block's link field.
98 * MARK_END should happen whenever a link field becomes a new endpoint.
99 * This happens when new blocks are added or whenever an existing
100 * block is freed leaving another existing block as the new endpoint.
101 */
102
Raymond Hettinger3223dd52013-07-26 23:14:22 -0700103#ifndef NDEBUG
Raymond Hettinger82df9252013-07-07 01:43:42 -1000104#define MARK_END(link) link = NULL;
105#define CHECK_END(link) assert(link == NULL);
106#define CHECK_NOT_END(link) assert(link != NULL);
107#else
108#define MARK_END(link)
109#define CHECK_END(link)
110#define CHECK_NOT_END(link)
111#endif
112
Raymond Hettinger41290a62015-03-31 08:12:23 -0700113/* To prevent len from overflowing PY_SSIZE_T_MAX, we refuse to
114 allocate new blocks if the current len is nearing overflow.
115*/
116
117#define MAX_DEQUE_LEN (PY_SSIZE_T_MAX - 3*BLOCKLEN)
118
Raymond Hettinger82df9252013-07-07 01:43:42 -1000119/* A simple freelisting scheme is used to minimize calls to the memory
Raymond Hettinger551350a2015-03-24 00:19:53 -0700120 allocator. It accommodates common use cases where new blocks are being
Raymond Hettinger82df9252013-07-07 01:43:42 -1000121 added at about the same rate as old blocks are being freed.
122 */
123
Guido van Rossum58da9312007-11-10 23:39:45 +0000124#define MAXFREEBLOCKS 10
Benjamin Petersond6313712008-07-31 16:23:04 +0000125static Py_ssize_t numfreeblocks = 0;
Guido van Rossum58da9312007-11-10 23:39:45 +0000126static block *freeblocks[MAXFREEBLOCKS];
127
Tim Peters6f853562004-10-01 01:04:50 +0000128static block *
Raymond Hettinger82df9252013-07-07 01:43:42 -1000129newblock(Py_ssize_t len) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000130 block *b;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700131 if (len >= MAX_DEQUE_LEN) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000132 PyErr_SetString(PyExc_OverflowError,
133 "cannot add more blocks to the deque");
134 return NULL;
135 }
136 if (numfreeblocks) {
Raymond Hettinger59cf23a2013-02-07 00:57:19 -0500137 numfreeblocks--;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000138 return freeblocks[numfreeblocks];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000139 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000140 b = PyMem_Malloc(sizeof(block));
141 if (b != NULL) {
142 return b;
143 }
144 PyErr_NoMemory();
145 return NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000146}
147
Martin v. Löwis59683e82008-06-13 07:50:45 +0000148static void
Guido van Rossum58da9312007-11-10 23:39:45 +0000149freeblock(block *b)
150{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000151 if (numfreeblocks < MAXFREEBLOCKS) {
152 freeblocks[numfreeblocks] = b;
153 numfreeblocks++;
154 } else {
155 PyMem_Free(b);
156 }
Guido van Rossum58da9312007-11-10 23:39:45 +0000157}
158
Raymond Hettingerda2850f2015-02-27 12:42:54 -0800159/* XXX Todo:
Raymond Hettinger54023152014-04-23 00:58:48 -0700160 If aligned memory allocations become available, make the
161 deque object 64 byte aligned so that all of the fields
162 can be retrieved or updated in a single cache line.
163*/
164
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000165static PyObject *
166deque_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
167{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000168 dequeobject *deque;
169 block *b;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000171 /* create dequeobject structure */
172 deque = (dequeobject *)type->tp_alloc(type, 0);
173 if (deque == NULL)
174 return NULL;
Tim Peters1065f752004-10-01 01:03:29 +0000175
Raymond Hettinger82df9252013-07-07 01:43:42 -1000176 b = newblock(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000177 if (b == NULL) {
178 Py_DECREF(deque);
179 return NULL;
180 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000181 MARK_END(b->leftlink);
182 MARK_END(b->rightlink);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000184 assert(BLOCKLEN >= 2);
Raymond Hettinger87e69122015-03-02 23:32:02 -0800185 Py_SIZE(deque) = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000186 deque->leftblock = b;
187 deque->rightblock = b;
188 deque->leftindex = CENTER + 1;
189 deque->rightindex = CENTER;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000190 deque->state = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000191 deque->maxlen = -1;
Raymond Hettinger87e69122015-03-02 23:32:02 -0800192 deque->weakreflist = NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000194 return (PyObject *)deque;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000195}
196
197static PyObject *
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000198deque_pop(dequeobject *deque, PyObject *unused)
199{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000200 PyObject *item;
201 block *prevblock;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000202
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000203 if (Py_SIZE(deque) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000204 PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
205 return NULL;
206 }
207 item = deque->rightblock->data[deque->rightindex];
208 deque->rightindex--;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000209 Py_SIZE(deque)--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000210 deque->state++;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000212 if (deque->rightindex == -1) {
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700213 if (Py_SIZE(deque)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000214 prevblock = deque->rightblock->leftlink;
215 assert(deque->leftblock != deque->rightblock);
216 freeblock(deque->rightblock);
Raymond Hettinger82df9252013-07-07 01:43:42 -1000217 CHECK_NOT_END(prevblock);
218 MARK_END(prevblock->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000219 deque->rightblock = prevblock;
220 deque->rightindex = BLOCKLEN - 1;
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700221 } else {
222 assert(deque->leftblock == deque->rightblock);
223 assert(deque->leftindex == deque->rightindex+1);
224 /* re-center instead of freeing a block */
225 deque->leftindex = CENTER + 1;
226 deque->rightindex = CENTER;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000227 }
228 }
229 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000230}
231
232PyDoc_STRVAR(pop_doc, "Remove and return the rightmost element.");
233
234static PyObject *
235deque_popleft(dequeobject *deque, PyObject *unused)
236{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000237 PyObject *item;
238 block *prevblock;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000239
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000240 if (Py_SIZE(deque) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000241 PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
242 return NULL;
243 }
244 assert(deque->leftblock != NULL);
245 item = deque->leftblock->data[deque->leftindex];
246 deque->leftindex++;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000247 Py_SIZE(deque)--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000248 deque->state++;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000250 if (deque->leftindex == BLOCKLEN) {
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700251 if (Py_SIZE(deque)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000252 assert(deque->leftblock != deque->rightblock);
253 prevblock = deque->leftblock->rightlink;
254 freeblock(deque->leftblock);
Raymond Hettinger82df9252013-07-07 01:43:42 -1000255 CHECK_NOT_END(prevblock);
256 MARK_END(prevblock->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000257 deque->leftblock = prevblock;
258 deque->leftindex = 0;
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700259 } else {
260 assert(deque->leftblock == deque->rightblock);
261 assert(deque->leftindex == deque->rightindex+1);
262 /* re-center instead of freeing a block */
263 deque->leftindex = CENTER + 1;
264 deque->rightindex = CENTER;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000265 }
266 }
267 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000268}
269
270PyDoc_STRVAR(popleft_doc, "Remove and return the leftmost element.");
271
Raymond Hettingerf30f5b92015-03-02 22:23:37 -0800272/* The deque's size limit is d.maxlen. The limit can be zero or positive.
273 * If there is no limit, then d.maxlen == -1.
274 *
275 * After an item is added to a deque, we check to see if the size has grown past
276 * the limit. If it has, we get the size back down to the limit by popping an
277 * item off of the opposite end. The methods that can trigger this are append(),
278 * appendleft(), extend(), and extendleft().
279 */
280
281static void
282deque_trim_right(dequeobject *deque)
283{
284 if (deque->maxlen != -1 && Py_SIZE(deque) > deque->maxlen) {
285 PyObject *rv = deque_pop(deque, NULL);
286 assert(rv != NULL);
287 assert(Py_SIZE(deque) <= deque->maxlen);
288 Py_DECREF(rv);
289 }
290}
291
292static void
293deque_trim_left(dequeobject *deque)
294{
295 if (deque->maxlen != -1 && Py_SIZE(deque) > deque->maxlen) {
296 PyObject *rv = deque_popleft(deque, NULL);
297 assert(rv != NULL);
298 assert(Py_SIZE(deque) <= deque->maxlen);
299 Py_DECREF(rv);
300 }
301}
302
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000303static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000304deque_append(dequeobject *deque, PyObject *item)
305{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000306 deque->state++;
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700307 if (deque->rightindex == BLOCKLEN - 1) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000308 block *b = newblock(Py_SIZE(deque));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000309 if (b == NULL)
310 return NULL;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000311 b->leftlink = deque->rightblock;
312 CHECK_END(deque->rightblock->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000313 deque->rightblock->rightlink = b;
314 deque->rightblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000315 MARK_END(b->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000316 deque->rightindex = -1;
317 }
318 Py_INCREF(item);
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000319 Py_SIZE(deque)++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000320 deque->rightindex++;
321 deque->rightblock->data[deque->rightindex] = item;
Raymond Hettingerf30f5b92015-03-02 22:23:37 -0800322 deque_trim_left(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000323 Py_RETURN_NONE;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000324}
325
326PyDoc_STRVAR(append_doc, "Add an element to the right side of the deque.");
327
328static PyObject *
329deque_appendleft(dequeobject *deque, PyObject *item)
330{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000331 deque->state++;
332 if (deque->leftindex == 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000333 block *b = newblock(Py_SIZE(deque));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000334 if (b == NULL)
335 return NULL;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000336 b->rightlink = deque->leftblock;
337 CHECK_END(deque->leftblock->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000338 deque->leftblock->leftlink = b;
339 deque->leftblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000340 MARK_END(b->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000341 deque->leftindex = BLOCKLEN;
342 }
343 Py_INCREF(item);
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000344 Py_SIZE(deque)++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000345 deque->leftindex--;
346 deque->leftblock->data[deque->leftindex] = item;
Raymond Hettingerf30f5b92015-03-02 22:23:37 -0800347 deque_trim_right(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000348 Py_RETURN_NONE;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000349}
350
351PyDoc_STRVAR(appendleft_doc, "Add an element to the left side of the deque.");
352
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000353
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000354/* Run an iterator to exhaustion. Shortcut for
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000355 the extend/extendleft methods when maxlen == 0. */
356static PyObject*
357consume_iterator(PyObject *it)
358{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000359 PyObject *item;
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000360
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000361 while ((item = PyIter_Next(it)) != NULL) {
362 Py_DECREF(item);
363 }
364 Py_DECREF(it);
365 if (PyErr_Occurred())
366 return NULL;
367 Py_RETURN_NONE;
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000368}
369
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000370static PyObject *
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000371deque_extend(dequeobject *deque, PyObject *iterable)
372{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000373 PyObject *it, *item;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 /* Handle case where id(deque) == id(iterable) */
376 if ((PyObject *)deque == iterable) {
377 PyObject *result;
378 PyObject *s = PySequence_List(iterable);
379 if (s == NULL)
380 return NULL;
381 result = deque_extend(deque, s);
382 Py_DECREF(s);
383 return result;
384 }
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000385
Raymond Hettingerd9c116c2013-07-09 00:13:21 -0700386 /* Space saving heuristic. Start filling from the left */
387 if (Py_SIZE(deque) == 0) {
388 assert(deque->leftblock == deque->rightblock);
389 assert(deque->leftindex == deque->rightindex+1);
390 deque->leftindex = 1;
391 deque->rightindex = 0;
392 }
393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000394 it = PyObject_GetIter(iterable);
395 if (it == NULL)
396 return NULL;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000397
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000398 if (deque->maxlen == 0)
399 return consume_iterator(it);
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000401 while ((item = PyIter_Next(it)) != NULL) {
402 deque->state++;
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700403 if (deque->rightindex == BLOCKLEN - 1) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000404 block *b = newblock(Py_SIZE(deque));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000405 if (b == NULL) {
406 Py_DECREF(item);
407 Py_DECREF(it);
408 return NULL;
409 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000410 b->leftlink = deque->rightblock;
411 CHECK_END(deque->rightblock->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000412 deque->rightblock->rightlink = b;
413 deque->rightblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000414 MARK_END(b->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000415 deque->rightindex = -1;
416 }
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000417 Py_SIZE(deque)++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000418 deque->rightindex++;
419 deque->rightblock->data[deque->rightindex] = item;
Raymond Hettingerf30f5b92015-03-02 22:23:37 -0800420 deque_trim_left(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 }
422 Py_DECREF(it);
423 if (PyErr_Occurred())
424 return NULL;
425 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 }
483 Py_DECREF(it);
484 if (PyErr_Occurred())
485 return NULL;
486 Py_RETURN_NONE;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000487}
488
Tim Peters1065f752004-10-01 01:03:29 +0000489PyDoc_STRVAR(extendleft_doc,
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000490"Extend the left side of the deque with elements from the iterable");
491
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000492static PyObject *
493deque_inplace_concat(dequeobject *deque, PyObject *other)
494{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000495 PyObject *result;
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 result = deque_extend(deque, other);
498 if (result == NULL)
499 return result;
500 Py_DECREF(result);
501 Py_INCREF(deque);
502 return (PyObject *)deque;
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000503}
504
Raymond Hettinger41290a62015-03-31 08:12:23 -0700505static PyObject *deque_copy(PyObject *deque);
506
507static PyObject *
508deque_concat(dequeobject *deque, PyObject *other)
509{
Benjamin Peterson1a629212015-04-04 10:52:36 -0400510 PyObject *new_deque, *result;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700511 int rv;
512
513 rv = PyObject_IsInstance(other, (PyObject *)&deque_type);
514 if (rv <= 0) {
515 if (rv == 0) {
516 PyErr_Format(PyExc_TypeError,
517 "can only concatenate deque (not \"%.200s\") to deque",
518 other->ob_type->tp_name);
519 }
520 return NULL;
521 }
522
523 new_deque = deque_copy((PyObject *)deque);
524 if (new_deque == NULL)
525 return NULL;
Benjamin Peterson1a629212015-04-04 10:52:36 -0400526 result = deque_extend((dequeobject *)new_deque, other);
527 if (result == NULL) {
528 Py_DECREF(new_deque);
529 return NULL;
530 }
531 Py_DECREF(result);
532 return new_deque;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700533}
534
535static void deque_clear(dequeobject *deque);
536
537static PyObject *
538deque_repeat(dequeobject *deque, Py_ssize_t n)
539{
540 dequeobject *new_deque;
541 PyObject *result;
542
543 /* XXX add a special case for when maxlen is defined */
544 if (n < 0)
545 n = 0;
546 else if (n > 0 && Py_SIZE(deque) > MAX_DEQUE_LEN / n)
547 return PyErr_NoMemory();
548
549 new_deque = (dequeobject *)deque_new(&deque_type, (PyObject *)NULL, (PyObject *)NULL);
550 new_deque->maxlen = deque->maxlen;
551
552 for ( ; n ; n--) {
553 result = deque_extend(new_deque, (PyObject *)deque);
554 if (result == NULL) {
555 Py_DECREF(new_deque);
556 return NULL;
557 }
558 Py_DECREF(result);
559 }
560 return (PyObject *)new_deque;
561}
562
563static PyObject *
564deque_inplace_repeat(dequeobject *deque, Py_ssize_t n)
565{
566 Py_ssize_t i, size;
567 PyObject *seq;
568 PyObject *rv;
569
570 size = Py_SIZE(deque);
571 if (size == 0 || n == 1) {
572 Py_INCREF(deque);
573 return (PyObject *)deque;
574 }
575
576 if (n <= 0) {
577 deque_clear(deque);
578 Py_INCREF(deque);
579 return (PyObject *)deque;
580 }
581
582 if (size > MAX_DEQUE_LEN / n) {
583 return PyErr_NoMemory();
584 }
585
586 if (size == 1) {
587 /* common case, repeating a single element */
588 PyObject *item = deque->leftblock->data[deque->leftindex];
589
590 if (deque->maxlen != -1 && n > deque->maxlen)
591 n = deque->maxlen;
592
593 for (i = 0 ; i < n-1 ; i++) {
594 rv = deque_append(deque, item);
595 if (rv == NULL)
596 return NULL;
597 Py_DECREF(rv);
598 }
599 Py_INCREF(deque);
600 return (PyObject *)deque;
601 }
602
603 seq = PySequence_List((PyObject *)deque);
604 if (seq == NULL)
605 return seq;
606
607 for (i = 0 ; i < n-1 ; i++) {
608 rv = deque_extend(deque, seq);
609 if (rv == NULL) {
610 Py_DECREF(seq);
611 return NULL;
612 }
613 Py_DECREF(rv);
614 }
615 Py_INCREF(deque);
616 Py_DECREF(seq);
617 return (PyObject *)deque;
618}
619
Raymond Hettinger54023152014-04-23 00:58:48 -0700620/* The rotate() method is part of the public API and is used internally
621as a primitive for other methods.
622
623Rotation by 1 or -1 is a common case, so any optimizations for high
624volume rotations should take care not to penalize the common case.
625
626Conceptually, a rotate by one is equivalent to a pop on one side and an
627append on the other. However, a pop/append pair is unnecessarily slow
628because it requires a incref/decref pair for an object located randomly
629in memory. It is better to just move the object pointer from one block
630to the next without changing the reference count.
631
632When moving batches of pointers, it is tempting to use memcpy() but that
633proved to be slower than a simple loop for a variety of reasons.
634Memcpy() cannot know in advance that we're copying pointers instead of
635bytes, that the source and destination are pointer aligned and
636non-overlapping, that moving just one pointer is a common case, that we
637never need to move more than BLOCKLEN pointers, and that at least one
638pointer is always moved.
639
640For high volume rotations, newblock() and freeblock() are never called
641more than once. Previously emptied blocks are immediately reused as a
642destination block. If a block is left-over at the end, it is freed.
643*/
644
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000645static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000646_deque_rotate(dequeobject *deque, Py_ssize_t n)
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000647{
Raymond Hettinger3959af92013-07-13 02:34:08 -0700648 block *b = NULL;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700649 block *leftblock = deque->leftblock;
650 block *rightblock = deque->rightblock;
651 Py_ssize_t leftindex = deque->leftindex;
652 Py_ssize_t rightindex = deque->rightindex;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000653 Py_ssize_t len=Py_SIZE(deque), halflen=len>>1;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700654 int rv = -1;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000655
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800656 if (len <= 1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000657 return 0;
658 if (n > halflen || n < -halflen) {
659 n %= len;
660 if (n > halflen)
661 n -= len;
662 else if (n < -halflen)
663 n += len;
664 }
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500665 assert(len > 1);
Raymond Hettingera4409c12013-02-04 00:08:12 -0500666 assert(-halflen <= n && n <= halflen);
Raymond Hettinger231ee4d2013-02-02 11:24:43 -0800667
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800668 deque->state++;
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500669 while (n > 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700670 if (leftindex == 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700671 if (b == NULL) {
Raymond Hettinger3959af92013-07-13 02:34:08 -0700672 b = newblock(len);
673 if (b == NULL)
674 goto done;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700675 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000676 b->rightlink = leftblock;
677 CHECK_END(leftblock->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700678 leftblock->leftlink = b;
679 leftblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000680 MARK_END(b->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700681 leftindex = BLOCKLEN;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700682 b = NULL;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800683 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700684 assert(leftindex > 0);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700685 {
686 PyObject **src, **dest;
687 Py_ssize_t m = n;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800688
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700689 if (m > rightindex + 1)
690 m = rightindex + 1;
691 if (m > leftindex)
692 m = leftindex;
693 assert (m > 0 && m <= len);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700694 rightindex -= m;
695 leftindex -= m;
Raymond Hettinger0e259f12015-02-01 22:53:41 -0800696 src = &rightblock->data[rightindex + 1];
697 dest = &leftblock->data[leftindex];
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700698 n -= m;
Raymond Hettinger840533b2013-07-13 17:03:58 -0700699 do {
Raymond Hettinger0e259f12015-02-01 22:53:41 -0800700 *(dest++) = *(src++);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700701 } while (--m);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700702 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700703 if (rightindex == -1) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700704 assert(leftblock != rightblock);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700705 assert(b == NULL);
Raymond Hettinger3959af92013-07-13 02:34:08 -0700706 b = rightblock;
Raymond Hettingerb97cc492013-07-21 01:51:07 -0700707 CHECK_NOT_END(rightblock->leftlink);
708 rightblock = rightblock->leftlink;
709 MARK_END(rightblock->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700710 rightindex = BLOCKLEN - 1;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800711 }
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800712 }
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500713 while (n < 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700714 if (rightindex == BLOCKLEN - 1) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700715 if (b == NULL) {
Raymond Hettinger3959af92013-07-13 02:34:08 -0700716 b = newblock(len);
717 if (b == NULL)
718 goto done;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700719 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000720 b->leftlink = rightblock;
721 CHECK_END(rightblock->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700722 rightblock->rightlink = b;
723 rightblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000724 MARK_END(b->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700725 rightindex = -1;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700726 b = NULL;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800727 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700728 assert (rightindex < BLOCKLEN - 1);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700729 {
730 PyObject **src, **dest;
731 Py_ssize_t m = -n;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800732
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700733 if (m > BLOCKLEN - leftindex)
734 m = BLOCKLEN - leftindex;
735 if (m > BLOCKLEN - 1 - rightindex)
736 m = BLOCKLEN - 1 - rightindex;
737 assert (m > 0 && m <= len);
738 src = &leftblock->data[leftindex];
739 dest = &rightblock->data[rightindex + 1];
740 leftindex += m;
741 rightindex += m;
742 n += m;
Raymond Hettinger840533b2013-07-13 17:03:58 -0700743 do {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700744 *(dest++) = *(src++);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700745 } while (--m);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700746 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700747 if (leftindex == BLOCKLEN) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700748 assert(leftblock != rightblock);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700749 assert(b == NULL);
Raymond Hettinger3959af92013-07-13 02:34:08 -0700750 b = leftblock;
Raymond Hettingerb97cc492013-07-21 01:51:07 -0700751 CHECK_NOT_END(leftblock->rightlink);
752 leftblock = leftblock->rightlink;
753 MARK_END(leftblock->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700754 leftindex = 0;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800755 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 }
Raymond Hettinger3959af92013-07-13 02:34:08 -0700757 rv = 0;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700758done:
Raymond Hettinger3959af92013-07-13 02:34:08 -0700759 if (b != NULL)
760 freeblock(b);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700761 deque->leftblock = leftblock;
762 deque->rightblock = rightblock;
763 deque->leftindex = leftindex;
764 deque->rightindex = rightindex;
765
766 return rv;
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000767}
768
769static PyObject *
770deque_rotate(dequeobject *deque, PyObject *args)
771{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000772 Py_ssize_t n=1;
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000774 if (!PyArg_ParseTuple(args, "|n:rotate", &n))
775 return NULL;
Raymond Hettinger6921c132015-03-21 02:03:40 -0700776 if (!_deque_rotate(deque, n))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000777 Py_RETURN_NONE;
778 return NULL;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000779}
780
Tim Peters1065f752004-10-01 01:03:29 +0000781PyDoc_STRVAR(rotate_doc,
Raymond Hettingeree33b272004-02-08 04:05:26 +0000782"Rotate the deque n steps to the right (default n=1). If n is negative, rotates left.");
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000783
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000784static PyObject *
785deque_reverse(dequeobject *deque, PyObject *unused)
786{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 block *leftblock = deque->leftblock;
788 block *rightblock = deque->rightblock;
789 Py_ssize_t leftindex = deque->leftindex;
790 Py_ssize_t rightindex = deque->rightindex;
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700791 Py_ssize_t n = Py_SIZE(deque) / 2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000792 Py_ssize_t i;
793 PyObject *tmp;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000794
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000795 for (i=0 ; i<n ; i++) {
796 /* Validate that pointers haven't met in the middle */
797 assert(leftblock != rightblock || leftindex < rightindex);
Raymond Hettinger82df9252013-07-07 01:43:42 -1000798 CHECK_NOT_END(leftblock);
799 CHECK_NOT_END(rightblock);
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000800
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000801 /* Swap */
802 tmp = leftblock->data[leftindex];
803 leftblock->data[leftindex] = rightblock->data[rightindex];
804 rightblock->data[rightindex] = tmp;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000805
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000806 /* Advance left block/index pair */
807 leftindex++;
808 if (leftindex == BLOCKLEN) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000809 leftblock = leftblock->rightlink;
810 leftindex = 0;
811 }
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000812
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000813 /* Step backwards with the right block/index pair */
814 rightindex--;
815 if (rightindex == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000816 rightblock = rightblock->leftlink;
817 rightindex = BLOCKLEN - 1;
818 }
819 }
820 Py_RETURN_NONE;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000821}
822
823PyDoc_STRVAR(reverse_doc,
824"D.reverse() -- reverse *IN PLACE*");
825
Raymond Hettinger44459de2010-04-03 23:20:46 +0000826static PyObject *
827deque_count(dequeobject *deque, PyObject *v)
828{
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000829 block *b = deque->leftblock;
830 Py_ssize_t index = deque->leftindex;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000831 Py_ssize_t n = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000832 Py_ssize_t i;
833 Py_ssize_t count = 0;
Raymond Hettingerf9d9c792015-03-02 22:47:46 -0800834 size_t start_state = deque->state;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 PyObject *item;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 int cmp;
Raymond Hettinger44459de2010-04-03 23:20:46 +0000837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 for (i=0 ; i<n ; i++) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000839 CHECK_NOT_END(b);
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000840 item = b->data[index];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000841 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
842 if (cmp > 0)
843 count++;
844 else if (cmp < 0)
845 return NULL;
Raymond Hettinger44459de2010-04-03 23:20:46 +0000846
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000847 if (start_state != deque->state) {
848 PyErr_SetString(PyExc_RuntimeError,
849 "deque mutated during iteration");
850 return NULL;
851 }
Raymond Hettinger44459de2010-04-03 23:20:46 +0000852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000853 /* Advance left block/index pair */
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000854 index++;
855 if (index == BLOCKLEN) {
856 b = b->rightlink;
857 index = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 }
859 }
860 return PyLong_FromSsize_t(count);
Raymond Hettinger44459de2010-04-03 23:20:46 +0000861}
862
863PyDoc_STRVAR(count_doc,
864"D.count(value) -> integer -- return number of occurrences of value");
865
Raymond Hettinger39dadf72015-03-20 16:38:56 -0700866static int
867deque_contains(dequeobject *deque, PyObject *v)
868{
869 block *b = deque->leftblock;
870 Py_ssize_t index = deque->leftindex;
871 Py_ssize_t n = Py_SIZE(deque);
872 Py_ssize_t i;
873 size_t start_state = deque->state;
874 PyObject *item;
875 int cmp;
876
877 for (i=0 ; i<n ; i++) {
878 CHECK_NOT_END(b);
879 item = b->data[index];
880 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
881 if (cmp) {
882 return cmp;
883 }
884 if (start_state != deque->state) {
885 PyErr_SetString(PyExc_RuntimeError,
886 "deque mutated during iteration");
887 return -1;
888 }
889 index++;
890 if (index == BLOCKLEN) {
891 b = b->rightlink;
892 index = 0;
893 }
894 }
895 return 0;
896}
897
Martin v. Löwis18e16552006-02-15 17:27:45 +0000898static Py_ssize_t
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000899deque_len(dequeobject *deque)
900{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000901 return Py_SIZE(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000902}
903
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000904static PyObject *
Raymond Hettinger32ea1652015-03-21 01:37:37 -0700905deque_index(dequeobject *deque, PyObject *args)
906{
907 Py_ssize_t i, start=0, stop=Py_SIZE(deque);
908 PyObject *v, *item;
909 block *b = deque->leftblock;
910 Py_ssize_t index = deque->leftindex;
911 size_t start_state = deque->state;
912
913 if (!PyArg_ParseTuple(args, "O|O&O&:index", &v,
914 _PyEval_SliceIndex, &start,
915 _PyEval_SliceIndex, &stop))
916 return NULL;
917 if (start < 0) {
918 start += Py_SIZE(deque);
919 if (start < 0)
920 start = 0;
921 }
922 if (stop < 0) {
923 stop += Py_SIZE(deque);
924 if (stop < 0)
925 stop = 0;
926 }
927
928 for (i=0 ; i<stop ; i++) {
929 if (i >= start) {
930 int cmp;
931 CHECK_NOT_END(b);
932 item = b->data[index];
933 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
934 if (cmp > 0)
935 return PyLong_FromSsize_t(i);
936 else if (cmp < 0)
937 return NULL;
938 if (start_state != deque->state) {
939 PyErr_SetString(PyExc_RuntimeError,
940 "deque mutated during iteration");
941 return NULL;
942 }
943 }
944 index++;
945 if (index == BLOCKLEN) {
946 b = b->rightlink;
947 index = 0;
948 }
949 }
950 PyErr_Format(PyExc_ValueError, "%R is not in deque", v);
951 return NULL;
952}
953
954PyDoc_STRVAR(index_doc,
955"D.index(value, [start, [stop]]) -> integer -- return first index of value.\n"
956"Raises ValueError if the value is not present.");
957
Raymond Hettinger551350a2015-03-24 00:19:53 -0700958/* insert(), remove(), and delitem() are implemented in terms of
959 rotate() for simplicity and reasonable performance near the end
960 points. If for some reason these methods become popular, it is not
961 hard to re-implement this using direct data movement (similar to
962 the code used in list slice assignments) and achieve a performance
Raymond Hettingerfef9c1b2015-03-24 21:12:57 -0700963 boost (by moving each pointer only once instead of twice).
Raymond Hettinger551350a2015-03-24 00:19:53 -0700964*/
965
Raymond Hettinger32ea1652015-03-21 01:37:37 -0700966static PyObject *
967deque_insert(dequeobject *deque, PyObject *args)
968{
969 Py_ssize_t index;
970 Py_ssize_t n = Py_SIZE(deque);
971 PyObject *value;
972 PyObject *rv;
973
974 if (!PyArg_ParseTuple(args, "nO:insert", &index, &value))
975 return NULL;
976 if (index >= n)
977 return deque_append(deque, value);
978 if (index <= -n || index == 0)
979 return deque_appendleft(deque, value);
980 if (_deque_rotate(deque, -index))
981 return NULL;
982 if (index < 0)
983 rv = deque_append(deque, value);
984 else
985 rv = deque_appendleft(deque, value);
986 if (rv == NULL)
987 return NULL;
988 Py_DECREF(rv);
989 if (_deque_rotate(deque, index))
990 return NULL;
991 Py_RETURN_NONE;
992}
993
994PyDoc_STRVAR(insert_doc,
995"D.insert(index, object) -- insert object before index");
996
997static PyObject *
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000998deque_remove(dequeobject *deque, PyObject *value)
999{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001000 Py_ssize_t i, n=Py_SIZE(deque);
Raymond Hettinger4aec61e2005-03-18 21:20:23 +00001001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 for (i=0 ; i<n ; i++) {
1003 PyObject *item = deque->leftblock->data[deque->leftindex];
1004 int cmp = PyObject_RichCompareBool(item, value, Py_EQ);
Raymond Hettingerd73202c2005-03-19 00:00:51 +00001005
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001006 if (Py_SIZE(deque) != n) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007 PyErr_SetString(PyExc_IndexError,
1008 "deque mutated during remove().");
1009 return NULL;
1010 }
1011 if (cmp > 0) {
1012 PyObject *tgt = deque_popleft(deque, NULL);
1013 assert (tgt != NULL);
Raymond Hettinger6921c132015-03-21 02:03:40 -07001014 if (_deque_rotate(deque, i))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 return NULL;
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001016 Py_DECREF(tgt);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 Py_RETURN_NONE;
1018 }
1019 else if (cmp < 0) {
1020 _deque_rotate(deque, i);
1021 return NULL;
1022 }
1023 _deque_rotate(deque, -1);
1024 }
1025 PyErr_SetString(PyExc_ValueError, "deque.remove(x): x not in deque");
1026 return NULL;
Raymond Hettinger4aec61e2005-03-18 21:20:23 +00001027}
1028
1029PyDoc_STRVAR(remove_doc,
1030"D.remove(value) -- remove first occurrence of value.");
1031
Benjamin Peterson0e5c48a2013-01-12 21:22:18 -05001032static void
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001033deque_clear(dequeobject *deque)
1034{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001035 PyObject *item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001036
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001037 while (Py_SIZE(deque)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 item = deque_pop(deque, NULL);
1039 assert (item != NULL);
1040 Py_DECREF(item);
1041 }
Raymond Hettinger87e69122015-03-02 23:32:02 -08001042 assert(deque->leftblock == deque->rightblock);
1043 assert(deque->leftindex - 1 == deque->rightindex);
1044 assert(Py_SIZE(deque) == 0);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001045}
1046
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001047static int
1048valid_index(Py_ssize_t i, Py_ssize_t limit)
1049{
1050 /* The cast to size_t let us use just a single comparison
1051 to check whether i is in the range: 0 <= i < limit */
1052 return (size_t) i < (size_t) limit;
1053}
1054
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001055static PyObject *
Benjamin Petersond6313712008-07-31 16:23:04 +00001056deque_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001057{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001058 block *b;
1059 PyObject *item;
1060 Py_ssize_t n, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001061
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001062 if (!valid_index(i, Py_SIZE(deque))) {
1063 PyErr_SetString(PyExc_IndexError, "deque index out of range");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001064 return NULL;
1065 }
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001067 if (i == 0) {
1068 i = deque->leftindex;
1069 b = deque->leftblock;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001070 } else if (i == Py_SIZE(deque) - 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 i = deque->rightindex;
1072 b = deque->rightblock;
1073 } else {
1074 i += deque->leftindex;
Raymond Hettingerc2083082015-02-28 23:29:16 -08001075 n = (Py_ssize_t)((size_t) i / BLOCKLEN);
1076 i = (Py_ssize_t)((size_t) i % BLOCKLEN);
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001077 if (index < (Py_SIZE(deque) >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 b = deque->leftblock;
1079 while (n--)
1080 b = b->rightlink;
1081 } else {
Raymond Hettinger63d1ff22015-02-28 07:41:30 -08001082 n = (Py_ssize_t)(
Raymond Hettingerc2083082015-02-28 23:29:16 -08001083 ((size_t)(deque->leftindex + Py_SIZE(deque) - 1))
Raymond Hettinger63d1ff22015-02-28 07:41:30 -08001084 / BLOCKLEN - n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001085 b = deque->rightblock;
1086 while (n--)
1087 b = b->leftlink;
1088 }
1089 }
1090 item = b->data[i];
1091 Py_INCREF(item);
1092 return item;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001093}
1094
1095static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001096deque_del_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001097{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098 PyObject *item;
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001099 int rv;
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001100
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001101 assert (i >= 0 && i < Py_SIZE(deque));
Raymond Hettinger6921c132015-03-21 02:03:40 -07001102 if (_deque_rotate(deque, -i))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001103 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001104 item = deque_popleft(deque, NULL);
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001105 rv = _deque_rotate(deque, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 assert (item != NULL);
1107 Py_DECREF(item);
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001108 return rv;
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001109}
1110
1111static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001112deque_ass_item(dequeobject *deque, Py_ssize_t i, PyObject *v)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001113{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001114 PyObject *old_value;
1115 block *b;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001116 Py_ssize_t n, len=Py_SIZE(deque), halflen=(len+1)>>1, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001117
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001118 if (!valid_index(i, len)) {
1119 PyErr_SetString(PyExc_IndexError, "deque index out of range");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001120 return -1;
1121 }
1122 if (v == NULL)
1123 return deque_del_item(deque, i);
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001125 i += deque->leftindex;
Raymond Hettingerc2083082015-02-28 23:29:16 -08001126 n = (Py_ssize_t)((size_t) i / BLOCKLEN);
1127 i = (Py_ssize_t)((size_t) i % BLOCKLEN);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001128 if (index <= halflen) {
1129 b = deque->leftblock;
1130 while (n--)
1131 b = b->rightlink;
1132 } else {
Raymond Hettingera473b9d2015-02-28 17:49:47 -08001133 n = (Py_ssize_t)(
Raymond Hettingerc2083082015-02-28 23:29:16 -08001134 ((size_t)(deque->leftindex + Py_SIZE(deque) - 1))
Raymond Hettingera473b9d2015-02-28 17:49:47 -08001135 / BLOCKLEN - n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136 b = deque->rightblock;
1137 while (n--)
1138 b = b->leftlink;
1139 }
1140 Py_INCREF(v);
1141 old_value = b->data[i];
1142 b->data[i] = v;
1143 Py_DECREF(old_value);
1144 return 0;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001145}
1146
1147static PyObject *
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001148deque_clearmethod(dequeobject *deque)
1149{
Benjamin Peterson0e5c48a2013-01-12 21:22:18 -05001150 deque_clear(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001151 Py_RETURN_NONE;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001152}
1153
1154PyDoc_STRVAR(clear_doc, "Remove all elements from the deque.");
1155
1156static void
1157deque_dealloc(dequeobject *deque)
1158{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001159 PyObject_GC_UnTrack(deque);
1160 if (deque->weakreflist != NULL)
1161 PyObject_ClearWeakRefs((PyObject *) deque);
1162 if (deque->leftblock != NULL) {
1163 deque_clear(deque);
1164 assert(deque->leftblock != NULL);
1165 freeblock(deque->leftblock);
1166 }
1167 deque->leftblock = NULL;
1168 deque->rightblock = NULL;
1169 Py_TYPE(deque)->tp_free(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001170}
1171
1172static int
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001173deque_traverse(dequeobject *deque, visitproc visit, void *arg)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001174{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001175 block *b;
1176 PyObject *item;
1177 Py_ssize_t index;
1178 Py_ssize_t indexlo = deque->leftindex;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001179
Raymond Hettinger5bfa8672013-07-06 11:58:09 -10001180 for (b = deque->leftblock; b != deque->rightblock; b = b->rightlink) {
1181 for (index = indexlo; index < BLOCKLEN ; index++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 item = b->data[index];
1183 Py_VISIT(item);
1184 }
1185 indexlo = 0;
1186 }
Raymond Hettinger5bfa8672013-07-06 11:58:09 -10001187 for (index = indexlo; index <= deque->rightindex; index++) {
1188 item = b->data[index];
1189 Py_VISIT(item);
1190 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001191 return 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001192}
1193
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001194static PyObject *
1195deque_copy(PyObject *deque)
1196{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001197 if (((dequeobject *)deque)->maxlen == -1)
1198 return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "O", deque, NULL);
1199 else
1200 return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "Oi",
1201 deque, ((dequeobject *)deque)->maxlen, NULL);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001202}
1203
1204PyDoc_STRVAR(copy_doc, "Return a shallow copy of a deque.");
1205
1206static PyObject *
1207deque_reduce(dequeobject *deque)
1208{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 PyObject *dict, *result, *aslist;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001210 _Py_IDENTIFIER(__dict__);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001211
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001212 dict = _PyObject_GetAttrId((PyObject *)deque, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 if (dict == NULL)
1214 PyErr_Clear();
1215 aslist = PySequence_List((PyObject *)deque);
1216 if (aslist == NULL) {
1217 Py_XDECREF(dict);
1218 return NULL;
1219 }
1220 if (dict == NULL) {
1221 if (deque->maxlen == -1)
1222 result = Py_BuildValue("O(O)", Py_TYPE(deque), aslist);
1223 else
1224 result = Py_BuildValue("O(On)", Py_TYPE(deque), aslist, deque->maxlen);
1225 } else {
1226 if (deque->maxlen == -1)
1227 result = Py_BuildValue("O(OO)O", Py_TYPE(deque), aslist, Py_None, dict);
1228 else
1229 result = Py_BuildValue("O(On)O", Py_TYPE(deque), aslist, deque->maxlen, dict);
1230 }
1231 Py_XDECREF(dict);
1232 Py_DECREF(aslist);
1233 return result;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001234}
1235
1236PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
1237
1238static PyObject *
1239deque_repr(PyObject *deque)
1240{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001241 PyObject *aslist, *result;
1242 int i;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001244 i = Py_ReprEnter(deque);
1245 if (i != 0) {
1246 if (i < 0)
1247 return NULL;
1248 return PyUnicode_FromString("[...]");
1249 }
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001251 aslist = PySequence_List(deque);
1252 if (aslist == NULL) {
1253 Py_ReprLeave(deque);
1254 return NULL;
1255 }
1256 if (((dequeobject *)deque)->maxlen != -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001257 result = PyUnicode_FromFormat("deque(%R, maxlen=%zd)",
1258 aslist, ((dequeobject *)deque)->maxlen);
1259 else
1260 result = PyUnicode_FromFormat("deque(%R)", aslist);
1261 Py_DECREF(aslist);
1262 Py_ReprLeave(deque);
1263 return result;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001264}
1265
Raymond Hettinger738ec902004-02-29 02:15:56 +00001266static PyObject *
1267deque_richcompare(PyObject *v, PyObject *w, int op)
1268{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001269 PyObject *it1=NULL, *it2=NULL, *x, *y;
1270 Py_ssize_t vs, ws;
1271 int b, cmp=-1;
Raymond Hettinger738ec902004-02-29 02:15:56 +00001272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001273 if (!PyObject_TypeCheck(v, &deque_type) ||
1274 !PyObject_TypeCheck(w, &deque_type)) {
Brian Curtindfc80e32011-08-10 20:28:54 -05001275 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001276 }
Raymond Hettinger738ec902004-02-29 02:15:56 +00001277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001278 /* Shortcuts */
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001279 vs = Py_SIZE((dequeobject *)v);
1280 ws = Py_SIZE((dequeobject *)w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001281 if (op == Py_EQ) {
1282 if (v == w)
1283 Py_RETURN_TRUE;
1284 if (vs != ws)
1285 Py_RETURN_FALSE;
1286 }
1287 if (op == Py_NE) {
1288 if (v == w)
1289 Py_RETURN_FALSE;
1290 if (vs != ws)
1291 Py_RETURN_TRUE;
1292 }
Raymond Hettinger738ec902004-02-29 02:15:56 +00001293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001294 /* Search for the first index where items are different */
1295 it1 = PyObject_GetIter(v);
1296 if (it1 == NULL)
1297 goto done;
1298 it2 = PyObject_GetIter(w);
1299 if (it2 == NULL)
1300 goto done;
1301 for (;;) {
1302 x = PyIter_Next(it1);
1303 if (x == NULL && PyErr_Occurred())
1304 goto done;
1305 y = PyIter_Next(it2);
1306 if (x == NULL || y == NULL)
1307 break;
1308 b = PyObject_RichCompareBool(x, y, Py_EQ);
1309 if (b == 0) {
1310 cmp = PyObject_RichCompareBool(x, y, op);
1311 Py_DECREF(x);
1312 Py_DECREF(y);
1313 goto done;
1314 }
1315 Py_DECREF(x);
1316 Py_DECREF(y);
1317 if (b == -1)
1318 goto done;
1319 }
1320 /* We reached the end of one deque or both */
1321 Py_XDECREF(x);
1322 Py_XDECREF(y);
1323 if (PyErr_Occurred())
1324 goto done;
1325 switch (op) {
1326 case Py_LT: cmp = y != NULL; break; /* if w was longer */
1327 case Py_LE: cmp = x == NULL; break; /* if v was not longer */
1328 case Py_EQ: cmp = x == y; break; /* if we reached the end of both */
1329 case Py_NE: cmp = x != y; break; /* if one deque continues */
1330 case Py_GT: cmp = x != NULL; break; /* if v was longer */
1331 case Py_GE: cmp = y == NULL; break; /* if w was not longer */
1332 }
Tim Peters1065f752004-10-01 01:03:29 +00001333
Raymond Hettinger738ec902004-02-29 02:15:56 +00001334done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001335 Py_XDECREF(it1);
1336 Py_XDECREF(it2);
1337 if (cmp == 1)
1338 Py_RETURN_TRUE;
1339 if (cmp == 0)
1340 Py_RETURN_FALSE;
1341 return NULL;
Raymond Hettinger738ec902004-02-29 02:15:56 +00001342}
1343
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001344static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001345deque_init(dequeobject *deque, PyObject *args, PyObject *kwdargs)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001346{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001347 PyObject *iterable = NULL;
1348 PyObject *maxlenobj = NULL;
1349 Py_ssize_t maxlen = -1;
1350 char *kwlist[] = {"iterable", "maxlen", 0};
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001352 if (!PyArg_ParseTupleAndKeywords(args, kwdargs, "|OO:deque", kwlist, &iterable, &maxlenobj))
1353 return -1;
1354 if (maxlenobj != NULL && maxlenobj != Py_None) {
1355 maxlen = PyLong_AsSsize_t(maxlenobj);
1356 if (maxlen == -1 && PyErr_Occurred())
1357 return -1;
1358 if (maxlen < 0) {
1359 PyErr_SetString(PyExc_ValueError, "maxlen must be non-negative");
1360 return -1;
1361 }
1362 }
1363 deque->maxlen = maxlen;
1364 deque_clear(deque);
1365 if (iterable != NULL) {
1366 PyObject *rv = deque_extend(deque, iterable);
1367 if (rv == NULL)
1368 return -1;
1369 Py_DECREF(rv);
1370 }
1371 return 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001372}
1373
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001374static PyObject *
Jesus Cea16e2fca2012-08-03 14:49:42 +02001375deque_sizeof(dequeobject *deque, void *unused)
1376{
1377 Py_ssize_t res;
1378 Py_ssize_t blocks;
1379
1380 res = sizeof(dequeobject);
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001381 blocks = (deque->leftindex + Py_SIZE(deque) + BLOCKLEN - 1) / BLOCKLEN;
1382 assert(deque->leftindex + Py_SIZE(deque) - 1 ==
Jesus Cea16e2fca2012-08-03 14:49:42 +02001383 (blocks - 1) * BLOCKLEN + deque->rightindex);
1384 res += blocks * sizeof(block);
1385 return PyLong_FromSsize_t(res);
1386}
1387
1388PyDoc_STRVAR(sizeof_doc,
1389"D.__sizeof__() -- size of D in memory, in bytes");
1390
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001391static int
1392deque_bool(dequeobject *deque)
1393{
1394 return Py_SIZE(deque) != 0;
1395}
1396
Jesus Cea16e2fca2012-08-03 14:49:42 +02001397static PyObject *
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001398deque_get_maxlen(dequeobject *deque)
1399{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001400 if (deque->maxlen == -1)
1401 Py_RETURN_NONE;
1402 return PyLong_FromSsize_t(deque->maxlen);
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001403}
1404
Raymond Hettinger41290a62015-03-31 08:12:23 -07001405
1406/* deque object ********************************************************/
1407
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001408static PyGetSetDef deque_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001409 {"maxlen", (getter)deque_get_maxlen, (setter)NULL,
1410 "maximum size of a deque or None if unbounded"},
1411 {0}
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001412};
1413
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001414static PySequenceMethods deque_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001415 (lenfunc)deque_len, /* sq_length */
Raymond Hettinger41290a62015-03-31 08:12:23 -07001416 (binaryfunc)deque_concat, /* sq_concat */
1417 (ssizeargfunc)deque_repeat, /* sq_repeat */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001418 (ssizeargfunc)deque_item, /* sq_item */
1419 0, /* sq_slice */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001420 (ssizeobjargproc)deque_ass_item, /* sq_ass_item */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001421 0, /* sq_ass_slice */
Raymond Hettinger39dadf72015-03-20 16:38:56 -07001422 (objobjproc)deque_contains, /* sq_contains */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001423 (binaryfunc)deque_inplace_concat, /* sq_inplace_concat */
Raymond Hettinger41290a62015-03-31 08:12:23 -07001424 (ssizeargfunc)deque_inplace_repeat, /* sq_inplace_repeat */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001425};
1426
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001427static PyNumberMethods deque_as_number = {
1428 0, /* nb_add */
1429 0, /* nb_subtract */
1430 0, /* nb_multiply */
1431 0, /* nb_remainder */
1432 0, /* nb_divmod */
1433 0, /* nb_power */
1434 0, /* nb_negative */
1435 0, /* nb_positive */
1436 0, /* nb_absolute */
1437 (inquiry)deque_bool, /* nb_bool */
1438 0, /* nb_invert */
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001439 };
1440
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001441static PyObject *deque_iter(dequeobject *deque);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001442static PyObject *deque_reviter(dequeobject *deque);
Tim Peters1065f752004-10-01 01:03:29 +00001443PyDoc_STRVAR(reversed_doc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001444 "D.__reversed__() -- return a reverse iterator over the deque");
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001445
1446static PyMethodDef deque_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001447 {"append", (PyCFunction)deque_append,
1448 METH_O, append_doc},
1449 {"appendleft", (PyCFunction)deque_appendleft,
1450 METH_O, appendleft_doc},
1451 {"clear", (PyCFunction)deque_clearmethod,
1452 METH_NOARGS, clear_doc},
1453 {"__copy__", (PyCFunction)deque_copy,
1454 METH_NOARGS, copy_doc},
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001455 {"copy", (PyCFunction)deque_copy,
1456 METH_NOARGS, copy_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001457 {"count", (PyCFunction)deque_count,
Raymond Hettinger0f6f9472015-03-21 01:42:10 -07001458 METH_O, count_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001459 {"extend", (PyCFunction)deque_extend,
1460 METH_O, extend_doc},
1461 {"extendleft", (PyCFunction)deque_extendleft,
1462 METH_O, extendleft_doc},
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001463 {"index", (PyCFunction)deque_index,
1464 METH_VARARGS, index_doc},
1465 {"insert", (PyCFunction)deque_insert,
1466 METH_VARARGS, insert_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001467 {"pop", (PyCFunction)deque_pop,
1468 METH_NOARGS, pop_doc},
1469 {"popleft", (PyCFunction)deque_popleft,
1470 METH_NOARGS, popleft_doc},
Raymond Hettinger0f6f9472015-03-21 01:42:10 -07001471 {"__reduce__", (PyCFunction)deque_reduce,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001472 METH_NOARGS, reduce_doc},
1473 {"remove", (PyCFunction)deque_remove,
1474 METH_O, remove_doc},
1475 {"__reversed__", (PyCFunction)deque_reviter,
1476 METH_NOARGS, reversed_doc},
1477 {"reverse", (PyCFunction)deque_reverse,
1478 METH_NOARGS, reverse_doc},
1479 {"rotate", (PyCFunction)deque_rotate,
Jesus Cea16e2fca2012-08-03 14:49:42 +02001480 METH_VARARGS, rotate_doc},
1481 {"__sizeof__", (PyCFunction)deque_sizeof,
1482 METH_NOARGS, sizeof_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001483 {NULL, NULL} /* sentinel */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001484};
1485
1486PyDoc_STRVAR(deque_doc,
Andrew Svetlov6a5c7c32012-10-31 11:50:40 +02001487"deque([iterable[, maxlen]]) --> deque object\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001488\n\
Raymond Hettinger41290a62015-03-31 08:12:23 -07001489A list-like sequence optimized for data accesses near its endpoints.");
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001490
Neal Norwitz87f10132004-02-29 15:40:53 +00001491static PyTypeObject deque_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001492 PyVarObject_HEAD_INIT(NULL, 0)
1493 "collections.deque", /* tp_name */
1494 sizeof(dequeobject), /* tp_basicsize */
1495 0, /* tp_itemsize */
1496 /* methods */
1497 (destructor)deque_dealloc, /* tp_dealloc */
1498 0, /* tp_print */
1499 0, /* tp_getattr */
1500 0, /* tp_setattr */
1501 0, /* tp_reserved */
1502 deque_repr, /* tp_repr */
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001503 &deque_as_number, /* tp_as_number */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001504 &deque_as_sequence, /* tp_as_sequence */
1505 0, /* tp_as_mapping */
Georg Brandlf038b322010-10-18 07:35:09 +00001506 PyObject_HashNotImplemented, /* tp_hash */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001507 0, /* tp_call */
1508 0, /* tp_str */
1509 PyObject_GenericGetAttr, /* tp_getattro */
1510 0, /* tp_setattro */
1511 0, /* tp_as_buffer */
1512 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
Georg Brandlf038b322010-10-18 07:35:09 +00001513 /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001514 deque_doc, /* tp_doc */
1515 (traverseproc)deque_traverse, /* tp_traverse */
1516 (inquiry)deque_clear, /* tp_clear */
1517 (richcmpfunc)deque_richcompare, /* tp_richcompare */
Georg Brandlf038b322010-10-18 07:35:09 +00001518 offsetof(dequeobject, weakreflist), /* tp_weaklistoffset*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001519 (getiterfunc)deque_iter, /* tp_iter */
1520 0, /* tp_iternext */
1521 deque_methods, /* tp_methods */
1522 0, /* tp_members */
Georg Brandlf038b322010-10-18 07:35:09 +00001523 deque_getset, /* tp_getset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001524 0, /* tp_base */
1525 0, /* tp_dict */
1526 0, /* tp_descr_get */
1527 0, /* tp_descr_set */
1528 0, /* tp_dictoffset */
1529 (initproc)deque_init, /* tp_init */
1530 PyType_GenericAlloc, /* tp_alloc */
1531 deque_new, /* tp_new */
1532 PyObject_GC_Del, /* tp_free */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001533};
1534
1535/*********************** Deque Iterator **************************/
1536
1537typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001538 PyObject_HEAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001539 block *b;
Raymond Hettinger87e69122015-03-02 23:32:02 -08001540 Py_ssize_t index;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001541 dequeobject *deque;
Raymond Hettingerf9d9c792015-03-02 22:47:46 -08001542 size_t state; /* state when the iterator is created */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001543 Py_ssize_t counter; /* number of items remaining for iteration */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001544} dequeiterobject;
1545
Martin v. Löwis59683e82008-06-13 07:50:45 +00001546static PyTypeObject dequeiter_type;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001547
1548static PyObject *
1549deque_iter(dequeobject *deque)
1550{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001551 dequeiterobject *it;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001553 it = PyObject_GC_New(dequeiterobject, &dequeiter_type);
1554 if (it == NULL)
1555 return NULL;
1556 it->b = deque->leftblock;
1557 it->index = deque->leftindex;
1558 Py_INCREF(deque);
1559 it->deque = deque;
1560 it->state = deque->state;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001561 it->counter = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001562 PyObject_GC_Track(it);
1563 return (PyObject *)it;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001564}
1565
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001566static int
1567dequeiter_traverse(dequeiterobject *dio, visitproc visit, void *arg)
1568{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001569 Py_VISIT(dio->deque);
1570 return 0;
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001571}
1572
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001573static void
1574dequeiter_dealloc(dequeiterobject *dio)
1575{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001576 Py_XDECREF(dio->deque);
1577 PyObject_GC_Del(dio);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001578}
1579
1580static PyObject *
1581dequeiter_next(dequeiterobject *it)
1582{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001583 PyObject *item;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001585 if (it->deque->state != it->state) {
1586 it->counter = 0;
1587 PyErr_SetString(PyExc_RuntimeError,
1588 "deque mutated during iteration");
1589 return NULL;
1590 }
1591 if (it->counter == 0)
1592 return NULL;
1593 assert (!(it->b == it->deque->rightblock &&
1594 it->index > it->deque->rightindex));
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001596 item = it->b->data[it->index];
1597 it->index++;
1598 it->counter--;
1599 if (it->index == BLOCKLEN && it->counter > 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -10001600 CHECK_NOT_END(it->b->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001601 it->b = it->b->rightlink;
1602 it->index = 0;
1603 }
1604 Py_INCREF(item);
1605 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001606}
1607
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001608static PyObject *
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001609dequeiter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1610{
1611 Py_ssize_t i, index=0;
1612 PyObject *deque;
1613 dequeiterobject *it;
1614 if (!PyArg_ParseTuple(args, "O!|n", &deque_type, &deque, &index))
1615 return NULL;
1616 assert(type == &dequeiter_type);
1617
1618 it = (dequeiterobject*)deque_iter((dequeobject *)deque);
1619 if (!it)
1620 return NULL;
1621 /* consume items from the queue */
1622 for(i=0; i<index; i++) {
1623 PyObject *item = dequeiter_next(it);
1624 if (item) {
1625 Py_DECREF(item);
1626 } else {
1627 if (it->counter) {
1628 Py_DECREF(it);
1629 return NULL;
1630 } else
1631 break;
1632 }
1633 }
1634 return (PyObject*)it;
1635}
1636
1637static PyObject *
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001638dequeiter_len(dequeiterobject *it)
1639{
Antoine Pitrou554f3342010-08-17 18:30:06 +00001640 return PyLong_FromSsize_t(it->counter);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001641}
1642
Armin Rigof5b3e362006-02-11 21:32:43 +00001643PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001644
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001645static PyObject *
1646dequeiter_reduce(dequeiterobject *it)
1647{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001648 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 +00001649}
1650
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001651static PyMethodDef dequeiter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001652 {"__length_hint__", (PyCFunction)dequeiter_len, METH_NOARGS, length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001653 {"__reduce__", (PyCFunction)dequeiter_reduce, METH_NOARGS, reduce_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001654 {NULL, NULL} /* sentinel */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001655};
1656
Martin v. Löwis59683e82008-06-13 07:50:45 +00001657static PyTypeObject dequeiter_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001658 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger87e69122015-03-02 23:32:02 -08001659 "_collections._deque_iterator", /* tp_name */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001660 sizeof(dequeiterobject), /* tp_basicsize */
1661 0, /* tp_itemsize */
1662 /* methods */
1663 (destructor)dequeiter_dealloc, /* tp_dealloc */
1664 0, /* tp_print */
1665 0, /* tp_getattr */
1666 0, /* tp_setattr */
1667 0, /* tp_reserved */
1668 0, /* tp_repr */
1669 0, /* tp_as_number */
1670 0, /* tp_as_sequence */
1671 0, /* tp_as_mapping */
1672 0, /* tp_hash */
1673 0, /* tp_call */
1674 0, /* tp_str */
1675 PyObject_GenericGetAttr, /* tp_getattro */
1676 0, /* tp_setattro */
1677 0, /* tp_as_buffer */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001678 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001679 0, /* tp_doc */
1680 (traverseproc)dequeiter_traverse, /* tp_traverse */
1681 0, /* tp_clear */
1682 0, /* tp_richcompare */
1683 0, /* tp_weaklistoffset */
1684 PyObject_SelfIter, /* tp_iter */
1685 (iternextfunc)dequeiter_next, /* tp_iternext */
1686 dequeiter_methods, /* tp_methods */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001687 0, /* tp_members */
1688 0, /* tp_getset */
1689 0, /* tp_base */
1690 0, /* tp_dict */
1691 0, /* tp_descr_get */
1692 0, /* tp_descr_set */
1693 0, /* tp_dictoffset */
1694 0, /* tp_init */
1695 0, /* tp_alloc */
1696 dequeiter_new, /* tp_new */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001697 0,
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001698};
1699
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001700/*********************** Deque Reverse Iterator **************************/
1701
Martin v. Löwis59683e82008-06-13 07:50:45 +00001702static PyTypeObject dequereviter_type;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001703
1704static PyObject *
1705deque_reviter(dequeobject *deque)
1706{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001707 dequeiterobject *it;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001709 it = PyObject_GC_New(dequeiterobject, &dequereviter_type);
1710 if (it == NULL)
1711 return NULL;
1712 it->b = deque->rightblock;
1713 it->index = deque->rightindex;
1714 Py_INCREF(deque);
1715 it->deque = deque;
1716 it->state = deque->state;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001717 it->counter = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001718 PyObject_GC_Track(it);
1719 return (PyObject *)it;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001720}
1721
1722static PyObject *
1723dequereviter_next(dequeiterobject *it)
1724{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001725 PyObject *item;
1726 if (it->counter == 0)
1727 return NULL;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001728
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001729 if (it->deque->state != it->state) {
1730 it->counter = 0;
1731 PyErr_SetString(PyExc_RuntimeError,
1732 "deque mutated during iteration");
1733 return NULL;
1734 }
1735 assert (!(it->b == it->deque->leftblock &&
1736 it->index < it->deque->leftindex));
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001738 item = it->b->data[it->index];
1739 it->index--;
1740 it->counter--;
1741 if (it->index == -1 && it->counter > 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -10001742 CHECK_NOT_END(it->b->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001743 it->b = it->b->leftlink;
1744 it->index = BLOCKLEN - 1;
1745 }
1746 Py_INCREF(item);
1747 return item;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001748}
1749
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001750static PyObject *
1751dequereviter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1752{
1753 Py_ssize_t i, index=0;
1754 PyObject *deque;
1755 dequeiterobject *it;
1756 if (!PyArg_ParseTuple(args, "O!|n", &deque_type, &deque, &index))
1757 return NULL;
1758 assert(type == &dequereviter_type);
1759
1760 it = (dequeiterobject*)deque_reviter((dequeobject *)deque);
1761 if (!it)
1762 return NULL;
1763 /* consume items from the queue */
1764 for(i=0; i<index; i++) {
1765 PyObject *item = dequereviter_next(it);
1766 if (item) {
1767 Py_DECREF(item);
1768 } else {
1769 if (it->counter) {
1770 Py_DECREF(it);
1771 return NULL;
1772 } else
1773 break;
1774 }
1775 }
1776 return (PyObject*)it;
1777}
1778
Martin v. Löwis59683e82008-06-13 07:50:45 +00001779static PyTypeObject dequereviter_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001780 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger87e69122015-03-02 23:32:02 -08001781 "_collections._deque_reverse_iterator", /* tp_name */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001782 sizeof(dequeiterobject), /* tp_basicsize */
1783 0, /* tp_itemsize */
1784 /* methods */
1785 (destructor)dequeiter_dealloc, /* tp_dealloc */
1786 0, /* tp_print */
1787 0, /* tp_getattr */
1788 0, /* tp_setattr */
1789 0, /* tp_reserved */
1790 0, /* tp_repr */
1791 0, /* tp_as_number */
1792 0, /* tp_as_sequence */
1793 0, /* tp_as_mapping */
1794 0, /* tp_hash */
1795 0, /* tp_call */
1796 0, /* tp_str */
1797 PyObject_GenericGetAttr, /* tp_getattro */
1798 0, /* tp_setattro */
1799 0, /* tp_as_buffer */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001800 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001801 0, /* tp_doc */
1802 (traverseproc)dequeiter_traverse, /* tp_traverse */
1803 0, /* tp_clear */
1804 0, /* tp_richcompare */
1805 0, /* tp_weaklistoffset */
1806 PyObject_SelfIter, /* tp_iter */
1807 (iternextfunc)dequereviter_next, /* tp_iternext */
1808 dequeiter_methods, /* tp_methods */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001809 0, /* tp_members */
1810 0, /* tp_getset */
1811 0, /* tp_base */
1812 0, /* tp_dict */
1813 0, /* tp_descr_get */
1814 0, /* tp_descr_set */
1815 0, /* tp_dictoffset */
1816 0, /* tp_init */
1817 0, /* tp_alloc */
1818 dequereviter_new, /* tp_new */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001819 0,
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001820};
1821
Guido van Rossum1968ad32006-02-25 22:38:04 +00001822/* defaultdict type *********************************************************/
1823
1824typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001825 PyDictObject dict;
1826 PyObject *default_factory;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001827} defdictobject;
1828
1829static PyTypeObject defdict_type; /* Forward */
1830
1831PyDoc_STRVAR(defdict_missing_doc,
1832"__missing__(key) # Called by __getitem__ for missing key; pseudo-code:\n\
Guido van Rossumd8faa362007-04-27 19:54:29 +00001833 if self.default_factory is None: raise KeyError((key,))\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00001834 self[key] = value = self.default_factory()\n\
1835 return value\n\
1836");
1837
1838static PyObject *
1839defdict_missing(defdictobject *dd, PyObject *key)
1840{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001841 PyObject *factory = dd->default_factory;
1842 PyObject *value;
1843 if (factory == NULL || factory == Py_None) {
1844 /* XXX Call dict.__missing__(key) */
1845 PyObject *tup;
1846 tup = PyTuple_Pack(1, key);
1847 if (!tup) return NULL;
1848 PyErr_SetObject(PyExc_KeyError, tup);
1849 Py_DECREF(tup);
1850 return NULL;
1851 }
1852 value = PyEval_CallObject(factory, NULL);
1853 if (value == NULL)
1854 return value;
1855 if (PyObject_SetItem((PyObject *)dd, key, value) < 0) {
1856 Py_DECREF(value);
1857 return NULL;
1858 }
1859 return value;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001860}
1861
1862PyDoc_STRVAR(defdict_copy_doc, "D.copy() -> a shallow copy of D.");
1863
1864static PyObject *
1865defdict_copy(defdictobject *dd)
1866{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001867 /* This calls the object's class. That only works for subclasses
1868 whose class constructor has the same signature. Subclasses that
1869 define a different constructor signature must override copy().
1870 */
Raymond Hettinger54628fa2009-08-04 19:16:39 +00001871
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001872 if (dd->default_factory == NULL)
1873 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd), Py_None, dd, NULL);
1874 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd),
1875 dd->default_factory, dd, NULL);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001876}
1877
1878static PyObject *
1879defdict_reduce(defdictobject *dd)
1880{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001881 /* __reduce__ must return a 5-tuple as follows:
Guido van Rossum1968ad32006-02-25 22:38:04 +00001882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001883 - factory function
1884 - tuple of args for the factory function
1885 - additional state (here None)
1886 - sequence iterator (here None)
1887 - dictionary iterator (yielding successive (key, value) pairs
Guido van Rossum1968ad32006-02-25 22:38:04 +00001888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001889 This API is used by pickle.py and copy.py.
Guido van Rossum1968ad32006-02-25 22:38:04 +00001890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001891 For this to be useful with pickle.py, the default_factory
1892 must be picklable; e.g., None, a built-in, or a global
1893 function in a module or package.
Guido van Rossum1968ad32006-02-25 22:38:04 +00001894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001895 Both shallow and deep copying are supported, but for deep
1896 copying, the default_factory must be deep-copyable; e.g. None,
1897 or a built-in (functions are not copyable at this time).
Guido van Rossum1968ad32006-02-25 22:38:04 +00001898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001899 This only works for subclasses as long as their constructor
1900 signature is compatible; the first argument must be the
1901 optional default_factory, defaulting to None.
1902 */
1903 PyObject *args;
1904 PyObject *items;
1905 PyObject *iter;
1906 PyObject *result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001907 _Py_IDENTIFIER(items);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001908
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001909 if (dd->default_factory == NULL || dd->default_factory == Py_None)
1910 args = PyTuple_New(0);
1911 else
1912 args = PyTuple_Pack(1, dd->default_factory);
1913 if (args == NULL)
1914 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001915 items = _PyObject_CallMethodId((PyObject *)dd, &PyId_items, "()");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001916 if (items == NULL) {
1917 Py_DECREF(args);
1918 return NULL;
1919 }
1920 iter = PyObject_GetIter(items);
1921 if (iter == NULL) {
1922 Py_DECREF(items);
1923 Py_DECREF(args);
1924 return NULL;
1925 }
1926 result = PyTuple_Pack(5, Py_TYPE(dd), args,
1927 Py_None, Py_None, iter);
1928 Py_DECREF(iter);
1929 Py_DECREF(items);
1930 Py_DECREF(args);
1931 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001932}
1933
1934static PyMethodDef defdict_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001935 {"__missing__", (PyCFunction)defdict_missing, METH_O,
1936 defdict_missing_doc},
1937 {"copy", (PyCFunction)defdict_copy, METH_NOARGS,
1938 defdict_copy_doc},
1939 {"__copy__", (PyCFunction)defdict_copy, METH_NOARGS,
1940 defdict_copy_doc},
1941 {"__reduce__", (PyCFunction)defdict_reduce, METH_NOARGS,
1942 reduce_doc},
1943 {NULL}
Guido van Rossum1968ad32006-02-25 22:38:04 +00001944};
1945
1946static PyMemberDef defdict_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001947 {"default_factory", T_OBJECT,
1948 offsetof(defdictobject, default_factory), 0,
1949 PyDoc_STR("Factory for default value called by __missing__().")},
1950 {NULL}
Guido van Rossum1968ad32006-02-25 22:38:04 +00001951};
1952
1953static void
1954defdict_dealloc(defdictobject *dd)
1955{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001956 Py_CLEAR(dd->default_factory);
1957 PyDict_Type.tp_dealloc((PyObject *)dd);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001958}
1959
Guido van Rossum1968ad32006-02-25 22:38:04 +00001960static PyObject *
1961defdict_repr(defdictobject *dd)
1962{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001963 PyObject *baserepr;
1964 PyObject *defrepr;
1965 PyObject *result;
1966 baserepr = PyDict_Type.tp_repr((PyObject *)dd);
1967 if (baserepr == NULL)
1968 return NULL;
1969 if (dd->default_factory == NULL)
1970 defrepr = PyUnicode_FromString("None");
1971 else
1972 {
1973 int status = Py_ReprEnter(dd->default_factory);
1974 if (status != 0) {
Antoine Pitrouf5f1fe02012-02-15 02:42:46 +01001975 if (status < 0) {
1976 Py_DECREF(baserepr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001977 return NULL;
Antoine Pitrouf5f1fe02012-02-15 02:42:46 +01001978 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001979 defrepr = PyUnicode_FromString("...");
1980 }
1981 else
1982 defrepr = PyObject_Repr(dd->default_factory);
1983 Py_ReprLeave(dd->default_factory);
1984 }
1985 if (defrepr == NULL) {
1986 Py_DECREF(baserepr);
1987 return NULL;
1988 }
1989 result = PyUnicode_FromFormat("defaultdict(%U, %U)",
1990 defrepr, baserepr);
1991 Py_DECREF(defrepr);
1992 Py_DECREF(baserepr);
1993 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001994}
1995
1996static int
1997defdict_traverse(PyObject *self, visitproc visit, void *arg)
1998{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001999 Py_VISIT(((defdictobject *)self)->default_factory);
2000 return PyDict_Type.tp_traverse(self, visit, arg);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002001}
2002
2003static int
2004defdict_tp_clear(defdictobject *dd)
2005{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002006 Py_CLEAR(dd->default_factory);
2007 return PyDict_Type.tp_clear((PyObject *)dd);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002008}
2009
2010static int
2011defdict_init(PyObject *self, PyObject *args, PyObject *kwds)
2012{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002013 defdictobject *dd = (defdictobject *)self;
2014 PyObject *olddefault = dd->default_factory;
2015 PyObject *newdefault = NULL;
2016 PyObject *newargs;
2017 int result;
2018 if (args == NULL || !PyTuple_Check(args))
2019 newargs = PyTuple_New(0);
2020 else {
2021 Py_ssize_t n = PyTuple_GET_SIZE(args);
2022 if (n > 0) {
2023 newdefault = PyTuple_GET_ITEM(args, 0);
2024 if (!PyCallable_Check(newdefault) && newdefault != Py_None) {
2025 PyErr_SetString(PyExc_TypeError,
2026 "first argument must be callable");
2027 return -1;
2028 }
2029 }
2030 newargs = PySequence_GetSlice(args, 1, n);
2031 }
2032 if (newargs == NULL)
2033 return -1;
2034 Py_XINCREF(newdefault);
2035 dd->default_factory = newdefault;
2036 result = PyDict_Type.tp_init(self, newargs, kwds);
2037 Py_DECREF(newargs);
2038 Py_XDECREF(olddefault);
2039 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00002040}
2041
2042PyDoc_STRVAR(defdict_doc,
Benjamin Peterson9cb33b72014-01-13 23:56:05 -05002043"defaultdict(default_factory[, ...]) --> dict with default factory\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00002044\n\
2045The default factory is called without arguments to produce\n\
2046a new value when a key is not present, in __getitem__ only.\n\
2047A defaultdict compares equal to a dict with the same items.\n\
Benjamin Peterson9cb33b72014-01-13 23:56:05 -05002048All remaining arguments are treated the same as if they were\n\
2049passed to the dict constructor, including keyword arguments.\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00002050");
2051
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002052/* See comment in xxsubtype.c */
2053#define DEFERRED_ADDRESS(ADDR) 0
2054
Guido van Rossum1968ad32006-02-25 22:38:04 +00002055static PyTypeObject defdict_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002056 PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0)
2057 "collections.defaultdict", /* tp_name */
2058 sizeof(defdictobject), /* tp_basicsize */
2059 0, /* tp_itemsize */
2060 /* methods */
2061 (destructor)defdict_dealloc, /* tp_dealloc */
2062 0, /* tp_print */
2063 0, /* tp_getattr */
2064 0, /* tp_setattr */
2065 0, /* tp_reserved */
2066 (reprfunc)defdict_repr, /* tp_repr */
2067 0, /* tp_as_number */
2068 0, /* tp_as_sequence */
2069 0, /* tp_as_mapping */
2070 0, /* tp_hash */
2071 0, /* tp_call */
2072 0, /* tp_str */
2073 PyObject_GenericGetAttr, /* tp_getattro */
2074 0, /* tp_setattro */
2075 0, /* tp_as_buffer */
2076 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
2077 /* tp_flags */
2078 defdict_doc, /* tp_doc */
2079 defdict_traverse, /* tp_traverse */
2080 (inquiry)defdict_tp_clear, /* tp_clear */
2081 0, /* tp_richcompare */
2082 0, /* tp_weaklistoffset*/
2083 0, /* tp_iter */
2084 0, /* tp_iternext */
2085 defdict_methods, /* tp_methods */
2086 defdict_members, /* tp_members */
2087 0, /* tp_getset */
2088 DEFERRED_ADDRESS(&PyDict_Type), /* tp_base */
2089 0, /* tp_dict */
2090 0, /* tp_descr_get */
2091 0, /* tp_descr_set */
2092 0, /* tp_dictoffset */
2093 defdict_init, /* tp_init */
2094 PyType_GenericAlloc, /* tp_alloc */
2095 0, /* tp_new */
2096 PyObject_GC_Del, /* tp_free */
Guido van Rossum1968ad32006-02-25 22:38:04 +00002097};
2098
Raymond Hettinger96f34102010-12-15 16:30:37 +00002099/* helper function for Counter *********************************************/
2100
2101PyDoc_STRVAR(_count_elements_doc,
2102"_count_elements(mapping, iterable) -> None\n\
2103\n\
2104Count elements in the iterable, updating the mappping");
2105
2106static PyObject *
2107_count_elements(PyObject *self, PyObject *args)
2108{
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002109 _Py_IDENTIFIER(get);
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002110 _Py_IDENTIFIER(__setitem__);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002111 PyObject *it, *iterable, *mapping, *oldval;
2112 PyObject *newval = NULL;
2113 PyObject *key = NULL;
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002114 PyObject *zero = NULL;
Raymond Hettinger96f34102010-12-15 16:30:37 +00002115 PyObject *one = NULL;
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002116 PyObject *bound_get = NULL;
2117 PyObject *mapping_get;
2118 PyObject *dict_get;
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002119 PyObject *mapping_setitem;
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002120 PyObject *dict_setitem;
Raymond Hettinger96f34102010-12-15 16:30:37 +00002121
2122 if (!PyArg_UnpackTuple(args, "_count_elements", 2, 2, &mapping, &iterable))
2123 return NULL;
2124
Raymond Hettinger96f34102010-12-15 16:30:37 +00002125 it = PyObject_GetIter(iterable);
2126 if (it == NULL)
2127 return NULL;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002128
Raymond Hettinger96f34102010-12-15 16:30:37 +00002129 one = PyLong_FromLong(1);
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002130 if (one == NULL)
2131 goto done;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002132
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002133 /* Only take the fast path when get() and __setitem__()
2134 * have not been overridden.
2135 */
2136 mapping_get = _PyType_LookupId(Py_TYPE(mapping), &PyId_get);
2137 dict_get = _PyType_LookupId(&PyDict_Type, &PyId_get);
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002138 mapping_setitem = _PyType_LookupId(Py_TYPE(mapping), &PyId___setitem__);
2139 dict_setitem = _PyType_LookupId(&PyDict_Type, &PyId___setitem__);
2140
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002141 if (mapping_get != NULL && mapping_get == dict_get &&
2142 mapping_setitem != NULL && mapping_setitem == dict_setitem) {
Raymond Hettinger426e0522011-01-03 02:12:02 +00002143 while (1) {
Raymond Hettinger507d9972014-05-18 21:32:40 +01002144 /* Fast path advantages:
2145 1. Eliminate double hashing
2146 (by re-using the same hash for both the get and set)
2147 2. Avoid argument overhead of PyObject_CallFunctionObjArgs
2148 (argument tuple creation and parsing)
2149 3. Avoid indirection through a bound method object
2150 (creates another argument tuple)
2151 4. Avoid initial increment from zero
2152 (reuse an existing one-object instead)
2153 */
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002154 Py_hash_t hash;
2155
Raymond Hettinger426e0522011-01-03 02:12:02 +00002156 key = PyIter_Next(it);
Victor Stinnera154b5c2011-04-20 23:23:52 +02002157 if (key == NULL)
2158 break;
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002159
2160 if (!PyUnicode_CheckExact(key) ||
2161 (hash = ((PyASCIIObject *) key)->hash) == -1)
2162 {
2163 hash = PyObject_Hash(key);
Raymond Hettingerda2850f2015-02-27 12:42:54 -08002164 if (hash == -1)
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002165 goto done;
2166 }
2167
2168 oldval = _PyDict_GetItem_KnownHash(mapping, key, hash);
Raymond Hettinger426e0522011-01-03 02:12:02 +00002169 if (oldval == NULL) {
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002170 if (_PyDict_SetItem_KnownHash(mapping, key, one, hash) == -1)
Raymond Hettinger507d9972014-05-18 21:32:40 +01002171 goto done;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002172 } else {
2173 newval = PyNumber_Add(oldval, one);
2174 if (newval == NULL)
Raymond Hettinger507d9972014-05-18 21:32:40 +01002175 goto done;
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002176 if (_PyDict_SetItem_KnownHash(mapping, key, newval, hash) == -1)
Raymond Hettinger507d9972014-05-18 21:32:40 +01002177 goto done;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002178 Py_CLEAR(newval);
2179 }
2180 Py_DECREF(key);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002181 }
Raymond Hettinger426e0522011-01-03 02:12:02 +00002182 } else {
Victor Stinnere7f516c2013-11-06 23:52:55 +01002183 bound_get = _PyObject_GetAttrId(mapping, &PyId_get);
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002184 if (bound_get == NULL)
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002185 goto done;
2186
2187 zero = PyLong_FromLong(0);
2188 if (zero == NULL)
2189 goto done;
2190
Raymond Hettinger426e0522011-01-03 02:12:02 +00002191 while (1) {
2192 key = PyIter_Next(it);
Victor Stinnera154b5c2011-04-20 23:23:52 +02002193 if (key == NULL)
2194 break;
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002195 oldval = PyObject_CallFunctionObjArgs(bound_get, key, zero, NULL);
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002196 if (oldval == NULL)
2197 break;
2198 newval = PyNumber_Add(oldval, one);
2199 Py_DECREF(oldval);
2200 if (newval == NULL)
2201 break;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002202 if (PyObject_SetItem(mapping, key, newval) == -1)
Raymond Hettinger96f34102010-12-15 16:30:37 +00002203 break;
2204 Py_CLEAR(newval);
Raymond Hettinger426e0522011-01-03 02:12:02 +00002205 Py_DECREF(key);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002206 }
Raymond Hettinger96f34102010-12-15 16:30:37 +00002207 }
Raymond Hettinger426e0522011-01-03 02:12:02 +00002208
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002209done:
Raymond Hettinger96f34102010-12-15 16:30:37 +00002210 Py_DECREF(it);
2211 Py_XDECREF(key);
2212 Py_XDECREF(newval);
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002213 Py_XDECREF(bound_get);
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002214 Py_XDECREF(zero);
2215 Py_XDECREF(one);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002216 if (PyErr_Occurred())
2217 return NULL;
2218 Py_RETURN_NONE;
2219}
2220
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002221/* module level code ********************************************************/
2222
2223PyDoc_STRVAR(module_doc,
Guido van Rossum1968ad32006-02-25 22:38:04 +00002224"High performance data structures.\n\
2225- deque: ordered collection accessible from endpoints only\n\
2226- defaultdict: dict subclass with a default value factory\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002227");
2228
Raymond Hettinger96f34102010-12-15 16:30:37 +00002229static struct PyMethodDef module_functions[] = {
2230 {"_count_elements", _count_elements, METH_VARARGS, _count_elements_doc},
2231 {NULL, NULL} /* sentinel */
2232};
Martin v. Löwis1a214512008-06-11 05:26:20 +00002233
2234static struct PyModuleDef _collectionsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002235 PyModuleDef_HEAD_INIT,
2236 "_collections",
2237 module_doc,
2238 -1,
Raymond Hettinger96f34102010-12-15 16:30:37 +00002239 module_functions,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002240 NULL,
2241 NULL,
2242 NULL,
2243 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002244};
2245
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002246PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002247PyInit__collections(void)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002248{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002249 PyObject *m;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002251 m = PyModule_Create(&_collectionsmodule);
2252 if (m == NULL)
2253 return NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002255 if (PyType_Ready(&deque_type) < 0)
2256 return NULL;
2257 Py_INCREF(&deque_type);
2258 PyModule_AddObject(m, "deque", (PyObject *)&deque_type);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002260 defdict_type.tp_base = &PyDict_Type;
2261 if (PyType_Ready(&defdict_type) < 0)
2262 return NULL;
2263 Py_INCREF(&defdict_type);
2264 PyModule_AddObject(m, "defaultdict", (PyObject *)&defdict_type);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002265
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002266 if (PyType_Ready(&dequeiter_type) < 0)
2267 return NULL;
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002268 Py_INCREF(&dequeiter_type);
2269 PyModule_AddObject(m, "_deque_iterator", (PyObject *)&dequeiter_type);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002271 if (PyType_Ready(&dequereviter_type) < 0)
2272 return NULL;
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002273 Py_INCREF(&dequereviter_type);
2274 PyModule_AddObject(m, "_deque_reverse_iterator", (PyObject *)&dequereviter_type);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00002275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002276 return m;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002277}