2019-01-10 11:42:02 +02:00
|
|
|
package json
|
|
|
|
|
|
|
|
import (
|
2020-04-08 11:50:19 +02:00
|
|
|
"bytes"
|
2019-01-10 11:42:02 +02:00
|
|
|
"encoding/json"
|
2019-06-09 05:50:50 +02:00
|
|
|
|
|
|
|
"github.com/golang/protobuf/jsonpb"
|
|
|
|
"github.com/golang/protobuf/proto"
|
2020-04-08 11:50:19 +02:00
|
|
|
"github.com/oxtoacart/bpool"
|
2019-01-10 11:42:02 +02:00
|
|
|
)
|
|
|
|
|
2020-04-08 11:50:19 +02:00
|
|
|
var jsonpbMarshaler = &jsonpb.Marshaler{}
|
|
|
|
|
2022-09-30 16:27:07 +02:00
|
|
|
// create buffer pool with 16 instances each preallocated with 256 bytes.
|
2020-04-08 11:50:19 +02:00
|
|
|
var bufferPool = bpool.NewSizedBufferPool(16, 256)
|
|
|
|
|
2019-01-10 11:42:02 +02:00
|
|
|
type Marshaler struct{}
|
|
|
|
|
|
|
|
func (j Marshaler) Marshal(v interface{}) ([]byte, error) {
|
2020-04-08 11:50:19 +02:00
|
|
|
if pb, ok := v.(proto.Message); ok {
|
|
|
|
buf := bufferPool.Get()
|
|
|
|
defer bufferPool.Put(buf)
|
|
|
|
if err := jsonpbMarshaler.Marshal(buf, pb); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return buf.Bytes(), nil
|
|
|
|
}
|
2019-01-10 11:42:02 +02:00
|
|
|
return json.Marshal(v)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (j Marshaler) Unmarshal(d []byte, v interface{}) error {
|
2019-06-09 05:50:50 +02:00
|
|
|
if pb, ok := v.(proto.Message); ok {
|
2020-04-08 11:50:19 +02:00
|
|
|
return jsonpb.Unmarshal(bytes.NewReader(d), pb)
|
2019-06-09 05:50:50 +02:00
|
|
|
}
|
2019-01-10 11:42:02 +02:00
|
|
|
return json.Unmarshal(d, v)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (j Marshaler) String() string {
|
|
|
|
return "json"
|
|
|
|
}
|