Created
October 3, 2023 12:00
-
-
Save xh3b4sd/c79e35919c75b7229a7f8a5303fb70fe to your computer and use it in GitHub Desktop.
generate random strings
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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