forked from mimuret/dtap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrbuf.go
46 lines (39 loc) · 780 Bytes
/
rbuf.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
package dtap
import (
"sync"
"github.com/prometheus/client_golang/prometheus"
)
type RBuf struct {
channel chan []byte
mux sync.Mutex
inCounter prometheus.Counter
lostCounter prometheus.Counter
}
func NewRbuf(size uint, inCounter prometheus.Counter, lostCounter prometheus.Counter) *RBuf {
rbuf := &RBuf{
channel: make(chan []byte, size),
mux: sync.Mutex{},
inCounter: inCounter,
lostCounter: lostCounter,
}
return rbuf
}
func (r *RBuf) Read() <-chan []byte {
return r.channel
}
func (r *RBuf) Write(b []byte) {
r.mux.Lock()
select {
case r.channel <- b:
r.inCounter.Inc()
default:
r.lostCounter.Inc()
r.inCounter.Inc()
<-r.channel
r.channel <- b
}
r.mux.Unlock()
}
func (r *RBuf) Close() {
close(r.channel)
}