rialo_s_random_seed/
lib.rs1#![cfg_attr(feature = "frozen-abi", feature(min_specialization))]
5#[cfg(not(target_os = "solana"))]
11use rand::Rng;
12use thiserror::Error;
13
14#[derive(Debug, Clone, PartialEq, Eq, Error)]
16pub enum RandomSeedError {
17 #[error("Failed to retrieve random seed")]
19 RetrievalFailed,
20}
21
22impl From<u64> for RandomSeedError {
23 fn from(_: u64) -> RandomSeedError {
24 RandomSeedError::RetrievalFailed
25 }
26}
27
28#[cfg(target_os = "solana")]
29pub use rialo_s_define_syscall::definitions::rlo_get_random_seed;
30
31pub fn get_random_seed() -> Result<u64, RandomSeedError> {
59 #[cfg(target_os = "solana")]
60 {
61 let mut seed: u64 = 0;
62 #[allow(unsafe_code)]
63 let result = unsafe { rlo_get_random_seed(&mut seed as *mut u64 as *mut u8) };
64
65 match result {
66 0 => Ok(seed),
67 error => Err(RandomSeedError::from(error)),
68 }
69 }
70
71 #[cfg(not(target_os = "solana"))]
72 {
73 let mut rng = rand::thread_rng();
75 Ok(rng.gen::<u64>())
76 }
77}
78
79#[cfg(test)]
80mod tests {
81 use super::*;
82
83 #[test]
84 fn test_get_random_seed_succeeds() {
85 let result = get_random_seed();
87 assert!(result.is_ok());
88 }
89
90 #[test]
91 fn test_random_seed_error_from() {
92 let error = RandomSeedError::from(1u64);
94 assert_eq!(error, RandomSeedError::RetrievalFailed);
95
96 let error = RandomSeedError::from(42u64);
97 assert_eq!(error, RandomSeedError::RetrievalFailed);
98
99 let error = RandomSeedError::from(u64::MAX);
100 assert_eq!(error, RandomSeedError::RetrievalFailed);
101 }
102
103 #[test]
104 fn test_random_seed_error_display() {
105 let error = RandomSeedError::RetrievalFailed;
107 let error_string = format!("{}", error);
108 assert_eq!(error_string, "Failed to retrieve random seed");
109 }
110}