-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathBtreeSP.java
2191 lines (1980 loc) · 138 KB
/
BtreeSP.java
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
//------------------------------------------------------------------------------
// BtreeSML with transaction
// Philip R Brenan at appaapps dot com, Appa Apps Ltd Inc., 2024
//------------------------------------------------------------------------------
package com.AppaApps.Silicon; // Design, layout and simulate a btree in a block on the surface of a silicon chip.
import java.util.*;
abstract class BtreeSP extends Test // Manipulate a btree using static methods and memory
{final MemoryLayout memoryLayout = new MemoryLayout(); // The memory layout of the btree
abstract int maxSize(); // The maximum number of leaves plus branches in the bree
abstract int bitsPerKey(); // The number of bits per key
abstract int bitsPerData(); // The number of bits per data
abstract int bitsPerNext(); // The number of bits in a next field
abstract int bitsPerSize(); // The number of bits in size field
abstract int maxKeysPerLeaf(); // Maximum number of leafs in a key
abstract int maxKeysPerBranch(); // Maximum number of keys in a branch
final int splitLeafSize; // The number of key, data pairs to split out of a leaf
final int splitBranchSize; // The number of key, next pairs to split out of a branch
Layout.Field leaf; // Layout of a leaf in the memory used by btree
Layout.Field branch; // Layout of a branch in the memory used by btree
Layout.Union branchOrLeaf; // Layout of either a leaf or a branch in the memory used by btree
Layout.Bit isLeaf; // Whether the current node is a leaf or a branch
Layout.Variable free; // Free list chain
Layout.Structure Node; // Layout of a node in the memory used by btree
Layout.Array nodes; // Layout of an array of nodes in the memory used by btree
Layout.Variable freedChain; // Single linked list of freed nodes
Layout.Structure bTree; // Btree
final static int
linesToPrintABranch = 4, // The number of lines required to print a branch
maxPrintLevels = 10, // Maximum number of levels to print in a tree
maxDepth = 99, // Maximum depth of any realistic tree
testMaxSize = github_actions ? 1000 : 50; // Maximum number of leaves plus branches during testing
int nodeUsed = 0; // Number of nodes currently in use
int maxNodeUsed = 0; // Maximum number of branches plus leaves used
final int root = 0; // The root of the tree is always node zero
final int Branch_Size = 0; // Get the size of a stuck
final int Branch_Leaf = 0; // Check whether a node has leaves for children
final int Branch_Top = 0; // Get the top element of a branch
final int Branch_FirstBranch = 0; // Locate the first greater or equal key in a branch
final int Branch_T = 1; // Process a parent node
final int Branch_tl = 2; // Process a left node
final int Branch_tr = 3; // Process a right node
final int Branch_length = 4; // Number of transaction types
final int Leaf_T = 0; // Process a parent node
final int Leaf_tl = 1; // Process a left node
final int Leaf_tr = 2; // Process a right node
final int Leaf_length = 3; // Number of transaction types
final StuckSP[]branchTransactions; // Transactions to use on branch stucks
final StuckSP[] leafTransactions; // Transactions to use on leaf stucks
final StuckSP bSize; // Branch size
final StuckSP bLeaf; // Check whether a node has leaves for children
final StuckSP bTop; // Get the size of a stuck
final StuckSP bFirstBranch; // Locate the first greater or equal key in a branch
final StuckSP bT; // Process a parent node
final StuckSP bL; // Process a left node
final StuckSP bR; // Process a right node
final StuckSP lSize; // Branch size
final StuckSP lLeaf; // Check whether a node has leaves for children
final StuckSP lEqual; // Locate an equal key
final StuckSP lFirstLeaf; // Locate the first greater or equal key in a leaf
final StuckSP lT; // Process a parent node
final StuckSP lL; // Process a left node
final StuckSP lR; // Process a right node
static boolean debug = false; // Debugging enabled
//D1 Construction // Create a Btree from nodes which can be branches or leaves. The data associated with the BTree is stored only in the leaves opposite the keys
BtreeSP() // Define a Btree with user specified dimensions
{z();
splitLeafSize = maxKeysPerLeaf() >> 1; // The number of key, data pairs to split out of a leaf
splitBranchSize = maxKeysPerBranch() >> 1; // The number of key, next pairs to split out of a branch
memoryLayout.layout(layout());
memoryLayout.memory(new Memory("BtreeSP", memoryLayout.layout.size()));
{final int N = Branch_length; // Preallocate transactions used on branch stucks
branchTransactions = new StuckSP[N];
for (int i = 0; i < N; i++)
{final StuckSP b = branchTransactions[i] = new StuckSP()
{int maxSize() {return BtreeSP.this.maxKeysPerBranch()+1;} // Not forgetting top next
int bitsPerKey() {return BtreeSP.this.bitsPerKey();}
int bitsPerData() {return BtreeSP.this.bitsPerNext();}
int bitsPerSize() {return BtreeSP.this.bitsPerSize();}
};
b.M.memory(memoryLayout.memory);
}
}
{final int N = Leaf_length; // Preallocate transactions used on leaf stucks
leafTransactions = new StuckSP[N];
for (int i = 0; i < N; i++)
{final StuckSP l = leafTransactions[i] = new StuckSP()
{int maxSize() {return BtreeSP.this.maxKeysPerLeaf();}
int bitsPerKey() {return BtreeSP.this.bitsPerKey();}
int bitsPerData() {return BtreeSP.this.bitsPerData();}
int bitsPerSize() {return BtreeSP.this.bitsPerSize();}
};
l.M.memory(memoryLayout.memory);
}
}
bSize = branchTransactions[Branch_Size ]; // Branch size
bLeaf = branchTransactions[Branch_Leaf ]; // Check whether a node has leaves for children
bTop = branchTransactions[Branch_Top ]; // Get the size of a stuck
bFirstBranch = branchTransactions[Branch_FirstBranch]; // Locate the first greater or equal key in a branch
bT = branchTransactions[Branch_T ]; // Process a parent node
bL = branchTransactions[Branch_tl ]; // Process a left node
bR = branchTransactions[Branch_tr ]; // Process a right node
lSize = leafTransactions[Leaf_T ]; // Leaf size
lLeaf = leafTransactions[Leaf_T ]; // Print a leaf
lEqual = leafTransactions[Leaf_T ]; // Locate an equal key
lFirstLeaf = leafTransactions[Leaf_T ]; // Locate the first greater or equal key in a leaf
lT = leafTransactions[Leaf_T ]; // Process a parent node
lL = leafTransactions[Leaf_tl ]; // Process a left node
lR = leafTransactions[Leaf_tr ]; // Process a right node
for (int i = maxSize(); i > 0; --i) // Put all the nodes on the free chain at the start with low nodes first
{final int n = i - 1; // Number of node
node_clear = n; clear();
final int f = getInt(freedChain);
setInt(free, f, n);
setInt(freedChain, n);
}
allocate(false); // The root is always at zero, which frees zero to act as the end of list marker on the free chain
node_setLeaf = root; setLeaf(); // The root starts as a leaf
}
static BtreeSP btreeSP(final int leafKeys, int branchKeys) // Define a test btree with the specified dimensions
{return new BtreeSP()
{int maxSize () {return testMaxSize;}
int maxKeysPerLeaf () {return leafKeys;}
int maxKeysPerBranch() {return branchKeys;}
int bitsPerKey () {return 16;}
int bitsPerData () {return 16;}
int bitsPerNext () {return 16;}
int bitsPerSize () {return 16;}
};
}
Layout layout() // Layout describing memory used by btree
{z();
final BtreeSP btree = this;
final StuckSP leafStuck = new StuckSP() // Leaf
{int maxSize() {return btree.maxKeysPerLeaf();}
int bitsPerKey() {return btree.bitsPerKey();}
int bitsPerData() {return btree.bitsPerData();}
int bitsPerSize() {return btree.bitsPerSize();}
};
final StuckSP branchStuck = new StuckSP() // Branch
{int maxSize() {return btree.maxKeysPerBranch()+1;} // Not forgetting top next
int bitsPerKey() {return btree.bitsPerKey();}
int bitsPerData() {return btree.bitsPerNext();}
int bitsPerSize() {return btree.bitsPerSize();}
};
final Layout l = Layout.layout();
leaf = l.duplicate("leaf", leafStuck.layout());
branch = l.duplicate("branch", branchStuck.layout());
branchOrLeaf = l.union ("branchOrLeaf", leaf, branch);
isLeaf = l.bit ("isLeaf");
free = l.variable ("free", btree.bitsPerNext());
Node = l.structure("node", isLeaf, free, branchOrLeaf);
nodes = l.array ("nodes", Node, maxSize());
freedChain = l.variable ("freedChain", btree.bitsPerNext());
bTree = l.structure("bTree", freedChain , nodes);
return l.compile();
}
//D1 Control // Testing, control and integrity
private void ok(String expected) {Test.ok(toString(), expected);} // Confirm tree is as expected
private void stop() {Test.stop(toString());} // Stop after printing the tree
public String toString() {return print();} // Print the tree
//D1 Memory access // Access to memory
private int getInt(Layout.Field field) {z(); return memoryLayout.getInt(field);}
private int getInt(Layout.Field field, int index) {z(); return memoryLayout.getInt(field, index);}
private void setInt(Layout.Field field, int value) {z(); memoryLayout.setInt(field, value);}
private void setInt(Layout.Field field, int value, int index) {z(); memoryLayout.setInt(field, value, index);}
//D1 Memory allocation // Allocate and free memory
private void allocate(boolean check) // Allocate a node with or without checking for sufficient free space
{z(); allocate = getInt(freedChain); // Last freed node
z(); if (check && allocate == 0) stop("No more memory available"); // No more free nodes available
z(); nextFree = getInt(free, allocate); // Second to last freed node
setInt(freedChain, nextFree); // Make second to last freed node the first freed node to liberate the existing first free node
node_clear = allocate; clear(); // Construct and clear the node
maxNodeUsed = max(maxNodeUsed, ++nodeUsed); // Number of nodes in use
}
private void allocate() {z(); allocate(true);} // Allocate a node checking for free space
//D1 Components // A branch or leaf in the tree
int allocate; // The latest allocation result
int nextFree; // Next element of the free chain
boolean success; // Inserted or updated if true
boolean inserted; // Inserted if true
int first; // Index of first key greater than or equal to the search key
int next; // The corresponding next field or top if no such key was found
// Find equal in leaf
int search; // Search key
boolean found; // Whether the key was found
int key; // Key to insert
int data; // Data associated with the key
int firstKey; // First of right leaf
int lastKey; // Last of left leaf
int flKey; // Key mid way between last of left and first of right
int parentKey; // Parent key
int lk; // Left child key
int ld; // Left child data
int rk; // Right child key
int rd; // Right child data
int index; // Index of a slot in a node
int nl; // Number in the left child
int nr; // Number in the right child
int l; // Left node
int r; // Right node
int splitParent; // The parent during a splitting operation
boolean IsLeaf; // On a leaf
boolean isFull; // The node is full
boolean isLow; // The node has too few children for a delete
boolean hasLeavesForChildren; // The node has leaves for children
boolean stolenOrMerged; // A merge or steal operation succeeded
int leafBase; // The offset of a leaf in memory
int branchBase; // The offset of a branch in memory
int leafSize; // Number of children in body of leaf
int branchSize; // Number of children in body of branch taking top for granted as it is always there
int top; // The top next element of a branch - only used in printing
// Find, insert, delete - the public entry points to this module
int Key; // Key being found, inserted or deleted
int Data; // Data found, inserted or deleted
int find; // Results of a find operation
int findAndInsert; // Results of a find and insert operation
int parent; // Parent node in a descent through the tree
int child; // Child node in a descent through the tree
int leafFound; // Leaf found by find
int node_isLeaf; // The node to be used to implicitly parameterize each method call
int node_setLeaf;
int node_setBranch;
int node_assertLeaf;
int node_assertBranch;
int allocLeaf;
int allocBranch;
int node_free;
int node_clear;
int node_erase;
int node_leafBase;
int node_branchBase;
int node_leafSize;
int node_branchSize;
int node_isFull;
int node_isLow;
int node_hasLeavesForChildren;
int node_top;
int node_findEqualInLeaf;
int node_findFirstGreaterThanOrEqualInLeaf;
int node_findFirstGreaterThanOrEqualInBranch;
int node_splitLeaf;
int node_splitBranch;
int node_stealFromLeft;
int node_stealFromRight;
int node_mergeRoot;
int node_mergeLeftSibling;
int node_mergeRightSibling;
int node_balance;
private void isLeaf() {z(); IsLeaf = getInt(isLeaf, node_isLeaf) > 0;} // A leaf if true
private void setLeaf() {z(); setInt(isLeaf, 1, node_setLeaf);} // Set as leaf
private void setBranch() {z(); setInt(isLeaf, 0, node_setBranch);} // Set as branch
private void assertLeaf() {z(); node_isLeaf = node_assertLeaf; isLeaf(); if (!IsLeaf) stop("Leaf required");}
private void assertBranch() {z(); node_isLeaf = node_assertBranch; isLeaf(); if ( IsLeaf) stop("Branch required");}
private void allocLeaf() {z(); allocate(); allocLeaf = node_setLeaf = allocate; setLeaf(); } // Allocate leaf
private void allocBranch(){z(); allocate(); allocBranch = node_setBranch = allocate; setBranch();} // Allocate branch
private void free() // Free a new node to make it available for reuse
{z(); if (node_free == 0) stop("Cannot free root"); // The root is never freed
z(); node_erase = node_free; erase(); // Clear the node to encourage erroneous frees to do damage that shows up quickly.
final int f = getInt(freedChain); // Last freed node from head of free chain
setInt(free, f, node_free); // Chain this node in front of the last freed node
setInt(freedChain, node_free); // Make this node the head of the free chain
maxNodeUsed = max(maxNodeUsed, --nodeUsed); // Number of nodes in use
}
private void clear() // Clear a new node to zeros ready for use
{z();
final Layout.Field n = Node;
final int at = n.at(node_clear), w = n.width;
memoryLayout.memory.zero(at, w);
}
private void erase() // Clear a new node to ones as this is likely to create invalid values that will be easily detected in the case of erroneous frees
{z();
final Layout.Field n = Node;
final int at = n.at(node_erase), w = n.width;
memoryLayout.memory.ones(at, w);
}
private void leafBase() {z(); leafBase = leaf .at(node_leafBase);} // Base of leaf stuck in memory
private void branchBase() {z(); branchBase = branch.at(node_branchBase);} // Base of branch stuck in memory
private void leafSize() // Number of children in body of leaf
{z();
node_leafBase = node_leafSize; leafBase();
lSize.base(leafBase);
lSize.size();
leafSize = lSize.size;
}
private void branchSize() // Number of children in body of branch taking top for granted as it is always there
{z();
node_branchBase = node_branchSize; branchBase();
bSize.base(branchBase);
bSize.size();
branchSize = bSize.size-1;
}
private void isFull() // The node is full
{z(); node_isLeaf = node_isFull; isLeaf();
if (IsLeaf)
{z(); node_leafSize = node_isFull; leafSize();
isFull = leafSize == maxKeysPerLeaf();
}
else
{z(); node_branchSize = node_isFull; branchSize();
isFull = branchSize == maxKeysPerBranch();
}
}
private void isLow() // The node is low on children making it impossible to merge two sibling children
{z(); node_isLeaf = node_isLow; isLeaf();
if (IsLeaf) {node_leafSize = node_isLow; leafSize(); isLow = leafSize < 2;}
else {node_branchSize = node_isLow; branchSize(); isLow = branchSize < 2;}
}
private void hasLeavesForChildren() // The node has leaves for children
{z(); node_assertBranch = node_hasLeavesForChildren; assertBranch();
node_branchBase = node_hasLeavesForChildren; branchBase();
bLeaf.base(branchBase);
bLeaf.lastElement();
node_isLeaf = bLeaf.tData; isLeaf();
hasLeavesForChildren = IsLeaf;
}
private void top() // The top next element of a branch - only used in printing
{z(); node_assertBranch = node_top; assertBranch();
node_branchBase = node_top; branchBase();
bTop.base(branchBase);
node_branchSize = node_top; branchSize();
bTop.index = branchSize;
bTop.elementAt();
top = bTop.tData;
}
public String toString(int node) // Print a node
{final StringBuilder s = new StringBuilder();
node_isLeaf = node; isLeaf(); // Print a leaf
if (IsLeaf) // Print a leaf
{node_leafSize = node; leafSize(); // Number of elements in leaf
final int N = leafSize; // Number of elements in leaf
s.append("Leaf(node:"+node+" size:"+N+")\n");
node_leafBase = node; leafBase();
lLeaf.base(leafBase);
for (int i = 0; i < N; i++) // Each element in the leaf
{lLeaf.index = i;
lLeaf.elementAt();
s.append(" "+(i+1)+" key:"+lLeaf.tKey+" data:"+lLeaf.tData+"\n");
}
}
else // Print a branch
{node_branchSize = node; branchSize();
final int N = branchSize; // Number of elements in branch not including top
node_top = node; top();
s.append("Branch(node:"+node+" size:"+N+" top:"+top+"\n");
node_branchBase = node; branchBase();
bLeaf.base(branchBase);
for (int i = 0; i < N; i++)
{bLeaf.index = i; bLeaf.elementAt();
s.append(String.format(" %2d key:%2d next:%2d\n", i+1, bLeaf.tKey, bLeaf.tData));
}
bLeaf.index = N; bLeaf.elementAt();
s.append(" Top:"+bLeaf.tData+")\n");
}
return s.toString();
}
//D2 Search // Search within a node and update the node description with the results
private void findEqualInLeaf() // Find the first key in the leaf that is equal to the search key
{z(); node_assertLeaf = node_findEqualInLeaf; assertLeaf();
node_leafBase = node_findEqualInLeaf; leafBase();
lEqual.base(leafBase);
lEqual.search = search; lEqual.search();
found = lEqual.found;
index = lEqual.index;
data = lEqual.tData;
}
public String findEqualInLeaf_toString() // Print details of find equal in leaf node
{final StringBuilder s = new StringBuilder();
s.append("FindEqualInLeaf(Leaf:"+node_findEqualInLeaf);
s.append(" Key:"+search+" found:"+found);
if (found) s.append(" data:"+data+" index:"+index);
s.append(")\n");
return s.toString();
}
private void findFirstGreaterThanOrEqualInLeaf() // Find the first key in the leaf that is equal to or greater than the search key
{z(); node_assertLeaf = node_findFirstGreaterThanOrEqualInLeaf; assertLeaf();
node_leafBase = node_findFirstGreaterThanOrEqualInLeaf; leafBase();
lFirstLeaf.base(leafBase);
lFirstLeaf.search = search; lFirstLeaf.searchFirstGreaterThanOrEqual();
found = lFirstLeaf.found;
first = lFirstLeaf.index;
}
private void findFirstGreaterThanOrEqualInBranch() // Find the first key in the branch that is equal to or greater than the search key
{z();
node_assertBranch = node_findFirstGreaterThanOrEqualInBranch; assertBranch();
node_branchBase = node_findFirstGreaterThanOrEqualInBranch; branchBase();
bFirstBranch.base(branchBase);
bFirstBranch.search = search; bFirstBranch.limit = 1;
bFirstBranch.searchFirstGreaterThanOrEqual();
found = bFirstBranch.found;
first = bFirstBranch.index;
if (bFirstBranch.found) next = bFirstBranch.tData; // Next if key matches else top
else {bFirstBranch.lastElement(); next = bFirstBranch.tData;}
}
//D2 Array // Represent the contents of the tree as an array
private void leafToArray(int node, Stack<ArrayElement> s) // Leaf as an array
{z(); node_assertLeaf = node; assertLeaf();
node_leafSize = node; leafSize();
final int K = leafSize;
final StuckSP t = lLeaf.copy();
node_leafBase = node; leafBase();
t.base(leafBase);
for (int i = 0; i < K; i++)
{z();
t.index = i; t.elementAt();
s.push(new ArrayElement(i, t.tKey, t.tData));
}
}
private void branchToArray(int node, Stack<ArrayElement> s) // Branch to array
{z(); node_assertBranch = node; assertBranch();
node_branchSize = node; branchSize();
final int K = branchSize+1; // Include top next
if (K > 0) // Branch has key, next pairs
{z();
final StuckSP t = bLeaf.copy();
node_branchBase = node; branchBase();
t.base(branchBase);
for (int i = 0; i < K; i++)
{z();
t.index = i; t.elementAt(); // Each node in the branch
node_isLeaf = t.tData; isLeaf();
if (IsLeaf) {z(); leafToArray(t.tData, s);}
else
{z();
if (t.tData == 0)
{say("Cannot descend through root from index", i,
"in branch", node);
break;
}
z(); branchToArray(t.tData, s);
}
}
}
}
//D2 Print // Print the contents of the tree
private void printLeaf(int node, Stack<StringBuilder>S, int level) // Print leaf horizontally
{node_assertLeaf = node; assertLeaf();
padStrings(S, level);
final StringBuilder s = new StringBuilder(); // String builder
node_leafSize = node; leafSize();
final int K = leafSize;
final StuckSP t = lLeaf.copy();
node_leafBase = node; leafBase();
t.base(leafBase);
for (int i = 0; i < K; i++)
{t.index = i; t.elementAt(); // Each node in the branch
s.append(""+t.tKey+",");
}
if (s.length() > 0) s.setLength(s.length()-1); // Remove trailing comma if present
s.append("="+node+" ");
S.elementAt(level*linesToPrintABranch).append(s.toString());
padStrings(S, level);
}
private void printBranch(int node, Stack<StringBuilder>S, int level) // Print branch horizontally
{node_assertBranch = node; assertBranch();
if (level > maxPrintLevels) return;
padStrings(S, level);
final int L = level * linesToPrintABranch;
node_branchSize = node; branchSize();
final int K = branchSize;
if (K > 0) // Branch has key, next pairs
{final StuckSP t = bLeaf.copy();
node_branchBase = node; branchBase();
t.base(branchBase);
for (int i = 0; i < K; i++)
{t.index = i; t.elementAt(); // Each node in the branch
node_isLeaf = t.tData; isLeaf();
if (IsLeaf)
{printLeaf(t.tData, S, level+1);
}
else
{if (t.tData == 0)
{say("Cannot descend through root from index", i,
"in branch", node);
break;
}
printBranch(t.tData, S, level+1);
}
S.elementAt(L+0).append(""+t.tKey); // Key
S.elementAt(L+1).append(""+node+(i > 0 ? "."+i : "")); // Index in node
S.elementAt(L+2).append(""+t.tData); // Next
}
}
else // Branch is empty so print just the index of the branch
{S.elementAt(L+0).append(""+node+"Empty");
}
node_top = node; top(); // Top next will always be present
S.elementAt(L+3).append(top); // Append top next
node_isLeaf = top; isLeaf(); // Print leaf
if (IsLeaf) // Print leaf
{printLeaf(top, S, level+1);
}
else // Print branch
{if (top == 0)
{say("Cannot descend through root from top in branch:", node);
return;
}
printBranch(top, S, level+1);
}
padStrings(S, level);
}
public String find_toString() // Print find result
{final StringBuilder s = new StringBuilder();
s.append("Find(");
s.append( " search:"+search);
s.append( " found:"+found);
s.append( " data:"+data);
s.append( " index:"+index);
s.append(")\n");
return s.toString();
}
public String findAndInsert_toString() // Print find and insert result
{final StringBuilder s = new StringBuilder();
s.append("FindAndInsert(");
s.append( " key:"+key);
s.append( " data:"+data);
s.append(" success:"+success);
if (success) s.append(" inserted:"+inserted);
s.append(")\n" );
return s.toString();
}
public String findFirstGreaterThanOrEqualInLeaf_toString() // Print results of search
{final StringBuilder s = new StringBuilder();
s.append("FindFirstGreaterThanOrEqualInLeaf(");
s.append( "Leaf:"+node_findFirstGreaterThanOrEqualInLeaf);
s.append( " Key:"+search);
s.append(" found:"+found);
if (found) s.append(" first:"+first);
s.append(")\n");
return s.toString();
}
public String findFirstGreaterThanOrEqualInBranch_toString() // Print search results
{final StringBuilder s = new StringBuilder();
s.append("FindFirstGreaterThanOrEqualInBranch(");
s.append("branch:"+node_findFirstGreaterThanOrEqualInBranch);
s.append( " Key:"+search);
s.append(" found:"+found);
s.append( " next:"+next);
if (found) s.append(" first:"+first);
s.append(")\n");
return s.toString();
}
//D2 Split // Split nodes in half to increase the number of nodes in the tree
private void splitLeafRoot() // Split a leaf which happens to be a full root into two half full leaves while transforming the root leaf into a branch
{z(); node_assertLeaf = root; assertLeaf();
z(); node_isFull = root; isFull();
if (!isFull)
{node_leafSize = root; leafSize();
stop("Root is not full, but has size:", leafSize);
}
allocLeaf(); l = allocLeaf; // New left leaf
allocLeaf(); r = allocLeaf; // New right leaf
node_leafBase = root; leafBase(); lT.base(leafBase); // Set address of the referenced leaf stuck
node_leafBase = l; leafBase(); lL.base(leafBase); // Set address of the referenced leaf stuck
node_leafBase = r; leafBase(); lR.base(leafBase); // Set address of the referenced leaf stuck
for (int i = 0; i < splitLeafSize; i++) // Build left leaf from parent
{z(); lT.shift(); lL.tKey = lT.tKey; lL.tData = lT.tData; lL.push();
}
for (int i = 0; i < splitLeafSize; i++) // Build right leaf from parent
{z(); lT.shift(); lR.tKey = lT.tKey; lR.tData = lT.tData; lR.push();
}
lR.firstElement();
lL. lastElement();
node_setBranch = root; setBranch(); // The root is now a branch
node_branchBase = root; branchBase(); // Set address of the referenced leaf stuck
bT.base(branchBase); // Set address of the referenced leaf stuck
bT.clear(); // Clear the branch
firstKey = lR.tKey; // First of right leaf
lastKey = lL.tKey; // Last of left leaf
flKey = (lastKey + firstKey) / 2; // Mid key
bT.tKey = flKey; bT.tData = l; bT.push(); // Insert left leaf into root
bT.tKey = 0; bT.tData = r; bT.push(); // Insert right into root. This will be the top node and so ignored by search ... except last.
}
private void splitBranchRoot() // Split a branch which happens to be a full root into two half full branches while retaining the current branch as the root
{z(); node_assertBranch = root; assertBranch();
z(); node_isFull = root; isFull();
if (!isFull)
{node_branchSize = root; branchSize();
stop("Root is not full, but has size:", branchSize);
}
z();
allocBranch(); l = allocBranch; // New left branch
allocBranch(); r = allocBranch; // New right branch
node_branchBase = root; branchBase(); bT.base(branchBase); // Set address of the referenced branch stuck
node_branchBase = l; branchBase(); bL.base(branchBase); // Set address of the referenced branch stuck
node_branchBase = r; branchBase(); bR.base(branchBase); // Set address of the referenced branch stuck
for (int i = 0; i < splitBranchSize; i++) // Build left child from parent
{z(); bT.shift(); bL.tKey = bT.tKey; bL.tData = bT.tData; bL.push();
}
bT.shift(); // This key, next pair will be part of the root
parentKey = bT.tKey;
bL.tKey = 0; bL.tData = bT.tData; bL.push(); // Becomes top and so ignored by search ... except last
for(int i = 0; i < splitBranchSize; i++) // Build right child from parent
{z(); bT.shift(); bR.tKey = bT.tKey; bR.tData = bT.tData; bR.push();
}
bT.shift(); bR.tKey = 0; bR.tData = bT.tData; bR.push(); // Becomes top and so ignored by search ... except last
bT.clear(); // Refer to new branches from root
bT.tKey = parentKey; bT.tData = l; bT.push();
bT.tKey = 0; bT.tData = r; bT.push(); // Becomes top and so ignored by search ... except last
}
private void splitLeaf() // Split a leaf which is not the root
{z(); node_assertLeaf = node_splitLeaf; assertLeaf();
z(); if (node_splitLeaf == 0) stop("Cannot split root with this method");
z(); node_leafSize = node_splitLeaf; leafSize();
z(); final int S = leafSize, I = index;
node_isFull = node_splitLeaf; isFull();
z(); final boolean nif = !isFull;
node_isFull = splitParent; isFull();
z(); final boolean pif = isFull;
z(); if (nif) stop("Leaf:", node_splitLeaf, "is not full, but has:", S, this);
z(); if (pif) stop("Leaf split parent:", splitParent, "must not be full");
z(); if (I < 0) stop("Index", I, "too small");
z(); if (I > S) stop("Index", I, "too big for leaf with:", S);
z();
allocLeaf(); l = allocLeaf; // New split out leaf
node_leafBase = l; leafBase(); lL.base(leafBase); // The leaf being split into
node_leafBase = node_splitLeaf; leafBase(); lR.base(leafBase); // The leaf being split on the right
for (int i = 0; i < splitLeafSize; i++) // Build left leaf
{z(); lR.shift(); lL.tKey = lR.tKey; lL.tData = lR.tData; lL.push();
}
lR.firstElement();
lL. lastElement();
node_branchBase = splitParent; branchBase(); // The parent branch
bT.base(branchBase); // The parent branch
bT.tKey = (lR.tKey + lL.tKey) / 2; // Splitting key
bT.tData = l;
bT.index = index;
bT.insertElementAt(); // Insert new key, next pair in parent
}
private void splitBranch() // Split a branch which is not the root by splitting right to left
{z(); node_assertBranch = node_splitBranch; assertBranch();
z(); node_branchSize = node_splitBranch; branchSize();
z(); final int bs = branchSize, I = index, pn = splitParent, nd = node_splitBranch;
node_isFull = node_splitBranch; isFull();
z(); final boolean nif = !isFull;
node_isFull = splitParent; isFull();
z(); final boolean pif = isFull;
z(); if (nd == 0) stop("Cannot split root with this method");
z(); if (nif) stop("Branch:", nd, "is not full, but", bs);
z(); if (pif) stop("Branch split parent:", pn, "must not be full");
z(); if (I < 0) stop("Index", I, "too small in node:", nd);
z(); if (I > bs) stop("Index", I, "too big for branch with:",
bs, "in node:", nd);
z();
allocBranch(); l = allocBranch;
node_branchBase = splitParent; branchBase(); bT.base(branchBase); // The parent branch
node_branchBase = l; branchBase(); bL.base(branchBase); // The branch being split into
node_branchBase = node_splitBranch; branchBase(); bR.base(branchBase); // The branch being split
for (int i = 0; i < splitBranchSize; i++) // Build left branch from right
{z(); bR.shift(); bL.tKey = bR.tKey; bL.tData = bR.tData; bL.push();
}
bR.shift(); bL.tKey = 0; bL.tData = bR.tData; bL.push(); // Build right branch - becomes top and so is ignored by search ... except last
bT.tKey = bR.tKey; bT.tData = l; bT.index = index; bT.insertElementAt();
}
private void stealFromLeft() // Steal from the left sibling of the indicated child if possible to give to the right - Dennis Moore, Dennis Moore, Dennis Moore.
{z(); node_assertBranch = node_stealFromLeft; assertBranch();
z(); if (index == 0) {z(); stolenOrMerged = false; return;}
z(); if (index < 0) stop("Index", index, "too small");
z(); node_branchSize = node_stealFromLeft; branchSize();
z(); if (index > branchSize) stop("Index", index, "too big");
z();
node_branchBase = node_stealFromLeft; branchBase();
bT.base(branchBase);
bT.index = index - 1; bT.elementAt(); l = bT.tData;
bT.index = index - 0; bT.elementAt(); r = bT.tData;
node_hasLeavesForChildren = node_stealFromLeft; hasLeavesForChildren(); // Children are leaves
if (hasLeavesForChildren) // Children are leaves
{z();
node_leafBase = l; leafBase(); lL.base(leafBase);
node_leafBase = r; leafBase(); lR.base(leafBase);
node_leafSize = l; leafSize(); nl = leafSize;
node_leafSize = r; leafSize(); nr = leafSize;
if (nr >= maxKeysPerLeaf()) {z(); stolenOrMerged = false; return;} // Steal not possible because there is no where to put the steal
if (nl <= 1) {z(); stolenOrMerged = false; return;} // Steal not allowed because it would leave the leaf sibling empty
z();
lL.lastElement(); lR.tKey = lL.tKey; lR.tData = lL.tData; lR.unshift(); // Increase right
lL.pop(); // Reduce left
lL.index = nl-2; lL.elementAt(); // Last key on left
bT.tKey = lL.tKey; bT.tData = l; bT.index = index-1; bT.setElementAt(); // Reduce key of parent of left
}
else // Children are branches
{z();
node_branchBase = l; branchBase(); bL.base(branchBase);
node_branchBase = r; branchBase(); bR.base(branchBase);
node_branchSize = l; branchSize(); nl = branchSize;
node_branchSize = r; branchSize(); nr = branchSize;
z(); if (nr >= maxKeysPerBranch()) {z(); stolenOrMerged = false; return;} // Steal not possible because there is no where to put the steal
z(); if (nl <= 1) {z(); stolenOrMerged = false; return;} // Steal not allowed because it would leave the left sibling empty
z();
bL.lastElement(); // Increase right with left top
bT.index = index; bT.elementAt(); // Top key
bR.tKey = bT.tKey; bR.tData = bL.tData; bR.unshift(); // Increase right with left top
bL.pop(); // Remove left top
bR.firstElement(); // Increase right with left top
bT.index = index-1; bT.elementAt(); // Parent key
bR.tKey = bT.tKey; bR.index = 0; bR.setElementAt(); // Reduce key of parent of right
bL.lastElement(); // Last left key
bT.tKey = bL.tKey; bT.tData = l; bT.index = index-1; bT.setElementAt(); // Reduce key of parent of left
}
z(); stolenOrMerged = true; return;
}
private void stealFromRight() // Steal from the right sibling of the indicated child if possible
{z(); node_assertBranch = node_stealFromRight; assertBranch();
z(); node_branchSize = node_stealFromRight; branchSize();
if (index == branchSize) {z(); stolenOrMerged = false; return;}
z(); if (index < 0) stop("Index", index, "too small");
z(); if (index >= branchSize) stop("Index", index, "too big");
z();
node_branchBase = node_stealFromRight; branchBase();
bT.base(branchBase);
bT.index = index+0; bT.elementAt(); lk = bT.tKey; l = bT.tData;
bT.index = index+1; bT.elementAt(); rk = bT.tKey; r = bT.tData;
node_hasLeavesForChildren = node_stealFromRight; hasLeavesForChildren(); // Children are leaves
if (hasLeavesForChildren) // Children are leaves
{z();
node_leafBase = l; leafBase(); lL.base(leafBase);
node_leafBase = r; leafBase(); lR.base(leafBase);
node_leafSize = l; leafSize(); nl = leafSize;
node_leafSize = r; leafSize(); nr = leafSize;
if (nl >= maxKeysPerLeaf()) {z(); stolenOrMerged = false; return;} // Steal not possible because there is no where to put the steal
if (nr <= 1) {z(); stolenOrMerged = false; return;} // Steal not allowed because it would leave the right sibling empty
z();
lR.firstElement(); // First element of right child
lL.tKey = lR.tKey; lL.tData = lR.tData; lL.push(); // Increase left
bT.tKey = lR.tKey; bT.tData = l; bT.index = index; bT.setElementAt(); // Swap key of parent
lR.shift(); // Reduce right
}
else // Children are branches
{z();
node_branchBase = l; branchBase(); bL.base(branchBase);
node_branchBase = r; branchBase(); bR.base(branchBase);
node_branchSize = l; branchSize(); nl = branchSize;
node_branchSize = r; branchSize(); nr = branchSize;
z(); if (nl >= maxKeysPerBranch()) {z(); stolenOrMerged = false; return;} // Steal not possible because there is no where to put the steal
z(); if (nr <= 1) {z(); stolenOrMerged = false; return;} // Steal not allowed because it would leave the right sibling empty
z();
bL.lastElement(); // Last element of left child
bL.tKey = lk; bL.index = nl; bL.setElementAt(); // Left top becomes real
bR.firstElement(); // First element of right child
bL.tKey = 0; bL.tData = bR.tData; bL.push(); // New top for left is ignored by search ,.. except last
bT.tKey = bR.tKey; bT.tData = l; bT.index = index; bT.setElementAt(); // Swap key of parent
bR.shift(); // Reduce right
}
z(); stolenOrMerged = true; return;
}
//D2 Merge // Merge two nodes together and free the resulting free node
private void mergeRoot() // Merge into the root
{z();
node_isLeaf = root; isLeaf();
z(); if (IsLeaf) {z(); stolenOrMerged = false; return;} // Confirm we are on a branch
node_branchSize = root; branchSize();
z(); if (branchSize > 1) {z(); stolenOrMerged = false; return;} // Confirm we are on an almost empty root
z();
node_branchBase = root; branchBase();
bT.base(branchBase);
bT.firstElement(); l = bT.tData;
bT. lastElement(); r = bT.tData;
node_hasLeavesForChildren = root; hasLeavesForChildren();
if (hasLeavesForChildren) // Leaves
{z();
node_leafSize = l; leafSize(); nl = leafSize;
node_leafSize = r; leafSize(); nr = leafSize;
if (nl + nr <= maxKeysPerLeaf())
{z(); bT.clear();
node_leafBase = l; leafBase(); lL.base(leafBase);
node_leafBase = r; leafBase(); lR.base(leafBase);
for (int i = 0; i < nl; ++i) // Merge in left child leaf
{z(); lL.shift(); bT.tKey = lL.tKey; bT.tData = lL.tData; bT.push();
}
for (int i = 0; i < nr; ++i) // Merge in right child leaf
{z(); lR.shift(); bT.tKey = lR.tKey; bT.tData = lR.tData; bT.push();
}
node_setLeaf = root; setLeaf(); // The root is now a leaf
node_free = l; free(); // Free the children
node_free = r; free();
z(); stolenOrMerged = true; return;
}
z(); stolenOrMerged = false; return;
}
else // Branches
{node_branchSize = l; branchSize(); nl = branchSize;
node_branchSize = r; branchSize(); nr = branchSize;
if (nl + 1 + nr <= maxKeysPerBranch())
{z();
node_branchBase = l; branchBase(); bL.base(branchBase);
node_branchBase = r; branchBase(); bR.base(branchBase);
bT.firstElement();
parentKey = bT.tKey;
bT.clear();
for (int i = 0; i < nl; ++i) // Merge left child branch
{z(); bL.shift(); bT.tKey = bL.tKey; bT.tData = bL.tData; bT.push();
}
bL.lastElement();
bT.tKey = parentKey; bT.tData = bL.tData; bT.push();
for (int i = 0; i < nr; ++i) // Merge right child branch
{z(); bR.shift(); bT.tKey = bR.tKey; bT.tData = bR.tData; bT.push();
}
bR.lastElement(); // Top next
bT.tKey = 0; bT.tData = bR.tData; bT.push(); // Top so ignored by search ... except last
node_free = l; free(); // Free the children
node_free = r; free();
z(); stolenOrMerged = true; return;
}
z(); stolenOrMerged = false; return;
}
}
private void mergeLeftSibling() // Merge the left sibling
{z(); node_assertBranch = node_mergeLeftSibling; assertBranch();
z(); if (index == 0) {z(); stolenOrMerged = false; return;}
node_branchSize = node_mergeLeftSibling; branchSize();
final int bs = branchSize;
final String s = "for branch of size: "+bs;
z(); if (index < 0 ) stop("Index", index, "too small", s);
z(); if (index > bs) stop("Index", index, "too big", s);
//if (branchSize() < 2) stop("Node:", this, "must have two or more children");
z(); if (bs < 2 ) {z(); stolenOrMerged = false; return;}
z();
node_branchBase = node_mergeLeftSibling; branchBase();
bT.base(branchBase);
bT.index = index-1; bT.elementAt(); l = bT.tData;
bT.index = index-0; bT.elementAt(); r = bT.tData;
node_hasLeavesForChildren = node_mergeLeftSibling; hasLeavesForChildren();
if (hasLeavesForChildren) // Children are leaves
{z();
node_leafBase = l; leafBase(); lL.base(leafBase);
node_leafBase = r; leafBase(); lR.base(leafBase);
node_leafSize = l; leafSize(); nl = leafSize;
node_leafSize = r; leafSize(); nr = leafSize;
if (nl + nr >= maxKeysPerLeaf()) {z(); stolenOrMerged = false; return;} // Combined body would be too big
for (int i = 0; i < nl; i++) // Transfer left to right
{z(); lL.pop(); lR.tKey = lL.tKey; lR.tData = lL.tData; lR.unshift();
}
}
else // Children are branches
{z();
node_branchBase = l; branchBase(); bL.base(branchBase);
node_branchBase = r; branchBase(); bR.base(branchBase);
node_branchSize = l; branchSize(); nl = branchSize;
node_branchSize = r; branchSize(); nr = branchSize;
if (nl + 1 + nr > maxKeysPerBranch()) {z(); stolenOrMerged = false; return;} // Merge not possible because there is not enough room for the combined result
z();
bT.index = index-1; // Top key
bT.elementAt(); // Top key
bL.lastElement(); // Last element of left child
bR.tKey = bT.tKey; bR.tData = bL.tData; bR.unshift(); // Left top to right
bL.pop(); // Remove left top
for (int i = 0; i < nl; i++) // Transfer left to right
{z(); bL.pop(); bR.tKey = bL.tKey; bR.tData = bL.tData; bR.unshift();
}
}
node_free = l; free(); // Free the empty left node
bT.index = index - 1;
bT.removeElementAt(); // Reduce parent on left
z(); stolenOrMerged = true; return;
}
private void mergeRightSibling() // Merge the right sibling
{z(); node_assertBranch = node_mergeRightSibling; assertBranch();
node_branchSize = node_mergeRightSibling; branchSize();
final int bs = branchSize;
final String s = "for branch of size: "+bs;
z(); if (index >= bs) {z(); stolenOrMerged = false; return;}
z(); if (index < 0 ) stop("Index", index, "too small", s);
z(); if (index > bs) stop("Index", index, "too big", s);