Module random
This commit is contained in:
parent
34cb5b19ca
commit
d85d270274
58
random/random.go
Normal file
58
random/random.go
Normal 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...))
|
||||
}
|
Loading…
Reference in New Issue
Block a user