1use std::ffi::OsStr;
2use std::path::Path;
3
4pub trait ToUtf8 {
7 fn to_utf8(&self) -> anyhow::Result<&str>;
8}
9
10impl ToUtf8 for OsStr {
12 fn to_utf8(&self) -> anyhow::Result<&str> {
15 self
16 .to_str()
17 .ok_or_else(|| anyhow::anyhow!("Unable to convert `{self:?}` to UTF-8 string"))
18 }
19}
20
21impl ToUtf8 for Path {
23 fn to_utf8(&self) -> anyhow::Result<&str> {
25 self.as_os_str().to_utf8()
26 }
27}
28
29#[cfg(test)]
30mod tests {
31 use super::*;
32
33 #[test]
34 fn test_os_str_to_utf8() -> anyhow::Result<()> {
35 let os_str = OsStr::new("hello");
36 assert_eq!(os_str.to_utf8()?, "hello");
37 Ok(())
38 }
39
40 #[test]
41 fn test_path_to_utf8() -> anyhow::Result<()> {
42 let path = Path::new("hello");
43 assert_eq!(path.to_utf8()?, "hello");
44 Ok(())
45 }
46}