-
Notifications
You must be signed in to change notification settings - Fork 0
/
formatter.go
142 lines (115 loc) · 2.28 KB
/
formatter.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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
package nmfmt
import (
"fmt"
"io"
"sync"
)
type formatterOptions struct {
cacheResetLimit int
}
type OptionFunc func(*formatterOptions)
// CacheResetLimit sets when to clear cache.
func CacheResetLimit(misses int) OptionFunc {
return func(f *formatterOptions) {
f.cacheResetLimit = misses
}
}
type Formatter struct {
cache *cache
argsBufPool sync.Pool
}
func New(opts ...OptionFunc) Formatter {
fo := formatterOptions{
cacheResetLimit: 100,
}
for _, o := range opts {
o(&fo)
}
return Formatter{
cache: newCache(fo.cacheResetLimit),
argsBufPool: sync.Pool{
New: func() any {
return &[]any{}
},
},
}
}
func (f *Formatter) Printf(format string, a ...any) (int, error) {
if len(a) == 0 {
return fmt.Printf(format)
}
cn := f.cache.get(format)
aa, err := cn.construct(a, func() *[]any {
return f.argsBufPool.Get().(*[]any)
})
if err != nil {
return 0, err
}
var n int
if aa == nil {
n, err = fmt.Printf(cn.format)
} else {
n, err = fmt.Printf(cn.format, (*aa)...)
f.argsBufPool.Put(aa)
}
return n, err
}
func (f *Formatter) Fprintf(w io.Writer, format string, a ...any) (int, error) {
if len(a) == 0 {
return fmt.Fprintf(w, format)
}
cn := f.cache.get(format)
aa, err := cn.construct(a, func() *[]any {
return f.argsBufPool.Get().(*[]any)
})
if err != nil {
return 0, err
}
var n int
if aa == nil {
n, err = fmt.Fprintf(w, cn.format)
} else {
n, err = fmt.Fprintf(w, cn.format, (*aa)...)
f.argsBufPool.Put(aa)
}
return n, err
}
func (f *Formatter) Sprintf(format string, a ...any) string {
if len(a) == 0 {
return fmt.Sprintf(format)
}
cn := f.cache.get(format)
aa, err := cn.construct(a, func() *[]any {
return f.argsBufPool.Get().(*[]any)
})
if err != nil {
return ""
}
var s string
if aa == nil {
s = fmt.Sprintf(cn.format)
} else {
s = fmt.Sprintf(cn.format, (*aa)...)
f.argsBufPool.Put(aa)
}
return s
}
func (f *Formatter) Errorf(format string, a ...any) error {
if len(a) == 0 {
return fmt.Errorf(format)
}
cn := f.cache.get(format)
aa, err := cn.construct(a, func() *[]any {
return f.argsBufPool.Get().(*[]any)
})
if err != nil {
return err
}
if aa == nil {
err = fmt.Errorf(cn.format)
} else {
err = fmt.Errorf(cn.format, (*aa)...)
f.argsBufPool.Put(aa)
}
return err
}