Skip to content

Commit

Permalink
Fix binary marshalling of decimal zero value (#253)
Browse files Browse the repository at this point in the history
* Fix binary marshalling of zero value
* Adapt the error message of BinaryUnmarshal
  • Loading branch information
Gilthoniel authored Oct 20, 2021
1 parent 2ae6f29 commit cd57bf1
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 4 deletions.
8 changes: 4 additions & 4 deletions decimal.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
19 changes: 19 additions & 0 deletions decimal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down

0 comments on commit cd57bf1

Please sign in to comment.