1
0
mirror of https://github.com/golang/go synced 2024-11-19 11:44:45 -07:00

fmt: float formatting should not permanently change width

formatFloat should restore the original f.wid value before
returning. Callers should not have to save and restore f.wid.

Fixes: #14642

Change-Id: I531dae15c7997fe8909e2ad1ef7c376654afb030
Reviewed-on: https://go-review.googlesource.com/20179
Run-TryBot: Rob Pike <r@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Rob Pike <r@golang.org>
This commit is contained in:
Martin Möhrmann 2016-03-04 15:52:35 +01:00 committed by Rob Pike
parent 72d90d8238
commit 783741844b
2 changed files with 11 additions and 4 deletions

View File

@ -735,6 +735,13 @@ var fmtTests = []struct {
{"%0-5s", "abc", "abc "},
{"%-05.1f", 1.0, "1.0 "},
// float and complex formatting should not change the padding width
// for other elements. See issue 14642.
{"%06v", []interface{}{+10.0, 10}, "[000010 000010]"},
{"%06v", []interface{}{-10.0, 10}, "[-00010 000010]"},
{"%06v", []interface{}{+10.0 + 10i, 10}, "[(000010+00010i) 000010]"},
{"%06v", []interface{}{-10.0 + 10i, 10}, "[(-00010+00010i) 000010]"},
// Complex fmt used to leave the plus flag set for future entries in the array
// causing +2+0i and +3+0i instead of 2+0i and 3+0i.
{"%v", []complex64{1, 2, 3}, "[(1+0i) (2+0i) (3+0i)]"},
@ -1008,6 +1015,7 @@ func BenchmarkSprintfFloat(b *testing.B) {
}
})
}
func BenchmarkSprintfBoolean(b *testing.B) {
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {

View File

@ -448,7 +448,9 @@ func (f *fmt) formatFloat(v float64, verb byte, prec, n int) {
if f.zero && f.widPresent && f.wid > len(num) {
f.buf.WriteByte(num[0])
f.wid--
num = num[1:]
f.pad(num[1:])
f.wid++
return
}
f.pad(num)
return
@ -512,7 +514,6 @@ func (f *fmt) fmt_complex(r, j float64, size int, verb rune) {
f.buf.WriteByte('(')
oldPlus := f.plus
oldSpace := f.space
oldWid := f.wid
for i := 0; ; i++ {
switch verb {
case 'b':
@ -534,11 +535,9 @@ func (f *fmt) fmt_complex(r, j float64, size int, verb rune) {
// Imaginary part always has a sign.
f.plus = true
f.space = false
f.wid = oldWid
r = j
}
f.space = oldSpace
f.plus = oldPlus
f.wid = oldWid
f.buf.WriteString("i)")
}