-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathstring.go
528 lines (473 loc) · 11.5 KB
/
string.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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
package dry
import (
"bytes"
"crypto/md5" //#nosec
"crypto/sha1" //#nosec
"encoding/base64"
"encoding/csv"
"encoding/json"
"fmt"
"reflect"
"sort"
"strconv"
"strings"
"time"
"unicode"
)
// StringMarshalJSON marshals data to an indented string.
func StringMarshalJSON(data interface{}, indent string) string {
buffer, err := json.MarshalIndent(data, "", indent)
if err != nil {
return ""
}
return string(buffer)
}
func StringListContains(l []string, s string) bool {
for i := range l {
if l[i] == s {
return true
}
}
return false
}
func StringListContainsCaseInsensitive(l []string, s string) bool {
s = strings.ToLower(s)
for i := range l {
if strings.ToLower(l[i]) == s {
return true
}
}
return false
}
func StringPrettifyJSON(compactJSON string) string {
var buf bytes.Buffer
err := json.Indent(&buf, []byte(compactJSON), "", "\t")
if err != nil {
return err.Error()
}
return buf.String()
}
func StringEscapeJSON(jsonString string) string {
jsonString = strings.Replace(jsonString, `\`, `\\`, -1)
jsonString = strings.Replace(jsonString, `"`, `\"`, -1)
return jsonString
}
// StringStripHTMLTags strips HTML/XML tags from text.
func StringStripHTMLTags(text string) (plainText string) {
var buf *bytes.Buffer
tagClose := -1
tagStart := -1
for i, char := range text {
if char == '<' {
if buf == nil {
buf = bytes.NewBufferString(text)
buf.Reset()
}
buf.WriteString(text[tagClose+1 : i])
tagStart = i
} else if char == '>' && tagStart != -1 {
tagClose = i
tagStart = -1
}
}
if buf == nil {
return text
}
buf.WriteString(text[tagClose+1:])
return buf.String()
}
// StringReplaceHTMLTags replaces HTML/XML tags from text with replacement.
func StringReplaceHTMLTags(text, replacement string) (plainText string) {
var buf *bytes.Buffer
tagClose := -1
tagStart := -1
for i, char := range text {
if char == '<' {
if buf == nil {
buf = bytes.NewBufferString(text)
buf.Reset()
}
buf.WriteString(text[tagClose+1 : i])
tagStart = i
} else if char == '>' && tagStart != -1 {
buf.WriteString(replacement)
tagClose = i
tagStart = -1
}
}
if buf == nil {
return text
}
buf.WriteString(text[tagClose+1:])
return buf.String()
}
// StringMD5Hex returns the hex encoded MD5 hash of data
func StringMD5Hex(data string) string {
hash := md5.New() //#nosec
hash.Write([]byte(data))
return fmt.Sprintf("%x", hash.Sum(nil))
}
// StringSHA1Base64 returns the base64 encoded SHA1 hash of data
func StringSHA1Base64(data string) string {
hash := sha1.Sum([]byte(data)) //#nosec
return base64.StdEncoding.EncodeToString(hash[:])
}
func StringAddURLParam(url, name, value string) string {
var separator string
if strings.IndexRune(url, '?') == -1 {
separator = "?"
} else {
separator = "&"
}
return url + separator + name + "=" + value
}
func StringConvertTime(timeString, formatIn, formatOut string) (resultTime string, err error) {
if timeString == "" {
return "", nil
}
t, err := time.Parse(formatIn, timeString)
if err != nil {
return "", err
}
return t.Format(formatOut), nil
}
func StringCSV(records [][]string) string {
var b strings.Builder
writer := csv.NewWriter(&b)
err := writer.WriteAll(records)
if err != nil {
return ""
}
return b.String()
}
func StringToInt(s string) int {
i, _ := strconv.ParseInt(s, 10, 64)
return int(i)
}
func StringToFloat(s string) float64 {
f, _ := strconv.ParseFloat(s, 64)
return f
}
func StringToBool(s string) bool {
b, _ := strconv.ParseBool(s)
return b
}
func StringInSlice(s string, slice []string) bool {
for i := range slice {
if slice[i] == s {
return true
}
}
return false
}
// StringJoinFormat formats every value in values with format
// and joins the result with sep as separator.
// values must be a slice of a formatable type
func StringJoinFormat(format string, values interface{}, sep string) string {
v := reflect.ValueOf(values)
if v.Kind() != reflect.Slice {
panic("values is not a slice")
}
var buffer bytes.Buffer
for i := 0; i < v.Len(); i++ {
if i > 0 {
buffer.WriteString(sep)
}
buffer.WriteString(fmt.Sprintf(format, v.Index(i).Interface()))
}
return buffer.String()
}
// StringJoin formats every value in values according to its default formatting
// and joins the result with sep as separator.
// values must be a slice of a formatable type
func StringJoin(values interface{}, sep string) string {
v := reflect.ValueOf(values)
if v.Kind() != reflect.Slice {
panic("values is not a slice")
}
var buffer bytes.Buffer
for i := 0; i < v.Len(); i++ {
if i > 0 {
buffer.WriteString(sep)
}
buffer.WriteString(fmt.Sprint(v.Index(i).Interface()))
}
return buffer.String()
}
func StringFormatBigInt(mem uint64) string {
switch {
case mem >= 10e12:
return fmt.Sprintf("%dT", mem/1e12)
case mem >= 1e12:
return strings.TrimSuffix(fmt.Sprintf("%.1fT", float64(mem)/1e12), ".0")
case mem >= 10e9:
return fmt.Sprintf("%dG", mem/1e9)
case mem >= 1e9:
return strings.TrimSuffix(fmt.Sprintf("%.1fG", float64(mem)/1e9), ".0")
case mem >= 10e6:
return fmt.Sprintf("%dM", mem/1e6)
case mem >= 1e6:
return strings.TrimSuffix(fmt.Sprintf("%.1fM", float64(mem)/1e6), ".0")
case mem >= 10e3:
return fmt.Sprintf("%dk", mem/1e3)
case mem >= 1e3:
return strings.TrimSuffix(fmt.Sprintf("%.1fk", float64(mem)/1e3), ".0")
}
return fmt.Sprintf("%d", mem)
}
func StringFormatMemory(mem uint64) string {
return StringFormatBigInt(mem) + "B"
}
func StringReplaceMulti(str string, fromTo ...string) string {
if len(fromTo)%2 != 0 {
panic("Need even number of fromTo arguments")
}
for i := 0; i < len(fromTo); i += 2 {
str = strings.Replace(str, fromTo[i], fromTo[i+1], -1)
}
return str
}
func StringToUpperCamelCase(str string) string {
var b strings.Builder
var last byte = '_'
for _, c := range []byte(str) {
if c != '_' {
if last == '_' {
c = byte(unicode.ToUpper(rune(c)))
} else {
c = byte(unicode.ToLower(rune(c)))
}
b.WriteByte(c)
}
last = c
}
return b.String()
}
func StringToLowerCamelCase(str string) string {
var b strings.Builder
var last byte
for _, c := range []byte(str) {
if c != '_' {
if last == '_' {
c = byte(unicode.ToUpper(rune(c)))
} else {
c = byte(unicode.ToLower(rune(c)))
}
b.WriteByte(c)
}
last = c
}
return b.String()
}
func StringMapSortedKeys(m map[string]string) []string {
keys := make([]string, 0, len(m))
for key := range m {
keys = append(keys, key)
}
sort.Strings(keys)
return keys
}
func StringMapGroupedNumberPostfixSortedKeys(m map[string]string) []string {
keys := make(StringGroupedNumberPostfixSorter, 0, len(m))
for key := range m {
keys = append(keys, key)
}
sort.Sort(keys)
return keys
}
func StringMapGroupedNumberPostfixSortedValues(m map[string]string) []string {
values := make(StringGroupedNumberPostfixSorter, 0, len(m))
for _, value := range m {
values = append(values, value)
}
sort.Sort(values)
return values
}
func StringEndsWithNumber(s string) bool {
if s == "" {
return false
}
c := s[len(s)-1]
return c >= '0' && c <= '9'
}
func StringSplitNumberPostfix(s string) (base, number string) {
if s == "" {
return "", ""
}
for i := len(s) - 1; i >= 0; i-- {
c := s[i]
if c < '0' || c > '9' {
if i == len(s)-1 {
return s, ""
}
return s[:i+1], s[i+1:]
}
}
return "", s
}
func StringSplitOnce(s, sep string) (pre, post string) {
parts := strings.SplitN(s, sep, 1)
if len(parts) == 2 {
return parts[0], parts[1]
} else {
return parts[0], ""
}
}
func StringSplitOnceChar(s string, sep byte) (pre, post string) {
i := strings.IndexByte(s, sep)
if i == -1 {
return s, ""
}
return s[:i], s[i+1:]
}
func StringSplitOnceRune(s string, sep rune) (pre, post string) {
sepIndex := -1
postSepIndex := -1
for i, c := range s {
if sepIndex != -1 {
postSepIndex = i
break // we got the index after the sep rune
}
if c == sep {
sepIndex = i
// continue to get index after the current UTF8 rune
}
}
if sepIndex == -1 {
return s, ""
}
return s[:sepIndex], s[postSepIndex:]
}
type StringGroupedNumberPostfixSorter []string
// Len is the number of elements in the collection.
func (s StringGroupedNumberPostfixSorter) Len() int {
return len(s)
}
// Less reports whether the element with
// index i should sort before the element with index j.
func (s StringGroupedNumberPostfixSorter) Less(i, j int) bool {
bi, ni := StringSplitNumberPostfix(s[i])
bj, nj := StringSplitNumberPostfix(s[j])
if bi == bj {
if len(ni) == len(nj) {
inti, _ := strconv.Atoi(ni)
intj, _ := strconv.Atoi(nj)
return inti < intj
} else {
return len(ni) < len(nj)
}
}
return bi < bj
}
// Swap swaps the elements with indexes i and j.
func (s StringGroupedNumberPostfixSorter) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
// Map a function on each element of a slice of strings.
func StringMap(f func(string) string, data []string) []string {
size := len(data)
result := make([]string, size, size)
for i := 0; i < size; i++ {
result[i] = f(data[i])
}
return result
}
// Filter out all strings where the function does not return true.
func StringFilter(f func(string) bool, data []string) []string {
result := make([]string, 0, 0)
for _, element := range data {
if f(element) {
result = append(result, element)
}
}
return result
}
// StringFindBetween returns the string between the first occurrences of the tokens start and stop.
// The remainder of the string after the stop token will be returned if found.
// If the tokens couldn't be found, then the whole string will be returned as remainder.
func StringFindBetween(s, start, stop string) (between, remainder string, found bool) {
begin := strings.Index(s, start)
if begin == -1 {
return "", s, false
}
between = s[begin+len(start):]
end := strings.Index(between, stop)
if end == -1 {
return "", s, false
}
return between[:end], s[begin+len(start)+end+len(stop):], true
}
// StringFind returns in found if token has been found in s,
// and returns the remaining string afte token in remainder.
// The whole string s will be returned if found is false.
func StringFind(s, token string) (remainder string, found bool) {
i := strings.Index(s, token)
if i == -1 {
return s, false
}
return s[i+len(token):], true
}
// StringSet wraps map[string]struct{} with some
// useful methods.
type StringSet map[string]struct{}
func (set StringSet) Has(s string) bool {
_, found := set[s]
return found
}
func (set StringSet) Set(s string) {
set[s] = struct{}{}
}
func (set StringSet) Delete(s string) {
delete(set, s)
}
func (set StringSet) Join(other StringSet) {
for s := range other {
set[s] = struct{}{}
}
}
func (set StringSet) Exclude(other StringSet) {
for s := range other {
delete(set, s)
}
}
func (set StringSet) Clone() StringSet {
clone := make(StringSet, len(set))
for s := range set {
clone[s] = struct{}{}
}
return clone
}
func (set StringSet) Sorted() []string {
list := make([]string, len(set))
i := 0
for s := range set {
list[i] = s
i++
}
sort.Strings(list)
return list
}
func (set StringSet) ReverseSorted() []string {
list := make([]string, len(set))
i := 0
for s := range set {
list[i] = s
i++
}
sort.Sort(sort.Reverse(sort.StringSlice(list)))
return list
}
// TwoSlicesSubtraction remove any string that A,B both contain from A and returns the remainder of A
func TwoSlicesSubtraction(A, B []string) []string {
remainder := make([]string, 0, len(A))
Range:
for _, sA := range A {
for _, sB := range B {
if sA == sB {
continue Range
}
}
remainder = append(remainder, sA)
}
return remainder
}