-
Notifications
You must be signed in to change notification settings - Fork 0
/
types.go
469 lines (375 loc) · 9.32 KB
/
types.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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
package common
import (
"fmt"
"github.com/paulrosania/go-charset/charset"
_ "github.com/paulrosania/go-charset/data"
"github.com/pkg/errors"
"io"
"math"
"reflect"
"regexp"
"sort"
"strconv"
"strings"
"unicode"
)
const (
BIG5 = "big5"
IBM437 = "ibm437"
IBM850 = "ibm850"
IBM866 = "ibm866"
ISO_8859_1 = "iso-8859-1"
ISO_8859_10 = "iso-8859-10"
iso_8859_15 = "iso-8859-15"
ISO_8859_2 = "iso-8859-2"
ISO_8859_3 = "iso-8859-3"
ISO_8859_4 = "iso-8859-4"
ISO_8859_5 = "iso-8859-5"
ISO_8859_6 = "iso-8859-6"
ISO_8859_7 = "iso-8859-7"
ISO_8859_8 = "iso-8859-8"
ISO_8859_9 = "iso-8859-9"
KOI8_R = "koi8-r"
US_ASCII = "us-ascii"
UTF_16 = "utf-16"
UTF_16BE = "utf-16be"
UTF_16LE = "utf-16le"
UTF_8 = "utf-8"
WINDOWS_1250 = "windows-1250"
WINDOWS_1251 = "windows-1251"
WINDOWS_1252 = "windows-1252"
)
var (
MEMORY_UNITS = []string{"Bytes", "KB", "MB", "GB", "TB"}
)
// Trim4Path trims given path to be usefully as filename
func Trim4Path(path string) string {
spath := []rune(path)
for i, ch := range spath {
if ch == ':' || ch == '\\' {
spath[i] = '_'
}
}
return string(spath)
}
// CompareIgnoreCase compares strings for equality ignoring case
func CompareIgnoreCase(s0 string, s1 string) bool {
return strings.ToLower(s0) == strings.ToLower(s1)
}
// SplitWithQuotation splits a sequented string by spaces and respects quotation
func SplitWithQuotation(txt string) []string {
var result []string
var line string
inQ := false
for _, c := range txt {
if c == '"' {
inQ = !inQ
} else if c == ' ' {
if !inQ {
if len(line) > 0 {
result = append(result, line)
line = ""
} else {
line += string(c)
}
} else {
line += string(c)
}
} else {
line += string(c)
}
}
if len(line) > 0 {
result = append(result, line)
}
return result
}
// Capitalize the first letter
func Capitalize(txt string) string {
if len(txt) == 0 {
return txt
}
runes := []rune(txt)
allUpper := true
for _, r := range runes {
allUpper = unicode.IsUpper(r)
if !allUpper {
break
}
}
if allUpper {
return txt
} else {
return fmt.Sprintf("%s%s", string(unicode.ToUpper(runes[0])), string(runes[1:]))
}
}
func SurroundWith(str []string, prefixSuffix string) []string {
var result []string
result = make([]string, len(str))
for i, v := range str {
result[i] = prefixSuffix + v + prefixSuffix
}
return result
}
func Shortener(s string, max int) string {
if len(s) > max {
s = s[:max-4] + "..."
}
return s
}
func DefaultEncoding() string {
if IsWindowsOS() {
return ISO_8859_1
} else {
return UTF_8
}
}
func DefaultConsoleEncoding() string {
if IsWindowsOS() {
return IBM850
} else {
return UTF_8
}
}
func ToUTF8String(s string, cs string) (string, error) {
b, err := ToUTF8(strings.NewReader(s), cs)
if Error(err) {
return "", err
}
return string(b), nil
}
func ToUTF8(r io.Reader, cs string) ([]byte, error) {
rcs, err := charset.NewReader(cs, r)
if Error(err) {
return []byte{}, err
}
b, err := io.ReadAll(rcs)
if Error(err) {
return []byte{}, err
}
return b, nil
}
func IndexOf(slice interface{}, search interface{}) int {
if reflect.TypeOf(slice).Kind() != reflect.Slice {
panic(fmt.Errorf("not a slice: %v", slice))
}
sl := reflect.ValueOf(slice)
if sl.Len() == 0 {
return -1
}
s := fmt.Sprintf("%v", search)
for i := 0; i < sl.Len(); i++ {
c := fmt.Sprintf("%v", sl.Index(i))
if c == s {
return i
}
}
return -1
}
func ToStrings(slice interface{}) ([]string, error) {
if reflect.TypeOf(slice).Kind() != reflect.Slice {
return []string{}, errors.WithStack(fmt.Errorf("not a slice: %v", slice))
}
sl := reflect.ValueOf(slice)
if sl.Len() == 0 {
return nil, nil
}
var result []string
for i := 0; i < sl.Len(); i++ {
result = append(result, fmt.Sprintf("%v", sl.Index(i).Interface()))
}
return result, nil
}
func ConvertToOSspecificLF(s string) string {
if IsWindowsOS() {
s = strings.ReplaceAll(s, "\r", "\r\n")
}
return s
}
func CountRunes(s string) int {
return len([]rune(s))
}
func Rune(s string, index int) (rune, error) {
runes := []rune(s)
if index < len(runes) {
return runes[index], nil
} else {
return rune(' '), fmt.Errorf("invalid rune position: %d", index)
}
}
func ContainsWildcard(s string) bool {
return strings.ContainsAny(s, "*?")
}
func EqualWildcards(s, mask string) (bool, error) {
mask = strings.ReplaceAll(mask, ".", "\\.")
mask = strings.ReplaceAll(mask, "*", ".*")
mask = strings.ReplaceAll(mask, "?", ".")
r, err := regexp.Compile("^" + mask + "$")
if Error(err) {
return false, err
}
return r.MatchString(s), nil
}
func ReflectStructField(Iface interface{}, FieldName string) (*reflect.Value, error) {
valueIface := reflect.ValueOf(Iface)
// Check if the passed interface is a pointer
if valueIface.Type().Kind() != reflect.Ptr {
// Create a new type of Iface's Type, so we have a pointer to work with
valueIface = reflect.New(reflect.TypeOf(Iface))
}
// 'dereference' with Elem() and get the field by name
field := valueIface.Elem().FieldByName(FieldName)
if !field.IsValid() {
return nil, fmt.Errorf("Interface `%s` does not have the field `%s`", valueIface.Type(), FieldName)
}
return &field, nil
}
func ReflectStructMethod(Iface interface{}, MethodName string) (*reflect.Value, error) {
valueIface := reflect.ValueOf(Iface)
// Check if the passed interface is a pointer
if valueIface.Type().Kind() != reflect.Ptr {
// Create a new type of Iface, so we have a pointer to work with
valueIface = reflect.New(reflect.TypeOf(Iface))
}
// Get the method by name
method := valueIface.MethodByName(MethodName)
if !method.IsValid() {
return nil, fmt.Errorf("Couldn't find method `%s` in interface `%s`, is it Exported?", MethodName, valueIface.Type())
}
return &method, nil
}
func IterateStruct(data interface{}, function func(path string, fieldType reflect.StructField, fieldValue reflect.Value) error) error {
return iterateStruct("", data, function)
}
func iterateStruct(path string, data interface{}, funcStructIterator func(path string, fieldType reflect.StructField, fieldValue reflect.Value) error) error {
DebugFunc()
val, ok := data.(reflect.Value)
if !ok {
val = reflect.Indirect(reflect.ValueOf(data))
}
typ := val.Type()
if typ.Kind() != reflect.Struct {
return fmt.Errorf("not a struct: %s", typ.Name())
}
DebugFunc("struct: %s", typ.Name())
if funcStructIterator != nil {
err := funcStructIterator(path, reflect.StructField{}, val)
if Error(err) {
return err
}
}
for i := 0; i < val.NumField(); i++ {
fieldPath := typ.Field(i).Name
if path != "" {
fieldPath = strings.Join([]string{path, fieldPath}, "_")
}
DebugFunc("field #%d %s : fieldpath: %s type: %s",
i,
typ.Field(i).Name,
fieldPath,
val.Field(i).Type().Name())
if val.Field(i).Kind() == reflect.Struct {
err := iterateStruct(fieldPath, val.Field(i), funcStructIterator)
if Error(err) {
return err
}
continue
}
if val.Field(i).Kind() == reflect.Slice && val.Field(i).Type().Kind() == reflect.Struct {
for j := 0; j < val.Field(i).Len(); j++ {
sliceFieldPath := fmt.Sprintf("%s[%d]", fieldPath, j)
sliceElement := val.Field(i).Index(j).Elem()
if sliceElement.Kind() == reflect.Struct {
err := iterateStruct(sliceFieldPath, sliceElement, funcStructIterator)
if Error(err) {
return err
}
continue
}
if funcStructIterator != nil {
err := funcStructIterator(sliceFieldPath, reflect.StructField{}, sliceElement)
if Error(err) {
return err
}
}
}
continue
}
if funcStructIterator != nil {
err := funcStructIterator(fieldPath, typ.Field(i), val.Field(i))
if Error(err) {
return err
}
}
}
return nil
}
func FillString(txt string, length int, asPrefix bool, add string) string {
for len(txt) < length {
if asPrefix {
txt = add + txt
} else {
txt = txt + add
}
}
return txt[:length]
}
func ParseMemory(txt string) (int64, error) {
txt = strings.ToLower(txt)
f, err := ExtractNumber(txt)
if Error(err) {
return 0, err
}
for i := 0; i < len(MEMORY_UNITS); i++ {
if strings.HasSuffix(txt, strings.ToLower(MEMORY_UNITS[i])) || strings.HasSuffix(txt, strings.ToLower(MEMORY_UNITS[i][:1])) {
return int64(f * math.Pow(1024, float64(i))), nil
}
}
return int64(f * math.Pow(1024, float64(0))), nil
}
func FormatMemory(mem int64) string {
neg := mem < 0
f := math.Abs(float64(mem))
var i int
var d float64
for i = len(MEMORY_UNITS) - 1; i >= 0; i-- {
d = math.Pow(1024, float64(i))
if f > d {
break
}
}
r := f / d
if neg {
r = r * -1
}
return fmt.Sprintf("%.3f %s", r, MEMORY_UNITS[Max(i, 0)])
}
func ExtractNumber(txt string) (float64, error) {
r := regexp.MustCompile("[\\d.-]*")
s := r.FindString(txt)
if s == "" {
return -1, fmt.Errorf("cannot getNumber() from %s", txt)
}
f, err := strconv.ParseFloat(s, 64)
if Error(err) {
return -1, err
}
return f, nil
}
func SortStringsCaseInsensitive(strs []string) {
sort.SliceStable(strs, func(i, j int) bool {
return strings.ToUpper(strs[i]) < strings.ToUpper(strs[j])
})
}
func Join(strs []string, sep string) string {
sb := strings.Builder{}
for i := 0; i < len(strs); i++ {
if strs[i] != "" {
if sb.Len() > 0 {
sb.WriteString(sep)
}
sb.WriteString(strs[i])
}
}
return sb.String()
}