Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: rebind a typed node #25

Merged
merged 2 commits into from
Oct 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions core/ipld/rebind.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
26 changes: 26 additions & 0 deletions core/ipld/rebind_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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)
}
Loading