1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
use std::{fmt::Display, marker::PhantomData, mem, ptr};

use windows::{
    core::{PCWSTR, PWSTR},
    Win32::{Globalization::lstrlenW, System::Com},
};

/// RAII holder for a [`PWSTR`] which is allocated with [`Com::CoTaskMemAlloc`] and freed
/// with [`Com::CoTaskMemFree`] when dropped.
pub struct CoTaskMemPWSTR<'a>(PWSTR, PhantomData<&'a PWSTR>);

/// Constant guard object tied to the lifetime of the [`CoTaskMemPWSTR`] so that it
/// is safe to dereference the [`PCWSTR`] as long as both are still in scope.
pub struct CoTaskMemRef<'a>(PCWSTR, PhantomData<&'a PCWSTR>);

impl<'a> CoTaskMemRef<'a> {
    pub fn as_pcwstr(&self) -> &PCWSTR {
        &self.0
    }
}

impl<'a> From<&'a CoTaskMemPWSTR<'a>> for CoTaskMemRef<'a> {
    fn from(value: &'a CoTaskMemPWSTR<'a>) -> Self {
        Self(PCWSTR::from_raw(value.0.as_ptr()), PhantomData)
    }
}

/// Mutable guard object tied to the lifetime of the [`CoTaskMemPWSTR`] so that it
/// is safe to dereference the [`PWSTR`] as long as both are still in scope.
pub struct CoTaskMemMut<'a>(&'a PWSTR);

impl<'a> CoTaskMemMut<'a> {
    pub fn as_pwstr(&mut self) -> &'a PWSTR {
        self.0
    }
}

impl<'a> From<&'a mut CoTaskMemPWSTR<'a>> for CoTaskMemMut<'a> {
    fn from(value: &'a mut CoTaskMemPWSTR<'a>) -> Self {
        Self(&value.0)
    }
}

impl<'a> CoTaskMemPWSTR<'a> {
    /// Get a mutable [`PWSTR`] guard which borrows the pointer.
    pub fn as_mut(&'a mut self) -> CoTaskMemMut<'a> {
        From::from(self)
    }

    /// Get a constant [`PCWSTR`] guard which borrows the pointer.
    pub fn as_ref(&'a self) -> CoTaskMemRef<'a> {
        From::from(self)
    }

    /// Take the [`PWSTR`] pointer and hand off ownership so that it is not freed when the `CoTaskMemPWSTR` is dropped.
    pub fn take(&mut self) -> PWSTR {
        let result = self.0;
        self.0 = PWSTR::null();
        result
    }
}

impl<'a> Drop for CoTaskMemPWSTR<'a> {
    fn drop(&mut self) {
        if !self.0.is_null() {
            unsafe {
                Com::CoTaskMemFree(Some(mem::transmute(self.0.as_ptr())));
            }
        }
    }
}

impl<'a> Default for CoTaskMemPWSTR<'a> {
    fn default() -> Self {
        Self(PWSTR::null(), PhantomData)
    }
}

impl<'a> From<PWSTR> for CoTaskMemPWSTR<'a> {
    fn from(value: PWSTR) -> Self {
        Self(value, PhantomData)
    }
}

impl<'a> From<&str> for CoTaskMemPWSTR<'a> {
    fn from(value: &str) -> Self {
        match value {
            "" => Default::default(),
            value => {
                let encoded: Vec<_> = value.encode_utf16().chain(std::iter::once(0)).collect();

                unsafe {
                    let mut buffer =
                        Com::CoTaskMemAlloc(encoded.len() * mem::size_of::<u16>()) as *mut u16;
                    let result = PWSTR::from_raw(buffer);

                    for char in encoded {
                        *buffer = char;
                        buffer = buffer.add(1);
                    }

                    Self(result, PhantomData)
                }
            }
        }
    }
}

impl<'a> Display for CoTaskMemPWSTR<'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let value = string_from_pcwstr(self.as_ref().as_pcwstr());
        f.write_str(value.as_str())
    }
}

/// Copy a [`PCWSTR`] from an input param to a [`String`].
pub fn string_from_pcwstr(source: &PCWSTR) -> String {
    if source.0.is_null() {
        String::new()
    } else {
        let len = unsafe { lstrlenW(*source) };

        if len > 0 {
            unsafe {
                let buffer = ptr::slice_from_raw_parts(source.0, len as usize);
                String::from_utf16_lossy(&*buffer)
            }
        } else {
            String::new()
        }
    }
}

/// Copy a [`PWSTR`] allocated with [`Com::CoTaskMemAlloc`] from an input param to a [`String`]
/// and free the original buffer with [`Com::CoTaskMemFree`].
pub fn take_pwstr(source: PWSTR) -> String {
    CoTaskMemPWSTR::from(source).to_string()
}

/// Allocate a [`PWSTR`] with [`Com::CoTaskMemAlloc`] and copy a [`&str`] into it.
pub fn pwstr_from_str(source: &str) -> PWSTR {
    CoTaskMemPWSTR::from(source).take()
}