From 77952751a7047c1818220002d396bd537f0b11cf Mon Sep 17 00:00:00 2001 From: Alan Shaw Date: Fri, 18 Oct 2024 14:03:35 +0100 Subject: [PATCH] fix: rebind a typed node --- core/ipld/rebind.go | 4 ++++ core/ipld/rebind_test.go | 26 ++++++++++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/core/ipld/rebind.go b/core/ipld/rebind.go index 118eed3..3f28589 100644 --- a/core/ipld/rebind.go +++ b/core/ipld/rebind.go @@ -22,6 +22,10 @@ func Rebind[T any](nd datamodel.Node, typ schema.Type) (ptrVal T, err error) { } }() + if typedNode, ok := nd.(schema.TypedNode); ok { + nd = typedNode.Representation() + } + var nilbind T np := bindnode.Prototype(&nilbind, typ) nb := np.Representation().NewBuilder() diff --git a/core/ipld/rebind_test.go b/core/ipld/rebind_test.go index de02f0e..f48234f 100644 --- a/core/ipld/rebind_test.go +++ b/core/ipld/rebind_test.go @@ -8,7 +8,9 @@ import ( "github.com/ipld/go-ipld-prime" "github.com/ipld/go-ipld-prime/datamodel" cidlink "github.com/ipld/go-ipld-prime/linking/cid" + "github.com/ipld/go-ipld-prime/node/bindnode" "github.com/storacha/go-ucanto/core/ipld/codec/cbor" + "github.com/stretchr/testify/require" ) func TestRebind(t *testing.T) { @@ -229,3 +231,27 @@ func TestRebindNonCompatibleSchema(t *testing.T) { } fmt.Println(err) } + +func TestRebindTypedNode(t *testing.T) { + type Target struct { + Astring string + Aint int + } + + ts, err := ipld.LoadSchemaBytes([]byte(` + type Target struct { + astring String + aint Int + } representation tuple + `)) + require.NoError(t, err) + + typ := ts.TypeByName("Target") + + target := Target{Astring: "hello", Aint: 1} + nd := bindnode.Wrap(&target, typ) + + rebindTarget, err := Rebind[Target](nd, typ) + require.NoError(t, err) + fmt.Printf("%+v\n", rebindTarget) +}