Debian Codegraph @

internal/spew/common.go

raw
1 /*
2 * Copyright (c) 2013-2016 Dave Collins <[email protected]>
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
17 package spew
18
19 import (
20 "fmt"
21 "io"
22 "reflect"
23 "strconv"
24 )
25
26 // Some constants in the form of bytes to avoid string overhead. This mirrors
27 // the technique used in the fmt package.
28 var (
29 panicBytes = []byte("(PANIC=")
30 plusBytes = []byte("+")
31 iBytes = []byte("i")
32 trueBytes = []byte("true")
33 falseBytes = []byte("false")
34 interfaceBytes = []byte("(interface {})")
35 commaNewlineBytes = []byte(",\n")
36 newlineBytes = []byte("\n")
37 openBraceNewlineBytes = []byte("{\n")
38 closeBraceBytes = []byte("}")
39 asteriskBytes = []byte("*")
40 colonSpaceBytes = []byte(": ")
41 openParenBytes = []byte("(")
42 closeParenBytes = []byte(")")
43 spaceBytes = []byte(" ")
44 pointerChainBytes = []byte("->")
45 nilAngleBytes = []byte("<nil>")
46 maxNewlineBytes = []byte("<max depth reached>\n")
47 circularBytes = []byte("<already shown>")
48 invalidAngleBytes = []byte("<invalid>")
49 lenEqualsBytes = []byte("len=")
50 capEqualsBytes = []byte("cap=")
51 )
52
53 // hexDigits is used to map a decimal value to a hex digit.
54 var hexDigits = "0123456789abcdef"
55
56 // catchPanic handles any panics that might occur during the handleMethods
57 // calls.
58 func catchPanic(w io.Writer) {
59 if err := recover(); err != nil {
60 w.Write(panicBytes) //nolint: errcheck
61 fmt.Fprintf(w, "%v", err) //nolint: errcheck
62 w.Write(closeParenBytes) //nolint: errcheck
63 }
64 }
65
66 // handleMethods attempts to call the Error and String methods on the underlying
67 // type the passed reflect.Value represents and outputes the result to Writer w.
68 //
69 // It handles panics in any called methods by catching and displaying the error
70 // as the formatted value.
71 func handleMethods(cs *ConfigState, w io.Writer, v reflect.Value) (handled bool) {
72 // We need an interface to check if the type implements the error or
73 // fmt.Stringer interface. However, the reflect package won't give us an
74 // interface on certain things like unexported struct fields in order
75 // to enforce visibility rules. We use unsafe, when it's available,
76 // to bypass these restrictions since this package does not mutate the
77 // values.
78 if !v.CanInterface() {
79 if UnsafeDisabled {
80 return false
81 }
82
83 v = UnsafeReflectValue(v)
84 }
85
86 // Choose whether or not to do error and fmt.Stringer interface
87 // lookups against the base type or a pointer to the base type
88 // depending on settings. Technically calling one of these methods
89 // with a pointer receiver can mutate the value, however, types
90 // which choose to satisify an error or fmt.Stringer interface with
91 // a pointer receiver should not be mutating their state inside
92 // these interface methods.
93 if !cs.DisablePointerMethods && !UnsafeDisabled && !v.CanAddr() {
94 v = UnsafeReflectValue(v)
95 }
96 if v.CanAddr() {
97 v = v.Addr()
98 }
99
100 // Is it an error or fmt.Stringer?
101 switch iface := v.Interface().(type) {
102 case error:
103 defer catchPanic(w)
104 w.Write([]byte(iface.Error())) //nolint: errcheck
105 return true
106
107 case fmt.Stringer:
108 defer catchPanic(w)
109 w.Write([]byte(iface.String())) //nolint: errcheck
110 return true
111 }
112 return false
113 }
114
115 // printBool outputs a boolean value as true or false to Writer w.
116 // nolint: errcheck
117 func printBool(w io.Writer, val bool) {
118 if val {
119 w.Write(trueBytes)
120 } else {
121 w.Write(falseBytes)
122 }
123 }
124
125 // printInt outputs a signed integer value to Writer w.
126 // nolint: errcheck
127 func printInt(w io.Writer, val int64, base int) {
128 w.Write([]byte(strconv.FormatInt(val, base)))
129 }
130
131 // printUint outputs an unsigned integer value to Writer w.
132 // nolint: errcheck
133 func printUint(w io.Writer, val uint64, base int) {
134 w.Write([]byte(strconv.FormatUint(val, base)))
135 }
136
137 // printFloat outputs a floating point value using the specified precision,
138 // which is expected to be 32 or 64bit, to Writer w.
139 // nolint: errcheck
140 func printFloat(w io.Writer, val float64, precision int) {
141 w.Write([]byte(strconv.FormatFloat(val, 'g', -1, precision)))
142 }
143
144 // printComplex outputs a complex value using the specified float precision
145 // for the real and imaginary parts to Writer w.
146 // nolint: errcheck
147 func printComplex(w io.Writer, c complex128, floatPrecision int) {
148 r := real(c)
149 w.Write(openParenBytes)
150 w.Write([]byte(strconv.FormatFloat(r, 'g', -1, floatPrecision)))
151 i := imag(c)
152 if i >= 0 {
153 w.Write(plusBytes) //nolint: errcheck
154 }
155 w.Write([]byte(strconv.FormatFloat(i, 'g', -1, floatPrecision)))
156 w.Write(iBytes)
157 w.Write(closeParenBytes)
158 }
159
160 // printHexPtr outputs a uintptr formatted as hexadecimal with a leading '0x'
161 // prefix to Writer w.
162 // nolint: errcheck
163 func printHexPtr(w io.Writer, p uintptr) {
164 // Null pointer.
165 num := uint64(p)
166 if num == 0 {
167 w.Write(nilAngleBytes)
168 return
169 }
170
171 // Max uint64 is 16 bytes in hex + 2 bytes for '0x' prefix
172 buf := make([]byte, 18)
173
174 // It's simpler to construct the hex string right to left.
175 base := uint64(16)
176 i := len(buf) - 1
177 for num >= base {
178 buf[i] = hexDigits[num%base]
179 num /= base
180 i--
181 }
182 buf[i] = hexDigits[num]
183
184 // Add '0x' prefix.
185 i--
186 buf[i] = 'x'
187 i--
188 buf[i] = '0'
189
190 // Strip unused leading bytes.
191 buf = buf[i:]
192 w.Write(buf)
193 }