3x-ui/util/random/random.go
Ilya Kryuchkov 6041d10e3d
Some checks are pending
Release 3X-UI / build (386) (push) Waiting to run
Release 3X-UI / build (amd64) (push) Waiting to run
Release 3X-UI / build (arm64) (push) Waiting to run
Release 3X-UI / build (armv5) (push) Waiting to run
Release 3X-UI / build (armv6) (push) Waiting to run
Release 3X-UI / build (armv7) (push) Waiting to run
Release 3X-UI / build (s390x) (push) Waiting to run
Release 3X-UI / Build for Windows (push) Waiting to run
Refactor code and fix linter warnings (#3627)
* refactor: use any instead of empty interface

* refactor: code cleanup
2026-01-05 05:54:56 +01:00

61 lines
1.5 KiB
Go

// Package random provides utilities for generating random strings and numbers.
package random
import (
"crypto/rand"
"math/big"
)
var (
numSeq [10]rune
lowerSeq [26]rune
upperSeq [26]rune
numLowerSeq [36]rune
numUpperSeq [36]rune
allSeq [62]rune
)
// init initializes the character sequences used for random string generation.
// It sets up arrays for numbers, lowercase letters, uppercase letters, and combinations.
func init() {
for i := range 10 {
numSeq[i] = rune('0' + i)
}
for i := range 26 {
lowerSeq[i] = rune('a' + i)
upperSeq[i] = rune('A' + i)
}
copy(numLowerSeq[:], numSeq[:])
copy(numLowerSeq[len(numSeq):], lowerSeq[:])
copy(numUpperSeq[:], numSeq[:])
copy(numUpperSeq[len(numSeq):], upperSeq[:])
copy(allSeq[:], numSeq[:])
copy(allSeq[len(numSeq):], lowerSeq[:])
copy(allSeq[len(numSeq)+len(lowerSeq):], upperSeq[:])
}
// Seq generates a random string of length n containing alphanumeric characters (numbers, lowercase and uppercase letters).
func Seq(n int) string {
runes := make([]rune, n)
for i := range n {
idx, err := rand.Int(rand.Reader, big.NewInt(int64(len(allSeq))))
if err != nil {
panic("crypto/rand failed: " + err.Error())
}
runes[i] = allSeq[idx.Int64()]
}
return string(runes)
}
// Num generates a random integer between 0 and n-1.
func Num(n int) int {
bn := big.NewInt(int64(n))
r, err := rand.Int(rand.Reader, bn)
if err != nil {
panic("crypto/rand failed: " + err.Error())
}
return int(r.Int64())
}