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)")
31 // State represents the printer state passed to custom formatters.
32 // It provides access to the io.Writer interface plus information about
33 // the flags and options for the operand's format specifier.
34 type State interface {
35 // Write is the function to call to emit formatted output to be printed.
36 Write(b []byte) (ret int, err os.Error)
37 // Width returns the value of the width option and whether it has been set.
38 Width() (wid int, ok bool)
39 // Precision returns the value of the precision option and whether it has been set.
40 Precision() (prec int, ok bool)
42 // Flag returns whether the flag c, a character, has been set.
46 // Formatter is the interface implemented by values with a custom formatter.
47 // The implementation of Format may call Sprintf or Fprintf(f) etc.
48 // to generate its output.
49 type Formatter interface {
50 Format(f State, c int)
53 // Stringer is implemented by any value that has a String method(),
54 // which defines the ``native'' format for that value.
55 // The String method is used to print values passed as an operand
56 // to a %s or %v format or to an unformatted printer such as Print.
57 type Stringer interface {
61 // GoStringer is implemented by any value that has a GoString() method,
62 // which defines the Go syntax for that value.
63 // The GoString method is used to print values passed as an operand
65 type GoStringer interface {
72 runeBuf [utf8.UTFMax]byte
76 // A leaky bucket of reusable pp structures.
77 var ppFree = make(chan *pp, 100)
79 // Allocate a new pp struct. Probably can grab the previous one from ppFree.
80 func newPrinter() *pp {
89 // Save used pp structs in ppFree; avoids an allocation per invocation.
91 // Don't hold on to pp structs with large buffers.
92 if cap(p.buf.Bytes()) > 1024 {
99 func (p *pp) Width() (wid int, ok bool) { return p.fmt.wid, p.fmt.widPresent }
101 func (p *pp) Precision() (prec int, ok bool) { return p.fmt.prec, p.fmt.precPresent }
103 func (p *pp) Flag(b int) bool {
119 func (p *pp) add(c int) {
120 if c < utf8.RuneSelf {
121 p.buf.WriteByte(byte(c))
123 w := utf8.EncodeRune(c, p.runeBuf[0:])
124 p.buf.Write(p.runeBuf[0:w])
128 // Implement Write so we can call Fprintf on a pp (through State), for
129 // recursive use in custom verbs.
130 func (p *pp) Write(b []byte) (ret int, err os.Error) {
131 return p.buf.Write(b)
134 // These routines end in 'f' and take a format string.
136 // Fprintf formats according to a format specifier and writes to w.
137 // It returns the number of bytes written and any write error encountered.
138 func Fprintf(w io.Writer, format string, a ...interface{}) (n int, error os.Error) {
140 p.doPrintf(format, a)
141 n64, error := p.buf.WriteTo(w)
143 return int(n64), error
146 // Printf formats according to a format specifier and writes to standard output.
147 // It returns the number of bytes written and any write error encountered.
148 func Printf(format string, a ...interface{}) (n int, errno os.Error) {
149 n, errno = Fprintf(os.Stdout, format, a...)
153 // Sprintf formats according to a format specifier and returns the resulting string.
154 func Sprintf(format string, a ...interface{}) string {
156 p.doPrintf(format, a)
162 // Errorf formats according to a format specifier and returns the string
163 // converted to an os.ErrorString, which satisfies the os.Error interface.
164 func Errorf(format string, a ...interface{}) os.Error {
165 return os.ErrorString(Sprintf(format, a...))
168 // These routines do not take a format string
170 // Fprint formats using the default formats for its operands and writes to w.
171 // Spaces are added between operands when neither is a string.
172 // It returns the number of bytes written and any write error encountered.
173 func Fprint(w io.Writer, a ...interface{}) (n int, error os.Error) {
175 p.doPrint(a, false, false)
176 n64, error := p.buf.WriteTo(w)
178 return int(n64), error
181 // Print formats using the default formats for its operands and writes to standard output.
182 // Spaces are added between operands when neither is a string.
183 // It returns the number of bytes written and any write error encountered.
184 func Print(a ...interface{}) (n int, errno os.Error) {
185 n, errno = Fprint(os.Stdout, a...)
189 // Sprint formats using the default formats for its operands and returns the resulting string.
190 // Spaces are added between operands when neither is a string.
191 func Sprint(a ...interface{}) string {
193 p.doPrint(a, false, false)
199 // These routines end in 'ln', do not take a format string,
200 // always add spaces between operands, and add a newline
201 // after the last operand.
203 // Fprintln formats using the default formats for its operands and writes to w.
204 // Spaces are always added between operands and a newline is appended.
205 // It returns the number of bytes written and any write error encountered.
206 func Fprintln(w io.Writer, a ...interface{}) (n int, error os.Error) {
208 p.doPrint(a, true, true)
209 n64, error := p.buf.WriteTo(w)
211 return int(n64), error
214 // Println formats using the default formats for its operands and writes to standard output.
215 // Spaces are always added between operands and a newline is appended.
216 // It returns the number of bytes written and any write error encountered.
217 func Println(a ...interface{}) (n int, errno os.Error) {
218 n, errno = Fprintln(os.Stdout, a...)
222 // Sprintln formats using the default formats for its operands and returns the resulting string.
223 // Spaces are always added between operands and a newline is appended.
224 func Sprintln(a ...interface{}) string {
226 p.doPrint(a, true, true)
233 // Get the i'th arg of the struct value.
234 // If the arg itself is an interface, return a value for
235 // the thing inside the interface, not the interface itself.
236 func getField(v *reflect.StructValue, i int) reflect.Value {
238 if i, ok := val.(*reflect.InterfaceValue); ok {
239 if inter := i.Interface(); inter != nil {
240 return reflect.NewValue(inter)
246 // Convert ASCII to integer. n is 0 (and got is false) if no number present.
247 func parsenum(s string, start, end int) (num int, isnum bool, newi int) {
251 for newi = start; newi < end && '0' <= s[newi] && s[newi] <= '9'; newi++ {
252 num = num*10 + int(s[newi]-'0')
258 // Reflection values like reflect.FuncValue implement this method. We use it for %p.
259 type uintptrGetter interface {
263 func (p *pp) unknownType(v interface{}) {
265 p.buf.Write(nilAngleBytes)
269 p.buf.WriteString(reflect.Typeof(v).String())
273 func (p *pp) badVerb(verb int, val interface{}) {
279 p.buf.Write(nilAngleBytes)
281 p.buf.WriteString(reflect.Typeof(val).String())
283 p.printField(val, 'v', false, false, 0)
288 func (p *pp) fmtBool(v bool, verb int, value interface{}) {
293 p.badVerb(verb, value)
297 // fmtC formats a rune for the 'c' format.
298 func (p *pp) fmtC(c int64) {
299 rune := int(c) // Check for overflow.
300 if int64(rune) != c {
301 rune = utf8.RuneError
303 w := utf8.EncodeRune(rune, p.runeBuf[0:utf8.UTFMax])
304 p.fmt.pad(p.runeBuf[0:w])
307 func (p *pp) fmtInt64(v int64, verb int, value interface{}) {
310 p.fmt.integer(v, 2, signed, ldigits)
314 p.fmt.integer(v, 10, signed, ldigits)
316 p.fmt.integer(v, 8, signed, ldigits)
318 p.fmt.integer(v, 16, signed, ldigits)
320 p.fmt.integer(v, 16, signed, udigits)
322 p.badVerb(verb, value)
326 // fmt_sharpHex64 formats a uint64 in hexadecimal and prefixes it with 0x by
327 // temporarily turning on the sharp flag.
328 func (p *pp) fmt0x64(v uint64) {
330 p.fmt.sharp = true // turn on 0x
331 p.fmt.integer(int64(v), 16, unsigned, ldigits)
335 func (p *pp) fmtUint64(v uint64, verb int, goSyntax bool, value interface{}) {
338 p.fmt.integer(int64(v), 2, unsigned, ldigits)
342 p.fmt.integer(int64(v), 10, unsigned, ldigits)
347 p.fmt.integer(int64(v), 10, unsigned, ldigits)
350 p.fmt.integer(int64(v), 8, unsigned, ldigits)
352 p.fmt.integer(int64(v), 16, unsigned, ldigits)
354 p.fmt.integer(int64(v), 16, unsigned, udigits)
356 p.badVerb(verb, value)
360 func (p *pp) fmtFloat32(v float32, verb int, value interface{}) {
375 p.badVerb(verb, value)
379 func (p *pp) fmtFloat64(v float64, verb int, value interface{}) {
394 p.badVerb(verb, value)
398 func (p *pp) fmtComplex64(v complex64, verb int, value interface{}) {
400 case 'e', 'E', 'f', 'F', 'g', 'G':
401 p.fmt.fmt_c64(v, verb)
403 p.fmt.fmt_c64(v, 'g')
405 p.badVerb(verb, value)
409 func (p *pp) fmtComplex128(v complex128, verb int, value interface{}) {
411 case 'e', 'E', 'f', 'F', 'g', 'G':
412 p.fmt.fmt_c128(v, verb)
414 p.fmt.fmt_c128(v, 'g')
416 p.badVerb(verb, value)
420 func (p *pp) fmtString(v string, verb int, goSyntax bool, value interface{}) {
437 p.badVerb(verb, value)
441 func (p *pp) fmtBytes(v []byte, verb int, goSyntax bool, depth int, value interface{}) {
442 if verb == 'v' || verb == 'd' {
444 p.buf.Write(bytesBytes)
448 for i, c := range v {
451 p.buf.Write(commaSpaceBytes)
456 p.printField(c, 'v', p.fmt.plus, goSyntax, depth+1)
476 p.badVerb(verb, value)
480 func (p *pp) fmtPointer(field interface{}, value reflect.Value, verb int, goSyntax bool) {
481 v, ok := value.(uintptrGetter)
482 if !ok { // reflect.PtrValue is a uintptrGetter, so failure means it's not a pointer at all.
483 p.badVerb(verb, field)
489 p.buf.WriteString(reflect.Typeof(field).String())
493 p.buf.Write(nilBytes)
495 p.fmt0x64(uint64(v.Get()))
504 intBits = reflect.Typeof(0).Bits()
505 floatBits = reflect.Typeof(0.0).Bits()
506 complexBits = reflect.Typeof(1i).Bits()
507 uintptrBits = reflect.Typeof(uintptr(0)).Bits()
510 func (p *pp) printField(field interface{}, verb int, plus, goSyntax bool, depth int) (wasString bool) {
512 if verb == 'T' || verb == 'v' {
513 p.buf.Write(nilAngleBytes)
515 p.badVerb(verb, field)
520 // Special processing considerations.
521 // %T (the value's type) and %p (its address) are special; we always do them first.
524 p.printField(reflect.Typeof(field).String(), 's', false, false, 0)
527 p.fmtPointer(field, reflect.NewValue(field), verb, goSyntax)
530 // Is it a Formatter?
531 if formatter, ok := field.(Formatter); ok {
532 formatter.Format(p, verb)
533 return false // this value is not a string
536 // Must not touch flags before Formatter looks at them.
540 // If we're doing Go syntax and the field knows how to supply it, take care of it now.
543 if stringer, ok := field.(GoStringer); ok {
544 // Print the result of GoString unadorned.
545 p.fmtString(stringer.GoString(), 's', false, field)
546 return false // this value is not a string
550 if stringer, ok := field.(Stringer); ok {
551 p.printField(stringer.String(), verb, plus, false, depth)
552 return false // this value is not a string
556 // Some types can be done without reflection.
557 switch f := field.(type) {
559 p.fmtBool(f, verb, field)
563 p.fmtFloat32(float32(f), verb, field)
565 p.fmtFloat64(float64(f), verb, field)
569 p.fmtFloat32(f, verb, field)
572 p.fmtFloat64(f, verb, field)
575 if complexBits == 64 {
576 p.fmtComplex64(complex64(f), verb, field)
578 p.fmtComplex128(complex128(f), verb, field)
582 p.fmtComplex64(complex64(f), verb, field)
585 p.fmtComplex128(f, verb, field)
588 p.fmtInt64(int64(f), verb, field)
591 p.fmtInt64(int64(f), verb, field)
594 p.fmtInt64(int64(f), verb, field)
597 p.fmtInt64(int64(f), verb, field)
600 p.fmtInt64(f, verb, field)
603 p.fmtUint64(uint64(f), verb, goSyntax, field)
606 p.fmtUint64(uint64(f), verb, goSyntax, field)
609 p.fmtUint64(uint64(f), verb, goSyntax, field)
612 p.fmtUint64(uint64(f), verb, goSyntax, field)
615 p.fmtUint64(f, verb, goSyntax, field)
618 p.fmtUint64(uint64(f), verb, goSyntax, field)
621 p.fmtString(f, verb, goSyntax, field)
622 return verb == 's' || verb == 'v'
624 p.fmtBytes(f, verb, goSyntax, depth, field)
628 // Need to use reflection
629 value := reflect.NewValue(field)
632 switch f := value.(type) {
633 case *reflect.BoolValue:
634 p.fmtBool(f.Get(), verb, field)
635 case *reflect.IntValue:
636 p.fmtInt64(f.Get(), verb, field)
637 case *reflect.UintValue:
638 p.fmtUint64(uint64(f.Get()), verb, goSyntax, field)
639 case *reflect.FloatValue:
640 if f.Type().Size() == 4 {
641 p.fmtFloat32(float32(f.Get()), verb, field)
643 p.fmtFloat64(float64(f.Get()), verb, field)
645 case *reflect.ComplexValue:
646 if f.Type().Size() == 8 {
647 p.fmtComplex64(complex64(f.Get()), verb, field)
649 p.fmtComplex128(complex128(f.Get()), verb, field)
651 case *reflect.StringValue:
652 p.fmtString(f.Get(), verb, goSyntax, field)
653 case *reflect.MapValue:
655 p.buf.WriteString(f.Type().String())
658 p.buf.Write(mapBytes)
661 for i, key := range keys {
664 p.buf.Write(commaSpaceBytes)
669 p.printField(key.Interface(), verb, plus, goSyntax, depth+1)
671 p.printField(f.Elem(key).Interface(), verb, plus, goSyntax, depth+1)
678 case *reflect.StructValue:
680 p.buf.WriteString(reflect.Typeof(field).String())
684 t := v.Type().(*reflect.StructType)
685 for i := 0; i < v.NumField(); i++ {
688 p.buf.Write(commaSpaceBytes)
693 if plus || goSyntax {
694 if f := t.Field(i); f.Name != "" {
695 p.buf.WriteString(f.Name)
699 p.printField(getField(v, i).Interface(), verb, plus, goSyntax, depth+1)
702 case *reflect.InterfaceValue:
706 p.buf.WriteString(reflect.Typeof(field).String())
707 p.buf.Write(nilParenBytes)
709 p.buf.Write(nilAngleBytes)
712 return p.printField(value.Interface(), verb, plus, goSyntax, depth+1)
714 case reflect.ArrayOrSliceValue:
715 // Byte slices are special.
716 if f.Type().(reflect.ArrayOrSliceType).Elem().Kind() == reflect.Uint8 {
717 // We know it's a slice of bytes, but we also know it does not have static type
718 // []byte, or it would have been caught above. Therefore we cannot convert
719 // it directly in the (slightly) obvious way: f.Interface().([]byte); it doesn't have
720 // that type, and we can't write an expression of the right type and do a
721 // conversion because we don't have a static way to write the right type.
722 // So we build a slice by hand. This is a rare case but it would be nice
723 // if reflection could help a little more.
724 bytes := make([]byte, f.Len())
725 for i := range bytes {
726 bytes[i] = byte(f.Elem(i).(*reflect.UintValue).Get())
728 p.fmtBytes(bytes, verb, goSyntax, depth, field)
732 p.buf.WriteString(reflect.Typeof(field).String())
737 for i := 0; i < f.Len(); i++ {
740 p.buf.Write(commaSpaceBytes)
745 p.printField(f.Elem(i).Interface(), verb, plus, goSyntax, depth+1)
752 case *reflect.PtrValue:
754 // pointer to array or slice or struct? ok at top level
755 // but not embedded (avoid loops)
756 if v != 0 && depth == 0 {
757 switch a := f.Elem().(type) {
758 case reflect.ArrayOrSliceValue:
760 p.printField(a.Interface(), verb, plus, goSyntax, depth+1)
762 case *reflect.StructValue:
764 p.printField(a.Interface(), verb, plus, goSyntax, depth+1)
770 p.buf.WriteString(reflect.Typeof(field).String())
774 p.buf.Write(nilBytes)
782 p.buf.Write(nilAngleBytes)
787 p.fmtPointer(field, value, verb, goSyntax)
794 // intFromArg gets the fieldnumth element of a. On return, isInt reports whether the argument has type int.
795 func intFromArg(a []interface{}, end, i, fieldnum int) (num int, isInt bool, newi, newfieldnum int) {
796 newi, newfieldnum = end, fieldnum
797 if i < end && fieldnum < len(a) {
798 num, isInt = a[fieldnum].(int)
799 newi, newfieldnum = i+1, fieldnum+1
804 func (p *pp) doPrintf(format string, a []interface{}) {
805 end := len(format) - 1
806 fieldnum := 0 // we process one field per non-trivial format
807 for i := 0; i <= end; {
808 c, w := utf8.DecodeRuneInString(format[i:])
809 if c != '%' || i == end {
811 p.buf.WriteByte(byte(c))
813 p.buf.WriteString(format[i : i+w])
839 if format[i] == '*' {
840 p.fmt.wid, p.fmt.widPresent, i, fieldnum = intFromArg(a, end, i, fieldnum)
841 if !p.fmt.widPresent {
842 p.buf.Write(widthBytes)
845 p.fmt.wid, p.fmt.widPresent, i = parsenum(format, i, end)
847 // do we have precision?
848 if i < end && format[i] == '.' {
849 if format[i+1] == '*' {
850 p.fmt.prec, p.fmt.precPresent, i, fieldnum = intFromArg(a, end, i+1, fieldnum)
851 if !p.fmt.precPresent {
852 p.buf.Write(precBytes)
855 p.fmt.prec, p.fmt.precPresent, i = parsenum(format, i+1, end)
858 c, w = utf8.DecodeRuneInString(format[i:])
860 // percent is special - absorbs no operand
862 p.buf.WriteByte('%') // We ignore width and prec.
865 if fieldnum >= len(a) { // out of operands
868 p.buf.Write(missingBytes)
874 goSyntax := c == 'v' && p.fmt.sharp
875 plus := c == 'v' && p.fmt.plus
876 p.printField(field, c, plus, goSyntax, 0)
879 if fieldnum < len(a) {
880 p.buf.Write(extraBytes)
881 for ; fieldnum < len(a); fieldnum++ {
884 p.buf.WriteString(reflect.Typeof(field).String())
887 p.printField(field, 'v', false, false, 0)
888 if fieldnum+1 < len(a) {
889 p.buf.Write(commaSpaceBytes)
896 func (p *pp) doPrint(a []interface{}, addspace, addnewline bool) {
898 for fieldnum := 0; fieldnum < len(a); fieldnum++ {
900 // always add spaces if we're doing println
903 isString := field != nil && reflect.Typeof(field).Kind() == reflect.String
904 if addspace || !isString && !prevString {
908 prevString = p.printField(field, 'v', false, false, 0)
911 p.buf.WriteByte('\n')