Skip to content

Commit

Permalink
thrift/thriftutil: Add Clone method helper
Browse files Browse the repository at this point in the history
  • Loading branch information
AlexisMontagne committed Jan 3, 2025
1 parent 5f0cb04 commit 5ba5058
Show file tree
Hide file tree
Showing 2 changed files with 80 additions and 0 deletions.
46 changes: 46 additions & 0 deletions thrift/thriftutil/clone.go
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
}
34 changes: 34 additions & 0 deletions thrift/thriftutil/clone_test.go
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)
}

0 comments on commit 5ba5058

Please sign in to comment.