Skip to content

Commit

Permalink
math: derive marshalled byte length from copy, not blind assumptions (#…
Browse files Browse the repository at this point in the history
…12010)

The specification of "copy", the builtin function per
https://pkg.go.dev/builtin#copy, says that it returns the minimum of
len(src) and len(dst) when invoked as:

   copy(dst, src)

of which the prior code blindly assumed that everytime that
copy is invoked that the buffer provided had enough size
to accomodate the contents of *.MarshalTo but this isn't true
at all if len(data) is less than the values of .Marshal()
  • Loading branch information
odeke-em authored May 23, 2022
1 parent 4459c2a commit b2af716
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 8 deletions.
8 changes: 4 additions & 4 deletions math/int.go
Original file line number Diff line number Diff line change
Expand Up @@ -383,17 +383,17 @@ func (i *Int) MarshalTo(data []byte) (n int, err error) {
i.i = new(big.Int)
}
if i.i.BitLen() == 0 { // The value 0
copy(data, []byte{0x30})
return 1, nil
n = copy(data, []byte{0x30})
return n, nil
}

bz, err := i.Marshal()
if err != nil {
return 0, err
}

copy(data, bz)
return len(bz), nil
n = copy(data, bz)
return n, nil
}

// Unmarshal implements the gogo proto custom type interface.
Expand Down
8 changes: 4 additions & 4 deletions math/uint.go
Original file line number Diff line number Diff line change
Expand Up @@ -162,17 +162,17 @@ func (u *Uint) MarshalTo(data []byte) (n int, err error) {
u.i = new(big.Int)
}
if u.i.BitLen() == 0 { // The value 0
copy(data, []byte{0x30})
return 1, nil
n = copy(data, []byte{0x30})
return n, nil
}

bz, err := u.Marshal()
if err != nil {
return 0, err
}

copy(data, bz)
return len(bz), nil
n = copy(data, bz)
return n, nil
}

// Unmarshal implements the gogo proto custom type interface.
Expand Down

0 comments on commit b2af716

Please sign in to comment.