-
Notifications
You must be signed in to change notification settings - Fork 39
/
ttree.d
1356 lines (1249 loc) · 33.5 KB
/
ttree.d
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
/**
* T-Tree.
* Copyright: © 2015 Economic Modeling Specialists, Intl.
* Authors: Brian Schott
* License: $(LINK2 http://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
*/
module containers.ttree;
private import containers.internal.node : shouldAddGCRange;
private import containers.internal.mixins : AllocatorState;
private import std.experimental.allocator.mallocator : Mallocator;
/**
* Implements a binary search tree with multiple items per tree node.
*
* T-tree Nodes are (by default) sized to fit within a 64-byte
* cache line. The number of items stored per node can be read from the
* `nodeCapacity` enum. Each node has 0, 1, or 2 children. Each node has between
* 1 and `nodeCapacity` items, or it has `nodeCapacity` items and 0 or
* more children.
*
* Inserting or removing items while iterating a range returned from `opSlice`,
* `upperBound`, `equalRange`, or other similar functions will result in
* unpredicable and likely invalid iteration orders.
*
* Params:
* T = the element type
* Allocator = the allocator to use. Defaults to `Mallocator`.
* allowDuplicates = if true, duplicate values will be allowed in the tree
* less = the comparitor function to use
* supportGC = true if the container should support holding references to
* GC-allocated memory.
* cacheLineSize = Nodes will be sized to fit within this number of bytes.
* See_also: $(LINK http://en.wikipedia.org/wiki/T-tree)
*/
struct TTree(T, Allocator = Mallocator, bool allowDuplicates = false,
alias less = "a < b", bool supportGC = shouldAddGCRange!T, size_t cacheLineSize = 64)
{
/**
* T-Trees are not copyable due to the way they manage memory and interact
* with allocators.
*/
this(this) @disable;
static if (stateSize!Allocator != 0)
{
/// No default construction if an allocator must be provided.
this() @disable;
/**
* Use `allocator` to allocate and free nodes in the tree.
*/
this(Allocator allocator)
in
{
assert(allocator !is null, "Allocator must not be null");
}
do
{
this.allocator = allocator;
}
private alias AllocatorType = Allocator;
}
else
private alias AllocatorType = void*;
~this() @trusted
{
scope(failure) assert(false, "TTree destructor threw an exception");
clear();
}
/**
* Removes all elements from the tree.
*/
void clear()
{
_length = 0;
if (root is null)
return;
static if (stateSize!Allocator > 0)
deallocateNode(root, allocator);
else
deallocateNode(root, null);
}
debug(EMSI_CONTAINERS) invariant()
{
assert (root is null || _length != 0, "Empty tree with non-null root");
}
/**
* $(B tree ~= item) operator overload.
*/
void opOpAssign(string op)(T value) if (op == "~")
{
insert(value);
}
/**
* Inserts the given value(s) into the tree.
*
* This is not a stable insert. You will get strange results if you insert
* into a tree while iterating over it.
*
* Params:
* value = the value to insert
* overwrite = if `true` the given `value` will replace the first item
* in the tree that is equivalent (That is greater-than and less-than
* are both false) to `value`. This is useful in cases where opCmp
* and opEquals for `T` type have different meanings. For example,
* if the element type is a circle that has a position and a color,
* the circle could implement `opCmp` to sort by color, and calling
* `insert` with `overwrite` set to `true` would allow you to update
* the position of the circle with a certain color in the tree.
* Returns: the number of values added.
*/
size_t insert(T value, bool overwrite = false) @safe
{
if (root is null)
{
static if (stateSize!Allocator > 0)
root = allocateNode(cast(Value) value, null, allocator);
else
root = allocateNode(cast(Value) value, null, null);
++_length;
return true;
}
static if (stateSize!Allocator > 0)
immutable bool r = root.insert(cast(Value) value, root, allocator, overwrite);
else
immutable bool r = root.insert(cast(Value) value, root, null, overwrite);
if (r)
++_length;
return r ? 1 : 0;
}
/// ditto
size_t insert(R)(R r, bool overwrite = false) if (isInputRange!R && is(ElementType!R == T))
{
size_t retVal;
while (!r.empty)
{
retVal += insert(r.front(), overwrite);
r.popFront();
}
return retVal;
}
/// ditto
size_t insert(T[] values, bool overwrite = false)
{
size_t retVal;
foreach (ref v; values)
retVal += insert(v, overwrite);
return retVal;
}
/// ditto
alias insertAnywhere = insert;
/// ditto
alias put = insert;
/**
* Removes a single value from the tree, or does nothing.
*
* If `allowDuplicates` is true only a single element that is equivalent to
* the given `value` will be removed. Which of these elements is removed is
* not defined.
*
* Params:
* value = a value equal to the one to be removed
* cleanup = a function that should be run on the removed item
* Retuns: true if any value was removed
*/
bool remove(T value, void delegate(T) cleanup = null)
{
static if (stateSize!Allocator > 0)
immutable bool removed = root !is null && root.remove(cast(Value) value, root, allocator, cleanup);
else
immutable bool removed = root !is null && root.remove(cast(Value) value, root, null, cleanup);
if (removed)
{
--_length;
if (_length == 0)
{
static if (stateSize!Allocator > 0)
deallocateNode(root, allocator);
else
deallocateNode(root, null);
}
}
return removed;
}
/**
* Returns: true if the tree _conains the given value
*/
bool contains(T value) const @nogc @safe
{
return root !is null && root.contains(value);
}
/**
* Returns: the number of elements in the tree.
*/
size_t length() const pure nothrow @nogc @safe @property
{
return _length;
}
/**
* Returns: true if the tree is empty.
*/
bool empty() const pure nothrow @nogc @safe @property
{
return _length == 0;
}
/**
* Returns: a range over the tree. Do not insert into the tree while
* iterating because you may iterate over the same value multiple times
* or skip some values entirely.
*/
auto opSlice(this This)() inout @trusted @nogc
{
return Range!(This)(cast(const(Node)*) root, RangeType.all, T.init);
}
/**
* Returns: a range of elements which are less than value.
*/
auto lowerBound(this This)(inout T value) inout @trusted
{
return Range!(This)(cast(const(Node)*) root, RangeType.lower, value);
}
/**
* Returns: a range of elements which are equivalent (though not necessarily
* equal) to value.
*/
auto equalRange(this This)(inout T value) inout @trusted
{
return Range!(This)(cast(const(Node)*) root, RangeType.equal, value);
}
/**
* Returns: a range of elements which are greater than value.
*/
auto upperBound(this This)(inout T value) inout @trusted
{
return Range!(This)(cast(const(Node)*) root, RangeType.upper, value);
}
/**
* Returns: the first element in the tree.
*/
auto front(this This)() inout pure @trusted @property
{
import std.exception : enforce;
alias CET = ContainerElementType!(This, T);
enforce(!empty(), "Attepted to get the front of an empty tree.");
Node* current = cast(Node*) root;
while (current.left !is null)
current = current.left;
return cast(CET) current.values[0];
}
/**
* Returns: the last element in the tree.
*/
auto back(this This)() inout pure @trusted @property
{
import std.exception : enforce;
alias CET = ContainerElementType!(This, T);
enforce(!empty(), "Attepted to get the back of an empty tree.");
Node* current = cast(Node*) root;
while (current.right !is null)
current = current.right;
return cast(CET) current.values[current.nextAvailableIndex - 1];
}
/**
* Tree range
*/
static struct Range(ThisT)
{
@disable this();
/**
* Standard range operations
*/
ET front() const @property @nogc
{
return cast(typeof(return)) current.values[index];
}
/// ditto
bool empty() const pure nothrow @nogc @safe @property
{
return current is null;
}
/// ditto
void popFront()
{
_popFront();
if (current is null)
return;
with (RangeType) final switch (type)
{
case upper:
case all: break;
case equal:
if (_less(val, front()))
current = null;
break;
case lower:
if (!_less(front(), val))
current = null;
break;
}
}
package(containers):
// The TreeMap container needs to be able to modify part of the tree
// in-place. The reason that this works is that the value part of the
// key-value struct contained in a TTree used by a TreeMap is not used
// when comparing nodes. Normal users of the containers library cannot
// get a reference to the elements because modifying them will violate
// the ordering invariant of the tree.
T* _containersFront() const @property @nogc @trusted
{
return cast(T*) ¤t.values[index];
}
private:
alias ET = ContainerElementType!(ThisT, T);
void currentToLeftmost() @nogc
{
if (current is null)
return;
while (current.left !is null)
current = current.left;
}
void currentToLeastContaining(inout T val)
{
if (current is null)
return;
while (current !is null)
{
assert(current.registry != 0, "Empty node");
auto first = current.values[0];
auto last = current.values[current.nextAvailableIndex - 1];
immutable bool valLessFirst = _less(val, first);
immutable bool valLessLast = _less(val, last);
immutable bool firstLessVal = _less(first, val);
immutable bool lastLessVal = _less(last, val);
if (firstLessVal && valLessLast)
return;
else if (valLessFirst)
current = current.left;
else if (lastLessVal)
current = current.right;
else
{
static if (allowDuplicates)
{
if (!valLessFirst && !firstLessVal)
{
auto c = current;
current = current.left;
currentToLeastContaining(val);
if (current is null)
current = c;
return;
}
else
return;
}
else
return;
}
}
}
this(inout(Node)* n, RangeType type, inout T val) @nogc
{
current = n;
this.type = type;
this.val = val;
with (RangeType) final switch(type)
{
case all:
currentToLeftmost();
break;
case lower:
currentToLeftmost();
if (_less(val, front()))
current = null;
break;
case equal:
currentToLeastContaining(val);
while (current !is null && _less(front(), val))
_popFront();
if (current is null || _less(front(), val) || _less(val, front()))
current = null;
break;
case upper:
currentToLeastContaining(val);
while (current !is null && !_less(val, front()))
_popFront();
break;
}
}
void _popFront() @nogc
in
{
assert (!empty, "Calling .popFront with empty TTree");
}
do
{
index++;
if (index >= nodeCapacity || current.isFree(index))
{
index = 0;
if (current.right !is null)
{
current = current.right;
while (current.left !is null)
current = current.left;
}
else if (current.parent is null)
current = null;
else if (current.parent.left is current)
current = current.parent;
else
{
while (current.parent.right is current)
{
current = current.parent;
if (current.parent is null)
{
current = null;
return;
}
}
current = current.parent;
}
}
}
size_t index;
const(Node)* current;
const RangeType type;
const T val;
}
mixin AllocatorState!Allocator;
/// The number of values that can be stored in a single T-Tree node.
enum size_t nodeCapacity = N[0];
private:
import containers.internal.element_type : ContainerElementType;
import containers.internal.node : FatNodeInfo, fullBits, shouldAddGCRange, shouldNullSlot;
import containers.internal.storage_type : ContainerStorageType;
import std.algorithm : sort;
import std.functional: binaryFun;
import std.range : ElementType, isInputRange;
import std.traits: isPointer, PointerTarget;
import std.experimental.allocator.common : stateSize;
alias N = FatNodeInfo!(T.sizeof, 3, cacheLineSize, ulong.sizeof);
alias Value = ContainerStorageType!T;
alias BookkeepingType = N[1];
enum HEIGHT_BIT_OFFSET = 48UL;
enum fullBitPattern = fullBits!(ulong, nodeCapacity);
enum RangeType : ubyte { all, lower, equal, upper }
enum bool useGC = supportGC && shouldAddGCRange!T;
static assert (nodeCapacity <= HEIGHT_BIT_OFFSET, "cannot fit height info and registry in ulong");
static assert (nodeCapacity <= (typeof(Node.registry).sizeof * 8));
static assert (Node.sizeof <= cacheLineSize);
// If we're storing a struct that defines opCmp, don't compare pointers as
// that is almost certainly not what the user intended.
static if (is(typeof(less) == string ))
{
// Everything inside of this `static if` is dumb. `binaryFun` does not
// correctly infer nothrow and @nogc attributes, among other things, so
// we need to declare a function here that has its attributes properly
// inferred. It's not currently possible, however, to use this function
// with std.algorithm.sort because of symbol visibility issues. Because
// of this problem, keep a duplicate of the sorting predicate in string
// form in the `_lessStr` alias.
static if (less == "a < b" && isPointer!T
&& __traits(hasMember, PointerTarget!T, "opCmp"))
{
enum _lessStr = "a.opCmp(*b) < 0";
static bool _less(TT)(const TT a, const TT b)
{
return a.opCmp(*b) < 0;
}
}
else
{
enum _lessStr = less;
alias _less = binaryFun!less;
}
}
else
alias _less = binaryFun!less;
static Node* allocateNode(Value value, Node* parent, AllocatorType allocator) @trusted
out (result)
{
assert (result.left is null);
assert (result.right is null);
}
do
{
import core.memory : GC;
import std.experimental.allocator : make;
static if (stateSize!Allocator == 0)
Node* n = make!Node(Allocator.instance);
else
Node* n = make!Node(allocator);
n.parent = parent;
n.markUsed(0);
n.values[0] = cast(Value) value;
static if (useGC)
GC.addRange(n, Node.sizeof);
return n;
}
static void deallocateNode(ref Node* n, AllocatorType allocator)
in
{
assert (n !is null);
}
do
{
import std.experimental.allocator : dispose;
import core.memory : GC;
if (n.left !is null)
deallocateNode(n.left, allocator);
if (n.right !is null)
deallocateNode(n.right, allocator);
static if (useGC)
GC.removeRange(n);
static if (stateSize!Allocator == 0)
dispose(Allocator.instance, n);
else
dispose(allocator, n);
n = null;
}
static struct Node
{
private size_t nextAvailableIndex() const pure nothrow @nogc @safe
{
import containers.internal.backwards : bsf;
return bsf(~(registry & fullBitPattern));
}
private void markUsed(size_t index) pure nothrow @nogc @safe
{
registry |= (1UL << index);
}
private void markUnused(size_t index) pure nothrow @nogc @safe
{
registry &= ~(1UL << index);
static if (shouldNullSlot!T)
values[index] = null;
}
private bool isFree(size_t index) const pure nothrow @nogc @safe
{
return (registry & (1UL << index)) == 0;
}
private bool isFull() const pure nothrow @nogc @safe
{
return (registry & fullBitPattern) == fullBitPattern;
}
private bool isEmpty() const pure nothrow @nogc @safe
{
return (registry & fullBitPattern) == 0;
}
bool contains(Value value) const @trusted
{
import std.range : assumeSorted;
size_t i = nextAvailableIndex();
if (_less(value, cast(Value) values[0]))
return left !is null && left.contains(value);
if (_less(values[i - 1], value))
return right !is null && right.contains(value);
static if (is(typeof(_lessStr)))
return !assumeSorted!_lessStr(values[0 .. i]).equalRange(value).empty;
else
return !assumeSorted!_less(values[0 .. i]).equalRange(value).empty;
}
ulong calcHeight() pure nothrow @nogc @safe
{
immutable ulong l = left !is null ? left.height() : 0;
immutable ulong r = right !is null ? right.height() : 0;
immutable ulong h = 1 + (l > r ? l : r);
assert (h < ushort.max, "Height overflow");
registry &= fullBitPattern;
registry |= (h << HEIGHT_BIT_OFFSET);
return h;
}
ulong height() const pure nothrow @nogc @safe
{
return registry >>> HEIGHT_BIT_OFFSET;
}
int imbalanced() const pure nothrow @nogc @safe
{
if (right !is null
&& ((left is null && right.height() > 1)
|| (left !is null && right.height() > left.height() + 1)))
return 1;
if (left !is null
&& ((right is null && left.height() > 1)
|| (right !is null && left.height() > right.height() + 1)))
return -1;
return 0;
}
bool insert(T value, ref Node* root, AllocatorType allocator, bool overwrite) @trusted
in
{
static if (isPointer!T || is (T == class) || is (T == interface))
assert (value !is null, "Inserting null values is not allowed");
}
do
{
import std.algorithm : sort;
import std.range : assumeSorted;
if (!isFull())
{
immutable size_t index = nextAvailableIndex();
static if (!allowDuplicates)
{
static if (is(typeof(_lessStr)))
auto r = assumeSorted!_lessStr(values[0 .. index]).trisect(
cast(Value) value);
else
auto r = assumeSorted!_less(values[0 .. index]).trisect(
cast(Value) value);
if (!r[1].empty)
{
if (overwrite)
{
values[r[0].length] = cast(Value) value;
return true;
}
return false;
}
}
values[index] = cast(Value) value;
markUsed(index);
static if (is(typeof(_lessStr)))
sort!_lessStr(values[0 .. index + 1]);
else
sort!_less(values[0 .. index + 1]);
return true;
}
if (_less(value, values[0]))
{
if (left is null)
{
left = allocateNode(cast(Value) value, &this, allocator);
calcHeight();
return true;
}
immutable bool b = left.insert(value, root, allocator, overwrite);
if (imbalanced() == -1)
rotateRight(root, allocator);
calcHeight();
return b;
}
if (_less(values[$ - 1], cast(Value) value))
{
if (right is null)
{
right = allocateNode(value, &this, allocator);
calcHeight();
return true;
}
immutable bool b = right.insert(value, root, allocator, overwrite);
if (imbalanced() == 1)
rotateLeft(root, allocator);
calcHeight();
return b;
}
static if (!allowDuplicates)
{
static if (is(typeof(_lessStr)))
{
if (!assumeSorted!_lessStr(values[]).equalRange(cast(Value) value).empty)
return false;
}
else
{
if (!assumeSorted!_less(values[]).equalRange(cast(Value) value).empty)
return false;
}
}
Value[nodeCapacity + 1] temp = void;
temp[0 .. $ - 1] = values[];
temp[$ - 1] = cast(Value) value;
static if (is(typeof(_lessStr)))
sort!_lessStr(temp[]);
else
sort!_less(temp[]);
if (right is null)
{
values[] = temp[0 .. $ - 1];
right = allocateNode(temp[$ - 1], &this, allocator);
return true;
}
if (left is null)
{
values[] = temp[1 .. $];
left = allocateNode(temp[0], &this, allocator);
return true;
}
if (right.height < left.height)
{
values[] = temp[0 .. $ - 1];
immutable bool b = right.insert(temp[$ - 1], root, allocator, overwrite);
if (imbalanced() == 1)
rotateLeft(root, allocator);
calcHeight();
return b;
}
values[] = temp[1 .. $];
immutable bool b = left.insert(temp[0], root, allocator, overwrite);
if (imbalanced() == -1)
rotateRight(root, allocator);
calcHeight();
return b;
}
bool remove(Value value, ref Node* n, AllocatorType allocator,
void delegate(T) cleanup = null)
{
import std.range : assumeSorted;
assert (!isEmpty(), "Calling .remove on an empty TTree.Node");
if (isFull() && _less(value, values[0]))
{
immutable bool r = left !is null && left.remove(value, left, allocator, cleanup);
if (left.isEmpty())
deallocateNode(left, allocator);
return r;
}
if (isFull() && _less(values[$ - 1], value))
{
immutable bool r = right !is null && right.remove(value, right, allocator, cleanup);
if (right.isEmpty())
deallocateNode(right, allocator);
return r;
}
size_t i = nextAvailableIndex();
static if (is(typeof(_lessStr)))
auto sv = assumeSorted!_lessStr(values[0 .. i]);
else
auto sv = assumeSorted!_less(values[0 .. i]);
auto tri = sv.trisect(value);
if (tri[1].length == 0)
return false;
// Clean up removed item
if (cleanup !is null)
cleanup(tri[1][0]);
immutable size_t l = tri[0].length;
if (right is null && left is null)
{
Value[nodeCapacity - 1] temp;
temp[0 .. l] = values[0 .. l];
temp[l .. $] = values[l + 1 .. $];
values[0 .. $ - 1] = temp[];
markUnused(nextAvailableIndex() - 1);
}
else if (right !is null)
{
Value[nodeCapacity - 1] temp;
temp[0 .. l] = values[0 .. l];
temp[l .. $] = values[l + 1 .. $];
values[0 .. $ - 1] = temp[];
values[$ - 1] = right.removeSmallest(allocator);
if (right.isEmpty())
deallocateNode(right, allocator);
}
else if (left !is null)
{
Value[nodeCapacity - 1] temp;
temp[0 .. l] = values[0 .. l];
temp[l .. $] = values[l + 1 .. $];
values[1 .. $] = temp[];
values[0] = left.removeLargest(allocator);
if (left.isEmpty())
deallocateNode(left, allocator);
}
return true;
}
Value removeSmallest(AllocatorType allocator)
in
{
assert (!isEmpty(), "Calling .removeSmallest on an empty TTree.Node");
}
do
{
if (left is null && right is null)
{
Value r = values[0];
Value[nodeCapacity - 1] temp = void;
temp[] = values[1 .. $];
values[0 .. $ - 1] = temp[];
markUnused(nextAvailableIndex() - 1);
return r;
}
if (left !is null)
{
auto r = left.removeSmallest(allocator);
if (left.isEmpty())
deallocateNode(left, allocator);
return r;
}
Value r = values[0];
Value[nodeCapacity - 1] temp = void;
temp[] = values[1 .. $];
values[0 .. $ - 1] = temp[];
values[$ - 1] = right.removeSmallest(allocator);
if (right.isEmpty())
deallocateNode(right, allocator);
return r;
}
Value removeLargest(AllocatorType allocator)
in
{
assert (!isEmpty(), "Calling .removeLargest on an empty TTree.Node");
}
out (result)
{
static if (isPointer!T || is (T == class) || is(T == interface))
assert (result !is null, "Removed a null value");
}
do
{
if (left is null && right is null)
{
immutable size_t i = nextAvailableIndex() - 1;
Value r = values[i];
markUnused(i);
return r;
}
if (right !is null)
{
auto r = right.removeLargest(allocator);
if (right.isEmpty())
deallocateNode(right, allocator);
return r;
}
Value r = values[$ - 1];
Value[nodeCapacity - 1] temp = void;
temp[] = values[0 .. $ - 1];
values[1 .. $] = temp[];
values[0] = left.removeLargest(allocator);
if (left.isEmpty())
deallocateNode(left, allocator);
return r;
}
void rotateLeft(ref Node* root, AllocatorType allocator) @safe
{
Node* newRoot;
if (right.left !is null && right.right is null)
{
newRoot = right.left;
newRoot.parent = this.parent;
newRoot.left = &this;
newRoot.left.parent = newRoot;
newRoot.right = right;
newRoot.right.parent = newRoot;
newRoot.right.left = null;
right = null;
left = null;
}
else
{
newRoot = right;
newRoot.parent = this.parent;
right = newRoot.left;
if (right !is null)
right.parent = &this;
newRoot.left = &this;
this.parent = newRoot;
}
cleanup(newRoot, root, allocator);
}
void rotateRight(ref Node* root, AllocatorType allocator) @safe
{
Node* newRoot;
if (left.right !is null && left.left is null)
{
newRoot = left.right;
newRoot.parent = this.parent;
newRoot.right = &this;
newRoot.right.parent = newRoot;
newRoot.left = left;
newRoot.left.parent = newRoot;
newRoot.left.right = null;
left = null;
right = null;
}
else
{
newRoot = left;
newRoot.parent = this.parent;
left = newRoot.right;
if (left !is null)
left.parent = &this;
newRoot.right = &this;
this.parent = newRoot;
}
cleanup(newRoot, root, allocator);
}
void cleanup(Node* newRoot, ref Node* root, AllocatorType allocator) @safe
{
if (newRoot.parent !is null)
{
if (newRoot.parent.right is &this)
newRoot.parent.right = newRoot;
else
newRoot.parent.left = newRoot;
}
else
root = newRoot;
newRoot.fillFromChildren(root, allocator);
if (newRoot.left !is null)
{
newRoot.left.fillFromChildren(root, allocator);
}
if (newRoot.right !is null)
{
newRoot.right.fillFromChildren(root, allocator);
}
if (newRoot.left !is null)
newRoot.left.calcHeight();
if (newRoot.right !is null)
newRoot.right.calcHeight();
newRoot.calcHeight();
}
void fillFromChildren(ref Node* root, AllocatorType allocator) @trusted
{
while (!isFull())
{
if (left !is null)
{
insert(left.removeLargest(allocator), root, allocator, false);
if (left.isEmpty())
deallocateNode(left, allocator);
}
else if (right !is null)
{
insert(right.removeSmallest(allocator), root, allocator, false);
if (right.isEmpty())
deallocateNode(right, allocator);
}
else