Move torrentOffsetRequest and torrentRequestOffset, fixing a bug in former, and test it

This commit is contained in:
Matt Joiner 2015-04-08 02:20:01 +10:00
parent 533c034747
commit ade6087b2f
3 changed files with 46 additions and 27 deletions

29
misc.go
View File

@ -78,3 +78,32 @@ func super(child interface{}) (parent interface{}, ok bool) {
ok = parent != nil
return
}
// Return the request that would include the given offset into the torrent data.
func torrentOffsetRequest(torrentLength, pieceSize, chunkSize, offset int64) (
r request, ok bool) {
if offset < 0 || offset >= torrentLength {
return
}
r.Index = pp.Integer(offset / pieceSize)
r.Begin = pp.Integer(offset % pieceSize / chunkSize * chunkSize)
r.Length = pp.Integer(chunkSize)
pieceLeft := pp.Integer(pieceSize - int64(r.Begin))
if r.Length > pieceLeft {
r.Length = pieceLeft
}
torrentLeft := torrentLength - int64(r.Index)*pieceSize - int64(r.Begin)
if int64(r.Length) > torrentLeft {
r.Length = pp.Integer(torrentLeft)
}
ok = true
return
}
func torrentRequestOffset(torrentLength, pieceSize int64, r request) (off int64) {
off = int64(r.Index)*pieceSize + int64(r.Begin)
if off < 0 || off >= torrentLength {
panic("invalid request")
}
return
}

15
misc_test.go Normal file
View File

@ -0,0 +1,15 @@
package torrent
import . "gopkg.in/check.v1"
func (suite) TestTorrentOffsetRequest(c *C) {
check := func(tl, ps, off int64, expected request, ok bool) {
req, _ok := torrentOffsetRequest(tl, ps, chunkSize, off)
c.Check(_ok, Equals, ok)
c.Check(req, Equals, expected)
}
check(13, 5, 0, newRequest(0, 0, 5), true)
check(13, 5, 3, newRequest(0, 0, 5), true)
check(13, 5, 11, newRequest(2, 0, 3), true)
check(13, 5, 13, request{}, false)
}

View File

@ -630,37 +630,12 @@ func (t *torrent) close() (err error) {
return
}
// Return the request that would include the given offset into the torrent data.
func torrentOffsetRequest(torrentLength, pieceSize, chunkSize, offset int64) (
r request, ok bool) {
if offset < 0 || offset >= torrentLength {
return
}
r.Index = pp.Integer(offset / pieceSize)
r.Begin = pp.Integer(offset % pieceSize / chunkSize * chunkSize)
left := torrentLength - int64(r.Index)*pieceSize - int64(r.Begin)
if chunkSize < left {
r.Length = pp.Integer(chunkSize)
} else {
r.Length = pp.Integer(left)
}
ok = true
return
}
func torrentRequestOffset(torrentLength, pieceSize int64, r request) (off int64) {
off = int64(r.Index)*pieceSize + int64(r.Begin)
if off < 0 || off >= torrentLength {
panic("invalid request")
}
return
}
func (t *torrent) requestOffset(r request) int64 {
return torrentRequestOffset(t.Length(), int64(t.usualPieceSize()), r)
}
// Return the request that would include the given offset into the torrent data.
// Return the request that would include the given offset into the torrent
// data. Returns !ok if there is no such request.
func (t *torrent) offsetRequest(off int64) (req request, ok bool) {
return torrentOffsetRequest(t.Length(), t.Info.PieceLength, chunkSize, off)
}