-
Notifications
You must be signed in to change notification settings - Fork 1
/
example_test.go
71 lines (54 loc) · 1.27 KB
/
example_test.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
package bencode_test
import (
"bytes"
"fmt"
"github.com/cristalhq/bencode"
)
func ExampleMarshal() {
// data to process, most of the types are supported
var data any = map[string]any{
"1": 42,
"hello": "world",
"foo": []string{"bar", "baz"},
}
buf, err := bencode.Marshal(data)
checkErr(err)
fmt.Printf("marshaled: %s\n", string(buf))
// or via Encoder:
w := &bytes.Buffer{} // or any other io.Writer
err = bencode.NewEncoder(w).Encode(data)
checkErr(err)
// Output:
// marshaled: d1:1i42e3:fool3:bar3:baze5:hello5:worlde
}
func ExampleMarshalTo() {
var data any = map[string]any{
"1": 42,
"hello": "world",
"foo": []string{"bar", "baz"},
}
buf := make([]byte, 0, 128)
buf, err := bencode.MarshalTo(buf, data)
checkErr(err)
fmt.Printf("marshaled: %s\n", string(buf))
// Output:
// marshaled: d1:1i42e3:fool3:bar3:baze5:hello5:worlde
}
func ExampleUnmarshal() {
var data any
buf := []byte("li1ei42ee")
err := bencode.Unmarshal(buf, &data)
checkErr(err)
// or via Decoder:
r := bytes.NewBufferString("li1ei42ee") // or any other io.Reader
err = bencode.NewDecoder(r).Decode(&data)
checkErr(err)
fmt.Printf("unmarshaled: %v\n", data)
// Output:
// unmarshaled: [1 42]
}
func checkErr(err error) {
if err != nil {
panic(err)
}
}