-
Notifications
You must be signed in to change notification settings - Fork 0
/
int.go
54 lines (47 loc) · 1.58 KB
/
int.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
package xrand
import (
"crypto/rand"
"log"
"math/big"
"runtime/debug"
)
func RangeUint64(min uint64, max uint64) (random uint64) {
// Swap min and max if min > max
if min > max {
min, max = max, min
log.Print("goclub/rand: RangeUint64(min, max) max should greater than or equal to min", "\n", string(debug.Stack()))
}
// Calculate the range
bigMax := new(big.Int).SetUint64(max)
bigMin := new(big.Int).SetUint64(min)
bigRange := new(big.Int).Sub(bigMax, bigMin)
// Generate a random number within the range
bigRandom, err := rand.Int(rand.Reader, bigRange.Add(bigRange, big.NewInt(1)))
if err != nil {
// 理论上不会出现这个错误,如果出错panic .
// 这样既能保证函数易用,又能保证程序不会出现意外的错误
panic(err)
}
random = bigRandom.Add(bigRandom, bigMin).Uint64()
return random
}
func RangeInt64(min int64, max int64) (random int64) {
// Swap min and max if min > max
if min > max {
min, max = max, min
log.Print("goclub/rand: RangeUint64(min, max) max should greater than or equal to min", "\n", string(debug.Stack()))
}
// Calculate the range
bigMax := new(big.Int).SetInt64(max)
bigMin := new(big.Int).SetInt64(min)
bigRange := new(big.Int).Sub(bigMax, bigMin)
// Generate a random number within the range
bigRandom, err := rand.Int(rand.Reader, bigRange.Add(bigRange, big.NewInt(1)))
if err != nil {
// 理论上不会出现这个错误,如果出错panic .
// 这样既能保证函数易用,又能保证程序不会出现意外的错误
panic(err)
}
random = bigRandom.Add(bigRandom, bigMin).Int64()
return random
}