forked from ngaut/unistore
/
block_iter.go
104 lines (84 loc) · 2.11 KB
/
block_iter.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
// Copyright 2019-present PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// See the License for the specific language governing permissions and
// limitations under the License.
package rocksdb
type blockIterator struct {
data []byte
cursor int
invalid bool
keyBuf []byte
valueBuf []byte
}
func newBlockIterator(block []byte) *blockIterator {
it := new(blockIterator)
it.Reset(block)
return it
}
func (it *blockIterator) SeekToFirst() {
it.Rewind()
it.Next()
}
func (it *blockIterator) Rewind() {
it.cursor = 0
}
func (it *blockIterator) Next() {
if it.end() {
it.invalid = true
return
}
var prefixLen, keyLen, valueLen uint32
var n int
if prefixLen, n = decodeVarint32(it.currData()); n <= 0 {
it.invalid = true
return
}
it.cursor += n
if keyLen, n = decodeVarint32(it.currData()); n <= 0 {
it.invalid = true
return
}
it.cursor += n
if valueLen, n = decodeVarint32(it.currData()); n <= 0 {
it.invalid = true
return
}
it.cursor += n
it.keyBuf = append(it.keyBuf[:prefixLen], it.currData()[:keyLen]...)
it.cursor += int(keyLen)
it.valueBuf = append(it.valueBuf[:0], it.currData()[:valueLen]...)
it.cursor += int(valueLen)
}
func (it *blockIterator) Key() []byte {
return it.keyBuf
}
func (it *blockIterator) Value() []byte {
return it.valueBuf
}
func (it *blockIterator) Valid() bool {
return !it.invalid
}
func (it *blockIterator) Reset(block []byte) {
numRestarts := rocksEndian.Uint32(block[len(block)-4:])
restartsSz := int(numRestarts*4 + 4)
data := block[:len(block)-restartsSz]
it.data = data
it.cursor = 0
it.invalid = false
it.keyBuf = it.keyBuf[:0]
it.valueBuf = it.valueBuf[:0]
}
func (it *blockIterator) currData() []byte {
return it.data[it.cursor:]
}
func (it *blockIterator) end() bool {
return it.cursor == len(it.data)
}