-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstringer.go
53 lines (48 loc) · 1.21 KB
/
stringer.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
42
43
44
45
46
47
48
49
50
51
52
53
package pretty
import (
"fmt"
"reflect"
)
var stringerType = reflect.TypeFor[fmt.Stringer]()
// StringerValueWriter is a [ValueWriter] that handles [fmt.Stringer].
//
// It should be created with [NewStringerValueWriter].
type StringerValueWriter struct {
// ShowLen shows the len.
// Default: true.
ShowLen bool
// Quote quotes the string.
// Default: true.
Quote bool
// MaxLen is the maximum length of the string.
// Default: 0 (no limit).
MaxLen int
}
// NewStringerValueWriter creates a new [StringerValueWriter].
func NewStringerValueWriter() *StringerValueWriter {
return &StringerValueWriter{
ShowLen: true,
Quote: true,
MaxLen: 0,
}
}
// WriteValue implements [ValueWriter].
func (vw *StringerValueWriter) WriteValue(st *State, v reflect.Value) bool {
if !v.Type().Implements(stringerType) {
return false
}
if v.Kind() == reflect.Pointer && v.IsNil() {
return false
}
if v.Type() == reflectValueType {
return false
}
if !v.CanInterface() {
return false
}
sr := v.Interface().(fmt.Stringer) //nolint:forcetypeassert // Checked above.
s := sr.String()
writeArrowWrappedString(st.Writer, ".String() ")
writeStringValue(st, s, vw.ShowLen, false, 0, vw.Quote, vw.MaxLen)
return true
}