-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBTree.cs
More file actions
2149 lines (1815 loc) · 78.8 KB
/
Copy pathBTree.cs
File metadata and controls
2149 lines (1815 loc) · 78.8 KB
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
/*
* ===========================================================================
* MODULE: B+ Tree Engine v1.0
* AUTHOR: Koivu
* DATE: 2026-03-08
* VERSION: 1.0.0
* LICENSE: MIT License
* ===========================================================================
*
* ABSTRACT:
* A high-performance, disk-resident B+ Tree implementation featuring
* proactive single-pass balancing. This engine prioritizes search
* efficiency via direct sector mapping for optimized node access.
*
*
* ARCHITECTURAL SPECIFICATION:
* - BALANCING: Top-down proactive splitting/merging (backtrack-free).
* - PERSISTENCE: Binary serialization with struct-based element alignment.
* - STORAGE: Stack-based FreeList for efficient sector-level reclamation.
* - INTEGRITY: Integrated Audit suite for cycle and ghost-key detection.
*
* KEYWORDS:
* Balanced Tree, Disk-Resident, Single-Pass, Sector Reclamation, Persistence.
*
* ---------------------------------------------------------------------------
* Copyright (c) 2026 Koivu.
* Licensed under the MIT License.
* ---------------------------------------------------------------------------
*/
using System.Buffers;
using System.Buffers.Binary;
using System.Collections;
namespace ArcOne
{
/// <summary>
/// Provides a structured interface for BTree file operations,
/// ensuring safe resource management and data persistence.
/// </summary>
public class BTree : IDisposable
{
private string MyFileName { get; set; }
private FileStream MyFileStream;
private BinaryReader MyReader;
private BinaryWriter MyWriter;
private readonly HashSet<int> FreeList = new HashSet<int>();
private const int HeaderSize = 4096;
private const int MagicConstant = BTreeHeader.MagicConstant;
public BTreeHeader Header;
/// <summary>
/// Initializes a new instance of the BTree class by opening an existing file
/// or creating a new one with the specified branching order.
/// </summary>
public BTree(string fileName, int order = 64)
{
if (string.IsNullOrEmpty(fileName))
throw new ArgumentException("File name cannot be empty.");
if (order < 4)
throw new ArgumentException("Order must be at least 4.");
MyFileName = fileName;
OpenStorage();
if (MyFileStream.Length > 0)
{
// 2. Existing file: Trust the disk.
LoadHeader();
LoadFreeList();
}
else
{
// 3. New file.
Header.Initialize(order);
SaveHeader();
}
}
/// <summary>
/// Open the file stream.
/// </summary>
private void OpenStorage()
{
const int BufferSize = 65536;
// 1. Close existing file.
MyWriter = null;
MyReader = null;
MyFileStream = null;
// 2. Open the file.
MyFileStream = new FileStream(MyFileName, FileMode.OpenOrCreate,
FileAccess.ReadWrite, FileShare.None, BufferSize);
// 3. Create the reader and writer.
MyReader = new BinaryReader(MyFileStream, System.Text.Encoding.UTF8, true);
MyWriter = new BinaryWriter(MyFileStream, System.Text.Encoding.UTF8, true);
}
/// <summary>
/// Close the file stream.
/// </summary>
private void CloseStorage()
{
MyWriter?.Dispose();
MyReader?.Dispose();
MyFileStream?.Dispose();
MyWriter = null;
MyReader = null;
MyFileStream = null;
}
// ------ HELPER METHODS ------
/// <summary>
/// Calculates the byte offset in the file for a given disk position (record index).
/// </summary>
private long CalculateOffset(int id)
{
if (id < 0)
throw new ArgumentOutOfRangeException(nameof(id), "Cannot be negative.");
if (Header.PageSize < 64)
throw new ArgumentException(nameof(Header.PageSize));
return ((long)Header.PageSize * id) + HeaderSize;
}
/// <summary>
/// Closes the object and releases resources by calling the Dispose method.
/// </summary>
public void Close()
{
Dispose();
}
/// <summary>
/// Safely persists data and releases the file stream while preventing redundant cleanup.
/// </summary>
public void Dispose()
{
if (MyFileStream != null)
{
try
{
SaveFreeList();
SaveHeader();
}
finally
{
MyFileStream.Dispose();
MyFileStream = null;
}
}
// Tell the GC we've already handled the cleanup.
GC.SuppressFinalize(this);
}
// -------- DISK I/O METHODS -----------
/// <summary>
/// Completely wipes the B-Tree structure and truncates the underlying data file.
/// This resets the header, clears the free list, and prepares the file for a fresh bulk load.
/// </summary>
/// <remarks>
/// Warning: This operation is destructive and cannot be undone.
/// </remarks>
public void Clear()
{
// 1. Wipe the physical file
MyFileStream.SetLength(0);
MyFileStream.Flush();
MyFileStream.Seek(0, SeekOrigin.Begin); // Crucial: Reset the pointer
// 2. Reset the logical state
Header.RootId = -1;
Header.NodeCount = 0;
FreeList.Clear();
// 3. Re-initialize the Header in the file
SaveHeader();
}
/// <summary>
/// Retrieves stored data from physical storage.
/// </summary>
public BNode DiskRead(int id)
{
if (id < 0)
{
throw new ArgumentOutOfRangeException(nameof(id), "Cannot be negative");
}
BNode node = new BNode(Header.Order);
long offset = CalculateOffset(id);
MyFileStream.Seek(offset, SeekOrigin.Begin);
node.Read(MyReader);
return node;
}
/// <summary>
/// Write a node to disk using the fixed binary layout described in DiskRead.
/// Ensure Header.Order and BNode layout remain compatible with previously written files.
/// </summary>
public void DiskWrite(BNode node)
{
if (node.Id < 0)
{
throw new ArgumentOutOfRangeException(nameof(node.Id), "Cannot be negative");
}
long offset = CalculateOffset(node.Id);
MyFileStream.Seek(offset, SeekOrigin.Begin);
node.Write(MyWriter);
}
/// <summary>
/// Wipes a specific node's data on disk by overwriting its sector with zeros.
/// This is typically used for security or to clean up nodes moved to a free list.
/// </summary>
public void ZeroNode(int id)
{
if (id < 0) throw new ArgumentOutOfRangeException(nameof(id), "Cannot be negative");
// 1. Create buffer on the stack.
Span<byte> buffer = stackalloc byte[Header.PageSize];
buffer.Clear();
// 2. Physical write.
long offset = CalculateOffset(id);
MyFileStream.Seek(offset, SeekOrigin.Begin);
MyFileStream.Write(buffer);
}
/// <summary>
/// Synchronizes the internal file stream with the underlying storage device to ensure all changes are persisted.
/// </summary>
public void Commit()
{
if (MyFileStream != null && MyFileStream.CanWrite)
{
SaveHeader();
MyFileStream.Flush();
}
}
// --- HEADER METHODS ---
/// <summary>
/// Writes the B-Tree header to disk.
/// </summary>
public void SaveHeader()
{
MyFileStream.Seek(0, SeekOrigin.Begin);
Header.Write(MyWriter);
}
/// <summary>
/// Load the B-Tree header from disk.
/// </summary>
public void LoadHeader()
{
MyFileStream.Seek(0, SeekOrigin.Begin);
Header = BTreeHeader.Read(MyReader);
if (Header.Magic != MagicConstant)
throw new InvalidDataException("Invalid File Format");
if (Header.Order < 4)
throw new ArgumentException("Order must be at least 4.");
if (Header.PageSize < 64 || Header.PageSize != BNode.CalculateNodeSize(Header.Order))
throw new ArgumentException(nameof(Header.PageSize));
}
// --- SEARCH METHODS ---
/// <summary>
/// Attempts to locate an element in the B-Tree by its unique key.
/// </summary>
public bool TrySearch(int key, out Element result)
{
result = Element.GetDefault();
if (Header.RootId == -1) return false;
BNode rootNode = DiskRead(Header.RootId);
return TrySearchIterative(rootNode, key, out result);
}
/// <summary>
/// Performs an iterative search for a specific key within the B-Tree.
/// This implementation avoids recursion to minimize stack overhead and uses
/// a tight loop for intra-node searching to maximize performance.
/// </summary>
private bool TrySearchIterative(BNode currentNode, int key, out Element result)
{
// Phase 1: Descend to the Leaf using Binary Search.
while (!currentNode.Leaf)
{
int low = 0;
int high = currentNode.NumKeys - 1;
int i = 0;
// Standard Binary Search to find the first key >= target key
while (low <= high)
{
int mid = low + (high - low) / 2;
if (currentNode.Keys[mid].Key <= key)
{
i = mid + 1; // Move right
low = mid + 1;
}
else
{
i = mid; // Potential candidate, move left
high = mid - 1;
}
}
// Always descend. Internal nodes are just signposts.
currentNode = DiskRead(currentNode.Kids[i]);
}
// Phase 2: Search the Leaf using Binary Search.
int l = 0;
int r = currentNode.NumKeys - 1;
while (l <= r)
{
int mid = l + (r - l) / 2;
if (currentNode.Keys[mid].Key == key)
{
result = currentNode.Keys[mid];
return true;
}
if (currentNode.Keys[mid].Key < key)
l = mid + 1;
else
r = mid - 1;
}
result = Element.GetDefault();
return false;
}
/// <summary>
/// Retrieves the very first (minimum) element in the B+ Tree.
/// It traverses the leftmost path of index nodes until it reaches the first leaf node,
/// where the smallest key is stored in the first position.
/// </summary>
public Element SelectFirst()
{
if (Header.RootId == -1) return default;
int currentId = Header.RootId;
while (true)
{
BNode node = DiskRead(currentId);
if (node.Leaf)
{
return node.NumKeys > 0 ? node.Keys[0] : default;
}
// Always go down the very first child pointer
currentId = node.Kids[0];
}
}
/// <summary>
/// Retrieves the very last (maximum) element in the B+ Tree.
/// It traverses the rightmost path of index nodes until it reaches the last leaf node,
/// where the largest key is stored at the final active index.
/// </summary>
public Element SelectLast()
{
if (Header.RootId == -1) return default;
int currentId = Header.RootId;
while (true)
{
BNode node = DiskRead(currentId);
if (node.Leaf)
{
return node.NumKeys > 0 ? node.Keys[node.NumKeys - 1] : default;
}
// Always go down the last active child pointer
currentId = node.Kids[node.NumKeys];
}
}
/// <summary>
/// Performs a range query to retrieve all elements between startKey and endKey (inclusive).
/// In a B+ Tree, this is highly efficient: it uses the index to find the starting leaf,
/// then follows the horizontal sibling links (NextLeafId) to traverse only the
/// necessary data pages until the endKey is exceeded.
/// </summary>
public IEnumerable<Element> EnumerateRange(int startKey, int endKey)
{
BNode current = FindLeaf(Header.RootId, startKey);
while (current != null)
{
for (int i = 0; i < current.NumKeys; i++)
{
int key = current.Keys[i].Key;
if (key >= startKey && key <= endKey)
yield return current.Keys[i];
if (key > endKey) yield break; // Exit the generator entirely
}
if (current.NextLeafId != -1)
current = DiskRead(current.NextLeafId);
else
break;
}
}
public List<int> GetKeyRange(int startKey, int endKey)
=> EnumerateRange(startKey, endKey).Select(e => e.Key).ToList();
public List<Element> GetElementRange(int startKey, int endKey)
=> EnumerateRange(startKey, endKey).ToList();
/// <summary>
/// Traverses the B+ Tree index to locate the leaf node that should contain the specified key.
/// It uses binary search at each internal node to determine which child branch to follow.
/// In a B+ Tree, this traversal always continues until a leaf is reached, as internal nodes
/// only act as a guide and do not store the actual data elements.
/// </summary>
public BNode FindLeaf(int nodeId, int key)
{
if (nodeId == -1) return null;
int currentId = nodeId;
while (true)
{
BNode node = DiskRead(currentId);
if (node.Leaf) return node;
// Binary Search for the child index
int low = 0, high = node.NumKeys - 1;
while (low <= high)
{
int mid = (low + high) / 2;
if (key >= node.Keys[mid].Key) low = mid + 1;
else high = mid - 1;
}
// low is the correct index for the child pointer
currentId = node.Kids[low];
}
}
// ------- INSERT METHODS --------
/// <summary>Inserts a new Element into the collection using the specified key and data.</summary>
public void Insert(int key, int data)
{
Element item = new Element(key, data);
Insert(item);
}
///// <summary>
///// Inserts an element into the B-Tree. If the tree is empty, it initializes the root.
///// If the root is full, it performs a preemptive split to increase tree height
///// before delegating to the recursive insertion logic.
///// </summary>
public void Insert(Element item)
{
bool headerChanged = false;
// 1. Handle Empty Tree.
if (Header.RootId == -1)
{
BNode firstNode = new BNode(Header.Order) { Leaf = true, Id = GetNextId() };
Header.RootId = firstNode.Id;
firstNode.Keys[0] = item;
firstNode.NumKeys = 1;
DiskWrite(firstNode);
headerChanged = true;
}
else
{
BNode rootNode = DiskRead(Header.RootId);
// 2. Handle Root Split (Preemptive split).
if (rootNode.NumKeys == Header.Order)
{
BNode newRoot = new BNode(Header.Order) { Leaf = false, Id = GetNextId() };
newRoot.Kids[0] = Header.RootId;
SplitChild(newRoot, 0, rootNode);
// Root changed, so update the header and track the change.
Header.RootId = newRoot.Id;
headerChanged = true;
// After split, decide which path to take.
InsertNonFull(newRoot, item);
}
else
{
InsertNonFull(rootNode, item);
}
}
// Only hit the disk for the header if a structural change occurred.
if (headerChanged)
{
SaveHeader();
}
}
// --- INSERTION HELPERS ---
/// <summary>
/// Navigates down the tree to the appropriate leaf for insertion, implementing a
/// proactive split strategy to maintain B+ Tree balance. If any internal node or leaf
/// along the path is at maximum capacity, it is split before descending.
/// For internal nodes, this method directs the search; for leaf nodes, it performs
/// the final sorted insertion and physical disk write.
/// </summary>
private void InsertNonFull(BNode node, Element item)
{
while (true)
{
if (node.Leaf)
{
// Binary search to find insert position
int low = 0, high = node.NumKeys - 1;
while (low <= high)
{
int mid = low + ((high - low) >> 1); // Optimized mid calculation
if (item.Key < node.Keys[mid].Key) high = mid - 1;
else low = mid + 1;
}
int insertPos = low;
if (insertPos < node.NumKeys)
{
Array.Copy(node.Keys, insertPos, node.Keys, insertPos + 1, node.NumKeys - insertPos);
}
node.Keys[insertPos] = item;
node.NumKeys++;
DiskWrite(node);
return;
}
else
{
// Internal Navigation
int low = 0, high = node.NumKeys - 1;
while (low <= high)
{
int mid = low + ((high - low) >> 1);
if (item.Key < node.Keys[mid].Key) high = mid - 1;
else low = mid + 1;
}
int pos = low;
BNode child = DiskRead(node.Kids[pos]);
if (child.NumKeys == Header.Order)
{
// Optimization: child is passed by reference; SplitChild updates it.
SplitChild(node, pos, child);
// Check if we need to move to the new sibling 'z' or stay with 'y'.
if (item.Key >= node.Keys[pos].Key)
{
pos++;
child = DiskRead(node.Kids[pos]); // Read the NEW sibling.
}
// Else: 'child' variable still points to 'y' which is now half-empty.
// We do NOT need to DiskRead(node.Kids[pos]) because 'child' is already 'y'.
}
node = child;
}
}
}
/// <summary>
/// Splits a full child node (y) into two, moving half of its contents into a new sibling node (z).
/// This method enforces B+ Tree structural rules:
/// 1. If 'y' is a leaf, the median key is COPIED to the parent and also stays in the leaf (z).
/// 2. If 'y' is a leaf, the sibling pointers (NextLeafId) are updated to maintain the linked list.
/// 3. If 'y' is internal, the median key is MOVED to the parent, acting as a separator.
/// </summary>
private void SplitChild(BNode x, int pos, BNode y)
{
BNode z = new BNode(Header.Order, leaf: y.Leaf) { Id = GetNextId() };
z.Leaf = y.Leaf;
z.NumKeys = 0; // Initialize clean
int medianIdx = y.NumKeys / 2;
Element keyToPromote = y.Keys[medianIdx];
// B+ Tree Rule: On a Leaf split, the median key stays in the right node (z).
// On an Internal split, the median key is promoted and removed from both children.
int startIdx = y.Leaf ? medianIdx : medianIdx + 1;
int keysToMove = y.NumKeys - startIdx;
if (y.Leaf)
{
z.NextLeafId = y.NextLeafId;
y.NextLeafId = z.Id;
}
// 2. BULK MOVE: Copy keys and children to Z
Array.Copy(y.Keys, startIdx, z.Keys, 0, keysToMove);
if (!y.Leaf)
{
Array.Copy(y.Kids, startIdx, z.Kids, 0, keysToMove + 1);
}
// 3. NUCLEAR WIPE: Clean Y completely from the split point forward
int wipeCount = y.NumKeys - medianIdx;
Array.Fill(y.Keys, Element.GetDefault(), medianIdx, wipeCount);
if (!y.Leaf)
{
// Internal nodes: Wipe the extra child pointer
Array.Fill(y.Kids, -1, medianIdx + 1, (y.NumKeys + 1) - (medianIdx + 1));
}
z.NumKeys = keysToMove;
y.NumKeys = medianIdx;
// 4. SHIFT PARENT X: Use Array.Copy for the right-shift
int parentMoveCount = x.NumKeys - pos;
if (parentMoveCount > 0)
{
Array.Copy(x.Keys, pos, x.Keys, pos + 1, parentMoveCount);
Array.Copy(x.Kids, pos + 1, x.Kids, pos + 2, parentMoveCount);
}
// 5. INSERT PROMOTED KEY
x.Keys[pos] = keyToPromote;
x.Kids[pos + 1] = z.Id;
x.NumKeys++;
DiskWrite(z);
DiskWrite(y);
DiskWrite(x);
}
/// <summary>
/// Provides a node ID for a new allocation by recycling an ID from the FreeList
/// or, if none are available, appending a new ID at the end of the storage.
/// </summary>
public int GetNextId()
{
// Get first item.
using (var enumerator = FreeList.GetEnumerator())
{
if (enumerator.MoveNext())
{
int nodeId = enumerator.Current;
FreeList.Remove(nodeId);
return nodeId;
}
}
// Append to end of file.
int nextPos = Header.NodeCount;
Header.NodeCount++;
return nextPos;
}
/// <summary>
/// Updates the data associated with an existing key.
/// In a B+ Tree architecture, actual data values are stored exclusively in leaf nodes.
/// This method traverses the index to the correct leaf, performs a binary search
/// to find the key, and persists the modified data element back to disk.
/// </summary>
public bool UpdateValue(int key, int data)
{
// 1. Find the leaf
BNode leaf = FindLeaf(Header.RootId, key);
// Safety check: ensure we actually have a leaf and not an internal node
if (leaf == null || !leaf.Leaf) return false;
// 2. Binary search
int low = 0, high = leaf.NumKeys - 1;
while (low <= high)
{
// Use the overflow-safe mid calculation
int mid = low + (high - low) / 2;
if (leaf.Keys[mid].Key == key)
{
// FOUND: Update user data and persist
leaf.Keys[mid].Data = data;
DiskWrite(leaf);
return true;
}
if (key < leaf.Keys[mid].Key) high = mid - 1;
else low = mid + 1;
}
return false;
}
/// <summary>
/// AddOrUpdates an element into the B+ Tree. It first attempts to locate the key
/// at the leaf level to update its value. If the key is not found, it performs
/// a standard B+ Tree insertion, which may involve splitting nodes from the
/// root down to the leaves to accommodate the new record.
/// </summary>
public void AddOrUpdate(int key, int data)
{
// Try to update; if it fails, the key doesn't exist, so insert.
if (!UpdateValue(key, data))
{
Insert(new Element { Key = key, Data = data });
}
}
/// <summary>
/// Adds a new element or updates an existing one using an Element object.
/// This ensures the B+ Tree remains the single source of truth for the
/// data record associated with the element's key.
/// </summary>
public void AddOrUpdate(Element item)
{
AddOrUpdate(item.Key, item.Data);
}
/// <summary>
/// Updates an existing record's data using the key provided in the Element object.
/// Returns true if the key was found and updated in a leaf node; otherwise, false.
/// </summary>
public bool UpdateValue(Element item)
{
return UpdateValue(item.Key, item.Data);
}
// ------ DELETE METHODS ------
/// <summary>
/// Removes the specified key from the B-Tree, rebalances the structure, and shrinks the tree height if the root becomes empty.
/// </summary>
public void Delete(int key, int data)
{
if (Header.RootId == -1) return;
Element deleteKey = new Element(key, data);
BNode rootNode = DiskRead(Header.RootId);
// 1. Perform the recursive deletion
DeleteSafe(rootNode, deleteKey);
// 2. IMPORTANT: Persist any changes made to the rootNode during recursion
// If DeleteSafe emptied it, we need that '0 keys' state on the disk now.
DiskWrite(rootNode);
// 3. RE-READ to ensure we are looking at the absolute latest state
BNode finalRoot = DiskRead(Header.RootId);
// 4. Root Collapse: If the root is a "Ghost" (0 keys, internal), bypass it.
if (finalRoot.NumKeys == 0 && !finalRoot.Leaf)
{
int oldId = Header.RootId;
// Promote the first child to be the new King.
Header.RootId = finalRoot.Kids[0];
// Save the Header immediately so the Audit knows where to start.
SaveHeader();
// Clean up the evidence of the old root
FreeNode(oldId);
}
}
// ------ DELETE HELPERS -------
/// <summary>
/// Locates and removes the absolute minimum element in the B+ Tree.
/// It traverses the leftmost edge of the index nodes to reach the first leaf node
/// in the linked chain, then triggers a deletion for the first key found there.
/// This may cause a ripple effect of merges or key redistributions up the tree
/// to satisfy B+ Tree occupancy requirements.
/// </summary>
public void DeleteFirst()
{
if (Header.RootId == -1) return;
// 1. Travel down the "Leftmost" path to the leaf
BNode current = DiskRead(Header.RootId);
while (!current.Leaf)
{
current = DiskRead(current.Kids[0]);
}
// 2. The first key in that leaf is the winner (or loser)
if (current.NumKeys > 0)
{
Delete(current.Keys[0].Key, current.Keys[0].Data);
}
}
/// <summary>
/// Locates and removes the absolute maximum element in the B+ Tree.
/// It traverses the rightmost path of the index nodes, always following the
/// last active child pointer, until it reaches the final leaf node.
/// The last key in this leaf is the maximum value, which is then passed to
/// the Delete logic for removal and potential structural rebalancing.
/// </summary>
public void DeleteLast()
{
if (Header.RootId == -1) return;
// 1. Travel down the "Rightmost" path
BNode current = DiskRead(Header.RootId);
while (!current.Leaf)
{
current = DiskRead(current.Kids[current.NumKeys]);
}
// 2. The last key in that leaf is the target
if (current.NumKeys > 0)
{
Delete(current.Keys[current.NumKeys - 1].Key, current.Keys[current.NumKeys - 1].Data);
}
}
/// <summary>
/// Merges two sibling nodes by pulling the separator key from the parent into the left child,
/// appending all contents from the right child, and decommissioning the now-redundant right node.
/// </summary>
///
private void MergeChildren(BNode parent, int pos, BNode y, BNode z)
{
if (!y.Leaf)
{
// INTERNAL: Move parent separator key down into Y
y.Keys[y.NumKeys] = parent.Keys[pos];
// Move all keys from Z to Y (starting after the promoted key)
Array.Copy(z.Keys, 0, y.Keys, y.NumKeys + 1, z.NumKeys);
// Move all kids from Z to Y
Array.Copy(z.Kids, 0, y.Kids, y.NumKeys + 1, z.NumKeys + 1);
y.NumKeys += 1 + z.NumKeys;
}
else
{
// LEAF: Concatenate keys (B+ Trees don't pull from parent into leaf)
Array.Copy(z.Keys, 0, y.Keys, y.NumKeys, z.NumKeys);
y.NumKeys += z.NumKeys;
y.NextLeafId = z.NextLeafId;
}
// Collapse parent: remove the separator key and the pointer to Z
parent.RemoveKeyAndChildAt(pos);
// Persist changes
DiskWrite(y);
DiskWrite(parent);
// Decommission Z: It is now empty space
FreeNode(z.Id);
}
/// <summary>
/// Performs a rightward rotation to rebalance a child node by moving a key from the parent down into the child,
/// and promoting the largest key from the left sibling up into the parent.
/// </summary>
private void BorrowFromLeftSibling(BNode parent, int pos, BNode child, BNode leftSibling)
{
// 1. Shift recipient (child) to the right
if (child.NumKeys > 0)
{
Array.Copy(child.Keys, 0, child.Keys, 1, child.NumKeys);
if (!child.Leaf)
{
Array.Copy(child.Kids, 0, child.Kids, 1, child.NumKeys + 1);
}
}
if (!child.Leaf)
{
// INTERNAL: Standard Rotation
child.Keys[0] = parent.Keys[pos - 1];
parent.Keys[pos - 1] = leftSibling.Keys[leftSibling.NumKeys - 1];
child.Kids[0] = leftSibling.Kids[leftSibling.NumKeys];
leftSibling.Kids[leftSibling.NumKeys] = -1; // Cleanup ghost pointer
}
else
{
// LEAF: Redistribution
child.Keys[0] = leftSibling.Keys[leftSibling.NumKeys - 1];
parent.Keys[pos - 1] = child.Keys[0];
}
child.NumKeys++;
// 2. Sibling Cleanup
leftSibling.Keys[leftSibling.NumKeys - 1] = Element.GetDefault();
leftSibling.NumKeys--;
// 3. Persist everything we touched
DiskWrite(child);
DiskWrite(leftSibling);
DiskWrite(parent);
}
/// <summary>
/// Performs a leftward rotation to rebalance a child node by moving a key from the parent down to the end of the child,
/// and promoting the smallest key from the right sibling up into the parent.
/// </summary>
///
private void BorrowFromRightSibling(BNode parent, int pos, BNode child, BNode rightSibling)
{
if (!child.Leaf)
{
// INTERNAL: Move parent down
child.Keys[child.NumKeys] = parent.Keys[pos];
child.Kids[child.NumKeys + 1] = rightSibling.Kids[0];
parent.Keys[pos] = rightSibling.Keys[0];
}
else
{
// LEAF: Pull first key from right sibling
child.Keys[child.NumKeys] = rightSibling.Keys[0];
// Parent separator becomes the new "smallest" in the right sibling
parent.Keys[pos] = rightSibling.Keys[1];
}
child.NumKeys++;
// 1. Shift right sibling's data to the left to fill the gap at index 0
int moveCount = rightSibling.NumKeys - 1;
if (moveCount > 0)
{
Array.Copy(rightSibling.Keys, 1, rightSibling.Keys, 0, moveCount);
if (!rightSibling.Leaf)
{
Array.Copy(rightSibling.Kids, 1, rightSibling.Kids, 0, rightSibling.NumKeys);
}
}
// 2. Sibling Cleanup (Nuclear Wipe)
rightSibling.Keys[rightSibling.NumKeys - 1] = Element.GetDefault();
if (!rightSibling.Leaf) rightSibling.Kids[rightSibling.NumKeys] = -1;
rightSibling.NumKeys--;
// 3. Persist
DiskWrite(child);
DiskWrite(rightSibling);
DiskWrite(parent);
}
/// <summary>
/// Performs a top-down, single-pass recursive deletion.
/// </summary>
/// <remarks>
/// This method proactively rebalances the tree by ensuring every child node visited has at least 't' keys
/// (minimum degree) before recursion. By performing rotations (Borrow) or Merges during the descent,
/// it guarantees that a deletion can be completed in a single trip to the leaf without backtracking.
/// </remarks>
private void DeleteSafe(BNode node, Element target)