-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjson.go
39 lines (31 loc) · 789 Bytes
/
json.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
package option
import (
"github.com/bytedance/sonic"
"slices"
)
type JsonCoder interface {
Marshal(any) ([]byte, error)
Unmarshal([]byte, any) error
}
var (
defaultCoder JsonCoder = sonic.ConfigStd
)
func SetJsonCoder(coder JsonCoder) {
defaultCoder = coder
}
// MarshalJSON converts the option to JSON.
func (opt *option[T]) MarshalJSON() ([]byte, error) {
if opt.cause != nil {
return []byte(`null`), nil
}
return defaultCoder.Marshal(opt.value)
}
// UnmarshalJSON converts JSON to an option.
func (opt *option[T]) UnmarshalJSON(data []byte) error {
if len(data) == 0 || slices.Equal(data, []byte("null")) ||
slices.Equal(data, []byte("{}")) || slices.Equal(data, []byte("[]")) {
opt.cause = Nil
return nil
}
return defaultCoder.Unmarshal(data, &opt.value)
}