-
Notifications
You must be signed in to change notification settings - Fork 0
/
strings.go
64 lines (55 loc) · 1.54 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
package strings
import (
"crypto/rand"
"strings"
)
const (
alphabeticBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
hexadecimalBytes = "abcdef1234567890"
letterIdxBits = 6
letterIdxMask = 1<<letterIdxBits - 1
)
// RandAlphabeticString Generator function of a random series of characters
// Uses a-zA-Z character set
func RandAlphabeticString(n int) string {
return randString(n, alphabeticBytes)
}
// RandHexAlphaNumericString Generator function of a random series of characters
// Uses a-f0-9 character set
func RandHexAlphaNumericString(n int) string {
return randString(n, hexadecimalBytes)
}
// From https://stackoverflow.com/a/35615565
func randString(n int, characterSet string) string {
if n <= 0 {
return ""
}
result := make([]byte, n)
bufferSize := int(float64(n) * 1.3)
for i, j, randomBytes := 0, 0, []byte{}; i < n; j++ {
if j%bufferSize == 0 {
randomBytes = mustSecureRandomBytes(bufferSize)
}
if idx := int(randomBytes[j%n] & letterIdxMask); idx < len(characterSet) {
result[i] = characterSet[idx]
i++
}
}
return string(result)
}
// mustSecureRandomBytes returns the requested number of bytes using crypto/rand
func mustSecureRandomBytes(length int) []byte {
var randomBytes = make([]byte, length)
// #nosec G104 -- Ignoring for now
rand.Read(randomBytes)
return randomBytes
}
// Append takes a string and appends a string to it
func Append(s string, args ...string) string {
var sb strings.Builder
sb.WriteString(s)
for _, arg := range args {
sb.WriteString(arg)
}
return sb.String()
}