-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbencode.go
72 lines (62 loc) · 1.56 KB
/
bencode.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
62
63
64
65
66
67
68
69
70
71
72
package bencode
import (
"bytes"
)
// Marshaler is the interface implemented by types that
// can marshal themselves into valid Bencode.
type Marshaler interface {
MarshalBencode() ([]byte, error)
}
// Marshal returns bencode encoding of v.
func Marshal(v any) ([]byte, error) {
buf := &bytes.Buffer{}
if err := NewEncoder(buf).Encode(v); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
// MarshalTo returns bencode encoding of v written to dst.
func MarshalTo(dst []byte, v any) ([]byte, error) {
enc := &Encoder{buf: dst}
if err := enc.marshal(v); err != nil {
return nil, err
}
return enc.buf, nil
}
// Unmarshaler is the interface implemented by types
// that can unmarshal a Bencode description of themselves.
type Unmarshaler interface {
UnmarshalBencode([]byte) error
}
// Unmarshal parses the bencoded data and stores the result
// in the value pointed to by v.
func Unmarshal(data []byte, v any) error {
d := NewDecodeBytes(data)
if err := d.Decode(v); err != nil {
return err
}
return nil
}
// A is a Bencode array.
//
// Example:
//
// bencode.A{"hello", "world", 3.14159, bencode.D{{"foo", 12345}}}
type A []any
// D is an ordered representation of a Bencode document.
//
// Example usage:
//
// bencode.D{{"hello", "world"}, {"foo", "bar"}, {"pi", 3.14159}}
type D []e
// e represents a Bencode element for a D. It is usually used inside a D.
type e struct {
K string
V any
}
// M is an unordered representation of a Bencode document.
//
// Example usage:
//
// bencode.M{"hello": "world", "foo": "bar", "pi": 3.14159}
type M map[string]any