LCOV - code coverage report
Current view: top level - pebble/sstable/rowblk - rowblk_iter.go (source / functions) Hit Total Coverage
Test: 2024-11-09 08:16Z b2cb561a - meta test only.lcov Lines: 894 1343 66.6 %
Date: 2024-11-09 08:16:58 Functions: 0 0 -

          Line data    Source code
       1             : // Copyright 2018 The LevelDB-Go and Pebble Authors. All rights reserved. Use
       2             : // of this source code is governed by a BSD-style license that can be found in
       3             : // the LICENSE file.
       4             : 
       5             : package rowblk
       6             : 
       7             : import (
       8             :         "bytes"
       9             :         "context"
      10             :         "encoding/binary"
      11             :         "io"
      12             :         "slices"
      13             :         "sort"
      14             :         "unsafe"
      15             : 
      16             :         "github.com/cockroachdb/errors"
      17             :         "github.com/cockroachdb/pebble/internal/base"
      18             :         "github.com/cockroachdb/pebble/internal/invariants"
      19             :         "github.com/cockroachdb/pebble/internal/manual"
      20             :         "github.com/cockroachdb/pebble/internal/treeprinter"
      21             :         "github.com/cockroachdb/pebble/sstable/block"
      22             : )
      23             : 
      24             : // Iter is an iterator over a single block of data.
      25             : //
      26             : // An Iter provides an additional guarantee around key stability when a block
      27             : // has a restart interval of 1 (i.e. when there is no prefix compression). Key
      28             : // stability refers to whether the InternalKey.UserKey bytes returned by a
      29             : // positioning call will remain stable after a subsequent positioning call. The
      30             : // normal case is that a positioning call will invalidate any previously
      31             : // returned InternalKey.UserKey. If a block has a restart interval of 1 (no
      32             : // prefix compression), Iter guarantees that InternalKey.UserKey will point to
      33             : // the key as stored in the block itself which will remain valid until the Iter
      34             : // is closed. The key stability guarantee is used by the range tombstone and
      35             : // range key code, which knows that the respective blocks are always encoded
      36             : // with a restart interval of 1. This per-block key stability guarantee is
      37             : // sufficient for range tombstones and range deletes as they are always encoded
      38             : // in a single block. Note: this stability guarantee no longer holds for a block
      39             : // iter with synthetic prefix/suffix replacement, but we don't use the synthetic
      40             : // suffix/prefix functionality of Iter for range keys.
      41             : //
      42             : // An Iter also provides a value stability guarantee for range deletions and
      43             : // range keys since there is only a single range deletion and range key block
      44             : // per sstable and the Iter will not release the bytes for the block until it is
      45             : // closed.
      46             : //
      47             : // Note on why Iter knows about lazyValueHandling:
      48             : //
      49             : // Iter's positioning functions (that return a LazyValue), are too
      50             : // complex to inline even prior to lazyValueHandling. Iter.Next and
      51             : // Iter.First were by far the cheapest and had costs 195 and 180
      52             : // respectively, which exceeds the budget of 80. We initially tried to keep
      53             : // the lazyValueHandling logic out of Iter by wrapping it with a
      54             : // lazyValueDataBlockIter. singleLevelIter and twoLevelIter would use this
      55             : // wrapped iter. The functions in lazyValueDataBlockIter were simple, in that
      56             : // they called the corresponding Iter func and then decided whether the
      57             : // value was in fact in-place (so return immediately) or needed further
      58             : // handling. But these also turned out too costly for mid-stack inlining since
      59             : // simple calls like the following have a high cost that is barely under the
      60             : // budget of 80
      61             : //
      62             : //      k, v := i.data.SeekGE(key, flags)  // cost 74
      63             : //      k, v := i.data.Next()              // cost 72
      64             : //
      65             : // We have 2 options for minimizing performance regressions:
      66             : //   - Include the lazyValueHandling logic in the already non-inlineable
      67             : //     Iter functions: Since most of the time is spent in data block iters,
      68             : //     it is acceptable to take the small hit of unnecessary branching (which
      69             : //     hopefully branch prediction will predict correctly) for other kinds of
      70             : //     blocks.
      71             : //   - Duplicate the logic of singleLevelIterator and twoLevelIterator for the
      72             : //     v3 sstable and only use the aforementioned lazyValueDataBlockIter for a
      73             : //     v3 sstable. We would want to manage these copies via code generation.
      74             : //
      75             : // We have picked the first option here.
      76             : type Iter struct {
      77             :         cmp   base.Compare
      78             :         split base.Split
      79             : 
      80             :         // Iterator transforms.
      81             :         //
      82             :         // SyntheticSuffix, if set, will replace the decoded ikey.UserKey suffix
      83             :         // before the key is returned to the user. A sequence of iter operations on a
      84             :         // block with a syntheticSuffix rule should return keys as if those operations
      85             :         // ran on a block with keys that all had the syntheticSuffix. As an example:
      86             :         // any sequence of block iter cmds should return the same keys for the
      87             :         // following two blocks:
      88             :         //
      89             :         // blockA: a@3,b@3,c@3
      90             :         // blockB: a@1,b@2,c@1 with syntheticSuffix=3
      91             :         //
      92             :         // To ensure this, Suffix replacement will not change the ordering of keys in
      93             :         // the block because the iter assumes that no two keys in the block share the
      94             :         // same prefix. Furthermore, during SeekGE and SeekLT operations, the block
      95             :         // iterator handles "off by one" errors (explained in more detail in those
      96             :         // functions) when, for a given key, originalSuffix < searchSuffix <
      97             :         // replacementSuffix, with integer comparison. To handle these cases, the
      98             :         // iterator assumes:
      99             :         //
     100             :         //  pebble.Compare(keyPrefix{replacementSuffix},keyPrefix{originalSuffix}) < 0
     101             :         //  for keys with a suffix.
     102             :         //
     103             :         //  NB: it is possible for a block iter to add a synthetic suffix on a key
     104             :         //  without a suffix, which implies
     105             :         //  pebble.Compare(keyPrefix{replacementSuffix},keyPrefix{noSuffix}) > 0 ,
     106             :         //  however, the iterator would never need to handle an off by one error in
     107             :         //  this case since originalSuffix (empty) > searchSuffix (non empty), with
     108             :         //  integer comparison.
     109             :         //
     110             :         //
     111             :         // In addition, we also assume that any block with rangekeys will not contain
     112             :         // a synthetic suffix.
     113             :         transforms block.IterTransforms
     114             : 
     115             :         // offset is the byte index that marks where the current key/value is
     116             :         // encoded in the block.
     117             :         offset int32
     118             :         // nextOffset is the byte index where the next key/value is encoded in the
     119             :         // block.
     120             :         nextOffset int32
     121             :         // A "restart point" in a block is a point where the full key is encoded,
     122             :         // instead of just having a suffix of the key encoded. See readEntry() for
     123             :         // how prefix compression of keys works. Keys in between two restart points
     124             :         // only have a suffix encoded in the block. When restart interval is 1, no
     125             :         // prefix compression of keys happens. This is the case with range tombstone
     126             :         // blocks.
     127             :         //
     128             :         // All restart offsets are listed in increasing order in
     129             :         // i.ptr[i.restarts:len(block)-4], while numRestarts is encoded in the last
     130             :         // 4 bytes of the block as a uint32 (i.ptr[len(block)-4:]). i.restarts can
     131             :         // therefore be seen as the point where data in the block ends, and a list
     132             :         // of offsets of all restart points begins.
     133             :         restarts int32
     134             :         // Number of restart points in this block. Encoded at the end of the block
     135             :         // as a uint32.
     136             :         numRestarts int32
     137             :         ptr         unsafe.Pointer
     138             :         data        []byte
     139             :         // key contains the raw key the iterator is currently pointed at. This may
     140             :         // point directly to data stored in the block (for a key which has no prefix
     141             :         // compression), to fullKey (for a prefix compressed key), or to a slice of
     142             :         // data stored in cachedBuf (during reverse iteration).
     143             :         //
     144             :         // NB: In general, key contains the same logical content as ikey
     145             :         // (i.e. ikey = decode(key)), but if the iterator contains a synthetic suffix
     146             :         // replacement rule, this will not be the case. Therefore, key should never
     147             :         // be used after ikey is set.
     148             :         key []byte
     149             :         // fullKey is a buffer used for key prefix decompression. Note that if
     150             :         // transforms.SyntheticPrifix is not nil, fullKey always starts with that
     151             :         // prefix.
     152             :         fullKey []byte
     153             :         // val contains the value the iterator is currently pointed at. If non-nil,
     154             :         // this points to a slice of the block data.
     155             :         val []byte
     156             :         // ikv contains the decoded internal KV the iterator is currently positioned
     157             :         // at.
     158             :         //
     159             :         // ikv.InternalKey contains the decoded InternalKey the iterator is
     160             :         // currently pointed at. Note that the memory backing ikv.UserKey is either
     161             :         // data stored directly in the block, fullKey, or cachedBuf. The key
     162             :         // stability guarantee for blocks built with a restart interval of 1 is
     163             :         // achieved by having ikv.UserKey always point to data stored directly in
     164             :         // the block.
     165             :         //
     166             :         // ikv.LazyValue is val turned into a LazyValue, whenever a positioning
     167             :         // method returns a non-nil key-value pair.
     168             :         ikv base.InternalKV
     169             :         // cached and cachedBuf are used during reverse iteration. They are needed
     170             :         // because we can't perform prefix decoding in reverse, only in the forward
     171             :         // direction. In order to iterate in reverse, we decode and cache the entries
     172             :         // between two restart points.
     173             :         //
     174             :         // Note that cached[len(cached)-1] contains the previous entry to the one the
     175             :         // blockIter is currently pointed at. As usual, nextOffset will contain the
     176             :         // offset of the next entry. During reverse iteration, nextOffset will be
     177             :         // updated to point to offset, and we'll set the blockIter to point at the
     178             :         // entry cached[len(cached)-1]. See Prev() for more details.
     179             :         //
     180             :         // For a block encoded with a restart interval of 1, cached and cachedBuf
     181             :         // will not be used as there are no prefix compressed entries between the
     182             :         // restart points.
     183             :         cached    []blockEntry
     184             :         cachedBuf []byte
     185             :         handle    block.BufferHandle
     186             :         // for block iteration for already loaded blocks.
     187             :         firstUserKey      []byte
     188             :         lazyValueHandling struct {
     189             :                 getValue       block.GetLazyValueForPrefixAndValueHandler
     190             :                 hasValuePrefix bool
     191             :         }
     192             :         synthSuffixBuf            []byte
     193             :         firstUserKeyWithPrefixBuf []byte
     194             : }
     195             : 
     196             : type blockEntry struct {
     197             :         offset   int32
     198             :         keyStart int32
     199             :         keyEnd   int32
     200             :         valStart int32
     201             :         valSize  int32
     202             : }
     203             : 
     204             : // *Iter implements the block.DataBlockIterator interface.
     205             : var _ block.DataBlockIterator = (*Iter)(nil)
     206             : 
     207             : // NewIter constructs a new row-oriented block iterator over the provided serialized block.
     208             : func NewIter(
     209             :         cmp base.Compare, split base.Split, block []byte, transforms block.IterTransforms,
     210           0 : ) (*Iter, error) {
     211           0 :         i := &Iter{}
     212           0 :         return i, i.Init(cmp, split, block, transforms)
     213           0 : }
     214             : 
     215             : // String implements fmt.Stringer.
     216           0 : func (i *Iter) String() string {
     217           0 :         return "block"
     218           0 : }
     219             : 
     220             : // Init initializes the block iterator from the provided block.
     221             : func (i *Iter) Init(
     222             :         cmp base.Compare, split base.Split, blk []byte, transforms block.IterTransforms,
     223           1 : ) error {
     224           1 :         numRestarts := int32(binary.LittleEndian.Uint32(blk[len(blk)-4:]))
     225           1 :         if numRestarts == 0 {
     226           0 :                 return base.CorruptionErrorf("pebble/table: invalid table (block has no restart points)")
     227           0 :         }
     228           1 :         i.transforms = transforms
     229           1 :         i.synthSuffixBuf = i.synthSuffixBuf[:0]
     230           1 :         i.split = split
     231           1 :         i.cmp = cmp
     232           1 :         i.restarts = int32(len(blk)) - 4*(1+numRestarts)
     233           1 :         i.numRestarts = numRestarts
     234           1 :         i.ptr = unsafe.Pointer(&blk[0])
     235           1 :         i.data = blk
     236           1 :         if i.transforms.HasSyntheticPrefix() {
     237           1 :                 i.fullKey = append(i.fullKey[:0], i.transforms.SyntheticPrefix()...)
     238           1 :         } else {
     239           1 :                 i.fullKey = i.fullKey[:0]
     240           1 :         }
     241           1 :         i.val = nil
     242           1 :         i.clearCache()
     243           1 :         if i.restarts > 0 {
     244           1 :                 if err := i.readFirstKey(); err != nil {
     245           0 :                         return err
     246           0 :                 }
     247           1 :         } else {
     248           1 :                 // Block is empty.
     249           1 :                 i.firstUserKey = nil
     250           1 :         }
     251           1 :         return nil
     252             : }
     253             : 
     254             : // InitHandle initializes an iterator from the provided block handle.
     255             : // NB: two cases of hideObsoletePoints:
     256             : //   - Local sstable iteration: syntheticSeqNum will be set iff the sstable was
     257             : //     ingested.
     258             : //   - Foreign sstable iteration: syntheticSeqNum is always set.
     259             : func (i *Iter) InitHandle(
     260             :         cmp base.Compare, split base.Split, block block.BufferHandle, transforms block.IterTransforms,
     261           1 : ) error {
     262           1 :         i.handle.Release()
     263           1 :         i.handle = block
     264           1 :         return i.Init(cmp, split, block.BlockData(), transforms)
     265           1 : }
     266             : 
     267             : // SetHasValuePrefix sets whether or not the block iterator should expect values
     268             : // corresponding to Set keys to have a prefix byte.
     269           1 : func (i *Iter) SetHasValuePrefix(hasValuePrefix bool) {
     270           1 :         i.lazyValueHandling.hasValuePrefix = hasValuePrefix
     271           1 : }
     272             : 
     273             : // SetGetLazyValuer sets the value block reader the iterator should use to get
     274             : // lazy values when the value encodes a value prefix.
     275           1 : func (i *Iter) SetGetLazyValuer(g block.GetLazyValueForPrefixAndValueHandler) {
     276           1 :         i.lazyValueHandling.getValue = g
     277           1 : 
     278           1 : }
     279             : 
     280             : // Handle returns the underlying block buffer handle, if the iterator was
     281             : // initialized with one.
     282           1 : func (i *Iter) Handle() block.BufferHandle {
     283           1 :         return i.handle
     284           1 : }
     285             : 
     286             : // Invalidate invalidates the block iterator, removing references to the block
     287             : // it was initialized with.
     288           1 : func (i *Iter) Invalidate() {
     289           1 :         i.clearCache()
     290           1 :         i.offset = 0
     291           1 :         i.nextOffset = 0
     292           1 :         i.restarts = 0
     293           1 :         i.numRestarts = 0
     294           1 :         i.data = nil
     295           1 : }
     296             : 
     297             : // IsDataInvalidated returns true when the blockIter has been invalidated
     298             : // using an invalidate call. NB: this is different from blockIter.Valid
     299             : // which is part of the InternalIterator implementation.
     300           1 : func (i *Iter) IsDataInvalidated() bool {
     301           1 :         return i.data == nil
     302           1 : }
     303             : 
     304           1 : func (i *Iter) readEntry() {
     305           1 :         ptr := unsafe.Pointer(uintptr(i.ptr) + uintptr(i.offset))
     306           1 : 
     307           1 :         // This is an ugly performance hack. Reading entries from blocks is one of
     308           1 :         // the inner-most routines and decoding the 3 varints per-entry takes
     309           1 :         // significant time. Neither go1.11 or go1.12 will inline decodeVarint for
     310           1 :         // us, so we do it manually. This provides a 10-15% performance improvement
     311           1 :         // on blockIter benchmarks on both go1.11 and go1.12.
     312           1 :         //
     313           1 :         // TODO(peter): remove this hack if go:inline is ever supported.
     314           1 : 
     315           1 :         var shared uint32
     316           1 :         if a := *((*uint8)(ptr)); a < 128 {
     317           1 :                 shared = uint32(a)
     318           1 :                 ptr = unsafe.Pointer(uintptr(ptr) + 1)
     319           1 :         } else if a, b := a&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 1))); b < 128 {
     320           0 :                 shared = uint32(b)<<7 | uint32(a)
     321           0 :                 ptr = unsafe.Pointer(uintptr(ptr) + 2)
     322           0 :         } else if b, c := b&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 2))); c < 128 {
     323           0 :                 shared = uint32(c)<<14 | uint32(b)<<7 | uint32(a)
     324           0 :                 ptr = unsafe.Pointer(uintptr(ptr) + 3)
     325           0 :         } else if c, d := c&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 3))); d < 128 {
     326           0 :                 shared = uint32(d)<<21 | uint32(c)<<14 | uint32(b)<<7 | uint32(a)
     327           0 :                 ptr = unsafe.Pointer(uintptr(ptr) + 4)
     328           0 :         } else {
     329           0 :                 d, e := d&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 4)))
     330           0 :                 shared = uint32(e)<<28 | uint32(d)<<21 | uint32(c)<<14 | uint32(b)<<7 | uint32(a)
     331           0 :                 ptr = unsafe.Pointer(uintptr(ptr) + 5)
     332           0 :         }
     333             : 
     334           1 :         var unshared uint32
     335           1 :         if a := *((*uint8)(ptr)); a < 128 {
     336           1 :                 unshared = uint32(a)
     337           1 :                 ptr = unsafe.Pointer(uintptr(ptr) + 1)
     338           1 :         } else if a, b := a&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 1))); b < 128 {
     339           0 :                 unshared = uint32(b)<<7 | uint32(a)
     340           0 :                 ptr = unsafe.Pointer(uintptr(ptr) + 2)
     341           0 :         } else if b, c := b&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 2))); c < 128 {
     342           0 :                 unshared = uint32(c)<<14 | uint32(b)<<7 | uint32(a)
     343           0 :                 ptr = unsafe.Pointer(uintptr(ptr) + 3)
     344           0 :         } else if c, d := c&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 3))); d < 128 {
     345           0 :                 unshared = uint32(d)<<21 | uint32(c)<<14 | uint32(b)<<7 | uint32(a)
     346           0 :                 ptr = unsafe.Pointer(uintptr(ptr) + 4)
     347           0 :         } else {
     348           0 :                 d, e := d&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 4)))
     349           0 :                 unshared = uint32(e)<<28 | uint32(d)<<21 | uint32(c)<<14 | uint32(b)<<7 | uint32(a)
     350           0 :                 ptr = unsafe.Pointer(uintptr(ptr) + 5)
     351           0 :         }
     352             : 
     353           1 :         var value uint32
     354           1 :         if a := *((*uint8)(ptr)); a < 128 {
     355           1 :                 value = uint32(a)
     356           1 :                 ptr = unsafe.Pointer(uintptr(ptr) + 1)
     357           1 :         } else if a, b := a&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 1))); b < 128 {
     358           1 :                 value = uint32(b)<<7 | uint32(a)
     359           1 :                 ptr = unsafe.Pointer(uintptr(ptr) + 2)
     360           1 :         } else if b, c := b&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 2))); c < 128 {
     361           0 :                 value = uint32(c)<<14 | uint32(b)<<7 | uint32(a)
     362           0 :                 ptr = unsafe.Pointer(uintptr(ptr) + 3)
     363           0 :         } else if c, d := c&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 3))); d < 128 {
     364           0 :                 value = uint32(d)<<21 | uint32(c)<<14 | uint32(b)<<7 | uint32(a)
     365           0 :                 ptr = unsafe.Pointer(uintptr(ptr) + 4)
     366           0 :         } else {
     367           0 :                 d, e := d&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 4)))
     368           0 :                 value = uint32(e)<<28 | uint32(d)<<21 | uint32(c)<<14 | uint32(b)<<7 | uint32(a)
     369           0 :                 ptr = unsafe.Pointer(uintptr(ptr) + 5)
     370           0 :         }
     371           1 :         shared += i.transforms.SyntheticPrefixAndSuffix.PrefixLen()
     372           1 :         unsharedKey := getBytes(ptr, int(unshared))
     373           1 :         // TODO(sumeer): move this into the else block below.
     374           1 :         i.fullKey = append(i.fullKey[:shared], unsharedKey...)
     375           1 :         if shared == 0 {
     376           1 :                 // Provide stability for the key across positioning calls if the key
     377           1 :                 // doesn't share a prefix with the previous key. This removes requiring the
     378           1 :                 // key to be copied if the caller knows the block has a restart interval of
     379           1 :                 // 1. An important example of this is range-del blocks.
     380           1 :                 i.key = unsharedKey
     381           1 :         } else {
     382           1 :                 i.key = i.fullKey
     383           1 :         }
     384           1 :         ptr = unsafe.Pointer(uintptr(ptr) + uintptr(unshared))
     385           1 :         i.val = getBytes(ptr, int(value))
     386           1 :         i.nextOffset = int32(uintptr(ptr)-uintptr(i.ptr)) + int32(value)
     387             : }
     388             : 
     389           1 : func (i *Iter) readFirstKey() error {
     390           1 :         ptr := i.ptr
     391           1 : 
     392           1 :         // This is an ugly performance hack. Reading entries from blocks is one of
     393           1 :         // the inner-most routines and decoding the 3 varints per-entry takes
     394           1 :         // significant time. Neither go1.11 or go1.12 will inline decodeVarint for
     395           1 :         // us, so we do it manually. This provides a 10-15% performance improvement
     396           1 :         // on blockIter benchmarks on both go1.11 and go1.12.
     397           1 :         //
     398           1 :         // TODO(peter): remove this hack if go:inline is ever supported.
     399           1 : 
     400           1 :         if shared := *((*uint8)(ptr)); shared == 0 {
     401           1 :                 ptr = unsafe.Pointer(uintptr(ptr) + 1)
     402           1 :         } else {
     403           0 :                 // The shared length is != 0, which is invalid.
     404           0 :                 panic("first key in block must have zero shared length")
     405             :         }
     406             : 
     407           1 :         var unshared uint32
     408           1 :         if a := *((*uint8)(ptr)); a < 128 {
     409           1 :                 unshared = uint32(a)
     410           1 :                 ptr = unsafe.Pointer(uintptr(ptr) + 1)
     411           1 :         } else if a, b := a&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 1))); b < 128 {
     412           0 :                 unshared = uint32(b)<<7 | uint32(a)
     413           0 :                 ptr = unsafe.Pointer(uintptr(ptr) + 2)
     414           0 :         } else if b, c := b&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 2))); c < 128 {
     415           0 :                 unshared = uint32(c)<<14 | uint32(b)<<7 | uint32(a)
     416           0 :                 ptr = unsafe.Pointer(uintptr(ptr) + 3)
     417           0 :         } else if c, d := c&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 3))); d < 128 {
     418           0 :                 unshared = uint32(d)<<21 | uint32(c)<<14 | uint32(b)<<7 | uint32(a)
     419           0 :                 ptr = unsafe.Pointer(uintptr(ptr) + 4)
     420           0 :         } else {
     421           0 :                 d, e := d&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 4)))
     422           0 :                 unshared = uint32(e)<<28 | uint32(d)<<21 | uint32(c)<<14 | uint32(b)<<7 | uint32(a)
     423           0 :                 ptr = unsafe.Pointer(uintptr(ptr) + 5)
     424           0 :         }
     425             : 
     426             :         // Skip the value length.
     427           1 :         if a := *((*uint8)(ptr)); a < 128 {
     428           1 :                 ptr = unsafe.Pointer(uintptr(ptr) + 1)
     429           1 :         } else if a := *((*uint8)(unsafe.Pointer(uintptr(ptr) + 1))); a < 128 {
     430           1 :                 ptr = unsafe.Pointer(uintptr(ptr) + 2)
     431           1 :         } else if a := *((*uint8)(unsafe.Pointer(uintptr(ptr) + 2))); a < 128 {
     432           0 :                 ptr = unsafe.Pointer(uintptr(ptr) + 3)
     433           0 :         } else if a := *((*uint8)(unsafe.Pointer(uintptr(ptr) + 3))); a < 128 {
     434           0 :                 ptr = unsafe.Pointer(uintptr(ptr) + 4)
     435           0 :         } else {
     436           0 :                 ptr = unsafe.Pointer(uintptr(ptr) + 5)
     437           0 :         }
     438             : 
     439           1 :         firstKey := getBytes(ptr, int(unshared))
     440           1 :         // Manually inlining base.DecodeInternalKey provides a 5-10% speedup on
     441           1 :         // BlockIter benchmarks.
     442           1 :         if n := len(firstKey) - 8; n >= 0 {
     443           1 :                 i.firstUserKey = firstKey[:n:n]
     444           1 :         } else {
     445           0 :                 i.firstUserKey = nil
     446           0 :                 return base.CorruptionErrorf("pebble/table: invalid firstKey in block")
     447           0 :         }
     448           1 :         if i.transforms.HasSyntheticPrefix() {
     449           1 :                 syntheticPrefix := i.transforms.SyntheticPrefix()
     450           1 :                 i.firstUserKeyWithPrefixBuf = slices.Grow(i.firstUserKeyWithPrefixBuf[:0], len(syntheticPrefix)+len(i.firstUserKey))
     451           1 :                 i.firstUserKeyWithPrefixBuf = append(i.firstUserKeyWithPrefixBuf, syntheticPrefix...)
     452           1 :                 i.firstUserKeyWithPrefixBuf = append(i.firstUserKeyWithPrefixBuf, i.firstUserKey...)
     453           1 :                 i.firstUserKey = i.firstUserKeyWithPrefixBuf
     454           1 :         }
     455           1 :         return nil
     456             : }
     457             : 
     458           1 : func (i *Iter) decodeInternalKey(key []byte) (hiddenPoint bool) {
     459           1 :         // Manually inlining base.DecodeInternalKey provides a 5-10% speedup on
     460           1 :         // BlockIter benchmarks.
     461           1 :         if n := len(key) - 8; n >= 0 {
     462           1 :                 trailer := base.InternalKeyTrailer(binary.LittleEndian.Uint64(key[n:]))
     463           1 :                 hiddenPoint = i.transforms.HideObsoletePoints &&
     464           1 :                         (trailer&TrailerObsoleteBit != 0)
     465           1 :                 i.ikv.K.Trailer = trailer & TrailerObsoleteMask
     466           1 :                 i.ikv.K.UserKey = key[:n:n]
     467           1 :                 if n := i.transforms.SyntheticSeqNum; n != 0 {
     468           1 :                         i.ikv.K.SetSeqNum(base.SeqNum(n))
     469           1 :                 }
     470           1 :         } else {
     471           1 :                 i.ikv.K.Trailer = base.InternalKeyTrailer(base.InternalKeyKindInvalid)
     472           1 :                 i.ikv.K.UserKey = nil
     473           1 :         }
     474           1 :         return hiddenPoint
     475             : }
     476             : 
     477             : // maybeReplaceSuffix replaces the suffix in i.ikey.UserKey with
     478             : // i.transforms.syntheticSuffix.
     479           1 : func (i *Iter) maybeReplaceSuffix() {
     480           1 :         if i.transforms.HasSyntheticSuffix() && i.ikv.K.UserKey != nil {
     481           1 :                 prefixLen := i.split(i.ikv.K.UserKey)
     482           1 :                 // If ikey is cached or may get cached, we must copy
     483           1 :                 // UserKey to a new buffer before suffix replacement.
     484           1 :                 i.synthSuffixBuf = append(i.synthSuffixBuf[:0], i.ikv.K.UserKey[:prefixLen]...)
     485           1 :                 i.synthSuffixBuf = append(i.synthSuffixBuf, i.transforms.SyntheticSuffix()...)
     486           1 :                 i.ikv.K.UserKey = i.synthSuffixBuf
     487           1 :         }
     488             : }
     489             : 
     490           1 : func (i *Iter) clearCache() {
     491           1 :         i.cached = i.cached[:0]
     492           1 :         i.cachedBuf = i.cachedBuf[:0]
     493           1 : }
     494             : 
     495           1 : func (i *Iter) cacheEntry() {
     496           1 :         var valStart int32
     497           1 :         valSize := int32(len(i.val))
     498           1 :         if valSize > 0 {
     499           1 :                 valStart = int32(uintptr(unsafe.Pointer(&i.val[0])) - uintptr(i.ptr))
     500           1 :         }
     501             : 
     502           1 :         i.cached = append(i.cached, blockEntry{
     503           1 :                 offset:   i.offset,
     504           1 :                 keyStart: int32(len(i.cachedBuf)),
     505           1 :                 keyEnd:   int32(len(i.cachedBuf) + len(i.key)),
     506           1 :                 valStart: valStart,
     507           1 :                 valSize:  valSize,
     508           1 :         })
     509           1 :         i.cachedBuf = append(i.cachedBuf, i.key...)
     510             : }
     511             : 
     512             : // IsLowerBound implements the block.DataBlockIterator interface.
     513           1 : func (i *Iter) IsLowerBound(k []byte) bool {
     514           1 :         // Note: we ignore HideObsoletePoints, but false negatives are allowed.
     515           1 :         return i.cmp(i.firstUserKey, k) >= 0
     516           1 : }
     517             : 
     518             : // SeekGE implements internalIterator.SeekGE, as documented in the pebble
     519             : // package.
     520           1 : func (i *Iter) SeekGE(key []byte, flags base.SeekGEFlags) *base.InternalKV {
     521           1 :         if invariants.Enabled && i.IsDataInvalidated() {
     522           0 :                 panic(errors.AssertionFailedf("invalidated blockIter used"))
     523             :         }
     524           1 :         searchKey := key
     525           1 :         if i.transforms.HasSyntheticPrefix() {
     526           1 :                 syntheticPrefix := i.transforms.SyntheticPrefix()
     527           1 :                 if !bytes.HasPrefix(key, syntheticPrefix) {
     528           0 :                         // The seek key is before or after the entire block of keys that start
     529           0 :                         // with SyntheticPrefix. To determine which, we need to compare against a
     530           0 :                         // valid key in the block. We use firstUserKey which has the synthetic
     531           0 :                         // prefix.
     532           0 :                         if i.cmp(i.firstUserKey, key) >= 0 {
     533           0 :                                 return i.First()
     534           0 :                         }
     535             :                         // Set the offset to the end of the block to mimic the offset of an
     536             :                         // invalid iterator. This ensures a subsequent i.Prev() returns a valid
     537             :                         // result.
     538           0 :                         i.offset = i.restarts
     539           0 :                         i.nextOffset = i.restarts
     540           0 :                         return nil
     541             :                 }
     542           1 :                 searchKey = key[len(syntheticPrefix):]
     543             :         }
     544             : 
     545           1 :         i.clearCache()
     546           1 :         // Find the index of the smallest restart point whose key is > the key
     547           1 :         // sought; index will be numRestarts if there is no such restart point.
     548           1 :         i.offset = 0
     549           1 :         var index int32
     550           1 : 
     551           1 :         {
     552           1 :                 // NB: manually inlined sort.Seach is ~5% faster.
     553           1 :                 //
     554           1 :                 // Define f(-1) == false and f(n) == true.
     555           1 :                 // Invariant: f(index-1) == false, f(upper) == true.
     556           1 :                 upper := i.numRestarts
     557           1 :                 for index < upper {
     558           1 :                         h := int32(uint(index+upper) >> 1) // avoid overflow when computing h
     559           1 :                         // index ≤ h < upper
     560           1 :                         offset := decodeRestart(i.data[i.restarts+4*h:])
     561           1 :                         // For a restart point, there are 0 bytes shared with the previous key.
     562           1 :                         // The varint encoding of 0 occupies 1 byte.
     563           1 :                         ptr := unsafe.Pointer(uintptr(i.ptr) + uintptr(offset+1))
     564           1 : 
     565           1 :                         // Decode the key at that restart point, and compare it to the key
     566           1 :                         // sought. See the comment in readEntry for why we manually inline the
     567           1 :                         // varint decoding.
     568           1 :                         var v1 uint32
     569           1 :                         if a := *((*uint8)(ptr)); a < 128 {
     570           1 :                                 v1 = uint32(a)
     571           1 :                                 ptr = unsafe.Pointer(uintptr(ptr) + 1)
     572           1 :                         } else if a, b := a&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 1))); b < 128 {
     573           0 :                                 v1 = uint32(b)<<7 | uint32(a)
     574           0 :                                 ptr = unsafe.Pointer(uintptr(ptr) + 2)
     575           0 :                         } else if b, c := b&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 2))); c < 128 {
     576           0 :                                 v1 = uint32(c)<<14 | uint32(b)<<7 | uint32(a)
     577           0 :                                 ptr = unsafe.Pointer(uintptr(ptr) + 3)
     578           0 :                         } else if c, d := c&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 3))); d < 128 {
     579           0 :                                 v1 = uint32(d)<<21 | uint32(c)<<14 | uint32(b)<<7 | uint32(a)
     580           0 :                                 ptr = unsafe.Pointer(uintptr(ptr) + 4)
     581           0 :                         } else {
     582           0 :                                 d, e := d&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 4)))
     583           0 :                                 v1 = uint32(e)<<28 | uint32(d)<<21 | uint32(c)<<14 | uint32(b)<<7 | uint32(a)
     584           0 :                                 ptr = unsafe.Pointer(uintptr(ptr) + 5)
     585           0 :                         }
     586             : 
     587           1 :                         if *((*uint8)(ptr)) < 128 {
     588           1 :                                 ptr = unsafe.Pointer(uintptr(ptr) + 1)
     589           1 :                         } else if *((*uint8)(unsafe.Pointer(uintptr(ptr) + 1))) < 128 {
     590           0 :                                 ptr = unsafe.Pointer(uintptr(ptr) + 2)
     591           0 :                         } else if *((*uint8)(unsafe.Pointer(uintptr(ptr) + 2))) < 128 {
     592           0 :                                 ptr = unsafe.Pointer(uintptr(ptr) + 3)
     593           0 :                         } else if *((*uint8)(unsafe.Pointer(uintptr(ptr) + 3))) < 128 {
     594           0 :                                 ptr = unsafe.Pointer(uintptr(ptr) + 4)
     595           0 :                         } else {
     596           0 :                                 ptr = unsafe.Pointer(uintptr(ptr) + 5)
     597           0 :                         }
     598             : 
     599             :                         // Manually inlining part of base.DecodeInternalKey provides a 5-10%
     600             :                         // speedup on BlockIter benchmarks.
     601           1 :                         s := getBytes(ptr, int(v1))
     602           1 :                         var k []byte
     603           1 :                         if n := len(s) - 8; n >= 0 {
     604           1 :                                 k = s[:n:n]
     605           1 :                         }
     606             :                         // Else k is invalid, and left as nil
     607             : 
     608           1 :                         if i.cmp(searchKey, k) > 0 {
     609           1 :                                 // The search key is greater than the user key at this restart point.
     610           1 :                                 // Search beyond this restart point, since we are trying to find the
     611           1 :                                 // first restart point with a user key >= the search key.
     612           1 :                                 index = h + 1 // preserves f(i-1) == false
     613           1 :                         } else {
     614           1 :                                 // k >= search key, so prune everything after index (since index
     615           1 :                                 // satisfies the property we are looking for).
     616           1 :                                 upper = h // preserves f(j) == true
     617           1 :                         }
     618             :                 }
     619             :                 // index == upper, f(index-1) == false, and f(upper) (= f(index)) == true
     620             :                 // => answer is index.
     621             :         }
     622             : 
     623             :         // index is the first restart point with key >= search key. Define the keys
     624             :         // between a restart point and the next restart point as belonging to that
     625             :         // restart point.
     626             :         //
     627             :         // Since keys are strictly increasing, if index > 0 then the restart point
     628             :         // at index-1 will be the first one that has some keys belonging to it that
     629             :         // could be equal to the search key.  If index == 0, then all keys in this
     630             :         // block are larger than the key sought, and offset remains at zero.
     631           1 :         if index > 0 {
     632           1 :                 i.offset = decodeRestart(i.data[i.restarts+4*(index-1):])
     633           1 :         }
     634           1 :         i.readEntry()
     635           1 :         hiddenPoint := i.decodeInternalKey(i.key)
     636           1 : 
     637           1 :         // Iterate from that restart point to somewhere >= the key sought.
     638           1 :         if !i.Valid() {
     639           0 :                 return nil
     640           0 :         }
     641             : 
     642             :         // A note on seeking in a block with a suffix replacement rule: even though
     643             :         // the binary search above was conducted on keys without suffix replacement,
     644             :         // Seek will still return the correct suffix replaced key. A binary
     645             :         // search without suffix replacement will land on a key that is _less_ than
     646             :         // the key the search would have landed on if all keys were already suffix
     647             :         // replaced. Since Seek then conducts forward iteration to the first suffix
     648             :         // replaced user key that is greater than or equal to the search key, the
     649             :         // correct key is still returned.
     650             :         //
     651             :         // As an example, consider the following block with a restart interval of 1,
     652             :         // with a replacement suffix of "4":
     653             :         // - Pre-suffix replacement: apple@1, banana@3
     654             :         // - Post-suffix replacement: apple@4, banana@4
     655             :         //
     656             :         // Suppose the client seeks with apple@3. Assuming suffixes sort in reverse
     657             :         // chronological order (i.e. apple@1>apple@3), the binary search without
     658             :         // suffix replacement would return apple@1. A binary search with suffix
     659             :         // replacement would return banana@4. After beginning forward iteration from
     660             :         // either returned restart point, forward iteration would
     661             :         // always return the correct key, banana@4.
     662             :         //
     663             :         // Further, if the user searched with apple@0 (i.e. a suffix less than the
     664             :         // pre replacement suffix) or with apple@5 (a suffix larger than the post
     665             :         // replacement suffix), the binary search with or without suffix replacement
     666             :         // would land on the same key, as we assume the following:
     667             :         // (1) no two keys in the sst share the same prefix.
     668             :         // (2) pebble.Compare(replacementSuffix,originalSuffix) > 0
     669             : 
     670           1 :         i.maybeReplaceSuffix()
     671           1 : 
     672           1 :         if !hiddenPoint && i.cmp(i.ikv.K.UserKey, key) >= 0 {
     673           1 :                 // Initialize i.lazyValue
     674           1 :                 if !i.lazyValueHandling.hasValuePrefix ||
     675           1 :                         i.ikv.K.Kind() != base.InternalKeyKindSet {
     676           1 :                         i.ikv.V = base.MakeInPlaceValue(i.val)
     677           1 :                 } else if i.lazyValueHandling.getValue == nil || !block.ValuePrefix(i.val[0]).IsValueHandle() {
     678           1 :                         i.ikv.V = base.MakeInPlaceValue(i.val[1:])
     679           1 :                 } else {
     680           1 :                         i.ikv.V = i.lazyValueHandling.getValue.GetLazyValueForPrefixAndValueHandle(i.val)
     681           1 :                 }
     682           1 :                 return &i.ikv
     683             :         }
     684           1 :         for i.Next(); i.Valid(); i.Next() {
     685           1 :                 if i.cmp(i.ikv.K.UserKey, key) >= 0 {
     686           1 :                         // i.Next() has already initialized i.ikv.LazyValue.
     687           1 :                         return &i.ikv
     688           1 :                 }
     689             :         }
     690           1 :         return nil
     691             : }
     692             : 
     693             : // SeekPrefixGE implements internalIterator.SeekPrefixGE, as documented in the
     694             : // pebble package.
     695           0 : func (i *Iter) SeekPrefixGE(prefix, key []byte, flags base.SeekGEFlags) *base.InternalKV {
     696           0 :         // This should never be called as prefix iteration is handled by sstable.Iterator.
     697           0 :         panic("pebble: SeekPrefixGE unimplemented")
     698             : }
     699             : 
     700             : // SeekLT implements internalIterator.SeekLT, as documented in the pebble
     701             : // package.
     702           1 : func (i *Iter) SeekLT(key []byte, flags base.SeekLTFlags) *base.InternalKV {
     703           1 :         if invariants.Enabled && i.IsDataInvalidated() {
     704           0 :                 panic(errors.AssertionFailedf("invalidated blockIter used"))
     705             :         }
     706           1 :         searchKey := key
     707           1 :         if i.transforms.HasSyntheticPrefix() {
     708           1 :                 syntheticPrefix := i.transforms.SyntheticPrefix()
     709           1 :                 if !bytes.HasPrefix(key, syntheticPrefix) {
     710           1 :                         // The seek key is before or after the entire block of keys that start
     711           1 :                         // with SyntheticPrefix. To determine which, we need to compare against a
     712           1 :                         // valid key in the block. We use firstUserKey which has the synthetic
     713           1 :                         // prefix.
     714           1 :                         if i.cmp(i.firstUserKey, key) < 0 {
     715           1 :                                 return i.Last()
     716           1 :                         }
     717             :                         // Set the offset to the beginning of the block to mimic an exhausted
     718             :                         // iterator that has conducted backward interation. This ensures a
     719             :                         // subsequent Next() call returns the first key in the block.
     720           1 :                         i.offset = -1
     721           1 :                         i.nextOffset = 0
     722           1 :                         return nil
     723             :                 }
     724           1 :                 searchKey = key[len(syntheticPrefix):]
     725             :         }
     726             : 
     727           1 :         i.clearCache()
     728           1 :         // Find the index of the smallest restart point whose key is >= the key
     729           1 :         // sought; index will be numRestarts if there is no such restart point.
     730           1 :         i.offset = 0
     731           1 :         var index int32
     732           1 : 
     733           1 :         {
     734           1 :                 // NB: manually inlined sort.Search is ~5% faster.
     735           1 :                 //
     736           1 :                 // Define f(-1) == false and f(n) == true.
     737           1 :                 // Invariant: f(index-1) == false, f(upper) == true.
     738           1 :                 upper := i.numRestarts
     739           1 :                 for index < upper {
     740           1 :                         h := int32(uint(index+upper) >> 1) // avoid overflow when computing h
     741           1 :                         // index ≤ h < upper
     742           1 :                         offset := decodeRestart(i.data[i.restarts+4*h:])
     743           1 :                         // For a restart point, there are 0 bytes shared with the previous key.
     744           1 :                         // The varint encoding of 0 occupies 1 byte.
     745           1 :                         ptr := unsafe.Pointer(uintptr(i.ptr) + uintptr(offset+1))
     746           1 : 
     747           1 :                         // Decode the key at that restart point, and compare it to the key
     748           1 :                         // sought. See the comment in readEntry for why we manually inline the
     749           1 :                         // varint decoding.
     750           1 :                         var v1 uint32
     751           1 :                         if a := *((*uint8)(ptr)); a < 128 {
     752           1 :                                 v1 = uint32(a)
     753           1 :                                 ptr = unsafe.Pointer(uintptr(ptr) + 1)
     754           1 :                         } else if a, b := a&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 1))); b < 128 {
     755           0 :                                 v1 = uint32(b)<<7 | uint32(a)
     756           0 :                                 ptr = unsafe.Pointer(uintptr(ptr) + 2)
     757           0 :                         } else if b, c := b&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 2))); c < 128 {
     758           0 :                                 v1 = uint32(c)<<14 | uint32(b)<<7 | uint32(a)
     759           0 :                                 ptr = unsafe.Pointer(uintptr(ptr) + 3)
     760           0 :                         } else if c, d := c&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 3))); d < 128 {
     761           0 :                                 v1 = uint32(d)<<21 | uint32(c)<<14 | uint32(b)<<7 | uint32(a)
     762           0 :                                 ptr = unsafe.Pointer(uintptr(ptr) + 4)
     763           0 :                         } else {
     764           0 :                                 d, e := d&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 4)))
     765           0 :                                 v1 = uint32(e)<<28 | uint32(d)<<21 | uint32(c)<<14 | uint32(b)<<7 | uint32(a)
     766           0 :                                 ptr = unsafe.Pointer(uintptr(ptr) + 5)
     767           0 :                         }
     768             : 
     769           1 :                         if *((*uint8)(ptr)) < 128 {
     770           1 :                                 ptr = unsafe.Pointer(uintptr(ptr) + 1)
     771           1 :                         } else if *((*uint8)(unsafe.Pointer(uintptr(ptr) + 1))) < 128 {
     772           1 :                                 ptr = unsafe.Pointer(uintptr(ptr) + 2)
     773           1 :                         } else if *((*uint8)(unsafe.Pointer(uintptr(ptr) + 2))) < 128 {
     774           0 :                                 ptr = unsafe.Pointer(uintptr(ptr) + 3)
     775           0 :                         } else if *((*uint8)(unsafe.Pointer(uintptr(ptr) + 3))) < 128 {
     776           0 :                                 ptr = unsafe.Pointer(uintptr(ptr) + 4)
     777           0 :                         } else {
     778           0 :                                 ptr = unsafe.Pointer(uintptr(ptr) + 5)
     779           0 :                         }
     780             : 
     781             :                         // Manually inlining part of base.DecodeInternalKey provides a 5-10%
     782             :                         // speedup on BlockIter benchmarks.
     783           1 :                         s := getBytes(ptr, int(v1))
     784           1 :                         var k []byte
     785           1 :                         if n := len(s) - 8; n >= 0 {
     786           1 :                                 k = s[:n:n]
     787           1 :                         }
     788             :                         // Else k is invalid, and left as nil
     789             : 
     790           1 :                         if i.cmp(searchKey, k) > 0 {
     791           1 :                                 // The search key is greater than the user key at this restart point.
     792           1 :                                 // Search beyond this restart point, since we are trying to find the
     793           1 :                                 // first restart point with a user key >= the search key.
     794           1 :                                 index = h + 1 // preserves f(i-1) == false
     795           1 :                         } else {
     796           1 :                                 // k >= search key, so prune everything after index (since index
     797           1 :                                 // satisfies the property we are looking for).
     798           1 :                                 upper = h // preserves f(j) == true
     799           1 :                         }
     800             :                 }
     801             :                 // index == upper, f(index-1) == false, and f(upper) (= f(index)) == true
     802             :                 // => answer is index.
     803             :         }
     804             : 
     805           1 :         if index == 0 {
     806           1 :                 if i.transforms.HasSyntheticSuffix() {
     807           1 :                         // The binary search was conducted on keys without suffix replacement,
     808           1 :                         // implying the first key in the block may be less than the search key. To
     809           1 :                         // double check, get the first key in the block with suffix replacement
     810           1 :                         // and compare to the search key. Consider the following example: suppose
     811           1 :                         // the user searches with a@3, the first key in the block is a@2 and the
     812           1 :                         // block contains a suffix replacement rule of 4. Since a@3 sorts before
     813           1 :                         // a@2, the binary search would return index==0. Without conducting the
     814           1 :                         // suffix replacement, the SeekLT would incorrectly return nil. With
     815           1 :                         // suffix replacement though, a@4 should be returned as a@4 sorts before
     816           1 :                         // a@3.
     817           1 :                         ikv := i.First()
     818           1 :                         if i.cmp(ikv.K.UserKey, key) < 0 {
     819           1 :                                 return ikv
     820           1 :                         }
     821             :                 }
     822             :                 // If index == 0 then all keys in this block are larger than the key
     823             :                 // sought, so there is no match.
     824           1 :                 i.offset = -1
     825           1 :                 i.nextOffset = 0
     826           1 :                 return nil
     827             :         }
     828             : 
     829             :         // INVARIANT: index > 0
     830             : 
     831             :         // Ignoring suffix replacement, index is the first restart point with key >=
     832             :         // search key. Define the keys between a restart point and the next restart
     833             :         // point as belonging to that restart point. Note that index could be equal to
     834             :         // i.numRestarts, i.e., we are past the last restart.  Since keys are strictly
     835             :         // increasing, then the restart point at index-1 will be the first one that
     836             :         // has some keys belonging to it that are less than the search key.
     837             :         //
     838             :         // Next, we will search between the restart at index-1 and the restart point
     839             :         // at index, for the first key >= key, and then on finding it, return
     840             :         // i.Prev(). We need to know when we have hit the offset for index, since then
     841             :         // we can stop searching. targetOffset encodes that offset for index.
     842           1 :         targetOffset := i.restarts
     843           1 :         i.offset = decodeRestart(i.data[i.restarts+4*(index-1):])
     844           1 :         if index < i.numRestarts {
     845           1 :                 targetOffset = decodeRestart(i.data[i.restarts+4*(index):])
     846           1 : 
     847           1 :                 if i.transforms.HasSyntheticSuffix() {
     848           1 :                         // The binary search was conducted on keys without suffix replacement,
     849           1 :                         // implying the returned restart point (index) may be less than the search
     850           1 :                         // key, breaking the assumption described above.
     851           1 :                         //
     852           1 :                         // For example: consider this block with a replacement ts of 4, and
     853           1 :                         // restart interval of 1: - pre replacement: a@3,b@2,c@3 - post
     854           1 :                         // replacement: a@4,b@4,c@4
     855           1 :                         //
     856           1 :                         // Suppose the client calls SeekLT(b@3), SeekLT must return b@4.
     857           1 :                         //
     858           1 :                         // If the client calls  SeekLT(b@3), the binary search would return b@2,
     859           1 :                         // the lowest key geq to b@3, pre-suffix replacement. Then, SeekLT will
     860           1 :                         // begin forward iteration from a@3, the previous restart point, to
     861           1 :                         // b{suffix}. The iteration stops when it encounters a key geq to the
     862           1 :                         // search key or if it reaches the upper bound. Without suffix
     863           1 :                         // replacement, we can assume that the upper bound of this forward
     864           1 :                         // iteration, b{suffix}, is greater than the search key, as implied by the
     865           1 :                         // binary search.
     866           1 :                         //
     867           1 :                         // If we naively hold this assumption with suffix replacement, the
     868           1 :                         // iteration would terminate at the upper bound, b@4, call i.Prev, and
     869           1 :                         // incorrectly return a@4. To correct for this, if the original returned
     870           1 :                         // index is less than the search key, shift our forward iteration to begin
     871           1 :                         // at index instead of index -1. With suffix replacement the key at index
     872           1 :                         // is guaranteed to be the highest restart point less than the seach key
     873           1 :                         // (i.e. the same property of index-1 for a block without suffix
     874           1 :                         // replacement). This property holds because of the invariant that a block
     875           1 :                         // with suffix replacement will not have two keys that share the same
     876           1 :                         // prefix. To consider the above example, binary searching with b@3 landed
     877           1 :                         // naively at a@3, but since b@4<b@3, we shift our forward iteration to
     878           1 :                         // begin at b@4. We never need to shift by more than one restart point
     879           1 :                         // (i.e. to c@4) because it's impossible for the search key to be greater
     880           1 :                         // than the key at the next restart point in the block because that
     881           1 :                         // key will always have a different prefix. Put another way, because no
     882           1 :                         // key in the block shares the same prefix, naive binary search should
     883           1 :                         // always land at most 1 restart point off the correct one.
     884           1 : 
     885           1 :                         naiveOffset := i.offset
     886           1 :                         // Shift up to the original binary search result and decode the key.
     887           1 :                         i.offset = targetOffset
     888           1 :                         i.readEntry()
     889           1 :                         i.decodeInternalKey(i.key)
     890           1 :                         i.maybeReplaceSuffix()
     891           1 : 
     892           1 :                         // If the binary search point is actually less than the search key, post
     893           1 :                         // replacement, bump the target offset.
     894           1 :                         if i.cmp(i.ikv.K.UserKey, key) < 0 {
     895           0 :                                 i.offset = targetOffset
     896           0 :                                 if index+1 < i.numRestarts {
     897           0 :                                         // if index+1 is within the i.data bounds, use it to find the target
     898           0 :                                         // offset.
     899           0 :                                         targetOffset = decodeRestart(i.data[i.restarts+4*(index+1):])
     900           0 :                                 } else {
     901           0 :                                         targetOffset = i.restarts
     902           0 :                                 }
     903           1 :                         } else {
     904           1 :                                 i.offset = naiveOffset
     905           1 :                         }
     906             :                 }
     907             :         }
     908             : 
     909             :         // Init nextOffset for the forward iteration below.
     910           1 :         i.nextOffset = i.offset
     911           1 : 
     912           1 :         for {
     913           1 :                 i.offset = i.nextOffset
     914           1 :                 i.readEntry()
     915           1 :                 // When hidden keys are common, there is additional optimization possible
     916           1 :                 // by not caching entries that are hidden (note that some calls to
     917           1 :                 // cacheEntry don't decode the internal key before caching, but checking
     918           1 :                 // whether a key is hidden does not require full decoding). However, we do
     919           1 :                 // need to use the blockEntry.offset in the cache for the first entry at
     920           1 :                 // the reset point to do the binary search when the cache is empty -- so
     921           1 :                 // we would need to cache that first entry (though not the key) even if
     922           1 :                 // was hidden. Our current assumption is that if there are large numbers
     923           1 :                 // of hidden keys we will be able to skip whole blocks (using block
     924           1 :                 // property filters) so we don't bother optimizing.
     925           1 :                 hiddenPoint := i.decodeInternalKey(i.key)
     926           1 :                 i.maybeReplaceSuffix()
     927           1 : 
     928           1 :                 // NB: we don't use the hiddenPoint return value of decodeInternalKey
     929           1 :                 // since we want to stop as soon as we reach a key >= ikey.UserKey, so
     930           1 :                 // that we can reverse.
     931           1 :                 if i.cmp(i.ikv.K.UserKey, key) >= 0 {
     932           1 :                         // The current key is greater than or equal to our search key. Back up to
     933           1 :                         // the previous key which was less than our search key. Note that this for
     934           1 :                         // loop will execute at least once with this if-block not being true, so
     935           1 :                         // the key we are backing up to is the last one this loop cached.
     936           1 :                         return i.Prev()
     937           1 :                 }
     938             : 
     939           1 :                 if i.nextOffset >= targetOffset {
     940           1 :                         // We've reached the end of the current restart block. Return the
     941           1 :                         // current key if not hidden, else call Prev().
     942           1 :                         //
     943           1 :                         // When the restart interval is 1, the first iteration of the for loop
     944           1 :                         // will bring us here. In that case ikey is backed by the block so we
     945           1 :                         // get the desired key stability guarantee for the lifetime of the
     946           1 :                         // blockIter. That is, we never cache anything and therefore never
     947           1 :                         // return a key backed by cachedBuf.
     948           1 :                         if hiddenPoint {
     949           1 :                                 return i.Prev()
     950           1 :                         }
     951           1 :                         break
     952             :                 }
     953           1 :                 i.cacheEntry()
     954             :         }
     955             : 
     956           1 :         if !i.Valid() {
     957           1 :                 return nil
     958           1 :         }
     959           1 :         if !i.lazyValueHandling.hasValuePrefix ||
     960           1 :                 i.ikv.K.Kind() != base.InternalKeyKindSet {
     961           1 :                 i.ikv.V = base.MakeInPlaceValue(i.val)
     962           1 :         } else if i.lazyValueHandling.getValue == nil || !block.ValuePrefix(i.val[0]).IsValueHandle() {
     963           1 :                 i.ikv.V = base.MakeInPlaceValue(i.val[1:])
     964           1 :         } else {
     965           1 :                 i.ikv.V = i.lazyValueHandling.getValue.GetLazyValueForPrefixAndValueHandle(i.val)
     966           1 :         }
     967           1 :         return &i.ikv
     968             : }
     969             : 
     970             : // First implements internalIterator.First, as documented in the pebble
     971             : // package.
     972           1 : func (i *Iter) First() *base.InternalKV {
     973           1 :         if invariants.Enabled && i.IsDataInvalidated() {
     974           0 :                 panic(errors.AssertionFailedf("invalidated blockIter used"))
     975             :         }
     976             : 
     977           1 :         i.offset = 0
     978           1 :         if !i.Valid() {
     979           1 :                 return nil
     980           1 :         }
     981           1 :         i.clearCache()
     982           1 :         i.readEntry()
     983           1 :         hiddenPoint := i.decodeInternalKey(i.key)
     984           1 :         if hiddenPoint {
     985           1 :                 return i.Next()
     986           1 :         }
     987           1 :         i.maybeReplaceSuffix()
     988           1 :         if !i.lazyValueHandling.hasValuePrefix ||
     989           1 :                 i.ikv.K.Kind() != base.InternalKeyKindSet {
     990           1 :                 i.ikv.V = base.MakeInPlaceValue(i.val)
     991           1 :         } else if i.lazyValueHandling.getValue == nil || !block.ValuePrefix(i.val[0]).IsValueHandle() {
     992           1 :                 i.ikv.V = base.MakeInPlaceValue(i.val[1:])
     993           1 :         } else {
     994           1 :                 i.ikv.V = i.lazyValueHandling.getValue.GetLazyValueForPrefixAndValueHandle(i.val)
     995           1 :         }
     996           1 :         return &i.ikv
     997             : }
     998             : 
     999             : const restartMaskLittleEndianHighByteWithoutSetHasSamePrefix byte = 0b0111_1111
    1000             : const restartMaskLittleEndianHighByteOnlySetHasSamePrefix byte = 0b1000_0000
    1001             : 
    1002           1 : func decodeRestart(b []byte) int32 {
    1003           1 :         _ = b[3] // bounds check hint to compiler; see golang.org/issue/14808
    1004           1 :         return int32(uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 |
    1005           1 :                 uint32(b[3]&restartMaskLittleEndianHighByteWithoutSetHasSamePrefix)<<24)
    1006           1 : }
    1007             : 
    1008             : // Last implements internalIterator.Last, as documented in the pebble package.
    1009           1 : func (i *Iter) Last() *base.InternalKV {
    1010           1 :         if invariants.Enabled && i.IsDataInvalidated() {
    1011           0 :                 panic(errors.AssertionFailedf("invalidated blockIter used"))
    1012             :         }
    1013             : 
    1014             :         // Seek forward from the last restart point.
    1015           1 :         i.offset = decodeRestart(i.data[i.restarts+4*(i.numRestarts-1):])
    1016           1 :         if !i.Valid() {
    1017           1 :                 return nil
    1018           1 :         }
    1019             : 
    1020           1 :         i.readEntry()
    1021           1 :         i.clearCache()
    1022           1 : 
    1023           1 :         for i.nextOffset < i.restarts {
    1024           1 :                 i.cacheEntry()
    1025           1 :                 i.offset = i.nextOffset
    1026           1 :                 i.readEntry()
    1027           1 :         }
    1028             : 
    1029           1 :         hiddenPoint := i.decodeInternalKey(i.key)
    1030           1 :         if hiddenPoint {
    1031           1 :                 return i.Prev()
    1032           1 :         }
    1033           1 :         i.maybeReplaceSuffix()
    1034           1 :         if !i.lazyValueHandling.hasValuePrefix ||
    1035           1 :                 i.ikv.K.Kind() != base.InternalKeyKindSet {
    1036           1 :                 i.ikv.V = base.MakeInPlaceValue(i.val)
    1037           1 :         } else if i.lazyValueHandling.getValue == nil || !block.ValuePrefix(i.val[0]).IsValueHandle() {
    1038           1 :                 i.ikv.V = base.MakeInPlaceValue(i.val[1:])
    1039           1 :         } else {
    1040           1 :                 i.ikv.V = i.lazyValueHandling.getValue.GetLazyValueForPrefixAndValueHandle(i.val)
    1041           1 :         }
    1042           1 :         return &i.ikv
    1043             : }
    1044             : 
    1045             : // Next implements internalIterator.Next, as documented in the pebble
    1046             : // package.
    1047           1 : func (i *Iter) Next() *base.InternalKV {
    1048           1 :         if len(i.cachedBuf) > 0 {
    1049           1 :                 // We're switching from reverse iteration to forward iteration. We need to
    1050           1 :                 // populate i.fullKey with the current key we're positioned at so that
    1051           1 :                 // readEntry() can use i.fullKey for key prefix decompression. Note that we
    1052           1 :                 // don't know whether i.key is backed by i.cachedBuf or i.fullKey (if
    1053           1 :                 // SeekLT was the previous call, i.key may be backed by i.fullKey), but
    1054           1 :                 // copying into i.fullKey works for both cases.
    1055           1 :                 //
    1056           1 :                 // TODO(peter): Rather than clearing the cache, we could instead use the
    1057           1 :                 // cache until it is exhausted. This would likely be faster than falling
    1058           1 :                 // through to the normal forward iteration code below.
    1059           1 :                 i.fullKey = append(i.fullKey[:0], i.key...)
    1060           1 :                 i.clearCache()
    1061           1 :         }
    1062             : 
    1063             : start:
    1064           1 :         i.offset = i.nextOffset
    1065           1 :         if !i.Valid() {
    1066           1 :                 return nil
    1067           1 :         }
    1068           1 :         i.readEntry()
    1069           1 :         // Manually inlined version of i.decodeInternalKey(i.key).
    1070           1 :         if n := len(i.key) - 8; n >= 0 {
    1071           1 :                 trailer := base.InternalKeyTrailer(binary.LittleEndian.Uint64(i.key[n:]))
    1072           1 :                 hiddenPoint := i.transforms.HideObsoletePoints &&
    1073           1 :                         (trailer&TrailerObsoleteBit != 0)
    1074           1 :                 i.ikv.K.Trailer = trailer & TrailerObsoleteMask
    1075           1 :                 i.ikv.K.UserKey = i.key[:n:n]
    1076           1 :                 if n := i.transforms.SyntheticSeqNum; n != 0 {
    1077           1 :                         i.ikv.K.SetSeqNum(base.SeqNum(n))
    1078           1 :                 }
    1079           1 :                 if hiddenPoint {
    1080           1 :                         goto start
    1081             :                 }
    1082           1 :                 if i.transforms.HasSyntheticSuffix() {
    1083           1 :                         // Inlined version of i.maybeReplaceSuffix()
    1084           1 :                         prefixLen := i.split(i.ikv.K.UserKey)
    1085           1 :                         i.synthSuffixBuf = append(i.synthSuffixBuf[:0], i.ikv.K.UserKey[:prefixLen]...)
    1086           1 :                         i.synthSuffixBuf = append(i.synthSuffixBuf, i.transforms.SyntheticSuffix()...)
    1087           1 :                         i.ikv.K.UserKey = i.synthSuffixBuf
    1088           1 :                 }
    1089           0 :         } else {
    1090           0 :                 i.ikv.K.Trailer = base.InternalKeyTrailer(base.InternalKeyKindInvalid)
    1091           0 :                 i.ikv.K.UserKey = nil
    1092           0 :         }
    1093           1 :         if !i.lazyValueHandling.hasValuePrefix ||
    1094           1 :                 i.ikv.K.Kind() != base.InternalKeyKindSet {
    1095           1 :                 i.ikv.V = base.MakeInPlaceValue(i.val)
    1096           1 :         } else if i.lazyValueHandling.getValue == nil || !block.ValuePrefix(i.val[0]).IsValueHandle() {
    1097           1 :                 i.ikv.V = base.MakeInPlaceValue(i.val[1:])
    1098           1 :         } else {
    1099           1 :                 i.ikv.V = i.lazyValueHandling.getValue.GetLazyValueForPrefixAndValueHandle(i.val)
    1100           1 :         }
    1101           1 :         return &i.ikv
    1102             : }
    1103             : 
    1104             : // NextPrefix implements (base.InternalIterator).NextPrefix.
    1105           1 : func (i *Iter) NextPrefix(succKey []byte) *base.InternalKV {
    1106           1 :         if i.lazyValueHandling.hasValuePrefix {
    1107           1 :                 return i.nextPrefixV3(succKey)
    1108           1 :         }
    1109           1 :         const nextsBeforeSeek = 3
    1110           1 :         kv := i.Next()
    1111           1 :         for j := 1; kv != nil && i.cmp(kv.K.UserKey, succKey) < 0; j++ {
    1112           0 :                 if j >= nextsBeforeSeek {
    1113           0 :                         return i.SeekGE(succKey, base.SeekGEFlagsNone)
    1114           0 :                 }
    1115           0 :                 kv = i.Next()
    1116             :         }
    1117           1 :         return kv
    1118             : }
    1119             : 
    1120           1 : func (i *Iter) nextPrefixV3(succKey []byte) *base.InternalKV {
    1121           1 :         // Doing nexts that involve a key comparison can be expensive (and the cost
    1122           1 :         // depends on the key length), so we use the same threshold of 3 that we use
    1123           1 :         // for TableFormatPebblev2 in blockIter.nextPrefix above. The next fast path
    1124           1 :         // that looks at setHasSamePrefix takes ~5ns per key, which is ~150x faster
    1125           1 :         // than doing a SeekGE within the block, so we do this 16 times
    1126           1 :         // (~5ns*16=80ns), and then switch to looking at restarts. Doing the binary
    1127           1 :         // search for the restart consumes > 100ns. If the number of versions is >
    1128           1 :         // 17, we will increment nextFastCount to 17, then do a binary search, and
    1129           1 :         // on average need to find a key between two restarts, so another 8 steps
    1130           1 :         // corresponding to nextFastCount, for a mean total of 17 + 8 = 25 such
    1131           1 :         // steps.
    1132           1 :         //
    1133           1 :         // TODO(sumeer): use the configured restartInterval for the sstable when it
    1134           1 :         // was written (which we don't currently store) instead of the default value
    1135           1 :         // of 16.
    1136           1 :         const nextCmpThresholdBeforeSeek = 3
    1137           1 :         const nextFastThresholdBeforeRestarts = 16
    1138           1 :         nextCmpCount := 0
    1139           1 :         nextFastCount := 0
    1140           1 :         usedRestarts := false
    1141           1 :         // INVARIANT: blockIter is valid.
    1142           1 :         if invariants.Enabled && !i.Valid() {
    1143           0 :                 panic(errors.AssertionFailedf("nextPrefixV3 called on invalid blockIter"))
    1144             :         }
    1145           1 :         prevKeyIsSet := i.ikv.Kind() == base.InternalKeyKindSet
    1146           1 :         for {
    1147           1 :                 i.offset = i.nextOffset
    1148           1 :                 if !i.Valid() {
    1149           1 :                         return nil
    1150           1 :                 }
    1151             :                 // Need to decode the length integers, so we can compute nextOffset.
    1152           1 :                 ptr := unsafe.Pointer(uintptr(i.ptr) + uintptr(i.offset))
    1153           1 :                 // This is an ugly performance hack. Reading entries from blocks is one of
    1154           1 :                 // the inner-most routines and decoding the 3 varints per-entry takes
    1155           1 :                 // significant time. Neither go1.11 or go1.12 will inline decodeVarint for
    1156           1 :                 // us, so we do it manually. This provides a 10-15% performance improvement
    1157           1 :                 // on blockIter benchmarks on both go1.11 and go1.12.
    1158           1 :                 //
    1159           1 :                 // TODO(peter): remove this hack if go:inline is ever supported.
    1160           1 : 
    1161           1 :                 // Decode the shared key length integer.
    1162           1 :                 var shared uint32
    1163           1 :                 if a := *((*uint8)(ptr)); a < 128 {
    1164           1 :                         shared = uint32(a)
    1165           1 :                         ptr = unsafe.Pointer(uintptr(ptr) + 1)
    1166           1 :                 } else if a, b := a&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 1))); b < 128 {
    1167           0 :                         shared = uint32(b)<<7 | uint32(a)
    1168           0 :                         ptr = unsafe.Pointer(uintptr(ptr) + 2)
    1169           0 :                 } else if b, c := b&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 2))); c < 128 {
    1170           0 :                         shared = uint32(c)<<14 | uint32(b)<<7 | uint32(a)
    1171           0 :                         ptr = unsafe.Pointer(uintptr(ptr) + 3)
    1172           0 :                 } else if c, d := c&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 3))); d < 128 {
    1173           0 :                         shared = uint32(d)<<21 | uint32(c)<<14 | uint32(b)<<7 | uint32(a)
    1174           0 :                         ptr = unsafe.Pointer(uintptr(ptr) + 4)
    1175           0 :                 } else {
    1176           0 :                         d, e := d&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 4)))
    1177           0 :                         shared = uint32(e)<<28 | uint32(d)<<21 | uint32(c)<<14 | uint32(b)<<7 | uint32(a)
    1178           0 :                         ptr = unsafe.Pointer(uintptr(ptr) + 5)
    1179           0 :                 }
    1180             :                 // Decode the unshared key length integer.
    1181           1 :                 var unshared uint32
    1182           1 :                 if a := *((*uint8)(ptr)); a < 128 {
    1183           1 :                         unshared = uint32(a)
    1184           1 :                         ptr = unsafe.Pointer(uintptr(ptr) + 1)
    1185           1 :                 } else if a, b := a&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 1))); b < 128 {
    1186           0 :                         unshared = uint32(b)<<7 | uint32(a)
    1187           0 :                         ptr = unsafe.Pointer(uintptr(ptr) + 2)
    1188           0 :                 } else if b, c := b&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 2))); c < 128 {
    1189           0 :                         unshared = uint32(c)<<14 | uint32(b)<<7 | uint32(a)
    1190           0 :                         ptr = unsafe.Pointer(uintptr(ptr) + 3)
    1191           0 :                 } else if c, d := c&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 3))); d < 128 {
    1192           0 :                         unshared = uint32(d)<<21 | uint32(c)<<14 | uint32(b)<<7 | uint32(a)
    1193           0 :                         ptr = unsafe.Pointer(uintptr(ptr) + 4)
    1194           0 :                 } else {
    1195           0 :                         d, e := d&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 4)))
    1196           0 :                         unshared = uint32(e)<<28 | uint32(d)<<21 | uint32(c)<<14 | uint32(b)<<7 | uint32(a)
    1197           0 :                         ptr = unsafe.Pointer(uintptr(ptr) + 5)
    1198           0 :                 }
    1199             :                 // Decode the value length integer.
    1200           1 :                 var value uint32
    1201           1 :                 if a := *((*uint8)(ptr)); a < 128 {
    1202           1 :                         value = uint32(a)
    1203           1 :                         ptr = unsafe.Pointer(uintptr(ptr) + 1)
    1204           1 :                 } else if a, b := a&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 1))); b < 128 {
    1205           0 :                         value = uint32(b)<<7 | uint32(a)
    1206           0 :                         ptr = unsafe.Pointer(uintptr(ptr) + 2)
    1207           0 :                 } else if b, c := b&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 2))); c < 128 {
    1208           0 :                         value = uint32(c)<<14 | uint32(b)<<7 | uint32(a)
    1209           0 :                         ptr = unsafe.Pointer(uintptr(ptr) + 3)
    1210           0 :                 } else if c, d := c&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 3))); d < 128 {
    1211           0 :                         value = uint32(d)<<21 | uint32(c)<<14 | uint32(b)<<7 | uint32(a)
    1212           0 :                         ptr = unsafe.Pointer(uintptr(ptr) + 4)
    1213           0 :                 } else {
    1214           0 :                         d, e := d&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 4)))
    1215           0 :                         value = uint32(e)<<28 | uint32(d)<<21 | uint32(c)<<14 | uint32(b)<<7 | uint32(a)
    1216           0 :                         ptr = unsafe.Pointer(uintptr(ptr) + 5)
    1217           0 :                 }
    1218           1 :                 shared += i.transforms.SyntheticPrefixAndSuffix.PrefixLen()
    1219           1 :                 // The starting position of the value.
    1220           1 :                 valuePtr := unsafe.Pointer(uintptr(ptr) + uintptr(unshared))
    1221           1 :                 i.nextOffset = int32(uintptr(valuePtr)-uintptr(i.ptr)) + int32(value)
    1222           1 :                 if invariants.Enabled && unshared < 8 {
    1223           0 :                         // This should not happen since only the key prefix is shared, so even
    1224           0 :                         // if the prefix length is the same as the user key length, the unshared
    1225           0 :                         // will include the trailer.
    1226           0 :                         panic(errors.AssertionFailedf("unshared %d is too small", unshared))
    1227             :                 }
    1228             :                 // The trailer is written in little endian, so the key kind is the first
    1229             :                 // byte in the trailer that is encoded in the slice [unshared-8:unshared].
    1230           1 :                 keyKind := base.InternalKeyKind((*[manual.MaxArrayLen]byte)(ptr)[unshared-8])
    1231           1 :                 keyKind = keyKind & base.InternalKeyKindSSTableInternalObsoleteMask
    1232           1 :                 prefixChanged := false
    1233           1 :                 if keyKind == base.InternalKeyKindSet {
    1234           1 :                         if invariants.Enabled && value == 0 {
    1235           0 :                                 panic(errors.AssertionFailedf("value is of length 0, but we expect a valuePrefix"))
    1236             :                         }
    1237           1 :                         valPrefix := *((*block.ValuePrefix)(valuePtr))
    1238           1 :                         if valPrefix.SetHasSamePrefix() {
    1239           1 :                                 // Fast-path. No need to assemble i.fullKey, or update i.key. We know
    1240           1 :                                 // that subsequent keys will not have a shared length that is greater
    1241           1 :                                 // than the prefix of the current key, which is also the prefix of
    1242           1 :                                 // i.key. Since we are continuing to iterate, we don't need to
    1243           1 :                                 // initialize i.ikey and i.lazyValue (these are initialized before
    1244           1 :                                 // returning).
    1245           1 :                                 nextFastCount++
    1246           1 :                                 if nextFastCount > nextFastThresholdBeforeRestarts {
    1247           0 :                                         if usedRestarts {
    1248           0 :                                                 // Exhausted iteration budget. This will never happen unless
    1249           0 :                                                 // someone is using a restart interval > 16. It is just to guard
    1250           0 :                                                 // against long restart intervals causing too much iteration.
    1251           0 :                                                 break
    1252             :                                         }
    1253             :                                         // Haven't used restarts yet, so find the first restart at or beyond
    1254             :                                         // the current offset.
    1255           0 :                                         targetOffset := i.offset
    1256           0 :                                         var index int32
    1257           0 :                                         {
    1258           0 :                                                 // NB: manually inlined sort.Sort is ~5% faster.
    1259           0 :                                                 //
    1260           0 :                                                 // f defined for a restart point is true iff the offset >=
    1261           0 :                                                 // targetOffset.
    1262           0 :                                                 // Define f(-1) == false and f(i.numRestarts) == true.
    1263           0 :                                                 // Invariant: f(index-1) == false, f(upper) == true.
    1264           0 :                                                 upper := i.numRestarts
    1265           0 :                                                 for index < upper {
    1266           0 :                                                         h := int32(uint(index+upper) >> 1) // avoid overflow when computing h
    1267           0 :                                                         // index ≤ h < upper
    1268           0 :                                                         offset := decodeRestart(i.data[i.restarts+4*h:])
    1269           0 :                                                         if offset < targetOffset {
    1270           0 :                                                                 index = h + 1 // preserves f(index-1) == false
    1271           0 :                                                         } else {
    1272           0 :                                                                 upper = h // preserves f(upper) == true
    1273           0 :                                                         }
    1274             :                                                 }
    1275             :                                                 // index == upper, f(index-1) == false, and f(upper) (= f(index)) == true
    1276             :                                                 // => answer is index.
    1277             :                                         }
    1278           0 :                                         usedRestarts = true
    1279           0 :                                         nextFastCount = 0
    1280           0 :                                         if index == i.numRestarts {
    1281           0 :                                                 // Already past the last real restart, so iterate a bit more until
    1282           0 :                                                 // we are done with the block.
    1283           0 :                                                 continue
    1284             :                                         }
    1285             :                                         // Have some real restarts after index. NB: index is the first
    1286             :                                         // restart at or beyond the current offset.
    1287           0 :                                         startingIndex := index
    1288           0 :                                         for index != i.numRestarts &&
    1289           0 :                                                 // The restart at index is 4 bytes written in little endian format
    1290           0 :                                                 // starting at i.restart+4*index. The 0th byte is the least
    1291           0 :                                                 // significant and the 3rd byte is the most significant. Since the
    1292           0 :                                                 // most significant bit of the 3rd byte is what we use for
    1293           0 :                                                 // encoding the set-has-same-prefix information, the indexing
    1294           0 :                                                 // below has +3.
    1295           0 :                                                 i.data[i.restarts+4*index+3]&restartMaskLittleEndianHighByteOnlySetHasSamePrefix != 0 {
    1296           0 :                                                 // We still have the same prefix, so move to the next restart.
    1297           0 :                                                 index++
    1298           0 :                                         }
    1299             :                                         // index is the first restart that did not have the same prefix.
    1300           0 :                                         if index != startingIndex {
    1301           0 :                                                 // Managed to skip past at least one restart. Resume iteration
    1302           0 :                                                 // from index-1. Since nextFastCount has been reset to 0, we
    1303           0 :                                                 // should be able to iterate to the next prefix.
    1304           0 :                                                 i.offset = decodeRestart(i.data[i.restarts+4*(index-1):])
    1305           0 :                                                 i.readEntry()
    1306           0 :                                         }
    1307             :                                         // Else, unable to skip past any restart. Resume iteration. Since
    1308             :                                         // nextFastCount has been reset to 0, we should be able to iterate
    1309             :                                         // to the next prefix.
    1310           0 :                                         continue
    1311             :                                 }
    1312           1 :                                 continue
    1313           1 :                         } else if prevKeyIsSet {
    1314           1 :                                 prefixChanged = true
    1315           1 :                         }
    1316           1 :                 } else {
    1317           1 :                         prevKeyIsSet = false
    1318           1 :                 }
    1319             :                 // Slow-path cases:
    1320             :                 // - (Likely) The prefix has changed.
    1321             :                 // - (Unlikely) The prefix has not changed.
    1322             :                 // We assemble the key etc. under the assumption that it is the likely
    1323             :                 // case.
    1324           1 :                 unsharedKey := getBytes(ptr, int(unshared))
    1325           1 :                 // TODO(sumeer): move this into the else block below. This is a bit tricky
    1326           1 :                 // since the current logic assumes we have always copied the latest key
    1327           1 :                 // into fullKey, which is why when we get to the next key we can (a)
    1328           1 :                 // access i.fullKey[:shared], (b) append only the unsharedKey to
    1329           1 :                 // i.fullKey. For (a), we can access i.key[:shared] since that memory is
    1330           1 :                 // valid (even if unshared). For (b), we will need to remember whether
    1331           1 :                 // i.key refers to i.fullKey or not, and can append the unsharedKey only
    1332           1 :                 // in the former case and for the latter case need to copy the shared part
    1333           1 :                 // too. This same comment applies to the other place where we can do this
    1334           1 :                 // optimization, in readEntry().
    1335           1 :                 i.fullKey = append(i.fullKey[:shared], unsharedKey...)
    1336           1 :                 i.val = getBytes(valuePtr, int(value))
    1337           1 :                 if shared == 0 {
    1338           1 :                         // Provide stability for the key across positioning calls if the key
    1339           1 :                         // doesn't share a prefix with the previous key. This removes requiring the
    1340           1 :                         // key to be copied if the caller knows the block has a restart interval of
    1341           1 :                         // 1. An important example of this is range-del blocks.
    1342           1 :                         i.key = unsharedKey
    1343           1 :                 } else {
    1344           1 :                         i.key = i.fullKey
    1345           1 :                 }
    1346             :                 // Manually inlined version of i.decodeInternalKey(i.key).
    1347           1 :                 hiddenPoint := false
    1348           1 :                 if n := len(i.key) - 8; n >= 0 {
    1349           1 :                         trailer := base.InternalKeyTrailer(binary.LittleEndian.Uint64(i.key[n:]))
    1350           1 :                         hiddenPoint = i.transforms.HideObsoletePoints &&
    1351           1 :                                 (trailer&TrailerObsoleteBit != 0)
    1352           1 :                         i.ikv.K = base.InternalKey{
    1353           1 :                                 Trailer: trailer & TrailerObsoleteMask,
    1354           1 :                                 UserKey: i.key[:n:n],
    1355           1 :                         }
    1356           1 :                         if n := i.transforms.SyntheticSeqNum; n != 0 {
    1357           1 :                                 i.ikv.K.SetSeqNum(base.SeqNum(n))
    1358           1 :                         }
    1359           1 :                         if i.transforms.HasSyntheticSuffix() {
    1360           0 :                                 // Inlined version of i.maybeReplaceSuffix()
    1361           0 :                                 prefixLen := i.split(i.ikv.K.UserKey)
    1362           0 :                                 i.synthSuffixBuf = append(i.synthSuffixBuf[:0], i.ikv.K.UserKey[:prefixLen]...)
    1363           0 :                                 i.synthSuffixBuf = append(i.synthSuffixBuf, i.transforms.SyntheticSuffix()...)
    1364           0 :                                 i.ikv.K.UserKey = i.synthSuffixBuf
    1365           0 :                         }
    1366           0 :                 } else {
    1367           0 :                         i.ikv.K.Trailer = base.InternalKeyTrailer(base.InternalKeyKindInvalid)
    1368           0 :                         i.ikv.K.UserKey = nil
    1369           0 :                 }
    1370           1 :                 nextCmpCount++
    1371           1 :                 if invariants.Enabled && prefixChanged && i.cmp(i.ikv.K.UserKey, succKey) < 0 {
    1372           0 :                         panic(errors.AssertionFailedf("prefix should have changed but %x < %x",
    1373           0 :                                 i.ikv.K.UserKey, succKey))
    1374             :                 }
    1375           1 :                 if prefixChanged || i.cmp(i.ikv.K.UserKey, succKey) >= 0 {
    1376           1 :                         // Prefix has changed.
    1377           1 :                         if hiddenPoint {
    1378           1 :                                 return i.Next()
    1379           1 :                         }
    1380           1 :                         if invariants.Enabled && !i.lazyValueHandling.hasValuePrefix {
    1381           0 :                                 panic(errors.AssertionFailedf("nextPrefixV3 being run for non-v3 sstable"))
    1382             :                         }
    1383           1 :                         if i.ikv.K.Kind() != base.InternalKeyKindSet {
    1384           1 :                                 i.ikv.V = base.MakeInPlaceValue(i.val)
    1385           1 :                         } else if i.lazyValueHandling.getValue == nil || !block.ValuePrefix(i.val[0]).IsValueHandle() {
    1386           1 :                                 i.ikv.V = base.MakeInPlaceValue(i.val[1:])
    1387           1 :                         } else {
    1388           0 :                                 i.ikv.V = i.lazyValueHandling.getValue.GetLazyValueForPrefixAndValueHandle(i.val)
    1389           0 :                         }
    1390           1 :                         return &i.ikv
    1391             :                 }
    1392             :                 // Else prefix has not changed.
    1393             : 
    1394           1 :                 if nextCmpCount >= nextCmpThresholdBeforeSeek {
    1395           0 :                         break
    1396             :                 }
    1397             :         }
    1398           0 :         return i.SeekGE(succKey, base.SeekGEFlagsNone)
    1399             : }
    1400             : 
    1401             : // Prev implements internalIterator.Prev, as documented in the pebble
    1402             : // package.
    1403           1 : func (i *Iter) Prev() *base.InternalKV {
    1404           1 : start:
    1405           1 :         for n := len(i.cached) - 1; n >= 0; n-- {
    1406           1 :                 i.nextOffset = i.offset
    1407           1 :                 e := &i.cached[n]
    1408           1 :                 i.offset = e.offset
    1409           1 :                 i.val = getBytes(unsafe.Pointer(uintptr(i.ptr)+uintptr(e.valStart)), int(e.valSize))
    1410           1 :                 // Manually inlined version of i.decodeInternalKey(i.key).
    1411           1 :                 i.key = i.cachedBuf[e.keyStart:e.keyEnd]
    1412           1 :                 if n := len(i.key) - 8; n >= 0 {
    1413           1 :                         trailer := base.InternalKeyTrailer(binary.LittleEndian.Uint64(i.key[n:]))
    1414           1 :                         hiddenPoint := i.transforms.HideObsoletePoints &&
    1415           1 :                                 (trailer&TrailerObsoleteBit != 0)
    1416           1 :                         if hiddenPoint {
    1417           1 :                                 continue
    1418             :                         }
    1419           1 :                         i.ikv.K = base.InternalKey{
    1420           1 :                                 Trailer: trailer & TrailerObsoleteMask,
    1421           1 :                                 UserKey: i.key[:n:n],
    1422           1 :                         }
    1423           1 :                         if n := i.transforms.SyntheticSeqNum; n != 0 {
    1424           1 :                                 i.ikv.K.SetSeqNum(base.SeqNum(n))
    1425           1 :                         }
    1426           1 :                         if i.transforms.HasSyntheticSuffix() {
    1427           1 :                                 // Inlined version of i.maybeReplaceSuffix()
    1428           1 :                                 prefixLen := i.split(i.ikv.K.UserKey)
    1429           1 :                                 // If ikey is cached or may get cached, we must de-reference
    1430           1 :                                 // UserKey before suffix replacement.
    1431           1 :                                 i.synthSuffixBuf = append(i.synthSuffixBuf[:0], i.ikv.K.UserKey[:prefixLen]...)
    1432           1 :                                 i.synthSuffixBuf = append(i.synthSuffixBuf, i.transforms.SyntheticSuffix()...)
    1433           1 :                                 i.ikv.K.UserKey = i.synthSuffixBuf
    1434           1 :                         }
    1435           0 :                 } else {
    1436           0 :                         i.ikv.K.Trailer = base.InternalKeyTrailer(base.InternalKeyKindInvalid)
    1437           0 :                         i.ikv.K.UserKey = nil
    1438           0 :                 }
    1439           1 :                 i.cached = i.cached[:n]
    1440           1 :                 if !i.lazyValueHandling.hasValuePrefix ||
    1441           1 :                         i.ikv.K.Kind() != base.InternalKeyKindSet {
    1442           1 :                         i.ikv.V = base.MakeInPlaceValue(i.val)
    1443           1 :                 } else if i.lazyValueHandling.getValue == nil || !block.ValuePrefix(i.val[0]).IsValueHandle() {
    1444           1 :                         i.ikv.V = base.MakeInPlaceValue(i.val[1:])
    1445           1 :                 } else {
    1446           1 :                         i.ikv.V = i.lazyValueHandling.getValue.GetLazyValueForPrefixAndValueHandle(i.val)
    1447           1 :                 }
    1448           1 :                 return &i.ikv
    1449             :         }
    1450             : 
    1451           1 :         i.clearCache()
    1452           1 :         if i.offset <= 0 {
    1453           1 :                 i.offset = -1
    1454           1 :                 i.nextOffset = 0
    1455           1 :                 return nil
    1456           1 :         }
    1457             : 
    1458           1 :         targetOffset := i.offset
    1459           1 :         var index int32
    1460           1 : 
    1461           1 :         {
    1462           1 :                 // NB: manually inlined sort.Sort is ~5% faster.
    1463           1 :                 //
    1464           1 :                 // Define f(-1) == false and f(n) == true.
    1465           1 :                 // Invariant: f(index-1) == false, f(upper) == true.
    1466           1 :                 upper := i.numRestarts
    1467           1 :                 for index < upper {
    1468           1 :                         h := int32(uint(index+upper) >> 1) // avoid overflow when computing h
    1469           1 :                         // index ≤ h < upper
    1470           1 :                         offset := decodeRestart(i.data[i.restarts+4*h:])
    1471           1 :                         if offset < targetOffset {
    1472           1 :                                 // Looking for the first restart that has offset >= targetOffset, so
    1473           1 :                                 // ignore h and earlier.
    1474           1 :                                 index = h + 1 // preserves f(i-1) == false
    1475           1 :                         } else {
    1476           1 :                                 upper = h // preserves f(j) == true
    1477           1 :                         }
    1478             :                 }
    1479             :                 // index == upper, f(index-1) == false, and f(upper) (= f(index)) == true
    1480             :                 // => answer is index.
    1481             :         }
    1482             : 
    1483             :         // index is first restart with offset >= targetOffset. Note that
    1484             :         // targetOffset may not be at a restart point since one can call Prev()
    1485             :         // after Next() (so the cache was not populated) and targetOffset refers to
    1486             :         // the current entry. index-1 must have an offset < targetOffset (it can't
    1487             :         // be equal to targetOffset since the binary search would have selected that
    1488             :         // as the index).
    1489           1 :         i.offset = 0
    1490           1 :         if index > 0 {
    1491           1 :                 i.offset = decodeRestart(i.data[i.restarts+4*(index-1):])
    1492           1 :         }
    1493             :         // TODO(sumeer): why is the else case not an error given targetOffset is a
    1494             :         // valid offset.
    1495             : 
    1496           1 :         i.readEntry()
    1497           1 : 
    1498           1 :         // We stop when i.nextOffset == targetOffset since the targetOffset is the
    1499           1 :         // entry we are stepping back from, and we don't need to cache the entry
    1500           1 :         // before it, since it is the candidate to return.
    1501           1 :         for i.nextOffset < targetOffset {
    1502           1 :                 i.cacheEntry()
    1503           1 :                 i.offset = i.nextOffset
    1504           1 :                 i.readEntry()
    1505           1 :         }
    1506             : 
    1507           1 :         hiddenPoint := i.decodeInternalKey(i.key)
    1508           1 :         if hiddenPoint {
    1509           1 :                 // Use the cache.
    1510           1 :                 goto start
    1511             :         }
    1512           1 :         if i.transforms.HasSyntheticSuffix() {
    1513           1 :                 // Inlined version of i.maybeReplaceSuffix()
    1514           1 :                 prefixLen := i.split(i.ikv.K.UserKey)
    1515           1 :                 // If ikey is cached or may get cached, we must de-reference
    1516           1 :                 // UserKey before suffix replacement.
    1517           1 :                 i.synthSuffixBuf = append(i.synthSuffixBuf[:0], i.ikv.K.UserKey[:prefixLen]...)
    1518           1 :                 i.synthSuffixBuf = append(i.synthSuffixBuf, i.transforms.SyntheticSuffix()...)
    1519           1 :                 i.ikv.K.UserKey = i.synthSuffixBuf
    1520           1 :         }
    1521           1 :         if !i.lazyValueHandling.hasValuePrefix ||
    1522           1 :                 i.ikv.K.Kind() != base.InternalKeyKindSet {
    1523           1 :                 i.ikv.V = base.MakeInPlaceValue(i.val)
    1524           1 :         } else if i.lazyValueHandling.getValue == nil || !block.ValuePrefix(i.val[0]).IsValueHandle() {
    1525           1 :                 i.ikv.V = base.MakeInPlaceValue(i.val[1:])
    1526           1 :         } else {
    1527           1 :                 i.ikv.V = i.lazyValueHandling.getValue.GetLazyValueForPrefixAndValueHandle(i.val)
    1528           1 :         }
    1529           1 :         return &i.ikv
    1530             : }
    1531             : 
    1532             : // Key returns the internal key at the current iterator position.
    1533           0 : func (i *Iter) Key() *base.InternalKey {
    1534           0 :         return &i.ikv.K
    1535           0 : }
    1536             : 
    1537             : // KV returns the internal KV at the current iterator position.
    1538           1 : func (i *Iter) KV() *base.InternalKV {
    1539           1 :         return &i.ikv
    1540           1 : }
    1541             : 
    1542             : // Value returns the value at the current iterator position.
    1543           0 : func (i *Iter) Value() base.LazyValue {
    1544           0 :         return i.ikv.V
    1545           0 : }
    1546             : 
    1547             : // Error implements internalIterator.Error, as documented in the pebble
    1548             : // package.
    1549           1 : func (i *Iter) Error() error {
    1550           1 :         return nil // infallible
    1551           1 : }
    1552             : 
    1553             : // Close implements internalIterator.Close, as documented in the pebble
    1554             : // package.
    1555           1 : func (i *Iter) Close() error {
    1556           1 :         i.handle.Release()
    1557           1 :         fullKey := i.fullKey[:0]
    1558           1 :         cached := i.cached[:0]
    1559           1 :         cachedBuf := i.cachedBuf[:0]
    1560           1 :         firstUserKeyWithPrefixBuf := i.firstUserKeyWithPrefixBuf[:0]
    1561           1 :         *i = Iter{
    1562           1 :                 fullKey:                   fullKey,
    1563           1 :                 cached:                    cached,
    1564           1 :                 cachedBuf:                 cachedBuf,
    1565           1 :                 firstUserKeyWithPrefixBuf: firstUserKeyWithPrefixBuf,
    1566           1 :         }
    1567           1 :         return nil
    1568           1 : }
    1569             : 
    1570             : // SetBounds implements base.InternalIterator. It panics, as bounds should
    1571             : // always be handled the by the parent sstable iterator.
    1572           0 : func (i *Iter) SetBounds(lower, upper []byte) {
    1573           0 :         // This should never be called as bounds are handled by sstable.Iterator.
    1574           0 :         panic("pebble: SetBounds unimplemented")
    1575             : }
    1576             : 
    1577             : // SetContext implements base.InternalIterator.
    1578           0 : func (i *Iter) SetContext(_ context.Context) {}
    1579             : 
    1580             : // Valid returns true if the iterator is currently positioned at a valid KV.
    1581           1 : func (i *Iter) Valid() bool {
    1582           1 :         return i.offset >= 0 && i.offset < i.restarts
    1583           1 : }
    1584             : 
    1585             : // DebugTree is part of the InternalIterator interface.
    1586           0 : func (i *Iter) DebugTree(tp treeprinter.Node) {
    1587           0 :         tp.Childf("%T(%p)", i, i)
    1588           0 : }
    1589             : 
    1590           0 : func (i *Iter) getRestart(idx int) int32 {
    1591           0 :         return int32(binary.LittleEndian.Uint32(i.data[i.restarts+4*int32(idx):]))
    1592           0 : }
    1593             : 
    1594           0 : func (i *Iter) isRestartPoint() bool {
    1595           0 :         j := sort.Search(int(i.numRestarts), func(j int) bool {
    1596           0 :                 return i.getRestart(j) >= i.offset
    1597           0 :         })
    1598           0 :         return j < int(i.numRestarts) && i.getRestart(j) == i.offset
    1599             : }
    1600             : 
    1601             : // DescribeKV is a function that formats a key-value pair, writing the
    1602             : // description to w.
    1603             : type DescribeKV func(w io.Writer, key *base.InternalKey, val []byte, enc KVEncoding)
    1604             : 
    1605             : // KVEncoding describes the encoding of a key-value pair within the block.
    1606             : type KVEncoding struct {
    1607             :         // IsRestart is true if the key is a restart point.
    1608             :         IsRestart bool
    1609             :         // Offset is the position within the block at which the key-value pair is
    1610             :         // encoded.
    1611             :         Offset int32
    1612             :         // Length is the total length of the KV pair as it is encoded in the block
    1613             :         // format.
    1614             :         Length int32
    1615             :         // KeyShared is the number of bytes this KV's user key shared with its predecessor.
    1616             :         KeyShared uint32
    1617             :         // KeyUnshared is the number of bytes this KV's user key did not share with
    1618             :         // its predecessor.
    1619             :         KeyUnshared uint32
    1620             :         // ValueLen is the length of the internal value.
    1621             :         ValueLen uint32
    1622             : }
    1623             : 
    1624             : // Describe describes the contents of a block, writing the description to w.
    1625             : // It invokes fmtKV to describe each key-value pair.
    1626           0 : func (i *Iter) Describe(tp treeprinter.Node, fmtKV DescribeKV) {
    1627           0 :         var buf bytes.Buffer
    1628           0 :         for kv := i.First(); kv != nil; kv = i.Next() {
    1629           0 :                 enc := KVEncoding{
    1630           0 :                         IsRestart: i.isRestartPoint(),
    1631           0 :                         Offset:    i.offset,
    1632           0 :                         Length:    int32(i.nextOffset - i.offset),
    1633           0 :                 }
    1634           0 :                 ptr := unsafe.Pointer(uintptr(i.ptr) + uintptr(i.offset))
    1635           0 :                 enc.KeyShared, ptr = decodeVarint(ptr)
    1636           0 :                 enc.KeyUnshared, ptr = decodeVarint(ptr)
    1637           0 :                 enc.ValueLen, _ = decodeVarint(ptr)
    1638           0 :                 buf.Reset()
    1639           0 :                 fmtKV(&buf, &kv.K, kv.V.ValueOrHandle, enc)
    1640           0 :                 tp.Child(buf.String())
    1641           0 :         }
    1642             :         // Format the restart points.
    1643           0 :         n := tp.Child("restart points")
    1644           0 :         // Format the restart points.
    1645           0 :         for j := 0; j < int(i.numRestarts); j++ {
    1646           0 :                 offset := i.getRestart(j)
    1647           0 :                 n.Childf("%05d [restart %d]", uint64(i.restarts+4*int32(j)), offset)
    1648           0 :         }
    1649             : }
    1650             : 
    1651             : // RawIter is an iterator over a single block of data. Unlike blockIter,
    1652             : // keys are stored in "raw" format (i.e. not as internal keys). Note that there
    1653             : // is significant similarity between this code and the code in blockIter. Yet
    1654             : // reducing duplication is difficult due to the blockIter being performance
    1655             : // critical. RawIter must only be used for blocks where the value is
    1656             : // stored together with the key.
    1657             : type RawIter struct {
    1658             :         cmp         base.Compare
    1659             :         offset      int32
    1660             :         nextOffset  int32
    1661             :         restarts    int32
    1662             :         numRestarts int32
    1663             :         ptr         unsafe.Pointer
    1664             :         data        []byte
    1665             :         key, val    []byte
    1666             :         ikey        base.InternalKey
    1667             :         cached      []blockEntry
    1668             :         cachedBuf   []byte
    1669             : }
    1670             : 
    1671             : // NewRawIter constructs a new raw block iterator.
    1672           1 : func NewRawIter(cmp base.Compare, block []byte) (*RawIter, error) {
    1673           1 :         i := &RawIter{}
    1674           1 :         return i, i.Init(cmp, block)
    1675           1 : }
    1676             : 
    1677             : // Init initializes the raw block iterator.
    1678           1 : func (i *RawIter) Init(cmp base.Compare, blk []byte) error {
    1679           1 :         numRestarts := int32(binary.LittleEndian.Uint32(blk[len(blk)-4:]))
    1680           1 :         if numRestarts == 0 {
    1681           0 :                 return base.CorruptionErrorf("pebble/table: invalid table (block has no restart points)")
    1682           0 :         }
    1683           1 :         i.cmp = cmp
    1684           1 :         i.restarts = int32(len(blk)) - 4*(1+numRestarts)
    1685           1 :         i.numRestarts = numRestarts
    1686           1 :         i.ptr = unsafe.Pointer(&blk[0])
    1687           1 :         i.data = blk
    1688           1 :         if i.key == nil {
    1689           1 :                 i.key = make([]byte, 0, 256)
    1690           1 :         } else {
    1691           0 :                 i.key = i.key[:0]
    1692           0 :         }
    1693           1 :         i.val = nil
    1694           1 :         i.clearCache()
    1695           1 :         return nil
    1696             : }
    1697             : 
    1698           1 : func (i *RawIter) readEntry() {
    1699           1 :         ptr := unsafe.Pointer(uintptr(i.ptr) + uintptr(i.offset))
    1700           1 :         shared, ptr := decodeVarint(ptr)
    1701           1 :         unshared, ptr := decodeVarint(ptr)
    1702           1 :         value, ptr := decodeVarint(ptr)
    1703           1 :         i.key = append(i.key[:shared], getBytes(ptr, int(unshared))...)
    1704           1 :         i.key = i.key[:len(i.key):len(i.key)]
    1705           1 :         ptr = unsafe.Pointer(uintptr(ptr) + uintptr(unshared))
    1706           1 :         i.val = getBytes(ptr, int(value))
    1707           1 :         i.nextOffset = int32(uintptr(ptr)-uintptr(i.ptr)) + int32(value)
    1708           1 : }
    1709             : 
    1710           1 : func (i *RawIter) loadEntry() {
    1711           1 :         i.readEntry()
    1712           1 :         i.ikey.UserKey = i.key
    1713           1 : }
    1714             : 
    1715           1 : func (i *RawIter) clearCache() {
    1716           1 :         i.cached = i.cached[:0]
    1717           1 :         i.cachedBuf = i.cachedBuf[:0]
    1718           1 : }
    1719             : 
    1720           0 : func (i *RawIter) cacheEntry() {
    1721           0 :         var valStart int32
    1722           0 :         valSize := int32(len(i.val))
    1723           0 :         if valSize > 0 {
    1724           0 :                 valStart = int32(uintptr(unsafe.Pointer(&i.val[0])) - uintptr(i.ptr))
    1725           0 :         }
    1726             : 
    1727           0 :         i.cached = append(i.cached, blockEntry{
    1728           0 :                 offset:   i.offset,
    1729           0 :                 keyStart: int32(len(i.cachedBuf)),
    1730           0 :                 keyEnd:   int32(len(i.cachedBuf) + len(i.key)),
    1731           0 :                 valStart: valStart,
    1732           0 :                 valSize:  valSize,
    1733           0 :         })
    1734           0 :         i.cachedBuf = append(i.cachedBuf, i.key...)
    1735             : }
    1736             : 
    1737             : // SeekGE implements internalIterator.SeekGE, as documented in the pebble
    1738             : // package.
    1739           0 : func (i *RawIter) SeekGE(key []byte) bool {
    1740           0 :         // Find the index of the smallest restart point whose key is > the key
    1741           0 :         // sought; index will be numRestarts if there is no such restart point.
    1742           0 :         i.offset = 0
    1743           0 :         index := sort.Search(int(i.numRestarts), func(j int) bool {
    1744           0 :                 offset := int32(binary.LittleEndian.Uint32(i.data[int(i.restarts)+4*j:]))
    1745           0 :                 // For a restart point, there are 0 bytes shared with the previous key.
    1746           0 :                 // The varint encoding of 0 occupies 1 byte.
    1747           0 :                 ptr := unsafe.Pointer(uintptr(i.ptr) + uintptr(offset+1))
    1748           0 :                 // Decode the key at that restart point, and compare it to the key sought.
    1749           0 :                 v1, ptr := decodeVarint(ptr)
    1750           0 :                 _, ptr = decodeVarint(ptr)
    1751           0 :                 s := getBytes(ptr, int(v1))
    1752           0 :                 return i.cmp(key, s) < 0
    1753           0 :         })
    1754             : 
    1755             :         // Since keys are strictly increasing, if index > 0 then the restart point at
    1756             :         // index-1 will be the largest whose key is <= the key sought.  If index ==
    1757             :         // 0, then all keys in this block are larger than the key sought, and offset
    1758             :         // remains at zero.
    1759           0 :         if index > 0 {
    1760           0 :                 i.offset = int32(binary.LittleEndian.Uint32(i.data[int(i.restarts)+4*(index-1):]))
    1761           0 :         }
    1762           0 :         i.loadEntry()
    1763           0 : 
    1764           0 :         // Iterate from that restart point to somewhere >= the key sought.
    1765           0 :         for valid := i.Valid(); valid; valid = i.Next() {
    1766           0 :                 if i.cmp(key, i.key) <= 0 {
    1767           0 :                         break
    1768             :                 }
    1769             :         }
    1770           0 :         return i.Valid()
    1771             : }
    1772             : 
    1773             : // First implements internalIterator.First, as documented in the pebble
    1774             : // package.
    1775           1 : func (i *RawIter) First() bool {
    1776           1 :         i.offset = 0
    1777           1 :         i.loadEntry()
    1778           1 :         return i.Valid()
    1779           1 : }
    1780             : 
    1781             : // Last implements internalIterator.Last, as documented in the pebble package.
    1782           0 : func (i *RawIter) Last() bool {
    1783           0 :         // Seek forward from the last restart point.
    1784           0 :         i.offset = int32(binary.LittleEndian.Uint32(i.data[i.restarts+4*(i.numRestarts-1):]))
    1785           0 : 
    1786           0 :         i.readEntry()
    1787           0 :         i.clearCache()
    1788           0 :         i.cacheEntry()
    1789           0 : 
    1790           0 :         for i.nextOffset < i.restarts {
    1791           0 :                 i.offset = i.nextOffset
    1792           0 :                 i.readEntry()
    1793           0 :                 i.cacheEntry()
    1794           0 :         }
    1795             : 
    1796           0 :         i.ikey.UserKey = i.key
    1797           0 :         return i.Valid()
    1798             : }
    1799             : 
    1800             : // Next implements internalIterator.Next, as documented in the pebble
    1801             : // package.
    1802           1 : func (i *RawIter) Next() bool {
    1803           1 :         i.offset = i.nextOffset
    1804           1 :         if !i.Valid() {
    1805           1 :                 return false
    1806           1 :         }
    1807           1 :         i.loadEntry()
    1808           1 :         return true
    1809             : }
    1810             : 
    1811             : // Prev implements internalIterator.Prev, as documented in the pebble
    1812             : // package.
    1813           0 : func (i *RawIter) Prev() bool {
    1814           0 :         if n := len(i.cached) - 1; n > 0 && i.cached[n].offset == i.offset {
    1815           0 :                 i.nextOffset = i.offset
    1816           0 :                 e := &i.cached[n-1]
    1817           0 :                 i.offset = e.offset
    1818           0 :                 i.val = getBytes(unsafe.Pointer(uintptr(i.ptr)+uintptr(e.valStart)), int(e.valSize))
    1819           0 :                 i.ikey.UserKey = i.cachedBuf[e.keyStart:e.keyEnd]
    1820           0 :                 i.cached = i.cached[:n]
    1821           0 :                 return true
    1822           0 :         }
    1823             : 
    1824           0 :         if i.offset == 0 {
    1825           0 :                 i.offset = -1
    1826           0 :                 i.nextOffset = 0
    1827           0 :                 return false
    1828           0 :         }
    1829             : 
    1830           0 :         targetOffset := i.offset
    1831           0 :         index := sort.Search(int(i.numRestarts), func(j int) bool {
    1832           0 :                 offset := int32(binary.LittleEndian.Uint32(i.data[int(i.restarts)+4*j:]))
    1833           0 :                 return offset >= targetOffset
    1834           0 :         })
    1835           0 :         i.offset = 0
    1836           0 :         if index > 0 {
    1837           0 :                 i.offset = int32(binary.LittleEndian.Uint32(i.data[int(i.restarts)+4*(index-1):]))
    1838           0 :         }
    1839             : 
    1840           0 :         i.readEntry()
    1841           0 :         i.clearCache()
    1842           0 :         i.cacheEntry()
    1843           0 : 
    1844           0 :         for i.nextOffset < targetOffset {
    1845           0 :                 i.offset = i.nextOffset
    1846           0 :                 i.readEntry()
    1847           0 :                 i.cacheEntry()
    1848           0 :         }
    1849             : 
    1850           0 :         i.ikey.UserKey = i.key
    1851           0 :         return true
    1852             : }
    1853             : 
    1854             : // Key implements internalIterator.Key, as documented in the pebble package.
    1855           1 : func (i *RawIter) Key() base.InternalKey {
    1856           1 :         return i.ikey
    1857           1 : }
    1858             : 
    1859             : // Value implements internalIterator.Value, as documented in the pebble
    1860             : // package.
    1861           1 : func (i *RawIter) Value() []byte {
    1862           1 :         return i.val
    1863           1 : }
    1864             : 
    1865             : // Valid implements internalIterator.Valid, as documented in the pebble
    1866             : // package.
    1867           1 : func (i *RawIter) Valid() bool {
    1868           1 :         return i.offset >= 0 && i.offset < i.restarts
    1869           1 : }
    1870             : 
    1871             : // Error implements internalIterator.Error, as documented in the pebble
    1872             : // package.
    1873           0 : func (i *RawIter) Error() error {
    1874           0 :         return nil
    1875           0 : }
    1876             : 
    1877             : // Close implements internalIterator.Close, as documented in the pebble
    1878             : // package.
    1879           1 : func (i *RawIter) Close() error {
    1880           1 :         i.val = nil
    1881           1 :         return nil
    1882           1 : }
    1883             : 
    1884             : // DebugTree is part of the InternalIterator interface.
    1885           0 : func (i *RawIter) DebugTree(tp treeprinter.Node) {
    1886           0 :         tp.Childf("%T(%p)", i, i)
    1887           0 : }
    1888             : 
    1889           0 : func (i *RawIter) getRestart(idx int) int32 {
    1890           0 :         return int32(binary.LittleEndian.Uint32(i.data[i.restarts+4*int32(idx):]))
    1891           0 : }
    1892             : 
    1893           0 : func (i *RawIter) isRestartPoint() bool {
    1894           0 :         j := sort.Search(int(i.numRestarts), func(j int) bool {
    1895           0 :                 return i.getRestart(j) >= i.offset
    1896           0 :         })
    1897           0 :         return j < int(i.numRestarts) && i.getRestart(j) == i.offset
    1898             : }
    1899             : 
    1900             : // Describe describes the contents of a block, writing the description to w.
    1901             : // It invokes fmtKV to describe each key-value pair.
    1902           0 : func (i *RawIter) Describe(tp treeprinter.Node, fmtKV DescribeKV) {
    1903           0 :         var buf bytes.Buffer
    1904           0 :         for valid := i.First(); valid; valid = i.Next() {
    1905           0 :                 enc := KVEncoding{
    1906           0 :                         IsRestart: i.isRestartPoint(),
    1907           0 :                         Offset:    i.offset,
    1908           0 :                         Length:    int32(i.nextOffset - i.offset),
    1909           0 :                 }
    1910           0 :                 ptr := unsafe.Pointer(uintptr(i.ptr) + uintptr(i.offset))
    1911           0 :                 enc.KeyShared, ptr = decodeVarint(ptr)
    1912           0 :                 enc.KeyUnshared, ptr = decodeVarint(ptr)
    1913           0 :                 enc.ValueLen, _ = decodeVarint(ptr)
    1914           0 :                 buf.Reset()
    1915           0 :                 fmtKV(&buf, &i.ikey, i.val, enc)
    1916           0 :                 if i.isRestartPoint() {
    1917           0 :                         buf.WriteString(" [restart]")
    1918           0 :                 }
    1919           0 :                 tp.Child(buf.String())
    1920             :         }
    1921           0 :         n := tp.Child("restart points")
    1922           0 :         // Format the restart points.
    1923           0 :         for j := 0; j < int(i.numRestarts); j++ {
    1924           0 :                 offset := i.getRestart(j)
    1925           0 :                 n.Childf("%05d [restart %d]", uint64(i.restarts+4*int32(j)), offset)
    1926           0 :         }
    1927             : }
    1928             : 
    1929           1 : func getBytes(ptr unsafe.Pointer, length int) []byte {
    1930           1 :         return (*[manual.MaxArrayLen]byte)(ptr)[:length:length]
    1931           1 : }
    1932             : 
    1933           1 : func decodeVarint(ptr unsafe.Pointer) (uint32, unsafe.Pointer) {
    1934           1 :         if a := *((*uint8)(ptr)); a < 128 {
    1935           1 :                 return uint32(a),
    1936           1 :                         unsafe.Pointer(uintptr(ptr) + 1)
    1937           1 :         } else if a, b := a&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 1))); b < 128 {
    1938           0 :                 return uint32(b)<<7 | uint32(a),
    1939           0 :                         unsafe.Pointer(uintptr(ptr) + 2)
    1940           0 :         } else if b, c := b&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 2))); c < 128 {
    1941           0 :                 return uint32(c)<<14 | uint32(b)<<7 | uint32(a),
    1942           0 :                         unsafe.Pointer(uintptr(ptr) + 3)
    1943           0 :         } else if c, d := c&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 3))); d < 128 {
    1944           0 :                 return uint32(d)<<21 | uint32(c)<<14 | uint32(b)<<7 | uint32(a),
    1945           0 :                         unsafe.Pointer(uintptr(ptr) + 4)
    1946           0 :         } else {
    1947           0 :                 d, e := d&0x7f, *((*uint8)(unsafe.Pointer(uintptr(ptr) + 4)))
    1948           0 :                 return uint32(e)<<28 | uint32(d)<<21 | uint32(c)<<14 | uint32(b)<<7 | uint32(a),
    1949           0 :                         unsafe.Pointer(uintptr(ptr) + 5)
    1950           0 :         }
    1951             : }

Generated by: LCOV version 1.14