Skip to content

Commit 5ba5058

Browse files
thrift/thriftutil: Add Clone method helper
1 parent 5f0cb04 commit 5ba5058

File tree

2 files changed

+80
-0
lines changed

2 files changed

+80
-0
lines changed

thrift/thriftutil/clone.go

+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package thriftutil
2+
3+
import (
4+
"github.com/upfluence/pkg/bytesutil"
5+
"github.com/upfluence/thrift/lib/go/thrift"
6+
)
7+
8+
var (
9+
transportFactory = BinaryProtocolFactory
10+
bufferPool = bytesutil.NewBufferPool()
11+
)
12+
13+
func Clone[T any, PT interface {
14+
thrift.TStruct
15+
*T
16+
}](in PT) (PT, error) {
17+
var (
18+
cpy PT = new(T)
19+
buf = bufferPool.Get()
20+
)
21+
22+
defer bufferPool.Put(buf)
23+
24+
if err := in.Write(transportFactory.GetProtocol(WrapWriter(buf))); err != nil {
25+
return nil, err
26+
}
27+
28+
if err := cpy.Read(transportFactory.GetProtocol(WrapReader(buf))); err != nil {
29+
return nil, err
30+
}
31+
32+
return cpy, nil
33+
}
34+
35+
func MustClone[T any, PT interface {
36+
thrift.TStruct
37+
*T
38+
}](in PT) PT {
39+
res, err := Clone(in)
40+
41+
if err != nil {
42+
panic(err)
43+
}
44+
45+
return res
46+
}

thrift/thriftutil/clone_test.go

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package thriftutil
2+
3+
import (
4+
"testing"
5+
6+
"github.com/stretchr/testify/assert"
7+
"github.com/stretchr/testify/require"
8+
"github.com/upfluence/thrift/lib/go/thrift"
9+
)
10+
11+
type stringTStruct struct {
12+
s string
13+
}
14+
15+
func (sts *stringTStruct) String() string { return sts.s }
16+
17+
func (sts *stringTStruct) Write(p thrift.TProtocol) error {
18+
return p.WriteString(sts.s)
19+
}
20+
21+
func (sts *stringTStruct) Read(p thrift.TProtocol) error {
22+
var err error
23+
24+
sts.s, err = p.ReadString()
25+
26+
return err
27+
}
28+
29+
func TestClone(t *testing.T) {
30+
res, err := Clone(&stringTStruct{s: "foobar"})
31+
32+
require.NoError(t, err)
33+
assert.Equal(t, &stringTStruct{"foobar"}, res)
34+
}

0 commit comments

Comments
 (0)