]> Sergey Matveev's repositories - btrtrc.git/blob - metainfo/piece.go
c1c71221c3d5c79220b9d7d4838bc56c3c62d4e5
[btrtrc.git] / metainfo / piece.go
1 package metainfo
2
3 import (
4         g "github.com/anacrolix/generics"
5 )
6
7 type Piece struct {
8         Info *Info // Can we embed the fields here instead, or is it something to do with saving memory?
9         i    pieceIndex
10 }
11
12 type pieceIndex = int
13
14 func (p Piece) Length() int64 {
15         if p.Info.HasV2() {
16                 var offset int64
17                 pieceLength := p.Info.PieceLength
18                 lastFileEnd := int64(0)
19                 done := false
20                 p.Info.FileTree.upvertedFiles(pieceLength, func(fi FileInfo) {
21                         if done {
22                                 return
23                         }
24                         fileStartPiece := int(offset / pieceLength)
25                         if fileStartPiece > p.i {
26                                 done = true
27                                 return
28                         }
29                         lastFileEnd = offset + fi.Length
30                         offset = (lastFileEnd + pieceLength - 1) / pieceLength * pieceLength
31                 })
32                 ret := min(lastFileEnd-int64(p.i)*pieceLength, pieceLength)
33                 if ret <= 0 {
34                         panic(ret)
35                 }
36                 return ret
37         }
38         if p.i == p.Info.NumPieces()-1 {
39                 return p.Info.TotalLength() - int64(p.i)*p.Info.PieceLength
40         }
41         return p.Info.PieceLength
42 }
43
44 func (p Piece) Offset() int64 {
45         return int64(p.i) * p.Info.PieceLength
46 }
47
48 func (p Piece) V1Hash() (ret g.Option[Hash]) {
49         if !p.Info.HasV1() {
50                 return
51         }
52         copy(ret.Value[:], p.Info.Pieces[p.i*HashSize:(p.i+1)*HashSize])
53         ret.Ok = true
54         return
55 }
56
57 func (p Piece) Index() int {
58         return p.i
59 }