-
Notifications
You must be signed in to change notification settings - Fork 0
/
buffer.go
54 lines (43 loc) · 953 Bytes
/
buffer.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
package fluent
import (
"sync"
)
type buffer struct {
new []*Message
pending []*Message
mu sync.Mutex
Dirty chan struct{}
}
func newBuffer() buffer {
return buffer{
Dirty: make(chan struct{}),
}
}
func (buffer *buffer) Add(message *Message) {
buffer.mu.Lock()
defer buffer.mu.Unlock()
buffer.new = append(buffer.new, message)
if len(buffer.new) == 1 {
go func() {
buffer.Dirty <- struct{}{}
}()
}
}
func (buffer *buffer) Remove() []*Message {
buffer.mu.Lock()
defer buffer.mu.Unlock()
if len(buffer.new) == 0 && len(buffer.pending) == 0 {
return nil
}
var messages []*Message
messages = append(messages, buffer.pending...)
messages = append(messages, buffer.new...)
buffer.pending = buffer.pending[:0]
buffer.new = buffer.new[:0]
return messages
}
func (buffer *buffer) Back(messages []*Message) {
buffer.mu.Lock()
defer buffer.mu.Unlock()
buffer.pending = append(buffer.pending, messages...)
}