forked from elastic/beats
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fmt.go
261 lines (208 loc) · 5.12 KB
/
fmt.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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
package dtfmt
import (
"errors"
"fmt"
"io"
"strings"
"sync"
"time"
"unicode/utf8"
)
// Formatter will format time values into strings, based on pattern used to
// create the Formatter.
type Formatter struct {
prog prog
sz int
config ctxConfig
}
var ctxPool = &sync.Pool{
New: func() interface{} { return &ctx{} },
}
func newCtx() *ctx {
return ctxPool.Get().(*ctx)
}
func newCtxWithSize(sz int) *ctx {
ctx := newCtx()
if ctx.buf == nil || cap(ctx.buf) < sz {
ctx.buf = make([]byte, 0, sz)
}
return ctx
}
func releaseCtx(c *ctx) {
ctxPool.Put(c)
}
// NewFormatter creates a new time formatter based on provided pattern.
// If pattern is invalid an error is returned.
func NewFormatter(pattern string) (*Formatter, error) {
b := newBuilder()
err := parsePatternTo(b, pattern)
if err != nil {
return nil, err
}
b.optimize()
cfg, err := b.createConfig()
if err != nil {
return nil, err
}
prog, err := b.compile()
if err != nil {
return nil, err
}
sz := b.estimateSize()
f := &Formatter{
prog: prog,
sz: sz,
config: cfg,
}
return f, nil
}
// EstimateSize estimates the required buffer size required to hold
// the formatted time string. Estimated size gives no exact guarantees.
// Estimated size might still be too low or too big.
func (f *Formatter) EstimateSize() int {
return f.sz
}
func (f *Formatter) appendTo(ctx *ctx, b []byte, t time.Time) ([]byte, error) {
ctx.initTime(&f.config, t)
return f.prog.eval(b, ctx, t)
}
// AppendTo appends the formatted time value to the given byte buffer.
func (f *Formatter) AppendTo(b []byte, t time.Time) ([]byte, error) {
ctx := newCtx()
defer releaseCtx(ctx)
return f.appendTo(ctx, b, t)
}
// Write writes the formatted time value to the given writer. Returns
// number of bytes written or error if formatter or writer fails.
func (f *Formatter) Write(w io.Writer, t time.Time) (int, error) {
var err error
ctx := newCtxWithSize(f.sz)
defer releaseCtx(ctx)
ctx.buf, err = f.appendTo(ctx, ctx.buf[:0], t)
if err != nil {
return 0, err
}
return w.Write(ctx.buf)
}
// Format formats the given time value into a new string.
func (f *Formatter) Format(t time.Time) (string, error) {
var err error
ctx := newCtxWithSize(f.sz)
defer releaseCtx(ctx)
ctx.buf, err = f.appendTo(ctx, ctx.buf[:0], t)
if err != nil {
return "", err
}
return string(ctx.buf), nil
}
func parsePatternTo(b *builder, pattern string) error {
for i := 0; i < len(pattern); {
tok, tokText, err := parseToken(pattern, &i)
if err != nil {
return err
}
tokLen := len(tokText)
switch tok {
case 'x': // weekyear (year)
if tokLen == 2 {
b.twoDigitWeekYear()
} else {
b.weekyear(tokLen, 4)
}
case 'y', 'Y': // year and year of era (year) == 'y'
if tokLen == 2 {
b.twoDigitYear()
} else {
b.year(tokLen, 4)
}
case 'w': // week of weekyear (num)
b.weekOfWeekyear(tokLen)
case 'e': // day of week (num)
b.dayOfWeek(tokLen)
case 'E': // day of week (text)
if tokLen >= 4 {
b.dayOfWeekText()
} else {
b.dayOfWeekShortText()
}
case 'D': // day of year (number)
b.dayOfYear(tokLen)
case 'M': // month of year (month)
if tokLen >= 3 {
if tokLen >= 4 {
b.monthOfYearText()
} else {
b.monthOfYearShortText()
}
} else {
b.monthOfYear(tokLen)
}
case 'd': //day of month (number)
b.dayOfMonth(tokLen)
case 'a': // half of day (text) 'AM/PM'
b.halfdayOfDayText()
case 'K': // hour of half day (number) (0 - 11)
b.hourOfHalfday(tokLen)
case 'h': // clock hour of half day (number) (1 - 12)
b.clockhourOfHalfday(tokLen)
case 'H': // hour of day (number) (0 - 23)
b.hourOfDay(tokLen)
case 'k': // clock hour of half day (number) (1 - 24)
b.clockhourOfDay(tokLen)
case 'm': // minute of hour
b.minuteOfHour(tokLen)
case 's': // second of minute
b.secondOfMinute(tokLen)
case 'S': // fraction of second
b.millisOfSecond(tokLen)
case '\'': // literal
if tokLen == 1 {
b.appendRune(rune(tokText[0]))
} else {
b.appendLiteral(tokText)
}
default:
return fmt.Errorf("unsupport format '%c'", tok)
}
}
return nil
}
func parseToken(pattern string, i *int) (rune, string, error) {
start := *i
idx := start
length := len(pattern)
r, w := utf8.DecodeRuneInString(pattern[idx:])
idx += w
if ('A' <= r && r <= 'Z') || ('a' <= r && r <= 'z') {
// Scan a run of the same character, which indicates a time pattern.
for idx < length {
peek, w := utf8.DecodeRuneInString(pattern[idx:])
if peek != r {
break
}
idx += w
}
*i = idx
return r, pattern[start:idx], nil
}
if r != '\'' { // single character, no escaped string
*i = idx
return '\'', pattern[start:idx], nil
}
start = idx // skip ' character
iEnd := strings.IndexRune(pattern[start:], '\'')
if iEnd < 0 {
return r, "", errors.New("missing closing '")
}
if iEnd == 0 {
// escape single quote literal
*i = idx + 1
return r, pattern[start : idx+1], nil
}
iEnd += start
*i = iEnd + 1 // point after '
if len(pattern) > iEnd+1 && pattern[iEnd+1] == '\'' {
return r, pattern[start : iEnd+1], nil
}
return r, pattern[start:iEnd], nil
}