Skip to content

Commit

Permalink
Attempt to support dagjson spec for bytes; writer side.
Browse files Browse the repository at this point in the history
I haven't implemented the reader side because I'm not sure it's possible;
the specification is insufficiently clear.
I opened Issue ipld/specs#302 to track this.
  • Loading branch information
warpfork committed Oct 20, 2020
1 parent e53a547 commit d5b658c
Showing 1 changed file with 37 additions and 4 deletions.
41 changes: 37 additions & 4 deletions codec/dagjson/marshal.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package dagjson

import (
"encoding/base64"
"fmt"

"github.com/polydawn/refmt/shared"
Expand Down Expand Up @@ -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 {
Expand Down

0 comments on commit d5b658c

Please sign in to comment.