/
lib.go
235 lines (188 loc) · 4.59 KB
/
lib.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
package main
import (
"bytes"
"crypto/sha256"
"fmt"
"math"
"math/rand"
"os"
"os/user"
"regexp"
"strconv"
"strings"
"time"
)
// UserHome builds path with user home path
func UserHome(s ...string) string {
user, err := user.Current()
if err != nil {
panic(err)
}
dir := user.HomeDir
if len(s) == 0 {
return dir
}
if []rune(s[0])[0] != '/' {
return dir + "/" + s[0]
}
return dir + s[0]
}
// StringSliceContain search the string slice and see if it contains the searched word, match from first character
func StringSliceContain(strSlice []string, strSearch string) bool {
strSearch = strings.Replace(strSearch, "\\", "/", -1)
for _, str := range strSlice {
str = strings.Replace(str, "\\", "/", -1)
if strings.Index(strSearch, str) == 0 {
return true
}
}
return false
}
// GenerateString create random new string for a certain length
// https://stackoverflow.com/questions/22892120/how-to-generate-a-random-string-of-a-fixed-length-in-go
func GenerateString(n int) string {
// only alpha-numeric
const letterBytes = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
// slightly less deterministic randomness
r := rand.New(rand.NewSource(time.Now().UnixNano()))
b := make([]byte, n)
for i := range b {
b[i] = letterBytes[r.Intn(len(letterBytes))]
}
return string(b)
}
// SHA256Iter iterate password and salt x times, return hex result
func SHA256Iter(password, salt string, iter int) string {
str := password + ":" + salt
bstr := []byte(str)
var bstrx [sha256.Size]byte
for i := 0; i < iter; i++ {
bstrx = sha256.Sum256(bstr)
bstr = bstrx[0:32]
}
return fmt.Sprintf("%x", bstr)
}
// NewUUIDV4 generate uuid version 4
func NewUUIDV4() (string, error) {
str := strings.Split("0123456789abcdef", "")
a := []string{}
t := time.Now().UnixNano()
rand.Seed(t)
for i := 0; i < 36; i++ {
a = append(a, str[rand.Intn(16)])
}
b := strings.Join(a, "")
uuid := fmt.Sprintf("%s-%s-%s-%s-%s", b[0:8], b[9:13], b[14:18], b[19:23], b[24:36])
return uuid, nil
}
var chunkifyRegexp = regexp.MustCompile(`(\d+|\D+)`)
func chunkify(s string) []string {
return chunkifyRegexp.FindAllString(s, -1)
}
// faster than chunkify x2~5 without use of regex
func chunkifyX(line string) []string {
var buf bytes.Buffer
var isText bool
var flip bool
for i, r := range line {
// first chr
if i == 0 {
if r < 48 || r > 57 {
isText = true
}
}
if r >= 48 && r <= 57 {
// 0-9
if isText {
flip = true
}
isText = false
} else {
if !isText {
flip = true
}
isText = true
}
if flip {
buf.WriteString("\n")
}
buf.WriteRune(r)
flip = false
}
return strings.Split(buf.String(), "\n")
}
// AlphaNumCaseCompare returns true if the first string precedes the second one according to natural order
// https://github.com/facette/natsort/blob/master/natsort.go
func AlphaNumCaseCompare(a, b string) bool {
a = strings.ToLower(a)
b = strings.ToLower(b)
chunksA := chunkifyX(a)
chunksB := chunkifyX(b)
nChunksA := len(chunksA)
nChunksB := len(chunksB)
for i := range chunksA {
if i >= nChunksB {
return false
}
aInt, aErr := strconv.Atoi(chunksA[i])
bInt, bErr := strconv.Atoi(chunksB[i])
// If both chunks are numeric, compare them as integers
if aErr == nil && bErr == nil {
if aInt == bInt {
if i == nChunksA-1 {
// We reached the last chunk of A, thus B is greater than A
return true
} else if i == nChunksB-1 {
// We reached the last chunk of B, thus A is greater than B
return false
}
continue
}
return aInt < bInt
}
// So far both strings are equal, continue to next chunk
if chunksA[i] == chunksB[i] {
if i == nChunksA-1 {
// We reached the last chunk of A, thus B is greater than A
return true
} else if i == nChunksB-1 {
// We reached the last chunk of B, thus A is greater than B
return false
}
continue
}
return chunksA[i] < chunksB[i]
}
return false
}
// IsFileExists returns whether the given file or directory exists
func IsFileExists(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
return true, nil
}
if os.IsNotExist(err) {
return false, nil
}
return true, err
}
// MathRound round the number
func MathRound(x float64) float64 {
t := math.Trunc(x)
if math.Abs(x-t) >= 0.5 {
return t + math.Copysign(1, x)
}
return t
}
// StringSliceFlatten removes any zero space string in slice and trim leading, trailing spaces
func StringSliceFlatten(in []string) []string {
ss := []string{}
for _, s := range in {
s = strings.TrimSpace(s)
if len(s) == 0 {
continue
}
ss = append(ss, s)
}
return ss
}