-
Notifications
You must be signed in to change notification settings - Fork 0
/
chanwriter.go
76 lines (60 loc) · 1.09 KB
/
chanwriter.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
package chanwriter
import (
"sync"
"time"
"github.com/cockroachdb/errors"
)
// ChanWriter is a writer that writes to a channel after a debounced period
type ChanWriter struct {
mu sync.Mutex
buf []byte
channel chan []byte
timer *time.Timer
closed bool
}
func New() *ChanWriter {
return &ChanWriter{
channel: make(chan []byte),
}
}
// Write implements io.Writer
func (w *ChanWriter) Write(p []byte) (n int, err error) {
w.mu.Lock()
defer w.mu.Unlock()
if w.closed {
return 0, errors.New("closed")
}
w.buf = append(w.buf, p...)
if w.timer != nil {
w.timer.Stop()
}
w.timer = time.AfterFunc(50*time.Millisecond, w.Flush)
return len(p), nil
}
// Flush the writer
func (w *ChanWriter) Flush() {
w.mu.Lock()
defer w.mu.Unlock()
if !w.closed {
w.flush()
}
}
// Close the writer
func (w *ChanWriter) Close() error {
w.mu.Lock()
defer w.mu.Unlock()
if w.closed {
return nil
}
w.flush()
close(w.channel)
w.closed = true
return nil
}
// flush must be called under lock
func (w *ChanWriter) flush() {
if len(w.buf) > 0 {
w.channel <- w.buf
w.buf = nil
}
}