common.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. /*
  2. * Copyright (c) 2013 Dave Collins <dave@davec.name>
  3. *
  4. * Permission to use, copy, modify, and distribute this software for any
  5. * purpose with or without fee is hereby granted, provided that the above
  6. * copyright notice and this permission notice appear in all copies.
  7. *
  8. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  9. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  10. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  11. * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  12. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  13. * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  14. * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  15. */
  16. package spew
  17. import (
  18. "fmt"
  19. "io"
  20. "reflect"
  21. "strconv"
  22. "unsafe"
  23. )
  24. // reflectValue mirrors the struct layout of the reflect package Value type.
  25. var reflectValue struct {
  26. typ unsafe.Pointer
  27. val unsafe.Pointer
  28. flag uintptr
  29. }
  30. // flagIndir indicates whether the value field of a reflect.Value is the actual
  31. // data or a pointer to the data.
  32. const flagIndir = 1 << 1
  33. // unsafeReflectValue converts the passed reflect.Value into a one that bypasses
  34. // the typical safety restrictions preventing access to unaddressable and
  35. // unexported data. It works by digging the raw pointer to the underlying
  36. // value out of the protected value and generating a new unprotected (unsafe)
  37. // reflect.Value to it.
  38. //
  39. // This allows us to check for implementations of the Stringer and error
  40. // interfaces to be used for pretty printing ordinarily unaddressable and
  41. // inaccessible values such as unexported struct fields.
  42. func unsafeReflectValue(v reflect.Value) (rv reflect.Value) {
  43. indirects := 1
  44. vt := v.Type()
  45. upv := unsafe.Pointer(uintptr(unsafe.Pointer(&v)) + unsafe.Offsetof(reflectValue.val))
  46. rvf := *(*uintptr)(unsafe.Pointer(uintptr(unsafe.Pointer(&v)) + unsafe.Offsetof(reflectValue.flag)))
  47. if rvf&flagIndir != 0 {
  48. vt = reflect.PtrTo(v.Type())
  49. indirects++
  50. }
  51. pv := reflect.NewAt(vt, upv)
  52. rv = pv
  53. for i := 0; i < indirects; i++ {
  54. rv = rv.Elem()
  55. }
  56. return rv
  57. }
  58. // Some constants in the form of bytes to avoid string overhead. This mirrors
  59. // the technique used in the fmt package.
  60. var (
  61. panicBytes = []byte("(PANIC=")
  62. plusBytes = []byte("+")
  63. iBytes = []byte("i")
  64. trueBytes = []byte("true")
  65. falseBytes = []byte("false")
  66. interfaceBytes = []byte("(interface {})")
  67. commaNewlineBytes = []byte(",\n")
  68. newlineBytes = []byte("\n")
  69. openBraceBytes = []byte("{")
  70. openBraceNewlineBytes = []byte("{\n")
  71. closeBraceBytes = []byte("}")
  72. asteriskBytes = []byte("*")
  73. colonBytes = []byte(":")
  74. colonSpaceBytes = []byte(": ")
  75. openParenBytes = []byte("(")
  76. closeParenBytes = []byte(")")
  77. spaceBytes = []byte(" ")
  78. pointerChainBytes = []byte("->")
  79. nilAngleBytes = []byte("<nil>")
  80. maxNewlineBytes = []byte("<max depth reached>\n")
  81. maxShortBytes = []byte("<max>")
  82. circularBytes = []byte("<already shown>")
  83. circularShortBytes = []byte("<shown>")
  84. invalidAngleBytes = []byte("<invalid>")
  85. openBracketBytes = []byte("[")
  86. closeBracketBytes = []byte("]")
  87. percentBytes = []byte("%")
  88. precisionBytes = []byte(".")
  89. openAngleBytes = []byte("<")
  90. closeAngleBytes = []byte(">")
  91. openMapBytes = []byte("map[")
  92. closeMapBytes = []byte("]")
  93. )
  94. // hexDigits is used to map a decimal value to a hex digit.
  95. var hexDigits = "0123456789abcdef"
  96. // catchPanic handles any panics that might occur during the handleMethods
  97. // calls.
  98. func catchPanic(w io.Writer, v reflect.Value) {
  99. if err := recover(); err != nil {
  100. w.Write(panicBytes)
  101. fmt.Fprintf(w, "%v", err)
  102. w.Write(closeParenBytes)
  103. }
  104. }
  105. // handleMethods attempts to call the Error and String methods on the underlying
  106. // type the passed reflect.Value represents and outputes the result to Writer w.
  107. //
  108. // It handles panics in any called methods by catching and displaying the error
  109. // as the formatted value.
  110. func handleMethods(cs *ConfigState, w io.Writer, v reflect.Value) (handled bool) {
  111. // We need an interface to check if the type implements the error or
  112. // Stringer interface. However, the reflect package won't give us an
  113. // an interface on certain things like unexported struct fields in order
  114. // to enforce visibility rules. We use unsafe to bypass these restrictions
  115. // since this package does not mutate the values.
  116. if !v.CanInterface() {
  117. v = unsafeReflectValue(v)
  118. }
  119. // Choose whether or not to do error and Stringer interface lookups against
  120. // the base type or a pointer to the base type depending on settings.
  121. // Technically calling one of these methods with a pointer receiver can
  122. // mutate the value, however, types which choose to satisify an error or
  123. // Stringer interface with a pointer receiver should not be mutating their
  124. // state inside these interface methods.
  125. var viface interface{}
  126. if !cs.DisablePointerMethods {
  127. if !v.CanAddr() {
  128. v = unsafeReflectValue(v)
  129. }
  130. viface = v.Addr().Interface()
  131. } else {
  132. viface = v.Interface()
  133. }
  134. // Is it an error or Stringer?
  135. switch iface := viface.(type) {
  136. case error:
  137. defer catchPanic(w, v)
  138. w.Write([]byte(iface.Error()))
  139. return true
  140. case fmt.Stringer:
  141. defer catchPanic(w, v)
  142. w.Write([]byte(iface.String()))
  143. return true
  144. }
  145. return false
  146. }
  147. // printBool outputs a boolean value as true or false to Writer w.
  148. func printBool(w io.Writer, val bool) {
  149. if val {
  150. w.Write(trueBytes)
  151. } else {
  152. w.Write(falseBytes)
  153. }
  154. }
  155. // printInt outputs a signed integer value to Writer w.
  156. func printInt(w io.Writer, val int64) {
  157. w.Write([]byte(strconv.FormatInt(val, 10)))
  158. }
  159. // printUint outputs an unsigned integer value to Writer w.
  160. func printUint(w io.Writer, val uint64) {
  161. w.Write([]byte(strconv.FormatUint(val, 10)))
  162. }
  163. // printFloat outputs a floating point value using the specified precision,
  164. // which is expected to be 32 or 64bit, to Writer w.
  165. func printFloat(w io.Writer, val float64, precision int) {
  166. w.Write([]byte(strconv.FormatFloat(val, 'g', -1, precision)))
  167. }
  168. // printComplex outputs a complex value using the specified float precision
  169. // for the real and imaginary parts to Writer w.
  170. func printComplex(w io.Writer, c complex128, floatPrecision int) {
  171. r := real(c)
  172. w.Write(openParenBytes)
  173. w.Write([]byte(strconv.FormatFloat(r, 'g', -1, floatPrecision)))
  174. i := imag(c)
  175. if i >= 0 {
  176. w.Write(plusBytes)
  177. }
  178. w.Write([]byte(strconv.FormatFloat(i, 'g', -1, floatPrecision)))
  179. w.Write(iBytes)
  180. w.Write(closeParenBytes)
  181. }
  182. // printHexPtr outputs a uintptr formatted as hexidecimal with a leading '0x'
  183. // prefix to Writer w.
  184. func printHexPtr(w io.Writer, p uintptr) {
  185. // Null pointer.
  186. num := uint64(p)
  187. if num == 0 {
  188. w.Write(nilAngleBytes)
  189. return
  190. }
  191. // Max uint64 is 16 bytes in hex + 2 bytes for '0x' prefix
  192. buf := make([]byte, 18)
  193. // It's simpler to construct the hex string right to left.
  194. base := uint64(16)
  195. i := len(buf) - 1
  196. for num >= base {
  197. buf[i] = hexDigits[num%base]
  198. num /= base
  199. i--
  200. }
  201. buf[i] = hexDigits[num]
  202. // Add '0x' prefix.
  203. i--
  204. buf[i] = 'x'
  205. i--
  206. buf[i] = '0'
  207. // Strip unused leading bytes.
  208. buf = buf[i:]
  209. w.Write(buf)
  210. }