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