2019-01-10 12:42:02 +03:00
|
|
|
package json
|
|
|
|
|
|
|
|
import (
|
2020-09-10 15:17:23 +03:00
|
|
|
"bytes"
|
2019-01-10 12:42:02 +03:00
|
|
|
"encoding/json"
|
2019-06-09 06:50:50 +03:00
|
|
|
|
2020-09-10 15:17:23 +03:00
|
|
|
oldjsonpb "github.com/golang/protobuf/jsonpb"
|
|
|
|
oldproto "github.com/golang/protobuf/proto"
|
2020-04-08 12:50:19 +03:00
|
|
|
"github.com/oxtoacart/bpool"
|
2020-08-25 15:41:48 +03:00
|
|
|
jsonpb "google.golang.org/protobuf/encoding/protojson"
|
|
|
|
"google.golang.org/protobuf/proto"
|
2019-01-10 12:42:02 +03:00
|
|
|
)
|
|
|
|
|
2020-08-25 15:41:48 +03:00
|
|
|
var jsonpbMarshaler = &jsonpb.MarshalOptions{}
|
2020-09-10 15:17:23 +03:00
|
|
|
var oldjsonpbMarshaler = &oldjsonpb.Marshaler{}
|
2020-04-08 12:50:19 +03:00
|
|
|
|
|
|
|
// create buffer pool with 16 instances each preallocated with 256 bytes
|
|
|
|
var bufferPool = bpool.NewSizedBufferPool(16, 256)
|
|
|
|
|
2019-01-10 12:42:02 +03:00
|
|
|
type Marshaler struct{}
|
|
|
|
|
|
|
|
func (j Marshaler) Marshal(v interface{}) ([]byte, error) {
|
2020-09-10 15:17:23 +03:00
|
|
|
switch m := v.(type) {
|
|
|
|
case proto.Message:
|
|
|
|
return jsonpbMarshaler.Marshal(m)
|
|
|
|
case oldproto.Message:
|
|
|
|
buf, err := oldjsonpbMarshaler.MarshalToString(m)
|
|
|
|
return []byte(buf), err
|
2020-04-08 12:50:19 +03:00
|
|
|
}
|
2019-01-10 12:42:02 +03:00
|
|
|
return json.Marshal(v)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (j Marshaler) Unmarshal(d []byte, v interface{}) error {
|
2020-09-10 15:17:23 +03:00
|
|
|
switch m := v.(type) {
|
|
|
|
case proto.Message:
|
|
|
|
return jsonpb.Unmarshal(d, m)
|
|
|
|
case oldproto.Message:
|
|
|
|
return oldjsonpb.Unmarshal(bytes.NewReader(d), m)
|
2019-06-09 06:50:50 +03:00
|
|
|
}
|
2019-01-10 12:42:02 +03:00
|
|
|
return json.Unmarshal(d, v)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (j Marshaler) String() string {
|
|
|
|
return "json"
|
|
|
|
}
|