-
Notifications
You must be signed in to change notification settings - Fork 42
/
limited_read.go
124 lines (107 loc) · 2.04 KB
/
limited_read.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
package utils
import (
"bufio"
"context"
"io"
"sync"
"time"
)
func ReadWithLen(r io.Reader, length int) ([]byte, int) {
scanner := bufio.NewScanner(r)
scanner.Split(bufio.ScanBytes)
var (
output []byte
count int
)
for scanner.Scan() {
count += 1
output = append(output, scanner.Bytes()...)
if count >= length {
break
}
}
return output, len(output)
}
func ReadWithContextTickCallback(ctx context.Context, rc io.Reader, callback func([]byte) bool, interval time.Duration) {
scanner := bufio.NewScanner(rc)
scanner.Split(bufio.ScanBytes)
ticker := time.Tick(interval)
// one go routine to read
var (
mux = new(sync.Mutex)
buf []byte
)
go func() {
for scanner.Scan() {
// 根据上下文退出
if ctx.Err() != nil {
break
}
// 临时读一下现有指纹信息
mux.Lock()
buf = append(buf, scanner.Bytes()...)
mux.Unlock()
}
}()
defer callback(buf)
for {
select {
case <-ctx.Done():
return
case <-ticker:
mux.Lock()
flag := callback(buf)
mux.Unlock()
if flag {
continue
} else {
return
}
}
}
}
func ReadWithContextCallback(ctx context.Context, rc io.Reader, callback func([]byte)) {
// full 4700 http matches : 1024 - 17s
// 2048 - 34s
ReadWithContextCallbackWithMaxLength(ctx, rc, callback, 4096)
}
func ReadWithContextCallbackWithMaxLength(ctx context.Context, rc io.Reader, callback func([]byte), length int) {
scanner := bufio.NewScanner(rc)
scanner.Split(bufio.ScanBytes)
ctx, cancel := context.WithCancel(ctx)
// one go routine to read
var (
mux = new(sync.Mutex)
buf []byte
)
go func() {
defer cancel()
for scanner.Scan() {
// 根据上下文退出
if ctx.Err() != nil {
break
}
// 临时读一下现有指纹信息
flag := false
mux.Lock()
buf = append(buf, scanner.Bytes()...)
if len(buf) > length {
cancel()
flag = true
}
mux.Unlock()
if flag {
break
}
}
}()
for {
select {
case <-ctx.Done():
mux.Lock()
callback(buf)
mux.Unlock()
return
}
}
}