-
Notifications
You must be signed in to change notification settings - Fork 29
/
readersearch.go
86 lines (72 loc) · 1.81 KB
/
readersearch.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
package browser
import (
"bytes"
"io"
)
const searchBufferSize = 32 * 1024
func searchPattern(r io.Reader, pattern []byte, maxDataLen int) ([]byte, error) {
var err error
pos := 0
// Create a buffer to hold the chunk of dataZ
buffer := make([]byte, searchBufferSize)
ofs := 0
var bytesRead int
for {
// Read a chunk of data into the buffer
bytesRead, err = r.Read(buffer[bytesRead-ofs:])
if err != nil && err != io.EOF {
return nil, err
}
// Search for the pattern within the buffer
index := bytes.Index(buffer, pattern)
if index >= 0 {
if index < searchBufferSize-maxDataLen {
return buffer[index : index+maxDataLen], nil
}
ofs = index
} else {
ofs = bytesRead - maxDataLen - 1
}
// Check if end of file is reached
if err == io.EOF {
break
}
// Move the remaining bytes of the current buffer to the beginning
copy(buffer, buffer[ofs:bytesRead])
pos += bytesRead
}
return nil, io.EOF
}
func seekReaderAtPattern(r io.Reader, pattern []byte) (io.Reader, error) {
var err error
pos := 0
// Create a buffer to hold the chunk of dataZ
buffer := make([]byte, searchBufferSize)
ofs := 0
var bytesRead int
for {
// Read a chunk of data into the buffer
bytesRead, err = r.Read(buffer[bytesRead-ofs:])
if err != nil && err != io.EOF {
return nil, err
}
// Search for the pattern within the buffer
index := bytes.Index(buffer, pattern)
if index >= 0 {
if index < searchBufferSize-len(pattern) {
return io.MultiReader(bytes.NewReader(buffer[index:]), r), nil
}
ofs = index
} else {
ofs = bytesRead - len(pattern) - 1
}
// Check if end of file is reached
if err == io.EOF {
break
}
// Move the remaining bytes of the current buffer to the beginning
copy(buffer, buffer[ofs:bytesRead])
pos += bytesRead
}
return nil, io.EOF
}