]> Sergey Matveev's repositories - btrtrc.git/blob - prioritized_peers.go
Use new anacrolix/multiless, and incorporate Peer.Trusted into peer prioritization
[btrtrc.git] / prioritized_peers.go
1 package torrent
2
3 import (
4         "github.com/anacrolix/multiless"
5         "github.com/google/btree"
6 )
7
8 // Peers are stored with their priority at insertion. Their priority may
9 // change if our apparent IP changes, we don't currently handle that.
10 type prioritizedPeersItem struct {
11         prio peerPriority
12         p    Peer
13 }
14
15 func (me prioritizedPeersItem) Less(than btree.Item) bool {
16         other := than.(prioritizedPeersItem)
17         return multiless.New().Bool(
18                 me.p.Trusted, other.p.Trusted).Uint32(
19                 me.prio, other.prio,
20         ).Less()
21 }
22
23 type prioritizedPeers struct {
24         om      *btree.BTree
25         getPrio func(Peer) peerPriority
26 }
27
28 func (me *prioritizedPeers) Each(f func(Peer)) {
29         me.om.Ascend(func(i btree.Item) bool {
30                 f(i.(prioritizedPeersItem).p)
31                 return true
32         })
33 }
34
35 func (me *prioritizedPeers) Len() int {
36         return me.om.Len()
37 }
38
39 // Returns true if a peer is replaced.
40 func (me *prioritizedPeers) Add(p Peer) bool {
41         return me.om.ReplaceOrInsert(prioritizedPeersItem{me.getPrio(p), p}) != nil
42 }
43
44 func (me *prioritizedPeers) DeleteMin() (ret prioritizedPeersItem, ok bool) {
45         i := me.om.DeleteMin()
46         if i == nil {
47                 return
48         }
49         ret = i.(prioritizedPeersItem)
50         ok = true
51         return
52 }
53
54 func (me *prioritizedPeers) PopMax() Peer {
55         return me.om.DeleteMax().(prioritizedPeersItem).p
56 }