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.
15 // Some constants in the form of bytes, to avoid string overhead.
16 // Needlessly fastidious, I suppose.
18 commaSpaceBytes = []byte(", ")
19 nilAngleBytes = []byte("<nil>")
20 nilParenBytes = []byte("(nil)")
21 nilBytes = []byte("nil")
22 mapBytes = []byte("map[")
23 missingBytes = []byte("(MISSING)")
24 extraBytes = []byte("%!(EXTRA ")
25 irparenBytes = []byte("i)")
26 bytesBytes = []byte("[]byte{")
27 widthBytes = []byte("%!(BADWIDTH)")
28 precBytes = []byte("%!(BADPREC)")
29 noVerbBytes = []byte("%!(NOVERB)")
32 // State represents the printer state passed to custom formatters.
33 // It provides access to the io.Writer interface plus information about
34 // the flags and options for the operand's format specifier.
35 type State interface {
36 // Write is the function to call to emit formatted output to be printed.
37 Write(b []byte) (ret int, err os.Error)
38 // Width returns the value of the width option and whether it has been set.
39 Width() (wid int, ok bool)
40 // Precision returns the value of the precision option and whether it has been set.
41 Precision() (prec int, ok bool)
43 // Flag returns whether the flag c, a character, has been set.
47 // Formatter is the interface implemented by values with a custom formatter.
48 // The implementation of Format may call Sprintf or Fprintf(f) etc.
49 // to generate its output.
50 type Formatter interface {
51 Format(f State, c int)
54 // Stringer is implemented by any value that has a String method(),
55 // which defines the ``native'' format for that value.
56 // The String method is used to print values passed as an operand
57 // to a %s or %v format or to an unformatted printer such as Print.
58 type Stringer interface {
62 // GoStringer is implemented by any value that has a GoString() method,
63 // which defines the Go syntax for that value.
64 // The GoString method is used to print values passed as an operand
66 type GoStringer interface {
73 runeBuf [utf8.UTFMax]byte
77 // A leaky bucket of reusable pp structures.
78 var ppFree = make(chan *pp, 100)
80 // Allocate a new pp struct. Probably can grab the previous one from ppFree.
81 func newPrinter() *pp {
90 // Save used pp structs in ppFree; avoids an allocation per invocation.
92 // Don't hold on to pp structs with large buffers.
93 if cap(p.buf.Bytes()) > 1024 {
100 func (p *pp) Width() (wid int, ok bool) { return p.fmt.wid, p.fmt.widPresent }
102 func (p *pp) Precision() (prec int, ok bool) { return p.fmt.prec, p.fmt.precPresent }
104 func (p *pp) Flag(b int) bool {
120 func (p *pp) add(c int) {
124 // Implement Write so we can call Fprintf on a pp (through State), for
125 // recursive use in custom verbs.
126 func (p *pp) Write(b []byte) (ret int, err os.Error) {
127 return p.buf.Write(b)
130 // These routines end in 'f' and take a format string.
132 // Fprintf formats according to a format specifier and writes to w.
133 // It returns the number of bytes written and any write error encountered.
134 func Fprintf(w io.Writer, format string, a ...interface{}) (n int, error os.Error) {
136 p.doPrintf(format, a)
137 n64, error := p.buf.WriteTo(w)
139 return int(n64), error
142 // Printf formats according to a format specifier and writes to standard output.
143 // It returns the number of bytes written and any write error encountered.
144 func Printf(format string, a ...interface{}) (n int, errno os.Error) {
145 n, errno = Fprintf(os.Stdout, format, a...)
149 // Sprintf formats according to a format specifier and returns the resulting string.
150 func Sprintf(format string, a ...interface{}) string {
152 p.doPrintf(format, a)
158 // Errorf formats according to a format specifier and returns the string
159 // converted to an os.ErrorString, which satisfies the os.Error interface.
160 func Errorf(format string, a ...interface{}) os.Error {
161 return os.ErrorString(Sprintf(format, a...))
164 // These routines do not take a format string
166 // Fprint formats using the default formats for its operands and writes to w.
167 // Spaces are added between operands when neither is a string.
168 // It returns the number of bytes written and any write error encountered.
169 func Fprint(w io.Writer, a ...interface{}) (n int, error os.Error) {
171 p.doPrint(a, false, false)
172 n64, error := p.buf.WriteTo(w)
174 return int(n64), error
177 // Print formats using the default formats for its operands and writes to standard output.
178 // Spaces are added between operands when neither is a string.
179 // It returns the number of bytes written and any write error encountered.
180 func Print(a ...interface{}) (n int, errno os.Error) {
181 n, errno = Fprint(os.Stdout, a...)
185 // Sprint formats using the default formats for its operands and returns the resulting string.
186 // Spaces are added between operands when neither is a string.
187 func Sprint(a ...interface{}) string {
189 p.doPrint(a, false, false)
195 // These routines end in 'ln', do not take a format string,
196 // always add spaces between operands, and add a newline
197 // after the last operand.
199 // Fprintln formats using the default formats for its operands and writes to w.
200 // Spaces are always added between operands and a newline is appended.
201 // It returns the number of bytes written and any write error encountered.
202 func Fprintln(w io.Writer, a ...interface{}) (n int, error os.Error) {
204 p.doPrint(a, true, true)
205 n64, error := p.buf.WriteTo(w)
207 return int(n64), error
210 // Println formats using the default formats for its operands and writes to standard output.
211 // Spaces are always added between operands and a newline is appended.
212 // It returns the number of bytes written and any write error encountered.
213 func Println(a ...interface{}) (n int, errno os.Error) {
214 n, errno = Fprintln(os.Stdout, a...)
218 // Sprintln formats using the default formats for its operands and returns the resulting string.
219 // Spaces are always added between operands and a newline is appended.
220 func Sprintln(a ...interface{}) string {
222 p.doPrint(a, true, true)
229 // Get the i'th arg of the struct value.
230 // If the arg itself is an interface, return a value for
231 // the thing inside the interface, not the interface itself.
232 func getField(v *reflect.StructValue, i int) reflect.Value {
234 if i, ok := val.(*reflect.InterfaceValue); ok {
235 if inter := i.Interface(); inter != nil {
236 return reflect.NewValue(inter)
242 // Convert ASCII to integer. n is 0 (and got is false) if no number present.
243 func parsenum(s string, start, end int) (num int, isnum bool, newi int) {
247 for newi = start; newi < end && '0' <= s[newi] && s[newi] <= '9'; newi++ {
248 num = num*10 + int(s[newi]-'0')
254 // Reflection values like reflect.FuncValue implement this method. We use it for %p.
255 type uintptrGetter interface {
259 func (p *pp) unknownType(v interface{}) {
261 p.buf.Write(nilAngleBytes)
265 p.buf.WriteString(reflect.Typeof(v).String())
269 func (p *pp) badVerb(verb int, val interface{}) {
275 p.buf.Write(nilAngleBytes)
277 p.buf.WriteString(reflect.Typeof(val).String())
279 p.printField(val, 'v', false, false, 0)
284 func (p *pp) fmtBool(v bool, verb int, value interface{}) {
289 p.badVerb(verb, value)
293 // fmtC formats a rune for the 'c' format.
294 func (p *pp) fmtC(c int64) {
295 rune := int(c) // Check for overflow.
296 if int64(rune) != c {
297 rune = utf8.RuneError
299 w := utf8.EncodeRune(p.runeBuf[0:utf8.UTFMax], rune)
300 p.fmt.pad(p.runeBuf[0:w])
303 func (p *pp) fmtInt64(v int64, verb int, value interface{}) {
306 p.fmt.integer(v, 2, signed, ldigits)
310 p.fmt.integer(v, 10, signed, ldigits)
312 p.fmt.integer(v, 8, signed, ldigits)
314 p.fmt.integer(v, 16, signed, ldigits)
318 p.fmt.integer(v, 16, signed, udigits)
320 p.badVerb(verb, value)
324 // fmt0x64 formats a uint64 in hexadecimal and prefixes it with 0x by
325 // temporarily turning on the sharp flag.
326 func (p *pp) fmt0x64(v uint64) {
328 p.fmt.sharp = true // turn on 0x
329 p.fmt.integer(int64(v), 16, unsigned, ldigits)
333 // fmtUnicode formats a uint64 in U+1234 form by
334 // temporarily turning on the unicode flag and tweaking the precision.
335 func (p *pp) fmtUnicode(v int64) {
336 precPresent := p.fmt.precPresent
339 // If prec is already set, leave it alone; otherwise 4 is minimum.
341 p.fmt.precPresent = true
343 p.fmt.unicode = true // turn on U+
344 p.fmt.integer(int64(v), 16, unsigned, udigits)
345 p.fmt.unicode = false
347 p.fmt.precPresent = precPresent
350 func (p *pp) fmtUint64(v uint64, verb int, goSyntax bool, value interface{}) {
353 p.fmt.integer(int64(v), 2, unsigned, ldigits)
357 p.fmt.integer(int64(v), 10, unsigned, ldigits)
362 p.fmt.integer(int64(v), 10, unsigned, ldigits)
365 p.fmt.integer(int64(v), 8, unsigned, ldigits)
367 p.fmt.integer(int64(v), 16, unsigned, ldigits)
369 p.fmt.integer(int64(v), 16, unsigned, udigits)
371 p.badVerb(verb, value)
375 func (p *pp) fmtFloat32(v float32, verb int, value interface{}) {
390 p.badVerb(verb, value)
394 func (p *pp) fmtFloat64(v float64, verb int, value interface{}) {
409 p.badVerb(verb, value)
413 func (p *pp) fmtComplex64(v complex64, verb int, value interface{}) {
415 case 'e', 'E', 'f', 'F', 'g', 'G':
416 p.fmt.fmt_c64(v, verb)
418 p.fmt.fmt_c64(v, 'g')
420 p.badVerb(verb, value)
424 func (p *pp) fmtComplex128(v complex128, verb int, value interface{}) {
426 case 'e', 'E', 'f', 'F', 'g', 'G':
427 p.fmt.fmt_c128(v, verb)
429 p.fmt.fmt_c128(v, 'g')
431 p.badVerb(verb, value)
435 func (p *pp) fmtString(v string, verb int, goSyntax bool, value interface{}) {
452 p.badVerb(verb, value)
456 func (p *pp) fmtBytes(v []byte, verb int, goSyntax bool, depth int, value interface{}) {
457 if verb == 'v' || verb == 'd' {
459 p.buf.Write(bytesBytes)
463 for i, c := range v {
466 p.buf.Write(commaSpaceBytes)
471 p.printField(c, 'v', p.fmt.plus, goSyntax, depth+1)
491 p.badVerb(verb, value)
495 func (p *pp) fmtPointer(field interface{}, value reflect.Value, verb int, goSyntax bool) {
496 v, ok := value.(uintptrGetter)
497 if !ok { // reflect.PtrValue is a uintptrGetter, so failure means it's not a pointer at all.
498 p.badVerb(verb, field)
504 p.buf.WriteString(reflect.Typeof(field).String())
508 p.buf.Write(nilBytes)
510 p.fmt0x64(uint64(v.Get()))
519 intBits = reflect.Typeof(0).Bits()
520 floatBits = reflect.Typeof(0.0).Bits()
521 complexBits = reflect.Typeof(1i).Bits()
522 uintptrBits = reflect.Typeof(uintptr(0)).Bits()
525 func (p *pp) printField(field interface{}, verb int, plus, goSyntax bool, depth int) (wasString bool) {
527 if verb == 'T' || verb == 'v' {
528 p.buf.Write(nilAngleBytes)
530 p.badVerb(verb, field)
535 // Special processing considerations.
536 // %T (the value's type) and %p (its address) are special; we always do them first.
539 p.printField(reflect.Typeof(field).String(), 's', false, false, 0)
542 p.fmtPointer(field, reflect.NewValue(field), verb, goSyntax)
545 // Is it a Formatter?
546 if formatter, ok := field.(Formatter); ok {
547 formatter.Format(p, verb)
548 return false // this value is not a string
551 // Must not touch flags before Formatter looks at them.
555 // If we're doing Go syntax and the field knows how to supply it, take care of it now.
558 if stringer, ok := field.(GoStringer); ok {
559 // Print the result of GoString unadorned.
560 p.fmtString(stringer.GoString(), 's', false, field)
561 return false // this value is not a string
565 if stringer, ok := field.(Stringer); ok {
566 p.printField(stringer.String(), verb, plus, false, depth)
567 return false // this value is not a string
571 // Some types can be done without reflection.
572 switch f := field.(type) {
574 p.fmtBool(f, verb, field)
577 p.fmtFloat32(f, verb, field)
580 p.fmtFloat64(f, verb, field)
583 p.fmtComplex64(complex64(f), verb, field)
586 p.fmtComplex128(f, verb, field)
589 p.fmtInt64(int64(f), verb, field)
592 p.fmtInt64(int64(f), verb, field)
595 p.fmtInt64(int64(f), verb, field)
598 p.fmtInt64(int64(f), verb, field)
601 p.fmtInt64(f, verb, field)
604 p.fmtUint64(uint64(f), verb, goSyntax, field)
607 p.fmtUint64(uint64(f), verb, goSyntax, field)
610 p.fmtUint64(uint64(f), verb, goSyntax, field)
613 p.fmtUint64(uint64(f), verb, goSyntax, field)
616 p.fmtUint64(f, verb, goSyntax, field)
619 p.fmtUint64(uint64(f), verb, goSyntax, field)
622 p.fmtString(f, verb, goSyntax, field)
623 return verb == 's' || verb == 'v'
625 p.fmtBytes(f, verb, goSyntax, depth, field)
629 // Need to use reflection
630 value := reflect.NewValue(field)
633 switch f := value.(type) {
634 case *reflect.BoolValue:
635 p.fmtBool(f.Get(), verb, field)
636 case *reflect.IntValue:
637 p.fmtInt64(f.Get(), verb, field)
638 case *reflect.UintValue:
639 p.fmtUint64(uint64(f.Get()), verb, goSyntax, field)
640 case *reflect.FloatValue:
641 if f.Type().Size() == 4 {
642 p.fmtFloat32(float32(f.Get()), verb, field)
644 p.fmtFloat64(float64(f.Get()), verb, field)
646 case *reflect.ComplexValue:
647 if f.Type().Size() == 8 {
648 p.fmtComplex64(complex64(f.Get()), verb, field)
650 p.fmtComplex128(complex128(f.Get()), verb, field)
652 case *reflect.StringValue:
653 p.fmtString(f.Get(), verb, goSyntax, field)
654 case *reflect.MapValue:
656 p.buf.WriteString(f.Type().String())
659 p.buf.Write(mapBytes)
662 for i, key := range keys {
665 p.buf.Write(commaSpaceBytes)
670 p.printField(key.Interface(), verb, plus, goSyntax, depth+1)
672 p.printField(f.Elem(key).Interface(), verb, plus, goSyntax, depth+1)
679 case *reflect.StructValue:
681 p.buf.WriteString(reflect.Typeof(field).String())
685 t := v.Type().(*reflect.StructType)
686 for i := 0; i < v.NumField(); i++ {
689 p.buf.Write(commaSpaceBytes)
694 if plus || goSyntax {
695 if f := t.Field(i); f.Name != "" {
696 p.buf.WriteString(f.Name)
700 p.printField(getField(v, i).Interface(), verb, plus, goSyntax, depth+1)
703 case *reflect.InterfaceValue:
707 p.buf.WriteString(reflect.Typeof(field).String())
708 p.buf.Write(nilParenBytes)
710 p.buf.Write(nilAngleBytes)
713 return p.printField(value.Interface(), verb, plus, goSyntax, depth+1)
715 case reflect.ArrayOrSliceValue:
716 // Byte slices are special.
717 if f.Type().(reflect.ArrayOrSliceType).Elem().Kind() == reflect.Uint8 {
718 // We know it's a slice of bytes, but we also know it does not have static type
719 // []byte, or it would have been caught above. Therefore we cannot convert
720 // it directly in the (slightly) obvious way: f.Interface().([]byte); it doesn't have
721 // that type, and we can't write an expression of the right type and do a
722 // conversion because we don't have a static way to write the right type.
723 // So we build a slice by hand. This is a rare case but it would be nice
724 // if reflection could help a little more.
725 bytes := make([]byte, f.Len())
726 for i := range bytes {
727 bytes[i] = byte(f.Elem(i).(*reflect.UintValue).Get())
729 p.fmtBytes(bytes, verb, goSyntax, depth, field)
733 p.buf.WriteString(reflect.Typeof(field).String())
738 for i := 0; i < f.Len(); i++ {
741 p.buf.Write(commaSpaceBytes)
746 p.printField(f.Elem(i).Interface(), verb, plus, goSyntax, depth+1)
753 case *reflect.PtrValue:
755 // pointer to array or slice or struct? ok at top level
756 // but not embedded (avoid loops)
757 if v != 0 && depth == 0 {
758 switch a := f.Elem().(type) {
759 case reflect.ArrayOrSliceValue:
761 p.printField(a.Interface(), verb, plus, goSyntax, depth+1)
763 case *reflect.StructValue:
765 p.printField(a.Interface(), verb, plus, goSyntax, depth+1)
771 p.buf.WriteString(reflect.Typeof(field).String())
775 p.buf.Write(nilBytes)
783 p.buf.Write(nilAngleBytes)
788 p.fmtPointer(field, value, verb, goSyntax)
795 // intFromArg gets the fieldnumth element of a. On return, isInt reports whether the argument has type int.
796 func intFromArg(a []interface{}, end, i, fieldnum int) (num int, isInt bool, newi, newfieldnum int) {
797 newi, newfieldnum = end, fieldnum
798 if i < end && fieldnum < len(a) {
799 num, isInt = a[fieldnum].(int)
800 newi, newfieldnum = i+1, fieldnum+1
805 func (p *pp) doPrintf(format string, a []interface{}) {
807 fieldnum := 0 // we process one field per non-trivial format
808 for i := 0; i < end; {
810 for i < end && format[i] != '%' {
814 p.buf.WriteString(format[lasti:i])
817 // done processing format string
843 if i < end && format[i] == '*' {
844 p.fmt.wid, p.fmt.widPresent, i, fieldnum = intFromArg(a, end, i, fieldnum)
845 if !p.fmt.widPresent {
846 p.buf.Write(widthBytes)
849 p.fmt.wid, p.fmt.widPresent, i = parsenum(format, i, end)
851 // do we have precision?
852 if i < end && format[i] == '.' {
853 if format[i+1] == '*' {
854 p.fmt.prec, p.fmt.precPresent, i, fieldnum = intFromArg(a, end, i+1, fieldnum)
855 if !p.fmt.precPresent {
856 p.buf.Write(precBytes)
859 p.fmt.prec, p.fmt.precPresent, i = parsenum(format, i+1, end)
863 p.buf.Write(noVerbBytes)
866 c, w := utf8.DecodeRuneInString(format[i:])
868 // percent is special - absorbs no operand
870 p.buf.WriteByte('%') // We ignore width and prec.
873 if fieldnum >= len(a) { // out of operands
876 p.buf.Write(missingBytes)
882 goSyntax := c == 'v' && p.fmt.sharp
883 plus := c == 'v' && p.fmt.plus
884 p.printField(field, c, plus, goSyntax, 0)
887 if fieldnum < len(a) {
888 p.buf.Write(extraBytes)
889 for ; fieldnum < len(a); fieldnum++ {
892 p.buf.WriteString(reflect.Typeof(field).String())
895 p.printField(field, 'v', false, false, 0)
896 if fieldnum+1 < len(a) {
897 p.buf.Write(commaSpaceBytes)
904 func (p *pp) doPrint(a []interface{}, addspace, addnewline bool) {
906 for fieldnum := 0; fieldnum < len(a); fieldnum++ {
908 // always add spaces if we're doing println
911 isString := field != nil && reflect.Typeof(field).Kind() == reflect.String
912 if addspace || !isString && !prevString {
916 prevString = p.printField(field, 'v', false, false, 0)
919 p.buf.WriteByte('\n')