github.com/storacha/go-ucanto@v0.7.2/core/ipld/rebind.go (about)

     1  package ipld
     2  
     3  import (
     4  	"errors"
     5  
     6  	"github.com/ipld/go-ipld-prime/datamodel"
     7  	"github.com/ipld/go-ipld-prime/node/bindnode"
     8  	"github.com/ipld/go-ipld-prime/schema"
     9  )
    10  
    11  // Rebind takes a Node and binds it to the Go type according to the passed schema.
    12  func Rebind[T any](nd datamodel.Node, typ schema.Type, opts ...bindnode.Option) (ptrVal T, err error) {
    13  	defer func() {
    14  		if r := recover(); r != nil {
    15  			if asStr, ok := r.(string); ok {
    16  				err = errors.New(asStr)
    17  			} else if asErr, ok := r.(error); ok {
    18  				err = asErr
    19  			} else {
    20  				err = errors.New("unknown panic rebinding node")
    21  			}
    22  		}
    23  	}()
    24  
    25  	if typedNode, ok := nd.(schema.TypedNode); ok {
    26  		nd = typedNode.Representation()
    27  	}
    28  
    29  	var nilbind T
    30  	np := bindnode.Prototype(&nilbind, typ, opts...)
    31  	nb := np.Representation().NewBuilder()
    32  	err = nb.AssignNode(nd)
    33  	if err != nil {
    34  		return
    35  	}
    36  	rnd := nb.Build()
    37  	ptrVal = *bindnode.Unwrap(rnd).(*T)
    38  	return
    39  }