Skip to content

Commit

Permalink
Re-apply fix intn panic (introduced in #163) (#166)
Browse files Browse the repository at this point in the history
This reverts commit ae23891.
jaswdr authored Feb 16, 2024
1 parent ae23891 commit d66c622
Showing 2 changed files with 13 additions and 23 deletions.
29 changes: 9 additions & 20 deletions faker.go
Original file line number Diff line number Diff line change
@@ -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
7 changes: 4 additions & 3 deletions faker_test.go
Original file line number Diff line number Diff line change
@@ -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) {

0 comments on commit d66c622

Please sign in to comment.