From d65c22fe116931bb231b4d13e18c1f451d6af7a1 Mon Sep 17 00:00:00 2001 From: Mattia Cabrini Date: Wed, 23 Apr 2025 18:11:33 +0200 Subject: [PATCH] +RandString --- rand_string.go | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 rand_string.go diff --git a/rand_string.go b/rand_string.go new file mode 100644 index 0000000..597aaeb --- /dev/null +++ b/rand_string.go @@ -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 +} -- 2.43.0