-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrecursion.go
More file actions
68 lines (61 loc) · 1.67 KB
/
Copy pathrecursion.go
File metadata and controls
68 lines (61 loc) · 1.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package pretty
import (
"reflect"
"github.com/pierrre/go-libs/reflectutil"
)
// RecursionWriter is a [ValueWriter] that prevents recursion.
//
// It should be created with [NewRecursionWriter].
type RecursionWriter struct {
ValueWriter
// ShowAddr shows the address (and type).
// Default: true.
ShowAddr bool
}
// NewRecursionWriter creates a new [RecursionWriter].
func NewRecursionWriter(vw ValueWriter) *RecursionWriter {
return &RecursionWriter{
ValueWriter: vw,
ShowAddr: true,
}
}
// WriteValue implements [ValueWriter].
func (vw *RecursionWriter) WriteValue(st *State, v reflect.Value) bool {
e, visitedAdded, recursionDetected := vw.checkRecursion(st, v)
if recursionDetected {
return true
}
if visitedAdded {
defer vw.postRecursion(st, e)
}
return vw.ValueWriter.WriteValue(st, v)
}
func (vw *RecursionWriter) checkRecursion(st *State, v reflect.Value) (e VisitedEntry, visitedAdded bool, recursionDetected bool) {
switch v.Kind() { //nolint:exhaustive // Only handles pointer kinds.
case reflect.Pointer, reflect.Map, reflect.Slice:
default:
return VisitedEntry{}, false, false
}
e = VisitedEntry{
Type: v.Type(),
Addr: uintptr(v.UnsafePointer()),
}
if _, ok := st.Visited[e]; !ok {
if st.Visited == nil {
st.Visited = make(map[VisitedEntry]struct{})
}
st.Visited[e] = struct{}{}
return e, true, false
}
st.Writer.AppendString("<recursion>")
if vw.ShowAddr {
st.Writer.AppendByte(' ')
st.Writer.AppendString(reflectutil.TypeFullName(e.Type))
st.Writer.AppendByte(' ')
writeUintptr(st, e.Addr)
}
return VisitedEntry{}, false, true
}
func (vw *RecursionWriter) postRecursion(st *State, e VisitedEntry) {
delete(st.Visited, e)
}