1 //! Randomness support. 2 3 use security_framework_sys::random::*; 4 use std::io; 5 6 /// A source of random data. 7 pub struct SecRandom(SecRandomRef); 8 9 unsafe impl Sync for SecRandom {} 10 unsafe impl Send for SecRandom {} 11 12 impl Default for SecRandom { 13 #[inline(always)] default() -> Self14 fn default() -> Self { 15 unsafe { Self(kSecRandomDefault) } 16 } 17 } 18 19 impl SecRandom { 20 /// Fills the buffer with cryptographically secure random bytes. copy_bytes(&self, buf: &mut [u8]) -> io::Result<()>21 pub fn copy_bytes(&self, buf: &mut [u8]) -> io::Result<()> { 22 if unsafe { SecRandomCopyBytes(self.0, buf.len(), buf.as_mut_ptr() as *mut _) } == 0 { 23 Ok(()) 24 } else { 25 Err(io::Error::last_os_error()) 26 } 27 } 28 } 29 30 #[cfg(test)] 31 mod test { 32 use super::*; 33 34 #[test] basic()35 fn basic() { 36 let mut buf = [0; 10]; 37 SecRandom::default().copy_bytes(&mut buf).unwrap(); 38 } 39 } 40