snarkvm_console_types_scalar/
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> Distribution<Scalar<E>> for Standard {
19    #[inline]
20    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Scalar<E> {
21        Scalar::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 = 100;
35
36    #[test]
37    fn test_random() {
38        // Initialize a set to store all seen random elements.
39        let mut set = HashSet::with_capacity(ITERATIONS);
40
41        let mut rng = TestRng::default();
42
43        // Note: This test technically has a `(1 + 2 + ... + ITERATIONS) / MODULUS` probability of being flaky.
44        for _ in 0..ITERATIONS {
45            // Sample a random value.
46            let scalar: Scalar<CurrentEnvironment> = Uniform::rand(&mut rng);
47            assert!(!set.contains(&scalar));
48
49            // Add the new random value to the set.
50            set.insert(scalar);
51        }
52    }
53}