Commit 78374184 authored by Martin Möhrmann's avatar Martin Möhrmann Committed by Rob Pike

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: default avatarRob Pike <r@golang.org>
parent 72d90d82
......@@ -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() {
......
......@@ -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)")
}
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment