-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsearcher.go
286 lines (251 loc) · 7.54 KB
/
searcher.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
/*
bsearch provides binary search functionality for line-ordered byte streams
by prefix (e.g. for searching `LC_ALL=C` sorted text files).
TODO: can we change the comparison function to support UTF-8 ordered keys?
e.g. BytesEqual, StringEqual, BytesLessEqual, StringLessEqual
*/
package bsearch
import (
"bytes"
"errors"
"io"
"os"
"path/filepath"
"regexp"
"github.com/rs/zerolog"
"launchpad.net/gommap"
)
var (
ErrFileNotFound = errors.New("filepath not found")
ErrNotFile = errors.New("filepath exists but is not a file")
ErrFileCompressed = errors.New("filepath exists but is compressed")
ErrNotFound = errors.New("key not found")
ErrKeyExceedsBlocksize = errors.New("key length exceeds blocksize")
ErrUnknownDelimiter = errors.New("cannot guess delimiter from filename")
reCompressedUnsupported = regexp.MustCompile(`\.(zst|gz|bz2|xz|zip)$`)
)
// SearcherOptions struct for use with NewSearcherOptions
type SearcherOptions struct {
MatchLE bool // use less-than-or-equal-to match semantics
Logger *zerolog.Logger // debug logger
// Index options (used to check index or build new one)
Delimiter []byte // delimiter separating fields in dataset
Header bool // first line of dataset is header and should be ignored
}
// Searcher provides binary search functionality on byte-ordered CSV-style
// delimited text files.
type Searcher struct {
r io.ReaderAt // data reader
l int64 // data length
mmap []byte // data mmap
filepath string // filename path
Index *Index // bsearch index
matchLE bool // LinePosition uses less-than-or-equal-to match semantics
logger *zerolog.Logger // debug logger
}
//buf []byte // data buffer
//bufOffset int64 // data buffer offset
//dbuf []byte // decompressed data buffer
//dbufOffset int64 // decompressed data buffer offset
// setOptions sets the given options on searcher
func (s *Searcher) setOptions(options SearcherOptions) {
if options.MatchLE {
s.matchLE = true
}
if options.Logger != nil {
s.logger = options.Logger
}
}
// NewSearcher returns a new Searcher for path using default options.
// The caller is responsible for calling *Searcher.Close() when finished.
func NewSearcher(path string) (*Searcher, error) {
return NewSearcherOptions(path, SearcherOptions{})
}
// NewSearcherOptions returns a new Searcher for path using opt.
// The caller is responsible for calling *Searcher.Close() when finished.
func NewSearcherOptions(path string, opt SearcherOptions) (*Searcher, error) {
path, err := filepath.Abs(path)
if err != nil {
return nil, err
}
// Get file length and epoch
stat, err := os.Stat(path)
if err != nil {
if os.IsNotExist(err) {
return nil, ErrFileNotFound
}
return nil, err
}
if stat.IsDir() {
return nil, ErrNotFile
}
filesize := stat.Size()
// Open file
rdr, err := os.Open(path)
if err != nil {
return nil, err
}
// Mmap file
mmap, err := gommap.Map(rdr.Fd(), gommap.PROT_READ, gommap.MAP_PRIVATE)
if err != nil {
return nil, err
}
s := Searcher{
r: rdr,
l: filesize,
mmap: mmap,
filepath: path,
}
//buf: nil,
//bufOffset: -1,
//dbufOffset: -1,
s.setOptions(opt)
// Load index
s.Index, err = LoadIndex(path)
if err != nil {
return nil, err
}
return &s, nil
}
func getNBytesFrom(buf []byte, length int, delim []byte) []byte {
segment := buf[:length]
// If segment includes a delimiter, truncate it there
if d := bytes.Index(segment, delim); d > -1 {
return segment[:d]
}
return segment
}
// scanLinesWithKey returns the first n lines beginning with key from buf.
func (s *Searcher) scanLinesWithKey(buf, key []byte, n int) [][]byte {
// This differs from the old scanLinesMatching in that it assumes
// that buf contains *all* lines we might need, rather than just
// an initial block.
var lines [][]byte
// Skip lines with a key < ours
keyde := append(key, s.Index.Delimiter...)
offset := 0
for offset < len(buf) {
// If buf is out of space, we're done
if len(buf)-offset < len(key) {
return lines
}
k := getNBytesFrom(buf[offset:], len(key), s.Index.Delimiter)
if bytes.Compare(k, key) > -1 {
break
}
nlidx := bytes.IndexByte(buf[offset:], '\n')
if nlidx == -1 {
// If no new newline is found, there are no more lines to check
return lines
}
offset += nlidx + 1
}
// Collate up to n lines beginning with keyde
for offset < len(buf) && bytes.HasPrefix(buf[offset:], keyde) {
nlidx := bytes.IndexByte(buf[offset:], '\n')
if nlidx == -1 {
// If no newline found, read to end of buf
nlidx = len(buf) - offset
}
lines = append(lines, clonebs(buf[offset:offset+nlidx]))
if n > 0 && len(lines) >= n {
break
}
offset += nlidx + 1
}
return lines
}
// scanIndexedLines returns the first n lines from reader that begin with key.
// Returns a slice of byte slices on success.
func (s *Searcher) scanIndexedLines(key []byte, n int) ([][]byte, error) {
var lines [][]byte
var entry IndexEntry
var e int
var err error
if s.Index.KeysIndexFirst {
// If index entries always have the first instance of a key, we
// can use the more efficient less-than-or-equal-to block lookup
e, entry, err = s.Index.blockEntryLE(key)
if err != nil {
return lines, err
}
} else {
e, entry = s.Index.blockEntryLT(key)
}
if s.logger != nil {
blockEntry := "blockEntryLT"
if s.Index.KeysIndexFirst {
blockEntry = "blockEntryLE"
}
s.logger.Trace().
Bytes("key", key).
Int("entryIndex", e).
Str("entry.Key", entry.Key).
Int64("entry.Offset", entry.Offset).
//Int64("entry.Length", entry.Length).
Str("blockEntry", blockEntry).
Msg("scanIndexedLines blockEntryXX returned")
}
lines = s.scanLinesWithKey(s.mmap[entry.Offset:], key, n)
if len(lines) == 0 {
return lines, ErrNotFound
}
return lines, nil
}
// Line returns the first line in the reader that begins with key,
// using a binary search (data must be bytewise-ordered).
func (s *Searcher) Line(key []byte) ([]byte, error) {
lines, err := s.LinesN(key, 1)
if err != nil || len(lines) < 1 {
return []byte{}, err
}
return lines[0], nil
}
// Lines returns all lines in the reader that begin with the byte
// slice b, using a binary search (data must be bytewise-ordered).
func (s *Searcher) Lines(b []byte) ([][]byte, error) {
return s.LinesN(b, 0)
}
// LinesN returns the first n lines in the reader that begin with key,
// using a binary search (data must be bytewise-ordered).
func (s *Searcher) LinesN(key []byte, n int) ([][]byte, error) {
// If keys are unique max(n) is 1
if n == 0 && s.Index.KeysUnique {
n = 1
}
// If no index exists, build and use a temporary one (but don't write)
if s.Index == nil {
index, err := NewIndex(s.filepath)
if err != nil {
return [][]byte{}, err
}
s.Index = index
}
return s.scanIndexedLines(key, n)
}
// Close closes the searcher's reader (if applicable)
func (s *Searcher) Close() {
if closer, ok := s.r.(io.Closer); ok {
closer.Close()
}
}
// prefixCompare compares the initial sequence of bufa matches b
// (up to len(b) only).
func prefixCompare(bufa, b []byte) int {
// If len(bufa) < len(b) we compare up to len(bufa), but disallow equality
if len(bufa) < len(b) {
cmp := bytes.Compare(bufa, b[:len(bufa)])
if cmp == 0 {
// An equal match here is short, so actually a less than
return -1
}
return cmp
}
return bytes.Compare(bufa[:len(b)], b)
}
// clonebs returns a copy of the given byte slice
func clonebs(b []byte) []byte {
c := make([]byte, len(b))
copy(c, b)
return c
}