use std::ffi::OsStr;
pub trait OsStrExt: private::Sealed {
fn try_str(&self) -> Result<&str, std::str::Utf8Error>;
fn contains(&self, needle: &str) -> bool;
fn find(&self, needle: &str) -> Option<usize>;
fn strip_prefix(&self, prefix: &str) -> Option<&OsStr>;
fn starts_with(&self, prefix: &str) -> bool;
fn split<'s, 'n>(&'s self, needle: &'n str) -> Split<'s, 'n>;
fn split_once(&self, needle: &'_ str) -> Option<(&OsStr, &OsStr)>;
}
impl OsStrExt for OsStr {
fn try_str(&self) -> Result<&str, std::str::Utf8Error> {
let bytes = to_bytes(self);
std::str::from_utf8(bytes)
}
fn contains(&self, needle: &str) -> bool {
self.find(needle).is_some()
}
fn find(&self, needle: &str) -> Option<usize> {
let bytes = to_bytes(self);
(0..=self.len().checked_sub(needle.len())?)
.find(|&x| bytes[x..].starts_with(needle.as_bytes()))
}
fn strip_prefix(&self, prefix: &str) -> Option<&OsStr> {
let bytes = to_bytes(self);
bytes.strip_prefix(prefix.as_bytes()).map(|s| {
unsafe { to_os_str_unchecked(s) }
})
}
fn starts_with(&self, prefix: &str) -> bool {
let bytes = to_bytes(self);
bytes.starts_with(prefix.as_bytes())
}
fn split<'s, 'n>(&'s self, needle: &'n str) -> Split<'s, 'n> {
assert_ne!(needle, "");
Split {
haystack: Some(self),
needle,
}
}
fn split_once(&self, needle: &'_ str) -> Option<(&OsStr, &OsStr)> {
let start = self.find(needle)?;
let end = start + needle.len();
let haystack = to_bytes(self);
let first = &haystack[0..start];
let second = &haystack[end..];
unsafe { Some((to_os_str_unchecked(first), to_os_str_unchecked(second))) }
}
}
mod private {
pub trait Sealed {}
impl Sealed for std::ffi::OsStr {}
}
fn to_bytes(s: &OsStr) -> &[u8] {
unsafe { std::mem::transmute(s) }
}
unsafe fn to_os_str_unchecked(s: &[u8]) -> &OsStr {
std::mem::transmute(s)
}
pub struct Split<'s, 'n> {
haystack: Option<&'s OsStr>,
needle: &'n str,
}
impl<'s, 'n> Iterator for Split<'s, 'n> {
type Item = &'s OsStr;
fn next(&mut self) -> Option<Self::Item> {
let haystack = self.haystack?;
match haystack.split_once(self.needle) {
Some((first, second)) => {
if !haystack.is_empty() {
debug_assert_ne!(haystack, second);
}
self.haystack = Some(second);
Some(first)
}
None => {
self.haystack = None;
Some(haystack)
}
}
}
}
pub(crate) unsafe fn split_at(os: &OsStr, index: usize) -> (&OsStr, &OsStr) {
let bytes = to_bytes(os);
let (first, second) = bytes.split_at(index);
(to_os_str_unchecked(first), to_os_str_unchecked(second))
}