From d85d270274d4f8a2834f8d97b64dcd6411cf2348 Mon Sep 17 00:00:00 2001 From: Benjamin VAUDOUR Date: Sat, 23 Sep 2023 21:47:17 +0200 Subject: [PATCH] Module random --- random/random.go | 58 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 random/random.go 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...)) +}