Skip to main content

mk_lib/
file.rs

1use std::borrow::Cow;
2use std::ffi::OsStr;
3use std::path::Path;
4
5/// This has been adapted from cross-rs file.rs source
6/// https://github.com/cross-rs/cross/blob/4090beca3cfffa44371a5bba524de3a578aa46c3/src/file.rs#L12
7pub trait ToUtf8 {
8  fn to_utf8(&self) -> anyhow::Result<&str>;
9}
10
11pub trait DisplayPath {
12  fn display_lossy(&self) -> Cow<'_, str>;
13}
14
15/// Implement `ToUtf8` for `OsStr`
16impl ToUtf8 for OsStr {
17  /// Convert `OsStr` to `&str`
18  /// This function will return an error if the conversion fails
19  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
32/// Implement `ToUtf8` for `Path`
33impl ToUtf8 for Path {
34  /// Convert `Path` to `&str`
35  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}