mirror of
https://github.com/samber/lo.git
synced 2025-09-26 20:11:13 +08:00
fix(string): fix division by zero (#684)
This commit is contained in:
11
string.go
11
string.go
@@ -43,6 +43,17 @@ func RandomString(size int, charset []rune) string {
|
||||
// see https://stackoverflow.com/questions/22892120/how-to-generate-a-random-string-of-a-fixed-length-in-go
|
||||
sb := strings.Builder{}
|
||||
sb.Grow(size)
|
||||
|
||||
if len(charset) == 1 {
|
||||
// Edge case, because if the charset is a single character,
|
||||
// it will panic below (divide by zero).
|
||||
// -> https://github.com/samber/lo/issues/679
|
||||
for i := 0; i < size; i++ {
|
||||
sb.WriteRune(charset[0])
|
||||
}
|
||||
return sb.String()
|
||||
}
|
||||
|
||||
// Calculate the number of bits required to represent the charset,
|
||||
// e.g., for 62 characters, it would need 6 bits (since 62 -> 64 = 2^6)
|
||||
letterIDBits := int(math.Log2(float64(nearestPowerOfTwo(len(charset)))))
|
||||
|
@@ -29,6 +29,10 @@ func TestRandomString(t *testing.T) {
|
||||
|
||||
is.PanicsWithValue("lo.RandomString: charset must not be empty", func() { RandomString(100, []rune{}) })
|
||||
is.PanicsWithValue("lo.RandomString: size must be greater than 0", func() { RandomString(0, LowerCaseLettersCharset) })
|
||||
|
||||
str4 := RandomString(10, []rune{65})
|
||||
is.Equal(10, RuneLength(str4))
|
||||
is.Subset([]rune{65, 65, 65, 65, 65, 65, 65, 65, 65, 65}, []rune(str4))
|
||||
}
|
||||
|
||||
func TestChunkString(t *testing.T) {
|
||||
|
Reference in New Issue
Block a user