-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRPCMixedParamsCodec.go
64 lines (57 loc) · 1.63 KB
/
RPCMixedParamsCodec.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
package wsrpc
import (
"bytes"
"encoding/json"
"errors"
"reflect"
)
type RPCMixedParamsCodec struct {
namedCodec RPCNamedParamsCodec
positionalCodec RPCPositionalParamsCodec
}
func NewRPCMixedParamsCodec(names []string) *RPCMixedParamsCodec {
return &RPCMixedParamsCodec{
namedCodec: constructRPCNamedParamsCodec(names),
positionalCodec: RPCPositionalParamsCodec{},
}
}
func (c *RPCMixedParamsCodec) Encode(values []reflect.Value) (json.RawMessage, error) {
return c.namedCodec.Encode(values)
}
func (c *RPCMixedParamsCodec) 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
}
if t == nil {
// JSON `null`
return c.positionalCodec.Decode([]byte("[]"), valueTypes)
}
if d, ok := t.(json.Delim); ok {
switch d.String() {
case "{":
return c.namedCodec.Decode(rawValues, valueTypes)
case "[":
return c.positionalCodec.Decode(rawValues, valueTypes)
}
}
return nil, errors.New("RPCNamedParamsCodec can handle array and object and null only")
}
func (c *RPCMixedParamsCodec) AllowExcessive() bool {
value1 := c.positionalCodec.AllowExcessive()
value2 := c.namedCodec.AllowExcessive()
if value1 != value2 {
panic(errors.New("allow excessive mismatch for internal codecs"))
}
return value1
}
func (c *RPCMixedParamsCodec) WithAllowExcessive(allowExcessive bool) *RPCMixedParamsCodec {
c.positionalCodec.WithAllowExcessive(allowExcessive)
c.namedCodec.WithAllowExcessive(allowExcessive)
return c
}