-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstring.go
69 lines (63 loc) · 1.57 KB
/
string.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package pretty
import (
"reflect"
"github.com/pierrre/go-libs/strconvio"
"github.com/pierrre/pretty/internal/write"
)
// StringValueWriter is a [ValueWriter] that handles string values.
//
// It should be created with [NewStringValueWriter].
type StringValueWriter struct {
// ShowLen shows the len.
// Default: true.
ShowLen bool
// ShowAddr shows the address.
// Default: false.
ShowAddr bool
// Quote quotes the string.
// Default: true.
Quote bool
// MaxLen is the maximum length of the string.
// Default: 0 (no limit).
MaxLen int
}
// NewStringValueWriter creates a new [StringValueWriter] with default values.
func NewStringValueWriter() *StringValueWriter {
return &StringValueWriter{
ShowLen: true,
ShowAddr: false,
Quote: true,
MaxLen: 0,
}
}
// WriteValue implements [ValueWriter].
func (vw *StringValueWriter) WriteValue(st *State, v reflect.Value) bool {
if v.Kind() != reflect.String {
return false
}
s := v.String()
writeStringValue(st, s, vw.ShowLen, vw.ShowAddr, uintptr(v.UnsafePointer()), vw.Quote, vw.MaxLen)
return true
}
func writeStringValue(st *State, s string, showLen bool, showAddr bool, addr uintptr, quote bool, maxLen int) {
infos{
showLen: showLen,
len: len(s),
showAddr: showAddr,
addr: addr,
}.writeWithTrailingSpace(st)
truncated := false
if maxLen > 0 && len(s) > maxLen {
s = s[:maxLen]
truncated = true
}
if quote {
write.Must(strconvio.WriteQuote(st.Writer, s))
} else {
write.MustString(st.Writer, s)
}
if truncated {
write.MustString(st.Writer, " ")
writeTruncated(st.Writer)
}
}