Skip to content

Commit d4b4b6a

Browse files
echistyakovfacebook-github-bot
authored andcommitted
Add serializer V2 implementation
Summary: A more idiomatic and faster-performing API for serialization. # Idiomatic: We are following the same pattern as other Encoder-style APIs in Go lib - e.g.: https://pkg.go.dev/encoding/gob#Encoder https://pkg.go.dev/encoding/json#Encoder This means - accepting a `io.Writer` in the constructor and providing an `Encode` method. # Faster-performance: As shown by benchmarks downstream - this updated API performs faster due to fewer allocations/writes. Reviewed By: podtserkovskiy Differential Revision: D71160874 fbshipit-source-id: 3dceef4882751e5187c3d5c174b3c92568daea91
1 parent bc26b3f commit d4b4b6a

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

third-party/thrift/src/thrift/lib/go/thrift/serializer.go

+34
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ package thrift
1818

1919
import (
2020
"bytes"
21+
"io"
2122

2223
"github.com/facebook/fbthrift/thrift/lib/go/thrift/types"
2324
)
@@ -63,6 +64,31 @@ func NewSimpleJSONSerializer() *Serializer {
6364
return &Serializer{buffer: buffer, encoder: encoder}
6465
}
6566

67+
// A SerializerV2 is used to turn a Struct in to a byte stream
68+
type SerializerV2 struct {
69+
format types.Format
70+
}
71+
72+
// NewBinarySerializerV2 creates a new serializer using the binary format
73+
func NewBinarySerializerV2(readWriter types.ReadWriteSizer) *SerializerV2 {
74+
return &SerializerV2{format: NewBinaryFormat(readWriter)}
75+
}
76+
77+
// NewCompactSerializerV2 creates a new serializer using the compact format
78+
func NewCompactSerializerV2(readWriter types.ReadWriteSizer) *SerializerV2 {
79+
return &SerializerV2{format: NewCompactFormat(readWriter)}
80+
}
81+
82+
// NewCompactJSONSerializerV2 creates a new serializer using the CompactJSON format
83+
func NewCompactJSONSerializerV2(readWriter io.ReadWriter) *SerializerV2 {
84+
return &SerializerV2{format: NewCompactJSONFormat(readWriter)}
85+
}
86+
87+
// NewSimpleJSONSerializerV2 creates a new serializer using the SimpleJSON format
88+
func NewSimpleJSONSerializerV2(readWriter io.ReadWriter) *SerializerV2 {
89+
return &SerializerV2{format: NewSimpleJSONFormat(readWriter)}
90+
}
91+
6692
// EncodeCompact serializes msg using the compact format
6793
func EncodeCompact(msg types.WritableStruct) ([]byte, error) {
6894
return NewCompactSerializer().Write(msg)
@@ -105,3 +131,11 @@ func (s *Serializer) Write(msg types.WritableStruct) ([]byte, error) {
105131

106132
return serBytes, nil
107133
}
134+
135+
// Encode encodes a Thrift struct into the underlying format/writer.
136+
func (s *SerializerV2) Encode(msg types.WritableStruct) error {
137+
if err := msg.Write(s.format); err != nil {
138+
return err
139+
}
140+
return s.format.Flush()
141+
}

0 commit comments

Comments
 (0)