github.com/ipld/go-ipld-prime@v0.21.0/codec/json/multicodec.go (about)

     1  package json
     2  
     3  import (
     4  	"io"
     5  
     6  	rfmtjson "github.com/polydawn/refmt/json"
     7  
     8  	"github.com/ipld/go-ipld-prime/codec"
     9  	"github.com/ipld/go-ipld-prime/codec/dagjson"
    10  	"github.com/ipld/go-ipld-prime/datamodel"
    11  	"github.com/ipld/go-ipld-prime/multicodec"
    12  )
    13  
    14  var (
    15  	_ codec.Decoder = Decode
    16  	_ codec.Encoder = Encode
    17  )
    18  
    19  func init() {
    20  	multicodec.RegisterEncoder(0x0200, Encode)
    21  	multicodec.RegisterDecoder(0x0200, Decode)
    22  }
    23  
    24  // Decode deserializes data from the given io.Reader and feeds it into the given datamodel.NodeAssembler.
    25  // Decode fits the codec.Decoder function interface.
    26  //
    27  // This is the function that will be registered in the default multicodec registry during package init time.
    28  func Decode(na datamodel.NodeAssembler, r io.Reader) error {
    29  	return dagjson.DecodeOptions{
    30  		ParseLinks: false,
    31  		ParseBytes: false,
    32  	}.Decode(na, r)
    33  }
    34  
    35  // Encode walks the given datamodel.Node and serializes it to the given io.Writer.
    36  // Encode fits the codec.Encoder function interface.
    37  //
    38  // This is the function that will be registered in the default multicodec registry during package init time.
    39  func Encode(n datamodel.Node, w io.Writer) error {
    40  	// Shell out directly to generic inspection path.
    41  	//  (There's not really any fastpaths of note for json.)
    42  	// Write another function if you need to tune encoding options about whitespace.
    43  	return dagjson.Marshal(n, rfmtjson.NewEncoder(w, rfmtjson.EncodeOptions{
    44  		Line:   []byte{'\n'},
    45  		Indent: []byte{'\t'},
    46  	}), dagjson.EncodeOptions{
    47  		EncodeLinks: false,
    48  		EncodeBytes: false,
    49  		MapSortMode: codec.MapSortMode_None,
    50  	})
    51  }