-
Notifications
You must be signed in to change notification settings - Fork 25
/
encode_decode_test.go
109 lines (88 loc) · 2.12 KB
/
encode_decode_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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package bencode
import (
"errors"
"time"
)
type myBoolType bool
// MarshalBencode implements Marshaler.MarshalBencode
func (mbt myBoolType) MarshalBencode() ([]byte, error) {
var c string
if mbt {
c = "y"
} else {
c = "n"
}
return EncodeBytes(c)
}
// UnmarshalBencode implements Unmarshaler.UnmarshalBencode
func (mbt *myBoolType) UnmarshalBencode(b []byte) error {
var str string
err := DecodeBytes(b, &str)
if err != nil {
return err
}
switch str {
case "y":
*mbt = true
case "n":
*mbt = false
default:
err = errors.New("invalid myBoolType")
}
return err
}
type myBoolTextType bool
// MarshalText implements TextMarshaler.MarshalText
func (mbt myBoolTextType) MarshalText() ([]byte, error) {
if mbt {
return []byte("y"), nil
}
return []byte("n"), nil
}
// UnmarshalText implements TextUnmarshaler.UnmarshalText
func (mbt *myBoolTextType) UnmarshalText(b []byte) error {
switch string(b) {
case "y":
*mbt = true
case "n":
*mbt = false
default:
return errors.New("invalid myBoolType")
}
return nil
}
type myTimeType struct {
time.Time
}
// MarshalBencode implements Marshaler.MarshalBencode
func (mtt myTimeType) MarshalBencode() ([]byte, error) {
return EncodeBytes(mtt.Time.Unix())
}
// UnmarshalBencode implements Unmarshaler.UnmarshalBencode
func (mtt *myTimeType) UnmarshalBencode(b []byte) error {
var epoch int64
err := DecodeBytes(b, &epoch)
if err != nil {
return err
}
mtt.Time = time.Unix(epoch, 0)
return nil
}
type errorMarshalType struct{}
// MarshalBencode implements Marshaler.MarshalBencode
func (emt errorMarshalType) MarshalBencode() ([]byte, error) {
return nil, errors.New("oops")
}
// UnmarshalBencode implements Unmarshaler.UnmarshalBencode
func (emt errorMarshalType) UnmarshalBencode([]byte) error {
return errors.New("oops")
}
type errorTextMarshalType struct{}
// MarshalText implements TextMarshaler.MarshalText
func (emt errorTextMarshalType) MarshalText() ([]byte, error) {
return nil, errors.New("oops")
}
// UnmarshalText implements TextUnmarshaler.UnmarshalText
func (emt errorTextMarshalType) UnmarshalText([]byte) error {
return errors.New("oops")
}