Skip to content

Commit

Permalink
Avoid reallocation of initial slice in MarshalBinary (GobEncode) (#355)
Browse files Browse the repository at this point in the history
  • Loading branch information
serprex committed Apr 3, 2024
1 parent 78289cc commit 547861c
Showing 1 changed file with 9 additions and 10 deletions.
19 changes: 9 additions & 10 deletions decimal.go
Expand Up @@ -1784,19 +1784,18 @@ func (d *Decimal) UnmarshalBinary(data []byte) error {

// MarshalBinary implements the encoding.BinaryMarshaler interface.
func (d Decimal) MarshalBinary() (data []byte, err error) {
// Write the exponent first since it's a fixed size
v1 := make([]byte, 4)
binary.BigEndian.PutUint32(v1, uint32(d.exp))

// Add the value
var v2 []byte
if v2, err = d.value.GobEncode(); err != nil {
return
// exp is written first, but encode value first to know output size
var valueData []byte
if valueData, err = d.value.GobEncode(); err != nil {
return nil, err
}

// Write the exponent in front, since it's a fixed size
expData := make([]byte, 4, len(valueData)+4)
binary.BigEndian.PutUint32(expData, uint32(d.exp))

// Return the byte array
data = append(v1, v2...)
return
return append(expData, valueData...), nil
}

// Scan implements the sql.Scanner interface for database deserialization.
Expand Down

0 comments on commit 547861c

Please sign in to comment.