blob: 5db7aed37735edcedd5eccfd95beb5532e888bdb [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
Raymond Hettingerf2b02ce2015-09-26 17:47:02 -0700124#define MAXFREEBLOCKS 16
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 }
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000318 Py_SIZE(deque)++;
Raymond Hettinger7c0b70f2015-09-26 21:11:05 -0700319 Py_INCREF(item);
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 }
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000343 Py_SIZE(deque)++;
Raymond Hettinger7c0b70f2015-09-26 21:11:05 -0700344 Py_INCREF(item);
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 Hettinger7a845522015-09-26 01:30:51 -0700374 PyObject *(*iternext)(PyObject *);
Raymond Hettinger0e14e662015-09-19 00:21:33 -0600375 int trim = (deque->maxlen != -1);
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000377 /* Handle case where id(deque) == id(iterable) */
378 if ((PyObject *)deque == iterable) {
379 PyObject *result;
380 PyObject *s = PySequence_List(iterable);
381 if (s == NULL)
382 return NULL;
383 result = deque_extend(deque, s);
384 Py_DECREF(s);
385 return result;
386 }
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000387
Raymond Hettingerd9c116c2013-07-09 00:13:21 -0700388 /* Space saving heuristic. Start filling from the left */
389 if (Py_SIZE(deque) == 0) {
390 assert(deque->leftblock == deque->rightblock);
391 assert(deque->leftindex == deque->rightindex+1);
392 deque->leftindex = 1;
393 deque->rightindex = 0;
394 }
395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000396 it = PyObject_GetIter(iterable);
397 if (it == NULL)
398 return NULL;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000400 if (deque->maxlen == 0)
401 return consume_iterator(it);
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000402
Raymond Hettinger7a845522015-09-26 01:30:51 -0700403 iternext = *Py_TYPE(it)->tp_iternext;
404 while ((item = iternext(it)) != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000405 deque->state++;
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700406 if (deque->rightindex == BLOCKLEN - 1) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000407 block *b = newblock(Py_SIZE(deque));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000408 if (b == NULL) {
409 Py_DECREF(item);
410 Py_DECREF(it);
411 return NULL;
412 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000413 b->leftlink = deque->rightblock;
414 CHECK_END(deque->rightblock->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000415 deque->rightblock->rightlink = b;
416 deque->rightblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000417 MARK_END(b->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000418 deque->rightindex = -1;
419 }
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000420 Py_SIZE(deque)++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 deque->rightindex++;
422 deque->rightblock->data[deque->rightindex] = item;
Raymond Hettinger0e14e662015-09-19 00:21:33 -0600423 if (trim)
424 deque_trim_left(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425 }
Raymond Hettinger2b2b7532015-09-05 17:05:52 -0700426 if (PyErr_Occurred()) {
Raymond Hettinger7a845522015-09-26 01:30:51 -0700427 if (PyErr_ExceptionMatches(PyExc_StopIteration))
428 PyErr_Clear();
429 else {
430 Py_DECREF(it);
431 return NULL;
432 }
Raymond Hettinger2b2b7532015-09-05 17:05:52 -0700433 }
434 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435 Py_RETURN_NONE;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000436}
437
Tim Peters1065f752004-10-01 01:03:29 +0000438PyDoc_STRVAR(extend_doc,
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000439"Extend the right side of the deque with elements from the iterable");
440
441static PyObject *
442deque_extendleft(dequeobject *deque, PyObject *iterable)
443{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000444 PyObject *it, *item;
Raymond Hettinger7a845522015-09-26 01:30:51 -0700445 PyObject *(*iternext)(PyObject *);
Raymond Hettinger0e14e662015-09-19 00:21:33 -0600446 int trim = (deque->maxlen != -1);
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000448 /* Handle case where id(deque) == id(iterable) */
449 if ((PyObject *)deque == iterable) {
450 PyObject *result;
451 PyObject *s = PySequence_List(iterable);
452 if (s == NULL)
453 return NULL;
454 result = deque_extendleft(deque, s);
455 Py_DECREF(s);
456 return result;
457 }
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000458
Raymond Hettingerd9c116c2013-07-09 00:13:21 -0700459 /* Space saving heuristic. Start filling from the right */
460 if (Py_SIZE(deque) == 0) {
461 assert(deque->leftblock == deque->rightblock);
462 assert(deque->leftindex == deque->rightindex+1);
463 deque->leftindex = BLOCKLEN - 1;
464 deque->rightindex = BLOCKLEN - 2;
465 }
466
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000467 it = PyObject_GetIter(iterable);
468 if (it == NULL)
469 return NULL;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 if (deque->maxlen == 0)
472 return consume_iterator(it);
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000473
Raymond Hettinger7a845522015-09-26 01:30:51 -0700474 iternext = *Py_TYPE(it)->tp_iternext;
475 while ((item = iternext(it)) != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 deque->state++;
477 if (deque->leftindex == 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000478 block *b = newblock(Py_SIZE(deque));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 if (b == NULL) {
480 Py_DECREF(item);
481 Py_DECREF(it);
482 return NULL;
483 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000484 b->rightlink = deque->leftblock;
485 CHECK_END(deque->leftblock->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 deque->leftblock->leftlink = b;
487 deque->leftblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000488 MARK_END(b->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 deque->leftindex = BLOCKLEN;
490 }
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000491 Py_SIZE(deque)++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 deque->leftindex--;
493 deque->leftblock->data[deque->leftindex] = item;
Raymond Hettinger0e14e662015-09-19 00:21:33 -0600494 if (trim)
495 deque_trim_right(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000496 }
Raymond Hettinger2b2b7532015-09-05 17:05:52 -0700497 if (PyErr_Occurred()) {
Raymond Hettinger7a845522015-09-26 01:30:51 -0700498 if (PyErr_ExceptionMatches(PyExc_StopIteration))
499 PyErr_Clear();
500 else {
501 Py_DECREF(it);
502 return NULL;
503 }
Raymond Hettinger2b2b7532015-09-05 17:05:52 -0700504 }
505 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 Py_RETURN_NONE;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000507}
508
Tim Peters1065f752004-10-01 01:03:29 +0000509PyDoc_STRVAR(extendleft_doc,
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000510"Extend the left side of the deque with elements from the iterable");
511
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000512static PyObject *
513deque_inplace_concat(dequeobject *deque, PyObject *other)
514{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000515 PyObject *result;
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 result = deque_extend(deque, other);
518 if (result == NULL)
519 return result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000520 Py_INCREF(deque);
Raymond Hettinger2b2b7532015-09-05 17:05:52 -0700521 Py_DECREF(result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000522 return (PyObject *)deque;
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000523}
524
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700525static PyObject *
526deque_copy(PyObject *deque)
527{
528 dequeobject *old_deque = (dequeobject *)deque;
529 if (Py_TYPE(deque) == &deque_type) {
530 dequeobject *new_deque;
531 PyObject *rv;
532
533 new_deque = (dequeobject *)deque_new(&deque_type, (PyObject *)NULL, (PyObject *)NULL);
534 if (new_deque == NULL)
535 return NULL;
536 new_deque->maxlen = old_deque->maxlen;
537 /* Fast path for the deque_repeat() common case where len(deque) == 1 */
538 if (Py_SIZE(deque) == 1 && new_deque->maxlen != 0) {
539 PyObject *item = old_deque->leftblock->data[old_deque->leftindex];
540 rv = deque_append(new_deque, item);
541 } else {
542 rv = deque_extend(new_deque, deque);
543 }
544 if (rv != NULL) {
545 Py_DECREF(rv);
546 return (PyObject *)new_deque;
547 }
548 Py_DECREF(new_deque);
549 return NULL;
550 }
551 if (old_deque->maxlen < 0)
552 return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "O", deque, NULL);
553 else
554 return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "Oi",
555 deque, old_deque->maxlen, NULL);
556}
557
558PyDoc_STRVAR(copy_doc, "Return a shallow copy of a deque.");
Raymond Hettinger41290a62015-03-31 08:12:23 -0700559
560static PyObject *
561deque_concat(dequeobject *deque, PyObject *other)
562{
Benjamin Peterson1a629212015-04-04 10:52:36 -0400563 PyObject *new_deque, *result;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700564 int rv;
565
566 rv = PyObject_IsInstance(other, (PyObject *)&deque_type);
567 if (rv <= 0) {
568 if (rv == 0) {
569 PyErr_Format(PyExc_TypeError,
570 "can only concatenate deque (not \"%.200s\") to deque",
571 other->ob_type->tp_name);
572 }
573 return NULL;
574 }
575
576 new_deque = deque_copy((PyObject *)deque);
577 if (new_deque == NULL)
578 return NULL;
Benjamin Peterson1a629212015-04-04 10:52:36 -0400579 result = deque_extend((dequeobject *)new_deque, other);
580 if (result == NULL) {
581 Py_DECREF(new_deque);
582 return NULL;
583 }
584 Py_DECREF(result);
585 return new_deque;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700586}
587
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700588static void
589deque_clear(dequeobject *deque)
590{
591 block *b;
592 block *prevblock;
593 block *leftblock;
594 Py_ssize_t leftindex;
595 Py_ssize_t n;
596 PyObject *item;
597
598 /* During the process of clearing a deque, decrefs can cause the
599 deque to mutate. To avoid fatal confusion, we have to make the
600 deque empty before clearing the blocks and never refer to
601 anything via deque->ref while clearing. (This is the same
602 technique used for clearing lists, sets, and dicts.)
603
604 Making the deque empty requires allocating a new empty block. In
605 the unlikely event that memory is full, we fall back to an
606 alternate method that doesn't require a new block. Repeating
607 pops in a while-loop is slower, possibly re-entrant (and a clever
608 adversary could cause it to never terminate).
609 */
610
611 b = newblock(0);
612 if (b == NULL) {
613 PyErr_Clear();
614 goto alternate_method;
615 }
616
617 /* Remember the old size, leftblock, and leftindex */
618 leftblock = deque->leftblock;
619 leftindex = deque->leftindex;
620 n = Py_SIZE(deque);
621
622 /* Set the deque to be empty using the newly allocated block */
623 MARK_END(b->leftlink);
624 MARK_END(b->rightlink);
625 Py_SIZE(deque) = 0;
626 deque->leftblock = b;
627 deque->rightblock = b;
628 deque->leftindex = CENTER + 1;
629 deque->rightindex = CENTER;
630 deque->state++;
631
632 /* Now the old size, leftblock, and leftindex are disconnected from
633 the empty deque and we can use them to decref the pointers.
634 */
635 while (n--) {
636 item = leftblock->data[leftindex];
637 Py_DECREF(item);
638 leftindex++;
639 if (leftindex == BLOCKLEN && n) {
640 CHECK_NOT_END(leftblock->rightlink);
641 prevblock = leftblock;
642 leftblock = leftblock->rightlink;
643 leftindex = 0;
644 freeblock(prevblock);
645 }
646 }
647 CHECK_END(leftblock->rightlink);
648 freeblock(leftblock);
649 return;
650
651 alternate_method:
652 while (Py_SIZE(deque)) {
653 item = deque_pop(deque, NULL);
654 assert (item != NULL);
655 Py_DECREF(item);
656 }
657}
658
659static PyObject *
660deque_clearmethod(dequeobject *deque)
661{
662 deque_clear(deque);
663 Py_RETURN_NONE;
664}
665
666PyDoc_STRVAR(clear_doc, "Remove all elements from the deque.");
Raymond Hettinger41290a62015-03-31 08:12:23 -0700667
668static PyObject *
Raymond Hettinger41290a62015-03-31 08:12:23 -0700669deque_inplace_repeat(dequeobject *deque, Py_ssize_t n)
670{
Raymond Hettingerc22eee62015-09-26 02:14:50 -0700671 Py_ssize_t i, m, size;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700672 PyObject *seq;
673 PyObject *rv;
674
675 size = Py_SIZE(deque);
676 if (size == 0 || n == 1) {
677 Py_INCREF(deque);
678 return (PyObject *)deque;
679 }
680
681 if (n <= 0) {
682 deque_clear(deque);
683 Py_INCREF(deque);
684 return (PyObject *)deque;
685 }
686
Raymond Hettinger41290a62015-03-31 08:12:23 -0700687 if (size == 1) {
688 /* common case, repeating a single element */
689 PyObject *item = deque->leftblock->data[deque->leftindex];
690
691 if (deque->maxlen != -1 && n > deque->maxlen)
692 n = deque->maxlen;
693
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400694 if (n > MAX_DEQUE_LEN)
695 return PyErr_NoMemory();
696
Raymond Hettinger67c78b52015-09-12 11:00:20 -0400697 deque->state++;
Raymond Hettingerad262252015-09-14 01:03:04 -0400698 for (i = 0 ; i < n-1 ; ) {
Raymond Hettinger67c78b52015-09-12 11:00:20 -0400699 if (deque->rightindex == BLOCKLEN - 1) {
700 block *b = newblock(Py_SIZE(deque) + i);
701 if (b == NULL) {
702 Py_SIZE(deque) += i;
703 return NULL;
704 }
705 b->leftlink = deque->rightblock;
706 CHECK_END(deque->rightblock->rightlink);
707 deque->rightblock->rightlink = b;
708 deque->rightblock = b;
709 MARK_END(b->rightlink);
710 deque->rightindex = -1;
711 }
Raymond Hettingerc22eee62015-09-26 02:14:50 -0700712 m = n - 1 - i;
713 if (m > BLOCKLEN - 1 - deque->rightindex)
714 m = BLOCKLEN - 1 - deque->rightindex;
715 i += m;
716 while (m--) {
Raymond Hettingerad262252015-09-14 01:03:04 -0400717 deque->rightindex++;
718 Py_INCREF(item);
719 deque->rightblock->data[deque->rightindex] = item;
720 }
Raymond Hettinger41290a62015-03-31 08:12:23 -0700721 }
Raymond Hettinger67c78b52015-09-12 11:00:20 -0400722 Py_SIZE(deque) += i;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700723 Py_INCREF(deque);
724 return (PyObject *)deque;
725 }
726
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400727 if ((size_t)size > MAX_DEQUE_LEN / (size_t)n) {
728 return PyErr_NoMemory();
729 }
730
Raymond Hettinger41290a62015-03-31 08:12:23 -0700731 seq = PySequence_List((PyObject *)deque);
732 if (seq == NULL)
733 return seq;
734
735 for (i = 0 ; i < n-1 ; i++) {
736 rv = deque_extend(deque, seq);
737 if (rv == NULL) {
738 Py_DECREF(seq);
739 return NULL;
740 }
741 Py_DECREF(rv);
742 }
743 Py_INCREF(deque);
744 Py_DECREF(seq);
745 return (PyObject *)deque;
746}
747
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400748static PyObject *
749deque_repeat(dequeobject *deque, Py_ssize_t n)
750{
751 dequeobject *new_deque;
Raymond Hettinger95e2cc52015-09-13 02:41:18 -0400752 PyObject *rv;
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400753
754 new_deque = (dequeobject *)deque_copy((PyObject *) deque);
755 if (new_deque == NULL)
756 return NULL;
Raymond Hettinger95e2cc52015-09-13 02:41:18 -0400757 rv = deque_inplace_repeat(new_deque, n);
758 Py_DECREF(new_deque);
759 return rv;
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400760}
761
Raymond Hettinger54023152014-04-23 00:58:48 -0700762/* The rotate() method is part of the public API and is used internally
763as a primitive for other methods.
764
765Rotation by 1 or -1 is a common case, so any optimizations for high
766volume rotations should take care not to penalize the common case.
767
768Conceptually, a rotate by one is equivalent to a pop on one side and an
769append on the other. However, a pop/append pair is unnecessarily slow
770because it requires a incref/decref pair for an object located randomly
771in memory. It is better to just move the object pointer from one block
772to the next without changing the reference count.
773
774When moving batches of pointers, it is tempting to use memcpy() but that
775proved to be slower than a simple loop for a variety of reasons.
776Memcpy() cannot know in advance that we're copying pointers instead of
777bytes, that the source and destination are pointer aligned and
778non-overlapping, that moving just one pointer is a common case, that we
779never need to move more than BLOCKLEN pointers, and that at least one
780pointer is always moved.
781
782For high volume rotations, newblock() and freeblock() are never called
783more than once. Previously emptied blocks are immediately reused as a
784destination block. If a block is left-over at the end, it is freed.
785*/
786
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000787static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000788_deque_rotate(dequeobject *deque, Py_ssize_t n)
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000789{
Raymond Hettinger3959af92013-07-13 02:34:08 -0700790 block *b = NULL;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700791 block *leftblock = deque->leftblock;
792 block *rightblock = deque->rightblock;
793 Py_ssize_t leftindex = deque->leftindex;
794 Py_ssize_t rightindex = deque->rightindex;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000795 Py_ssize_t len=Py_SIZE(deque), halflen=len>>1;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700796 int rv = -1;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000797
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800798 if (len <= 1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000799 return 0;
800 if (n > halflen || n < -halflen) {
801 n %= len;
802 if (n > halflen)
803 n -= len;
804 else if (n < -halflen)
805 n += len;
806 }
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500807 assert(len > 1);
Raymond Hettingera4409c12013-02-04 00:08:12 -0500808 assert(-halflen <= n && n <= halflen);
Raymond Hettinger231ee4d2013-02-02 11:24:43 -0800809
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800810 deque->state++;
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500811 while (n > 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700812 if (leftindex == 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700813 if (b == NULL) {
Raymond Hettinger3959af92013-07-13 02:34:08 -0700814 b = newblock(len);
815 if (b == NULL)
816 goto done;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700817 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000818 b->rightlink = leftblock;
819 CHECK_END(leftblock->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700820 leftblock->leftlink = b;
821 leftblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000822 MARK_END(b->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700823 leftindex = BLOCKLEN;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700824 b = NULL;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800825 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700826 assert(leftindex > 0);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700827 {
828 PyObject **src, **dest;
829 Py_ssize_t m = n;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800830
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700831 if (m > rightindex + 1)
832 m = rightindex + 1;
833 if (m > leftindex)
834 m = leftindex;
835 assert (m > 0 && m <= len);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700836 rightindex -= m;
837 leftindex -= m;
Raymond Hettinger0e259f12015-02-01 22:53:41 -0800838 src = &rightblock->data[rightindex + 1];
839 dest = &leftblock->data[leftindex];
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700840 n -= m;
Raymond Hettinger840533b2013-07-13 17:03:58 -0700841 do {
Raymond Hettinger0e259f12015-02-01 22:53:41 -0800842 *(dest++) = *(src++);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700843 } while (--m);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700844 }
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -0700845 if (rightindex < 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700846 assert(leftblock != rightblock);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700847 assert(b == NULL);
Raymond Hettinger3959af92013-07-13 02:34:08 -0700848 b = rightblock;
Raymond Hettingerb97cc492013-07-21 01:51:07 -0700849 CHECK_NOT_END(rightblock->leftlink);
850 rightblock = rightblock->leftlink;
851 MARK_END(rightblock->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700852 rightindex = BLOCKLEN - 1;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800853 }
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800854 }
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500855 while (n < 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700856 if (rightindex == BLOCKLEN - 1) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700857 if (b == NULL) {
Raymond Hettinger3959af92013-07-13 02:34:08 -0700858 b = newblock(len);
859 if (b == NULL)
860 goto done;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700861 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000862 b->leftlink = rightblock;
863 CHECK_END(rightblock->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700864 rightblock->rightlink = b;
865 rightblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000866 MARK_END(b->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700867 rightindex = -1;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700868 b = NULL;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800869 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700870 assert (rightindex < BLOCKLEN - 1);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700871 {
872 PyObject **src, **dest;
873 Py_ssize_t m = -n;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800874
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700875 if (m > BLOCKLEN - leftindex)
876 m = BLOCKLEN - leftindex;
877 if (m > BLOCKLEN - 1 - rightindex)
878 m = BLOCKLEN - 1 - rightindex;
879 assert (m > 0 && m <= len);
880 src = &leftblock->data[leftindex];
881 dest = &rightblock->data[rightindex + 1];
882 leftindex += m;
883 rightindex += m;
884 n += m;
Raymond Hettinger840533b2013-07-13 17:03:58 -0700885 do {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700886 *(dest++) = *(src++);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700887 } while (--m);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700888 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700889 if (leftindex == BLOCKLEN) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700890 assert(leftblock != rightblock);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700891 assert(b == NULL);
Raymond Hettinger3959af92013-07-13 02:34:08 -0700892 b = leftblock;
Raymond Hettingerb97cc492013-07-21 01:51:07 -0700893 CHECK_NOT_END(leftblock->rightlink);
894 leftblock = leftblock->rightlink;
895 MARK_END(leftblock->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700896 leftindex = 0;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800897 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000898 }
Raymond Hettinger3959af92013-07-13 02:34:08 -0700899 rv = 0;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700900done:
Raymond Hettinger3959af92013-07-13 02:34:08 -0700901 if (b != NULL)
902 freeblock(b);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700903 deque->leftblock = leftblock;
904 deque->rightblock = rightblock;
905 deque->leftindex = leftindex;
906 deque->rightindex = rightindex;
907
908 return rv;
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000909}
910
911static PyObject *
912deque_rotate(dequeobject *deque, PyObject *args)
913{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 Py_ssize_t n=1;
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 if (!PyArg_ParseTuple(args, "|n:rotate", &n))
917 return NULL;
Raymond Hettinger6921c132015-03-21 02:03:40 -0700918 if (!_deque_rotate(deque, n))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000919 Py_RETURN_NONE;
920 return NULL;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000921}
922
Tim Peters1065f752004-10-01 01:03:29 +0000923PyDoc_STRVAR(rotate_doc,
Raymond Hettingeree33b272004-02-08 04:05:26 +0000924"Rotate the deque n steps to the right (default n=1). If n is negative, rotates left.");
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000925
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000926static PyObject *
927deque_reverse(dequeobject *deque, PyObject *unused)
928{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000929 block *leftblock = deque->leftblock;
930 block *rightblock = deque->rightblock;
931 Py_ssize_t leftindex = deque->leftindex;
932 Py_ssize_t rightindex = deque->rightindex;
Raymond Hettingercfe5b6c2015-07-20 00:25:50 -0400933 Py_ssize_t n = Py_SIZE(deque) >> 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 PyObject *tmp;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000935
Raymond Hettinger7a237232015-09-22 01:20:36 -0700936 while (n-- > 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000937 /* Validate that pointers haven't met in the middle */
938 assert(leftblock != rightblock || leftindex < rightindex);
Raymond Hettinger82df9252013-07-07 01:43:42 -1000939 CHECK_NOT_END(leftblock);
940 CHECK_NOT_END(rightblock);
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 /* Swap */
943 tmp = leftblock->data[leftindex];
944 leftblock->data[leftindex] = rightblock->data[rightindex];
945 rightblock->data[rightindex] = tmp;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 /* Advance left block/index pair */
948 leftindex++;
949 if (leftindex == BLOCKLEN) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 leftblock = leftblock->rightlink;
951 leftindex = 0;
952 }
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000953
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000954 /* Step backwards with the right block/index pair */
955 rightindex--;
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -0700956 if (rightindex < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000957 rightblock = rightblock->leftlink;
958 rightindex = BLOCKLEN - 1;
959 }
960 }
961 Py_RETURN_NONE;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000962}
963
964PyDoc_STRVAR(reverse_doc,
965"D.reverse() -- reverse *IN PLACE*");
966
Raymond Hettinger44459de2010-04-03 23:20:46 +0000967static PyObject *
968deque_count(dequeobject *deque, PyObject *v)
969{
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000970 block *b = deque->leftblock;
971 Py_ssize_t index = deque->leftindex;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000972 Py_ssize_t n = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000973 Py_ssize_t count = 0;
Raymond Hettingerf9d9c792015-03-02 22:47:46 -0800974 size_t start_state = deque->state;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000975 PyObject *item;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000976 int cmp;
Raymond Hettinger44459de2010-04-03 23:20:46 +0000977
Raymond Hettinger3a1a8d02015-09-23 02:42:02 -0700978 while (n--) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000979 CHECK_NOT_END(b);
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000980 item = b->data[index];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000981 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
Raymond Hettinger2b0d6462015-09-23 19:15:44 -0700982 if (cmp < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000983 return NULL;
Raymond Hettinger2b0d6462015-09-23 19:15:44 -0700984 count += cmp;
Raymond Hettinger44459de2010-04-03 23:20:46 +0000985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 if (start_state != deque->state) {
987 PyErr_SetString(PyExc_RuntimeError,
988 "deque mutated during iteration");
989 return NULL;
990 }
Raymond Hettinger44459de2010-04-03 23:20:46 +0000991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992 /* Advance left block/index pair */
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000993 index++;
994 if (index == BLOCKLEN) {
995 b = b->rightlink;
996 index = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 }
998 }
999 return PyLong_FromSsize_t(count);
Raymond Hettinger44459de2010-04-03 23:20:46 +00001000}
1001
1002PyDoc_STRVAR(count_doc,
1003"D.count(value) -> integer -- return number of occurrences of value");
1004
Raymond Hettinger39dadf72015-03-20 16:38:56 -07001005static int
1006deque_contains(dequeobject *deque, PyObject *v)
1007{
1008 block *b = deque->leftblock;
1009 Py_ssize_t index = deque->leftindex;
1010 Py_ssize_t n = Py_SIZE(deque);
Raymond Hettinger39dadf72015-03-20 16:38:56 -07001011 size_t start_state = deque->state;
1012 PyObject *item;
1013 int cmp;
1014
Raymond Hettinger3a1a8d02015-09-23 02:42:02 -07001015 while (n--) {
Raymond Hettinger39dadf72015-03-20 16:38:56 -07001016 CHECK_NOT_END(b);
1017 item = b->data[index];
1018 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
1019 if (cmp) {
1020 return cmp;
1021 }
1022 if (start_state != deque->state) {
1023 PyErr_SetString(PyExc_RuntimeError,
1024 "deque mutated during iteration");
1025 return -1;
1026 }
1027 index++;
1028 if (index == BLOCKLEN) {
1029 b = b->rightlink;
1030 index = 0;
1031 }
1032 }
1033 return 0;
1034}
1035
Martin v. Löwis18e16552006-02-15 17:27:45 +00001036static Py_ssize_t
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001037deque_len(dequeobject *deque)
1038{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001039 return Py_SIZE(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001040}
1041
Raymond Hettinger4aec61e2005-03-18 21:20:23 +00001042static PyObject *
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001043deque_index(dequeobject *deque, PyObject *args)
1044{
1045 Py_ssize_t i, start=0, stop=Py_SIZE(deque);
1046 PyObject *v, *item;
1047 block *b = deque->leftblock;
1048 Py_ssize_t index = deque->leftindex;
1049 size_t start_state = deque->state;
1050
1051 if (!PyArg_ParseTuple(args, "O|O&O&:index", &v,
1052 _PyEval_SliceIndex, &start,
1053 _PyEval_SliceIndex, &stop))
1054 return NULL;
1055 if (start < 0) {
1056 start += Py_SIZE(deque);
1057 if (start < 0)
1058 start = 0;
1059 }
1060 if (stop < 0) {
1061 stop += Py_SIZE(deque);
1062 if (stop < 0)
1063 stop = 0;
1064 }
Raymond Hettinger87674ec2015-08-26 08:08:38 -07001065 if (stop > Py_SIZE(deque))
1066 stop = Py_SIZE(deque);
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001067
1068 for (i=0 ; i<stop ; i++) {
1069 if (i >= start) {
1070 int cmp;
1071 CHECK_NOT_END(b);
1072 item = b->data[index];
1073 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
1074 if (cmp > 0)
1075 return PyLong_FromSsize_t(i);
1076 else if (cmp < 0)
1077 return NULL;
1078 if (start_state != deque->state) {
1079 PyErr_SetString(PyExc_RuntimeError,
1080 "deque mutated during iteration");
1081 return NULL;
1082 }
1083 }
1084 index++;
1085 if (index == BLOCKLEN) {
1086 b = b->rightlink;
1087 index = 0;
1088 }
1089 }
1090 PyErr_Format(PyExc_ValueError, "%R is not in deque", v);
1091 return NULL;
1092}
1093
1094PyDoc_STRVAR(index_doc,
1095"D.index(value, [start, [stop]]) -> integer -- return first index of value.\n"
1096"Raises ValueError if the value is not present.");
1097
Raymond Hettinger551350a2015-03-24 00:19:53 -07001098/* insert(), remove(), and delitem() are implemented in terms of
1099 rotate() for simplicity and reasonable performance near the end
1100 points. If for some reason these methods become popular, it is not
1101 hard to re-implement this using direct data movement (similar to
1102 the code used in list slice assignments) and achieve a performance
Raymond Hettingerfef9c1b2015-03-24 21:12:57 -07001103 boost (by moving each pointer only once instead of twice).
Raymond Hettinger551350a2015-03-24 00:19:53 -07001104*/
1105
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001106static PyObject *
1107deque_insert(dequeobject *deque, PyObject *args)
1108{
1109 Py_ssize_t index;
1110 Py_ssize_t n = Py_SIZE(deque);
1111 PyObject *value;
1112 PyObject *rv;
1113
1114 if (!PyArg_ParseTuple(args, "nO:insert", &index, &value))
1115 return NULL;
1116 if (index >= n)
1117 return deque_append(deque, value);
1118 if (index <= -n || index == 0)
1119 return deque_appendleft(deque, value);
1120 if (_deque_rotate(deque, -index))
1121 return NULL;
1122 if (index < 0)
1123 rv = deque_append(deque, value);
1124 else
1125 rv = deque_appendleft(deque, value);
1126 if (rv == NULL)
1127 return NULL;
1128 Py_DECREF(rv);
1129 if (_deque_rotate(deque, index))
1130 return NULL;
1131 Py_RETURN_NONE;
1132}
1133
1134PyDoc_STRVAR(insert_doc,
1135"D.insert(index, object) -- insert object before index");
1136
1137static PyObject *
Raymond Hettinger4aec61e2005-03-18 21:20:23 +00001138deque_remove(dequeobject *deque, PyObject *value)
1139{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001140 Py_ssize_t i, n=Py_SIZE(deque);
Raymond Hettinger4aec61e2005-03-18 21:20:23 +00001141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142 for (i=0 ; i<n ; i++) {
1143 PyObject *item = deque->leftblock->data[deque->leftindex];
1144 int cmp = PyObject_RichCompareBool(item, value, Py_EQ);
Raymond Hettingerd73202c2005-03-19 00:00:51 +00001145
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001146 if (Py_SIZE(deque) != n) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001147 PyErr_SetString(PyExc_IndexError,
1148 "deque mutated during remove().");
1149 return NULL;
1150 }
1151 if (cmp > 0) {
1152 PyObject *tgt = deque_popleft(deque, NULL);
1153 assert (tgt != NULL);
Raymond Hettinger6921c132015-03-21 02:03:40 -07001154 if (_deque_rotate(deque, i))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001155 return NULL;
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001156 Py_DECREF(tgt);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001157 Py_RETURN_NONE;
1158 }
1159 else if (cmp < 0) {
1160 _deque_rotate(deque, i);
1161 return NULL;
1162 }
1163 _deque_rotate(deque, -1);
1164 }
1165 PyErr_SetString(PyExc_ValueError, "deque.remove(x): x not in deque");
1166 return NULL;
Raymond Hettinger4aec61e2005-03-18 21:20:23 +00001167}
1168
1169PyDoc_STRVAR(remove_doc,
1170"D.remove(value) -- remove first occurrence of value.");
1171
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001172static int
1173valid_index(Py_ssize_t i, Py_ssize_t limit)
1174{
Raymond Hettinger12f896c2015-07-31 12:03:20 -07001175 /* The cast to size_t lets us use just a single comparison
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001176 to check whether i is in the range: 0 <= i < limit */
1177 return (size_t) i < (size_t) limit;
1178}
1179
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001180static PyObject *
Benjamin Petersond6313712008-07-31 16:23:04 +00001181deque_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001182{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 block *b;
1184 PyObject *item;
1185 Py_ssize_t n, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001186
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001187 if (!valid_index(i, Py_SIZE(deque))) {
1188 PyErr_SetString(PyExc_IndexError, "deque index out of range");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001189 return NULL;
1190 }
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001192 if (i == 0) {
1193 i = deque->leftindex;
1194 b = deque->leftblock;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001195 } else if (i == Py_SIZE(deque) - 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001196 i = deque->rightindex;
1197 b = deque->rightblock;
1198 } else {
1199 i += deque->leftindex;
Raymond Hettingerc2083082015-02-28 23:29:16 -08001200 n = (Py_ssize_t)((size_t) i / BLOCKLEN);
1201 i = (Py_ssize_t)((size_t) i % BLOCKLEN);
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001202 if (index < (Py_SIZE(deque) >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001203 b = deque->leftblock;
1204 while (n--)
1205 b = b->rightlink;
1206 } else {
Raymond Hettinger63d1ff22015-02-28 07:41:30 -08001207 n = (Py_ssize_t)(
Raymond Hettingerc2083082015-02-28 23:29:16 -08001208 ((size_t)(deque->leftindex + Py_SIZE(deque) - 1))
Raymond Hettinger63d1ff22015-02-28 07:41:30 -08001209 / BLOCKLEN - n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001210 b = deque->rightblock;
1211 while (n--)
1212 b = b->leftlink;
1213 }
1214 }
1215 item = b->data[i];
1216 Py_INCREF(item);
1217 return item;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001218}
1219
1220static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001221deque_del_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001222{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001223 PyObject *item;
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001224 int rv;
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001225
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001226 assert (i >= 0 && i < Py_SIZE(deque));
Raymond Hettinger6921c132015-03-21 02:03:40 -07001227 if (_deque_rotate(deque, -i))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001228 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 item = deque_popleft(deque, NULL);
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001230 rv = _deque_rotate(deque, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001231 assert (item != NULL);
1232 Py_DECREF(item);
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001233 return rv;
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001234}
1235
1236static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001237deque_ass_item(dequeobject *deque, Py_ssize_t i, PyObject *v)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001238{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001239 PyObject *old_value;
1240 block *b;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001241 Py_ssize_t n, len=Py_SIZE(deque), halflen=(len+1)>>1, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001242
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001243 if (!valid_index(i, len)) {
1244 PyErr_SetString(PyExc_IndexError, "deque index out of range");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001245 return -1;
1246 }
1247 if (v == NULL)
1248 return deque_del_item(deque, i);
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001250 i += deque->leftindex;
Raymond Hettingerc2083082015-02-28 23:29:16 -08001251 n = (Py_ssize_t)((size_t) i / BLOCKLEN);
1252 i = (Py_ssize_t)((size_t) i % BLOCKLEN);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001253 if (index <= halflen) {
1254 b = deque->leftblock;
1255 while (n--)
1256 b = b->rightlink;
1257 } else {
Raymond Hettingera473b9d2015-02-28 17:49:47 -08001258 n = (Py_ssize_t)(
Raymond Hettingerc2083082015-02-28 23:29:16 -08001259 ((size_t)(deque->leftindex + Py_SIZE(deque) - 1))
Raymond Hettingera473b9d2015-02-28 17:49:47 -08001260 / BLOCKLEN - n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001261 b = deque->rightblock;
1262 while (n--)
1263 b = b->leftlink;
1264 }
1265 Py_INCREF(v);
1266 old_value = b->data[i];
1267 b->data[i] = v;
1268 Py_DECREF(old_value);
1269 return 0;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001270}
1271
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001272static void
1273deque_dealloc(dequeobject *deque)
1274{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001275 PyObject_GC_UnTrack(deque);
1276 if (deque->weakreflist != NULL)
1277 PyObject_ClearWeakRefs((PyObject *) deque);
1278 if (deque->leftblock != NULL) {
1279 deque_clear(deque);
1280 assert(deque->leftblock != NULL);
1281 freeblock(deque->leftblock);
1282 }
1283 deque->leftblock = NULL;
1284 deque->rightblock = NULL;
1285 Py_TYPE(deque)->tp_free(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001286}
1287
1288static int
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001289deque_traverse(dequeobject *deque, visitproc visit, void *arg)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001290{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001291 block *b;
1292 PyObject *item;
1293 Py_ssize_t index;
1294 Py_ssize_t indexlo = deque->leftindex;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001295
Raymond Hettinger5bfa8672013-07-06 11:58:09 -10001296 for (b = deque->leftblock; b != deque->rightblock; b = b->rightlink) {
1297 for (index = indexlo; index < BLOCKLEN ; index++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001298 item = b->data[index];
1299 Py_VISIT(item);
1300 }
1301 indexlo = 0;
1302 }
Raymond Hettinger5bfa8672013-07-06 11:58:09 -10001303 for (index = indexlo; index <= deque->rightindex; index++) {
1304 item = b->data[index];
1305 Py_VISIT(item);
1306 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001307 return 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001308}
1309
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001310static PyObject *
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001311deque_reduce(dequeobject *deque)
1312{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001313 PyObject *dict, *result, *aslist;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001314 _Py_IDENTIFIER(__dict__);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001315
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001316 dict = _PyObject_GetAttrId((PyObject *)deque, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001317 if (dict == NULL)
1318 PyErr_Clear();
1319 aslist = PySequence_List((PyObject *)deque);
1320 if (aslist == NULL) {
1321 Py_XDECREF(dict);
1322 return NULL;
1323 }
1324 if (dict == NULL) {
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -07001325 if (deque->maxlen < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001326 result = Py_BuildValue("O(O)", Py_TYPE(deque), aslist);
1327 else
1328 result = Py_BuildValue("O(On)", Py_TYPE(deque), aslist, deque->maxlen);
1329 } else {
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -07001330 if (deque->maxlen < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001331 result = Py_BuildValue("O(OO)O", Py_TYPE(deque), aslist, Py_None, dict);
1332 else
1333 result = Py_BuildValue("O(On)O", Py_TYPE(deque), aslist, deque->maxlen, dict);
1334 }
1335 Py_XDECREF(dict);
1336 Py_DECREF(aslist);
1337 return result;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001338}
1339
1340PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
1341
1342static PyObject *
1343deque_repr(PyObject *deque)
1344{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001345 PyObject *aslist, *result;
1346 int i;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001348 i = Py_ReprEnter(deque);
1349 if (i != 0) {
1350 if (i < 0)
1351 return NULL;
1352 return PyUnicode_FromString("[...]");
1353 }
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001355 aslist = PySequence_List(deque);
1356 if (aslist == NULL) {
1357 Py_ReprLeave(deque);
1358 return NULL;
1359 }
1360 if (((dequeobject *)deque)->maxlen != -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001361 result = PyUnicode_FromFormat("deque(%R, maxlen=%zd)",
1362 aslist, ((dequeobject *)deque)->maxlen);
1363 else
1364 result = PyUnicode_FromFormat("deque(%R)", aslist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001365 Py_ReprLeave(deque);
Raymond Hettinger2b2b7532015-09-05 17:05:52 -07001366 Py_DECREF(aslist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001367 return result;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001368}
1369
Raymond Hettinger738ec902004-02-29 02:15:56 +00001370static PyObject *
1371deque_richcompare(PyObject *v, PyObject *w, int op)
1372{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001373 PyObject *it1=NULL, *it2=NULL, *x, *y;
1374 Py_ssize_t vs, ws;
1375 int b, cmp=-1;
Raymond Hettinger738ec902004-02-29 02:15:56 +00001376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001377 if (!PyObject_TypeCheck(v, &deque_type) ||
1378 !PyObject_TypeCheck(w, &deque_type)) {
Brian Curtindfc80e32011-08-10 20:28:54 -05001379 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001380 }
Raymond Hettinger738ec902004-02-29 02:15:56 +00001381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001382 /* Shortcuts */
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001383 vs = Py_SIZE((dequeobject *)v);
1384 ws = Py_SIZE((dequeobject *)w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001385 if (op == Py_EQ) {
1386 if (v == w)
1387 Py_RETURN_TRUE;
1388 if (vs != ws)
1389 Py_RETURN_FALSE;
1390 }
1391 if (op == Py_NE) {
1392 if (v == w)
1393 Py_RETURN_FALSE;
1394 if (vs != ws)
1395 Py_RETURN_TRUE;
1396 }
Raymond Hettinger738ec902004-02-29 02:15:56 +00001397
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001398 /* Search for the first index where items are different */
1399 it1 = PyObject_GetIter(v);
1400 if (it1 == NULL)
1401 goto done;
1402 it2 = PyObject_GetIter(w);
1403 if (it2 == NULL)
1404 goto done;
1405 for (;;) {
1406 x = PyIter_Next(it1);
1407 if (x == NULL && PyErr_Occurred())
1408 goto done;
1409 y = PyIter_Next(it2);
1410 if (x == NULL || y == NULL)
1411 break;
1412 b = PyObject_RichCompareBool(x, y, Py_EQ);
1413 if (b == 0) {
1414 cmp = PyObject_RichCompareBool(x, y, op);
1415 Py_DECREF(x);
1416 Py_DECREF(y);
1417 goto done;
1418 }
1419 Py_DECREF(x);
1420 Py_DECREF(y);
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -07001421 if (b < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001422 goto done;
1423 }
1424 /* We reached the end of one deque or both */
1425 Py_XDECREF(x);
1426 Py_XDECREF(y);
1427 if (PyErr_Occurred())
1428 goto done;
1429 switch (op) {
1430 case Py_LT: cmp = y != NULL; break; /* if w was longer */
1431 case Py_LE: cmp = x == NULL; break; /* if v was not longer */
1432 case Py_EQ: cmp = x == y; break; /* if we reached the end of both */
1433 case Py_NE: cmp = x != y; break; /* if one deque continues */
1434 case Py_GT: cmp = x != NULL; break; /* if v was longer */
1435 case Py_GE: cmp = y == NULL; break; /* if w was not longer */
1436 }
Tim Peters1065f752004-10-01 01:03:29 +00001437
Raymond Hettinger738ec902004-02-29 02:15:56 +00001438done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001439 Py_XDECREF(it1);
1440 Py_XDECREF(it2);
1441 if (cmp == 1)
1442 Py_RETURN_TRUE;
1443 if (cmp == 0)
1444 Py_RETURN_FALSE;
1445 return NULL;
Raymond Hettinger738ec902004-02-29 02:15:56 +00001446}
1447
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001448static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001449deque_init(dequeobject *deque, PyObject *args, PyObject *kwdargs)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001450{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001451 PyObject *iterable = NULL;
1452 PyObject *maxlenobj = NULL;
1453 Py_ssize_t maxlen = -1;
1454 char *kwlist[] = {"iterable", "maxlen", 0};
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001456 if (!PyArg_ParseTupleAndKeywords(args, kwdargs, "|OO:deque", kwlist, &iterable, &maxlenobj))
1457 return -1;
1458 if (maxlenobj != NULL && maxlenobj != Py_None) {
1459 maxlen = PyLong_AsSsize_t(maxlenobj);
1460 if (maxlen == -1 && PyErr_Occurred())
1461 return -1;
1462 if (maxlen < 0) {
1463 PyErr_SetString(PyExc_ValueError, "maxlen must be non-negative");
1464 return -1;
1465 }
1466 }
1467 deque->maxlen = maxlen;
1468 deque_clear(deque);
1469 if (iterable != NULL) {
1470 PyObject *rv = deque_extend(deque, iterable);
1471 if (rv == NULL)
1472 return -1;
1473 Py_DECREF(rv);
1474 }
1475 return 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001476}
1477
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001478static PyObject *
Jesus Cea16e2fca2012-08-03 14:49:42 +02001479deque_sizeof(dequeobject *deque, void *unused)
1480{
1481 Py_ssize_t res;
1482 Py_ssize_t blocks;
1483
1484 res = sizeof(dequeobject);
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001485 blocks = (deque->leftindex + Py_SIZE(deque) + BLOCKLEN - 1) / BLOCKLEN;
1486 assert(deque->leftindex + Py_SIZE(deque) - 1 ==
Jesus Cea16e2fca2012-08-03 14:49:42 +02001487 (blocks - 1) * BLOCKLEN + deque->rightindex);
1488 res += blocks * sizeof(block);
1489 return PyLong_FromSsize_t(res);
1490}
1491
1492PyDoc_STRVAR(sizeof_doc,
1493"D.__sizeof__() -- size of D in memory, in bytes");
1494
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001495static int
1496deque_bool(dequeobject *deque)
1497{
1498 return Py_SIZE(deque) != 0;
1499}
1500
Jesus Cea16e2fca2012-08-03 14:49:42 +02001501static PyObject *
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001502deque_get_maxlen(dequeobject *deque)
1503{
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -07001504 if (deque->maxlen < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001505 Py_RETURN_NONE;
1506 return PyLong_FromSsize_t(deque->maxlen);
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001507}
1508
Raymond Hettinger41290a62015-03-31 08:12:23 -07001509
1510/* deque object ********************************************************/
1511
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001512static PyGetSetDef deque_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001513 {"maxlen", (getter)deque_get_maxlen, (setter)NULL,
1514 "maximum size of a deque or None if unbounded"},
1515 {0}
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001516};
1517
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001518static PySequenceMethods deque_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001519 (lenfunc)deque_len, /* sq_length */
Raymond Hettinger41290a62015-03-31 08:12:23 -07001520 (binaryfunc)deque_concat, /* sq_concat */
1521 (ssizeargfunc)deque_repeat, /* sq_repeat */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001522 (ssizeargfunc)deque_item, /* sq_item */
1523 0, /* sq_slice */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001524 (ssizeobjargproc)deque_ass_item, /* sq_ass_item */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001525 0, /* sq_ass_slice */
Raymond Hettinger39dadf72015-03-20 16:38:56 -07001526 (objobjproc)deque_contains, /* sq_contains */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001527 (binaryfunc)deque_inplace_concat, /* sq_inplace_concat */
Raymond Hettinger41290a62015-03-31 08:12:23 -07001528 (ssizeargfunc)deque_inplace_repeat, /* sq_inplace_repeat */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001529};
1530
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001531static PyNumberMethods deque_as_number = {
1532 0, /* nb_add */
1533 0, /* nb_subtract */
1534 0, /* nb_multiply */
1535 0, /* nb_remainder */
1536 0, /* nb_divmod */
1537 0, /* nb_power */
1538 0, /* nb_negative */
1539 0, /* nb_positive */
1540 0, /* nb_absolute */
1541 (inquiry)deque_bool, /* nb_bool */
1542 0, /* nb_invert */
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001543 };
1544
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001545static PyObject *deque_iter(dequeobject *deque);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001546static PyObject *deque_reviter(dequeobject *deque);
Tim Peters1065f752004-10-01 01:03:29 +00001547PyDoc_STRVAR(reversed_doc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001548 "D.__reversed__() -- return a reverse iterator over the deque");
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001549
1550static PyMethodDef deque_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001551 {"append", (PyCFunction)deque_append,
1552 METH_O, append_doc},
1553 {"appendleft", (PyCFunction)deque_appendleft,
1554 METH_O, appendleft_doc},
1555 {"clear", (PyCFunction)deque_clearmethod,
1556 METH_NOARGS, clear_doc},
1557 {"__copy__", (PyCFunction)deque_copy,
1558 METH_NOARGS, copy_doc},
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001559 {"copy", (PyCFunction)deque_copy,
1560 METH_NOARGS, copy_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001561 {"count", (PyCFunction)deque_count,
Raymond Hettinger0f6f9472015-03-21 01:42:10 -07001562 METH_O, count_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001563 {"extend", (PyCFunction)deque_extend,
1564 METH_O, extend_doc},
1565 {"extendleft", (PyCFunction)deque_extendleft,
1566 METH_O, extendleft_doc},
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001567 {"index", (PyCFunction)deque_index,
1568 METH_VARARGS, index_doc},
1569 {"insert", (PyCFunction)deque_insert,
1570 METH_VARARGS, insert_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001571 {"pop", (PyCFunction)deque_pop,
1572 METH_NOARGS, pop_doc},
1573 {"popleft", (PyCFunction)deque_popleft,
1574 METH_NOARGS, popleft_doc},
Raymond Hettinger0f6f9472015-03-21 01:42:10 -07001575 {"__reduce__", (PyCFunction)deque_reduce,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001576 METH_NOARGS, reduce_doc},
1577 {"remove", (PyCFunction)deque_remove,
1578 METH_O, remove_doc},
1579 {"__reversed__", (PyCFunction)deque_reviter,
1580 METH_NOARGS, reversed_doc},
1581 {"reverse", (PyCFunction)deque_reverse,
1582 METH_NOARGS, reverse_doc},
1583 {"rotate", (PyCFunction)deque_rotate,
Jesus Cea16e2fca2012-08-03 14:49:42 +02001584 METH_VARARGS, rotate_doc},
1585 {"__sizeof__", (PyCFunction)deque_sizeof,
1586 METH_NOARGS, sizeof_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001587 {NULL, NULL} /* sentinel */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001588};
1589
1590PyDoc_STRVAR(deque_doc,
Andrew Svetlov6a5c7c32012-10-31 11:50:40 +02001591"deque([iterable[, maxlen]]) --> deque object\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001592\n\
Raymond Hettinger41290a62015-03-31 08:12:23 -07001593A list-like sequence optimized for data accesses near its endpoints.");
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001594
Neal Norwitz87f10132004-02-29 15:40:53 +00001595static PyTypeObject deque_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001596 PyVarObject_HEAD_INIT(NULL, 0)
1597 "collections.deque", /* tp_name */
1598 sizeof(dequeobject), /* tp_basicsize */
1599 0, /* tp_itemsize */
1600 /* methods */
1601 (destructor)deque_dealloc, /* tp_dealloc */
1602 0, /* tp_print */
1603 0, /* tp_getattr */
1604 0, /* tp_setattr */
1605 0, /* tp_reserved */
1606 deque_repr, /* tp_repr */
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001607 &deque_as_number, /* tp_as_number */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001608 &deque_as_sequence, /* tp_as_sequence */
1609 0, /* tp_as_mapping */
Georg Brandlf038b322010-10-18 07:35:09 +00001610 PyObject_HashNotImplemented, /* tp_hash */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001611 0, /* tp_call */
1612 0, /* tp_str */
1613 PyObject_GenericGetAttr, /* tp_getattro */
1614 0, /* tp_setattro */
1615 0, /* tp_as_buffer */
1616 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
Georg Brandlf038b322010-10-18 07:35:09 +00001617 /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001618 deque_doc, /* tp_doc */
1619 (traverseproc)deque_traverse, /* tp_traverse */
1620 (inquiry)deque_clear, /* tp_clear */
1621 (richcmpfunc)deque_richcompare, /* tp_richcompare */
Georg Brandlf038b322010-10-18 07:35:09 +00001622 offsetof(dequeobject, weakreflist), /* tp_weaklistoffset*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001623 (getiterfunc)deque_iter, /* tp_iter */
1624 0, /* tp_iternext */
1625 deque_methods, /* tp_methods */
1626 0, /* tp_members */
Georg Brandlf038b322010-10-18 07:35:09 +00001627 deque_getset, /* tp_getset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001628 0, /* tp_base */
1629 0, /* tp_dict */
1630 0, /* tp_descr_get */
1631 0, /* tp_descr_set */
1632 0, /* tp_dictoffset */
1633 (initproc)deque_init, /* tp_init */
1634 PyType_GenericAlloc, /* tp_alloc */
1635 deque_new, /* tp_new */
1636 PyObject_GC_Del, /* tp_free */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001637};
1638
1639/*********************** Deque Iterator **************************/
1640
1641typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001642 PyObject_HEAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001643 block *b;
Raymond Hettinger87e69122015-03-02 23:32:02 -08001644 Py_ssize_t index;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001645 dequeobject *deque;
Raymond Hettingerf9d9c792015-03-02 22:47:46 -08001646 size_t state; /* state when the iterator is created */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001647 Py_ssize_t counter; /* number of items remaining for iteration */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001648} dequeiterobject;
1649
Martin v. Löwis59683e82008-06-13 07:50:45 +00001650static PyTypeObject dequeiter_type;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001651
1652static PyObject *
1653deque_iter(dequeobject *deque)
1654{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001655 dequeiterobject *it;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001657 it = PyObject_GC_New(dequeiterobject, &dequeiter_type);
1658 if (it == NULL)
1659 return NULL;
1660 it->b = deque->leftblock;
1661 it->index = deque->leftindex;
1662 Py_INCREF(deque);
1663 it->deque = deque;
1664 it->state = deque->state;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001665 it->counter = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001666 PyObject_GC_Track(it);
1667 return (PyObject *)it;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001668}
1669
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001670static int
1671dequeiter_traverse(dequeiterobject *dio, visitproc visit, void *arg)
1672{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001673 Py_VISIT(dio->deque);
1674 return 0;
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001675}
1676
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001677static void
1678dequeiter_dealloc(dequeiterobject *dio)
1679{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001680 Py_XDECREF(dio->deque);
1681 PyObject_GC_Del(dio);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001682}
1683
1684static PyObject *
1685dequeiter_next(dequeiterobject *it)
1686{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001687 PyObject *item;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001688
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001689 if (it->deque->state != it->state) {
1690 it->counter = 0;
1691 PyErr_SetString(PyExc_RuntimeError,
1692 "deque mutated during iteration");
1693 return NULL;
1694 }
1695 if (it->counter == 0)
1696 return NULL;
1697 assert (!(it->b == it->deque->rightblock &&
1698 it->index > it->deque->rightindex));
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001699
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001700 item = it->b->data[it->index];
1701 it->index++;
1702 it->counter--;
1703 if (it->index == BLOCKLEN && it->counter > 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -10001704 CHECK_NOT_END(it->b->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001705 it->b = it->b->rightlink;
1706 it->index = 0;
1707 }
1708 Py_INCREF(item);
1709 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001710}
1711
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001712static PyObject *
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001713dequeiter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1714{
1715 Py_ssize_t i, index=0;
1716 PyObject *deque;
1717 dequeiterobject *it;
1718 if (!PyArg_ParseTuple(args, "O!|n", &deque_type, &deque, &index))
1719 return NULL;
1720 assert(type == &dequeiter_type);
1721
1722 it = (dequeiterobject*)deque_iter((dequeobject *)deque);
1723 if (!it)
1724 return NULL;
1725 /* consume items from the queue */
1726 for(i=0; i<index; i++) {
1727 PyObject *item = dequeiter_next(it);
1728 if (item) {
1729 Py_DECREF(item);
1730 } else {
1731 if (it->counter) {
1732 Py_DECREF(it);
1733 return NULL;
1734 } else
1735 break;
1736 }
1737 }
1738 return (PyObject*)it;
1739}
1740
1741static PyObject *
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001742dequeiter_len(dequeiterobject *it)
1743{
Antoine Pitrou554f3342010-08-17 18:30:06 +00001744 return PyLong_FromSsize_t(it->counter);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001745}
1746
Armin Rigof5b3e362006-02-11 21:32:43 +00001747PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001748
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001749static PyObject *
1750dequeiter_reduce(dequeiterobject *it)
1751{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001752 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 +00001753}
1754
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001755static PyMethodDef dequeiter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001756 {"__length_hint__", (PyCFunction)dequeiter_len, METH_NOARGS, length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001757 {"__reduce__", (PyCFunction)dequeiter_reduce, METH_NOARGS, reduce_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001758 {NULL, NULL} /* sentinel */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001759};
1760
Martin v. Löwis59683e82008-06-13 07:50:45 +00001761static PyTypeObject dequeiter_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001762 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger87e69122015-03-02 23:32:02 -08001763 "_collections._deque_iterator", /* tp_name */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001764 sizeof(dequeiterobject), /* tp_basicsize */
1765 0, /* tp_itemsize */
1766 /* methods */
1767 (destructor)dequeiter_dealloc, /* tp_dealloc */
1768 0, /* tp_print */
1769 0, /* tp_getattr */
1770 0, /* tp_setattr */
1771 0, /* tp_reserved */
1772 0, /* tp_repr */
1773 0, /* tp_as_number */
1774 0, /* tp_as_sequence */
1775 0, /* tp_as_mapping */
1776 0, /* tp_hash */
1777 0, /* tp_call */
1778 0, /* tp_str */
1779 PyObject_GenericGetAttr, /* tp_getattro */
1780 0, /* tp_setattro */
1781 0, /* tp_as_buffer */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001782 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001783 0, /* tp_doc */
1784 (traverseproc)dequeiter_traverse, /* tp_traverse */
1785 0, /* tp_clear */
1786 0, /* tp_richcompare */
1787 0, /* tp_weaklistoffset */
1788 PyObject_SelfIter, /* tp_iter */
1789 (iternextfunc)dequeiter_next, /* tp_iternext */
1790 dequeiter_methods, /* tp_methods */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001791 0, /* tp_members */
1792 0, /* tp_getset */
1793 0, /* tp_base */
1794 0, /* tp_dict */
1795 0, /* tp_descr_get */
1796 0, /* tp_descr_set */
1797 0, /* tp_dictoffset */
1798 0, /* tp_init */
1799 0, /* tp_alloc */
1800 dequeiter_new, /* tp_new */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001801 0,
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001802};
1803
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001804/*********************** Deque Reverse Iterator **************************/
1805
Martin v. Löwis59683e82008-06-13 07:50:45 +00001806static PyTypeObject dequereviter_type;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001807
1808static PyObject *
1809deque_reviter(dequeobject *deque)
1810{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001811 dequeiterobject *it;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001812
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001813 it = PyObject_GC_New(dequeiterobject, &dequereviter_type);
1814 if (it == NULL)
1815 return NULL;
1816 it->b = deque->rightblock;
1817 it->index = deque->rightindex;
1818 Py_INCREF(deque);
1819 it->deque = deque;
1820 it->state = deque->state;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001821 it->counter = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001822 PyObject_GC_Track(it);
1823 return (PyObject *)it;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001824}
1825
1826static PyObject *
1827dequereviter_next(dequeiterobject *it)
1828{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001829 PyObject *item;
1830 if (it->counter == 0)
1831 return NULL;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001832
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001833 if (it->deque->state != it->state) {
1834 it->counter = 0;
1835 PyErr_SetString(PyExc_RuntimeError,
1836 "deque mutated during iteration");
1837 return NULL;
1838 }
1839 assert (!(it->b == it->deque->leftblock &&
1840 it->index < it->deque->leftindex));
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001841
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001842 item = it->b->data[it->index];
1843 it->index--;
1844 it->counter--;
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -07001845 if (it->index < 0 && it->counter > 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -10001846 CHECK_NOT_END(it->b->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001847 it->b = it->b->leftlink;
1848 it->index = BLOCKLEN - 1;
1849 }
1850 Py_INCREF(item);
1851 return item;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001852}
1853
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001854static PyObject *
1855dequereviter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1856{
1857 Py_ssize_t i, index=0;
1858 PyObject *deque;
1859 dequeiterobject *it;
1860 if (!PyArg_ParseTuple(args, "O!|n", &deque_type, &deque, &index))
1861 return NULL;
1862 assert(type == &dequereviter_type);
1863
1864 it = (dequeiterobject*)deque_reviter((dequeobject *)deque);
1865 if (!it)
1866 return NULL;
1867 /* consume items from the queue */
1868 for(i=0; i<index; i++) {
1869 PyObject *item = dequereviter_next(it);
1870 if (item) {
1871 Py_DECREF(item);
1872 } else {
1873 if (it->counter) {
1874 Py_DECREF(it);
1875 return NULL;
1876 } else
1877 break;
1878 }
1879 }
1880 return (PyObject*)it;
1881}
1882
Martin v. Löwis59683e82008-06-13 07:50:45 +00001883static PyTypeObject dequereviter_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001884 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger87e69122015-03-02 23:32:02 -08001885 "_collections._deque_reverse_iterator", /* tp_name */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001886 sizeof(dequeiterobject), /* tp_basicsize */
1887 0, /* tp_itemsize */
1888 /* methods */
1889 (destructor)dequeiter_dealloc, /* tp_dealloc */
1890 0, /* tp_print */
1891 0, /* tp_getattr */
1892 0, /* tp_setattr */
1893 0, /* tp_reserved */
1894 0, /* tp_repr */
1895 0, /* tp_as_number */
1896 0, /* tp_as_sequence */
1897 0, /* tp_as_mapping */
1898 0, /* tp_hash */
1899 0, /* tp_call */
1900 0, /* tp_str */
1901 PyObject_GenericGetAttr, /* tp_getattro */
1902 0, /* tp_setattro */
1903 0, /* tp_as_buffer */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001904 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001905 0, /* tp_doc */
1906 (traverseproc)dequeiter_traverse, /* tp_traverse */
1907 0, /* tp_clear */
1908 0, /* tp_richcompare */
1909 0, /* tp_weaklistoffset */
1910 PyObject_SelfIter, /* tp_iter */
1911 (iternextfunc)dequereviter_next, /* tp_iternext */
1912 dequeiter_methods, /* tp_methods */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001913 0, /* tp_members */
1914 0, /* tp_getset */
1915 0, /* tp_base */
1916 0, /* tp_dict */
1917 0, /* tp_descr_get */
1918 0, /* tp_descr_set */
1919 0, /* tp_dictoffset */
1920 0, /* tp_init */
1921 0, /* tp_alloc */
1922 dequereviter_new, /* tp_new */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001923 0,
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001924};
1925
Guido van Rossum1968ad32006-02-25 22:38:04 +00001926/* defaultdict type *********************************************************/
1927
1928typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001929 PyDictObject dict;
1930 PyObject *default_factory;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001931} defdictobject;
1932
1933static PyTypeObject defdict_type; /* Forward */
1934
1935PyDoc_STRVAR(defdict_missing_doc,
1936"__missing__(key) # Called by __getitem__ for missing key; pseudo-code:\n\
Guido van Rossumd8faa362007-04-27 19:54:29 +00001937 if self.default_factory is None: raise KeyError((key,))\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00001938 self[key] = value = self.default_factory()\n\
1939 return value\n\
1940");
1941
1942static PyObject *
1943defdict_missing(defdictobject *dd, PyObject *key)
1944{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001945 PyObject *factory = dd->default_factory;
1946 PyObject *value;
1947 if (factory == NULL || factory == Py_None) {
1948 /* XXX Call dict.__missing__(key) */
1949 PyObject *tup;
1950 tup = PyTuple_Pack(1, key);
1951 if (!tup) return NULL;
1952 PyErr_SetObject(PyExc_KeyError, tup);
1953 Py_DECREF(tup);
1954 return NULL;
1955 }
1956 value = PyEval_CallObject(factory, NULL);
1957 if (value == NULL)
1958 return value;
1959 if (PyObject_SetItem((PyObject *)dd, key, value) < 0) {
1960 Py_DECREF(value);
1961 return NULL;
1962 }
1963 return value;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001964}
1965
1966PyDoc_STRVAR(defdict_copy_doc, "D.copy() -> a shallow copy of D.");
1967
1968static PyObject *
1969defdict_copy(defdictobject *dd)
1970{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001971 /* This calls the object's class. That only works for subclasses
1972 whose class constructor has the same signature. Subclasses that
1973 define a different constructor signature must override copy().
1974 */
Raymond Hettinger54628fa2009-08-04 19:16:39 +00001975
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001976 if (dd->default_factory == NULL)
1977 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd), Py_None, dd, NULL);
1978 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd),
1979 dd->default_factory, dd, NULL);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001980}
1981
1982static PyObject *
1983defdict_reduce(defdictobject *dd)
1984{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001985 /* __reduce__ must return a 5-tuple as follows:
Guido van Rossum1968ad32006-02-25 22:38:04 +00001986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001987 - factory function
1988 - tuple of args for the factory function
1989 - additional state (here None)
1990 - sequence iterator (here None)
1991 - dictionary iterator (yielding successive (key, value) pairs
Guido van Rossum1968ad32006-02-25 22:38:04 +00001992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001993 This API is used by pickle.py and copy.py.
Guido van Rossum1968ad32006-02-25 22:38:04 +00001994
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001995 For this to be useful with pickle.py, the default_factory
1996 must be picklable; e.g., None, a built-in, or a global
1997 function in a module or package.
Guido van Rossum1968ad32006-02-25 22:38:04 +00001998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001999 Both shallow and deep copying are supported, but for deep
2000 copying, the default_factory must be deep-copyable; e.g. None,
2001 or a built-in (functions are not copyable at this time).
Guido van Rossum1968ad32006-02-25 22:38:04 +00002002
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002003 This only works for subclasses as long as their constructor
2004 signature is compatible; the first argument must be the
2005 optional default_factory, defaulting to None.
2006 */
2007 PyObject *args;
2008 PyObject *items;
2009 PyObject *iter;
2010 PyObject *result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002011 _Py_IDENTIFIER(items);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002013 if (dd->default_factory == NULL || dd->default_factory == Py_None)
2014 args = PyTuple_New(0);
2015 else
2016 args = PyTuple_Pack(1, dd->default_factory);
2017 if (args == NULL)
2018 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002019 items = _PyObject_CallMethodId((PyObject *)dd, &PyId_items, "()");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002020 if (items == NULL) {
2021 Py_DECREF(args);
2022 return NULL;
2023 }
2024 iter = PyObject_GetIter(items);
2025 if (iter == NULL) {
2026 Py_DECREF(items);
2027 Py_DECREF(args);
2028 return NULL;
2029 }
2030 result = PyTuple_Pack(5, Py_TYPE(dd), args,
2031 Py_None, Py_None, iter);
2032 Py_DECREF(iter);
2033 Py_DECREF(items);
2034 Py_DECREF(args);
2035 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00002036}
2037
2038static PyMethodDef defdict_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002039 {"__missing__", (PyCFunction)defdict_missing, METH_O,
2040 defdict_missing_doc},
2041 {"copy", (PyCFunction)defdict_copy, METH_NOARGS,
2042 defdict_copy_doc},
2043 {"__copy__", (PyCFunction)defdict_copy, METH_NOARGS,
2044 defdict_copy_doc},
2045 {"__reduce__", (PyCFunction)defdict_reduce, METH_NOARGS,
2046 reduce_doc},
2047 {NULL}
Guido van Rossum1968ad32006-02-25 22:38:04 +00002048};
2049
2050static PyMemberDef defdict_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002051 {"default_factory", T_OBJECT,
2052 offsetof(defdictobject, default_factory), 0,
2053 PyDoc_STR("Factory for default value called by __missing__().")},
2054 {NULL}
Guido van Rossum1968ad32006-02-25 22:38:04 +00002055};
2056
2057static void
2058defdict_dealloc(defdictobject *dd)
2059{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002060 Py_CLEAR(dd->default_factory);
2061 PyDict_Type.tp_dealloc((PyObject *)dd);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002062}
2063
Guido van Rossum1968ad32006-02-25 22:38:04 +00002064static PyObject *
2065defdict_repr(defdictobject *dd)
2066{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002067 PyObject *baserepr;
2068 PyObject *defrepr;
2069 PyObject *result;
2070 baserepr = PyDict_Type.tp_repr((PyObject *)dd);
2071 if (baserepr == NULL)
2072 return NULL;
2073 if (dd->default_factory == NULL)
2074 defrepr = PyUnicode_FromString("None");
2075 else
2076 {
2077 int status = Py_ReprEnter(dd->default_factory);
2078 if (status != 0) {
Antoine Pitrouf5f1fe02012-02-15 02:42:46 +01002079 if (status < 0) {
2080 Py_DECREF(baserepr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002081 return NULL;
Antoine Pitrouf5f1fe02012-02-15 02:42:46 +01002082 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002083 defrepr = PyUnicode_FromString("...");
2084 }
2085 else
2086 defrepr = PyObject_Repr(dd->default_factory);
2087 Py_ReprLeave(dd->default_factory);
2088 }
2089 if (defrepr == NULL) {
2090 Py_DECREF(baserepr);
2091 return NULL;
2092 }
2093 result = PyUnicode_FromFormat("defaultdict(%U, %U)",
2094 defrepr, baserepr);
2095 Py_DECREF(defrepr);
2096 Py_DECREF(baserepr);
2097 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00002098}
2099
2100static int
2101defdict_traverse(PyObject *self, visitproc visit, void *arg)
2102{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002103 Py_VISIT(((defdictobject *)self)->default_factory);
2104 return PyDict_Type.tp_traverse(self, visit, arg);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002105}
2106
2107static int
2108defdict_tp_clear(defdictobject *dd)
2109{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002110 Py_CLEAR(dd->default_factory);
2111 return PyDict_Type.tp_clear((PyObject *)dd);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002112}
2113
2114static int
2115defdict_init(PyObject *self, PyObject *args, PyObject *kwds)
2116{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002117 defdictobject *dd = (defdictobject *)self;
2118 PyObject *olddefault = dd->default_factory;
2119 PyObject *newdefault = NULL;
2120 PyObject *newargs;
2121 int result;
2122 if (args == NULL || !PyTuple_Check(args))
2123 newargs = PyTuple_New(0);
2124 else {
2125 Py_ssize_t n = PyTuple_GET_SIZE(args);
2126 if (n > 0) {
2127 newdefault = PyTuple_GET_ITEM(args, 0);
2128 if (!PyCallable_Check(newdefault) && newdefault != Py_None) {
2129 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger239aba72015-07-20 03:09:22 -04002130 "first argument must be callable or None");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002131 return -1;
2132 }
2133 }
2134 newargs = PySequence_GetSlice(args, 1, n);
2135 }
2136 if (newargs == NULL)
2137 return -1;
2138 Py_XINCREF(newdefault);
2139 dd->default_factory = newdefault;
2140 result = PyDict_Type.tp_init(self, newargs, kwds);
2141 Py_DECREF(newargs);
2142 Py_XDECREF(olddefault);
2143 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00002144}
2145
2146PyDoc_STRVAR(defdict_doc,
Benjamin Peterson9cb33b72014-01-13 23:56:05 -05002147"defaultdict(default_factory[, ...]) --> dict with default factory\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00002148\n\
2149The default factory is called without arguments to produce\n\
2150a new value when a key is not present, in __getitem__ only.\n\
2151A defaultdict compares equal to a dict with the same items.\n\
Benjamin Peterson9cb33b72014-01-13 23:56:05 -05002152All remaining arguments are treated the same as if they were\n\
2153passed to the dict constructor, including keyword arguments.\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00002154");
2155
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002156/* See comment in xxsubtype.c */
2157#define DEFERRED_ADDRESS(ADDR) 0
2158
Guido van Rossum1968ad32006-02-25 22:38:04 +00002159static PyTypeObject defdict_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002160 PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0)
2161 "collections.defaultdict", /* tp_name */
2162 sizeof(defdictobject), /* tp_basicsize */
2163 0, /* tp_itemsize */
2164 /* methods */
2165 (destructor)defdict_dealloc, /* tp_dealloc */
2166 0, /* tp_print */
2167 0, /* tp_getattr */
2168 0, /* tp_setattr */
2169 0, /* tp_reserved */
2170 (reprfunc)defdict_repr, /* tp_repr */
2171 0, /* tp_as_number */
2172 0, /* tp_as_sequence */
2173 0, /* tp_as_mapping */
2174 0, /* tp_hash */
2175 0, /* tp_call */
2176 0, /* tp_str */
2177 PyObject_GenericGetAttr, /* tp_getattro */
2178 0, /* tp_setattro */
2179 0, /* tp_as_buffer */
2180 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
2181 /* tp_flags */
2182 defdict_doc, /* tp_doc */
2183 defdict_traverse, /* tp_traverse */
2184 (inquiry)defdict_tp_clear, /* tp_clear */
2185 0, /* tp_richcompare */
2186 0, /* tp_weaklistoffset*/
2187 0, /* tp_iter */
2188 0, /* tp_iternext */
2189 defdict_methods, /* tp_methods */
2190 defdict_members, /* tp_members */
2191 0, /* tp_getset */
2192 DEFERRED_ADDRESS(&PyDict_Type), /* tp_base */
2193 0, /* tp_dict */
2194 0, /* tp_descr_get */
2195 0, /* tp_descr_set */
2196 0, /* tp_dictoffset */
2197 defdict_init, /* tp_init */
2198 PyType_GenericAlloc, /* tp_alloc */
2199 0, /* tp_new */
2200 PyObject_GC_Del, /* tp_free */
Guido van Rossum1968ad32006-02-25 22:38:04 +00002201};
2202
Raymond Hettinger96f34102010-12-15 16:30:37 +00002203/* helper function for Counter *********************************************/
2204
2205PyDoc_STRVAR(_count_elements_doc,
2206"_count_elements(mapping, iterable) -> None\n\
2207\n\
2208Count elements in the iterable, updating the mappping");
2209
2210static PyObject *
2211_count_elements(PyObject *self, PyObject *args)
2212{
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002213 _Py_IDENTIFIER(get);
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002214 _Py_IDENTIFIER(__setitem__);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002215 PyObject *it, *iterable, *mapping, *oldval;
2216 PyObject *newval = NULL;
2217 PyObject *key = NULL;
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002218 PyObject *zero = NULL;
Raymond Hettinger96f34102010-12-15 16:30:37 +00002219 PyObject *one = NULL;
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002220 PyObject *bound_get = NULL;
2221 PyObject *mapping_get;
2222 PyObject *dict_get;
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002223 PyObject *mapping_setitem;
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002224 PyObject *dict_setitem;
Raymond Hettinger96f34102010-12-15 16:30:37 +00002225
2226 if (!PyArg_UnpackTuple(args, "_count_elements", 2, 2, &mapping, &iterable))
2227 return NULL;
2228
Raymond Hettinger96f34102010-12-15 16:30:37 +00002229 it = PyObject_GetIter(iterable);
2230 if (it == NULL)
2231 return NULL;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002232
Raymond Hettinger96f34102010-12-15 16:30:37 +00002233 one = PyLong_FromLong(1);
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002234 if (one == NULL)
2235 goto done;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002236
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002237 /* Only take the fast path when get() and __setitem__()
2238 * have not been overridden.
2239 */
2240 mapping_get = _PyType_LookupId(Py_TYPE(mapping), &PyId_get);
2241 dict_get = _PyType_LookupId(&PyDict_Type, &PyId_get);
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002242 mapping_setitem = _PyType_LookupId(Py_TYPE(mapping), &PyId___setitem__);
2243 dict_setitem = _PyType_LookupId(&PyDict_Type, &PyId___setitem__);
2244
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002245 if (mapping_get != NULL && mapping_get == dict_get &&
2246 mapping_setitem != NULL && mapping_setitem == dict_setitem) {
Raymond Hettinger426e0522011-01-03 02:12:02 +00002247 while (1) {
Raymond Hettinger507d9972014-05-18 21:32:40 +01002248 /* Fast path advantages:
2249 1. Eliminate double hashing
2250 (by re-using the same hash for both the get and set)
2251 2. Avoid argument overhead of PyObject_CallFunctionObjArgs
2252 (argument tuple creation and parsing)
2253 3. Avoid indirection through a bound method object
2254 (creates another argument tuple)
2255 4. Avoid initial increment from zero
2256 (reuse an existing one-object instead)
2257 */
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002258 Py_hash_t hash;
2259
Raymond Hettinger426e0522011-01-03 02:12:02 +00002260 key = PyIter_Next(it);
Victor Stinnera154b5c2011-04-20 23:23:52 +02002261 if (key == NULL)
2262 break;
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002263
2264 if (!PyUnicode_CheckExact(key) ||
2265 (hash = ((PyASCIIObject *) key)->hash) == -1)
2266 {
2267 hash = PyObject_Hash(key);
Raymond Hettingerda2850f2015-02-27 12:42:54 -08002268 if (hash == -1)
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002269 goto done;
2270 }
2271
2272 oldval = _PyDict_GetItem_KnownHash(mapping, key, hash);
Raymond Hettinger426e0522011-01-03 02:12:02 +00002273 if (oldval == NULL) {
Raymond Hettinger28c995d2015-08-14 02:07:41 -07002274 if (_PyDict_SetItem_KnownHash(mapping, key, one, hash) < 0)
Raymond Hettinger507d9972014-05-18 21:32:40 +01002275 goto done;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002276 } else {
2277 newval = PyNumber_Add(oldval, one);
2278 if (newval == NULL)
Raymond Hettinger507d9972014-05-18 21:32:40 +01002279 goto done;
Raymond Hettinger28c995d2015-08-14 02:07:41 -07002280 if (_PyDict_SetItem_KnownHash(mapping, key, newval, hash) < 0)
Raymond Hettinger507d9972014-05-18 21:32:40 +01002281 goto done;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002282 Py_CLEAR(newval);
2283 }
2284 Py_DECREF(key);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002285 }
Raymond Hettinger426e0522011-01-03 02:12:02 +00002286 } else {
Victor Stinnere7f516c2013-11-06 23:52:55 +01002287 bound_get = _PyObject_GetAttrId(mapping, &PyId_get);
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002288 if (bound_get == NULL)
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002289 goto done;
2290
2291 zero = PyLong_FromLong(0);
2292 if (zero == NULL)
2293 goto done;
2294
Raymond Hettinger426e0522011-01-03 02:12:02 +00002295 while (1) {
2296 key = PyIter_Next(it);
Victor Stinnera154b5c2011-04-20 23:23:52 +02002297 if (key == NULL)
2298 break;
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002299 oldval = PyObject_CallFunctionObjArgs(bound_get, key, zero, NULL);
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002300 if (oldval == NULL)
2301 break;
2302 newval = PyNumber_Add(oldval, one);
2303 Py_DECREF(oldval);
2304 if (newval == NULL)
2305 break;
Raymond Hettinger28c995d2015-08-14 02:07:41 -07002306 if (PyObject_SetItem(mapping, key, newval) < 0)
Raymond Hettinger96f34102010-12-15 16:30:37 +00002307 break;
2308 Py_CLEAR(newval);
Raymond Hettinger426e0522011-01-03 02:12:02 +00002309 Py_DECREF(key);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002310 }
Raymond Hettinger96f34102010-12-15 16:30:37 +00002311 }
Raymond Hettinger426e0522011-01-03 02:12:02 +00002312
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002313done:
Raymond Hettinger96f34102010-12-15 16:30:37 +00002314 Py_DECREF(it);
2315 Py_XDECREF(key);
2316 Py_XDECREF(newval);
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002317 Py_XDECREF(bound_get);
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002318 Py_XDECREF(zero);
2319 Py_XDECREF(one);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002320 if (PyErr_Occurred())
2321 return NULL;
2322 Py_RETURN_NONE;
2323}
2324
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002325/* module level code ********************************************************/
2326
2327PyDoc_STRVAR(module_doc,
Guido van Rossum1968ad32006-02-25 22:38:04 +00002328"High performance data structures.\n\
2329- deque: ordered collection accessible from endpoints only\n\
2330- defaultdict: dict subclass with a default value factory\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002331");
2332
Raymond Hettinger96f34102010-12-15 16:30:37 +00002333static struct PyMethodDef module_functions[] = {
2334 {"_count_elements", _count_elements, METH_VARARGS, _count_elements_doc},
2335 {NULL, NULL} /* sentinel */
2336};
Martin v. Löwis1a214512008-06-11 05:26:20 +00002337
2338static struct PyModuleDef _collectionsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002339 PyModuleDef_HEAD_INIT,
2340 "_collections",
2341 module_doc,
2342 -1,
Raymond Hettinger96f34102010-12-15 16:30:37 +00002343 module_functions,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002344 NULL,
2345 NULL,
2346 NULL,
2347 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002348};
2349
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002350PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002351PyInit__collections(void)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002352{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002353 PyObject *m;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002355 m = PyModule_Create(&_collectionsmodule);
2356 if (m == NULL)
2357 return NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002359 if (PyType_Ready(&deque_type) < 0)
2360 return NULL;
2361 Py_INCREF(&deque_type);
2362 PyModule_AddObject(m, "deque", (PyObject *)&deque_type);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002364 defdict_type.tp_base = &PyDict_Type;
2365 if (PyType_Ready(&defdict_type) < 0)
2366 return NULL;
2367 Py_INCREF(&defdict_type);
2368 PyModule_AddObject(m, "defaultdict", (PyObject *)&defdict_type);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002369
Eric Snow47db7172015-05-29 22:21:39 -06002370 Py_INCREF(&PyODict_Type);
2371 PyModule_AddObject(m, "OrderedDict", (PyObject *)&PyODict_Type);
2372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002373 if (PyType_Ready(&dequeiter_type) < 0)
2374 return NULL;
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002375 Py_INCREF(&dequeiter_type);
2376 PyModule_AddObject(m, "_deque_iterator", (PyObject *)&dequeiter_type);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002378 if (PyType_Ready(&dequereviter_type) < 0)
2379 return NULL;
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002380 Py_INCREF(&dequereviter_type);
2381 PyModule_AddObject(m, "_deque_reverse_iterator", (PyObject *)&dequereviter_type);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00002382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002383 return m;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002384}