-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathchannel.go
75 lines (67 loc) · 1.23 KB
/
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
package logs
import (
"context"
"fmt"
"github.com/pharosnet/flyline"
"os"
"reflect"
)
const (
flybuffer_cap = 1024 * 16
)
type Channel interface {
Send(pac *Packet) error
Recv() (*Packet, bool)
Close(ctx context.Context) error
}
func NewFlyChannel(sink Sink) Channel {
ch := &flyChannel{
buffer:flyline.NewArrayBuffer(flybuffer_cap),
sink:sink,
}
go func(ch *flyChannel) {
for {
pac, ok := ch.Recv()
if !ok {
break
}
ch.sink.FlowInto(pac)
}
}(ch)
return ch
}
type flyChannel struct {
buffer flyline.Buffer
sink Sink
}
func (c *flyChannel) Send(pac *Packet) error {
c.buffer.Send(pac)
return nil
}
func (c *flyChannel) Recv() (*Packet, bool) {
v, ok := c.buffer.Recv()
if !ok {
return nil, ok
}
pac, isPac := v.(*Packet)
if !isPac {
panic(fmt.Sprintf("the type of received from channel is not *Packet, received's type is %s", reflect.TypeOf(v)))
os.Exit(1)
}
return pac, ok
}
func (c *flyChannel) Close(ctx context.Context) error {
bufCloseErr := c.buffer.Close()
bufSyncErr := c.buffer.Sync(ctx)
sinkCloseErr := c.sink.Close(ctx)
if bufCloseErr != nil {
return bufCloseErr
}
if bufSyncErr != nil {
return bufSyncErr
}
if sinkCloseErr != nil {
return sinkCloseErr
}
return nil
}