From 4d8a0f4d17658066b4efb02b636f445d53b3b958 Mon Sep 17 00:00:00 2001 From: "Jonathan A. Schweder" Date: Fri, 16 Feb 2024 15:11:13 +0000 Subject: [PATCH] fix intn panic (#163) This reverts commit ae23891d4c901b3603aad44fa0bba41cf0735f84. --- faker.go | 29 +++++++++-------------------- faker_test.go | 7 ++++--- 2 files changed, 13 insertions(+), 23 deletions(-) diff --git a/faker.go b/faker.go index 7102ce3..c4bdf56 100644 --- a/faker.go +++ b/faker.go @@ -10,13 +10,6 @@ import ( "time" ) -const ( - maxUint = ^uint(0) - minUint = 0 - maxInt = int(maxUint >> 1) - minInt = -maxInt - 1 -) - // Faker is the Generator struct for Faker type Faker struct { Generator GeneratorInterface @@ -103,8 +96,8 @@ func (f Faker) Float64(maxDecimals, min, max int) float64 { // Int returns a fake Int number for Faker func (f Faker) Int() int { - max := int(^uint(0)>>1) - 1 - min := 0 + max := math.MaxInt + min := math.MinInt return f.IntBetween(min, max) } @@ -130,8 +123,7 @@ func (f Faker) Int64() int64 { // UInt returns a fake UInt number for Faker func (f Faker) UInt() uint { - maxU := ^uint(0) >> 1 - max := int(maxU) + max := math.MaxInt return uint(f.IntBetween(0, max)) } @@ -159,19 +151,16 @@ func (f Faker) UInt64() uint64 { func (f Faker) IntBetween(min, max int) int { diff := max - min - if diff < 0 { - diff = 0 - } - + var value int if diff == 0 { return min + } else if diff == math.MaxInt { + value = f.Generator.Intn(diff) + } else if diff > 0 { + value = f.Generator.Intn(diff + 1) } - if diff == maxInt { - return f.Generator.Intn(diff) - } - - return f.Generator.Intn(diff+1) + min + return min + value } // Int8Between returns a fake Int8 between a given minimum and maximum values for Faker diff --git a/faker_test.go b/faker_test.go index bbe3c77..70e86b0 100644 --- a/faker_test.go +++ b/faker_test.go @@ -2,6 +2,7 @@ package faker import ( "fmt" + "math" "math/rand" "reflect" "strings" @@ -160,10 +161,10 @@ func TestIntBetweenNegativeValues(t *testing.T) { func TestIntBetweenWithMaxValues(t *testing.T) { f := New() - value := f.IntBetween(minInt, maxInt) + value := f.IntBetween(math.MinInt, math.MaxInt) Expect(t, fmt.Sprintf("%T", value), "int") - Expect(t, true, value >= minInt) - Expect(t, true, value <= maxInt) + Expect(t, true, value >= math.MinInt) + Expect(t, true, value <= math.MaxInt) } func TestIntBetweenWithInvalidInterval(t *testing.T) {