Refactor pkg/common, Fixes #11599
Signed-off-by: Antonio Murdaca <me@runcom.ninja>
This commit is contained in:
parent
6a6ba3da1d
commit
4dd569ee0f
7 changed files with 97 additions and 60 deletions
1
stringutils/README.md
Normal file
1
stringutils/README.md
Normal file
|
@ -0,0 +1 @@
|
|||
This package provides helper functions for dealing with strings
|
43
stringutils/stringutils.go
Normal file
43
stringutils/stringutils.go
Normal file
|
@ -0,0 +1,43 @@
|
|||
package stringutils
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"io"
|
||||
mathrand "math/rand"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Generate 32 chars random string
|
||||
func GenerateRandomString() string {
|
||||
id := make([]byte, 32)
|
||||
|
||||
if _, err := io.ReadFull(rand.Reader, id); err != nil {
|
||||
panic(err) // This shouldn't happen
|
||||
}
|
||||
return hex.EncodeToString(id)
|
||||
}
|
||||
|
||||
// Generate alpha only random stirng with length n
|
||||
func GenerateRandomAlphaOnlyString(n int) string {
|
||||
// make a really long string
|
||||
letters := []byte("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
|
||||
b := make([]byte, n)
|
||||
r := mathrand.New(mathrand.NewSource(time.Now().UTC().UnixNano()))
|
||||
for i := range b {
|
||||
b[i] = letters[r.Intn(len(letters))]
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
|
||||
// Generate Ascii random stirng with length n
|
||||
func GenerateRandomAsciiString(n int) string {
|
||||
chars := "abcdefghijklmnopqrstuvwxyz" +
|
||||
"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
|
||||
"~!@#$%^&*()-_+={}[]\\|<,>.?/\"';:` "
|
||||
res := make([]byte, n)
|
||||
for i := 0; i < n; i++ {
|
||||
res[i] = chars[mathrand.Intn(len(chars))]
|
||||
}
|
||||
return string(res)
|
||||
}
|
25
stringutils/stringutils_test.go
Normal file
25
stringutils/stringutils_test.go
Normal file
|
@ -0,0 +1,25 @@
|
|||
package stringutils
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestRandomString(t *testing.T) {
|
||||
str := GenerateRandomString()
|
||||
if len(str) != 64 {
|
||||
t.Fatalf("Id returned is incorrect: %s", str)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRandomStringUniqueness(t *testing.T) {
|
||||
repeats := 25
|
||||
set := make(map[string]struct{}, repeats)
|
||||
for i := 0; i < repeats; i = i + 1 {
|
||||
str := GenerateRandomString()
|
||||
if len(str) != 64 {
|
||||
t.Fatalf("Id returned is incorrect: %s", str)
|
||||
}
|
||||
if _, ok := set[str]; ok {
|
||||
t.Fatalf("Random number is repeated")
|
||||
}
|
||||
set[str] = struct{}{}
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue