From 19ccb13893a2c8f06e13edea4d4ab03e092fd400 Mon Sep 17 00:00:00 2001 From: Yusuf Efe <120668197+yuefdev@users.noreply.github.com> Date: Thu, 22 Oct 2026 05:29:10 +0300 Subject: [PATCH] fix(package): [random] handle non-positive unique slice lengths (#402) --- random/negative_length_test.go | 14 ++++++++++++++ random/random.go | 5 ++++- 2 files changed, 18 insertions(+), 1 deletion(-) create mode 100644 random/negative_length_test.go diff --git a/random/negative_length_test.go b/random/negative_length_test.go new file mode 100644 index 0000000..fcff677 --- /dev/null +++ b/random/negative_length_test.go @@ -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) + } + } +} diff --git a/random/random.go b/random/random.go index 60e5815..81d4603 100644 --- a/random/random.go +++ b/random/random.go @@ -98,7 +98,7 @@ func RandIntSlice(length, min, max int) []int { // RandUniqueIntSlice generate a slice of random int of length that do not repeat. // Play: https://go.dev/play/p/uBkRSOz73Ec func RandUniqueIntSlice(length, min, max int) []int { - if min > max { + if length <= 0 || min > max { return []int{} } 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. // Play: https://go.dev/play/p/I3yndUQ-rhh func RandFloats(length int, min, max float64, precision int) []float64 { + if length <= 0 { + return []float64{} + } if max < min { min, max = max, min }