-
Notifications
You must be signed in to change notification settings - Fork 465
/
block.go
2052 lines (1916 loc) · 75.9 KB
/
block.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 2018 The LevelDB-Go and Pebble 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 sstable
import (
"context"
"encoding/binary"
"unsafe"
"github.com/cockroachdb/errors"
"github.com/cockroachdb/pebble/internal/base"
"github.com/cockroachdb/pebble/internal/invariants"
"github.com/cockroachdb/pebble/internal/keyspan"
"github.com/cockroachdb/pebble/internal/manual"
"github.com/cockroachdb/pebble/internal/rangedel"
"github.com/cockroachdb/pebble/internal/rangekey"
)
func uvarintLen(v uint32) int {
i := 0
for v >= 0x80 {
v >>= 7
i++
}
return i + 1
}
type blockWriter struct {
restartInterval int
nEntries int
nextRestart int
buf []byte
// For datablocks in TableFormatPebblev3, we steal the most significant bit
// in restarts for encoding setHasSameKeyPrefixSinceLastRestart. This leaves
// us with 31 bits, which is more than enough (no one needs > 2GB blocks).
// Typically, restarts occur every 16 keys, and by storing this bit with the
// restart, we can optimize for the case where a user wants to skip to the
// next prefix which happens to be in the same data block, but is > 16 keys
// away. We have seen production situations with 100+ versions per MVCC key
// (which share the same prefix). Additionally, for such writers, the prefix
// compression of the key, that shares the key with the preceding key, is
// limited to the prefix part of the preceding key -- this ensures that when
// doing NPrefix (see blockIter) we don't need to assemble the full key
// for each step since by limiting the length of the shared key we are
// ensuring that any of the keys with the same prefix can be used to
// assemble the full key when the prefix does change.
restarts []uint32
// Do not read curKey directly from outside blockWriter since it can have
// the InternalKeyKindSSTableInternalObsoleteBit set. Use getCurKey() or
// getCurUserKey() instead.
curKey []byte
// curValue excludes the optional prefix provided to
// storeWithOptionalValuePrefix.
curValue []byte
prevKey []byte
tmp [4]byte
// We don't know the state of the sets that were at the end of the previous
// block, so this is initially 0. It may be true for the second and later
// restarts in a block. Not having inter-block information is fine since we
// will optimize by stepping through restarts only within the same block.
// Note that the first restart is the first key in the block.
setHasSameKeyPrefixSinceLastRestart bool
}
func (w *blockWriter) clear() {
*w = blockWriter{
buf: w.buf[:0],
restarts: w.restarts[:0],
curKey: w.curKey[:0],
curValue: w.curValue[:0],
prevKey: w.prevKey[:0],
}
}
// MaximumBlockSize is an extremely generous maximum block size of 256MiB. We
// explicitly place this limit to reserve a few bits in the restart for
// internal use.
const MaximumBlockSize = 1 << 28
const setHasSameKeyPrefixRestartMask uint32 = 1 << 31
const restartMaskLittleEndianHighByteWithoutSetHasSamePrefix byte = 0b0111_1111
const restartMaskLittleEndianHighByteOnlySetHasSamePrefix byte = 0b1000_0000
func (w *blockWriter) getCurKey() InternalKey {
k := base.DecodeInternalKey(w.curKey)
k.Trailer = k.Trailer & trailerObsoleteMask
return k
}
func (w *blockWriter) getCurUserKey() []byte {
n := len(w.curKey) - base.InternalTrailerLen
if n < 0 {
panic(errors.AssertionFailedf("corrupt key in blockWriter buffer"))
}
return w.curKey[:n:n]
}
// If !addValuePrefix, the valuePrefix is ignored.
func (w *blockWriter) storeWithOptionalValuePrefix(
keySize int,
value []byte,
maxSharedKeyLen int,
addValuePrefix bool,
valuePrefix valuePrefix,
setHasSameKeyPrefix bool,
) {
shared := 0
if !setHasSameKeyPrefix {
w.setHasSameKeyPrefixSinceLastRestart = false
}
if w.nEntries == w.nextRestart {
w.nextRestart = w.nEntries + w.restartInterval
restart := uint32(len(w.buf))
if w.setHasSameKeyPrefixSinceLastRestart {
restart = restart | setHasSameKeyPrefixRestartMask
}
w.setHasSameKeyPrefixSinceLastRestart = true
w.restarts = append(w.restarts, restart)
} else {
// TODO(peter): Manually inlined version of base.SharedPrefixLen(). This
// is 3% faster on BenchmarkWriter on go1.16. Remove if future versions
// show this to not be a performance win. For now, functions that use of
// unsafe cannot be inlined.
n := maxSharedKeyLen
if n > len(w.prevKey) {
n = len(w.prevKey)
}
asUint64 := func(b []byte, i int) uint64 {
return binary.LittleEndian.Uint64(b[i:])
}
for shared < n-7 && asUint64(w.curKey, shared) == asUint64(w.prevKey, shared) {
shared += 8
}
for shared < n && w.curKey[shared] == w.prevKey[shared] {
shared++
}
}
lenValuePlusOptionalPrefix := len(value)
if addValuePrefix {
lenValuePlusOptionalPrefix++
}
needed := 3*binary.MaxVarintLen32 + len(w.curKey[shared:]) + lenValuePlusOptionalPrefix
n := len(w.buf)
if cap(w.buf) < n+needed {
newCap := 2 * cap(w.buf)
if newCap == 0 {
newCap = 1024
}
for newCap < n+needed {
newCap *= 2
}
newBuf := make([]byte, n, newCap)
copy(newBuf, w.buf)
w.buf = newBuf
}
w.buf = w.buf[:n+needed]
// TODO(peter): Manually inlined versions of binary.PutUvarint(). This is 15%
// faster on BenchmarkWriter on go1.13. Remove if go1.14 or future versions
// show this to not be a performance win.
{
x := uint32(shared)
for x >= 0x80 {
w.buf[n] = byte(x) | 0x80
x >>= 7
n++
}
w.buf[n] = byte(x)
n++
}
{
x := uint32(keySize - shared)
for x >= 0x80 {
w.buf[n] = byte(x) | 0x80
x >>= 7
n++
}
w.buf[n] = byte(x)
n++
}
{
x := uint32(lenValuePlusOptionalPrefix)
for x >= 0x80 {
w.buf[n] = byte(x) | 0x80
x >>= 7
n++
}
w.buf[n] = byte(x)
n++
}
n += copy(w.buf[n:], w.curKey[shared:])
if addValuePrefix {
w.buf[n : n+1][0] = byte(valuePrefix)
n++
}
n += copy(w.buf[n:], value)
w.buf = w.buf[:n]
w.curValue = w.buf[n-len(value):]
w.nEntries++
}
func (w *blockWriter) add(key InternalKey, value []byte) {
w.addWithOptionalValuePrefix(
key, false, value, len(key.UserKey), false, 0, false)
}
// Callers that always set addValuePrefix to false should use add() instead.
//
// isObsolete indicates whether this key-value pair is obsolete in this
// sstable (only applicable when writing data blocks) -- see the comment in
// table.go and the longer one in format.go. addValuePrefix adds a 1 byte
// prefix to the value, specified in valuePrefix -- this is used for data
// blocks in TableFormatPebblev3 onwards for SETs (see the comment in
// format.go, with more details in value_block.go). setHasSameKeyPrefix is
// also used in TableFormatPebblev3 onwards for SETs.
func (w *blockWriter) addWithOptionalValuePrefix(
key InternalKey,
isObsolete bool,
value []byte,
maxSharedKeyLen int,
addValuePrefix bool,
valuePrefix valuePrefix,
setHasSameKeyPrefix bool,
) {
w.curKey, w.prevKey = w.prevKey, w.curKey
size := key.Size()
if cap(w.curKey) < size {
w.curKey = make([]byte, 0, size*2)
}
w.curKey = w.curKey[:size]
if isObsolete {
key.Trailer = key.Trailer | trailerObsoleteBit
}
key.Encode(w.curKey)
w.storeWithOptionalValuePrefix(
size, value, maxSharedKeyLen, addValuePrefix, valuePrefix, setHasSameKeyPrefix)
}
func (w *blockWriter) finish() []byte {
// Write the restart points to the buffer.
if w.nEntries == 0 {
// Every block must have at least one restart point.
if cap(w.restarts) > 0 {
w.restarts = w.restarts[:1]
w.restarts[0] = 0
} else {
w.restarts = append(w.restarts, 0)
}
}
tmp4 := w.tmp[:4]
for _, x := range w.restarts {
binary.LittleEndian.PutUint32(tmp4, x)
w.buf = append(w.buf, tmp4...)
}
binary.LittleEndian.PutUint32(tmp4, uint32(len(w.restarts)))
w.buf = append(w.buf, tmp4...)
result := w.buf
// Reset the block state.
w.nEntries = 0
w.nextRestart = 0
w.buf = w.buf[:0]
w.restarts = w.restarts[:0]
return result
}
// emptyBlockSize holds the size of an empty block. Every block ends
// in a uint32 trailer encoding the number of restart points within the
// block.
const emptyBlockSize = 4
func (w *blockWriter) estimatedSize() int {
return len(w.buf) + 4*len(w.restarts) + emptyBlockSize
}
type blockEntry struct {
offset int32
keyStart int32
keyEnd int32
valStart int32
valSize int32
}
// blockIter is an iterator over a single block of data.
//
// A blockIter provides an additional guarantee around key stability when a
// block has a restart interval of 1 (i.e. when there is no prefix
// compression). Key stability refers to whether the InternalKey.UserKey bytes
// returned by a positioning call will remain stable after a subsequent
// positioning call. The normal case is that a positioning call will invalidate
// any previously returned InternalKey.UserKey. If a block has a restart
// interval of 1 (no prefix compression), blockIter guarantees that
// InternalKey.UserKey will point to the key as stored in the block itself
// which will remain valid until the blockIter is closed. The key stability
// guarantee is used by the range tombstone and range key code, which knows that
// the respective blocks are always encoded with a restart interval of 1. This
// per-block key stability guarantee is sufficient for range tombstones and
// range deletes as they are always encoded in a single block. Note: this
// stability guarantee no longer holds for a block iter with synthetic suffix
// replacement, but this doesn't matter, as the user will not open
// an iterator with a synthetic suffix on a block with rangekeys (for now).
//
// A blockIter also provides a value stability guarantee for range deletions and
// range keys since there is only a single range deletion and range key block
// per sstable and the blockIter will not release the bytes for the block until
// it is closed.
//
// Note on why blockIter knows about lazyValueHandling:
//
// blockIter's positioning functions (that return a LazyValue), are too
// complex to inline even prior to lazyValueHandling. blockIter.Next and
// blockIter.First were by far the cheapest and had costs 195 and 180
// respectively, which exceeds the budget of 80. We initially tried to keep
// the lazyValueHandling logic out of blockIter by wrapping it with a
// lazyValueDataBlockIter. singleLevelIter and twoLevelIter would use this
// wrapped iter. The functions in lazyValueDataBlockIter were simple, in that
// they called the corresponding blockIter func and then decided whether the
// value was in fact in-place (so return immediately) or needed further
// handling. But these also turned out too costly for mid-stack inlining since
// simple calls like the following have a high cost that is barely under the
// budget of 80
//
// k, v := i.data.SeekGE(key, flags) // cost 74
// k, v := i.data.Next() // cost 72
//
// We have 2 options for minimizing performance regressions:
// - Include the lazyValueHandling logic in the already non-inlineable
// blockIter functions: Since most of the time is spent in data block iters,
// it is acceptable to take the small hit of unnecessary branching (which
// hopefully branch prediction will predict correctly) for other kinds of
// blocks.
// - Duplicate the logic of singleLevelIterator and twoLevelIterator for the
// v3 sstable and only use the aforementioned lazyValueDataBlockIter for a
// v3 sstable. We would want to manage these copies via code generation.
//
// We have picked the first option here.
type blockIter struct {
cmp Compare
split Split
// offset is the byte index that marks where the current key/value is
// encoded in the block.
offset int32
// nextOffset is the byte index where the next key/value is encoded in the
// block.
nextOffset int32
// A "restart point" in a block is a point where the full key is encoded,
// instead of just having a suffix of the key encoded. See readEntry() for
// how prefix compression of keys works. Keys in between two restart points
// only have a suffix encoded in the block. When restart interval is 1, no
// prefix compression of keys happens. This is the case with range tombstone
// blocks.
//
// All restart offsets are listed in increasing order in
// i.ptr[i.restarts:len(block)-4], while numRestarts is encoded in the last
// 4 bytes of the block as a uint32 (i.ptr[len(block)-4:]). i.restarts can
// therefore be seen as the point where data in the block ends, and a list
// of offsets of all restart points begins.
restarts int32
// Number of restart points in this block. Encoded at the end of the block
// as a uint32.
numRestarts int32
globalSeqNum uint64
ptr unsafe.Pointer
data []byte
// key contains the raw key the iterator is currently pointed at. This may
// point directly to data stored in the block (for a key which has no prefix
// compression), to fullKey (for a prefix compressed key), or to a slice of
// data stored in cachedBuf (during reverse iteration).
//
// NB: In general, key contains the same logical content as ikey
// (i.e. ikey = decode(key)), but if the iterator contains a synthetic suffix
// replacement rule, this will not be the case. Therefore, key should never
// be used after ikey is set.
key []byte
// fullKey is a buffer used for key prefix decompression.
fullKey []byte
// val contains the value the iterator is currently pointed at. If non-nil,
// this points to a slice of the block data.
val []byte
// lazyValue is val turned into a LazyValue, whenever a positioning method
// returns a non-nil key-value pair.
lazyValue base.LazyValue
// ikey contains the decoded InternalKey the iterator is currently pointed
// at. Note that the memory backing ikey.UserKey is either data stored
// directly in the block, fullKey, cachedBuf, or synthSuffixBuf. The key
// stability guarantee for blocks built with a restart interval of 1 is
// achieved by having ikey.UserKey always point to data stored directly in the
// block.
ikey InternalKey
// cached and cachedBuf are used during reverse iteration. They are needed
// because we can't perform prefix decoding in reverse, only in the forward
// direction. In order to iterate in reverse, we decode and cache the entries
// between two restart points.
//
// Note that cached[len(cached)-1] contains the previous entry to the one the
// blockIter is currently pointed at. As usual, nextOffset will contain the
// offset of the next entry. During reverse iteration, nextOffset will be
// updated to point to offset, and we'll set the blockIter to point at the
// entry cached[len(cached)-1]. See Prev() for more details.
//
// For a block encoded with a restart interval of 1, cached and cachedBuf
// will not be used as there are no prefix compressed entries between the
// restart points.
cached []blockEntry
cachedBuf []byte
handle bufferHandle
// for block iteration for already loaded blocks.
firstUserKey []byte
lazyValueHandling struct {
vbr *valueBlockReader
hasValuePrefix bool
}
hideObsoletePoints bool
// syntheticSuffix, if not nil, will replace the decoded ikey.UserKey suffix
// before the key is returned to the user. A sequence of iter operations on a
// block with a syntheticSuffix rule should return keys as if those operations
// ran on a block with keys that all had the syntheticSuffix. As an example:
// any sequence of block iter cmds should return the same keys for the
// following two blocks:
//
// blockA: a@3,b@3,c@3
// blockB: a@1,b@2,c@1 with syntheticSuffix=3
//
// To ensure this, Suffix replacement will not change the ordering of keys in
// the block because the iter assumes the following about the block:
//
// (1) no two keys in the block share the same prefix.
// (2) pebble.Compare(keyPrefix{replacementSuffix},keyPrefix{originalSuffix}) < 0
//
// In addition, we also assume that any block with rangekeys will not contain
// a synthetic suffix.
syntheticSuffix SyntheticSuffix
synthSuffixBuf []byte
}
// blockIter implements the base.InternalIterator interface.
var _ base.InternalIterator = (*blockIter)(nil)
func newBlockIter(
cmp Compare, split Split, block block, syntheticSuffix SyntheticSuffix,
) (*blockIter, error) {
i := &blockIter{}
return i, i.init(cmp, split, block, 0, false, syntheticSuffix)
}
func (i *blockIter) String() string {
return "block"
}
func (i *blockIter) init(
cmp Compare,
split Split,
block block,
globalSeqNum uint64,
hideObsoletePoints bool,
syntheticSuffix SyntheticSuffix,
) error {
numRestarts := int32(binary.LittleEndian.Uint32(block[len(block)-4:]))
if numRestarts == 0 {
return base.CorruptionErrorf("pebble/table: invalid table (block has no restart points)")
}
i.syntheticSuffix = syntheticSuffix
i.synthSuffixBuf = i.synthSuffixBuf[:0]
i.split = split
i.cmp = cmp
i.restarts = int32(len(block)) - 4*(1+numRestarts)
i.numRestarts = numRestarts
i.globalSeqNum = globalSeqNum
i.ptr = unsafe.Pointer(&block[0])
i.data = block
i.fullKey = i.fullKey[:0]
i.val = nil
i.hideObsoletePoints = hideObsoletePoints
i.clearCache()
if i.restarts > 0 {
if err := i.readFirstKey(); err != nil {
return err
}
} else {
// Block is empty.
i.firstUserKey = nil
}
return nil
}
// NB: two cases of hideObsoletePoints:
// - Local sstable iteration: globalSeqNum will be set iff the sstable was
// ingested.
// - Foreign sstable iteration: globalSeqNum is always set.
func (i *blockIter) initHandle(
cmp Compare,
split Split,
block bufferHandle,
globalSeqNum uint64,
hideObsoletePoints bool,
syntheticSuffix SyntheticSuffix,
) error {
i.handle.Release()
i.handle = block
return i.init(cmp, split, block.Get(), globalSeqNum, hideObsoletePoints, syntheticSuffix)
}
func (i *blockIter) invalidate() {
i.clearCache()
i.offset = 0
i.nextOffset = 0
i.restarts = 0
i.numRestarts = 0
i.data = nil
}
// isDataInvalidated returns true when the blockIter has been invalidated
// using an invalidate call. NB: this is different from blockIter.Valid
// which is part of the InternalIterator implementation.
func (i *blockIter) isDataInvalidated() bool {
return i.data == nil
}
func (i *blockIter) resetForReuse() blockIter {
return blockIter{
fullKey: i.fullKey[:0],
cached: i.cached[:0],
cachedBuf: i.cachedBuf[:0],
data: nil,
}
}
func (i *blockIter) readEntry() {
ptr := unsafe.Pointer(uintptr(i.ptr) + uintptr(i.offset))
// This is an ugly performance hack. Reading entries from blocks is one of
// the inner-most routines and decoding the 3 varints per-entry takes
// significant time. Neither go1.11 or go1.12 will inline decodeVarint for
// us, so we do it manually. This provides a 10-15% performance improvement
// on blockIter benchmarks on both go1.11 and go1.12.
//
// TODO(peter): remove this hack if go:inline is ever supported.
var shared uint32
if a := *((*uint8)(ptr)); a < 128 {
shared = uint32(a)
ptr = unsafe.Pointer(uintptr(ptr) + 1)
} else if a, b := a&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 1))); b < 128 {
shared = uint32(b)<<7 | uint32(a)
ptr = unsafe.Pointer(uintptr(ptr) + 2)
} else if b, c := b&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 2))); c < 128 {
shared = uint32(c)<<14 | uint32(b)<<7 | uint32(a)
ptr = unsafe.Pointer(uintptr(ptr) + 3)
} else if c, d := c&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 3))); d < 128 {
shared = uint32(d)<<21 | uint32(c)<<14 | uint32(b)<<7 | uint32(a)
ptr = unsafe.Pointer(uintptr(ptr) + 4)
} else {
d, e := d&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 4)))
shared = uint32(e)<<28 | uint32(d)<<21 | uint32(c)<<14 | uint32(b)<<7 | uint32(a)
ptr = unsafe.Pointer(uintptr(ptr) + 5)
}
var unshared uint32
if a := *((*uint8)(ptr)); a < 128 {
unshared = uint32(a)
ptr = unsafe.Pointer(uintptr(ptr) + 1)
} else if a, b := a&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 1))); b < 128 {
unshared = uint32(b)<<7 | uint32(a)
ptr = unsafe.Pointer(uintptr(ptr) + 2)
} else if b, c := b&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 2))); c < 128 {
unshared = uint32(c)<<14 | uint32(b)<<7 | uint32(a)
ptr = unsafe.Pointer(uintptr(ptr) + 3)
} else if c, d := c&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 3))); d < 128 {
unshared = uint32(d)<<21 | uint32(c)<<14 | uint32(b)<<7 | uint32(a)
ptr = unsafe.Pointer(uintptr(ptr) + 4)
} else {
d, e := d&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 4)))
unshared = uint32(e)<<28 | uint32(d)<<21 | uint32(c)<<14 | uint32(b)<<7 | uint32(a)
ptr = unsafe.Pointer(uintptr(ptr) + 5)
}
var value uint32
if a := *((*uint8)(ptr)); a < 128 {
value = uint32(a)
ptr = unsafe.Pointer(uintptr(ptr) + 1)
} else if a, b := a&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 1))); b < 128 {
value = uint32(b)<<7 | uint32(a)
ptr = unsafe.Pointer(uintptr(ptr) + 2)
} else if b, c := b&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 2))); c < 128 {
value = uint32(c)<<14 | uint32(b)<<7 | uint32(a)
ptr = unsafe.Pointer(uintptr(ptr) + 3)
} else if c, d := c&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 3))); d < 128 {
value = uint32(d)<<21 | uint32(c)<<14 | uint32(b)<<7 | uint32(a)
ptr = unsafe.Pointer(uintptr(ptr) + 4)
} else {
d, e := d&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 4)))
value = uint32(e)<<28 | uint32(d)<<21 | uint32(c)<<14 | uint32(b)<<7 | uint32(a)
ptr = unsafe.Pointer(uintptr(ptr) + 5)
}
unsharedKey := getBytes(ptr, int(unshared))
// TODO(sumeer): move this into the else block below.
i.fullKey = append(i.fullKey[:shared], unsharedKey...)
if shared == 0 {
// Provide stability for the key across positioning calls if the key
// doesn't share a prefix with the previous key. This removes requiring the
// key to be copied if the caller knows the block has a restart interval of
// 1. An important example of this is range-del blocks.
i.key = unsharedKey
} else {
i.key = i.fullKey
}
ptr = unsafe.Pointer(uintptr(ptr) + uintptr(unshared))
i.val = getBytes(ptr, int(value))
i.nextOffset = int32(uintptr(ptr)-uintptr(i.ptr)) + int32(value)
}
func (i *blockIter) readFirstKey() error {
ptr := i.ptr
// This is an ugly performance hack. Reading entries from blocks is one of
// the inner-most routines and decoding the 3 varints per-entry takes
// significant time. Neither go1.11 or go1.12 will inline decodeVarint for
// us, so we do it manually. This provides a 10-15% performance improvement
// on blockIter benchmarks on both go1.11 and go1.12.
//
// TODO(peter): remove this hack if go:inline is ever supported.
if shared := *((*uint8)(ptr)); shared == 0 {
ptr = unsafe.Pointer(uintptr(ptr) + 1)
} else {
// The shared length is != 0, which is invalid.
panic("first key in block must have zero shared length")
}
var unshared uint32
if a := *((*uint8)(ptr)); a < 128 {
unshared = uint32(a)
ptr = unsafe.Pointer(uintptr(ptr) + 1)
} else if a, b := a&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 1))); b < 128 {
unshared = uint32(b)<<7 | uint32(a)
ptr = unsafe.Pointer(uintptr(ptr) + 2)
} else if b, c := b&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 2))); c < 128 {
unshared = uint32(c)<<14 | uint32(b)<<7 | uint32(a)
ptr = unsafe.Pointer(uintptr(ptr) + 3)
} else if c, d := c&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 3))); d < 128 {
unshared = uint32(d)<<21 | uint32(c)<<14 | uint32(b)<<7 | uint32(a)
ptr = unsafe.Pointer(uintptr(ptr) + 4)
} else {
d, e := d&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 4)))
unshared = uint32(e)<<28 | uint32(d)<<21 | uint32(c)<<14 | uint32(b)<<7 | uint32(a)
ptr = unsafe.Pointer(uintptr(ptr) + 5)
}
// Skip the value length.
if a := *((*uint8)(ptr)); a < 128 {
ptr = unsafe.Pointer(uintptr(ptr) + 1)
} else if a := *((*uint8)(unsafe.Pointer(uintptr(ptr) + 1))); a < 128 {
ptr = unsafe.Pointer(uintptr(ptr) + 2)
} else if a := *((*uint8)(unsafe.Pointer(uintptr(ptr) + 2))); a < 128 {
ptr = unsafe.Pointer(uintptr(ptr) + 3)
} else if a := *((*uint8)(unsafe.Pointer(uintptr(ptr) + 3))); a < 128 {
ptr = unsafe.Pointer(uintptr(ptr) + 4)
} else {
ptr = unsafe.Pointer(uintptr(ptr) + 5)
}
firstKey := getBytes(ptr, int(unshared))
// Manually inlining base.DecodeInternalKey provides a 5-10% speedup on
// BlockIter benchmarks.
if n := len(firstKey) - 8; n >= 0 {
i.firstUserKey = firstKey[:n:n]
} else {
i.firstUserKey = nil
return base.CorruptionErrorf("pebble/table: invalid firstKey in block")
}
return nil
}
// The sstable internal obsolete bit is set when writing a block and unset by
// blockIter, so no code outside block writing/reading code ever sees it.
const trailerObsoleteBit = uint64(base.InternalKeyKindSSTableInternalObsoleteBit)
const trailerObsoleteMask = (InternalKeySeqNumMax << 8) | uint64(base.InternalKeyKindSSTableInternalObsoleteMask)
func (i *blockIter) decodeInternalKey(key []byte) (hiddenPoint bool) {
// Manually inlining base.DecodeInternalKey provides a 5-10% speedup on
// BlockIter benchmarks.
if n := len(key) - 8; n >= 0 {
trailer := binary.LittleEndian.Uint64(key[n:])
hiddenPoint = i.hideObsoletePoints &&
(trailer&trailerObsoleteBit != 0)
i.ikey.Trailer = trailer & trailerObsoleteMask
i.ikey.UserKey = key[:n:n]
if i.globalSeqNum != 0 {
i.ikey.SetSeqNum(i.globalSeqNum)
}
} else {
i.ikey.Trailer = uint64(InternalKeyKindInvalid)
i.ikey.UserKey = nil
}
return hiddenPoint
}
// maybeReplaceSuffix replaces the suffix in i.ikey.UserKey with
// i.syntheticSuffix. allowInPlace is set to false if there's a chance that
// i.ikey.UserKey points to the same buffer as i.cachedBuf (i.e. during reverse
// iteration).
func (i *blockIter) maybeReplaceSuffix(allowInPlace bool) {
if i.syntheticSuffix != nil && i.ikey.UserKey != nil {
prefixLen := i.split(i.ikey.UserKey)
if allowInPlace && cap(i.ikey.UserKey) >= prefixLen+len(i.syntheticSuffix) {
i.ikey.UserKey = append(i.ikey.UserKey[:prefixLen], i.syntheticSuffix...)
return
}
// If ikey is cached or may get cached, we must copy
// UserKey to a new buffer before prefix replacement.
i.synthSuffixBuf = append(i.synthSuffixBuf[:0], i.ikey.UserKey[:prefixLen]...)
i.synthSuffixBuf = append(i.synthSuffixBuf, i.syntheticSuffix...)
i.ikey.UserKey = i.synthSuffixBuf
}
}
func (i *blockIter) clearCache() {
i.cached = i.cached[:0]
i.cachedBuf = i.cachedBuf[:0]
}
func (i *blockIter) cacheEntry() {
var valStart int32
valSize := int32(len(i.val))
if valSize > 0 {
valStart = int32(uintptr(unsafe.Pointer(&i.val[0])) - uintptr(i.ptr))
}
i.cached = append(i.cached, blockEntry{
offset: i.offset,
keyStart: int32(len(i.cachedBuf)),
keyEnd: int32(len(i.cachedBuf) + len(i.key)),
valStart: valStart,
valSize: valSize,
})
i.cachedBuf = append(i.cachedBuf, i.key...)
}
func (i *blockIter) getFirstUserKey() []byte {
return i.firstUserKey
}
// SeekGE implements internalIterator.SeekGE, as documented in the pebble
// package.
func (i *blockIter) SeekGE(key []byte, flags base.SeekGEFlags) (*InternalKey, base.LazyValue) {
if invariants.Enabled && i.isDataInvalidated() {
panic(errors.AssertionFailedf("invalidated blockIter used"))
}
i.clearCache()
// Find the index of the smallest restart point whose key is > the key
// sought; index will be numRestarts if there is no such restart point.
i.offset = 0
var index int32
{
// NB: manually inlined sort.Seach is ~5% faster.
//
// Define f(-1) == false and f(n) == true.
// Invariant: f(index-1) == false, f(upper) == true.
upper := i.numRestarts
for index < upper {
h := int32(uint(index+upper) >> 1) // avoid overflow when computing h
// index ≤ h < upper
offset := decodeRestart(i.data[i.restarts+4*h:])
// For a restart point, there are 0 bytes shared with the previous key.
// The varint encoding of 0 occupies 1 byte.
ptr := unsafe.Pointer(uintptr(i.ptr) + uintptr(offset+1))
// Decode the key at that restart point, and compare it to the key
// sought. See the comment in readEntry for why we manually inline the
// varint decoding.
var v1 uint32
if a := *((*uint8)(ptr)); a < 128 {
v1 = uint32(a)
ptr = unsafe.Pointer(uintptr(ptr) + 1)
} else if a, b := a&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 1))); b < 128 {
v1 = uint32(b)<<7 | uint32(a)
ptr = unsafe.Pointer(uintptr(ptr) + 2)
} else if b, c := b&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 2))); c < 128 {
v1 = uint32(c)<<14 | uint32(b)<<7 | uint32(a)
ptr = unsafe.Pointer(uintptr(ptr) + 3)
} else if c, d := c&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 3))); d < 128 {
v1 = uint32(d)<<21 | uint32(c)<<14 | uint32(b)<<7 | uint32(a)
ptr = unsafe.Pointer(uintptr(ptr) + 4)
} else {
d, e := d&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 4)))
v1 = uint32(e)<<28 | uint32(d)<<21 | uint32(c)<<14 | uint32(b)<<7 | uint32(a)
ptr = unsafe.Pointer(uintptr(ptr) + 5)
}
if *((*uint8)(ptr)) < 128 {
ptr = unsafe.Pointer(uintptr(ptr) + 1)
} else if *((*uint8)(unsafe.Pointer(uintptr(ptr) + 1))) < 128 {
ptr = unsafe.Pointer(uintptr(ptr) + 2)
} else if *((*uint8)(unsafe.Pointer(uintptr(ptr) + 2))) < 128 {
ptr = unsafe.Pointer(uintptr(ptr) + 3)
} else if *((*uint8)(unsafe.Pointer(uintptr(ptr) + 3))) < 128 {
ptr = unsafe.Pointer(uintptr(ptr) + 4)
} else {
ptr = unsafe.Pointer(uintptr(ptr) + 5)
}
// Manually inlining part of base.DecodeInternalKey provides a 5-10%
// speedup on BlockIter benchmarks.
s := getBytes(ptr, int(v1))
var k []byte
if n := len(s) - 8; n >= 0 {
k = s[:n:n]
}
// Else k is invalid, and left as nil
if i.cmp(key, k) > 0 {
// The search key is greater than the user key at this restart point.
// Search beyond this restart point, since we are trying to find the
// first restart point with a user key >= the search key.
index = h + 1 // preserves f(i-1) == false
} else {
// k >= search key, so prune everything after index (since index
// satisfies the property we are looking for).
upper = h // preserves f(j) == true
}
}
// index == upper, f(index-1) == false, and f(upper) (= f(index)) == true
// => answer is index.
}
// index is the first restart point with key >= search key. Define the keys
// between a restart point and the next restart point as belonging to that
// restart point.
//
// Since keys are strictly increasing, if index > 0 then the restart point
// at index-1 will be the first one that has some keys belonging to it that
// could be equal to the search key. If index == 0, then all keys in this
// block are larger than the key sought, and offset remains at zero.
if index > 0 {
i.offset = decodeRestart(i.data[i.restarts+4*(index-1):])
}
i.readEntry()
hiddenPoint := i.decodeInternalKey(i.key)
// Iterate from that restart point to somewhere >= the key sought.
if !i.valid() {
return nil, base.LazyValue{}
}
// A note on seeking in a block with a suffix replacement rule: even though
// the binary search above was conducted on keys without suffix replacement,
// Seek will still return the correct suffix replaced key. A binary
// search without suffix replacement will land on a key that is _less_ than
// the key the search would have landed on if all keys were already suffix
// replaced. Since Seek then conducts forward iteration to the first suffix
// replaced user key that is greater than or equal to the search key, the
// correct key is still returned.
//
// As an example, consider the following block with a restart interval of 1,
// with a replacement suffix of "4":
// - Pre-suffix replacement: apple@1, banana@3
// - Post-suffix replacement: apple@4, banana@4
//
// Suppose the client seeks with apple@3. Assuming suffixes sort in reverse
// chronological order (i.e. apple@1>apple@3), the binary search without
// suffix replacement would return apple@1. A binary search with suffix
// replacement would return banana@4. After beginning forward iteration from
// either returned restart point, forward iteration would
// always return the correct key, banana@4.
//
// Further, if the user searched with apple@0 (i.e. a suffix less than the
// pre replacement suffix) or with apple@5 (a suffix larger than the post
// replacement suffix), the binary search with or without suffix replacement
// would land on the same key, as we assume the following:
// (1) no two keys in the sst share the same prefix.
// (2) pebble.Compare(replacementSuffix,originalSuffix) > 0
i.maybeReplaceSuffix(true /*allowInPlace*/)
if !hiddenPoint && i.cmp(i.ikey.UserKey, key) >= 0 {
// Initialize i.lazyValue
if !i.lazyValueHandling.hasValuePrefix ||
base.TrailerKind(i.ikey.Trailer) != InternalKeyKindSet {
i.lazyValue = base.MakeInPlaceValue(i.val)
} else if i.lazyValueHandling.vbr == nil || !isValueHandle(valuePrefix(i.val[0])) {
i.lazyValue = base.MakeInPlaceValue(i.val[1:])
} else {
i.lazyValue = i.lazyValueHandling.vbr.getLazyValueForPrefixAndValueHandle(i.val)
}
return &i.ikey, i.lazyValue
}
for i.Next(); i.valid(); i.Next() {
if i.cmp(i.ikey.UserKey, key) >= 0 {
// i.Next() has already initialized i.lazyValue.
return &i.ikey, i.lazyValue
}
}
return nil, base.LazyValue{}
}
// SeekPrefixGE implements internalIterator.SeekPrefixGE, as documented in the
// pebble package.
func (i *blockIter) SeekPrefixGE(
prefix, key []byte, flags base.SeekGEFlags,
) (*base.InternalKey, base.LazyValue) {
// This should never be called as prefix iteration is handled by sstable.Iterator.
panic("pebble: SeekPrefixGE unimplemented")
}
// SeekLT implements internalIterator.SeekLT, as documented in the pebble
// package.
func (i *blockIter) SeekLT(key []byte, flags base.SeekLTFlags) (*InternalKey, base.LazyValue) {
if invariants.Enabled && i.isDataInvalidated() {
panic(errors.AssertionFailedf("invalidated blockIter used"))
}
i.clearCache()
// Find the index of the smallest restart point whose key is >= the key
// sought; index will be numRestarts if there is no such restart point.
i.offset = 0
var index int32
{
// NB: manually inlined sort.Search is ~5% faster.
//
// Define f(-1) == false and f(n) == true.
// Invariant: f(index-1) == false, f(upper) == true.
upper := i.numRestarts
for index < upper {
h := int32(uint(index+upper) >> 1) // avoid overflow when computing h
// index ≤ h < upper
offset := decodeRestart(i.data[i.restarts+4*h:])
// For a restart point, there are 0 bytes shared with the previous key.
// The varint encoding of 0 occupies 1 byte.
ptr := unsafe.Pointer(uintptr(i.ptr) + uintptr(offset+1))
// Decode the key at that restart point, and compare it to the key
// sought. See the comment in readEntry for why we manually inline the
// varint decoding.
var v1 uint32
if a := *((*uint8)(ptr)); a < 128 {
v1 = uint32(a)
ptr = unsafe.Pointer(uintptr(ptr) + 1)
} else if a, b := a&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 1))); b < 128 {
v1 = uint32(b)<<7 | uint32(a)
ptr = unsafe.Pointer(uintptr(ptr) + 2)
} else if b, c := b&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 2))); c < 128 {
v1 = uint32(c)<<14 | uint32(b)<<7 | uint32(a)
ptr = unsafe.Pointer(uintptr(ptr) + 3)
} else if c, d := c&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 3))); d < 128 {
v1 = uint32(d)<<21 | uint32(c)<<14 | uint32(b)<<7 | uint32(a)
ptr = unsafe.Pointer(uintptr(ptr) + 4)
} else {
d, e := d&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 4)))
v1 = uint32(e)<<28 | uint32(d)<<21 | uint32(c)<<14 | uint32(b)<<7 | uint32(a)
ptr = unsafe.Pointer(uintptr(ptr) + 5)
}
if *((*uint8)(ptr)) < 128 {
ptr = unsafe.Pointer(uintptr(ptr) + 1)
} else if *((*uint8)(unsafe.Pointer(uintptr(ptr) + 1))) < 128 {
ptr = unsafe.Pointer(uintptr(ptr) + 2)
} else if *((*uint8)(unsafe.Pointer(uintptr(ptr) + 2))) < 128 {
ptr = unsafe.Pointer(uintptr(ptr) + 3)
} else if *((*uint8)(unsafe.Pointer(uintptr(ptr) + 3))) < 128 {
ptr = unsafe.Pointer(uintptr(ptr) + 4)
} else {
ptr = unsafe.Pointer(uintptr(ptr) + 5)
}
// Manually inlining part of base.DecodeInternalKey provides a 5-10%
// speedup on BlockIter benchmarks.
s := getBytes(ptr, int(v1))
var k []byte
if n := len(s) - 8; n >= 0 {
k = s[:n:n]
}
// Else k is invalid, and left as nil
if i.cmp(key, k) > 0 {
// The search key is greater than the user key at this restart point.
// Search beyond this restart point, since we are trying to find the
// first restart point with a user key >= the search key.
index = h + 1 // preserves f(i-1) == false
} else {
// k >= search key, so prune everything after index (since index
// satisfies the property we are looking for).
upper = h // preserves f(j) == true
}
}
// index == upper, f(index-1) == false, and f(upper) (= f(index)) == true
// => answer is index.