-
Notifications
You must be signed in to change notification settings - Fork 0
/
subscriptions.go
76 lines (59 loc) · 1.21 KB
/
subscriptions.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
package botpoll
import (
"math/rand"
"strconv"
"sync"
"time"
"github.com/SevereCloud/vksdk/object"
)
type subscriptions struct {
subs map[string]*subscription
lock sync.Mutex
}
func newSubscriptions() *subscriptions {
return &subscriptions{subs: map[string]*subscription{}}
}
func generateKey(check func(string) bool) string {
for {
key := strconv.FormatInt(rand.Int63(), 16) + strconv.FormatInt(time.Now().UnixNano(), 16)
if !check(key) {
return key
}
}
}
func (s *subscriptions) Create() string {
s.lock.Lock()
defer s.lock.Unlock()
key := generateKey(func(k string) bool {
_, ok := s.subs[k]
return ok
})
s.subs[key] = newSubscription()
return key
}
func (s *subscriptions) Get(key string) (*subscription, bool) {
s.lock.Lock()
defer s.lock.Unlock()
v, ok := s.subs[key]
return v, ok
}
func (s *subscriptions) Notify(events []object.GroupEvent) {
s.lock.Lock()
defer s.lock.Unlock()
for _, sub := range s.subs {
sub.Notify(events)
}
}
func (s *subscriptions) Delete(key string) {
s.lock.Lock()
defer s.lock.Unlock()
delete(s.subs, key)
}
func (s *subscriptions) Close() error {
s.lock.Lock()
defer s.lock.Unlock()
for _, sub := range s.subs {
_ = sub.Close()
}
return nil
}