-
Notifications
You must be signed in to change notification settings - Fork 191
/
Copy pathconvert.go
420 lines (356 loc) · 9.99 KB
/
convert.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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
package strutil
import (
"encoding/json"
"errors"
"fmt"
"reflect"
"regexp"
"strconv"
"strings"
"time"
"unsafe"
"github.com/gookit/goutil/comdef"
"github.com/gookit/goutil/internal/comfunc"
"github.com/gookit/goutil/mathutil"
)
var (
ErrDateLayout = errors.New("invalid date layout string")
ErrInvalidParam = errors.New("invalid input parameter")
// some regex for convert string.
toSnakeReg = regexp.MustCompile("[A-Z][a-z]")
toCamelRegs = map[string]*regexp.Regexp{
" ": regexp.MustCompile(" +[a-zA-Z]"),
"-": regexp.MustCompile("-+[a-zA-Z]"),
"_": regexp.MustCompile("_+[a-zA-Z]"),
}
)
// Internal func refers:
// strconv.QuoteRune()
// strconv.QuoteToASCII()
// strconv.AppendQuote()
// strconv.AppendQuoteRune()
// Quote alias of strings.Quote
func Quote(s string) string { return strconv.Quote(s) }
// Unquote remove start and end quotes by single-quote or double-quote
func Unquote(s string) string {
ln := len(s)
if ln < 2 {
return s
}
qs, qe := s[0], s[ln-1]
var valid bool
if qs == '"' && qe == '"' {
valid = true
} else if qs == '\'' && qe == '\'' {
valid = true
}
if valid {
s = s[1 : ln-1] // exclude quotes
}
// strconv.Unquote cannot unquote single-quote
// if ns, err := strconv.Unquote(s); err == nil {
// return ns
// }
return s
}
// Join alias of strings.Join
func Join(sep string, ss ...string) string { return strings.Join(ss, sep) }
// JoinList alias of strings.Join
func JoinList(sep string, ss []string) string { return strings.Join(ss, sep) }
// Implode alias of strings.Join
func Implode(sep string, ss ...string) string { return strings.Join(ss, sep) }
/*************************************************************
* convert value to string
*************************************************************/
// String convert val to string
func String(val interface{}) (string, error) {
return AnyToString(val, true)
}
// QuietString convert value to string, will ignore error
func QuietString(in interface{}) string {
val, _ := AnyToString(in, false)
return val
}
// MustString convert value to string, TODO will panic on error
func MustString(in interface{}) string {
val, _ := AnyToString(in, false)
return val
}
// StringOrErr convert value to string, return error on failed
func StringOrErr(val interface{}) (string, error) {
return AnyToString(val, true)
}
// ToString convert value to string
func ToString(val interface{}) (string, error) {
return AnyToString(val, true)
}
// AnyToString convert value to string.
//
// if defaultAsErr:
//
// False will use fmt.Sprint convert complex type
// True will return error on fail.
func AnyToString(val interface{}, defaultAsErr bool) (str string, err error) {
if val == nil {
return
}
switch value := val.(type) {
case int:
str = strconv.Itoa(value)
case int8:
str = strconv.Itoa(int(value))
case int16:
str = strconv.Itoa(int(value))
case int32: // same as `rune`
str = strconv.Itoa(int(value))
case int64:
str = strconv.FormatInt(value, 10)
case uint:
str = strconv.FormatUint(uint64(value), 10)
case uint8:
str = strconv.FormatUint(uint64(value), 10)
case uint16:
str = strconv.FormatUint(uint64(value), 10)
case uint32:
str = strconv.FormatUint(uint64(value), 10)
case uint64:
str = strconv.FormatUint(value, 10)
case float32:
str = strconv.FormatFloat(float64(value), 'f', -1, 32)
case float64:
str = strconv.FormatFloat(value, 'f', -1, 64)
case bool:
str = strconv.FormatBool(value)
case string:
str = value
case []byte:
str = string(value)
case time.Duration:
str = value.String()
case json.Number:
str = value.String()
default:
if defaultAsErr {
err = comdef.ErrConvType
} else {
str = fmt.Sprint(value)
}
}
return
}
/*************************************************************
* convert string value to byte
* refer from https://github.com/valyala/fastjson/blob/master/util.go
*************************************************************/
// Byte2str convert bytes to string
func Byte2str(b []byte) string {
return *(*string)(unsafe.Pointer(&b))
}
// Byte2string convert bytes to string
func Byte2string(b []byte) string {
return *(*string)(unsafe.Pointer(&b))
}
// ToBytes convert string to bytes
func ToBytes(s string) (b []byte) {
strh := (*reflect.StringHeader)(unsafe.Pointer(&s))
sh := (*reflect.SliceHeader)(unsafe.Pointer(&b))
sh.Data = strh.Data
sh.Len = strh.Len
sh.Cap = strh.Len
return b
}
/*************************************************************
* convert string value to bool
*************************************************************/
// ToBool convert string to bool
func ToBool(s string) (bool, error) {
return comfunc.StrToBool(s)
}
// QuietBool convert to bool, will ignore error
func QuietBool(s string) bool {
val, _ := comfunc.StrToBool(strings.TrimSpace(s))
return val
}
// MustBool convert, will panic on error
func MustBool(s string) bool {
val, _ := comfunc.StrToBool(strings.TrimSpace(s))
return val
}
// Bool parse string to bool. like strconv.ParseBool()
func Bool(s string) (bool, error) {
return comfunc.StrToBool(s)
}
/*************************************************************
* convert string value to int, float
*************************************************************/
// Int convert string to int, alias of ToInt()
func Int(s string) (int, error) {
return strconv.Atoi(strings.TrimSpace(s))
}
// ToInt convert string to int, return error on fail
func ToInt(s string) (int, error) {
return strconv.Atoi(strings.TrimSpace(s))
}
// QuietInt convert string to int, will ignore error
func QuietInt(s string) int {
val, _ := ToInt(s)
return val
}
// MustInt convert string to int, will panic on error
func MustInt(s string) int {
val, _ := ToInt(s)
return val
}
// IntOrPanic convert value to int, will panic on error
func IntOrPanic(s string) int {
val, err := ToInt(s)
if err != nil {
panic(err)
}
return val
}
// Int64 convert string to int, will ignore error
func Int64(s string) int64 {
val, _ := Int64OrErr(s)
return val
}
// QuietInt64 convert string to int, will ignore error
func QuietInt64(s string) int64 {
val, _ := Int64OrErr(s)
return val
}
// ToInt64 convert string to int, return error on fail
func ToInt64(s string) (int64, error) {
return strconv.ParseInt(s, 10, 0)
}
// Int64OrErr convert string to int, return error on fail
func Int64OrErr(s string) (int64, error) {
return strconv.ParseInt(s, 10, 0)
}
// MustInt64 convert value to int, will panic on error
func MustInt64(s string) int64 {
return Int64OrPanic(s)
}
// Int64OrPanic convert value to int, will panic on error
func Int64OrPanic(s string) int64 {
val, err := strconv.ParseInt(s, 10, 0)
if err != nil {
panic(err)
}
return val
}
/*************************************************************
* convert string value to int/string slice, time.Time
*************************************************************/
// Ints alias of the ToIntSlice(). default sep is comma(,)
func Ints(s string, sep ...string) []int {
ints, _ := ToIntSlice(s, sep...)
return ints
}
// ToInts alias of the ToIntSlice(). default sep is comma(,)
func ToInts(s string, sep ...string) ([]int, error) { return ToIntSlice(s, sep...) }
// ToIntSlice split string to slice and convert item to int.
//
// Default sep is comma(,)
func ToIntSlice(s string, sep ...string) (ints []int, err error) {
ss := ToSlice(s, sep...)
for _, item := range ss {
iVal, err := mathutil.ToInt(item)
if err != nil {
return []int{}, err
}
ints = append(ints, iVal)
}
return
}
// ToArray alias of the ToSlice()
func ToArray(s string, sep ...string) []string { return ToSlice(s, sep...) }
// Strings alias of the ToSlice()
func Strings(s string, sep ...string) []string { return ToSlice(s, sep...) }
// ToStrings alias of the ToSlice()
func ToStrings(s string, sep ...string) []string { return ToSlice(s, sep...) }
// ToSlice split string to array.
func ToSlice(s string, sep ...string) []string {
if len(sep) > 0 {
return Split(s, sep[0])
}
return Split(s, ",")
}
// ToOSArgs split string to string[](such as os.Args)
// func ToOSArgs(s string) []string {
// return cliutil.StringToOSArgs(s) // error: import cycle not allowed
// }
// MustToTime convert date string to time.Time
func MustToTime(s string, layouts ...string) time.Time {
t, err := ToTime(s, layouts...)
if err != nil {
panic(err)
}
return t
}
// auto match use some commonly layouts.
// key is layout length.
var layoutMap = map[int][]string{
6: {"200601", "060102", time.Kitchen},
8: {"20060102"},
10: {"2006-01-02"},
13: {"2006-01-02 15"},
15: {time.Stamp},
16: {"2006-01-02 15:04"},
19: {"2006-01-02 15:04:05", time.RFC822, time.StampMilli},
20: {"2006-01-02 15:04:05Z"},
21: {time.RFC822Z},
22: {time.StampMicro},
24: {time.ANSIC},
25: {time.RFC3339, time.StampNano},
// 26: {time.Layout}, // must go >= 1.19
28: {time.UnixDate},
29: {time.RFC1123},
30: {time.RFC850},
31: {time.RFC1123Z},
35: {time.RFC3339Nano},
}
// ToTime convert date string to time.Time
func ToTime(s string, layouts ...string) (t time.Time, err error) {
// custom layout
if len(layouts) > 0 {
if len(layouts[0]) > 0 {
return time.Parse(layouts[0], s)
}
err = ErrDateLayout
return
}
// auto match use some commonly layouts.
strLn := len(s)
maybeLayouts, ok := layoutMap[strLn]
if !ok {
err = ErrInvalidParam
return
}
var hasAlphaT bool
if pos := strings.IndexByte(s, 'T'); pos > 0 && pos < 12 {
hasAlphaT = true
}
hasSlashR := strings.IndexByte(s, '/') > 0
for _, layout := range maybeLayouts {
// date string has "T". eg: "2006-01-02T15:04:05"
if hasAlphaT {
layout = strings.Replace(layout, " ", "T", 1)
}
// date string has "/". eg: "2006/01/02 15:04:05"
if hasSlashR {
layout = strings.Replace(layout, "-", "/", -1)
}
t, err = time.Parse(layout, s)
if err == nil {
return
}
}
// t, err = time.ParseInLocation(layout, s, time.Local)
return
}
// ToDuration parses a duration string. such as "300ms", "-1.5h" or "2h45m".
// Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h".
func ToDuration(s string) (time.Duration, error) {
return time.ParseDuration(s)
}