-
Notifications
You must be signed in to change notification settings - Fork 18
/
dynamicchannel.go
73 lines (67 loc) · 1.57 KB
/
dynamicchannel.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
package o3
//dynSendChan implements a buffered channel for sending messages with dynamic size. It will
//immediately consume input and store it in a growing FIFO buffer that can be read from using Out.
type dynSendChan struct {
In chan Message
Out chan Message
buf []Message
}
//newDynSendChan returns a new dynamic sending channel that need not be further initialized to
//be usable.
func newDynSendChan() *dynSendChan {
d := &dynSendChan{
In: make(chan Message),
Out: make(chan Message),
buf: make([]Message, 0),
}
go d.run()
return d
}
func (d *dynSendChan) run() {
for {
if len(d.buf) > 0 {
select {
case d.Out <- d.buf[0]:
d.buf = d.buf[1:]
case v := <-d.In:
d.buf = append(d.buf, v)
}
} else {
v := <-d.In
d.buf = append(d.buf, v)
}
}
}
//dynRecvChan implements a buffered channel for receiving messages with dynamic size. It will
//immediately consume input and store it in a growing FIFO buffer that can be read from using Out.
type dynRecvChan struct {
In chan ReceivedMsg
Out chan ReceivedMsg
buf []ReceivedMsg
}
//newDynRecvChan returns a new dynamic receiving channel that need not be further initialized to
//be usable.
func newDynRecvChan() *dynRecvChan {
d := &dynRecvChan{
In: make(chan ReceivedMsg),
Out: make(chan ReceivedMsg),
buf: make([]ReceivedMsg, 0),
}
go d.run()
return d
}
func (d *dynRecvChan) run() {
for {
if len(d.buf) > 0 {
select {
case d.Out <- d.buf[0]:
d.buf = d.buf[1:]
case v := <-d.In:
d.buf = append(d.buf, v)
}
} else {
v := <-d.In
d.buf = append(d.buf, v)
}
}
}