blob: d4794be08fef47f5cd0cce60111616ee1c8535ff [file] [log] [blame]
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001#include "Python.h"
Raymond Hettinger691d8052004-05-30 07:26:47 +00002#include "structmember.h"
Raymond Hettinger756b3f32004-01-29 06:37:52 +00003
Raymond Hettingerc2083082015-02-28 23:29:16 -08004#ifdef STDC_HEADERS
5#include <stddef.h>
6#else
7#include <sys/types.h> /* For size_t */
8#endif
9
Raymond Hettinger756b3f32004-01-29 06:37:52 +000010/* collections module implementation of a deque() datatype
11 Written and maintained by Raymond D. Hettinger <python@rcn.com>
Raymond Hettingereb6b5542015-02-10 22:37:22 -060012 Copyright (c) 2004-2015 Python Software Foundation.
Raymond Hettinger756b3f32004-01-29 06:37:52 +000013 All rights reserved.
14*/
15
Raymond Hettinger77e8bf12004-10-01 15:25:53 +000016/* The block length may be set to any number over 1. Larger numbers
Raymond Hettinger20b0f872013-06-23 15:44:33 -070017 * reduce the number of calls to the memory allocator, give faster
Raymond Hettinger30c90742015-03-02 22:31:35 -080018 * indexing and rotation, and reduce the link to data overhead ratio.
Raymond Hettingerdaf57f22015-02-26 23:21:29 -080019 * Making the block length a power of two speeds-up the modulo
Raymond Hettinger30c90742015-03-02 22:31:35 -080020 * and division calculations in deque_item() and deque_ass_item().
Raymond Hettinger77e8bf12004-10-01 15:25:53 +000021 */
22
Raymond Hettingerdaf57f22015-02-26 23:21:29 -080023#define BLOCKLEN 64
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000024#define CENTER ((BLOCKLEN - 1) / 2)
Raymond Hettinger756b3f32004-01-29 06:37:52 +000025
Tim Petersd8768d32004-10-01 01:32:53 +000026/* A `dequeobject` is composed of a doubly-linked list of `block` nodes.
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000027 * The list of blocks is never empty, so d.leftblock and d.rightblock
Raymond Hettinger82df9252013-07-07 01:43:42 -100028 * are never equal to NULL. The list is not circular.
29 *
30 * A deque d's first element is at d.leftblock[leftindex]
31 * and its last element is at d.rightblock[rightindex].
32 * Unlike Python slice indices, these indices are inclusive
33 * on both ends. This makes the algorithms for left and
34 * right operations more symmetrical and simplifies the design.
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000035 *
36 * The indices, d.leftindex and d.rightindex are always in the range
37 * 0 <= index < BLOCKLEN.
Raymond Hettinger4ca4c7c2004-10-01 15:14:39 +000038 * Their exact relationship is:
39 * (d.leftindex + d.len - 1) % BLOCKLEN == d.rightindex.
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000040 *
41 * Empty deques have d.len == 0; d.leftblock==d.rightblock;
42 * d.leftindex == CENTER+1; and d.rightindex == CENTER.
43 * Checking for d.len == 0 is the intended way to see whether d is empty.
44 *
Thomas Wouters0e3f5912006-08-11 14:57:12 +000045 * Whenever d.leftblock == d.rightblock,
Raymond Hettinger4ca4c7c2004-10-01 15:14:39 +000046 * d.leftindex + d.len - 1 == d.rightindex.
Thomas Wouters0e3f5912006-08-11 14:57:12 +000047 *
Raymond Hettinger4ca4c7c2004-10-01 15:14:39 +000048 * However, when d.leftblock != d.rightblock, d.leftindex and d.rightindex
Thomas Wouters0e3f5912006-08-11 14:57:12 +000049 * become indices into distinct blocks and either may be larger than the
Raymond Hettinger4ca4c7c2004-10-01 15:14:39 +000050 * other.
Tim Petersd8768d32004-10-01 01:32:53 +000051 */
52
Raymond Hettinger756b3f32004-01-29 06:37:52 +000053typedef struct BLOCK {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000054 struct BLOCK *leftlink;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000055 PyObject *data[BLOCKLEN];
Raymond Hettinger20b0f872013-06-23 15:44:33 -070056 struct BLOCK *rightlink;
Raymond Hettinger756b3f32004-01-29 06:37:52 +000057} block;
58
Raymond Hettinger30c90742015-03-02 22:31:35 -080059typedef struct {
60 PyObject_VAR_HEAD
61 block *leftblock;
62 block *rightblock;
63 Py_ssize_t leftindex; /* in range(BLOCKLEN) */
64 Py_ssize_t rightindex; /* in range(BLOCKLEN) */
Raymond Hettingerf9d9c792015-03-02 22:47:46 -080065 size_t state; /* incremented whenever the indices move */
Raymond Hettinger30c90742015-03-02 22:31:35 -080066 Py_ssize_t maxlen;
67 PyObject *weakreflist; /* List of weak references */
68} dequeobject;
69
70static PyTypeObject deque_type;
71
Raymond Hettinger82df9252013-07-07 01:43:42 -100072/* For debug builds, add error checking to track the endpoints
73 * in the chain of links. The goal is to make sure that link
74 * assignments only take place at endpoints so that links already
75 * in use do not get overwritten.
76 *
77 * CHECK_END should happen before each assignment to a block's link field.
78 * MARK_END should happen whenever a link field becomes a new endpoint.
79 * This happens when new blocks are added or whenever an existing
80 * block is freed leaving another existing block as the new endpoint.
81 */
82
Raymond Hettinger3223dd52013-07-26 23:14:22 -070083#ifndef NDEBUG
Raymond Hettinger82df9252013-07-07 01:43:42 -100084#define MARK_END(link) link = NULL;
85#define CHECK_END(link) assert(link == NULL);
86#define CHECK_NOT_END(link) assert(link != NULL);
87#else
88#define MARK_END(link)
89#define CHECK_END(link)
90#define CHECK_NOT_END(link)
91#endif
92
93/* A simple freelisting scheme is used to minimize calls to the memory
94 allocator. It accomodates common use cases where new blocks are being
95 added at about the same rate as old blocks are being freed.
96 */
97
Guido van Rossum58da9312007-11-10 23:39:45 +000098#define MAXFREEBLOCKS 10
Benjamin Petersond6313712008-07-31 16:23:04 +000099static Py_ssize_t numfreeblocks = 0;
Guido van Rossum58da9312007-11-10 23:39:45 +0000100static block *freeblocks[MAXFREEBLOCKS];
101
Tim Peters6f853562004-10-01 01:04:50 +0000102static block *
Raymond Hettinger82df9252013-07-07 01:43:42 -1000103newblock(Py_ssize_t len) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000104 block *b;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700105 /* To prevent len from overflowing PY_SSIZE_T_MAX, we refuse to
106 * allocate new blocks if the current len is nearing overflow. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000107 if (len >= PY_SSIZE_T_MAX - 2*BLOCKLEN) {
108 PyErr_SetString(PyExc_OverflowError,
109 "cannot add more blocks to the deque");
110 return NULL;
111 }
112 if (numfreeblocks) {
Raymond Hettinger59cf23a2013-02-07 00:57:19 -0500113 numfreeblocks--;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000114 return freeblocks[numfreeblocks];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000115 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000116 b = PyMem_Malloc(sizeof(block));
117 if (b != NULL) {
118 return b;
119 }
120 PyErr_NoMemory();
121 return NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000122}
123
Martin v. Löwis59683e82008-06-13 07:50:45 +0000124static void
Guido van Rossum58da9312007-11-10 23:39:45 +0000125freeblock(block *b)
126{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000127 if (numfreeblocks < MAXFREEBLOCKS) {
128 freeblocks[numfreeblocks] = b;
129 numfreeblocks++;
130 } else {
131 PyMem_Free(b);
132 }
Guido van Rossum58da9312007-11-10 23:39:45 +0000133}
134
Raymond Hettingerda2850f2015-02-27 12:42:54 -0800135/* XXX Todo:
Raymond Hettinger54023152014-04-23 00:58:48 -0700136 If aligned memory allocations become available, make the
137 deque object 64 byte aligned so that all of the fields
138 can be retrieved or updated in a single cache line.
139*/
140
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000141static PyObject *
142deque_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
143{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000144 dequeobject *deque;
145 block *b;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000147 /* create dequeobject structure */
148 deque = (dequeobject *)type->tp_alloc(type, 0);
149 if (deque == NULL)
150 return NULL;
Tim Peters1065f752004-10-01 01:03:29 +0000151
Raymond Hettinger82df9252013-07-07 01:43:42 -1000152 b = newblock(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000153 if (b == NULL) {
154 Py_DECREF(deque);
155 return NULL;
156 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000157 MARK_END(b->leftlink);
158 MARK_END(b->rightlink);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000159
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000160 assert(BLOCKLEN >= 2);
Raymond Hettinger87e69122015-03-02 23:32:02 -0800161 Py_SIZE(deque) = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000162 deque->leftblock = b;
163 deque->rightblock = b;
164 deque->leftindex = CENTER + 1;
165 deque->rightindex = CENTER;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000166 deque->state = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000167 deque->maxlen = -1;
Raymond Hettinger87e69122015-03-02 23:32:02 -0800168 deque->weakreflist = NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000169
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000170 return (PyObject *)deque;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000171}
172
173static PyObject *
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000174deque_pop(dequeobject *deque, PyObject *unused)
175{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000176 PyObject *item;
177 block *prevblock;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000178
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000179 if (Py_SIZE(deque) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000180 PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
181 return NULL;
182 }
183 item = deque->rightblock->data[deque->rightindex];
184 deque->rightindex--;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000185 Py_SIZE(deque)--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000186 deque->state++;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000188 if (deque->rightindex == -1) {
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000189 if (Py_SIZE(deque) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000190 assert(deque->leftblock == deque->rightblock);
191 assert(deque->leftindex == deque->rightindex+1);
192 /* re-center instead of freeing a block */
193 deque->leftindex = CENTER + 1;
194 deque->rightindex = CENTER;
195 } else {
196 prevblock = deque->rightblock->leftlink;
197 assert(deque->leftblock != deque->rightblock);
198 freeblock(deque->rightblock);
Raymond Hettinger82df9252013-07-07 01:43:42 -1000199 CHECK_NOT_END(prevblock);
200 MARK_END(prevblock->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000201 deque->rightblock = prevblock;
202 deque->rightindex = BLOCKLEN - 1;
203 }
204 }
205 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000206}
207
208PyDoc_STRVAR(pop_doc, "Remove and return the rightmost element.");
209
210static PyObject *
211deque_popleft(dequeobject *deque, PyObject *unused)
212{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000213 PyObject *item;
214 block *prevblock;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000215
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000216 if (Py_SIZE(deque) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000217 PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
218 return NULL;
219 }
220 assert(deque->leftblock != NULL);
221 item = deque->leftblock->data[deque->leftindex];
222 deque->leftindex++;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000223 Py_SIZE(deque)--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000224 deque->state++;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000225
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000226 if (deque->leftindex == BLOCKLEN) {
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000227 if (Py_SIZE(deque) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000228 assert(deque->leftblock == deque->rightblock);
229 assert(deque->leftindex == deque->rightindex+1);
230 /* re-center instead of freeing a block */
231 deque->leftindex = CENTER + 1;
232 deque->rightindex = CENTER;
233 } else {
234 assert(deque->leftblock != deque->rightblock);
235 prevblock = deque->leftblock->rightlink;
236 freeblock(deque->leftblock);
Raymond Hettinger82df9252013-07-07 01:43:42 -1000237 CHECK_NOT_END(prevblock);
238 MARK_END(prevblock->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000239 deque->leftblock = prevblock;
240 deque->leftindex = 0;
241 }
242 }
243 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000244}
245
246PyDoc_STRVAR(popleft_doc, "Remove and return the leftmost element.");
247
Raymond Hettingerf30f5b92015-03-02 22:23:37 -0800248/* The deque's size limit is d.maxlen. The limit can be zero or positive.
249 * If there is no limit, then d.maxlen == -1.
250 *
251 * After an item is added to a deque, we check to see if the size has grown past
252 * the limit. If it has, we get the size back down to the limit by popping an
253 * item off of the opposite end. The methods that can trigger this are append(),
254 * appendleft(), extend(), and extendleft().
255 */
256
257static void
258deque_trim_right(dequeobject *deque)
259{
260 if (deque->maxlen != -1 && Py_SIZE(deque) > deque->maxlen) {
261 PyObject *rv = deque_pop(deque, NULL);
262 assert(rv != NULL);
263 assert(Py_SIZE(deque) <= deque->maxlen);
264 Py_DECREF(rv);
265 }
266}
267
268static void
269deque_trim_left(dequeobject *deque)
270{
271 if (deque->maxlen != -1 && Py_SIZE(deque) > deque->maxlen) {
272 PyObject *rv = deque_popleft(deque, NULL);
273 assert(rv != NULL);
274 assert(Py_SIZE(deque) <= deque->maxlen);
275 Py_DECREF(rv);
276 }
277}
278
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000279static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000280deque_append(dequeobject *deque, PyObject *item)
281{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000282 deque->state++;
283 if (deque->rightindex == BLOCKLEN-1) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000284 block *b = newblock(Py_SIZE(deque));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000285 if (b == NULL)
286 return NULL;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000287 b->leftlink = deque->rightblock;
288 CHECK_END(deque->rightblock->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000289 deque->rightblock->rightlink = b;
290 deque->rightblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000291 MARK_END(b->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000292 deque->rightindex = -1;
293 }
294 Py_INCREF(item);
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000295 Py_SIZE(deque)++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000296 deque->rightindex++;
297 deque->rightblock->data[deque->rightindex] = item;
Raymond Hettingerf30f5b92015-03-02 22:23:37 -0800298 deque_trim_left(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000299 Py_RETURN_NONE;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000300}
301
302PyDoc_STRVAR(append_doc, "Add an element to the right side of the deque.");
303
304static PyObject *
305deque_appendleft(dequeobject *deque, PyObject *item)
306{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000307 deque->state++;
308 if (deque->leftindex == 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000309 block *b = newblock(Py_SIZE(deque));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000310 if (b == NULL)
311 return NULL;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000312 b->rightlink = deque->leftblock;
313 CHECK_END(deque->leftblock->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000314 deque->leftblock->leftlink = b;
315 deque->leftblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000316 MARK_END(b->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000317 deque->leftindex = BLOCKLEN;
318 }
319 Py_INCREF(item);
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000320 Py_SIZE(deque)++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000321 deque->leftindex--;
322 deque->leftblock->data[deque->leftindex] = item;
Raymond Hettingerf30f5b92015-03-02 22:23:37 -0800323 deque_trim_right(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000324 Py_RETURN_NONE;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000325}
326
327PyDoc_STRVAR(appendleft_doc, "Add an element to the left side of the deque.");
328
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330/* Run an iterator to exhaustion. Shortcut for
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000331 the extend/extendleft methods when maxlen == 0. */
332static PyObject*
333consume_iterator(PyObject *it)
334{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000335 PyObject *item;
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000337 while ((item = PyIter_Next(it)) != NULL) {
338 Py_DECREF(item);
339 }
340 Py_DECREF(it);
341 if (PyErr_Occurred())
342 return NULL;
343 Py_RETURN_NONE;
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000344}
345
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000346static PyObject *
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000347deque_extend(dequeobject *deque, PyObject *iterable)
348{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000349 PyObject *it, *item;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000351 /* Handle case where id(deque) == id(iterable) */
352 if ((PyObject *)deque == iterable) {
353 PyObject *result;
354 PyObject *s = PySequence_List(iterable);
355 if (s == NULL)
356 return NULL;
357 result = deque_extend(deque, s);
358 Py_DECREF(s);
359 return result;
360 }
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000361
Raymond Hettingerd9c116c2013-07-09 00:13:21 -0700362 /* Space saving heuristic. Start filling from the left */
363 if (Py_SIZE(deque) == 0) {
364 assert(deque->leftblock == deque->rightblock);
365 assert(deque->leftindex == deque->rightindex+1);
366 deque->leftindex = 1;
367 deque->rightindex = 0;
368 }
369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000370 it = PyObject_GetIter(iterable);
371 if (it == NULL)
372 return NULL;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000374 if (deque->maxlen == 0)
375 return consume_iterator(it);
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000377 while ((item = PyIter_Next(it)) != NULL) {
378 deque->state++;
379 if (deque->rightindex == BLOCKLEN-1) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000380 block *b = newblock(Py_SIZE(deque));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000381 if (b == NULL) {
382 Py_DECREF(item);
383 Py_DECREF(it);
384 return NULL;
385 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000386 b->leftlink = deque->rightblock;
387 CHECK_END(deque->rightblock->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000388 deque->rightblock->rightlink = b;
389 deque->rightblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000390 MARK_END(b->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000391 deque->rightindex = -1;
392 }
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000393 Py_SIZE(deque)++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000394 deque->rightindex++;
395 deque->rightblock->data[deque->rightindex] = item;
Raymond Hettingerf30f5b92015-03-02 22:23:37 -0800396 deque_trim_left(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000397 }
398 Py_DECREF(it);
399 if (PyErr_Occurred())
400 return NULL;
401 Py_RETURN_NONE;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000402}
403
Tim Peters1065f752004-10-01 01:03:29 +0000404PyDoc_STRVAR(extend_doc,
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000405"Extend the right side of the deque with elements from the iterable");
406
407static PyObject *
408deque_extendleft(dequeobject *deque, PyObject *iterable)
409{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000410 PyObject *it, *item;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000412 /* Handle case where id(deque) == id(iterable) */
413 if ((PyObject *)deque == iterable) {
414 PyObject *result;
415 PyObject *s = PySequence_List(iterable);
416 if (s == NULL)
417 return NULL;
418 result = deque_extendleft(deque, s);
419 Py_DECREF(s);
420 return result;
421 }
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000422
Raymond Hettingerd9c116c2013-07-09 00:13:21 -0700423 /* Space saving heuristic. Start filling from the right */
424 if (Py_SIZE(deque) == 0) {
425 assert(deque->leftblock == deque->rightblock);
426 assert(deque->leftindex == deque->rightindex+1);
427 deque->leftindex = BLOCKLEN - 1;
428 deque->rightindex = BLOCKLEN - 2;
429 }
430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 it = PyObject_GetIter(iterable);
432 if (it == NULL)
433 return NULL;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435 if (deque->maxlen == 0)
436 return consume_iterator(it);
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000437
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000438 while ((item = PyIter_Next(it)) != NULL) {
439 deque->state++;
440 if (deque->leftindex == 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000441 block *b = newblock(Py_SIZE(deque));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000442 if (b == NULL) {
443 Py_DECREF(item);
444 Py_DECREF(it);
445 return NULL;
446 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000447 b->rightlink = deque->leftblock;
448 CHECK_END(deque->leftblock->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000449 deque->leftblock->leftlink = b;
450 deque->leftblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000451 MARK_END(b->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000452 deque->leftindex = BLOCKLEN;
453 }
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000454 Py_SIZE(deque)++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000455 deque->leftindex--;
456 deque->leftblock->data[deque->leftindex] = item;
Raymond Hettingerf30f5b92015-03-02 22:23:37 -0800457 deque_trim_right(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000458 }
459 Py_DECREF(it);
460 if (PyErr_Occurred())
461 return NULL;
462 Py_RETURN_NONE;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000463}
464
Tim Peters1065f752004-10-01 01:03:29 +0000465PyDoc_STRVAR(extendleft_doc,
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000466"Extend the left side of the deque with elements from the iterable");
467
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000468static PyObject *
469deque_inplace_concat(dequeobject *deque, PyObject *other)
470{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 PyObject *result;
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000473 result = deque_extend(deque, other);
474 if (result == NULL)
475 return result;
476 Py_DECREF(result);
477 Py_INCREF(deque);
478 return (PyObject *)deque;
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000479}
480
Raymond Hettinger54023152014-04-23 00:58:48 -0700481/* The rotate() method is part of the public API and is used internally
482as a primitive for other methods.
483
484Rotation by 1 or -1 is a common case, so any optimizations for high
485volume rotations should take care not to penalize the common case.
486
487Conceptually, a rotate by one is equivalent to a pop on one side and an
488append on the other. However, a pop/append pair is unnecessarily slow
489because it requires a incref/decref pair for an object located randomly
490in memory. It is better to just move the object pointer from one block
491to the next without changing the reference count.
492
493When moving batches of pointers, it is tempting to use memcpy() but that
494proved to be slower than a simple loop for a variety of reasons.
495Memcpy() cannot know in advance that we're copying pointers instead of
496bytes, that the source and destination are pointer aligned and
497non-overlapping, that moving just one pointer is a common case, that we
498never need to move more than BLOCKLEN pointers, and that at least one
499pointer is always moved.
500
501For high volume rotations, newblock() and freeblock() are never called
502more than once. Previously emptied blocks are immediately reused as a
503destination block. If a block is left-over at the end, it is freed.
504*/
505
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000506static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000507_deque_rotate(dequeobject *deque, Py_ssize_t n)
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000508{
Raymond Hettinger3959af92013-07-13 02:34:08 -0700509 block *b = NULL;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700510 block *leftblock = deque->leftblock;
511 block *rightblock = deque->rightblock;
512 Py_ssize_t leftindex = deque->leftindex;
513 Py_ssize_t rightindex = deque->rightindex;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000514 Py_ssize_t len=Py_SIZE(deque), halflen=len>>1;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700515 int rv = -1;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000516
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800517 if (len <= 1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 return 0;
519 if (n > halflen || n < -halflen) {
520 n %= len;
521 if (n > halflen)
522 n -= len;
523 else if (n < -halflen)
524 n += len;
525 }
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500526 assert(len > 1);
Raymond Hettingera4409c12013-02-04 00:08:12 -0500527 assert(-halflen <= n && n <= halflen);
Raymond Hettinger231ee4d2013-02-02 11:24:43 -0800528
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800529 deque->state++;
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500530 while (n > 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700531 if (leftindex == 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700532 if (b == NULL) {
Raymond Hettinger3959af92013-07-13 02:34:08 -0700533 b = newblock(len);
534 if (b == NULL)
535 goto done;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700536 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000537 b->rightlink = leftblock;
538 CHECK_END(leftblock->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700539 leftblock->leftlink = b;
540 leftblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000541 MARK_END(b->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700542 leftindex = BLOCKLEN;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700543 b = NULL;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800544 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700545 assert(leftindex > 0);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700546 {
547 PyObject **src, **dest;
548 Py_ssize_t m = n;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800549
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700550 if (m > rightindex + 1)
551 m = rightindex + 1;
552 if (m > leftindex)
553 m = leftindex;
554 assert (m > 0 && m <= len);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700555 rightindex -= m;
556 leftindex -= m;
Raymond Hettinger0e259f12015-02-01 22:53:41 -0800557 src = &rightblock->data[rightindex + 1];
558 dest = &leftblock->data[leftindex];
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700559 n -= m;
Raymond Hettinger840533b2013-07-13 17:03:58 -0700560 do {
Raymond Hettinger0e259f12015-02-01 22:53:41 -0800561 *(dest++) = *(src++);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700562 } while (--m);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700563 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700564 if (rightindex == -1) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700565 assert(leftblock != rightblock);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700566 assert(b == NULL);
Raymond Hettinger3959af92013-07-13 02:34:08 -0700567 b = rightblock;
Raymond Hettingerb97cc492013-07-21 01:51:07 -0700568 CHECK_NOT_END(rightblock->leftlink);
569 rightblock = rightblock->leftlink;
570 MARK_END(rightblock->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700571 rightindex = BLOCKLEN - 1;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800572 }
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800573 }
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500574 while (n < 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700575 if (rightindex == BLOCKLEN - 1) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700576 if (b == NULL) {
Raymond Hettinger3959af92013-07-13 02:34:08 -0700577 b = newblock(len);
578 if (b == NULL)
579 goto done;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700580 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000581 b->leftlink = rightblock;
582 CHECK_END(rightblock->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700583 rightblock->rightlink = b;
584 rightblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000585 MARK_END(b->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700586 rightindex = -1;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700587 b = NULL;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800588 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700589 assert (rightindex < BLOCKLEN - 1);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700590 {
591 PyObject **src, **dest;
592 Py_ssize_t m = -n;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800593
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700594 if (m > BLOCKLEN - leftindex)
595 m = BLOCKLEN - leftindex;
596 if (m > BLOCKLEN - 1 - rightindex)
597 m = BLOCKLEN - 1 - rightindex;
598 assert (m > 0 && m <= len);
599 src = &leftblock->data[leftindex];
600 dest = &rightblock->data[rightindex + 1];
601 leftindex += m;
602 rightindex += m;
603 n += m;
Raymond Hettinger840533b2013-07-13 17:03:58 -0700604 do {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700605 *(dest++) = *(src++);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700606 } while (--m);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700607 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700608 if (leftindex == BLOCKLEN) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700609 assert(leftblock != rightblock);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700610 assert(b == NULL);
Raymond Hettinger3959af92013-07-13 02:34:08 -0700611 b = leftblock;
Raymond Hettingerb97cc492013-07-21 01:51:07 -0700612 CHECK_NOT_END(leftblock->rightlink);
613 leftblock = leftblock->rightlink;
614 MARK_END(leftblock->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700615 leftindex = 0;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800616 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000617 }
Raymond Hettinger3959af92013-07-13 02:34:08 -0700618 rv = 0;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700619done:
Raymond Hettinger3959af92013-07-13 02:34:08 -0700620 if (b != NULL)
621 freeblock(b);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700622 deque->leftblock = leftblock;
623 deque->rightblock = rightblock;
624 deque->leftindex = leftindex;
625 deque->rightindex = rightindex;
626
627 return rv;
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000628}
629
630static PyObject *
631deque_rotate(dequeobject *deque, PyObject *args)
632{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000633 Py_ssize_t n=1;
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000635 if (!PyArg_ParseTuple(args, "|n:rotate", &n))
636 return NULL;
637 if (_deque_rotate(deque, n) == 0)
638 Py_RETURN_NONE;
639 return NULL;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000640}
641
Tim Peters1065f752004-10-01 01:03:29 +0000642PyDoc_STRVAR(rotate_doc,
Raymond Hettingeree33b272004-02-08 04:05:26 +0000643"Rotate the deque n steps to the right (default n=1). If n is negative, rotates left.");
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000644
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000645static PyObject *
646deque_reverse(dequeobject *deque, PyObject *unused)
647{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000648 block *leftblock = deque->leftblock;
649 block *rightblock = deque->rightblock;
650 Py_ssize_t leftindex = deque->leftindex;
651 Py_ssize_t rightindex = deque->rightindex;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000652 Py_ssize_t n = (Py_SIZE(deque))/2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000653 Py_ssize_t i;
654 PyObject *tmp;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000655
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000656 for (i=0 ; i<n ; i++) {
657 /* Validate that pointers haven't met in the middle */
658 assert(leftblock != rightblock || leftindex < rightindex);
Raymond Hettinger82df9252013-07-07 01:43:42 -1000659 CHECK_NOT_END(leftblock);
660 CHECK_NOT_END(rightblock);
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000661
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000662 /* Swap */
663 tmp = leftblock->data[leftindex];
664 leftblock->data[leftindex] = rightblock->data[rightindex];
665 rightblock->data[rightindex] = tmp;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000666
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000667 /* Advance left block/index pair */
668 leftindex++;
669 if (leftindex == BLOCKLEN) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 leftblock = leftblock->rightlink;
671 leftindex = 0;
672 }
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000673
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000674 /* Step backwards with the right block/index pair */
675 rightindex--;
676 if (rightindex == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000677 rightblock = rightblock->leftlink;
678 rightindex = BLOCKLEN - 1;
679 }
680 }
681 Py_RETURN_NONE;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000682}
683
684PyDoc_STRVAR(reverse_doc,
685"D.reverse() -- reverse *IN PLACE*");
686
Raymond Hettinger44459de2010-04-03 23:20:46 +0000687static PyObject *
688deque_count(dequeobject *deque, PyObject *v)
689{
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000690 block *b = deque->leftblock;
691 Py_ssize_t index = deque->leftindex;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000692 Py_ssize_t n = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000693 Py_ssize_t i;
694 Py_ssize_t count = 0;
Raymond Hettingerf9d9c792015-03-02 22:47:46 -0800695 size_t start_state = deque->state;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000696 PyObject *item;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000697 int cmp;
Raymond Hettinger44459de2010-04-03 23:20:46 +0000698
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000699 for (i=0 ; i<n ; i++) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000700 CHECK_NOT_END(b);
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000701 item = b->data[index];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000702 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
703 if (cmp > 0)
704 count++;
705 else if (cmp < 0)
706 return NULL;
Raymond Hettinger44459de2010-04-03 23:20:46 +0000707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708 if (start_state != deque->state) {
709 PyErr_SetString(PyExc_RuntimeError,
710 "deque mutated during iteration");
711 return NULL;
712 }
Raymond Hettinger44459de2010-04-03 23:20:46 +0000713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 /* Advance left block/index pair */
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000715 index++;
716 if (index == BLOCKLEN) {
717 b = b->rightlink;
718 index = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000719 }
720 }
721 return PyLong_FromSsize_t(count);
Raymond Hettinger44459de2010-04-03 23:20:46 +0000722}
723
724PyDoc_STRVAR(count_doc,
725"D.count(value) -> integer -- return number of occurrences of value");
726
Martin v. Löwis18e16552006-02-15 17:27:45 +0000727static Py_ssize_t
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000728deque_len(dequeobject *deque)
729{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000730 return Py_SIZE(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000731}
732
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000733static PyObject *
734deque_remove(dequeobject *deque, PyObject *value)
735{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000736 Py_ssize_t i, n=Py_SIZE(deque);
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000738 for (i=0 ; i<n ; i++) {
739 PyObject *item = deque->leftblock->data[deque->leftindex];
740 int cmp = PyObject_RichCompareBool(item, value, Py_EQ);
Raymond Hettingerd73202c2005-03-19 00:00:51 +0000741
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000742 if (Py_SIZE(deque) != n) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000743 PyErr_SetString(PyExc_IndexError,
744 "deque mutated during remove().");
745 return NULL;
746 }
747 if (cmp > 0) {
748 PyObject *tgt = deque_popleft(deque, NULL);
749 assert (tgt != NULL);
750 Py_DECREF(tgt);
751 if (_deque_rotate(deque, i) == -1)
752 return NULL;
753 Py_RETURN_NONE;
754 }
755 else if (cmp < 0) {
756 _deque_rotate(deque, i);
757 return NULL;
758 }
759 _deque_rotate(deque, -1);
760 }
761 PyErr_SetString(PyExc_ValueError, "deque.remove(x): x not in deque");
762 return NULL;
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000763}
764
765PyDoc_STRVAR(remove_doc,
766"D.remove(value) -- remove first occurrence of value.");
767
Benjamin Peterson0e5c48a2013-01-12 21:22:18 -0500768static void
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000769deque_clear(dequeobject *deque)
770{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000771 PyObject *item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000772
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000773 while (Py_SIZE(deque)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000774 item = deque_pop(deque, NULL);
775 assert (item != NULL);
776 Py_DECREF(item);
777 }
Raymond Hettinger87e69122015-03-02 23:32:02 -0800778 assert(deque->leftblock == deque->rightblock);
779 assert(deque->leftindex - 1 == deque->rightindex);
780 assert(Py_SIZE(deque) == 0);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000781}
782
Raymond Hettinger3c186ba2015-03-02 21:45:02 -0800783static int
784valid_index(Py_ssize_t i, Py_ssize_t limit)
785{
786 /* The cast to size_t let us use just a single comparison
787 to check whether i is in the range: 0 <= i < limit */
788 return (size_t) i < (size_t) limit;
789}
790
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000791static PyObject *
Benjamin Petersond6313712008-07-31 16:23:04 +0000792deque_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000793{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000794 block *b;
795 PyObject *item;
796 Py_ssize_t n, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000797
Raymond Hettinger3c186ba2015-03-02 21:45:02 -0800798 if (!valid_index(i, Py_SIZE(deque))) {
799 PyErr_SetString(PyExc_IndexError, "deque index out of range");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000800 return NULL;
801 }
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000802
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 if (i == 0) {
804 i = deque->leftindex;
805 b = deque->leftblock;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000806 } else if (i == Py_SIZE(deque) - 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000807 i = deque->rightindex;
808 b = deque->rightblock;
809 } else {
810 i += deque->leftindex;
Raymond Hettingerc2083082015-02-28 23:29:16 -0800811 n = (Py_ssize_t)((size_t) i / BLOCKLEN);
812 i = (Py_ssize_t)((size_t) i % BLOCKLEN);
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000813 if (index < (Py_SIZE(deque) >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000814 b = deque->leftblock;
815 while (n--)
816 b = b->rightlink;
817 } else {
Raymond Hettinger63d1ff22015-02-28 07:41:30 -0800818 n = (Py_ssize_t)(
Raymond Hettingerc2083082015-02-28 23:29:16 -0800819 ((size_t)(deque->leftindex + Py_SIZE(deque) - 1))
Raymond Hettinger63d1ff22015-02-28 07:41:30 -0800820 / BLOCKLEN - n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000821 b = deque->rightblock;
822 while (n--)
823 b = b->leftlink;
824 }
825 }
826 item = b->data[i];
827 Py_INCREF(item);
828 return item;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000829}
830
Raymond Hettinger616f4f62004-06-26 04:42:06 +0000831/* delitem() implemented in terms of rotate for simplicity and reasonable
832 performance near the end points. If for some reason this method becomes
Tim Peters1065f752004-10-01 01:03:29 +0000833 popular, it is not hard to re-implement this using direct data movement
Raymond Hettinger616f4f62004-06-26 04:42:06 +0000834 (similar to code in list slice assignment) and achieve a two or threefold
835 performance boost.
836*/
837
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000838static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000839deque_del_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000840{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000841 PyObject *item;
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000842
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000843 assert (i >= 0 && i < Py_SIZE(deque));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000844 if (_deque_rotate(deque, -i) == -1)
845 return -1;
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000846
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000847 item = deque_popleft(deque, NULL);
848 assert (item != NULL);
849 Py_DECREF(item);
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000850
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000851 return _deque_rotate(deque, i);
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000852}
853
854static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000855deque_ass_item(dequeobject *deque, Py_ssize_t i, PyObject *v)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000856{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000857 PyObject *old_value;
858 block *b;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000859 Py_ssize_t n, len=Py_SIZE(deque), halflen=(len+1)>>1, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000860
Raymond Hettinger3c186ba2015-03-02 21:45:02 -0800861 if (!valid_index(i, len)) {
862 PyErr_SetString(PyExc_IndexError, "deque index out of range");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000863 return -1;
864 }
865 if (v == NULL)
866 return deque_del_item(deque, i);
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 i += deque->leftindex;
Raymond Hettingerc2083082015-02-28 23:29:16 -0800869 n = (Py_ssize_t)((size_t) i / BLOCKLEN);
870 i = (Py_ssize_t)((size_t) i % BLOCKLEN);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000871 if (index <= halflen) {
872 b = deque->leftblock;
873 while (n--)
874 b = b->rightlink;
875 } else {
Raymond Hettingera473b9d2015-02-28 17:49:47 -0800876 n = (Py_ssize_t)(
Raymond Hettingerc2083082015-02-28 23:29:16 -0800877 ((size_t)(deque->leftindex + Py_SIZE(deque) - 1))
Raymond Hettingera473b9d2015-02-28 17:49:47 -0800878 / BLOCKLEN - n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000879 b = deque->rightblock;
880 while (n--)
881 b = b->leftlink;
882 }
883 Py_INCREF(v);
884 old_value = b->data[i];
885 b->data[i] = v;
886 Py_DECREF(old_value);
887 return 0;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000888}
889
890static PyObject *
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000891deque_clearmethod(dequeobject *deque)
892{
Benjamin Peterson0e5c48a2013-01-12 21:22:18 -0500893 deque_clear(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 Py_RETURN_NONE;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000895}
896
897PyDoc_STRVAR(clear_doc, "Remove all elements from the deque.");
898
899static void
900deque_dealloc(dequeobject *deque)
901{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000902 PyObject_GC_UnTrack(deque);
903 if (deque->weakreflist != NULL)
904 PyObject_ClearWeakRefs((PyObject *) deque);
905 if (deque->leftblock != NULL) {
906 deque_clear(deque);
907 assert(deque->leftblock != NULL);
908 freeblock(deque->leftblock);
909 }
910 deque->leftblock = NULL;
911 deque->rightblock = NULL;
912 Py_TYPE(deque)->tp_free(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000913}
914
915static int
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000916deque_traverse(dequeobject *deque, visitproc visit, void *arg)
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000917{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 block *b;
919 PyObject *item;
920 Py_ssize_t index;
921 Py_ssize_t indexlo = deque->leftindex;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000922
Raymond Hettinger5bfa8672013-07-06 11:58:09 -1000923 for (b = deque->leftblock; b != deque->rightblock; b = b->rightlink) {
924 for (index = indexlo; index < BLOCKLEN ; index++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000925 item = b->data[index];
926 Py_VISIT(item);
927 }
928 indexlo = 0;
929 }
Raymond Hettinger5bfa8672013-07-06 11:58:09 -1000930 for (index = indexlo; index <= deque->rightindex; index++) {
931 item = b->data[index];
932 Py_VISIT(item);
933 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 return 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000935}
936
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000937static PyObject *
938deque_copy(PyObject *deque)
939{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 if (((dequeobject *)deque)->maxlen == -1)
941 return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "O", deque, NULL);
942 else
943 return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "Oi",
944 deque, ((dequeobject *)deque)->maxlen, NULL);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000945}
946
947PyDoc_STRVAR(copy_doc, "Return a shallow copy of a deque.");
948
949static PyObject *
950deque_reduce(dequeobject *deque)
951{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 PyObject *dict, *result, *aslist;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200953 _Py_IDENTIFIER(__dict__);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000954
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200955 dict = _PyObject_GetAttrId((PyObject *)deque, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000956 if (dict == NULL)
957 PyErr_Clear();
958 aslist = PySequence_List((PyObject *)deque);
959 if (aslist == NULL) {
960 Py_XDECREF(dict);
961 return NULL;
962 }
963 if (dict == NULL) {
964 if (deque->maxlen == -1)
965 result = Py_BuildValue("O(O)", Py_TYPE(deque), aslist);
966 else
967 result = Py_BuildValue("O(On)", Py_TYPE(deque), aslist, deque->maxlen);
968 } else {
969 if (deque->maxlen == -1)
970 result = Py_BuildValue("O(OO)O", Py_TYPE(deque), aslist, Py_None, dict);
971 else
972 result = Py_BuildValue("O(On)O", Py_TYPE(deque), aslist, deque->maxlen, dict);
973 }
974 Py_XDECREF(dict);
975 Py_DECREF(aslist);
976 return result;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000977}
978
979PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
980
981static PyObject *
982deque_repr(PyObject *deque)
983{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000984 PyObject *aslist, *result;
985 int i;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 i = Py_ReprEnter(deque);
988 if (i != 0) {
989 if (i < 0)
990 return NULL;
991 return PyUnicode_FromString("[...]");
992 }
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000994 aslist = PySequence_List(deque);
995 if (aslist == NULL) {
996 Py_ReprLeave(deque);
997 return NULL;
998 }
999 if (((dequeobject *)deque)->maxlen != -1)
Benjamin Petersona786b022008-08-25 21:05:21 +00001000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001001 result = PyUnicode_FromFormat("deque(%R, maxlen=%zd)",
1002 aslist, ((dequeobject *)deque)->maxlen);
1003 else
1004 result = PyUnicode_FromFormat("deque(%R)", aslist);
1005 Py_DECREF(aslist);
1006 Py_ReprLeave(deque);
1007 return result;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001008}
1009
Raymond Hettinger738ec902004-02-29 02:15:56 +00001010static PyObject *
1011deque_richcompare(PyObject *v, PyObject *w, int op)
1012{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001013 PyObject *it1=NULL, *it2=NULL, *x, *y;
1014 Py_ssize_t vs, ws;
1015 int b, cmp=-1;
Raymond Hettinger738ec902004-02-29 02:15:56 +00001016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 if (!PyObject_TypeCheck(v, &deque_type) ||
1018 !PyObject_TypeCheck(w, &deque_type)) {
Brian Curtindfc80e32011-08-10 20:28:54 -05001019 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 }
Raymond Hettinger738ec902004-02-29 02:15:56 +00001021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001022 /* Shortcuts */
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001023 vs = Py_SIZE((dequeobject *)v);
1024 ws = Py_SIZE((dequeobject *)w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001025 if (op == Py_EQ) {
1026 if (v == w)
1027 Py_RETURN_TRUE;
1028 if (vs != ws)
1029 Py_RETURN_FALSE;
1030 }
1031 if (op == Py_NE) {
1032 if (v == w)
1033 Py_RETURN_FALSE;
1034 if (vs != ws)
1035 Py_RETURN_TRUE;
1036 }
Raymond Hettinger738ec902004-02-29 02:15:56 +00001037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 /* Search for the first index where items are different */
1039 it1 = PyObject_GetIter(v);
1040 if (it1 == NULL)
1041 goto done;
1042 it2 = PyObject_GetIter(w);
1043 if (it2 == NULL)
1044 goto done;
1045 for (;;) {
1046 x = PyIter_Next(it1);
1047 if (x == NULL && PyErr_Occurred())
1048 goto done;
1049 y = PyIter_Next(it2);
1050 if (x == NULL || y == NULL)
1051 break;
1052 b = PyObject_RichCompareBool(x, y, Py_EQ);
1053 if (b == 0) {
1054 cmp = PyObject_RichCompareBool(x, y, op);
1055 Py_DECREF(x);
1056 Py_DECREF(y);
1057 goto done;
1058 }
1059 Py_DECREF(x);
1060 Py_DECREF(y);
1061 if (b == -1)
1062 goto done;
1063 }
1064 /* We reached the end of one deque or both */
1065 Py_XDECREF(x);
1066 Py_XDECREF(y);
1067 if (PyErr_Occurred())
1068 goto done;
1069 switch (op) {
1070 case Py_LT: cmp = y != NULL; break; /* if w was longer */
1071 case Py_LE: cmp = x == NULL; break; /* if v was not longer */
1072 case Py_EQ: cmp = x == y; break; /* if we reached the end of both */
1073 case Py_NE: cmp = x != y; break; /* if one deque continues */
1074 case Py_GT: cmp = x != NULL; break; /* if v was longer */
1075 case Py_GE: cmp = y == NULL; break; /* if w was not longer */
1076 }
Tim Peters1065f752004-10-01 01:03:29 +00001077
Raymond Hettinger738ec902004-02-29 02:15:56 +00001078done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001079 Py_XDECREF(it1);
1080 Py_XDECREF(it2);
1081 if (cmp == 1)
1082 Py_RETURN_TRUE;
1083 if (cmp == 0)
1084 Py_RETURN_FALSE;
1085 return NULL;
Raymond Hettinger738ec902004-02-29 02:15:56 +00001086}
1087
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001088static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001089deque_init(dequeobject *deque, PyObject *args, PyObject *kwdargs)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001090{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 PyObject *iterable = NULL;
1092 PyObject *maxlenobj = NULL;
1093 Py_ssize_t maxlen = -1;
1094 char *kwlist[] = {"iterable", "maxlen", 0};
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001095
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001096 if (!PyArg_ParseTupleAndKeywords(args, kwdargs, "|OO:deque", kwlist, &iterable, &maxlenobj))
1097 return -1;
1098 if (maxlenobj != NULL && maxlenobj != Py_None) {
1099 maxlen = PyLong_AsSsize_t(maxlenobj);
1100 if (maxlen == -1 && PyErr_Occurred())
1101 return -1;
1102 if (maxlen < 0) {
1103 PyErr_SetString(PyExc_ValueError, "maxlen must be non-negative");
1104 return -1;
1105 }
1106 }
1107 deque->maxlen = maxlen;
1108 deque_clear(deque);
1109 if (iterable != NULL) {
1110 PyObject *rv = deque_extend(deque, iterable);
1111 if (rv == NULL)
1112 return -1;
1113 Py_DECREF(rv);
1114 }
1115 return 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001116}
1117
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001118static PyObject *
Jesus Cea16e2fca2012-08-03 14:49:42 +02001119deque_sizeof(dequeobject *deque, void *unused)
1120{
1121 Py_ssize_t res;
1122 Py_ssize_t blocks;
1123
1124 res = sizeof(dequeobject);
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001125 blocks = (deque->leftindex + Py_SIZE(deque) + BLOCKLEN - 1) / BLOCKLEN;
1126 assert(deque->leftindex + Py_SIZE(deque) - 1 ==
Jesus Cea16e2fca2012-08-03 14:49:42 +02001127 (blocks - 1) * BLOCKLEN + deque->rightindex);
1128 res += blocks * sizeof(block);
1129 return PyLong_FromSsize_t(res);
1130}
1131
1132PyDoc_STRVAR(sizeof_doc,
1133"D.__sizeof__() -- size of D in memory, in bytes");
1134
1135static PyObject *
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001136deque_get_maxlen(dequeobject *deque)
1137{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001138 if (deque->maxlen == -1)
1139 Py_RETURN_NONE;
1140 return PyLong_FromSsize_t(deque->maxlen);
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001141}
1142
1143static PyGetSetDef deque_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001144 {"maxlen", (getter)deque_get_maxlen, (setter)NULL,
1145 "maximum size of a deque or None if unbounded"},
1146 {0}
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001147};
1148
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001149static PySequenceMethods deque_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001150 (lenfunc)deque_len, /* sq_length */
1151 0, /* sq_concat */
1152 0, /* sq_repeat */
1153 (ssizeargfunc)deque_item, /* sq_item */
1154 0, /* sq_slice */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001155 (ssizeobjargproc)deque_ass_item, /* sq_ass_item */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001156 0, /* sq_ass_slice */
1157 0, /* sq_contains */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001158 (binaryfunc)deque_inplace_concat, /* sq_inplace_concat */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001159 0, /* sq_inplace_repeat */
Raymond Hettinger3f9afd82009-12-10 03:03:02 +00001160
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001161};
1162
1163/* deque object ********************************************************/
1164
1165static PyObject *deque_iter(dequeobject *deque);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001166static PyObject *deque_reviter(dequeobject *deque);
Tim Peters1065f752004-10-01 01:03:29 +00001167PyDoc_STRVAR(reversed_doc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001168 "D.__reversed__() -- return a reverse iterator over the deque");
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001169
1170static PyMethodDef deque_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001171 {"append", (PyCFunction)deque_append,
1172 METH_O, append_doc},
1173 {"appendleft", (PyCFunction)deque_appendleft,
1174 METH_O, appendleft_doc},
1175 {"clear", (PyCFunction)deque_clearmethod,
1176 METH_NOARGS, clear_doc},
1177 {"__copy__", (PyCFunction)deque_copy,
1178 METH_NOARGS, copy_doc},
1179 {"count", (PyCFunction)deque_count,
1180 METH_O, count_doc},
1181 {"extend", (PyCFunction)deque_extend,
1182 METH_O, extend_doc},
1183 {"extendleft", (PyCFunction)deque_extendleft,
1184 METH_O, extendleft_doc},
1185 {"pop", (PyCFunction)deque_pop,
1186 METH_NOARGS, pop_doc},
1187 {"popleft", (PyCFunction)deque_popleft,
1188 METH_NOARGS, popleft_doc},
1189 {"__reduce__", (PyCFunction)deque_reduce,
1190 METH_NOARGS, reduce_doc},
1191 {"remove", (PyCFunction)deque_remove,
1192 METH_O, remove_doc},
1193 {"__reversed__", (PyCFunction)deque_reviter,
1194 METH_NOARGS, reversed_doc},
1195 {"reverse", (PyCFunction)deque_reverse,
1196 METH_NOARGS, reverse_doc},
1197 {"rotate", (PyCFunction)deque_rotate,
Jesus Cea16e2fca2012-08-03 14:49:42 +02001198 METH_VARARGS, rotate_doc},
1199 {"__sizeof__", (PyCFunction)deque_sizeof,
1200 METH_NOARGS, sizeof_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001201 {NULL, NULL} /* sentinel */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001202};
1203
1204PyDoc_STRVAR(deque_doc,
Andrew Svetlov6a5c7c32012-10-31 11:50:40 +02001205"deque([iterable[, maxlen]]) --> deque object\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001206\n\
Raymond Hettinger49747052011-03-29 17:36:31 -07001207Build an ordered collection with optimized access from its endpoints.");
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001208
Neal Norwitz87f10132004-02-29 15:40:53 +00001209static PyTypeObject deque_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001210 PyVarObject_HEAD_INIT(NULL, 0)
1211 "collections.deque", /* tp_name */
1212 sizeof(dequeobject), /* tp_basicsize */
1213 0, /* tp_itemsize */
1214 /* methods */
1215 (destructor)deque_dealloc, /* tp_dealloc */
1216 0, /* tp_print */
1217 0, /* tp_getattr */
1218 0, /* tp_setattr */
1219 0, /* tp_reserved */
1220 deque_repr, /* tp_repr */
1221 0, /* tp_as_number */
1222 &deque_as_sequence, /* tp_as_sequence */
1223 0, /* tp_as_mapping */
Georg Brandlf038b322010-10-18 07:35:09 +00001224 PyObject_HashNotImplemented, /* tp_hash */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 0, /* tp_call */
1226 0, /* tp_str */
1227 PyObject_GenericGetAttr, /* tp_getattro */
1228 0, /* tp_setattro */
1229 0, /* tp_as_buffer */
1230 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
Georg Brandlf038b322010-10-18 07:35:09 +00001231 /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001232 deque_doc, /* tp_doc */
1233 (traverseproc)deque_traverse, /* tp_traverse */
1234 (inquiry)deque_clear, /* tp_clear */
1235 (richcmpfunc)deque_richcompare, /* tp_richcompare */
Georg Brandlf038b322010-10-18 07:35:09 +00001236 offsetof(dequeobject, weakreflist), /* tp_weaklistoffset*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001237 (getiterfunc)deque_iter, /* tp_iter */
1238 0, /* tp_iternext */
1239 deque_methods, /* tp_methods */
1240 0, /* tp_members */
Georg Brandlf038b322010-10-18 07:35:09 +00001241 deque_getset, /* tp_getset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001242 0, /* tp_base */
1243 0, /* tp_dict */
1244 0, /* tp_descr_get */
1245 0, /* tp_descr_set */
1246 0, /* tp_dictoffset */
1247 (initproc)deque_init, /* tp_init */
1248 PyType_GenericAlloc, /* tp_alloc */
1249 deque_new, /* tp_new */
1250 PyObject_GC_Del, /* tp_free */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001251};
1252
1253/*********************** Deque Iterator **************************/
1254
1255typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001256 PyObject_HEAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001257 block *b;
Raymond Hettinger87e69122015-03-02 23:32:02 -08001258 Py_ssize_t index;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001259 dequeobject *deque;
Raymond Hettingerf9d9c792015-03-02 22:47:46 -08001260 size_t state; /* state when the iterator is created */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001261 Py_ssize_t counter; /* number of items remaining for iteration */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001262} dequeiterobject;
1263
Martin v. Löwis59683e82008-06-13 07:50:45 +00001264static PyTypeObject dequeiter_type;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001265
1266static PyObject *
1267deque_iter(dequeobject *deque)
1268{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001269 dequeiterobject *it;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001271 it = PyObject_GC_New(dequeiterobject, &dequeiter_type);
1272 if (it == NULL)
1273 return NULL;
1274 it->b = deque->leftblock;
1275 it->index = deque->leftindex;
1276 Py_INCREF(deque);
1277 it->deque = deque;
1278 it->state = deque->state;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001279 it->counter = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001280 PyObject_GC_Track(it);
1281 return (PyObject *)it;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001282}
1283
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001284static int
1285dequeiter_traverse(dequeiterobject *dio, visitproc visit, void *arg)
1286{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001287 Py_VISIT(dio->deque);
1288 return 0;
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001289}
1290
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001291static void
1292dequeiter_dealloc(dequeiterobject *dio)
1293{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001294 Py_XDECREF(dio->deque);
1295 PyObject_GC_Del(dio);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001296}
1297
1298static PyObject *
1299dequeiter_next(dequeiterobject *it)
1300{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001301 PyObject *item;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001303 if (it->deque->state != it->state) {
1304 it->counter = 0;
1305 PyErr_SetString(PyExc_RuntimeError,
1306 "deque mutated during iteration");
1307 return NULL;
1308 }
1309 if (it->counter == 0)
1310 return NULL;
1311 assert (!(it->b == it->deque->rightblock &&
1312 it->index > it->deque->rightindex));
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001314 item = it->b->data[it->index];
1315 it->index++;
1316 it->counter--;
1317 if (it->index == BLOCKLEN && it->counter > 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -10001318 CHECK_NOT_END(it->b->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001319 it->b = it->b->rightlink;
1320 it->index = 0;
1321 }
1322 Py_INCREF(item);
1323 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001324}
1325
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001326static PyObject *
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001327dequeiter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1328{
1329 Py_ssize_t i, index=0;
1330 PyObject *deque;
1331 dequeiterobject *it;
1332 if (!PyArg_ParseTuple(args, "O!|n", &deque_type, &deque, &index))
1333 return NULL;
1334 assert(type == &dequeiter_type);
1335
1336 it = (dequeiterobject*)deque_iter((dequeobject *)deque);
1337 if (!it)
1338 return NULL;
1339 /* consume items from the queue */
1340 for(i=0; i<index; i++) {
1341 PyObject *item = dequeiter_next(it);
1342 if (item) {
1343 Py_DECREF(item);
1344 } else {
1345 if (it->counter) {
1346 Py_DECREF(it);
1347 return NULL;
1348 } else
1349 break;
1350 }
1351 }
1352 return (PyObject*)it;
1353}
1354
1355static PyObject *
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001356dequeiter_len(dequeiterobject *it)
1357{
Antoine Pitrou554f3342010-08-17 18:30:06 +00001358 return PyLong_FromSsize_t(it->counter);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001359}
1360
Armin Rigof5b3e362006-02-11 21:32:43 +00001361PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001362
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001363static PyObject *
1364dequeiter_reduce(dequeiterobject *it)
1365{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001366 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 +00001367}
1368
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001369static PyMethodDef dequeiter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001370 {"__length_hint__", (PyCFunction)dequeiter_len, METH_NOARGS, length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001371 {"__reduce__", (PyCFunction)dequeiter_reduce, METH_NOARGS, reduce_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001372 {NULL, NULL} /* sentinel */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001373};
1374
Martin v. Löwis59683e82008-06-13 07:50:45 +00001375static PyTypeObject dequeiter_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001376 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger87e69122015-03-02 23:32:02 -08001377 "_collections._deque_iterator", /* tp_name */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001378 sizeof(dequeiterobject), /* tp_basicsize */
1379 0, /* tp_itemsize */
1380 /* methods */
1381 (destructor)dequeiter_dealloc, /* tp_dealloc */
1382 0, /* tp_print */
1383 0, /* tp_getattr */
1384 0, /* tp_setattr */
1385 0, /* tp_reserved */
1386 0, /* tp_repr */
1387 0, /* tp_as_number */
1388 0, /* tp_as_sequence */
1389 0, /* tp_as_mapping */
1390 0, /* tp_hash */
1391 0, /* tp_call */
1392 0, /* tp_str */
1393 PyObject_GenericGetAttr, /* tp_getattro */
1394 0, /* tp_setattro */
1395 0, /* tp_as_buffer */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001396 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001397 0, /* tp_doc */
1398 (traverseproc)dequeiter_traverse, /* tp_traverse */
1399 0, /* tp_clear */
1400 0, /* tp_richcompare */
1401 0, /* tp_weaklistoffset */
1402 PyObject_SelfIter, /* tp_iter */
1403 (iternextfunc)dequeiter_next, /* tp_iternext */
1404 dequeiter_methods, /* tp_methods */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001405 0, /* tp_members */
1406 0, /* tp_getset */
1407 0, /* tp_base */
1408 0, /* tp_dict */
1409 0, /* tp_descr_get */
1410 0, /* tp_descr_set */
1411 0, /* tp_dictoffset */
1412 0, /* tp_init */
1413 0, /* tp_alloc */
1414 dequeiter_new, /* tp_new */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001415 0,
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001416};
1417
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001418/*********************** Deque Reverse Iterator **************************/
1419
Martin v. Löwis59683e82008-06-13 07:50:45 +00001420static PyTypeObject dequereviter_type;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001421
1422static PyObject *
1423deque_reviter(dequeobject *deque)
1424{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001425 dequeiterobject *it;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001426
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001427 it = PyObject_GC_New(dequeiterobject, &dequereviter_type);
1428 if (it == NULL)
1429 return NULL;
1430 it->b = deque->rightblock;
1431 it->index = deque->rightindex;
1432 Py_INCREF(deque);
1433 it->deque = deque;
1434 it->state = deque->state;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001435 it->counter = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001436 PyObject_GC_Track(it);
1437 return (PyObject *)it;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001438}
1439
1440static PyObject *
1441dequereviter_next(dequeiterobject *it)
1442{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001443 PyObject *item;
1444 if (it->counter == 0)
1445 return NULL;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001446
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001447 if (it->deque->state != it->state) {
1448 it->counter = 0;
1449 PyErr_SetString(PyExc_RuntimeError,
1450 "deque mutated during iteration");
1451 return NULL;
1452 }
1453 assert (!(it->b == it->deque->leftblock &&
1454 it->index < it->deque->leftindex));
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001456 item = it->b->data[it->index];
1457 it->index--;
1458 it->counter--;
1459 if (it->index == -1 && it->counter > 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -10001460 CHECK_NOT_END(it->b->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001461 it->b = it->b->leftlink;
1462 it->index = BLOCKLEN - 1;
1463 }
1464 Py_INCREF(item);
1465 return item;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001466}
1467
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001468static PyObject *
1469dequereviter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1470{
1471 Py_ssize_t i, index=0;
1472 PyObject *deque;
1473 dequeiterobject *it;
1474 if (!PyArg_ParseTuple(args, "O!|n", &deque_type, &deque, &index))
1475 return NULL;
1476 assert(type == &dequereviter_type);
1477
1478 it = (dequeiterobject*)deque_reviter((dequeobject *)deque);
1479 if (!it)
1480 return NULL;
1481 /* consume items from the queue */
1482 for(i=0; i<index; i++) {
1483 PyObject *item = dequereviter_next(it);
1484 if (item) {
1485 Py_DECREF(item);
1486 } else {
1487 if (it->counter) {
1488 Py_DECREF(it);
1489 return NULL;
1490 } else
1491 break;
1492 }
1493 }
1494 return (PyObject*)it;
1495}
1496
Martin v. Löwis59683e82008-06-13 07:50:45 +00001497static PyTypeObject dequereviter_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001498 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger87e69122015-03-02 23:32:02 -08001499 "_collections._deque_reverse_iterator", /* tp_name */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001500 sizeof(dequeiterobject), /* tp_basicsize */
1501 0, /* tp_itemsize */
1502 /* methods */
1503 (destructor)dequeiter_dealloc, /* tp_dealloc */
1504 0, /* tp_print */
1505 0, /* tp_getattr */
1506 0, /* tp_setattr */
1507 0, /* tp_reserved */
1508 0, /* tp_repr */
1509 0, /* tp_as_number */
1510 0, /* tp_as_sequence */
1511 0, /* tp_as_mapping */
1512 0, /* tp_hash */
1513 0, /* tp_call */
1514 0, /* tp_str */
1515 PyObject_GenericGetAttr, /* tp_getattro */
1516 0, /* tp_setattro */
1517 0, /* tp_as_buffer */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001518 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001519 0, /* tp_doc */
1520 (traverseproc)dequeiter_traverse, /* tp_traverse */
1521 0, /* tp_clear */
1522 0, /* tp_richcompare */
1523 0, /* tp_weaklistoffset */
1524 PyObject_SelfIter, /* tp_iter */
1525 (iternextfunc)dequereviter_next, /* tp_iternext */
1526 dequeiter_methods, /* tp_methods */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001527 0, /* tp_members */
1528 0, /* tp_getset */
1529 0, /* tp_base */
1530 0, /* tp_dict */
1531 0, /* tp_descr_get */
1532 0, /* tp_descr_set */
1533 0, /* tp_dictoffset */
1534 0, /* tp_init */
1535 0, /* tp_alloc */
1536 dequereviter_new, /* tp_new */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001537 0,
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001538};
1539
Guido van Rossum1968ad32006-02-25 22:38:04 +00001540/* defaultdict type *********************************************************/
1541
1542typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001543 PyDictObject dict;
1544 PyObject *default_factory;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001545} defdictobject;
1546
1547static PyTypeObject defdict_type; /* Forward */
1548
1549PyDoc_STRVAR(defdict_missing_doc,
1550"__missing__(key) # Called by __getitem__ for missing key; pseudo-code:\n\
Guido van Rossumd8faa362007-04-27 19:54:29 +00001551 if self.default_factory is None: raise KeyError((key,))\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00001552 self[key] = value = self.default_factory()\n\
1553 return value\n\
1554");
1555
1556static PyObject *
1557defdict_missing(defdictobject *dd, PyObject *key)
1558{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001559 PyObject *factory = dd->default_factory;
1560 PyObject *value;
1561 if (factory == NULL || factory == Py_None) {
1562 /* XXX Call dict.__missing__(key) */
1563 PyObject *tup;
1564 tup = PyTuple_Pack(1, key);
1565 if (!tup) return NULL;
1566 PyErr_SetObject(PyExc_KeyError, tup);
1567 Py_DECREF(tup);
1568 return NULL;
1569 }
1570 value = PyEval_CallObject(factory, NULL);
1571 if (value == NULL)
1572 return value;
1573 if (PyObject_SetItem((PyObject *)dd, key, value) < 0) {
1574 Py_DECREF(value);
1575 return NULL;
1576 }
1577 return value;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001578}
1579
1580PyDoc_STRVAR(defdict_copy_doc, "D.copy() -> a shallow copy of D.");
1581
1582static PyObject *
1583defdict_copy(defdictobject *dd)
1584{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001585 /* This calls the object's class. That only works for subclasses
1586 whose class constructor has the same signature. Subclasses that
1587 define a different constructor signature must override copy().
1588 */
Raymond Hettinger54628fa2009-08-04 19:16:39 +00001589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001590 if (dd->default_factory == NULL)
1591 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd), Py_None, dd, NULL);
1592 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd),
1593 dd->default_factory, dd, NULL);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001594}
1595
1596static PyObject *
1597defdict_reduce(defdictobject *dd)
1598{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001599 /* __reduce__ must return a 5-tuple as follows:
Guido van Rossum1968ad32006-02-25 22:38:04 +00001600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001601 - factory function
1602 - tuple of args for the factory function
1603 - additional state (here None)
1604 - sequence iterator (here None)
1605 - dictionary iterator (yielding successive (key, value) pairs
Guido van Rossum1968ad32006-02-25 22:38:04 +00001606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001607 This API is used by pickle.py and copy.py.
Guido van Rossum1968ad32006-02-25 22:38:04 +00001608
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001609 For this to be useful with pickle.py, the default_factory
1610 must be picklable; e.g., None, a built-in, or a global
1611 function in a module or package.
Guido van Rossum1968ad32006-02-25 22:38:04 +00001612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001613 Both shallow and deep copying are supported, but for deep
1614 copying, the default_factory must be deep-copyable; e.g. None,
1615 or a built-in (functions are not copyable at this time).
Guido van Rossum1968ad32006-02-25 22:38:04 +00001616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001617 This only works for subclasses as long as their constructor
1618 signature is compatible; the first argument must be the
1619 optional default_factory, defaulting to None.
1620 */
1621 PyObject *args;
1622 PyObject *items;
1623 PyObject *iter;
1624 PyObject *result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001625 _Py_IDENTIFIER(items);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001626
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001627 if (dd->default_factory == NULL || dd->default_factory == Py_None)
1628 args = PyTuple_New(0);
1629 else
1630 args = PyTuple_Pack(1, dd->default_factory);
1631 if (args == NULL)
1632 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001633 items = _PyObject_CallMethodId((PyObject *)dd, &PyId_items, "()");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001634 if (items == NULL) {
1635 Py_DECREF(args);
1636 return NULL;
1637 }
1638 iter = PyObject_GetIter(items);
1639 if (iter == NULL) {
1640 Py_DECREF(items);
1641 Py_DECREF(args);
1642 return NULL;
1643 }
1644 result = PyTuple_Pack(5, Py_TYPE(dd), args,
1645 Py_None, Py_None, iter);
1646 Py_DECREF(iter);
1647 Py_DECREF(items);
1648 Py_DECREF(args);
1649 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001650}
1651
1652static PyMethodDef defdict_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001653 {"__missing__", (PyCFunction)defdict_missing, METH_O,
1654 defdict_missing_doc},
1655 {"copy", (PyCFunction)defdict_copy, METH_NOARGS,
1656 defdict_copy_doc},
1657 {"__copy__", (PyCFunction)defdict_copy, METH_NOARGS,
1658 defdict_copy_doc},
1659 {"__reduce__", (PyCFunction)defdict_reduce, METH_NOARGS,
1660 reduce_doc},
1661 {NULL}
Guido van Rossum1968ad32006-02-25 22:38:04 +00001662};
1663
1664static PyMemberDef defdict_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001665 {"default_factory", T_OBJECT,
1666 offsetof(defdictobject, default_factory), 0,
1667 PyDoc_STR("Factory for default value called by __missing__().")},
1668 {NULL}
Guido van Rossum1968ad32006-02-25 22:38:04 +00001669};
1670
1671static void
1672defdict_dealloc(defdictobject *dd)
1673{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001674 Py_CLEAR(dd->default_factory);
1675 PyDict_Type.tp_dealloc((PyObject *)dd);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001676}
1677
Guido van Rossum1968ad32006-02-25 22:38:04 +00001678static PyObject *
1679defdict_repr(defdictobject *dd)
1680{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001681 PyObject *baserepr;
1682 PyObject *defrepr;
1683 PyObject *result;
1684 baserepr = PyDict_Type.tp_repr((PyObject *)dd);
1685 if (baserepr == NULL)
1686 return NULL;
1687 if (dd->default_factory == NULL)
1688 defrepr = PyUnicode_FromString("None");
1689 else
1690 {
1691 int status = Py_ReprEnter(dd->default_factory);
1692 if (status != 0) {
Antoine Pitrouf5f1fe02012-02-15 02:42:46 +01001693 if (status < 0) {
1694 Py_DECREF(baserepr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001695 return NULL;
Antoine Pitrouf5f1fe02012-02-15 02:42:46 +01001696 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001697 defrepr = PyUnicode_FromString("...");
1698 }
1699 else
1700 defrepr = PyObject_Repr(dd->default_factory);
1701 Py_ReprLeave(dd->default_factory);
1702 }
1703 if (defrepr == NULL) {
1704 Py_DECREF(baserepr);
1705 return NULL;
1706 }
1707 result = PyUnicode_FromFormat("defaultdict(%U, %U)",
1708 defrepr, baserepr);
1709 Py_DECREF(defrepr);
1710 Py_DECREF(baserepr);
1711 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001712}
1713
1714static int
1715defdict_traverse(PyObject *self, visitproc visit, void *arg)
1716{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001717 Py_VISIT(((defdictobject *)self)->default_factory);
1718 return PyDict_Type.tp_traverse(self, visit, arg);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001719}
1720
1721static int
1722defdict_tp_clear(defdictobject *dd)
1723{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001724 Py_CLEAR(dd->default_factory);
1725 return PyDict_Type.tp_clear((PyObject *)dd);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001726}
1727
1728static int
1729defdict_init(PyObject *self, PyObject *args, PyObject *kwds)
1730{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001731 defdictobject *dd = (defdictobject *)self;
1732 PyObject *olddefault = dd->default_factory;
1733 PyObject *newdefault = NULL;
1734 PyObject *newargs;
1735 int result;
1736 if (args == NULL || !PyTuple_Check(args))
1737 newargs = PyTuple_New(0);
1738 else {
1739 Py_ssize_t n = PyTuple_GET_SIZE(args);
1740 if (n > 0) {
1741 newdefault = PyTuple_GET_ITEM(args, 0);
1742 if (!PyCallable_Check(newdefault) && newdefault != Py_None) {
1743 PyErr_SetString(PyExc_TypeError,
1744 "first argument must be callable");
1745 return -1;
1746 }
1747 }
1748 newargs = PySequence_GetSlice(args, 1, n);
1749 }
1750 if (newargs == NULL)
1751 return -1;
1752 Py_XINCREF(newdefault);
1753 dd->default_factory = newdefault;
1754 result = PyDict_Type.tp_init(self, newargs, kwds);
1755 Py_DECREF(newargs);
1756 Py_XDECREF(olddefault);
1757 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001758}
1759
1760PyDoc_STRVAR(defdict_doc,
Benjamin Peterson9cb33b72014-01-13 23:56:05 -05001761"defaultdict(default_factory[, ...]) --> dict with default factory\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00001762\n\
1763The default factory is called without arguments to produce\n\
1764a new value when a key is not present, in __getitem__ only.\n\
1765A defaultdict compares equal to a dict with the same items.\n\
Benjamin Peterson9cb33b72014-01-13 23:56:05 -05001766All remaining arguments are treated the same as if they were\n\
1767passed to the dict constructor, including keyword arguments.\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00001768");
1769
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001770/* See comment in xxsubtype.c */
1771#define DEFERRED_ADDRESS(ADDR) 0
1772
Guido van Rossum1968ad32006-02-25 22:38:04 +00001773static PyTypeObject defdict_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001774 PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0)
1775 "collections.defaultdict", /* tp_name */
1776 sizeof(defdictobject), /* tp_basicsize */
1777 0, /* tp_itemsize */
1778 /* methods */
1779 (destructor)defdict_dealloc, /* tp_dealloc */
1780 0, /* tp_print */
1781 0, /* tp_getattr */
1782 0, /* tp_setattr */
1783 0, /* tp_reserved */
1784 (reprfunc)defdict_repr, /* tp_repr */
1785 0, /* tp_as_number */
1786 0, /* tp_as_sequence */
1787 0, /* tp_as_mapping */
1788 0, /* tp_hash */
1789 0, /* tp_call */
1790 0, /* tp_str */
1791 PyObject_GenericGetAttr, /* tp_getattro */
1792 0, /* tp_setattro */
1793 0, /* tp_as_buffer */
1794 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
1795 /* tp_flags */
1796 defdict_doc, /* tp_doc */
1797 defdict_traverse, /* tp_traverse */
1798 (inquiry)defdict_tp_clear, /* tp_clear */
1799 0, /* tp_richcompare */
1800 0, /* tp_weaklistoffset*/
1801 0, /* tp_iter */
1802 0, /* tp_iternext */
1803 defdict_methods, /* tp_methods */
1804 defdict_members, /* tp_members */
1805 0, /* tp_getset */
1806 DEFERRED_ADDRESS(&PyDict_Type), /* tp_base */
1807 0, /* tp_dict */
1808 0, /* tp_descr_get */
1809 0, /* tp_descr_set */
1810 0, /* tp_dictoffset */
1811 defdict_init, /* tp_init */
1812 PyType_GenericAlloc, /* tp_alloc */
1813 0, /* tp_new */
1814 PyObject_GC_Del, /* tp_free */
Guido van Rossum1968ad32006-02-25 22:38:04 +00001815};
1816
Raymond Hettinger96f34102010-12-15 16:30:37 +00001817/* helper function for Counter *********************************************/
1818
1819PyDoc_STRVAR(_count_elements_doc,
1820"_count_elements(mapping, iterable) -> None\n\
1821\n\
1822Count elements in the iterable, updating the mappping");
1823
1824static PyObject *
1825_count_elements(PyObject *self, PyObject *args)
1826{
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07001827 _Py_IDENTIFIER(get);
Raymond Hettinger2ff21902013-10-01 00:55:43 -07001828 _Py_IDENTIFIER(__setitem__);
Raymond Hettinger96f34102010-12-15 16:30:37 +00001829 PyObject *it, *iterable, *mapping, *oldval;
1830 PyObject *newval = NULL;
1831 PyObject *key = NULL;
Raymond Hettinger224c87d2013-10-01 21:36:09 -07001832 PyObject *zero = NULL;
Raymond Hettinger96f34102010-12-15 16:30:37 +00001833 PyObject *one = NULL;
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07001834 PyObject *bound_get = NULL;
1835 PyObject *mapping_get;
1836 PyObject *dict_get;
Raymond Hettinger2ff21902013-10-01 00:55:43 -07001837 PyObject *mapping_setitem;
Raymond Hettinger2ff21902013-10-01 00:55:43 -07001838 PyObject *dict_setitem;
Raymond Hettinger96f34102010-12-15 16:30:37 +00001839
1840 if (!PyArg_UnpackTuple(args, "_count_elements", 2, 2, &mapping, &iterable))
1841 return NULL;
1842
Raymond Hettinger96f34102010-12-15 16:30:37 +00001843 it = PyObject_GetIter(iterable);
1844 if (it == NULL)
1845 return NULL;
Raymond Hettinger426e0522011-01-03 02:12:02 +00001846
Raymond Hettinger96f34102010-12-15 16:30:37 +00001847 one = PyLong_FromLong(1);
Raymond Hettinger224c87d2013-10-01 21:36:09 -07001848 if (one == NULL)
1849 goto done;
Raymond Hettinger426e0522011-01-03 02:12:02 +00001850
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07001851 /* Only take the fast path when get() and __setitem__()
1852 * have not been overridden.
1853 */
1854 mapping_get = _PyType_LookupId(Py_TYPE(mapping), &PyId_get);
1855 dict_get = _PyType_LookupId(&PyDict_Type, &PyId_get);
Raymond Hettinger2ff21902013-10-01 00:55:43 -07001856 mapping_setitem = _PyType_LookupId(Py_TYPE(mapping), &PyId___setitem__);
1857 dict_setitem = _PyType_LookupId(&PyDict_Type, &PyId___setitem__);
1858
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07001859 if (mapping_get != NULL && mapping_get == dict_get &&
1860 mapping_setitem != NULL && mapping_setitem == dict_setitem) {
Raymond Hettinger426e0522011-01-03 02:12:02 +00001861 while (1) {
Raymond Hettinger507d9972014-05-18 21:32:40 +01001862 /* Fast path advantages:
1863 1. Eliminate double hashing
1864 (by re-using the same hash for both the get and set)
1865 2. Avoid argument overhead of PyObject_CallFunctionObjArgs
1866 (argument tuple creation and parsing)
1867 3. Avoid indirection through a bound method object
1868 (creates another argument tuple)
1869 4. Avoid initial increment from zero
1870 (reuse an existing one-object instead)
1871 */
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07001872 Py_hash_t hash;
1873
Raymond Hettinger426e0522011-01-03 02:12:02 +00001874 key = PyIter_Next(it);
Victor Stinnera154b5c2011-04-20 23:23:52 +02001875 if (key == NULL)
1876 break;
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07001877
1878 if (!PyUnicode_CheckExact(key) ||
1879 (hash = ((PyASCIIObject *) key)->hash) == -1)
1880 {
1881 hash = PyObject_Hash(key);
Raymond Hettingerda2850f2015-02-27 12:42:54 -08001882 if (hash == -1)
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07001883 goto done;
1884 }
1885
1886 oldval = _PyDict_GetItem_KnownHash(mapping, key, hash);
Raymond Hettinger426e0522011-01-03 02:12:02 +00001887 if (oldval == NULL) {
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07001888 if (_PyDict_SetItem_KnownHash(mapping, key, one, hash) == -1)
Raymond Hettinger507d9972014-05-18 21:32:40 +01001889 goto done;
Raymond Hettinger426e0522011-01-03 02:12:02 +00001890 } else {
1891 newval = PyNumber_Add(oldval, one);
1892 if (newval == NULL)
Raymond Hettinger507d9972014-05-18 21:32:40 +01001893 goto done;
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07001894 if (_PyDict_SetItem_KnownHash(mapping, key, newval, hash) == -1)
Raymond Hettinger507d9972014-05-18 21:32:40 +01001895 goto done;
Raymond Hettinger426e0522011-01-03 02:12:02 +00001896 Py_CLEAR(newval);
1897 }
1898 Py_DECREF(key);
Raymond Hettinger96f34102010-12-15 16:30:37 +00001899 }
Raymond Hettinger426e0522011-01-03 02:12:02 +00001900 } else {
Victor Stinnere7f516c2013-11-06 23:52:55 +01001901 bound_get = _PyObject_GetAttrId(mapping, &PyId_get);
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07001902 if (bound_get == NULL)
Raymond Hettinger224c87d2013-10-01 21:36:09 -07001903 goto done;
1904
1905 zero = PyLong_FromLong(0);
1906 if (zero == NULL)
1907 goto done;
1908
Raymond Hettinger426e0522011-01-03 02:12:02 +00001909 while (1) {
1910 key = PyIter_Next(it);
Victor Stinnera154b5c2011-04-20 23:23:52 +02001911 if (key == NULL)
1912 break;
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07001913 oldval = PyObject_CallFunctionObjArgs(bound_get, key, zero, NULL);
Raymond Hettinger224c87d2013-10-01 21:36:09 -07001914 if (oldval == NULL)
1915 break;
1916 newval = PyNumber_Add(oldval, one);
1917 Py_DECREF(oldval);
1918 if (newval == NULL)
1919 break;
Raymond Hettinger426e0522011-01-03 02:12:02 +00001920 if (PyObject_SetItem(mapping, key, newval) == -1)
Raymond Hettinger96f34102010-12-15 16:30:37 +00001921 break;
1922 Py_CLEAR(newval);
Raymond Hettinger426e0522011-01-03 02:12:02 +00001923 Py_DECREF(key);
Raymond Hettinger96f34102010-12-15 16:30:37 +00001924 }
Raymond Hettinger96f34102010-12-15 16:30:37 +00001925 }
Raymond Hettinger426e0522011-01-03 02:12:02 +00001926
Raymond Hettinger224c87d2013-10-01 21:36:09 -07001927done:
Raymond Hettinger96f34102010-12-15 16:30:37 +00001928 Py_DECREF(it);
1929 Py_XDECREF(key);
1930 Py_XDECREF(newval);
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07001931 Py_XDECREF(bound_get);
Raymond Hettinger224c87d2013-10-01 21:36:09 -07001932 Py_XDECREF(zero);
1933 Py_XDECREF(one);
Raymond Hettinger96f34102010-12-15 16:30:37 +00001934 if (PyErr_Occurred())
1935 return NULL;
1936 Py_RETURN_NONE;
1937}
1938
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001939/* module level code ********************************************************/
1940
1941PyDoc_STRVAR(module_doc,
Guido van Rossum1968ad32006-02-25 22:38:04 +00001942"High performance data structures.\n\
1943- deque: ordered collection accessible from endpoints only\n\
1944- defaultdict: dict subclass with a default value factory\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001945");
1946
Raymond Hettinger96f34102010-12-15 16:30:37 +00001947static struct PyMethodDef module_functions[] = {
1948 {"_count_elements", _count_elements, METH_VARARGS, _count_elements_doc},
1949 {NULL, NULL} /* sentinel */
1950};
Martin v. Löwis1a214512008-06-11 05:26:20 +00001951
1952static struct PyModuleDef _collectionsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001953 PyModuleDef_HEAD_INIT,
1954 "_collections",
1955 module_doc,
1956 -1,
Raymond Hettinger96f34102010-12-15 16:30:37 +00001957 module_functions,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001958 NULL,
1959 NULL,
1960 NULL,
1961 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001962};
1963
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001964PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001965PyInit__collections(void)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001966{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001967 PyObject *m;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001969 m = PyModule_Create(&_collectionsmodule);
1970 if (m == NULL)
1971 return NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001972
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001973 if (PyType_Ready(&deque_type) < 0)
1974 return NULL;
1975 Py_INCREF(&deque_type);
1976 PyModule_AddObject(m, "deque", (PyObject *)&deque_type);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001977
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001978 defdict_type.tp_base = &PyDict_Type;
1979 if (PyType_Ready(&defdict_type) < 0)
1980 return NULL;
1981 Py_INCREF(&defdict_type);
1982 PyModule_AddObject(m, "defaultdict", (PyObject *)&defdict_type);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001983
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001984 if (PyType_Ready(&dequeiter_type) < 0)
1985 return NULL;
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001986 Py_INCREF(&dequeiter_type);
1987 PyModule_AddObject(m, "_deque_iterator", (PyObject *)&dequeiter_type);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001988
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001989 if (PyType_Ready(&dequereviter_type) < 0)
1990 return NULL;
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001991 Py_INCREF(&dequereviter_type);
1992 PyModule_AddObject(m, "_deque_reverse_iterator", (PyObject *)&dequereviter_type);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001994 return m;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001995}