Skip to content

Commit

Permalink
Use (Un)MarshalText instead of (Un)MarshalJSON for encoding.
Browse files Browse the repository at this point in the history
This is more to the point and will also allow the use of apicid.Hash
as keys is JSON objects.
  • Loading branch information
kevina committed Sep 27, 2018
1 parent bb0a383 commit be6ca1e
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 9 deletions.
17 changes: 8 additions & 9 deletions apicid/apicid.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
package apicid

import (
"encoding/json"

cid "github.com/ipfs/go-cid"
"github.com/ipfs/go-cidutil/cidenc"
mbase "github.com/multiformats/go-multibase"
Expand All @@ -12,12 +10,12 @@ import (
var JSONBase mbase.Encoder = mbase.MustNewEncoder(mbase.Base58BTC)

// apicid.Hash is a type to respesnt a CID in the API which marshals
// as a hash
// as a string
type Hash struct {
str string // always in CidJSONBase
str string
}

// FromCid created an APICid from a Cid
// FromCid creates an APICid from a Cid
func FromCid(c cid.Cid) Hash {
return Hash{c.Encode(JSONBase)}
}
Expand All @@ -42,12 +40,13 @@ func (c Hash) Encode(enc cidenc.Interface) string {
return str
}

func (c *Hash) UnmarshalJSON(b []byte) error {
return json.Unmarshal(b, &c.str)
func (c *Hash) UnmarshalText(b []byte) error {
c.str = string(b)
return nil
}

func (c Hash) MarshalJSON() ([]byte, error) {
return json.Marshal(c.str)
func (c Hash) MarshalText() ([]byte, error) {
return []byte(c.str), nil
}

// Cid is type to represent a normal CID in the API which marshals
Expand Down
48 changes: 48 additions & 0 deletions apicid/apicid_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package apicid

import (
"encoding/json"
"testing"

cid "github.com/ipfs/go-cid"
)

func TestJson(t *testing.T) {
cid, _ := cid.Decode("zb2rhak9iRgDiik36KQBRr2qiCJHdyBH7YxFmw7FTdM6zo31m")
hash := FromCid(cid)
data, err := json.Marshal(hash)
if err != nil {
t.Fatal(err)
}
if string(data) != `"zb2rhak9iRgDiik36KQBRr2qiCJHdyBH7YxFmw7FTdM6zo31m"` {
t.Fatalf("json string incorrect: %s\n", data)
}
var hash2 Hash
err = json.Unmarshal(data, &hash2)
if err != nil {
t.Fatal(err)
}
if hash != hash2 {
t.Fatal("round trip failed")
}
}

func TestJsonMap(t *testing.T) {
cid1, _ := cid.Decode("zb2rhak9iRgDiik36KQBRr2qiCJHdyBH7YxFmw7FTdM6zo31m")
cid2, _ := cid.Decode("QmRJggJREPCt7waGQKMXymrXRvrvsSiiPjgFbLK9isuM8K")
hash1 := FromCid(cid1)
hash2 := FromCid(cid2)
m := map[Hash]string{hash1: "a value", hash2: "something else"}
data, err := json.Marshal(m)
if err != nil {
t.Fatal(err)
}
m2 := map[Hash]string{}
err = json.Unmarshal(data, &m2)
if err != nil {
t.Fatal(err)
}
if len(m2) != 2 || m[hash1] != m2[hash1] || m[hash2] != m2[hash2] {
t.Fatal("round trip failed")
}
}

0 comments on commit be6ca1e

Please sign in to comment.