-
Notifications
You must be signed in to change notification settings - Fork 0
/
BPlusTree.cs
795 lines (653 loc) · 25.1 KB
/
BPlusTree.cs
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
using Optional;
namespace HeapsAndBTrees
{
public class BPlusTree<TKey, TValue> :
DiagnostableBTreeBase<
TKey, TValue,
BPlusTree<TKey, TValue>.IBPlusTreeNode,
BPlusTree<TKey, TValue>.VirtualNode,
BPlusTree<TKey, TValue>.Node
>
where TKey : IComparable
{
public interface IBPlusTreeNode : INode<TKey>
{
public void RemoveFull(int index, bool leftToRight);
public void Print(int offset = 0);
}
public interface IBPlusTreeInternalNode : IBPlusTreeNode, IInternalNode<IBPlusTreeNode, TKey>
{
public void InsertKey(int index, TKey key);
public void RemoveKey(int index);
}
public interface IBPlusTreeValueNode : IBPlusTreeNode, IValueNode<TKey, TValue> { }
public abstract class Node : IBPlusTreeNode, IActualNode<IBPlusTreeNode, TKey>
{
protected int _keysCount;
public int KeysCount { get { return _keysCount; } set { _keysCount = value; } }
protected TKey[] _keys;
public ref TKey[] Keys { get { return ref _keys; } }
public virtual TKey GetKey(int index) => Keys[index];
public virtual void SetKey(int index, TKey key) => Keys[index] = key;
public abstract void RemoveFull(int index, bool leftToRight);
public abstract void Print(int offset = 0);
}
public class InternalNode : Node, IBPlusTreeInternalNode
{
public void InsertKey(int index, TKey key)
{
if (index < KeysCount)
{
Utilities.ShiftArrayRight(ref Keys, index, KeysCount);
}
Keys[index] = key;
KeysCount++;
}
public void RemoveKey(int index)
{
Keys[index] = default;
if (index != KeysCount - 1)
{
Utilities.ShiftArrayLeft(ref Keys, index, KeysCount - 1);
}
KeysCount--;
}
protected IBPlusTreeNode[] _children;
public ref IBPlusTreeNode[] Children { get { return ref _children; } }
public IBPlusTreeNode GetChild(int index)
{
if (Children is null)
{
InitializeChildren();
}
return Children[index];
}
public void SetChild(int index, IBPlusTreeNode child)
{
if (Children is null)
{
InitializeChildren();
}
Node childTyped = child switch
{
Node node => node,
VirtualNode virtualNode => virtualNode.Node as Node,
_ => throw new ArgumentException("Could not retrieve an actual node")
};
Children[index] = childTyped;
}
protected void InitializeChildren()
{
int size = Keys.Length + 1;
Children = new Node[size];
}
public void InsertChild(int index, IBPlusTreeNode child)
{
if (Children is null)
{
InitializeChildren();
}
if (index < KeysCount)
{
Utilities.ShiftArrayRight(ref Children, index, KeysCount);
}
SetChild(index, child);
}
public void RemoveChild(int index)
{
Children[index] = default;
Utilities.ShiftArrayLeft(ref Children, index, Keys.Length);
}
public InternalNode(int size)
{
KeysCount = 0;
Keys = new TKey[size - 1];
}
public override void RemoveFull(int index, bool leftToRight)
{
RemoveKey(index);
(this as IInternalNode<IBPlusTreeNode, TKey>).RemoveChild(leftToRight ? index + 1 : index);
}
public override void Print(int offset = 0)
{
for (int i = 0; i < offset; i++)
{
Console.Write("\t");
}
for (int i = 0; i < KeysCount; i++)
{
Console.Write(Keys[i]);
Console.Write(" ");
}
Console.Write("_");
Console.WriteLine();
if (Children is null)
{
return;
}
for (int i = 0; i <= KeysCount; i++)
{
Children[i].Print(offset + 1);
}
}
}
public class LeafNode : Node, IBPlusTreeValueNode
{
protected TValue[] _values;
public ref TValue[] Values { get { return ref _values; } }
public LeafNode(int size)
{
KeysCount = 0;
Keys = new TKey[size];
Values = new TValue[size];
}
public override void RemoveFull(int index, bool leftToRight)
{
(this as IValueNode<TKey, TValue>).RemoveValue(index);
}
public override void Print(int offset = 0)
{
for (int i = 0; i < offset; i++)
{
Console.Write("\t");
}
for (int i = 0; i < KeysCount; i++)
{
Console.Write($"{Keys[i]}: {Values[i]}");
Console.Write(" ");
}
Console.WriteLine();
}
}
public abstract class VirtualNode : IBPlusTreeNode, IVirtualNode<Node, IBPlusTreeNode, TKey>
{
public Node Node { get; protected set; }
public IBPlusTreeNode NodeTyped => Node;
protected BTreeContext<TKey, TValue, IBPlusTreeNode, VirtualNode, Node> _context;
public VirtualNode(Node node, BTreeContext<TKey, TValue, IBPlusTreeNode, VirtualNode, Node> context)
{
Node = node;
_context = context;
}
public bool IsDirty { get; protected set; } = false;
public int KeysCount
{
get
{
_context.Actualize(this);
return NodeTyped.KeysCount;
}
set
{
throw new Exception("Virtual node should change keys count only via wrapped node");
}
}
public ref TKey[] Keys
{
get
{
_context.Actualize(this);
return ref Node.Keys;
}
}
public virtual TKey GetKey(int index) => Keys[index];
public virtual void SetKey(int index, TKey key) => Keys[index] = key;
public virtual void RemoveFull(int index, bool leftToRight)
{
_context.Actualize(this);
IsDirty = true;
NodeTyped.RemoveFull(index, leftToRight);
}
public virtual void Print(int offset = 0)
{
_context.Actualize(this);
NodeTyped.Print(offset);
}
}
public class VirtualInternalNode : VirtualNode, IBPlusTreeInternalNode
{
public InternalNode NodeTyped => Node as InternalNode;
public VirtualInternalNode(InternalNode node, BTreeContext<TKey, TValue, IBPlusTreeNode, VirtualNode, Node> context) : base(node, context) { }
public void InsertKey(int index, TKey key)
{
_context.Actualize(this);
IsDirty = true;
NodeTyped.InsertKey(index, key);
}
public void RemoveKey(int index)
{
_context.Actualize(this);
IsDirty = true;
}
public ref IBPlusTreeNode[] Children
{
get
{
_context.Actualize(this);
return ref NodeTyped.Children;
}
}
public IBPlusTreeNode GetChild(int index)
{
_context.Actualize(this);
Node child = NodeTyped.GetChild(index) as Node;
return child switch
{
InternalNode internalNode => new VirtualInternalNode(internalNode, _context),
LeafNode leafNode => new VirtualLeafNode(leafNode, _context),
null => throw new ArgumentException("Requested child was null"),
_ => throw new ArgumentException("Child has unknown type")
};
}
public void SetChild(int index, IBPlusTreeNode child)
{
_context.Actualize(this);
IsDirty = true;
NodeTyped.SetChild(index, child);
}
public void InsertChild(int index, IBPlusTreeNode child)
{
_context.Actualize(this);
IsDirty = true;
NodeTyped.InsertChild(index, child);
}
public void RemoveChild(int index)
{
_context.Actualize(this);
IsDirty = true;
NodeTyped.RemoveChild(index);
}
}
public class VirtualLeafNode : VirtualNode, IBPlusTreeValueNode
{
public IValueNode<TKey, TValue> NodeTyped => Node as LeafNode;
public VirtualLeafNode(LeafNode node, BTreeContext<TKey, TValue, IBPlusTreeNode, VirtualNode, Node> context) : base(node, context)
{ }
public ref TValue[] Values
{
get
{
_context.Actualize(this);
return ref (NodeTyped as LeafNode).Values;
}
}
public TValue GetValue(int index)
{
_context.Actualize(this);
return NodeTyped.GetValue(index);
}
public void SetValue(int index, TValue key)
{
_context.Actualize(this);
IsDirty = true;
NodeTyped.SetValue(index, key);
}
public void InsertValue(int index, TKey key, TValue value)
{
_context.Actualize(this);
IsDirty = true;
NodeTyped.InsertValue(index, key, value);
}
public void RemoveValue(int index)
{
_context.Actualize(this);
IsDirty = true;
NodeTyped.RemoveValue(index);
}
}
private int _nodeSize;
private int _leafSize;
private int _contextSize;
private Node _root;
public BPlusTree(int nodeSize, int leafSize, int contextSize = 3)
{
_nodeSize = nodeSize;
_leafSize = leafSize;
_contextSize = contextSize;
UpdateRoot(new LeafNode(_leafSize));
}
private BTreeContext<TKey, TValue, IBPlusTreeNode, VirtualNode, Node> CreateContext(BTreeOperation caller) =>
new(
this,
(n, op) => DiskRead(n, op),
(n, op) => DiskWrite(n, op),
(n, context) => n switch
{
InternalNode internalNode => new VirtualInternalNode(internalNode, context),
LeafNode leafNode => new VirtualLeafNode(leafNode, context),
_ => throw new NotSupportedException()
},
_root, caller, _contextSize
);
public void UpdateRoot(IBPlusTreeNode newRoot)
{
Node newRootTyped = newRoot switch
{
Node node => node,
VirtualNode virtualNode => virtualNode.Node,
_ => throw new ArgumentException("Could not retrieve an actual node")
};
_root = newRootTyped;
InvokeOnRootChanged(newRootTyped);
}
public override void Clear()
{
UpdateRoot(new LeafNode(_leafSize));
}
private bool IsFull(IBPlusTreeNode node) => node switch
{
IBPlusTreeValueNode leafNode => leafNode.KeysCount == _leafSize,
IBPlusTreeInternalNode internalNode => internalNode.KeysCount == (_nodeSize - 1),
_ => throw new NotSupportedException()
};
private bool IsBig(IBPlusTreeNode node) => node switch
{
IBPlusTreeValueNode leafNode => leafNode.KeysCount > ((_leafSize / 2) - 1),
IBPlusTreeInternalNode internalNode => internalNode.KeysCount > ((_nodeSize / 2) - 1),
_ => throw new NotSupportedException()
};
private bool IsRoot(IBPlusTreeNode node) => node switch
{
Node n => n == _root,
VirtualNode v => v.Node == _root,
_ => throw new ArgumentException("Could not retrieve an actual node")
};
private int FindIndex(IBPlusTreeNode pointer, TKey key)
{
int start = 0;
int end = pointer.KeysCount;
while (start < end)
{
int middle = (start + end) / 2;
int comparisonResult = key.CompareTo(pointer.GetKey(middle));
switch (comparisonResult)
{
case 0:
return middle;
case < 0:
end = middle;
break;
default:
start = middle + 1;
break;
}
}
return end;
}
private void IndexFixup(TKey key, IBPlusTreeNode pointer, ref int index)
{
while (index < pointer.KeysCount && key.CompareTo(pointer.GetKey(index)) > 0)
{
index++;
}
}
private void Transfer(IBPlusTreeInternalNode donor, IBPlusTreeInternalNode donee, IBPlusTreeInternalNode parent, int mutualKey, bool leftToRight)
{
int insertIndex = leftToRight ? 0 : donee.KeysCount;
int transferIndex = leftToRight ? donor.KeysCount - 1 : 0;
int childTransferIndex = leftToRight ? transferIndex + 1 : transferIndex;
TKey transferKey = donor.GetKey(transferIndex);
donee.InsertKey(insertIndex, parent.GetKey(mutualKey));
donee.InsertChild(leftToRight ? insertIndex : insertIndex + 1, donor.GetChild(childTransferIndex));
donor.RemoveFull(transferIndex, leftToRight);
parent.SetKey(mutualKey, transferKey);
}
private void Transfer(IBPlusTreeValueNode donor, IBPlusTreeValueNode donee, IBPlusTreeInternalNode parent, int mutualKey, bool leftToRight)
{
int insertIndex = leftToRight ? 0 : donee.KeysCount;
int transferIndex = leftToRight ? donor.KeysCount - 1 : 0;
TKey transferKey = donor.GetKey(transferIndex);
donee.InsertValue(insertIndex, transferKey, donor.GetValue(transferIndex));
donor.RemoveFull(transferIndex, leftToRight);
parent.SetKey(mutualKey, leftToRight ? donor.GetKey(transferIndex - 1) : transferKey);
}
private void Transfer<T>(T donor, T donee, IBPlusTreeInternalNode parent, int mutualKey, bool leftToRight) where T : IBPlusTreeNode
{
switch ((donor, donee))
{
case (IBPlusTreeValueNode donorLeaf, IBPlusTreeValueNode doneeLeaf):
Transfer(donorLeaf, doneeLeaf, parent, mutualKey, leftToRight);
break;
case (IBPlusTreeInternalNode donorNode, IBPlusTreeInternalNode doneeNode):
Transfer(donorNode, doneeNode, parent, mutualKey, leftToRight);
break;
}
}
private void LeftTransfer<T>(T donor, T donee, IBPlusTreeInternalNode parent, int mutualKey) where T : IBPlusTreeNode => Transfer(donor, donee, parent, mutualKey, false);
private void RightTransfer<T>(T donor, T donee, IBPlusTreeInternalNode parent, int mutualKey) where T : IBPlusTreeNode => Transfer(donor, donee, parent, mutualKey, true);
private void Split(IBPlusTreeInternalNode parent, IBPlusTreeInternalNode child, int childIndex)
{
var node = new InternalNode(_nodeSize);
int size = child.KeysCount + 1;
int median = (size / 2) - 1;
node.InsertChild(0, child.GetChild(size - 1));
parent.InsertKey(childIndex, child.GetKey(size - 2));
child.RemoveFull(size - 2, true);
parent.InsertChild(childIndex + 1, node);
for (int index = size - 3; index >= median; index--)
{
RightTransfer(child, node, parent, childIndex);
}
}
private void Split(IBPlusTreeInternalNode parent, IBPlusTreeValueNode child, int childIndex)
{
var node = new LeafNode(_leafSize);
int size = child.KeysCount;
int median = (size / 2) - 1;
parent.InsertKey(childIndex, child.GetKey(size - 1));
parent.InsertChild(childIndex + 1, node);
for (int index = size - 2; index >= median; index--)
{
RightTransfer(child, node, parent, childIndex);
}
}
private void Split(IBPlusTreeInternalNode parent, IBPlusTreeNode child, int childIndex)
{
switch (child)
{
case IBPlusTreeValueNode leafNode:
Split(parent, leafNode, childIndex);
break;
case IBPlusTreeInternalNode internalNode:
Split(parent, internalNode, childIndex);
break;
}
}
private void Insert(TKey key, TValue value, IBPlusTreeValueNode pointer)
{
int index = FindIndex(pointer, key);
pointer.InsertValue(index, key, value);
return;
}
private void Insert(TKey key, TValue value, IBPlusTreeInternalNode pointer)
{
int index = FindIndex(pointer, key);
IBPlusTreeNode child = pointer.GetChild(index);
if (IsFull(child))
{
Split(pointer, child, index);
IndexFixup(key, pointer, ref index);
Insert(key, value, pointer.GetChild(index));
return;
}
Insert(key, value, child);
}
private void Insert(TKey key, TValue value, IBPlusTreeNode pointer)
{
switch (pointer)
{
case IBPlusTreeValueNode leafNode:
Insert(key, value, leafNode);
break;
case IBPlusTreeInternalNode internalNode:
Insert(key, value, internalNode);
break;
}
}
private void RootFix(IBPlusTreeNode root)
{
if (!IsFull(root))
{
return;
}
var node = new InternalNode(_nodeSize);
var temp = root;
UpdateRoot(node);
node.SetChild(0, temp);
Split(node, temp, 0);
}
public override void Insert(TKey key, TValue value)
{
using var context = CreateContext(BTreeOperation.Insert);
if (_watched)
{
_diagnosticsData[BTreeOperation.Insert].Count++;
}
RootFix(context.Root);
Insert(key, value, context.Root);
}
private void Merge(IBPlusTreeNode donor, IBPlusTreeNode donee, IBPlusTreeInternalNode parent, int mutualKey, bool leftToRight)
{
int keysCount = donor.KeysCount;
for (int fusionIndex = 0; fusionIndex < keysCount; fusionIndex++)
{
LeftTransfer(donor, donee, parent, mutualKey);
}
if (donee is IBPlusTreeInternalNode doneeTyped && donor is IBPlusTreeInternalNode donorTyped)
{
doneeTyped.InsertChild(donee.KeysCount + 1, donorTyped.GetChild(0));
doneeTyped.InsertKey(donee.KeysCount, parent.GetKey(mutualKey));
}
parent.RemoveFull(mutualKey, leftToRight);
if (IsRoot(parent) && parent.KeysCount == 0)
{
UpdateRoot(donee);
}
}
private void Delete(TKey key, IBPlusTreeInternalNode pointer)
{
if (pointer == null)
{
return;
}
int index = FindIndex(pointer, key);
var childNode = pointer.GetChild(index);
if (IsBig(childNode))
{
Delete(key, childNode);
return;
}
var childNodeNeighbor = index == 0 ? pointer.GetChild(index + 1) : pointer.GetChild(index - 1);
int parentKeyIndex = Math.Max(0, index - 1);
if (IsBig(childNodeNeighbor))
{
if (index == 0)
{
LeftTransfer(childNodeNeighbor, childNode, pointer, index);
}
else
{
RightTransfer(childNodeNeighbor, childNode, pointer, index - 1);
}
Delete(key, childNode);
return;
}
if (index != 0)
{
var temp = childNodeNeighbor;
childNodeNeighbor = childNode;
childNode = temp;
}
else
{
index++;
}
Merge(childNodeNeighbor, childNode, pointer, parentKeyIndex, index != 0);
Delete(key, childNode);
return;
}
private void Delete(TKey key, IBPlusTreeValueNode pointer)
{
int index = FindIndex(pointer, key);
if (index < pointer.KeysCount && key.CompareTo(pointer.GetKey(index)) == 0)
{
pointer.RemoveValue(index);
}
return;
}
private void Delete(TKey key, IBPlusTreeNode pointer)
{
switch (pointer)
{
case IBPlusTreeValueNode leafNode:
Delete(key, leafNode);
break;
case IBPlusTreeInternalNode internalNode:
Delete(key, internalNode);
break;
}
}
public override void Delete(TKey key)
{
using var context = CreateContext(BTreeOperation.Delete);
if (_watched)
{
_diagnosticsData[BTreeOperation.Delete].Count++;
}
Delete(key, context.Root);
}
public override Option<TValue> Search(TKey key)
{
using var context = CreateContext(BTreeOperation.Search);
if (_watched)
{
_diagnosticsData[BTreeOperation.Search].Count++;
}
IBPlusTreeNode pointer = context.Root;
while (pointer is IBPlusTreeInternalNode internalNode)
{
int index = FindIndex(internalNode, key);
pointer = internalNode.GetChild(index);
}
int leafIndex = FindIndex(pointer, key);
if (leafIndex < pointer.KeysCount && key.CompareTo(pointer.GetKey(leafIndex)) == 0)
{
return Option.Some((pointer as IBPlusTreeValueNode).GetValue(leafIndex));
}
return Option.None<TValue>();
}
private IEnumerable<(TKey, TValue)> Traverse(IBPlusTreeValueNode pointer)
{
IEnumerable<(TKey, TValue)> accumulator = new List<(TKey, TValue)>();
for (int i = 0; i <= pointer.KeysCount; ++i)
{
accumulator = accumulator.Append((pointer.GetKey(i), pointer.GetValue(i)));
}
return accumulator;
}
private IEnumerable<(TKey, TValue)> Traverse(IBPlusTreeInternalNode pointer)
{
IEnumerable<(TKey, TValue)> accumulator = new List<(TKey, TValue)>();
for (int i = 0; i <= pointer.KeysCount; ++i)
{
accumulator = accumulator.Concat(Traverse(pointer.GetChild(i)));
}
return accumulator;
}
private IEnumerable<(TKey, TValue)> Traverse(IBPlusTreeNode pointer) => pointer switch
{
LeafNode leafNode => Traverse(leafNode),
InternalNode internalNode => Traverse(internalNode),
_ => throw new NotSupportedException()
};
public override IEnumerable<(TKey, TValue)> Traverse()
{
return Traverse(_root);
}
public override void PrettyPrint()
{
_root.Print();
Console.WriteLine();
}
}
}