github.com/sberex/go-sberex@v1.8.2-0.20181113200658-ed96ac38f7d7/p2p/testing/peerpool.go (about) 1 // This file is part of the go-sberex library. The go-sberex library is 2 // free software: you can redistribute it and/or modify it under the terms 3 // of the GNU Lesser General Public License as published by the Free 4 // Software Foundation, either version 3 of the License, or (at your option) 5 // any later version. 6 // 7 // The go-sberex library is distributed in the hope that it will be useful, 8 // but WITHOUT ANY WARRANTY; without even the implied warranty of 9 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser 10 // General Public License <http://www.gnu.org/licenses/> for more details. 11 12 package testing 13 14 import ( 15 "fmt" 16 "sync" 17 18 "github.com/Sberex/go-sberex/log" 19 "github.com/Sberex/go-sberex/p2p/discover" 20 ) 21 22 type TestPeer interface { 23 ID() discover.NodeID 24 Drop(error) 25 } 26 27 // TestPeerPool is an example peerPool to demonstrate registration of peer connections 28 type TestPeerPool struct { 29 lock sync.Mutex 30 peers map[discover.NodeID]TestPeer 31 } 32 33 func NewTestPeerPool() *TestPeerPool { 34 return &TestPeerPool{peers: make(map[discover.NodeID]TestPeer)} 35 } 36 37 func (self *TestPeerPool) Add(p TestPeer) { 38 self.lock.Lock() 39 defer self.lock.Unlock() 40 log.Trace(fmt.Sprintf("pp add peer %v", p.ID())) 41 self.peers[p.ID()] = p 42 43 } 44 45 func (self *TestPeerPool) Remove(p TestPeer) { 46 self.lock.Lock() 47 defer self.lock.Unlock() 48 delete(self.peers, p.ID()) 49 } 50 51 func (self *TestPeerPool) Has(id discover.NodeID) bool { 52 self.lock.Lock() 53 defer self.lock.Unlock() 54 _, ok := self.peers[id] 55 return ok 56 } 57 58 func (self *TestPeerPool) Get(id discover.NodeID) TestPeer { 59 self.lock.Lock() 60 defer self.lock.Unlock() 61 return self.peers[id] 62 }