]> Cypherpunks repositories - gostls13.git/commitdiff
fmt: float formatting should not permanently change width
authorMartin Möhrmann <martisch@uos.de>
Fri, 4 Mar 2016 14:52:35 +0000 (15:52 +0100)
committerRob Pike <r@golang.org>
Sat, 5 Mar 2016 03:01:22 +0000 (03:01 +0000)
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>
src/fmt/fmt_test.go
src/fmt/format.go

index 47486c4586c350ab1e1ba1d913136bc084f6fae5..e43bf1029c0c267e29942f6d66f17869e5240208 100644 (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() {
index 0388d4764cb3811768aa3d52b9b4ebaa0e89d58d..821c7b44b1ad63f1c886bf167505716edaaec39a 100644 (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)")
 }