use anyhow::{Result, anyhow};
use std::path::{Path, PathBuf};
pub trait PathExt {
fn to_str_anyhow(&self) -> Result<&str>;
}
impl PathExt for Path {
fn to_str_anyhow(&self) -> Result<&str> {
self.to_str()
.ok_or_else(|| anyhow!("Invalid file path: path contains invalid UTF-8"))
}
}
impl PathExt for PathBuf {
fn to_str_anyhow(&self) -> Result<&str> {
self.to_str()
.ok_or_else(|| anyhow!("Invalid file path: path contains invalid UTF-8"))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_path_to_str_anyhow_valid() {
let path = Path::new("/some/valid/path");
assert_eq!(path.to_str_anyhow().unwrap(), "/some/valid/path");
}
#[test]
fn test_pathbuf_to_str_anyhow_valid() {
let path = PathBuf::from("/some/valid/path");
assert_eq!(path.to_str_anyhow().unwrap(), "/some/valid/path");
}
#[test]
fn test_path_with_spaces() {
let path = Path::new("/path/with spaces/file.txt");
assert_eq!(path.to_str_anyhow().unwrap(), "/path/with spaces/file.txt");
}
}