forked from gookit/goutil
-
Notifications
You must be signed in to change notification settings - Fork 0
/
format.go
123 lines (102 loc) · 2.12 KB
/
format.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
package arrutil
import (
"io"
"reflect"
"github.com/gookit/goutil/comdef"
"github.com/gookit/goutil/strutil"
)
// ArrFormatter struct
type ArrFormatter struct {
comdef.BaseFormatter
// Prefix string for each element
Prefix string
// Indent string for format each element
Indent string
// ClosePrefix on before end char: ]
ClosePrefix string
}
// NewFormatter instance
func NewFormatter(arr any) *ArrFormatter {
f := &ArrFormatter{}
f.Src = arr
return f
}
// FormatIndent array data to string.
func FormatIndent(arr any, indent string) string {
return NewFormatter(arr).WithIndent(indent).Format()
}
// WithFn for config self
func (f *ArrFormatter) WithFn(fn func(f *ArrFormatter)) *ArrFormatter {
fn(f)
return f
}
// WithIndent string
func (f *ArrFormatter) WithIndent(indent string) *ArrFormatter {
f.Indent = indent
return f
}
// FormatTo to custom buffer
func (f *ArrFormatter) FormatTo(w io.Writer) {
f.SetOutput(w)
f.doFormat()
}
// Format to string
func (f *ArrFormatter) String() string {
return f.Format()
}
// Format to string
func (f *ArrFormatter) Format() string {
f.doFormat()
return f.BsWriter().String()
}
// Format to string
//
//goland:noinspection GoUnhandledErrorResult
func (f *ArrFormatter) doFormat() {
if f.Src == nil {
return
}
rv, ok := f.Src.(reflect.Value)
if !ok {
rv = reflect.ValueOf(f.Src)
}
rv = reflect.Indirect(rv)
if rv.Kind() != reflect.Slice && rv.Kind() != reflect.Array {
return
}
writer := f.BsWriter()
arrLn := rv.Len()
if arrLn == 0 {
writer.WriteString("[]")
return
}
// if f.AfterReset {
// defer f.Reset()
// }
// sb.Grow(arrLn * 4)
writer.WriteByte('[')
indentLn := len(f.Indent)
if indentLn > 0 {
writer.WriteByte('\n')
}
for i := 0; i < arrLn; i++ {
if indentLn > 0 {
writer.WriteString(f.Indent)
}
writer.WriteString(strutil.QuietString(rv.Index(i).Interface()))
if i < arrLn-1 {
writer.WriteByte(',')
// no indent, with space
if indentLn == 0 {
writer.WriteByte(' ')
}
}
if indentLn > 0 {
writer.WriteByte('\n')
}
}
if f.ClosePrefix != "" {
writer.WriteString(f.ClosePrefix)
}
writer.WriteByte(']')
}