fix(string): fix division by zero (#684)

This commit is contained in:
Samuel Berthe
2025-09-25 04:21:56 +02:00
committed by GitHub
parent ec86b574ed
commit 268215359e
2 changed files with 15 additions and 0 deletions

View File

@@ -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)))))

View File

@@ -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) {