| 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 |
"bytes" |
| 21 |
"encoding/hex" |
| 22 |
"fmt" |
| 23 |
"io" |
| 24 |
"reflect" |
| 25 |
"strconv" |
| 26 |
"strings" |
| 27 |
|
| 28 |
"github.com/maxatome/go-testdeep/internal/sort" |
| 29 |
) |
| 30 |
|
| 31 |
var ( |
| 32 |
// uint8Type is a reflect.Type representing a uint8. It is used to |
| 33 |
// convert cgo types to uint8 slices for hexdumping. |
| 34 |
uint8Type = reflect.TypeOf(uint8(0)) |
| 35 |
|
| 36 |
// cCharSuffix is the suffix that matches a cgo char. |
| 37 |
// It is used to detect character arrays to hexdump them. |
| 38 |
cCharSuffix = `._Ctype_char` |
| 39 |
|
| 40 |
// cUnsignedCharSuffix is the suffix that matches a cgo unsigned |
| 41 |
// char. It is used to detect unsigned character arrays to hexdump |
| 42 |
// them. |
| 43 |
cUnsignedCharSuffix = `._Ctype_unsignedchar` |
| 44 |
|
| 45 |
// cUint8tCharSuffix is the suffix that matches a cgo uint8_t. |
| 46 |
// It is used to detect uint8_t arrays to hexdump them. |
| 47 |
cUint8tCharSuffix = `._Ctype_uint8_t` |
| 48 |
) |
| 49 |
|
| 50 |
// dumpState contains information about the state of a dump operation. |
| 51 |
type dumpState struct { |
| 52 |
w io.Writer |
| 53 |
depth int |
| 54 |
pointers map[uintptr]int |
| 55 |
ignoreNextType bool |
| 56 |
ignoreNextIndent bool |
| 57 |
cs *ConfigState |
| 58 |
} |
| 59 |
|
| 60 |
// indent performs indentation according to the depth level and cs.Indent |
| 61 |
// option. |
| 62 |
func (d *dumpState) indent() { |
| 63 |
if d.ignoreNextIndent { |
| 64 |
d.ignoreNextIndent = false |
| 65 |
return |
| 66 |
} |
| 67 |
d.w.Write(bytes.Repeat([]byte(d.cs.Indent), d.depth)) //nolint: errcheck |
| 68 |
} |
| 69 |
|
| 70 |
// unpackValue returns values inside of non-nil interfaces when possible. |
| 71 |
// This is useful for data types like structs, arrays, slices, and maps which |
| 72 |
// can contain varying types packed inside an interface. |
| 73 |
func (d *dumpState) unpackValue(v reflect.Value) reflect.Value { |
| 74 |
if v.Kind() == reflect.Interface && !v.IsNil() { |
| 75 |
v = v.Elem() |
| 76 |
} |
| 77 |
return v |
| 78 |
} |
| 79 |
|
| 80 |
// dumpPtr handles formatting of pointers by indirecting them as necessary. |
| 81 |
// nolint: errcheck |
| 82 |
func (d *dumpState) dumpPtr(v reflect.Value) { |
| 83 |
// Remove pointers at or below the current depth from map used to detect |
| 84 |
// circular refs. |
| 85 |
for k, depth := range d.pointers { |
| 86 |
if depth >= d.depth { |
| 87 |
delete(d.pointers, k) |
| 88 |
} |
| 89 |
} |
| 90 |
|
| 91 |
// Keep list of all dereferenced pointers to show later. |
| 92 |
pointerChain := make([]uintptr, 0) |
| 93 |
|
| 94 |
// Figure out how many levels of indirection there are by dereferencing |
| 95 |
// pointers and unpacking interfaces down the chain while detecting circular |
| 96 |
// references. |
| 97 |
nilFound := false |
| 98 |
cycleFound := false |
| 99 |
indirects := 0 |
| 100 |
ve := v |
| 101 |
for ve.Kind() == reflect.Ptr { |
| 102 |
if ve.IsNil() { |
| 103 |
nilFound = true |
| 104 |
break |
| 105 |
} |
| 106 |
indirects++ |
| 107 |
addr := ve.Pointer() |
| 108 |
pointerChain = append(pointerChain, addr) |
| 109 |
if pd, ok := d.pointers[addr]; ok && pd < d.depth { |
| 110 |
cycleFound = true |
| 111 |
indirects-- |
| 112 |
break |
| 113 |
} |
| 114 |
d.pointers[addr] = d.depth |
| 115 |
|
| 116 |
ve = ve.Elem() |
| 117 |
if ve.Kind() == reflect.Interface { |
| 118 |
if ve.IsNil() { |
| 119 |
nilFound = true |
| 120 |
break |
| 121 |
} |
| 122 |
ve = ve.Elem() |
| 123 |
} |
| 124 |
} |
| 125 |
|
| 126 |
// Display type information. |
| 127 |
d.w.Write(openParenBytes) |
| 128 |
d.w.Write(bytes.Repeat(asteriskBytes, indirects)) |
| 129 |
d.w.Write([]byte(ve.Type().String())) |
| 130 |
d.w.Write(closeParenBytes) |
| 131 |
|
| 132 |
// Display pointer information. |
| 133 |
if !d.cs.DisablePointerAddresses && len(pointerChain) > 0 { |
| 134 |
d.w.Write(openParenBytes) |
| 135 |
for i, addr := range pointerChain { |
| 136 |
if i > 0 { |
| 137 |
d.w.Write(pointerChainBytes) |
| 138 |
} |
| 139 |
printHexPtr(d.w, addr) |
| 140 |
} |
| 141 |
d.w.Write(closeParenBytes) |
| 142 |
} |
| 143 |
|
| 144 |
// Display dereferenced value. |
| 145 |
d.w.Write(openParenBytes) |
| 146 |
switch { |
| 147 |
case nilFound: |
| 148 |
d.w.Write(nilAngleBytes) |
| 149 |
|
| 150 |
case cycleFound: |
| 151 |
d.w.Write(circularBytes) |
| 152 |
|
| 153 |
default: |
| 154 |
d.ignoreNextType = true |
| 155 |
d.dump(ve) |
| 156 |
} |
| 157 |
d.w.Write(closeParenBytes) |
| 158 |
} |
| 159 |
|
| 160 |
// dumpSlice handles formatting of arrays and slices. Byte (uint8 under |
| 161 |
// reflection) arrays and slices are dumped in hexdump -C fashion. |
| 162 |
// nolint: errcheck |
| 163 |
func (d *dumpState) dumpSlice(v reflect.Value) { |
| 164 |
// Determine whether this type should be hex dumped or not. Also, |
| 165 |
// for types which should be hexdumped, try to use the underlying data |
| 166 |
// first, then fall back to trying to convert them to a uint8 slice. |
| 167 |
var buf []uint8 |
| 168 |
doHexDump := false |
| 169 |
numEntries := v.Len() |
| 170 |
if numEntries > 0 { |
| 171 |
vt := v.Index(0).Type() |
| 172 |
vts := vt.String() |
| 173 |
// C types that need to be converted. |
| 174 |
doConvert := strings.HasSuffix(vts, cCharSuffix) || |
| 175 |
strings.HasSuffix(vts, cUnsignedCharSuffix) || |
| 176 |
strings.HasSuffix(vts, cUint8tCharSuffix) |
| 177 |
|
| 178 |
// Try to use existing uint8 slices and fall back to converting |
| 179 |
// and copying if that fails. |
| 180 |
if !doConvert && vt.Kind() == reflect.Uint8 { |
| 181 |
// The underlying data needs to be converted if it can't |
| 182 |
// be type asserted to a uint8 slice. |
| 183 |
doConvert = true |
| 184 |
|
| 185 |
// We need an addressable interface to convert the type |
| 186 |
// to a byte slice. However, the reflect package won't |
| 187 |
// give us an interface on certain things like |
| 188 |
// unexported struct fields in order to enforce |
| 189 |
// visibility rules. We use unsafe, when available, to |
| 190 |
// bypass these restrictions since this package does not |
| 191 |
// mutate the values. |
| 192 |
vs := v |
| 193 |
if !vs.CanInterface() || !vs.CanAddr() { |
| 194 |
vs = UnsafeReflectValue(vs) |
| 195 |
} |
| 196 |
if !UnsafeDisabled { |
| 197 |
vs = vs.Slice(0, numEntries) |
| 198 |
|
| 199 |
// Use the existing uint8 slice if it can be type asserted. |
| 200 |
if slice, ok := vs.Interface().([]uint8); ok { |
| 201 |
buf = slice |
| 202 |
doHexDump = true |
| 203 |
doConvert = false |
| 204 |
} |
| 205 |
} |
| 206 |
} |
| 207 |
|
| 208 |
// Copy and convert the underlying type if needed. |
| 209 |
if doConvert && vt.ConvertibleTo(uint8Type) { |
| 210 |
// Convert and copy each element into a uint8 byte |
| 211 |
// slice. |
| 212 |
buf = make([]uint8, numEntries) |
| 213 |
for i := 0; i < numEntries; i++ { |
| 214 |
vv := v.Index(i) |
| 215 |
buf[i] = uint8(vv.Convert(uint8Type).Uint()) |
| 216 |
} |
| 217 |
doHexDump = true |
| 218 |
} |
| 219 |
} |
| 220 |
|
| 221 |
// Hexdump the entire slice as needed. |
| 222 |
if doHexDump { |
| 223 |
indent := strings.Repeat(d.cs.Indent, d.depth) |
| 224 |
str := indent + hex.Dump(buf) |
| 225 |
str = strings.ReplaceAll(str, "\n", "\n"+indent) |
| 226 |
str = strings.TrimRight(str, d.cs.Indent) |
| 227 |
d.w.Write([]byte(str)) |
| 228 |
return |
| 229 |
} |
| 230 |
|
| 231 |
// Recursively call dump for each item. |
| 232 |
for i := 0; i < numEntries; i++ { |
| 233 |
d.dump(d.unpackValue(v.Index(i))) |
| 234 |
if i < (numEntries - 1) { |
| 235 |
d.w.Write(commaNewlineBytes) |
| 236 |
} else { |
| 237 |
d.w.Write(newlineBytes) |
| 238 |
} |
| 239 |
} |
| 240 |
} |
| 241 |
|
| 242 |
// dump is the main workhorse for dumping a value. It uses the passed reflect |
| 243 |
// value to figure out what kind of object we are dealing with and formats it |
| 244 |
// appropriately. It is a recursive function, however circular data structures |
| 245 |
// are detected and handled properly. |
| 246 |
// nolint: errcheck |
| 247 |
func (d *dumpState) dump(v reflect.Value) { |
| 248 |
// Handle invalid reflect values immediately. |
| 249 |
kind := v.Kind() |
| 250 |
if kind == reflect.Invalid { |
| 251 |
d.w.Write(invalidAngleBytes) |
| 252 |
return |
| 253 |
} |
| 254 |
|
| 255 |
// Handle pointers specially. |
| 256 |
if kind == reflect.Ptr { |
| 257 |
d.indent() |
| 258 |
d.dumpPtr(v) |
| 259 |
return |
| 260 |
} |
| 261 |
|
| 262 |
// Print type information unless already handled elsewhere. |
| 263 |
if !d.ignoreNextType { |
| 264 |
d.indent() |
| 265 |
d.w.Write(openParenBytes) |
| 266 |
d.w.Write([]byte(v.Type().String())) |
| 267 |
d.w.Write(closeParenBytes) |
| 268 |
d.w.Write(spaceBytes) |
| 269 |
} |
| 270 |
d.ignoreNextType = false |
| 271 |
|
| 272 |
// Display length and capacity if the built-in len and cap functions |
| 273 |
// work with the value's kind and the len/cap itself is non-zero. |
| 274 |
valueLen, valueCap := 0, 0 |
| 275 |
switch v.Kind() { |
| 276 |
case reflect.Array, reflect.Slice, reflect.Chan: |
| 277 |
valueLen, valueCap = v.Len(), v.Cap() |
| 278 |
case reflect.Map, reflect.String: |
| 279 |
valueLen = v.Len() |
| 280 |
} |
| 281 |
if valueLen != 0 || d.cs.EnableCapacities && valueCap != 0 { |
| 282 |
d.w.Write(openParenBytes) |
| 283 |
if valueLen != 0 { |
| 284 |
d.w.Write(lenEqualsBytes) |
| 285 |
printInt(d.w, int64(valueLen), 10) |
| 286 |
} |
| 287 |
if d.cs.EnableCapacities && valueCap != 0 { |
| 288 |
if valueLen != 0 { |
| 289 |
d.w.Write(spaceBytes) |
| 290 |
} |
| 291 |
d.w.Write(capEqualsBytes) |
| 292 |
printInt(d.w, int64(valueCap), 10) |
| 293 |
} |
| 294 |
d.w.Write(closeParenBytes) |
| 295 |
d.w.Write(spaceBytes) |
| 296 |
} |
| 297 |
|
| 298 |
// Call fmt.Stringer/error interfaces if they exist and the handle |
| 299 |
// methods flag is enabled |
| 300 |
if !d.cs.DisableMethods && |
| 301 |
kind != reflect.Invalid && kind != reflect.Interface { |
| 302 |
if handled := handleMethods(d.cs, d.w, v); handled { |
| 303 |
return |
| 304 |
} |
| 305 |
} |
| 306 |
|
| 307 |
switch kind { |
| 308 |
case reflect.Invalid, reflect.Ptr: |
| 309 |
// Do nothing. We should never get here since invalid & pointers |
| 310 |
// have already been handled above. |
| 311 |
|
| 312 |
case reflect.Bool: |
| 313 |
printBool(d.w, v.Bool()) |
| 314 |
|
| 315 |
case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: |
| 316 |
printInt(d.w, v.Int(), 10) |
| 317 |
|
| 318 |
case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: |
| 319 |
printUint(d.w, v.Uint(), 10) |
| 320 |
|
| 321 |
case reflect.Float32: |
| 322 |
printFloat(d.w, v.Float(), 32) |
| 323 |
|
| 324 |
case reflect.Float64: |
| 325 |
printFloat(d.w, v.Float(), 64) |
| 326 |
|
| 327 |
case reflect.Complex64: |
| 328 |
printComplex(d.w, v.Complex(), 32) |
| 329 |
|
| 330 |
case reflect.Complex128: |
| 331 |
printComplex(d.w, v.Complex(), 64) |
| 332 |
|
| 333 |
case reflect.Slice: |
| 334 |
if v.IsNil() { |
| 335 |
d.w.Write(nilAngleBytes) |
| 336 |
break |
| 337 |
} |
| 338 |
fallthrough |
| 339 |
|
| 340 |
case reflect.Array: |
| 341 |
d.w.Write(openBraceNewlineBytes) |
| 342 |
d.depth++ |
| 343 |
if d.cs.MaxDepth != 0 && d.depth > d.cs.MaxDepth { |
| 344 |
d.indent() |
| 345 |
d.w.Write(maxNewlineBytes) |
| 346 |
} else { |
| 347 |
d.dumpSlice(v) |
| 348 |
} |
| 349 |
d.depth-- |
| 350 |
d.indent() |
| 351 |
d.w.Write(closeBraceBytes) |
| 352 |
|
| 353 |
case reflect.String: |
| 354 |
d.w.Write([]byte(strconv.Quote(v.String()))) |
| 355 |
|
| 356 |
case reflect.Interface: |
| 357 |
// The only time we should get here is for nil interfaces due to |
| 358 |
// unpackValue calls. |
| 359 |
if v.IsNil() { |
| 360 |
d.w.Write(nilAngleBytes) |
| 361 |
} |
| 362 |
|
| 363 |
case reflect.Map: |
| 364 |
// nil maps should be indicated as different than empty maps |
| 365 |
if v.IsNil() { |
| 366 |
d.w.Write(nilAngleBytes) |
| 367 |
break |
| 368 |
} |
| 369 |
|
| 370 |
d.w.Write(openBraceNewlineBytes) |
| 371 |
d.depth++ |
| 372 |
if d.cs.MaxDepth != 0 && d.depth > d.cs.MaxDepth { |
| 373 |
d.indent() |
| 374 |
d.w.Write(maxNewlineBytes) |
| 375 |
} else { |
| 376 |
i := v.Len() |
| 377 |
sort.MapEach(v, func(key reflect.Value, val reflect.Value) bool { |
| 378 |
d.dump(d.unpackValue(key)) |
| 379 |
d.w.Write(colonSpaceBytes) |
| 380 |
d.ignoreNextIndent = true |
| 381 |
d.dump(d.unpackValue(val)) |
| 382 |
i-- |
| 383 |
if i > 0 { |
| 384 |
d.w.Write(commaNewlineBytes) |
| 385 |
} else { |
| 386 |
d.w.Write(newlineBytes) |
| 387 |
} |
| 388 |
return true |
| 389 |
}) |
| 390 |
} |
| 391 |
d.depth-- |
| 392 |
d.indent() |
| 393 |
d.w.Write(closeBraceBytes) |
| 394 |
|
| 395 |
case reflect.Struct: |
| 396 |
d.w.Write(openBraceNewlineBytes) |
| 397 |
d.depth++ |
| 398 |
if d.cs.MaxDepth != 0 && d.depth > d.cs.MaxDepth { |
| 399 |
d.indent() |
| 400 |
d.w.Write(maxNewlineBytes) |
| 401 |
} else { |
| 402 |
vt := v.Type() |
| 403 |
numFields := v.NumField() |
| 404 |
for i := 0; i < numFields; i++ { |
| 405 |
vf := v.Field(i) |
| 406 |
if vf.IsZero() { |
| 407 |
continue |
| 408 |
} |
| 409 |
d.indent() |
| 410 |
vtf := vt.Field(i) |
| 411 |
d.w.Write([]byte(vtf.Name)) |
| 412 |
d.w.Write(colonSpaceBytes) |
| 413 |
d.ignoreNextIndent = true |
| 414 |
d.dump(d.unpackValue(vf)) |
| 415 |
if i < (numFields - 1) { |
| 416 |
d.w.Write(commaNewlineBytes) |
| 417 |
} else { |
| 418 |
d.w.Write(newlineBytes) |
| 419 |
} |
| 420 |
} |
| 421 |
} |
| 422 |
d.depth-- |
| 423 |
d.indent() |
| 424 |
d.w.Write(closeBraceBytes) |
| 425 |
|
| 426 |
case reflect.Uintptr: |
| 427 |
printHexPtr(d.w, uintptr(v.Uint())) |
| 428 |
|
| 429 |
case reflect.UnsafePointer, reflect.Chan, reflect.Func: |
| 430 |
printHexPtr(d.w, v.Pointer()) |
| 431 |
|
| 432 |
// There were not any other types at the time this code was written, but |
| 433 |
// fall back to letting the default fmt package handle it in case any new |
| 434 |
// types are added. |
| 435 |
default: |
| 436 |
if v.CanInterface() { |
| 437 |
fmt.Fprintf(d.w, "%v", v.Interface()) |
| 438 |
} else { |
| 439 |
fmt.Fprintf(d.w, "%v", v.String()) |
| 440 |
} |
| 441 |
} |
| 442 |
} |
| 443 |
|
| 444 |
// fdump is a helper function to consolidate the logic from the various public |
| 445 |
// methods which take varying writers and config states. |
| 446 |
// nolint: errcheck |
| 447 |
func fdump(cs *ConfigState, w io.Writer, arg any) { |
| 448 |
if arg == nil { |
| 449 |
w.Write(interfaceBytes) |
| 450 |
w.Write(spaceBytes) |
| 451 |
w.Write(nilAngleBytes) |
| 452 |
w.Write(newlineBytes) |
| 453 |
return |
| 454 |
} |
| 455 |
|
| 456 |
d := dumpState{w: w, cs: cs} |
| 457 |
d.pointers = make(map[uintptr]int) |
| 458 |
d.dump(reflect.ValueOf(arg)) |
| 459 |
d.w.Write(newlineBytes) |
| 460 |
} |
| 461 |
|
| 462 |
// Sdump returns the string representation of a using config[0] if passed. |
| 463 |
func Sdump(a any, config ...ConfigState) string { |
| 464 |
var buf strings.Builder |
| 465 |
cs := Config |
| 466 |
if len(config) > 0 { |
| 467 |
cs = config[0] |
| 468 |
} |
| 469 |
fdump(&cs, &buf, a) |
| 470 |
return strings.TrimRight(buf.String(), "\n") |
| 471 |
} |