common.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  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. closeBraceNewlinBytes = []byte("}\n")
  73. asteriskBytes = []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. percentBytes = []byte("%")
  86. precisionBytes = []byte(".")
  87. openAngleBytes = []byte("<")
  88. closeAngleBytes = []byte(">")
  89. openMapBytes = []byte("map[")
  90. closeMapBytes = []byte("]")
  91. )
  92. // hexDigits is used to map a decimal value to a hex digit.
  93. var hexDigits = "0123456789abcdef"
  94. // unpackValue returns values inside of non-nil inteferfaces when possible.
  95. // This is useful for data types like structs, arrays, slices, and maps which
  96. // can contain varying types packed inside an interface.
  97. func unpackValue(v reflect.Value) reflect.Value {
  98. if v.Kind() == reflect.Interface && !v.IsNil() {
  99. v = v.Elem()
  100. }
  101. return v
  102. }
  103. // catchPanic handles any panics that might occur during the handleMethods
  104. // calls.
  105. func catchPanic(w io.Writer, v reflect.Value) {
  106. if err := recover(); err != nil {
  107. w.Write(panicBytes)
  108. fmt.Fprintf(w, "%v", err)
  109. w.Write(closeParenBytes)
  110. }
  111. }
  112. // handleMethods attempts to call the Error and String methods on the underlying
  113. // type the passed reflect.Value represents and outputes the result to Writer w.
  114. //
  115. // It handles panics in any called methods by catching and displaying the error
  116. // as the formatted value.
  117. func handleMethods(cs *ConfigState, w io.Writer, v reflect.Value) (handled bool) {
  118. // We need an interface to check if the type implements the error or
  119. // Stringer interface. However, the reflect package won't give us an
  120. // an interface on certain things like unexported struct fields in order
  121. // to enforce visibility rules. We use unsafe to bypass these restrictions
  122. // since this package does not mutate the values.
  123. if !v.CanInterface() {
  124. v = unsafeReflectValue(v)
  125. }
  126. // Choose whether or not to do error and Stringer interface lookups against
  127. // the base type or a pointer to the base type depending on settings.
  128. // Technically calling one of these methods with a pointer receiver can
  129. // mutate the value, however, types which choose to satisify an error or
  130. // Stringer interface with a pointer receiver should not be mutating their
  131. // state inside these interface methods.
  132. var viface interface{}
  133. if !cs.DisablePointerMethods {
  134. if !v.CanAddr() {
  135. v = unsafeReflectValue(v)
  136. }
  137. viface = v.Addr().Interface()
  138. } else {
  139. viface = v.Interface()
  140. }
  141. // Is it an error or Stringer?
  142. switch iface := viface.(type) {
  143. case error:
  144. defer catchPanic(w, v)
  145. w.Write([]byte(iface.Error()))
  146. return true
  147. case fmt.Stringer:
  148. defer catchPanic(w, v)
  149. w.Write([]byte(iface.String()))
  150. return true
  151. }
  152. return false
  153. }
  154. // printBool outputs a boolean value as true or false to Writer w.
  155. func printBool(w io.Writer, val bool) {
  156. if val {
  157. w.Write(trueBytes)
  158. } else {
  159. w.Write(falseBytes)
  160. }
  161. }
  162. // printInt outputs a signed integer value to Writer w.
  163. func printInt(w io.Writer, val int64) {
  164. w.Write([]byte(strconv.FormatInt(val, 10)))
  165. }
  166. // printUint outputs an unsigned integer value to Writer w.
  167. func printUint(w io.Writer, val uint64) {
  168. w.Write([]byte(strconv.FormatUint(val, 10)))
  169. }
  170. // printFloat outputs a floating point value using the specified precision,
  171. // which is expected to be 32 or 64bit, to Writer w.
  172. func printFloat(w io.Writer, val float64, precision int) {
  173. w.Write([]byte(strconv.FormatFloat(val, 'g', -1, precision)))
  174. }
  175. // printComplex outputs a complex value using the specified float precision
  176. // for the real and imaginary parts to Writer w.
  177. func printComplex(w io.Writer, c complex128, floatPrecision int) {
  178. r := real(c)
  179. w.Write(openParenBytes)
  180. w.Write([]byte(strconv.FormatFloat(r, 'g', -1, floatPrecision)))
  181. i := imag(c)
  182. if i >= 0 {
  183. w.Write(plusBytes)
  184. }
  185. w.Write([]byte(strconv.FormatFloat(i, 'g', -1, floatPrecision)))
  186. w.Write(iBytes)
  187. w.Write(closeParenBytes)
  188. }
  189. // printHexPtr outputs a uintptr formatted as hexidecimal with a leading '0x'
  190. // prefix to Writer w.
  191. func printHexPtr(w io.Writer, p uintptr) {
  192. // Null pointer.
  193. num := uint64(p)
  194. if num == 0 {
  195. w.Write(nilAngleBytes)
  196. return
  197. }
  198. // Max uint64 is 16 bytes in hex + 2 bytes for '0x' prefix
  199. buf := make([]byte, 18)
  200. // It's simpler to construct the hex string right to left.
  201. base := uint64(16)
  202. i := len(buf) - 1
  203. for num >= base {
  204. buf[i] = hexDigits[num%base]
  205. num /= base
  206. i--
  207. }
  208. buf[i] = hexDigits[num]
  209. // Add '0x' prefix.
  210. i--
  211. buf[i] = 'x'
  212. i--
  213. buf[i] = '0'
  214. // Strip unused leading bytes.
  215. buf = buf[i:]
  216. w.Write(buf)
  217. }