[#168] object: Implement binary/JSON encoders/decoders on ShortHeader

Signed-off-by: Leonard Lyubich <leonard@nspcc.ru>
This commit is contained in:
Leonard Lyubich 2020-11-13 15:26:23 +03:00 committed by Alex Vanin
parent a684da6118
commit ce0d70fa02
4 changed files with 59 additions and 4 deletions

26
v2/object/json.go Normal file
View file

@ -0,0 +1,26 @@
package object
import (
object "github.com/nspcc-dev/neofs-api-go/v2/object/grpc"
"google.golang.org/protobuf/encoding/protojson"
)
func (h *ShortHeader) MarshalJSON() ([]byte, error) {
return protojson.MarshalOptions{
EmitUnpopulated: true,
}.Marshal(
ShortHeaderToGRPCMessage(h),
)
}
func (h *ShortHeader) UnmarshalJSON(data []byte) error {
msg := new(object.ShortHeader)
if err := protojson.Unmarshal(data, msg); err != nil {
return err
}
*h = *ShortHeaderFromGRPCMessage(msg)
return nil
}

20
v2/object/json_test.go Normal file
View file

@ -0,0 +1,20 @@
package object_test
import (
"testing"
"github.com/nspcc-dev/neofs-api-go/v2/object"
"github.com/stretchr/testify/require"
)
func TestShortHeaderJSON(t *testing.T) {
h := generateShortHeader("id")
data, err := h.MarshalJSON()
require.NoError(t, err)
h2 := new(object.ShortHeader)
require.NoError(t, h2.UnmarshalJSON(data))
require.Equal(t, h, h2)
}

View file

@ -162,6 +162,17 @@ func (h *ShortHeader) StableSize() (size int) {
return size return size
} }
func (h *ShortHeader) Unmarshal(data []byte) error {
m := new(object.ShortHeader)
if err := goproto.Unmarshal(data, m); err != nil {
return err
}
*h = *ShortHeaderFromGRPCMessage(m)
return nil
}
func (a *Attribute) StableMarshal(buf []byte) ([]byte, error) { func (a *Attribute) StableMarshal(buf []byte) ([]byte, error) {
if a == nil { if a == nil {
return []byte{}, nil return []byte{}, nil

View file

@ -15,16 +15,14 @@ import (
func TestShortHeader_StableMarshal(t *testing.T) { func TestShortHeader_StableMarshal(t *testing.T) {
hdrFrom := generateShortHeader("Owner ID") hdrFrom := generateShortHeader("Owner ID")
transport := new(grpc.ShortHeader)
t.Run("non empty", func(t *testing.T) { t.Run("non empty", func(t *testing.T) {
wire, err := hdrFrom.StableMarshal(nil) wire, err := hdrFrom.StableMarshal(nil)
require.NoError(t, err) require.NoError(t, err)
err = goproto.Unmarshal(wire, transport) hdrTo := new(object.ShortHeader)
require.NoError(t, err) require.NoError(t, hdrTo.Unmarshal(wire))
hdrTo := object.ShortHeaderFromGRPCMessage(transport)
require.Equal(t, hdrFrom, hdrTo) require.Equal(t, hdrFrom, hdrTo)
}) })
} }