blob: cc325e1aaac4b6b9b79e46c415f47a59b818e849 [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
Pablo Galindo3f5fc702018-12-30 09:24:03 +000010/*[clinic input]
11class _tuplegetter "_tuplegetterobject *" "&tuplegetter_type"
12[clinic start generated code]*/
13/*[clinic end generated code: output=da39a3ee5e6b4b0d input=ee5ed5baabe35068]*/
14
15static PyTypeObject tuplegetter_type;
16#include "clinic/_collectionsmodule.c.h"
17
Raymond Hettinger756b3f32004-01-29 06:37:52 +000018/* collections module implementation of a deque() datatype
19 Written and maintained by Raymond D. Hettinger <python@rcn.com>
Raymond Hettinger756b3f32004-01-29 06:37:52 +000020*/
21
Raymond Hettinger77e8bf12004-10-01 15:25:53 +000022/* The block length may be set to any number over 1. Larger numbers
Raymond Hettinger20b0f872013-06-23 15:44:33 -070023 * reduce the number of calls to the memory allocator, give faster
Raymond Hettinger30c90742015-03-02 22:31:35 -080024 * indexing and rotation, and reduce the link to data overhead ratio.
Raymond Hettingerdaf57f22015-02-26 23:21:29 -080025 * Making the block length a power of two speeds-up the modulo
Raymond Hettinger30c90742015-03-02 22:31:35 -080026 * and division calculations in deque_item() and deque_ass_item().
Raymond Hettinger77e8bf12004-10-01 15:25:53 +000027 */
28
Raymond Hettingerdaf57f22015-02-26 23:21:29 -080029#define BLOCKLEN 64
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000030#define CENTER ((BLOCKLEN - 1) / 2)
Raymond Hettinger756b3f32004-01-29 06:37:52 +000031
Raymond Hettinger551350a2015-03-24 00:19:53 -070032/* Data for deque objects is stored in a doubly-linked list of fixed
33 * length blocks. This assures that appends or pops never move any
34 * other data elements besides the one being appended or popped.
35 *
36 * Another advantage is that it completely avoids use of realloc(),
37 * resulting in more predictable performance.
38 *
39 * Textbook implementations of doubly-linked lists store one datum
40 * per link, but that gives them a 200% memory overhead (a prev and
41 * next link for each datum) and it costs one malloc() call per data
42 * element. By using fixed-length blocks, the link to data ratio is
43 * significantly improved and there are proportionally fewer calls
44 * to malloc() and free(). The data blocks of consecutive pointers
45 * also improve cache locality.
46 *
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000047 * The list of blocks is never empty, so d.leftblock and d.rightblock
Raymond Hettinger82df9252013-07-07 01:43:42 -100048 * are never equal to NULL. The list is not circular.
49 *
50 * A deque d's first element is at d.leftblock[leftindex]
51 * and its last element is at d.rightblock[rightindex].
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000052 *
Raymond Hettinger551350a2015-03-24 00:19:53 -070053 * Unlike Python slice indices, these indices are inclusive on both
54 * ends. This makes the algorithms for left and right operations
55 * more symmetrical and it simplifies the design.
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000056 *
Raymond Hettinger551350a2015-03-24 00:19:53 -070057 * The indices, d.leftindex and d.rightindex are always in the range:
58 * 0 <= index < BLOCKLEN
59 *
60 * And their exact relationship is:
61 * (d.leftindex + d.len - 1) % BLOCKLEN == d.rightindex
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000062 *
Raymond Hettinger8dbbae22015-03-24 21:01:50 -070063 * Whenever d.leftblock == d.rightblock, then:
Raymond Hettinger551350a2015-03-24 00:19:53 -070064 * d.leftindex + d.len - 1 == d.rightindex
Thomas Wouters0e3f5912006-08-11 14:57:12 +000065 *
Raymond Hettinger551350a2015-03-24 00:19:53 -070066 * However, when d.leftblock != d.rightblock, the d.leftindex and
67 * d.rightindex become indices into distinct blocks and either may
68 * be larger than the other.
69 *
70 * Empty deques have:
71 * d.len == 0
72 * d.leftblock == d.rightblock
73 * d.leftindex == CENTER + 1
74 * d.rightindex == CENTER
75 *
76 * Checking for d.len == 0 is the intended way to see whether d is empty.
Tim Petersd8768d32004-10-01 01:32:53 +000077 */
78
Raymond Hettinger756b3f32004-01-29 06:37:52 +000079typedef struct BLOCK {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000080 struct BLOCK *leftlink;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000081 PyObject *data[BLOCKLEN];
Raymond Hettinger20b0f872013-06-23 15:44:33 -070082 struct BLOCK *rightlink;
Raymond Hettinger756b3f32004-01-29 06:37:52 +000083} block;
84
Raymond Hettinger30c90742015-03-02 22:31:35 -080085typedef struct {
86 PyObject_VAR_HEAD
87 block *leftblock;
88 block *rightblock;
Raymond Hettinger551350a2015-03-24 00:19:53 -070089 Py_ssize_t leftindex; /* 0 <= leftindex < BLOCKLEN */
90 Py_ssize_t rightindex; /* 0 <= rightindex < BLOCKLEN */
Raymond Hettingerf9d9c792015-03-02 22:47:46 -080091 size_t state; /* incremented whenever the indices move */
Raymond Hettingerd84ec222016-01-24 09:12:06 -080092 Py_ssize_t maxlen; /* maxlen is -1 for unbounded deques */
Raymond Hettinger0f6f9472015-03-21 01:42:10 -070093 PyObject *weakreflist;
Raymond Hettinger30c90742015-03-02 22:31:35 -080094} dequeobject;
95
96static PyTypeObject deque_type;
97
Raymond Hettinger82df9252013-07-07 01:43:42 -100098/* For debug builds, add error checking to track the endpoints
99 * in the chain of links. The goal is to make sure that link
100 * assignments only take place at endpoints so that links already
101 * in use do not get overwritten.
102 *
103 * CHECK_END should happen before each assignment to a block's link field.
104 * MARK_END should happen whenever a link field becomes a new endpoint.
105 * This happens when new blocks are added or whenever an existing
106 * block is freed leaving another existing block as the new endpoint.
107 */
108
Raymond Hettinger3223dd52013-07-26 23:14:22 -0700109#ifndef NDEBUG
Raymond Hettinger82df9252013-07-07 01:43:42 -1000110#define MARK_END(link) link = NULL;
111#define CHECK_END(link) assert(link == NULL);
112#define CHECK_NOT_END(link) assert(link != NULL);
113#else
114#define MARK_END(link)
115#define CHECK_END(link)
116#define CHECK_NOT_END(link)
117#endif
118
119/* A simple freelisting scheme is used to minimize calls to the memory
Raymond Hettinger551350a2015-03-24 00:19:53 -0700120 allocator. It accommodates common use cases where new blocks are being
Raymond Hettinger82df9252013-07-07 01:43:42 -1000121 added at about the same rate as old blocks are being freed.
122 */
123
Raymond Hettingerf2b02ce2015-09-26 17:47:02 -0700124#define MAXFREEBLOCKS 16
Benjamin Petersond6313712008-07-31 16:23:04 +0000125static Py_ssize_t numfreeblocks = 0;
Guido van Rossum58da9312007-11-10 23:39:45 +0000126static block *freeblocks[MAXFREEBLOCKS];
127
Tim Peters6f853562004-10-01 01:04:50 +0000128static block *
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700129newblock(void) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000130 block *b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000131 if (numfreeblocks) {
Raymond Hettinger59cf23a2013-02-07 00:57:19 -0500132 numfreeblocks--;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000133 return freeblocks[numfreeblocks];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000134 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000135 b = PyMem_Malloc(sizeof(block));
136 if (b != NULL) {
137 return b;
138 }
139 PyErr_NoMemory();
140 return NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000141}
142
Martin v. Löwis59683e82008-06-13 07:50:45 +0000143static void
Guido van Rossum58da9312007-11-10 23:39:45 +0000144freeblock(block *b)
145{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000146 if (numfreeblocks < MAXFREEBLOCKS) {
147 freeblocks[numfreeblocks] = b;
148 numfreeblocks++;
149 } else {
150 PyMem_Free(b);
151 }
Guido van Rossum58da9312007-11-10 23:39:45 +0000152}
153
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000154static PyObject *
155deque_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
156{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000157 dequeobject *deque;
158 block *b;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000159
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000160 /* create dequeobject structure */
161 deque = (dequeobject *)type->tp_alloc(type, 0);
162 if (deque == NULL)
163 return NULL;
Tim Peters1065f752004-10-01 01:03:29 +0000164
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700165 b = newblock();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000166 if (b == NULL) {
167 Py_DECREF(deque);
168 return NULL;
169 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000170 MARK_END(b->leftlink);
171 MARK_END(b->rightlink);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000173 assert(BLOCKLEN >= 2);
Raymond Hettinger87e69122015-03-02 23:32:02 -0800174 Py_SIZE(deque) = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175 deque->leftblock = b;
176 deque->rightblock = b;
177 deque->leftindex = CENTER + 1;
178 deque->rightindex = CENTER;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000179 deque->state = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000180 deque->maxlen = -1;
Raymond Hettinger87e69122015-03-02 23:32:02 -0800181 deque->weakreflist = NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000182
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000183 return (PyObject *)deque;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000184}
185
186static PyObject *
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000187deque_pop(dequeobject *deque, PyObject *unused)
188{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000189 PyObject *item;
190 block *prevblock;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000191
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000192 if (Py_SIZE(deque) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000193 PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
194 return NULL;
195 }
196 item = deque->rightblock->data[deque->rightindex];
197 deque->rightindex--;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000198 Py_SIZE(deque)--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000199 deque->state++;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000200
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -0700201 if (deque->rightindex < 0) {
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700202 if (Py_SIZE(deque)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000203 prevblock = deque->rightblock->leftlink;
204 assert(deque->leftblock != deque->rightblock);
205 freeblock(deque->rightblock);
Raymond Hettinger82df9252013-07-07 01:43:42 -1000206 CHECK_NOT_END(prevblock);
207 MARK_END(prevblock->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000208 deque->rightblock = prevblock;
209 deque->rightindex = BLOCKLEN - 1;
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700210 } else {
211 assert(deque->leftblock == deque->rightblock);
212 assert(deque->leftindex == deque->rightindex+1);
213 /* re-center instead of freeing a block */
214 deque->leftindex = CENTER + 1;
215 deque->rightindex = CENTER;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000216 }
217 }
218 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000219}
220
221PyDoc_STRVAR(pop_doc, "Remove and return the rightmost element.");
222
223static PyObject *
224deque_popleft(dequeobject *deque, PyObject *unused)
225{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000226 PyObject *item;
227 block *prevblock;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000228
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000229 if (Py_SIZE(deque) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000230 PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
231 return NULL;
232 }
233 assert(deque->leftblock != NULL);
234 item = deque->leftblock->data[deque->leftindex];
235 deque->leftindex++;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000236 Py_SIZE(deque)--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000237 deque->state++;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000239 if (deque->leftindex == BLOCKLEN) {
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700240 if (Py_SIZE(deque)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000241 assert(deque->leftblock != deque->rightblock);
242 prevblock = deque->leftblock->rightlink;
243 freeblock(deque->leftblock);
Raymond Hettinger82df9252013-07-07 01:43:42 -1000244 CHECK_NOT_END(prevblock);
245 MARK_END(prevblock->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000246 deque->leftblock = prevblock;
247 deque->leftindex = 0;
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700248 } else {
249 assert(deque->leftblock == deque->rightblock);
250 assert(deque->leftindex == deque->rightindex+1);
251 /* re-center instead of freeing a block */
252 deque->leftindex = CENTER + 1;
253 deque->rightindex = CENTER;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000254 }
255 }
256 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000257}
258
259PyDoc_STRVAR(popleft_doc, "Remove and return the leftmost element.");
260
Raymond Hettingerf30f5b92015-03-02 22:23:37 -0800261/* The deque's size limit is d.maxlen. The limit can be zero or positive.
262 * If there is no limit, then d.maxlen == -1.
263 *
Raymond Hettingera4b13d02015-10-15 08:05:31 -0700264 * After an item is added to a deque, we check to see if the size has
265 * grown past the limit. If it has, we get the size back down to the limit
266 * by popping an item off of the opposite end. The methods that can
267 * trigger this are append(), appendleft(), extend(), and extendleft().
Raymond Hettingerd96db092015-10-11 22:34:48 -0700268 *
269 * The macro to check whether a deque needs to be trimmed uses a single
270 * unsigned test that returns true whenever 0 <= maxlen < Py_SIZE(deque).
Raymond Hettingerf30f5b92015-03-02 22:23:37 -0800271 */
272
Raymond Hettingerd96db092015-10-11 22:34:48 -0700273#define NEEDS_TRIM(deque, maxlen) ((size_t)(maxlen) < (size_t)(Py_SIZE(deque)))
Raymond Hettingerf30f5b92015-03-02 22:23:37 -0800274
Raymond Hettinger66953f02018-07-10 04:17:40 -0700275static inline int
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800276deque_append_internal(dequeobject *deque, PyObject *item, Py_ssize_t maxlen)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000277{
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700278 if (deque->rightindex == BLOCKLEN - 1) {
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700279 block *b = newblock();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 if (b == NULL)
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800281 return -1;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000282 b->leftlink = deque->rightblock;
283 CHECK_END(deque->rightblock->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000284 deque->rightblock->rightlink = b;
285 deque->rightblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000286 MARK_END(b->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000287 deque->rightindex = -1;
288 }
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000289 Py_SIZE(deque)++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000290 deque->rightindex++;
291 deque->rightblock->data[deque->rightindex] = item;
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800292 if (NEEDS_TRIM(deque, maxlen)) {
Raymond Hettinger1286d142015-10-14 23:16:57 -0700293 PyObject *olditem = deque_popleft(deque, NULL);
294 Py_DECREF(olditem);
Raymond Hettinger0f43bb12015-10-20 00:03:33 -0700295 } else {
296 deque->state++;
Raymond Hettingerd96db092015-10-11 22:34:48 -0700297 }
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800298 return 0;
299}
300
301static PyObject *
302deque_append(dequeobject *deque, PyObject *item)
303{
304 Py_INCREF(item);
305 if (deque_append_internal(deque, item, deque->maxlen) < 0)
306 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000307 Py_RETURN_NONE;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000308}
309
310PyDoc_STRVAR(append_doc, "Add an element to the right side of the deque.");
311
Raymond Hettinger66953f02018-07-10 04:17:40 -0700312static inline int
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800313deque_appendleft_internal(dequeobject *deque, PyObject *item, Py_ssize_t maxlen)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000314{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000315 if (deque->leftindex == 0) {
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700316 block *b = newblock();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000317 if (b == NULL)
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800318 return -1;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000319 b->rightlink = deque->leftblock;
320 CHECK_END(deque->leftblock->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000321 deque->leftblock->leftlink = b;
322 deque->leftblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000323 MARK_END(b->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000324 deque->leftindex = BLOCKLEN;
325 }
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000326 Py_SIZE(deque)++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000327 deque->leftindex--;
328 deque->leftblock->data[deque->leftindex] = item;
Raymond Hettingerd96db092015-10-11 22:34:48 -0700329 if (NEEDS_TRIM(deque, deque->maxlen)) {
Raymond Hettinger1286d142015-10-14 23:16:57 -0700330 PyObject *olditem = deque_pop(deque, NULL);
331 Py_DECREF(olditem);
Raymond Hettinger0f43bb12015-10-20 00:03:33 -0700332 } else {
333 deque->state++;
Raymond Hettingerd96db092015-10-11 22:34:48 -0700334 }
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800335 return 0;
336}
337
338static PyObject *
339deque_appendleft(dequeobject *deque, PyObject *item)
340{
341 Py_INCREF(item);
342 if (deque_appendleft_internal(deque, item, deque->maxlen) < 0)
343 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000344 Py_RETURN_NONE;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000345}
346
347PyDoc_STRVAR(appendleft_doc, "Add an element to the left side of the deque.");
348
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700349static PyObject*
350finalize_iterator(PyObject *it)
351{
352 if (PyErr_Occurred()) {
353 if (PyErr_ExceptionMatches(PyExc_StopIteration))
354 PyErr_Clear();
355 else {
356 Py_DECREF(it);
357 return NULL;
358 }
359 }
360 Py_DECREF(it);
361 Py_RETURN_NONE;
362}
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000364/* Run an iterator to exhaustion. Shortcut for
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000365 the extend/extendleft methods when maxlen == 0. */
366static PyObject*
367consume_iterator(PyObject *it)
368{
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700369 PyObject *(*iternext)(PyObject *);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000370 PyObject *item;
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000371
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700372 iternext = *Py_TYPE(it)->tp_iternext;
373 while ((item = iternext(it)) != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000374 Py_DECREF(item);
375 }
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700376 return finalize_iterator(it);
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000377}
378
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000379static PyObject *
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000380deque_extend(dequeobject *deque, PyObject *iterable)
381{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000382 PyObject *it, *item;
Raymond Hettinger7a845522015-09-26 01:30:51 -0700383 PyObject *(*iternext)(PyObject *);
Raymond Hettinger6b1e1132015-10-11 09:43:50 -0700384 Py_ssize_t maxlen = deque->maxlen;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000386 /* Handle case where id(deque) == id(iterable) */
387 if ((PyObject *)deque == iterable) {
388 PyObject *result;
389 PyObject *s = PySequence_List(iterable);
390 if (s == NULL)
391 return NULL;
392 result = deque_extend(deque, s);
393 Py_DECREF(s);
394 return result;
395 }
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000396
Raymond Hettingerd79d5b12016-03-04 09:55:07 -0800397 it = PyObject_GetIter(iterable);
398 if (it == NULL)
399 return NULL;
400
401 if (maxlen == 0)
402 return consume_iterator(it);
403
Raymond Hettingerd9c116c2013-07-09 00:13:21 -0700404 /* Space saving heuristic. Start filling from the left */
405 if (Py_SIZE(deque) == 0) {
406 assert(deque->leftblock == deque->rightblock);
407 assert(deque->leftindex == deque->rightindex+1);
408 deque->leftindex = 1;
409 deque->rightindex = 0;
410 }
411
Raymond Hettinger7a845522015-09-26 01:30:51 -0700412 iternext = *Py_TYPE(it)->tp_iternext;
413 while ((item = iternext(it)) != NULL) {
Raymond Hettinger66953f02018-07-10 04:17:40 -0700414 if (deque_append_internal(deque, item, maxlen) == -1) {
415 Py_DECREF(item);
416 Py_DECREF(it);
417 return NULL;
Raymond Hettinger6b1e1132015-10-11 09:43:50 -0700418 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000419 }
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700420 return finalize_iterator(it);
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000421}
422
Tim Peters1065f752004-10-01 01:03:29 +0000423PyDoc_STRVAR(extend_doc,
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000424"Extend the right side of the deque with elements from the iterable");
425
426static PyObject *
427deque_extendleft(dequeobject *deque, PyObject *iterable)
428{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000429 PyObject *it, *item;
Raymond Hettinger7a845522015-09-26 01:30:51 -0700430 PyObject *(*iternext)(PyObject *);
Raymond Hettinger6b1e1132015-10-11 09:43:50 -0700431 Py_ssize_t maxlen = deque->maxlen;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000432
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000433 /* Handle case where id(deque) == id(iterable) */
434 if ((PyObject *)deque == iterable) {
435 PyObject *result;
436 PyObject *s = PySequence_List(iterable);
437 if (s == NULL)
438 return NULL;
439 result = deque_extendleft(deque, s);
440 Py_DECREF(s);
441 return result;
442 }
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000443
Raymond Hettingerd79d5b12016-03-04 09:55:07 -0800444 it = PyObject_GetIter(iterable);
445 if (it == NULL)
446 return NULL;
447
448 if (maxlen == 0)
449 return consume_iterator(it);
450
Raymond Hettingerd9c116c2013-07-09 00:13:21 -0700451 /* Space saving heuristic. Start filling from the right */
452 if (Py_SIZE(deque) == 0) {
453 assert(deque->leftblock == deque->rightblock);
454 assert(deque->leftindex == deque->rightindex+1);
455 deque->leftindex = BLOCKLEN - 1;
456 deque->rightindex = BLOCKLEN - 2;
457 }
458
Raymond Hettinger7a845522015-09-26 01:30:51 -0700459 iternext = *Py_TYPE(it)->tp_iternext;
460 while ((item = iternext(it)) != NULL) {
Raymond Hettinger66953f02018-07-10 04:17:40 -0700461 if (deque_appendleft_internal(deque, item, maxlen) == -1) {
462 Py_DECREF(item);
463 Py_DECREF(it);
464 return NULL;
Raymond Hettinger6b1e1132015-10-11 09:43:50 -0700465 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000466 }
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700467 return finalize_iterator(it);
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000468}
469
Tim Peters1065f752004-10-01 01:03:29 +0000470PyDoc_STRVAR(extendleft_doc,
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000471"Extend the left side of the deque with elements from the iterable");
472
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000473static PyObject *
474deque_inplace_concat(dequeobject *deque, PyObject *other)
475{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 PyObject *result;
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 result = deque_extend(deque, other);
479 if (result == NULL)
480 return result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000481 Py_INCREF(deque);
Raymond Hettinger2b2b7532015-09-05 17:05:52 -0700482 Py_DECREF(result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 return (PyObject *)deque;
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000484}
485
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700486static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530487deque_copy(PyObject *deque, PyObject *Py_UNUSED(ignored))
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700488{
Oren Milman24bd50b2018-09-11 21:46:55 +0300489 PyObject *result;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700490 dequeobject *old_deque = (dequeobject *)deque;
491 if (Py_TYPE(deque) == &deque_type) {
492 dequeobject *new_deque;
493 PyObject *rv;
494
495 new_deque = (dequeobject *)deque_new(&deque_type, (PyObject *)NULL, (PyObject *)NULL);
496 if (new_deque == NULL)
497 return NULL;
498 new_deque->maxlen = old_deque->maxlen;
499 /* Fast path for the deque_repeat() common case where len(deque) == 1 */
Raymond Hettinger0443ac22015-10-05 22:52:37 -0400500 if (Py_SIZE(deque) == 1) {
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700501 PyObject *item = old_deque->leftblock->data[old_deque->leftindex];
502 rv = deque_append(new_deque, item);
503 } else {
504 rv = deque_extend(new_deque, deque);
505 }
506 if (rv != NULL) {
507 Py_DECREF(rv);
508 return (PyObject *)new_deque;
509 }
510 Py_DECREF(new_deque);
511 return NULL;
512 }
513 if (old_deque->maxlen < 0)
Oren Milman24bd50b2018-09-11 21:46:55 +0300514 result = PyObject_CallFunctionObjArgs((PyObject *)(Py_TYPE(deque)),
515 deque, NULL);
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700516 else
Oren Milman24bd50b2018-09-11 21:46:55 +0300517 result = PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "Oi",
518 deque, old_deque->maxlen, NULL);
519 if (result != NULL && !PyObject_TypeCheck(result, &deque_type)) {
520 PyErr_Format(PyExc_TypeError,
521 "%.200s() must return a deque, not %.200s",
522 Py_TYPE(deque)->tp_name, Py_TYPE(result)->tp_name);
523 Py_DECREF(result);
524 return NULL;
525 }
526 return result;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700527}
528
529PyDoc_STRVAR(copy_doc, "Return a shallow copy of a deque.");
Raymond Hettinger41290a62015-03-31 08:12:23 -0700530
531static PyObject *
532deque_concat(dequeobject *deque, PyObject *other)
533{
Benjamin Peterson1a629212015-04-04 10:52:36 -0400534 PyObject *new_deque, *result;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700535 int rv;
536
537 rv = PyObject_IsInstance(other, (PyObject *)&deque_type);
538 if (rv <= 0) {
539 if (rv == 0) {
540 PyErr_Format(PyExc_TypeError,
541 "can only concatenate deque (not \"%.200s\") to deque",
542 other->ob_type->tp_name);
543 }
544 return NULL;
545 }
546
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530547 new_deque = deque_copy((PyObject *)deque, NULL);
Raymond Hettinger41290a62015-03-31 08:12:23 -0700548 if (new_deque == NULL)
549 return NULL;
Benjamin Peterson1a629212015-04-04 10:52:36 -0400550 result = deque_extend((dequeobject *)new_deque, other);
551 if (result == NULL) {
552 Py_DECREF(new_deque);
553 return NULL;
554 }
555 Py_DECREF(result);
556 return new_deque;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700557}
558
Serhiy Storchakaa5c42282018-05-31 07:34:34 +0300559static int
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700560deque_clear(dequeobject *deque)
561{
562 block *b;
563 block *prevblock;
564 block *leftblock;
565 Py_ssize_t leftindex;
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800566 Py_ssize_t n, m;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700567 PyObject *item;
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800568 PyObject **itemptr, **limit;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700569
Raymond Hettinger38031142015-09-29 22:45:05 -0700570 if (Py_SIZE(deque) == 0)
Serhiy Storchakaa5c42282018-05-31 07:34:34 +0300571 return 0;
Raymond Hettinger38031142015-09-29 22:45:05 -0700572
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700573 /* During the process of clearing a deque, decrefs can cause the
574 deque to mutate. To avoid fatal confusion, we have to make the
575 deque empty before clearing the blocks and never refer to
576 anything via deque->ref while clearing. (This is the same
577 technique used for clearing lists, sets, and dicts.)
578
579 Making the deque empty requires allocating a new empty block. In
580 the unlikely event that memory is full, we fall back to an
581 alternate method that doesn't require a new block. Repeating
582 pops in a while-loop is slower, possibly re-entrant (and a clever
583 adversary could cause it to never terminate).
584 */
585
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700586 b = newblock();
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700587 if (b == NULL) {
588 PyErr_Clear();
589 goto alternate_method;
590 }
591
592 /* Remember the old size, leftblock, and leftindex */
Raymond Hettinger6f86a332016-03-02 00:30:58 -0800593 n = Py_SIZE(deque);
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700594 leftblock = deque->leftblock;
595 leftindex = deque->leftindex;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700596
597 /* Set the deque to be empty using the newly allocated block */
598 MARK_END(b->leftlink);
599 MARK_END(b->rightlink);
600 Py_SIZE(deque) = 0;
601 deque->leftblock = b;
602 deque->rightblock = b;
603 deque->leftindex = CENTER + 1;
604 deque->rightindex = CENTER;
605 deque->state++;
606
607 /* Now the old size, leftblock, and leftindex are disconnected from
608 the empty deque and we can use them to decref the pointers.
609 */
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800610 m = (BLOCKLEN - leftindex > n) ? n : BLOCKLEN - leftindex;
Raymond Hettinger589106b2016-03-02 00:06:21 -0800611 itemptr = &leftblock->data[leftindex];
Raymond Hettinger6f86a332016-03-02 00:30:58 -0800612 limit = itemptr + m;
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800613 n -= m;
614 while (1) {
615 if (itemptr == limit) {
616 if (n == 0)
617 break;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700618 CHECK_NOT_END(leftblock->rightlink);
619 prevblock = leftblock;
620 leftblock = leftblock->rightlink;
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800621 m = (n > BLOCKLEN) ? BLOCKLEN : n;
Raymond Hettinger589106b2016-03-02 00:06:21 -0800622 itemptr = leftblock->data;
Raymond Hettinger6f86a332016-03-02 00:30:58 -0800623 limit = itemptr + m;
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800624 n -= m;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700625 freeblock(prevblock);
626 }
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800627 item = *(itemptr++);
628 Py_DECREF(item);
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700629 }
630 CHECK_END(leftblock->rightlink);
631 freeblock(leftblock);
Serhiy Storchakaa5c42282018-05-31 07:34:34 +0300632 return 0;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700633
634 alternate_method:
635 while (Py_SIZE(deque)) {
636 item = deque_pop(deque, NULL);
637 assert (item != NULL);
638 Py_DECREF(item);
639 }
Serhiy Storchakaa5c42282018-05-31 07:34:34 +0300640 return 0;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700641}
642
643static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530644deque_clearmethod(dequeobject *deque, PyObject *Py_UNUSED(ignored))
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700645{
646 deque_clear(deque);
647 Py_RETURN_NONE;
648}
649
650PyDoc_STRVAR(clear_doc, "Remove all elements from the deque.");
Raymond Hettinger41290a62015-03-31 08:12:23 -0700651
652static PyObject *
Raymond Hettinger41290a62015-03-31 08:12:23 -0700653deque_inplace_repeat(dequeobject *deque, Py_ssize_t n)
654{
Raymond Hettingerc22eee62015-09-26 02:14:50 -0700655 Py_ssize_t i, m, size;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700656 PyObject *seq;
657 PyObject *rv;
658
659 size = Py_SIZE(deque);
660 if (size == 0 || n == 1) {
661 Py_INCREF(deque);
662 return (PyObject *)deque;
663 }
664
665 if (n <= 0) {
666 deque_clear(deque);
667 Py_INCREF(deque);
668 return (PyObject *)deque;
669 }
670
Raymond Hettinger41290a62015-03-31 08:12:23 -0700671 if (size == 1) {
672 /* common case, repeating a single element */
673 PyObject *item = deque->leftblock->data[deque->leftindex];
674
Raymond Hettingera7f630092015-10-10 23:56:02 -0400675 if (deque->maxlen >= 0 && n > deque->maxlen)
Raymond Hettinger41290a62015-03-31 08:12:23 -0700676 n = deque->maxlen;
677
Raymond Hettinger67c78b52015-09-12 11:00:20 -0400678 deque->state++;
Raymond Hettingerad262252015-09-14 01:03:04 -0400679 for (i = 0 ; i < n-1 ; ) {
Raymond Hettinger67c78b52015-09-12 11:00:20 -0400680 if (deque->rightindex == BLOCKLEN - 1) {
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700681 block *b = newblock();
Raymond Hettinger67c78b52015-09-12 11:00:20 -0400682 if (b == NULL) {
683 Py_SIZE(deque) += i;
684 return NULL;
685 }
686 b->leftlink = deque->rightblock;
687 CHECK_END(deque->rightblock->rightlink);
688 deque->rightblock->rightlink = b;
689 deque->rightblock = b;
690 MARK_END(b->rightlink);
691 deque->rightindex = -1;
692 }
Raymond Hettingerc22eee62015-09-26 02:14:50 -0700693 m = n - 1 - i;
694 if (m > BLOCKLEN - 1 - deque->rightindex)
695 m = BLOCKLEN - 1 - deque->rightindex;
696 i += m;
697 while (m--) {
Raymond Hettingerad262252015-09-14 01:03:04 -0400698 deque->rightindex++;
699 Py_INCREF(item);
700 deque->rightblock->data[deque->rightindex] = item;
701 }
Raymond Hettinger41290a62015-03-31 08:12:23 -0700702 }
Raymond Hettinger67c78b52015-09-12 11:00:20 -0400703 Py_SIZE(deque) += i;
Raymond Hettinger41290a62015-03-31 08:12:23 -0700704 Py_INCREF(deque);
705 return (PyObject *)deque;
706 }
707
Raymond Hettinger20151f52015-10-16 22:47:29 -0700708 if ((size_t)size > PY_SSIZE_T_MAX / (size_t)n) {
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400709 return PyErr_NoMemory();
710 }
711
Raymond Hettinger41290a62015-03-31 08:12:23 -0700712 seq = PySequence_List((PyObject *)deque);
713 if (seq == NULL)
714 return seq;
715
Louie Lu357bad72017-02-24 11:59:49 +0800716 /* Reduce the number of repetitions when maxlen would be exceeded */
717 if (deque->maxlen >= 0 && n * size > deque->maxlen)
718 n = (deque->maxlen + size - 1) / size;
719
Raymond Hettinger41290a62015-03-31 08:12:23 -0700720 for (i = 0 ; i < n-1 ; i++) {
721 rv = deque_extend(deque, seq);
722 if (rv == NULL) {
723 Py_DECREF(seq);
724 return NULL;
725 }
726 Py_DECREF(rv);
727 }
728 Py_INCREF(deque);
729 Py_DECREF(seq);
730 return (PyObject *)deque;
731}
732
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400733static PyObject *
734deque_repeat(dequeobject *deque, Py_ssize_t n)
735{
736 dequeobject *new_deque;
Raymond Hettinger95e2cc52015-09-13 02:41:18 -0400737 PyObject *rv;
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400738
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530739 new_deque = (dequeobject *)deque_copy((PyObject *) deque, NULL);
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400740 if (new_deque == NULL)
741 return NULL;
Raymond Hettinger95e2cc52015-09-13 02:41:18 -0400742 rv = deque_inplace_repeat(new_deque, n);
743 Py_DECREF(new_deque);
744 return rv;
Raymond Hettingerf5d72f32015-09-09 22:39:44 -0400745}
746
Raymond Hettinger54023152014-04-23 00:58:48 -0700747/* The rotate() method is part of the public API and is used internally
748as a primitive for other methods.
749
750Rotation by 1 or -1 is a common case, so any optimizations for high
751volume rotations should take care not to penalize the common case.
752
753Conceptually, a rotate by one is equivalent to a pop on one side and an
754append on the other. However, a pop/append pair is unnecessarily slow
Martin Panterd2ad5712015-11-02 04:20:33 +0000755because it requires an incref/decref pair for an object located randomly
Raymond Hettinger54023152014-04-23 00:58:48 -0700756in memory. It is better to just move the object pointer from one block
757to the next without changing the reference count.
758
759When moving batches of pointers, it is tempting to use memcpy() but that
760proved to be slower than a simple loop for a variety of reasons.
761Memcpy() cannot know in advance that we're copying pointers instead of
762bytes, that the source and destination are pointer aligned and
763non-overlapping, that moving just one pointer is a common case, that we
764never need to move more than BLOCKLEN pointers, and that at least one
765pointer is always moved.
766
767For high volume rotations, newblock() and freeblock() are never called
768more than once. Previously emptied blocks are immediately reused as a
769destination block. If a block is left-over at the end, it is freed.
770*/
771
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000772static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000773_deque_rotate(dequeobject *deque, Py_ssize_t n)
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000774{
Raymond Hettinger3959af92013-07-13 02:34:08 -0700775 block *b = NULL;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700776 block *leftblock = deque->leftblock;
777 block *rightblock = deque->rightblock;
778 Py_ssize_t leftindex = deque->leftindex;
779 Py_ssize_t rightindex = deque->rightindex;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000780 Py_ssize_t len=Py_SIZE(deque), halflen=len>>1;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700781 int rv = -1;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000782
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800783 if (len <= 1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 return 0;
785 if (n > halflen || n < -halflen) {
786 n %= len;
787 if (n > halflen)
788 n -= len;
789 else if (n < -halflen)
790 n += len;
791 }
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500792 assert(len > 1);
Raymond Hettingera4409c12013-02-04 00:08:12 -0500793 assert(-halflen <= n && n <= halflen);
Raymond Hettinger231ee4d2013-02-02 11:24:43 -0800794
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800795 deque->state++;
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500796 while (n > 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700797 if (leftindex == 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700798 if (b == NULL) {
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700799 b = newblock();
Raymond Hettinger3959af92013-07-13 02:34:08 -0700800 if (b == NULL)
801 goto done;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700802 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000803 b->rightlink = leftblock;
804 CHECK_END(leftblock->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700805 leftblock->leftlink = b;
806 leftblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000807 MARK_END(b->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700808 leftindex = BLOCKLEN;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700809 b = NULL;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800810 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700811 assert(leftindex > 0);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700812 {
813 PyObject **src, **dest;
814 Py_ssize_t m = n;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800815
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700816 if (m > rightindex + 1)
817 m = rightindex + 1;
818 if (m > leftindex)
819 m = leftindex;
820 assert (m > 0 && m <= len);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700821 rightindex -= m;
822 leftindex -= m;
Raymond Hettinger0e259f12015-02-01 22:53:41 -0800823 src = &rightblock->data[rightindex + 1];
824 dest = &leftblock->data[leftindex];
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700825 n -= m;
Raymond Hettinger840533b2013-07-13 17:03:58 -0700826 do {
Raymond Hettinger0e259f12015-02-01 22:53:41 -0800827 *(dest++) = *(src++);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700828 } while (--m);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700829 }
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -0700830 if (rightindex < 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700831 assert(leftblock != rightblock);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700832 assert(b == NULL);
Raymond Hettinger3959af92013-07-13 02:34:08 -0700833 b = rightblock;
Raymond Hettingerb97cc492013-07-21 01:51:07 -0700834 CHECK_NOT_END(rightblock->leftlink);
835 rightblock = rightblock->leftlink;
836 MARK_END(rightblock->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700837 rightindex = BLOCKLEN - 1;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800838 }
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800839 }
Raymond Hettinger1f0044c2013-02-05 01:30:46 -0500840 while (n < 0) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700841 if (rightindex == BLOCKLEN - 1) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700842 if (b == NULL) {
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700843 b = newblock();
Raymond Hettinger3959af92013-07-13 02:34:08 -0700844 if (b == NULL)
845 goto done;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700846 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000847 b->leftlink = rightblock;
848 CHECK_END(rightblock->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700849 rightblock->rightlink = b;
850 rightblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000851 MARK_END(b->rightlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700852 rightindex = -1;
Raymond Hettinger3959af92013-07-13 02:34:08 -0700853 b = NULL;
Raymond Hettinger464d89b2013-01-11 22:29:50 -0800854 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700855 assert (rightindex < BLOCKLEN - 1);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700856 {
857 PyObject **src, **dest;
858 Py_ssize_t m = -n;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800859
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700860 if (m > BLOCKLEN - leftindex)
861 m = BLOCKLEN - leftindex;
862 if (m > BLOCKLEN - 1 - rightindex)
863 m = BLOCKLEN - 1 - rightindex;
864 assert (m > 0 && m <= len);
865 src = &leftblock->data[leftindex];
866 dest = &rightblock->data[rightindex + 1];
867 leftindex += m;
868 rightindex += m;
869 n += m;
Raymond Hettinger840533b2013-07-13 17:03:58 -0700870 do {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700871 *(dest++) = *(src++);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700872 } while (--m);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700873 }
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700874 if (leftindex == BLOCKLEN) {
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700875 assert(leftblock != rightblock);
Raymond Hettinger840533b2013-07-13 17:03:58 -0700876 assert(b == NULL);
Raymond Hettinger3959af92013-07-13 02:34:08 -0700877 b = leftblock;
Raymond Hettingerb97cc492013-07-21 01:51:07 -0700878 CHECK_NOT_END(leftblock->rightlink);
879 leftblock = leftblock->rightlink;
880 MARK_END(leftblock->leftlink);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700881 leftindex = 0;
Raymond Hettinger21777ac2013-02-02 09:56:08 -0800882 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000883 }
Raymond Hettinger3959af92013-07-13 02:34:08 -0700884 rv = 0;
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700885done:
Raymond Hettinger3959af92013-07-13 02:34:08 -0700886 if (b != NULL)
887 freeblock(b);
Raymond Hettinger20b0f872013-06-23 15:44:33 -0700888 deque->leftblock = leftblock;
889 deque->rightblock = rightblock;
890 deque->leftindex = leftindex;
891 deque->rightindex = rightindex;
892
893 return rv;
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000894}
895
896static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +0200897deque_rotate(dequeobject *deque, PyObject *const *args, Py_ssize_t nargs)
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000898{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000899 Py_ssize_t n=1;
Raymond Hettingerdcb9d942004-10-09 16:02:18 +0000900
Victor Stinnerdd407d52017-02-06 16:06:49 +0100901 if (!_PyArg_ParseStack(args, nargs, "|n:rotate", &n)) {
902 return NULL;
903 }
904
Raymond Hettinger6921c132015-03-21 02:03:40 -0700905 if (!_deque_rotate(deque, n))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 Py_RETURN_NONE;
907 return NULL;
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000908}
909
Tim Peters1065f752004-10-01 01:03:29 +0000910PyDoc_STRVAR(rotate_doc,
Raymond Hettingeree33b272004-02-08 04:05:26 +0000911"Rotate the deque n steps to the right (default n=1). If n is negative, rotates left.");
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000912
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000913static PyObject *
914deque_reverse(dequeobject *deque, PyObject *unused)
915{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 block *leftblock = deque->leftblock;
917 block *rightblock = deque->rightblock;
918 Py_ssize_t leftindex = deque->leftindex;
919 Py_ssize_t rightindex = deque->rightindex;
Raymond Hettingercfe5b6c2015-07-20 00:25:50 -0400920 Py_ssize_t n = Py_SIZE(deque) >> 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 PyObject *tmp;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000922
Raymond Hettingere1b02872017-09-04 16:07:06 -0700923 while (--n >= 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 /* Validate that pointers haven't met in the middle */
925 assert(leftblock != rightblock || leftindex < rightindex);
Raymond Hettinger82df9252013-07-07 01:43:42 -1000926 CHECK_NOT_END(leftblock);
927 CHECK_NOT_END(rightblock);
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000928
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000929 /* Swap */
930 tmp = leftblock->data[leftindex];
931 leftblock->data[leftindex] = rightblock->data[rightindex];
932 rightblock->data[rightindex] = tmp;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000933
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 /* Advance left block/index pair */
935 leftindex++;
936 if (leftindex == BLOCKLEN) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000937 leftblock = leftblock->rightlink;
938 leftindex = 0;
939 }
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 /* Step backwards with the right block/index pair */
942 rightindex--;
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -0700943 if (rightindex < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000944 rightblock = rightblock->leftlink;
945 rightindex = BLOCKLEN - 1;
946 }
947 }
948 Py_RETURN_NONE;
Raymond Hettingere5fdedb2009-12-10 00:47:21 +0000949}
950
951PyDoc_STRVAR(reverse_doc,
952"D.reverse() -- reverse *IN PLACE*");
953
Raymond Hettinger44459de2010-04-03 23:20:46 +0000954static PyObject *
955deque_count(dequeobject *deque, PyObject *v)
956{
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000957 block *b = deque->leftblock;
958 Py_ssize_t index = deque->leftindex;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000959 Py_ssize_t n = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 Py_ssize_t count = 0;
Raymond Hettingerf9d9c792015-03-02 22:47:46 -0800961 size_t start_state = deque->state;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962 PyObject *item;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000963 int cmp;
Raymond Hettinger44459de2010-04-03 23:20:46 +0000964
Raymond Hettingere1b02872017-09-04 16:07:06 -0700965 while (--n >= 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -1000966 CHECK_NOT_END(b);
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000967 item = b->data[index];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000968 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
Raymond Hettinger2b0d6462015-09-23 19:15:44 -0700969 if (cmp < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000970 return NULL;
Raymond Hettinger2b0d6462015-09-23 19:15:44 -0700971 count += cmp;
Raymond Hettinger44459de2010-04-03 23:20:46 +0000972
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000973 if (start_state != deque->state) {
974 PyErr_SetString(PyExc_RuntimeError,
975 "deque mutated during iteration");
976 return NULL;
977 }
Raymond Hettinger44459de2010-04-03 23:20:46 +0000978
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 /* Advance left block/index pair */
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000980 index++;
981 if (index == BLOCKLEN) {
982 b = b->rightlink;
983 index = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000984 }
985 }
986 return PyLong_FromSsize_t(count);
Raymond Hettinger44459de2010-04-03 23:20:46 +0000987}
988
989PyDoc_STRVAR(count_doc,
990"D.count(value) -> integer -- return number of occurrences of value");
991
Raymond Hettinger39dadf72015-03-20 16:38:56 -0700992static int
993deque_contains(dequeobject *deque, PyObject *v)
994{
995 block *b = deque->leftblock;
996 Py_ssize_t index = deque->leftindex;
997 Py_ssize_t n = Py_SIZE(deque);
Raymond Hettinger39dadf72015-03-20 16:38:56 -0700998 size_t start_state = deque->state;
999 PyObject *item;
1000 int cmp;
1001
Raymond Hettingere1b02872017-09-04 16:07:06 -07001002 while (--n >= 0) {
Raymond Hettinger39dadf72015-03-20 16:38:56 -07001003 CHECK_NOT_END(b);
1004 item = b->data[index];
1005 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
1006 if (cmp) {
1007 return cmp;
1008 }
1009 if (start_state != deque->state) {
1010 PyErr_SetString(PyExc_RuntimeError,
1011 "deque mutated during iteration");
1012 return -1;
1013 }
1014 index++;
1015 if (index == BLOCKLEN) {
1016 b = b->rightlink;
1017 index = 0;
1018 }
1019 }
1020 return 0;
1021}
1022
Martin v. Löwis18e16552006-02-15 17:27:45 +00001023static Py_ssize_t
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001024deque_len(dequeobject *deque)
1025{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001026 return Py_SIZE(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001027}
1028
Raymond Hettinger4aec61e2005-03-18 21:20:23 +00001029static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02001030deque_index(dequeobject *deque, PyObject *const *args, Py_ssize_t nargs)
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001031{
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001032 Py_ssize_t i, n, start=0, stop=Py_SIZE(deque);
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001033 PyObject *v, *item;
1034 block *b = deque->leftblock;
1035 Py_ssize_t index = deque->leftindex;
1036 size_t start_state = deque->state;
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001037 int cmp;
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001038
Victor Stinnerdd407d52017-02-06 16:06:49 +01001039 if (!_PyArg_ParseStack(args, nargs, "O|O&O&:index", &v,
Serhiy Storchakad4edfc92017-03-30 18:29:23 +03001040 _PyEval_SliceIndexNotNone, &start,
1041 _PyEval_SliceIndexNotNone, &stop)) {
Victor Stinnerdd407d52017-02-06 16:06:49 +01001042 return NULL;
1043 }
1044
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001045 if (start < 0) {
1046 start += Py_SIZE(deque);
1047 if (start < 0)
1048 start = 0;
1049 }
1050 if (stop < 0) {
1051 stop += Py_SIZE(deque);
1052 if (stop < 0)
1053 stop = 0;
1054 }
Raymond Hettinger87674ec2015-08-26 08:08:38 -07001055 if (stop > Py_SIZE(deque))
1056 stop = Py_SIZE(deque);
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001057 if (start > stop)
1058 start = stop;
1059 assert(0 <= start && start <= stop && stop <= Py_SIZE(deque));
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001060
Raymond Hettingerb46ad542018-09-21 01:46:41 -07001061 for (i=0 ; i < start - BLOCKLEN ; i += BLOCKLEN) {
1062 b = b->rightlink;
1063 }
1064 for ( ; i < start ; i++) {
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001065 index++;
1066 if (index == BLOCKLEN) {
1067 b = b->rightlink;
1068 index = 0;
1069 }
1070 }
1071
Raymond Hettingere1b02872017-09-04 16:07:06 -07001072 n = stop - i;
1073 while (--n >= 0) {
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001074 CHECK_NOT_END(b);
1075 item = b->data[index];
1076 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
1077 if (cmp > 0)
Raymond Hettingere1b02872017-09-04 16:07:06 -07001078 return PyLong_FromSsize_t(stop - n - 1);
Raymond Hettingerdf8f5b52015-11-02 07:27:40 -05001079 if (cmp < 0)
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001080 return NULL;
1081 if (start_state != deque->state) {
1082 PyErr_SetString(PyExc_RuntimeError,
1083 "deque mutated during iteration");
1084 return NULL;
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001085 }
1086 index++;
1087 if (index == BLOCKLEN) {
1088 b = b->rightlink;
1089 index = 0;
1090 }
1091 }
1092 PyErr_Format(PyExc_ValueError, "%R is not in deque", v);
1093 return NULL;
1094}
1095
1096PyDoc_STRVAR(index_doc,
1097"D.index(value, [start, [stop]]) -> integer -- return first index of value.\n"
1098"Raises ValueError if the value is not present.");
1099
Raymond Hettinger551350a2015-03-24 00:19:53 -07001100/* insert(), remove(), and delitem() are implemented in terms of
1101 rotate() for simplicity and reasonable performance near the end
1102 points. If for some reason these methods become popular, it is not
1103 hard to re-implement this using direct data movement (similar to
1104 the code used in list slice assignments) and achieve a performance
Raymond Hettingerfef9c1b2015-03-24 21:12:57 -07001105 boost (by moving each pointer only once instead of twice).
Raymond Hettinger551350a2015-03-24 00:19:53 -07001106*/
1107
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001108static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02001109deque_insert(dequeobject *deque, PyObject *const *args, Py_ssize_t nargs)
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001110{
1111 Py_ssize_t index;
1112 Py_ssize_t n = Py_SIZE(deque);
1113 PyObject *value;
1114 PyObject *rv;
1115
Victor Stinnerdd407d52017-02-06 16:06:49 +01001116 if (!_PyArg_ParseStack(args, nargs, "nO:insert", &index, &value)) {
1117 return NULL;
1118 }
1119
Raymond Hettinger37434322016-01-26 21:44:16 -08001120 if (deque->maxlen == Py_SIZE(deque)) {
Raymond Hettingera6389712016-02-01 21:21:19 -08001121 PyErr_SetString(PyExc_IndexError, "deque already at its maximum size");
1122 return NULL;
Raymond Hettinger37434322016-01-26 21:44:16 -08001123 }
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001124 if (index >= n)
1125 return deque_append(deque, value);
1126 if (index <= -n || index == 0)
1127 return deque_appendleft(deque, value);
1128 if (_deque_rotate(deque, -index))
1129 return NULL;
1130 if (index < 0)
1131 rv = deque_append(deque, value);
1132 else
1133 rv = deque_appendleft(deque, value);
1134 if (rv == NULL)
1135 return NULL;
1136 Py_DECREF(rv);
1137 if (_deque_rotate(deque, index))
1138 return NULL;
1139 Py_RETURN_NONE;
1140}
1141
1142PyDoc_STRVAR(insert_doc,
1143"D.insert(index, object) -- insert object before index");
1144
1145static PyObject *
Raymond Hettinger4aec61e2005-03-18 21:20:23 +00001146deque_remove(dequeobject *deque, PyObject *value)
1147{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001148 Py_ssize_t i, n=Py_SIZE(deque);
Raymond Hettinger4aec61e2005-03-18 21:20:23 +00001149
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001150 for (i=0 ; i<n ; i++) {
1151 PyObject *item = deque->leftblock->data[deque->leftindex];
1152 int cmp = PyObject_RichCompareBool(item, value, Py_EQ);
Raymond Hettingerd73202c2005-03-19 00:00:51 +00001153
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001154 if (Py_SIZE(deque) != n) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001155 PyErr_SetString(PyExc_IndexError,
1156 "deque mutated during remove().");
1157 return NULL;
1158 }
1159 if (cmp > 0) {
1160 PyObject *tgt = deque_popleft(deque, NULL);
1161 assert (tgt != NULL);
Raymond Hettinger6921c132015-03-21 02:03:40 -07001162 if (_deque_rotate(deque, i))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001163 return NULL;
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001164 Py_DECREF(tgt);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001165 Py_RETURN_NONE;
1166 }
1167 else if (cmp < 0) {
1168 _deque_rotate(deque, i);
1169 return NULL;
1170 }
1171 _deque_rotate(deque, -1);
1172 }
1173 PyErr_SetString(PyExc_ValueError, "deque.remove(x): x not in deque");
1174 return NULL;
Raymond Hettinger4aec61e2005-03-18 21:20:23 +00001175}
1176
1177PyDoc_STRVAR(remove_doc,
1178"D.remove(value) -- remove first occurrence of value.");
1179
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001180static int
1181valid_index(Py_ssize_t i, Py_ssize_t limit)
1182{
Raymond Hettinger12f896c2015-07-31 12:03:20 -07001183 /* The cast to size_t lets us use just a single comparison
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001184 to check whether i is in the range: 0 <= i < limit */
1185 return (size_t) i < (size_t) limit;
1186}
1187
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001188static PyObject *
Benjamin Petersond6313712008-07-31 16:23:04 +00001189deque_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001190{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001191 block *b;
1192 PyObject *item;
1193 Py_ssize_t n, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001194
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001195 if (!valid_index(i, Py_SIZE(deque))) {
1196 PyErr_SetString(PyExc_IndexError, "deque index out of range");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001197 return NULL;
1198 }
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001200 if (i == 0) {
1201 i = deque->leftindex;
1202 b = deque->leftblock;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001203 } else if (i == Py_SIZE(deque) - 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 i = deque->rightindex;
1205 b = deque->rightblock;
1206 } else {
1207 i += deque->leftindex;
Raymond Hettingerc2083082015-02-28 23:29:16 -08001208 n = (Py_ssize_t)((size_t) i / BLOCKLEN);
1209 i = (Py_ssize_t)((size_t) i % BLOCKLEN);
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001210 if (index < (Py_SIZE(deque) >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001211 b = deque->leftblock;
Raymond Hettingere1b02872017-09-04 16:07:06 -07001212 while (--n >= 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 b = b->rightlink;
1214 } else {
Raymond Hettinger63d1ff22015-02-28 07:41:30 -08001215 n = (Py_ssize_t)(
Raymond Hettingerc2083082015-02-28 23:29:16 -08001216 ((size_t)(deque->leftindex + Py_SIZE(deque) - 1))
Raymond Hettinger63d1ff22015-02-28 07:41:30 -08001217 / BLOCKLEN - n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001218 b = deque->rightblock;
Raymond Hettingere1b02872017-09-04 16:07:06 -07001219 while (--n >= 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001220 b = b->leftlink;
1221 }
1222 }
1223 item = b->data[i];
1224 Py_INCREF(item);
1225 return item;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001226}
1227
1228static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001229deque_del_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001230{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001231 PyObject *item;
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001232 int rv;
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001233
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001234 assert (i >= 0 && i < Py_SIZE(deque));
Raymond Hettinger6921c132015-03-21 02:03:40 -07001235 if (_deque_rotate(deque, -i))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001236 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001237 item = deque_popleft(deque, NULL);
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001238 rv = _deque_rotate(deque, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001239 assert (item != NULL);
1240 Py_DECREF(item);
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001241 return rv;
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001242}
1243
1244static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001245deque_ass_item(dequeobject *deque, Py_ssize_t i, PyObject *v)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001246{
Raymond Hettinger38418662016-02-08 20:34:49 -08001247 PyObject *old_value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001248 block *b;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001249 Py_ssize_t n, len=Py_SIZE(deque), halflen=(len+1)>>1, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001250
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001251 if (!valid_index(i, len)) {
1252 PyErr_SetString(PyExc_IndexError, "deque index out of range");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001253 return -1;
1254 }
1255 if (v == NULL)
1256 return deque_del_item(deque, i);
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258 i += deque->leftindex;
Raymond Hettingerc2083082015-02-28 23:29:16 -08001259 n = (Py_ssize_t)((size_t) i / BLOCKLEN);
1260 i = (Py_ssize_t)((size_t) i % BLOCKLEN);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001261 if (index <= halflen) {
1262 b = deque->leftblock;
Raymond Hettingere1b02872017-09-04 16:07:06 -07001263 while (--n >= 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001264 b = b->rightlink;
1265 } else {
Raymond Hettingera473b9d2015-02-28 17:49:47 -08001266 n = (Py_ssize_t)(
Raymond Hettingerc2083082015-02-28 23:29:16 -08001267 ((size_t)(deque->leftindex + Py_SIZE(deque) - 1))
Raymond Hettingera473b9d2015-02-28 17:49:47 -08001268 / BLOCKLEN - n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001269 b = deque->rightblock;
Raymond Hettingere1b02872017-09-04 16:07:06 -07001270 while (--n >= 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001271 b = b->leftlink;
1272 }
1273 Py_INCREF(v);
Raymond Hettinger38418662016-02-08 20:34:49 -08001274 old_value = b->data[i];
1275 b->data[i] = v;
1276 Py_DECREF(old_value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001277 return 0;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001278}
1279
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001280static void
1281deque_dealloc(dequeobject *deque)
1282{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001283 PyObject_GC_UnTrack(deque);
1284 if (deque->weakreflist != NULL)
1285 PyObject_ClearWeakRefs((PyObject *) deque);
1286 if (deque->leftblock != NULL) {
1287 deque_clear(deque);
1288 assert(deque->leftblock != NULL);
1289 freeblock(deque->leftblock);
1290 }
1291 deque->leftblock = NULL;
1292 deque->rightblock = NULL;
1293 Py_TYPE(deque)->tp_free(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001294}
1295
1296static int
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001297deque_traverse(dequeobject *deque, visitproc visit, void *arg)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001298{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001299 block *b;
1300 PyObject *item;
1301 Py_ssize_t index;
1302 Py_ssize_t indexlo = deque->leftindex;
Raymond Hettinger1286d142015-10-14 23:16:57 -07001303 Py_ssize_t indexhigh;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001304
Raymond Hettinger5bfa8672013-07-06 11:58:09 -10001305 for (b = deque->leftblock; b != deque->rightblock; b = b->rightlink) {
1306 for (index = indexlo; index < BLOCKLEN ; index++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001307 item = b->data[index];
1308 Py_VISIT(item);
1309 }
1310 indexlo = 0;
1311 }
Raymond Hettinger1286d142015-10-14 23:16:57 -07001312 indexhigh = deque->rightindex;
1313 for (index = indexlo; index <= indexhigh; index++) {
Raymond Hettinger5bfa8672013-07-06 11:58:09 -10001314 item = b->data[index];
1315 Py_VISIT(item);
1316 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001317 return 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001318}
1319
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001320static PyObject *
Serhiy Storchaka81524022018-11-27 13:05:02 +02001321deque_reduce(dequeobject *deque, PyObject *Py_UNUSED(ignored))
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001322{
Serhiy Storchakaa0d416f2016-03-06 08:55:21 +02001323 PyObject *dict, *it;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001324 _Py_IDENTIFIER(__dict__);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001325
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001326 if (_PyObject_LookupAttrId((PyObject *)deque, &PyId___dict__, &dict) < 0) {
1327 return NULL;
1328 }
Serhiy Storchakaa0d416f2016-03-06 08:55:21 +02001329 if (dict == NULL) {
Serhiy Storchakaa0d416f2016-03-06 08:55:21 +02001330 dict = Py_None;
1331 Py_INCREF(dict);
1332 }
1333
1334 it = PyObject_GetIter((PyObject *)deque);
1335 if (it == NULL) {
1336 Py_DECREF(dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001337 return NULL;
1338 }
Serhiy Storchakaa0d416f2016-03-06 08:55:21 +02001339
1340 if (deque->maxlen < 0) {
1341 return Py_BuildValue("O()NN", Py_TYPE(deque), dict, it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001342 }
Serhiy Storchakaa0d416f2016-03-06 08:55:21 +02001343 else {
1344 return Py_BuildValue("O(()n)NN", Py_TYPE(deque), deque->maxlen, dict, it);
1345 }
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001346}
1347
1348PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
1349
1350static PyObject *
1351deque_repr(PyObject *deque)
1352{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001353 PyObject *aslist, *result;
1354 int i;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001356 i = Py_ReprEnter(deque);
1357 if (i != 0) {
1358 if (i < 0)
1359 return NULL;
1360 return PyUnicode_FromString("[...]");
1361 }
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001363 aslist = PySequence_List(deque);
1364 if (aslist == NULL) {
1365 Py_ReprLeave(deque);
1366 return NULL;
1367 }
Raymond Hettingera7f630092015-10-10 23:56:02 -04001368 if (((dequeobject *)deque)->maxlen >= 0)
Serhiy Storchakab3a77962017-09-21 14:24:13 +03001369 result = PyUnicode_FromFormat("%s(%R, maxlen=%zd)",
1370 _PyType_Name(Py_TYPE(deque)), aslist,
1371 ((dequeobject *)deque)->maxlen);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001372 else
Serhiy Storchakab3a77962017-09-21 14:24:13 +03001373 result = PyUnicode_FromFormat("%s(%R)",
1374 _PyType_Name(Py_TYPE(deque)), aslist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001375 Py_ReprLeave(deque);
Raymond Hettinger2b2b7532015-09-05 17:05:52 -07001376 Py_DECREF(aslist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001377 return result;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001378}
1379
Raymond Hettinger738ec902004-02-29 02:15:56 +00001380static PyObject *
1381deque_richcompare(PyObject *v, PyObject *w, int op)
1382{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001383 PyObject *it1=NULL, *it2=NULL, *x, *y;
1384 Py_ssize_t vs, ws;
1385 int b, cmp=-1;
Raymond Hettinger738ec902004-02-29 02:15:56 +00001386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001387 if (!PyObject_TypeCheck(v, &deque_type) ||
1388 !PyObject_TypeCheck(w, &deque_type)) {
Brian Curtindfc80e32011-08-10 20:28:54 -05001389 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001390 }
Raymond Hettinger738ec902004-02-29 02:15:56 +00001391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001392 /* Shortcuts */
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001393 vs = Py_SIZE((dequeobject *)v);
1394 ws = Py_SIZE((dequeobject *)w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001395 if (op == Py_EQ) {
1396 if (v == w)
1397 Py_RETURN_TRUE;
1398 if (vs != ws)
1399 Py_RETURN_FALSE;
1400 }
1401 if (op == Py_NE) {
1402 if (v == w)
1403 Py_RETURN_FALSE;
1404 if (vs != ws)
1405 Py_RETURN_TRUE;
1406 }
Raymond Hettinger738ec902004-02-29 02:15:56 +00001407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001408 /* Search for the first index where items are different */
1409 it1 = PyObject_GetIter(v);
1410 if (it1 == NULL)
1411 goto done;
1412 it2 = PyObject_GetIter(w);
1413 if (it2 == NULL)
1414 goto done;
1415 for (;;) {
1416 x = PyIter_Next(it1);
1417 if (x == NULL && PyErr_Occurred())
1418 goto done;
1419 y = PyIter_Next(it2);
1420 if (x == NULL || y == NULL)
1421 break;
1422 b = PyObject_RichCompareBool(x, y, Py_EQ);
1423 if (b == 0) {
1424 cmp = PyObject_RichCompareBool(x, y, op);
1425 Py_DECREF(x);
1426 Py_DECREF(y);
1427 goto done;
1428 }
1429 Py_DECREF(x);
1430 Py_DECREF(y);
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -07001431 if (b < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001432 goto done;
1433 }
1434 /* We reached the end of one deque or both */
1435 Py_XDECREF(x);
1436 Py_XDECREF(y);
1437 if (PyErr_Occurred())
1438 goto done;
1439 switch (op) {
1440 case Py_LT: cmp = y != NULL; break; /* if w was longer */
1441 case Py_LE: cmp = x == NULL; break; /* if v was not longer */
1442 case Py_EQ: cmp = x == y; break; /* if we reached the end of both */
1443 case Py_NE: cmp = x != y; break; /* if one deque continues */
1444 case Py_GT: cmp = x != NULL; break; /* if v was longer */
1445 case Py_GE: cmp = y == NULL; break; /* if w was not longer */
1446 }
Tim Peters1065f752004-10-01 01:03:29 +00001447
Raymond Hettinger738ec902004-02-29 02:15:56 +00001448done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001449 Py_XDECREF(it1);
1450 Py_XDECREF(it2);
1451 if (cmp == 1)
1452 Py_RETURN_TRUE;
1453 if (cmp == 0)
1454 Py_RETURN_FALSE;
1455 return NULL;
Raymond Hettinger738ec902004-02-29 02:15:56 +00001456}
1457
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001458static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001459deque_init(dequeobject *deque, PyObject *args, PyObject *kwdargs)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001460{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001461 PyObject *iterable = NULL;
1462 PyObject *maxlenobj = NULL;
1463 Py_ssize_t maxlen = -1;
1464 char *kwlist[] = {"iterable", "maxlen", 0};
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001465
Raymond Hettinger0d309402015-09-30 23:15:02 -07001466 if (kwdargs == NULL) {
1467 if (!PyArg_UnpackTuple(args, "deque()", 0, 2, &iterable, &maxlenobj))
1468 return -1;
1469 } else {
1470 if (!PyArg_ParseTupleAndKeywords(args, kwdargs, "|OO:deque", kwlist,
1471 &iterable, &maxlenobj))
1472 return -1;
1473 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001474 if (maxlenobj != NULL && maxlenobj != Py_None) {
1475 maxlen = PyLong_AsSsize_t(maxlenobj);
1476 if (maxlen == -1 && PyErr_Occurred())
1477 return -1;
1478 if (maxlen < 0) {
1479 PyErr_SetString(PyExc_ValueError, "maxlen must be non-negative");
1480 return -1;
1481 }
1482 }
1483 deque->maxlen = maxlen;
Raymond Hettinger0d309402015-09-30 23:15:02 -07001484 if (Py_SIZE(deque) > 0)
1485 deque_clear(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001486 if (iterable != NULL) {
1487 PyObject *rv = deque_extend(deque, iterable);
1488 if (rv == NULL)
1489 return -1;
1490 Py_DECREF(rv);
1491 }
1492 return 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001493}
1494
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001495static PyObject *
Jesus Cea16e2fca2012-08-03 14:49:42 +02001496deque_sizeof(dequeobject *deque, void *unused)
1497{
1498 Py_ssize_t res;
1499 Py_ssize_t blocks;
1500
Serhiy Storchaka5c4064e2015-12-19 20:05:25 +02001501 res = _PyObject_SIZE(Py_TYPE(deque));
Raymond Hettingerbc003412015-10-14 23:33:23 -07001502 blocks = (size_t)(deque->leftindex + Py_SIZE(deque) + BLOCKLEN - 1) / BLOCKLEN;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001503 assert(deque->leftindex + Py_SIZE(deque) - 1 ==
Jesus Cea16e2fca2012-08-03 14:49:42 +02001504 (blocks - 1) * BLOCKLEN + deque->rightindex);
1505 res += blocks * sizeof(block);
1506 return PyLong_FromSsize_t(res);
1507}
1508
1509PyDoc_STRVAR(sizeof_doc,
1510"D.__sizeof__() -- size of D in memory, in bytes");
1511
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001512static int
1513deque_bool(dequeobject *deque)
1514{
1515 return Py_SIZE(deque) != 0;
1516}
1517
Jesus Cea16e2fca2012-08-03 14:49:42 +02001518static PyObject *
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +02001519deque_get_maxlen(dequeobject *deque, void *Py_UNUSED(ignored))
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001520{
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -07001521 if (deque->maxlen < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001522 Py_RETURN_NONE;
1523 return PyLong_FromSsize_t(deque->maxlen);
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001524}
1525
Raymond Hettinger41290a62015-03-31 08:12:23 -07001526
1527/* deque object ********************************************************/
1528
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001529static PyGetSetDef deque_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001530 {"maxlen", (getter)deque_get_maxlen, (setter)NULL,
1531 "maximum size of a deque or None if unbounded"},
1532 {0}
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001533};
1534
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001535static PySequenceMethods deque_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001536 (lenfunc)deque_len, /* sq_length */
Raymond Hettinger41290a62015-03-31 08:12:23 -07001537 (binaryfunc)deque_concat, /* sq_concat */
1538 (ssizeargfunc)deque_repeat, /* sq_repeat */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001539 (ssizeargfunc)deque_item, /* sq_item */
1540 0, /* sq_slice */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001541 (ssizeobjargproc)deque_ass_item, /* sq_ass_item */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001542 0, /* sq_ass_slice */
Raymond Hettinger39dadf72015-03-20 16:38:56 -07001543 (objobjproc)deque_contains, /* sq_contains */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001544 (binaryfunc)deque_inplace_concat, /* sq_inplace_concat */
Raymond Hettinger41290a62015-03-31 08:12:23 -07001545 (ssizeargfunc)deque_inplace_repeat, /* sq_inplace_repeat */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001546};
1547
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001548static PyNumberMethods deque_as_number = {
1549 0, /* nb_add */
1550 0, /* nb_subtract */
1551 0, /* nb_multiply */
1552 0, /* nb_remainder */
1553 0, /* nb_divmod */
1554 0, /* nb_power */
1555 0, /* nb_negative */
1556 0, /* nb_positive */
1557 0, /* nb_absolute */
1558 (inquiry)deque_bool, /* nb_bool */
1559 0, /* nb_invert */
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001560 };
1561
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001562static PyObject *deque_iter(dequeobject *deque);
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301563static PyObject *deque_reviter(dequeobject *deque, PyObject *Py_UNUSED(ignored));
Tim Peters1065f752004-10-01 01:03:29 +00001564PyDoc_STRVAR(reversed_doc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001565 "D.__reversed__() -- return a reverse iterator over the deque");
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001566
1567static PyMethodDef deque_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001568 {"append", (PyCFunction)deque_append,
1569 METH_O, append_doc},
1570 {"appendleft", (PyCFunction)deque_appendleft,
1571 METH_O, appendleft_doc},
1572 {"clear", (PyCFunction)deque_clearmethod,
1573 METH_NOARGS, clear_doc},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301574 {"__copy__", deque_copy,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001575 METH_NOARGS, copy_doc},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301576 {"copy", deque_copy,
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001577 METH_NOARGS, copy_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001578 {"count", (PyCFunction)deque_count,
Raymond Hettinger0f6f9472015-03-21 01:42:10 -07001579 METH_O, count_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001580 {"extend", (PyCFunction)deque_extend,
1581 METH_O, extend_doc},
1582 {"extendleft", (PyCFunction)deque_extendleft,
1583 METH_O, extendleft_doc},
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001584 {"index", (PyCFunction)(void(*)(void))deque_index,
Victor Stinnerdd407d52017-02-06 16:06:49 +01001585 METH_FASTCALL, index_doc},
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001586 {"insert", (PyCFunction)(void(*)(void))deque_insert,
Victor Stinnerdd407d52017-02-06 16:06:49 +01001587 METH_FASTCALL, insert_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001588 {"pop", (PyCFunction)deque_pop,
1589 METH_NOARGS, pop_doc},
1590 {"popleft", (PyCFunction)deque_popleft,
1591 METH_NOARGS, popleft_doc},
Raymond Hettinger0f6f9472015-03-21 01:42:10 -07001592 {"__reduce__", (PyCFunction)deque_reduce,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001593 METH_NOARGS, reduce_doc},
1594 {"remove", (PyCFunction)deque_remove,
1595 METH_O, remove_doc},
1596 {"__reversed__", (PyCFunction)deque_reviter,
1597 METH_NOARGS, reversed_doc},
1598 {"reverse", (PyCFunction)deque_reverse,
1599 METH_NOARGS, reverse_doc},
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001600 {"rotate", (PyCFunction)(void(*)(void))deque_rotate,
Victor Stinnerdd407d52017-02-06 16:06:49 +01001601 METH_FASTCALL, rotate_doc},
Jesus Cea16e2fca2012-08-03 14:49:42 +02001602 {"__sizeof__", (PyCFunction)deque_sizeof,
1603 METH_NOARGS, sizeof_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001604 {NULL, NULL} /* sentinel */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001605};
1606
1607PyDoc_STRVAR(deque_doc,
Andrew Svetlov6a5c7c32012-10-31 11:50:40 +02001608"deque([iterable[, maxlen]]) --> deque object\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001609\n\
Raymond Hettinger41290a62015-03-31 08:12:23 -07001610A list-like sequence optimized for data accesses near its endpoints.");
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001611
Neal Norwitz87f10132004-02-29 15:40:53 +00001612static PyTypeObject deque_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001613 PyVarObject_HEAD_INIT(NULL, 0)
1614 "collections.deque", /* tp_name */
1615 sizeof(dequeobject), /* tp_basicsize */
1616 0, /* tp_itemsize */
1617 /* methods */
1618 (destructor)deque_dealloc, /* tp_dealloc */
1619 0, /* tp_print */
1620 0, /* tp_getattr */
1621 0, /* tp_setattr */
1622 0, /* tp_reserved */
1623 deque_repr, /* tp_repr */
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001624 &deque_as_number, /* tp_as_number */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001625 &deque_as_sequence, /* tp_as_sequence */
1626 0, /* tp_as_mapping */
Georg Brandlf038b322010-10-18 07:35:09 +00001627 PyObject_HashNotImplemented, /* tp_hash */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001628 0, /* tp_call */
1629 0, /* tp_str */
1630 PyObject_GenericGetAttr, /* tp_getattro */
1631 0, /* tp_setattro */
1632 0, /* tp_as_buffer */
1633 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
Georg Brandlf038b322010-10-18 07:35:09 +00001634 /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001635 deque_doc, /* tp_doc */
1636 (traverseproc)deque_traverse, /* tp_traverse */
1637 (inquiry)deque_clear, /* tp_clear */
1638 (richcmpfunc)deque_richcompare, /* tp_richcompare */
Georg Brandlf038b322010-10-18 07:35:09 +00001639 offsetof(dequeobject, weakreflist), /* tp_weaklistoffset*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001640 (getiterfunc)deque_iter, /* tp_iter */
1641 0, /* tp_iternext */
1642 deque_methods, /* tp_methods */
1643 0, /* tp_members */
Georg Brandlf038b322010-10-18 07:35:09 +00001644 deque_getset, /* tp_getset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001645 0, /* tp_base */
1646 0, /* tp_dict */
1647 0, /* tp_descr_get */
1648 0, /* tp_descr_set */
1649 0, /* tp_dictoffset */
1650 (initproc)deque_init, /* tp_init */
1651 PyType_GenericAlloc, /* tp_alloc */
1652 deque_new, /* tp_new */
1653 PyObject_GC_Del, /* tp_free */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001654};
1655
1656/*********************** Deque Iterator **************************/
1657
1658typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001659 PyObject_HEAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001660 block *b;
Raymond Hettinger87e69122015-03-02 23:32:02 -08001661 Py_ssize_t index;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001662 dequeobject *deque;
Raymond Hettingerf9d9c792015-03-02 22:47:46 -08001663 size_t state; /* state when the iterator is created */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001664 Py_ssize_t counter; /* number of items remaining for iteration */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001665} dequeiterobject;
1666
Martin v. Löwis59683e82008-06-13 07:50:45 +00001667static PyTypeObject dequeiter_type;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001668
1669static PyObject *
1670deque_iter(dequeobject *deque)
1671{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001672 dequeiterobject *it;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001673
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001674 it = PyObject_GC_New(dequeiterobject, &dequeiter_type);
1675 if (it == NULL)
1676 return NULL;
1677 it->b = deque->leftblock;
1678 it->index = deque->leftindex;
1679 Py_INCREF(deque);
1680 it->deque = deque;
1681 it->state = deque->state;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001682 it->counter = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001683 PyObject_GC_Track(it);
1684 return (PyObject *)it;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001685}
1686
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001687static int
1688dequeiter_traverse(dequeiterobject *dio, visitproc visit, void *arg)
1689{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001690 Py_VISIT(dio->deque);
1691 return 0;
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001692}
1693
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001694static void
1695dequeiter_dealloc(dequeiterobject *dio)
1696{
INADA Naokia6296d32017-08-24 14:55:17 +09001697 /* bpo-31095: UnTrack is needed before calling any callbacks */
1698 PyObject_GC_UnTrack(dio);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001699 Py_XDECREF(dio->deque);
1700 PyObject_GC_Del(dio);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001701}
1702
1703static PyObject *
1704dequeiter_next(dequeiterobject *it)
1705{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001706 PyObject *item;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001708 if (it->deque->state != it->state) {
1709 it->counter = 0;
1710 PyErr_SetString(PyExc_RuntimeError,
1711 "deque mutated during iteration");
1712 return NULL;
1713 }
1714 if (it->counter == 0)
1715 return NULL;
1716 assert (!(it->b == it->deque->rightblock &&
1717 it->index > it->deque->rightindex));
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001719 item = it->b->data[it->index];
1720 it->index++;
1721 it->counter--;
1722 if (it->index == BLOCKLEN && it->counter > 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -10001723 CHECK_NOT_END(it->b->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001724 it->b = it->b->rightlink;
1725 it->index = 0;
1726 }
1727 Py_INCREF(item);
1728 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001729}
1730
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001731static PyObject *
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001732dequeiter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1733{
1734 Py_ssize_t i, index=0;
1735 PyObject *deque;
1736 dequeiterobject *it;
1737 if (!PyArg_ParseTuple(args, "O!|n", &deque_type, &deque, &index))
1738 return NULL;
1739 assert(type == &dequeiter_type);
1740
1741 it = (dequeiterobject*)deque_iter((dequeobject *)deque);
1742 if (!it)
1743 return NULL;
1744 /* consume items from the queue */
1745 for(i=0; i<index; i++) {
1746 PyObject *item = dequeiter_next(it);
1747 if (item) {
1748 Py_DECREF(item);
1749 } else {
1750 if (it->counter) {
1751 Py_DECREF(it);
1752 return NULL;
1753 } else
1754 break;
1755 }
1756 }
1757 return (PyObject*)it;
1758}
1759
1760static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301761dequeiter_len(dequeiterobject *it, PyObject *Py_UNUSED(ignored))
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001762{
Antoine Pitrou554f3342010-08-17 18:30:06 +00001763 return PyLong_FromSsize_t(it->counter);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001764}
1765
Armin Rigof5b3e362006-02-11 21:32:43 +00001766PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001767
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001768static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301769dequeiter_reduce(dequeiterobject *it, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001770{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001771 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 +00001772}
1773
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001774static PyMethodDef dequeiter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001775 {"__length_hint__", (PyCFunction)dequeiter_len, METH_NOARGS, length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001776 {"__reduce__", (PyCFunction)dequeiter_reduce, METH_NOARGS, reduce_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001777 {NULL, NULL} /* sentinel */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001778};
1779
Martin v. Löwis59683e82008-06-13 07:50:45 +00001780static PyTypeObject dequeiter_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001781 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger87e69122015-03-02 23:32:02 -08001782 "_collections._deque_iterator", /* tp_name */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001783 sizeof(dequeiterobject), /* tp_basicsize */
1784 0, /* tp_itemsize */
1785 /* methods */
1786 (destructor)dequeiter_dealloc, /* tp_dealloc */
1787 0, /* tp_print */
1788 0, /* tp_getattr */
1789 0, /* tp_setattr */
1790 0, /* tp_reserved */
1791 0, /* tp_repr */
1792 0, /* tp_as_number */
1793 0, /* tp_as_sequence */
1794 0, /* tp_as_mapping */
1795 0, /* tp_hash */
1796 0, /* tp_call */
1797 0, /* tp_str */
1798 PyObject_GenericGetAttr, /* tp_getattro */
1799 0, /* tp_setattro */
1800 0, /* tp_as_buffer */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001801 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001802 0, /* tp_doc */
1803 (traverseproc)dequeiter_traverse, /* tp_traverse */
1804 0, /* tp_clear */
1805 0, /* tp_richcompare */
1806 0, /* tp_weaklistoffset */
1807 PyObject_SelfIter, /* tp_iter */
1808 (iternextfunc)dequeiter_next, /* tp_iternext */
1809 dequeiter_methods, /* tp_methods */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001810 0, /* tp_members */
1811 0, /* tp_getset */
1812 0, /* tp_base */
1813 0, /* tp_dict */
1814 0, /* tp_descr_get */
1815 0, /* tp_descr_set */
1816 0, /* tp_dictoffset */
1817 0, /* tp_init */
1818 0, /* tp_alloc */
1819 dequeiter_new, /* tp_new */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001820 0,
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001821};
1822
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001823/*********************** Deque Reverse Iterator **************************/
1824
Martin v. Löwis59683e82008-06-13 07:50:45 +00001825static PyTypeObject dequereviter_type;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001826
1827static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301828deque_reviter(dequeobject *deque, PyObject *Py_UNUSED(ignored))
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001829{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001830 dequeiterobject *it;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001831
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001832 it = PyObject_GC_New(dequeiterobject, &dequereviter_type);
1833 if (it == NULL)
1834 return NULL;
1835 it->b = deque->rightblock;
1836 it->index = deque->rightindex;
1837 Py_INCREF(deque);
1838 it->deque = deque;
1839 it->state = deque->state;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001840 it->counter = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001841 PyObject_GC_Track(it);
1842 return (PyObject *)it;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001843}
1844
1845static PyObject *
1846dequereviter_next(dequeiterobject *it)
1847{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001848 PyObject *item;
1849 if (it->counter == 0)
1850 return NULL;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001851
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001852 if (it->deque->state != it->state) {
1853 it->counter = 0;
1854 PyErr_SetString(PyExc_RuntimeError,
1855 "deque mutated during iteration");
1856 return NULL;
1857 }
1858 assert (!(it->b == it->deque->leftblock &&
1859 it->index < it->deque->leftindex));
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001860
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001861 item = it->b->data[it->index];
1862 it->index--;
1863 it->counter--;
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -07001864 if (it->index < 0 && it->counter > 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -10001865 CHECK_NOT_END(it->b->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001866 it->b = it->b->leftlink;
1867 it->index = BLOCKLEN - 1;
1868 }
1869 Py_INCREF(item);
1870 return item;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001871}
1872
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001873static PyObject *
1874dequereviter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1875{
1876 Py_ssize_t i, index=0;
1877 PyObject *deque;
1878 dequeiterobject *it;
1879 if (!PyArg_ParseTuple(args, "O!|n", &deque_type, &deque, &index))
1880 return NULL;
1881 assert(type == &dequereviter_type);
1882
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301883 it = (dequeiterobject*)deque_reviter((dequeobject *)deque, NULL);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001884 if (!it)
1885 return NULL;
1886 /* consume items from the queue */
1887 for(i=0; i<index; i++) {
1888 PyObject *item = dequereviter_next(it);
1889 if (item) {
1890 Py_DECREF(item);
1891 } else {
1892 if (it->counter) {
1893 Py_DECREF(it);
1894 return NULL;
1895 } else
1896 break;
1897 }
1898 }
1899 return (PyObject*)it;
1900}
1901
Martin v. Löwis59683e82008-06-13 07:50:45 +00001902static PyTypeObject dequereviter_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001903 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger87e69122015-03-02 23:32:02 -08001904 "_collections._deque_reverse_iterator", /* tp_name */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001905 sizeof(dequeiterobject), /* tp_basicsize */
1906 0, /* tp_itemsize */
1907 /* methods */
1908 (destructor)dequeiter_dealloc, /* tp_dealloc */
1909 0, /* tp_print */
1910 0, /* tp_getattr */
1911 0, /* tp_setattr */
1912 0, /* tp_reserved */
1913 0, /* tp_repr */
1914 0, /* tp_as_number */
1915 0, /* tp_as_sequence */
1916 0, /* tp_as_mapping */
1917 0, /* tp_hash */
1918 0, /* tp_call */
1919 0, /* tp_str */
1920 PyObject_GenericGetAttr, /* tp_getattro */
1921 0, /* tp_setattro */
1922 0, /* tp_as_buffer */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001923 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001924 0, /* tp_doc */
1925 (traverseproc)dequeiter_traverse, /* tp_traverse */
1926 0, /* tp_clear */
1927 0, /* tp_richcompare */
1928 0, /* tp_weaklistoffset */
1929 PyObject_SelfIter, /* tp_iter */
1930 (iternextfunc)dequereviter_next, /* tp_iternext */
1931 dequeiter_methods, /* tp_methods */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001932 0, /* tp_members */
1933 0, /* tp_getset */
1934 0, /* tp_base */
1935 0, /* tp_dict */
1936 0, /* tp_descr_get */
1937 0, /* tp_descr_set */
1938 0, /* tp_dictoffset */
1939 0, /* tp_init */
1940 0, /* tp_alloc */
1941 dequereviter_new, /* tp_new */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001942 0,
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001943};
1944
Guido van Rossum1968ad32006-02-25 22:38:04 +00001945/* defaultdict type *********************************************************/
1946
1947typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001948 PyDictObject dict;
1949 PyObject *default_factory;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001950} defdictobject;
1951
1952static PyTypeObject defdict_type; /* Forward */
1953
1954PyDoc_STRVAR(defdict_missing_doc,
1955"__missing__(key) # Called by __getitem__ for missing key; pseudo-code:\n\
Guido van Rossumd8faa362007-04-27 19:54:29 +00001956 if self.default_factory is None: raise KeyError((key,))\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00001957 self[key] = value = self.default_factory()\n\
1958 return value\n\
1959");
1960
1961static PyObject *
1962defdict_missing(defdictobject *dd, PyObject *key)
1963{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001964 PyObject *factory = dd->default_factory;
1965 PyObject *value;
1966 if (factory == NULL || factory == Py_None) {
1967 /* XXX Call dict.__missing__(key) */
1968 PyObject *tup;
1969 tup = PyTuple_Pack(1, key);
1970 if (!tup) return NULL;
1971 PyErr_SetObject(PyExc_KeyError, tup);
1972 Py_DECREF(tup);
1973 return NULL;
1974 }
1975 value = PyEval_CallObject(factory, NULL);
1976 if (value == NULL)
1977 return value;
1978 if (PyObject_SetItem((PyObject *)dd, key, value) < 0) {
1979 Py_DECREF(value);
1980 return NULL;
1981 }
1982 return value;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001983}
1984
1985PyDoc_STRVAR(defdict_copy_doc, "D.copy() -> a shallow copy of D.");
1986
1987static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301988defdict_copy(defdictobject *dd, PyObject *Py_UNUSED(ignored))
Guido van Rossum1968ad32006-02-25 22:38:04 +00001989{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001990 /* This calls the object's class. That only works for subclasses
1991 whose class constructor has the same signature. Subclasses that
1992 define a different constructor signature must override copy().
1993 */
Raymond Hettinger54628fa2009-08-04 19:16:39 +00001994
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001995 if (dd->default_factory == NULL)
1996 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd), Py_None, dd, NULL);
1997 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd),
1998 dd->default_factory, dd, NULL);
Guido van Rossum1968ad32006-02-25 22:38:04 +00001999}
2000
2001static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302002defdict_reduce(defdictobject *dd, PyObject *Py_UNUSED(ignored))
Guido van Rossum1968ad32006-02-25 22:38:04 +00002003{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002004 /* __reduce__ must return a 5-tuple as follows:
Guido van Rossum1968ad32006-02-25 22:38:04 +00002005
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002006 - factory function
2007 - tuple of args for the factory function
2008 - additional state (here None)
2009 - sequence iterator (here None)
2010 - dictionary iterator (yielding successive (key, value) pairs
Guido van Rossum1968ad32006-02-25 22:38:04 +00002011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002012 This API is used by pickle.py and copy.py.
Guido van Rossum1968ad32006-02-25 22:38:04 +00002013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002014 For this to be useful with pickle.py, the default_factory
2015 must be picklable; e.g., None, a built-in, or a global
2016 function in a module or package.
Guido van Rossum1968ad32006-02-25 22:38:04 +00002017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002018 Both shallow and deep copying are supported, but for deep
2019 copying, the default_factory must be deep-copyable; e.g. None,
2020 or a built-in (functions are not copyable at this time).
Guido van Rossum1968ad32006-02-25 22:38:04 +00002021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002022 This only works for subclasses as long as their constructor
2023 signature is compatible; the first argument must be the
2024 optional default_factory, defaulting to None.
2025 */
2026 PyObject *args;
2027 PyObject *items;
2028 PyObject *iter;
2029 PyObject *result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002030 _Py_IDENTIFIER(items);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002031
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002032 if (dd->default_factory == NULL || dd->default_factory == Py_None)
2033 args = PyTuple_New(0);
2034 else
2035 args = PyTuple_Pack(1, dd->default_factory);
2036 if (args == NULL)
2037 return NULL;
Victor Stinnerad8c83a2016-09-05 17:53:15 -07002038 items = _PyObject_CallMethodId((PyObject *)dd, &PyId_items, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002039 if (items == NULL) {
2040 Py_DECREF(args);
2041 return NULL;
2042 }
2043 iter = PyObject_GetIter(items);
2044 if (iter == NULL) {
2045 Py_DECREF(items);
2046 Py_DECREF(args);
2047 return NULL;
2048 }
2049 result = PyTuple_Pack(5, Py_TYPE(dd), args,
2050 Py_None, Py_None, iter);
2051 Py_DECREF(iter);
2052 Py_DECREF(items);
2053 Py_DECREF(args);
2054 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00002055}
2056
2057static PyMethodDef defdict_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002058 {"__missing__", (PyCFunction)defdict_missing, METH_O,
2059 defdict_missing_doc},
2060 {"copy", (PyCFunction)defdict_copy, METH_NOARGS,
2061 defdict_copy_doc},
2062 {"__copy__", (PyCFunction)defdict_copy, METH_NOARGS,
2063 defdict_copy_doc},
2064 {"__reduce__", (PyCFunction)defdict_reduce, METH_NOARGS,
2065 reduce_doc},
2066 {NULL}
Guido van Rossum1968ad32006-02-25 22:38:04 +00002067};
2068
2069static PyMemberDef defdict_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002070 {"default_factory", T_OBJECT,
2071 offsetof(defdictobject, default_factory), 0,
2072 PyDoc_STR("Factory for default value called by __missing__().")},
2073 {NULL}
Guido van Rossum1968ad32006-02-25 22:38:04 +00002074};
2075
2076static void
2077defdict_dealloc(defdictobject *dd)
2078{
INADA Naokia6296d32017-08-24 14:55:17 +09002079 /* bpo-31095: UnTrack is needed before calling any callbacks */
2080 PyObject_GC_UnTrack(dd);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002081 Py_CLEAR(dd->default_factory);
2082 PyDict_Type.tp_dealloc((PyObject *)dd);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002083}
2084
Guido van Rossum1968ad32006-02-25 22:38:04 +00002085static PyObject *
2086defdict_repr(defdictobject *dd)
2087{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002088 PyObject *baserepr;
2089 PyObject *defrepr;
2090 PyObject *result;
2091 baserepr = PyDict_Type.tp_repr((PyObject *)dd);
2092 if (baserepr == NULL)
2093 return NULL;
2094 if (dd->default_factory == NULL)
2095 defrepr = PyUnicode_FromString("None");
2096 else
2097 {
2098 int status = Py_ReprEnter(dd->default_factory);
2099 if (status != 0) {
Antoine Pitrouf5f1fe02012-02-15 02:42:46 +01002100 if (status < 0) {
2101 Py_DECREF(baserepr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002102 return NULL;
Antoine Pitrouf5f1fe02012-02-15 02:42:46 +01002103 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002104 defrepr = PyUnicode_FromString("...");
2105 }
2106 else
2107 defrepr = PyObject_Repr(dd->default_factory);
2108 Py_ReprLeave(dd->default_factory);
2109 }
2110 if (defrepr == NULL) {
2111 Py_DECREF(baserepr);
2112 return NULL;
2113 }
Serhiy Storchakab3a77962017-09-21 14:24:13 +03002114 result = PyUnicode_FromFormat("%s(%U, %U)",
2115 _PyType_Name(Py_TYPE(dd)),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002116 defrepr, baserepr);
2117 Py_DECREF(defrepr);
2118 Py_DECREF(baserepr);
2119 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00002120}
2121
2122static int
2123defdict_traverse(PyObject *self, visitproc visit, void *arg)
2124{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002125 Py_VISIT(((defdictobject *)self)->default_factory);
2126 return PyDict_Type.tp_traverse(self, visit, arg);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002127}
2128
2129static int
2130defdict_tp_clear(defdictobject *dd)
2131{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002132 Py_CLEAR(dd->default_factory);
2133 return PyDict_Type.tp_clear((PyObject *)dd);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002134}
2135
2136static int
2137defdict_init(PyObject *self, PyObject *args, PyObject *kwds)
2138{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002139 defdictobject *dd = (defdictobject *)self;
2140 PyObject *olddefault = dd->default_factory;
2141 PyObject *newdefault = NULL;
2142 PyObject *newargs;
2143 int result;
2144 if (args == NULL || !PyTuple_Check(args))
2145 newargs = PyTuple_New(0);
2146 else {
2147 Py_ssize_t n = PyTuple_GET_SIZE(args);
2148 if (n > 0) {
2149 newdefault = PyTuple_GET_ITEM(args, 0);
2150 if (!PyCallable_Check(newdefault) && newdefault != Py_None) {
2151 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger239aba72015-07-20 03:09:22 -04002152 "first argument must be callable or None");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002153 return -1;
2154 }
2155 }
2156 newargs = PySequence_GetSlice(args, 1, n);
2157 }
2158 if (newargs == NULL)
2159 return -1;
2160 Py_XINCREF(newdefault);
2161 dd->default_factory = newdefault;
2162 result = PyDict_Type.tp_init(self, newargs, kwds);
2163 Py_DECREF(newargs);
2164 Py_XDECREF(olddefault);
2165 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00002166}
2167
2168PyDoc_STRVAR(defdict_doc,
Benjamin Peterson9cb33b72014-01-13 23:56:05 -05002169"defaultdict(default_factory[, ...]) --> dict with default factory\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00002170\n\
2171The default factory is called without arguments to produce\n\
2172a new value when a key is not present, in __getitem__ only.\n\
2173A defaultdict compares equal to a dict with the same items.\n\
Benjamin Peterson9cb33b72014-01-13 23:56:05 -05002174All remaining arguments are treated the same as if they were\n\
2175passed to the dict constructor, including keyword arguments.\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00002176");
2177
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002178/* See comment in xxsubtype.c */
2179#define DEFERRED_ADDRESS(ADDR) 0
2180
Guido van Rossum1968ad32006-02-25 22:38:04 +00002181static PyTypeObject defdict_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002182 PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0)
2183 "collections.defaultdict", /* tp_name */
2184 sizeof(defdictobject), /* tp_basicsize */
2185 0, /* tp_itemsize */
2186 /* methods */
2187 (destructor)defdict_dealloc, /* tp_dealloc */
2188 0, /* tp_print */
2189 0, /* tp_getattr */
2190 0, /* tp_setattr */
2191 0, /* tp_reserved */
2192 (reprfunc)defdict_repr, /* tp_repr */
2193 0, /* tp_as_number */
2194 0, /* tp_as_sequence */
2195 0, /* tp_as_mapping */
2196 0, /* tp_hash */
2197 0, /* tp_call */
2198 0, /* tp_str */
2199 PyObject_GenericGetAttr, /* tp_getattro */
2200 0, /* tp_setattro */
2201 0, /* tp_as_buffer */
2202 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
2203 /* tp_flags */
2204 defdict_doc, /* tp_doc */
2205 defdict_traverse, /* tp_traverse */
2206 (inquiry)defdict_tp_clear, /* tp_clear */
2207 0, /* tp_richcompare */
2208 0, /* tp_weaklistoffset*/
2209 0, /* tp_iter */
2210 0, /* tp_iternext */
2211 defdict_methods, /* tp_methods */
2212 defdict_members, /* tp_members */
2213 0, /* tp_getset */
2214 DEFERRED_ADDRESS(&PyDict_Type), /* tp_base */
2215 0, /* tp_dict */
2216 0, /* tp_descr_get */
2217 0, /* tp_descr_set */
2218 0, /* tp_dictoffset */
2219 defdict_init, /* tp_init */
2220 PyType_GenericAlloc, /* tp_alloc */
2221 0, /* tp_new */
2222 PyObject_GC_Del, /* tp_free */
Guido van Rossum1968ad32006-02-25 22:38:04 +00002223};
2224
Raymond Hettinger96f34102010-12-15 16:30:37 +00002225/* helper function for Counter *********************************************/
2226
2227PyDoc_STRVAR(_count_elements_doc,
2228"_count_elements(mapping, iterable) -> None\n\
2229\n\
Raymond Hettingera24dca62017-01-12 22:25:25 -08002230Count elements in the iterable, updating the mapping");
Raymond Hettinger96f34102010-12-15 16:30:37 +00002231
2232static PyObject *
2233_count_elements(PyObject *self, PyObject *args)
2234{
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002235 _Py_IDENTIFIER(get);
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002236 _Py_IDENTIFIER(__setitem__);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002237 PyObject *it, *iterable, *mapping, *oldval;
2238 PyObject *newval = NULL;
2239 PyObject *key = NULL;
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002240 PyObject *bound_get = NULL;
2241 PyObject *mapping_get;
2242 PyObject *dict_get;
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002243 PyObject *mapping_setitem;
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002244 PyObject *dict_setitem;
Raymond Hettinger96f34102010-12-15 16:30:37 +00002245
2246 if (!PyArg_UnpackTuple(args, "_count_elements", 2, 2, &mapping, &iterable))
2247 return NULL;
2248
Raymond Hettinger96f34102010-12-15 16:30:37 +00002249 it = PyObject_GetIter(iterable);
2250 if (it == NULL)
2251 return NULL;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002252
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002253 /* Only take the fast path when get() and __setitem__()
2254 * have not been overridden.
2255 */
2256 mapping_get = _PyType_LookupId(Py_TYPE(mapping), &PyId_get);
2257 dict_get = _PyType_LookupId(&PyDict_Type, &PyId_get);
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002258 mapping_setitem = _PyType_LookupId(Py_TYPE(mapping), &PyId___setitem__);
2259 dict_setitem = _PyType_LookupId(&PyDict_Type, &PyId___setitem__);
2260
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002261 if (mapping_get != NULL && mapping_get == dict_get &&
Oren Milman31aca4b2017-09-27 06:18:21 +03002262 mapping_setitem != NULL && mapping_setitem == dict_setitem &&
2263 PyDict_Check(mapping))
2264 {
Raymond Hettinger426e0522011-01-03 02:12:02 +00002265 while (1) {
Raymond Hettinger507d9972014-05-18 21:32:40 +01002266 /* Fast path advantages:
2267 1. Eliminate double hashing
2268 (by re-using the same hash for both the get and set)
2269 2. Avoid argument overhead of PyObject_CallFunctionObjArgs
2270 (argument tuple creation and parsing)
2271 3. Avoid indirection through a bound method object
2272 (creates another argument tuple)
2273 4. Avoid initial increment from zero
2274 (reuse an existing one-object instead)
2275 */
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002276 Py_hash_t hash;
2277
Raymond Hettinger426e0522011-01-03 02:12:02 +00002278 key = PyIter_Next(it);
Victor Stinnera154b5c2011-04-20 23:23:52 +02002279 if (key == NULL)
2280 break;
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002281
2282 if (!PyUnicode_CheckExact(key) ||
2283 (hash = ((PyASCIIObject *) key)->hash) == -1)
2284 {
2285 hash = PyObject_Hash(key);
Raymond Hettingerda2850f2015-02-27 12:42:54 -08002286 if (hash == -1)
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002287 goto done;
2288 }
2289
2290 oldval = _PyDict_GetItem_KnownHash(mapping, key, hash);
Raymond Hettinger426e0522011-01-03 02:12:02 +00002291 if (oldval == NULL) {
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02002292 if (PyErr_Occurred())
2293 goto done;
Serhiy Storchakaba85d692017-03-30 09:09:41 +03002294 if (_PyDict_SetItem_KnownHash(mapping, key, _PyLong_One, hash) < 0)
Raymond Hettinger507d9972014-05-18 21:32:40 +01002295 goto done;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002296 } else {
Serhiy Storchakaba85d692017-03-30 09:09:41 +03002297 newval = PyNumber_Add(oldval, _PyLong_One);
Raymond Hettinger426e0522011-01-03 02:12:02 +00002298 if (newval == NULL)
Raymond Hettinger507d9972014-05-18 21:32:40 +01002299 goto done;
Raymond Hettinger28c995d2015-08-14 02:07:41 -07002300 if (_PyDict_SetItem_KnownHash(mapping, key, newval, hash) < 0)
Raymond Hettinger507d9972014-05-18 21:32:40 +01002301 goto done;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002302 Py_CLEAR(newval);
2303 }
2304 Py_DECREF(key);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002305 }
Raymond Hettinger426e0522011-01-03 02:12:02 +00002306 } else {
Victor Stinnere7f516c2013-11-06 23:52:55 +01002307 bound_get = _PyObject_GetAttrId(mapping, &PyId_get);
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002308 if (bound_get == NULL)
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002309 goto done;
2310
Raymond Hettinger426e0522011-01-03 02:12:02 +00002311 while (1) {
2312 key = PyIter_Next(it);
Victor Stinnera154b5c2011-04-20 23:23:52 +02002313 if (key == NULL)
2314 break;
Serhiy Storchakaba85d692017-03-30 09:09:41 +03002315 oldval = PyObject_CallFunctionObjArgs(bound_get, key, _PyLong_Zero, NULL);
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002316 if (oldval == NULL)
2317 break;
Serhiy Storchakaba85d692017-03-30 09:09:41 +03002318 newval = PyNumber_Add(oldval, _PyLong_One);
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002319 Py_DECREF(oldval);
2320 if (newval == NULL)
2321 break;
Raymond Hettinger28c995d2015-08-14 02:07:41 -07002322 if (PyObject_SetItem(mapping, key, newval) < 0)
Raymond Hettinger96f34102010-12-15 16:30:37 +00002323 break;
2324 Py_CLEAR(newval);
Raymond Hettinger426e0522011-01-03 02:12:02 +00002325 Py_DECREF(key);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002326 }
Raymond Hettinger96f34102010-12-15 16:30:37 +00002327 }
Raymond Hettinger426e0522011-01-03 02:12:02 +00002328
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002329done:
Raymond Hettinger96f34102010-12-15 16:30:37 +00002330 Py_DECREF(it);
2331 Py_XDECREF(key);
2332 Py_XDECREF(newval);
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002333 Py_XDECREF(bound_get);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002334 if (PyErr_Occurred())
2335 return NULL;
2336 Py_RETURN_NONE;
2337}
2338
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002339/* Helper functions for namedtuples */
2340
2341typedef struct {
2342 PyObject_HEAD
2343 Py_ssize_t index;
2344 PyObject* doc;
2345} _tuplegetterobject;
2346
2347/*[clinic input]
2348@classmethod
2349_tuplegetter.__new__ as tuplegetter_new
2350
2351 index: Py_ssize_t
2352 doc: object
2353 /
2354[clinic start generated code]*/
2355
2356static PyObject *
2357tuplegetter_new_impl(PyTypeObject *type, Py_ssize_t index, PyObject *doc)
2358/*[clinic end generated code: output=014be444ad80263f input=87c576a5bdbc0bbb]*/
2359{
2360 _tuplegetterobject* self;
2361 self = (_tuplegetterobject *)type->tp_alloc(type, 0);
2362 if (self == NULL) {
2363 return NULL;
2364 }
2365 self->index = index;
2366 Py_INCREF(doc);
2367 self->doc = doc;
2368 return (PyObject *)self;
2369}
2370
2371static PyObject *
2372tuplegetterdescr_get(PyObject *self, PyObject *obj, PyObject *type)
2373{
2374 PyObject *result;
2375 if (obj == NULL) {
2376 Py_INCREF(self);
2377 return self;
2378 }
2379 if (!PyTuple_Check(obj)) {
2380 if (obj == Py_None) {
2381 Py_INCREF(self);
2382 return self;
2383 }
2384 PyErr_Format(PyExc_TypeError,
2385 "descriptor for index '%d' for tuple subclasses "
2386 "doesn't apply to '%s' object",
2387 ((_tuplegetterobject*)self)->index,
2388 obj->ob_type->tp_name);
2389 return NULL;
2390 }
2391
2392 Py_ssize_t index = ((_tuplegetterobject*)self)->index;
2393
2394 if (!valid_index(index, PyTuple_GET_SIZE(obj))) {
2395 PyErr_SetString(PyExc_IndexError, "tuple index out of range");
2396 return NULL;
2397 }
2398
2399 result = PyTuple_GET_ITEM(obj, index);
2400 Py_INCREF(result);
2401 return result;
2402}
2403
2404static int
2405tuplegetter_set(PyObject *self, PyObject *obj, PyObject *value)
2406{
2407 if (value == NULL) {
2408 PyErr_SetString(PyExc_AttributeError, "can't delete attribute");
2409 } else {
2410 PyErr_SetString(PyExc_AttributeError, "can't set attribute");
2411 }
2412 return -1;
2413}
2414
2415static int
2416tuplegetter_traverse(PyObject *self, visitproc visit, void *arg)
2417{
2418 _tuplegetterobject *tuplegetter = (_tuplegetterobject *)self;
2419 Py_VISIT(tuplegetter->doc);
2420 return 0;
2421}
2422
2423static int
2424tuplegetter_clear(PyObject *self)
2425{
2426 _tuplegetterobject *tuplegetter = (_tuplegetterobject *)self;
2427 Py_CLEAR(tuplegetter->doc);
2428 return 0;
2429}
2430
2431static void
2432tuplegetter_dealloc(_tuplegetterobject *self)
2433{
2434 PyObject_GC_UnTrack(self);
2435 tuplegetter_clear((PyObject*)self);
2436 Py_TYPE(self)->tp_free((PyObject*)self);
2437}
2438
2439
2440static PyMemberDef tuplegetter_members[] = {
2441 {"__doc__", T_OBJECT, offsetof(_tuplegetterobject, doc), 0},
2442 {0}
2443};
2444
2445static PyTypeObject tuplegetter_type = {
2446 PyVarObject_HEAD_INIT(NULL, 0)
2447 "_collections._tuplegetter", /* tp_name */
2448 sizeof(_tuplegetterobject), /* tp_basicsize */
2449 0, /* tp_itemsize */
2450 /* methods */
2451 (destructor)tuplegetter_dealloc, /* tp_dealloc */
2452 0, /* tp_print */
2453 0, /* tp_getattr */
2454 0, /* tp_setattr */
2455 0, /* tp_reserved */
2456 0, /* tp_repr */
2457 0, /* tp_as_number */
2458 0, /* tp_as_sequence */
2459 0, /* tp_as_mapping */
2460 0, /* tp_hash */
2461 0, /* tp_call */
2462 0, /* tp_str */
2463 0, /* tp_getattro */
2464 0, /* tp_setattro */
2465 0, /* tp_as_buffer */
2466 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
2467 0, /* tp_doc */
2468 (traverseproc)tuplegetter_traverse, /* tp_traverse */
2469 (inquiry)tuplegetter_clear, /* tp_clear */
2470 0, /* tp_richcompare */
2471 0, /* tp_weaklistoffset */
2472 0, /* tp_iter */
2473 0, /* tp_iternext */
2474 0, /* tp_methods */
2475 tuplegetter_members, /* tp_members */
2476 0, /* tp_getset */
2477 0, /* tp_base */
2478 0, /* tp_dict */
2479 tuplegetterdescr_get, /* tp_descr_get */
2480 tuplegetter_set, /* tp_descr_set */
2481 0, /* tp_dictoffset */
2482 0, /* tp_init */
2483 0, /* tp_alloc */
2484 tuplegetter_new, /* tp_new */
2485 0,
2486};
2487
2488
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002489/* module level code ********************************************************/
2490
2491PyDoc_STRVAR(module_doc,
Guido van Rossum1968ad32006-02-25 22:38:04 +00002492"High performance data structures.\n\
2493- deque: ordered collection accessible from endpoints only\n\
2494- defaultdict: dict subclass with a default value factory\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002495");
2496
Raymond Hettinger96f34102010-12-15 16:30:37 +00002497static struct PyMethodDef module_functions[] = {
2498 {"_count_elements", _count_elements, METH_VARARGS, _count_elements_doc},
2499 {NULL, NULL} /* sentinel */
2500};
Martin v. Löwis1a214512008-06-11 05:26:20 +00002501
2502static struct PyModuleDef _collectionsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002503 PyModuleDef_HEAD_INIT,
2504 "_collections",
2505 module_doc,
2506 -1,
Raymond Hettinger96f34102010-12-15 16:30:37 +00002507 module_functions,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002508 NULL,
2509 NULL,
2510 NULL,
2511 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002512};
2513
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002514PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002515PyInit__collections(void)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002516{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002517 PyObject *m;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002519 m = PyModule_Create(&_collectionsmodule);
2520 if (m == NULL)
2521 return NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002523 if (PyType_Ready(&deque_type) < 0)
2524 return NULL;
2525 Py_INCREF(&deque_type);
2526 PyModule_AddObject(m, "deque", (PyObject *)&deque_type);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002528 defdict_type.tp_base = &PyDict_Type;
2529 if (PyType_Ready(&defdict_type) < 0)
2530 return NULL;
2531 Py_INCREF(&defdict_type);
2532 PyModule_AddObject(m, "defaultdict", (PyObject *)&defdict_type);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002533
Eric Snow47db7172015-05-29 22:21:39 -06002534 Py_INCREF(&PyODict_Type);
2535 PyModule_AddObject(m, "OrderedDict", (PyObject *)&PyODict_Type);
2536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002537 if (PyType_Ready(&dequeiter_type) < 0)
2538 return NULL;
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002539 Py_INCREF(&dequeiter_type);
2540 PyModule_AddObject(m, "_deque_iterator", (PyObject *)&dequeiter_type);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002542 if (PyType_Ready(&dequereviter_type) < 0)
2543 return NULL;
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002544 Py_INCREF(&dequereviter_type);
2545 PyModule_AddObject(m, "_deque_reverse_iterator", (PyObject *)&dequereviter_type);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00002546
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002547 if (PyType_Ready(&tuplegetter_type) < 0)
2548 return NULL;
2549 Py_INCREF(&tuplegetter_type);
2550 PyModule_AddObject(m, "_tuplegetter", (PyObject *)&tuplegetter_type);
2551
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002552 return m;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002553}