Coverage Report

Created: 2026-12-01 06:09

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