-
Notifications
You must be signed in to change notification settings - Fork 1
/
chan.go
135 lines (121 loc) · 2.36 KB
/
chan.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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
package gostream
import (
"reflect"
"time"
)
// BufferChan 对channel缓存
// 当接收消息达到`size`或超过`timeout`未收到新消息时,发送消息
// 参数说明
//
// typ slice类型参数
// size 缓存数量
// timeout 超时时间
func (s Stream) BufferChan(typ interface{}, size int, timeout time.Duration) Stream {
t := reflect.TypeOf(typ)
if t.Kind() != reflect.Slice {
panic("typ should be slice")
}
if size <= 0 {
panic("size should gt 0")
}
if timeout <= 0 {
panic("timeout should gt 0")
}
in := make(chan interface{})
out := make(chan interface{})
go s.OutChan(in)
go func() {
sv := reflect.MakeSlice(t, size, size)
idx := 0
var flush = func() {
out <- sv.Slice(0, idx).Interface()
sv = reflect.MakeSlice(t, size, size)
idx = 0
}
for {
select {
case v, ok := <-in:
if ok {
sv.Index(idx).Set(reflect.ValueOf(v))
idx++
if idx == size {
flush()
}
} else {
if idx > 0 {
flush()
}
close(out)
return
}
case <-time.After(timeout):
if idx > 0 {
flush()
}
}
}
}()
return From(out)
}
// BufferChanInterval 对channel缓存
// 当接收消息达到`size`或超过`timeout`未收到新消息时,发送消息
// 参数说明
//
// typ slice类型参数
// size 缓存数量
// interval 时间窗口
func (s Stream) BufferChanInterval(typ interface{}, size int, interval time.Duration) Stream {
t := reflect.TypeOf(typ)
if t.Kind() != reflect.Slice {
panic("typ should be slice")
}
if size <= 0 {
panic("size should gt 0")
}
if interval <= 0 {
panic("interval should gt 0")
}
in := make(chan interface{})
out := make(chan interface{})
go s.OutChan(in)
go func() {
sv := reflect.MakeSlice(t, size, size)
idx := 0
var after = time.After(time.Hour)
var resetAfter = func() {
after = time.After(interval)
}
var flush = func() {
out <- sv.Slice(0, idx).Interface()
sv = reflect.MakeSlice(t, size, size)
idx = 0
after = time.After(time.Hour)
}
for {
select {
case v, ok := <-in:
if ok {
sv.Index(idx).Set(reflect.ValueOf(v))
idx++
if idx == 1 {
resetAfter()
}
if idx == size {
flush()
}
} else {
if idx > 0 {
flush()
}
close(out)
return
}
case <-after:
if idx > 0 {
flush()
}
}
}
}()
return From(out)
}