Skip to content

Commit

Permalink
Fix metainfo.Piece.Length for v2 torrents
Browse files Browse the repository at this point in the history
  • Loading branch information
anacrolix committed Feb 28, 2024
1 parent fd97a99 commit 07182d1
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 14 deletions.
12 changes: 1 addition & 11 deletions metainfo/fileinfo.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,17 +28,7 @@ func (fi *FileInfo) DisplayPath(info *Info) string {
}
}

func (me FileInfo) Offset(info *Info) (ret int64) {
for _, fi := range info.UpvertedFiles() {
if me.DisplayPath(info) == fi.DisplayPath(info) {
return
}
ret += fi.Length
}
panic("not found")
}

func (fi FileInfo) BestPath() []string {
func (fi *FileInfo) BestPath() []string {
if len(fi.PathUtf8) != 0 {
return fi.PathUtf8
}
Expand Down
2 changes: 1 addition & 1 deletion metainfo/info.go
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ func (info *Info) UpvertedFiles() (files []FileInfo) {
}

func (info *Info) Piece(index int) Piece {
return Piece{info, pieceIndex(index)}
return Piece{info, index}
}

func (info *Info) BestName() string {
Expand Down
27 changes: 25 additions & 2 deletions metainfo/piece.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,30 @@ type Piece struct {
type pieceIndex = int

func (p Piece) Length() int64 {
if int(p.i) == p.Info.NumPieces()-1 {
if p.Info.HasV2() {
var offset int64
pieceLength := p.Info.PieceLength
lastFileEnd := int64(0)
done := false
p.Info.FileTree.UpvertedFiles(nil, func(fi FileInfo) {
if done {
return
}
fileStartPiece := int(offset / pieceLength)
if fileStartPiece > p.i {
done = true
return
}
lastFileEnd = offset + fi.Length
offset = (lastFileEnd + pieceLength - 1) / pieceLength * pieceLength
})
ret := min(lastFileEnd-int64(p.i)*pieceLength, pieceLength)
if ret <= 0 {
panic(ret)
}
return ret
}
if p.i == p.Info.NumPieces()-1 {
return p.Info.TotalLength() - int64(p.i)*p.Info.PieceLength
}
return p.Info.PieceLength
Expand All @@ -23,6 +46,6 @@ func (p Piece) Hash() (ret Hash) {
return
}

func (p Piece) Index() pieceIndex {
func (p Piece) Index() int {
return p.i
}

0 comments on commit 07182d1

Please sign in to comment.