-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
70 lines (57 loc) · 998 Bytes
/
main.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
package fanout
import (
"sync"
)
type Fanner[T any] struct {
mu sync.Mutex
chans []chan T
closed bool
}
func New[T any]() *Fanner[T] {
result := Fanner[T]{
chans: make([]chan T, 0),
}
return &result
}
func (c *Fanner[T]) Sub() <-chan T {
c.mu.Lock()
defer c.mu.Unlock()
result := make(chan T)
c.chans = append(c.chans, result)
return result
}
func (c *Fanner[T]) Pub(payload T) {
c.mu.Lock()
defer c.mu.Unlock()
if !c.closed { // channel was not closed
for _, ch := range c.chans {
ch <- payload
}
}
}
func (c *Fanner[T]) Cancel(ch <-chan T) bool {
c.mu.Lock()
defer c.mu.Unlock()
if c.closed {
return true
}
found := false
for i, ci := range c.chans {
if ci == ch {
c.chans[i] = c.chans[len(c.chans)-1]
c.chans[len(c.chans)-1] = nil
c.chans = c.chans[:len(c.chans)-1]
found = true
break
}
}
return found
}
func (c *Fanner[T]) Close() {
c.mu.Lock()
defer c.mu.Unlock()
if !c.closed {
c.chans = nil
c.closed = true
}
}