forked from colinmarc/sequencefile
-
Notifications
You must be signed in to change notification settings - Fork 0
/
block.go
147 lines (119 loc) · 2.43 KB
/
block.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
package sequencefile
import (
"bytes"
"errors"
"io"
)
// a blockReader represents an iterator over a single compressed block, for
// block-compressed SequenceFiles.
type blockReader struct {
n int
i int
key []byte
value []byte
err error
keys []byte
keyLengths []int
keyOffset int
values []byte
valueLengths []int
valueOffset int
}
func (b *blockReader) next() bool {
if b.i >= b.n {
return false
}
keyLength := b.keyLengths[b.i]
b.key = b.keys[b.keyOffset : b.keyOffset+keyLength]
b.keyOffset += keyLength
if b.values != nil {
valueLength := b.valueLengths[b.i]
b.value = b.values[b.valueOffset : b.valueOffset+valueLength]
b.valueOffset += valueLength
}
b.i++
return true
}
func (r *Reader) scanBlock() bool {
for !r.block.next() {
err := r.startBlock()
if err == io.EOF {
return false
} else if err != nil {
r.close(err)
return false
}
}
r.key = r.block.key
r.value = r.block.value
return true
}
func (r *Reader) startBlock() error {
// The sync appears at the start of every block, but it still has the -1
// length prefix in front, just for funsies.
r.clear()
_, err := r.consume(4)
if err != nil {
return err
}
err = r.checkSync()
if err != nil {
return err
}
n, err := ReadVInt(r.reader)
if err != nil {
return err
}
block := blockReader{n: int(n)}
r.clear()
keyLengthsBytes, err := r.consumeSection()
if err != nil {
return err
}
block.keyLengths, err = readLengths(keyLengthsBytes, int(n))
if err != nil {
return err
}
block.keys, err = r.consumeSection()
if err != nil {
return err
}
valueLengthsBytes, err := r.consumeSection()
if err != nil {
return err
}
block.valueLengths, err = readLengths(valueLengthsBytes, int(n))
if err != nil {
return err
}
block.values, err = r.consumeSection()
if err != nil {
return err
}
r.block = block
return nil
}
func (r *Reader) consumeSection() ([]byte, error) {
length, err := ReadVInt(r.reader)
if err != nil {
return nil, err
}
return r.consumeCompressed(int(length))
}
func readLengths(b []byte, n int) ([]int, error) {
buf := bytes.NewBuffer(b)
res := make([]int, 0, n)
for i := 0; i < n; i++ {
vint, err := ReadVInt(buf)
if err == io.EOF {
return nil, io.ErrUnexpectedEOF
} else if err != nil {
return nil, err
}
res = append(res, int(vint))
}
if buf.Len() != 0 {
return nil, errors.New("sequencefile: invalid lengths for block")
}
return res, nil
}