strconv: avoid panic on invalid call to FormatFloat

Calling FormatFloat with an invalid value of fmt is expected
to return a string containing '%' and the input fmt character.
Since even before Go 1.0, the code has been panicking in the
case where prec=0.

Fixes #52187

Change-Id: I74fec601eedb7fe28efc5132c4253674661452aa
Reviewed-on: https://go-review.googlesource.com/c/go/+/402817
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Ian Lance Taylor <iant@golang.org>
Reviewed-by: Emmanuel Odeke <emmanuel@orijtech.com>
Reviewed-by: Ian Lance Taylor <iant@google.com>
Run-TryBot: Ian Lance Taylor <iant@google.com>
Reviewed-by: Carlos Amedee <carlos@golang.org>
Auto-Submit: Emmanuel Odeke <emmanuel@orijtech.com>
Auto-Submit: Ian Lance Taylor <iant@google.com>
This commit is contained in:
Rémy Oudompheng 2022-04-29 11:54:13 +02:00 committed by Gopher Robot
parent bd4753905d
commit 41e1d9075e
2 changed files with 8 additions and 0 deletions

View file

@ -138,6 +138,9 @@ func genericFtoa(dst []byte, val float64, fmt byte, prec, bitSize int) []byte {
prec = 1
}
digits = prec
default:
// Invalid mode.
digits = 1
}
var buf [24]byte
if bitSize == 32 && digits <= 9 {

View file

@ -151,6 +151,11 @@ var ftoatests = []ftoaTest{
{498484681984085570, 'f', -1, "498484681984085570"},
{-5.8339553793802237e+23, 'g', -1, "-5.8339553793802237e+23"},
// Issue 52187
{123.45, '?', 0, "%?"},
{123.45, '?', 1, "%?"},
{123.45, '?', -1, "%?"},
// rounding
{2.275555555555555, 'x', -1, "0x1.23456789abcdep+01"},
{2.275555555555555, 'x', 0, "0x1p+01"},