Skip to content

Commit

Permalink
Add random string
Browse files Browse the repository at this point in the history
  • Loading branch information
hanpengfei01 committed Aug 11, 2023
1 parent 9bd378d commit 73e178c
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
43 changes: 43 additions & 0 deletions utils/string.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package utils

import (
"math/rand"
"strings"
"time"
"unsafe"
)

var randSource rand.Source

const (
bits = 6
mask = 1<<bits - 1
maxIndex = 63 / bits

characters = "abcdefghijkmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ23456789"
)

func init() {
randSource = rand.NewSource(time.Now().UnixNano())
}

// RandString
// - param n: suggest at least 10 to avoid conflict
//
// referred to https://stackoverflow.com/questions/22892120/how-to-generate-a-random-string-of-a-fixed-length-in-go
func RandString(n int) string {
b := make([]byte, n)
for i, cache, remain := n-1, randSource.Int63(), maxIndex; i >= 0; {
if remain == 0 {
cache, remain = randSource.Int63(), maxIndex
}
if idx := int(cache & mask); idx < len(characters) {
b[i] = characters[idx]
i--
}
cache >>= bits
remain--
}

return strings.ToLower(*(*string)(unsafe.Pointer(&b)))
}
12 changes: 12 additions & 0 deletions utils/string_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package utils

import (
"testing"

"github.com/stretchr/testify/assert"
)

func TestRandString(t *testing.T) {
res := RandString(6)
assert.Equal(t, len(res), 6)
}

0 comments on commit 73e178c

Please sign in to comment.