1use std::borrow::Cow; 2use std::error::Error; 3use std::ffi::OsStr; 4use std::ffi::OsString; 5use std::fmt; 6use std::fmt::Display; 7use std::fmt::Formatter; 8use std::result; 9use std::str; 10use std::str::Utf8Error; 11 12if_raw_str! { 13 pub(super) mod raw; 14} 15 16#[derive(Clone, Copy, Debug, Eq, PartialEq)] 17pub(super) struct EncodingError(Utf8Error); 18 19impl Display for EncodingError { 20 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { 21 write!(f, "os_str_bytes: {}", self.0) 22 } 23} 24 25impl Error for EncodingError {} 26 27type Result<T> = result::Result<T, EncodingError>; 28 29macro_rules! expect_utf8 { 30 ( $result:expr ) => { 31 $result.expect( 32 "platform string contains invalid UTF-8, which should not be \ 33 possible", 34 ) 35 }; 36} 37 38fn from_bytes(string: &[u8]) -> Result<&str> { 39 str::from_utf8(string).map_err(EncodingError) 40} 41 42pub(super) fn os_str_from_bytes(string: &[u8]) -> Result<Cow<'_, OsStr>> { 43 from_bytes(string).map(|x| Cow::Borrowed(OsStr::new(x))) 44} 45 46pub(super) fn os_str_to_bytes(os_string: &OsStr) -> Cow<'_, [u8]> { 47 Cow::Borrowed(expect_utf8!(os_string.to_str()).as_bytes()) 48} 49 50pub(super) fn os_string_from_vec(string: Vec<u8>) -> Result<OsString> { 51 String::from_utf8(string) 52 .map(Into::into) 53 .map_err(|x| EncodingError(x.utf8_error())) 54} 55 56pub(super) fn os_string_into_vec(os_string: OsString) -> Vec<u8> { 57 expect_utf8!(os_string.into_string()).into_bytes() 58} 59