-
Notifications
You must be signed in to change notification settings - Fork 0
/
concurrentmap.go
84 lines (67 loc) · 1.74 KB
/
concurrentmap.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
package main
import (
"sort"
"sync"
)
type discordChannel string
// ChannelAddressMap maps a discord channel to a server address
type ChannelAddressMap struct {
mu sync.Mutex
m map[discordChannel]Address
}
func newChannelAddressMap() ChannelAddressMap {
return ChannelAddressMap{m: make(map[discordChannel]Address)}
}
// GetAddresses returns a sorted list of all actively mapped addresses
func (a *ChannelAddressMap) GetAddresses() []Address {
a.mu.Lock()
result := make([]Address, 0, len(a.m))
for _, addr := range a.m {
result = append(result, addr)
}
a.mu.Unlock()
sort.Sort(byAddress(result))
return result
}
// Set connects a discord channel ID with a server Address
func (a *ChannelAddressMap) Set(channelID discordChannel, addr Address) {
a.mu.Lock()
defer a.mu.Unlock()
a.m[channelID] = addr
}
// Get returns the Address that is associated with the used channel.
func (a *ChannelAddressMap) Get(channelID discordChannel) (Address, bool) {
a.mu.Lock()
defer a.mu.Unlock()
addr, ok := a.m[channelID]
return addr, ok
}
// RemoveAddress removes server address from mapping
func (a *ChannelAddressMap) RemoveAddress(addr Address) {
a.mu.Lock()
defer a.mu.Unlock()
for key, value := range a.m {
if value == addr {
delete(a.m, key)
break
}
}
}
// RemoveChannel removes channel address from mapping
func (a *ChannelAddressMap) RemoveChannel(chann discordChannel) {
a.mu.Lock()
defer a.mu.Unlock()
delete(a.m, chann)
}
// AlreadyRegistered checks if a server address is already registered to a discord channel.
func (a *ChannelAddressMap) AlreadyRegistered(addr Address) (found bool) {
a.mu.Lock()
defer a.mu.Unlock()
for _, serverAddr := range a.m {
if serverAddr == addr {
found = true
return
}
}
return
}