Skip to content

Commit c54aa61

Browse files
serprexepelc
authored andcommitted
Avoid reallocation of initial slice in MarshalBinary (GobEncode) (shopspring#355)
1 parent f1f5d69 commit c54aa61

1 file changed

Lines changed: 9 additions & 10 deletions

File tree

decimal.go

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1746,19 +1746,18 @@ func (d *Decimal) UnmarshalBinary(data []byte) error {
17461746

17471747
// MarshalBinary implements the encoding.BinaryMarshaler interface.
17481748
func (d Decimal) MarshalBinary() (data []byte, err error) {
1749-
// Write the exponent first since it's a fixed size
1750-
v1 := make([]byte, 4)
1751-
binary.BigEndian.PutUint32(v1, uint32(d.exp))
1752-
1753-
// Add the value
1754-
var v2 []byte
1755-
if v2, err = d.value.GobEncode(); err != nil {
1756-
return
1749+
// exp is written first, but encode value first to know output size
1750+
var valueData []byte
1751+
if valueData, err = d.value.GobEncode(); err != nil {
1752+
return nil, err
17571753
}
17581754

1755+
// Write the exponent in front, since it's a fixed size
1756+
expData := make([]byte, 4, len(valueData)+4)
1757+
binary.BigEndian.PutUint32(expData, uint32(d.exp))
1758+
17591759
// Return the byte array
1760-
data = append(v1, v2...)
1761-
return
1760+
return append(expData, valueData...), nil
17621761
}
17631762

17641763
// Scan implements the sql.Scanner interface for database deserialization.

0 commit comments

Comments
 (0)