-
Notifications
You must be signed in to change notification settings - Fork 0
/
uint.go
75 lines (62 loc) · 1.3 KB
/
uint.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package chance
import (
"math"
"math/rand"
"strconv"
)
// UIntOption is a type
type UIntOption func(*UIntOptions)
// UIntOptions is uint options
type UIntOptions struct {
min uint
max uint
}
func (ch *chance) UInt(options ...UIntOption) uint {
ops := UIntOptions{}
for i := range options {
options[i](&ops)
}
ch.r.Seed(ch.seed)
// TODO: handle error on bad options
// Check machine architecture
if strconv.IntSize == 32 {
return uint(randomHelper32(uint32(ops.max-ops.min)) + uint32(ops.min))
}
return uint(randomHelper64(uint64(ops.max-ops.min)) + uint64(ops.min))
}
// UInt returns a random uint
func UInt(options ...UIntOption) uint {
return defaultChance.UInt(options...)
}
// SetUIntMin sets min of random uint
func SetUIntMin(min uint) UIntOption {
return func(iOpts *UIntOptions) {
iOpts.min = min
}
}
// SetUIntMax sets max of random uint
func SetUIntMax(max uint) UIntOption {
return func(iOpts *UIntOptions) {
iOpts.max = max
}
}
func randomHelper64(n uint64) uint64 {
if n < math.MaxInt64 {
return uint64(rand.Int63n(int64(n + 1)))
}
x := rand.Uint64()
for x > n {
x = rand.Uint64()
}
return x
}
func randomHelper32(n uint32) uint32 {
if n < math.MaxInt32 {
return uint32(rand.Int31n(int32(n + 1)))
}
x := rand.Uint32()
for x > n {
x = rand.Uint32()
}
return x
}