From d5b658c1b2265e2839191eaca17f2f9d7d38290d Mon Sep 17 00:00:00 2001 From: Eric Myhre Date: Thu, 1 Oct 2020 08:33:42 +0200 Subject: [PATCH] Attempt to support dagjson spec for bytes; writer side. I haven't implemented the reader side because I'm not sure it's possible; the specification is insufficiently clear. I opened Issue https://github.com/ipld/specs/issues/302 to track this. --- codec/dagjson/marshal.go | 41 ++++++++++++++++++++++++++++++++++++---- 1 file changed, 37 insertions(+), 4 deletions(-) diff --git a/codec/dagjson/marshal.go b/codec/dagjson/marshal.go index f01b92cd..83fd225f 100644 --- a/codec/dagjson/marshal.go +++ b/codec/dagjson/marshal.go @@ -1,6 +1,7 @@ package dagjson import ( + "encoding/base64" "fmt" "github.com/polydawn/refmt/shared" @@ -115,10 +116,42 @@ func Marshal(n ipld.Node, sink shared.TokenSink) error { if err != nil { return err } - tk.Type = tok.TBytes - tk.Bytes = v - _, err = sink.Step(&tk) - return err + // A json encoder can't handle bytes tokens, so, we're not going to use `tok.TBytes`, etc, here: + // instead, we're going to convert this to a b64 string, and swaddle it a bit: + // see https://github.com/ipld/specs/blob/master/block-layer/codecs/dag-json.md#bytes-kind . + tk.Type = tok.TMapOpen + tk.Length = 1 + if _, err = sink.Step(&tk); err != nil { + return err + } + tk.Type = tok.TString + tk.String = "/" + if _, err = sink.Step(&tk); err != nil { + return err + } + tk.Type = tok.TMapOpen + tk.Length = 1 + if _, err = sink.Step(&tk); err != nil { + return err + } + tk.Type = tok.TString + tk.String = "bytes" + if _, err = sink.Step(&tk); err != nil { + return err + } + tk.Type = tok.TString + tk.String = base64.RawStdEncoding.EncodeToString(v) + if _, err = sink.Step(&tk); err != nil { + return err + } + tk.Type = tok.TMapClose + if _, err = sink.Step(&tk); err != nil { + return err + } + if _, err = sink.Step(&tk); err != nil { + return err + } + return nil case ipld.ReprKind_Link: v, err := n.AsLink() if err != nil {