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 { default() -> Self13 fn default() -> Self { 14 unsafe { Self(kSecRandomDefault) } 15 } 16 } 17 18 impl SecRandom { 19 /// Fills the buffer with cryptographically secure random bytes. copy_bytes(&self, buf: &mut [u8]) -> io::Result<()>20 pub fn copy_bytes(&self, buf: &mut [u8]) -> io::Result<()> { 21 if unsafe { SecRandomCopyBytes(self.0, buf.len(), buf.as_mut_ptr() as *mut _) } == 0 { 22 Ok(()) 23 } else { 24 Err(io::Error::last_os_error()) 25 } 26 } 27 } 28 29 #[cfg(test)] 30 mod test { 31 use super::*; 32 33 #[test] basic()34 fn basic() { 35 let mut buf = [0; 10]; 36 SecRandom::default().copy_bytes(&mut buf).unwrap(); 37 } 38 } 39