-
Notifications
You must be signed in to change notification settings - Fork 191
/
format.go
125 lines (102 loc) · 2.05 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
124
125
package maputil
import (
"io"
"reflect"
"github.com/gookit/goutil/comdef"
"github.com/gookit/goutil/strutil"
)
// MapFormatter struct
type MapFormatter struct {
comdef.BaseFormatter
// Prefix string for each element
Prefix string
// Indent string for each element
Indent string
// ClosePrefix string for last "}"
ClosePrefix string
// AfterReset after reset on call Format().
// AfterReset bool
}
// NewFormatter instance
func NewFormatter(mp any) *MapFormatter {
f := &MapFormatter{}
f.Src = mp
return f
}
// WithFn for config self
func (f *MapFormatter) WithFn(fn func(f *MapFormatter)) *MapFormatter {
fn(f)
return f
}
// WithIndent string
func (f *MapFormatter) WithIndent(indent string) *MapFormatter {
f.Indent = indent
return f
}
// FormatTo to custom buffer
func (f *MapFormatter) FormatTo(w io.Writer) {
f.SetOutput(w)
f.doFormat()
}
// Format to string
func (f *MapFormatter) String() string {
return f.Format()
}
// Format to string
func (f *MapFormatter) Format() string {
f.doFormat()
return f.BsWriter().String()
}
// Format map data to string.
//
//goland:noinspection GoUnhandledErrorResult
func (f *MapFormatter) 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.Map {
return
}
buf := f.BsWriter()
ln := rv.Len()
if ln == 0 {
buf.WriteString("{}")
return
}
// buf.Grow(ln * 16)
buf.WriteByte('{')
indentLn := len(f.Indent)
if indentLn > 0 {
buf.WriteByte('\n')
}
for i, key := range rv.MapKeys() {
strK := strutil.SafeString(key.Interface())
if indentLn > 0 {
buf.WriteString(f.Indent)
}
buf.WriteString(strK)
buf.WriteByte(':')
strV := strutil.SafeString(rv.MapIndex(key).Interface())
buf.WriteString(strV)
if i < ln-1 {
buf.WriteByte(',')
// no indent, with space
if indentLn == 0 {
buf.WriteByte(' ')
}
}
// with newline
if indentLn > 0 {
buf.WriteByte('\n')
}
}
if f.ClosePrefix != "" {
buf.WriteString(f.ClosePrefix)
}
buf.WriteByte('}')
}