fix(package): [random] handle non-positive unique slice lengths (#402)

This commit is contained in:
Yusuf Efe authored and GitHub committed 2026-10-22 10:29:10 +08:00
1 parent ef22b5b339
commit 19ccb13893
2 files changed
+18 -1

No files matched your search

+14
View File
@@ -0,0 +1,14 @@
package random
import "testing"
func TestUniqueRandomSlicesNonPositiveLength(t *testing.T) {
for _, length := range []int{-1, 0} {
if got := RandUniqueIntSlice(length, 1, 10); len(got) != 0 {
t.Errorf("unexpected integers: %v", got)
}
if got := RandFloats(length, 1, 10, 2); len(got) != 0 {
t.Errorf("unexpected floats: %v", got)
}
}
}
+4 -1
View File
@@ -98,7 +98,7 @@ func RandIntSlice(length, min, max int) []int {
// RandUniqueIntSlice generate a slice of random int of length that do not repeat. // RandUniqueIntSlice generate a slice of random int of length that do not repeat.
// Play: https://go.dev/play/p/uBkRSOz73Ec // Play: https://go.dev/play/p/uBkRSOz73Ec
func RandUniqueIntSlice(length, min, max int) []int { func RandUniqueIntSlice(length, min, max int) []int {
if min > max { if length <= 0 || min > max {
return []int{} return []int{}
} }
if length > max-min { if length > max-min {
@@ -139,6 +139,9 @@ func RandFloat(min, max float64, precision int) float64 {
// RandFloats generate a slice of random float64 numbers of length that do not repeat. // RandFloats generate a slice of random float64 numbers of length that do not repeat.
// Play: https://go.dev/play/p/I3yndUQ-rhh // Play: https://go.dev/play/p/I3yndUQ-rhh
func RandFloats(length int, min, max float64, precision int) []float64 { func RandFloats(length int, min, max float64, precision int) []float64 {
if length <= 0 {
return []float64{}
}
if max < min { if max < min {
min, max = max, min min, max = max, min
} }