Skip to content

Instantly share code, notes, and snippets.

@xh3b4sd
Created October 3, 2023 12:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xh3b4sd/c79e35919c75b7229a7f8a5303fb70fe to your computer and use it in GitHub Desktop.
Save xh3b4sd/c79e35919c75b7229a7f8a5303fb70fe to your computer and use it in GitHub Desktop.
generate random strings
package random
import (
"crypto/rand"
"math/big"
)
const (
Length = 5
Number = "0123456789"
Letter = "abcdefghijklmnopqrstuvwxyz"
)
const (
all = Number + Letter
)
func New() string {
var ran string
for i := 0; i < Length; i++ {
ind, err := rand.Int(rand.Reader, big.NewInt(int64(len(all))))
if err != nil {
panic(err)
}
ran += string(all[ind.Int64()])
}
return ran
}
package random
import (
"sync"
"testing"
)
func Test_Random_New(t *testing.T) {
mut := sync.Mutex{}
see := map[string]struct{}{}
for i := 0; i < 1000; i++ {
go func() {
a := New()
b := New()
if a == "" || b == "" {
panic("random strings must not be empty")
}
if len(a) != Length || len(b) != Length {
panic("random strings must have the right length")
}
if a == b {
panic("random strings must be unique")
}
{
mut.Lock()
}
{
_, exi := see[a]
if exi {
panic("random strings must not be duplicated")
}
see[a] = struct{}{}
}
{
_, exi := see[b]
if exi {
panic("random strings must not be duplicated")
}
see[b] = struct{}{}
}
{
mut.Unlock()
}
}()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment