forked from json-iterator/go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
types.go
50 lines (42 loc) · 1.03 KB
/
types.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
package test
import (
"bytes"
"encoding/base64"
"encoding/json"
"strings"
)
type marshalerForTest string
func encode(str string) string {
buf := bytes.Buffer{}
b64 := base64.NewEncoder(base64.StdEncoding, &buf)
if _, err := b64.Write([]byte(str)); err != nil {
panic(err)
}
if err := b64.Close(); err != nil {
panic(err)
}
return buf.String()
}
func decode(str string) string {
if len(str) == 0 {
return ""
}
b64 := base64.NewDecoder(base64.StdEncoding, strings.NewReader(str))
bs := make([]byte, len(str))
if n, err := b64.Read(bs); err != nil {
panic(err)
} else {
bs = bs[:n]
}
return string(bs)
}
func (m marshalerForTest) MarshalJSON() ([]byte, error) {
return []byte(`"MANUAL__` + encode(string(m)) + `"`), nil
}
func (m *marshalerForTest) UnmarshalJSON(text []byte) error {
*m = marshalerForTest(decode(strings.TrimPrefix(strings.Trim(string(text), `"`), "MANUAL__")))
return nil
}
var _ json.Marshaler = *new(marshalerForTest)
var _ json.Unmarshaler = new(marshalerForTest)
type typeForTest marshalerForTest