-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
thrift/thriftutil: Add Clone method helper
- Loading branch information
1 parent
5f0cb04
commit 5ba5058
Showing
2 changed files
with
80 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
package thriftutil | ||
|
||
import ( | ||
"github.com/upfluence/pkg/bytesutil" | ||
"github.com/upfluence/thrift/lib/go/thrift" | ||
) | ||
|
||
var ( | ||
transportFactory = BinaryProtocolFactory | ||
bufferPool = bytesutil.NewBufferPool() | ||
) | ||
|
||
func Clone[T any, PT interface { | ||
thrift.TStruct | ||
*T | ||
}](in PT) (PT, error) { | ||
var ( | ||
cpy PT = new(T) | ||
buf = bufferPool.Get() | ||
) | ||
|
||
defer bufferPool.Put(buf) | ||
|
||
if err := in.Write(transportFactory.GetProtocol(WrapWriter(buf))); err != nil { | ||
return nil, err | ||
} | ||
|
||
if err := cpy.Read(transportFactory.GetProtocol(WrapReader(buf))); err != nil { | ||
return nil, err | ||
} | ||
|
||
return cpy, nil | ||
} | ||
|
||
func MustClone[T any, PT interface { | ||
thrift.TStruct | ||
*T | ||
}](in PT) PT { | ||
res, err := Clone(in) | ||
|
||
if err != nil { | ||
panic(err) | ||
} | ||
|
||
return res | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
package thriftutil | ||
|
||
import ( | ||
"testing" | ||
|
||
"github.com/stretchr/testify/assert" | ||
"github.com/stretchr/testify/require" | ||
"github.com/upfluence/thrift/lib/go/thrift" | ||
) | ||
|
||
type stringTStruct struct { | ||
s string | ||
} | ||
|
||
func (sts *stringTStruct) String() string { return sts.s } | ||
|
||
func (sts *stringTStruct) Write(p thrift.TProtocol) error { | ||
return p.WriteString(sts.s) | ||
} | ||
|
||
func (sts *stringTStruct) Read(p thrift.TProtocol) error { | ||
var err error | ||
|
||
sts.s, err = p.ReadString() | ||
|
||
return err | ||
} | ||
|
||
func TestClone(t *testing.T) { | ||
res, err := Clone(&stringTStruct{s: "foobar"}) | ||
|
||
require.NoError(t, err) | ||
assert.Equal(t, &stringTStruct{"foobar"}, res) | ||
} |