-
Notifications
You must be signed in to change notification settings - Fork 0
/
strings.go
483 lines (425 loc) · 10.4 KB
/
strings.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
package utilz
import (
"bytes"
"fmt"
"regexp"
"sort"
"strconv"
"strings"
"github.com/miekg/dns"
)
type Replacer struct {
s string
n int
}
func NewReplacer(s string, n int) *Replacer {
return &Replacer{
s: s,
n: n,
}
}
//
func (re *Replacer) Replace(old, new string) *Replacer {
re.s = strings.Replace(re.s, old, new, re.n)
return re
}
func (re *Replacer) String() string {
return re.s
}
var illegalFileNameCharacters = regexp.MustCompile(`[^[a-zA-Z0-9]-_]`)
func SanitizeFileNamePart(part string) string {
part = strings.Replace(part, "/", "-", -1)
part = illegalFileNameCharacters.ReplaceAllString(part, "")
return part
}
// SliceContains returns true if the provided slice of strings contains the element
func SliceContains(slice []string, element string) bool {
for _, elem := range slice {
if strings.EqualFold(element, elem) {
return true
}
}
return false
}
// IntSliceContains returns true if the provided slice of ints contains the element
func IntSliceContains(slice []int, element int) bool {
for _, elem := range slice {
if element == elem {
return true
}
}
return false
}
// ConcatBytesFromStrings concatenates multiple strings into one array of bytes
func ConcatBytesFromStrings(strs ...string) ([]byte, error) {
var concatBytesBuffer bytes.Buffer
for _, stringValue := range strs {
_, err := concatBytesBuffer.WriteString(stringValue)
if err != nil {
return []byte{}, err
}
}
return concatBytesBuffer.Bytes(), nil
}
// NewUniqueElements removes elements that have duplicates in the original or new elements.
func NewUniqueElements(orig []string, add ...string) []string {
var n []string
for _, av := range add {
found := false
s := av
// Check the original slice for duplicates
for _, ov := range orig {
if s == ov {
found = true
break
}
}
// Check that we didn't already add it in
if !found {
for _, nv := range n {
if s == nv {
found = true
break
}
}
}
// If no duplicates were found, add the entry in
if !found {
n = append(n, s)
}
}
return n
}
// UniqueAppend behaves like the Go append, but does not add duplicate elements.
func UniqueAppend(orig []string, add ...string) []string {
return append(orig, NewUniqueElements(orig, add...)...)
}
// Deduplicate returns a deduplicated copy of a.
func Deduplicate(a []string) []string {
var res []string
res = UniqueAppend(res, a...)
return res
}
type ElasticStringIterator struct {
arr []string
}
func NewElasticStringIterator(arr []string) *ElasticStringIterator {
return &ElasticStringIterator{
arr: arr,
}
}
func (e *ElasticStringIterator) Iterate(callback func(s string) ([]string, bool)) {
tot := len(e.arr)
for i := 0; i < tot; i++ {
x := e.arr[i]
toAdd, goOn := callback(x)
if !goOn {
break
}
if toAdd != nil {
for _, addThis := range toAdd {
e.arr = append(e.arr, addThis)
tot++
}
}
}
}
func GetAddedRemoved(previous []string, next []string) (added []string, removed []string) {
for _, prev := range previous {
if !SliceContains(next, prev) {
removed = append(removed, prev)
}
}
for _, nx := range next {
if !SliceContains(previous, nx) {
added = append(added, nx)
}
}
return
}
var ConstantPredeterminedLength = 60
func CustomConstantLength(ln int, s string) string {
if len(s) < ln {
s += ReturnNSpaces(ln - len(s))
return s
}
return s
}
func ConstantLength(s string) string {
if len(s) < ConstantPredeterminedLength {
s += ReturnNSpaces(ConstantPredeterminedLength - len(s))
return s
}
return s
}
func RepeatString(n int, char string) string {
var res string
for i := 0; i < n; i++ {
res += char
}
return res
}
func ReturnNSpaces(n int) string {
return RepeatString(n, " ")
}
func IndentWithSpaces(n int, s string) string {
return ReturnNSpaces(n) + s
}
func NewSpacesIndenter(spaceWidth int) func(n int, s string) string {
return func(n int, s string) string {
return ReturnNSpaces(n*spaceWidth) + s
}
}
func IndentWithTabs(n int, s string) string {
return RepeatString(n, " ") + s
}
func IsNotAnyOf(s string, candidates ...string) bool {
return !IsAnyOf(s, candidates...)
}
func IsAnyOf(s string, candidates ...string) bool {
for _, v := range candidates {
if s == v {
return true
}
}
return false
}
// Reverses a string
func ReverseString(s string) string {
runes := []rune(s)
for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
runes[i], runes[j] = runes[j], runes[i]
}
return string(runes)
}
// ReverseStringSlice reverses a string slice
func ReverseStringSlice(ss []string) {
last := len(ss) - 1
for i := 0; i < len(ss)/2; i++ {
ss[i], ss[last-i] = ss[last-i], ss[i]
}
}
// ReverseDNSLabels reverses the labels of a DNS, and returns the DNS name.
func ReverseDNSLabels(hostname string) string {
labels := dns.SplitDomainName(hostname)
ReverseStringSlice(labels)
reversed := strings.Join(labels, ".")
return reversed
}
// HasAnySuffixDottedOrNot returns true if the string s has any of the
// suffixes, whether they are in the .<suffix> or <suffix> variant.
func HasAnySuffixDottedOrNot(s string, suffixes ...string) bool {
newSuffixes := make([]string, 0)
for _, suffixCandidate := range suffixes {
suffix := strings.TrimPrefix(suffixCandidate, ".")
newSuffixes = append(newSuffixes,
suffix,
"."+suffix,
)
}
return HasAnySuffix(s, newSuffixes...)
}
// HasAnySuffix returns true if the string s has any of the prefixes
// provided.
func HasAnySuffix(s string, suffixes ...string) bool {
for _, suffix := range suffixes {
if strings.HasSuffix(s, suffix) {
return true
}
}
return false
}
// TrimDNSLabelFromBeginning removes one label from the DNS name,
// and returns the new DNS name and the removed label.
func TrimDNSLabelFromBeginning(name string) (string, string) {
labels := dns.SplitDomainName(name)
if len(labels) == 0 {
// TODO: what to return???
return "", name
}
labels = labels[1:]
return strings.Join(labels, "."), labels[0]
}
func InitDomainExtensions(path string) {
domainExtensions = func() []string {
extensions := make([]string, 0)
err := ReadFileLinesAsString(
path,
func(ext string) bool {
extensions = append(extensions, ext)
return true
})
if err != nil {
panic(err)
}
// sort by length:
sort.Strings(extensions)
// invert to have the longer extensions first:
sort.Sort(sort.Reverse(sort.StringSlice(extensions)))
return extensions
}()
}
var domainExtensions []string
// GetDomainExtension returns the domain extension (among the known ones)
// of the provided host names.
func GetDomainExtension(name string) string {
for _, ext := range domainExtensions {
if strings.HasSuffix(name, ext) {
return ext
}
}
return ""
}
// GetBaseDomain returns the first label after the domain extension,
// ad the domain extension.
//
// e.g. example.com -> example + .com
// e.g. subdomain.example.com -> example + .com
//
// e.g. example.co.uk -> example + .co.uk
// e.g. subdomain.example.co.uk -> example + .co.uk
func GetBaseDomain(name string) (string, string) {
ext := GetDomainExtension(name)
if ext == "" {
panic(Sf("no extension found for %q", name))
}
hostPart := strings.TrimSuffix(name, ext)
trimmed := hostPart
for {
remainingLabels := dns.CountLabel(hostPart)
if remainingLabels > 1 {
hostPart, trimmed = TrimDNSLabelFromBeginning(hostPart)
} else {
break
}
}
return trimmed, ext
}
// TrimFrom removes the string `after` from the string `s`
// and anything that comes after it.
func TrimFrom(s string, after string) string {
parts := strings.Split(s, after)
if len(parts) > 0 {
return parts[0]
}
return s
}
// FilterModify returns a new array containing the values of `ss` after they
// have been processed by the func `filter`; no modification to `ss` is done.
func FilterModify(ss []string, filter func(s string) string) []string {
filtered := make([]string, 0)
for _, s := range ss {
filtered = append(filtered, filter(s))
}
return filtered
}
// FilterExclude returns a new array of items that do not match the filter func;
// for any item in `ss`, if the `filter` func returns true,
// then the item will be excluded from the result slice.
func FilterExclude(ss []string, filter func(s string) bool) []string {
filtered := make([]string, 0)
for _, s := range ss {
exclude := filter(s)
if !exclude {
filtered = append(filtered, s)
}
}
return filtered
}
func CloneSlice(sl []string) []string {
clone := make([]string, len(sl))
copy(clone, sl)
return clone
}
func SplitStringSlice(parts int, slice []string) [][]string {
var divided [][]string
chunkSize := (len(slice) + parts - 1) / parts
for i := 0; i < len(slice); i += chunkSize {
end := i + chunkSize
if end > len(slice) {
end = len(slice)
}
divided = append(divided, slice[i:end])
}
return divided
}
func AnyIsEmptyString(slice ...string) bool {
for _, v := range slice {
if v == "" {
return true
}
}
return false
}
func IsLastUnicode(s string) bool {
return s == "10FFFF"
}
func MustParseUnicode(code string) string {
parsed, err := ParseUnicode(code)
if err != nil {
panic(fmt.Errorf("error for %s: %s", code, err))
}
return string(parsed)
}
func MustParseUnicodeAsRune(code string) rune {
parsed, err := ParseUnicode(code)
if err != nil {
panic(fmt.Errorf("error for %s: %s", code, err))
}
return parsed
}
func ParseUnicode(code string) (rune, error) {
// Trim eventual `\u` prefix:
code = strings.TrimPrefix(code, `\u`)
unquoted, _, _, err := strconv.UnquoteChar(`\u`+code, '\'')
if err != nil {
return ' ', err
}
return unquoted, nil
}
func SplitStringByRune(s string) []rune {
var res []rune
IterateStringAsRunes(s, func(r rune) bool {
res = append(res, r)
return true
})
return res
}
func SplitStringByRuneAsStringSlice(s string) []string {
var res []string
IterateStringAsRunes(s, func(r rune) bool {
res = append(res, string(r))
return true
})
return res
}
func IterateStringAsRunes(s string, callback func(r rune) bool) {
for _, rn := range s {
//fmt.Printf("%d: %c\n", i, rn)
doContinue := callback(rn)
if !doContinue {
return
}
}
}
func ToLower(s string) string {
return strings.ToLower(s)
}
func ToTitle(s string) string {
return strings.ToTitle(s)
}
func ToStringKeyVals(keyvals ...string) (keys []string, vals []string) {
if len(keyvals) == 0 {
return
}
for i := 0; i < len(keyvals); i += 2 {
k := keyvals[i]
var v = "MISSING"
if i+1 < len(keyvals) {
v = keyvals[i+1]
}
keys = append(keys, k)
vals = append(vals, v)
}
return
}