9 "github.com/anacrolix/multiless"
10 "github.com/anacrolix/sync"
13 type worseConnInput struct {
16 CompletedHandshake time.Time
17 GetPeerPriority func() (peerPriority, error)
18 getPeerPriorityOnce sync.Once
19 peerPriority peerPriority
24 func (me *worseConnInput) doGetPeerPriority() {
25 me.peerPriority, me.peerPriorityErr = me.GetPeerPriority()
28 func (me *worseConnInput) doGetPeerPriorityOnce() {
29 me.getPeerPriorityOnce.Do(me.doGetPeerPriority)
32 func worseConnInputFromPeer(p *Peer) worseConnInput {
33 ret := worseConnInput{
35 LastHelpful: p.lastHelpful(),
36 CompletedHandshake: p.completedHandshake,
37 Pointer: uintptr(unsafe.Pointer(p)),
38 GetPeerPriority: p.peerPriority,
43 func worseConn(_l, _r *Peer) bool {
44 // TODO: Use generics for ptr to
45 l := worseConnInputFromPeer(_l)
46 r := worseConnInputFromPeer(_r)
50 func (l *worseConnInput) Less(r *worseConnInput) bool {
51 less, ok := multiless.New().Bool(
52 l.Useful, r.Useful).CmpInt64(
53 l.LastHelpful.Sub(r.LastHelpful).Nanoseconds()).CmpInt64(
54 l.CompletedHandshake.Sub(r.CompletedHandshake).Nanoseconds()).LazySameLess(
55 func() (same, less bool) {
56 l.doGetPeerPriorityOnce()
57 if l.peerPriorityErr != nil {
61 r.doGetPeerPriorityOnce()
62 if r.peerPriorityErr != nil {
66 same = l.peerPriority == r.peerPriority
67 less = l.peerPriority < r.peerPriority
73 panic(fmt.Sprintf("cannot differentiate %#v and %#v", l, r))
78 type worseConnSlice struct {
83 func (me *worseConnSlice) initKeys() {
84 me.keys = make([]worseConnInput, len(me.conns))
85 for i, c := range me.conns {
86 me.keys[i] = worseConnInputFromPeer(&c.Peer)
90 var _ heap.Interface = &worseConnSlice{}
92 func (me worseConnSlice) Len() int {
96 func (me worseConnSlice) Less(i, j int) bool {
97 return me.keys[i].Less(&me.keys[j])
100 func (me *worseConnSlice) Pop() interface{} {
101 i := len(me.conns) - 1
103 me.conns = me.conns[:i]
107 func (me *worseConnSlice) Push(x interface{}) {
108 panic("not implemented")
111 func (me worseConnSlice) Swap(i, j int) {
112 me.conns[i], me.conns[j] = me.conns[j], me.conns[i]
113 me.keys[i], me.keys[j] = me.keys[j], me.keys[i]