-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary.go
More file actions
83 lines (70 loc) · 1.58 KB
/
Copy pathbinary.go
File metadata and controls
83 lines (70 loc) · 1.58 KB
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
package binary
import (
"bytes"
"io"
"github.com/tinywasm/fmt"
"github.com/tinywasm/model"
)
// Encode encodes input to output.
// input: Encodable struct
// output: *[]byte or io.Writer
func Encode(input model.Encodable, output any) error {
if input == nil || input.IsNil() {
return fmt.Err("Encode: input is nil")
}
w := getWriter()
defer putWriter(w)
var err error
switch out := output.(type) {
case *[]byte:
var buffer bytes.Buffer
w.reset(&buffer)
input.EncodeFields(w)
if w.err == nil {
*out = buffer.Bytes()
}
err = w.err
case io.Writer:
w.reset(out)
input.EncodeFields(w)
err = w.err
default:
err = fmt.Err("Encode", "output", "must be *[]byte or io.Writer")
}
return err
}
// Decode decodes input to output.
// input: []byte or io.Reader
// output: pointer to Decodable struct
func Decode(input, output any) error {
if output == nil {
return fmt.Err("Decode: output is nil")
}
dec, ok := output.(model.Decodable)
if !ok {
return fmt.Err("Decode", "output", "must implement model.Decodable")
}
if dec.IsNil() {
return fmt.Err("Decode: output is nil")
}
r := getReader()
defer putReader(r)
var err error
switch in := input.(type) {
case []byte:
r.reset(bytes.NewReader(in))
dec.DecodeFields(r)
case io.Reader:
r.reset(in)
dec.DecodeFields(r)
default:
err = fmt.Err("Decode", "input", "must be []byte or io.Reader")
}
return err
}
// SetLog is deprecated and does nothing.
func SetLog(fn func(msg ...any)) {}
// Errorf is a helper for fmt.Errorf
func Errorf(format string, a ...any) error {
return fmt.Errf(format, a...)
}