1use std::borrow::Cow;
2use std::ffi::OsStr;
3use std::path::Path;
4
5pub trait ToUtf8 {
8 fn to_utf8(&self) -> anyhow::Result<&str>;
9}
10
11pub trait DisplayPath {
12 fn display_lossy(&self) -> Cow<'_, str>;
13}
14
15impl ToUtf8 for OsStr {
17 fn to_utf8(&self) -> anyhow::Result<&str> {
20 self
21 .to_str()
22 .ok_or_else(|| anyhow::anyhow!("Unable to convert `{self:?}` to UTF-8 string"))
23 }
24}
25
26impl DisplayPath for OsStr {
27 fn display_lossy(&self) -> Cow<'_, str> {
28 self.to_string_lossy()
29 }
30}
31
32impl ToUtf8 for Path {
34 fn to_utf8(&self) -> anyhow::Result<&str> {
36 self.as_os_str().to_utf8()
37 }
38}
39
40impl DisplayPath for Path {
41 fn display_lossy(&self) -> Cow<'_, str> {
42 self.as_os_str().display_lossy()
43 }
44}
45
46#[cfg(test)]
47mod tests {
48 use super::*;
49
50 #[test]
51 fn test_os_str_to_utf8() -> anyhow::Result<()> {
52 let os_str = OsStr::new("hello");
53 assert_eq!(os_str.to_utf8()?, "hello");
54 Ok(())
55 }
56
57 #[test]
58 fn test_path_to_utf8() -> anyhow::Result<()> {
59 let path = Path::new("hello");
60 assert_eq!(path.to_utf8()?, "hello");
61 Ok(())
62 }
63
64 #[test]
65 fn test_path_display_lossy() {
66 let path = Path::new("hello");
67 assert_eq!(path.display_lossy(), "hello");
68 }
69}