-
Notifications
You must be signed in to change notification settings - Fork 2
/
scanner_writer.go
141 lines (105 loc) · 2.05 KB
/
scanner_writer.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
package logger
import (
"bufio"
"fmt"
"io"
"sync"
)
type (
ScannerWriter struct {
buf []byte
max_buf int
me sync.Mutex
closed bool
splitFunc bufio.SplitFunc
tokenFunc func(token []byte) error
}
)
var (
ExceededBufferSizeLimitError = fmt.Errorf("exceeded buffer size limit")
WriterClosedError = fmt.Errorf("cannot write to closed writer")
)
func NewScannerWriter(splitFunc bufio.SplitFunc, max_buf int, tokenFunc func([]byte) error) *ScannerWriter {
return &ScannerWriter{
splitFunc: splitFunc,
tokenFunc: tokenFunc,
max_buf: max_buf,
}
}
func (sc *ScannerWriter) Write(data []byte) (int, error) {
sc.me.Lock()
defer sc.me.Unlock()
if sc.closed {
return 0, WriterClosedError
}
data_len := len(data)
if sc.buf != nil {
data = append(sc.buf, data...)
sc.buf = nil
}
for len(data) > 0 {
adv, token, err := sc.splitFunc(data, false)
if err != nil {
return 0, err
}
if token == nil {
if adv == 0 {
// read more requests are buffered until next write
if len(sc.buf)+len(data) > sc.max_buf {
return 0, ExceededBufferSizeLimitError
}
sc.buf = append(sc.buf, data...)
return data_len, nil
}
} else if err := sc.tokenFunc(token); err != nil {
return 0, err
}
if adv > 0 {
data = data[adv:]
}
}
return data_len, nil
}
func (sc *ScannerWriter) Flush() error {
sc.me.Lock()
defer sc.me.Unlock()
return sc.flush()
}
func (sc *ScannerWriter) flush() error {
if sc.closed {
return WriterClosedError
}
if len(sc.buf) == 0 {
sc.buf = nil
return nil
}
_, token, err := sc.splitFunc(sc.buf, true)
if err != nil {
if err == io.EOF {
return nil
}
return err
}
if len(token) > 0 {
if err := sc.tokenFunc(token); err != nil {
return err
}
}
sc.buf = nil
return nil
}
func (sc *ScannerWriter) Close() error {
sc.me.Lock()
defer sc.me.Unlock()
if sc.closed {
return WriterClosedError
}
if err := sc.flush(); err != nil {
return err
}
sc.closed = true
sc.buf = nil
sc.splitFunc = nil
sc.tokenFunc = nil
return nil
}