]> git repos ~mattia - go-utility.git/commitdiff
+RandString v0.0.9
authorMattia Cabrini <dev@mattiacabrini.com>
Wed, 23 Apr 2025 16:11:33 +0000 (18:11 +0200)
committerMattia Cabrini <dev@mattiacabrini.com>
Wed, 23 Apr 2025 16:11:33 +0000 (18:11 +0200)
rand_string.go [new file with mode: 0644]

diff --git a/rand_string.go b/rand_string.go
new file mode 100644 (file)
index 0000000..597aaeb
--- /dev/null
@@ -0,0 +1,40 @@
+// Copyright (c) 2023 Mattia Cabrini
+// SPDX-License-Identifier: MIT
+
+package utility
+
+import (
+       "crypto/rand"
+       "fmt"
+)
+
+func RandString(n int) (string, error) {
+       if n <= 0 {
+               return "", fmt.Errorf("lunghezza non valida: %d", n)
+       }
+
+       const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
+       const mask = 63
+       const maxByte = 255 - (255 % len(charset))
+
+       b := make([]byte, n)
+       i := 0
+       for i < n {
+               buf := make([]byte, 1)
+               if _, err := rand.Read(buf); err != nil {
+                       return "", AppendError(err)
+               }
+
+               if int(buf[0]) > maxByte {
+                       continue
+               }
+
+               idx := int(buf[0] & mask)
+               if idx < len(charset) {
+                       b[i] = charset[idx]
+                       i++
+               }
+       }
+
+       return string(b), nil
+}