Coverage Report

Created: 2026-02-26 06:53

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