1 #![allow(dead_code)] 2 3 use std::ffi::OsString; 4 #[cfg(unix)] 5 use std::os::unix::ffi::OsStringExt; 6 #[cfg(windows)] 7 use std::os::windows::ffi::OsStringExt; 8 #[cfg(windows)] 9 use std::slice; 10 11 use getrandom::getrandom; 12 13 pub(crate) const SMALL_LENGTH: usize = 16; 14 15 pub(crate) const ITERATIONS: usize = 1024; 16 random_os_string( buffer_length: usize, ) -> Result<OsString, getrandom::Error>17pub(crate) fn random_os_string( 18 buffer_length: usize, 19 ) -> Result<OsString, getrandom::Error> { 20 let mut buffer = vec![0; buffer_length]; 21 #[cfg(unix)] 22 { 23 getrandom(&mut buffer)?; 24 Ok(OsStringExt::from_vec(buffer)) 25 } 26 #[cfg(windows)] 27 { 28 fn as_mut_bytes(buffer: &mut [u16]) -> &mut [u8] { 29 // SAFETY: [u16] can always be transmuted to two [u8] bytes. 30 unsafe { 31 slice::from_raw_parts_mut( 32 buffer.as_mut_ptr().cast(), 33 buffer.len() * 2, 34 ) 35 } 36 } 37 38 getrandom(as_mut_bytes(&mut buffer))?; 39 Ok(OsStringExt::from_wide(&buffer)) 40 } 41 } 42