Skip to content
This repository has been archived by the owner on Dec 7, 2019. It is now read-only.

Protobuf and JSON (un-)marshalling methods for peer.ID #41

Merged
merged 3 commits into from
Dec 12, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions peer_serde.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
// This file contains Protobuf and JSON serialization/deserialization methods for peer IDs.
package peer

import (
"encoding/json"
)

// Interface assertions commented out to avoid introducing hard dependencies to protobuf.
// var _ proto.Marshaler = (*ID)(nil)
// var _ proto.Unmarshaler = (*ID)(nil)
var _ json.Marshaler = (*ID)(nil)
var _ json.Unmarshaler = (*ID)(nil)

func (id ID) Marshal() ([]byte, error) {
return []byte(id), nil
}

func (id ID) MarshalTo(data []byte) (n int, err error) {
return copy(data, []byte(id)), nil
}

func (id *ID) Unmarshal(data []byte) (err error) {
*id, err = IDFromBytes(data)
return err
}

// Implements Gogo's proto.Sizer, but we omit the compile-time assertion to avoid introducing a hard
// dependency on gogo.
func (id ID) Size() int {
return len([]byte(id))
}

func (id ID) MarshalJSON() ([]byte, error) {
return json.Marshal(IDB58Encode(id))
}

func (id *ID) UnmarshalJSON(data []byte) (err error) {
var v string
if err = json.Unmarshal(data, &v); err != nil {
return err
}
*id, err = IDB58Decode(v)
return err
}
45 changes: 45 additions & 0 deletions peer_serde_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package peer_test

import (
"testing"

"github.com/libp2p/go-libp2p-peer"
"github.com/libp2p/go-libp2p-peer/test"
)

func TestPeerSerdePB(t *testing.T) {
id, err := testutil.RandPeerID()
if err != nil {
t.Fatal(err)
}
b, err := id.Marshal()
if err != nil {
t.Fatal(err)
}

var id2 peer.ID
if err = id2.Unmarshal(b); err != nil {
t.Fatal(err)
}
if id != id2 {
t.Error("expected equal ids in circular serde test")
}
}

func TestPeerSerdeJSON(t *testing.T) {
id, err := testutil.RandPeerID()
if err != nil {
t.Fatal(err)
}
b, err := id.MarshalJSON()
if err != nil {
t.Fatal(err)
}
var id2 peer.ID
if err = id2.UnmarshalJSON(b); err != nil {
t.Fatal(err)
}
if id != id2 {
t.Error("expected equal ids in circular serde test")
}
}