first commit
This commit is contained in:
53
internal/pkg/rand/rand.go
Normal file
53
internal/pkg/rand/rand.go
Normal file
@@ -0,0 +1,53 @@
|
||||
package rand
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
randv2 "math/rand/v2"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
|
||||
|
||||
func Bytes(n int) ([]byte, error) {
|
||||
b := make([]byte, n)
|
||||
nRead, err := rand.Read(b)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("bytes: %w", err)
|
||||
}
|
||||
if nRead < n {
|
||||
return nil, fmt.Errorf("bytes: didn't read enough random bytes")
|
||||
}
|
||||
return b, nil
|
||||
}
|
||||
|
||||
func String(n int) (string, error) {
|
||||
b, err := Bytes(n)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("string: %w", err)
|
||||
}
|
||||
return base64.URLEncoding.EncodeToString(b), nil
|
||||
}
|
||||
|
||||
func RandomInt(n int) string {
|
||||
letters := []byte("0123456789")
|
||||
l := len(letters)
|
||||
result := make([]byte, n)
|
||||
for i := range result {
|
||||
result[i] = letters[randv2.IntN(l)]
|
||||
}
|
||||
return string(result)
|
||||
}
|
||||
|
||||
func RandomString(n int) string {
|
||||
var sb strings.Builder
|
||||
k := len(alphabet)
|
||||
|
||||
for i := 0; i < n; i++ {
|
||||
c := alphabet[randv2.IntN(k)]
|
||||
sb.WriteByte(c)
|
||||
}
|
||||
|
||||
return sb.String()
|
||||
}
|
||||
Reference in New Issue
Block a user