Repository navigation
Expand file tree
/
Copy pathBTreeMap.java
More file actions
3586 lines (3002 loc) · 115 KB
/
Copy pathBTreeMap.java
File metadata and controls
3586 lines (3002 loc) · 115 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
/*
* Copyright (c) 2012 Jan Kotek
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* NOTE: some code (and javadoc) used in this class
* comes from JSR-166 group with following copyright:
*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/licenses/publicdomain
*/
package org.mapdb;
import java.io.Closeable;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ConcurrentNavigableMap;
import java.util.concurrent.locks.LockSupport;
/**
* <p>
* A scalable concurrent {@link ConcurrentNavigableMap} implementation.
* The map is sorted according to the {@linkplain Comparable natural
* ordering} of its keys, or by a {@link Comparator} provided at map
* creation time.
* </p><p>
*
* Insertion, removal,
* update, and access operations safely execute concurrently by
* multiple threads. Iterators are <i>weakly consistent</i>, returning
* elements reflecting the state of the map at some point at or since
* the creation of the iterator. They do <em>not</em> throw {@link
* ConcurrentModificationException}, and may proceed concurrently with
* other operations. Ascending key ordered views and their iterators
* are faster than descending ones.
* </p><p>
*
* It is possible to obtain <i>consistent</i> iterator by using <code>snapshot()</code>
* method.
* </p><p>
*
* All <tt>Map.Entry</tt> pairs returned by methods in this class
* and its views represent snapshots of mappings at the time they were
* produced. They do <em>not</em> support the <tt>Entry.setValue</tt>
* method. (Note however that it is possible to change mappings in the
* associated map using <tt>put</tt>, <tt>putIfAbsent</tt>, or
* <tt>replace</tt>, depending on exactly which effect you need.)
* </p><p>
*
* This collection has optional size counter. If this is enabled Map size is
* kept in {@link Atomic.Long} variable. Keeping counter brings considerable
* overhead on inserts and removals.
* If the size counter is not enabled the <tt>size</tt> method is <em>not</em> a constant-time operation.
* Determining the current number of elements requires a traversal of the elements.
* </p><p>
*
* Additionally, the bulk operations <tt>putAll</tt>, <tt>equals</tt>, and
* <tt>clear</tt> are <em>not</em> guaranteed to be performed
* atomically. For example, an iterator operating concurrently with a
* <tt>putAll</tt> operation might view only some of the added
* elements. NOTE: there is an optional
* </p><p>
*
* This class and its views and iterators implement all of the
* <em>optional</em> methods of the {@link Map} and {@link Iterator}
* interfaces. Like most other concurrent collections, this class does
* <em>not</em> permit the use of <tt>null</tt> keys or values because some
* null return values cannot be reliably distinguished from the absence of
* elements.
* </p><p>
*
* Theoretical design of BTreeMap is based on 1986 paper
* <a href="http://www.sciencedirect.com/science/article/pii/0022000086900218">
* Concurrent operations on B∗-trees with overtaking</a>
* written by Yehoshua Sagiv.
* More practical aspects of BTreeMap implementation are based on
* <a href="http://cs.au.dk/~tyoung/~td202/">notes</a>
* and <a href="http://cs.au.dk/~tyoung/~td202/btree/">demo application</a> from Thomas Dinsdale-Young.
* Also more work from Thomas: <a href="http://www.doc.ic.ac.uk/research/technicalreports/2011/#10">A Simple Abstraction for Complex Concurrent Indexes</a>
* </p><p>
*
* B-Linked-Tree used here does not require locking for read.
* Updates and inserts locks only one, two or three nodes.
* Original BTree design does not use overlapping lock (lock is released before parent node is locked), I added it just to feel safer.
* </p><p>
*
* This B-Linked-Tree structure does not support removal well, entry deletion does not collapse tree nodes. Massive
* deletion causes empty nodes and performance lost. There is workaround in form of compaction process, but it is not
* implemented yet.
* </p>
*
* @author Jan Kotek
* @author some parts by Doug Lea and JSR-166 group
*
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public class BTreeMap<K,V>
extends AbstractMap<K,V>
implements ConcurrentNavigableMap<K,V>,
Bind.MapWithModificationListener<K,V>,
Closeable {
/** recid under which reference to rootRecid is stored */
protected final long rootRecidRef;
/** Serializer used to convert keys from/into binary form. */
protected final BTreeKeySerializer keySerializer;
/** Serializer used to convert keys from/into binary form*/
protected final Serializer<V> valueSerializer;
/** holds node level locks*/
protected final LongConcurrentHashMap<Thread> nodeLocks = new LongConcurrentHashMap<Thread>();
/** maximal node size allowed in this BTree*/
protected final int maxNodeSize;
/** DB Engine in which entries are persisted */
protected final Engine engine;
/** is this a Map or Set? if false, entries do not have values, only keys are allowed*/
protected final boolean hasValues;
/** store values as part of BTree nodes */
protected final boolean valsOutsideNodes;
protected final List<Long> leftEdges;
private final KeySet keySet;
private final EntrySet entrySet;
private final Values values = new Values(this);
private final ConcurrentNavigableMap<K,V> descendingMap = new DescendingMap(this, null,true, null, false);
protected final Atomic.Long counter;
protected final int numberOfNodeMetas;
/**
* Indicates if this collection collection was not made by DB by user.
* If user can not access DB object, we must shutdown Executor and close Engine ourself in close() method.
*/
protected final boolean closeEngine;
/* hack used for DB Catalog*/
protected static SortedMap<String, Object> preinitCatalog(DB db) {
Long rootRef = db.getEngine().get(Engine.RECID_NAME_CATALOG, Serializer.RECID);
;
//$DELAY$
if(rootRef==null){
if(db.getEngine().isReadOnly())
return Collections.unmodifiableSortedMap(new TreeMap<String, Object>());
NodeSerializer rootSerializer = new NodeSerializer(false,BTreeKeySerializer.STRING,
db.getDefaultSerializer(), 0);
BNode root = new LeafNode(BTreeKeySerializer.STRING.emptyKeys(), true,true,false, new Object[]{}, 0);
rootRef = db.getEngine().put(root, rootSerializer);
//$DELAY$
db.getEngine().update(Engine.RECID_NAME_CATALOG,rootRef, Serializer.RECID);
db.getEngine().commit();
}
Serializer valser = db.getDefaultSerializer();
if(CC.ASSERT && valser == null)
throw new AssertionError();
return new BTreeMap<String, Object>(
db.engine,
false,
Engine.RECID_NAME_CATALOG,
32,
false,
0,
BTreeKeySerializer.STRING,
valser,
0
);
}
/** if <code>valsOutsideNodes</code> is true, this class is used instead of values.
* It contains reference to actual value. It also supports assertions from preventing it to leak outside of Map*/
protected static final class ValRef{
/** reference to actual value */
final long recid;
public ValRef(long recid) {
this.recid = recid;
}
@Override
public boolean equals(Object obj) {
throw new IllegalAccessError();
}
@Override
public int hashCode() {
throw new IllegalAccessError();
}
@Override
public String toString() {
return "BTreeMap-ValRef["+recid+"]";
}
}
protected static final class ValRefSerializer extends Serializer<ValRef>{
@Override
public void serialize(DataOutput out, ValRef value) throws IOException {
DataIO.packLong(out,value.recid);
}
@Override
public ValRef deserialize(DataInput in, int available) throws IOException {
return new ValRef(DataIO.unpackLong(in));
}
@Override
public boolean isTrusted() {
return true;
}
@Override
public boolean equals(ValRef a1, ValRef a2) {
throw new IllegalAccessError();
}
@Override
public int hashCode(ValRef valRef) {
throw new IllegalAccessError();
}
}
/** common interface for BTree node */
public abstract static class BNode{
static final int LEFT_MASK = 1;
static final int RIGHT_MASK = 1<<1;
static final int TOO_LARGE_MASK = 1<<2;
final Object keys;
final byte flags;
public BNode(Object keys, boolean leftEdge, boolean rightEdge, boolean tooLarge){
this.keys = keys;
this.flags = (byte)(
(leftEdge?LEFT_MASK:0)|
(rightEdge?RIGHT_MASK:0)|
(tooLarge?TOO_LARGE_MASK:0)
);
}
final public Object key(BTreeKeySerializer keyser, int pos) {
if(isLeftEdge()){
if(pos--==0)
return null;
}
if(pos==keyser.length(keys) && isRightEdge())
return null;
return keyser.getKey(keys,pos);
}
final public int keysLen(BTreeKeySerializer keyser) {
return keyser.length(keys) + leftEdgeInc() + rightEdgeInc();
}
final public boolean isLeftEdge(){
return (flags&LEFT_MASK)!=0;
}
final public boolean isRightEdge(){
return (flags&RIGHT_MASK)!=0;
}
/** @return 1 if is left edge, or 0*/
final public int leftEdgeInc(){
return flags&LEFT_MASK;
}
/** @return 1 if is right edge, or 0*/
final public int rightEdgeInc(){
return (flags&RIGHT_MASK)>>>1;
}
final public boolean isTooLarge(){
return (flags&TOO_LARGE_MASK)!=0;
}
public abstract boolean isLeaf();
public abstract Object val(int pos, Serializer valueSerializer);
final public Object highKey(BTreeKeySerializer keyser) {
if(isRightEdge())
return null;
return keyser.getKey(keys,keyser.length(keys)-1);
}
public abstract Object childArray();
public abstract long child(int i);
public abstract long next();
public final int compare(final BTreeKeySerializer keyser, int pos1, int pos2){
if(pos1==pos2)
return 0;
//$DELAY$
if(isLeftEdge()){
//first position is negative infinity, so everything else is bigger
//first keys is missing in array, so adjust positions
if(pos1--==0)
return -1;
if(pos2--==0)
return 1;
}
//$DELAY$
if(isRightEdge()){
int keysLen = keyser.length(keys);
//last position is positive infinity, so everything else is smaller
if(pos1==keysLen)
return 1;
if(pos2==keysLen)
return -1;
}
return keyser.compare(keys,pos1,pos2);
}
public final int compare(final BTreeKeySerializer keyser, int pos, Object second){
if(isLeftEdge()) {
//first position is negative infinity, so everything else is bigger
//first keys is missing in array, so adjust positions
if (pos-- == 0)
return -1;
}
//$DELAY$
if(isRightEdge() && pos==keyser.length(keys)){
//last position is positive infinity, so everything else is smaller
return 1;
}
return keyser.compare(keys,pos,second);
}
public void checkStructure(BTreeKeySerializer keyser, Serializer valser){
//check all keys are sorted;
if(keyser==null)
return;
int keylen = keyser.length(keys);
int end = keylen-2+rightEdgeInc();
if(end>1){
for(int i = 1;i<=end;i++){
if(keyser.compare(keys,i-1, i)>=0)
throw new DBException.DataCorruption("keys are not sorted: "+Arrays.toString(keyser.keysToArray(keys)));
}
}
//check last key is sorted or null
if(!isRightEdge() && keylen>2){
if(keyser.compare(keys,keylen-2, keylen-1)>0){
throw new DBException.DataCorruption("Last key is not sorted: "+Arrays.toString(keyser.keysToArray(keys)));
}
}
}
public abstract BNode copyAddKey(BTreeKeySerializer keyser, Serializer valser, int pos, Object newKey, long newChild, Object newValue);
public abstract BNode copySplitRight(BTreeKeySerializer keyser, Serializer valser, int splitPos);
public abstract BNode copySplitLeft(BTreeKeySerializer keyser, Serializer valser, int splitPos, long newNext);
public abstract int valSize(Serializer valueSerializer);
public abstract int childArrayLength();
}
public final static class DirNode extends BNode{
final Object child;
DirNode(Object keys, boolean leftEdge, boolean rightEdge, boolean tooLarge, Object child) {
super(keys, leftEdge, rightEdge, tooLarge);
this.child = child;
if(CC.ASSERT)
checkStructure(null,null);
}
@Override public boolean isLeaf() { return false;}
@Override public Object val(int pos, Serializer valueSerializer){
return null;
}
@Override public Object childArray() { return child;}
@Override public long child(int pos) {
Object c = child;
return c instanceof int[]?
((int[])c)[pos]:
((long[])c)[pos];
}
@Override
public int childArrayLength() {
return child instanceof int[]?
((int[])child).length:
((long[])child).length;
}
@Override public long next() {
Object c = child;
if(c instanceof int[]){
int[] cc = (int[]) c;
return cc[cc.length-1];
}else{
long[] cc = (long[]) c;
return cc[cc.length-1];
}
}
@Override public String toString(){
return "Dir("+leftEdgeInc()+"-"+rightEdgeInc()+"-K"+Fun.toString(keys)+", C"+Fun.toString(child)+")";
}
@Override
public void checkStructure(BTreeKeySerializer keyser, Serializer valser) {
super.checkStructure(keyser,valser);
int childLen = child instanceof int[]? ((int[])child).length : ((long[])child).length;
if(keyser!=null && childLen!=keysLen(keyser))
throw new DBException.DataCorruption("bnode has inconsistent lengths");
if((isRightEdge() != (next()==0)))
throw new DBException.DataCorruption("bnode right edge inconsistent with link");
}
@Override
public DirNode copyAddKey(BTreeKeySerializer keyser, Serializer valser, int pos, Object newKey, long newChild, Object newValue) {
Object keys2 = keyser.putKey(keys, pos - leftEdgeInc(), newKey);
Object child2;
//expand children and put new child
if(child instanceof int[]) {
int[] child_ = (int[]) child;
if (newChild < Integer.MAX_VALUE) {
//operate on ints
final int[] child2_ = Arrays.copyOf(child_, child_.length + 1);
child2 = child2_;
if (pos < child_.length) {
System.arraycopy(child_, pos, child2_, pos + 1, child_.length - pos);
}
child2_[pos] = (int) newChild;
} else {
//new child does not fit, must upgrade to long[]
long[] child2_ = new long[child_.length + 1];
child2 = child2_;
for (int i = 0; i < pos; i++) {
child2_[i] = child_[i];
}
child2_[pos] = newChild;
for (int i = pos + 1; i < child2_.length; i++) {
child2_[i] = child_[pos - 1];
}
}
}else {
long[] child_ = (long[]) child;
//operate on ints
final long[] child2_ = Arrays.copyOf(child_, child_.length + 1);
child2 = child2_;
if (pos < child_.length) {
System.arraycopy(child_, pos, child2_, pos + 1, child_.length - pos);
}
child2_[pos] = (int) newChild;
}
//$DELAY$
return new DirNode(keys2, isLeftEdge(),isRightEdge(),false,child2);
}
@Override
public DirNode copySplitRight(BTreeKeySerializer keyser, Serializer valser, int splitPos) {
int keylen = keyser.length(keys);
Object keys2 = keyser.copyOfRange(keys,splitPos-leftEdgeInc(),keylen);
//$DELAY$
Object child2;
if(child instanceof int[]){
int[] child_ = (int[]) child;
child2 = Arrays.copyOfRange(child_, splitPos, child_.length);
}else{
long[] child_ = (long[]) child;
child2 = Arrays.copyOfRange(child_, splitPos, child_.length);
}
//$DELAY$
return new DirNode(keys2,false,isRightEdge(),false,child2);
}
@Override
public DirNode copySplitLeft(BTreeKeySerializer keyser, Serializer valser, int splitPos, long newNext) {
Object keys2 = keyser.copyOfRange(keys, 0, splitPos + 1 - leftEdgeInc());
Object child2;
boolean intArrayInstance = child instanceof int[];
if(intArrayInstance){
int[] child_ = (int[]) child;
if(newNext<Integer.MAX_VALUE) {
//all fits operate on int[]
int[] child2_ = Arrays.copyOf(child_, splitPos + 1);
child2_[splitPos] = (int) newNext;
child2 = child2_;
}else{
//does not fit, upgrade to long
long[] child2_ = new long[splitPos+1];
for(int i=0;i<=splitPos;i++){
child2_[i] = child_[i];
}
child2_[splitPos] = newNext;
child2 = child2_;
}
}else{
long[] child2_ = Arrays.copyOf((long[])child, splitPos+1);
child2_[splitPos] = (int) newNext;
child2 = child2_;
}
return new DirNode(keys2,isLeftEdge(),false,false,child2);
}
@Override
public int valSize(Serializer valueSerializer) {
throw new UnsupportedOperationException("dirnode");
}
}
public final static class LeafNode extends BNode{
final Object vals;
final long next;
LeafNode(Object keys, boolean leftEdge, boolean rightEdge, boolean tooLarge, Object vals, long next) {
super(keys,leftEdge, rightEdge, tooLarge);
this.vals = vals;
this.next = next;
if(CC.ASSERT)
checkStructure(null,null);
}
@Override public boolean isLeaf() { return true;}
@Override public Object val(int pos, Serializer valueSerializer){
return valueSerializer.valueArrayGet(vals, pos);
}
@Override public byte[] childArray() { return null;}
@Override public long child(int i){throw new UnsupportedOperationException();}
@Override public long next() {return next;}
@Override public String toString(){
String valsStr = Fun.toString(vals); //TODO use value serializer to turn this into string
return "Leaf("+leftEdgeInc()+"-"+rightEdgeInc()+"-"+"K"+Fun.toString(keys)+", V"+valsStr+", L="+next+")";
}
@Override
public void checkStructure(BTreeKeySerializer keyser, Serializer valser) {
super.checkStructure(keyser,valser);
if((next==0)!=isRightEdge()){
throw new DBException.DataCorruption("Next link inconsistent: "+this);
}
if(valser==null)
return;
int valsSize = valser.valueArraySize(vals);
if(keyser!=null && (keysLen(keyser) != valsSize+2)) {
throw new DBException.DataCorruption("Inconsistent vals size: " + this);
}
//$DELAY$
for (int i=0;i<valsSize;i++) {
Object val = valser.valueArrayGet(vals,i);
if (val == null)
throw new DBException.DataCorruption("Val is null: " + this);
}
}
@Override
public LeafNode copyAddKey(BTreeKeySerializer keyser, Serializer valser, int pos, Object newKey, long newChild, Object newValue) {
Object keys2 = keyser.putKey(keys, pos - leftEdgeInc(), newKey);
//$DELAY$
Object vals2 = valser.valueArrayPut(vals,pos-1,newValue);
//$DELAY$
return new LeafNode(keys2, isLeftEdge(), isRightEdge(), false, vals2,next);
}
@Override
public LeafNode copySplitRight(BTreeKeySerializer keyser, Serializer valser, int splitPos) {
int keylen = keyser.length(keys);
Object keys2 = keyser.copyOfRange(keys, splitPos - leftEdgeInc(), keylen);
//$DELAY$
Object vals2 = valser.valueArrayCopyOfRange(vals, splitPos, valser.valueArraySize(vals));
//$DELAY$
return new LeafNode(keys2,false, isRightEdge(), false, vals2, next);
}
@Override
public LeafNode copySplitLeft(BTreeKeySerializer keyser, Serializer valser, int splitPos, long newNext) {
int keypos =splitPos+1-leftEdgeInc();
Object keys2 = keyser.copyOfRange(keys,0,keypos);
//clone end value
Object endkey = keyser.getKey(keys2, keypos - 1);
keys2 = keyser.putKey(keys2,keypos,endkey);
//$DELAY$
Object vals2 = valser.valueArrayCopyOfRange(vals, 0, splitPos);
//$DELAY$
//TODO check high/low keys overlap
return new LeafNode(keys2, isLeftEdge(), false, false, vals2, newNext);
}
@Override
public int valSize(Serializer valueSerializer) {
return valueSerializer.valueArraySize(vals);
}
@Override
public int childArrayLength() {
return -1;
}
public LeafNode copyChangeValue(Serializer valser, int pos, Object value) {
Object vals2 = valser.valueArrayUpdateVal(vals, pos - 1, value);
//$DELAY$
return new LeafNode(keys, isLeftEdge(), isRightEdge(), false, vals2, next);
}
public LeafNode copyRemoveKey(BTreeKeySerializer keyser, Serializer valser, int pos) {
int keyPos = pos -leftEdgeInc();
Object keys2 = keyser.deleteKey(keys,keyPos);
//$DELAY$
Object vals2 = valser.valueArrayDeleteValue(vals,pos);
//$DELAY$
return new LeafNode(keys2, isLeftEdge(), isRightEdge(), false, vals2, next);
}
public LeafNode copyClear(BTreeKeySerializer keyser, Serializer valser) {
Object[] keys2 = new Object[2-leftEdgeInc()-rightEdgeInc()];
if(!isLeftEdge())
keys2[0] = key(keyser,0);
//$DELAY$
if(!isRightEdge())
keys2[1-leftEdgeInc()] = highKey(keyser);
//$DELAY$
return new LeafNode (keyser.arrayToKeys(keys2), isLeftEdge(), isRightEdge(), false, valser.valueArrayEmpty(), next);
}
}
protected final Serializer<BNode> nodeSerializer;
protected static final class NodeSerializer<A,B> extends Serializer<BNode>{
protected static final int LEAF_MASK = 1<<15;
protected static final int LEFT_SHIFT = 14;
protected static final int LEFT_MASK = 1<< LEFT_SHIFT;
protected static final int RIGHT_SHIFT = 13;
protected static final int RIGHT_MASK = 1<< RIGHT_SHIFT;
protected static final int SIZE_MASK = RIGHT_MASK - 1;
protected final boolean hasValues;
protected final boolean valsOutsideNodes;
protected final BTreeKeySerializer keySerializer;
protected final Serializer<Object> valueSerializer;
protected final int numberOfNodeMetas;
public NodeSerializer(boolean valsOutsideNodes, BTreeKeySerializer keySerializer, Serializer valueSerializer, int numberOfNodeMetas) {
if(keySerializer==null)
throw new NullPointerException("keySerializer not set");
this.hasValues = valueSerializer!=null;
this.valsOutsideNodes = valsOutsideNodes;
this.keySerializer = keySerializer;
this.valueSerializer = (Serializer) (hasValues?
(valsOutsideNodes? new ValRefSerializer() : valueSerializer):
Serializer.BOOLEAN);
this.numberOfNodeMetas = numberOfNodeMetas;
}
@Override
public void serialize(DataOutput out, BNode value) throws IOException {
final boolean isLeaf = value.isLeaf();
//check node integrity in paranoid mode
if(CC.ASSERT){
value.checkStructure(keySerializer,valueSerializer);
}
//$DELAY$
final int header =
(isLeaf ? LEAF_MASK : 0) |
(value.isLeftEdge() ? LEFT_MASK : 0) |
(value.isRightEdge() ? RIGHT_MASK : 0) |
value.keysLen(keySerializer);
out.writeShort(header);
//$DELAY$
//write node metas, right now this is ignored, but in future it could be used for counted btrees or aggregations
for(int i=0;i<numberOfNodeMetas;i++){
DataIO.packLong(out,0);
}
//$DELAY$
//longs go first, so it is possible to reconstruct tree without serializer
if(isLeaf){
DataIO.packLong(out, ((LeafNode) value).next);
}else{
serializeChildArray(out, value.childArray());
}
if(keySerializer.length(value.keys)>0)
keySerializer.serialize(out,value.keys);
//$DELAY$
if(isLeaf){
valueSerializer.valueArraySerialize(out,((LeafNode)value).vals);
}
}
protected void serializeChildArray(DataOutput out, Object childArray) throws IOException {
if(childArray instanceof int[]){
int[] cc = (int[]) childArray;
DataIO.packLong(out, (((long)cc[0]) << 1) | 1L); //pack first value mixed with int flag
for(int i=1;i<cc.length;i++){
DataIO.packInt(out,cc[i]);
}
}else{
long[] cc = (long[]) childArray;
DataIO.packLong(out, (cc[0]<<1) | 0); //pack first value mixed with int flag
for(int i=1;i<cc.length;i++) {
DataIO.packLong(out, cc[i]);
}
}
}
@Override
public BNode deserialize(DataInput in, int available) throws IOException {
final int header = in.readUnsignedShort();
final int size = header & SIZE_MASK;
//read node metas, right now this is ignored, but in future it could be used for counted btrees or aggregations
for(int i=0;i<numberOfNodeMetas;i++){
DataIO.unpackLong(in);
}
//$DELAY$
//first bite indicates leaf
final boolean isLeaf = ((header& LEAF_MASK) != 0);
final int left = (header& LEFT_MASK) >>LEFT_SHIFT;
final int right = (header& RIGHT_MASK) >>RIGHT_SHIFT;
DataIO.DataInputInternal in2 = (DataIO.DataInputInternal) in; //TODO fallback option if cast fails
BNode node;
if(isLeaf){
node = deserializeLeaf(in2, size, left, right);
}else{
node = deserializeDir(in2, size, left, right);
}
//$DELAY$
if(CC.ASSERT){
node.checkStructure(keySerializer,valueSerializer);
}
return node;
}
private BNode deserializeDir(final DataIO.DataInputInternal in, final int size, final int left, final int right) throws IOException {
Object child;
long firstChild = in.unpackLong();
if((firstChild&1) == 0){
//deserialize as long[]
long[] child_ = new long[size];
child = child_;
child_[0] = firstChild>>>1;
in.unpackLongArray(child_,1,size);
}else{
//deserialize as long[]
int[] child_ = new int[size];
child = child_;
child_[0] = (int) (firstChild>>>1);
in.unpackIntArray(child_,1,size);
}
int keysize = size - left- right;
//$DELAY$
final Object keys = keysize==0?
keySerializer.emptyKeys():
keySerializer.deserialize(in, keysize);
//$DELAY$
return new DirNode(keys, left!=0, right!=0, false ,child);
}
private BNode deserializeLeaf(final DataIO.DataInputInternal in, final int size, final int left, final int right) throws IOException {
final long next = in.unpackLong();
int keysize = size - left- right;
//$DELAY$
final Object keys = keysize==0?
keySerializer.emptyKeys():
keySerializer.deserialize(in, keysize);
//$DELAY$
Object vals = valueSerializer.valueArrayDeserialize(in,size-2);
return new LeafNode(keys, left!=0, right!=0, false , vals, next);
}
@Override
public boolean isTrusted() {
return keySerializer.isTrusted() && valueSerializer.isTrusted();
}
}
/** Constructor used to create new BTreeMap.
*
* @param engine used for persistence
* @param closeEngine if this object was created without DB. If true shutdown everything on close method, otherwise DB takes care of shutdown
* @param rootRecidRef reference to root recid
* @param maxNodeSize maximal BTree Node size. Node will split if number of entries is higher
* @param valsOutsideNodes Store Values outside of BTree Nodes in separate record?
* @param counterRecid recid under which {@code Atomic.Long} is stored, or {@code 0} for no counter
* @param keySerializer Serializer used for keys. May be null for default value.
* @param valueSerializer Serializer used for values. May be null for default value
* @param numberOfNodeMetas number of meta records associated with each BTree node
*/
public BTreeMap(
Engine engine,
boolean closeEngine,
long rootRecidRef,
int maxNodeSize,
boolean valsOutsideNodes,
long counterRecid,
BTreeKeySerializer keySerializer,
final Serializer<V> valueSerializer,
int numberOfNodeMetas
) {
this.closeEngine = closeEngine;
if(maxNodeSize%2!=0)
throw new IllegalArgumentException("maxNodeSize must be dividable by 2");
if(maxNodeSize<6)
throw new IllegalArgumentException("maxNodeSize too low");
if((maxNodeSize& NodeSerializer.SIZE_MASK) !=maxNodeSize)
throw new IllegalArgumentException("maxNodeSize too high");
if(rootRecidRef<=0||counterRecid<0 || numberOfNodeMetas<0)
throw new IllegalArgumentException();
if(keySerializer==null)
throw new NullPointerException();
this.rootRecidRef = rootRecidRef;
this.hasValues = valueSerializer!=null;
this.valsOutsideNodes = valsOutsideNodes;
this.engine = engine;
this.maxNodeSize = maxNodeSize;
this.numberOfNodeMetas = numberOfNodeMetas;
this.keySerializer = keySerializer;
this.valueSerializer = valueSerializer!=null? valueSerializer: (Serializer<V>) Serializer.BOOLEAN;
entrySet = new EntrySet(this, this.valueSerializer);
this.nodeSerializer = new NodeSerializer(valsOutsideNodes,keySerializer,valueSerializer,numberOfNodeMetas);
this.keySet = new KeySet(this, hasValues);
//$DELAY$
if(counterRecid!=0){
this.counter = new Atomic.Long(engine,counterRecid);
Bind.size(this,counter);
}else{
this.counter = null;
}
//load left edge refs
ArrayList leftEdges2 = new ArrayList<Long>();
long r = engine.get(rootRecidRef,Serializer.RECID);
for(;;){
if(CC.ASSERT && r<=0)
throw new DBException.DataCorruption("wrong recid");
//$DELAY$
BNode n= engine.get(r,nodeSerializer);
leftEdges2.add(r);
if(n.isLeaf())
break;
r = n.child(0);
}
//$DELAY$
Collections.reverse(leftEdges2);
leftEdges = Collections.synchronizedList(leftEdges2);
}
/* creates empty root node and returns recid of its reference*/
static protected long createRootRef(Engine engine, BTreeKeySerializer keySer, Serializer valueSer, int numberOfNodeMetas){
Object emptyArray = valueSer!=null?
valueSer.valueArrayEmpty():
Serializer.BOOLEAN.valueArrayEmpty();
final LeafNode emptyRoot = new LeafNode(keySer.emptyKeys(), true,true, false,emptyArray, 0);
//empty root is serializer simpler way, so we can use dummy values
long rootRecidVal = engine.put(emptyRoot, new NodeSerializer(false,keySer, valueSer, numberOfNodeMetas));
return engine.put(rootRecidVal,Serializer.RECID);
}
@Override
public V get(Object key){
return (V) get(key, true);
}
protected Object get(Object key, boolean expandValue) {
if(key==null) throw new NullPointerException();
K v = (K) key;
long current = engine.get(rootRecidRef, Serializer.RECID); //get root
//$DELAY$
BNode A = engine.get(current, nodeSerializer);
//dive until leaf
while(!A.isLeaf()){
//$DELAY$
current = nextDir((DirNode) A, v);
//$DELAY$
A = engine.get(current, nodeSerializer);
}
for(;;) {
int pos = keySerializer.findChildren2(A, key);
//$DELAY$
if (pos > 0 && pos != A.keysLen(keySerializer) - 1) {
//found
Object val = A.val(pos - 1,valueSerializer);
//$DELAY$
if(expandValue)
val = valExpand(val);
return val;
} else if (pos <= 0 && -pos - 1 != A.keysLen(keySerializer) - 1) {
//$DELAY$
//not found
return null;
} else {
//move to next link
current = A.next();
//$DELAY$
if (current == 0) {
return null;
}
A = engine.get(current, nodeSerializer);
}
}
}