7 // IPeerSet has a (immutable) subset of the methods of PeerSet.
8 type IPeerSet interface {
15 //-----------------------------------------------------------------------------
17 // PeerSet is a special structure for keeping a table of peers.
18 // Iteration over the peers is super fast and thread-safe.
21 lookup map[string]*peerSetItem
25 type peerSetItem struct {
30 // NewPeerSet creates a new peerSet with a list of initial capacity of 256 items.
31 func NewPeerSet() *PeerSet {
33 lookup: make(map[string]*peerSetItem),
34 list: make([]*Peer, 0, 256),
38 // Add adds the peer to the PeerSet.
39 // Returns false if peer with key (PubKeyEd25519) is already set
40 func (ps *PeerSet) Add(peer *Peer) error {
44 if ps.lookup[peer.Key] != nil {
45 return ErrDuplicatePeer
48 ps.lookup[peer.Key] = &peerSetItem{peer, len(ps.list)}
49 ps.list = append(ps.list, peer)
53 func (ps *PeerSet) DoFilter(ip string, pubKey string) error {
55 return ErrDuplicatePeer
61 // Get looks up a peer by the provided peerKey.
62 func (ps *PeerSet) Get(peerKey string) *Peer {
65 item, ok := ps.lookup[peerKey]
72 // Has returns true if the PeerSet contains
73 // the peer referred to by this peerKey.
74 func (ps *PeerSet) Has(peerKey string) bool {
77 _, ok := ps.lookup[peerKey]
81 // List threadsafe list of peers.
82 func (ps *PeerSet) List() []*Peer {
88 // Remove discards peer if the peer was previously memoized.
89 func (ps *PeerSet) Remove(peer *Peer) {
92 item := ps.lookup[peer.Key]
98 // Copy the list but without the last element.
99 // (we must copy because we're mutating the list)
100 newList := make([]*Peer, len(ps.list)-1)
101 copy(newList, ps.list)
102 // If it's the last peer, that's an easy special case.
103 if index == len(ps.list)-1 {
105 delete(ps.lookup, peer.Key)
109 // Move the last item from ps.list to "index" in list.
110 lastPeer := ps.list[len(ps.list)-1]
111 lastPeerKey := lastPeer.Key
112 lastPeerItem := ps.lookup[lastPeerKey]
113 newList[index] = lastPeer
114 lastPeerItem.index = index
116 delete(ps.lookup, peer.Key)
119 // Size returns the number of unique items in the peerSet.
120 func (ps *PeerSet) Size() int {
122 defer ps.mtx.Unlock()