use std::path::{PathBuf,Path};
pub trait PathMod {
fn is_dot(&self) -> bool;
fn last_component(&self) -> Option<PathBuf>;
fn first_component(&self) -> Option<PathBuf>;
fn as_str(&self) -> &str;
fn as_string(&self) -> String;
}
impl PathMod for PathBuf {
fn is_dot(&self) -> bool {
let file_name = match self.file_name() {
Some(s) => {
match s.to_str() {
Some(k) => { k },
None => { return false; }
}
},
None => { return false; }
};
if file_name.starts_with(".") { return true; }
else { return false; }
}
fn last_component(&self) -> Option<PathBuf> {
match self.components().last() {
Some(s) => { Some(PathBuf::from(s.as_os_str())) },
None => { None },
}
}
fn first_component(&self) -> Option<PathBuf> {
match self.components().nth(0) {
Some(s) => { Some(PathBuf::from(s.as_os_str())) },
None => { None },
}
}
fn as_str(&self) -> &str {
match self.to_str() {
Some(s) => { s },
None => { "" },
}
}
fn as_string(&self) -> String {
self.as_str().to_string()
}
}
impl PathMod for Path {
fn is_dot(&self) -> bool {
let file_name = match self.file_name() {
Some(s) => {
match s.to_str() {
Some(k) => { k },
None => { "" }
}
},
None => { "" }
};
if file_name.starts_with(".") { return true; }
else { return false; }
}
fn last_component(&self) -> Option<PathBuf> {
match self.components().last() {
Some(s) => { Some(PathBuf::from(s.as_os_str())) },
None => { None },
}
}
fn first_component(&self) -> Option<PathBuf> {
match self.components().nth(0) {
Some(s) => { Some(PathBuf::from(s.as_os_str())) },
None => { None },
}
}
fn as_str(&self) -> &str {
match self.to_str() {
Some(s) => { s },
None => { "" },
}
}
fn as_string(&self) -> String {
self.as_str().to_string()
}
}
#[test]
fn test_pathmod_first_comp() {
let comp = Path::new("/etc/test").first_component().unwrap();
assert_eq!(comp, PathBuf::from("/"));
}
#[test]
fn test_pathmod_last_comp() {
let comp = Path::new("/etc/test").last_component().unwrap();
assert_eq!(comp, PathBuf::from("test"));
}
#[test]
fn test_pathmod_as_str() {
let string = Path::new("/var/log/test").as_str();
assert_eq!(string, "/var/log/test");
}
#[test]
fn test_pathmod_as_string() {
let string = Path::new("/var/log/test").as_string();
assert_eq!(string, "/var/log/test".to_string());
}
#[test]
fn test_pathmod_is_dot_success() {
let path = Path::new("/dir/test/.test");
assert_eq!(path.is_dot(), true);
}
#[test]
#[should_panic]
fn test_pathmod_is_dot_fail() {
let false_path = Path::new("/");
assert_eq!(false_path.is_dot(), true);
}