Debian Codegraph @

rng.go

raw symbols SCIP
1 package wyhash
2
3 import "math/bits"
4
5 // RNG is a random number generator.
6 // The zero value is valid.
7 type RNG uint64
8
9 // Int returns a random positive int.
10 // Not safe for concurrent callers.
11 func (r *RNG) Int() int {
12 return int(uint(r.Uint64()) >> 1)
13 }
14
15 // Intn returns an int uniformly in [0, n).
16 // Not safe for concurrent callers.
17 func (r *RNG) Intn(n int) int {
18 if n <= 0 {
19 return 0
20 }
21 return int(r.Uint64n(uint64(n)))
22 }
23
24 // Uint64 returns a random uint64.
25 // Not safe for concurrent callers.
26 func (r *RNG) Uint64() uint64 {
27 *r += _wyp0
28 return _wymum(u64(*r)^_wyp1, u64(*r))
29 }
30
31 // Uint64n returns a uint64 uniformly in [0, n).
32 // Not safe for concurrent callers.
33 func (r *RNG) Uint64n(n uint64) uint64 {
34 if n == 0 {
35 return 0
36 }
37
38 x := r.Uint64()
39 h, l := bits.Mul64(x, n)
40
41 if l < n {
42 t := -n
43 if t >= n {
44 t -= n
45 if t >= n {
46 t = t % n
47 }
48 }
49
50 again:
51 if l < t {
52 x = r.Uint64()
53 h, l = bits.Mul64(x, n)
54 goto again
55 }
56 }
57
58 return h
59 }
60
61 // Float64 returns a float64 uniformly in [0, 1).
62 // Not safe for concurrent callers.
63 func (r *RNG) Float64() (v float64) {
64 again:
65 v = float64(r.Uint64()>>11) / (1 << 53)
66 if v == 1 {
67 goto again
68 }
69 return
70 }