-
-
Notifications
You must be signed in to change notification settings - Fork 81
/
reverse_map.go
81 lines (69 loc) · 1.53 KB
/
reverse_map.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
package ktable
import (
"net/netip"
)
type reverseMap struct {
addrs map[string]*infoForAddr
}
type infoForAddr struct {
peerID ID
hashes map[ID]struct{}
}
func newInfoForAddr(peerID ID, hashes ...ID) *infoForAddr {
info := infoForAddr{
peerID: peerID,
hashes: make(map[ID]struct{}, len(hashes)),
}
info.addHashes(hashes...)
return &info
}
func (i infoForAddr) addHashes(hashes ...ID) {
for _, h := range hashes {
i.hashes[h] = struct{}{}
}
}
func (i infoForAddr) dropHashes(hashes ...ID) {
for _, h := range hashes {
delete(i.hashes, h)
}
}
func (m reverseMap) putAddrPeerID(addr netip.Addr, id ID) {
str := addr.String()
if _, ok := m.addrs[str]; ok {
m.addrs[str].peerID = id
} else {
m.addrs[str] = newInfoForAddr(id)
}
}
func (m reverseMap) putAddrHashes(addr netip.Addr, hashes ...ID) {
str := addr.String()
if _, ok := m.addrs[str]; ok {
m.addrs[str].addHashes(hashes...)
} else {
m.addrs[str] = newInfoForAddr(ID{}, hashes...)
}
}
func (m reverseMap) getPeerIDForAddr(addr netip.Addr) (ID, bool) {
info, ok := m.addrs[addr.String()]
if ok && !info.peerID.IsZero() {
return info.peerID, ok
}
return ID{}, false
}
func (m reverseMap) dropAddr(addr netip.Addr) bool {
if _, ok := m.addrs[addr.String()]; ok {
delete(m.addrs, addr.String())
return true
}
return false
}
func (m reverseMap) dropHashForAddrs(hash ID, addrs ...netip.Addr) {
for _, addr := range addrs {
if info, ok := m.addrs[addr.String()]; ok {
info.dropHashes(hash)
}
}
}
func (m reverseMap) len() int {
return len(m.addrs)
}