-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfstr.go
307 lines (263 loc) Β· 6.92 KB
/
fstr.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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
package fstr
import (
"fmt"
"io"
"reflect"
"strconv"
"strings"
)
// Sprintf formats according to a format specifier (with Rust-like placeholders).
// See the doc comment for full details on placeholders, escaping, etc.
func Sprintf(format string, args ...interface{}) string {
segments, placeholders := parseFormat(format)
placeholderValues := make([]interface{}, len(placeholders))
autoIndex := 0
for i, ph := range placeholders {
switch {
// Case 1: "{}" or "{:x}" without explicit positional index or field
case ph.PositionalIndex == nil && len(ph.FieldChain) == 0:
val := getArgOrNoValue(autoIndex, args)
placeholderValues[i] = val
autoIndex++
// Case 2: "{2}", "{1}", etc. (positional, no fields)
case ph.PositionalIndex != nil && len(ph.FieldChain) == 0:
val := getArgOrNoValue(*ph.PositionalIndex, args)
placeholderValues[i] = val
// Case 3: "{2.Name}", etc. (positional with fields)
case ph.PositionalIndex != nil && len(ph.FieldChain) > 0:
baseVal := getArgOrNoValue(*ph.PositionalIndex, args)
placeholderValues[i] = getFieldChainValue(baseVal, ph.FieldChain)
// Case 4: No index, but fields => default to argument #0
case ph.PositionalIndex == nil && len(ph.FieldChain) > 0:
baseVal := getArgOrNoValue(0, args)
placeholderValues[i] = getFieldChainValue(baseVal, ph.FieldChain)
}
}
// Build final output
var sb strings.Builder
for i, ph := range placeholders {
sb.WriteString(segments[i]) // literal text
val := placeholderValues[i]
formatSpec := placeholderSpecToPrintf(ph.Spec)
sb.WriteString(fmt.Sprintf(formatSpec, val))
}
if len(segments) > len(placeholders) {
sb.WriteString(segments[len(placeholders)])
}
return sb.String()
}
// Printf calls fmt.Print(...) on Sprintf(format, args...).
func Printf(format string, args ...interface{}) (int, error) {
return fmt.Print(Sprintf(format, args...))
}
// Println calls fmt.Println(...) on Sprintf(format, args...).
func Println(format string, args ...interface{}) (int, error) {
return fmt.Println(Sprintf(format, args...))
}
// Fprintf is like Printf but allows you to specify an io.Writer.
func Fprintf(w io.Writer, format string, args ...interface{}) (int, error) {
str := Sprintf(format, args...)
return fmt.Fprint(w, str)
}
// Fprintln is like Println but allows you to specify an io.Writer.
func Fprintln(w io.Writer, format string, args ...interface{}) (int, error) {
str := Sprintf(format, args...)
return fmt.Fprintln(w, str)
}
// F quickly formats the string.
func F(format string, args ...interface{}) string {
return Sprintf(format, args...)
}
// P is a shorthand alternative to Printf
func P(format string, args ...interface{}) (int, error) {
return fmt.Print(Sprintf(format, args...))
}
// Pln is a shorthand alternative to Println
func Pln(format string, args ...interface{}) (int, error) {
return fmt.Println(Sprintf(format, args...))
}
// ------------------------------------------------------------------
// Parser
// ------------------------------------------------------------------
type placeholder struct {
PositionalIndex *int
FieldChain []string
Spec string
}
func parseFormat(format string) ([]string, []placeholder) {
var segments []string
var placeholders []placeholder
r := []rune(format)
n := len(r)
var sb strings.Builder
i := 0
for i < n {
switch r[i] {
case '{':
// Check escaped '{{'
if i+1 < n && r[i+1] == '{' {
sb.WriteRune('{')
i += 2
continue
}
// Start placeholder
segments = append(segments, sb.String())
sb.Reset()
closing := findClosingBrace(r, i+1)
if closing == -1 {
sb.WriteRune('{')
i++
continue
}
inside := string(r[i+1 : closing])
i = closing + 1
ph := parsePlaceholder(inside)
placeholders = append(placeholders, ph)
case '}':
// Check escaped '}}'
if i+1 < n && r[i+1] == '}' {
sb.WriteRune('}')
i += 2
continue
}
sb.WriteRune('}')
i++
default:
sb.WriteRune(r[i])
i++
}
}
segments = append(segments, sb.String())
return segments, placeholders
}
func parsePlaceholder(inside string) placeholder {
// If empty => "{}"
if inside == "" {
return placeholder{}
}
// If starts with ":" => "{:x}", etc.
if inside[0] == ':' {
return placeholder{Spec: inside[1:]}
}
// Possibly includes a colon => "0.Name:x"
colonIdx := strings.IndexRune(inside, ':')
var mainPart, specPart string
if colonIdx >= 0 {
mainPart = inside[:colonIdx]
specPart = inside[colonIdx+1:]
} else {
mainPart = inside
specPart = ""
}
argIndex, fieldChain := parseArgIndexAndFieldChain(mainPart)
return placeholder{
PositionalIndex: argIndex,
FieldChain: fieldChain,
Spec: specPart,
}
}
func parseArgIndexAndFieldChain(s string) (*int, []string) {
parts := strings.Split(s, ".")
if len(parts[0]) > 0 && isAllDigits(parts[0]) {
idx, err := strconv.Atoi(parts[0])
if err == nil {
return &idx, parts[1:]
}
}
return nil, parts
}
func isAllDigits(s string) bool {
for _, r := range s {
if r < '0' || r > '9' {
return false
}
}
return true
}
func findClosingBrace(r []rune, start int) int {
for j := start; j < len(r); j++ {
if r[j] == '}' {
return j
}
}
return -1
}
// ------------------------------------------------------------------
// Field/Map Access
// ------------------------------------------------------------------
func getArgOrNoValue(idx int, args []interface{}) interface{} {
if idx < 0 || idx >= len(args) {
return "<no value>"
}
return args[idx]
}
func getFieldChainValue(base interface{}, fields []string) interface{} {
current := base
for _, f := range fields {
current = reflectFieldOrMapKey(current, f)
}
return current
}
func reflectFieldOrMapKey(val interface{}, name string) interface{} {
if val == nil {
return "<invalid field>"
}
rv := reflect.ValueOf(val)
switch rv.Kind() {
case reflect.Ptr:
if rv.IsNil() {
return "<invalid field>"
}
rv = rv.Elem()
fallthrough
case reflect.Struct:
return reflectField(rv, name)
case reflect.Map:
return reflectMap(rv, name)
default:
return "<invalid field>"
}
}
func reflectField(rv reflect.Value, fieldName string) interface{} {
fv := rv.FieldByName(fieldName)
if !fv.IsValid() {
return "<invalid field>"
}
if !fv.CanInterface() {
return "<invalid field>"
}
return fv.Interface()
}
func reflectMap(rv reflect.Value, key string) interface{} {
if rv.Type().Key().Kind() == reflect.String {
kv := rv.MapIndex(reflect.ValueOf(key))
if !kv.IsValid() {
return "<invalid field>"
}
return kv.Interface()
}
return "<invalid field>"
}
// ------------------------------------------------------------------
// Format Spec
// ------------------------------------------------------------------
func placeholderSpecToPrintf(spec string) string {
switch spec {
case "":
return "%v"
case "?":
return "%+v"
case "x":
return "%x"
case "X":
return "%X"
case "b":
return "%b"
case "o":
return "%o"
case "s":
return "%s"
default:
return "%v"
}
}