From 75f3d7445e4227daf0a6e208a321ae3ad3530c67 Mon Sep 17 00:00:00 2001 From: Gaylor Bosson Date: Tue, 19 Oct 2021 11:34:50 +0200 Subject: [PATCH 1/2] Fix binary marshalling of zero value --- decimal.go | 6 +++--- decimal_test.go | 19 +++++++++++++++++++ 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/decimal.go b/decimal.go index 7686af12..9f5c40f1 100644 --- a/decimal.go +++ b/decimal.go @@ -1353,9 +1353,9 @@ func (d Decimal) MarshalJSON() ([]byte, error) { // UnmarshalBinary implements the encoding.BinaryUnmarshaler interface. As a string representation // is already used when encoding to text, this method stores that string as []byte func (d *Decimal) UnmarshalBinary(data []byte) error { - // Verify we have at least 5 bytes, 4 for the exponent and at least 1 more - // for the GOB encoded value. - if len(data) < 5 { + // Verify we have at least 4 bytes for the exponent. The GOB encoded value + // can be empty. + if len(data) < 4 { return fmt.Errorf("error decoding binary %v: expected at least 5 bytes, got %d", data, len(data)) } diff --git a/decimal_test.go b/decimal_test.go index b53b68b9..cd7f00b1 100644 --- a/decimal_test.go +++ b/decimal_test.go @@ -3002,6 +3002,25 @@ func TestBinary(t *testing.T) { } } +func TestBinary_Zero(t *testing.T) { + var d1 Decimal + + b, err := d1.MarshalBinary() + if err != nil { + t.Fatalf("error marshalling %v to binary: %v", d1, err) + } + + var d2 Decimal + err = (&d2).UnmarshalBinary(b) + if err != nil { + t.Errorf("error unmarshalling from binary: %v", err) + } + + if !d1.Equals(d2) { + t.Errorf("expected %v when restoring, got %v", d1, d2) + } +} + func TestBinary_DataTooShort(t *testing.T) { var d Decimal From 9e19cfc3ff9602bca3ab184c3304205b178b719a Mon Sep 17 00:00:00 2001 From: Gaylor Bosson Date: Wed, 20 Oct 2021 11:12:15 +0200 Subject: [PATCH 2/2] Adapt the error message of BinaryUnmarshal --- decimal.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/decimal.go b/decimal.go index 9f5c40f1..62edc05e 100644 --- a/decimal.go +++ b/decimal.go @@ -1354,9 +1354,9 @@ func (d Decimal) MarshalJSON() ([]byte, error) { // is already used when encoding to text, this method stores that string as []byte func (d *Decimal) UnmarshalBinary(data []byte) error { // Verify we have at least 4 bytes for the exponent. The GOB encoded value - // can be empty. + // may be empty. if len(data) < 4 { - return fmt.Errorf("error decoding binary %v: expected at least 5 bytes, got %d", data, len(data)) + return fmt.Errorf("error decoding binary %v: expected at least 4 bytes, got %d", data, len(data)) } // Extract the exponent