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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
use std::ptr::null_mut;

use winapi::um::oleauto::{SysAllocStringLen, SysFreeString, SysStringLen};
use winapi::shared::wtypes::BSTR;
pub(crate) use widestring::U16String;

use super::errors::{BStringError, ElementError, FromVariantError, IntoSafeArrayError, IntoSafeArrElemError, IntoVariantError, SafeArrayError};
use super::ptr::Ptr;
use super::types::TryConvert;

/// This trait is implemented on `U16String` to enable the convenient and safe conversion of
/// It utilizes the Sys* functions to manage the allocated memory. 
/// Generally you will want to use [`allocate_managed_bstr`] because it provides a
/// type that will automatically free the BSTR when dropped. 
/// 
/// For FFI, you **cannot** use a straight up `*mut u16` when an interface calls for a 
/// BSTR. The reason being is that at the four bytes before where the BSTR pointer points to, 
/// there is a length prefix. In addition, the memory will be freed by the same allocator used in 
/// `SysAllocString`, which can cause UB if you didn't allocate the memory that way. **Any** other
/// allocation method will cause UB and crashes. 
/// 
/// ## Example
/// ```
/// extern crate oaidl;
/// extern crate widestring;
/// 
/// use oaidl::{BStringError, BStringExt};
/// use widestring::U16String;
/// 
/// fn main() -> Result<(), BStringError> {
///     let mut ustr = U16String::from_str("testing abc1267 ?Ťũřǐꝥꞔ");
///     // Automagically dropped once you leave scope. 
///     let bstr = ustr.allocate_managed_bstr()?;
/// 
///     //Unless you call .consume() on it
///     // bstr.consume(); <-- THIS WILL LEAK if you don't take care.
///     Ok(())
/// }
/// ```
/// 
/// [`allocate_managed_bstr`]: #tymethod.allocate_managed_bstr
/// [`DroppableBString`]: struct.DroppableBString.html
pub trait BStringExt {
    /// Allocates a [`Ptr<u16>`] (aka a `*mut u16` aka a BSTR)
    fn allocate_bstr(&mut self) -> Result<Ptr<u16>, BStringError>;

    /// Allocates a [`Ptr<u16>`] (aka a `*mut u16` aka a BSTR)
    /// 
    /// ### Memory handling
    /// 
    /// Consumes input. Input value will be dropped. 
    fn consume_to_bstr(self) -> Result<Ptr<u16>, BStringError>;

    /// Allocates a [`DroppableBString`] container - automatically frees the memory properly if dropped.
    fn allocate_managed_bstr(&mut self) -> Result<DroppableBString, BStringError>;

    /// Allocates a [`DroppableBString`] container - automatically frees the memory properly if dropped.
    /// 
    /// ### Memory handling
    /// 
    /// Consumes input. Input value will be dropped. 
    fn consume_to_managed_bstr(self) -> Result<DroppableBString, BStringError>;

    /// Manually and correctly free the memory allocated via Sys* methods
    fn deallocate_bstr(bstr: Ptr<u16>);
    
    /// Convenience method for conversion to a good intermediary type
    fn from_bstr(bstr: *mut u16) -> U16String;
    
    /// Convenience method for conversion to a good intermediary type
    
    fn from_pbstr(bstr: Ptr<u16>) -> U16String;
    
    /// Convenience method for conversion to a good intermediary type
    fn from_boxed_bstr(bstr: Box<u16>) -> U16String;
}

impl BStringExt for U16String {
    fn allocate_bstr(&mut self) -> Result<Ptr<u16>, BStringError> {
        let sz = self.len();
        let rw = self.as_ptr();
        let bstr: BSTR = unsafe {SysAllocStringLen(rw, sz as u32)};
        match Ptr::with_checked(bstr) {
            Some(pbstr) => Ok(pbstr), 
            None => Err(BStringError::AllocateFailed{len: sz})
        }
    }

    fn consume_to_bstr(self) -> Result<Ptr<u16>, BStringError> {
        let sz = self.len();
        let rw = self.as_ptr();
        let bstr: BSTR = unsafe {SysAllocStringLen(rw, sz as u32)};
        match Ptr::with_checked(bstr) {
            Some(pbstr) => Ok(pbstr), 
            None => Err(BStringError::AllocateFailed{len: sz})
        }
    }

    fn allocate_managed_bstr(&mut self) -> Result<DroppableBString, BStringError> {
        Ok(DroppableBString{ inner: Some(self.allocate_bstr()?) })
    }

    fn consume_to_managed_bstr(self) -> Result<DroppableBString, BStringError> {
        Ok(DroppableBString{ inner: Some(self.consume_to_bstr()?) })
    }

    fn deallocate_bstr(bstr: Ptr<u16>) {
        let bstr: BSTR = bstr.as_ptr();
        unsafe { SysFreeString(bstr) }
    }

    fn from_bstr(bstr: *mut u16) -> U16String {
        assert!(!bstr.is_null());
        let sz = unsafe {SysStringLen(bstr)};
        unsafe {U16String::from_ptr(bstr, sz as usize)}
    }

    fn from_pbstr(bstr: Ptr<u16>) -> U16String {
        U16String::from_bstr(bstr.as_ptr())
    }

    fn from_boxed_bstr(bstr: Box<u16>) -> U16String {
        U16String::from_bstr(Box::into_raw(bstr))
    }
}

/// Struct that holds pointer to Sys* allocated memory. 
/// It will automatically free the memory via the Sys* 
/// functions unless it has been consumed. 
/// 
/// ## Safety
/// 
/// This wraps up a pointer to Sys* allocated memory and 
/// will automatically clean up that memory correctly
/// unless the memory has been leaked by `consume()`.
/// 
/// One would use the `.consume()` method when sending the 
/// pointer through FFI.
/// 
/// If you don't manually free the memory yourself (correctly)
/// or send it to an FFI function that will do so, then it 
/// *will* be leaked memory. 
/// 
/// If you have a memory leak and you're using this type, 
/// then check your use of consume. 
/// 
/// ## Example
/// 
/// ```
/// extern crate oaidl;
/// extern crate widestring;
/// 
/// use oaidl::{BStringError, BStringExt, DroppableBString};
/// use widestring::U16String;
/// 
/// fn main() -> Result<(), BStringError> {
///     let s = U16String::from_str("The first step to doing anything is to believe you can do it. See it finished in your mind before you ever start. It takes dark in order to show light.");
///     let dbs = s.consume_to_managed_bstr()?;
///     drop(dbs); // Correctly deallocates allocated memory.
///     Ok(())
/// }
/// ```
#[derive( Debug, Eq, Hash, PartialEq, PartialOrd)]
pub struct DroppableBString {
    inner: Option<Ptr<u16>>
}

impl DroppableBString {
    /// `consume()` -> `*mut u16` returns the contained data
    /// while also setting a flag that the data has been
    /// consumed. It is your responsibility to manage the 
    /// memory yourself. Most uses of BSTR in FFI will
    /// free the memory for you. 
    /// 
    /// This method is very unsafe to use unless you know
    /// how to handle it correctly, hence the `unsafe` marker. 
    pub unsafe fn consume(&mut self) -> *mut u16 {
        let ret = match self.inner {
            Some(ptr) => ptr.as_ptr(), 
            None => null_mut()
        };
        self.inner = None;
        ret
    }
}

impl Drop for DroppableBString {
    /// Handles freeing the allocated BSTR correctly via `SysFreeString`. 
    /// The only (safe) way to construct a [`DroppableBString`] is via 
    /// an [`allocate_managed_bstr`] call. 
    fn drop(&mut self) {
        match self.inner {
            Some(ptr) => {
                unsafe { SysFreeString(ptr.as_ptr())}
            }, 
            None => {}
        }
    }
}

impl TryConvert<U16String, IntoVariantError> for BSTR {
    /// Clones input, then allocates a new BSTR. 
    /// 
    /// ### Errors
    /// 
    /// Allocation can throw [`BStringError`]. 
    fn try_convert(u: U16String) -> Result<Self, IntoVariantError> {
        Ok(u.clone().allocate_bstr()?.as_ptr())
    }
}

impl TryConvert<BSTR, FromVariantError> for U16String {
    /// Converts the BSTR to a U16String.
    /// 
    /// ### Panics
    /// 
    /// Will panic if BSTR is null. 
    fn try_convert(p: BSTR) -> Result<Self, FromVariantError> {
        assert!(!p.is_null(), "BSTR ptr was null.");
        Ok(U16String::from_bstr(p))
    }
}

impl TryConvert<U16String, SafeArrayError> for BSTR {
    /// Clones input, then allocates a new BSTR. 
    /// 
    /// ### Errors
    /// 
    /// Allocation can throw [`SafeArrayError`].
    fn try_convert(u: U16String) -> Result<Self, SafeArrayError> {
        match u.clone().allocate_bstr() {
            Ok(ptr) => Ok(ptr.as_ptr()), 
            Err(bse) => Err(SafeArrayError::from(IntoSafeArrayError::from_element_err(IntoSafeArrElemError::from(bse), 0)))
        }
    }
}

impl TryConvert<U16String, ElementError> for BSTR {
    /// Clones input, then allocates a new BSTR. 
    /// 
    /// ### Errors
    /// 
    /// Allocation can throw [`ElementError`].
    fn try_convert(u: U16String) -> Result<Self,ElementError> {
         match u.clone().allocate_bstr() {
            Ok(ptr) => Ok(ptr.as_ptr()), 
            Err(bse) => Err(ElementError::from(IntoSafeArrElemError::from(bse)))
        }
    } 
}

impl TryConvert<BSTR, ElementError> for U16String {
    /// Converts the BSTR to a U16String.
    /// 
    /// ### Panics
    /// 
    /// Will panic if BSTR is null. 
    fn try_convert(ptr: BSTR) -> Result<Self, ElementError> {
        assert!(!ptr.is_null(), "BSTR ptr was null.");
        Ok(U16String::from_bstr(ptr))
    }
}