blob: 66c2a7458ab8511ecbf3903035b552a17a8bf5dd [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
Raymond Hettingerf2b02ce2015-09-26 17:47:02 -0700124#define MAXFREEBLOCKS 16
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
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -0700212 if (deque->rightindex < 0) {
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 }
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000318 Py_SIZE(deque)++;
Raymond Hettinger7c0b70f2015-09-26 21:11:05 -0700319 Py_INCREF(item);
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 }
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000343 Py_SIZE(deque)++;
Raymond Hettinger7c0b70f2015-09-26 21:11:05 -0700344 Py_INCREF(item);
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 Hettinger7a845522015-09-26 01:30:51 -0700374 PyObject *(*iternext)(PyObject *);
Raymond Hettinger0e14e662015-09-19 00:21:33 -0600375 int trim = (deque->maxlen != -1);
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000377 /* Handle case where id(deque) == id(iterable) */
378 if ((PyObject *)deque == iterable) {
379 PyObject *result;
380 PyObject *s = PySequence_List(iterable);
381 if (s == NULL)
382 return NULL;
383 result = deque_extend(deque, s);
384 Py_DECREF(s);
385 return result;
386 }
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000387
Raymond Hettingerd9c116c2013-07-09 00:13:21 -0700388 /* Space saving heuristic. Start filling from the left */
389 if (Py_SIZE(deque) == 0) {
390 assert(deque->leftblock == deque->rightblock);
391 assert(deque->leftindex == deque->rightindex+1);
392 deque->leftindex = 1;
393 deque->rightindex = 0;
394 }
395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000396 it = PyObject_GetIter(iterable);
397 if (it == NULL)
398 return NULL;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000400 if (deque->maxlen == 0)
401 return consume_iterator(it);
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000402
Raymond Hettinger7a845522015-09-26 01:30:51 -0700403 iternext = *Py_TYPE(it)->tp_iternext;
404 while ((item = iternext(it)) != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000405 deque->state++;
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700406 if (deque->rightindex == BLOCKLEN - 1) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000407 block *b = newblock(Py_SIZE(deque));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000408 if (b == NULL) {
409 Py_DECREF(item);
410 Py_DECREF(it);
411 return NULL;
412 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000413 b->leftlink = deque->rightblock;
414 CHECK_END(deque->rightblock->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000415 deque->rightblock->rightlink = b;
416 deque->rightblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000417 MARK_END(b->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000418 deque->rightindex = -1;
419 }
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000420 Py_SIZE(deque)++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 deque->rightindex++;
422 deque->rightblock->data[deque->rightindex] = item;
Raymond Hettinger0e14e662015-09-19 00:21:33 -0600423 if (trim)
424 deque_trim_left(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425 }
Raymond Hettinger2b2b7532015-09-05 17:05:52 -0700426 if (PyErr_Occurred()) {
Raymond Hettinger7a845522015-09-26 01:30:51 -0700427 if (PyErr_ExceptionMatches(PyExc_StopIteration))
428 PyErr_Clear();
429 else {
430 Py_DECREF(it);
431 return NULL;
432 }
Raymond Hettinger2b2b7532015-09-05 17:05:52 -0700433 }
434 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435 Py_RETURN_NONE;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000436}
437
Tim Peters1065f752004-10-01 01:03:29 +0000438PyDoc_STRVAR(extend_doc,
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000439"Extend the right side of the deque with elements from the iterable");
440
441static PyObject *
442deque_extendleft(dequeobject *deque, PyObject *iterable)
443{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000444 PyObject *it, *item;
Raymond Hettinger7a845522015-09-26 01:30:51 -0700445 PyObject *(*iternext)(PyObject *);
Raymond Hettinger0e14e662015-09-19 00:21:33 -0600446 int trim = (deque->maxlen != -1);
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000448 /* Handle case where id(deque) == id(iterable) */
449 if ((PyObject *)deque == iterable) {
450 PyObject *result;
451 PyObject *s = PySequence_List(iterable);
452 if (s == NULL)
453 return NULL;
454 result = deque_extendleft(deque, s);
455 Py_DECREF(s);
456 return result;
457 }
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000458
Raymond Hettingerd9c116c2013-07-09 00:13:21 -0700459 /* Space saving heuristic. Start filling from the right */
460 if (Py_SIZE(deque) == 0) {
461 assert(deque->leftblock == deque->rightblock);
462 assert(deque->leftindex == deque->rightindex+1);
463 deque->leftindex = BLOCKLEN - 1;
464 deque->rightindex = BLOCKLEN - 2;
465 }
466
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000467 it = PyObject_GetIter(iterable);
468 if (it == NULL)
469 return NULL;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 if (deque->maxlen == 0)
472 return consume_iterator(it);
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000473
Raymond Hettinger7a845522015-09-26 01:30:51 -0700474 iternext = *Py_TYPE(it)->tp_iternext;
475 while ((item = iternext(it)) != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 deque->state++;
477 if (deque->leftindex == 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000478 block *b = newblock(Py_SIZE(deque));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 if (b == NULL) {
480 Py_DECREF(item);
481 Py_DECREF(it);
482 return NULL;
483 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000484 b->rightlink = deque->leftblock;
485 CHECK_END(deque->leftblock->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 deque->leftblock->leftlink = b;
487 deque->leftblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000488 MARK_END(b->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 deque->leftindex = BLOCKLEN;
490 }
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000491 Py_SIZE(deque)++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 deque->leftindex--;
493 deque->leftblock->data[deque->leftindex] = item;
Raymond Hettinger0e14e662015-09-19 00:21:33 -0600494 if (trim)
495 deque_trim_right(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000496 }
Raymond Hettinger2b2b7532015-09-05 17:05:52 -0700497 if (PyErr_Occurred()) {
Raymond Hettinger7a845522015-09-26 01:30:51 -0700498 if (PyErr_ExceptionMatches(PyExc_StopIteration))
499 PyErr_Clear();
500 else {
501 Py_DECREF(it);
502 return NULL;
503 }
Raymond Hettinger2b2b7532015-09-05 17:05:52 -0700504 }
505 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 Py_RETURN_NONE;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000507}
508
Tim Peters1065f752004-10-01 01:03:29 +0000509PyDoc_STRVAR(extendleft_doc,
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000510"Extend the left side of the deque with elements from the iterable");
511
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000512static PyObject *
513deque_inplace_concat(dequeobject *deque, PyObject *other)
514{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000515 PyObject *result;
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 result = deque_extend(deque, other);
518 if (result == NULL)
519 return result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000520 Py_INCREF(deque);
Raymond Hettinger2b2b7532015-09-05 17:05:52 -0700521 Py_DECREF(result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000522 return (PyObject *)deque;
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000523}
524
Raymond Hettinger41290a62015-03-31 08:12:23 -0700525static PyObject *deque_copy(PyObject *deque);
526
527static PyObject *
528deque_concat(dequeobject *deque, PyObject *other)
529{
Benjamin Peterson1a629212015-04-04 10:52:36 -0400530 PyObject *new_deque, *result;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700531 int rv;
532
533 rv = PyObject_IsInstance(other, (PyObject *)&deque_type);
534 if (rv <= 0) {
535 if (rv == 0) {
536 PyErr_Format(PyExc_TypeError,
537 "can only concatenate deque (not \"%.200s\") to deque",
538 other->ob_type->tp_name);
539 }
540 return NULL;
541 }
542
543 new_deque = deque_copy((PyObject *)deque);
544 if (new_deque == NULL)
545 return NULL;
Benjamin Peterson1a629212015-04-04 10:52:36 -0400546 result = deque_extend((dequeobject *)new_deque, other);
547 if (result == NULL) {
548 Py_DECREF(new_deque);
549 return NULL;
550 }
551 Py_DECREF(result);
552 return new_deque;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700553}
554
555static void deque_clear(dequeobject *deque);
556
557static PyObject *
Raymond Hettinger41290a62015-03-31 08:12:23 -0700558deque_inplace_repeat(dequeobject *deque, Py_ssize_t n)
559{
Raymond Hettingerc22eee62015-09-26 02:14:50 -0700560 Py_ssize_t i, m, size;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700561 PyObject *seq;
562 PyObject *rv;
563
564 size = Py_SIZE(deque);
565 if (size == 0 || n == 1) {
566 Py_INCREF(deque);
567 return (PyObject *)deque;
568 }
569
570 if (n <= 0) {
571 deque_clear(deque);
572 Py_INCREF(deque);
573 return (PyObject *)deque;
574 }
575
Raymond Hettinger41290a62015-03-31 08:12:23 -0700576 if (size == 1) {
577 /* common case, repeating a single element */
578 PyObject *item = deque->leftblock->data[deque->leftindex];
579
580 if (deque->maxlen != -1 && n > deque->maxlen)
581 n = deque->maxlen;
582
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400583 if (n > MAX_DEQUE_LEN)
584 return PyErr_NoMemory();
585
Raymond Hettinger67c78b52015-09-12 11:00:20 -0400586 deque->state++;
Raymond Hettingerad262252015-09-14 01:03:04 -0400587 for (i = 0 ; i < n-1 ; ) {
Raymond Hettinger67c78b52015-09-12 11:00:20 -0400588 if (deque->rightindex == BLOCKLEN - 1) {
589 block *b = newblock(Py_SIZE(deque) + i);
590 if (b == NULL) {
591 Py_SIZE(deque) += i;
592 return NULL;
593 }
594 b->leftlink = deque->rightblock;
595 CHECK_END(deque->rightblock->rightlink);
596 deque->rightblock->rightlink = b;
597 deque->rightblock = b;
598 MARK_END(b->rightlink);
599 deque->rightindex = -1;
600 }
Raymond Hettingerc22eee62015-09-26 02:14:50 -0700601 m = n - 1 - i;
602 if (m > BLOCKLEN - 1 - deque->rightindex)
603 m = BLOCKLEN - 1 - deque->rightindex;
604 i += m;
605 while (m--) {
Raymond Hettingerad262252015-09-14 01:03:04 -0400606 deque->rightindex++;
607 Py_INCREF(item);
608 deque->rightblock->data[deque->rightindex] = item;
609 }
Raymond Hettinger41290a62015-03-31 08:12:23 -0700610 }
Raymond Hettinger67c78b52015-09-12 11:00:20 -0400611 Py_SIZE(deque) += i;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700612 Py_INCREF(deque);
613 return (PyObject *)deque;
614 }
615
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400616 if ((size_t)size > MAX_DEQUE_LEN / (size_t)n) {
617 return PyErr_NoMemory();
618 }
619
Raymond Hettinger41290a62015-03-31 08:12:23 -0700620 seq = PySequence_List((PyObject *)deque);
621 if (seq == NULL)
622 return seq;
623
624 for (i = 0 ; i < n-1 ; i++) {
625 rv = deque_extend(deque, seq);
626 if (rv == NULL) {
627 Py_DECREF(seq);
628 return NULL;
629 }
630 Py_DECREF(rv);
631 }
632 Py_INCREF(deque);
633 Py_DECREF(seq);
634 return (PyObject *)deque;
635}
636
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400637static PyObject *
638deque_repeat(dequeobject *deque, Py_ssize_t n)
639{
640 dequeobject *new_deque;
Raymond Hettinger95e2cc52015-09-13 02:41:18 -0400641 PyObject *rv;
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400642
643 new_deque = (dequeobject *)deque_copy((PyObject *) deque);
644 if (new_deque == NULL)
645 return NULL;
Raymond Hettinger95e2cc52015-09-13 02:41:18 -0400646 rv = deque_inplace_repeat(new_deque, n);
647 Py_DECREF(new_deque);
648 return rv;
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400649}
650
Raymond Hettinger54023152014-04-23 00:58:48 -0700651/* The rotate() method is part of the public API and is used internally
652as a primitive for other methods.
653
654Rotation by 1 or -1 is a common case, so any optimizations for high
655volume rotations should take care not to penalize the common case.
656
657Conceptually, a rotate by one is equivalent to a pop on one side and an
658append on the other. However, a pop/append pair is unnecessarily slow
659because it requires a incref/decref pair for an object located randomly
660in memory. It is better to just move the object pointer from one block
661to the next without changing the reference count.
662
663When moving batches of pointers, it is tempting to use memcpy() but that
664proved to be slower than a simple loop for a variety of reasons.
665Memcpy() cannot know in advance that we're copying pointers instead of
666bytes, that the source and destination are pointer aligned and
667non-overlapping, that moving just one pointer is a common case, that we
668never need to move more than BLOCKLEN pointers, and that at least one
669pointer is always moved.
670
671For high volume rotations, newblock() and freeblock() are never called
672more than once. Previously emptied blocks are immediately reused as a
673destination block. If a block is left-over at the end, it is freed.
674*/
675
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000676static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000677_deque_rotate(dequeobject *deque, Py_ssize_t n)
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000678{
Raymond Hettinger3959af92013-07-13 02:34:08 -0700679 block *b = NULL;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700680 block *leftblock = deque->leftblock;
681 block *rightblock = deque->rightblock;
682 Py_ssize_t leftindex = deque->leftindex;
683 Py_ssize_t rightindex = deque->rightindex;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000684 Py_ssize_t len=Py_SIZE(deque), halflen=len>>1;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700685 int rv = -1;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000686
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800687 if (len <= 1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000688 return 0;
689 if (n > halflen || n < -halflen) {
690 n %= len;
691 if (n > halflen)
692 n -= len;
693 else if (n < -halflen)
694 n += len;
695 }
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500696 assert(len > 1);
Raymond Hettingera4409c12013-02-04 00:08:12 -0500697 assert(-halflen <= n && n <= halflen);
Raymond Hettinger231ee4d2013-02-02 11:24:43 -0800698
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800699 deque->state++;
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500700 while (n > 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700701 if (leftindex == 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700702 if (b == NULL) {
Raymond Hettinger3959af92013-07-13 02:34:08 -0700703 b = newblock(len);
704 if (b == NULL)
705 goto done;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700706 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000707 b->rightlink = leftblock;
708 CHECK_END(leftblock->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700709 leftblock->leftlink = b;
710 leftblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000711 MARK_END(b->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700712 leftindex = BLOCKLEN;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700713 b = NULL;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800714 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700715 assert(leftindex > 0);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700716 {
717 PyObject **src, **dest;
718 Py_ssize_t m = n;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800719
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700720 if (m > rightindex + 1)
721 m = rightindex + 1;
722 if (m > leftindex)
723 m = leftindex;
724 assert (m > 0 && m <= len);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700725 rightindex -= m;
726 leftindex -= m;
Raymond Hettinger0e259f12015-02-01 22:53:41 -0800727 src = &rightblock->data[rightindex + 1];
728 dest = &leftblock->data[leftindex];
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700729 n -= m;
Raymond Hettinger840533b2013-07-13 17:03:58 -0700730 do {
Raymond Hettinger0e259f12015-02-01 22:53:41 -0800731 *(dest++) = *(src++);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700732 } while (--m);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700733 }
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -0700734 if (rightindex < 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700735 assert(leftblock != rightblock);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700736 assert(b == NULL);
Raymond Hettinger3959af92013-07-13 02:34:08 -0700737 b = rightblock;
Raymond Hettingerb97cc492013-07-21 01:51:07 -0700738 CHECK_NOT_END(rightblock->leftlink);
739 rightblock = rightblock->leftlink;
740 MARK_END(rightblock->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700741 rightindex = BLOCKLEN - 1;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800742 }
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800743 }
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500744 while (n < 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700745 if (rightindex == BLOCKLEN - 1) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700746 if (b == NULL) {
Raymond Hettinger3959af92013-07-13 02:34:08 -0700747 b = newblock(len);
748 if (b == NULL)
749 goto done;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700750 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000751 b->leftlink = rightblock;
752 CHECK_END(rightblock->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700753 rightblock->rightlink = b;
754 rightblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000755 MARK_END(b->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700756 rightindex = -1;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700757 b = NULL;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800758 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700759 assert (rightindex < BLOCKLEN - 1);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700760 {
761 PyObject **src, **dest;
762 Py_ssize_t m = -n;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800763
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700764 if (m > BLOCKLEN - leftindex)
765 m = BLOCKLEN - leftindex;
766 if (m > BLOCKLEN - 1 - rightindex)
767 m = BLOCKLEN - 1 - rightindex;
768 assert (m > 0 && m <= len);
769 src = &leftblock->data[leftindex];
770 dest = &rightblock->data[rightindex + 1];
771 leftindex += m;
772 rightindex += m;
773 n += m;
Raymond Hettinger840533b2013-07-13 17:03:58 -0700774 do {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700775 *(dest++) = *(src++);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700776 } while (--m);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700777 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700778 if (leftindex == BLOCKLEN) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700779 assert(leftblock != rightblock);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700780 assert(b == NULL);
Raymond Hettinger3959af92013-07-13 02:34:08 -0700781 b = leftblock;
Raymond Hettingerb97cc492013-07-21 01:51:07 -0700782 CHECK_NOT_END(leftblock->rightlink);
783 leftblock = leftblock->rightlink;
784 MARK_END(leftblock->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700785 leftindex = 0;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800786 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 }
Raymond Hettinger3959af92013-07-13 02:34:08 -0700788 rv = 0;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700789done:
Raymond Hettinger3959af92013-07-13 02:34:08 -0700790 if (b != NULL)
791 freeblock(b);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700792 deque->leftblock = leftblock;
793 deque->rightblock = rightblock;
794 deque->leftindex = leftindex;
795 deque->rightindex = rightindex;
796
797 return rv;
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000798}
799
800static PyObject *
801deque_rotate(dequeobject *deque, PyObject *args)
802{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 Py_ssize_t n=1;
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000804
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000805 if (!PyArg_ParseTuple(args, "|n:rotate", &n))
806 return NULL;
Raymond Hettinger6921c132015-03-21 02:03:40 -0700807 if (!_deque_rotate(deque, n))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 Py_RETURN_NONE;
809 return NULL;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000810}
811
Tim Peters1065f752004-10-01 01:03:29 +0000812PyDoc_STRVAR(rotate_doc,
Raymond Hettingeree33b272004-02-08 04:05:26 +0000813"Rotate the deque n steps to the right (default n=1). If n is negative, rotates left.");
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000814
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000815static PyObject *
816deque_reverse(dequeobject *deque, PyObject *unused)
817{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000818 block *leftblock = deque->leftblock;
819 block *rightblock = deque->rightblock;
820 Py_ssize_t leftindex = deque->leftindex;
821 Py_ssize_t rightindex = deque->rightindex;
Raymond Hettingercfe5b6c2015-07-20 00:25:50 -0400822 Py_ssize_t n = Py_SIZE(deque) >> 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 PyObject *tmp;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000824
Raymond Hettinger7a237232015-09-22 01:20:36 -0700825 while (n-- > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000826 /* Validate that pointers haven't met in the middle */
827 assert(leftblock != rightblock || leftindex < rightindex);
Raymond Hettinger82df9252013-07-07 01:43:42 -1000828 CHECK_NOT_END(leftblock);
829 CHECK_NOT_END(rightblock);
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000830
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000831 /* Swap */
832 tmp = leftblock->data[leftindex];
833 leftblock->data[leftindex] = rightblock->data[rightindex];
834 rightblock->data[rightindex] = tmp;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 /* Advance left block/index pair */
837 leftindex++;
838 if (leftindex == BLOCKLEN) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 leftblock = leftblock->rightlink;
840 leftindex = 0;
841 }
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000842
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000843 /* Step backwards with the right block/index pair */
844 rightindex--;
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -0700845 if (rightindex < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000846 rightblock = rightblock->leftlink;
847 rightindex = BLOCKLEN - 1;
848 }
849 }
850 Py_RETURN_NONE;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000851}
852
853PyDoc_STRVAR(reverse_doc,
854"D.reverse() -- reverse *IN PLACE*");
855
Raymond Hettinger44459de2010-04-03 23:20:46 +0000856static PyObject *
857deque_count(dequeobject *deque, PyObject *v)
858{
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000859 block *b = deque->leftblock;
860 Py_ssize_t index = deque->leftindex;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000861 Py_ssize_t n = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 Py_ssize_t count = 0;
Raymond Hettingerf9d9c792015-03-02 22:47:46 -0800863 size_t start_state = deque->state;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 PyObject *item;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000865 int cmp;
Raymond Hettinger44459de2010-04-03 23:20:46 +0000866
Raymond Hettinger3a1a8d02015-09-23 02:42:02 -0700867 while (n--) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000868 CHECK_NOT_END(b);
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000869 item = b->data[index];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000870 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
Raymond Hettinger2b0d6462015-09-23 19:15:44 -0700871 if (cmp < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000872 return NULL;
Raymond Hettinger2b0d6462015-09-23 19:15:44 -0700873 count += cmp;
Raymond Hettinger44459de2010-04-03 23:20:46 +0000874
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000875 if (start_state != deque->state) {
876 PyErr_SetString(PyExc_RuntimeError,
877 "deque mutated during iteration");
878 return NULL;
879 }
Raymond Hettinger44459de2010-04-03 23:20:46 +0000880
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 /* Advance left block/index pair */
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000882 index++;
883 if (index == BLOCKLEN) {
884 b = b->rightlink;
885 index = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 }
887 }
888 return PyLong_FromSsize_t(count);
Raymond Hettinger44459de2010-04-03 23:20:46 +0000889}
890
891PyDoc_STRVAR(count_doc,
892"D.count(value) -> integer -- return number of occurrences of value");
893
Raymond Hettinger39dadf72015-03-20 16:38:56 -0700894static int
895deque_contains(dequeobject *deque, PyObject *v)
896{
897 block *b = deque->leftblock;
898 Py_ssize_t index = deque->leftindex;
899 Py_ssize_t n = Py_SIZE(deque);
Raymond Hettinger39dadf72015-03-20 16:38:56 -0700900 size_t start_state = deque->state;
901 PyObject *item;
902 int cmp;
903
Raymond Hettinger3a1a8d02015-09-23 02:42:02 -0700904 while (n--) {
Raymond Hettinger39dadf72015-03-20 16:38:56 -0700905 CHECK_NOT_END(b);
906 item = b->data[index];
907 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
908 if (cmp) {
909 return cmp;
910 }
911 if (start_state != deque->state) {
912 PyErr_SetString(PyExc_RuntimeError,
913 "deque mutated during iteration");
914 return -1;
915 }
916 index++;
917 if (index == BLOCKLEN) {
918 b = b->rightlink;
919 index = 0;
920 }
921 }
922 return 0;
923}
924
Martin v. Löwis18e16552006-02-15 17:27:45 +0000925static Py_ssize_t
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000926deque_len(dequeobject *deque)
927{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000928 return Py_SIZE(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000929}
930
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000931static PyObject *
Raymond Hettinger32ea1652015-03-21 01:37:37 -0700932deque_index(dequeobject *deque, PyObject *args)
933{
934 Py_ssize_t i, start=0, stop=Py_SIZE(deque);
935 PyObject *v, *item;
936 block *b = deque->leftblock;
937 Py_ssize_t index = deque->leftindex;
938 size_t start_state = deque->state;
939
940 if (!PyArg_ParseTuple(args, "O|O&O&:index", &v,
941 _PyEval_SliceIndex, &start,
942 _PyEval_SliceIndex, &stop))
943 return NULL;
944 if (start < 0) {
945 start += Py_SIZE(deque);
946 if (start < 0)
947 start = 0;
948 }
949 if (stop < 0) {
950 stop += Py_SIZE(deque);
951 if (stop < 0)
952 stop = 0;
953 }
Raymond Hettinger87674ec2015-08-26 08:08:38 -0700954 if (stop > Py_SIZE(deque))
955 stop = Py_SIZE(deque);
Raymond Hettinger32ea1652015-03-21 01:37:37 -0700956
957 for (i=0 ; i<stop ; i++) {
958 if (i >= start) {
959 int cmp;
960 CHECK_NOT_END(b);
961 item = b->data[index];
962 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
963 if (cmp > 0)
964 return PyLong_FromSsize_t(i);
965 else if (cmp < 0)
966 return NULL;
967 if (start_state != deque->state) {
968 PyErr_SetString(PyExc_RuntimeError,
969 "deque mutated during iteration");
970 return NULL;
971 }
972 }
973 index++;
974 if (index == BLOCKLEN) {
975 b = b->rightlink;
976 index = 0;
977 }
978 }
979 PyErr_Format(PyExc_ValueError, "%R is not in deque", v);
980 return NULL;
981}
982
983PyDoc_STRVAR(index_doc,
984"D.index(value, [start, [stop]]) -> integer -- return first index of value.\n"
985"Raises ValueError if the value is not present.");
986
Raymond Hettinger551350a2015-03-24 00:19:53 -0700987/* insert(), remove(), and delitem() are implemented in terms of
988 rotate() for simplicity and reasonable performance near the end
989 points. If for some reason these methods become popular, it is not
990 hard to re-implement this using direct data movement (similar to
991 the code used in list slice assignments) and achieve a performance
Raymond Hettingerfef9c1b2015-03-24 21:12:57 -0700992 boost (by moving each pointer only once instead of twice).
Raymond Hettinger551350a2015-03-24 00:19:53 -0700993*/
994
Raymond Hettinger32ea1652015-03-21 01:37:37 -0700995static PyObject *
996deque_insert(dequeobject *deque, PyObject *args)
997{
998 Py_ssize_t index;
999 Py_ssize_t n = Py_SIZE(deque);
1000 PyObject *value;
1001 PyObject *rv;
1002
1003 if (!PyArg_ParseTuple(args, "nO:insert", &index, &value))
1004 return NULL;
1005 if (index >= n)
1006 return deque_append(deque, value);
1007 if (index <= -n || index == 0)
1008 return deque_appendleft(deque, value);
1009 if (_deque_rotate(deque, -index))
1010 return NULL;
1011 if (index < 0)
1012 rv = deque_append(deque, value);
1013 else
1014 rv = deque_appendleft(deque, value);
1015 if (rv == NULL)
1016 return NULL;
1017 Py_DECREF(rv);
1018 if (_deque_rotate(deque, index))
1019 return NULL;
1020 Py_RETURN_NONE;
1021}
1022
1023PyDoc_STRVAR(insert_doc,
1024"D.insert(index, object) -- insert object before index");
1025
1026static PyObject *
Raymond Hettinger4aec61e2005-03-18 21:20:23 +00001027deque_remove(dequeobject *deque, PyObject *value)
1028{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001029 Py_ssize_t i, n=Py_SIZE(deque);
Raymond Hettinger4aec61e2005-03-18 21:20:23 +00001030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 for (i=0 ; i<n ; i++) {
1032 PyObject *item = deque->leftblock->data[deque->leftindex];
1033 int cmp = PyObject_RichCompareBool(item, value, Py_EQ);
Raymond Hettingerd73202c2005-03-19 00:00:51 +00001034
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001035 if (Py_SIZE(deque) != n) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001036 PyErr_SetString(PyExc_IndexError,
1037 "deque mutated during remove().");
1038 return NULL;
1039 }
1040 if (cmp > 0) {
1041 PyObject *tgt = deque_popleft(deque, NULL);
1042 assert (tgt != NULL);
Raymond Hettinger6921c132015-03-21 02:03:40 -07001043 if (_deque_rotate(deque, i))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 return NULL;
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001045 Py_DECREF(tgt);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 Py_RETURN_NONE;
1047 }
1048 else if (cmp < 0) {
1049 _deque_rotate(deque, i);
1050 return NULL;
1051 }
1052 _deque_rotate(deque, -1);
1053 }
1054 PyErr_SetString(PyExc_ValueError, "deque.remove(x): x not in deque");
1055 return NULL;
Raymond Hettinger4aec61e2005-03-18 21:20:23 +00001056}
1057
1058PyDoc_STRVAR(remove_doc,
1059"D.remove(value) -- remove first occurrence of value.");
1060
Benjamin Peterson0e5c48a2013-01-12 21:22:18 -05001061static void
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001062deque_clear(dequeobject *deque)
1063{
Raymond Hettingerbf49fee2015-09-26 00:14:59 -07001064 block *b;
1065 block *prevblock;
1066 block *leftblock;
1067 Py_ssize_t leftindex;
1068 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001069 PyObject *item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001070
Raymond Hettingerbf49fee2015-09-26 00:14:59 -07001071 /* During the process of clearing a deque, decrefs can cause the
1072 deque to mutate. To avoid fatal confusion, we have to make the
1073 deque empty before clearing the blocks and never refer to
1074 anything via deque->ref while clearing. (This is the same
1075 technique used for clearing lists, sets, and dicts.)
1076
1077 Making the deque empty requires allocating a new empty block. In
1078 the unlikely event that memory is full, we fall back to an
1079 alternate method that doesn't require a new block. Repeating
1080 pops in a while-loop is slower, possibly re-entrant (and a clever
1081 adversary could cause it to never terminate).
1082 */
1083
1084 b = newblock(0);
1085 if (b == NULL) {
1086 PyErr_Clear();
1087 goto alternate_method;
1088 }
1089
1090 /* Remember the old size, leftblock, and leftindex */
1091 leftblock = deque->leftblock;
1092 leftindex = deque->leftindex;
1093 n = Py_SIZE(deque);
1094
1095 /* Set the deque to be empty using the newly allocated block */
1096 MARK_END(b->leftlink);
1097 MARK_END(b->rightlink);
1098 Py_SIZE(deque) = 0;
1099 deque->leftblock = b;
1100 deque->rightblock = b;
1101 deque->leftindex = CENTER + 1;
1102 deque->rightindex = CENTER;
1103 deque->state++;
1104
1105 /* Now the old size, leftblock, and leftindex are disconnected from
1106 the empty deque and we can use them to decref the pointers.
1107 */
1108 while (n--) {
1109 item = leftblock->data[leftindex];
1110 Py_DECREF(item);
1111 leftindex++;
1112 if (leftindex == BLOCKLEN && n) {
1113 CHECK_NOT_END(leftblock->rightlink);
1114 prevblock = leftblock;
1115 leftblock = leftblock->rightlink;
1116 leftindex = 0;
1117 freeblock(prevblock);
1118 }
1119 }
1120 CHECK_END(leftblock->rightlink);
1121 freeblock(leftblock);
1122 return;
1123
1124 alternate_method:
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001125 while (Py_SIZE(deque)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 item = deque_pop(deque, NULL);
1127 assert (item != NULL);
1128 Py_DECREF(item);
1129 }
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001130}
1131
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001132static int
1133valid_index(Py_ssize_t i, Py_ssize_t limit)
1134{
Raymond Hettinger12f896c2015-07-31 12:03:20 -07001135 /* The cast to size_t lets us use just a single comparison
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001136 to check whether i is in the range: 0 <= i < limit */
1137 return (size_t) i < (size_t) limit;
1138}
1139
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001140static PyObject *
Benjamin Petersond6313712008-07-31 16:23:04 +00001141deque_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001142{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001143 block *b;
1144 PyObject *item;
1145 Py_ssize_t n, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001146
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001147 if (!valid_index(i, Py_SIZE(deque))) {
1148 PyErr_SetString(PyExc_IndexError, "deque index out of range");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001149 return NULL;
1150 }
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001152 if (i == 0) {
1153 i = deque->leftindex;
1154 b = deque->leftblock;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001155 } else if (i == Py_SIZE(deque) - 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001156 i = deque->rightindex;
1157 b = deque->rightblock;
1158 } else {
1159 i += deque->leftindex;
Raymond Hettingerc2083082015-02-28 23:29:16 -08001160 n = (Py_ssize_t)((size_t) i / BLOCKLEN);
1161 i = (Py_ssize_t)((size_t) i % BLOCKLEN);
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001162 if (index < (Py_SIZE(deque) >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001163 b = deque->leftblock;
1164 while (n--)
1165 b = b->rightlink;
1166 } else {
Raymond Hettinger63d1ff22015-02-28 07:41:30 -08001167 n = (Py_ssize_t)(
Raymond Hettingerc2083082015-02-28 23:29:16 -08001168 ((size_t)(deque->leftindex + Py_SIZE(deque) - 1))
Raymond Hettinger63d1ff22015-02-28 07:41:30 -08001169 / BLOCKLEN - n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001170 b = deque->rightblock;
1171 while (n--)
1172 b = b->leftlink;
1173 }
1174 }
1175 item = b->data[i];
1176 Py_INCREF(item);
1177 return item;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001178}
1179
1180static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001181deque_del_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001182{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 PyObject *item;
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001184 int rv;
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001185
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001186 assert (i >= 0 && i < Py_SIZE(deque));
Raymond Hettinger6921c132015-03-21 02:03:40 -07001187 if (_deque_rotate(deque, -i))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001189 item = deque_popleft(deque, NULL);
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001190 rv = _deque_rotate(deque, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001191 assert (item != NULL);
1192 Py_DECREF(item);
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001193 return rv;
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001194}
1195
1196static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001197deque_ass_item(dequeobject *deque, Py_ssize_t i, PyObject *v)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001198{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001199 PyObject *old_value;
1200 block *b;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001201 Py_ssize_t n, len=Py_SIZE(deque), halflen=(len+1)>>1, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001202
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001203 if (!valid_index(i, len)) {
1204 PyErr_SetString(PyExc_IndexError, "deque index out of range");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001205 return -1;
1206 }
1207 if (v == NULL)
1208 return deque_del_item(deque, i);
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001210 i += deque->leftindex;
Raymond Hettingerc2083082015-02-28 23:29:16 -08001211 n = (Py_ssize_t)((size_t) i / BLOCKLEN);
1212 i = (Py_ssize_t)((size_t) i % BLOCKLEN);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 if (index <= halflen) {
1214 b = deque->leftblock;
1215 while (n--)
1216 b = b->rightlink;
1217 } else {
Raymond Hettingera473b9d2015-02-28 17:49:47 -08001218 n = (Py_ssize_t)(
Raymond Hettingerc2083082015-02-28 23:29:16 -08001219 ((size_t)(deque->leftindex + Py_SIZE(deque) - 1))
Raymond Hettingera473b9d2015-02-28 17:49:47 -08001220 / BLOCKLEN - n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001221 b = deque->rightblock;
1222 while (n--)
1223 b = b->leftlink;
1224 }
1225 Py_INCREF(v);
1226 old_value = b->data[i];
1227 b->data[i] = v;
1228 Py_DECREF(old_value);
1229 return 0;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001230}
1231
1232static PyObject *
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001233deque_clearmethod(dequeobject *deque)
1234{
Benjamin Peterson0e5c48a2013-01-12 21:22:18 -05001235 deque_clear(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001236 Py_RETURN_NONE;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001237}
1238
1239PyDoc_STRVAR(clear_doc, "Remove all elements from the deque.");
1240
1241static void
1242deque_dealloc(dequeobject *deque)
1243{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001244 PyObject_GC_UnTrack(deque);
1245 if (deque->weakreflist != NULL)
1246 PyObject_ClearWeakRefs((PyObject *) deque);
1247 if (deque->leftblock != NULL) {
1248 deque_clear(deque);
1249 assert(deque->leftblock != NULL);
1250 freeblock(deque->leftblock);
1251 }
1252 deque->leftblock = NULL;
1253 deque->rightblock = NULL;
1254 Py_TYPE(deque)->tp_free(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001255}
1256
1257static int
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001258deque_traverse(dequeobject *deque, visitproc visit, void *arg)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001259{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001260 block *b;
1261 PyObject *item;
1262 Py_ssize_t index;
1263 Py_ssize_t indexlo = deque->leftindex;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001264
Raymond Hettinger5bfa8672013-07-06 11:58:09 -10001265 for (b = deque->leftblock; b != deque->rightblock; b = b->rightlink) {
1266 for (index = indexlo; index < BLOCKLEN ; index++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001267 item = b->data[index];
1268 Py_VISIT(item);
1269 }
1270 indexlo = 0;
1271 }
Raymond Hettinger5bfa8672013-07-06 11:58:09 -10001272 for (index = indexlo; index <= deque->rightindex; index++) {
1273 item = b->data[index];
1274 Py_VISIT(item);
1275 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001276 return 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001277}
1278
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001279static PyObject *
1280deque_copy(PyObject *deque)
1281{
Raymond Hettingeraed88302015-09-19 09:05:42 -07001282 dequeobject *old_deque = (dequeobject *)deque;
Raymond Hettingere4f34672015-09-13 19:27:01 -04001283 if (Py_TYPE(deque) == &deque_type) {
1284 dequeobject *new_deque;
1285 PyObject *rv;
1286
1287 new_deque = (dequeobject *)deque_new(&deque_type, (PyObject *)NULL, (PyObject *)NULL);
1288 if (new_deque == NULL)
1289 return NULL;
Raymond Hettingeraed88302015-09-19 09:05:42 -07001290 new_deque->maxlen = old_deque->maxlen;
1291 /* Fast path for the deque_repeat() common case where len(deque) == 1 */
1292 if (Py_SIZE(deque) == 1 && new_deque->maxlen != 0) {
1293 PyObject *item = old_deque->leftblock->data[old_deque->leftindex];
1294 rv = deque_append(new_deque, item);
1295 } else {
1296 rv = deque_extend(new_deque, deque);
1297 }
Raymond Hettingere4f34672015-09-13 19:27:01 -04001298 if (rv != NULL) {
1299 Py_DECREF(rv);
1300 return (PyObject *)new_deque;
1301 }
1302 Py_DECREF(new_deque);
1303 return NULL;
1304 }
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -07001305 if (old_deque->maxlen < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001306 return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "O", deque, NULL);
1307 else
1308 return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "Oi",
Raymond Hettingeraed88302015-09-19 09:05:42 -07001309 deque, old_deque->maxlen, NULL);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001310}
1311
1312PyDoc_STRVAR(copy_doc, "Return a shallow copy of a deque.");
1313
1314static PyObject *
1315deque_reduce(dequeobject *deque)
1316{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001317 PyObject *dict, *result, *aslist;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001318 _Py_IDENTIFIER(__dict__);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001319
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001320 dict = _PyObject_GetAttrId((PyObject *)deque, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001321 if (dict == NULL)
1322 PyErr_Clear();
1323 aslist = PySequence_List((PyObject *)deque);
1324 if (aslist == NULL) {
1325 Py_XDECREF(dict);
1326 return NULL;
1327 }
1328 if (dict == NULL) {
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -07001329 if (deque->maxlen < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001330 result = Py_BuildValue("O(O)", Py_TYPE(deque), aslist);
1331 else
1332 result = Py_BuildValue("O(On)", Py_TYPE(deque), aslist, deque->maxlen);
1333 } else {
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -07001334 if (deque->maxlen < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001335 result = Py_BuildValue("O(OO)O", Py_TYPE(deque), aslist, Py_None, dict);
1336 else
1337 result = Py_BuildValue("O(On)O", Py_TYPE(deque), aslist, deque->maxlen, dict);
1338 }
1339 Py_XDECREF(dict);
1340 Py_DECREF(aslist);
1341 return result;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001342}
1343
1344PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
1345
1346static PyObject *
1347deque_repr(PyObject *deque)
1348{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001349 PyObject *aslist, *result;
1350 int i;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001352 i = Py_ReprEnter(deque);
1353 if (i != 0) {
1354 if (i < 0)
1355 return NULL;
1356 return PyUnicode_FromString("[...]");
1357 }
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001359 aslist = PySequence_List(deque);
1360 if (aslist == NULL) {
1361 Py_ReprLeave(deque);
1362 return NULL;
1363 }
1364 if (((dequeobject *)deque)->maxlen != -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001365 result = PyUnicode_FromFormat("deque(%R, maxlen=%zd)",
1366 aslist, ((dequeobject *)deque)->maxlen);
1367 else
1368 result = PyUnicode_FromFormat("deque(%R)", aslist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001369 Py_ReprLeave(deque);
Raymond Hettinger2b2b7532015-09-05 17:05:52 -07001370 Py_DECREF(aslist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001371 return result;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001372}
1373
Raymond Hettinger738ec902004-02-29 02:15:56 +00001374static PyObject *
1375deque_richcompare(PyObject *v, PyObject *w, int op)
1376{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001377 PyObject *it1=NULL, *it2=NULL, *x, *y;
1378 Py_ssize_t vs, ws;
1379 int b, cmp=-1;
Raymond Hettinger738ec902004-02-29 02:15:56 +00001380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001381 if (!PyObject_TypeCheck(v, &deque_type) ||
1382 !PyObject_TypeCheck(w, &deque_type)) {
Brian Curtindfc80e32011-08-10 20:28:54 -05001383 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001384 }
Raymond Hettinger738ec902004-02-29 02:15:56 +00001385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001386 /* Shortcuts */
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001387 vs = Py_SIZE((dequeobject *)v);
1388 ws = Py_SIZE((dequeobject *)w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001389 if (op == Py_EQ) {
1390 if (v == w)
1391 Py_RETURN_TRUE;
1392 if (vs != ws)
1393 Py_RETURN_FALSE;
1394 }
1395 if (op == Py_NE) {
1396 if (v == w)
1397 Py_RETURN_FALSE;
1398 if (vs != ws)
1399 Py_RETURN_TRUE;
1400 }
Raymond Hettinger738ec902004-02-29 02:15:56 +00001401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001402 /* Search for the first index where items are different */
1403 it1 = PyObject_GetIter(v);
1404 if (it1 == NULL)
1405 goto done;
1406 it2 = PyObject_GetIter(w);
1407 if (it2 == NULL)
1408 goto done;
1409 for (;;) {
1410 x = PyIter_Next(it1);
1411 if (x == NULL && PyErr_Occurred())
1412 goto done;
1413 y = PyIter_Next(it2);
1414 if (x == NULL || y == NULL)
1415 break;
1416 b = PyObject_RichCompareBool(x, y, Py_EQ);
1417 if (b == 0) {
1418 cmp = PyObject_RichCompareBool(x, y, op);
1419 Py_DECREF(x);
1420 Py_DECREF(y);
1421 goto done;
1422 }
1423 Py_DECREF(x);
1424 Py_DECREF(y);
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -07001425 if (b < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001426 goto done;
1427 }
1428 /* We reached the end of one deque or both */
1429 Py_XDECREF(x);
1430 Py_XDECREF(y);
1431 if (PyErr_Occurred())
1432 goto done;
1433 switch (op) {
1434 case Py_LT: cmp = y != NULL; break; /* if w was longer */
1435 case Py_LE: cmp = x == NULL; break; /* if v was not longer */
1436 case Py_EQ: cmp = x == y; break; /* if we reached the end of both */
1437 case Py_NE: cmp = x != y; break; /* if one deque continues */
1438 case Py_GT: cmp = x != NULL; break; /* if v was longer */
1439 case Py_GE: cmp = y == NULL; break; /* if w was not longer */
1440 }
Tim Peters1065f752004-10-01 01:03:29 +00001441
Raymond Hettinger738ec902004-02-29 02:15:56 +00001442done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001443 Py_XDECREF(it1);
1444 Py_XDECREF(it2);
1445 if (cmp == 1)
1446 Py_RETURN_TRUE;
1447 if (cmp == 0)
1448 Py_RETURN_FALSE;
1449 return NULL;
Raymond Hettinger738ec902004-02-29 02:15:56 +00001450}
1451
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001452static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001453deque_init(dequeobject *deque, PyObject *args, PyObject *kwdargs)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001454{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001455 PyObject *iterable = NULL;
1456 PyObject *maxlenobj = NULL;
1457 Py_ssize_t maxlen = -1;
1458 char *kwlist[] = {"iterable", "maxlen", 0};
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001460 if (!PyArg_ParseTupleAndKeywords(args, kwdargs, "|OO:deque", kwlist, &iterable, &maxlenobj))
1461 return -1;
1462 if (maxlenobj != NULL && maxlenobj != Py_None) {
1463 maxlen = PyLong_AsSsize_t(maxlenobj);
1464 if (maxlen == -1 && PyErr_Occurred())
1465 return -1;
1466 if (maxlen < 0) {
1467 PyErr_SetString(PyExc_ValueError, "maxlen must be non-negative");
1468 return -1;
1469 }
1470 }
1471 deque->maxlen = maxlen;
1472 deque_clear(deque);
1473 if (iterable != NULL) {
1474 PyObject *rv = deque_extend(deque, iterable);
1475 if (rv == NULL)
1476 return -1;
1477 Py_DECREF(rv);
1478 }
1479 return 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001480}
1481
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001482static PyObject *
Jesus Cea16e2fca2012-08-03 14:49:42 +02001483deque_sizeof(dequeobject *deque, void *unused)
1484{
1485 Py_ssize_t res;
1486 Py_ssize_t blocks;
1487
1488 res = sizeof(dequeobject);
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001489 blocks = (deque->leftindex + Py_SIZE(deque) + BLOCKLEN - 1) / BLOCKLEN;
1490 assert(deque->leftindex + Py_SIZE(deque) - 1 ==
Jesus Cea16e2fca2012-08-03 14:49:42 +02001491 (blocks - 1) * BLOCKLEN + deque->rightindex);
1492 res += blocks * sizeof(block);
1493 return PyLong_FromSsize_t(res);
1494}
1495
1496PyDoc_STRVAR(sizeof_doc,
1497"D.__sizeof__() -- size of D in memory, in bytes");
1498
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001499static int
1500deque_bool(dequeobject *deque)
1501{
1502 return Py_SIZE(deque) != 0;
1503}
1504
Jesus Cea16e2fca2012-08-03 14:49:42 +02001505static PyObject *
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001506deque_get_maxlen(dequeobject *deque)
1507{
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -07001508 if (deque->maxlen < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001509 Py_RETURN_NONE;
1510 return PyLong_FromSsize_t(deque->maxlen);
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001511}
1512
Raymond Hettinger41290a62015-03-31 08:12:23 -07001513
1514/* deque object ********************************************************/
1515
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001516static PyGetSetDef deque_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001517 {"maxlen", (getter)deque_get_maxlen, (setter)NULL,
1518 "maximum size of a deque or None if unbounded"},
1519 {0}
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001520};
1521
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001522static PySequenceMethods deque_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001523 (lenfunc)deque_len, /* sq_length */
Raymond Hettinger41290a62015-03-31 08:12:23 -07001524 (binaryfunc)deque_concat, /* sq_concat */
1525 (ssizeargfunc)deque_repeat, /* sq_repeat */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001526 (ssizeargfunc)deque_item, /* sq_item */
1527 0, /* sq_slice */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001528 (ssizeobjargproc)deque_ass_item, /* sq_ass_item */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001529 0, /* sq_ass_slice */
Raymond Hettinger39dadf72015-03-20 16:38:56 -07001530 (objobjproc)deque_contains, /* sq_contains */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001531 (binaryfunc)deque_inplace_concat, /* sq_inplace_concat */
Raymond Hettinger41290a62015-03-31 08:12:23 -07001532 (ssizeargfunc)deque_inplace_repeat, /* sq_inplace_repeat */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001533};
1534
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001535static PyNumberMethods deque_as_number = {
1536 0, /* nb_add */
1537 0, /* nb_subtract */
1538 0, /* nb_multiply */
1539 0, /* nb_remainder */
1540 0, /* nb_divmod */
1541 0, /* nb_power */
1542 0, /* nb_negative */
1543 0, /* nb_positive */
1544 0, /* nb_absolute */
1545 (inquiry)deque_bool, /* nb_bool */
1546 0, /* nb_invert */
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001547 };
1548
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001549static PyObject *deque_iter(dequeobject *deque);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001550static PyObject *deque_reviter(dequeobject *deque);
Tim Peters1065f752004-10-01 01:03:29 +00001551PyDoc_STRVAR(reversed_doc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001552 "D.__reversed__() -- return a reverse iterator over the deque");
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001553
1554static PyMethodDef deque_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001555 {"append", (PyCFunction)deque_append,
1556 METH_O, append_doc},
1557 {"appendleft", (PyCFunction)deque_appendleft,
1558 METH_O, appendleft_doc},
1559 {"clear", (PyCFunction)deque_clearmethod,
1560 METH_NOARGS, clear_doc},
1561 {"__copy__", (PyCFunction)deque_copy,
1562 METH_NOARGS, copy_doc},
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001563 {"copy", (PyCFunction)deque_copy,
1564 METH_NOARGS, copy_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001565 {"count", (PyCFunction)deque_count,
Raymond Hettinger0f6f9472015-03-21 01:42:10 -07001566 METH_O, count_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001567 {"extend", (PyCFunction)deque_extend,
1568 METH_O, extend_doc},
1569 {"extendleft", (PyCFunction)deque_extendleft,
1570 METH_O, extendleft_doc},
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001571 {"index", (PyCFunction)deque_index,
1572 METH_VARARGS, index_doc},
1573 {"insert", (PyCFunction)deque_insert,
1574 METH_VARARGS, insert_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001575 {"pop", (PyCFunction)deque_pop,
1576 METH_NOARGS, pop_doc},
1577 {"popleft", (PyCFunction)deque_popleft,
1578 METH_NOARGS, popleft_doc},
Raymond Hettinger0f6f9472015-03-21 01:42:10 -07001579 {"__reduce__", (PyCFunction)deque_reduce,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001580 METH_NOARGS, reduce_doc},
1581 {"remove", (PyCFunction)deque_remove,
1582 METH_O, remove_doc},
1583 {"__reversed__", (PyCFunction)deque_reviter,
1584 METH_NOARGS, reversed_doc},
1585 {"reverse", (PyCFunction)deque_reverse,
1586 METH_NOARGS, reverse_doc},
1587 {"rotate", (PyCFunction)deque_rotate,
Jesus Cea16e2fca2012-08-03 14:49:42 +02001588 METH_VARARGS, rotate_doc},
1589 {"__sizeof__", (PyCFunction)deque_sizeof,
1590 METH_NOARGS, sizeof_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001591 {NULL, NULL} /* sentinel */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001592};
1593
1594PyDoc_STRVAR(deque_doc,
Andrew Svetlov6a5c7c32012-10-31 11:50:40 +02001595"deque([iterable[, maxlen]]) --> deque object\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001596\n\
Raymond Hettinger41290a62015-03-31 08:12:23 -07001597A list-like sequence optimized for data accesses near its endpoints.");
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001598
Neal Norwitz87f10132004-02-29 15:40:53 +00001599static PyTypeObject deque_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001600 PyVarObject_HEAD_INIT(NULL, 0)
1601 "collections.deque", /* tp_name */
1602 sizeof(dequeobject), /* tp_basicsize */
1603 0, /* tp_itemsize */
1604 /* methods */
1605 (destructor)deque_dealloc, /* tp_dealloc */
1606 0, /* tp_print */
1607 0, /* tp_getattr */
1608 0, /* tp_setattr */
1609 0, /* tp_reserved */
1610 deque_repr, /* tp_repr */
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001611 &deque_as_number, /* tp_as_number */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001612 &deque_as_sequence, /* tp_as_sequence */
1613 0, /* tp_as_mapping */
Georg Brandlf038b322010-10-18 07:35:09 +00001614 PyObject_HashNotImplemented, /* tp_hash */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001615 0, /* tp_call */
1616 0, /* tp_str */
1617 PyObject_GenericGetAttr, /* tp_getattro */
1618 0, /* tp_setattro */
1619 0, /* tp_as_buffer */
1620 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
Georg Brandlf038b322010-10-18 07:35:09 +00001621 /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001622 deque_doc, /* tp_doc */
1623 (traverseproc)deque_traverse, /* tp_traverse */
1624 (inquiry)deque_clear, /* tp_clear */
1625 (richcmpfunc)deque_richcompare, /* tp_richcompare */
Georg Brandlf038b322010-10-18 07:35:09 +00001626 offsetof(dequeobject, weakreflist), /* tp_weaklistoffset*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001627 (getiterfunc)deque_iter, /* tp_iter */
1628 0, /* tp_iternext */
1629 deque_methods, /* tp_methods */
1630 0, /* tp_members */
Georg Brandlf038b322010-10-18 07:35:09 +00001631 deque_getset, /* tp_getset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001632 0, /* tp_base */
1633 0, /* tp_dict */
1634 0, /* tp_descr_get */
1635 0, /* tp_descr_set */
1636 0, /* tp_dictoffset */
1637 (initproc)deque_init, /* tp_init */
1638 PyType_GenericAlloc, /* tp_alloc */
1639 deque_new, /* tp_new */
1640 PyObject_GC_Del, /* tp_free */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001641};
1642
1643/*********************** Deque Iterator **************************/
1644
1645typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001646 PyObject_HEAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001647 block *b;
Raymond Hettinger87e69122015-03-02 23:32:02 -08001648 Py_ssize_t index;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001649 dequeobject *deque;
Raymond Hettingerf9d9c792015-03-02 22:47:46 -08001650 size_t state; /* state when the iterator is created */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001651 Py_ssize_t counter; /* number of items remaining for iteration */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001652} dequeiterobject;
1653
Martin v. Löwis59683e82008-06-13 07:50:45 +00001654static PyTypeObject dequeiter_type;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001655
1656static PyObject *
1657deque_iter(dequeobject *deque)
1658{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001659 dequeiterobject *it;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001660
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001661 it = PyObject_GC_New(dequeiterobject, &dequeiter_type);
1662 if (it == NULL)
1663 return NULL;
1664 it->b = deque->leftblock;
1665 it->index = deque->leftindex;
1666 Py_INCREF(deque);
1667 it->deque = deque;
1668 it->state = deque->state;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001669 it->counter = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001670 PyObject_GC_Track(it);
1671 return (PyObject *)it;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001672}
1673
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001674static int
1675dequeiter_traverse(dequeiterobject *dio, visitproc visit, void *arg)
1676{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001677 Py_VISIT(dio->deque);
1678 return 0;
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001679}
1680
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001681static void
1682dequeiter_dealloc(dequeiterobject *dio)
1683{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001684 Py_XDECREF(dio->deque);
1685 PyObject_GC_Del(dio);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001686}
1687
1688static PyObject *
1689dequeiter_next(dequeiterobject *it)
1690{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001691 PyObject *item;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001692
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001693 if (it->deque->state != it->state) {
1694 it->counter = 0;
1695 PyErr_SetString(PyExc_RuntimeError,
1696 "deque mutated during iteration");
1697 return NULL;
1698 }
1699 if (it->counter == 0)
1700 return NULL;
1701 assert (!(it->b == it->deque->rightblock &&
1702 it->index > it->deque->rightindex));
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001703
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001704 item = it->b->data[it->index];
1705 it->index++;
1706 it->counter--;
1707 if (it->index == BLOCKLEN && it->counter > 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -10001708 CHECK_NOT_END(it->b->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001709 it->b = it->b->rightlink;
1710 it->index = 0;
1711 }
1712 Py_INCREF(item);
1713 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001714}
1715
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001716static PyObject *
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001717dequeiter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1718{
1719 Py_ssize_t i, index=0;
1720 PyObject *deque;
1721 dequeiterobject *it;
1722 if (!PyArg_ParseTuple(args, "O!|n", &deque_type, &deque, &index))
1723 return NULL;
1724 assert(type == &dequeiter_type);
1725
1726 it = (dequeiterobject*)deque_iter((dequeobject *)deque);
1727 if (!it)
1728 return NULL;
1729 /* consume items from the queue */
1730 for(i=0; i<index; i++) {
1731 PyObject *item = dequeiter_next(it);
1732 if (item) {
1733 Py_DECREF(item);
1734 } else {
1735 if (it->counter) {
1736 Py_DECREF(it);
1737 return NULL;
1738 } else
1739 break;
1740 }
1741 }
1742 return (PyObject*)it;
1743}
1744
1745static PyObject *
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001746dequeiter_len(dequeiterobject *it)
1747{
Antoine Pitrou554f3342010-08-17 18:30:06 +00001748 return PyLong_FromSsize_t(it->counter);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001749}
1750
Armin Rigof5b3e362006-02-11 21:32:43 +00001751PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001752
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001753static PyObject *
1754dequeiter_reduce(dequeiterobject *it)
1755{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001756 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 +00001757}
1758
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001759static PyMethodDef dequeiter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001760 {"__length_hint__", (PyCFunction)dequeiter_len, METH_NOARGS, length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001761 {"__reduce__", (PyCFunction)dequeiter_reduce, METH_NOARGS, reduce_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001762 {NULL, NULL} /* sentinel */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001763};
1764
Martin v. Löwis59683e82008-06-13 07:50:45 +00001765static PyTypeObject dequeiter_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001766 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger87e69122015-03-02 23:32:02 -08001767 "_collections._deque_iterator", /* tp_name */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001768 sizeof(dequeiterobject), /* tp_basicsize */
1769 0, /* tp_itemsize */
1770 /* methods */
1771 (destructor)dequeiter_dealloc, /* tp_dealloc */
1772 0, /* tp_print */
1773 0, /* tp_getattr */
1774 0, /* tp_setattr */
1775 0, /* tp_reserved */
1776 0, /* tp_repr */
1777 0, /* tp_as_number */
1778 0, /* tp_as_sequence */
1779 0, /* tp_as_mapping */
1780 0, /* tp_hash */
1781 0, /* tp_call */
1782 0, /* tp_str */
1783 PyObject_GenericGetAttr, /* tp_getattro */
1784 0, /* tp_setattro */
1785 0, /* tp_as_buffer */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001786 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001787 0, /* tp_doc */
1788 (traverseproc)dequeiter_traverse, /* tp_traverse */
1789 0, /* tp_clear */
1790 0, /* tp_richcompare */
1791 0, /* tp_weaklistoffset */
1792 PyObject_SelfIter, /* tp_iter */
1793 (iternextfunc)dequeiter_next, /* tp_iternext */
1794 dequeiter_methods, /* tp_methods */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001795 0, /* tp_members */
1796 0, /* tp_getset */
1797 0, /* tp_base */
1798 0, /* tp_dict */
1799 0, /* tp_descr_get */
1800 0, /* tp_descr_set */
1801 0, /* tp_dictoffset */
1802 0, /* tp_init */
1803 0, /* tp_alloc */
1804 dequeiter_new, /* tp_new */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001805 0,
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001806};
1807
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001808/*********************** Deque Reverse Iterator **************************/
1809
Martin v. Löwis59683e82008-06-13 07:50:45 +00001810static PyTypeObject dequereviter_type;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001811
1812static PyObject *
1813deque_reviter(dequeobject *deque)
1814{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001815 dequeiterobject *it;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001816
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001817 it = PyObject_GC_New(dequeiterobject, &dequereviter_type);
1818 if (it == NULL)
1819 return NULL;
1820 it->b = deque->rightblock;
1821 it->index = deque->rightindex;
1822 Py_INCREF(deque);
1823 it->deque = deque;
1824 it->state = deque->state;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001825 it->counter = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001826 PyObject_GC_Track(it);
1827 return (PyObject *)it;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001828}
1829
1830static PyObject *
1831dequereviter_next(dequeiterobject *it)
1832{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001833 PyObject *item;
1834 if (it->counter == 0)
1835 return NULL;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001836
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001837 if (it->deque->state != it->state) {
1838 it->counter = 0;
1839 PyErr_SetString(PyExc_RuntimeError,
1840 "deque mutated during iteration");
1841 return NULL;
1842 }
1843 assert (!(it->b == it->deque->leftblock &&
1844 it->index < it->deque->leftindex));
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001845
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001846 item = it->b->data[it->index];
1847 it->index--;
1848 it->counter--;
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -07001849 if (it->index < 0 && it->counter > 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -10001850 CHECK_NOT_END(it->b->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001851 it->b = it->b->leftlink;
1852 it->index = BLOCKLEN - 1;
1853 }
1854 Py_INCREF(item);
1855 return item;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001856}
1857
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001858static PyObject *
1859dequereviter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1860{
1861 Py_ssize_t i, index=0;
1862 PyObject *deque;
1863 dequeiterobject *it;
1864 if (!PyArg_ParseTuple(args, "O!|n", &deque_type, &deque, &index))
1865 return NULL;
1866 assert(type == &dequereviter_type);
1867
1868 it = (dequeiterobject*)deque_reviter((dequeobject *)deque);
1869 if (!it)
1870 return NULL;
1871 /* consume items from the queue */
1872 for(i=0; i<index; i++) {
1873 PyObject *item = dequereviter_next(it);
1874 if (item) {
1875 Py_DECREF(item);
1876 } else {
1877 if (it->counter) {
1878 Py_DECREF(it);
1879 return NULL;
1880 } else
1881 break;
1882 }
1883 }
1884 return (PyObject*)it;
1885}
1886
Martin v. Löwis59683e82008-06-13 07:50:45 +00001887static PyTypeObject dequereviter_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001888 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger87e69122015-03-02 23:32:02 -08001889 "_collections._deque_reverse_iterator", /* tp_name */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001890 sizeof(dequeiterobject), /* tp_basicsize */
1891 0, /* tp_itemsize */
1892 /* methods */
1893 (destructor)dequeiter_dealloc, /* tp_dealloc */
1894 0, /* tp_print */
1895 0, /* tp_getattr */
1896 0, /* tp_setattr */
1897 0, /* tp_reserved */
1898 0, /* tp_repr */
1899 0, /* tp_as_number */
1900 0, /* tp_as_sequence */
1901 0, /* tp_as_mapping */
1902 0, /* tp_hash */
1903 0, /* tp_call */
1904 0, /* tp_str */
1905 PyObject_GenericGetAttr, /* tp_getattro */
1906 0, /* tp_setattro */
1907 0, /* tp_as_buffer */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001908 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001909 0, /* tp_doc */
1910 (traverseproc)dequeiter_traverse, /* tp_traverse */
1911 0, /* tp_clear */
1912 0, /* tp_richcompare */
1913 0, /* tp_weaklistoffset */
1914 PyObject_SelfIter, /* tp_iter */
1915 (iternextfunc)dequereviter_next, /* tp_iternext */
1916 dequeiter_methods, /* tp_methods */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001917 0, /* tp_members */
1918 0, /* tp_getset */
1919 0, /* tp_base */
1920 0, /* tp_dict */
1921 0, /* tp_descr_get */
1922 0, /* tp_descr_set */
1923 0, /* tp_dictoffset */
1924 0, /* tp_init */
1925 0, /* tp_alloc */
1926 dequereviter_new, /* tp_new */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001927 0,
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001928};
1929
Guido van Rossum1968ad32006-02-25 22:38:04 +00001930/* defaultdict type *********************************************************/
1931
1932typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001933 PyDictObject dict;
1934 PyObject *default_factory;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001935} defdictobject;
1936
1937static PyTypeObject defdict_type; /* Forward */
1938
1939PyDoc_STRVAR(defdict_missing_doc,
1940"__missing__(key) # Called by __getitem__ for missing key; pseudo-code:\n\
Guido van Rossumd8faa362007-04-27 19:54:29 +00001941 if self.default_factory is None: raise KeyError((key,))\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00001942 self[key] = value = self.default_factory()\n\
1943 return value\n\
1944");
1945
1946static PyObject *
1947defdict_missing(defdictobject *dd, PyObject *key)
1948{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001949 PyObject *factory = dd->default_factory;
1950 PyObject *value;
1951 if (factory == NULL || factory == Py_None) {
1952 /* XXX Call dict.__missing__(key) */
1953 PyObject *tup;
1954 tup = PyTuple_Pack(1, key);
1955 if (!tup) return NULL;
1956 PyErr_SetObject(PyExc_KeyError, tup);
1957 Py_DECREF(tup);
1958 return NULL;
1959 }
1960 value = PyEval_CallObject(factory, NULL);
1961 if (value == NULL)
1962 return value;
1963 if (PyObject_SetItem((PyObject *)dd, key, value) < 0) {
1964 Py_DECREF(value);
1965 return NULL;
1966 }
1967 return value;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001968}
1969
1970PyDoc_STRVAR(defdict_copy_doc, "D.copy() -> a shallow copy of D.");
1971
1972static PyObject *
1973defdict_copy(defdictobject *dd)
1974{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001975 /* This calls the object's class. That only works for subclasses
1976 whose class constructor has the same signature. Subclasses that
1977 define a different constructor signature must override copy().
1978 */
Raymond Hettinger54628fa2009-08-04 19:16:39 +00001979
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001980 if (dd->default_factory == NULL)
1981 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd), Py_None, dd, NULL);
1982 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd),
1983 dd->default_factory, dd, NULL);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001984}
1985
1986static PyObject *
1987defdict_reduce(defdictobject *dd)
1988{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001989 /* __reduce__ must return a 5-tuple as follows:
Guido van Rossum1968ad32006-02-25 22:38:04 +00001990
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001991 - factory function
1992 - tuple of args for the factory function
1993 - additional state (here None)
1994 - sequence iterator (here None)
1995 - dictionary iterator (yielding successive (key, value) pairs
Guido van Rossum1968ad32006-02-25 22:38:04 +00001996
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001997 This API is used by pickle.py and copy.py.
Guido van Rossum1968ad32006-02-25 22:38:04 +00001998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001999 For this to be useful with pickle.py, the default_factory
2000 must be picklable; e.g., None, a built-in, or a global
2001 function in a module or package.
Guido van Rossum1968ad32006-02-25 22:38:04 +00002002
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002003 Both shallow and deep copying are supported, but for deep
2004 copying, the default_factory must be deep-copyable; e.g. None,
2005 or a built-in (functions are not copyable at this time).
Guido van Rossum1968ad32006-02-25 22:38:04 +00002006
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002007 This only works for subclasses as long as their constructor
2008 signature is compatible; the first argument must be the
2009 optional default_factory, defaulting to None.
2010 */
2011 PyObject *args;
2012 PyObject *items;
2013 PyObject *iter;
2014 PyObject *result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002015 _Py_IDENTIFIER(items);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002017 if (dd->default_factory == NULL || dd->default_factory == Py_None)
2018 args = PyTuple_New(0);
2019 else
2020 args = PyTuple_Pack(1, dd->default_factory);
2021 if (args == NULL)
2022 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002023 items = _PyObject_CallMethodId((PyObject *)dd, &PyId_items, "()");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002024 if (items == NULL) {
2025 Py_DECREF(args);
2026 return NULL;
2027 }
2028 iter = PyObject_GetIter(items);
2029 if (iter == NULL) {
2030 Py_DECREF(items);
2031 Py_DECREF(args);
2032 return NULL;
2033 }
2034 result = PyTuple_Pack(5, Py_TYPE(dd), args,
2035 Py_None, Py_None, iter);
2036 Py_DECREF(iter);
2037 Py_DECREF(items);
2038 Py_DECREF(args);
2039 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00002040}
2041
2042static PyMethodDef defdict_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002043 {"__missing__", (PyCFunction)defdict_missing, METH_O,
2044 defdict_missing_doc},
2045 {"copy", (PyCFunction)defdict_copy, METH_NOARGS,
2046 defdict_copy_doc},
2047 {"__copy__", (PyCFunction)defdict_copy, METH_NOARGS,
2048 defdict_copy_doc},
2049 {"__reduce__", (PyCFunction)defdict_reduce, METH_NOARGS,
2050 reduce_doc},
2051 {NULL}
Guido van Rossum1968ad32006-02-25 22:38:04 +00002052};
2053
2054static PyMemberDef defdict_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002055 {"default_factory", T_OBJECT,
2056 offsetof(defdictobject, default_factory), 0,
2057 PyDoc_STR("Factory for default value called by __missing__().")},
2058 {NULL}
Guido van Rossum1968ad32006-02-25 22:38:04 +00002059};
2060
2061static void
2062defdict_dealloc(defdictobject *dd)
2063{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002064 Py_CLEAR(dd->default_factory);
2065 PyDict_Type.tp_dealloc((PyObject *)dd);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002066}
2067
Guido van Rossum1968ad32006-02-25 22:38:04 +00002068static PyObject *
2069defdict_repr(defdictobject *dd)
2070{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002071 PyObject *baserepr;
2072 PyObject *defrepr;
2073 PyObject *result;
2074 baserepr = PyDict_Type.tp_repr((PyObject *)dd);
2075 if (baserepr == NULL)
2076 return NULL;
2077 if (dd->default_factory == NULL)
2078 defrepr = PyUnicode_FromString("None");
2079 else
2080 {
2081 int status = Py_ReprEnter(dd->default_factory);
2082 if (status != 0) {
Antoine Pitrouf5f1fe02012-02-15 02:42:46 +01002083 if (status < 0) {
2084 Py_DECREF(baserepr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002085 return NULL;
Antoine Pitrouf5f1fe02012-02-15 02:42:46 +01002086 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002087 defrepr = PyUnicode_FromString("...");
2088 }
2089 else
2090 defrepr = PyObject_Repr(dd->default_factory);
2091 Py_ReprLeave(dd->default_factory);
2092 }
2093 if (defrepr == NULL) {
2094 Py_DECREF(baserepr);
2095 return NULL;
2096 }
2097 result = PyUnicode_FromFormat("defaultdict(%U, %U)",
2098 defrepr, baserepr);
2099 Py_DECREF(defrepr);
2100 Py_DECREF(baserepr);
2101 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00002102}
2103
2104static int
2105defdict_traverse(PyObject *self, visitproc visit, void *arg)
2106{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002107 Py_VISIT(((defdictobject *)self)->default_factory);
2108 return PyDict_Type.tp_traverse(self, visit, arg);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002109}
2110
2111static int
2112defdict_tp_clear(defdictobject *dd)
2113{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002114 Py_CLEAR(dd->default_factory);
2115 return PyDict_Type.tp_clear((PyObject *)dd);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002116}
2117
2118static int
2119defdict_init(PyObject *self, PyObject *args, PyObject *kwds)
2120{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002121 defdictobject *dd = (defdictobject *)self;
2122 PyObject *olddefault = dd->default_factory;
2123 PyObject *newdefault = NULL;
2124 PyObject *newargs;
2125 int result;
2126 if (args == NULL || !PyTuple_Check(args))
2127 newargs = PyTuple_New(0);
2128 else {
2129 Py_ssize_t n = PyTuple_GET_SIZE(args);
2130 if (n > 0) {
2131 newdefault = PyTuple_GET_ITEM(args, 0);
2132 if (!PyCallable_Check(newdefault) && newdefault != Py_None) {
2133 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger239aba72015-07-20 03:09:22 -04002134 "first argument must be callable or None");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002135 return -1;
2136 }
2137 }
2138 newargs = PySequence_GetSlice(args, 1, n);
2139 }
2140 if (newargs == NULL)
2141 return -1;
2142 Py_XINCREF(newdefault);
2143 dd->default_factory = newdefault;
2144 result = PyDict_Type.tp_init(self, newargs, kwds);
2145 Py_DECREF(newargs);
2146 Py_XDECREF(olddefault);
2147 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00002148}
2149
2150PyDoc_STRVAR(defdict_doc,
Benjamin Peterson9cb33b72014-01-13 23:56:05 -05002151"defaultdict(default_factory[, ...]) --> dict with default factory\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00002152\n\
2153The default factory is called without arguments to produce\n\
2154a new value when a key is not present, in __getitem__ only.\n\
2155A defaultdict compares equal to a dict with the same items.\n\
Benjamin Peterson9cb33b72014-01-13 23:56:05 -05002156All remaining arguments are treated the same as if they were\n\
2157passed to the dict constructor, including keyword arguments.\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00002158");
2159
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002160/* See comment in xxsubtype.c */
2161#define DEFERRED_ADDRESS(ADDR) 0
2162
Guido van Rossum1968ad32006-02-25 22:38:04 +00002163static PyTypeObject defdict_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002164 PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0)
2165 "collections.defaultdict", /* tp_name */
2166 sizeof(defdictobject), /* tp_basicsize */
2167 0, /* tp_itemsize */
2168 /* methods */
2169 (destructor)defdict_dealloc, /* tp_dealloc */
2170 0, /* tp_print */
2171 0, /* tp_getattr */
2172 0, /* tp_setattr */
2173 0, /* tp_reserved */
2174 (reprfunc)defdict_repr, /* tp_repr */
2175 0, /* tp_as_number */
2176 0, /* tp_as_sequence */
2177 0, /* tp_as_mapping */
2178 0, /* tp_hash */
2179 0, /* tp_call */
2180 0, /* tp_str */
2181 PyObject_GenericGetAttr, /* tp_getattro */
2182 0, /* tp_setattro */
2183 0, /* tp_as_buffer */
2184 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
2185 /* tp_flags */
2186 defdict_doc, /* tp_doc */
2187 defdict_traverse, /* tp_traverse */
2188 (inquiry)defdict_tp_clear, /* tp_clear */
2189 0, /* tp_richcompare */
2190 0, /* tp_weaklistoffset*/
2191 0, /* tp_iter */
2192 0, /* tp_iternext */
2193 defdict_methods, /* tp_methods */
2194 defdict_members, /* tp_members */
2195 0, /* tp_getset */
2196 DEFERRED_ADDRESS(&PyDict_Type), /* tp_base */
2197 0, /* tp_dict */
2198 0, /* tp_descr_get */
2199 0, /* tp_descr_set */
2200 0, /* tp_dictoffset */
2201 defdict_init, /* tp_init */
2202 PyType_GenericAlloc, /* tp_alloc */
2203 0, /* tp_new */
2204 PyObject_GC_Del, /* tp_free */
Guido van Rossum1968ad32006-02-25 22:38:04 +00002205};
2206
Raymond Hettinger96f34102010-12-15 16:30:37 +00002207/* helper function for Counter *********************************************/
2208
2209PyDoc_STRVAR(_count_elements_doc,
2210"_count_elements(mapping, iterable) -> None\n\
2211\n\
2212Count elements in the iterable, updating the mappping");
2213
2214static PyObject *
2215_count_elements(PyObject *self, PyObject *args)
2216{
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002217 _Py_IDENTIFIER(get);
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002218 _Py_IDENTIFIER(__setitem__);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002219 PyObject *it, *iterable, *mapping, *oldval;
2220 PyObject *newval = NULL;
2221 PyObject *key = NULL;
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002222 PyObject *zero = NULL;
Raymond Hettinger96f34102010-12-15 16:30:37 +00002223 PyObject *one = NULL;
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002224 PyObject *bound_get = NULL;
2225 PyObject *mapping_get;
2226 PyObject *dict_get;
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002227 PyObject *mapping_setitem;
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002228 PyObject *dict_setitem;
Raymond Hettinger96f34102010-12-15 16:30:37 +00002229
2230 if (!PyArg_UnpackTuple(args, "_count_elements", 2, 2, &mapping, &iterable))
2231 return NULL;
2232
Raymond Hettinger96f34102010-12-15 16:30:37 +00002233 it = PyObject_GetIter(iterable);
2234 if (it == NULL)
2235 return NULL;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002236
Raymond Hettinger96f34102010-12-15 16:30:37 +00002237 one = PyLong_FromLong(1);
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002238 if (one == NULL)
2239 goto done;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002240
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002241 /* Only take the fast path when get() and __setitem__()
2242 * have not been overridden.
2243 */
2244 mapping_get = _PyType_LookupId(Py_TYPE(mapping), &PyId_get);
2245 dict_get = _PyType_LookupId(&PyDict_Type, &PyId_get);
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002246 mapping_setitem = _PyType_LookupId(Py_TYPE(mapping), &PyId___setitem__);
2247 dict_setitem = _PyType_LookupId(&PyDict_Type, &PyId___setitem__);
2248
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002249 if (mapping_get != NULL && mapping_get == dict_get &&
2250 mapping_setitem != NULL && mapping_setitem == dict_setitem) {
Raymond Hettinger426e0522011-01-03 02:12:02 +00002251 while (1) {
Raymond Hettinger507d9972014-05-18 21:32:40 +01002252 /* Fast path advantages:
2253 1. Eliminate double hashing
2254 (by re-using the same hash for both the get and set)
2255 2. Avoid argument overhead of PyObject_CallFunctionObjArgs
2256 (argument tuple creation and parsing)
2257 3. Avoid indirection through a bound method object
2258 (creates another argument tuple)
2259 4. Avoid initial increment from zero
2260 (reuse an existing one-object instead)
2261 */
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002262 Py_hash_t hash;
2263
Raymond Hettinger426e0522011-01-03 02:12:02 +00002264 key = PyIter_Next(it);
Victor Stinnera154b5c2011-04-20 23:23:52 +02002265 if (key == NULL)
2266 break;
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002267
2268 if (!PyUnicode_CheckExact(key) ||
2269 (hash = ((PyASCIIObject *) key)->hash) == -1)
2270 {
2271 hash = PyObject_Hash(key);
Raymond Hettingerda2850f2015-02-27 12:42:54 -08002272 if (hash == -1)
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002273 goto done;
2274 }
2275
2276 oldval = _PyDict_GetItem_KnownHash(mapping, key, hash);
Raymond Hettinger426e0522011-01-03 02:12:02 +00002277 if (oldval == NULL) {
Raymond Hettinger28c995d2015-08-14 02:07:41 -07002278 if (_PyDict_SetItem_KnownHash(mapping, key, one, hash) < 0)
Raymond Hettinger507d9972014-05-18 21:32:40 +01002279 goto done;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002280 } else {
2281 newval = PyNumber_Add(oldval, one);
2282 if (newval == NULL)
Raymond Hettinger507d9972014-05-18 21:32:40 +01002283 goto done;
Raymond Hettinger28c995d2015-08-14 02:07:41 -07002284 if (_PyDict_SetItem_KnownHash(mapping, key, newval, hash) < 0)
Raymond Hettinger507d9972014-05-18 21:32:40 +01002285 goto done;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002286 Py_CLEAR(newval);
2287 }
2288 Py_DECREF(key);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002289 }
Raymond Hettinger426e0522011-01-03 02:12:02 +00002290 } else {
Victor Stinnere7f516c2013-11-06 23:52:55 +01002291 bound_get = _PyObject_GetAttrId(mapping, &PyId_get);
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002292 if (bound_get == NULL)
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002293 goto done;
2294
2295 zero = PyLong_FromLong(0);
2296 if (zero == NULL)
2297 goto done;
2298
Raymond Hettinger426e0522011-01-03 02:12:02 +00002299 while (1) {
2300 key = PyIter_Next(it);
Victor Stinnera154b5c2011-04-20 23:23:52 +02002301 if (key == NULL)
2302 break;
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002303 oldval = PyObject_CallFunctionObjArgs(bound_get, key, zero, NULL);
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002304 if (oldval == NULL)
2305 break;
2306 newval = PyNumber_Add(oldval, one);
2307 Py_DECREF(oldval);
2308 if (newval == NULL)
2309 break;
Raymond Hettinger28c995d2015-08-14 02:07:41 -07002310 if (PyObject_SetItem(mapping, key, newval) < 0)
Raymond Hettinger96f34102010-12-15 16:30:37 +00002311 break;
2312 Py_CLEAR(newval);
Raymond Hettinger426e0522011-01-03 02:12:02 +00002313 Py_DECREF(key);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002314 }
Raymond Hettinger96f34102010-12-15 16:30:37 +00002315 }
Raymond Hettinger426e0522011-01-03 02:12:02 +00002316
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002317done:
Raymond Hettinger96f34102010-12-15 16:30:37 +00002318 Py_DECREF(it);
2319 Py_XDECREF(key);
2320 Py_XDECREF(newval);
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002321 Py_XDECREF(bound_get);
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002322 Py_XDECREF(zero);
2323 Py_XDECREF(one);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002324 if (PyErr_Occurred())
2325 return NULL;
2326 Py_RETURN_NONE;
2327}
2328
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002329/* module level code ********************************************************/
2330
2331PyDoc_STRVAR(module_doc,
Guido van Rossum1968ad32006-02-25 22:38:04 +00002332"High performance data structures.\n\
2333- deque: ordered collection accessible from endpoints only\n\
2334- defaultdict: dict subclass with a default value factory\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002335");
2336
Raymond Hettinger96f34102010-12-15 16:30:37 +00002337static struct PyMethodDef module_functions[] = {
2338 {"_count_elements", _count_elements, METH_VARARGS, _count_elements_doc},
2339 {NULL, NULL} /* sentinel */
2340};
Martin v. Löwis1a214512008-06-11 05:26:20 +00002341
2342static struct PyModuleDef _collectionsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002343 PyModuleDef_HEAD_INIT,
2344 "_collections",
2345 module_doc,
2346 -1,
Raymond Hettinger96f34102010-12-15 16:30:37 +00002347 module_functions,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002348 NULL,
2349 NULL,
2350 NULL,
2351 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002352};
2353
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002354PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002355PyInit__collections(void)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002356{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002357 PyObject *m;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002359 m = PyModule_Create(&_collectionsmodule);
2360 if (m == NULL)
2361 return NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002363 if (PyType_Ready(&deque_type) < 0)
2364 return NULL;
2365 Py_INCREF(&deque_type);
2366 PyModule_AddObject(m, "deque", (PyObject *)&deque_type);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002368 defdict_type.tp_base = &PyDict_Type;
2369 if (PyType_Ready(&defdict_type) < 0)
2370 return NULL;
2371 Py_INCREF(&defdict_type);
2372 PyModule_AddObject(m, "defaultdict", (PyObject *)&defdict_type);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002373
Eric Snow47db7172015-05-29 22:21:39 -06002374 Py_INCREF(&PyODict_Type);
2375 PyModule_AddObject(m, "OrderedDict", (PyObject *)&PyODict_Type);
2376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002377 if (PyType_Ready(&dequeiter_type) < 0)
2378 return NULL;
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002379 Py_INCREF(&dequeiter_type);
2380 PyModule_AddObject(m, "_deque_iterator", (PyObject *)&dequeiter_type);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002382 if (PyType_Ready(&dequereviter_type) < 0)
2383 return NULL;
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002384 Py_INCREF(&dequereviter_type);
2385 PyModule_AddObject(m, "_deque_reverse_iterator", (PyObject *)&dequereviter_type);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00002386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002387 return m;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002388}