utf8_path/
path_to_string.rs1use anyhow::{Context, Result};
6use std::path::{Path, PathBuf};
7
8pub trait PathToStringExt {
10 fn path_to_string(&self) -> Result<String>;
12}
13
14impl PathToStringExt for Path {
15 fn path_to_string(&self) -> Result<String> {
16 self.to_str()
17 .context(format!("Path is not valid UTF-8: {}", self.display()))
18 .map(str::to_string)
19 }
20}
21
22impl PathToStringExt for PathBuf {
23 fn path_to_string(&self) -> Result<String> {
24 self.to_str()
25 .context(format!("Path is not valid UTF-8: {}", self.display()))
26 .map(str::to_string)
27 }
28}
29
30#[cfg(test)]
31mod tests {
32 use super::PathToStringExt;
33 use std::ffi::OsString;
34 use std::os::unix::ffi::OsStringExt;
35 use std::path::PathBuf;
36
37 #[test]
38 fn path_to_string() {
39 let path = PathBuf::from("/some/path/to/file.txt");
40 let string = path.path_to_string().unwrap();
41 assert_eq!(string, "/some/path/to/file.txt".to_string());
42 }
43
44 #[test]
45 fn invalid_path_to_string() {
46 let invalid_path = PathBuf::from(OsString::from_vec(b"invalid\xe7".to_vec()));
47 assert!(invalid_path.path_to_string().is_err());
48 }
49}