use std::borrow::Cow;
use std::ffi::OsStr;
use std::path::Path;
mod sealing {
use std::path::Path;
pub trait PathExt {}
impl PathExt for Path {}
}
pub trait PathExt: sealing::PathExt {
fn ensure_extension<S: AsRef<OsStr>>(&self, extension: S) -> Cow<Path>;
}
impl PathExt for Path {
fn ensure_extension<S: AsRef<OsStr>>(&self, extension: S) -> Cow<Path> {
if let Some(ext) = self.extension() {
if ext == extension.as_ref() {
self.into()
} else {
let mut buf = self.to_path_buf();
buf.set_extension(extension);
buf.into()
}
} else {
self.with_extension(extension).into()
}
}
}
#[cfg(test)]
mod tests {
use crate::utils::PathExt;
use std::borrow::Cow;
use std::path::Path;
#[test]
fn basic() {
let wrong_ext = Path::new("myfile.txt");
let no_ext = Path::new("myfile");
let correct_ext = Path::new("myfile.bpx");
let wrong_ext_corrected = wrong_ext.ensure_extension("bpx");
let no_ext_corrected = no_ext.ensure_extension("bpx");
let correct_ext_corrected = correct_ext.ensure_extension("bpx");
if let Cow::Owned(_) = correct_ext_corrected {
panic!("If the extension is already correct no allocation should be performed")
}
assert_eq!(&wrong_ext_corrected, Path::new("myfile.bpx"));
assert_eq!(&no_ext_corrected, Path::new("myfile.bpx"));
assert_eq!(&correct_ext_corrected, Path::new("myfile.bpx"));
}
}