1 #![allow(dead_code)] 2 3 macro_rules! if_checked_conversions { 4 ( $($item:item)+ ) => { 5 $( 6 #[cfg(feature = "checked_conversions")] 7 $item 8 )+ 9 }; 10 } 11 12 if_checked_conversions! { 13 use std::borrow::Cow; 14 use std::ffi::OsStr; 15 use std::ffi::OsString; 16 use std::path::Path; 17 use std::path::PathBuf; 18 use std::result; 19 20 use os_str_bytes::EncodingError; 21 use os_str_bytes::OsStrBytes; 22 use os_str_bytes::OsStringBytes; 23 } 24 25 if_checked_conversions! { 26 pub(crate) type Result<T> = result::Result<T, EncodingError>; 27 } 28 29 pub(crate) const WTF8_STRING: &[u8] = b"foo\xED\xA0\xBD\xF0\x9F\x92\xA9bar"; 30 31 if_checked_conversions! { 32 #[track_caller] 33 fn test_from_bytes<'a, T, U, S>(result: &Result<U>, string: S) 34 where 35 S: Into<Cow<'a, [u8]>>, 36 T: 'a + AsRef<OsStr> + OsStrBytes + ?Sized, 37 U: AsRef<OsStr>, 38 { 39 assert_eq!( 40 result.as_ref().map(AsRef::as_ref), 41 T::from_raw_bytes(string).as_deref().map(AsRef::as_ref), 42 ); 43 } 44 45 pub(crate) fn from_bytes(string: &[u8]) -> Result<Cow<'_, OsStr>> { 46 let os_string = OsStr::from_raw_bytes(string); 47 48 test_from_bytes::<Path, _, _>(&os_string, string); 49 50 os_string 51 } 52 53 pub(crate) fn from_vec(string: Vec<u8>) -> Result<OsString> { 54 let os_string = OsString::from_raw_vec(string.clone()); 55 test_from_bytes::<OsStr, _, _>(&os_string, string.clone()); 56 57 let path = PathBuf::from_raw_vec(string.clone()); 58 test_from_bytes::<Path, _, _>(&path, string); 59 assert_eq!(os_string, path.map(PathBuf::into_os_string)); 60 61 os_string 62 } 63 64 pub(crate) fn test_bytes(string: &[u8]) -> Result<()> { 65 let os_string = from_bytes(string)?; 66 assert_eq!(string.len(), os_string.len()); 67 assert_eq!(string, &*os_string.to_raw_bytes()); 68 Ok(()) 69 } 70 71 pub(crate) fn test_vec(string: &[u8]) -> Result<()> { 72 let os_string = from_vec(string.to_owned())?; 73 assert_eq!(string.len(), os_string.len()); 74 assert_eq!(string, os_string.into_raw_vec()); 75 Ok(()) 76 } 77 78 pub(crate) fn test_utf8_bytes(string: &str) { 79 let os_string = OsStr::new(string); 80 let string = string.as_bytes(); 81 assert_eq!(Ok(Cow::Borrowed(os_string)), from_bytes(string)); 82 assert_eq!(string, &*os_string.to_raw_bytes()); 83 } 84 85 pub(crate) fn test_utf8_vec(string: &str) { 86 let os_string = string.to_owned().into(); 87 let string = string.as_bytes(); 88 assert_eq!(Ok(&os_string), from_vec(string.to_owned()).as_ref()); 89 assert_eq!(string, os_string.into_raw_vec()); 90 } 91 } 92