-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: introduce random package (#58)
random package generate random string
- Loading branch information
1 parent
da50cb3
commit 61ff285
Showing
2 changed files
with
56 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,32 @@ | ||
package random | ||
|
||
import ( | ||
"crypto/rand" | ||
"io" | ||
) | ||
|
||
func GenerateAlphabets(length int) string { | ||
const letters = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" | ||
return generateRandomString(letters, length) | ||
} | ||
|
||
func GenerateAlphabetsLowerCase(length int) string { | ||
const letters = "abcdefghijkmnopqrstuvwxyz" | ||
return generateRandomString(letters, length) | ||
} | ||
|
||
func GenerateBase58(length int) string { | ||
const letters = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" | ||
return generateRandomString(letters, length) | ||
} | ||
|
||
func generateRandomString(letters string, length int) string { | ||
b := make([]byte, length) | ||
_, _ = io.ReadFull(rand.Reader, b) | ||
|
||
var result string | ||
for _, v := range b { | ||
result += string(letters[int(v)%len(letters)]) | ||
} | ||
return result | ||
} |
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,24 @@ | ||
package random_test | ||
|
||
import ( | ||
"testing" | ||
|
||
"github.com/stretchr/testify/assert" | ||
|
||
"github.com/tier4/x-go/random" | ||
) | ||
|
||
func TestGenerateAlphabets(t *testing.T) { | ||
t.Parallel() | ||
assert.Regexp(t, "^[a-zA-Z]{50}$", random.GenerateAlphabets(50)) | ||
} | ||
|
||
func TestGenerateAlphabetsLowerCase(t *testing.T) { | ||
t.Parallel() | ||
assert.Regexp(t, "^[a-z]{50}$", random.GenerateAlphabetsLowerCase(50)) | ||
} | ||
|
||
func TestGenerateBase58(t *testing.T) { | ||
t.Parallel() | ||
assert.Regexp(t, "^[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{50}$", random.GenerateBase58(50)) | ||
} |