-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patharray.go
70 lines (64 loc) · 1.58 KB
/
array.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
70
package pretty
import (
"reflect"
"github.com/pierrre/go-libs/strconvio"
"github.com/pierrre/pretty/internal"
)
// ArrayValueWriter is a [ValueWriter] that handles array values.
//
// It should be created with [NewArrayValueWriter].
type ArrayValueWriter struct {
ValueWriter
// ShowIndexes shows the indexes.
// Default: false.
ShowIndexes bool
// MaxLen is the maximum length of the array.
// Default: 0 (no limit).
MaxLen int
}
// NewArrayValueWriter creates a new [ArrayValueWriter] with default values.
func NewArrayValueWriter(vw ValueWriter) *ArrayValueWriter {
return &ArrayValueWriter{
ValueWriter: vw,
ShowIndexes: false,
MaxLen: 0,
}
}
// WriteValue implements [ValueWriter].
func (vw *ArrayValueWriter) 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
}
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
}
writeString(st.Writer, "{")
if v.Len() > 0 {
writeString(st.Writer, "\n")
st.IndentLevel++
for i := range l {
st.writeIndent()
if showIndexes {
internal.MustWrite(strconvio.WriteInt(st.Writer, int64(i), 10))
writeString(st.Writer, ": ")
}
mustHandle(vw(st, v.Index(i)))
writeString(st.Writer, ",\n")
}
if truncated {
st.writeIndent()
writeTruncated(st.Writer)
writeString(st.Writer, "\n")
}
st.IndentLevel--
st.writeIndent()
}
writeString(st.Writer, "}")
}