Coverage Report

Created: 2026-10-17 06:15

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