2014-08-28 06:04:41 +08:00
|
|
|
package torrent
|
|
|
|
|
|
|
|
import (
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
2014-09-11 18:31:31 +08:00
|
|
|
// Implements heap functions such that [0] is the worst connection.
|
2014-09-14 01:40:35 +08:00
|
|
|
type worstConns struct {
|
2015-06-16 14:57:47 +08:00
|
|
|
c []*connection
|
|
|
|
t *torrent
|
|
|
|
cl *Client
|
2014-09-14 01:40:35 +08:00
|
|
|
}
|
2014-08-28 06:04:41 +08:00
|
|
|
|
2015-06-16 14:57:47 +08:00
|
|
|
func (me *worstConns) Len() int { return len(me.c) }
|
|
|
|
func (me *worstConns) Swap(i, j int) { me.c[i], me.c[j] = me.c[j], me.c[i] }
|
2014-08-28 06:04:41 +08:00
|
|
|
|
2014-09-11 18:31:31 +08:00
|
|
|
func (me *worstConns) Pop() (ret interface{}) {
|
2014-09-14 01:40:35 +08:00
|
|
|
old := me.c
|
2014-08-28 06:04:41 +08:00
|
|
|
n := len(old)
|
|
|
|
ret = old[n-1]
|
2014-09-14 01:40:35 +08:00
|
|
|
me.c = old[:n-1]
|
2014-08-28 06:04:41 +08:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2014-09-11 18:31:31 +08:00
|
|
|
func (me *worstConns) Push(x interface{}) {
|
2014-09-14 01:40:35 +08:00
|
|
|
me.c = append(me.c, x.(*connection))
|
|
|
|
}
|
|
|
|
|
|
|
|
type worstConnsSortKey struct {
|
2015-06-16 14:57:47 +08:00
|
|
|
useful bool
|
|
|
|
lastHelpful time.Time
|
2015-06-29 22:45:26 +08:00
|
|
|
connected time.Time
|
2014-08-28 06:04:41 +08:00
|
|
|
}
|
2014-09-11 18:31:31 +08:00
|
|
|
|
2014-09-14 01:40:35 +08:00
|
|
|
func (me worstConnsSortKey) Less(other worstConnsSortKey) bool {
|
2015-06-16 14:57:47 +08:00
|
|
|
if me.useful != other.useful {
|
|
|
|
return !me.useful
|
2014-09-14 01:40:35 +08:00
|
|
|
}
|
2015-06-29 22:45:26 +08:00
|
|
|
if !me.lastHelpful.Equal(other.lastHelpful) {
|
|
|
|
return me.lastHelpful.Before(other.lastHelpful)
|
|
|
|
}
|
|
|
|
return me.connected.Before(other.connected)
|
2014-09-14 01:40:35 +08:00
|
|
|
}
|
|
|
|
|
2015-06-16 14:57:47 +08:00
|
|
|
func (me *worstConns) key(i int) (key worstConnsSortKey) {
|
2014-09-14 01:40:35 +08:00
|
|
|
c := me.c[i]
|
2015-06-16 14:57:47 +08:00
|
|
|
key.useful = me.cl.usefulConn(me.t, c)
|
|
|
|
if me.cl.seeding(me.t) {
|
|
|
|
key.lastHelpful = c.lastChunkSent
|
2015-06-29 22:45:26 +08:00
|
|
|
}
|
|
|
|
// Intentionally consider the last time a chunk was received when seeding,
|
|
|
|
// because we might go from seeding back to leeching.
|
|
|
|
if c.lastUsefulChunkReceived.After(key.lastHelpful) {
|
2015-06-16 14:57:47 +08:00
|
|
|
key.lastHelpful = c.lastUsefulChunkReceived
|
2014-09-14 01:40:35 +08:00
|
|
|
}
|
2015-06-29 22:45:26 +08:00
|
|
|
key.connected = c.completedHandshake
|
2014-09-14 01:40:35 +08:00
|
|
|
return
|
2014-09-11 18:31:31 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
func (me worstConns) Less(i, j int) bool {
|
2014-09-14 01:40:35 +08:00
|
|
|
return me.key(i).Less(me.key(j))
|
2014-09-11 18:31:31 +08:00
|
|
|
}
|