mirror of
https://github.com/shopspring/decimal.git
synced 2024-11-22 12:30:49 +01:00
Add slice range checks to UnmarshalBinary()
(#232)
* Add slice range checks to `UnmarshalBinary()`. * Avoid use of `%w` verb with `Errorf()` for compatibility with older Go versions.
This commit is contained in:
parent
501661573f
commit
cc4584f0a5
2 changed files with 29 additions and 1 deletions
12
decimal.go
12
decimal.go
|
@ -1152,12 +1152,22 @@ func (d Decimal) MarshalJSON() ([]byte, error) {
|
||||||
// UnmarshalBinary implements the encoding.BinaryUnmarshaler interface. As a string representation
|
// UnmarshalBinary implements the encoding.BinaryUnmarshaler interface. As a string representation
|
||||||
// is already used when encoding to text, this method stores that string as []byte
|
// is already used when encoding to text, this method stores that string as []byte
|
||||||
func (d *Decimal) UnmarshalBinary(data []byte) error {
|
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
|
// Extract the exponent
|
||||||
d.exp = int32(binary.BigEndian.Uint32(data[:4]))
|
d.exp = int32(binary.BigEndian.Uint32(data[:4]))
|
||||||
|
|
||||||
// Extract the value
|
// Extract the value
|
||||||
d.value = new(big.Int)
|
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.
|
// MarshalBinary implements the encoding.BinaryMarshaler interface.
|
||||||
|
|
|
@ -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 {
|
func slicesEqual(a, b []byte) bool {
|
||||||
for i, val := range a {
|
for i, val := range a {
|
||||||
if b[i] != val {
|
if b[i] != val {
|
||||||
|
|
Loading…
Reference in a new issue