|
13 | 13 | // limitations under the License.
|
14 | 14 |
|
15 | 15 | ///|
|
16 |
| -/// Currently we only support [chacha8] as the source of randomness. |
17 |
| -struct Rand { |
18 |
| - src : @random_source.ChaCha8 |
| 16 | +/// `Rand` is a pseudo-random number generator (PRNG) that provides various |
| 17 | +/// methods to generate random numbers of different types. |
| 18 | +type Rand &Source |
| 19 | + |
| 20 | +///| |
| 21 | +/// The [Source] trait defines a method to generate random numbers. |
| 22 | +pub(open) trait Source { |
| 23 | + next(Self) -> UInt64 |
| 24 | +} |
| 25 | + |
| 26 | +///| |
| 27 | +impl Source for @random_source.ChaCha8 with next(self : @random_source.ChaCha8) -> UInt64 { |
| 28 | + for { |
| 29 | + let x = self.state.next() |
| 30 | + if x.1 { |
| 31 | + return x.0 |
| 32 | + } |
| 33 | + self.state.refill() |
| 34 | + } |
19 | 35 | }
|
20 | 36 |
|
21 | 37 | ///|
|
22 | 38 | /// Create a new random number generator with [seed].
|
23 | 39 | /// @alert unsafe "Panic if seed is not 32 bytes long"
|
| 40 | +#deprecated("Use `Rand::new(chacha8())` instead") |
24 | 41 | pub fn new(seed~ : Bytes = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ123456") -> Rand {
|
25 | 42 | if seed.length() != 32 {
|
26 | 43 | abort("seed must be 32 bytes long")
|
27 | 44 | }
|
28 |
| - let src = @random_source.ChaCha8::new(seed) |
29 |
| - { src, } |
| 45 | + @random_source.ChaCha8::new(seed) as &Source |
| 46 | +} |
| 47 | + |
| 48 | +///| |
| 49 | +/// Create a new random number generator with [seed]. |
| 50 | +/// @alert unsafe "Panic if seed is not 32 bytes long" |
| 51 | +pub fn chacha8(seed~ : Bytes = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ123456") -> &Source { |
| 52 | + if seed.length() != 32 { |
| 53 | + abort("seed must be 32 bytes long") |
| 54 | + } |
| 55 | + @random_source.ChaCha8::new(seed) as &Source |
30 | 56 | }
|
31 | 57 |
|
32 |
| -///| @alert deprecated "use `@random.new` instead" |
33 |
| -pub fn Rand::new(seed~ : Bytes = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ123456") -> Rand { |
34 |
| - new(seed~) |
| 58 | +///| |
| 59 | +/// Create a new random number generator with a given [Gen] source. |
| 60 | +pub fn Rand::new(generator : &Source) -> Rand { |
| 61 | + generator |
35 | 62 | }
|
36 | 63 |
|
37 | 64 | ///|
|
38 | 65 | fn next(self : Rand) -> UInt64 {
|
39 |
| - for { |
40 |
| - let x = self.src.state.next() |
41 |
| - if x.1 { |
42 |
| - return x.0 |
43 |
| - } |
44 |
| - self.src.state.refill() |
45 |
| - } |
| 66 | + self._.next() |
46 | 67 | }
|
47 | 68 |
|
48 | 69 | ///|
|
|
0 commit comments