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-06-01 16:25:45 +08:00
|
|
|
func worseConn(l, r *peer) 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 {
|
2020-06-01 16:25:45 +08:00
|
|
|
return worseConn(&me.conns[i].peer, &me.conns[j].peer)
|
2016-10-31 13:24:48 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
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]
|
|
|
|
}
|