mk_lib/
file.rs

1use std::ffi::OsStr;
2use std::path::Path;
3
4/// This has been adapted from cross-rs file.rs source
5/// https://github.com/cross-rs/cross/blob/4090beca3cfffa44371a5bba524de3a578aa46c3/src/file.rs#L12
6pub trait ToUtf8 {
7  fn to_utf8(&self) -> anyhow::Result<&str>;
8}
9
10/// Implement `ToUtf8` for `OsStr`
11impl ToUtf8 for OsStr {
12  /// Convert `OsStr` to `&str`
13  /// This function will return an error if the conversion fails
14  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
21/// Implement `ToUtf8` for `Path`
22impl ToUtf8 for Path {
23  /// Convert `Path` to `&str`
24  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}