math: derive marshalled byte length from copy, not blind assumptions (#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()
This commit is contained in:
Emmanuel T Odeke 2022-05-23 13:08:11 +03:00 committed by GitHub
parent 4459c2aebd
commit b2af716bf7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 8 additions and 8 deletions

View File

@ -383,8 +383,8 @@ 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()
@ -392,8 +392,8 @@ func (i *Int) MarshalTo(data []byte) (n int, err error) {
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.

View File

@ -162,8 +162,8 @@ 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()
@ -171,8 +171,8 @@ func (u *Uint) MarshalTo(data []byte) (n int, err error) {
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.