teamy_windows/string/
pcwstr_guard.rs

1use std::ops::Deref;
2use widestring::U16CString;
3use windows::core::PCWSTR;
4use windows::core::Param;
5
6/// Prevents `Self` from being dropped before the finish of a FFI call.
7pub struct PCWSTRGuard {
8    string: U16CString,
9}
10impl PCWSTRGuard {
11    pub fn new(string: U16CString) -> Self {
12        Self { string }
13    }
14
15    /// # Safety
16    ///
17    /// You must ensure that the `PCWSTRGuard` outlives any usage of the pointer.
18    pub unsafe fn as_ptr(&self) -> PCWSTR {
19        PCWSTR(self.string.as_ptr())
20    }
21
22    pub fn as_wide(&self) -> &[u16] {
23        self.string.as_slice()
24    }
25}
26impl Deref for PCWSTRGuard {
27    type Target = U16CString;
28
29    fn deref(&self) -> &Self::Target {
30        &self.string
31    }
32}
33
34/// MUST NOT implement this for `PCWSTRGuard` itself, only for `&PCWSTRGuard`,
35/// to ensure the data the PCWSTR points to is valid for the lifetime of the parameter.
36impl Param<PCWSTR> for &PCWSTRGuard {
37    unsafe fn param(self) -> windows::core::ParamValue<PCWSTR> {
38        windows::core::ParamValue::Borrowed(PCWSTR(self.string.as_ptr()))
39    }
40}
41
42/// Included for postfix `.as_ref()` convenience.
43impl AsRef<PCWSTRGuard> for PCWSTRGuard {
44    fn as_ref(&self) -> &PCWSTRGuard {
45        self
46    }
47}