1 // Copyright 2009 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.
16 // Some constants in the form of bytes, to avoid string overhead.
17 // Needlessly fastidious, I suppose.
19 commaSpaceBytes
= []byte(", ")
20 nilAngleBytes
= []byte("<nil>")
21 nilParenBytes
= []byte("(nil)")
22 nilBytes
= []byte("nil")
23 mapBytes
= []byte("map[")
24 percentBangBytes
= []byte("%!")
25 missingBytes
= []byte("(MISSING)")
26 badIndexBytes
= []byte("(BADINDEX)")
27 panicBytes
= []byte("(PANIC=")
28 extraBytes
= []byte("%!(EXTRA ")
29 irparenBytes
= []byte("i)")
30 bytesBytes
= []byte("[]byte{")
31 badWidthBytes
= []byte("%!(BADWIDTH)")
32 badPrecBytes
= []byte("%!(BADPREC)")
33 noVerbBytes
= []byte("%!(NOVERB)")
36 // State represents the printer state passed to custom formatters.
37 // It provides access to the io.Writer interface plus information about
38 // the flags and options for the operand's format specifier.
39 type State
interface {
40 // Write is the function to call to emit formatted output to be printed.
41 Write(b
[]byte) (ret
int, err error
)
42 // Width returns the value of the width option and whether it has been set.
43 Width() (wid
int, ok
bool)
44 // Precision returns the value of the precision option and whether it has been set.
45 Precision() (prec
int, ok
bool)
47 // Flag reports whether the flag c, a character, has been set.
51 // Formatter is the interface implemented by values with a custom formatter.
52 // The implementation of Format may call Sprint(f) or Fprint(f) etc.
53 // to generate its output.
54 type Formatter
interface {
55 Format(f State
, c rune
)
58 // Stringer is implemented by any value that has a String method,
59 // which defines the ``native'' format for that value.
60 // The String method is used to print values passed as an operand
61 // to any format that accepts a string or to an unformatted printer
63 type Stringer
interface {
67 // GoStringer is implemented by any value that has a GoString method,
68 // which defines the Go syntax for that value.
69 // The GoString method is used to print values passed as an operand
71 type GoStringer
interface {
75 // Use simple []byte instead of bytes.Buffer to avoid large dependency.
78 func (b
*buffer
) Write(p
[]byte) (n
int, err error
) {
83 func (b
*buffer
) WriteString(s
string) (n
int, err error
) {
88 func (b
*buffer
) WriteByte(c
byte) error
{
93 func (bp
*buffer
) WriteRune(r rune
) error
{
94 if r
< utf8
.RuneSelf
{
95 *bp
= append(*bp
, byte(r
))
101 for n
+utf8
.UTFMax
> cap(b
) {
104 w
:= utf8
.EncodeRune(b
[n
:n
+utf8
.UTFMax
], r
)
112 erroring
bool // printing an error condition
114 // arg holds the current item, as an interface{}.
116 // value holds the current item, as a reflect.Value, and will be
117 // the zero Value if the item has not been reflected.
119 // reordered records whether the format string used argument reordering.
121 // goodArgNum records whether the most recent reordering directive was valid.
123 runeBuf
[utf8
.UTFMax
]byte
127 var ppFree
= sync
.Pool
{
128 New
: func() interface{} { return new(pp
) },
131 // newPrinter allocates a new pp struct or grabs a cached one.
132 func newPrinter() *pp
{
133 p
:= ppFree
.Get().(*pp
)
140 // free saves used pp structs in ppFree; avoids an allocation per invocation.
141 func (p
*pp
) free() {
142 // Don't hold on to pp structs with large buffers.
143 if cap(p
.buf
) > 1024 {
148 p
.value
= reflect
.Value
{}
152 func (p
*pp
) Width() (wid
int, ok
bool) { return p
.fmt
.wid
, p
.fmt
.widPresent
}
154 func (p
*pp
) Precision() (prec
int, ok
bool) { return p
.fmt
.prec
, p
.fmt
.precPresent
}
156 func (p
*pp
) Flag(b
int) bool {
172 func (p
*pp
) add(c rune
) {
176 // Implement Write so we can call Fprintf on a pp (through State), for
177 // recursive use in custom verbs.
178 func (p
*pp
) Write(b
[]byte) (ret
int, err error
) {
179 return p
.buf
.Write(b
)
182 // These routines end in 'f' and take a format string.
184 // Fprintf formats according to a format specifier and writes to w.
185 // It returns the number of bytes written and any write error encountered.
186 func Fprintf(w io
.Writer
, format
string, a
...interface{}) (n
int, err error
) {
188 p
.doPrintf(format
, a
)
189 n
, err
= w
.Write(p
.buf
)
194 // Printf formats according to a format specifier and writes to standard output.
195 // It returns the number of bytes written and any write error encountered.
196 func Printf(format
string, a
...interface{}) (n
int, err error
) {
197 return Fprintf(os
.Stdout
, format
, a
...)
200 // Sprintf formats according to a format specifier and returns the resulting string.
201 func Sprintf(format
string, a
...interface{}) string {
203 p
.doPrintf(format
, a
)
209 // Errorf formats according to a format specifier and returns the string
210 // as a value that satisfies error.
211 func Errorf(format
string, a
...interface{}) error
{
212 return errors
.New(Sprintf(format
, a
...))
215 // These routines do not take a format string
217 // Fprint formats using the default formats for its operands and writes to w.
218 // Spaces are added between operands when neither is a string.
219 // It returns the number of bytes written and any write error encountered.
220 func Fprint(w io
.Writer
, a
...interface{}) (n
int, err error
) {
222 p
.doPrint(a
, false, false)
223 n
, err
= w
.Write(p
.buf
)
228 // Print formats using the default formats for its operands and writes to standard output.
229 // Spaces are added between operands when neither is a string.
230 // It returns the number of bytes written and any write error encountered.
231 func Print(a
...interface{}) (n
int, err error
) {
232 return Fprint(os
.Stdout
, a
...)
235 // Sprint formats using the default formats for its operands and returns the resulting string.
236 // Spaces are added between operands when neither is a string.
237 func Sprint(a
...interface{}) string {
239 p
.doPrint(a
, false, false)
245 // These routines end in 'ln', do not take a format string,
246 // always add spaces between operands, and add a newline
247 // after the last operand.
249 // Fprintln formats using the default formats for its operands and writes to w.
250 // Spaces are always added between operands and a newline is appended.
251 // It returns the number of bytes written and any write error encountered.
252 func Fprintln(w io
.Writer
, a
...interface{}) (n
int, err error
) {
254 p
.doPrint(a
, true, true)
255 n
, err
= w
.Write(p
.buf
)
260 // Println formats using the default formats for its operands and writes to standard output.
261 // Spaces are always added between operands and a newline is appended.
262 // It returns the number of bytes written and any write error encountered.
263 func Println(a
...interface{}) (n
int, err error
) {
264 return Fprintln(os
.Stdout
, a
...)
267 // Sprintln formats using the default formats for its operands and returns the resulting string.
268 // Spaces are always added between operands and a newline is appended.
269 func Sprintln(a
...interface{}) string {
271 p
.doPrint(a
, true, true)
277 // getField gets the i'th field of the struct value.
278 // If the field is itself is an interface, return a value for
279 // the thing inside the interface, not the interface itself.
280 func getField(v reflect
.Value
, i
int) reflect
.Value
{
282 if val
.Kind() == reflect
.Interface
&& !val
.IsNil() {
288 // parsenum converts ASCII to integer. num is 0 (and isnum is false) if no number present.
289 func parsenum(s
string, start
, end
int) (num
int, isnum
bool, newi
int) {
293 for newi
= start
; newi
< end
&& '0' <= s
[newi
] && s
[newi
] <= '9'; newi
++ {
294 num
= num
*10 + int(s
[newi
]-'0')
300 func (p
*pp
) unknownType(v reflect
.Value
) {
302 p
.buf
.Write(nilAngleBytes
)
306 p
.buf
.WriteString(v
.Type().String())
310 func (p
*pp
) badVerb(verb rune
) {
318 p
.buf
.WriteString(reflect
.TypeOf(p
.arg
).String())
320 p
.printArg(p
.arg
, 'v', 0)
321 case p
.value
.IsValid():
322 p
.buf
.WriteString(p
.value
.Type().String())
324 p
.printValue(p
.value
, 'v', 0)
326 p
.buf
.Write(nilAngleBytes
)
332 func (p
*pp
) fmtBool(v
bool, verb rune
) {
341 // fmtC formats a rune for the 'c' format.
342 func (p
*pp
) fmtC(c
int64) {
343 r
:= rune(c
) // Check for overflow.
347 w
:= utf8
.EncodeRune(p
.runeBuf
[0:utf8
.UTFMax
], r
)
348 p
.fmt
.pad(p
.runeBuf
[0:w
])
351 func (p
*pp
) fmtInt64(v
int64, verb rune
) {
354 p
.fmt
.integer(v
, 2, signed
, ldigits
)
358 p
.fmt
.integer(v
, 10, signed
, ldigits
)
360 p
.fmt
.integer(v
, 8, signed
, ldigits
)
362 if 0 <= v
&& v
<= utf8
.MaxRune
{
368 p
.fmt
.integer(v
, 16, signed
, ldigits
)
372 p
.fmt
.integer(v
, 16, signed
, udigits
)
378 // fmt0x64 formats a uint64 in hexadecimal and prefixes it with 0x or
379 // not, as requested, by temporarily setting the sharp flag.
380 func (p
*pp
) fmt0x64(v
uint64, leading0x
bool) {
382 p
.fmt
.sharp
= leading0x
383 p
.fmt
.integer(int64(v
), 16, unsigned
, ldigits
)
387 // fmtUnicode formats a uint64 in U+1234 form by
388 // temporarily turning on the unicode flag and tweaking the precision.
389 func (p
*pp
) fmtUnicode(v
int64) {
390 precPresent
:= p
.fmt
.precPresent
395 // If prec is already set, leave it alone; otherwise 4 is minimum.
397 p
.fmt
.precPresent
= true
399 p
.fmt
.unicode
= true // turn on U+
400 p
.fmt
.uniQuote
= sharp
401 p
.fmt
.integer(int64(v
), 16, unsigned
, udigits
)
402 p
.fmt
.unicode
= false
403 p
.fmt
.uniQuote
= false
405 p
.fmt
.precPresent
= precPresent
409 func (p
*pp
) fmtUint64(v
uint64, verb rune
) {
412 p
.fmt
.integer(int64(v
), 2, unsigned
, ldigits
)
416 p
.fmt
.integer(int64(v
), 10, unsigned
, ldigits
)
421 p
.fmt
.integer(int64(v
), 10, unsigned
, ldigits
)
424 p
.fmt
.integer(int64(v
), 8, unsigned
, ldigits
)
426 if 0 <= v
&& v
<= utf8
.MaxRune
{
427 p
.fmt
.fmt_qc(int64(v
))
432 p
.fmt
.integer(int64(v
), 16, unsigned
, ldigits
)
434 p
.fmt
.integer(int64(v
), 16, unsigned
, udigits
)
436 p
.fmtUnicode(int64(v
))
442 func (p
*pp
) fmtFloat32(v
float32, verb rune
) {
461 func (p
*pp
) fmtFloat64(v
float64, verb rune
) {
480 func (p
*pp
) fmtComplex64(v complex64
, verb rune
) {
482 case 'b', 'e', 'E', 'f', 'F', 'g', 'G':
483 p
.fmt
.fmt_c64(v
, verb
)
485 p
.fmt
.fmt_c64(v
, 'g')
491 func (p
*pp
) fmtComplex128(v complex128
, verb rune
) {
493 case 'b', 'e', 'E', 'f', 'F', 'g', 'G':
494 p
.fmt
.fmt_c128(v
, verb
)
496 p
.fmt
.fmt_c128(v
, 'g')
502 func (p
*pp
) fmtString(v
string, verb rune
) {
513 p
.fmt
.fmt_sx(v
, ldigits
)
515 p
.fmt
.fmt_sx(v
, udigits
)
523 func (p
*pp
) fmtBytes(v
[]byte, verb rune
, typ reflect
.Type
, depth
int) {
524 if verb
== 'v' || verb
== 'd' {
528 p
.buf
.WriteString("[]byte(nil)")
530 p
.buf
.WriteString(typ
.String())
531 p
.buf
.Write(nilParenBytes
)
536 p
.buf
.Write(bytesBytes
)
538 p
.buf
.WriteString(typ
.String())
544 for i
, c
:= range v
{
547 p
.buf
.Write(commaSpaceBytes
)
552 p
.printArg(c
, 'v', depth
+1)
563 p
.fmt
.fmt_s(string(v
))
565 p
.fmt
.fmt_bx(v
, ldigits
)
567 p
.fmt
.fmt_bx(v
, udigits
)
569 p
.fmt
.fmt_q(string(v
))
575 func (p
*pp
) fmtPointer(value reflect
.Value
, verb rune
) {
580 case 'b', 'd', 'o', 'x', 'X':
589 switch value
.Kind() {
590 case reflect
.Chan
, reflect
.Func
, reflect
.Map
, reflect
.Ptr
, reflect
.Slice
, reflect
.UnsafePointer
:
599 p
.buf
.WriteString(value
.Type().String())
603 p
.buf
.Write(nilBytes
)
605 p
.fmt0x64(uint64(u
), true)
608 } else if verb
== 'v' && u
== 0 {
609 p
.buf
.Write(nilAngleBytes
)
612 p
.fmt0x64(uint64(u
), !p
.fmt
.sharp
)
614 p
.fmtUint64(uint64(u
), verb
)
620 intBits
= reflect
.TypeOf(0).Bits()
621 uintptrBits
= reflect
.TypeOf(uintptr(0)).Bits()
624 func (p
*pp
) catchPanic(arg
interface{}, verb rune
) {
625 if err
:= recover(); err
!= nil {
626 // If it's a nil pointer, just say "<nil>". The likeliest causes are a
627 // Stringer that fails to guard against nil or a nil pointer for a
628 // value receiver, and in either case, "<nil>" is a nice result.
629 if v
:= reflect
.ValueOf(arg
); v
.Kind() == reflect
.Ptr
&& v
.IsNil() {
630 p
.buf
.Write(nilAngleBytes
)
633 // Otherwise print a concise panic message. Most of the time the panic
634 // value will print itself nicely.
636 // Nested panics; the recursion in printArg cannot succeed.
639 p
.fmt
.clearflags() // We are done, and for this output we want default behavior.
640 p
.buf
.Write(percentBangBytes
)
642 p
.buf
.Write(panicBytes
)
644 p
.printArg(err
, 'v', 0)
650 // clearSpecialFlags pushes %#v back into the regular flags and returns their old state.
651 func (p
*pp
) clearSpecialFlags() (plusV
, sharpV
bool) {
657 sharpV
= p
.fmt
.sharpV
665 // restoreSpecialFlags, whose argument should be a call to clearSpecialFlags,
666 // restores the setting of the plusV and sharpV flags.
667 func (p
*pp
) restoreSpecialFlags(plusV
, sharpV
bool) {
678 func (p
*pp
) handleMethods(verb rune
, depth
int) (handled
bool) {
682 // Is it a Formatter?
683 if formatter
, ok
:= p
.arg
.(Formatter
); ok
{
685 defer p
.restoreSpecialFlags(p
.clearSpecialFlags())
686 defer p
.catchPanic(p
.arg
, verb
)
687 formatter
.Format(p
, verb
)
691 // If we're doing Go syntax and the argument knows how to supply it, take care of it now.
693 if stringer
, ok
:= p
.arg
.(GoStringer
); ok
{
695 defer p
.catchPanic(p
.arg
, verb
)
696 // Print the result of GoString unadorned.
697 p
.fmt
.fmt_s(stringer
.GoString())
701 // If a string is acceptable according to the format, see if
702 // the value satisfies one of the string-valued interfaces.
703 // Println etc. set verb to %v, which is "stringable".
705 case 'v', 's', 'x', 'X', 'q':
706 // Is it an error or Stringer?
707 // The duplication in the bodies is necessary:
708 // setting handled and deferring catchPanic
709 // must happen before calling the method.
710 switch v
:= p
.arg
.(type) {
713 defer p
.catchPanic(p
.arg
, verb
)
714 p
.printArg(v
.Error(), verb
, depth
)
719 defer p
.catchPanic(p
.arg
, verb
)
720 p
.printArg(v
.String(), verb
, depth
)
728 func (p
*pp
) printArg(arg
interface{}, verb rune
, depth
int) (wasString
bool) {
730 p
.value
= reflect
.Value
{}
733 if verb
== 'T' || verb
== 'v' {
734 p
.fmt
.pad(nilAngleBytes
)
741 // Special processing considerations.
742 // %T (the value's type) and %p (its address) are special; we always do them first.
745 p
.printArg(reflect
.TypeOf(arg
).String(), 's', 0)
748 p
.fmtPointer(reflect
.ValueOf(arg
), verb
)
752 // Some types can be done without reflection.
753 switch f
:= arg
.(type) {
757 p
.fmtFloat32(f
, verb
)
759 p
.fmtFloat64(f
, verb
)
761 p
.fmtComplex64(f
, verb
)
763 p
.fmtComplex128(f
, verb
)
765 p
.fmtInt64(int64(f
), verb
)
767 p
.fmtInt64(int64(f
), verb
)
769 p
.fmtInt64(int64(f
), verb
)
771 p
.fmtInt64(int64(f
), verb
)
775 p
.fmtUint64(uint64(f
), verb
)
777 p
.fmtUint64(uint64(f
), verb
)
779 p
.fmtUint64(uint64(f
), verb
)
781 p
.fmtUint64(uint64(f
), verb
)
785 p
.fmtUint64(uint64(f
), verb
)
788 wasString
= verb
== 's' || verb
== 'v'
790 p
.fmtBytes(f
, verb
, nil, depth
)
791 wasString
= verb
== 's'
793 // If the type is not simple, it might have methods.
794 if handled
:= p
.handleMethods(verb
, depth
); handled
{
797 // Need to use reflection
798 return p
.printReflectValue(reflect
.ValueOf(arg
), verb
, depth
)
804 // printValue is like printArg but starts with a reflect value, not an interface{} value.
805 func (p
*pp
) printValue(value reflect
.Value
, verb rune
, depth
int) (wasString
bool) {
806 if !value
.IsValid() {
807 if verb
== 'T' || verb
== 'v' {
808 p
.buf
.Write(nilAngleBytes
)
815 // Special processing considerations.
816 // %T (the value's type) and %p (its address) are special; we always do them first.
819 p
.printArg(value
.Type().String(), 's', 0)
822 p
.fmtPointer(value
, verb
)
826 // Handle values with special methods.
827 // Call always, even when arg == nil, because handleMethods clears p.fmt.plus for us.
828 p
.arg
= nil // Make sure it's cleared, for safety.
829 if value
.CanInterface() {
830 p
.arg
= value
.Interface()
832 if handled
:= p
.handleMethods(verb
, depth
); handled
{
836 return p
.printReflectValue(value
, verb
, depth
)
839 var byteType
= reflect
.TypeOf(byte(0))
841 // printReflectValue is the fallback for both printArg and printValue.
842 // It uses reflect to print the value.
843 func (p
*pp
) printReflectValue(value reflect
.Value
, verb rune
, depth
int) (wasString
bool) {
847 switch f
:= value
; f
.Kind() {
849 p
.fmtBool(f
.Bool(), verb
)
850 case reflect
.Int
, reflect
.Int8
, reflect
.Int16
, reflect
.Int32
, reflect
.Int64
:
851 p
.fmtInt64(f
.Int(), verb
)
852 case reflect
.Uint
, reflect
.Uint8
, reflect
.Uint16
, reflect
.Uint32
, reflect
.Uint64
, reflect
.Uintptr
:
853 p
.fmtUint64(f
.Uint(), verb
)
854 case reflect
.Float32
, reflect
.Float64
:
855 if f
.Type().Size() == 4 {
856 p
.fmtFloat32(float32(f
.Float()), verb
)
858 p
.fmtFloat64(f
.Float(), verb
)
860 case reflect
.Complex64
, reflect
.Complex128
:
861 if f
.Type().Size() == 8 {
862 p
.fmtComplex64(complex64(f
.Complex()), verb
)
864 p
.fmtComplex128(f
.Complex(), verb
)
867 p
.fmtString(f
.String(), verb
)
870 p
.buf
.WriteString(f
.Type().String())
872 p
.buf
.WriteString("(nil)")
877 p
.buf
.Write(mapBytes
)
880 for i
, key
:= range keys
{
883 p
.buf
.Write(commaSpaceBytes
)
888 p
.printValue(key
, verb
, depth
+1)
890 p
.printValue(f
.MapIndex(key
), verb
, depth
+1)
899 p
.buf
.WriteString(value
.Type().String())
904 for i
:= 0; i
< v
.NumField(); i
++ {
907 p
.buf
.Write(commaSpaceBytes
)
912 if p
.fmt
.plusV || p
.fmt
.sharpV
{
913 if f
:= t
.Field(i
); f
.Name
!= "" {
914 p
.buf
.WriteString(f
.Name
)
918 p
.printValue(getField(v
, i
), verb
, depth
+1)
921 case reflect
.Interface
:
923 if !value
.IsValid() {
925 p
.buf
.WriteString(f
.Type().String())
926 p
.buf
.Write(nilParenBytes
)
928 p
.buf
.Write(nilAngleBytes
)
931 wasString
= p
.printValue(value
, verb
, depth
+1)
933 case reflect
.Array
, reflect
.Slice
:
934 // Byte slices are special:
935 // - Handle []byte (== []uint8) with fmtBytes.
936 // - Handle []T, where T is a named byte type, with fmtBytes only
937 // for the s, q, an x verbs. For other verbs, T might be a
938 // Stringer, so we use printValue to print each element.
939 if typ
:= f
.Type(); typ
.Elem().Kind() == reflect
.Uint8
&& (typ
.Elem() == byteType || verb
== 's' || verb
== 'q' || verb
== 'x') {
941 if f
.Kind() == reflect
.Slice
{
943 } else if f
.CanAddr() {
944 bytes
= f
.Slice(0, f
.Len()).Bytes()
946 // We have an array, but we cannot Slice() a non-addressable array,
947 // so we build a slice by hand. This is a rare case but it would be nice
948 // if reflection could help a little more.
949 bytes
= make([]byte, f
.Len())
950 for i
:= range bytes
{
951 bytes
[i
] = byte(f
.Index(i
).Uint())
954 p
.fmtBytes(bytes
, verb
, typ
, depth
)
955 wasString
= verb
== 's'
959 p
.buf
.WriteString(value
.Type().String())
960 if f
.Kind() == reflect
.Slice
&& f
.IsNil() {
961 p
.buf
.WriteString("(nil)")
968 for i
:= 0; i
< f
.Len(); i
++ {
971 p
.buf
.Write(commaSpaceBytes
)
976 p
.printValue(f
.Index(i
), verb
, depth
+1)
985 // pointer to array or slice or struct? ok at top level
986 // but not embedded (avoid loops)
987 if v
!= 0 && depth
== 0 {
988 switch a
:= f
.Elem(); a
.Kind() {
989 case reflect
.Array
, reflect
.Slice
:
991 p
.printValue(a
, verb
, depth
+1)
995 p
.printValue(a
, verb
, depth
+1)
999 p
.printValue(a
, verb
, depth
+1)
1004 case reflect
.Chan
, reflect
.Func
, reflect
.UnsafePointer
:
1005 p
.fmtPointer(value
, verb
)
1013 // intFromArg gets the argNumth element of a. On return, isInt reports whether the argument has type int.
1014 func intFromArg(a
[]interface{}, argNum
int) (num
int, isInt
bool, newArgNum
int) {
1016 if argNum
< len(a
) {
1017 num
, isInt
= a
[argNum
].(int)
1018 newArgNum
= argNum
+ 1
1023 // parseArgNumber returns the value of the bracketed number, minus 1
1024 // (explicit argument numbers are one-indexed but we want zero-indexed).
1025 // The opening bracket is known to be present at format[0].
1026 // The returned values are the index, the number of bytes to consume
1027 // up to the closing paren, if present, and whether the number parsed
1028 // ok. The bytes to consume will be 1 if no closing paren is present.
1029 func parseArgNumber(format
string) (index
int, wid
int, ok
bool) {
1030 // Find closing bracket.
1031 for i
:= 1; i
< len(format
); i
++ {
1032 if format
[i
] == ']' {
1033 width
, ok
, newi
:= parsenum(format
, 1, i
)
1034 if !ok || newi
!= i
{
1035 return 0, i
+ 1, false
1037 return width
- 1, i
+ 1, true // arg numbers are one-indexed and skip paren.
1043 // argNumber returns the next argument to evaluate, which is either the value of the passed-in
1044 // argNum or the value of the bracketed integer that begins format[i:]. It also returns
1045 // the new value of i, that is, the index of the next byte of the format to process.
1046 func (p
*pp
) argNumber(argNum
int, format
string, i
int, numArgs
int) (newArgNum
, newi
int, found
bool) {
1047 if len(format
) <= i || format
[i
] != '[' {
1048 return argNum
, i
, false
1051 index
, wid
, ok
:= parseArgNumber(format
[i
:])
1052 if ok
&& 0 <= index
&& index
< numArgs
{
1053 return index
, i
+ wid
, true
1055 p
.goodArgNum
= false
1056 return argNum
, i
+ wid
, true
1059 func (p
*pp
) doPrintf(format
string, a
[]interface{}) {
1061 argNum
:= 0 // we process one argument per non-trivial format
1062 afterIndex
:= false // previous item in format was an index like [3].
1064 for i
:= 0; i
< end
; {
1067 for i
< end
&& format
[i
] != '%' {
1071 p
.buf
.WriteString(format
[lasti
:i
])
1074 // done processing format string
1081 // Do we have flags?
1084 for ; i
< end
; i
++ {
1101 // Do we have an explicit argument index?
1102 argNum
, i
, afterIndex
= p
.argNumber(argNum
, format
, i
, len(a
))
1104 // Do we have width?
1105 if i
< end
&& format
[i
] == '*' {
1107 p
.fmt
.wid
, p
.fmt
.widPresent
, argNum
= intFromArg(a
, argNum
)
1108 if !p
.fmt
.widPresent
{
1109 p
.buf
.Write(badWidthBytes
)
1113 p
.fmt
.wid
, p
.fmt
.widPresent
, i
= parsenum(format
, i
, end
)
1114 if afterIndex
&& p
.fmt
.widPresent
{ // "%[3]2d"
1115 p
.goodArgNum
= false
1119 // Do we have precision?
1120 if i
+1 < end
&& format
[i
] == '.' {
1122 if afterIndex
{ // "%[3].2d"
1123 p
.goodArgNum
= false
1125 argNum
, i
, afterIndex
= p
.argNumber(argNum
, format
, i
, len(a
))
1126 if format
[i
] == '*' {
1128 p
.fmt
.prec
, p
.fmt
.precPresent
, argNum
= intFromArg(a
, argNum
)
1129 if !p
.fmt
.precPresent
{
1130 p
.buf
.Write(badPrecBytes
)
1134 p
.fmt
.prec
, p
.fmt
.precPresent
, i
= parsenum(format
, i
, end
)
1135 if !p
.fmt
.precPresent
{
1137 p
.fmt
.precPresent
= true
1143 argNum
, i
, afterIndex
= p
.argNumber(argNum
, format
, i
, len(a
))
1147 p
.buf
.Write(noVerbBytes
)
1150 c
, w
:= utf8
.DecodeRuneInString(format
[i
:])
1152 // percent is special - absorbs no operand
1154 p
.buf
.WriteByte('%') // We ignore width and prec.
1158 p
.buf
.Write(percentBangBytes
)
1160 p
.buf
.Write(badIndexBytes
)
1162 } else if argNum
>= len(a
) { // out of operands
1163 p
.buf
.Write(percentBangBytes
)
1165 p
.buf
.Write(missingBytes
)
1173 // Go syntax. Set the flag in the fmt and clear the sharp flag.
1178 // Struct-field syntax. Set the flag in the fmt and clear the plus flag.
1183 p
.printArg(arg
, c
, 0)
1186 // Check for extra arguments unless the call accessed the arguments
1187 // out of order, in which case it's too expensive to detect if they've all
1188 // been used and arguably OK if they're not.
1189 if !p
.reordered
&& argNum
< len(a
) {
1190 p
.buf
.Write(extraBytes
)
1191 for ; argNum
< len(a
); argNum
++ {
1194 p
.buf
.WriteString(reflect
.TypeOf(arg
).String())
1195 p
.buf
.WriteByte('=')
1197 p
.printArg(arg
, 'v', 0)
1198 if argNum
+1 < len(a
) {
1199 p
.buf
.Write(commaSpaceBytes
)
1202 p
.buf
.WriteByte(')')
1206 func (p
*pp
) doPrint(a
[]interface{}, addspace
, addnewline
bool) {
1208 for argNum
:= 0; argNum
< len(a
); argNum
++ {
1210 // always add spaces if we're doing Println
1213 isString
:= arg
!= nil && reflect
.TypeOf(arg
).Kind() == reflect
.String
1214 if addspace ||
!isString
&& !prevString
{
1215 p
.buf
.WriteByte(' ')
1218 prevString
= p
.printArg(arg
, 'v', 0)
1221 p
.buf
.WriteByte('\n')