forked from anacrolix/torrent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
prioritized_peers.go
49 lines (40 loc) · 1.09 KB
/
prioritized_peers.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package torrent
import "github.com/google/btree"
// 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 {
return me.prio < than.(prioritizedPeersItem).prio
}
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
}
func (me *prioritizedPeers) DeleteMin() (ret prioritizedPeersItem, ok bool) {
i := me.om.DeleteMin()
if i == nil {
return
}
ret = i.(prioritizedPeersItem)
ok = true
return
}
func (me *prioritizedPeers) PopMax() Peer {
return me.om.DeleteMax().(prioritizedPeersItem).p
}