diff --git a/random/random.go b/random/random.go new file mode 100644 index 0000000..8fe96be --- /dev/null +++ b/random/random.go @@ -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...)) +}