]> Sergey Matveev's repositories - btrtrc.git/blob - metainfo/infoex.go
metainfo: Move method in wrong file
[btrtrc.git] / metainfo / infoex.go
1 package metainfo
2
3 import "github.com/anacrolix/torrent/bencode"
4
5 // A wrapper around Info that exposes the Bytes directly, in case marshalling
6 // and unmarshalling Info doesn't produce the same bytes.
7 type InfoEx struct {
8         Info
9         // Set when unmarshalling, and used when marshalling. Call .UpdateBytes to
10         // set it by bencoding Info.
11         Bytes []byte
12 }
13
14 var (
15         _ bencode.Marshaler   = &InfoEx{}
16         _ bencode.Unmarshaler = &InfoEx{}
17 )
18
19 // Marshals .Info, and sets .Bytes with the result.
20 func (ie *InfoEx) UpdateBytes() {
21         var err error
22         ie.Bytes, err = bencode.Marshal(&ie.Info)
23         if err != nil {
24                 panic(err)
25         }
26 }
27
28 // Returns the SHA1 hash of .Bytes.
29 func (ie *InfoEx) Hash() Hash {
30         return HashBytes(ie.Bytes)
31 }
32
33 func (ie *InfoEx) UnmarshalBencode(data []byte) error {
34         ie.Bytes = append([]byte(nil), data...)
35         return bencode.Unmarshal(data, &ie.Info)
36 }
37
38 func (ie *InfoEx) MarshalBencode() ([]byte, error) {
39         if ie.Bytes == nil {
40                 ie.UpdateBytes()
41         }
42         return ie.Bytes, nil
43 }
44
45 func (info *InfoEx) Piece(i int) Piece {
46         return Piece{info, i}
47 }