1//! Platform dependent types.
23cfg_if::cfg_if! {
4if #[cfg(feature = "std")] {
5use std::borrow::Cow;
6use std::fmt;
7use std::path::PathBuf;
8use std::prelude::v1::*;
9use std::str;
10 }
11}
1213/// A platform independent representation of a string. When working with `std`
14/// enabled it is recommended to the convenience methods for providing
15/// conversions to `std` types.
16#[derive(Debug)]
17pub enum BytesOrWideString<'a> {
18/// A slice, typically provided on Unix platforms.
19Bytes(&'a [u8]),
20/// Wide strings typically from Windows.
21Wide(&'a [u16]),
22}
2324#[cfg(feature = "std")]
25impl<'a> BytesOrWideString<'a> {
26/// Lossy converts to a `Cow<str>`, will allocate if `Bytes` is not valid
27 /// UTF-8 or if `BytesOrWideString` is `Wide`.
28 ///
29 /// # Required features
30 ///
31 /// This function requires the `std` feature of the `backtrace` crate to be
32 /// enabled, and the `std` feature is enabled by default.
33pub fn to_str_lossy(&self) -> Cow<'a, str> {
34use self::BytesOrWideString::*;
3536match self {
37&Bytes(slice) => String::from_utf8_lossy(slice),
38&Wide(wide) => Cow::Owned(String::from_utf16_lossy(wide)),
39 }
40 }
4142/// Provides a `Path` representation of `BytesOrWideString`.
43 ///
44 /// # Required features
45 ///
46 /// This function requires the `std` feature of the `backtrace` crate to be
47 /// enabled, and the `std` feature is enabled by default.
48pub fn into_path_buf(self) -> PathBuf {
49#[cfg(unix)]
50{
51use std::ffi::OsStr;
52use std::os::unix::ffi::OsStrExt;
5354if let BytesOrWideString::Bytes(slice) = self {
55return PathBuf::from(OsStr::from_bytes(slice));
56 }
57 }
5859#[cfg(windows)]
60{
61use std::ffi::OsString;
62use std::os::windows::ffi::OsStringExt;
6364if let BytesOrWideString::Wide(slice) = self {
65return PathBuf::from(OsString::from_wide(slice));
66 }
67 }
6869if let BytesOrWideString::Bytes(b) = self {
70if let Ok(s) = str::from_utf8(b) {
71return PathBuf::from(s);
72 }
73 }
74unreachable!()
75 }
76}
7778#[cfg(feature = "std")]
79impl<'a> fmt::Display for BytesOrWideString<'a> {
80fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
81self.to_str_lossy().fmt(f)
82 }
83}