diff --git a/metainfo/fileinfo.go b/metainfo/fileinfo.go index bf47215634..82e1c94f81 100644 --- a/metainfo/fileinfo.go +++ b/metainfo/fileinfo.go @@ -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 } diff --git a/metainfo/info.go b/metainfo/info.go index 2798fd5902..d1b54d44d6 100644 --- a/metainfo/info.go +++ b/metainfo/info.go @@ -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 { diff --git a/metainfo/piece.go b/metainfo/piece.go index d8895384d0..c7377f5db6 100644 --- a/metainfo/piece.go +++ b/metainfo/piece.go @@ -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 }