From: Martin Möhrmann Date: Fri, 4 Mar 2016 14:52:35 +0000 (+0100) Subject: fmt: float formatting should not permanently change width X-Git-Tag: go1.7beta1~1536 X-Git-Url: http://www.git.cypherpunks.su/?a=commitdiff_plain;h=783741844b48ebbe6b575369c915bfc1c6e53972;p=gostls13.git 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 TryBot-Result: Gobot Gobot Reviewed-by: Rob Pike --- diff --git a/src/fmt/fmt_test.go b/src/fmt/fmt_test.go index 47486c4586..e43bf1029c 100644 --- a/src/fmt/fmt_test.go +++ b/src/fmt/fmt_test.go @@ -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() { diff --git a/src/fmt/format.go b/src/fmt/format.go index 0388d4764c..821c7b44b1 100644 --- a/src/fmt/format.go +++ b/src/fmt/format.go @@ -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)") }