Coverage Report

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