Skip to content

Commit ae23891

Browse files
authored
Revert "fix intn panic (#163)" (#165)
This reverts commit 4f477b6.
1 parent 4f477b6 commit ae23891

File tree

2 files changed

+23
-13
lines changed

2 files changed

+23
-13
lines changed

faker.go

+20-9
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,13 @@ import (
1010
"time"
1111
)
1212

13+
const (
14+
maxUint = ^uint(0)
15+
minUint = 0
16+
maxInt = int(maxUint >> 1)
17+
minInt = -maxInt - 1
18+
)
19+
1320
// Faker is the Generator struct for Faker
1421
type Faker struct {
1522
Generator GeneratorInterface
@@ -96,8 +103,8 @@ func (f Faker) Float64(maxDecimals, min, max int) float64 {
96103

97104
// Int returns a fake Int number for Faker
98105
func (f Faker) Int() int {
99-
max := math.MaxInt
100-
min := math.MinInt
106+
max := int(^uint(0)>>1) - 1
107+
min := 0
101108
return f.IntBetween(min, max)
102109
}
103110

@@ -123,7 +130,8 @@ func (f Faker) Int64() int64 {
123130

124131
// UInt returns a fake UInt number for Faker
125132
func (f Faker) UInt() uint {
126-
max := math.MaxInt
133+
maxU := ^uint(0) >> 1
134+
max := int(maxU)
127135
return uint(f.IntBetween(0, max))
128136
}
129137

@@ -151,16 +159,19 @@ func (f Faker) UInt64() uint64 {
151159
func (f Faker) IntBetween(min, max int) int {
152160
diff := max - min
153161

154-
var value int
162+
if diff < 0 {
163+
diff = 0
164+
}
165+
155166
if diff == 0 {
156167
return min
157-
} else if diff == math.MaxInt {
158-
value = f.Generator.Intn(diff)
159-
} else if diff > 0 {
160-
value = f.Generator.Intn(diff + 1)
161168
}
162169

163-
return min + value
170+
if diff == maxInt {
171+
return f.Generator.Intn(diff)
172+
}
173+
174+
return f.Generator.Intn(diff+1) + min
164175
}
165176

166177
// Int8Between returns a fake Int8 between a given minimum and maximum values for Faker

faker_test.go

+3-4
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ package faker
22

33
import (
44
"fmt"
5-
"math"
65
"math/rand"
76
"reflect"
87
"strings"
@@ -161,10 +160,10 @@ func TestIntBetweenNegativeValues(t *testing.T) {
161160

162161
func TestIntBetweenWithMaxValues(t *testing.T) {
163162
f := New()
164-
value := f.IntBetween(math.MinInt, math.MaxInt)
163+
value := f.IntBetween(minInt, maxInt)
165164
Expect(t, fmt.Sprintf("%T", value), "int")
166-
Expect(t, true, value >= math.MinInt)
167-
Expect(t, true, value <= math.MaxInt)
165+
Expect(t, true, value >= minInt)
166+
Expect(t, true, value <= maxInt)
168167
}
169168

170169
func TestIntBetweenWithInvalidInterval(t *testing.T) {

0 commit comments

Comments
 (0)