1 use std::borrow::Cow;
2 use std::error::Error;
3 use std::ffi::OsStr;
4 use std::ffi::OsString;
5 use std::fmt;
6 use std::fmt::Display;
7 use std::fmt::Formatter;
8 use std::result;
9 use std::str;
10 use std::str::Utf8Error;
11 
12 if_raw_str! {
13     pub(super) mod raw;
14 }
15 
16 #[derive(Debug, Eq, PartialEq)]
17 pub(super) struct EncodingError(Utf8Error);
18 
19 impl Display for EncodingError {
fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result20     fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
21         write!(formatter, "os_str_bytes: {}", self.0)
22     }
23 }
24 
25 impl Error for EncodingError {}
26 
27 type Result<T> = result::Result<T, EncodingError>;
28 
29 macro_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 
os_str_from_bytes(string: &[u8]) -> Result<Cow<'_, OsStr>>38 pub(super) fn os_str_from_bytes(string: &[u8]) -> Result<Cow<'_, OsStr>> {
39     str::from_utf8(string)
40         .map(|x| Cow::Borrowed(OsStr::new(x)))
41         .map_err(EncodingError)
42 }
43 
os_str_to_bytes(os_string: &OsStr) -> Cow<'_, [u8]>44 pub(super) fn os_str_to_bytes(os_string: &OsStr) -> Cow<'_, [u8]> {
45     Cow::Borrowed(expect_utf8!(os_string.to_str()).as_bytes())
46 }
47 
os_string_from_vec(string: Vec<u8>) -> Result<OsString>48 pub(super) fn os_string_from_vec(string: Vec<u8>) -> Result<OsString> {
49     String::from_utf8(string)
50         .map(Into::into)
51         .map_err(|x| EncodingError(x.utf8_error()))
52 }
53 
os_string_into_vec(os_string: OsString) -> Vec<u8>54 pub(super) fn os_string_into_vec(os_string: OsString) -> Vec<u8> {
55     expect_utf8!(os_string.into_string()).into_bytes()
56 }
57