From: Martin Möhrmann Date: Sun, 27 Mar 2016 09:50:25 +0000 (+0200) Subject: fmt: improve handling of zero padding X-Git-Tag: go1.7beta1~1031 X-Git-Url: http://www.git.cypherpunks.su/?a=commitdiff_plain;h=d175a85c5cef41b7f9ad8e7a9e2ebf84546a216e;p=gostls13.git fmt: improve handling of zero padding Simplify the handling of zero padding in fmt_integer and fmt_float to not require any adjustment of the format flags. Note that f.zero can only be true when padding to the left and f.wid is always greater than or equal to 0. Change-Id: I204b57d103c0eac13d86995992f2b26209196925 Reviewed-on: https://go-review.googlesource.com/21185 Run-TryBot: Rob Pike TryBot-Result: Gobot Gobot Reviewed-by: Rob Pike --- diff --git a/src/fmt/format.go b/src/fmt/format.go index 648da8a6a3..6539c0b1c1 100644 --- a/src/fmt/format.go +++ b/src/fmt/format.go @@ -220,12 +220,10 @@ func (f *fmt) fmt_integer(u uint64, base int, isSigned bool, digits string) { // two ways to ask for extra leading zero digits: %.3d or %03d. // apparently the first cancels the second. - oldZero := f.zero // f.zero is used in f.pad but modified below; restored at end of function. prec := 0 if f.precPresent { prec = f.prec - f.zero = false - } else if f.zero && f.widPresent && !f.minus && f.wid > 0 { + } else if f.zero && f.widPresent { prec = f.wid if negative || f.plus || f.space { prec-- // leave room for sign @@ -302,8 +300,14 @@ func (f *fmt) fmt_integer(u uint64, base int, isSigned bool, digits string) { buf[i] = ' ' } + // Left padding with zeros has already been handled like precision earlier + // or was overruled by an explicitly set precision. + if f.zero { + f.buf.Write(buf[i:]) + return + } + f.pad(buf[i:]) - f.zero = oldZero } // truncate truncates the string to the specified precision, if present. @@ -480,13 +484,12 @@ func (f *fmt) fmt_float(v float64, size int, verb rune, prec int) { } // We want a sign if asked for and if the sign is not positive. if f.plus || num[0] != '+' { - // If we're zero padding we want the sign before the leading zeros. + // If we're zero padding to the left we want the sign before the leading zeros. // Achieve this by writing the sign out and then padding the unsigned number. if f.zero && f.widPresent && f.wid > len(num) { f.buf.WriteByte(num[0]) - f.wid-- - f.pad(num[1:]) - f.wid++ + f.writePadding(f.wid - len(num)) + f.buf.Write(num[1:]) return } f.pad(num)