-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
104 lines (98 loc) · 2.51 KB
/
main.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
package codec
import (
"io"
"github.com/toxyl/flo/errors"
"github.com/toxyl/flo/utils"
)
type Codec struct {
Name string
Decode func(input io.Reader, output any) error
DecodeString func(input string, output any) error
DecodeBytes func(input []byte, output any) error
Encode func(input any, output io.Writer) error
EncodeString func(input any) string
EncodeBytes func(input any) []byte
}
func NewCodec(
name string,
fnEncode func(input any, output io.Writer) error,
fnDecode func(input io.Reader, output any) error,
) *Codec {
c := &Codec{
Name: name,
Encode: func(source any, target io.Writer) error {
return errors.ErrNoEncoderImplemented
},
EncodeString: func(input any) string {
return "no encoder implemented for " + name
},
EncodeBytes: func(input any) []byte {
return []byte("no encoder implemented for " + name)
},
Decode: func(source io.Reader, target any) error {
return errors.ErrNoDecoderImplemented
},
DecodeString: func(source string, target any) error {
return errors.ErrNoDecoderImplemented
},
DecodeBytes: func(source []byte, target any) error {
return errors.ErrNoDecoderImplemented
},
}
if fnEncode != nil {
c.Encode = func(source any, target io.Writer) error {
switch t := target.(type) {
case io.WriteCloser:
defer t.Close()
}
return fnEncode(utils.Dereference(source), target)
}
c.EncodeString = func(input any) string {
res := utils.NewStringIO("")
if err := c.Encode(input, res); err != nil {
return ""
}
return res.String()
}
c.EncodeBytes = func(input any) []byte {
res := utils.NewBytesIO([]byte{})
if err := c.Encode(input, res); err != nil {
return []byte{}
}
return res.Bytes()
}
}
if fnDecode != nil {
c.Decode = func(source io.Reader, target any) error {
switch t := source.(type) {
case io.ReadCloser:
defer t.Close()
}
if !utils.IsPointer(target) {
return errors.ErrMustBePointer(target)
}
return fnDecode(source, target)
}
c.DecodeString = func(source string, target any) error {
if !utils.IsPointer(target) {
return errors.ErrMustBePointer(target)
}
in := utils.NewStringIO(source)
if err := c.Decode(in, target); err != nil {
return err
}
return nil
}
c.DecodeBytes = func(source []byte, target any) error {
if !utils.IsPointer(target) {
return errors.ErrMustBePointer(target)
}
in := utils.NewBytesIO(source)
if err := c.Decode(in, target); err != nil {
return err
}
return nil
}
}
return c
}