[#168] accounting: Implement binary/JSON encoders/decoders on Decimal

Signed-off-by: Leonard Lyubich <leonard@nspcc.ru>
This commit is contained in:
Leonard Lyubich 2020-11-13 13:38:49 +03:00 committed by Alex Vanin
parent 52fae76533
commit 9bebc1247d
6 changed files with 139 additions and 25 deletions

View file

@ -40,3 +40,35 @@ func (d *Decimal) SetPrecision(p uint32) {
(*accounting.Decimal)(d).
SetPrecision(p)
}
// Marshal marshals Decimal into a protobuf binary form.
//
// Buffer is allocated when the argument is empty.
// Otherwise, the first buffer is used.
func (d *Decimal) Marshal(b ...[]byte) ([]byte, error) {
var buf []byte
if len(b) > 0 {
buf = b[0]
}
return (*accounting.Decimal)(d).
StableMarshal(buf)
}
// Unmarshal unmarshals protobuf binary representation of Decimal.
func (d *Decimal) Unmarshal(data []byte) error {
return (*accounting.Decimal)(d).
Unmarshal(data)
}
// MarshalJSON encodes Decimal to protobuf JSON format.
func (d *Decimal) MarshalJSON() ([]byte, error) {
return (*accounting.Decimal)(d).
MarshalJSON()
}
// UnmarshalJSON decodes Decimal from protobuf JSON format.
func (d *Decimal) UnmarshalJSON(data []byte) error {
return (*accounting.Decimal)(d).
UnmarshalJSON(data)
}

View file

@ -23,3 +23,29 @@ func TestDecimal_Precision(t *testing.T) {
require.Equal(t, p, d.Precision())
}
func TestDecimalEncoding(t *testing.T) {
d := NewDecimal()
d.SetValue(1)
d.SetPrecision(2)
t.Run("binary", func(t *testing.T) {
data, err := d.Marshal()
require.NoError(t, err)
d2 := NewDecimal()
require.NoError(t, d2.Unmarshal(data))
require.Equal(t, d, d2)
})
t.Run("json", func(t *testing.T) {
data, err := d.MarshalJSON()
require.NoError(t, err)
d2 := NewDecimal()
require.NoError(t, d2.UnmarshalJSON(data))
require.Equal(t, d, d2)
})
}