Skip to content

Commit 547861c

Browse files
authored
Avoid reallocation of initial slice in MarshalBinary (GobEncode) (#355)
1 parent 78289cc commit 547861c

File tree

1 file changed

+9
-10
lines changed

1 file changed

+9
-10
lines changed

decimal.go

+9-10
Original file line numberDiff line numberDiff line change
@@ -1784,19 +1784,18 @@ func (d *Decimal) UnmarshalBinary(data []byte) error {
17841784

17851785
// MarshalBinary implements the encoding.BinaryMarshaler interface.
17861786
func (d Decimal) MarshalBinary() (data []byte, err error) {
1787-
// Write the exponent first since it's a fixed size
1788-
v1 := make([]byte, 4)
1789-
binary.BigEndian.PutUint32(v1, uint32(d.exp))
1790-
1791-
// Add the value
1792-
var v2 []byte
1793-
if v2, err = d.value.GobEncode(); err != nil {
1794-
return
1787+
// exp is written first, but encode value first to know output size
1788+
var valueData []byte
1789+
if valueData, err = d.value.GobEncode(); err != nil {
1790+
return nil, err
17951791
}
17961792

1793+
// Write the exponent in front, since it's a fixed size
1794+
expData := make([]byte, 4, len(valueData)+4)
1795+
binary.BigEndian.PutUint32(expData, uint32(d.exp))
1796+
17971797
// Return the byte array
1798-
data = append(v1, v2...)
1799-
return
1798+
return append(expData, valueData...), nil
18001799
}
18011800

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

0 commit comments

Comments
 (0)