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 // Get looks up a peer by the provided peerKey.
54 func (ps *PeerSet) Get(peerKey string) *Peer {
57 item, ok := ps.lookup[peerKey]
64 // Has returns true if the PeerSet contains
65 // the peer referred to by this peerKey.
66 func (ps *PeerSet) Has(peerKey string) bool {
69 _, ok := ps.lookup[peerKey]
73 // List threadsafe list of peers.
74 func (ps *PeerSet) List() []*Peer {
80 // Remove discards peer if the peer was previously memoized.
81 func (ps *PeerSet) Remove(peer *Peer) {
84 item := ps.lookup[peer.Key]
90 // Copy the list but without the last element.
91 // (we must copy because we're mutating the list)
92 newList := make([]*Peer, len(ps.list)-1)
93 copy(newList, ps.list)
94 // If it's the last peer, that's an easy special case.
95 if index == len(ps.list)-1 {
97 delete(ps.lookup, peer.Key)
101 // Move the last item from ps.list to "index" in list.
102 lastPeer := ps.list[len(ps.list)-1]
103 lastPeerKey := lastPeer.Key
104 lastPeerItem := ps.lookup[lastPeerKey]
105 newList[index] = lastPeer
106 lastPeerItem.index = index
108 delete(ps.lookup, peer.Key)
111 // Size returns the number of unique items in the peerSet.
112 func (ps *PeerSet) Size() int {
114 defer ps.mtx.Unlock()