blob: be6c90c6fe89aaed3313ef1bbaf88a0beac91a17 [file] [log] [blame]
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001#include "Python.h"
Raymond Hettinger691d8052004-05-30 07:26:47 +00002#include "structmember.h"
Raymond Hettinger756b3f32004-01-29 06:37:52 +00003
Raymond Hettingerc2083082015-02-28 23:29:16 -08004#ifdef STDC_HEADERS
5#include <stddef.h>
6#else
7#include <sys/types.h> /* For size_t */
8#endif
9
Raymond Hettinger756b3f32004-01-29 06:37:52 +000010/* collections module implementation of a deque() datatype
11 Written and maintained by Raymond D. Hettinger <python@rcn.com>
Raymond Hettingereb6b5542015-02-10 22:37:22 -060012 Copyright (c) 2004-2015 Python Software Foundation.
Raymond Hettinger756b3f32004-01-29 06:37:52 +000013 All rights reserved.
14*/
15
Raymond Hettinger77e8bf12004-10-01 15:25:53 +000016/* The block length may be set to any number over 1. Larger numbers
Raymond Hettinger20b0f872013-06-23 15:44:33 -070017 * reduce the number of calls to the memory allocator, give faster
Raymond Hettinger30c90742015-03-02 22:31:35 -080018 * indexing and rotation, and reduce the link to data overhead ratio.
Raymond Hettingerdaf57f22015-02-26 23:21:29 -080019 * Making the block length a power of two speeds-up the modulo
Raymond Hettinger30c90742015-03-02 22:31:35 -080020 * and division calculations in deque_item() and deque_ass_item().
Raymond Hettinger77e8bf12004-10-01 15:25:53 +000021 */
22
Raymond Hettingerdaf57f22015-02-26 23:21:29 -080023#define BLOCKLEN 64
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000024#define CENTER ((BLOCKLEN - 1) / 2)
Raymond Hettinger756b3f32004-01-29 06:37:52 +000025
Raymond Hettinger551350a2015-03-24 00:19:53 -070026/* Data for deque objects is stored in a doubly-linked list of fixed
27 * length blocks. This assures that appends or pops never move any
28 * other data elements besides the one being appended or popped.
29 *
30 * Another advantage is that it completely avoids use of realloc(),
31 * resulting in more predictable performance.
32 *
33 * Textbook implementations of doubly-linked lists store one datum
34 * per link, but that gives them a 200% memory overhead (a prev and
35 * next link for each datum) and it costs one malloc() call per data
36 * element. By using fixed-length blocks, the link to data ratio is
37 * significantly improved and there are proportionally fewer calls
38 * to malloc() and free(). The data blocks of consecutive pointers
39 * also improve cache locality.
40 *
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000041 * The list of blocks is never empty, so d.leftblock and d.rightblock
Raymond Hettinger82df9252013-07-07 01:43:42 -100042 * are never equal to NULL. The list is not circular.
43 *
44 * A deque d's first element is at d.leftblock[leftindex]
45 * and its last element is at d.rightblock[rightindex].
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000046 *
Raymond Hettinger551350a2015-03-24 00:19:53 -070047 * Unlike Python slice indices, these indices are inclusive on both
48 * ends. This makes the algorithms for left and right operations
49 * more symmetrical and it simplifies the design.
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000050 *
Raymond Hettinger551350a2015-03-24 00:19:53 -070051 * The indices, d.leftindex and d.rightindex are always in the range:
52 * 0 <= index < BLOCKLEN
53 *
54 * And their exact relationship is:
55 * (d.leftindex + d.len - 1) % BLOCKLEN == d.rightindex
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000056 *
Raymond Hettinger8dbbae22015-03-24 21:01:50 -070057 * Whenever d.leftblock == d.rightblock, then:
Raymond Hettinger551350a2015-03-24 00:19:53 -070058 * d.leftindex + d.len - 1 == d.rightindex
Thomas Wouters0e3f5912006-08-11 14:57:12 +000059 *
Raymond Hettinger551350a2015-03-24 00:19:53 -070060 * However, when d.leftblock != d.rightblock, the d.leftindex and
61 * d.rightindex become indices into distinct blocks and either may
62 * be larger than the other.
63 *
64 * Empty deques have:
65 * d.len == 0
66 * d.leftblock == d.rightblock
67 * d.leftindex == CENTER + 1
68 * d.rightindex == CENTER
69 *
70 * Checking for d.len == 0 is the intended way to see whether d is empty.
Tim Petersd8768d32004-10-01 01:32:53 +000071 */
72
Raymond Hettinger756b3f32004-01-29 06:37:52 +000073typedef struct BLOCK {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000074 struct BLOCK *leftlink;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000075 PyObject *data[BLOCKLEN];
Raymond Hettinger20b0f872013-06-23 15:44:33 -070076 struct BLOCK *rightlink;
Raymond Hettinger756b3f32004-01-29 06:37:52 +000077} block;
78
Raymond Hettinger30c90742015-03-02 22:31:35 -080079typedef struct {
80 PyObject_VAR_HEAD
81 block *leftblock;
82 block *rightblock;
Raymond Hettinger551350a2015-03-24 00:19:53 -070083 Py_ssize_t leftindex; /* 0 <= leftindex < BLOCKLEN */
84 Py_ssize_t rightindex; /* 0 <= rightindex < BLOCKLEN */
Raymond Hettingerf9d9c792015-03-02 22:47:46 -080085 size_t state; /* incremented whenever the indices move */
Raymond Hettinger30c90742015-03-02 22:31:35 -080086 Py_ssize_t maxlen;
Raymond Hettinger0f6f9472015-03-21 01:42:10 -070087 PyObject *weakreflist;
Raymond Hettinger30c90742015-03-02 22:31:35 -080088} dequeobject;
89
90static PyTypeObject deque_type;
91
Raymond Hettinger82df9252013-07-07 01:43:42 -100092/* For debug builds, add error checking to track the endpoints
93 * in the chain of links. The goal is to make sure that link
94 * assignments only take place at endpoints so that links already
95 * in use do not get overwritten.
96 *
97 * CHECK_END should happen before each assignment to a block's link field.
98 * MARK_END should happen whenever a link field becomes a new endpoint.
99 * This happens when new blocks are added or whenever an existing
100 * block is freed leaving another existing block as the new endpoint.
101 */
102
Raymond Hettinger3223dd52013-07-26 23:14:22 -0700103#ifndef NDEBUG
Raymond Hettinger82df9252013-07-07 01:43:42 -1000104#define MARK_END(link) link = NULL;
105#define CHECK_END(link) assert(link == NULL);
106#define CHECK_NOT_END(link) assert(link != NULL);
107#else
108#define MARK_END(link)
109#define CHECK_END(link)
110#define CHECK_NOT_END(link)
111#endif
112
Raymond Hettinger41290a62015-03-31 08:12:23 -0700113/* To prevent len from overflowing PY_SSIZE_T_MAX, we refuse to
114 allocate new blocks if the current len is nearing overflow.
115*/
116
117#define MAX_DEQUE_LEN (PY_SSIZE_T_MAX - 3*BLOCKLEN)
118
Raymond Hettinger82df9252013-07-07 01:43:42 -1000119/* A simple freelisting scheme is used to minimize calls to the memory
Raymond Hettinger551350a2015-03-24 00:19:53 -0700120 allocator. It accommodates common use cases where new blocks are being
Raymond Hettinger82df9252013-07-07 01:43:42 -1000121 added at about the same rate as old blocks are being freed.
122 */
123
Guido van Rossum58da9312007-11-10 23:39:45 +0000124#define MAXFREEBLOCKS 10
Benjamin Petersond6313712008-07-31 16:23:04 +0000125static Py_ssize_t numfreeblocks = 0;
Guido van Rossum58da9312007-11-10 23:39:45 +0000126static block *freeblocks[MAXFREEBLOCKS];
127
Tim Peters6f853562004-10-01 01:04:50 +0000128static block *
Raymond Hettinger82df9252013-07-07 01:43:42 -1000129newblock(Py_ssize_t len) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000130 block *b;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700131 if (len >= MAX_DEQUE_LEN) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000132 PyErr_SetString(PyExc_OverflowError,
133 "cannot add more blocks to the deque");
134 return NULL;
135 }
136 if (numfreeblocks) {
Raymond Hettinger59cf23a2013-02-07 00:57:19 -0500137 numfreeblocks--;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000138 return freeblocks[numfreeblocks];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000139 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000140 b = PyMem_Malloc(sizeof(block));
141 if (b != NULL) {
142 return b;
143 }
144 PyErr_NoMemory();
145 return NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000146}
147
Martin v. Löwis59683e82008-06-13 07:50:45 +0000148static void
Guido van Rossum58da9312007-11-10 23:39:45 +0000149freeblock(block *b)
150{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000151 if (numfreeblocks < MAXFREEBLOCKS) {
152 freeblocks[numfreeblocks] = b;
153 numfreeblocks++;
154 } else {
155 PyMem_Free(b);
156 }
Guido van Rossum58da9312007-11-10 23:39:45 +0000157}
158
Raymond Hettingerda2850f2015-02-27 12:42:54 -0800159/* XXX Todo:
Raymond Hettinger54023152014-04-23 00:58:48 -0700160 If aligned memory allocations become available, make the
161 deque object 64 byte aligned so that all of the fields
162 can be retrieved or updated in a single cache line.
163*/
164
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000165static PyObject *
166deque_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
167{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000168 dequeobject *deque;
169 block *b;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000171 /* create dequeobject structure */
172 deque = (dequeobject *)type->tp_alloc(type, 0);
173 if (deque == NULL)
174 return NULL;
Tim Peters1065f752004-10-01 01:03:29 +0000175
Raymond Hettinger82df9252013-07-07 01:43:42 -1000176 b = newblock(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000177 if (b == NULL) {
178 Py_DECREF(deque);
179 return NULL;
180 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000181 MARK_END(b->leftlink);
182 MARK_END(b->rightlink);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000184 assert(BLOCKLEN >= 2);
Raymond Hettinger87e69122015-03-02 23:32:02 -0800185 Py_SIZE(deque) = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000186 deque->leftblock = b;
187 deque->rightblock = b;
188 deque->leftindex = CENTER + 1;
189 deque->rightindex = CENTER;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000190 deque->state = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000191 deque->maxlen = -1;
Raymond Hettinger87e69122015-03-02 23:32:02 -0800192 deque->weakreflist = NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000194 return (PyObject *)deque;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000195}
196
197static PyObject *
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000198deque_pop(dequeobject *deque, PyObject *unused)
199{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000200 PyObject *item;
201 block *prevblock;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000202
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000203 if (Py_SIZE(deque) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000204 PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
205 return NULL;
206 }
207 item = deque->rightblock->data[deque->rightindex];
208 deque->rightindex--;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000209 Py_SIZE(deque)--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000210 deque->state++;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000211
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -0700212 if (deque->rightindex < 0) {
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700213 if (Py_SIZE(deque)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000214 prevblock = deque->rightblock->leftlink;
215 assert(deque->leftblock != deque->rightblock);
216 freeblock(deque->rightblock);
Raymond Hettinger82df9252013-07-07 01:43:42 -1000217 CHECK_NOT_END(prevblock);
218 MARK_END(prevblock->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000219 deque->rightblock = prevblock;
220 deque->rightindex = BLOCKLEN - 1;
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700221 } else {
222 assert(deque->leftblock == deque->rightblock);
223 assert(deque->leftindex == deque->rightindex+1);
224 /* re-center instead of freeing a block */
225 deque->leftindex = CENTER + 1;
226 deque->rightindex = CENTER;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000227 }
228 }
229 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000230}
231
232PyDoc_STRVAR(pop_doc, "Remove and return the rightmost element.");
233
234static PyObject *
235deque_popleft(dequeobject *deque, PyObject *unused)
236{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000237 PyObject *item;
238 block *prevblock;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000239
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000240 if (Py_SIZE(deque) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000241 PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
242 return NULL;
243 }
244 assert(deque->leftblock != NULL);
245 item = deque->leftblock->data[deque->leftindex];
246 deque->leftindex++;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000247 Py_SIZE(deque)--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000248 deque->state++;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000250 if (deque->leftindex == BLOCKLEN) {
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700251 if (Py_SIZE(deque)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000252 assert(deque->leftblock != deque->rightblock);
253 prevblock = deque->leftblock->rightlink;
254 freeblock(deque->leftblock);
Raymond Hettinger82df9252013-07-07 01:43:42 -1000255 CHECK_NOT_END(prevblock);
256 MARK_END(prevblock->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000257 deque->leftblock = prevblock;
258 deque->leftindex = 0;
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700259 } else {
260 assert(deque->leftblock == deque->rightblock);
261 assert(deque->leftindex == deque->rightindex+1);
262 /* re-center instead of freeing a block */
263 deque->leftindex = CENTER + 1;
264 deque->rightindex = CENTER;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000265 }
266 }
267 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000268}
269
270PyDoc_STRVAR(popleft_doc, "Remove and return the leftmost element.");
271
Raymond Hettingerf30f5b92015-03-02 22:23:37 -0800272/* The deque's size limit is d.maxlen. The limit can be zero or positive.
273 * If there is no limit, then d.maxlen == -1.
274 *
275 * After an item is added to a deque, we check to see if the size has grown past
276 * the limit. If it has, we get the size back down to the limit by popping an
277 * item off of the opposite end. The methods that can trigger this are append(),
278 * appendleft(), extend(), and extendleft().
279 */
280
281static void
282deque_trim_right(dequeobject *deque)
283{
284 if (deque->maxlen != -1 && Py_SIZE(deque) > deque->maxlen) {
285 PyObject *rv = deque_pop(deque, NULL);
286 assert(rv != NULL);
287 assert(Py_SIZE(deque) <= deque->maxlen);
288 Py_DECREF(rv);
289 }
290}
291
292static void
293deque_trim_left(dequeobject *deque)
294{
295 if (deque->maxlen != -1 && Py_SIZE(deque) > deque->maxlen) {
296 PyObject *rv = deque_popleft(deque, NULL);
297 assert(rv != NULL);
298 assert(Py_SIZE(deque) <= deque->maxlen);
299 Py_DECREF(rv);
300 }
301}
302
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000303static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000304deque_append(dequeobject *deque, PyObject *item)
305{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000306 deque->state++;
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700307 if (deque->rightindex == BLOCKLEN - 1) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000308 block *b = newblock(Py_SIZE(deque));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000309 if (b == NULL)
310 return NULL;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000311 b->leftlink = deque->rightblock;
312 CHECK_END(deque->rightblock->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000313 deque->rightblock->rightlink = b;
314 deque->rightblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000315 MARK_END(b->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000316 deque->rightindex = -1;
317 }
318 Py_INCREF(item);
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000319 Py_SIZE(deque)++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000320 deque->rightindex++;
321 deque->rightblock->data[deque->rightindex] = item;
Raymond Hettingerf30f5b92015-03-02 22:23:37 -0800322 deque_trim_left(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000323 Py_RETURN_NONE;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000324}
325
326PyDoc_STRVAR(append_doc, "Add an element to the right side of the deque.");
327
328static PyObject *
329deque_appendleft(dequeobject *deque, PyObject *item)
330{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000331 deque->state++;
332 if (deque->leftindex == 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000333 block *b = newblock(Py_SIZE(deque));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000334 if (b == NULL)
335 return NULL;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000336 b->rightlink = deque->leftblock;
337 CHECK_END(deque->leftblock->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000338 deque->leftblock->leftlink = b;
339 deque->leftblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000340 MARK_END(b->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000341 deque->leftindex = BLOCKLEN;
342 }
343 Py_INCREF(item);
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000344 Py_SIZE(deque)++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000345 deque->leftindex--;
346 deque->leftblock->data[deque->leftindex] = item;
Raymond Hettingerf30f5b92015-03-02 22:23:37 -0800347 deque_trim_right(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000348 Py_RETURN_NONE;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000349}
350
351PyDoc_STRVAR(appendleft_doc, "Add an element to the left side of the deque.");
352
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000353
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000354/* Run an iterator to exhaustion. Shortcut for
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000355 the extend/extendleft methods when maxlen == 0. */
356static PyObject*
357consume_iterator(PyObject *it)
358{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000359 PyObject *item;
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000360
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000361 while ((item = PyIter_Next(it)) != NULL) {
362 Py_DECREF(item);
363 }
364 Py_DECREF(it);
365 if (PyErr_Occurred())
366 return NULL;
367 Py_RETURN_NONE;
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000368}
369
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000370static PyObject *
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000371deque_extend(dequeobject *deque, PyObject *iterable)
372{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000373 PyObject *it, *item;
Raymond Hettinger0e14e662015-09-19 00:21:33 -0600374 int trim = (deque->maxlen != -1);
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000376 /* Handle case where id(deque) == id(iterable) */
377 if ((PyObject *)deque == iterable) {
378 PyObject *result;
379 PyObject *s = PySequence_List(iterable);
380 if (s == NULL)
381 return NULL;
382 result = deque_extend(deque, s);
383 Py_DECREF(s);
384 return result;
385 }
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000386
Raymond Hettingerd9c116c2013-07-09 00:13:21 -0700387 /* Space saving heuristic. Start filling from the left */
388 if (Py_SIZE(deque) == 0) {
389 assert(deque->leftblock == deque->rightblock);
390 assert(deque->leftindex == deque->rightindex+1);
391 deque->leftindex = 1;
392 deque->rightindex = 0;
393 }
394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000395 it = PyObject_GetIter(iterable);
396 if (it == NULL)
397 return NULL;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000399 if (deque->maxlen == 0)
400 return consume_iterator(it);
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000402 while ((item = PyIter_Next(it)) != NULL) {
403 deque->state++;
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700404 if (deque->rightindex == BLOCKLEN - 1) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000405 block *b = newblock(Py_SIZE(deque));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000406 if (b == NULL) {
407 Py_DECREF(item);
408 Py_DECREF(it);
409 return NULL;
410 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000411 b->leftlink = deque->rightblock;
412 CHECK_END(deque->rightblock->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000413 deque->rightblock->rightlink = b;
414 deque->rightblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000415 MARK_END(b->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000416 deque->rightindex = -1;
417 }
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000418 Py_SIZE(deque)++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000419 deque->rightindex++;
420 deque->rightblock->data[deque->rightindex] = item;
Raymond Hettinger0e14e662015-09-19 00:21:33 -0600421 if (trim)
422 deque_trim_left(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000423 }
Raymond Hettinger2b2b7532015-09-05 17:05:52 -0700424 if (PyErr_Occurred()) {
425 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000426 return NULL;
Raymond Hettinger2b2b7532015-09-05 17:05:52 -0700427 }
428 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000429 Py_RETURN_NONE;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000430}
431
Tim Peters1065f752004-10-01 01:03:29 +0000432PyDoc_STRVAR(extend_doc,
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000433"Extend the right side of the deque with elements from the iterable");
434
435static PyObject *
436deque_extendleft(dequeobject *deque, PyObject *iterable)
437{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000438 PyObject *it, *item;
Raymond Hettinger0e14e662015-09-19 00:21:33 -0600439 int trim = (deque->maxlen != -1);
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000440
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000441 /* Handle case where id(deque) == id(iterable) */
442 if ((PyObject *)deque == iterable) {
443 PyObject *result;
444 PyObject *s = PySequence_List(iterable);
445 if (s == NULL)
446 return NULL;
447 result = deque_extendleft(deque, s);
448 Py_DECREF(s);
449 return result;
450 }
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000451
Raymond Hettingerd9c116c2013-07-09 00:13:21 -0700452 /* Space saving heuristic. Start filling from the right */
453 if (Py_SIZE(deque) == 0) {
454 assert(deque->leftblock == deque->rightblock);
455 assert(deque->leftindex == deque->rightindex+1);
456 deque->leftindex = BLOCKLEN - 1;
457 deque->rightindex = BLOCKLEN - 2;
458 }
459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 it = PyObject_GetIter(iterable);
461 if (it == NULL)
462 return NULL;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000463
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000464 if (deque->maxlen == 0)
465 return consume_iterator(it);
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000466
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000467 while ((item = PyIter_Next(it)) != NULL) {
468 deque->state++;
469 if (deque->leftindex == 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000470 block *b = newblock(Py_SIZE(deque));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 if (b == NULL) {
472 Py_DECREF(item);
473 Py_DECREF(it);
474 return NULL;
475 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000476 b->rightlink = deque->leftblock;
477 CHECK_END(deque->leftblock->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 deque->leftblock->leftlink = b;
479 deque->leftblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000480 MARK_END(b->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000481 deque->leftindex = BLOCKLEN;
482 }
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000483 Py_SIZE(deque)++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 deque->leftindex--;
485 deque->leftblock->data[deque->leftindex] = item;
Raymond Hettinger0e14e662015-09-19 00:21:33 -0600486 if (trim)
487 deque_trim_right(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 }
Raymond Hettinger2b2b7532015-09-05 17:05:52 -0700489 if (PyErr_Occurred()) {
490 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000491 return NULL;
Raymond Hettinger2b2b7532015-09-05 17:05:52 -0700492 }
493 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 Py_RETURN_NONE;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000495}
496
Tim Peters1065f752004-10-01 01:03:29 +0000497PyDoc_STRVAR(extendleft_doc,
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000498"Extend the left side of the deque with elements from the iterable");
499
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000500static PyObject *
501deque_inplace_concat(dequeobject *deque, PyObject *other)
502{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000503 PyObject *result;
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000505 result = deque_extend(deque, other);
506 if (result == NULL)
507 return result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 Py_INCREF(deque);
Raymond Hettinger2b2b7532015-09-05 17:05:52 -0700509 Py_DECREF(result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 return (PyObject *)deque;
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000511}
512
Raymond Hettinger41290a62015-03-31 08:12:23 -0700513static PyObject *deque_copy(PyObject *deque);
514
515static PyObject *
516deque_concat(dequeobject *deque, PyObject *other)
517{
Benjamin Peterson1a629212015-04-04 10:52:36 -0400518 PyObject *new_deque, *result;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700519 int rv;
520
521 rv = PyObject_IsInstance(other, (PyObject *)&deque_type);
522 if (rv <= 0) {
523 if (rv == 0) {
524 PyErr_Format(PyExc_TypeError,
525 "can only concatenate deque (not \"%.200s\") to deque",
526 other->ob_type->tp_name);
527 }
528 return NULL;
529 }
530
531 new_deque = deque_copy((PyObject *)deque);
532 if (new_deque == NULL)
533 return NULL;
Benjamin Peterson1a629212015-04-04 10:52:36 -0400534 result = deque_extend((dequeobject *)new_deque, other);
535 if (result == NULL) {
536 Py_DECREF(new_deque);
537 return NULL;
538 }
539 Py_DECREF(result);
540 return new_deque;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700541}
542
543static void deque_clear(dequeobject *deque);
544
545static PyObject *
Raymond Hettinger41290a62015-03-31 08:12:23 -0700546deque_inplace_repeat(dequeobject *deque, Py_ssize_t n)
547{
548 Py_ssize_t i, size;
549 PyObject *seq;
550 PyObject *rv;
551
552 size = Py_SIZE(deque);
553 if (size == 0 || n == 1) {
554 Py_INCREF(deque);
555 return (PyObject *)deque;
556 }
557
558 if (n <= 0) {
559 deque_clear(deque);
560 Py_INCREF(deque);
561 return (PyObject *)deque;
562 }
563
Raymond Hettinger41290a62015-03-31 08:12:23 -0700564 if (size == 1) {
565 /* common case, repeating a single element */
566 PyObject *item = deque->leftblock->data[deque->leftindex];
567
568 if (deque->maxlen != -1 && n > deque->maxlen)
569 n = deque->maxlen;
570
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400571 if (n > MAX_DEQUE_LEN)
572 return PyErr_NoMemory();
573
Raymond Hettinger67c78b52015-09-12 11:00:20 -0400574 deque->state++;
Raymond Hettingerad262252015-09-14 01:03:04 -0400575 for (i = 0 ; i < n-1 ; ) {
Raymond Hettinger67c78b52015-09-12 11:00:20 -0400576 if (deque->rightindex == BLOCKLEN - 1) {
577 block *b = newblock(Py_SIZE(deque) + i);
578 if (b == NULL) {
579 Py_SIZE(deque) += i;
580 return NULL;
581 }
582 b->leftlink = deque->rightblock;
583 CHECK_END(deque->rightblock->rightlink);
584 deque->rightblock->rightlink = b;
585 deque->rightblock = b;
586 MARK_END(b->rightlink);
587 deque->rightindex = -1;
588 }
Raymond Hettingerad262252015-09-14 01:03:04 -0400589 for ( ; i < n-1 && deque->rightindex != BLOCKLEN - 1 ; i++) {
590 deque->rightindex++;
591 Py_INCREF(item);
592 deque->rightblock->data[deque->rightindex] = item;
593 }
Raymond Hettinger41290a62015-03-31 08:12:23 -0700594 }
Raymond Hettinger67c78b52015-09-12 11:00:20 -0400595 Py_SIZE(deque) += i;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700596 Py_INCREF(deque);
597 return (PyObject *)deque;
598 }
599
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400600 if ((size_t)size > MAX_DEQUE_LEN / (size_t)n) {
601 return PyErr_NoMemory();
602 }
603
Raymond Hettinger41290a62015-03-31 08:12:23 -0700604 seq = PySequence_List((PyObject *)deque);
605 if (seq == NULL)
606 return seq;
607
608 for (i = 0 ; i < n-1 ; i++) {
609 rv = deque_extend(deque, seq);
610 if (rv == NULL) {
611 Py_DECREF(seq);
612 return NULL;
613 }
614 Py_DECREF(rv);
615 }
616 Py_INCREF(deque);
617 Py_DECREF(seq);
618 return (PyObject *)deque;
619}
620
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400621static PyObject *
622deque_repeat(dequeobject *deque, Py_ssize_t n)
623{
624 dequeobject *new_deque;
Raymond Hettinger95e2cc52015-09-13 02:41:18 -0400625 PyObject *rv;
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400626
627 new_deque = (dequeobject *)deque_copy((PyObject *) deque);
628 if (new_deque == NULL)
629 return NULL;
Raymond Hettinger95e2cc52015-09-13 02:41:18 -0400630 rv = deque_inplace_repeat(new_deque, n);
631 Py_DECREF(new_deque);
632 return rv;
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400633}
634
Raymond Hettinger54023152014-04-23 00:58:48 -0700635/* The rotate() method is part of the public API and is used internally
636as a primitive for other methods.
637
638Rotation by 1 or -1 is a common case, so any optimizations for high
639volume rotations should take care not to penalize the common case.
640
641Conceptually, a rotate by one is equivalent to a pop on one side and an
642append on the other. However, a pop/append pair is unnecessarily slow
643because it requires a incref/decref pair for an object located randomly
644in memory. It is better to just move the object pointer from one block
645to the next without changing the reference count.
646
647When moving batches of pointers, it is tempting to use memcpy() but that
648proved to be slower than a simple loop for a variety of reasons.
649Memcpy() cannot know in advance that we're copying pointers instead of
650bytes, that the source and destination are pointer aligned and
651non-overlapping, that moving just one pointer is a common case, that we
652never need to move more than BLOCKLEN pointers, and that at least one
653pointer is always moved.
654
655For high volume rotations, newblock() and freeblock() are never called
656more than once. Previously emptied blocks are immediately reused as a
657destination block. If a block is left-over at the end, it is freed.
658*/
659
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000660static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000661_deque_rotate(dequeobject *deque, Py_ssize_t n)
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000662{
Raymond Hettinger3959af92013-07-13 02:34:08 -0700663 block *b = NULL;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700664 block *leftblock = deque->leftblock;
665 block *rightblock = deque->rightblock;
666 Py_ssize_t leftindex = deque->leftindex;
667 Py_ssize_t rightindex = deque->rightindex;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000668 Py_ssize_t len=Py_SIZE(deque), halflen=len>>1;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700669 int rv = -1;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000670
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800671 if (len <= 1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000672 return 0;
673 if (n > halflen || n < -halflen) {
674 n %= len;
675 if (n > halflen)
676 n -= len;
677 else if (n < -halflen)
678 n += len;
679 }
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500680 assert(len > 1);
Raymond Hettingera4409c12013-02-04 00:08:12 -0500681 assert(-halflen <= n && n <= halflen);
Raymond Hettinger231ee4d2013-02-02 11:24:43 -0800682
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800683 deque->state++;
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500684 while (n > 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700685 if (leftindex == 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700686 if (b == NULL) {
Raymond Hettinger3959af92013-07-13 02:34:08 -0700687 b = newblock(len);
688 if (b == NULL)
689 goto done;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700690 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000691 b->rightlink = leftblock;
692 CHECK_END(leftblock->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700693 leftblock->leftlink = b;
694 leftblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000695 MARK_END(b->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700696 leftindex = BLOCKLEN;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700697 b = NULL;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800698 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700699 assert(leftindex > 0);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700700 {
701 PyObject **src, **dest;
702 Py_ssize_t m = n;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800703
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700704 if (m > rightindex + 1)
705 m = rightindex + 1;
706 if (m > leftindex)
707 m = leftindex;
708 assert (m > 0 && m <= len);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700709 rightindex -= m;
710 leftindex -= m;
Raymond Hettinger0e259f12015-02-01 22:53:41 -0800711 src = &rightblock->data[rightindex + 1];
712 dest = &leftblock->data[leftindex];
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700713 n -= m;
Raymond Hettinger840533b2013-07-13 17:03:58 -0700714 do {
Raymond Hettinger0e259f12015-02-01 22:53:41 -0800715 *(dest++) = *(src++);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700716 } while (--m);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700717 }
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -0700718 if (rightindex < 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700719 assert(leftblock != rightblock);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700720 assert(b == NULL);
Raymond Hettinger3959af92013-07-13 02:34:08 -0700721 b = rightblock;
Raymond Hettingerb97cc492013-07-21 01:51:07 -0700722 CHECK_NOT_END(rightblock->leftlink);
723 rightblock = rightblock->leftlink;
724 MARK_END(rightblock->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700725 rightindex = BLOCKLEN - 1;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800726 }
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800727 }
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500728 while (n < 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700729 if (rightindex == BLOCKLEN - 1) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700730 if (b == NULL) {
Raymond Hettinger3959af92013-07-13 02:34:08 -0700731 b = newblock(len);
732 if (b == NULL)
733 goto done;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700734 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000735 b->leftlink = rightblock;
736 CHECK_END(rightblock->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700737 rightblock->rightlink = b;
738 rightblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000739 MARK_END(b->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700740 rightindex = -1;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700741 b = NULL;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800742 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700743 assert (rightindex < BLOCKLEN - 1);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700744 {
745 PyObject **src, **dest;
746 Py_ssize_t m = -n;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800747
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700748 if (m > BLOCKLEN - leftindex)
749 m = BLOCKLEN - leftindex;
750 if (m > BLOCKLEN - 1 - rightindex)
751 m = BLOCKLEN - 1 - rightindex;
752 assert (m > 0 && m <= len);
753 src = &leftblock->data[leftindex];
754 dest = &rightblock->data[rightindex + 1];
755 leftindex += m;
756 rightindex += m;
757 n += m;
Raymond Hettinger840533b2013-07-13 17:03:58 -0700758 do {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700759 *(dest++) = *(src++);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700760 } while (--m);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700761 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700762 if (leftindex == BLOCKLEN) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700763 assert(leftblock != rightblock);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700764 assert(b == NULL);
Raymond Hettinger3959af92013-07-13 02:34:08 -0700765 b = leftblock;
Raymond Hettingerb97cc492013-07-21 01:51:07 -0700766 CHECK_NOT_END(leftblock->rightlink);
767 leftblock = leftblock->rightlink;
768 MARK_END(leftblock->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700769 leftindex = 0;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800770 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000771 }
Raymond Hettinger3959af92013-07-13 02:34:08 -0700772 rv = 0;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700773done:
Raymond Hettinger3959af92013-07-13 02:34:08 -0700774 if (b != NULL)
775 freeblock(b);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700776 deque->leftblock = leftblock;
777 deque->rightblock = rightblock;
778 deque->leftindex = leftindex;
779 deque->rightindex = rightindex;
780
781 return rv;
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000782}
783
784static PyObject *
785deque_rotate(dequeobject *deque, PyObject *args)
786{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 Py_ssize_t n=1;
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 if (!PyArg_ParseTuple(args, "|n:rotate", &n))
790 return NULL;
Raymond Hettinger6921c132015-03-21 02:03:40 -0700791 if (!_deque_rotate(deque, n))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000792 Py_RETURN_NONE;
793 return NULL;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000794}
795
Tim Peters1065f752004-10-01 01:03:29 +0000796PyDoc_STRVAR(rotate_doc,
Raymond Hettingeree33b272004-02-08 04:05:26 +0000797"Rotate the deque n steps to the right (default n=1). If n is negative, rotates left.");
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000798
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000799static PyObject *
800deque_reverse(dequeobject *deque, PyObject *unused)
801{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000802 block *leftblock = deque->leftblock;
803 block *rightblock = deque->rightblock;
804 Py_ssize_t leftindex = deque->leftindex;
805 Py_ssize_t rightindex = deque->rightindex;
Raymond Hettingercfe5b6c2015-07-20 00:25:50 -0400806 Py_ssize_t n = Py_SIZE(deque) >> 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000807 PyObject *tmp;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000808
Raymond Hettinger7a237232015-09-22 01:20:36 -0700809 while (n-- > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000810 /* Validate that pointers haven't met in the middle */
811 assert(leftblock != rightblock || leftindex < rightindex);
Raymond Hettinger82df9252013-07-07 01:43:42 -1000812 CHECK_NOT_END(leftblock);
813 CHECK_NOT_END(rightblock);
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000814
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000815 /* Swap */
816 tmp = leftblock->data[leftindex];
817 leftblock->data[leftindex] = rightblock->data[rightindex];
818 rightblock->data[rightindex] = tmp;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000819
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000820 /* Advance left block/index pair */
821 leftindex++;
822 if (leftindex == BLOCKLEN) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 leftblock = leftblock->rightlink;
824 leftindex = 0;
825 }
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000826
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000827 /* Step backwards with the right block/index pair */
828 rightindex--;
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -0700829 if (rightindex < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 rightblock = rightblock->leftlink;
831 rightindex = BLOCKLEN - 1;
832 }
833 }
834 Py_RETURN_NONE;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000835}
836
837PyDoc_STRVAR(reverse_doc,
838"D.reverse() -- reverse *IN PLACE*");
839
Raymond Hettinger44459de2010-04-03 23:20:46 +0000840static PyObject *
841deque_count(dequeobject *deque, PyObject *v)
842{
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000843 block *b = deque->leftblock;
844 Py_ssize_t index = deque->leftindex;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000845 Py_ssize_t n = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000846 Py_ssize_t count = 0;
Raymond Hettingerf9d9c792015-03-02 22:47:46 -0800847 size_t start_state = deque->state;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 PyObject *item;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 int cmp;
Raymond Hettinger44459de2010-04-03 23:20:46 +0000850
Raymond Hettinger3a1a8d02015-09-23 02:42:02 -0700851 while (n--) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000852 CHECK_NOT_END(b);
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000853 item = b->data[index];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000854 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
855 if (cmp > 0)
856 count++;
857 else if (cmp < 0)
858 return NULL;
Raymond Hettinger44459de2010-04-03 23:20:46 +0000859
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000860 if (start_state != deque->state) {
861 PyErr_SetString(PyExc_RuntimeError,
862 "deque mutated during iteration");
863 return NULL;
864 }
Raymond Hettinger44459de2010-04-03 23:20:46 +0000865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 /* Advance left block/index pair */
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000867 index++;
868 if (index == BLOCKLEN) {
869 b = b->rightlink;
870 index = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000871 }
872 }
873 return PyLong_FromSsize_t(count);
Raymond Hettinger44459de2010-04-03 23:20:46 +0000874}
875
876PyDoc_STRVAR(count_doc,
877"D.count(value) -> integer -- return number of occurrences of value");
878
Raymond Hettinger39dadf72015-03-20 16:38:56 -0700879static int
880deque_contains(dequeobject *deque, PyObject *v)
881{
882 block *b = deque->leftblock;
883 Py_ssize_t index = deque->leftindex;
884 Py_ssize_t n = Py_SIZE(deque);
Raymond Hettinger39dadf72015-03-20 16:38:56 -0700885 size_t start_state = deque->state;
886 PyObject *item;
887 int cmp;
888
Raymond Hettinger3a1a8d02015-09-23 02:42:02 -0700889 while (n--) {
Raymond Hettinger39dadf72015-03-20 16:38:56 -0700890 CHECK_NOT_END(b);
891 item = b->data[index];
892 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
893 if (cmp) {
894 return cmp;
895 }
896 if (start_state != deque->state) {
897 PyErr_SetString(PyExc_RuntimeError,
898 "deque mutated during iteration");
899 return -1;
900 }
901 index++;
902 if (index == BLOCKLEN) {
903 b = b->rightlink;
904 index = 0;
905 }
906 }
907 return 0;
908}
909
Martin v. Löwis18e16552006-02-15 17:27:45 +0000910static Py_ssize_t
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000911deque_len(dequeobject *deque)
912{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000913 return Py_SIZE(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000914}
915
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000916static PyObject *
Raymond Hettinger32ea1652015-03-21 01:37:37 -0700917deque_index(dequeobject *deque, PyObject *args)
918{
919 Py_ssize_t i, start=0, stop=Py_SIZE(deque);
920 PyObject *v, *item;
921 block *b = deque->leftblock;
922 Py_ssize_t index = deque->leftindex;
923 size_t start_state = deque->state;
924
925 if (!PyArg_ParseTuple(args, "O|O&O&:index", &v,
926 _PyEval_SliceIndex, &start,
927 _PyEval_SliceIndex, &stop))
928 return NULL;
929 if (start < 0) {
930 start += Py_SIZE(deque);
931 if (start < 0)
932 start = 0;
933 }
934 if (stop < 0) {
935 stop += Py_SIZE(deque);
936 if (stop < 0)
937 stop = 0;
938 }
Raymond Hettinger87674ec2015-08-26 08:08:38 -0700939 if (stop > Py_SIZE(deque))
940 stop = Py_SIZE(deque);
Raymond Hettinger32ea1652015-03-21 01:37:37 -0700941
942 for (i=0 ; i<stop ; i++) {
943 if (i >= start) {
944 int cmp;
945 CHECK_NOT_END(b);
946 item = b->data[index];
947 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
948 if (cmp > 0)
949 return PyLong_FromSsize_t(i);
950 else if (cmp < 0)
951 return NULL;
952 if (start_state != deque->state) {
953 PyErr_SetString(PyExc_RuntimeError,
954 "deque mutated during iteration");
955 return NULL;
956 }
957 }
958 index++;
959 if (index == BLOCKLEN) {
960 b = b->rightlink;
961 index = 0;
962 }
963 }
964 PyErr_Format(PyExc_ValueError, "%R is not in deque", v);
965 return NULL;
966}
967
968PyDoc_STRVAR(index_doc,
969"D.index(value, [start, [stop]]) -> integer -- return first index of value.\n"
970"Raises ValueError if the value is not present.");
971
Raymond Hettinger551350a2015-03-24 00:19:53 -0700972/* insert(), remove(), and delitem() are implemented in terms of
973 rotate() for simplicity and reasonable performance near the end
974 points. If for some reason these methods become popular, it is not
975 hard to re-implement this using direct data movement (similar to
976 the code used in list slice assignments) and achieve a performance
Raymond Hettingerfef9c1b2015-03-24 21:12:57 -0700977 boost (by moving each pointer only once instead of twice).
Raymond Hettinger551350a2015-03-24 00:19:53 -0700978*/
979
Raymond Hettinger32ea1652015-03-21 01:37:37 -0700980static PyObject *
981deque_insert(dequeobject *deque, PyObject *args)
982{
983 Py_ssize_t index;
984 Py_ssize_t n = Py_SIZE(deque);
985 PyObject *value;
986 PyObject *rv;
987
988 if (!PyArg_ParseTuple(args, "nO:insert", &index, &value))
989 return NULL;
990 if (index >= n)
991 return deque_append(deque, value);
992 if (index <= -n || index == 0)
993 return deque_appendleft(deque, value);
994 if (_deque_rotate(deque, -index))
995 return NULL;
996 if (index < 0)
997 rv = deque_append(deque, value);
998 else
999 rv = deque_appendleft(deque, value);
1000 if (rv == NULL)
1001 return NULL;
1002 Py_DECREF(rv);
1003 if (_deque_rotate(deque, index))
1004 return NULL;
1005 Py_RETURN_NONE;
1006}
1007
1008PyDoc_STRVAR(insert_doc,
1009"D.insert(index, object) -- insert object before index");
1010
1011static PyObject *
Raymond Hettinger4aec61e2005-03-18 21:20:23 +00001012deque_remove(dequeobject *deque, PyObject *value)
1013{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001014 Py_ssize_t i, n=Py_SIZE(deque);
Raymond Hettinger4aec61e2005-03-18 21:20:23 +00001015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 for (i=0 ; i<n ; i++) {
1017 PyObject *item = deque->leftblock->data[deque->leftindex];
1018 int cmp = PyObject_RichCompareBool(item, value, Py_EQ);
Raymond Hettingerd73202c2005-03-19 00:00:51 +00001019
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001020 if (Py_SIZE(deque) != n) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001021 PyErr_SetString(PyExc_IndexError,
1022 "deque mutated during remove().");
1023 return NULL;
1024 }
1025 if (cmp > 0) {
1026 PyObject *tgt = deque_popleft(deque, NULL);
1027 assert (tgt != NULL);
Raymond Hettinger6921c132015-03-21 02:03:40 -07001028 if (_deque_rotate(deque, i))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 return NULL;
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001030 Py_DECREF(tgt);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 Py_RETURN_NONE;
1032 }
1033 else if (cmp < 0) {
1034 _deque_rotate(deque, i);
1035 return NULL;
1036 }
1037 _deque_rotate(deque, -1);
1038 }
1039 PyErr_SetString(PyExc_ValueError, "deque.remove(x): x not in deque");
1040 return NULL;
Raymond Hettinger4aec61e2005-03-18 21:20:23 +00001041}
1042
1043PyDoc_STRVAR(remove_doc,
1044"D.remove(value) -- remove first occurrence of value.");
1045
Benjamin Peterson0e5c48a2013-01-12 21:22:18 -05001046static void
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001047deque_clear(dequeobject *deque)
1048{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 PyObject *item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001050
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001051 while (Py_SIZE(deque)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 item = deque_pop(deque, NULL);
1053 assert (item != NULL);
1054 Py_DECREF(item);
1055 }
Raymond Hettinger87e69122015-03-02 23:32:02 -08001056 assert(deque->leftblock == deque->rightblock);
1057 assert(deque->leftindex - 1 == deque->rightindex);
1058 assert(Py_SIZE(deque) == 0);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001059}
1060
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001061static int
1062valid_index(Py_ssize_t i, Py_ssize_t limit)
1063{
Raymond Hettinger12f896c2015-07-31 12:03:20 -07001064 /* The cast to size_t lets us use just a single comparison
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001065 to check whether i is in the range: 0 <= i < limit */
1066 return (size_t) i < (size_t) limit;
1067}
1068
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001069static PyObject *
Benjamin Petersond6313712008-07-31 16:23:04 +00001070deque_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001071{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001072 block *b;
1073 PyObject *item;
1074 Py_ssize_t n, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001075
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001076 if (!valid_index(i, Py_SIZE(deque))) {
1077 PyErr_SetString(PyExc_IndexError, "deque index out of range");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 return NULL;
1079 }
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001080
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001081 if (i == 0) {
1082 i = deque->leftindex;
1083 b = deque->leftblock;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001084 } else if (i == Py_SIZE(deque) - 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001085 i = deque->rightindex;
1086 b = deque->rightblock;
1087 } else {
1088 i += deque->leftindex;
Raymond Hettingerc2083082015-02-28 23:29:16 -08001089 n = (Py_ssize_t)((size_t) i / BLOCKLEN);
1090 i = (Py_ssize_t)((size_t) i % BLOCKLEN);
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001091 if (index < (Py_SIZE(deque) >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001092 b = deque->leftblock;
1093 while (n--)
1094 b = b->rightlink;
1095 } else {
Raymond Hettinger63d1ff22015-02-28 07:41:30 -08001096 n = (Py_ssize_t)(
Raymond Hettingerc2083082015-02-28 23:29:16 -08001097 ((size_t)(deque->leftindex + Py_SIZE(deque) - 1))
Raymond Hettinger63d1ff22015-02-28 07:41:30 -08001098 / BLOCKLEN - n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001099 b = deque->rightblock;
1100 while (n--)
1101 b = b->leftlink;
1102 }
1103 }
1104 item = b->data[i];
1105 Py_INCREF(item);
1106 return item;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001107}
1108
1109static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001110deque_del_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001111{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001112 PyObject *item;
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001113 int rv;
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001114
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001115 assert (i >= 0 && i < Py_SIZE(deque));
Raymond Hettinger6921c132015-03-21 02:03:40 -07001116 if (_deque_rotate(deque, -i))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001117 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001118 item = deque_popleft(deque, NULL);
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001119 rv = _deque_rotate(deque, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001120 assert (item != NULL);
1121 Py_DECREF(item);
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001122 return rv;
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001123}
1124
1125static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001126deque_ass_item(dequeobject *deque, Py_ssize_t i, PyObject *v)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001127{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001128 PyObject *old_value;
1129 block *b;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001130 Py_ssize_t n, len=Py_SIZE(deque), halflen=(len+1)>>1, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001131
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001132 if (!valid_index(i, len)) {
1133 PyErr_SetString(PyExc_IndexError, "deque index out of range");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001134 return -1;
1135 }
1136 if (v == NULL)
1137 return deque_del_item(deque, i);
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001139 i += deque->leftindex;
Raymond Hettingerc2083082015-02-28 23:29:16 -08001140 n = (Py_ssize_t)((size_t) i / BLOCKLEN);
1141 i = (Py_ssize_t)((size_t) i % BLOCKLEN);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142 if (index <= halflen) {
1143 b = deque->leftblock;
1144 while (n--)
1145 b = b->rightlink;
1146 } else {
Raymond Hettingera473b9d2015-02-28 17:49:47 -08001147 n = (Py_ssize_t)(
Raymond Hettingerc2083082015-02-28 23:29:16 -08001148 ((size_t)(deque->leftindex + Py_SIZE(deque) - 1))
Raymond Hettingera473b9d2015-02-28 17:49:47 -08001149 / BLOCKLEN - n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001150 b = deque->rightblock;
1151 while (n--)
1152 b = b->leftlink;
1153 }
1154 Py_INCREF(v);
1155 old_value = b->data[i];
1156 b->data[i] = v;
1157 Py_DECREF(old_value);
1158 return 0;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001159}
1160
1161static PyObject *
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001162deque_clearmethod(dequeobject *deque)
1163{
Benjamin Peterson0e5c48a2013-01-12 21:22:18 -05001164 deque_clear(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001165 Py_RETURN_NONE;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001166}
1167
1168PyDoc_STRVAR(clear_doc, "Remove all elements from the deque.");
1169
1170static void
1171deque_dealloc(dequeobject *deque)
1172{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001173 PyObject_GC_UnTrack(deque);
1174 if (deque->weakreflist != NULL)
1175 PyObject_ClearWeakRefs((PyObject *) deque);
1176 if (deque->leftblock != NULL) {
1177 deque_clear(deque);
1178 assert(deque->leftblock != NULL);
1179 freeblock(deque->leftblock);
1180 }
1181 deque->leftblock = NULL;
1182 deque->rightblock = NULL;
1183 Py_TYPE(deque)->tp_free(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001184}
1185
1186static int
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001187deque_traverse(dequeobject *deque, visitproc visit, void *arg)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001188{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001189 block *b;
1190 PyObject *item;
1191 Py_ssize_t index;
1192 Py_ssize_t indexlo = deque->leftindex;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001193
Raymond Hettinger5bfa8672013-07-06 11:58:09 -10001194 for (b = deque->leftblock; b != deque->rightblock; b = b->rightlink) {
1195 for (index = indexlo; index < BLOCKLEN ; index++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001196 item = b->data[index];
1197 Py_VISIT(item);
1198 }
1199 indexlo = 0;
1200 }
Raymond Hettinger5bfa8672013-07-06 11:58:09 -10001201 for (index = indexlo; index <= deque->rightindex; index++) {
1202 item = b->data[index];
1203 Py_VISIT(item);
1204 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001205 return 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001206}
1207
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001208static PyObject *
1209deque_copy(PyObject *deque)
1210{
Raymond Hettingeraed88302015-09-19 09:05:42 -07001211 dequeobject *old_deque = (dequeobject *)deque;
Raymond Hettingere4f34672015-09-13 19:27:01 -04001212 if (Py_TYPE(deque) == &deque_type) {
1213 dequeobject *new_deque;
1214 PyObject *rv;
1215
1216 new_deque = (dequeobject *)deque_new(&deque_type, (PyObject *)NULL, (PyObject *)NULL);
1217 if (new_deque == NULL)
1218 return NULL;
Raymond Hettingeraed88302015-09-19 09:05:42 -07001219 new_deque->maxlen = old_deque->maxlen;
1220 /* Fast path for the deque_repeat() common case where len(deque) == 1 */
1221 if (Py_SIZE(deque) == 1 && new_deque->maxlen != 0) {
1222 PyObject *item = old_deque->leftblock->data[old_deque->leftindex];
1223 rv = deque_append(new_deque, item);
1224 } else {
1225 rv = deque_extend(new_deque, deque);
1226 }
Raymond Hettingere4f34672015-09-13 19:27:01 -04001227 if (rv != NULL) {
1228 Py_DECREF(rv);
1229 return (PyObject *)new_deque;
1230 }
1231 Py_DECREF(new_deque);
1232 return NULL;
1233 }
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -07001234 if (old_deque->maxlen < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001235 return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "O", deque, NULL);
1236 else
1237 return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "Oi",
Raymond Hettingeraed88302015-09-19 09:05:42 -07001238 deque, old_deque->maxlen, NULL);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001239}
1240
1241PyDoc_STRVAR(copy_doc, "Return a shallow copy of a deque.");
1242
1243static PyObject *
1244deque_reduce(dequeobject *deque)
1245{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001246 PyObject *dict, *result, *aslist;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001247 _Py_IDENTIFIER(__dict__);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001248
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001249 dict = _PyObject_GetAttrId((PyObject *)deque, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001250 if (dict == NULL)
1251 PyErr_Clear();
1252 aslist = PySequence_List((PyObject *)deque);
1253 if (aslist == NULL) {
1254 Py_XDECREF(dict);
1255 return NULL;
1256 }
1257 if (dict == NULL) {
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -07001258 if (deque->maxlen < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001259 result = Py_BuildValue("O(O)", Py_TYPE(deque), aslist);
1260 else
1261 result = Py_BuildValue("O(On)", Py_TYPE(deque), aslist, deque->maxlen);
1262 } else {
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -07001263 if (deque->maxlen < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001264 result = Py_BuildValue("O(OO)O", Py_TYPE(deque), aslist, Py_None, dict);
1265 else
1266 result = Py_BuildValue("O(On)O", Py_TYPE(deque), aslist, deque->maxlen, dict);
1267 }
1268 Py_XDECREF(dict);
1269 Py_DECREF(aslist);
1270 return result;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001271}
1272
1273PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
1274
1275static PyObject *
1276deque_repr(PyObject *deque)
1277{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001278 PyObject *aslist, *result;
1279 int i;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001281 i = Py_ReprEnter(deque);
1282 if (i != 0) {
1283 if (i < 0)
1284 return NULL;
1285 return PyUnicode_FromString("[...]");
1286 }
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001288 aslist = PySequence_List(deque);
1289 if (aslist == NULL) {
1290 Py_ReprLeave(deque);
1291 return NULL;
1292 }
1293 if (((dequeobject *)deque)->maxlen != -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001294 result = PyUnicode_FromFormat("deque(%R, maxlen=%zd)",
1295 aslist, ((dequeobject *)deque)->maxlen);
1296 else
1297 result = PyUnicode_FromFormat("deque(%R)", aslist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001298 Py_ReprLeave(deque);
Raymond Hettinger2b2b7532015-09-05 17:05:52 -07001299 Py_DECREF(aslist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001300 return result;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001301}
1302
Raymond Hettinger738ec902004-02-29 02:15:56 +00001303static PyObject *
1304deque_richcompare(PyObject *v, PyObject *w, int op)
1305{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001306 PyObject *it1=NULL, *it2=NULL, *x, *y;
1307 Py_ssize_t vs, ws;
1308 int b, cmp=-1;
Raymond Hettinger738ec902004-02-29 02:15:56 +00001309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001310 if (!PyObject_TypeCheck(v, &deque_type) ||
1311 !PyObject_TypeCheck(w, &deque_type)) {
Brian Curtindfc80e32011-08-10 20:28:54 -05001312 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001313 }
Raymond Hettinger738ec902004-02-29 02:15:56 +00001314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001315 /* Shortcuts */
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001316 vs = Py_SIZE((dequeobject *)v);
1317 ws = Py_SIZE((dequeobject *)w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001318 if (op == Py_EQ) {
1319 if (v == w)
1320 Py_RETURN_TRUE;
1321 if (vs != ws)
1322 Py_RETURN_FALSE;
1323 }
1324 if (op == Py_NE) {
1325 if (v == w)
1326 Py_RETURN_FALSE;
1327 if (vs != ws)
1328 Py_RETURN_TRUE;
1329 }
Raymond Hettinger738ec902004-02-29 02:15:56 +00001330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001331 /* Search for the first index where items are different */
1332 it1 = PyObject_GetIter(v);
1333 if (it1 == NULL)
1334 goto done;
1335 it2 = PyObject_GetIter(w);
1336 if (it2 == NULL)
1337 goto done;
1338 for (;;) {
1339 x = PyIter_Next(it1);
1340 if (x == NULL && PyErr_Occurred())
1341 goto done;
1342 y = PyIter_Next(it2);
1343 if (x == NULL || y == NULL)
1344 break;
1345 b = PyObject_RichCompareBool(x, y, Py_EQ);
1346 if (b == 0) {
1347 cmp = PyObject_RichCompareBool(x, y, op);
1348 Py_DECREF(x);
1349 Py_DECREF(y);
1350 goto done;
1351 }
1352 Py_DECREF(x);
1353 Py_DECREF(y);
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -07001354 if (b < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001355 goto done;
1356 }
1357 /* We reached the end of one deque or both */
1358 Py_XDECREF(x);
1359 Py_XDECREF(y);
1360 if (PyErr_Occurred())
1361 goto done;
1362 switch (op) {
1363 case Py_LT: cmp = y != NULL; break; /* if w was longer */
1364 case Py_LE: cmp = x == NULL; break; /* if v was not longer */
1365 case Py_EQ: cmp = x == y; break; /* if we reached the end of both */
1366 case Py_NE: cmp = x != y; break; /* if one deque continues */
1367 case Py_GT: cmp = x != NULL; break; /* if v was longer */
1368 case Py_GE: cmp = y == NULL; break; /* if w was not longer */
1369 }
Tim Peters1065f752004-10-01 01:03:29 +00001370
Raymond Hettinger738ec902004-02-29 02:15:56 +00001371done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001372 Py_XDECREF(it1);
1373 Py_XDECREF(it2);
1374 if (cmp == 1)
1375 Py_RETURN_TRUE;
1376 if (cmp == 0)
1377 Py_RETURN_FALSE;
1378 return NULL;
Raymond Hettinger738ec902004-02-29 02:15:56 +00001379}
1380
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001381static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001382deque_init(dequeobject *deque, PyObject *args, PyObject *kwdargs)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001383{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001384 PyObject *iterable = NULL;
1385 PyObject *maxlenobj = NULL;
1386 Py_ssize_t maxlen = -1;
1387 char *kwlist[] = {"iterable", "maxlen", 0};
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001389 if (!PyArg_ParseTupleAndKeywords(args, kwdargs, "|OO:deque", kwlist, &iterable, &maxlenobj))
1390 return -1;
1391 if (maxlenobj != NULL && maxlenobj != Py_None) {
1392 maxlen = PyLong_AsSsize_t(maxlenobj);
1393 if (maxlen == -1 && PyErr_Occurred())
1394 return -1;
1395 if (maxlen < 0) {
1396 PyErr_SetString(PyExc_ValueError, "maxlen must be non-negative");
1397 return -1;
1398 }
1399 }
1400 deque->maxlen = maxlen;
1401 deque_clear(deque);
1402 if (iterable != NULL) {
1403 PyObject *rv = deque_extend(deque, iterable);
1404 if (rv == NULL)
1405 return -1;
1406 Py_DECREF(rv);
1407 }
1408 return 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001409}
1410
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001411static PyObject *
Jesus Cea16e2fca2012-08-03 14:49:42 +02001412deque_sizeof(dequeobject *deque, void *unused)
1413{
1414 Py_ssize_t res;
1415 Py_ssize_t blocks;
1416
1417 res = sizeof(dequeobject);
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001418 blocks = (deque->leftindex + Py_SIZE(deque) + BLOCKLEN - 1) / BLOCKLEN;
1419 assert(deque->leftindex + Py_SIZE(deque) - 1 ==
Jesus Cea16e2fca2012-08-03 14:49:42 +02001420 (blocks - 1) * BLOCKLEN + deque->rightindex);
1421 res += blocks * sizeof(block);
1422 return PyLong_FromSsize_t(res);
1423}
1424
1425PyDoc_STRVAR(sizeof_doc,
1426"D.__sizeof__() -- size of D in memory, in bytes");
1427
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001428static int
1429deque_bool(dequeobject *deque)
1430{
1431 return Py_SIZE(deque) != 0;
1432}
1433
Jesus Cea16e2fca2012-08-03 14:49:42 +02001434static PyObject *
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001435deque_get_maxlen(dequeobject *deque)
1436{
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -07001437 if (deque->maxlen < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001438 Py_RETURN_NONE;
1439 return PyLong_FromSsize_t(deque->maxlen);
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001440}
1441
Raymond Hettinger41290a62015-03-31 08:12:23 -07001442
1443/* deque object ********************************************************/
1444
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001445static PyGetSetDef deque_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001446 {"maxlen", (getter)deque_get_maxlen, (setter)NULL,
1447 "maximum size of a deque or None if unbounded"},
1448 {0}
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001449};
1450
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001451static PySequenceMethods deque_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001452 (lenfunc)deque_len, /* sq_length */
Raymond Hettinger41290a62015-03-31 08:12:23 -07001453 (binaryfunc)deque_concat, /* sq_concat */
1454 (ssizeargfunc)deque_repeat, /* sq_repeat */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001455 (ssizeargfunc)deque_item, /* sq_item */
1456 0, /* sq_slice */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001457 (ssizeobjargproc)deque_ass_item, /* sq_ass_item */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001458 0, /* sq_ass_slice */
Raymond Hettinger39dadf72015-03-20 16:38:56 -07001459 (objobjproc)deque_contains, /* sq_contains */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001460 (binaryfunc)deque_inplace_concat, /* sq_inplace_concat */
Raymond Hettinger41290a62015-03-31 08:12:23 -07001461 (ssizeargfunc)deque_inplace_repeat, /* sq_inplace_repeat */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001462};
1463
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001464static PyNumberMethods deque_as_number = {
1465 0, /* nb_add */
1466 0, /* nb_subtract */
1467 0, /* nb_multiply */
1468 0, /* nb_remainder */
1469 0, /* nb_divmod */
1470 0, /* nb_power */
1471 0, /* nb_negative */
1472 0, /* nb_positive */
1473 0, /* nb_absolute */
1474 (inquiry)deque_bool, /* nb_bool */
1475 0, /* nb_invert */
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001476 };
1477
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001478static PyObject *deque_iter(dequeobject *deque);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001479static PyObject *deque_reviter(dequeobject *deque);
Tim Peters1065f752004-10-01 01:03:29 +00001480PyDoc_STRVAR(reversed_doc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001481 "D.__reversed__() -- return a reverse iterator over the deque");
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001482
1483static PyMethodDef deque_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001484 {"append", (PyCFunction)deque_append,
1485 METH_O, append_doc},
1486 {"appendleft", (PyCFunction)deque_appendleft,
1487 METH_O, appendleft_doc},
1488 {"clear", (PyCFunction)deque_clearmethod,
1489 METH_NOARGS, clear_doc},
1490 {"__copy__", (PyCFunction)deque_copy,
1491 METH_NOARGS, copy_doc},
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001492 {"copy", (PyCFunction)deque_copy,
1493 METH_NOARGS, copy_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001494 {"count", (PyCFunction)deque_count,
Raymond Hettinger0f6f9472015-03-21 01:42:10 -07001495 METH_O, count_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001496 {"extend", (PyCFunction)deque_extend,
1497 METH_O, extend_doc},
1498 {"extendleft", (PyCFunction)deque_extendleft,
1499 METH_O, extendleft_doc},
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001500 {"index", (PyCFunction)deque_index,
1501 METH_VARARGS, index_doc},
1502 {"insert", (PyCFunction)deque_insert,
1503 METH_VARARGS, insert_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001504 {"pop", (PyCFunction)deque_pop,
1505 METH_NOARGS, pop_doc},
1506 {"popleft", (PyCFunction)deque_popleft,
1507 METH_NOARGS, popleft_doc},
Raymond Hettinger0f6f9472015-03-21 01:42:10 -07001508 {"__reduce__", (PyCFunction)deque_reduce,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001509 METH_NOARGS, reduce_doc},
1510 {"remove", (PyCFunction)deque_remove,
1511 METH_O, remove_doc},
1512 {"__reversed__", (PyCFunction)deque_reviter,
1513 METH_NOARGS, reversed_doc},
1514 {"reverse", (PyCFunction)deque_reverse,
1515 METH_NOARGS, reverse_doc},
1516 {"rotate", (PyCFunction)deque_rotate,
Jesus Cea16e2fca2012-08-03 14:49:42 +02001517 METH_VARARGS, rotate_doc},
1518 {"__sizeof__", (PyCFunction)deque_sizeof,
1519 METH_NOARGS, sizeof_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001520 {NULL, NULL} /* sentinel */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001521};
1522
1523PyDoc_STRVAR(deque_doc,
Andrew Svetlov6a5c7c32012-10-31 11:50:40 +02001524"deque([iterable[, maxlen]]) --> deque object\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001525\n\
Raymond Hettinger41290a62015-03-31 08:12:23 -07001526A list-like sequence optimized for data accesses near its endpoints.");
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001527
Neal Norwitz87f10132004-02-29 15:40:53 +00001528static PyTypeObject deque_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001529 PyVarObject_HEAD_INIT(NULL, 0)
1530 "collections.deque", /* tp_name */
1531 sizeof(dequeobject), /* tp_basicsize */
1532 0, /* tp_itemsize */
1533 /* methods */
1534 (destructor)deque_dealloc, /* tp_dealloc */
1535 0, /* tp_print */
1536 0, /* tp_getattr */
1537 0, /* tp_setattr */
1538 0, /* tp_reserved */
1539 deque_repr, /* tp_repr */
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001540 &deque_as_number, /* tp_as_number */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001541 &deque_as_sequence, /* tp_as_sequence */
1542 0, /* tp_as_mapping */
Georg Brandlf038b322010-10-18 07:35:09 +00001543 PyObject_HashNotImplemented, /* tp_hash */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001544 0, /* tp_call */
1545 0, /* tp_str */
1546 PyObject_GenericGetAttr, /* tp_getattro */
1547 0, /* tp_setattro */
1548 0, /* tp_as_buffer */
1549 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
Georg Brandlf038b322010-10-18 07:35:09 +00001550 /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001551 deque_doc, /* tp_doc */
1552 (traverseproc)deque_traverse, /* tp_traverse */
1553 (inquiry)deque_clear, /* tp_clear */
1554 (richcmpfunc)deque_richcompare, /* tp_richcompare */
Georg Brandlf038b322010-10-18 07:35:09 +00001555 offsetof(dequeobject, weakreflist), /* tp_weaklistoffset*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001556 (getiterfunc)deque_iter, /* tp_iter */
1557 0, /* tp_iternext */
1558 deque_methods, /* tp_methods */
1559 0, /* tp_members */
Georg Brandlf038b322010-10-18 07:35:09 +00001560 deque_getset, /* tp_getset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001561 0, /* tp_base */
1562 0, /* tp_dict */
1563 0, /* tp_descr_get */
1564 0, /* tp_descr_set */
1565 0, /* tp_dictoffset */
1566 (initproc)deque_init, /* tp_init */
1567 PyType_GenericAlloc, /* tp_alloc */
1568 deque_new, /* tp_new */
1569 PyObject_GC_Del, /* tp_free */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001570};
1571
1572/*********************** Deque Iterator **************************/
1573
1574typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001575 PyObject_HEAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001576 block *b;
Raymond Hettinger87e69122015-03-02 23:32:02 -08001577 Py_ssize_t index;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001578 dequeobject *deque;
Raymond Hettingerf9d9c792015-03-02 22:47:46 -08001579 size_t state; /* state when the iterator is created */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001580 Py_ssize_t counter; /* number of items remaining for iteration */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001581} dequeiterobject;
1582
Martin v. Löwis59683e82008-06-13 07:50:45 +00001583static PyTypeObject dequeiter_type;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001584
1585static PyObject *
1586deque_iter(dequeobject *deque)
1587{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001588 dequeiterobject *it;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001590 it = PyObject_GC_New(dequeiterobject, &dequeiter_type);
1591 if (it == NULL)
1592 return NULL;
1593 it->b = deque->leftblock;
1594 it->index = deque->leftindex;
1595 Py_INCREF(deque);
1596 it->deque = deque;
1597 it->state = deque->state;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001598 it->counter = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001599 PyObject_GC_Track(it);
1600 return (PyObject *)it;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001601}
1602
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001603static int
1604dequeiter_traverse(dequeiterobject *dio, visitproc visit, void *arg)
1605{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001606 Py_VISIT(dio->deque);
1607 return 0;
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001608}
1609
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001610static void
1611dequeiter_dealloc(dequeiterobject *dio)
1612{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001613 Py_XDECREF(dio->deque);
1614 PyObject_GC_Del(dio);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001615}
1616
1617static PyObject *
1618dequeiter_next(dequeiterobject *it)
1619{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001620 PyObject *item;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001622 if (it->deque->state != it->state) {
1623 it->counter = 0;
1624 PyErr_SetString(PyExc_RuntimeError,
1625 "deque mutated during iteration");
1626 return NULL;
1627 }
1628 if (it->counter == 0)
1629 return NULL;
1630 assert (!(it->b == it->deque->rightblock &&
1631 it->index > it->deque->rightindex));
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001632
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001633 item = it->b->data[it->index];
1634 it->index++;
1635 it->counter--;
1636 if (it->index == BLOCKLEN && it->counter > 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -10001637 CHECK_NOT_END(it->b->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001638 it->b = it->b->rightlink;
1639 it->index = 0;
1640 }
1641 Py_INCREF(item);
1642 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001643}
1644
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001645static PyObject *
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001646dequeiter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1647{
1648 Py_ssize_t i, index=0;
1649 PyObject *deque;
1650 dequeiterobject *it;
1651 if (!PyArg_ParseTuple(args, "O!|n", &deque_type, &deque, &index))
1652 return NULL;
1653 assert(type == &dequeiter_type);
1654
1655 it = (dequeiterobject*)deque_iter((dequeobject *)deque);
1656 if (!it)
1657 return NULL;
1658 /* consume items from the queue */
1659 for(i=0; i<index; i++) {
1660 PyObject *item = dequeiter_next(it);
1661 if (item) {
1662 Py_DECREF(item);
1663 } else {
1664 if (it->counter) {
1665 Py_DECREF(it);
1666 return NULL;
1667 } else
1668 break;
1669 }
1670 }
1671 return (PyObject*)it;
1672}
1673
1674static PyObject *
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001675dequeiter_len(dequeiterobject *it)
1676{
Antoine Pitrou554f3342010-08-17 18:30:06 +00001677 return PyLong_FromSsize_t(it->counter);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001678}
1679
Armin Rigof5b3e362006-02-11 21:32:43 +00001680PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001681
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001682static PyObject *
1683dequeiter_reduce(dequeiterobject *it)
1684{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001685 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 +00001686}
1687
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001688static PyMethodDef dequeiter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001689 {"__length_hint__", (PyCFunction)dequeiter_len, METH_NOARGS, length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001690 {"__reduce__", (PyCFunction)dequeiter_reduce, METH_NOARGS, reduce_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001691 {NULL, NULL} /* sentinel */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001692};
1693
Martin v. Löwis59683e82008-06-13 07:50:45 +00001694static PyTypeObject dequeiter_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001695 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger87e69122015-03-02 23:32:02 -08001696 "_collections._deque_iterator", /* tp_name */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001697 sizeof(dequeiterobject), /* tp_basicsize */
1698 0, /* tp_itemsize */
1699 /* methods */
1700 (destructor)dequeiter_dealloc, /* tp_dealloc */
1701 0, /* tp_print */
1702 0, /* tp_getattr */
1703 0, /* tp_setattr */
1704 0, /* tp_reserved */
1705 0, /* tp_repr */
1706 0, /* tp_as_number */
1707 0, /* tp_as_sequence */
1708 0, /* tp_as_mapping */
1709 0, /* tp_hash */
1710 0, /* tp_call */
1711 0, /* tp_str */
1712 PyObject_GenericGetAttr, /* tp_getattro */
1713 0, /* tp_setattro */
1714 0, /* tp_as_buffer */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001715 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001716 0, /* tp_doc */
1717 (traverseproc)dequeiter_traverse, /* tp_traverse */
1718 0, /* tp_clear */
1719 0, /* tp_richcompare */
1720 0, /* tp_weaklistoffset */
1721 PyObject_SelfIter, /* tp_iter */
1722 (iternextfunc)dequeiter_next, /* tp_iternext */
1723 dequeiter_methods, /* tp_methods */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001724 0, /* tp_members */
1725 0, /* tp_getset */
1726 0, /* tp_base */
1727 0, /* tp_dict */
1728 0, /* tp_descr_get */
1729 0, /* tp_descr_set */
1730 0, /* tp_dictoffset */
1731 0, /* tp_init */
1732 0, /* tp_alloc */
1733 dequeiter_new, /* tp_new */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001734 0,
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001735};
1736
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001737/*********************** Deque Reverse Iterator **************************/
1738
Martin v. Löwis59683e82008-06-13 07:50:45 +00001739static PyTypeObject dequereviter_type;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001740
1741static PyObject *
1742deque_reviter(dequeobject *deque)
1743{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001744 dequeiterobject *it;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001745
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001746 it = PyObject_GC_New(dequeiterobject, &dequereviter_type);
1747 if (it == NULL)
1748 return NULL;
1749 it->b = deque->rightblock;
1750 it->index = deque->rightindex;
1751 Py_INCREF(deque);
1752 it->deque = deque;
1753 it->state = deque->state;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001754 it->counter = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001755 PyObject_GC_Track(it);
1756 return (PyObject *)it;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001757}
1758
1759static PyObject *
1760dequereviter_next(dequeiterobject *it)
1761{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001762 PyObject *item;
1763 if (it->counter == 0)
1764 return NULL;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001765
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001766 if (it->deque->state != it->state) {
1767 it->counter = 0;
1768 PyErr_SetString(PyExc_RuntimeError,
1769 "deque mutated during iteration");
1770 return NULL;
1771 }
1772 assert (!(it->b == it->deque->leftblock &&
1773 it->index < it->deque->leftindex));
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001774
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001775 item = it->b->data[it->index];
1776 it->index--;
1777 it->counter--;
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -07001778 if (it->index < 0 && it->counter > 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -10001779 CHECK_NOT_END(it->b->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001780 it->b = it->b->leftlink;
1781 it->index = BLOCKLEN - 1;
1782 }
1783 Py_INCREF(item);
1784 return item;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001785}
1786
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001787static PyObject *
1788dequereviter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1789{
1790 Py_ssize_t i, index=0;
1791 PyObject *deque;
1792 dequeiterobject *it;
1793 if (!PyArg_ParseTuple(args, "O!|n", &deque_type, &deque, &index))
1794 return NULL;
1795 assert(type == &dequereviter_type);
1796
1797 it = (dequeiterobject*)deque_reviter((dequeobject *)deque);
1798 if (!it)
1799 return NULL;
1800 /* consume items from the queue */
1801 for(i=0; i<index; i++) {
1802 PyObject *item = dequereviter_next(it);
1803 if (item) {
1804 Py_DECREF(item);
1805 } else {
1806 if (it->counter) {
1807 Py_DECREF(it);
1808 return NULL;
1809 } else
1810 break;
1811 }
1812 }
1813 return (PyObject*)it;
1814}
1815
Martin v. Löwis59683e82008-06-13 07:50:45 +00001816static PyTypeObject dequereviter_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001817 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger87e69122015-03-02 23:32:02 -08001818 "_collections._deque_reverse_iterator", /* tp_name */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001819 sizeof(dequeiterobject), /* tp_basicsize */
1820 0, /* tp_itemsize */
1821 /* methods */
1822 (destructor)dequeiter_dealloc, /* tp_dealloc */
1823 0, /* tp_print */
1824 0, /* tp_getattr */
1825 0, /* tp_setattr */
1826 0, /* tp_reserved */
1827 0, /* tp_repr */
1828 0, /* tp_as_number */
1829 0, /* tp_as_sequence */
1830 0, /* tp_as_mapping */
1831 0, /* tp_hash */
1832 0, /* tp_call */
1833 0, /* tp_str */
1834 PyObject_GenericGetAttr, /* tp_getattro */
1835 0, /* tp_setattro */
1836 0, /* tp_as_buffer */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001837 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001838 0, /* tp_doc */
1839 (traverseproc)dequeiter_traverse, /* tp_traverse */
1840 0, /* tp_clear */
1841 0, /* tp_richcompare */
1842 0, /* tp_weaklistoffset */
1843 PyObject_SelfIter, /* tp_iter */
1844 (iternextfunc)dequereviter_next, /* tp_iternext */
1845 dequeiter_methods, /* tp_methods */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001846 0, /* tp_members */
1847 0, /* tp_getset */
1848 0, /* tp_base */
1849 0, /* tp_dict */
1850 0, /* tp_descr_get */
1851 0, /* tp_descr_set */
1852 0, /* tp_dictoffset */
1853 0, /* tp_init */
1854 0, /* tp_alloc */
1855 dequereviter_new, /* tp_new */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001856 0,
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001857};
1858
Guido van Rossum1968ad32006-02-25 22:38:04 +00001859/* defaultdict type *********************************************************/
1860
1861typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001862 PyDictObject dict;
1863 PyObject *default_factory;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001864} defdictobject;
1865
1866static PyTypeObject defdict_type; /* Forward */
1867
1868PyDoc_STRVAR(defdict_missing_doc,
1869"__missing__(key) # Called by __getitem__ for missing key; pseudo-code:\n\
Guido van Rossumd8faa362007-04-27 19:54:29 +00001870 if self.default_factory is None: raise KeyError((key,))\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00001871 self[key] = value = self.default_factory()\n\
1872 return value\n\
1873");
1874
1875static PyObject *
1876defdict_missing(defdictobject *dd, PyObject *key)
1877{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001878 PyObject *factory = dd->default_factory;
1879 PyObject *value;
1880 if (factory == NULL || factory == Py_None) {
1881 /* XXX Call dict.__missing__(key) */
1882 PyObject *tup;
1883 tup = PyTuple_Pack(1, key);
1884 if (!tup) return NULL;
1885 PyErr_SetObject(PyExc_KeyError, tup);
1886 Py_DECREF(tup);
1887 return NULL;
1888 }
1889 value = PyEval_CallObject(factory, NULL);
1890 if (value == NULL)
1891 return value;
1892 if (PyObject_SetItem((PyObject *)dd, key, value) < 0) {
1893 Py_DECREF(value);
1894 return NULL;
1895 }
1896 return value;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001897}
1898
1899PyDoc_STRVAR(defdict_copy_doc, "D.copy() -> a shallow copy of D.");
1900
1901static PyObject *
1902defdict_copy(defdictobject *dd)
1903{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001904 /* This calls the object's class. That only works for subclasses
1905 whose class constructor has the same signature. Subclasses that
1906 define a different constructor signature must override copy().
1907 */
Raymond Hettinger54628fa2009-08-04 19:16:39 +00001908
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001909 if (dd->default_factory == NULL)
1910 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd), Py_None, dd, NULL);
1911 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd),
1912 dd->default_factory, dd, NULL);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001913}
1914
1915static PyObject *
1916defdict_reduce(defdictobject *dd)
1917{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001918 /* __reduce__ must return a 5-tuple as follows:
Guido van Rossum1968ad32006-02-25 22:38:04 +00001919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001920 - factory function
1921 - tuple of args for the factory function
1922 - additional state (here None)
1923 - sequence iterator (here None)
1924 - dictionary iterator (yielding successive (key, value) pairs
Guido van Rossum1968ad32006-02-25 22:38:04 +00001925
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001926 This API is used by pickle.py and copy.py.
Guido van Rossum1968ad32006-02-25 22:38:04 +00001927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001928 For this to be useful with pickle.py, the default_factory
1929 must be picklable; e.g., None, a built-in, or a global
1930 function in a module or package.
Guido van Rossum1968ad32006-02-25 22:38:04 +00001931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001932 Both shallow and deep copying are supported, but for deep
1933 copying, the default_factory must be deep-copyable; e.g. None,
1934 or a built-in (functions are not copyable at this time).
Guido van Rossum1968ad32006-02-25 22:38:04 +00001935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001936 This only works for subclasses as long as their constructor
1937 signature is compatible; the first argument must be the
1938 optional default_factory, defaulting to None.
1939 */
1940 PyObject *args;
1941 PyObject *items;
1942 PyObject *iter;
1943 PyObject *result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001944 _Py_IDENTIFIER(items);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001945
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001946 if (dd->default_factory == NULL || dd->default_factory == Py_None)
1947 args = PyTuple_New(0);
1948 else
1949 args = PyTuple_Pack(1, dd->default_factory);
1950 if (args == NULL)
1951 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001952 items = _PyObject_CallMethodId((PyObject *)dd, &PyId_items, "()");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001953 if (items == NULL) {
1954 Py_DECREF(args);
1955 return NULL;
1956 }
1957 iter = PyObject_GetIter(items);
1958 if (iter == NULL) {
1959 Py_DECREF(items);
1960 Py_DECREF(args);
1961 return NULL;
1962 }
1963 result = PyTuple_Pack(5, Py_TYPE(dd), args,
1964 Py_None, Py_None, iter);
1965 Py_DECREF(iter);
1966 Py_DECREF(items);
1967 Py_DECREF(args);
1968 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001969}
1970
1971static PyMethodDef defdict_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001972 {"__missing__", (PyCFunction)defdict_missing, METH_O,
1973 defdict_missing_doc},
1974 {"copy", (PyCFunction)defdict_copy, METH_NOARGS,
1975 defdict_copy_doc},
1976 {"__copy__", (PyCFunction)defdict_copy, METH_NOARGS,
1977 defdict_copy_doc},
1978 {"__reduce__", (PyCFunction)defdict_reduce, METH_NOARGS,
1979 reduce_doc},
1980 {NULL}
Guido van Rossum1968ad32006-02-25 22:38:04 +00001981};
1982
1983static PyMemberDef defdict_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001984 {"default_factory", T_OBJECT,
1985 offsetof(defdictobject, default_factory), 0,
1986 PyDoc_STR("Factory for default value called by __missing__().")},
1987 {NULL}
Guido van Rossum1968ad32006-02-25 22:38:04 +00001988};
1989
1990static void
1991defdict_dealloc(defdictobject *dd)
1992{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001993 Py_CLEAR(dd->default_factory);
1994 PyDict_Type.tp_dealloc((PyObject *)dd);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001995}
1996
Guido van Rossum1968ad32006-02-25 22:38:04 +00001997static PyObject *
1998defdict_repr(defdictobject *dd)
1999{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002000 PyObject *baserepr;
2001 PyObject *defrepr;
2002 PyObject *result;
2003 baserepr = PyDict_Type.tp_repr((PyObject *)dd);
2004 if (baserepr == NULL)
2005 return NULL;
2006 if (dd->default_factory == NULL)
2007 defrepr = PyUnicode_FromString("None");
2008 else
2009 {
2010 int status = Py_ReprEnter(dd->default_factory);
2011 if (status != 0) {
Antoine Pitrouf5f1fe02012-02-15 02:42:46 +01002012 if (status < 0) {
2013 Py_DECREF(baserepr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002014 return NULL;
Antoine Pitrouf5f1fe02012-02-15 02:42:46 +01002015 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002016 defrepr = PyUnicode_FromString("...");
2017 }
2018 else
2019 defrepr = PyObject_Repr(dd->default_factory);
2020 Py_ReprLeave(dd->default_factory);
2021 }
2022 if (defrepr == NULL) {
2023 Py_DECREF(baserepr);
2024 return NULL;
2025 }
2026 result = PyUnicode_FromFormat("defaultdict(%U, %U)",
2027 defrepr, baserepr);
2028 Py_DECREF(defrepr);
2029 Py_DECREF(baserepr);
2030 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00002031}
2032
2033static int
2034defdict_traverse(PyObject *self, visitproc visit, void *arg)
2035{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002036 Py_VISIT(((defdictobject *)self)->default_factory);
2037 return PyDict_Type.tp_traverse(self, visit, arg);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002038}
2039
2040static int
2041defdict_tp_clear(defdictobject *dd)
2042{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002043 Py_CLEAR(dd->default_factory);
2044 return PyDict_Type.tp_clear((PyObject *)dd);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002045}
2046
2047static int
2048defdict_init(PyObject *self, PyObject *args, PyObject *kwds)
2049{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002050 defdictobject *dd = (defdictobject *)self;
2051 PyObject *olddefault = dd->default_factory;
2052 PyObject *newdefault = NULL;
2053 PyObject *newargs;
2054 int result;
2055 if (args == NULL || !PyTuple_Check(args))
2056 newargs = PyTuple_New(0);
2057 else {
2058 Py_ssize_t n = PyTuple_GET_SIZE(args);
2059 if (n > 0) {
2060 newdefault = PyTuple_GET_ITEM(args, 0);
2061 if (!PyCallable_Check(newdefault) && newdefault != Py_None) {
2062 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger239aba72015-07-20 03:09:22 -04002063 "first argument must be callable or None");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002064 return -1;
2065 }
2066 }
2067 newargs = PySequence_GetSlice(args, 1, n);
2068 }
2069 if (newargs == NULL)
2070 return -1;
2071 Py_XINCREF(newdefault);
2072 dd->default_factory = newdefault;
2073 result = PyDict_Type.tp_init(self, newargs, kwds);
2074 Py_DECREF(newargs);
2075 Py_XDECREF(olddefault);
2076 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00002077}
2078
2079PyDoc_STRVAR(defdict_doc,
Benjamin Peterson9cb33b72014-01-13 23:56:05 -05002080"defaultdict(default_factory[, ...]) --> dict with default factory\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00002081\n\
2082The default factory is called without arguments to produce\n\
2083a new value when a key is not present, in __getitem__ only.\n\
2084A defaultdict compares equal to a dict with the same items.\n\
Benjamin Peterson9cb33b72014-01-13 23:56:05 -05002085All remaining arguments are treated the same as if they were\n\
2086passed to the dict constructor, including keyword arguments.\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00002087");
2088
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002089/* See comment in xxsubtype.c */
2090#define DEFERRED_ADDRESS(ADDR) 0
2091
Guido van Rossum1968ad32006-02-25 22:38:04 +00002092static PyTypeObject defdict_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002093 PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0)
2094 "collections.defaultdict", /* tp_name */
2095 sizeof(defdictobject), /* tp_basicsize */
2096 0, /* tp_itemsize */
2097 /* methods */
2098 (destructor)defdict_dealloc, /* tp_dealloc */
2099 0, /* tp_print */
2100 0, /* tp_getattr */
2101 0, /* tp_setattr */
2102 0, /* tp_reserved */
2103 (reprfunc)defdict_repr, /* tp_repr */
2104 0, /* tp_as_number */
2105 0, /* tp_as_sequence */
2106 0, /* tp_as_mapping */
2107 0, /* tp_hash */
2108 0, /* tp_call */
2109 0, /* tp_str */
2110 PyObject_GenericGetAttr, /* tp_getattro */
2111 0, /* tp_setattro */
2112 0, /* tp_as_buffer */
2113 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
2114 /* tp_flags */
2115 defdict_doc, /* tp_doc */
2116 defdict_traverse, /* tp_traverse */
2117 (inquiry)defdict_tp_clear, /* tp_clear */
2118 0, /* tp_richcompare */
2119 0, /* tp_weaklistoffset*/
2120 0, /* tp_iter */
2121 0, /* tp_iternext */
2122 defdict_methods, /* tp_methods */
2123 defdict_members, /* tp_members */
2124 0, /* tp_getset */
2125 DEFERRED_ADDRESS(&PyDict_Type), /* tp_base */
2126 0, /* tp_dict */
2127 0, /* tp_descr_get */
2128 0, /* tp_descr_set */
2129 0, /* tp_dictoffset */
2130 defdict_init, /* tp_init */
2131 PyType_GenericAlloc, /* tp_alloc */
2132 0, /* tp_new */
2133 PyObject_GC_Del, /* tp_free */
Guido van Rossum1968ad32006-02-25 22:38:04 +00002134};
2135
Raymond Hettinger96f34102010-12-15 16:30:37 +00002136/* helper function for Counter *********************************************/
2137
2138PyDoc_STRVAR(_count_elements_doc,
2139"_count_elements(mapping, iterable) -> None\n\
2140\n\
2141Count elements in the iterable, updating the mappping");
2142
2143static PyObject *
2144_count_elements(PyObject *self, PyObject *args)
2145{
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002146 _Py_IDENTIFIER(get);
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002147 _Py_IDENTIFIER(__setitem__);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002148 PyObject *it, *iterable, *mapping, *oldval;
2149 PyObject *newval = NULL;
2150 PyObject *key = NULL;
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002151 PyObject *zero = NULL;
Raymond Hettinger96f34102010-12-15 16:30:37 +00002152 PyObject *one = NULL;
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002153 PyObject *bound_get = NULL;
2154 PyObject *mapping_get;
2155 PyObject *dict_get;
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002156 PyObject *mapping_setitem;
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002157 PyObject *dict_setitem;
Raymond Hettinger96f34102010-12-15 16:30:37 +00002158
2159 if (!PyArg_UnpackTuple(args, "_count_elements", 2, 2, &mapping, &iterable))
2160 return NULL;
2161
Raymond Hettinger96f34102010-12-15 16:30:37 +00002162 it = PyObject_GetIter(iterable);
2163 if (it == NULL)
2164 return NULL;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002165
Raymond Hettinger96f34102010-12-15 16:30:37 +00002166 one = PyLong_FromLong(1);
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002167 if (one == NULL)
2168 goto done;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002169
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002170 /* Only take the fast path when get() and __setitem__()
2171 * have not been overridden.
2172 */
2173 mapping_get = _PyType_LookupId(Py_TYPE(mapping), &PyId_get);
2174 dict_get = _PyType_LookupId(&PyDict_Type, &PyId_get);
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002175 mapping_setitem = _PyType_LookupId(Py_TYPE(mapping), &PyId___setitem__);
2176 dict_setitem = _PyType_LookupId(&PyDict_Type, &PyId___setitem__);
2177
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002178 if (mapping_get != NULL && mapping_get == dict_get &&
2179 mapping_setitem != NULL && mapping_setitem == dict_setitem) {
Raymond Hettinger426e0522011-01-03 02:12:02 +00002180 while (1) {
Raymond Hettinger507d9972014-05-18 21:32:40 +01002181 /* Fast path advantages:
2182 1. Eliminate double hashing
2183 (by re-using the same hash for both the get and set)
2184 2. Avoid argument overhead of PyObject_CallFunctionObjArgs
2185 (argument tuple creation and parsing)
2186 3. Avoid indirection through a bound method object
2187 (creates another argument tuple)
2188 4. Avoid initial increment from zero
2189 (reuse an existing one-object instead)
2190 */
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002191 Py_hash_t hash;
2192
Raymond Hettinger426e0522011-01-03 02:12:02 +00002193 key = PyIter_Next(it);
Victor Stinnera154b5c2011-04-20 23:23:52 +02002194 if (key == NULL)
2195 break;
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002196
2197 if (!PyUnicode_CheckExact(key) ||
2198 (hash = ((PyASCIIObject *) key)->hash) == -1)
2199 {
2200 hash = PyObject_Hash(key);
Raymond Hettingerda2850f2015-02-27 12:42:54 -08002201 if (hash == -1)
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002202 goto done;
2203 }
2204
2205 oldval = _PyDict_GetItem_KnownHash(mapping, key, hash);
Raymond Hettinger426e0522011-01-03 02:12:02 +00002206 if (oldval == NULL) {
Raymond Hettinger28c995d2015-08-14 02:07:41 -07002207 if (_PyDict_SetItem_KnownHash(mapping, key, one, hash) < 0)
Raymond Hettinger507d9972014-05-18 21:32:40 +01002208 goto done;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002209 } else {
2210 newval = PyNumber_Add(oldval, one);
2211 if (newval == NULL)
Raymond Hettinger507d9972014-05-18 21:32:40 +01002212 goto done;
Raymond Hettinger28c995d2015-08-14 02:07:41 -07002213 if (_PyDict_SetItem_KnownHash(mapping, key, newval, hash) < 0)
Raymond Hettinger507d9972014-05-18 21:32:40 +01002214 goto done;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002215 Py_CLEAR(newval);
2216 }
2217 Py_DECREF(key);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002218 }
Raymond Hettinger426e0522011-01-03 02:12:02 +00002219 } else {
Victor Stinnere7f516c2013-11-06 23:52:55 +01002220 bound_get = _PyObject_GetAttrId(mapping, &PyId_get);
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002221 if (bound_get == NULL)
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002222 goto done;
2223
2224 zero = PyLong_FromLong(0);
2225 if (zero == NULL)
2226 goto done;
2227
Raymond Hettinger426e0522011-01-03 02:12:02 +00002228 while (1) {
2229 key = PyIter_Next(it);
Victor Stinnera154b5c2011-04-20 23:23:52 +02002230 if (key == NULL)
2231 break;
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002232 oldval = PyObject_CallFunctionObjArgs(bound_get, key, zero, NULL);
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002233 if (oldval == NULL)
2234 break;
2235 newval = PyNumber_Add(oldval, one);
2236 Py_DECREF(oldval);
2237 if (newval == NULL)
2238 break;
Raymond Hettinger28c995d2015-08-14 02:07:41 -07002239 if (PyObject_SetItem(mapping, key, newval) < 0)
Raymond Hettinger96f34102010-12-15 16:30:37 +00002240 break;
2241 Py_CLEAR(newval);
Raymond Hettinger426e0522011-01-03 02:12:02 +00002242 Py_DECREF(key);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002243 }
Raymond Hettinger96f34102010-12-15 16:30:37 +00002244 }
Raymond Hettinger426e0522011-01-03 02:12:02 +00002245
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002246done:
Raymond Hettinger96f34102010-12-15 16:30:37 +00002247 Py_DECREF(it);
2248 Py_XDECREF(key);
2249 Py_XDECREF(newval);
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002250 Py_XDECREF(bound_get);
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002251 Py_XDECREF(zero);
2252 Py_XDECREF(one);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002253 if (PyErr_Occurred())
2254 return NULL;
2255 Py_RETURN_NONE;
2256}
2257
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002258/* module level code ********************************************************/
2259
2260PyDoc_STRVAR(module_doc,
Guido van Rossum1968ad32006-02-25 22:38:04 +00002261"High performance data structures.\n\
2262- deque: ordered collection accessible from endpoints only\n\
2263- defaultdict: dict subclass with a default value factory\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002264");
2265
Raymond Hettinger96f34102010-12-15 16:30:37 +00002266static struct PyMethodDef module_functions[] = {
2267 {"_count_elements", _count_elements, METH_VARARGS, _count_elements_doc},
2268 {NULL, NULL} /* sentinel */
2269};
Martin v. Löwis1a214512008-06-11 05:26:20 +00002270
2271static struct PyModuleDef _collectionsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002272 PyModuleDef_HEAD_INIT,
2273 "_collections",
2274 module_doc,
2275 -1,
Raymond Hettinger96f34102010-12-15 16:30:37 +00002276 module_functions,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002277 NULL,
2278 NULL,
2279 NULL,
2280 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002281};
2282
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002283PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002284PyInit__collections(void)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002285{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002286 PyObject *m;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002288 m = PyModule_Create(&_collectionsmodule);
2289 if (m == NULL)
2290 return NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002292 if (PyType_Ready(&deque_type) < 0)
2293 return NULL;
2294 Py_INCREF(&deque_type);
2295 PyModule_AddObject(m, "deque", (PyObject *)&deque_type);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002297 defdict_type.tp_base = &PyDict_Type;
2298 if (PyType_Ready(&defdict_type) < 0)
2299 return NULL;
2300 Py_INCREF(&defdict_type);
2301 PyModule_AddObject(m, "defaultdict", (PyObject *)&defdict_type);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002302
Eric Snow47db7172015-05-29 22:21:39 -06002303 Py_INCREF(&PyODict_Type);
2304 PyModule_AddObject(m, "OrderedDict", (PyObject *)&PyODict_Type);
2305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002306 if (PyType_Ready(&dequeiter_type) < 0)
2307 return NULL;
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002308 Py_INCREF(&dequeiter_type);
2309 PyModule_AddObject(m, "_deque_iterator", (PyObject *)&dequeiter_type);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002311 if (PyType_Ready(&dequereviter_type) < 0)
2312 return NULL;
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002313 Py_INCREF(&dequereviter_type);
2314 PyModule_AddObject(m, "_deque_reverse_iterator", (PyObject *)&dequereviter_type);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00002315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002316 return m;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002317}