-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmax_depth.go
41 lines (36 loc) · 882 Bytes
/
max_depth.go
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
package pretty
import (
"reflect"
"github.com/pierrre/pretty/internal/write"
)
// MaxDepthValueWriter is a [ValueWriter] that limits the depth.
//
// It should be created with [NewMaxDepthValueWriter].
type MaxDepthValueWriter struct {
ValueWriter
// Max is the maximum depth.
// Default: 0 (no limit).
Max int
}
// NewMaxDepthValueWriter creates a new [MaxDepthValueWriter].
func NewMaxDepthValueWriter(vw ValueWriter) *MaxDepthValueWriter {
return &MaxDepthValueWriter{
ValueWriter: vw,
Max: 0,
}
}
// WriteValue implements [ValueWriter].
func (vw *MaxDepthValueWriter) WriteValue(st *State, v reflect.Value) bool {
if vw.Max <= 0 {
return vw.ValueWriter.WriteValue(st, v)
}
if st.Depth >= vw.Max {
write.MustString(st.Writer, "<max depth>")
return true
}
st.Depth++
defer func() {
st.Depth--
}()
return vw.ValueWriter.WriteValue(st, v)
}