1 // Copyright 2017 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
14 ldigits = "0123456789abcdefx"
15 udigits = "0123456789ABCDEFX"
23 // flags placed in a separate struct for easy clearing.
24 type fmtFlags struct {
33 // For the formats %+v %#v, we set the plusV/sharpV flags
34 // and clear the plus/sharp flags since %+v and %#v are in effect
35 // different, flagless formats set at the top level.
40 // A formatInfo is the raw formatter used by Printf etc.
41 // It prints into a buffer that must be set up separately.
42 type formatInfo struct {
50 // intbuf is large enough to store %b of an int64 with a sign and
51 // avoids padding at the end of the struct on 32 bit architectures.
55 func (f *formatInfo) clearflags() {
56 f.fmtFlags = fmtFlags{}
59 func (f *formatInfo) init(buf *bytes.Buffer) {
64 // writePadding generates n bytes of padding.
65 func (f *formatInfo) writePadding(n int) {
66 if n <= 0 { // No padding bytes needed.
70 // Decide which byte the padding should be filled with.
75 // Fill padding with padByte.
76 for i := 0; i < n; i++ {
77 f.buf.WriteByte(padByte) // TODO: make more efficient.
81 // pad appends b to f.buf, padded on left (!f.minus) or right (f.minus).
82 func (f *formatInfo) pad(b []byte) {
83 if !f.widPresent || f.wid == 0 {
87 width := f.wid - utf8.RuneCount(b)
99 // padString appends s to f.buf, padded on left (!f.minus) or right (f.minus).
100 func (f *formatInfo) padString(s string) {
101 if !f.widPresent || f.wid == 0 {
105 width := f.wid - utf8.RuneCountInString(s)
108 f.writePadding(width)
113 f.writePadding(width)
117 // fmt_boolean formats a boolean.
118 func (f *formatInfo) fmt_boolean(v bool) {
126 // fmt_unicode formats a uint64 as "U+0078" or with f.sharp set as "U+0078 'x'".
127 func (f *formatInfo) fmt_unicode(u uint64) {
130 // With default precision set the maximum needed buf length is 18
131 // for formatting -1 with %#U ("U+FFFFFFFFFFFFFFFF") which fits
132 // into the already allocated intbuf with a capacity of 68 bytes.
134 if f.precPresent && f.prec > 4 {
136 // Compute space needed for "U+" , number, " '", character, "'".
137 width := 2 + prec + 2 + utf8.UTFMax + 1
138 if width > len(buf) {
139 buf = make([]byte, width)
143 // Format into buf, ending at buf[i]. Formatting numbers is easier right-to-left.
146 // For %#U we want to add a space and a quoted character at the end of the buffer.
147 if f.sharp && u <= utf8.MaxRune && strconv.IsPrint(rune(u)) {
150 i -= utf8.RuneLen(rune(u))
151 utf8.EncodeRune(buf[i:], rune(u))
157 // Format the Unicode code point u as a hexadecimal number.
160 buf[i] = udigits[u&0xF]
167 // Add zeros in front of the number until requested precision is reached.
173 // Add a leading "U+".
185 // fmt_integer formats signed and unsigned integers.
186 func (f *formatInfo) fmt_integer(u uint64, base int, isSigned bool, digits string) {
187 negative := isSigned && int64(u) < 0
193 // The already allocated f.intbuf with a capacity of 68 bytes
194 // is large enough for integer formatting when no precision or width is set.
195 if f.widPresent || f.precPresent {
196 // Account 3 extra bytes for possible addition of a sign and "0x".
197 width := 3 + f.wid + f.prec // wid and prec are always positive.
198 if width > len(buf) {
199 // We're going to need a bigger boat.
200 buf = make([]byte, width)
204 // Two ways to ask for extra leading zero digits: %.3d or %03d.
205 // If both are specified the f.zero flag is ignored and
206 // padding with spaces is used instead.
210 // Precision of 0 and value of 0 means "print nothing" but padding.
211 if prec == 0 && u == 0 {
214 f.writePadding(f.wid)
218 } else if f.zero && f.widPresent {
220 if negative || f.plus || f.space {
221 prec-- // leave room for sign
225 // Because printing is easier right-to-left: format u into buf, ending at buf[i].
226 // We could make things marginally faster by splitting the 32-bit case out
227 // into a separate block but it's not worth the duplication, so u has 64 bits.
229 // Use constants for the division and modulo for more efficient code.
230 // Switch cases ordered by popularity.
236 buf[i] = byte('0' + u - next*10)
242 buf[i] = digits[u&0xF]
248 buf[i] = byte('0' + u&7)
254 buf[i] = byte('0' + u&1)
258 panic("fmt: unknown base; can't happen")
262 for i > 0 && prec > len(buf)-i {
267 // Various prefixes: 0x, -, etc.
276 // Add a leading 0x or 0X.
295 // Left padding with zeros has already been handled like precision earlier
296 // or the f.zero flag is ignored due to an explicitly set precision.
303 // truncate truncates the string to the specified precision, if present.
304 func (f *formatInfo) truncate(s string) string {
317 // fmt_s formats a string.
318 func (f *formatInfo) fmt_s(s string) {
323 // fmt_sbx formats a string or byte slice as a hexadecimal encoding of its bytes.
324 func (f *formatInfo) fmt_sbx(s string, b []byte, digits string) {
327 // No byte slice present. Assume string s should be encoded.
330 // Set length to not process more bytes than the precision demands.
331 if f.precPresent && f.prec < length {
334 // Compute width of the encoding taking into account the f.sharp and f.space flag.
338 // Each element encoded by two hexadecimals will get a leading 0x or 0X.
342 // Elements will be separated by a space.
345 // Only a leading 0x or 0X will be added for the whole string.
348 } else { // The byte slice or string that should be encoded is empty.
350 f.writePadding(f.wid)
354 // Handle padding to the left.
355 if f.widPresent && f.wid > width && !f.minus {
356 f.writePadding(f.wid - width)
358 // Write the encoding directly into the output buffer.
361 // Add leading 0x or 0X.
363 buf.WriteByte(digits[16])
366 for i := 0; i < length; i++ {
367 if f.space && i > 0 {
368 // Separate elements with a space.
371 // Add leading 0x or 0X for each element.
373 buf.WriteByte(digits[16])
377 c = b[i] // Take a byte from the input byte slice.
379 c = s[i] // Take a byte from the input string.
381 // Encode each byte as two hexadecimal digits.
382 buf.WriteByte(digits[c>>4])
383 buf.WriteByte(digits[c&0xF])
385 // Handle padding to the right.
386 if f.widPresent && f.wid > width && f.minus {
387 f.writePadding(f.wid - width)
391 // fmt_sx formats a string as a hexadecimal encoding of its bytes.
392 func (f *formatInfo) fmt_sx(s, digits string) {
393 f.fmt_sbx(s, nil, digits)
396 // fmt_bx formats a byte slice as a hexadecimal encoding of its bytes.
397 func (f *formatInfo) fmt_bx(b []byte, digits string) {
398 f.fmt_sbx("", b, digits)
401 // fmt_q formats a string as a double-quoted, escaped Go string constant.
402 // If f.sharp is set a raw (backquoted) string may be returned instead
403 // if the string does not contain any control characters other than tab.
404 func (f *formatInfo) fmt_q(s string) {
406 if f.sharp && strconv.CanBackquote(s) {
407 f.padString("`" + s + "`")
412 f.pad(strconv.AppendQuoteToASCII(buf, s))
414 f.pad(strconv.AppendQuote(buf, s))
418 // fmt_c formats an integer as a Unicode character.
419 // If the character is not valid Unicode, it will print '\ufffd'.
420 func (f *formatInfo) fmt_c(c uint64) {
422 if c > utf8.MaxRune {
426 w := utf8.EncodeRune(buf[:utf8.UTFMax], r)
430 // fmt_qc formats an integer as a single-quoted, escaped Go character constant.
431 // If the character is not valid Unicode, it will print '\ufffd'.
432 func (f *formatInfo) fmt_qc(c uint64) {
434 if c > utf8.MaxRune {
439 f.pad(strconv.AppendQuoteRuneToASCII(buf, r))
441 f.pad(strconv.AppendQuoteRune(buf, r))
445 // fmt_float formats a float64. It assumes that verb is a valid format specifier
446 // for strconv.AppendFloat and therefore fits into a byte.
447 func (f *formatInfo) fmt_float(v float64, size int, verb rune, prec int) {
448 // Explicit precision in format specifier overrules default precision.
452 // Format number, reserving space for leading + sign if needed.
453 num := strconv.AppendFloat(f.intbuf[:1], v, byte(verb), prec, size)
454 if num[1] == '-' || num[1] == '+' {
459 // f.space means to add a leading space instead of a "+" sign unless
460 // the sign is explicitly asked for by f.plus.
461 if f.space && num[0] == '+' && !f.plus {
464 // Special handling for infinities and NaN,
465 // which don't look like a number so shouldn't be padded with zeros.
466 if num[1] == 'I' || num[1] == 'N' {
469 // Remove sign before NaN if not asked for.
470 if num[1] == 'N' && !f.space && !f.plus {
477 // The sharp flag forces printing a decimal point for non-binary formats
478 // and retains trailing zeros, which we may need to restore.
479 if f.sharp && verb != 'b' {
484 // If no precision is set explicitly use a precision of 6.
490 // Buffer pre-allocated with enough room for
491 // exponent notations of the form "e+123".
495 hasDecimalPoint := false
496 // Starting from i = 1 to skip sign at num[0].
497 for i := 1; i < len(num); i++ {
500 hasDecimalPoint = true
502 tail = append(tail, num[i:]...)
508 if !hasDecimalPoint {
509 num = append(num, '.')
512 num = append(num, '0')
515 num = append(num, tail...)
517 // We want a sign if asked for and if the sign is not positive.
518 if f.plus || num[0] != '+' {
519 // If we're zero padding to the left we want the sign before the leading zeros.
520 // Achieve this by writing the sign out and then padding the unsigned number.
521 if f.zero && f.widPresent && f.wid > len(num) {
522 f.buf.WriteByte(num[0])
523 f.writePadding(f.wid - len(num))
530 // No sign to show and the number is positive; just print the unsigned number.