-
Notifications
You must be signed in to change notification settings - Fork 68
/
ring_channel.go
114 lines (101 loc) · 2.63 KB
/
ring_channel.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
package channels
import "github.com/eapache/queue"
// RingChannel implements the Channel interface in a way that never blocks the writer.
// Specifically, if a value is written to a RingChannel when its buffer is full then the oldest
// value in the buffer is discarded to make room (just like a standard ring-buffer).
// Note that Go's scheduler can cause discarded values when they could be avoided, simply by scheduling
// the writer before the reader, so caveat emptor.
// For the opposite behaviour (discarding the newest element, not the oldest) see OverflowingChannel.
type RingChannel struct {
input, output chan interface{}
length chan int
buffer *queue.Queue
size BufferCap
}
func NewRingChannel(size BufferCap) *RingChannel {
if size < 0 && size != Infinity {
panic("channels: invalid negative size in NewRingChannel")
}
ch := &RingChannel{
input: make(chan interface{}),
output: make(chan interface{}),
buffer: queue.New(),
size: size,
}
if size == None {
go ch.overflowingDirect()
} else {
ch.length = make(chan int)
go ch.ringBuffer()
}
return ch
}
func (ch *RingChannel) In() chan<- interface{} {
return ch.input
}
func (ch *RingChannel) Out() <-chan interface{} {
return ch.output
}
func (ch *RingChannel) Len() int {
if ch.size == None {
return 0
} else {
return <-ch.length
}
}
func (ch *RingChannel) Cap() BufferCap {
return ch.size
}
func (ch *RingChannel) Close() {
close(ch.input)
}
// for entirely unbuffered cases
func (ch *RingChannel) overflowingDirect() {
for elem := range ch.input {
// if we can't write it immediately, drop it and move on
select {
case ch.output <- elem:
default:
}
}
close(ch.output)
}
// for all buffered cases
func (ch *RingChannel) ringBuffer() {
var input, output chan interface{}
var next interface{}
input = ch.input
for input != nil || output != nil {
select {
// Prefer to write if possible, which is surprisingly effective in reducing
// dropped elements due to overflow. The naive read/write select chooses randomly
// when both channels are ready, which produces unnecessary drops 50% of the time.
case output <- next:
ch.buffer.Remove()
default:
select {
case elem, open := <-input:
if open {
ch.buffer.Add(elem)
if ch.size != Infinity && ch.buffer.Length() > int(ch.size) {
ch.buffer.Remove()
}
} else {
input = nil
}
case output <- next:
ch.buffer.Remove()
case ch.length <- ch.buffer.Length():
}
}
if ch.buffer.Length() > 0 {
output = ch.output
next = ch.buffer.Peek()
} else {
output = nil
next = nil
}
}
close(ch.output)
close(ch.length)
}