[#378] accounting: Add binary encoding for Decimal type

Define `Marshal` / `Unmarshal` methods of the `Decimal` type.

Signed-off-by: Leonard Lyubich <ctulhurider@gmail.com>
This commit is contained in:
Leonard Lyubich 2023-01-31 11:51:49 +04:00
parent ae44191e8c
commit 4191e5f13e
2 changed files with 40 additions and 1 deletions

View file

@ -1,6 +1,8 @@
package accounting
import "github.com/nspcc-dev/neofs-api-go/v2/accounting"
import (
"github.com/nspcc-dev/neofs-api-go/v2/accounting"
)
// Decimal represents decimal number for accounting operations.
//
@ -62,3 +64,30 @@ func (d Decimal) Precision() uint32 {
func (d *Decimal) SetPrecision(p uint32) {
(*accounting.Decimal)(d).SetPrecision(p)
}
// Marshal encodes Decimal into a binary format of the NeoFS API protocol
// (Protocol Buffers with direct field order).
//
// See also Unmarshal.
func (d Decimal) Marshal() []byte {
var m accounting.Decimal
d.WriteToV2(&m)
return m.StableMarshal(nil)
}
// Unmarshal decodes NeoFS API protocol binary format into the Decimal
// (Protocol Buffers with direct field order). Returns an error describing
// a format violation.
//
// See also Marshal.
func (d *Decimal) Unmarshal(data []byte) error {
var m accounting.Decimal
err := m.Unmarshal(data)
if err != nil {
return err
}
return d.ReadFromV2(m)
}

View file

@ -5,6 +5,7 @@ import (
v2accounting "github.com/nspcc-dev/neofs-api-go/v2/accounting"
"github.com/nspcc-dev/neofs-sdk-go/accounting"
accountingtest "github.com/nspcc-dev/neofs-sdk-go/accounting/test"
"github.com/stretchr/testify/require"
)
@ -44,3 +45,12 @@ func TestDecimalMessageV2(t *testing.T) {
require.EqualValues(t, d.Value(), m2.GetValue())
require.EqualValues(t, d.Precision(), m2.GetPrecision())
}
func TestDecimal_Marshal(t *testing.T) {
d := *accountingtest.Decimal()
var d2 accounting.Decimal
require.NoError(t, d2.Unmarshal(d.Marshal()))
require.Equal(t, d, d2)
}