-
Notifications
You must be signed in to change notification settings - Fork 0
/
RPCPositionalParamsCodec.go
89 lines (82 loc) · 2.01 KB
/
RPCPositionalParamsCodec.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
package wsrpc
import (
"bytes"
"encoding/json"
"errors"
"reflect"
)
type RPCPositionalParamsCodec struct {
allowExcessive bool
}
func NewRPCPositionalParamsCodec() *RPCPositionalParamsCodec {
return &RPCPositionalParamsCodec{
true,
}
}
func (*RPCPositionalParamsCodec) Encode(values []reflect.Value) (json.RawMessage, error) {
nParams := len(values)
result := make([]interface{}, nParams)
for i := 0; i < nParams; i++ {
result[i] = values[i].Interface()
}
return json.Marshal(result)
}
func (c *RPCPositionalParamsCodec) Decode(rawValues json.RawMessage, valueTypes []reflect.Type) ([]reflect.Value, error) {
if len(valueTypes) == 0 {
// empty
return []reflect.Value{}, nil
}
dec := json.NewDecoder(bytes.NewReader(rawValues))
t, err := dec.Token()
if err != nil {
return nil, err
}
var valuesInJSON []json.RawMessage
if t == nil {
// JSON `null`
valuesInJSON = []json.RawMessage{}
} else if d, ok := t.(json.Delim); ok {
if d.String() != "[" {
return nil, errors.New("RPCPositionalParamsCodec can handle array and null only")
}
err = json.Unmarshal(rawValues, &valuesInJSON)
if err != nil {
return nil, err
}
}
values := make([]reflect.Value, len(valueTypes))
for i := 0; i < len(values); i++ {
pType := valueTypes[i]
if pType.Kind() == reflect.Ptr {
values[i] = reflect.New(pType.Elem())
} else {
values[i] = reflect.New(pType)
}
}
for i, curArg := range valuesInJSON {
if i >= len(valueTypes) {
if !c.allowExcessive {
return nil, errors.New("too many arguments")
}
break
}
err = json.Unmarshal(curArg, values[i].Interface())
if err != nil {
return nil, err
}
}
for i := 0; i < len(values); i++ {
pType := valueTypes[i]
if pType.Kind() != reflect.Ptr {
values[i] = values[i].Elem()
}
}
return values, nil
}
func (c *RPCPositionalParamsCodec) AllowExcessive() bool {
return c.allowExcessive
}
func (c *RPCPositionalParamsCodec) WithAllowExcessive(allowExcessive bool) *RPCPositionalParamsCodec {
c.allowExcessive = allowExcessive
return c
}