From 268215359e7eec34a8c0d34476472240c8a9284f Mon Sep 17 00:00:00 2001 From: Samuel Berthe Date: Thu, 25 Sep 2025 04:21:56 +0200 Subject: [PATCH] fix(string): fix division by zero (#684) --- string.go | 11 +++++++++++ string_test.go | 4 ++++ 2 files changed, 15 insertions(+) diff --git a/string.go b/string.go index f4aa85c..19a3c45 100644 --- a/string.go +++ b/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))))) diff --git a/string_test.go b/string_test.go index ba7f7a2..30aeca2 100644 --- a/string_test.go +++ b/string_test.go @@ -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) {