8 "github.com/anacrolix/libtorgo/bencode"
11 // Information specific to a single file inside the MetaInfo structure.
12 type FileInfo struct {
13 Length int64 `bencode:"length"`
14 Path []string `bencode:"path"`
17 // Load a MetaInfo from an io.Reader. Returns a non-nil error in case of
19 func Load(r io.Reader) (*MetaInfo, error) {
21 d := bencode.NewDecoder(r)
29 // Convenience function for loading a MetaInfo from a file.
30 func LoadFromFile(filename string) (*MetaInfo, error) {
31 f, err := os.Open(filename)
39 // The info dictionary.
41 PieceLength int64 `bencode:"piece length"`
42 Pieces []byte `bencode:"pieces"`
43 Name string `bencode:"name"`
44 Length int64 `bencode:"length,omitempty"`
45 Private bool `bencode:"private,omitempty"`
46 Files []FileInfo `bencode:"files,omitempty"`
49 func (me *Info) TotalLength() (ret int64) {
51 for _, fi := range me.Files {
60 func (me *Info) NumPieces() int {
61 return len(me.Pieces) / 20
64 type Piece interface {
74 func (me piece) Length() int64 {
75 if me.i == me.Info.NumPieces()-1 {
76 return me.Info.TotalLength() - int64(me.i)*me.Info.PieceLength
78 return me.Info.PieceLength
81 func (me piece) Hash() []byte {
82 return me.Info.Pieces[me.i*20 : (me.i+1)*20]
85 func (me *Info) Piece(i int) piece {
89 func (i *Info) IsDir() bool {
90 return len(i.Files) != 0
93 // The files field, converted up from the old single-file in the parent info
94 // dict if necessary. This is a helper to avoid having to conditionally handle
95 // single and multi-file torrent infos.
96 func (i *Info) UpvertedFiles() []FileInfo {
97 if len(i.Files) == 0 {
100 // Callers should determine that Info.Name is the basename, and
101 // thus a regular file.
108 // The info dictionary with its hash and raw bytes exposed, as these are
109 // important to Bittorrent.
117 _ bencode.Marshaler = InfoEx{}
118 _ bencode.Unmarshaler = &InfoEx{}
121 func (this *InfoEx) UnmarshalBencode(data []byte) error {
122 this.Bytes = make([]byte, 0, len(data))
123 this.Bytes = append(this.Bytes, data...)
125 _, err := h.Write(this.Bytes)
129 this.Hash = h.Sum(nil)
130 return bencode.Unmarshal(data, &this.Info)
133 func (this InfoEx) MarshalBencode() ([]byte, error) {
134 if this.Bytes != nil {
135 return this.Bytes, nil
137 return bencode.Marshal(&this.Info)
140 type MetaInfo struct {
141 Info InfoEx `bencode:"info"`
142 Announce string `bencode:"announce"`
143 AnnounceList [][]string `bencode:"announce-list,omitempty"`
144 CreationDate int64 `bencode:"creation date,omitempty"`
145 Comment string `bencode:"comment,omitempty"`
146 CreatedBy string `bencode:"created by,omitempty"`
147 Encoding string `bencode:"encoding,omitempty"`
148 URLList interface{} `bencode:"url-list,omitempty"`