src

Go monorepo.
Log | Files | Refs

commit cf572d822632779429ea666b57c67a76c11b8b6b
parent 1523337fe467711f82fb521e326f2b122eb30d3b
Author: dwrz <dwrz@dwrz.net>
Date:   Tue, 10 Jan 2023 01:25:09 +0000

Add randstr pkg

Diffstat:
Apkg/randstr/randstr.go | 25+++++++++++++++++++++++++
Apkg/randstr/randstr_test.go | 15+++++++++++++++
2 files changed, 40 insertions(+), 0 deletions(-)

diff --git a/pkg/randstr/randstr.go b/pkg/randstr/randstr.go @@ -0,0 +1,25 @@ +package randstr + +import ( + "math/rand" + "time" +) + +const ( + Alphanumeric = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" + Numeric string = "0123456789" +) + +var random = rand.New(rand.NewSource(time.Now().UnixNano())) + +func Charset(charset string, length int) string { + var b = make([]byte, length) + + random.Read(b) + + for i := 0; i < length; i++ { + b[i] = charset[int(b[i])%len(charset)] + } + + return string(b) +} diff --git a/pkg/randstr/randstr_test.go b/pkg/randstr/randstr_test.go @@ -0,0 +1,15 @@ +package randstr + +import "testing" + +func BenchmarkCharsetAlphanumeric(b *testing.B) { + for i := 0; i < b.N; i++ { + Charset(Alphanumeric, 100) + } +} + +func BenchmarkCharsetNumeric(b *testing.B) { + for i := 0; i < b.N; i++ { + Charset(Numeric, 10) + } +}