Coverage Report

Created: 2026-10-31 06:21

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