/
codec.go
72 lines (61 loc) · 1.1 KB
/
codec.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
package codec
import (
"encoding"
"encoding/json"
"errors"
"fmt"
"path"
"path/filepath"
"strings"
"github.com/glaucusio/confetti/cti"
)
var Default = make(Map)
func init() {
cti.DefaultCodec = Default
}
func cleanpath(s string) string {
s = strings.TrimLeft(s, `/.\`)
s = filepath.FromSlash(s)
s = filepath.Clean(s)
s = filepath.ToSlash(s)
s = path.Join("/", s)
return s
}
func tobytes(v interface{}) (p []byte, err error) {
switch v := v.(type) {
case nil:
// ignore
case []byte:
p = v
case string:
p = []byte(v)
case encoding.TextMarshaler:
p, err = v.MarshalText()
case encoding.BinaryMarshaler:
p, err = v.MarshalBinary()
default:
err = fmt.Errorf("value is neither string nor []byte: %T", v)
}
switch {
case err != nil:
return nil, err
case len(p) == 0:
return nil, errors.New("byte slice is empty")
}
return p, nil
}
func nonil(v ...interface{}) interface{} {
for _, v := range v {
if v != nil {
return v
}
}
return nil
}
func reencode(in, out interface{}) error {
p, err := json.Marshal(in)
if err != nil {
return err
}
return json.Unmarshal(p, out)
}