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 cache holds a set of reusable objects.
78 // The buffered channel holds the currently available objects.
79 // If more are needed, the cache creates them by calling new.
81 saved chan interface{}
82 new func() interface{}
85 func (c *cache) put(x interface{}) {
94 func (c *cache) get() interface{} {
97 return x // reused from cache
104 func newCache(f func() interface{}) *cache {
105 return &cache{make(chan interface{}, 100), f}
108 var ppFree = newCache(func() interface{} { return new(pp) })
110 // Allocate a new pp struct or grab a cached one.
111 func newPrinter() *pp {
112 p := ppFree.get().(*pp)
117 // Save used pp structs in ppFree; avoids an allocation per invocation.
118 func (p *pp) free() {
119 // Don't hold on to pp structs with large buffers.
120 if cap(p.buf.Bytes()) > 1024 {
127 func (p *pp) Width() (wid int, ok bool) { return p.fmt.wid, p.fmt.widPresent }
129 func (p *pp) Precision() (prec int, ok bool) { return p.fmt.prec, p.fmt.precPresent }
131 func (p *pp) Flag(b int) bool {
147 func (p *pp) add(c int) {
151 // Implement Write so we can call Fprintf on a pp (through State), for
152 // recursive use in custom verbs.
153 func (p *pp) Write(b []byte) (ret int, err os.Error) {
154 return p.buf.Write(b)
157 // These routines end in 'f' and take a format string.
159 // Fprintf formats according to a format specifier and writes to w.
160 // It returns the number of bytes written and any write error encountered.
161 func Fprintf(w io.Writer, format string, a ...interface{}) (n int, error os.Error) {
163 p.doPrintf(format, a)
164 n64, error := p.buf.WriteTo(w)
166 return int(n64), error
169 // Printf formats according to a format specifier and writes to standard output.
170 // It returns the number of bytes written and any write error encountered.
171 func Printf(format string, a ...interface{}) (n int, errno os.Error) {
172 n, errno = Fprintf(os.Stdout, format, a...)
176 // Sprintf formats according to a format specifier and returns the resulting string.
177 func Sprintf(format string, a ...interface{}) string {
179 p.doPrintf(format, a)
185 // Errorf formats according to a format specifier and returns the string
186 // converted to an os.ErrorString, which satisfies the os.Error interface.
187 func Errorf(format string, a ...interface{}) os.Error {
188 return os.ErrorString(Sprintf(format, a...))
191 // These routines do not take a format string
193 // Fprint formats using the default formats for its operands and writes to w.
194 // Spaces are added between operands when neither is a string.
195 // It returns the number of bytes written and any write error encountered.
196 func Fprint(w io.Writer, a ...interface{}) (n int, error os.Error) {
198 p.doPrint(a, false, false)
199 n64, error := p.buf.WriteTo(w)
201 return int(n64), error
204 // Print formats using the default formats for its operands and writes to standard output.
205 // Spaces are added between operands when neither is a string.
206 // It returns the number of bytes written and any write error encountered.
207 func Print(a ...interface{}) (n int, errno os.Error) {
208 n, errno = Fprint(os.Stdout, a...)
212 // Sprint formats using the default formats for its operands and returns the resulting string.
213 // Spaces are added between operands when neither is a string.
214 func Sprint(a ...interface{}) string {
216 p.doPrint(a, false, false)
222 // These routines end in 'ln', do not take a format string,
223 // always add spaces between operands, and add a newline
224 // after the last operand.
226 // Fprintln formats using the default formats for its operands and writes to w.
227 // Spaces are always added between operands and a newline is appended.
228 // It returns the number of bytes written and any write error encountered.
229 func Fprintln(w io.Writer, a ...interface{}) (n int, error os.Error) {
231 p.doPrint(a, true, true)
232 n64, error := p.buf.WriteTo(w)
234 return int(n64), error
237 // Println formats using the default formats for its operands and writes to standard output.
238 // Spaces are always added between operands and a newline is appended.
239 // It returns the number of bytes written and any write error encountered.
240 func Println(a ...interface{}) (n int, errno os.Error) {
241 n, errno = Fprintln(os.Stdout, a...)
245 // Sprintln formats using the default formats for its operands and returns the resulting string.
246 // Spaces are always added between operands and a newline is appended.
247 func Sprintln(a ...interface{}) string {
249 p.doPrint(a, true, true)
256 // Get the i'th arg of the struct value.
257 // If the arg itself is an interface, return a value for
258 // the thing inside the interface, not the interface itself.
259 func getField(v reflect.Value, i int) reflect.Value {
261 if i := val; i.Kind() == reflect.Interface {
262 if inter := i.Interface(); inter != nil {
263 return reflect.ValueOf(inter)
269 // Convert ASCII to integer. n is 0 (and got is false) if no number present.
270 func parsenum(s string, start, end int) (num int, isnum bool, newi int) {
274 for newi = start; newi < end && '0' <= s[newi] && s[newi] <= '9'; newi++ {
275 num = num*10 + int(s[newi]-'0')
281 func (p *pp) unknownType(v interface{}) {
283 p.buf.Write(nilAngleBytes)
287 p.buf.WriteString(reflect.TypeOf(v).String())
291 func (p *pp) badVerb(verb int, val interface{}) {
297 p.buf.Write(nilAngleBytes)
299 p.buf.WriteString(reflect.TypeOf(val).String())
301 p.printField(val, 'v', false, false, 0)
306 func (p *pp) fmtBool(v bool, verb int, value interface{}) {
311 p.badVerb(verb, value)
315 // fmtC formats a rune for the 'c' format.
316 func (p *pp) fmtC(c int64) {
317 rune := int(c) // Check for overflow.
318 if int64(rune) != c {
319 rune = utf8.RuneError
321 w := utf8.EncodeRune(p.runeBuf[0:utf8.UTFMax], rune)
322 p.fmt.pad(p.runeBuf[0:w])
325 func (p *pp) fmtInt64(v int64, verb int, value interface{}) {
328 p.fmt.integer(v, 2, signed, ldigits)
332 p.fmt.integer(v, 10, signed, ldigits)
334 p.fmt.integer(v, 8, signed, ldigits)
336 p.fmt.integer(v, 16, signed, ldigits)
340 p.fmt.integer(v, 16, signed, udigits)
342 p.badVerb(verb, value)
346 // fmt0x64 formats a uint64 in hexadecimal and prefixes it with 0x or
347 // not, as requested, by temporarily setting the sharp flag.
348 func (p *pp) fmt0x64(v uint64, leading0x bool) {
350 p.fmt.sharp = leading0x
351 p.fmt.integer(int64(v), 16, unsigned, ldigits)
355 // fmtUnicode formats a uint64 in U+1234 form by
356 // temporarily turning on the unicode flag and tweaking the precision.
357 func (p *pp) fmtUnicode(v int64) {
358 precPresent := p.fmt.precPresent
361 // If prec is already set, leave it alone; otherwise 4 is minimum.
363 p.fmt.precPresent = true
365 p.fmt.unicode = true // turn on U+
366 p.fmt.integer(int64(v), 16, unsigned, udigits)
367 p.fmt.unicode = false
369 p.fmt.precPresent = precPresent
372 func (p *pp) fmtUint64(v uint64, verb int, goSyntax bool, value interface{}) {
375 p.fmt.integer(int64(v), 2, unsigned, ldigits)
379 p.fmt.integer(int64(v), 10, unsigned, ldigits)
384 p.fmt.integer(int64(v), 10, unsigned, ldigits)
387 p.fmt.integer(int64(v), 8, unsigned, ldigits)
389 p.fmt.integer(int64(v), 16, unsigned, ldigits)
391 p.fmt.integer(int64(v), 16, unsigned, udigits)
393 p.fmtUnicode(int64(v))
395 p.badVerb(verb, value)
399 func (p *pp) fmtFloat32(v float32, verb int, value interface{}) {
414 p.badVerb(verb, value)
418 func (p *pp) fmtFloat64(v float64, verb int, value interface{}) {
433 p.badVerb(verb, value)
437 func (p *pp) fmtComplex64(v complex64, verb int, value interface{}) {
439 case 'e', 'E', 'f', 'F', 'g', 'G':
440 p.fmt.fmt_c64(v, verb)
442 p.fmt.fmt_c64(v, 'g')
444 p.badVerb(verb, value)
448 func (p *pp) fmtComplex128(v complex128, verb int, value interface{}) {
450 case 'e', 'E', 'f', 'F', 'g', 'G':
451 p.fmt.fmt_c128(v, verb)
453 p.fmt.fmt_c128(v, 'g')
455 p.badVerb(verb, value)
459 func (p *pp) fmtString(v string, verb int, goSyntax bool, value interface{}) {
476 p.badVerb(verb, value)
480 func (p *pp) fmtBytes(v []byte, verb int, goSyntax bool, depth int, value interface{}) {
481 if verb == 'v' || verb == 'd' {
483 p.buf.Write(bytesBytes)
487 for i, c := range v {
490 p.buf.Write(commaSpaceBytes)
495 p.printField(c, 'v', p.fmt.plus, goSyntax, depth+1)
515 p.badVerb(verb, value)
519 func (p *pp) fmtPointer(field interface{}, value reflect.Value, verb int, goSyntax bool) {
521 switch value.Kind() {
522 case reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr, reflect.Slice, reflect.UnsafePointer:
525 p.badVerb(verb, field)
530 p.buf.WriteString(reflect.TypeOf(field).String())
534 p.buf.Write(nilBytes)
536 p.fmt0x64(uint64(u), true)
540 p.fmt0x64(uint64(u), !p.fmt.sharp)
545 intBits = reflect.TypeOf(0).Bits()
546 floatBits = reflect.TypeOf(0.0).Bits()
547 complexBits = reflect.TypeOf(1i).Bits()
548 uintptrBits = reflect.TypeOf(uintptr(0)).Bits()
551 func (p *pp) printField(field interface{}, verb int, plus, goSyntax bool, depth int) (wasString bool) {
553 if verb == 'T' || verb == 'v' {
554 p.buf.Write(nilAngleBytes)
556 p.badVerb(verb, field)
561 // Special processing considerations.
562 // %T (the value's type) and %p (its address) are special; we always do them first.
565 p.printField(reflect.TypeOf(field).String(), 's', false, false, 0)
568 p.fmtPointer(field, reflect.ValueOf(field), verb, goSyntax)
571 // Is it a Formatter?
572 if formatter, ok := field.(Formatter); ok {
573 formatter.Format(p, verb)
574 return false // this value is not a string
577 // Must not touch flags before Formatter looks at them.
581 // If we're doing Go syntax and the field knows how to supply it, take care of it now.
584 if stringer, ok := field.(GoStringer); ok {
585 // Print the result of GoString unadorned.
586 p.fmtString(stringer.GoString(), 's', false, field)
587 return false // this value is not a string
591 if stringer, ok := field.(Stringer); ok {
592 p.printField(stringer.String(), verb, plus, false, depth)
593 return false // this value is not a string
597 // Some types can be done without reflection.
598 switch f := field.(type) {
600 p.fmtBool(f, verb, field)
603 p.fmtFloat32(f, verb, field)
606 p.fmtFloat64(f, verb, field)
609 p.fmtComplex64(complex64(f), verb, field)
612 p.fmtComplex128(f, verb, field)
615 p.fmtInt64(int64(f), verb, field)
618 p.fmtInt64(int64(f), verb, field)
621 p.fmtInt64(int64(f), verb, field)
624 p.fmtInt64(int64(f), verb, field)
627 p.fmtInt64(f, verb, field)
630 p.fmtUint64(uint64(f), verb, goSyntax, field)
633 p.fmtUint64(uint64(f), verb, goSyntax, field)
636 p.fmtUint64(uint64(f), verb, goSyntax, field)
639 p.fmtUint64(uint64(f), verb, goSyntax, field)
642 p.fmtUint64(f, verb, goSyntax, field)
645 p.fmtUint64(uint64(f), verb, goSyntax, field)
648 p.fmtString(f, verb, goSyntax, field)
649 return verb == 's' || verb == 'v'
651 p.fmtBytes(f, verb, goSyntax, depth, field)
655 // Need to use reflection
656 value := reflect.ValueOf(field)
659 switch f := value; f.Kind() {
661 p.fmtBool(f.Bool(), verb, field)
662 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
663 p.fmtInt64(f.Int(), verb, field)
664 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
665 p.fmtUint64(uint64(f.Uint()), verb, goSyntax, field)
666 case reflect.Float32, reflect.Float64:
667 if f.Type().Size() == 4 {
668 p.fmtFloat32(float32(f.Float()), verb, field)
670 p.fmtFloat64(float64(f.Float()), verb, field)
672 case reflect.Complex64, reflect.Complex128:
673 if f.Type().Size() == 8 {
674 p.fmtComplex64(complex64(f.Complex()), verb, field)
676 p.fmtComplex128(complex128(f.Complex()), verb, field)
679 p.fmtString(f.String(), verb, goSyntax, field)
682 p.buf.WriteString(f.Type().String())
685 p.buf.Write(mapBytes)
688 for i, key := range keys {
691 p.buf.Write(commaSpaceBytes)
696 p.printField(key.Interface(), verb, plus, goSyntax, depth+1)
698 p.printField(f.MapIndex(key).Interface(), verb, plus, goSyntax, depth+1)
707 p.buf.WriteString(reflect.TypeOf(field).String())
712 for i := 0; i < v.NumField(); i++ {
715 p.buf.Write(commaSpaceBytes)
720 if plus || goSyntax {
721 if f := t.Field(i); f.Name != "" {
722 p.buf.WriteString(f.Name)
726 p.printField(getField(v, i).Interface(), verb, plus, goSyntax, depth+1)
729 case reflect.Interface:
731 if !value.IsValid() {
733 p.buf.WriteString(reflect.TypeOf(field).String())
734 p.buf.Write(nilParenBytes)
736 p.buf.Write(nilAngleBytes)
739 return p.printField(value.Interface(), verb, plus, goSyntax, depth+1)
741 case reflect.Array, reflect.Slice:
742 // Byte slices are special.
743 if f.Type().Elem().Kind() == reflect.Uint8 {
744 // We know it's a slice of bytes, but we also know it does not have static type
745 // []byte, or it would have been caught above. Therefore we cannot convert
746 // it directly in the (slightly) obvious way: f.Interface().([]byte); it doesn't have
747 // that type, and we can't write an expression of the right type and do a
748 // conversion because we don't have a static way to write the right type.
749 // So we build a slice by hand. This is a rare case but it would be nice
750 // if reflection could help a little more.
751 bytes := make([]byte, f.Len())
752 for i := range bytes {
753 bytes[i] = byte(f.Index(i).Uint())
755 p.fmtBytes(bytes, verb, goSyntax, depth, field)
759 p.buf.WriteString(reflect.TypeOf(field).String())
764 for i := 0; i < f.Len(); i++ {
767 p.buf.Write(commaSpaceBytes)
772 p.printField(f.Index(i).Interface(), verb, plus, goSyntax, depth+1)
781 // pointer to array or slice or struct? ok at top level
782 // but not embedded (avoid loops)
783 if v != 0 && depth == 0 {
784 switch a := f.Elem(); a.Kind() {
785 case reflect.Array, reflect.Slice:
787 p.printField(a.Interface(), verb, plus, goSyntax, depth+1)
791 p.printField(a.Interface(), verb, plus, goSyntax, depth+1)
797 p.buf.WriteString(reflect.TypeOf(field).String())
801 p.buf.Write(nilBytes)
803 p.fmt0x64(uint64(v), true)
809 p.buf.Write(nilAngleBytes)
812 p.fmt0x64(uint64(v), true)
813 case reflect.Chan, reflect.Func, reflect.UnsafePointer:
814 p.fmtPointer(field, value, verb, goSyntax)
821 // intFromArg gets the fieldnumth element of a. On return, isInt reports whether the argument has type int.
822 func intFromArg(a []interface{}, end, i, fieldnum int) (num int, isInt bool, newi, newfieldnum int) {
823 newi, newfieldnum = end, fieldnum
824 if i < end && fieldnum < len(a) {
825 num, isInt = a[fieldnum].(int)
826 newi, newfieldnum = i+1, fieldnum+1
831 func (p *pp) doPrintf(format string, a []interface{}) {
833 fieldnum := 0 // we process one field per non-trivial format
834 for i := 0; i < end; {
836 for i < end && format[i] != '%' {
840 p.buf.WriteString(format[lasti:i])
843 // done processing format string
869 if i < end && format[i] == '*' {
870 p.fmt.wid, p.fmt.widPresent, i, fieldnum = intFromArg(a, end, i, fieldnum)
871 if !p.fmt.widPresent {
872 p.buf.Write(widthBytes)
875 p.fmt.wid, p.fmt.widPresent, i = parsenum(format, i, end)
877 // do we have precision?
878 if i < end && format[i] == '.' {
879 if format[i+1] == '*' {
880 p.fmt.prec, p.fmt.precPresent, i, fieldnum = intFromArg(a, end, i+1, fieldnum)
881 if !p.fmt.precPresent {
882 p.buf.Write(precBytes)
885 p.fmt.prec, p.fmt.precPresent, i = parsenum(format, i+1, end)
889 p.buf.Write(noVerbBytes)
892 c, w := utf8.DecodeRuneInString(format[i:])
894 // percent is special - absorbs no operand
896 p.buf.WriteByte('%') // We ignore width and prec.
899 if fieldnum >= len(a) { // out of operands
902 p.buf.Write(missingBytes)
908 goSyntax := c == 'v' && p.fmt.sharp
909 plus := c == 'v' && p.fmt.plus
910 p.printField(field, c, plus, goSyntax, 0)
913 if fieldnum < len(a) {
914 p.buf.Write(extraBytes)
915 for ; fieldnum < len(a); fieldnum++ {
918 p.buf.WriteString(reflect.TypeOf(field).String())
921 p.printField(field, 'v', false, false, 0)
922 if fieldnum+1 < len(a) {
923 p.buf.Write(commaSpaceBytes)
930 func (p *pp) doPrint(a []interface{}, addspace, addnewline bool) {
932 for fieldnum := 0; fieldnum < len(a); fieldnum++ {
934 // always add spaces if we're doing println
937 isString := field != nil && reflect.TypeOf(field).Kind() == reflect.String
938 if addspace || !isString && !prevString {
942 prevString = p.printField(field, 'v', false, false, 0)
945 p.buf.WriteByte('\n')