/
spec.go
61 lines (52 loc) · 1.14 KB
/
spec.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package testutil
import (
"io"
"io/ioutil"
"strings"
"github.com/anacrolix/missinggo/expect"
"github.com/anacrolix/torrent/bencode"
"github.com/anacrolix/torrent/metainfo"
)
type File struct {
Name string
Data string
}
type Torrent struct {
Files []File
Name string
}
func (t *Torrent) IsDir() bool {
return len(t.Files) == 1 && t.Files[0].Name == ""
}
func (t *Torrent) GetFile(name string) *File {
if t.IsDir() && t.Name == name {
return &t.Files[0]
}
for _, f := range t.Files {
if f.Name == name {
return &f
}
}
return nil
}
func (t *Torrent) Info(pieceLength int64) metainfo.Info {
info := metainfo.Info{
Name: t.Name,
PieceLength: pieceLength,
}
if t.IsDir() {
info.Length = int64(len(t.Files[0].Data))
}
err := info.GeneratePieces(func(fi metainfo.FileInfo) (io.ReadCloser, error) {
return ioutil.NopCloser(strings.NewReader(t.GetFile(strings.Join(fi.Path, "/")).Data)), nil
})
expect.Nil(err)
return info
}
func (t *Torrent) Metainfo(pieceLength int64) *metainfo.MetaInfo {
mi := metainfo.MetaInfo{}
var err error
mi.InfoBytes, err = bencode.Marshal(t.Info(pieceLength))
expect.Nil(err)
return &mi
}