]> Sergey Matveev's repositories - btrtrc.git/commitdiff
Fix metainfo.Piece.Length for v2 torrents
authorMatt Joiner <anacrolix@gmail.com>
Tue, 27 Feb 2024 13:15:40 +0000 (00:15 +1100)
committerMatt Joiner <anacrolix@gmail.com>
Sat, 2 Mar 2024 02:02:55 +0000 (13:02 +1100)
metainfo/fileinfo.go
metainfo/info.go
metainfo/piece.go

index bf4721563461913c1b6bf0123ab3933d0d3bccf8..82e1c94f812ad12bac40fe42a2faf2aabe7fc789 100644 (file)
@@ -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
        }
index 2798fd5902d6278af6343535187fb5534c16a4d6..d1b54d44d61a93e8087fe53641dd886a0b5739bb 100644 (file)
@@ -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 {
index d8895384d0a1858d17bd3d08fdf89dd4672b3f99..c7377f5db643b9e372010c7e7f39043316495a24 100644 (file)
@@ -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
@@ -23,6 +46,6 @@ func (p Piece) Hash() (ret Hash) {
        return
 }
 
-func (p Piece) Index() pieceIndex {
+func (p Piece) Index() int {
        return p.i
 }