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