forked from perkeep/perkeep
/
btree.go
2276 lines (1916 loc) · 50.2 KB
/
btree.go
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 2014 The lldb Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package lldb
import (
"bytes"
"errors"
"fmt"
"io"
"sort"
"strings"
"camlistore.org/third_party/github.com/cznic/bufs"
"camlistore.org/third_party/github.com/cznic/fileutil"
"camlistore.org/third_party/github.com/cznic/sortutil"
)
const (
kData = 256 // [1, 512]
kIndex = 256 // [2, 2048]
kKV = 19 // Size of the key/value field in btreeDataPage
kSz = kKV - 1 - 7 // Content prefix size
kH = kKV - 7 // Content field offset for handle
tagBTreeDataPage = 1
tagBTreeIndexPage = 0
)
// BTree is a B+tree[1][2], i.e. a variant which speeds up
// enumeration/iteration of the BTree. According to its origin it can be
// volatile (backed only by memory) or non-volatile (backed by a non-volatile
// Allocator).
//
// The specific implementation of BTrees in this package are B+trees with
// delayed split/concatenation (discussed in e.g. [3]).
//
// Note: No BTree methods returns io.EOF for physical Filer reads/writes. The
// io.EOF is returned only by bTreeEnumerator methods to indicate "no more K-V
// pair".
//
// [1]: http://en.wikipedia.org/wiki/B+tree
// [2]: http://zgking.com:8080/home/donghui/publications/books/dshandbook_BTree.pdf
// [3]: http://people.cs.aau.dk/~simas/aalg06/UbiquitBtree.pdf
type BTree struct {
store btreeStore
root btree
collate func(a, b []byte) int
serial uint64
}
// NewBTree returns a new, memory-only BTree.
func NewBTree(collate func(a, b []byte) int) *BTree {
store := newMemBTreeStore()
root, err := newBTree(store)
if err != nil { // should not happen
panic(err.Error())
}
return &BTree{store, root, collate, 0}
}
// IsMem reports if t is a memory only BTree.
func (t *BTree) IsMem() (r bool) {
_, r = t.store.(*memBTreeStore)
return
}
// Clear empties the tree.
func (t *BTree) Clear() (err error) {
if t == nil {
err = errors.New("BTree method invoked on nil receiver")
return
}
t.serial++
return t.root.clear(t.store)
}
// Delete deletes key and its associated value from the tree.
func (t *BTree) Delete(key []byte) (err error) {
if t == nil {
err = errors.New("BTree method invoked on nil receiver")
return
}
t.serial++
_, err = t.root.extract(t.store, nil, t.collate, key)
return
}
// DeleteAny deletes one key and its associated value from the tree. If the
// tree is empty on return then empty is true.
func (t *BTree) DeleteAny() (empty bool, err error) {
if t == nil {
err = errors.New("BTree method invoked on nil receiver")
return
}
t.serial++
return t.root.deleteAny(t.store)
}
func elem(v interface{}) string {
switch x := v.(type) {
default:
panic("internal error")
case nil:
return "nil"
case bool:
if x {
return "true"
}
return "false"
case int64:
return fmt.Sprint(x)
case uint64:
return fmt.Sprint(x)
case float64:
s := fmt.Sprintf("%g", x)
if !strings.Contains(s, ".") {
s += "."
}
return s
case complex128:
s := fmt.Sprint(x)
return s[1 : len(s)-1]
case []byte:
return fmt.Sprintf("[]byte{% 02x}", x)
case string:
return fmt.Sprintf("%q", x)
}
}
// Dump outputs a human readable dump of t to w. It is usable iff t keys and
// values are encoded scalars (see EncodeScalars). Intended use is only for
// examples or debugging. Some type information is lost in the rendering, for
// example a float value '17.' and an integer value '17' may both output as
// '17'.
func (t *BTree) Dump(w io.Writer) (err error) {
enum, err := t.seekFirst()
if err != nil {
return
}
for {
bkey, bval, err := enum.current()
if err != nil {
return err
}
key, err := DecodeScalars(bkey)
if err != nil {
return err
}
val, err := DecodeScalars(bval)
if err != nil {
return err
}
kk := []string{}
if key == nil {
kk = []string{"null"}
}
for _, v := range key {
kk = append(kk, elem(v))
}
vv := []string{}
if val == nil {
vv = []string{"null"}
}
for _, v := range val {
vv = append(vv, elem(v))
}
skey := strings.Join(kk, ", ")
sval := strings.Join(vv, ", ")
if len(vv) > 1 {
sval = fmt.Sprintf("[]interface{%s}", sval)
}
if _, err = fmt.Fprintf(w, "%s → %s\n", skey, sval); err != nil {
return err
}
err = enum.next()
if err != nil {
if fileutil.IsEOF(err) {
err = nil
break
}
return err
}
}
return
}
// Extract is a combination of Get and Delete. If the key exists in the tree,
// it is returned (like Get) and also deleted from a tree in a more efficient
// way which doesn't walk it twice. The returned slice may be a sub-slice of
// buf if buf was large enough to hold the entire content. Otherwise, a newly
// allocated slice will be returned. It is valid to pass a nil buf.
func (t *BTree) Extract(buf, key []byte) (value []byte, err error) {
if t == nil {
err = errors.New("BTree method invoked on nil receiver")
return
}
t.serial++
return t.root.extract(t.store, buf, t.collate, key)
}
// First returns the first KV pair of the tree, if it exists. Otherwise key == nil
// and value == nil.
func (t *BTree) First() (key, value []byte, err error) {
if t == nil {
err = errors.New("BTree method invoked on nil receiver")
return
}
var p btreeDataPage
if _, p, err = t.root.first(t.store); err != nil || p == nil {
return
}
if key, err = p.key(t.store, 0); err != nil {
return
}
value, err = p.value(t.store, 0)
return
}
// Get returns the value associated with key, or nil if no such value exists.
// The returned slice may be a sub-slice of buf if buf was large enough to hold
// the entire content. Otherwise, a newly allocated slice will be returned.
// It is valid to pass a nil buf.
func (t *BTree) Get(buf, key []byte) (value []byte, err error) {
if t == nil {
err = errors.New("BTree method invoked on nil receiver")
return
}
buffer := bufs.GCache.Get(maxBuf)
defer bufs.GCache.Put(buffer)
if buffer, err = t.root.get(t.store, buffer, t.collate, key); buffer == nil || err != nil {
return
}
value = need(len(buffer), buf)
copy(value, buffer)
return
}
// Handle reports t's handle.
func (t *BTree) Handle() int64 {
return int64(t.root)
}
// Last returns the last KV pair of the tree, if it exists. Otherwise key == nil
// and value == nil.
func (t *BTree) Last() (key, value []byte, err error) {
if t == nil {
err = errors.New("BTree method invoked on nil receiver")
return
}
var p btreeDataPage
if _, p, err = t.root.last(t.store); err != nil || p == nil {
return
}
index := p.len() - 1
if key, err = p.key(t.store, index); err != nil {
return
}
value, err = p.value(t.store, index)
return
}
// Put combines Get and Set in a more efficient way where the tree is walked
// only once. The upd(ater) receives the current (key, old-value), if that
// exists or (key, nil) otherwise. It can then return a (new-value, true, nil)
// to create or overwrite the existing value in the KV pair, or (whatever,
// false, nil) if it decides not to create or not to update the value of the KV
// pair.
//
// tree.Set(k, v)
//
// conceptually equals
//
// tree.Put(k, func(k, v []byte){ return v, true }([]byte, bool))
//
// modulo the differing return values.
//
// The returned slice may be a sub-slice of buf if buf was large enough to hold
// the entire content. Otherwise, a newly allocated slice will be returned.
// It is valid to pass a nil buf.
func (t *BTree) Put(buf, key []byte, upd func(key, old []byte) (new []byte, write bool, err error)) (old []byte, written bool, err error) {
if t == nil {
err = errors.New("BTree method invoked on nil receiver")
return
}
t.serial++
return t.root.put2(buf, t.store, t.collate, key, upd)
}
// Seek returns an Enumerator with "position" or an error of any. Normally the
// position is on a KV pair such that key >= KV.key. Then hit is key == KV.key.
// The position is possibly "after" the last KV pair, but that is not an error.
func (t *BTree) Seek(key []byte) (enum *BTreeEnumerator, hit bool, err error) {
enum0, hit, err := t.seek(key)
if err != nil {
return
}
enum = &BTreeEnumerator{
enum: enum0,
firstHit: hit,
key: append([]byte(nil), key...),
}
return
}
func (t *BTree) seek(key []byte) (enum *bTreeEnumerator, hit bool, err error) {
if t == nil {
err = errors.New("BTree method invoked on nil receiver")
return
}
r := &bTreeEnumerator{t: t, collate: t.collate, serial: t.serial}
if r.p, r.index, hit, err = t.root.seek(t.store, r.collate, key); err != nil {
return
}
enum = r
return
}
// IndexSeek returns an Enumerator with "position" or an error of any. Normally
// the position is on a KV pair such that key >= KV.key. Then hit is key ==
// KV.key. The position is possibly "after" the last KV pair, but that is not
// an error. The collate function originally passed to CreateBTree is used for
// enumerating the tree but a custom collate function c is used for IndexSeek.
func (t *BTree) IndexSeek(key []byte, c func(a, b []byte) int) (enum *BTreeEnumerator, hit bool, err error) { //TODO +test
enum0, hit, err := t.indexSeek(key, c)
if err != nil {
return
}
enum = &BTreeEnumerator{
enum: enum0,
firstHit: hit,
key: append([]byte(nil), key...),
}
return
}
func (t *BTree) indexSeek(key []byte, c func(a, b []byte) int) (enum *bTreeEnumerator, hit bool, err error) {
if t == nil {
err = errors.New("BTree method invoked on nil receiver")
return
}
r := &bTreeEnumerator{t: t, collate: t.collate, serial: t.serial}
if r.p, r.index, hit, err = t.root.seek(t.store, c, key); err != nil {
return
}
enum = r
return
}
// seekFirst returns an enumerator positioned on the first KV pair in the tree,
// if any. For an empty tree, err == io.EOF is returend.
func (t *BTree) SeekFirst() (enum *BTreeEnumerator, err error) {
enum0, err := t.seekFirst()
if err != nil {
return
}
var key []byte
if key, _, err = enum0.current(); err != nil {
return
}
enum = &BTreeEnumerator{
enum: enum0,
firstHit: true,
key: append([]byte(nil), key...),
}
return
}
func (t *BTree) seekFirst() (enum *bTreeEnumerator, err error) {
if t == nil {
err = errors.New("BTree method invoked on nil receiver")
return
}
var p btreeDataPage
if _, p, err = t.root.first(t.store); err == nil && p == nil {
err = io.EOF
}
if err != nil {
return
}
return &bTreeEnumerator{t: t, collate: t.collate, p: p, index: 0, serial: t.serial}, nil
}
// seekLast returns an enumerator positioned on the last KV pair in the tree,
// if any. For an empty tree, err == io.EOF is returend.
func (t *BTree) SeekLast() (enum *BTreeEnumerator, err error) {
enum0, err := t.seekLast()
if err != nil {
return
}
var key []byte
if key, _, err = enum0.current(); err != nil {
return
}
enum = &BTreeEnumerator{
enum: enum0,
firstHit: true,
key: append([]byte(nil), key...),
}
return
}
func (t *BTree) seekLast() (enum *bTreeEnumerator, err error) {
if t == nil {
err = errors.New("BTree method invoked on nil receiver")
return
}
var p btreeDataPage
if _, p, err = t.root.last(t.store); err == nil && p == nil {
err = io.EOF
}
if err != nil {
return
}
return &bTreeEnumerator{t: t, collate: t.collate, p: p, index: p.len() - 1, serial: t.serial}, nil
}
// Set sets the value associated with key. Any previous value, if existed, is
// overwritten by the new one.
func (t *BTree) Set(key, value []byte) (err error) {
if t == nil {
err = errors.New("BTree method invoked on nil receiver")
return
}
t.serial++
dst := bufs.GCache.Get(maxBuf)
_, err = t.root.put(dst, t.store, t.collate, key, value, true)
bufs.GCache.Put(dst)
return
}
// bTreeEnumerator is a closure of a BTree and a position. It is returned from
// BTree.seek.
//
// NOTE: bTreeEnumerator cannot be used after its BTree was mutated after the
// bTreeEnumerator was acquired from any of the seek, seekFirst, seekLast
// methods.
type bTreeEnumerator struct {
t *BTree
collate func(a, b []byte) int
p btreeDataPage
index int
serial uint64
}
// Current returns the KV pair the enumerator is currently positioned on. If
// the position is before the first KV pair in the tree or after the last KV
// pair in the tree then err == io.EOF is returned.
//
// If the enumerator has been invalidated by updating the tree, ErrINVAL is
// returned.
func (e *bTreeEnumerator) current() (key, value []byte, err error) {
if e == nil {
err = errors.New("bTreeEnumerator method invoked on nil receiver")
return
}
if e.serial != e.t.serial {
err = &ErrINVAL{Src: "bTreeEnumerator invalidated by updating the tree"}
return
}
if e.p == nil || e.index == e.p.len() {
return nil, nil, io.EOF
}
if key, err = e.p.key(e.t.store, e.index); err != nil {
return
}
value, err = e.p.value(e.t.store, e.index)
return
}
// Next attempts to position the enumerator onto the next KV pair wrt the
// current position. If there is no "next" KV pair, io.EOF is returned.
//
// If the enumerator has been invalidated by updating the tree, ErrINVAL is
// returned.
func (e *bTreeEnumerator) next() (err error) {
if e == nil {
err = errors.New("bTreeEnumerator method invoked on nil receiver")
return
}
if e.serial != e.t.serial {
err = &ErrINVAL{Src: "bTreeEnumerator invalidated by updating the tree"}
return
}
if e.p == nil {
return io.EOF
}
switch {
case e.index < e.p.len()-1:
e.index++
default:
ph := e.p.next()
if ph == 0 {
err = io.EOF
break
}
if e.p, err = e.t.store.Get(e.p, ph); err != nil {
e.p = nil
return
}
e.index = 0
}
return
}
// Prev attempts to position the enumerator onto the previous KV pair wrt the
// current position. If there is no "previous" KV pair, io.EOF is returned.
//
// If the enumerator has been invalidated by updating the tree, ErrINVAL is
// returned.
func (e *bTreeEnumerator) prev() (err error) {
if e == nil {
err = errors.New("bTreeEnumerator method invoked on nil receiver")
return
}
if e.serial != e.t.serial {
err = &ErrINVAL{Src: "bTreeEnumerator invalidated by updating the tree"}
return
}
if e.p == nil {
return io.EOF
}
switch {
case e.index > 0:
e.index--
default:
ph := e.p.prev()
if ph == 0 {
err = io.EOF
break
}
if e.p, err = e.t.store.Get(e.p, ph); err != nil {
e.p = nil
return
}
e.index = e.p.len() - 1
}
return
}
// BTreeEnumerator captures the state of enumerating a tree. It is returned
// from the Seek* methods. The enumerator is aware of any mutations made to
// the tree in the process of enumerating it and automatically resumes the
// enumeration.
type BTreeEnumerator struct {
enum *bTreeEnumerator
err error
key []byte
firstHit bool
}
// Next returns the currently enumerated KV pair, if it exists and moves to the
// next KV in the key collation order. If there is no KV pair to return, err ==
// io.EOF is returned.
func (e *BTreeEnumerator) Next() (key, value []byte, err error) {
if err = e.err; err != nil {
return
}
canRetry := true
retry:
if key, value, err = e.enum.current(); err != nil {
if _, ok := err.(*ErrINVAL); !ok || !canRetry {
e.err = err
return
}
canRetry = false
var hit bool
if e.enum, hit, err = e.enum.t.seek(e.key); err != nil {
e.err = err
return
}
if !e.firstHit && hit {
err = e.enum.next()
if err != nil {
e.err = err
return
}
}
goto retry
}
e.firstHit = false
e.key = append([]byte(nil), key...)
e.err = e.enum.next()
return
}
// Prev returns the currently enumerated KV pair, if it exists and moves to the
// previous KV in the key collation order. If there is no KV pair to return,
// err == io.EOF is returned.
func (e *BTreeEnumerator) Prev() (key, value []byte, err error) {
if err = e.err; err != nil {
return
}
canRetry := true
retry:
if key, value, err = e.enum.current(); err != nil {
if _, ok := err.(*ErrINVAL); !ok || !canRetry {
e.err = err
return
}
canRetry = false
var hit bool
if e.enum, hit, err = e.enum.t.seek(e.key); err != nil {
e.err = err
return
}
if !e.firstHit && hit {
err = e.enum.prev()
if err != nil {
e.err = err
return
}
}
goto retry
}
e.firstHit = false
e.key = append([]byte(nil), key...)
e.err = e.enum.prev()
return
}
// CreateBTree creates a new BTree in store. It returns the tree, its (freshly
// assigned) handle (for OpenBTree or RemoveBTree) or an error, if any.
func CreateBTree(store *Allocator, collate func(a, b []byte) int) (bt *BTree, handle int64, err error) {
r := &BTree{store: store, collate: collate}
if r.root, err = newBTree(store); err != nil {
return
}
return r, int64(r.root), nil
}
// OpenBTree opens a store's BTree using handle. It returns the tree or an
// error, if any. The same tree may be opened more than once, but operations on
// the separate instances should not ever overlap or void the other instances.
// However, the intended API usage is to open the same tree handle only once
// (handled by some upper layer "dispatcher").
func OpenBTree(store *Allocator, collate func(a, b []byte) int, handle int64) (bt *BTree, err error) {
r := &BTree{store: store, root: btree(handle), collate: collate}
b := bufs.GCache.Get(7)
defer bufs.GCache.Put(b)
if b, err = store.Get(b, handle); err != nil {
return
}
if len(b) != 7 {
return nil, &ErrILSEQ{Off: h2off(handle), More: "btree.go:671"}
}
return r, nil
}
// RemoveBTree removes tree, represented by handle from store. Empty trees are
// cheap, each uses only few bytes of the store. If there's a chance that a
// tree will eventually get reused (non empty again), it's recommended to
// not/never remove it. One advantage of such approach is a stable handle of
// such tree.
func RemoveBTree(store *Allocator, handle int64) (err error) {
tree, err := OpenBTree(store, nil, handle)
if err != nil {
return
}
if err = tree.Clear(); err != nil {
return
}
return store.Free(handle)
}
type btreeStore interface {
Alloc(b []byte) (handle int64, err error)
Free(handle int64) (err error)
Get(dst []byte, handle int64) (b []byte, err error)
Realloc(handle int64, b []byte) (err error)
}
// Read only zero bytes
var zeros [2 * kKV]byte
func init() {
if kData < 1 || kData > 512 {
panic(fmt.Errorf("kData %d: out of limits", kData))
}
if kIndex < 2 || kIndex > 2048 {
panic(fmt.Errorf("kIndex %d: out of limits", kIndex))
}
if kKV < 8 || kKV > 23 {
panic(fmt.Errorf("kKV %d: out of limits", kKV))
}
if n := len(zeros); n < 15 {
panic(fmt.Errorf("not enough zeros: %d", n))
}
}
type memBTreeStore struct {
h int64
m map[int64][]byte
}
func newMemBTreeStore() *memBTreeStore {
return &memBTreeStore{h: 0, m: map[int64][]byte{}}
}
func (s *memBTreeStore) String() string {
var a sortutil.Int64Slice
for k := range s.m {
a = append(a, k)
}
sort.Sort(a)
var sa []string
for _, k := range a {
sa = append(sa, fmt.Sprintf("%#x:|% x|", k, s.m[k]))
}
return strings.Join(sa, "\n")
}
func (s *memBTreeStore) Alloc(b []byte) (handle int64, err error) {
s.h++
handle = s.h
s.m[handle] = bpack(b)
return
}
func (s *memBTreeStore) Free(handle int64) (err error) {
if _, ok := s.m[handle]; !ok {
return &ErrILSEQ{Type: ErrOther, Off: h2off(handle), More: "btree.go:754"}
}
delete(s.m, handle)
return
}
func (s *memBTreeStore) Get(dst []byte, handle int64) (b []byte, err error) {
r, ok := s.m[handle]
if !ok {
return nil, &ErrILSEQ{Type: ErrOther, Off: h2off(handle), More: "btree.go:764"}
}
b = need(len(r), dst)
copy(b, r)
return
}
func (s *memBTreeStore) Realloc(handle int64, b []byte) (err error) {
if _, ok := s.m[handle]; !ok {
return &ErrILSEQ{Type: ErrOther, Off: h2off(handle), More: "btree.go:774"}
}
s.m[handle] = bpack(b)
return
}
/*
0...0 (1 bytes):
Flag
0
+---+
| 0 |
+---+
0 indicates an index page
1...count*14-1
"array" of items, 14 bytes each. Count of items in kIndex-1..2*kIndex+2
Count = (len(raw) - 8) / 14
0..6 7..13
+-------+----------+
| Child | DataPage |
+-------+----------+
Child == handle of a child index page
DataPage == handle of a data page
Offsets into the raw []byte:
Child[X] == 1+14*X
DataPage[X] == 8+14*X
*/
type btreeIndexPage []byte
func newBTreeIndexPage(leftmostChild int64) (p btreeIndexPage) {
p = bufs.GCache.Get(1 + (kIndex+1)*2*7)[:8]
p[0] = tagBTreeIndexPage
h2b(p[1:], leftmostChild)
return
}
func (p btreeIndexPage) len() int {
return (len(p) - 8) / 14
}
func (p btreeIndexPage) child(index int) int64 {
return b2h(p[1+14*index:])
}
func (p btreeIndexPage) setChild(index int, dp int64) {
h2b(p[1+14*index:], dp)
}
func (p btreeIndexPage) dataPage(index int) int64 {
return b2h(p[8+14*index:])
}
func (p btreeIndexPage) setDataPage(index int, dp int64) {
h2b(p[8+14*index:], dp)
}
func (q btreeIndexPage) insert(index int) btreeIndexPage {
switch len0 := q.len(); {
case index < len0:
has := len(q)
need := has + 14
switch {
case cap(q) >= need:
q = q[:need]
default:
q = append(q, zeros[:14]...)
}
copy(q[8+14*(index+1):8+14*(index+1)+2*(len0-index)*7], q[8+14*index:])
case index == len0:
has := len(q)
need := has + 14
switch {
case cap(q) >= need:
q = q[:need]
default:
q = append(q, zeros[:14]...)
}
}
return q
}
func (p btreeIndexPage) insert3(index int, dataPage, child int64) btreeIndexPage {
p = p.insert(index)
p.setDataPage(index, dataPage)
p.setChild(index+1, child)
return p
}
func (p btreeIndexPage) cmp(a btreeStore, c func(a, b []byte) int, keyA []byte, keyBIndex int) (int, error) {
b := bufs.GCache.Get(maxBuf)
defer bufs.GCache.Put(b)
dp, err := a.Get(b, p.dataPage(keyBIndex))
if err != nil {
return 0, err
}
return btreeDataPage(dp).cmp(a, c, keyA, 0)
}
func (q btreeIndexPage) setLen(n int) btreeIndexPage {
q = q[:cap(q)]
need := 8 + 14*n
if need < len(q) {
return q[:need]
}
return append(q, make([]byte, need-len(q))...)
}
func (p btreeIndexPage) split(a btreeStore, root btree, ph *int64, parent int64, parentIndex int, index *int) (btreeIndexPage, error) {
right := newBTreeIndexPage(0)
canRecycle := true
defer func() {
if canRecycle {
bufs.GCache.Put(right)
}
}()
right = right.setLen(kIndex)
copy(right[1:1+(2*kIndex+1)*7], p[1+14*(kIndex+1):])
p = p.setLen(kIndex)
if err := a.Realloc(*ph, p); err != nil {
return nil, err
}
rh, err := a.Alloc(right)
if err != nil {
return nil, err
}
if parentIndex >= 0 {
var pp btreeIndexPage = bufs.GCache.Get(maxBuf)
defer bufs.GCache.Put(pp)
if pp, err = a.Get(pp, parent); err != nil {
return nil, err
}
pp = pp.insert3(parentIndex, p.dataPage(kIndex), rh)
if err = a.Realloc(parent, pp); err != nil {
return nil, err
}
} else {
nr := newBTreeIndexPage(*ph)
defer bufs.GCache.Put(nr)
nr = nr.insert3(0, p.dataPage(kIndex), rh)
nrh, err := a.Alloc(nr)
if err != nil {
return nil, err
}
if err = a.Realloc(int64(root), h2b(make([]byte, 7), nrh)); err != nil {
return nil, err
}
}
if *index > kIndex {
p = right
canRecycle = false
*ph = rh
*index -= kIndex + 1
}
return p, nil
}
// p is dirty on return
func (p btreeIndexPage) extract(index int) btreeIndexPage {
n := p.len() - 1
if index < n {
sz := (n-index)*14 + 7
copy(p[1+14*index:1+14*index+sz], p[1+14*(index+1):])
}
return p.setLen(n)
}
// must persist all changes made
func (p btreeIndexPage) underflow(a btreeStore, root, iroot, parent int64, ph *int64, parentIndex int, index *int) (btreeIndexPage, error) {
lh, rh, err := checkSiblings(a, parent, parentIndex)
if err != nil {
return nil, err
}
var left btreeIndexPage = bufs.GCache.Get(maxBuf)
defer bufs.GCache.Put(left)
if lh != 0 {
if left, err = a.Get(left, lh); err != nil {