blob: d12f0e8769ec01cdf7758e57cb08c8c2e0a7d709 [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 Hettingereb6b5542015-02-10 22:37:22 -06006 Copyright (c) 2004-2015 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 Hettingerdaf57f22015-02-26 23:21:29 -080013 * Making the block length a power of two speeds-up the modulo
14 * calculation in deque_item().
Raymond Hettinger77e8bf12004-10-01 15:25:53 +000015 */
16
Raymond Hettingerdaf57f22015-02-26 23:21:29 -080017#define BLOCKLEN 64
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000018#define CENTER ((BLOCKLEN - 1) / 2)
Raymond Hettinger756b3f32004-01-29 06:37:52 +000019
Tim Petersd8768d32004-10-01 01:32:53 +000020/* A `dequeobject` is composed of a doubly-linked list of `block` nodes.
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000021 * The list of blocks is never empty, so d.leftblock and d.rightblock
Raymond Hettinger82df9252013-07-07 01:43:42 -100022 * are never equal to NULL. The list is not circular.
23 *
24 * A deque d's first element is at d.leftblock[leftindex]
25 * and its last element is at d.rightblock[rightindex].
26 * Unlike Python slice indices, these indices are inclusive
27 * on both ends. This makes the algorithms for left and
28 * right operations more symmetrical and simplifies the design.
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000029 *
30 * The indices, d.leftindex and d.rightindex are always in the range
31 * 0 <= index < BLOCKLEN.
Raymond Hettinger4ca4c7c2004-10-01 15:14:39 +000032 * Their exact relationship is:
33 * (d.leftindex + d.len - 1) % BLOCKLEN == d.rightindex.
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000034 *
35 * Empty deques have d.len == 0; d.leftblock==d.rightblock;
36 * d.leftindex == CENTER+1; and d.rightindex == CENTER.
37 * Checking for d.len == 0 is the intended way to see whether d is empty.
38 *
Thomas Wouters0e3f5912006-08-11 14:57:12 +000039 * Whenever d.leftblock == d.rightblock,
Raymond Hettinger4ca4c7c2004-10-01 15:14:39 +000040 * d.leftindex + d.len - 1 == d.rightindex.
Thomas Wouters0e3f5912006-08-11 14:57:12 +000041 *
Raymond Hettinger4ca4c7c2004-10-01 15:14:39 +000042 * However, when d.leftblock != d.rightblock, d.leftindex and d.rightindex
Thomas Wouters0e3f5912006-08-11 14:57:12 +000043 * become indices into distinct blocks and either may be larger than the
Raymond Hettinger4ca4c7c2004-10-01 15:14:39 +000044 * other.
Tim Petersd8768d32004-10-01 01:32:53 +000045 */
46
Raymond Hettinger756b3f32004-01-29 06:37:52 +000047typedef struct BLOCK {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000048 struct BLOCK *leftlink;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000049 PyObject *data[BLOCKLEN];
Raymond Hettinger20b0f872013-06-23 15:44:33 -070050 struct BLOCK *rightlink;
Raymond Hettinger756b3f32004-01-29 06:37:52 +000051} block;
52
Raymond Hettinger82df9252013-07-07 01:43:42 -100053/* For debug builds, add error checking to track the endpoints
54 * in the chain of links. The goal is to make sure that link
55 * assignments only take place at endpoints so that links already
56 * in use do not get overwritten.
57 *
58 * CHECK_END should happen before each assignment to a block's link field.
59 * MARK_END should happen whenever a link field becomes a new endpoint.
60 * This happens when new blocks are added or whenever an existing
61 * block is freed leaving another existing block as the new endpoint.
62 */
63
Raymond Hettinger3223dd52013-07-26 23:14:22 -070064#ifndef NDEBUG
Raymond Hettinger82df9252013-07-07 01:43:42 -100065#define MARK_END(link) link = NULL;
66#define CHECK_END(link) assert(link == NULL);
67#define CHECK_NOT_END(link) assert(link != NULL);
68#else
69#define MARK_END(link)
70#define CHECK_END(link)
71#define CHECK_NOT_END(link)
72#endif
73
74/* A simple freelisting scheme is used to minimize calls to the memory
75 allocator. It accomodates common use cases where new blocks are being
76 added at about the same rate as old blocks are being freed.
77 */
78
Guido van Rossum58da9312007-11-10 23:39:45 +000079#define MAXFREEBLOCKS 10
Benjamin Petersond6313712008-07-31 16:23:04 +000080static Py_ssize_t numfreeblocks = 0;
Guido van Rossum58da9312007-11-10 23:39:45 +000081static block *freeblocks[MAXFREEBLOCKS];
82
Tim Peters6f853562004-10-01 01:04:50 +000083static block *
Raymond Hettinger82df9252013-07-07 01:43:42 -100084newblock(Py_ssize_t len) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000085 block *b;
Raymond Hettinger20b0f872013-06-23 15:44:33 -070086 /* To prevent len from overflowing PY_SSIZE_T_MAX, we refuse to
87 * allocate new blocks if the current len is nearing overflow. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000088 if (len >= PY_SSIZE_T_MAX - 2*BLOCKLEN) {
89 PyErr_SetString(PyExc_OverflowError,
90 "cannot add more blocks to the deque");
91 return NULL;
92 }
93 if (numfreeblocks) {
Raymond Hettinger59cf23a2013-02-07 00:57:19 -050094 numfreeblocks--;
Raymond Hettinger82df9252013-07-07 01:43:42 -100095 return freeblocks[numfreeblocks];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000096 }
Raymond Hettinger82df9252013-07-07 01:43:42 -100097 b = PyMem_Malloc(sizeof(block));
98 if (b != NULL) {
99 return b;
100 }
101 PyErr_NoMemory();
102 return NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000103}
104
Martin v. Löwis59683e82008-06-13 07:50:45 +0000105static void
Guido van Rossum58da9312007-11-10 23:39:45 +0000106freeblock(block *b)
107{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000108 if (numfreeblocks < MAXFREEBLOCKS) {
109 freeblocks[numfreeblocks] = b;
110 numfreeblocks++;
111 } else {
112 PyMem_Free(b);
113 }
Guido van Rossum58da9312007-11-10 23:39:45 +0000114}
115
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000116typedef struct {
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000117 PyObject_VAR_HEAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000118 block *leftblock;
119 block *rightblock;
120 Py_ssize_t leftindex; /* in range(BLOCKLEN) */
121 Py_ssize_t rightindex; /* in range(BLOCKLEN) */
Raymond Hettinger90dea4c2013-07-13 22:30:25 -0700122 long state; /* incremented whenever the indices move */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000123 Py_ssize_t maxlen;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000124 PyObject *weakreflist; /* List of weak references */
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000125} dequeobject;
126
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000127/* The deque's size limit is d.maxlen. The limit can be zero or positive.
128 * If there is no limit, then d.maxlen == -1.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000129 *
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000130 * After an item is added to a deque, we check to see if the size has grown past
131 * the limit. If it has, we get the size back down to the limit by popping an
132 * item off of the opposite end. The methods that can trigger this are append(),
133 * appendleft(), extend(), and extendleft().
134 */
135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000136#define TRIM(d, popfunction) \
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000137 if (d->maxlen != -1 && Py_SIZE(d) > d->maxlen) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000138 PyObject *rv = popfunction(d, NULL); \
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000139 assert(rv != NULL && Py_SIZE(d) <= d->maxlen); \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000140 Py_DECREF(rv); \
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000141 }
142
Neal Norwitz87f10132004-02-29 15:40:53 +0000143static PyTypeObject deque_type;
Raymond Hettinger738ec902004-02-29 02:15:56 +0000144
Raymond Hettingerda2850f2015-02-27 12:42:54 -0800145/* XXX Todo:
Raymond Hettinger54023152014-04-23 00:58:48 -0700146 If aligned memory allocations become available, make the
147 deque object 64 byte aligned so that all of the fields
148 can be retrieved or updated in a single cache line.
149*/
150
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000151static PyObject *
152deque_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
153{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000154 dequeobject *deque;
155 block *b;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000157 /* create dequeobject structure */
158 deque = (dequeobject *)type->tp_alloc(type, 0);
159 if (deque == NULL)
160 return NULL;
Tim Peters1065f752004-10-01 01:03:29 +0000161
Raymond Hettinger82df9252013-07-07 01:43:42 -1000162 b = newblock(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000163 if (b == NULL) {
164 Py_DECREF(deque);
165 return NULL;
166 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000167 MARK_END(b->leftlink);
168 MARK_END(b->rightlink);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000169
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000170 assert(BLOCKLEN >= 2);
171 deque->leftblock = b;
172 deque->rightblock = b;
173 deque->leftindex = CENTER + 1;
174 deque->rightindex = CENTER;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000175 Py_SIZE(deque) = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000176 deque->state = 0;
177 deque->weakreflist = NULL;
178 deque->maxlen = -1;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000179
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000180 return (PyObject *)deque;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000181}
182
183static PyObject *
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000184deque_pop(dequeobject *deque, PyObject *unused)
185{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000186 PyObject *item;
187 block *prevblock;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000188
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000189 if (Py_SIZE(deque) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000190 PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
191 return NULL;
192 }
193 item = deque->rightblock->data[deque->rightindex];
194 deque->rightindex--;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000195 Py_SIZE(deque)--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000196 deque->state++;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000198 if (deque->rightindex == -1) {
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000199 if (Py_SIZE(deque) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000200 assert(deque->leftblock == deque->rightblock);
201 assert(deque->leftindex == deque->rightindex+1);
202 /* re-center instead of freeing a block */
203 deque->leftindex = CENTER + 1;
204 deque->rightindex = CENTER;
205 } else {
206 prevblock = deque->rightblock->leftlink;
207 assert(deque->leftblock != deque->rightblock);
208 freeblock(deque->rightblock);
Raymond Hettinger82df9252013-07-07 01:43:42 -1000209 CHECK_NOT_END(prevblock);
210 MARK_END(prevblock->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000211 deque->rightblock = prevblock;
212 deque->rightindex = BLOCKLEN - 1;
213 }
214 }
215 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000216}
217
218PyDoc_STRVAR(pop_doc, "Remove and return the rightmost element.");
219
220static PyObject *
221deque_popleft(dequeobject *deque, PyObject *unused)
222{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000223 PyObject *item;
224 block *prevblock;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000225
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000226 if (Py_SIZE(deque) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000227 PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
228 return NULL;
229 }
230 assert(deque->leftblock != NULL);
231 item = deque->leftblock->data[deque->leftindex];
232 deque->leftindex++;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000233 Py_SIZE(deque)--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000234 deque->state++;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000236 if (deque->leftindex == BLOCKLEN) {
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000237 if (Py_SIZE(deque) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000238 assert(deque->leftblock == deque->rightblock);
239 assert(deque->leftindex == deque->rightindex+1);
240 /* re-center instead of freeing a block */
241 deque->leftindex = CENTER + 1;
242 deque->rightindex = CENTER;
243 } else {
244 assert(deque->leftblock != deque->rightblock);
245 prevblock = deque->leftblock->rightlink;
246 freeblock(deque->leftblock);
Raymond Hettinger82df9252013-07-07 01:43:42 -1000247 CHECK_NOT_END(prevblock);
248 MARK_END(prevblock->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000249 deque->leftblock = prevblock;
250 deque->leftindex = 0;
251 }
252 }
253 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000254}
255
256PyDoc_STRVAR(popleft_doc, "Remove and return the leftmost element.");
257
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000258static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000259deque_append(dequeobject *deque, PyObject *item)
260{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000261 deque->state++;
262 if (deque->rightindex == BLOCKLEN-1) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000263 block *b = newblock(Py_SIZE(deque));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000264 if (b == NULL)
265 return NULL;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000266 b->leftlink = deque->rightblock;
267 CHECK_END(deque->rightblock->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000268 deque->rightblock->rightlink = b;
269 deque->rightblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000270 MARK_END(b->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000271 deque->rightindex = -1;
272 }
273 Py_INCREF(item);
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000274 Py_SIZE(deque)++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000275 deque->rightindex++;
276 deque->rightblock->data[deque->rightindex] = item;
277 TRIM(deque, deque_popleft);
278 Py_RETURN_NONE;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000279}
280
281PyDoc_STRVAR(append_doc, "Add an element to the right side of the deque.");
282
283static PyObject *
284deque_appendleft(dequeobject *deque, PyObject *item)
285{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 deque->state++;
287 if (deque->leftindex == 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000288 block *b = newblock(Py_SIZE(deque));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000289 if (b == NULL)
290 return NULL;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000291 b->rightlink = deque->leftblock;
292 CHECK_END(deque->leftblock->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000293 deque->leftblock->leftlink = b;
294 deque->leftblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000295 MARK_END(b->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000296 deque->leftindex = BLOCKLEN;
297 }
298 Py_INCREF(item);
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000299 Py_SIZE(deque)++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000300 deque->leftindex--;
301 deque->leftblock->data[deque->leftindex] = item;
302 TRIM(deque, deque_pop);
303 Py_RETURN_NONE;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000304}
305
306PyDoc_STRVAR(appendleft_doc, "Add an element to the left side of the deque.");
307
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000309/* Run an iterator to exhaustion. Shortcut for
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000310 the extend/extendleft methods when maxlen == 0. */
311static PyObject*
312consume_iterator(PyObject *it)
313{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000314 PyObject *item;
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000316 while ((item = PyIter_Next(it)) != NULL) {
317 Py_DECREF(item);
318 }
319 Py_DECREF(it);
320 if (PyErr_Occurred())
321 return NULL;
322 Py_RETURN_NONE;
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000323}
324
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000325static PyObject *
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000326deque_extend(dequeobject *deque, PyObject *iterable)
327{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000328 PyObject *it, *item;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 /* Handle case where id(deque) == id(iterable) */
331 if ((PyObject *)deque == iterable) {
332 PyObject *result;
333 PyObject *s = PySequence_List(iterable);
334 if (s == NULL)
335 return NULL;
336 result = deque_extend(deque, s);
337 Py_DECREF(s);
338 return result;
339 }
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000340
Raymond Hettingerd9c116c2013-07-09 00:13:21 -0700341 /* Space saving heuristic. Start filling from the left */
342 if (Py_SIZE(deque) == 0) {
343 assert(deque->leftblock == deque->rightblock);
344 assert(deque->leftindex == deque->rightindex+1);
345 deque->leftindex = 1;
346 deque->rightindex = 0;
347 }
348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000349 it = PyObject_GetIter(iterable);
350 if (it == NULL)
351 return NULL;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000353 if (deque->maxlen == 0)
354 return consume_iterator(it);
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000356 while ((item = PyIter_Next(it)) != NULL) {
357 deque->state++;
358 if (deque->rightindex == BLOCKLEN-1) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000359 block *b = newblock(Py_SIZE(deque));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000360 if (b == NULL) {
361 Py_DECREF(item);
362 Py_DECREF(it);
363 return NULL;
364 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000365 b->leftlink = deque->rightblock;
366 CHECK_END(deque->rightblock->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000367 deque->rightblock->rightlink = b;
368 deque->rightblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000369 MARK_END(b->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000370 deque->rightindex = -1;
371 }
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000372 Py_SIZE(deque)++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000373 deque->rightindex++;
374 deque->rightblock->data[deque->rightindex] = item;
375 TRIM(deque, deque_popleft);
376 }
377 Py_DECREF(it);
378 if (PyErr_Occurred())
379 return NULL;
380 Py_RETURN_NONE;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000381}
382
Tim Peters1065f752004-10-01 01:03:29 +0000383PyDoc_STRVAR(extend_doc,
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000384"Extend the right side of the deque with elements from the iterable");
385
386static PyObject *
387deque_extendleft(dequeobject *deque, PyObject *iterable)
388{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000389 PyObject *it, *item;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000391 /* Handle case where id(deque) == id(iterable) */
392 if ((PyObject *)deque == iterable) {
393 PyObject *result;
394 PyObject *s = PySequence_List(iterable);
395 if (s == NULL)
396 return NULL;
397 result = deque_extendleft(deque, s);
398 Py_DECREF(s);
399 return result;
400 }
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000401
Raymond Hettingerd9c116c2013-07-09 00:13:21 -0700402 /* Space saving heuristic. Start filling from the right */
403 if (Py_SIZE(deque) == 0) {
404 assert(deque->leftblock == deque->rightblock);
405 assert(deque->leftindex == deque->rightindex+1);
406 deque->leftindex = BLOCKLEN - 1;
407 deque->rightindex = BLOCKLEN - 2;
408 }
409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000410 it = PyObject_GetIter(iterable);
411 if (it == NULL)
412 return NULL;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000413
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000414 if (deque->maxlen == 0)
415 return consume_iterator(it);
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 while ((item = PyIter_Next(it)) != NULL) {
418 deque->state++;
419 if (deque->leftindex == 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000420 block *b = newblock(Py_SIZE(deque));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 if (b == NULL) {
422 Py_DECREF(item);
423 Py_DECREF(it);
424 return NULL;
425 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000426 b->rightlink = deque->leftblock;
427 CHECK_END(deque->leftblock->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000428 deque->leftblock->leftlink = b;
429 deque->leftblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000430 MARK_END(b->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 deque->leftindex = BLOCKLEN;
432 }
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000433 Py_SIZE(deque)++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000434 deque->leftindex--;
435 deque->leftblock->data[deque->leftindex] = item;
436 TRIM(deque, deque_pop);
437 }
438 Py_DECREF(it);
439 if (PyErr_Occurred())
440 return NULL;
441 Py_RETURN_NONE;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000442}
443
Tim Peters1065f752004-10-01 01:03:29 +0000444PyDoc_STRVAR(extendleft_doc,
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000445"Extend the left side of the deque with elements from the iterable");
446
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000447static PyObject *
448deque_inplace_concat(dequeobject *deque, PyObject *other)
449{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000450 PyObject *result;
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000451
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000452 result = deque_extend(deque, other);
453 if (result == NULL)
454 return result;
455 Py_DECREF(result);
456 Py_INCREF(deque);
457 return (PyObject *)deque;
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000458}
459
Raymond Hettinger54023152014-04-23 00:58:48 -0700460/* The rotate() method is part of the public API and is used internally
461as a primitive for other methods.
462
463Rotation by 1 or -1 is a common case, so any optimizations for high
464volume rotations should take care not to penalize the common case.
465
466Conceptually, a rotate by one is equivalent to a pop on one side and an
467append on the other. However, a pop/append pair is unnecessarily slow
468because it requires a incref/decref pair for an object located randomly
469in memory. It is better to just move the object pointer from one block
470to the next without changing the reference count.
471
472When moving batches of pointers, it is tempting to use memcpy() but that
473proved to be slower than a simple loop for a variety of reasons.
474Memcpy() cannot know in advance that we're copying pointers instead of
475bytes, that the source and destination are pointer aligned and
476non-overlapping, that moving just one pointer is a common case, that we
477never need to move more than BLOCKLEN pointers, and that at least one
478pointer is always moved.
479
480For high volume rotations, newblock() and freeblock() are never called
481more than once. Previously emptied blocks are immediately reused as a
482destination block. If a block is left-over at the end, it is freed.
483*/
484
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000485static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000486_deque_rotate(dequeobject *deque, Py_ssize_t n)
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000487{
Raymond Hettinger3959af92013-07-13 02:34:08 -0700488 block *b = NULL;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700489 block *leftblock = deque->leftblock;
490 block *rightblock = deque->rightblock;
491 Py_ssize_t leftindex = deque->leftindex;
492 Py_ssize_t rightindex = deque->rightindex;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000493 Py_ssize_t len=Py_SIZE(deque), halflen=len>>1;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700494 int rv = -1;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000495
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800496 if (len <= 1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 return 0;
498 if (n > halflen || n < -halflen) {
499 n %= len;
500 if (n > halflen)
501 n -= len;
502 else if (n < -halflen)
503 n += len;
504 }
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500505 assert(len > 1);
Raymond Hettingera4409c12013-02-04 00:08:12 -0500506 assert(-halflen <= n && n <= halflen);
Raymond Hettinger231ee4d2013-02-02 11:24:43 -0800507
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800508 deque->state++;
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500509 while (n > 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700510 if (leftindex == 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700511 if (b == NULL) {
Raymond Hettinger3959af92013-07-13 02:34:08 -0700512 b = newblock(len);
513 if (b == NULL)
514 goto done;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700515 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000516 b->rightlink = leftblock;
517 CHECK_END(leftblock->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700518 leftblock->leftlink = b;
519 leftblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000520 MARK_END(b->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700521 leftindex = BLOCKLEN;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700522 b = NULL;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800523 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700524 assert(leftindex > 0);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700525 {
526 PyObject **src, **dest;
527 Py_ssize_t m = n;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800528
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700529 if (m > rightindex + 1)
530 m = rightindex + 1;
531 if (m > leftindex)
532 m = leftindex;
533 assert (m > 0 && m <= len);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700534 rightindex -= m;
535 leftindex -= m;
Raymond Hettinger0e259f12015-02-01 22:53:41 -0800536 src = &rightblock->data[rightindex + 1];
537 dest = &leftblock->data[leftindex];
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700538 n -= m;
Raymond Hettinger840533b2013-07-13 17:03:58 -0700539 do {
Raymond Hettinger0e259f12015-02-01 22:53:41 -0800540 *(dest++) = *(src++);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700541 } while (--m);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700542 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700543 if (rightindex == -1) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700544 assert(leftblock != rightblock);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700545 assert(b == NULL);
Raymond Hettinger3959af92013-07-13 02:34:08 -0700546 b = rightblock;
Raymond Hettingerb97cc492013-07-21 01:51:07 -0700547 CHECK_NOT_END(rightblock->leftlink);
548 rightblock = rightblock->leftlink;
549 MARK_END(rightblock->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700550 rightindex = BLOCKLEN - 1;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800551 }
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800552 }
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500553 while (n < 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700554 if (rightindex == BLOCKLEN - 1) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700555 if (b == NULL) {
Raymond Hettinger3959af92013-07-13 02:34:08 -0700556 b = newblock(len);
557 if (b == NULL)
558 goto done;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700559 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000560 b->leftlink = rightblock;
561 CHECK_END(rightblock->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700562 rightblock->rightlink = b;
563 rightblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000564 MARK_END(b->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700565 rightindex = -1;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700566 b = NULL;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800567 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700568 assert (rightindex < BLOCKLEN - 1);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700569 {
570 PyObject **src, **dest;
571 Py_ssize_t m = -n;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800572
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700573 if (m > BLOCKLEN - leftindex)
574 m = BLOCKLEN - leftindex;
575 if (m > BLOCKLEN - 1 - rightindex)
576 m = BLOCKLEN - 1 - rightindex;
577 assert (m > 0 && m <= len);
578 src = &leftblock->data[leftindex];
579 dest = &rightblock->data[rightindex + 1];
580 leftindex += m;
581 rightindex += m;
582 n += m;
Raymond Hettinger840533b2013-07-13 17:03:58 -0700583 do {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700584 *(dest++) = *(src++);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700585 } while (--m);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700586 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700587 if (leftindex == BLOCKLEN) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700588 assert(leftblock != rightblock);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700589 assert(b == NULL);
Raymond Hettinger3959af92013-07-13 02:34:08 -0700590 b = leftblock;
Raymond Hettingerb97cc492013-07-21 01:51:07 -0700591 CHECK_NOT_END(leftblock->rightlink);
592 leftblock = leftblock->rightlink;
593 MARK_END(leftblock->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700594 leftindex = 0;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800595 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 }
Raymond Hettinger3959af92013-07-13 02:34:08 -0700597 rv = 0;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700598done:
Raymond Hettinger3959af92013-07-13 02:34:08 -0700599 if (b != NULL)
600 freeblock(b);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700601 deque->leftblock = leftblock;
602 deque->rightblock = rightblock;
603 deque->leftindex = leftindex;
604 deque->rightindex = rightindex;
605
606 return rv;
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000607}
608
609static PyObject *
610deque_rotate(dequeobject *deque, PyObject *args)
611{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 Py_ssize_t n=1;
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000614 if (!PyArg_ParseTuple(args, "|n:rotate", &n))
615 return NULL;
616 if (_deque_rotate(deque, n) == 0)
617 Py_RETURN_NONE;
618 return NULL;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000619}
620
Tim Peters1065f752004-10-01 01:03:29 +0000621PyDoc_STRVAR(rotate_doc,
Raymond Hettingeree33b272004-02-08 04:05:26 +0000622"Rotate the deque n steps to the right (default n=1). If n is negative, rotates left.");
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000623
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000624static PyObject *
625deque_reverse(dequeobject *deque, PyObject *unused)
626{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 block *leftblock = deque->leftblock;
628 block *rightblock = deque->rightblock;
629 Py_ssize_t leftindex = deque->leftindex;
630 Py_ssize_t rightindex = deque->rightindex;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000631 Py_ssize_t n = (Py_SIZE(deque))/2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000632 Py_ssize_t i;
633 PyObject *tmp;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000635 for (i=0 ; i<n ; i++) {
636 /* Validate that pointers haven't met in the middle */
637 assert(leftblock != rightblock || leftindex < rightindex);
Raymond Hettinger82df9252013-07-07 01:43:42 -1000638 CHECK_NOT_END(leftblock);
639 CHECK_NOT_END(rightblock);
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000640
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 /* Swap */
642 tmp = leftblock->data[leftindex];
643 leftblock->data[leftindex] = rightblock->data[rightindex];
644 rightblock->data[rightindex] = tmp;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 /* Advance left block/index pair */
647 leftindex++;
648 if (leftindex == BLOCKLEN) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000649 leftblock = leftblock->rightlink;
650 leftindex = 0;
651 }
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000653 /* Step backwards with the right block/index pair */
654 rightindex--;
655 if (rightindex == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000656 rightblock = rightblock->leftlink;
657 rightindex = BLOCKLEN - 1;
658 }
659 }
660 Py_RETURN_NONE;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000661}
662
663PyDoc_STRVAR(reverse_doc,
664"D.reverse() -- reverse *IN PLACE*");
665
Raymond Hettinger44459de2010-04-03 23:20:46 +0000666static PyObject *
667deque_count(dequeobject *deque, PyObject *v)
668{
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000669 block *b = deque->leftblock;
670 Py_ssize_t index = deque->leftindex;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000671 Py_ssize_t n = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000672 Py_ssize_t i;
673 Py_ssize_t count = 0;
674 PyObject *item;
675 long start_state = deque->state;
676 int cmp;
Raymond Hettinger44459de2010-04-03 23:20:46 +0000677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000678 for (i=0 ; i<n ; i++) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000679 CHECK_NOT_END(b);
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000680 item = b->data[index];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000681 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
682 if (cmp > 0)
683 count++;
684 else if (cmp < 0)
685 return NULL;
Raymond Hettinger44459de2010-04-03 23:20:46 +0000686
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000687 if (start_state != deque->state) {
688 PyErr_SetString(PyExc_RuntimeError,
689 "deque mutated during iteration");
690 return NULL;
691 }
Raymond Hettinger44459de2010-04-03 23:20:46 +0000692
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000693 /* Advance left block/index pair */
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000694 index++;
695 if (index == BLOCKLEN) {
696 b = b->rightlink;
697 index = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000698 }
699 }
700 return PyLong_FromSsize_t(count);
Raymond Hettinger44459de2010-04-03 23:20:46 +0000701}
702
703PyDoc_STRVAR(count_doc,
704"D.count(value) -> integer -- return number of occurrences of value");
705
Martin v. Löwis18e16552006-02-15 17:27:45 +0000706static Py_ssize_t
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000707deque_len(dequeobject *deque)
708{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000709 return Py_SIZE(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000710}
711
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000712static PyObject *
713deque_remove(dequeobject *deque, PyObject *value)
714{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000715 Py_ssize_t i, n=Py_SIZE(deque);
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000716
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000717 for (i=0 ; i<n ; i++) {
718 PyObject *item = deque->leftblock->data[deque->leftindex];
719 int cmp = PyObject_RichCompareBool(item, value, Py_EQ);
Raymond Hettingerd73202c2005-03-19 00:00:51 +0000720
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000721 if (Py_SIZE(deque) != n) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000722 PyErr_SetString(PyExc_IndexError,
723 "deque mutated during remove().");
724 return NULL;
725 }
726 if (cmp > 0) {
727 PyObject *tgt = deque_popleft(deque, NULL);
728 assert (tgt != NULL);
729 Py_DECREF(tgt);
730 if (_deque_rotate(deque, i) == -1)
731 return NULL;
732 Py_RETURN_NONE;
733 }
734 else if (cmp < 0) {
735 _deque_rotate(deque, i);
736 return NULL;
737 }
738 _deque_rotate(deque, -1);
739 }
740 PyErr_SetString(PyExc_ValueError, "deque.remove(x): x not in deque");
741 return NULL;
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000742}
743
744PyDoc_STRVAR(remove_doc,
745"D.remove(value) -- remove first occurrence of value.");
746
Benjamin Peterson0e5c48a2013-01-12 21:22:18 -0500747static void
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000748deque_clear(dequeobject *deque)
749{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000750 PyObject *item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000751
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000752 while (Py_SIZE(deque)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000753 item = deque_pop(deque, NULL);
754 assert (item != NULL);
755 Py_DECREF(item);
756 }
757 assert(deque->leftblock == deque->rightblock &&
758 deque->leftindex - 1 == deque->rightindex &&
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000759 Py_SIZE(deque) == 0);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000760}
761
762static PyObject *
Benjamin Petersond6313712008-07-31 16:23:04 +0000763deque_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000764{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000765 block *b;
766 PyObject *item;
767 Py_ssize_t n, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000768
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000769 if (i < 0 || i >= Py_SIZE(deque)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000770 PyErr_SetString(PyExc_IndexError,
771 "deque index out of range");
772 return NULL;
773 }
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000774
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000775 if (i == 0) {
776 i = deque->leftindex;
777 b = deque->leftblock;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000778 } else if (i == Py_SIZE(deque) - 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 i = deque->rightindex;
780 b = deque->rightblock;
781 } else {
782 i += deque->leftindex;
Raymond Hettingerda2850f2015-02-27 12:42:54 -0800783 assert(i >= 0);
784 n = (Py_ssize_t)((unsigned) i / BLOCKLEN);
785 i = (Py_ssize_t)((unsigned) i % BLOCKLEN);
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000786 if (index < (Py_SIZE(deque) >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 b = deque->leftblock;
788 while (n--)
789 b = b->rightlink;
790 } else {
Raymond Hettinger63d1ff22015-02-28 07:41:30 -0800791 n = (Py_ssize_t)(
792 ((unsigned)(deque->leftindex + Py_SIZE(deque) - 1))
793 / 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);
Raymond Hettingerda2850f2015-02-27 12:42:54 -08001854 if (hash == -1)
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07001855 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}