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