ipld_impl.go 1.84 KB
Newer Older
1 2 3 4 5 6 7
package ipldbridge

import (
	"bytes"
	"context"

	ipld "github.com/ipld/go-ipld-prime"
8
	dagpb "github.com/ipld/go-ipld-prime-proto"
9 10
	"github.com/ipld/go-ipld-prime/encoding/dagcbor"
	free "github.com/ipld/go-ipld-prime/impl/free"
11
	"github.com/ipld/go-ipld-prime/traversal"
12 13 14 15 16
	ipldtraversal "github.com/ipld/go-ipld-prime/traversal"
	ipldselector "github.com/ipld/go-ipld-prime/traversal/selector"
)

// TraversalConfig is an alias from ipld, in case it's renamed/moved.
Edgar Lee's avatar
Edgar Lee committed
17
type TraversalConfig = ipldtraversal.Config
18 19 20 21 22

type ipldBridge struct {
}

// NewIPLDBridge returns an IPLD Bridge.
23 24
func NewIPLDBridge() IPLDBridge {
	return &ipldBridge{}
25 26
}

27 28 29 30 31 32
var (
	defaultChooser traversal.NodeBuilderChooser = dagpb.AddDagPBSupportToChooser(func(ipld.Link, ipld.LinkContext) ipld.NodeBuilder {
		return free.NodeBuilder()
	})
)

33
func (rb *ipldBridge) Traverse(ctx context.Context, loader Loader, root ipld.Link, s Selector, fn AdvVisitFn) error {
34 35
	builder := defaultChooser(root, LinkContext{})
	node, err := root.Load(ctx, LinkContext{}, builder, loader)
36 37 38 39 40
	if err != nil {
		return err
	}
	return TraversalProgress{
		Cfg: &TraversalConfig{
41 42 43
			Ctx:                    ctx,
			LinkLoader:             loader,
			LinkNodeBuilderChooser: defaultChooser,
44
		},
Edgar Lee's avatar
Edgar Lee committed
45
	}.WalkAdv(node, s, fn)
46 47
}

48 49 50 51
func (rb *ipldBridge) WalkMatching(node ipld.Node, s Selector, fn VisitFn) error {
	return ipldtraversal.WalkMatching(node, s, fn)
}

52 53
func (rb *ipldBridge) EncodeNode(node ipld.Node) ([]byte, error) {
	var buffer bytes.Buffer
54
	err := dagcbor.Encoder(node, &buffer)
55 56 57 58 59 60 61 62
	if err != nil {
		return nil, err
	}
	return buffer.Bytes(), nil
}

func (rb *ipldBridge) DecodeNode(encoded []byte) (ipld.Node, error) {
	reader := bytes.NewReader(encoded)
63
	return dagcbor.Decoder(free.NodeBuilder(), reader)
64 65
}

66 67
func (rb *ipldBridge) ParseSelector(selector ipld.Node) (Selector, error) {
	return ipldselector.ParseSelector(selector)
68
}