-
Notifications
You must be signed in to change notification settings - Fork 1
/
peerset.go
76 lines (67 loc) · 1.23 KB
/
peerset.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 collect
import (
"sync"
"github.com/libp2p/go-libp2p-core/peer"
)
type PeerSet struct {
rw sync.RWMutex
peers map[peer.ID]struct{}
}
func NewPeerSet() *PeerSet {
return &PeerSet{
rw: sync.RWMutex{},
peers: make(map[peer.ID]struct{}),
}
}
func (ps *PeerSet) Add(p peer.ID) {
ps.rw.Lock()
defer ps.rw.Unlock()
ps.peers[p] = struct{}{}
}
func (ps *PeerSet) Del(p peer.ID) {
ps.rw.Lock()
defer ps.rw.Unlock()
delete(ps.peers, p)
}
func (ps *PeerSet) Equal(another *PeerSet) bool {
ps.rw.RLock()
defer ps.rw.RUnlock()
another.rw.RLock()
defer another.rw.RUnlock()
if len(ps.peers) != len(another.peers) {
return false
}
for pid := range ps.peers {
if _, ok := another.peers[pid]; !ok {
return false
}
}
for pid := range another.peers {
if _, ok := ps.peers[pid]; !ok {
return false
}
}
return true
}
func (ps *PeerSet) String() string {
ps.rw.RLock()
defer ps.rw.RUnlock()
out := "["
for p := range ps.peers {
out += p.ShortString() + ","
}
out += "]"
return out
}
func (ps *PeerSet) Slice() []peer.ID {
if ps == nil {
return []peer.ID{}
}
ps.rw.RLock()
defer ps.rw.RUnlock()
out := make([]peer.ID, 0, len(ps.peers))
for p := range ps.peers {
out = append(out, p)
}
return out
}