-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathlazysorted.c
1615 lines (1405 loc) · 46.4 KB
/
lazysorted.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
/* LazySorted objects */
#include <Python.h>
#include <time.h>
/* Parameters for the sorting function */
/* SORT_THRESH: Sort if the sublist has SORT_THRESH or fewer elements */
#define SORT_THRESH 16 /* Should be at least three because of prefetch */
/* CONTIG_THRESH: When computing slices with integer step sizes, sort all data
* between start and stop and then populate the list with it if
* |step| <= CONTIG_THRESH, otherwise select each element individually.
* CONTIG_THRESH should always be bigger than SORT_THRESH */
#define CONTIG_THRESH 32
/* Macro definitions to deal different python versions */
#if PY_MAJOR_VERSION >= 3
#define PyString_FromString PyUnicode_FromString
#define PyString_Format PyUnicode_Format
#define PyInt_FromSsize_t PyLong_FromSsize_t
#endif
#if PY_VERSION_HEX < 0x03020000
#define PySlice_GetIndicesEx(item, \
length, start, stop, step, slicelength) \
PySlice_GetIndicesEx((PySliceObject*)item, \
length, start, stop, step, slicelength)
#endif
/* Macros for python2.5 */
#ifndef PyVarObject_HEAD_INIT
#define PyVarObject_HEAD_INIT(type, size) \
PyObject_HEAD_INIT(type) size,
#endif
#ifndef Py_SIZE
#define Py_SIZE(ob) (((PyVarObject*)(ob))->ob_size)
#endif
#ifndef Py_Type
#define Py_TYPE(ob) (((PyObject*)(ob))->ob_type)
#endif
/* Macros to support different compilers */
#if !(defined(__GNUC__) || defined(__clang__))
#define __builtin_prefetch(x)
#endif
/* Definitions and functions for the binary search tree of pivot points.
* The BST implementation is a Treap, selected because of its general speed,
* especially when inserting and removing elements, which happens a lot in this
* application. */
typedef struct PivotNode {
Py_ssize_t idx; /* The index it represents */
int flags; /* Descriptors of the data between pivots */
int priority; /* Priority in the Treap */
struct PivotNode *left;
struct PivotNode *right;
struct PivotNode *parent;
} PivotNode;
/* SORTED_RIGHT means the pivot is to the right of a sorted region.
* SORTED_LEFT means the pivot is the left of a sorted region */
#define SORTED_RIGHT 1
#define SORTED_LEFT 2
#define UNSORTED 0
#define SORTED_BOTH 3
/* The LazySorted object */
typedef struct {
PyObject_HEAD
PyListObject *xs; /* Partially sorted list */
PivotNode *root; /* Root of the pivot BST */
PyObject *keyfunc; /* The key function */
int reverse; /* 1 for reverse order */
} LSObject;
static PyTypeObject LS_Type;
#define LSObject_Check(v) (Py_TYPE(v) == &LS_Type)
/* Returns the next (bigger) pivot, or NULL if it's the last pivot */
PivotNode *
next_pivot(PivotNode *current)
{
PivotNode *curr = current;
if (curr->right != NULL) {
curr = curr->right;
while (curr->left != NULL) {
curr = curr->left;
}
}
else {
while (curr->parent != NULL && curr->parent->idx < curr->idx) {
curr = curr->parent;
}
if (curr->parent == NULL) {
return NULL;
}
else {
curr = curr->parent;
}
}
assert(curr->idx > current->idx);
return curr;
}
/* A recursive function getting the consistency of a node.
* Does not assume that the node is the root of the tree, and does NOT examine
* the parentage of node. This is important, because it is often called on
* nodes whose future parents don't know them yet, like in merge_trees(.) */
#ifndef NDEBUG
static void
assert_node(PivotNode *node)
{
if (node->left != NULL) {
assert(node->left->idx < node->idx);
assert(node->left->priority <= node->priority);
assert(node->left->parent == node);
assert_node(node->left);
}
if (node->right != NULL) {
assert(node->right->idx > node->idx);
assert(node->right->priority <= node->priority);
assert(node->right->parent == node);
assert_node(node->right);
}
}
/* A series of assert statements that the tree structure is consistent */
static void
assert_tree(PivotNode *root)
{
assert(root != NULL);
assert(root->parent == NULL);
assert_node(root);
}
/* A series of assert statements that the tree's flags are consistent */
static void
assert_tree_flags(PivotNode *root)
{
PivotNode *prev = NULL;
PivotNode *curr = root;
while (curr->left != NULL)
curr = curr->left;
while (curr != NULL) {
if (curr->flags & SORTED_LEFT)
assert(next_pivot(curr)->flags & SORTED_RIGHT);
if (curr->flags & SORTED_RIGHT)
assert(prev->flags & SORTED_LEFT);
prev = curr;
curr = next_pivot(curr);
}
}
#else
/* Silences -Wunused-parameter */
#define assert_node(x)
#define assert_tree(x)
#define assert_tree_flags(x)
#endif
/* Inserts an index, returning a pointer to the node, or NULL on error.
* *root is the root of the tree, while start is the node to insert from.
*/
static PivotNode *insert_pivot(Py_ssize_t, int, PivotNode **, PivotNode *)
Py_GCC_ATTRIBUTE((warn_unused_result));
static PivotNode *
insert_pivot(Py_ssize_t k, int flags, PivotNode **root, PivotNode *start)
{
/* Build the node */
PivotNode *node = (PivotNode *)PyMem_Malloc(sizeof(PivotNode));
if (node == NULL)
return (PivotNode *)PyErr_NoMemory();
node->idx = k;
node->flags = flags;
node->priority = rand();
node->left = NULL;
node->right = NULL;
/* Special case the empty tree */
if (*root == NULL) {
node->parent = NULL;
*root = node;
return node;
}
/* Put the node in its sorted order */
PivotNode *current = start;
while (1) {
if (current->idx < k) {
if (current->right == NULL) {
current->right = node;
node->parent = current;
break;
}
current = current->right;
}
else if (current->idx > k) {
if (current->left == NULL) {
current->left = node;
node->parent = current;
break;
}
current = current->left;
}
else {
/* The pivot BST should always have unique pivots */
PyErr_SetString(PyExc_SystemError, "All pivots must be unique");
return NULL;
}
}
/* Reestablish the treap invariant if necessary by tree rotations */
PivotNode *child, *parent, *grandparent;
while (node->priority > node->parent->priority) {
/* (parent) (node)
* / \
* / \
* / \
* (node) -> (parent)
* \ /
* \ /
* (child) (child)
*/
if (node->idx < node->parent->idx) {
child = node->right;
parent = node->parent;
grandparent = parent->parent;
node->parent = grandparent;
node->right = parent;
parent->parent = node;
parent->left = child;
if (child != NULL)
child->parent = parent;
}
/* (parent) (node)
* \ /
* \ /
* \ /
* (node) -> (parent)
* / \
* / \
* (child) (child)
*/
else {
child = node->left;
parent = node->parent;
grandparent = parent->parent;
node->parent = grandparent;
node->left = parent;
parent->parent = node;
parent->right = child;
if (child != NULL)
child->parent = parent;
}
/* Adjust node->parent's child pointer to point to node */
if (node->parent != NULL) {
if (k < node->parent->idx) {
node->parent->left = node;
}
else {
node->parent->right = node;
}
}
else { /* The node has propogated up to the root */
*root = node;
break;
}
}
assert_tree(*root);
assert_tree_flags(*root);
return node;
}
/* Takes two trees and merges them into one while preserving the treap
* invariant. left must have a smaller index than right. */
static PivotNode *
merge_trees(PivotNode *left, PivotNode *right)
{
assert(left != NULL || right != NULL);
if (left == NULL)
return right;
if (right == NULL)
return left;
assert(left->parent == right->parent);
assert(left->idx < right->idx);
assert_node(left);
assert_node(right);
if (left->priority > right->priority) {
right->parent = left;
left->right = merge_trees(left->right, right);
assert_node(left);
return left;
}
else {
left->parent = right;
right->left = merge_trees(left, right->left);
assert_node(right);
return right;
}
}
static void
delete_node(PivotNode *node, PivotNode **root)
{
assert_tree(*root);
if (node->left == NULL) {
/* node has at most one child in node->right, so we just have the
* grandparent adopt it, if node is not the root. If node is the root,
* we promote the child to root. */
if (node->parent != NULL) {
if (node->parent->left == node) {
node->parent->left = node->right;
}
else {
node->parent->right = node->right;
}
}
else { /* Node is the root */
*root = node->right;
}
if (node->right != NULL) {
node->right->parent = node->parent;
}
PyMem_Free(node);
}
else {
if (node->right == NULL) {
/* node has a single child in node->left, so have grandparent
* adopt it as above */
if (node->parent != NULL) {
if (node->parent->left == node) {
node->parent->left = node->left;
}
else {
node->parent->right = node->left;
}
}
else { /* Node is the root */
*root = node->left;
}
/* node->left is not NULL because of the outer if-else statement */
node->left->parent = node->parent;
PyMem_Free(node);
}
else {
/* The hard case: node has two children. We merge the two children
* into one treap, and then replace node by this treap */
PivotNode *children = merge_trees(node->left, node->right);
if (node->parent != NULL) {
if (node->parent->left == node) {
node->parent->left = children;
}
else {
node->parent->right = children;
}
}
else { /* Node is the root */
*root = children;
}
/* children is not NULL since node has two children */
children->parent = node->parent;
PyMem_Free(node);
}
}
assert_tree(*root);
}
/* If a sorted pivot is between two sorted section, removes the sorted pivot */
static void
depivot(PivotNode *left, PivotNode *right, PivotNode **root)
{
assert_tree(*root);
assert_tree_flags(*root);
assert(left->flags & SORTED_LEFT);
assert(right->flags & SORTED_RIGHT);
if (left->flags & SORTED_RIGHT) {
delete_node(left, root);
}
if (right->flags & SORTED_LEFT) {
delete_node(right, root);
}
assert_tree(*root);
assert_tree_flags(*root);
}
/* If the value at middle is equal to the value at left, left is removed.
* If the value at middle is equal to the value at right, right is removed.
* Returns 0 on success, or -1 on failure */
static int uniq_pivots(PivotNode *, PivotNode *, PivotNode *, LSObject *)
Py_GCC_ATTRIBUTE((warn_unused_result));
static int
uniq_pivots(PivotNode *left, PivotNode *middle, PivotNode *right, LSObject *ls)
{
assert_tree(ls->root);
assert_tree_flags(ls->root);
assert(left->idx < middle->idx && middle->idx < right->idx);
int cmp;
if (left->idx >= 0) {
if ((cmp = PyObject_RichCompareBool(ls->xs->ob_item[left->idx],
ls->xs->ob_item[middle->idx],
Py_EQ)) < 0) {
return -1;
}
else if (cmp) {
middle->flags = left->flags;
delete_node(left, &ls->root);
}
}
if (right->idx < Py_SIZE(ls->xs)) {
if ((cmp = PyObject_RichCompareBool(ls->xs->ob_item[middle->idx],
ls->xs->ob_item[right->idx],
Py_EQ)) < 0) {
return -1;
}
else if (cmp) {
middle->flags = right->flags;
delete_node(right, &ls->root);
}
}
assert_tree(ls->root);
assert_tree_flags(ls->root);
return 0;
}
/* Finds PivotNodes left and right that bound the index */
/* Never returns k in right_node, only the left, if applicable */
static void
bound_idx(Py_ssize_t k, PivotNode *root, PivotNode **left, PivotNode **right)
{
assert_tree(root);
assert_tree_flags(root);
*left = NULL;
*right = NULL;
PivotNode *current = root;
while (current != NULL) {
if (current->idx < k) {
*left = current;
current = current->right;
}
else if (current->idx > k) {
*right = current;
current = current->left;
}
else {
*left = current;
break;
}
}
assert(*left != NULL && ((*left)->idx == k || *right != NULL));
assert((*left)->idx == k || *right == next_pivot(*left));
}
static void
free_tree(PivotNode *root)
{
assert_node(root); /* might not be the actual root because of recursion */
if (root->left != NULL)
free_tree(root->left);
if (root->right != NULL)
free_tree(root->right);
PyMem_Free(root);
}
static void
LS_dealloc(LSObject *self)
{
Py_DECREF(self->xs);
Py_XDECREF(self->keyfunc);
if (self->root != NULL) {
free_tree(self->root);
}
Py_TYPE(self)->tp_free((PyObject*)self);
}
static PyObject *
newLSObject(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
LSObject *self;
PyListObject *xs;
PyObject *sequence = NULL;
PyObject *keyfunc = NULL;
int reverse = 0;
static char *kwdlist[] = {"sequence", "key", "reverse", 0};
if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|Oi:LazySorted",
kwdlist, &sequence, &keyfunc, &reverse))
return NULL;
PyObject *list_args = Py_BuildValue("(O)", sequence);
if (list_args == NULL)
return NULL;
xs = (PyListObject *)PyList_Type.tp_new(&PyList_Type, list_args, NULL);
if (xs == NULL) {
Py_DECREF(list_args);
return NULL;
}
if (PyList_Type.tp_init((PyObject *)xs, list_args, NULL)) {
Py_DECREF(list_args);
Py_DECREF(xs);
return NULL;
}
Py_DECREF(list_args);
self = (LSObject *)type->tp_alloc(type, 0);
if (self == NULL) {
Py_DECREF(xs);
return NULL;
}
self->root = NULL;
self->keyfunc = NULL;
self->reverse = 0;
self->xs = xs;
if (insert_pivot(-1, UNSORTED, &self->root, self->root) == NULL) {
Py_DECREF(self);
return NULL;
}
if (insert_pivot(Py_SIZE(xs), UNSORTED, &self->root, self->root) == NULL) {
Py_DECREF(self);
return NULL;
}
if (reverse)
self->reverse = 1;
if (keyfunc == Py_None)
keyfunc = NULL;
if (keyfunc != NULL) {
/* Since we sort lazily, we wouldn't discover that the key isn't
* callable until we actually attempted sorting. So let's try to help
* the user by failing fast if this is the case. */
if (!PyCallable_Check(keyfunc)) {
PyErr_SetString(PyExc_TypeError, "key must be callable");
Py_DECREF(self);
return NULL;
}
self->keyfunc = keyfunc;
Py_INCREF(self->keyfunc);
}
return (PyObject *)self;
}
/* Private helper functions for partial sorting */
/* These macros are basically taken from list.c
* Returns 1 if x < y, 0 if x >= y, and -1 on error */
/* #define ISLT(X, Y) PyObject_RichCompareBool(X, Y, Py_LT) */
static inline int islt(PyObject *, PyObject *, LSObject *)
Py_GCC_ATTRIBUTE((warn_unused_result));
static inline int
islt(PyObject *x, PyObject *y, LSObject *ls)
{
if (ls->keyfunc != NULL) {
PyObject *x_cmp, *y_cmp;
PyObject *x_arg = Py_BuildValue("(O)", x);
x_cmp = PyObject_CallObject(ls->keyfunc, x_arg);
Py_DECREF(x_arg);
if (x_cmp == NULL) {
return -1;
}
PyObject *y_arg = Py_BuildValue("(O)", y);
y_cmp = PyObject_CallObject(ls->keyfunc, y_arg);
Py_DECREF(y_arg);
if (y_cmp == NULL) {
Py_DECREF(x_cmp);
return -1;
}
int res = ls->reverse ? PyObject_RichCompareBool(x_cmp, y_cmp, Py_GT)
: PyObject_RichCompareBool(x_cmp, y_cmp, Py_LT);
Py_DECREF(x_cmp);
Py_DECREF(y_cmp);
return res;
} else {
return ls->reverse ? PyObject_RichCompareBool(x, y, Py_GT)
: PyObject_RichCompareBool(x, y, Py_LT);
}
}
#define IFLT(X, Y) if ((ltflag = islt(X, Y, ls)) < 0) goto fail; \
if(ltflag)
/* N.B: No semicolon at the end, so that you can include one yourself */
#define SWAP(i, j) tmp = ob_item[i]; \
ob_item[i] = ob_item[j]; \
ob_item[j] = tmp
/* Picks a pivot point among the indices left <= i < right. Returns -1 on
* error */
static Py_ssize_t pick_pivot(LSObject *, Py_ssize_t, Py_ssize_t)
Py_GCC_ATTRIBUTE((warn_unused_result));
static Py_ssize_t
pick_pivot(LSObject *ls, Py_ssize_t left, Py_ssize_t right)
{
PyObject **ob_item = ls->xs->ob_item;
/* Use median of three trick */
Py_ssize_t idx1 = left + rand() % (right - left);
Py_ssize_t idx2 = left + rand() % (right - left);
Py_ssize_t idx3 = left + rand() % (right - left);
int ltflag;
IFLT(ob_item[idx1], ob_item[idx3]) {
IFLT(ob_item[idx1], ob_item[idx2]) {
/* 1 2 3 vs. 1 3 2 */
IFLT(ob_item[idx2], ob_item[idx3]) {
return idx2;
}
else {
return idx3;
}
}
else {
/* 2 1 3 */
return idx1;
}
}
else {
IFLT(ob_item[idx3], ob_item[idx2]) {
/* 3 1 2 vs 3 2 1 */
IFLT(ob_item[idx1], ob_item[idx2]) {
return idx1;
}
else {
return idx2;
}
}
else {
/* 2 3 1 */
return idx3;
}
}
fail:
return -1;
}
/* Partitions the data between left and right into
* [less than region | greater or equal to region]
* and returns the pivot index, or -1 on error */
static Py_ssize_t partition(LSObject *, Py_ssize_t, Py_ssize_t)
Py_GCC_ATTRIBUTE((warn_unused_result));
static Py_ssize_t
partition(LSObject *ls, Py_ssize_t left, Py_ssize_t right)
{
PyObject **ob_item = ls->xs->ob_item;
PyObject *tmp; /* Used by SWAP macro */
PyObject *pivot;
int ltflag;
Py_ssize_t piv_idx = pick_pivot(ls, left, right);
if (piv_idx < 0) {
return -1;
}
pivot = ob_item[piv_idx];
SWAP(left, piv_idx);
Py_ssize_t last_less = left;
/* Invariant: last_less and everything to its left is less than
* pivot or the pivot itself */
Py_ssize_t i;
for (i = left + 1; i < right - 3; i++) {
/*
This single line boosts performance by a factor of around 2 on GCC.
The optimal lookahead distance i+3 was chosen by experimentation.
See http://www.naftaliharris.com/blog/2x-speedup-with-one-line-of-code/
*/
__builtin_prefetch(ob_item[i+3]);
IFLT(ob_item[i], pivot) {
last_less++;
SWAP(i, last_less);
}
}
assert(right - left >= 3); /* partition isn't called on small lists */
for (i = right - 3; i < right; i++) {
IFLT(ob_item[i], pivot) {
last_less++;
SWAP(i, last_less);
}
}
SWAP(left, last_less);
return last_less;
fail: /* From IFLT macro */
return -1;
}
/* Runs insertion sort on the items left <= i < right */
static int insertion_sort(LSObject *, Py_ssize_t, Py_ssize_t)
Py_GCC_ATTRIBUTE((warn_unused_result));
static int
insertion_sort(LSObject *ls, Py_ssize_t left, Py_ssize_t right)
{
PyObject **ob_item = ls->xs->ob_item;
PyObject *tmp;
Py_ssize_t i, j;
for (i = left; i < right; i++) {
tmp = ob_item[i];
int ltflag = 0;
for (j = i; j > 0 && (ltflag = islt(tmp, ob_item[j - 1], ls)) > 0; j--)
ob_item[j] = ob_item[j - 1];
ob_item[j] = tmp;
if (ltflag < 0) {
return -1;
}
}
return 0;
}
/* Runs quicksort on the items left <= i < right, returning 0 on success
* or -1 on error. Does not affect stored pivots at all. */
static int quick_sort(LSObject *, Py_ssize_t, Py_ssize_t)
Py_GCC_ATTRIBUTE((warn_unused_result));
static int
quick_sort(LSObject *ls, Py_ssize_t left, Py_ssize_t right)
{
if (right - left <= SORT_THRESH) {
return insertion_sort(ls, left, right);
}
Py_ssize_t piv_idx = partition(ls, left, right);
if (piv_idx < 0)
return -1;
if (quick_sort(ls, left, piv_idx) < 0)
return -1;
if (quick_sort(ls, piv_idx + 1, right) < 0)
return -1;
return 0;
}
/* Sorts the list ls sufficiently such that ls->xs->ob_item[k] is actually the
* kth value in sorted order. Returns 0 on success and -1 on error. */
static int sort_point(LSObject *, Py_ssize_t)
Py_GCC_ATTRIBUTE((warn_unused_result));
static int
sort_point(LSObject *ls, Py_ssize_t k)
{
/* Find the best possible bounds */
PivotNode *left, *right, *middle;
bound_idx(k, ls->root, &left, &right);
/* bound_idx never returns k in right, but right might be NULL if
* left->idx == k, so check left->idx first. */
if (left->idx == k || right->flags & SORTED_RIGHT) {
return 0;
}
/* Run quickselect */
Py_ssize_t piv_idx;
while (left->idx + 1 + SORT_THRESH <= right->idx) {
piv_idx = partition(ls, left->idx + 1, right->idx);
if (piv_idx < 0) {
return -1;
}
if (piv_idx < k) {
if (left->right == NULL) {
middle = insert_pivot(piv_idx, UNSORTED, &ls->root, left);
}
else {
middle = insert_pivot(piv_idx, UNSORTED, &ls->root, right);
}
if (middle == NULL)
return -1;
if (uniq_pivots(left, middle, right, ls) < 0) return -1;
left = middle;
}
else if (piv_idx > k) {
if (left->right == NULL) {
middle = insert_pivot(piv_idx, UNSORTED, &ls->root, left);
}
else {
middle = insert_pivot(piv_idx, UNSORTED, &ls->root, right);
}
if (middle == NULL)
return -1;
if (uniq_pivots(left, middle, right, ls) < 0) return -1;
right = middle;
}
else {
if (left->right == NULL) {
middle = insert_pivot(piv_idx, UNSORTED, &ls->root, left);
}
else {
middle = insert_pivot(piv_idx, UNSORTED, &ls->root, right);
}
if (middle == NULL)
return -1;
if (uniq_pivots(left, middle, right, ls) < 0) return -1;
return 0;
}
}
if (insertion_sort(ls, left->idx + 1, right->idx) < 0) {
return -1;
}
left->flags |= SORTED_LEFT;
right->flags |= SORTED_RIGHT;
depivot(left, right, &ls->root);
return 0;
}
/* Sorts the list ls sufficiently such that everything between indices start
* and stop is in sorted order. Returns 0 on success and -1 on error. */
static int sort_range(LSObject *, Py_ssize_t, Py_ssize_t)
Py_GCC_ATTRIBUTE((warn_unused_result));
static int
sort_range(LSObject *ls, Py_ssize_t start, Py_ssize_t stop)
{
/* The xs list is always partially sorted, with pivots partioning up the
* space, like in this picture:
*
* | ~~~~~ | ~~~ | ~~~~~ | ~~ | ~~~~~~~ |
*
* '|' indicates a pivot and '~~' indicates unsorted data.
*
* So we iterate through the regions bounding our data, and sort them.
*/
assert(0 <= start && start < stop && stop <= Py_SIZE(ls->xs));
if (sort_point(ls, start) < 0)
return -1;
if (sort_point(ls, stop) < 0)
return -1;
PivotNode *current, *next;
bound_idx(start, ls->root, ¤t, &next);
if (current->idx == start)
next = next_pivot(current);
while (current->idx < stop) {
if (current->flags & SORTED_LEFT) {
assert(next->flags & SORTED_RIGHT);
}
else {
/* Since we are sorting the entire region, we don't need to keep
* track of pivots, and so we can use vanilla quicksort */
if (quick_sort(ls, current->idx + 1, next->idx) < 0) {
return -1;
}
current->flags |= SORTED_LEFT;
next->flags |= SORTED_RIGHT;
}
if (current->flags & SORTED_RIGHT) {
delete_node(current, &ls->root);
}
current = next;
next = next_pivot(current);
}
assert(current->flags & SORTED_RIGHT);
if (current->flags & SORTED_LEFT) {
delete_node(current, &ls->root);
}
return 0;
}
/* Returns the first index of item in the list, or -2 on error, or -1 if item
* is not present. Places item in that first idx, but makes no guarantees
* any duplicate versions of item will immediately follow. Eg, it's possible
* calling find_item on some list with item = 1 will result in the following
* list:
* [0, 0, 0, 1, 2, 2, 1, 2, 1, 1, 2]
*/
static Py_ssize_t find_item(LSObject *, PyObject *)
Py_GCC_ATTRIBUTE((warn_unused_result));
static Py_ssize_t
find_item(LSObject *ls, PyObject *item)
{
PivotNode *left = NULL;
PivotNode *right = NULL;
PivotNode *middle;
PivotNode *current = ls->root;
int ltflag;
Py_ssize_t xs_len = Py_SIZE(ls->xs);
Py_ssize_t left_idx, right_idx;
while (current != NULL) {
if (current->idx == -1) {
left = current;
current = current->right;
}
else if (current->idx == xs_len) {
right = current;
current = current->left;
}
else {
IFLT(ls->xs->ob_item[current->idx], item) {
left = current;
current = current->right;
}
else {
right = current;
current = current->left;
}
}
}
if (left->flags & SORTED_LEFT) {
assert(right->flags & SORTED_RIGHT);
left_idx = left->idx + 1;
right_idx = right->idx == xs_len ? xs_len : right->idx + 1;
}
else {
Py_ssize_t piv_idx;
while (left->idx + 1 + SORT_THRESH <= right->idx) {
if ((piv_idx = partition(ls, left->idx + 1, right->idx)) < 0) {
return -2;
}
IFLT(ls->xs->ob_item[piv_idx], item) {
if (left->right == NULL) {
middle = insert_pivot(piv_idx, UNSORTED, &ls->root, left);
}
else {
middle = insert_pivot(piv_idx, UNSORTED, &ls->root, right);
}
if (middle == NULL)
return -2;
if (uniq_pivots(left, middle, right, ls) < 0) return -1;
left = middle;
}
else {
if (left->right == NULL) {
middle = insert_pivot(piv_idx, UNSORTED, &ls->root, left);
}
else {