torrent/misc.go

81 lines
1.5 KiB
Go
Raw Normal View History

package torrent
import (
"crypto"
"errors"
2014-12-01 22:34:45 +00:00
"fmt"
"time"
2014-08-21 11:08:56 +00:00
2015-04-07 16:17:15 +00:00
pp "github.com/anacrolix/torrent/peer_protocol"
)
const (
2014-11-19 03:53:00 +00:00
pieceHash = crypto.SHA1
maxRequests = 250 // Maximum pending requests we allow peers to send us.
chunkSize = 0x4000 // 16KiB
2015-03-08 06:28:14 +00:00
bep20 = "-GT0000-" // Peer ID client identifier prefix
2014-11-19 03:53:00 +00:00
nominalDialTimeout = time.Second * 30
minDialTimeout = 5 * time.Second
)
2014-08-21 08:24:19 +00:00
type (
InfoHash [20]byte
pieceSum [20]byte
)
func (ih *InfoHash) AsString() string {
return string(ih[:])
}
2014-12-01 22:34:45 +00:00
func (ih *InfoHash) HexString() string {
return fmt.Sprintf("%x", ih[:])
}
2015-04-07 16:17:15 +00:00
func lastChunkSpec(pieceLength pp.Integer) (cs chunkSpec) {
cs.Begin = (pieceLength - 1) / chunkSize * chunkSize
cs.Length = pieceLength - cs.Begin
return
}
type chunkSpec struct {
2015-04-07 16:17:15 +00:00
Begin, Length pp.Integer
}
2014-04-16 11:13:44 +00:00
type request struct {
2015-04-07 16:17:15 +00:00
Index pp.Integer
chunkSpec
}
2015-04-07 16:17:15 +00:00
func newRequest(index, begin, length pp.Integer) request {
2014-04-16 11:13:44 +00:00
return request{index, chunkSpec{begin, length}}
2014-04-16 07:33:33 +00:00
}
var (
// Requested data not yet available.
2015-03-08 06:28:14 +00:00
errDataNotReady = errors.New("data not ready")
)
2014-11-19 03:53:00 +00:00
// The size in bytes of a metadata extension piece.
func metadataPieceSize(totalSize int, piece int) int {
ret := totalSize - piece*(1<<14)
if ret > 1<<14 {
ret = 1 << 14
}
return ret
}
2015-03-10 15:41:21 +00:00
2015-03-20 12:52:53 +00:00
type superer interface {
2015-03-10 15:41:21 +00:00
Super() interface{}
}
// Returns ok if there's a parent, and it's not nil.
func super(child interface{}) (parent interface{}, ok bool) {
2015-03-20 12:52:53 +00:00
s, ok := child.(superer)
2015-03-10 15:41:21 +00:00
if !ok {
return
}
parent = s.Super()
ok = parent != nil
return
}