From 8c9b889ccfe1f891ce8ab36c843f15794ce8f30f Mon Sep 17 00:00:00 2001 From: Ethan Frey Date: Thu, 23 Feb 2017 18:11:20 +0100 Subject: [PATCH] Support json encode/decode for nil values in S structs --- encode_test.go | 24 ++++++++++++++++++++++++ priv_key.go | 2 +- pub_key.go | 2 +- signature.go | 2 +- 4 files changed, 27 insertions(+), 3 deletions(-) diff --git a/encode_test.go b/encode_test.go index 224f413c1..8f2eebbaa 100644 --- a/encode_test.go +++ b/encode_test.go @@ -84,5 +84,29 @@ func TestKeyEncodings(t *testing.T) { checkJSON(t, pubKey, &pub3, tc.keyName) assert.EqualValues(t, pubKey, pub3) } +} + +func toFromJSON(t *testing.T, in interface{}, recvr interface{}) { + js, err := data.ToJSON(in) + require.Nil(t, err, "%+v", err) + err = data.FromJSON(js, recvr) + require.Nil(t, err, "%+v", err) +} + +func TestNilEncodings(t *testing.T) { + // make sure sigs are okay with nil + a, b := SignatureS{}, SignatureS{} + toFromJSON(t, a, &b) + assert.EqualValues(t, a, b) + + // make sure sigs are okay with nil + c, d := PubKeyS{}, PubKeyS{} + toFromJSON(t, c, &d) + assert.EqualValues(t, c, d) + + // make sure sigs are okay with nil + e, f := PrivKeyS{}, PrivKeyS{} + toFromJSON(t, e, &f) + assert.EqualValues(t, e, f) } diff --git a/priv_key.go b/priv_key.go index 60a82636d..81edfb3f6 100644 --- a/priv_key.go +++ b/priv_key.go @@ -47,7 +47,7 @@ func (p PrivKeyS) MarshalJSON() ([]byte, error) { func (p *PrivKeyS) UnmarshalJSON(data []byte) (err error) { parsed, err := privKeyMapper.FromJSON(data) - if err == nil { + if err == nil && parsed != nil { p.PrivKey = parsed.(PrivKey) } return diff --git a/pub_key.go b/pub_key.go index e5fe5209a..77ce74a97 100644 --- a/pub_key.go +++ b/pub_key.go @@ -49,7 +49,7 @@ func (p PubKeyS) MarshalJSON() ([]byte, error) { func (p *PubKeyS) UnmarshalJSON(data []byte) (err error) { parsed, err := pubKeyMapper.FromJSON(data) - if err == nil { + if err == nil && parsed != nil { p.PubKey = parsed.(PubKey) } return diff --git a/signature.go b/signature.go index 376a535d6..076358879 100644 --- a/signature.go +++ b/signature.go @@ -45,7 +45,7 @@ func (p SignatureS) MarshalJSON() ([]byte, error) { func (p *SignatureS) UnmarshalJSON(data []byte) (err error) { parsed, err := sigMapper.FromJSON(data) - if err == nil { + if err == nil && parsed != nil { p.Signature = parsed.(Signature) } return