forked from s7techlab/cckit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
to_bytes.go
81 lines (67 loc) · 1.76 KB
/
to_bytes.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
package convert
import (
"encoding/json"
"fmt"
"reflect"
"strconv"
"github.com/pkg/errors"
"github.com/golang/protobuf/proto"
)
// ArgsToBytes converts func arguments to bytes
func ArgsToBytes(iargs ...interface{}) (aa [][]byte, err error) {
args := make([][]byte, len(iargs))
for i, arg := range iargs {
val, err := ToBytes(arg)
if err != nil {
return nil, errors.Wrap(err, fmt.Sprintf(`unable to convert invoke arg[%d]`, i))
}
args[i] = val
}
return args, nil
}
// ToBytes converts inteface{} (string, []byte , struct to ToByter interface to []byte for storing in state
func ToBytes(value interface{}) ([]byte, error) {
if value == nil {
return nil, nil
}
switch value.(type) {
// first priority if value implements ToByter interface
case ToByter:
return value.(ToByter).ToBytes()
case proto.Message:
return proto.Marshal(proto.Clone(value.(proto.Message)))
case bool:
return []byte(strconv.FormatBool(value.(bool))), nil
case string:
return []byte(value.(string)), nil
case uint:
return []byte(fmt.Sprint(value.(uint))), nil
case int:
return []byte(fmt.Sprint(value.(int))), nil
case int32:
return []byte(fmt.Sprint(value.(int32))), nil
case []byte:
return value.([]byte), nil
default:
valueType := reflect.TypeOf(value).Kind()
switch valueType {
case reflect.Ptr:
fallthrough
case reflect.Struct:
fallthrough
case reflect.Array:
fallthrough
case reflect.Map:
fallthrough
case reflect.Slice:
return json.Marshal(value)
// used when type based on string
case reflect.String:
return []byte(reflect.ValueOf(value).String()), nil
default:
return nil, fmt.Errorf(
`toBytes converting supports ToByter interface,struct,array,slice,bool and string, current type is %s`,
valueType)
}
}
}