From 0909684492ae3397fee190aa5c1bdadd73c47978 Mon Sep 17 00:00:00 2001 From: Hannah Howard Date: Thu, 17 Oct 2024 22:55:00 -0700 Subject: [PATCH] Add json codec (#24) Block Encode/Decode is really nice and id would be nice to use it with JSON :) --- core/ipld/codec/json/json.go | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 core/ipld/codec/json/json.go diff --git a/core/ipld/codec/json/json.go b/core/ipld/codec/json/json.go new file mode 100644 index 0000000..0f606e8 --- /dev/null +++ b/core/ipld/codec/json/json.go @@ -0,0 +1,34 @@ +package json + +import ( + "github.com/ipld/go-ipld-prime" + "github.com/ipld/go-ipld-prime/codec/dagjson" + "github.com/ipld/go-ipld-prime/schema" +) + +const Code = 0x0129 + +type codec struct{} + +func (codec) Code() uint64 { + return Code +} + +func (codec) Encode(val any, typ schema.Type) ([]byte, error) { + return Encode(val, typ) +} + +func (codec) Decode(b []byte, bind any, typ schema.Type) error { + return Decode(b, bind, typ) +} + +var Codec = codec{} + +func Encode(val any, typ schema.Type) ([]byte, error) { + return ipld.Marshal(dagjson.Encode, val, typ) +} + +func Decode(b []byte, bind any, typ schema.Type) error { + _, err := ipld.Unmarshal(b, dagjson.Decode, bind, typ) + return err +}