common.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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. "sort"
  22. "strconv"
  23. "unsafe"
  24. )
  25. // reflectValue mirrors the struct layout of the reflect package Value type.
  26. var reflectValue struct {
  27. typ unsafe.Pointer
  28. val unsafe.Pointer
  29. flag uintptr
  30. }
  31. // flagIndir indicates whether the value field of a reflect.Value is the actual
  32. // data or a pointer to the data.
  33. const flagIndir = 1 << 1
  34. // unsafeReflectValue converts the passed reflect.Value into a one that bypasses
  35. // the typical safety restrictions preventing access to unaddressable and
  36. // unexported data. It works by digging the raw pointer to the underlying
  37. // value out of the protected value and generating a new unprotected (unsafe)
  38. // reflect.Value to it.
  39. //
  40. // This allows us to check for implementations of the Stringer and error
  41. // interfaces to be used for pretty printing ordinarily unaddressable and
  42. // inaccessible values such as unexported struct fields.
  43. func unsafeReflectValue(v reflect.Value) (rv reflect.Value) {
  44. indirects := 1
  45. vt := v.Type()
  46. upv := unsafe.Pointer(uintptr(unsafe.Pointer(&v)) + unsafe.Offsetof(reflectValue.val))
  47. rvf := *(*uintptr)(unsafe.Pointer(uintptr(unsafe.Pointer(&v)) + unsafe.Offsetof(reflectValue.flag)))
  48. if rvf&flagIndir != 0 {
  49. vt = reflect.PtrTo(v.Type())
  50. indirects++
  51. }
  52. pv := reflect.NewAt(vt, upv)
  53. rv = pv
  54. for i := 0; i < indirects; i++ {
  55. rv = rv.Elem()
  56. }
  57. return rv
  58. }
  59. // Some constants in the form of bytes to avoid string overhead. This mirrors
  60. // the technique used in the fmt package.
  61. var (
  62. panicBytes = []byte("(PANIC=")
  63. plusBytes = []byte("+")
  64. iBytes = []byte("i")
  65. trueBytes = []byte("true")
  66. falseBytes = []byte("false")
  67. interfaceBytes = []byte("(interface {})")
  68. commaNewlineBytes = []byte(",\n")
  69. newlineBytes = []byte("\n")
  70. openBraceBytes = []byte("{")
  71. openBraceNewlineBytes = []byte("{\n")
  72. closeBraceBytes = []byte("}")
  73. asteriskBytes = []byte("*")
  74. colonBytes = []byte(":")
  75. colonSpaceBytes = []byte(": ")
  76. openParenBytes = []byte("(")
  77. closeParenBytes = []byte(")")
  78. spaceBytes = []byte(" ")
  79. pointerChainBytes = []byte("->")
  80. nilAngleBytes = []byte("<nil>")
  81. maxNewlineBytes = []byte("<max depth reached>\n")
  82. maxShortBytes = []byte("<max>")
  83. circularBytes = []byte("<already shown>")
  84. circularShortBytes = []byte("<shown>")
  85. invalidAngleBytes = []byte("<invalid>")
  86. openBracketBytes = []byte("[")
  87. closeBracketBytes = []byte("]")
  88. percentBytes = []byte("%")
  89. precisionBytes = []byte(".")
  90. openAngleBytes = []byte("<")
  91. closeAngleBytes = []byte(">")
  92. openMapBytes = []byte("map[")
  93. closeMapBytes = []byte("]")
  94. )
  95. // hexDigits is used to map a decimal value to a hex digit.
  96. var hexDigits = "0123456789abcdef"
  97. // catchPanic handles any panics that might occur during the handleMethods
  98. // calls.
  99. func catchPanic(w io.Writer, v reflect.Value) {
  100. if err := recover(); err != nil {
  101. w.Write(panicBytes)
  102. fmt.Fprintf(w, "%v", err)
  103. w.Write(closeParenBytes)
  104. }
  105. }
  106. // handleMethods attempts to call the Error and String methods on the underlying
  107. // type the passed reflect.Value represents and outputes the result to Writer w.
  108. //
  109. // It handles panics in any called methods by catching and displaying the error
  110. // as the formatted value.
  111. func handleMethods(cs *ConfigState, w io.Writer, v reflect.Value) (handled bool) {
  112. // We need an interface to check if the type implements the error or
  113. // Stringer interface. However, the reflect package won't give us an
  114. // interface on certain things like unexported struct fields in order
  115. // to enforce visibility rules. We use unsafe to bypass these restrictions
  116. // since this package does not mutate the values.
  117. if !v.CanInterface() {
  118. v = unsafeReflectValue(v)
  119. }
  120. // Choose whether or not to do error and Stringer interface lookups against
  121. // the base type or a pointer to the base type depending on settings.
  122. // Technically calling one of these methods with a pointer receiver can
  123. // mutate the value, however, types which choose to satisify an error or
  124. // Stringer interface with a pointer receiver should not be mutating their
  125. // state inside these interface methods.
  126. var viface interface{}
  127. if !cs.DisablePointerMethods {
  128. if !v.CanAddr() {
  129. v = unsafeReflectValue(v)
  130. }
  131. viface = v.Addr().Interface()
  132. } else {
  133. if v.CanAddr() {
  134. v = v.Addr()
  135. }
  136. viface = v.Interface()
  137. }
  138. // Is it an error or Stringer?
  139. switch iface := viface.(type) {
  140. case error:
  141. defer catchPanic(w, v)
  142. if cs.ContinueOnMethod {
  143. w.Write(openParenBytes)
  144. w.Write([]byte(iface.Error()))
  145. w.Write(closeParenBytes)
  146. w.Write(spaceBytes)
  147. return false
  148. }
  149. w.Write([]byte(iface.Error()))
  150. return true
  151. case fmt.Stringer:
  152. defer catchPanic(w, v)
  153. if cs.ContinueOnMethod {
  154. w.Write(openParenBytes)
  155. w.Write([]byte(iface.String()))
  156. w.Write(closeParenBytes)
  157. w.Write(spaceBytes)
  158. return false
  159. }
  160. w.Write([]byte(iface.String()))
  161. return true
  162. }
  163. return false
  164. }
  165. // printBool outputs a boolean value as true or false to Writer w.
  166. func printBool(w io.Writer, val bool) {
  167. if val {
  168. w.Write(trueBytes)
  169. } else {
  170. w.Write(falseBytes)
  171. }
  172. }
  173. // printInt outputs a signed integer value to Writer w.
  174. func printInt(w io.Writer, val int64, base int) {
  175. w.Write([]byte(strconv.FormatInt(val, base)))
  176. }
  177. // printUint outputs an unsigned integer value to Writer w.
  178. func printUint(w io.Writer, val uint64, base int) {
  179. w.Write([]byte(strconv.FormatUint(val, base)))
  180. }
  181. // printFloat outputs a floating point value using the specified precision,
  182. // which is expected to be 32 or 64bit, to Writer w.
  183. func printFloat(w io.Writer, val float64, precision int) {
  184. w.Write([]byte(strconv.FormatFloat(val, 'g', -1, precision)))
  185. }
  186. // printComplex outputs a complex value using the specified float precision
  187. // for the real and imaginary parts to Writer w.
  188. func printComplex(w io.Writer, c complex128, floatPrecision int) {
  189. r := real(c)
  190. w.Write(openParenBytes)
  191. w.Write([]byte(strconv.FormatFloat(r, 'g', -1, floatPrecision)))
  192. i := imag(c)
  193. if i >= 0 {
  194. w.Write(plusBytes)
  195. }
  196. w.Write([]byte(strconv.FormatFloat(i, 'g', -1, floatPrecision)))
  197. w.Write(iBytes)
  198. w.Write(closeParenBytes)
  199. }
  200. // printHexPtr outputs a uintptr formatted as hexidecimal with a leading '0x'
  201. // prefix to Writer w.
  202. func printHexPtr(w io.Writer, p uintptr) {
  203. // Null pointer.
  204. num := uint64(p)
  205. if num == 0 {
  206. w.Write(nilAngleBytes)
  207. return
  208. }
  209. // Max uint64 is 16 bytes in hex + 2 bytes for '0x' prefix
  210. buf := make([]byte, 18)
  211. // It's simpler to construct the hex string right to left.
  212. base := uint64(16)
  213. i := len(buf) - 1
  214. for num >= base {
  215. buf[i] = hexDigits[num%base]
  216. num /= base
  217. i--
  218. }
  219. buf[i] = hexDigits[num]
  220. // Add '0x' prefix.
  221. i--
  222. buf[i] = 'x'
  223. i--
  224. buf[i] = '0'
  225. // Strip unused leading bytes.
  226. buf = buf[i:]
  227. w.Write(buf)
  228. }
  229. // valuesSorter implements sort.Interface to allow a slice of reflect.Value
  230. // elements to be sorted.
  231. type valuesSorter struct {
  232. values []reflect.Value
  233. }
  234. // Len returns the number of values in the slice. It is part of the
  235. // sort.Interface implementation.
  236. func (s *valuesSorter) Len() int {
  237. return len(s.values)
  238. }
  239. // Swap swaps the values at the passed indices. It is part of the
  240. // sort.Interface implementation.
  241. func (s *valuesSorter) Swap(i, j int) {
  242. s.values[i], s.values[j] = s.values[j], s.values[i]
  243. }
  244. // Less returns whether the value at index i should sort before the
  245. // value at index j. It is part of the sort.Interface implementation.
  246. func (s *valuesSorter) Less(i, j int) bool {
  247. switch s.values[i].Kind() {
  248. case reflect.Bool:
  249. return !s.values[i].Bool() && s.values[j].Bool()
  250. case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int:
  251. return s.values[i].Int() < s.values[j].Int()
  252. case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint:
  253. return s.values[i].Uint() < s.values[j].Uint()
  254. case reflect.Float32, reflect.Float64:
  255. return s.values[i].Float() < s.values[j].Float()
  256. case reflect.String:
  257. return s.values[i].String() < s.values[j].String()
  258. case reflect.Uintptr:
  259. return s.values[i].UnsafeAddr() < s.values[j].UnsafeAddr()
  260. }
  261. return s.values[i].String() < s.values[j].String()
  262. }
  263. // sortValues is a generic sort function for native types: int, uint, bool,
  264. // string and uintptr. Other inputs are sorted according to their
  265. // Value.String() value to ensure display stability.
  266. func sortValues(values []reflect.Value) {
  267. if len(values) == 0 {
  268. return
  269. }
  270. sort.Sort(&valuesSorter{values})
  271. }