Skip to content

Commit

Permalink
fmt: allow padding and minus flags at the same time
Browse files Browse the repository at this point in the history
Existing implementation did not allow setting both padding and
minus flags at the same time because standard formatting does
not allow that. But custom Formatter interface implementations
might have use of it. This change moves the check from the
place flags are parsed to where they are used in standard
formatting.

Fixes golang#61784
  • Loading branch information
mitar committed Aug 8, 2023
1 parent 87fe5fa commit 4ab8256
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 5 deletions.
8 changes: 5 additions & 3 deletions src/fmt/format.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,8 @@ func (f *fmt) writePadding(n int) {
}
// Decide which byte the padding should be filled with.
padByte := byte(' ')
if f.zero {
// Zero padding is allowed only to the left.
if f.zero && !f.minus {
padByte = byte('0')
}
// Fill padding with padByte.
Expand Down Expand Up @@ -223,7 +224,7 @@ func (f *fmt) fmtInteger(u uint64, base int, isSigned bool, verb rune, digits st
f.zero = oldZero
return
}
} else if f.zero && f.widPresent {
} else if f.zero && !f.minus && f.widPresent { // Zero padding is allowed only to the left.
prec = f.wid
if negative || f.plus || f.space {
prec-- // leave room for sign
Expand Down Expand Up @@ -580,7 +581,8 @@ func (f *fmt) fmtFloat(v float64, size int, verb rune, prec int) {
if f.plus || num[0] != '+' {
// 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) {
// Zero padding is allowed only to the left.
if f.zero && !f.minus && f.widPresent && f.wid > len(num) {
f.buf.writeByte(num[0])
f.writePadding(f.wid - len(num))
f.buf.write(num[1:])
Expand Down
3 changes: 1 addition & 2 deletions src/fmt/print.go
Original file line number Diff line number Diff line change
Expand Up @@ -1050,12 +1050,11 @@ formatLoop:
case '#':
p.fmt.sharp = true
case '0':
p.fmt.zero = !p.fmt.minus // Only allow zero padding to the left.
p.fmt.zero = true
case '+':
p.fmt.plus = true
case '-':
p.fmt.minus = true
p.fmt.zero = false // Do not pad with zeros to the right.
case ' ':
p.fmt.space = true
default:
Expand Down

0 comments on commit 4ab8256

Please sign in to comment.