github.com/storacha/go-ucanto@v0.7.2/core/ipld/codec/json/json.go (about) 1 package json 2 3 import ( 4 "errors" 5 "fmt" 6 7 "github.com/ipld/go-ipld-prime" 8 "github.com/ipld/go-ipld-prime/codec/dagjson" 9 "github.com/ipld/go-ipld-prime/node/bindnode" 10 "github.com/ipld/go-ipld-prime/schema" 11 ) 12 13 const Code = 0x0129 14 15 type codec struct{} 16 17 func (codec) Code() uint64 { 18 return Code 19 } 20 21 func (codec) Encode(val any, typ schema.Type, opts ...bindnode.Option) ([]byte, error) { 22 return Encode(val, typ, opts...) 23 } 24 25 func (codec) Decode(b []byte, bind any, typ schema.Type, opts ...bindnode.Option) error { 26 return Decode(b, bind, typ, opts...) 27 } 28 29 var Codec = codec{} 30 31 func Encode(val any, typ schema.Type, opts ...bindnode.Option) (bytes []byte, err error) { 32 defer func() { 33 if r := recover(); r != nil { 34 if asStr, ok := r.(string); ok { 35 err = errors.New(asStr) 36 } else if asErr, ok := r.(error); ok { 37 err = asErr 38 } else { 39 err = fmt.Errorf("unknown panic encoding JSON: %+v", r) 40 } 41 } 42 }() 43 bytes, err = ipld.Marshal(dagjson.Encode, val, typ, opts...) 44 return 45 } 46 47 func Decode(b []byte, bind any, typ schema.Type, opts ...bindnode.Option) error { 48 _, err := ipld.Unmarshal(b, dagjson.Decode, bind, typ, opts...) 49 return err 50 }