Module random

This commit is contained in:
Benjamin VAUDOUR 2023-09-23 21:47:17 +02:00
parent 34cb5b19ca
commit d85d270274
1 changed files with 58 additions and 0 deletions

58
random/random.go Normal file
View File

@ -0,0 +1,58 @@
package random
import (
"math/rand"
"strings"
"time"
)
const (
Digit = "0123456789"
LowserCase = "abcdefghijklmnopqrstuvwxyz"
UpperCase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
Letter = LowserCase + UpperCase
AlphaNum = Digit + Letter
Special = " !\"#$%&'()*+-./:;<=>?@[\\]^_`{|}~"
All = AlphaNum + Special
)
func choice(charClass []string) string {
out := strings.Join(charClass, "")
if len(out) == 0 {
out = AlphaNum
}
return out
}
func randomer() *rand.Rand {
return rand.New(rand.NewSource(time.Now().UnixNano()))
}
// Randomize retourne un tableau de taille size
// et avec des valeurs aléatoires dans available.
func Randomize[T any](size int, available []T) (out []T) {
lc, r := len(available), randomer()
out = make([]T, size)
for i := range out {
out[i] = available[r.Intn(lc)]
}
return
}
// BytesKey génère une clé de bytes.
func BytesKey(size int, charClass ...string) []byte {
return Randomize(size, []byte(choice(charClass)))
}
// RunesKey génère une clé de runes.
func RunesKey(size int, charClass ...string) []rune {
return Randomize(size, []rune(choice(charClass)))
}
// Key génère une clé sous forme de string.
func Key(size int, charClass ...string) string {
return string(RunesKey(size, charClass...))
}