common.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  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. // 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. if v.CanAddr() {
  133. v = v.Addr()
  134. }
  135. viface = v.Interface()
  136. }
  137. // Is it an error or Stringer?
  138. switch iface := viface.(type) {
  139. case error:
  140. defer catchPanic(w, v)
  141. if cs.ContinueOnMethod {
  142. w.Write(openParenBytes)
  143. w.Write([]byte(iface.Error()))
  144. w.Write(closeParenBytes)
  145. w.Write(spaceBytes)
  146. return false
  147. }
  148. w.Write([]byte(iface.Error()))
  149. return true
  150. case fmt.Stringer:
  151. defer catchPanic(w, v)
  152. if cs.ContinueOnMethod {
  153. w.Write(openParenBytes)
  154. w.Write([]byte(iface.String()))
  155. w.Write(closeParenBytes)
  156. w.Write(spaceBytes)
  157. return false
  158. }
  159. w.Write([]byte(iface.String()))
  160. return true
  161. }
  162. return false
  163. }
  164. // printBool outputs a boolean value as true or false to Writer w.
  165. func printBool(w io.Writer, val bool) {
  166. if val {
  167. w.Write(trueBytes)
  168. } else {
  169. w.Write(falseBytes)
  170. }
  171. }
  172. // printInt outputs a signed integer value to Writer w.
  173. func printInt(w io.Writer, val int64, base int) {
  174. w.Write([]byte(strconv.FormatInt(val, base)))
  175. }
  176. // printUint outputs an unsigned integer value to Writer w.
  177. func printUint(w io.Writer, val uint64, base int) {
  178. w.Write([]byte(strconv.FormatUint(val, base)))
  179. }
  180. // printFloat outputs a floating point value using the specified precision,
  181. // which is expected to be 32 or 64bit, to Writer w.
  182. func printFloat(w io.Writer, val float64, precision int) {
  183. w.Write([]byte(strconv.FormatFloat(val, 'g', -1, precision)))
  184. }
  185. // printComplex outputs a complex value using the specified float precision
  186. // for the real and imaginary parts to Writer w.
  187. func printComplex(w io.Writer, c complex128, floatPrecision int) {
  188. r := real(c)
  189. w.Write(openParenBytes)
  190. w.Write([]byte(strconv.FormatFloat(r, 'g', -1, floatPrecision)))
  191. i := imag(c)
  192. if i >= 0 {
  193. w.Write(plusBytes)
  194. }
  195. w.Write([]byte(strconv.FormatFloat(i, 'g', -1, floatPrecision)))
  196. w.Write(iBytes)
  197. w.Write(closeParenBytes)
  198. }
  199. // printHexPtr outputs a uintptr formatted as hexidecimal with a leading '0x'
  200. // prefix to Writer w.
  201. func printHexPtr(w io.Writer, p uintptr) {
  202. // Null pointer.
  203. num := uint64(p)
  204. if num == 0 {
  205. w.Write(nilAngleBytes)
  206. return
  207. }
  208. // Max uint64 is 16 bytes in hex + 2 bytes for '0x' prefix
  209. buf := make([]byte, 18)
  210. // It's simpler to construct the hex string right to left.
  211. base := uint64(16)
  212. i := len(buf) - 1
  213. for num >= base {
  214. buf[i] = hexDigits[num%base]
  215. num /= base
  216. i--
  217. }
  218. buf[i] = hexDigits[num]
  219. // Add '0x' prefix.
  220. i--
  221. buf[i] = 'x'
  222. i--
  223. buf[i] = '0'
  224. // Strip unused leading bytes.
  225. buf = buf[i:]
  226. w.Write(buf)
  227. }