Skip to content

Commit

Permalink
Add slice range checks to UnmarshalBinary() (#232)
Browse files Browse the repository at this point in the history
* Add slice range checks to `UnmarshalBinary()`.
* Avoid use of `%w` verb with `Errorf()` for compatibility with older Go versions.
  • Loading branch information
jmalloc committed Jun 22, 2021
1 parent 5016615 commit cc4584f
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
12 changes: 11 additions & 1 deletion decimal.go
Expand Up @@ -1152,12 +1152,22 @@ 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))
}

// Extract the exponent
d.exp = int32(binary.BigEndian.Uint32(data[:4]))

// Extract the value
d.value = new(big.Int)
return d.value.GobDecode(data[4:])
if err := d.value.GobDecode(data[4:]); err != nil {
return fmt.Errorf("error decoding binary %v: %s", data, err)
}

return nil
}

// MarshalBinary implements the encoding.BinaryMarshaler interface.
Expand Down
18 changes: 18 additions & 0 deletions decimal_test.go
Expand Up @@ -2798,6 +2798,24 @@ func TestBinary(t *testing.T) {
}
}

func TestBinary_DataTooShort(t *testing.T) {
var d Decimal

err := d.UnmarshalBinary(nil) // nil slice has length 0
if err == nil {
t.Fatalf("expected error, got %v", d)
}
}

func TestBinary_InvalidValue(t *testing.T) {
var d Decimal

err := d.UnmarshalBinary([]byte{0, 0, 0, 0, 'x'}) // valid exponent, invalid value
if err == nil {
t.Fatalf("expected error, got %v", d)
}
}

func slicesEqual(a, b []byte) bool {
for i, val := range a {
if b[i] != val {
Expand Down

0 comments on commit cc4584f

Please sign in to comment.