This repository has been archived by the owner on Jan 10, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
reader.go
403 lines (331 loc) · 9.2 KB
/
reader.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
package sntable
import (
"bytes"
"encoding/binary"
"io"
"sort"
"sync"
"github.com/golang/snappy"
)
// Reader instances can seek and iterate across data in tables.
type Reader struct {
r io.ReaderAt
index []blockInfo
maxOffset int64
}
// NewReader opens a reader.
func NewReader(r io.ReaderAt, size int64) (*Reader, error) {
tmp := make([]byte, 16+binary.MaxVarintLen64)
// read footer
footerOffset := size - 16
if _, err := r.ReadAt(tmp[:16], footerOffset); err != nil {
return nil, err
}
// parse footer
if !bytes.Equal(tmp[8:16], magic) {
return nil, errBadMagic
}
indexOffset := int64(binary.LittleEndian.Uint64(tmp[:8]))
// read index
var index []blockInfo
var info blockInfo
for pos := indexOffset; pos < footerOffset; {
tmp = tmp[:2*binary.MaxVarintLen64]
if x := footerOffset - pos; x < int64(len(tmp)) {
tmp = tmp[:int(x)]
}
_, err := r.ReadAt(tmp, pos)
if err != nil {
return nil, err
}
u1, n := binary.Uvarint(tmp[0:])
pos += int64(n)
u2, n := binary.Uvarint(tmp[n:])
pos += int64(n)
info.MaxKey += u1
info.Offset += int64(u2)
index = append(index, info)
}
return &Reader{
r: r,
index: index, // block offsets
maxOffset: indexOffset,
}, nil
}
// NumBlocks returns the number of stored blocks.
func (r *Reader) NumBlocks() int {
return len(r.index)
}
// Append retrieves a single value for a key. Unlike Get it doesn't
// appends it to dst instead of allocating a new byte slice.
// It may return an ErrNotFound error.
func (r *Reader) Append(dst []byte, key uint64) ([]byte, error) {
iter, err := r.Seek(key)
if err != nil {
return dst, err
}
defer iter.Release()
if !iter.Next() || iter.Key() != key {
return dst, ErrNotFound
}
return append(dst, iter.Value()...), nil
}
// Get is a shortcut for Append(nil, key).
// It may return an ErrNotFound error.
func (r *Reader) Get(key uint64) ([]byte, error) {
return r.Append(nil, key)
}
// Seek returns an iterator starting at the position >= key.
func (r *Reader) Seek(key uint64) (*Iterator, error) {
b, err := r.SeekBlock(key)
if err != nil {
return nil, err
}
s := b.SeekSection(key)
s.Seek(key)
return &Iterator{r: r, b: b, s: s}, nil
}
// GetBlock returns a reader for the n-th block.
func (r *Reader) GetBlock(bpos int) (*BlockReader, error) {
if len(r.index) == 0 {
return &BlockReader{}, nil
}
if bpos < 0 {
bpos = 0
}
if bpos >= len(r.index) {
return &BlockReader{
bpos: len(r.index),
}, nil
}
return r.readBlock(bpos)
}
// SeekBlock seeks the block containing the key.
func (r *Reader) SeekBlock(key uint64) (*BlockReader, error) {
bpos := sort.Search(len(r.index), func(i int) bool {
return r.index[i].MaxKey >= key
})
return r.GetBlock(bpos)
}
func (r *Reader) readBlock(bpos int) (*BlockReader, error) {
min := r.index[bpos].Offset
max := r.maxOffset
if next := bpos + 1; next < len(r.index) {
max = r.index[next].Offset
}
raw := fetchBuffer(int(max - min))
if _, err := r.r.ReadAt(raw, min); err != nil {
releaseBuffer(raw)
return nil, err
}
var block []byte
switch cBitPos := len(raw) - 1; raw[cBitPos] {
case blockNoCompression:
block = raw[:cBitPos]
case blockSnappyCompression:
defer releaseBuffer(raw)
sz, err := snappy.DecodedLen(raw[:cBitPos])
if err != nil {
return nil, err
}
plain := fetchBuffer(sz)
if block, err = snappy.Decode(plain, raw[:cBitPos]); err != nil {
releaseBuffer(plain)
return nil, err
}
default:
releaseBuffer(raw)
return nil, errBadCompression
}
return &BlockReader{
block: block,
bpos: bpos,
scnt: int(binary.LittleEndian.Uint32(block[len(block)-4:])),
maxKey: r.index[bpos].MaxKey,
}, nil
}
// --------------------------------------------------------------------
// BlockReader reads a single block.
type BlockReader struct {
block []byte
bpos int // the current block position
scnt int // the section count
maxKey uint64
}
// NumSections returns the number of sections in this block.
func (r *BlockReader) NumSections() int { return r.scnt }
// Pos returns the index position the current block within the table.
func (r *BlockReader) Pos() int { return r.bpos }
// GetSection gets a single section.
func (r *BlockReader) GetSection(spos int) *SectionReader {
if spos < 0 {
spos = 0
}
if spos >= r.scnt {
return newSectionReader(r.scnt, nil)
}
min := r.sectionOffset(spos)
max := r.sectionOffset(spos + 1)
return newSectionReader(spos, r.block[min:max])
}
// SeekSection seeks the section for a key.
func (r *BlockReader) SeekSection(key uint64) *SectionReader {
if key > r.maxKey {
return r.GetSection(r.scnt)
}
spos := sort.Search(r.scnt, func(i int) bool {
off := r.sectionOffset(i)
first, _ := binary.Uvarint(r.block[off:]) // first key of the section
return first > key
}) - 1
return r.GetSection(spos)
}
// Release releases the block reader and frees up resources. The reader must not be used
// after this method is called.
func (r *BlockReader) Release() { bufPool.Put(r.block) }
// The starting offset of the section within the block.
func (r *BlockReader) sectionOffset(spos int) int {
if spos < 1 {
return 0
} else if spos >= r.scnt {
return len(r.block) - r.scnt*4
} else {
nn := len(r.block) - r.scnt*4 + (spos-1)*4
return int(binary.LittleEndian.Uint32(r.block[nn:]))
}
}
var sectionReaderPool sync.Pool
// SectionReader reads an individual section within a block.
type SectionReader struct {
section []byte
spos int // the section
read int // bytes read
key uint64 // current key
val []byte // current value
}
func newSectionReader(spos int, section []byte) *SectionReader {
if v := sectionReaderPool.Get(); v != nil {
sr := v.(*SectionReader)
*sr = SectionReader{spos: spos, section: section}
return sr
}
return &SectionReader{spos: spos, section: section}
}
// Seek positions the cursor before the key.
func (r *SectionReader) Seek(key uint64) bool {
for r.More() {
inc, n := binary.Uvarint(r.section[r.read:])
r.read += n
r.key += inc
if r.key >= key {
r.read -= n
r.key -= inc
return true
}
if r.More() {
vln, n := binary.Uvarint(r.section[r.read:])
r.read += n
r.val = r.section[r.read : r.read+int(vln)]
r.read += int(vln)
}
}
return false
}
// Pos returns the index position the current section within the block.
func (r *SectionReader) Pos() int { return r.spos }
// Key returns the key if the current entry.
func (r *SectionReader) Key() uint64 { return r.key }
// Value returns the value of the current entry. Please note that values
// are temporary buffers and must be copied if used beyond the next cursor move.
func (r *SectionReader) Value() []byte { return r.val }
// More returns true if more data can be read in the section.
func (r *SectionReader) More() bool { return r.read < len(r.section) }
// Next advances the cursor to the next entry within the section and
// returns true if successful.
func (r *SectionReader) Next() bool {
if r.More() {
inc, n := binary.Uvarint(r.section[r.read:])
r.read += n
r.key += inc
}
if r.More() {
vln, n := binary.Uvarint(r.section[r.read:])
r.read += n
r.val = r.section[r.read : r.read+int(vln)]
r.read += int(vln)
return true
}
return false
}
// Release releases the section reader and frees up resources. The reader must not be used
// after this method is called.
func (r *SectionReader) Release() { sectionReaderPool.Put(r) }
// --------------------------------------------------------------------
// Iterator is a convenience wrapper around BlockReader and SectionReader
// which can (forward-) iterate over keys across block and section boundaries.
type Iterator struct {
r *Reader
b *BlockReader
s *SectionReader
err error
}
// Key returns the key if the current entry.
func (i *Iterator) Key() uint64 { return i.s.Key() }
// Value returns the value of the current entry. Please note that values
// are temporary buffers and must be copied if used beyond the next cursor move.
func (i *Iterator) Value() []byte { return i.s.Value() }
// More returns true if more data can be read.
func (i *Iterator) More() bool {
if i.err != nil {
return false
}
return i.s.More() || i.s.Pos()+1 < i.b.NumSections() || i.b.Pos()+1 < i.r.NumBlocks()
}
// Next advances the cursor to the next entry and returns true if successful.
func (i *Iterator) Next() bool {
if i.err != nil {
return false
}
// more entries in the section
if i.s.More() {
return i.s.Next()
}
// more sections in the block
if n := i.s.Pos() + 1; n < i.b.NumSections() {
i.s = i.b.GetSection(n)
return i.s.Next()
}
// more blocks
if n := i.b.Pos() + 1; n < i.r.NumBlocks() {
i.b, i.err = i.r.GetBlock(n)
i.s = i.b.GetSection(0)
return i.s.Next()
}
return false
}
// Err exposes iterator errors, if any.
func (i *Iterator) Err() error {
return i.err
}
// Release releases the iterator and frees up resources. The iterator must not be used
// after this method is called.
func (i *Iterator) Release() {
i.b.Release()
i.s.Release()
i.err = errReleased
}
// --------------------------------------------------------------------
var bufPool sync.Pool
func fetchBuffer(sz int) []byte {
if v := bufPool.Get(); v != nil {
if p := v.([]byte); sz <= cap(p) {
return p[:sz]
}
}
return make([]byte, sz)
}
func releaseBuffer(p []byte) {
if cap(p) != 0 {
bufPool.Put(p)
}
}