teamy_windows/string/
easy_pcwstr.rs

1use crate::string::pcwstr_guard::PCWSTRGuard;
2use eyre::eyre;
3use std::convert::Infallible;
4use std::ffi::OsStr;
5use std::ffi::OsString;
6use std::path::Path;
7use std::path::PathBuf;
8use widestring::U16CString;
9
10/// Conversion to `PCWSTRGuard` from various string types for easy FFI usage.
11pub trait EasyPCWSTR {
12    type Error;
13    fn easy_pcwstr(self) -> eyre::Result<PCWSTRGuard, Self::Error>;
14}
15
16impl EasyPCWSTR for U16CString {
17    type Error = Infallible;
18
19    fn easy_pcwstr(self) -> eyre::Result<PCWSTRGuard, Self::Error> {
20        Ok(PCWSTRGuard::new(self))
21    }
22}
23
24impl EasyPCWSTR for &str {
25    type Error = eyre::Error;
26
27    fn easy_pcwstr(self) -> eyre::Result<PCWSTRGuard, Self::Error> {
28        Ok(PCWSTRGuard::new(U16CString::from_str(self).map_err(
29            |_| eyre!("Failed to convert `&str` to U16CString: {}", self),
30        )?))
31    }
32}
33
34impl EasyPCWSTR for &OsString {
35    type Error = eyre::Error;
36
37    fn easy_pcwstr(self) -> eyre::Result<PCWSTRGuard, Self::Error> {
38        Ok(PCWSTRGuard::new(U16CString::from_os_str_truncate(self)))
39    }
40}
41impl EasyPCWSTR for &OsStr {
42    type Error = eyre::Error;
43
44    fn easy_pcwstr(self) -> eyre::Result<PCWSTRGuard, Self::Error> {
45        Ok(PCWSTRGuard::new(U16CString::from_os_str_truncate(self)))
46    }
47}
48
49impl EasyPCWSTR for &PathBuf {
50    type Error = eyre::Error;
51
52    fn easy_pcwstr(self) -> eyre::Result<PCWSTRGuard, Self::Error> {
53        Ok(PCWSTRGuard::new(U16CString::from_os_str_truncate(
54            self.as_os_str(),
55        )))
56    }
57}
58
59impl EasyPCWSTR for &Path {
60    type Error = eyre::Error;
61
62    fn easy_pcwstr(self) -> eyre::Result<PCWSTRGuard, Self::Error> {
63        Ok(PCWSTRGuard::new(U16CString::from_os_str_truncate(
64            self.as_os_str(),
65        )))
66    }
67}
68
69#[cfg(test)]
70mod test {
71    use super::EasyPCWSTR;
72    use std::ffi::OsString;
73    use std::path::Path;
74    use std::path::PathBuf;
75    use widestring::U16CString;
76
77    #[test]
78    fn it_works() -> eyre::Result<()> {
79        "Hello, World!".easy_pcwstr()?;
80        OsString::from("asd").easy_pcwstr()?;
81        "asd".to_string().easy_pcwstr()?;
82        PathBuf::from("asd").easy_pcwstr()?;
83        Path::new("asd").easy_pcwstr()?;
84        U16CString::from_str("asd")?.easy_pcwstr()?;
85        Ok(())
86    }
87}