Coverage Report

Created: 2025-07-11 06:24

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