• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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(Clone, Copy, Debug, Eq, PartialEq)]
17 pub(super) struct EncodingError(Utf8Error);
18 
19 impl Display for EncodingError {
fmt(&self, f: &mut Formatter<'_>) -> fmt::Result20     fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
21         write!(f, "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 
from_bytes(string: &[u8]) -> Result<&str>38 fn from_bytes(string: &[u8]) -> Result<&str> {
39     str::from_utf8(string).map_err(EncodingError)
40 }
41 
os_str_from_bytes(string: &[u8]) -> Result<Cow<'_, OsStr>>42 pub(super) fn os_str_from_bytes(string: &[u8]) -> Result<Cow<'_, OsStr>> {
43     from_bytes(string).map(|x| Cow::Borrowed(OsStr::new(x)))
44 }
45 
os_str_to_bytes(os_string: &OsStr) -> Cow<'_, [u8]>46 pub(super) fn os_str_to_bytes(os_string: &OsStr) -> Cow<'_, [u8]> {
47     Cow::Borrowed(expect_utf8!(os_string.to_str()).as_bytes())
48 }
49 
os_string_from_vec(string: Vec<u8>) -> Result<OsString>50 pub(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 
os_string_into_vec(os_string: OsString) -> Vec<u8>56 pub(super) fn os_string_into_vec(os_string: OsString) -> Vec<u8> {
57     expect_utf8!(os_string.into_string()).into_bytes()
58 }
59