#[cfg(feature = "std")]
use std::{
borrow::Cow,
ffi::{OsStr, OsString},
str::FromStr,
};
#[cfg(windows)]
type CharBase = u16;
#[cfg(not(windows))]
type CharBase = u8;
pub type PlatChar = CharBase;
#[doc(hidden)]
#[macro_export]
macro_rules! plat_char {
($ch:expr) => {{
const RESULT: $crate::util::PlatChar = {
const CH: ::core::primitive::char = $ch;
assert!(CH.is_ascii(), "argument must be an ASCII character");
CH as $crate::util::PlatChar
};
RESULT
}};
}
#[doc(inline)]
pub use crate::plat_char;
#[doc(hidden)]
#[macro_export]
macro_rules! plat_str {
($str:expr) => {{
const RESULT: &[$crate::util::PlatChar] = &{
const STR: &::core::primitive::str = $str;
assert!(STR.is_ascii(), "argument must be an ASCII string");
let mut result = [0; STR.len()];
let mut i = 0;
while i < STR.len() {
let ch = STR.as_bytes()[i];
result[i] = ch as $crate::util::PlatChar;
i += 1;
}
result
};
RESULT
}};
}
#[doc(inline)]
pub use crate::plat_str;
#[cfg(feature = "std")]
pub trait OsStrExt {
fn parse_str<T: FromStr>(&self) -> Option<T>;
#[must_use]
fn to_plat(&self) -> Cow<'_, [PlatChar]>;
}
#[cfg(feature = "std")]
impl OsStrExt for OsStr {
#[inline]
fn parse_str<T: FromStr>(&self) -> Option<T> {
self.to_str().and_then(|s| T::from_str(s).ok())
}
#[inline]
fn to_plat(&self) -> Cow<'_, [PlatChar]> {
#[cfg(windows)]
{
use std::os::windows::ffi::OsStrExt as _;
Cow::Owned(self.encode_wide().collect())
}
#[cfg(not(windows))]
{
#[cfg(all(target_vendor = "fortanix", target_env = "sgx"))]
use std::os::fortanix_sgx::ffi::OsStrExt as _;
#[cfg(target_os = "hermit")]
use std::os::hermit::ffi::OsStrExt as _;
#[cfg(target_os = "solid_asp3")]
use std::os::solid::ffi::OsStrExt as _;
#[cfg(unix)]
use std::os::unix::ffi::OsStrExt as _;
#[cfg(target_os = "wasi")]
use std::os::wasi::ffi::OsStrExt as _;
#[cfg(target_os = "xous")]
use std::os::xous::ffi::OsStrExt as _;
Cow::Borrowed(self.as_bytes())
}
}
}
#[cfg(feature = "std")]
pub trait OsStringExt {
#[must_use]
fn from_plat(slice: &[PlatChar]) -> Cow<'_, OsStr>;
}
#[cfg(feature = "std")]
impl OsStringExt for OsString {
#[inline]
fn from_plat(slice: &[PlatChar]) -> Cow<'_, OsStr> {
#[cfg(windows)]
{
use std::{ffi::OsString, os::windows::ffi::OsStringExt as _};
Cow::Owned(OsString::from_wide(slice))
}
#[cfg(not(windows))]
{
#[cfg(all(target_vendor = "fortanix", target_env = "sgx"))]
use std::os::fortanix_sgx::ffi::OsStrExt as _;
#[cfg(target_os = "hermit")]
use std::os::hermit::ffi::OsStrExt as _;
#[cfg(target_os = "solid_asp3")]
use std::os::solid::ffi::OsStrExt as _;
#[cfg(unix)]
use std::os::unix::ffi::OsStrExt as _;
#[cfg(target_os = "wasi")]
use std::os::wasi::ffi::OsStrExt as _;
#[cfg(target_os = "xous")]
use std::os::xous::ffi::OsStrExt as _;
Cow::Borrowed(OsStr::from_bytes(slice))
}
}
}