-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharray.go
More file actions
80 lines (73 loc) · 1.8 KB
/
array.go
File metadata and controls
80 lines (73 loc) · 1.8 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
76
77
78
79
80
package pretty
import (
"reflect"
"github.com/pierrre/go-libs/strconvio"
"github.com/pierrre/pretty/internal/must"
"github.com/pierrre/pretty/internal/write"
)
// ArrayWriter is a [ValueWriter] that handles array values.
//
// It should be created with [NewArrayWriter].
type ArrayWriter struct {
ValueWriter
// ShowIndexes shows the indexes.
// Default: false.
ShowIndexes bool
// MaxLen is the maximum length of the array.
// Default: 0 (no limit).
MaxLen int
}
// NewArrayWriter creates a new [ArrayWriter] with default values.
func NewArrayWriter(vw ValueWriter) *ArrayWriter {
return &ArrayWriter{
ValueWriter: vw,
ShowIndexes: false,
MaxLen: 0,
}
}
// WriteValue implements [ValueWriter].
func (vw *ArrayWriter) WriteValue(st *State, v reflect.Value) bool {
if v.Kind() != reflect.Array {
return false
}
writeArray(st, v, vw.ShowIndexes, vw.MaxLen, vw.ValueWriter)
return true
}
// Supports implements [SupportChecker].
func (vw *ArrayWriter) Supports(typ reflect.Type) ValueWriter {
var res ValueWriter
if typ.Kind() == reflect.Array {
res = vw
}
return res
}
func writeArray(st *State, v reflect.Value, showIndexes bool, maxLen int, vw ValueWriter) {
l := v.Len()
truncated := false
if maxLen > 0 && l > maxLen {
l = maxLen
truncated = true
}
write.MustString(st.Writer, "{")
if l > 0 {
write.MustString(st.Writer, "\n")
st.IndentLevel++
for i := range l {
st.WriteIndent()
if showIndexes {
write.Must(strconvio.WriteInt(st.Writer, int64(i), 10))
write.MustString(st.Writer, ": ")
}
must.Handle(vw.WriteValue(st, v.Index(i)))
write.MustString(st.Writer, ",\n")
}
if truncated {
st.WriteIndent()
writeTruncated(st.Writer)
write.MustString(st.Writer, "\n")
}
st.IndentLevel--
st.WriteIndent()
}
write.MustString(st.Writer, "}")
}