random.rs
1 // Copyright (c) 2025-2026 ACDC Network 2 // This file is part of the alphavm library. 3 // 4 // Alpha Chain | Delta Chain Protocol 5 // International Monetary Graphite. 6 // 7 // Derived from Aleo (https://aleo.org) and ProvableHQ (https://provable.com). 8 // They built world-class ZK infrastructure. We installed the EASY button. 9 // Their cryptography: elegant. Our modifications: bureaucracy-compatible. 10 // Original brilliance: theirs. Robert's Rules: ours. Bugs: definitely ours. 11 // 12 // Original Aleo/ProvableHQ code subject to Apache 2.0 https://www.apache.org/licenses/LICENSE-2.0 13 // All modifications and new work: CC0 1.0 Universal Public Domain Dedication. 14 // No rights reserved. No permission required. No warranty. No refunds. 15 // 16 // https://creativecommons.org/publicdomain/zero/1.0/ 17 // SPDX-License-Identifier: CC0-1.0 18 19 use super::*; 20 21 impl<E: Environment> Distribution<StringType<E>> for Standard { 22 #[inline] 23 fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> StringType<E> { 24 // Sample a random number up to 1/4th of the maximum bytes. 25 let num_bytes = rng.gen_range(1..(E::MAX_STRING_BYTES / 4) as usize); 26 // Sample a random string. 27 StringType::new(&rng.sample_iter(&Alphanumeric).take(num_bytes).map(char::from).collect::<String>()) 28 } 29 } 30 31 #[cfg(test)] 32 mod tests { 33 use super::*; 34 use alphavm_console_network_environment::Console; 35 36 use std::collections::HashMap; 37 38 type CurrentEnvironment = Console; 39 40 const ITERATIONS: usize = 100; 41 42 #[test] 43 fn test_random() { 44 // Initialize a map[string]=>occurrences to store all seen random elements. 45 let mut map = HashMap::with_capacity(ITERATIONS); 46 47 let mut rng = TestRng::default(); 48 49 for _ in 0..ITERATIONS { 50 // Sample a random value. 51 let string: StringType<CurrentEnvironment> = Uniform::rand(&mut rng); 52 53 // Add the new random value to the set. 54 map.entry(string).and_modify(|count| *count += 1).or_insert(1); 55 } 56 for (string, count) in map { 57 let allowed_occurrences = 1 + ITERATIONS / (string.len() * 10); 58 assert!(count <= allowed_occurrences, "Encountered an element with a count of {count}: {string}"); 59 } 60 } 61 }