blob: 087f8e51a5a64ecc44fec1d69b4845b0212998ef [file] [log] [blame]
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001#include "Python.h"
Raymond Hettinger691d8052004-05-30 07:26:47 +00002#include "structmember.h"
Raymond Hettinger756b3f32004-01-29 06:37:52 +00003
Raymond Hettingerc2083082015-02-28 23:29:16 -08004#ifdef STDC_HEADERS
5#include <stddef.h>
6#else
7#include <sys/types.h> /* For size_t */
8#endif
9
Raymond Hettinger756b3f32004-01-29 06:37:52 +000010/* collections module implementation of a deque() datatype
11 Written and maintained by Raymond D. Hettinger <python@rcn.com>
Raymond Hettingereb6b5542015-02-10 22:37:22 -060012 Copyright (c) 2004-2015 Python Software Foundation.
Raymond Hettinger756b3f32004-01-29 06:37:52 +000013 All rights reserved.
14*/
15
Raymond Hettinger77e8bf12004-10-01 15:25:53 +000016/* The block length may be set to any number over 1. Larger numbers
Raymond Hettinger20b0f872013-06-23 15:44:33 -070017 * reduce the number of calls to the memory allocator, give faster
Raymond Hettinger30c90742015-03-02 22:31:35 -080018 * indexing and rotation, and reduce the link to data overhead ratio.
Raymond Hettingerdaf57f22015-02-26 23:21:29 -080019 * Making the block length a power of two speeds-up the modulo
Raymond Hettinger30c90742015-03-02 22:31:35 -080020 * and division calculations in deque_item() and deque_ass_item().
Raymond Hettinger77e8bf12004-10-01 15:25:53 +000021 */
22
Raymond Hettingerdaf57f22015-02-26 23:21:29 -080023#define BLOCKLEN 64
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000024#define CENTER ((BLOCKLEN - 1) / 2)
Raymond Hettinger756b3f32004-01-29 06:37:52 +000025
Raymond Hettinger551350a2015-03-24 00:19:53 -070026/* Data for deque objects is stored in a doubly-linked list of fixed
27 * length blocks. This assures that appends or pops never move any
28 * other data elements besides the one being appended or popped.
29 *
30 * Another advantage is that it completely avoids use of realloc(),
31 * resulting in more predictable performance.
32 *
33 * Textbook implementations of doubly-linked lists store one datum
34 * per link, but that gives them a 200% memory overhead (a prev and
35 * next link for each datum) and it costs one malloc() call per data
36 * element. By using fixed-length blocks, the link to data ratio is
37 * significantly improved and there are proportionally fewer calls
38 * to malloc() and free(). The data blocks of consecutive pointers
39 * also improve cache locality.
40 *
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000041 * The list of blocks is never empty, so d.leftblock and d.rightblock
Raymond Hettinger82df9252013-07-07 01:43:42 -100042 * are never equal to NULL. The list is not circular.
43 *
44 * A deque d's first element is at d.leftblock[leftindex]
45 * and its last element is at d.rightblock[rightindex].
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000046 *
Raymond Hettinger551350a2015-03-24 00:19:53 -070047 * Unlike Python slice indices, these indices are inclusive on both
48 * ends. This makes the algorithms for left and right operations
49 * more symmetrical and it simplifies the design.
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000050 *
Raymond Hettinger551350a2015-03-24 00:19:53 -070051 * The indices, d.leftindex and d.rightindex are always in the range:
52 * 0 <= index < BLOCKLEN
53 *
54 * And their exact relationship is:
55 * (d.leftindex + d.len - 1) % BLOCKLEN == d.rightindex
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000056 *
Raymond Hettinger8dbbae22015-03-24 21:01:50 -070057 * Whenever d.leftblock == d.rightblock, then:
Raymond Hettinger551350a2015-03-24 00:19:53 -070058 * d.leftindex + d.len - 1 == d.rightindex
Thomas Wouters0e3f5912006-08-11 14:57:12 +000059 *
Raymond Hettinger551350a2015-03-24 00:19:53 -070060 * However, when d.leftblock != d.rightblock, the d.leftindex and
61 * d.rightindex become indices into distinct blocks and either may
62 * be larger than the other.
63 *
64 * Empty deques have:
65 * d.len == 0
66 * d.leftblock == d.rightblock
67 * d.leftindex == CENTER + 1
68 * d.rightindex == CENTER
69 *
70 * Checking for d.len == 0 is the intended way to see whether d is empty.
Tim Petersd8768d32004-10-01 01:32:53 +000071 */
72
Raymond Hettinger756b3f32004-01-29 06:37:52 +000073typedef struct BLOCK {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000074 struct BLOCK *leftlink;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000075 PyObject *data[BLOCKLEN];
Raymond Hettinger20b0f872013-06-23 15:44:33 -070076 struct BLOCK *rightlink;
Raymond Hettinger756b3f32004-01-29 06:37:52 +000077} block;
78
Raymond Hettinger30c90742015-03-02 22:31:35 -080079typedef struct {
80 PyObject_VAR_HEAD
81 block *leftblock;
82 block *rightblock;
Raymond Hettinger551350a2015-03-24 00:19:53 -070083 Py_ssize_t leftindex; /* 0 <= leftindex < BLOCKLEN */
84 Py_ssize_t rightindex; /* 0 <= rightindex < BLOCKLEN */
Raymond Hettingerf9d9c792015-03-02 22:47:46 -080085 size_t state; /* incremented whenever the indices move */
Raymond Hettinger30c90742015-03-02 22:31:35 -080086 Py_ssize_t maxlen;
Raymond Hettinger0f6f9472015-03-21 01:42:10 -070087 PyObject *weakreflist;
Raymond Hettinger30c90742015-03-02 22:31:35 -080088} dequeobject;
89
90static PyTypeObject deque_type;
91
Raymond Hettinger82df9252013-07-07 01:43:42 -100092/* For debug builds, add error checking to track the endpoints
93 * in the chain of links. The goal is to make sure that link
94 * assignments only take place at endpoints so that links already
95 * in use do not get overwritten.
96 *
97 * CHECK_END should happen before each assignment to a block's link field.
98 * MARK_END should happen whenever a link field becomes a new endpoint.
99 * This happens when new blocks are added or whenever an existing
100 * block is freed leaving another existing block as the new endpoint.
101 */
102
Raymond Hettinger3223dd52013-07-26 23:14:22 -0700103#ifndef NDEBUG
Raymond Hettinger82df9252013-07-07 01:43:42 -1000104#define MARK_END(link) link = NULL;
105#define CHECK_END(link) assert(link == NULL);
106#define CHECK_NOT_END(link) assert(link != NULL);
107#else
108#define MARK_END(link)
109#define CHECK_END(link)
110#define CHECK_NOT_END(link)
111#endif
112
Raymond Hettinger41290a62015-03-31 08:12:23 -0700113/* To prevent len from overflowing PY_SSIZE_T_MAX, we refuse to
114 allocate new blocks if the current len is nearing overflow.
115*/
116
117#define MAX_DEQUE_LEN (PY_SSIZE_T_MAX - 3*BLOCKLEN)
118
Raymond Hettinger82df9252013-07-07 01:43:42 -1000119/* A simple freelisting scheme is used to minimize calls to the memory
Raymond Hettinger551350a2015-03-24 00:19:53 -0700120 allocator. It accommodates common use cases where new blocks are being
Raymond Hettinger82df9252013-07-07 01:43:42 -1000121 added at about the same rate as old blocks are being freed.
122 */
123
Guido van Rossum58da9312007-11-10 23:39:45 +0000124#define MAXFREEBLOCKS 10
Benjamin Petersond6313712008-07-31 16:23:04 +0000125static Py_ssize_t numfreeblocks = 0;
Guido van Rossum58da9312007-11-10 23:39:45 +0000126static block *freeblocks[MAXFREEBLOCKS];
127
Tim Peters6f853562004-10-01 01:04:50 +0000128static block *
Raymond Hettinger82df9252013-07-07 01:43:42 -1000129newblock(Py_ssize_t len) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000130 block *b;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700131 if (len >= MAX_DEQUE_LEN) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000132 PyErr_SetString(PyExc_OverflowError,
133 "cannot add more blocks to the deque");
134 return NULL;
135 }
136 if (numfreeblocks) {
Raymond Hettinger59cf23a2013-02-07 00:57:19 -0500137 numfreeblocks--;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000138 return freeblocks[numfreeblocks];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000139 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000140 b = PyMem_Malloc(sizeof(block));
141 if (b != NULL) {
142 return b;
143 }
144 PyErr_NoMemory();
145 return NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000146}
147
Martin v. Löwis59683e82008-06-13 07:50:45 +0000148static void
Guido van Rossum58da9312007-11-10 23:39:45 +0000149freeblock(block *b)
150{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000151 if (numfreeblocks < MAXFREEBLOCKS) {
152 freeblocks[numfreeblocks] = b;
153 numfreeblocks++;
154 } else {
155 PyMem_Free(b);
156 }
Guido van Rossum58da9312007-11-10 23:39:45 +0000157}
158
Raymond Hettingerda2850f2015-02-27 12:42:54 -0800159/* XXX Todo:
Raymond Hettinger54023152014-04-23 00:58:48 -0700160 If aligned memory allocations become available, make the
161 deque object 64 byte aligned so that all of the fields
162 can be retrieved or updated in a single cache line.
163*/
164
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000165static PyObject *
166deque_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
167{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000168 dequeobject *deque;
169 block *b;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000171 /* create dequeobject structure */
172 deque = (dequeobject *)type->tp_alloc(type, 0);
173 if (deque == NULL)
174 return NULL;
Tim Peters1065f752004-10-01 01:03:29 +0000175
Raymond Hettinger82df9252013-07-07 01:43:42 -1000176 b = newblock(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000177 if (b == NULL) {
178 Py_DECREF(deque);
179 return NULL;
180 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000181 MARK_END(b->leftlink);
182 MARK_END(b->rightlink);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000184 assert(BLOCKLEN >= 2);
Raymond Hettinger87e69122015-03-02 23:32:02 -0800185 Py_SIZE(deque) = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000186 deque->leftblock = b;
187 deque->rightblock = b;
188 deque->leftindex = CENTER + 1;
189 deque->rightindex = CENTER;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000190 deque->state = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000191 deque->maxlen = -1;
Raymond Hettinger87e69122015-03-02 23:32:02 -0800192 deque->weakreflist = NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000194 return (PyObject *)deque;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000195}
196
197static PyObject *
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000198deque_pop(dequeobject *deque, PyObject *unused)
199{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000200 PyObject *item;
201 block *prevblock;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000202
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000203 if (Py_SIZE(deque) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000204 PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
205 return NULL;
206 }
207 item = deque->rightblock->data[deque->rightindex];
208 deque->rightindex--;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000209 Py_SIZE(deque)--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000210 deque->state++;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000212 if (deque->rightindex == -1) {
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700213 if (Py_SIZE(deque)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000214 prevblock = deque->rightblock->leftlink;
215 assert(deque->leftblock != deque->rightblock);
216 freeblock(deque->rightblock);
Raymond Hettinger82df9252013-07-07 01:43:42 -1000217 CHECK_NOT_END(prevblock);
218 MARK_END(prevblock->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000219 deque->rightblock = prevblock;
220 deque->rightindex = BLOCKLEN - 1;
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700221 } else {
222 assert(deque->leftblock == deque->rightblock);
223 assert(deque->leftindex == deque->rightindex+1);
224 /* re-center instead of freeing a block */
225 deque->leftindex = CENTER + 1;
226 deque->rightindex = CENTER;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000227 }
228 }
229 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000230}
231
232PyDoc_STRVAR(pop_doc, "Remove and return the rightmost element.");
233
234static PyObject *
235deque_popleft(dequeobject *deque, PyObject *unused)
236{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000237 PyObject *item;
238 block *prevblock;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000239
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000240 if (Py_SIZE(deque) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000241 PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
242 return NULL;
243 }
244 assert(deque->leftblock != NULL);
245 item = deque->leftblock->data[deque->leftindex];
246 deque->leftindex++;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000247 Py_SIZE(deque)--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000248 deque->state++;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000250 if (deque->leftindex == BLOCKLEN) {
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700251 if (Py_SIZE(deque)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000252 assert(deque->leftblock != deque->rightblock);
253 prevblock = deque->leftblock->rightlink;
254 freeblock(deque->leftblock);
Raymond Hettinger82df9252013-07-07 01:43:42 -1000255 CHECK_NOT_END(prevblock);
256 MARK_END(prevblock->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000257 deque->leftblock = prevblock;
258 deque->leftindex = 0;
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700259 } else {
260 assert(deque->leftblock == deque->rightblock);
261 assert(deque->leftindex == deque->rightindex+1);
262 /* re-center instead of freeing a block */
263 deque->leftindex = CENTER + 1;
264 deque->rightindex = CENTER;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000265 }
266 }
267 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000268}
269
270PyDoc_STRVAR(popleft_doc, "Remove and return the leftmost element.");
271
Raymond Hettingerf30f5b92015-03-02 22:23:37 -0800272/* The deque's size limit is d.maxlen. The limit can be zero or positive.
273 * If there is no limit, then d.maxlen == -1.
274 *
275 * After an item is added to a deque, we check to see if the size has grown past
276 * the limit. If it has, we get the size back down to the limit by popping an
277 * item off of the opposite end. The methods that can trigger this are append(),
278 * appendleft(), extend(), and extendleft().
279 */
280
281static void
282deque_trim_right(dequeobject *deque)
283{
284 if (deque->maxlen != -1 && Py_SIZE(deque) > deque->maxlen) {
285 PyObject *rv = deque_pop(deque, NULL);
286 assert(rv != NULL);
287 assert(Py_SIZE(deque) <= deque->maxlen);
288 Py_DECREF(rv);
289 }
290}
291
292static void
293deque_trim_left(dequeobject *deque)
294{
295 if (deque->maxlen != -1 && Py_SIZE(deque) > deque->maxlen) {
296 PyObject *rv = deque_popleft(deque, NULL);
297 assert(rv != NULL);
298 assert(Py_SIZE(deque) <= deque->maxlen);
299 Py_DECREF(rv);
300 }
301}
302
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000303static PyObject *
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000304deque_append(dequeobject *deque, PyObject *item)
305{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000306 deque->state++;
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700307 if (deque->rightindex == BLOCKLEN - 1) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000308 block *b = newblock(Py_SIZE(deque));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000309 if (b == NULL)
310 return NULL;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000311 b->leftlink = deque->rightblock;
312 CHECK_END(deque->rightblock->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000313 deque->rightblock->rightlink = b;
314 deque->rightblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000315 MARK_END(b->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000316 deque->rightindex = -1;
317 }
318 Py_INCREF(item);
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000319 Py_SIZE(deque)++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000320 deque->rightindex++;
321 deque->rightblock->data[deque->rightindex] = item;
Raymond Hettingerf30f5b92015-03-02 22:23:37 -0800322 deque_trim_left(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000323 Py_RETURN_NONE;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000324}
325
326PyDoc_STRVAR(append_doc, "Add an element to the right side of the deque.");
327
328static PyObject *
329deque_appendleft(dequeobject *deque, PyObject *item)
330{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000331 deque->state++;
332 if (deque->leftindex == 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000333 block *b = newblock(Py_SIZE(deque));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000334 if (b == NULL)
335 return NULL;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000336 b->rightlink = deque->leftblock;
337 CHECK_END(deque->leftblock->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000338 deque->leftblock->leftlink = b;
339 deque->leftblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000340 MARK_END(b->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000341 deque->leftindex = BLOCKLEN;
342 }
343 Py_INCREF(item);
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000344 Py_SIZE(deque)++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000345 deque->leftindex--;
346 deque->leftblock->data[deque->leftindex] = item;
Raymond Hettingerf30f5b92015-03-02 22:23:37 -0800347 deque_trim_right(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000348 Py_RETURN_NONE;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000349}
350
351PyDoc_STRVAR(appendleft_doc, "Add an element to the left side of the deque.");
352
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000353
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000354/* Run an iterator to exhaustion. Shortcut for
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000355 the extend/extendleft methods when maxlen == 0. */
356static PyObject*
357consume_iterator(PyObject *it)
358{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000359 PyObject *item;
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000360
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000361 while ((item = PyIter_Next(it)) != NULL) {
362 Py_DECREF(item);
363 }
364 Py_DECREF(it);
365 if (PyErr_Occurred())
366 return NULL;
367 Py_RETURN_NONE;
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000368}
369
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000370static PyObject *
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000371deque_extend(dequeobject *deque, PyObject *iterable)
372{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000373 PyObject *it, *item;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 /* Handle case where id(deque) == id(iterable) */
376 if ((PyObject *)deque == iterable) {
377 PyObject *result;
378 PyObject *s = PySequence_List(iterable);
379 if (s == NULL)
380 return NULL;
381 result = deque_extend(deque, s);
382 Py_DECREF(s);
383 return result;
384 }
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000385
Raymond Hettingerd9c116c2013-07-09 00:13:21 -0700386 /* Space saving heuristic. Start filling from the left */
387 if (Py_SIZE(deque) == 0) {
388 assert(deque->leftblock == deque->rightblock);
389 assert(deque->leftindex == deque->rightindex+1);
390 deque->leftindex = 1;
391 deque->rightindex = 0;
392 }
393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000394 it = PyObject_GetIter(iterable);
395 if (it == NULL)
396 return NULL;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000397
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000398 if (deque->maxlen == 0)
399 return consume_iterator(it);
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000401 while ((item = PyIter_Next(it)) != NULL) {
402 deque->state++;
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700403 if (deque->rightindex == BLOCKLEN - 1) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000404 block *b = newblock(Py_SIZE(deque));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000405 if (b == NULL) {
406 Py_DECREF(item);
407 Py_DECREF(it);
408 return NULL;
409 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000410 b->leftlink = deque->rightblock;
411 CHECK_END(deque->rightblock->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000412 deque->rightblock->rightlink = b;
413 deque->rightblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000414 MARK_END(b->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000415 deque->rightindex = -1;
416 }
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000417 Py_SIZE(deque)++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000418 deque->rightindex++;
419 deque->rightblock->data[deque->rightindex] = item;
Raymond Hettingerf30f5b92015-03-02 22:23:37 -0800420 deque_trim_left(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 }
Raymond Hettinger2b2b7532015-09-05 17:05:52 -0700422 if (PyErr_Occurred()) {
423 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000424 return NULL;
Raymond Hettinger2b2b7532015-09-05 17:05:52 -0700425 }
426 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000427 Py_RETURN_NONE;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000428}
429
Tim Peters1065f752004-10-01 01:03:29 +0000430PyDoc_STRVAR(extend_doc,
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000431"Extend the right side of the deque with elements from the iterable");
432
433static PyObject *
434deque_extendleft(dequeobject *deque, PyObject *iterable)
435{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000436 PyObject *it, *item;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000437
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000438 /* Handle case where id(deque) == id(iterable) */
439 if ((PyObject *)deque == iterable) {
440 PyObject *result;
441 PyObject *s = PySequence_List(iterable);
442 if (s == NULL)
443 return NULL;
444 result = deque_extendleft(deque, s);
445 Py_DECREF(s);
446 return result;
447 }
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000448
Raymond Hettingerd9c116c2013-07-09 00:13:21 -0700449 /* Space saving heuristic. Start filling from the right */
450 if (Py_SIZE(deque) == 0) {
451 assert(deque->leftblock == deque->rightblock);
452 assert(deque->leftindex == deque->rightindex+1);
453 deque->leftindex = BLOCKLEN - 1;
454 deque->rightindex = BLOCKLEN - 2;
455 }
456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000457 it = PyObject_GetIter(iterable);
458 if (it == NULL)
459 return NULL;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000460
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 if (deque->maxlen == 0)
462 return consume_iterator(it);
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000463
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000464 while ((item = PyIter_Next(it)) != NULL) {
465 deque->state++;
466 if (deque->leftindex == 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000467 block *b = newblock(Py_SIZE(deque));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000468 if (b == NULL) {
469 Py_DECREF(item);
470 Py_DECREF(it);
471 return NULL;
472 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000473 b->rightlink = deque->leftblock;
474 CHECK_END(deque->leftblock->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000475 deque->leftblock->leftlink = b;
476 deque->leftblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000477 MARK_END(b->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 deque->leftindex = BLOCKLEN;
479 }
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000480 Py_SIZE(deque)++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000481 deque->leftindex--;
482 deque->leftblock->data[deque->leftindex] = item;
Raymond Hettingerf30f5b92015-03-02 22:23:37 -0800483 deque_trim_right(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 }
Raymond Hettinger2b2b7532015-09-05 17:05:52 -0700485 if (PyErr_Occurred()) {
486 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000487 return NULL;
Raymond Hettinger2b2b7532015-09-05 17:05:52 -0700488 }
489 Py_DECREF(it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 Py_RETURN_NONE;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000491}
492
Tim Peters1065f752004-10-01 01:03:29 +0000493PyDoc_STRVAR(extendleft_doc,
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000494"Extend the left side of the deque with elements from the iterable");
495
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000496static PyObject *
497deque_inplace_concat(dequeobject *deque, PyObject *other)
498{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000499 PyObject *result;
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 result = deque_extend(deque, other);
502 if (result == NULL)
503 return result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 Py_INCREF(deque);
Raymond Hettinger2b2b7532015-09-05 17:05:52 -0700505 Py_DECREF(result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 return (PyObject *)deque;
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000507}
508
Raymond Hettinger41290a62015-03-31 08:12:23 -0700509static PyObject *deque_copy(PyObject *deque);
510
511static PyObject *
512deque_concat(dequeobject *deque, PyObject *other)
513{
Benjamin Peterson1a629212015-04-04 10:52:36 -0400514 PyObject *new_deque, *result;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700515 int rv;
516
517 rv = PyObject_IsInstance(other, (PyObject *)&deque_type);
518 if (rv <= 0) {
519 if (rv == 0) {
520 PyErr_Format(PyExc_TypeError,
521 "can only concatenate deque (not \"%.200s\") to deque",
522 other->ob_type->tp_name);
523 }
524 return NULL;
525 }
526
527 new_deque = deque_copy((PyObject *)deque);
528 if (new_deque == NULL)
529 return NULL;
Benjamin Peterson1a629212015-04-04 10:52:36 -0400530 result = deque_extend((dequeobject *)new_deque, other);
531 if (result == NULL) {
532 Py_DECREF(new_deque);
533 return NULL;
534 }
535 Py_DECREF(result);
536 return new_deque;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700537}
538
539static void deque_clear(dequeobject *deque);
540
541static PyObject *
Raymond Hettinger41290a62015-03-31 08:12:23 -0700542deque_inplace_repeat(dequeobject *deque, Py_ssize_t n)
543{
544 Py_ssize_t i, size;
545 PyObject *seq;
546 PyObject *rv;
547
548 size = Py_SIZE(deque);
549 if (size == 0 || n == 1) {
550 Py_INCREF(deque);
551 return (PyObject *)deque;
552 }
553
554 if (n <= 0) {
555 deque_clear(deque);
556 Py_INCREF(deque);
557 return (PyObject *)deque;
558 }
559
Raymond Hettinger41290a62015-03-31 08:12:23 -0700560 if (size == 1) {
561 /* common case, repeating a single element */
562 PyObject *item = deque->leftblock->data[deque->leftindex];
563
564 if (deque->maxlen != -1 && n > deque->maxlen)
565 n = deque->maxlen;
566
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400567 if (n > MAX_DEQUE_LEN)
568 return PyErr_NoMemory();
569
Raymond Hettinger67c78b52015-09-12 11:00:20 -0400570 deque->state++;
Raymond Hettingerad262252015-09-14 01:03:04 -0400571 for (i = 0 ; i < n-1 ; ) {
Raymond Hettinger67c78b52015-09-12 11:00:20 -0400572 if (deque->rightindex == BLOCKLEN - 1) {
573 block *b = newblock(Py_SIZE(deque) + i);
574 if (b == NULL) {
575 Py_SIZE(deque) += i;
576 return NULL;
577 }
578 b->leftlink = deque->rightblock;
579 CHECK_END(deque->rightblock->rightlink);
580 deque->rightblock->rightlink = b;
581 deque->rightblock = b;
582 MARK_END(b->rightlink);
583 deque->rightindex = -1;
584 }
Raymond Hettingerad262252015-09-14 01:03:04 -0400585 for ( ; i < n-1 && deque->rightindex != BLOCKLEN - 1 ; i++) {
586 deque->rightindex++;
587 Py_INCREF(item);
588 deque->rightblock->data[deque->rightindex] = item;
589 }
Raymond Hettinger41290a62015-03-31 08:12:23 -0700590 }
Raymond Hettinger67c78b52015-09-12 11:00:20 -0400591 Py_SIZE(deque) += i;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700592 Py_INCREF(deque);
593 return (PyObject *)deque;
594 }
595
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400596 if ((size_t)size > MAX_DEQUE_LEN / (size_t)n) {
597 return PyErr_NoMemory();
598 }
599
Raymond Hettinger41290a62015-03-31 08:12:23 -0700600 seq = PySequence_List((PyObject *)deque);
601 if (seq == NULL)
602 return seq;
603
604 for (i = 0 ; i < n-1 ; i++) {
605 rv = deque_extend(deque, seq);
606 if (rv == NULL) {
607 Py_DECREF(seq);
608 return NULL;
609 }
610 Py_DECREF(rv);
611 }
612 Py_INCREF(deque);
613 Py_DECREF(seq);
614 return (PyObject *)deque;
615}
616
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400617static PyObject *
618deque_repeat(dequeobject *deque, Py_ssize_t n)
619{
620 dequeobject *new_deque;
Raymond Hettinger95e2cc52015-09-13 02:41:18 -0400621 PyObject *rv;
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400622
623 new_deque = (dequeobject *)deque_copy((PyObject *) deque);
624 if (new_deque == NULL)
625 return NULL;
Raymond Hettinger95e2cc52015-09-13 02:41:18 -0400626 rv = deque_inplace_repeat(new_deque, n);
627 Py_DECREF(new_deque);
628 return rv;
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400629}
630
Raymond Hettinger54023152014-04-23 00:58:48 -0700631/* The rotate() method is part of the public API and is used internally
632as a primitive for other methods.
633
634Rotation by 1 or -1 is a common case, so any optimizations for high
635volume rotations should take care not to penalize the common case.
636
637Conceptually, a rotate by one is equivalent to a pop on one side and an
638append on the other. However, a pop/append pair is unnecessarily slow
639because it requires a incref/decref pair for an object located randomly
640in memory. It is better to just move the object pointer from one block
641to the next without changing the reference count.
642
643When moving batches of pointers, it is tempting to use memcpy() but that
644proved to be slower than a simple loop for a variety of reasons.
645Memcpy() cannot know in advance that we're copying pointers instead of
646bytes, that the source and destination are pointer aligned and
647non-overlapping, that moving just one pointer is a common case, that we
648never need to move more than BLOCKLEN pointers, and that at least one
649pointer is always moved.
650
651For high volume rotations, newblock() and freeblock() are never called
652more than once. Previously emptied blocks are immediately reused as a
653destination block. If a block is left-over at the end, it is freed.
654*/
655
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000656static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000657_deque_rotate(dequeobject *deque, Py_ssize_t n)
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000658{
Raymond Hettinger3959af92013-07-13 02:34:08 -0700659 block *b = NULL;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700660 block *leftblock = deque->leftblock;
661 block *rightblock = deque->rightblock;
662 Py_ssize_t leftindex = deque->leftindex;
663 Py_ssize_t rightindex = deque->rightindex;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000664 Py_ssize_t len=Py_SIZE(deque), halflen=len>>1;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700665 int rv = -1;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000666
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800667 if (len <= 1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 return 0;
669 if (n > halflen || n < -halflen) {
670 n %= len;
671 if (n > halflen)
672 n -= len;
673 else if (n < -halflen)
674 n += len;
675 }
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500676 assert(len > 1);
Raymond Hettingera4409c12013-02-04 00:08:12 -0500677 assert(-halflen <= n && n <= halflen);
Raymond Hettinger231ee4d2013-02-02 11:24:43 -0800678
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800679 deque->state++;
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500680 while (n > 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700681 if (leftindex == 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700682 if (b == NULL) {
Raymond Hettinger3959af92013-07-13 02:34:08 -0700683 b = newblock(len);
684 if (b == NULL)
685 goto done;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700686 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000687 b->rightlink = leftblock;
688 CHECK_END(leftblock->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700689 leftblock->leftlink = b;
690 leftblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000691 MARK_END(b->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700692 leftindex = BLOCKLEN;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700693 b = NULL;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800694 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700695 assert(leftindex > 0);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700696 {
697 PyObject **src, **dest;
698 Py_ssize_t m = n;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800699
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700700 if (m > rightindex + 1)
701 m = rightindex + 1;
702 if (m > leftindex)
703 m = leftindex;
704 assert (m > 0 && m <= len);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700705 rightindex -= m;
706 leftindex -= m;
Raymond Hettinger0e259f12015-02-01 22:53:41 -0800707 src = &rightblock->data[rightindex + 1];
708 dest = &leftblock->data[leftindex];
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700709 n -= m;
Raymond Hettinger840533b2013-07-13 17:03:58 -0700710 do {
Raymond Hettinger0e259f12015-02-01 22:53:41 -0800711 *(dest++) = *(src++);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700712 } while (--m);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700713 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700714 if (rightindex == -1) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700715 assert(leftblock != rightblock);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700716 assert(b == NULL);
Raymond Hettinger3959af92013-07-13 02:34:08 -0700717 b = rightblock;
Raymond Hettingerb97cc492013-07-21 01:51:07 -0700718 CHECK_NOT_END(rightblock->leftlink);
719 rightblock = rightblock->leftlink;
720 MARK_END(rightblock->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700721 rightindex = BLOCKLEN - 1;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800722 }
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800723 }
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500724 while (n < 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700725 if (rightindex == BLOCKLEN - 1) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700726 if (b == NULL) {
Raymond Hettinger3959af92013-07-13 02:34:08 -0700727 b = newblock(len);
728 if (b == NULL)
729 goto done;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700730 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000731 b->leftlink = rightblock;
732 CHECK_END(rightblock->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700733 rightblock->rightlink = b;
734 rightblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000735 MARK_END(b->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700736 rightindex = -1;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700737 b = NULL;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800738 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700739 assert (rightindex < BLOCKLEN - 1);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700740 {
741 PyObject **src, **dest;
742 Py_ssize_t m = -n;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800743
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700744 if (m > BLOCKLEN - leftindex)
745 m = BLOCKLEN - leftindex;
746 if (m > BLOCKLEN - 1 - rightindex)
747 m = BLOCKLEN - 1 - rightindex;
748 assert (m > 0 && m <= len);
749 src = &leftblock->data[leftindex];
750 dest = &rightblock->data[rightindex + 1];
751 leftindex += m;
752 rightindex += m;
753 n += m;
Raymond Hettinger840533b2013-07-13 17:03:58 -0700754 do {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700755 *(dest++) = *(src++);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700756 } while (--m);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700757 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700758 if (leftindex == BLOCKLEN) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700759 assert(leftblock != rightblock);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700760 assert(b == NULL);
Raymond Hettinger3959af92013-07-13 02:34:08 -0700761 b = leftblock;
Raymond Hettingerb97cc492013-07-21 01:51:07 -0700762 CHECK_NOT_END(leftblock->rightlink);
763 leftblock = leftblock->rightlink;
764 MARK_END(leftblock->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700765 leftindex = 0;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800766 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000767 }
Raymond Hettinger3959af92013-07-13 02:34:08 -0700768 rv = 0;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700769done:
Raymond Hettinger3959af92013-07-13 02:34:08 -0700770 if (b != NULL)
771 freeblock(b);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700772 deque->leftblock = leftblock;
773 deque->rightblock = rightblock;
774 deque->leftindex = leftindex;
775 deque->rightindex = rightindex;
776
777 return rv;
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000778}
779
780static PyObject *
781deque_rotate(dequeobject *deque, PyObject *args)
782{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000783 Py_ssize_t n=1;
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000785 if (!PyArg_ParseTuple(args, "|n:rotate", &n))
786 return NULL;
Raymond Hettinger6921c132015-03-21 02:03:40 -0700787 if (!_deque_rotate(deque, n))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000788 Py_RETURN_NONE;
789 return NULL;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000790}
791
Tim Peters1065f752004-10-01 01:03:29 +0000792PyDoc_STRVAR(rotate_doc,
Raymond Hettingeree33b272004-02-08 04:05:26 +0000793"Rotate the deque n steps to the right (default n=1). If n is negative, rotates left.");
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000794
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000795static PyObject *
796deque_reverse(dequeobject *deque, PyObject *unused)
797{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000798 block *leftblock = deque->leftblock;
799 block *rightblock = deque->rightblock;
800 Py_ssize_t leftindex = deque->leftindex;
801 Py_ssize_t rightindex = deque->rightindex;
Raymond Hettingercfe5b6c2015-07-20 00:25:50 -0400802 Py_ssize_t n = Py_SIZE(deque) >> 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 Py_ssize_t i;
804 PyObject *tmp;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000805
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000806 for (i=0 ; i<n ; i++) {
807 /* Validate that pointers haven't met in the middle */
808 assert(leftblock != rightblock || leftindex < rightindex);
Raymond Hettinger82df9252013-07-07 01:43:42 -1000809 CHECK_NOT_END(leftblock);
810 CHECK_NOT_END(rightblock);
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000811
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 /* Swap */
813 tmp = leftblock->data[leftindex];
814 leftblock->data[leftindex] = rightblock->data[rightindex];
815 rightblock->data[rightindex] = tmp;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000816
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000817 /* Advance left block/index pair */
818 leftindex++;
819 if (leftindex == BLOCKLEN) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000820 leftblock = leftblock->rightlink;
821 leftindex = 0;
822 }
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000823
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000824 /* Step backwards with the right block/index pair */
825 rightindex--;
826 if (rightindex == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000827 rightblock = rightblock->leftlink;
828 rightindex = BLOCKLEN - 1;
829 }
830 }
831 Py_RETURN_NONE;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000832}
833
834PyDoc_STRVAR(reverse_doc,
835"D.reverse() -- reverse *IN PLACE*");
836
Raymond Hettinger44459de2010-04-03 23:20:46 +0000837static PyObject *
838deque_count(dequeobject *deque, PyObject *v)
839{
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000840 block *b = deque->leftblock;
841 Py_ssize_t index = deque->leftindex;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000842 Py_ssize_t n = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000843 Py_ssize_t i;
844 Py_ssize_t count = 0;
Raymond Hettingerf9d9c792015-03-02 22:47:46 -0800845 size_t start_state = deque->state;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000846 PyObject *item;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000847 int cmp;
Raymond Hettinger44459de2010-04-03 23:20:46 +0000848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 for (i=0 ; i<n ; i++) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000850 CHECK_NOT_END(b);
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000851 item = b->data[index];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000852 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
853 if (cmp > 0)
854 count++;
855 else if (cmp < 0)
856 return NULL;
Raymond Hettinger44459de2010-04-03 23:20:46 +0000857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 if (start_state != deque->state) {
859 PyErr_SetString(PyExc_RuntimeError,
860 "deque mutated during iteration");
861 return NULL;
862 }
Raymond Hettinger44459de2010-04-03 23:20:46 +0000863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 /* Advance left block/index pair */
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000865 index++;
866 if (index == BLOCKLEN) {
867 b = b->rightlink;
868 index = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000869 }
870 }
871 return PyLong_FromSsize_t(count);
Raymond Hettinger44459de2010-04-03 23:20:46 +0000872}
873
874PyDoc_STRVAR(count_doc,
875"D.count(value) -> integer -- return number of occurrences of value");
876
Raymond Hettinger39dadf72015-03-20 16:38:56 -0700877static int
878deque_contains(dequeobject *deque, PyObject *v)
879{
880 block *b = deque->leftblock;
881 Py_ssize_t index = deque->leftindex;
882 Py_ssize_t n = Py_SIZE(deque);
883 Py_ssize_t i;
884 size_t start_state = deque->state;
885 PyObject *item;
886 int cmp;
887
888 for (i=0 ; i<n ; i++) {
889 CHECK_NOT_END(b);
890 item = b->data[index];
891 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
892 if (cmp) {
893 return cmp;
894 }
895 if (start_state != deque->state) {
896 PyErr_SetString(PyExc_RuntimeError,
897 "deque mutated during iteration");
898 return -1;
899 }
900 index++;
901 if (index == BLOCKLEN) {
902 b = b->rightlink;
903 index = 0;
904 }
905 }
906 return 0;
907}
908
Martin v. Löwis18e16552006-02-15 17:27:45 +0000909static Py_ssize_t
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000910deque_len(dequeobject *deque)
911{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000912 return Py_SIZE(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000913}
914
Raymond Hettinger4aec61e2005-03-18 21:20:23 +0000915static PyObject *
Raymond Hettinger32ea1652015-03-21 01:37:37 -0700916deque_index(dequeobject *deque, PyObject *args)
917{
918 Py_ssize_t i, start=0, stop=Py_SIZE(deque);
919 PyObject *v, *item;
920 block *b = deque->leftblock;
921 Py_ssize_t index = deque->leftindex;
922 size_t start_state = deque->state;
923
924 if (!PyArg_ParseTuple(args, "O|O&O&:index", &v,
925 _PyEval_SliceIndex, &start,
926 _PyEval_SliceIndex, &stop))
927 return NULL;
928 if (start < 0) {
929 start += Py_SIZE(deque);
930 if (start < 0)
931 start = 0;
932 }
933 if (stop < 0) {
934 stop += Py_SIZE(deque);
935 if (stop < 0)
936 stop = 0;
937 }
Raymond Hettinger87674ec2015-08-26 08:08:38 -0700938 if (stop > Py_SIZE(deque))
939 stop = Py_SIZE(deque);
Raymond Hettinger32ea1652015-03-21 01:37:37 -0700940
941 for (i=0 ; i<stop ; i++) {
942 if (i >= start) {
943 int cmp;
944 CHECK_NOT_END(b);
945 item = b->data[index];
946 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
947 if (cmp > 0)
948 return PyLong_FromSsize_t(i);
949 else if (cmp < 0)
950 return NULL;
951 if (start_state != deque->state) {
952 PyErr_SetString(PyExc_RuntimeError,
953 "deque mutated during iteration");
954 return NULL;
955 }
956 }
957 index++;
958 if (index == BLOCKLEN) {
959 b = b->rightlink;
960 index = 0;
961 }
962 }
963 PyErr_Format(PyExc_ValueError, "%R is not in deque", v);
964 return NULL;
965}
966
967PyDoc_STRVAR(index_doc,
968"D.index(value, [start, [stop]]) -> integer -- return first index of value.\n"
969"Raises ValueError if the value is not present.");
970
Raymond Hettinger551350a2015-03-24 00:19:53 -0700971/* insert(), remove(), and delitem() are implemented in terms of
972 rotate() for simplicity and reasonable performance near the end
973 points. If for some reason these methods become popular, it is not
974 hard to re-implement this using direct data movement (similar to
975 the code used in list slice assignments) and achieve a performance
Raymond Hettingerfef9c1b2015-03-24 21:12:57 -0700976 boost (by moving each pointer only once instead of twice).
Raymond Hettinger551350a2015-03-24 00:19:53 -0700977*/
978
Raymond Hettinger32ea1652015-03-21 01:37:37 -0700979static PyObject *
980deque_insert(dequeobject *deque, PyObject *args)
981{
982 Py_ssize_t index;
983 Py_ssize_t n = Py_SIZE(deque);
984 PyObject *value;
985 PyObject *rv;
986
987 if (!PyArg_ParseTuple(args, "nO:insert", &index, &value))
988 return NULL;
989 if (index >= n)
990 return deque_append(deque, value);
991 if (index <= -n || index == 0)
992 return deque_appendleft(deque, value);
993 if (_deque_rotate(deque, -index))
994 return NULL;
995 if (index < 0)
996 rv = deque_append(deque, value);
997 else
998 rv = deque_appendleft(deque, value);
999 if (rv == NULL)
1000 return NULL;
1001 Py_DECREF(rv);
1002 if (_deque_rotate(deque, index))
1003 return NULL;
1004 Py_RETURN_NONE;
1005}
1006
1007PyDoc_STRVAR(insert_doc,
1008"D.insert(index, object) -- insert object before index");
1009
1010static PyObject *
Raymond Hettinger4aec61e2005-03-18 21:20:23 +00001011deque_remove(dequeobject *deque, PyObject *value)
1012{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001013 Py_ssize_t i, n=Py_SIZE(deque);
Raymond Hettinger4aec61e2005-03-18 21:20:23 +00001014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 for (i=0 ; i<n ; i++) {
1016 PyObject *item = deque->leftblock->data[deque->leftindex];
1017 int cmp = PyObject_RichCompareBool(item, value, Py_EQ);
Raymond Hettingerd73202c2005-03-19 00:00:51 +00001018
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001019 if (Py_SIZE(deque) != n) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 PyErr_SetString(PyExc_IndexError,
1021 "deque mutated during remove().");
1022 return NULL;
1023 }
1024 if (cmp > 0) {
1025 PyObject *tgt = deque_popleft(deque, NULL);
1026 assert (tgt != NULL);
Raymond Hettinger6921c132015-03-21 02:03:40 -07001027 if (_deque_rotate(deque, i))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 return NULL;
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001029 Py_DECREF(tgt);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001030 Py_RETURN_NONE;
1031 }
1032 else if (cmp < 0) {
1033 _deque_rotate(deque, i);
1034 return NULL;
1035 }
1036 _deque_rotate(deque, -1);
1037 }
1038 PyErr_SetString(PyExc_ValueError, "deque.remove(x): x not in deque");
1039 return NULL;
Raymond Hettinger4aec61e2005-03-18 21:20:23 +00001040}
1041
1042PyDoc_STRVAR(remove_doc,
1043"D.remove(value) -- remove first occurrence of value.");
1044
Benjamin Peterson0e5c48a2013-01-12 21:22:18 -05001045static void
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001046deque_clear(dequeobject *deque)
1047{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 PyObject *item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001049
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001050 while (Py_SIZE(deque)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001051 item = deque_pop(deque, NULL);
1052 assert (item != NULL);
1053 Py_DECREF(item);
1054 }
Raymond Hettinger87e69122015-03-02 23:32:02 -08001055 assert(deque->leftblock == deque->rightblock);
1056 assert(deque->leftindex - 1 == deque->rightindex);
1057 assert(Py_SIZE(deque) == 0);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001058}
1059
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001060static int
1061valid_index(Py_ssize_t i, Py_ssize_t limit)
1062{
Raymond Hettinger12f896c2015-07-31 12:03:20 -07001063 /* The cast to size_t lets us use just a single comparison
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001064 to check whether i is in the range: 0 <= i < limit */
1065 return (size_t) i < (size_t) limit;
1066}
1067
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001068static PyObject *
Benjamin Petersond6313712008-07-31 16:23:04 +00001069deque_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001070{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 block *b;
1072 PyObject *item;
1073 Py_ssize_t n, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001074
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001075 if (!valid_index(i, Py_SIZE(deque))) {
1076 PyErr_SetString(PyExc_IndexError, "deque index out of range");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001077 return NULL;
1078 }
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001079
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001080 if (i == 0) {
1081 i = deque->leftindex;
1082 b = deque->leftblock;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001083 } else if (i == Py_SIZE(deque) - 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 i = deque->rightindex;
1085 b = deque->rightblock;
1086 } else {
1087 i += deque->leftindex;
Raymond Hettingerc2083082015-02-28 23:29:16 -08001088 n = (Py_ssize_t)((size_t) i / BLOCKLEN);
1089 i = (Py_ssize_t)((size_t) i % BLOCKLEN);
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001090 if (index < (Py_SIZE(deque) >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 b = deque->leftblock;
1092 while (n--)
1093 b = b->rightlink;
1094 } else {
Raymond Hettinger63d1ff22015-02-28 07:41:30 -08001095 n = (Py_ssize_t)(
Raymond Hettingerc2083082015-02-28 23:29:16 -08001096 ((size_t)(deque->leftindex + Py_SIZE(deque) - 1))
Raymond Hettinger63d1ff22015-02-28 07:41:30 -08001097 / BLOCKLEN - n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098 b = deque->rightblock;
1099 while (n--)
1100 b = b->leftlink;
1101 }
1102 }
1103 item = b->data[i];
1104 Py_INCREF(item);
1105 return item;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001106}
1107
1108static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001109deque_del_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001110{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001111 PyObject *item;
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001112 int rv;
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001113
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001114 assert (i >= 0 && i < Py_SIZE(deque));
Raymond Hettinger6921c132015-03-21 02:03:40 -07001115 if (_deque_rotate(deque, -i))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001116 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001117 item = deque_popleft(deque, NULL);
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001118 rv = _deque_rotate(deque, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001119 assert (item != NULL);
1120 Py_DECREF(item);
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001121 return rv;
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001122}
1123
1124static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001125deque_ass_item(dequeobject *deque, Py_ssize_t i, PyObject *v)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001126{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001127 PyObject *old_value;
1128 block *b;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001129 Py_ssize_t n, len=Py_SIZE(deque), halflen=(len+1)>>1, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001130
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001131 if (!valid_index(i, len)) {
1132 PyErr_SetString(PyExc_IndexError, "deque index out of range");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001133 return -1;
1134 }
1135 if (v == NULL)
1136 return deque_del_item(deque, i);
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001137
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001138 i += deque->leftindex;
Raymond Hettingerc2083082015-02-28 23:29:16 -08001139 n = (Py_ssize_t)((size_t) i / BLOCKLEN);
1140 i = (Py_ssize_t)((size_t) i % BLOCKLEN);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001141 if (index <= halflen) {
1142 b = deque->leftblock;
1143 while (n--)
1144 b = b->rightlink;
1145 } else {
Raymond Hettingera473b9d2015-02-28 17:49:47 -08001146 n = (Py_ssize_t)(
Raymond Hettingerc2083082015-02-28 23:29:16 -08001147 ((size_t)(deque->leftindex + Py_SIZE(deque) - 1))
Raymond Hettingera473b9d2015-02-28 17:49:47 -08001148 / BLOCKLEN - n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001149 b = deque->rightblock;
1150 while (n--)
1151 b = b->leftlink;
1152 }
1153 Py_INCREF(v);
1154 old_value = b->data[i];
1155 b->data[i] = v;
1156 Py_DECREF(old_value);
1157 return 0;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001158}
1159
1160static PyObject *
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001161deque_clearmethod(dequeobject *deque)
1162{
Benjamin Peterson0e5c48a2013-01-12 21:22:18 -05001163 deque_clear(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001164 Py_RETURN_NONE;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001165}
1166
1167PyDoc_STRVAR(clear_doc, "Remove all elements from the deque.");
1168
1169static void
1170deque_dealloc(dequeobject *deque)
1171{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001172 PyObject_GC_UnTrack(deque);
1173 if (deque->weakreflist != NULL)
1174 PyObject_ClearWeakRefs((PyObject *) deque);
1175 if (deque->leftblock != NULL) {
1176 deque_clear(deque);
1177 assert(deque->leftblock != NULL);
1178 freeblock(deque->leftblock);
1179 }
1180 deque->leftblock = NULL;
1181 deque->rightblock = NULL;
1182 Py_TYPE(deque)->tp_free(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001183}
1184
1185static int
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001186deque_traverse(dequeobject *deque, visitproc visit, void *arg)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001187{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 block *b;
1189 PyObject *item;
1190 Py_ssize_t index;
1191 Py_ssize_t indexlo = deque->leftindex;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001192
Raymond Hettinger5bfa8672013-07-06 11:58:09 -10001193 for (b = deque->leftblock; b != deque->rightblock; b = b->rightlink) {
1194 for (index = indexlo; index < BLOCKLEN ; index++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 item = b->data[index];
1196 Py_VISIT(item);
1197 }
1198 indexlo = 0;
1199 }
Raymond Hettinger5bfa8672013-07-06 11:58:09 -10001200 for (index = indexlo; index <= deque->rightindex; index++) {
1201 item = b->data[index];
1202 Py_VISIT(item);
1203 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 return 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001205}
1206
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001207static PyObject *
1208deque_copy(PyObject *deque)
1209{
Raymond Hettingere4f34672015-09-13 19:27:01 -04001210 if (Py_TYPE(deque) == &deque_type) {
1211 dequeobject *new_deque;
1212 PyObject *rv;
1213
1214 new_deque = (dequeobject *)deque_new(&deque_type, (PyObject *)NULL, (PyObject *)NULL);
1215 if (new_deque == NULL)
1216 return NULL;
1217 new_deque->maxlen = ((dequeobject *)deque)->maxlen;
1218 rv = deque_extend(new_deque, deque);
1219 if (rv != NULL) {
1220 Py_DECREF(rv);
1221 return (PyObject *)new_deque;
1222 }
1223 Py_DECREF(new_deque);
1224 return NULL;
1225 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001226 if (((dequeobject *)deque)->maxlen == -1)
1227 return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "O", deque, NULL);
1228 else
1229 return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "Oi",
1230 deque, ((dequeobject *)deque)->maxlen, NULL);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001231}
1232
1233PyDoc_STRVAR(copy_doc, "Return a shallow copy of a deque.");
1234
1235static PyObject *
1236deque_reduce(dequeobject *deque)
1237{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001238 PyObject *dict, *result, *aslist;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001239 _Py_IDENTIFIER(__dict__);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001240
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001241 dict = _PyObject_GetAttrId((PyObject *)deque, &PyId___dict__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001242 if (dict == NULL)
1243 PyErr_Clear();
1244 aslist = PySequence_List((PyObject *)deque);
1245 if (aslist == NULL) {
1246 Py_XDECREF(dict);
1247 return NULL;
1248 }
1249 if (dict == NULL) {
1250 if (deque->maxlen == -1)
1251 result = Py_BuildValue("O(O)", Py_TYPE(deque), aslist);
1252 else
1253 result = Py_BuildValue("O(On)", Py_TYPE(deque), aslist, deque->maxlen);
1254 } else {
1255 if (deque->maxlen == -1)
1256 result = Py_BuildValue("O(OO)O", Py_TYPE(deque), aslist, Py_None, dict);
1257 else
1258 result = Py_BuildValue("O(On)O", Py_TYPE(deque), aslist, deque->maxlen, dict);
1259 }
1260 Py_XDECREF(dict);
1261 Py_DECREF(aslist);
1262 return result;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001263}
1264
1265PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
1266
1267static PyObject *
1268deque_repr(PyObject *deque)
1269{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001270 PyObject *aslist, *result;
1271 int i;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001273 i = Py_ReprEnter(deque);
1274 if (i != 0) {
1275 if (i < 0)
1276 return NULL;
1277 return PyUnicode_FromString("[...]");
1278 }
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001280 aslist = PySequence_List(deque);
1281 if (aslist == NULL) {
1282 Py_ReprLeave(deque);
1283 return NULL;
1284 }
1285 if (((dequeobject *)deque)->maxlen != -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001286 result = PyUnicode_FromFormat("deque(%R, maxlen=%zd)",
1287 aslist, ((dequeobject *)deque)->maxlen);
1288 else
1289 result = PyUnicode_FromFormat("deque(%R)", aslist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001290 Py_ReprLeave(deque);
Raymond Hettinger2b2b7532015-09-05 17:05:52 -07001291 Py_DECREF(aslist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001292 return result;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001293}
1294
Raymond Hettinger738ec902004-02-29 02:15:56 +00001295static PyObject *
1296deque_richcompare(PyObject *v, PyObject *w, int op)
1297{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001298 PyObject *it1=NULL, *it2=NULL, *x, *y;
1299 Py_ssize_t vs, ws;
1300 int b, cmp=-1;
Raymond Hettinger738ec902004-02-29 02:15:56 +00001301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001302 if (!PyObject_TypeCheck(v, &deque_type) ||
1303 !PyObject_TypeCheck(w, &deque_type)) {
Brian Curtindfc80e32011-08-10 20:28:54 -05001304 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001305 }
Raymond Hettinger738ec902004-02-29 02:15:56 +00001306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001307 /* Shortcuts */
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001308 vs = Py_SIZE((dequeobject *)v);
1309 ws = Py_SIZE((dequeobject *)w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001310 if (op == Py_EQ) {
1311 if (v == w)
1312 Py_RETURN_TRUE;
1313 if (vs != ws)
1314 Py_RETURN_FALSE;
1315 }
1316 if (op == Py_NE) {
1317 if (v == w)
1318 Py_RETURN_FALSE;
1319 if (vs != ws)
1320 Py_RETURN_TRUE;
1321 }
Raymond Hettinger738ec902004-02-29 02:15:56 +00001322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001323 /* Search for the first index where items are different */
1324 it1 = PyObject_GetIter(v);
1325 if (it1 == NULL)
1326 goto done;
1327 it2 = PyObject_GetIter(w);
1328 if (it2 == NULL)
1329 goto done;
1330 for (;;) {
1331 x = PyIter_Next(it1);
1332 if (x == NULL && PyErr_Occurred())
1333 goto done;
1334 y = PyIter_Next(it2);
1335 if (x == NULL || y == NULL)
1336 break;
1337 b = PyObject_RichCompareBool(x, y, Py_EQ);
1338 if (b == 0) {
1339 cmp = PyObject_RichCompareBool(x, y, op);
1340 Py_DECREF(x);
1341 Py_DECREF(y);
1342 goto done;
1343 }
1344 Py_DECREF(x);
1345 Py_DECREF(y);
1346 if (b == -1)
1347 goto done;
1348 }
1349 /* We reached the end of one deque or both */
1350 Py_XDECREF(x);
1351 Py_XDECREF(y);
1352 if (PyErr_Occurred())
1353 goto done;
1354 switch (op) {
1355 case Py_LT: cmp = y != NULL; break; /* if w was longer */
1356 case Py_LE: cmp = x == NULL; break; /* if v was not longer */
1357 case Py_EQ: cmp = x == y; break; /* if we reached the end of both */
1358 case Py_NE: cmp = x != y; break; /* if one deque continues */
1359 case Py_GT: cmp = x != NULL; break; /* if v was longer */
1360 case Py_GE: cmp = y == NULL; break; /* if w was not longer */
1361 }
Tim Peters1065f752004-10-01 01:03:29 +00001362
Raymond Hettinger738ec902004-02-29 02:15:56 +00001363done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001364 Py_XDECREF(it1);
1365 Py_XDECREF(it2);
1366 if (cmp == 1)
1367 Py_RETURN_TRUE;
1368 if (cmp == 0)
1369 Py_RETURN_FALSE;
1370 return NULL;
Raymond Hettinger738ec902004-02-29 02:15:56 +00001371}
1372
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001373static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001374deque_init(dequeobject *deque, PyObject *args, PyObject *kwdargs)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001375{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001376 PyObject *iterable = NULL;
1377 PyObject *maxlenobj = NULL;
1378 Py_ssize_t maxlen = -1;
1379 char *kwlist[] = {"iterable", "maxlen", 0};
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001381 if (!PyArg_ParseTupleAndKeywords(args, kwdargs, "|OO:deque", kwlist, &iterable, &maxlenobj))
1382 return -1;
1383 if (maxlenobj != NULL && maxlenobj != Py_None) {
1384 maxlen = PyLong_AsSsize_t(maxlenobj);
1385 if (maxlen == -1 && PyErr_Occurred())
1386 return -1;
1387 if (maxlen < 0) {
1388 PyErr_SetString(PyExc_ValueError, "maxlen must be non-negative");
1389 return -1;
1390 }
1391 }
1392 deque->maxlen = maxlen;
1393 deque_clear(deque);
1394 if (iterable != NULL) {
1395 PyObject *rv = deque_extend(deque, iterable);
1396 if (rv == NULL)
1397 return -1;
1398 Py_DECREF(rv);
1399 }
1400 return 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001401}
1402
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001403static PyObject *
Jesus Cea16e2fca2012-08-03 14:49:42 +02001404deque_sizeof(dequeobject *deque, void *unused)
1405{
1406 Py_ssize_t res;
1407 Py_ssize_t blocks;
1408
1409 res = sizeof(dequeobject);
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001410 blocks = (deque->leftindex + Py_SIZE(deque) + BLOCKLEN - 1) / BLOCKLEN;
1411 assert(deque->leftindex + Py_SIZE(deque) - 1 ==
Jesus Cea16e2fca2012-08-03 14:49:42 +02001412 (blocks - 1) * BLOCKLEN + deque->rightindex);
1413 res += blocks * sizeof(block);
1414 return PyLong_FromSsize_t(res);
1415}
1416
1417PyDoc_STRVAR(sizeof_doc,
1418"D.__sizeof__() -- size of D in memory, in bytes");
1419
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001420static int
1421deque_bool(dequeobject *deque)
1422{
1423 return Py_SIZE(deque) != 0;
1424}
1425
Jesus Cea16e2fca2012-08-03 14:49:42 +02001426static PyObject *
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001427deque_get_maxlen(dequeobject *deque)
1428{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001429 if (deque->maxlen == -1)
1430 Py_RETURN_NONE;
1431 return PyLong_FromSsize_t(deque->maxlen);
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001432}
1433
Raymond Hettinger41290a62015-03-31 08:12:23 -07001434
1435/* deque object ********************************************************/
1436
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001437static PyGetSetDef deque_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001438 {"maxlen", (getter)deque_get_maxlen, (setter)NULL,
1439 "maximum size of a deque or None if unbounded"},
1440 {0}
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001441};
1442
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001443static PySequenceMethods deque_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001444 (lenfunc)deque_len, /* sq_length */
Raymond Hettinger41290a62015-03-31 08:12:23 -07001445 (binaryfunc)deque_concat, /* sq_concat */
1446 (ssizeargfunc)deque_repeat, /* sq_repeat */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001447 (ssizeargfunc)deque_item, /* sq_item */
1448 0, /* sq_slice */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001449 (ssizeobjargproc)deque_ass_item, /* sq_ass_item */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001450 0, /* sq_ass_slice */
Raymond Hettinger39dadf72015-03-20 16:38:56 -07001451 (objobjproc)deque_contains, /* sq_contains */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001452 (binaryfunc)deque_inplace_concat, /* sq_inplace_concat */
Raymond Hettinger41290a62015-03-31 08:12:23 -07001453 (ssizeargfunc)deque_inplace_repeat, /* sq_inplace_repeat */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001454};
1455
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001456static PyNumberMethods deque_as_number = {
1457 0, /* nb_add */
1458 0, /* nb_subtract */
1459 0, /* nb_multiply */
1460 0, /* nb_remainder */
1461 0, /* nb_divmod */
1462 0, /* nb_power */
1463 0, /* nb_negative */
1464 0, /* nb_positive */
1465 0, /* nb_absolute */
1466 (inquiry)deque_bool, /* nb_bool */
1467 0, /* nb_invert */
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001468 };
1469
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001470static PyObject *deque_iter(dequeobject *deque);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001471static PyObject *deque_reviter(dequeobject *deque);
Tim Peters1065f752004-10-01 01:03:29 +00001472PyDoc_STRVAR(reversed_doc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001473 "D.__reversed__() -- return a reverse iterator over the deque");
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001474
1475static PyMethodDef deque_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001476 {"append", (PyCFunction)deque_append,
1477 METH_O, append_doc},
1478 {"appendleft", (PyCFunction)deque_appendleft,
1479 METH_O, appendleft_doc},
1480 {"clear", (PyCFunction)deque_clearmethod,
1481 METH_NOARGS, clear_doc},
1482 {"__copy__", (PyCFunction)deque_copy,
1483 METH_NOARGS, copy_doc},
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001484 {"copy", (PyCFunction)deque_copy,
1485 METH_NOARGS, copy_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001486 {"count", (PyCFunction)deque_count,
Raymond Hettinger0f6f9472015-03-21 01:42:10 -07001487 METH_O, count_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001488 {"extend", (PyCFunction)deque_extend,
1489 METH_O, extend_doc},
1490 {"extendleft", (PyCFunction)deque_extendleft,
1491 METH_O, extendleft_doc},
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001492 {"index", (PyCFunction)deque_index,
1493 METH_VARARGS, index_doc},
1494 {"insert", (PyCFunction)deque_insert,
1495 METH_VARARGS, insert_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001496 {"pop", (PyCFunction)deque_pop,
1497 METH_NOARGS, pop_doc},
1498 {"popleft", (PyCFunction)deque_popleft,
1499 METH_NOARGS, popleft_doc},
Raymond Hettinger0f6f9472015-03-21 01:42:10 -07001500 {"__reduce__", (PyCFunction)deque_reduce,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001501 METH_NOARGS, reduce_doc},
1502 {"remove", (PyCFunction)deque_remove,
1503 METH_O, remove_doc},
1504 {"__reversed__", (PyCFunction)deque_reviter,
1505 METH_NOARGS, reversed_doc},
1506 {"reverse", (PyCFunction)deque_reverse,
1507 METH_NOARGS, reverse_doc},
1508 {"rotate", (PyCFunction)deque_rotate,
Jesus Cea16e2fca2012-08-03 14:49:42 +02001509 METH_VARARGS, rotate_doc},
1510 {"__sizeof__", (PyCFunction)deque_sizeof,
1511 METH_NOARGS, sizeof_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001512 {NULL, NULL} /* sentinel */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001513};
1514
1515PyDoc_STRVAR(deque_doc,
Andrew Svetlov6a5c7c32012-10-31 11:50:40 +02001516"deque([iterable[, maxlen]]) --> deque object\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001517\n\
Raymond Hettinger41290a62015-03-31 08:12:23 -07001518A list-like sequence optimized for data accesses near its endpoints.");
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001519
Neal Norwitz87f10132004-02-29 15:40:53 +00001520static PyTypeObject deque_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001521 PyVarObject_HEAD_INIT(NULL, 0)
1522 "collections.deque", /* tp_name */
1523 sizeof(dequeobject), /* tp_basicsize */
1524 0, /* tp_itemsize */
1525 /* methods */
1526 (destructor)deque_dealloc, /* tp_dealloc */
1527 0, /* tp_print */
1528 0, /* tp_getattr */
1529 0, /* tp_setattr */
1530 0, /* tp_reserved */
1531 deque_repr, /* tp_repr */
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001532 &deque_as_number, /* tp_as_number */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001533 &deque_as_sequence, /* tp_as_sequence */
1534 0, /* tp_as_mapping */
Georg Brandlf038b322010-10-18 07:35:09 +00001535 PyObject_HashNotImplemented, /* tp_hash */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001536 0, /* tp_call */
1537 0, /* tp_str */
1538 PyObject_GenericGetAttr, /* tp_getattro */
1539 0, /* tp_setattro */
1540 0, /* tp_as_buffer */
1541 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
Georg Brandlf038b322010-10-18 07:35:09 +00001542 /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001543 deque_doc, /* tp_doc */
1544 (traverseproc)deque_traverse, /* tp_traverse */
1545 (inquiry)deque_clear, /* tp_clear */
1546 (richcmpfunc)deque_richcompare, /* tp_richcompare */
Georg Brandlf038b322010-10-18 07:35:09 +00001547 offsetof(dequeobject, weakreflist), /* tp_weaklistoffset*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001548 (getiterfunc)deque_iter, /* tp_iter */
1549 0, /* tp_iternext */
1550 deque_methods, /* tp_methods */
1551 0, /* tp_members */
Georg Brandlf038b322010-10-18 07:35:09 +00001552 deque_getset, /* tp_getset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001553 0, /* tp_base */
1554 0, /* tp_dict */
1555 0, /* tp_descr_get */
1556 0, /* tp_descr_set */
1557 0, /* tp_dictoffset */
1558 (initproc)deque_init, /* tp_init */
1559 PyType_GenericAlloc, /* tp_alloc */
1560 deque_new, /* tp_new */
1561 PyObject_GC_Del, /* tp_free */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001562};
1563
1564/*********************** Deque Iterator **************************/
1565
1566typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001567 PyObject_HEAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001568 block *b;
Raymond Hettinger87e69122015-03-02 23:32:02 -08001569 Py_ssize_t index;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001570 dequeobject *deque;
Raymond Hettingerf9d9c792015-03-02 22:47:46 -08001571 size_t state; /* state when the iterator is created */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001572 Py_ssize_t counter; /* number of items remaining for iteration */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001573} dequeiterobject;
1574
Martin v. Löwis59683e82008-06-13 07:50:45 +00001575static PyTypeObject dequeiter_type;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001576
1577static PyObject *
1578deque_iter(dequeobject *deque)
1579{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001580 dequeiterobject *it;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001581
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001582 it = PyObject_GC_New(dequeiterobject, &dequeiter_type);
1583 if (it == NULL)
1584 return NULL;
1585 it->b = deque->leftblock;
1586 it->index = deque->leftindex;
1587 Py_INCREF(deque);
1588 it->deque = deque;
1589 it->state = deque->state;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001590 it->counter = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001591 PyObject_GC_Track(it);
1592 return (PyObject *)it;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001593}
1594
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001595static int
1596dequeiter_traverse(dequeiterobject *dio, visitproc visit, void *arg)
1597{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001598 Py_VISIT(dio->deque);
1599 return 0;
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001600}
1601
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001602static void
1603dequeiter_dealloc(dequeiterobject *dio)
1604{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001605 Py_XDECREF(dio->deque);
1606 PyObject_GC_Del(dio);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001607}
1608
1609static PyObject *
1610dequeiter_next(dequeiterobject *it)
1611{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001612 PyObject *item;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001614 if (it->deque->state != it->state) {
1615 it->counter = 0;
1616 PyErr_SetString(PyExc_RuntimeError,
1617 "deque mutated during iteration");
1618 return NULL;
1619 }
1620 if (it->counter == 0)
1621 return NULL;
1622 assert (!(it->b == it->deque->rightblock &&
1623 it->index > it->deque->rightindex));
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001624
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001625 item = it->b->data[it->index];
1626 it->index++;
1627 it->counter--;
1628 if (it->index == BLOCKLEN && it->counter > 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -10001629 CHECK_NOT_END(it->b->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001630 it->b = it->b->rightlink;
1631 it->index = 0;
1632 }
1633 Py_INCREF(item);
1634 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001635}
1636
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001637static PyObject *
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001638dequeiter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1639{
1640 Py_ssize_t i, index=0;
1641 PyObject *deque;
1642 dequeiterobject *it;
1643 if (!PyArg_ParseTuple(args, "O!|n", &deque_type, &deque, &index))
1644 return NULL;
1645 assert(type == &dequeiter_type);
1646
1647 it = (dequeiterobject*)deque_iter((dequeobject *)deque);
1648 if (!it)
1649 return NULL;
1650 /* consume items from the queue */
1651 for(i=0; i<index; i++) {
1652 PyObject *item = dequeiter_next(it);
1653 if (item) {
1654 Py_DECREF(item);
1655 } else {
1656 if (it->counter) {
1657 Py_DECREF(it);
1658 return NULL;
1659 } else
1660 break;
1661 }
1662 }
1663 return (PyObject*)it;
1664}
1665
1666static PyObject *
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001667dequeiter_len(dequeiterobject *it)
1668{
Antoine Pitrou554f3342010-08-17 18:30:06 +00001669 return PyLong_FromSsize_t(it->counter);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001670}
1671
Armin Rigof5b3e362006-02-11 21:32:43 +00001672PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001673
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001674static PyObject *
1675dequeiter_reduce(dequeiterobject *it)
1676{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001677 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 +00001678}
1679
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001680static PyMethodDef dequeiter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001681 {"__length_hint__", (PyCFunction)dequeiter_len, METH_NOARGS, length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001682 {"__reduce__", (PyCFunction)dequeiter_reduce, METH_NOARGS, reduce_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001683 {NULL, NULL} /* sentinel */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001684};
1685
Martin v. Löwis59683e82008-06-13 07:50:45 +00001686static PyTypeObject dequeiter_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001687 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger87e69122015-03-02 23:32:02 -08001688 "_collections._deque_iterator", /* tp_name */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001689 sizeof(dequeiterobject), /* tp_basicsize */
1690 0, /* tp_itemsize */
1691 /* methods */
1692 (destructor)dequeiter_dealloc, /* tp_dealloc */
1693 0, /* tp_print */
1694 0, /* tp_getattr */
1695 0, /* tp_setattr */
1696 0, /* tp_reserved */
1697 0, /* tp_repr */
1698 0, /* tp_as_number */
1699 0, /* tp_as_sequence */
1700 0, /* tp_as_mapping */
1701 0, /* tp_hash */
1702 0, /* tp_call */
1703 0, /* tp_str */
1704 PyObject_GenericGetAttr, /* tp_getattro */
1705 0, /* tp_setattro */
1706 0, /* tp_as_buffer */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001707 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001708 0, /* tp_doc */
1709 (traverseproc)dequeiter_traverse, /* tp_traverse */
1710 0, /* tp_clear */
1711 0, /* tp_richcompare */
1712 0, /* tp_weaklistoffset */
1713 PyObject_SelfIter, /* tp_iter */
1714 (iternextfunc)dequeiter_next, /* tp_iternext */
1715 dequeiter_methods, /* tp_methods */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001716 0, /* tp_members */
1717 0, /* tp_getset */
1718 0, /* tp_base */
1719 0, /* tp_dict */
1720 0, /* tp_descr_get */
1721 0, /* tp_descr_set */
1722 0, /* tp_dictoffset */
1723 0, /* tp_init */
1724 0, /* tp_alloc */
1725 dequeiter_new, /* tp_new */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001726 0,
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001727};
1728
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001729/*********************** Deque Reverse Iterator **************************/
1730
Martin v. Löwis59683e82008-06-13 07:50:45 +00001731static PyTypeObject dequereviter_type;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001732
1733static PyObject *
1734deque_reviter(dequeobject *deque)
1735{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 dequeiterobject *it;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001738 it = PyObject_GC_New(dequeiterobject, &dequereviter_type);
1739 if (it == NULL)
1740 return NULL;
1741 it->b = deque->rightblock;
1742 it->index = deque->rightindex;
1743 Py_INCREF(deque);
1744 it->deque = deque;
1745 it->state = deque->state;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001746 it->counter = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001747 PyObject_GC_Track(it);
1748 return (PyObject *)it;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001749}
1750
1751static PyObject *
1752dequereviter_next(dequeiterobject *it)
1753{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001754 PyObject *item;
1755 if (it->counter == 0)
1756 return NULL;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001758 if (it->deque->state != it->state) {
1759 it->counter = 0;
1760 PyErr_SetString(PyExc_RuntimeError,
1761 "deque mutated during iteration");
1762 return NULL;
1763 }
1764 assert (!(it->b == it->deque->leftblock &&
1765 it->index < it->deque->leftindex));
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001766
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001767 item = it->b->data[it->index];
1768 it->index--;
1769 it->counter--;
1770 if (it->index == -1 && it->counter > 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -10001771 CHECK_NOT_END(it->b->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001772 it->b = it->b->leftlink;
1773 it->index = BLOCKLEN - 1;
1774 }
1775 Py_INCREF(item);
1776 return item;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001777}
1778
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001779static PyObject *
1780dequereviter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1781{
1782 Py_ssize_t i, index=0;
1783 PyObject *deque;
1784 dequeiterobject *it;
1785 if (!PyArg_ParseTuple(args, "O!|n", &deque_type, &deque, &index))
1786 return NULL;
1787 assert(type == &dequereviter_type);
1788
1789 it = (dequeiterobject*)deque_reviter((dequeobject *)deque);
1790 if (!it)
1791 return NULL;
1792 /* consume items from the queue */
1793 for(i=0; i<index; i++) {
1794 PyObject *item = dequereviter_next(it);
1795 if (item) {
1796 Py_DECREF(item);
1797 } else {
1798 if (it->counter) {
1799 Py_DECREF(it);
1800 return NULL;
1801 } else
1802 break;
1803 }
1804 }
1805 return (PyObject*)it;
1806}
1807
Martin v. Löwis59683e82008-06-13 07:50:45 +00001808static PyTypeObject dequereviter_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001809 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger87e69122015-03-02 23:32:02 -08001810 "_collections._deque_reverse_iterator", /* tp_name */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001811 sizeof(dequeiterobject), /* tp_basicsize */
1812 0, /* tp_itemsize */
1813 /* methods */
1814 (destructor)dequeiter_dealloc, /* tp_dealloc */
1815 0, /* tp_print */
1816 0, /* tp_getattr */
1817 0, /* tp_setattr */
1818 0, /* tp_reserved */
1819 0, /* tp_repr */
1820 0, /* tp_as_number */
1821 0, /* tp_as_sequence */
1822 0, /* tp_as_mapping */
1823 0, /* tp_hash */
1824 0, /* tp_call */
1825 0, /* tp_str */
1826 PyObject_GenericGetAttr, /* tp_getattro */
1827 0, /* tp_setattro */
1828 0, /* tp_as_buffer */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001829 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001830 0, /* tp_doc */
1831 (traverseproc)dequeiter_traverse, /* tp_traverse */
1832 0, /* tp_clear */
1833 0, /* tp_richcompare */
1834 0, /* tp_weaklistoffset */
1835 PyObject_SelfIter, /* tp_iter */
1836 (iternextfunc)dequereviter_next, /* tp_iternext */
1837 dequeiter_methods, /* tp_methods */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001838 0, /* tp_members */
1839 0, /* tp_getset */
1840 0, /* tp_base */
1841 0, /* tp_dict */
1842 0, /* tp_descr_get */
1843 0, /* tp_descr_set */
1844 0, /* tp_dictoffset */
1845 0, /* tp_init */
1846 0, /* tp_alloc */
1847 dequereviter_new, /* tp_new */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001848 0,
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001849};
1850
Guido van Rossum1968ad32006-02-25 22:38:04 +00001851/* defaultdict type *********************************************************/
1852
1853typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001854 PyDictObject dict;
1855 PyObject *default_factory;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001856} defdictobject;
1857
1858static PyTypeObject defdict_type; /* Forward */
1859
1860PyDoc_STRVAR(defdict_missing_doc,
1861"__missing__(key) # Called by __getitem__ for missing key; pseudo-code:\n\
Guido van Rossumd8faa362007-04-27 19:54:29 +00001862 if self.default_factory is None: raise KeyError((key,))\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00001863 self[key] = value = self.default_factory()\n\
1864 return value\n\
1865");
1866
1867static PyObject *
1868defdict_missing(defdictobject *dd, PyObject *key)
1869{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001870 PyObject *factory = dd->default_factory;
1871 PyObject *value;
1872 if (factory == NULL || factory == Py_None) {
1873 /* XXX Call dict.__missing__(key) */
1874 PyObject *tup;
1875 tup = PyTuple_Pack(1, key);
1876 if (!tup) return NULL;
1877 PyErr_SetObject(PyExc_KeyError, tup);
1878 Py_DECREF(tup);
1879 return NULL;
1880 }
1881 value = PyEval_CallObject(factory, NULL);
1882 if (value == NULL)
1883 return value;
1884 if (PyObject_SetItem((PyObject *)dd, key, value) < 0) {
1885 Py_DECREF(value);
1886 return NULL;
1887 }
1888 return value;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001889}
1890
1891PyDoc_STRVAR(defdict_copy_doc, "D.copy() -> a shallow copy of D.");
1892
1893static PyObject *
1894defdict_copy(defdictobject *dd)
1895{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001896 /* This calls the object's class. That only works for subclasses
1897 whose class constructor has the same signature. Subclasses that
1898 define a different constructor signature must override copy().
1899 */
Raymond Hettinger54628fa2009-08-04 19:16:39 +00001900
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001901 if (dd->default_factory == NULL)
1902 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd), Py_None, dd, NULL);
1903 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd),
1904 dd->default_factory, dd, NULL);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001905}
1906
1907static PyObject *
1908defdict_reduce(defdictobject *dd)
1909{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001910 /* __reduce__ must return a 5-tuple as follows:
Guido van Rossum1968ad32006-02-25 22:38:04 +00001911
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001912 - factory function
1913 - tuple of args for the factory function
1914 - additional state (here None)
1915 - sequence iterator (here None)
1916 - dictionary iterator (yielding successive (key, value) pairs
Guido van Rossum1968ad32006-02-25 22:38:04 +00001917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001918 This API is used by pickle.py and copy.py.
Guido van Rossum1968ad32006-02-25 22:38:04 +00001919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001920 For this to be useful with pickle.py, the default_factory
1921 must be picklable; e.g., None, a built-in, or a global
1922 function in a module or package.
Guido van Rossum1968ad32006-02-25 22:38:04 +00001923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001924 Both shallow and deep copying are supported, but for deep
1925 copying, the default_factory must be deep-copyable; e.g. None,
1926 or a built-in (functions are not copyable at this time).
Guido van Rossum1968ad32006-02-25 22:38:04 +00001927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001928 This only works for subclasses as long as their constructor
1929 signature is compatible; the first argument must be the
1930 optional default_factory, defaulting to None.
1931 */
1932 PyObject *args;
1933 PyObject *items;
1934 PyObject *iter;
1935 PyObject *result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001936 _Py_IDENTIFIER(items);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001938 if (dd->default_factory == NULL || dd->default_factory == Py_None)
1939 args = PyTuple_New(0);
1940 else
1941 args = PyTuple_Pack(1, dd->default_factory);
1942 if (args == NULL)
1943 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001944 items = _PyObject_CallMethodId((PyObject *)dd, &PyId_items, "()");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001945 if (items == NULL) {
1946 Py_DECREF(args);
1947 return NULL;
1948 }
1949 iter = PyObject_GetIter(items);
1950 if (iter == NULL) {
1951 Py_DECREF(items);
1952 Py_DECREF(args);
1953 return NULL;
1954 }
1955 result = PyTuple_Pack(5, Py_TYPE(dd), args,
1956 Py_None, Py_None, iter);
1957 Py_DECREF(iter);
1958 Py_DECREF(items);
1959 Py_DECREF(args);
1960 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001961}
1962
1963static PyMethodDef defdict_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001964 {"__missing__", (PyCFunction)defdict_missing, METH_O,
1965 defdict_missing_doc},
1966 {"copy", (PyCFunction)defdict_copy, METH_NOARGS,
1967 defdict_copy_doc},
1968 {"__copy__", (PyCFunction)defdict_copy, METH_NOARGS,
1969 defdict_copy_doc},
1970 {"__reduce__", (PyCFunction)defdict_reduce, METH_NOARGS,
1971 reduce_doc},
1972 {NULL}
Guido van Rossum1968ad32006-02-25 22:38:04 +00001973};
1974
1975static PyMemberDef defdict_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001976 {"default_factory", T_OBJECT,
1977 offsetof(defdictobject, default_factory), 0,
1978 PyDoc_STR("Factory for default value called by __missing__().")},
1979 {NULL}
Guido van Rossum1968ad32006-02-25 22:38:04 +00001980};
1981
1982static void
1983defdict_dealloc(defdictobject *dd)
1984{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001985 Py_CLEAR(dd->default_factory);
1986 PyDict_Type.tp_dealloc((PyObject *)dd);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001987}
1988
Guido van Rossum1968ad32006-02-25 22:38:04 +00001989static PyObject *
1990defdict_repr(defdictobject *dd)
1991{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001992 PyObject *baserepr;
1993 PyObject *defrepr;
1994 PyObject *result;
1995 baserepr = PyDict_Type.tp_repr((PyObject *)dd);
1996 if (baserepr == NULL)
1997 return NULL;
1998 if (dd->default_factory == NULL)
1999 defrepr = PyUnicode_FromString("None");
2000 else
2001 {
2002 int status = Py_ReprEnter(dd->default_factory);
2003 if (status != 0) {
Antoine Pitrouf5f1fe02012-02-15 02:42:46 +01002004 if (status < 0) {
2005 Py_DECREF(baserepr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002006 return NULL;
Antoine Pitrouf5f1fe02012-02-15 02:42:46 +01002007 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002008 defrepr = PyUnicode_FromString("...");
2009 }
2010 else
2011 defrepr = PyObject_Repr(dd->default_factory);
2012 Py_ReprLeave(dd->default_factory);
2013 }
2014 if (defrepr == NULL) {
2015 Py_DECREF(baserepr);
2016 return NULL;
2017 }
2018 result = PyUnicode_FromFormat("defaultdict(%U, %U)",
2019 defrepr, baserepr);
2020 Py_DECREF(defrepr);
2021 Py_DECREF(baserepr);
2022 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00002023}
2024
2025static int
2026defdict_traverse(PyObject *self, visitproc visit, void *arg)
2027{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002028 Py_VISIT(((defdictobject *)self)->default_factory);
2029 return PyDict_Type.tp_traverse(self, visit, arg);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002030}
2031
2032static int
2033defdict_tp_clear(defdictobject *dd)
2034{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002035 Py_CLEAR(dd->default_factory);
2036 return PyDict_Type.tp_clear((PyObject *)dd);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002037}
2038
2039static int
2040defdict_init(PyObject *self, PyObject *args, PyObject *kwds)
2041{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002042 defdictobject *dd = (defdictobject *)self;
2043 PyObject *olddefault = dd->default_factory;
2044 PyObject *newdefault = NULL;
2045 PyObject *newargs;
2046 int result;
2047 if (args == NULL || !PyTuple_Check(args))
2048 newargs = PyTuple_New(0);
2049 else {
2050 Py_ssize_t n = PyTuple_GET_SIZE(args);
2051 if (n > 0) {
2052 newdefault = PyTuple_GET_ITEM(args, 0);
2053 if (!PyCallable_Check(newdefault) && newdefault != Py_None) {
2054 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger239aba72015-07-20 03:09:22 -04002055 "first argument must be callable or None");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002056 return -1;
2057 }
2058 }
2059 newargs = PySequence_GetSlice(args, 1, n);
2060 }
2061 if (newargs == NULL)
2062 return -1;
2063 Py_XINCREF(newdefault);
2064 dd->default_factory = newdefault;
2065 result = PyDict_Type.tp_init(self, newargs, kwds);
2066 Py_DECREF(newargs);
2067 Py_XDECREF(olddefault);
2068 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00002069}
2070
2071PyDoc_STRVAR(defdict_doc,
Benjamin Peterson9cb33b72014-01-13 23:56:05 -05002072"defaultdict(default_factory[, ...]) --> dict with default factory\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00002073\n\
2074The default factory is called without arguments to produce\n\
2075a new value when a key is not present, in __getitem__ only.\n\
2076A defaultdict compares equal to a dict with the same items.\n\
Benjamin Peterson9cb33b72014-01-13 23:56:05 -05002077All remaining arguments are treated the same as if they were\n\
2078passed to the dict constructor, including keyword arguments.\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00002079");
2080
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002081/* See comment in xxsubtype.c */
2082#define DEFERRED_ADDRESS(ADDR) 0
2083
Guido van Rossum1968ad32006-02-25 22:38:04 +00002084static PyTypeObject defdict_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002085 PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0)
2086 "collections.defaultdict", /* tp_name */
2087 sizeof(defdictobject), /* tp_basicsize */
2088 0, /* tp_itemsize */
2089 /* methods */
2090 (destructor)defdict_dealloc, /* tp_dealloc */
2091 0, /* tp_print */
2092 0, /* tp_getattr */
2093 0, /* tp_setattr */
2094 0, /* tp_reserved */
2095 (reprfunc)defdict_repr, /* tp_repr */
2096 0, /* tp_as_number */
2097 0, /* tp_as_sequence */
2098 0, /* tp_as_mapping */
2099 0, /* tp_hash */
2100 0, /* tp_call */
2101 0, /* tp_str */
2102 PyObject_GenericGetAttr, /* tp_getattro */
2103 0, /* tp_setattro */
2104 0, /* tp_as_buffer */
2105 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
2106 /* tp_flags */
2107 defdict_doc, /* tp_doc */
2108 defdict_traverse, /* tp_traverse */
2109 (inquiry)defdict_tp_clear, /* tp_clear */
2110 0, /* tp_richcompare */
2111 0, /* tp_weaklistoffset*/
2112 0, /* tp_iter */
2113 0, /* tp_iternext */
2114 defdict_methods, /* tp_methods */
2115 defdict_members, /* tp_members */
2116 0, /* tp_getset */
2117 DEFERRED_ADDRESS(&PyDict_Type), /* tp_base */
2118 0, /* tp_dict */
2119 0, /* tp_descr_get */
2120 0, /* tp_descr_set */
2121 0, /* tp_dictoffset */
2122 defdict_init, /* tp_init */
2123 PyType_GenericAlloc, /* tp_alloc */
2124 0, /* tp_new */
2125 PyObject_GC_Del, /* tp_free */
Guido van Rossum1968ad32006-02-25 22:38:04 +00002126};
2127
Raymond Hettinger96f34102010-12-15 16:30:37 +00002128/* helper function for Counter *********************************************/
2129
2130PyDoc_STRVAR(_count_elements_doc,
2131"_count_elements(mapping, iterable) -> None\n\
2132\n\
2133Count elements in the iterable, updating the mappping");
2134
2135static PyObject *
2136_count_elements(PyObject *self, PyObject *args)
2137{
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002138 _Py_IDENTIFIER(get);
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002139 _Py_IDENTIFIER(__setitem__);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002140 PyObject *it, *iterable, *mapping, *oldval;
2141 PyObject *newval = NULL;
2142 PyObject *key = NULL;
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002143 PyObject *zero = NULL;
Raymond Hettinger96f34102010-12-15 16:30:37 +00002144 PyObject *one = NULL;
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002145 PyObject *bound_get = NULL;
2146 PyObject *mapping_get;
2147 PyObject *dict_get;
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002148 PyObject *mapping_setitem;
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002149 PyObject *dict_setitem;
Raymond Hettinger96f34102010-12-15 16:30:37 +00002150
2151 if (!PyArg_UnpackTuple(args, "_count_elements", 2, 2, &mapping, &iterable))
2152 return NULL;
2153
Raymond Hettinger96f34102010-12-15 16:30:37 +00002154 it = PyObject_GetIter(iterable);
2155 if (it == NULL)
2156 return NULL;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002157
Raymond Hettinger96f34102010-12-15 16:30:37 +00002158 one = PyLong_FromLong(1);
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002159 if (one == NULL)
2160 goto done;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002161
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002162 /* Only take the fast path when get() and __setitem__()
2163 * have not been overridden.
2164 */
2165 mapping_get = _PyType_LookupId(Py_TYPE(mapping), &PyId_get);
2166 dict_get = _PyType_LookupId(&PyDict_Type, &PyId_get);
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002167 mapping_setitem = _PyType_LookupId(Py_TYPE(mapping), &PyId___setitem__);
2168 dict_setitem = _PyType_LookupId(&PyDict_Type, &PyId___setitem__);
2169
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002170 if (mapping_get != NULL && mapping_get == dict_get &&
2171 mapping_setitem != NULL && mapping_setitem == dict_setitem) {
Raymond Hettinger426e0522011-01-03 02:12:02 +00002172 while (1) {
Raymond Hettinger507d9972014-05-18 21:32:40 +01002173 /* Fast path advantages:
2174 1. Eliminate double hashing
2175 (by re-using the same hash for both the get and set)
2176 2. Avoid argument overhead of PyObject_CallFunctionObjArgs
2177 (argument tuple creation and parsing)
2178 3. Avoid indirection through a bound method object
2179 (creates another argument tuple)
2180 4. Avoid initial increment from zero
2181 (reuse an existing one-object instead)
2182 */
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002183 Py_hash_t hash;
2184
Raymond Hettinger426e0522011-01-03 02:12:02 +00002185 key = PyIter_Next(it);
Victor Stinnera154b5c2011-04-20 23:23:52 +02002186 if (key == NULL)
2187 break;
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002188
2189 if (!PyUnicode_CheckExact(key) ||
2190 (hash = ((PyASCIIObject *) key)->hash) == -1)
2191 {
2192 hash = PyObject_Hash(key);
Raymond Hettingerda2850f2015-02-27 12:42:54 -08002193 if (hash == -1)
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002194 goto done;
2195 }
2196
2197 oldval = _PyDict_GetItem_KnownHash(mapping, key, hash);
Raymond Hettinger426e0522011-01-03 02:12:02 +00002198 if (oldval == NULL) {
Raymond Hettinger28c995d2015-08-14 02:07:41 -07002199 if (_PyDict_SetItem_KnownHash(mapping, key, one, hash) < 0)
Raymond Hettinger507d9972014-05-18 21:32:40 +01002200 goto done;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002201 } else {
2202 newval = PyNumber_Add(oldval, one);
2203 if (newval == NULL)
Raymond Hettinger507d9972014-05-18 21:32:40 +01002204 goto done;
Raymond Hettinger28c995d2015-08-14 02:07:41 -07002205 if (_PyDict_SetItem_KnownHash(mapping, key, newval, hash) < 0)
Raymond Hettinger507d9972014-05-18 21:32:40 +01002206 goto done;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002207 Py_CLEAR(newval);
2208 }
2209 Py_DECREF(key);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002210 }
Raymond Hettinger426e0522011-01-03 02:12:02 +00002211 } else {
Victor Stinnere7f516c2013-11-06 23:52:55 +01002212 bound_get = _PyObject_GetAttrId(mapping, &PyId_get);
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002213 if (bound_get == NULL)
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002214 goto done;
2215
2216 zero = PyLong_FromLong(0);
2217 if (zero == NULL)
2218 goto done;
2219
Raymond Hettinger426e0522011-01-03 02:12:02 +00002220 while (1) {
2221 key = PyIter_Next(it);
Victor Stinnera154b5c2011-04-20 23:23:52 +02002222 if (key == NULL)
2223 break;
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002224 oldval = PyObject_CallFunctionObjArgs(bound_get, key, zero, NULL);
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002225 if (oldval == NULL)
2226 break;
2227 newval = PyNumber_Add(oldval, one);
2228 Py_DECREF(oldval);
2229 if (newval == NULL)
2230 break;
Raymond Hettinger28c995d2015-08-14 02:07:41 -07002231 if (PyObject_SetItem(mapping, key, newval) < 0)
Raymond Hettinger96f34102010-12-15 16:30:37 +00002232 break;
2233 Py_CLEAR(newval);
Raymond Hettinger426e0522011-01-03 02:12:02 +00002234 Py_DECREF(key);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002235 }
Raymond Hettinger96f34102010-12-15 16:30:37 +00002236 }
Raymond Hettinger426e0522011-01-03 02:12:02 +00002237
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002238done:
Raymond Hettinger96f34102010-12-15 16:30:37 +00002239 Py_DECREF(it);
2240 Py_XDECREF(key);
2241 Py_XDECREF(newval);
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002242 Py_XDECREF(bound_get);
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002243 Py_XDECREF(zero);
2244 Py_XDECREF(one);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002245 if (PyErr_Occurred())
2246 return NULL;
2247 Py_RETURN_NONE;
2248}
2249
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002250/* module level code ********************************************************/
2251
2252PyDoc_STRVAR(module_doc,
Guido van Rossum1968ad32006-02-25 22:38:04 +00002253"High performance data structures.\n\
2254- deque: ordered collection accessible from endpoints only\n\
2255- defaultdict: dict subclass with a default value factory\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002256");
2257
Raymond Hettinger96f34102010-12-15 16:30:37 +00002258static struct PyMethodDef module_functions[] = {
2259 {"_count_elements", _count_elements, METH_VARARGS, _count_elements_doc},
2260 {NULL, NULL} /* sentinel */
2261};
Martin v. Löwis1a214512008-06-11 05:26:20 +00002262
2263static struct PyModuleDef _collectionsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002264 PyModuleDef_HEAD_INIT,
2265 "_collections",
2266 module_doc,
2267 -1,
Raymond Hettinger96f34102010-12-15 16:30:37 +00002268 module_functions,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002269 NULL,
2270 NULL,
2271 NULL,
2272 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002273};
2274
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002275PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002276PyInit__collections(void)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002277{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002278 PyObject *m;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002280 m = PyModule_Create(&_collectionsmodule);
2281 if (m == NULL)
2282 return NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002284 if (PyType_Ready(&deque_type) < 0)
2285 return NULL;
2286 Py_INCREF(&deque_type);
2287 PyModule_AddObject(m, "deque", (PyObject *)&deque_type);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002289 defdict_type.tp_base = &PyDict_Type;
2290 if (PyType_Ready(&defdict_type) < 0)
2291 return NULL;
2292 Py_INCREF(&defdict_type);
2293 PyModule_AddObject(m, "defaultdict", (PyObject *)&defdict_type);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002294
Eric Snow47db7172015-05-29 22:21:39 -06002295 Py_INCREF(&PyODict_Type);
2296 PyModule_AddObject(m, "OrderedDict", (PyObject *)&PyODict_Type);
2297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002298 if (PyType_Ready(&dequeiter_type) < 0)
2299 return NULL;
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002300 Py_INCREF(&dequeiter_type);
2301 PyModule_AddObject(m, "_deque_iterator", (PyObject *)&dequeiter_type);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002303 if (PyType_Ready(&dequereviter_type) < 0)
2304 return NULL;
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002305 Py_INCREF(&dequereviter_type);
2306 PyModule_AddObject(m, "_deque_reverse_iterator", (PyObject *)&dequereviter_type);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00002307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002308 return m;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002309}