v
Зеркало из https://github.com/vlang/v
1// Copyright (c) 2019-2024 Alexander Medvednikov. All rights reserved.
2// Use of this source code is governed by an MIT license
3// that can be found in the LICENSE file.
4
5module rand
6
7import math.bits
8import math.big
9import encoding.binary
10
11// int_u64 returns a random unsigned 64-bit integer `u64` read from a real OS source of entropy.
12pub fn int_u64(max u64) !u64 {
13bitlen := bits.len_64(max)
14if bitlen == 0 {
15return u64(0)
16}
17k := (bitlen + 7) / 8
18mut b := u64(bitlen % 8)
19if b == u64(0) {
20b = u64(8)
21}
22mut n := u64(0)
23for {
24mut bytes := read(k)!
25bytes[0] &= u8(int(u64(1) << b) - 1)
26x := bytes_to_u64(bytes)
27n = x[0]
28// NOTE: maybe until we have bigint could do it another way?
29// if x.len > 1 {
30// n = u64(u32(x[1])<<u32(32)) | n
31// }
32if n < max {
33return n
34}
35}
36return n
37}
38
39fn bytes_to_u64(b []u8) []u64 {
40ws := 64 / 8
41mut z := []u64{len: ((b.len + ws - 1) / ws)}
42mut i := b.len
43for k := 0; i >= ws; k++ {
44z[k] = binary.big_endian_u64(b[i - ws..i])
45i -= ws
46}
47if i > 0 {
48mut d := u64(0)
49for s := u64(0); i > 0; s += u64(8) {
50d |= u64(b[i - 1]) << s
51i--
52}
53z[z.len - 1] = d
54}
55return z
56}
57
58// int_big creates a random `big.Integer` with range [0, n)
59// returns an error if `n` is 0 or negative.
60pub fn int_big(n big.Integer) !big.Integer {
61if n.signum < 1 {
62return error('`n` cannot be 0 or negative.')
63}
64
65max := n - big.integer_from_int(1)
66len := max.bit_len()
67
68if len == 0 {
69// max = n - 1, if max = 0 then return max, as it is the only valid integer in [0, 1)
70return max
71}
72
73// k is the maximum byte length needed to encode a value < n
74k := (len + 7) / 8
75
76// b is the number of bits in the most significant byte of n-1
77mut b := u8(len % 8)
78if b == 0 {
79b = 8
80}
81
82mut result := big.Integer{}
83for {
84mut bytes := read(k)!
85
86// Clear bits in the first byte to increase the probability that the result is < max
87bytes[0] &= u8(int(1 << b) - 1)
88
89result = big.integer_from_bytes(bytes)
90if result < max {
91break
92}
93}
94return result
95}
96