2014-08-28 06:04:41 +08:00
|
|
|
package torrent
|
|
|
|
|
2018-07-10 07:50:39 +08:00
|
|
|
import (
|
|
|
|
"container/heap"
|
|
|
|
"fmt"
|
|
|
|
"unsafe"
|
2019-12-23 11:04:07 +08:00
|
|
|
|
|
|
|
"github.com/anacrolix/multiless"
|
2018-07-10 07:50:39 +08:00
|
|
|
)
|
2016-10-31 13:24:48 +08:00
|
|
|
|
2020-02-21 08:07:50 +08:00
|
|
|
func worseConn(l, r *PeerConn) bool {
|
2019-12-23 11:04:07 +08:00
|
|
|
less, ok := multiless.New().Bool(
|
|
|
|
l.useful(), r.useful()).CmpInt64(
|
|
|
|
l.lastHelpful().Sub(r.lastHelpful()).Nanoseconds()).CmpInt64(
|
2020-04-13 12:08:32 +08:00
|
|
|
l.completedHandshake.Sub(r.completedHandshake).Nanoseconds()).LazySameLess(
|
|
|
|
func() (same, less bool) {
|
|
|
|
lpp, err := l.peerPriority()
|
|
|
|
if err != nil {
|
|
|
|
same = true
|
|
|
|
return
|
|
|
|
}
|
|
|
|
rpp, err := r.peerPriority()
|
|
|
|
if err != nil {
|
|
|
|
same = true
|
|
|
|
return
|
|
|
|
}
|
|
|
|
return lpp == rpp, lpp < rpp
|
|
|
|
}).Uintptr(
|
|
|
|
uintptr(unsafe.Pointer(l)), uintptr(unsafe.Pointer(r)),
|
|
|
|
).LessOk()
|
2018-07-10 07:50:39 +08:00
|
|
|
if !ok {
|
|
|
|
panic(fmt.Sprintf("cannot differentiate %#v and %#v", l, r))
|
|
|
|
}
|
|
|
|
return less
|
2014-09-11 18:31:31 +08:00
|
|
|
}
|
2016-10-31 13:24:48 +08:00
|
|
|
|
|
|
|
type worseConnSlice struct {
|
2020-02-21 08:07:50 +08:00
|
|
|
conns []*PeerConn
|
2016-10-31 13:24:48 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
var _ heap.Interface = &worseConnSlice{}
|
|
|
|
|
|
|
|
func (me worseConnSlice) Len() int {
|
|
|
|
return len(me.conns)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (me worseConnSlice) Less(i, j int) bool {
|
|
|
|
return worseConn(me.conns[i], me.conns[j])
|
|
|
|
}
|
|
|
|
|
|
|
|
func (me *worseConnSlice) Pop() interface{} {
|
|
|
|
i := len(me.conns) - 1
|
|
|
|
ret := me.conns[i]
|
|
|
|
me.conns = me.conns[:i]
|
|
|
|
return ret
|
|
|
|
}
|
|
|
|
|
|
|
|
func (me *worseConnSlice) Push(x interface{}) {
|
2020-02-21 08:07:50 +08:00
|
|
|
me.conns = append(me.conns, x.(*PeerConn))
|
2016-10-31 13:24:48 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
func (me worseConnSlice) Swap(i, j int) {
|
|
|
|
me.conns[i], me.conns[j] = me.conns[j], me.conns[i]
|
|
|
|
}
|