multicodec.go 1.84 KB
Newer Older
Rod Vagg's avatar
Rod Vagg committed
1 2 3 4 5 6
package dagpb

import (
	"io"

	ipld "github.com/ipld/go-ipld-prime"
7
	cidlink "github.com/ipld/go-ipld-prime/linking/cid"
8
	"github.com/ipld/go-ipld-prime/multicodec"
9
	"github.com/ipld/go-ipld-prime/traversal"
Rod Vagg's avatar
Rod Vagg committed
10 11 12
)

var (
acruikshank's avatar
acruikshank committed
13 14
	_ ipld.Decoder = Decode
	_ ipld.Encoder = Encode
Rod Vagg's avatar
Rod Vagg committed
15 16 17
)

func init() {
18 19
	multicodec.RegisterDecoder(0x70, Decode)
	multicodec.RegisterEncoder(0x70, Encode)
Rod Vagg's avatar
Rod Vagg committed
20 21
}

22
// Decode provides an IPLD codec decode interface for DAG-PB data. Provide a
Rod Vagg's avatar
Rod Vagg committed
23
// compatible NodeAssembler and a byte source to unmarshal a DAG-PB IPLD Node.
Rod Vagg's avatar
Rod Vagg committed
24 25 26 27
// Use the NodeAssembler from the PBNode type for safest construction
// (Type.PBNode.NewBuilder()). A Map assembler will also work.
// This function is registered via the go-ipld-prime link loader for multicodec
// code 0x70 when this package is invoked via init.
28
func Decode(na ipld.NodeAssembler, r io.Reader) error {
Rod Vagg's avatar
Rod Vagg committed
29 30 31
	return Unmarshal(na, r)
}

32
// Encode provides an IPLD codec encode interface for DAG-PB data. Provide a
Rod Vagg's avatar
Rod Vagg committed
33 34 35
// conforming Node and a destination for bytes to marshal a DAG-PB IPLD Node.
// The Node must strictly conform to the DAG-PB schema
// (https://github.com/ipld/specs/blob/master/block-layer/codecs/dag-pb.md).
Rod Vagg's avatar
Rod Vagg committed
36 37 38
// For safest use, build Nodes using the Type.PBNode type.
// This function is registered via the go-ipld-prime link loader for multicodec
// code 0x70 when this package is invoked via init.
39
func Encode(n ipld.Node, w io.Writer) error {
Rod Vagg's avatar
Rod Vagg committed
40
	return Marshal(n, w)
Rod Vagg's avatar
Rod Vagg committed
41
}
42 43 44 45 46 47 48 49 50 51 52

// AddSupportToChooser takes an existing node prototype chooser and subs in
// PBNode for the dag-pb multicodec code.
func AddSupportToChooser(existing traversal.LinkTargetNodePrototypeChooser) traversal.LinkTargetNodePrototypeChooser {
	return func(lnk ipld.Link, lnkCtx ipld.LinkContext) (ipld.NodePrototype, error) {
		if lnk, ok := lnk.(cidlink.Link); ok && lnk.Cid.Prefix().Codec == 0x70 {
			return Type.PBNode, nil
		}
		return existing(lnk, lnkCtx)
	}
}