Skip to content

Commit

Permalink
fix intn panic (#163)
Browse files Browse the repository at this point in the history
This reverts commit ae23891.
  • Loading branch information
jaswdr committed Feb 16, 2024
1 parent ae23891 commit 4d8a0f4
Show file tree
Hide file tree
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
Expand Up @@ -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
Expand Down Expand Up @@ -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)
}

Expand All @@ -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))
}

Expand Down Expand Up @@ -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
Expand Down
7 changes: 4 additions & 3 deletions faker_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package faker

import (
"fmt"
"math"
"math/rand"
"reflect"
"strings"
Expand Down Expand Up @@ -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) {
Expand Down

0 comments on commit 4d8a0f4

Please sign in to comment.