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