From fd57c55d87f2702fc85020fd269f2399379bdcb9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ra=C3=BAl=20Kripalani?= Date: Fri, 30 Nov 2018 16:09:25 +0000 Subject: [PATCH] document custom gogo types; reorg code. --- pb/custom.go | 41 +++++++++++++++++++++++++++++++---------- 1 file changed, 31 insertions(+), 10 deletions(-) diff --git a/pb/custom.go b/pb/custom.go index e51b2ca..711963c 100644 --- a/pb/custom.go +++ b/pb/custom.go @@ -3,19 +3,28 @@ package pstore_pb import ( "encoding/json" + proto "github.com/gogo/protobuf/proto" peer "github.com/libp2p/go-libp2p-peer" pt "github.com/libp2p/go-libp2p-peer/test" ma "github.com/multiformats/go-multiaddr" ) +// customGogoType aggregates the interfaces that custom Gogo types need to implement. +// it is only used for type assertions. +type customGogoType interface { + proto.Marshaler + proto.Unmarshaler + json.Marshaler + json.Unmarshaler + proto.Sizer +} + +// ProtoAddr is a custom type used by gogo to serde raw peer IDs into the peer.ID type, and back. type ProtoPeerID struct { peer.ID } -func NewPopulatedProtoPeerID(r randyPstore) *ProtoPeerID { - id, _ := pt.RandPeerID() - return &ProtoPeerID{ID: id} -} +var _ customGogoType = (*ProtoPeerID)(nil) func (id ProtoPeerID) Marshal() ([]byte, error) { return []byte(id.ID), nil @@ -36,26 +45,24 @@ func (id *ProtoPeerID) Unmarshal(data []byte) (err error) { } func (id *ProtoPeerID) UnmarshalJSON(data []byte) error { - v := new([]byte) + var v []byte err := json.Unmarshal(data, v) if err != nil { return err } - return id.Unmarshal(*v) + return id.Unmarshal(v) } func (id ProtoPeerID) Size() int { return len([]byte(id.ID)) } +// ProtoAddr is a custom type used by gogo to serde raw multiaddresses into the ma.Multiaddr type, and back. type ProtoAddr struct { ma.Multiaddr } -func NewPopulatedProtoAddr(r randyPstore) *ProtoAddr { - a, _ := ma.NewMultiaddr("/ip4/123.123.123.123/tcp/7001") - return &ProtoAddr{Multiaddr: a} -} +var _ customGogoType = (*ProtoAddr)(nil) func (a ProtoAddr) Marshal() ([]byte, error) { return a.Bytes(), nil @@ -87,3 +94,17 @@ func (a *ProtoAddr) UnmarshalJSON(data []byte) error { func (a ProtoAddr) Size() int { return len(a.Bytes()) } + +// NewPopulatedProtoAddr generates a populated instance of the custom gogo type ProtoAddr. +// It is required by gogo-generated tests. +func NewPopulatedProtoAddr(r randyPstore) *ProtoAddr { + a, _ := ma.NewMultiaddr("/ip4/123.123.123.123/tcp/7001") + return &ProtoAddr{Multiaddr: a} +} + +// NewPopulatedProtoPeerID generates a populated instance of the custom gogo type ProtoPeerID. +// It is required by gogo-generated tests. +func NewPopulatedProtoPeerID(r randyPstore) *ProtoPeerID { + id, _ := pt.RandPeerID() + return &ProtoPeerID{ID: id} +}