blob: 7120e4dda0ed236cd99c420e4d483aa40b6b8d9a [file] [log] [blame]
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001#include "Python.h"
Victor Stinner4a21e572020-04-15 02:35:41 +02002#include "structmember.h" // PyMemberDef
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
Victor Stinner4a21e572020-04-15 02:35:41 +02007#include <sys/types.h> // size_t
Raymond Hettingerc2083082015-02-28 23:29:16 -08008#endif
9
Pablo Galindo3f5fc702018-12-30 09:24:03 +000010/*[clinic input]
Raymond Hettingere9858042019-06-05 16:05:25 -070011module _collections
Pablo Galindo3f5fc702018-12-30 09:24:03 +000012class _tuplegetter "_tuplegetterobject *" "&tuplegetter_type"
13[clinic start generated code]*/
Raymond Hettingere9858042019-06-05 16:05:25 -070014/*[clinic end generated code: output=da39a3ee5e6b4b0d input=a8ece4ccad7e30ac]*/
Pablo Galindo3f5fc702018-12-30 09:24:03 +000015
16static PyTypeObject tuplegetter_type;
17#include "clinic/_collectionsmodule.c.h"
18
Raymond Hettinger756b3f32004-01-29 06:37:52 +000019/* collections module implementation of a deque() datatype
20 Written and maintained by Raymond D. Hettinger <python@rcn.com>
Raymond Hettinger756b3f32004-01-29 06:37:52 +000021*/
22
Raymond Hettinger77e8bf12004-10-01 15:25:53 +000023/* The block length may be set to any number over 1. Larger numbers
Raymond Hettinger20b0f872013-06-23 15:44:33 -070024 * reduce the number of calls to the memory allocator, give faster
Raymond Hettinger30c90742015-03-02 22:31:35 -080025 * indexing and rotation, and reduce the link to data overhead ratio.
Raymond Hettingerdaf57f22015-02-26 23:21:29 -080026 * Making the block length a power of two speeds-up the modulo
Raymond Hettinger30c90742015-03-02 22:31:35 -080027 * and division calculations in deque_item() and deque_ass_item().
Raymond Hettinger77e8bf12004-10-01 15:25:53 +000028 */
29
Raymond Hettingerdaf57f22015-02-26 23:21:29 -080030#define BLOCKLEN 64
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000031#define CENTER ((BLOCKLEN - 1) / 2)
Raymond Hettinger756b3f32004-01-29 06:37:52 +000032
Raymond Hettinger551350a2015-03-24 00:19:53 -070033/* Data for deque objects is stored in a doubly-linked list of fixed
34 * length blocks. This assures that appends or pops never move any
35 * other data elements besides the one being appended or popped.
36 *
37 * Another advantage is that it completely avoids use of realloc(),
38 * resulting in more predictable performance.
39 *
40 * Textbook implementations of doubly-linked lists store one datum
41 * per link, but that gives them a 200% memory overhead (a prev and
42 * next link for each datum) and it costs one malloc() call per data
43 * element. By using fixed-length blocks, the link to data ratio is
44 * significantly improved and there are proportionally fewer calls
45 * to malloc() and free(). The data blocks of consecutive pointers
46 * also improve cache locality.
47 *
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000048 * The list of blocks is never empty, so d.leftblock and d.rightblock
Raymond Hettinger82df9252013-07-07 01:43:42 -100049 * are never equal to NULL. The list is not circular.
50 *
51 * A deque d's first element is at d.leftblock[leftindex]
52 * and its last element is at d.rightblock[rightindex].
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000053 *
Raymond Hettinger551350a2015-03-24 00:19:53 -070054 * Unlike Python slice indices, these indices are inclusive on both
55 * ends. This makes the algorithms for left and right operations
56 * more symmetrical and it simplifies the design.
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000057 *
Raymond Hettinger551350a2015-03-24 00:19:53 -070058 * The indices, d.leftindex and d.rightindex are always in the range:
59 * 0 <= index < BLOCKLEN
60 *
61 * And their exact relationship is:
62 * (d.leftindex + d.len - 1) % BLOCKLEN == d.rightindex
Raymond Hettinger61f05fb2004-10-01 06:24:12 +000063 *
Raymond Hettinger8dbbae22015-03-24 21:01:50 -070064 * Whenever d.leftblock == d.rightblock, then:
Raymond Hettinger551350a2015-03-24 00:19:53 -070065 * d.leftindex + d.len - 1 == d.rightindex
Thomas Wouters0e3f5912006-08-11 14:57:12 +000066 *
Raymond Hettinger551350a2015-03-24 00:19:53 -070067 * However, when d.leftblock != d.rightblock, the d.leftindex and
68 * d.rightindex become indices into distinct blocks and either may
69 * be larger than the other.
70 *
71 * Empty deques have:
72 * d.len == 0
73 * d.leftblock == d.rightblock
74 * d.leftindex == CENTER + 1
75 * d.rightindex == CENTER
76 *
77 * Checking for d.len == 0 is the intended way to see whether d is empty.
Tim Petersd8768d32004-10-01 01:32:53 +000078 */
79
Raymond Hettinger756b3f32004-01-29 06:37:52 +000080typedef struct BLOCK {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000081 struct BLOCK *leftlink;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000082 PyObject *data[BLOCKLEN];
Raymond Hettinger20b0f872013-06-23 15:44:33 -070083 struct BLOCK *rightlink;
Raymond Hettinger756b3f32004-01-29 06:37:52 +000084} block;
85
Raymond Hettinger30c90742015-03-02 22:31:35 -080086typedef struct {
87 PyObject_VAR_HEAD
88 block *leftblock;
89 block *rightblock;
Raymond Hettinger551350a2015-03-24 00:19:53 -070090 Py_ssize_t leftindex; /* 0 <= leftindex < BLOCKLEN */
91 Py_ssize_t rightindex; /* 0 <= rightindex < BLOCKLEN */
Raymond Hettingerf9d9c792015-03-02 22:47:46 -080092 size_t state; /* incremented whenever the indices move */
Raymond Hettingerd84ec222016-01-24 09:12:06 -080093 Py_ssize_t maxlen; /* maxlen is -1 for unbounded deques */
Raymond Hettinger0f6f9472015-03-21 01:42:10 -070094 PyObject *weakreflist;
Raymond Hettinger30c90742015-03-02 22:31:35 -080095} dequeobject;
96
97static PyTypeObject deque_type;
98
Raymond Hettinger82df9252013-07-07 01:43:42 -100099/* For debug builds, add error checking to track the endpoints
100 * in the chain of links. The goal is to make sure that link
101 * assignments only take place at endpoints so that links already
102 * in use do not get overwritten.
103 *
104 * CHECK_END should happen before each assignment to a block's link field.
105 * MARK_END should happen whenever a link field becomes a new endpoint.
106 * This happens when new blocks are added or whenever an existing
107 * block is freed leaving another existing block as the new endpoint.
108 */
109
Raymond Hettinger3223dd52013-07-26 23:14:22 -0700110#ifndef NDEBUG
Raymond Hettinger82df9252013-07-07 01:43:42 -1000111#define MARK_END(link) link = NULL;
112#define CHECK_END(link) assert(link == NULL);
113#define CHECK_NOT_END(link) assert(link != NULL);
114#else
115#define MARK_END(link)
116#define CHECK_END(link)
117#define CHECK_NOT_END(link)
118#endif
119
120/* A simple freelisting scheme is used to minimize calls to the memory
Raymond Hettinger551350a2015-03-24 00:19:53 -0700121 allocator. It accommodates common use cases where new blocks are being
Raymond Hettinger82df9252013-07-07 01:43:42 -1000122 added at about the same rate as old blocks are being freed.
123 */
124
Raymond Hettingerf2b02ce2015-09-26 17:47:02 -0700125#define MAXFREEBLOCKS 16
Benjamin Petersond6313712008-07-31 16:23:04 +0000126static Py_ssize_t numfreeblocks = 0;
Guido van Rossum58da9312007-11-10 23:39:45 +0000127static block *freeblocks[MAXFREEBLOCKS];
128
Tim Peters6f853562004-10-01 01:04:50 +0000129static block *
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700130newblock(void) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000131 block *b;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000132 if (numfreeblocks) {
Raymond Hettinger59cf23a2013-02-07 00:57:19 -0500133 numfreeblocks--;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000134 return freeblocks[numfreeblocks];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000135 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000136 b = PyMem_Malloc(sizeof(block));
137 if (b != NULL) {
138 return b;
139 }
140 PyErr_NoMemory();
141 return NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000142}
143
Martin v. Löwis59683e82008-06-13 07:50:45 +0000144static void
Guido van Rossum58da9312007-11-10 23:39:45 +0000145freeblock(block *b)
146{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000147 if (numfreeblocks < MAXFREEBLOCKS) {
148 freeblocks[numfreeblocks] = b;
149 numfreeblocks++;
150 } else {
151 PyMem_Free(b);
152 }
Guido van Rossum58da9312007-11-10 23:39:45 +0000153}
154
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000155static PyObject *
156deque_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
157{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000158 dequeobject *deque;
159 block *b;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000161 /* create dequeobject structure */
162 deque = (dequeobject *)type->tp_alloc(type, 0);
163 if (deque == NULL)
164 return NULL;
Tim Peters1065f752004-10-01 01:03:29 +0000165
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700166 b = newblock();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000167 if (b == NULL) {
168 Py_DECREF(deque);
169 return NULL;
170 }
Raymond Hettinger82df9252013-07-07 01:43:42 -1000171 MARK_END(b->leftlink);
172 MARK_END(b->rightlink);
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000174 assert(BLOCKLEN >= 2);
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100175 Py_SET_SIZE(deque, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000176 deque->leftblock = b;
177 deque->rightblock = b;
178 deque->leftindex = CENTER + 1;
179 deque->rightindex = CENTER;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000180 deque->state = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000181 deque->maxlen = -1;
Raymond Hettinger87e69122015-03-02 23:32:02 -0800182 deque->weakreflist = NULL;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000184 return (PyObject *)deque;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000185}
186
187static PyObject *
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000188deque_pop(dequeobject *deque, PyObject *unused)
189{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000190 PyObject *item;
191 block *prevblock;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000192
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000193 if (Py_SIZE(deque) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000194 PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
195 return NULL;
196 }
197 item = deque->rightblock->data[deque->rightindex];
198 deque->rightindex--;
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100199 Py_SET_SIZE(deque, Py_SIZE(deque) - 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000200 deque->state++;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000201
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -0700202 if (deque->rightindex < 0) {
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700203 if (Py_SIZE(deque)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000204 prevblock = deque->rightblock->leftlink;
205 assert(deque->leftblock != deque->rightblock);
206 freeblock(deque->rightblock);
Raymond Hettinger82df9252013-07-07 01:43:42 -1000207 CHECK_NOT_END(prevblock);
208 MARK_END(prevblock->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000209 deque->rightblock = prevblock;
210 deque->rightindex = BLOCKLEN - 1;
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700211 } else {
212 assert(deque->leftblock == deque->rightblock);
213 assert(deque->leftindex == deque->rightindex+1);
214 /* re-center instead of freeing a block */
215 deque->leftindex = CENTER + 1;
216 deque->rightindex = CENTER;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000217 }
218 }
219 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000220}
221
222PyDoc_STRVAR(pop_doc, "Remove and return the rightmost element.");
223
224static PyObject *
225deque_popleft(dequeobject *deque, PyObject *unused)
226{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000227 PyObject *item;
228 block *prevblock;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000229
Raymond Hettingerdf715ba2013-07-06 13:01:13 -1000230 if (Py_SIZE(deque) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000231 PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
232 return NULL;
233 }
234 assert(deque->leftblock != NULL);
235 item = deque->leftblock->data[deque->leftindex];
236 deque->leftindex++;
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100237 Py_SET_SIZE(deque, Py_SIZE(deque) - 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000238 deque->state++;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000240 if (deque->leftindex == BLOCKLEN) {
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700241 if (Py_SIZE(deque)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000242 assert(deque->leftblock != deque->rightblock);
243 prevblock = deque->leftblock->rightlink;
244 freeblock(deque->leftblock);
Raymond Hettinger82df9252013-07-07 01:43:42 -1000245 CHECK_NOT_END(prevblock);
246 MARK_END(prevblock->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000247 deque->leftblock = prevblock;
248 deque->leftindex = 0;
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700249 } else {
250 assert(deque->leftblock == deque->rightblock);
251 assert(deque->leftindex == deque->rightindex+1);
252 /* re-center instead of freeing a block */
253 deque->leftindex = CENTER + 1;
254 deque->rightindex = CENTER;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000255 }
256 }
257 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000258}
259
260PyDoc_STRVAR(popleft_doc, "Remove and return the leftmost element.");
261
Raymond Hettingerf30f5b92015-03-02 22:23:37 -0800262/* The deque's size limit is d.maxlen. The limit can be zero or positive.
263 * If there is no limit, then d.maxlen == -1.
264 *
Raymond Hettingera4b13d02015-10-15 08:05:31 -0700265 * After an item is added to a deque, we check to see if the size has
266 * grown past the limit. If it has, we get the size back down to the limit
267 * by popping an item off of the opposite end. The methods that can
268 * trigger this are append(), appendleft(), extend(), and extendleft().
Raymond Hettingerd96db092015-10-11 22:34:48 -0700269 *
270 * The macro to check whether a deque needs to be trimmed uses a single
271 * unsigned test that returns true whenever 0 <= maxlen < Py_SIZE(deque).
Raymond Hettingerf30f5b92015-03-02 22:23:37 -0800272 */
273
Raymond Hettingerd96db092015-10-11 22:34:48 -0700274#define NEEDS_TRIM(deque, maxlen) ((size_t)(maxlen) < (size_t)(Py_SIZE(deque)))
Raymond Hettingerf30f5b92015-03-02 22:23:37 -0800275
Raymond Hettinger66953f02018-07-10 04:17:40 -0700276static inline int
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800277deque_append_internal(dequeobject *deque, PyObject *item, Py_ssize_t maxlen)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000278{
Raymond Hettinger8dbbae22015-03-24 21:01:50 -0700279 if (deque->rightindex == BLOCKLEN - 1) {
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700280 block *b = newblock();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000281 if (b == NULL)
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800282 return -1;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000283 b->leftlink = deque->rightblock;
284 CHECK_END(deque->rightblock->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000285 deque->rightblock->rightlink = b;
286 deque->rightblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000287 MARK_END(b->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000288 deque->rightindex = -1;
289 }
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100290 Py_SET_SIZE(deque, Py_SIZE(deque) + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000291 deque->rightindex++;
292 deque->rightblock->data[deque->rightindex] = item;
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800293 if (NEEDS_TRIM(deque, maxlen)) {
Raymond Hettinger1286d142015-10-14 23:16:57 -0700294 PyObject *olditem = deque_popleft(deque, NULL);
295 Py_DECREF(olditem);
Raymond Hettinger0f43bb12015-10-20 00:03:33 -0700296 } else {
297 deque->state++;
Raymond Hettingerd96db092015-10-11 22:34:48 -0700298 }
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800299 return 0;
300}
301
302static PyObject *
303deque_append(dequeobject *deque, PyObject *item)
304{
305 Py_INCREF(item);
306 if (deque_append_internal(deque, item, deque->maxlen) < 0)
307 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000308 Py_RETURN_NONE;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000309}
310
311PyDoc_STRVAR(append_doc, "Add an element to the right side of the deque.");
312
Raymond Hettinger66953f02018-07-10 04:17:40 -0700313static inline int
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800314deque_appendleft_internal(dequeobject *deque, PyObject *item, Py_ssize_t maxlen)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000315{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000316 if (deque->leftindex == 0) {
Raymond Hettingerdb41fd42015-10-22 22:48:16 -0700317 block *b = newblock();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000318 if (b == NULL)
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800319 return -1;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000320 b->rightlink = deque->leftblock;
321 CHECK_END(deque->leftblock->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000322 deque->leftblock->leftlink = b;
323 deque->leftblock = b;
Raymond Hettinger82df9252013-07-07 01:43:42 -1000324 MARK_END(b->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000325 deque->leftindex = BLOCKLEN;
326 }
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100327 Py_SET_SIZE(deque, Py_SIZE(deque) + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000328 deque->leftindex--;
329 deque->leftblock->data[deque->leftindex] = item;
Raymond Hettingerd96db092015-10-11 22:34:48 -0700330 if (NEEDS_TRIM(deque, deque->maxlen)) {
Raymond Hettinger1286d142015-10-14 23:16:57 -0700331 PyObject *olditem = deque_pop(deque, NULL);
332 Py_DECREF(olditem);
Raymond Hettinger0f43bb12015-10-20 00:03:33 -0700333 } else {
334 deque->state++;
Raymond Hettingerd96db092015-10-11 22:34:48 -0700335 }
Raymond Hettingerd84ec222016-01-24 09:12:06 -0800336 return 0;
337}
338
339static PyObject *
340deque_appendleft(dequeobject *deque, PyObject *item)
341{
342 Py_INCREF(item);
343 if (deque_appendleft_internal(deque, item, deque->maxlen) < 0)
344 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000345 Py_RETURN_NONE;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000346}
347
348PyDoc_STRVAR(appendleft_doc, "Add an element to the left side of the deque.");
349
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700350static PyObject*
351finalize_iterator(PyObject *it)
352{
353 if (PyErr_Occurred()) {
354 if (PyErr_ExceptionMatches(PyExc_StopIteration))
355 PyErr_Clear();
356 else {
357 Py_DECREF(it);
358 return NULL;
359 }
360 }
361 Py_DECREF(it);
362 Py_RETURN_NONE;
363}
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000365/* Run an iterator to exhaustion. Shortcut for
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000366 the extend/extendleft methods when maxlen == 0. */
367static PyObject*
368consume_iterator(PyObject *it)
369{
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700370 PyObject *(*iternext)(PyObject *);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000371 PyObject *item;
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000372
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700373 iternext = *Py_TYPE(it)->tp_iternext;
374 while ((item = iternext(it)) != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 Py_DECREF(item);
376 }
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700377 return finalize_iterator(it);
Raymond Hettinger060c7f62009-03-10 09:36:07 +0000378}
379
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000380static PyObject *
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000381deque_extend(dequeobject *deque, PyObject *iterable)
382{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000383 PyObject *it, *item;
Raymond Hettinger7a845522015-09-26 01:30:51 -0700384 PyObject *(*iternext)(PyObject *);
Raymond Hettinger6b1e1132015-10-11 09:43:50 -0700385 Py_ssize_t maxlen = deque->maxlen;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000387 /* Handle case where id(deque) == id(iterable) */
388 if ((PyObject *)deque == iterable) {
389 PyObject *result;
390 PyObject *s = PySequence_List(iterable);
391 if (s == NULL)
392 return NULL;
393 result = deque_extend(deque, s);
394 Py_DECREF(s);
395 return result;
396 }
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000397
Raymond Hettingerd79d5b12016-03-04 09:55:07 -0800398 it = PyObject_GetIter(iterable);
399 if (it == NULL)
400 return NULL;
401
402 if (maxlen == 0)
403 return consume_iterator(it);
404
Raymond Hettingerd9c116c2013-07-09 00:13:21 -0700405 /* Space saving heuristic. Start filling from the left */
406 if (Py_SIZE(deque) == 0) {
407 assert(deque->leftblock == deque->rightblock);
408 assert(deque->leftindex == deque->rightindex+1);
409 deque->leftindex = 1;
410 deque->rightindex = 0;
411 }
412
Raymond Hettinger7a845522015-09-26 01:30:51 -0700413 iternext = *Py_TYPE(it)->tp_iternext;
414 while ((item = iternext(it)) != NULL) {
Raymond Hettinger66953f02018-07-10 04:17:40 -0700415 if (deque_append_internal(deque, item, maxlen) == -1) {
416 Py_DECREF(item);
417 Py_DECREF(it);
418 return NULL;
Raymond Hettinger6b1e1132015-10-11 09:43:50 -0700419 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 }
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700421 return finalize_iterator(it);
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000422}
423
Tim Peters1065f752004-10-01 01:03:29 +0000424PyDoc_STRVAR(extend_doc,
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000425"Extend the right side of the deque with elements from the iterable");
426
427static PyObject *
428deque_extendleft(dequeobject *deque, PyObject *iterable)
429{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000430 PyObject *it, *item;
Raymond Hettinger7a845522015-09-26 01:30:51 -0700431 PyObject *(*iternext)(PyObject *);
Raymond Hettinger6b1e1132015-10-11 09:43:50 -0700432 Py_ssize_t maxlen = deque->maxlen;
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000434 /* Handle case where id(deque) == id(iterable) */
435 if ((PyObject *)deque == iterable) {
436 PyObject *result;
437 PyObject *s = PySequence_List(iterable);
438 if (s == NULL)
439 return NULL;
440 result = deque_extendleft(deque, s);
441 Py_DECREF(s);
442 return result;
443 }
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000444
Raymond Hettingerd79d5b12016-03-04 09:55:07 -0800445 it = PyObject_GetIter(iterable);
446 if (it == NULL)
447 return NULL;
448
449 if (maxlen == 0)
450 return consume_iterator(it);
451
Raymond Hettingerd9c116c2013-07-09 00:13:21 -0700452 /* Space saving heuristic. Start filling from the right */
453 if (Py_SIZE(deque) == 0) {
454 assert(deque->leftblock == deque->rightblock);
455 assert(deque->leftindex == deque->rightindex+1);
456 deque->leftindex = BLOCKLEN - 1;
457 deque->rightindex = BLOCKLEN - 2;
458 }
459
Raymond Hettinger7a845522015-09-26 01:30:51 -0700460 iternext = *Py_TYPE(it)->tp_iternext;
461 while ((item = iternext(it)) != NULL) {
Raymond Hettinger66953f02018-07-10 04:17:40 -0700462 if (deque_appendleft_internal(deque, item, maxlen) == -1) {
463 Py_DECREF(item);
464 Py_DECREF(it);
465 return NULL;
Raymond Hettinger6b1e1132015-10-11 09:43:50 -0700466 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000467 }
Raymond Hettingerfd265f42015-10-02 23:17:33 -0700468 return finalize_iterator(it);
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000469}
470
Tim Peters1065f752004-10-01 01:03:29 +0000471PyDoc_STRVAR(extendleft_doc,
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000472"Extend the left side of the deque with elements from the iterable");
473
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000474static PyObject *
475deque_inplace_concat(dequeobject *deque, PyObject *other)
476{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 PyObject *result;
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 result = deque_extend(deque, other);
480 if (result == NULL)
481 return result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 Py_INCREF(deque);
Raymond Hettinger2b2b7532015-09-05 17:05:52 -0700483 Py_DECREF(result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 return (PyObject *)deque;
Raymond Hettinger3f9afd82009-12-10 03:03:02 +0000485}
486
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700487static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530488deque_copy(PyObject *deque, PyObject *Py_UNUSED(ignored))
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700489{
Oren Milman24bd50b2018-09-11 21:46:55 +0300490 PyObject *result;
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700491 dequeobject *old_deque = (dequeobject *)deque;
Andy Lesterdffe4c02020-03-04 07:15:20 -0600492 if (Py_IS_TYPE(deque, &deque_type)) {
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700493 dequeobject *new_deque;
494 PyObject *rv;
495
496 new_deque = (dequeobject *)deque_new(&deque_type, (PyObject *)NULL, (PyObject *)NULL);
497 if (new_deque == NULL)
498 return NULL;
499 new_deque->maxlen = old_deque->maxlen;
500 /* Fast path for the deque_repeat() common case where len(deque) == 1 */
Raymond Hettinger0443ac22015-10-05 22:52:37 -0400501 if (Py_SIZE(deque) == 1) {
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700502 PyObject *item = old_deque->leftblock->data[old_deque->leftindex];
503 rv = deque_append(new_deque, item);
504 } else {
505 rv = deque_extend(new_deque, deque);
506 }
507 if (rv != NULL) {
508 Py_DECREF(rv);
509 return (PyObject *)new_deque;
510 }
511 Py_DECREF(new_deque);
512 return NULL;
513 }
514 if (old_deque->maxlen < 0)
Petr Viktorinffd97532020-02-11 17:46:57 +0100515 result = PyObject_CallOneArg((PyObject *)(Py_TYPE(deque)), deque);
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",
Victor Stinnerdaa97562020-02-07 03:37:06 +0100542 Py_TYPE(other)->tp_name);
Raymond Hettinger41290a62015-03-31 08:12:23 -0700543 }
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);
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100600 Py_SET_SIZE(deque, 0);
Raymond Hettinger8299e9b2015-09-26 21:31:23 -0700601 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) {
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100683 Py_SET_SIZE(deque, Py_SIZE(deque) + i);
Raymond Hettinger67c78b52015-09-12 11:00:20 -0400684 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 }
Victor Stinner60ac6ed2020-02-07 23:18:08 +0100703 Py_SET_SIZE(deque, 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];
sweeneydec6dedde2020-02-09 03:16:43 -0500968 Py_INCREF(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
sweeneydec6dedde2020-02-09 03:16:43 -0500970 Py_DECREF(item);
Raymond Hettinger2b0d6462015-09-23 19:15:44 -0700971 if (cmp < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 return NULL;
Raymond Hettinger2b0d6462015-09-23 19:15:44 -0700973 count += cmp;
Raymond Hettinger44459de2010-04-03 23:20:46 +0000974
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000975 if (start_state != deque->state) {
976 PyErr_SetString(PyExc_RuntimeError,
977 "deque mutated during iteration");
978 return NULL;
979 }
Raymond Hettinger44459de2010-04-03 23:20:46 +0000980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000981 /* Advance left block/index pair */
Raymond Hettingerf3a67b72013-07-06 17:49:06 -1000982 index++;
983 if (index == BLOCKLEN) {
984 b = b->rightlink;
985 index = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 }
987 }
988 return PyLong_FromSsize_t(count);
Raymond Hettinger44459de2010-04-03 23:20:46 +0000989}
990
991PyDoc_STRVAR(count_doc,
992"D.count(value) -> integer -- return number of occurrences of value");
993
Raymond Hettinger39dadf72015-03-20 16:38:56 -0700994static int
995deque_contains(dequeobject *deque, PyObject *v)
996{
997 block *b = deque->leftblock;
998 Py_ssize_t index = deque->leftindex;
999 Py_ssize_t n = Py_SIZE(deque);
Raymond Hettinger39dadf72015-03-20 16:38:56 -07001000 size_t start_state = deque->state;
1001 PyObject *item;
1002 int cmp;
1003
Raymond Hettingere1b02872017-09-04 16:07:06 -07001004 while (--n >= 0) {
Raymond Hettinger39dadf72015-03-20 16:38:56 -07001005 CHECK_NOT_END(b);
1006 item = b->data[index];
sweeneydec6dedde2020-02-09 03:16:43 -05001007 Py_INCREF(item);
Raymond Hettinger39dadf72015-03-20 16:38:56 -07001008 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
sweeneydec6dedde2020-02-09 03:16:43 -05001009 Py_DECREF(item);
Raymond Hettinger39dadf72015-03-20 16:38:56 -07001010 if (cmp) {
1011 return cmp;
1012 }
1013 if (start_state != deque->state) {
1014 PyErr_SetString(PyExc_RuntimeError,
1015 "deque mutated during iteration");
1016 return -1;
1017 }
1018 index++;
1019 if (index == BLOCKLEN) {
1020 b = b->rightlink;
1021 index = 0;
1022 }
1023 }
1024 return 0;
1025}
1026
Martin v. Löwis18e16552006-02-15 17:27:45 +00001027static Py_ssize_t
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001028deque_len(dequeobject *deque)
1029{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001030 return Py_SIZE(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001031}
1032
Raymond Hettinger4aec61e2005-03-18 21:20:23 +00001033static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02001034deque_index(dequeobject *deque, PyObject *const *args, Py_ssize_t nargs)
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001035{
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001036 Py_ssize_t i, n, start=0, stop=Py_SIZE(deque);
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001037 PyObject *v, *item;
1038 block *b = deque->leftblock;
1039 Py_ssize_t index = deque->leftindex;
1040 size_t start_state = deque->state;
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001041 int cmp;
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001042
Victor Stinnerdd407d52017-02-06 16:06:49 +01001043 if (!_PyArg_ParseStack(args, nargs, "O|O&O&:index", &v,
Serhiy Storchakad4edfc92017-03-30 18:29:23 +03001044 _PyEval_SliceIndexNotNone, &start,
1045 _PyEval_SliceIndexNotNone, &stop)) {
Victor Stinnerdd407d52017-02-06 16:06:49 +01001046 return NULL;
1047 }
1048
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001049 if (start < 0) {
1050 start += Py_SIZE(deque);
1051 if (start < 0)
1052 start = 0;
1053 }
1054 if (stop < 0) {
1055 stop += Py_SIZE(deque);
1056 if (stop < 0)
1057 stop = 0;
1058 }
Raymond Hettinger87674ec2015-08-26 08:08:38 -07001059 if (stop > Py_SIZE(deque))
1060 stop = Py_SIZE(deque);
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001061 if (start > stop)
1062 start = stop;
1063 assert(0 <= start && start <= stop && stop <= Py_SIZE(deque));
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001064
Raymond Hettingerb46ad542018-09-21 01:46:41 -07001065 for (i=0 ; i < start - BLOCKLEN ; i += BLOCKLEN) {
1066 b = b->rightlink;
1067 }
1068 for ( ; i < start ; i++) {
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001069 index++;
1070 if (index == BLOCKLEN) {
1071 b = b->rightlink;
1072 index = 0;
1073 }
1074 }
1075
Raymond Hettingere1b02872017-09-04 16:07:06 -07001076 n = stop - i;
1077 while (--n >= 0) {
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001078 CHECK_NOT_END(b);
1079 item = b->data[index];
1080 cmp = PyObject_RichCompareBool(item, v, Py_EQ);
1081 if (cmp > 0)
Raymond Hettingere1b02872017-09-04 16:07:06 -07001082 return PyLong_FromSsize_t(stop - n - 1);
Raymond Hettingerdf8f5b52015-11-02 07:27:40 -05001083 if (cmp < 0)
Raymond Hettinger67b97b82015-11-01 23:57:37 -05001084 return NULL;
1085 if (start_state != deque->state) {
1086 PyErr_SetString(PyExc_RuntimeError,
1087 "deque mutated during iteration");
1088 return NULL;
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001089 }
1090 index++;
1091 if (index == BLOCKLEN) {
1092 b = b->rightlink;
1093 index = 0;
1094 }
1095 }
1096 PyErr_Format(PyExc_ValueError, "%R is not in deque", v);
1097 return NULL;
1098}
1099
1100PyDoc_STRVAR(index_doc,
1101"D.index(value, [start, [stop]]) -> integer -- return first index of value.\n"
1102"Raises ValueError if the value is not present.");
1103
Raymond Hettinger551350a2015-03-24 00:19:53 -07001104/* insert(), remove(), and delitem() are implemented in terms of
1105 rotate() for simplicity and reasonable performance near the end
1106 points. If for some reason these methods become popular, it is not
1107 hard to re-implement this using direct data movement (similar to
1108 the code used in list slice assignments) and achieve a performance
Raymond Hettingerfef9c1b2015-03-24 21:12:57 -07001109 boost (by moving each pointer only once instead of twice).
Raymond Hettinger551350a2015-03-24 00:19:53 -07001110*/
1111
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001112static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02001113deque_insert(dequeobject *deque, PyObject *const *args, Py_ssize_t nargs)
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001114{
1115 Py_ssize_t index;
1116 Py_ssize_t n = Py_SIZE(deque);
1117 PyObject *value;
1118 PyObject *rv;
1119
Victor Stinnerdd407d52017-02-06 16:06:49 +01001120 if (!_PyArg_ParseStack(args, nargs, "nO:insert", &index, &value)) {
1121 return NULL;
1122 }
1123
Raymond Hettinger37434322016-01-26 21:44:16 -08001124 if (deque->maxlen == Py_SIZE(deque)) {
Raymond Hettingera6389712016-02-01 21:21:19 -08001125 PyErr_SetString(PyExc_IndexError, "deque already at its maximum size");
1126 return NULL;
Raymond Hettinger37434322016-01-26 21:44:16 -08001127 }
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001128 if (index >= n)
1129 return deque_append(deque, value);
1130 if (index <= -n || index == 0)
1131 return deque_appendleft(deque, value);
1132 if (_deque_rotate(deque, -index))
1133 return NULL;
1134 if (index < 0)
1135 rv = deque_append(deque, value);
1136 else
1137 rv = deque_appendleft(deque, value);
1138 if (rv == NULL)
1139 return NULL;
1140 Py_DECREF(rv);
1141 if (_deque_rotate(deque, index))
1142 return NULL;
1143 Py_RETURN_NONE;
1144}
1145
1146PyDoc_STRVAR(insert_doc,
1147"D.insert(index, object) -- insert object before index");
1148
1149static PyObject *
Raymond Hettinger4aec61e2005-03-18 21:20:23 +00001150deque_remove(dequeobject *deque, PyObject *value)
1151{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001152 Py_ssize_t i, n=Py_SIZE(deque);
Raymond Hettinger4aec61e2005-03-18 21:20:23 +00001153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001154 for (i=0 ; i<n ; i++) {
1155 PyObject *item = deque->leftblock->data[deque->leftindex];
1156 int cmp = PyObject_RichCompareBool(item, value, Py_EQ);
Raymond Hettingerd73202c2005-03-19 00:00:51 +00001157
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001158 if (Py_SIZE(deque) != n) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001159 PyErr_SetString(PyExc_IndexError,
1160 "deque mutated during remove().");
1161 return NULL;
1162 }
1163 if (cmp > 0) {
1164 PyObject *tgt = deque_popleft(deque, NULL);
1165 assert (tgt != NULL);
Raymond Hettinger6921c132015-03-21 02:03:40 -07001166 if (_deque_rotate(deque, i))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001167 return NULL;
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001168 Py_DECREF(tgt);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001169 Py_RETURN_NONE;
1170 }
1171 else if (cmp < 0) {
1172 _deque_rotate(deque, i);
1173 return NULL;
1174 }
1175 _deque_rotate(deque, -1);
1176 }
1177 PyErr_SetString(PyExc_ValueError, "deque.remove(x): x not in deque");
1178 return NULL;
Raymond Hettinger4aec61e2005-03-18 21:20:23 +00001179}
1180
1181PyDoc_STRVAR(remove_doc,
1182"D.remove(value) -- remove first occurrence of value.");
1183
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001184static int
1185valid_index(Py_ssize_t i, Py_ssize_t limit)
1186{
Raymond Hettinger12f896c2015-07-31 12:03:20 -07001187 /* The cast to size_t lets us use just a single comparison
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001188 to check whether i is in the range: 0 <= i < limit */
1189 return (size_t) i < (size_t) limit;
1190}
1191
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001192static PyObject *
Benjamin Petersond6313712008-07-31 16:23:04 +00001193deque_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001194{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 block *b;
1196 PyObject *item;
1197 Py_ssize_t n, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001198
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001199 if (!valid_index(i, Py_SIZE(deque))) {
1200 PyErr_SetString(PyExc_IndexError, "deque index out of range");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001201 return NULL;
1202 }
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 if (i == 0) {
1205 i = deque->leftindex;
1206 b = deque->leftblock;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001207 } else if (i == Py_SIZE(deque) - 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001208 i = deque->rightindex;
1209 b = deque->rightblock;
1210 } else {
1211 i += deque->leftindex;
Raymond Hettingerc2083082015-02-28 23:29:16 -08001212 n = (Py_ssize_t)((size_t) i / BLOCKLEN);
1213 i = (Py_ssize_t)((size_t) i % BLOCKLEN);
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001214 if (index < (Py_SIZE(deque) >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001215 b = deque->leftblock;
Raymond Hettingere1b02872017-09-04 16:07:06 -07001216 while (--n >= 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001217 b = b->rightlink;
1218 } else {
Raymond Hettinger63d1ff22015-02-28 07:41:30 -08001219 n = (Py_ssize_t)(
Raymond Hettingerc2083082015-02-28 23:29:16 -08001220 ((size_t)(deque->leftindex + Py_SIZE(deque) - 1))
Raymond Hettinger63d1ff22015-02-28 07:41:30 -08001221 / BLOCKLEN - n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001222 b = deque->rightblock;
Raymond Hettingere1b02872017-09-04 16:07:06 -07001223 while (--n >= 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001224 b = b->leftlink;
1225 }
1226 }
1227 item = b->data[i];
1228 Py_INCREF(item);
1229 return item;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001230}
1231
1232static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001233deque_del_item(dequeobject *deque, Py_ssize_t i)
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001234{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001235 PyObject *item;
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001236 int rv;
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001237
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001238 assert (i >= 0 && i < Py_SIZE(deque));
Raymond Hettinger6921c132015-03-21 02:03:40 -07001239 if (_deque_rotate(deque, -i))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001240 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001241 item = deque_popleft(deque, NULL);
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001242 rv = _deque_rotate(deque, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001243 assert (item != NULL);
1244 Py_DECREF(item);
Raymond Hettingerac13ad62015-03-21 01:53:16 -07001245 return rv;
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001246}
1247
1248static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001249deque_ass_item(dequeobject *deque, Py_ssize_t i, PyObject *v)
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001250{
Raymond Hettinger38418662016-02-08 20:34:49 -08001251 PyObject *old_value;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001252 block *b;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001253 Py_ssize_t n, len=Py_SIZE(deque), halflen=(len+1)>>1, index=i;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001254
Raymond Hettinger3c186ba2015-03-02 21:45:02 -08001255 if (!valid_index(i, len)) {
1256 PyErr_SetString(PyExc_IndexError, "deque index out of range");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001257 return -1;
1258 }
1259 if (v == NULL)
1260 return deque_del_item(deque, i);
Raymond Hettinger0e371f22004-05-12 20:55:56 +00001261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001262 i += deque->leftindex;
Raymond Hettingerc2083082015-02-28 23:29:16 -08001263 n = (Py_ssize_t)((size_t) i / BLOCKLEN);
1264 i = (Py_ssize_t)((size_t) i % BLOCKLEN);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001265 if (index <= halflen) {
1266 b = deque->leftblock;
Raymond Hettingere1b02872017-09-04 16:07:06 -07001267 while (--n >= 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001268 b = b->rightlink;
1269 } else {
Raymond Hettingera473b9d2015-02-28 17:49:47 -08001270 n = (Py_ssize_t)(
Raymond Hettingerc2083082015-02-28 23:29:16 -08001271 ((size_t)(deque->leftindex + Py_SIZE(deque) - 1))
Raymond Hettingera473b9d2015-02-28 17:49:47 -08001272 / BLOCKLEN - n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001273 b = deque->rightblock;
Raymond Hettingere1b02872017-09-04 16:07:06 -07001274 while (--n >= 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001275 b = b->leftlink;
1276 }
1277 Py_INCREF(v);
Raymond Hettinger38418662016-02-08 20:34:49 -08001278 old_value = b->data[i];
1279 b->data[i] = v;
1280 Py_DECREF(old_value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001281 return 0;
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001282}
1283
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001284static void
1285deque_dealloc(dequeobject *deque)
1286{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001287 PyObject_GC_UnTrack(deque);
1288 if (deque->weakreflist != NULL)
1289 PyObject_ClearWeakRefs((PyObject *) deque);
1290 if (deque->leftblock != NULL) {
1291 deque_clear(deque);
1292 assert(deque->leftblock != NULL);
1293 freeblock(deque->leftblock);
1294 }
1295 deque->leftblock = NULL;
1296 deque->rightblock = NULL;
1297 Py_TYPE(deque)->tp_free(deque);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001298}
1299
1300static int
Raymond Hettinger0a4977c2004-03-01 23:16:22 +00001301deque_traverse(dequeobject *deque, visitproc visit, void *arg)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001302{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001303 block *b;
1304 PyObject *item;
1305 Py_ssize_t index;
1306 Py_ssize_t indexlo = deque->leftindex;
Raymond Hettinger1286d142015-10-14 23:16:57 -07001307 Py_ssize_t indexhigh;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001308
Raymond Hettinger5bfa8672013-07-06 11:58:09 -10001309 for (b = deque->leftblock; b != deque->rightblock; b = b->rightlink) {
1310 for (index = indexlo; index < BLOCKLEN ; index++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001311 item = b->data[index];
1312 Py_VISIT(item);
1313 }
1314 indexlo = 0;
1315 }
Raymond Hettinger1286d142015-10-14 23:16:57 -07001316 indexhigh = deque->rightindex;
1317 for (index = indexlo; index <= indexhigh; index++) {
Raymond Hettinger5bfa8672013-07-06 11:58:09 -10001318 item = b->data[index];
1319 Py_VISIT(item);
1320 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001321 return 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001322}
1323
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001324static PyObject *
Serhiy Storchaka81524022018-11-27 13:05:02 +02001325deque_reduce(dequeobject *deque, PyObject *Py_UNUSED(ignored))
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001326{
Serhiy Storchakaa0d416f2016-03-06 08:55:21 +02001327 PyObject *dict, *it;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001328 _Py_IDENTIFIER(__dict__);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001329
Serhiy Storchakaf320be72018-01-25 10:49:40 +02001330 if (_PyObject_LookupAttrId((PyObject *)deque, &PyId___dict__, &dict) < 0) {
1331 return NULL;
1332 }
Serhiy Storchakaa0d416f2016-03-06 08:55:21 +02001333 if (dict == NULL) {
Serhiy Storchakaa0d416f2016-03-06 08:55:21 +02001334 dict = Py_None;
1335 Py_INCREF(dict);
1336 }
1337
1338 it = PyObject_GetIter((PyObject *)deque);
1339 if (it == NULL) {
1340 Py_DECREF(dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001341 return NULL;
1342 }
Serhiy Storchakaa0d416f2016-03-06 08:55:21 +02001343
1344 if (deque->maxlen < 0) {
1345 return Py_BuildValue("O()NN", Py_TYPE(deque), dict, it);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001346 }
Serhiy Storchakaa0d416f2016-03-06 08:55:21 +02001347 else {
1348 return Py_BuildValue("O(()n)NN", Py_TYPE(deque), deque->maxlen, dict, it);
1349 }
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001350}
1351
1352PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
1353
1354static PyObject *
1355deque_repr(PyObject *deque)
1356{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001357 PyObject *aslist, *result;
1358 int i;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001360 i = Py_ReprEnter(deque);
1361 if (i != 0) {
1362 if (i < 0)
1363 return NULL;
1364 return PyUnicode_FromString("[...]");
1365 }
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001367 aslist = PySequence_List(deque);
1368 if (aslist == NULL) {
1369 Py_ReprLeave(deque);
1370 return NULL;
1371 }
Raymond Hettingera7f630092015-10-10 23:56:02 -04001372 if (((dequeobject *)deque)->maxlen >= 0)
Serhiy Storchakab3a77962017-09-21 14:24:13 +03001373 result = PyUnicode_FromFormat("%s(%R, maxlen=%zd)",
1374 _PyType_Name(Py_TYPE(deque)), aslist,
1375 ((dequeobject *)deque)->maxlen);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001376 else
Serhiy Storchakab3a77962017-09-21 14:24:13 +03001377 result = PyUnicode_FromFormat("%s(%R)",
1378 _PyType_Name(Py_TYPE(deque)), aslist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001379 Py_ReprLeave(deque);
Raymond Hettinger2b2b7532015-09-05 17:05:52 -07001380 Py_DECREF(aslist);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001381 return result;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001382}
1383
Raymond Hettinger738ec902004-02-29 02:15:56 +00001384static PyObject *
1385deque_richcompare(PyObject *v, PyObject *w, int op)
1386{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001387 PyObject *it1=NULL, *it2=NULL, *x, *y;
1388 Py_ssize_t vs, ws;
1389 int b, cmp=-1;
Raymond Hettinger738ec902004-02-29 02:15:56 +00001390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001391 if (!PyObject_TypeCheck(v, &deque_type) ||
1392 !PyObject_TypeCheck(w, &deque_type)) {
Brian Curtindfc80e32011-08-10 20:28:54 -05001393 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001394 }
Raymond Hettinger738ec902004-02-29 02:15:56 +00001395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001396 /* Shortcuts */
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001397 vs = Py_SIZE((dequeobject *)v);
1398 ws = Py_SIZE((dequeobject *)w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001399 if (op == Py_EQ) {
1400 if (v == w)
1401 Py_RETURN_TRUE;
1402 if (vs != ws)
1403 Py_RETURN_FALSE;
1404 }
1405 if (op == Py_NE) {
1406 if (v == w)
1407 Py_RETURN_FALSE;
1408 if (vs != ws)
1409 Py_RETURN_TRUE;
1410 }
Raymond Hettinger738ec902004-02-29 02:15:56 +00001411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001412 /* Search for the first index where items are different */
1413 it1 = PyObject_GetIter(v);
1414 if (it1 == NULL)
1415 goto done;
1416 it2 = PyObject_GetIter(w);
1417 if (it2 == NULL)
1418 goto done;
1419 for (;;) {
1420 x = PyIter_Next(it1);
1421 if (x == NULL && PyErr_Occurred())
1422 goto done;
1423 y = PyIter_Next(it2);
1424 if (x == NULL || y == NULL)
1425 break;
1426 b = PyObject_RichCompareBool(x, y, Py_EQ);
1427 if (b == 0) {
1428 cmp = PyObject_RichCompareBool(x, y, op);
1429 Py_DECREF(x);
1430 Py_DECREF(y);
1431 goto done;
1432 }
1433 Py_DECREF(x);
1434 Py_DECREF(y);
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -07001435 if (b < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001436 goto done;
1437 }
1438 /* We reached the end of one deque or both */
1439 Py_XDECREF(x);
1440 Py_XDECREF(y);
1441 if (PyErr_Occurred())
1442 goto done;
1443 switch (op) {
1444 case Py_LT: cmp = y != NULL; break; /* if w was longer */
1445 case Py_LE: cmp = x == NULL; break; /* if v was not longer */
1446 case Py_EQ: cmp = x == y; break; /* if we reached the end of both */
1447 case Py_NE: cmp = x != y; break; /* if one deque continues */
1448 case Py_GT: cmp = x != NULL; break; /* if v was longer */
1449 case Py_GE: cmp = y == NULL; break; /* if w was not longer */
1450 }
Tim Peters1065f752004-10-01 01:03:29 +00001451
Raymond Hettinger738ec902004-02-29 02:15:56 +00001452done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001453 Py_XDECREF(it1);
1454 Py_XDECREF(it2);
1455 if (cmp == 1)
1456 Py_RETURN_TRUE;
1457 if (cmp == 0)
1458 Py_RETURN_FALSE;
1459 return NULL;
Raymond Hettinger738ec902004-02-29 02:15:56 +00001460}
1461
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001462static int
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001463deque_init(dequeobject *deque, PyObject *args, PyObject *kwdargs)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001464{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001465 PyObject *iterable = NULL;
1466 PyObject *maxlenobj = NULL;
1467 Py_ssize_t maxlen = -1;
1468 char *kwlist[] = {"iterable", "maxlen", 0};
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001469
Raymond Hettinger05f1b932019-01-31 22:13:43 -08001470 if (kwdargs == NULL && PyTuple_GET_SIZE(args) <= 2) {
1471 if (PyTuple_GET_SIZE(args) > 0) {
1472 iterable = PyTuple_GET_ITEM(args, 0);
1473 }
1474 if (PyTuple_GET_SIZE(args) > 1) {
1475 maxlenobj = PyTuple_GET_ITEM(args, 1);
1476 }
Raymond Hettinger0d309402015-09-30 23:15:02 -07001477 } else {
1478 if (!PyArg_ParseTupleAndKeywords(args, kwdargs, "|OO:deque", kwlist,
1479 &iterable, &maxlenobj))
1480 return -1;
1481 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001482 if (maxlenobj != NULL && maxlenobj != Py_None) {
1483 maxlen = PyLong_AsSsize_t(maxlenobj);
1484 if (maxlen == -1 && PyErr_Occurred())
1485 return -1;
1486 if (maxlen < 0) {
1487 PyErr_SetString(PyExc_ValueError, "maxlen must be non-negative");
1488 return -1;
1489 }
1490 }
1491 deque->maxlen = maxlen;
Raymond Hettinger0d309402015-09-30 23:15:02 -07001492 if (Py_SIZE(deque) > 0)
1493 deque_clear(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001494 if (iterable != NULL) {
1495 PyObject *rv = deque_extend(deque, iterable);
1496 if (rv == NULL)
1497 return -1;
1498 Py_DECREF(rv);
1499 }
1500 return 0;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001501}
1502
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001503static PyObject *
Jesus Cea16e2fca2012-08-03 14:49:42 +02001504deque_sizeof(dequeobject *deque, void *unused)
1505{
1506 Py_ssize_t res;
1507 Py_ssize_t blocks;
1508
Serhiy Storchaka5c4064e2015-12-19 20:05:25 +02001509 res = _PyObject_SIZE(Py_TYPE(deque));
Raymond Hettingerbc003412015-10-14 23:33:23 -07001510 blocks = (size_t)(deque->leftindex + Py_SIZE(deque) + BLOCKLEN - 1) / BLOCKLEN;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001511 assert(deque->leftindex + Py_SIZE(deque) - 1 ==
Jesus Cea16e2fca2012-08-03 14:49:42 +02001512 (blocks - 1) * BLOCKLEN + deque->rightindex);
1513 res += blocks * sizeof(block);
1514 return PyLong_FromSsize_t(res);
1515}
1516
1517PyDoc_STRVAR(sizeof_doc,
1518"D.__sizeof__() -- size of D in memory, in bytes");
1519
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001520static int
1521deque_bool(dequeobject *deque)
1522{
1523 return Py_SIZE(deque) != 0;
1524}
1525
Jesus Cea16e2fca2012-08-03 14:49:42 +02001526static PyObject *
Serhiy Storchakad4f9cf52018-11-27 19:34:35 +02001527deque_get_maxlen(dequeobject *deque, void *Py_UNUSED(ignored))
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001528{
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -07001529 if (deque->maxlen < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001530 Py_RETURN_NONE;
1531 return PyLong_FromSsize_t(deque->maxlen);
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001532}
1533
Raymond Hettinger41290a62015-03-31 08:12:23 -07001534
1535/* deque object ********************************************************/
1536
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001537static PyGetSetDef deque_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001538 {"maxlen", (getter)deque_get_maxlen, (setter)NULL,
1539 "maximum size of a deque or None if unbounded"},
1540 {0}
Raymond Hettinger5bb0f0e2009-03-10 12:56:32 +00001541};
1542
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001543static PySequenceMethods deque_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001544 (lenfunc)deque_len, /* sq_length */
Raymond Hettinger41290a62015-03-31 08:12:23 -07001545 (binaryfunc)deque_concat, /* sq_concat */
1546 (ssizeargfunc)deque_repeat, /* sq_repeat */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001547 (ssizeargfunc)deque_item, /* sq_item */
1548 0, /* sq_slice */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001549 (ssizeobjargproc)deque_ass_item, /* sq_ass_item */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001550 0, /* sq_ass_slice */
Raymond Hettinger39dadf72015-03-20 16:38:56 -07001551 (objobjproc)deque_contains, /* sq_contains */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001552 (binaryfunc)deque_inplace_concat, /* sq_inplace_concat */
Raymond Hettinger41290a62015-03-31 08:12:23 -07001553 (ssizeargfunc)deque_inplace_repeat, /* sq_inplace_repeat */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001554};
1555
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001556static PyNumberMethods deque_as_number = {
1557 0, /* nb_add */
1558 0, /* nb_subtract */
1559 0, /* nb_multiply */
1560 0, /* nb_remainder */
1561 0, /* nb_divmod */
1562 0, /* nb_power */
1563 0, /* nb_negative */
1564 0, /* nb_positive */
1565 0, /* nb_absolute */
1566 (inquiry)deque_bool, /* nb_bool */
1567 0, /* nb_invert */
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001568 };
1569
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001570static PyObject *deque_iter(dequeobject *deque);
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301571static PyObject *deque_reviter(dequeobject *deque, PyObject *Py_UNUSED(ignored));
Tim Peters1065f752004-10-01 01:03:29 +00001572PyDoc_STRVAR(reversed_doc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001573 "D.__reversed__() -- return a reverse iterator over the deque");
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001574
1575static PyMethodDef deque_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001576 {"append", (PyCFunction)deque_append,
1577 METH_O, append_doc},
1578 {"appendleft", (PyCFunction)deque_appendleft,
1579 METH_O, appendleft_doc},
1580 {"clear", (PyCFunction)deque_clearmethod,
1581 METH_NOARGS, clear_doc},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301582 {"__copy__", deque_copy,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001583 METH_NOARGS, copy_doc},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301584 {"copy", deque_copy,
Raymond Hettinger32ea1652015-03-21 01:37:37 -07001585 METH_NOARGS, copy_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001586 {"count", (PyCFunction)deque_count,
Raymond Hettinger0f6f9472015-03-21 01:42:10 -07001587 METH_O, count_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001588 {"extend", (PyCFunction)deque_extend,
1589 METH_O, extend_doc},
1590 {"extendleft", (PyCFunction)deque_extendleft,
1591 METH_O, extendleft_doc},
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001592 {"index", (PyCFunction)(void(*)(void))deque_index,
Victor Stinnerdd407d52017-02-06 16:06:49 +01001593 METH_FASTCALL, index_doc},
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001594 {"insert", (PyCFunction)(void(*)(void))deque_insert,
Victor Stinnerdd407d52017-02-06 16:06:49 +01001595 METH_FASTCALL, insert_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001596 {"pop", (PyCFunction)deque_pop,
1597 METH_NOARGS, pop_doc},
1598 {"popleft", (PyCFunction)deque_popleft,
1599 METH_NOARGS, popleft_doc},
Raymond Hettinger0f6f9472015-03-21 01:42:10 -07001600 {"__reduce__", (PyCFunction)deque_reduce,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001601 METH_NOARGS, reduce_doc},
1602 {"remove", (PyCFunction)deque_remove,
1603 METH_O, remove_doc},
1604 {"__reversed__", (PyCFunction)deque_reviter,
1605 METH_NOARGS, reversed_doc},
1606 {"reverse", (PyCFunction)deque_reverse,
1607 METH_NOARGS, reverse_doc},
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001608 {"rotate", (PyCFunction)(void(*)(void))deque_rotate,
Victor Stinnerdd407d52017-02-06 16:06:49 +01001609 METH_FASTCALL, rotate_doc},
Jesus Cea16e2fca2012-08-03 14:49:42 +02001610 {"__sizeof__", (PyCFunction)deque_sizeof,
1611 METH_NOARGS, sizeof_doc},
Guido van Rossum48b069a2020-04-07 09:50:06 -07001612 {"__class_getitem__", (PyCFunction)Py_GenericAlias,
1613 METH_O|METH_CLASS, PyDoc_STR("See PEP 585")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001614 {NULL, NULL} /* sentinel */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001615};
1616
1617PyDoc_STRVAR(deque_doc,
Andrew Svetlov6a5c7c32012-10-31 11:50:40 +02001618"deque([iterable[, maxlen]]) --> deque object\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001619\n\
Raymond Hettinger41290a62015-03-31 08:12:23 -07001620A list-like sequence optimized for data accesses near its endpoints.");
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001621
Neal Norwitz87f10132004-02-29 15:40:53 +00001622static PyTypeObject deque_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001623 PyVarObject_HEAD_INIT(NULL, 0)
1624 "collections.deque", /* tp_name */
1625 sizeof(dequeobject), /* tp_basicsize */
1626 0, /* tp_itemsize */
1627 /* methods */
1628 (destructor)deque_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001629 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001630 0, /* tp_getattr */
1631 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001632 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001633 deque_repr, /* tp_repr */
Raymond Hettinger0f1451c2015-03-23 23:23:55 -07001634 &deque_as_number, /* tp_as_number */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001635 &deque_as_sequence, /* tp_as_sequence */
1636 0, /* tp_as_mapping */
Georg Brandlf038b322010-10-18 07:35:09 +00001637 PyObject_HashNotImplemented, /* tp_hash */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001638 0, /* tp_call */
1639 0, /* tp_str */
1640 PyObject_GenericGetAttr, /* tp_getattro */
1641 0, /* tp_setattro */
1642 0, /* tp_as_buffer */
1643 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
Georg Brandlf038b322010-10-18 07:35:09 +00001644 /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001645 deque_doc, /* tp_doc */
1646 (traverseproc)deque_traverse, /* tp_traverse */
1647 (inquiry)deque_clear, /* tp_clear */
1648 (richcmpfunc)deque_richcompare, /* tp_richcompare */
Georg Brandlf038b322010-10-18 07:35:09 +00001649 offsetof(dequeobject, weakreflist), /* tp_weaklistoffset*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001650 (getiterfunc)deque_iter, /* tp_iter */
1651 0, /* tp_iternext */
1652 deque_methods, /* tp_methods */
1653 0, /* tp_members */
Georg Brandlf038b322010-10-18 07:35:09 +00001654 deque_getset, /* tp_getset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001655 0, /* tp_base */
1656 0, /* tp_dict */
1657 0, /* tp_descr_get */
1658 0, /* tp_descr_set */
1659 0, /* tp_dictoffset */
1660 (initproc)deque_init, /* tp_init */
1661 PyType_GenericAlloc, /* tp_alloc */
1662 deque_new, /* tp_new */
1663 PyObject_GC_Del, /* tp_free */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001664};
1665
1666/*********************** Deque Iterator **************************/
1667
1668typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001669 PyObject_HEAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001670 block *b;
Raymond Hettinger87e69122015-03-02 23:32:02 -08001671 Py_ssize_t index;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001672 dequeobject *deque;
Raymond Hettingerf9d9c792015-03-02 22:47:46 -08001673 size_t state; /* state when the iterator is created */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001674 Py_ssize_t counter; /* number of items remaining for iteration */
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001675} dequeiterobject;
1676
Martin v. Löwis59683e82008-06-13 07:50:45 +00001677static PyTypeObject dequeiter_type;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001678
1679static PyObject *
1680deque_iter(dequeobject *deque)
1681{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001682 dequeiterobject *it;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001683
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001684 it = PyObject_GC_New(dequeiterobject, &dequeiter_type);
1685 if (it == NULL)
1686 return NULL;
1687 it->b = deque->leftblock;
1688 it->index = deque->leftindex;
1689 Py_INCREF(deque);
1690 it->deque = deque;
1691 it->state = deque->state;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001692 it->counter = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001693 PyObject_GC_Track(it);
1694 return (PyObject *)it;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001695}
1696
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001697static int
1698dequeiter_traverse(dequeiterobject *dio, visitproc visit, void *arg)
1699{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001700 Py_VISIT(dio->deque);
1701 return 0;
Antoine Pitrou7ddda782009-01-01 15:35:33 +00001702}
1703
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001704static void
1705dequeiter_dealloc(dequeiterobject *dio)
1706{
INADA Naokia6296d32017-08-24 14:55:17 +09001707 /* bpo-31095: UnTrack is needed before calling any callbacks */
1708 PyObject_GC_UnTrack(dio);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001709 Py_XDECREF(dio->deque);
1710 PyObject_GC_Del(dio);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001711}
1712
1713static PyObject *
1714dequeiter_next(dequeiterobject *it)
1715{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001716 PyObject *item;
Raymond Hettingerd1b3d882004-10-02 00:43:13 +00001717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001718 if (it->deque->state != it->state) {
1719 it->counter = 0;
1720 PyErr_SetString(PyExc_RuntimeError,
1721 "deque mutated during iteration");
1722 return NULL;
1723 }
1724 if (it->counter == 0)
1725 return NULL;
1726 assert (!(it->b == it->deque->rightblock &&
1727 it->index > it->deque->rightindex));
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001728
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001729 item = it->b->data[it->index];
1730 it->index++;
1731 it->counter--;
1732 if (it->index == BLOCKLEN && it->counter > 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -10001733 CHECK_NOT_END(it->b->rightlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001734 it->b = it->b->rightlink;
1735 it->index = 0;
1736 }
1737 Py_INCREF(item);
1738 return item;
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001739}
1740
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001741static PyObject *
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001742dequeiter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1743{
1744 Py_ssize_t i, index=0;
1745 PyObject *deque;
1746 dequeiterobject *it;
1747 if (!PyArg_ParseTuple(args, "O!|n", &deque_type, &deque, &index))
1748 return NULL;
1749 assert(type == &dequeiter_type);
1750
1751 it = (dequeiterobject*)deque_iter((dequeobject *)deque);
1752 if (!it)
1753 return NULL;
1754 /* consume items from the queue */
1755 for(i=0; i<index; i++) {
1756 PyObject *item = dequeiter_next(it);
1757 if (item) {
1758 Py_DECREF(item);
1759 } else {
1760 if (it->counter) {
1761 Py_DECREF(it);
1762 return NULL;
1763 } else
1764 break;
1765 }
1766 }
1767 return (PyObject*)it;
1768}
1769
1770static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301771dequeiter_len(dequeiterobject *it, PyObject *Py_UNUSED(ignored))
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001772{
Antoine Pitrou554f3342010-08-17 18:30:06 +00001773 return PyLong_FromSsize_t(it->counter);
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001774}
1775
Armin Rigof5b3e362006-02-11 21:32:43 +00001776PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001777
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001778static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301779dequeiter_reduce(dequeiterobject *it, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001780{
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001781 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 +00001782}
1783
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001784static PyMethodDef dequeiter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001785 {"__length_hint__", (PyCFunction)dequeiter_len, METH_NOARGS, length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001786 {"__reduce__", (PyCFunction)dequeiter_reduce, METH_NOARGS, reduce_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001787 {NULL, NULL} /* sentinel */
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001788};
1789
Martin v. Löwis59683e82008-06-13 07:50:45 +00001790static PyTypeObject dequeiter_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001791 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger87e69122015-03-02 23:32:02 -08001792 "_collections._deque_iterator", /* tp_name */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001793 sizeof(dequeiterobject), /* tp_basicsize */
1794 0, /* tp_itemsize */
1795 /* methods */
1796 (destructor)dequeiter_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001797 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001798 0, /* tp_getattr */
1799 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001800 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001801 0, /* tp_repr */
1802 0, /* tp_as_number */
1803 0, /* tp_as_sequence */
1804 0, /* tp_as_mapping */
1805 0, /* tp_hash */
1806 0, /* tp_call */
1807 0, /* tp_str */
1808 PyObject_GenericGetAttr, /* tp_getattro */
1809 0, /* tp_setattro */
1810 0, /* tp_as_buffer */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001811 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001812 0, /* tp_doc */
1813 (traverseproc)dequeiter_traverse, /* tp_traverse */
1814 0, /* tp_clear */
1815 0, /* tp_richcompare */
1816 0, /* tp_weaklistoffset */
1817 PyObject_SelfIter, /* tp_iter */
1818 (iternextfunc)dequeiter_next, /* tp_iternext */
1819 dequeiter_methods, /* tp_methods */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001820 0, /* tp_members */
1821 0, /* tp_getset */
1822 0, /* tp_base */
1823 0, /* tp_dict */
1824 0, /* tp_descr_get */
1825 0, /* tp_descr_set */
1826 0, /* tp_dictoffset */
1827 0, /* tp_init */
1828 0, /* tp_alloc */
1829 dequeiter_new, /* tp_new */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001830 0,
Raymond Hettinger756b3f32004-01-29 06:37:52 +00001831};
1832
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001833/*********************** Deque Reverse Iterator **************************/
1834
Martin v. Löwis59683e82008-06-13 07:50:45 +00001835static PyTypeObject dequereviter_type;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001836
1837static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301838deque_reviter(dequeobject *deque, PyObject *Py_UNUSED(ignored))
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001839{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001840 dequeiterobject *it;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001841
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001842 it = PyObject_GC_New(dequeiterobject, &dequereviter_type);
1843 if (it == NULL)
1844 return NULL;
1845 it->b = deque->rightblock;
1846 it->index = deque->rightindex;
1847 Py_INCREF(deque);
1848 it->deque = deque;
1849 it->state = deque->state;
Raymond Hettingerdf715ba2013-07-06 13:01:13 -10001850 it->counter = Py_SIZE(deque);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001851 PyObject_GC_Track(it);
1852 return (PyObject *)it;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001853}
1854
1855static PyObject *
1856dequereviter_next(dequeiterobject *it)
1857{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001858 PyObject *item;
1859 if (it->counter == 0)
1860 return NULL;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001861
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001862 if (it->deque->state != it->state) {
1863 it->counter = 0;
1864 PyErr_SetString(PyExc_RuntimeError,
1865 "deque mutated during iteration");
1866 return NULL;
1867 }
1868 assert (!(it->b == it->deque->leftblock &&
1869 it->index < it->deque->leftindex));
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001871 item = it->b->data[it->index];
1872 it->index--;
1873 it->counter--;
Raymond Hettingerd3d2b2c2015-09-21 23:41:56 -07001874 if (it->index < 0 && it->counter > 0) {
Raymond Hettinger82df9252013-07-07 01:43:42 -10001875 CHECK_NOT_END(it->b->leftlink);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001876 it->b = it->b->leftlink;
1877 it->index = BLOCKLEN - 1;
1878 }
1879 Py_INCREF(item);
1880 return item;
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001881}
1882
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001883static PyObject *
1884dequereviter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1885{
1886 Py_ssize_t i, index=0;
1887 PyObject *deque;
1888 dequeiterobject *it;
1889 if (!PyArg_ParseTuple(args, "O!|n", &deque_type, &deque, &index))
1890 return NULL;
1891 assert(type == &dequereviter_type);
1892
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301893 it = (dequeiterobject*)deque_reviter((dequeobject *)deque, NULL);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001894 if (!it)
1895 return NULL;
1896 /* consume items from the queue */
1897 for(i=0; i<index; i++) {
1898 PyObject *item = dequereviter_next(it);
1899 if (item) {
1900 Py_DECREF(item);
1901 } else {
1902 if (it->counter) {
1903 Py_DECREF(it);
1904 return NULL;
1905 } else
1906 break;
1907 }
1908 }
1909 return (PyObject*)it;
1910}
1911
Martin v. Löwis59683e82008-06-13 07:50:45 +00001912static PyTypeObject dequereviter_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001913 PyVarObject_HEAD_INIT(NULL, 0)
Raymond Hettinger87e69122015-03-02 23:32:02 -08001914 "_collections._deque_reverse_iterator", /* tp_name */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001915 sizeof(dequeiterobject), /* tp_basicsize */
1916 0, /* tp_itemsize */
1917 /* methods */
1918 (destructor)dequeiter_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001919 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001920 0, /* tp_getattr */
1921 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001922 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001923 0, /* tp_repr */
1924 0, /* tp_as_number */
1925 0, /* tp_as_sequence */
1926 0, /* tp_as_mapping */
1927 0, /* tp_hash */
1928 0, /* tp_call */
1929 0, /* tp_str */
1930 PyObject_GenericGetAttr, /* tp_getattro */
1931 0, /* tp_setattro */
1932 0, /* tp_as_buffer */
Raymond Hettinger87e69122015-03-02 23:32:02 -08001933 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001934 0, /* tp_doc */
1935 (traverseproc)dequeiter_traverse, /* tp_traverse */
1936 0, /* tp_clear */
1937 0, /* tp_richcompare */
1938 0, /* tp_weaklistoffset */
1939 PyObject_SelfIter, /* tp_iter */
1940 (iternextfunc)dequereviter_next, /* tp_iternext */
1941 dequeiter_methods, /* tp_methods */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001942 0, /* tp_members */
1943 0, /* tp_getset */
1944 0, /* tp_base */
1945 0, /* tp_dict */
1946 0, /* tp_descr_get */
1947 0, /* tp_descr_set */
1948 0, /* tp_dictoffset */
1949 0, /* tp_init */
1950 0, /* tp_alloc */
1951 dequereviter_new, /* tp_new */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001952 0,
Raymond Hettinger1e5809f2004-03-18 11:04:57 +00001953};
1954
Guido van Rossum1968ad32006-02-25 22:38:04 +00001955/* defaultdict type *********************************************************/
1956
1957typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001958 PyDictObject dict;
1959 PyObject *default_factory;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001960} defdictobject;
1961
1962static PyTypeObject defdict_type; /* Forward */
1963
1964PyDoc_STRVAR(defdict_missing_doc,
1965"__missing__(key) # Called by __getitem__ for missing key; pseudo-code:\n\
Guido van Rossumd8faa362007-04-27 19:54:29 +00001966 if self.default_factory is None: raise KeyError((key,))\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00001967 self[key] = value = self.default_factory()\n\
1968 return value\n\
1969");
1970
1971static PyObject *
1972defdict_missing(defdictobject *dd, PyObject *key)
1973{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001974 PyObject *factory = dd->default_factory;
1975 PyObject *value;
1976 if (factory == NULL || factory == Py_None) {
1977 /* XXX Call dict.__missing__(key) */
1978 PyObject *tup;
1979 tup = PyTuple_Pack(1, key);
1980 if (!tup) return NULL;
1981 PyErr_SetObject(PyExc_KeyError, tup);
1982 Py_DECREF(tup);
1983 return NULL;
1984 }
Jeroen Demeyer7f41c8e2019-07-04 12:35:31 +02001985 value = _PyObject_CallNoArg(factory);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001986 if (value == NULL)
1987 return value;
1988 if (PyObject_SetItem((PyObject *)dd, key, value) < 0) {
1989 Py_DECREF(value);
1990 return NULL;
1991 }
1992 return value;
Guido van Rossum1968ad32006-02-25 22:38:04 +00001993}
1994
Brandt Bucher57c9d172020-03-06 09:24:08 -08001995static inline PyObject*
1996new_defdict(defdictobject *dd, PyObject *arg)
1997{
1998 return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd),
1999 dd->default_factory ? dd->default_factory : Py_None, arg, NULL);
2000}
2001
Guido van Rossum1968ad32006-02-25 22:38:04 +00002002PyDoc_STRVAR(defdict_copy_doc, "D.copy() -> a shallow copy of D.");
2003
2004static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302005defdict_copy(defdictobject *dd, PyObject *Py_UNUSED(ignored))
Guido van Rossum1968ad32006-02-25 22:38:04 +00002006{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002007 /* This calls the object's class. That only works for subclasses
2008 whose class constructor has the same signature. Subclasses that
2009 define a different constructor signature must override copy().
2010 */
Brandt Bucher57c9d172020-03-06 09:24:08 -08002011 return new_defdict(dd, (PyObject*)dd);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002012}
2013
2014static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302015defdict_reduce(defdictobject *dd, PyObject *Py_UNUSED(ignored))
Guido van Rossum1968ad32006-02-25 22:38:04 +00002016{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002017 /* __reduce__ must return a 5-tuple as follows:
Guido van Rossum1968ad32006-02-25 22:38:04 +00002018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002019 - factory function
2020 - tuple of args for the factory function
2021 - additional state (here None)
2022 - sequence iterator (here None)
2023 - dictionary iterator (yielding successive (key, value) pairs
Guido van Rossum1968ad32006-02-25 22:38:04 +00002024
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002025 This API is used by pickle.py and copy.py.
Guido van Rossum1968ad32006-02-25 22:38:04 +00002026
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002027 For this to be useful with pickle.py, the default_factory
2028 must be picklable; e.g., None, a built-in, or a global
2029 function in a module or package.
Guido van Rossum1968ad32006-02-25 22:38:04 +00002030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002031 Both shallow and deep copying are supported, but for deep
2032 copying, the default_factory must be deep-copyable; e.g. None,
2033 or a built-in (functions are not copyable at this time).
Guido van Rossum1968ad32006-02-25 22:38:04 +00002034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002035 This only works for subclasses as long as their constructor
2036 signature is compatible; the first argument must be the
2037 optional default_factory, defaulting to None.
2038 */
2039 PyObject *args;
2040 PyObject *items;
2041 PyObject *iter;
2042 PyObject *result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002043 _Py_IDENTIFIER(items);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002044
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002045 if (dd->default_factory == NULL || dd->default_factory == Py_None)
2046 args = PyTuple_New(0);
2047 else
2048 args = PyTuple_Pack(1, dd->default_factory);
2049 if (args == NULL)
2050 return NULL;
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002051 items = _PyObject_CallMethodIdNoArgs((PyObject *)dd, &PyId_items);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002052 if (items == NULL) {
2053 Py_DECREF(args);
2054 return NULL;
2055 }
2056 iter = PyObject_GetIter(items);
2057 if (iter == NULL) {
2058 Py_DECREF(items);
2059 Py_DECREF(args);
2060 return NULL;
2061 }
2062 result = PyTuple_Pack(5, Py_TYPE(dd), args,
2063 Py_None, Py_None, iter);
2064 Py_DECREF(iter);
2065 Py_DECREF(items);
2066 Py_DECREF(args);
2067 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00002068}
2069
2070static PyMethodDef defdict_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002071 {"__missing__", (PyCFunction)defdict_missing, METH_O,
2072 defdict_missing_doc},
2073 {"copy", (PyCFunction)defdict_copy, METH_NOARGS,
2074 defdict_copy_doc},
2075 {"__copy__", (PyCFunction)defdict_copy, METH_NOARGS,
2076 defdict_copy_doc},
2077 {"__reduce__", (PyCFunction)defdict_reduce, METH_NOARGS,
2078 reduce_doc},
Guido van Rossum48b069a2020-04-07 09:50:06 -07002079 {"__class_getitem__", (PyCFunction)Py_GenericAlias, METH_O|METH_CLASS,
2080 PyDoc_STR("See PEP 585")},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002081 {NULL}
Guido van Rossum1968ad32006-02-25 22:38:04 +00002082};
2083
2084static PyMemberDef defdict_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002085 {"default_factory", T_OBJECT,
2086 offsetof(defdictobject, default_factory), 0,
2087 PyDoc_STR("Factory for default value called by __missing__().")},
2088 {NULL}
Guido van Rossum1968ad32006-02-25 22:38:04 +00002089};
2090
2091static void
2092defdict_dealloc(defdictobject *dd)
2093{
INADA Naokia6296d32017-08-24 14:55:17 +09002094 /* bpo-31095: UnTrack is needed before calling any callbacks */
2095 PyObject_GC_UnTrack(dd);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002096 Py_CLEAR(dd->default_factory);
2097 PyDict_Type.tp_dealloc((PyObject *)dd);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002098}
2099
Guido van Rossum1968ad32006-02-25 22:38:04 +00002100static PyObject *
2101defdict_repr(defdictobject *dd)
2102{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002103 PyObject *baserepr;
2104 PyObject *defrepr;
2105 PyObject *result;
2106 baserepr = PyDict_Type.tp_repr((PyObject *)dd);
2107 if (baserepr == NULL)
2108 return NULL;
2109 if (dd->default_factory == NULL)
2110 defrepr = PyUnicode_FromString("None");
2111 else
2112 {
2113 int status = Py_ReprEnter(dd->default_factory);
2114 if (status != 0) {
Antoine Pitrouf5f1fe02012-02-15 02:42:46 +01002115 if (status < 0) {
2116 Py_DECREF(baserepr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002117 return NULL;
Antoine Pitrouf5f1fe02012-02-15 02:42:46 +01002118 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002119 defrepr = PyUnicode_FromString("...");
2120 }
2121 else
2122 defrepr = PyObject_Repr(dd->default_factory);
2123 Py_ReprLeave(dd->default_factory);
2124 }
2125 if (defrepr == NULL) {
2126 Py_DECREF(baserepr);
2127 return NULL;
2128 }
Serhiy Storchakab3a77962017-09-21 14:24:13 +03002129 result = PyUnicode_FromFormat("%s(%U, %U)",
2130 _PyType_Name(Py_TYPE(dd)),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002131 defrepr, baserepr);
2132 Py_DECREF(defrepr);
2133 Py_DECREF(baserepr);
2134 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00002135}
2136
Brandt Bucher57c9d172020-03-06 09:24:08 -08002137static PyObject*
2138defdict_or(PyObject* left, PyObject* right)
2139{
Brandt Bucher57c9d172020-03-06 09:24:08 -08002140 PyObject *self, *other;
Brandt Bucher1dd37942020-03-11 21:06:46 -07002141 if (PyObject_TypeCheck(left, &defdict_type)) {
Brandt Bucher57c9d172020-03-06 09:24:08 -08002142 self = left;
2143 other = right;
2144 }
2145 else {
2146 self = right;
2147 other = left;
2148 }
2149 if (!PyDict_Check(other)) {
2150 Py_RETURN_NOTIMPLEMENTED;
2151 }
2152 // Like copy(), this calls the object's class.
2153 // Override __or__/__ror__ for subclasses with different constructors.
2154 PyObject *new = new_defdict((defdictobject*)self, left);
2155 if (!new) {
2156 return NULL;
2157 }
2158 if (PyDict_Update(new, right)) {
2159 Py_DECREF(new);
2160 return NULL;
2161 }
2162 return new;
2163}
2164
2165static PyNumberMethods defdict_as_number = {
2166 .nb_or = defdict_or,
2167};
2168
Guido van Rossum1968ad32006-02-25 22:38:04 +00002169static int
2170defdict_traverse(PyObject *self, visitproc visit, void *arg)
2171{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002172 Py_VISIT(((defdictobject *)self)->default_factory);
2173 return PyDict_Type.tp_traverse(self, visit, arg);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002174}
2175
2176static int
2177defdict_tp_clear(defdictobject *dd)
2178{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002179 Py_CLEAR(dd->default_factory);
2180 return PyDict_Type.tp_clear((PyObject *)dd);
Guido van Rossum1968ad32006-02-25 22:38:04 +00002181}
2182
2183static int
2184defdict_init(PyObject *self, PyObject *args, PyObject *kwds)
2185{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002186 defdictobject *dd = (defdictobject *)self;
2187 PyObject *olddefault = dd->default_factory;
2188 PyObject *newdefault = NULL;
2189 PyObject *newargs;
2190 int result;
2191 if (args == NULL || !PyTuple_Check(args))
2192 newargs = PyTuple_New(0);
2193 else {
2194 Py_ssize_t n = PyTuple_GET_SIZE(args);
2195 if (n > 0) {
2196 newdefault = PyTuple_GET_ITEM(args, 0);
2197 if (!PyCallable_Check(newdefault) && newdefault != Py_None) {
2198 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger239aba72015-07-20 03:09:22 -04002199 "first argument must be callable or None");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002200 return -1;
2201 }
2202 }
2203 newargs = PySequence_GetSlice(args, 1, n);
2204 }
2205 if (newargs == NULL)
2206 return -1;
2207 Py_XINCREF(newdefault);
2208 dd->default_factory = newdefault;
2209 result = PyDict_Type.tp_init(self, newargs, kwds);
2210 Py_DECREF(newargs);
2211 Py_XDECREF(olddefault);
2212 return result;
Guido van Rossum1968ad32006-02-25 22:38:04 +00002213}
2214
2215PyDoc_STRVAR(defdict_doc,
Benjamin Peterson9cb33b72014-01-13 23:56:05 -05002216"defaultdict(default_factory[, ...]) --> dict with default factory\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00002217\n\
2218The default factory is called without arguments to produce\n\
2219a new value when a key is not present, in __getitem__ only.\n\
2220A defaultdict compares equal to a dict with the same items.\n\
Benjamin Peterson9cb33b72014-01-13 23:56:05 -05002221All remaining arguments are treated the same as if they were\n\
2222passed to the dict constructor, including keyword arguments.\n\
Guido van Rossum1968ad32006-02-25 22:38:04 +00002223");
2224
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002225/* See comment in xxsubtype.c */
2226#define DEFERRED_ADDRESS(ADDR) 0
2227
Guido van Rossum1968ad32006-02-25 22:38:04 +00002228static PyTypeObject defdict_type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002229 PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0)
2230 "collections.defaultdict", /* tp_name */
2231 sizeof(defdictobject), /* tp_basicsize */
2232 0, /* tp_itemsize */
2233 /* methods */
2234 (destructor)defdict_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002235 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002236 0, /* tp_getattr */
2237 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002238 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002239 (reprfunc)defdict_repr, /* tp_repr */
Brandt Bucher57c9d172020-03-06 09:24:08 -08002240 &defdict_as_number, /* tp_as_number */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002241 0, /* tp_as_sequence */
2242 0, /* tp_as_mapping */
2243 0, /* tp_hash */
2244 0, /* tp_call */
2245 0, /* tp_str */
2246 PyObject_GenericGetAttr, /* tp_getattro */
2247 0, /* tp_setattro */
2248 0, /* tp_as_buffer */
2249 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
2250 /* tp_flags */
2251 defdict_doc, /* tp_doc */
2252 defdict_traverse, /* tp_traverse */
2253 (inquiry)defdict_tp_clear, /* tp_clear */
2254 0, /* tp_richcompare */
2255 0, /* tp_weaklistoffset*/
2256 0, /* tp_iter */
2257 0, /* tp_iternext */
2258 defdict_methods, /* tp_methods */
2259 defdict_members, /* tp_members */
2260 0, /* tp_getset */
2261 DEFERRED_ADDRESS(&PyDict_Type), /* tp_base */
2262 0, /* tp_dict */
2263 0, /* tp_descr_get */
2264 0, /* tp_descr_set */
2265 0, /* tp_dictoffset */
2266 defdict_init, /* tp_init */
2267 PyType_GenericAlloc, /* tp_alloc */
2268 0, /* tp_new */
2269 PyObject_GC_Del, /* tp_free */
Guido van Rossum1968ad32006-02-25 22:38:04 +00002270};
2271
Raymond Hettinger96f34102010-12-15 16:30:37 +00002272/* helper function for Counter *********************************************/
2273
Raymond Hettingere9858042019-06-05 16:05:25 -07002274/*[clinic input]
2275_collections._count_elements
2276
2277 mapping: object
2278 iterable: object
2279 /
2280
2281Count elements in the iterable, updating the mapping
2282[clinic start generated code]*/
Raymond Hettinger96f34102010-12-15 16:30:37 +00002283
2284static PyObject *
Raymond Hettingere9858042019-06-05 16:05:25 -07002285_collections__count_elements_impl(PyObject *module, PyObject *mapping,
2286 PyObject *iterable)
2287/*[clinic end generated code: output=7e0c1789636b3d8f input=e79fad04534a0b45]*/
Raymond Hettinger96f34102010-12-15 16:30:37 +00002288{
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002289 _Py_IDENTIFIER(get);
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002290 _Py_IDENTIFIER(__setitem__);
Raymond Hettingere9858042019-06-05 16:05:25 -07002291 PyObject *it, *oldval;
Raymond Hettinger96f34102010-12-15 16:30:37 +00002292 PyObject *newval = NULL;
2293 PyObject *key = NULL;
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002294 PyObject *bound_get = NULL;
2295 PyObject *mapping_get;
2296 PyObject *dict_get;
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002297 PyObject *mapping_setitem;
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002298 PyObject *dict_setitem;
Raymond Hettinger96f34102010-12-15 16:30:37 +00002299
Raymond Hettinger96f34102010-12-15 16:30:37 +00002300 it = PyObject_GetIter(iterable);
2301 if (it == NULL)
2302 return NULL;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002303
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002304 /* Only take the fast path when get() and __setitem__()
2305 * have not been overridden.
2306 */
2307 mapping_get = _PyType_LookupId(Py_TYPE(mapping), &PyId_get);
2308 dict_get = _PyType_LookupId(&PyDict_Type, &PyId_get);
Raymond Hettinger2ff21902013-10-01 00:55:43 -07002309 mapping_setitem = _PyType_LookupId(Py_TYPE(mapping), &PyId___setitem__);
2310 dict_setitem = _PyType_LookupId(&PyDict_Type, &PyId___setitem__);
2311
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002312 if (mapping_get != NULL && mapping_get == dict_get &&
Oren Milman31aca4b2017-09-27 06:18:21 +03002313 mapping_setitem != NULL && mapping_setitem == dict_setitem &&
2314 PyDict_Check(mapping))
2315 {
Raymond Hettinger426e0522011-01-03 02:12:02 +00002316 while (1) {
Raymond Hettinger507d9972014-05-18 21:32:40 +01002317 /* Fast path advantages:
2318 1. Eliminate double hashing
2319 (by re-using the same hash for both the get and set)
2320 2. Avoid argument overhead of PyObject_CallFunctionObjArgs
2321 (argument tuple creation and parsing)
2322 3. Avoid indirection through a bound method object
2323 (creates another argument tuple)
2324 4. Avoid initial increment from zero
2325 (reuse an existing one-object instead)
2326 */
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002327 Py_hash_t hash;
2328
Raymond Hettinger426e0522011-01-03 02:12:02 +00002329 key = PyIter_Next(it);
Victor Stinnera154b5c2011-04-20 23:23:52 +02002330 if (key == NULL)
2331 break;
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002332
2333 if (!PyUnicode_CheckExact(key) ||
2334 (hash = ((PyASCIIObject *) key)->hash) == -1)
2335 {
2336 hash = PyObject_Hash(key);
Raymond Hettingerda2850f2015-02-27 12:42:54 -08002337 if (hash == -1)
Raymond Hettinger4b0b1ac2014-05-03 16:41:19 -07002338 goto done;
2339 }
2340
2341 oldval = _PyDict_GetItem_KnownHash(mapping, key, hash);
Raymond Hettinger426e0522011-01-03 02:12:02 +00002342 if (oldval == NULL) {
Serhiy Storchakaf0b311b2016-11-06 13:18:24 +02002343 if (PyErr_Occurred())
2344 goto done;
Serhiy Storchakaba85d692017-03-30 09:09:41 +03002345 if (_PyDict_SetItem_KnownHash(mapping, key, _PyLong_One, hash) < 0)
Raymond Hettinger507d9972014-05-18 21:32:40 +01002346 goto done;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002347 } else {
Serhiy Storchakaba85d692017-03-30 09:09:41 +03002348 newval = PyNumber_Add(oldval, _PyLong_One);
Raymond Hettinger426e0522011-01-03 02:12:02 +00002349 if (newval == NULL)
Raymond Hettinger507d9972014-05-18 21:32:40 +01002350 goto done;
Raymond Hettinger28c995d2015-08-14 02:07:41 -07002351 if (_PyDict_SetItem_KnownHash(mapping, key, newval, hash) < 0)
Raymond Hettinger507d9972014-05-18 21:32:40 +01002352 goto done;
Raymond Hettinger426e0522011-01-03 02:12:02 +00002353 Py_CLEAR(newval);
2354 }
2355 Py_DECREF(key);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002356 }
Raymond Hettinger426e0522011-01-03 02:12:02 +00002357 } else {
Victor Stinnere7f516c2013-11-06 23:52:55 +01002358 bound_get = _PyObject_GetAttrId(mapping, &PyId_get);
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002359 if (bound_get == NULL)
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002360 goto done;
2361
Raymond Hettinger426e0522011-01-03 02:12:02 +00002362 while (1) {
2363 key = PyIter_Next(it);
Victor Stinnera154b5c2011-04-20 23:23:52 +02002364 if (key == NULL)
2365 break;
Serhiy Storchakaba85d692017-03-30 09:09:41 +03002366 oldval = PyObject_CallFunctionObjArgs(bound_get, key, _PyLong_Zero, NULL);
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002367 if (oldval == NULL)
2368 break;
Serhiy Storchakaba85d692017-03-30 09:09:41 +03002369 newval = PyNumber_Add(oldval, _PyLong_One);
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002370 Py_DECREF(oldval);
2371 if (newval == NULL)
2372 break;
Raymond Hettinger28c995d2015-08-14 02:07:41 -07002373 if (PyObject_SetItem(mapping, key, newval) < 0)
Raymond Hettinger96f34102010-12-15 16:30:37 +00002374 break;
2375 Py_CLEAR(newval);
Raymond Hettinger426e0522011-01-03 02:12:02 +00002376 Py_DECREF(key);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002377 }
Raymond Hettinger96f34102010-12-15 16:30:37 +00002378 }
Raymond Hettinger426e0522011-01-03 02:12:02 +00002379
Raymond Hettinger224c87d2013-10-01 21:36:09 -07002380done:
Raymond Hettinger96f34102010-12-15 16:30:37 +00002381 Py_DECREF(it);
2382 Py_XDECREF(key);
2383 Py_XDECREF(newval);
Raymond Hettingercb1d96f2013-10-04 16:51:02 -07002384 Py_XDECREF(bound_get);
Raymond Hettinger96f34102010-12-15 16:30:37 +00002385 if (PyErr_Occurred())
2386 return NULL;
2387 Py_RETURN_NONE;
2388}
2389
Serhiy Storchaka052b2df2018-12-31 14:15:16 +02002390/* Helper function for namedtuple() ************************************/
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002391
2392typedef struct {
2393 PyObject_HEAD
2394 Py_ssize_t index;
2395 PyObject* doc;
2396} _tuplegetterobject;
2397
2398/*[clinic input]
2399@classmethod
2400_tuplegetter.__new__ as tuplegetter_new
2401
2402 index: Py_ssize_t
2403 doc: object
2404 /
2405[clinic start generated code]*/
2406
2407static PyObject *
2408tuplegetter_new_impl(PyTypeObject *type, Py_ssize_t index, PyObject *doc)
2409/*[clinic end generated code: output=014be444ad80263f input=87c576a5bdbc0bbb]*/
2410{
2411 _tuplegetterobject* self;
2412 self = (_tuplegetterobject *)type->tp_alloc(type, 0);
2413 if (self == NULL) {
2414 return NULL;
2415 }
2416 self->index = index;
2417 Py_INCREF(doc);
2418 self->doc = doc;
2419 return (PyObject *)self;
2420}
2421
2422static PyObject *
Serhiy Storchaka052b2df2018-12-31 14:15:16 +02002423tuplegetter_descr_get(PyObject *self, PyObject *obj, PyObject *type)
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002424{
Serhiy Storchaka052b2df2018-12-31 14:15:16 +02002425 Py_ssize_t index = ((_tuplegetterobject*)self)->index;
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002426 PyObject *result;
Serhiy Storchaka052b2df2018-12-31 14:15:16 +02002427
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002428 if (obj == NULL) {
2429 Py_INCREF(self);
2430 return self;
2431 }
2432 if (!PyTuple_Check(obj)) {
2433 if (obj == Py_None) {
2434 Py_INCREF(self);
2435 return self;
2436 }
2437 PyErr_Format(PyExc_TypeError,
Serhiy Storchakad53fe5f2019-03-13 22:59:55 +02002438 "descriptor for index '%zd' for tuple subclasses "
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002439 "doesn't apply to '%s' object",
Serhiy Storchaka052b2df2018-12-31 14:15:16 +02002440 index,
Victor Stinnerdaa97562020-02-07 03:37:06 +01002441 Py_TYPE(obj)->tp_name);
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002442 return NULL;
2443 }
2444
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002445 if (!valid_index(index, PyTuple_GET_SIZE(obj))) {
2446 PyErr_SetString(PyExc_IndexError, "tuple index out of range");
2447 return NULL;
2448 }
2449
2450 result = PyTuple_GET_ITEM(obj, index);
2451 Py_INCREF(result);
2452 return result;
2453}
2454
2455static int
Serhiy Storchaka052b2df2018-12-31 14:15:16 +02002456tuplegetter_descr_set(PyObject *self, PyObject *obj, PyObject *value)
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002457{
2458 if (value == NULL) {
2459 PyErr_SetString(PyExc_AttributeError, "can't delete attribute");
2460 } else {
2461 PyErr_SetString(PyExc_AttributeError, "can't set attribute");
2462 }
2463 return -1;
2464}
2465
2466static int
2467tuplegetter_traverse(PyObject *self, visitproc visit, void *arg)
2468{
2469 _tuplegetterobject *tuplegetter = (_tuplegetterobject *)self;
2470 Py_VISIT(tuplegetter->doc);
2471 return 0;
2472}
2473
2474static int
2475tuplegetter_clear(PyObject *self)
2476{
2477 _tuplegetterobject *tuplegetter = (_tuplegetterobject *)self;
2478 Py_CLEAR(tuplegetter->doc);
2479 return 0;
2480}
2481
2482static void
2483tuplegetter_dealloc(_tuplegetterobject *self)
2484{
2485 PyObject_GC_UnTrack(self);
2486 tuplegetter_clear((PyObject*)self);
2487 Py_TYPE(self)->tp_free((PyObject*)self);
2488}
2489
Joe Jevnikf36f8922019-02-21 16:00:40 -05002490static PyObject*
Serhiy Storchakaadfffc72019-03-05 18:41:09 +02002491tuplegetter_reduce(_tuplegetterobject *self, PyObject *Py_UNUSED(ignored))
Joe Jevnikf36f8922019-02-21 16:00:40 -05002492{
2493 return Py_BuildValue("(O(nO))", (PyObject*) Py_TYPE(self), self->index, self->doc);
2494}
2495
Ammar Askara86b5222020-04-14 23:36:08 -07002496static PyObject*
2497tuplegetter_repr(_tuplegetterobject *self)
2498{
2499 return PyUnicode_FromFormat("%s(%zd, %R)",
2500 _PyType_Name(Py_TYPE(self)),
2501 self->index, self->doc);
2502}
2503
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002504
2505static PyMemberDef tuplegetter_members[] = {
2506 {"__doc__", T_OBJECT, offsetof(_tuplegetterobject, doc), 0},
2507 {0}
2508};
2509
Joe Jevnikf36f8922019-02-21 16:00:40 -05002510static PyMethodDef tuplegetter_methods[] = {
Serhiy Storchakaadfffc72019-03-05 18:41:09 +02002511 {"__reduce__", (PyCFunction)tuplegetter_reduce, METH_NOARGS, NULL},
Joe Jevnikf36f8922019-02-21 16:00:40 -05002512 {NULL},
2513};
2514
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002515static PyTypeObject tuplegetter_type = {
2516 PyVarObject_HEAD_INIT(NULL, 0)
2517 "_collections._tuplegetter", /* tp_name */
2518 sizeof(_tuplegetterobject), /* tp_basicsize */
2519 0, /* tp_itemsize */
2520 /* methods */
2521 (destructor)tuplegetter_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002522 0, /* tp_vectorcall_offset */
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002523 0, /* tp_getattr */
2524 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002525 0, /* tp_as_async */
Ammar Askara86b5222020-04-14 23:36:08 -07002526 (reprfunc)tuplegetter_repr, /* tp_repr */
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002527 0, /* tp_as_number */
2528 0, /* tp_as_sequence */
2529 0, /* tp_as_mapping */
2530 0, /* tp_hash */
2531 0, /* tp_call */
2532 0, /* tp_str */
2533 0, /* tp_getattro */
2534 0, /* tp_setattro */
2535 0, /* tp_as_buffer */
2536 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
2537 0, /* tp_doc */
2538 (traverseproc)tuplegetter_traverse, /* tp_traverse */
2539 (inquiry)tuplegetter_clear, /* tp_clear */
2540 0, /* tp_richcompare */
2541 0, /* tp_weaklistoffset */
2542 0, /* tp_iter */
2543 0, /* tp_iternext */
Joe Jevnikf36f8922019-02-21 16:00:40 -05002544 tuplegetter_methods, /* tp_methods */
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002545 tuplegetter_members, /* tp_members */
2546 0, /* tp_getset */
2547 0, /* tp_base */
2548 0, /* tp_dict */
Serhiy Storchaka052b2df2018-12-31 14:15:16 +02002549 tuplegetter_descr_get, /* tp_descr_get */
2550 tuplegetter_descr_set, /* tp_descr_set */
Pablo Galindo3f5fc702018-12-30 09:24:03 +00002551 0, /* tp_dictoffset */
2552 0, /* tp_init */
2553 0, /* tp_alloc */
2554 tuplegetter_new, /* tp_new */
2555 0,
2556};
2557
2558
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002559/* module level code ********************************************************/
2560
Dong-hee Na77248a22020-03-20 01:16:04 +09002561PyDoc_STRVAR(collections_doc,
Guido van Rossum1968ad32006-02-25 22:38:04 +00002562"High performance data structures.\n\
2563- deque: ordered collection accessible from endpoints only\n\
2564- defaultdict: dict subclass with a default value factory\n\
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002565");
2566
Dong-hee Na77248a22020-03-20 01:16:04 +09002567static struct PyMethodDef collections_methods[] = {
Raymond Hettingere9858042019-06-05 16:05:25 -07002568 _COLLECTIONS__COUNT_ELEMENTS_METHODDEF
Raymond Hettinger96f34102010-12-15 16:30:37 +00002569 {NULL, NULL} /* sentinel */
2570};
Martin v. Löwis1a214512008-06-11 05:26:20 +00002571
Dong-hee Na77248a22020-03-20 01:16:04 +09002572static int
2573collections_exec(PyObject *module) {
2574 PyTypeObject *typelist[] = {
2575 &deque_type,
2576 &defdict_type,
2577 &PyODict_Type,
2578 &dequeiter_type,
2579 &dequereviter_type,
Dong-hee Na05e4a292020-03-23 01:17:34 +09002580 &tuplegetter_type
Dong-hee Na77248a22020-03-20 01:16:04 +09002581 };
2582
2583 defdict_type.tp_base = &PyDict_Type;
2584
Dong-hee Na05e4a292020-03-23 01:17:34 +09002585 for (size_t i = 0; i < Py_ARRAY_LENGTH(typelist); i++) {
2586 if (PyModule_AddType(module, typelist[i]) < 0) {
Dong-hee Na77248a22020-03-20 01:16:04 +09002587 return -1;
2588 }
2589 }
2590
2591 return 0;
2592}
2593
2594static struct PyModuleDef_Slot collections_slots[] = {
2595 {Py_mod_exec, collections_exec},
2596 {0, NULL}
2597};
2598
Martin v. Löwis1a214512008-06-11 05:26:20 +00002599static struct PyModuleDef _collectionsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002600 PyModuleDef_HEAD_INIT,
2601 "_collections",
Dong-hee Na77248a22020-03-20 01:16:04 +09002602 collections_doc,
2603 0,
2604 collections_methods,
2605 collections_slots,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002606 NULL,
2607 NULL,
2608 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002609};
2610
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002611PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002612PyInit__collections(void)
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002613{
Dong-hee Na77248a22020-03-20 01:16:04 +09002614 return PyModuleDef_Init(&_collectionsmodule);
Raymond Hettinger756b3f32004-01-29 06:37:52 +00002615}