snarkvm_console_types_integers/random.rs
1// Copyright 2024 Aleo Network Foundation
2// This file is part of the snarkVM library.
3
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at:
7
8// http://www.apache.org/licenses/LICENSE-2.0
9
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16use super::*;
17
18impl<E: Environment, I: IntegerType> Distribution<Integer<E, I>> for Standard {
19 #[inline]
20 fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Integer<E, I> {
21 Integer::new(Uniform::rand(rng))
22 }
23}
24
25#[cfg(test)]
26mod tests {
27 use super::*;
28 use snarkvm_console_network_environment::Console;
29
30 use std::collections::HashSet;
31
32 type CurrentEnvironment = Console;
33
34 const ITERATIONS: usize = 10;
35
36 fn check_random<I: IntegerType>(rng: &mut TestRng) {
37 // Initialize a set to store all seen random elements.
38 let mut set = HashSet::with_capacity(ITERATIONS);
39
40 // Note: This test technically has a `(1 + 2 + ... + ITERATIONS) / MODULUS` probability of being flaky.
41 for _ in 0..ITERATIONS {
42 // Sample a random value.
43 let integer: Integer<CurrentEnvironment, I> = Uniform::rand(rng);
44 assert!(!set.contains(&integer));
45
46 // Add the new random value to the set.
47 set.insert(integer);
48 }
49 }
50
51 #[test]
52 fn test_random() {
53 let mut rng = TestRng::default();
54
55 check_random::<u32>(&mut rng);
56 check_random::<u64>(&mut rng);
57 check_random::<u128>(&mut rng);
58
59 check_random::<i32>(&mut rng);
60 check_random::<i64>(&mut rng);
61 check_random::<i128>(&mut rng);
62 }
63}