forked from python/cpython
-
Notifications
You must be signed in to change notification settings - Fork 0
/
_collectionsmodule.c
2615 lines (2348 loc) · 79.2 KB
/
_collectionsmodule.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "Python.h"
#include "structmember.h" // PyMemberDef
#ifdef STDC_HEADERS
#include <stddef.h>
#else
#include <sys/types.h> // size_t
#endif
/*[clinic input]
module _collections
class _tuplegetter "_tuplegetterobject *" "&tuplegetter_type"
[clinic start generated code]*/
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=a8ece4ccad7e30ac]*/
static PyTypeObject tuplegetter_type;
#include "clinic/_collectionsmodule.c.h"
/* collections module implementation of a deque() datatype
Written and maintained by Raymond D. Hettinger <[email protected]>
*/
/* The block length may be set to any number over 1. Larger numbers
* reduce the number of calls to the memory allocator, give faster
* indexing and rotation, and reduce the link to data overhead ratio.
* Making the block length a power of two speeds-up the modulo
* and division calculations in deque_item() and deque_ass_item().
*/
#define BLOCKLEN 64
#define CENTER ((BLOCKLEN - 1) / 2)
/* Data for deque objects is stored in a doubly-linked list of fixed
* length blocks. This assures that appends or pops never move any
* other data elements besides the one being appended or popped.
*
* Another advantage is that it completely avoids use of realloc(),
* resulting in more predictable performance.
*
* Textbook implementations of doubly-linked lists store one datum
* per link, but that gives them a 200% memory overhead (a prev and
* next link for each datum) and it costs one malloc() call per data
* element. By using fixed-length blocks, the link to data ratio is
* significantly improved and there are proportionally fewer calls
* to malloc() and free(). The data blocks of consecutive pointers
* also improve cache locality.
*
* The list of blocks is never empty, so d.leftblock and d.rightblock
* are never equal to NULL. The list is not circular.
*
* A deque d's first element is at d.leftblock[leftindex]
* and its last element is at d.rightblock[rightindex].
*
* Unlike Python slice indices, these indices are inclusive on both
* ends. This makes the algorithms for left and right operations
* more symmetrical and it simplifies the design.
*
* The indices, d.leftindex and d.rightindex are always in the range:
* 0 <= index < BLOCKLEN
*
* And their exact relationship is:
* (d.leftindex + d.len - 1) % BLOCKLEN == d.rightindex
*
* Whenever d.leftblock == d.rightblock, then:
* d.leftindex + d.len - 1 == d.rightindex
*
* However, when d.leftblock != d.rightblock, the d.leftindex and
* d.rightindex become indices into distinct blocks and either may
* be larger than the other.
*
* Empty deques have:
* d.len == 0
* d.leftblock == d.rightblock
* d.leftindex == CENTER + 1
* d.rightindex == CENTER
*
* Checking for d.len == 0 is the intended way to see whether d is empty.
*/
typedef struct BLOCK {
struct BLOCK *leftlink;
PyObject *data[BLOCKLEN];
struct BLOCK *rightlink;
} block;
typedef struct {
PyObject_VAR_HEAD
block *leftblock;
block *rightblock;
Py_ssize_t leftindex; /* 0 <= leftindex < BLOCKLEN */
Py_ssize_t rightindex; /* 0 <= rightindex < BLOCKLEN */
size_t state; /* incremented whenever the indices move */
Py_ssize_t maxlen; /* maxlen is -1 for unbounded deques */
PyObject *weakreflist;
} dequeobject;
static PyTypeObject deque_type;
/* For debug builds, add error checking to track the endpoints
* in the chain of links. The goal is to make sure that link
* assignments only take place at endpoints so that links already
* in use do not get overwritten.
*
* CHECK_END should happen before each assignment to a block's link field.
* MARK_END should happen whenever a link field becomes a new endpoint.
* This happens when new blocks are added or whenever an existing
* block is freed leaving another existing block as the new endpoint.
*/
#ifndef NDEBUG
#define MARK_END(link) link = NULL;
#define CHECK_END(link) assert(link == NULL);
#define CHECK_NOT_END(link) assert(link != NULL);
#else
#define MARK_END(link)
#define CHECK_END(link)
#define CHECK_NOT_END(link)
#endif
/* A simple freelisting scheme is used to minimize calls to the memory
allocator. It accommodates common use cases where new blocks are being
added at about the same rate as old blocks are being freed.
*/
#define MAXFREEBLOCKS 16
static Py_ssize_t numfreeblocks = 0;
static block *freeblocks[MAXFREEBLOCKS];
static block *
newblock(void) {
block *b;
if (numfreeblocks) {
numfreeblocks--;
return freeblocks[numfreeblocks];
}
b = PyMem_Malloc(sizeof(block));
if (b != NULL) {
return b;
}
PyErr_NoMemory();
return NULL;
}
static void
freeblock(block *b)
{
if (numfreeblocks < MAXFREEBLOCKS) {
freeblocks[numfreeblocks] = b;
numfreeblocks++;
} else {
PyMem_Free(b);
}
}
static PyObject *
deque_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
dequeobject *deque;
block *b;
/* create dequeobject structure */
deque = (dequeobject *)type->tp_alloc(type, 0);
if (deque == NULL)
return NULL;
b = newblock();
if (b == NULL) {
Py_DECREF(deque);
return NULL;
}
MARK_END(b->leftlink);
MARK_END(b->rightlink);
assert(BLOCKLEN >= 2);
Py_SET_SIZE(deque, 0);
deque->leftblock = b;
deque->rightblock = b;
deque->leftindex = CENTER + 1;
deque->rightindex = CENTER;
deque->state = 0;
deque->maxlen = -1;
deque->weakreflist = NULL;
return (PyObject *)deque;
}
static PyObject *
deque_pop(dequeobject *deque, PyObject *unused)
{
PyObject *item;
block *prevblock;
if (Py_SIZE(deque) == 0) {
PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
return NULL;
}
item = deque->rightblock->data[deque->rightindex];
deque->rightindex--;
Py_SET_SIZE(deque, Py_SIZE(deque) - 1);
deque->state++;
if (deque->rightindex < 0) {
if (Py_SIZE(deque)) {
prevblock = deque->rightblock->leftlink;
assert(deque->leftblock != deque->rightblock);
freeblock(deque->rightblock);
CHECK_NOT_END(prevblock);
MARK_END(prevblock->rightlink);
deque->rightblock = prevblock;
deque->rightindex = BLOCKLEN - 1;
} else {
assert(deque->leftblock == deque->rightblock);
assert(deque->leftindex == deque->rightindex+1);
/* re-center instead of freeing a block */
deque->leftindex = CENTER + 1;
deque->rightindex = CENTER;
}
}
return item;
}
PyDoc_STRVAR(pop_doc, "Remove and return the rightmost element.");
static PyObject *
deque_popleft(dequeobject *deque, PyObject *unused)
{
PyObject *item;
block *prevblock;
if (Py_SIZE(deque) == 0) {
PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
return NULL;
}
assert(deque->leftblock != NULL);
item = deque->leftblock->data[deque->leftindex];
deque->leftindex++;
Py_SET_SIZE(deque, Py_SIZE(deque) - 1);
deque->state++;
if (deque->leftindex == BLOCKLEN) {
if (Py_SIZE(deque)) {
assert(deque->leftblock != deque->rightblock);
prevblock = deque->leftblock->rightlink;
freeblock(deque->leftblock);
CHECK_NOT_END(prevblock);
MARK_END(prevblock->leftlink);
deque->leftblock = prevblock;
deque->leftindex = 0;
} else {
assert(deque->leftblock == deque->rightblock);
assert(deque->leftindex == deque->rightindex+1);
/* re-center instead of freeing a block */
deque->leftindex = CENTER + 1;
deque->rightindex = CENTER;
}
}
return item;
}
PyDoc_STRVAR(popleft_doc, "Remove and return the leftmost element.");
/* The deque's size limit is d.maxlen. The limit can be zero or positive.
* If there is no limit, then d.maxlen == -1.
*
* After an item is added to a deque, we check to see if the size has
* grown past the limit. If it has, we get the size back down to the limit
* by popping an item off of the opposite end. The methods that can
* trigger this are append(), appendleft(), extend(), and extendleft().
*
* The macro to check whether a deque needs to be trimmed uses a single
* unsigned test that returns true whenever 0 <= maxlen < Py_SIZE(deque).
*/
#define NEEDS_TRIM(deque, maxlen) ((size_t)(maxlen) < (size_t)(Py_SIZE(deque)))
static inline int
deque_append_internal(dequeobject *deque, PyObject *item, Py_ssize_t maxlen)
{
if (deque->rightindex == BLOCKLEN - 1) {
block *b = newblock();
if (b == NULL)
return -1;
b->leftlink = deque->rightblock;
CHECK_END(deque->rightblock->rightlink);
deque->rightblock->rightlink = b;
deque->rightblock = b;
MARK_END(b->rightlink);
deque->rightindex = -1;
}
Py_SET_SIZE(deque, Py_SIZE(deque) + 1);
deque->rightindex++;
deque->rightblock->data[deque->rightindex] = item;
if (NEEDS_TRIM(deque, maxlen)) {
PyObject *olditem = deque_popleft(deque, NULL);
Py_DECREF(olditem);
} else {
deque->state++;
}
return 0;
}
static PyObject *
deque_append(dequeobject *deque, PyObject *item)
{
Py_INCREF(item);
if (deque_append_internal(deque, item, deque->maxlen) < 0)
return NULL;
Py_RETURN_NONE;
}
PyDoc_STRVAR(append_doc, "Add an element to the right side of the deque.");
static inline int
deque_appendleft_internal(dequeobject *deque, PyObject *item, Py_ssize_t maxlen)
{
if (deque->leftindex == 0) {
block *b = newblock();
if (b == NULL)
return -1;
b->rightlink = deque->leftblock;
CHECK_END(deque->leftblock->leftlink);
deque->leftblock->leftlink = b;
deque->leftblock = b;
MARK_END(b->leftlink);
deque->leftindex = BLOCKLEN;
}
Py_SET_SIZE(deque, Py_SIZE(deque) + 1);
deque->leftindex--;
deque->leftblock->data[deque->leftindex] = item;
if (NEEDS_TRIM(deque, deque->maxlen)) {
PyObject *olditem = deque_pop(deque, NULL);
Py_DECREF(olditem);
} else {
deque->state++;
}
return 0;
}
static PyObject *
deque_appendleft(dequeobject *deque, PyObject *item)
{
Py_INCREF(item);
if (deque_appendleft_internal(deque, item, deque->maxlen) < 0)
return NULL;
Py_RETURN_NONE;
}
PyDoc_STRVAR(appendleft_doc, "Add an element to the left side of the deque.");
static PyObject*
finalize_iterator(PyObject *it)
{
if (PyErr_Occurred()) {
if (PyErr_ExceptionMatches(PyExc_StopIteration))
PyErr_Clear();
else {
Py_DECREF(it);
return NULL;
}
}
Py_DECREF(it);
Py_RETURN_NONE;
}
/* Run an iterator to exhaustion. Shortcut for
the extend/extendleft methods when maxlen == 0. */
static PyObject*
consume_iterator(PyObject *it)
{
PyObject *(*iternext)(PyObject *);
PyObject *item;
iternext = *Py_TYPE(it)->tp_iternext;
while ((item = iternext(it)) != NULL) {
Py_DECREF(item);
}
return finalize_iterator(it);
}
static PyObject *
deque_extend(dequeobject *deque, PyObject *iterable)
{
PyObject *it, *item;
PyObject *(*iternext)(PyObject *);
Py_ssize_t maxlen = deque->maxlen;
/* Handle case where id(deque) == id(iterable) */
if ((PyObject *)deque == iterable) {
PyObject *result;
PyObject *s = PySequence_List(iterable);
if (s == NULL)
return NULL;
result = deque_extend(deque, s);
Py_DECREF(s);
return result;
}
it = PyObject_GetIter(iterable);
if (it == NULL)
return NULL;
if (maxlen == 0)
return consume_iterator(it);
/* Space saving heuristic. Start filling from the left */
if (Py_SIZE(deque) == 0) {
assert(deque->leftblock == deque->rightblock);
assert(deque->leftindex == deque->rightindex+1);
deque->leftindex = 1;
deque->rightindex = 0;
}
iternext = *Py_TYPE(it)->tp_iternext;
while ((item = iternext(it)) != NULL) {
if (deque_append_internal(deque, item, maxlen) == -1) {
Py_DECREF(item);
Py_DECREF(it);
return NULL;
}
}
return finalize_iterator(it);
}
PyDoc_STRVAR(extend_doc,
"Extend the right side of the deque with elements from the iterable");
static PyObject *
deque_extendleft(dequeobject *deque, PyObject *iterable)
{
PyObject *it, *item;
PyObject *(*iternext)(PyObject *);
Py_ssize_t maxlen = deque->maxlen;
/* Handle case where id(deque) == id(iterable) */
if ((PyObject *)deque == iterable) {
PyObject *result;
PyObject *s = PySequence_List(iterable);
if (s == NULL)
return NULL;
result = deque_extendleft(deque, s);
Py_DECREF(s);
return result;
}
it = PyObject_GetIter(iterable);
if (it == NULL)
return NULL;
if (maxlen == 0)
return consume_iterator(it);
/* Space saving heuristic. Start filling from the right */
if (Py_SIZE(deque) == 0) {
assert(deque->leftblock == deque->rightblock);
assert(deque->leftindex == deque->rightindex+1);
deque->leftindex = BLOCKLEN - 1;
deque->rightindex = BLOCKLEN - 2;
}
iternext = *Py_TYPE(it)->tp_iternext;
while ((item = iternext(it)) != NULL) {
if (deque_appendleft_internal(deque, item, maxlen) == -1) {
Py_DECREF(item);
Py_DECREF(it);
return NULL;
}
}
return finalize_iterator(it);
}
PyDoc_STRVAR(extendleft_doc,
"Extend the left side of the deque with elements from the iterable");
static PyObject *
deque_inplace_concat(dequeobject *deque, PyObject *other)
{
PyObject *result;
result = deque_extend(deque, other);
if (result == NULL)
return result;
Py_INCREF(deque);
Py_DECREF(result);
return (PyObject *)deque;
}
static PyObject *
deque_copy(PyObject *deque, PyObject *Py_UNUSED(ignored))
{
PyObject *result;
dequeobject *old_deque = (dequeobject *)deque;
if (Py_IS_TYPE(deque, &deque_type)) {
dequeobject *new_deque;
PyObject *rv;
new_deque = (dequeobject *)deque_new(&deque_type, (PyObject *)NULL, (PyObject *)NULL);
if (new_deque == NULL)
return NULL;
new_deque->maxlen = old_deque->maxlen;
/* Fast path for the deque_repeat() common case where len(deque) == 1 */
if (Py_SIZE(deque) == 1) {
PyObject *item = old_deque->leftblock->data[old_deque->leftindex];
rv = deque_append(new_deque, item);
} else {
rv = deque_extend(new_deque, deque);
}
if (rv != NULL) {
Py_DECREF(rv);
return (PyObject *)new_deque;
}
Py_DECREF(new_deque);
return NULL;
}
if (old_deque->maxlen < 0)
result = PyObject_CallOneArg((PyObject *)(Py_TYPE(deque)), deque);
else
result = PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "Oi",
deque, old_deque->maxlen, NULL);
if (result != NULL && !PyObject_TypeCheck(result, &deque_type)) {
PyErr_Format(PyExc_TypeError,
"%.200s() must return a deque, not %.200s",
Py_TYPE(deque)->tp_name, Py_TYPE(result)->tp_name);
Py_DECREF(result);
return NULL;
}
return result;
}
PyDoc_STRVAR(copy_doc, "Return a shallow copy of a deque.");
static PyObject *
deque_concat(dequeobject *deque, PyObject *other)
{
PyObject *new_deque, *result;
int rv;
rv = PyObject_IsInstance(other, (PyObject *)&deque_type);
if (rv <= 0) {
if (rv == 0) {
PyErr_Format(PyExc_TypeError,
"can only concatenate deque (not \"%.200s\") to deque",
Py_TYPE(other)->tp_name);
}
return NULL;
}
new_deque = deque_copy((PyObject *)deque, NULL);
if (new_deque == NULL)
return NULL;
result = deque_extend((dequeobject *)new_deque, other);
if (result == NULL) {
Py_DECREF(new_deque);
return NULL;
}
Py_DECREF(result);
return new_deque;
}
static int
deque_clear(dequeobject *deque)
{
block *b;
block *prevblock;
block *leftblock;
Py_ssize_t leftindex;
Py_ssize_t n, m;
PyObject *item;
PyObject **itemptr, **limit;
if (Py_SIZE(deque) == 0)
return 0;
/* During the process of clearing a deque, decrefs can cause the
deque to mutate. To avoid fatal confusion, we have to make the
deque empty before clearing the blocks and never refer to
anything via deque->ref while clearing. (This is the same
technique used for clearing lists, sets, and dicts.)
Making the deque empty requires allocating a new empty block. In
the unlikely event that memory is full, we fall back to an
alternate method that doesn't require a new block. Repeating
pops in a while-loop is slower, possibly re-entrant (and a clever
adversary could cause it to never terminate).
*/
b = newblock();
if (b == NULL) {
PyErr_Clear();
goto alternate_method;
}
/* Remember the old size, leftblock, and leftindex */
n = Py_SIZE(deque);
leftblock = deque->leftblock;
leftindex = deque->leftindex;
/* Set the deque to be empty using the newly allocated block */
MARK_END(b->leftlink);
MARK_END(b->rightlink);
Py_SET_SIZE(deque, 0);
deque->leftblock = b;
deque->rightblock = b;
deque->leftindex = CENTER + 1;
deque->rightindex = CENTER;
deque->state++;
/* Now the old size, leftblock, and leftindex are disconnected from
the empty deque and we can use them to decref the pointers.
*/
m = (BLOCKLEN - leftindex > n) ? n : BLOCKLEN - leftindex;
itemptr = &leftblock->data[leftindex];
limit = itemptr + m;
n -= m;
while (1) {
if (itemptr == limit) {
if (n == 0)
break;
CHECK_NOT_END(leftblock->rightlink);
prevblock = leftblock;
leftblock = leftblock->rightlink;
m = (n > BLOCKLEN) ? BLOCKLEN : n;
itemptr = leftblock->data;
limit = itemptr + m;
n -= m;
freeblock(prevblock);
}
item = *(itemptr++);
Py_DECREF(item);
}
CHECK_END(leftblock->rightlink);
freeblock(leftblock);
return 0;
alternate_method:
while (Py_SIZE(deque)) {
item = deque_pop(deque, NULL);
assert (item != NULL);
Py_DECREF(item);
}
return 0;
}
static PyObject *
deque_clearmethod(dequeobject *deque, PyObject *Py_UNUSED(ignored))
{
deque_clear(deque);
Py_RETURN_NONE;
}
PyDoc_STRVAR(clear_doc, "Remove all elements from the deque.");
static PyObject *
deque_inplace_repeat(dequeobject *deque, Py_ssize_t n)
{
Py_ssize_t i, m, size;
PyObject *seq;
PyObject *rv;
size = Py_SIZE(deque);
if (size == 0 || n == 1) {
Py_INCREF(deque);
return (PyObject *)deque;
}
if (n <= 0) {
deque_clear(deque);
Py_INCREF(deque);
return (PyObject *)deque;
}
if (size == 1) {
/* common case, repeating a single element */
PyObject *item = deque->leftblock->data[deque->leftindex];
if (deque->maxlen >= 0 && n > deque->maxlen)
n = deque->maxlen;
deque->state++;
for (i = 0 ; i < n-1 ; ) {
if (deque->rightindex == BLOCKLEN - 1) {
block *b = newblock();
if (b == NULL) {
Py_SET_SIZE(deque, Py_SIZE(deque) + i);
return NULL;
}
b->leftlink = deque->rightblock;
CHECK_END(deque->rightblock->rightlink);
deque->rightblock->rightlink = b;
deque->rightblock = b;
MARK_END(b->rightlink);
deque->rightindex = -1;
}
m = n - 1 - i;
if (m > BLOCKLEN - 1 - deque->rightindex)
m = BLOCKLEN - 1 - deque->rightindex;
i += m;
while (m--) {
deque->rightindex++;
Py_INCREF(item);
deque->rightblock->data[deque->rightindex] = item;
}
}
Py_SET_SIZE(deque, Py_SIZE(deque) + i);
Py_INCREF(deque);
return (PyObject *)deque;
}
if ((size_t)size > PY_SSIZE_T_MAX / (size_t)n) {
return PyErr_NoMemory();
}
seq = PySequence_List((PyObject *)deque);
if (seq == NULL)
return seq;
/* Reduce the number of repetitions when maxlen would be exceeded */
if (deque->maxlen >= 0 && n * size > deque->maxlen)
n = (deque->maxlen + size - 1) / size;
for (i = 0 ; i < n-1 ; i++) {
rv = deque_extend(deque, seq);
if (rv == NULL) {
Py_DECREF(seq);
return NULL;
}
Py_DECREF(rv);
}
Py_INCREF(deque);
Py_DECREF(seq);
return (PyObject *)deque;
}
static PyObject *
deque_repeat(dequeobject *deque, Py_ssize_t n)
{
dequeobject *new_deque;
PyObject *rv;
new_deque = (dequeobject *)deque_copy((PyObject *) deque, NULL);
if (new_deque == NULL)
return NULL;
rv = deque_inplace_repeat(new_deque, n);
Py_DECREF(new_deque);
return rv;
}
/* The rotate() method is part of the public API and is used internally
as a primitive for other methods.
Rotation by 1 or -1 is a common case, so any optimizations for high
volume rotations should take care not to penalize the common case.
Conceptually, a rotate by one is equivalent to a pop on one side and an
append on the other. However, a pop/append pair is unnecessarily slow
because it requires an incref/decref pair for an object located randomly
in memory. It is better to just move the object pointer from one block
to the next without changing the reference count.
When moving batches of pointers, it is tempting to use memcpy() but that
proved to be slower than a simple loop for a variety of reasons.
Memcpy() cannot know in advance that we're copying pointers instead of
bytes, that the source and destination are pointer aligned and
non-overlapping, that moving just one pointer is a common case, that we
never need to move more than BLOCKLEN pointers, and that at least one
pointer is always moved.
For high volume rotations, newblock() and freeblock() are never called
more than once. Previously emptied blocks are immediately reused as a
destination block. If a block is left-over at the end, it is freed.
*/
static int
_deque_rotate(dequeobject *deque, Py_ssize_t n)
{
block *b = NULL;
block *leftblock = deque->leftblock;
block *rightblock = deque->rightblock;
Py_ssize_t leftindex = deque->leftindex;
Py_ssize_t rightindex = deque->rightindex;
Py_ssize_t len=Py_SIZE(deque), halflen=len>>1;
int rv = -1;
if (len <= 1)
return 0;
if (n > halflen || n < -halflen) {
n %= len;
if (n > halflen)
n -= len;
else if (n < -halflen)
n += len;
}
assert(len > 1);
assert(-halflen <= n && n <= halflen);
deque->state++;
while (n > 0) {
if (leftindex == 0) {
if (b == NULL) {
b = newblock();
if (b == NULL)
goto done;
}
b->rightlink = leftblock;
CHECK_END(leftblock->leftlink);
leftblock->leftlink = b;
leftblock = b;
MARK_END(b->leftlink);
leftindex = BLOCKLEN;
b = NULL;
}
assert(leftindex > 0);
{
PyObject **src, **dest;
Py_ssize_t m = n;
if (m > rightindex + 1)
m = rightindex + 1;
if (m > leftindex)
m = leftindex;
assert (m > 0 && m <= len);
rightindex -= m;
leftindex -= m;
src = &rightblock->data[rightindex + 1];
dest = &leftblock->data[leftindex];
n -= m;
do {
*(dest++) = *(src++);
} while (--m);
}
if (rightindex < 0) {
assert(leftblock != rightblock);
assert(b == NULL);
b = rightblock;
CHECK_NOT_END(rightblock->leftlink);
rightblock = rightblock->leftlink;
MARK_END(rightblock->rightlink);
rightindex = BLOCKLEN - 1;
}
}
while (n < 0) {
if (rightindex == BLOCKLEN - 1) {
if (b == NULL) {
b = newblock();
if (b == NULL)
goto done;
}
b->leftlink = rightblock;
CHECK_END(rightblock->rightlink);
rightblock->rightlink = b;
rightblock = b;
MARK_END(b->rightlink);
rightindex = -1;
b = NULL;
}
assert (rightindex < BLOCKLEN - 1);
{
PyObject **src, **dest;
Py_ssize_t m = -n;
if (m > BLOCKLEN - leftindex)
m = BLOCKLEN - leftindex;
if (m > BLOCKLEN - 1 - rightindex)
m = BLOCKLEN - 1 - rightindex;
assert (m > 0 && m <= len);
src = &leftblock->data[leftindex];
dest = &rightblock->data[rightindex + 1];
leftindex += m;
rightindex += m;
n += m;
do {
*(dest++) = *(src++);
} while (--m);
}
if (leftindex == BLOCKLEN) {
assert(leftblock != rightblock);
assert(b == NULL);
b = leftblock;
CHECK_NOT_END(leftblock->rightlink);
leftblock = leftblock->rightlink;
MARK_END(leftblock->leftlink);
leftindex = 0;
}
}
rv = 0;
done:
if (b != NULL)
freeblock(b);
deque->leftblock = leftblock;
deque->rightblock = rightblock;
deque->leftindex = leftindex;
deque->rightindex = rightindex;
return rv;
}
static PyObject *
deque_rotate(dequeobject *deque, PyObject *const *args, Py_ssize_t nargs)
{
Py_ssize_t n=1;
if (!_PyArg_ParseStack(args, nargs, "|n:rotate", &n)) {
return NULL;
}
if (!_deque_rotate(deque, n))
Py_RETURN_NONE;
return NULL;
}
PyDoc_STRVAR(rotate_doc,
"Rotate the deque n steps to the right (default n=1). If n is negative, rotates left.");
static PyObject *
deque_reverse(dequeobject *deque, PyObject *unused)
{
block *leftblock = deque->leftblock;
block *rightblock = deque->rightblock;
Py_ssize_t leftindex = deque->leftindex;
Py_ssize_t rightindex = deque->rightindex;
Py_ssize_t n = Py_SIZE(deque) >> 1;
PyObject *tmp;
while (--n >= 0) {
/* Validate that pointers haven't met in the middle */
assert(leftblock != rightblock || leftindex < rightindex);
CHECK_NOT_END(leftblock);
CHECK_NOT_END(rightblock);
/* Swap */
tmp = leftblock->data[leftindex];
leftblock->data[leftindex] = rightblock->data[rightindex];
rightblock->data[rightindex] = tmp;
/* Advance left block/index pair */
leftindex++;
if (leftindex == BLOCKLEN) {
leftblock = leftblock->rightlink;
leftindex = 0;
}
/* Step backwards with the right block/index pair */
rightindex--;
if (rightindex < 0) {
rightblock = rightblock->leftlink;
rightindex = BLOCKLEN - 1;
}
}
Py_RETURN_NONE;
}
PyDoc_STRVAR(reverse_doc,
"D.reverse() -- reverse *IN PLACE*");
static PyObject *
deque_count(dequeobject *deque, PyObject *v)
{
block *b = deque->leftblock;
Py_ssize_t index = deque->leftindex;
Py_ssize_t n = Py_SIZE(deque);
Py_ssize_t count = 0;
size_t start_state = deque->state;
PyObject *item;
int cmp;
while (--n >= 0) {
CHECK_NOT_END(b);
item = b->data[index];
Py_INCREF(item);
cmp = PyObject_RichCompareBool(item, v, Py_EQ);
Py_DECREF(item);
if (cmp < 0)
return NULL;
count += cmp;
if (start_state != deque->state) {
PyErr_SetString(PyExc_RuntimeError,
"deque mutated during iteration");
return NULL;
}
/* Advance left block/index pair */
index++;
if (index == BLOCKLEN) {
b = b->rightlink;
index = 0;
}
}
return PyLong_FromSsize_t(count);
}
PyDoc_STRVAR(count_doc,
"D.count(value) -> integer -- return number of occurrences of value");
static int
deque_contains(dequeobject *deque, PyObject *v)
{
block *b = deque->leftblock;
Py_ssize_t index = deque->leftindex;
Py_ssize_t n = Py_SIZE(deque);
size_t start_state = deque->state;