2018-04-04 07:59:28 +00:00
|
|
|
package torrent
|
|
|
|
|
2019-12-23 03:04:07 +00:00
|
|
|
import (
|
|
|
|
"github.com/anacrolix/multiless"
|
|
|
|
"github.com/google/btree"
|
|
|
|
)
|
2018-04-04 07:59:28 +00:00
|
|
|
|
|
|
|
// Peers are stored with their priority at insertion. Their priority may
|
|
|
|
// change if our apparent IP changes, we don't currently handle that.
|
|
|
|
type prioritizedPeersItem struct {
|
|
|
|
prio peerPriority
|
|
|
|
p Peer
|
|
|
|
}
|
|
|
|
|
|
|
|
func (me prioritizedPeersItem) Less(than btree.Item) bool {
|
2019-12-23 03:04:07 +00:00
|
|
|
other := than.(prioritizedPeersItem)
|
|
|
|
return multiless.New().Bool(
|
|
|
|
me.p.Trusted, other.p.Trusted).Uint32(
|
|
|
|
me.prio, other.prio,
|
|
|
|
).Less()
|
2018-04-04 07:59:28 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type prioritizedPeers struct {
|
|
|
|
om *btree.BTree
|
|
|
|
getPrio func(Peer) peerPriority
|
|
|
|
}
|
|
|
|
|
|
|
|
func (me *prioritizedPeers) Each(f func(Peer)) {
|
|
|
|
me.om.Ascend(func(i btree.Item) bool {
|
|
|
|
f(i.(prioritizedPeersItem).p)
|
|
|
|
return true
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
func (me *prioritizedPeers) Len() int {
|
|
|
|
return me.om.Len()
|
|
|
|
}
|
|
|
|
|
|
|
|
// Returns true if a peer is replaced.
|
|
|
|
func (me *prioritizedPeers) Add(p Peer) bool {
|
|
|
|
return me.om.ReplaceOrInsert(prioritizedPeersItem{me.getPrio(p), p}) != nil
|
|
|
|
}
|
|
|
|
|
2018-04-14 11:44:03 +00:00
|
|
|
func (me *prioritizedPeers) DeleteMin() (ret prioritizedPeersItem, ok bool) {
|
|
|
|
i := me.om.DeleteMin()
|
|
|
|
if i == nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
ret = i.(prioritizedPeersItem)
|
|
|
|
ok = true
|
|
|
|
return
|
2018-04-04 07:59:28 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (me *prioritizedPeers) PopMax() Peer {
|
|
|
|
return me.om.DeleteMax().(prioritizedPeersItem).p
|
|
|
|
}
|