encode.go 1001 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package jsonpb
  2. import (
  3. "bytes"
  4. "sync"
  5. "github.com/golang/protobuf/jsonpb"
  6. "github.com/golang/protobuf/proto"
  7. )
  8. var marshaller = &jsonpb.Marshaler{EmitDefaults: true, OrigName: true, EnumsAsInts: true}
  9. func Marshal(pb proto.Message) (string, error) {
  10. e := newEncodeState()
  11. if err := marshaller.Marshal(e, pb); err != nil {
  12. return "", err
  13. }
  14. s := e.String()
  15. e.Reset()
  16. encodeStatePool.Put(e)
  17. return s, nil
  18. }
  19. func MarshalBytes(pb proto.Message) ([]byte, error) {
  20. e := newEncodeState()
  21. if err := marshaller.Marshal(e, pb); err != nil {
  22. return nil, err
  23. }
  24. buf := append([]byte(nil), e.Bytes()...)
  25. e.Reset()
  26. encodeStatePool.Put(e)
  27. return buf, nil
  28. }
  29. // An encodeState encodes proto into a bytes.Buffer.
  30. type encodeState struct {
  31. *bytes.Buffer
  32. }
  33. var encodeStatePool sync.Pool
  34. func newEncodeState() *encodeState {
  35. if v := encodeStatePool.Get(); v != nil {
  36. e := v.(*encodeState)
  37. e.Reset()
  38. return e
  39. }
  40. return &encodeState{Buffer: bytes.NewBuffer(make([]byte, 0, 2048))}
  41. }