Fix bytesLeft for files (#348)

* Refactor (*File).bytesLeft

* Always use the same piece size
This commit is contained in:
i96751414 2019-11-30 08:53:35 +00:00 committed by Matt Joiner
parent 61fa4bf51f
commit f15aa27e24
1 changed files with 14 additions and 21 deletions

35
file.go
View File

@ -6,7 +6,6 @@ import (
"github.com/anacrolix/missinggo/bitmap"
"github.com/anacrolix/torrent/metainfo"
pp "github.com/anacrolix/torrent/peer_protocol"
)
// Provides access to regions of torrent data that correspond to its files.
@ -56,30 +55,24 @@ func (f *File) bytesCompleted() int64 {
}
func (f *File) bytesLeft() (left int64) {
pieceSize := int64(f.t.usualPieceSize())
firstPieceIndex := f.firstPieceIndex()
endPieceIndex := f.endPieceIndex()
bitmap.Flip(f.t.completedPieces, firstPieceIndex, endPieceIndex+1).IterTyped(func(piece int) bool {
p := &f.t.pieces[piece]
left += int64(p.length() - p.numDirtyBytes())
return true
})
startPiece := f.t.piece(firstPieceIndex)
endChunk := int(f.offset%f.t.info.PieceLength) * int(startPiece.numChunks()) / int(startPiece.length())
bitmap.Flip(startPiece.dirtyChunks, 0, endChunk).IterTyped(func(chunk int) bool {
left -= int64(startPiece.chunkSize())
return true
})
endPiece := f.t.piece(endPieceIndex)
startChunk := int((f.offset+f.length)%f.t.info.PieceLength) * int(endPiece.numChunks()) / int(endPiece.length())
lastChunkIndex := int(endPiece.lastChunkIndex())
bitmap.Flip(endPiece.dirtyChunks, startChunk, int(endPiece.numChunks())).IterTyped(func(chunk int) bool {
if chunk == lastChunkIndex {
left -= int64(endPiece.chunkIndexSpec(pp.Integer(chunk)).Length)
} else {
left -= int64(endPiece.chunkSize())
endPieceIndex := f.endPieceIndex() - 1
bitmap.Flip(f.t.completedPieces, firstPieceIndex+1, endPieceIndex).IterTyped(func(piece int) bool {
if piece >= endPieceIndex {
return false
}
if piece > firstPieceIndex {
left += pieceSize
}
return true
})
if !f.t.pieceComplete(firstPieceIndex) {
left += pieceSize - (f.offset % pieceSize)
}
if !f.t.pieceComplete(endPieceIndex) {
left += (f.offset + f.length) % pieceSize
}
return
}