From e986f47807218dcd45fab075553870b3f279f26b Mon Sep 17 00:00:00 2001 From: Leonard Lyubich Date: Wed, 15 Jun 2022 22:08:19 +0300 Subject: [PATCH] [#227] netmap: Add more encoding methods for `PlacementPolicy` Signed-off-by: Leonard Lyubich --- netmap/policy.go | 43 ++++++++++++++++++++++++++++++++++++++++++- netmap/policy_test.go | 25 ++++++++++++++++++++++++- 2 files changed, 66 insertions(+), 2 deletions(-) diff --git a/netmap/policy.go b/netmap/policy.go index 26aa1ca..6139f9f 100644 --- a/netmap/policy.go +++ b/netmap/policy.go @@ -57,7 +57,48 @@ func (p *PlacementPolicy) readFromV2(m netmap.PlacementPolicy, checkFieldPresenc return nil } -// UnmarshalJSON decodes PlacementPolicy from protobuf JSON format. +// Marshal encodes PlacementPolicy into a binary format of the NeoFS API +// protocol (Protocol Buffers with direct field order). +// +// See also Unmarshal. +func (p PlacementPolicy) Marshal() []byte { + var m netmap.PlacementPolicy + p.WriteToV2(&m) + + return m.StableMarshal(nil) +} + +// Unmarshal decodes NeoFS API protocol binary format into the PlacementPolicy +// (Protocol Buffers with direct field order). Returns an error describing +// a format violation. +// +// See also Marshal. +func (p *PlacementPolicy) Unmarshal(data []byte) error { + var m netmap.PlacementPolicy + + err := m.Unmarshal(data) + if err != nil { + return err + } + + return p.readFromV2(m, false) +} + +// MarshalJSON encodes PlacementPolicy into a JSON format of the NeoFS API +// protocol (Protocol Buffers JSON). +// +// See also UnmarshalJSON. +func (p PlacementPolicy) MarshalJSON() ([]byte, error) { + var m netmap.PlacementPolicy + p.WriteToV2(&m) + + return m.MarshalJSON() +} + +// UnmarshalJSON decodes NeoFS API protocol JSON format into the PlacementPolicy +// (Protocol Buffers JSON). Returns an error describing a format violation. +// +// See also MarshalJSON. func (p *PlacementPolicy) UnmarshalJSON(data []byte) error { var m netmap.PlacementPolicy diff --git a/netmap/policy_test.go b/netmap/policy_test.go index 47ec1d7..0c2782c 100644 --- a/netmap/policy_test.go +++ b/netmap/policy_test.go @@ -1,9 +1,11 @@ -package netmap +package netmap_test import ( "strings" "testing" + . "github.com/nspcc-dev/neofs-sdk-go/netmap" + netmaptest "github.com/nspcc-dev/neofs-sdk-go/netmap/test" "github.com/stretchr/testify/require" ) @@ -34,3 +36,24 @@ FILTER City EQ SPB AND SSD EQ true OR City EQ SPB AND Rating GE 5 AS SPBSSD`, require.Equal(t, testCase, b.String()) } } + +func TestPlacementPolicyEncoding(t *testing.T) { + v := netmaptest.PlacementPolicy() + + t.Run("binary", func(t *testing.T) { + var v2 PlacementPolicy + require.NoError(t, v2.Unmarshal(v.Marshal())) + + require.Equal(t, v, v2) + }) + + t.Run("json", func(t *testing.T) { + data, err := v.MarshalJSON() + require.NoError(t, err) + + var v2 PlacementPolicy + require.NoError(t, v2.UnmarshalJSON(data)) + + require.Equal(t, v, v2) + }) +}