-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstringer.go
More file actions
75 lines (68 loc) · 1.63 KB
/
stringer.go
File metadata and controls
75 lines (68 loc) · 1.63 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
69
70
71
72
73
74
75
package pretty
import (
"fmt"
"reflect"
"github.com/pierrre/go-libs/reflectutil"
"github.com/pierrre/pretty/internal/itfassert"
)
var stringerImplementsCache = reflectutil.NewImplementsCacheFor[fmt.Stringer]()
// StringerWriter is a [ValueWriter] that handles [fmt.Stringer].
//
// If [fmt.Stringer.String] panics, [StringerWriter.WriteValue] returns false.
//
// It should be created with [NewStringerWriter].
type StringerWriter struct {
// ShowLen shows the len.
// Default: false.
ShowLen bool
// Quote quotes the string.
// Default: true.
Quote bool
// MaxLen is the maximum length of the string.
// Default: 0 (no limit).
MaxLen int
}
// NewStringerWriter creates a new [StringerWriter].
func NewStringerWriter() *StringerWriter {
return &StringerWriter{
ShowLen: false,
Quote: true,
MaxLen: 0,
}
}
// WriteValue implements [ValueWriter].
func (vw *StringerWriter) WriteValue(st *State, v reflect.Value) bool {
typ := v.Type()
if typ == reflectValueType {
return false
}
if !stringerImplementsCache.ImplementedBy(typ) {
return false
}
sr, ok := itfassert.Assert[fmt.Stringer](v)
if !ok {
return false
}
s, ok := func() (_ string, ok bool) {
defer func() {
if !ok {
_ = recover()
}
}()
return sr.String(), true
}()
if !ok {
return false
}
writeArrowWrappedString(st, "String() ")
writeStringValue(st, s, vw.ShowLen, false, 0, vw.Quote, vw.MaxLen)
return true
}
// Supports implements [SupportChecker].
func (vw *StringerWriter) Supports(typ reflect.Type) ValueWriter {
var res ValueWriter
if typ != reflectValueType && stringerImplementsCache.ImplementedBy(typ) {
res = vw
}
return res
}