6 "github.com/anacrolix/multiless"
7 "github.com/google/btree"
10 // Peers are stored with their priority at insertion. Their priority may
11 // change if our apparent IP changes, we don't currently handle that.
12 type prioritizedPeersItem struct {
17 var hashSeed = maphash.MakeSeed()
19 func (me prioritizedPeersItem) addrHash() int64 {
22 h.WriteString(me.p.Addr.String())
23 return int64(h.Sum64())
26 func (me prioritizedPeersItem) Less(than btree.Item) bool {
27 other := than.(prioritizedPeersItem)
28 return multiless.New().Bool(
29 me.p.Trusted, other.p.Trusted).Uint32(
30 me.prio, other.prio).Int64(
31 me.addrHash(), other.addrHash(),
35 type prioritizedPeers struct {
37 getPrio func(PeerInfo) peerPriority
40 func (me *prioritizedPeers) Each(f func(PeerInfo)) {
41 me.om.Ascend(func(i btree.Item) bool {
42 f(i.(prioritizedPeersItem).p)
47 func (me *prioritizedPeers) Len() int {
48 if me == nil || me.om == nil {
54 // Returns true if a peer is replaced.
55 func (me *prioritizedPeers) Add(p PeerInfo) bool {
56 return me.om.ReplaceOrInsert(prioritizedPeersItem{me.getPrio(p), p}) != nil
59 // Returns true if a peer is replaced.
60 func (me *prioritizedPeers) AddReturningReplacedPeer(p PeerInfo) (ret PeerInfo, ok bool) {
61 item := me.om.ReplaceOrInsert(prioritizedPeersItem{me.getPrio(p), p})
65 ret = item.(prioritizedPeersItem).p
70 func (me *prioritizedPeers) DeleteMin() (ret prioritizedPeersItem, ok bool) {
71 i := me.om.DeleteMin()
75 ret = i.(prioritizedPeersItem)
80 func (me *prioritizedPeers) PopMax() PeerInfo {
81 return me.om.DeleteMax().(prioritizedPeersItem).p