blob: b8316279ac5e010d2d46b55f1cdd0a88bfedd6a9 [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;
Raymond Hettinger0f6f9472015-03-21 01:42:10 -070067 PyObject *weakreflist;
Raymond Hettinger30c90742015-03-02 22:31:35 -080068} 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;
Raymond Hettinger6921c132015-03-21 02:03:40 -0700637 if (!_deque_rotate(deque, n))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 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
Raymond Hettinger39dadf72015-03-20 16:38:56 -0700727static int
728deque_contains(dequeobject *deque, PyObject *v)
729{
730 block *b = deque->leftblock;
731 Py_ssize_t index = deque->leftindex;
732 Py_ssize_t n = Py_SIZE(deque);
733 Py_ssize_t i;
734 size_t start_state = deque->state;
735 PyObject *item;
736 int cmp;
737
738 for (i=0 ; i<n ; i++) {
739 CHECK_NOT_END(b);
740 item = b->data[index];
741 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
742 if (cmp) {
743 return cmp;
744 }
745 if (start_state != deque->state) {
746 PyErr_SetString(PyExc_RuntimeError,
747 "deque mutated during iteration");
748 return -1;
749 }
750 index++;
751 if (index == BLOCKLEN) {
752 b = b->rightlink;
753 index = 0;
754 }
755 }
756 return 0;
757}
758
Martin v. Löwis18e16552006-02-15 17:27:45 +0000759static Py_ssize_t
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000760deque_len(dequeobject *deque)
761{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000762 return Py_SIZE(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000763}
764
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000765static PyObject *
Raymond Hettinger32ea1652015-03-21 01:37:37 -0700766deque_index(dequeobject *deque, PyObject *args)
767{
768 Py_ssize_t i, start=0, stop=Py_SIZE(deque);
769 PyObject *v, *item;
770 block *b = deque->leftblock;
771 Py_ssize_t index = deque->leftindex;
772 size_t start_state = deque->state;
773
774 if (!PyArg_ParseTuple(args, "O|O&O&:index", &v,
775 _PyEval_SliceIndex, &start,
776 _PyEval_SliceIndex, &stop))
777 return NULL;
778 if (start < 0) {
779 start += Py_SIZE(deque);
780 if (start < 0)
781 start = 0;
782 }
783 if (stop < 0) {
784 stop += Py_SIZE(deque);
785 if (stop < 0)
786 stop = 0;
787 }
788
789 for (i=0 ; i<stop ; i++) {
790 if (i >= start) {
791 int cmp;
792 CHECK_NOT_END(b);
793 item = b->data[index];
794 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
795 if (cmp > 0)
796 return PyLong_FromSsize_t(i);
797 else if (cmp < 0)
798 return NULL;
799 if (start_state != deque->state) {
800 PyErr_SetString(PyExc_RuntimeError,
801 "deque mutated during iteration");
802 return NULL;
803 }
804 }
805 index++;
806 if (index == BLOCKLEN) {
807 b = b->rightlink;
808 index = 0;
809 }
810 }
811 PyErr_Format(PyExc_ValueError, "%R is not in deque", v);
812 return NULL;
813}
814
815PyDoc_STRVAR(index_doc,
816"D.index(value, [start, [stop]]) -> integer -- return first index of value.\n"
817"Raises ValueError if the value is not present.");
818
819static PyObject *
820deque_insert(dequeobject *deque, PyObject *args)
821{
822 Py_ssize_t index;
823 Py_ssize_t n = Py_SIZE(deque);
824 PyObject *value;
825 PyObject *rv;
826
827 if (!PyArg_ParseTuple(args, "nO:insert", &index, &value))
828 return NULL;
829 if (index >= n)
830 return deque_append(deque, value);
831 if (index <= -n || index == 0)
832 return deque_appendleft(deque, value);
833 if (_deque_rotate(deque, -index))
834 return NULL;
835 if (index < 0)
836 rv = deque_append(deque, value);
837 else
838 rv = deque_appendleft(deque, value);
839 if (rv == NULL)
840 return NULL;
841 Py_DECREF(rv);
842 if (_deque_rotate(deque, index))
843 return NULL;
844 Py_RETURN_NONE;
845}
846
847PyDoc_STRVAR(insert_doc,
848"D.insert(index, object) -- insert object before index");
849
850static PyObject *
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000851deque_remove(dequeobject *deque, PyObject *value)
852{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000853 Py_ssize_t i, n=Py_SIZE(deque);
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 for (i=0 ; i<n ; i++) {
856 PyObject *item = deque->leftblock->data[deque->leftindex];
857 int cmp = PyObject_RichCompareBool(item, value, Py_EQ);
Raymond Hettingerd73202c2005-03-19 00:00:51 +0000858
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000859 if (Py_SIZE(deque) != n) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000860 PyErr_SetString(PyExc_IndexError,
861 "deque mutated during remove().");
862 return NULL;
863 }
864 if (cmp > 0) {
865 PyObject *tgt = deque_popleft(deque, NULL);
866 assert (tgt != NULL);
Raymond Hettinger6921c132015-03-21 02:03:40 -0700867 if (_deque_rotate(deque, i))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 return NULL;
Raymond Hettingerac13ad62015-03-21 01:53:16 -0700869 Py_DECREF(tgt);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000870 Py_RETURN_NONE;
871 }
872 else if (cmp < 0) {
873 _deque_rotate(deque, i);
874 return NULL;
875 }
876 _deque_rotate(deque, -1);
877 }
878 PyErr_SetString(PyExc_ValueError, "deque.remove(x): x not in deque");
879 return NULL;
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000880}
881
882PyDoc_STRVAR(remove_doc,
883"D.remove(value) -- remove first occurrence of value.");
884
Benjamin Peterson0e5c48a2013-01-12 21:22:18 -0500885static void
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000886deque_clear(dequeobject *deque)
887{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000888 PyObject *item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000889
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000890 while (Py_SIZE(deque)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000891 item = deque_pop(deque, NULL);
892 assert (item != NULL);
893 Py_DECREF(item);
894 }
Raymond Hettinger87e69122015-03-02 23:32:02 -0800895 assert(deque->leftblock == deque->rightblock);
896 assert(deque->leftindex - 1 == deque->rightindex);
897 assert(Py_SIZE(deque) == 0);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000898}
899
Raymond Hettinger3c186ba2015-03-02 21:45:02 -0800900static int
901valid_index(Py_ssize_t i, Py_ssize_t limit)
902{
903 /* The cast to size_t let us use just a single comparison
904 to check whether i is in the range: 0 <= i < limit */
905 return (size_t) i < (size_t) limit;
906}
907
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000908static PyObject *
Benjamin Petersond6313712008-07-31 16:23:04 +0000909deque_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000910{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000911 block *b;
912 PyObject *item;
913 Py_ssize_t n, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000914
Raymond Hettinger3c186ba2015-03-02 21:45:02 -0800915 if (!valid_index(i, Py_SIZE(deque))) {
916 PyErr_SetString(PyExc_IndexError, "deque index out of range");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000917 return NULL;
918 }
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 if (i == 0) {
921 i = deque->leftindex;
922 b = deque->leftblock;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000923 } else if (i == Py_SIZE(deque) - 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 i = deque->rightindex;
925 b = deque->rightblock;
926 } else {
927 i += deque->leftindex;
Raymond Hettingerc2083082015-02-28 23:29:16 -0800928 n = (Py_ssize_t)((size_t) i / BLOCKLEN);
929 i = (Py_ssize_t)((size_t) i % BLOCKLEN);
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000930 if (index < (Py_SIZE(deque) >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 b = deque->leftblock;
932 while (n--)
933 b = b->rightlink;
934 } else {
Raymond Hettinger63d1ff22015-02-28 07:41:30 -0800935 n = (Py_ssize_t)(
Raymond Hettingerc2083082015-02-28 23:29:16 -0800936 ((size_t)(deque->leftindex + Py_SIZE(deque) - 1))
Raymond Hettinger63d1ff22015-02-28 07:41:30 -0800937 / BLOCKLEN - n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 b = deque->rightblock;
939 while (n--)
940 b = b->leftlink;
941 }
942 }
943 item = b->data[i];
944 Py_INCREF(item);
945 return item;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000946}
947
Raymond Hettinger616f4f62004-06-26 04:42:06 +0000948/* delitem() implemented in terms of rotate for simplicity and reasonable
949 performance near the end points. If for some reason this method becomes
Tim Peters1065f752004-10-01 01:03:29 +0000950 popular, it is not hard to re-implement this using direct data movement
Raymond Hettinger616f4f62004-06-26 04:42:06 +0000951 (similar to code in list slice assignment) and achieve a two or threefold
952 performance boost.
953*/
954
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000955static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000956deque_del_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000957{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000958 PyObject *item;
Raymond Hettingerac13ad62015-03-21 01:53:16 -0700959 int rv;
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000960
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000961 assert (i >= 0 && i < Py_SIZE(deque));
Raymond Hettinger6921c132015-03-21 02:03:40 -0700962 if (_deque_rotate(deque, -i))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000963 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000964 item = deque_popleft(deque, NULL);
Raymond Hettingerac13ad62015-03-21 01:53:16 -0700965 rv = _deque_rotate(deque, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 assert (item != NULL);
967 Py_DECREF(item);
Raymond Hettingerac13ad62015-03-21 01:53:16 -0700968 return rv;
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000969}
970
971static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000972deque_ass_item(dequeobject *deque, Py_ssize_t i, PyObject *v)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000973{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 PyObject *old_value;
975 block *b;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000976 Py_ssize_t n, len=Py_SIZE(deque), halflen=(len+1)>>1, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000977
Raymond Hettinger3c186ba2015-03-02 21:45:02 -0800978 if (!valid_index(i, len)) {
979 PyErr_SetString(PyExc_IndexError, "deque index out of range");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000980 return -1;
981 }
982 if (v == NULL)
983 return deque_del_item(deque, i);
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000984
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000985 i += deque->leftindex;
Raymond Hettingerc2083082015-02-28 23:29:16 -0800986 n = (Py_ssize_t)((size_t) i / BLOCKLEN);
987 i = (Py_ssize_t)((size_t) i % BLOCKLEN);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000988 if (index <= halflen) {
989 b = deque->leftblock;
990 while (n--)
991 b = b->rightlink;
992 } else {
Raymond Hettingera473b9d2015-02-28 17:49:47 -0800993 n = (Py_ssize_t)(
Raymond Hettingerc2083082015-02-28 23:29:16 -0800994 ((size_t)(deque->leftindex + Py_SIZE(deque) - 1))
Raymond Hettingera473b9d2015-02-28 17:49:47 -0800995 / BLOCKLEN - n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000996 b = deque->rightblock;
997 while (n--)
998 b = b->leftlink;
999 }
1000 Py_INCREF(v);
1001 old_value = b->data[i];
1002 b->data[i] = v;
1003 Py_DECREF(old_value);
1004 return 0;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001005}
1006
1007static PyObject *
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001008deque_clearmethod(dequeobject *deque)
1009{
Benjamin Peterson0e5c48a2013-01-12 21:22:18 -05001010 deque_clear(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001011 Py_RETURN_NONE;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001012}
1013
1014PyDoc_STRVAR(clear_doc, "Remove all elements from the deque.");
1015
1016static void
1017deque_dealloc(dequeobject *deque)
1018{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 PyObject_GC_UnTrack(deque);
1020 if (deque->weakreflist != NULL)
1021 PyObject_ClearWeakRefs((PyObject *) deque);
1022 if (deque->leftblock != NULL) {
1023 deque_clear(deque);
1024 assert(deque->leftblock != NULL);
1025 freeblock(deque->leftblock);
1026 }
1027 deque->leftblock = NULL;
1028 deque->rightblock = NULL;
1029 Py_TYPE(deque)->tp_free(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001030}
1031
1032static int
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001033deque_traverse(dequeobject *deque, visitproc visit, void *arg)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001034{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001035 block *b;
1036 PyObject *item;
1037 Py_ssize_t index;
1038 Py_ssize_t indexlo = deque->leftindex;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001039
Raymond Hettinger5bfa8672013-07-06 11:58:09 -10001040 for (b = deque->leftblock; b != deque->rightblock; b = b->rightlink) {
1041 for (index = indexlo; index < BLOCKLEN ; index++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 item = b->data[index];
1043 Py_VISIT(item);
1044 }
1045 indexlo = 0;
1046 }
Raymond Hettinger5bfa8672013-07-06 11:58:09 -10001047 for (index = indexlo; index <= deque->rightindex; index++) {
1048 item = b->data[index];
1049 Py_VISIT(item);
1050 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001051 return 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001052}
1053
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001054static PyObject *
1055deque_copy(PyObject *deque)
1056{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001057 if (((dequeobject *)deque)->maxlen == -1)
1058 return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "O", deque, NULL);
1059 else
1060 return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "Oi",
1061 deque, ((dequeobject *)deque)->maxlen, NULL);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001062}
1063
1064PyDoc_STRVAR(copy_doc, "Return a shallow copy of a deque.");
1065
1066static PyObject *
1067deque_reduce(dequeobject *deque)
1068{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001069 PyObject *dict, *result, *aslist;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001070 _Py_IDENTIFIER(__dict__);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001071
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001072 dict = _PyObject_GetAttrId((PyObject *)deque, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 if (dict == NULL)
1074 PyErr_Clear();
1075 aslist = PySequence_List((PyObject *)deque);
1076 if (aslist == NULL) {
1077 Py_XDECREF(dict);
1078 return NULL;
1079 }
1080 if (dict == NULL) {
1081 if (deque->maxlen == -1)
1082 result = Py_BuildValue("O(O)", Py_TYPE(deque), aslist);
1083 else
1084 result = Py_BuildValue("O(On)", Py_TYPE(deque), aslist, deque->maxlen);
1085 } else {
1086 if (deque->maxlen == -1)
1087 result = Py_BuildValue("O(OO)O", Py_TYPE(deque), aslist, Py_None, dict);
1088 else
1089 result = Py_BuildValue("O(On)O", Py_TYPE(deque), aslist, deque->maxlen, dict);
1090 }
1091 Py_XDECREF(dict);
1092 Py_DECREF(aslist);
1093 return result;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001094}
1095
1096PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
1097
1098static PyObject *
1099deque_repr(PyObject *deque)
1100{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001101 PyObject *aslist, *result;
1102 int i;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001104 i = Py_ReprEnter(deque);
1105 if (i != 0) {
1106 if (i < 0)
1107 return NULL;
1108 return PyUnicode_FromString("[...]");
1109 }
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001111 aslist = PySequence_List(deque);
1112 if (aslist == NULL) {
1113 Py_ReprLeave(deque);
1114 return NULL;
1115 }
1116 if (((dequeobject *)deque)->maxlen != -1)
Benjamin Petersona786b022008-08-25 21:05:21 +00001117
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001118 result = PyUnicode_FromFormat("deque(%R, maxlen=%zd)",
1119 aslist, ((dequeobject *)deque)->maxlen);
1120 else
1121 result = PyUnicode_FromFormat("deque(%R)", aslist);
1122 Py_DECREF(aslist);
1123 Py_ReprLeave(deque);
1124 return result;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001125}
1126
Raymond Hettinger738ec902004-02-29 02:15:56 +00001127static PyObject *
1128deque_richcompare(PyObject *v, PyObject *w, int op)
1129{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001130 PyObject *it1=NULL, *it2=NULL, *x, *y;
1131 Py_ssize_t vs, ws;
1132 int b, cmp=-1;
Raymond Hettinger738ec902004-02-29 02:15:56 +00001133
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001134 if (!PyObject_TypeCheck(v, &deque_type) ||
1135 !PyObject_TypeCheck(w, &deque_type)) {
Brian Curtindfc80e32011-08-10 20:28:54 -05001136 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001137 }
Raymond Hettinger738ec902004-02-29 02:15:56 +00001138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001139 /* Shortcuts */
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001140 vs = Py_SIZE((dequeobject *)v);
1141 ws = Py_SIZE((dequeobject *)w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142 if (op == Py_EQ) {
1143 if (v == w)
1144 Py_RETURN_TRUE;
1145 if (vs != ws)
1146 Py_RETURN_FALSE;
1147 }
1148 if (op == Py_NE) {
1149 if (v == w)
1150 Py_RETURN_FALSE;
1151 if (vs != ws)
1152 Py_RETURN_TRUE;
1153 }
Raymond Hettinger738ec902004-02-29 02:15:56 +00001154
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001155 /* Search for the first index where items are different */
1156 it1 = PyObject_GetIter(v);
1157 if (it1 == NULL)
1158 goto done;
1159 it2 = PyObject_GetIter(w);
1160 if (it2 == NULL)
1161 goto done;
1162 for (;;) {
1163 x = PyIter_Next(it1);
1164 if (x == NULL && PyErr_Occurred())
1165 goto done;
1166 y = PyIter_Next(it2);
1167 if (x == NULL || y == NULL)
1168 break;
1169 b = PyObject_RichCompareBool(x, y, Py_EQ);
1170 if (b == 0) {
1171 cmp = PyObject_RichCompareBool(x, y, op);
1172 Py_DECREF(x);
1173 Py_DECREF(y);
1174 goto done;
1175 }
1176 Py_DECREF(x);
1177 Py_DECREF(y);
1178 if (b == -1)
1179 goto done;
1180 }
1181 /* We reached the end of one deque or both */
1182 Py_XDECREF(x);
1183 Py_XDECREF(y);
1184 if (PyErr_Occurred())
1185 goto done;
1186 switch (op) {
1187 case Py_LT: cmp = y != NULL; break; /* if w was longer */
1188 case Py_LE: cmp = x == NULL; break; /* if v was not longer */
1189 case Py_EQ: cmp = x == y; break; /* if we reached the end of both */
1190 case Py_NE: cmp = x != y; break; /* if one deque continues */
1191 case Py_GT: cmp = x != NULL; break; /* if v was longer */
1192 case Py_GE: cmp = y == NULL; break; /* if w was not longer */
1193 }
Tim Peters1065f752004-10-01 01:03:29 +00001194
Raymond Hettinger738ec902004-02-29 02:15:56 +00001195done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001196 Py_XDECREF(it1);
1197 Py_XDECREF(it2);
1198 if (cmp == 1)
1199 Py_RETURN_TRUE;
1200 if (cmp == 0)
1201 Py_RETURN_FALSE;
1202 return NULL;
Raymond Hettinger738ec902004-02-29 02:15:56 +00001203}
1204
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001205static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001206deque_init(dequeobject *deque, PyObject *args, PyObject *kwdargs)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001207{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001208 PyObject *iterable = NULL;
1209 PyObject *maxlenobj = NULL;
1210 Py_ssize_t maxlen = -1;
1211 char *kwlist[] = {"iterable", "maxlen", 0};
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 if (!PyArg_ParseTupleAndKeywords(args, kwdargs, "|OO:deque", kwlist, &iterable, &maxlenobj))
1214 return -1;
1215 if (maxlenobj != NULL && maxlenobj != Py_None) {
1216 maxlen = PyLong_AsSsize_t(maxlenobj);
1217 if (maxlen == -1 && PyErr_Occurred())
1218 return -1;
1219 if (maxlen < 0) {
1220 PyErr_SetString(PyExc_ValueError, "maxlen must be non-negative");
1221 return -1;
1222 }
1223 }
1224 deque->maxlen = maxlen;
1225 deque_clear(deque);
1226 if (iterable != NULL) {
1227 PyObject *rv = deque_extend(deque, iterable);
1228 if (rv == NULL)
1229 return -1;
1230 Py_DECREF(rv);
1231 }
1232 return 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001233}
1234
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001235static PyObject *
Jesus Cea16e2fca2012-08-03 14:49:42 +02001236deque_sizeof(dequeobject *deque, void *unused)
1237{
1238 Py_ssize_t res;
1239 Py_ssize_t blocks;
1240
1241 res = sizeof(dequeobject);
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001242 blocks = (deque->leftindex + Py_SIZE(deque) + BLOCKLEN - 1) / BLOCKLEN;
1243 assert(deque->leftindex + Py_SIZE(deque) - 1 ==
Jesus Cea16e2fca2012-08-03 14:49:42 +02001244 (blocks - 1) * BLOCKLEN + deque->rightindex);
1245 res += blocks * sizeof(block);
1246 return PyLong_FromSsize_t(res);
1247}
1248
1249PyDoc_STRVAR(sizeof_doc,
1250"D.__sizeof__() -- size of D in memory, in bytes");
1251
1252static PyObject *
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001253deque_get_maxlen(dequeobject *deque)
1254{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001255 if (deque->maxlen == -1)
1256 Py_RETURN_NONE;
1257 return PyLong_FromSsize_t(deque->maxlen);
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001258}
1259
1260static PyGetSetDef deque_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001261 {"maxlen", (getter)deque_get_maxlen, (setter)NULL,
1262 "maximum size of a deque or None if unbounded"},
1263 {0}
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001264};
1265
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001266static PySequenceMethods deque_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001267 (lenfunc)deque_len, /* sq_length */
1268 0, /* sq_concat */
1269 0, /* sq_repeat */
1270 (ssizeargfunc)deque_item, /* sq_item */
1271 0, /* sq_slice */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001272 (ssizeobjargproc)deque_ass_item, /* sq_ass_item */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001273 0, /* sq_ass_slice */
Raymond Hettinger39dadf72015-03-20 16:38:56 -07001274 (objobjproc)deque_contains, /* sq_contains */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001275 (binaryfunc)deque_inplace_concat, /* sq_inplace_concat */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001276 0, /* sq_inplace_repeat */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001277};
1278
1279/* deque object ********************************************************/
1280
1281static PyObject *deque_iter(dequeobject *deque);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001282static PyObject *deque_reviter(dequeobject *deque);
Tim Peters1065f752004-10-01 01:03:29 +00001283PyDoc_STRVAR(reversed_doc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001284 "D.__reversed__() -- return a reverse iterator over the deque");
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001285
1286static PyMethodDef deque_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001287 {"append", (PyCFunction)deque_append,
1288 METH_O, append_doc},
1289 {"appendleft", (PyCFunction)deque_appendleft,
1290 METH_O, appendleft_doc},
1291 {"clear", (PyCFunction)deque_clearmethod,
1292 METH_NOARGS, clear_doc},
1293 {"__copy__", (PyCFunction)deque_copy,
1294 METH_NOARGS, copy_doc},
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001295 {"copy", (PyCFunction)deque_copy,
1296 METH_NOARGS, copy_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001297 {"count", (PyCFunction)deque_count,
Raymond Hettinger0f6f9472015-03-21 01:42:10 -07001298 METH_O, count_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001299 {"extend", (PyCFunction)deque_extend,
1300 METH_O, extend_doc},
1301 {"extendleft", (PyCFunction)deque_extendleft,
1302 METH_O, extendleft_doc},
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001303 {"index", (PyCFunction)deque_index,
1304 METH_VARARGS, index_doc},
1305 {"insert", (PyCFunction)deque_insert,
1306 METH_VARARGS, insert_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001307 {"pop", (PyCFunction)deque_pop,
1308 METH_NOARGS, pop_doc},
1309 {"popleft", (PyCFunction)deque_popleft,
1310 METH_NOARGS, popleft_doc},
Raymond Hettinger0f6f9472015-03-21 01:42:10 -07001311 {"__reduce__", (PyCFunction)deque_reduce,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001312 METH_NOARGS, reduce_doc},
1313 {"remove", (PyCFunction)deque_remove,
1314 METH_O, remove_doc},
1315 {"__reversed__", (PyCFunction)deque_reviter,
1316 METH_NOARGS, reversed_doc},
1317 {"reverse", (PyCFunction)deque_reverse,
1318 METH_NOARGS, reverse_doc},
1319 {"rotate", (PyCFunction)deque_rotate,
Jesus Cea16e2fca2012-08-03 14:49:42 +02001320 METH_VARARGS, rotate_doc},
1321 {"__sizeof__", (PyCFunction)deque_sizeof,
1322 METH_NOARGS, sizeof_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001323 {NULL, NULL} /* sentinel */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001324};
1325
1326PyDoc_STRVAR(deque_doc,
Andrew Svetlov6a5c7c32012-10-31 11:50:40 +02001327"deque([iterable[, maxlen]]) --> deque object\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001328\n\
Raymond Hettinger49747052011-03-29 17:36:31 -07001329Build an ordered collection with optimized access from its endpoints.");
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001330
Neal Norwitz87f10132004-02-29 15:40:53 +00001331static PyTypeObject deque_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001332 PyVarObject_HEAD_INIT(NULL, 0)
1333 "collections.deque", /* tp_name */
1334 sizeof(dequeobject), /* tp_basicsize */
1335 0, /* tp_itemsize */
1336 /* methods */
1337 (destructor)deque_dealloc, /* tp_dealloc */
1338 0, /* tp_print */
1339 0, /* tp_getattr */
1340 0, /* tp_setattr */
1341 0, /* tp_reserved */
1342 deque_repr, /* tp_repr */
1343 0, /* tp_as_number */
1344 &deque_as_sequence, /* tp_as_sequence */
1345 0, /* tp_as_mapping */
Georg Brandlf038b322010-10-18 07:35:09 +00001346 PyObject_HashNotImplemented, /* tp_hash */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001347 0, /* tp_call */
1348 0, /* tp_str */
1349 PyObject_GenericGetAttr, /* tp_getattro */
1350 0, /* tp_setattro */
1351 0, /* tp_as_buffer */
1352 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
Georg Brandlf038b322010-10-18 07:35:09 +00001353 /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001354 deque_doc, /* tp_doc */
1355 (traverseproc)deque_traverse, /* tp_traverse */
1356 (inquiry)deque_clear, /* tp_clear */
1357 (richcmpfunc)deque_richcompare, /* tp_richcompare */
Georg Brandlf038b322010-10-18 07:35:09 +00001358 offsetof(dequeobject, weakreflist), /* tp_weaklistoffset*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001359 (getiterfunc)deque_iter, /* tp_iter */
1360 0, /* tp_iternext */
1361 deque_methods, /* tp_methods */
1362 0, /* tp_members */
Georg Brandlf038b322010-10-18 07:35:09 +00001363 deque_getset, /* tp_getset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001364 0, /* tp_base */
1365 0, /* tp_dict */
1366 0, /* tp_descr_get */
1367 0, /* tp_descr_set */
1368 0, /* tp_dictoffset */
1369 (initproc)deque_init, /* tp_init */
1370 PyType_GenericAlloc, /* tp_alloc */
1371 deque_new, /* tp_new */
1372 PyObject_GC_Del, /* tp_free */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001373};
1374
1375/*********************** Deque Iterator **************************/
1376
1377typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001378 PyObject_HEAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001379 block *b;
Raymond Hettinger87e69122015-03-02 23:32:02 -08001380 Py_ssize_t index;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001381 dequeobject *deque;
Raymond Hettingerf9d9c792015-03-02 22:47:46 -08001382 size_t state; /* state when the iterator is created */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001383 Py_ssize_t counter; /* number of items remaining for iteration */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001384} dequeiterobject;
1385
Martin v. Löwis59683e82008-06-13 07:50:45 +00001386static PyTypeObject dequeiter_type;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001387
1388static PyObject *
1389deque_iter(dequeobject *deque)
1390{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001391 dequeiterobject *it;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001393 it = PyObject_GC_New(dequeiterobject, &dequeiter_type);
1394 if (it == NULL)
1395 return NULL;
1396 it->b = deque->leftblock;
1397 it->index = deque->leftindex;
1398 Py_INCREF(deque);
1399 it->deque = deque;
1400 it->state = deque->state;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001401 it->counter = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001402 PyObject_GC_Track(it);
1403 return (PyObject *)it;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001404}
1405
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001406static int
1407dequeiter_traverse(dequeiterobject *dio, visitproc visit, void *arg)
1408{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001409 Py_VISIT(dio->deque);
1410 return 0;
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001411}
1412
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001413static void
1414dequeiter_dealloc(dequeiterobject *dio)
1415{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001416 Py_XDECREF(dio->deque);
1417 PyObject_GC_Del(dio);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001418}
1419
1420static PyObject *
1421dequeiter_next(dequeiterobject *it)
1422{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001423 PyObject *item;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001425 if (it->deque->state != it->state) {
1426 it->counter = 0;
1427 PyErr_SetString(PyExc_RuntimeError,
1428 "deque mutated during iteration");
1429 return NULL;
1430 }
1431 if (it->counter == 0)
1432 return NULL;
1433 assert (!(it->b == it->deque->rightblock &&
1434 it->index > it->deque->rightindex));
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001436 item = it->b->data[it->index];
1437 it->index++;
1438 it->counter--;
1439 if (it->index == BLOCKLEN && it->counter > 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -10001440 CHECK_NOT_END(it->b->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001441 it->b = it->b->rightlink;
1442 it->index = 0;
1443 }
1444 Py_INCREF(item);
1445 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001446}
1447
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001448static PyObject *
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001449dequeiter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1450{
1451 Py_ssize_t i, index=0;
1452 PyObject *deque;
1453 dequeiterobject *it;
1454 if (!PyArg_ParseTuple(args, "O!|n", &deque_type, &deque, &index))
1455 return NULL;
1456 assert(type == &dequeiter_type);
1457
1458 it = (dequeiterobject*)deque_iter((dequeobject *)deque);
1459 if (!it)
1460 return NULL;
1461 /* consume items from the queue */
1462 for(i=0; i<index; i++) {
1463 PyObject *item = dequeiter_next(it);
1464 if (item) {
1465 Py_DECREF(item);
1466 } else {
1467 if (it->counter) {
1468 Py_DECREF(it);
1469 return NULL;
1470 } else
1471 break;
1472 }
1473 }
1474 return (PyObject*)it;
1475}
1476
1477static PyObject *
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001478dequeiter_len(dequeiterobject *it)
1479{
Antoine Pitrou554f3342010-08-17 18:30:06 +00001480 return PyLong_FromSsize_t(it->counter);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001481}
1482
Armin Rigof5b3e362006-02-11 21:32:43 +00001483PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001484
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001485static PyObject *
1486dequeiter_reduce(dequeiterobject *it)
1487{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001488 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 +00001489}
1490
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001491static PyMethodDef dequeiter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001492 {"__length_hint__", (PyCFunction)dequeiter_len, METH_NOARGS, length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001493 {"__reduce__", (PyCFunction)dequeiter_reduce, METH_NOARGS, reduce_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001494 {NULL, NULL} /* sentinel */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001495};
1496
Martin v. Löwis59683e82008-06-13 07:50:45 +00001497static PyTypeObject dequeiter_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001498 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger87e69122015-03-02 23:32:02 -08001499 "_collections._deque_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)dequeiter_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 dequeiter_new, /* tp_new */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001537 0,
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001538};
1539
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001540/*********************** Deque Reverse Iterator **************************/
1541
Martin v. Löwis59683e82008-06-13 07:50:45 +00001542static PyTypeObject dequereviter_type;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001543
1544static PyObject *
1545deque_reviter(dequeobject *deque)
1546{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001547 dequeiterobject *it;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001549 it = PyObject_GC_New(dequeiterobject, &dequereviter_type);
1550 if (it == NULL)
1551 return NULL;
1552 it->b = deque->rightblock;
1553 it->index = deque->rightindex;
1554 Py_INCREF(deque);
1555 it->deque = deque;
1556 it->state = deque->state;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001557 it->counter = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001558 PyObject_GC_Track(it);
1559 return (PyObject *)it;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001560}
1561
1562static PyObject *
1563dequereviter_next(dequeiterobject *it)
1564{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001565 PyObject *item;
1566 if (it->counter == 0)
1567 return NULL;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001568
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001569 if (it->deque->state != it->state) {
1570 it->counter = 0;
1571 PyErr_SetString(PyExc_RuntimeError,
1572 "deque mutated during iteration");
1573 return NULL;
1574 }
1575 assert (!(it->b == it->deque->leftblock &&
1576 it->index < it->deque->leftindex));
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001578 item = it->b->data[it->index];
1579 it->index--;
1580 it->counter--;
1581 if (it->index == -1 && it->counter > 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -10001582 CHECK_NOT_END(it->b->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001583 it->b = it->b->leftlink;
1584 it->index = BLOCKLEN - 1;
1585 }
1586 Py_INCREF(item);
1587 return item;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001588}
1589
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001590static PyObject *
1591dequereviter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1592{
1593 Py_ssize_t i, index=0;
1594 PyObject *deque;
1595 dequeiterobject *it;
1596 if (!PyArg_ParseTuple(args, "O!|n", &deque_type, &deque, &index))
1597 return NULL;
1598 assert(type == &dequereviter_type);
1599
1600 it = (dequeiterobject*)deque_reviter((dequeobject *)deque);
1601 if (!it)
1602 return NULL;
1603 /* consume items from the queue */
1604 for(i=0; i<index; i++) {
1605 PyObject *item = dequereviter_next(it);
1606 if (item) {
1607 Py_DECREF(item);
1608 } else {
1609 if (it->counter) {
1610 Py_DECREF(it);
1611 return NULL;
1612 } else
1613 break;
1614 }
1615 }
1616 return (PyObject*)it;
1617}
1618
Martin v. Löwis59683e82008-06-13 07:50:45 +00001619static PyTypeObject dequereviter_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001620 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger87e69122015-03-02 23:32:02 -08001621 "_collections._deque_reverse_iterator", /* tp_name */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001622 sizeof(dequeiterobject), /* tp_basicsize */
1623 0, /* tp_itemsize */
1624 /* methods */
1625 (destructor)dequeiter_dealloc, /* tp_dealloc */
1626 0, /* tp_print */
1627 0, /* tp_getattr */
1628 0, /* tp_setattr */
1629 0, /* tp_reserved */
1630 0, /* tp_repr */
1631 0, /* tp_as_number */
1632 0, /* tp_as_sequence */
1633 0, /* tp_as_mapping */
1634 0, /* tp_hash */
1635 0, /* tp_call */
1636 0, /* tp_str */
1637 PyObject_GenericGetAttr, /* tp_getattro */
1638 0, /* tp_setattro */
1639 0, /* tp_as_buffer */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001640 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001641 0, /* tp_doc */
1642 (traverseproc)dequeiter_traverse, /* tp_traverse */
1643 0, /* tp_clear */
1644 0, /* tp_richcompare */
1645 0, /* tp_weaklistoffset */
1646 PyObject_SelfIter, /* tp_iter */
1647 (iternextfunc)dequereviter_next, /* tp_iternext */
1648 dequeiter_methods, /* tp_methods */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001649 0, /* tp_members */
1650 0, /* tp_getset */
1651 0, /* tp_base */
1652 0, /* tp_dict */
1653 0, /* tp_descr_get */
1654 0, /* tp_descr_set */
1655 0, /* tp_dictoffset */
1656 0, /* tp_init */
1657 0, /* tp_alloc */
1658 dequereviter_new, /* tp_new */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001659 0,
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001660};
1661
Guido van Rossum1968ad32006-02-25 22:38:04 +00001662/* defaultdict type *********************************************************/
1663
1664typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001665 PyDictObject dict;
1666 PyObject *default_factory;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001667} defdictobject;
1668
1669static PyTypeObject defdict_type; /* Forward */
1670
1671PyDoc_STRVAR(defdict_missing_doc,
1672"__missing__(key) # Called by __getitem__ for missing key; pseudo-code:\n\
Guido van Rossumd8faa362007-04-27 19:54:29 +00001673 if self.default_factory is None: raise KeyError((key,))\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00001674 self[key] = value = self.default_factory()\n\
1675 return value\n\
1676");
1677
1678static PyObject *
1679defdict_missing(defdictobject *dd, PyObject *key)
1680{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001681 PyObject *factory = dd->default_factory;
1682 PyObject *value;
1683 if (factory == NULL || factory == Py_None) {
1684 /* XXX Call dict.__missing__(key) */
1685 PyObject *tup;
1686 tup = PyTuple_Pack(1, key);
1687 if (!tup) return NULL;
1688 PyErr_SetObject(PyExc_KeyError, tup);
1689 Py_DECREF(tup);
1690 return NULL;
1691 }
1692 value = PyEval_CallObject(factory, NULL);
1693 if (value == NULL)
1694 return value;
1695 if (PyObject_SetItem((PyObject *)dd, key, value) < 0) {
1696 Py_DECREF(value);
1697 return NULL;
1698 }
1699 return value;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001700}
1701
1702PyDoc_STRVAR(defdict_copy_doc, "D.copy() -> a shallow copy of D.");
1703
1704static PyObject *
1705defdict_copy(defdictobject *dd)
1706{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001707 /* This calls the object's class. That only works for subclasses
1708 whose class constructor has the same signature. Subclasses that
1709 define a different constructor signature must override copy().
1710 */
Raymond Hettinger54628fa2009-08-04 19:16:39 +00001711
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001712 if (dd->default_factory == NULL)
1713 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd), Py_None, dd, NULL);
1714 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd),
1715 dd->default_factory, dd, NULL);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001716}
1717
1718static PyObject *
1719defdict_reduce(defdictobject *dd)
1720{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001721 /* __reduce__ must return a 5-tuple as follows:
Guido van Rossum1968ad32006-02-25 22:38:04 +00001722
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001723 - factory function
1724 - tuple of args for the factory function
1725 - additional state (here None)
1726 - sequence iterator (here None)
1727 - dictionary iterator (yielding successive (key, value) pairs
Guido van Rossum1968ad32006-02-25 22:38:04 +00001728
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001729 This API is used by pickle.py and copy.py.
Guido van Rossum1968ad32006-02-25 22:38:04 +00001730
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001731 For this to be useful with pickle.py, the default_factory
1732 must be picklable; e.g., None, a built-in, or a global
1733 function in a module or package.
Guido van Rossum1968ad32006-02-25 22:38:04 +00001734
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001735 Both shallow and deep copying are supported, but for deep
1736 copying, the default_factory must be deep-copyable; e.g. None,
1737 or a built-in (functions are not copyable at this time).
Guido van Rossum1968ad32006-02-25 22:38:04 +00001738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001739 This only works for subclasses as long as their constructor
1740 signature is compatible; the first argument must be the
1741 optional default_factory, defaulting to None.
1742 */
1743 PyObject *args;
1744 PyObject *items;
1745 PyObject *iter;
1746 PyObject *result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001747 _Py_IDENTIFIER(items);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001748
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001749 if (dd->default_factory == NULL || dd->default_factory == Py_None)
1750 args = PyTuple_New(0);
1751 else
1752 args = PyTuple_Pack(1, dd->default_factory);
1753 if (args == NULL)
1754 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001755 items = _PyObject_CallMethodId((PyObject *)dd, &PyId_items, "()");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001756 if (items == NULL) {
1757 Py_DECREF(args);
1758 return NULL;
1759 }
1760 iter = PyObject_GetIter(items);
1761 if (iter == NULL) {
1762 Py_DECREF(items);
1763 Py_DECREF(args);
1764 return NULL;
1765 }
1766 result = PyTuple_Pack(5, Py_TYPE(dd), args,
1767 Py_None, Py_None, iter);
1768 Py_DECREF(iter);
1769 Py_DECREF(items);
1770 Py_DECREF(args);
1771 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001772}
1773
1774static PyMethodDef defdict_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001775 {"__missing__", (PyCFunction)defdict_missing, METH_O,
1776 defdict_missing_doc},
1777 {"copy", (PyCFunction)defdict_copy, METH_NOARGS,
1778 defdict_copy_doc},
1779 {"__copy__", (PyCFunction)defdict_copy, METH_NOARGS,
1780 defdict_copy_doc},
1781 {"__reduce__", (PyCFunction)defdict_reduce, METH_NOARGS,
1782 reduce_doc},
1783 {NULL}
Guido van Rossum1968ad32006-02-25 22:38:04 +00001784};
1785
1786static PyMemberDef defdict_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001787 {"default_factory", T_OBJECT,
1788 offsetof(defdictobject, default_factory), 0,
1789 PyDoc_STR("Factory for default value called by __missing__().")},
1790 {NULL}
Guido van Rossum1968ad32006-02-25 22:38:04 +00001791};
1792
1793static void
1794defdict_dealloc(defdictobject *dd)
1795{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001796 Py_CLEAR(dd->default_factory);
1797 PyDict_Type.tp_dealloc((PyObject *)dd);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001798}
1799
Guido van Rossum1968ad32006-02-25 22:38:04 +00001800static PyObject *
1801defdict_repr(defdictobject *dd)
1802{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001803 PyObject *baserepr;
1804 PyObject *defrepr;
1805 PyObject *result;
1806 baserepr = PyDict_Type.tp_repr((PyObject *)dd);
1807 if (baserepr == NULL)
1808 return NULL;
1809 if (dd->default_factory == NULL)
1810 defrepr = PyUnicode_FromString("None");
1811 else
1812 {
1813 int status = Py_ReprEnter(dd->default_factory);
1814 if (status != 0) {
Antoine Pitrouf5f1fe02012-02-15 02:42:46 +01001815 if (status < 0) {
1816 Py_DECREF(baserepr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001817 return NULL;
Antoine Pitrouf5f1fe02012-02-15 02:42:46 +01001818 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001819 defrepr = PyUnicode_FromString("...");
1820 }
1821 else
1822 defrepr = PyObject_Repr(dd->default_factory);
1823 Py_ReprLeave(dd->default_factory);
1824 }
1825 if (defrepr == NULL) {
1826 Py_DECREF(baserepr);
1827 return NULL;
1828 }
1829 result = PyUnicode_FromFormat("defaultdict(%U, %U)",
1830 defrepr, baserepr);
1831 Py_DECREF(defrepr);
1832 Py_DECREF(baserepr);
1833 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001834}
1835
1836static int
1837defdict_traverse(PyObject *self, visitproc visit, void *arg)
1838{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001839 Py_VISIT(((defdictobject *)self)->default_factory);
1840 return PyDict_Type.tp_traverse(self, visit, arg);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001841}
1842
1843static int
1844defdict_tp_clear(defdictobject *dd)
1845{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001846 Py_CLEAR(dd->default_factory);
1847 return PyDict_Type.tp_clear((PyObject *)dd);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001848}
1849
1850static int
1851defdict_init(PyObject *self, PyObject *args, PyObject *kwds)
1852{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001853 defdictobject *dd = (defdictobject *)self;
1854 PyObject *olddefault = dd->default_factory;
1855 PyObject *newdefault = NULL;
1856 PyObject *newargs;
1857 int result;
1858 if (args == NULL || !PyTuple_Check(args))
1859 newargs = PyTuple_New(0);
1860 else {
1861 Py_ssize_t n = PyTuple_GET_SIZE(args);
1862 if (n > 0) {
1863 newdefault = PyTuple_GET_ITEM(args, 0);
1864 if (!PyCallable_Check(newdefault) && newdefault != Py_None) {
1865 PyErr_SetString(PyExc_TypeError,
1866 "first argument must be callable");
1867 return -1;
1868 }
1869 }
1870 newargs = PySequence_GetSlice(args, 1, n);
1871 }
1872 if (newargs == NULL)
1873 return -1;
1874 Py_XINCREF(newdefault);
1875 dd->default_factory = newdefault;
1876 result = PyDict_Type.tp_init(self, newargs, kwds);
1877 Py_DECREF(newargs);
1878 Py_XDECREF(olddefault);
1879 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001880}
1881
1882PyDoc_STRVAR(defdict_doc,
Benjamin Peterson9cb33b72014-01-13 23:56:05 -05001883"defaultdict(default_factory[, ...]) --> dict with default factory\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00001884\n\
1885The default factory is called without arguments to produce\n\
1886a new value when a key is not present, in __getitem__ only.\n\
1887A defaultdict compares equal to a dict with the same items.\n\
Benjamin Peterson9cb33b72014-01-13 23:56:05 -05001888All remaining arguments are treated the same as if they were\n\
1889passed to the dict constructor, including keyword arguments.\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00001890");
1891
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001892/* See comment in xxsubtype.c */
1893#define DEFERRED_ADDRESS(ADDR) 0
1894
Guido van Rossum1968ad32006-02-25 22:38:04 +00001895static PyTypeObject defdict_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001896 PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0)
1897 "collections.defaultdict", /* tp_name */
1898 sizeof(defdictobject), /* tp_basicsize */
1899 0, /* tp_itemsize */
1900 /* methods */
1901 (destructor)defdict_dealloc, /* tp_dealloc */
1902 0, /* tp_print */
1903 0, /* tp_getattr */
1904 0, /* tp_setattr */
1905 0, /* tp_reserved */
1906 (reprfunc)defdict_repr, /* tp_repr */
1907 0, /* tp_as_number */
1908 0, /* tp_as_sequence */
1909 0, /* tp_as_mapping */
1910 0, /* tp_hash */
1911 0, /* tp_call */
1912 0, /* tp_str */
1913 PyObject_GenericGetAttr, /* tp_getattro */
1914 0, /* tp_setattro */
1915 0, /* tp_as_buffer */
1916 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
1917 /* tp_flags */
1918 defdict_doc, /* tp_doc */
1919 defdict_traverse, /* tp_traverse */
1920 (inquiry)defdict_tp_clear, /* tp_clear */
1921 0, /* tp_richcompare */
1922 0, /* tp_weaklistoffset*/
1923 0, /* tp_iter */
1924 0, /* tp_iternext */
1925 defdict_methods, /* tp_methods */
1926 defdict_members, /* tp_members */
1927 0, /* tp_getset */
1928 DEFERRED_ADDRESS(&PyDict_Type), /* tp_base */
1929 0, /* tp_dict */
1930 0, /* tp_descr_get */
1931 0, /* tp_descr_set */
1932 0, /* tp_dictoffset */
1933 defdict_init, /* tp_init */
1934 PyType_GenericAlloc, /* tp_alloc */
1935 0, /* tp_new */
1936 PyObject_GC_Del, /* tp_free */
Guido van Rossum1968ad32006-02-25 22:38:04 +00001937};
1938
Raymond Hettinger96f34102010-12-15 16:30:37 +00001939/* helper function for Counter *********************************************/
1940
1941PyDoc_STRVAR(_count_elements_doc,
1942"_count_elements(mapping, iterable) -> None\n\
1943\n\
1944Count elements in the iterable, updating the mappping");
1945
1946static PyObject *
1947_count_elements(PyObject *self, PyObject *args)
1948{
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07001949 _Py_IDENTIFIER(get);
Raymond Hettinger2ff21902013-10-01 00:55:43 -07001950 _Py_IDENTIFIER(__setitem__);
Raymond Hettinger96f34102010-12-15 16:30:37 +00001951 PyObject *it, *iterable, *mapping, *oldval;
1952 PyObject *newval = NULL;
1953 PyObject *key = NULL;
Raymond Hettinger224c87d2013-10-01 21:36:09 -07001954 PyObject *zero = NULL;
Raymond Hettinger96f34102010-12-15 16:30:37 +00001955 PyObject *one = NULL;
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07001956 PyObject *bound_get = NULL;
1957 PyObject *mapping_get;
1958 PyObject *dict_get;
Raymond Hettinger2ff21902013-10-01 00:55:43 -07001959 PyObject *mapping_setitem;
Raymond Hettinger2ff21902013-10-01 00:55:43 -07001960 PyObject *dict_setitem;
Raymond Hettinger96f34102010-12-15 16:30:37 +00001961
1962 if (!PyArg_UnpackTuple(args, "_count_elements", 2, 2, &mapping, &iterable))
1963 return NULL;
1964
Raymond Hettinger96f34102010-12-15 16:30:37 +00001965 it = PyObject_GetIter(iterable);
1966 if (it == NULL)
1967 return NULL;
Raymond Hettinger426e0522011-01-03 02:12:02 +00001968
Raymond Hettinger96f34102010-12-15 16:30:37 +00001969 one = PyLong_FromLong(1);
Raymond Hettinger224c87d2013-10-01 21:36:09 -07001970 if (one == NULL)
1971 goto done;
Raymond Hettinger426e0522011-01-03 02:12:02 +00001972
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07001973 /* Only take the fast path when get() and __setitem__()
1974 * have not been overridden.
1975 */
1976 mapping_get = _PyType_LookupId(Py_TYPE(mapping), &PyId_get);
1977 dict_get = _PyType_LookupId(&PyDict_Type, &PyId_get);
Raymond Hettinger2ff21902013-10-01 00:55:43 -07001978 mapping_setitem = _PyType_LookupId(Py_TYPE(mapping), &PyId___setitem__);
1979 dict_setitem = _PyType_LookupId(&PyDict_Type, &PyId___setitem__);
1980
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07001981 if (mapping_get != NULL && mapping_get == dict_get &&
1982 mapping_setitem != NULL && mapping_setitem == dict_setitem) {
Raymond Hettinger426e0522011-01-03 02:12:02 +00001983 while (1) {
Raymond Hettinger507d9972014-05-18 21:32:40 +01001984 /* Fast path advantages:
1985 1. Eliminate double hashing
1986 (by re-using the same hash for both the get and set)
1987 2. Avoid argument overhead of PyObject_CallFunctionObjArgs
1988 (argument tuple creation and parsing)
1989 3. Avoid indirection through a bound method object
1990 (creates another argument tuple)
1991 4. Avoid initial increment from zero
1992 (reuse an existing one-object instead)
1993 */
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07001994 Py_hash_t hash;
1995
Raymond Hettinger426e0522011-01-03 02:12:02 +00001996 key = PyIter_Next(it);
Victor Stinnera154b5c2011-04-20 23:23:52 +02001997 if (key == NULL)
1998 break;
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07001999
2000 if (!PyUnicode_CheckExact(key) ||
2001 (hash = ((PyASCIIObject *) key)->hash) == -1)
2002 {
2003 hash = PyObject_Hash(key);
Raymond Hettingerda2850f2015-02-27 12:42:54 -08002004 if (hash == -1)
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002005 goto done;
2006 }
2007
2008 oldval = _PyDict_GetItem_KnownHash(mapping, key, hash);
Raymond Hettinger426e0522011-01-03 02:12:02 +00002009 if (oldval == NULL) {
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002010 if (_PyDict_SetItem_KnownHash(mapping, key, one, hash) == -1)
Raymond Hettinger507d9972014-05-18 21:32:40 +01002011 goto done;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002012 } else {
2013 newval = PyNumber_Add(oldval, one);
2014 if (newval == NULL)
Raymond Hettinger507d9972014-05-18 21:32:40 +01002015 goto done;
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002016 if (_PyDict_SetItem_KnownHash(mapping, key, newval, hash) == -1)
Raymond Hettinger507d9972014-05-18 21:32:40 +01002017 goto done;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002018 Py_CLEAR(newval);
2019 }
2020 Py_DECREF(key);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002021 }
Raymond Hettinger426e0522011-01-03 02:12:02 +00002022 } else {
Victor Stinnere7f516c2013-11-06 23:52:55 +01002023 bound_get = _PyObject_GetAttrId(mapping, &PyId_get);
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002024 if (bound_get == NULL)
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002025 goto done;
2026
2027 zero = PyLong_FromLong(0);
2028 if (zero == NULL)
2029 goto done;
2030
Raymond Hettinger426e0522011-01-03 02:12:02 +00002031 while (1) {
2032 key = PyIter_Next(it);
Victor Stinnera154b5c2011-04-20 23:23:52 +02002033 if (key == NULL)
2034 break;
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002035 oldval = PyObject_CallFunctionObjArgs(bound_get, key, zero, NULL);
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002036 if (oldval == NULL)
2037 break;
2038 newval = PyNumber_Add(oldval, one);
2039 Py_DECREF(oldval);
2040 if (newval == NULL)
2041 break;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002042 if (PyObject_SetItem(mapping, key, newval) == -1)
Raymond Hettinger96f34102010-12-15 16:30:37 +00002043 break;
2044 Py_CLEAR(newval);
Raymond Hettinger426e0522011-01-03 02:12:02 +00002045 Py_DECREF(key);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002046 }
Raymond Hettinger96f34102010-12-15 16:30:37 +00002047 }
Raymond Hettinger426e0522011-01-03 02:12:02 +00002048
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002049done:
Raymond Hettinger96f34102010-12-15 16:30:37 +00002050 Py_DECREF(it);
2051 Py_XDECREF(key);
2052 Py_XDECREF(newval);
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002053 Py_XDECREF(bound_get);
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002054 Py_XDECREF(zero);
2055 Py_XDECREF(one);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002056 if (PyErr_Occurred())
2057 return NULL;
2058 Py_RETURN_NONE;
2059}
2060
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002061/* module level code ********************************************************/
2062
2063PyDoc_STRVAR(module_doc,
Guido van Rossum1968ad32006-02-25 22:38:04 +00002064"High performance data structures.\n\
2065- deque: ordered collection accessible from endpoints only\n\
2066- defaultdict: dict subclass with a default value factory\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002067");
2068
Raymond Hettinger96f34102010-12-15 16:30:37 +00002069static struct PyMethodDef module_functions[] = {
2070 {"_count_elements", _count_elements, METH_VARARGS, _count_elements_doc},
2071 {NULL, NULL} /* sentinel */
2072};
Martin v. Löwis1a214512008-06-11 05:26:20 +00002073
2074static struct PyModuleDef _collectionsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002075 PyModuleDef_HEAD_INIT,
2076 "_collections",
2077 module_doc,
2078 -1,
Raymond Hettinger96f34102010-12-15 16:30:37 +00002079 module_functions,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002080 NULL,
2081 NULL,
2082 NULL,
2083 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002084};
2085
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002086PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002087PyInit__collections(void)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002088{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002089 PyObject *m;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002090
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002091 m = PyModule_Create(&_collectionsmodule);
2092 if (m == NULL)
2093 return NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002094
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002095 if (PyType_Ready(&deque_type) < 0)
2096 return NULL;
2097 Py_INCREF(&deque_type);
2098 PyModule_AddObject(m, "deque", (PyObject *)&deque_type);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002099
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002100 defdict_type.tp_base = &PyDict_Type;
2101 if (PyType_Ready(&defdict_type) < 0)
2102 return NULL;
2103 Py_INCREF(&defdict_type);
2104 PyModule_AddObject(m, "defaultdict", (PyObject *)&defdict_type);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002106 if (PyType_Ready(&dequeiter_type) < 0)
2107 return NULL;
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002108 Py_INCREF(&dequeiter_type);
2109 PyModule_AddObject(m, "_deque_iterator", (PyObject *)&dequeiter_type);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002111 if (PyType_Ready(&dequereviter_type) < 0)
2112 return NULL;
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002113 Py_INCREF(&dequereviter_type);
2114 PyModule_AddObject(m, "_deque_reverse_iterator", (PyObject *)&dequereviter_type);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00002115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002116 return m;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002117}