Fix binary marshalling of decimal zero value (#253)

* Fix binary marshalling of zero value
* Adapt the error message of BinaryUnmarshal
This commit is contained in:
Gaylor Bosson 2021-10-20 12:49:41 +02:00 committed by GitHub
parent 2ae6f298b8
commit cd57bf11a4
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 23 additions and 4 deletions

View file

@ -1353,10 +1353,10 @@ 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 {
return fmt.Errorf("error decoding binary %v: expected at least 5 bytes, got %d", data, len(data))
// Verify we have at least 4 bytes for the exponent. The GOB encoded value
// may be empty.
if len(data) < 4 {
return fmt.Errorf("error decoding binary %v: expected at least 4 bytes, got %d", data, len(data))
}
// Extract the exponent

View file

@ -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