mirror of
https://github.com/ipfs/kubo.git
synced 2026-03-05 00:08:06 +08:00
Add json unmarshal code and fix panic
A panic would occur when a link was created with a nil cid, this should be allowable, just catch the potential problem and skip marshaling the cid. License: MIT Signed-off-by: Jeromy <why@ipfs.io>
This commit is contained in:
parent
4373bf9d75
commit
7c8a8a81cf
@ -60,7 +60,9 @@ func (n *ProtoNode) getPBNode() *pb.PBNode {
|
||||
pbn.Links[i] = &pb.PBLink{}
|
||||
pbn.Links[i].Name = &l.Name
|
||||
pbn.Links[i].Tsize = &l.Size
|
||||
pbn.Links[i].Hash = l.Cid.Bytes()
|
||||
if l.Cid != nil {
|
||||
pbn.Links[i].Hash = l.Cid.Bytes()
|
||||
}
|
||||
}
|
||||
|
||||
if len(n.data) > 0 {
|
||||
|
||||
@ -229,6 +229,22 @@ func (n *ProtoNode) Loggable() map[string]interface{} {
|
||||
}
|
||||
}
|
||||
|
||||
func (n *ProtoNode) UnmarshalJSON(b []byte) error {
|
||||
s := struct {
|
||||
Data []byte `json:"data"`
|
||||
Links []*node.Link `json:"links"`
|
||||
}{}
|
||||
|
||||
err := json.Unmarshal(b, &s)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
n.data = s.Data
|
||||
n.links = s.Links
|
||||
return nil
|
||||
}
|
||||
|
||||
func (n *ProtoNode) MarshalJSON() ([]byte, error) {
|
||||
out := map[string]interface{}{
|
||||
"data": n.data,
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
package merkledag_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
@ -128,3 +129,32 @@ func TestNodeCopy(t *testing.T) {
|
||||
t.Fatal("should be different objects")
|
||||
}
|
||||
}
|
||||
|
||||
func TestJsonRoundtrip(t *testing.T) {
|
||||
nd := new(ProtoNode)
|
||||
nd.SetLinks([]*node.Link{
|
||||
{Name: "a"},
|
||||
{Name: "c"},
|
||||
{Name: "b"},
|
||||
})
|
||||
nd.SetData([]byte("testing"))
|
||||
|
||||
jb, err := nd.MarshalJSON()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
nn := new(ProtoNode)
|
||||
err = nn.UnmarshalJSON(jb)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if !bytes.Equal(nn.Data(), nd.Data()) {
|
||||
t.Fatal("data wasnt the same")
|
||||
}
|
||||
|
||||
if !nn.Cid().Equals(nd.Cid()) {
|
||||
t.Fatal("objects differed after marshaling")
|
||||
}
|
||||
}
|
||||
|
||||
Loading…
Reference in New Issue
Block a user