Skip to content

Commit

Permalink
Basic support for serializing v2 torrent file (#968)
Browse files Browse the repository at this point in the history
* Support marshalling FileTree

* Omit Pieces in torrent info if empty

Otherwise some BitTorrent client (e.g. libttorrent) will not be able to
parse v2 torrent file.
  • Loading branch information
Mivik authored Aug 26, 2024
1 parent f471182 commit 1b6a6f7
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 3 deletions.
29 changes: 29 additions & 0 deletions metainfo/file-tree.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,35 @@ func (ft *FileTree) UnmarshalBencode(bytes []byte) (err error) {

var _ bencode.Unmarshaler = (*FileTree)(nil)

func (ft *FileTree) MarshalBencode() (bytes []byte, err error) {
if ft.IsDir() {
dir := make(map[string]bencode.Bytes, len(ft.Dir))
for _, key := range ft.orderedKeys() {
if key == FileTreePropertiesKey {
continue
}
sub := g.MapMustGet(ft.Dir, key)
subBytes, err := sub.MarshalBencode()
if err != nil {
return nil, err
}
dir[key] = subBytes
}
return bencode.Marshal(dir)
} else {
fileBytes, err := bencode.Marshal(ft.File)
if err != nil {
return nil, err
}
res := map[string]bencode.Bytes{
"": fileBytes,
}
return bencode.Marshal(res)
}
}

var _ bencode.Marshaler = (*FileTree)(nil)

func (ft *FileTree) NumEntries() (num int) {
num = len(ft.Dir)
if g.MapContains(ft.Dir, FileTreePropertiesKey) {
Expand Down
6 changes: 3 additions & 3 deletions metainfo/info.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@ import (

// The info dictionary. See BEP 3 and BEP 52.
type Info struct {
PieceLength int64 `bencode:"piece length"` // BEP3
Pieces []byte `bencode:"pieces"` // BEP3
Name string `bencode:"name"` // BEP3
PieceLength int64 `bencode:"piece length"` // BEP3
Pieces []byte `bencode:"pieces,omitempty"` // BEP3
Name string `bencode:"name"` // BEP3
NameUtf8 string `bencode:"name.utf-8,omitempty"`
Length int64 `bencode:"length,omitempty"` // BEP3, mutually exclusive with Files
ExtendedFileAttrs
Expand Down

0 comments on commit 1b6a6f7

Please sign in to comment.