Thank you very much @drewtato . Unfortunately there is a problem converting into Path
fn main() {
let x = OsStr::new("abcdef");
let x = x.strip_prefix(OsStr::new("abc"));
assert_eq!(x, Some(OsStr::new("def")));
let x = Path::new("abcdef");
let x = x.strip_prefix(Path::new("abc"));
assert_eq!(x, Some(Path::new("def")));
// ^^^^^^^^^^^^^^^^^^^^^^ expected `Result<&Path, StripPrefixError>`, found `Option<&Path>`
}
That probably has something to do with more restrictions on Path...
That's because Path has an inherent method with the same name but returns a different value. Changing the method name in your extension trait is the simplest solution.
@parasyte , @drewtato do you think you could please help me with the second function? I thought split_once will be easy after strip_prefix but apparently not
use std::ffi::OsStr;
use std::os::unix::ffi::OsStrExt;
use std::path::Path;
pub trait OsStrUtil: AsRef<OsStr>
where
OsStr: AsRef<Self>,
{
fn split_once_os<'a, P: AsRef<OsStr> + ?Sized>(&'a self, separator: &P) -> Option<(&'a Self, &'a Self)>;
}
impl<S> OsStrUtil for S
where
S: AsRef<OsStr> + ?Sized,
OsStr: AsRef<Self>,
{
fn split_once_os<'a, P: AsRef<OsStr> + ?Sized>(&'a self, separator: &P) -> Option<(&'a Self, &'a Self)> {
self.as_ref()
.as_bytes()
//////////////
////.split_once(separator.as_ref().as_bytes())
/// use of unstable library feature 'slice_split_once': newly added
//////////////
.map(|(left, right)| (OsStr::from_bytes(left).as_ref(), OsStr::from_bytes(right).as_ref()))
}
}
fn main() {
let x = OsStr::new("abcdef");
let x = x.split_once_os(OsStr::new("cd"));
assert_eq!(x, Some((OsStr::new("ab"), OsStr::new("ef"))));
let x = Path::new("abcdef");
let x = x.split_once_os(Path::new("cd"));
assert_eq!(x, Some((Path::new("ab"), Path::new("ef"))));
}