blob: b2783d2739580a288ee76eb9b5848b543a5cba1a [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
4/* collections module implementation of a deque() datatype
5 Written and maintained by Raymond D. Hettinger <python@rcn.com>
Raymond Hettinger54023152014-04-23 00:58:48 -07006 Copyright (c) 2004-2014 Python Software Foundation.
Raymond Hettinger756b3f32004-01-29 06:37:52 +00007 All rights reserved.
8*/
9
Raymond Hettinger77e8bf12004-10-01 15:25:53 +000010/* The block length may be set to any number over 1. Larger numbers
Raymond Hettinger20b0f872013-06-23 15:44:33 -070011 * reduce the number of calls to the memory allocator, give faster
12 * indexing and rotation, and reduce the link::data overhead ratio.
Raymond Hettinger77578202013-07-28 02:39:49 -070013 *
14 * Ideally, the block length will be set to two less than some
15 * multiple of the cache-line length (so that the full block
16 * including the leftlink and rightlink will fit neatly into
17 * cache lines).
Raymond Hettinger77e8bf12004-10-01 15:25:53 +000018 */
19
Raymond Hettinger77578202013-07-28 02:39:49 -070020#define BLOCKLEN 62
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000021#define CENTER ((BLOCKLEN - 1) / 2)
Raymond Hettinger756b3f32004-01-29 06:37:52 +000022
Tim Petersd8768d32004-10-01 01:32:53 +000023/* A `dequeobject` is composed of a doubly-linked list of `block` nodes.
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000024 * The list of blocks is never empty, so d.leftblock and d.rightblock
Raymond Hettinger82df9252013-07-07 01:43:42 -100025 * are never equal to NULL. The list is not circular.
26 *
27 * A deque d's first element is at d.leftblock[leftindex]
28 * and its last element is at d.rightblock[rightindex].
29 * Unlike Python slice indices, these indices are inclusive
30 * on both ends. This makes the algorithms for left and
31 * right operations more symmetrical and simplifies the design.
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000032 *
33 * The indices, d.leftindex and d.rightindex are always in the range
34 * 0 <= index < BLOCKLEN.
Raymond Hettinger4ca4c7c2004-10-01 15:14:39 +000035 * Their exact relationship is:
36 * (d.leftindex + d.len - 1) % BLOCKLEN == d.rightindex.
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000037 *
38 * Empty deques have d.len == 0; d.leftblock==d.rightblock;
39 * d.leftindex == CENTER+1; and d.rightindex == CENTER.
40 * Checking for d.len == 0 is the intended way to see whether d is empty.
41 *
Thomas Wouters0e3f5912006-08-11 14:57:12 +000042 * Whenever d.leftblock == d.rightblock,
Raymond Hettinger4ca4c7c2004-10-01 15:14:39 +000043 * d.leftindex + d.len - 1 == d.rightindex.
Thomas Wouters0e3f5912006-08-11 14:57:12 +000044 *
Raymond Hettinger4ca4c7c2004-10-01 15:14:39 +000045 * However, when d.leftblock != d.rightblock, d.leftindex and d.rightindex
Thomas Wouters0e3f5912006-08-11 14:57:12 +000046 * become indices into distinct blocks and either may be larger than the
Raymond Hettinger4ca4c7c2004-10-01 15:14:39 +000047 * other.
Tim Petersd8768d32004-10-01 01:32:53 +000048 */
49
Raymond Hettinger756b3f32004-01-29 06:37:52 +000050typedef struct BLOCK {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000051 struct BLOCK *leftlink;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000052 PyObject *data[BLOCKLEN];
Raymond Hettinger20b0f872013-06-23 15:44:33 -070053 struct BLOCK *rightlink;
Raymond Hettinger756b3f32004-01-29 06:37:52 +000054} block;
55
Raymond Hettinger82df9252013-07-07 01:43:42 -100056/* For debug builds, add error checking to track the endpoints
57 * in the chain of links. The goal is to make sure that link
58 * assignments only take place at endpoints so that links already
59 * in use do not get overwritten.
60 *
61 * CHECK_END should happen before each assignment to a block's link field.
62 * MARK_END should happen whenever a link field becomes a new endpoint.
63 * This happens when new blocks are added or whenever an existing
64 * block is freed leaving another existing block as the new endpoint.
65 */
66
Raymond Hettinger3223dd52013-07-26 23:14:22 -070067#ifndef NDEBUG
Raymond Hettinger82df9252013-07-07 01:43:42 -100068#define MARK_END(link) link = NULL;
69#define CHECK_END(link) assert(link == NULL);
70#define CHECK_NOT_END(link) assert(link != NULL);
71#else
72#define MARK_END(link)
73#define CHECK_END(link)
74#define CHECK_NOT_END(link)
75#endif
76
77/* A simple freelisting scheme is used to minimize calls to the memory
78 allocator. It accomodates common use cases where new blocks are being
79 added at about the same rate as old blocks are being freed.
80 */
81
Guido van Rossum58da9312007-11-10 23:39:45 +000082#define MAXFREEBLOCKS 10
Benjamin Petersond6313712008-07-31 16:23:04 +000083static Py_ssize_t numfreeblocks = 0;
Guido van Rossum58da9312007-11-10 23:39:45 +000084static block *freeblocks[MAXFREEBLOCKS];
85
Tim Peters6f853562004-10-01 01:04:50 +000086static block *
Raymond Hettinger82df9252013-07-07 01:43:42 -100087newblock(Py_ssize_t len) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000088 block *b;
Raymond Hettinger20b0f872013-06-23 15:44:33 -070089 /* To prevent len from overflowing PY_SSIZE_T_MAX, we refuse to
90 * allocate new blocks if the current len is nearing overflow. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000091 if (len >= PY_SSIZE_T_MAX - 2*BLOCKLEN) {
92 PyErr_SetString(PyExc_OverflowError,
93 "cannot add more blocks to the deque");
94 return NULL;
95 }
96 if (numfreeblocks) {
Raymond Hettinger59cf23a2013-02-07 00:57:19 -050097 numfreeblocks--;
Raymond Hettinger82df9252013-07-07 01:43:42 -100098 return freeblocks[numfreeblocks];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000099 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000100 b = PyMem_Malloc(sizeof(block));
101 if (b != NULL) {
102 return b;
103 }
104 PyErr_NoMemory();
105 return NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000106}
107
Martin v. Löwis59683e82008-06-13 07:50:45 +0000108static void
Guido van Rossum58da9312007-11-10 23:39:45 +0000109freeblock(block *b)
110{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000111 if (numfreeblocks < MAXFREEBLOCKS) {
112 freeblocks[numfreeblocks] = b;
113 numfreeblocks++;
114 } else {
115 PyMem_Free(b);
116 }
Guido van Rossum58da9312007-11-10 23:39:45 +0000117}
118
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000119typedef struct {
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000120 PyObject_VAR_HEAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000121 block *leftblock;
122 block *rightblock;
123 Py_ssize_t leftindex; /* in range(BLOCKLEN) */
124 Py_ssize_t rightindex; /* in range(BLOCKLEN) */
Raymond Hettinger90dea4c2013-07-13 22:30:25 -0700125 long state; /* incremented whenever the indices move */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000126 Py_ssize_t maxlen;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000127 PyObject *weakreflist; /* List of weak references */
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000128} dequeobject;
129
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000130/* The deque's size limit is d.maxlen. The limit can be zero or positive.
131 * If there is no limit, then d.maxlen == -1.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000132 *
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000133 * After an item is added to a deque, we check to see if the size has grown past
134 * the limit. If it has, we get the size back down to the limit by popping an
135 * item off of the opposite end. The methods that can trigger this are append(),
136 * appendleft(), extend(), and extendleft().
137 */
138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000139#define TRIM(d, popfunction) \
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000140 if (d->maxlen != -1 && Py_SIZE(d) > d->maxlen) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000141 PyObject *rv = popfunction(d, NULL); \
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000142 assert(rv != NULL && Py_SIZE(d) <= d->maxlen); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000143 Py_DECREF(rv); \
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000144 }
145
Neal Norwitz87f10132004-02-29 15:40:53 +0000146static PyTypeObject deque_type;
Raymond Hettinger738ec902004-02-29 02:15:56 +0000147
Raymond Hettinger54023152014-04-23 00:58:48 -0700148/* XXX Todo:
149 If aligned memory allocations become available, make the
150 deque object 64 byte aligned so that all of the fields
151 can be retrieved or updated in a single cache line.
152*/
153
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000154static PyObject *
155deque_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
156{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000157 dequeobject *deque;
158 block *b;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000159
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000160 /* create dequeobject structure */
161 deque = (dequeobject *)type->tp_alloc(type, 0);
162 if (deque == NULL)
163 return NULL;
Tim Peters1065f752004-10-01 01:03:29 +0000164
Raymond Hettinger82df9252013-07-07 01:43:42 -1000165 b = newblock(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000166 if (b == NULL) {
167 Py_DECREF(deque);
168 return NULL;
169 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000170 MARK_END(b->leftlink);
171 MARK_END(b->rightlink);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000173 assert(BLOCKLEN >= 2);
174 deque->leftblock = b;
175 deque->rightblock = b;
176 deque->leftindex = CENTER + 1;
177 deque->rightindex = CENTER;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000178 Py_SIZE(deque) = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000179 deque->state = 0;
180 deque->weakreflist = NULL;
181 deque->maxlen = -1;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000182
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000183 return (PyObject *)deque;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000184}
185
186static PyObject *
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000187deque_pop(dequeobject *deque, PyObject *unused)
188{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000189 PyObject *item;
190 block *prevblock;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000191
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000192 if (Py_SIZE(deque) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000193 PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
194 return NULL;
195 }
196 item = deque->rightblock->data[deque->rightindex];
197 deque->rightindex--;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000198 Py_SIZE(deque)--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000199 deque->state++;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000201 if (deque->rightindex == -1) {
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000202 if (Py_SIZE(deque) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000203 assert(deque->leftblock == deque->rightblock);
204 assert(deque->leftindex == deque->rightindex+1);
205 /* re-center instead of freeing a block */
206 deque->leftindex = CENTER + 1;
207 deque->rightindex = CENTER;
208 } else {
209 prevblock = deque->rightblock->leftlink;
210 assert(deque->leftblock != deque->rightblock);
211 freeblock(deque->rightblock);
Raymond Hettinger82df9252013-07-07 01:43:42 -1000212 CHECK_NOT_END(prevblock);
213 MARK_END(prevblock->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000214 deque->rightblock = prevblock;
215 deque->rightindex = BLOCKLEN - 1;
216 }
217 }
218 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000219}
220
221PyDoc_STRVAR(pop_doc, "Remove and return the rightmost element.");
222
223static PyObject *
224deque_popleft(dequeobject *deque, PyObject *unused)
225{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000226 PyObject *item;
227 block *prevblock;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000228
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000229 if (Py_SIZE(deque) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000230 PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
231 return NULL;
232 }
233 assert(deque->leftblock != NULL);
234 item = deque->leftblock->data[deque->leftindex];
235 deque->leftindex++;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000236 Py_SIZE(deque)--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000237 deque->state++;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000239 if (deque->leftindex == BLOCKLEN) {
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000240 if (Py_SIZE(deque) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000241 assert(deque->leftblock == deque->rightblock);
242 assert(deque->leftindex == deque->rightindex+1);
243 /* re-center instead of freeing a block */
244 deque->leftindex = CENTER + 1;
245 deque->rightindex = CENTER;
246 } else {
247 assert(deque->leftblock != deque->rightblock);
248 prevblock = deque->leftblock->rightlink;
249 freeblock(deque->leftblock);
Raymond Hettinger82df9252013-07-07 01:43:42 -1000250 CHECK_NOT_END(prevblock);
251 MARK_END(prevblock->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000252 deque->leftblock = prevblock;
253 deque->leftindex = 0;
254 }
255 }
256 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000257}
258
259PyDoc_STRVAR(popleft_doc, "Remove and return the leftmost element.");
260
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000261static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000262deque_append(dequeobject *deque, PyObject *item)
263{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000264 deque->state++;
265 if (deque->rightindex == BLOCKLEN-1) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000266 block *b = newblock(Py_SIZE(deque));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000267 if (b == NULL)
268 return NULL;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000269 b->leftlink = deque->rightblock;
270 CHECK_END(deque->rightblock->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000271 deque->rightblock->rightlink = b;
272 deque->rightblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000273 MARK_END(b->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000274 deque->rightindex = -1;
275 }
276 Py_INCREF(item);
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000277 Py_SIZE(deque)++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000278 deque->rightindex++;
279 deque->rightblock->data[deque->rightindex] = item;
280 TRIM(deque, deque_popleft);
281 Py_RETURN_NONE;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000282}
283
284PyDoc_STRVAR(append_doc, "Add an element to the right side of the deque.");
285
286static PyObject *
287deque_appendleft(dequeobject *deque, PyObject *item)
288{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000289 deque->state++;
290 if (deque->leftindex == 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000291 block *b = newblock(Py_SIZE(deque));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000292 if (b == NULL)
293 return NULL;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000294 b->rightlink = deque->leftblock;
295 CHECK_END(deque->leftblock->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000296 deque->leftblock->leftlink = b;
297 deque->leftblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000298 MARK_END(b->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000299 deque->leftindex = BLOCKLEN;
300 }
301 Py_INCREF(item);
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000302 Py_SIZE(deque)++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000303 deque->leftindex--;
304 deque->leftblock->data[deque->leftindex] = item;
305 TRIM(deque, deque_pop);
306 Py_RETURN_NONE;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000307}
308
309PyDoc_STRVAR(appendleft_doc, "Add an element to the left side of the deque.");
310
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000312/* Run an iterator to exhaustion. Shortcut for
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000313 the extend/extendleft methods when maxlen == 0. */
314static PyObject*
315consume_iterator(PyObject *it)
316{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000317 PyObject *item;
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000318
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000319 while ((item = PyIter_Next(it)) != NULL) {
320 Py_DECREF(item);
321 }
322 Py_DECREF(it);
323 if (PyErr_Occurred())
324 return NULL;
325 Py_RETURN_NONE;
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000326}
327
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000328static PyObject *
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000329deque_extend(dequeobject *deque, PyObject *iterable)
330{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000331 PyObject *it, *item;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000333 /* Handle case where id(deque) == id(iterable) */
334 if ((PyObject *)deque == iterable) {
335 PyObject *result;
336 PyObject *s = PySequence_List(iterable);
337 if (s == NULL)
338 return NULL;
339 result = deque_extend(deque, s);
340 Py_DECREF(s);
341 return result;
342 }
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000343
Raymond Hettingerd9c116c2013-07-09 00:13:21 -0700344 /* Space saving heuristic. Start filling from the left */
345 if (Py_SIZE(deque) == 0) {
346 assert(deque->leftblock == deque->rightblock);
347 assert(deque->leftindex == deque->rightindex+1);
348 deque->leftindex = 1;
349 deque->rightindex = 0;
350 }
351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000352 it = PyObject_GetIter(iterable);
353 if (it == NULL)
354 return NULL;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000356 if (deque->maxlen == 0)
357 return consume_iterator(it);
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000359 while ((item = PyIter_Next(it)) != NULL) {
360 deque->state++;
361 if (deque->rightindex == BLOCKLEN-1) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000362 block *b = newblock(Py_SIZE(deque));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000363 if (b == NULL) {
364 Py_DECREF(item);
365 Py_DECREF(it);
366 return NULL;
367 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000368 b->leftlink = deque->rightblock;
369 CHECK_END(deque->rightblock->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000370 deque->rightblock->rightlink = b;
371 deque->rightblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000372 MARK_END(b->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000373 deque->rightindex = -1;
374 }
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000375 Py_SIZE(deque)++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000376 deque->rightindex++;
377 deque->rightblock->data[deque->rightindex] = item;
378 TRIM(deque, deque_popleft);
379 }
380 Py_DECREF(it);
381 if (PyErr_Occurred())
382 return NULL;
383 Py_RETURN_NONE;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000384}
385
Tim Peters1065f752004-10-01 01:03:29 +0000386PyDoc_STRVAR(extend_doc,
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000387"Extend the right side of the deque with elements from the iterable");
388
389static PyObject *
390deque_extendleft(dequeobject *deque, PyObject *iterable)
391{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000392 PyObject *it, *item;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000394 /* Handle case where id(deque) == id(iterable) */
395 if ((PyObject *)deque == iterable) {
396 PyObject *result;
397 PyObject *s = PySequence_List(iterable);
398 if (s == NULL)
399 return NULL;
400 result = deque_extendleft(deque, s);
401 Py_DECREF(s);
402 return result;
403 }
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000404
Raymond Hettingerd9c116c2013-07-09 00:13:21 -0700405 /* Space saving heuristic. Start filling from the right */
406 if (Py_SIZE(deque) == 0) {
407 assert(deque->leftblock == deque->rightblock);
408 assert(deque->leftindex == deque->rightindex+1);
409 deque->leftindex = BLOCKLEN - 1;
410 deque->rightindex = BLOCKLEN - 2;
411 }
412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000413 it = PyObject_GetIter(iterable);
414 if (it == NULL)
415 return NULL;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 if (deque->maxlen == 0)
418 return consume_iterator(it);
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000419
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 while ((item = PyIter_Next(it)) != NULL) {
421 deque->state++;
422 if (deque->leftindex == 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000423 block *b = newblock(Py_SIZE(deque));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000424 if (b == NULL) {
425 Py_DECREF(item);
426 Py_DECREF(it);
427 return NULL;
428 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000429 b->rightlink = deque->leftblock;
430 CHECK_END(deque->leftblock->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 deque->leftblock->leftlink = b;
432 deque->leftblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000433 MARK_END(b->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000434 deque->leftindex = BLOCKLEN;
435 }
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000436 Py_SIZE(deque)++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000437 deque->leftindex--;
438 deque->leftblock->data[deque->leftindex] = item;
439 TRIM(deque, deque_pop);
440 }
441 Py_DECREF(it);
442 if (PyErr_Occurred())
443 return NULL;
444 Py_RETURN_NONE;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000445}
446
Tim Peters1065f752004-10-01 01:03:29 +0000447PyDoc_STRVAR(extendleft_doc,
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000448"Extend the left side of the deque with elements from the iterable");
449
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000450static PyObject *
451deque_inplace_concat(dequeobject *deque, PyObject *other)
452{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000453 PyObject *result;
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000454
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000455 result = deque_extend(deque, other);
456 if (result == NULL)
457 return result;
458 Py_DECREF(result);
459 Py_INCREF(deque);
460 return (PyObject *)deque;
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000461}
462
Raymond Hettinger54023152014-04-23 00:58:48 -0700463/* The rotate() method is part of the public API and is used internally
464as a primitive for other methods.
465
466Rotation by 1 or -1 is a common case, so any optimizations for high
467volume rotations should take care not to penalize the common case.
468
469Conceptually, a rotate by one is equivalent to a pop on one side and an
470append on the other. However, a pop/append pair is unnecessarily slow
471because it requires a incref/decref pair for an object located randomly
472in memory. It is better to just move the object pointer from one block
473to the next without changing the reference count.
474
475When moving batches of pointers, it is tempting to use memcpy() but that
476proved to be slower than a simple loop for a variety of reasons.
477Memcpy() cannot know in advance that we're copying pointers instead of
478bytes, that the source and destination are pointer aligned and
479non-overlapping, that moving just one pointer is a common case, that we
480never need to move more than BLOCKLEN pointers, and that at least one
481pointer is always moved.
482
483For high volume rotations, newblock() and freeblock() are never called
484more than once. Previously emptied blocks are immediately reused as a
485destination block. If a block is left-over at the end, it is freed.
486*/
487
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000488static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000489_deque_rotate(dequeobject *deque, Py_ssize_t n)
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000490{
Raymond Hettinger3959af92013-07-13 02:34:08 -0700491 block *b = NULL;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700492 block *leftblock = deque->leftblock;
493 block *rightblock = deque->rightblock;
494 Py_ssize_t leftindex = deque->leftindex;
495 Py_ssize_t rightindex = deque->rightindex;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000496 Py_ssize_t len=Py_SIZE(deque), halflen=len>>1;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700497 int rv = -1;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000498
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800499 if (len <= 1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 return 0;
501 if (n > halflen || n < -halflen) {
502 n %= len;
503 if (n > halflen)
504 n -= len;
505 else if (n < -halflen)
506 n += len;
507 }
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500508 assert(len > 1);
Raymond Hettingera4409c12013-02-04 00:08:12 -0500509 assert(-halflen <= n && n <= halflen);
Raymond Hettinger231ee4d2013-02-02 11:24:43 -0800510
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800511 deque->state++;
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500512 while (n > 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700513 if (leftindex == 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700514 if (b == NULL) {
Raymond Hettinger3959af92013-07-13 02:34:08 -0700515 b = newblock(len);
516 if (b == NULL)
517 goto done;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700518 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000519 b->rightlink = leftblock;
520 CHECK_END(leftblock->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700521 leftblock->leftlink = b;
522 leftblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000523 MARK_END(b->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700524 leftindex = BLOCKLEN;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700525 b = NULL;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800526 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700527 assert(leftindex > 0);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700528 {
529 PyObject **src, **dest;
530 Py_ssize_t m = n;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800531
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700532 if (m > rightindex + 1)
533 m = rightindex + 1;
534 if (m > leftindex)
535 m = leftindex;
536 assert (m > 0 && m <= len);
537 src = &rightblock->data[rightindex];
538 dest = &leftblock->data[leftindex - 1];
539 rightindex -= m;
540 leftindex -= m;
541 n -= m;
Raymond Hettinger840533b2013-07-13 17:03:58 -0700542 do {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700543 *(dest--) = *(src--);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700544 } while (--m);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700545 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700546 if (rightindex == -1) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700547 assert(leftblock != rightblock);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700548 assert(b == NULL);
Raymond Hettinger3959af92013-07-13 02:34:08 -0700549 b = rightblock;
Raymond Hettingerb97cc492013-07-21 01:51:07 -0700550 CHECK_NOT_END(rightblock->leftlink);
551 rightblock = rightblock->leftlink;
552 MARK_END(rightblock->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700553 rightindex = BLOCKLEN - 1;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800554 }
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800555 }
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500556 while (n < 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700557 if (rightindex == BLOCKLEN - 1) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700558 if (b == NULL) {
Raymond Hettinger3959af92013-07-13 02:34:08 -0700559 b = newblock(len);
560 if (b == NULL)
561 goto done;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700562 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000563 b->leftlink = rightblock;
564 CHECK_END(rightblock->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700565 rightblock->rightlink = b;
566 rightblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000567 MARK_END(b->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700568 rightindex = -1;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700569 b = NULL;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800570 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700571 assert (rightindex < BLOCKLEN - 1);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700572 {
573 PyObject **src, **dest;
574 Py_ssize_t m = -n;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800575
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700576 if (m > BLOCKLEN - leftindex)
577 m = BLOCKLEN - leftindex;
578 if (m > BLOCKLEN - 1 - rightindex)
579 m = BLOCKLEN - 1 - rightindex;
580 assert (m > 0 && m <= len);
581 src = &leftblock->data[leftindex];
582 dest = &rightblock->data[rightindex + 1];
583 leftindex += m;
584 rightindex += m;
585 n += m;
Raymond Hettinger840533b2013-07-13 17:03:58 -0700586 do {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700587 *(dest++) = *(src++);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700588 } while (--m);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700589 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700590 if (leftindex == BLOCKLEN) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700591 assert(leftblock != rightblock);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700592 assert(b == NULL);
Raymond Hettinger3959af92013-07-13 02:34:08 -0700593 b = leftblock;
Raymond Hettingerb97cc492013-07-21 01:51:07 -0700594 CHECK_NOT_END(leftblock->rightlink);
595 leftblock = leftblock->rightlink;
596 MARK_END(leftblock->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700597 leftindex = 0;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800598 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000599 }
Raymond Hettinger3959af92013-07-13 02:34:08 -0700600 rv = 0;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700601done:
Raymond Hettinger3959af92013-07-13 02:34:08 -0700602 if (b != NULL)
603 freeblock(b);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700604 deque->leftblock = leftblock;
605 deque->rightblock = rightblock;
606 deque->leftindex = leftindex;
607 deque->rightindex = rightindex;
608
609 return rv;
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000610}
611
612static PyObject *
613deque_rotate(dequeobject *deque, PyObject *args)
614{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 Py_ssize_t n=1;
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000617 if (!PyArg_ParseTuple(args, "|n:rotate", &n))
618 return NULL;
619 if (_deque_rotate(deque, n) == 0)
620 Py_RETURN_NONE;
621 return NULL;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000622}
623
Tim Peters1065f752004-10-01 01:03:29 +0000624PyDoc_STRVAR(rotate_doc,
Raymond Hettingeree33b272004-02-08 04:05:26 +0000625"Rotate the deque n steps to the right (default n=1). If n is negative, rotates left.");
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000626
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000627static PyObject *
628deque_reverse(dequeobject *deque, PyObject *unused)
629{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 block *leftblock = deque->leftblock;
631 block *rightblock = deque->rightblock;
632 Py_ssize_t leftindex = deque->leftindex;
633 Py_ssize_t rightindex = deque->rightindex;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000634 Py_ssize_t n = (Py_SIZE(deque))/2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000635 Py_ssize_t i;
636 PyObject *tmp;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000637
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 for (i=0 ; i<n ; i++) {
639 /* Validate that pointers haven't met in the middle */
640 assert(leftblock != rightblock || leftindex < rightindex);
Raymond Hettinger82df9252013-07-07 01:43:42 -1000641 CHECK_NOT_END(leftblock);
642 CHECK_NOT_END(rightblock);
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000643
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 /* Swap */
645 tmp = leftblock->data[leftindex];
646 leftblock->data[leftindex] = rightblock->data[rightindex];
647 rightblock->data[rightindex] = tmp;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000649 /* Advance left block/index pair */
650 leftindex++;
651 if (leftindex == BLOCKLEN) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000652 leftblock = leftblock->rightlink;
653 leftindex = 0;
654 }
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000655
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000656 /* Step backwards with the right block/index pair */
657 rightindex--;
658 if (rightindex == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000659 rightblock = rightblock->leftlink;
660 rightindex = BLOCKLEN - 1;
661 }
662 }
663 Py_RETURN_NONE;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000664}
665
666PyDoc_STRVAR(reverse_doc,
667"D.reverse() -- reverse *IN PLACE*");
668
Raymond Hettinger44459de2010-04-03 23:20:46 +0000669static PyObject *
670deque_count(dequeobject *deque, PyObject *v)
671{
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000672 block *b = deque->leftblock;
673 Py_ssize_t index = deque->leftindex;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000674 Py_ssize_t n = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000675 Py_ssize_t i;
676 Py_ssize_t count = 0;
677 PyObject *item;
678 long start_state = deque->state;
679 int cmp;
Raymond Hettinger44459de2010-04-03 23:20:46 +0000680
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000681 for (i=0 ; i<n ; i++) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000682 CHECK_NOT_END(b);
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000683 item = b->data[index];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000684 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
685 if (cmp > 0)
686 count++;
687 else if (cmp < 0)
688 return NULL;
Raymond Hettinger44459de2010-04-03 23:20:46 +0000689
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000690 if (start_state != deque->state) {
691 PyErr_SetString(PyExc_RuntimeError,
692 "deque mutated during iteration");
693 return NULL;
694 }
Raymond Hettinger44459de2010-04-03 23:20:46 +0000695
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000696 /* Advance left block/index pair */
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000697 index++;
698 if (index == BLOCKLEN) {
699 b = b->rightlink;
700 index = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000701 }
702 }
703 return PyLong_FromSsize_t(count);
Raymond Hettinger44459de2010-04-03 23:20:46 +0000704}
705
706PyDoc_STRVAR(count_doc,
707"D.count(value) -> integer -- return number of occurrences of value");
708
Martin v. Löwis18e16552006-02-15 17:27:45 +0000709static Py_ssize_t
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000710deque_len(dequeobject *deque)
711{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000712 return Py_SIZE(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000713}
714
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000715static PyObject *
716deque_remove(dequeobject *deque, PyObject *value)
717{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000718 Py_ssize_t i, n=Py_SIZE(deque);
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000719
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000720 for (i=0 ; i<n ; i++) {
721 PyObject *item = deque->leftblock->data[deque->leftindex];
722 int cmp = PyObject_RichCompareBool(item, value, Py_EQ);
Raymond Hettingerd73202c2005-03-19 00:00:51 +0000723
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000724 if (Py_SIZE(deque) != n) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000725 PyErr_SetString(PyExc_IndexError,
726 "deque mutated during remove().");
727 return NULL;
728 }
729 if (cmp > 0) {
730 PyObject *tgt = deque_popleft(deque, NULL);
731 assert (tgt != NULL);
732 Py_DECREF(tgt);
733 if (_deque_rotate(deque, i) == -1)
734 return NULL;
735 Py_RETURN_NONE;
736 }
737 else if (cmp < 0) {
738 _deque_rotate(deque, i);
739 return NULL;
740 }
741 _deque_rotate(deque, -1);
742 }
743 PyErr_SetString(PyExc_ValueError, "deque.remove(x): x not in deque");
744 return NULL;
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000745}
746
747PyDoc_STRVAR(remove_doc,
748"D.remove(value) -- remove first occurrence of value.");
749
Benjamin Peterson0e5c48a2013-01-12 21:22:18 -0500750static void
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000751deque_clear(dequeobject *deque)
752{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000753 PyObject *item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000754
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000755 while (Py_SIZE(deque)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 item = deque_pop(deque, NULL);
757 assert (item != NULL);
758 Py_DECREF(item);
759 }
760 assert(deque->leftblock == deque->rightblock &&
761 deque->leftindex - 1 == deque->rightindex &&
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000762 Py_SIZE(deque) == 0);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000763}
764
765static PyObject *
Benjamin Petersond6313712008-07-31 16:23:04 +0000766deque_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000767{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000768 block *b;
769 PyObject *item;
770 Py_ssize_t n, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000771
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000772 if (i < 0 || i >= Py_SIZE(deque)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000773 PyErr_SetString(PyExc_IndexError,
774 "deque index out of range");
775 return NULL;
776 }
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000777
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 if (i == 0) {
779 i = deque->leftindex;
780 b = deque->leftblock;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000781 } else if (i == Py_SIZE(deque) - 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 i = deque->rightindex;
783 b = deque->rightblock;
784 } else {
785 i += deque->leftindex;
786 n = i / BLOCKLEN;
787 i %= BLOCKLEN;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000788 if (index < (Py_SIZE(deque) >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 b = deque->leftblock;
790 while (n--)
791 b = b->rightlink;
792 } else {
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000793 n = (deque->leftindex + Py_SIZE(deque) - 1) / BLOCKLEN - n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000794 b = deque->rightblock;
795 while (n--)
796 b = b->leftlink;
797 }
798 }
799 item = b->data[i];
800 Py_INCREF(item);
801 return item;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000802}
803
Raymond Hettinger616f4f62004-06-26 04:42:06 +0000804/* delitem() implemented in terms of rotate for simplicity and reasonable
805 performance near the end points. If for some reason this method becomes
Tim Peters1065f752004-10-01 01:03:29 +0000806 popular, it is not hard to re-implement this using direct data movement
Raymond Hettinger616f4f62004-06-26 04:42:06 +0000807 (similar to code in list slice assignment) and achieve a two or threefold
808 performance boost.
809*/
810
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000811static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000812deque_del_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000813{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000814 PyObject *item;
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000815
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000816 assert (i >= 0 && i < Py_SIZE(deque));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000817 if (_deque_rotate(deque, -i) == -1)
818 return -1;
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000819
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000820 item = deque_popleft(deque, NULL);
821 assert (item != NULL);
822 Py_DECREF(item);
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000823
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000824 return _deque_rotate(deque, i);
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000825}
826
827static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000828deque_ass_item(dequeobject *deque, Py_ssize_t i, PyObject *v)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000829{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 PyObject *old_value;
831 block *b;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000832 Py_ssize_t n, len=Py_SIZE(deque), halflen=(len+1)>>1, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000834 if (i < 0 || i >= len) {
835 PyErr_SetString(PyExc_IndexError,
836 "deque index out of range");
837 return -1;
838 }
839 if (v == NULL)
840 return deque_del_item(deque, i);
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000841
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000842 i += deque->leftindex;
843 n = i / BLOCKLEN;
844 i %= BLOCKLEN;
845 if (index <= halflen) {
846 b = deque->leftblock;
847 while (n--)
848 b = b->rightlink;
849 } else {
850 n = (deque->leftindex + len - 1) / BLOCKLEN - n;
851 b = deque->rightblock;
852 while (n--)
853 b = b->leftlink;
854 }
855 Py_INCREF(v);
856 old_value = b->data[i];
857 b->data[i] = v;
858 Py_DECREF(old_value);
859 return 0;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000860}
861
862static PyObject *
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000863deque_clearmethod(dequeobject *deque)
864{
Benjamin Peterson0e5c48a2013-01-12 21:22:18 -0500865 deque_clear(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 Py_RETURN_NONE;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000867}
868
869PyDoc_STRVAR(clear_doc, "Remove all elements from the deque.");
870
871static void
872deque_dealloc(dequeobject *deque)
873{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000874 PyObject_GC_UnTrack(deque);
875 if (deque->weakreflist != NULL)
876 PyObject_ClearWeakRefs((PyObject *) deque);
877 if (deque->leftblock != NULL) {
878 deque_clear(deque);
879 assert(deque->leftblock != NULL);
880 freeblock(deque->leftblock);
881 }
882 deque->leftblock = NULL;
883 deque->rightblock = NULL;
884 Py_TYPE(deque)->tp_free(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000885}
886
887static int
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000888deque_traverse(dequeobject *deque, visitproc visit, void *arg)
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000889{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000890 block *b;
891 PyObject *item;
892 Py_ssize_t index;
893 Py_ssize_t indexlo = deque->leftindex;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000894
Raymond Hettinger5bfa8672013-07-06 11:58:09 -1000895 for (b = deque->leftblock; b != deque->rightblock; b = b->rightlink) {
896 for (index = indexlo; index < BLOCKLEN ; index++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000897 item = b->data[index];
898 Py_VISIT(item);
899 }
900 indexlo = 0;
901 }
Raymond Hettinger5bfa8672013-07-06 11:58:09 -1000902 for (index = indexlo; index <= deque->rightindex; index++) {
903 item = b->data[index];
904 Py_VISIT(item);
905 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 return 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000907}
908
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000909static PyObject *
910deque_copy(PyObject *deque)
911{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000912 if (((dequeobject *)deque)->maxlen == -1)
913 return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "O", deque, NULL);
914 else
915 return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "Oi",
916 deque, ((dequeobject *)deque)->maxlen, NULL);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000917}
918
919PyDoc_STRVAR(copy_doc, "Return a shallow copy of a deque.");
920
921static PyObject *
922deque_reduce(dequeobject *deque)
923{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 PyObject *dict, *result, *aslist;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200925 _Py_IDENTIFIER(__dict__);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000926
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200927 dict = _PyObject_GetAttrId((PyObject *)deque, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 if (dict == NULL)
929 PyErr_Clear();
930 aslist = PySequence_List((PyObject *)deque);
931 if (aslist == NULL) {
932 Py_XDECREF(dict);
933 return NULL;
934 }
935 if (dict == NULL) {
936 if (deque->maxlen == -1)
937 result = Py_BuildValue("O(O)", Py_TYPE(deque), aslist);
938 else
939 result = Py_BuildValue("O(On)", Py_TYPE(deque), aslist, deque->maxlen);
940 } else {
941 if (deque->maxlen == -1)
942 result = Py_BuildValue("O(OO)O", Py_TYPE(deque), aslist, Py_None, dict);
943 else
944 result = Py_BuildValue("O(On)O", Py_TYPE(deque), aslist, deque->maxlen, dict);
945 }
946 Py_XDECREF(dict);
947 Py_DECREF(aslist);
948 return result;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000949}
950
951PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
952
953static PyObject *
954deque_repr(PyObject *deque)
955{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000956 PyObject *aslist, *result;
957 int i;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000958
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 i = Py_ReprEnter(deque);
960 if (i != 0) {
961 if (i < 0)
962 return NULL;
963 return PyUnicode_FromString("[...]");
964 }
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000965
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 aslist = PySequence_List(deque);
967 if (aslist == NULL) {
968 Py_ReprLeave(deque);
969 return NULL;
970 }
971 if (((dequeobject *)deque)->maxlen != -1)
Benjamin Petersona786b022008-08-25 21:05:21 +0000972
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000973 result = PyUnicode_FromFormat("deque(%R, maxlen=%zd)",
974 aslist, ((dequeobject *)deque)->maxlen);
975 else
976 result = PyUnicode_FromFormat("deque(%R)", aslist);
977 Py_DECREF(aslist);
978 Py_ReprLeave(deque);
979 return result;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000980}
981
Raymond Hettinger738ec902004-02-29 02:15:56 +0000982static PyObject *
983deque_richcompare(PyObject *v, PyObject *w, int op)
984{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000985 PyObject *it1=NULL, *it2=NULL, *x, *y;
986 Py_ssize_t vs, ws;
987 int b, cmp=-1;
Raymond Hettinger738ec902004-02-29 02:15:56 +0000988
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000989 if (!PyObject_TypeCheck(v, &deque_type) ||
990 !PyObject_TypeCheck(w, &deque_type)) {
Brian Curtindfc80e32011-08-10 20:28:54 -0500991 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992 }
Raymond Hettinger738ec902004-02-29 02:15:56 +0000993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000994 /* Shortcuts */
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000995 vs = Py_SIZE((dequeobject *)v);
996 ws = Py_SIZE((dequeobject *)w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 if (op == Py_EQ) {
998 if (v == w)
999 Py_RETURN_TRUE;
1000 if (vs != ws)
1001 Py_RETURN_FALSE;
1002 }
1003 if (op == Py_NE) {
1004 if (v == w)
1005 Py_RETURN_FALSE;
1006 if (vs != ws)
1007 Py_RETURN_TRUE;
1008 }
Raymond Hettinger738ec902004-02-29 02:15:56 +00001009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001010 /* Search for the first index where items are different */
1011 it1 = PyObject_GetIter(v);
1012 if (it1 == NULL)
1013 goto done;
1014 it2 = PyObject_GetIter(w);
1015 if (it2 == NULL)
1016 goto done;
1017 for (;;) {
1018 x = PyIter_Next(it1);
1019 if (x == NULL && PyErr_Occurred())
1020 goto done;
1021 y = PyIter_Next(it2);
1022 if (x == NULL || y == NULL)
1023 break;
1024 b = PyObject_RichCompareBool(x, y, Py_EQ);
1025 if (b == 0) {
1026 cmp = PyObject_RichCompareBool(x, y, op);
1027 Py_DECREF(x);
1028 Py_DECREF(y);
1029 goto done;
1030 }
1031 Py_DECREF(x);
1032 Py_DECREF(y);
1033 if (b == -1)
1034 goto done;
1035 }
1036 /* We reached the end of one deque or both */
1037 Py_XDECREF(x);
1038 Py_XDECREF(y);
1039 if (PyErr_Occurred())
1040 goto done;
1041 switch (op) {
1042 case Py_LT: cmp = y != NULL; break; /* if w was longer */
1043 case Py_LE: cmp = x == NULL; break; /* if v was not longer */
1044 case Py_EQ: cmp = x == y; break; /* if we reached the end of both */
1045 case Py_NE: cmp = x != y; break; /* if one deque continues */
1046 case Py_GT: cmp = x != NULL; break; /* if v was longer */
1047 case Py_GE: cmp = y == NULL; break; /* if w was not longer */
1048 }
Tim Peters1065f752004-10-01 01:03:29 +00001049
Raymond Hettinger738ec902004-02-29 02:15:56 +00001050done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001051 Py_XDECREF(it1);
1052 Py_XDECREF(it2);
1053 if (cmp == 1)
1054 Py_RETURN_TRUE;
1055 if (cmp == 0)
1056 Py_RETURN_FALSE;
1057 return NULL;
Raymond Hettinger738ec902004-02-29 02:15:56 +00001058}
1059
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001060static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001061deque_init(dequeobject *deque, PyObject *args, PyObject *kwdargs)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001062{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001063 PyObject *iterable = NULL;
1064 PyObject *maxlenobj = NULL;
1065 Py_ssize_t maxlen = -1;
1066 char *kwlist[] = {"iterable", "maxlen", 0};
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001068 if (!PyArg_ParseTupleAndKeywords(args, kwdargs, "|OO:deque", kwlist, &iterable, &maxlenobj))
1069 return -1;
1070 if (maxlenobj != NULL && maxlenobj != Py_None) {
1071 maxlen = PyLong_AsSsize_t(maxlenobj);
1072 if (maxlen == -1 && PyErr_Occurred())
1073 return -1;
1074 if (maxlen < 0) {
1075 PyErr_SetString(PyExc_ValueError, "maxlen must be non-negative");
1076 return -1;
1077 }
1078 }
1079 deque->maxlen = maxlen;
1080 deque_clear(deque);
1081 if (iterable != NULL) {
1082 PyObject *rv = deque_extend(deque, iterable);
1083 if (rv == NULL)
1084 return -1;
1085 Py_DECREF(rv);
1086 }
1087 return 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001088}
1089
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001090static PyObject *
Jesus Cea16e2fca2012-08-03 14:49:42 +02001091deque_sizeof(dequeobject *deque, void *unused)
1092{
1093 Py_ssize_t res;
1094 Py_ssize_t blocks;
1095
1096 res = sizeof(dequeobject);
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001097 blocks = (deque->leftindex + Py_SIZE(deque) + BLOCKLEN - 1) / BLOCKLEN;
1098 assert(deque->leftindex + Py_SIZE(deque) - 1 ==
Jesus Cea16e2fca2012-08-03 14:49:42 +02001099 (blocks - 1) * BLOCKLEN + deque->rightindex);
1100 res += blocks * sizeof(block);
1101 return PyLong_FromSsize_t(res);
1102}
1103
1104PyDoc_STRVAR(sizeof_doc,
1105"D.__sizeof__() -- size of D in memory, in bytes");
1106
1107static PyObject *
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001108deque_get_maxlen(dequeobject *deque)
1109{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001110 if (deque->maxlen == -1)
1111 Py_RETURN_NONE;
1112 return PyLong_FromSsize_t(deque->maxlen);
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001113}
1114
1115static PyGetSetDef deque_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001116 {"maxlen", (getter)deque_get_maxlen, (setter)NULL,
1117 "maximum size of a deque or None if unbounded"},
1118 {0}
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001119};
1120
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001121static PySequenceMethods deque_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001122 (lenfunc)deque_len, /* sq_length */
1123 0, /* sq_concat */
1124 0, /* sq_repeat */
1125 (ssizeargfunc)deque_item, /* sq_item */
1126 0, /* sq_slice */
1127 (ssizeobjargproc)deque_ass_item, /* sq_ass_item */
1128 0, /* sq_ass_slice */
1129 0, /* sq_contains */
1130 (binaryfunc)deque_inplace_concat, /* sq_inplace_concat */
1131 0, /* sq_inplace_repeat */
Raymond Hettinger3f9afd82009-12-10 03:03:02 +00001132
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001133};
1134
1135/* deque object ********************************************************/
1136
1137static PyObject *deque_iter(dequeobject *deque);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001138static PyObject *deque_reviter(dequeobject *deque);
Tim Peters1065f752004-10-01 01:03:29 +00001139PyDoc_STRVAR(reversed_doc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001140 "D.__reversed__() -- return a reverse iterator over the deque");
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001141
1142static PyMethodDef deque_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001143 {"append", (PyCFunction)deque_append,
1144 METH_O, append_doc},
1145 {"appendleft", (PyCFunction)deque_appendleft,
1146 METH_O, appendleft_doc},
1147 {"clear", (PyCFunction)deque_clearmethod,
1148 METH_NOARGS, clear_doc},
1149 {"__copy__", (PyCFunction)deque_copy,
1150 METH_NOARGS, copy_doc},
1151 {"count", (PyCFunction)deque_count,
1152 METH_O, count_doc},
1153 {"extend", (PyCFunction)deque_extend,
1154 METH_O, extend_doc},
1155 {"extendleft", (PyCFunction)deque_extendleft,
1156 METH_O, extendleft_doc},
1157 {"pop", (PyCFunction)deque_pop,
1158 METH_NOARGS, pop_doc},
1159 {"popleft", (PyCFunction)deque_popleft,
1160 METH_NOARGS, popleft_doc},
1161 {"__reduce__", (PyCFunction)deque_reduce,
1162 METH_NOARGS, reduce_doc},
1163 {"remove", (PyCFunction)deque_remove,
1164 METH_O, remove_doc},
1165 {"__reversed__", (PyCFunction)deque_reviter,
1166 METH_NOARGS, reversed_doc},
1167 {"reverse", (PyCFunction)deque_reverse,
1168 METH_NOARGS, reverse_doc},
1169 {"rotate", (PyCFunction)deque_rotate,
Jesus Cea16e2fca2012-08-03 14:49:42 +02001170 METH_VARARGS, rotate_doc},
1171 {"__sizeof__", (PyCFunction)deque_sizeof,
1172 METH_NOARGS, sizeof_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001173 {NULL, NULL} /* sentinel */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001174};
1175
1176PyDoc_STRVAR(deque_doc,
Andrew Svetlov6a5c7c32012-10-31 11:50:40 +02001177"deque([iterable[, maxlen]]) --> deque object\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001178\n\
Raymond Hettinger49747052011-03-29 17:36:31 -07001179Build an ordered collection with optimized access from its endpoints.");
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001180
Neal Norwitz87f10132004-02-29 15:40:53 +00001181static PyTypeObject deque_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 PyVarObject_HEAD_INIT(NULL, 0)
1183 "collections.deque", /* tp_name */
1184 sizeof(dequeobject), /* tp_basicsize */
1185 0, /* tp_itemsize */
1186 /* methods */
1187 (destructor)deque_dealloc, /* tp_dealloc */
1188 0, /* tp_print */
1189 0, /* tp_getattr */
1190 0, /* tp_setattr */
1191 0, /* tp_reserved */
1192 deque_repr, /* tp_repr */
1193 0, /* tp_as_number */
1194 &deque_as_sequence, /* tp_as_sequence */
1195 0, /* tp_as_mapping */
Georg Brandlf038b322010-10-18 07:35:09 +00001196 PyObject_HashNotImplemented, /* tp_hash */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001197 0, /* tp_call */
1198 0, /* tp_str */
1199 PyObject_GenericGetAttr, /* tp_getattro */
1200 0, /* tp_setattro */
1201 0, /* tp_as_buffer */
1202 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
Georg Brandlf038b322010-10-18 07:35:09 +00001203 /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 deque_doc, /* tp_doc */
1205 (traverseproc)deque_traverse, /* tp_traverse */
1206 (inquiry)deque_clear, /* tp_clear */
1207 (richcmpfunc)deque_richcompare, /* tp_richcompare */
Georg Brandlf038b322010-10-18 07:35:09 +00001208 offsetof(dequeobject, weakreflist), /* tp_weaklistoffset*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 (getiterfunc)deque_iter, /* tp_iter */
1210 0, /* tp_iternext */
1211 deque_methods, /* tp_methods */
1212 0, /* tp_members */
Georg Brandlf038b322010-10-18 07:35:09 +00001213 deque_getset, /* tp_getset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001214 0, /* tp_base */
1215 0, /* tp_dict */
1216 0, /* tp_descr_get */
1217 0, /* tp_descr_set */
1218 0, /* tp_dictoffset */
1219 (initproc)deque_init, /* tp_init */
1220 PyType_GenericAlloc, /* tp_alloc */
1221 deque_new, /* tp_new */
1222 PyObject_GC_Del, /* tp_free */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001223};
1224
1225/*********************** Deque Iterator **************************/
1226
1227typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001228 PyObject_HEAD
1229 Py_ssize_t index;
1230 block *b;
1231 dequeobject *deque;
1232 long state; /* state when the iterator is created */
1233 Py_ssize_t counter; /* number of items remaining for iteration */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001234} dequeiterobject;
1235
Martin v. Löwis59683e82008-06-13 07:50:45 +00001236static PyTypeObject dequeiter_type;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001237
1238static PyObject *
1239deque_iter(dequeobject *deque)
1240{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001241 dequeiterobject *it;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001243 it = PyObject_GC_New(dequeiterobject, &dequeiter_type);
1244 if (it == NULL)
1245 return NULL;
1246 it->b = deque->leftblock;
1247 it->index = deque->leftindex;
1248 Py_INCREF(deque);
1249 it->deque = deque;
1250 it->state = deque->state;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001251 it->counter = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001252 PyObject_GC_Track(it);
1253 return (PyObject *)it;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001254}
1255
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001256static int
1257dequeiter_traverse(dequeiterobject *dio, visitproc visit, void *arg)
1258{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001259 Py_VISIT(dio->deque);
1260 return 0;
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001261}
1262
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001263static void
1264dequeiter_dealloc(dequeiterobject *dio)
1265{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001266 Py_XDECREF(dio->deque);
1267 PyObject_GC_Del(dio);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001268}
1269
1270static PyObject *
1271dequeiter_next(dequeiterobject *it)
1272{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001273 PyObject *item;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001275 if (it->deque->state != it->state) {
1276 it->counter = 0;
1277 PyErr_SetString(PyExc_RuntimeError,
1278 "deque mutated during iteration");
1279 return NULL;
1280 }
1281 if (it->counter == 0)
1282 return NULL;
1283 assert (!(it->b == it->deque->rightblock &&
1284 it->index > it->deque->rightindex));
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001286 item = it->b->data[it->index];
1287 it->index++;
1288 it->counter--;
1289 if (it->index == BLOCKLEN && it->counter > 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -10001290 CHECK_NOT_END(it->b->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001291 it->b = it->b->rightlink;
1292 it->index = 0;
1293 }
1294 Py_INCREF(item);
1295 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001296}
1297
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001298static PyObject *
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001299dequeiter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1300{
1301 Py_ssize_t i, index=0;
1302 PyObject *deque;
1303 dequeiterobject *it;
1304 if (!PyArg_ParseTuple(args, "O!|n", &deque_type, &deque, &index))
1305 return NULL;
1306 assert(type == &dequeiter_type);
1307
1308 it = (dequeiterobject*)deque_iter((dequeobject *)deque);
1309 if (!it)
1310 return NULL;
1311 /* consume items from the queue */
1312 for(i=0; i<index; i++) {
1313 PyObject *item = dequeiter_next(it);
1314 if (item) {
1315 Py_DECREF(item);
1316 } else {
1317 if (it->counter) {
1318 Py_DECREF(it);
1319 return NULL;
1320 } else
1321 break;
1322 }
1323 }
1324 return (PyObject*)it;
1325}
1326
1327static PyObject *
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001328dequeiter_len(dequeiterobject *it)
1329{
Antoine Pitrou554f3342010-08-17 18:30:06 +00001330 return PyLong_FromSsize_t(it->counter);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001331}
1332
Armin Rigof5b3e362006-02-11 21:32:43 +00001333PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001334
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001335static PyObject *
1336dequeiter_reduce(dequeiterobject *it)
1337{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001338 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 +00001339}
1340
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001341static PyMethodDef dequeiter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001342 {"__length_hint__", (PyCFunction)dequeiter_len, METH_NOARGS, length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001343 {"__reduce__", (PyCFunction)dequeiter_reduce, METH_NOARGS, reduce_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001344 {NULL, NULL} /* sentinel */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001345};
1346
Martin v. Löwis59683e82008-06-13 07:50:45 +00001347static PyTypeObject dequeiter_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001348 PyVarObject_HEAD_INIT(NULL, 0)
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001349 "_collections._deque_iterator", /* tp_name */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001350 sizeof(dequeiterobject), /* tp_basicsize */
1351 0, /* tp_itemsize */
1352 /* methods */
1353 (destructor)dequeiter_dealloc, /* tp_dealloc */
1354 0, /* tp_print */
1355 0, /* tp_getattr */
1356 0, /* tp_setattr */
1357 0, /* tp_reserved */
1358 0, /* tp_repr */
1359 0, /* tp_as_number */
1360 0, /* tp_as_sequence */
1361 0, /* tp_as_mapping */
1362 0, /* tp_hash */
1363 0, /* tp_call */
1364 0, /* tp_str */
1365 PyObject_GenericGetAttr, /* tp_getattro */
1366 0, /* tp_setattro */
1367 0, /* tp_as_buffer */
1368 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
1369 0, /* tp_doc */
1370 (traverseproc)dequeiter_traverse, /* tp_traverse */
1371 0, /* tp_clear */
1372 0, /* tp_richcompare */
1373 0, /* tp_weaklistoffset */
1374 PyObject_SelfIter, /* tp_iter */
1375 (iternextfunc)dequeiter_next, /* tp_iternext */
1376 dequeiter_methods, /* tp_methods */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001377 0, /* tp_members */
1378 0, /* tp_getset */
1379 0, /* tp_base */
1380 0, /* tp_dict */
1381 0, /* tp_descr_get */
1382 0, /* tp_descr_set */
1383 0, /* tp_dictoffset */
1384 0, /* tp_init */
1385 0, /* tp_alloc */
1386 dequeiter_new, /* tp_new */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001387 0,
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001388};
1389
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001390/*********************** Deque Reverse Iterator **************************/
1391
Martin v. Löwis59683e82008-06-13 07:50:45 +00001392static PyTypeObject dequereviter_type;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001393
1394static PyObject *
1395deque_reviter(dequeobject *deque)
1396{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001397 dequeiterobject *it;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001399 it = PyObject_GC_New(dequeiterobject, &dequereviter_type);
1400 if (it == NULL)
1401 return NULL;
1402 it->b = deque->rightblock;
1403 it->index = deque->rightindex;
1404 Py_INCREF(deque);
1405 it->deque = deque;
1406 it->state = deque->state;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001407 it->counter = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001408 PyObject_GC_Track(it);
1409 return (PyObject *)it;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001410}
1411
1412static PyObject *
1413dequereviter_next(dequeiterobject *it)
1414{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001415 PyObject *item;
1416 if (it->counter == 0)
1417 return NULL;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001418
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001419 if (it->deque->state != it->state) {
1420 it->counter = 0;
1421 PyErr_SetString(PyExc_RuntimeError,
1422 "deque mutated during iteration");
1423 return NULL;
1424 }
1425 assert (!(it->b == it->deque->leftblock &&
1426 it->index < it->deque->leftindex));
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001427
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001428 item = it->b->data[it->index];
1429 it->index--;
1430 it->counter--;
1431 if (it->index == -1 && it->counter > 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -10001432 CHECK_NOT_END(it->b->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001433 it->b = it->b->leftlink;
1434 it->index = BLOCKLEN - 1;
1435 }
1436 Py_INCREF(item);
1437 return item;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001438}
1439
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001440static PyObject *
1441dequereviter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1442{
1443 Py_ssize_t i, index=0;
1444 PyObject *deque;
1445 dequeiterobject *it;
1446 if (!PyArg_ParseTuple(args, "O!|n", &deque_type, &deque, &index))
1447 return NULL;
1448 assert(type == &dequereviter_type);
1449
1450 it = (dequeiterobject*)deque_reviter((dequeobject *)deque);
1451 if (!it)
1452 return NULL;
1453 /* consume items from the queue */
1454 for(i=0; i<index; i++) {
1455 PyObject *item = dequereviter_next(it);
1456 if (item) {
1457 Py_DECREF(item);
1458 } else {
1459 if (it->counter) {
1460 Py_DECREF(it);
1461 return NULL;
1462 } else
1463 break;
1464 }
1465 }
1466 return (PyObject*)it;
1467}
1468
Martin v. Löwis59683e82008-06-13 07:50:45 +00001469static PyTypeObject dequereviter_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001470 PyVarObject_HEAD_INIT(NULL, 0)
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001471 "_collections._deque_reverse_iterator", /* tp_name */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001472 sizeof(dequeiterobject), /* tp_basicsize */
1473 0, /* tp_itemsize */
1474 /* methods */
1475 (destructor)dequeiter_dealloc, /* tp_dealloc */
1476 0, /* tp_print */
1477 0, /* tp_getattr */
1478 0, /* tp_setattr */
1479 0, /* tp_reserved */
1480 0, /* tp_repr */
1481 0, /* tp_as_number */
1482 0, /* tp_as_sequence */
1483 0, /* tp_as_mapping */
1484 0, /* tp_hash */
1485 0, /* tp_call */
1486 0, /* tp_str */
1487 PyObject_GenericGetAttr, /* tp_getattro */
1488 0, /* tp_setattro */
1489 0, /* tp_as_buffer */
1490 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
1491 0, /* tp_doc */
1492 (traverseproc)dequeiter_traverse, /* tp_traverse */
1493 0, /* tp_clear */
1494 0, /* tp_richcompare */
1495 0, /* tp_weaklistoffset */
1496 PyObject_SelfIter, /* tp_iter */
1497 (iternextfunc)dequereviter_next, /* tp_iternext */
1498 dequeiter_methods, /* tp_methods */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001499 0, /* tp_members */
1500 0, /* tp_getset */
1501 0, /* tp_base */
1502 0, /* tp_dict */
1503 0, /* tp_descr_get */
1504 0, /* tp_descr_set */
1505 0, /* tp_dictoffset */
1506 0, /* tp_init */
1507 0, /* tp_alloc */
1508 dequereviter_new, /* tp_new */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001509 0,
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001510};
1511
Guido van Rossum1968ad32006-02-25 22:38:04 +00001512/* defaultdict type *********************************************************/
1513
1514typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001515 PyDictObject dict;
1516 PyObject *default_factory;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001517} defdictobject;
1518
1519static PyTypeObject defdict_type; /* Forward */
1520
1521PyDoc_STRVAR(defdict_missing_doc,
1522"__missing__(key) # Called by __getitem__ for missing key; pseudo-code:\n\
Guido van Rossumd8faa362007-04-27 19:54:29 +00001523 if self.default_factory is None: raise KeyError((key,))\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00001524 self[key] = value = self.default_factory()\n\
1525 return value\n\
1526");
1527
1528static PyObject *
1529defdict_missing(defdictobject *dd, PyObject *key)
1530{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001531 PyObject *factory = dd->default_factory;
1532 PyObject *value;
1533 if (factory == NULL || factory == Py_None) {
1534 /* XXX Call dict.__missing__(key) */
1535 PyObject *tup;
1536 tup = PyTuple_Pack(1, key);
1537 if (!tup) return NULL;
1538 PyErr_SetObject(PyExc_KeyError, tup);
1539 Py_DECREF(tup);
1540 return NULL;
1541 }
1542 value = PyEval_CallObject(factory, NULL);
1543 if (value == NULL)
1544 return value;
1545 if (PyObject_SetItem((PyObject *)dd, key, value) < 0) {
1546 Py_DECREF(value);
1547 return NULL;
1548 }
1549 return value;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001550}
1551
1552PyDoc_STRVAR(defdict_copy_doc, "D.copy() -> a shallow copy of D.");
1553
1554static PyObject *
1555defdict_copy(defdictobject *dd)
1556{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001557 /* This calls the object's class. That only works for subclasses
1558 whose class constructor has the same signature. Subclasses that
1559 define a different constructor signature must override copy().
1560 */
Raymond Hettinger54628fa2009-08-04 19:16:39 +00001561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001562 if (dd->default_factory == NULL)
1563 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd), Py_None, dd, NULL);
1564 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd),
1565 dd->default_factory, dd, NULL);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001566}
1567
1568static PyObject *
1569defdict_reduce(defdictobject *dd)
1570{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001571 /* __reduce__ must return a 5-tuple as follows:
Guido van Rossum1968ad32006-02-25 22:38:04 +00001572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001573 - factory function
1574 - tuple of args for the factory function
1575 - additional state (here None)
1576 - sequence iterator (here None)
1577 - dictionary iterator (yielding successive (key, value) pairs
Guido van Rossum1968ad32006-02-25 22:38:04 +00001578
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001579 This API is used by pickle.py and copy.py.
Guido van Rossum1968ad32006-02-25 22:38:04 +00001580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001581 For this to be useful with pickle.py, the default_factory
1582 must be picklable; e.g., None, a built-in, or a global
1583 function in a module or package.
Guido van Rossum1968ad32006-02-25 22:38:04 +00001584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001585 Both shallow and deep copying are supported, but for deep
1586 copying, the default_factory must be deep-copyable; e.g. None,
1587 or a built-in (functions are not copyable at this time).
Guido van Rossum1968ad32006-02-25 22:38:04 +00001588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001589 This only works for subclasses as long as their constructor
1590 signature is compatible; the first argument must be the
1591 optional default_factory, defaulting to None.
1592 */
1593 PyObject *args;
1594 PyObject *items;
1595 PyObject *iter;
1596 PyObject *result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001597 _Py_IDENTIFIER(items);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001599 if (dd->default_factory == NULL || dd->default_factory == Py_None)
1600 args = PyTuple_New(0);
1601 else
1602 args = PyTuple_Pack(1, dd->default_factory);
1603 if (args == NULL)
1604 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001605 items = _PyObject_CallMethodId((PyObject *)dd, &PyId_items, "()");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001606 if (items == NULL) {
1607 Py_DECREF(args);
1608 return NULL;
1609 }
1610 iter = PyObject_GetIter(items);
1611 if (iter == NULL) {
1612 Py_DECREF(items);
1613 Py_DECREF(args);
1614 return NULL;
1615 }
1616 result = PyTuple_Pack(5, Py_TYPE(dd), args,
1617 Py_None, Py_None, iter);
1618 Py_DECREF(iter);
1619 Py_DECREF(items);
1620 Py_DECREF(args);
1621 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001622}
1623
1624static PyMethodDef defdict_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001625 {"__missing__", (PyCFunction)defdict_missing, METH_O,
1626 defdict_missing_doc},
1627 {"copy", (PyCFunction)defdict_copy, METH_NOARGS,
1628 defdict_copy_doc},
1629 {"__copy__", (PyCFunction)defdict_copy, METH_NOARGS,
1630 defdict_copy_doc},
1631 {"__reduce__", (PyCFunction)defdict_reduce, METH_NOARGS,
1632 reduce_doc},
1633 {NULL}
Guido van Rossum1968ad32006-02-25 22:38:04 +00001634};
1635
1636static PyMemberDef defdict_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001637 {"default_factory", T_OBJECT,
1638 offsetof(defdictobject, default_factory), 0,
1639 PyDoc_STR("Factory for default value called by __missing__().")},
1640 {NULL}
Guido van Rossum1968ad32006-02-25 22:38:04 +00001641};
1642
1643static void
1644defdict_dealloc(defdictobject *dd)
1645{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001646 Py_CLEAR(dd->default_factory);
1647 PyDict_Type.tp_dealloc((PyObject *)dd);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001648}
1649
Guido van Rossum1968ad32006-02-25 22:38:04 +00001650static PyObject *
1651defdict_repr(defdictobject *dd)
1652{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001653 PyObject *baserepr;
1654 PyObject *defrepr;
1655 PyObject *result;
1656 baserepr = PyDict_Type.tp_repr((PyObject *)dd);
1657 if (baserepr == NULL)
1658 return NULL;
1659 if (dd->default_factory == NULL)
1660 defrepr = PyUnicode_FromString("None");
1661 else
1662 {
1663 int status = Py_ReprEnter(dd->default_factory);
1664 if (status != 0) {
Antoine Pitrouf5f1fe02012-02-15 02:42:46 +01001665 if (status < 0) {
1666 Py_DECREF(baserepr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001667 return NULL;
Antoine Pitrouf5f1fe02012-02-15 02:42:46 +01001668 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001669 defrepr = PyUnicode_FromString("...");
1670 }
1671 else
1672 defrepr = PyObject_Repr(dd->default_factory);
1673 Py_ReprLeave(dd->default_factory);
1674 }
1675 if (defrepr == NULL) {
1676 Py_DECREF(baserepr);
1677 return NULL;
1678 }
1679 result = PyUnicode_FromFormat("defaultdict(%U, %U)",
1680 defrepr, baserepr);
1681 Py_DECREF(defrepr);
1682 Py_DECREF(baserepr);
1683 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001684}
1685
1686static int
1687defdict_traverse(PyObject *self, visitproc visit, void *arg)
1688{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001689 Py_VISIT(((defdictobject *)self)->default_factory);
1690 return PyDict_Type.tp_traverse(self, visit, arg);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001691}
1692
1693static int
1694defdict_tp_clear(defdictobject *dd)
1695{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001696 Py_CLEAR(dd->default_factory);
1697 return PyDict_Type.tp_clear((PyObject *)dd);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001698}
1699
1700static int
1701defdict_init(PyObject *self, PyObject *args, PyObject *kwds)
1702{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001703 defdictobject *dd = (defdictobject *)self;
1704 PyObject *olddefault = dd->default_factory;
1705 PyObject *newdefault = NULL;
1706 PyObject *newargs;
1707 int result;
1708 if (args == NULL || !PyTuple_Check(args))
1709 newargs = PyTuple_New(0);
1710 else {
1711 Py_ssize_t n = PyTuple_GET_SIZE(args);
1712 if (n > 0) {
1713 newdefault = PyTuple_GET_ITEM(args, 0);
1714 if (!PyCallable_Check(newdefault) && newdefault != Py_None) {
1715 PyErr_SetString(PyExc_TypeError,
1716 "first argument must be callable");
1717 return -1;
1718 }
1719 }
1720 newargs = PySequence_GetSlice(args, 1, n);
1721 }
1722 if (newargs == NULL)
1723 return -1;
1724 Py_XINCREF(newdefault);
1725 dd->default_factory = newdefault;
1726 result = PyDict_Type.tp_init(self, newargs, kwds);
1727 Py_DECREF(newargs);
1728 Py_XDECREF(olddefault);
1729 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001730}
1731
1732PyDoc_STRVAR(defdict_doc,
Benjamin Peterson9cb33b72014-01-13 23:56:05 -05001733"defaultdict(default_factory[, ...]) --> dict with default factory\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00001734\n\
1735The default factory is called without arguments to produce\n\
1736a new value when a key is not present, in __getitem__ only.\n\
1737A defaultdict compares equal to a dict with the same items.\n\
Benjamin Peterson9cb33b72014-01-13 23:56:05 -05001738All remaining arguments are treated the same as if they were\n\
1739passed to the dict constructor, including keyword arguments.\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00001740");
1741
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001742/* See comment in xxsubtype.c */
1743#define DEFERRED_ADDRESS(ADDR) 0
1744
Guido van Rossum1968ad32006-02-25 22:38:04 +00001745static PyTypeObject defdict_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001746 PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0)
1747 "collections.defaultdict", /* tp_name */
1748 sizeof(defdictobject), /* tp_basicsize */
1749 0, /* tp_itemsize */
1750 /* methods */
1751 (destructor)defdict_dealloc, /* tp_dealloc */
1752 0, /* tp_print */
1753 0, /* tp_getattr */
1754 0, /* tp_setattr */
1755 0, /* tp_reserved */
1756 (reprfunc)defdict_repr, /* tp_repr */
1757 0, /* tp_as_number */
1758 0, /* tp_as_sequence */
1759 0, /* tp_as_mapping */
1760 0, /* tp_hash */
1761 0, /* tp_call */
1762 0, /* tp_str */
1763 PyObject_GenericGetAttr, /* tp_getattro */
1764 0, /* tp_setattro */
1765 0, /* tp_as_buffer */
1766 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
1767 /* tp_flags */
1768 defdict_doc, /* tp_doc */
1769 defdict_traverse, /* tp_traverse */
1770 (inquiry)defdict_tp_clear, /* tp_clear */
1771 0, /* tp_richcompare */
1772 0, /* tp_weaklistoffset*/
1773 0, /* tp_iter */
1774 0, /* tp_iternext */
1775 defdict_methods, /* tp_methods */
1776 defdict_members, /* tp_members */
1777 0, /* tp_getset */
1778 DEFERRED_ADDRESS(&PyDict_Type), /* tp_base */
1779 0, /* tp_dict */
1780 0, /* tp_descr_get */
1781 0, /* tp_descr_set */
1782 0, /* tp_dictoffset */
1783 defdict_init, /* tp_init */
1784 PyType_GenericAlloc, /* tp_alloc */
1785 0, /* tp_new */
1786 PyObject_GC_Del, /* tp_free */
Guido van Rossum1968ad32006-02-25 22:38:04 +00001787};
1788
Raymond Hettinger96f34102010-12-15 16:30:37 +00001789/* helper function for Counter *********************************************/
1790
1791PyDoc_STRVAR(_count_elements_doc,
1792"_count_elements(mapping, iterable) -> None\n\
1793\n\
1794Count elements in the iterable, updating the mappping");
1795
1796static PyObject *
1797_count_elements(PyObject *self, PyObject *args)
1798{
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07001799 _Py_IDENTIFIER(get);
Raymond Hettinger2ff21902013-10-01 00:55:43 -07001800 _Py_IDENTIFIER(__setitem__);
Raymond Hettinger96f34102010-12-15 16:30:37 +00001801 PyObject *it, *iterable, *mapping, *oldval;
1802 PyObject *newval = NULL;
1803 PyObject *key = NULL;
Raymond Hettinger224c87d2013-10-01 21:36:09 -07001804 PyObject *zero = NULL;
Raymond Hettinger96f34102010-12-15 16:30:37 +00001805 PyObject *one = NULL;
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07001806 PyObject *bound_get = NULL;
1807 PyObject *mapping_get;
1808 PyObject *dict_get;
Raymond Hettinger2ff21902013-10-01 00:55:43 -07001809 PyObject *mapping_setitem;
Raymond Hettinger2ff21902013-10-01 00:55:43 -07001810 PyObject *dict_setitem;
Raymond Hettinger96f34102010-12-15 16:30:37 +00001811
1812 if (!PyArg_UnpackTuple(args, "_count_elements", 2, 2, &mapping, &iterable))
1813 return NULL;
1814
Raymond Hettinger96f34102010-12-15 16:30:37 +00001815 it = PyObject_GetIter(iterable);
1816 if (it == NULL)
1817 return NULL;
Raymond Hettinger426e0522011-01-03 02:12:02 +00001818
Raymond Hettinger96f34102010-12-15 16:30:37 +00001819 one = PyLong_FromLong(1);
Raymond Hettinger224c87d2013-10-01 21:36:09 -07001820 if (one == NULL)
1821 goto done;
Raymond Hettinger426e0522011-01-03 02:12:02 +00001822
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07001823 /* Only take the fast path when get() and __setitem__()
1824 * have not been overridden.
1825 */
1826 mapping_get = _PyType_LookupId(Py_TYPE(mapping), &PyId_get);
1827 dict_get = _PyType_LookupId(&PyDict_Type, &PyId_get);
Raymond Hettinger2ff21902013-10-01 00:55:43 -07001828 mapping_setitem = _PyType_LookupId(Py_TYPE(mapping), &PyId___setitem__);
1829 dict_setitem = _PyType_LookupId(&PyDict_Type, &PyId___setitem__);
1830
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07001831 if (mapping_get != NULL && mapping_get == dict_get &&
1832 mapping_setitem != NULL && mapping_setitem == dict_setitem) {
Raymond Hettinger426e0522011-01-03 02:12:02 +00001833 while (1) {
Raymond Hettinger507d9972014-05-18 21:32:40 +01001834 /* Fast path advantages:
1835 1. Eliminate double hashing
1836 (by re-using the same hash for both the get and set)
1837 2. Avoid argument overhead of PyObject_CallFunctionObjArgs
1838 (argument tuple creation and parsing)
1839 3. Avoid indirection through a bound method object
1840 (creates another argument tuple)
1841 4. Avoid initial increment from zero
1842 (reuse an existing one-object instead)
1843 */
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07001844 Py_hash_t hash;
1845
Raymond Hettinger426e0522011-01-03 02:12:02 +00001846 key = PyIter_Next(it);
Victor Stinnera154b5c2011-04-20 23:23:52 +02001847 if (key == NULL)
1848 break;
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07001849
1850 if (!PyUnicode_CheckExact(key) ||
1851 (hash = ((PyASCIIObject *) key)->hash) == -1)
1852 {
1853 hash = PyObject_Hash(key);
1854 if (hash == -1)
1855 goto done;
1856 }
1857
1858 oldval = _PyDict_GetItem_KnownHash(mapping, key, hash);
Raymond Hettinger426e0522011-01-03 02:12:02 +00001859 if (oldval == NULL) {
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07001860 if (_PyDict_SetItem_KnownHash(mapping, key, one, hash) == -1)
Raymond Hettinger507d9972014-05-18 21:32:40 +01001861 goto done;
Raymond Hettinger426e0522011-01-03 02:12:02 +00001862 } else {
1863 newval = PyNumber_Add(oldval, one);
1864 if (newval == NULL)
Raymond Hettinger507d9972014-05-18 21:32:40 +01001865 goto done;
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07001866 if (_PyDict_SetItem_KnownHash(mapping, key, newval, hash) == -1)
Raymond Hettinger507d9972014-05-18 21:32:40 +01001867 goto done;
Raymond Hettinger426e0522011-01-03 02:12:02 +00001868 Py_CLEAR(newval);
1869 }
1870 Py_DECREF(key);
Raymond Hettinger96f34102010-12-15 16:30:37 +00001871 }
Raymond Hettinger426e0522011-01-03 02:12:02 +00001872 } else {
Victor Stinnere7f516c2013-11-06 23:52:55 +01001873 bound_get = _PyObject_GetAttrId(mapping, &PyId_get);
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07001874 if (bound_get == NULL)
Raymond Hettinger224c87d2013-10-01 21:36:09 -07001875 goto done;
1876
1877 zero = PyLong_FromLong(0);
1878 if (zero == NULL)
1879 goto done;
1880
Raymond Hettinger426e0522011-01-03 02:12:02 +00001881 while (1) {
1882 key = PyIter_Next(it);
Victor Stinnera154b5c2011-04-20 23:23:52 +02001883 if (key == NULL)
1884 break;
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07001885 oldval = PyObject_CallFunctionObjArgs(bound_get, key, zero, NULL);
Raymond Hettinger224c87d2013-10-01 21:36:09 -07001886 if (oldval == NULL)
1887 break;
1888 newval = PyNumber_Add(oldval, one);
1889 Py_DECREF(oldval);
1890 if (newval == NULL)
1891 break;
Raymond Hettinger426e0522011-01-03 02:12:02 +00001892 if (PyObject_SetItem(mapping, key, newval) == -1)
Raymond Hettinger96f34102010-12-15 16:30:37 +00001893 break;
1894 Py_CLEAR(newval);
Raymond Hettinger426e0522011-01-03 02:12:02 +00001895 Py_DECREF(key);
Raymond Hettinger96f34102010-12-15 16:30:37 +00001896 }
Raymond Hettinger96f34102010-12-15 16:30:37 +00001897 }
Raymond Hettinger426e0522011-01-03 02:12:02 +00001898
Raymond Hettinger224c87d2013-10-01 21:36:09 -07001899done:
Raymond Hettinger96f34102010-12-15 16:30:37 +00001900 Py_DECREF(it);
1901 Py_XDECREF(key);
1902 Py_XDECREF(newval);
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07001903 Py_XDECREF(bound_get);
Raymond Hettinger224c87d2013-10-01 21:36:09 -07001904 Py_XDECREF(zero);
1905 Py_XDECREF(one);
Raymond Hettinger96f34102010-12-15 16:30:37 +00001906 if (PyErr_Occurred())
1907 return NULL;
1908 Py_RETURN_NONE;
1909}
1910
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001911/* module level code ********************************************************/
1912
1913PyDoc_STRVAR(module_doc,
Guido van Rossum1968ad32006-02-25 22:38:04 +00001914"High performance data structures.\n\
1915- deque: ordered collection accessible from endpoints only\n\
1916- defaultdict: dict subclass with a default value factory\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001917");
1918
Raymond Hettinger96f34102010-12-15 16:30:37 +00001919static struct PyMethodDef module_functions[] = {
1920 {"_count_elements", _count_elements, METH_VARARGS, _count_elements_doc},
1921 {NULL, NULL} /* sentinel */
1922};
Martin v. Löwis1a214512008-06-11 05:26:20 +00001923
1924static struct PyModuleDef _collectionsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001925 PyModuleDef_HEAD_INIT,
1926 "_collections",
1927 module_doc,
1928 -1,
Raymond Hettinger96f34102010-12-15 16:30:37 +00001929 module_functions,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001930 NULL,
1931 NULL,
1932 NULL,
1933 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001934};
1935
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001936PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001937PyInit__collections(void)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001938{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001939 PyObject *m;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001941 m = PyModule_Create(&_collectionsmodule);
1942 if (m == NULL)
1943 return NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001945 if (PyType_Ready(&deque_type) < 0)
1946 return NULL;
1947 Py_INCREF(&deque_type);
1948 PyModule_AddObject(m, "deque", (PyObject *)&deque_type);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001950 defdict_type.tp_base = &PyDict_Type;
1951 if (PyType_Ready(&defdict_type) < 0)
1952 return NULL;
1953 Py_INCREF(&defdict_type);
1954 PyModule_AddObject(m, "defaultdict", (PyObject *)&defdict_type);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001956 if (PyType_Ready(&dequeiter_type) < 0)
1957 return NULL;
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001958 Py_INCREF(&dequeiter_type);
1959 PyModule_AddObject(m, "_deque_iterator", (PyObject *)&dequeiter_type);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001961 if (PyType_Ready(&dequereviter_type) < 0)
1962 return NULL;
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001963 Py_INCREF(&dequereviter_type);
1964 PyModule_AddObject(m, "_deque_reverse_iterator", (PyObject *)&dequereviter_type);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001965
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001966 return m;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001967}