1 #include "Python.h"
2 #include "pycore_call.h"          // _PyObject_CallNoArgs()
3 #include "pycore_dict.h"          // _PyDict_GetItem_KnownHash()
4 #include "pycore_long.h"          // _PyLong_GetZero()
5 #include "pycore_moduleobject.h"  // _PyModule_GetState()
6 #include "pycore_pyatomic_ft_wrappers.h"
7 #include "pycore_typeobject.h"    // _PyType_GetModuleState()
8 
9 #include <stddef.h>
10 
11 typedef struct {
12     PyTypeObject *deque_type;
13     PyTypeObject *defdict_type;
14     PyTypeObject *dequeiter_type;
15     PyTypeObject *dequereviter_type;
16     PyTypeObject *tuplegetter_type;
17 } collections_state;
18 
19 static inline collections_state *
get_module_state(PyObject * mod)20 get_module_state(PyObject *mod)
21 {
22     void *state = _PyModule_GetState(mod);
23     assert(state != NULL);
24     return (collections_state *)state;
25 }
26 
27 static inline collections_state *
get_module_state_by_cls(PyTypeObject * cls)28 get_module_state_by_cls(PyTypeObject *cls)
29 {
30     void *state = _PyType_GetModuleState(cls);
31     assert(state != NULL);
32     return (collections_state *)state;
33 }
34 
35 static struct PyModuleDef _collectionsmodule;
36 
37 static inline collections_state *
find_module_state_by_def(PyTypeObject * type)38 find_module_state_by_def(PyTypeObject *type)
39 {
40     PyObject *mod = PyType_GetModuleByDef(type, &_collectionsmodule);
41     assert(mod != NULL);
42     return get_module_state(mod);
43 }
44 
45 /*[clinic input]
46 module _collections
47 class _tuplegetter "_tuplegetterobject *" "clinic_state()->tuplegetter_type"
48 class _collections.deque "dequeobject *" "clinic_state()->deque_type"
49 [clinic start generated code]*/
50 /*[clinic end generated code: output=da39a3ee5e6b4b0d input=a033cc2a8476b3f1]*/
51 
52 typedef struct dequeobject dequeobject;
53 
54 /* We can safely assume type to be the defining class,
55  * since tuplegetter is not a base type */
56 #define clinic_state() (get_module_state_by_cls(type))
57 #include "clinic/_collectionsmodule.c.h"
58 #undef clinic_state
59 
60 /*[python input]
61 class dequeobject_converter(self_converter):
62     type = "dequeobject *"
63 [python start generated code]*/
64 /*[python end generated code: output=da39a3ee5e6b4b0d input=b6ae4a3ff852be2f]*/
65 
66 /* collections module implementation of a deque() datatype
67    Written and maintained by Raymond D. Hettinger <python@rcn.com>
68 */
69 
70 /* The block length may be set to any number over 1.  Larger numbers
71  * reduce the number of calls to the memory allocator, give faster
72  * indexing and rotation, and reduce the link to data overhead ratio.
73  * Making the block length a power of two speeds-up the modulo
74  * and division calculations in deque_item() and deque_ass_item().
75  */
76 
77 #define BLOCKLEN 64
78 #define CENTER ((BLOCKLEN - 1) / 2)
79 #define MAXFREEBLOCKS 16
80 
81 /* Data for deque objects is stored in a doubly-linked list of fixed
82  * length blocks.  This assures that appends or pops never move any
83  * other data elements besides the one being appended or popped.
84  *
85  * Another advantage is that it completely avoids use of realloc(),
86  * resulting in more predictable performance.
87  *
88  * Textbook implementations of doubly-linked lists store one datum
89  * per link, but that gives them a 200% memory overhead (a prev and
90  * next link for each datum) and it costs one malloc() call per data
91  * element.  By using fixed-length blocks, the link to data ratio is
92  * significantly improved and there are proportionally fewer calls
93  * to malloc() and free().  The data blocks of consecutive pointers
94  * also improve cache locality.
95  *
96  * The list of blocks is never empty, so d.leftblock and d.rightblock
97  * are never equal to NULL.  The list is not circular.
98  *
99  * A deque d's first element is at d.leftblock[leftindex]
100  * and its last element is at d.rightblock[rightindex].
101  *
102  * Unlike Python slice indices, these indices are inclusive on both
103  * ends.  This makes the algorithms for left and right operations
104  * more symmetrical and it simplifies the design.
105  *
106  * The indices, d.leftindex and d.rightindex are always in the range:
107  *     0 <= index < BLOCKLEN
108  *
109  * And their exact relationship is:
110  *     (d.leftindex + d.len - 1) % BLOCKLEN == d.rightindex
111  *
112  * Whenever d.leftblock == d.rightblock, then:
113  *     d.leftindex + d.len - 1 == d.rightindex
114  *
115  * However, when d.leftblock != d.rightblock, the d.leftindex and
116  * d.rightindex become indices into distinct blocks and either may
117  * be larger than the other.
118  *
119  * Empty deques have:
120  *     d.len == 0
121  *     d.leftblock == d.rightblock
122  *     d.leftindex == CENTER + 1
123  *     d.rightindex == CENTER
124  *
125  * Checking for d.len == 0 is the intended way to see whether d is empty.
126  */
127 
128 typedef struct BLOCK {
129     struct BLOCK *leftlink;
130     PyObject *data[BLOCKLEN];
131     struct BLOCK *rightlink;
132 } block;
133 
134 struct dequeobject {
135     PyObject_VAR_HEAD
136     block *leftblock;
137     block *rightblock;
138     Py_ssize_t leftindex;       /* 0 <= leftindex < BLOCKLEN */
139     Py_ssize_t rightindex;      /* 0 <= rightindex < BLOCKLEN */
140     size_t state;               /* incremented whenever the indices move */
141     Py_ssize_t maxlen;          /* maxlen is -1 for unbounded deques */
142     Py_ssize_t numfreeblocks;
143     block *freeblocks[MAXFREEBLOCKS];
144     PyObject *weakreflist;
145 };
146 
147 /* For debug builds, add error checking to track the endpoints
148  * in the chain of links.  The goal is to make sure that link
149  * assignments only take place at endpoints so that links already
150  * in use do not get overwritten.
151  *
152  * CHECK_END should happen before each assignment to a block's link field.
153  * MARK_END should happen whenever a link field becomes a new endpoint.
154  * This happens when new blocks are added or whenever an existing
155  * block is freed leaving another existing block as the new endpoint.
156  */
157 
158 #ifndef NDEBUG
159 #define MARK_END(link)  link = NULL;
160 #define CHECK_END(link) assert(link == NULL);
161 #define CHECK_NOT_END(link) assert(link != NULL);
162 #else
163 #define MARK_END(link)
164 #define CHECK_END(link)
165 #define CHECK_NOT_END(link)
166 #endif
167 
168 /* A simple freelisting scheme is used to minimize calls to the memory
169    allocator.  It accommodates common use cases where new blocks are being
170    added at about the same rate as old blocks are being freed.
171  */
172 
173 static inline block *
newblock(dequeobject * deque)174 newblock(dequeobject *deque) {
175     block *b;
176     if (deque->numfreeblocks) {
177         deque->numfreeblocks--;
178         return deque->freeblocks[deque->numfreeblocks];
179     }
180     b = PyMem_Malloc(sizeof(block));
181     if (b != NULL) {
182         return b;
183     }
184     PyErr_NoMemory();
185     return NULL;
186 }
187 
188 static inline void
freeblock(dequeobject * deque,block * b)189 freeblock(dequeobject *deque, block *b)
190 {
191     if (deque->numfreeblocks < MAXFREEBLOCKS) {
192         deque->freeblocks[deque->numfreeblocks] = b;
193         deque->numfreeblocks++;
194     } else {
195         PyMem_Free(b);
196     }
197 }
198 
199 static PyObject *
deque_new(PyTypeObject * type,PyObject * args,PyObject * kwds)200 deque_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
201 {
202     dequeobject *deque;
203     block *b;
204 
205     /* create dequeobject structure */
206     deque = (dequeobject *)type->tp_alloc(type, 0);
207     if (deque == NULL)
208         return NULL;
209 
210     b = newblock(deque);
211     if (b == NULL) {
212         Py_DECREF(deque);
213         return NULL;
214     }
215     MARK_END(b->leftlink);
216     MARK_END(b->rightlink);
217 
218     assert(BLOCKLEN >= 2);
219     Py_SET_SIZE(deque, 0);
220     deque->leftblock = b;
221     deque->rightblock = b;
222     deque->leftindex = CENTER + 1;
223     deque->rightindex = CENTER;
224     deque->state = 0;
225     deque->maxlen = -1;
226     deque->numfreeblocks = 0;
227     deque->weakreflist = NULL;
228 
229     return (PyObject *)deque;
230 }
231 
232 /*[clinic input]
233 @critical_section
234 _collections.deque.pop as deque_pop
235 
236     deque: dequeobject
237 
238 Remove and return the rightmost element.
239 [clinic start generated code]*/
240 
241 static PyObject *
deque_pop_impl(dequeobject * deque)242 deque_pop_impl(dequeobject *deque)
243 /*[clinic end generated code: output=2e5f7890c4251f07 input=55c5b6a8ad51d72f]*/
244 {
245     PyObject *item;
246     block *prevblock;
247 
248     if (Py_SIZE(deque) == 0) {
249         PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
250         return NULL;
251     }
252     item = deque->rightblock->data[deque->rightindex];
253     deque->rightindex--;
254     Py_SET_SIZE(deque, Py_SIZE(deque) - 1);
255     deque->state++;
256 
257     if (deque->rightindex < 0) {
258         if (Py_SIZE(deque)) {
259             prevblock = deque->rightblock->leftlink;
260             assert(deque->leftblock != deque->rightblock);
261             freeblock(deque, deque->rightblock);
262             CHECK_NOT_END(prevblock);
263             MARK_END(prevblock->rightlink);
264             deque->rightblock = prevblock;
265             deque->rightindex = BLOCKLEN - 1;
266         } else {
267             assert(deque->leftblock == deque->rightblock);
268             assert(deque->leftindex == deque->rightindex+1);
269             /* re-center instead of freeing a block */
270             deque->leftindex = CENTER + 1;
271             deque->rightindex = CENTER;
272         }
273     }
274     return item;
275 }
276 
277 /*[clinic input]
278 @critical_section
279 _collections.deque.popleft as deque_popleft
280 
281      deque: dequeobject
282 
283 Remove and return the leftmost element.
284 [clinic start generated code]*/
285 
286 static PyObject *
deque_popleft_impl(dequeobject * deque)287 deque_popleft_impl(dequeobject *deque)
288 /*[clinic end generated code: output=62b154897097ff68 input=1571ce88fe3053de]*/
289 {
290     PyObject *item;
291     block *prevblock;
292 
293     if (Py_SIZE(deque) == 0) {
294         PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
295         return NULL;
296     }
297     assert(deque->leftblock != NULL);
298     item = deque->leftblock->data[deque->leftindex];
299     deque->leftindex++;
300     Py_SET_SIZE(deque, Py_SIZE(deque) - 1);
301     deque->state++;
302 
303     if (deque->leftindex == BLOCKLEN) {
304         if (Py_SIZE(deque)) {
305             assert(deque->leftblock != deque->rightblock);
306             prevblock = deque->leftblock->rightlink;
307             freeblock(deque, deque->leftblock);
308             CHECK_NOT_END(prevblock);
309             MARK_END(prevblock->leftlink);
310             deque->leftblock = prevblock;
311             deque->leftindex = 0;
312         } else {
313             assert(deque->leftblock == deque->rightblock);
314             assert(deque->leftindex == deque->rightindex+1);
315             /* re-center instead of freeing a block */
316             deque->leftindex = CENTER + 1;
317             deque->rightindex = CENTER;
318         }
319     }
320     return item;
321 }
322 
323 /* The deque's size limit is d.maxlen.  The limit can be zero or positive.
324  * If there is no limit, then d.maxlen == -1.
325  *
326  * After an item is added to a deque, we check to see if the size has
327  * grown past the limit. If it has, we get the size back down to the limit
328  * by popping an item off of the opposite end.  The methods that can
329  * trigger this are append(), appendleft(), extend(), and extendleft().
330  *
331  * The macro to check whether a deque needs to be trimmed uses a single
332  * unsigned test that returns true whenever 0 <= maxlen < Py_SIZE(deque).
333  */
334 
335 #define NEEDS_TRIM(deque, maxlen) ((size_t)(maxlen) < (size_t)(Py_SIZE(deque)))
336 
337 static inline int
deque_append_lock_held(dequeobject * deque,PyObject * item,Py_ssize_t maxlen)338 deque_append_lock_held(dequeobject *deque, PyObject *item, Py_ssize_t maxlen)
339 {
340     if (deque->rightindex == BLOCKLEN - 1) {
341         block *b = newblock(deque);
342         if (b == NULL)
343             return -1;
344         b->leftlink = deque->rightblock;
345         CHECK_END(deque->rightblock->rightlink);
346         deque->rightblock->rightlink = b;
347         deque->rightblock = b;
348         MARK_END(b->rightlink);
349         deque->rightindex = -1;
350     }
351     Py_SET_SIZE(deque, Py_SIZE(deque) + 1);
352     deque->rightindex++;
353     deque->rightblock->data[deque->rightindex] = item;
354     if (NEEDS_TRIM(deque, maxlen)) {
355         PyObject *olditem = deque_popleft_impl(deque);
356         Py_DECREF(olditem);
357     } else {
358         deque->state++;
359     }
360     return 0;
361 }
362 
363 /*[clinic input]
364 @critical_section
365 _collections.deque.append as deque_append
366 
367     deque: dequeobject
368     item: object
369     /
370 
371 Add an element to the right side of the deque.
372 [clinic start generated code]*/
373 
374 static PyObject *
deque_append_impl(dequeobject * deque,PyObject * item)375 deque_append_impl(dequeobject *deque, PyObject *item)
376 /*[clinic end generated code: output=9c7bcb8b599c6362 input=b0eeeb09b9f5cf18]*/
377 {
378     if (deque_append_lock_held(deque, Py_NewRef(item), deque->maxlen) < 0)
379         return NULL;
380     Py_RETURN_NONE;
381 }
382 
383 static inline int
deque_appendleft_lock_held(dequeobject * deque,PyObject * item,Py_ssize_t maxlen)384 deque_appendleft_lock_held(dequeobject *deque, PyObject *item,
385                            Py_ssize_t maxlen)
386 {
387     if (deque->leftindex == 0) {
388         block *b = newblock(deque);
389         if (b == NULL)
390             return -1;
391         b->rightlink = deque->leftblock;
392         CHECK_END(deque->leftblock->leftlink);
393         deque->leftblock->leftlink = b;
394         deque->leftblock = b;
395         MARK_END(b->leftlink);
396         deque->leftindex = BLOCKLEN;
397     }
398     Py_SET_SIZE(deque, Py_SIZE(deque) + 1);
399     deque->leftindex--;
400     deque->leftblock->data[deque->leftindex] = item;
401     if (NEEDS_TRIM(deque, maxlen)) {
402         PyObject *olditem = deque_pop_impl(deque);
403         Py_DECREF(olditem);
404     } else {
405         deque->state++;
406     }
407     return 0;
408 }
409 
410 /*[clinic input]
411 @critical_section
412 _collections.deque.appendleft as deque_appendleft
413 
414     deque: dequeobject
415     item: object
416     /
417 
418 Add an element to the left side of the deque.
419 [clinic start generated code]*/
420 
421 static PyObject *
deque_appendleft_impl(dequeobject * deque,PyObject * item)422 deque_appendleft_impl(dequeobject *deque, PyObject *item)
423 /*[clinic end generated code: output=9a192edbcd0f20db input=236c2fbceaf08e14]*/
424 {
425     if (deque_appendleft_lock_held(deque, Py_NewRef(item), deque->maxlen) < 0)
426         return NULL;
427     Py_RETURN_NONE;
428 }
429 
430 static PyObject*
finalize_iterator(PyObject * it)431 finalize_iterator(PyObject *it)
432 {
433     if (PyErr_Occurred()) {
434         if (PyErr_ExceptionMatches(PyExc_StopIteration))
435             PyErr_Clear();
436         else {
437             Py_DECREF(it);
438             return NULL;
439         }
440     }
441     Py_DECREF(it);
442     Py_RETURN_NONE;
443 }
444 
445 /* Run an iterator to exhaustion.  Shortcut for
446    the extend/extendleft methods when maxlen == 0. */
447 static PyObject*
consume_iterator(PyObject * it)448 consume_iterator(PyObject *it)
449 {
450     PyObject *(*iternext)(PyObject *);
451     PyObject *item;
452 
453     iternext = *Py_TYPE(it)->tp_iternext;
454     while ((item = iternext(it)) != NULL) {
455         Py_DECREF(item);
456     }
457     return finalize_iterator(it);
458 }
459 
460 /*[clinic input]
461 @critical_section
462 _collections.deque.extend as deque_extend
463 
464     deque: dequeobject
465     iterable: object
466     /
467 
468 Extend the right side of the deque with elements from the iterable.
469 [clinic start generated code]*/
470 
471 static PyObject *
deque_extend_impl(dequeobject * deque,PyObject * iterable)472 deque_extend_impl(dequeobject *deque, PyObject *iterable)
473 /*[clinic end generated code: output=8b5ffa57ce82d980 input=85861954127c81da]*/
474 {
475     PyObject *it, *item;
476     PyObject *(*iternext)(PyObject *);
477     Py_ssize_t maxlen = deque->maxlen;
478 
479     /* Handle case where id(deque) == id(iterable) */
480     if ((PyObject *)deque == iterable) {
481         PyObject *result;
482         PyObject *s = PySequence_List(iterable);
483         if (s == NULL)
484             return NULL;
485         result = deque_extend(deque, s);
486         Py_DECREF(s);
487         return result;
488     }
489 
490     it = PyObject_GetIter(iterable);
491     if (it == NULL)
492         return NULL;
493 
494     if (maxlen == 0)
495         return consume_iterator(it);
496 
497     /* Space saving heuristic.  Start filling from the left */
498     if (Py_SIZE(deque) == 0) {
499         assert(deque->leftblock == deque->rightblock);
500         assert(deque->leftindex == deque->rightindex+1);
501         deque->leftindex = 1;
502         deque->rightindex = 0;
503     }
504 
505     iternext = *Py_TYPE(it)->tp_iternext;
506     while ((item = iternext(it)) != NULL) {
507         if (deque_append_lock_held(deque, item, maxlen) == -1) {
508             Py_DECREF(item);
509             Py_DECREF(it);
510             return NULL;
511         }
512     }
513     return finalize_iterator(it);
514 }
515 
516 /*[clinic input]
517 @critical_section
518 _collections.deque.extendleft as deque_extendleft
519 
520     deque: dequeobject
521     iterable: object
522     /
523 
524 Extend the left side of the deque with elements from the iterable.
525 [clinic start generated code]*/
526 
527 static PyObject *
deque_extendleft_impl(dequeobject * deque,PyObject * iterable)528 deque_extendleft_impl(dequeobject *deque, PyObject *iterable)
529 /*[clinic end generated code: output=ba44191aa8e35a26 input=640dabd086115689]*/
530 {
531     PyObject *it, *item;
532     PyObject *(*iternext)(PyObject *);
533     Py_ssize_t maxlen = deque->maxlen;
534 
535     /* Handle case where id(deque) == id(iterable) */
536     if ((PyObject *)deque == iterable) {
537         PyObject *result;
538         PyObject *s = PySequence_List(iterable);
539         if (s == NULL)
540             return NULL;
541         result = deque_extendleft_impl(deque, s);
542         Py_DECREF(s);
543         return result;
544     }
545 
546     it = PyObject_GetIter(iterable);
547     if (it == NULL)
548         return NULL;
549 
550     if (maxlen == 0)
551         return consume_iterator(it);
552 
553     /* Space saving heuristic.  Start filling from the right */
554     if (Py_SIZE(deque) == 0) {
555         assert(deque->leftblock == deque->rightblock);
556         assert(deque->leftindex == deque->rightindex+1);
557         deque->leftindex = BLOCKLEN - 1;
558         deque->rightindex = BLOCKLEN - 2;
559     }
560 
561     iternext = *Py_TYPE(it)->tp_iternext;
562     while ((item = iternext(it)) != NULL) {
563         if (deque_appendleft_lock_held(deque, item, maxlen) == -1) {
564             Py_DECREF(item);
565             Py_DECREF(it);
566             return NULL;
567         }
568     }
569     return finalize_iterator(it);
570 }
571 
572 static PyObject *
deque_inplace_concat(dequeobject * deque,PyObject * other)573 deque_inplace_concat(dequeobject *deque, PyObject *other)
574 {
575     PyObject *result;
576 
577     // deque_extend is thread-safe
578     result = deque_extend(deque, other);
579     if (result == NULL)
580         return result;
581     Py_INCREF(deque);
582     Py_DECREF(result);
583     return (PyObject *)deque;
584 }
585 
586 /*[clinic input]
587 @critical_section
588 _collections.deque.copy as deque_copy
589 
590     deque: dequeobject
591 
592 Return a shallow copy of a deque.
593 [clinic start generated code]*/
594 
595 static PyObject *
deque_copy_impl(dequeobject * deque)596 deque_copy_impl(dequeobject *deque)
597 /*[clinic end generated code: output=6409b3d1ad2898b5 input=51d2ed1a23bab5e2]*/
598 {
599     PyObject *result;
600     dequeobject *old_deque = (dequeobject *)deque;
601     collections_state *state = find_module_state_by_def(Py_TYPE(deque));
602     if (Py_IS_TYPE(deque, state->deque_type)) {
603         dequeobject *new_deque;
604         PyObject *rv;
605 
606         new_deque = (dequeobject *)deque_new(state->deque_type,
607                                              (PyObject *)NULL, (PyObject *)NULL);
608         if (new_deque == NULL)
609             return NULL;
610         new_deque->maxlen = old_deque->maxlen;
611         /* Fast path for the deque_repeat() common case where len(deque) == 1
612          *
613          * It's safe to not acquire the per-object lock for new_deque; it's
614          * invisible to other threads.
615          */
616         if (Py_SIZE(deque) == 1) {
617             PyObject *item = old_deque->leftblock->data[old_deque->leftindex];
618             rv = deque_append_impl(new_deque, item);
619         } else {
620             rv = deque_extend_impl(new_deque, (PyObject *)deque);
621         }
622         if (rv != NULL) {
623             Py_DECREF(rv);
624             return (PyObject *)new_deque;
625         }
626         Py_DECREF(new_deque);
627         return NULL;
628     }
629     if (old_deque->maxlen < 0)
630         result = PyObject_CallOneArg((PyObject *)(Py_TYPE(deque)),
631                                      (PyObject *)deque);
632     else
633         result = PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "Oi",
634                                        deque, old_deque->maxlen, NULL);
635     if (result != NULL && !PyObject_TypeCheck(result, state->deque_type)) {
636         PyErr_Format(PyExc_TypeError,
637                      "%.200s() must return a deque, not %.200s",
638                      Py_TYPE(deque)->tp_name, Py_TYPE(result)->tp_name);
639         Py_DECREF(result);
640         return NULL;
641     }
642     return result;
643 }
644 
645 /*[clinic input]
646 @critical_section
647 _collections.deque.__copy__ as deque___copy__ = _collections.deque.copy
648 
649 Return a shallow copy of a deque.
650 [clinic start generated code]*/
651 
652 static PyObject *
deque___copy___impl(dequeobject * deque)653 deque___copy___impl(dequeobject *deque)
654 /*[clinic end generated code: output=7c5821504342bf23 input=f5464036f9686a55]*/
655 {
656     return deque_copy_impl(deque);
657 }
658 
659 static PyObject *
deque_concat_lock_held(dequeobject * deque,PyObject * other)660 deque_concat_lock_held(dequeobject *deque, PyObject *other)
661 {
662     PyObject *new_deque, *result;
663     int rv;
664 
665     collections_state *state = find_module_state_by_def(Py_TYPE(deque));
666     rv = PyObject_IsInstance(other, (PyObject *)state->deque_type);
667     if (rv <= 0) {
668         if (rv == 0) {
669             PyErr_Format(PyExc_TypeError,
670                          "can only concatenate deque (not \"%.200s\") to deque",
671                          Py_TYPE(other)->tp_name);
672         }
673         return NULL;
674     }
675 
676     new_deque = deque_copy_impl(deque);
677     if (new_deque == NULL)
678         return NULL;
679 
680     // It's safe to not acquire the per-object lock for new_deque; it's
681     // invisible to other threads.
682     result = deque_extend_impl((dequeobject *)new_deque, other);
683     if (result == NULL) {
684         Py_DECREF(new_deque);
685         return NULL;
686     }
687     Py_DECREF(result);
688     return new_deque;
689 }
690 
691 static PyObject *
deque_concat(dequeobject * deque,PyObject * other)692 deque_concat(dequeobject *deque, PyObject *other)
693 {
694     PyObject *result;
695     Py_BEGIN_CRITICAL_SECTION(deque);
696     result = deque_concat_lock_held(deque, other);
697     Py_END_CRITICAL_SECTION();
698     return result;
699 }
700 
701 static int
deque_clear(dequeobject * deque)702 deque_clear(dequeobject *deque)
703 {
704     block *b;
705     block *prevblock;
706     block *leftblock;
707     Py_ssize_t leftindex;
708     Py_ssize_t n, m;
709     PyObject *item;
710     PyObject **itemptr, **limit;
711 
712     if (Py_SIZE(deque) == 0)
713         return 0;
714 
715     /* During the process of clearing a deque, decrefs can cause the
716        deque to mutate.  To avoid fatal confusion, we have to make the
717        deque empty before clearing the blocks and never refer to
718        anything via deque->ref while clearing.  (This is the same
719        technique used for clearing lists, sets, and dicts.)
720 
721        Making the deque empty requires allocating a new empty block.  In
722        the unlikely event that memory is full, we fall back to an
723        alternate method that doesn't require a new block.  Repeating
724        pops in a while-loop is slower, possibly re-entrant (and a clever
725        adversary could cause it to never terminate).
726     */
727 
728     b = newblock(deque);
729     if (b == NULL) {
730         PyErr_Clear();
731         goto alternate_method;
732     }
733 
734     /* Remember the old size, leftblock, and leftindex */
735     n = Py_SIZE(deque);
736     leftblock = deque->leftblock;
737     leftindex = deque->leftindex;
738 
739     /* Set the deque to be empty using the newly allocated block */
740     MARK_END(b->leftlink);
741     MARK_END(b->rightlink);
742     Py_SET_SIZE(deque, 0);
743     deque->leftblock = b;
744     deque->rightblock = b;
745     deque->leftindex = CENTER + 1;
746     deque->rightindex = CENTER;
747     deque->state++;
748 
749     /* Now the old size, leftblock, and leftindex are disconnected from
750        the empty deque and we can use them to decref the pointers.
751     */
752     m = (BLOCKLEN - leftindex > n) ? n : BLOCKLEN - leftindex;
753     itemptr = &leftblock->data[leftindex];
754     limit = itemptr + m;
755     n -= m;
756     while (1) {
757         if (itemptr == limit) {
758             if (n == 0)
759                 break;
760             CHECK_NOT_END(leftblock->rightlink);
761             prevblock = leftblock;
762             leftblock = leftblock->rightlink;
763             m = (n > BLOCKLEN) ? BLOCKLEN : n;
764             itemptr = leftblock->data;
765             limit = itemptr + m;
766             n -= m;
767             freeblock(deque, prevblock);
768         }
769         item = *(itemptr++);
770         Py_DECREF(item);
771     }
772     CHECK_END(leftblock->rightlink);
773     freeblock(deque, leftblock);
774     return 0;
775 
776   alternate_method:
777     while (Py_SIZE(deque)) {
778         item = deque_pop_impl(deque);
779         assert (item != NULL);
780         Py_DECREF(item);
781     }
782     return 0;
783 }
784 
785 /*[clinic input]
786 @critical_section
787 _collections.deque.clear as deque_clearmethod
788 
789     deque: dequeobject
790 
791 Remove all elements from the deque.
792 [clinic start generated code]*/
793 
794 static PyObject *
deque_clearmethod_impl(dequeobject * deque)795 deque_clearmethod_impl(dequeobject *deque)
796 /*[clinic end generated code: output=79b2513e097615c1 input=3a22e9605d20c5e9]*/
797 {
798     deque_clear(deque);
799     Py_RETURN_NONE;
800 }
801 
802 static PyObject *
deque_inplace_repeat_lock_held(dequeobject * deque,Py_ssize_t n)803 deque_inplace_repeat_lock_held(dequeobject *deque, Py_ssize_t n)
804 {
805     Py_ssize_t i, m, size;
806     PyObject *seq;
807     PyObject *rv;
808 
809     size = Py_SIZE(deque);
810     if (size == 0 || n == 1) {
811         return Py_NewRef(deque);
812     }
813 
814     if (n <= 0) {
815         deque_clear(deque);
816         return Py_NewRef(deque);
817     }
818 
819     if (size == 1) {
820         /* common case, repeating a single element */
821         PyObject *item = deque->leftblock->data[deque->leftindex];
822 
823         if (deque->maxlen >= 0 && n > deque->maxlen)
824             n = deque->maxlen;
825 
826         deque->state++;
827         for (i = 0 ; i < n-1 ; ) {
828             if (deque->rightindex == BLOCKLEN - 1) {
829                 block *b = newblock(deque);
830                 if (b == NULL) {
831                     Py_SET_SIZE(deque, Py_SIZE(deque) + i);
832                     return NULL;
833                 }
834                 b->leftlink = deque->rightblock;
835                 CHECK_END(deque->rightblock->rightlink);
836                 deque->rightblock->rightlink = b;
837                 deque->rightblock = b;
838                 MARK_END(b->rightlink);
839                 deque->rightindex = -1;
840             }
841             m = n - 1 - i;
842             if (m > BLOCKLEN - 1 - deque->rightindex)
843                 m = BLOCKLEN - 1 - deque->rightindex;
844             i += m;
845             while (m--) {
846                 deque->rightindex++;
847                 deque->rightblock->data[deque->rightindex] = Py_NewRef(item);
848             }
849         }
850         Py_SET_SIZE(deque, Py_SIZE(deque) + i);
851         return Py_NewRef(deque);
852     }
853 
854     if ((size_t)size > PY_SSIZE_T_MAX / (size_t)n) {
855         return PyErr_NoMemory();
856     }
857 
858     seq = PySequence_List((PyObject *)deque);
859     if (seq == NULL)
860         return seq;
861 
862     /* Reduce the number of repetitions when maxlen would be exceeded */
863     if (deque->maxlen >= 0 && n * size > deque->maxlen)
864         n = (deque->maxlen + size - 1) / size;
865 
866     for (i = 0 ; i < n-1 ; i++) {
867         rv = deque_extend_impl(deque, seq);
868         if (rv == NULL) {
869             Py_DECREF(seq);
870             return NULL;
871         }
872         Py_DECREF(rv);
873     }
874     Py_INCREF(deque);
875     Py_DECREF(seq);
876     return (PyObject *)deque;
877 }
878 
879 static PyObject *
deque_inplace_repeat(dequeobject * deque,Py_ssize_t n)880 deque_inplace_repeat(dequeobject *deque, Py_ssize_t n)
881 {
882     PyObject *result;
883     Py_BEGIN_CRITICAL_SECTION(deque);
884     result = deque_inplace_repeat_lock_held(deque, n);
885     Py_END_CRITICAL_SECTION();
886     return result;
887 }
888 
889 static PyObject *
deque_repeat(dequeobject * deque,Py_ssize_t n)890 deque_repeat(dequeobject *deque, Py_ssize_t n)
891 {
892     dequeobject *new_deque;
893     PyObject *rv;
894 
895     Py_BEGIN_CRITICAL_SECTION(deque);
896     new_deque = (dequeobject *)deque_copy_impl(deque);
897     Py_END_CRITICAL_SECTION();
898     if (new_deque == NULL)
899         return NULL;
900     // It's safe to not acquire the per-object lock for new_deque; it's
901     // invisible to other threads.
902     rv = deque_inplace_repeat_lock_held(new_deque, n);
903     Py_DECREF(new_deque);
904     return rv;
905 }
906 
907 /* The rotate() method is part of the public API and is used internally
908 as a primitive for other methods.
909 
910 Rotation by 1 or -1 is a common case, so any optimizations for high
911 volume rotations should take care not to penalize the common case.
912 
913 Conceptually, a rotate by one is equivalent to a pop on one side and an
914 append on the other.  However, a pop/append pair is unnecessarily slow
915 because it requires an incref/decref pair for an object located randomly
916 in memory.  It is better to just move the object pointer from one block
917 to the next without changing the reference count.
918 
919 When moving batches of pointers, it is tempting to use memcpy() but that
920 proved to be slower than a simple loop for a variety of reasons.
921 Memcpy() cannot know in advance that we're copying pointers instead of
922 bytes, that the source and destination are pointer aligned and
923 non-overlapping, that moving just one pointer is a common case, that we
924 never need to move more than BLOCKLEN pointers, and that at least one
925 pointer is always moved.
926 
927 For high volume rotations, newblock() and freeblock() are never called
928 more than once.  Previously emptied blocks are immediately reused as a
929 destination block.  If a block is left-over at the end, it is freed.
930 */
931 
932 static int
_deque_rotate(dequeobject * deque,Py_ssize_t n)933 _deque_rotate(dequeobject *deque, Py_ssize_t n)
934 {
935     block *b = NULL;
936     block *leftblock = deque->leftblock;
937     block *rightblock = deque->rightblock;
938     Py_ssize_t leftindex = deque->leftindex;
939     Py_ssize_t rightindex = deque->rightindex;
940     Py_ssize_t len=Py_SIZE(deque), halflen=len>>1;
941     int rv = -1;
942 
943     if (len <= 1)
944         return 0;
945     if (n > halflen || n < -halflen) {
946         n %= len;
947         if (n > halflen)
948             n -= len;
949         else if (n < -halflen)
950             n += len;
951     }
952     assert(len > 1);
953     assert(-halflen <= n && n <= halflen);
954 
955     deque->state++;
956     while (n > 0) {
957         if (leftindex == 0) {
958             if (b == NULL) {
959                 b = newblock(deque);
960                 if (b == NULL)
961                     goto done;
962             }
963             b->rightlink = leftblock;
964             CHECK_END(leftblock->leftlink);
965             leftblock->leftlink = b;
966             leftblock = b;
967             MARK_END(b->leftlink);
968             leftindex = BLOCKLEN;
969             b = NULL;
970         }
971         assert(leftindex > 0);
972         {
973             PyObject **src, **dest;
974             Py_ssize_t m = n;
975 
976             if (m > rightindex + 1)
977                 m = rightindex + 1;
978             if (m > leftindex)
979                 m = leftindex;
980             assert (m > 0 && m <= len);
981             rightindex -= m;
982             leftindex -= m;
983             src = &rightblock->data[rightindex + 1];
984             dest = &leftblock->data[leftindex];
985             n -= m;
986             do {
987                 *(dest++) = *(src++);
988             } while (--m);
989         }
990         if (rightindex < 0) {
991             assert(leftblock != rightblock);
992             assert(b == NULL);
993             b = rightblock;
994             CHECK_NOT_END(rightblock->leftlink);
995             rightblock = rightblock->leftlink;
996             MARK_END(rightblock->rightlink);
997             rightindex = BLOCKLEN - 1;
998         }
999     }
1000     while (n < 0) {
1001         if (rightindex == BLOCKLEN - 1) {
1002             if (b == NULL) {
1003                 b = newblock(deque);
1004                 if (b == NULL)
1005                     goto done;
1006             }
1007             b->leftlink = rightblock;
1008             CHECK_END(rightblock->rightlink);
1009             rightblock->rightlink = b;
1010             rightblock = b;
1011             MARK_END(b->rightlink);
1012             rightindex = -1;
1013             b = NULL;
1014         }
1015         assert (rightindex < BLOCKLEN - 1);
1016         {
1017             PyObject **src, **dest;
1018             Py_ssize_t m = -n;
1019 
1020             if (m > BLOCKLEN - leftindex)
1021                 m = BLOCKLEN - leftindex;
1022             if (m > BLOCKLEN - 1 - rightindex)
1023                 m = BLOCKLEN - 1 - rightindex;
1024             assert (m > 0 && m <= len);
1025             src = &leftblock->data[leftindex];
1026             dest = &rightblock->data[rightindex + 1];
1027             leftindex += m;
1028             rightindex += m;
1029             n += m;
1030             do {
1031                 *(dest++) = *(src++);
1032             } while (--m);
1033         }
1034         if (leftindex == BLOCKLEN) {
1035             assert(leftblock != rightblock);
1036             assert(b == NULL);
1037             b = leftblock;
1038             CHECK_NOT_END(leftblock->rightlink);
1039             leftblock = leftblock->rightlink;
1040             MARK_END(leftblock->leftlink);
1041             leftindex = 0;
1042         }
1043     }
1044     rv = 0;
1045 done:
1046     if (b != NULL)
1047         freeblock(deque, b);
1048     deque->leftblock = leftblock;
1049     deque->rightblock = rightblock;
1050     deque->leftindex = leftindex;
1051     deque->rightindex = rightindex;
1052 
1053     return rv;
1054 }
1055 
1056 /*[clinic input]
1057 @critical_section
1058 _collections.deque.rotate as deque_rotate
1059 
1060     deque: dequeobject
1061     n: Py_ssize_t = 1
1062     /
1063 
1064 Rotate the deque n steps to the right.  If n is negative, rotates left.
1065 [clinic start generated code]*/
1066 
1067 static PyObject *
deque_rotate_impl(dequeobject * deque,Py_ssize_t n)1068 deque_rotate_impl(dequeobject *deque, Py_ssize_t n)
1069 /*[clinic end generated code: output=96c2402a371eb15d input=5bf834296246e002]*/
1070 {
1071     if (!_deque_rotate(deque, n))
1072         Py_RETURN_NONE;
1073     return NULL;
1074 }
1075 
1076 /*[clinic input]
1077 @critical_section
1078 _collections.deque.reverse as deque_reverse
1079 
1080     deque: dequeobject
1081 
1082 Reverse *IN PLACE*.
1083 [clinic start generated code]*/
1084 
1085 static PyObject *
deque_reverse_impl(dequeobject * deque)1086 deque_reverse_impl(dequeobject *deque)
1087 /*[clinic end generated code: output=bdeebc2cf8c1f064 input=26f4167fd623027f]*/
1088 {
1089     block *leftblock = deque->leftblock;
1090     block *rightblock = deque->rightblock;
1091     Py_ssize_t leftindex = deque->leftindex;
1092     Py_ssize_t rightindex = deque->rightindex;
1093     Py_ssize_t n = Py_SIZE(deque) >> 1;
1094     PyObject *tmp;
1095 
1096     while (--n >= 0) {
1097         /* Validate that pointers haven't met in the middle */
1098         assert(leftblock != rightblock || leftindex < rightindex);
1099         CHECK_NOT_END(leftblock);
1100         CHECK_NOT_END(rightblock);
1101 
1102         /* Swap */
1103         tmp = leftblock->data[leftindex];
1104         leftblock->data[leftindex] = rightblock->data[rightindex];
1105         rightblock->data[rightindex] = tmp;
1106 
1107         /* Advance left block/index pair */
1108         leftindex++;
1109         if (leftindex == BLOCKLEN) {
1110             leftblock = leftblock->rightlink;
1111             leftindex = 0;
1112         }
1113 
1114         /* Step backwards with the right block/index pair */
1115         rightindex--;
1116         if (rightindex < 0) {
1117             rightblock = rightblock->leftlink;
1118             rightindex = BLOCKLEN - 1;
1119         }
1120     }
1121     Py_RETURN_NONE;
1122 }
1123 
1124 /*[clinic input]
1125 @critical_section
1126 _collections.deque.count as deque_count
1127 
1128     deque: dequeobject
1129     value as v: object
1130     /
1131 
1132 Return number of occurrences of value.
1133 [clinic start generated code]*/
1134 
1135 static PyObject *
deque_count_impl(dequeobject * deque,PyObject * v)1136 deque_count_impl(dequeobject *deque, PyObject *v)
1137 /*[clinic end generated code: output=2ca26c49b6ab0400 input=4ef67ef2b34dc1fc]*/
1138 {
1139     block *b = deque->leftblock;
1140     Py_ssize_t index = deque->leftindex;
1141     Py_ssize_t n = Py_SIZE(deque);
1142     Py_ssize_t count = 0;
1143     size_t start_state = deque->state;
1144     PyObject *item;
1145     int cmp;
1146 
1147     while (--n >= 0) {
1148         CHECK_NOT_END(b);
1149         item = Py_NewRef(b->data[index]);
1150         cmp = PyObject_RichCompareBool(item, v, Py_EQ);
1151         Py_DECREF(item);
1152         if (cmp < 0)
1153             return NULL;
1154         count += cmp;
1155 
1156         if (start_state != deque->state) {
1157             PyErr_SetString(PyExc_RuntimeError,
1158                             "deque mutated during iteration");
1159             return NULL;
1160         }
1161 
1162         /* Advance left block/index pair */
1163         index++;
1164         if (index == BLOCKLEN) {
1165             b = b->rightlink;
1166             index = 0;
1167         }
1168     }
1169     return PyLong_FromSsize_t(count);
1170 }
1171 
1172 static int
deque_contains_lock_held(dequeobject * deque,PyObject * v)1173 deque_contains_lock_held(dequeobject *deque, PyObject *v)
1174 {
1175     block *b = deque->leftblock;
1176     Py_ssize_t index = deque->leftindex;
1177     Py_ssize_t n = Py_SIZE(deque);
1178     size_t start_state = deque->state;
1179     PyObject *item;
1180     int cmp;
1181 
1182     while (--n >= 0) {
1183         CHECK_NOT_END(b);
1184         item = Py_NewRef(b->data[index]);
1185         cmp = PyObject_RichCompareBool(item, v, Py_EQ);
1186         Py_DECREF(item);
1187         if (cmp) {
1188             return cmp;
1189         }
1190         if (start_state != deque->state) {
1191             PyErr_SetString(PyExc_RuntimeError,
1192                             "deque mutated during iteration");
1193             return -1;
1194         }
1195         index++;
1196         if (index == BLOCKLEN) {
1197             b = b->rightlink;
1198             index = 0;
1199         }
1200     }
1201     return 0;
1202 }
1203 
1204 static int
deque_contains(dequeobject * deque,PyObject * v)1205 deque_contains(dequeobject *deque, PyObject *v)
1206 {
1207     int result;
1208     Py_BEGIN_CRITICAL_SECTION(deque);
1209     result = deque_contains_lock_held(deque, v);
1210     Py_END_CRITICAL_SECTION();
1211     return result;
1212 }
1213 
1214 static Py_ssize_t
deque_len(dequeobject * deque)1215 deque_len(dequeobject *deque)
1216 {
1217     return FT_ATOMIC_LOAD_SSIZE(((PyVarObject *)deque)->ob_size);
1218 }
1219 
1220 /*[clinic input]
1221 @critical_section
1222 @text_signature "($self, value, [start, [stop]])"
1223 _collections.deque.index as deque_index
1224 
1225     deque: dequeobject
1226     value as v: object
1227     start: object(converter='_PyEval_SliceIndexNotNone', type='Py_ssize_t', c_default='0') = NULL
1228     stop: object(converter='_PyEval_SliceIndexNotNone', type='Py_ssize_t', c_default='Py_SIZE(deque)') = NULL
1229     /
1230 
1231 Return first index of value.
1232 
1233 Raises ValueError if the value is not present.
1234 [clinic start generated code]*/
1235 
1236 static PyObject *
deque_index_impl(dequeobject * deque,PyObject * v,Py_ssize_t start,Py_ssize_t stop)1237 deque_index_impl(dequeobject *deque, PyObject *v, Py_ssize_t start,
1238                  Py_ssize_t stop)
1239 /*[clinic end generated code: output=df45132753175ef9 input=90f48833a91e1743]*/
1240 {
1241     Py_ssize_t i, n;
1242     PyObject *item;
1243     block *b = deque->leftblock;
1244     Py_ssize_t index = deque->leftindex;
1245     size_t start_state = deque->state;
1246     int cmp;
1247 
1248     if (start < 0) {
1249         start += Py_SIZE(deque);
1250         if (start < 0)
1251             start = 0;
1252     }
1253     if (stop < 0) {
1254         stop += Py_SIZE(deque);
1255         if (stop < 0)
1256             stop = 0;
1257     }
1258     if (stop > Py_SIZE(deque))
1259         stop = Py_SIZE(deque);
1260     if (start > stop)
1261         start = stop;
1262     assert(0 <= start && start <= stop && stop <= Py_SIZE(deque));
1263 
1264     for (i=0 ; i < start - BLOCKLEN ; i += BLOCKLEN) {
1265         b = b->rightlink;
1266     }
1267     for ( ; i < start ; i++) {
1268         index++;
1269         if (index == BLOCKLEN) {
1270             b = b->rightlink;
1271             index = 0;
1272         }
1273     }
1274 
1275     n = stop - i;
1276     while (--n >= 0) {
1277         CHECK_NOT_END(b);
1278         item = Py_NewRef(b->data[index]);
1279         cmp = PyObject_RichCompareBool(item, v, Py_EQ);
1280         Py_DECREF(item);
1281         if (cmp > 0)
1282             return PyLong_FromSsize_t(stop - n - 1);
1283         if (cmp < 0)
1284             return NULL;
1285         if (start_state != deque->state) {
1286             PyErr_SetString(PyExc_RuntimeError,
1287                             "deque mutated during iteration");
1288             return NULL;
1289         }
1290         index++;
1291         if (index == BLOCKLEN) {
1292             b = b->rightlink;
1293             index = 0;
1294         }
1295     }
1296     PyErr_Format(PyExc_ValueError, "%R is not in deque", v);
1297     return NULL;
1298 }
1299 
1300 /* insert(), remove(), and delitem() are implemented in terms of
1301    rotate() for simplicity and reasonable performance near the end
1302    points.  If for some reason these methods become popular, it is not
1303    hard to re-implement this using direct data movement (similar to
1304    the code used in list slice assignments) and achieve a performance
1305    boost (by moving each pointer only once instead of twice).
1306 */
1307 
1308 /*[clinic input]
1309 @critical_section
1310 _collections.deque.insert as deque_insert
1311 
1312     deque: dequeobject
1313     index: Py_ssize_t
1314     value: object
1315     /
1316 
1317 Insert value before index.
1318 [clinic start generated code]*/
1319 
1320 static PyObject *
deque_insert_impl(dequeobject * deque,Py_ssize_t index,PyObject * value)1321 deque_insert_impl(dequeobject *deque, Py_ssize_t index, PyObject *value)
1322 /*[clinic end generated code: output=ef4d2c15d5532b80 input=dbee706586cc9cde]*/
1323 {
1324     Py_ssize_t n = Py_SIZE(deque);
1325     PyObject *rv;
1326 
1327     if (deque->maxlen == Py_SIZE(deque)) {
1328         PyErr_SetString(PyExc_IndexError, "deque already at its maximum size");
1329         return NULL;
1330     }
1331     if (index >= n)
1332         return deque_append_impl(deque, value);
1333     if (index <= -n || index == 0)
1334         return deque_appendleft_impl(deque, value);
1335     if (_deque_rotate(deque, -index))
1336         return NULL;
1337     if (index < 0)
1338         rv = deque_append_impl(deque, value);
1339     else
1340         rv = deque_appendleft_impl(deque, value);
1341     if (rv == NULL)
1342         return NULL;
1343     Py_DECREF(rv);
1344     if (_deque_rotate(deque, index))
1345         return NULL;
1346     Py_RETURN_NONE;
1347 }
1348 
1349 static int
valid_index(Py_ssize_t i,Py_ssize_t limit)1350 valid_index(Py_ssize_t i, Py_ssize_t limit)
1351 {
1352     /* The cast to size_t lets us use just a single comparison
1353        to check whether i is in the range: 0 <= i < limit */
1354     return (size_t) i < (size_t) limit;
1355 }
1356 
1357 static PyObject *
deque_item_lock_held(dequeobject * deque,Py_ssize_t i)1358 deque_item_lock_held(dequeobject *deque, Py_ssize_t i)
1359 {
1360     block *b;
1361     PyObject *item;
1362     Py_ssize_t n, index=i;
1363 
1364     if (!valid_index(i, Py_SIZE(deque))) {
1365         PyErr_SetString(PyExc_IndexError, "deque index out of range");
1366         return NULL;
1367     }
1368 
1369     if (i == 0) {
1370         i = deque->leftindex;
1371         b = deque->leftblock;
1372     } else if (i == Py_SIZE(deque) - 1) {
1373         i = deque->rightindex;
1374         b = deque->rightblock;
1375     } else {
1376         i += deque->leftindex;
1377         n = (Py_ssize_t)((size_t) i / BLOCKLEN);
1378         i = (Py_ssize_t)((size_t) i % BLOCKLEN);
1379         if (index < (Py_SIZE(deque) >> 1)) {
1380             b = deque->leftblock;
1381             while (--n >= 0)
1382                 b = b->rightlink;
1383         } else {
1384             n = (Py_ssize_t)(
1385                     ((size_t)(deque->leftindex + Py_SIZE(deque) - 1))
1386                     / BLOCKLEN - n);
1387             b = deque->rightblock;
1388             while (--n >= 0)
1389                 b = b->leftlink;
1390         }
1391     }
1392     item = b->data[i];
1393     return Py_NewRef(item);
1394 }
1395 
1396 static PyObject *
deque_item(dequeobject * deque,Py_ssize_t i)1397 deque_item(dequeobject *deque, Py_ssize_t i)
1398 {
1399     PyObject *result;
1400     Py_BEGIN_CRITICAL_SECTION(deque);
1401     result = deque_item_lock_held(deque, i);
1402     Py_END_CRITICAL_SECTION();
1403     return result;
1404 }
1405 
1406 static int
deque_del_item(dequeobject * deque,Py_ssize_t i)1407 deque_del_item(dequeobject *deque, Py_ssize_t i)
1408 {
1409     PyObject *item;
1410     int rv;
1411 
1412     assert (i >= 0 && i < Py_SIZE(deque));
1413     if (_deque_rotate(deque, -i))
1414         return -1;
1415     item = deque_popleft_impl(deque);
1416     rv = _deque_rotate(deque, i);
1417     assert (item != NULL);
1418     Py_DECREF(item);
1419     return rv;
1420 }
1421 
1422 /*[clinic input]
1423 @critical_section
1424 _collections.deque.remove as deque_remove
1425 
1426     deque: dequeobject
1427     value: object
1428     /
1429 
1430 Remove first occurrence of value.
1431 [clinic start generated code]*/
1432 
1433 static PyObject *
deque_remove_impl(dequeobject * deque,PyObject * value)1434 deque_remove_impl(dequeobject *deque, PyObject *value)
1435 /*[clinic end generated code: output=54cff28b8ef78c5b input=60eb3f8aa4de532a]*/
1436 {
1437     PyObject *item;
1438     block *b = deque->leftblock;
1439     Py_ssize_t i, n = Py_SIZE(deque), index = deque->leftindex;
1440     size_t start_state = deque->state;
1441     int cmp, rv;
1442 
1443     for (i = 0 ; i < n; i++) {
1444         item = Py_NewRef(b->data[index]);
1445         cmp = PyObject_RichCompareBool(item, value, Py_EQ);
1446         Py_DECREF(item);
1447         if (cmp < 0) {
1448             return NULL;
1449         }
1450         if (start_state != deque->state) {
1451             PyErr_SetString(PyExc_IndexError,
1452                             "deque mutated during iteration");
1453             return NULL;
1454         }
1455         if (cmp > 0) {
1456             break;
1457         }
1458         index++;
1459         if (index == BLOCKLEN) {
1460             b = b->rightlink;
1461             index = 0;
1462         }
1463     }
1464     if (i == n) {
1465         PyErr_Format(PyExc_ValueError, "%R is not in deque", value);
1466         return NULL;
1467     }
1468     rv = deque_del_item(deque, i);
1469     if (rv == -1) {
1470         return NULL;
1471     }
1472     Py_RETURN_NONE;
1473 }
1474 
1475 static int
deque_ass_item_lock_held(dequeobject * deque,Py_ssize_t i,PyObject * v)1476 deque_ass_item_lock_held(dequeobject *deque, Py_ssize_t i, PyObject *v)
1477 {
1478     block *b;
1479     Py_ssize_t n, len=Py_SIZE(deque), halflen=(len+1)>>1, index=i;
1480 
1481     if (!valid_index(i, len)) {
1482         PyErr_SetString(PyExc_IndexError, "deque index out of range");
1483         return -1;
1484     }
1485     if (v == NULL)
1486         return deque_del_item(deque, i);
1487 
1488     i += deque->leftindex;
1489     n = (Py_ssize_t)((size_t) i / BLOCKLEN);
1490     i = (Py_ssize_t)((size_t) i % BLOCKLEN);
1491     if (index <= halflen) {
1492         b = deque->leftblock;
1493         while (--n >= 0)
1494             b = b->rightlink;
1495     } else {
1496         n = (Py_ssize_t)(
1497                 ((size_t)(deque->leftindex + Py_SIZE(deque) - 1))
1498                 / BLOCKLEN - n);
1499         b = deque->rightblock;
1500         while (--n >= 0)
1501             b = b->leftlink;
1502     }
1503     Py_SETREF(b->data[i], Py_NewRef(v));
1504     return 0;
1505 }
1506 
1507 static int
deque_ass_item(dequeobject * deque,Py_ssize_t i,PyObject * v)1508 deque_ass_item(dequeobject *deque, Py_ssize_t i, PyObject *v)
1509 {
1510     int result;
1511     Py_BEGIN_CRITICAL_SECTION(deque);
1512     result = deque_ass_item_lock_held(deque, i, v);
1513     Py_END_CRITICAL_SECTION();
1514     return result;
1515 }
1516 
1517 static void
deque_dealloc(dequeobject * deque)1518 deque_dealloc(dequeobject *deque)
1519 {
1520     PyTypeObject *tp = Py_TYPE(deque);
1521     Py_ssize_t i;
1522 
1523     PyObject_GC_UnTrack(deque);
1524     if (deque->weakreflist != NULL)
1525         PyObject_ClearWeakRefs((PyObject *) deque);
1526     if (deque->leftblock != NULL) {
1527         deque_clear(deque);
1528         assert(deque->leftblock != NULL);
1529         freeblock(deque, deque->leftblock);
1530     }
1531     deque->leftblock = NULL;
1532     deque->rightblock = NULL;
1533     for (i=0 ; i < deque->numfreeblocks ; i++) {
1534         PyMem_Free(deque->freeblocks[i]);
1535     }
1536     tp->tp_free(deque);
1537     Py_DECREF(tp);
1538 }
1539 
1540 static int
deque_traverse(dequeobject * deque,visitproc visit,void * arg)1541 deque_traverse(dequeobject *deque, visitproc visit, void *arg)
1542 {
1543     Py_VISIT(Py_TYPE(deque));
1544 
1545     block *b;
1546     PyObject *item;
1547     Py_ssize_t index;
1548     Py_ssize_t indexlo = deque->leftindex;
1549     Py_ssize_t indexhigh;
1550 
1551     for (b = deque->leftblock; b != deque->rightblock; b = b->rightlink) {
1552         for (index = indexlo; index < BLOCKLEN ; index++) {
1553             item = b->data[index];
1554             Py_VISIT(item);
1555         }
1556         indexlo = 0;
1557     }
1558     indexhigh = deque->rightindex;
1559     for (index = indexlo; index <= indexhigh; index++) {
1560         item = b->data[index];
1561         Py_VISIT(item);
1562     }
1563     return 0;
1564 }
1565 
1566 /*[clinic input]
1567 _collections.deque.__reduce__ as deque___reduce__
1568 
1569     deque: dequeobject
1570 
1571 Return state information for pickling.
1572 [clinic start generated code]*/
1573 
1574 static PyObject *
deque___reduce___impl(dequeobject * deque)1575 deque___reduce___impl(dequeobject *deque)
1576 /*[clinic end generated code: output=cb85d9e0b7d2c5ad input=991a933a5bc7a526]*/
1577 {
1578     PyObject *state, *it;
1579 
1580     state = _PyObject_GetState((PyObject *)deque);
1581     if (state == NULL) {
1582         return NULL;
1583     }
1584 
1585     it = PyObject_GetIter((PyObject *)deque);
1586     if (it == NULL) {
1587         Py_DECREF(state);
1588         return NULL;
1589     }
1590 
1591     // It's safe to access deque->maxlen here without holding the per object
1592     // lock for deque; deque->maxlen is only assigned during construction.
1593     if (deque->maxlen < 0) {
1594         return Py_BuildValue("O()NN", Py_TYPE(deque), state, it);
1595     }
1596     else {
1597         return Py_BuildValue("O(()n)NN", Py_TYPE(deque), deque->maxlen, state, it);
1598     }
1599 }
1600 
1601 PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
1602 
1603 static PyObject *
deque_repr(PyObject * deque)1604 deque_repr(PyObject *deque)
1605 {
1606     PyObject *aslist, *result;
1607     int i;
1608 
1609     i = Py_ReprEnter(deque);
1610     if (i != 0) {
1611         if (i < 0)
1612             return NULL;
1613         return PyUnicode_FromString("[...]");
1614     }
1615 
1616     aslist = PySequence_List(deque);
1617     if (aslist == NULL) {
1618         Py_ReprLeave(deque);
1619         return NULL;
1620     }
1621     if (((dequeobject *)deque)->maxlen >= 0)
1622         result = PyUnicode_FromFormat("%s(%R, maxlen=%zd)",
1623                                       _PyType_Name(Py_TYPE(deque)), aslist,
1624                                       ((dequeobject *)deque)->maxlen);
1625     else
1626         result = PyUnicode_FromFormat("%s(%R)",
1627                                       _PyType_Name(Py_TYPE(deque)), aslist);
1628     Py_ReprLeave(deque);
1629     Py_DECREF(aslist);
1630     return result;
1631 }
1632 
1633 static PyObject *
deque_richcompare(PyObject * v,PyObject * w,int op)1634 deque_richcompare(PyObject *v, PyObject *w, int op)
1635 {
1636     PyObject *it1=NULL, *it2=NULL, *x, *y;
1637     Py_ssize_t vs, ws;
1638     int b, cmp=-1;
1639 
1640     collections_state *state = find_module_state_by_def(Py_TYPE(v));
1641     if (!PyObject_TypeCheck(v, state->deque_type) ||
1642         !PyObject_TypeCheck(w, state->deque_type)) {
1643         Py_RETURN_NOTIMPLEMENTED;
1644     }
1645 
1646     /* Shortcuts */
1647     vs = Py_SIZE((dequeobject *)v);
1648     ws = Py_SIZE((dequeobject *)w);
1649     if (op == Py_EQ) {
1650         if (v == w)
1651             Py_RETURN_TRUE;
1652         if (vs != ws)
1653             Py_RETURN_FALSE;
1654     }
1655     if (op == Py_NE) {
1656         if (v == w)
1657             Py_RETURN_FALSE;
1658         if (vs != ws)
1659             Py_RETURN_TRUE;
1660     }
1661 
1662     /* Search for the first index where items are different */
1663     it1 = PyObject_GetIter(v);
1664     if (it1 == NULL)
1665         goto done;
1666     it2 = PyObject_GetIter(w);
1667     if (it2 == NULL)
1668         goto done;
1669     for (;;) {
1670         x = PyIter_Next(it1);
1671         if (x == NULL && PyErr_Occurred())
1672             goto done;
1673         y = PyIter_Next(it2);
1674         if (x == NULL || y == NULL)
1675             break;
1676         b = PyObject_RichCompareBool(x, y, Py_EQ);
1677         if (b == 0) {
1678             cmp = PyObject_RichCompareBool(x, y, op);
1679             Py_DECREF(x);
1680             Py_DECREF(y);
1681             goto done;
1682         }
1683         Py_DECREF(x);
1684         Py_DECREF(y);
1685         if (b < 0)
1686             goto done;
1687     }
1688     /* We reached the end of one deque or both */
1689     Py_XDECREF(x);
1690     Py_XDECREF(y);
1691     if (PyErr_Occurred())
1692         goto done;
1693     switch (op) {
1694     case Py_LT: cmp = y != NULL; break;  /* if w was longer */
1695     case Py_LE: cmp = x == NULL; break;  /* if v was not longer */
1696     case Py_EQ: cmp = x == y;    break;  /* if we reached the end of both */
1697     case Py_NE: cmp = x != y;    break;  /* if one deque continues */
1698     case Py_GT: cmp = x != NULL; break;  /* if v was longer */
1699     case Py_GE: cmp = y == NULL; break;  /* if w was not longer */
1700     }
1701 
1702 done:
1703     Py_XDECREF(it1);
1704     Py_XDECREF(it2);
1705     if (cmp == 1)
1706         Py_RETURN_TRUE;
1707     if (cmp == 0)
1708         Py_RETURN_FALSE;
1709     return NULL;
1710 }
1711 
1712 /*[clinic input]
1713 @critical_section
1714 @text_signature "([iterable[, maxlen]])"
1715 _collections.deque.__init__ as deque_init
1716 
1717     deque: dequeobject
1718     iterable: object = NULL
1719     maxlen as maxlenobj: object = NULL
1720 
1721 A list-like sequence optimized for data accesses near its endpoints.
1722 [clinic start generated code]*/
1723 
1724 static int
deque_init_impl(dequeobject * deque,PyObject * iterable,PyObject * maxlenobj)1725 deque_init_impl(dequeobject *deque, PyObject *iterable, PyObject *maxlenobj)
1726 /*[clinic end generated code: output=7084a39d71218dcd input=2b9e37af1fd73143]*/
1727 {
1728     Py_ssize_t maxlen = -1;
1729     if (maxlenobj != NULL && maxlenobj != Py_None) {
1730         maxlen = PyLong_AsSsize_t(maxlenobj);
1731         if (maxlen == -1 && PyErr_Occurred())
1732             return -1;
1733         if (maxlen < 0) {
1734             PyErr_SetString(PyExc_ValueError, "maxlen must be non-negative");
1735             return -1;
1736         }
1737     }
1738     deque->maxlen = maxlen;
1739     if (Py_SIZE(deque) > 0)
1740         deque_clear(deque);
1741     if (iterable != NULL) {
1742         PyObject *rv = deque_extend_impl(deque, iterable);
1743         if (rv == NULL)
1744             return -1;
1745         Py_DECREF(rv);
1746     }
1747     return 0;
1748 }
1749 
1750 /*[clinic input]
1751 @critical_section
1752 _collections.deque.__sizeof__ as deque___sizeof__
1753 
1754     deque: dequeobject
1755 
1756 Return the size of the deque in memory, in bytes.
1757 [clinic start generated code]*/
1758 
1759 static PyObject *
deque___sizeof___impl(dequeobject * deque)1760 deque___sizeof___impl(dequeobject *deque)
1761 /*[clinic end generated code: output=4d36e9fb4f30bbaf input=762312f2d4813535]*/
1762 {
1763     size_t res = _PyObject_SIZE(Py_TYPE(deque));
1764     size_t blocks;
1765     blocks = (size_t)(deque->leftindex + Py_SIZE(deque) + BLOCKLEN - 1) / BLOCKLEN;
1766     assert(((size_t)deque->leftindex + (size_t)Py_SIZE(deque) - 1) ==
1767            ((blocks - 1) * BLOCKLEN + (size_t)deque->rightindex));
1768     res += blocks * sizeof(block);
1769     return PyLong_FromSize_t(res);
1770 }
1771 
1772 static PyObject *
deque_get_maxlen(dequeobject * deque,void * Py_UNUSED (ignored))1773 deque_get_maxlen(dequeobject *deque, void *Py_UNUSED(ignored))
1774 {
1775     if (deque->maxlen < 0)
1776         Py_RETURN_NONE;
1777     return PyLong_FromSsize_t(deque->maxlen);
1778 }
1779 
1780 static PyObject *deque_reviter(dequeobject *deque);
1781 
1782 /*[clinic input]
1783 _collections.deque.__reversed__ as deque___reversed__
1784 
1785     deque: dequeobject
1786 
1787 Return a reverse iterator over the deque.
1788 [clinic start generated code]*/
1789 
1790 static PyObject *
deque___reversed___impl(dequeobject * deque)1791 deque___reversed___impl(dequeobject *deque)
1792 /*[clinic end generated code: output=3e7e7e715883cf2e input=3d494c25a6fe5c7e]*/
1793 {
1794     return deque_reviter(deque);
1795 }
1796 
1797 /* deque object ********************************************************/
1798 
1799 static PyGetSetDef deque_getset[] = {
1800     {"maxlen", (getter)deque_get_maxlen, (setter)NULL,
1801      "maximum size of a deque or None if unbounded"},
1802     {0}
1803 };
1804 
1805 static PyObject *deque_iter(dequeobject *deque);
1806 
1807 static PyMethodDef deque_methods[] = {
1808     DEQUE_APPEND_METHODDEF
1809     DEQUE_APPENDLEFT_METHODDEF
1810     DEQUE_CLEARMETHOD_METHODDEF
1811     DEQUE___COPY___METHODDEF
1812     DEQUE_COPY_METHODDEF
1813     DEQUE_COUNT_METHODDEF
1814     DEQUE_EXTEND_METHODDEF
1815     DEQUE_EXTENDLEFT_METHODDEF
1816     DEQUE_INDEX_METHODDEF
1817     DEQUE_INSERT_METHODDEF
1818     DEQUE_POP_METHODDEF
1819     DEQUE_POPLEFT_METHODDEF
1820     DEQUE___REDUCE___METHODDEF
1821     DEQUE_REMOVE_METHODDEF
1822     DEQUE___REVERSED___METHODDEF
1823     DEQUE_REVERSE_METHODDEF
1824     DEQUE_ROTATE_METHODDEF
1825     DEQUE___SIZEOF___METHODDEF
1826     {"__class_getitem__",       Py_GenericAlias,
1827         METH_O|METH_CLASS,       PyDoc_STR("See PEP 585")},
1828     {NULL,              NULL}   /* sentinel */
1829 };
1830 
1831 static PyMemberDef deque_members[] = {
1832     {"__weaklistoffset__", Py_T_PYSSIZET, offsetof(dequeobject, weakreflist), Py_READONLY},
1833     {NULL},
1834 };
1835 
1836 static PyType_Slot deque_slots[] = {
1837     {Py_tp_dealloc, deque_dealloc},
1838     {Py_tp_repr, deque_repr},
1839     {Py_tp_hash, PyObject_HashNotImplemented},
1840     {Py_tp_getattro, PyObject_GenericGetAttr},
1841     {Py_tp_doc, (void *)deque_init__doc__},
1842     {Py_tp_traverse, deque_traverse},
1843     {Py_tp_clear, deque_clear},
1844     {Py_tp_richcompare, deque_richcompare},
1845     {Py_tp_iter, deque_iter},
1846     {Py_tp_getset, deque_getset},
1847     {Py_tp_init, deque_init},
1848     {Py_tp_alloc, PyType_GenericAlloc},
1849     {Py_tp_new, deque_new},
1850     {Py_tp_free, PyObject_GC_Del},
1851     {Py_tp_methods, deque_methods},
1852     {Py_tp_members, deque_members},
1853 
1854     // Sequence protocol
1855     {Py_sq_length, deque_len},
1856     {Py_sq_concat, deque_concat},
1857     {Py_sq_repeat, deque_repeat},
1858     {Py_sq_item, deque_item},
1859     {Py_sq_ass_item, deque_ass_item},
1860     {Py_sq_contains, deque_contains},
1861     {Py_sq_inplace_concat, deque_inplace_concat},
1862     {Py_sq_inplace_repeat, deque_inplace_repeat},
1863     {0, NULL},
1864 };
1865 
1866 static PyType_Spec deque_spec = {
1867     .name = "collections.deque",
1868     .basicsize = sizeof(dequeobject),
1869     .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
1870               Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_SEQUENCE |
1871               Py_TPFLAGS_IMMUTABLETYPE),
1872     .slots = deque_slots,
1873 };
1874 
1875 /*********************** Deque Iterator **************************/
1876 
1877 typedef struct {
1878     PyObject_HEAD
1879     block *b;
1880     Py_ssize_t index;
1881     dequeobject *deque;
1882     size_t state;          /* state when the iterator is created */
1883     Py_ssize_t counter;    /* number of items remaining for iteration */
1884 } dequeiterobject;
1885 
1886 static PyObject *
deque_iter(dequeobject * deque)1887 deque_iter(dequeobject *deque)
1888 {
1889     dequeiterobject *it;
1890 
1891     collections_state *state = find_module_state_by_def(Py_TYPE(deque));
1892     it = PyObject_GC_New(dequeiterobject, state->dequeiter_type);
1893     if (it == NULL)
1894         return NULL;
1895     Py_BEGIN_CRITICAL_SECTION(deque);
1896     it->b = deque->leftblock;
1897     it->index = deque->leftindex;
1898     it->deque = (dequeobject*)Py_NewRef(deque);
1899     it->state = deque->state;
1900     it->counter = Py_SIZE(deque);
1901     Py_END_CRITICAL_SECTION();
1902     PyObject_GC_Track(it);
1903     return (PyObject *)it;
1904 }
1905 
1906 static int
dequeiter_traverse(dequeiterobject * dio,visitproc visit,void * arg)1907 dequeiter_traverse(dequeiterobject *dio, visitproc visit, void *arg)
1908 {
1909     Py_VISIT(Py_TYPE(dio));
1910     Py_VISIT(dio->deque);
1911     return 0;
1912 }
1913 
1914 static int
dequeiter_clear(dequeiterobject * dio)1915 dequeiter_clear(dequeiterobject *dio)
1916 {
1917     Py_CLEAR(dio->deque);
1918     return 0;
1919 }
1920 
1921 static void
dequeiter_dealloc(dequeiterobject * dio)1922 dequeiter_dealloc(dequeiterobject *dio)
1923 {
1924     /* bpo-31095: UnTrack is needed before calling any callbacks */
1925     PyTypeObject *tp = Py_TYPE(dio);
1926     PyObject_GC_UnTrack(dio);
1927     (void)dequeiter_clear(dio);
1928     PyObject_GC_Del(dio);
1929     Py_DECREF(tp);
1930 }
1931 
1932 static PyObject *
dequeiter_next_lock_held(dequeiterobject * it,dequeobject * deque)1933 dequeiter_next_lock_held(dequeiterobject *it, dequeobject *deque)
1934 {
1935     PyObject *item;
1936 
1937     if (it->deque->state != it->state) {
1938         it->counter = 0;
1939         PyErr_SetString(PyExc_RuntimeError,
1940                         "deque mutated during iteration");
1941         return NULL;
1942     }
1943     if (it->counter == 0)
1944         return NULL;
1945     assert (!(it->b == it->deque->rightblock &&
1946               it->index > it->deque->rightindex));
1947 
1948     item = it->b->data[it->index];
1949     it->index++;
1950     it->counter--;
1951     if (it->index == BLOCKLEN && it->counter > 0) {
1952         CHECK_NOT_END(it->b->rightlink);
1953         it->b = it->b->rightlink;
1954         it->index = 0;
1955     }
1956     return Py_NewRef(item);
1957 }
1958 
1959 static PyObject *
dequeiter_next(dequeiterobject * it)1960 dequeiter_next(dequeiterobject *it)
1961 {
1962     PyObject *result;
1963     // It's safe to access it->deque without holding the per-object lock for it
1964     // here; it->deque is only assigned during construction of it.
1965     dequeobject *deque = it->deque;
1966     Py_BEGIN_CRITICAL_SECTION2(it, deque);
1967     result = dequeiter_next_lock_held(it, deque);
1968     Py_END_CRITICAL_SECTION2();
1969 
1970     return result;
1971 }
1972 
1973 static PyObject *
dequeiter_new(PyTypeObject * type,PyObject * args,PyObject * kwds)1974 dequeiter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1975 {
1976     Py_ssize_t i, index=0;
1977     PyObject *deque;
1978     dequeiterobject *it;
1979     collections_state *state = get_module_state_by_cls(type);
1980     if (!PyArg_ParseTuple(args, "O!|n", state->deque_type, &deque, &index))
1981         return NULL;
1982     assert(type == state->dequeiter_type);
1983 
1984     it = (dequeiterobject*)deque_iter((dequeobject *)deque);
1985     if (!it)
1986         return NULL;
1987     /* consume items from the queue */
1988     for(i=0; i<index; i++) {
1989         PyObject *item = dequeiter_next(it);
1990         if (item) {
1991             Py_DECREF(item);
1992         } else {
1993             /*
1994              * It's safe to read directly from it without acquiring the
1995              * per-object lock; the iterator isn't visible to any other threads
1996              * yet.
1997              */
1998             if (it->counter) {
1999                 Py_DECREF(it);
2000                 return NULL;
2001             } else
2002                 break;
2003         }
2004     }
2005     return (PyObject*)it;
2006 }
2007 
2008 static PyObject *
dequeiter_len(dequeiterobject * it,PyObject * Py_UNUSED (ignored))2009 dequeiter_len(dequeiterobject *it, PyObject *Py_UNUSED(ignored))
2010 {
2011     Py_ssize_t len = FT_ATOMIC_LOAD_SSIZE(it->counter);
2012     return PyLong_FromSsize_t(len);
2013 }
2014 
2015 PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
2016 
2017 static PyObject *
dequeiter_reduce(dequeiterobject * it,PyObject * Py_UNUSED (ignored))2018 dequeiter_reduce(dequeiterobject *it, PyObject *Py_UNUSED(ignored))
2019 {
2020     PyTypeObject *ty = Py_TYPE(it);
2021     // It's safe to access it->deque without holding the per-object lock for it
2022     // here; it->deque is only assigned during construction of it.
2023     dequeobject *deque = it->deque;
2024     Py_ssize_t size, counter;
2025     Py_BEGIN_CRITICAL_SECTION2(it, deque);
2026     size = Py_SIZE(deque);
2027     counter = it->counter;
2028     Py_END_CRITICAL_SECTION2();
2029     return Py_BuildValue("O(On)", ty, deque, size - counter);
2030 }
2031 
2032 static PyMethodDef dequeiter_methods[] = {
2033     {"__length_hint__", (PyCFunction)dequeiter_len, METH_NOARGS, length_hint_doc},
2034     {"__reduce__", (PyCFunction)dequeiter_reduce, METH_NOARGS, reduce_doc},
2035     {NULL,              NULL}           /* sentinel */
2036 };
2037 
2038 static PyType_Slot dequeiter_slots[] = {
2039     {Py_tp_dealloc, dequeiter_dealloc},
2040     {Py_tp_getattro, PyObject_GenericGetAttr},
2041     {Py_tp_traverse, dequeiter_traverse},
2042     {Py_tp_clear, dequeiter_clear},
2043     {Py_tp_iter, PyObject_SelfIter},
2044     {Py_tp_iternext, dequeiter_next},
2045     {Py_tp_methods, dequeiter_methods},
2046     {Py_tp_new, dequeiter_new},
2047     {0, NULL},
2048 };
2049 
2050 static PyType_Spec dequeiter_spec = {
2051     .name = "collections._deque_iterator",
2052     .basicsize = sizeof(dequeiterobject),
2053     .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2054               Py_TPFLAGS_IMMUTABLETYPE),
2055     .slots = dequeiter_slots,
2056 };
2057 
2058 /*********************** Deque Reverse Iterator **************************/
2059 
2060 static PyObject *
deque_reviter(dequeobject * deque)2061 deque_reviter(dequeobject *deque)
2062 {
2063     dequeiterobject *it;
2064     collections_state *state = find_module_state_by_def(Py_TYPE(deque));
2065 
2066     it = PyObject_GC_New(dequeiterobject, state->dequereviter_type);
2067     if (it == NULL)
2068         return NULL;
2069     Py_BEGIN_CRITICAL_SECTION(deque);
2070     it->b = deque->rightblock;
2071     it->index = deque->rightindex;
2072     it->deque = (dequeobject*)Py_NewRef(deque);
2073     it->state = deque->state;
2074     it->counter = Py_SIZE(deque);
2075     Py_END_CRITICAL_SECTION();
2076     PyObject_GC_Track(it);
2077     return (PyObject *)it;
2078 }
2079 
2080 static PyObject *
dequereviter_next_lock_held(dequeiterobject * it,dequeobject * deque)2081 dequereviter_next_lock_held(dequeiterobject *it, dequeobject *deque)
2082 {
2083     PyObject *item;
2084     if (it->counter == 0)
2085         return NULL;
2086 
2087     if (it->deque->state != it->state) {
2088         it->counter = 0;
2089         PyErr_SetString(PyExc_RuntimeError,
2090                         "deque mutated during iteration");
2091         return NULL;
2092     }
2093     assert (!(it->b == it->deque->leftblock &&
2094               it->index < it->deque->leftindex));
2095 
2096     item = it->b->data[it->index];
2097     it->index--;
2098     it->counter--;
2099     if (it->index < 0 && it->counter > 0) {
2100         CHECK_NOT_END(it->b->leftlink);
2101         it->b = it->b->leftlink;
2102         it->index = BLOCKLEN - 1;
2103     }
2104     return Py_NewRef(item);
2105 }
2106 
2107 static PyObject *
dequereviter_next(dequeiterobject * it)2108 dequereviter_next(dequeiterobject *it)
2109 {
2110     PyObject *item;
2111     // It's safe to access it->deque without holding the per-object lock for it
2112     // here; it->deque is only assigned during construction of it.
2113     dequeobject *deque = it->deque;
2114     Py_BEGIN_CRITICAL_SECTION2(it, deque);
2115     item = dequereviter_next_lock_held(it, deque);
2116     Py_END_CRITICAL_SECTION2();
2117     return item;
2118 }
2119 
2120 static PyObject *
dequereviter_new(PyTypeObject * type,PyObject * args,PyObject * kwds)2121 dequereviter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2122 {
2123     Py_ssize_t i, index=0;
2124     PyObject *deque;
2125     dequeiterobject *it;
2126     collections_state *state = get_module_state_by_cls(type);
2127     if (!PyArg_ParseTuple(args, "O!|n", state->deque_type, &deque, &index))
2128         return NULL;
2129     assert(type == state->dequereviter_type);
2130 
2131     it = (dequeiterobject *)deque_reviter((dequeobject *)deque);
2132     if (!it)
2133         return NULL;
2134     /* consume items from the queue */
2135     for(i=0; i<index; i++) {
2136         PyObject *item = dequereviter_next(it);
2137         if (item) {
2138             Py_DECREF(item);
2139         } else {
2140             /*
2141              * It's safe to read directly from it without acquiring the
2142              * per-object lock; the iterator isn't visible to any other threads
2143              * yet.
2144              */
2145             if (it->counter) {
2146                 Py_DECREF(it);
2147                 return NULL;
2148             } else
2149                 break;
2150         }
2151     }
2152     return (PyObject*)it;
2153 }
2154 
2155 static PyType_Slot dequereviter_slots[] = {
2156     {Py_tp_dealloc, dequeiter_dealloc},
2157     {Py_tp_getattro, PyObject_GenericGetAttr},
2158     {Py_tp_traverse, dequeiter_traverse},
2159     {Py_tp_clear, dequeiter_clear},
2160     {Py_tp_iter, PyObject_SelfIter},
2161     {Py_tp_iternext, dequereviter_next},
2162     {Py_tp_methods, dequeiter_methods},
2163     {Py_tp_new, dequereviter_new},
2164     {0, NULL},
2165 };
2166 
2167 static PyType_Spec dequereviter_spec = {
2168     .name = "collections._deque_reverse_iterator",
2169     .basicsize = sizeof(dequeiterobject),
2170     .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2171               Py_TPFLAGS_IMMUTABLETYPE),
2172     .slots = dequereviter_slots,
2173 };
2174 
2175 /* defaultdict type *********************************************************/
2176 
2177 typedef struct {
2178     PyDictObject dict;
2179     PyObject *default_factory;
2180 } defdictobject;
2181 
2182 PyDoc_STRVAR(defdict_missing_doc,
2183 "__missing__(key) # Called by __getitem__ for missing key; pseudo-code:\n\
2184   if self.default_factory is None: raise KeyError((key,))\n\
2185   self[key] = value = self.default_factory()\n\
2186   return value\n\
2187 ");
2188 
2189 static PyObject *
defdict_missing(defdictobject * dd,PyObject * key)2190 defdict_missing(defdictobject *dd, PyObject *key)
2191 {
2192     PyObject *factory = dd->default_factory;
2193     PyObject *value;
2194     if (factory == NULL || factory == Py_None) {
2195         /* XXX Call dict.__missing__(key) */
2196         PyObject *tup;
2197         tup = PyTuple_Pack(1, key);
2198         if (!tup) return NULL;
2199         PyErr_SetObject(PyExc_KeyError, tup);
2200         Py_DECREF(tup);
2201         return NULL;
2202     }
2203     value = _PyObject_CallNoArgs(factory);
2204     if (value == NULL)
2205         return value;
2206     if (PyObject_SetItem((PyObject *)dd, key, value) < 0) {
2207         Py_DECREF(value);
2208         return NULL;
2209     }
2210     return value;
2211 }
2212 
2213 static inline PyObject*
new_defdict(defdictobject * dd,PyObject * arg)2214 new_defdict(defdictobject *dd, PyObject *arg)
2215 {
2216     return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd),
2217         dd->default_factory ? dd->default_factory : Py_None, arg, NULL);
2218 }
2219 
2220 PyDoc_STRVAR(defdict_copy_doc, "D.copy() -> a shallow copy of D.");
2221 
2222 static PyObject *
defdict_copy(defdictobject * dd,PyObject * Py_UNUSED (ignored))2223 defdict_copy(defdictobject *dd, PyObject *Py_UNUSED(ignored))
2224 {
2225     /* This calls the object's class.  That only works for subclasses
2226        whose class constructor has the same signature.  Subclasses that
2227        define a different constructor signature must override copy().
2228     */
2229     return new_defdict(dd, (PyObject*)dd);
2230 }
2231 
2232 static PyObject *
defdict_reduce(defdictobject * dd,PyObject * Py_UNUSED (ignored))2233 defdict_reduce(defdictobject *dd, PyObject *Py_UNUSED(ignored))
2234 {
2235     /* __reduce__ must return a 5-tuple as follows:
2236 
2237        - factory function
2238        - tuple of args for the factory function
2239        - additional state (here None)
2240        - sequence iterator (here None)
2241        - dictionary iterator (yielding successive (key, value) pairs
2242 
2243        This API is used by pickle.py and copy.py.
2244 
2245        For this to be useful with pickle.py, the default_factory
2246        must be picklable; e.g., None, a built-in, or a global
2247        function in a module or package.
2248 
2249        Both shallow and deep copying are supported, but for deep
2250        copying, the default_factory must be deep-copyable; e.g. None,
2251        or a built-in (functions are not copyable at this time).
2252 
2253        This only works for subclasses as long as their constructor
2254        signature is compatible; the first argument must be the
2255        optional default_factory, defaulting to None.
2256     */
2257     PyObject *args;
2258     PyObject *items;
2259     PyObject *iter;
2260     PyObject *result;
2261 
2262     if (dd->default_factory == NULL || dd->default_factory == Py_None)
2263         args = PyTuple_New(0);
2264     else
2265         args = PyTuple_Pack(1, dd->default_factory);
2266     if (args == NULL)
2267         return NULL;
2268     items = PyObject_CallMethodNoArgs((PyObject *)dd, &_Py_ID(items));
2269     if (items == NULL) {
2270         Py_DECREF(args);
2271         return NULL;
2272     }
2273     iter = PyObject_GetIter(items);
2274     if (iter == NULL) {
2275         Py_DECREF(items);
2276         Py_DECREF(args);
2277         return NULL;
2278     }
2279     result = PyTuple_Pack(5, Py_TYPE(dd), args,
2280                           Py_None, Py_None, iter);
2281     Py_DECREF(iter);
2282     Py_DECREF(items);
2283     Py_DECREF(args);
2284     return result;
2285 }
2286 
2287 static PyMethodDef defdict_methods[] = {
2288     {"__missing__", (PyCFunction)defdict_missing, METH_O,
2289      defdict_missing_doc},
2290     {"copy", (PyCFunction)defdict_copy, METH_NOARGS,
2291      defdict_copy_doc},
2292     {"__copy__", (PyCFunction)defdict_copy, METH_NOARGS,
2293      defdict_copy_doc},
2294     {"__reduce__", (PyCFunction)defdict_reduce, METH_NOARGS,
2295      reduce_doc},
2296     {"__class_getitem__", Py_GenericAlias, METH_O|METH_CLASS,
2297      PyDoc_STR("See PEP 585")},
2298     {NULL}
2299 };
2300 
2301 static PyMemberDef defdict_members[] = {
2302     {"default_factory", _Py_T_OBJECT,
2303      offsetof(defdictobject, default_factory), 0,
2304      PyDoc_STR("Factory for default value called by __missing__().")},
2305     {NULL}
2306 };
2307 
2308 static void
defdict_dealloc(defdictobject * dd)2309 defdict_dealloc(defdictobject *dd)
2310 {
2311     /* bpo-31095: UnTrack is needed before calling any callbacks */
2312     PyTypeObject *tp = Py_TYPE(dd);
2313     PyObject_GC_UnTrack(dd);
2314     Py_CLEAR(dd->default_factory);
2315     PyDict_Type.tp_dealloc((PyObject *)dd);
2316     Py_DECREF(tp);
2317 }
2318 
2319 static PyObject *
defdict_repr(defdictobject * dd)2320 defdict_repr(defdictobject *dd)
2321 {
2322     PyObject *baserepr;
2323     PyObject *defrepr;
2324     PyObject *result;
2325     baserepr = PyDict_Type.tp_repr((PyObject *)dd);
2326     if (baserepr == NULL)
2327         return NULL;
2328     if (dd->default_factory == NULL)
2329         defrepr = PyUnicode_FromString("None");
2330     else
2331     {
2332         int status = Py_ReprEnter(dd->default_factory);
2333         if (status != 0) {
2334             if (status < 0) {
2335                 Py_DECREF(baserepr);
2336                 return NULL;
2337             }
2338             defrepr = PyUnicode_FromString("...");
2339         }
2340         else
2341             defrepr = PyObject_Repr(dd->default_factory);
2342         Py_ReprLeave(dd->default_factory);
2343     }
2344     if (defrepr == NULL) {
2345         Py_DECREF(baserepr);
2346         return NULL;
2347     }
2348     result = PyUnicode_FromFormat("%s(%U, %U)",
2349                                   _PyType_Name(Py_TYPE(dd)),
2350                                   defrepr, baserepr);
2351     Py_DECREF(defrepr);
2352     Py_DECREF(baserepr);
2353     return result;
2354 }
2355 
2356 static PyObject*
defdict_or(PyObject * left,PyObject * right)2357 defdict_or(PyObject* left, PyObject* right)
2358 {
2359     PyObject *self, *other;
2360 
2361     // Find module state
2362     PyTypeObject *tp = Py_TYPE(left);
2363     PyObject *mod = PyType_GetModuleByDef(tp, &_collectionsmodule);
2364     if (mod == NULL) {
2365         PyErr_Clear();
2366         tp = Py_TYPE(right);
2367         mod = PyType_GetModuleByDef(tp, &_collectionsmodule);
2368     }
2369     assert(mod != NULL);
2370     collections_state *state = get_module_state(mod);
2371 
2372     if (PyObject_TypeCheck(left, state->defdict_type)) {
2373         self = left;
2374         other = right;
2375     }
2376     else {
2377         assert(PyObject_TypeCheck(right, state->defdict_type));
2378         self = right;
2379         other = left;
2380     }
2381     if (!PyDict_Check(other)) {
2382         Py_RETURN_NOTIMPLEMENTED;
2383     }
2384     // Like copy(), this calls the object's class.
2385     // Override __or__/__ror__ for subclasses with different constructors.
2386     PyObject *new = new_defdict((defdictobject*)self, left);
2387     if (!new) {
2388         return NULL;
2389     }
2390     if (PyDict_Update(new, right)) {
2391         Py_DECREF(new);
2392         return NULL;
2393     }
2394     return new;
2395 }
2396 
2397 static int
defdict_traverse(PyObject * self,visitproc visit,void * arg)2398 defdict_traverse(PyObject *self, visitproc visit, void *arg)
2399 {
2400     Py_VISIT(Py_TYPE(self));
2401     Py_VISIT(((defdictobject *)self)->default_factory);
2402     return PyDict_Type.tp_traverse(self, visit, arg);
2403 }
2404 
2405 static int
defdict_tp_clear(defdictobject * dd)2406 defdict_tp_clear(defdictobject *dd)
2407 {
2408     Py_CLEAR(dd->default_factory);
2409     return PyDict_Type.tp_clear((PyObject *)dd);
2410 }
2411 
2412 static int
defdict_init(PyObject * self,PyObject * args,PyObject * kwds)2413 defdict_init(PyObject *self, PyObject *args, PyObject *kwds)
2414 {
2415     defdictobject *dd = (defdictobject *)self;
2416     PyObject *olddefault = dd->default_factory;
2417     PyObject *newdefault = NULL;
2418     PyObject *newargs;
2419     int result;
2420     if (args == NULL || !PyTuple_Check(args))
2421         newargs = PyTuple_New(0);
2422     else {
2423         Py_ssize_t n = PyTuple_GET_SIZE(args);
2424         if (n > 0) {
2425             newdefault = PyTuple_GET_ITEM(args, 0);
2426             if (!PyCallable_Check(newdefault) && newdefault != Py_None) {
2427                 PyErr_SetString(PyExc_TypeError,
2428                     "first argument must be callable or None");
2429                 return -1;
2430             }
2431         }
2432         newargs = PySequence_GetSlice(args, 1, n);
2433     }
2434     if (newargs == NULL)
2435         return -1;
2436     dd->default_factory = Py_XNewRef(newdefault);
2437     result = PyDict_Type.tp_init(self, newargs, kwds);
2438     Py_DECREF(newargs);
2439     Py_XDECREF(olddefault);
2440     return result;
2441 }
2442 
2443 PyDoc_STRVAR(defdict_doc,
2444 "defaultdict(default_factory=None, /, [...]) --> dict with default factory\n\
2445 \n\
2446 The default factory is called without arguments to produce\n\
2447 a new value when a key is not present, in __getitem__ only.\n\
2448 A defaultdict compares equal to a dict with the same items.\n\
2449 All remaining arguments are treated the same as if they were\n\
2450 passed to the dict constructor, including keyword arguments.\n\
2451 ");
2452 
2453 /* See comment in xxsubtype.c */
2454 #define DEFERRED_ADDRESS(ADDR) 0
2455 
2456 static PyType_Slot defdict_slots[] = {
2457     {Py_tp_dealloc, defdict_dealloc},
2458     {Py_tp_repr, defdict_repr},
2459     {Py_nb_or, defdict_or},
2460     {Py_tp_getattro, PyObject_GenericGetAttr},
2461     {Py_tp_doc, (void *)defdict_doc},
2462     {Py_tp_traverse, defdict_traverse},
2463     {Py_tp_clear, defdict_tp_clear},
2464     {Py_tp_methods, defdict_methods},
2465     {Py_tp_members, defdict_members},
2466     {Py_tp_init, defdict_init},
2467     {Py_tp_alloc, PyType_GenericAlloc},
2468     {Py_tp_free, PyObject_GC_Del},
2469     {0, NULL},
2470 };
2471 
2472 static PyType_Spec defdict_spec = {
2473     .name = "collections.defaultdict",
2474     .basicsize = sizeof(defdictobject),
2475     .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
2476               Py_TPFLAGS_IMMUTABLETYPE),
2477     .slots = defdict_slots,
2478 };
2479 
2480 /* helper function for Counter  *********************************************/
2481 
2482 /*[clinic input]
2483 _collections._count_elements
2484 
2485     mapping: object
2486     iterable: object
2487     /
2488 
2489 Count elements in the iterable, updating the mapping
2490 [clinic start generated code]*/
2491 
2492 static PyObject *
_collections__count_elements_impl(PyObject * module,PyObject * mapping,PyObject * iterable)2493 _collections__count_elements_impl(PyObject *module, PyObject *mapping,
2494                                   PyObject *iterable)
2495 /*[clinic end generated code: output=7e0c1789636b3d8f input=e79fad04534a0b45]*/
2496 {
2497     PyObject *it, *oldval;
2498     PyObject *newval = NULL;
2499     PyObject *key = NULL;
2500     PyObject *bound_get = NULL;
2501     PyObject *mapping_get;
2502     PyObject *dict_get;
2503     PyObject *mapping_setitem;
2504     PyObject *dict_setitem;
2505     PyObject *one = _PyLong_GetOne();  // borrowed reference
2506 
2507     it = PyObject_GetIter(iterable);
2508     if (it == NULL)
2509         return NULL;
2510 
2511     /* Only take the fast path when get() and __setitem__()
2512      * have not been overridden.
2513      */
2514     mapping_get = _PyType_LookupRef(Py_TYPE(mapping), &_Py_ID(get));
2515     dict_get = _PyType_Lookup(&PyDict_Type, &_Py_ID(get));
2516     mapping_setitem = _PyType_LookupRef(Py_TYPE(mapping), &_Py_ID(__setitem__));
2517     dict_setitem = _PyType_Lookup(&PyDict_Type, &_Py_ID(__setitem__));
2518 
2519     if (mapping_get != NULL && mapping_get == dict_get &&
2520         mapping_setitem != NULL && mapping_setitem == dict_setitem &&
2521         PyDict_Check(mapping))
2522     {
2523         while (1) {
2524             /* Fast path advantages:
2525                    1. Eliminate double hashing
2526                       (by re-using the same hash for both the get and set)
2527                    2. Avoid argument overhead of PyObject_CallFunctionObjArgs
2528                       (argument tuple creation and parsing)
2529                    3. Avoid indirection through a bound method object
2530                       (creates another argument tuple)
2531                    4. Avoid initial increment from zero
2532                       (reuse an existing one-object instead)
2533             */
2534             Py_hash_t hash;
2535 
2536             key = PyIter_Next(it);
2537             if (key == NULL)
2538                 break;
2539 
2540             hash = _PyObject_HashFast(key);
2541             if (hash == -1) {
2542                 goto done;
2543             }
2544 
2545             oldval = _PyDict_GetItem_KnownHash(mapping, key, hash);
2546             if (oldval == NULL) {
2547                 if (PyErr_Occurred())
2548                     goto done;
2549                 if (_PyDict_SetItem_KnownHash(mapping, key, one, hash) < 0)
2550                     goto done;
2551             } else {
2552                 newval = PyNumber_Add(oldval, one);
2553                 if (newval == NULL)
2554                     goto done;
2555                 if (_PyDict_SetItem_KnownHash(mapping, key, newval, hash) < 0)
2556                     goto done;
2557                 Py_CLEAR(newval);
2558             }
2559             Py_DECREF(key);
2560         }
2561     }
2562     else {
2563         bound_get = PyObject_GetAttr(mapping, &_Py_ID(get));
2564         if (bound_get == NULL)
2565             goto done;
2566 
2567         PyObject *zero = _PyLong_GetZero();  // borrowed reference
2568         while (1) {
2569             key = PyIter_Next(it);
2570             if (key == NULL)
2571                 break;
2572             oldval = PyObject_CallFunctionObjArgs(bound_get, key, zero, NULL);
2573             if (oldval == NULL)
2574                 break;
2575             newval = PyNumber_Add(oldval, one);
2576             Py_DECREF(oldval);
2577             if (newval == NULL)
2578                 break;
2579             if (PyObject_SetItem(mapping, key, newval) < 0)
2580                 break;
2581             Py_CLEAR(newval);
2582             Py_DECREF(key);
2583         }
2584     }
2585 
2586 done:
2587     Py_XDECREF(mapping_get);
2588     Py_XDECREF(mapping_setitem);
2589     Py_DECREF(it);
2590     Py_XDECREF(key);
2591     Py_XDECREF(newval);
2592     Py_XDECREF(bound_get);
2593     if (PyErr_Occurred())
2594         return NULL;
2595     Py_RETURN_NONE;
2596 }
2597 
2598 /* Helper function for namedtuple() ************************************/
2599 
2600 typedef struct {
2601     PyObject_HEAD
2602     Py_ssize_t index;
2603     PyObject* doc;
2604 } _tuplegetterobject;
2605 
2606 /*[clinic input]
2607 @classmethod
2608 _tuplegetter.__new__ as tuplegetter_new
2609 
2610     index: Py_ssize_t
2611     doc: object
2612     /
2613 [clinic start generated code]*/
2614 
2615 static PyObject *
tuplegetter_new_impl(PyTypeObject * type,Py_ssize_t index,PyObject * doc)2616 tuplegetter_new_impl(PyTypeObject *type, Py_ssize_t index, PyObject *doc)
2617 /*[clinic end generated code: output=014be444ad80263f input=87c576a5bdbc0bbb]*/
2618 {
2619     _tuplegetterobject* self;
2620     self = (_tuplegetterobject *)type->tp_alloc(type, 0);
2621     if (self == NULL) {
2622         return NULL;
2623     }
2624     self->index = index;
2625     self->doc = Py_NewRef(doc);
2626     return (PyObject *)self;
2627 }
2628 
2629 static PyObject *
tuplegetter_descr_get(PyObject * self,PyObject * obj,PyObject * type)2630 tuplegetter_descr_get(PyObject *self, PyObject *obj, PyObject *type)
2631 {
2632     Py_ssize_t index = ((_tuplegetterobject*)self)->index;
2633     PyObject *result;
2634 
2635     if (obj == NULL) {
2636         return Py_NewRef(self);
2637     }
2638     if (!PyTuple_Check(obj)) {
2639         if (obj == Py_None) {
2640             return Py_NewRef(self);
2641         }
2642         PyErr_Format(PyExc_TypeError,
2643                      "descriptor for index '%zd' for tuple subclasses "
2644                      "doesn't apply to '%s' object",
2645                      index,
2646                      Py_TYPE(obj)->tp_name);
2647         return NULL;
2648     }
2649 
2650     if (!valid_index(index, PyTuple_GET_SIZE(obj))) {
2651         PyErr_SetString(PyExc_IndexError, "tuple index out of range");
2652         return NULL;
2653     }
2654 
2655     result = PyTuple_GET_ITEM(obj, index);
2656     return Py_NewRef(result);
2657 }
2658 
2659 static int
tuplegetter_descr_set(PyObject * self,PyObject * obj,PyObject * value)2660 tuplegetter_descr_set(PyObject *self, PyObject *obj, PyObject *value)
2661 {
2662     if (value == NULL) {
2663         PyErr_SetString(PyExc_AttributeError, "can't delete attribute");
2664     } else {
2665         PyErr_SetString(PyExc_AttributeError, "can't set attribute");
2666     }
2667     return -1;
2668 }
2669 
2670 static int
tuplegetter_traverse(PyObject * self,visitproc visit,void * arg)2671 tuplegetter_traverse(PyObject *self, visitproc visit, void *arg)
2672 {
2673     _tuplegetterobject *tuplegetter = (_tuplegetterobject *)self;
2674     Py_VISIT(Py_TYPE(tuplegetter));
2675     Py_VISIT(tuplegetter->doc);
2676     return 0;
2677 }
2678 
2679 static int
tuplegetter_clear(PyObject * self)2680 tuplegetter_clear(PyObject *self)
2681 {
2682     _tuplegetterobject *tuplegetter = (_tuplegetterobject *)self;
2683     Py_CLEAR(tuplegetter->doc);
2684     return 0;
2685 }
2686 
2687 static void
tuplegetter_dealloc(_tuplegetterobject * self)2688 tuplegetter_dealloc(_tuplegetterobject *self)
2689 {
2690     PyTypeObject *tp = Py_TYPE(self);
2691     PyObject_GC_UnTrack(self);
2692     tuplegetter_clear((PyObject*)self);
2693     tp->tp_free((PyObject*)self);
2694     Py_DECREF(tp);
2695 }
2696 
2697 static PyObject*
tuplegetter_reduce(_tuplegetterobject * self,PyObject * Py_UNUSED (ignored))2698 tuplegetter_reduce(_tuplegetterobject *self, PyObject *Py_UNUSED(ignored))
2699 {
2700     return Py_BuildValue("(O(nO))", (PyObject*) Py_TYPE(self), self->index, self->doc);
2701 }
2702 
2703 static PyObject*
tuplegetter_repr(_tuplegetterobject * self)2704 tuplegetter_repr(_tuplegetterobject *self)
2705 {
2706     return PyUnicode_FromFormat("%s(%zd, %R)",
2707                                 _PyType_Name(Py_TYPE(self)),
2708                                 self->index, self->doc);
2709 }
2710 
2711 
2712 static PyMemberDef tuplegetter_members[] = {
2713     {"__doc__",  _Py_T_OBJECT, offsetof(_tuplegetterobject, doc), 0},
2714     {0}
2715 };
2716 
2717 static PyMethodDef tuplegetter_methods[] = {
2718     {"__reduce__", (PyCFunction)tuplegetter_reduce, METH_NOARGS, NULL},
2719     {NULL},
2720 };
2721 
2722 static PyType_Slot tuplegetter_slots[] = {
2723     {Py_tp_dealloc, tuplegetter_dealloc},
2724     {Py_tp_repr, tuplegetter_repr},
2725     {Py_tp_traverse, tuplegetter_traverse},
2726     {Py_tp_clear, tuplegetter_clear},
2727     {Py_tp_methods, tuplegetter_methods},
2728     {Py_tp_members, tuplegetter_members},
2729     {Py_tp_descr_get, tuplegetter_descr_get},
2730     {Py_tp_descr_set, tuplegetter_descr_set},
2731     {Py_tp_new, tuplegetter_new},
2732     {0, NULL},
2733 };
2734 
2735 static PyType_Spec tuplegetter_spec = {
2736     .name = "collections._tuplegetter",
2737     .basicsize = sizeof(_tuplegetterobject),
2738     .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2739               Py_TPFLAGS_IMMUTABLETYPE),
2740     .slots = tuplegetter_slots,
2741 };
2742 
2743 
2744 /* module level code ********************************************************/
2745 
2746 static int
collections_traverse(PyObject * mod,visitproc visit,void * arg)2747 collections_traverse(PyObject *mod, visitproc visit, void *arg)
2748 {
2749     collections_state *state = get_module_state(mod);
2750     Py_VISIT(state->deque_type);
2751     Py_VISIT(state->defdict_type);
2752     Py_VISIT(state->dequeiter_type);
2753     Py_VISIT(state->dequereviter_type);
2754     Py_VISIT(state->tuplegetter_type);
2755     return 0;
2756 }
2757 
2758 static int
collections_clear(PyObject * mod)2759 collections_clear(PyObject *mod)
2760 {
2761     collections_state *state = get_module_state(mod);
2762     Py_CLEAR(state->deque_type);
2763     Py_CLEAR(state->defdict_type);
2764     Py_CLEAR(state->dequeiter_type);
2765     Py_CLEAR(state->dequereviter_type);
2766     Py_CLEAR(state->tuplegetter_type);
2767     return 0;
2768 }
2769 
2770 static void
collections_free(void * module)2771 collections_free(void *module)
2772 {
2773     collections_clear((PyObject *)module);
2774 }
2775 
2776 PyDoc_STRVAR(collections_doc,
2777 "High performance data structures.\n\
2778 - deque:        ordered collection accessible from endpoints only\n\
2779 - defaultdict:  dict subclass with a default value factory\n\
2780 ");
2781 
2782 static struct PyMethodDef collections_methods[] = {
2783     _COLLECTIONS__COUNT_ELEMENTS_METHODDEF
2784     {NULL,       NULL}          /* sentinel */
2785 };
2786 
2787 #define ADD_TYPE(MOD, SPEC, TYPE, BASE) do {                        \
2788     TYPE = (PyTypeObject *)PyType_FromMetaclass(NULL, MOD, SPEC,    \
2789                                                 (PyObject *)BASE);  \
2790     if (TYPE == NULL) {                                             \
2791         return -1;                                                  \
2792     }                                                               \
2793     if (PyModule_AddType(MOD, TYPE) < 0) {                          \
2794         return -1;                                                  \
2795     }                                                               \
2796 } while (0)
2797 
2798 static int
collections_exec(PyObject * module)2799 collections_exec(PyObject *module) {
2800     collections_state *state = get_module_state(module);
2801     ADD_TYPE(module, &deque_spec, state->deque_type, NULL);
2802     ADD_TYPE(module, &defdict_spec, state->defdict_type, &PyDict_Type);
2803     ADD_TYPE(module, &dequeiter_spec, state->dequeiter_type, NULL);
2804     ADD_TYPE(module, &dequereviter_spec, state->dequereviter_type, NULL);
2805     ADD_TYPE(module, &tuplegetter_spec, state->tuplegetter_type, NULL);
2806 
2807     if (PyModule_AddType(module, &PyODict_Type) < 0) {
2808         return -1;
2809     }
2810 
2811     return 0;
2812 }
2813 
2814 #undef ADD_TYPE
2815 
2816 static struct PyModuleDef_Slot collections_slots[] = {
2817     {Py_mod_exec, collections_exec},
2818     {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
2819     {Py_mod_gil, Py_MOD_GIL_NOT_USED},
2820     {0, NULL}
2821 };
2822 
2823 static struct PyModuleDef _collectionsmodule = {
2824     .m_base = PyModuleDef_HEAD_INIT,
2825     .m_name = "_collections",
2826     .m_doc = collections_doc,
2827     .m_size = sizeof(collections_state),
2828     .m_methods = collections_methods,
2829     .m_slots = collections_slots,
2830     .m_traverse = collections_traverse,
2831     .m_clear = collections_clear,
2832     .m_free = collections_free,
2833 };
2834 
2835 PyMODINIT_FUNC
PyInit__collections(void)2836 PyInit__collections(void)
2837 {
2838     return PyModuleDef_Init(&_collectionsmodule);
2839 }
2840