-
Notifications
You must be signed in to change notification settings - Fork 20
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
hanpengfei01
committed
Aug 11, 2023
1 parent
9bd378d
commit 73e178c
Showing
2 changed files
with
55 additions
and
0 deletions.
There are no files selected for viewing
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
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))) | ||
} |
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
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) | ||
} |